@bleedingdev/modern-js-server 3.2.0-ultramodern.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.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -0
  3. package/dist/cjs/createDevServer.js +102 -0
  4. package/dist/cjs/dev-tools/https/index.js +57 -0
  5. package/dist/cjs/dev-tools/watcher/dependencyTree.js +94 -0
  6. package/dist/cjs/dev-tools/watcher/index.js +143 -0
  7. package/dist/cjs/dev-tools/watcher/statsCache.js +95 -0
  8. package/dist/cjs/dev.js +111 -0
  9. package/dist/cjs/helpers/devOptions.js +61 -0
  10. package/dist/cjs/helpers/fileReader.js +53 -0
  11. package/dist/cjs/helpers/index.js +173 -0
  12. package/dist/cjs/helpers/mock.js +136 -0
  13. package/dist/cjs/helpers/repack.js +50 -0
  14. package/dist/cjs/helpers/utils.js +37 -0
  15. package/dist/cjs/index.js +36 -0
  16. package/dist/cjs/types.js +18 -0
  17. package/dist/esm/createDevServer.mjs +58 -0
  18. package/dist/esm/dev-tools/https/index.mjs +23 -0
  19. package/dist/esm/dev-tools/watcher/dependencyTree.mjs +57 -0
  20. package/dist/esm/dev-tools/watcher/index.mjs +91 -0
  21. package/dist/esm/dev-tools/watcher/statsCache.mjs +50 -0
  22. package/dist/esm/dev.mjs +77 -0
  23. package/dist/esm/helpers/devOptions.mjs +24 -0
  24. package/dist/esm/helpers/fileReader.mjs +19 -0
  25. package/dist/esm/helpers/index.mjs +65 -0
  26. package/dist/esm/helpers/mock.mjs +86 -0
  27. package/dist/esm/helpers/repack.mjs +16 -0
  28. package/dist/esm/helpers/utils.mjs +3 -0
  29. package/dist/esm/index.mjs +1 -0
  30. package/dist/esm/types.mjs +0 -0
  31. package/dist/esm-node/createDevServer.mjs +59 -0
  32. package/dist/esm-node/dev-tools/https/index.mjs +28 -0
  33. package/dist/esm-node/dev-tools/watcher/dependencyTree.mjs +58 -0
  34. package/dist/esm-node/dev-tools/watcher/index.mjs +93 -0
  35. package/dist/esm-node/dev-tools/watcher/statsCache.mjs +51 -0
  36. package/dist/esm-node/dev.mjs +78 -0
  37. package/dist/esm-node/helpers/devOptions.mjs +25 -0
  38. package/dist/esm-node/helpers/fileReader.mjs +20 -0
  39. package/dist/esm-node/helpers/index.mjs +67 -0
  40. package/dist/esm-node/helpers/mock.mjs +87 -0
  41. package/dist/esm-node/helpers/repack.mjs +18 -0
  42. package/dist/esm-node/helpers/utils.mjs +4 -0
  43. package/dist/esm-node/index.mjs +2 -0
  44. package/dist/esm-node/types.mjs +1 -0
  45. package/dist/types/createDevServer.d.ts +8 -0
  46. package/dist/types/dev-tools/https/index.d.ts +6 -0
  47. package/dist/types/dev-tools/watcher/dependencyTree.d.ts +28 -0
  48. package/dist/types/dev-tools/watcher/index.d.ts +17 -0
  49. package/dist/types/dev-tools/watcher/statsCache.d.ts +10 -0
  50. package/dist/types/dev.d.ts +9 -0
  51. package/dist/types/helpers/devOptions.d.ts +11 -0
  52. package/dist/types/helpers/fileReader.d.ts +3 -0
  53. package/dist/types/helpers/index.d.ts +15 -0
  54. package/dist/types/helpers/mock.d.ts +16 -0
  55. package/dist/types/helpers/repack.d.ts +2 -0
  56. package/dist/types/helpers/utils.d.ts +1 -0
  57. package/dist/types/index.d.ts +4 -0
  58. package/dist/types/types.d.ts +56 -0
  59. package/package.json +89 -0
  60. package/rslib.config.mts +4 -0
  61. package/rstest.config.mts +5 -0
