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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +162 -0
  3. package/lib/cjs/config/resolve-config.d.ts +56 -0
  4. package/lib/cjs/config/resolve-config.d.ts.map +1 -0
  5. package/lib/cjs/config/resolve-config.js +114 -0
  6. package/lib/cjs/config/resolve-config.js.map +1 -0
  7. package/lib/cjs/engine.d.ts +54 -0
  8. package/lib/cjs/engine.d.ts.map +1 -0
  9. package/lib/cjs/engine.js +139 -0
  10. package/lib/cjs/engine.js.map +1 -0
  11. package/lib/cjs/fallback-css-path.d.ts +53 -0
  12. package/lib/cjs/fallback-css-path.d.ts.map +1 -0
  13. package/lib/cjs/fallback-css-path.js +124 -0
  14. package/lib/cjs/fallback-css-path.js.map +1 -0
  15. package/lib/cjs/generate-selector.d.ts +54 -0
  16. package/lib/cjs/generate-selector.d.ts.map +1 -0
  17. package/lib/cjs/generate-selector.js +76 -0
  18. package/lib/cjs/generate-selector.js.map +1 -0
  19. package/lib/cjs/helpers/describe-relative.d.ts +28 -0
  20. package/lib/cjs/helpers/describe-relative.d.ts.map +1 -0
  21. package/lib/cjs/helpers/describe-relative.js +60 -0
  22. package/lib/cjs/helpers/describe-relative.js.map +1 -0
  23. package/lib/cjs/helpers/escape-css-identifier.d.ts +8 -0
  24. package/lib/cjs/helpers/escape-css-identifier.d.ts.map +1 -0
  25. package/lib/cjs/helpers/escape-css-identifier.js +50 -0
  26. package/lib/cjs/helpers/escape-css-identifier.js.map +1 -0
  27. package/lib/cjs/helpers/escape-id.d.ts +3 -0
  28. package/lib/cjs/helpers/escape-id.d.ts.map +1 -0
  29. package/lib/cjs/helpers/escape-id.js +10 -0
  30. package/lib/cjs/helpers/escape-id.js.map +1 -0
  31. package/lib/cjs/helpers/get-stable-id.d.ts +23 -0
  32. package/lib/cjs/helpers/get-stable-id.d.ts.map +1 -0
  33. package/lib/cjs/helpers/get-stable-id.js +44 -0
  34. package/lib/cjs/helpers/get-stable-id.js.map +1 -0
  35. package/lib/cjs/index.d.ts +31 -0
  36. package/lib/cjs/index.d.ts.map +1 -0
  37. package/lib/cjs/index.js +71 -0
  38. package/lib/cjs/index.js.map +1 -0
  39. package/lib/cjs/legacy-css-path.d.ts +84 -0
  40. package/lib/cjs/legacy-css-path.d.ts.map +1 -0
  41. package/lib/cjs/legacy-css-path.js +230 -0
  42. package/lib/cjs/legacy-css-path.js.map +1 -0
  43. package/lib/cjs/orchestrator.d.ts +61 -0
  44. package/lib/cjs/orchestrator.d.ts.map +1 -0
  45. package/lib/cjs/orchestrator.js +140 -0
  46. package/lib/cjs/orchestrator.js.map +1 -0
  47. package/lib/cjs/patterns/autogenerated-ids.d.ts +37 -0
  48. package/lib/cjs/patterns/autogenerated-ids.d.ts.map +1 -0
  49. package/lib/cjs/patterns/autogenerated-ids.js +102 -0
  50. package/lib/cjs/patterns/autogenerated-ids.js.map +1 -0
  51. package/lib/cjs/patterns/unstable-classes.d.ts +48 -0
  52. package/lib/cjs/patterns/unstable-classes.d.ts.map +1 -0
  53. package/lib/cjs/patterns/unstable-classes.js +155 -0
  54. package/lib/cjs/patterns/unstable-classes.js.map +1 -0
  55. package/lib/cjs/strategies/explicit-tracking-attribute.d.ts +22 -0
  56. package/lib/cjs/strategies/explicit-tracking-attribute.d.ts.map +1 -0
  57. package/lib/cjs/strategies/explicit-tracking-attribute.js +36 -0
  58. package/lib/cjs/strategies/explicit-tracking-attribute.js.map +1 -0
  59. package/lib/cjs/strategies/stable-id.d.ts +14 -0
  60. package/lib/cjs/strategies/stable-id.d.ts.map +1 -0
  61. package/lib/cjs/strategies/stable-id.js +27 -0
  62. package/lib/cjs/strategies/stable-id.js.map +1 -0
  63. package/lib/cjs/types.d.ts +100 -0
  64. package/lib/cjs/types.d.ts.map +1 -0
  65. package/lib/cjs/types.js +13 -0
  66. package/lib/cjs/types.js.map +1 -0
  67. package/lib/esm/config/resolve-config.d.ts +56 -0
  68. package/lib/esm/config/resolve-config.d.ts.map +1 -0
  69. package/lib/esm/config/resolve-config.js +110 -0
  70. package/lib/esm/config/resolve-config.js.map +1 -0
  71. package/lib/esm/engine.d.ts +54 -0
  72. package/lib/esm/engine.d.ts.map +1 -0
  73. package/lib/esm/engine.js +135 -0
  74. package/lib/esm/engine.js.map +1 -0
  75. package/lib/esm/fallback-css-path.d.ts +53 -0
  76. package/lib/esm/fallback-css-path.d.ts.map +1 -0
  77. package/lib/esm/fallback-css-path.js +120 -0
  78. package/lib/esm/fallback-css-path.js.map +1 -0
  79. package/lib/esm/generate-selector.d.ts +54 -0
  80. package/lib/esm/generate-selector.d.ts.map +1 -0
  81. package/lib/esm/generate-selector.js +72 -0
  82. package/lib/esm/generate-selector.js.map +1 -0
  83. package/lib/esm/helpers/describe-relative.d.ts +28 -0
  84. package/lib/esm/helpers/describe-relative.d.ts.map +1 -0
  85. package/lib/esm/helpers/describe-relative.js +56 -0
  86. package/lib/esm/helpers/describe-relative.js.map +1 -0
  87. package/lib/esm/helpers/escape-css-identifier.d.ts +8 -0
  88. package/lib/esm/helpers/escape-css-identifier.d.ts.map +1 -0
  89. package/lib/esm/helpers/escape-css-identifier.js +46 -0
  90. package/lib/esm/helpers/escape-css-identifier.js.map +1 -0
  91. package/lib/esm/helpers/escape-id.d.ts +3 -0
  92. package/lib/esm/helpers/escape-id.d.ts.map +1 -0
  93. package/lib/esm/helpers/escape-id.js +6 -0
  94. package/lib/esm/helpers/escape-id.js.map +1 -0
  95. package/lib/esm/helpers/get-stable-id.d.ts +23 -0
  96. package/lib/esm/helpers/get-stable-id.d.ts.map +1 -0
  97. package/lib/esm/helpers/get-stable-id.js +40 -0
  98. package/lib/esm/helpers/get-stable-id.js.map +1 -0
  99. package/lib/esm/index.d.ts +31 -0
  100. package/lib/esm/index.d.ts.map +1 -0
  101. package/lib/esm/index.js +50 -0
  102. package/lib/esm/index.js.map +1 -0
  103. package/lib/esm/legacy-css-path.d.ts +84 -0
  104. package/lib/esm/legacy-css-path.d.ts.map +1 -0
  105. package/lib/esm/legacy-css-path.js +226 -0
  106. package/lib/esm/legacy-css-path.js.map +1 -0
  107. package/lib/esm/orchestrator.d.ts +61 -0
  108. package/lib/esm/orchestrator.d.ts.map +1 -0
  109. package/lib/esm/orchestrator.js +136 -0
  110. package/lib/esm/orchestrator.js.map +1 -0
  111. package/lib/esm/patterns/autogenerated-ids.d.ts +37 -0
  112. package/lib/esm/patterns/autogenerated-ids.d.ts.map +1 -0
  113. package/lib/esm/patterns/autogenerated-ids.js +97 -0
  114. package/lib/esm/patterns/autogenerated-ids.js.map +1 -0
  115. package/lib/esm/patterns/unstable-classes.d.ts +48 -0
  116. package/lib/esm/patterns/unstable-classes.d.ts.map +1 -0
  117. package/lib/esm/patterns/unstable-classes.js +150 -0
  118. package/lib/esm/patterns/unstable-classes.js.map +1 -0
  119. package/lib/esm/strategies/explicit-tracking-attribute.d.ts +22 -0
  120. package/lib/esm/strategies/explicit-tracking-attribute.d.ts.map +1 -0
  121. package/lib/esm/strategies/explicit-tracking-attribute.js +33 -0
  122. package/lib/esm/strategies/explicit-tracking-attribute.js.map +1 -0
  123. package/lib/esm/strategies/stable-id.d.ts +14 -0
  124. package/lib/esm/strategies/stable-id.d.ts.map +1 -0
  125. package/lib/esm/strategies/stable-id.js +24 -0
  126. package/lib/esm/strategies/stable-id.js.map +1 -0
  127. package/lib/esm/types.d.ts +100 -0
  128. package/lib/esm/types.d.ts.map +1 -0
  129. package/lib/esm/types.js +12 -0
  130. package/lib/esm/types.js.map +1 -0
  131. package/package.json +40 -5
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ /**
3
+ * @amplitude/element-selector
4
+ *
5
+ * Shared element-selector algorithm consumed by autocapture, the
6
+ * app.amplitude.com tagging UI, and the Chrome extension visual tagger.
7
+ *
8
+ * This file is the package's public API surface. The orchestrator, fallback,
9
+ * config resolver, and engine factory compose on top of the primitives
10
+ * (types, pattern packs, helpers, strategies) to produce the runtime engine
11
+ * consumers actually call.
12
+ *
13
+ * See the design doc:
14
+ * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
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
+ exports.PACKAGE_NAME = '@amplitude/element-selector';
19
+ // ===== Pattern packs =====
20
+ var autogenerated_ids_1 = require("./patterns/autogenerated-ids");
21
+ Object.defineProperty(exports, "DEFAULT_AUTOGENERATED_ID_PATTERNS", { enumerable: true, get: function () { return autogenerated_ids_1.DEFAULT_AUTOGENERATED_ID_PATTERNS; } });
22
+ Object.defineProperty(exports, "compileAutogeneratedIdPatterns", { enumerable: true, get: function () { return autogenerated_ids_1.compile; } });
23
+ Object.defineProperty(exports, "isStableId", { enumerable: true, get: function () { return autogenerated_ids_1.isStableId; } });
24
+ var unstable_classes_1 = require("./patterns/unstable-classes");
25
+ Object.defineProperty(exports, "DEFAULT_UNSTABLE_CLASS_PATTERNS", { enumerable: true, get: function () { return unstable_classes_1.DEFAULT_UNSTABLE_CLASS_PATTERNS; } });
26
+ Object.defineProperty(exports, "compileUnstableClassPatterns", { enumerable: true, get: function () { return unstable_classes_1.compile; } });
27
+ Object.defineProperty(exports, "filterClasses", { enumerable: true, get: function () { return unstable_classes_1.filterClasses; } });
28
+ // ===== Helpers =====
29
+ var get_stable_id_1 = require("./helpers/get-stable-id");
30
+ Object.defineProperty(exports, "getStableId", { enumerable: true, get: function () { return get_stable_id_1.getStableId; } });
31
+ var describe_relative_1 = require("./helpers/describe-relative");
32
+ Object.defineProperty(exports, "describeRelative", { enumerable: true, get: function () { return describe_relative_1.describeRelative; } });
33
+ // ===== Strategies =====
34
+ var explicit_tracking_attribute_1 = require("./strategies/explicit-tracking-attribute");
35
+ Object.defineProperty(exports, "explicitTrackingAttribute", { enumerable: true, get: function () { return explicit_tracking_attribute_1.explicitTrackingAttribute; } });
36
+ var stable_id_1 = require("./strategies/stable-id");
37
+ Object.defineProperty(exports, "stableIdStrategy", { enumerable: true, get: function () { return stable_id_1.stableId; } });
38
+ // ===== Orchestrator + fallback =====
39
+ // Exposed publicly so the dashboard / Chrome extension can call them ad-hoc
40
+ // without instantiating a full engine — useful for preview / debugging flows.
41
+ var orchestrator_1 = require("./orchestrator");
42
+ Object.defineProperty(exports, "runOrchestrator", { enumerable: true, get: function () { return orchestrator_1.runOrchestrator; } });
43
+ Object.defineProperty(exports, "DEFAULT_STRATEGIES", { enumerable: true, get: function () { return orchestrator_1.DEFAULT_STRATEGIES; } });
44
+ var fallback_css_path_1 = require("./fallback-css-path");
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; } });
57
+ // ===== Config resolver =====
58
+ var resolve_config_1 = require("./config/resolve-config");
59
+ Object.defineProperty(exports, "resolveSelectorConfig", { enumerable: true, get: function () { return resolve_config_1.resolveSelectorConfig; } });
60
+ Object.defineProperty(exports, "DEFAULT_RESOLVED_CONFIG", { enumerable: true, get: function () { return resolve_config_1.DEFAULT_RESOLVED_CONFIG; } });
61
+ // ===== Engine factory =====
62
+ var engine_1 = require("./engine");
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; } });
71
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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,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"}
@@ -0,0 +1,230 @@
1
+ "use strict";
2
+ /**
3
+ * Canonical legacy CSS-path walker.
4
+ *
5
+ * This is the Chromium-DevTools-derived `cssPath` algorithm that was the only
6
+ * selector source autocapture used before the strategy engine existed. It still
7
+ * matters in two situations:
8
+ *
9
+ * 1. The kill switch: when `ResolvedSelectorConfig.enabled === false`, the
10
+ * engine routes here so a customer who flips the engine off mid-session
11
+ * keeps emitting the same selectors their downstream zones and cohorts
12
+ * were built against.
13
+ * 2. The safety net: when the strategy chain or its internal walker throws
14
+ * anything unexpected, the engine catches and falls back here. The
15
+ * autocapture click handler must always produce *some* selector — a
16
+ * runtime exception in selector generation is a worse outcome than a
17
+ * slightly less stable selector.
18
+ *
19
+ * Until this file existed, the algorithm was duplicated in two places kept
20
+ * "in sync by comment":
21
+ *
22
+ * - `packages/plugin-autocapture-browser/src/libs/element-path.ts`
23
+ * - `javascript/packages/session-replay-ui/src/utils/element-path.ts`
24
+ *
25
+ * Both will eventually re-export from here so divergence becomes impossible.
26
+ *
27
+ * Behavior is byte-identical to those two copies — selectors emitted by this
28
+ * function for a given element MUST match what the SDK has been emitting in
29
+ * production. Do not "fix" the selector format without an explicit version
30
+ * bump and a coordinated dashboard rollout.
31
+ *
32
+ * **Why this lives in the package, not as an optional consumer concern:**
33
+ *
34
+ * Every consumer that uses `engine.generate(el)` benefits from the kill
35
+ * switch and the safety net automatically. Without this, each new consumer
36
+ * (Chrome extension visual tagger, future tagging surfaces) has to
37
+ * reimplement the same router and the same legacy walker. We learned that
38
+ * the hard way — by writing the same `if (config.enabled && engine) ...
39
+ * else cssPath()` block in two repositories with two copies of cssPath.
40
+ *
41
+ * Code is adapted from The Chromium Authors.
42
+ * Source: https://github.com/ChromeDevTools/devtools-frontend/blob/main/front_end/panels/elements/DOMPath.ts#L14
43
+ * License: BSD-style license
44
+ *
45
+ * Copyright 2014 The Chromium Authors
46
+ *
47
+ * Redistribution and use in source and binary forms, with or without
48
+ * modification, are permitted provided that the following conditions are
49
+ * met:
50
+ *
51
+ * * Redistributions of source code must retain the above copyright
52
+ * notice, this list of conditions and the following disclaimer.
53
+ * * Redistributions in binary form must reproduce the above
54
+ * copyright notice, this list of conditions and the following
55
+ * disclaimer in the documentation and/or other materials provided
56
+ * with the distribution.
57
+ * * Neither the name of Google Inc. nor the names of its
58
+ * contributors may be used to endorse or promote products derived
59
+ * from this software without specific prior written permission.
60
+ *
61
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
62
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
63
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
64
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
65
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
66
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
67
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
68
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
69
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
70
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
71
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
72
+ */
73
+ Object.defineProperty(exports, "__esModule", { value: true });
74
+ exports.legacyCssPath = void 0;
75
+ var tslib_1 = require("tslib");
76
+ /* istanbul ignore file -- the algorithm is locked-down behavior inherited from
77
+ Chromium and validated by the SDK's own end-to-end suite. Re-running line
78
+ coverage here only obscures the parts of the package that *do* have
79
+ meaningful coverage. */
80
+ var escape_css_identifier_1 = require("./helpers/escape-css-identifier");
81
+ var Step = /** @class */ (function () {
82
+ function Step(value, optimized) {
83
+ this.value = value;
84
+ this.optimized = optimized;
85
+ }
86
+ Step.prototype.toString = function () {
87
+ return this.value;
88
+ };
89
+ return Step;
90
+ }());
91
+ /**
92
+ * Produce a CSS selector string for `node` using the legacy positional walker.
93
+ *
94
+ * Returns the empty string for non-element nodes — same shape every existing
95
+ * caller depends on. Never throws for well-formed Element inputs.
96
+ *
97
+ * @param node Element to identify.
98
+ * @param optimized When `true`, short-circuits at the nearest unique-ish step
99
+ * (id or `<body>` / `<head>` / `<html>`). Default `false`,
100
+ * which matches what autocapture has always passed.
101
+ */
102
+ var legacyCssPath = function (node, optimized) {
103
+ // `node` is already an Element; this check is defensive.
104
+ if (node.nodeType !== Node.ELEMENT_NODE) {
105
+ return '';
106
+ }
107
+ var steps = [];
108
+ var contextNode = node;
109
+ while (contextNode) {
110
+ var step = cssPathStep(contextNode, Boolean(optimized), contextNode === node);
111
+ if (!step) {
112
+ break;
113
+ }
114
+ steps.push(step);
115
+ if (step.optimized) {
116
+ break;
117
+ }
118
+ contextNode = contextNode.parentElement;
119
+ }
120
+ steps.reverse();
121
+ return steps.join(' > ');
122
+ };
123
+ exports.legacyCssPath = legacyCssPath;
124
+ var cssPathStep = function (node, optimized, isTargetNode) {
125
+ var e_1, _a;
126
+ if (node.nodeType !== Node.ELEMENT_NODE) {
127
+ return null;
128
+ }
129
+ var id = node.getAttribute('id');
130
+ if (optimized) {
131
+ if (id) {
132
+ return new Step(idSelector(id), true);
133
+ }
134
+ var nodeNameLower = node.tagName.toLowerCase();
135
+ if (nodeNameLower === 'body' || nodeNameLower === 'head' || nodeNameLower === 'html') {
136
+ return new Step(nodeNameLower, true);
137
+ }
138
+ }
139
+ var nodeName = node.tagName.toLowerCase();
140
+ if (id) {
141
+ return new Step(nodeName + idSelector(id), true);
142
+ }
143
+ var parent = node.parentNode;
144
+ if (!parent || parent.nodeType === Node.DOCUMENT_NODE) {
145
+ return new Step(nodeName, true);
146
+ }
147
+ var prefixedOwnClassNamesArray = prefixedElementClassNames(node);
148
+ var needsClassNames = false;
149
+ var needsNthChild = false;
150
+ var ownIndex = -1;
151
+ var elementIndex = -1;
152
+ var siblings = parent.children;
153
+ for (var i = 0; siblings && (ownIndex === -1 || !needsNthChild) && i < siblings.length; ++i) {
154
+ var sibling = siblings[i];
155
+ if (sibling.nodeType !== Node.ELEMENT_NODE) {
156
+ continue;
157
+ }
158
+ elementIndex += 1;
159
+ if (sibling === node) {
160
+ ownIndex = elementIndex;
161
+ continue;
162
+ }
163
+ if (needsNthChild) {
164
+ continue;
165
+ }
166
+ if (sibling.tagName.toLowerCase() !== nodeName) {
167
+ continue;
168
+ }
169
+ needsClassNames = true;
170
+ var ownClassNames = new Set(prefixedOwnClassNamesArray);
171
+ if (!ownClassNames.size) {
172
+ needsNthChild = true;
173
+ continue;
174
+ }
175
+ var siblingClassNamesArray = prefixedElementClassNames(sibling);
176
+ for (var j = 0; j < siblingClassNamesArray.length; ++j) {
177
+ var siblingClass = siblingClassNamesArray[j];
178
+ if (!ownClassNames.has(siblingClass)) {
179
+ continue;
180
+ }
181
+ ownClassNames.delete(siblingClass);
182
+ if (!ownClassNames.size) {
183
+ needsNthChild = true;
184
+ break;
185
+ }
186
+ }
187
+ }
188
+ var result = nodeName;
189
+ if (isTargetNode &&
190
+ nodeName.toLowerCase() === 'input' &&
191
+ node.getAttribute('type') &&
192
+ !node.getAttribute('id') &&
193
+ !node.getAttribute('class')) {
194
+ result += '[type=' + (0, escape_css_identifier_1.escapeCssIdentifier)(node.getAttribute('type') || '') + ']';
195
+ }
196
+ if (needsNthChild) {
197
+ result += ':nth-child(' + String(ownIndex + 1) + ')';
198
+ }
199
+ else if (needsClassNames) {
200
+ try {
201
+ for (var prefixedOwnClassNamesArray_1 = tslib_1.__values(prefixedOwnClassNamesArray), prefixedOwnClassNamesArray_1_1 = prefixedOwnClassNamesArray_1.next(); !prefixedOwnClassNamesArray_1_1.done; prefixedOwnClassNamesArray_1_1 = prefixedOwnClassNamesArray_1.next()) {
202
+ var prefixedName = prefixedOwnClassNamesArray_1_1.value;
203
+ result += '.' + (0, escape_css_identifier_1.escapeCssIdentifier)(prefixedName.slice(1));
204
+ }
205
+ }
206
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
207
+ finally {
208
+ try {
209
+ if (prefixedOwnClassNamesArray_1_1 && !prefixedOwnClassNamesArray_1_1.done && (_a = prefixedOwnClassNamesArray_1.return)) _a.call(prefixedOwnClassNamesArray_1);
210
+ }
211
+ finally { if (e_1) throw e_1.error; }
212
+ }
213
+ }
214
+ return new Step(result, false);
215
+ };
216
+ var prefixedElementClassNames = function (el) {
217
+ var classAttribute = el.getAttribute('class');
218
+ if (!classAttribute) {
219
+ return [];
220
+ }
221
+ return classAttribute
222
+ .split(/\s+/g)
223
+ .filter(Boolean)
224
+ .map(function (name) {
225
+ // The prefix is required to store "__proto__" in a object-based map.
226
+ return '$' + name;
227
+ });
228
+ };
229
+ var idSelector = function (id) { return '#' + (0, escape_css_identifier_1.escapeCssIdentifier)(id); };
230
+ //# sourceMappingURL=legacy-css-path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"legacy-css-path.js","sourceRoot":"","sources":["../../src/legacy-css-path.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsEG;;;;AAEH;;;0BAG0B;AAE1B,yEAAsE;AAEtE;IACE,cAAmB,KAAa,EAAS,SAAkB;QAAxC,UAAK,GAAL,KAAK,CAAQ;QAAS,cAAS,GAAT,SAAS,CAAS;IAAG,CAAC;IAC/D,uBAAQ,GAAR;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IACH,WAAC;AAAD,CAAC,AALD,IAKC;AAED;;;;;;;;;;GAUG;AACI,IAAM,aAAa,GAAG,UAAC,IAAa,EAAE,SAAmB;IAC9D,yDAAyD;IACzD,IAAI,IAAI,CAAC,QAAQ,KAAK,IAAI,CAAC,YAAY,EAAE;QACvC,OAAO,EAAE,CAAC;KACX;IAED,IAAM,KAAK,GAAW,EAAE,CAAC;IACzB,IAAI,WAAW,GAAmB,IAAI,CA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W;IAC5C,IAAM,cAAc,GAAG,EAAE,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IAChD,IAAI,CAAC,cAAc,EAAE;QACnB,OAAO,EAAE,CAAC;KACX;IACD,OAAO,cAAc;SAClB,KAAK,CAAC,MAAM,CAAC;SACb,MAAM,CAAC,OAAO,CAAC;SACf,GAAG,CAAC,UAAC,IAAI;QACR,qEAAqE;QACrE,OAAO,GAAG,GAAG,IAAI,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC,CAAC;AAEF,IAAM,UAAU,GAAG,UAAC,EAAU,IAAa,OAAA,GAAG,GAAG,IAAA,2CAAmB,EAAC,EAAE,CAAC,EAA7B,CAA6B,CAAC","sourcesContent":["/**\n * Canonical legacy CSS-path walker.\n *\n * This is the Chromium-DevTools-derived `cssPath` algorithm that was the only\n * selector source autocapture used before the strategy engine existed. It still\n * matters in two situations:\n *\n * 1. The kill switch: when `ResolvedSelectorConfig.enabled === false`, the\n * engine routes here so a customer who flips the engine off mid-session\n * keeps emitting the same selectors their downstream zones and cohorts\n * were built against.\n * 2. The safety net: when the strategy chain or its internal walker throws\n * anything unexpected, the engine catches and falls back here. The\n * autocapture click handler must always produce *some* selector — a\n * runtime exception in selector generation is a worse outcome than a\n * slightly less stable selector.\n *\n * Until this file existed, the algorithm was duplicated in two places kept\n * \"in sync by comment\":\n *\n * - `packages/plugin-autocapture-browser/src/libs/element-path.ts`\n * - `javascript/packages/session-replay-ui/src/utils/element-path.ts`\n *\n * Both will eventually re-export from here so divergence becomes impossible.\n *\n * Behavior is byte-identical to those two copies — selectors emitted by this\n * function for a given element MUST match what the SDK has been emitting in\n * production. Do not \"fix\" the selector format without an explicit version\n * bump and a coordinated dashboard rollout.\n *\n * **Why this lives in the package, not as an optional consumer concern:**\n *\n * Every consumer that uses `engine.generate(el)` benefits from the kill\n * switch and the safety net automatically. Without this, each new consumer\n * (Chrome extension visual tagger, future tagging surfaces) has to\n * reimplement the same router and the same legacy walker. We learned that\n * the hard way — by writing the same `if (config.enabled && engine) ...\n * else cssPath()` block in two repositories with two copies of cssPath.\n *\n * Code is adapted from The Chromium Authors.\n * Source: https://github.com/ChromeDevTools/devtools-frontend/blob/main/front_end/panels/elements/DOMPath.ts#L14\n * License: BSD-style license\n *\n * Copyright 2014 The Chromium Authors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/* istanbul ignore file -- the algorithm is locked-down behavior inherited from\n Chromium and validated by the SDK's own end-to-end suite. Re-running line\n coverage here only obscures the parts of the package that *do* have\n meaningful coverage. */\n\nimport { escapeCssIdentifier } from './helpers/escape-css-identifier';\n\nclass Step {\n constructor(public value: string, public optimized: boolean) {}\n toString(): string {\n return this.value;\n }\n}\n\n/**\n * Produce a CSS selector string for `node` using the legacy positional walker.\n *\n * Returns the empty string for non-element nodes — same shape every existing\n * caller depends on. Never throws for well-formed Element inputs.\n *\n * @param node Element to identify.\n * @param optimized When `true`, short-circuits at the nearest unique-ish step\n * (id or `<body>` / `<head>` / `<html>`). Default `false`,\n * which matches what autocapture has always passed.\n */\nexport const legacyCssPath = (node: Element, optimized?: boolean): string => {\n // `node` is already an Element; this check is defensive.\n if (node.nodeType !== Node.ELEMENT_NODE) {\n return '';\n }\n\n const steps: Step[] = [];\n let contextNode: Element | null = node;\n\n while (contextNode) {\n const step = cssPathStep(contextNode, Boolean(optimized), contextNode === node);\n if (!step) {\n break;\n }\n steps.push(step);\n if (step.optimized) {\n break;\n }\n contextNode = contextNode.parentElement;\n }\n\n steps.reverse();\n return steps.join(' > ');\n};\n\nconst cssPathStep = (node: Element, optimized: boolean, isTargetNode: boolean): Step | null => {\n if (node.nodeType !== Node.ELEMENT_NODE) {\n return null;\n }\n\n const id = node.getAttribute('id');\n if (optimized) {\n if (id) {\n return new Step(idSelector(id), true);\n }\n\n const nodeNameLower = node.tagName.toLowerCase();\n if (nodeNameLower === 'body' || nodeNameLower === 'head' || nodeNameLower === 'html') {\n return new Step(nodeNameLower, true);\n }\n }\n\n const nodeName = node.tagName.toLowerCase();\n\n if (id) {\n return new Step(nodeName + idSelector(id), true);\n }\n\n const parent = node.parentNode;\n if (!parent || parent.nodeType === Node.DOCUMENT_NODE) {\n return new Step(nodeName, true);\n }\n\n const prefixedOwnClassNamesArray = prefixedElementClassNames(node);\n let needsClassNames = false;\n let needsNthChild = false;\n let ownIndex = -1;\n let elementIndex = -1;\n\n const siblings: HTMLCollectionOf<Element> = (parent as Element | Document).children;\n\n for (let i = 0; siblings && (ownIndex === -1 || !needsNthChild) && i < siblings.length; ++i) {\n const sibling = siblings[i];\n if (sibling.nodeType !== Node.ELEMENT_NODE) {\n continue;\n }\n\n elementIndex += 1;\n if (sibling === node) {\n ownIndex = elementIndex;\n continue;\n }\n if (needsNthChild) {\n continue;\n }\n\n if (sibling.tagName.toLowerCase() !== nodeName) {\n continue;\n }\n\n needsClassNames = true;\n const ownClassNames = new Set<string>(prefixedOwnClassNamesArray);\n if (!ownClassNames.size) {\n needsNthChild = true;\n continue;\n }\n\n const siblingClassNamesArray = prefixedElementClassNames(sibling);\n for (let j = 0; j < siblingClassNamesArray.length; ++j) {\n const siblingClass = siblingClassNamesArray[j];\n if (!ownClassNames.has(siblingClass)) {\n continue;\n }\n ownClassNames.delete(siblingClass);\n if (!ownClassNames.size) {\n needsNthChild = true;\n break;\n }\n }\n }\n\n let result = nodeName;\n if (\n isTargetNode &&\n nodeName.toLowerCase() === 'input' &&\n node.getAttribute('type') &&\n !node.getAttribute('id') &&\n !node.getAttribute('class')\n ) {\n result += '[type=' + escapeCssIdentifier(node.getAttribute('type') || '') + ']';\n }\n if (needsNthChild) {\n result += ':nth-child(' + String(ownIndex + 1) + ')';\n } else if (needsClassNames) {\n for (const prefixedName of prefixedOwnClassNamesArray) {\n result += '.' + escapeCssIdentifier(prefixedName.slice(1));\n }\n }\n\n return new Step(result, false);\n};\n\nconst prefixedElementClassNames = (el: Element): string[] => {\n const classAttribute = el.getAttribute('class');\n if (!classAttribute) {\n return [];\n }\n return classAttribute\n .split(/\\s+/g)\n .filter(Boolean)\n .map((name) => {\n // The prefix is required to store \"__proto__\" in a object-based map.\n return '$' + name;\n });\n};\n\nconst idSelector = (id: string): string => '#' + escapeCssIdentifier(id);\n"]}
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Orchestrator — the entry point for the v1 element-selector algorithm.
3
+ *
4
+ * Given a click target, the orchestrator walks from the target up through its
5
+ * ancestors and tries each registered strategy at each level. The first
6
+ * strategy that returns a non-null candidate (and produces a selector that
7
+ * resolves uniquely under the scope) wins; the trail of intermediate elements
8
+ * between the anchor and the original target is then expressed as a positional
9
+ * descent via `describeRelative`.
10
+ *
11
+ * Two-pass design: every ancestor is tried under the `explicitTrackingAttribute`
12
+ * strategy first, then the entire walk repeats with `stableId`. This ordering
13
+ * means an explicit anchor anywhere up the tree always beats a stable id deeper
14
+ * down — the design doc describes this as the "customer intent overrides
15
+ * structural inference" rule.
16
+ *
17
+ * The orchestrator does not own the fallback. When no strategy + walk produces
18
+ * a unique selector, it returns `null` and the engine wires the
19
+ * `fallback-css-path` path in instead. Keeping the fallback outside the
20
+ * orchestrator keeps the strategy chain testable in isolation.
21
+ *
22
+ * See the design doc:
23
+ * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
24
+ */
25
+ import { ElementSelectorLogger, ResolvedSelectorConfig, Strategy } from './types';
26
+ /**
27
+ * Default strategy chain in priority order. Used by the engine factory when the
28
+ * caller doesn't provide an explicit list. Exported for diagnostics — tests
29
+ * import this so they don't have to duplicate the list.
30
+ */
31
+ export declare const DEFAULT_STRATEGIES: ReadonlyArray<Strategy>;
32
+ export interface OrchestratorOptions {
33
+ /** Strategy chain. Defaults to `DEFAULT_STRATEGIES`. Order = priority. */
34
+ strategies?: ReadonlyArray<Strategy>;
35
+ /** Document or shadow root used for uniqueness checks. Defaults to the target's owner document. */
36
+ scope?: ParentNode;
37
+ /**
38
+ * Optional logger. When provided, the orchestrator emits a `debug` log if a
39
+ * strategy produces a malformed selector that throws during the uniqueness
40
+ * check — useful for diagnosing strategy bugs without crashing the engine.
41
+ */
42
+ logger?: ElementSelectorLogger;
43
+ }
44
+ /**
45
+ * Try to produce a CSS selector for `el` using the strategy chain.
46
+ *
47
+ * Returns the composed selector string on success, or `null` if every strategy
48
+ * declined at every walked ancestor. Callers (the engine) treat `null` as the
49
+ * signal to invoke the fallback walker.
50
+ *
51
+ * Selector format on success:
52
+ *
53
+ * - Anchor only (target itself was an anchor): `<anchor-selector>`
54
+ * - Anchor + trail (anchor was an ancestor): `<anchor-selector> > <descent>`
55
+ *
56
+ * Where `<anchor-selector>` is whatever the winning strategy returned for the
57
+ * anchor element (e.g. `[data-amp-track-id="login-form"]` or `div#hero`), and
58
+ * `<descent>` is `describeRelative(anchor, trail)`.
59
+ */
60
+ export declare function runOrchestrator(el: Element, config: ResolvedSelectorConfig, options?: OrchestratorOptions): string | null;
61
+ //# sourceMappingURL=orchestrator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orchestrator.d.ts","sourceRoot":"","sources":["../../src/orchestrator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,QAAQ,EAAmB,MAAM,SAAS,CAAC;AAKnG;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,EAAE,aAAa,CAAC,QAAQ,CAAiD,CAAC;AAEzG,MAAM,WAAW,mBAAmB;IAClC,0EAA0E;IAC1E,UAAU,CAAC,EAAE,aAAa,CAAC,QAAQ,CAAC,CAAC;IACrC,mGAAmG;IACnG,KAAK,CAAC,EAAE,UAAU,CAAC;IACnB;;;;OAIG;IACH,MAAM,CAAC,EAAE,qBAAqB,CAAC;CAChC;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,eAAe,CAC7B,EAAE,EAAE,OAAO,EACX,MAAM,EAAE,sBAAsB,EAC9B,OAAO,GAAE,mBAAwB,GAChC,MAAM,GAAG,IAAI,CAoCf"}
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ /**
3
+ * Orchestrator — the entry point for the v1 element-selector algorithm.
4
+ *
5
+ * Given a click target, the orchestrator walks from the target up through its
6
+ * ancestors and tries each registered strategy at each level. The first
7
+ * strategy that returns a non-null candidate (and produces a selector that
8
+ * resolves uniquely under the scope) wins; the trail of intermediate elements
9
+ * between the anchor and the original target is then expressed as a positional
10
+ * descent via `describeRelative`.
11
+ *
12
+ * Two-pass design: every ancestor is tried under the `explicitTrackingAttribute`
13
+ * strategy first, then the entire walk repeats with `stableId`. This ordering
14
+ * means an explicit anchor anywhere up the tree always beats a stable id deeper
15
+ * down — the design doc describes this as the "customer intent overrides
16
+ * structural inference" rule.
17
+ *
18
+ * The orchestrator does not own the fallback. When no strategy + walk produces
19
+ * a unique selector, it returns `null` and the engine wires the
20
+ * `fallback-css-path` path in instead. Keeping the fallback outside the
21
+ * orchestrator keeps the strategy chain testable in isolation.
22
+ *
23
+ * See the design doc:
24
+ * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
25
+ */
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.runOrchestrator = exports.DEFAULT_STRATEGIES = void 0;
28
+ var tslib_1 = require("tslib");
29
+ var explicit_tracking_attribute_1 = require("./strategies/explicit-tracking-attribute");
30
+ var stable_id_1 = require("./strategies/stable-id");
31
+ var describe_relative_1 = require("./helpers/describe-relative");
32
+ /**
33
+ * Default strategy chain in priority order. Used by the engine factory when the
34
+ * caller doesn't provide an explicit list. Exported for diagnostics — tests
35
+ * import this so they don't have to duplicate the list.
36
+ */
37
+ exports.DEFAULT_STRATEGIES = [explicit_tracking_attribute_1.explicitTrackingAttribute, stable_id_1.stableId];
38
+ /**
39
+ * Try to produce a CSS selector for `el` using the strategy chain.
40
+ *
41
+ * Returns the composed selector string on success, or `null` if every strategy
42
+ * declined at every walked ancestor. Callers (the engine) treat `null` as the
43
+ * signal to invoke the fallback walker.
44
+ *
45
+ * Selector format on success:
46
+ *
47
+ * - Anchor only (target itself was an anchor): `<anchor-selector>`
48
+ * - Anchor + trail (anchor was an ancestor): `<anchor-selector> > <descent>`
49
+ *
50
+ * Where `<anchor-selector>` is whatever the winning strategy returned for the
51
+ * anchor element (e.g. `[data-amp-track-id="login-form"]` or `div#hero`), and
52
+ * `<descent>` is `describeRelative(anchor, trail)`.
53
+ */
54
+ function runOrchestrator(el, config, options) {
55
+ var e_1, _a;
56
+ var _b, _c, _d;
57
+ if (options === void 0) { options = {}; }
58
+ var strategies = (_b = options.strategies) !== null && _b !== void 0 ? _b : exports.DEFAULT_STRATEGIES;
59
+ var scope = (_d = (_c = options.scope) !== null && _c !== void 0 ? _c : el.ownerDocument) !== null && _d !== void 0 ? _d : document;
60
+ var ctx = { scope: scope, config: config };
61
+ var walk = collectWalk(el, config.maxAncestorWalkDepth);
62
+ try {
63
+ // Two-pass: try strategy[0] across the whole walk, then strategy[1], etc.
64
+ // This gives an "explicit anchor at any depth beats a structural anchor any
65
+ // depth" priority, which matches the design doc's "customer intent overrides
66
+ // structural inference" rule.
67
+ for (var strategies_1 = tslib_1.__values(strategies), strategies_1_1 = strategies_1.next(); !strategies_1_1.done; strategies_1_1 = strategies_1.next()) {
68
+ var strategy = strategies_1_1.value;
69
+ for (var i = 0; i < walk.length; i++) {
70
+ var anchor = walk[i];
71
+ var anchorSelector = strategy.try(anchor, ctx);
72
+ if (anchorSelector === null)
73
+ continue;
74
+ // Anchor was the target itself — no descent needed.
75
+ if (i === 0) {
76
+ if (isUniqueMatch(scope, anchorSelector, el, strategy.name, options.logger)) {
77
+ return anchorSelector;
78
+ }
79
+ continue;
80
+ }
81
+ // Anchor was an ancestor — descend back to the target through the trail.
82
+ var trail = walk.slice(0, i).reverse();
83
+ var descent = (0, describe_relative_1.describeRelative)(anchor, trail);
84
+ var composed = "".concat(anchorSelector, " > ").concat(descent);
85
+ if (isUniqueMatch(scope, composed, el, strategy.name, options.logger)) {
86
+ return composed;
87
+ }
88
+ }
89
+ }
90
+ }
91
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
92
+ finally {
93
+ try {
94
+ if (strategies_1_1 && !strategies_1_1.done && (_a = strategies_1.return)) _a.call(strategies_1);
95
+ }
96
+ finally { if (e_1) throw e_1.error; }
97
+ }
98
+ return null;
99
+ }
100
+ exports.runOrchestrator = runOrchestrator;
101
+ /**
102
+ * Build the walk array `[target, parent, grandparent, ...]`, stopping at
103
+ * `<html>` (or at the depth limit if configured). Excludes the document
104
+ * element's parent (which is the Document node and not an Element).
105
+ */
106
+ function collectWalk(el, maxDepth) {
107
+ var walk = [];
108
+ var cursor = el;
109
+ while (cursor !== null) {
110
+ walk.push(cursor);
111
+ if (maxDepth !== undefined && walk.length > maxDepth)
112
+ break;
113
+ cursor = cursor.parentElement;
114
+ }
115
+ return walk;
116
+ }
117
+ /**
118
+ * Check whether `selector` resolves to exactly `el` and no other element in
119
+ * `scope`. The strategies themselves don't run uniqueness checks — that's the
120
+ * orchestrator's job, so strategies stay pure transforms and stay testable in
121
+ * isolation.
122
+ *
123
+ * When the selector is malformed (which is a strategy bug rather than user
124
+ * input), we log at `debug` and return false rather than throwing. The log
125
+ * lets engineers diagnose a misbehaving strategy without the engine taking
126
+ * down whatever it's wired into.
127
+ */
128
+ function isUniqueMatch(scope, selector, el, strategyName, logger) {
129
+ var matches;
130
+ try {
131
+ matches = scope.querySelectorAll(selector);
132
+ }
133
+ catch (e) {
134
+ var message = e instanceof Error ? e.message : String(e);
135
+ logger === null || logger === void 0 ? void 0 : logger.debug("@amplitude/element-selector: strategy \"".concat(strategyName, "\" emitted a malformed selector \"").concat(selector, "\" (").concat(message, ")"));
136
+ return false;
137
+ }
138
+ return matches.length === 1 && matches[0] === el;
139
+ }
140
+ //# sourceMappingURL=orchestrator.js.map