Repository navigation
Expand file tree
/
Copy pathtransform.ts
More file actions
1837 lines (1648 loc) · 77 KB
/
Copy pathtransform.ts
File metadata and controls
1837 lines (1648 loc) · 77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {
ElementNode,
NodeTransform,
RootNode,
TemplateChildNode,
AttributeNode,
DirectiveNode,
SimpleExpressionNode,
CompoundExpressionNode,
IfNode,
IfBranchNode,
ForNode,
} from "@vue/compiler-core";
import type { AttributeValue, DataTestIdEntryOverrides, HierarchyMap, ResolvedKeyInfo } from "./utils";
import { createSimpleExpression, NodeTypes, processExpression } from "@vue/compiler-core";
import { parseExpression } from "@babel/parser"
import { isIdentifierNode, isStringLiteralNode } from "./compiler/babel-guards";
import path from "node:path";
import fs from "node:fs";
import { TESTID_CLICK_EVENT_NAME } from "./click-instrumentation";
import { createPomParameterSpec } from "./pom-params";
import { createPomStringPattern } from "./pom-patterns";
import {
buildVueSfcPathIndex,
elementExplicitlyForwardsTestId,
getElementControlRole,
normalizeWrapperSearchRoots,
resetWrapperContractCaches,
resolveSfcPathForTag,
resolveWrapperContractForTag,
toKebabCaseTag,
} from "./wrapper-contract";
import {
findLoadActionDirective,
isAsciiDigitCode,
isAsciiLetterCode,
isAsciiUppercaseLetterCode,
nodeHasStaticClickDirective,
resolveActionPropNames,
upsertAttribute,
formatTagName,
getComposedClickHandlerContent,
getStaticIdOrNameHint,
getInnerText,
getContainedInSlotDataKeyInfo,
getContainedInVForDirectiveKeyInfo,
getVueExpressionSource,
renderTemplateLiteralExpression,
tryGetContainedInStaticVForSourceLiteralValues,
getKeyDirectiveInfo,
getBindingKeyInfo,
getBindingValueHint,
getModelBindingValues,
getNativeWrapperTransformInfo,
nodeHandlerAttributeValue,
nodeHandlerAttributeInfo,
tryGetClickDirective,
nodeHasToDirective,
generateToDirectiveDataTestId,
toDirectiveObjectFieldNameValue,
staticAttributeValue,
templateAttributeValue,
toPascalCase,
tryResolveToDirectiveTargetComponentName,
IComponentDependencies,
NativeWrappersMap,
NativeRole,
applyResolvedDataTestId,
tryGetExistingElementDataTestId,
buildSlotScopeFallbackKeyExpression,
toResolvedKeyInfo,
findTemplateSlotScopeExpression,
tryExtractSlotScopeVariableNames,
getContainedInSlotTemplateNode,
isSlotScopeCallbackClickHandler,
getDegenerateSlotScopeFallbackKeyVariable,
getSlotScopeVariablesUsedAsBareCallbackHandlers } from "./utils";
const CLICK_EVENT_NAME = TESTID_CLICK_EVENT_NAME;
const POM_INSTANCE_ATTRIBUTE = "data-pom-instance";
interface SemanticExpressionNode {
type?: string;
name?: string;
value?: string;
computed?: boolean;
property?: SemanticExpressionNode;
object?: SemanticExpressionNode;
expression?: SemanticExpressionNode;
callee?: SemanticExpressionNode;
}
function getLastSemanticIdentifier(node: SemanticExpressionNode | null | undefined): string | null {
if (!node) {
return null;
}
if (node.type === "Identifier") {
return node.name?.trim() || null;
}
if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
if (!node.computed && node.property?.type === "Identifier") {
return node.property.name?.trim() || null;
}
if (node.computed && node.property?.type === "StringLiteral") {
return node.property.value?.trim() || null;
}
return getLastSemanticIdentifier(node.object);
}
if (node.type === "CallExpression" || node.type === "OptionalCallExpression") {
return getLastSemanticIdentifier(node.callee);
}
if (
node.type === "TSAsExpression"
|| node.type === "TSTypeAssertion"
|| node.type === "TSNonNullExpression"
|| node.type === "ChainExpression"
) {
return getLastSemanticIdentifier(node.expression);
}
return null;
}
function getBoundSemanticName(element: ElementNode, attributeName: string): string | null {
const directive = element.props.find((prop): prop is DirectiveNode => {
return prop.type === NodeTypes.DIRECTIVE
&& prop.name === "bind"
&& prop.arg?.type === NodeTypes.SIMPLE_EXPRESSION
&& prop.arg.content === attributeName
&& !!prop.exp;
});
if (!directive?.exp) {
return null;
}
const source = getVueExpressionSource(
directive.exp as SimpleExpressionNode | CompoundExpressionNode,
"loc",
"content",
"compiled",
);
if (!source) {
return null;
}
try {
const identifier = getLastSemanticIdentifier(parseExpression(source, { plugins: ["typescript"] }) as SemanticExpressionNode);
return identifier ? toPascalCase(identifier) : null;
}
catch {
return null;
}
}
function getComponentInstanceNameCandidates(element: ElementNode): string[] {
const explicitAccessibleNames = ["aria-label", "label", "title", "name"]
.map(attributeName => getStaticAttributeContent(element, attributeName))
.filter((value): value is string => !!value)
.map(toPascalCase);
const optionsName = getBoundSemanticName(element, "options");
const { vModel, modelValue } = getModelBindingValues(element);
const modelName = modelValue || vModel;
const candidates = [
...explicitAccessibleNames,
optionsName && optionsName !== "Options" ? optionsName : null,
modelName && !new Set(["Data", "Item", "ModelValue", "Value"]).has(modelName)
? toPascalCase(modelName)
: null,
toPascalCase(element.tag),
].filter((value): value is string => !!value);
return Array.from(new Set(candidates));
}
function getElementSourceId(element: ElementNode): string {
return `${element.tag}:${element.loc.start.offset}:${element.loc.end.offset}`;
}
function getNearestComponentAncestor(
element: ElementNode,
hierarchyMap: HierarchyMap,
isComponentLikeTag: (tag: string) => boolean,
): ElementNode | null {
let parent = hierarchyMap.get(element) ?? null;
while (parent) {
if (isComponentLikeTag(parent.tag)) {
return parent;
}
parent = hierarchyMap.get(parent) ?? null;
}
return null;
}
function getSlotNameFromTemplate(element: ElementNode): string | null {
const directive = element.props.find((prop): prop is DirectiveNode => {
return prop.type === NodeTypes.DIRECTIVE && prop.name === "slot";
});
if (!directive) {
return null;
}
if (!directive.arg) {
return "default";
}
return directive.arg.type === NodeTypes.SIMPLE_EXPRESSION
? directive.arg.content.trim() || "default"
: null;
}
function getStaticAttributeContent(element: ElementNode, name: string): string | null {
const attr = element.props.find((prop): prop is AttributeNode => {
return prop.type === NodeTypes.ATTRIBUTE && prop.name === name;
});
return attr?.value?.content?.trim() || null;
}
function getNativeHtmlControlRole(element: ElementNode): NativeRole | null {
return getElementControlRole(element);
}
function getConventionalOptionIdentityAttribute(element: ElementNode): "data-value" | "value" | null {
const explicitRole = getStaticAttributeContent(element, "role")?.toLowerCase();
if (explicitRole === "option") {
return "data-value";
}
if (explicitRole === "radio") {
return "value";
}
const tag = element.tag.toLowerCase();
const type = getStaticAttributeContent(element, "type")?.toLowerCase();
if ((tag === "input" || tag === "uinput") && type === "radio") {
return "value";
}
return null;
}
function describeConventionalOption(element: ElementNode): string {
return getConventionalOptionIdentityAttribute(element) === "value"
? "radio"
: `<${element.tag} role="option">`;
}
/**
* Normalizes label text into the stable string used for generated control names.
*
* This operates on plain UI text, not source code, so the regex usage is intentionally scoped
* to this helper instead of adding broader string-scanning logic.
*/
/* eslint-disable no-restricted-syntax -- allowed: regex is restricted for source parsing, but this helper only normalizes plain UI label text */
function normalizeControlLabelText(value: string | null): string | null {
const normalized = (value ?? "")
.replace(/\*/g, " ")
.replace(/\s+/g, " ")
.trim();
return normalized || null;
}
/* eslint-enable no-restricted-syntax */
function getLabelNodeText(labelNode: ElementNode): string | null {
for (const child of labelNode.children || []) {
if (child.type === NodeTypes.TEXT) {
const normalized = normalizeControlLabelText(child.content);
if (normalized) {
return normalized;
}
continue;
}
if (child.type !== NodeTypes.ELEMENT) {
continue;
}
if (getNativeHtmlControlRole(child)) {
continue;
}
const normalized = normalizeControlLabelText(getInnerText(child));
if (normalized) {
return normalized;
}
}
return normalizeControlLabelText(getInnerText(labelNode));
}
function getAssociatedLabelText(element: ElementNode, hierarchyMap: HierarchyMap): string | null {
let parent = hierarchyMap.get(element) || null;
while (parent) {
if (parent.tag === "label") {
return getLabelNodeText(parent);
}
parent = hierarchyMap.get(parent) || null;
}
const id = getStaticAttributeContent(element, "id");
if (!id) {
return null;
}
const candidates = new Set<ElementNode>();
for (const child of hierarchyMap.keys()) {
candidates.add(child);
}
for (const maybeParent of hierarchyMap.values()) {
if (maybeParent) {
candidates.add(maybeParent);
}
}
for (const candidate of candidates) {
if (candidate.tag !== "label") {
continue;
}
if (getStaticAttributeContent(candidate, "for") === id) {
return getLabelNodeText(candidate);
}
}
return null;
}
function trimLeadingSeparators(value: string): string {
if (!value) {
return "";
}
let i = 0;
while (i < value.length) {
const ch = value[i];
if (ch === "-" || ch === "_" || ch === " " || ch === "\t" || ch === "\n" || ch === "\r") {
i += 1;
continue;
}
break;
}
return value.slice(i);
}
function getConditionalDirectiveInfo(element: ElementNode): { kind: "if" | "else-if" | "else"; source: string } | null {
const directive = element.props.find((p): p is DirectiveNode => {
return p.type === NodeTypes.DIRECTIVE && (p.name === "if" || p.name === "else-if" || p.name === "else" || p.name === "elseif");
});
if (!directive)
return null;
// Some compiler versions/paths represent `v-else-if` as directive.name === "else" with an expression.
if (directive.name === "else") {
const exp = directive.exp;
if (exp && (exp.type === NodeTypes.SIMPLE_EXPRESSION || exp.type === NodeTypes.COMPOUND_EXPRESSION)) {
const source = getVueExpressionSource(exp as SimpleExpressionNode | CompoundExpressionNode, "content", "compiled");
return { kind: "else-if", source };
}
return { kind: "else", source: "" };
}
// Alternate naming for else-if.
if (directive.name === "elseif") {
const exp = directive.exp;
if (!exp || (exp.type !== NodeTypes.SIMPLE_EXPRESSION && exp.type !== NodeTypes.COMPOUND_EXPRESSION))
return null;
const source = getVueExpressionSource(exp as SimpleExpressionNode | CompoundExpressionNode, "content", "compiled");
return { kind: "else-if", source };
}
const exp = directive.exp;
if (!exp || (exp.type !== NodeTypes.SIMPLE_EXPRESSION && exp.type !== NodeTypes.COMPOUND_EXPRESSION))
return null;
const source = getVueExpressionSource(exp as SimpleExpressionNode | CompoundExpressionNode, "content", "compiled");
return { kind: directive.name as "if" | "else-if", source };
}
function tryExtractStableHintFromConditionalExpressionSource(source: string): string | null {
const src = (source ?? "").trim();
if (!src)
return null;
const isIdentifierish = (value: string): boolean => {
const v = value.trim();
if (!v)
return false;
const isUnderscore = (ch: number) => ch === 95;
const first = v.charCodeAt(0);
if (!isAsciiLetterCode(first))
return false;
for (let i = 1; i < v.length; i += 1) {
const ch = v.charCodeAt(i);
if (isAsciiLetterCode(ch) || isAsciiDigitCode(ch) || isUnderscore(ch)) {
continue;
}
return false;
}
return true;
};
try {
const expr = parseExpression(src, { plugins: ["typescript"] }) as object;
const results: string[] = [];
const walk = (n: object | null) => {
if (!n)
return;
if (isStringLiteralNode(n)) {
const v = (n.value ?? "").trim();
if (isIdentifierish(v)) {
results.push(v);
}
}
if (isIdentifierNode(n)) {
const v = (n.name ?? "").trim();
if (isIdentifierish(v)) {
results.push(v);
}
}
const node = n as Record<string, unknown>;
for (const value of Object.values(node)) {
if (!value)
continue;
if (Array.isArray(value)) {
for (const item of value) {
if (item && typeof item === "object") {
walk(item as object);
}
}
continue;
}
if (typeof value === "object") {
walk(value as object);
}
}
};
walk(expr);
return results.length ? results[results.length - 1]! : null;
}
catch {
return null;
}
}
function tryWrapClickDirectiveForTestEvents(
element: ElementNode,
testIdAttribute: string,
resolvedRuntimeTestId: AttributeValue | null | undefined,
): void {
const jsStringLiteral = (value: string) => {
// Use JSON.stringify to safely escape quotes/newlines.
return JSON.stringify(value);
};
const getTestIdExpressionForNode = (): string => {
if (!resolvedRuntimeTestId) {
return "undefined";
}
if (resolvedRuntimeTestId.kind === "static") {
return jsStringLiteral(resolvedRuntimeTestId.value);
}
// Template AttributeValues keep only the fragment body (`line-${item.id}`), because most call sites
// splice that fragment into a larger generated template. Click instrumentation needs a standalone
// JavaScript template-literal expression again, so we rebuild it here from the parsed quasis/spans.
return `(${renderTemplateLiteralExpression(resolvedRuntimeTestId)})`;
};
const testIdExpression = getTestIdExpressionForNode();
// Find @click / v-on:click directive.
const clickDirective = tryGetClickDirective(element);
if (!clickDirective)
return;
// Mark nodes whose click handlers we instrument so the Playwright runtime can
// deterministically decide whether it should wait for the event.
// (Avoids env-var gating and avoids waiting on clicks that aren't instrumented.)
const hasInstrumentedAttr = element.props.some(p => p.type === NodeTypes.ATTRIBUTE && p.name === "data-click-instrumented");
if (!hasInstrumentedAttr) {
upsertAttribute(element, "data-click-instrumented", staticAttributeValue("1"));
}
const exp = clickDirective.exp;
if (!exp)
return;
// Avoid double-wrapping if transform runs multiple times (SSR + client passes).
const existingSource = getVueExpressionSource(exp as SimpleExpressionNode | CompoundExpressionNode, "loc", "content");
if (existingSource.includes(CLICK_EVENT_NAME))
return;
// Best-effort extract of the original handler expression.
// For SIMPLE_EXPRESSION, prefer content; otherwise fall back to loc.source.
const originalExpression = getVueExpressionSource(exp as SimpleExpressionNode | CompoundExpressionNode, "content", "loc");
if (!originalExpression)
return;
// Vue treats v-on expressions as raw statements in many cases (e.g. multiline @click with `if (...) ...`).
// Our wrapper must preserve that capability; otherwise the Vue compiler will try to parse statements as
// an expression and fail.
const isStatementBody = (() => {
const v = originalExpression.trim();
if (!v)
return false;
// Prefer AST parsing over string heuristics.
// - If the handler parses as an expression, we can treat it as an expression body.
// - If it fails to parse as an expression (e.g. `if (...) ...`, `foo(); bar();`, `{ ... }` block),
// Vue expects statement semantics.
try {
parseExpression(v, { plugins: ["typescript"] });
return false;
}
catch {
return true;
}
})();
// Wrap in an arrow to preserve $event semantics.
// We intentionally read the test id at runtime from the event target rather than trying to
// statically embed it. NOTE: wrapper components often don't forward data-testid to the actual DOM.
// We therefore prefer the template node's data-testid expression, with an event-target fallback.
const statementWrappedHandler = `($event) => {
const __win = ($event && $event.view) ? $event.view : undefined;
const __target = ($event && $event.currentTarget) ? $event.currentTarget : undefined;
const __testIdFromNode = ${testIdExpression};
const __testIdFromTarget = (__target && typeof __target.getAttribute === 'function') ? __target.getAttribute(${jsStringLiteral(testIdAttribute)}) : undefined;
const __testId = (__testIdFromNode ?? __testIdFromTarget);
const __emit = (phase, err) => {
try {
const __w = __win || (__target && __target.ownerDocument && __target.ownerDocument.defaultView);
const __CustomEvent = __w && __w.CustomEvent;
if (__w && typeof __w.dispatchEvent === 'function' && __CustomEvent) {
__w.dispatchEvent(new __CustomEvent('${CLICK_EVENT_NAME}', { detail: { testId: __testId, phase, err: err ? String(err) : undefined } }));
}
} catch (e) {
// Instrumentation failures should never be silent. Log the root cause and fail fast.
const __w = __win || (__target && __target.ownerDocument && __target.ownerDocument.defaultView);
if (__w && __w.console && typeof __w.console.error === 'function') {
__w.console.error('[testid-click-event] failed to emit ${CLICK_EVENT_NAME}', e);
}
throw e;
}
};
const __w2 = __win || (__target && __target.ownerDocument && __target.ownerDocument.defaultView);
const __P = __w2 && __w2.Promise;
__emit('before');
let __ret;
try {
__ret = (async () => {
${originalExpression}
})();
} catch (e) {
__emit('error', e);
throw e;
}
// Avoid referencing globals like Promise/globalThis directly in the template expression;
// Vue may rewrite them to _ctx.* and break at runtime. Use window properties instead.
if (__P && typeof __P.resolve === 'function') {
return __P.resolve(__ret)
.then(() => { __emit('after'); }, (e) => { __emit('error', e); throw e; });
}
// Fallback: if the return is thenable, attach handlers.
if (__ret && typeof __ret.then === 'function') {
return __ret.then(() => { __emit('after'); }, (e) => { __emit('error', e); throw e; });
}
__emit('after');
return __ret;
}`;
const expressionWrappedHandler = `($event) => {
const __win = ($event && $event.view) ? $event.view : undefined;
const __target = ($event && $event.currentTarget) ? $event.currentTarget : undefined;
const __testIdFromNode = ${testIdExpression};
const __testIdFromTarget = (__target && typeof __target.getAttribute === 'function') ? __target.getAttribute(${jsStringLiteral(testIdAttribute)}) : undefined;
const __testId = (__testIdFromNode ?? __testIdFromTarget);
const __emit = (phase, err) => {
try {
const __w = __win || (__target && __target.ownerDocument && __target.ownerDocument.defaultView);
const __CustomEvent = __w && __w.CustomEvent;
if (__w && typeof __w.dispatchEvent === 'function' && __CustomEvent) {
__w.dispatchEvent(new __CustomEvent('${CLICK_EVENT_NAME}', { detail: { testId: __testId, phase, err: err ? String(err) : undefined } }));
}
} catch (e) {
// Instrumentation failures should never be silent. Log the root cause and fail fast.
const __w = __win || (__target && __target.ownerDocument && __target.ownerDocument.defaultView);
if (__w && __w.console && typeof __w.console.error === 'function') {
__w.console.error('[testid-click-event] failed to emit ${CLICK_EVENT_NAME}', e);
}
throw e;
}
};
const __w2 = __win || (__target && __target.ownerDocument && __target.ownerDocument.defaultView);
const __P = __w2 && __w2.Promise;
__emit('before');
let __ret;
try {
const __maybeFn = (${originalExpression});
__ret = (typeof __maybeFn === 'function') ? __maybeFn($event) : __maybeFn;
} catch (e) {
__emit('error', e);
throw e;
}
// Avoid referencing globals like Promise/globalThis directly in the template expression;
// Vue may rewrite them to _ctx.* and break at runtime. Use window properties instead.
if (__P && typeof __P.resolve === 'function') {
return __P.resolve(__ret)
.then((v) => { __emit('after'); return v; }, (e) => { __emit('error', e); throw e; });
}
if (__ret && typeof __ret.then === 'function') {
return __ret.then((v) => { __emit('after'); return v; }, (e) => { __emit('error', e); throw e; });
}
__emit('after');
return __ret;
}`;
clickDirective.exp = {
type: NodeTypes.SIMPLE_EXPRESSION,
content: isStatementBody ? statementWrappedHandler : expressionWrappedHandler,
isStatic: false,
constType: 0,
// Preserve location metadata so downstream Vue compiler transforms don't crash.
loc: exp.loc,
} as SimpleExpressionNode;
}
let previousFileName = "";
const hierarchyMap: HierarchyMap = new Map(); // key is child, value is parent
/**
* Cross-file key context: when a child component is rendered inside a keyed slot scope,
* the parent records which prop receives the slot data. The child then uses that prop
* to key its internal testids.
*
* Key: child component name (PascalCase, as seen in the parent's template)
* Value: the prop name on the child that receives the slot-scope data object
*/
export type CrossFileKeyRegistry = Map<string, string>;
/**
* Creates a NodeTransform that adds data-testid attributes to elements
*/
export function createTestIdTransform(
componentName: string,
componentHierarchyMap: Map<string, IComponentDependencies>,
nativeWrappers: NativeWrappersMap = {},
skipTestIdGenerationInsideComponents: string[] = [],
viewsDirAbs: string,
options: {
existingIdBehavior?: "preserve" | "overwrite" | "error";
testIdAttribute?: string;
nameCollisionBehavior?: "error" | "warn" | "suffix";
missingSemanticNameBehavior?: "error" | "ignore";
warn?: (message: string) => void;
vueFilesPathMap?: Map<string, string>;
wrapperSearchRoots?: string[];
annotatorMetadata?: {
sourceAttribute: string;
metadataAttributePrefix: string;
} | null;
/** Shared registry for cross-file keyed slot context. */
crossFileKeyRegistry?: CrossFileKeyRegistry;
/**
* Per-component map of SFC component name -> attribute/binding name that overrides
* the conventional identity for repeated option controls.
*/
optionKeyAttribute?: Record<string, string>;
} = {},
): NodeTransform {
const existingIdBehavior = options.existingIdBehavior ?? "error";
const testIdAttribute = (options.testIdAttribute || "data-testid").trim() || "data-testid";
const nameCollisionBehavior = options.nameCollisionBehavior ?? "error";
const missingSemanticNameBehavior = options.missingSemanticNameBehavior ?? "error";
const warn = options.warn;
const vueFilesPathMap = options.vueFilesPathMap;
const wrapperSearchRoots = options.wrapperSearchRoots ?? [];
const annotatorMetadata = options.annotatorMetadata ?? null;
const crossFileKeyRegistry = options.crossFileKeyRegistry;
const optionKeyAttribute = options.optionKeyAttribute ?? {};
const resolvedNativeWrappers: NativeWrappersMap = Object.fromEntries(
Object.entries(nativeWrappers).map(([tag, config]) => [tag, { ...config }]),
);
const wrapperContractByTag = new Map<string, ReturnType<typeof resolveWrapperContractForTag>>();
const instanceWrapperContractByTag = new Map<string, ReturnType<typeof resolveWrapperContractForTag>>();
const getWrapperContract = (tag: string) => {
if (!wrapperContractByTag.has(tag)) {
wrapperContractByTag.set(tag, resolveWrapperContractForTag({
tag,
vueFilesPathMap,
wrapperSearchRoots,
testIdAttribute,
}));
}
return wrapperContractByTag.get(tag) ?? null;
};
const getInstanceWrapperContract = (tag: string) => {
if (!instanceWrapperContractByTag.has(tag)) {
instanceWrapperContractByTag.set(tag, resolveWrapperContractForTag({
tag,
vueFilesPathMap,
wrapperSearchRoots,
testIdAttribute: POM_INSTANCE_ATTRIBUTE,
}));
}
return instanceWrapperContractByTag.get(tag) ?? null;
};
// Some projects (and dev environments) use symlinks. We want viewsDir containment checks
// to behave like the filesystem does (real paths), but we must not crash for virtual
// Vite filenames (e.g. /@fs/...) or any non-existent paths.
const safeRealpath = (p: string) => {
try {
return fs.existsSync(p) ? fs.realpathSync(p) : p;
} catch {
return p;
}
};
const normalizedViewsDirAbs = path.normalize(safeRealpath(path.resolve(viewsDirAbs)));
// When `prefixIdentifiers` is enabled (e.g. the runtime Vue plugin pass), the Vue
// compiler transforms directive expressions (e.g. :data-testid="`foo-${bar}`") into
// compiled/compound forms BEFORE our exit function runs. This makes
// `tryGetExistingElementDataTestId` unable to detect the raw template literal.
//
// We save the raw directive `exp` node in the entry function (before Vue's transforms)
// and restore it in the exit function so the preservation logic can still see it.
// When generating methods incrementally, it's possible for the same logical test id to be
// encountered multiple times (e.g. due to wrapper behaviors, template shape, or repeated nodes).
// Deduplicate by method *content* to avoid duplicate declarations in generated POM classes.
const generatedMethodContentByComponent = new Map<string, Set<string>>();
// Track the most recent conditional (v-if / v-else-if) hint for a given parent element so
// adjacent v-else branches can derive a stable semantic hint (e.g. `else personId`).
const lastConditionalHintByParent = new WeakMap<object, string>();
const lastConditionalMergeGroupByParent = new WeakMap<object, string>();
// Track conditional hints per element so descendants can inherit context when they have
// an existing data-testid but no other naming signals.
const conditionalHintByElement = new WeakMap<ElementNode, string>();
// Track conditional hints per IF_BRANCH. This is required because Vue's structural transforms
// may remove v-if/v-else directives from element.props and instead wrap elements in IF/IF_BRANCH.
const conditionalHintByIfBranch = new WeakMap<IfBranchNode, string>();
const conditionalMergeGroupByElement = new WeakMap<ElementNode, string>();
const conditionalMergeGroupByElementLoc = new Map<string, string>();
const conditionalMergeGroupByIfBranch = new WeakMap<IfBranchNode, string>();
const componentInstanceNameOwnerByName = new Map<string, {
componentName: string;
keyed: boolean;
sourceId: string;
}>();
let conditionalMergeGroupCounter = 0;
// Slot-scope variables used as bare callback click handlers, captured per slot
// template element the first time the compiler visits it. The transform
// instruments @click handlers in document order, so by the time a later sibling
// is processed, earlier siblings' original handler expressions are already
// rewritten away — the snapshot must be taken at the template node itself,
// before any descendant is mutated.
const slotScopeCallbackVariablesByTemplate = new WeakMap<ElementNode, Set<string>>();
const getElementLocationKey = (element: ElementNode): string | null => {
const startOffset = element.loc?.start.offset;
const endOffset = element.loc?.end.offset;
if (typeof startOffset !== "number" || typeof endOffset !== "number") {
return null;
}
return `${element.tag}:${startOffset}:${endOffset}`;
};
const markConditionalMergeGroup = (nodes: TemplateChildNode[], mergeGroupKey: string) => {
for (const child of nodes) {
if (child.type === NodeTypes.ELEMENT) {
const element = child as ElementNode;
conditionalMergeGroupByElement.set(element, mergeGroupKey);
const elementLocationKey = getElementLocationKey(element);
if (elementLocationKey) {
conditionalMergeGroupByElementLoc.set(elementLocationKey, mergeGroupKey);
}
markConditionalMergeGroup(element.children as TemplateChildNode[], mergeGroupKey);
continue;
}
if (child.type === NodeTypes.IF) {
const ifNode = child as IfNode;
for (const branch of ifNode.branches ?? []) {
markConditionalMergeGroup(branch.children as TemplateChildNode[], mergeGroupKey);
}
continue;
}
if (child.type === NodeTypes.IF_BRANCH || child.type === NodeTypes.FOR) {
const branchLike = child as IfBranchNode | ForNode;
markConditionalMergeGroup((branchLike.children ?? []) as TemplateChildNode[], mergeGroupKey);
}
}
};
return (node: RootNode | TemplateChildNode, context) => {
if (skipTestIdGenerationInsideComponents.includes(componentName)) {
return;
}
// Capture conditional information early (before we reach elements nested under IF_BRANCH).
if (node.type === NodeTypes.IF) {
const ifNode = node as IfNode;
const branches = ifNode.branches ?? [];
const mergeGroupKey = `if-group:${++conditionalMergeGroupCounter}`;
const ifParentKey = context?.parent ? (context.parent as object) : null;
if (ifParentKey) {
lastConditionalMergeGroupByParent.set(ifParentKey, mergeGroupKey);
}
let lastHint: string | null = null;
for (const branch of branches) {
conditionalMergeGroupByIfBranch.set(branch, mergeGroupKey);
markConditionalMergeGroup((branch.children ?? []) as TemplateChildNode[], mergeGroupKey);
const cond = (branch.condition ?? null) as (SimpleExpressionNode | CompoundExpressionNode | null);
if (!cond) {
// else branch
const hint = lastHint ? `else ${lastHint}` : "else";
conditionalHintByIfBranch.set(branch, hint);
continue;
}
const condSource = getVueExpressionSource(cond, "content", "compiled");
const stable = tryExtractStableHintFromConditionalExpressionSource(condSource);
if (stable) {
conditionalHintByIfBranch.set(branch, stable);
lastHint = stable;
} else {
// Still set something so downstream code can distinguish the branch shape.
conditionalHintByIfBranch.set(branch, "if");
}
}
return;
}
// Only process element nodes
if (node.type !== NodeTypes.ELEMENT) {
return;
}
const actualFileName = `${componentName}.vue`;
if (previousFileName !== actualFileName) {
previousFileName = actualFileName;
hierarchyMap.clear();
}
const element = node as ElementNode;
const parentIsRoot = context?.parent?.type === NodeTypes.ROOT;
// Snapshot slot-scope callback usage before descendants are processed (and
// their @click handlers instrumented). Template nodes are entered before any
// of their children, so this runs at the right time.
if (element.tag === "template" && !slotScopeCallbackVariablesByTemplate.has(element)) {
const callbackVariables = getSlotScopeVariablesUsedAsBareCallbackHandlers(element);
if (callbackVariables.length > 0) {
slotScopeCallbackVariablesByTemplate.set(element, new Set(callbackVariables));
}
}
// When the immediate parent is a non-element wrapper (IF_BRANCH, FOR, IF),
// fall back to context.grandParent to maintain the element-to-element chain
// in the hierarchy map. This ensures slot-scope and v-for key detection can
// walk past v-if/v-for wrappers to find the enclosing <template> or v-for element.
const grandParent = (context as { grandParent?: { type?: number } }).grandParent;
const parentElement = (!parentIsRoot && context?.parent?.type === NodeTypes.ELEMENT)
? (context.parent as ElementNode)
: (!parentIsRoot && grandParent?.type === NodeTypes.ELEMENT)
? (grandParent as ElementNode)
: null;
hierarchyMap.set(element, parentElement);
// Convert any path (including Windows "C:\\..." and Vite /@fs/ paths) into a
// normalized POSIX-ish form so `path.posix.*` helpers behave predictably.
//
// NOTE: `path.resolve()` on Windows returns backslashes, and `path.posix.basename()`
// only treats '/' as a separator. If we don't normalize separators first, we can end
// up treating the entire absolute path as the "basename" and generating invalid
// identifiers like `export class C:\\Users\\...`.
const normalizeFilePath = (filePath: string) => path.normalize(safeRealpath(path.resolve(filePath)));
const normalizedFilePath = normalizeFilePath(context.filename);
const parentComponentName = componentName;
const dependencies = (() => {
let deps = componentHierarchyMap.get(componentName);
if (!deps) {
// Treat a component as a "view" when its .vue file is contained under viewsDir.
// This uses a real path containment check instead of substring matching.
const relToViewsDir = path.relative(normalizedViewsDirAbs, normalizedFilePath);
const isView = !relToViewsDir.startsWith("..") && !path.isAbsolute(relToViewsDir);
deps = {
filePath: context.filename,
childrenComponentSet: new Set<string>(),
usedComponentSet: new Set<string>(),
dataTestIdSet: new Set(),
componentInstances: [],
slotOutlets: [],
isView,
methodsContent: "",
};
componentHierarchyMap.set(componentName, deps);
}
return deps;
})();
const isComponentLikeTag = (tag: string) => {
// Vue component tags are typically PascalCase or kebab-case.
// - PascalCase: DxDataGrid
// - kebab-case: dx-data-grid
// HTML tags are lowercase and do not contain '-'.
if (!tag) return false;
const first = tag.charCodeAt(0);
const isUpper = isAsciiUppercaseLetterCode(first);
return isUpper || tag.includes("-");
};
if (element.tag === "slot") {
const slotName = getStaticAttributeContent(element, "name") ?? "default";
const target = getNearestComponentAncestor(element, hierarchyMap, isComponentLikeTag);
if (target) {
dependencies.slotOutlets ??= [];
const outlet = { name: slotName, targetSourceId: getElementSourceId(target) };
if (!dependencies.slotOutlets.some(existing => existing.name === outlet.name && existing.targetSourceId === outlet.targetSourceId)) {
dependencies.slotOutlets.push(outlet);
}
}
}
// Track all component-like tags used in the template, even when we do not emit a data-testid.
// This supports per-view helper attachment (e.g. Grid) based on component usage.
if (isComponentLikeTag(element.tag)) {
dependencies.usedComponentSet.add(element.tag);
// Cross-file key registry: if this component is inside a keyed slot scope,
// record which prop receives the slot data so the child can key its testids.
if (crossFileKeyRegistry && context.scopes.vSlot > 0) {
const findSlotTemplate = (): ElementNode | null => {
const gp = (context as { grandParent?: { type?: number; tag?: string } }).grandParent;
if (gp?.type === NodeTypes.ELEMENT && gp.tag === "template") {
return gp as ElementNode;
}
return getContainedInSlotTemplateNode(element, hierarchyMap);
};
const slotTemplate = findSlotTemplate();
if (slotTemplate) {
const slotScopeExpression = findTemplateSlotScopeExpression(slotTemplate);
if (slotScopeExpression) {
// Parse the slot scope to extract variable names (e.g. { data, key } → ["data", "key"])
const slotVarNames = tryExtractSlotScopeVariableNames(slotScopeExpression);
if (slotVarNames.length > 0) {
// Find a :prop="slotVar" binding where slotVar is one of the slot scope variables.
for (const prop of element.props) {
if (
prop.type === NodeTypes.DIRECTIVE
&& prop.name === "bind"
&& prop.arg?.type === NodeTypes.SIMPLE_EXPRESSION
&& prop.exp?.type === NodeTypes.SIMPLE_EXPRESSION
&& slotVarNames.includes(prop.exp.content)
) {
const propName = (prop.arg as SimpleExpressionNode).content;
crossFileKeyRegistry.set(element.tag, propName);
break;
}
}
}
}
}
}
}
// A reusable component's public test id belongs on the exact element that receives
// Vue fallthrough attributes. Do not generate a competing component-internal id on
// that target; continue traversing so unrelated internal controls still get POM APIs.
const ownWrapperContract = getWrapperContract(componentName);