@modern-js/app-tools 3.10.3 → 3.11.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.
@@ -136,10 +136,7 @@ const analyze = ()=>({
136
136
  partialsByEntrypoint
137
137
  });
138
138
  let checkedEntries = entrypoints.map((point)=>point.entryName);
139
- if ((0, utils_namespaceObject.isDevCommand)()) {
140
- const { entry } = (0, utils_namespaceObject.minimist)((0, utils_namespaceObject.getArgv)());
141
- checkedEntries = await (0, getSelectedEntries_js_namespaceObject.getSelectedEntries)('string' == typeof entry ? entry.split(',') : entry, entrypoints);
142
- }
139
+ if ((0, utils_namespaceObject.isDevCommand)()) checkedEntries = await (0, getSelectedEntries_js_namespaceObject.getSelectedEntries)((0, getSelectedEntries_js_namespaceObject.parseEntryOption)((0, utils_namespaceObject.getArgv)()), entrypoints);
143
140
  appContext = {
144
141
  ...api.getAppContext(),
145
142
  entrypoints,
@@ -28,10 +28,19 @@ var __webpack_require__ = {};
28
28
  var __webpack_exports__ = {};
29
29
  __webpack_require__.r(__webpack_exports__);
30
30
  __webpack_require__.d(__webpack_exports__, {
31
- getSelectedEntries: ()=>getSelectedEntries
31
+ getSelectedEntries: ()=>getSelectedEntries,
32
+ parseEntryOption: ()=>parseEntryOption
32
33
  });
33
34
  const utils_namespaceObject = require("@modern-js/utils");
34
35
  const index_js_namespaceObject = require("../locale/index.js");
36
+ const parseEntryOption = (argv)=>{
37
+ const { entry } = (0, utils_namespaceObject.minimist)(argv, {
38
+ alias: {
39
+ e: 'entry'
40
+ }
41
+ });
42
+ return 'string' == typeof entry ? entry.split(',') : entry ?? false;
43
+ };
35
44
  const getSelectedEntries = async (entry, entrypoints)=>{
36
45
  const entryNames = entrypoints.map((e)=>e.entryName);
37
46
  if (!entry) return entryNames;
@@ -56,8 +65,10 @@ const getSelectedEntries = async (entry, entrypoints)=>{
56
65
  return entry;
57
66
  };
58
67
  exports.getSelectedEntries = __webpack_exports__.getSelectedEntries;
68
+ exports.parseEntryOption = __webpack_exports__.parseEntryOption;
59
69
  for(var __rspack_i in __webpack_exports__)if (-1 === [
60
- "getSelectedEntries"
70
+ "getSelectedEntries",
71
+ "parseEntryOption"
61
72
  ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
62
73
  Object.defineProperty(exports, '__esModule', {
63
74
  value: true
@@ -89,8 +89,9 @@ const createRuntimePaths = ({ alias, paths, absoluteBaseUrl })=>{
89
89
  });
90
90
  return normalizedPaths;
91
91
  };
92
- const resolveTsRuntimeRegisterMode = (hasTsNode)=>{
92
+ const resolveTsRuntimeRegisterMode = (hasTsNode, moduleType)=>{
93
93
  if (hasTsNode) return 'ts-node';
94
+ if ('module' !== moduleType) return 'swc';
94
95
  const hasNativeTypeScriptSupport = process.features?.typescript;
95
96
  const nodeMajorVersion = Number(process.versions.node.split('.')[0]);
96
97
  const supportsNativeTypeScript = void 0 === hasNativeTypeScriptSupport ? nodeMajorVersion >= 22 : false !== hasNativeTypeScriptSupport;
@@ -102,7 +103,7 @@ const setupTsRuntime = async (appDir, distDir, alias, options = {})=>{
102
103
  const isTsProject = await utils_namespaceObject.fs.pathExists(tsconfigPath);
103
104
  const hasTsNode = (0, utils_namespaceObject.isDepExists)(appDir, 'ts-node');
104
105
  if (!isTsProject) return;
105
- const registerMode = resolveTsRuntimeRegisterMode(hasTsNode);
106
+ const registerMode = resolveTsRuntimeRegisterMode(hasTsNode, options.moduleType);
106
107
  const aliasConfig = (0, utils_namespaceObject.getAliasConfig)(alias, {
107
108
  appDirectory: appDir,
108
109
  tsconfigPath
@@ -144,6 +145,17 @@ const setupTsRuntime = async (appDir, distDir, alias, options = {})=>{
144
145
  ],
145
146
  ...tsNodeOptions
146
147
  });
148
+ } else if ('swc' === registerMode) {
149
+ const { register } = await import("@modern-js/utils/tsconfig-paths");
150
+ register({
151
+ baseUrl: absoluteBaseUrl || './',
152
+ paths: runtimePaths
153
+ });
154
+ const { readCompilerOptions, registerSwc } = await import("./swcRegister.js");
155
+ registerSwc({
156
+ distDir,
157
+ compilerOptions: readCompilerOptions(tsconfigPath)
158
+ });
147
159
  } else if ('node-loader' === registerMode) {
148
160
  const { registerPathsLoader } = await import("../esm/register-esm.js");
149
161
  await registerPathsLoader({
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.n = (module)=>{
5
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
6
+ __webpack_require__.d(getter, {
7
+ a: getter
8
+ });
9
+ return getter;
10
+ };
11
+ })();
12
+ (()=>{
13
+ __webpack_require__.d = (exports1, getters, values)=>{
14
+ var define = (defs, kind)=>{
15
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
16
+ enumerable: true,
17
+ [kind]: defs[key]
18
+ });
19
+ };
20
+ define(getters, "get");
21
+ define(values, "value");
22
+ };
23
+ })();
24
+ (()=>{
25
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
26
+ })();
27
+ (()=>{
28
+ __webpack_require__.r = (exports1)=>{
29
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
30
+ value: 'Module'
31
+ });
32
+ Object.defineProperty(exports1, '__esModule', {
33
+ value: true
34
+ });
35
+ };
36
+ })();
37
+ var __webpack_exports__ = {};
38
+ __webpack_require__.r(__webpack_exports__);
39
+ __webpack_require__.d(__webpack_exports__, {
40
+ createSwcOptions: ()=>createSwcOptions,
41
+ readCompilerOptions: ()=>readCompilerOptions,
42
+ registerSwc: ()=>registerSwc
43
+ });
44
+ const external_node_module_namespaceObject = require("node:module");
45
+ var external_node_module_default = /*#__PURE__*/ __webpack_require__.n(external_node_module_namespaceObject);
46
+ const external_node_path_namespaceObject = require("node:path");
47
+ var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
48
+ const core_namespaceObject = require("@swc/core");
49
+ const utils_namespaceObject = require("@modern-js/utils");
50
+ const TS_EXTENSIONS = [
51
+ '.ts',
52
+ '.tsx',
53
+ '.cts'
54
+ ];
55
+ const ES2022_OR_LATER = /^es(20(2[2-9]|[3-9]\d)|next)$/i;
56
+ let currentOptions;
57
+ const resolveExtendedConfig = (extendsPath, fromDir)=>{
58
+ const candidates = extendsPath.endsWith('.json') ? [
59
+ extendsPath
60
+ ] : [
61
+ extendsPath,
62
+ `${extendsPath}.json`,
63
+ `${extendsPath}/tsconfig.json`
64
+ ];
65
+ for (const candidate of candidates)try {
66
+ return require.resolve(candidate, {
67
+ paths: [
68
+ fromDir
69
+ ]
70
+ });
71
+ } catch {}
72
+ };
73
+ const readCompilerOptions = (tsconfigPath, visited = new Set())=>{
74
+ if (visited.has(tsconfigPath)) return {};
75
+ visited.add(tsconfigPath);
76
+ const config = (0, utils_namespaceObject.readTsConfigByFile)(tsconfigPath);
77
+ const extendsList = config.extends ? [].concat(config.extends) : [];
78
+ const baseOptions = extendsList.reduce((result, extendsPath)=>{
79
+ const resolved = resolveExtendedConfig(extendsPath, external_node_path_default().dirname(tsconfigPath));
80
+ return resolved ? {
81
+ ...result,
82
+ ...readCompilerOptions(resolved, visited)
83
+ } : result;
84
+ }, {});
85
+ return {
86
+ ...baseOptions,
87
+ ...config.compilerOptions
88
+ };
89
+ };
90
+ const isIgnored = (filename, distDir)=>{
91
+ if (filename.split(external_node_path_default().sep).includes('node_modules')) return true;
92
+ const relativeToDist = external_node_path_default().relative(distDir, filename);
93
+ return !relativeToDist.startsWith('..') && !external_node_path_default().isAbsolute(relativeToDist);
94
+ };
95
+ const createSwcOptions = (filename, compilerOptions = {})=>{
96
+ const tsx = filename.endsWith('.tsx');
97
+ const useDefineForClassFields = compilerOptions.useDefineForClassFields ?? ES2022_OR_LATER.test(String(compilerOptions.target ?? ''));
98
+ return {
99
+ filename,
100
+ swcrc: false,
101
+ configFile: false,
102
+ sourceMaps: 'inline',
103
+ module: {
104
+ type: 'commonjs'
105
+ },
106
+ jsc: {
107
+ target: 'es2022',
108
+ parser: {
109
+ syntax: "typescript",
110
+ tsx,
111
+ decorators: Boolean(compilerOptions.experimentalDecorators)
112
+ },
113
+ transform: {
114
+ legacyDecorator: Boolean(compilerOptions.experimentalDecorators),
115
+ decoratorMetadata: Boolean(compilerOptions.emitDecoratorMetadata),
116
+ useDefineForClassFields,
117
+ react: {
118
+ runtime: 'react' === compilerOptions.jsx ? 'classic' : 'automatic',
119
+ importSource: compilerOptions.jsxImportSource
120
+ }
121
+ }
122
+ }
123
+ };
124
+ };
125
+ const registerSwc = (options)=>{
126
+ const shouldInstall = !currentOptions;
127
+ currentOptions = options;
128
+ if (!shouldInstall) return;
129
+ process.setSourceMapsEnabled(true);
130
+ const extensions = external_node_module_default()._extensions;
131
+ for (const ext of TS_EXTENSIONS){
132
+ const originalHandler = extensions[ext];
133
+ extensions[ext] = (module, filename)=>{
134
+ const { distDir, compilerOptions } = currentOptions;
135
+ if (isIgnored(filename, distDir)) return void (originalHandler || extensions['.js'])(module, filename);
136
+ const source = utils_namespaceObject.fs.readFileSync(filename, 'utf-8');
137
+ const { code } = (0, core_namespaceObject.transformSync)(source, createSwcOptions(filename, compilerOptions));
138
+ module._compile(code, filename);
139
+ };
140
+ }
141
+ };
142
+ exports.createSwcOptions = __webpack_exports__.createSwcOptions;
143
+ exports.readCompilerOptions = __webpack_exports__.readCompilerOptions;
144
+ exports.registerSwc = __webpack_exports__.registerSwc;
145
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
146
+ "createSwcOptions",
147
+ "readCompilerOptions",
148
+ "registerSwc"
149
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
150
+ Object.defineProperty(exports, '__esModule', {
151
+ value: true
152
+ });
@@ -1,9 +1,9 @@
1
1
  import { isPromise } from "node:util/types";
2
- import { createDebugger, fs, getArgv, getMeta, isApiOnly, isDevCommand, minimist } from "@modern-js/utils";
2
+ import { createDebugger, fs, getArgv, getMeta, isApiOnly, isDevCommand } from "@modern-js/utils";
3
3
  import { createBuilderGenerator } from "../../builder/index.mjs";
4
4
  import { initialNormalizedConfig } from "../../config/index.mjs";
5
5
  import { emitResolvedConfig } from "../../utils/config.mjs";
6
- import { getSelectedEntries } from "../../utils/getSelectedEntries.mjs";
6
+ import { getSelectedEntries, parseEntryOption } from "../../utils/getSelectedEntries.mjs";
7
7
  import { printInstructions } from "../../utils/printInstructions.mjs";
8
8
  import { generateRoutes } from "../../utils/routes.mjs";
9
9
  import { checkIsBuildCommands, checkIsServeCommand } from "./utils.mjs";
@@ -104,10 +104,7 @@ const analyze = ()=>({
104
104
  partialsByEntrypoint
105
105
  });
106
106
  let checkedEntries = entrypoints.map((point)=>point.entryName);
107
- if (isDevCommand()) {
108
- const { entry } = minimist(getArgv());
109
- checkedEntries = await getSelectedEntries('string' == typeof entry ? entry.split(',') : entry, entrypoints);
110
- }
107
+ if (isDevCommand()) checkedEntries = await getSelectedEntries(parseEntryOption(getArgv()), entrypoints);
111
108
  appContext = {
112
109
  ...api.getAppContext(),
113
110
  entrypoints,
@@ -1,5 +1,13 @@
1
- import { chalk, inquirer } from "@modern-js/utils";
1
+ import { chalk, inquirer, minimist } from "@modern-js/utils";
2
2
  import { i18n, localeKeys } from "../locale/index.mjs";
3
+ const parseEntryOption = (argv)=>{
4
+ const { entry } = minimist(argv, {
5
+ alias: {
6
+ e: 'entry'
7
+ }
8
+ });
9
+ return 'string' == typeof entry ? entry.split(',') : entry ?? false;
10
+ };
3
11
  const getSelectedEntries = async (entry, entrypoints)=>{
4
12
  const entryNames = entrypoints.map((e)=>e.entryName);
5
13
  if (!entry) return entryNames;
@@ -23,4 +31,4 @@ const getSelectedEntries = async (entry, entrypoints)=>{
23
31
  });
24
32
  return entry;
25
33
  };
26
- export { getSelectedEntries };
34
+ export { getSelectedEntries, parseEntryOption };
@@ -46,8 +46,9 @@ const createRuntimePaths = ({ alias, paths, absoluteBaseUrl })=>{
46
46
  });
47
47
  return normalizedPaths;
48
48
  };
49
- const resolveTsRuntimeRegisterMode = (hasTsNode)=>{
49
+ const resolveTsRuntimeRegisterMode = (hasTsNode, moduleType)=>{
50
50
  if (hasTsNode) return 'ts-node';
51
+ if ('module' !== moduleType) return 'swc';
51
52
  const hasNativeTypeScriptSupport = process.features?.typescript;
52
53
  const nodeMajorVersion = Number(process.versions.node.split('.')[0]);
53
54
  const supportsNativeTypeScript = void 0 === hasNativeTypeScriptSupport ? nodeMajorVersion >= 22 : false !== hasNativeTypeScriptSupport;
@@ -59,7 +60,7 @@ const setupTsRuntime = async (appDir, distDir, alias, options = {})=>{
59
60
  const isTsProject = await fs.pathExists(tsconfigPath);
60
61
  const hasTsNode = isDepExists(appDir, 'ts-node');
61
62
  if (!isTsProject) return;
62
- const registerMode = resolveTsRuntimeRegisterMode(hasTsNode);
63
+ const registerMode = resolveTsRuntimeRegisterMode(hasTsNode, options.moduleType);
63
64
  const aliasConfig = getAliasConfig(alias, {
64
65
  appDirectory: appDir,
65
66
  tsconfigPath
@@ -101,6 +102,17 @@ const setupTsRuntime = async (appDir, distDir, alias, options = {})=>{
101
102
  ],
102
103
  ...tsNodeOptions
103
104
  });
105
+ } else if ('swc' === registerMode) {
106
+ const { register } = await import("@modern-js/utils/tsconfig-paths");
107
+ register({
108
+ baseUrl: absoluteBaseUrl || './',
109
+ paths: runtimePaths
110
+ });
111
+ const { readCompilerOptions, registerSwc } = await import("./swcRegister.mjs");
112
+ registerSwc({
113
+ distDir,
114
+ compilerOptions: readCompilerOptions(tsconfigPath)
115
+ });
104
116
  } else if ('node-loader' === registerMode) {
105
117
  const { registerPathsLoader } = await import("../esm/register-esm.mjs");
106
118
  await registerPathsLoader({
@@ -0,0 +1,97 @@
1
+ import node_module from "node:module";
2
+ import node_path from "node:path";
3
+ import { transformSync } from "@swc/core";
4
+ import { fs, readTsConfigByFile } from "@modern-js/utils";
5
+ const TS_EXTENSIONS = [
6
+ '.ts',
7
+ '.tsx',
8
+ '.cts'
9
+ ];
10
+ const ES2022_OR_LATER = /^es(20(2[2-9]|[3-9]\d)|next)$/i;
11
+ let currentOptions;
12
+ const resolveExtendedConfig = (extendsPath, fromDir)=>{
13
+ const candidates = extendsPath.endsWith('.json') ? [
14
+ extendsPath
15
+ ] : [
16
+ extendsPath,
17
+ `${extendsPath}.json`,
18
+ `${extendsPath}/tsconfig.json`
19
+ ];
20
+ for (const candidate of candidates)try {
21
+ return require.resolve(candidate, {
22
+ paths: [
23
+ fromDir
24
+ ]
25
+ });
26
+ } catch {}
27
+ };
28
+ const readCompilerOptions = (tsconfigPath, visited = new Set())=>{
29
+ if (visited.has(tsconfigPath)) return {};
30
+ visited.add(tsconfigPath);
31
+ const config = readTsConfigByFile(tsconfigPath);
32
+ const extendsList = config.extends ? [].concat(config.extends) : [];
33
+ const baseOptions = extendsList.reduce((result, extendsPath)=>{
34
+ const resolved = resolveExtendedConfig(extendsPath, node_path.dirname(tsconfigPath));
35
+ return resolved ? {
36
+ ...result,
37
+ ...readCompilerOptions(resolved, visited)
38
+ } : result;
39
+ }, {});
40
+ return {
41
+ ...baseOptions,
42
+ ...config.compilerOptions
43
+ };
44
+ };
45
+ const isIgnored = (filename, distDir)=>{
46
+ if (filename.split(node_path.sep).includes('node_modules')) return true;
47
+ const relativeToDist = node_path.relative(distDir, filename);
48
+ return !relativeToDist.startsWith('..') && !node_path.isAbsolute(relativeToDist);
49
+ };
50
+ const createSwcOptions = (filename, compilerOptions = {})=>{
51
+ const tsx = filename.endsWith('.tsx');
52
+ const useDefineForClassFields = compilerOptions.useDefineForClassFields ?? ES2022_OR_LATER.test(String(compilerOptions.target ?? ''));
53
+ return {
54
+ filename,
55
+ swcrc: false,
56
+ configFile: false,
57
+ sourceMaps: 'inline',
58
+ module: {
59
+ type: 'commonjs'
60
+ },
61
+ jsc: {
62
+ target: 'es2022',
63
+ parser: {
64
+ syntax: "typescript",
65
+ tsx,
66
+ decorators: Boolean(compilerOptions.experimentalDecorators)
67
+ },
68
+ transform: {
69
+ legacyDecorator: Boolean(compilerOptions.experimentalDecorators),
70
+ decoratorMetadata: Boolean(compilerOptions.emitDecoratorMetadata),
71
+ useDefineForClassFields,
72
+ react: {
73
+ runtime: 'react' === compilerOptions.jsx ? 'classic' : 'automatic',
74
+ importSource: compilerOptions.jsxImportSource
75
+ }
76
+ }
77
+ }
78
+ };
79
+ };
80
+ const registerSwc = (options)=>{
81
+ const shouldInstall = !currentOptions;
82
+ currentOptions = options;
83
+ if (!shouldInstall) return;
84
+ process.setSourceMapsEnabled(true);
85
+ const extensions = node_module._extensions;
86
+ for (const ext of TS_EXTENSIONS){
87
+ const originalHandler = extensions[ext];
88
+ extensions[ext] = (module, filename)=>{
89
+ const { distDir, compilerOptions } = currentOptions;
90
+ if (isIgnored(filename, distDir)) return void (originalHandler || extensions['.js'])(module, filename);
91
+ const source = fs.readFileSync(filename, 'utf-8');
92
+ const { code } = transformSync(source, createSwcOptions(filename, compilerOptions));
93
+ module._compile(code, filename);
94
+ };
95
+ }
96
+ };
97
+ export { createSwcOptions, readCompilerOptions, registerSwc };
@@ -1,10 +1,10 @@
1
1
  import "node:module";
2
2
  import { isPromise } from "node:util/types";
3
- import { createDebugger, fs, getArgv, getMeta, isApiOnly, isDevCommand, minimist } from "@modern-js/utils";
3
+ import { createDebugger, fs, getArgv, getMeta, isApiOnly, isDevCommand } from "@modern-js/utils";
4
4
  import { createBuilderGenerator } from "../../builder/index.mjs";
5
5
  import { initialNormalizedConfig } from "../../config/index.mjs";
6
6
  import { emitResolvedConfig } from "../../utils/config.mjs";
7
- import { getSelectedEntries } from "../../utils/getSelectedEntries.mjs";
7
+ import { getSelectedEntries, parseEntryOption } from "../../utils/getSelectedEntries.mjs";
8
8
  import { printInstructions } from "../../utils/printInstructions.mjs";
9
9
  import { generateRoutes } from "../../utils/routes.mjs";
10
10
  import { checkIsBuildCommands, checkIsServeCommand } from "./utils.mjs";
@@ -105,10 +105,7 @@ const analyze = ()=>({
105
105
  partialsByEntrypoint
106
106
  });
107
107
  let checkedEntries = entrypoints.map((point)=>point.entryName);
108
- if (isDevCommand()) {
109
- const { entry } = minimist(getArgv());
110
- checkedEntries = await getSelectedEntries('string' == typeof entry ? entry.split(',') : entry, entrypoints);
111
- }
108
+ if (isDevCommand()) checkedEntries = await getSelectedEntries(parseEntryOption(getArgv()), entrypoints);
112
109
  appContext = {
113
110
  ...api.getAppContext(),
114
111
  entrypoints,
@@ -1,6 +1,14 @@
1
1
  import "node:module";
2
- import { chalk, inquirer } from "@modern-js/utils";
2
+ import { chalk, inquirer, minimist } from "@modern-js/utils";
3
3
  import { i18n, localeKeys } from "../locale/index.mjs";
4
+ const parseEntryOption = (argv)=>{
5
+ const { entry } = minimist(argv, {
6
+ alias: {
7
+ e: 'entry'
8
+ }
9
+ });
10
+ return 'string' == typeof entry ? entry.split(',') : entry ?? false;
11
+ };
4
12
  const getSelectedEntries = async (entry, entrypoints)=>{
5
13
  const entryNames = entrypoints.map((e)=>e.entryName);
6
14
  if (!entry) return entryNames;
@@ -24,4 +32,4 @@ const getSelectedEntries = async (entry, entrypoints)=>{
24
32
  });
25
33
  return entry;
26
34
  };
27
- export { getSelectedEntries };
35
+ export { getSelectedEntries, parseEntryOption };
@@ -48,8 +48,9 @@ const createRuntimePaths = ({ alias, paths, absoluteBaseUrl })=>{
48
48
  });
49
49
  return normalizedPaths;
50
50
  };
51
- const resolveTsRuntimeRegisterMode = (hasTsNode)=>{
51
+ const resolveTsRuntimeRegisterMode = (hasTsNode, moduleType)=>{
52
52
  if (hasTsNode) return 'ts-node';
53
+ if ('module' !== moduleType) return 'swc';
53
54
  const hasNativeTypeScriptSupport = process.features?.typescript;
54
55
  const nodeMajorVersion = Number(process.versions.node.split('.')[0]);
55
56
  const supportsNativeTypeScript = void 0 === hasNativeTypeScriptSupport ? nodeMajorVersion >= 22 : false !== hasNativeTypeScriptSupport;
@@ -61,7 +62,7 @@ const setupTsRuntime = async (appDir, distDir, alias, options = {})=>{
61
62
  const isTsProject = await fs.pathExists(tsconfigPath);
62
63
  const hasTsNode = isDepExists(appDir, 'ts-node');
63
64
  if (!isTsProject) return;
64
- const registerMode = resolveTsRuntimeRegisterMode(hasTsNode);
65
+ const registerMode = resolveTsRuntimeRegisterMode(hasTsNode, options.moduleType);
65
66
  const aliasConfig = getAliasConfig(alias, {
66
67
  appDirectory: appDir,
67
68
  tsconfigPath
@@ -103,6 +104,17 @@ const setupTsRuntime = async (appDir, distDir, alias, options = {})=>{
103
104
  ],
104
105
  ...tsNodeOptions
105
106
  });
107
+ } else if ('swc' === registerMode) {
108
+ const { register } = await import("@modern-js/utils/tsconfig-paths");
109
+ register({
110
+ baseUrl: absoluteBaseUrl || './',
111
+ paths: runtimePaths
112
+ });
113
+ const { readCompilerOptions, registerSwc } = await import("./swcRegister.mjs");
114
+ registerSwc({
115
+ distDir,
116
+ compilerOptions: readCompilerOptions(tsconfigPath)
117
+ });
106
118
  } else if ('node-loader' === registerMode) {
107
119
  const { registerPathsLoader } = await import("../esm/register-esm.mjs");
108
120
  await registerPathsLoader({
@@ -0,0 +1,99 @@
1
+ import __rslib_shim_module__ from "node:module";
2
+ const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(/*#__PURE__*/ (()=>import.meta.url)());
3
+ import node_module from "node:module";
4
+ import node_path from "node:path";
5
+ import { transformSync } from "@swc/core";
6
+ import { fs, readTsConfigByFile } from "@modern-js/utils";
7
+ const TS_EXTENSIONS = [
8
+ '.ts',
9
+ '.tsx',
10
+ '.cts'
11
+ ];
12
+ const ES2022_OR_LATER = /^es(20(2[2-9]|[3-9]\d)|next)$/i;
13
+ let currentOptions;
14
+ const resolveExtendedConfig = (extendsPath, fromDir)=>{
15
+ const candidates = extendsPath.endsWith('.json') ? [
16
+ extendsPath
17
+ ] : [
18
+ extendsPath,
19
+ `${extendsPath}.json`,
20
+ `${extendsPath}/tsconfig.json`
21
+ ];
22
+ for (const candidate of candidates)try {
23
+ return require.resolve(candidate, {
24
+ paths: [
25
+ fromDir
26
+ ]
27
+ });
28
+ } catch {}
29
+ };
30
+ const readCompilerOptions = (tsconfigPath, visited = new Set())=>{
31
+ if (visited.has(tsconfigPath)) return {};
32
+ visited.add(tsconfigPath);
33
+ const config = readTsConfigByFile(tsconfigPath);
34
+ const extendsList = config.extends ? [].concat(config.extends) : [];
35
+ const baseOptions = extendsList.reduce((result, extendsPath)=>{
36
+ const resolved = resolveExtendedConfig(extendsPath, node_path.dirname(tsconfigPath));
37
+ return resolved ? {
38
+ ...result,
39
+ ...readCompilerOptions(resolved, visited)
40
+ } : result;
41
+ }, {});
42
+ return {
43
+ ...baseOptions,
44
+ ...config.compilerOptions
45
+ };
46
+ };
47
+ const isIgnored = (filename, distDir)=>{
48
+ if (filename.split(node_path.sep).includes('node_modules')) return true;
49
+ const relativeToDist = node_path.relative(distDir, filename);
50
+ return !relativeToDist.startsWith('..') && !node_path.isAbsolute(relativeToDist);
51
+ };
52
+ const createSwcOptions = (filename, compilerOptions = {})=>{
53
+ const tsx = filename.endsWith('.tsx');
54
+ const useDefineForClassFields = compilerOptions.useDefineForClassFields ?? ES2022_OR_LATER.test(String(compilerOptions.target ?? ''));
55
+ return {
56
+ filename,
57
+ swcrc: false,
58
+ configFile: false,
59
+ sourceMaps: 'inline',
60
+ module: {
61
+ type: 'commonjs'
62
+ },
63
+ jsc: {
64
+ target: 'es2022',
65
+ parser: {
66
+ syntax: "typescript",
67
+ tsx,
68
+ decorators: Boolean(compilerOptions.experimentalDecorators)
69
+ },
70
+ transform: {
71
+ legacyDecorator: Boolean(compilerOptions.experimentalDecorators),
72
+ decoratorMetadata: Boolean(compilerOptions.emitDecoratorMetadata),
73
+ useDefineForClassFields,
74
+ react: {
75
+ runtime: 'react' === compilerOptions.jsx ? 'classic' : 'automatic',
76
+ importSource: compilerOptions.jsxImportSource
77
+ }
78
+ }
79
+ }
80
+ };
81
+ };
82
+ const registerSwc = (options)=>{
83
+ const shouldInstall = !currentOptions;
84
+ currentOptions = options;
85
+ if (!shouldInstall) return;
86
+ process.setSourceMapsEnabled(true);
87
+ const extensions = node_module._extensions;
88
+ for (const ext of TS_EXTENSIONS){
89
+ const originalHandler = extensions[ext];
90
+ extensions[ext] = (module, filename)=>{
91
+ const { distDir, compilerOptions } = currentOptions;
92
+ if (isIgnored(filename, distDir)) return void (originalHandler || extensions['.js'])(module, filename);
93
+ const source = fs.readFileSync(filename, 'utf-8');
94
+ const { code } = transformSync(source, createSwcOptions(filename, compilerOptions));
95
+ module._compile(code, filename);
96
+ };
97
+ }
98
+ };
99
+ export { createSwcOptions, readCompilerOptions, registerSwc };
@@ -1,4 +1,5 @@
1
1
  import type { Entrypoint } from '@modern-js/types';
2
+ export declare const parseEntryOption: (argv: string[]) => string[] | boolean;
2
3
  /**
3
4
  * Allow user to select entrypoints to build.
4
5
  */
@@ -1,6 +1,6 @@
1
1
  import { type Alias } from '@modern-js/utils';
2
2
  import type { ConfigChain } from '@rsbuild/core';
3
- type TsRuntimeRegisterMode = 'ts-node' | 'node-loader' | 'unsupported';
3
+ type TsRuntimeRegisterMode = 'ts-node' | 'swc' | 'node-loader' | 'unsupported';
4
4
  interface TsRuntimeSetupOptions {
5
5
  moduleType?: string;
6
6
  /**
@@ -10,10 +10,11 @@ interface TsRuntimeSetupOptions {
10
10
  */
11
11
  tsconfigPath?: string;
12
12
  }
13
- export declare const resolveTsRuntimeRegisterMode: (hasTsNode: boolean) => TsRuntimeRegisterMode;
13
+ export declare const resolveTsRuntimeRegisterMode: (hasTsNode: boolean, moduleType?: string) => TsRuntimeRegisterMode;
14
14
  /**
15
15
  * Setup TypeScript runtime support.
16
- * Register ts-node for compilation and tsconfig-paths for path alias resolution.
16
+ * Register ts-node (or swc when ts-node is not installed) for compilation and
17
+ * tsconfig-paths for path alias resolution.
17
18
  */
18
19
  export declare const setupTsRuntime: (appDir: string, distDir: string, alias?: ConfigChain<Alias>, options?: TsRuntimeSetupOptions) => Promise<void>;
19
20
  export {};
@@ -0,0 +1,22 @@
1
+ import { type Options } from '@swc/core';
2
+ type CompilerOptions = Record<string, any>;
3
+ interface SwcRegisterOptions {
4
+ distDir: string;
5
+ compilerOptions?: CompilerOptions;
6
+ }
7
+ /**
8
+ * Read `compilerOptions` of a tsconfig file, following `extends` so options
9
+ * like `experimentalDecorators` from a shared base config are respected.
10
+ */
11
+ export declare const readCompilerOptions: (tsconfigPath: string, visited?: Set<string>) => CompilerOptions;
12
+ export declare const createSwcOptions: (filename: string, compilerOptions?: CompilerOptions) => Options;
13
+ /**
14
+ * Compile `.ts` files to CommonJS with swc through CJS require hooks.
15
+ *
16
+ * Used when ts-node is not installed. Unlike Node.js native type stripping,
17
+ * the compiled modules live in `require.cache`, so the dev server can reload
18
+ * them by deleting cache entries, and syntax that needs transforming (enum,
19
+ * decorators, parameter properties, etc.) keeps working.
20
+ */
21
+ export declare const registerSwc: (options: SwcRegisterOptions) => void;
22
+ export {};
@@ -0,0 +1,159 @@
1
+ > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.
2
+
3
+ # MCP Apps
4
+
5
+ Modern.js builds React cards for MCP hosts. UI builds and servers exchange only `ui-manifest.json`. Servers use the official MCP SDK directly.
6
+
7
+ ## Create a project
8
+
9
+ ```bash
10
+ npx @modern-js/create@latest my-mcp --template mcp-apps
11
+ npx @modern-js/create@latest my-mf-mcp --template mcp-apps --mf
12
+ ```
13
+
14
+ Choose a release containing MCP Apps support. Run `pnpm dev`. The explicit BFF route is `/api/mcp`.
15
+
16
+ `@modern-js/mcp-apps` provides the build plugin, server plugin, server adapters and card runtime through `./cli`, `./server-plugin`, `./server` and `./react`. The application must install the peers `react`, `react-dom`, `@modelcontextprotocol/server` and `@modelcontextprotocol/ext-apps`, so cards use the application's React and tools, resources and HTTP handling use the application's SDK versions. `@modern-js/server-runtime` and `@module-federation/enhanced` are optional peers that provide the default request context for BFF handlers and the default MF shell runtime. The project templates already declare these dependencies.
17
+
18
+ ## Build cards
19
+
20
+ Declare local default-export React components or this project's MF exposes in `mcp-views.json`:
21
+
22
+ ```json
23
+ {
24
+ "views": {
25
+ "todos": "./src/components/Todos.tsx",
26
+ "stats": { "expose": "./Stats" }
27
+ },
28
+ "csp": { "resourceDomains": [], "connectDomains": [] },
29
+ "prefersBorder": true
30
+ }
31
+ ```
32
+
33
+ Import `mcpAppsPlugin` from `@modern-js/mcp-apps/cli` and add `mcpAppsPlugin({ views: './mcp-views.json' })` to your Modern.js plugins. Paths resolve relative to the JSON file. MF cards require the Modern.js MF plugin with manifest output enabled. The UI plugin validates exposes against the actual emitted MF manifest and builds the shell with the application's React dependencies.
34
+
35
+ The plugin finds the MF manifest in the web build output by filename, `mf-manifest.json` by default, and requires exactly one match. The shell imports `createInstance` from `@module-federation/enhanced/runtime` by default. Other MF implementations can replace both through the `mf` option:
36
+
37
+ ```ts
38
+ mcpAppsPlugin({
39
+ views: './mcp-views.json',
40
+ mf: {
41
+ // MF manifest filename in the build output
42
+ manifestFile: 'vmok-manifest.json',
43
+ // Resolved from the application. Must export a compatible createInstance
44
+ runtime: '@vmok/kit/runtime',
45
+ },
46
+ });
47
+ ```
48
+
49
+ Local cards build as separate entries without the framework page runtime. With `source.enableAsyncEntry`, each entry adds a dynamic import boundary so MF shared dependencies can initialize. The MF plugin enables this option automatically. Otherwise cards mount directly without an extra request.
50
+
51
+
52
+ ```tsx
53
+ import type { McpViewProps } from '@modern-js/mcp-apps/react'
54
+
55
+ export default function Todos({
56
+ todos = [],
57
+ mcpApp,
58
+ }: McpViewProps<{ todos: string[] }>) {
59
+ return (
60
+ <section>
61
+ <ul>
62
+ {todos.map(todo => (
63
+ <li key={todo}>{todo}</li>
64
+ ))}
65
+ </ul>
66
+ <button
67
+ onClick={() =>
68
+ mcpApp.callServerTool({ name: 'refresh', arguments: {} })
69
+ }
70
+ >
71
+ Refresh
72
+ </button>
73
+ </section>
74
+ )
75
+ }
76
+ ```
77
+
78
+ Props come from successful `structuredContent`. The reserved `mcpApp` prop is injected by the wrapper. Input arguments are not merged into props. New input, cancellation and teardown clear previous output. The wrapper manages connection, host styling and loading/error states. Results from tools called inside a card must be handled by the component itself.
79
+
80
+ ## Write the server
81
+
82
+ Enable `bffPlugin()` and create `api/lambda/mcp.ts`. The UI plugin does not register any HTTP route.
83
+
84
+
85
+ ```ts
86
+ import { McpServer } from '@modelcontextprotocol/server'
87
+ import { registerAppTool } from '@modelcontextprotocol/ext-apps/server'
88
+ import {
89
+ createBffHandlers,
90
+ registerUiResources,
91
+ } from '@modern-js/mcp-apps/server'
92
+ import { z } from 'zod'
93
+
94
+ async function createServer(request: Request) {
95
+ const server = new McpServer({ name: 'todos', version: '1.0.0' })
96
+ const ui = await registerUiResources(server, { request })
97
+ registerAppTool(
98
+ server,
99
+ 'list_todos',
100
+ {
101
+ inputSchema: z.object({}),
102
+ _meta: { ui: { resourceUri: ui.todos } },
103
+ },
104
+ async () => ({
105
+ content: [{ type: 'text', text: 'Todo list' }],
106
+ structuredContent: { todos: ['Read the MCP Apps guide'] },
107
+ }),
108
+ )
109
+ return server
110
+ }
111
+
112
+ export const { POST, GET, DELETE } = createBffHandlers(createServer)
113
+ ```
114
+
115
+ The adapter reconstructs BFF's consumed JSON body and returns the SDK Response. It reads the raw request through `useHonoContext` from `@modern-js/server-runtime`. Frameworks built on Modern.js can pass their own implementation with `createBffHandlers(createServer, { useContext })`. The official SDK owns protocol serving and tool validation. Serving is stateless, so unsupported session operations such as GET and DELETE are rejected by the SDK. Return a fresh server per request. Put authentication and authorization in surrounding middleware or the factory, and persist business data in an external store.
116
+
117
+ For independent Hono servers, create `handle = createFetchHandler(createServer)` and mount `app.all('/mcp', c => handle(c.req.raw))`. Foreign browser origins are rejected unless listed in `allowedOrigins` in the adapter's second argument.
118
+
119
+ ## Manifest and deployment
120
+
121
+ Builds emit `dist/mcp-apps/ui-manifest.json` and `dist/mcp-apps/ui/*.html`. Static JavaScript, CSS and MF files remain in the application's standard output. MF-only projects also emit a UI manifest. Local HTML filenames use a stable hash of the view name. MF cards share `mcp-shell.html`.
122
+
123
+ The version 1 manifest contains `assetBase`, `remotes` and `views`. A local view has `{ html, ui }`. An MF view has `{ remote, expose, ui }`, with its remote declaring `{ entry, shell }`.
124
+
125
+ - HTML and shell paths resolve relative to the manifest location
126
+ - MF entry paths resolve relative to `assetBase`
127
+ - Absolute HTTP(S) sources are supported for independent deployments
128
+ - `ui` preserves CSP, permissions, domain and border preferences
129
+ - Resource URIs are generated as `ui://app/<encoded-view-name>` by the server, and multiple tools can share a card
130
+ - MF configuration is injected into resource HTML instead of tool results
131
+
132
+ `createBffHandlers()` associates the server plugin’s manifest path and runtime mode with the current request. Call `registerUiResources(server, { request })` to resolve them automatically. Development uses the framework internal directory and production uses the runtime output directory. Explicit options override injected configuration. Independent services must provide a `manifest` file path or HTTP(S) URL. The `mode` option defaults to `production`. Relative HTML resolves against the manifest location.
133
+
134
+ Manifests are cached by source URL and environment. Production caches successful loads for the process lifetime, so updating the same location requires a process restart. Development detects local file changes and caches remote manifests for 60 seconds. Concurrent loads are coalesced and failures can be retried. HTML is read per resource request, and request-specific URLs and metadata remain isolated.
135
+
136
+ An absolute `output.assetPrefix` becomes `assetBase`. Otherwise request-origin resolution is used. Override `assetBase` in `registerUiResources` for a separate static origin or deployment path prefix. Request mode honors sanitized `x-forwarded-proto` headers. Reverse proxies must preserve the public host and sanitize forwarded headers.
137
+
138
+ Required asset, connection and base URI origins are added to CSP. MF entry origins are also added to connection permissions. The origin of an absolute or protocol-relative `output.assetPrefix` is added at build time, with `//cdn.example/` treated as `https://cdn.example`. Declare any other API, chunk/CDN or iframe origins in `mcp-views.json`, or pass domains computed in the config through `mcpAppsPlugin({ csp })`. Both are merged into every view. Deploy the manifest and HTML together with the application static assets and MF output.
139
+
140
+ Platforms may rewrite file and MF addresses to absolute URLs and combine cards into another manifest of the same version. Unknown versions are rejected.
141
+
142
+ ## Card capabilities
143
+
144
+ Cards advertise `inline` and `fullscreen` by default. Both local component modules and MF exposes can export `mcpCapabilities` to declare additional capabilities or override the display modes.
145
+
146
+
147
+ ```tsx
148
+ import type { McpCapabilities } from '@modern-js/mcp-apps/react'
149
+
150
+ export const mcpCapabilities = {
151
+ availableDisplayModes: ['inline'],
152
+ } satisfies McpCapabilities
153
+
154
+ export default function Card() {
155
+ return <div>My card</div>
156
+ }
157
+ ```
158
+
159
+ You can also pass capabilities as the third argument to `createMcpView`. Explicit display mode arrays replace the defaults. MF modules are loaded before initialization so the handshake includes their capabilities. Declaring fullscreen support does not add a fullscreen button or switch modes automatically.
package/docs/llms.txt CHANGED
@@ -52,6 +52,7 @@
52
52
  - [Extend Request SDK](/guides/advanced-features/bff/sdk.md): The unified invocation of BFF functions is isomorphic in both CSR and SSR. The request SDK encapsulated by Modern.js relies on the Fetch API on the browser side, and on node-fetch on the server side. However, in actual business scenarios, additional processing may be required for requests or responses, such as: Writing authentication information in the request headersUniform handling of response data or errorsUsing other methods to send requests when the native fetch function is unavailable on specific platforms To address these scenarios, Modern.js provides the configure function, which offers a series of extension capabilities. You can use it to configure SSR passthrough request headers, add interceptors, or customize the request SDK.
53
53
  - [File Upload](/guides/advanced-features/bff/upload.md): BFF combined with runtime framework provides file upload capabilities, supporting integrated calls and pure function manual calls. BFF Function First, create the api/lambda/upload.ts file: Integrated Calling Next, directly import and call the function in src/routes/upload/page.tsx: Manual Calling You can manually upload files using the fetch API, when calling fetch, set the body as FormData type and submit a post request.
54
54
  - [Cross-Project Invocation](/guides/advanced-features/bff/cross-project.md): Based on the BFF architecture, Modern.js provides cross-project invocation capabilities, allowing BFF functions created in one project to be invoked by other projects through integrated calls, enabling function sharing and feature reuse across projects. Cross-project invocation consists of producer and consumer sides. The producer is responsible for creating and providing BFF services while generating integrated invocation SDK, and the consumer initiates requests through these SDK.
55
+ - [MCP Apps](/guides/advanced-features/mcp-apps.md): Modern.js builds React cards for MCP hosts. UI builds and servers exchange only ui-manifest.json. Servers use the official MCP SDK directly.
55
56
  - [Code Splitting](/guides/advanced-features/page-performance/code-split.md): Code splitting is a common way to optimize frontend resource loading. This article will introduce the three types of code splitting supported by Modern.js: dynamic importReact.lazyloadable
56
57
  - [Inline Static Assets](/guides/advanced-features/page-performance/inline-assets.md): Inline static assets refer to the practice of including the content of a static asset directly in a HTML or JS file, instead of linking to an external file. This can improve the performance of a website by reducing the number of HTTP requests that the browser has to make to load the page. However, static assets inlining also has some disadvantages, such as increasing the size of a single file, which may lead to slower loading. Therefore, in the actual scenario, it is necessary to decide whether to use static assets inlining according to the specific situation. Modern.js will automatically inline static assets that are less than 10KB, but sometimes you may need to manually control assets to force them to be inlined or not, and this document explains how to precisely control the inlining behavior of static assets.
57
58
  - [Bundle Size Optimization](/guides/advanced-features/page-performance/optimize-bundle.md): Bundle size optimization is an important part of optimizing your production environment because it directly affects the user experience. In this document, we will introduce some common bundle size optimization methods in Modern.js.
package/package.json CHANGED
@@ -15,7 +15,7 @@
15
15
  "modern",
16
16
  "modern.js"
17
17
  ],
18
- "version": "3.10.3",
18
+ "version": "3.11.0",
19
19
  "types": "./dist/types/index.d.ts",
20
20
  "main": "./dist/cjs/index.js",
21
21
  "exports": {
@@ -113,11 +113,11 @@
113
113
  }
114
114
  },
115
115
  "dependencies": {
116
- "@babel/parser": "^7.29.9",
116
+ "@babel/parser": "^7.29.11",
117
117
  "@babel/traverse": "^7.29.10",
118
- "@babel/types": "^7.29.8",
118
+ "@babel/types": "^7.29.11",
119
119
  "@rsbuild/core": "2.2.13",
120
- "@swc/core": "1.16.18",
120
+ "@swc/core": "1.16.20",
121
121
  "@swc/helpers": "^0.5.17",
122
122
  "es-module-lexer": "^1.7.0",
123
123
  "flatted": "^3.4.4",
@@ -126,16 +126,16 @@
126
126
  "ndepe": "^0.1.13",
127
127
  "pkg-types": "^1.3.1",
128
128
  "std-env": "^3.10.0",
129
- "@modern-js/builder": "3.10.3",
130
- "@modern-js/plugin": "3.10.3",
131
- "@modern-js/i18n-utils": "3.10.3",
132
- "@modern-js/plugin-data-loader": "3.10.3",
133
- "@modern-js/prod-server": "3.10.3",
134
- "@modern-js/server": "3.10.3",
135
- "@modern-js/server-core": "3.10.3",
136
- "@modern-js/server-utils": "3.10.3",
137
- "@modern-js/types": "3.10.3",
138
- "@modern-js/utils": "3.10.3"
129
+ "@modern-js/builder": "3.11.0",
130
+ "@modern-js/i18n-utils": "3.11.0",
131
+ "@modern-js/plugin": "3.11.0",
132
+ "@modern-js/prod-server": "3.11.0",
133
+ "@modern-js/plugin-data-loader": "3.11.0",
134
+ "@modern-js/server": "3.11.0",
135
+ "@modern-js/server-core": "3.11.0",
136
+ "@modern-js/server-utils": "3.11.0",
137
+ "@modern-js/types": "3.11.0",
138
+ "@modern-js/utils": "3.11.0"
139
139
  },
140
140
  "devDependencies": {
141
141
  "@types/babel__traverse": "7.28.0",
@@ -143,8 +143,8 @@
143
143
  "ts-node": "^10.9.2",
144
144
  "tsconfig-paths": "^4.2.0",
145
145
  "typescript": "^5",
146
- "@scripts/rstest-config": "2.66.2",
147
- "@modern-js/rslib": "3.10.3"
146
+ "@modern-js/rslib": "3.11.0",
147
+ "@scripts/rstest-config": "2.66.4"
148
148
  },
149
149
  "peerDependencies": {
150
150
  "ts-node": "^10.9.2",