@mui/internal-code-infra 0.1.1-canary.35 → 0.1.1-canary.36

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.
package/README.md CHANGED
@@ -77,3 +77,13 @@ After following these steps, the `Publish` workflow can be invoked again.
77
77
  ## Agent skills
78
78
 
79
79
  The agent skills previously shipped with this package now live at the repository root. See [Install instructions](../../README.md#agent-skills).
80
+
81
+ ## Upcoming tsdown builds
82
+
83
+ `code-infra build-new` is experimental. It compiles the `src` modules behind the package's
84
+ `exports`, `imports` and `bin`, plus every module they import, to the `publishConfig.directory`
85
+ with tsdown, keeping every package import external. Modules loaded with
86
+ `new URL('./file', import.meta.url)`, such as workers, are built too, and the URL points at their
87
+ output. It does not
88
+ apply the Babel configuration or write declarations, `package.json` or extra files.
89
+ Continue using `code-infra build` for package builds.
@@ -82,6 +82,14 @@ export declare function createPackageBin(bin: import('../cli/packageJson').Packa
82
82
  cwd: string;
83
83
  packageType?: 'module' | 'commonjs';
84
84
  }): Promise<string | Record<string, string> | undefined>;
85
+ /**
86
+ * The JS/TS sources the package's `exports`, `imports` and `bin` point at, relative to `cwd`.
87
+ * Glob patterns are expanded against the files on disk, as in the published `package.json`.
88
+ * @param {import('../cli/packageJson').PackageJson} packageJson
89
+ * @param {string} cwd
90
+ * @returns {Promise<string[]>}
91
+ */
92
+ export declare function getPackageSources({ exports, imports, bin }: import('../cli/packageJson').PackageJson, cwd: string): Promise<string[]>;
85
93
  /**
86
94
  * Validates the package.json before building.
87
95
  * @param {Record<string, any>} packageJson
@@ -0,0 +1,9 @@
1
+ export type NewExpression = import('rolldown/utils').ESTree.NewExpression;
2
+ /**
3
+ * Builds the modules sources load with `new URL('./file', import.meta.url)`, such as workers. No
4
+ * import or `exports` entry reaches them, so they would be missing from the output. Each becomes
5
+ * an entry, compiled like any other source, and the URL is rewritten to its output path and
6
+ * extension (`new URL('./worker.ts', …)` → `new URL('./worker.mjs', …)`).
7
+ * @returns {import('tsdown').Rolldown.Plugin}
8
+ */
9
+ export declare function fileUrlEntriesPlugin(): import('tsdown').Rolldown.Plugin;
@@ -5,6 +5,13 @@
5
5
  * @returns {Promise<string>} The path of the created temporary directory.
6
6
  */
7
7
  export declare function makeTempDir(): Promise<string>;
