@amplitude/element-selector 0.0.1 → 0.1.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 (115) 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 +104 -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/helpers/describe-relative.d.ts +28 -0
  16. package/lib/cjs/helpers/describe-relative.d.ts.map +1 -0
  17. package/lib/cjs/helpers/describe-relative.js +60 -0
  18. package/lib/cjs/helpers/describe-relative.js.map +1 -0
  19. package/lib/cjs/helpers/escape-css-identifier.d.ts +8 -0
  20. package/lib/cjs/helpers/escape-css-identifier.d.ts.map +1 -0
  21. package/lib/cjs/helpers/escape-css-identifier.js +50 -0
  22. package/lib/cjs/helpers/escape-css-identifier.js.map +1 -0
  23. package/lib/cjs/helpers/escape-id.d.ts +3 -0
  24. package/lib/cjs/helpers/escape-id.d.ts.map +1 -0
  25. package/lib/cjs/helpers/escape-id.js +10 -0
  26. package/lib/cjs/helpers/escape-id.js.map +1 -0
  27. package/lib/cjs/helpers/get-stable-id.d.ts +23 -0
  28. package/lib/cjs/helpers/get-stable-id.d.ts.map +1 -0
  29. package/lib/cjs/helpers/get-stable-id.js +44 -0
  30. package/lib/cjs/helpers/get-stable-id.js.map +1 -0
  31. package/lib/cjs/index.d.ts +29 -0
  32. package/lib/cjs/index.d.ts.map +1 -0
  33. package/lib/cjs/index.js +53 -0
  34. package/lib/cjs/index.js.map +1 -0
  35. package/lib/cjs/orchestrator.d.ts +61 -0
  36. package/lib/cjs/orchestrator.d.ts.map +1 -0
  37. package/lib/cjs/orchestrator.js +140 -0
  38. package/lib/cjs/orchestrator.js.map +1 -0
  39. package/lib/cjs/patterns/autogenerated-ids.d.ts +37 -0
  40. package/lib/cjs/patterns/autogenerated-ids.d.ts.map +1 -0
  41. package/lib/cjs/patterns/autogenerated-ids.js +102 -0
  42. package/lib/cjs/patterns/autogenerated-ids.js.map +1 -0
  43. package/lib/cjs/patterns/unstable-classes.d.ts +48 -0
  44. package/lib/cjs/patterns/unstable-classes.d.ts.map +1 -0
  45. package/lib/cjs/patterns/unstable-classes.js +155 -0
  46. package/lib/cjs/patterns/unstable-classes.js.map +1 -0
  47. package/lib/cjs/strategies/explicit-tracking-attribute.d.ts +22 -0
  48. package/lib/cjs/strategies/explicit-tracking-attribute.d.ts.map +1 -0
  49. package/lib/cjs/strategies/explicit-tracking-attribute.js +36 -0
  50. package/lib/cjs/strategies/explicit-tracking-attribute.js.map +1 -0
  51. package/lib/cjs/strategies/stable-id.d.ts +14 -0
  52. package/lib/cjs/strategies/stable-id.d.ts.map +1 -0
  53. package/lib/cjs/strategies/stable-id.js +27 -0
  54. package/lib/cjs/strategies/stable-id.js.map +1 -0
  55. package/lib/cjs/types.d.ts +100 -0
  56. package/lib/cjs/types.d.ts.map +1 -0
  57. package/lib/cjs/types.js +13 -0
  58. package/lib/cjs/types.js.map +1 -0
  59. package/lib/esm/config/resolve-config.d.ts +56 -0
  60. package/lib/esm/config/resolve-config.d.ts.map +1 -0
  61. package/lib/esm/config/resolve-config.js +110 -0
  62. package/lib/esm/config/resolve-config.js.map +1 -0
  63. package/lib/esm/engine.d.ts +54 -0
  64. package/lib/esm/engine.d.ts.map +1 -0
  65. package/lib/esm/engine.js +100 -0
  66. package/lib/esm/engine.js.map +1 -0
  67. package/lib/esm/fallback-css-path.d.ts +53 -0
  68. package/lib/esm/fallback-css-path.d.ts.map +1 -0
  69. package/lib/esm/fallback-css-path.js +120 -0
  70. package/lib/esm/fallback-css-path.js.map +1 -0
  71. package/lib/esm/helpers/describe-relative.d.ts +28 -0
  72. package/lib/esm/helpers/describe-relative.d.ts.map +1 -0
  73. package/lib/esm/helpers/describe-relative.js +56 -0
  74. package/lib/esm/helpers/describe-relative.js.map +1 -0
  75. package/lib/esm/helpers/escape-css-identifier.d.ts +8 -0
  76. package/lib/esm/helpers/escape-css-identifier.d.ts.map +1 -0
  77. package/lib/esm/helpers/escape-css-identifier.js +46 -0
  78. package/lib/esm/helpers/escape-css-identifier.js.map +1 -0
  79. package/lib/esm/helpers/escape-id.d.ts +3 -0
  80. package/lib/esm/helpers/escape-id.d.ts.map +1 -0
  81. package/lib/esm/helpers/escape-id.js +6 -0
  82. package/lib/esm/helpers/escape-id.js.map +1 -0
  83. package/lib/esm/helpers/get-stable-id.d.ts +23 -0
  84. package/lib/esm/helpers/get-stable-id.d.ts.map +1 -0
  85. package/lib/esm/helpers/get-stable-id.js +40 -0
  86. package/lib/esm/helpers/get-stable-id.js.map +1 -0
  87. package/lib/esm/index.d.ts +29 -0
  88. package/lib/esm/index.d.ts.map +1 -0
  89. package/lib/esm/index.js +34 -0
  90. package/lib/esm/index.js.map +1 -0
  91. package/lib/esm/orchestrator.d.ts +61 -0
  92. package/lib/esm/orchestrator.d.ts.map +1 -0
  93. package/lib/esm/orchestrator.js +136 -0
  94. package/lib/esm/orchestrator.js.map +1 -0
  95. package/lib/esm/patterns/autogenerated-ids.d.ts +37 -0
  96. package/lib/esm/patterns/autogenerated-ids.d.ts.map +1 -0
  97. package/lib/esm/patterns/autogenerated-ids.js +97 -0
  98. package/lib/esm/patterns/autogenerated-ids.js.map +1 -0
  99. package/lib/esm/patterns/unstable-classes.d.ts +48 -0
  100. package/lib/esm/patterns/unstable-classes.d.ts.map +1 -0
  101. package/lib/esm/patterns/unstable-classes.js +150 -0
  102. package/lib/esm/patterns/unstable-classes.js.map +1 -0
  103. package/lib/esm/strategies/explicit-tracking-attribute.d.ts +22 -0
  104. package/lib/esm/strategies/explicit-tracking-attribute.d.ts.map +1 -0
  105. package/lib/esm/strategies/explicit-tracking-attribute.js +33 -0
  106. package/lib/esm/strategies/explicit-tracking-attribute.js.map +1 -0
  107. package/lib/esm/strategies/stable-id.d.ts +14 -0
  108. package/lib/esm/strategies/stable-id.d.ts.map +1 -0
  109. package/lib/esm/strategies/stable-id.js +24 -0
  110. package/lib/esm/strategies/stable-id.js.map +1 -0
  111. package/lib/esm/types.d.ts +100 -0
  112. package/lib/esm/types.d.ts.map +1 -0
  113. package/lib/esm/types.js +12 -0
  114. package/lib/esm/types.js.map +1 -0
  115. package/package.json +40 -5
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Orchestrator — the entry point for the v1 element-selector algorithm.
3
+ *
4
+ * Given a click target, the orchestrator walks from the target up through its
5
+ * ancestors and tries each registered strategy at each level. The first
6
+ * strategy that returns a non-null candidate (and produces a selector that
7
+ * resolves uniquely under the scope) wins; the trail of intermediate elements
8
+ * between the anchor and the original target is then expressed as a positional
9
+ * descent via `describeRelative`.
10
+ *
11
+ * Two-pass design: every ancestor is tried under the `explicitTrackingAttribute`
12
+ * strategy first, then the entire walk repeats with `stableId`. This ordering
13
+ * means an explicit anchor anywhere up the tree always beats a stable id deeper
14
+ * down — the design doc describes this as the "customer intent overrides
15
+ * structural inference" rule.
16
+ *
17
+ * The orchestrator does not own the fallback. When no strategy + walk produces
18
+ * a unique selector, it returns `null` and the engine wires the
19
+ * `fallback-css-path` path in instead. Keeping the fallback outside the
20
+ * orchestrator keeps the strategy chain testable in isolation.
21
+ *
22
+ * See the design doc:
23
+ * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
24
+ */
25
+ import { __values } from "tslib";
26
+ import { explicitTrackingAttribute } from './strategies/explicit-tracking-attribute';
27
+ import { stableId as stableIdStrategy } from './strategies/stable-id';
28
+ import { describeRelative } from './helpers/describe-relative';
29
+ /**
30
+ * Default strategy chain in priority order. Used by the engine factory when the
31
+ * caller doesn't provide an explicit list. Exported for diagnostics — tests
32
+ * import this so they don't have to duplicate the list.
33
+ */
34
+ export var DEFAULT_STRATEGIES = [explicitTrackingAttribute, stableIdStrategy];
35
+ /**
36
+ * Try to produce a CSS selector for `el` using the strategy chain.
37
+ *
38
+ * Returns the composed selector string on success, or `null` if every strategy
39
+ * declined at every walked ancestor. Callers (the engine) treat `null` as the
40
+ * signal to invoke the fallback walker.
41
+ *
42
+ * Selector format on success:
43
+ *
44
+ * - Anchor only (target itself was an anchor): `<anchor-selector>`
45
+ * - Anchor + trail (anchor was an ancestor): `<anchor-selector> > <descent>`
46
+ *
47
+ * Where `<anchor-selector>` is whatever the winning strategy returned for the
48
+ * anchor element (e.g. `[data-amp-track-id="login-form"]` or `div#hero`), and
49
+ * `<descent>` is `describeRelative(anchor, trail)`.
50
+ */
51
+ export function runOrchestrator(el, config, options) {
52
+ var e_1, _a;
53
+ var _b, _c, _d;
54
+ if (options === void 0) { options = {}; }
55
+ var strategies = (_b = options.strategies) !== null && _b !== void 0 ? _b : DEFAULT_STRATEGIES;
56
+ var scope = (_d = (_c = options.scope) !== null && _c !== void 0 ? _c : el.ownerDocument) !== null && _d !== void 0 ? _d : document;
57
+ var ctx = { scope: scope, config: config };
58
+ var walk = collectWalk(el, config.maxAncestorWalkDepth);
59
+ try {
60
+ // Two-pass: try strategy[0] across the whole walk, then strategy[1], etc.
61
+ // This gives an "explicit anchor at any depth beats a structural anchor any
62
+ // depth" priority, which matches the design doc's "customer intent overrides
63
+ // structural inference" rule.
64
+ for (var strategies_1 = __values(strategies), strategies_1_1 = strategies_1.next(); !strategies_1_1.done; strategies_1_1 = strategies_1.next()) {
65
+ var strategy = strategies_1_1.value;
66
+ for (var i = 0; i < walk.length; i++) {
67
+ var anchor = walk[i];
68
+ var anchorSelector = strategy.try(anchor, ctx);
69
+ if (anchorSelector === null)
70
+ continue;
71
+ // Anchor was the target itself — no descent needed.
72
+ if (i === 0) {
73
+ if (isUniqueMatch(scope, anchorSelector, el, strategy.name, options.logger)) {
74
+ return anchorSelector;
75
+ }
76
+ continue;
77
+ }
78
+ // Anchor was an ancestor — descend back to the target through the trail.
79
+ var trail = walk.slice(0, i).reverse();
80
+ var descent = describeRelative(anchor, trail);
81
+ var composed = "".concat(anchorSelector, " > ").concat(descent);
82
+ if (isUniqueMatch(scope, composed, el, strategy.name, options.logger)) {
83
+ return composed;
84
+ }
85
+ }
86
+ }
87
+ }
88
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
89
+ finally {
90
+ try {
91
+ if (strategies_1_1 && !strategies_1_1.done && (_a = strategies_1.return)) _a.call(strategies_1);
92
+ }
93
+ finally { if (e_1) throw e_1.error; }
94
+ }
95
+ return null;
96
+ }
97
+ /**
98
+ * Build the walk array `[target, parent, grandparent, ...]`, stopping at
99
+ * `<html>` (or at the depth limit if configured). Excludes the document
100
+ * element's parent (which is the Document node and not an Element).
101
+ */
102
+ function collectWalk(el, maxDepth) {
103
+ var walk = [];
104
+ var cursor = el;
105
+ while (cursor !== null) {
106
+ walk.push(cursor);
107
+ if (maxDepth !== undefined && walk.length > maxDepth)
108
+ break;
109
+ cursor = cursor.parentElement;
110
+ }
111
+ return walk;
112
+ }
113
+ /**
114
+ * Check whether `selector` resolves to exactly `el` and no other element in
115
+ * `scope`. The strategies themselves don't run uniqueness checks — that's the
116
+ * orchestrator's job, so strategies stay pure transforms and stay testable in
117
+ * isolation.
118
+ *
119
+ * When the selector is malformed (which is a strategy bug rather than user
120
+ * input), we log at `debug` and return false rather than throwing. The log
121
+ * lets engineers diagnose a misbehaving strategy without the engine taking
122
+ * down whatever it's wired into.
123
+ */
124
+ function isUniqueMatch(scope, selector, el, strategyName, logger) {
125
+ var matches;
126
+ try {
127
+ matches = scope.querySelectorAll(selector);
128
+ }
129
+ catch (e) {
130
+ var message = e instanceof Error ? e.message : String(e);
131
+ logger === null || logger === void 0 ? void 0 : logger.debug("@amplitude/element-selector: strategy \"".concat(strategyName, "\" emitted a malformed selector \"").concat(selector, "\" (").concat(message, ")"));
132
+ return false;
133
+ }
134
+ return matches.length === 1 && matches[0] === el;
135
+ }
136
+ //# sourceMappingURL=orchestrator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orchestrator.js","sourceRoot":"","sources":["../../src/orchestrator.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * Orchestrator — the entry point for the v1 element-selector algorithm.\n *\n * Given a click target, the orchestrator walks from the target up through its\n * ancestors and tries each registered strategy at each level. The first\n * strategy that returns a non-null candidate (and produces a selector that\n * resolves uniquely under the scope) wins; the trail of intermediate elements\n * between the anchor and the original target is then expressed as a positional\n * descent via `describeRelative`.\n *\n * Two-pass design: every ancestor is tried under the `explicitTrackingAttribute`\n * strategy first, then the entire walk repeats with `stableId`. This ordering\n * means an explicit anchor anywhere up the tree always beats a stable id deeper\n * down — the design doc describes this as the \"customer intent overrides\n * structural inference\" rule.\n *\n * The orchestrator does not own the fallback. When no strategy + walk produces\n * a unique selector, it returns `null` and the engine wires the\n * `fallback-css-path` path in instead. Keeping the fallback outside the\n * orchestrator keeps the strategy chain testable in isolation.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { ElementSelectorLogger, ResolvedSelectorConfig, Strategy, StrategyContext } from './types';\nimport { explicitTrackingAttribute } from './strategies/explicit-tracking-attribute';\nimport { stableId as stableIdStrategy } from './strategies/stable-id';\nimport { describeRelative } from './helpers/describe-relative';\n\n/**\n * Default strategy chain in priority order. Used by the engine factory when the\n * caller doesn't provide an explicit list. Exported for diagnostics — tests\n * import this so they don't have to duplicate the list.\n */\nexport const DEFAULT_STRATEGIES: ReadonlyArray<Strategy> = [explicitTrackingAttribute, stableIdStrategy];\n\nexport interface OrchestratorOptions {\n /** Strategy chain. Defaults to `DEFAULT_STRATEGIES`. Order = priority. */\n strategies?: ReadonlyArray<Strategy>;\n /** Document or shadow root used for uniqueness checks. Defaults to the target's owner document. */\n scope?: ParentNode;\n /**\n * Optional logger. When provided, the orchestrator emits a `debug` log if a\n * strategy produces a malformed selector that throws during the uniqueness\n * check — useful for diagnosing strategy bugs without crashing the engine.\n */\n logger?: ElementSelectorLogger;\n}\n\n/**\n * Try to produce a CSS selector for `el` using the strategy chain.\n *\n * Returns the composed selector string on success, or `null` if every strategy\n * declined at every walked ancestor. Callers (the engine) treat `null` as the\n * signal to invoke the fallback walker.\n *\n * Selector format on success:\n *\n * - Anchor only (target itself was an anchor): `<anchor-selector>`\n * - Anchor + trail (anchor was an ancestor): `<anchor-selector> > <descent>`\n *\n * Where `<anchor-selector>` is whatever the winning strategy returned for the\n * anchor element (e.g. `[data-amp-track-id=\"login-form\"]` or `div#hero`), and\n * `<descent>` is `describeRelative(anchor, trail)`.\n */\nexport function runOrchestrator(\n el: Element,\n config: ResolvedSelectorConfig,\n options: OrchestratorOptions = {},\n): string | null {\n const strategies = options.strategies ?? DEFAULT_STRATEGIES;\n const scope: ParentNode = options.scope ?? el.ownerDocument ?? document;\n const ctx: StrategyContext = { scope, config };\n\n const walk = collectWalk(el, config.maxAncestorWalkDepth);\n\n // Two-pass: try strategy[0] across the whole walk, then strategy[1], etc.\n // This gives an \"explicit anchor at any depth beats a structural anchor any\n // depth\" priority, which matches the design doc's \"customer intent overrides\n // structural inference\" rule.\n for (const strategy of strategies) {\n for (let i = 0; i < walk.length; i++) {\n const anchor = walk[i];\n const anchorSelector = strategy.try(anchor, ctx);\n if (anchorSelector === null) continue;\n\n // Anchor was the target itself — no descent needed.\n if (i === 0) {\n if (isUniqueMatch(scope, anchorSelector, el, strategy.name, options.logger)) {\n return anchorSelector;\n }\n continue;\n }\n\n // Anchor was an ancestor — descend back to the target through the trail.\n const trail = walk.slice(0, i).reverse();\n const descent = describeRelative(anchor, trail);\n const composed = `${anchorSelector} > ${descent}`;\n if (isUniqueMatch(scope, composed, el, strategy.name, options.logger)) {\n return composed;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Build the walk array `[target, parent, grandparent, ...]`, stopping at\n * `<html>` (or at the depth limit if configured). Excludes the document\n * element's parent (which is the Document node and not an Element).\n */\nfunction collectWalk(el: Element, maxDepth: number | undefined): Element[] {\n const walk: Element[] = [];\n let cursor: Element | null = el;\n while (cursor !== null) {\n walk.push(cursor);\n if (maxDepth !== undefined && walk.length > maxDepth) break;\n cursor = cursor.parentElement;\n }\n return walk;\n}\n\n/**\n * Check whether `selector` resolves to exactly `el` and no other element in\n * `scope`. The strategies themselves don't run uniqueness checks — that's the\n * orchestrator's job, so strategies stay pure transforms and stay testable in\n * isolation.\n *\n * When the selector is malformed (which is a strategy bug rather than user\n * input), we log at `debug` and return false rather than throwing. The log\n * lets engineers diagnose a misbehaving strategy without the engine taking\n * down whatever it's wired into.\n */\nfunction isUniqueMatch(\n scope: ParentNode,\n selector: string,\n el: Element,\n strategyName: string,\n logger?: ElementSelectorLogger,\n): boolean {\n let matches: NodeListOf<Element>;\n try {\n matches = scope.querySelectorAll(selector);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.debug(\n `@amplitude/element-selector: strategy \"${strategyName}\" emitted a malformed selector \"${selector}\" (${message})`,\n );\n return false;\n }\n return matches.length === 1 && matches[0] === el;\n}\n"]}
@@ -0,0 +1,37 @@
1
+ import { ElementSelectorLogger } from '../types';
2
+ /**
3
+ * Autogenerated-id pattern pack.
4
+ *
5
+ * When an element id matches any of these regexes, the algorithm treats the
6
+ * element as if it has no id — the stableId strategy returns null and the
7
+ * fallback walks past it instead of anchoring on it. Stops selectors from
8
+ * pinning to ids that change between page loads or component re-mounts.
9
+ *
10
+ * Defaults are surfaced to customers in remote config so they can audit what's
11
+ * being filtered and add or remove patterns to match their stack.
12
+ */
13
+ /**
14
+ * Built-in defaults, in the order they're applied (order doesn't affect
15
+ * correctness — `some()` short-circuits on the first match).
16
+ */
17
+ export declare const DEFAULT_AUTOGENERATED_ID_PATTERNS: ReadonlyArray<RegExp>;
18
+ /**
19
+ * Compile a list of regex pattern strings (e.g. from a remote-config payload)
20
+ * into RegExp objects. Invalid patterns are skipped (not thrown) so a single
21
+ * bad regex in remote config can't crash the engine.
22
+ *
23
+ * Pass `logger` to surface invalid patterns at `warn` level — useful for
24
+ * diagnosing why a customer's override isn't taking effect.
25
+ *
26
+ * Callers decide whether to merge the result with `DEFAULT_AUTOGENERATED_ID_PATTERNS`
27
+ * or use it as a full replacement. That policy lives in the config resolver,
28
+ * not here.
29
+ */
30
+ export declare function compile(patterns: string[], logger?: ElementSelectorLogger): RegExp[];
31
+ /**
32
+ * Check whether `id` is "stable" relative to a set of patterns. An id is
33
+ * stable when it's a non-empty string AND doesn't match any pattern in
34
+ * `patterns`. Null, undefined, and empty-string ids are not stable.
35
+ */
36
+ export declare function isStableId(id: string | null | undefined, patterns: ReadonlyArray<RegExp>): boolean;
37
+ //# sourceMappingURL=autogenerated-ids.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"autogenerated-ids.d.ts","sourceRoot":"","sources":["../../../src/patterns/autogenerated-ids.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAEjD;;;;;;;;;;GAUG;AAEH;;;GAGG;AACH,eAAO,MAAM,iCAAiC,EAAE,aAAa,CAAC,MAAM,CAkBnE,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,OAAO,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,MAAM,CAAC,EAAE,qBAAqB,GAAG,MAAM,EAAE,CAWpF;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,QAAQ,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,OAAO,CAMlG"}
@@ -0,0 +1,97 @@
1
+ import { __values } from "tslib";
2
+ /**
3
+ * Autogenerated-id pattern pack.
4
+ *
5
+ * When an element id matches any of these regexes, the algorithm treats the
6
+ * element as if it has no id — the stableId strategy returns null and the
7
+ * fallback walks past it instead of anchoring on it. Stops selectors from
8
+ * pinning to ids that change between page loads or component re-mounts.
9
+ *
10
+ * Defaults are surfaced to customers in remote config so they can audit what's
11
+ * being filtered and add or remove patterns to match their stack.
12
+ */
13
+ /**
14
+ * Built-in defaults, in the order they're applied (order doesn't affect
15
+ * correctness — `some()` short-circuits on the first match).
16
+ */
17
+ export var DEFAULT_AUTOGENERATED_ID_PATTERNS = [
18
+ // React useId() — ":r0:", ":r1:", ":rk:". Stable for one render; new id on next mount.
19
+ /^:r[0-9a-z]+:$/,
20
+ // Radix UI primitives — "radix-:r3:", "radix-A1B2C3". Prefix match (the
21
+ // shape of what comes after `radix-` varies by Radix version and React
22
+ // major; only the prefix is reliable).
23
+ /^radix-/,
24
+ // Headless UI (Tailwind Labs) — "headlessui-menu-button-:r5:". Prefix match.
25
+ /^headlessui-/,
26
+ // MUI internal id prefix — "mui-12345". Don't confuse with Mui-* CSS class state markers.
27
+ /^mui-/,
28
+ // Hex-only ids >=16 chars — UUIDs without hyphens, build hashes. Whole-string match.
29
+ /^[a-f0-9]{16,}$/i,
30
+ // Trailing long digit run — "session-1700000000", "row-20250515". Timestamps, counters.
31
+ /-\d{8,}$/,
32
+ // Any 4+ consecutive digits anywhere — "product-2134", "swiper-wrapper-…41039".
33
+ // ContentSquare's heuristic; catches the digit-heavy portions of library-generated ids.
34
+ /\d{4,}/,
35
+ ];
36
+ /**
37
+ * Compile a list of regex pattern strings (e.g. from a remote-config payload)
38
+ * into RegExp objects. Invalid patterns are skipped (not thrown) so a single
39
+ * bad regex in remote config can't crash the engine.
40
+ *
41
+ * Pass `logger` to surface invalid patterns at `warn` level — useful for
42
+ * diagnosing why a customer's override isn't taking effect.
43
+ *
44
+ * Callers decide whether to merge the result with `DEFAULT_AUTOGENERATED_ID_PATTERNS`
45
+ * or use it as a full replacement. That policy lives in the config resolver,
46
+ * not here.
47
+ */
48
+ export function compile(patterns, logger) {
49
+ var e_1, _a;
50
+ var compiled = [];
51
+ try {
52
+ for (var patterns_1 = __values(patterns), patterns_1_1 = patterns_1.next(); !patterns_1_1.done; patterns_1_1 = patterns_1.next()) {
53
+ var pattern = patterns_1_1.value;
54
+ try {
55
+ compiled.push(new RegExp(pattern));
56
+ }
57
+ catch (e) {
58
+ var message = e instanceof Error ? e.message : String(e);
59
+ logger === null || logger === void 0 ? void 0 : logger.warn("@amplitude/element-selector: ignoring invalid autogenerated-id pattern \"".concat(pattern, "\" (").concat(message, ")"));
60
+ }
61
+ }
62
+ }
63
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
64
+ finally {
65
+ try {
66
+ if (patterns_1_1 && !patterns_1_1.done && (_a = patterns_1.return)) _a.call(patterns_1);
67
+ }
68
+ finally { if (e_1) throw e_1.error; }
69
+ }
70
+ return compiled;
71
+ }
72
+ /**
73
+ * Check whether `id` is "stable" relative to a set of patterns. An id is
74
+ * stable when it's a non-empty string AND doesn't match any pattern in
75
+ * `patterns`. Null, undefined, and empty-string ids are not stable.
76
+ */
77
+ export function isStableId(id, patterns) {
78
+ var e_2, _a;
79
+ if (id === null || id === undefined || id === '')
80
+ return false;
81
+ try {
82
+ for (var patterns_2 = __values(patterns), patterns_2_1 = patterns_2.next(); !patterns_2_1.done; patterns_2_1 = patterns_2.next()) {
83
+ var pattern = patterns_2_1.value;
84
+ if (pattern.test(id))
85
+ return false;
86
+ }
87
+ }
88
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
89
+ finally {
90
+ try {
91
+ if (patterns_2_1 && !patterns_2_1.done && (_a = patterns_2.return)) _a.call(patterns_2);
92
+ }
93
+ finally { if (e_2) throw e_2.error; }
94
+ }
95
+ return true;
96
+ }
97
+ //# sourceMappingURL=autogenerated-ids.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"autogenerated-ids.js","sourceRoot":"","sources":["../../../src/patterns/autogenerated-ids.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;GAUG;AAEH;;;GAGG;AACH,MAAM,CAAC,IAAM,iCAAiC,GAA0B;IACtE,uFAAuF;IACvF,gBAAgB;IAChB,wEAAwE;IACxE,uEAAuE;IACvE,uCAAuC;IACvC,SAAS;IACT,6EAA6E;IAC7E,cAAc;IACd,0FAA0F;IAC1F,OAAO;IACP,qFAAqF;IACrF,kBAAkB;IAClB,wFAAwF;IACxF,UAAU;IACV,gFAAgF;IAChF,wFAAwF;IACxF,QAAQ;CACT,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,OAAO,CAAC,QAAkB,EAAE,MAA8B;;IACxE,IAAM,QAAQ,GAAa,EAAE,CAAC;;QAC9B,KAAsB,IAAA,aAAA,SAAA,QAAQ,CAAA,kCAAA,wDAAE;YAA3B,IAAM,OAAO,qBAAA;YAChB,IAAI;gBACF,QAAQ,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;aACpC;YAAC,OAAO,CAAC,EAAE;gBACV,IAAM,OAAO,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;gBAC3D,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,IAAI,CAAC,mFAA2E,OAAO,iBAAM,OAAO,MAAG,CAAC,CAAC;aAClH;SACF;;;;;;;;;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,UAAU,CAAC,EAA6B,EAAE,QAA+B;;IACvF,IAAI,EAAE,KAAK,IAAI,IAAI,EAAE,KAAK,SAAS,IAAI,EAAE,KAAK,EAAE;QAAE,OAAO,KAAK,CAAC;;QAC/D,KAAsB,IAAA,aAAA,SAAA,QAAQ,CAAA,kCAAA,wDAAE;YAA3B,IAAM,OAAO,qBAAA;YAChB,IAAI,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;gBAAE,OAAO,KAAK,CAAC;SACpC;;;;;;;;;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { ElementSelectorLogger } from '../types';\n\n/**\n * Autogenerated-id pattern pack.\n *\n * When an element id matches any of these regexes, the algorithm treats the\n * element as if it has no id — the stableId strategy returns null and the\n * fallback walks past it instead of anchoring on it. Stops selectors from\n * pinning to ids that change between page loads or component re-mounts.\n *\n * Defaults are surfaced to customers in remote config so they can audit what's\n * being filtered and add or remove patterns to match their stack.\n */\n\n/**\n * Built-in defaults, in the order they're applied (order doesn't affect\n * correctness — `some()` short-circuits on the first match).\n */\nexport const DEFAULT_AUTOGENERATED_ID_PATTERNS: ReadonlyArray<RegExp> = [\n // React useId() — \":r0:\", \":r1:\", \":rk:\". Stable for one render; new id on next mount.\n /^:r[0-9a-z]+:$/,\n // Radix UI primitives — \"radix-:r3:\", \"radix-A1B2C3\". Prefix match (the\n // shape of what comes after `radix-` varies by Radix version and React\n // major; only the prefix is reliable).\n /^radix-/,\n // Headless UI (Tailwind Labs) — \"headlessui-menu-button-:r5:\". Prefix match.\n /^headlessui-/,\n // MUI internal id prefix — \"mui-12345\". Don't confuse with Mui-* CSS class state markers.\n /^mui-/,\n // Hex-only ids >=16 chars — UUIDs without hyphens, build hashes. Whole-string match.\n /^[a-f0-9]{16,}$/i,\n // Trailing long digit run — \"session-1700000000\", \"row-20250515\". Timestamps, counters.\n /-\\d{8,}$/,\n // Any 4+ consecutive digits anywhere — \"product-2134\", \"swiper-wrapper-…41039\".\n // ContentSquare's heuristic; catches the digit-heavy portions of library-generated ids.\n /\\d{4,}/,\n];\n\n/**\n * Compile a list of regex pattern strings (e.g. from a remote-config payload)\n * into RegExp objects. Invalid patterns are skipped (not thrown) so a single\n * bad regex in remote config can't crash the engine.\n *\n * Pass `logger` to surface invalid patterns at `warn` level — useful for\n * diagnosing why a customer's override isn't taking effect.\n *\n * Callers decide whether to merge the result with `DEFAULT_AUTOGENERATED_ID_PATTERNS`\n * or use it as a full replacement. That policy lives in the config resolver,\n * not here.\n */\nexport function compile(patterns: string[], logger?: ElementSelectorLogger): RegExp[] {\n const compiled: RegExp[] = [];\n for (const pattern of patterns) {\n try {\n compiled.push(new RegExp(pattern));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: ignoring invalid autogenerated-id pattern \"${pattern}\" (${message})`);\n }\n }\n return compiled;\n}\n\n/**\n * Check whether `id` is \"stable\" relative to a set of patterns. An id is\n * stable when it's a non-empty string AND doesn't match any pattern in\n * `patterns`. Null, undefined, and empty-string ids are not stable.\n */\nexport function isStableId(id: string | null | undefined, patterns: ReadonlyArray<RegExp>): boolean {\n if (id === null || id === undefined || id === '') return false;\n for (const pattern of patterns) {\n if (pattern.test(id)) return false;\n }\n return true;\n}\n"]}
@@ -0,0 +1,48 @@
1
+ import { ElementSelectorLogger } from '../types';
2
+ /**
3
+ * Unstable-class pattern pack.
4
+ *
5
+ * The fallback walker filters classes through these regexes before adding them
6
+ * to a selector. Classes that match are dropped — they don't participate in
7
+ * sibling disambiguation and never appear in the emitted output. Defends
8
+ * against three failure modes:
9
+ *
10
+ * 1. Build-tool / framework utilities (Tailwind, etc.) — class names that
11
+ * look stable but change with every design tweak.
12
+ * 2. CSS-in-JS / build-hash classes (Emotion, CSS modules, styled-components,
13
+ * styled-jsx) — change on every build.
14
+ * 3. Library runtime state classes (Swiper, MUI, Radix, Headless UI,
15
+ * BEM-style is-active/is-open) — class is stable in name but its presence
16
+ * on a given element moves as the user interacts.
17
+ *
18
+ * Defaults are surfaced to customers in remote config so they can audit what's
19
+ * being filtered and add or remove patterns to match their stack.
20
+ */
21
+ /**
22
+ * Built-in defaults grouped by category for readability. The runtime treats
23
+ * the whole list uniformly via `Array.prototype.some(pattern.test)`.
24
+ */
25
+ export declare const DEFAULT_UNSTABLE_CLASS_PATTERNS: ReadonlyArray<RegExp>;
26
+ /**
27
+ * Compile a list of regex pattern strings (e.g. from a remote-config payload)
28
+ * into RegExp objects. Invalid patterns are skipped (not thrown) so a single
29
+ * bad regex in remote config can't crash the engine.
30
+ *
31
+ * Pass `logger` to surface invalid patterns at `warn` level — useful for
32
+ * diagnosing why a customer's override isn't taking effect.
33
+ *
34
+ * Callers decide whether to merge the result with `DEFAULT_UNSTABLE_CLASS_PATTERNS`
35
+ * or use it as a full replacement. That policy lives in the config resolver,
36
+ * not here.
37
+ */
38
+ export declare function compile(patterns: string[], logger?: ElementSelectorLogger): RegExp[];
39
+ /**
40
+ * Filter a list of class names, dropping any that match a pattern. Returns a
41
+ * new array containing only the survivors, preserving original order.
42
+ *
43
+ * Used by the fallback walker (in the next PR) before adding classes to a
44
+ * selector for sibling disambiguation. Also returns sensibly on null /
45
+ * undefined / empty inputs.
46
+ */
47
+ export declare function filterClasses(classes: string[], patterns: ReadonlyArray<RegExp>): string[];
48
+ //# sourceMappingURL=unstable-classes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unstable-classes.d.ts","sourceRoot":"","sources":["../../../src/patterns/unstable-classes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAEjD;;;;;;;;;;;;;;;;;;GAkBG;AAEH;;;GAGG;AACH,eAAO,MAAM,+BAA+B,EAAE,aAAa,CAAC,MAAM,CA6CjE,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,OAAO,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,MAAM,CAAC,EAAE,qBAAqB,GAAG,MAAM,EAAE,CAWpF;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,QAAQ,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,MAAM,EAAE,CAe1F"}
@@ -0,0 +1,150 @@
1
+ import { __values } from "tslib";
2
+ /**
3
+ * Unstable-class pattern pack.
4
+ *
5
+ * The fallback walker filters classes through these regexes before adding them
6
+ * to a selector. Classes that match are dropped — they don't participate in
7
+ * sibling disambiguation and never appear in the emitted output. Defends
8
+ * against three failure modes:
9
+ *
10
+ * 1. Build-tool / framework utilities (Tailwind, etc.) — class names that
11
+ * look stable but change with every design tweak.
12
+ * 2. CSS-in-JS / build-hash classes (Emotion, CSS modules, styled-components,
13
+ * styled-jsx) — change on every build.
14
+ * 3. Library runtime state classes (Swiper, MUI, Radix, Headless UI,
15
+ * BEM-style is-active/is-open) — class is stable in name but its presence
16
+ * on a given element moves as the user interacts.
17
+ *
18
+ * Defaults are surfaced to customers in remote config so they can audit what's
19
+ * being filtered and add or remove patterns to match their stack.
20
+ */
21
+ /**
22
+ * Built-in defaults grouped by category for readability. The runtime treats
23
+ * the whole list uniformly via `Array.prototype.some(pattern.test)`.
24
+ */
25
+ export var DEFAULT_UNSTABLE_CLASS_PATTERNS = [
26
+ // ===== Tailwind / build-tool utilities =====
27
+ // Tailwind spacing: p-4, px-2, py-8, pt-1, mt-4, etc.
28
+ /^(p|m|px|py|mx|my|pt|pb|pl|pr|mt|mb|ml|mr)-\d+$/,
29
+ // Tailwind sizing: w-full, h-screen, max-w-[1440px], etc.
30
+ /^(w|h|min-w|max-w|min-h|max-h)-/,
31
+ // Tailwind color / visual: bg-blue-500, text-white, border-gray-200, ring-2, etc.
32
+ /^(text|bg|border|ring|fill|stroke)-/,
33
+ // Tailwind state variants: hover:underline, focus:ring-2, active:bg-transparent.
34
+ /^(hover|focus|active|disabled|group-hover):/,
35
+ // Tailwind breakpoint variants: md:flex, lg:grid-cols-3.
36
+ /^(sm|md|lg|xl|2xl):/,
37
+ // Tailwind z-index utility: z-10, z-50.
38
+ /^z-\d+$/,
39
+ // Tailwind arbitrary data-attribute variants: data-[state=open]:bg-white.
40
+ /^data-\[/,
41
+ // Tailwind arbitrary selector variants: [&_.swiper-slide]:h-auto, [&>div]:p-4.
42
+ /^\[/,
43
+ // ===== CSS-in-JS / build hashes =====
44
+ // Emotion: css-1abcd23, css-9xyzkw0.
45
+ /^css-[a-z0-9]{6,}$/,
46
+ // CSS modules: Button_root__abc123, Card_container__xyz789. The middle
47
+ // segment can be as short as `root` (4 chars) in practice; the trailing
48
+ // hash is the load-bearing part.
49
+ /^[a-zA-Z]+_[a-zA-Z0-9]{3,}__[a-zA-Z0-9]{5,}$/,
50
+ // styled-components: sc-bdVaJa, sc-1jjuPXC0.
51
+ /^sc-[a-zA-Z0-9]{6,}$/,
52
+ // styled-jsx (Next.js): jsx-1234567.
53
+ /^jsx-\d+$/,
54
+ // ===== Library runtime state classes =====
55
+ // Swiper carousel slide states. Move between elements as carousel advances.
56
+ /^swiper-slide-(visible|fully-visible|active|prev|next|duplicate)$/,
57
+ // BEM-style interaction state: is-active, is-open, is-selected, etc.
58
+ /^is-(active|open|selected|hovered|focused|expanded)$/,
59
+ // MUI per-component state: MuiButton-focusVisible, MuiSwitch-checked, etc.
60
+ /^Mui[A-Z][a-zA-Z]+-(focused|selected|disabled|expanded|focusVisible|active|checked)$/,
61
+ // MUI bare state classes: Mui-selected, Mui-disabled.
62
+ /^Mui-(selected|focused|disabled|expanded|focusVisible|active|checked)$/,
63
+ // Radix-style state class mirrors: data-state-open, data-state-checked.
64
+ /^data-state-/,
65
+ ];
66
+ /**
67
+ * Compile a list of regex pattern strings (e.g. from a remote-config payload)
68
+ * into RegExp objects. Invalid patterns are skipped (not thrown) so a single
69
+ * bad regex in remote config can't crash the engine.
70
+ *
71
+ * Pass `logger` to surface invalid patterns at `warn` level — useful for
72
+ * diagnosing why a customer's override isn't taking effect.
73
+ *
74
+ * Callers decide whether to merge the result with `DEFAULT_UNSTABLE_CLASS_PATTERNS`
75
+ * or use it as a full replacement. That policy lives in the config resolver,
76
+ * not here.
77
+ */
78
+ export function compile(patterns, logger) {
79
+ var e_1, _a;
80
+ var compiled = [];
81
+ try {
82
+ for (var patterns_1 = __values(patterns), patterns_1_1 = patterns_1.next(); !patterns_1_1.done; patterns_1_1 = patterns_1.next()) {
83
+ var pattern = patterns_1_1.value;
84
+ try {
85
+ compiled.push(new RegExp(pattern));
86
+ }
87
+ catch (e) {
88
+ var message = e instanceof Error ? e.message : String(e);
89
+ logger === null || logger === void 0 ? void 0 : logger.warn("@amplitude/element-selector: ignoring invalid unstable-class pattern \"".concat(pattern, "\" (").concat(message, ")"));
90
+ }
91
+ }
92
+ }
93
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
94
+ finally {
95
+ try {
96
+ if (patterns_1_1 && !patterns_1_1.done && (_a = patterns_1.return)) _a.call(patterns_1);
97
+ }
98
+ finally { if (e_1) throw e_1.error; }
99
+ }
100
+ return compiled;
101
+ }
102
+ /**
103
+ * Filter a list of class names, dropping any that match a pattern. Returns a
104
+ * new array containing only the survivors, preserving original order.
105
+ *
106
+ * Used by the fallback walker (in the next PR) before adding classes to a
107
+ * selector for sibling disambiguation. Also returns sensibly on null /
108
+ * undefined / empty inputs.
109
+ */
110
+ export function filterClasses(classes, patterns) {
111
+ var e_2, _a, e_3, _b;
112
+ if (!classes || classes.length === 0)
113
+ return [];
114
+ var survivors = [];
115
+ try {
116
+ for (var classes_1 = __values(classes), classes_1_1 = classes_1.next(); !classes_1_1.done; classes_1_1 = classes_1.next()) {
117
+ var cls = classes_1_1.value;
118
+ if (!cls)
119
+ continue;
120
+ var matched = false;
121
+ try {
122
+ for (var patterns_2 = (e_3 = void 0, __values(patterns)), patterns_2_1 = patterns_2.next(); !patterns_2_1.done; patterns_2_1 = patterns_2.next()) {
123
+ var pattern = patterns_2_1.value;
124
+ if (pattern.test(cls)) {
125
+ matched = true;
126
+ break;
127
+ }
128
+ }
129
+ }
130
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
131
+ finally {
132
+ try {
133
+ if (patterns_2_1 && !patterns_2_1.done && (_b = patterns_2.return)) _b.call(patterns_2);
134
+ }
135
+ finally { if (e_3) throw e_3.error; }
136
+ }
137
+ if (!matched)
138
+ survivors.push(cls);
139
+ }
140
+ }
141
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
142
+ finally {
143
+ try {
144
+ if (classes_1_1 && !classes_1_1.done && (_a = classes_1.return)) _a.call(classes_1);
145
+ }
146
+ finally { if (e_2) throw e_2.error; }
147
+ }
148
+ return survivors;
149
+ }
150
+ //# sourceMappingURL=unstable-classes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unstable-classes.js","sourceRoot":"","sources":["../../../src/patterns/unstable-classes.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;;;;;;;;;GAkBG;AAEH;;;GAGG;AACH,MAAM,CAAC,IAAM,+BAA+B,GAA0B;IACpE,8CAA8C;IAE9C,sDAAsD;IACtD,iDAAiD;IACjD,0DAA0D;IAC1D,iCAAiC;IACjC,kFAAkF;IAClF,qCAAqC;IACrC,iFAAiF;IACjF,6CAA6C;IAC7C,yDAAyD;IACzD,qBAAqB;IACrB,wCAAwC;IACxC,SAAS;IACT,0EAA0E;IAC1E,UAAU;IACV,+EAA+E;IAC/E,KAAK;IAEL,uCAAuC;IAEvC,qCAAqC;IACrC,oBAAoB;IACpB,uEAAuE;IACvE,wEAAwE;IACxE,iCAAiC;IACjC,8CAA8C;IAC9C,6CAA6C;IAC7C,sBAAsB;IACtB,qCAAqC;IACrC,WAAW;IAEX,4CAA4C;IAE5C,4EAA4E;IAC5E,mEAAmE;IACnE,qEAAqE;IACrE,sDAAsD;IACtD,2EAA2E;IAC3E,sFAAsF;IACtF,sDAAsD;IACtD,wEAAwE;IACxE,wEAAwE;IACxE,cAAc;CACf,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,OAAO,CAAC,QAAkB,EAAE,MAA8B;;IACxE,IAAM,QAAQ,GAAa,EAAE,CAAC;;QAC9B,KAAsB,IAAA,aAAA,SAAA,QAAQ,CAAA,kCAAA,wDAAE;YAA3B,IAAM,OAAO,qBAAA;YAChB,IAAI;gBACF,QAAQ,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;aACpC;YAAC,OAAO,CAAC,EAAE;gBACV,IAAM,OAAO,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;gBAC3D,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,IAAI,CAAC,iFAAyE,OAAO,iBAAM,OAAO,MAAG,CAAC,CAAC;aAChH;SACF;;;;;;;;;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa,CAAC,OAAiB,EAAE,QAA+B;;IAC9E,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAChD,IAAM,SAAS,GAAa,EAAE,CAAC;;QAC/B,KAAkB,IAAA,YAAA,SAAA,OAAO,CAAA,gCAAA,qDAAE;YAAtB,IAAM,GAAG,oBAAA;YACZ,IAAI,CAAC,GAAG;gBAAE,SAAS;YACnB,IAAI,OAAO,GAAG,KAAK,CAAC;;gBACpB,KAAsB,IAAA,4BAAA,SAAA,QAAQ,CAAA,CAAA,kCAAA,wDAAE;oBAA3B,IAAM,OAAO,qBAAA;oBAChB,IAAI,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;wBACrB,OAAO,GAAG,IAAI,CAAC;wBACf,MAAM;qBACP;iBACF;;;;;;;;;YACD,IAAI,CAAC,OAAO;gBAAE,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SACnC;;;;;;;;;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import { ElementSelectorLogger } from '../types';\n\n/**\n * Unstable-class pattern pack.\n *\n * The fallback walker filters classes through these regexes before adding them\n * to a selector. Classes that match are dropped — they don't participate in\n * sibling disambiguation and never appear in the emitted output. Defends\n * against three failure modes:\n *\n * 1. Build-tool / framework utilities (Tailwind, etc.) — class names that\n * look stable but change with every design tweak.\n * 2. CSS-in-JS / build-hash classes (Emotion, CSS modules, styled-components,\n * styled-jsx) — change on every build.\n * 3. Library runtime state classes (Swiper, MUI, Radix, Headless UI,\n * BEM-style is-active/is-open) — class is stable in name but its presence\n * on a given element moves as the user interacts.\n *\n * Defaults are surfaced to customers in remote config so they can audit what's\n * being filtered and add or remove patterns to match their stack.\n */\n\n/**\n * Built-in defaults grouped by category for readability. The runtime treats\n * the whole list uniformly via `Array.prototype.some(pattern.test)`.\n */\nexport const DEFAULT_UNSTABLE_CLASS_PATTERNS: ReadonlyArray<RegExp> = [\n // ===== Tailwind / build-tool utilities =====\n\n // Tailwind spacing: p-4, px-2, py-8, pt-1, mt-4, etc.\n /^(p|m|px|py|mx|my|pt|pb|pl|pr|mt|mb|ml|mr)-\\d+$/,\n // Tailwind sizing: w-full, h-screen, max-w-[1440px], etc.\n /^(w|h|min-w|max-w|min-h|max-h)-/,\n // Tailwind color / visual: bg-blue-500, text-white, border-gray-200, ring-2, etc.\n /^(text|bg|border|ring|fill|stroke)-/,\n // Tailwind state variants: hover:underline, focus:ring-2, active:bg-transparent.\n /^(hover|focus|active|disabled|group-hover):/,\n // Tailwind breakpoint variants: md:flex, lg:grid-cols-3.\n /^(sm|md|lg|xl|2xl):/,\n // Tailwind z-index utility: z-10, z-50.\n /^z-\\d+$/,\n // Tailwind arbitrary data-attribute variants: data-[state=open]:bg-white.\n /^data-\\[/,\n // Tailwind arbitrary selector variants: [&_.swiper-slide]:h-auto, [&>div]:p-4.\n /^\\[/,\n\n // ===== CSS-in-JS / build hashes =====\n\n // Emotion: css-1abcd23, css-9xyzkw0.\n /^css-[a-z0-9]{6,}$/,\n // CSS modules: Button_root__abc123, Card_container__xyz789. The middle\n // segment can be as short as `root` (4 chars) in practice; the trailing\n // hash is the load-bearing part.\n /^[a-zA-Z]+_[a-zA-Z0-9]{3,}__[a-zA-Z0-9]{5,}$/,\n // styled-components: sc-bdVaJa, sc-1jjuPXC0.\n /^sc-[a-zA-Z0-9]{6,}$/,\n // styled-jsx (Next.js): jsx-1234567.\n /^jsx-\\d+$/,\n\n // ===== Library runtime state classes =====\n\n // Swiper carousel slide states. Move between elements as carousel advances.\n /^swiper-slide-(visible|fully-visible|active|prev|next|duplicate)$/,\n // BEM-style interaction state: is-active, is-open, is-selected, etc.\n /^is-(active|open|selected|hovered|focused|expanded)$/,\n // MUI per-component state: MuiButton-focusVisible, MuiSwitch-checked, etc.\n /^Mui[A-Z][a-zA-Z]+-(focused|selected|disabled|expanded|focusVisible|active|checked)$/,\n // MUI bare state classes: Mui-selected, Mui-disabled.\n /^Mui-(selected|focused|disabled|expanded|focusVisible|active|checked)$/,\n // Radix-style state class mirrors: data-state-open, data-state-checked.\n /^data-state-/,\n];\n\n/**\n * Compile a list of regex pattern strings (e.g. from a remote-config payload)\n * into RegExp objects. Invalid patterns are skipped (not thrown) so a single\n * bad regex in remote config can't crash the engine.\n *\n * Pass `logger` to surface invalid patterns at `warn` level — useful for\n * diagnosing why a customer's override isn't taking effect.\n *\n * Callers decide whether to merge the result with `DEFAULT_UNSTABLE_CLASS_PATTERNS`\n * or use it as a full replacement. That policy lives in the config resolver,\n * not here.\n */\nexport function compile(patterns: string[], logger?: ElementSelectorLogger): RegExp[] {\n const compiled: RegExp[] = [];\n for (const pattern of patterns) {\n try {\n compiled.push(new RegExp(pattern));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: ignoring invalid unstable-class pattern \"${pattern}\" (${message})`);\n }\n }\n return compiled;\n}\n\n/**\n * Filter a list of class names, dropping any that match a pattern. Returns a\n * new array containing only the survivors, preserving original order.\n *\n * Used by the fallback walker (in the next PR) before adding classes to a\n * selector for sibling disambiguation. Also returns sensibly on null /\n * undefined / empty inputs.\n */\nexport function filterClasses(classes: string[], patterns: ReadonlyArray<RegExp>): string[] {\n if (!classes || classes.length === 0) return [];\n const survivors: string[] = [];\n for (const cls of classes) {\n if (!cls) continue;\n let matched = false;\n for (const pattern of patterns) {\n if (pattern.test(cls)) {\n matched = true;\n break;\n }\n }\n if (!matched) survivors.push(cls);\n }\n return survivors;\n}\n"]}
@@ -0,0 +1,22 @@
1
+ import { Strategy } from '../types';
2
+ /**
3
+ * First strategy in the chain. Customer-controlled anchor selector via the
4
+ * configured tracking attribute (default: `data-amp-track-id`).
5
+ *
6
+ * Semantics:
7
+ *
8
+ * - Attribute set with a non-empty value:
9
+ * returns `[<attr>="<value>"]` — uses this element as an explicit anchor.
10
+ * - Attribute set with an empty value:
11
+ * returns null. The empty value is a suppression signal for downstream
12
+ * components (the `stableId` strategy and the fallback both consult
13
+ * `getStableId` which honors the empty-value semantic). This strategy
14
+ * doesn't anchor on the element either.
15
+ * - Attribute absent:
16
+ * returns null.
17
+ *
18
+ * The selector wraps the value in JSON-encoded quotes so any special CSS
19
+ * characters in the value are escaped uniformly.
20
+ */
21
+ export declare const explicitTrackingAttribute: Strategy;
22
+ //# sourceMappingURL=explicit-tracking-attribute.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"explicit-tracking-attribute.d.ts","sourceRoot":"","sources":["../../../src/strategies/explicit-tracking-attribute.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEpC;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,yBAAyB,EAAE,QAavC,CAAC"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * First strategy in the chain. Customer-controlled anchor selector via the
3
+ * configured tracking attribute (default: `data-amp-track-id`).
4
+ *
5
+ * Semantics:
6
+ *
7
+ * - Attribute set with a non-empty value:
8
+ * returns `[<attr>="<value>"]` — uses this element as an explicit anchor.
9
+ * - Attribute set with an empty value:
10
+ * returns null. The empty value is a suppression signal for downstream
11
+ * components (the `stableId` strategy and the fallback both consult
12
+ * `getStableId` which honors the empty-value semantic). This strategy
13
+ * doesn't anchor on the element either.
14
+ * - Attribute absent:
15
+ * returns null.
16
+ *
17
+ * The selector wraps the value in JSON-encoded quotes so any special CSS
18
+ * characters in the value are escaped uniformly.
19
+ */
20
+ export var explicitTrackingAttribute = {
21
+ name: 'explicitTrackingAttribute',
22
+ try: function (el, ctx) {
23
+ var attrName = ctx.config.explicitTrackingAttribute;
24
+ var value = el.getAttribute(attrName);
25
+ if (value === null || value === '') {
26
+ return null;
27
+ }
28
+ // JSON.stringify wraps in double quotes and escapes embedded quotes /
29
+ // backslashes — the resulting attribute selector is valid CSS.
30
+ return "[".concat(attrName, "=").concat(JSON.stringify(value), "]");
31
+ },
32
+ };
33
+ //# sourceMappingURL=explicit-tracking-attribute.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"explicit-tracking-attribute.js","sourceRoot":"","sources":["../../../src/strategies/explicit-tracking-attribute.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,IAAM,yBAAyB,GAAa;IACjD,IAAI,EAAE,2BAA2B;IAEjC,GAAG,YAAC,EAAE,EAAE,GAAG;QACT,IAAM,QAAQ,GAAG,GAAG,CAAC,MAAM,CAAC,yBAAyB,CAAC;QACtD,IAAM,KAAK,GAAG,EAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;QACxC,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,EAAE,EAAE;YAClC,OAAO,IAAI,CAAC;SACb;QACD,sEAAsE;QACtE,+DAA+D;QAC/D,OAAO,WAAI,QAAQ,cAAI,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,MAAG,CAAC;IAClD,CAAC;CACF,CAAC","sourcesContent":["import { Strategy } from '../types';\n\n/**\n * First strategy in the chain. Customer-controlled anchor selector via the\n * configured tracking attribute (default: `data-amp-track-id`).\n *\n * Semantics:\n *\n * - Attribute set with a non-empty value:\n * returns `[<attr>=\"<value>\"]` — uses this element as an explicit anchor.\n * - Attribute set with an empty value:\n * returns null. The empty value is a suppression signal for downstream\n * components (the `stableId` strategy and the fallback both consult\n * `getStableId` which honors the empty-value semantic). This strategy\n * doesn't anchor on the element either.\n * - Attribute absent:\n * returns null.\n *\n * The selector wraps the value in JSON-encoded quotes so any special CSS\n * characters in the value are escaped uniformly.\n */\nexport const explicitTrackingAttribute: Strategy = {\n name: 'explicitTrackingAttribute',\n\n try(el, ctx) {\n const attrName = ctx.config.explicitTrackingAttribute;\n const value = el.getAttribute(attrName);\n if (value === null || value === '') {\n return null;\n }\n // JSON.stringify wraps in double quotes and escapes embedded quotes /\n // backslashes — the resulting attribute selector is valid CSS.\n return `[${attrName}=${JSON.stringify(value)}]`;\n },\n};\n"]}
@@ -0,0 +1,14 @@
1
+ import { Strategy } from '../types';
2
+ /**
3
+ * Second strategy in the chain. Anchors on the element's `id` when the id is
4
+ * "stable" — i.e., present, not suppressed via the explicit-tracking-attribute
5
+ * empty-value mechanism, and not matching any autogenerated-id pattern.
6
+ *
7
+ * Returns `tag#id` (CSS-escaped) when the id is usable; null otherwise.
8
+ *
9
+ * Filtering is delegated to `getStableId` so this strategy and the
10
+ * `fallback-css-path` walker (in the orchestration PR) share a single source
11
+ * of truth for "is this id usable?"
12
+ */
13
+ export declare const stableId: Strategy;
14
+ //# sourceMappingURL=stable-id.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stable-id.d.ts","sourceRoot":"","sources":["../../../src/strategies/stable-id.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAIpC;;;;;;;;;;GAUG;AACH,eAAO,MAAM,QAAQ,EAAE,QAUtB,CAAC"}
@@ -0,0 +1,24 @@
1
+ import { getStableId } from '../helpers/get-stable-id';
2
+ import { escapeIdForCss } from '../helpers/escape-id';
3
+ /**
4
+ * Second strategy in the chain. Anchors on the element's `id` when the id is
5
+ * "stable" — i.e., present, not suppressed via the explicit-tracking-attribute
6
+ * empty-value mechanism, and not matching any autogenerated-id pattern.
7
+ *
8
+ * Returns `tag#id` (CSS-escaped) when the id is usable; null otherwise.
9
+ *
10
+ * Filtering is delegated to `getStableId` so this strategy and the
11
+ * `fallback-css-path` walker (in the orchestration PR) share a single source
12
+ * of truth for "is this id usable?"
13
+ */
14
+ export var stableId = {
15
+ name: 'stableId',
16
+ try: function (el, ctx) {
17
+ var id = getStableId(el, ctx.config);
18
+ if (id === null) {
19
+ return null;
20
+ }
21
+ return "".concat(el.tagName.toLowerCase(), "#").concat(escapeIdForCss(id));
22
+ },
23
+ };
24
+ //# sourceMappingURL=stable-id.js.map