Skip to content

feat: add transform loader #70

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,21 @@ This allows the installed Amaro to override the Amaro version used by Node.js.
node --experimental-strip-types --import="amaro/register" script.ts
```

Or with the alias:

```bash
node --experimental-strip-types --import="amaro/strip" script.ts
```

Enabling TypeScript feature transformation:

```bash
node --experimental-transform-types --import="amaro/transform" script.ts
```

> Note that the "amaro/transform" loader should be used with `--experimental-transform-types` flag, or
> at least with `--enable-source-maps` flag, to preserve the original source maps.

### How to update SWC

To update the SWC version, run:
Expand Down
24 changes: 0 additions & 24 deletions esbuild.config.js

This file was deleted.

44 changes: 44 additions & 0 deletions esbuild.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { build } from "esbuild";
import { copy } from "esbuild-plugin-copy";

const copyPlugin = copy({
assets: [
{
from: ["./src/register/register-strip.mjs"],
to: ["."],
},
{
from: ["./src/register/register-transform.mjs"],
to: ["."],
},
{
from: ["./lib/LICENSE", "./lib/package.json"],
to: ["."],
},
],
});

await build({
entryPoints: ["src/index.ts"],
bundle: true,
platform: "node",
target: "node22",
outfile: "dist/index.js",
plugins: [copyPlugin],
});

await build({
entryPoints: ["src/strip-loader.ts"],
bundle: false,
outfile: "dist/strip-loader.js",
platform: "node",
target: "node22",
});

await build({
entryPoints: ["src/transform-loader.ts"],
bundle: false,
outfile: "dist/transform-loader.js",
platform: "node",
target: "node22",
});
13 changes: 9 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,27 @@
"ci:fix": "biome check --write",
"prepack": "npm run build",
"postpack": "npm run clean",
"build": "node esbuild.config.js",
"build": "node esbuild.config.mjs",
"typecheck": "tsc --noEmit",
"test": "node --test --experimental-test-snapshots \"**/*.test.js\"",
"test:regenerate": "node --test --experimental-test-snapshots --test-update-snapshots \"**/*.test.js\""
},
"devDependencies": {
"@biomejs/biome": "1.8.3",
"@types/node": "^20.14.11",
"@types/node": "^22.0.0",
"esbuild": "^0.23.0",
"esbuild-plugin-copy": "^2.1.1",
"rimraf": "^6.0.1",
"typescript": "^5.5.3"
},
"exports": {
".": "./dist/index.js",
"./register": "./dist/register.mjs"
"./register": "./dist/register-strip.mjs",
"./strip": "./dist/register-strip.mjs",
"./transform": "./dist/register-transform.mjs"
},
"files": ["dist", "LICENSE.md"]
"files": ["dist", "LICENSE.md"],
"engines": {
"node": ">=22"
}
}
1 change: 0 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
export { transformSync } from "./transform.ts";
export { load } from "./loader.ts";
3 changes: 3 additions & 0 deletions src/register/register-strip.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { register } from "node:module";

register("./strip-loader.js", import.meta.url);
12 changes: 12 additions & 0 deletions src/register/register-transform.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { register } from "node:module";
import { emitWarning, env, execArgv } from "node:process";

const hasSourceMaps =
execArgv.includes("--enable-source-maps") ||
env.NODE_OPTIONS?.includes("--enable-source-maps");

if (!hasSourceMaps) {
emitWarning("Source maps are disabled, stack traces will not accurate");
}

register("./transform-loader.js", import.meta.url);
3 changes: 0 additions & 3 deletions src/register/register.mjs

This file was deleted.

12 changes: 7 additions & 5 deletions src/loader.ts → src/strip-loader.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { LoadFnOutput, LoadHookContext } from "node:module";
import type { Options } from "../lib/wasm";
import { transformSync } from "./index.ts";
import { transformSync } from "./index.js";

type NextLoad = (
url: string,
Expand All @@ -20,14 +20,16 @@ export async function load(
...context,
format: "module",
});
if (source == null)
throw new Error("Source code cannot be null or undefined");
const { code } = transformSync(source.toString(), {
// biome-ignore lint/style/noNonNullAssertion: If module exists, it will have a source
const { code } = transformSync(source!.toString(), {
mode: "strip-only",
} as Options);
return {
format: format.replace("-typescript", ""),
source: code,
// Source map is not necessary in strip-only mode. However, to map the source
// file in debuggers to the original TypeScript source, add a sourceURL magic
// comment to hint that it is a generated source.
source: `${code}\n\n//# sourceURL=${url}`,
};
}
return nextLoad(url, context);
Expand Down
44 changes: 44 additions & 0 deletions src/transform-loader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import type { LoadFnOutput, LoadHookContext } from "node:module";
import type { Options } from "../lib/wasm";
import { transformSync } from "./index.js";

