@effected/bundler 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,121 @@
1
+ import { Context, Effect, FileSystem, Option, Path } from "effect";
2
+
3
+ // src/passes/stamp-versions.ts
4
+ /** The exact expression the build defines; a package reads its own version through it. */
5
+ const VERSION_EXPRESSION = "process.env.__PACKAGE_VERSION__";
6
+ const isNode = (value) => typeof value === "object" && value !== null && typeof value.type === "string";
7
+ const isIdentifier = (node, name) => isNode(node) && node.type === "Identifier" && node.name === name;
8
+ /** `process.env.__PACKAGE_VERSION__` as a member expression, written the way `define` matches it: no computed access. */
9
+ const isVersionExpression = (node) => {
10
+ if (node.type !== "MemberExpression" || node.computed === true || !isIdentifier(node.property, "__PACKAGE_VERSION__")) return false;
11
+ const object = node.object;
12
+ return isNode(object) && object.type === "MemberExpression" && object.computed !== true && isIdentifier(object.object, "process") && isIdentifier(object.property, "env");
13
+ };
14
+ /** Every occurrence of the expression in a program, outermost first, never descending into one it took. */
15
+ const collectSpans = (root) => {
16
+ const spans = [];
17
+ const stack = [root];
18
+ while (stack.length > 0) {
19
+ const value = stack.pop();
20
+ if (Array.isArray(value)) {
21
+ for (const item of value) stack.push(item);
22
+ continue;
23
+ }
24
+ if (!isNode(value)) continue;
25
+ if (isVersionExpression(value) && typeof value.start === "number" && typeof value.end === "number") {
26
+ spans.push({
27
+ start: value.start,
28
+ end: value.end
29
+ });
30
+ continue;
31
+ }
32
+ for (const [key, child] of Object.entries(value)) if (key !== "type" && typeof child === "object" && child !== null) stack.push(child);
33
+ }
34
+ return spans;
35
+ };
36
+ /**
37
+ * Replaces each `process.env.__PACKAGE_VERSION__` expression in `code` with a string literal of `version`, leaving
38
+ * strings, comments and other spellings alone, as the build's `define` does. `undefined` when nothing matched.
39
+ *
40
+ * @param parse - a parser answering an ESTree program, with UTF-16 offsets, for a file name and its source
41
+ *
42
+ * @internal
43
+ */
44
+ const stampSource = (code, filename, version, parse) => {
45
+ if (!code.includes("process.env.__PACKAGE_VERSION__")) return void 0;
46
+ const spans = [...collectSpans(parse(filename, code))].sort((a, b) => b.start - a.start);
47
+ if (spans.length === 0) return void 0;
48
+ let out = code;
49
+ const literal = JSON.stringify(version);
50
+ for (const { start, end } of spans) out = `${out.slice(0, start)}${literal}${out.slice(end)}`;
51
+ return out;
52
+ };
53
+ /**
54
+ * Rolldown plugin: stamps every inlined module of ANOTHER package with that package's own version.
55
+ *
56
+ * @remarks
57
+ * The build defines `process.env.__PACKAGE_VERSION__` as the built package's version, and `define` applies to every
58
+ * module in the bundle. A workspace sibling or a registry package inlined by `bundle` or `bundleNodeModules` reads the
59
+ * same expression for its own version, so without this it would report the bundling package's. This hook runs before
60
+ * the native transform that applies `define`, finds the nearest `package.json` above each module that spells the
61
+ * expression and, when that is not the package being built, writes the owner's version in its place. A module whose
62
+ * owner has no version is left to `define`.
63
+ *
64
+ * rolldown calls `transform` as a plain async hook, so the plugin captures the `FileSystem` and `Path` it is built under.
65
+ *
66
+ * @public
67
+ */
68
+ const stampVersions = (options) => Effect.map(Effect.context(), (services) => stampVersionsWith(options, services));
69
+ const stampVersionsWith = (options, services) => {
70
+ const run = Effect.runPromiseWith(services);
71
+ const path = Context.get(services, Path.Path);
72
+ const owners = /* @__PURE__ */ new Map();
73
+ const ownerOf = (directory) => {
74
+ const cached = owners.get(directory);
75
+ if (cached !== void 0) return cached;
76
+ const found = run(Effect.gen(function* () {
77
+ const text = yield* (yield* FileSystem.FileSystem).readFileString(path.join(directory, "package.json")).pipe(Effect.option);
78
+ if (Option.isSome(text)) {
79
+ const manifest = yield* Effect.try(() => JSON.parse(text.value)).pipe(Effect.option);
80
+ if (Option.isSome(manifest) && typeof manifest.value.name === "string") {
81
+ const version = manifest.value.version;
82
+ return Option.some({
83
+ directory,
84
+ version: typeof version === "string" ? version : void 0
85
+ });
86
+ }
87
+ }
88
+ const parent = path.dirname(directory);
89
+ return parent === directory ? Option.none() : yield* Effect.promise(() => ownerOf(parent));
90
+ }));
91
+ owners.set(directory, found);
92
+ return found;
93
+ };
94
+ const self = run(Effect.gen(function* () {
95
+ return yield* (yield* FileSystem.FileSystem).realPath(options.cwd).pipe(Effect.orElseSucceed(() => options.cwd));
96
+ }));
97
+ let parser;
98
+ const parse = () => {
99
+ parser ??= import("rolldown/utils").then(({ parseSync }) => (filename, code) => parseSync(filename, code).program);
100
+ return parser;
101
+ };
102
+ return {
103
+ name: "effected:stamp-versions",
104
+ transform: {
105
+ filter: { code: VERSION_EXPRESSION },
106
+ async handler(code, id) {
107
+ if (id.startsWith("\0") || !code.includes("process.env.__PACKAGE_VERSION__")) return null;
108
+ const file = id.split("?")[0] ?? id;
109
+ const owner = await ownerOf(path.dirname(file));
110
+ if (Option.isNone(owner) || owner.value.directory === await self || owner.value.version === void 0) return null;
111
+ const stamped = stampSource(code, file, owner.value.version, await parse());
112
+ return stamped === void 0 ? null : {
113
+ code: stamped,
114
+ map: null
115
+ };
116
+ }
117
+ }
118
+ };
119
+ };
120
+
121
+ export { VERSION_EXPRESSION, stampSource, stampVersions };
@@ -1,38 +1,36 @@
1
1
  import { findRelativeSpecifiers } from "../dts/relative-imports.js";
