@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.
- package/LICENSE +21 -0
- package/README.md +162 -0
- package/lib/cjs/config/resolve-config.d.ts +56 -0
- package/lib/cjs/config/resolve-config.d.ts.map +1 -0
- package/lib/cjs/config/resolve-config.js +114 -0
- package/lib/cjs/config/resolve-config.js.map +1 -0
- package/lib/cjs/engine.d.ts +54 -0
- package/lib/cjs/engine.d.ts.map +1 -0
- package/lib/cjs/engine.js +139 -0
- package/lib/cjs/engine.js.map +1 -0
- package/lib/cjs/fallback-css-path.d.ts +53 -0
- package/lib/cjs/fallback-css-path.d.ts.map +1 -0
- package/lib/cjs/fallback-css-path.js +124 -0
- package/lib/cjs/fallback-css-path.js.map +1 -0
- package/lib/cjs/generate-selector.d.ts +54 -0
- package/lib/cjs/generate-selector.d.ts.map +1 -0
- package/lib/cjs/generate-selector.js +76 -0
- package/lib/cjs/generate-selector.js.map +1 -0
- package/lib/cjs/helpers/describe-relative.d.ts +28 -0
- package/lib/cjs/helpers/describe-relative.d.ts.map +1 -0
- package/lib/cjs/helpers/describe-relative.js +60 -0
- package/lib/cjs/helpers/describe-relative.js.map +1 -0
- package/lib/cjs/helpers/escape-css-identifier.d.ts +8 -0
- package/lib/cjs/helpers/escape-css-identifier.d.ts.map +1 -0
- package/lib/cjs/helpers/escape-css-identifier.js +50 -0
- package/lib/cjs/helpers/escape-css-identifier.js.map +1 -0
- package/lib/cjs/helpers/escape-id.d.ts +3 -0
- package/lib/cjs/helpers/escape-id.d.ts.map +1 -0
- package/lib/cjs/helpers/escape-id.js +10 -0
- package/lib/cjs/helpers/escape-id.js.map +1 -0
- package/lib/cjs/helpers/get-stable-id.d.ts +23 -0
- package/lib/cjs/helpers/get-stable-id.d.ts.map +1 -0
- package/lib/cjs/helpers/get-stable-id.js +44 -0
- package/lib/cjs/helpers/get-stable-id.js.map +1 -0
- package/lib/cjs/index.d.ts +31 -0
- package/lib/cjs/index.d.ts.map +1 -0
- package/lib/cjs/index.js +71 -0
- package/lib/cjs/index.js.map +1 -0
- package/lib/cjs/legacy-css-path.d.ts +84 -0
- package/lib/cjs/legacy-css-path.d.ts.map +1 -0
- package/lib/cjs/legacy-css-path.js +230 -0
- package/lib/cjs/legacy-css-path.js.map +1 -0
- package/lib/cjs/orchestrator.d.ts +61 -0
- package/lib/cjs/orchestrator.d.ts.map +1 -0
- package/lib/cjs/orchestrator.js +140 -0
- package/lib/cjs/orchestrator.js.map +1 -0
- package/lib/cjs/patterns/autogenerated-ids.d.ts +37 -0
- package/lib/cjs/patterns/autogenerated-ids.d.ts.map +1 -0
- package/lib/cjs/patterns/autogenerated-ids.js +102 -0
- package/lib/cjs/patterns/autogenerated-ids.js.map +1 -0
- package/lib/cjs/patterns/unstable-classes.d.ts +48 -0
- package/lib/cjs/patterns/unstable-classes.d.ts.map +1 -0
- package/lib/cjs/patterns/unstable-classes.js +155 -0
- package/lib/cjs/patterns/unstable-classes.js.map +1 -0
- package/lib/cjs/strategies/explicit-tracking-attribute.d.ts +22 -0
- package/lib/cjs/strategies/explicit-tracking-attribute.d.ts.map +1 -0
- package/lib/cjs/strategies/explicit-tracking-attribute.js +36 -0
- package/lib/cjs/strategies/explicit-tracking-attribute.js.map +1 -0
- package/lib/cjs/strategies/stable-id.d.ts +14 -0
- package/lib/cjs/strategies/stable-id.d.ts.map +1 -0
- package/lib/cjs/strategies/stable-id.js +27 -0
- package/lib/cjs/strategies/stable-id.js.map +1 -0
- package/lib/cjs/types.d.ts +100 -0
- package/lib/cjs/types.d.ts.map +1 -0
- package/lib/cjs/types.js +13 -0
- package/lib/cjs/types.js.map +1 -0
- package/lib/esm/config/resolve-config.d.ts +56 -0
- package/lib/esm/config/resolve-config.d.ts.map +1 -0
- package/lib/esm/config/resolve-config.js +110 -0
- package/lib/esm/config/resolve-config.js.map +1 -0
- package/lib/esm/engine.d.ts +54 -0
- package/lib/esm/engine.d.ts.map +1 -0
- package/lib/esm/engine.js +135 -0
- package/lib/esm/engine.js.map +1 -0
- package/lib/esm/fallback-css-path.d.ts +53 -0
- package/lib/esm/fallback-css-path.d.ts.map +1 -0
- package/lib/esm/fallback-css-path.js +120 -0
- package/lib/esm/fallback-css-path.js.map +1 -0
- package/lib/esm/generate-selector.d.ts +54 -0
- package/lib/esm/generate-selector.d.ts.map +1 -0
- package/lib/esm/generate-selector.js +72 -0
- package/lib/esm/generate-selector.js.map +1 -0
- package/lib/esm/helpers/describe-relative.d.ts +28 -0
- package/lib/esm/helpers/describe-relative.d.ts.map +1 -0
- package/lib/esm/helpers/describe-relative.js +56 -0
- package/lib/esm/helpers/describe-relative.js.map +1 -0
- package/lib/esm/helpers/escape-css-identifier.d.ts +8 -0
- package/lib/esm/helpers/escape-css-identifier.d.ts.map +1 -0
- package/lib/esm/helpers/escape-css-identifier.js +46 -0
- package/lib/esm/helpers/escape-css-identifier.js.map +1 -0
- package/lib/esm/helpers/escape-id.d.ts +3 -0
- package/lib/esm/helpers/escape-id.d.ts.map +1 -0
- package/lib/esm/helpers/escape-id.js +6 -0
- package/lib/esm/helpers/escape-id.js.map +1 -0
- package/lib/esm/helpers/get-stable-id.d.ts +23 -0
- package/lib/esm/helpers/get-stable-id.d.ts.map +1 -0
- package/lib/esm/helpers/get-stable-id.js +40 -0
- package/lib/esm/helpers/get-stable-id.js.map +1 -0
- package/lib/esm/index.d.ts +31 -0
- package/lib/esm/index.d.ts.map +1 -0
- package/lib/esm/index.js +50 -0
- package/lib/esm/index.js.map +1 -0
- package/lib/esm/legacy-css-path.d.ts +84 -0
- package/lib/esm/legacy-css-path.d.ts.map +1 -0
- package/lib/esm/legacy-css-path.js +226 -0
- package/lib/esm/legacy-css-path.js.map +1 -0
- package/lib/esm/orchestrator.d.ts +61 -0
- package/lib/esm/orchestrator.d.ts.map +1 -0
- package/lib/esm/orchestrator.js +136 -0
- package/lib/esm/orchestrator.js.map +1 -0
- package/lib/esm/patterns/autogenerated-ids.d.ts +37 -0
- package/lib/esm/patterns/autogenerated-ids.d.ts.map +1 -0
- package/lib/esm/patterns/autogenerated-ids.js +97 -0
- package/lib/esm/patterns/autogenerated-ids.js.map +1 -0
- package/lib/esm/patterns/unstable-classes.d.ts +48 -0
- package/lib/esm/patterns/unstable-classes.d.ts.map +1 -0
- package/lib/esm/patterns/unstable-classes.js +150 -0
- package/lib/esm/patterns/unstable-classes.js.map +1 -0
- package/lib/esm/strategies/explicit-tracking-attribute.d.ts +22 -0
- package/lib/esm/strategies/explicit-tracking-attribute.d.ts.map +1 -0
- package/lib/esm/strategies/explicit-tracking-attribute.js +33 -0
- package/lib/esm/strategies/explicit-tracking-attribute.js.map +1 -0
- package/lib/esm/strategies/stable-id.d.ts +14 -0
- package/lib/esm/strategies/stable-id.d.ts.map +1 -0
- package/lib/esm/strategies/stable-id.js +24 -0
- package/lib/esm/strategies/stable-id.js.map +1 -0
- package/lib/esm/types.d.ts +100 -0
- package/lib/esm/types.d.ts.map +1 -0
- package/lib/esm/types.js +12 -0
- package/lib/esm/types.js.map +1 -0
- package/package.json +40 -5
|
@@ -0,0 +1,226 @@
|
|
|
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
|
+
import { __values } from "tslib";
|
|
73
|
+
/* istanbul ignore file -- the algorithm is locked-down behavior inherited from
|
|
74
|
+
Chromium and validated by the SDK's own end-to-end suite. Re-running line
|
|
75
|
+
coverage here only obscures the parts of the package that *do* have
|
|
76
|
+
meaningful coverage. */
|
|
77
|
+
import { escapeCssIdentifier } from './helpers/escape-css-identifier';
|
|
78
|
+
var Step = /** @class */ (function () {
|
|
79
|
+
function Step(value, optimized) {
|
|
80
|
+
this.value = value;
|
|
81
|
+
this.optimized = optimized;
|
|
82
|
+
}
|
|
83
|
+
Step.prototype.toString = function () {
|
|
84
|
+
return this.value;
|
|
85
|
+
};
|
|
86
|
+
return Step;
|
|
87
|
+
}());
|
|
88
|
+
/**
|
|
89
|
+
* Produce a CSS selector string for `node` using the legacy positional walker.
|
|
90
|
+
*
|
|
91
|
+
* Returns the empty string for non-element nodes — same shape every existing
|
|
92
|
+
* caller depends on. Never throws for well-formed Element inputs.
|
|
93
|
+
*
|
|
94
|
+
* @param node Element to identify.
|
|
95
|
+
* @param optimized When `true`, short-circuits at the nearest unique-ish step
|
|
96
|
+
* (id or `<body>` / `<head>` / `<html>`). Default `false`,
|
|
97
|
+
* which matches what autocapture has always passed.
|
|
98
|
+
*/
|
|
99
|
+
export var legacyCssPath = function (node, optimized) {
|
|
100
|
+
// `node` is already an Element; this check is defensive.
|
|
101
|
+
if (node.nodeType !== Node.ELEMENT_NODE) {
|
|
102
|
+
return '';
|
|
103
|
+
}
|
|
104
|
+
var steps = [];
|
|
105
|
+
var contextNode = node;
|
|
106
|
+
while (contextNode) {
|
|
107
|
+
var step = cssPathStep(contextNode, Boolean(optimized), contextNode === node);
|
|
108
|
+
if (!step) {
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
steps.push(step);
|
|
112
|
+
if (step.optimized) {
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
contextNode = contextNode.parentElement;
|
|
116
|
+
}
|
|
117
|
+
steps.reverse();
|
|
118
|
+
return steps.join(' > ');
|
|
119
|
+
};
|
|
120
|
+
var cssPathStep = function (node, optimized, isTargetNode) {
|
|
121
|
+
var e_1, _a;
|
|
122
|
+
if (node.nodeType !== Node.ELEMENT_NODE) {
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
var id = node.getAttribute('id');
|
|
126
|
+
if (optimized) {
|
|
127
|
+
if (id) {
|
|
128
|
+
return new Step(idSelector(id), true);
|
|
129
|
+
}
|
|
130
|
+
var nodeNameLower = node.tagName.toLowerCase();
|
|
131
|
+
if (nodeNameLower === 'body' || nodeNameLower === 'head' || nodeNameLower === 'html') {
|
|
132
|
+
return new Step(nodeNameLower, true);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
var nodeName = node.tagName.toLowerCase();
|
|
136
|
+
if (id) {
|
|
137
|
+
return new Step(nodeName + idSelector(id), true);
|
|
138
|
+
}
|
|
139
|
+
var parent = node.parentNode;
|
|
140
|
+
if (!parent || parent.nodeType === Node.DOCUMENT_NODE) {
|
|
141
|
+
return new Step(nodeName, true);
|
|
142
|
+
}
|
|
143
|
+
var prefixedOwnClassNamesArray = prefixedElementClassNames(node);
|
|
144
|
+
var needsClassNames = false;
|
|
145
|
+
var needsNthChild = false;
|
|
146
|
+
var ownIndex = -1;
|
|
147
|
+
var elementIndex = -1;
|
|
148
|
+
var siblings = parent.children;
|
|
149
|
+
for (var i = 0; siblings && (ownIndex === -1 || !needsNthChild) && i < siblings.length; ++i) {
|
|
150
|
+
var sibling = siblings[i];
|
|
151
|
+
if (sibling.nodeType !== Node.ELEMENT_NODE) {
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
elementIndex += 1;
|
|
155
|
+
if (sibling === node) {
|
|
156
|
+
ownIndex = elementIndex;
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (needsNthChild) {
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
if (sibling.tagName.toLowerCase() !== nodeName) {
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
needsClassNames = true;
|
|
166
|
+
var ownClassNames = new Set(prefixedOwnClassNamesArray);
|
|
167
|
+
if (!ownClassNames.size) {
|
|
168
|
+
needsNthChild = true;
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
var siblingClassNamesArray = prefixedElementClassNames(sibling);
|
|
172
|
+
for (var j = 0; j < siblingClassNamesArray.length; ++j) {
|
|
173
|
+
var siblingClass = siblingClassNamesArray[j];
|
|
174
|
+
if (!ownClassNames.has(siblingClass)) {
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
ownClassNames.delete(siblingClass);
|
|
178
|
+
if (!ownClassNames.size) {
|
|
179
|
+
needsNthChild = true;
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
var result = nodeName;
|
|
185
|
+
if (isTargetNode &&
|
|
186
|
+
nodeName.toLowerCase() === 'input' &&
|
|
187
|
+
node.getAttribute('type') &&
|
|
188
|
+
!node.getAttribute('id') &&
|
|
189
|
+
!node.getAttribute('class')) {
|
|
190
|
+
result += '[type=' + escapeCssIdentifier(node.getAttribute('type') || '') + ']';
|
|
191
|
+
}
|
|
192
|
+
if (needsNthChild) {
|
|
193
|
+
result += ':nth-child(' + String(ownIndex + 1) + ')';
|
|
194
|
+
}
|
|
195
|
+
else if (needsClassNames) {
|
|
196
|
+
try {
|
|
197
|
+
for (var prefixedOwnClassNamesArray_1 = __values(prefixedOwnClassNamesArray), prefixedOwnClassNamesArray_1_1 = prefixedOwnClassNamesArray_1.next(); !prefixedOwnClassNamesArray_1_1.done; prefixedOwnClassNamesArray_1_1 = prefixedOwnClassNamesArray_1.next()) {
|
|
198
|
+
var prefixedName = prefixedOwnClassNamesArray_1_1.value;
|
|
199
|
+
result += '.' + escapeCssIdentifier(prefixedName.slice(1));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
203
|
+
finally {
|
|
204
|
+
try {
|
|
205
|
+
if (prefixedOwnClassNamesArray_1_1 && !prefixedOwnClassNamesArray_1_1.done && (_a = prefixedOwnClassNamesArray_1.return)) _a.call(prefixedOwnClassNamesArray_1);
|
|
206
|
+
}
|
|
207
|
+
finally { if (e_1) throw e_1.error; }
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return new Step(result, false);
|
|
211
|
+
};
|
|
212
|
+
var prefixedElementClassNames = function (el) {
|
|
213
|
+
var classAttribute = el.getAttribute('class');
|
|
214
|
+
if (!classAttribute) {
|
|
215
|
+
return [];
|
|
216
|
+
}
|
|
217
|
+
return classAttribute
|
|
218
|
+
.split(/\s+/g)
|
|
219
|
+
.filter(Boolean)
|
|
220
|
+
.map(function (name) {
|
|
221
|
+
// The prefix is required to store "__proto__" in a object-based map.
|
|
222
|
+
return '$' + name;
|
|
223
|
+
});
|
|
224
|
+
};
|
|
225
|
+
var idSelector = function (id) { return '#' + escapeCssIdentifier(id); };
|
|
226
|
+
//# 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,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;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;AACH,MAAM,CAAC,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,CAAC;IAEvC,OAAO,WAAW,EAAE;QAClB,IAAM,IAAI,GAAG,WAAW,CAAC,WAAW,EAAE,OAAO,CAAC,SAAS,CAAC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Ac;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,mBAAmB,CAAC,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,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Orchestrator — the entry point for the v1 element-selector algorithm.
|
|
3
|
+
*
|
|
4
|
+
* Given a click target, the orchestrator walks from the target up through its
|
|
5
|
+
* ancestors and tries each registered strategy at each level. The first
|
|
6
|
+
* strategy that returns a non-null candidate (and produces a selector that
|
|
7
|
+
* resolves uniquely under the scope) wins; the trail of intermediate elements
|
|
8
|
+
* between the anchor and the original target is then expressed as a positional
|
|
9
|
+
* descent via `describeRelative`.
|
|
10
|
+
*
|
|
11
|
+
* Two-pass design: every ancestor is tried under the `explicitTrackingAttribute`
|
|
12
|
+
* strategy first, then the entire walk repeats with `stableId`. This ordering
|
|
13
|
+
* means an explicit anchor anywhere up the tree always beats a stable id deeper
|
|
14
|
+
* down — the design doc describes this as the "customer intent overrides
|
|
15
|
+
* structural inference" rule.
|
|
16
|
+
*
|
|
17
|
+
* The orchestrator does not own the fallback. When no strategy + walk produces
|
|
18
|
+
* a unique selector, it returns `null` and the engine wires the
|
|
19
|
+
* `fallback-css-path` path in instead. Keeping the fallback outside the
|
|
20
|
+
* orchestrator keeps the strategy chain testable in isolation.
|
|
21
|
+
*
|
|
22
|
+
* See the design doc:
|
|
23
|
+
* packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
|
|
24
|
+
*/
|
|
25
|
+
import { __values } from "tslib";
|
|
26
|
+
import { explicitTrackingAttribute } from './strategies/explicit-tracking-attribute';
|
|
27
|
+
import { stableId as stableIdStrategy } from './strategies/stable-id';
|
|
28
|
+
import { describeRelative } from './helpers/describe-relative';
|
|
29
|
+
/**
|
|
30
|
+
* Default strategy chain in priority order. Used by the engine factory when the
|
|
31
|
+
* caller doesn't provide an explicit list. Exported for diagnostics — tests
|
|
32
|
+
* import this so they don't have to duplicate the list.
|
|
33
|
+
*/
|
|
34
|
+
export var DEFAULT_STRATEGIES = [explicitTrackingAttribute, stableIdStrategy];
|
|
35
|
+
/**
|
|
36
|
+
* Try to produce a CSS selector for `el` using the strategy chain.
|
|
37
|
+
*
|
|
38
|
+
* Returns the composed selector string on success, or `null` if every strategy
|
|
39
|
+
* declined at every walked ancestor. Callers (the engine) treat `null` as the
|
|
40
|
+
* signal to invoke the fallback walker.
|
|
41
|
+
*
|
|
42
|
+
* Selector format on success:
|
|
43
|
+
*
|
|
44
|
+
* - Anchor only (target itself was an anchor): `<anchor-selector>`
|
|
45
|
+
* - Anchor + trail (anchor was an ancestor): `<anchor-selector> > <descent>`
|
|
46
|
+
*
|
|
47
|
+
* Where `<anchor-selector>` is whatever the winning strategy returned for the
|
|
48
|
+
* anchor element (e.g. `[data-amp-track-id="login-form"]` or `div#hero`), and
|
|
49
|
+
* `<descent>` is `describeRelative(anchor, trail)`.
|
|
50
|
+
*/
|
|
51
|
+
export function runOrchestrator(el, config, options) {
|
|
52
|
+
var e_1, _a;
|
|
53
|
+
var _b, _c, _d;
|
|
54
|
+
if (options === void 0) { options = {}; }
|
|
55
|
+
var strategies = (_b = options.strategies) !== null && _b !== void 0 ? _b : DEFAULT_STRATEGIES;
|
|
56
|
+
var scope = (_d = (_c = options.scope) !== null && _c !== void 0 ? _c : el.ownerDocument) !== null && _d !== void 0 ? _d : document;
|
|
57
|
+
var ctx = { scope: scope, config: config };
|
|
58
|
+
var walk = collectWalk(el, config.maxAncestorWalkDepth);
|
|
59
|
+
try {
|
|
60
|
+
// Two-pass: try strategy[0] across the whole walk, then strategy[1], etc.
|
|
61
|
+
// This gives an "explicit anchor at any depth beats a structural anchor any
|
|
62
|
+
// depth" priority, which matches the design doc's "customer intent overrides
|
|
63
|
+
// structural inference" rule.
|
|
64
|
+
for (var strategies_1 = __values(strategies), strategies_1_1 = strategies_1.next(); !strategies_1_1.done; strategies_1_1 = strategies_1.next()) {
|
|
65
|
+
var strategy = strategies_1_1.value;
|
|
66
|
+
for (var i = 0; i < walk.length; i++) {
|
|
67
|
+
var anchor = walk[i];
|
|
68
|
+
var anchorSelector = strategy.try(anchor, ctx);
|
|
69
|
+
if (anchorSelector === null)
|
|
70
|
+
continue;
|
|
71
|
+
// Anchor was the target itself — no descent needed.
|
|
72
|
+
if (i === 0) {
|
|
73
|
+
if (isUniqueMatch(scope, anchorSelector, el, strategy.name, options.logger)) {
|
|
74
|
+
return anchorSelector;
|
|
75
|
+
}
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
// Anchor was an ancestor — descend back to the target through the trail.
|
|
79
|
+
var trail = walk.slice(0, i).reverse();
|
|
80
|
+
var descent = describeRelative(anchor, trail);
|
|
81
|
+
var composed = "".concat(anchorSelector, " > ").concat(descent);
|
|
82
|
+
if (isUniqueMatch(scope, composed, el, strategy.name, options.logger)) {
|
|
83
|
+
return composed;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
89
|
+
finally {
|
|
90
|
+
try {
|
|
91
|
+
if (strategies_1_1 && !strategies_1_1.done && (_a = strategies_1.return)) _a.call(strategies_1);
|
|
92
|
+
}
|
|
93
|
+
finally { if (e_1) throw e_1.error; }
|
|
94
|
+
}
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Build the walk array `[target, parent, grandparent, ...]`, stopping at
|
|
99
|
+
* `<html>` (or at the depth limit if configured). Excludes the document
|
|
100
|
+
* element's parent (which is the Document node and not an Element).
|
|
101
|
+
*/
|
|
102
|
+
function collectWalk(el, maxDepth) {
|
|
103
|
+
var walk = [];
|
|
104
|
+
var cursor = el;
|
|
105
|
+
while (cursor !== null) {
|
|
106
|
+
walk.push(cursor);
|
|
107
|
+
if (maxDepth !== undefined && walk.length > maxDepth)
|
|
108
|
+
break;
|
|
109
|
+
cursor = cursor.parentElement;
|
|
110
|
+
}
|
|
111
|
+
return walk;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Check whether `selector` resolves to exactly `el` and no other element in
|
|
115
|
+
* `scope`. The strategies themselves don't run uniqueness checks — that's the
|
|
116
|
+
* orchestrator's job, so strategies stay pure transforms and stay testable in
|
|
117
|
+
* isolation.
|
|
118
|
+
*
|
|
119
|
+
* When the selector is malformed (which is a strategy bug rather than user
|
|
120
|
+
* input), we log at `debug` and return false rather than throwing. The log
|
|
121
|
+
* lets engineers diagnose a misbehaving strategy without the engine taking
|
|
122
|
+
* down whatever it's wired into.
|
|
123
|
+
*/
|
|
124
|
+
function isUniqueMatch(scope, selector, el, strategyName, logger) {
|
|
125
|
+
var matches;
|
|
126
|
+
try {
|
|
127
|
+
matches = scope.querySelectorAll(selector);
|
|
128
|
+
}
|
|
129
|
+
catch (e) {
|
|
130
|
+
var message = e instanceof Error ? e.message : String(e);
|
|
131
|
+
logger === null || logger === void 0 ? void 0 : logger.debug("@amplitude/element-selector: strategy \"".concat(strategyName, "\" emitted a malformed selector \"").concat(selector, "\" (").concat(message, ")"));
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
return matches.length === 1 && matches[0] === el;
|
|
135
|
+
}
|
|
136
|
+
//# sourceMappingURL=orchestrator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orchestrator.js","sourceRoot":"","sources":["../../src/orchestrator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;;AAGH,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AACrF,OAAO,EAAE,QAAQ,IAAI,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAE/D;;;;GAIG;AACH,MAAM,CAAC,IAAM,kBAAkB,GAA4B,CAAC,yBAAyB,EAAE,gBAAgB,CAAC,CAAC;AAezG;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,eAAe,CAC7B,EAAW,EACX,MAA8B,EAC9B,OAAiC;;;IAAjC,wBAAA,EAAA,YAAiC;IAEjC,IAAM,UAAU,G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EAAE,QAAQ,EAAE,EAAE,EAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE;oBACrE,OAAO,QAAQ,CAAC;iBACjB;aACF;SACF;;;;;;;;;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;GAIG;AACH,SAAS,WAAW,CAAC,EAAW,EAAE,QAA4B;IAC5D,IAAM,IAAI,GAAc,EAAE,CAAC;IAC3B,IAAI,MAAM,GAAmB,EAAE,CAAC;IAChC,OAAO,MAAM,KAAK,IAAI,EAAE;QACtB,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAClB,IAAI,QAAQ,KAAK,SAAS,IAAI,IAAI,CAAC,MAAM,GAAG,QAAQ;YAAE,MAAM;QAC5D,MAAM,GAAG,MAAM,CAAC,aAAa,CAAC;KAC/B;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;;;;;GAUG;AACH,SAAS,aAAa,CACpB,KAAiB,EACjB,QAAgB,EAChB,EAAW,EACX,YAAoB,EACpB,MAA8B;IAE9B,IAAI,OAA4B,CAAC;IACjC,IAAI;QACF,OAAO,GAAG,KAAK,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC;KAC5C;IAAC,OAAO,CAAC,EAAE;QACV,IAAM,OAAO,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QAC3D,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,KAAK,CACX,kDAA0C,YAAY,+CAAmC,QAAQ,iBAAM,OAAO,MAAG,CAClH,CAAC;QACF,OAAO,KAAK,CAAC;KACd;IACD,OAAO,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;AACnD,CAAC","sourcesContent":["/**\n * Orchestrator — the entry point for the v1 element-selector algorithm.\n *\n * Given a click target, the orchestrator walks from the target up through its\n * ancestors and tries each registered strategy at each level. The first\n * strategy that returns a non-null candidate (and produces a selector that\n * resolves uniquely under the scope) wins; the trail of intermediate elements\n * between the anchor and the original target is then expressed as a positional\n * descent via `describeRelative`.\n *\n * Two-pass design: every ancestor is tried under the `explicitTrackingAttribute`\n * strategy first, then the entire walk repeats with `stableId`. This ordering\n * means an explicit anchor anywhere up the tree always beats a stable id deeper\n * down — the design doc describes this as the \"customer intent overrides\n * structural inference\" rule.\n *\n * The orchestrator does not own the fallback. When no strategy + walk produces\n * a unique selector, it returns `null` and the engine wires the\n * `fallback-css-path` path in instead. Keeping the fallback outside the\n * orchestrator keeps the strategy chain testable in isolation.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { ElementSelectorLogger, ResolvedSelectorConfig, Strategy, StrategyContext } from './types';\nimport { explicitTrackingAttribute } from './strategies/explicit-tracking-attribute';\nimport { stableId as stableIdStrategy } from './strategies/stable-id';\nimport { describeRelative } from './helpers/describe-relative';\n\n/**\n * Default strategy chain in priority order. Used by the engine factory when the\n * caller doesn't provide an explicit list. Exported for diagnostics — tests\n * import this so they don't have to duplicate the list.\n */\nexport const DEFAULT_STRATEGIES: ReadonlyArray<Strategy> = [explicitTrackingAttribute, stableIdStrategy];\n\nexport interface OrchestratorOptions {\n /** Strategy chain. Defaults to `DEFAULT_STRATEGIES`. Order = priority. */\n strategies?: ReadonlyArray<Strategy>;\n /** Document or shadow root used for uniqueness checks. Defaults to the target's owner document. */\n scope?: ParentNode;\n /**\n * Optional logger. When provided, the orchestrator emits a `debug` log if a\n * strategy produces a malformed selector that throws during the uniqueness\n * check — useful for diagnosing strategy bugs without crashing the engine.\n */\n logger?: ElementSelectorLogger;\n}\n\n/**\n * Try to produce a CSS selector for `el` using the strategy chain.\n *\n * Returns the composed selector string on success, or `null` if every strategy\n * declined at every walked ancestor. Callers (the engine) treat `null` as the\n * signal to invoke the fallback walker.\n *\n * Selector format on success:\n *\n * - Anchor only (target itself was an anchor): `<anchor-selector>`\n * - Anchor + trail (anchor was an ancestor): `<anchor-selector> > <descent>`\n *\n * Where `<anchor-selector>` is whatever the winning strategy returned for the\n * anchor element (e.g. `[data-amp-track-id=\"login-form\"]` or `div#hero`), and\n * `<descent>` is `describeRelative(anchor, trail)`.\n */\nexport function runOrchestrator(\n el: Element,\n config: ResolvedSelectorConfig,\n options: OrchestratorOptions = {},\n): string | null {\n const strategies = options.strategies ?? DEFAULT_STRATEGIES;\n const scope: ParentNode = options.scope ?? el.ownerDocument ?? document;\n const ctx: StrategyContext = { scope, config };\n\n const walk = collectWalk(el, config.maxAncestorWalkDepth);\n\n // Two-pass: try strategy[0] across the whole walk, then strategy[1], etc.\n // This gives an \"explicit anchor at any depth beats a structural anchor any\n // depth\" priority, which matches the design doc's \"customer intent overrides\n // structural inference\" rule.\n for (const strategy of strategies) {\n for (let i = 0; i < walk.length; i++) {\n const anchor = walk[i];\n const anchorSelector = strategy.try(anchor, ctx);\n if (anchorSelector === null) continue;\n\n // Anchor was the target itself — no descent needed.\n if (i === 0) {\n if (isUniqueMatch(scope, anchorSelector, el, strategy.name, options.logger)) {\n return anchorSelector;\n }\n continue;\n }\n\n // Anchor was an ancestor — descend back to the target through the trail.\n const trail = walk.slice(0, i).reverse();\n const descent = describeRelative(anchor, trail);\n const composed = `${anchorSelector} > ${descent}`;\n if (isUniqueMatch(scope, composed, el, strategy.name, options.logger)) {\n return composed;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Build the walk array `[target, parent, grandparent, ...]`, stopping at\n * `<html>` (or at the depth limit if configured). Excludes the document\n * element's parent (which is the Document node and not an Element).\n */\nfunction collectWalk(el: Element, maxDepth: number | undefined): Element[] {\n const walk: Element[] = [];\n let cursor: Element | null = el;\n while (cursor !== null) {\n walk.push(cursor);\n if (maxDepth !== undefined && walk.length > maxDepth) break;\n cursor = cursor.parentElement;\n }\n return walk;\n}\n\n/**\n * Check whether `selector` resolves to exactly `el` and no other element in\n * `scope`. The strategies themselves don't run uniqueness checks — that's the\n * orchestrator's job, so strategies stay pure transforms and stay testable in\n * isolation.\n *\n * When the selector is malformed (which is a strategy bug rather than user\n * input), we log at `debug` and return false rather than throwing. The log\n * lets engineers diagnose a misbehaving strategy without the engine taking\n * down whatever it's wired into.\n */\nfunction isUniqueMatch(\n scope: ParentNode,\n selector: string,\n el: Element,\n strategyName: string,\n logger?: ElementSelectorLogger,\n): boolean {\n let matches: NodeListOf<Element>;\n try {\n matches = scope.querySelectorAll(selector);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.debug(\n `@amplitude/element-selector: strategy \"${strategyName}\" emitted a malformed selector \"${selector}\" (${message})`,\n );\n return false;\n }\n return matches.length === 1 && matches[0] === el;\n}\n"]}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { ElementSelectorLogger } from '../types';
|
|
2
|
+
/**
|
|
3
|
+
* Autogenerated-id pattern pack.
|
|
4
|
+
*
|
|
5
|
+
* When an element id matches any of these regexes, the algorithm treats the
|
|
6
|
+
* element as if it has no id — the stableId strategy returns null and the
|
|
7
|
+
* fallback walks past it instead of anchoring on it. Stops selectors from
|
|
8
|
+
* pinning to ids that change between page loads or component re-mounts.
|
|
9
|
+
*
|
|
10
|
+
* Defaults are surfaced to customers in remote config so they can audit what's
|
|
11
|
+
* being filtered and add or remove patterns to match their stack.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Built-in defaults, in the order they're applied (order doesn't affect
|
|
15
|
+
* correctness — `some()` short-circuits on the first match).
|
|
16
|
+
*/
|
|
17
|
+
export declare const DEFAULT_AUTOGENERATED_ID_PATTERNS: ReadonlyArray<RegExp>;
|
|
18
|
+
/**
|
|
19
|
+
* Compile a list of regex pattern strings (e.g. from a remote-config payload)
|
|
20
|
+
* into RegExp objects. Invalid patterns are skipped (not thrown) so a single
|
|
21
|
+
* bad regex in remote config can't crash the engine.
|
|
22
|
+
*
|
|
23
|
+
* Pass `logger` to surface invalid patterns at `warn` level — useful for
|
|
24
|
+
* diagnosing why a customer's override isn't taking effect.
|
|
25
|
+
*
|
|
26
|
+
* Callers decide whether to merge the result with `DEFAULT_AUTOGENERATED_ID_PATTERNS`
|
|
27
|
+
* or use it as a full replacement. That policy lives in the config resolver,
|
|
28
|
+
* not here.
|
|
29
|
+
*/
|
|
30
|
+
export declare function compile(patterns: string[], logger?: ElementSelectorLogger): RegExp[];
|
|
31
|
+
/**
|
|
32
|
+
* Check whether `id` is "stable" relative to a set of patterns. An id is
|
|
33
|
+
* stable when it's a non-empty string AND doesn't match any pattern in
|
|
34
|
+
* `patterns`. Null, undefined, and empty-string ids are not stable.
|
|
35
|
+
*/
|
|
36
|
+
export declare function isStableId(id: string | null | undefined, patterns: ReadonlyArray<RegExp>): boolean;
|
|
37
|
+
//# sourceMappingURL=autogenerated-ids.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"autogenerated-ids.d.ts","sourceRoot":"","sources":["../../../src/patterns/autogenerated-ids.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAEjD;;;;;;;;;;GAUG;AAEH;;;GAGG;AACH,eAAO,MAAM,iCAAiC,EAAE,aAAa,CAAC,MAAM,CAkBnE,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,OAAO,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,MAAM,CAAC,EAAE,qBAAqB,GAAG,MAAM,EAAE,CAWpF;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,QAAQ,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,OAAO,CAMlG"}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { __values } from "tslib";
|
|
2
|
+
/**
|
|
3
|
+
* Autogenerated-id pattern pack.
|
|
4
|
+
*
|
|
5
|
+
* When an element id matches any of these regexes, the algorithm treats the
|
|
6
|
+
* element as if it has no id — the stableId strategy returns null and the
|
|
7
|
+
* fallback walks past it instead of anchoring on it. Stops selectors from
|
|
8
|
+
* pinning to ids that change between page loads or component re-mounts.
|
|
9
|
+
*
|
|
10
|
+
* Defaults are surfaced to customers in remote config so they can audit what's
|
|
11
|
+
* being filtered and add or remove patterns to match their stack.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Built-in defaults, in the order they're applied (order doesn't affect
|
|
15
|
+
* correctness — `some()` short-circuits on the first match).
|
|
16
|
+
*/
|
|
17
|
+
export var DEFAULT_AUTOGENERATED_ID_PATTERNS = [
|
|
18
|
+
// React useId() — ":r0:", ":r1:", ":rk:". Stable for one render; new id on next mount.
|
|
19
|
+
/^:r[0-9a-z]+:$/,
|
|
20
|
+
// Radix UI primitives — "radix-:r3:", "radix-A1B2C3". Prefix match (the
|
|
21
|
+
// shape of what comes after `radix-` varies by Radix version and React
|
|
22
|
+
// major; only the prefix is reliable).
|
|
23
|
+
/^radix-/,
|
|
24
|
+
// Headless UI (Tailwind Labs) — "headlessui-menu-button-:r5:". Prefix match.
|
|
25
|
+
/^headlessui-/,
|
|
26
|
+
// MUI internal id prefix — "mui-12345". Don't confuse with Mui-* CSS class state markers.
|
|
27
|
+
/^mui-/,
|
|
28
|
+
// Hex-only ids >=16 chars — UUIDs without hyphens, build hashes. Whole-string match.
|
|
29
|
+
/^[a-f0-9]{16,}$/i,
|
|
30
|
+
// Trailing long digit run — "session-1700000000", "row-20250515". Timestamps, counters.
|
|
31
|
+
/-\d{8,}$/,
|
|
32
|
+
// Any 4+ consecutive digits anywhere — "product-2134", "swiper-wrapper-…41039".
|
|
33
|
+
// ContentSquare's heuristic; catches the digit-heavy portions of library-generated ids.
|
|
34
|
+
/\d{4,}/,
|
|
35
|
+
];
|
|
36
|
+
/**
|
|
37
|
+
* Compile a list of regex pattern strings (e.g. from a remote-config payload)
|
|
38
|
+
* into RegExp objects. Invalid patterns are skipped (not thrown) so a single
|
|
39
|
+
* bad regex in remote config can't crash the engine.
|
|
40
|
+
*
|
|
41
|
+
* Pass `logger` to surface invalid patterns at `warn` level — useful for
|
|
42
|
+
* diagnosing why a customer's override isn't taking effect.
|
|
43
|
+
*
|
|
44
|
+
* Callers decide whether to merge the result with `DEFAULT_AUTOGENERATED_ID_PATTERNS`
|
|
45
|
+
* or use it as a full replacement. That policy lives in the config resolver,
|
|
46
|
+
* not here.
|
|
47
|
+
*/
|
|
48
|
+
export function compile(patterns, logger) {
|
|
49
|
+
var e_1, _a;
|
|
50
|
+
var compiled = [];
|
|
51
|
+
try {
|
|
52
|
+
for (var patterns_1 = __values(patterns), patterns_1_1 = patterns_1.next(); !patterns_1_1.done; patterns_1_1 = patterns_1.next()) {
|
|
53
|
+
var pattern = patterns_1_1.value;
|
|
54
|
+
try {
|
|
55
|
+
compiled.push(new RegExp(pattern));
|
|
56
|
+
}
|
|
57
|
+
catch (e) {
|
|
58
|
+
var message = e instanceof Error ? e.message : String(e);
|
|
59
|
+
logger === null || logger === void 0 ? void 0 : logger.warn("@amplitude/element-selector: ignoring invalid autogenerated-id pattern \"".concat(pattern, "\" (").concat(message, ")"));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
64
|
+
finally {
|
|
65
|
+
try {
|
|
66
|
+
if (patterns_1_1 && !patterns_1_1.done && (_a = patterns_1.return)) _a.call(patterns_1);
|
|
67
|
+
}
|
|
68
|
+
finally { if (e_1) throw e_1.error; }
|
|
69
|
+
}
|
|
70
|
+
return compiled;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Check whether `id` is "stable" relative to a set of patterns. An id is
|
|
74
|
+
* stable when it's a non-empty string AND doesn't match any pattern in
|
|
75
|
+
* `patterns`. Null, undefined, and empty-string ids are not stable.
|
|
76
|
+
*/
|
|
77
|
+
export function isStableId(id, patterns) {
|
|
78
|
+
var e_2, _a;
|
|
79
|
+
if (id === null || id === undefined || id === '')
|
|
80
|
+
return false;
|
|
81
|
+
try {
|
|
82
|
+
for (var patterns_2 = __values(patterns), patterns_2_1 = patterns_2.next(); !patterns_2_1.done; patterns_2_1 = patterns_2.next()) {
|
|
83
|
+
var pattern = patterns_2_1.value;
|
|
84
|
+
if (pattern.test(id))
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
catch (e_2_1) { e_2 = { error: e_2_1 }; }
|
|
89
|
+
finally {
|
|
90
|
+
try {
|
|
91
|
+
if (patterns_2_1 && !patterns_2_1.done && (_a = patterns_2.return)) _a.call(patterns_2);
|
|
92
|
+
}
|
|
93
|
+
finally { if (e_2) throw e_2.error; }
|
|
94
|
+
}
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=autogenerated-ids.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"autogenerated-ids.js","sourceRoot":"","sources":["../../../src/patterns/autogenerated-ids.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;GAUG;AAEH;;;GAGG;AACH,MAAM,CAAC,IAAM,iCAAiC,GAA0B;IACtE,uFAAuF;IACvF,gBAAgB;IAChB,wEAAwE;IACxE,uEAAuE;IACvE,uCAAuC;IACvC,SAAS;IACT,6EAA6E;IAC7E,cAAc;IACd,0FAA0F;IAC1F,OAAO;IACP,qFAAqF;IACrF,kBAAkB;IAClB,wFAAwF;IACxF,UAAU;IACV,gFAAgF;IAChF,wFAAwF;IACxF,QAAQ;CACT,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,OAAO,CAAC,QAAkB,EAAE,MAA8B;;IACxE,IAAM,QAAQ,GAAa,EAAE,CAAC;;QAC9B,KAAsB,IAAA,aAAA,SAAA,QAAQ,CAAA,kCAAA,wDAAE;YAA3B,IAAM,OAAO,qBAAA;YAChB,IAAI;gBACF,QAAQ,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;aACpC;YAAC,OAAO,CAAC,EAAE;gBACV,IAAM,OAAO,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;gBAC3D,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,IAAI,CAAC,mFAA2E,OAAO,iBAAM,OAAO,MAAG,CAAC,CAAC;aAClH;SACF;;;;;;;;;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,UAAU,CAAC,EAA6B,EAAE,QAA+B;;IACvF,IAAI,EAAE,KAAK,IAAI,IAAI,EAAE,KAAK,SAAS,IAAI,EAAE,KAAK,EAAE;QAAE,OAAO,KAAK,CAAC;;QAC/D,KAAsB,IAAA,aAAA,SAAA,QAAQ,CAAA,kCAAA,wDAAE;YAA3B,IAAM,OAAO,qBAAA;YAChB,IAAI,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;gBAAE,OAAO,KAAK,CAAC;SACpC;;;;;;;;;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { ElementSelectorLogger } from '../types';\n\n/**\n * Autogenerated-id pattern pack.\n *\n * When an element id matches any of these regexes, the algorithm treats the\n * element as if it has no id — the stableId strategy returns null and the\n * fallback walks past it instead of anchoring on it. Stops selectors from\n * pinning to ids that change between page loads or component re-mounts.\n *\n * Defaults are surfaced to customers in remote config so they can audit what's\n * being filtered and add or remove patterns to match their stack.\n */\n\n/**\n * Built-in defaults, in the order they're applied (order doesn't affect\n * correctness — `some()` short-circuits on the first match).\n */\nexport const DEFAULT_AUTOGENERATED_ID_PATTERNS: ReadonlyArray<RegExp> = [\n // React useId() — \":r0:\", \":r1:\", \":rk:\". Stable for one render; new id on next mount.\n /^:r[0-9a-z]+:$/,\n // Radix UI primitives — \"radix-:r3:\", \"radix-A1B2C3\". Prefix match (the\n // shape of what comes after `radix-` varies by Radix version and React\n // major; only the prefix is reliable).\n /^radix-/,\n // Headless UI (Tailwind Labs) — \"headlessui-menu-button-:r5:\". Prefix match.\n /^headlessui-/,\n // MUI internal id prefix — \"mui-12345\". Don't confuse with Mui-* CSS class state markers.\n /^mui-/,\n // Hex-only ids >=16 chars — UUIDs without hyphens, build hashes. Whole-string match.\n /^[a-f0-9]{16,}$/i,\n // Trailing long digit run — \"session-1700000000\", \"row-20250515\". Timestamps, counters.\n /-\\d{8,}$/,\n // Any 4+ consecutive digits anywhere — \"product-2134\", \"swiper-wrapper-…41039\".\n // ContentSquare's heuristic; catches the digit-heavy portions of library-generated ids.\n /\\d{4,}/,\n];\n\n/**\n * Compile a list of regex pattern strings (e.g. from a remote-config payload)\n * into RegExp objects. Invalid patterns are skipped (not thrown) so a single\n * bad regex in remote config can't crash the engine.\n *\n * Pass `logger` to surface invalid patterns at `warn` level — useful for\n * diagnosing why a customer's override isn't taking effect.\n *\n * Callers decide whether to merge the result with `DEFAULT_AUTOGENERATED_ID_PATTERNS`\n * or use it as a full replacement. That policy lives in the config resolver,\n * not here.\n */\nexport function compile(patterns: string[], logger?: ElementSelectorLogger): RegExp[] {\n const compiled: RegExp[] = [];\n for (const pattern of patterns) {\n try {\n compiled.push(new RegExp(pattern));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: ignoring invalid autogenerated-id pattern \"${pattern}\" (${message})`);\n }\n }\n return compiled;\n}\n\n/**\n * Check whether `id` is \"stable\" relative to a set of patterns. An id is\n * stable when it's a non-empty string AND doesn't match any pattern in\n * `patterns`. Null, undefined, and empty-string ids are not stable.\n */\nexport function isStableId(id: string | null | undefined, patterns: ReadonlyArray<RegExp>): boolean {\n if (id === null || id === undefined || id === '') return false;\n for (const pattern of patterns) {\n if (pattern.test(id)) return false;\n }\n return true;\n}\n"]}
|