Skip to content

Commit

Permalink
Address comments
Browse files Browse the repository at this point in the history
  • Loading branch information
Pessimistress committed Jan 29, 2024
1 parent 48184cf commit d407343
Show file tree
Hide file tree
Showing 9 changed files with 180 additions and 106 deletions.
7 changes: 4 additions & 3 deletions modules/dev-tools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@
"src",
"scripts",
"templates",
"ts-plugins",
"CHANGELOG.md"
],
"exports": {
".": "./src/index.js",
"./configuration": "./src/configuration/index.cjs",
"./ts-transform-version-inline": "./ts-transform-version-inline/index.cjs",
"./ts-transform-append-extension": "./ts-transform-append-extension/index.cjs"
"./ts-transform-version-inline": "./ts-plugins/ts-transform-version-inline/index.cjs",
"./ts-transform-append-extension": "./ts-plugins/ts-transform-append-extension/index.cjs"
},
"types": "./src/index.d.ts",
"main": "./src/index.js",
Expand All @@ -41,7 +42,7 @@
"bootstrap": "yarn install-fast && ocular-bootstrap",
"install-fast": "PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true yarn",
"clean": "echo No build needed",
"build": "echo No build needed",
"build": "tsc && find ./ts-plugins -depth -name \"*.js\" -exec sh -c 'f=\"{}\"; mv -- \"$f\" \"${f%.js}.cjs\"' \\;",
"lint": "npm run lint-yarn",
"lint-yarn": "!(grep -q unpm.u yarn.lock) || (echo 'Please rebuild yarn file using public npmrc' && false)",
"publish-prod": "npm run build && npm run test && npm run test dist && npm publish",
Expand Down
1 change: 1 addition & 0 deletions modules/dev-tools/src/configuration/get-esbuild-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ export async function getCJSExportConfig(opts) {
outfile: opts.output,
bundle: true,
format: 'cjs',
// Node 16 is out of support, kept for compatibility. Move to 18?
target: 'node16',
packages: 'external',
sourcemap: true,
Expand Down
6 changes: 6 additions & 0 deletions modules/dev-tools/src/helpers/get-config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
/**
* Used by command line scripts to print a field from the local ocular config.
Path is period separated.
Example:
$ node get-config.js ".babel.configPath"
*/
import {getOcularConfig} from '../helpers/get-ocular-config.js';

let ocularConfig;
Expand Down
1 change: 1 addition & 0 deletions modules/dev-tools/ts-plugins/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/**
* TypeScript transform to append file extension to import statements in the compiled JS files
* Usage with ts-patch:
{
"plugins": [
{
"transform": "ocular-dev-tools/ts-transform-append-extension",
"extensions": [".js"],
"after": true
}
]
}
* Adapted from https://github.com/murolem/ts-transformer-append-js-extension to support custom extensions
*/
import * as path from 'path';
import type {Program, TransformationContext, SourceFile, Node} from 'typescript';
import type {TransformerExtras, PluginConfig} from 'ts-patch';

type AppendExtensionPluginConfig = PluginConfig & {
/** List of file extensions, for example:
* '.js': applies to paths without an extension, e.g. `import {add} from './math'` => `import {add} from './math.js'`
* '.lib.cjs': applies to paths ending with .lib, e.g. `import fft from './fft.lib` => `import fft from './fft.lib.cjs'`
* @default [".js"]
*/
extensions?: string[];
};

export default function (

Check warning on line 28 in modules/dev-tools/ts-plugins/ts-transform-append-extension/index.ts

View workflow job for this annotation

GitHub Actions / test (18)

Missing return type on function
program: Program,
pluginConfig: AppendExtensionPluginConfig,
{ts}: TransformerExtras
) {
// only append .js when module specifier has no extension or user-provided extensions
const {extensions = ['.js']} = pluginConfig;
const extMappings = new Map<string, string>();
for (const ext of extensions) {
const addition = path.extname(ext) || ext;
const base = path.basename(ext, addition);
extMappings.set(base, addition);
}

function shouldMutateModuleSpecifier(node: Node): string | false {
if (!ts.isImportDeclaration(node) && !ts.isExportDeclaration(node)) return false;
if (node.moduleSpecifier === undefined) return false;
// only when module specifier is valid
if (!ts.isStringLiteral(node.moduleSpecifier)) return false;
// only when path is relative
if (!node.moduleSpecifier.text.startsWith('./') && !node.moduleSpecifier.text.startsWith('../'))
return false;
// only when module specifier has accepted extension
const ext = path.extname(node.moduleSpecifier.text);
if (!extMappings.has(ext)) return false;
return node.moduleSpecifier.text + extMappings.get(ext);
}

return (ctx: TransformationContext) => {
const {factory} = ctx;

return (sourceFile: SourceFile) => {
function visit(node: Node): Node {
const newImportSource = shouldMutateModuleSpecifier(node);
if (newImportSource) {
if (ts.isImportDeclaration(node)) {
const newModuleSpecifier = factory.createStringLiteral(newImportSource);
node = factory.updateImportDeclaration(
node,
node.modifiers,
node.importClause,
newModuleSpecifier,
node.assertClause
);
} else if (ts.isExportDeclaration(node)) {
const newModuleSpecifier = factory.createStringLiteral(newImportSource);
node = factory.updateExportDeclaration(
node,
node.modifiers,
node.isTypeOnly,
node.exportClause,
newModuleSpecifier,
node.assertClause
);
}
}

return ts.visitEachChild(node, visit, ctx);
}

return ts.visitNode(sourceFile, visit);
};
};
}
73 changes: 73 additions & 0 deletions modules/dev-tools/ts-plugins/ts-transform-version-inline/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/**
* TypeScript transform to inject the current version of the package as string.
* Usage with ts-patch:
{
"plugins": [
{
"transform": "ocular-dev-tools/ts-transform-version-inline",
"identifier": "PACKAGE_VERSION"
}
]
}
*/
import * as fs from 'fs';
import * as path from 'path';
import type {Program, TransformationContext, SourceFile, Node} from 'typescript';
import type {TransformerExtras, PluginConfig} from 'ts-patch';

type VersionInlinePluginConfig = PluginConfig & {
/** Identifier name to replace in code.
* @default "__VERSION__"
*/
identifier?: string;
};

export default function (

Check warning on line 25 in modules/dev-tools/ts-plugins/ts-transform-version-inline/index.ts

View workflow job for this annotation

GitHub Actions / test (18)

Missing return type on function
program: Program,
pluginConfig: VersionInlinePluginConfig,
{ts}: TransformerExtras
) {
const {identifier = '__VERSION__'} = pluginConfig;

return (ctx: TransformationContext) => {
const {factory} = ctx;

return (sourceFile: SourceFile) => {
let packageVersion: string | null;

function visit(node: Node): Node {
if (ts.isIdentifier(node) && node.getText() === identifier) {
if (packageVersion === undefined) {
packageVersion = getPackageVersion(sourceFile.fileName);
}
if (packageVersion) {
return factory.createStringLiteral(packageVersion);
}
}
return ts.visitEachChild(node, visit, ctx);
}
return ts.visitNode(sourceFile, visit);
};
};
}

/**
* Retrieve the version string from the closest package.json
*/
function getPackageVersion(fileName: string): string | null {
let currentDir = fileName;
while (currentDir !== '/') {
try {
currentDir = path.dirname(currentDir);
const packageJson = path.join(currentDir, 'package.json');
const stat = fs.statSync(packageJson);
if (stat.isFile()) {
const content = fs.readFileSync(packageJson, 'utf8');
return JSON.parse(content).version as string;

Check warning on line 66 in modules/dev-tools/ts-plugins/ts-transform-version-inline/index.ts

View workflow job for this annotation

GitHub Actions / test (18)

Unsafe member access .version on an `any` value
}
} catch {
// file does not exist, try going up
}
}
return null;
}
51 changes: 0 additions & 51 deletions modules/dev-tools/ts-transform-append-extension/index.cjs

This file was deleted.

48 changes: 0 additions & 48 deletions modules/dev-tools/ts-transform-version-inline/index.cjs

This file was deleted.

8 changes: 4 additions & 4 deletions modules/dev-tools/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"allowJs": true,
"module": "commonjs",
"allowJs": false,
"checkJs": false,
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"noEmit": true,
"baseUrl": ".",
"skipLibCheck": true,
"strict": true
},
"include":[
"src/**/*"
"src/**/*",
"ts-plugins/**/*"
]
}

0 comments on commit d407343

Please sign in to comment.