8
+ /**
9
+ * Creates a temporary directory (see {@link makeTempDir}) containing `files`.
10
+ *
11
+ * @param {Record<string, string>} files - File contents keyed by path relative to the directory.
12
+ * @returns {Promise<string>} The path of the created temporary directory.
13
+ */
14
+ export declare function makeTempFiles(files: Record<string, string>): Promise<string>;
8
15
  /**
9
16
  * Write a package.json into a subdirectory of a temp workspace.
10
17
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mui/internal-code-infra",
3
- "version": "0.1.1-canary.35",
3
+ "version": "0.1.1-canary.36",
4
4
  "author": "MUI Team",
5
5
  "description": "Infra scripts and configs to be used across MUI repos.",
6
6
  "license": "MIT",
@@ -141,8 +141,10 @@
141
141
  "remark-parse": "^11.0.0",
142
142
  "remark-rehype": "^11.1.2",
143
143
  "resolve-pkg-maps": "^1.0.0",
144
+ "rolldown": "1.2.16",
144
145
  "semver": "^7.8.6",
145
146
  "stylelint-config-standard": "^41.0.0",
147
+ "tsdown": "0.23.4",
146
148
  "typescript-eslint": "^8.72.2",
147
149
  "unified": "^11.0.5",
148
150
  "unified-lint-rule": "^3.0.1",
@@ -197,7 +199,7 @@
197
199
  "publishConfig": {
198
200
  "access": "public"
199
201
  },
200
- "gitSha": "648d5a45da76163e2153dfc37431b1e4df7bb868",
202
+ "gitSha": "29461ce4eeb3bcf91d92816e632191bebb17677d",
201
203
  "scripts": {
202
204
  "build": "tsc -p tsconfig.build.json",
203
205
  "typescript": "tsc -noEmit",
@@ -0,0 +1,88 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+
4
+ import { getOutExtension, getPackageSources, validatePkgJson } from '../utils/build.mjs';
5
+ import { fileUrlEntriesPlugin } from '../utils/fileUrlEntriesPlugin.mjs';
6
+
7
+ /**
8
+ * @typedef {Object} Args
9
+ * @property {import('../utils/build.mjs').BundleType[]} bundle
10
+ */
11
+
12
+ const SOURCE_DIR = 'src';
13
+ // Importers keep `#` specifiers, so consumers resolve the `imports` conditions.
14
+ const PACKAGE_IMPORTS = /^#/;
15
+ const MODULE_LEVEL_DIRECTIVE = 'MODULE_LEVEL_DIRECTIVE';
16
+
17
+ /** @type {Record<import('../utils/build.mjs').BundleType, 'es' | 'cjs'>} */
18
+ const FORMATS = { esm: 'es', cjs: 'cjs' };
19
+
20
+ /**
21
+ * Resolves the source modules behind the package's published paths, keyed by output name.
22
+ * @param {import('./packageJson').PackageJson} packageJson
23
+ * @param {string} cwd
24
+ * @returns {Promise<Record<string, string>>}
25
+ */
26
+ async function getEntry(packageJson, cwd) {
27
+ const sources = await getPackageSources(packageJson, cwd);
28
+
29
+ return Object.fromEntries(
30
+ sources.map((source) => {
31
+ const name = path.relative(SOURCE_DIR, source);
32
+
33
+ return [name.slice(0, -path.extname(name).length), source];
34
+ }),
35
+ );
36
+ }
37
+
38
+ export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
39
+ command: 'build-new',
40
+ describe: 'Experimental tsdown build. Compiles JavaScript only.',
41
+ builder: (yargs) =>
42
+ yargs.option('bundle', {
43
+ array: true,
44
+ type: 'string',
45
+ choices: /** @type {const} */ (['esm', 'cjs']),
46
+ default: /** @type {import('../utils/build.mjs').BundleType[]} */ (['esm', 'cjs']),
47
+ description: 'Bundles to output.',
48
+ }),
49
+ async handler(args) {
50
+ const cwd = process.cwd();
51
+ const packageJson = JSON.parse(await fs.readFile(path.join(cwd, 'package.json'), 'utf8'));
52
+ validatePkgJson(packageJson);
53
+
54
+ const outDir = path.join(cwd, packageJson.publishConfig.directory);
55
+ const packageType = packageJson.type === 'module' ? 'module' : 'commonjs';
56
+ const entry = await getEntry(packageJson, cwd);
57
+
58
+ const { build } = await import('tsdown');
59
+ await build({
60
+ cwd,
61
+ config: false,
62
+ entry,
63
+ unbundle: true,
64
+ platform: 'neutral',
65
+ root: SOURCE_DIR,
66
+ outDir,
67
+ clean: true,
68
+ format: [...new Set(args.bundle)].map((bundle) => FORMATS[bundle]),
69
+ outExtensions: ({ format }) => ({
70
+ js: getOutExtension(format === 'es' ? 'esm' : 'cjs', { packageType }),
71
+ }),
72
+ deps: { neverBundle: true },
73
+ plugins: [fileUrlEntriesPlugin()],
74
+ inputOptions: {
75
+ external: [PACKAGE_IMPORTS],
76
+ // tsdown otherwise takes `jsx` from the package's tsconfig, which may preserve JSX.
77
+ transform: { jsx: { runtime: 'automatic' } },
78
+ },
79
+ outputOptions: { exports: 'named' },
80
+ dts: false,
81
+ exports: false,
82
+ report: false,
83
+ logLevel: 'warn',
84
+ // Unbundled output keeps each module's directives; the warning is about bundling.
85
+ suppressWarnings: [MODULE_LEVEL_DIRECTIVE],
86
+ });
87
+ },
88
+ });
package/src/cli/index.mjs CHANGED
@@ -6,6 +6,7 @@ import { hideBin } from 'yargs/helpers';
6
6
  import cmdArgosPush from './cmdArgosPush.mjs';
