@amplitude/element-selector 0.2.0 → 0.3.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 +29 -3
  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
package/README.md CHANGED
@@ -56,9 +56,13 @@ const engine = createSelectorEngine(resolveSelectorConfig(remote, config.loggerP
56
56
  logger: config.loggerProvider,
57
57
  });
58
58
 
59
- config.remoteConfigClient.subscribe('elementSelector', 'all', (next) => {
60
- engine.updateConfig(resolveSelectorConfig(next, config.loggerProvider));
61
- });
59
+ config.remoteConfigClient.subscribe(
60
+ 'configs.analyticsSDK.browserSDK.autocapture.elementSelector',
61
+ 'all',
62
+ (next) => {
63
+ engine.updateConfig(resolveSelectorConfig(next, config.loggerProvider));
64
+ },
65
+ );
62
66
  ```
63
67
 
64
68
  ### Chrome extension visual tagger
@@ -126,6 +130,28 @@ The default list (used by the fallback) catches classes that look stable in name
126
130
 
127
131
  By default the walk runs all the way to `<html>`. Set this to a positive integer to cap the depth — useful for catastrophically deep DOMs where uniqueness checks could become expensive.
128
132
 
133
+ ## Shadow DOM
134
+
135
+ Shadow support is controlled independently from the selector engine kill switch via `shadowDomEnabled` and `maxShadowDomDepth` in remote config. Defaults: `shadowDomEnabled: false`, `maxShadowDomDepth: 1` (clamped to `[1, 10]`).
136
+
137
+ When enabled, `engine.generate` emits a delimited selector (` >>> ` between per-tree segments) that must be re-resolved with `resolveSelector` — plain `document.querySelector` cannot pierce shadow boundaries.
138
+
139
+ The autocapture plugin arms shadow support once per page via a latch (`ShadowGate`): the first remote-config delivery that enables it takes effect for the rest of the page load. A later delivery that disables shadow support does not turn it off until the next navigation.
140
+
141
+ **Full design doc (architecture, performance, late-root scenarios, DFS mitigations, follow-ups):** [`packages/plugin-autocapture-browser/SHADOW-DOM.md`](../plugin-autocapture-browser/SHADOW-DOM.md)
142
+
143
+ ### Rollout limitations (summary)
144
+
145
+ | Limitation | Impact |
146
+ |------------|--------|
147
+ | **Open shadow roots only** | Closed roots are opaque. `composedPath()` retargets events to the host; selectors cannot round-trip through closed roots. |
148
+ | **Latch-once per page** | Disabling `shadowDomEnabled` mid-session has no effect until the next full page load. First arming delivery also fixes `maxShadowDomDepth` for the page. |
149
+ | **Late `attachShadow`** | Roots attached to elements already in the DOM are not discovered by observers. Clicks still capture; mutation/exposure may miss. A global `attachShadow` patch is **not planned** — session replay and other libs already wrap the same API ([details](../plugin-autocapture-browser/SHADOW-DOM.md#performance)). |
150
+ | **Depth budget** | Targets deeper than `maxShadowDomDepth` produce a best-effort selector for the outermost in-budget shadow host. |
151
+ | **Traversal caps** | `MAX_SHADOW_COMPOSED_WALK_ITERATIONS` (ancestor walks) and `MAX_SHADOW_DOM_TRAVERSAL_NODES` (shadow-root collection DFS) bound synchronous work on pathological trees. |
152
+
153
+ Pre-rollout: run `e2e/shadow-dom.spec.ts` (CI) and `e2e/shadow-dom-perf.spec.ts` locally before enabling the flag for an org.
154
+
129
155
  ## Remote config
130
156
 
131
157
  The remote-config payload shape is defined in `src/types.ts` as `ElementSelectorRemoteConfig` and mirrored as a JSON Schema at `schema/element-selector-remote-config.schema.json` for the dashboard's remote-config editor and backend validation.
@@ -27,13 +27,24 @@
27
27
  * See the design doc:
28
28
  * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
29
29
  */
30
- import { ElementSelectorLogger, ElementSelectorRemoteConfig, ResolvedSelectorConfig } from '../types';
30
+ import { ElementSelectorLogger, ElementSelectorRemoteConfig, NormalizedSelectorConfig, ResolvedSelectorConfig } from '../types';
31
+ /** Shadow-DOM piercing is disabled by default, opt in via remote config. */
32
+ export declare const DEFAULT_SHADOW_DOM_ENABLED = false;
33
+ /** Default number of shadow-boundary crossings to traverse when piercing is on. */
34
+ export declare const DEFAULT_MAX_SHADOW_DOM_DEPTH = 1;
35
+ /**
36
+ * Internal hard cap on shadow-boundary crossings. Customer-supplied
37
+ * `maxShadowDomDepth` is clamped into `[1, MAX_SHADOW_DOM_DEPTH]` — a defensive
38
+ * bound on traversal cost (and on selector length) for pathologically nested
39
+ * shadow trees, mirroring how `maxAncestorWalkDepth` guards the light-DOM walk.
40
+ */
41
+ export declare const MAX_SHADOW_DOM_DEPTH = 10;
31
42
  /**
32
43
  * Built-in defaults applied when a field is absent from the remote payload.
33
44
  * Exported so consumers (and tests) can introspect the baseline without
34
45
  * round-tripping through `resolveSelectorConfig({})`.
35
46
  */
36
- export declare const DEFAULT_RESOLVED_CONFIG: Readonly<ResolvedSelectorConfig>;
47
+ export declare const DEFAULT_RESOLVED_CONFIG: Readonly<NormalizedSelectorConfig>;
37
48
  /**
38
49
  * Resolve a (possibly partial, possibly absent) remote-config payload into a
39
50
  * fully-typed runtime config. Always returns a fresh object; never mutates the
@@ -52,5 +63,12 @@ export declare const DEFAULT_RESOLVED_CONFIG: Readonly<ResolvedSelectorConfig>;
52
63
  * - `maxAncestorWalkDepth`: positive finite integer → use as-is. Anything
53
64
  * else (zero, negative, NaN, Infinity) → `undefined` (no limit).
54
65
  */
55
- export declare function resolveSelectorConfig(remote?: ElementSelectorRemoteConfig, logger?: ElementSelectorLogger): ResolvedSelectorConfig;
66
+ /**
67
+ * Apply shadow-field defaults to a resolved config object. Callers that
68
+ * construct a `ResolvedSelectorConfig` manually (dashboard, extension, tests)
69
+ * may omit the shadow fields added after the initial API ship; the engine
70
+ * normalizes through this before reading them.
71
+ */
72
+ export declare function normalizeResolvedConfig(config: ResolvedSelectorConfig): NormalizedSelectorConfig;
73
+ export declare function resolveSelectorConfig(remote?: ElementSelectorRemoteConfig, logger?: ElementSelectorLogger): NormalizedSelectorConfig;
56
74
  //# sourceMappingURL=resolve-config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-config.d.ts","sourceRoot":"","sources":["../../../src/config/resolve-config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,EAAE,qBAAqB,EAAE,2BAA2B,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAOtG;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,sBAAsB,CAQnE,CAAC;AAEH;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,CAAC,EAAE,2BAA2B,EACpC,MAAM,CAAC,EAAE,qBAAqB,GAC7B,sBAAsB,CA4BxB"}
1
+ {"version":3,"file":"resolve-config.d.ts","sourceRoot":"","sources":["../../../src/config/resolve-config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,EACL,qBAAqB,EACrB,2BAA2B,EAC3B,wBAAwB,EACxB,sBAAsB,EACvB,MAAM,UAAU,CAAC;AAOlB,4EAA4E;AAC5E,eAAO,MAAM,0BAA0B,QAAQ,CAAC;AAEhD,mFAAmF;AACnF,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAE9C;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,KAAK,CAAC;AAEvC;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,wBAAwB,CAUrE,CAAC;AAEH;;;;;;;;;;;;;;;;;GAiBG;AACH;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,sBAAsB,GAAG,wBAAwB,CAMhG;AAED,wBAAgB,qBAAqB,CACnC,MAAM,CAAC,EAAE,2BAA2B,EACpC,MAAM,CAAC,EAAE,qBAAqB,GAC7B,wBAAwB,CAkC1B"}
@@ -29,10 +29,21 @@
29
29
  * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
30
30
  */
31
31
  Object.defineProperty(exports, "__esModule", { value: true });
32
- exports.resolveSelectorConfig = exports.DEFAULT_RESOLVED_CONFIG = void 0;
32
+ exports.resolveSelectorConfig = exports.normalizeResolvedConfig = exports.DEFAULT_RESOLVED_CONFIG = exports.MAX_SHADOW_DOM_DEPTH = exports.DEFAULT_MAX_SHADOW_DOM_DEPTH = exports.DEFAULT_SHADOW_DOM_ENABLED = void 0;
33
33
  var tslib_1 = require("tslib");
34
34
  var autogenerated_ids_1 = require("../patterns/autogenerated-ids");
35
35
  var unstable_classes_1 = require("../patterns/unstable-classes");
36
+ /** Shadow-DOM piercing is disabled by default, opt in via remote config. */
37
+ exports.DEFAULT_SHADOW_DOM_ENABLED = false;
38
+ /** Default number of shadow-boundary crossings to traverse when piercing is on. */
39
+ exports.DEFAULT_MAX_SHADOW_DOM_DEPTH = 1;
40
+ /**
41
+ * Internal hard cap on shadow-boundary crossings. Customer-supplied
42
+ * `maxShadowDomDepth` is clamped into `[1, MAX_SHADOW_DOM_DEPTH]` — a defensive
43
+ * bound on traversal cost (and on selector length) for pathologically nested
44
+ * shadow trees, mirroring how `maxAncestorWalkDepth` guards the light-DOM walk.
45
+ */
46
+ exports.MAX_SHADOW_DOM_DEPTH = 10;
36
47
  /**
37
48
  * Built-in defaults applied when a field is absent from the remote payload.
38
49
  * Exported so consumers (and tests) can introspect the baseline without
@@ -46,6 +57,8 @@ exports.DEFAULT_RESOLVED_CONFIG = Object.freeze({
46
57
  autogeneratedIdPatterns: tslib_1.__spreadArray([], tslib_1.__read(autogenerated_ids_1.DEFAULT_AUTOGENERATED_ID_PATTERNS), false),
47
58
  unstableClassPatterns: tslib_1.__spreadArray([], tslib_1.__read(unstable_classes_1.DEFAULT_UNSTABLE_CLASS_PATTERNS), false),
48
59
  maxAncestorWalkDepth: undefined,
60
+ shadowDomEnabled: exports.DEFAULT_SHADOW_DOM_ENABLED,
61
+ maxShadowDomDepth: exports.DEFAULT_MAX_SHADOW_DOM_DEPTH,
49
62
  });
50
63
  /**
51
64
  * Resolve a (possibly partial, possibly absent) remote-config payload into a
@@ -65,6 +78,17 @@ exports.DEFAULT_RESOLVED_CONFIG = Object.freeze({
65
78
  * - `maxAncestorWalkDepth`: positive finite integer → use as-is. Anything
66
79
  * else (zero, negative, NaN, Infinity) → `undefined` (no limit).
67
80
  */
81
+ /**
82
+ * Apply shadow-field defaults to a resolved config object. Callers that
83
+ * construct a `ResolvedSelectorConfig` manually (dashboard, extension, tests)
84
+ * may omit the shadow fields added after the initial API ship; the engine
85
+ * normalizes through this before reading them.
86
+ */
87
+ function normalizeResolvedConfig(config) {
88
+ var _a;
89
+ return tslib_1.__assign(tslib_1.__assign({}, config), { shadowDomEnabled: (_a = config.shadowDomEnabled) !== null && _a !== void 0 ? _a : exports.DEFAULT_SHADOW_DOM_ENABLED, maxShadowDomDepth: clampShadowDepth(config.maxShadowDomDepth) });
90
+ }
91
+ exports.normalizeResolvedConfig = normalizeResolvedConfig;
68
92
  function resolveSelectorConfig(remote, logger) {
69
93
  if (!remote) {
70
94
  // Return a fresh copy so callers can safely mutate the result without
@@ -85,7 +109,11 @@ function resolveSelectorConfig(remote, logger) {
85
109
  resolved.unstableClassPatterns = (0, unstable_classes_1.compile)(remote.unstableClassPatterns, logger);
86
110
  }
87
111
  resolved.maxAncestorWalkDepth = clampDepth(remote.maxAncestorWalkDepth);
88
- return resolved;
112
+ if (typeof remote.shadowDomEnabled === 'boolean') {
113
+ resolved.shadowDomEnabled = remote.shadowDomEnabled;
114
+ }
115
+ resolved.maxShadowDomDepth = clampShadowDepth(remote.maxShadowDomDepth);
116
+ return normalizeResolvedConfig(resolved);
89
117
  }
90
118
  exports.resolveSelectorConfig = resolveSelectorConfig;
91
119
  /**
@@ -102,6 +130,21 @@ function clampDepth(depth) {
102
130
  return undefined;
103
131
  return Math.floor(depth);
104
132
  }
133
+ /**
134
+ * Coerce a remote-supplied shadow depth into the runtime contract:
135
+ * - undefined / non-number / NaN / Infinity → default (1)
136
+ * - otherwise → floor()'d, then clamped into [1, MAX_SHADOW_DOM_DEPTH]
137
+ *
138
+ * Unlike `maxAncestorWalkDepth`, this never resolves to "no limit" — shadow
139
+ * piercing is always bounded by the hard cap to keep traversal and selector
140
+ * length under control.
141
+ */
142
+ function clampShadowDepth(depth) {
143
+ if (typeof depth !== 'number' || !Number.isFinite(depth)) {
144
+ return exports.DEFAULT_MAX_SHADOW_DOM_DEPTH;
145
+ }
146
+ return Math.min(Math.max(Math.floor(depth), 1), exports.MAX_SHADOW_DOM_DEPTH);
147
+ }
105
148
  function cloneDefaults() {
106
149
  return {
107
150
  enabled: exports.DEFAULT_RESOLVED_CONFIG.enabled,
@@ -109,6 +152,8 @@ function cloneDefaults() {
109
152
  autogeneratedIdPatterns: tslib_1.__spreadArray([], tslib_1.__read(exports.DEFAULT_RESOLVED_CONFIG.autogeneratedIdPatterns), false),
110
153
  unstableClassPatterns: tslib_1.__spreadArray([], tslib_1.__read(exports.DEFAULT_RESOLVED_CONFIG.unstableClassPatterns), false),
111
154
  maxAncestorWalkDepth: exports.DEFAULT_RESOLVED_CONFIG.maxAncestorWalkDepth,
155
+ shadowDomEnabled: exports.DEFAULT_RESOLVED_CONFIG.shadowDomEnabled,
156
+ maxShadowDomDepth: exports.DEFAULT_RESOLVED_CONFIG.maxShadowDomDepth,
112
157
  };
113
158
  }
114
159
  //# sourceMappingURL=resolve-config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-config.js","sourceRoot":"","sources":["../../../src/config/resolve-config.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;;;;AAGH,mEAGuC;AACvC,iEAAwH;AAExH;;;;GAIG;AACU,QAAA,uBAAuB,GAAqC,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AC,KAAyB;IAC3C,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IAChD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAC9C,IAAI,KAAK,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC;IACjC,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAC3B,CAAC;AAED,SAAS,aAAa;IACpB,OAAO;QACL,OAAO,EAAE,+BAAuB,CAAC,OAAO;QACxC,yBAAyB,EAAE,+BAAuB,CAAC,yBAAyB;QAC5E,uBAAuB,2CAAM,+BAAuB,CAAC,uBAAuB,SAAC;QAC7E,qBAAqB,2CAAM,+BAAuB,CAAC,qBAAqB,SAAC;QACzE,oBAAoB,EAAE,+BAAuB,CAAC,oBAAoB;KACnE,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Config resolver — collapses the optional, string-based remote-config payload\n * into the fully-typed `ResolvedSelectorConfig` that strategies, orchestrator,\n * and fallback consume at runtime.\n *\n * Responsibilities:\n *\n * 1. Apply defaults for every field. The defaults (enabled = false,\n * attribute = `data-amp-track-id`, built-in pattern packs) match the\n * design doc's \"v1 defaults\" table.\n *\n * 2. Compile regex strings into `RegExp[]`. Bad regexes are skipped by the\n * underlying `compile` helpers; when a logger is provided it surfaces a\n * warning for each invalid pattern so customers can diagnose why their\n * override isn't taking effect.\n *\n * 3. Treat customer-provided pattern lists as a **full replacement** of the\n * defaults — not a merge. This matches the design doc: \"The customer\n * sees the defaults in the remote-config UI and may add or remove\n * patterns as needed.\" If a customer provides `autogeneratedIdPatterns:\n * []`, that's their explicit request to disable autogen filtering.\n *\n * 4. Clamp `maxAncestorWalkDepth` into a sane range. Negative / zero values\n * are coerced to `undefined` (treat as \"no limit\") rather than throwing —\n * remote config should never crash the engine.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { ElementSelectorLogger, ElementSelectorRemoteConfig, ResolvedSelectorConfig } from '../types';\nimport {\n DEFAULT_AUTOGENERATED_ID_PATTERNS,\n compile as compileAutogeneratedIdPatterns,\n} from '../patterns/autogenerated-ids';\nimport { DEFAULT_UNSTABLE_CLASS_PATTERNS, compile as compileUnstableClassPatterns } from '../patterns/unstable-classes';\n\n/**\n * Built-in defaults applied when a field is absent from the remote payload.\n * Exported so consumers (and tests) can introspect the baseline without\n * round-tripping through `resolveSelectorConfig({})`.\n */\nexport const DEFAULT_RESOLVED_CONFIG: Readonly<ResolvedSelectorConfig> = Object.freeze({\n // v1 ships disabled — autocapture only flips to the new engine when the\n // remote config explicitly enables it for an org.\n enabled: false,\n explicitTrackingAttribute: 'data-amp-track-id',\n autogeneratedIdPatterns: [...DEFAULT_AUTOGENERATED_ID_PATTERNS],\n unstableClassPatterns: [...DEFAULT_UNSTABLE_CLASS_PATTERNS],\n maxAncestorWalkDepth: undefined,\n});\n\n/**\n * Resolve a (possibly partial, possibly absent) remote-config payload into a\n * fully-typed runtime config. Always returns a fresh object; never mutates the\n * input.\n *\n * Field-by-field semantics:\n *\n * - `enabled`: defaults to false (the engine ships dormant). Any boolean in\n * the payload — including `false` — wins.\n * - `explicitTrackingAttribute`: defaults to `data-amp-track-id`. Empty\n * strings are rejected (they'd make the strategy match every element);\n * fall back to the default in that case.\n * - `autogeneratedIdPatterns` / `unstableClassPatterns`: present → compile\n * the strings (skipping invalid regexes), use the compiled list as-is.\n * Absent → use the defaults.\n * - `maxAncestorWalkDepth`: positive finite integer → use as-is. Anything\n * else (zero, negative, NaN, Infinity) → `undefined` (no limit).\n */\nexport function resolveSelectorConfig(\n remote?: ElementSelectorRemoteConfig,\n logger?: ElementSelectorLogger,\n): ResolvedSelectorConfig {\n if (!remote) {\n // Return a fresh copy so callers can safely mutate the result without\n // poisoning the frozen defaults singleton.\n return cloneDefaults();\n }\n\n const resolved: ResolvedSelectorConfig = cloneDefaults();\n\n if (typeof remote.enabled === 'boolean') {\n resolved.enabled = remote.enabled;\n }\n\n if (typeof remote.explicitTrackingAttribute === 'string' && remote.explicitTrackingAttribute !== '') {\n resolved.explicitTrackingAttribute = remote.explicitTrackingAttribute;\n }\n\n if (Array.isArray(remote.autogeneratedIdPatterns)) {\n resolved.autogeneratedIdPatterns = compileAutogeneratedIdPatterns(remote.autogeneratedIdPatterns, logger);\n }\n\n if (Array.isArray(remote.unstableClassPatterns)) {\n resolved.unstableClassPatterns = compileUnstableClassPatterns(remote.unstableClassPatterns, logger);\n }\n\n resolved.maxAncestorWalkDepth = clampDepth(remote.maxAncestorWalkDepth);\n\n return resolved;\n}\n\n/**\n * Coerce a remote-supplied depth value into the runtime contract:\n * - undefined / non-number / NaN / Infinity / <= 0 → undefined (no limit)\n * - positive finite number → floor()'d integer\n */\nfunction clampDepth(depth: number | undefined): number | undefined {\n if (typeof depth !== 'number') return undefined;\n if (!Number.isFinite(depth)) return undefined;\n if (depth <= 0) return undefined;\n return Math.floor(depth);\n}\n\nfunction cloneDefaults(): ResolvedSelectorConfig {\n return {\n enabled: DEFAULT_RESOLVED_CONFIG.enabled,\n explicitTrackingAttribute: DEFAULT_RESOLVED_CONFIG.explicitTrackingAttribute,\n autogeneratedIdPatterns: [...DEFAULT_RESOLVED_CONFIG.autogeneratedIdPatterns],\n unstableClassPatterns: [...DEFAULT_RESOLVED_CONFIG.unstableClassPatterns],\n maxAncestorWalkDepth: DEFAULT_RESOLVED_CONFIG.maxAncestorWalkDepth,\n };\n}\n"]}
1
+ {"version":3,"file":"resolve-config.js","sourceRoot":"","sources":["../../../src/config/resolve-config.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;;;;AAQH,mEAGuC;AACvC,iEAAwH;AAExH,4EAA4E;AAC/D,QAAA,0BAA0B,GAAG,KAAK,CAAC;AAEhD,mFAAmF;AACtE,QAAA,4BAA4B,GAAG,CAAC,CAAC;AAE9C;;;;;GAKG;AACU,QAAA,oBAAoB,GAAG,EA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C,yBAAyB,EAAE,+BAAuB,CAAC,yBAAyB;QAC5E,uBAAuB,2CAAM,+BAAuB,CAAC,uBAAuB,SAAC;QAC7E,qBAAqB,2CAAM,+BAAuB,CAAC,qBAAqB,SAAC;QACzE,oBAAoB,EAAE,+BAAuB,CAAC,oBAAoB;QAClE,gBAAgB,EAAE,+BAAuB,CAAC,gBAAgB;QAC1D,iBAAiB,EAAE,+BAAuB,CAAC,iBAAiB;KAC7D,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Config resolver — collapses the optional, string-based remote-config payload\n * into the fully-typed `ResolvedSelectorConfig` that strategies, orchestrator,\n * and fallback consume at runtime.\n *\n * Responsibilities:\n *\n * 1. Apply defaults for every field. The defaults (enabled = false,\n * attribute = `data-amp-track-id`, built-in pattern packs) match the\n * design doc's \"v1 defaults\" table.\n *\n * 2. Compile regex strings into `RegExp[]`. Bad regexes are skipped by the\n * underlying `compile` helpers; when a logger is provided it surfaces a\n * warning for each invalid pattern so customers can diagnose why their\n * override isn't taking effect.\n *\n * 3. Treat customer-provided pattern lists as a **full replacement** of the\n * defaults — not a merge. This matches the design doc: \"The customer\n * sees the defaults in the remote-config UI and may add or remove\n * patterns as needed.\" If a customer provides `autogeneratedIdPatterns:\n * []`, that's their explicit request to disable autogen filtering.\n *\n * 4. Clamp `maxAncestorWalkDepth` into a sane range. Negative / zero values\n * are coerced to `undefined` (treat as \"no limit\") rather than throwing —\n * remote config should never crash the engine.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport {\n ElementSelectorLogger,\n ElementSelectorRemoteConfig,\n NormalizedSelectorConfig,\n ResolvedSelectorConfig,\n} from '../types';\nimport {\n DEFAULT_AUTOGENERATED_ID_PATTERNS,\n compile as compileAutogeneratedIdPatterns,\n} from '../patterns/autogenerated-ids';\nimport { DEFAULT_UNSTABLE_CLASS_PATTERNS, compile as compileUnstableClassPatterns } from '../patterns/unstable-classes';\n\n/** Shadow-DOM piercing is disabled by default, opt in via remote config. */\nexport const DEFAULT_SHADOW_DOM_ENABLED = false;\n\n/** Default number of shadow-boundary crossings to traverse when piercing is on. */\nexport const DEFAULT_MAX_SHADOW_DOM_DEPTH = 1;\n\n/**\n * Internal hard cap on shadow-boundary crossings. Customer-supplied\n * `maxShadowDomDepth` is clamped into `[1, MAX_SHADOW_DOM_DEPTH]` — a defensive\n * bound on traversal cost (and on selector length) for pathologically nested\n * shadow trees, mirroring how `maxAncestorWalkDepth` guards the light-DOM walk.\n */\nexport const MAX_SHADOW_DOM_DEPTH = 10;\n\n/**\n * Built-in defaults applied when a field is absent from the remote payload.\n * Exported so consumers (and tests) can introspect the baseline without\n * round-tripping through `resolveSelectorConfig({})`.\n */\nexport const DEFAULT_RESOLVED_CONFIG: Readonly<NormalizedSelectorConfig> = Object.freeze({\n // v1 ships disabled — autocapture only flips to the new engine when the\n // remote config explicitly enables it for an org.\n enabled: false,\n explicitTrackingAttribute: 'data-amp-track-id',\n autogeneratedIdPatterns: [...DEFAULT_AUTOGENERATED_ID_PATTERNS],\n unstableClassPatterns: [...DEFAULT_UNSTABLE_CLASS_PATTERNS],\n maxAncestorWalkDepth: undefined,\n shadowDomEnabled: DEFAULT_SHADOW_DOM_ENABLED,\n maxShadowDomDepth: DEFAULT_MAX_SHADOW_DOM_DEPTH,\n});\n\n/**\n * Resolve a (possibly partial, possibly absent) remote-config payload into a\n * fully-typed runtime config. Always returns a fresh object; never mutates the\n * input.\n *\n * Field-by-field semantics:\n *\n * - `enabled`: defaults to false (the engine ships dormant). Any boolean in\n * the payload — including `false` — wins.\n * - `explicitTrackingAttribute`: defaults to `data-amp-track-id`. Empty\n * strings are rejected (they'd make the strategy match every element);\n * fall back to the default in that case.\n * - `autogeneratedIdPatterns` / `unstableClassPatterns`: present → compile\n * the strings (skipping invalid regexes), use the compiled list as-is.\n * Absent → use the defaults.\n * - `maxAncestorWalkDepth`: positive finite integer → use as-is. Anything\n * else (zero, negative, NaN, Infinity) → `undefined` (no limit).\n */\n/**\n * Apply shadow-field defaults to a resolved config object. Callers that\n * construct a `ResolvedSelectorConfig` manually (dashboard, extension, tests)\n * may omit the shadow fields added after the initial API ship; the engine\n * normalizes through this before reading them.\n */\nexport function normalizeResolvedConfig(config: ResolvedSelectorConfig): NormalizedSelectorConfig {\n return {\n ...config,\n shadowDomEnabled: config.shadowDomEnabled ?? DEFAULT_SHADOW_DOM_ENABLED,\n maxShadowDomDepth: clampShadowDepth(config.maxShadowDomDepth),\n };\n}\n\nexport function resolveSelectorConfig(\n remote?: ElementSelectorRemoteConfig,\n logger?: ElementSelectorLogger,\n): NormalizedSelectorConfig {\n if (!remote) {\n // Return a fresh copy so callers can safely mutate the result without\n // poisoning the frozen defaults singleton.\n return cloneDefaults();\n }\n\n const resolved: NormalizedSelectorConfig = cloneDefaults();\n\n if (typeof remote.enabled === 'boolean') {\n resolved.enabled = remote.enabled;\n }\n\n if (typeof remote.explicitTrackingAttribute === 'string' && remote.explicitTrackingAttribute !== '') {\n resolved.explicitTrackingAttribute = remote.explicitTrackingAttribute;\n }\n\n if (Array.isArray(remote.autogeneratedIdPatterns)) {\n resolved.autogeneratedIdPatterns = compileAutogeneratedIdPatterns(remote.autogeneratedIdPatterns, logger);\n }\n\n if (Array.isArray(remote.unstableClassPatterns)) {\n resolved.unstableClassPatterns = compileUnstableClassPatterns(remote.unstableClassPatterns, logger);\n }\n\n resolved.maxAncestorWalkDepth = clampDepth(remote.maxAncestorWalkDepth);\n\n if (typeof remote.shadowDomEnabled === 'boolean') {\n resolved.shadowDomEnabled = remote.shadowDomEnabled;\n }\n\n resolved.maxShadowDomDepth = clampShadowDepth(remote.maxShadowDomDepth);\n\n return normalizeResolvedConfig(resolved);\n}\n\n/**\n * Coerce a remote-supplied depth value into the runtime contract:\n * - undefined / non-number / NaN / Infinity / <= 0 → undefined (no limit)\n * - positive finite number → floor()'d integer\n */\nfunction clampDepth(depth: number | undefined): number | undefined {\n if (typeof depth !== 'number') return undefined;\n if (!Number.isFinite(depth)) return undefined;\n if (depth <= 0) return undefined;\n return Math.floor(depth);\n}\n\n/**\n * Coerce a remote-supplied shadow depth into the runtime contract:\n * - undefined / non-number / NaN / Infinity → default (1)\n * - otherwise → floor()'d, then clamped into [1, MAX_SHADOW_DOM_DEPTH]\n *\n * Unlike `maxAncestorWalkDepth`, this never resolves to \"no limit\" — shadow\n * piercing is always bounded by the hard cap to keep traversal and selector\n * length under control.\n */\nfunction clampShadowDepth(depth: number | undefined): number {\n if (typeof depth !== 'number' || !Number.isFinite(depth)) {\n return DEFAULT_MAX_SHADOW_DOM_DEPTH;\n }\n return Math.min(Math.max(Math.floor(depth), 1), MAX_SHADOW_DOM_DEPTH);\n}\n\nfunction cloneDefaults(): NormalizedSelectorConfig {\n return {\n enabled: DEFAULT_RESOLVED_CONFIG.enabled,\n explicitTrackingAttribute: DEFAULT_RESOLVED_CONFIG.explicitTrackingAttribute,\n autogeneratedIdPatterns: [...DEFAULT_RESOLVED_CONFIG.autogeneratedIdPatterns],\n unstableClassPatterns: [...DEFAULT_RESOLVED_CONFIG.unstableClassPatterns],\n maxAncestorWalkDepth: DEFAULT_RESOLVED_CONFIG.maxAncestorWalkDepth,\n shadowDomEnabled: DEFAULT_RESOLVED_CONFIG.shadowDomEnabled,\n maxShadowDomDepth: DEFAULT_RESOLVED_CONFIG.maxShadowDomDepth,\n };\n}\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;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,CAqEhB"}
1
+ {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAGH,OAAO,EAAE,qBAAqB,EAA4B,sBAAsB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClH,OAAO,EAAmB,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAkBtE,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,CAwGhB"}
package/lib/cjs/engine.js CHANGED
@@ -29,9 +29,11 @@
29
29
  Object.defineProperty(exports, "__esModule", { value: true });
30
30
  exports.createSelectorEngine = void 0;
31
31
  var tslib_1 = require("tslib");
32
+ var resolve_config_1 = require("./config/resolve-config");
32
33
  var orchestrator_1 = require("./orchestrator");
33
34
  var fallback_css_path_1 = require("./fallback-css-path");
34
35
  var legacy_css_path_1 = require("./legacy-css-path");
36
+ var shadow_1 = require("./helpers/shadow");
35
37
  /**
36
38
  * Build a `SelectorEngine` bound to the supplied config.
37
39
  *
@@ -43,42 +45,74 @@ var legacy_css_path_1 = require("./legacy-css-path");
43
45
  */
44
46
  function createSelectorEngine(initialConfig, options) {
45
47
  if (options === void 0) { options = {}; }
46
- var config = initialConfig;
48
+ var config = (0, resolve_config_1.normalizeResolvedConfig)(initialConfig);
47
49
  var subscribers = new Set();
48
50
  var logger = options.logger;
49
- var orchestratorOptions = {
50
- strategies: options.strategies,
51
- scope: options.scope,
52
- logger: logger,
51
+ // ── Per-tree algorithms: the `config.enabled` axis ────────────────────────
52
+ /**
53
+ * LEGACY algorithm
54
+ * The algorithm has no notion of scope.
55
+ */
56
+ var legacyTree = function (target) { return (0, legacy_css_path_1.safeLegacyCssPath)(target, logger); };
57
+ /**
58
+ * ENGINE algorithm: the strategy chain, then the hardened fallback, both
59
+ * scoped to the tree's own root.
60
+ */
61
+ var engineTree = function (target, scope) {
62
+ var _a;
63
+ return (_a = (0, orchestrator_1.runOrchestrator)(target, config, { strategies: options.strategies, scope: scope, logger: logger })) !== null && _a !== void 0 ? _a : (0, fallback_css_path_1.fallbackCssPath)(target, config, { scope: scope });
53
64
  };
65
+ // ── Shadow-aware variant: reachable ONLY from `pierce` ────────────────────
66
+ /**
67
+ * `legacyCssPath` ignores scope, so for a shadow-tree element with no id
68
+ * ancestor it emits an unanchored positional chain that `querySelector` would
69
+ * match tree-wide. Anchor such a chain so `resolveSelector` descends by direct
70
+ * child instead. `engineTree` needs no counterpart — `fallbackCssPath` anchors
71
+ * its own output from the scope it is handed.
72
+ */
73
+ var legacyTreeInShadow = function (target, scope) {
74
+ return (0, shadow_1.anchorSegmentToShadowScope)(legacyTree(target, scope), scope, (0, shadow_1.legacyPathIsRootAnchored)(target));
75
+ };
76
+ /**
77
+ * Split the outward walk into per-tree segments (capped at `maxShadowDomDepth`
78
+ * boundary crossings), run `perTree` for each segment scoped to that tree's
79
+ * root, and join the results with the boundary delimiter. Passing the per-tree
80
+ * generator as a callback keeps "how to select within one tree" in one place
81
+ * and lets both the legacy and engine algorithms reuse the same walk.
82
+ */
83
+ function pierce(el, perTree) {
84
+ var _a = (0, shadow_1.segmentWalk)(el, config.maxShadowDomDepth), segments = _a.segments, truncated = _a.truncated;
85
+ if (truncated) {
86
+ logger === null || logger === void 0 ? void 0 : logger.debug("@amplitude/element-selector: target is nested deeper than maxShadowDomDepth (".concat(config.maxShadowDomDepth, ") \u2014 emitting a best-effort selector for the outermost in-budget shadow host"));
87
+ }
88
+ return segments.map(function (_a) {
89
+ var target = _a.target, root = _a.root;
90
+ return perTree(target, root);
91
+ }).join(shadow_1.SHADOW_BOUNDARY_DELIMITER);
92
+ }
54
93
  return {
55
94
  generate: function (el) {
56
95
  var _a, _b;
57
- // Kill switch: when the customer's remote config has the engine
58
- // disabled (the default for orgs that haven't opted in), emit the same
59
- // Chromium-derived selector autocapture has shipped since before the
60
- // strategy chain existed. This is what makes "flip enabled back to
61
- // false" a one-config-fetch revert for both the SDK and the dashboard —
62
- // they both go through this entry point now.
63
- if (!config.enabled) {
64
- return (0, legacy_css_path_1.safeLegacyCssPath)(el, logger);
65
- }
66
- // Engine path: try the strategy chain, then the hardened fallback. Both
67
- // are wrapped so a runtime exception (malformed config slipped past the
68
- // resolver, browser API quirks, a bad scope) still produces a usable
69
- // selector. Without this, an autocapture click handler could throw
70
- // mid-flow and the customer would silently lose the event — a worse
71
- // outcome than emitting a less-stable selector.
96
+ // Two independent switches:
97
+ //
98
+ // config.enabled → which per-tree algorithm runs (engine vs legacy)
99
+ // config.shadowDomEnabled → whether we pierce boundaries or stay in one tree
100
+ //
101
+ // One try/catch covers all four corners. It is the safety net: a runtime
102
+ // exception (malformed config slipped past the resolver, browser API
103
+ // quirks, a bad scope, a pathological host chain) still produces a usable
104
+ // selector rather than throwing mid-capture and silently dropping the
105
+ // customer's event.
72
106
  try {
73
- var composed = (0, orchestrator_1.runOrchestrator)(el, config, orchestratorOptions);
74
- if (composed !== null) {
75
- return composed;
107
+ if (!config.shadowDomEnabled) {
108
+ var perTree = config.enabled ? engineTree : legacyTree;
109
+ return perTree(el, (_b = (_a = options.scope) !== null && _a !== void 0 ? _a : el.ownerDocument) !== null && _b !== void 0 ? _b : document);
76
110
  }
77
- return (0, fallback_css_path_1.fallbackCssPath)(el, config, { scope: (_b = (_a = options.scope) !== null && _a !== void 0 ? _a : el.ownerDocument) !== null && _b !== void 0 ? _b : document });
111
+ return pierce(el, config.enabled ? engineTree : legacyTreeInShadow);
78
112
  }
79
113
  catch (e) {
80
114
  var message = e instanceof Error ? e.message : String(e);
81
- logger === null || logger === void 0 ? void 0 : logger.warn("@amplitude/element-selector: strategy chain threw \u2014 falling back to legacy cssPath: ".concat(message));
115
+ logger === null || logger === void 0 ? void 0 : logger.warn("@amplitude/element-selector: selector generation threw \u2014 falling back to legacy cssPath: ".concat(message));
82
116
  return (0, legacy_css_path_1.safeLegacyCssPath)(el, logger);
83
117
  }
84
118
  },
@@ -87,7 +121,7 @@ function createSelectorEngine(initialConfig, options) {
87
121
  },
88
122
  updateConfig: function (next) {
89
123
  var e_1, _a;
90
- config = next;
124
+ config = (0, resolve_config_1.normalizeResolvedConfig)(next);
91
125
  try {
92
126
  // Notify subscribers in insertion order. Errors thrown by individual
93
127
  // subscribers are isolated so one bad listener can't break the others —
@@ -96,7 +130,7 @@ function createSelectorEngine(initialConfig, options) {
96
130
  for (var subscribers_1 = tslib_1.__values(subscribers), subscribers_1_1 = subscribers_1.next(); !subscribers_1_1.done; subscribers_1_1 = subscribers_1.next()) {
97
131
  var cb = subscribers_1_1.value;
98
132
  try {
99
- cb(next);
133
+ cb(config);
100
134
  }
101
135
  catch (e) {
102
136
  var message = e instanceof Error ? e.message : String(e);
@@ -1 +1 @@
1
- {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;;;;AAGH,+CAAsE;AACtE,yDAAsD;AACtD,qDAAsD;AAiBtD;;;;;;;;GAQG;AACH,SAAgB,oBAAoB,CAClC,aAAqC,EACrC,OAAyC;IAAzC,wBAAA,EAAA,YAAyC;IAEzC,IAAI,MAAM,GAA2B,aAAa,CAAC;IACnD,IAAM,WAAW,GAAG,IAA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C;QAED,YAAY,YAAC,IAA4B;;YACvC,MAAM,GAAG,IAAI,CAAC;;gBACd,qEAAqE;gBACrE,wEAAwE;gBACxE,uEAAuE;gBACvE,qEAAqE;gBACrE,KAAiB,IAAA,gBAAA,iBAAA,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;AAxED,oDAwEC","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 { safeLegacyCssPath } 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, logger);\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, logger);\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"]}
1
+ {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;;;;AAEH,0DAAkE;AAElE,+CAAsE;AACtE,yDAAsD;AACtD,qDAAsD;AACtD,2CAK0B;AAyB1B;;;;;;;;GAQG;AACH,SAAgB,oBAAoB,CAClC,aAAqC,EACrC,OAAyC;IAAzC,wBAAA,EAAA,YAAyC;IAEzC,IAAI,MAAM,GAA6B,IAAA,wCAAuB,EAAC,aAAa,CAAC,CAAC;IAC9E,IAAM,WAAW,GAAG,IAAI,GAAG,EAA8C,CAAC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CAAC,MAAM,CAAC,CAAC;qBACZ;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,EAA8C;YAC3D,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;AA3GD,oDA2GC","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 { normalizeResolvedConfig } from './config/resolve-config';\nimport { ElementSelectorLogger, NormalizedSelectorConfig, ResolvedSelectorConfig, SelectorEngine } from './types';\nimport { runOrchestrator, OrchestratorOptions } from './orchestrator';\nimport { fallbackCssPath } from './fallback-css-path';\nimport { safeLegacyCssPath } from './legacy-css-path';\nimport {\n anchorSegmentToShadowScope,\n legacyPathIsRootAnchored,\n segmentWalk,\n SHADOW_BOUNDARY_DELIMITER,\n} from './helpers/shadow';\n\n/**\n * Produce a selector for `target` that is resolvable **within a single tree**,\n * using `scope` (a `Document` or `ShadowRoot`) for uniqueness checks. The two\n * implementations below are the `config.enabled` axis; `pierce` composes one of\n * them across shadow boundaries for the `config.shadowDomEnabled` axis.\n */\ntype TreeSelector = (target: Element, scope: ParentNode) => string;\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: NormalizedSelectorConfig = normalizeResolvedConfig(initialConfig);\n const subscribers = new Set<(config: NormalizedSelectorConfig) => void>();\n const logger = options.logger;\n\n // ── Per-tree algorithms: the `config.enabled` axis ────────────────────────\n\n /**\n * LEGACY algorithm\n * The algorithm has no notion of scope.\n */\n const legacyTree: TreeSelector = (target) => safeLegacyCssPath(target, logger);\n\n /**\n * ENGINE algorithm: the strategy chain, then the hardened fallback, both\n * scoped to the tree's own root.\n */\n const engineTree: TreeSelector = (target, scope) =>\n runOrchestrator(target, config, { strategies: options.strategies, scope, logger }) ??\n fallbackCssPath(target, config, { scope });\n\n // ── Shadow-aware variant: reachable ONLY from `pierce` ────────────────────\n\n /**\n * `legacyCssPath` ignores scope, so for a shadow-tree element with no id\n * ancestor it emits an unanchored positional chain that `querySelector` would\n * match tree-wide. Anchor such a chain so `resolveSelector` descends by direct\n * child instead. `engineTree` needs no counterpart — `fallbackCssPath` anchors\n * its own output from the scope it is handed.\n */\n const legacyTreeInShadow: TreeSelector = (target, scope) =>\n anchorSegmentToShadowScope(legacyTree(target, scope), scope, legacyPathIsRootAnchored(target));\n\n /**\n * Split the outward walk into per-tree segments (capped at `maxShadowDomDepth`\n * boundary crossings), run `perTree` for each segment scoped to that tree's\n * root, and join the results with the boundary delimiter. Passing the per-tree\n * generator as a callback keeps \"how to select within one tree\" in one place\n * and lets both the legacy and engine algorithms reuse the same walk.\n */\n function pierce(el: Element, perTree: TreeSelector): string {\n const { segments, truncated } = segmentWalk(el, config.maxShadowDomDepth);\n if (truncated) {\n logger?.debug(\n `@amplitude/element-selector: target is nested deeper than maxShadowDomDepth (${config.maxShadowDomDepth}) — emitting a best-effort selector for the outermost in-budget shadow host`,\n );\n }\n return segments.map(({ target, root }) => perTree(target, root)).join(SHADOW_BOUNDARY_DELIMITER);\n }\n\n return {\n generate(el: Element): string {\n // Two independent switches:\n //\n // config.enabled → which per-tree algorithm runs (engine vs legacy)\n // config.shadowDomEnabled → whether we pierce boundaries or stay in one tree\n //\n // One try/catch covers all four corners. It is the safety net: a runtime\n // exception (malformed config slipped past the resolver, browser API\n // quirks, a bad scope, a pathological host chain) still produces a usable\n // selector rather than throwing mid-capture and silently dropping the\n // customer's event.\n try {\n if (!config.shadowDomEnabled) {\n const perTree = config.enabled ? engineTree : legacyTree;\n return perTree(el, options.scope ?? el.ownerDocument ?? document);\n }\n return pierce(el, config.enabled ? engineTree : legacyTreeInShadow);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(\n `@amplitude/element-selector: selector generation threw — falling back to legacy cssPath: ${message}`,\n );\n return safeLegacyCssPath(el, logger);\n }\n },\n\n getConfig(): Readonly<NormalizedSelectorConfig> {\n return config;\n },\n\n updateConfig(next: ResolvedSelectorConfig): void {\n config = normalizeResolvedConfig(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(config);\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: NormalizedSelectorConfig) => void): () => void {\n subscribers.add(cb);\n return () => {\n subscribers.delete(cb);\n };\n },\n };\n}\n"]}
@@ -47,7 +47,12 @@ export interface FallbackCssPathOptions {
47
47
  *
48
48
  * Honors `config.maxAncestorWalkDepth` defensively — once the depth limit is
49
49
  * reached, the walker stops and returns whatever it has built so far rooted at
50
- * the deepest reached ancestor.
50
+ * the deepest reached ancestor. Exception: a shadow-root scope always walks to
51
+ * the tree root (see `honorDepthCap`).
52
+ *
53
+ * A depth-capped light-DOM chain is relative and may match more than one
54
+ * element — `resolveSelector` returns the first match, not necessarily the
55
+ * target. Treat capped paths as locators, not identities.
51
56
  */
52
57
  export declare function fallbackCssPath(el: Element, config: ResolvedSelectorConfig, options?: FallbackCssPathOptions): string;
53
58
  //# sourceMappingURL=fallback-css-path.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fallback-css-path.d.ts","sourceRoot":"","sources":["../../src/fallback-css-path.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAIjD,MAAM,WAAW,sBAAsB;IACrC,mGAAmG;IACnG,KAAK,CAAC,EAAE,UAAU,CAAC;CACpB;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAC7B,EAAE,EAAE,OAAO,EACX,MAAM,EAAE,sBAAsB,EAC9B,OAAO,GAAE,sBAA2B,GACnC,MAAM,CAgCR"}
1
+ {"version":3,"file":"fallback-css-path.d.ts","sourceRoot":"","sources":["../../src/fallback-css-path.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAMjD,MAAM,WAAW,sBAAsB;IACrC,mGAAmG;IACnG,KAAK,CAAC,EAAE,UAAU,CAAC;CACpB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAC7B,EAAE,EAAE,OAAO,EACX,MAAM,EAAE,sBAAsB,EAC9B,OAAO,GAAE,sBAA2B,GACnC,MAAM,CA0DR"}
@@ -40,28 +40,43 @@
40
40
  Object.defineProperty(exports, "__esModule", { value: true });
41
41
  exports.fallbackCssPath = void 0;
42
42
  var tslib_1 = require("tslib");
43
+ var resolve_config_1 = require("./config/resolve-config");
43
44
  var get_stable_id_1 = require("./helpers/get-stable-id");
44
45
  var escape_id_1 = require("./helpers/escape-id");
46
+ var shadow_1 = require("./helpers/shadow");
45
47
  /**
46
48
  * Build a positional CSS selector for `el`, using stable ids as anchors when
47
49
  * available and falling back to `tag:nth-of-type(n)` for disambiguation.
48
50
  *
49
51
  * Honors `config.maxAncestorWalkDepth` defensively — once the depth limit is
50
52
  * reached, the walker stops and returns whatever it has built so far rooted at
51
- * the deepest reached ancestor.
53
+ * the deepest reached ancestor. Exception: a shadow-root scope always walks to
54
+ * the tree root (see `honorDepthCap`).
55
+ *
56
+ * A depth-capped light-DOM chain is relative and may match more than one
57
+ * element — `resolveSelector` returns the first match, not necessarily the
58
+ * target. Treat capped paths as locators, not identities.
52
59
  */
53
60
  function fallbackCssPath(el, config, options) {
54
61
  var _a, _b;
55
62
  if (options === void 0) { options = {}; }
63
+ var resolved = (0, resolve_config_1.normalizeResolvedConfig)(config);
56
64
  var scope = (_b = (_a = options.scope) !== null && _a !== void 0 ? _a : el.ownerDocument) !== null && _b !== void 0 ? _b : document;
65
+ var scopeIsShadowRoot = (0, shadow_1.isShadowRoot)(scope);
57
66
  var segments = [];
58
67
  var cursor = el;
59
68
  var depth = 0;
69
+ // The `SHADOW_CHILD_CHAIN_PREFIX` marker below is only emitted when the walk
70
+ // terminates naturally, and it's the only thing anchoring a positional chain
71
+ // inside a shadow root. Capping the walk there drops the marker, so
72
+ // `resolveSelector` matches the first same-shaped subtree instead of the
73
+ // target. The cap targets deep light DOMs; skipping it here is cheap.
74
+ var honorDepthCap = !(resolved.shadowDomEnabled && scopeIsShadowRoot);
60
75
  while (cursor !== null) {
61
- if (config.maxAncestorWalkDepth !== undefined && depth > config.maxAncestorWalkDepth) {
76
+ if (honorDepthCap && resolved.maxAncestorWalkDepth !== undefined && depth > resolved.maxAncestorWalkDepth) {
62
77
  break;
63
78
  }
64
- var id = (0, get_stable_id_1.getStableId)(cursor, config);
79
+ var id = (0, get_stable_id_1.getStableId)(cursor, resolved);
65
80
  if (id !== null) {
66
81
  // Anchor format mirrors the stableId strategy: `tag#id` with the id
