Skip to content
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
9 changes: 9 additions & 0 deletions .changeset/quiet-flags-transform.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'zile': patch
---

Added `package.json#zile.transform`, which names a module whose default export rewrites each emitted JavaScript file.

```js
export default (code, file) => code.replaceAll('process.env.DEBUG', 'false')
```
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,33 @@ Use keys with `.src` suffix to indicate source files:
> }
> ```

### `zile.transform`

The `zile.transform` field names a module that rewrites each emitted JavaScript file. Zile runs it after `tsc` emits the output.

```diff
{
"name": "my-pkg",
"version": "0.0.0",
"type": "module",
"main": "./src/index.ts",
+ "zile": {
+ "transform": "./transform.js"
+ }
}
```

The module's default export receives the code of a `.js`, `.mjs`, or `.cjs` file and its output path relative to the package directory, such as `dist/index.js`. It returns, or resolves to, the new code.

```js
// transform.js
export default (code, file) => code.replaceAll('process.env.DEBUG', 'false')
```

- **Resolution**: The specifier resolves from the package directory, so it can be a relative path or a package export such as `my-flags/zile`.
- **Source maps**: Zile leaves `.js.map` files unchanged, so mappings can shift on lines that the transform changes.
- **`zile dev`**: The transform does not run. Link mode does not emit JavaScript, so the output resolves to the unchanged source.

### Additional Fields

Zile also sets these fields if not already present:
Expand Down
38 changes: 38 additions & 0 deletions src/Package.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,44 @@ if (!fs.existsSync(started)) {
})
})

describe('Package.readTransform', () => {
test('returns undefined when not set', async () => {
expect(await Package.readTransform({ cwd: process.cwd(), pkgJson: {} })).toBeUndefined()
})

test('resolves a package export with ESM conditions', async () => {
const cwd = path.resolve(import.meta.dirname, '.tmp', crypto.randomUUID())
const pkgDir = path.resolve(cwd, 'node_modules', 'my-flags')
await fs.mkdir(pkgDir, { recursive: true })
await fs.writeFile(
path.resolve(pkgDir, 'package.json'),
JSON.stringify({
name: 'my-flags',
type: 'module',
exports: { './zile': { import: './zile.js' } },
}),
)
await fs.writeFile(path.resolve(pkgDir, 'zile.js'), 'export default (code) => code + "!"')
const transform = await Package.readTransform({
cwd,
pkgJson: { zile: { transform: 'my-flags/zile' } },
})
expect(await transform?.('a', 'dist/index.js')).toBe('a!')
expect(await fs.readdir(cwd)).toEqual(['node_modules'])
})

test('throws when the default export is not a function', async () => {
const cwd = path.resolve(import.meta.dirname, '.tmp', crypto.randomUUID())
await fs.mkdir(cwd, { recursive: true })
await fs.writeFile(path.resolve(cwd, 'transform.js'), 'export default {}')
await expect(
Package.readTransform({ cwd, pkgJson: { zile: { transform: './transform.js' } } }),
).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: \`./transform.js\` on \`package.json#zile.transform\` must default export a function]`,
)
})
})

