@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,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.stableId = void 0;
4
+ var get_stable_id_1 = require("../helpers/get-stable-id");
5
+ var escape_id_1 = require("../helpers/escape-id");
6
+ /**
7
+ * Second strategy in the chain. Anchors on the element's `id` when the id is
8
+ * "stable" — i.e., present, not suppressed via the explicit-tracking-attribute
9
+ * empty-value mechanism, and not matching any autogenerated-id pattern.
10
+ *
11
+ * Returns `tag#id` (CSS-escaped) when the id is usable; null otherwise.
12
+ *
13
+ * Filtering is delegated to `getStableId` so this strategy and the
14
+ * `fallback-css-path` walker (in the orchestration PR) share a single source
15
+ * of truth for "is this id usable?"
16
+ */
17
+ exports.stableId = {
18
+ name: 'stableId',
19
+ try: function (el, ctx) {
20
+ var id = (0, get_stable_id_1.getStableId)(el, ctx.config);
21
+ if (id === null) {
22
+ return null;
23
+ }
24
+ return "".concat(el.tagName.toLowerCase(), "#").concat((0, escape_id_1.escapeIdForCss)(id));
25
+ },
26
+ };
27
+ //# sourceMappingURL=stable-id.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stable-id.js","sourceRoot":"","sources":["../../../src/strategies/stable-id.ts"],"names":[],"mappings":";;;AACA,0DAAuD;AACvD,kDAAsD;AAEtD;;;;;;;;;;GAUG;AACU,QAAA,QAAQ,GAAa;IAChC,IAAI,EAAE,UAAU;IAEhB,GAAG,YAAC,EAAE,EAAE,GAAG;QACT,IAAM,EAAE,GAAG,IAAA,2BAAW,EAAC,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;QACvC,IAAI,EAAE,KAAK,IAAI,EAAE;YACf,OAAO,IAAI,CAAC;SACb;QACD,OAAO,UAAG,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,cAAI,IAAA,0BAAc,EAAC,EAAE,CAAC,CAAE,CAAC;IAC7D,CAAC;CACF,CAAC","sourcesContent":["import { Strategy } from '../types';\nimport { getStableId } from '../helpers/get-stable-id';\nimport { escapeIdForCss } from '../helpers/escape-id';\n\n/**\n * Second strategy in the chain. Anchors on the element's `id` when the id is\n * \"stable\" — i.e., present, not suppressed via the explicit-tracking-attribute\n * empty-value mechanism, and not matching any autogenerated-id pattern.\n *\n * Returns `tag#id` (CSS-escaped) when the id is usable; null otherwise.\n *\n * Filtering is delegated to `getStableId` so this strategy and the\n * `fallback-css-path` walker (in the orchestration PR) share a single source\n * of truth for \"is this id usable?\"\n */\nexport const stableId: Strategy = {\n name: 'stableId',\n\n try(el, ctx) {\n const id = getStableId(el, ctx.config);\n if (id === null) {\n return null;\n }\n return `${el.tagName.toLowerCase()}#${escapeIdForCss(id)}`;\n },\n};\n"]}
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Core type definitions for the v1 element-selector algorithm.
3
+ *
4
+ * These are the public-API contract that consumers (autocapture SDK, dashboard
5
+ * tagging UI, Chrome extension visual tagger) design against. They land before
6
+ * any implementation so the contract is stable for cross-team review.
7
+ *
8
+ * See the design doc:
9
+ * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
10
+ */
11
+ /**
12
+ * A pluggable selector strategy. Given an element + context, returns a CSS
13
+ * selector string candidate (which the orchestrator will then uniqueness-check)
14
+ * or `null` when the strategy doesn't apply to this element.
15
+ */
16
+ export interface Strategy {
17
+ /** Stable identifier for the strategy. Used for diagnostics and remote-config references. */
18
+ readonly name: string;
19
+ /**
20
+ * Produce a candidate selector for `el`, or `null` if this strategy has
21
+ * nothing to contribute for this element. Strategies are pure transforms —
22
+ * they never call `querySelectorAll` themselves; uniqueness is checked by
23
+ * the orchestrator in the next layer up.
24
+ */
25
+ try(el: Element, ctx: StrategyContext): string | null;
26
+ }
27
+ /**
28
+ * Context passed to every strategy invocation. `scope` is the document or
29
+ * shadow root the orchestrator will use for uniqueness checks; `config` is the
30
+ * resolved configuration (defaults + remote + local options merged).
31
+ */
32
+ export interface StrategyContext {
33
+ scope: ParentNode;
34
+ config: ResolvedSelectorConfig;
35
+ }
36
+ /**
37
+ * Logger shape accepted by element-selector diagnostics.
38
+ *
39
+ * This is intentionally structural so callers can pass the SDK's
40
+ * `@amplitude/analytics-core` ILogger without this package needing to import
41
+ * analytics-core types during standalone tests/builds.
42
+ */
43
+ export interface ElementSelectorLogger {
44
+ warn(...args: unknown[]): void;
45
+ debug(...args: unknown[]): void;
46
+ }
47
+ /**
48
+ * Fully-resolved configuration consumed at runtime. Produced by
49
+ * `resolveSelectorConfig` (lands in the orchestration PR) from the
50
+ * `ElementSelectorRemoteConfig` payload plus built-in defaults.
51
+ */
52
+ export interface ResolvedSelectorConfig {
53
+ /** Master kill switch. When false, autocapture reverts to legacy cssPath. */
54
+ enabled: boolean;
55
+ /** Attribute name customers can use to set or suppress anchors. Default: 'data-amp-track-id'. */
56
+ explicitTrackingAttribute: string;
57
+ /** Compiled regex patterns matching ids the algorithm should treat as autogenerated. */
58
+ autogeneratedIdPatterns: RegExp[];
59
+ /** Compiled regex patterns matching classes the fallback should filter from sibling disambiguation. */
60
+ unstableClassPatterns: RegExp[];
61
+ /** Optional throttle on the ancestor walk. When undefined, the walk runs to <html>. */
62
+ maxAncestorWalkDepth?: number;
63
+ }
64
+ /**
65
+ * Remote-config payload shape. Each field is optional; absent fields fall back
66
+ * to built-in defaults. Customers see the defaults in the remote-config UI and
67
+ * may add or remove patterns as needed.
68
+ */
69
+ export interface ElementSelectorRemoteConfig {
70
+ /** Kill switch. When set, overrides the default at resolve time. */
71
+ enabled?: boolean;
72
+ /** Override the attribute name used for explicit tracking. */
73
+ explicitTrackingAttribute?: string;
74
+ /** Full replacement for the autogenerated-id pattern list. When omitted, defaults apply. */
75
+ autogeneratedIdPatterns?: string[];
76
+ /** Full replacement for the unstable-class pattern list. When omitted, defaults apply. */
77
+ unstableClassPatterns?: string[];
78
+ /** Defensive throttle on the ancestor walk. Omit for unbounded walking to <html>. */
79
+ maxAncestorWalkDepth?: number;
80
+ }
81
+ /**
82
+ * Public interface of the runtime engine. Implementation lands in the
83
+ * orchestration PR; the interface is declared here so consumers can write
84
+ * against the contract before the class exists.
85
+ */
86
+ export interface SelectorEngine {
87
+ /** Produce a CSS selector string identifying `el` using the engine's current config. */
88
+ generate(el: Element): string;
89
+ /** Read-only access to the current resolved config — for diagnostics and consumer hydration. */
90
+ getConfig(): Readonly<ResolvedSelectorConfig>;
91
+ /** Replace the current config. Notifies any onConfigChange subscribers. */
92
+ updateConfig(next: ResolvedSelectorConfig): void;
93
+ /**
94
+ * Subscribe to config-change notifications. Returns an unsubscribe function.
95
+ * Used by the Chrome extension to keep its locally-hydrated engine in sync
96
+ * with the customer's SDK as remote config updates flow in.
97
+ */
98
+ onConfigChange(cb: (config: ResolvedSelectorConfig) => void): () => void;
99
+ }
100
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH;;;;GAIG;AACH,MAAM,WAAW,QAAQ;IACvB,6FAA6F;IAC7F,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB;;;;;OAKG;IACH,GAAG,CAAC,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,eAAe,GAAG,MA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AE,CAAC,MAAM,EAAE,sBAAsB,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CAC1E"}
@@ -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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,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;AAGtE,MAAM,WAAW,2BAA2B;IAC1C,gHAAgH;IAChH,KAAK,CAAC,EAAE,UAAU,CAAC;IACnB,8FAA8F;IAC9F,UAAU,CAAC,EAAE,mBAAmB,CAAC,YAAY,CAAC,CAAC;IAC/C;;;;;;OAMG;IACH,MAAM,CAAC,EAAE,qBAAqB,CAAC;CAChC;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAClC,aAAa,EAAE,sBAAsB,EACrC,OAAO,GAAE,2BAAgC,GACxC,cAAc,CAkDhB"}
@@ -0,0 +1,100 @@
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
+ /**
32
+ * Build a `SelectorEngine` bound to the supplied config.
33
+ *
34
+ * The returned engine is independent — calling the factory twice yields two
35
+ * engines with separate config state and separate subscriber lists. This is the
36
+ * shape the autocapture plugin wants (one engine per SDK instance) and the
37
+ * shape the Chrome extension consumes off the page (the extension reads, never
38
+ * writes).
39
+ */
40
+ export function createSelectorEngine(initialConfig, options) {
41
+ if (options === void 0) { options = {}; }
42
+ var config = initialConfig;
43
+ var subscribers = new Set();
44
+ var logger = options.logger;
45
+ var orchestratorOptions = {
46
+ strategies: options.strategies,
47
+ scope: options.scope,
48
+ logger: logger,
49
+ };
50
+ return {
51
+ generate: function (el) {
52
+ var _a, _b;
53
+ // Try the strategy chain first.
54
+ var composed = runOrchestrator(el, config, orchestratorOptions);
55
+ if (composed !== null) {
56
+ return composed;
57
+ }
58
+ // Strategy chain found nothing usable — fall back to the hardened
59
+ // positional walker with the same scope used by the orchestrator.
60
+ return fallbackCssPath(el, config, { scope: (_b = (_a = options.scope) !== null && _a !== void 0 ? _a : el.ownerDocument) !== null && _b !== void 0 ? _b : document });
61
+ },
62
+ getConfig: function () {
63
+ return config;
64
+ },
65
+ updateConfig: function (next) {
66
+ var e_1, _a;
67
+ config = next;
68
+ try {
69
+ // Notify subscribers in insertion order. Errors thrown by individual
70
+ // subscribers are isolated so one bad listener can't break the others —
71
+ // the extension's listener is the canonical consumer here and we don't
72
+ // want SDK-side changes to cascade-fail because of an extension bug.
73
+ for (var subscribers_1 = __values(subscribers), subscribers_1_1 = subscribers_1.next(); !subscribers_1_1.done; subscribers_1_1 = subscribers_1.next()) {
74
+ var cb = subscribers_1_1.value;
75
+ try {
76
+ cb(next);
77
+ }
78
+ catch (e) {
79
+ var message = e instanceof Error ? e.message : String(e);
80
+ logger === null || logger === void 0 ? void 0 : logger.warn("@amplitude/element-selector: onConfigChange subscriber threw \u2014 ".concat(message));
81
+ }
82
+ }
83
+ }
84
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
85
+ finally {
86
+ try {
87
+ if (subscribers_1_1 && !subscribers_1_1.done && (_a = subscribers_1.return)) _a.call(subscribers_1);
88
+ }
89
+ finally { if (e_1) throw e_1.error; }
90
+ }
91
+ },
92
+ onConfigChange: function (cb) {
93
+ subscribers.add(cb);
94
+ return function () {
95
+ subscribers.delete(cb);
96
+ };
97
+ },
98
+ };
99
+ }
100
+ //# sourceMappingURL=engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;;AAGH,OAAO,EAAE,e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AAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;wBAC3D,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,IAAI,CAAC,8EAAkE,OAAO,CAAE,CAAC,CAAC;qBAC3F;iBACF;;;;;;;;;QACH,CAAC;QAED,cAAc,YAAC,EAA4C;YACzD,WAAW,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YACpB,OAAO;gBACL,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACzB,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Engine factory — composes the strategy chain (via `runOrchestrator`) with\n * the safety-net fallback (`fallbackCssPath`) behind a single `SelectorEngine`\n * interface.\n *\n * This is the surface every consumer talks to:\n *\n * - autocapture SDK plugin → instantiates one engine per init() call,\n * wires it into the click handler, and forwards remote-config updates\n * via `updateConfig`.\n * - app.amplitude.com tagging UI → fetches the customer's remote config\n * out-of-band and stands up a transient engine to compute selectors for\n * elements the user clicks in the iframe.\n * - Chrome extension visual tagger → reads the customer's already-live\n * engine off `window.amplitude.elementSelector` (when present) and\n * subscribes to `onConfigChange` so the extension's preview stays in\n * sync with the customer's runtime config.\n *\n * The factory deliberately takes a pre-resolved `ResolvedSelectorConfig` rather\n * than the raw remote payload — config resolution is a separate concern handled\n * by `resolveSelectorConfig`, and keeping it out of the engine constructor lets\n * dashboard / extension consumers stand up an engine from a static snapshot\n * without re-running the full resolver.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { ElementSelectorLogger, ResolvedSelectorConfig, SelectorEngine } from './types';\nimport { runOrchestrator, OrchestratorOptions } from './orchestrator';\nimport { fallbackCssPath } from './fallback-css-path';\n\nexport interface CreateSelectorEngineOptions {\n /** Optional document or shadow root for uniqueness checks. Defaults per-call to the target's owner document. */\n scope?: ParentNode;\n /** Optional override of the strategy chain. Primarily for testing / dashboard ad-hoc runs. */\n strategies?: OrchestratorOptions['strategies'];\n /**\n * Optional logger threaded through the orchestrator and the subscriber-fan-out\n * inside `updateConfig`. When provided, the engine surfaces malformed\n * selectors (`debug`) and listener exceptions (`warn`); when absent it stays\n * silent — preserving the legacy \"fire-and-forget\" semantics existing\n * consumers may rely on.\n */\n logger?: ElementSelectorLogger;\n}\n\n/**\n * Build a `SelectorEngine` bound to the supplied config.\n *\n * The returned engine is independent — calling the factory twice yields two\n * engines with separate config state and separate subscriber lists. This is the\n * shape the autocapture plugin wants (one engine per SDK instance) and the\n * shape the Chrome extension consumes off the page (the extension reads, never\n * writes).\n */\nexport function createSelectorEngine(\n initialConfig: ResolvedSelectorConfig,\n options: CreateSelectorEngineOptions = {},\n): SelectorEngine {\n let config: ResolvedSelectorConfig = initialConfig;\n const subscribers = new Set<(config: ResolvedSelectorConfig) => void>();\n const logger = options.logger;\n\n const orchestratorOptions: OrchestratorOptions = {\n strategies: options.strategies,\n scope: options.scope,\n logger,\n };\n\n return {\n generate(el: Element): string {\n // Try the strategy chain first.\n const composed = runOrchestrator(el, config, orchestratorOptions);\n if (composed !== null) {\n return composed;\n }\n // Strategy chain found nothing usable — fall back to the hardened\n // positional walker with the same scope used by the orchestrator.\n return fallbackCssPath(el, config, { scope: options.scope ?? el.ownerDocument ?? document });\n },\n\n getConfig(): Readonly<ResolvedSelectorConfig> {\n return config;\n },\n\n updateConfig(next: ResolvedSelectorConfig): void {\n config = next;\n // Notify subscribers in insertion order. Errors thrown by individual\n // subscribers are isolated so one bad listener can't break the others —\n // the extension's listener is the canonical consumer here and we don't\n // want SDK-side changes to cascade-fail because of an extension bug.\n for (const cb of subscribers) {\n try {\n cb(next);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: onConfigChange subscriber threw — ${message}`);\n }\n }\n },\n\n onConfigChange(cb: (config: ResolvedSelectorConfig) => void): () => void {\n subscribers.add(cb);\n return () => {\n subscribers.delete(cb);\n };\n },\n };\n}\n"]}
@@ -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"}