@amplitude/element-selector 0.1.0 → 0.1.1-featelement-selector-v1.0

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.
@@ -0,0 +1,230 @@
1
+ "use strict";
2
+ /**
3
+ * Canonical legacy CSS-path walker.
4
+ *
5
+ * This is the Chromium-DevTools-derived `cssPath` algorithm that was the only
6
+ * selector source autocapture used before the strategy engine existed. It still
7
+ * matters in two situations:
8
+ *
9
+ * 1. The kill switch: when `ResolvedSelectorConfig.enabled === false`, the
10
+ * engine routes here so a customer who flips the engine off mid-session
11
+ * keeps emitting the same selectors their downstream zones and cohorts
12
+ * were built against.
13
+ * 2. The safety net: when the strategy chain or its internal walker throws
14
+ * anything unexpected, the engine catches and falls back here. The
15
+ * autocapture click handler must always produce *some* selector — a
16
+ * runtime exception in selector generation is a worse outcome than a
17
+ * slightly less stable selector.
18
+ *
19
+ * Until this file existed, the algorithm was duplicated in two places kept
20
+ * "in sync by comment":
21
+ *
22
+ * - `packages/plugin-autocapture-browser/src/libs/element-path.ts`
23
+ * - `javascript/packages/session-replay-ui/src/utils/element-path.ts`
24
+ *
25
+ * Both will eventually re-export from here so divergence becomes impossible.
26
+ *
27
+ * Behavior is byte-identical to those two copies — selectors emitted by this
28
+ * function for a given element MUST match what the SDK has been emitting in
29
+ * production. Do not "fix" the selector format without an explicit version
30
+ * bump and a coordinated dashboard rollout.
31
+ *
32
+ * **Why this lives in the package, not as an optional consumer concern:**
33
+ *
34
+ * Every consumer that uses `engine.generate(el)` benefits from the kill
35
+ * switch and the safety net automatically. Without this, each new consumer
36
+ * (Chrome extension visual tagger, future tagging surfaces) has to
37
+ * reimplement the same router and the same legacy walker. We learned that
38
+ * the hard way — by writing the same `if (config.enabled && engine) ...
39
+ * else cssPath()` block in two repositories with two copies of cssPath.
40
+ *
41
+ * Code is adapted from The Chromium Authors.
42
+ * Source: https://github.com/ChromeDevTools/devtools-frontend/blob/main/front_end/panels/elements/DOMPath.ts#L14
43
+ * License: BSD-style license
44
+ *
45
+ * Copyright 2014 The Chromium Authors
46
+ *
47
+ * Redistribution and use in source and binary forms, with or without
48
+ * modification, are permitted provided that the following conditions are
49
+ * met:
50
+ *
51
+ * * Redistributions of source code must retain the above copyright
52
+ * notice, this list of conditions and the following disclaimer.
53
+ * * Redistributions in binary form must reproduce the above
54
+ * copyright notice, this list of conditions and the following
55
+ * disclaimer in the documentation and/or other materials provided
56
+ * with the distribution.
57
+ * * Neither the name of Google Inc. nor the names of its
58
+ * contributors may be used to endorse or promote products derived
59
+ * from this software without specific prior written permission.
60
+ *
61
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
62
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
63
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
64
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
65
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
66
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
67
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
68
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
69
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
70
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
71
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
72
+ */
73
+ Object.defineProperty(exports, "__esModule", { value: true });
74
+ exports.legacyCssPath = void 0;
75
+ var tslib_1 = require("tslib");
76
+ /* istanbul ignore file -- the algorithm is locked-down behavior inherited from
77
+ Chromium and validated by the SDK's own end-to-end suite. Re-running line
78
+ coverage here only obscures the parts of the package that *do* have
79
+ meaningful coverage. */
80
+ var escape_css_identifier_1 = require("./helpers/escape-css-identifier");
81
+ var Step = /** @class */ (function () {
82
+ function Step(value, optimized) {
83
+ this.value = value;
84
+ this.optimized = optimized;
85
+ }
86
+ Step.prototype.toString = function () {
87
+ return this.value;
88
+ };
89
+ return Step;
90
+ }());
91
+ /**
92
+ * Produce a CSS selector string for `node` using the legacy positional walker.
93
+ *
94
+ * Returns the empty string for non-element nodes — same shape every existing
95
+ * caller depends on. Never throws for well-formed Element inputs.
96
+ *
97
+ * @param node Element to identify.
98
+ * @param optimized When `true`, short-circuits at the nearest unique-ish step
99
+ * (id or `<body>` / `<head>` / `<html>`). Default `false`,
100
+ * which matches what autocapture has always passed.
101
+ */
102
+ var legacyCssPath = function (node, optimized) {
103
+ // `node` is already an Element; this check is defensive.
104
+ if (node.nodeType !== Node.ELEMENT_NODE) {
105
+ return '';
106
+ }
107
+ var steps = [];
108
+ var contextNode = node;
109
+ while (contextNode) {
110
+ var step = cssPathStep(contextNode, Boolean(optimized), contextNode === node);
111
+ if (!step) {
112
+ break;
113
+ }
114
+ steps.push(step);
115
+ if (step.optimized) {
116
+ break;
117
+ }
118
+ contextNode = contextNode.parentElement;
119
+ }
120
+ steps.reverse();
121
+ return steps.join(' > ');
122
+ };
123
+ exports.legacyCssPath = legacyCssPath;
124
+ var cssPathStep = function (node, optimized, isTargetNode) {
125
+ var e_1, _a;
126
+ if (node.nodeType !== Node.ELEMENT_NODE) {
127
+ return null;
128
+ }
129
+ var id = node.getAttribute('id');
130
+ if (optimized) {
131
+ if (id) {
132
+ return new Step(idSelector(id), true);
133
+ }
134
+ var nodeNameLower = node.tagName.toLowerCase();
135
+ if (nodeNameLower === 'body' || nodeNameLower === 'head' || nodeNameLower === 'html') {
136
+ return new Step(nodeNameLower, true);
137
+ }
138
+ }
139
+ var nodeName = node.tagName.toLowerCase();
140
+ if (id) {
141
+ return new Step(nodeName + idSelector(id), true);
142
+ }
143
+ var parent = node.parentNode;
144
+ if (!parent || parent.nodeType === Node.DOCUMENT_NODE) {
145
+ return new Step(nodeName, true);
146
+ }
147
+ var prefixedOwnClassNamesArray = prefixedElementClassNames(node);
148
+ var needsClassNames = false;
149
+ var needsNthChild = false;
150
+ var ownIndex = -1;
151
+ var elementIndex = -1;
152
+ var siblings = parent.children;
153
+ for (var i = 0; siblings && (ownIndex === -1 || !needsNthChild) && i < siblings.length; ++i) {
154
+ var sibling = siblings[i];
155
+ if (sibling.nodeType !== Node.ELEMENT_NODE) {
156
+ continue;
157
+ }
158
+ elementIndex += 1;
159
+ if (sibling === node) {
160
+ ownIndex = elementIndex;
161
+ continue;
162
+ }
163
+ if (needsNthChild) {
164
+ continue;
165
+ }
166
+ if (sibling.tagName.toLowerCase() !== nodeName) {
167
+ continue;
168
+ }
169
+ needsClassNames = true;
170
+ var ownClassNames = new Set(prefixedOwnClassNamesArray);
171
+ if (!ownClassNames.size) {
172
+ needsNthChild = true;
173
+ continue;
174
+ }
175
+ var siblingClassNamesArray = prefixedElementClassNames(sibling);
176
+ for (var j = 0; j < siblingClassNamesArray.length; ++j) {
177
+ var siblingClass = siblingClassNamesArray[j];
178
+ if (!ownClassNames.has(siblingClass)) {
179
+ continue;
180
+ }
181
+ ownClassNames.delete(siblingClass);
182
+ if (!ownClassNames.size) {
183
+ needsNthChild = true;
184
+ break;
185
+ }
186
+ }
187
+ }
188
+ var result = nodeName;
189
+ if (isTargetNode &&
190
+ nodeName.toLowerCase() === 'input' &&
191
+ node.getAttribute('type') &&
192
+ !node.getAttribute('id') &&
193
+ !node.getAttribute('class')) {
194
+ result += '[type=' + (0, escape_css_identifier_1.escapeCssIdentifier)(node.getAttribute('type') || '') + ']';
195
+ }
196
+ if (needsNthChild) {
197
+ result += ':nth-child(' + String(ownIndex + 1) + ')';
198
+ }
199
+ else if (needsClassNames) {
200
+ try {
201
+ for (var prefixedOwnClassNamesArray_1 = tslib_1.__values(prefixedOwnClassNamesArray), prefixedOwnClassNamesArray_1_1 = prefixedOwnClassNamesArray_1.next(); !prefixedOwnClassNamesArray_1_1.done; prefixedOwnClassNamesArray_1_1 = prefixedOwnClassNamesArray_1.next()) {
202
+ var prefixedName = prefixedOwnClassNamesArray_1_1.value;
203
+ result += '.' + (0, escape_css_identifier_1.escapeCssIdentifier)(prefixedName.slice(1));
204
+ }
205
+ }
206
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
207
+ finally {
208
+ try {
209
+ if (prefixedOwnClassNamesArray_1_1 && !prefixedOwnClassNamesArray_1_1.done && (_a = prefixedOwnClassNamesArray_1.return)) _a.call(prefixedOwnClassNamesArray_1);
210
+ }
211
+ finally { if (e_1) throw e_1.error; }
212
+ }
213
+ }
214
+ return new Step(result, false);
215
+ };
216
+ var prefixedElementClassNames = function (el) {
217
+ var classAttribute = el.getAttribute('class');
218
+ if (!classAttribute) {
219
+ return [];
220
+ }
221
+ return classAttribute
222
+ .split(/\s+/g)
223
+ .filter(Boolean)
224
+ .map(function (name) {
225
+ // The prefix is required to store "__proto__" in a object-based map.
226
+ return '$' + name;
227
+ });
228
+ };
229
+ var idSelector = function (id) { return '#' + (0, escape_css_identifier_1.escapeCssIdentifier)(id); };
230
+ //# sourceMappingURL=legacy-css-path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"legacy-css-path.js","sourceRoot":"","sources":["../../src/legacy-css-path.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsEG;;;;AAEH;;;0BAG0B;AAE1B,yEAAsE;AAEtE;IACE,cAAmB,KAAa,EAAS,SAAkB;QAAxC,UAAK,GAAL,KAAK,CAAQ;QAAS,cAAS,GAAT,SAAS,CAAS;IAAG,CAAC;IAC/D,uBAAQ,GAAR;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IACH,WAAC;AAAD,CAAC,AALD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AM,YAAY,uCAAA;gBACrB,MAAM,IAAI,GAAG,GAAG,IAAA,2CAAmB,EAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;aAC5D;;;;;;;;;KACF;IAED,OAAO,IAAI,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AACjC,CAAC,CAAC;AAEF,IAAM,yBAAyB,GAAG,UAAC,EAAW;IAC5C,IAAM,cAAc,GAAG,EAAE,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IAChD,IAAI,CAAC,cAAc,EAAE;QACnB,OAAO,EAAE,CAAC;KACX;IACD,OAAO,cAAc;SAClB,KAAK,CAAC,MAAM,CAAC;SACb,MAAM,CAAC,OAAO,CAAC;SACf,GAAG,CAAC,UAAC,IAAI;QACR,qEAAqE;QACrE,OAAO,GAAG,GAAG,IAAI,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC,CAAC;AAEF,IAAM,UAAU,GAAG,UAAC,EAAU,IAAa,OAAA,GAAG,GAAG,IAAA,2CAAmB,EAAC,EAAE,CAAC,EAA7B,CAA6B,CAAC","sourcesContent":["/**\n * Canonical legacy CSS-path walker.\n *\n * This is the Chromium-DevTools-derived `cssPath` algorithm that was the only\n * selector source autocapture used before the strategy engine existed. It still\n * matters in two situations:\n *\n * 1. The kill switch: when `ResolvedSelectorConfig.enabled === false`, the\n * engine routes here so a customer who flips the engine off mid-session\n * keeps emitting the same selectors their downstream zones and cohorts\n * were built against.\n * 2. The safety net: when the strategy chain or its internal walker throws\n * anything unexpected, the engine catches and falls back here. The\n * autocapture click handler must always produce *some* selector — a\n * runtime exception in selector generation is a worse outcome than a\n * slightly less stable selector.\n *\n * Until this file existed, the algorithm was duplicated in two places kept\n * \"in sync by comment\":\n *\n * - `packages/plugin-autocapture-browser/src/libs/element-path.ts`\n * - `javascript/packages/session-replay-ui/src/utils/element-path.ts`\n *\n * Both will eventually re-export from here so divergence becomes impossible.\n *\n * Behavior is byte-identical to those two copies — selectors emitted by this\n * function for a given element MUST match what the SDK has been emitting in\n * production. Do not \"fix\" the selector format without an explicit version\n * bump and a coordinated dashboard rollout.\n *\n * **Why this lives in the package, not as an optional consumer concern:**\n *\n * Every consumer that uses `engine.generate(el)` benefits from the kill\n * switch and the safety net automatically. Without this, each new consumer\n * (Chrome extension visual tagger, future tagging surfaces) has to\n * reimplement the same router and the same legacy walker. We learned that\n * the hard way — by writing the same `if (config.enabled && engine) ...\n * else cssPath()` block in two repositories with two copies of cssPath.\n *\n * Code is adapted from The Chromium Authors.\n * Source: https://github.com/ChromeDevTools/devtools-frontend/blob/main/front_end/panels/elements/DOMPath.ts#L14\n * License: BSD-style license\n *\n * Copyright 2014 The Chromium Authors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/* istanbul ignore file -- the algorithm is locked-down behavior inherited from\n Chromium and validated by the SDK's own end-to-end suite. Re-running line\n coverage here only obscures the parts of the package that *do* have\n meaningful coverage. */\n\nimport { escapeCssIdentifier } from './helpers/escape-css-identifier';\n\nclass Step {\n constructor(public value: string, public optimized: boolean) {}\n toString(): string {\n return this.value;\n }\n}\n\n/**\n * Produce a CSS selector string for `node` using the legacy positional walker.\n *\n * Returns the empty string for non-element nodes — same shape every existing\n * caller depends on. Never throws for well-formed Element inputs.\n *\n * @param node Element to identify.\n * @param optimized When `true`, short-circuits at the nearest unique-ish step\n * (id or `<body>` / `<head>` / `<html>`). Default `false`,\n * which matches what autocapture has always passed.\n */\nexport const legacyCssPath = (node: Element, optimized?: boolean): string => {\n // `node` is already an Element; this check is defensive.\n if (node.nodeType !== Node.ELEMENT_NODE) {\n return '';\n }\n\n const steps: Step[] = [];\n let contextNode: Element | null = node;\n\n while (contextNode) {\n const step = cssPathStep(contextNode, Boolean(optimized), contextNode === node);\n if (!step) {\n break;\n }\n steps.push(step);\n if (step.optimized) {\n break;\n }\n contextNode = contextNode.parentElement;\n }\n\n steps.reverse();\n return steps.join(' > ');\n};\n\nconst cssPathStep = (node: Element, optimized: boolean, isTargetNode: boolean): Step | null => {\n if (node.nodeType !== Node.ELEMENT_NODE) {\n return null;\n }\n\n const id = node.getAttribute('id');\n if (optimized) {\n if (id) {\n return new Step(idSelector(id), true);\n }\n\n const nodeNameLower = node.tagName.toLowerCase();\n if (nodeNameLower === 'body' || nodeNameLower === 'head' || nodeNameLower === 'html') {\n return new Step(nodeNameLower, true);\n }\n }\n\n const nodeName = node.tagName.toLowerCase();\n\n if (id) {\n return new Step(nodeName + idSelector(id), true);\n }\n\n const parent = node.parentNode;\n if (!parent || parent.nodeType === Node.DOCUMENT_NODE) {\n return new Step(nodeName, true);\n }\n\n const prefixedOwnClassNamesArray = prefixedElementClassNames(node);\n let needsClassNames = false;\n let needsNthChild = false;\n let ownIndex = -1;\n let elementIndex = -1;\n\n const siblings: HTMLCollectionOf<Element> = (parent as Element | Document).children;\n\n for (let i = 0; siblings && (ownIndex === -1 || !needsNthChild) && i < siblings.length; ++i) {\n const sibling = siblings[i];\n if (sibling.nodeType !== Node.ELEMENT_NODE) {\n continue;\n }\n\n elementIndex += 1;\n if (sibling === node) {\n ownIndex = elementIndex;\n continue;\n }\n if (needsNthChild) {\n continue;\n }\n\n if (sibling.tagName.toLowerCase() !== nodeName) {\n continue;\n }\n\n needsClassNames = true;\n const ownClassNames = new Set<string>(prefixedOwnClassNamesArray);\n if (!ownClassNames.size) {\n needsNthChild = true;\n continue;\n }\n\n const siblingClassNamesArray = prefixedElementClassNames(sibling);\n for (let j = 0; j < siblingClassNamesArray.length; ++j) {\n const siblingClass = siblingClassNamesArray[j];\n if (!ownClassNames.has(siblingClass)) {\n continue;\n }\n ownClassNames.delete(siblingClass);\n if (!ownClassNames.size) {\n needsNthChild = true;\n break;\n }\n }\n }\n\n let result = nodeName;\n if (\n isTargetNode &&\n nodeName.toLowerCase() === 'input' &&\n node.getAttribute('type') &&\n !node.getAttribute('id') &&\n !node.getAttribute('class')\n ) {\n result += '[type=' + escapeCssIdentifier(node.getAttribute('type') || '') + ']';\n }\n if (needsNthChild) {\n result += ':nth-child(' + String(ownIndex + 1) + ')';\n } else if (needsClassNames) {\n for (const prefixedName of prefixedOwnClassNamesArray) {\n result += '.' + escapeCssIdentifier(prefixedName.slice(1));\n }\n }\n\n return new Step(result, false);\n};\n\nconst prefixedElementClassNames = (el: Element): string[] => {\n const classAttribute = el.getAttribute('class');\n if (!classAttribute) {\n return [];\n }\n return classAttribute\n .split(/\\s+/g)\n .filter(Boolean)\n .map((name) => {\n // The prefix is required to store \"__proto__\" in a object-based map.\n return '$' + name;\n });\n};\n\nconst idSelector = (id: string): string => '#' + escapeCssIdentifier(id);\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACxF,OAAO,EAAmB,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAGtE,MAAM,WAAW,2BAA2B;IAC1C,gHAAgH;IAChH,KAAK,CAAC,EAAE,UAAU,CAAC;IACnB,8FAA8F;IAC9F,UAAU,CAAC,EAAE,mBAAmB,CAAC,YAAY,CAAC,CAAC;IAC/C;;;;;;OAMG;IACH,MAAM,CAAC,EAAE,qBAAqB,CAAC;CAChC;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAClC,aAAa,EAAE,sBAAsB,EACrC,OAAO,GAAE,2BAAgC,GACxC,cAAc,CAkDhB"}
1
+ {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACxF,OAAO,EAAmB,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAItE,MAAM,WAAW,2BAA2B;IAC1C,gHAAgH;IAChH,KAAK,CAAC,EAAE,UAAU,CAAC;IACnB,8FAA8F;IAC9F,UAAU,CAAC,EAAE,mBAAmB,CAAC,YAAY,CAAC,CAAC;IAC/C;;;;;;OAMG;IACH,MAAM,CAAC,EAAE,qBAAqB,CAAC;CAChC;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAClC,aAAa,EAAE,sBAAsB,EACrC,OAAO,GAAE,2BAAgC,GACxC,cAAc,CAoFhB"}
package/lib/esm/engine.js CHANGED
@@ -28,6 +28,7 @@
28
28
  import { __values } from "tslib";
29
29
  import { runOrchestrator } from './orchestrator';
30
30
  import { fallbackCssPath } from './fallback-css-path';
31
+ import { legacyCssPath } from './legacy-css-path';
31
32
  /**
32
33
  * Build a `SelectorEngine` bound to the supplied config.
33
34
  *
@@ -50,14 +51,33 @@ export function createSelectorEngine(initialConfig, options) {
50
51
  return {
51
52
  generate: function (el) {
52
53
  var _a, _b;
53
- // Try the strategy chain first.
54
- var composed = runOrchestrator(el, config, orchestratorOptions);
55
- if (composed !== null) {
56
- return composed;
54
+ // Kill switch: when the customer's remote config has the engine
55
+ // disabled (the default for orgs that haven't opted in), emit the same
56
+ // Chromium-derived selector autocapture has shipped since before the
57
+ // strategy chain existed. This is what makes "flip enabled back to
58
+ // false" a one-config-fetch revert for both the SDK and the dashboard —
59
+ // they both go through this entry point now.
60
+ if (!config.enabled) {
61
+ return safeLegacyCssPath(el);
62
+ }
63
+ // Engine path: try the strategy chain, then the hardened fallback. Both
64
+ // are wrapped so a runtime exception (malformed config slipped past the
65
+ // resolver, browser API quirks, a bad scope) still produces a usable
66
+ // selector. Without this, an autocapture click handler could throw
67
+ // mid-flow and the customer would silently lose the event — a worse
68
+ // outcome than emitting a less-stable selector.
69
+ try {
70
+ var composed = runOrchestrator(el, config, orchestratorOptions);
71
+ if (composed !== null) {
72
+ return composed;
73
+ }
74
+ return fallbackCssPath(el, config, { scope: (_b = (_a = options.scope) !== null && _a !== void 0 ? _a : el.ownerDocument) !== null && _b !== void 0 ? _b : document });
75
+ }
76
+ catch (e) {
77
+ var message = e instanceof Error ? e.message : String(e);
78
+ logger === null || logger === void 0 ? void 0 : logger.warn("@amplitude/element-selector: strategy chain threw \u2014 falling back to legacy cssPath: ".concat(message));
79
+ return safeLegacyCssPath(el);
57
80
  }
58
- // Strategy chain found nothing usable — fall back to the hardened
59
- // positional walker with the same scope used by the orchestrator.
60
- return fallbackCssPath(el, config, { scope: (_b = (_a = options.scope) !== null && _a !== void 0 ? _a : el.ownerDocument) !== null && _b !== void 0 ? _b : document });
61
81
  },
62
82
  getConfig: function () {
63
83
  return config;
@@ -96,5 +116,20 @@ export function createSelectorEngine(initialConfig, options) {
96
116
  };
97
117
  },
98
118
  };
119
+ // Local wrapper so a thrown error in the legacy walker (extremely unlikely
120
+ // — Element inputs only — but defensible if a host environment is missing
121
+ // `CSS.escape` or `Node` constants) doesn't escape `generate` and crash the
122
+ // caller. Returns the empty string in that pathological case; consumers
123
+ // already coalesce empty results to a sentinel.
124
+ function safeLegacyCssPath(el) {
125
+ try {
126
+ return legacyCssPath(el);
127
+ }
128
+ catch (e) {
129
+ var message = e instanceof Error ? e.message : String(e);
130
+ logger === null || logger === void 0 ? void 0 : logger.warn("@amplitude/element-selector: legacyCssPath threw \u2014 emitting empty selector: ".concat(message));
131
+ return '';
132
+ }
133
+ }
99
134
  }
100
135
  //# sourceMappingURL=engine.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;;AAGH,OAAO,EAAE,eAAe,EAAuB,MAAM,gBAAgB,CAAC;AACtE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAiBtD;;;;;;;;GAQG;AACH,MAAM,UAAU,oBAAoB,CAClC,aAAqC,EACrC,OAAyC;IAAzC,wBAAA,EAAA,YAAyC;IAEzC,IAAI,MAAM,GAA2B,aAAa,CAAC;IACnD,IAAM,WAAW,GAAG,IAAI,GAAG,EAA4C,CAAC;IACxE,IAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAE9B,IAAM,mBAAmB,GAAwB;QAC/C,UAAU,EAAE,OAAO,CAAC,UAAU;QAC9B,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,MAAM,QAAA;KACP,CAAC;IAEF,OAAO;QACL,QAAQ,YAAC,EAAW;;YAClB,gCAAgC;YAChC,IAAM,QAAQ,GAAG,eAAe,CAAC,EAAE,EAAE,MAAM,EAAE,mBAAmB,CAAC,CAAC;YAClE,IAAI,QAAQ,KAAK,IAAI,EAAE;gBACrB,OAAO,QAAQ,CAAC;aACjB;YACD,kEAAkE;YAClE,kEAAkE;YAClE,OAAO,eAAe,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,MAAA,MAAA,OAAO,CAAC,KAAK,mCAAI,EAAE,CAAC,aAAa,mCAAI,QAAQ,EAAE,CAAC,CAAC;QAC/F,CAAC;QAED,SAAS;YACP,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,YAAY,YAAC,IAA4B;;YACvC,MAAM,GAAG,IAAI,CAAC;;gBACd,qEAAqE;gBACrE,wEAAwE;gBACxE,uEAAuE;gBACvE,qEAAqE;gBACrE,KAAiB,IAAA,gBAAA,SAAA,WAAW,CAAA,wCAAA,iEAAE;oBAAzB,IAAM,EAAE,wBAAA;oBACX,IAAI;wBACF,EAAE,CAAC,IAAI,CAAC,CAAC;qBACV;oBAAC,OAAO,CAAC,EAAE;wBACV,IAAM,OAAO,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;wBAC3D,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,IAAI,CAAC,8EAAkE,OAAO,CAAE,CAAC,CAAC;qBAC3F;iBACF;;;;;;;;;QACH,CAAC;QAED,cAAc,YAAC,EAA4C;YACzD,WAAW,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YACpB,OAAO;gBACL,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACzB,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Engine factory — composes the strategy chain (via `runOrchestrator`) with\n * the safety-net fallback (`fallbackCssPath`) behind a single `SelectorEngine`\n * interface.\n *\n * This is the surface every consumer talks to:\n *\n * - autocapture SDK plugin → instantiates one engine per init() call,\n * wires it into the click handler, and forwards remote-config updates\n * via `updateConfig`.\n * - app.amplitude.com tagging UI → fetches the customer's remote config\n * out-of-band and stands up a transient engine to compute selectors for\n * elements the user clicks in the iframe.\n * - Chrome extension visual tagger → reads the customer's already-live\n * engine off `window.amplitude.elementSelector` (when present) and\n * subscribes to `onConfigChange` so the extension's preview stays in\n * sync with the customer's runtime config.\n *\n * The factory deliberately takes a pre-resolved `ResolvedSelectorConfig` rather\n * than the raw remote payload — config resolution is a separate concern handled\n * by `resolveSelectorConfig`, and keeping it out of the engine constructor lets\n * dashboard / extension consumers stand up an engine from a static snapshot\n * without re-running the full resolver.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { ElementSelectorLogger, ResolvedSelectorConfig, SelectorEngine } from './types';\nimport { runOrchestrator, OrchestratorOptions } from './orchestrator';\nimport { fallbackCssPath } from './fallback-css-path';\n\nexport interface CreateSelectorEngineOptions {\n /** Optional document or shadow root for uniqueness checks. Defaults per-call to the target's owner document. */\n scope?: ParentNode;\n /** Optional override of the strategy chain. Primarily for testing / dashboard ad-hoc runs. */\n strategies?: OrchestratorOptions['strategies'];\n /**\n * Optional logger threaded through the orchestrator and the subscriber-fan-out\n * inside `updateConfig`. When provided, the engine surfaces malformed\n * selectors (`debug`) and listener exceptions (`warn`); when absent it stays\n * silent — preserving the legacy \"fire-and-forget\" semantics existing\n * consumers may rely on.\n */\n logger?: ElementSelectorLogger;\n}\n\n/**\n * Build a `SelectorEngine` bound to the supplied config.\n *\n * The returned engine is independent — calling the factory twice yields two\n * engines with separate config state and separate subscriber lists. This is the\n * shape the autocapture plugin wants (one engine per SDK instance) and the\n * shape the Chrome extension consumes off the page (the extension reads, never\n * writes).\n */\nexport function createSelectorEngine(\n initialConfig: ResolvedSelectorConfig,\n options: CreateSelectorEngineOptions = {},\n): SelectorEngine {\n let config: ResolvedSelectorConfig = initialConfig;\n const subscribers = new Set<(config: ResolvedSelectorConfig) => void>();\n const logger = options.logger;\n\n const orchestratorOptions: OrchestratorOptions = {\n strategies: options.strategies,\n scope: options.scope,\n logger,\n };\n\n return {\n generate(el: Element): string {\n // Try the strategy chain first.\n const composed = runOrchestrator(el, config, orchestratorOptions);\n if (composed !== null) {\n return composed;\n }\n // Strategy chain found nothing usable — fall back to the hardened\n // positional walker with the same scope used by the orchestrator.\n return fallbackCssPath(el, config, { scope: options.scope ?? el.ownerDocument ?? document });\n },\n\n getConfig(): Readonly<ResolvedSelectorConfig> {\n return config;\n },\n\n updateConfig(next: ResolvedSelectorConfig): void {\n config = next;\n // Notify subscribers in insertion order. Errors thrown by individual\n // subscribers are isolated so one bad listener can't break the others —\n // the extension's listener is the canonical consumer here and we don't\n // want SDK-side changes to cascade-fail because of an extension bug.\n for (const cb of subscribers) {\n try {\n cb(next);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: onConfigChange subscriber threw — ${message}`);\n }\n }\n },\n\n onConfigChange(cb: (config: ResolvedSelectorConfig) => void): () => void {\n subscribers.add(cb);\n return () => {\n subscribers.delete(cb);\n };\n },\n };\n}\n"]}
1
+ {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;;AAGH,OAAO,EAAE,eAAe,EAAuB,MAAM,gBAAgB,CAAC;AACtE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAiBlD;;;;;;;;GAQG;AACH,MAAM,UAAU,oBAAoB,CAClC,aAAqC,EACrC,OAAyC;IAAzC,wBAAA,EAAA,YAAyC;IAEzC,IAAI,MAAM,GAA2B,aAAa,CAAC;IACnD,IAAM,WAAW,GAAG,IAAI,GAAG,EAA4C,CAAC;IACxE,IAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IA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gBACrE,KAAiB,IAAA,gBAAA,SAAA,WAAW,CAAA,wCAAA,iEAAE;oBAAzB,IAAM,EAAE,wBAAA;oBACX,IAAI;wBACF,EAAE,CAAC,IAAI,CAAC,CAAC;qBACV;oBAAC,OAAO,CAAC,EAAE;wBACV,IAAM,OAAO,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;wBAC3D,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,IAAI,CAAC,8EAAkE,OAAO,CAAE,CAAC,CAAC;qBAC3F;iBACF;;;;;;;;;QACH,CAAC;QAED,cAAc,YAAC,EAA4C;YACzD,WAAW,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YACpB,OAAO;gBACL,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACzB,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;IAEF,2EAA2E;IAC3E,0EAA0E;IAC1E,4EAA4E;IAC5E,wEAAwE;IACxE,gDAAgD;IAChD,SAAS,iBAAiB,CAAC,EAAW;QACpC,IAAI;YACF,OAAO,aAAa,CAAC,EAAE,CAAC,CAAC;SAC1B;QAAC,OAAO,CAAC,EAAE;YACV,IAAM,OAAO,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YAC3D,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,IAAI,CAAC,2FAA+E,OAAO,CAAE,CAAC,CAAC;YACvG,OAAO,EAAE,CAAC;SACX;IACH,CAAC;AACH,CAAC","sourcesContent":["/**\n * Engine factory — composes the strategy chain (via `runOrchestrator`) with\n * the safety-net fallback (`fallbackCssPath`) behind a single `SelectorEngine`\n * interface.\n *\n * This is the surface every consumer talks to:\n *\n * - autocapture SDK plugin → instantiates one engine per init() call,\n * wires it into the click handler, and forwards remote-config updates\n * via `updateConfig`.\n * - app.amplitude.com tagging UI → fetches the customer's remote config\n * out-of-band and stands up a transient engine to compute selectors for\n * elements the user clicks in the iframe.\n * - Chrome extension visual tagger → reads the customer's already-live\n * engine off `window.amplitude.elementSelector` (when present) and\n * subscribes to `onConfigChange` so the extension's preview stays in\n * sync with the customer's runtime config.\n *\n * The factory deliberately takes a pre-resolved `ResolvedSelectorConfig` rather\n * than the raw remote payload — config resolution is a separate concern handled\n * by `resolveSelectorConfig`, and keeping it out of the engine constructor lets\n * dashboard / extension consumers stand up an engine from a static snapshot\n * without re-running the full resolver.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { ElementSelectorLogger, ResolvedSelectorConfig, SelectorEngine } from './types';\nimport { runOrchestrator, OrchestratorOptions } from './orchestrator';\nimport { fallbackCssPath } from './fallback-css-path';\nimport { legacyCssPath } from './legacy-css-path';\n\nexport interface CreateSelectorEngineOptions {\n /** Optional document or shadow root for uniqueness checks. Defaults per-call to the target's owner document. */\n scope?: ParentNode;\n /** Optional override of the strategy chain. Primarily for testing / dashboard ad-hoc runs. */\n strategies?: OrchestratorOptions['strategies'];\n /**\n * Optional logger threaded through the orchestrator and the subscriber-fan-out\n * inside `updateConfig`. When provided, the engine surfaces malformed\n * selectors (`debug`) and listener exceptions (`warn`); when absent it stays\n * silent — preserving the legacy \"fire-and-forget\" semantics existing\n * consumers may rely on.\n */\n logger?: ElementSelectorLogger;\n}\n\n/**\n * Build a `SelectorEngine` bound to the supplied config.\n *\n * The returned engine is independent — calling the factory twice yields two\n * engines with separate config state and separate subscriber lists. This is the\n * shape the autocapture plugin wants (one engine per SDK instance) and the\n * shape the Chrome extension consumes off the page (the extension reads, never\n * writes).\n */\nexport function createSelectorEngine(\n initialConfig: ResolvedSelectorConfig,\n options: CreateSelectorEngineOptions = {},\n): SelectorEngine {\n let config: ResolvedSelectorConfig = initialConfig;\n const subscribers = new Set<(config: ResolvedSelectorConfig) => void>();\n const logger = options.logger;\n\n const orchestratorOptions: OrchestratorOptions = {\n strategies: options.strategies,\n scope: options.scope,\n logger,\n };\n\n return {\n generate(el: Element): string {\n // Kill switch: when the customer's remote config has the engine\n // disabled (the default for orgs that haven't opted in), emit the same\n // Chromium-derived selector autocapture has shipped since before the\n // strategy chain existed. This is what makes \"flip enabled back to\n // false\" a one-config-fetch revert for both the SDK and the dashboard —\n // they both go through this entry point now.\n if (!config.enabled) {\n return safeLegacyCssPath(el);\n }\n\n // Engine path: try the strategy chain, then the hardened fallback. Both\n // are wrapped so a runtime exception (malformed config slipped past the\n // resolver, browser API quirks, a bad scope) still produces a usable\n // selector. Without this, an autocapture click handler could throw\n // mid-flow and the customer would silently lose the event — a worse\n // outcome than emitting a less-stable selector.\n try {\n const composed = runOrchestrator(el, config, orchestratorOptions);\n if (composed !== null) {\n return composed;\n }\n return fallbackCssPath(el, config, { scope: options.scope ?? el.ownerDocument ?? document });\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: strategy chain threw — falling back to legacy cssPath: ${message}`);\n return safeLegacyCssPath(el);\n }\n },\n\n getConfig(): Readonly<ResolvedSelectorConfig> {\n return config;\n },\n\n updateConfig(next: ResolvedSelectorConfig): void {\n config = next;\n // Notify subscribers in insertion order. Errors thrown by individual\n // subscribers are isolated so one bad listener can't break the others —\n // the extension's listener is the canonical consumer here and we don't\n // want SDK-side changes to cascade-fail because of an extension bug.\n for (const cb of subscribers) {\n try {\n cb(next);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: onConfigChange subscriber threw — ${message}`);\n }\n }\n },\n\n onConfigChange(cb: (config: ResolvedSelectorConfig) => void): () => void {\n subscribers.add(cb);\n return () => {\n subscribers.delete(cb);\n };\n },\n };\n\n // Local wrapper so a thrown error in the legacy walker (extremely unlikely\n // — Element inputs only — but defensible if a host environment is missing\n // `CSS.escape` or `Node` constants) doesn't escape `generate` and crash the\n // caller. Returns the empty string in that pathological case; consumers\n // already coalesce empty results to a sentinel.\n function safeLegacyCssPath(el: Element): string {\n try {\n return legacyCssPath(el);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: legacyCssPath threw — emitting empty selector: ${message}`);\n return '';\n }\n }\n}\n"]}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Top-level chokepoint for "generate a selector for this element."
3
+ *
4
+ * Both the SDK plugin (`plugin-autocapture-browser`) and the dashboard
5
+ * (`session-replay-ui`) used to maintain their own copy of this routing logic:
6
+ *
7
+ * if (config.enabled && engine) return engine.generate(el);
8
+ * else return cssPath(el, false);
9
+ *
10
+ * Two consumers, two routers, two locally-bundled copies of `cssPath`. As soon
11
+ * as we considered a third consumer (Chrome extension visual tagger, future
12
+ * tagging surfaces) the duplication became untenable — bug fixes had to land
13
+ * three places and the kill-switch semantics could drift between them.
14
+ *
15
+ * Moving the kill switch inside `engine.generate` covered the "engine present"
16
+ * case. This helper covers the remaining "engine is null" case that some
17
+ * consumers genuinely have:
18
+ *
19
+ * - dashboard's `useElementSelectorEngineContext()` returns
20
+ * `{ engine: null }` when no provider is mounted (tests, content-renderer
21
+ * paths, future call sites outside the canonical mount tree).
22
+ * - Chrome extension boots before the customer's SDK has stood up an engine
23
+ * on the page; reads `null` from `window.amplitude.elementSelector` until
24
+ * the SDK init finishes.
25
+ *
26
+ * In those cases, callers want the legacy `cssPath` selector — same shape the
27
+ * SDK is emitting in production for orgs without the engine. This helper makes
28
+ * that explicit and centralizes the rule so future consumers don't reinvent
29
+ * it.
30
+ */
31
+ import { ResolvedSelectorConfig, SelectorEngine } from './types';
32
+ /**
33
+ * Generate a selector for `el`, transparently routing to the legacy
34
+ * `cssPath` walker when no engine is available.
35
+ *
36
+ * Why this signature (engine + config separately, rather than just engine):
37
+ * the dashboard's inert context has `engine: null` but still carries a
38
+ * resolved config. Both `null`-engine and engine-with-`enabled: false`
39
+ * collapse to "legacy `cssPath`", and we want the same one-line call site
40
+ * to handle both. When the engine *is* present, this just delegates — the
41
+ * engine's own kill switch handles `enabled === false`.
42
+ *
43
+ * Never throws. Returns the empty string in the pathological case where the
44
+ * legacy walker itself can't produce one (non-element nodes; environments
45
+ * missing `CSS.escape`).
46
+ *
47
+ * @param el DOM element to identify.
48
+ * @param engine Live `SelectorEngine`, or `null` when no engine is mounted.
49
+ * @param config Resolved selector config. Only consulted in the null-engine
50
+ * branch; when `engine` is present, the engine consults its
51
+ * own internal config.
52
+ */
53
+ export declare const generateSelector: (el: Element, engine: SelectorEngine | null, config: ResolvedSelectorConfig) => string;
54
+ //# sourceMappingURL=generate-selector.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-selector.d.ts","sourceRoot":"","sources":["../../src/generate-selector.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAGjE;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,gBAAgB,OACvB,OAAO,UACH,cAAc,GAAG,IAAI,UACrB,sBAAsB,KAC7B,MAiBF,CAAC"}
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Top-level chokepoint for "generate a selector for this element."
3
+ *
4
+ * Both the SDK plugin (`plugin-autocapture-browser`) and the dashboard
5
+ * (`session-replay-ui`) used to maintain their own copy of this routing logic:
6
+ *
7
+ * if (config.enabled && engine) return engine.generate(el);
8
+ * else return cssPath(el, false);
9
+ *
10
+ * Two consumers, two routers, two locally-bundled copies of `cssPath`. As soon
11
+ * as we considered a third consumer (Chrome extension visual tagger, future
12
+ * tagging surfaces) the duplication became untenable — bug fixes had to land
13
+ * three places and the kill-switch semantics could drift between them.
14
+ *
15
+ * Moving the kill switch inside `engine.generate` covered the "engine present"
16
+ * case. This helper covers the remaining "engine is null" case that some
17
+ * consumers genuinely have:
18
+ *
19
+ * - dashboard's `useElementSelectorEngineContext()` returns
20
+ * `{ engine: null }` when no provider is mounted (tests, content-renderer
21
+ * paths, future call sites outside the canonical mount tree).
22
+ * - Chrome extension boots before the customer's SDK has stood up an engine
23
+ * on the page; reads `null` from `window.amplitude.elementSelector` until
24
+ * the SDK init finishes.
25
+ *
26
+ * In those cases, callers want the legacy `cssPath` selector — same shape the
27
+ * SDK is emitting in production for orgs without the engine. This helper makes
28
+ * that explicit and centralizes the rule so future consumers don't reinvent
29
+ * it.
30
+ */
31
+ import { legacyCssPath } from './legacy-css-path';
32
+ /**
33
+ * Generate a selector for `el`, transparently routing to the legacy
34
+ * `cssPath` walker when no engine is available.
35
+ *
36
+ * Why this signature (engine + config separately, rather than just engine):
37
+ * the dashboard's inert context has `engine: null` but still carries a
38
+ * resolved config. Both `null`-engine and engine-with-`enabled: false`
39
+ * collapse to "legacy `cssPath`", and we want the same one-line call site
40
+ * to handle both. When the engine *is* present, this just delegates — the
41
+ * engine's own kill switch handles `enabled === false`.
42
+ *
43
+ * Never throws. Returns the empty string in the pathological case where the
44
+ * legacy walker itself can't produce one (non-element nodes; environments
45
+ * missing `CSS.escape`).
46
+ *
47
+ * @param el DOM element to identify.
48
+ * @param engine Live `SelectorEngine`, or `null` when no engine is mounted.
49
+ * @param config Resolved selector config. Only consulted in the null-engine
50
+ * branch; when `engine` is present, the engine consults its
51
+ * own internal config.
52
+ */
53
+ export var generateSelector = function (el, engine, config) {
54
+ if (engine) {
55
+ // The engine has its own kill switch (`config.enabled === false` →
56
+ // legacy cssPath) and its own try/catch safety net. Trust it.
57
+ return engine.generate(el);
58
+ }
59
+ // Engine-null branch. We don't have a live engine to consult, so we route
60
+ // straight to the legacy walker — the same selector the SDK would be
61
+ // emitting if `config.enabled === false`. `config` is accepted for symmetry
62
+ // with the engine signature and so future versions can extend behavior
63
+ // without a breaking change.
64
+ void config;
65
+ try {
66
+ return legacyCssPath(el);
67
+ }
68
+ catch (_a) {
69
+ return '';
70
+ }
71
+ };
72
+ //# sourceMappingURL=generate-selector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-selector.js","sourceRoot":"","sources":["../../src/generate-selector.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,CAAC,IAAM,gBAAgB,GAAG,UAC9B,EAAW,EACX,MAA6B,EAC7B,MAA8B;IAE9B,IAAI,MAAM,EAAE;QACV,mEAAmE;QACnE,8DAA8D;QAC9D,OAAO,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;KAC5B;IACD,0EAA0E;IAC1E,qEAAqE;IACrE,4EAA4E;IAC5E,uEAAuE;IACvE,6BAA6B;IAC7B,KAAK,MAAM,CAAC;IACZ,IAAI;QACF,OAAO,aAAa,CAAC,EAAE,CAAC,CAAC;KAC1B;IAAC,WAAM;QACN,OAAO,EAAE,CAAC;KACX;AACH,CAAC,CAAC","sourcesContent":["/**\n * Top-level chokepoint for \"generate a selector for this element.\"\n *\n * Both the SDK plugin (`plugin-autocapture-browser`) and the dashboard\n * (`session-replay-ui`) used to maintain their own copy of this routing logic:\n *\n * if (config.enabled && engine) return engine.generate(el);\n * else return cssPath(el, false);\n *\n * Two consumers, two routers, two locally-bundled copies of `cssPath`. As soon\n * as we considered a third consumer (Chrome extension visual tagger, future\n * tagging surfaces) the duplication became untenable — bug fixes had to land\n * three places and the kill-switch semantics could drift between them.\n *\n * Moving the kill switch inside `engine.generate` covered the \"engine present\"\n * case. This helper covers the remaining \"engine is null\" case that some\n * consumers genuinely have:\n *\n * - dashboard's `useElementSelectorEngineContext()` returns\n * `{ engine: null }` when no provider is mounted (tests, content-renderer\n * paths, future call sites outside the canonical mount tree).\n * - Chrome extension boots before the customer's SDK has stood up an engine\n * on the page; reads `null` from `window.amplitude.elementSelector` until\n * the SDK init finishes.\n *\n * In those cases, callers want the legacy `cssPath` selector — same shape the\n * SDK is emitting in production for orgs without the engine. This helper makes\n * that explicit and centralizes the rule so future consumers don't reinvent\n * it.\n */\n\nimport { ResolvedSelectorConfig, SelectorEngine } from './types';\nimport { legacyCssPath } from './legacy-css-path';\n\n/**\n * Generate a selector for `el`, transparently routing to the legacy\n * `cssPath` walker when no engine is available.\n *\n * Why this signature (engine + config separately, rather than just engine):\n * the dashboard's inert context has `engine: null` but still carries a\n * resolved config. Both `null`-engine and engine-with-`enabled: false`\n * collapse to \"legacy `cssPath`\", and we want the same one-line call site\n * to handle both. When the engine *is* present, this just delegates — the\n * engine's own kill switch handles `enabled === false`.\n *\n * Never throws. Returns the empty string in the pathological case where the\n * legacy walker itself can't produce one (non-element nodes; environments\n * missing `CSS.escape`).\n *\n * @param el DOM element to identify.\n * @param engine Live `SelectorEngine`, or `null` when no engine is mounted.\n * @param config Resolved selector config. Only consulted in the null-engine\n * branch; when `engine` is present, the engine consults its\n * own internal config.\n */\nexport const generateSelector = (\n el: Element,\n engine: SelectorEngine | null,\n config: ResolvedSelectorConfig,\n): string => {\n if (engine) {\n // The engine has its own kill switch (`config.enabled === false` →\n // legacy cssPath) and its own try/catch safety net. Trust it.\n return engine.generate(el);\n }\n // Engine-null branch. We don't have a live engine to consult, so we route\n // straight to the legacy walker — the same selector the SDK would be\n // emitting if `config.enabled === false`. `config` is accepted for symmetry\n // with the engine signature and so future versions can extend behavior\n // without a breaking change.\n void config;\n try {\n return legacyCssPath(el);\n } catch {\n return '';\n }\n};\n"]}
@@ -23,7 +23,9 @@ export { stableId as stableIdStrategy } from './strategies/stable-id';
23
23
  export { runOrchestrator, DEFAULT_STRATEGIES } from './orchestrator';
24
24
  export type { OrchestratorOptions } from './orchestrator';
25
25
  export { fallbackCssPath } from './fallback-css-path';
26
+ export { legacyCssPath } from './legacy-css-path';
26
27
  export { resolveSelectorConfig, DEFAULT_RESOLVED_CONFIG } from './config/resolve-config';
27
28
  export { createSelectorEngine } from './engine';
28
29
  export type { CreateSelectorEngineOptions } from './engine';
30
+ export { generateSelector } from './generate-selector';
29
31
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,eAAO,MAAM,YAAY,gCAAgC,CAAC;AAG1D,YAAY,EACV,QAAQ,EACR,eAAe,EACf,sBAAsB,EACtB,2BAA2B,EAC3B,qBAAqB,EACrB,cAAc,GACf,MAAM,SAAS,CAAC;AAGjB,OAAO,EACL,iCAAiC,EACjC,OAAO,IAAI,8BAA8B,EACzC,UAAU,GACX,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,+BAA+B,EAC/B,OAAO,IAAI,4BAA4B,EACvC,aAAa,GACd,MAAM,6BAA6B,CAAC;AAGrC,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAG/D,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AACrF,OAAO,EAAE,QAAQ,IAAI,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAKtE,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACrE,YAAY,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAGtD,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAGzF,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAChD,YAAY,EAAE,2BAA2B,EAAE,MAAM,UAAU,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,eAAO,MAAM,YAAY,gCAAgC,CAAC;AAG1D,YAAY,EACV,QAAQ,EACR,eAAe,EACf,sBAAsB,EACtB,2BAA2B,EAC3B,qBAAqB,EACrB,cAAc,GACf,MAAM,SAAS,CAAC;AAGjB,OAAO,EACL,iCAAiC,EACjC,OAAO,IAAI,8BAA8B,EACzC,UAAU,GACX,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,+BAA+B,EAC/B,OAAO,IAAI,4BAA4B,EACvC,aAAa,GACd,MAAM,6BAA6B,CAAC;AAGrC,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAG/D,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AACrF,OAAO,EAAE,QAAQ,IAAI,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAKtE,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACrE,YAAY,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAWtD,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAGlD,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAGzF,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAChD,YAAY,EAAE,2BAA2B,EAAE,MAAM,UAAU,CAAC;AAO5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC"}
package/lib/esm/index.js CHANGED
@@ -27,8 +27,24 @@ export { stableId as stableIdStrategy } from './strategies/stable-id';
27
27
  // without instantiating a full engine — useful for preview / debugging flows.
28
28
  export { runOrchestrator, DEFAULT_STRATEGIES } from './orchestrator';
29
29
  export { fallbackCssPath } from './fallback-css-path';
30
+ // ===== Legacy walker =====
31
+ // Canonical home for the Chromium-DevTools-derived `cssPath` algorithm.
32
+ // Both `plugin-autocapture-browser` and `session-replay-ui` historically
33
+ // shipped their own copies kept in sync by comment; both will switch to
34
+ // re-exporting from here so the two can never drift again. End consumers
35
+ // rarely need to call this directly — `engine.generate` and
36
+ // `generateSelector` route through it automatically — but it's exported so
37
+ // the SDK and dashboard can drop their local copies without breaking
38
+ // downstream imports.
39
+ export { legacyCssPath } from './legacy-css-path';
30
40
  // ===== Config resolver =====
31
41
  export { resolveSelectorConfig, DEFAULT_RESOLVED_CONFIG } from './config/resolve-config';
32
42
  // ===== Engine factory =====
33
43
  export { createSelectorEngine } from './engine';
44
+ // ===== Top-level selector entry point =====
45
+ // Use this from React contexts / boot-time call sites where the engine may
46
+ // not yet be available. When the engine *is* present, just call
47
+ // `engine.generate(el)` directly — it has the same kill-switch semantics
48
+ // baked in.
49
+ export { generateSelector } from './generate-selector';
34
50
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,MAAM,CAAC,IAAM,YAAY,GAAG,6BAA6B,CAAC;AAY1D,4BAA4B;AAC5B,OAAO,EACL,iCAAiC,EACjC,OAAO,IAAI,8BAA8B,EACzC,UAAU,GACX,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,+BAA+B,EAC/B,OAAO,IAAI,4BAA4B,EACvC,aAAa,GACd,MAAM,6BAA6B,CAAC;AAErC,sBAAsB;AACtB,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAE/D,yBAAyB;AACzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AACrF,OAAO,EAAE,QAAQ,IAAI,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAEtE,sCAAsC;AACtC,4EAA4E;AAC5E,8EAA8E;AAC9E,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAErE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD,8BAA8B;AAC9B,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAEzF,6BAA6B;AAC7B,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC","sourcesContent":["/**\n * @amplitude/element-selector\n *\n * Shared element-selector algorithm consumed by autocapture, the\n * app.amplitude.com tagging UI, and the Chrome extension visual tagger.\n *\n * This file is the package's public API surface. The orchestrator, fallback,\n * config resolver, and engine factory compose on top of the primitives\n * (types, pattern packs, helpers, strategies) to produce the runtime engine\n * consumers actually call.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nexport const PACKAGE_NAME = '@amplitude/element-selector';\n\n// ===== Types =====\nexport type {\n Strategy,\n StrategyContext,\n ResolvedSelectorConfig,\n ElementSelectorRemoteConfig,\n ElementSelectorLogger,\n SelectorEngine,\n} from './types';\n\n// ===== Pattern packs =====\nexport {\n DEFAULT_AUTOGENERATED_ID_PATTERNS,\n compile as compileAutogeneratedIdPatterns,\n isStableId,\n} from './patterns/autogenerated-ids';\n\nexport {\n DEFAULT_UNSTABLE_CLASS_PATTERNS,\n compile as compileUnstableClassPatterns,\n filterClasses,\n} from './patterns/unstable-classes';\n\n// ===== Helpers =====\nexport { getStableId } from './helpers/get-stable-id';\nexport { describeRelative } from './helpers/describe-relative';\n\n// ===== Strategies =====\nexport { explicitTrackingAttribute } from './strategies/explicit-tracking-attribute';\nexport { stableId as stableIdStrategy } from './strategies/stable-id';\n\n// ===== Orchestrator + fallback =====\n// Exposed publicly so the dashboard / Chrome extension can call them ad-hoc\n// without instantiating a full engine — useful for preview / debugging flows.\nexport { runOrchestrator, DEFAULT_STRATEGIES } from './orchestrator';\nexport type { OrchestratorOptions } from './orchestrator';\nexport { fallbackCssPath } from './fallback-css-path';\n\n// ===== Config resolver =====\nexport { resolveSelectorConfig, DEFAULT_RESOLVED_CONFIG } from './config/resolve-config';\n\n// ===== Engine factory =====\nexport { createSelectorEngine } from './engine';\nexport type { CreateSelectorEngineOptions } from './engine';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,MAAM,CAAC,IAAM,YAAY,GAAG,6BAA6B,CAAC;AAY1D,4BAA4B;AAC5B,OAAO,EACL,iCAAiC,EACjC,OAAO,IAAI,8BAA8B,EACzC,UAAU,GACX,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,+BAA+B,EAC/B,OAAO,IAAI,4BAA4B,EACvC,aAAa,GACd,MAAM,6BAA6B,CAAC;AAErC,sBAAsB;AACtB,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAE/D,yBAAyB;AACzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AACrF,OAAO,EAAE,QAAQ,IAAI,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAEtE,sCAAsC;AACtC,4EAA4E;AAC5E,8EAA8E;AAC9E,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAErE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD,4BAA4B;AAC5B,wEAAwE;AACxE,yEAAyE;AACzE,wEAAwE;AACxE,yEAAyE;AACzE,4DAA4D;AAC5D,2EAA2E;AAC3E,qEAAqE;AACrE,sBAAsB;AACtB,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAElD,8BAA8B;AAC9B,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAEzF,6BAA6B;AAC7B,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAGhD,6CAA6C;AAC7C,2EAA2E;AAC3E,gEAAgE;AAChE,yEAAyE;AACzE,YAAY;AACZ,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["/**\n * @amplitude/element-selector\n *\n * Shared element-selector algorithm consumed by autocapture, the\n * app.amplitude.com tagging UI, and the Chrome extension visual tagger.\n *\n * This file is the package's public API surface. The orchestrator, fallback,\n * config resolver, and engine factory compose on top of the primitives\n * (types, pattern packs, helpers, strategies) to produce the runtime engine\n * consumers actually call.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nexport const PACKAGE_NAME = '@amplitude/element-selector';\n\n// ===== Types =====\nexport type {\n Strategy,\n StrategyContext,\n ResolvedSelectorConfig,\n ElementSelectorRemoteConfig,\n ElementSelectorLogger,\n SelectorEngine,\n} from './types';\n\n// ===== Pattern packs =====\nexport {\n DEFAULT_AUTOGENERATED_ID_PATTERNS,\n compile as compileAutogeneratedIdPatterns,\n isStableId,\n} from './patterns/autogenerated-ids';\n\nexport {\n DEFAULT_UNSTABLE_CLASS_PATTERNS,\n compile as compileUnstableClassPatterns,\n filterClasses,\n} from './patterns/unstable-classes';\n\n// ===== Helpers =====\nexport { getStableId } from './helpers/get-stable-id';\nexport { describeRelative } from './helpers/describe-relative';\n\n// ===== Strategies =====\nexport { explicitTrackingAttribute } from './strategies/explicit-tracking-attribute';\nexport { stableId as stableIdStrategy } from './strategies/stable-id';\n\n// ===== Orchestrator + fallback =====\n// Exposed publicly so the dashboard / Chrome extension can call them ad-hoc\n// without instantiating a full engine — useful for preview / debugging flows.\nexport { runOrchestrator, DEFAULT_STRATEGIES } from './orchestrator';\nexport type { OrchestratorOptions } from './orchestrator';\nexport { fallbackCssPath } from './fallback-css-path';\n\n// ===== Legacy walker =====\n// Canonical home for the Chromium-DevTools-derived `cssPath` algorithm.\n// Both `plugin-autocapture-browser` and `session-replay-ui` historically\n// shipped their own copies kept in sync by comment; both will switch to\n// re-exporting from here so the two can never drift again. End consumers\n// rarely need to call this directly — `engine.generate` and\n// `generateSelector` route through it automatically — but it's exported so\n// the SDK and dashboard can drop their local copies without breaking\n// downstream imports.\nexport { legacyCssPath } from './legacy-css-path';\n\n// ===== Config resolver =====\nexport { resolveSelectorConfig, DEFAULT_RESOLVED_CONFIG } from './config/resolve-config';\n\n// ===== Engine factory =====\nexport { createSelectorEngine } from './engine';\nexport type { CreateSelectorEngineOptions } from './engine';\n\n// ===== Top-level selector entry point =====\n// Use this from React contexts / boot-time call sites where the engine may\n// not yet be available. When the engine *is* present, just call\n// `engine.generate(el)` directly — it has the same kill-switch semantics\n// baked in.\nexport { generateSelector } from './generate-selector';\n"]}