-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrolldown.config.ts
More file actions
326 lines (276 loc) · 9.05 KB
/
rolldown.config.ts
File metadata and controls
326 lines (276 loc) · 9.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/**
* Rolldown configuration that dynamically builds the package it's been called from.
*
* This configuration works specifically for this monorepo's structure and workflow:
* - Packages are organized under a common {@linkcode PACKAGES_FOLDER} directory
* - Source files use TypeScript with `.ts` extensions
* - Built files are output to a {@linkcode OUTPUT_DIR} directory
* - The `publishConfig` field is used to override exports for publishing
*
* This config is designed for internal use within this project structure and is not intended as a general-purpose build configuration for external projects.
*
* @module
*/
import { access, cp, writeFile } from "node:fs/promises";
import { basename, extname, parse, relative, resolve } from "node:path";
import { cwd, exit } from "node:process";
import { defineConfig } from "rolldown";
import { dts } from "rolldown-plugin-dts";
import { glob } from "tinyglobby";
import type { Plugin } from "rolldown";
import type { PackageJson } from "type-fest";
// #region constants
/**
* The directory to output the build into.
*/
const OUTPUT_DIR = "dist";
/**
* Files to bundle from a package's `exports` while all other exported files get copied without processing.
*
* Matches `.ts` files that are not `.d.ts` declaration files. These files will be bundled.
*/
const FILES_TO_BUNDLE = /(?<!\.d)\.ts$/;
/**
* The folder containing all the packages.
*/
const PACKAGES_FOLDER = `packages`;
// #endregion
// #region helpers
/**
* Check if a file exists.
*/
const exists = (path: string): Promise<boolean> =>
access(path)
.then(() => true)
.catch(() => false);
/**
* Find the package root directory by traversing up from the given path until a `package.json` is found.
*
* @throws If the filesystem root is reached or if the {@linkcode PACKAGES_FOLDER} directory is reached.
*/
const getPackageDirectory = async (path: string): Promise<string> => {
const resolvedPath = resolve(path);
if (parse(resolvedPath).root === resolvedPath) {
throw new Error("Reached fs root without finding a package.");
}
// stop if we've reached the packages container directory
if (resolvedPath.endsWith(resolve("/", PACKAGES_FOLDER))) {
throw new Error("A build has to be called from within a package.");
}
const nodeModulesIndex = resolvedPath.indexOf("node_modules");
// continue search outside of `node_modules` to find the actual package root
if (nodeModulesIndex > 0) {
return getPackageDirectory(resolvedPath.slice(0, nodeModulesIndex));
}
const isPackage = await exists(resolve(resolvedPath, "package.json"));
if (isPackage === false) {
return getPackageDirectory(resolve(resolvedPath, ".."));
}
return resolvedPath;
};
/**
* Recursively extract all file paths from the exports field in `package.json`.
*
* Handles string, array, and object formats, prioritizing `import` over `default` conditions.
*/
const getExports = (exports: PackageJson["exports"]): string[] => {
if (exports == null) {
return [];
}
if (typeof exports === "string") {
return [exports];
}
if (Array.isArray(exports)) {
return exports.flatMap((entry) => getExports(entry));
}
// prioritize "import" condition for ESM exports
if (Reflect.has(exports, "import") && typeof exports.import === "string") {
return [exports.import];
}
// fall back to "default" condition
if (Reflect.has(exports, "default") && typeof exports.default === "string") {
return [exports.default];
}
// recursively process nested export conditions
return Object.values(exports).flatMap((entry) => getExports(entry));
};
/**
* Split export entries into files to bundle and files to copy as-is based on the {@linkcode FILES_TO_BUNDLE} pattern.
*/
const resolveExports = (
exports: readonly string[],
): { toBundle: string[]; toCopy: string[] } =>
exports.reduce(
(obj, entry) => {
obj[FILES_TO_BUNDLE.test(entry) ? "toBundle" : "toCopy"].push(entry);
return obj;
},
{ toBundle: [], toCopy: [] } as ReturnType<typeof resolveExports>,
);
/**
* A type representing a readonly array that can be nested to any depth, used for handling grouped file paths.
*/
type RecursiveReadonlyArray<T> = readonly (T | RecursiveReadonlyArray<T>)[];
/**
* Copy the provided files to the {@linkcode OUTPUT_DIR} directory.
*/
const recursiveCopy = async (
filepaths: RecursiveReadonlyArray<string>,
): Promise<void> => {
await Promise.all(
filepaths.map((filepath) => {
if (typeof filepath === "string") {
return cp(filepath, resolve(OUTPUT_DIR, filepath), {
recursive: true,
force: true,
});
}
return recursiveCopy(filepath);
}),
);
};
/**
* Converts a "source" path to point to the {@linkcode OUTPUT_DIR} directory and adjust file extensions for published packages.
*
* Converts source file paths to their built equivalents:
* - `.ts` files become `.js` (or `.d.ts` for type declarations)
* - Files matching {@linkcode FILES_TO_BUNDLE} are processed, others are kept as-is
*
* @param filePath - The original path from package.json
* @param isType - Whether this is a type declaration path
* @param packageRoot - The package's root directory
*/
const toDirPath = (filePath: string, isType: boolean, packageRoot: string) => {
const newPath = relative(
packageRoot,
resolve(packageRoot, OUTPUT_DIR, filePath),
);
const extension = extname(newPath);
return `./${
FILES_TO_BUNDLE.test(filePath)
? isType
? newPath.replace(extension, ".d.ts")
: extension === ".ts"
? newPath.replace(extension, ".js")
: newPath
: newPath
}`;
};
/**
* Recursively transform the exports field to point to built files in the {@linkcode OUTPUT_DIR} directory.
*
* Handles all export formats (string, array, object) and preserves the structure while updating paths.
*
* @param exports - The exports field to transform
* @param isType - Whether processing type declaration paths
* @param packageRoot - The package's root directory
*/
const createPublishExports = (
exports: PackageJson["exports"],
isType: boolean,
packageRoot: string,
): PackageJson["exports"] => {
if (exports == null) {
return exports;
}
if (typeof exports === "string") {
return toDirPath(exports, isType, packageRoot);
}
if (Array.isArray(exports)) {
return exports.map((entry) =>
createPublishExports(entry, isType, packageRoot),
) as typeof exports;
}
const exportsClone = structuredClone(exports);
for (const [key, value] of Object.entries(exports)) {
exportsClone[key] =
// mark "types" condition entries as type declaration paths
createPublishExports(value, key === "types", packageRoot) ?? null;
}
return exportsClone;
};
/**
* Rolldown plugin that updates `package.json` with a `publishConfig` field containing corrected export paths.
*
* The `publishConfig.exports` field will override the original exports when the package is published,
* pointing to the built files in the {@linkcode OUTPUT_DIR} directory instead of source files.
*
* @param packageContents - The parsed package.json contents
* @param packageRoot - The package's root directory
*/
const setPackagePublishConfig = (
packageContents: PackageJson,
packageRoot: string,
): Plugin => ({
name: "set-package-publish-config",
buildEnd: async () => {
const packageClone = structuredClone(packageContents);
// add `publishConfig` with transformed exports for publishing
packageClone.publishConfig = {
exports: createPublishExports(packageClone.exports, false, packageRoot),
};
await writeFile(
resolve(packageRoot, "package.json"),
`${JSON.stringify(packageClone, null, 2)}\n`,
);
},
});
// #endregion
// #region config
/**
* The package's "root" directory resolved from the directory the build has been called from.
*/
const WORKING_DIRECTORY = await getPackageDirectory(cwd());
// import `package.json` (guaranteed to exist at this point)
const { default: packageContents } = (await import(
resolve(WORKING_DIRECTORY, "package.json"),
{
with: { type: "json" },
}
)) as { default: PackageJson };
// skip building private packages
if (packageContents.private === true) {
console.log(
`\`${basename(WORKING_DIRECTORY)}\` is a private package, it won't get built`,
);
exit(0);
}
const {
exports = {},
dependencies = {},
devDependencies = {},
peerDependencies = {},
} = packageContents;
const external = Array.from(
new Set([
...Object.keys(dependencies),
...Object.keys(devDependencies),
...Object.keys(peerDependencies),
]),
).flatMap((dependency) =>
// match both the package name and any subpath imports (e.g., `lodash` and `lodash/*`)
[dependency, new RegExp(`${dependency}/.*?`)],
);
const { toBundle, toCopy } = resolveExports(getExports(exports));
// copy all files that don't need bundling to the output folder
await recursiveCopy(
await Promise.all(
toCopy.map(async (entry) => glob(entry, { cwd: WORKING_DIRECTORY })),
),
);
export default defineConfig({
platform: "browser",
plugins: [dts(), setPackagePublishConfig(packageContents, WORKING_DIRECTORY)],
external,
input: Object.fromEntries(
toBundle.map((entry) => [
entry.slice(0, entry.length - extname(entry).length),
entry,
]),
),
output: {
format: "esm",
dir: OUTPUT_DIR,
},
});
// #endregion