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

@travetto/transformer

Package Overview
Dependencies
Maintainers
1
Versions
146
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@travetto/transformer - npm Package Compare versions

Comparing version 2.0.0-alpha.2 to 2.0.0-alpha.3

31

package.json
{
"author": {
"email": "travetto.framework@gmail.com",
"name": "Travetto Framework"
},
"publishConfig": {
"access": "public"
},
"dependencies": {
"@travetto/base": "^2.0.0-alpha.2"
},
"title": "Transformation",
"name": "@travetto/transformer",
"displayName": "Transformation",
"version": "2.0.0-alpha.3",
"description": "Functionality for AST transformations, with transformer registration, and general utils",
"homepage": "https://travetto.io",
"keywords": [

@@ -20,4 +11,8 @@ "typescript",

],
"homepage": "https://travetto.io",
"license": "MIT",
"main": "index.ts",
"author": {
"email": "travetto.framework@gmail.com",
"name": "Travetto Framework"
},
"files": [

@@ -29,3 +24,3 @@ "index.ts",

],
"name": "@travetto/transformer",
"main": "index.ts",
"repository": {

@@ -35,4 +30,8 @@ "url": "https://github.com/travetto/travetto.git",

},
"version": "2.0.0-alpha.2",
"gitHead": "9cc3d202bb120b47f0918a4f94ebbd7875d87101"
"dependencies": {
"@travetto/base": "2.0.0-alpha.3"
},
"publishConfig": {
"access": "public"
}
}

@@ -1,3 +0,3 @@

<!-- This file was generated by the framweork and should not be modified directly -->
<!-- Please modify https://github.com/travetto/travetto/tree/master/module/transformer/doc.ts and execute "npm run docs" to rebuild -->
<!-- This file was generated by @travetto/doc and should not be modified directly -->
<!-- Please modify https://github.com/travetto/travetto/tree/master/module/transformer/doc.ts and execute "npx trv doc" to rebuild -->
# Transformation

@@ -33,3 +33,3 @@ ## Functionality for AST transformations, with transformer registration, and general utils

