Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ts-patch

Package Overview
Dependencies
Maintainers
1
Versions
46
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-patch - npm Package Compare versions

Comparing version 3.1.2 to 3.2.0

slice/ts54.d.ts

7

CHANGELOG.md

@@ -5,2 +5,9 @@ # Changelog

## [3.2.0](https://github.com/nonara/ts-patch/compare/v3.1.2...v3.2.0) (2024-06-03)
### Features
* Added support for TS 5.5 ([2c4954d](https://github.com/nonara/ts-patch/commit/2c4954d91def5f0654804bfbf64704720f605840))
### [3.1.2](https://github.com/nonara/ts-patch/compare/v3.1.1...v3.1.2) (2024-01-10)

@@ -7,0 +14,0 @@

2

config.d.ts

@@ -16,6 +16,4 @@ import ts from 'typescript';

export declare const dtsPatchFilePath: string;
export declare const tsWrapperOpen = "var ts = (() => {";
export declare const tsWrapperClose = "})();";
export declare const execTscCmd = "execTsc";
export declare const cachedFilePatchedPrefix = "patched.";
export declare const lockFileDir = "locks";

@@ -6,3 +6,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.lockFileDir = exports.cachedFilePatchedPrefix = exports.execTscCmd = exports.tsWrapperClose = exports.tsWrapperOpen = exports.dtsPatchFilePath = exports.modulePatchFilePath = exports.corePatchName = exports.defaultInstallLibraries = exports.defaultNodePrinterOptions = exports.RESOURCES_PATH = exports.tspPackageJSON = exports.appRoot = void 0;
exports.lockFileDir = exports.cachedFilePatchedPrefix = exports.execTscCmd = exports.dtsPatchFilePath = exports.modulePatchFilePath = exports.corePatchName = exports.defaultInstallLibraries = exports.defaultNodePrinterOptions = exports.RESOURCES_PATH = exports.tspPackageJSON = exports.appRoot = void 0;
const path_1 = __importDefault(require("path"));

@@ -43,5 +43,2 @@ const fs_1 = __importDefault(require("fs"));

exports.dtsPatchFilePath = path_1.default.resolve(exports.appRoot, exports.tspPackageJSON.directories.resources, 'module-patch.d.ts');
// TODO - should do this in a better/dynamic way later
exports.tsWrapperOpen = `var ts = (() => {`;
exports.tsWrapperClose = `})();`;
exports.execTscCmd = 'execTsc';

@@ -48,0 +45,0 @@ // endregion

@@ -10,3 +10,7 @@ import { SourceSection } from './source-section';

getSections(): [sectionName: SourceSection['sectionName'], section: SourceSection | undefined][];
bodyWrapper?: {
start: string;
end: string;
};
}
export declare function getModuleSource(tsModule: TsModule): ModuleSource;

@@ -12,3 +12,3 @@ "use strict";

const moduleFile = tsModule.getUnpatchedModuleFile();
const { firstSourceFileStart, fileEnd, wrapperPos, bodyPos, sourceFileStarts } = (0, module_slice_1.sliceModule)(moduleFile, tsModule.package.version);
const { firstSourceFileStart, fileEnd, wrapperPos, bodyPos, sourceFileStarts, bodyWrapper } = (0, module_slice_1.sliceModule)(moduleFile, tsModule.package.version);
const fileHeaderEnd = wrapperPos?.start ?? firstSourceFileStart;

@@ -31,3 +31,4 @@ return {

];
}
},
bodyWrapper,
};

@@ -34,0 +35,0 @@ }

{
"name": "ts-patch",
"version": "3.1.2",
"version": "3.2.0",
"description": "Patch typescript to support custom transformers in tsconfig.json",

@@ -5,0 +5,0 @@ "main": "./index.js",

@@ -34,2 +34,3 @@ "use strict";

const source = tsModule.getUnpatchedSource();
const { bodyWrapper } = source;
const printableBodyFooters = [];

@@ -54,7 +55,10 @@ const printableFooters = [];

/* Fix early return */
const typescriptSection = source.body.find(s => s.srcFileName === 'src/typescript/typescript.ts');
if (!typescriptSection)
throw new system_1.PatchError(`Could not find Typescript source section`);
typescriptSection.transform([transformers_1.fixTsEarlyReturnTransformer]);
printableBodyFooters.push(`return returnResult;`);
// NOTE - This exists up until TS 5.4, but isn't there for 5.5+
if (tsModule.majorVer <= 5 && tsModule.minorVer <= 4) {
const typescriptSection = source.body.find(s => s.srcFileName === 'src/typescript/typescript.ts');
if (!typescriptSection)
throw new system_1.PatchError(`Could not find Typescript source section`);
typescriptSection.transform([transformers_1.fixTsEarlyReturnTransformer]);
printableBodyFooters.push(`return returnResult;`);
}
}

