@amplitude/element-selector 0.2.1 → 0.3.1-video-analytics-2.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.
Files changed (52) hide show
  1. package/README.md +22 -0
  2. package/lib/cjs/config/resolve-config.d.ts +21 -3
  3. package/lib/cjs/config/resolve-config.d.ts.map +1 -1
  4. package/lib/cjs/config/resolve-config.js +47 -2
  5. package/lib/cjs/config/resolve-config.js.map +1 -1
  6. package/lib/cjs/engine.d.ts.map +1 -1
  7. package/lib/cjs/engine.js +61 -27
  8. package/lib/cjs/engine.js.map +1 -1
  9. package/lib/cjs/fallback-css-path.d.ts +6 -1
  10. package/lib/cjs/fallback-css-path.d.ts.map +1 -1
  11. package/lib/cjs/fallback-css-path.js +38 -37
  12. package/lib/cjs/fallback-css-path.js.map +1 -1
  13. package/lib/cjs/helpers/shadow.d.ts +196 -0
  14. package/lib/cjs/helpers/shadow.d.ts.map +1 -0
  15. package/lib/cjs/helpers/shadow.js +415 -0
  16. package/lib/cjs/helpers/shadow.js.map +1 -0
  17. package/lib/cjs/index.d.ts +4 -2
  18. package/lib/cjs/index.d.ts.map +1 -1
  19. package/lib/cjs/index.js +19 -1
  20. package/lib/cjs/index.js.map +1 -1
  21. package/lib/cjs/orchestrator.d.ts.map +1 -1
  22. package/lib/cjs/orchestrator.js +4 -2
  23. package/lib/cjs/orchestrator.js.map +1 -1
  24. package/lib/cjs/types.d.ts +36 -1
  25. package/lib/cjs/types.d.ts.map +1 -1
  26. package/lib/cjs/types.js.map +1 -1
  27. package/lib/esm/config/resolve-config.d.ts +21 -3
  28. package/lib/esm/config/resolve-config.d.ts.map +1 -1
  29. package/lib/esm/config/resolve-config.js +46 -2
  30. package/lib/esm/config/resolve-config.js.map +1 -1
  31. package/lib/esm/engine.d.ts.map +1 -1
  32. package/lib/esm/engine.js +61 -27
  33. package/lib/esm/engine.js.map +1 -1
  34. package/lib/esm/fallback-css-path.d.ts +6 -1
  35. package/lib/esm/fallback-css-path.d.ts.map +1 -1
  36. package/lib/esm/fallback-css-path.js +37 -36
  37. package/lib/esm/fallback-css-path.js.map +1 -1
  38. package/lib/esm/helpers/shadow.d.ts +196 -0
  39. package/lib/esm/helpers/shadow.d.ts.map +1 -0
  40. package/lib/esm/helpers/shadow.js +402 -0
  41. package/lib/esm/helpers/shadow.js.map +1 -0
  42. package/lib/esm/index.d.ts +4 -2
  43. package/lib/esm/index.d.ts.map +1 -1
  44. package/lib/esm/index.js +9 -1
  45. package/lib/esm/index.js.map +1 -1
  46. package/lib/esm/orchestrator.d.ts.map +1 -1
  47. package/lib/esm/orchestrator.js +4 -2
  48. package/lib/esm/orchestrator.js.map +1 -1
  49. package/lib/esm/types.d.ts +36 -1
  50. package/lib/esm/types.d.ts.map +1 -1
  51. package/lib/esm/types.js.map +1 -1
  52. package/package.json +1 -1