static handleProperty(state: TransformerState, node: ts.PropertyDeclaration) {
if (!state.source.fileName.includes(`upper/src`)) {
if (!state.source.fileName.includes('doc/src')) {
return node;

@@ -50,3 +50,3 @@ }

static handleClass(state: TransformerState, node: ts.ClassDeclaration) {
if (!state.source.fileName.includes(`upper/src`)) {
if (!state.source.fileName.includes('doc/src')) {
return node;

@@ -67,3 +67,3 @@ }

static handleMethod(state: TransformerState, node: ts.MethodDeclaration) {
if (!state.source.fileName.includes(`upper/src`)) {
if (!state.source.fileName.includes('doc/src')) {
return node;

@@ -70,0 +70,0 @@ }

import * as ts from 'typescript';
import { basename } from 'path';
import { basename, dirname, relative } from 'path';
import { FsUtil } from '@travetto/boot';
import { SystemUtil } from '@travetto/base/src/internal/system';
import { PathUtil } from '@travetto/boot';
import { ModuleUtil } from '@travetto/boot/src/internal/module-util';

@@ -17,9 +17,9 @@ import { AnyType, ExternalType } from './resolver/types';

private newImports = new Map<string, Import>();
private imports: Map<string, Import>;
private idx: Record<string, number> = {};
private ids = new Map<string, string>();
#newImports = new Map<string, Import>();
#imports: Map<string, Import>;
#idx: Record<string, number> = {};
#ids = new Map<string, string>();
constructor(public source: ts.SourceFile, public factory: ts.NodeFactory) {
this.imports = ImportUtil.collectImports(source);
this.#imports = ImportUtil.collectImports(source);
}

@@ -31,7 +31,7 @@

getId(file: string) {
if (!this.ids.has(file)) {
if (!this.#ids.has(file)) {
const key = basename(file).replace(/[.][^.]*$/, '').replace(/[^A-Za-z0-9]+/g, '_');
this.ids.set(file, `ᚕ_${key}_${this.idx[key] = (this.idx[key] || 0) + 1}`);
this.#ids.set(file, `ᚕ_${key}_${this.#idx[key] = (this.#idx[key] || 0) + 1}`);
}
return this.ids.get(file)!;
return this.#ids.get(file)!;
}

@@ -43,9 +43,21 @@

importFile(file: string, base?: string) {
file = SystemUtil.convertFileToModule(file, base);
file = ModuleUtil.normalizePath(file);
if (!file.endsWith('.d.ts') && !this.newImports.has(file)) {
// Handle relative imports
if (file.startsWith('.') && base &&
!base.startsWith('@travetto') && !base.includes('node_modules')
) { // Relative path
const fileDir = dirname(PathUtil.resolveUnix(file));
const baseDir = dirname(PathUtil.resolveUnix(base));
file = `${relative(baseDir, fileDir) || '.'}/${basename(file)}`;
if (/^[A-Za-z]/.test(file)) {
file = `./${file}`;
}
}
if (!file.endsWith('.d.ts') && !this.#newImports.has(file)) {
const id = this.getId(file);
if (this.imports.has(id)) { // Already imported, be cool
return this.imports.get(id)!;
if (this.#imports.has(id)) { // Already imported, be cool
return this.#imports.get(id)!;
}

@@ -55,6 +67,6 @@

const imprt = { path: file, ident };
this.imports.set(ident.escapedText.toString(), imprt);
this.newImports.set(file, imprt);
this.#imports.set(ident.escapedText.toString(), imprt);
this.#newImports.set(file, imprt);
}
return this.newImports.get(file)!;
return this.#newImports.get(file)!;
}

@@ -84,3 +96,3 @@

finalizeNewImports(file: ts.SourceFile) {
if (!this.newImports.size) {
if (!this.#newImports.size) {
return;

@@ -90,3 +102,3 @@ }

try {
const importStmts = [...this.newImports.values()].map(({ path, ident }) => {
const importStmts = [...this.#newImports.values()].map(({ path, ident }) => {
const imptStmt = this.factory.createImportDeclaration(

@@ -105,3 +117,3 @@ undefined, undefined,

} catch (err) { // Missing import
const out = new Error(`${err.message} in ${file.fileName.replace(FsUtil.cwd, '.')}`);
const out = new Error(`${err.message} in ${file.fileName.replace(PathUtil.cwd, '.')}`);
out.stack = err.stack;

@@ -126,3 +138,3 @@ throw out;

} else {
const { ident } = this.imports.get(type.source) ?? this.importFile(type.source, this.source.fileName);
const { ident } = this.#imports.get(type.source) ?? this.importFile(type.source, this.source.fileName);
return factory.createPropertyAccessExpression(ident, type.name!);

@@ -129,0 +141,0 @@ }

@@ -5,3 +5,3 @@ /* eslint-disable no-bitwise */

import { FsUtil } from '@travetto/boot';
import { PathUtil } from '@travetto/boot';
import { Util } from '@travetto/base';

@@ -57,4 +57,8 @@

let resolvedType = type;
if ('target' in resolvedType && resolvedType['target']) {
resolvedType = resolvedType['target'] as ts.Type;
if (CoreUtil.hasTarget(resolvedType)) {
resolvedType = resolvedType.target;
// If resolved target has a concrete type
if (DocUtil.readDocTag(resolvedType, 'concrete').length) {
return { category: 'concrete', type: resolvedType };
}
}

@@ -214,6 +218,6 @@

} else if (source.startsWith('.')) {
source = FsUtil.resolveUnix(dirname(sourceFile), source);
source = PathUtil.resolveUnix(dirname(sourceFile), source);
}
return { key: 'external', name, source: FsUtil.resolveUnix(sourceFile, source) };
return { key: 'external', name, source: PathUtil.resolveUnix(sourceFile, source) };
}

@@ -220,0 +224,0 @@ }

@@ -12,5 +12,17 @@ import * as ts from 'typescript';

export class TypeResolver implements Checker {
constructor(private tsChecker: ts.TypeChecker) { }
#tsChecker: ts.TypeChecker;
constructor(tsChecker: ts.TypeChecker) {
this.#tsChecker = tsChecker;
}
/**
* Get type checker
* @private
*/
getChecker() {
return this.#tsChecker;
}
/**
* Get type from element

@@ -20,3 +32,3 @@ * @param el

getType(el: ts.Type | ts.Node) {
return 'getSourceFile' in el ? this.tsChecker.getTypeAtLocation(el as ts.Node) : el;
return 'getSourceFile' in el ? this.#tsChecker.getTypeAtLocation(el as ts.Node) : el;
}

@@ -28,3 +40,3 @@

getAllTypeArguments(ref: ts.Type): ts.Type[] {
return this.tsChecker.getTypeArguments(ref as ts.TypeReference) as ts.Type[];
return this.#tsChecker.getTypeArguments(ref as ts.TypeReference) as ts.Type[];
}

@@ -38,3 +50,3 @@

const [sig] = type.getCallSignatures();
return this.tsChecker.getReturnTypeOfSignature(sig);
return this.#tsChecker.getReturnTypeOfSignature(sig);
}

@@ -46,3 +58,3 @@

getTypeAsString(type: ts.Type) {
return this.tsChecker.typeToString(this.tsChecker.getApparentType(type)) || undefined;
return this.#tsChecker.typeToString(this.#tsChecker.getApparentType(type)) || undefined;
}

@@ -54,3 +66,3 @@

getPropertiesOfType(type: ts.Type) {
return this.tsChecker.getPropertiesOfType(type);
return this.#tsChecker.getPropertiesOfType(type);
}

@@ -69,3 +81,3 @@

const { category, type } = TypeCategorize(this.tsChecker, resType);
const { category, type } = TypeCategorize(this.#tsChecker, resType);
const { build, finalize } = TypeBuilder[category];

@@ -110,3 +122,3 @@

} catch (err) {
console.error(`Unable to resolve type`, err.stack);
console.error('Unable to resolve type', err.stack);
return { key: 'literal', ctor: Object, name: 'object' };

@@ -113,0 +125,0 @@ }

@@ -1,2 +0,2 @@

import ts = require('typescript');
import type * as ts from 'typescript';

@@ -3,0 +3,0 @@ /**

import * as ts from 'typescript';
import { SystemUtil } from '@travetto/base/src/internal/system';
import { SystemUtil } from '@travetto/boot/src/internal/system';
import { ModuleUtil } from '@travetto/boot/src/internal/module-util';
import { Util } from '@travetto/base';

@@ -30,6 +31,7 @@

private resolver: TypeResolver;
private imports: ImportManager;
private syntheticIdentifiers = new Map<string, ts.Identifier>();
private decorators = new Map<string, ts.PropertyAccessExpression>();
#resolver: TypeResolver;
#imports: ImportManager;
#syntheticIdentifiers = new Map<string, ts.Identifier>();
#decorators = new Map<string, ts.PropertyAccessExpression>();
added = new Map<number, ts.Statement[]>();

@@ -39,12 +41,20 @@ module: string;

constructor(public source: ts.SourceFile, public factory: ts.NodeFactory, checker: ts.TypeChecker) {
this.imports = new ImportManager(source, factory);
this.resolver = new TypeResolver(checker);
this.module = SystemUtil.convertFileToModule(this.source.fileName);
this.#imports = new ImportManager(source, factory);
this.#resolver = new TypeResolver(checker);
this.module = ModuleUtil.normalizePath(this.source.fileName);
}
/**
* Allow access to resolver
* @private
*/
getResolver() {
return this.#resolver;
}
/**
* Get or import the node or external type
*/
getOrImport(type: ExternalType) {
return this.imports.getOrImport(this.factory, type);
return this.#imports.getOrImport(this.factory, type);
}

@@ -56,3 +66,3 @@

importFile(file: string) {
return this.imports.importFile(file);
return this.#imports.importFile(file);
}

@@ -64,4 +74,4 @@

resolveType(node: ts.Type | ts.Node) {
const resolved = this.resolver.resolveType(node);
this.imports.importFromResolved(resolved);
const resolved = this.#resolver.resolveType(node);
this.#imports.importFromResolved(resolved);
return resolved;

@@ -97,3 +107,3 @@ }

resolveReturnType(node: ts.MethodDeclaration) {
return this.resolveType(this.resolver.getReturnType(node));
return this.resolveType(this.#resolver.getReturnType(node));
}

@@ -105,3 +115,3 @@

readDocTag(node: ts.Declaration, name: string) {
return DocUtil.readDocTag(this.resolver.getType(node), name);
return DocUtil.readDocTag(this.#resolver.getType(node), name);
}

@@ -113,8 +123,8 @@

importDecorator(pth: string, name: string) {
if (!this.decorators.has(`${pth}:${name}`)) {
const ref = this.imports.importFile(pth);
if (!this.#decorators.has(`${pth}:${name}`)) {
const ref = this.#imports.importFile(pth);
const ident = this.factory.createIdentifier(name);
this.decorators.set(name, this.factory.createPropertyAccessExpression(ref.ident, ident));
this.#decorators.set(name, this.factory.createPropertyAccessExpression(ref.ident, ident));
}
return this.decorators.get(name);
return this.#decorators.get(name);
}

@@ -127,3 +137,3 @@

this.importDecorator(pth, name);
return CoreUtil.createDecorator(this.factory, this.decorators.get(name)!, ...contents);
return CoreUtil.createDecorator(this.factory, this.#decorators.get(name)!, ...contents);
}

@@ -137,19 +147,19 @@

const decl = DeclarationUtil.getPrimaryDeclarationNode(
this.resolver.getType(ident)
this.#resolver.getType(ident)
);
return ({
return {
dec,
ident,
file: decl?.getSourceFile().fileName,
module: SystemUtil.convertFileToModule(decl?.getSourceFile().fileName), // All decorators will be absolute
targets: DocUtil.readAugments(this.resolver.getType(ident)),
module: decl ? ModuleUtil.normalizePath(decl.getSourceFile().fileName) : undefined, // All #decorators will be absolute
targets: DocUtil.readAugments(this.#resolver.getType(ident)),
name: ident ?
ident.escapedText! as string :
undefined
});
};
}
/**
* Get list of all decorators for a node
* Get list of all #decorators for a node
*/

@@ -166,3 +176,3 @@ getDecoratorList(node: ts.Node): DecoratorMeta[] {

getDeclarations(node: ts.Node): ts.Declaration[] {
return DeclarationUtil.getDeclarations(this.resolver.getType(node));
return DeclarationUtil.getDeclarations(this.#resolver.getType(node));
}

@@ -198,3 +208,3 @@

finalize(ret: ts.SourceFile) {
ret = this.imports.finalize(ret);
ret = this.#imports.finalize(ret);
return ret;

@@ -299,8 +309,8 @@ }

let exists = true;
if (!this.syntheticIdentifiers.has(id)) {
this.syntheticIdentifiers.set(id, this.factory.createIdentifier(id));
if (!this.#syntheticIdentifiers.has(id)) {
this.#syntheticIdentifiers.set(id, this.factory.createIdentifier(id));
exists = false;
}
return [this.syntheticIdentifiers.get(id), exists] as [id: ts.Identifier, exists: boolean];
return [this.#syntheticIdentifiers.get(id), exists] as [id: ts.Identifier, exists: boolean];
}
}

@@ -11,6 +11,13 @@ import * as ts from 'typescript';

static hasOriginal(o: ts.Node): o is (ts.Node & { original: ts.Node }) {
return 'original' in o && !!o['original'];
return 'original' in o && !!(o as { original?: ts.Node }).original;
}
/**
* See if type has target
*/
static hasTarget(o: ts.Type): o is (ts.Type & { target: ts.Type }) {
return 'target' in o && !!(o as { target?: ts.Type }).target;
}
/**
* Get first line of method body

@@ -55,3 +62,7 @@ * @param m

static getSymbol(type: ts.Type | ts.Symbol) {
return 'valueDeclaration' in type ? type : (type.aliasSymbol ?? type.symbol);
if ('valueDeclaration' in type) {
return type;
} else {
return (type as ts.TypeReference).aliasSymbol ?? (type as ts.Type).symbol;
}
}

@@ -95,2 +106,10 @@

}
/**
* Is declaration abstract?
*/
static isAbstract(node: ts.Declaration) {
// eslint-disable-next-line no-bitwise
return !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Abstract);
}
}
import * as ts from 'typescript';
import { DeclDocumentation } from '../types/shared';

@@ -18,2 +19,9 @@ import { CoreUtil } from './core';

/**
* Read doc comment for node
*/
static getDocComment(o: ts.JSDoc | ts.JSDocTag, def?: string) {
return (typeof o.comment === 'string' ? o.comment : undefined) ?? def;
}
/**
* Read JS Docs from a `ts.Declaration`

@@ -42,3 +50,3 @@ */

if (ts.isJSDoc(top)) {
out.description = top.comment;
out.description = this.getDocComment(top, out.description);
}

@@ -50,7 +58,7 @@ }

if (ts.isJSDocReturnTag(tag)) {
out.return = tag.comment;
out.return = this.getDocComment(tag, out.return);
} else if (ts.isJSDocParameterTag(tag)) {
out.params!.push({
name: tag.name && tag.name.getText(),
description: tag.comment ?? ''
description: this.getDocComment(tag, '')!
});

@@ -70,4 +78,4 @@ }

return tags
.filter(el => el.name === name)
.map(el => el.text!);
.filter(el => el.name === name && !!el.text)
.map(el => el.text!.map(x => x.text).join('')); // Join all text
}

@@ -74,0 +82,0 @@

import * as ts from 'typescript';
import { resolve as pathResolve } from 'path';
import { FsUtil } from '@travetto/boot';
import { PathUtil } from '@travetto/boot';

@@ -29,3 +29,3 @@ import { Import } from '../types/shared';

const pth = require.resolve(src.fileName);
const base = FsUtil.toUnix(pth);
const base = PathUtil.toUnix(pth);

@@ -32,0 +32,0 @@ const imports = new Map<string, Import>();

@@ -36,10 +36,14 @@ import * as ts from 'typescript';

private transformers = new Map<TransformerType, TransformerSet<S>>();
#transformers = new Map<TransformerType, TransformerSet<S>>();
#logTarget: string;
#getState: (context: ts.TransformationContext, src: ts.SourceFile) => S;
constructor(
private getState: (context: ts.TransformationContext, src: ts.SourceFile) => S,
getState: (context: ts.TransformationContext, src: ts.SourceFile) => S,
transformers: NodeTransformer<S, TransformerType, ts.Node>[],
private logTarget = 'compiler.log'
logTarget = 'compiler.log'
) {
this.init(transformers);
this.#logTarget = logTarget;
this.#getState = getState;
this.#init(transformers);
}

@@ -50,8 +54,8 @@

*/
private init(transformers: NodeTransformer<S, TransformerType, ts.Node>[]) {
#init(transformers: NodeTransformer<S, TransformerType, ts.Node>[]) {
for (const trn of transformers) {
if (!this.transformers.has(trn.type)) {
this.transformers.set(trn.type, {});
if (!this.#transformers.has(trn.type)) {
this.#transformers.set(trn.type, {});
}
const set = this.transformers.get(trn.type)!;
const set = this.#transformers.get(trn.type)!;
const targets = trn.target && trn.target.length ? trn.target : ['ALL'];

@@ -82,3 +86,3 @@

const c = new console.Console({
stdout: fs.createWriteStream(AppCache.toEntryName(this.logTarget), { flags: 'a' }),
stdout: fs.createWriteStream(AppCache.toEntryName(this.#logTarget), { flags: 'a' }),
inspectOptions: { depth: 4 },

@@ -92,3 +96,3 @@ });

console.debug('Processing', { file: file.fileName, pid: process.pid });
const state = this.getState(context, file);
const state = this.#getState(context, file);
let ret = this.visit(state, context, file);

@@ -177,3 +181,3 @@

const targetType = VisitorFactory.nodeToType(node)!;
const target = this.transformers.get(targetType);
const target = this.#transformers.get(targetType);

@@ -180,0 +184,0 @@ if (!target) {

@@ -1,2 +0,2 @@

import { TranspileUtil } from '@travetto/boot';
import { SourceUtil } from '@travetto/boot/src/internal/source-util';

@@ -16,2 +16,3 @@ declare const global: { ts: unknown }; // Used for transformers

get(t, p, r) {
// Load Synchronously
return (global.ts = require('typescript'))[p]; // Overwrite

@@ -22,3 +23,3 @@ }

// Drop typescript import, and use global. Great speedup;
TranspileUtil.addPreProcessor((name, contents) => {
SourceUtil.addPreProcessor((_, contents) => {
contents = contents.replace(/^import\s+[*]\s+as\s+ts\s+from\s+'typescript'/mg, x => `// ${x}`);

@@ -25,0 +26,0 @@ return contents;

@@ -16,10 +16,7 @@ import * as ts from 'typescript';

static async compile(folder: string, file?: string) {
let tsconfig = FsUtil.resolveUnix(folder, 'tsconfig.json');
if (!FsUtil.existsSync(tsconfig)) {
tsconfig = FsUtil.resolveUnix(__dirname, '..', '..', 'node_modules', '@travetto', 'boot', 'tsconfig.json');
}
const tsconfigObj = await import('@travetto/boot/tsconfig.trv.json');
const prog = ts.createProgram({
options: ts.convertCompilerOptionsFromJson(require(tsconfig), tsconfig).options,
options: ts.convertCompilerOptionsFromJson(tsconfigObj, '').options,
rootNames: (await ScanFs.scanDir({ testFile: f => f.startsWith('src/') && f.endsWith('.ts') }, folder))

@@ -34,8 +31,10 @@ .filter(x => x.stats.isFile())

const transformers =
(await ScanFs.scanDir({ testFile: f => f.startsWith('support/transformer') }, folder))
.filter(x => x.stats.isFile())
.map(x => import(x.file).then(getAllTransformers));
const visitor = new VisitorFactory(
(ctx, src) => new TransformerState(src, ctx.factory, prog.getTypeChecker()),
(await ScanFs.scanDir({ testFile: f => f.startsWith('support/transformer') }, folder))
.filter(x => x.stats.isFile())
.map(x => getAllTransformers(require(x.file)))
.flat(),
(await Promise.all(transformers)).flat(),
log

@@ -51,3 +50,5 @@ );

await new Promise((res) => setTimeout(res, 1000)); // Wait for file buffer to sync
console.info(fs.readFileSync(log, 'utf8'));
try {
console.info(fs.readFileSync(log, 'utf8'));
} catch { }

@@ -54,0 +55,0 @@ await FsUtil.unlinkRecursive(log, true);

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