@ikaros-cli/ikaros 2.1.3 → 2.2.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.
- package/dist/index.d.mts +282 -153
- package/dist/index.mjs +9 -8
- package/package.json +19 -18
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as _rspack_core0 from "@rspack/core";
|
|
2
2
|
import { Configuration, DefinePluginOptions, LightningcssLoaderOptions, Loader, ModuleFederationPluginOptions, Plugin, RuleSetRule, WatchOptions, rspack } from "@rspack/core";
|
|
3
3
|
import * as _rspack_dev_server0 from "@rspack/dev-server";
|
|
4
|
-
import * as
|
|
4
|
+
import * as https from "https";
|
|
5
5
|
|
|
6
6
|
//#region src/types/env.d.ts
|
|
7
7
|
interface ImportMetaBaseEnv {
|
|
@@ -12,96 +12,21 @@ interface ImportMetaBaseEnv {
|
|
|
12
12
|
/** 平台 */
|
|
13
13
|
PLATFORM: 'web' | 'desktopClient';
|
|
14
14
|
}
|
|
15
|
-
type ImportMetaEnv = Record<string,
|
|
15
|
+
type ImportMetaEnv = Record<string, string | boolean | undefined>;
|
|
16
16
|
interface ImportMeta {
|
|
17
17
|
readonly env: Readonly<ImportMetaEnv & ImportMetaBaseEnv>;
|
|
18
18
|
}
|
|
19
19
|
//#endregion
|
|
20
|
-
//#region src/node/
|
|
21
|
-
type PackageJson = {
|
|
22
|
-
name: string;
|
|
23
|
-
version: string;
|
|
24
|
-
};
|
|
25
|
-
/** 命令 */
|
|
26
|
-
declare enum Command {
|
|
27
|
-
SERVER = "server",
|
|
28
|
-
BUILD = "build",
|
|
29
|
-
}
|
|
30
|
-
/** 命令选项 */
|
|
31
|
-
type CompileOptions = {
|
|
32
|
-
/** 模式 */
|
|
33
|
-
readonly mode?: string;
|
|
34
|
-
/** 平台 */
|
|
35
|
-
readonly platform: ImportMetaBaseEnv['PLATFORM'];
|
|
36
|
-
};
|
|
37
|
-
type CompileServeParame = {
|
|
38
|
-
command: Command;
|
|
39
|
-
options: CompileOptions;
|
|
40
|
-
configFile?: string;
|
|
41
|
-
onBuildStatus?: (status: {
|
|
42
|
-
success: boolean;
|
|
43
|
-
port?: number;
|
|
44
|
-
message?: string;
|
|
45
|
-
}) => void;
|
|
46
|
-
};
|
|
47
|
-
declare abstract class BaseCompileService {
|
|
48
|
-
/** 构建类型 */
|
|
49
|
-
readonly command: Command;
|
|
50
|
-
/** cli上下文空间 */
|
|
51
|
-
readonly context: string;
|
|
52
|
-
/** 选项 */
|
|
53
|
-
readonly options: CompileOptions;
|
|
54
|
-
/** 基于工作目录的Require */
|
|
55
|
-
readonly contextRequire: NodeRequire;
|
|
56
|
-
private _env;
|
|
57
|
-
/** 配置文件 */
|
|
58
|
-
readonly configFile?: string;
|
|
59
|
-
/** env */
|
|
60
|
-
private set env(value);
|
|
61
|
-
get env(): ConfigEnvPre["env"];
|
|
62
|
-
private _contextPkg?;
|
|
63
|
-
/** 用户配置 */
|
|
64
|
-
userConfig?: UserConfig;
|
|
65
|
-
/** 工作目录的 package.json */
|
|
66
|
-
private set contextPkg(value);
|
|
67
|
-
get contextPkg(): PackageJson | undefined;
|
|
68
|
-
/** 是否为electron环境 */
|
|
69
|
-
get isElectron(): boolean;
|
|
70
|
-
constructor(parame: CompileServeParame);
|
|
71
|
-
static create<T extends BaseCompileService, P extends CompileServeParame>(this: new (params: P) => T, params: P): Promise<T>;
|
|
72
|
-
private initialize;
|
|
73
|
-
protected onAfterConfigLoaded(): Promise<void>;
|
|
74
|
-
/** 基于工作目录的定位 */
|
|
75
|
-
protected resolveContext: (...paths: string[]) => string;
|
|
76
|
-
private initContextPkg;
|
|
77
|
-
private initEnv;
|
|
78
|
-
private loadUserConfig;
|
|
79
|
-
/** 检索工作目录的模块路径 */
|
|
80
|
-
protected resolveContextModule(id: string): string | undefined;
|
|
81
|
-
/** 加载模块工作目录的模块 */
|
|
82
|
-
protected loadContextModule<T>(id: string): T;
|
|
83
|
-
/**
|
|
84
|
-
* 获取配置文件
|
|
85
|
-
* @param configFile 配置文件路径
|
|
86
|
-
*/
|
|
87
|
-
protected getUserConfig(): Promise<UserConfig | undefined>;
|
|
88
|
-
protected startCompile(): Promise<void>;
|
|
89
|
-
/** 生命周期抽象方法:dev 启动 */
|
|
90
|
-
protected abstract dev(): unknown | Promise<unknown>;
|
|
91
|
-
/** 生命周期抽象方法:build 启动 */
|
|
92
|
-
protected abstract build(): unknown | Promise<unknown>;
|
|
93
|
-
}
|
|
94
|
-
//#endregion
|
|
95
|
-
//#region src/node/utils/css-loaders-helper.d.ts
|
|
20
|
+
//#region src/node/bundler/rspack/css-loaders-helper.d.ts
|
|
96
21
|
interface CssLoaderOptions {
|
|
97
22
|
lightningcss?: LightningcssLoaderOptions;
|
|
98
23
|
sourceMap?: boolean;
|
|
99
|
-
less?: Record<string,
|
|
100
|
-
sass?: Record<string,
|
|
101
|
-
stylus?: Record<string,
|
|
24
|
+
less?: Record<string, unknown>;
|
|
25
|
+
sass?: Record<string, unknown>;
|
|
26
|
+
stylus?: Record<string, unknown>;
|
|
102
27
|
}
|
|
103
28
|
//#endregion
|
|
104
|
-
//#region src/node/
|
|
29
|
+
//#region src/node/bundler/rspack/loader-plugin-helper.d.ts
|
|
105
30
|
type ListItemType = RuleSetRule | Plugin;
|
|
106
31
|
type RspackExperiments = {
|
|
107
32
|
import: Record<string, unknown>[];
|
|
@@ -165,6 +90,129 @@ type Pages = {
|
|
|
165
90
|
};
|
|
166
91
|
};
|
|
167
92
|
//#endregion
|
|
93
|
+
//#region src/node/bundler/types.d.ts
|
|
94
|
+
interface BuildStatus {
|
|
95
|
+
success: boolean;
|
|
96
|
+
message?: string;
|
|
97
|
+
port?: number;
|
|
98
|
+
/** 预留多目标结构 */
|
|
99
|
+
target?: 'web' | 'renderer' | 'main' | 'preload';
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* 编译器适配器接口
|
|
103
|
+
*
|
|
104
|
+
* 泛型参数 TConfig 默认为 unknown,core 层按 BundlerAdapter(即 BundlerAdapter<unknown>)对待;
|
|
105
|
+
* adapter 实现内部可指定具体类型以获得强类型约束。
|
|
106
|
+
* 例如:class RspackAdapter implements BundlerAdapter<Configuration> { ... }
|
|
107
|
+
*/
|
|
108
|
+
interface BundlerAdapter<TConfig = unknown> {
|
|
109
|
+
/** 编译器标识 */
|
|
110
|
+
readonly name: 'rspack' | 'vite';
|
|
111
|
+
/**
|
|
112
|
+
* 根据编译参数生成编译器配置
|
|
113
|
+
*/
|
|
114
|
+
createConfig(params: CreateConfigParams): TConfig | Promise<TConfig>;
|
|
115
|
+
/**
|
|
116
|
+
* 启动开发服务器
|
|
117
|
+
*/
|
|
118
|
+
runDev(config: TConfig, options: BundlerDevOptions): Promise<void>;
|
|
119
|
+
/**
|
|
120
|
+
* 执行生产构建
|
|
121
|
+
*/
|
|
122
|
+
runBuild(config: TConfig, options: BundlerBuildOptions): Promise<string | undefined>;
|
|
123
|
+
}
|
|
124
|
+
interface CreateConfigParams {
|
|
125
|
+
command: 'server' | 'build';
|
|
126
|
+
mode?: string;
|
|
127
|
+
env: Record<string, unknown>;
|
|
128
|
+
context: string;
|
|
129
|
+
contextPkg?: {
|
|
130
|
+
name: string;
|
|
131
|
+
version: string;
|
|
132
|
+
};
|
|
133
|
+
userConfig?: UserConfig;
|
|
134
|
+
pages: Pages;
|
|
135
|
+
base: string;
|
|
136
|
+
port: number;
|
|
137
|
+
browserslist: string;
|
|
138
|
+
isElectron: boolean;
|
|
139
|
+
isVue: boolean;
|
|
140
|
+
isReact: boolean;
|
|
141
|
+
resolveContext: (...paths: string[]) => string;
|
|
142
|
+
}
|
|
143
|
+
interface BundlerDevOptions {
|
|
144
|
+
port?: number;
|
|
145
|
+
onBuildStatus?: (status: BuildStatus) => void;
|
|
146
|
+
}
|
|
147
|
+
interface BundlerBuildOptions {
|
|
148
|
+
onBuildStatus?: (status: BuildStatus) => void;
|
|
149
|
+
}
|
|
150
|
+
//#endregion
|
|
151
|
+
//#region src/node/compile/compile-context.d.ts
|
|
152
|
+
type PackageJson = {
|
|
153
|
+
name: string;
|
|
154
|
+
version: string;
|
|
155
|
+
};
|
|
156
|
+
/** 命令 */
|
|
157
|
+
declare enum Command {
|
|
158
|
+
SERVER = "server",
|
|
159
|
+
BUILD = "build"
|
|
160
|
+
}
|
|
161
|
+
/** 命令选项 */
|
|
162
|
+
type CompileOptions = {
|
|
163
|
+
/** 模式 */readonly mode?: string; /** 平台 */
|
|
164
|
+
readonly platform: ImportMetaBaseEnv['PLATFORM'];
|
|
165
|
+
};
|
|
166
|
+
type CompileServeParams = {
|
|
167
|
+
command: Command;
|
|
168
|
+
options: CompileOptions;
|
|
169
|
+
configFile?: string;
|
|
170
|
+
onBuildStatus?: (status: BuildStatus) => void;
|
|
171
|
+
};
|
|
172
|
+
/**
|
|
173
|
+
* 编译上下文
|
|
174
|
+
*
|
|
175
|
+
* 由 createCompileContext() 工厂函数创建,以组合方式提供给 Platform/Bundler 使用。
|
|
176
|
+
*/
|
|
177
|
+
interface CompileContext {
|
|
178
|
+
/** 工作目录 */
|
|
179
|
+
readonly context: string;
|
|
180
|
+
/** 命令 */
|
|
181
|
+
readonly command: Command;
|
|
182
|
+
/** CLI 选项 */
|
|
183
|
+
readonly options: CompileOptions;
|
|
184
|
+
/** 环境变量 */
|
|
185
|
+
readonly env: Record<string, unknown>;
|
|
186
|
+
/** 用户配置(可在 resolvePreConfig 阶段被更新) */
|
|
187
|
+
userConfig?: UserConfig;
|
|
188
|
+
/** 工作目录 package.json */
|
|
189
|
+
readonly contextPkg?: PackageJson;
|
|
190
|
+
/** 基于工作目录的路径解析 */
|
|
191
|
+
readonly resolveContext: (...paths: string[]) => string;
|
|
192
|
+
/** 加载工作目录模块 */
|
|
193
|
+
readonly loadContextModule: <T>(id: string) => T;
|
|
194
|
+
/** 检索工作目录模块路径 */
|
|
195
|
+
readonly resolveContextModule: (id: string) => string | undefined;
|
|
196
|
+
/** 基于工作目录的 require(供需要完整 NodeRequire 的场景使用) */
|
|
197
|
+
readonly contextRequire: NodeRequire;
|
|
198
|
+
/** 是否 Electron */
|
|
199
|
+
readonly isElectron: boolean;
|
|
200
|
+
/** 配置文件路径 */
|
|
201
|
+
readonly configFile?: string;
|
|
202
|
+
/** 构建状态回调 */
|
|
203
|
+
onBuildStatus?: (status: BuildStatus) => void;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* 创建编译上下文
|
|
207
|
+
*
|
|
208
|
+
* 替代 BaseCompileService 的构造函数 + initialize() 流程:
|
|
209
|
+
* 1. 设置工作目录和选项
|
|
210
|
+
* 2. 加载 package.json
|
|
211
|
+
* 3. 加载环境变量
|
|
212
|
+
* 4. 加载并验证用户配置
|
|
213
|
+
*/
|
|
214
|
+
declare function createCompileContext(params: CompileServeParams): Promise<CompileContext>;
|
|
215
|
+
//#endregion
|
|
168
216
|
//#region src/node/plugins/cdn-plugin.d.ts
|
|
169
217
|
interface CdnModule {
|
|
170
218
|
name: string;
|
|
@@ -185,7 +233,7 @@ interface CdnPluginOptions {
|
|
|
185
233
|
crossOrigin?: boolean | string;
|
|
186
234
|
}
|
|
187
235
|
//#endregion
|
|
188
|
-
//#region src/node/user-config.d.ts
|
|
236
|
+
//#region src/node/config/user-config.d.ts
|
|
189
237
|
type Bundler = 'rspack' | 'vite';
|
|
190
238
|
interface ElectronConfig {
|
|
191
239
|
main?: {
|
|
@@ -315,7 +363,7 @@ interface UserConfig {
|
|
|
315
363
|
* @see {@link https://webpack.js.org/configuration/dev-server/#devserverhttps}
|
|
316
364
|
* @default false
|
|
317
365
|
*/
|
|
318
|
-
https?: boolean |
|
|
366
|
+
https?: boolean | https.ServerOptions;
|
|
319
367
|
};
|
|
320
368
|
/**
|
|
321
369
|
* css loader 配置
|
|
@@ -402,16 +450,95 @@ type UserConfigWebExport = UserConfig | Promise<UserConfig> | UserConfigFn<UserC
|
|
|
402
450
|
/** 辅助工具函数 */
|
|
403
451
|
declare const defineConfig: (config: UserConfigWebExport) => UserConfigWebExport;
|
|
404
452
|
//#endregion
|
|
405
|
-
//#region src/node/compile/
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
453
|
+
//#region src/node/compile/compile-pipeline.d.ts
|
|
454
|
+
/**
|
|
455
|
+
* 统一编译管线
|
|
456
|
+
*
|
|
457
|
+
* 线性流程:
|
|
458
|
+
* 1. createCompileContext — 加载 pkg、env、config
|
|
459
|
+
* 2. createPlatformAdapter — 根据 platform 创建平台适配器
|
|
460
|
+
* 3. resolvePreConfig — 解析平台预配置(port、pages 等)
|
|
461
|
+
* 4. createBundlerAdapter — 根据 bundler 创建编译器适配器
|
|
462
|
+
* 5. platform.compile — 通过平台适配器执行编译
|
|
463
|
+
*/
|
|
464
|
+
declare function runCompile(params: CompileServeParams): Promise<void>;
|
|
465
|
+
//#endregion
|
|
466
|
+
//#region src/node/platform/types.d.ts
|
|
467
|
+
/**
|
|
468
|
+
* 平台预配置
|
|
469
|
+
*
|
|
470
|
+
* 由 PlatformAdapter.resolvePreConfig() 返回,包含平台相关的配置解析结果。
|
|
471
|
+
* 与 WebPreConfig 形状一致,作为 platform 层的规范类型。
|
|
472
|
+
*/
|
|
473
|
+
interface PlatformPreConfig {
|
|
474
|
+
userConfig?: UserConfig;
|
|
475
|
+
base: string;
|
|
476
|
+
target: 'pc' | 'mobile';
|
|
477
|
+
pages: Pages;
|
|
478
|
+
port: number;
|
|
479
|
+
browserslist: string;
|
|
480
|
+
isVue: boolean;
|
|
481
|
+
isReact: boolean;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* 平台适配器接口
|
|
485
|
+
*
|
|
486
|
+
* 抽象出 Web / Desktop 两种平台的编译职责:
|
|
487
|
+
* - resolvePreConfig: 解析平台相关的预配置(port、browserslist、pages 等)
|
|
488
|
+
* - compile: 执行编译(Web 直接调用 bundler;Desktop 需要编排 main/preload/renderer)
|
|
489
|
+
*/
|
|
490
|
+
interface PlatformAdapter {
|
|
491
|
+
/** 平台标识 */
|
|
492
|
+
readonly name: 'web' | 'desktopClient';
|
|
493
|
+
/**
|
|
494
|
+
* 解析平台相关的预配置
|
|
495
|
+
*
|
|
496
|
+
* - Web 平台:确定 port、browserslist、pages、检测 Vue/React 等
|
|
497
|
+
* - Desktop 平台:同上(用于 renderer),内部另行处理 main/preload
|
|
498
|
+
*/
|
|
499
|
+
resolvePreConfig(ctx: CompileContext): Promise<PlatformPreConfig>;
|
|
500
|
+
/**
|
|
501
|
+
* 执行编译
|
|
502
|
+
*
|
|
503
|
+
* - Web 平台:直接调用 bundler.createConfig + runDev/runBuild
|
|
504
|
+
* - Desktop 平台:包装 main/preload/renderer 三目标编排
|
|
505
|
+
*
|
|
506
|
+
* @param bundler 编译器适配器(由 pipeline 根据 userConfig.bundler 创建)
|
|
507
|
+
* @param params 编译参数
|
|
508
|
+
*/
|
|
509
|
+
compile(bundler: BundlerAdapter, params: PlatformCompileParams): Promise<void>;
|
|
510
|
+
}
|
|
511
|
+
interface PlatformCompileParams {
|
|
512
|
+
/** 当前命令 */
|
|
513
|
+
command: 'server' | 'build';
|
|
514
|
+
/** 平台预配置(由 resolvePreConfig 返回) */
|
|
515
|
+
preConfig: PlatformPreConfig;
|
|
516
|
+
/** 编译上下文 */
|
|
517
|
+
compileContext: CompileContext;
|
|
518
|
+
}
|
|
519
|
+
//#endregion
|
|
520
|
+
//#region src/node/platform/platform-factory.d.ts
|
|
521
|
+
/**
|
|
522
|
+
* 根据平台类型创建平台适配器实例
|
|
523
|
+
*
|
|
524
|
+
* 这是 platform 分支逻辑唯一存在的地方。
|
|
525
|
+
* - 'web': 直接实例化内部的 WebPlatformAdapter
|
|
526
|
+
* - 'desktopClient': 懒加载 @ikaros-cli/ikaros-platform-desktop-client 包
|
|
527
|
+
*/
|
|
528
|
+
declare function createPlatformAdapter(platform: string): PlatformAdapter;
|
|
529
|
+
//#endregion
|
|
530
|
+
//#region src/node/platform/web/web-platform.d.ts
|
|
531
|
+
/**
|
|
532
|
+
* Web 平台适配器
|
|
533
|
+
*
|
|
534
|
+
* 实现 PlatformAdapter 接口,替代原来的 WebCompileService。
|
|
535
|
+
* - resolvePreConfig: 委托给 resolveWebPreConfig 解析 port/pages/browserslist 等
|
|
536
|
+
* - compile: 通过 BundlerAdapter 创建配置并执行 dev/build
|
|
537
|
+
*/
|
|
538
|
+
declare class WebPlatformAdapter implements PlatformAdapter {
|
|
539
|
+
readonly name: "web";
|
|
540
|
+
resolvePreConfig(ctx: CompileContext): Promise<PlatformPreConfig>;
|
|
541
|
+
compile(bundler: BundlerAdapter, params: PlatformCompileParams): Promise<void>;
|
|
415
542
|
}
|
|
416
543
|
//#endregion
|
|
417
544
|
//#region src/node/compile/web/resolve-web-preconfig.d.ts
|
|
@@ -425,64 +552,16 @@ type WebPreConfig = {
|
|
|
425
552
|
isVue: boolean;
|
|
426
553
|
isReact: boolean;
|
|
427
554
|
};
|
|
428
|
-
|
|
429
|
-
//#region src/node/utils/optional-vite.d.ts
|
|
430
|
-
type OptionalViteAdapter = {
|
|
431
|
-
createWebViteConfig: (params: {
|
|
432
|
-
command: 'server' | 'build';
|
|
433
|
-
mode?: string;
|
|
434
|
-
env: Record<string, unknown>;
|
|
435
|
-
context: string;
|
|
436
|
-
userConfig?: Record<string, unknown>;
|
|
437
|
-
pages: Record<string, {
|
|
438
|
-
html: string;
|
|
439
|
-
entry: string;
|
|
440
|
-
}>;
|
|
441
|
-
base: string;
|
|
442
|
-
port: number;
|
|
443
|
-
isElectron: boolean;
|
|
444
|
-
resolveContext: (...paths: string[]) => string;
|
|
445
|
-
}) => unknown;
|
|
446
|
-
runViteBuild: (config: unknown, options?: {
|
|
447
|
-
onBuildStatus?: (status: {
|
|
448
|
-
success: boolean;
|
|
449
|
-
port?: number;
|
|
450
|
-
message?: string;
|
|
451
|
-
}) => void;
|
|
452
|
-
}) => Promise<string | undefined>;
|
|
453
|
-
startViteDevServer: (config: unknown, options?: {
|
|
454
|
-
port?: number;
|
|
455
|
-
onBuildStatus?: (status: {
|
|
456
|
-
success: boolean;
|
|
457
|
-
port?: number;
|
|
458
|
-
message?: string;
|
|
459
|
-
}) => void;
|
|
460
|
-
}) => Promise<unknown>;
|
|
461
|
-
};
|
|
462
|
-
declare const loadOptionalViteAdapter: (params: {
|
|
463
|
-
loadContextModule: <T>(id: string) => T;
|
|
464
|
-
}) => OptionalViteAdapter;
|
|
465
|
-
//#endregion
|
|
466
|
-
//#region src/node/compile/web/prepare-web-compile.d.ts
|
|
467
|
-
type PrepareWebCompileParams = {
|
|
555
|
+
type ResolveWebPreConfigParams = {
|
|
468
556
|
command: Command;
|
|
469
|
-
|
|
470
|
-
env: DefinePluginOptions;
|
|
471
|
-
context: string;
|
|
472
|
-
contextPkg?: PackageJson;
|
|
473
|
-
userConfig?: UserConfig;
|
|
474
|
-
isElectron: boolean;
|
|
557
|
+
context?: string;
|
|
475
558
|
resolveContext: (...paths: string[]) => string;
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
type PrepareWebCompileResult = {
|
|
479
|
-
bundler: NonNullable<UserConfig['bundler']>;
|
|
480
|
-
config: Configuration | unknown;
|
|
481
|
-
pre: WebPreConfig;
|
|
559
|
+
getUserConfig: () => Promise<UserConfig | undefined>;
|
|
560
|
+
isElectron?: boolean;
|
|
482
561
|
};
|
|
483
|
-
declare const
|
|
562
|
+
declare const resolveWebPreConfig: (params: ResolveWebPreConfigParams) => Promise<WebPreConfig>;
|
|
484
563
|
//#endregion
|
|
485
|
-
//#region src/node/
|
|
564
|
+
//#region src/node/shared/logger.d.ts
|
|
486
565
|
declare const LoggerSystem: () => {
|
|
487
566
|
done: ({
|
|
488
567
|
text,
|
|
@@ -524,19 +603,19 @@ declare const LoggerSystem: () => {
|
|
|
524
603
|
eventArray: string[];
|
|
525
604
|
};
|
|
526
605
|
//#endregion
|
|
527
|
-
//#region src/node/
|
|
528
|
-
type BuildStatus = {
|
|
606
|
+
//#region src/node/bundler/rspack/rspack-runner.d.ts
|
|
607
|
+
type BuildStatus$1 = {
|
|
529
608
|
success: boolean;
|
|
530
609
|
port?: number;
|
|
531
610
|
message?: string;
|
|
532
611
|
};
|
|
533
612
|
type WatchRspackBuildOptions = WatchOptions & {
|
|
534
|
-
onBuildStatus?: (status: BuildStatus) => void;
|
|
613
|
+
onBuildStatus?: (status: BuildStatus$1) => void;
|
|
535
614
|
};
|
|
536
615
|
declare const runRspackBuild: (config: Configuration | Configuration[], options?: WatchRspackBuildOptions) => Promise<string | undefined>;
|
|
537
616
|
declare const watchRspackBuild: (config: Configuration | Configuration[], options?: WatchRspackBuildOptions) => Promise<string | undefined>;
|
|
538
617
|
//#endregion
|
|
539
|
-
//#region src/node/
|
|
618
|
+
//#region src/node/shared/constants.d.ts
|
|
540
619
|
declare const extensions: string[];
|
|
541
620
|
/**
|
|
542
621
|
* 基于cli的绝对定位
|
|
@@ -544,4 +623,54 @@ declare const extensions: string[];
|
|
|
544
623
|
*/
|
|
545
624
|
declare const resolveCLI: (...paths: string[]) => string;
|
|
546
625
|
//#endregion
|
|
547
|
-
|
|
626
|
+
//#region src/node/bundler/bundler-factory.d.ts
|
|
627
|
+
interface CreateBundlerAdapterParams {
|
|
628
|
+
/** 编译器类型 */
|
|
629
|
+
bundler: 'rspack' | 'vite';
|
|
630
|
+
/** 基于工作目录加载模块的能力(ViteAdapterLoader 需要) */
|
|
631
|
+
loadContextModule: <T>(id: string) => T;
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* 根据 bundler 类型创建编译器适配器实例
|
|
635
|
+
*
|
|
636
|
+
* 这是 bundler 分支逻辑唯一存在的地方。
|
|
637
|
+
* 新增 bundler 只需在此处增加 case + 实现 BundlerAdapter 接口。
|
|
638
|
+
*/
|
|
639
|
+
declare function createBundlerAdapter(params: CreateBundlerAdapterParams): BundlerAdapter;
|
|
640
|
+
//#endregion
|
|
641
|
+
//#region src/node/bundler/rspack/rspack-adapter.d.ts
|
|
642
|
+
/**
|
|
643
|
+
* Rspack 编译器适配器
|
|
644
|
+
*
|
|
645
|
+
* 实现 BundlerAdapter<Configuration>,将现有 rspack 相关逻辑封装为统一接口
|
|
646
|
+
*/
|
|
647
|
+
declare class RspackAdapter implements BundlerAdapter<Configuration> {
|
|
648
|
+
readonly name: "rspack";
|
|
649
|
+
createConfig(params: CreateConfigParams): Configuration;
|
|
650
|
+
runDev(config: Configuration, options: BundlerDevOptions): Promise<void>;
|
|
651
|
+
runBuild(config: Configuration, options: BundlerBuildOptions): Promise<string | undefined>;
|
|
652
|
+
}
|
|
653
|
+
//#endregion
|
|
654
|
+
//#region src/node/bundler/vite/vite-adapter-loader.d.ts
|
|
655
|
+
/**
|
|
656
|
+
* Vite 编译器适配器(懒加载代理)
|
|
657
|
+
*
|
|
658
|
+
* 通过 loadContextModule 动态加载 @ikaros-cli/ikaros-bundler-vite,
|
|
659
|
+
* 实例化其导出的 ViteBundlerAdapter,直接代理 BundlerAdapter 接口。
|
|
660
|
+
*
|
|
661
|
+
* adapter 实例由 BundlerFactory 创建并统一持有,无需外部手动缓存。
|
|
662
|
+
*/
|
|
663
|
+
declare class ViteAdapterLoader implements BundlerAdapter<unknown> {
|
|
664
|
+
readonly name: "vite";
|
|
665
|
+
private adapter;
|
|
666
|
+
private readonly loadContextModule;
|
|
667
|
+
constructor(params: {
|
|
668
|
+
loadContextModule: <T>(id: string) => T;
|
|
669
|
+
});
|
|
670
|
+
private ensureAdapter;
|
|
671
|
+
createConfig(params: CreateConfigParams): unknown | Promise<unknown>;
|
|
672
|
+
runDev(config: unknown, options: BundlerDevOptions): Promise<void>;
|
|
673
|
+
runBuild(config: unknown, options: BundlerBuildOptions): Promise<string | undefined>;
|
|
674
|
+
}
|
|
675
|
+
//#endregion
|
|
676
|
+
export { type BuildStatus, Bundler, type BundlerAdapter, type BundlerBuildOptions, type BundlerDevOptions, Command, type CompileContext, type CompileOptions, type CompileServeParams, ConfigEnvPre, type CreateBundlerAdapterParams, type CreateConfigParams, CreateLoader, CreatePlugins, ElectronConfig, LoggerSystem, ModuleFederationOptions, type PackageJson, type PlatformAdapter, type PlatformCompileParams, type PlatformPreConfig, type ResolveWebPreConfigParams, RspackAdapter, UserConfig, UserConfigFn, UserConfigWebExport, ViteAdapterLoader, WebPlatformAdapter, type WebPreConfig, createBundlerAdapter, createCompileContext, createPlatformAdapter, defineConfig, extensions, resolveCLI, resolveWebPreConfig, runCompile, runRspackBuild, watchRspackBuild };
|
package/dist/index.mjs
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";import{Option as t,program as n}from"commander";import r
|
|
2
|
-
`;return e.toString({chunks:!1,colors:!0}).split(/\r?\n/).forEach(e=>{t+=` ${e}\n`}),t},z=(e,t)=>{let{onBuildStatus:n}=t??{};return new Promise((t,r)=>{let i=T(e);i.run((e,a)=>{i.close(i=>{let o=e||i;if(o)return n?.({success:!1,message:o.message||`build error`}),r(o);if(a?.hasErrors()){let e=R(a);return n?.({success:!1,message:e}),r(Error(e))}let s=a?.toString({chunks:!1,colors:!0});return n?.({success:!0,message:s}),t(s)})})})},xe=async(e,t)=>{let{port:n,onBuildStatus:r}=t??{},i=T(e),a=new ne(e.devServer,i);await new Promise((e,t)=>{a.startCallback(i=>i?(r?.({success:!1,port:n,message:i.message}),t(i)):(r?.({success:!0,port:n}),e()))})},Se=(e,t)=>{let{onBuildStatus:n,...r}=t??{};return new Promise((t,i)=>{T(e).watch({ignored:/node_modules/,aggregateTimeout:300,poll:!1,...r},(e,r)=>{if(e)return n?.({success:!1,message:e.message||`watch build error`}),i(e);if(r?.hasErrors()){let e=R(r);return n?.({success:!1,message:e}),i(Error(e))}let a=r?.toString({chunks:!1,colors:!0});return n?.({success:!0,message:a}),t(a)})})},B=x(process.cwd(),`./`),V=[`...`,`.mjs`,`.jsx`,`.ts`,`.tsx`];x(B,`tsconfig.json`);const H=c.fileURLToPath(new c.URL(`../`,import.meta.url)),Ce=e(H),U=(...e)=>x(H,...e),W=(e,t)=>({loader:e.includes(`builtin`)?e:Ce.resolve(e),options:t}),we=(e,t)=>{let{lightningcss:n,sourceMap:r}=t??{},i=W(`builtin:lightningcss-loader`,{...n}),a=(e,n)=>{let a=[i],o=t&&t[`${e}`];return e&&e!==`css`&&a.push(W(`${e}-loader`,Object.assign(o??{},n,{sourceMap:r}))),a};return{less:a(`less`),sass:a(`sass`,{sassOptions:{indentedSyntax:!0,api:`modern-compiler`}}),scss:a(`sass`,{sassOptions:{api:`modern-compiler`}}),stylus:a(`stylus`),styl:a(`stylus`),css:a(`css`)}},Te=(e,t)=>{let n=we(e,t);return Object.entries(n).map(([e,t])=>({test:RegExp(`\\.${e}$`),use:t,type:`css/auto`}))};var G=class{constructor({env:e=`development`,mode:t=``}){this.list=[],this.env=`development`,this.mode=``,this.isDev=!0,this.env=e,this.mode=t,this.isDev=e===`development`}add(e){return e&&(h(e)?this.list=this.list.concat(e):this.list.push(e)),this}end(){return this.list}},K=class extends G{constructor({env:e=`development`,mode:t=``}){super({env:e,mode:t}),this.defaultScriptLoader=e=>[{test:/\.m?ts$/i,loader:`builtin:swc-loader`,options:{jsc:{parser:{syntax:`typescript`}}},type:`javascript/auto`,exclude:[x(B,`node_modules`)]},{test:/\.m?js$/i,loader:`builtin:swc-loader`,options:{isModule:`unknown`,rspackExperiments:e},type:`javascript/auto`,exclude:[x(B,`node_modules`)]}],this.defaultResourceLoader=[{test:/\.(png|jpe?g|gif|svg|ico)(\?.*)?$/,type:`asset/resource`,generator:{filename:this.isDev?`[id][ext]`:`assets/img/[contenthash][ext]`}},{test:/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,type:`asset/resource`,generator:{filename:this.isDev?`[id][ext]`:`assets/media/[contenthash][ext]`}},{test:/\.(woff2?|eot|ttf|otf)(\?.*)?$/,type:`asset/resource`,generator:{filename:this.isDev?`[id][ext]`:`assets/fonts/[contenthash][ext]`}}]}useDefaultCssLoader(e){return Te(this.env,e).forEach(e=>this.add(e)),this}useDefaultScriptLoader(e){return this.add(this.defaultScriptLoader(e)),this}useDefaultResourceLoader(){return this.defaultResourceLoader.forEach(e=>this.add(e)),this}},q=class extends G{constructor({env:e=`development`,mode:t=``}){super({env:e,mode:t})}useDefaultEnvPlugin(e){let{frameworkEnv:t={},extEnv:n={},env:r={}}=e??{};return this.add(De({frameworkEnv:t,extEnv:n,env:r})),this}useCopyPlugin(){return this.env===`production`&&this.add(new T.CopyRspackPlugin({patterns:[{context:x(B,`public`),from:`./`,noErrorOnMissing:!0,globOptions:{ignore:[`**/index.html`,`.*`]}}]})),this}useHtmlPlugin(e){return this.add(new T.HtmlRspackPlugin({template:e??x(B,`index.html`)})),this}},Ee=class{constructor({pages:e,enablePages:t}){this.pages=e,this.enablePages=t,this.getEnablePages()}create(){let e={},t=[];return Object.keys(this.pages).forEach(n=>{e[n]={import:this.pages[n].entry,library:this.pages[n].library},t.push(new T.HtmlRspackPlugin({template:this.pages[n].html,filename:`${n}.html`,chunks:[n],scriptLoading:`blocking`,...this.pages[n].options}))}),{entry:e,plugins:t}}getEnablePages(){let{warning:e,emitEvent:t}=M();if(!g(this.pages)&&h(this.enablePages)){let n={},r=[];if(this.enablePages.forEach(e=>{this.pages[e]?n[e]=this.pages[e]:r.push(e)}),g(r)&&t(e({text:`当前设置页面${r.join()}不存在`,onlyText:!0})),g(n))return;this.pages=n}}};const De=({frameworkEnv:e={},extEnv:t={},env:n={}})=>{let r=Object.assign({},O(t,n)),i=Object.fromEntries(Object.entries(r).map(([e,t])=>[`import.meta.env.${e}`,JSON.stringify(t)])),a=Object.fromEntries(Object.entries({...i,...e}).map(([e,t])=>[e,t]));return new T.DefinePlugin(a)},J={name:de,version:D},Y=`@rspack/ikaros-stats-plugin`,X=w.hex(`#222222`);var Oe=class{constructor(e){this.startCompileHrtime=void 0,this.userConfig=e}apply(e){this.compiler=e,this.isDev=e.options.mode===`development`,new T.ProgressPlugin().apply(e),ae.hide(),this.isDev?this.initDevHook():this.initProdHook()}updateStartCompileTime(){this.startCompileHrtime=oe.hrtime()}getCurrentEndCompileTime(){let e=oe.hrtime(this.startCompileHrtime);return(e[0]*1e9+e[1])/1e6}getError(e){let{errors:t,errorsCount:n=0}=e;if(!(!t||n===0))return t.map(e=>`${X.bgRed(` ERROR `)} ${e.message.trim()}`).join(`
|
|
1
|
+
import{createRequire as e}from"node:module";import{Option as t,program as n}from"commander";import{rspack as r}from"@rspack/core";import{isFunction as i,isString as a}from"es-toolkit";import o,{dirname as s,extname as c,join as l,resolve as u}from"node:path";import d,{join as f}from"path";import p,{pathToFileURL as m}from"node:url";import{isArray as h,isEmpty as g,isObject as _}from"es-toolkit/compat";import v from"chalk";import y from"fs/promises";import b from"node:os";import x from"pretty-bytes";import S from"easy-table";import C from"cli-cursor";import w from"node:process";import{RsdoctorRspackPlugin as T}from"@rsdoctor/rspack-plugin";import ee from"compression-webpack-plugin";import{ModuleFederationPlugin as E}from"@module-federation/enhanced/rspack";import te from"node:fs";import D,{readFile as ne}from"node:fs/promises";import{z as O}from"zod/v4";import k from"fs-extra";import{config as A}from"dotenv";import{parse as re}from"yaml";import{transform as ie}from"oxc-transform";import{RspackDevServer as ae}from"@rspack/dev-server";import{detect as oe}from"detect-port";var se=`@ikaros-cli/ikaros`,ce=`2.2.0`;const j=f(process.cwd(),`./`),M=[`...`,`.mjs`,`.jsx`,`.ts`,`.tsx`];f(j,`tsconfig.json`);const N=p.fileURLToPath(new p.URL(`../`,import.meta.url)),le=e(N),P=(...e)=>f(N,...e),F=(e,t)=>({loader:e.includes(`builtin`)?e:le.resolve(e),options:t}),ue=(e,t)=>{let{lightningcss:n,sourceMap:r}=t??{},i=F(`builtin:lightningcss-loader`,{...n}),a=(e,n)=>{let a=[i],o=t&&t[`${e}`];return e&&e!==`css`&&a.push(F(`${e}-loader`,Object.assign(o??{},n,{sourceMap:r}))),a};return{less:a(`less`),sass:a(`sass`,{sassOptions:{indentedSyntax:!0,api:`modern-compiler`}}),scss:a(`sass`,{sassOptions:{api:`modern-compiler`}}),stylus:a(`stylus`),styl:a(`stylus`),css:a(`css`)}},de=(e,t)=>{let n=ue(e,t);return Object.entries(n).map(([e,t])=>({test:RegExp(`\\.${e}$`),use:t,type:`css/auto`}))},I=[],L=()=>{let e=(e,t)=>({DONE:v.bgGreen.white,ERROR:v.bgRed.white,OKAY:v.bgBlue.white,WARNING:v.bgYellow.white,INFO:v.bgCyan.white})[e](` ${e} `)+` ${t}`;return{done:({text:t,onlyText:n})=>{if(n)return e(`DONE`,t);console.log(e(`DONE`,t))},error:({text:t,onlyText:n})=>{if(n)return e(`ERROR`,t);console.error(e(`ERROR`,t))},okay:({text:t,onlyText:n})=>{if(n)return e(`OKAY`,t);console.log(e(`OKAY`,t))},warning:({text:t,onlyText:n})=>{if(n)return e(`WARNING`,t);console.warn(e(`WARNING`,t))},info:({text:t,onlyText:n})=>{if(n)return e(`INFO`,t);console.info(e(`INFO`,t))},emitEvent:e=>{let t=new Date().toLocaleTimeString(`en-US`,{hour12:!1}).split(` `)[0];I.push(`[${t}] ${e}`)},clearEventArray:()=>{I.length=0},eventArray:I}},R=(e,t)=>{let n=e,r=t;for(let e of Object.keys(r)){let t=r[e],i=n[e];_(t)&&_(i)?n[e]=R(i,t):n[e]=t}return e};async function z(e,t=process.cwd()){try{let n=f(t,`node_modules`,e);return await y.access(n,y.constants.F_OK),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}var B=class{constructor({env:e=`development`,mode:t=``}){this.list=[],this.env=`development`,this.mode=``,this.isDev=!0,this.env=e,this.mode=t,this.isDev=e===`development`}add(e){return e&&(h(e)?this.list=this.list.concat(e):this.list.push(e)),this}end(){return this.list}},V=class extends B{constructor({env:e=`development`,mode:t=``}){super({env:e,mode:t}),this.defaultScriptLoader=e=>[{test:/\.m?ts$/i,loader:`builtin:swc-loader`,options:{jsc:{parser:{syntax:`typescript`}}},type:`javascript/auto`,exclude:[f(j,`node_modules`)]},{test:/\.m?js$/i,loader:`builtin:swc-loader`,options:{isModule:`unknown`,rspackExperiments:e},type:`javascript/auto`,exclude:[f(j,`node_modules`)]}],this.defaultResourceLoader=[{test:/\.(png|jpe?g|gif|svg|ico)(\?.*)?$/,type:`asset/resource`,generator:{filename:this.isDev?`[id][ext]`:`assets/img/[contenthash][ext]`}},{test:/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,type:`asset/resource`,generator:{filename:this.isDev?`[id][ext]`:`assets/media/[contenthash][ext]`}},{test:/\.(woff2?|eot|ttf|otf)(\?.*)?$/,type:`asset/resource`,generator:{filename:this.isDev?`[id][ext]`:`assets/fonts/[contenthash][ext]`}}]}useDefaultCssLoader(e){return de(this.env,e).forEach(e=>this.add(e)),this}useDefaultScriptLoader(e){return this.add(this.defaultScriptLoader(e)),this}useDefaultResourceLoader(){return this.defaultResourceLoader.forEach(e=>this.add(e)),this}},H=class extends B{constructor({env:e=`development`,mode:t=``}){super({env:e,mode:t})}useDefaultEnvPlugin(e){let{frameworkEnv:t={},extEnv:n={},env:r={}}=e??{};return this.add(pe({frameworkEnv:t,extEnv:n,env:r})),this}useCopyPlugin(){return this.env===`production`&&this.add(new r.CopyRspackPlugin({patterns:[{context:f(j,`public`),from:`./`,noErrorOnMissing:!0,globOptions:{ignore:[`**/index.html`,`.*`]}}]})),this}useHtmlPlugin(e){return this.add(new r.HtmlRspackPlugin({template:e??f(j,`index.html`)})),this}},fe=class{constructor({pages:e,enablePages:t}){this.pages=e,this.enablePages=t,this.getEnablePages()}create(){let e={},t=[];return Object.keys(this.pages).forEach(n=>{e[n]={import:this.pages[n].entry,library:this.pages[n].library},t.push(new r.HtmlRspackPlugin({template:this.pages[n].html,filename:`${n}.html`,chunks:[n],scriptLoading:`blocking`,...this.pages[n].options}))}),{entry:e,plugins:t}}getEnablePages(){let{warning:e,emitEvent:t}=L();if(!g(this.pages)&&h(this.enablePages)){let n={},r=[];if(this.enablePages.forEach(e=>{this.pages[e]?n[e]=this.pages[e]:r.push(e)}),g(r)&&t(e({text:`当前设置页面${r.join()}不存在`,onlyText:!0})),g(n))return;this.pages=n}}};const pe=({frameworkEnv:e={},extEnv:t={},env:n={}})=>{let i=Object.assign({},R(t,n)),a=Object.fromEntries(Object.entries(i).map(([e,t])=>[`import.meta.env.${e}`,JSON.stringify(t)])),o=Object.fromEntries(Object.entries({...a,...e}).map(([e,t])=>[e,t]));return new r.DefinePlugin(o)},U={name:se,version:ce},W=`@rspack/ikaros-stats-plugin`,G=v.hex(`#222222`);var me=class{constructor(e){this.startCompileHrtime=void 0,this.userConfig=e}apply(e){this.compiler=e,this.isDev=e.options.mode===`development`,new r.ProgressPlugin().apply(e),C.hide(),this.isDev?this.initDevHook():this.initProdHook()}updateStartCompileTime(){this.startCompileHrtime=w.hrtime()}getCurrentEndCompileTime(){let e=w.hrtime(this.startCompileHrtime);return(e[0]*1e9+e[1])/1e6}getError(e){let{errors:t,errorsCount:n=0}=e;if(!(!t||n===0))return t.map(e=>`${G.bgRed(` ERROR `)} ${e.message.trim()}`).join(`
|
|
3
2
|
|
|
4
|
-
`)}getWarn(e){let{warnings:t,warningsCount:n=0}=e;if(!(!t||n===0))return t.map(e=>`${
|
|
3
|
+
`)}getWarn(e){let{warnings:t,warningsCount:n=0}=e;if(!(!t||n===0))return t.map(e=>`${G.bgYellow(` WARN `)} ${e.message.trim()}`).join(`
|
|
5
4
|
|
|
6
|
-
`)}getEndTips(e,t){let{gray:n,cyan:r,red:i,green:a,yellow:o}=
|
|
7
|
-
`)),console.log());let{name:e,version:s}=J,l=`${r(`${e} v${s}`)} entry address:\n\n`;for(let e of t)l+=n(` ${e}\n`);console.log(i(l))}console.log(this.getEndTips(a,this.getCurrentEndCompileTime())),console.log()}})}initProdHook(){let{compiler:e}=this,t;e.hooks.environment.intercept({name:Y,call:()=>{console.log(w.gray(`start build...`)),this.updateStartCompileTime()}}),e.hooks.done.intercept({name:Y,call:e=>{t=e.toJson({preset:`normal`,colors:!0,assetsSort:`size`})}}),e.cache.hooks.shutdown.intercept({name:Y,done:()=>{let{errorsCount:e=0,warningsCount:n=0}=t;console.log(),e>0?(console.log(this.getError(t)),console.log()):(n>0&&(console.log(this.getWarn(t)),console.log()),console.log(this.getTableInfo(t)),console.log()),console.log(this.getEndTips(t,this.getCurrentEndCompileTime()))}})}};const Z=`@rspack/ikaros-cdn-plugin`,ke=/:([a-z]+)/gi;var Ae=class{constructor(e){this.isDev=!1,this.options={prodUrl:`https://unpkg.com/:name@:version/:path`,devUrl:`:name/:path`,crossOrigin:!1,...e}}apply(e){this.compiler=e,this.isDev=e.options.mode===`development`,this.handleExternals(),e.hooks.compilation.tap(Z,e=>{T.HtmlRspackPlugin.getCompilationHooks(e).alterAssetTags.tapAsync(Z,(e,t)=>{try{this.injectResources(e),t(null,e)}catch(e){t(e)}})})}handleExternals(){let e=this.compiler.options.externals||{};this.options.modules.filter(e=>!e.cssOnly).forEach(t=>{e[t.name]=t.var||t.name}),this.compiler.options.externals=e}injectResources(e){let t=this.options.modules,n=[];t.forEach(e=>{this.getStyles(e).forEach(e=>{n.push({tagName:`link`,voidTag:!0,attributes:{rel:`stylesheet`,href:e,...this.options.crossOrigin&&{crossorigin:this.options.crossOrigin}}})})}),t.filter(e=>!e.cssOnly).forEach(e=>{this.getScripts(e).forEach(e=>{n.push({tagName:`script`,voidTag:!0,attributes:{src:e,...this.options.crossOrigin&&{crossorigin:this.options.crossOrigin}}})})}),e.assetTags&&(e.assetTags.styles.unshift(...n.filter(e=>e.tagName===`link`)),e.assetTags.scripts.unshift(...n.filter(e=>e.tagName===`script`)))}getStyles(e){let t=[...e.styles||[]];return e.style&&t.unshift(e.style),t.map(t=>this.generateUrl(e,t))}getScripts(e){let t=[...e.paths||[]];return e.path&&t.unshift(e.path),t.map(t=>this.generateUrl(e,t))}joinUrl(e,t){return e=e.replace(/\/+$/,``),t=t.replace(/^\/+/,``),`${e}/${t}`}generateUrl(e,t){let n=this.isDev?e.devUrl||this.options.devUrl:e.prodUrl||this.options.prodUrl;return n.match(ke)?n.replace(ke,(n,r)=>{switch(r){case`name`:return e.name;case`version`:return e.version||this.getModuleVersion(e.name);case`path`:return t;default:return n}}):this.joinUrl(n,t)}getModuleVersion(t){try{return e(b.join(process.cwd(),`node_modules`))(b.join(t,`package.json`)).version}catch{return console.warn(w.yellow(`[${Z}] 无法获取模块 "${t}" 的版本信息`)),`latest`}}},je=class{constructor(e){this.options=e}createSourceMapPlugin(){let{isDev:e,userConfig:t}=this.options;if(e)return new T.EvalSourceMapDevToolPlugin({columns:!1,module:!0});if(t?.build?.sourceMap??!1)return new T.SourceMapDevToolPlugin({test:[/.js/,/.mjs/],filename:`[file].map[query]`})}createCssExtractPlugin(){if(!this.options.isDev)return new T.CssExtractRspackPlugin({filename:this.joinAssetsDir(`assets/css/[contenthash].css`),ignoreOrder:!0})}createDoctorPlugin(){let{isDev:e,userConfig:t}=this.options;if(!(e||!t?.build?.outReport))return new se}createGzipPlugin(){let{isDev:e,userConfig:t}=this.options;if(!(e||!t?.build?.gzip))return new ce}createCdnPlugin(){let{cdnOptions:e}=this.options.userConfig??{};if(!(!e||g(e.modules)))return new Ae(e)}createModuleFederationPlugin(){let e=this.options.userConfig?.moduleFederation;if(e)return h(e)?e.map(e=>new le(e)):new le(e)}createDependencyCyclePlugin(){let{isDev:e,userConfig:t}=this.options;if(!(e||!t?.build?.dependencyCycleCheck))return new T.CircularDependencyRspackPlugin({exclude:/node_modules/,failOnError:!1})}joinAssetsDir(...e){return[this.options.assetsDir,...e].join(`/`).replace(/\/+/g,`/`)}};const Me=e=>{let{isVue:t,isReact:n}=e;return t?{noParse:/^(vue|vue-router|vuex|vuex-router-sync)$/,env:{__VUE_OPTIONS_API__:!0,__VUE_PROD_DEVTOOLS__:!1,__VUE_PROD_HYDRATION_MISMATCH_DETAILS__:!1}}:n?{noParse:e=>/(react|react-dom|react-is)\.production\.min\.js$/.test(e),env:{REACT_APP_ENABLE_DEVTOOLS:!1}}:{env:void 0,noParse:void 0}},Ne=e=>e===I.SERVER?{minimize:!1,removeAvailableModules:!1,removeEmptyChunks:!1,splitChunks:!1}:{minimize:!0,minimizer:[new T.LightningCssMinimizerRspackPlugin,new T.SwcJsMinimizerRspackPlugin],splitChunks:{chunks:`all`,minSize:3e4,minChunks:1,maxAsyncRequests:5,maxInitialRequests:3,cacheGroups:{vendor:{test:/[\\/]node_modules[\\/]/,name:`vendors`,priority:10,chunks:`all`},common:{name:`common`,minChunks:2,priority:5,reuseExistingChunk:!0}}}},Pe=e=>{if(e.command!==I.SERVER&&e.userConfig?.build?.cache)return{cache:!0,experiments:{cache:{type:`persistent`}}}},Fe=e=>{let{userConfig:t,isElectron:n,resolveContext:r}=e,i=t?.build?.outDirName;if(n){let e=t?.electron,n=r(`dist/electron/renderer`);return e?.build?.outDir?o(r(e.build.outDir),`renderer`):n}return m(i)?r(i):r(`dist`)},Ie=(e,t)=>[e,t].filter(Boolean).join(`/`).replace(/\/+/g,`/`),Le=e=>{let{command:t,mode:n,env:r,context:i,contextPkg:a,userConfig:s,pages:c,browserslist:l,base:u,port:d,isElectron:f,resolveContext:p}=e,m=t===I.SERVER,h=m?`development`:`production`,g=new K({env:h,mode:n}),_=new q({env:h,mode:n}),{entry:v,plugins:y}=new Ee({pages:c,enablePages:s?.enablePages}).create(),{env:b,noParse:x}=Me({isVue:e.isVue,isReact:e.isReact}),S=g.useDefaultResourceLoader().useDefaultScriptLoader(s?.experiments).useDefaultCssLoader(s?.css).add(s?.loaders).end(),C=s?.build?.assetsDir??``,w=new je({command:t,userConfig:s,isDev:m,assetsDir:C}),ee=_.useDefaultEnvPlugin({extEnv:{...s?.define},frameworkEnv:b,env:r}).useCopyPlugin().add(y).add(new Oe).add(w.createSourceMapPlugin()).add(w.createCssExtractPlugin()).add(w.createDoctorPlugin()).add(w.createGzipPlugin()).add(w.createCdnPlugin()).add(w.createModuleFederationPlugin()).add(w.createDependencyCyclePlugin()).add(s?.plugins).end();return{mode:h,context:i,entry:v,target:f?`electron-renderer`:[`web`,`es2015`,`browserslist:${l}`],resolve:{alias:{"@":p(`src`),...s?.resolve?.alias},extensions:s?.resolve?.extensions||V,modules:[`node_modules`,p(`node_modules`),U(`node_modules`)]},output:{clean:!0,path:Fe({userConfig:s,isElectron:f,resolveContext:p}),publicPath:f?`./`:u,filename:m?`[name].[contenthash:8].js`:Ie(C,`assets/js/[contenthash:8].js`),chunkFilename:m?`[name].[contenthash:8].chunk.js`:Ie(C,`assets/js/[contenthash:8].chunk.js`),chunkLoadingGlobal:`${a?.name||`ikaros`}_chunk`,pathinfo:!1},optimization:Ne(t),stats:`none`,watchOptions:{aggregateTimeout:500,ignored:/node_modules/},module:{rules:S,noParse:x},plugins:ee,devServer:{hot:!0,port:d,server:(()=>{let e=s?.server?.https;return e?e===!0?`https`:{type:`https`,options:e}:`http`})(),allowedHosts:`all`,proxy:s?.server?.proxy,historyApiFallback:{disableDotRule:!0,rewrites:[{from:/\.(js|css|json|png|jpe?g|gif|svg|ico|woff2?|eot|ttf|otf|mp4|webm|ogg|mp3|wav|flac|aac|map)(\?.*)?$/,to:e=>e.parsedUrl.pathname},{from:RegExp(`^${u}`),to:o(u,`index.html`)}]},headers:{"Access-Control-Allow-Origin":`*`},static:{directory:p(`public`),publicPath:u},client:{logging:`none`,overlay:{errors:!0,warnings:!1,runtimeErrors:!1},webSocketURL:`auto://0.0.0.0:${d}/ws`}},experiments:{css:!0},...Pe({command:t,userConfig:s})}},Re=e=>{let t=e===`mobile`,n=[`defaults`];return t?n.push(`IOS >= 16`,`Chrome >= 80`):n.push(`>0.2%`,`Chrome >= 90`,`Safari >= 16`,`last 2 versions`,`not dead`),n.join(`,`)},ze=(e,t)=>t?{index:{html:e(`src/renderer/index.html`),entry:e(`src/renderer/index`)}}:{index:{html:e(`index.html`),entry:e(`src/index`)}},Be=async e=>{let{command:t,resolveContext:n,getUserConfig:r,isElectron:i}=e,a=await r(),o=a?.build?.base??`/`;if(t===I.SERVER&&/^https?:/.test(o)){let e=w.cyan(`build.base`);throw Error(`本地开发时 ${e} 不应该为外部 Host!`)}let s=a?.target??`pc`,c=a?.pages??ze(n,!!i),l=a?.server?.port??await ue(`8080`),u=!1,d=!1;try{let[e,t]=await Promise.all([k(`react`),k(`vue`)]);u=t,d=e}catch{}return{userConfig:a,base:o,target:s,pages:c,port:l,browserslist:Re(s),isVue:u,isReact:d}},Ve=async e=>{let{command:t,options:n,env:r,context:i,contextPkg:a,userConfig:o,isElectron:s,resolveContext:c,loadViteAdapter:l}=e,u=await Be({command:t,resolveContext:c,getUserConfig:async()=>o,isElectron:s}),d=u.userConfig?.bundler??`rspack`;return{bundler:d,config:(()=>{switch(d){case`vite`:{let e=l?.();if(!e)throw Error(`bundler='vite' 需要安装可选依赖 @ikaros-cli/ikaros-bundler-vite`);return e.createWebViteConfig({command:t,mode:n.mode,env:r,context:i,userConfig:u.userConfig,pages:u.pages,base:u.base,port:u.port,isElectron:s,resolveContext:c})}case`rspack`:default:return Le({command:t,mode:n.mode,env:r,context:i,contextPkg:a,userConfig:u.userConfig,pages:u.pages,browserslist:u.browserslist,base:u.base,port:u.port,isElectron:s,isVue:u.isVue,isReact:u.isReact,resolveContext:c})}})(),pre:u}},He=()=>{let e=`@ikaros-cli/ikaros-bundler-vite`,t=[`你启用了 bundler='vite',但未安装可选依赖 ${e}。`,``,`请安装后重试:`,` pnpm add -D ${e}`];return Error(t.join(`
|
|
8
|
-
`))},
|
|
9
|
-
`))},
|
|
10
|
-
`))}
|
|
5
|
+
`)}getEndTips(e,t){let{gray:n,cyan:r,red:i,green:a,yellow:o}=v,{errorsCount:s=-1,warningsCount:c=-1}=e,l=(t/1e3).toFixed(2);return n(s>0?`${r(U.name)} compiled with${i(` ${s} error`)}`:c>0?`compile ${a(`success`)} and with ${o(`${c} warning`)}, time: ${l}s`:`compile ${a(`success`)}, time: ${l}s.`)}getTableInfo(e){let{assets:t}=e;if(!t||t.length===0)return;let n=new S,r=this.userConfig?.build?.gzip??!1,i=0,a=0,o=!1;for(let e=0;e<t.length;e++){let{name:s,size:c,related:l,info:u}=t[e];if(u.development)continue;let d=r&&h(l)?l.find(e=>e.type===`gzipped`).size:0;if(i+=c,a+=d,t.length>20&&e>=4&&e<t.length-1-4){o||(o=!0,n.cell(`name`,`....`),n.cell(`size`,`....`),r&&n.cell(`gzip`,`....`),n.newRow());continue}n.cell(`name`,s),n.cell(`size`,x(c)),r&&n.cell(`gzip`,x(d)),n.newRow()}return n.pushDelimeter(),n.cell(`name`,`There are ${t.length} files`),n.cell(`size`,x(i)),r&&n.cell(`gzip`,x(a)),n.newRow(),v.cyan.dim(n.toString().trim())}getHostList(){let{userConfig:e,compiler:t}=this,{devServer:n}=t.options,r=n?.server===`https`||typeof n?.server==`object`,i=Number(n?.port),a=[],s=``,c=Object.values(b.networkInterfaces());if(e){s=e.build?.base??``,(!s||s===`auto`)&&(s=`/`);let t=Object.keys(e?.pages||{})[0];t&&t!==`index`?s=o.join(s,`${t}.html`):s.endsWith(`/`)||(s+=`/`)}for(let e of c){let{address:t}=e?.find(e=>e.family===`IPv4`)||{};t&&a.push(t)}a.sort((e,t)=>{let n=e.split(`.`),r=t.split(`.`);for(let[t]of n.entries())if(e[t]!==r[t])return Number(r[t])-Number(e[t]);return 0});let l=a.indexOf(`127.0.0.1`);return l!==-1&&(a.splice(l,1),a.unshift(`localhost`)),a=a.map(e=>(r?(e=`https://${e}`,i!==443&&(e=e+`:`+i)):(e=`http://`+e,i!==80&&(e=e+`:`+i)),new URL(s,e).href)),a}initDevHook(){let{compiler:e}=this,t=this.getHostList(),{blue:n,cyan:r,gray:i}=v;e.hooks.environment.intercept({name:W}),e.hooks.watchRun.intercept({name:W,call:()=>{this.updateStartCompileTime()}}),e.hooks.done.intercept({name:W,call:e=>{console.clear();let a=e.toJson({preset:`errors-warnings`,colors:!0}),{eventArray:o}=L(),{errorsCount:s=0,warningsCount:c=0}=a;if(s>0)console.log(this.getError(a)),console.log();else{c>0&&(console.log(this.getWarn(a)),console.log()),o.length>0&&(console.log(o.map(e=>e).join(`
|
|
6
|
+
`)),console.log());let{name:e,version:s}=U,l=`${r(`${e} v${s}`)} entry address:\n\n`;for(let e of t)l+=n(` ${e}\n`);console.log(i(l))}console.log(this.getEndTips(a,this.getCurrentEndCompileTime())),console.log()}})}initProdHook(){let{compiler:e}=this,t;e.hooks.environment.intercept({name:W,call:()=>{console.log(v.gray(`start build...`)),this.updateStartCompileTime()}}),e.hooks.done.intercept({name:W,call:e=>{t=e.toJson({preset:`normal`,colors:!0,assetsSort:`size`})}}),e.cache.hooks.shutdown.intercept({name:W,done:()=>{let{errorsCount:e=0,warningsCount:n=0}=t;console.log(),e>0?(console.log(this.getError(t)),console.log()):(n>0&&(console.log(this.getWarn(t)),console.log()),console.log(this.getTableInfo(t)),console.log()),console.log(this.getEndTips(t,this.getCurrentEndCompileTime()))}})}};const K=`@rspack/ikaros-cdn-plugin`,q=/:([a-z]+)/gi;var he=class{constructor(e){this.isDev=!1,this.options={prodUrl:`https://unpkg.com/:name@:version/:path`,devUrl:`:name/:path`,crossOrigin:!1,...e}}apply(e){this.compiler=e,this.isDev=e.options.mode===`development`,this.handleExternals(),e.hooks.compilation.tap(K,e=>{r.HtmlRspackPlugin.getCompilationHooks(e).alterAssetTags.tapAsync(K,(e,t)=>{try{this.injectResources(e),t(null,e)}catch(e){t(e)}})})}handleExternals(){let e=this.compiler.options.externals||{};this.options.modules.filter(e=>!e.cssOnly).forEach(t=>{e[t.name]=t.var||t.name}),this.compiler.options.externals=e}injectResources(e){let t=this.options.modules,n=[];t.forEach(e=>{this.getStyles(e).forEach(e=>{n.push({tagName:`link`,voidTag:!0,attributes:{rel:`stylesheet`,href:e,...this.options.crossOrigin&&{crossorigin:this.options.crossOrigin}}})})}),t.filter(e=>!e.cssOnly).forEach(e=>{this.getScripts(e).forEach(e=>{n.push({tagName:`script`,voidTag:!0,attributes:{src:e,...this.options.crossOrigin&&{crossorigin:this.options.crossOrigin}}})})}),e.assetTags&&(e.assetTags.styles.unshift(...n.filter(e=>e.tagName===`link`)),e.assetTags.scripts.unshift(...n.filter(e=>e.tagName===`script`)))}getStyles(e){let t=[...e.styles||[]];return e.style&&t.unshift(e.style),t.map(t=>this.generateUrl(e,t))}getScripts(e){let t=[...e.paths||[]];return e.path&&t.unshift(e.path),t.map(t=>this.generateUrl(e,t))}joinUrl(e,t){return e=e.replace(/\/+$/,``),t=t.replace(/^\/+/,``),`${e}/${t}`}generateUrl(e,t){let n=this.isDev?e.devUrl||this.options.devUrl:e.prodUrl||this.options.prodUrl;return n.match(q)?n.replace(q,(n,r)=>{switch(r){case`name`:return e.name;case`version`:return e.version||this.getModuleVersion(e.name);case`path`:return t;default:return n}}):this.joinUrl(n,t)}getModuleVersion(t){try{return e(d.join(process.cwd(),`node_modules`))(d.join(t,`package.json`)).version}catch{return console.warn(v.yellow(`[${K}] 无法获取模块 "${t}" 的版本信息`)),`latest`}}},ge=class{constructor(e){this.options=e}createSourceMapPlugin(){let{isDev:e,userConfig:t}=this.options;if(e)return new r.EvalSourceMapDevToolPlugin({columns:!1,module:!0});if(t?.build?.sourceMap??!1)return new r.SourceMapDevToolPlugin({test:[/.js/,/.mjs/],filename:`[file].map[query]`})}createCssExtractPlugin(){if(!this.options.isDev)return new r.CssExtractRspackPlugin({filename:this.joinAssetsDir(`assets/css/[contenthash].css`),ignoreOrder:!0})}createDoctorPlugin(){let{isDev:e,userConfig:t}=this.options;if(!(e||!t?.build?.outReport))return new T}createGzipPlugin(){let{isDev:e,userConfig:t}=this.options;if(!(e||!t?.build?.gzip))return new ee}createCdnPlugin(){let{cdnOptions:e}=this.options.userConfig??{};if(!(!e||g(e.modules)))return new he(e)}createModuleFederationPlugin(){let e=this.options.userConfig?.moduleFederation;if(e)return h(e)?e.map(e=>new E(e)):new E(e)}createDependencyCyclePlugin(){let{isDev:e,userConfig:t}=this.options;if(!(e||!t?.build?.dependencyCycleCheck))return new r.CircularDependencyRspackPlugin({exclude:/node_modules/,failOnError:!1})}joinAssetsDir(...e){return[this.options.assetsDir,...e].join(`/`).replace(/\/+/g,`/`)}};const J={target:O.enum([`pc`,`mobile`]).optional().default(`pc`),pages:O.custom().optional(),enablePages:O.union([O.array(O.string()),O.literal(!1)]).optional(),define:O.custom().optional(),build:O.object({base:O.string().optional().default(`/`),assetsDir:O.string().optional(),sourceMap:O.boolean().optional().default(!1),outDirName:O.string().optional().default(`dist`)}).optional(),resolve:O.object({alias:O.record(O.string(),O.string()).optional(),extensions:O.array(O.string()).optional()}).optional(),server:O.object({port:O.number().int().min(1024).max(65535).optional()}).optional(),electron:O.unknown().optional()},_e=O.object({bundler:O.custom().optional().default(`rspack`).refine(e=>e===`rspack`,{message:`bundler must be 'rspack' for rspack config`}),...J,moduleFederation:O.union([O.custom(),O.array(O.custom())]).optional(),plugins:O.union([O.custom(),O.array(O.custom())]).optional(),loaders:O.array(O.custom()).optional(),experiments:O.custom().optional(),cdnOptions:O.custom().optional(),server:O.object({port:O.number().int().min(1024).max(65535).optional(),proxy:O.custom().optional(),https:O.union([O.boolean(),O.record(O.string(),O.unknown())]).optional().default(!1)}).optional(),css:O.object({lightningcssOptions:O.record(O.string(),O.unknown()).optional(),sourceMap:O.boolean().optional(),lessOptions:O.record(O.string(),O.unknown()).optional(),sassOptions:O.record(O.string(),O.unknown()).optional(),stylusOptions:O.record(O.string(),O.unknown()).optional()}).optional(),build:O.object({base:O.string().optional().default(`/`),assetsDir:O.string().optional(),gzip:O.boolean().optional().default(!1),sourceMap:O.boolean().optional().default(!1),outDirName:O.string().optional().default(`dist`),outReport:O.boolean().optional().default(!1),cache:O.boolean().optional().default(!1),dependencyCycleCheck:O.boolean().optional().default(!1)}).optional()}),ve=O.object({bundler:O.literal(`vite`),...J,server:O.object({port:O.number().int().min(1024).max(65535).optional(),proxy:O.record(O.string(),O.unknown()).optional(),https:O.union([O.boolean(),O.record(O.string(),O.unknown())]).optional()}).optional(),vite:O.object({plugins:O.unknown().optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{for(let n of[`plugins`,`loaders`,`experiments`,`cdnOptions`,`moduleFederation`,`css`]){let r=e;n in r&&r[n]!==void 0&&t.addIssue({code:O.ZodIssueCode.custom,path:[n],message:`bundler='vite' 时不支持 ${String(n)},请使用 vite.plugins 或 Vite 原生配置能力`})}}),Y=O.union([ve,_e]),X=(e,t)=>t?f(e,`env`,`.env.${t}`):f(e,`env`,`.env`),ye=async(e,t)=>{let{warning:n,emitEvent:r}=L();if(!await k.pathExists(f(e,`env`)))return r(n({text:`env folder not found`,onlyText:!0})),!1;if(t){if(!await k.pathExists(X(e,t)))return r(n({text:`.env.${t} file not found`,onlyText:!0})),!1}else return await k.pathExists(X(e))?!0:(r(n({text:`.env file not found`,onlyText:!0})),!1);return!0},be=async(e,t)=>await ye(e,t)?t?A({path:X(e,t),quiet:!0}).parsed??{}:A({path:X(e),quiet:!0}).parsed??{}:{};async function xe(e,t){let{code:n,errors:r}=await ie(e,await ne(e,`utf-8`),{lang:t?`ts`:`js`});if(r.length>0)throw Error(`Transformation failed: `+r.map(e=>e.message).join(`, `));return{code:n}}async function Se(e,t){let n=`${e}.timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`,r=`${n}.mjs`,i=`${m(n)}.mjs`;await D.writeFile(r,t);try{return(await import(i)).default}finally{await D.unlink(r)}}async function Ce(e,t=!1){let{code:n}=await xe(e,t);return Se(e,n)}const Z=new Map;Z.set(`.mjs`,async e=>(await import(m(e).href)).default),Z.set(`.ts`,async e=>await Ce(e,!0)),Z.set(`.json`,async e=>await k.readJson(e)),Z.set(`.yaml`,async e=>re(await D.readFile(e,`utf8`)));async function we({configFile:e,context:t}){let n,r=t??process.cwd(),i=`ikaros.config`,a=[`ts`,`mjs`,`json`,`yaml`].map(e=>`${l(r,i)}.${e}`),o=(await Promise.all(a.map(e=>k.pathExists(e)))).findIndex(Boolean);if(!(o<0)){if(n=c(a[o]),r=u(r,`${i}${n}`),e&&(r=s(e),n=c(e)),!Z.has(n))throw Error(`No configuration file ! `);return Z.get(n)(r)}}let Q=function(e){return e.SERVER=`server`,e.BUILD=`build`,e}({});async function Te(t){let{command:n,options:r,configFile:i,onBuildStatus:a}=t,o=process.cwd(),s=e(l(o,`./`)),c=(...e)=>l(o,...e),u=e=>s(e),d=e=>{try{return s.resolve(e)}catch{return}},f=await Ee(c),p=await De(r,o);return{context:o,command:n,options:r,env:p,userConfig:await Oe({configFile:i,context:o,options:r,env:p,command:n}),contextPkg:f,resolveContext:c,loadContextModule:u,resolveContextModule:d,contextRequire:s,isElectron:r.platform===`desktopClient`,configFile:i,onBuildStatus:a}}async function Ee(e){let t=e(`package.json`);try{await D.access(t,te.constants.F_OK)}catch{return}return JSON.parse(await D.readFile(t,{encoding:`utf8`}))}async function De(e,t){let{platform:n,mode:r}=e,i={PLATFORM:n,MODE:r},a=await be(t,r);return{...i,...a}}async function Oe(e){let{configFile:t,context:n,options:r,env:a,command:o}=e,s=await we({configFile:t,context:n});if(s){if(i(s)){let e={mode:r.mode??``,env:{...a,PLATFORM:r.platform,MODE:r.mode??a?.MODE},command:o};return Y.parse(await s(e))}if(_(s))return Y.parse(s)}}const ke=e=>{let{isVue:t,isReact:n}=e;return t?{noParse:/^(vue|vue-router|vuex|vuex-router-sync)$/,env:{__VUE_OPTIONS_API__:!0,__VUE_PROD_DEVTOOLS__:!1,__VUE_PROD_HYDRATION_MISMATCH_DETAILS__:!1}}:n?{noParse:e=>/(react|react-dom|react-is)\.production\.min\.js$/.test(e),env:{REACT_APP_ENABLE_DEVTOOLS:!1}}:{env:void 0,noParse:void 0}},Ae=e=>e===Q.SERVER?{minimize:!1,removeAvailableModules:!1,removeEmptyChunks:!1,splitChunks:!1}:{minimize:!0,minimizer:[new r.LightningCssMinimizerRspackPlugin,new r.SwcJsMinimizerRspackPlugin],splitChunks:{chunks:`all`,minSize:3e4,minChunks:1,maxAsyncRequests:5,maxInitialRequests:3,cacheGroups:{vendor:{test:/[\\/]node_modules[\\/]/,name:`vendors`,priority:10,chunks:`all`},common:{name:`common`,minChunks:2,priority:5,reuseExistingChunk:!0}}}},je=e=>{if(e.command!==Q.SERVER&&e.userConfig?.build?.cache)return{cache:!0,experiments:{cache:{type:`persistent`}}}},Me=e=>{let{userConfig:t,isElectron:n,resolveContext:r}=e,i=t?.build?.outDirName;if(n){let e=t?.electron,n=r(`dist/electron/renderer`);return e?.build?.outDir?l(r(e.build.outDir),`renderer`):n}return a(i)?r(i):r(`dist`)},Ne=(e,t)=>[e,t].filter(Boolean).join(`/`).replace(/\/+/g,`/`),Pe=e=>{let{command:t,mode:n,env:r,context:i,contextPkg:a,userConfig:o,pages:s,browserslist:c,base:u,port:d,isElectron:f,resolveContext:p}=e,m=t===Q.SERVER,h=m?`development`:`production`,g=new V({env:h,mode:n}),_=new H({env:h,mode:n}),{entry:v,plugins:y}=new fe({pages:s,enablePages:o?.enablePages}).create(),{env:b,noParse:x}=ke({isVue:e.isVue,isReact:e.isReact}),S=g.useDefaultResourceLoader().useDefaultScriptLoader(o?.experiments).useDefaultCssLoader(o?.css).add(o?.loaders).end(),C=o?.build?.assetsDir??``,w=new ge({command:t,userConfig:o,isDev:m,assetsDir:C}),T=_.useDefaultEnvPlugin({extEnv:{...o?.define},frameworkEnv:b,env:r}).useCopyPlugin().add(y).add(new me).add(w.createSourceMapPlugin()).add(w.createCssExtractPlugin()).add(w.createDoctorPlugin()).add(w.createGzipPlugin()).add(w.createCdnPlugin()).add(w.createModuleFederationPlugin()).add(w.createDependencyCyclePlugin()).add(o?.plugins).end();return{mode:h,context:i,entry:v,target:f?`electron-renderer`:[`web`,`es2015`,`browserslist:${c}`],resolve:{alias:{"@":p(`src`),...o?.resolve?.alias},extensions:o?.resolve?.extensions||M,modules:[`node_modules`,p(`node_modules`),P(`node_modules`)]},output:{clean:!0,path:Me({userConfig:o,isElectron:f,resolveContext:p}),publicPath:f&&!m?`./`:u,filename:m?`[name].[contenthash:8].js`:Ne(C,`assets/js/[contenthash:8].js`),chunkFilename:m?`[name].[contenthash:8].chunk.js`:Ne(C,`assets/js/[contenthash:8].chunk.js`),chunkLoadingGlobal:`${a?.name||`ikaros`}_chunk`,pathinfo:!1},optimization:Ae(t),stats:`none`,watchOptions:{aggregateTimeout:500,ignored:/node_modules/},module:{rules:S,noParse:x},plugins:T,devServer:{hot:!0,port:d,server:(()=>{let e=o?.server?.https;return e?e===!0?`https`:{type:`https`,options:e}:`http`})(),allowedHosts:`all`,proxy:o?.server?.proxy,historyApiFallback:{disableDotRule:!0,rewrites:[{from:/\.(js|css|json|png|jpe?g|gif|svg|ico|woff2?|eot|ttf|otf|mp4|webm|ogg|mp3|wav|flac|aac|map)(\?.*)?$/,to:e=>e.parsedUrl.pathname},{from:RegExp(`^${u}`),to:l(u,`index.html`)}]},headers:{"Access-Control-Allow-Origin":`*`},static:{directory:p(`public`),publicPath:u},client:{logging:`none`,overlay:{errors:!0,warnings:!1,runtimeErrors:!1},webSocketURL:`auto://0.0.0.0:${d}/ws`}},experiments:{css:!0},...je({command:t,userConfig:o})}},Fe=e=>{let t=`Build failed with errors.
|
|
7
|
+
`;return e.toString({chunks:!1,colors:!0}).split(/\r?\n/).forEach(e=>{t+=` ${e}\n`}),t},Ie=(e,t)=>{let{onBuildStatus:n}=t??{};return new Promise((t,i)=>{let a=r(e);a.run((e,r)=>{a.close(a=>{let o=e||a;if(o)return n?.({success:!1,message:o.message||`build error`}),i(o);if(r?.hasErrors()){let e=Fe(r);return n?.({success:!1,message:e}),i(Error(e))}let s=r?.toString({chunks:!1,colors:!0});return n?.({success:!0,message:s}),t(s)})})})},Le=async(e,t)=>{let{port:n,onBuildStatus:i}=t??{},a=r(e),o=new ae(e.devServer,a);await new Promise((e,t)=>{o.startCallback(r=>r?(i?.({success:!1,port:n,message:r.message}),t(r)):(i?.({success:!0,port:n}),e()))})},Re=(e,t)=>{let{onBuildStatus:n,...i}=t??{};return new Promise((t,a)=>{r(e).watch({ignored:/node_modules/,aggregateTimeout:300,poll:!1,...i},(e,r)=>{if(e)return n?.({success:!1,message:e.message||`watch build error`}),a(e);if(r?.hasErrors()){let e=Fe(r);return n?.({success:!1,message:e}),a(Error(e))}let i=r?.toString({chunks:!1,colors:!0});return n?.({success:!0,message:i}),t(i)})})};var ze=class{constructor(){this.name=`rspack`}createConfig(e){return Pe({command:e.command===`server`?Q.SERVER:Q.BUILD,mode:e.mode,env:e.env,context:e.context,contextPkg:e.contextPkg,userConfig:e.userConfig,pages:e.pages,browserslist:e.browserslist,base:e.base,port:e.port,isElectron:e.isElectron,isVue:e.isVue,isReact:e.isReact,resolveContext:e.resolveContext})}async runDev(e,t){await Le(e,{port:t.port,onBuildStatus:t.onBuildStatus})}async runBuild(e,t){return Ie(e,{onBuildStatus:t.onBuildStatus})}};const Be=()=>{let e=`@ikaros-cli/ikaros-bundler-vite`,t=[`你启用了 bundler='vite',但未安装可选依赖 ${e}。`,``,`请安装后重试:`,` pnpm add -D ${e}`];return Error(t.join(`
|
|
8
|
+
`))},Ve=()=>{let e=[`你启用了 bundler='vite',但当前 Node.js 版本过低。`,`当前版本:v${process.versions.node}`,`Vite 7 运行时通常需要 Node.js >= 22。`];return Error(e.join(`
|
|
9
|
+
`))};var He=class{constructor(e){this.name=`vite`,this.loadContextModule=e.loadContextModule}ensureAdapter(){if(this.adapter)return this.adapter;let e=Number(process.versions.node.split(`.`)[0]);if(Number.isFinite(e)&&e<22)throw Ve();try{let e=this.loadContextModule(`@ikaros-cli/ikaros-bundler-vite`),t=(e.default??e).ViteBundlerAdapter;if(typeof t!=`function`)throw Be();return this.adapter=new t,this.adapter}catch(e){throw e instanceof Error&&e.message.includes(`bundler='vite'`)?e:Be()}}createConfig(e){return this.ensureAdapter().createConfig(e)}async runDev(e,t){return this.ensureAdapter().runDev(e,t)}async runBuild(e,t){return this.ensureAdapter().runBuild(e,t)}};function Ue(e){let{bundler:t,loadContextModule:n}=e;switch(t){case`vite`:return new He({loadContextModule:n});default:return new ze}}const We=e=>{let t=e===`mobile`,n=[`defaults`];return t?n.push(`IOS >= 16`,`Chrome >= 80`):n.push(`>0.2%`,`Chrome >= 90`,`Safari >= 16`,`last 2 versions`,`not dead`),n.join(`,`)},Ge=(e,t)=>t?{index:{html:e(`src/renderer/index.html`),entry:e(`src/renderer/index`)}}:{index:{html:e(`index.html`),entry:e(`src/index`)}},Ke=async e=>{let{command:t,context:n,resolveContext:r,getUserConfig:i,isElectron:a}=e,o=await i(),s=o?.build?.base??`/`;if(t===Q.SERVER&&/^https?:/.test(s)){let e=v.cyan(`build.base`);throw Error(`本地开发时 ${e} 不应该为外部 Host!`)}let c=o?.target??`pc`,l=o?.pages??Ge(r,!!a),u=o?.server?.port??await oe(`8080`),d=!1,f=!1;try{let[e,t]=await Promise.all([z(`react`,n),z(`vue`,n)]);d=t,f=e}catch{}return{userConfig:o,base:s,target:c,pages:l,port:u,browserslist:We(c),isVue:d,isReact:f}};var qe=class{constructor(){this.name=`web`}async resolvePreConfig(e){return Ke({command:e.command,context:e.context,resolveContext:e.resolveContext,getUserConfig:async()=>e.userConfig,isElectron:e.isElectron})}async compile(e,t){let{command:n,preConfig:r,compileContext:i}=t,a=await e.createConfig({command:n,mode:i.options.mode,env:i.env,context:i.context,contextPkg:i.contextPkg,userConfig:r.userConfig,pages:r.pages,base:r.base,port:r.port,browserslist:r.browserslist,isElectron:i.isElectron,isVue:r.isVue,isReact:r.isReact,resolveContext:i.resolveContext});n===`server`?await e.runDev(a,{port:r.port,onBuildStatus:i.onBuildStatus}):await e.runBuild(a,{onBuildStatus:i.onBuildStatus})}};function Je(e){switch(e){case`desktopClient`:return Ye();default:return new qe}}function Ye(){let e,t=async()=>e||(e=await Xe(),e);return{name:`desktopClient`,async resolvePreConfig(e){return(await t()).resolvePreConfig(e)},async compile(e,n){return(await t()).compile(e,n)}}}async function Xe(){let t=`@ikaros-cli/ikaros-platform-desktop-client`,n=e=>{let n=[`你启用了 platform='desktopClient',但未安装可选依赖 ${t}。`,``,`请安装后重试:`,` pnpm add -D ${t}`];if(e){let t=e instanceof Error?e.message:String(e);n.push(``,`原始错误: ${t}`)}return Error(n.join(`
|
|
10
|
+
`))},r;try{r=await import(m(e(l(process.cwd(),`./`)).resolve(t)).href)}catch(e){throw n(e)}let i=(r.default??r).ElectronDesktopPlatformInstance;if(!i||typeof i.resolvePreConfig!=`function`)throw Error([`${t} 已安装但加载失败:未找到 ElectronDesktopPlatformInstance 导出。`,`请确认安装的版本与 @ikaros-cli/ikaros 兼容(需 >=3.0)。`].join(`
|
|
11
|
+
`));return i}async function Ze(e){let t=await Te(e),n=Je(t.options.platform),r=await n.resolvePreConfig(t);t.userConfig=r.userConfig;let i=Ue({bundler:t.userConfig?.bundler??`rspack`,loadContextModule:t.loadContextModule});await n.compile(i,{command:t.command,preConfig:r,compileContext:t})}const Qe={WEB:`web`,DESKTOPCLIENT:`desktopClient`,ELECTRON:`desktopClient`},$e=[new t(`-m, --mode <name>`,`Environment variable`),new t(`-p, --platform <type>`,`build platform type`).default(Qe.WEB).choices(Object.values(Qe))],$=async e=>{try{await Ze(e)}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}\n`),process.exit(1)}},et=e=>{let t=e.command(Q.SERVER,{isDefault:!0}).description(`Start local develop serve`).action(async e=>{await $({command:Q.SERVER,options:e})}),n=e.command(Q.BUILD).description(`Start build`).action(async e=>{await $({command:Q.BUILD,options:e})});for(let e of $e)t.addOption(e),n.addOption(e)},tt=e=>e;if(Number(process.versions.node.split(`.`)[0])<22){let e=v.bgRed.white(` ERROR `);process.stderr.write(`${e} Node.js version must be greater than or equal to v22!\n\n`),process.exit(1)}n.version(ce,`-v, --version`),et(n),n.parse();export{Q as Command,V as CreateLoader,H as CreatePlugins,L as LoggerSystem,ze as RspackAdapter,He as ViteAdapterLoader,qe as WebPlatformAdapter,Ue as createBundlerAdapter,Te as createCompileContext,Je as createPlatformAdapter,tt as defineConfig,M as extensions,P as resolveCLI,Ke as resolveWebPreConfig,Ze as runCompile,Ie as runRspackBuild,Re as watchRspackBuild};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ikaros-cli/ikaros",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -18,7 +18,8 @@
|
|
|
18
18
|
"scripts": {
|
|
19
19
|
"dev": "tsdown --watch",
|
|
20
20
|
"dts": "tsdown --dts",
|
|
21
|
-
"build": "tsdown"
|
|
21
|
+
"build": "tsdown",
|
|
22
|
+
"test": "vitest run"
|
|
22
23
|
},
|
|
23
24
|
"keywords": [
|
|
24
25
|
"vue",
|
|
@@ -42,35 +43,35 @@
|
|
|
42
43
|
"npm": ">=9.5.0"
|
|
43
44
|
},
|
|
44
45
|
"dependencies": {
|
|
45
|
-
"@module-federation/enhanced": "^0.
|
|
46
|
-
"@rsdoctor/rspack-plugin": "^1.
|
|
46
|
+
"@module-federation/enhanced": "^2.0.0",
|
|
47
|
+
"@rsdoctor/rspack-plugin": "^1.5.2",
|
|
47
48
|
"@rspack/core": "^1.7.2",
|
|
48
|
-
"@rspack/dev-server": "^1.1
|
|
49
|
+
"@rspack/dev-server": "^1.2.1",
|
|
49
50
|
"chalk": "^5.6.2",
|
|
50
51
|
"cli-cursor": "^5.0.0",
|
|
51
|
-
"commander": "^14.0.
|
|
52
|
+
"commander": "^14.0.3",
|
|
52
53
|
"compression-webpack-plugin": "^11.1.0",
|
|
53
|
-
"css-loader": "^7.1.
|
|
54
|
+
"css-loader": "^7.1.3",
|
|
54
55
|
"detect-port": "^2.1.0",
|
|
55
|
-
"dotenv": "^17.2.
|
|
56
|
+
"dotenv": "^17.2.4",
|
|
56
57
|
"easy-table": "^1.2.0",
|
|
57
|
-
"es-toolkit": "^1.
|
|
58
|
+
"es-toolkit": "^1.44.0",
|
|
58
59
|
"fs-extra": "^11.3.3",
|
|
59
|
-
"glob": "^13.0.
|
|
60
|
-
"less-loader": "^12.3.
|
|
61
|
-
"listr2": "^
|
|
62
|
-
"ora": "^9.
|
|
63
|
-
"oxc-transform": "^0.
|
|
60
|
+
"glob": "^13.0.1",
|
|
61
|
+
"less-loader": "^12.3.1",
|
|
62
|
+
"listr2": "^10.1.0",
|
|
63
|
+
"ora": "^9.3.0",
|
|
64
|
+
"oxc-transform": "^0.112.0",
|
|
64
65
|
"picocolors": "^1.1.1",
|
|
65
66
|
"pretty-bytes": "^7.1.0",
|
|
66
|
-
"sass-loader": "^16.0.
|
|
67
|
-
"stylus-loader": "^8.1.
|
|
67
|
+
"sass-loader": "^16.0.7",
|
|
68
|
+
"stylus-loader": "^8.1.3",
|
|
68
69
|
"vue-style-loader": "^4.1.3",
|
|
69
70
|
"yaml": "^2.8.2",
|
|
70
|
-
"zod": "^4.3.
|
|
71
|
+
"zod": "^4.3.6"
|
|
71
72
|
},
|
|
72
73
|
"devDependencies": {
|
|
73
74
|
"@types/fs-extra": "^11.0.4",
|
|
74
|
-
"vitest": "^4.0.
|
|
75
|
+
"vitest": "^4.0.18"
|
|
75
76
|
}
|
|
76
77
|
}
|