7
7
  import cmdBaseline from './cmdBaseline.mjs';
8
8
  import cmdBuild from './cmdBuild.mjs';
9
+ import cmdBuildNew from './cmdBuildNew.mjs';
9
10
  import cmdCopyFiles from './cmdCopyFiles.mjs';
10
11
  import cmdExtractErrorCodes from './cmdExtractErrorCodes.mjs';
11
12
  import cmdGenerateChangelog from './cmdGenerateChangelog.mjs';
@@ -41,6 +42,7 @@ await yargs(hideBin(process.argv))
41
42
  .command(cmdArgosPush)
42
43
  .command(cmdBaseline)
43
44
  .command(cmdBuild)
45
+ .command(cmdBuildNew)
44
46
  .command(cmdCopyFiles)
45
47
  .command(cmdExtractErrorCodes)
46
48
  .command(cmdGenerateChangelog)
@@ -794,6 +794,53 @@ export async function createPackageBin(bin, { bundles, cwd, packageType }) {
794
794
  return newBin;
795
795
  }
796
796
 
797
+ /**
798
+ * @param {unknown} value
799
+ * @returns {string[]}
800
+ */
801
+ function getLeaves(value) {
802
+ if (typeof value === 'string') {
803
+ return [value];
804
+ }
805
+
806
+ if (!value || typeof value !== 'object') {
807
+ return [];
808
+ }
809
+
810
+ return Object.values(value).flatMap(getLeaves);
811
+ }
812
+
813
+ /**
814
+ * The JS/TS sources the package's `exports`, `imports` and `bin` point at, relative to `cwd`.
815
+ * Glob patterns are expanded against the files on disk, as in the published `package.json`.
816
+ * @param {import('../cli/packageJson').PackageJson} packageJson
817
+ * @param {string} cwd
818
+ * @returns {Promise<string[]>}
819
+ */
820
+ export async function getPackageSources({ exports, imports, bin }, cwd) {
821
+ const maps = await Promise.all(
822
+ [
823
+ typeof exports === 'string' || Array.isArray(exports) ? { '.': exports } : exports,
824
+ imports,
825
+ ].map((map) =>
826
+ expandExportGlobs(
827
+ /** @type {import('../cli/packageJson').PackageJson.ExportConditions} */ (map ?? {}),
828
+ cwd,
829
+ ),
830
+ ),
831
+ );
832
+
833
+ return [...new Set(getLeaves([...maps, bin]))].flatMap((leaf) => {
834
+ const rel = srcRelative(leaf);
835
+
836
+ if (rel === null || rel.includes('*') || !JS_TS_EXTENSIONS.has(path.extname(rel))) {
837
+ return [];
838
+ }
839
+
840
+ return [path.posix.join('src', rel)];
841
+ });
842
+ }
843
+
797
844
  /**
798
845
  * Validates the package.json before building.
799
846
  * @param {Record<string, any>} packageJson
@@ -0,0 +1,84 @@
1
+ import * as path from 'node:path';
2
+ import { RolldownMagicString } from 'rolldown';
3
+ import { parse, Visitor } from 'rolldown/utils';
4
+
5
+ const SCRIPT_FILES = /\.[cm]?[jt]sx?$/;
6
+ const TS_FILES = /\.[cm]?ts$/;
7
+
8
+ /**
9
+ * @typedef {import('rolldown/utils').ESTree.NewExpression} NewExpression
10
+ */
11
+
12
+ /**
13
+ * Returns the relative path of `new URL('./file', import.meta.url)`.
14
+ * @param {NewExpression} node
15
+ */
16
+ function getFileUrlPath(node) {
17
+ const [file, base] = node.arguments;
18
+ if (
19
+ node.callee.type !== 'Identifier' ||
20
+ node.callee.name !== 'URL' ||
21
+ file?.type !== 'Literal' ||
22
+ typeof file.value !== 'string' ||
23
+ !file.value.startsWith('.') ||
24
+ base?.type !== 'MemberExpression' ||
25
+ base.object.type !== 'MetaProperty' ||
26
+ base.property.type !== 'Identifier' ||
27
+ base.property.name !== 'url'
28
+ ) {
29
+ return undefined;
30
+ }
31
+ return file.value;
32
+ }
33
+
34
+ /**
35
+ * Builds the modules sources load with `new URL('./file', import.meta.url)`, such as workers. No
36
+ * import or `exports` entry reaches them, so they would be missing from the output. Each becomes
37
+ * an entry, compiled like any other source, and the URL is rewritten to its output path and
38
+ * extension (`new URL('./worker.ts', …)` → `new URL('./worker.mjs', …)`).
39
+ * @returns {import('tsdown').Rolldown.Plugin}
40
+ */
41
+ export function fileUrlEntriesPlugin() {
42
+ return {
43
+ name: 'code-infra:file-url-entries',
44
+ transform: {
45
+ filter: { id: { exclude: /node_modules/ }, code: 'import.meta.url' },
46
+ async handler(code, id) {
47
+ // `.js` sources may contain JSX.
48
+ const lang = TS_FILES.test(id) ? 'ts' : 'tsx';
49
+ const { program } = await parse(id, code, { lang });
50
+
51
+ /** @type {NewExpression[]} */
52
+ const urls = [];
53
+ new Visitor({
54
+ NewExpression(node) {
55
+ if (getFileUrlPath(node)) {
56
+ urls.push(node);
57
+ }
58
+ },
59
+ }).visit(program);
60
+
61
+ const result = new RolldownMagicString(code);
62
+ const resolved = await Promise.all(
63
+ urls.map((node) => this.resolve(/** @type {string} */ (getFileUrlPath(node)), id)),
64
+ );
65
+ resolved.forEach((target, index) => {
66
+ if (!target || target.external || !SCRIPT_FILES.test(target.id)) {
67
+ return;
68
+ }
69
+ const ref = this.emitFile({ type: 'chunk', id: target.id, preserveSignature: 'strict' });
70
+ result.update(urls[index].start, urls[index].end, `import.meta.ROLLUP_FILE_URL_${ref}`);
71
+ });
72
+ return result.hasChanged() ? result.toString() : null;
73
+ },
74
+ },
75
+ resolveFileUrl({ chunkId, fileName, format }) {
76
+ const relative = path.posix.relative(path.posix.dirname(chunkId), fileName);
77
+ const file = JSON.stringify(relative.startsWith('.') ? relative : `./${relative}`);
78
+ // Bundlers only treat the literal `new URL('./file', import.meta.url)` as a worker or asset.
79
+ return format === 'es'
80
+ ? `new URL(${file}, import.meta.url)`
81
+ : `new URL(${file}, require("node:url").pathToFileURL(__filename))`;
82
+ },
83
+ };
84
+ }
@@ -19,6 +19,24 @@ export async function makeTempDir() {
19
19
  return tmpDir;
20
20
  }
21
21
 
22
+ /**
23
+ * Creates a temporary directory (see {@link makeTempDir}) containing `files`.
24
+ *
25
+ * @param {Record<string, string>} files - File contents keyed by path relative to the directory.
26
+ * @returns {Promise<string>} The path of the created temporary directory.
27
+ */
28
+ export async function makeTempFiles(files) {
29
+ const tmpDir = await makeTempDir();
30
+ await Promise.all(
31
+ Object.entries(files).map(async ([name, contents]) => {
32
+ const file = path.join(tmpDir, name);
33
+ await fs.mkdir(path.dirname(file), { recursive: true });
34
+ await fs.writeFile(file, contents);
35
+ }),
36
+ );
37
+ return tmpDir;
38
+ }
39
+
22
40
  /**
23
41
  * Write a package.json into a subdirectory of a temp workspace.
24
42
  *