2
2
  import { ConfigValidationError } from "../errors.js";
3
- import { Result } from "effect";
4
- import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
5
- import { dirname, join, resolve } from "node:path";
3
+ import { existsLikeNode } from "../internal/exists.js";
4
+ import { Effect, FileSystem, Path, Result } from "effect";
6
5
  import { GlobPattern, GlobPatternOptions } from "@effected/glob";
7
- import { descendSync } from "@effected/walker";
8
- import { nodeWalkerSyncOps } from "@effected/walker/node-sync";
6
+ import { descend } from "@effected/walker";
9
7
 
10
8
  // src/passes/sync-public.ts
11
9
  /** Every file at any depth, dotfiles included. */
12
10
  const EVERY_FILE = Result.getOrThrow(GlobPattern.compileResult("**", GlobPatternOptions.make({ dot: true })));
11
+ /** True when both files exist with identical size and bytes. Size is checked first so the byte read is skipped for the common changed case. */
12
+ const sameBytes = Effect.fnUntraced(function* (a, b) {
13
+ const fs = yield* FileSystem.FileSystem;
14
+ if ((yield* fs.stat(a)).size !== (yield* fs.stat(b)).size) return false;
15
+ const left = yield* fs.readFile(a);
16
+ const right = yield* fs.readFile(b);
17
+ return Buffer.from(left.buffer, left.byteOffset, left.byteLength).equals(right);
18
+ });
19
+ /** The standard public-asset collision error for a destination-relative path. */
20
+ const publicCollision = (rel) => new ConfigValidationError({
21
+ path: `public/${rel}`,
22
+ reason: `public asset "${rel}" collides with a built output at the package root — rename or remove it`
23
+ });
13
24
  /**
14
- * Every file path under `dir`, relative to it (POSIX separators, sorted). Nothing is pruned, so a
15
- * `public/.well-known/` or `public/node_modules/` asset still copies; symlinked directories are not entered.
25
+ * `EEXIST`, `ENOTDIR` and `EISDIR`: a path segment the copy needs is occupied by the wrong kind of entry. A Node
26
+ * backend reports `ENOTDIR` and `EISDIR` as `BadResource`, which also covers `ELOOP`; a symlink loop is no collision,
27
+ * and fails as the IO error it is, as the old errno check let it.
16
28
  */