type NextLoad = (
url: string,
context?: LoadHookContext,
) => LoadFnOutput | Promise<LoadFnOutput>;

export async function load(
url: string,
context: LoadHookContext,
nextLoad: NextLoad,
) {
const { format } = context;
if (format.endsWith("-typescript")) {
// Use format 'module' so it returns the source as-is, without stripping the types.
// Format 'commonjs' would not return the source for historical reasons.
const { source } = await nextLoad(url, {
...context,
format: "module",
});

// biome-ignore lint/style/noNonNullAssertion: If module exists, it will have a source
const { code, map } = transformSync(source!.toString(), {
mode: "transform",
sourceMap: true,
filename: url,
} as Options);

let output = code;

if (map) {
const base64SourceMap = Buffer.from(map).toString("base64");
output = `${code}\n\n//# sourceMappingURL=data:application/json;base64,${base64SourceMap}`;
}

return {
format: format.replace("-typescript", ""),
source: `${output}\n\n//# sourceURL=${url}`,
};
}
return nextLoad(url, context);
}
4 changes: 4 additions & 0 deletions test/fixtures/stacktrace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
enum Foo {
A = "Hello, TypeScript!",
}
throw new Error(Foo.A);
48 changes: 44 additions & 4 deletions test/loader.test.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
const { spawnPromisified, fixturesPath } = require("./util/util.js");
const { test } = require("node:test");
const { match, strictEqual } = require("node:assert");
const { match, doesNotMatch, strictEqual } = require("node:assert");

test("should work as a loader", async () => {
const result = await spawnPromisified(process.execPath, [
"--experimental-strip-types",
"--no-warnings",
"--import=./dist/register.mjs",
"--import=./dist/register-strip.mjs",
fixturesPath("hello.ts"),
]);

Expand All @@ -15,15 +15,55 @@ test("should work as a loader", async () => {
strictEqual(result.code, 0);
});

test("should work with enums", async () => {
test("should not work with enums", async () => {
const result = await spawnPromisified(process.execPath, [
"--experimental-strip-types",
"--no-warnings",
"--import=./dist/register.mjs",
"--import=./dist/register-strip.mjs",
fixturesPath("enum.ts"),
]);

strictEqual(result.stdout, "");
match(result.stderr, /TypeScript enum is not supported in strip-only mode/);
strictEqual(result.code, 1);
});

test("should work with enums", async () => {
const result = await spawnPromisified(process.execPath, [
"--experimental-strip-types",
"--no-warnings",
"--import=./dist/register-transform.mjs",
fixturesPath("enum.ts"),
]);

match(result.stdout, /Hello, TypeScript!/);
strictEqual(result.stderr, "");
strictEqual(result.code, 0);
});

test("should warn and inaccurate stracktrace", async () => {
const result = await spawnPromisified(process.execPath, [
"--experimental-strip-types",
"--import=./dist/register-transform.mjs",
fixturesPath("stacktrace.ts"),
]);

strictEqual(result.stdout, "");
match(result.stderr, /Source maps are disabled/);
match(result.stderr, /stacktrace.ts:5:7/); // inaccurate
strictEqual(result.code, 1);
});

test("should not warn and accurate stracktrace", async () => {
const result = await spawnPromisified(process.execPath, [
"--experimental-strip-types",
"--enable-source-maps",
"--import=./dist/register-transform.mjs",
fixturesPath("stacktrace.ts"),
]);

doesNotMatch(result.stderr, /Source maps are disabled/);
strictEqual(result.stdout, "");
match(result.stderr, /stacktrace.ts:4:7/); // accurate
strictEqual(result.code, 1);
});
Loading