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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +162 -0
  3. package/lib/cjs/config/resolve-config.d.ts +56 -0
  4. package/lib/cjs/config/resolve-config.d.ts.map +1 -0
  5. package/lib/cjs/config/resolve-config.js +114 -0
  6. package/lib/cjs/config/resolve-config.js.map +1 -0
  7. package/lib/cjs/engine.d.ts +54 -0
  8. package/lib/cjs/engine.d.ts.map +1 -0
  9. package/lib/cjs/engine.js +139 -0
  10. package/lib/cjs/engine.js.map +1 -0
  11. package/lib/cjs/fallback-css-path.d.ts +53 -0
  12. package/lib/cjs/fallback-css-path.d.ts.map +1 -0
  13. package/lib/cjs/fallback-css-path.js +124 -0
  14. package/lib/cjs/fallback-css-path.js.map +1 -0
  15. package/lib/cjs/generate-selector.d.ts +54 -0
  16. package/lib/cjs/generate-selector.d.ts.map +1 -0
  17. package/lib/cjs/generate-selector.js +76 -0
  18. package/lib/cjs/generate-selector.js.map +1 -0
  19. package/lib/cjs/helpers/describe-relative.d.ts +28 -0
  20. package/lib/cjs/helpers/describe-relative.d.ts.map +1 -0
  21. package/lib/cjs/helpers/describe-relative.js +60 -0
  22. package/lib/cjs/helpers/describe-relative.js.map +1 -0
  23. package/lib/cjs/helpers/escape-css-identifier.d.ts +8 -0
  24. package/lib/cjs/helpers/escape-css-identifier.d.ts.map +1 -0
  25. package/lib/cjs/helpers/escape-css-identifier.js +50 -0
  26. package/lib/cjs/helpers/escape-css-identifier.js.map +1 -0
  27. package/lib/cjs/helpers/escape-id.d.ts +3 -0
  28. package/lib/cjs/helpers/escape-id.d.ts.map +1 -0
  29. package/lib/cjs/helpers/escape-id.js +10 -0
  30. package/lib/cjs/helpers/escape-id.js.map +1 -0
  31. package/lib/cjs/helpers/get-stable-id.d.ts +23 -0
  32. package/lib/cjs/helpers/get-stable-id.d.ts.map +1 -0
  33. package/lib/cjs/helpers/get-stable-id.js +44 -0
  34. package/lib/cjs/helpers/get-stable-id.js.map +1 -0
  35. package/lib/cjs/index.d.ts +31 -0
  36. package/lib/cjs/index.d.ts.map +1 -0
  37. package/lib/cjs/index.js +71 -0
  38. package/lib/cjs/index.js.map +1 -0
  39. package/lib/cjs/legacy-css-path.d.ts +84 -0
  40. package/lib/cjs/legacy-css-path.d.ts.map +1 -0
  41. package/lib/cjs/legacy-css-path.js +230 -0
  42. package/lib/cjs/legacy-css-path.js.map +1 -0
  43. package/lib/cjs/orchestrator.d.ts +61 -0
  44. package/lib/cjs/orchestrator.d.ts.map +1 -0
  45. package/lib/cjs/orchestrator.js +140 -0
  46. package/lib/cjs/orchestrator.js.map +1 -0
  47. package/lib/cjs/patterns/autogenerated-ids.d.ts +37 -0
  48. package/lib/cjs/patterns/autogenerated-ids.d.ts.map +1 -0
  49. package/lib/cjs/patterns/autogenerated-ids.js +102 -0
  50. package/lib/cjs/patterns/autogenerated-ids.js.map +1 -0
  51. package/lib/cjs/patterns/unstable-classes.d.ts +48 -0
  52. package/lib/cjs/patterns/unstable-classes.d.ts.map +1 -0
  53. package/lib/cjs/patterns/unstable-classes.js +155 -0
  54. package/lib/cjs/patterns/unstable-classes.js.map +1 -0
  55. package/lib/cjs/strategies/explicit-tracking-attribute.d.ts +22 -0
  56. package/lib/cjs/strategies/explicit-tracking-attribute.d.ts.map +1 -0
  57. package/lib/cjs/strategies/explicit-tracking-attribute.js +36 -0
  58. package/lib/cjs/strategies/explicit-tracking-attribute.js.map +1 -0
  59. package/lib/cjs/strategies/stable-id.d.ts +14 -0
  60. package/lib/cjs/strategies/stable-id.d.ts.map +1 -0
  61. package/lib/cjs/strategies/stable-id.js +27 -0
  62. package/lib/cjs/strategies/stable-id.js.map +1 -0
  63. package/lib/cjs/types.d.ts +100 -0
  64. package/lib/cjs/types.d.ts.map +1 -0
  65. package/lib/cjs/types.js +13 -0
  66. package/lib/cjs/types.js.map +1 -0
  67. package/lib/esm/config/resolve-config.d.ts +56 -0
  68. package/lib/esm/config/resolve-config.d.ts.map +1 -0
  69. package/lib/esm/config/resolve-config.js +110 -0
  70. package/lib/esm/config/resolve-config.js.map +1 -0
  71. package/lib/esm/engine.d.ts +54 -0
  72. package/lib/esm/engine.d.ts.map +1 -0
  73. package/lib/esm/engine.js +135 -0
  74. package/lib/esm/engine.js.map +1 -0
  75. package/lib/esm/fallback-css-path.d.ts +53 -0
  76. package/lib/esm/fallback-css-path.d.ts.map +1 -0
  77. package/lib/esm/fallback-css-path.js +120 -0
  78. package/lib/esm/fallback-css-path.js.map +1 -0
  79. package/lib/esm/generate-selector.d.ts +54 -0
  80. package/lib/esm/generate-selector.d.ts.map +1 -0
  81. package/lib/esm/generate-selector.js +72 -0
  82. package/lib/esm/generate-selector.js.map +1 -0
  83. package/lib/esm/helpers/describe-relative.d.ts +28 -0
  84. package/lib/esm/helpers/describe-relative.d.ts.map +1 -0
  85. package/lib/esm/helpers/describe-relative.js +56 -0
  86. package/lib/esm/helpers/describe-relative.js.map +1 -0
  87. package/lib/esm/helpers/escape-css-identifier.d.ts +8 -0
  88. package/lib/esm/helpers/escape-css-identifier.d.ts.map +1 -0
  89. package/lib/esm/helpers/escape-css-identifier.js +46 -0
  90. package/lib/esm/helpers/escape-css-identifier.js.map +1 -0
  91. package/lib/esm/helpers/escape-id.d.ts +3 -0
  92. package/lib/esm/helpers/escape-id.d.ts.map +1 -0
  93. package/lib/esm/helpers/escape-id.js +6 -0
  94. package/lib/esm/helpers/escape-id.js.map +1 -0
  95. package/lib/esm/helpers/get-stable-id.d.ts +23 -0
  96. package/lib/esm/helpers/get-stable-id.d.ts.map +1 -0
  97. package/lib/esm/helpers/get-stable-id.js +40 -0
  98. package/lib/esm/helpers/get-stable-id.js.map +1 -0
  99. package/lib/esm/index.d.ts +31 -0
  100. package/lib/esm/index.d.ts.map +1 -0
  101. package/lib/esm/index.js +50 -0
  102. package/lib/esm/index.js.map +1 -0
  103. package/lib/esm/legacy-css-path.d.ts +84 -0
  104. package/lib/esm/legacy-css-path.d.ts.map +1 -0
  105. package/lib/esm/legacy-css-path.js +226 -0
  106. package/lib/esm/legacy-css-path.js.map +1 -0
  107. package/lib/esm/orchestrator.d.ts +61 -0
  108. package/lib/esm/orchestrator.d.ts.map +1 -0
  109. package/lib/esm/orchestrator.js +136 -0
  110. package/lib/esm/orchestrator.js.map +1 -0
  111. package/lib/esm/patterns/autogenerated-ids.d.ts +37 -0
  112. package/lib/esm/patterns/autogenerated-ids.d.ts.map +1 -0
  113. package/lib/esm/patterns/autogenerated-ids.js +97 -0
  114. package/lib/esm/patterns/autogenerated-ids.js.map +1 -0
  115. package/lib/esm/patterns/unstable-classes.d.ts +48 -0
  116. package/lib/esm/patterns/unstable-classes.d.ts.map +1 -0
  117. package/lib/esm/patterns/unstable-classes.js +150 -0
  118. package/lib/esm/patterns/unstable-classes.js.map +1 -0
  119. package/lib/esm/strategies/explicit-tracking-attribute.d.ts +22 -0
  120. package/lib/esm/strategies/explicit-tracking-attribute.d.ts.map +1 -0
  121. package/lib/esm/strategies/explicit-tracking-attribute.js +33 -0
  122. package/lib/esm/strategies/explicit-tracking-attribute.js.map +1 -0
  123. package/lib/esm/strategies/stable-id.d.ts +14 -0
  124. package/lib/esm/strategies/stable-id.d.ts.map +1 -0
  125. package/lib/esm/strategies/stable-id.js +24 -0
  126. package/lib/esm/strategies/stable-id.js.map +1 -0
  127. package/lib/esm/types.d.ts +100 -0
  128. package/lib/esm/types.d.ts.map +1 -0
  129. package/lib/esm/types.js +12 -0
  130. package/lib/esm/types.js.map +1 -0
  131. package/package.json +40 -5
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ /**
3
+ * Core type definitions for the v1 element-selector algorithm.
4
+ *
5
+ * These are the public-API contract that consumers (autocapture SDK, dashboard
6
+ * tagging UI, Chrome extension visual tagger) design against. They land before
7
+ * any implementation so the contract is stable for cross-team review.
8
+ *
9
+ * See the design doc:
10
+ * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG","sourcesContent":["/**\n * Core type definitions for the v1 element-selector algorithm.\n *\n * These are the public-API contract that consumers (autocapture SDK, dashboard\n * tagging UI, Chrome extension visual tagger) design against. They land before\n * any implementation so the contract is stable for cross-team review.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\n/**\n * A pluggable selector strategy. Given an element + context, returns a CSS\n * selector string candidate (which the orchestrator will then uniqueness-check)\n * or `null` when the strategy doesn't apply to this element.\n */\nexport interface Strategy {\n /** Stable identifier for the strategy. Used for diagnostics and remote-config references. */\n readonly name: string;\n\n /**\n * Produce a candidate selector for `el`, or `null` if this strategy has\n * nothing to contribute for this element. Strategies are pure transforms —\n * they never call `querySelectorAll` themselves; uniqueness is checked by\n * the orchestrator in the next layer up.\n */\n try(el: Element, ctx: StrategyContext): string | null;\n}\n\n/**\n * Context passed to every strategy invocation. `scope` is the document or\n * shadow root the orchestrator will use for uniqueness checks; `config` is the\n * resolved configuration (defaults + remote + local options merged).\n */\nexport interface StrategyContext {\n scope: ParentNode;\n config: ResolvedSelectorConfig;\n}\n\n/**\n * Logger shape accepted by element-selector diagnostics.\n *\n * This is intentionally structural so callers can pass the SDK's\n * `@amplitude/analytics-core` ILogger without this package needing to import\n * analytics-core types during standalone tests/builds.\n */\nexport interface ElementSelectorLogger {\n warn(...args: unknown[]): void;\n debug(...args: unknown[]): void;\n}\n\n/**\n * Fully-resolved configuration consumed at runtime. Produced by\n * `resolveSelectorConfig` (lands in the orchestration PR) from the\n * `ElementSelectorRemoteConfig` payload plus built-in defaults.\n */\nexport interface ResolvedSelectorConfig {\n /** Master kill switch. When false, autocapture reverts to legacy cssPath. */\n enabled: boolean;\n /** Attribute name customers can use to set or suppress anchors. Default: 'data-amp-track-id'. */\n explicitTrackingAttribute: string;\n /** Compiled regex patterns matching ids the algorithm should treat as autogenerated. */\n autogeneratedIdPatterns: RegExp[];\n /** Compiled regex patterns matching classes the fallback should filter from sibling disambiguation. */\n unstableClassPatterns: RegExp[];\n /** Optional throttle on the ancestor walk. When undefined, the walk runs to <html>. */\n maxAncestorWalkDepth?: number;\n}\n\n/**\n * Remote-config payload shape. Each field is optional; absent fields fall back\n * to built-in defaults. Customers see the defaults in the remote-config UI and\n * may add or remove patterns as needed.\n */\nexport interface ElementSelectorRemoteConfig {\n /** Kill switch. When set, overrides the default at resolve time. */\n enabled?: boolean;\n /** Override the attribute name used for explicit tracking. */\n explicitTrackingAttribute?: string;\n /** Full replacement for the autogenerated-id pattern list. When omitted, defaults apply. */\n autogeneratedIdPatterns?: string[];\n /** Full replacement for the unstable-class pattern list. When omitted, defaults apply. */\n unstableClassPatterns?: string[];\n /** Defensive throttle on the ancestor walk. Omit for unbounded walking to <html>. */\n maxAncestorWalkDepth?: number;\n}\n\n/**\n * Public interface of the runtime engine. Implementation lands in the\n * orchestration PR; the interface is declared here so consumers can write\n * against the contract before the class exists.\n */\nexport interface SelectorEngine {\n /** Produce a CSS selector string identifying `el` using the engine's current config. */\n generate(el: Element): string;\n\n /** Read-only access to the current resolved config — for diagnostics and consumer hydration. */\n getConfig(): Readonly<ResolvedSelectorConfig>;\n\n /** Replace the current config. Notifies any onConfigChange subscribers. */\n updateConfig(next: ResolvedSelectorConfig): void;\n\n /**\n * Subscribe to config-change notifications. Returns an unsubscribe function.\n * Used by the Chrome extension to keep its locally-hydrated engine in sync\n * with the customer's SDK as remote config updates flow in.\n */\n onConfigChange(cb: (config: ResolvedSelectorConfig) => void): () => void;\n}\n"]}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Config resolver — collapses the optional, string-based remote-config payload
3
+ * into the fully-typed `ResolvedSelectorConfig` that strategies, orchestrator,
4
+ * and fallback consume at runtime.
5
+ *
6
+ * Responsibilities:
7
+ *
8
+ * 1. Apply defaults for every field. The defaults (enabled = false,
9
+ * attribute = `data-amp-track-id`, built-in pattern packs) match the
10
+ * design doc's "v1 defaults" table.
11
+ *
12
+ * 2. Compile regex strings into `RegExp[]`. Bad regexes are skipped by the
13
+ * underlying `compile` helpers; when a logger is provided it surfaces a
14
+ * warning for each invalid pattern so customers can diagnose why their
15
+ * override isn't taking effect.
16
+ *
17
+ * 3. Treat customer-provided pattern lists as a **full replacement** of the
18
+ * defaults — not a merge. This matches the design doc: "The customer
19
+ * sees the defaults in the remote-config UI and may add or remove
20
+ * patterns as needed." If a customer provides `autogeneratedIdPatterns:
21
+ * []`, that's their explicit request to disable autogen filtering.
22
+ *
23
+ * 4. Clamp `maxAncestorWalkDepth` into a sane range. Negative / zero values
24
+ * are coerced to `undefined` (treat as "no limit") rather than throwing —
25
+ * remote config should never crash the engine.
26
+ *
27
+ * See the design doc:
28
+ * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
29
+ */
30
+ import { ElementSelectorLogger, ElementSelectorRemoteConfig, ResolvedSelectorConfig } from '../types';
31
+ /**
32
+ * Built-in defaults applied when a field is absent from the remote payload.
33
+ * Exported so consumers (and tests) can introspect the baseline without
34
+ * round-tripping through `resolveSelectorConfig({})`.
35
+ */
36
+ export declare const DEFAULT_RESOLVED_CONFIG: Readonly<ResolvedSelectorConfig>;
37
+ /**
38
+ * Resolve a (possibly partial, possibly absent) remote-config payload into a
39
+ * fully-typed runtime config. Always returns a fresh object; never mutates the
40
+ * input.
41
+ *
42
+ * Field-by-field semantics:
43
+ *
44
+ * - `enabled`: defaults to false (the engine ships dormant). Any boolean in
45
+ * the payload — including `false` — wins.
46
+ * - `explicitTrackingAttribute`: defaults to `data-amp-track-id`. Empty
47
+ * strings are rejected (they'd make the strategy match every element);
48
+ * fall back to the default in that case.
49
+ * - `autogeneratedIdPatterns` / `unstableClassPatterns`: present → compile
50
+ * the strings (skipping invalid regexes), use the compiled list as-is.
51
+ * Absent → use the defaults.
52
+ * - `maxAncestorWalkDepth`: positive finite integer → use as-is. Anything
53
+ * else (zero, negative, NaN, Infinity) → `undefined` (no limit).
54
+ */
55
+ export declare function resolveSelectorConfig(remote?: ElementSelectorRemoteConfig, logger?: ElementSelectorLogger): ResolvedSelectorConfig;
56
+ //# sourceMappingURL=resolve-config.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Config resolver — collapses the optional, string-based remote-config payload
3
+ * into the fully-typed `ResolvedSelectorConfig` that strategies, orchestrator,
4
+ * and fallback consume at runtime.
5
+ *
6
+ * Responsibilities:
7
+ *
8
+ * 1. Apply defaults for every field. The defaults (enabled = false,
9
+ * attribute = `data-amp-track-id`, built-in pattern packs) match the
10
+ * design doc's "v1 defaults" table.
11
+ *
12
+ * 2. Compile regex strings into `RegExp[]`. Bad regexes are skipped by the
13
+ * underlying `compile` helpers; when a logger is provided it surfaces a
14
+ * warning for each invalid pattern so customers can diagnose why their
15
+ * override isn't taking effect.
16
+ *
17
+ * 3. Treat customer-provided pattern lists as a **full replacement** of the
18
+ * defaults — not a merge. This matches the design doc: "The customer
19
+ * sees the defaults in the remote-config UI and may add or remove
20
+ * patterns as needed." If a customer provides `autogeneratedIdPatterns:
21
+ * []`, that's their explicit request to disable autogen filtering.
22
+ *
23
+ * 4. Clamp `maxAncestorWalkDepth` into a sane range. Negative / zero values
24
+ * are coerced to `undefined` (treat as "no limit") rather than throwing —
25
+ * remote config should never crash the engine.
26
+ *
27
+ * See the design doc:
28
+ * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
29
+ */
30
+ import { __read, __spreadArray } from "tslib";
31
+ import { DEFAULT_AUTOGENERATED_ID_PATTERNS, compile as compileAutogeneratedIdPatterns, } from '../patterns/autogenerated-ids';
32
+ import { DEFAULT_UNSTABLE_CLASS_PATTERNS, compile as compileUnstableClassPatterns } from '../patterns/unstable-classes';
33
+ /**
34
+ * Built-in defaults applied when a field is absent from the remote payload.
35
+ * Exported so consumers (and tests) can introspect the baseline without
36
+ * round-tripping through `resolveSelectorConfig({})`.
37
+ */
38
+ export var DEFAULT_RESOLVED_CONFIG = Object.freeze({
39
+ // v1 ships disabled — autocapture only flips to the new engine when the
40
+ // remote config explicitly enables it for an org.
41
+ enabled: false,
42
+ explicitTrackingAttribute: 'data-amp-track-id',
43
+ autogeneratedIdPatterns: __spreadArray([], __read(DEFAULT_AUTOGENERATED_ID_PATTERNS), false),
44
+ unstableClassPatterns: __spreadArray([], __read(DEFAULT_UNSTABLE_CLASS_PATTERNS), false),
45
+ maxAncestorWalkDepth: undefined,
46
+ });
47
+ /**
48
+ * Resolve a (possibly partial, possibly absent) remote-config payload into a
49
+ * fully-typed runtime config. Always returns a fresh object; never mutates the
50
+ * input.
51
+ *
52
+ * Field-by-field semantics:
53
+ *
54
+ * - `enabled`: defaults to false (the engine ships dormant). Any boolean in
55
+ * the payload — including `false` — wins.
56
+ * - `explicitTrackingAttribute`: defaults to `data-amp-track-id`. Empty
57
+ * strings are rejected (they'd make the strategy match every element);
58
+ * fall back to the default in that case.
59
+ * - `autogeneratedIdPatterns` / `unstableClassPatterns`: present → compile
60
+ * the strings (skipping invalid regexes), use the compiled list as-is.
61
+ * Absent → use the defaults.
62
+ * - `maxAncestorWalkDepth`: positive finite integer → use as-is. Anything
63
+ * else (zero, negative, NaN, Infinity) → `undefined` (no limit).
64
+ */
65
+ export function resolveSelectorConfig(remote, logger) {
66
+ if (!remote) {
67
+ // Return a fresh copy so callers can safely mutate the result without
68
+ // poisoning the frozen defaults singleton.
69
+ return cloneDefaults();
70
+ }
71
+ var resolved = cloneDefaults();
72
+ if (typeof remote.enabled === 'boolean') {
73
+ resolved.enabled = remote.enabled;
74
+ }
75
+ if (typeof remote.explicitTrackingAttribute === 'string' && remote.explicitTrackingAttribute !== '') {
76
+ resolved.explicitTrackingAttribute = remote.explicitTrackingAttribute;
77
+ }
78
+ if (Array.isArray(remote.autogeneratedIdPatterns)) {
79
+ resolved.autogeneratedIdPatterns = compileAutogeneratedIdPatterns(remote.autogeneratedIdPatterns, logger);
80
+ }
81
+ if (Array.isArray(remote.unstableClassPatterns)) {
82
+ resolved.unstableClassPatterns = compileUnstableClassPatterns(remote.unstableClassPatterns, logger);
83
+ }
84
+ resolved.maxAncestorWalkDepth = clampDepth(remote.maxAncestorWalkDepth);
85
+ return resolved;
86
+ }
87
+ /**
88
+ * Coerce a remote-supplied depth value into the runtime contract:
89
+ * - undefined / non-number / NaN / Infinity / <= 0 → undefined (no limit)
90
+ * - positive finite number → floor()'d integer
91
+ */
92
+ function clampDepth(depth) {
93
+ if (typeof depth !== 'number')
94
+ return undefined;
95
+ if (!Number.isFinite(depth))
96
+ return undefined;
97
+ if (depth <= 0)
98
+ return undefined;
99
+ return Math.floor(depth);
100
+ }
101
+ function cloneDefaults() {
102
+ return {
103
+ enabled: DEFAULT_RESOLVED_CONFIG.enabled,
104
+ explicitTrackingAttribute: DEFAULT_RESOLVED_CONFIG.explicitTrackingAttribute,
105
+ autogeneratedIdPatterns: __spreadArray([], __read(DEFAULT_RESOLVED_CONFIG.autogeneratedIdPatterns), false),
106
+ unstableClassPatterns: __spreadArray([], __read(DEFAULT_RESOLVED_CONFIG.unstableClassPatterns), false),
107
+ maxAncestorWalkDepth: DEFAULT_RESOLVED_CONFIG.maxAncestorWalkDepth,
108
+ };
109
+ }
110
+ //# sourceMappingURL=resolve-config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve-config.js","sourceRoot":"","sources":["../../../src/config/resolve-config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;;AAGH,OAAO,EACL,iCAAiC,EACjC,OAAO,IAAI,8BAA8B,GAC1C,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,+BAA+B,EAAE,OAAO,IAAI,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAExH;;;;GAIG;AACH,MAAM,CAAC,IAAM,uBAAuB,GAAqC,MAAM,CAAC,MAAM,CAAC;IACrF,wEAAwE;IACxE,kDAAkD;IAClD,OAAO,EAAE,KAAK;IACd,yBAAyB,EAAE,mBAAmB;IAC9C,uBAAuB,2BAAM,iCAAiC,SAAC;IAC/D,qBAAqB,2BAAM,+BAA+B,SAAC;IAC3D,oBAAoB,EAAE,SAAS;CAChC,CAAC,CAAC;AAEH;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,qBAAqB,CACnC,MAAoC,EACpC,MAA8B;IAE9B,IAAI,CAAC,MAAM,EAAE;QACX,sEAAsE;QACtE,2CAA2C;QAC3C,OAAO,aAAa,EAAE,CAAC;KACxB;IAED,IAAM,QAAQ,GAA2B,aAAa,EAAE,CAAC;IAEzD,IAAI,OAAO,MAAM,CAAC,OAAO,KAAK,SAAS,EAAE;QACvC,QAAQ,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;KACnC;IAED,IAAI,OAAO,MAAM,CAAC,yBAAyB,KAAK,QAAQ,IAAI,MAAM,CAAC,yBAAyB,KAAK,EAAE,EAAE;QACnG,QAAQ,CAAC,yBAAyB,GAAG,MAAM,CAAC,yBAAyB,CAAC;KACvE;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,uBAAuB,CAAC,EAAE;QACjD,QAAQ,CAAC,uBAAuB,GAAG,8BAA8B,CAAC,MAAM,CAAC,uBAAuB,EAAE,MAAM,CAAC,CAAC;KAC3G;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,qBAAqB,CAAC,EAAE;QAC/C,QAAQ,CAAC,qBAAqB,GAAG,4BAA4B,CAAC,MAAM,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC;KACrG;IAED,QAAQ,CAAC,oBAAoB,GAAG,UAAU,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC;IAExE,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;GAIG;AACH,SAAS,UAAU,CAAC,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,uBAAuB,CAAC,OAAO;QACxC,yBAAyB,EAAE,uBAAuB,CAAC,yBAAyB;QAC5E,uBAAuB,2BAAM,uBAAuB,CAAC,uBAAuB,SAAC;QAC7E,qBAAqB,2BAAM,uBAAuB,CAAC,qBAAqB,SAAC;QACzE,oBAAoB,EAAE,uBAAuB,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"]}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Engine factory — composes the strategy chain (via `runOrchestrator`) with
3
+ * the safety-net fallback (`fallbackCssPath`) behind a single `SelectorEngine`
4
+ * interface.
5
+ *
6
+ * This is the surface every consumer talks to:
7
+ *
8
+ * - autocapture SDK plugin → instantiates one engine per init() call,
9
+ * wires it into the click handler, and forwards remote-config updates
10
+ * via `updateConfig`.
11
+ * - app.amplitude.com tagging UI → fetches the customer's remote config
12
+ * out-of-band and stands up a transient engine to compute selectors for
13
+ * elements the user clicks in the iframe.
14
+ * - Chrome extension visual tagger → reads the customer's already-live
15
+ * engine off `window.amplitude.elementSelector` (when present) and
16
+ * subscribes to `onConfigChange` so the extension's preview stays in
17
+ * sync with the customer's runtime config.
18
+ *
19
+ * The factory deliberately takes a pre-resolved `ResolvedSelectorConfig` rather
20
+ * than the raw remote payload — config resolution is a separate concern handled
21
+ * by `resolveSelectorConfig`, and keeping it out of the engine constructor lets
22
+ * dashboard / extension consumers stand up an engine from a static snapshot
23
+ * without re-running the full resolver.
24
+ *
25
+ * See the design doc:
26
+ * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
27
+ */
28
+ import { ElementSelectorLogger, ResolvedSelectorConfig, SelectorEngine } from './types';
29
+ import { OrchestratorOptions } from './orchestrator';
30
+ export interface CreateSelectorEngineOptions {
31
+ /** Optional document or shadow root for uniqueness checks. Defaults per-call to the target's owner document. */
32
+ scope?: ParentNode;
33
+ /** Optional override of the strategy chain. Primarily for testing / dashboard ad-hoc runs. */
34
+ strategies?: OrchestratorOptions['strategies'];
35
+ /**
36
+ * Optional logger threaded through the orchestrator and the subscriber-fan-out
37
+ * inside `updateConfig`. When provided, the engine surfaces malformed
38
+ * selectors (`debug`) and listener exceptions (`warn`); when absent it stays
39
+ * silent — preserving the legacy "fire-and-forget" semantics existing
40
+ * consumers may rely on.
41
+ */
42
+ logger?: ElementSelectorLogger;
43
+ }
44
+ /**
45
+ * Build a `SelectorEngine` bound to the supplied config.
46
+ *
47
+ * The returned engine is independent — calling the factory twice yields two
48
+ * engines with separate config state and separate subscriber lists. This is the
49
+ * shape the autocapture plugin wants (one engine per SDK instance) and the
50
+ * shape the Chrome extension consumes off the page (the extension reads, never
51
+ * writes).
52
+ */
53
+ export declare function createSelectorEngine(initialConfig: ResolvedSelectorConfig, options?: CreateSelectorEngineOptions): SelectorEngine;
54
+ //# sourceMappingURL=engine.d.ts.map
@@ -0,0 +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,CAoFhB"}
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Engine factory — composes the strategy chain (via `runOrchestrator`) with
3
+ * the safety-net fallback (`fallbackCssPath`) behind a single `SelectorEngine`
4
+ * interface.
5
+ *
6
+ * This is the surface every consumer talks to:
7
+ *
8
+ * - autocapture SDK plugin → instantiates one engine per init() call,
9
+ * wires it into the click handler, and forwards remote-config updates
10
+ * via `updateConfig`.
11
+ * - app.amplitude.com tagging UI → fetches the customer's remote config
12
+ * out-of-band and stands up a transient engine to compute selectors for
13
+ * elements the user clicks in the iframe.
14
+ * - Chrome extension visual tagger → reads the customer's already-live
15
+ * engine off `window.amplitude.elementSelector` (when present) and
16
+ * subscribes to `onConfigChange` so the extension's preview stays in
17
+ * sync with the customer's runtime config.
18
+ *
19
+ * The factory deliberately takes a pre-resolved `ResolvedSelectorConfig` rather
20
+ * than the raw remote payload — config resolution is a separate concern handled
21
+ * by `resolveSelectorConfig`, and keeping it out of the engine constructor lets
22
+ * dashboard / extension consumers stand up an engine from a static snapshot
23
+ * without re-running the full resolver.
24
+ *
25
+ * See the design doc:
26
+ * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
27
+ */
28
+ import { __values } from "tslib";
29
+ import { runOrchestrator } from './orchestrator';
30
+ import { fallbackCssPath } from './fallback-css-path';
31
+ import { legacyCssPath } from './legacy-css-path';
32
+ /**
33
+ * Build a `SelectorEngine` bound to the supplied config.
34
+ *
35
+ * The returned engine is independent — calling the factory twice yields two
36
+ * engines with separate config state and separate subscriber lists. This is the
37
+ * shape the autocapture plugin wants (one engine per SDK instance) and the
38
+ * shape the Chrome extension consumes off the page (the extension reads, never
39
+ * writes).
40
+ */
41
+ export function createSelectorEngine(initialConfig, options) {
42
+ if (options === void 0) { options = {}; }
43
+ var config = initialConfig;
44
+ var subscribers = new Set();
45
+ var logger = options.logger;
46
+ var orchestratorOptions = {
47
+ strategies: options.strategies,
48
+ scope: options.scope,
49
+ logger: logger,
50
+ };
51
+ return {
52
+ generate: function (el) {
53
+ var _a, _b;
54
+ // Kill switch: when the customer's remote config has the engine
55
+ // disabled (the default for orgs that haven't opted in), emit the same
56
+ // Chromium-derived selector autocapture has shipped since before the
57
+ // strategy chain existed. This is what makes "flip enabled back to
58
+ // false" a one-config-fetch revert for both the SDK and the dashboard —
59
+ // they both go through this entry point now.
60
+ if (!config.enabled) {
61
+ return safeLegacyCssPath(el);
62
+ }
63
+ // Engine path: try the strategy chain, then the hardened fallback. Both
64
+ // are wrapped so a runtime exception (malformed config slipped past the
65
+ // resolver, browser API quirks, a bad scope) still produces a usable
66
+ // selector. Without this, an autocapture click handler could throw
67
+ // mid-flow and the customer would silently lose the event — a worse
68
+ // outcome than emitting a less-stable selector.
69
+ try {
70
+ var composed = runOrchestrator(el, config, orchestratorOptions);
71
+ if (composed !== null) {
72
+ return composed;
73
+ }
74
+ return fallbackCssPath(el, config, { scope: (_b = (_a = options.scope) !== null && _a !== void 0 ? _a : el.ownerDocument) !== null && _b !== void 0 ? _b : document });
75
+ }
76
+ catch (e) {
77
+ var message = e instanceof Error ? e.message : String(e);
78
+ logger === null || logger === void 0 ? void 0 : logger.warn("@amplitude/element-selector: strategy chain threw \u2014 falling back to legacy cssPath: ".concat(message));
79
+ return safeLegacyCssPath(el);
80
+ }
81
+ },
82
+ getConfig: function () {
83
+ return config;
84
+ },
85
+ updateConfig: function (next) {
86
+ var e_1, _a;
87
+ config = next;
88
+ try {
89
+ // Notify subscribers in insertion order. Errors thrown by individual
90
+ // subscribers are isolated so one bad listener can't break the others —
91
+ // the extension's listener is the canonical consumer here and we don't
92
+ // want SDK-side changes to cascade-fail because of an extension bug.
93
+ for (var subscribers_1 = __values(subscribers), subscribers_1_1 = subscribers_1.next(); !subscribers_1_1.done; subscribers_1_1 = subscribers_1.next()) {
94
+ var cb = subscribers_1_1.value;
95
+ try {
96
+ cb(next);
97
+ }
98
+ catch (e) {
99
+ var message = e instanceof Error ? e.message : String(e);
100
+ logger === null || logger === void 0 ? void 0 : logger.warn("@amplitude/element-selector: onConfigChange subscriber threw \u2014 ".concat(message));
101
+ }
102
+ }
103
+ }
104
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
105
+ finally {
106
+ try {
107
+ if (subscribers_1_1 && !subscribers_1_1.done && (_a = subscribers_1.return)) _a.call(subscribers_1);
108
+ }
109
+ finally { if (e_1) throw e_1.error; }
110
+ }
111
+ },
112
+ onConfigChange: function (cb) {
113
+ subscribers.add(cb);
114
+ return function () {
115
+ subscribers.delete(cb);
116
+ };
117
+ },
118
+ };
119
+ // Local wrapper so a thrown error in the legacy walker (extremely unlikely
120
+ // — Element inputs only — but defensible if a host environment is missing
121
+ // `CSS.escape` or `Node` constants) doesn't escape `generate` and crash the
122
+ // caller. Returns the empty string in that pathological case; consumers
123
+ // already coalesce empty results to a sentinel.
124
+ function safeLegacyCssPath(el) {
125
+ try {
126
+ return legacyCssPath(el);
127
+ }
128
+ catch (e) {
129
+ var message = e instanceof Error ? e.message : String(e);
130
+ logger === null || logger === void 0 ? void 0 : logger.warn("@amplitude/element-selector: legacyCssPath threw \u2014 emitting empty selector: ".concat(message));
131
+ return '';
132
+ }
133
+ }
134
+ }
135
+ //# sourceMappingURL=engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * Engine factory — composes the strategy chain (via `runOrchestrator`) with\n * the safety-net fallback (`fallbackCssPath`) behind a single `SelectorEngine`\n * interface.\n *\n * This is the surface every consumer talks to:\n *\n * - autocapture SDK plugin → instantiates one engine per init() call,\n * wires it into the click handler, and forwards remote-config updates\n * via `updateConfig`.\n * - app.amplitude.com tagging UI → fetches the customer's remote config\n * out-of-band and stands up a transient engine to compute selectors for\n * elements the user clicks in the iframe.\n * - Chrome extension visual tagger → reads the customer's already-live\n * engine off `window.amplitude.elementSelector` (when present) and\n * subscribes to `onConfigChange` so the extension's preview stays in\n * sync with the customer's runtime config.\n *\n * The factory deliberately takes a pre-resolved `ResolvedSelectorConfig` rather\n * than the raw remote payload — config resolution is a separate concern handled\n * by `resolveSelectorConfig`, and keeping it out of the engine constructor lets\n * dashboard / extension consumers stand up an engine from a static snapshot\n * without re-running the full resolver.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { ElementSelectorLogger, ResolvedSelectorConfig, SelectorEngine } from './types';\nimport { runOrchestrator, OrchestratorOptions } from './orchestrator';\nimport { fallbackCssPath } from './fallback-css-path';\nimport { legacyCssPath } from './legacy-css-path';\n\nexport interface CreateSelectorEngineOptions {\n /** Optional document or shadow root for uniqueness checks. Defaults per-call to the target's owner document. */\n scope?: ParentNode;\n /** Optional override of the strategy chain. Primarily for testing / dashboard ad-hoc runs. */\n strategies?: OrchestratorOptions['strategies'];\n /**\n * Optional logger threaded through the orchestrator and the subscriber-fan-out\n * inside `updateConfig`. When provided, the engine surfaces malformed\n * selectors (`debug`) and listener exceptions (`warn`); when absent it stays\n * silent — preserving the legacy \"fire-and-forget\" semantics existing\n * consumers may rely on.\n */\n logger?: ElementSelectorLogger;\n}\n\n/**\n * Build a `SelectorEngine` bound to the supplied config.\n *\n * The returned engine is independent — calling the factory twice yields two\n * engines with separate config state and separate subscriber lists. This is the\n * shape the autocapture plugin wants (one engine per SDK instance) and the\n * shape the Chrome extension consumes off the page (the extension reads, never\n * writes).\n */\nexport function createSelectorEngine(\n initialConfig: ResolvedSelectorConfig,\n options: CreateSelectorEngineOptions = {},\n): SelectorEngine {\n let config: ResolvedSelectorConfig = initialConfig;\n const subscribers = new Set<(config: ResolvedSelectorConfig) => void>();\n const logger = options.logger;\n\n const orchestratorOptions: OrchestratorOptions = {\n strategies: options.strategies,\n scope: options.scope,\n logger,\n };\n\n return {\n generate(el: Element): string {\n // Kill switch: when the customer's remote config has the engine\n // disabled (the default for orgs that haven't opted in), emit the same\n // Chromium-derived selector autocapture has shipped since before the\n // strategy chain existed. This is what makes \"flip enabled back to\n // false\" a one-config-fetch revert for both the SDK and the dashboard —\n // they both go through this entry point now.\n if (!config.enabled) {\n return safeLegacyCssPath(el);\n }\n\n // Engine path: try the strategy chain, then the hardened fallback. Both\n // are wrapped so a runtime exception (malformed config slipped past the\n // resolver, browser API quirks, a bad scope) still produces a usable\n // selector. Without this, an autocapture click handler could throw\n // mid-flow and the customer would silently lose the event — a worse\n // outcome than emitting a less-stable selector.\n try {\n const composed = runOrchestrator(el, config, orchestratorOptions);\n if (composed !== null) {\n return composed;\n }\n return fallbackCssPath(el, config, { scope: options.scope ?? el.ownerDocument ?? document });\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: strategy chain threw — falling back to legacy cssPath: ${message}`);\n return safeLegacyCssPath(el);\n }\n },\n\n getConfig(): Readonly<ResolvedSelectorConfig> {\n return config;\n },\n\n updateConfig(next: ResolvedSelectorConfig): void {\n config = next;\n // Notify subscribers in insertion order. Errors thrown by individual\n // subscribers are isolated so one bad listener can't break the others —\n // the extension's listener is the canonical consumer here and we don't\n // want SDK-side changes to cascade-fail because of an extension bug.\n for (const cb of subscribers) {\n try {\n cb(next);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: onConfigChange subscriber threw — ${message}`);\n }\n }\n },\n\n onConfigChange(cb: (config: ResolvedSelectorConfig) => void): () => void {\n subscribers.add(cb);\n return () => {\n subscribers.delete(cb);\n };\n },\n };\n\n // Local wrapper so a thrown error in the legacy walker (extremely unlikely\n // — Element inputs only — but defensible if a host environment is missing\n // `CSS.escape` or `Node` constants) doesn't escape `generate` and crash the\n // caller. Returns the empty string in that pathological case; consumers\n // already coalesce empty results to a sentinel.\n function safeLegacyCssPath(el: Element): string {\n try {\n return legacyCssPath(el);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: legacyCssPath threw — emitting empty selector: ${message}`);\n return '';\n }\n }\n}\n"]}
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Fallback CSS-path walker — the safety net for the v1 element-selector
3
+ * algorithm.
4
+ *
5
+ * When the orchestrator's strategy chain finds nothing usable across the full
6
+ * ancestor walk, the engine invokes this fallback. It produces a positional
7
+ * selector by walking up from the target to <html>, expressing each step as
8
+ * either an id anchor (when one survives the autogen filter) or a
9
+ * `tag:nth-of-type(n)` step.
10
+ *
11
+ * Key differences from the legacy autocapture `cssPath`:
12
+ *
13
+ * 1. Ids are filtered through `getStableId`, which honors the
14
+ * explicit-tracking-attribute suppression signal AND the autogenerated-id
15
+ * pattern pack. The legacy `cssPath` would happily anchor on `id=":r5:"`
16
+ * and produce selectors that never match across page loads.
17
+ *
18
+ * 2. Classes — when they're used at all for sibling disambiguation — are
19
+ * filtered through `filterClasses` against the unstable-class pattern
20
+ * pack. The current v1 implementation here doesn't emit classes (we lean
21
+ * entirely on `:nth-of-type` for sibling disambiguation), but the
22
+ * filtering helper is wired through so future iterations can opt back in
23
+ * surgically without re-deriving the policy.
24
+ *
25
+ * 3. A unique anchor id terminates the walk early — once we hit `body#main`,
26
+ * we don't need to keep walking up to `<html>`.
27
+ *
28
+ * 4. Ambiguous id anchors are skipped. Duplicate ids are invalid HTML but
29
+ * common enough in the wild that fallback must not emit selectors that
30
+ * resolve to the wrong target.
31
+ *
32
+ * Output format mirrors the orchestrator's output: `<anchor> > <descent>`.
33
+ * When no usable id is found anywhere on the walk, the fallback emits a
34
+ * pure-positional selector rooted at `html`.
35
+ *
36
+ * See the design doc:
37
+ * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
38
+ */
39
+ import { ResolvedSelectorConfig } from './types';
40
+ export interface FallbackCssPathOptions {
41
+ /** Document or shadow root used for uniqueness checks. Defaults to the target's owner document. */
42
+ scope?: ParentNode;
43
+ }
44
+ /**
45
+ * Build a positional CSS selector for `el`, using stable ids as anchors when
46
+ * available and falling back to `tag:nth-of-type(n)` for disambiguation.
47
+ *
48
+ * Honors `config.maxAncestorWalkDepth` defensively — once the depth limit is
49
+ * reached, the walker stops and returns whatever it has built so far rooted at
50
+ * the deepest reached ancestor.
51
+ */
52
+ export declare function fallbackCssPath(el: Element, config: ResolvedSelectorConfig, options?: FallbackCssPathOptions): string;
53
+ //# sourceMappingURL=fallback-css-path.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Fallback CSS-path walker — the safety net for the v1 element-selector
3
+ * algorithm.
4
+ *
5
+ * When the orchestrator's strategy chain finds nothing usable across the full
6
+ * ancestor walk, the engine invokes this fallback. It produces a positional
7
+ * selector by walking up from the target to <html>, expressing each step as
8
+ * either an id anchor (when one survives the autogen filter) or a
9
+ * `tag:nth-of-type(n)` step.
10
+ *
11
+ * Key differences from the legacy autocapture `cssPath`:
12
+ *
13
+ * 1. Ids are filtered through `getStableId`, which honors the
14
+ * explicit-tracking-attribute suppression signal AND the autogenerated-id
15
+ * pattern pack. The legacy `cssPath` would happily anchor on `id=":r5:"`
16
+ * and produce selectors that never match across page loads.
17
+ *
18
+ * 2. Classes — when they're used at all for sibling disambiguation — are
19
+ * filtered through `filterClasses` against the unstable-class pattern
20
+ * pack. The current v1 implementation here doesn't emit classes (we lean
21
+ * entirely on `:nth-of-type` for sibling disambiguation), but the
22
+ * filtering helper is wired through so future iterations can opt back in
23
+ * surgically without re-deriving the policy.
24
+ *
25
+ * 3. A unique anchor id terminates the walk early — once we hit `body#main`,
26
+ * we don't need to keep walking up to `<html>`.
27
+ *
28
+ * 4. Ambiguous id anchors are skipped. Duplicate ids are invalid HTML but
29
+ * common enough in the wild that fallback must not emit selectors that
30
+ * resolve to the wrong target.
31
+ *
32
+ * Output format mirrors the orchestrator's output: `<anchor> > <descent>`.
33
+ * When no usable id is found anywhere on the walk, the fallback emits a
34
+ * pure-positional selector rooted at `html`.
35
+ *
36
+ * See the design doc:
37
+ * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
38
+ */
39
+ import { __read, __spreadArray } from "tslib";
40
+ import { getStableId } from './helpers/get-stable-id';
41
+ import { escapeIdForCss } from './helpers/escape-id';
42
+ /**
43
+ * Build a positional CSS selector for `el`, using stable ids as anchors when
44
+ * available and falling back to `tag:nth-of-type(n)` for disambiguation.
45
+ *
46
+ * Honors `config.maxAncestorWalkDepth` defensively — once the depth limit is
47
+ * reached, the walker stops and returns whatever it has built so far rooted at
48
+ * the deepest reached ancestor.
49
+ */
50
+ export function fallbackCssPath(el, config, options) {
51
+ var _a, _b;
52
+ if (options === void 0) { options = {}; }
53
+ var scope = (_b = (_a = options.scope) !== null && _a !== void 0 ? _a : el.ownerDocument) !== null && _b !== void 0 ? _b : document;
54
+ var segments = [];
55
+ var cursor = el;
56
+ var depth = 0;
57
+ while (cursor !== null) {
58
+ if (config.maxAncestorWalkDepth !== undefined && depth > config.maxAncestorWalkDepth) {
59
+ break;
60
+ }
61
+ var id = getStableId(cursor, config);
62
+ if (id !== null) {
63
+ // Anchor format mirrors the stableId strategy: `tag#id` with the id
64
+ // CSS-escaped. Only terminate if the composed selector uniquely resolves
65
+ // to the target; duplicate ids should fall through to positional steps.
66
+ var anchorSegment = "".concat(cursor.tagName.toLowerCase(), "#").concat(escapeIdForCss(id));
67
+ var candidate = __spreadArray([anchorSegment], __read(segments), false).join(' > ');
68
+ if (isUniqueMatch(scope, candidate, el)) {
69
+ return candidate;
70
+ }
71
+ }
72
+ segments.unshift(stepFor(cursor));
73
+ cursor = cursor.parentElement;
74
+ depth += 1;
75
+ }
76
+ // Walked all the way to the document root without finding an id. The first
77
+ // segment is whatever `<html>` produced (which is just `html` since it has
78
+ // no parent and no same-tag siblings).
79
+ return segments.join(' > ');
80
+ }
81
+ /**
82
+ * Build a single step. For an element with a parent: `tag:nth-of-type(n)`.
83
+ * For a root element (no parent — i.e. <html>): just `tag`.
84
+ *
85
+ * Class-based disambiguation is intentionally not emitted in v1 — see the
86
+ * design doc, "Why we don't use classes for sibling disambiguation". The
87
+ * `filterClasses` helper is imported in the package for future iterations.
88
+ */
89
+ function stepFor(el) {
90
+ var tag = el.tagName.toLowerCase();
91
+ var parent = el.parentElement;
92
+ if (parent === null) {
93
+ return tag;
94
+ }
95
+ var index = sameTypeIndex(el, parent);
96
+ return "".concat(tag, ":nth-of-type(").concat(index, ")");
97
+ }
98
+ function sameTypeIndex(el, parent) {
99
+ var count = 0;
100
+ for (var i = 0; i < parent.children.length; i++) {
101
+ var sibling = parent.children[i];
102
+ if (sibling.tagName === el.tagName) {
103
+ count += 1;
104
+ if (sibling === el)
105
+ return count;
106
+ }
107
+ }
108
+ return 1;
109
+ }
110
+ function isUniqueMatch(scope, selector, el) {
111
+ var matches;
112
+ try {
113
+ matches = scope.querySelectorAll(selector);
114
+ }
115
+ catch (_e) {
116
+ return false;
117
+ }
118
+ return matches.length === 1 && matches[0] === el;
119
+ }
120
+ //# sourceMappingURL=fallback-css-path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fallback-css-path.js","sourceRoot":"","sources":["../../src/fallback-css-path.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;;AAGH,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAOrD;;;;;;;GAOG;AACH,MAAM,UAAU,eAAe,CAC7B,EAAW,EACX,MAA8B,EAC9B,OAAoC;;IAApC,wBAAA,EAAA,YAAoC;IAEpC,IAAM,KAAK,GAAe,MAAA,MAAA,OAAO,CAAC,KAAK,mCAAI,EAAE,CAAC,aAAa,mCAAI,QAAQ,CAAC;IACxE,IAAM,QAAQ,GAAa,EAAE,CAAC;IAC9B,IAAI,MAAM,GAAmB,EAAE,CAAC;IAChC,IAAI,KAAK,GAAG,CAAC,CAAC;IAEd,OAAO,MAAM,KAAK,IAAI,EAAE;QACtB,IAAI,MAAM,CAAC,oBAAoB,KAAK,SAAS,IAAI,KAAK,GAAG,MAAM,CAAC,oBAAoB,EAAE;YACpF,MAAM;SACP;QAED,IAAM,EAAE,GAAG,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACvC,IAAI,EAAE,KAAK,IAAI,EAAE;YACf,oEAAoE;YACpE,yEAAyE;YACzE,wEAAwE;YACxE,IAAM,aAAa,GAAG,UAAG,MAAM,CAAC,OAAO,CAAC,WAAW,EAAE,cAAI,cAAc,CAAC,EAAE,CAAC,CAAE,CAAC;YAC9E,IAAM,SAAS,GAAG,eAAC,aAAa,UAAK,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,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;QAClC,MAAM,GAAG,MAAM,CAAC,aAAa,CAAC;QAC9B,KAAK,IAAI,CAAC,CAAC;KACZ;IAED,2EAA2E;IAC3E,2EAA2E;IAC3E,uCAAuC;IACvC,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,OAAO,CAAC,EAAW;IAC1B,IAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC;IACrC,IAAM,MAAM,GAAG,EAAE,CAAC,aAAa,CAAC;IAChC,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,OAAO,GAAG,CAAC;KACZ;IACD,IAAM,KAAK,GAAG,aAAa,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;IACxC,OAAO,UAAG,GAAG,0BAAgB,KAAK,MAAG,CAAC;AACxC,CAAC;AAED,SAAS,aAAa,CAAC,EAAW,EAAE,MAAe;IACjD,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QAC/C,IAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QACnC,IAAI,OAAO,CAAC,OAAO,KAAK,EAAE,CAAC,OAAO,EAAE;YAClC,KAAK,IAAI,CAAC,CAAC;YACX,IAAI,OAAO,KAAK,EAAE;gBAAE,OAAO,KAAK,CAAC;SAClC;KACF;IACD,OAAO,CAAC,CAAC;AACX,CAAC;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 { 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"]}