17
- function listFilesRel(dir) {
18
- return Result.getOrThrow(descendSync(EVERY_FILE, {
19
- cwd: resolve(dir),
20
- prune: [],
21
- ...nodeWalkerSyncOps
22
- }));
23
- }
24
- /** True when both files exist with identical size and bytes. Size is checked first so the byte read is skipped for the common changed case. */
25
- function sameBytes(a, b) {
26
- if (statSync(a).size !== statSync(b).size) return false;
27
- return readFileSync(a).equals(readFileSync(b));
28
- }
29
- /** Throw the standard public-asset collision error for a destination-relative path. */
30
- function throwPublicCollision(rel) {
31
- throw new ConfigValidationError({
32
- path: `public/${rel}`,
33
- reason: `public asset "${rel}" collides with a built output at the package root — rename or remove it`
34
- });
35
- }
29
+ const isOccupied = (error) => {
30
+ if (error.reason._tag === "AlreadyExists") return true;
31
+ if (error.reason._tag !== "BadResource") return false;
32
+ return error.reason.cause?.code !== "ELOOP";
33
+ };
36
34
  /**
37
35
  * Copy the CONTENTS of `sourceDir` into `outDir`, additively.
38
36
  *
@@ -49,25 +47,24 @@ function throwPublicCollision(rel) {
49
47
  * {@link ConfigValidationError} rather than clobbering it or surfacing a raw fs error.
50
48
  * @public
51
49
  */