describe('Package.getSourceDir', () => {
test('common', async () => {
{
Expand Down
47 changes: 47 additions & 0 deletions src/Package.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as crypto from 'node:crypto'
import * as fsSync from 'node:fs'
import * as fs from 'node:fs/promises'
import * as path from 'node:path'
import * as url from 'node:url'
import * as Tsconfig from 'tsconfck'
import type { PackageJson, TsConfigJson } from 'type-fest'

Expand Down Expand Up @@ -31,8 +32,15 @@ export async function build(options: build.Options): Promise<build.ReturnType> {
const sourceDir = getSourceDir({ cwd, sources })

if (!link) {
const transform = await readTransform({ cwd, pkgJson })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Load the transform after transpilation

When a relative transform such as ./dist/transform.js is itself emitted by the package—or the transform imports another generated file—a clean build fails during module loading because readTransform runs before transpile creates those files. Resolve and import the transform after transpilation, immediately before applying it to the emitted JavaScript.

Useful? React with 👍 / 👎.

const result = await transpile({ cwd, sources, sourceDir, tsgo })
tsConfig = result.tsConfig
if (transform)
for await (const file of fs.glob('**/*.{js,mjs,cjs}', { cwd: outDir })) {
const filePath = path.resolve(outDir, file)
const code = await fs.readFile(filePath, 'utf-8')
await fs.writeFile(filePath, await transform(code, path.relative(cwd, filePath)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Normalize callback paths across platforms

On Windows, path.relative returns a path such as dist\index.js, while the documented callback contract shows package-relative paths such as dist/index.js. Transforms that select files using the documented slash-separated value therefore silently skip their replacements on Windows; normalize the callback path to forward slashes before invoking the transform.

Useful? React with 👍 / 👎.

}
}

await copyAssets({ assets, cwd, outDir, sourceDir })
Expand Down Expand Up @@ -612,6 +620,45 @@ export declare namespace getSourceDir {
}
}

/**
* Reads the transform function of the module named by `package.json#zile.transform`.
*
* @param options - Options for reading the transform.
* @returns Transform function, or `undefined` if `zile.transform` is not set.
*/
export async function readTransform(
options: readTransform.Options,
): Promise<readTransform.ReturnType> {
const { cwd, pkgJson } = options

const specifier = (pkgJson.zile as { transform?: string } | undefined)?.transform
if (!specifier) return undefined

// Re-exports from the package directory so the specifier resolves with ESM conditions.
const tmpModule = path.resolve(
cwd,
`zile.transform.${process.pid}.${crypto.randomUUID()}.tmp.mjs`,
)
await fs.writeFile(tmpModule, `export { default } from ${JSON.stringify(specifier)}\n`)
const module = await import(url.pathToFileURL(tmpModule).href).finally(() => fs.rm(tmpModule))
if (typeof module.default !== 'function')
throw new Error(
`\`${specifier}\` on \`package.json#zile.transform\` must default export a function`,
)
return module.default
}

export declare namespace readTransform {
type Options = {
/** Working directory. */
cwd: string
/** Package.json file. */
pkgJson: PackageJson
}

type ReturnType = ((code: string, file: string) => string | Promise<string>) | undefined
}

/**
* Reads the package.json file from the given working directory.
*
Expand Down
4 changes: 4 additions & 0 deletions src/Packages.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ describe('Packages.find', () => {
[
"/",
"/test/repos/wildcard-exports",
"/test/repos/transform",
"/test/repos/single-entrypoint",
"/test/repos/multiple-entrypoint",
"/test/repos/error-module-resolution",
Expand Down Expand Up @@ -50,6 +51,7 @@ describe('Packages.find', () => {
expect(relative(result)).toMatchInlineSnapshot(`
[
"/test/repos/wildcard-exports",
"/test/repos/transform",
"/test/repos/single-entrypoint",
"/test/repos/multiple-entrypoint",
"/test/repos/error-module-resolution",
Expand Down Expand Up @@ -103,6 +105,7 @@ describe('Packages.find', () => {
expect(relative(result)).toMatchInlineSnapshot(`
[
"/test/repos/wildcard-exports",
"/test/repos/transform",
"/test/repos/single-entrypoint",
"/test/repos/multiple-entrypoint",
"/test/repos/error-module-resolution",
Expand Down Expand Up @@ -179,6 +182,7 @@ describe('Packages.find', () => {
[
"/",
"/test/repos/wildcard-exports",
"/test/repos/transform",
"/test/repos/single-entrypoint",
"/test/repos/multiple-entrypoint",
"/test/repos/error-module-resolution",
Expand Down
98 changes: 98 additions & 0 deletions src/__snapshots__/Cli.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -763,6 +763,104 @@ exports[`'/single-entrypoint': Cli.run > link > output 1`] = `

exports[`'/single-entrypoint': Cli.run > link > types-target 1`] = `"../index.ts"`;

exports[`'/transform': Cli.run > default > main 1`] = `
"// dist/index.js
/** Encodes a value. */
export function encode(value) {
// Replaced with \`false\` by \`transform.js\`.
if (false)
return \`v2:\${value}\`;
return \`v1:\${value}\`;
}
//# sourceMappingURL=index.js.map"
`;

exports[`'/transform': Cli.run > default > output 1`] = `
"{
"name": "transform",
"version": "0.0.0",
"type": "module",
"main": "./dist/index.js",
"zile": {
"transform": "./transform.js"
},
"sideEffects": false,
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"src": "./src/index.ts",
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
}
}



├── dist
│ ├── flags.d.ts
│ ├── flags.d.ts.map
│ ├── flags.js
│ ├── flags.js.map
│ ├── index.d.ts
│ ├── index.d.ts.map
│ ├── index.js
│ └── index.js.map
├── src
│ ├── flags.ts
│ └── index.ts
├── package.json
├── transform.js
└── tsconfig.json
"
`;

exports[`'/transform': Cli.run > default > types 1`] = `
"/** Encodes a value. */
export declare function encode(value: string): string;
//# sourceMappingURL=index.d.ts.map"
`;

exports[`'/transform': Cli.run > link > main-target 1`] = `"../src/index.ts"`;

exports[`'/transform': Cli.run > link > output 1`] = `
"{
"name": "transform",
"version": "0.0.0",
"type": "module",
"main": "./dist/index.js",
"zile": {
"transform": "./transform.js"
},
"sideEffects": false,
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"src": "./src/index.ts",
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
}
}



├── dist
│ ├── index.d.ts -> ../src/index.ts
│ └── index.js -> ../src/index.ts
├── src
│ ├── flags.ts
│ └── index.ts
├── package.json
├── transform.js
└── tsconfig.json
"
`;

exports[`'/transform': Cli.run > link > types-target 1`] = `"../src/index.ts"`;

exports[`'/wildcard-exports': Cli.run > default > main 1`] = `
"export const name = 'wildcard-exports';
//# sourceMappingURL=index.js.map"
Expand Down
Loading
Loading