67
82
  // CSS-escaped. Only terminate if the composed selector uniquely resolves
@@ -72,45 +87,31 @@ function fallbackCssPath(el, config, options) {
72
87
  return candidate;
73
88
  }
74
89
  }
75
- segments.unshift(stepFor(cursor));
90
+ // `positionalStep` emits `tag:nth-of-type(n)` for an element with a parent
91
+ // and the bare `tag` for the document root. `config.shadowDomEnabled` also
92
+ // lets it index a shadow-root-top element against its `ShadowRoot` siblings —
93
+ // its `parentElement` is null, but it can have same-tag peers.
94
+ segments.unshift((0, shadow_1.positionalStep)(cursor, resolved.shadowDomEnabled));
76
95
  cursor = cursor.parentElement;
77
96
  depth += 1;
78
97
  }
79
- // Walked all the way to the document root without finding an id. The first
80
- // segment is whatever `<html>` produced (which is just `html` since it has
81
- // no parent and no same-tag siblings).
82
- return segments.join(' > ');
83
- }
84
- exports.fallbackCssPath = fallbackCssPath;
85
- /**
86
- * Build a single step. For an element with a parent: `tag:nth-of-type(n)`.
87
- * For a root element (no parent — i.e. <html>): just `tag`.
88
- *
89
- * Class-based disambiguation is intentionally not emitted in v1 — see the
90
- * design doc, "Why we don't use classes for sibling disambiguation". The
91
- * `filterClasses` helper is imported in the package for future iterations.
92
- */
93
- function stepFor(el) {
94
- var tag = el.tagName.toLowerCase();
95
- var parent = el.parentElement;
96
- if (parent === null) {
97
- return tag;
98
- }
99
- var index = sameTypeIndex(el, parent);
100
- return "".concat(tag, ":nth-of-type(").concat(index, ")");
101
- }
102
- function sameTypeIndex(el, parent) {
103
- var count = 0;
104
- for (var i = 0; i < parent.children.length; i++) {
105
- var sibling = parent.children[i];
106
- if (sibling.tagName === el.tagName) {
107
- count += 1;
108
- if (sibling === el)
109
- return count;
110
- }
98
+ var path = segments.join(' > ');
99
+ // In the light DOM the chain's first segment is `<html>` (unique), which
100
+ // anchors it. Inside a shadow root there is no anchoring root element, so a
101
+ // bare positional chain would match tree-wide. When we reached the top of the
102
+ // tree naturally (`cursor === null`, not a depth-limit break), the chain spans
103
+ // root → target via direct children — mark it so `resolveSelector` resolves it
104
+ // by direct-child descent. The marker is explicit (not inferred from the step
105
+ // syntax), so it stays correct even if steps later include classes.
106
+ //
107
+ // Requires `shadowDomEnabled`: the marker is only meaningful to a resolver that
108
+ // is descending shadow roots, so a `ShadowRoot` scope alone doesn't produce it.
109
+ if (resolved.shadowDomEnabled && scopeIsShadowRoot && cursor === null) {
110
+ return "".concat(shadow_1.SHADOW_CHILD_CHAIN_PREFIX).concat(path);
111
111
  }
112
- return 1;
112
+ return path;
113
113
  }
114
+ exports.fallbackCssPath = fallbackCssPath;
114
115
  function isUniqueMatch(scope, selector, el) {
115
116
  var matches;
116
117
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"fallback-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n * Fallback CSS-path walker — the safety net for the v1 element-selector\n * algorithm.\n *\n * When the orchestrator's strategy chain finds nothing usable across the full\n * ancestor walk, the engine invokes this fallback. It produces a positional\n * selector by walking up from the target to <html>, expressing each step as\n * either an id anchor (when one survives the autogen filter) or a\n * `tag:nth-of-type(n)` step.\n *\n * Key differences from the legacy autocapture `cssPath`:\n *\n * 1. Ids are filtered through `getStableId`, which honors the\n * explicit-tracking-attribute suppression signal AND the autogenerated-id\n * pattern pack. The legacy `cssPath` would happily anchor on `id=\":r5:\"`\n * and produce selectors that never match across page loads.\n *\n * 2. Classes — when they're used at all for sibling disambiguation — are\n * filtered through `filterClasses` against the unstable-class pattern\n * pack. The current v1 implementation here doesn't emit classes (we lean\n * entirely on `:nth-of-type` for sibling disambiguation), but the\n * filtering helper is wired through so future iterations can opt back in\n * surgically without re-deriving the policy.\n *\n * 3. A unique anchor id terminates the walk early — once we hit `body#main`,\n * we don't need to keep walking up to `<html>`.\n *\n * 4. Ambiguous id anchors are skipped. Duplicate ids are invalid HTML but\n * common enough in the wild that fallback must not emit selectors that\n * resolve to the wrong target.\n *\n * Output format mirrors the orchestrator's output: `<anchor> > <descent>`.\n * When no usable id is found anywhere on the walk, the fallback emits a\n * pure-positional selector rooted at `html`.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { ResolvedSelectorConfig } from './types';\nimport { getStableId } from './helpers/get-stable-id';\nimport { escapeIdForCss } from './helpers/escape-id';\n\nexport interface FallbackCssPathOptions {\n /** Document or shadow root used for uniqueness checks. Defaults to the target's owner document. */\n scope?: ParentNode;\n}\n\n/**\n * Build a positional CSS selector for `el`, using stable ids as anchors when\n * available and falling back to `tag:nth-of-type(n)` for disambiguation.\n *\n * Honors `config.maxAncestorWalkDepth` defensively — once the depth limit is\n * reached, the walker stops and returns whatever it has built so far rooted at\n * the deepest reached ancestor.\n */\nexport function fallbackCssPath(\n el: Element,\n config: ResolvedSelectorConfig,\n options: FallbackCssPathOptions = {},\n): string {\n const scope: ParentNode = options.scope ?? el.ownerDocument ?? document;\n const segments: string[] = [];\n let cursor: Element | null = el;\n let depth = 0;\n\n while (cursor !== null) {\n if (config.maxAncestorWalkDepth !== undefined && depth > config.maxAncestorWalkDepth) {\n break;\n }\n\n const id = getStableId(cursor, config);\n if (id !== null) {\n // Anchor format mirrors the stableId strategy: `tag#id` with the id\n // CSS-escaped. Only terminate if the composed selector uniquely resolves\n // to the target; duplicate ids should fall through to positional steps.\n const anchorSegment = `${cursor.tagName.toLowerCase()}#${escapeIdForCss(id)}`;\n const candidate = [anchorSegment, ...segments].join(' > ');\n if (isUniqueMatch(scope, candidate, el)) {\n return candidate;\n }\n }\n\n segments.unshift(stepFor(cursor));\n cursor = cursor.parentElement;\n depth += 1;\n }\n\n // Walked all the way to the document root without finding an id. The first\n // segment is whatever `<html>` produced (which is just `html` since it has\n // no parent and no same-tag siblings).\n return segments.join(' > ');\n}\n\n/**\n * Build a single step. For an element with a parent: `tag:nth-of-type(n)`.\n * For a root element (no parent — i.e. <html>): just `tag`.\n *\n * Class-based disambiguation is intentionally not emitted in v1 — see the\n * design doc, \"Why we don't use classes for sibling disambiguation\". The\n * `filterClasses` helper is imported in the package for future iterations.\n */\nfunction stepFor(el: Element): string {\n const tag = el.tagName.toLowerCase();\n const parent = el.parentElement;\n if (parent === null) {\n return tag;\n }\n const index = sameTypeIndex(el, parent);\n return `${tag}:nth-of-type(${index})`;\n}\n\nfunction sameTypeIndex(el: Element, parent: Element): number {\n let count = 0;\n for (let i = 0; i < parent.children.length; i++) {\n const sibling = parent.children[i];\n if (sibling.tagName === el.tagName) {\n count += 1;\n if (sibling === el) return count;\n }\n }\n return 1;\n}\n\nfunction isUniqueMatch(scope: ParentNode, selector: string, el: Element): boolean {\n let matches: NodeListOf<Element>;\n try {\n matches = scope.querySelectorAll(selector);\n } catch (_e) {\n return false;\n }\n return matches.length === 1 && matches[0] === el;\n}\n"]}
1
+ {"version":3,"file":"fall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AG,uBAAC,aAAa,kBAAK,QAAQ,UAAE,IAAI,CAAC,KAAK,CAAC,CAAC;YAC3D,IAAI,aAAa,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE,CAAC,EAAE;gBACvC,OAAO,SAAS,CAAC;aAClB;SACF;QAED,2EAA2E;QAC3E,2EAA2E;QAC3E,8EAA8E;QAC9E,+DAA+D;QAC/D,QAAQ,CAAC,OAAO,CAAC,IAAA,uBAAc,EAAC,MAAM,EAAE,QAAQ,CAAC,gBAAgB,CAAC,CAAC,CAAC;QACpE,MAAM,GAAG,MAAM,CAAC,aAAa,CAAC;QAC9B,KAAK,IAAI,CAAC,CAAC;KACZ;IAED,IAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAElC,yEAAyE;IACzE,4EAA4E;IAC5E,8EAA8E;IAC9E,+EAA+E;IAC/E,+EAA+E;IAC/E,8EAA8E;IAC9E,oEAAoE;IACpE,EAAE;IACF,gFAAgF;IAChF,gFAAgF;IAChF,IAAI,QAAQ,CAAC,gBAAgB,IAAI,iBAAiB,IAAI,MAAM,KAAK,IAAI,EAAE;QACrE,OAAO,UAAG,kCAAyB,SAAG,IAAI,CAAE,CAAC;KAC9C;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AA9DD,0CA8DC;AAED,SAAS,aAAa,CAAC,KAAiB,EAAE,QAAgB,EAAE,EAAW;IACrE,IAAI,OAA4B,CAAC;IACjC,IAAI;QACF,OAAO,GAAG,KAAK,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC;KAC5C;IAAC,OAAO,EAAE,EAAE;QACX,OAAO,KAAK,CAAC;KACd;IACD,OAAO,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;AACnD,CAAC","sourcesContent":["/**\n * Fallback CSS-path walker — the safety net for the v1 element-selector\n * algorithm.\n *\n * When the orchestrator's strategy chain finds nothing usable across the full\n * ancestor walk, the engine invokes this fallback. It produces a positional\n * selector by walking up from the target to <html>, expressing each step as\n * either an id anchor (when one survives the autogen filter) or a\n * `tag:nth-of-type(n)` step.\n *\n * Key differences from the legacy autocapture `cssPath`:\n *\n * 1. Ids are filtered through `getStableId`, which honors the\n * explicit-tracking-attribute suppression signal AND the autogenerated-id\n * pattern pack. The legacy `cssPath` would happily anchor on `id=\":r5:\"`\n * and produce selectors that never match across page loads.\n *\n * 2. Classes — when they're used at all for sibling disambiguation — are\n * filtered through `filterClasses` against the unstable-class pattern\n * pack. The current v1 implementation here doesn't emit classes (we lean\n * entirely on `:nth-of-type` for sibling disambiguation), but the\n * filtering helper is wired through so future iterations can opt back in\n * surgically without re-deriving the policy.\n *\n * 3. A unique anchor id terminates the walk early — once we hit `body#main`,\n * we don't need to keep walking up to `<html>`.\n *\n * 4. Ambiguous id anchors are skipped. Duplicate ids are invalid HTML but\n * common enough in the wild that fallback must not emit selectors that\n * resolve to the wrong target.\n *\n * Output format mirrors the orchestrator's output: `<anchor> > <descent>`.\n * When no usable id is found anywhere on the walk, the fallback emits a\n * pure-positional selector rooted at `html`.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { ResolvedSelectorConfig } from './types';\nimport { normalizeResolvedConfig } from './config/resolve-config';\nimport { getStableId } from './helpers/get-stable-id';\nimport { escapeIdForCss } from './helpers/escape-id';\nimport { isShadowRoot, positionalStep, SHADOW_CHILD_CHAIN_PREFIX } from './helpers/shadow';\n\nexport interface FallbackCssPathOptions {\n /** Document or shadow root used for uniqueness checks. Defaults to the target's owner document. */\n scope?: ParentNode;\n}\n\n/**\n * Build a positional CSS selector for `el`, using stable ids as anchors when\n * available and falling back to `tag:nth-of-type(n)` for disambiguation.\n *\n * Honors `config.maxAncestorWalkDepth` defensively — once the depth limit is\n * reached, the walker stops and returns whatever it has built so far rooted at\n * the deepest reached ancestor. Exception: a shadow-root scope always walks to\n * the tree root (see `honorDepthCap`).\n *\n * A depth-capped light-DOM chain is relative and may match more than one\n * element — `resolveSelector` returns the first match, not necessarily the\n * target. Treat capped paths as locators, not identities.\n */\nexport function fallbackCssPath(\n el: Element,\n config: ResolvedSelectorConfig,\n options: FallbackCssPathOptions = {},\n): string {\n const resolved = normalizeResolvedConfig(config);\n const scope: ParentNode = options.scope ?? el.ownerDocument ?? document;\n const scopeIsShadowRoot = isShadowRoot(scope as Node);\n const segments: string[] = [];\n let cursor: Element | null = el;\n let depth = 0;\n\n // The `SHADOW_CHILD_CHAIN_PREFIX` marker below is only emitted when the walk\n // terminates naturally, and it's the only thing anchoring a positional chain\n // inside a shadow root. Capping the walk there drops the marker, so\n // `resolveSelector` matches the first same-shaped subtree instead of the\n // target. The cap targets deep light DOMs; skipping it here is cheap.\n const honorDepthCap = !(resolved.shadowDomEnabled && scopeIsShadowRoot);\n\n while (cursor !== null) {\n if (honorDepthCap && resolved.maxAncestorWalkDepth !== undefined && depth > resolved.maxAncestorWalkDepth) {\n break;\n }\n\n const id = getStableId(cursor, resolved);\n if (id !== null) {\n // Anchor format mirrors the stableId strategy: `tag#id` with the id\n // CSS-escaped. Only terminate if the composed selector uniquely resolves\n // to the target; duplicate ids should fall through to positional steps.\n const anchorSegment = `${cursor.tagName.toLowerCase()}#${escapeIdForCss(id)}`;\n const candidate = [anchorSegment, ...segments].join(' > ');\n if (isUniqueMatch(scope, candidate, el)) {\n return candidate;\n }\n }\n\n // `positionalStep` emits `tag:nth-of-type(n)` for an element with a parent\n // and the bare `tag` for the document root. `config.shadowDomEnabled` also\n // lets it index a shadow-root-top element against its `ShadowRoot` siblings —\n // its `parentElement` is null, but it can have same-tag peers.\n segments.unshift(positionalStep(cursor, resolved.shadowDomEnabled));\n cursor = cursor.parentElement;\n depth += 1;\n }\n\n const path = segments.join(' > ');\n\n // In the light DOM the chain's first segment is `<html>` (unique), which\n // anchors it. Inside a shadow root there is no anchoring root element, so a\n // bare positional chain would match tree-wide. When we reached the top of the\n // tree naturally (`cursor === null`, not a depth-limit break), the chain spans\n // root → target via direct children — mark it so `resolveSelector` resolves it\n // by direct-child descent. The marker is explicit (not inferred from the step\n // syntax), so it stays correct even if steps later include classes.\n //\n // Requires `shadowDomEnabled`: the marker is only meaningful to a resolver that\n // is descending shadow roots, so a `ShadowRoot` scope alone doesn't produce it.\n if (resolved.shadowDomEnabled && scopeIsShadowRoot && cursor === null) {\n return `${SHADOW_CHILD_CHAIN_PREFIX}${path}`;\n }\n\n return path;\n}\n\nfunction isUniqueMatch(scope: ParentNode, selector: string, el: Element): boolean {\n let matches: NodeListOf<Element>;\n try {\n matches = scope.querySelectorAll(selector);\n } catch (_e) {\n return false;\n }\n return matches.length === 1 && matches[0] === el;\n}\n"]}