@@ -0,0 +1,57 @@
1
+ import * as __rspack_external_minimatch from "minimatch";
2
+ const defaultIgnores = [
3
+ '**/coverage/**',
4
+ '**/node_modules/**',
5
+ '**/.*/**',
6
+ '**/*.d.ts',
7
+ '**/*.log'
8
+ ];
9
+ class DependencyTree {
10
+ getNode(path) {
11
+ return this.tree.get(path);
12
+ }
13
+ update(cache) {
14
+ this.tree.clear();
15
+ Object.keys(cache).forEach((path)=>{
16
+ if (!this.shouldIgnore(path)) {
17
+ const module = cache[path];
18
+ this.tree.set(module.filename, {
19
+ module,
20
+ parent: new Set(),
21
+ children: new Set()
22
+ });
23
+ }
24
+ });
25
+ for (const treeNode of this.tree.values()){
26
+ const { parent } = treeNode.module;
27
+ const { children } = treeNode.module;
28
+ if (parent && !this.shouldIgnore(parent.filename)) {
29
+ const parentTreeNode = this.tree.get(parent.filename);
30
+ if (parentTreeNode) treeNode.parent.add(parentTreeNode);
31
+ }
32
+ children?.forEach((child)=>{
33
+ if (!this.shouldIgnore(child.filename)) {
34
+ const childTreeNode = this.tree.get(child.filename);
35
+ if (childTreeNode) {
36
+ treeNode.children.add(childTreeNode);
37
+ childTreeNode.parent.add(treeNode);
38
+ }
39
+ }
40
+ });
41
+ }
42
+ }
43
+ shouldIgnore(path) {
44
+ return !path || Boolean(this.ignore.find((rule)=>__rspack_external_minimatch.match([
45
+ path
46
+ ], rule, {
47
+ dot: true
48
+ }).length > 0));
49
+ }
50
+ constructor(){
51
+ this.tree = new Map();
52
+ this.ignore = [
53
+ ...defaultIgnores
54
+ ];
55
+ }
56
+ }
57
+ export { DependencyTree, defaultIgnores };
@@ -0,0 +1,91 @@
1
+ import { chokidar, fs } from "@modern-js/utils";
2
+ import path from "path";
3
+ import { DependencyTree } from "./dependencyTree.mjs";
4
+ import { StatsCache } from "./statsCache.mjs";
5
+ const defaultWatchOptions = {
6
+ ignoreInitial: true,
7
+ ignored: /api\/typings\/.*/
8
+ };
9
+ const getWatchedFiles = (watcher)=>{
10
+ const watched = watcher.getWatched();
11
+ const files = [];
12
+ Object.keys(watched).forEach((dir)=>{
13
+ const dirFiles = watched[dir];
14
+ if (!dirFiles) return;
15
+ dirFiles.forEach((fileName)=>{
16
+ files.push(path.join(dir, fileName));
17
+ });
18
+ });
19
+ return files;
20
+ };
21
+ const mergeWatchOptions = (options)=>{
22
+ const watchOptions = {
23
+ ...options
24
+ };
25
+ if (watchOptions) {
26
+ const { ignored } = watchOptions;
27
+ const finalIgnored = ignored ? [
28
+ defaultWatchOptions.ignored,
29
+ ...Array.isArray(ignored) ? ignored : [
30
+ ignored
31
+ ]
32
+ ] : ignored;
33
+ if (finalIgnored) watchOptions.ignored = finalIgnored;
34
+ }
35
+ const finalWatchOptions = {
36
+ ...defaultWatchOptions,
37
+ ...watchOptions
38
+ };
39
+ return finalWatchOptions;
40
+ };
41
+ class Watcher {
42
+ listen(files, options, callback) {
43
+ const watched = files.filter(Boolean);
44
+ const filenames = watched.map((filename)=>filename.replace(/\\/g, '/'));
45
+ const cache = new StatsCache();
46
+ const watcher = chokidar.watch(filenames, options);
47
+ watcher.on('ready', ()=>{
48
+ cache.add(getWatchedFiles(watcher));
49
+ });
50
+ watcher.on('change', (changed)=>{
51
+ if (!fs.existsSync(changed) || cache.isDiff(changed)) {
52
+ cache.refresh(changed);
53
+ callback(changed, 'change');
54
+ }
55
+ });
56
+ watcher.on('add', (changed)=>{
57
+ if (!cache.has(changed)) {
58
+ cache.add([
59
+ changed
60
+ ]);
61
+ callback(changed, 'add');
62
+ }
63
+ });
64
+ watcher.on('unlink', (changed)=>{
65
+ cache.del(changed);
66
+ callback(changed, 'unlink');
67
+ });
68
+ this.watcher = watcher;
69
+ }
70
+ createDepTree() {
71
+ this.dependencyTree = new DependencyTree();
72
+ }
73
+ updateDepTree() {
74
+ this.dependencyTree?.update(require.cache);
75
+ }
76
+ cleanDepCache(filepath) {
77
+ const node = this.dependencyTree?.getNode(filepath);
78
+ if (node && require.cache[filepath]) {
79
+ delete require.cache[filepath];
80
+ for (const parentNode of node.parent.values())this.cleanDepCache(parentNode.module.filename);
81
+ }
82
+ }
83
+ close() {
84
+ return this.watcher.close();
85
+ }
86
+ constructor(){
87
+ this.dependencyTree = null;
88
+ }
89
+ }
90
+ export default Watcher;
91
+ export { defaultWatchOptions, getWatchedFiles, mergeWatchOptions };
@@ -0,0 +1,50 @@
1
+ import crypto_0 from "crypto";
2
+ import fs from "fs";
3
+ class StatsCache {
4
+ add(files) {
5
+ const { cachedHash, cachedSize } = this;
6
+ for (const filename of files)if (fs.existsSync(filename)) {
7
+ const stats = fs.statSync(filename);
8
+ if (stats.isFile() && !cachedHash[filename]) {
9
+ cachedHash[filename] = this.hash(stats, filename);
10
+ cachedSize[filename] = stats.size;
11
+ }
12
+ }
13
+ }
14
+ refresh(filename) {
15
+ const { cachedHash, cachedSize } = this;
16
+ if (fs.existsSync(filename)) {
17
+ const stats = fs.statSync(filename);
18
+ if (stats.isFile()) {
19
+ cachedHash[filename] = this.hash(stats, filename);
20
+ cachedSize[filename] = stats.size;
21
+ }
22
+ }
23
+ }
24
+ del(filename) {
25
+ if (this.cachedHash[filename]) {
26
+ delete this.cachedHash[filename];
27
+ delete this.cachedSize[filename];
28
+ }
29
+ }
30
+ isDiff(filename) {
31
+ const { cachedHash, cachedSize } = this;
32
+ const stats = fs.statSync(filename);
33
+ const hash = cachedHash[filename];
34
+ const size = cachedSize[filename];
35
+ if (stats.size !== size) return true;
36
+ if (this.hash(stats, filename) !== hash) return true;
37
+ return false;
38
+ }
39
+ has(filename) {
40
+ return Boolean(this.cachedHash[filename]);
41
+ }
42
+ hash(stats, filename) {
43
+ return crypto_0.createHash('md5').update(fs.readFileSync(filename)).digest('hex');
44
+ }
45
+ constructor(){
46
+ this.cachedHash = {};
47
+ this.cachedSize = {};
48
+ }
49
+ }
50
+ export { StatsCache };
@@ -0,0 +1,77 @@
1
+ import { connectMid2HonoMid } from "@modern-js/server-core/node";
2
+ import { API_DIR, SHARED_DIR } from "@modern-js/utils";
3
+ import { getDevOptions, getMockMiddleware, initFileReader, onRepack, startWatcher } from "./helpers/index.mjs";
4
+ const devPlugin = (options, compiler)=>({
5
+ name: '@modern-js/plugin-dev',
6
+ setup (api) {
7
+ const { config, pwd, builder, builderDevServer } = options;
8
+ const closeCb = [];
9
+ const dev = getDevOptions(options.dev);
10
+ api.onPrepare(async ()=>{
11
+ const { middlewares: builderMiddlewares, close, connectWebSocket } = builderDevServer || {};
12
+ close && closeCb.push(close);
13
+ const { middlewares, distDirectory, nodeServer, apiDirectory, sharedDirectory, serverBase } = api.getServerContext();
14
+ connectWebSocket && nodeServer && connectWebSocket({
15
+ server: nodeServer
16
+ });
17
+ const hooks = api.getHooks();
18
+ builder?.onDevCompileDone(({ stats })=>{
19
+ if ('server' !== stats.toJson({
20
+ all: false
21
+ }).name) onRepack(distDirectory, hooks);
22
+ });
23
+ const { watchOptions } = config.server;
24
+ const watcher = startWatcher({
25
+ pwd,
26
+ distDir: distDirectory,
27
+ apiDir: apiDirectory || API_DIR,
28
+ sharedDir: sharedDirectory || SHARED_DIR,
29
+ watchOptions,
30
+ server: serverBase
31
+ });
32
+ closeCb.push(watcher.close.bind(watcher));
33
+ closeCb.length > 0 && nodeServer?.on('close', ()=>{
34
+ closeCb.forEach((cb)=>{
35
+ cb();
36
+ });
37
+ });
38
+ const before = [];
39
+ const after = [];
40
+ const { setupMiddlewares = [] } = dev;
41
+ setupMiddlewares.forEach((handler)=>{
42
+ handler({
43
+ unshift: (...handlers)=>before.unshift(...handlers),
44
+ push: (...handlers)=>after.push(...handlers)
45
+ }, {
46
+ sockWrite: ()=>{}
47
+ });
48
+ });
49
+ before.forEach((middleware, index)=>{
50
+ middlewares.push({
51
+ name: `before-dev-server-${index}`,
52
+ handler: connectMid2HonoMid(middleware)
53
+ });
54
+ });
55
+ const mockMiddleware = await getMockMiddleware(pwd);
56
+ middlewares.push({
57
+ name: 'mock-dev',
58
+ handler: mockMiddleware
59
+ });
60
+ builderMiddlewares && middlewares.push({
61
+ name: 'rsbuild-dev',
62
+ handler: connectMid2HonoMid(builderMiddlewares)
63
+ });
64
+ after.forEach((middleware, index)=>{
65
+ middlewares.push({
66
+ name: `after-dev-server-${index}`,
67
+ handler: connectMid2HonoMid(middleware)
68
+ });
69
+ });
70
+ middlewares.push({
71
+ name: 'init-file-reader',
72
+ handler: initFileReader(compiler)
73
+ });
74
+ });
75
+ }
76
+ });
77
+ export { devPlugin };
@@ -0,0 +1,24 @@
1
+ const getDevOptions = (devOptions)=>{
2
+ const defaultOptions = {
3
+ https: false,
4
+ server: {}
5
+ };
6
+ return {
7
+ ...defaultOptions,
8
+ ...devOptions
9
+ };
10
+ };
11
+ const getDevAssetPrefix = (builder)=>new Promise((resolve)=>{
12
+ if (!builder) return resolve('');
13
+ builder?.onAfterCreateCompiler((params)=>{
14
+ let webCompiler;
15
+ webCompiler = 'compilers' in params.compiler ? params.compiler.compilers.find((c)=>'web' === c.name || 'client' === c.name) : params.compiler;
16
+ const publicPath = webCompiler?.options?.output?.publicPath;
17
+ if (publicPath && 'string' == typeof publicPath) {
18
+ const formatPublicPath = publicPath.replace(/^https?:\/\/[^/]+/, '');
19
+ return resolve(formatPublicPath);
20
+ }
21
+ return resolve('');
22
+ });
23
+ });
24
+ export { getDevAssetPrefix, getDevOptions };
@@ -0,0 +1,19 @@
1
+ import { fileReader } from "@modern-js/runtime-utils/fileReader";
2
+ const initFileReader = (compiler)=>{
3
+ let isInit = false;
4
+ return async (ctx, next)=>{
5
+ if (isInit) return next();
6
+ isInit = true;
7
+ const { res } = ctx.env.node;
8
+ if (!compiler) {
9
+ fileReader.reset();
10
+ return next();
11
+ }
12
+ const resolvedCompiler = 'compilers' in compiler ? compiler.compilers[0] : compiler;
13
+ const outputFileSystem = resolvedCompiler?.outputFileSystem;
14
+ if (outputFileSystem) fileReader.reset(outputFileSystem);
15
+ else fileReader.reset();
16
+ return next();
17
+ };
18
+ };
19
+ export { initFileReader };
@@ -0,0 +1,65 @@
1
+ import { AGGRED_DIR } from "@modern-js/server-core";
2
+ import { SERVER_BUNDLE_DIRECTORY, SERVER_DIR, logger } from "@modern-js/utils";
3
+ import path from "path";
4
+ import dev_tools_watcher, { mergeWatchOptions } from "../dev-tools/watcher/index.mjs";
5
+ import { initOrUpdateMockMiddlewares } from "./mock.mjs";
6
+ import { debug } from "./utils.mjs";
7
+ export * from "./devOptions.mjs";
8
+ export * from "./fileReader.mjs";
9
+ export * from "./mock.mjs";
10
+ export * from "./repack.mjs";
11
+ async function onServerChange({ pwd, filepath, event, server }) {
12
+ const { mock } = AGGRED_DIR;
13
+ const mockPath = path.normalize(path.join(pwd, mock));
14
+ const { hooks } = server;
15
+ if (filepath.startsWith(mockPath)) {
16
+ await initOrUpdateMockMiddlewares(pwd);
17
+ logger.info('Finish update the mock handlers');
18
+ } else try {
19
+ const fileChangeEvent = {
20
+ type: 'file-change',
21
+ payload: [
22
+ {
23
+ filename: filepath,
24
+ event
25
+ }
26
+ ]
27
+ };
28
+ await hooks.onReset.call({
29
+ event: fileChangeEvent
30
+ });
31
+ debug(`Finish reload server, trigger by ${filepath} ${event}`);
32
+ } catch (e) {
33
+ logger.error(e);
34
+ }
35
+ }
36
+ function startWatcher({ pwd, distDir, apiDir, sharedDir, watchOptions, server }) {
37
+ const { mock } = AGGRED_DIR;
38
+ const defaultWatched = [
39
+ `${mock}/**/*`,
40
+ `${SERVER_DIR}/**/*`,
41
+ `${apiDir}/**`,
42
+ `${sharedDir}/**/*`,
43
+ `${distDir}/${SERVER_BUNDLE_DIRECTORY}/*-server-loaders.js`
44
+ ];
45
+ const mergedWatchOptions = mergeWatchOptions(watchOptions);
46
+ const defaultWatchedPaths = defaultWatched.map((p)=>{
47
+ const finalPath = path.isAbsolute(p) ? p : path.join(pwd, p);
48
+ return path.normalize(finalPath);
49
+ });
50
+ const watcher = new dev_tools_watcher();
51
+ watcher.createDepTree();
52
+ watcher.listen(defaultWatchedPaths, mergedWatchOptions, (filepath, event)=>{
53
+ if (filepath.includes('-server-loaders.js')) return void delete require.cache[filepath];
54
+ watcher.updateDepTree();
55
+ watcher.cleanDepCache(filepath);
56
+ onServerChange({
57
+ pwd,
58
+ filepath,
59
+ event,
60
+ server
61
+ });
62
+ });
63
+ return watcher;
64
+ }
65
+ export { startWatcher };
@@ -0,0 +1,86 @@
1
+ import node_path from "node:path";
2
+ import { AGGRED_DIR } from "@modern-js/server-core";
3
+ import { connectMockMid2HonoMid } from "@modern-js/server-core/node";
4
+ import { fs } from "@modern-js/utils";
5
+ import { match } from "path-to-regexp";
6
+ let mockAPIs = [];
7
+ let mockConfig;
8
+ const parseKey = (key)=>{
9
+ const _blank = ' ';
10
+ const splitted = key.split(_blank).filter(Boolean);
11
+ if (splitted.length > 1) {
12
+ const [method, pathname] = splitted;
13
+ return {
14
+ method: (method ?? 'get').toLowerCase(),
15
+ path: pathname ?? '/'
16
+ };
17
+ }
18
+ return {
19
+ method: 'get',
20
+ path: key
21
+ };
22
+ };
23
+ const getMockModule = async (pwd)=>{
24
+ const exts = [
25
+ '.ts',
26
+ '.js'
27
+ ];
28
+ let mockFilePath = '';
29
+ for (const ext of exts){
30
+ const maybeMatch = node_path.join(pwd, `${AGGRED_DIR.mock}/index${ext}`);
31
+ if (await fs.pathExists(maybeMatch)) {
32
+ mockFilePath = maybeMatch;
33
+ break;
34
+ }
35
+ }
36
+ if (!mockFilePath) return;
37
+ const { default: mockHandlers, config } = await import(mockFilePath);
38
+ const enable = config?.enable;
39
+ if (false === enable) return;
40
+ if (!mockHandlers) throw new Error(`Mock file ${mockFilePath} parsed failed!`);
41
+ return {
42
+ mockHandlers,
43
+ config
44
+ };
45
+ };
46
+ const getMatched = (request, mockApis)=>{
47
+ const { path: targetPathname, method: targetMethod } = request;
48
+ const matched = mockApis.find((mockApi)=>{
49
+ const { method, path: pathname } = mockApi;
50
+ if (method.toLowerCase() === targetMethod.toLowerCase()) return match(pathname, {
51
+ decode: decodeURIComponent
52
+ })(targetPathname);
53
+ return false;
54
+ });
55
+ return matched;
56
+ };
57
+ async function initOrUpdateMockMiddlewares(pwd) {
58
+ const mockModule = await getMockModule(pwd);
59
+ mockConfig = mockModule?.config;
60
+ mockAPIs = Object.entries(mockModule?.mockHandlers || {}).map(([key, handler])=>{
61
+ const { method, path } = parseKey(key);
62
+ return {
63
+ method,
64
+ path,
65
+ handler
66
+ };
67
+ });
68
+ }
69
+ async function getMockMiddleware(pwd) {
70
+ await initOrUpdateMockMiddlewares(pwd);
71
+ const mockMiddleware = async (c, next)=>{
72
+ if ('function' == typeof mockConfig?.enable) {
73
+ const isEnabled = mockConfig.enable(c.env.node.req, c.env.node.res);
74
+ if (!isEnabled) return next();
75
+ }
76
+ const matchedMockAPI = getMatched(c.req, mockAPIs);
77
+ if (matchedMockAPI) {
78
+ const { handler } = matchedMockAPI;
79
+ if ('function' == typeof handler) return await connectMockMid2HonoMid(handler)(c, next);
80
+ return c.json(handler);
81
+ }
82
+ return next();
83
+ };
84
+ return mockMiddleware;
85
+ }
86
+ export { getMatched, getMockMiddleware, initOrUpdateMockMiddlewares };
@@ -0,0 +1,16 @@
1
+ import { fileReader } from "@modern-js/runtime-utils/fileReader";
2
+ const cleanSSRCache = (distDir)=>{
3
+ Object.keys(require.cache).forEach((key)=>{
4
+ if (key.startsWith(distDir)) delete require.cache[key];
5
+ });
6
+ };
7
+ const onRepack = (distDir, hooks)=>{
8
+ cleanSSRCache(distDir);
9
+ fileReader.reset();
10
+ hooks.onReset.call({
11
+ event: {
12
+ type: 'repack'
13
+ }
14
+ });
15
+ };
16
+ export { onRepack };
@@ -0,0 +1,3 @@
1
+ import { createDebugger } from "@modern-js/utils";
2
+ const debug = createDebugger('server');
3
+ export { debug };
@@ -0,0 +1 @@
1
+ export { createDevServer } from "./createDevServer.mjs";
File without changes
@@ -0,0 +1,59 @@
1
+ import "node:module";
2
+ import node_path from "node:path";
3
+ import { createServerBase } from "@modern-js/server-core";
4
+ import { createNodeServer, loadServerRuntimeConfig } from "@modern-js/server-core/node";
5
+ import { devPlugin } from "./dev.mjs";
6
+ import { getDevAssetPrefix, getDevOptions } from "./helpers/index.mjs";
7
+ async function createDevServer(options, applyPlugins) {
8
+ const { config, pwd, serverConfigPath, builder } = options;
9
+ const dev = getDevOptions(options.dev);
10
+ const distDir = node_path.resolve(pwd, config.output.distPath?.root || 'dist');
11
+ const serverConfig = await loadServerRuntimeConfig(serverConfigPath) || {};
12
+ const prodServerOptions = {
13
+ ...options,
14
+ pwd: distDir,
15
+ serverConfig: {
16
+ ...serverConfig,
17
+ ...options.serverConfig
18
+ },
19
+ plugins: [
20
+ ...serverConfig.plugins || [],
21
+ ...options.plugins || []
22
+ ]
23
+ };
24
+ const server = createServerBase(prodServerOptions);
25
+ const devHttpsOption = 'object' == typeof dev && dev.https;
26
+ const isHttp2 = !!devHttpsOption;
27
+ let nodeServer;
28
+ if (devHttpsOption) {
29
+ const { genHttpsOptions } = await import("./dev-tools/https/index.mjs");
30
+ const httpsOptions = await genHttpsOptions(devHttpsOption, pwd);
31
+ nodeServer = await createNodeServer(server.handle.bind(server), httpsOptions, isHttp2);
32
+ } else nodeServer = await createNodeServer(server.handle.bind(server));
33
+ const promise = getDevAssetPrefix(builder);
34
+ let compiler = null;
35
+ builder?.onAfterCreateCompiler((context)=>{
36
+ compiler = context.compiler;
37
+ });
38
+ const builderDevServer = await builder?.createDevServer({
39
+ runCompile: options.runCompile
40
+ });
41
+ server.addPlugins([
42
+ devPlugin({
43
+ ...options,
44
+ builderDevServer
45
+ }, compiler)
46
+ ]);
47
+ const assetPrefix = await promise;
48
+ if (assetPrefix) prodServerOptions.config.output.assetPrefix = assetPrefix;
49
+ await applyPlugins(server, prodServerOptions, nodeServer);
50
+ await server.init();
51
+ const afterListen = async ()=>{
52
+ await builderDevServer?.afterListen();
53
+ };
54
+ return {
55
+ server: nodeServer,
56
+ afterListen
57
+ };
58
+ }
59
+ export { createDevServer };
@@ -0,0 +1,28 @@
1
+ import __rslib_shim_module__ from "node:module";
2
+ const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(/*#__PURE__*/ (()=>import.meta.url)());
3
+ import { chalk, getPackageManager, logger, tryResolve } from "@modern-js/utils";
4
+ import { fileURLToPath as __rspack_fileURLToPath } from "node:url";
5
+ import { dirname as __rspack_dirname } from "node:path";
6
+ var https_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
7
+ const genHttpsOptions = async (userOptions, pwd)=>{
8
+ const httpsOptions = 'boolean' == typeof userOptions ? {} : userOptions;
9
+ if (!httpsOptions.key || !httpsOptions.cert) {
10
+ let devcertPath;
11
+ try {
12
+ devcertPath = tryResolve('devcert', pwd, https_dirname);
13
+ } catch (err) {
14
+ const packageManager = await getPackageManager(pwd);
15
+ const command = chalk.yellow.bold(`${packageManager} add devcert@1.2.2 -D`);
16
+ logger.error('You have enabled "dev.https" option, but the "devcert" package is not installed.');
17
+ logger.error(`Please run ${command} to install manually, otherwise the https can not work.`);
18
+ throw new Error('[https] "devcert" is not found.');
19
+ }
20
+ const devcert = require(devcertPath);
21
+ const selfsign = await devcert.certificateFor([
22
+ 'localhost'
23
+ ]);
24
+ return selfsign;
25
+ }
26
+ return httpsOptions;
27
+ };
28
+ export { genHttpsOptions };
@@ -0,0 +1,58 @@
1
+ import "node:module";
2
+ import * as __rspack_external_minimatch from "minimatch";
3
+ const defaultIgnores = [
4
+ '**/coverage/**',
5
+ '**/node_modules/**',
6
+ '**/.*/**',
7
+ '**/*.d.ts',
8
+ '**/*.log'
9
+ ];
10
+ class DependencyTree {
11
+ getNode(path) {
12
+ return this.tree.get(path);
13
+ }
14
+ update(cache) {
15
+ this.tree.clear();
16
+ Object.keys(cache).forEach((path)=>{
17
+ if (!this.shouldIgnore(path)) {
18
+ const module = cache[path];
19
+ this.tree.set(module.filename, {
20
+ module,
21
+ parent: new Set(),
22
+ children: new Set()
23
+ });
24
+ }
25
+ });
26
+ for (const treeNode of this.tree.values()){
27
+ const { parent } = treeNode.module;
28
+ const { children } = treeNode.module;
29
+ if (parent && !this.shouldIgnore(parent.filename)) {
30
+ const parentTreeNode = this.tree.get(parent.filename);
31
+ if (parentTreeNode) treeNode.parent.add(parentTreeNode);
32
+ }
33
+ children?.forEach((child)=>{
34
+ if (!this.shouldIgnore(child.filename)) {
35
+ const childTreeNode = this.tree.get(child.filename);
36
+ if (childTreeNode) {
37
+ treeNode.children.add(childTreeNode);
38
+ childTreeNode.parent.add(treeNode);
39
+ }
40
+ }
41
+ });
42
+ }
43
+ }
44
+ shouldIgnore(path) {
45
+ return !path || Boolean(this.ignore.find((rule)=>__rspack_external_minimatch.match([
46
+ path
47
+ ], rule, {
48
+ dot: true
49
+ }).length > 0));
50
+ }
51
+ constructor(){
52
+ this.tree = new Map();
53
+ this.ignore = [
54
+ ...defaultIgnores
55
+ ];
56
+ }
57
+ }
58
+ export { DependencyTree, defaultIgnores };