@@ -67,6 +71,20 @@ /* Patch Program */

/* Add originalCreateProgram to exports */
const namespacesTsSection = source.body.find(s => s.srcFileName === 'src/typescript/_namespaces/ts.ts');
if (!namespacesTsSection)
throw new system_1.PatchError(`Could not find NamespacesTs source section`);
namespacesTsSection.transform([transformers_1.addOriginalCreateProgramTransformer]);
let createProgramAdded = false;
for (const fileName of transformers_1.createProgramExportFiles) {
// As of TS 5.5, we have to handle cases of multiple instances of the same file name. In this case, we need to
// handle both src/typescript/typescript.ts
const sections = source.body.filter(s => s.srcFileName === fileName);
for (const section of sections) {
try {
section.transform([transformers_1.addOriginalCreateProgramTransformer]);
createProgramAdded = true;
}
catch (e) {
if (!(e instanceof system_1.PatchError))
throw e;
}
}
}
if (!createProgramAdded)
throw new system_1.PatchError(`Could not find any of the createProgram export files`);
/* Patch emitter (for diagnostics tools) */

@@ -110,3 +128,4 @@ const emitterSection = source.body.find(s => s.srcFileName === 'src/compiler/watch.ts');

if (shouldWrap) {
list.push([`\n${config_1.tsWrapperOpen}\n`, indentLevel]);
if (bodyWrapper)
list.push([`\n${bodyWrapper.start}\n`, indentLevel]);
indentLevel = 2;

@@ -123,3 +142,4 @@ }

indentLevel = 0;
list.push([`\n${config_1.tsWrapperClose}\n`, indentLevel]);
if (bodyWrapper)
list.push([`\n${bodyWrapper.end}\n`, indentLevel]);
}

@@ -126,0 +146,0 @@ /* File Footer */

import ts from 'typescript';
export declare const createProgramExportFiles: string[];
export declare function addOriginalCreateProgramTransformer(context: ts.TransformationContext): (sourceFile: ts.SourceFile) => ts.SourceFile;

@@ -6,5 +6,17 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.addOriginalCreateProgramTransformer = void 0;
exports.addOriginalCreateProgramTransformer = exports.createProgramExportFiles = void 0;
const typescript_1 = __importDefault(require("typescript"));
const system_1 = require("../../system");
/* ****************************************************************************************************************** */
// region: Config
/* ****************************************************************************************************************** */
exports.createProgramExportFiles = [
/* TS < 5.4 */
'src/typescript/_namespaces/ts.ts',
/* TS >= 5.4 */
'src/server/_namespaces/ts.ts',
'src/typescript/typescript.ts'
];
// endregion
/* ****************************************************************************************************************** */
// region: Utils

@@ -16,15 +28,16 @@ /* ****************************************************************************************************************** */

