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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACxF,OAAO,EAAmB,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;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"}
1
+ {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACxF,OAAO,EAAmB,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAItE,MAAM,WAAW,2BAA2B;IAC1C,gHAAgH;IAChH,KAAK,CAAC,EAAE,UAAU,CAAC;IACnB,8FAA8F;IAC9F,UAAU,CAAC,EAAE,mBAAmB,CAAC,YAAY,CAAC,CAAC;IAC/C;;;;;;OAMG;IACH,MAAM,CAAC,EAAE,qBAAqB,CAAC;CAChC;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAClC,aAAa,EAAE,sBAAsB,EACrC,OAAO,GAAE,2BAAgC,GACxC,cAAc,CAoFhB"}
package/lib/cjs/engine.js CHANGED
@@ -31,6 +31,7 @@ exports.createSelectorEngine = void 0;
31
31
  var tslib_1 = require("tslib");
32
32
  var orchestrator_1 = require("./orchestrator");
33
33
  var fallback_css_path_1 = require("./fallback-css-path");
34
+ var legacy_css_path_1 = require("./legacy-css-path");
34
35
  /**
35
36
  * Build a `SelectorEngine` bound to the supplied config.
36
37
  *
@@ -53,14 +54,33 @@ function createSelectorEngine(initialConfig, options) {
53
54
  return {
54
55
  generate: function (el) {
55
56
  var _a, _b;
56
- // Try the strategy chain first.
57
- var composed = (0, orchestrator_1.runOrchestrator)(el, config, orchestratorOptions);
58
- if (composed !== null) {
59
- return composed;
57
+ // Kill switch: when the customer's remote config has the engine
58
+ // disabled (the default for orgs that haven't opted in), emit the same
59
+ // Chromium-derived selector autocapture has shipped since before the
60
+ // strategy chain existed. This is what makes "flip enabled back to
61
+ // false" a one-config-fetch revert for both the SDK and the dashboard —
62
+ // they both go through this entry point now.
63
+ if (!config.enabled) {
64
+ return safeLegacyCssPath(el);
65
+ }
66
+ // Engine path: try the strategy chain, then the hardened fallback. Both
67
+ // are wrapped so a runtime exception (malformed config slipped past the
68
+ // resolver, browser API quirks, a bad scope) still produces a usable
69
+ // selector. Without this, an autocapture click handler could throw
70
+ // mid-flow and the customer would silently lose the event — a worse
71
+ // outcome than emitting a less-stable selector.
72
+ try {
73
+ var composed = (0, orchestrator_1.runOrchestrator)(el, config, orchestratorOptions);
74
+ if (composed !== null) {
75
+ return composed;
76
+ }
77
+ return (0, fallback_css_path_1.fallbackCssPath)(el, config, { scope: (_b = (_a = options.scope) !== null && _a !== void 0 ? _a : el.ownerDocument) !== null && _b !== void 0 ? _b : document });
78
+ }
79
+ catch (e) {
80
+ var message = e instanceof Error ? e.message : String(e);
81
+ logger === null || logger === void 0 ? void 0 : logger.warn("@amplitude/element-selector: strategy chain threw \u2014 falling back to legacy cssPath: ".concat(message));
82
+ return safeLegacyCssPath(el);
60
83
  }
61
- // Strategy chain found nothing usable — fall back to the hardened
62
- // positional walker with the same scope used by the orchestrator.
63
- return (0, fallback_css_path_1.fallbackCssPath)(el, config, { scope: (_b = (_a = options.scope) !== null && _a !== void 0 ? _a : el.ownerDocument) !== null && _b !== void 0 ? _b : document });
64
84
  },
65
85
  getConfig: function () {
66
86
  return config;
@@ -99,6 +119,21 @@ function createSelectorEngine(initialConfig, options) {
99
119
  };
100
120
  },
101
121
  };
122
+ // Local wrapper so a thrown error in the legacy walker (extremely unlikely
123
+ // — Element inputs only — but defensible if a host environment is missing
124
+ // `CSS.escape` or `Node` constants) doesn't escape `generate` and crash the
125
+ // caller. Returns the empty string in that pathological case; consumers
126
+ // already coalesce empty results to a sentinel.
127
+ function safeLegacyCssPath(el) {
128
+ try {
129
+ return (0, legacy_css_path_1.legacyCssPath)(el);
130
+ }
131
+ catch (e) {
132
+ var message = e instanceof Error ? e.message : String(e);
133
+ logger === null || logger === void 0 ? void 0 : logger.warn("@amplitude/element-selector: legacyCssPath threw \u2014 emitting empty selector: ".concat(message));
134
+ return '';
135
+ }
136
+ }
102
137
  }
103
138
  exports.createSelectorEngine = createSelectorEngine;
104
139
  //# sourceMappingURL=engine.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;;;;AAGH,+CAAsE;AACtE,yDAAsD;AAiBtD;;;;;;;;GAQG;AACH,SAAgB,oBAAoB,CAClC,aAAqC,EACrC,OAAyC;IAAzC,wBAAA,EAAA,YAAyC;IAEzC,IAAI,MAAM,GAA2B,aAAa,CAAC;IACnD,IAAM,WAAW,GAAG,IAAI,GAAG,EAA4C,CAAC;IACxE,IAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAE9B,IAAM,mBAAmB,GAAwB;QAC/C,UAAU,EAAE,OAAO,CAAC,UAAU;QAC9B,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,MAAM,QAAA;KACP,CAAC;IAEF,OAAO;QACL,QAAQ,YAAC,EAAW;;YAClB,gCAAgC;YAChC,IAAM,QAAQ,GAAG,IAAA,8BAAe,EAAC,EAAE,EAAE,MAAM,EAAE,mBAAmB,CAAC,CAAC;YAClE,IAAI,QAAQ,KAAK,IAAI,EAAE;gBACrB,OAAO,QAAQ,CAAC;aACjB;YACD,kEAAkE;YAClE,kEAAkE;YAClE,OAAO,IAAA,mCAAe,EAAC,EAAE,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,MAAA,MAAA,OAAO,CAAC,KAAK,mCAAI,EAAE,CAAC,aAAa,mCAAI,QAAQ,EAAE,CAAC,CAAC;QAC/F,CAAC;QAED,SAAS;YACP,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,YAAY,YAAC,IAA4B;;YACvC,MAAM,GAAG,IAAI,CAAC;;gBACd,qEAAqE;gBACrE,wEAAwE;gBACxE,uEAAuE;gBACvE,qEAAqE;gBACrE,KAAiB,IAAA,gBAAA,iBAAA,WAAW,CAAA,wCAAA,iEAAE;oBAAzB,IAAM,EAAE,wBAAA;oBACX,IAAI;wBACF,EAAE,CAAC,IAAI,CAAC,CAAC;qBACV;oBAAC,OAAO,CAAC,EAAE;wBACV,IAAM,OAAO,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;wBAC3D,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,IAAI,CAAC,8EAAkE,OAAO,CAAE,CAAC,CAAC;qBAC3F;iBACF;;;;;;;;;QACH,CAAC;QAED,cAAc,YAAC,EAA4C;YACzD,WAAW,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YACpB,OAAO;gBACL,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACzB,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC;AArDD,oDAqDC","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"]}
1
+ {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * Engine factory — composes the strategy chain (via `runOrchestrator`) with\n * the safety-net fallback (`fallbackCssPath`) behind a single `SelectorEngine`\n * interface.\n *\n * This is the surface every consumer talks to:\n *\n * - autocapture SDK plugin → instantiates one engine per init() call,\n * wires it into the click handler, and forwards remote-config updates\n * via `updateConfig`.\n * - app.amplitude.com tagging UI → fetches the customer's remote config\n * out-of-band and stands up a transient engine to compute selectors for\n * elements the user clicks in the iframe.\n * - Chrome extension visual tagger → reads the customer's already-live\n * engine off `window.amplitude.elementSelector` (when present) and\n * subscribes to `onConfigChange` so the extension's preview stays in\n * sync with the customer's runtime config.\n *\n * The factory deliberately takes a pre-resolved `ResolvedSelectorConfig` rather\n * than the raw remote payload — config resolution is a separate concern handled\n * by `resolveSelectorConfig`, and keeping it out of the engine constructor lets\n * dashboard / extension consumers stand up an engine from a static snapshot\n * without re-running the full resolver.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { ElementSelectorLogger, ResolvedSelectorConfig, SelectorEngine } from './types';\nimport { runOrchestrator, OrchestratorOptions } from './orchestrator';\nimport { fallbackCssPath } from './fallback-css-path';\nimport { legacyCssPath } from './legacy-css-path';\n\nexport interface CreateSelectorEngineOptions {\n /** Optional document or shadow root for uniqueness checks. Defaults per-call to the target's owner document. */\n scope?: ParentNode;\n /** Optional override of the strategy chain. Primarily for testing / dashboard ad-hoc runs. */\n strategies?: OrchestratorOptions['strategies'];\n /**\n * Optional logger threaded through the orchestrator and the subscriber-fan-out\n * inside `updateConfig`. When provided, the engine surfaces malformed\n * selectors (`debug`) and listener exceptions (`warn`); when absent it stays\n * silent — preserving the legacy \"fire-and-forget\" semantics existing\n * consumers may rely on.\n */\n logger?: ElementSelectorLogger;\n}\n\n/**\n * Build a `SelectorEngine` bound to the supplied config.\n *\n * The returned engine is independent — calling the factory twice yields two\n * engines with separate config state and separate subscriber lists. This is the\n * shape the autocapture plugin wants (one engine per SDK instance) and the\n * shape the Chrome extension consumes off the page (the extension reads, never\n * writes).\n */\nexport function createSelectorEngine(\n initialConfig: ResolvedSelectorConfig,\n options: CreateSelectorEngineOptions = {},\n): SelectorEngine {\n let config: ResolvedSelectorConfig = initialConfig;\n const subscribers = new Set<(config: ResolvedSelectorConfig) => void>();\n const logger = options.logger;\n\n const orchestratorOptions: OrchestratorOptions = {\n strategies: options.strategies,\n scope: options.scope,\n logger,\n };\n\n return {\n generate(el: Element): string {\n // Kill switch: when the customer's remote config has the engine\n // disabled (the default for orgs that haven't opted in), emit the same\n // Chromium-derived selector autocapture has shipped since before the\n // strategy chain existed. This is what makes \"flip enabled back to\n // false\" a one-config-fetch revert for both the SDK and the dashboard —\n // they both go through this entry point now.\n if (!config.enabled) {\n return safeLegacyCssPath(el);\n }\n\n // Engine path: try the strategy chain, then the hardened fallback. Both\n // are wrapped so a runtime exception (malformed config slipped past the\n // resolver, browser API quirks, a bad scope) still produces a usable\n // selector. Without this, an autocapture click handler could throw\n // mid-flow and the customer would silently lose the event — a worse\n // outcome than emitting a less-stable selector.\n try {\n const composed = runOrchestrator(el, config, orchestratorOptions);\n if (composed !== null) {\n return composed;\n }\n return fallbackCssPath(el, config, { scope: options.scope ?? el.ownerDocument ?? document });\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: strategy chain threw — falling back to legacy cssPath: ${message}`);\n return safeLegacyCssPath(el);\n }\n },\n\n getConfig(): Readonly<ResolvedSelectorConfig> {\n return config;\n },\n\n updateConfig(next: ResolvedSelectorConfig): void {\n config = next;\n // Notify subscribers in insertion order. Errors thrown by individual\n // subscribers are isolated so one bad listener can't break the others —\n // the extension's listener is the canonical consumer here and we don't\n // want SDK-side changes to cascade-fail because of an extension bug.\n for (const cb of subscribers) {\n try {\n cb(next);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: onConfigChange subscriber threw — ${message}`);\n }\n }\n },\n\n onConfigChange(cb: (config: ResolvedSelectorConfig) => void): () => void {\n subscribers.add(cb);\n return () => {\n subscribers.delete(cb);\n };\n },\n };\n\n // Local wrapper so a thrown error in the legacy walker (extremely unlikely\n // — Element inputs only — but defensible if a host environment is missing\n // `CSS.escape` or `Node` constants) doesn't escape `generate` and crash the\n // caller. Returns the empty string in that pathological case; consumers\n // already coalesce empty results to a sentinel.\n function safeLegacyCssPath(el: Element): string {\n try {\n return legacyCssPath(el);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: legacyCssPath threw — emitting empty selector: ${message}`);\n return '';\n }\n }\n}\n"]}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Top-level chokepoint for "generate a selector for this element."
3
+ *
4
+ * Both the SDK plugin (`plugin-autocapture-browser`) and the dashboard
5
+ * (`session-replay-ui`) used to maintain their own copy of this routing logic:
6
+ *
7
+ * if (config.enabled && engine) return engine.generate(el);
8
+ * else return cssPath(el, false);
9
+ *
10
+ * Two consumers, two routers, two locally-bundled copies of `cssPath`. As soon
11
+ * as we considered a third consumer (Chrome extension visual tagger, future
12
+ * tagging surfaces) the duplication became untenable — bug fixes had to land
13
+ * three places and the kill-switch semantics could drift between them.
14
+ *
15
+ * Moving the kill switch inside `engine.generate` covered the "engine present"
16
+ * case. This helper covers the remaining "engine is null" case that some
17
+ * consumers genuinely have:
18
+ *
19
+ * - dashboard's `useElementSelectorEngineContext()` returns
20
+ * `{ engine: null }` when no provider is mounted (tests, content-renderer
21
+ * paths, future call sites outside the canonical mount tree).
22
+ * - Chrome extension boots before the customer's SDK has stood up an engine
23
+ * on the page; reads `null` from `window.amplitude.elementSelector` until
24
+ * the SDK init finishes.
25
+ *
26
+ * In those cases, callers want the legacy `cssPath` selector — same shape the
27
+ * SDK is emitting in production for orgs without the engine. This helper makes
28
+ * that explicit and centralizes the rule so future consumers don't reinvent
29
+ * it.
30
+ */
31
+ import { ResolvedSelectorConfig, SelectorEngine } from './types';
32
+ /**
33
+ * Generate a selector for `el`, transparently routing to the legacy
34
+ * `cssPath` walker when no engine is available.
35
+ *
36
+ * Why this signature (engine + config separately, rather than just engine):
37
+ * the dashboard's inert context has `engine: null` but still carries a
38
+ * resolved config. Both `null`-engine and engine-with-`enabled: false`
39
+ * collapse to "legacy `cssPath`", and we want the same one-line call site
40
+ * to handle both. When the engine *is* present, this just delegates — the
41
+ * engine's own kill switch handles `enabled === false`.
42
+ *
43
+ * Never throws. Returns the empty string in the pathological case where the
44
+ * legacy walker itself can't produce one (non-element nodes; environments
45
+ * missing `CSS.escape`).
46
+ *
47
+ * @param el DOM element to identify.
48
+ * @param engine Live `SelectorEngine`, or `null` when no engine is mounted.
49
+ * @param config Resolved selector config. Only consulted in the null-engine
50
+ * branch; when `engine` is present, the engine consults its
51
+ * own internal config.
52
+ */
53
+ export declare const generateSelector: (el: Element, engine: SelectorEngine | null, config: ResolvedSelectorConfig) => string;
54
+ //# sourceMappingURL=generate-selector.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-selector.d.ts","sourceRoot":"","sources":["../../src/generate-selector.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAGjE;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,gBAAgB,OACvB,OAAO,UACH,cAAc,GAAG,IAAI,UACrB,sBAAsB,KAC7B,MAiBF,CAAC"}
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ /**
3
+ * Top-level chokepoint for "generate a selector for this element."
4
+ *
5
+ * Both the SDK plugin (`plugin-autocapture-browser`) and the dashboard
6
+ * (`session-replay-ui`) used to maintain their own copy of this routing logic:
7
+ *
8
+ * if (config.enabled && engine) return engine.generate(el);
9
+ * else return cssPath(el, false);
10
+ *
11
+ * Two consumers, two routers, two locally-bundled copies of `cssPath`. As soon
12
+ * as we considered a third consumer (Chrome extension visual tagger, future
13
+ * tagging surfaces) the duplication became untenable — bug fixes had to land
14
+ * three places and the kill-switch semantics could drift between them.
15
+ *
16
+ * Moving the kill switch inside `engine.generate` covered the "engine present"
17
+ * case. This helper covers the remaining "engine is null" case that some
18
+ * consumers genuinely have:
19
+ *
20
+ * - dashboard's `useElementSelectorEngineContext()` returns
21
+ * `{ engine: null }` when no provider is mounted (tests, content-renderer
22
+ * paths, future call sites outside the canonical mount tree).
23
+ * - Chrome extension boots before the customer's SDK has stood up an engine
24
+ * on the page; reads `null` from `window.amplitude.elementSelector` until
25
+ * the SDK init finishes.
26
+ *
27
+ * In those cases, callers want the legacy `cssPath` selector — same shape the
28
+ * SDK is emitting in production for orgs without the engine. This helper makes
29
+ * that explicit and centralizes the rule so future consumers don't reinvent
30
+ * it.
31
+ */
32
+ Object.defineProperty(exports, "__esModule", { value: true });
33
+ exports.generateSelector = void 0;
34
+ var legacy_css_path_1 = require("./legacy-css-path");
35
+ /**
36
+ * Generate a selector for `el`, transparently routing to the legacy
37
+ * `cssPath` walker when no engine is available.
38
+ *
39
+ * Why this signature (engine + config separately, rather than just engine):
40
+ * the dashboard's inert context has `engine: null` but still carries a
41
+ * resolved config. Both `null`-engine and engine-with-`enabled: false`
42
+ * collapse to "legacy `cssPath`", and we want the same one-line call site
43
+ * to handle both. When the engine *is* present, this just delegates — the
44
+ * engine's own kill switch handles `enabled === false`.
45
+ *
46
+ * Never throws. Returns the empty string in the pathological case where the
47
+ * legacy walker itself can't produce one (non-element nodes; environments
48
+ * missing `CSS.escape`).
49
+ *
50
+ * @param el DOM element to identify.
51
+ * @param engine Live `SelectorEngine`, or `null` when no engine is mounted.
52
+ * @param config Resolved selector config. Only consulted in the null-engine
53
+ * branch; when `engine` is present, the engine consults its
54
+ * own internal config.
55
+ */
56
+ var generateSelector = function (el, engine, config) {
57
+ if (engine) {
58
+ // The engine has its own kill switch (`config.enabled === false` →
59
+ // legacy cssPath) and its own try/catch safety net. Trust it.
60
+ return engine.generate(el);
61
+ }
62
+ // Engine-null branch. We don't have a live engine to consult, so we route
63
+ // straight to the legacy walker — the same selector the SDK would be
64
+ // emitting if `config.enabled === false`. `config` is accepted for symmetry
65
+ // with the engine signature and so future versions can extend behavior
66
+ // without a breaking change.
67
+ void config;
68
+ try {
69
+ return (0, legacy_css_path_1.legacyCssPath)(el);
70
+ }
71
+ catch (_a) {
72
+ return '';
73
+ }
74
+ };
75
+ exports.generateSelector = generateSelector;
76
+ //# sourceMappingURL=generate-selector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-selector.js","sourceRoot":"","sources":["../../src/generate-selector.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;;;AAGH,qDAAkD;AAElD;;;;;;;;;;;;;;;;;;;;GAoBG;AACI,IAAM,gBAAgB,GAAG,UAC9B,EAAW,EACX,MAA6B,EAC7B,MAA8B;IAE9B,IAAI,MAAM,EAAE;QACV,mEAAmE;QACnE,8DAA8D;QAC9D,OAAO,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;KAC5B;IACD,0EAA0E;IAC1E,qEAAqE;IACrE,4EAA4E;IAC5E,uEAAuE;IACvE,6BAA6B;IAC7B,KAAK,MAAM,CAAC;IACZ,IAAI;QACF,OAAO,IAAA,+BAAa,EAAC,EAAE,CAAC,CAAC;KAC1B;IAAC,WAAM;QACN,OAAO,EAAE,CAAC;KACX;AACH,CAAC,CAAC;AArBW,QAAA,gBAAgB,oBAqB3B","sourcesContent":["/**\n * Top-level chokepoint for \"generate a selector for this element.\"\n *\n * Both the SDK plugin (`plugin-autocapture-browser`) and the dashboard\n * (`session-replay-ui`) used to maintain their own copy of this routing logic:\n *\n * if (config.enabled && engine) return engine.generate(el);\n * else return cssPath(el, false);\n *\n * Two consumers, two routers, two locally-bundled copies of `cssPath`. As soon\n * as we considered a third consumer (Chrome extension visual tagger, future\n * tagging surfaces) the duplication became untenable — bug fixes had to land\n * three places and the kill-switch semantics could drift between them.\n *\n * Moving the kill switch inside `engine.generate` covered the \"engine present\"\n * case. This helper covers the remaining \"engine is null\" case that some\n * consumers genuinely have:\n *\n * - dashboard's `useElementSelectorEngineContext()` returns\n * `{ engine: null }` when no provider is mounted (tests, content-renderer\n * paths, future call sites outside the canonical mount tree).\n * - Chrome extension boots before the customer's SDK has stood up an engine\n * on the page; reads `null` from `window.amplitude.elementSelector` until\n * the SDK init finishes.\n *\n * In those cases, callers want the legacy `cssPath` selector — same shape the\n * SDK is emitting in production for orgs without the engine. This helper makes\n * that explicit and centralizes the rule so future consumers don't reinvent\n * it.\n */\n\nimport { ResolvedSelectorConfig, SelectorEngine } from './types';\nimport { legacyCssPath } from './legacy-css-path';\n\n/**\n * Generate a selector for `el`, transparently routing to the legacy\n * `cssPath` walker when no engine is available.\n *\n * Why this signature (engine + config separately, rather than just engine):\n * the dashboard's inert context has `engine: null` but still carries a\n * resolved config. Both `null`-engine and engine-with-`enabled: false`\n * collapse to \"legacy `cssPath`\", and we want the same one-line call site\n * to handle both. When the engine *is* present, this just delegates — the\n * engine's own kill switch handles `enabled === false`.\n *\n * Never throws. Returns the empty string in the pathological case where the\n * legacy walker itself can't produce one (non-element nodes; environments\n * missing `CSS.escape`).\n *\n * @param el DOM element to identify.\n * @param engine Live `SelectorEngine`, or `null` when no engine is mounted.\n * @param config Resolved selector config. Only consulted in the null-engine\n * branch; when `engine` is present, the engine consults its\n * own internal config.\n */\nexport const generateSelector = (\n el: Element,\n engine: SelectorEngine | null,\n config: ResolvedSelectorConfig,\n): string => {\n if (engine) {\n // The engine has its own kill switch (`config.enabled === false` →\n // legacy cssPath) and its own try/catch safety net. Trust it.\n return engine.generate(el);\n }\n // Engine-null branch. We don't have a live engine to consult, so we route\n // straight to the legacy walker — the same selector the SDK would be\n // emitting if `config.enabled === false`. `config` is accepted for symmetry\n // with the engine signature and so future versions can extend behavior\n // without a breaking change.\n void config;\n try {\n return legacyCssPath(el);\n } catch {\n return '';\n }\n};\n"]}
@@ -23,7 +23,9 @@ export { stableId as stableIdStrategy } from './strategies/stable-id';
23
23
  export { runOrchestrator, DEFAULT_STRATEGIES } from './orchestrator';
24
24
  export type { OrchestratorOptions } from './orchestrator';
25
25
  export { fallbackCssPath } from './fallback-css-path';
26
+ export { legacyCssPath } from './legacy-css-path';
26
27
  export { resolveSelectorConfig, DEFAULT_RESOLVED_CONFIG } from './config/resolve-config';
27
28
  export { createSelectorEngine } from './engine';
28
29
  export type { CreateSelectorEngineOptions } from './engine';
30
+ export { generateSelector } from './generate-selector';
29
31
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,eAAO,MAAM,YAAY,gCAAgC,CAAC;AAG1D,YAAY,EACV,QAAQ,EACR,eAAe,EACf,sBAAsB,EACtB,2BAA2B,EAC3B,qBAAqB,EACrB,cAAc,GACf,MAAM,SAAS,CAAC;AAGjB,OAAO,EACL,iCAAiC,EACjC,OAAO,IAAI,8BAA8B,EACzC,UAAU,GACX,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,+BAA+B,EAC/B,OAAO,IAAI,4BAA4B,EACvC,aAAa,GACd,MAAM,6BAA6B,CAAC;AAGrC,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAG/D,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AACrF,OAAO,EAAE,QAAQ,IAAI,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAKtE,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACrE,YAAY,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAGtD,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAGzF,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAChD,YAAY,EAAE,2BAA2B,EAAE,MAAM,UAAU,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,eAAO,MAAM,YAAY,gCAAgC,CAAC;AAG1D,YAAY,EACV,QAAQ,EACR,eAAe,EACf,sBAAsB,EACtB,2BAA2B,EAC3B,qBAAqB,EACrB,cAAc,GACf,MAAM,SAAS,CAAC;AAGjB,OAAO,EACL,iCAAiC,EACjC,OAAO,IAAI,8BAA8B,EACzC,UAAU,GACX,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,+BAA+B,EAC/B,OAAO,IAAI,4BAA4B,EACvC,aAAa,GACd,MAAM,6BAA6B,CAAC;AAGrC,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAG/D,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AACrF,OAAO,EAAE,QAAQ,IAAI,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAKtE,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACrE,YAAY,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAWtD,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAGlD,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAGzF,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAChD,YAAY,EAAE,2BAA2B,EAAE,MAAM,UAAU,CAAC;AAO5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC"}
package/lib/cjs/index.js CHANGED
@@ -14,7 +14,7 @@
14
14
  * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
15
15
  */
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.createSelectorEngine = exports.DEFAULT_RESOLVED_CONFIG = exports.resolveSelectorConfig = exports.fallbackCssPath = exports.DEFAULT_STRATEGIES = exports.runOrchestrator = exports.stableIdStrategy = exports.explicitTrackingAttribute = exports.describeRelative = exports.getStableId = exports.filterClasses = exports.compileUnstableClassPatterns = exports.DEFAULT_UNSTABLE_CLASS_PATTERNS = exports.isStableId = exports.compileAutogeneratedIdPatterns = exports.DEFAULT_AUTOGENERATED_ID_PATTERNS = exports.PACKAGE_NAME = void 0;
17
+ exports.generateSelector = exports.createSelectorEngine = exports.DEFAULT_RESOLVED_CONFIG = exports.resolveSelectorConfig = exports.legacyCssPath = exports.fallbackCssPath = exports.DEFAULT_STRATEGIES = exports.runOrchestrator = exports.stableIdStrategy = exports.explicitTrackingAttribute = exports.describeRelative = exports.getStableId = exports.filterClasses = exports.compileUnstableClassPatterns = exports.DEFAULT_UNSTABLE_CLASS_PATTERNS = exports.isStableId = exports.compileAutogeneratedIdPatterns = exports.DEFAULT_AUTOGENERATED_ID_PATTERNS = exports.PACKAGE_NAME = void 0;
18
18
  exports.PACKAGE_NAME = '@amplitude/element-selector';
19
19
  // ===== Pattern packs =====
20
20
  var autogenerated_ids_1 = require("./patterns/autogenerated-ids");
@@ -43,6 +43,17 @@ Object.defineProperty(exports, "runOrchestrator", { enumerable: true, get: funct
43
43
  Object.defineProperty(exports, "DEFAULT_STRATEGIES", { enumerable: true, get: function () { return orchestrator_1.DEFAULT_STRATEGIES; } });
44
44
  var fallback_css_path_1 = require("./fallback-css-path");
45
45
  Object.defineProperty(exports, "fallbackCssPath", { enumerable: true, get: function () { return fallback_css_path_1.fallbackCssPath; } });
46
+ // ===== Legacy walker =====
47
+ // Canonical home for the Chromium-DevTools-derived `cssPath` algorithm.
48
+ // Both `plugin-autocapture-browser` and `session-replay-ui` historically
49
+ // shipped their own copies kept in sync by comment; both will switch to
50
+ // re-exporting from here so the two can never drift again. End consumers
51
+ // rarely need to call this directly — `engine.generate` and
52
+ // `generateSelector` route through it automatically — but it's exported so
53
+ // the SDK and dashboard can drop their local copies without breaking
54
+ // downstream imports.
55
+ var legacy_css_path_1 = require("./legacy-css-path");
56
+ Object.defineProperty(exports, "legacyCssPath", { enumerable: true, get: function () { return legacy_css_path_1.legacyCssPath; } });
46
57
  // ===== Config resolver =====
47
58
  var resolve_config_1 = require("./config/resolve-config");
48
59
  Object.defineProperty(exports, "resolveSelectorConfig", { enumerable: true, get: function () { return resolve_config_1.resolveSelectorConfig; } });
@@ -50,4 +61,11 @@ Object.defineProperty(exports, "DEFAULT_RESOLVED_CONFIG", { enumerable: true, ge
50
61
  // ===== Engine factory =====
51
62
  var engine_1 = require("./engine");
52
63
  Object.defineProperty(exports, "createSelectorEngine", { enumerable: true, get: function () { return engine_1.createSelectorEngine; } });
64
+ // ===== Top-level selector entry point =====
65
+ // Use this from React contexts / boot-time call sites where the engine may
66
+ // not yet be available. When the engine *is* present, just call
67
+ // `engine.generate(el)` directly — it has the same kill-switch semantics
68
+ // baked in.
69
+ var generate_selector_1 = require("./generate-selector");
70
+ Object.defineProperty(exports, "generateSelector", { enumerable: true, get: function () { return generate_selector_1.generateSelector; } });
53
71
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;GAaG;;;AAEU,QAAA,YAAY,GAAG,6BAA6B,CAAC;AAY1D,4BAA4B;AAC5B,kEAIsC;AAHpC,sIAAA,iCAAiC,OAAA;AACjC,mIAAA,OAAO,OAAkC;AACzC,+GAAA,UAAU,OAAA;AAGZ,gEAIqC;AAHnC,mIAAA,+BAA+B,OAAA;AAC/B,gIAAA,OAAO,OAAgC;AACvC,iHAAA,aAAa,OAAA;AAGf,sBAAsB;AACtB,yDAAsD;AAA7C,4GAAA,WAAW,OAAA;AACpB,iEAA+D;AAAtD,qHAAA,gBAAgB,OAAA;AAEzB,yBAAyB;AACzB,wFAAqF;AAA5E,wIAAA,yBAAyB,OAAA;AAClC,oDAAsE;AAA7D,6GAAA,QAAQ,OAAoB;AAErC,sCAAsC;AACtC,4EAA4E;AAC5E,8EAA8E;AAC9E,+CAAqE;AAA5D,+GAAA,eAAe,OAAA;AAAE,kHAAA,kBAAkB,OAAA;AAE5C,yDAAsD;AAA7C,oHAAA,eAAe,OAAA;AAExB,8BAA8B;AAC9B,0DAAyF;AAAhF,uHAAA,qBAAqB,OAAA;AAAE,yHAAA,uBAAuB,OAAA;AAEvD,6BAA6B;AAC7B,mCAAgD;AAAvC,8GAAA,oBAAoB,OAAA","sourcesContent":["/**\n * @amplitude/element-selector\n *\n * Shared element-selector algorithm consumed by autocapture, the\n * app.amplitude.com tagging UI, and the Chrome extension visual tagger.\n *\n * This file is the package's public API surface. The orchestrator, fallback,\n * config resolver, and engine factory compose on top of the primitives\n * (types, pattern packs, helpers, strategies) to produce the runtime engine\n * consumers actually call.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nexport const PACKAGE_NAME = '@amplitude/element-selector';\n\n// ===== Types =====\nexport type {\n Strategy,\n StrategyContext,\n ResolvedSelectorConfig,\n ElementSelectorRemoteConfig,\n ElementSelectorLogger,\n SelectorEngine,\n} from './types';\n\n// ===== Pattern packs =====\nexport {\n DEFAULT_AUTOGENERATED_ID_PATTERNS,\n compile as compileAutogeneratedIdPatterns,\n isStableId,\n} from './patterns/autogenerated-ids';\n\nexport {\n DEFAULT_UNSTABLE_CLASS_PATTERNS,\n compile as compileUnstableClassPatterns,\n filterClasses,\n} from './patterns/unstable-classes';\n\n// ===== Helpers =====\nexport { getStableId } from './helpers/get-stable-id';\nexport { describeRelative } from './helpers/describe-relative';\n\n// ===== Strategies =====\nexport { explicitTrackingAttribute } from './strategies/explicit-tracking-attribute';\nexport { stableId as stableIdStrategy } from './strategies/stable-id';\n\n// ===== Orchestrator + fallback =====\n// Exposed publicly so the dashboard / Chrome extension can call them ad-hoc\n// without instantiating a full engine — useful for preview / debugging flows.\nexport { runOrchestrator, DEFAULT_STRATEGIES } from './orchestrator';\nexport type { OrchestratorOptions } from './orchestrator';\nexport { fallbackCssPath } from './fallback-css-path';\n\n// ===== Config resolver =====\nexport { resolveSelectorConfig, DEFAULT_RESOLVED_CONFIG } from './config/resolve-config';\n\n// ===== Engine factory =====\nexport { createSelectorEngine } from './engine';\nexport type { CreateSelectorEngineOptions } from './engine';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;GAaG;;;AAEU,QAAA,YAAY,GAAG,6BAA6B,CAAC;AAY1D,4BAA4B;AAC5B,kEAIsC;AAHpC,sIAAA,iCAAiC,OAAA;AACjC,mIAAA,OAAO,OAAkC;AACzC,+GAAA,UAAU,OAAA;AAGZ,gEAIqC;AAHnC,mIAAA,+BAA+B,OAAA;AAC/B,gIAAA,OAAO,OAAgC;AACvC,iHAAA,aAAa,OAAA;AAGf,sBAAsB;AACtB,yDAAsD;AAA7C,4GAAA,WAAW,OAAA;AACpB,iEAA+D;AAAtD,qHAAA,gBAAgB,OAAA;AAEzB,yBAAyB;AACzB,wFAAqF;AAA5E,wIAAA,yBAAyB,OAAA;AAClC,oDAAsE;AAA7D,6GAAA,QAAQ,OAAoB;AAErC,sCAAsC;AACtC,4EAA4E;AAC5E,8EAA8E;AAC9E,+CAAqE;AAA5D,+GAAA,eAAe,OAAA;AAAE,kHAAA,kBAAkB,OAAA;AAE5C,yDAAsD;AAA7C,oHAAA,eAAe,OAAA;AAExB,4BAA4B;AAC5B,wEAAwE;AACxE,yEAAyE;AACzE,wEAAwE;AACxE,yEAAyE;AACzE,4DAA4D;AAC5D,2EAA2E;AAC3E,qEAAqE;AACrE,sBAAsB;AACtB,qDAAkD;AAAzC,gHAAA,aAAa,OAAA;AAEtB,8BAA8B;AAC9B,0DAAyF;AAAhF,uHAAA,qBAAqB,OAAA;AAAE,yHAAA,uBAAuB,OAAA;AAEvD,6BAA6B;AAC7B,mCAAgD;AAAvC,8GAAA,oBAAoB,OAAA;AAG7B,6CAA6C;AAC7C,2EAA2E;AAC3E,gEAAgE;AAChE,yEAAyE;AACzE,YAAY;AACZ,yDAAuD;AAA9C,qHAAA,gBAAgB,OAAA","sourcesContent":["/**\n * @amplitude/element-selector\n *\n * Shared element-selector algorithm consumed by autocapture, the\n * app.amplitude.com tagging UI, and the Chrome extension visual tagger.\n *\n * This file is the package's public API surface. The orchestrator, fallback,\n * config resolver, and engine factory compose on top of the primitives\n * (types, pattern packs, helpers, strategies) to produce the runtime engine\n * consumers actually call.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nexport const PACKAGE_NAME = '@amplitude/element-selector';\n\n// ===== Types =====\nexport type {\n Strategy,\n StrategyContext,\n ResolvedSelectorConfig,\n ElementSelectorRemoteConfig,\n ElementSelectorLogger,\n SelectorEngine,\n} from './types';\n\n// ===== Pattern packs =====\nexport {\n DEFAULT_AUTOGENERATED_ID_PATTERNS,\n compile as compileAutogeneratedIdPatterns,\n isStableId,\n} from './patterns/autogenerated-ids';\n\nexport {\n DEFAULT_UNSTABLE_CLASS_PATTERNS,\n compile as compileUnstableClassPatterns,\n filterClasses,\n} from './patterns/unstable-classes';\n\n// ===== Helpers =====\nexport { getStableId } from './helpers/get-stable-id';\nexport { describeRelative } from './helpers/describe-relative';\n\n// ===== Strategies =====\nexport { explicitTrackingAttribute } from './strategies/explicit-tracking-attribute';\nexport { stableId as stableIdStrategy } from './strategies/stable-id';\n\n// ===== Orchestrator + fallback =====\n// Exposed publicly so the dashboard / Chrome extension can call them ad-hoc\n// without instantiating a full engine — useful for preview / debugging flows.\nexport { runOrchestrator, DEFAULT_STRATEGIES } from './orchestrator';\nexport type { OrchestratorOptions } from './orchestrator';\nexport { fallbackCssPath } from './fallback-css-path';\n\n// ===== Legacy walker =====\n// Canonical home for the Chromium-DevTools-derived `cssPath` algorithm.\n// Both `plugin-autocapture-browser` and `session-replay-ui` historically\n// shipped their own copies kept in sync by comment; both will switch to\n// re-exporting from here so the two can never drift again. End consumers\n// rarely need to call this directly — `engine.generate` and\n// `generateSelector` route through it automatically — but it's exported so\n// the SDK and dashboard can drop their local copies without breaking\n// downstream imports.\nexport { legacyCssPath } from './legacy-css-path';\n\n// ===== Config resolver =====\nexport { resolveSelectorConfig, DEFAULT_RESOLVED_CONFIG } from './config/resolve-config';\n\n// ===== Engine factory =====\nexport { createSelectorEngine } from './engine';\nexport type { CreateSelectorEngineOptions } from './engine';\n\n// ===== Top-level selector entry point =====\n// Use this from React contexts / boot-time call sites where the engine may\n// not yet be available. When the engine *is* present, just call\n// `engine.generate(el)` directly — it has the same kill-switch semantics\n// baked in.\nexport { generateSelector } from './generate-selector';\n"]}
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Canonical legacy CSS-path walker.
3
+ *
4
+ * This is the Chromium-DevTools-derived `cssPath` algorithm that was the only
5
+ * selector source autocapture used before the strategy engine existed. It still
6
+ * matters in two situations:
7
+ *
8
+ * 1. The kill switch: when `ResolvedSelectorConfig.enabled === false`, the
9
+ * engine routes here so a customer who flips the engine off mid-session
10
+ * keeps emitting the same selectors their downstream zones and cohorts
11
+ * were built against.
12
+ * 2. The safety net: when the strategy chain or its internal walker throws
13
+ * anything unexpected, the engine catches and falls back here. The
14
+ * autocapture click handler must always produce *some* selector — a
15
+ * runtime exception in selector generation is a worse outcome than a
16
+ * slightly less stable selector.
17
+ *
18
+ * Until this file existed, the algorithm was duplicated in two places kept
19
+ * "in sync by comment":
20
+ *
21
+ * - `packages/plugin-autocapture-browser/src/libs/element-path.ts`
22
+ * - `javascript/packages/session-replay-ui/src/utils/element-path.ts`
23
+ *
24
+ * Both will eventually re-export from here so divergence becomes impossible.
25
+ *
26
+ * Behavior is byte-identical to those two copies — selectors emitted by this
27
+ * function for a given element MUST match what the SDK has been emitting in
28
+ * production. Do not "fix" the selector format without an explicit version
29
+ * bump and a coordinated dashboard rollout.
30
+ *
31
+ * **Why this lives in the package, not as an optional consumer concern:**
32
+ *
33
+ * Every consumer that uses `engine.generate(el)` benefits from the kill
34
+ * switch and the safety net automatically. Without this, each new consumer
35
+ * (Chrome extension visual tagger, future tagging surfaces) has to
36
+ * reimplement the same router and the same legacy walker. We learned that
37
+ * the hard way — by writing the same `if (config.enabled && engine) ...
38
+ * else cssPath()` block in two repositories with two copies of cssPath.
39
+ *
40
+ * Code is adapted from The Chromium Authors.
41
+ * Source: https://github.com/ChromeDevTools/devtools-frontend/blob/main/front_end/panels/elements/DOMPath.ts#L14
42
+ * License: BSD-style license
43
+ *
44
+ * Copyright 2014 The Chromium Authors
45
+ *
46
+ * Redistribution and use in source and binary forms, with or without
47
+ * modification, are permitted provided that the following conditions are
48
+ * met:
49
+ *
50
+ * * Redistributions of source code must retain the above copyright
51
+ * notice, this list of conditions and the following disclaimer.
52
+ * * Redistributions in binary form must reproduce the above
53
+ * copyright notice, this list of conditions and the following
54
+ * disclaimer in the documentation and/or other materials provided
55
+ * with the distribution.
56
+ * * Neither the name of Google Inc. nor the names of its
57
+ * contributors may be used to endorse or promote products derived
58
+ * from this software without specific prior written permission.
59
+ *
60
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
61
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
62
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
63
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
64
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
65
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
66
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
67
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
68
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
69
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
70
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
71
+ */
72
+ /**
73
+ * Produce a CSS selector string for `node` using the legacy positional walker.
74
+ *
75
+ * Returns the empty string for non-element nodes — same shape every existing
76
+ * caller depends on. Never throws for well-formed Element inputs.
77
+ *
78
+ * @param node Element to identify.
79
+ * @param optimized When `true`, short-circuits at the nearest unique-ish step
80
+ * (id or `<body>` / `<head>` / `<html>`). Default `false`,
81
+ * which matches what autocapture has always passed.
82
+ */
83
+ export declare const legacyCssPath: (node: Element, optimized?: boolean) => string;
84
+ //# sourceMappingURL=legacy-css-path.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"legacy-css-path.d.ts","sourceRoot":"","sources":["../../src/legacy-css-path.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsEG;AAgBH;;;;;;;;;;GAUG;AACH,eAAO,MAAM,aAAa,SAAU,OAAO,cAAc,OAAO,KAAG,MAuBlE,CAAC"}