52
- function copyPublicDir(sourceDir, outDir) {
53
- if (!existsSync(sourceDir)) return;
54
- for (const rel of listFilesRel(sourceDir)) {
55
- const src = join(sourceDir, rel);
56
- const dst = join(outDir, rel);
57
- if (existsSync(dst)) {
58
- if (statSync(dst).isFile() && sameBytes(src, dst)) continue;
59
- throwPublicCollision(rel);
60
- }
61
- try {
62
- mkdirSync(dirname(dst), { recursive: true });
63
- copyFileSync(src, dst);
64
- } catch (err) {
65
- const code = err.code;
66
- if (code === "ENOTDIR" || code === "EEXIST" || code === "EISDIR") throwPublicCollision(rel);
67
- throw err;
50
+ const copyPublicDir = Effect.fnUntraced(function* (sourceDir, outDir) {
51
+ const fs = yield* FileSystem.FileSystem;
52
+ const path = yield* Path.Path;
53
+ if (!(yield* existsLikeNode(sourceDir))) return;
54
+ const files = yield* descend(EVERY_FILE, {
55
+ cwd: path.resolve(sourceDir),
56
+ prune: []
57
+ });
58
+ for (const rel of files) {
59
+ const src = path.join(sourceDir, rel);
60
+ const dst = path.join(outDir, rel);
61
+ if (yield* existsLikeNode(dst)) {
62
+ if ((yield* fs.stat(dst)).type === "File" && (yield* sameBytes(src, dst))) continue;
63
+ return yield* publicCollision(rel);
68
64
  }
65
+ yield* fs.makeDirectory(path.dirname(dst), { recursive: true }).pipe(Effect.andThen(fs.copyFile(src, dst)), Effect.catchIf(isOccupied, () => Effect.fail(publicCollision(rel))));
69
66
  }
70
- }
67
+ });
71
68
  /**
72
69
  * Copy each ambient `.d.ts` export's source verbatim into `outDir/<outName>`, byte-stable (an
73
70
  * unchanged file keeps its timestamp). The copy is NOT compiled or bundled, so the build owns two
@@ -77,24 +74,26 @@ function copyPublicDir(sourceDir, outDir) {
77
74
  * Throws {@link ConfigValidationError} on a missing source or any relative specifier.
78
75
  * @public
79
76
  */
80
- function copyAmbientDts(options) {
77
+ const copyAmbientDts = Effect.fnUntraced(function* (options) {
78
+ const fs = yield* FileSystem.FileSystem;
79
+ const path = yield* Path.Path;
81
80
  for (const a of options.ambient) {
82
- const src = join(options.srcCwd, a.source);
83
- if (!existsSync(src)) throw new ConfigValidationError({
81
+ const src = path.join(options.srcCwd, a.source);
82
+ if (!(yield* existsLikeNode(src))) return yield* new ConfigValidationError({
84
83
  path: `exports."${a.exportKey}"`,
85
84
  reason: `ambient .d.ts source not found: ${a.source}`
86
85
  });
87
- const relativeSpecifiers = findRelativeSpecifiers(readFileSync(src, "utf-8"), a.source);
88
- if (relativeSpecifiers.length > 0) throw new ConfigValidationError({
86
+ const relativeSpecifiers = findRelativeSpecifiers(yield* fs.readFileString(src), a.source);
87
+ if (relativeSpecifiers.length > 0) return yield* new ConfigValidationError({
89
88
  path: `exports."${a.exportKey}"`,
90
89
  reason: `ambient .d.ts "${a.source}" has relative import(s) [${relativeSpecifiers.join(", ")}] that cannot resolve after a verbatim copy — use bare package specifiers or self-contained declare module/global blocks`
91
90
  });
92
- const dst = join(options.outDir, a.outName);
93
- if (!existsSync(dst) || !sameBytes(src, dst)) {
94
- mkdirSync(dirname(dst), { recursive: true });
95
- copyFileSync(src, dst);
91
+ const dst = path.join(options.outDir, a.outName);
92
+ if (!(yield* existsLikeNode(dst)) || !(yield* sameBytes(src, dst))) {
93
+ yield* fs.makeDirectory(path.dirname(dst), { recursive: true });
94
+ yield* fs.copyFile(src, dst);
96
95
  }
97
96
  }
98
- }
97
+ });
99
98
 
100
99
  export { copyAmbientDts, copyPublicDir };
@@ -0,0 +1,102 @@
1
+ import { Context, Effect, FileSystem, Option, Path } from "effect";
2
+
3
+ // src/passes/third-party-licenses.ts
4
+ /** The file a build writes beside its manifest when it inlined another package's code. */
5
+ const THIRD_PARTY_LICENSES = "THIRD_PARTY_LICENSES.txt";
6
+ /** A licence or notice file by the names packages ship them under. */
7
+ const NOTICE_FILE = /^(?:licen[cs]e|copying|notice)(?:[.-].*)?$/i;
8
+ /**
9
+ * Renders the notices file: one section per package, sorted by name and version, each with its declared licence and
10
+ * the text of every licence or notice file it ships.
11
+ *
12
+ * @internal
13
+ */
14
+ const renderThirdPartyLicenses = (packageName, packages) => {
15
+ const sorted = [...packages].sort((a, b) => a.name === b.name ? a.version.localeCompare(b.version) : a.name.localeCompare(b.name));
16
+ const rule = "-".repeat(80);
17
+ return `${packageName} includes code from the following packages, inlined at build time.\n\n${sorted.map((pkg) => {
18
+ const head = `${pkg.name}@${pkg.version}\nLicense: ${pkg.license}`;
19
+ const body = pkg.notices.length === 0 ? "(no licence file is shipped with this package)" : pkg.notices.map((notice) => `${notice.file}:\n\n${notice.text.trimEnd()}`).join("\n\n");
20
+ return `${rule}\n${head}\n\n${body}\n`;
21
+ }).join("\n")}`;
22
+ };
23
+ /**
24
+ * Rolldown plugin: writes {@link THIRD_PARTY_LICENSES} when the JS pass inlined code from any other package.
25
+ *
26
+ * @remarks
27
+ * Every module in the output whose nearest `package.json` belongs to another package is that package's code, a
28
+ * workspace sibling's or a registry package's, and the file carries its name, version, declared licence and the text
29
+ * of the licence and notice files it ships, so the notices travel with the code. A pass that inlined nothing, the
30
+ * usual per-module build, writes no file.
31
+ *
32
+ * rolldown calls `generateBundle` as a plain async hook, so the plugin captures the `FileSystem` and `Path` it is built
33
+ * under.
34
+ *
35
+ * @public
36
+ */
37
+ const thirdPartyLicenses = (options) => Effect.map(Effect.context(), (services) => thirdPartyLicensesWith(options, services));
38
+ const thirdPartyLicensesWith = (options, services) => {
39
+ const run = Effect.runPromiseWith(services);
40
+ const path = Context.get(services, Path.Path);
41
+ /** The directory and manifest of the package owning `directory`, walking up to the nearest named package. */
42
+ const ownerOf = (directory) => Effect.gen(function* () {
43
+ const text = yield* (yield* FileSystem.FileSystem).readFileString(path.join(directory, "package.json")).pipe(Effect.option);
44
+ if (Option.isSome(text)) {
45
+ const manifest = yield* Effect.try(() => JSON.parse(text.value)).pipe(Effect.option);
46
+ if (Option.isSome(manifest) && typeof manifest.value.name === "string") return Option.some([directory, manifest.value]);
47
+ }
48
+ const parent = path.dirname(directory);
49
+ return parent === directory ? Option.none() : yield* ownerOf(parent);
50
+ });
51
+ const describe = (directory, manifest) => Effect.gen(function* () {
52
+ const fs = yield* FileSystem.FileSystem;
53
+ const entries = yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
54
+ const notices = [];
55
+ for (const file of [...entries].filter((entry) => NOTICE_FILE.test(entry)).sort()) {
56
+ const text = yield* fs.readFileString(path.join(directory, file)).pipe(Effect.option);
57
+ if (Option.isSome(text)) notices.push({
58
+ file,
59
+ text: text.value
60
+ });
61
+ }
62
+ return {
63
+ name: String(manifest.name),
64
+ version: typeof manifest.version === "string" ? manifest.version : "unknown",
65
+ license: typeof manifest.license === "string" ? manifest.license : "UNKNOWN",
66
+ notices
67
+ };
68
+ });
69
+ return {
70
+ name: "effected:third-party-licenses",
71
+ async generateBundle(_output, bundle) {
72
+ const ids = /* @__PURE__ */ new Set();
73
+ for (const chunk of Object.values(bundle)) {
74
+ if (chunk.type !== "chunk") continue;
75
+ for (const id of chunk.moduleIds) if (!id.startsWith("\0") && path.isAbsolute(id)) ids.add(id);
76
+ }
77
+ await run(Effect.gen(function* () {
78
+ const self = yield* (yield* FileSystem.FileSystem).realPath(options.cwd).pipe(Effect.orElseSucceed(() => options.cwd));
79
+ const seen = /* @__PURE__ */ new Set();
80
+ for (const id of ids) {
81
+ const directory = path.dirname(id.split("?")[0] ?? id);
82
+ if (seen.has(directory)) continue;
83
+ seen.add(directory);
84
+ const owner = yield* ownerOf(directory);
85
+ if (Option.isNone(owner)) continue;
86
+ const [root, manifest] = owner.value;
87
+ if (root === self || root === options.cwd) continue;
88
+ const key = `${String(manifest.name)}@${String(manifest.version)}`;
89
+ if (!options.found.has(key)) options.found.set(key, yield* describe(root, manifest));
90
+ }
91
+ }));
92
+ if (options.found.size === 0) return;
93
+ this.emitFile({
94
+ type: "asset",
95
+ fileName: THIRD_PARTY_LICENSES,
96
+ source: renderThirdPartyLicenses(options.packageName, [...options.found.values()])
97
+ });
98
+ }
99
+ };
100
+ };
101
+
102
+ export { THIRD_PARTY_LICENSES, renderThirdPartyLicenses, thirdPartyLicenses };
@@ -1,20 +0,0 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import * as nodePath from "node:path";
3
-
4
- // src/tsconfig/sync-options.ts
5
- /**
6
- * The consumer-supplied sync operations backing every `TsconfigLoaderSync` call in this
7
- * package: Node's `existsSync`/`readFileSync` satisfy the loader's `SyncFileSystem`, and
8
- * `node:path` satisfies `SyncPath` verbatim.
9
- *
10
- * @internal
11
- */
12
- const tsconfigSyncOptions = {
13
- fileSystem: {
14
- exists: existsSync,
15
- readFile: (p) => readFileSync(p, "utf8")
16
- },
17
- path: nodePath
18
- };
19
-
20
- export { tsconfigSyncOptions };