return (sourceFile) => {
if (sourceFile.fileName !== 'src/typescript/_namespaces/ts.ts')
if (!exports.createProgramExportFiles.includes(sourceFile.fileName))
throw new Error('Wrong emitter file sent to transformer! This should be unreachable.');
const res = factory.updateSourceFile(sourceFile, typescript_1.default.visitNodes(sourceFile.statements, visitNodes));
if (!patchSuccess)
throw new Error('Failed to patch typescript early return!');
throw new system_1.PatchError('Failed to patch typescript originalCreateProgram!');
return res;
function visitNodes(node) {
/* Handle: __export({ ... }) */
if (typescript_1.default.isExpressionStatement(node) &&
typescript_1.default.isCallExpression(node.expression) &&
node.expression.expression.getText() === "__export") {
node.expression.expression.getText() === '__export') {
const exportObjectLiteral = node.expression.arguments[1];
if (typescript_1.default.isObjectLiteralExpression(exportObjectLiteral)) {
const originalCreateProgramProperty = factory.createPropertyAssignment("originalCreateProgram", factory.createArrowFunction(undefined, undefined, [], undefined, factory.createToken(typescript_1.default.SyntaxKind.EqualsGreaterThanToken), factory.createIdentifier("originalCreateProgram")));
const originalCreateProgramProperty = factory.createPropertyAssignment('originalCreateProgram', factory.createArrowFunction(undefined, undefined, [], undefined, factory.createToken(typescript_1.default.SyntaxKind.EqualsGreaterThanToken), factory.createIdentifier('originalCreateProgram')));
const updatedExportObjectLiteral = factory.updateObjectLiteralExpression(exportObjectLiteral, [...exportObjectLiteral.properties, originalCreateProgramProperty]);

@@ -36,2 +49,20 @@ const updatedNode = factory.updateExpressionStatement(node, factory.updateCallExpression(node.expression, node.expression.expression, undefined, [node.expression.arguments[0], updatedExportObjectLiteral]));

}
/* Handle: 1 && (module.exports = { ... }) (ts5.5+) */
if (typescript_1.default.isExpressionStatement(node) && typescript_1.default.isBinaryExpression(node.expression) &&
node.expression.operatorToken.kind === typescript_1.default.SyntaxKind.AmpersandAmpersandToken &&
typescript_1.default.isParenthesizedExpression(node.expression.right) &&
typescript_1.default.isBinaryExpression(node.expression.right.expression) &&
node.expression.right.expression.operatorToken.kind === typescript_1.default.SyntaxKind.EqualsToken &&
typescript_1.default.isPropertyAccessExpression(node.expression.right.expression.left) &&
node.expression.right.expression.left.expression.getText() === 'module' &&
node.expression.right.expression.left.name.getText() === 'exports' &&
typescript_1.default.isObjectLiteralExpression(node.expression.right.expression.right)) {
// Add originalCreateProgram to the object literal
const originalCreateProgramProperty = factory.createShorthandPropertyAssignment('originalCreateProgram');
const updatedObjectLiteral = factory.updateObjectLiteralExpression(node.expression.right.expression.right, [...node.expression.right.expression.right.properties, originalCreateProgramProperty]);
// Update the node
const updatedNode = factory.updateExpressionStatement(node, factory.updateBinaryExpression(node.expression, node.expression.left, node.expression.operatorToken, factory.updateParenthesizedExpression(node.expression.right, factory.updateBinaryExpression(node.expression.right.expression, node.expression.right.expression.left, node.expression.right.expression.operatorToken, updatedObjectLiteral))));
patchSuccess = true;
return updatedNode;
}
return node;

@@ -38,0 +69,0 @@ }

@@ -25,2 +25,6 @@ var tsp = (function () {

tsp.getTmpDir = getTmpDir;
function getTsInstance() {
return (typeof ts !== "undefined" ? ts : module.exports);
}
tsp.getTsInstance = getTsInstance;
class TsPatchError extends Error {

@@ -96,3 +100,4 @@ constructor(message, diagnostic) {

const tsCode = fs.readFileSync(resolvedPath, "utf8");
const jsCode = registerConfig.tsNodeInstance.compile(tsCode, resolvedPath);
const newPath = resolvedPath.replace(/\.ts$/, ".mts");
const jsCode = registerConfig.tsNodeInstance.compile(tsCode, newPath);
const outputFileName = getHash() + ".mjs";

@@ -157,3 +162,3 @@ const outputFilePath = path.join(tsp.getTmpDir("esm"), outputFileName);

pluginFactoryResult = factory(program, cleanConfig, {
ts: ts,
ts: tsp.getTsInstance(),
addDiagnostic,

@@ -566,3 +571,3 @@ removeDiagnostic,

activeProgramTransformers.add(transformerKey);
const newProgram = programTransformer(program, host, config, { ts: ts });
const newProgram = programTransformer(program, host, config, { ts: tsp.getTsInstance() });
if (typeof newProgram?.["emit"] === "function")

@@ -592,4 +597,5 @@ program = newProgram;

get(_, key) {
if (ts) {
return ts[key];
const target = tsp.getTsInstance();
if (target) {
return target[key];
}

@@ -601,3 +607,3 @@ else {

catch (e) {
return undefined;
throw new tsp.TsPatchError(`Failed to find "${key}" in TypeScript shim`, e);
}

@@ -604,0 +610,0 @@ }

@@ -10,2 +10,6 @@ import { ModuleFile } from '../module';

sourceFileStarts: [name: string, position: number][];
bodyWrapper?: {
start: string;
end: string;
};
}

@@ -12,0 +16,0 @@ export declare function sliceModule(moduleFile: ModuleFile, tsVersion: string): ModuleSlice;

@@ -8,3 +8,4 @@ "use strict";

const semver_1 = __importDefault(require("semver"));
const ts5_1 = require("./ts5");
const ts54_1 = require("./ts54");
const ts55_1 = require("./ts55");
// endregion

@@ -15,7 +16,12 @@ /* ****************************************************************************************************************** */

function sliceModule(moduleFile, tsVersion) {
if (semver_1.default.lte(tsVersion, '5.0.0')) {
const baseVersion = semver_1.default.coerce(tsVersion, { includePrerelease: false });
if (!baseVersion)
throw new Error(`Could not parse TS version: ${tsVersion}`);
if (semver_1.default.lt(baseVersion, '5.0.0')) {
throw new Error(`Cannot patch TS version <5`);
}
/* Handle 5+ */
return (0, ts5_1.sliceTs5)(moduleFile);
if (semver_1.default.lt(baseVersion, '5.5.0')) {
return (0, ts54_1.sliceTs54)(moduleFile);
}
return (0, ts55_1.sliceTs55)(moduleFile);
}

@@ -22,0 +28,0 @@ exports.sliceModule = sliceModule;

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc