Primeiro commit do projeto Angular

This commit is contained in:
2026-03-14 20:41:55 +00:00
parent 9bebe1de72
commit 94f4f46395
22413 changed files with 3221690 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Rule } from '@angular-devkit/schematics';
import { Schema } from './schema';
export default function (options: Schema): Rule;
+110
View File
@@ -0,0 +1,110 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
const schematics_1 = require("@angular-devkit/schematics");
const posix_1 = require("node:path/posix");
const workspace_1 = require("../../utility/workspace");
const test_file_transformer_1 = require("./test-file-transformer");
const refactor_reporter_1 = require("./utils/refactor-reporter");
async function getProject(tree, projectName) {
const workspace = await (0, workspace_1.getWorkspace)(tree);
if (projectName) {
const project = workspace.projects.get(projectName);
if (!project) {
throw new schematics_1.SchematicsException(`Project "${projectName}" not found.`);
}
return { project, name: projectName };
}
if (workspace.projects.size === 1) {
const [name, project] = Array.from(workspace.projects.entries())[0];
return { project, name };
}
const projectNames = Array.from(workspace.projects.keys());
throw new schematics_1.SchematicsException(`Multiple projects found: [${projectNames.join(', ')}]. Please specify a project name.`);
}
const DIRECTORIES_TO_SKIP = new Set(['node_modules', '.git', 'dist', '.angular']);
function findTestFiles(directory, fileSuffix) {
const files = [];
const stack = [directory];
let current;
while ((current = stack.pop())) {
for (const path of current.subfiles) {
if (path.endsWith(fileSuffix)) {
files.push(current.path + '/' + path);
}
}
for (const path of current.subdirs) {
if (DIRECTORIES_TO_SKIP.has(path)) {
continue;
}
stack.push(current.dir(path));
}
}
return files;
}
function default_1(options) {
return async (tree, context) => {
const reporter = new refactor_reporter_1.RefactorReporter(context.logger);
const { project, name: projectName } = await getProject(tree, options.project);
const projectRoot = project.root;
const fileSuffix = options.fileSuffix ?? '.spec.ts';
let files;
let searchScope;
if (options.include) {
const normalizedInclude = options.include.replace(/\\/g, '/');
const includePath = (0, posix_1.normalize)((0, posix_1.join)(projectRoot, normalizedInclude));
searchScope = options.include;
let dirEntry = null;
try {
dirEntry = tree.getDir(includePath);
}
catch {
// Path is not a directory.
}
// Approximation of a directory exists check
if (dirEntry && (dirEntry.subdirs.length > 0 || dirEntry.subfiles.length > 0)) {
// It is a directory
files = findTestFiles(dirEntry, fileSuffix);
}
else if (tree.exists(includePath)) {
// It is a file
files = [includePath];
}
else {
throw new schematics_1.SchematicsException(`The specified include path '${options.include}' does not exist.`);
}
}
else {
searchScope = `project '${projectName}'`;
files = findTestFiles(tree.getDir(projectRoot), fileSuffix);
}
if (files.length === 0) {
throw new schematics_1.SchematicsException(`No files ending with '${fileSuffix}' found in ${searchScope}.`);
}
for (const file of files) {
reporter.incrementScannedFiles();
const content = tree.readText(file);
const newContent = (0, test_file_transformer_1.transformJasmineToVitest)(file, content, reporter, {
addImports: !!options.addImports,
browserMode: !!options.browerMode,
});
if (content !== newContent) {
tree.overwrite(file, newContent);
reporter.incrementTransformedFiles();
}
}
if (options.report) {
const reportContent = reporter.generateReportContent();
tree.create(`jasmine-vitest-${new Date().toISOString().replaceAll(/[-:.]/g, '')}.md`, reportContent);
}
reporter.printSummary(options.verbose);
};
}
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAmEH,4BAqEC;AAtID,2DAMoC;AACpC,2CAAkD;AAClD,uDAA0E;AAE1E,mEAAmE;AACnE,iEAA6D;AAE7D,KAAK,UAAU,UAAU,CACvB,IAAU,EACV,WAA+B;IAE/B,MAAM,SAAS,GAAG,MAAM,IAAA,wBAAY,EAAC,IAAI,CAAC,CAAC;IAE3C,IAAI,WAAW,EAAE,CAAC;QAChB,MAAM,OAAO,GAAG,SAAS,C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BACjC,QAAQ,CAAC,yBAAyB,EAAE,CAAC;YACvC,CAAC;QACH,CAAC;QAED,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;YACnB,MAAM,aAAa,GAAG,QAAQ,CAAC,qBAAqB,EAAE,CAAC;YACvD,IAAI,CAAC,MAAM,CACT,kBAAkB,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,EAAE,CAAC,KAAK,EACxE,aAAa,CACd,CAAC;QACJ,CAAC;QAED,QAAQ,CAAC,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IACzC,CAAC,CAAC;AACJ,CAAC"}
+42
View File
@@ -0,0 +1,42 @@
/**
* Refactors a Jasmine test file to use Vitest.
*/
export type Schema = {
/**
* Whether to add imports for the Vitest API. The Angular `unit-test` system automatically
* uses the Vitest globals option, which means explicit imports for global APIs like
* `describe`, `it`, `expect`, and `vi` are often not strictly necessary unless Vitest has
* been configured not to use globals.
*/
addImports?: boolean;
/**
* Whether the tests are intended to run in browser mode. If true, the `toHaveClass`
* assertions are left as is because Vitest browser mode has such an assertion. Otherwise
* they're migrated to an equivalent assertion.
*/
browserMode?: boolean;
/**
* The file suffix to identify test files (e.g., '.spec.ts', '.test.ts').
*/
fileSuffix?: string;
/**
* A path to a specific file or directory to refactor. If not provided, all test files in
* the project will be refactored.
*/
include?: string;
/**
* The name of the project where the tests should be refactored. If not specified, the CLI
* will determine the project from the current directory.
*/
project?: string;
/**
* Whether to generate a summary report file (jasmine-vitest-<date>.md) in the project root.
*/
report?: boolean;
/**
* Enable verbose logging to see detailed information about the transformations being
* applied.
*/
verbose?: boolean;
[property: string]: any;
};
+5
View File
@@ -0,0 +1,5 @@
"use strict";
// THIS FILE IS AUTOMATICALLY GENERATED. TO UPDATE THIS FILE YOU NEED TO CHANGE THE
// CORRESPONDING JSON SCHEMA FILE, THEN RUN devkit-admin build (or bazel build ...).
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
{"version":3,"file":"schema.js","sourceRoot":"","sources":["schema.ts"],"names":[],"mappings":";AACA,mFAAmF;AACnF,oFAAoF"}
+45
View File
@@ -0,0 +1,45 @@
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "SchematicsAngularJasmineToVitest",
"title": "Angular Jasmine to Vitest Schematic",
"type": "object",
"description": "Refactors a Jasmine test file to use Vitest.",
"properties": {
"include": {
"type": "string",
"description": "A path to a specific file or directory to refactor. If not provided, all test files in the project will be refactored."
},
"fileSuffix": {
"type": "string",
"description": "The file suffix to identify test files (e.g., '.spec.ts', '.test.ts').",
"default": ".spec.ts"
},
"project": {
"type": "string",
"description": "The name of the project where the tests should be refactored. If not specified, the CLI will determine the project from the current directory.",
"$default": {
"$source": "projectName"
}
},
"verbose": {
"type": "boolean",
"description": "Enable verbose logging to see detailed information about the transformations being applied.",
"default": false
},
"addImports": {
"type": "boolean",
"description": "Whether to add imports for the Vitest API. The Angular `unit-test` system automatically uses the Vitest globals option, which means explicit imports for global APIs like `describe`, `it`, `expect`, and `vi` are often not strictly necessary unless Vitest has been configured not to use globals.",
"default": false
},
"browserMode": {
"type": "boolean",
"description": "Whether the tests are intended to run in browser mode. If true, the `toHaveClass` assertions are left as is because Vitest browser mode has such an assertion. Otherwise they're migrated to an equivalent assertion.",
"default": false
},
"report": {
"type": "boolean",
"description": "Whether to generate a summary report file (jasmine-vitest-<date>.md) in the project root.",
"default": true
}
}
}
@@ -0,0 +1,21 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { RefactorReporter } from './utils/refactor-reporter';
/**
* Transforms a string of Jasmine test code to Vitest test code.
* This is the main entry point for the transformation.
* @param filePath The path to the file being transformed.
* @param content The source code to transform.
* @param reporter The reporter to track TODOs.
* @param options Transformation options, including whether to add Vitest API imports.
* @returns The transformed code.
*/
export declare function transformJasmineToVitest(filePath: string, content: string, reporter: RefactorReporter, options: {
addImports: boolean;
browserMode: boolean;
}): string;
@@ -0,0 +1,209 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformJasmineToVitest = transformJasmineToVitest;
/**
* @fileoverview This is the main entry point for the Jasmine to Vitest transformation.
* It orchestrates the application of various AST transformers to convert Jasmine test
* syntax and APIs to their Vitest equivalents. It also handles import management,
* blank line preservation, and reporting of transformation details.
*/
const typescript_1 = __importDefault(require("../../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
const jasmine_lifecycle_1 = require("./transformers/jasmine-lifecycle");
const jasmine_matcher_1 = require("./transformers/jasmine-matcher");
const jasmine_misc_1 = require("./transformers/jasmine-misc");
const jasmine_spy_1 = require("./transformers/jasmine-spy");
const jasmine_type_1 = require("./transformers/jasmine-type");
const ast_helpers_1 = require("./utils/ast-helpers");
/**
* A placeholder used to temporarily replace blank lines in the source code.
* This is necessary because TypeScript's printer removes blank lines by default.
*/
const BLANK_LINE_PLACEHOLDER = '// __PRESERVE_BLANK_LINE__';
/**
* Vitest function names that should be imported when using the --add-imports option.
*/
const VITEST_FUNCTION_NAMES = new Set([
'describe',
'it',
'expect',
'beforeEach',
'afterEach',
'beforeAll',
'afterAll',
]);
/**
* Replaces blank lines in the content with a placeholder to prevent TypeScript's printer
* from removing them. This ensures that the original formatting of blank lines is preserved.
* @param content The source code content.
* @returns The content with blank lines replaced by placeholders.
*/
function preserveBlankLines(content) {
return content
.split('\n')
.map((line) => (line.trim() === '' ? BLANK_LINE_PLACEHOLDER : line))
.join('\n');
}
/**
* Restores blank lines in the content by replacing the placeholder with actual blank lines.
* This is called after TypeScript's printer has processed the file.
* @param content The content with blank line placeholders.
* @returns The content with blank lines restored.
*/
function restoreBlankLines(content) {
const regex = /^\s*\/\/ __PRESERVE_BLANK_LINE__\s*$/gm;
return content.replace(regex, '');
}
/**
* A collection of transformers that operate on `ts.CallExpression` nodes.
* These are applied in stages to ensure correct order of operations:
* 1. High-Level & Context-Sensitive: Transformations that fundamentally change the call.
* 2. Core Matcher & Spy: Bulk conversions for `expect(...)` and `spyOn(...)`.
* 3. Global Functions & Cleanup: Handles global Jasmine functions and unsupported APIs.
*/
const callExpressionTransformers = [
// **Stage 1: High-Level & Context-Sensitive Transformations**
// These transformers often wrap or fundamentally change the nature of the call,
// so they need to run before more specific matchers.
jasmine_matcher_1.transformWithContext,
jasmine_matcher_1.transformExpectAsync,
jasmine_lifecycle_1.transformFocusedAndSkippedTests,
jasmine_lifecycle_1.transformPending,
jasmine_lifecycle_1.transformDoneCallback,
// **Stage 2: Core Matcher & Spy Transformations**
// This is the bulk of the `expect(...)` and `spyOn(...)` conversions.
jasmine_matcher_1.transformSyntacticSugarMatchers,
jasmine_matcher_1.transformComplexMatchers,
jasmine_spy_1.transformSpies,
jasmine_spy_1.transformCreateSpyObj,
jasmine_spy_1.transformSpyReset,
jasmine_spy_1.transformSpyCallInspection,
jasmine_matcher_1.transformtoHaveBeenCalledBefore,
jasmine_matcher_1.transformToHaveClass,
// **Stage 3: Global Functions & Cleanup**
// These handle global Jasmine functions and catch-alls for unsupported APIs.
jasmine_misc_1.transformTimerMocks,
jasmine_misc_1.transformGlobalFunctions,
jasmine_misc_1.transformUnsupportedJasmineCalls,
];
/**
* A collection of transformers that operate on `ts.PropertyAccessExpression` nodes.
* These primarily handle `jasmine.any()` and other `jasmine.*` properties.
*/
const propertyAccessExpressionTransformers = [
// These transformers handle `jasmine.any()` and other `jasmine.*` properties.
jasmine_matcher_1.transformAsymmetricMatchers,
jasmine_spy_1.transformSpyCallInspection,
jasmine_misc_1.transformUnknownJasmineProperties,
];
/**
* A collection of transformers that operate on `ts.ExpressionStatement` nodes.
* These are mutually exclusive; the first one that matches will be applied.
*/
const expressionStatementTransformers = [
jasmine_matcher_1.transformCalledOnceWith,
jasmine_matcher_1.transformArrayWithExactContents,
jasmine_matcher_1.transformExpectNothing,
jasmine_misc_1.transformFail,
jasmine_misc_1.transformDefaultTimeoutInterval,
];
/**
* Transforms a string of Jasmine test code to Vitest test code.
* This is the main entry point for the transformation.
* @param filePath The path to the file being transformed.
* @param content The source code to transform.
* @param reporter The reporter to track TODOs.
* @param options Transformation options, including whether to add Vitest API imports.
* @returns The transformed code.
*/
function transformJasmineToVitest(filePath, content, reporter, options) {
const contentWithPlaceholders = preserveBlankLines(content);
const sourceFile = typescript_1.default.createSourceFile(filePath, contentWithPlaceholders, typescript_1.default.ScriptTarget.Latest, true, typescript_1.default.ScriptKind.TS);
const pendingVitestValueImports = new Set();
const pendingVitestTypeImports = new Set();
const transformer = (context) => {
const refactorCtx = {
sourceFile,
reporter,
tsContext: context,
pendingVitestValueImports,
pendingVitestTypeImports,
};
const visitor = (node) => {
let transformedNode = node;
// Transform the node itself based on its type
if (typescript_1.default.isCallExpression(transformedNode)) {
if (options.addImports && typescript_1.default.isIdentifier(transformedNode.expression)) {
const name = transformedNode.expression.text;
if (VITEST_FUNCTION_NAMES.has(name)) {
(0, ast_helpers_1.addVitestValueImport)(pendingVitestValueImports, name);
}
}
for (const transformer of callExpressionTransformers) {
if (!(options.browserMode && transformer === jasmine_matcher_1.transformToHaveClass)) {
transformedNode = transformer(transformedNode, refactorCtx);
}
}
}
else if (typescript_1.default.isPropertyAccessExpression(transformedNode)) {
for (const transformer of propertyAccessExpressionTransformers) {
transformedNode = transformer(transformedNode, refactorCtx);
}
}
else if (typescript_1.default.isExpressionStatement(transformedNode)) {
// Statement-level transformers are mutually exclusive. The first one that
// matches will be applied, and then the visitor will stop for this node.
for (const transformer of expressionStatementTransformers) {
const result = transformer(transformedNode, refactorCtx);
if (result !== transformedNode) {
transformedNode = result;
break;
}
}
}
else if (typescript_1.default.isQualifiedName(transformedNode) || typescript_1.default.isTypeReferenceNode(transformedNode)) {
transformedNode = (0, jasmine_type_1.transformJasmineTypes)(transformedNode, refactorCtx);
}
// Visit the children of the node to ensure they are transformed
if (Array.isArray(transformedNode)) {
return transformedNode.map((node) => typescript_1.default.visitEachChild(node, visitor, context));
}
else {
return typescript_1.default.visitEachChild(transformedNode, visitor, context);
}
};
return (node) => typescript_1.default.visitEachChild(node, visitor, context);
};
const result = typescript_1.default.transform(sourceFile, [transformer]);
let transformedSourceFile = result.transformed[0];
const hasPendingValueImports = pendingVitestValueImports.size > 0;
const hasPendingTypeImports = pendingVitestTypeImports.size > 0;
if (transformedSourceFile === sourceFile &&
!reporter.hasTodos &&
!hasPendingValueImports &&
!hasPendingTypeImports) {
return content;
}
if (hasPendingTypeImports || (options.addImports && hasPendingValueImports)) {
const vitestImport = (0, ast_helpers_1.getVitestAutoImports)(options.addImports ? pendingVitestValueImports : new Set(), pendingVitestTypeImports);
if (vitestImport) {
transformedSourceFile = typescript_1.default.factory.updateSourceFile(transformedSourceFile, [
vitestImport,
...transformedSourceFile.statements,
]);
}
}
const printer = typescript_1.default.createPrinter();
const transformedContentWithPlaceholders = printer.printFile(transformedSourceFile);
return restoreBlankLines(transformedContentWithPlaceholders);
}
//# sourceMappingURL=test-file-transformer.js.map
@@ -0,0 +1 @@
{"version":3,"file":"test-file-transformer.js","sourceRoot":"","sources":["test-file-transformer.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;;;AA6JH,4DA0GC;AArQD;;;;;GAKG;AAEH,kHAAkF;AAClF,wEAI0C;AAC1C,oEAWwC;AACxC,8DAOqC;AACrC,4DAKoC;AACpC,8DAAoE;AACpE,qDAAiF;AAIjF;;;GAGG;AACH,MAAM,sBAAsB,GAAG,4BAA4B,CAAC;AAE5D;;GAEG;AACH,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC;IACpC,UAAU;IACV,IAAI;IACJ,QAAQ;IACR,YAAY;IACZ,WAAW;IACX,WAAW;IACX,UAAU;CACX,CAAC,CAAC;AAEH;;;;;G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AAI,qBAAqB,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;IAElD,MAAM,sBAAsB,GAAG,yBAAyB,CAAC,IAAI,GAAG,CAAC,CAAC;IAClE,MAAM,qBAAqB,GAAG,wBAAwB,CAAC,IAAI,GAAG,CAAC,CAAC;IAEhE,IACE,qBAAqB,KAAK,UAAU;QACpC,CAAC,QAAQ,CAAC,QAAQ;QAClB,CAAC,sBAAsB;QACvB,CAAC,qBAAqB,EACtB,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,IAAI,qBAAqB,IAAI,CAAC,OAAO,CAAC,UAAU,IAAI,sBAAsB,CAAC,EAAE,CAAC;QAC5E,MAAM,YAAY,GAAG,IAAA,kCAAoB,EACvC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,yBAAyB,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,EAC1D,wBAAwB,CACzB,CAAC;QACF,IAAI,YAAY,EAAE,CAAC;YACjB,qBAAqB,GAAG,oBAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,qBAAqB,EAAE;gBACzE,YAAY;gBACZ,GAAG,qBAAqB,CAAC,UAAU;aACpC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,MAAM,OAAO,GAAG,oBAAE,CAAC,aAAa,EAAE,CAAC;IACnC,MAAM,kCAAkC,GAAG,OAAO,CAAC,SAAS,CAAC,qBAAqB,CAAC,CAAC;IAEpF,OAAO,iBAAiB,CAAC,kCAAkC,CAAC,CAAC;AAC/D,CAAC"}
@@ -0,0 +1,18 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @fileoverview This file contains transformers that convert Jasmine lifecycle functions
* and test setup/teardown patterns to their Vitest equivalents. This includes handling
* focused/skipped tests (fdescribe, fit, xdescribe, xit), pending tests, and asynchronous
* operations that use the `done` callback.
*/
import ts from '../../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
import { RefactorContext } from '../utils/refactor-context';
export declare function transformFocusedAndSkippedTests(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
export declare function transformPending(node: ts.Node, { sourceFile, reporter, tsContext }: RefactorContext): ts.Node;
export declare function transformDoneCallback(node: ts.Node, refactorCtx: RefactorContext): ts.Node;
@@ -0,0 +1,276 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformFocusedAndSkippedTests = transformFocusedAndSkippedTests;
exports.transformPending = transformPending;
exports.transformDoneCallback = transformDoneCallback;
/**
* @fileoverview This file contains transformers that convert Jasmine lifecycle functions
* and test setup/teardown patterns to their Vitest equivalents. This includes handling
* focused/skipped tests (fdescribe, fit, xdescribe, xit), pending tests, and asynchronous
* operations that use the `done` callback.
*/
const typescript_1 = __importDefault(require("../../../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
const ast_helpers_1 = require("../utils/ast-helpers");
const comment_helpers_1 = require("../utils/comment-helpers");
const FOCUSED_SKIPPED_RENAMES = new Map([
['fdescribe', { newBase: 'describe', newName: 'only' }],
['fit', { newBase: 'it', newName: 'only' }],
['xdescribe', { newBase: 'describe', newName: 'skip' }],
['xit', { newBase: 'it', newName: 'skip' }],
]);
function transformFocusedAndSkippedTests(node, { sourceFile, reporter }) {
if (!typescript_1.default.isCallExpression(node) || !typescript_1.default.isIdentifier(node.expression)) {
return node;
}
const oldName = node.expression.text;
const rename = FOCUSED_SKIPPED_RENAMES.get(oldName);
if (rename) {
reporter.reportTransformation(sourceFile, node, `Transformed \`${oldName}\` to \`${rename.newBase}.${rename.newName}\`.`);
const newPropAccess = (0, ast_helpers_1.createPropertyAccess)(rename.newBase, rename.newName);
return typescript_1.default.factory.updateCallExpression(node, newPropAccess, node.typeArguments, node.arguments);
}
return node;
}
function transformPending(node, { sourceFile, reporter, tsContext }) {
if (!typescript_1.default.isCallExpression(node) ||
!typescript_1.default.isIdentifier(node.expression) ||
node.expression.text !== 'it') {
return node;
}
const testFn = node.arguments[1];
if (!testFn || (!typescript_1.default.isArrowFunction(testFn) && !typescript_1.default.isFunctionExpression(testFn))) {
return node;
}
let hasPending = false;
const bodyTransformVisitor = (bodyNode) => {
if (typescript_1.default.isExpressionStatement(bodyNode) &&
typescript_1.default.isCallExpression(bodyNode.expression) &&
typescript_1.default.isIdentifier(bodyNode.expression.expression) &&
bodyNode.expression.expression.text === 'pending') {
hasPending = true;
const replacement = typescript_1.default.factory.createEmptyStatement();
const originalText = bodyNode.getFullText().trim();
reporter.reportTransformation(sourceFile, bodyNode, 'Converted `pending()` to a skipped test (`it.skip`).');
const category = 'pending';
reporter.recordTodo(category, sourceFile, bodyNode);
(0, comment_helpers_1.addTodoComment)(replacement, category);
typescript_1.default.addSyntheticLeadingComment(replacement, typescript_1.default.SyntaxKind.SingleLineCommentTrivia, ` ${originalText}`, true);
return replacement;
}
return typescript_1.default.visitEachChild(bodyNode, bodyTransformVisitor, tsContext);
};
const newBody = typescript_1.default.visitNode(testFn.body, bodyTransformVisitor);
if (!hasPending) {
return node;
}
const newExpression = (0, ast_helpers_1.createPropertyAccess)(node.expression, 'skip');
const newTestFn = typescript_1.default.isArrowFunction(testFn)
? typescript_1.default.factory.updateArrowFunction(testFn, testFn.modifiers, testFn.typeParameters, testFn.parameters, testFn.type, testFn.equalsGreaterThanToken, newBody ?? typescript_1.default.factory.createBlock([]))
: typescript_1.default.factory.updateFunctionExpression(testFn, testFn.modifiers, testFn.asteriskToken, testFn.name, testFn.typeParameters, testFn.parameters, testFn.type, newBody ?? typescript_1.default.factory.createBlock([]));
const newArgs = [node.arguments[0], newTestFn, ...node.arguments.slice(2)];
return typescript_1.default.factory.updateCallExpression(node, newExpression, node.typeArguments, newArgs);
}
function transformComplexDoneCallback(node, doneIdentifier, refactorCtx) {
const { sourceFile, reporter } = refactorCtx;
if (!typescript_1.default.isExpressionStatement(node) ||
!typescript_1.default.isCallExpression(node.expression) ||
!typescript_1.default.isPropertyAccessExpression(node.expression.expression)) {
return node;
}
const call = node.expression;
const pae = call.expression;
if (!typescript_1.default.isPropertyAccessExpression(pae)) {
return node;
}
if (pae.name.text !== 'then' || call.arguments.length !== 1) {
return node;
}
const thenCallback = call.arguments[0];
if (!typescript_1.default.isArrowFunction(thenCallback) && !typescript_1.default.isFunctionExpression(thenCallback)) {
return node;
}
// Re-create the .then() call but with a modified callback that has `done()` removed.
const thenCallbackBody = typescript_1.default.isBlock(thenCallback.body)
? thenCallback.body
: typescript_1.default.factory.createBlock([typescript_1.default.factory.createExpressionStatement(thenCallback.body)]);
const newStatements = thenCallbackBody.statements.filter((stmt) => {
return (!typescript_1.default.isExpressionStatement(stmt) ||
!typescript_1.default.isCallExpression(stmt.expression) ||
!typescript_1.default.isIdentifier(stmt.expression.expression) ||
stmt.expression.expression.text !== doneIdentifier.text);
});
if (newStatements.length === thenCallbackBody.statements.length) {
// No "done()" call was removed, so don't transform.
return node;
}
reporter.reportTransformation(sourceFile, node, 'Transformed promise `.then()` with `done()` to `await`.');
const newThenCallback = typescript_1.default.isArrowFunction(thenCallback)
? typescript_1.default.factory.updateArrowFunction(thenCallback, thenCallback.modifiers, thenCallback.typeParameters, thenCallback.parameters, thenCallback.type, thenCallback.equalsGreaterThanToken, typescript_1.default.factory.updateBlock(thenCallbackBody, newStatements))
: typescript_1.default.factory.updateFunctionExpression(thenCallback, thenCallback.modifiers, thenCallback.asteriskToken, thenCallback.name, thenCallback.typeParameters, thenCallback.parameters, thenCallback.type, typescript_1.default.factory.updateBlock(thenCallbackBody, newStatements));
const newCall = typescript_1.default.factory.updateCallExpression(call, call.expression, call.typeArguments, [
newThenCallback,
]);
return typescript_1.default.factory.createExpressionStatement(typescript_1.default.factory.createAwaitExpression(newCall));
}
function transformPromiseBasedDone(callExpr, doneIdentifier, refactorCtx) {
const { sourceFile, reporter } = refactorCtx;
if (typescript_1.default.isPropertyAccessExpression(callExpr.expression) &&
(callExpr.expression.name.text === 'then' || callExpr.expression.name.text === 'catch')) {
const promiseHandler = callExpr.arguments[0];
if (promiseHandler) {
let isDoneHandler = false;
// promise.then(done)
if (typescript_1.default.isIdentifier(promiseHandler) && promiseHandler.text === doneIdentifier.text) {
isDoneHandler = true;
}
// promise.catch(done.fail)
if (typescript_1.default.isPropertyAccessExpression(promiseHandler) &&
typescript_1.default.isIdentifier(promiseHandler.expression) &&
promiseHandler.expression.text === doneIdentifier.text &&
promiseHandler.name.text === 'fail') {
isDoneHandler = true;
}
// promise.then(() => done())
if (typescript_1.default.isArrowFunction(promiseHandler) && !promiseHandler.parameters.length) {
const body = promiseHandler.body;
if (typescript_1.default.isCallExpression(body) &&
typescript_1.default.isIdentifier(body.expression) &&
body.expression.text === doneIdentifier.text) {
isDoneHandler = true;
}
if (typescript_1.default.isBlock(body) && body.statements.length === 1) {
const stmt = body.statements[0];
if (typescript_1.default.isExpressionStatement(stmt) &&
typescript_1.default.isCallExpression(stmt.expression) &&
typescript_1.default.isIdentifier(stmt.expression.expression) &&
stmt.expression.expression.text === doneIdentifier.text) {
isDoneHandler = true;
}
}
}
if (isDoneHandler) {
reporter.reportTransformation(sourceFile, callExpr, 'Transformed promise `.then(done)` to `await`.');
return typescript_1.default.factory.createExpressionStatement(typescript_1.default.factory.createAwaitExpression(callExpr.expression.expression));
}
}
}
return undefined;
}
function countDoneUsages(node, doneIdentifier) {
let count = 0;
const visitor = (n) => {
if (typescript_1.default.isIdentifier(n) && n.text === doneIdentifier.text) {
count++;
}
typescript_1.default.forEachChild(n, visitor);
};
typescript_1.default.forEachChild(node, visitor);
return count;
}
function transformDoneCallback(node, refactorCtx) {
const { sourceFile, reporter, tsContext } = refactorCtx;
if (!typescript_1.default.isCallExpression(node) ||
!typescript_1.default.isIdentifier(node.expression) ||
!['it', 'beforeEach', 'afterEach', 'beforeAll', 'afterAll'].includes(node.expression.text)) {
return node;
}
const functionArg = node.arguments.find((arg) => typescript_1.default.isArrowFunction(arg) || typescript_1.default.isFunctionExpression(arg));
if (!functionArg || (!typescript_1.default.isArrowFunction(functionArg) && !typescript_1.default.isFunctionExpression(functionArg))) {
return node;
}
if (functionArg.parameters.length !== 1) {
return node;
}
const doneParam = functionArg.parameters[0];
if (!typescript_1.default.isIdentifier(doneParam.name)) {
return node;
}
const doneIdentifier = doneParam.name;
// Count total usages of 'done' in the body
const totalUsages = countDoneUsages(functionArg.body, doneIdentifier);
let handledUsages = 0;
let doneWasUsed = false;
const bodyVisitor = (bodyNode) => {
const complexTransformed = transformComplexDoneCallback(bodyNode, doneIdentifier, refactorCtx);
if (complexTransformed !== bodyNode) {
doneWasUsed = true;
handledUsages++; // complex transform handles one usage
return complexTransformed;
}
if (typescript_1.default.isExpressionStatement(bodyNode) && typescript_1.default.isCallExpression(bodyNode.expression)) {
const callExpr = bodyNode.expression;
// Transform `done.fail('message')` to `throw new Error('message')`
if (typescript_1.default.isPropertyAccessExpression(callExpr.expression) &&
typescript_1.default.isIdentifier(callExpr.expression.expression) &&
callExpr.expression.expression.text === doneIdentifier.text &&
callExpr.expression.name.text === 'fail') {
doneWasUsed = true;
handledUsages++;
reporter.reportTransformation(sourceFile, bodyNode, 'Transformed `done.fail()` to `throw new Error()`.');
const errorArgs = callExpr.arguments.length > 0 ? [callExpr.arguments[0]] : [];
return typescript_1.default.factory.createThrowStatement(typescript_1.default.factory.createNewExpression(typescript_1.default.factory.createIdentifier('Error'), undefined, errorArgs));
}
// Transform `promise.then(done)` or `promise.catch(done.fail)` to `await promise`
const promiseTransformed = transformPromiseBasedDone(callExpr, doneIdentifier, refactorCtx);
if (promiseTransformed) {
doneWasUsed = true;
handledUsages++;
return promiseTransformed;
}
// Remove `done()`
if (typescript_1.default.isIdentifier(callExpr.expression) &&
callExpr.expression.text === doneIdentifier.text) {
doneWasUsed = true;
handledUsages++;
return typescript_1.default.setTextRange(typescript_1.default.factory.createEmptyStatement(), callExpr.expression);
}
}
return typescript_1.default.visitEachChild(bodyNode, bodyVisitor, tsContext);
};
const newBody = typescript_1.default.visitNode(functionArg.body, (node) => {
if (typescript_1.default.isBlock(node)) {
const newStatements = node.statements.flatMap((stmt) => bodyVisitor(stmt));
return typescript_1.default.factory.updateBlock(node, newStatements.filter((s) => !!s));
}
return bodyVisitor(node);
});
// Safety check: if we found usages but didn't handle all of them, abort.
if (handledUsages < totalUsages) {
reporter.reportTransformation(sourceFile, node, `Found unhandled usage of \`${doneIdentifier.text}\` callback. Skipping transformation.`);
const category = 'unhandled-done-usage';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(node, category);
return node;
}
if (!doneWasUsed) {
return node;
}
reporter.reportTransformation(sourceFile, node, `Converted test with \`done\` callback to an \`async\` test.`);
const newModifiers = [
typescript_1.default.factory.createModifier(typescript_1.default.SyntaxKind.AsyncKeyword),
...(typescript_1.default.getModifiers(functionArg) ?? []).filter((mod) => mod.kind !== typescript_1.default.SyntaxKind.AsyncKeyword),
];
let newFunction;
if (typescript_1.default.isArrowFunction(functionArg)) {
newFunction = typescript_1.default.factory.updateArrowFunction(functionArg, newModifiers, functionArg.typeParameters, [], // remove parameters
functionArg.type, functionArg.equalsGreaterThanToken, newBody ?? typescript_1.default.factory.createBlock([]));
}
else {
// isFunctionExpression
newFunction = typescript_1.default.factory.updateFunctionExpression(functionArg, newModifiers, functionArg.asteriskToken, functionArg.name, functionArg.typeParameters, [], // remove parameters
functionArg.type, newBody ?? typescript_1.default.factory.createBlock([]));
}
const newArgs = node.arguments.map((arg) => (arg === functionArg ? newFunction : arg));
return typescript_1.default.factory.updateCallExpression(node, node.expression, node.typeArguments, newArgs);
}
//# sourceMappingURL=jasmine-lifecycle.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,26 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @fileoverview This file contains transformers that migrate Jasmine matchers to their
* Vitest counterparts. It handles a wide range of matchers, including syntactic sugar
* (e.g., `toBeTrue`), asymmetric matchers (e.g., `jasmine.any`), async promise matchers
* (`expectAsync`), and complex matchers that require restructuring, such as
* `toHaveBeenCalledOnceWith` and `arrayWithExactContents`.
*/
import ts from '../../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
import { RefactorContext } from '../utils/refactor-context';
export declare function transformSyntacticSugarMatchers(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
export declare function transformAsymmetricMatchers(node: ts.Node, { sourceFile, reporter, pendingVitestValueImports }: RefactorContext): ts.Node;
export declare function transformtoHaveBeenCalledBefore(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
export declare function transformToHaveClass(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
export declare function transformExpectAsync(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
export declare function transformComplexMatchers(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
export declare function transformArrayWithExactContents(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node | readonly ts.Node[];
export declare function transformCalledOnceWith(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node | readonly ts.Node[];
export declare function transformWithContext(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
export declare function transformExpectNothing(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
@@ -0,0 +1,401 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformSyntacticSugarMatchers = transformSyntacticSugarMatchers;
exports.transformAsymmetricMatchers = transformAsymmetricMatchers;
exports.transformtoHaveBeenCalledBefore = transformtoHaveBeenCalledBefore;
exports.transformToHaveClass = transformToHaveClass;
exports.transformExpectAsync = transformExpectAsync;
exports.transformComplexMatchers = transformComplexMatchers;
exports.transformArrayWithExactContents = transformArrayWithExactContents;
exports.transformCalledOnceWith = transformCalledOnceWith;
exports.transformWithContext = transformWithContext;
exports.transformExpectNothing = transformExpectNothing;
/**
* @fileoverview This file contains transformers that migrate Jasmine matchers to their
* Vitest counterparts. It handles a wide range of matchers, including syntactic sugar
* (e.g., `toBeTrue`), asymmetric matchers (e.g., `jasmine.any`), async promise matchers
* (`expectAsync`), and complex matchers that require restructuring, such as
* `toHaveBeenCalledOnceWith` and `arrayWithExactContents`.
*/
const typescript_1 = __importDefault(require("../../../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
const ast_helpers_1 = require("../utils/ast-helpers");
const ast_validation_1 = require("../utils/ast-validation");
const comment_helpers_1 = require("../utils/comment-helpers");
const SUGAR_MATCHER_CHANGES = new Map([
['toBeTrue', { newName: 'toBe', newArgs: [typescript_1.default.factory.createTrue()] }],
['toBeFalse', { newName: 'toBe', newArgs: [typescript_1.default.factory.createFalse()] }],
['toBePositiveInfinity', { newName: 'toBe', newArgs: [typescript_1.default.factory.createIdentifier('Infinity')] }],
[
'toBeNegativeInfinity',
{
newName: 'toBe',
newArgs: [
typescript_1.default.factory.createPrefixUnaryExpression(typescript_1.default.SyntaxKind.MinusToken, typescript_1.default.factory.createIdentifier('Infinity')),
],
},
],
['toHaveSize', { newName: 'toHaveLength' }],
]);
function transformSyntacticSugarMatchers(node, { sourceFile, reporter }) {
if (!typescript_1.default.isCallExpression(node) || !typescript_1.default.isPropertyAccessExpression(node.expression)) {
return node;
}
const pae = node.expression;
const matcherName = pae.name.text;
if (matcherName === 'toHaveSpyInteractions') {
const category = 'toHaveSpyInteractions';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(node, category);
return node;
}
if (matcherName === 'toThrowMatching') {
const category = 'toThrowMatching';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(node, category, { name: matcherName });
return node;
}
const mapping = SUGAR_MATCHER_CHANGES.get(matcherName);
if (mapping) {
reporter.reportTransformation(sourceFile, node, `Transformed matcher ".${matcherName}()" to ".${mapping.newName}()".`);
const newExpression = (0, ast_helpers_1.createPropertyAccess)(pae.expression, mapping.newName);
const newArgs = mapping.newArgs ?? [...node.arguments];
return typescript_1.default.factory.updateCallExpression(node, newExpression, node.typeArguments, newArgs);
}
return node;
}
const ASYMMETRIC_MATCHER_NAMES = [
'anything',
'any',
'stringMatching',
'objectContaining',
'arrayContaining',
'stringContaining',
];
function transformAsymmetricMatchers(node, { sourceFile, reporter, pendingVitestValueImports }) {
if (typescript_1.default.isPropertyAccessExpression(node) &&
typescript_1.default.isIdentifier(node.expression) &&
node.expression.text === 'jasmine') {
const matcherName = node.name.text;
if (ASYMMETRIC_MATCHER_NAMES.includes(matcherName)) {
(0, ast_helpers_1.addVitestValueImport)(pendingVitestValueImports, 'expect');
reporter.reportTransformation(sourceFile, node, `Transformed asymmetric matcher \`jasmine.${matcherName}\` to \`expect.${matcherName}\`.`);
return (0, ast_helpers_1.createPropertyAccess)('expect', node.name);
}
}
return node;
}
function transformtoHaveBeenCalledBefore(node, { sourceFile, reporter }) {
if (!typescript_1.default.isCallExpression(node) ||
!typescript_1.default.isPropertyAccessExpression(node.expression) ||
node.arguments.length !== 1) {
return node;
}
const pae = node.expression;
const matcherName = pae.name.text;
let isNegated = false;
let expectExpression = pae.expression;
if (typescript_1.default.isPropertyAccessExpression(expectExpression) && expectExpression.name.text === 'not') {
isNegated = true;
expectExpression = expectExpression.expression;
}
if (!typescript_1.default.isCallExpression(expectExpression) || matcherName !== 'toHaveBeenCalledBefore') {
return node;
}
reporter.reportTransformation(sourceFile, node, 'Transformed `toHaveBeenCalledBefore` to a Vitest-compatible spy invocation order comparison.');
const [spyB] = node.arguments;
const [spyA] = expectExpression.arguments;
const createInvocationOrderAccess = (spyIdentifier) => {
const mockedSpy = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)('vi', 'mocked'), undefined, [spyIdentifier]);
const mockProperty = (0, ast_helpers_1.createPropertyAccess)(mockedSpy, 'mock');
return (0, ast_helpers_1.createPropertyAccess)(mockProperty, 'invocationCallOrder');
};
const createMinCall = (spyIdentifier) => {
return typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)('Math', 'min'), undefined, [
typescript_1.default.factory.createSpreadElement(createInvocationOrderAccess(spyIdentifier)),
]);
};
const newExpect = (0, ast_helpers_1.createExpectCallExpression)([createMinCall(spyA)]);
const newMatcherName = isNegated ? 'toBeGreaterThanOrEqual' : 'toBeLessThan';
return typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(newExpect, newMatcherName), undefined, [createMinCall(spyB)]);
}
function transformToHaveClass(node, { sourceFile, reporter }) {
if (!typescript_1.default.isCallExpression(node) ||
!typescript_1.default.isPropertyAccessExpression(node.expression) ||
node.arguments.length !== 1) {
return node;
}
const pae = node.expression;
const matcherName = pae.name.text;
let isNegated = false;
let expectExpression = pae.expression;
if (typescript_1.default.isPropertyAccessExpression(expectExpression) && expectExpression.name.text === 'not') {
isNegated = true;
expectExpression = expectExpression.expression;
}
if (matcherName !== 'toHaveClass') {
return node;
}
reporter.reportTransformation(sourceFile, node, 'Transformed `.toHaveClass()` to a `classList.contains()` check.');
const [className] = node.arguments;
const newExpectArgs = [];
if (typescript_1.default.isCallExpression(expectExpression)) {
const [element] = expectExpression.arguments;
const classListContains = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)((0, ast_helpers_1.createPropertyAccess)(element, 'classList'), 'contains'), undefined, [className]);
newExpectArgs.push(classListContains);
// Pass the context message from withContext to the new expect call
if (expectExpression.arguments.length > 1) {
newExpectArgs.push(expectExpression.arguments[1]);
}
}
else {
return node;
}
const newExpect = (0, ast_helpers_1.createExpectCallExpression)(newExpectArgs);
const newMatcher = isNegated ? typescript_1.default.factory.createFalse() : typescript_1.default.factory.createTrue();
return typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(newExpect, 'toBe'), undefined, [
newMatcher,
]);
}
const ASYNC_MATCHER_CHANGES = new Map([
['toBeResolved', { base: 'resolves', matcher: 'toThrow', not: true, keepArgs: false }],
['toBeResolvedTo', { base: 'resolves', matcher: 'toEqual', keepArgs: true }],
['toBeRejected', { base: 'rejects', matcher: 'toThrow', keepArgs: false }],
['toBeRejectedWith', { base: 'rejects', matcher: 'toEqual', keepArgs: true }],
['toBeRejectedWithError', { base: 'rejects', matcher: 'toThrowError', keepArgs: true }],
]);
function transformExpectAsync(node, { sourceFile, reporter }) {
if (!typescript_1.default.isCallExpression(node) ||
!typescript_1.default.isPropertyAccessExpression(node.expression) ||
!typescript_1.default.isCallExpression(node.expression.expression)) {
return node;
}
const matcherCall = node;
const matcherPae = node.expression;
const expectCall = node.expression.expression;
if (!typescript_1.default.isIdentifier(expectCall.expression) || expectCall.expression.text !== 'expectAsync') {
return node;
}
const matcherName = typescript_1.default.isIdentifier(matcherPae.name) ? matcherPae.name.text : undefined;
const mapping = matcherName ? ASYNC_MATCHER_CHANGES.get(matcherName) : undefined;
if (mapping) {
reporter.reportTransformation(sourceFile, node, `Transformed \`expectAsync(...).${matcherName}\` to \`expect(...).${mapping.base}.${mapping.matcher}\`.`);
const newExpectCall = (0, ast_helpers_1.createExpectCallExpression)([expectCall.arguments[0]]);
let newMatcherChain = (0, ast_helpers_1.createPropertyAccess)(newExpectCall, mapping.base);
if (mapping.not) {
newMatcherChain = (0, ast_helpers_1.createPropertyAccess)(newMatcherChain, 'not');
}
newMatcherChain = (0, ast_helpers_1.createPropertyAccess)(newMatcherChain, mapping.matcher);
const newMatcherArgs = mapping.keepArgs ? [...matcherCall.arguments] : [];
return typescript_1.default.factory.createCallExpression(newMatcherChain, undefined, newMatcherArgs);
}
if (matcherName) {
if (matcherName === 'toBePending') {
const category = 'toBePending';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(node, category);
}
else {
const category = 'unsupported-expect-async-matcher';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(node, category, { name: matcherName });
}
}
return node;
}
function transformComplexMatchers(node, { sourceFile, reporter }) {
if (!typescript_1.default.isCallExpression(node) ||
!typescript_1.default.isPropertyAccessExpression(node.expression) ||
node.expression.name.text !== 'toEqual' ||
node.arguments.length !== 1) {
return node;
}
const argument = node.arguments[0];
const jasmineMatcherName = (0, ast_validation_1.getJasmineMethodName)(argument);
if (!jasmineMatcherName) {
return node;
}
const expectCall = node.expression.expression;
let newMatcherName;
let newArgs;
let negate = false;
switch (jasmineMatcherName) {
case 'truthy':
newMatcherName = 'toBeTruthy';
break;
case 'falsy':
newMatcherName = 'toBeFalsy';
break;
case 'empty':
newMatcherName = 'toHaveLength';
newArgs = [typescript_1.default.factory.createNumericLiteral(0)];
break;
case 'notEmpty':
newMatcherName = 'toHaveLength';
newArgs = [typescript_1.default.factory.createNumericLiteral(0)];
negate = true;
break;
case 'is':
newMatcherName = 'toBe';
if (typescript_1.default.isCallExpression(argument)) {
newArgs = [...argument.arguments];
}
break;
}
if (newMatcherName) {
reporter.reportTransformation(sourceFile, node, `Transformed \`.toEqual(jasmine.${jasmineMatcherName}())\` to \`.${newMatcherName}()\`.`);
let expectExpression = expectCall;
// Handle cases like `expect(...).not.toEqual(jasmine.notEmpty())`
if (typescript_1.default.isPropertyAccessExpression(expectCall) && expectCall.name.text === 'not') {
// The original expression was negated, so flip the negate flag
negate = !negate;
// Use the expression before the `.not`
expectExpression = expectCall.expression;
}
if (negate) {
expectExpression = (0, ast_helpers_1.createPropertyAccess)(expectExpression, 'not');
}
const newExpression = (0, ast_helpers_1.createPropertyAccess)(expectExpression, newMatcherName);
return typescript_1.default.factory.createCallExpression(newExpression, undefined, newArgs ?? []);
}
return node;
}
function transformArrayWithExactContents(node, { sourceFile, reporter }) {
if (!typescript_1.default.isExpressionStatement(node) ||
!typescript_1.default.isCallExpression(node.expression) ||
!typescript_1.default.isPropertyAccessExpression(node.expression.expression) ||
node.expression.expression.name.text !== 'toEqual' ||
node.expression.arguments.length !== 1) {
return node;
}
const argument = node.expression.arguments[0];
if (!(0, ast_validation_1.isJasmineCallExpression)(argument, 'arrayWithExactContents') ||
argument.arguments.length !== 1) {
return node;
}
if (!typescript_1.default.isArrayLiteralExpression(argument.arguments[0])) {
const category = 'arrayWithExactContents-dynamic-variable';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(node, category);
return node;
}
reporter.reportTransformation(sourceFile, node, 'Transformed `jasmine.arrayWithExactContents()` to `.toHaveLength()` and `.toEqual(expect.arrayContaining())`.');
const expectCall = node.expression.expression.expression;
const arrayLiteral = argument.arguments[0];
const lengthCall = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(expectCall, 'toHaveLength'), undefined, [typescript_1.default.factory.createNumericLiteral(arrayLiteral.elements.length)]);
const containingCall = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(expectCall, 'toEqual'), undefined, [
typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)('expect', 'arrayContaining'), undefined, [arrayLiteral]),
]);
const lengthStmt = typescript_1.default.factory.createExpressionStatement(lengthCall);
const containingStmt = typescript_1.default.factory.createExpressionStatement(containingCall);
const category = 'arrayWithExactContents-check';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(lengthStmt, category);
return [lengthStmt, containingStmt];
}
function transformCalledOnceWith(node, { sourceFile, reporter }) {
if (!typescript_1.default.isExpressionStatement(node)) {
return node;
}
const call = node.expression;
if (!typescript_1.default.isCallExpression(call) ||
!typescript_1.default.isPropertyAccessExpression(call.expression) ||
call.expression.name.text !== 'toHaveBeenCalledOnceWith') {
return node;
}
reporter.reportTransformation(sourceFile, node, 'Transformed `.toHaveBeenCalledOnceWith()` to `.toHaveBeenCalledTimes(1)` and `.toHaveBeenCalledWith()`.');
const expectCall = call.expression.expression;
const args = call.arguments;
const timesCall = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(expectCall, 'toHaveBeenCalledTimes'), undefined, [typescript_1.default.factory.createNumericLiteral(1)]);
const withCall = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(expectCall, 'toHaveBeenCalledWith'), undefined, args);
return [
typescript_1.default.factory.createExpressionStatement(timesCall),
typescript_1.default.factory.createExpressionStatement(withCall),
];
}
function transformWithContext(node, { sourceFile, reporter }) {
if (!typescript_1.default.isCallExpression(node) || !typescript_1.default.isPropertyAccessExpression(node.expression)) {
return node;
}
// Traverse the chain of property access expressions to find the .withContext() call
let currentExpression = node.expression;
const propertyChain = [];
while (typescript_1.default.isPropertyAccessExpression(currentExpression)) {
if (!typescript_1.default.isIdentifier(currentExpression.name)) {
// Break if we encounter a private identifier or something else unexpected
return node;
}
propertyChain.push(currentExpression.name);
currentExpression = currentExpression.expression;
}
const withContextCall = currentExpression;
// Check if we found a .withContext() call
if (!typescript_1.default.isCallExpression(withContextCall) ||
!typescript_1.default.isPropertyAccessExpression(withContextCall.expression) ||
!typescript_1.default.isIdentifier(withContextCall.expression.name) ||
withContextCall.expression.name.text !== 'withContext') {
return node;
}
reporter.reportTransformation(sourceFile, withContextCall, 'Transformed `.withContext()` to the `expect(..., message)` syntax.');
const expectCall = withContextCall.expression.expression;
if (!typescript_1.default.isCallExpression(expectCall) ||
!typescript_1.default.isIdentifier(expectCall.expression) ||
expectCall.expression.text !== 'expect') {
return node;
}
const contextMessage = withContextCall.arguments[0];
if (!contextMessage) {
// No message provided, so unwrap the .withContext() call.
let newChain = expectCall;
for (let i = propertyChain.length - 1; i >= 0; i--) {
newChain = typescript_1.default.factory.createPropertyAccessExpression(newChain, propertyChain[i]);
}
return typescript_1.default.factory.updateCallExpression(node, newChain, node.typeArguments, node.arguments);
}
const newExpectArgs = [...expectCall.arguments, contextMessage];
const newExpectCall = typescript_1.default.factory.updateCallExpression(expectCall, expectCall.expression, expectCall.typeArguments, newExpectArgs);
// Rebuild the property access chain
let newExpression = newExpectCall;
for (let i = propertyChain.length - 1; i >= 0; i--) {
newExpression = typescript_1.default.factory.createPropertyAccessExpression(newExpression, propertyChain[i]);
}
return typescript_1.default.factory.updateCallExpression(node, newExpression, node.typeArguments, node.arguments);
}
function transformExpectNothing(node, { sourceFile, reporter }) {
if (!typescript_1.default.isExpressionStatement(node)) {
return node;
}
const call = node.expression;
if (!typescript_1.default.isCallExpression(call) ||
!typescript_1.default.isPropertyAccessExpression(call.expression) ||
!typescript_1.default.isIdentifier(call.expression.name) ||
call.expression.name.text !== 'nothing') {
return node;
}
const expectCall = call.expression.expression;
if (!typescript_1.default.isCallExpression(expectCall) ||
!typescript_1.default.isIdentifier(expectCall.expression) ||
expectCall.expression.text !== 'expect' ||
expectCall.arguments.length > 0) {
return node;
}
// The statement is `expect().nothing()`, which can be removed.
const replacement = typescript_1.default.factory.createEmptyStatement();
const originalText = node.getFullText().trim();
reporter.reportTransformation(sourceFile, node, 'Removed `expect().nothing()` statement.');
const category = 'expect-nothing';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(replacement, category);
typescript_1.default.addSyntheticLeadingComment(replacement, typescript_1.default.SyntaxKind.SingleLineCommentTrivia, ` ${originalText}`, true);
return replacement;
}
//# sourceMappingURL=jasmine-matcher.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,21 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @fileoverview This file contains transformers for miscellaneous Jasmine APIs that don't
* fit into other categories. This includes timer mocks (`jasmine.clock`), the `fail()`
* function, and configuration settings like `jasmine.DEFAULT_TIMEOUT_INTERVAL`. It also
* includes logic to identify and add TODO comments for unsupported Jasmine features.
*/
import ts from '../../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
import { RefactorContext } from '../utils/refactor-context';
export declare function transformTimerMocks(node: ts.Node, { sourceFile, reporter, pendingVitestValueImports }: RefactorContext): ts.Node;
export declare function transformFail(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
export declare function transformDefaultTimeoutInterval(node: ts.Node, { sourceFile, reporter, pendingVitestValueImports }: RefactorContext): ts.Node;
export declare function transformGlobalFunctions(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
export declare function transformUnsupportedJasmineCalls(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
export declare function transformUnknownJasmineProperties(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
@@ -0,0 +1,174 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformTimerMocks = transformTimerMocks;
exports.transformFail = transformFail;
exports.transformDefaultTimeoutInterval = transformDefaultTimeoutInterval;
exports.transformGlobalFunctions = transformGlobalFunctions;
exports.transformUnsupportedJasmineCalls = transformUnsupportedJasmineCalls;
exports.transformUnknownJasmineProperties = transformUnknownJasmineProperties;
/**
* @fileoverview This file contains transformers for miscellaneous Jasmine APIs that don't
* fit into other categories. This includes timer mocks (`jasmine.clock`), the `fail()`
* function, and configuration settings like `jasmine.DEFAULT_TIMEOUT_INTERVAL`. It also
* includes logic to identify and add TODO comments for unsupported Jasmine features.
*/
const typescript_1 = __importDefault(require("../../../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
const ast_helpers_1 = require("../utils/ast-helpers");
const ast_validation_1 = require("../utils/ast-validation");
const comment_helpers_1 = require("../utils/comment-helpers");
function transformTimerMocks(node, { sourceFile, reporter, pendingVitestValueImports }) {
if (!typescript_1.default.isCallExpression(node) ||
!typescript_1.default.isPropertyAccessExpression(node.expression) ||
!typescript_1.default.isIdentifier(node.expression.name)) {
return node;
}
const pae = node.expression;
const clockCall = pae.expression;
if (!(0, ast_validation_1.isJasmineCallExpression)(clockCall, 'clock')) {
return node;
}
let newMethodName;
switch (pae.name.text) {
case 'install':
newMethodName = 'useFakeTimers';
break;
case 'tick':
newMethodName = 'advanceTimersByTime';
break;
case 'uninstall':
newMethodName = 'useRealTimers';
break;
case 'mockDate':
newMethodName = 'setSystemTime';
break;
}
if (newMethodName) {
(0, ast_helpers_1.addVitestValueImport)(pendingVitestValueImports, 'vi');
reporter.reportTransformation(sourceFile, node, `Transformed \`jasmine.clock().${pae.name.text}\` to \`vi.${newMethodName}\`.`);
let newArgs = node.arguments;
if (newMethodName === 'useFakeTimers') {
newArgs = [];
}
if (newMethodName === 'setSystemTime' && node.arguments.length === 0) {
newArgs = [
typescript_1.default.factory.createNewExpression(typescript_1.default.factory.createIdentifier('Date'), undefined, []),
];
}
return (0, ast_helpers_1.createViCallExpression)(newMethodName, newArgs);
}
return node;
}
function transformFail(node, { sourceFile, reporter }) {
if (typescript_1.default.isExpressionStatement(node) &&
typescript_1.default.isCallExpression(node.expression) &&
typescript_1.default.isIdentifier(node.expression.expression) &&
node.expression.expression.text === 'fail') {
reporter.reportTransformation(sourceFile, node, 'Transformed `fail()` to `throw new Error()`.');
const reason = node.expression.arguments[0];
const replacement = typescript_1.default.factory.createThrowStatement(typescript_1.default.factory.createNewExpression(typescript_1.default.factory.createIdentifier('Error'), undefined, reason ? [reason] : []));
return typescript_1.default.setOriginalNode(typescript_1.default.setTextRange(replacement, node), node);
}
return node;
}
function transformDefaultTimeoutInterval(node, { sourceFile, reporter, pendingVitestValueImports }) {
if (typescript_1.default.isExpressionStatement(node) &&
typescript_1.default.isBinaryExpression(node.expression) &&
node.expression.operatorToken.kind === typescript_1.default.SyntaxKind.EqualsToken) {
const assignment = node.expression;
if (typescript_1.default.isPropertyAccessExpression(assignment.left) &&
typescript_1.default.isIdentifier(assignment.left.expression) &&
assignment.left.expression.text === 'jasmine' &&
assignment.left.name.text === 'DEFAULT_TIMEOUT_INTERVAL') {
(0, ast_helpers_1.addVitestValueImport)(pendingVitestValueImports, 'vi');
reporter.reportTransformation(sourceFile, node, 'Transformed `jasmine.DEFAULT_TIMEOUT_INTERVAL` to `vi.setConfig()`.');
const timeoutValue = assignment.right;
const setConfigCall = (0, ast_helpers_1.createViCallExpression)('setConfig', [
typescript_1.default.factory.createObjectLiteralExpression([typescript_1.default.factory.createPropertyAssignment('testTimeout', timeoutValue)], false),
]);
return typescript_1.default.factory.updateExpressionStatement(node, setConfigCall);
}
}
return node;
}
function transformGlobalFunctions(node, { sourceFile, reporter }) {
if (typescript_1.default.isCallExpression(node) &&
typescript_1.default.isIdentifier(node.expression) &&
(node.expression.text === 'setSpecProperty' || node.expression.text === 'setSuiteProperty')) {
const functionName = node.expression.text;
reporter.reportTransformation(sourceFile, node, `Found unsupported global function \`${functionName}\`.`);
const category = 'unsupported-global-function';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(node, category, { name: functionName });
}
return node;
}
const UNSUPPORTED_JASMINE_CALLS_CATEGORIES = new Set([
'addMatchers',
'addCustomEqualityTester',
'mapContaining',
'setContaining',
]);
// A type guard to ensure that the methodName is one of the categories handled by this transformer.
function isUnsupportedJasmineCall(methodName) {
return UNSUPPORTED_JASMINE_CALLS_CATEGORIES.has(methodName);
}
function transformUnsupportedJasmineCalls(node, { sourceFile, reporter }) {
const methodName = (0, ast_validation_1.getJasmineMethodName)(node);
if (methodName && isUnsupportedJasmineCall(methodName)) {
reporter.reportTransformation(sourceFile, node, `Found unsupported call \`jasmine.${methodName}\`.`);
reporter.recordTodo(methodName, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(node, methodName);
}
return node;
}
// If any additional properties are added to transforms, they should also be added to this list.
const HANDLED_JASMINE_PROPERTIES = new Set([
// Spies
'createSpy',
'createSpyObj',
'spyOnAllFunctions',
// Clock
'clock',
// Matchers
'any',
'anything',
'stringMatching',
'objectContaining',
'arrayContaining',
'arrayWithExactContents',
'truthy',
'falsy',
'empty',
'notEmpty',
'mapContaining',
'setContaining',
// Other
'DEFAULT_TIMEOUT_INTERVAL',
'addMatchers',
'addCustomEqualityTester',
]);
function transformUnknownJasmineProperties(node, { sourceFile, reporter }) {
if (typescript_1.default.isPropertyAccessExpression(node) &&
typescript_1.default.isIdentifier(node.expression) &&
node.expression.text === 'jasmine') {
const propName = node.name.text;
if (!HANDLED_JASMINE_PROPERTIES.has(propName)) {
reporter.reportTransformation(sourceFile, node, `Found unknown jasmine property \`jasmine.${propName}\`.`);
const category = 'unknown-jasmine-property';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(node, category, { name: propName });
}
}
return node;
}
//# sourceMappingURL=jasmine-misc.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,19 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @fileoverview This file contains transformers dedicated to converting Jasmine's spying
* functionality to Vitest's mocking APIs. It handles the creation of spies (`spyOn`,
* `createSpy`, `createSpyObj`), spy strategies (`and.returnValue`, `and.callFake`),
* and the inspection of spy calls (`spy.calls.reset`, `spy.calls.mostRecent`).
*/
import ts from '../../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
import { RefactorContext } from '../utils/refactor-context';
export declare function transformSpies(node: ts.Node, refactorCtx: RefactorContext): ts.Node;
export declare function transformCreateSpyObj(node: ts.Node, { sourceFile, reporter, pendingVitestValueImports }: RefactorContext): ts.Node;
export declare function transformSpyReset(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
export declare function transformSpyCallInspection(node: ts.Node, refactorCtx: RefactorContext): ts.Node;
@@ -0,0 +1,316 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformSpies = transformSpies;
exports.transformCreateSpyObj = transformCreateSpyObj;
exports.transformSpyReset = transformSpyReset;
exports.transformSpyCallInspection = transformSpyCallInspection;
/**
* @fileoverview This file contains transformers dedicated to converting Jasmine's spying
* functionality to Vitest's mocking APIs. It handles the creation of spies (`spyOn`,
* `createSpy`, `createSpyObj`), spy strategies (`and.returnValue`, `and.callFake`),
* and the inspection of spy calls (`spy.calls.reset`, `spy.calls.mostRecent`).
*/
const typescript_1 = __importDefault(require("../../../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
const ast_helpers_1 = require("../utils/ast-helpers");
const ast_validation_1 = require("../utils/ast-validation");
const comment_helpers_1 = require("../utils/comment-helpers");
function transformSpies(node, refactorCtx) {
const { sourceFile, reporter, pendingVitestValueImports } = refactorCtx;
if (!typescript_1.default.isCallExpression(node)) {
return node;
}
if (typescript_1.default.isIdentifier(node.expression) &&
(node.expression.text === 'spyOn' || node.expression.text === 'spyOnProperty')) {
(0, ast_helpers_1.addVitestValueImport)(pendingVitestValueImports, 'vi');
reporter.reportTransformation(sourceFile, node, `Transformed \`${node.expression.text}\` to \`vi.spyOn\`.`);
return typescript_1.default.factory.updateCallExpression(node, (0, ast_helpers_1.createPropertyAccess)('vi', 'spyOn'), node.typeArguments, node.arguments);
}
if (typescript_1.default.isPropertyAccessExpression(node.expression)) {
const pae = node.expression;
if (typescript_1.default.isPropertyAccessExpression(pae.expression) &&
typescript_1.default.isIdentifier(pae.expression.name) &&
pae.expression.name.text === 'and') {
const spyCall = pae.expression.expression;
let newMethodName;
if (typescript_1.default.isIdentifier(pae.name)) {
const strategyName = pae.name.text;
switch (strategyName) {
case 'returnValue':
newMethodName = 'mockReturnValue';
break;
case 'resolveTo':
newMethodName = 'mockResolvedValue';
break;
case 'rejectWith':
newMethodName = 'mockRejectedValue';
break;
case 'returnValues': {
reporter.reportTransformation(sourceFile, node, 'Transformed `.and.returnValues()` to chained `.mockReturnValueOnce()` calls.');
const returnValues = node.arguments;
if (returnValues.length === 0) {
// No values, so it's a no-op. Just transform the spyOn call.
return transformSpies(spyCall, refactorCtx);
}
// spy.and.returnValues(a, b) -> spy.mockReturnValueOnce(a).mockReturnValueOnce(b)
let chainedCall = spyCall;
for (const value of returnValues) {
const mockCall = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(chainedCall, 'mockReturnValueOnce'), undefined, [value]);
chainedCall = mockCall;
}
return chainedCall;
}
case 'callFake':
newMethodName = 'mockImplementation';
break;
case 'callThrough':
reporter.reportTransformation(sourceFile, node, 'Removed redundant `.and.callThrough()` call.');
return transformSpies(spyCall, refactorCtx); // .and.callThrough() is redundant, just transform spyOn.
case 'stub': {
reporter.reportTransformation(sourceFile, node, 'Transformed `.and.stub()` to `.mockImplementation()`.');
const newExpression = (0, ast_helpers_1.createPropertyAccess)(spyCall, 'mockImplementation');
const arrowFn = typescript_1.default.factory.createArrowFunction(undefined, undefined, [], undefined, typescript_1.default.factory.createToken(typescript_1.default.SyntaxKind.EqualsGreaterThanToken), typescript_1.default.factory.createBlock([], /* multiline */ true));
return typescript_1.default.factory.createCallExpression(newExpression, undefined, [arrowFn]);
}
case 'throwError': {
reporter.reportTransformation(sourceFile, node, 'Transformed `.and.throwError()` to `.mockImplementation()`.');
const errorArg = node.arguments[0];
const throwStatement = typescript_1.default.factory.createThrowStatement(typescript_1.default.isNewExpression(errorArg)
? errorArg
: typescript_1.default.factory.createNewExpression(typescript_1.default.factory.createIdentifier('Error'), undefined, node.arguments));
const arrowFunction = typescript_1.default.factory.createArrowFunction(undefined, undefined, [], undefined, typescript_1.default.factory.createToken(typescript_1.default.SyntaxKind.EqualsGreaterThanToken), typescript_1.default.factory.createBlock([throwStatement], true));
const newExpression = (0, ast_helpers_1.createPropertyAccess)(spyCall, 'mockImplementation');
return typescript_1.default.factory.createCallExpression(newExpression, undefined, [arrowFunction]);
}
default: {
const category = 'unsupported-spy-strategy';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(node, category, { name: strategyName });
break;
}
}
if (newMethodName) {
reporter.reportTransformation(sourceFile, node, `Transformed spy strategy \`.and.${strategyName}()\` to \`.${newMethodName}()\`.`);
const newExpression = typescript_1.default.factory.updatePropertyAccessExpression(pae, spyCall, typescript_1.default.factory.createIdentifier(newMethodName));
return typescript_1.default.factory.updateCallExpression(node, newExpression, node.typeArguments, node.arguments);
}
}
}
}
const jasmineMethodName = (0, ast_validation_1.getJasmineMethodName)(node);
switch (jasmineMethodName) {
case 'createSpy':
(0, ast_helpers_1.addVitestValueImport)(pendingVitestValueImports, 'vi');
reporter.reportTransformation(sourceFile, node, 'Transformed `jasmine.createSpy()` to `vi.fn()`.');
// jasmine.createSpy(name, originalFn) -> vi.fn(originalFn)
return (0, ast_helpers_1.createViCallExpression)('fn', node.arguments.length > 1 ? [node.arguments[1]] : []);
case 'spyOnAllFunctions': {
reporter.reportTransformation(sourceFile, node, 'Found unsupported `jasmine.spyOnAllFunctions()`.');
const category = 'spyOnAllFunctions';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(node, category);
return node;
}
}
return node;
}
function transformCreateSpyObj(node, { sourceFile, reporter, pendingVitestValueImports }) {
if (!(0, ast_validation_1.isJasmineCallExpression)(node, 'createSpyObj')) {
return node;
}
(0, ast_helpers_1.addVitestValueImport)(pendingVitestValueImports, 'vi');
reporter.reportTransformation(sourceFile, node, 'Transformed `jasmine.createSpyObj()` to an object literal with `vi.fn()`.');
const firstArg = node.arguments[0];
const hasBaseName = typescript_1.default.isStringLiteral(firstArg);
const baseName = hasBaseName ? firstArg.text : undefined;
const methods = hasBaseName ? node.arguments[1] : firstArg;
const propertiesArg = hasBaseName ? node.arguments[2] : node.arguments[1];
let properties = [];
if (node.arguments.length < 2 && hasBaseName) {
const category = 'createSpyObj-single-argument';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(node, category);
return node;
}
if (typescript_1.default.isArrayLiteralExpression(methods)) {
properties = createSpyObjWithArray(methods, baseName);
}
else if (typescript_1.default.isObjectLiteralExpression(methods)) {
properties = createSpyObjWithObject(methods, baseName);
}
else {
const category = 'createSpyObj-dynamic-variable';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(node, category);
return node;
}
if (propertiesArg) {
if (typescript_1.default.isObjectLiteralExpression(propertiesArg)) {
properties.push(...propertiesArg.properties);
}
else {
const category = 'createSpyObj-dynamic-property-map';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(node, category);
}
}
return typescript_1.default.factory.createObjectLiteralExpression(properties, true);
}
function createSpyObjWithArray(methods, baseName) {
return methods.elements
.map((element) => {
if (typescript_1.default.isStringLiteral(element)) {
const mockFn = (0, ast_helpers_1.createViCallExpression)('fn');
const methodName = element.text;
let finalExpression = mockFn;
if (baseName) {
finalExpression = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(finalExpression, 'mockName'), undefined, [typescript_1.default.factory.createStringLiteral(`${baseName}.${methodName}`)]);
}
return typescript_1.default.factory.createPropertyAssignment(typescript_1.default.factory.createIdentifier(methodName), finalExpression);
}
return undefined;
})
.filter((p) => !!p);
}
function createSpyObjWithObject(methods, baseName) {
return methods.properties
.map((prop) => {
if (typescript_1.default.isPropertyAssignment(prop) && typescript_1.default.isIdentifier(prop.name)) {
const methodName = prop.name.text;
const returnValue = prop.initializer;
let mockFn = (0, ast_helpers_1.createViCallExpression)('fn');
if (baseName) {
mockFn = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(mockFn, 'mockName'), undefined, [typescript_1.default.factory.createStringLiteral(`${baseName}.${methodName}`)]);
}
const mockReturnValue = (0, ast_helpers_1.createPropertyAccess)(mockFn, 'mockReturnValue');
return typescript_1.default.factory.createPropertyAssignment(typescript_1.default.factory.createIdentifier(methodName), typescript_1.default.factory.createCallExpression(mockReturnValue, undefined, [returnValue]));
}
return undefined;
})
.filter((p) => !!p);
}
function transformSpyReset(node, { sourceFile, reporter }) {
if (typescript_1.default.isCallExpression(node) &&
typescript_1.default.isPropertyAccessExpression(node.expression) &&
typescript_1.default.isIdentifier(node.expression.name) &&
node.expression.name.text === 'reset' &&
typescript_1.default.isPropertyAccessExpression(node.expression.expression)) {
const callsPae = node.expression.expression;
if (typescript_1.default.isIdentifier(callsPae.name) && callsPae.name.text === 'calls') {
reporter.reportTransformation(sourceFile, node, 'Transformed `spy.calls.reset()` to `.mockClear()`.');
const spyIdentifier = callsPae.expression;
const newExpression = (0, ast_helpers_1.createPropertyAccess)(spyIdentifier, 'mockClear');
return typescript_1.default.factory.updateCallExpression(node, newExpression, node.typeArguments, []);
}
}
return node;
}
function getSpyIdentifierFromCalls(node) {
if (typescript_1.default.isIdentifier(node.name) && node.name.text === 'calls') {
return node.expression;
}
return undefined;
}
function createMockedSpyMockProperty(spyIdentifier, pendingVitestValueImports) {
(0, ast_helpers_1.addVitestValueImport)(pendingVitestValueImports, 'vi');
const mockedSpy = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)('vi', 'mocked'), undefined, [spyIdentifier]);
return (0, ast_helpers_1.createPropertyAccess)(mockedSpy, 'mock');
}
function transformMostRecentArgs(node, { sourceFile, reporter, pendingVitestValueImports }) {
// Check 1: Is it a property access for `.args`?
if (!typescript_1.default.isPropertyAccessExpression(node) ||
!typescript_1.default.isIdentifier(node.name) ||
node.name.text !== 'args') {
return node;
}
// Check 2: Is the preceding expression a call expression?
const mostRecentCall = node.expression;
if (!typescript_1.default.isCallExpression(mostRecentCall) ||
!typescript_1.default.isPropertyAccessExpression(mostRecentCall.expression)) {
return node;
}
// Check 3: Is it a call to `.mostRecent`?
const mostRecentPae = mostRecentCall.expression;
if (!typescript_1.default.isIdentifier(mostRecentPae.name) ||
mostRecentPae.name.text !== 'mostRecent' ||
!typescript_1.default.isPropertyAccessExpression(mostRecentPae.expression)) {
return node;
}
// Check 4: Can we get the spy identifier from `spy.calls`?
const spyIdentifier = getSpyIdentifierFromCalls(mostRecentPae.expression);
if (!spyIdentifier) {
return node;
}
// If all checks pass, perform the transformation.
reporter.reportTransformation(sourceFile, node, 'Transformed `spy.calls.mostRecent().args` to `vi.mocked(spy).mock.lastCall`.');
const mockProperty = createMockedSpyMockProperty(spyIdentifier, pendingVitestValueImports);
return (0, ast_helpers_1.createPropertyAccess)(mockProperty, 'lastCall');
}
function transformSpyCallInspection(node, refactorCtx) {
const mostRecentArgsTransformed = transformMostRecentArgs(node, refactorCtx);
if (mostRecentArgsTransformed !== node) {
return mostRecentArgsTransformed;
}
if (!typescript_1.default.isCallExpression(node) || !typescript_1.default.isPropertyAccessExpression(node.expression)) {
return node;
}
const { sourceFile, reporter, pendingVitestValueImports } = refactorCtx;
const pae = node.expression; // e.g., mySpy.calls.count
const spyIdentifier = typescript_1.default.isPropertyAccessExpression(pae.expression)
? getSpyIdentifierFromCalls(pae.expression)
: undefined;
if (spyIdentifier) {
const mockProperty = createMockedSpyMockProperty(spyIdentifier, pendingVitestValueImports);
const callsProperty = (0, ast_helpers_1.createPropertyAccess)(mockProperty, 'calls');
const callName = pae.name.text;
let newExpression;
let message;
switch (callName) {
case 'any':
message = 'Transformed `spy.calls.any()` to a check on `mock.calls.length`.';
newExpression = typescript_1.default.factory.createBinaryExpression((0, ast_helpers_1.createPropertyAccess)(callsProperty, 'length'), typescript_1.default.SyntaxKind.GreaterThanToken, typescript_1.default.factory.createNumericLiteral(0));
break;
case 'count':
message = 'Transformed `spy.calls.count()` to `mock.calls.length`.';
newExpression = (0, ast_helpers_1.createPropertyAccess)(callsProperty, 'length');
break;
case 'first':
message = 'Transformed `spy.calls.first()` to `mock.calls[0]`.';
newExpression = typescript_1.default.factory.createElementAccessExpression(callsProperty, 0);
break;
case 'all':
case 'allArgs':
message = `Transformed \`spy.calls.${callName}()\` to \`mock.calls\`.`;
newExpression = callsProperty;
break;
case 'argsFor':
message = 'Transformed `spy.calls.argsFor()` to `mock.calls[i]`.';
newExpression = typescript_1.default.factory.createElementAccessExpression(callsProperty, node.arguments[0]);
break;
case 'mostRecent':
if (!typescript_1.default.isPropertyAccessExpression(node.parent) ||
!typescript_1.default.isIdentifier(node.parent.name) ||
node.parent.name.text !== 'args') {
const category = 'mostRecent-without-args';
reporter.recordTodo(category, sourceFile, node);
(0, comment_helpers_1.addTodoComment)(node, category);
}
return node;
}
if (newExpression && message) {
reporter.reportTransformation(sourceFile, node, message);
return newExpression;
}
}
return node;
}
//# sourceMappingURL=jasmine-spy.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,16 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @fileoverview This file contains a transformer that migrates Jasmine type definitions to
* their Vitest equivalents. It handles the conversion of types like `jasmine.Spy` and
* `jasmine.SpyObj` to Vitest's `Mock` and `MockedObject` types, and ensures that the
* necessary `vitest` imports are added to the file.
*/
import ts from '../../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
import { RefactorContext } from '../utils/refactor-context';
export declare function transformJasmineTypes(node: ts.Node, { sourceFile, reporter, pendingVitestTypeImports }: RefactorContext): ts.Node;
@@ -0,0 +1,64 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformJasmineTypes = transformJasmineTypes;
/**
* @fileoverview This file contains a transformer that migrates Jasmine type definitions to
* their Vitest equivalents. It handles the conversion of types like `jasmine.Spy` and
* `jasmine.SpyObj` to Vitest's `Mock` and `MockedObject` types, and ensures that the
* necessary `vitest` imports are added to the file.
*/
const typescript_1 = __importDefault(require("../../../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
const ast_helpers_1 = require("../utils/ast-helpers");
function transformJasmineTypes(node, { sourceFile, reporter, pendingVitestTypeImports }) {
const typeNameNode = typescript_1.default.isTypeReferenceNode(node) ? node.typeName : node;
if (!typescript_1.default.isQualifiedName(typeNameNode) ||
!typescript_1.default.isIdentifier(typeNameNode.left) ||
typeNameNode.left.text !== 'jasmine') {
return node;
}
const jasmineTypeName = typeNameNode.right.text;
switch (jasmineTypeName) {
case 'Spy': {
const vitestTypeName = 'Mock';
reporter.reportTransformation(sourceFile, node, `Transformed type \`jasmine.Spy\` to \`${vitestTypeName}\`.`);
(0, ast_helpers_1.addVitestTypeImport)(pendingVitestTypeImports, vitestTypeName);
return typescript_1.default.factory.createIdentifier(vitestTypeName);
}
case 'SpyObj': {
const vitestTypeName = 'MockedObject';
reporter.reportTransformation(sourceFile, node, `Transformed type \`jasmine.SpyObj\` to \`${vitestTypeName}\`.`);
(0, ast_helpers_1.addVitestTypeImport)(pendingVitestTypeImports, vitestTypeName);
if (typescript_1.default.isTypeReferenceNode(node)) {
return typescript_1.default.factory.updateTypeReferenceNode(node, typescript_1.default.factory.createIdentifier(vitestTypeName), node.typeArguments);
}
return typescript_1.default.factory.createIdentifier(vitestTypeName);
}
case 'Any':
reporter.reportTransformation(sourceFile, node, `Transformed type \`jasmine.Any\` to \`any\`.`);
return typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.AnyKeyword);
case 'ObjectContaining': {
const typeArguments = typescript_1.default.isTypeReferenceNode(node) ? node.typeArguments : undefined;
if (typeArguments && typeArguments.length > 0) {
reporter.reportTransformation(sourceFile, node, `Transformed type \`jasmine.ObjectContaining\` to \`Partial\`.`);
return typescript_1.default.factory.createTypeReferenceNode('Partial', typeArguments);
}
reporter.reportTransformation(sourceFile, node, `Transformed type \`jasmine.ObjectContaining\` to \`object\`.`);
return typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.ObjectKeyword);
}
case 'DoneFn':
reporter.reportTransformation(sourceFile, node, 'Transformed type `jasmine.DoneFn` to `() => void`.');
return typescript_1.default.factory.createFunctionTypeNode(undefined, [], typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.VoidKeyword));
}
return node;
}
//# sourceMappingURL=jasmine-type.js.map
@@ -0,0 +1 @@
{"version":3,"file":"jasmine-type.js","sourceRoot":"","sources":["jasmine-type.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;;;AAaH,sDAyFC;AApGD;;;;;GAKG;AAEH,qHAAqF;AACrF,sDAA2D;AAG3D,SAAgB,qBAAqB,CACnC,IAAa,EACb,EAAE,UAAU,EAAE,QAAQ,EAAE,wBAAwB,EAAmB;IAEnE,MAAM,YAAY,GAAG,oBAAE,CAAC,mBAAmB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC;IACzE,IACE,CAAC,oBAAE,CAAC,eAAe,CAAC,YAAY,CAAC;QACjC,CAAC,oBAAE,CAAC,YAAY,CAAC,YAAY,CAAC,IAAI,CAAC;QACnC,YAAY,CAAC,IAAI,CAAC,IAAI,KAAK,SAAS,EACpC,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,eAAe,GAAG,YAAY,CAAC,KAAK,CAAC,IAAI,CAAC;IAEhD,QAAQ,eAAe,EAAE,CAAC;QACxB,KAAK,KAAK,CAAC,CAAC,CAAC;YACX,MAAM,cAAc,GAAG,MAAM,CAAC;YAC9B,QAAQ,CAAC,oBAAoB,CAC3B,UAAU,EACV,IAAI,EACJ,yCAAyC,cAAc,KAAK,CAC7D,CAAC;YACF,IAAA,iCAAmB,EAAC,wBAAwB,EAAE,cAAc,CAAC,CAAC;YAE9D,OAAO,oBAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,cAAc,CAAC,CAAC;QACrD,CAAC;QACD,KAAK,QAAQ,CAAC,CAAC,CA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AE,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC;QACvE,CAAC;QACD,KAAK,QAAQ;YACX,QAAQ,CAAC,oBAAoB,CAC3B,UAAU,EACV,IAAI,EACJ,oDAAoD,CACrD,CAAC;YAEF,OAAO,oBAAE,CAAC,OAAO,CAAC,sBAAsB,CACtC,SAAS,EACT,EAAE,EACF,oBAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,oBAAE,CAAC,UAAU,CAAC,WAAW,CAAC,CAC5D,CAAC;IACN,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,14 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from '../../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
export declare function addVitestValueImport(imports: Set<string>, importName: string): void;
export declare function addVitestTypeImport(imports: Set<string>, importName: string): void;
export declare function getVitestAutoImports(valueImports: Set<string>, typeImports: Set<string>): ts.ImportDeclaration | undefined;
export declare function createViCallExpression(methodName: string, args?: readonly ts.Expression[], typeArgs?: ts.TypeNode[] | undefined): ts.CallExpression;
export declare function createExpectCallExpression(args: ts.Expression[], typeArgs?: ts.TypeNode[] | undefined): ts.CallExpression;
export declare function createPropertyAccess(expressionOrIndentifierText: ts.Expression | string, name: string | ts.MemberName): ts.PropertyAccessExpression;
@@ -0,0 +1,58 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.addVitestValueImport = addVitestValueImport;
exports.addVitestTypeImport = addVitestTypeImport;
exports.getVitestAutoImports = getVitestAutoImports;
exports.createViCallExpression = createViCallExpression;
exports.createExpectCallExpression = createExpectCallExpression;
exports.createPropertyAccess = createPropertyAccess;
const typescript_1 = __importDefault(require("../../../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
function addVitestValueImport(imports, importName) {
imports.add(importName);
}
function addVitestTypeImport(imports, importName) {
imports.add(importName);
}
function getVitestAutoImports(valueImports, typeImports) {
if (valueImports.size === 0 && typeImports.size === 0) {
return undefined;
}
const isClauseTypeOnly = valueImports.size === 0 && typeImports.size > 0;
const allSpecifiers = [];
// Add value imports
for (const i of [...valueImports].sort()) {
allSpecifiers.push(typescript_1.default.factory.createImportSpecifier(false, undefined, typescript_1.default.factory.createIdentifier(i)));
}
// Add type imports
for (const i of [...typeImports].sort()) {
// Only set isTypeOnly on individual specifiers if the clause itself is NOT type-only
allSpecifiers.push(typescript_1.default.factory.createImportSpecifier(!isClauseTypeOnly, undefined, typescript_1.default.factory.createIdentifier(i)));
}
allSpecifiers.sort((a, b) => a.name.text.localeCompare(b.name.text));
const importClause = typescript_1.default.factory.createImportClause(isClauseTypeOnly, // Set isTypeOnly on the clause if only type imports
undefined, typescript_1.default.factory.createNamedImports(allSpecifiers));
return typescript_1.default.factory.createImportDeclaration(undefined, importClause, typescript_1.default.factory.createStringLiteral('vitest'));
}
function createViCallExpression(methodName, args = [], typeArgs = undefined) {
const callee = typescript_1.default.factory.createPropertyAccessExpression(typescript_1.default.factory.createIdentifier('vi'), methodName);
return typescript_1.default.factory.createCallExpression(callee, typeArgs, args);
}
function createExpectCallExpression(args, typeArgs = undefined) {
return typescript_1.default.factory.createCallExpression(typescript_1.default.factory.createIdentifier('expect'), typeArgs, args);
}
function createPropertyAccess(expressionOrIndentifierText, name) {
return typescript_1.default.factory.createPropertyAccessExpression(typeof expressionOrIndentifierText === 'string'
? typescript_1.default.factory.createIdentifier(expressionOrIndentifierText)
: expressionOrIndentifierText, name);
}
//# sourceMappingURL=ast-helpers.js.map
@@ -0,0 +1 @@
{"version":3,"file":"ast-helpers.js","sourceRoot":"","sources":["ast-helpers.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;;;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CAAC"}
@@ -0,0 +1,25 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @fileoverview This file contains helper functions for validating the structure of
* TypeScript AST nodes, particularly for identifying specific patterns in Jasmine tests.
*/
import ts from '../../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
/**
* If a node is a `jasmine.method()` call, returns the method name.
* @param node The node to check.
* @returns The name of the method if it's a jasmine call, otherwise undefined.
*/
export declare function getJasmineMethodName(node: ts.Node): string | undefined;
/**
* Checks if a node is a call expression for a specific method on the `jasmine` object.
* @param node The node to check.
* @param methodName The name of the method on the `jasmine` object.
* @returns True if the node is a `jasmine.<methodName>()` call.
*/
export declare function isJasmineCallExpression(node: ts.Node, methodName: string): node is ts.CallExpression;
@@ -0,0 +1,44 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getJasmineMethodName = getJasmineMethodName;
exports.isJasmineCallExpression = isJasmineCallExpression;
/**
* @fileoverview This file contains helper functions for validating the structure of
* TypeScript AST nodes, particularly for identifying specific patterns in Jasmine tests.
*/
const typescript_1 = __importDefault(require("../../../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
/**
* If a node is a `jasmine.method()` call, returns the method name.
* @param node The node to check.
* @returns The name of the method if it's a jasmine call, otherwise undefined.
*/
function getJasmineMethodName(node) {
if (!typescript_1.default.isCallExpression(node) || !typescript_1.default.isPropertyAccessExpression(node.expression)) {
return undefined;
}
const pae = node.expression;
if (!typescript_1.default.isIdentifier(pae.expression) || pae.expression.text !== 'jasmine') {
return undefined;
}
return typescript_1.default.isIdentifier(pae.name) ? pae.name.text : undefined;
}
/**
* Checks if a node is a call expression for a specific method on the `jasmine` object.
* @param node The node to check.
* @param methodName The name of the method on the `jasmine` object.
* @returns True if the node is a `jasmine.<methodName>()` call.
*/
function isJasmineCallExpression(node, methodName) {
return getJasmineMethodName(node) === methodName;
}
//# sourceMappingURL=ast-validation.js.map
@@ -0,0 +1 @@
{"version":3,"file":"ast-validation.js","sourceRoot":"","sources":["ast-validation.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;;;AAcH,oDAWC;AAQD,0DAKC;AApCD;;;GAGG;AAEH,qHAAqF;AAErF;;;;GAIG;AACH,SAAgB,oBAAoB,CAAC,IAAa;IAChD,IAAI,CAAC,oBAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,oBAAE,CAAC,0BAA0B,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;QAClF,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAC;IAC5B,IAAI,CAAC,oBAAE,CAAC,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,GAAG,CAAC,UAAU,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QAC1E,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,oBAAE,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AAC/D,CAAC;AAED;;;;;GAKG;AACH,SAAgB,uBAAuB,CACrC,IAAa,EACb,UAAkB;IAElB,OAAO,oBAAoB,CAAC,IAAI,CAAC,KAAK,UAAU,CAAC;AACnD,CAAC"}
@@ -0,0 +1,29 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from '../../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
import { TodoCategory, TodoContextMap } from './todo-notes';
type CategoriesWithNoContext = {
[K in TodoCategory]: TodoContextMap[K] extends never ? K : never;
}[TodoCategory];
/**
* Adds a TODO comment to a TypeScript node for manual migration.
* This overload handles categories that do not require a context object.
* @param node The AST node to which the comment will be added.
* @param category The category of the TODO, used to look up the message and URL.
*/
export declare function addTodoComment<T extends CategoriesWithNoContext>(node: ts.Node, category: T): void;
/**
* Adds a TODO comment to a TypeScript node for manual migration.
* This overload handles categories that require a context object, ensuring it is
* provided and correctly typed.
* @param node The AST node to which the comment will be added.
* @param category The category of the TODO, used to look up the message and URL.
* @param context The context object providing dynamic values for the message.
*/
export declare function addTodoComment<T extends TodoCategory>(node: ts.Node, category: T, context: TodoContextMap[T]): void;
export {};
@@ -0,0 +1,37 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.addTodoComment = addTodoComment;
const typescript_1 = __importDefault(require("../../../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
const todo_notes_1 = require("./todo-notes");
// Implementation that covers both overloads.
function addTodoComment(node, category, context) {
const note = todo_notes_1.TODO_NOTES[category];
// The type assertion is safe here because the overloads guarantee the correct context is passed.
const message = typeof note.message === 'function' ? note.message(context) : note.message;
const url = 'url' in note && note.url ? ` See: ${note.url}` : '';
const commentText = ` TODO: vitest-migration: ${message}${url}`;
let statement = node;
// Traverse up the AST to find the containing statement for the node.
// This ensures that the comment is placed before the entire statement,
// rather than being attached to a deeply nested node. For example, if the
// node is an `Identifier`, we want the comment on the `VariableStatement`
// or `ExpressionStatement` that contains it.
while (statement.parent && !typescript_1.default.isBlock(statement.parent) && !typescript_1.default.isSourceFile(statement.parent)) {
if (typescript_1.default.isExpressionStatement(statement) || typescript_1.default.isVariableStatement(statement)) {
break;
}
statement = statement.parent;
}
typescript_1.default.addSyntheticLeadingComment(statement, typescript_1.default.SyntaxKind.SingleLineCommentTrivia, commentText, true);
}
//# sourceMappingURL=comment-helpers.js.map
@@ -0,0 +1 @@
{"version":3,"file":"comment-helpers.js","sourceRoot":"","sources":["comment-helpers.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;;;AAiCH,wCAgCC;AA/DD,qHAAqF;AACrF,6CAAwE;AA6BxE,6CAA6C;AAC7C,SAAgB,cAAc,CAC5B,IAAa,EACb,QAAsB,EACtB,OAAiC;IAEjC,MAAM,IAAI,GAAG,uBAAU,CAAC,QAAQ,CAAC,CAAC;IAClC,iGAAiG;IACjG,MAAM,OAAO,GACX,OAAO,IAAI,CAAC,OAAO,KAAK,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,OAAgB,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC;IACrF,MAAM,GAAG,GAAG,KAAK,IAAI,IAAI,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACjE,MAAM,WAAW,GAAG,4BAA4B,OAAO,GAAG,GAAG,EAAE,CAAC;IAEhE,IAAI,SAAS,GAAY,IAAI,CAAC;IAE9B,qEAAqE;IACrE,uEAAuE;IACvE,0EAA0E;IAC1E,0EAA0E;IAC1E,6CAA6C;IAC7C,OAAO,SAAS,CAAC,MAAM,IAAI,CAAC,oBAAE,CAAC,OAAO,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,oBAAE,CAAC,YAAY,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC;QAC/F,IAAI,oBAAE,CAAC,qBAAqB,CAAC,SAAS,CAAC,IAAI,oBAAE,CAAC,mBAAmB,CAAC,SAAS,CAAC,EAAE,CAAC;YAC7E,MAAM;QACR,CAAC;QACD,SAAS,GAAG,SAAS,CAAC,MAAM,CAAC;IAC/B,CAAC;IAED,oBAAE,CAAC,0BAA0B,CAC3B,SAAS,EACT,oBAAE,CAAC,UAAU,CAAC,uBAAuB,EACrC,WAAW,EACX,IAAI,CACL,CAAC;AACJ,CAAC"}
@@ -0,0 +1,30 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from '../../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
import { RefactorReporter } from './refactor-reporter';
/**
* A context object that provides access to shared utilities and state
* throughout the transformation process.
*/
export interface RefactorContext {
/** The root ts.SourceFile node of the file being transformed. */
readonly sourceFile: ts.SourceFile;
/** The reporter for logging changes and TODOs. */
readonly reporter: RefactorReporter;
/** The official context from the TypeScript Transformer API. */
readonly tsContext: ts.TransformationContext;
/** A set of Vitest value imports to be added to the file. */
readonly pendingVitestValueImports: Set<string>;
/** A set of Vitest type imports to be added to the file. */
readonly pendingVitestTypeImports: Set<string>;
}
/**
* A generic transformer function that operates on a specific type of ts.Node.
* @template T The specific type of AST node this transformer works on (e.g., ts.CallExpression).
*/
export type NodeTransformer<T extends ts.Node> = (node: T, refactorCtx: RefactorContext) => ts.Node | readonly ts.Node[];
@@ -0,0 +1,10 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=refactor-context.js.map
@@ -0,0 +1 @@
{"version":3,"file":"refactor-context.js","sourceRoot":"","sources":["refactor-context.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG"}
@@ -0,0 +1,28 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from '../../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
import { TodoCategory } from './todo-notes';
export declare class RefactorReporter {
private logger;
private filesScanned;
private filesTransformed;
private readonly todos;
private readonly verboseLogs;
private readonly fileTodos;
constructor(logger: {
info(message: string): void;
warn(message: string): void;
});
get hasTodos(): boolean;
incrementScannedFiles(): void;
incrementTransformedFiles(): void;
recordTodo(category: TodoCategory, sourceFile: ts.SourceFile, node: ts.Node): void;
reportTransformation(sourceFile: ts.SourceFile, node: ts.Node, message: string): void;
generateReportContent(): string;
printSummary(verbose?: boolean): void;
}
@@ -0,0 +1,142 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RefactorReporter = void 0;
const typescript_1 = __importDefault(require("../../../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
class RefactorReporter {
logger;
filesScanned = 0;
filesTransformed = 0;
todos = new Map();
verboseLogs = new Map();
fileTodos = new Map();
constructor(logger) {
this.logger = logger;
}
get hasTodos() {
return this.todos.size > 0;
}
incrementScannedFiles() {
this.filesScanned++;
}
incrementTransformedFiles() {
this.filesTransformed++;
}
recordTodo(category, sourceFile, node) {
this.todos.set(category, (this.todos.get(category) ?? 0) + 1);
const { line } = typescript_1.default.getLineAndCharacterOfPosition(sourceFile, typescript_1.default.getOriginalNode(node).getStart(sourceFile));
const filePath = sourceFile.fileName;
let fileTodos = this.fileTodos.get(filePath);
if (!fileTodos) {
fileTodos = [];
this.fileTodos.set(filePath, fileTodos);
}
fileTodos.push({ category, line: line + 1 });
}
reportTransformation(sourceFile, node, message) {
const { line } = typescript_1.default.getLineAndCharacterOfPosition(sourceFile, typescript_1.default.getOriginalNode(node).getStart(sourceFile));
const filePath = sourceFile.fileName;
let logs = this.verboseLogs.get(filePath);
if (!logs) {
logs = [];
this.verboseLogs.set(filePath, logs);
}
logs.push(`L${line + 1}: ${message}`);
}
generateReportContent() {
const lines = [];
lines.push('# Jasmine to Vitest Refactoring Report');
lines.push('');
lines.push(`Date: ${new Date().toISOString()}`);
lines.push('');
const summaryEntries = [
{ label: 'Files Scanned', value: this.filesScanned },
{ label: 'Files Transformed', value: this.filesTransformed },
{ label: 'Files Skipped', value: this.filesScanned - this.filesTransformed },
{ label: 'Total TODOs', value: [...this.todos.values()].reduce((a, b) => a + b, 0) },
];
const firstColPad = Math.max(...summaryEntries.map(({ label }) => label.length));
const secondColPad = 5;
lines.push('## Summary');
lines.push('');
lines.push(`| ${' '.padEnd(firstColPad)} | ${'Count'.padStart(secondColPad)} |`);
lines.push(`|:${'-'.repeat(firstColPad + 1)}|${'-'.repeat(secondColPad + 1)}:|`);
for (const { label, value } of summaryEntries) {
lines.push(`| ${label.padEnd(firstColPad)} | ${String(value).padStart(secondColPad)} |`);
}
lines.push('');
if (this.todos.size > 0) {
lines.push('## TODO Overview');
lines.push('');
const todoEntries = [...this.todos.entries()];
const firstColPad = Math.max('Category'.length, ...todoEntries.map(([category]) => category.length));
const secondColPad = 5;
lines.push(`| ${'Category'.padEnd(firstColPad)} | ${'Count'.padStart(secondColPad)} |`);
lines.push(`|:${'-'.repeat(firstColPad + 1)}|${'-'.repeat(secondColPad + 1)}:|`);
for (const [category, count] of todoEntries) {
lines.push(`| ${category.padEnd(firstColPad)} | ${String(count).padStart(secondColPad)} |`);
}
lines.push('');
}
if (this.fileTodos.size > 0) {
lines.push('## Files Requiring Manual Attention');
lines.push('');
// Sort files alphabetically
const sortedFiles = [...this.fileTodos.keys()].sort();
for (const filePath of sortedFiles) {
const relativePath = filePath.startsWith('/') ? filePath.substring(1) : filePath;
lines.push(`### [\`${relativePath}\`](./${relativePath})`);
const todos = this.fileTodos.get(filePath);
if (todos) {
// Sort todos by line number
todos.sort((a, b) => a.line - b.line);
for (const todo of todos) {
lines.push(`- [L${todo.line}](./${relativePath}#L${todo.line}): ${todo.category}`);
}
}
lines.push('');
}
}
else {
lines.push('## No Manual Changes Required');
lines.push('');
lines.push('All identified patterns were successfully transformed.');
}
return lines.join('\n');
}
printSummary(verbose = false) {
if (verbose && this.verboseLogs.size > 0) {
this.logger.info('Detailed Transformation Log:');
for (const [filePath, logs] of this.verboseLogs) {
this.logger.info(`Processing: ${filePath}`);
logs.forEach((log) => this.logger.info(` - ${log}`));
}
this.logger.info(''); // Add a blank line for separation
}
this.logger.info('Jasmine to Vitest Refactoring Summary:');
this.logger.info(`- ${this.filesScanned} test file(s) scanned.`);
this.logger.info(`- ${this.filesTransformed} file(s) transformed.`);
const filesSkipped = this.filesScanned - this.filesTransformed;
if (filesSkipped > 0) {
this.logger.info(`- ${filesSkipped} file(s) skipped (no changes needed).`);
}
if (this.todos.size > 0) {
const totalTodos = [...this.todos.values()].reduce((a, b) => a + b, 0);
this.logger.warn(`- ${totalTodos} TODO(s) added for manual review:`);
for (const [category, count] of this.todos) {
this.logger.warn(` - ${count}x ${category}`);
}
}
}
}
exports.RefactorReporter = RefactorReporter;
//# sourceMappingURL=refactor-reporter.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,138 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @fileoverview This file is the single source of truth for all "TODO" notes
* generated by the Jasmine to Vitest schematic.
*
* It defines the `TODO_NOTES` constant, which contains the message and optional
* documentation URL for each category of manual migration task.
*
* The file also exports advanced mapped types (`TodoCategory`, `TodoContextMap`)
* that are inferred directly from the `TODO_NOTES` object. This creates a
* maintainable, type-safe system that ensures consistency across all
* transformers and prevents runtime errors.
*/
/**
* The central configuration for all "TODO" notes. Each key represents a unique
* `TodoCategory`.
*
* Each entry is an object with:
* - `message`: A string or a function that returns a string. If it's a function,
* it receives a `context` object to generate a dynamic message.
* - `url`: An optional documentation URL that will be appended to the message.
*/
export declare const TODO_NOTES: {
readonly pending: {
readonly message: "The pending() function was converted to a skipped test (`it.skip`).";
readonly url: "https://vitest.dev/api/vi.html#it-skip";
};
readonly toHaveSpyInteractions: {
readonly message: string;
};
readonly toThrowMatching: {
readonly message: (context: {
name: string;
}) => string;
readonly url: "https://vitest.dev/api/expect.html#tothrowerror";
};
readonly toBePending: {
readonly message: string;
};
readonly 'unsupported-expect-async-matcher': {
readonly message: (context: {
name: string;
}) => string;
};
readonly 'arrayWithExactContents-dynamic-variable': {
readonly message: "Cannot transform jasmine.arrayWithExactContents with a dynamic variable. Please migrate this manually.";
};
readonly 'arrayWithExactContents-check': {
readonly message: "Verify this matches strict array content (multiset equality). Vitest's arrayContaining is a subset check.";
};
readonly 'expect-nothing': {
readonly message: "expect().nothing() has been removed because it is redundant in Vitest. Tests without assertions pass by default.";
};
readonly 'unsupported-global-function': {
readonly message: (context: {
name: string;
}) => string;
};
readonly addMatchers: {
readonly message: "jasmine.addMatchers is not supported. Please manually migrate to expect.extend().";
readonly url: "https://vitest.dev/api/expect.html#expect-extend";
};
readonly addCustomEqualityTester: {
readonly message: "jasmine.addCustomEqualityTester is not supported. Please manually migrate to expect.addEqualityTesters().";
readonly url: "https://vitest.dev/api/expect.html#expect-addequalitytesters";
};
readonly mapContaining: {
readonly message: string;
};
readonly setContaining: {
readonly message: string;
};
readonly 'unknown-jasmine-property': {
readonly message: (context: {
name: string;
}) => string;
};
readonly spyOnAllFunctions: {
readonly message: string;
readonly url: "https://vitest.dev/api/vi.html#vi-spyon";
};
readonly 'createSpyObj-single-argument': {
readonly message: "jasmine.createSpyObj called with a single argument is not supported for transformation.";
readonly url: "https://vitest.dev/api/vi.html#vi-fn";
};
readonly 'createSpyObj-dynamic-variable': {
readonly message: "Cannot transform jasmine.createSpyObj with a dynamic variable. Please migrate this manually.";
readonly url: "https://vitest.dev/api/vi.html#vi-fn";
};
readonly 'createSpyObj-dynamic-property-map': {
readonly message: "Cannot transform jasmine.createSpyObj with a dynamic property map. Please migrate this manually.";
readonly url: "https://vitest.dev/api/vi.html#vi-fn";
};
readonly 'unsupported-spy-strategy': {
readonly message: (context: {
name: string;
}) => string;
readonly url: "https://vitest.dev/api/mocked.html#mock";
};
readonly 'mostRecent-without-args': {
readonly message: string;
readonly url: "https://vitest.dev/api/mocked.html#mock-lastcall";
};
readonly 'unhandled-done-usage': {
readonly message: "The 'done' callback was used in an unhandled way. Please migrate manually.";
};
};
/**
* A union type of all possible "TODO" categories.
* It is derived from the keys of the `TODO_NOTES` object to ensure that only
* valid categories can be used throughout the transformers.
*/
export type TodoCategory = keyof typeof TODO_NOTES;
/**
* A mapped type that creates a map from a `TodoCategory` to the type of the
* context object that its message function expects. This provides strong type
* safety for calls to `addTodoComment`.
*
* It works by checking if the `message` property for a given category is a
* function. If it is, it uses `infer` to extract the type of the first
* parameter (`P`). If it's not a function, it resolves to `never`.
*
* @example
* // `Context` will be `{ name: string }`
* type Context = TodoContextMap['unknown-jasmine-property'];
*
* // `Context` will be `never`
* type Context = TodoContextMap['pending'];
*/
export type TodoContextMap = {
[K in TodoCategory]: (typeof TODO_NOTES)[K]['message'] extends (context: infer P) => string ? P : never;
};
@@ -0,0 +1,114 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TODO_NOTES = void 0;
/**
* @fileoverview This file is the single source of truth for all "TODO" notes
* generated by the Jasmine to Vitest schematic.
*
* It defines the `TODO_NOTES` constant, which contains the message and optional
* documentation URL for each category of manual migration task.
*
* The file also exports advanced mapped types (`TodoCategory`, `TodoContextMap`)
* that are inferred directly from the `TODO_NOTES` object. This creates a
* maintainable, type-safe system that ensures consistency across all
* transformers and prevents runtime errors.
*/
/**
* The central configuration for all "TODO" notes. Each key represents a unique
* `TodoCategory`.
*
* Each entry is an object with:
* - `message`: A string or a function that returns a string. If it's a function,
* it receives a `context` object to generate a dynamic message.
* - `url`: An optional documentation URL that will be appended to the message.
*/
exports.TODO_NOTES = {
'pending': {
message: 'The pending() function was converted to a skipped test (`it.skip`).',
url: 'https://vitest.dev/api/vi.html#it-skip',
},
'toHaveSpyInteractions': {
message: 'Unsupported matcher ".toHaveSpyInteractions()" found. ' +
'Please migrate this manually by checking the `mock.calls.length` of the individual spies.',
},
'toThrowMatching': {
message: (context) => `Unsupported matcher ".${context.name}()" found. Please migrate this manually.`,
url: 'https://vitest.dev/api/expect.html#tothrowerror',
},
'toBePending': {
message: 'Unsupported matcher ".toBePending()" found. Vitest does not have a direct equivalent. ' +
'Please migrate this manually, for example by using `Promise.race` to check if the promise settles within a short timeout.',
},
'unsupported-expect-async-matcher': {
message: (context) => `Unsupported expectAsync matcher ".${context.name}()" found. Please migrate this manually.`,
},
'arrayWithExactContents-dynamic-variable': {
message: 'Cannot transform jasmine.arrayWithExactContents with a dynamic variable. Please migrate this manually.',
},
'arrayWithExactContents-check': {
message: "Verify this matches strict array content (multiset equality). Vitest's arrayContaining is a subset check.",
},
'expect-nothing': {
message: 'expect().nothing() has been removed because it is redundant in Vitest. Tests without assertions pass by default.',
},
'unsupported-global-function': {
message: (context) => `Unsupported global function \`${context.name}\` found. This function is used for custom reporters in Jasmine ` +
'and has no direct equivalent in Vitest.',
},
'addMatchers': {
message: 'jasmine.addMatchers is not supported. Please manually migrate to expect.extend().',
url: 'https://vitest.dev/api/expect.html#expect-extend',
},
'addCustomEqualityTester': {
message: 'jasmine.addCustomEqualityTester is not supported. Please manually migrate to expect.addEqualityTesters().',
url: 'https://vitest.dev/api/expect.html#expect-addequalitytesters',
},
'mapContaining': {
message: 'jasmine.mapContaining is not supported. Vitest does not have a built-in matcher for Maps.' +
' Please manually assert the contents of the Map.',
},
'setContaining': {
message: 'jasmine.setContaining is not supported. Vitest does not have a built-in matcher for Sets.' +
' Please manually assert the contents of the Set.',
},
'unknown-jasmine-property': {
message: (context) => `Unsupported jasmine property "${context.name}" found. Please migrate this manually.`,
},
'spyOnAllFunctions': {
message: 'Vitest does not have a direct equivalent for jasmine.spyOnAllFunctions().' +
' Please spy on individual methods manually using vi.spyOn().',
url: 'https://vitest.dev/api/vi.html#vi-spyon',
},
'createSpyObj-single-argument': {
message: 'jasmine.createSpyObj called with a single argument is not supported for transformation.',
url: 'https://vitest.dev/api/vi.html#vi-fn',
},
'createSpyObj-dynamic-variable': {
message: 'Cannot transform jasmine.createSpyObj with a dynamic variable. Please migrate this manually.',
url: 'https://vitest.dev/api/vi.html#vi-fn',
},
'createSpyObj-dynamic-property-map': {
message: 'Cannot transform jasmine.createSpyObj with a dynamic property map. Please migrate this manually.',
url: 'https://vitest.dev/api/vi.html#vi-fn',
},
'unsupported-spy-strategy': {
message: (context) => `Unsupported spy strategy ".and.${context.name}()" found. Please migrate this manually.`,
url: 'https://vitest.dev/api/mocked.html#mock',
},
'mostRecent-without-args': {
message: 'Direct usage of mostRecent() is not supported.' +
' Please refactor to access .args directly or use vi.mocked(spy).mock.lastCall.',
url: 'https://vitest.dev/api/mocked.html#mock-lastcall',
},
'unhandled-done-usage': {
message: "The 'done' callback was used in an unhandled way. Please migrate manually.",
},
};
//# sourceMappingURL=todo-notes.js.map
@@ -0,0 +1 @@
{"version":3,"file":"todo-notes.js","sourceRoot":"","sources":["todo-notes.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH;;;;;;;;;;;GAWG;AAEH;;;;;;;;GAQG;AACU,QAAA,UAAU,GAAG;IACxB,SAAS,EAAE;QACT,OAAO,EAAE,qEAAqE;QAC9E,GAAG,EAAE,wCAAwC;KAC9C;IACD,uBAAuB,EAAE;QACvB,OAAO,EACL,wDAAwD;YACxD,2FAA2F;KAC9F;IACD,iBAAiB,EAAE;QACjB,OAAO,EAAE,CAAC,OAAyB,EAAU,EAAE,CAC7C,yBAAyB,OAAO,CAAC,IAAI,0CAA0C;QACjF,GAAG,EAAE,iDAAiD;KACvD;IACD,aAAa,EAAE;QACb,OAAO,EACL,wFAAwF;YACxF,2HAA2H;KAC9H;IACD,kCAAkC,EAAE;QAClC,OAAO,EAAE,CAAC,OAAyB,EAAU,EAAE,CAC7C,qCAAqC,OAAO,CAAC,IAAI,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