@@ -0,0 +1,402 @@
1
+ /**
2
+ * Shadow-DOM traversal + re-resolution helpers.
3
+ *
4
+ * CSS selectors cannot pierce shadow boundaries: `document.querySelector` never
5
+ * matches an element that lives inside a shadow root. So a selector that needs
6
+ * to reach into shadow DOM can't be a single flat string — it has to be a
7
+ * sequence of per-tree selectors, one per shadow tree, each resolvable within
8
+ * its own root. We join those segments with `SHADOW_BOUNDARY_DELIMITER` and
9
+ * re-resolve them with `resolveSelector`, descending one `shadowRoot` per
10
+ * boundary.
11
+ *
12
+ * This module owns the primitives that knowledge lives in:
13
+ *
14
+ * - `composedParent` / `rootOf` — walk *out* of a shadow tree (the light-DOM
15
+ * `parentElement` chain dead-ends at a shadow root; `getRootNode().host`
16
+ * crosses the boundary).
17
+ * - `segmentWalk` — split the outward walk into per-tree segments, honoring
18
+ * the configured max shadow depth.
19
+ * - `resolveSelector` — the symmetric inverse of the engine's output: split
20
+ * on the delimiter and pierce open shadow roots to re-find the element.
21
+ * - `walkComposedAncestors` — yield ancestors up the composed tree, honoring a
22
+ * shadow-boundary crossing budget (shared by capture and selector layers).
23
+ * - `collectOpenShadowRoots` — DFS collection of open shadow roots for
24
+ * observer fan-out and deep `querySelectorAll`.
25
+ * - `positionalStep` — a shadow-aware `tag:nth-of-type(n)` builder shared by
26
+ * the orchestrator's descent and the fallback walker, so a shadow-root-top
27
+ * element is still disambiguated against its `ShadowRoot` siblings.
28
+ *
29
+ * See the design doc:
30
+ * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
31
+ */
32
+ import { __generator, __read, __values } from "tslib";
33
+ /**
34
+ * Delimiter that separates per-shadow-tree segments in a generated selector.
35
+ *
36
+ * Chosen to be visually distinct and trivially splittable, and to be invalid as
37
+ * a real CSS combinator so it can never be confused with a `>` child combinator
38
+ * the engine emits inside a single tree. Example output:
39
+ *
40
+ * `div#host >>> button:nth-of-type(1)`
41
+ *
42
+ * which `resolveSelector` re-resolves as
43
+ * `document.querySelector('div#host').shadowRoot.querySelector('button:nth-of-type(1)')`.
44
+ */
45
+ export var SHADOW_BOUNDARY_DELIMITER = ' >>> ';
46
+ /**
47
+ * Marker prefix for a "direct child from the root" chain inside a shadow tree.
48
+ *
49
+ * A positional chain scoped to a `ShadowRoot` (e.g. `div:nth-of-type(2)`) is not
50
+ * anchored: `querySelector` matches it tree-wide, and `:scope` matches nothing
51
+ * on a `ShadowRoot` (it isn't an element), so there is no CSS way to express
52
+ * "direct child of the root." The generator therefore prefixes such chains with
53
+ * this marker and `resolveSelector` resolves them by strict direct-child descent
54
+ * instead of `querySelector`. Keying off this explicit marker — rather than
55
+ * sniffing a segment for the absence of `#`/`[` — keeps the round-trip correct
56
+ * no matter what the steps contain (tag, `:nth-of-type`, classes, …).
57
+ *
58
+ * `:scope > ` is deliberately valid CSS syntax so a generated selector stays a
59
+ * syntactically legal string; its meaning here is purely the descent signal.
60
+ */
61
+ export var SHADOW_CHILD_CHAIN_PREFIX = ':scope > ';
62
+ /** Narrowing guard that tolerates environments without a `ShadowRoot` global. */
63
+ export function isShadowRoot(node) {
64
+ return typeof ShadowRoot !== 'undefined' && node instanceof ShadowRoot;
65
+ }
66
+ /**
67
+ * Anchor a per-tree segment so it re-resolves within a `ShadowRoot`.
68
+ *
69
+ * Both selector algorithms (the strategy-chain fallback and the legacy Chromium
70
+ * `cssPath`) can emit a segment that is only *positionally* specified — a chain
71
+ * of `tag:nth-*` / class steps with no id or attribute to pin it. In the light
72
+ * DOM the chain is implicitly anchored by the unique `<html>` root; inside a
73
+ * shadow root there is no such root element, so `querySelector` matches the
74
+ * chain tree-wide and can resolve to the wrong element (or none).
75
+ *
76
+ * When `segment` is such a root-anchored positional chain inside a shadow root,
77
+ * we prefix it with {@link SHADOW_CHILD_CHAIN_PREFIX} so `resolveSelector`
78
+ * descends by strict direct-child matching instead of `querySelector`. An
79
+ * id/attribute-anchored segment is already resolvable tree-wide and is returned
80
+ * untouched. `isRootAnchored` is the caller's decision (each generator knows
81
+ * whether its own output reached the tree top vs. short-circuited on an id), so
82
+ * this stays correct regardless of what the steps contain.
83
+ */
84
+ export function anchorSegmentToShadowScope(segment, scope, isRootAnchored) {
85
+ if (segment && isRootAnchored && isShadowRoot(scope)) {
86
+ return "".concat(SHADOW_CHILD_CHAIN_PREFIX).concat(segment);
87
+ }
88
+ return segment;
89
+ }
90
+ /**
91
+ * Whether the legacy `cssPath` output for `el` is a root-anchored positional
92
+ * chain rather than one anchored by an id.
93
+ *
94
+ * `legacyCssPath` short-circuits at the first element — inclusive of `el` —
95
+ * that carries an `id`, emitting `tag#id > …` from there. If some element in
96
+ * `el`'s ancestor chain has an id the emitted selector is id-anchored (a plain,
97
+ * tree-wide-resolvable `querySelector`); if none does, the chain spans the tree
98
+ * top down to `el` via positional steps and must be marked for direct-child
99
+ * descent inside a shadow root. This walks the same `parentElement` chain the
100
+ * legacy walker does, so the two stay in lockstep.
101
+ */
102
+ export function legacyPathIsRootAnchored(el) {
103
+ for (var node = el; node !== null; node = node.parentElement) {
104
+ if (node.getAttribute('id')) {
105
+ return false;
106
+ }
107
+ }
108
+ return true;
109
+ }
110
+ /**
111
+ * The queryable root for `el`'s own tree: the enclosing `ShadowRoot` when `el`
112
+ * lives inside shadow DOM, otherwise the owner document. Both support
113
+ * `querySelectorAll`, so uniqueness checks can be scoped to the correct tree.
114
+ *
115
+ * Preserves the legacy default for non-shadow elements (`ownerDocument`), so
116
+ * nothing changes for the common flat-document case.
117
+ */
118
+ export function rootOf(el) {
119
+ var _a;
120
+ var root = el.getRootNode();
121
+ if (isShadowRoot(root)) {
122
+ return root;
123
+ }
124
+ return (_a = el.ownerDocument) !== null && _a !== void 0 ? _a : document;
125
+ }
126
+ /**
127
+ * The next element up, crossing shadow boundaries: `parentElement` within a
128
+ * tree, or the shadow host when `el` is at the top of a shadow tree. Returns
129
+ * `null` only at the document root (or a detached non-shadow root).
130
+ */
131
+ export function composedParent(el) {
132
+ if (el.parentElement) {
133
+ return el.parentElement;
134
+ }
135
+ var root = el.getRootNode();
136
+ if (isShadowRoot(root)) {
137
+ return root.host;
138
+ }
139
+ return null;
140
+ }
141
+ /**
142
+ * Defensive bound on composed-ancestor walks (host-chain iteration in
143
+ * `walkComposedAncestors` and `segmentWalk`). Far above any real shadow nesting
144
+ * (the resolver caps effective depth at `MAX_SHADOW_DOM_DEPTH`). See also
145
+ * {@link MAX_SHADOW_DOM_TRAVERSAL_NODES} for the DFS collection cap.
146
+ */
147
+ export var MAX_SHADOW_COMPOSED_WALK_ITERATIONS = 1024;
148
+ /**
149
+ * Defensive bound on node visits when collecting open shadow roots via DFS.
150
+ * Caps synchronous work inside MutationObserver callbacks on pathologically
151
+ * large trees. See also {@link MAX_SHADOW_COMPOSED_WALK_ITERATIONS} for the
152
+ * ancestor-walk cap.
153
+ */
154
+ export var MAX_SHADOW_DOM_TRAVERSAL_NODES = 50000;
155
+ /**
156
+ * Yield `start` and each ancestor up the composed tree. Within a tree the walk
157
+ * follows `parentElement`; at the top of a shadow tree it crosses to the host
158
+ * when `crossings < maxShadowDepth`. Yields every element including detached
159
+ * nodes at the top of their tree (where `parentElement` is null).
160
+ */
161
+ export function walkComposedAncestors(start, maxShadowDepth) {
162
+ var node, crossings, iterations, host;
163
+ return __generator(this, function (_a) {
164
+ switch (_a.label) {
165
+ case 0:
166
+ node = start;
167
+ crossings = 0;
168
+ iterations = 0;
169
+ _a.label = 1;
170
+ case 1:
171
+ if (!(node !== null && iterations < MAX_SHADOW_COMPOSED_WALK_ITERATIONS)) return [3 /*break*/, 3];
172
+ iterations += 1;
173
+ return [4 /*yield*/, node];
174
+ case 2:
175
+ _a.sent();
176
+ if (node.parentElement) {
177
+ node = node.parentElement;
178
+ return [3 /*break*/, 1];
179
+ }
180
+ if (crossings < maxShadowDepth && typeof node.getRootNode === 'function') {
181
+ host = composedParent(node);
182
+ if (host && host !== node) {
183
+ crossings += 1;
184
+ node = host;
185
+ return [3 /*break*/, 1];
186
+ }
187
+ }
188
+ return [3 /*break*/, 3];
189
+ case 3: return [2 /*return*/];
190
+ }
191
+ });
192
+ }
193
+ /**
194
+ * Collect the OPEN shadow roots within `root`'s composed subtree (its own light
195
+ * children and any nested shadow trees), each paired with how many shadow
196
+ * boundary crossings deep it sits relative to `root` (1-based). Bounded by
197
+ * `maxShadowDepth` crossings and by {@link MAX_SHADOW_DOM_TRAVERSAL_NODES}
198
+ * total nodes. Closed roots are invisible (`el.shadowRoot` is null) and skipped.
199
+ */
200
+ export function collectOpenShadowRoots(root, maxShadowDepth) {
201
+ var found = [];
202
+ if (maxShadowDepth <= 0) {
203
+ return found;
204
+ }
205
+ var stack = [[root, 0]];
206
+ var visited = 0;
207
+ while (stack.length && visited < MAX_SHADOW_DOM_TRAVERSAL_NODES) {
208
+ visited += 1;
209
+ var _a = __read(stack.pop(), 2), el = _a[0], depth = _a[1];
210
+ var shadowRoot = el.shadowRoot;
211
+ if (shadowRoot && depth + 1 <= maxShadowDepth) {
212
+ found.push({ root: shadowRoot, depth: depth + 1 });
213
+ var shadowChildren = shadowRoot.children;
214
+ for (var i = 0; i < shadowChildren.length; i++) {
215
+ stack.push([shadowChildren[i], depth + 1]);
216
+ }
217
+ }
218
+ var children = el.children;
219
+ for (var i = 0; i < children.length; i++) {
220
+ stack.push([children[i], depth]);
221
+ }
222
+ }
223
+ return found;
224
+ }
225
+ /**
226
+ * Split the outward composed walk from `el` into per-tree segments.
227
+ *
228
+ * Always walks fully out to the document so the outermost segment is
229
+ * document-rooted and therefore re-resolvable. `maxShadowDepth` caps how many
230
+ * shadow boundaries the *emitted* selector descends through: when the target is
231
+ * nested deeper than the budget, the innermost (over-budget) trees are dropped
232
+ * and the result is flagged `truncated` — the innermost kept segment then
233
+ * targets the shadow host at the depth limit (a best-effort, still-resolvable
234
+ * selector for an ancestor of the true target).
235
+ */
236
+ export function segmentWalk(el, maxShadowDepth) {
237
+ // Build innermost-first: one segment per tree, each `target` being the
238
+ // element to locate within that tree (the inner tree's host, or `el`).
239
+ var innermostFirst = [];
240
+ var node = el;
241
+ var iterations = 0;
242
+ while (node !== null && iterations < MAX_SHADOW_COMPOSED_WALK_ITERATIONS) {
243
+ iterations += 1;
244
+ var root = rootOf(node);
245
+ innermostFirst.push({ root: root, target: node });
246
+ var actualRoot = node.getRootNode();
247
+ if (!isShadowRoot(actualRoot)) {
248
+ break; // reached the document (or a detached non-shadow root)
249
+ }
250
+ node = actualRoot.host; // cross the boundary outward
251
+ }
252
+ var totalCrossings = innermostFirst.length - 1;
253
+ var truncated = false;
254
+ var kept = innermostFirst;
255
+ if (totalCrossings > maxShadowDepth) {
256
+ // Drop the innermost over-budget trees, keeping the outermost
257
+ // (maxShadowDepth + 1) trees. The new innermost kept segment's `target` is
258
+ // already the shadow host of the first dropped tree.
259
+ kept = innermostFirst.slice(totalCrossings - maxShadowDepth);
260
+ truncated = true;
261
+ }
262
+ // Reverse to outermost-first so the engine joins document → target order.
263
+ return { segments: kept.reverse(), truncated: truncated };
264
+ }
265
+ /**
266
+ * Re-resolve a generated selector back to its element, piercing open shadow
267
+ * roots at each boundary. The symmetric inverse of `engine.generate`.
268
+ *
269
+ * Returns `null` when any segment fails to match, or when a boundary crossing
270
+ * hits a *closed* shadow root (`host.shadowRoot === null`) — closed roots are
271
+ * opaque from outside, so such selectors cannot round-trip (a documented
272
+ * limitation). Never throws on a malformed segment.
273
+ *
274
+ * @param root Root to resolve against — almost always `document`.
275
+ * @param selector A selector produced by the engine (may contain boundary delimiters).
276
+ */
277
+ export function resolveSelector(root, selector) {
278
+ var segments = selector.split(SHADOW_BOUNDARY_DELIMITER);
279
+ var scope = root;
280
+ var found = null;
281
+ for (var i = 0; i < segments.length; i++) {
282
+ if (scope === null) {
283
+ return null; // previous segment's host had no (open) shadow root
284
+ }
285
+ var segment = segments[i].trim();
286
+ try {
287
+ found = resolveSegment(scope, segment);
288
+ }
289
+ catch (_a) {
290
+ return null; // malformed segment — never throw out of the resolver
291
+ }
292
+ if (found === null) {
293
+ return null;
294
+ }
295
+ if (i < segments.length - 1) {
296
+ // Descend into this host's shadow root for the next segment. `null` for a
297
+ // closed root ends resolution gracefully on the next iteration.
298
+ scope = found.shadowRoot;
299
+ }
300
+ }
301
+ return found;
302
+ }
303
+ /**
304
+ * Resolve a single (non-delimited) segment within `scope`.
305
+ *
306
+ * A segment marked with {@link SHADOW_CHILD_CHAIN_PREFIX} is a root-anchored
307
+ * "direct child from the root" chain (emitted by the fallback for a shadow-root
308
+ * scope, where `querySelector` can't express that anchoring). We strip the
309
+ * marker and resolve by strict direct-child descent. The marker is set
310
+ * explicitly by the generator, so this stays correct regardless of what the
311
+ * steps contain (tag, `:nth-of-type`, classes, …). Every other segment —
312
+ * id/attribute-anchored, or any document-scope segment — resolves via a plain
313
+ * `querySelector`.
314
+ */
315
+ function resolveSegment(scope, segment) {
316
+ if (segment.startsWith(SHADOW_CHILD_CHAIN_PREFIX)) {
317
+ return resolveChildChain(scope, segment.slice(SHADOW_CHILD_CHAIN_PREFIX.length));
318
+ }
319
+ return scope.querySelector(segment);
320
+ }
321
+ /**
322
+ * Resolve a `>`-joined chain as a strict direct-child descent from `scope`. At
323
+ * each level exactly one child matches the step (positional or otherwise via
324
+ * `matches()`), so the walk is deterministic. Returns `null` if any step matches
325
+ * no child.
326
+ */
327
+ function resolveChildChain(scope, chain) {
328
+ var e_1, _a;
329
+ var _b;
330
+ var steps = chain.split('>').map(function (s) { return s.trim(); });
331
+ var children = Array.from(scope.children);
332
+ var el = null;
333
+ var _loop_1 = function (step) {
334
+ el = (_b = children.find(function (child) { return child.matches(step); })) !== null && _b !== void 0 ? _b : null;
335
+ if (el === null) {
336
+ return { value: null };
337
+ }
338
+ children = Array.from(el.children);
339
+ };
340
+ try {
341
+ for (var steps_1 = __values(steps), steps_1_1 = steps_1.next(); !steps_1_1.done; steps_1_1 = steps_1.next()) {
342
+ var step = steps_1_1.value;
343
+ var state_1 = _loop_1(step);
344
+ if (typeof state_1 === "object")
345
+ return state_1.value;
346
+ }
347
+ }
348
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
349
+ finally {
350
+ try {
351
+ if (steps_1_1 && !steps_1_1.done && (_a = steps_1.return)) _a.call(steps_1);
352
+ }
353
+ finally { if (e_1) throw e_1.error; }
354
+ }
355
+ return el;
356
+ }
357
+ /**
358
+ * Build a single positional step for `el`: `tag:nth-of-type(n)`, indexed among
359
+ * its same-tag siblings. A parentless element emits the bare tag.
360
+ *
361
+ * `shadowAware` extends the parentless case: an element at the top of a shadow
362
+ * tree has a null `parentElement` but can still have same-tag peers among the
363
+ * `ShadowRoot`'s children, so it is indexed against those instead. When
364
+ * `shadowAware` is false every parentless element emits the bare tag.
365
+ */
366
+ export function positionalStep(el, shadowAware) {
367
+ var tag = el.tagName.toLowerCase();
368
+ var parent = el.parentElement;
369
+ if (parent === null) {
370
+ // Parentless means the document root (`<html>`), a detached element, or the
371
+ // top of a shadow tree. Only the last has siblings worth indexing, and only
372
+ // when the caller asks for shadow-aware stepping.
373
+ var root = el.getRootNode();
374
+ if (shadowAware && isShadowRoot(root)) {
375
+ return "".concat(tag, ":nth-of-type(").concat(sameTypeIndexAmong(el, root.children), ")");
376
+ }
377
+ return tag;
378
+ }
379
+ return "".concat(tag, ":nth-of-type(").concat(sameTypeIndexAmong(el, parent.children), ")");
380
+ }
381
+ /**
382
+ * 1-based index of `el` among same-tag siblings in `siblings`, mirroring
383
+ * `:nth-of-type`. Takes an `HTMLCollection` rather than a parent `Element` so a
384
+ * `ShadowRoot`'s children can be counted too — a `ShadowRoot` is not an
385
+ * `Element` but does expose `children`.
386
+ */
387
+ function sameTypeIndexAmong(el, siblings) {
388
+ var count = 0;
389
+ for (var i = 0; i < siblings.length; i++) {
390
+ var sibling = siblings[i];
391
+ if (sibling.tagName === el.tagName) {
392
+ count += 1;
393
+ if (sibling === el) {
394
+ return count;
395
+ }
396
+ }
397
+ }
398
+ // Defensive: element not found among its parent's children (shouldn't happen
399
+ // for a live element). Return 1 rather than throwing.
400
+ return 1;
401
+ }
402
+ //# sourceMappingURL=shadow.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shadow.js","sourceRoot":"","sources":["../../../src/helpers/shadow.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;;AAEH;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,IAAM,yBAAyB,GAAG,OAAO,CAAC;AAEjD;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,IAAM,yBAAyB,GAAG,WAAW,CAAC;AAErD,iFAAiF;AACjF,MAAM,UAAU,YAAY,CAAC,IAAU;IACrC,OAAO,OAAO,UAAU,KAAK,WAAW,IAAI,IAAI,YAAY,UAAU,CAAC;AACzE,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,0BAA0B,CAAC,OAAe,EAAE,KAAiB,EAAE,cAAuB;IACpG,IAAI,OAAO,IAAI,cAAc,IAAI,YAAY,CAAC,KAAa,CAAC,EAAE;QAC5D,OAAO,UAAG,yBAAyB,SAAG,OAAO,CAAE,CAAC;KACjD;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAA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,EAAE,CAAC,WAAW,EAAE,CAAC;QAC9B,IAAI,WAAW,IAAI,YAAY,CAAC,IAAI,CAAC,EAAE;YACrC,OAAO,UAAG,GAAG,0BAAgB,kBAAkB,CAAC,EAAE,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAG,CAAC;SACvE;QACD,OAAO,GAAG,CAAC;KACZ;IAED,OAAO,UAAG,GAAG,0BAAgB,kBAAkB,CAAC,EAAE,EAAE,MAAM,CAAC,QAAQ,CAAC,MAAG,CAAC;AAC1E,CAAC;AAED;;;;;GAKG;AACH,SAAS,kBAAkB,CAAC,EAAW,EAAE,QAAwB;IAC/D,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACxC,IAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC5B,IAAI,OAAO,CAAC,OAAO,KAAK,EAAE,CAAC,OAAO,EAAE;YAClC,KAAK,IAAI,CAAC,CAAC;YACX,IAAI,OAAO,KAAK,EAAE,EAAE;gBAClB,OAAO,KAAK,CAAC;aACd;SACF;KACF;IACD,6EAA6E;IAC7E,sDAAsD;IACtD,OAAO,CAAC,CAAC;AACX,CAAC","sourcesContent":["/**\n * Shadow-DOM traversal + re-resolution helpers.\n *\n * CSS selectors cannot pierce shadow boundaries: `document.querySelector` never\n * matches an element that lives inside a shadow root. So a selector that needs\n * to reach into shadow DOM can't be a single flat string — it has to be a\n * sequence of per-tree selectors, one per shadow tree, each resolvable within\n * its own root. We join those segments with `SHADOW_BOUNDARY_DELIMITER` and\n * re-resolve them with `resolveSelector`, descending one `shadowRoot` per\n * boundary.\n *\n * This module owns the primitives that knowledge lives in:\n *\n * - `composedParent` / `rootOf` — walk *out* of a shadow tree (the light-DOM\n * `parentElement` chain dead-ends at a shadow root; `getRootNode().host`\n * crosses the boundary).\n * - `segmentWalk` — split the outward walk into per-tree segments, honoring\n * the configured max shadow depth.\n * - `resolveSelector` — the symmetric inverse of the engine's output: split\n * on the delimiter and pierce open shadow roots to re-find the element.\n * - `walkComposedAncestors` — yield ancestors up the composed tree, honoring a\n * shadow-boundary crossing budget (shared by capture and selector layers).\n * - `collectOpenShadowRoots` — DFS collection of open shadow roots for\n * observer fan-out and deep `querySelectorAll`.\n * - `positionalStep` — a shadow-aware `tag:nth-of-type(n)` builder shared by\n * the orchestrator's descent and the fallback walker, so a shadow-root-top\n * element is still disambiguated against its `ShadowRoot` siblings.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\n/**\n * Delimiter that separates per-shadow-tree segments in a generated selector.\n *\n * Chosen to be visually distinct and trivially splittable, and to be invalid as\n * a real CSS combinator so it can never be confused with a `>` child combinator\n * the engine emits inside a single tree. Example output:\n *\n * `div#host >>> button:nth-of-type(1)`\n *\n * which `resolveSelector` re-resolves as\n * `document.querySelector('div#host').shadowRoot.querySelector('button:nth-of-type(1)')`.\n */\nexport const SHADOW_BOUNDARY_DELIMITER = ' >>> ';\n\n/**\n * Marker prefix for a \"direct child from the root\" chain inside a shadow tree.\n *\n * A positional chain scoped to a `ShadowRoot` (e.g. `div:nth-of-type(2)`) is not\n * anchored: `querySelector` matches it tree-wide, and `:scope` matches nothing\n * on a `ShadowRoot` (it isn't an element), so there is no CSS way to express\n * \"direct child of the root.\" The generator therefore prefixes such chains with\n * this marker and `resolveSelector` resolves them by strict direct-child descent\n * instead of `querySelector`. Keying off this explicit marker — rather than\n * sniffing a segment for the absence of `#`/`[` — keeps the round-trip correct\n * no matter what the steps contain (tag, `:nth-of-type`, classes, …).\n *\n * `:scope > ` is deliberately valid CSS syntax so a generated selector stays a\n * syntactically legal string; its meaning here is purely the descent signal.\n */\nexport const SHADOW_CHILD_CHAIN_PREFIX = ':scope > ';\n\n/** Narrowing guard that tolerates environments without a `ShadowRoot` global. */\nexport function isShadowRoot(node: Node): node is ShadowRoot {\n return typeof ShadowRoot !== 'undefined' && node instanceof ShadowRoot;\n}\n\n/**\n * Anchor a per-tree segment so it re-resolves within a `ShadowRoot`.\n *\n * Both selector algorithms (the strategy-chain fallback and the legacy Chromium\n * `cssPath`) can emit a segment that is only *positionally* specified — a chain\n * of `tag:nth-*` / class steps with no id or attribute to pin it. In the light\n * DOM the chain is implicitly anchored by the unique `<html>` root; inside a\n * shadow root there is no such root element, so `querySelector` matches the\n * chain tree-wide and can resolve to the wrong element (or none).\n *\n * When `segment` is such a root-anchored positional chain inside a shadow root,\n * we prefix it with {@link SHADOW_CHILD_CHAIN_PREFIX} so `resolveSelector`\n * descends by strict direct-child matching instead of `querySelector`. An\n * id/attribute-anchored segment is already resolvable tree-wide and is returned\n * untouched. `isRootAnchored` is the caller's decision (each generator knows\n * whether its own output reached the tree top vs. short-circuited on an id), so\n * this stays correct regardless of what the steps contain.\n */\nexport function anchorSegmentToShadowScope(segment: string, scope: ParentNode, isRootAnchored: boolean): string {\n if (segment && isRootAnchored && isShadowRoot(scope as Node)) {\n return `${SHADOW_CHILD_CHAIN_PREFIX}${segment}`;\n }\n return segment;\n}\n\n/**\n * Whether the legacy `cssPath` output for `el` is a root-anchored positional\n * chain rather than one anchored by an id.\n *\n * `legacyCssPath` short-circuits at the first element — inclusive of `el` —\n * that carries an `id`, emitting `tag#id > …` from there. If some element in\n * `el`'s ancestor chain has an id the emitted selector is id-anchored (a plain,\n * tree-wide-resolvable `querySelector`); if none does, the chain spans the tree\n * top down to `el` via positional steps and must be marked for direct-child\n * descent inside a shadow root. This walks the same `parentElement` chain the\n * legacy walker does, so the two stay in lockstep.\n */\nexport function legacyPathIsRootAnchored(el: Element): boolean {\n for (let node: Element | null = el; node !== null; node = node.parentElement) {\n if (node.getAttribute('id')) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * The queryable root for `el`'s own tree: the enclosing `ShadowRoot` when `el`\n * lives inside shadow DOM, otherwise the owner document. Both support\n * `querySelectorAll`, so uniqueness checks can be scoped to the correct tree.\n *\n * Preserves the legacy default for non-shadow elements (`ownerDocument`), so\n * nothing changes for the common flat-document case.\n */\nexport function rootOf(el: Element): ParentNode {\n const root = el.getRootNode();\n if (isShadowRoot(root)) {\n return root;\n }\n return el.ownerDocument ?? document;\n}\n\n/**\n * The next element up, crossing shadow boundaries: `parentElement` within a\n * tree, or the shadow host when `el` is at the top of a shadow tree. Returns\n * `null` only at the document root (or a detached non-shadow root).\n */\nexport function composedParent(el: Element): Element | null {\n if (el.parentElement) {\n return el.parentElement;\n }\n const root = el.getRootNode();\n if (isShadowRoot(root)) {\n return root.host;\n }\n return null;\n}\n\n/** One tree's contribution to a piercing selector. */\nexport interface TreeSegment {\n /** Queryable root for this tree — a `Document` or `ShadowRoot`. */\n root: ParentNode;\n /** Element to locate within `root`: the host of the next inner tree, or the original target. */\n target: Element;\n}\n\nexport interface SegmentWalkResult {\n /** Tree segments, outermost (document) first — the order they're joined for output. */\n segments: TreeSegment[];\n /**\n * True when the target sat deeper than `maxShadowDepth` allowed, so inner\n * trees were dropped and the innermost emitted segment targets the shadow\n * host at the depth limit rather than the original target.\n */\n truncated: boolean;\n}\n\n/**\n * Defensive bound on composed-ancestor walks (host-chain iteration in\n * `walkComposedAncestors` and `segmentWalk`). Far above any real shadow nesting\n * (the resolver caps effective depth at `MAX_SHADOW_DOM_DEPTH`). See also\n * {@link MAX_SHADOW_DOM_TRAVERSAL_NODES} for the DFS collection cap.\n */\nexport const MAX_SHADOW_COMPOSED_WALK_ITERATIONS = 1024;\n\n/**\n * Defensive bound on node visits when collecting open shadow roots via DFS.\n * Caps synchronous work inside MutationObserver callbacks on pathologically\n * large trees. See also {@link MAX_SHADOW_COMPOSED_WALK_ITERATIONS} for the\n * ancestor-walk cap.\n */\nexport const MAX_SHADOW_DOM_TRAVERSAL_NODES = 50000;\n\nexport interface OpenShadowRootEntry {\n root: ShadowRoot;\n /** 1-based shadow-boundary depth relative to the collection `root`. */\n depth: number;\n}\n\n/**\n * Yield `start` and each ancestor up the composed tree. Within a tree the walk\n * follows `parentElement`; at the top of a shadow tree it crosses to the host\n * when `crossings < maxShadowDepth`. Yields every element including detached\n * nodes at the top of their tree (where `parentElement` is null).\n */\nexport function* walkComposedAncestors(start: Element, maxShadowDepth: number): Generator<Element> {\n let node: Element | null = start;\n let crossings = 0;\n let iterations = 0;\n\n while (node !== null && iterations < MAX_SHADOW_COMPOSED_WALK_ITERATIONS) {\n iterations += 1;\n yield node;\n\n if (node.parentElement) {\n node = node.parentElement;\n continue;\n }\n if (crossings < maxShadowDepth && typeof node.getRootNode === 'function') {\n const host = composedParent(node);\n if (host && host !== node) {\n crossings += 1;\n node = host;\n continue;\n }\n }\n break;\n }\n}\n\n/**\n * Collect the OPEN shadow roots within `root`'s composed subtree (its own light\n * children and any nested shadow trees), each paired with how many shadow\n * boundary crossings deep it sits relative to `root` (1-based). Bounded by\n * `maxShadowDepth` crossings and by {@link MAX_SHADOW_DOM_TRAVERSAL_NODES}\n * total nodes. Closed roots are invisible (`el.shadowRoot` is null) and skipped.\n */\nexport function collectOpenShadowRoots(root: Element, maxShadowDepth: number): OpenShadowRootEntry[] {\n const found: OpenShadowRootEntry[] = [];\n if (maxShadowDepth <= 0) {\n return found;\n }\n const stack: Array<[Element, number]> = [[root, 0]];\n let visited = 0;\n while (stack.length && visited < MAX_SHADOW_DOM_TRAVERSAL_NODES) {\n visited += 1;\n const [el, depth] = stack.pop() as [Element, number];\n const shadowRoot = el.shadowRoot;\n if (shadowRoot && depth + 1 <= maxShadowDepth) {\n found.push({ root: shadowRoot, depth: depth + 1 });\n const shadowChildren = shadowRoot.children;\n for (let i = 0; i < shadowChildren.length; i++) {\n stack.push([shadowChildren[i], depth + 1]);\n }\n }\n const children = el.children;\n for (let i = 0; i < children.length; i++) {\n stack.push([children[i], depth]);\n }\n }\n return found;\n}\n\n/**\n * Split the outward composed walk from `el` into per-tree segments.\n *\n * Always walks fully out to the document so the outermost segment is\n * document-rooted and therefore re-resolvable. `maxShadowDepth` caps how many\n * shadow boundaries the *emitted* selector descends through: when the target is\n * nested deeper than the budget, the innermost (over-budget) trees are dropped\n * and the result is flagged `truncated` — the innermost kept segment then\n * targets the shadow host at the depth limit (a best-effort, still-resolvable\n * selector for an ancestor of the true target).\n */\nexport function segmentWalk(el: Element, maxShadowDepth: number): SegmentWalkResult {\n // Build innermost-first: one segment per tree, each `target` being the\n // element to locate within that tree (the inner tree's host, or `el`).\n const innermostFirst: TreeSegment[] = [];\n let node: Element | null = el;\n let iterations = 0;\n\n while (node !== null && iterations < MAX_SHADOW_COMPOSED_WALK_ITERATIONS) {\n iterations += 1;\n const root = rootOf(node);\n innermostFirst.push({ root, target: node });\n const actualRoot = node.getRootNode();\n if (!isShadowRoot(actualRoot)) {\n break; // reached the document (or a detached non-shadow root)\n }\n node = actualRoot.host; // cross the boundary outward\n }\n\n const totalCrossings = innermostFirst.length - 1;\n let truncated = false;\n let kept = innermostFirst;\n\n if (totalCrossings > maxShadowDepth) {\n // Drop the innermost over-budget trees, keeping the outermost\n // (maxShadowDepth + 1) trees. The new innermost kept segment's `target` is\n // already the shadow host of the first dropped tree.\n kept = innermostFirst.slice(totalCrossings - maxShadowDepth);\n truncated = true;\n }\n\n // Reverse to outermost-first so the engine joins document → target order.\n return { segments: kept.reverse(), truncated };\n}\n\n/**\n * Re-resolve a generated selector back to its element, piercing open shadow\n * roots at each boundary. The symmetric inverse of `engine.generate`.\n *\n * Returns `null` when any segment fails to match, or when a boundary crossing\n * hits a *closed* shadow root (`host.shadowRoot === null`) — closed roots are\n * opaque from outside, so such selectors cannot round-trip (a documented\n * limitation). Never throws on a malformed segment.\n *\n * @param root Root to resolve against — almost always `document`.\n * @param selector A selector produced by the engine (may contain boundary delimiters).\n */\nexport function resolveSelector(root: ParentNode, selector: string): Element | null {\n const segments = selector.split(SHADOW_BOUNDARY_DELIMITER);\n let scope: ParentNode | null = root;\n let found: Element | null = null;\n\n for (let i = 0; i < segments.length; i++) {\n if (scope === null) {\n return null; // previous segment's host had no (open) shadow root\n }\n const segment = segments[i].trim();\n try {\n found = resolveSegment(scope, segment);\n } catch {\n return null; // malformed segment — never throw out of the resolver\n }\n if (found === null) {\n return null;\n }\n if (i < segments.length - 1) {\n // Descend into this host's shadow root for the next segment. `null` for a\n // closed root ends resolution gracefully on the next iteration.\n scope = found.shadowRoot;\n }\n }\n\n return found;\n}\n\n/**\n * Resolve a single (non-delimited) segment within `scope`.\n *\n * A segment marked with {@link SHADOW_CHILD_CHAIN_PREFIX} is a root-anchored\n * \"direct child from the root\" chain (emitted by the fallback for a shadow-root\n * scope, where `querySelector` can't express that anchoring). We strip the\n * marker and resolve by strict direct-child descent. The marker is set\n * explicitly by the generator, so this stays correct regardless of what the\n * steps contain (tag, `:nth-of-type`, classes, …). Every other segment —\n * id/attribute-anchored, or any document-scope segment — resolves via a plain\n * `querySelector`.\n */\nfunction resolveSegment(scope: ParentNode, segment: string): Element | null {\n if (segment.startsWith(SHADOW_CHILD_CHAIN_PREFIX)) {\n return resolveChildChain(scope, segment.slice(SHADOW_CHILD_CHAIN_PREFIX.length));\n }\n return scope.querySelector(segment);\n}\n\n/**\n * Resolve a `>`-joined chain as a strict direct-child descent from `scope`. At\n * each level exactly one child matches the step (positional or otherwise via\n * `matches()`), so the walk is deterministic. Returns `null` if any step matches\n * no child.\n */\nfunction resolveChildChain(scope: ParentNode, chain: string): Element | null {\n const steps = chain.split('>').map((s) => s.trim());\n let children: Element[] = Array.from(scope.children);\n let el: Element | null = null;\n for (const step of steps) {\n el = children.find((child) => child.matches(step)) ?? null;\n if (el === null) {\n return null;\n }\n children = Array.from(el.children);\n }\n return el;\n}\n\n/**\n * Build a single positional step for `el`: `tag:nth-of-type(n)`, indexed among\n * its same-tag siblings. A parentless element emits the bare tag.\n *\n * `shadowAware` extends the parentless case: an element at the top of a shadow\n * tree has a null `parentElement` but can still have same-tag peers among the\n * `ShadowRoot`'s children, so it is indexed against those instead. When\n * `shadowAware` is false every parentless element emits the bare tag.\n */\nexport function positionalStep(el: Element, shadowAware: boolean): string {\n const tag = el.tagName.toLowerCase();\n const parent = el.parentElement;\n\n if (parent === null) {\n // Parentless means the document root (`<html>`), a detached element, or the\n // top of a shadow tree. Only the last has siblings worth indexing, and only\n // when the caller asks for shadow-aware stepping.\n const root = el.getRootNode();\n if (shadowAware && isShadowRoot(root)) {\n return `${tag}:nth-of-type(${sameTypeIndexAmong(el, root.children)})`;\n }\n return tag;\n }\n\n return `${tag}:nth-of-type(${sameTypeIndexAmong(el, parent.children)})`;\n}\n\n/**\n * 1-based index of `el` among same-tag siblings in `siblings`, mirroring\n * `:nth-of-type`. Takes an `HTMLCollection` rather than a parent `Element` so a\n * `ShadowRoot`'s children can be counted too — a `ShadowRoot` is not an\n * `Element` but does expose `children`.\n */\nfunction sameTypeIndexAmong(el: Element, siblings: HTMLCollection): number {\n let count = 0;\n for (let i = 0; i < siblings.length; i++) {\n const sibling = siblings[i];\n if (sibling.tagName === el.tagName) {\n count += 1;\n if (sibling === el) {\n return count;\n }\n }\n }\n // Defensive: element not found among its parent's children (shouldn't happen\n // for a live element). Return 1 rather than throwing.\n return 1;\n}\n"]}
@@ -13,18 +13,20 @@
13
13
  * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
14
14
  */
15
15
  export declare const PACKAGE_NAME = "@amplitude/element-selector";
16
- export type { Strategy, StrategyContext, ResolvedSelectorConfig, ElementSelectorRemoteConfig, ElementSelectorLogger, SelectorEngine, } from './types';
16
+ export type { Strategy, StrategyContext, ResolvedSelectorConfig, NormalizedSelectorConfig, ElementSelectorRemoteConfig, ElementSelectorLogger, SelectorEngine, } from './types';
17
17
  export { DEFAULT_AUTOGENERATED_ID_PATTERNS, compile as compileAutogeneratedIdPatterns, isStableId, } from './patterns/autogenerated-ids';
18
18
  export { DEFAULT_UNSTABLE_CLASS_PATTERNS, compile as compileUnstableClassPatterns, filterClasses, } from './patterns/unstable-classes';
19
19
  export { getStableId } from './helpers/get-stable-id';
20
20
  export { describeRelative } from './helpers/describe-relative';
21
+ export { resolveSelector, SHADOW_BOUNDARY_DELIMITER, composedParent, isShadowRoot, segmentWalk, walkComposedAncestors, collectOpenShadowRoots, MAX_SHADOW_COMPOSED_WALK_ITERATIONS, MAX_SHADOW_DOM_TRAVERSAL_NODES, } from './helpers/shadow';
22
+ export type { OpenShadowRootEntry } from './helpers/shadow';
21
23
  export { explicitTrackingAttribute } from './strategies/explicit-tracking-attribute';
22
24
  export { stableId as stableIdStrategy } from './strategies/stable-id';
23
25
  export { runOrchestrator, DEFAULT_STRATEGIES } from './orchestrator';
24
26
  export type { OrchestratorOptions } from './orchestrator';
25
27
  export { fallbackCssPath } from './fallback-css-path';
26
28
  export { legacyCssPath } from './legacy-css-path';
27
- export { resolveSelectorConfig, DEFAULT_RESOLVED_CONFIG } from './config/resolve-config';
29
+ export { resolveSelectorConfig, DEFAULT_RESOLVED_CONFIG, normalizeResolvedConfig } from './config/resolve-config';
28
30
  export { createSelectorEngine } from './engine';
29
31
  export type { CreateSelectorEngineOptions } from './engine';
30
32
  export { generateSelector } from './generate-selector';
@@ -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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kBAAkB,CAAC;AAC1B,YAAY,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAG5D,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,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAGlH,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
@@ -19,6 +19,14 @@ export { DEFAULT_UNSTABLE_CLASS_PATTERNS, compile as compileUnstableClassPattern
19
19
  // ===== Helpers =====
20
20
  export { getStableId } from './helpers/get-stable-id';
21
21
  export { describeRelative } from './helpers/describe-relative';
22
+ // ===== Shadow DOM =====
23
+ // `resolveSelector` is the symmetric inverse of `engine.generate` — consumers
24
+ // (autocapture, dashboard tagging UI, Chrome extension) MUST re-resolve a
25
+ // generated selector through this rather than `document.querySelector`, since a
26
+ // shadow-piercing selector is delimited and `querySelector` can't cross shadow
27
+ // boundaries. `composedParent` is exported for consumers that walk ancestors
28
+ // (e.g. closest-tracked-ancestor logic) across shadow boundaries.
29
+ export { resolveSelector, SHADOW_BOUNDARY_DELIMITER, composedParent, isShadowRoot, segmentWalk, walkComposedAncestors, collectOpenShadowRoots, MAX_SHADOW_COMPOSED_WALK_ITERATIONS, MAX_SHADOW_DOM_TRAVERSAL_NODES, } from './helpers/shadow';
22
30
  // ===== Strategies =====
23
31
  export { explicitTrackingAttribute } from './strategies/explicit-tracking-attribute';
24
32
  export { stableId as stableIdStrategy } from './strategies/stable-id';
@@ -38,7 +46,7 @@ export { fallbackCssPath } from './fallback-css-path';
38
46
  // downstream imports.
39
47
  export { legacyCssPath } from './legacy-css-path';
40
48
  // ===== Config resolver =====
41
- export { resolveSelectorConfig, DEFAULT_RESOLVED_CONFIG } from './config/resolve-config';
49
+ export { resolveSelectorConfig, DEFAULT_RESOLVED_CONFIG, normalizeResolvedConfig } from './config/resolve-config';
42
50
  // ===== Engine factory =====
43
51
  export { createSelectorEngine } from './engine';
44
52
  // ===== Top-level selector entry point =====
@@ -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,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"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,MAAM,CAAC,IAAM,YAAY,GAAG,6BAA6B,CAAC;AAa1D,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,8EAA8E;AAC9E,0EAA0E;AAC1E,gFAAgF;AAChF,+EAA+E;AAC/E,6EAA6E;AAC7E,kEAAkE;AAClE,OAAO,EACL,eAAe,EACf,yBAAyB,EACzB,cAAc,EACd,YAAY,EACZ,WAAW,EACX,qBAAqB,EACrB,sBAAsB,EACtB,mCAAmC,EACnC,8BAA8B,GAC/B,MAAM,kBAAkB,CAAC;AAG1B,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,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAElH,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 NormalizedSelectorConfig,\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// ===== Shadow DOM =====\n// `resolveSelector` is the symmetric inverse of `engine.generate` — consumers\n// (autocapture, dashboard tagging UI, Chrome extension) MUST re-resolve a\n// generated selector through this rather than `document.querySelector`, since a\n// shadow-piercing selector is delimited and `querySelector` can't cross shadow\n// boundaries. `composedParent` is exported for consumers that walk ancestors\n// (e.g. closest-tracked-ancestor logic) across shadow boundaries.\nexport {\n resolveSelector,\n SHADOW_BOUNDARY_DELIMITER,\n composedParent,\n isShadowRoot,\n segmentWalk,\n walkComposedAncestors,\n collectOpenShadowRoots,\n MAX_SHADOW_COMPOSED_WALK_ITERATIONS,\n MAX_SHADOW_DOM_TRAVERSAL_NODES,\n} from './helpers/shadow';\nexport type { OpenShadowRootEntry } from './helpers/shadow';\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, normalizeResolvedConfig } 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"]}
@@ -1 +1 @@
1
- {"version":3,"file":"orchestrator.d.ts","sourceRoot":"","sources":["../../src/orchestrator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,QAAQ,EAAmB,MAAM,SAAS,CAAC;AAKnG;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,EAAE,aAAa,CAAC,QAAQ,CAAiD,CAAC;AAEzG,MAAM,WAAW,mBAAmB;IAClC,0EAA0E;IAC1E,UAAU,CAAC,EAAE,aAAa,CAAC,QAAQ,CAAC,CAAC;IACrC,mGAAmG;IACnG,KAAK,CAAC,EAAE,UAAU,CAAC;IACnB;;;;OAIG;IACH,MAAM,CAAC,EAAE,qBAAqB,CAAC;CAChC;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,eAAe,CAC7B,EAAE,EAAE,OAAO,EACX,MAAM,EAAE,sBAAsB,EAC9B,OAAO,GAAE,mBAAwB,GAChC,MAAM,GAAG,IAAI,CAoCf"}
1
+ {"version":3,"file":"orchestrator.d.ts","sourceRoot":"","sources":["../../src/orchestrator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,QAAQ,EAAmB,MAAM,SAAS,CAAC;AAMnG;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,EAAE,aAAa,CAAC,QAAQ,CAAiD,CAAC;AAEzG,MAAM,WAAW,mBAAmB;IAClC,0EAA0E;IAC1E,UAAU,CAAC,EAAE,aAAa,CAAC,QAAQ,CAAC,CAAC;IACrC,mGAAmG;IACnG,KAAK,CAAC,EAAE,UAAU,CAAC;IACnB;;;;OAIG;IACH,MAAM,CAAC,EAAE,qBAAqB,CAAC;CAChC;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,eAAe,CAC7B,EAAE,EAAE,OAAO,EACX,MAAM,EAAE,sBAAsB,EAC9B,OAAO,GAAE,mBAAwB,GAChC,MAAM,GAAG,IAAI,CAqCf"}
@@ -23,6 +23,7 @@
23
23
  * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
24
24
  */
25
25
  import { __values } from "tslib";
26
+ import { normalizeResolvedConfig } from './config/resolve-config';
26
27
  import { explicitTrackingAttribute } from './strategies/explicit-tracking-attribute';
27
28
  import { stableId as stableIdStrategy } from './strategies/stable-id';
28
29
  import { describeRelative } from './helpers/describe-relative';
@@ -52,10 +53,11 @@ export function runOrchestrator(el, config, options) {
52
53
  var e_1, _a;
53
54
  var _b, _c, _d;
54
55
  if (options === void 0) { options = {}; }
56
+ var resolved = normalizeResolvedConfig(config);
55
57
  var strategies = (_b = options.strategies) !== null && _b !== void 0 ? _b : DEFAULT_STRATEGIES;
56
58
  var scope = (_d = (_c = options.scope) !== null && _c !== void 0 ? _c : el.ownerDocument) !== null && _d !== void 0 ? _d : document;
57
- var ctx = { scope: scope, config: config };
58
- var walk = collectWalk(el, config.maxAncestorWalkDepth);
59
+ var ctx = { scope: scope, config: resolved };
60
+ var walk = collectWalk(el, resolved.maxAncestorWalkDepth);
59
61
  try {
60
62
  // Two-pass: try strategy[0] across the whole walk, then strategy[1], etc.
61
63
  // This gives an "explicit anchor at any depth beats a structural anchor any
@@ -1 +1 @@
1
- {"version":3,"file":"orchestrator.js","sourceRoot":"","sources":["../../src/orchestrator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;;AAGH,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AACrF,OAAO,EAAE,QAAQ,IAAI,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAE/D;;;;GAIG;AACH,MAAM,CAAC,IAAM,kBAAkB,GAA4B,CAAC,yBAAyB,EAAE,gBAAgB,CAAC,CAAC;AAezG;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,eAAe,CAC7B,EAAW,EACX,MAA8B,EAC9B,OAAiC;;;IAAjC,wBAAA,EAAA,YAAiC;IAEjC,IAAM,UAAU,GAAG,MAAA,OAAO,CAAC,UAAU,mCAAI,kBAAkB,CAAC;IAC5D,IAAM,KAAK,GAAe,MAAA,MAAA,OAAO,CAAC,KAAK,mCAAI,EAAE,CAAC,aAAa,mCAAI,QAAQ,CAAC;IACxE,IAAM,GAAG,GAAoB,EAAE,KAAK,OAAA,EAAE,MAAM,QAAA,EAAE,CAAC;IAE/C,IAAM,IAAI,GAAG,WAAW,CAAC,EAAE,EAAE,MAAM,CAAC,oBAAoB,CAAC,CAAC;;QAE1D,0EAA0E;QAC1E,4EAA4E;QAC5E,6EAA6E;QAC7E,8BAA8B;QAC9B,KAAuB,IAAA,eAAA,SAAA,UAAU,CAAA,sCAAA,8DAAE;YAA9B,IAAM,QAAQ,uBAAA;YACjB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,C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B;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;;;;;GAUG;AACH,SAAS,aAAa,CACpB,KAAiB,EACjB,QAAgB,EAChB,EAAW,EACX,YAAoB,EACpB,MAA8B;IAE9B,IAAI,OAA4B,CAAC;IACjC,IAAI;QACF,OAAO,GAAG,KAAK,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC;KAC5C;IAAC,OAAO,CAAC,EAAE;QACV,IAAM,OAAO,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QAC3D,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,KAAK,CACX,kDAA0C,YAAY,+CAAmC,QAAQ,iBAAM,OAAO,MAAG,CAClH,CAAC;QACF,OAAO,KAAK,CAAC;KACd;IACD,OAAO,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;AACnD,CAAC","sourcesContent":["/**\n * Orchestrator — the entry point for the v1 element-selector algorithm.\n *\n * Given a click target, the orchestrator walks from the target up through its\n * ancestors and tries each registered strategy at each level. The first\n * strategy that returns a non-null candidate (and produces a selector that\n * resolves uniquely under the scope) wins; the trail of intermediate elements\n * between the anchor and the original target is then expressed as a positional\n * descent via `describeRelative`.\n *\n * Two-pass design: every ancestor is tried under the `explicitTrackingAttribute`\n * strategy first, then the entire walk repeats with `stableId`. This ordering\n * means an explicit anchor anywhere up the tree always beats a stable id deeper\n * down — the design doc describes this as the \"customer intent overrides\n * structural inference\" rule.\n *\n * The orchestrator does not own the fallback. When no strategy + walk produces\n * a unique selector, it returns `null` and the engine wires the\n * `fallback-css-path` path in instead. Keeping the fallback outside the\n * orchestrator keeps the strategy chain testable in isolation.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { ElementSelectorLogger, ResolvedSelectorConfig, Strategy, StrategyContext } from './types';\nimport { explicitTrackingAttribute } from './strategies/explicit-tracking-attribute';\nimport { stableId as stableIdStrategy } from './strategies/stable-id';\nimport { describeRelative } from './helpers/describe-relative';\n\n/**\n * Default strategy chain in priority order. Used by the engine factory when the\n * caller doesn't provide an explicit list. Exported for diagnostics — tests\n * import this so they don't have to duplicate the list.\n */\nexport const DEFAULT_STRATEGIES: ReadonlyArray<Strategy> = [explicitTrackingAttribute, stableIdStrategy];\n\nexport interface OrchestratorOptions {\n /** Strategy chain. Defaults to `DEFAULT_STRATEGIES`. Order = priority. */\n strategies?: ReadonlyArray<Strategy>;\n /** Document or shadow root used for uniqueness checks. Defaults to the target's owner document. */\n scope?: ParentNode;\n /**\n * Optional logger. When provided, the orchestrator emits a `debug` log if a\n * strategy produces a malformed selector that throws during the uniqueness\n * check — useful for diagnosing strategy bugs without crashing the engine.\n */\n logger?: ElementSelectorLogger;\n}\n\n/**\n * Try to produce a CSS selector for `el` using the strategy chain.\n *\n * Returns the composed selector string on success, or `null` if every strategy\n * declined at every walked ancestor. Callers (the engine) treat `null` as the\n * signal to invoke the fallback walker.\n *\n * Selector format on success:\n *\n * - Anchor only (target itself was an anchor): `<anchor-selector>`\n * - Anchor + trail (anchor was an ancestor): `<anchor-selector> > <descent>`\n *\n * Where `<anchor-selector>` is whatever the winning strategy returned for the\n * anchor element (e.g. `[data-amp-track-id=\"login-form\"]` or `div#hero`), and\n * `<descent>` is `describeRelative(anchor, trail)`.\n */\nexport function runOrchestrator(\n el: Element,\n config: ResolvedSelectorConfig,\n options: OrchestratorOptions = {},\n): string | null {\n const strategies = options.strategies ?? DEFAULT_STRATEGIES;\n const scope: ParentNode = options.scope ?? el.ownerDocument ?? document;\n const ctx: StrategyContext = { scope, config };\n\n const walk = collectWalk(el, config.maxAncestorWalkDepth);\n\n // Two-pass: try strategy[0] across the whole walk, then strategy[1], etc.\n // This gives an \"explicit anchor at any depth beats a structural anchor any\n // depth\" priority, which matches the design doc's \"customer intent overrides\n // structural inference\" rule.\n for (const strategy of strategies) {\n for (let i = 0; i < walk.length; i++) {\n const anchor = walk[i];\n const anchorSelector = strategy.try(anchor, ctx);\n if (anchorSelector === null) continue;\n\n // Anchor was the target itself — no descent needed.\n if (i === 0) {\n if (isUniqueMatch(scope, anchorSelector, el, strategy.name, options.logger)) {\n return anchorSelector;\n }\n continue;\n }\n\n // Anchor was an ancestor — descend back to the target through the trail.\n const trail = walk.slice(0, i).reverse();\n const descent = describeRelative(anchor, trail);\n const composed = `${anchorSelector} > ${descent}`;\n if (isUniqueMatch(scope, composed, el, strategy.name, options.logger)) {\n return composed;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Build the walk array `[target, parent, grandparent, ...]`, stopping at\n * `<html>` (or at the depth limit if configured). Excludes the document\n * element's parent (which is the Document node and not an Element).\n */\nfunction collectWalk(el: Element, maxDepth: number | undefined): Element[] {\n const walk: Element[] = [];\n let cursor: Element | null = el;\n while (cursor !== null) {\n walk.push(cursor);\n if (maxDepth !== undefined && walk.length > maxDepth) break;\n cursor = cursor.parentElement;\n }\n return walk;\n}\n\n/**\n * Check whether `selector` resolves to exactly `el` and no other element in\n * `scope`. The strategies themselves don't run uniqueness checks — that's the\n * orchestrator's job, so strategies stay pure transforms and stay testable in\n * isolation.\n *\n * When the selector is malformed (which is a strategy bug rather than user\n * input), we log at `debug` and return false rather than throwing. The log\n * lets engineers diagnose a misbehaving strategy without the engine taking\n * down whatever it's wired into.\n */\nfunction isUniqueMatch(\n scope: ParentNode,\n selector: string,\n el: Element,\n strategyName: string,\n logger?: ElementSelectorLogger,\n): boolean {\n let matches: NodeListOf<Element>;\n try {\n matches = scope.querySelectorAll(selector);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.debug(\n `@amplitude/element-selector: strategy \"${strategyName}\" emitted a malformed selector \"${selector}\" (${message})`,\n );\n return false;\n }\n return matches.length === 1 && matches[0] === el;\n}\n"]}
1
+ {"version":3,"file":"orchestrator.js","sourceRoot":"","sources":["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EACX,YAAoB,EACpB,MAA8B;IAE9B,IAAI,OAA4B,CAAC;IACjC,IAAI;QACF,OAAO,GAAG,KAAK,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC;KAC5C;IAAC,OAAO,CAAC,EAAE;QACV,IAAM,OAAO,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QAC3D,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,KAAK,CACX,kDAA0C,YAAY,+CAAmC,QAAQ,iBAAM,OAAO,MAAG,CAClH,CAAC;QACF,OAAO,KAAK,CAAC;KACd;IACD,OAAO,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;AACnD,CAAC","sourcesContent":["/**\n * Orchestrator — the entry point for the v1 element-selector algorithm.\n *\n * Given a click target, the orchestrator walks from the target up through its\n * ancestors and tries each registered strategy at each level. The first\n * strategy that returns a non-null candidate (and produces a selector that\n * resolves uniquely under the scope) wins; the trail of intermediate elements\n * between the anchor and the original target is then expressed as a positional\n * descent via `describeRelative`.\n *\n * Two-pass design: every ancestor is tried under the `explicitTrackingAttribute`\n * strategy first, then the entire walk repeats with `stableId`. This ordering\n * means an explicit anchor anywhere up the tree always beats a stable id deeper\n * down — the design doc describes this as the \"customer intent overrides\n * structural inference\" rule.\n *\n * The orchestrator does not own the fallback. When no strategy + walk produces\n * a unique selector, it returns `null` and the engine wires the\n * `fallback-css-path` path in instead. Keeping the fallback outside the\n * orchestrator keeps the strategy chain testable in isolation.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { ElementSelectorLogger, ResolvedSelectorConfig, Strategy, StrategyContext } from './types';\nimport { normalizeResolvedConfig } from './config/resolve-config';\nimport { explicitTrackingAttribute } from './strategies/explicit-tracking-attribute';\nimport { stableId as stableIdStrategy } from './strategies/stable-id';\nimport { describeRelative } from './helpers/describe-relative';\n\n/**\n * Default strategy chain in priority order. Used by the engine factory when the\n * caller doesn't provide an explicit list. Exported for diagnostics — tests\n * import this so they don't have to duplicate the list.\n */\nexport const DEFAULT_STRATEGIES: ReadonlyArray<Strategy> = [explicitTrackingAttribute, stableIdStrategy];\n\nexport interface OrchestratorOptions {\n /** Strategy chain. Defaults to `DEFAULT_STRATEGIES`. Order = priority. */\n strategies?: ReadonlyArray<Strategy>;\n /** Document or shadow root used for uniqueness checks. Defaults to the target's owner document. */\n scope?: ParentNode;\n /**\n * Optional logger. When provided, the orchestrator emits a `debug` log if a\n * strategy produces a malformed selector that throws during the uniqueness\n * check — useful for diagnosing strategy bugs without crashing the engine.\n */\n logger?: ElementSelectorLogger;\n}\n\n/**\n * Try to produce a CSS selector for `el` using the strategy chain.\n *\n * Returns the composed selector string on success, or `null` if every strategy\n * declined at every walked ancestor. Callers (the engine) treat `null` as the\n * signal to invoke the fallback walker.\n *\n * Selector format on success:\n *\n * - Anchor only (target itself was an anchor): `<anchor-selector>`\n * - Anchor + trail (anchor was an ancestor): `<anchor-selector> > <descent>`\n *\n * Where `<anchor-selector>` is whatever the winning strategy returned for the\n * anchor element (e.g. `[data-amp-track-id=\"login-form\"]` or `div#hero`), and\n * `<descent>` is `describeRelative(anchor, trail)`.\n */\nexport function runOrchestrator(\n el: Element,\n config: ResolvedSelectorConfig,\n options: OrchestratorOptions = {},\n): string | null {\n const resolved = normalizeResolvedConfig(config);\n const strategies = options.strategies ?? DEFAULT_STRATEGIES;\n const scope: ParentNode = options.scope ?? el.ownerDocument ?? document;\n const ctx: StrategyContext = { scope, config: resolved };\n\n const walk = collectWalk(el, resolved.maxAncestorWalkDepth);\n\n // Two-pass: try strategy[0] across the whole walk, then strategy[1], etc.\n // This gives an \"explicit anchor at any depth beats a structural anchor any\n // depth\" priority, which matches the design doc's \"customer intent overrides\n // structural inference\" rule.\n for (const strategy of strategies) {\n for (let i = 0; i < walk.length; i++) {\n const anchor = walk[i];\n const anchorSelector = strategy.try(anchor, ctx);\n if (anchorSelector === null) continue;\n\n // Anchor was the target itself — no descent needed.\n if (i === 0) {\n if (isUniqueMatch(scope, anchorSelector, el, strategy.name, options.logger)) {\n return anchorSelector;\n }\n continue;\n }\n\n // Anchor was an ancestor — descend back to the target through the trail.\n const trail = walk.slice(0, i).reverse();\n const descent = describeRelative(anchor, trail);\n const composed = `${anchorSelector} > ${descent}`;\n if (isUniqueMatch(scope, composed, el, strategy.name, options.logger)) {\n return composed;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Build the walk array `[target, parent, grandparent, ...]`, stopping at\n * `<html>` (or at the depth limit if configured). Excludes the document\n * element's parent (which is the Document node and not an Element).\n */\nfunction collectWalk(el: Element, maxDepth: number | undefined): Element[] {\n const walk: Element[] = [];\n let cursor: Element | null = el;\n while (cursor !== null) {\n walk.push(cursor);\n if (maxDepth !== undefined && walk.length > maxDepth) break;\n cursor = cursor.parentElement;\n }\n return walk;\n}\n\n/**\n * Check whether `selector` resolves to exactly `el` and no other element in\n * `scope`. The strategies themselves don't run uniqueness checks — that's the\n * orchestrator's job, so strategies stay pure transforms and stay testable in\n * isolation.\n *\n * When the selector is malformed (which is a strategy bug rather than user\n * input), we log at `debug` and return false rather than throwing. The log\n * lets engineers diagnose a misbehaving strategy without the engine taking\n * down whatever it's wired into.\n */\nfunction isUniqueMatch(\n scope: ParentNode,\n selector: string,\n el: Element,\n strategyName: string,\n logger?: ElementSelectorLogger,\n): boolean {\n let matches: NodeListOf<Element>;\n try {\n matches = scope.querySelectorAll(selector);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.debug(\n `@amplitude/element-selector: strategy \"${strategyName}\" emitted a malformed selector \"${selector}\" (${message})`,\n );\n return false;\n }\n return matches.length === 1 && matches[0] === el;\n}\n"]}