@rsdoctor/core 2.0.0-alpha.1 → 2.0.0-beta.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 (177) hide show
  1. package/dist/26.js +26174 -0
  2. package/dist/630.js +1280 -0
  3. package/dist/630.js.LICENSE.txt +7 -0
  4. package/dist/build-utils/build/chunks/assetsModules.d.ts +7 -1
  5. package/dist/build-utils/build/loader/probeLoader.d.ts +7 -2
  6. package/dist/build-utils/build/server.d.ts +1 -2
  7. package/dist/build-utils/build/utils/parseBundle.d.ts +1 -1
  8. package/dist/index.d.ts +5 -5
  9. package/dist/index.js +1908 -7
  10. package/dist/inner-plugins/constants.d.ts +1 -1
  11. package/dist/inner-plugins/plugins/base.d.ts +2 -2
  12. package/dist/inner-plugins/plugins/errors.d.ts +1 -0
  13. package/dist/inner-plugins/plugins/plugins.d.ts +1 -1
  14. package/dist/inner-plugins/plugins/summary.d.ts +3 -2
  15. package/dist/inner-plugins/utils/sdk.d.ts +2 -1
  16. package/dist/logger.d.ts +2 -2
  17. package/dist/probe-loader.js +2 -0
  18. package/dist/proxy-loader.d.ts +1 -0
  19. package/dist/proxy-loader.js +48 -0
  20. package/dist/rslib-runtime.js +28 -0
  21. package/dist/rspack-plugin/constants.d.ts +1 -1
  22. package/dist/rspack-plugin/multiple.d.ts +5 -3
  23. package/dist/rspack-plugin/plugin.d.ts +43 -17
  24. package/dist/rspack-plugin/session.d.ts +20 -0
  25. package/dist/rules/rules/ecma-version-check/htmlParserStub.d.ts +3 -0
  26. package/dist/rules/rules/ecma-version-check/types.d.ts +13 -2
  27. package/dist/sdk/multiple/controller.d.ts +13 -2
  28. package/dist/sdk/multiple/primary.d.ts +12 -4
  29. package/dist/sdk/server/apis/base.d.ts +1 -1
  30. package/dist/sdk/server/socket/api.d.ts +1 -1
  31. package/dist/sdk/utils/date.d.ts +1 -0
  32. package/dist/types/loader.d.ts +1 -1
  33. package/package.json +23 -117
  34. package/dist/build-utils/build/chunks/assetsModules.js +0 -9
  35. package/dist/build-utils/build/chunks/index.js +0 -3
  36. package/dist/build-utils/build/chunks/rspack/transform.js +0 -44
  37. package/dist/build-utils/build/envinfo.js +0 -60
  38. package/dist/build-utils/build/file/cache.js +0 -24
  39. package/dist/build-utils/build/file/index.js +0 -5
  40. package/dist/build-utils/build/file/sharding.js +0 -38
  41. package/dist/build-utils/build/index.js +0 -12
  42. package/dist/build-utils/build/json.js +0 -67
  43. package/dist/build-utils/build/loader/index.js +0 -3
  44. package/dist/build-utils/build/loader/probeLoader.js +0 -44
  45. package/dist/build-utils/build/loader/probeLoaderPlugin.js +0 -32
  46. package/dist/build-utils/build/module-graph/index.js +0 -2
  47. package/dist/build-utils/build/module-graph/parser.js +0 -13
  48. package/dist/build-utils/build/module-graph/rspack/transform.js +0 -111
  49. package/dist/build-utils/build/module-graph/utils.js +0 -60
  50. package/dist/build-utils/build/process.js +0 -18
  51. package/dist/build-utils/build/server.js +0 -107
  52. package/dist/build-utils/build/utils/index.js +0 -4
  53. package/dist/build-utils/build/utils/loader.js +0 -267
  54. package/dist/build-utils/build/utils/parseBundle.js +0 -238
  55. package/dist/build-utils/build/utils/plugin.js +0 -21
  56. package/dist/build-utils/index.js +0 -13
  57. package/dist/collection.d.ts +0 -1
  58. package/dist/collection.js +0 -2
  59. package/dist/common/file.js +0 -8
  60. package/dist/common/global-config.js +0 -33
  61. package/dist/common/index.d.ts +0 -4
  62. package/dist/common/index.js +0 -6
  63. package/dist/common-browser.d.ts +0 -1
  64. package/dist/common-browser.js +0 -2
  65. package/dist/error/error.js +0 -143
  66. package/dist/error/index.js +0 -3
  67. package/dist/error/transform.js +0 -138
  68. package/dist/error/utils.js +0 -23
  69. package/dist/graph/index.d.ts +0 -1
  70. package/dist/graph/index.js +0 -2
  71. package/dist/inner-plugins/constants.js +0 -19
  72. package/dist/inner-plugins/index.js +0 -3
  73. package/dist/inner-plugins/loaders/proxy.js +0 -65
  74. package/dist/inner-plugins/plugins/base.js +0 -20
  75. package/dist/inner-plugins/plugins/bundle.js +0 -63
  76. package/dist/inner-plugins/plugins/ensureModulesChunkGraph.js +0 -74
  77. package/dist/inner-plugins/plugins/errors.js +0 -65
  78. package/dist/inner-plugins/plugins/index.js +0 -11
  79. package/dist/inner-plugins/plugins/loader.js +0 -108
  80. package/dist/inner-plugins/plugins/plugins.js +0 -40
  81. package/dist/inner-plugins/plugins/progress.js +0 -35
  82. package/dist/inner-plugins/plugins/resolver.js +0 -57
  83. package/dist/inner-plugins/plugins/rspack.js +0 -99
  84. package/dist/inner-plugins/plugins/rules.js +0 -64
  85. package/dist/inner-plugins/plugins/sourcemapTool.js +0 -230
  86. package/dist/inner-plugins/plugins/summary.js +0 -92
  87. package/dist/inner-plugins/utils/circleDetect.js +0 -16
  88. package/dist/inner-plugins/utils/config.js +0 -141
  89. package/dist/inner-plugins/utils/index.js +0 -8
  90. package/dist/inner-plugins/utils/loader.js +0 -134
  91. package/dist/inner-plugins/utils/normalize-config.js +0 -77
  92. package/dist/inner-plugins/utils/openBrowser.js +0 -55
  93. package/dist/inner-plugins/utils/plugin-common.js +0 -94
  94. package/dist/inner-plugins/utils/plugin.js +0 -70
  95. package/dist/inner-plugins/utils/sdk.js +0 -19
  96. package/dist/logger.js +0 -51
  97. package/dist/rspack-plugin/constants.js +0 -23
  98. package/dist/rspack-plugin/index.js +0 -3
  99. package/dist/rspack-plugin/multiple.js +0 -39
  100. package/dist/rspack-plugin/plugin.js +0 -133
  101. package/dist/rule-utils/document/document.js +0 -46
  102. package/dist/rule-utils/document/index.js +0 -4
  103. package/dist/rule-utils/document/server.js +0 -13
  104. package/dist/rule-utils/document/types.js +0 -1
  105. package/dist/rule-utils/index.js +0 -3
  106. package/dist/rule-utils/parser/asserts.js +0 -105
  107. package/dist/rule-utils/parser/index.js +0 -5
  108. package/dist/rule-utils/parser/parser.js +0 -24
  109. package/dist/rule-utils/parser/types.js +0 -8
  110. package/dist/rule-utils/parser/utils.js +0 -106
  111. package/dist/rules/index.js +0 -4
  112. package/dist/rules/linter.js +0 -36
  113. package/dist/rules/rule.js +0 -101
  114. package/dist/rules/rules/cjs-require/index.js +0 -50
  115. package/dist/rules/rules/cjs-require/types.js +0 -1
  116. package/dist/rules/rules/cross-chunks-package/index.js +0 -41
  117. package/dist/rules/rules/cross-chunks-package/types.js +0 -1
  118. package/dist/rules/rules/cross-chunks-package/utils.js +0 -7
  119. package/dist/rules/rules/default-import-check/index.js +0 -83
  120. package/dist/rules/rules/default-import-check/types.js +0 -1
  121. package/dist/rules/rules/default-import-check/utils.js +0 -52
  122. package/dist/rules/rules/duplicate-package/index.js +0 -39
  123. package/dist/rules/rules/duplicate-package/types.js +0 -24
  124. package/dist/rules/rules/duplicate-package/utils.js +0 -38
  125. package/dist/rules/rules/ecma-version-check/index.js +0 -53
  126. package/dist/rules/rules/ecma-version-check/types.js +0 -1
  127. package/dist/rules/rules/ecma-version-check/utils.js +0 -6
  128. package/dist/rules/rules/esm-resolved-to-cjs/index.js +0 -193
  129. package/dist/rules/rules/esm-resolved-to-cjs/types.js +0 -1
  130. package/dist/rules/rules/index.js +0 -22
  131. package/dist/rules/rules/loader-performance-optimization/index.js +0 -86
  132. package/dist/rules/rules/loader-performance-optimization/types.js +0 -1
  133. package/dist/rules/rules/loader-performance-optimization/utils.js +0 -10
  134. package/dist/rules/rules/module-mixed-chunks/index.js +0 -52
  135. package/dist/rules/rules/module-mixed-chunks/types.js +0 -1
  136. package/dist/rules/rules/side-effects-only-imports/index.js +0 -81
  137. package/dist/rules/rules/side-effects-only-imports/types.js +0 -1
  138. package/dist/rules/utils.js +0 -10
  139. package/dist/sdk/index.js +0 -3
  140. package/dist/sdk/multiple/controller.js +0 -42
  141. package/dist/sdk/multiple/index.js +0 -3
  142. package/dist/sdk/multiple/primary.js +0 -64
  143. package/dist/sdk/multiple/server.js +0 -14
  144. package/dist/sdk/sdk/core.js +0 -163
  145. package/dist/sdk/sdk/index.js +0 -435
  146. package/dist/sdk/sdk/types.js +0 -1
  147. package/dist/sdk/server/apis/alerts.js +0 -30
  148. package/dist/sdk/server/apis/base.js +0 -22
  149. package/dist/sdk/server/apis/bundle-diff.js +0 -51
  150. package/dist/sdk/server/apis/data.js +0 -44
  151. package/dist/sdk/server/apis/fs.js +0 -28
  152. package/dist/sdk/server/apis/graph.js +0 -116
  153. package/dist/sdk/server/apis/index.js +0 -11
  154. package/dist/sdk/server/apis/loader.js +0 -120
  155. package/dist/sdk/server/apis/plugin.js +0 -39
  156. package/dist/sdk/server/apis/project.js +0 -59
  157. package/dist/sdk/server/apis/renderer.js +0 -33
  158. package/dist/sdk/server/apis/resolver.js +0 -38
  159. package/dist/sdk/server/client.js +0 -8
  160. package/dist/sdk/server/fakeServer.js +0 -12
  161. package/dist/sdk/server/index.js +0 -292
  162. package/dist/sdk/server/json-body.js +0 -150
  163. package/dist/sdk/server/router.js +0 -83
  164. package/dist/sdk/server/security.js +0 -47
  165. package/dist/sdk/server/socket/api.js +0 -22
  166. package/dist/sdk/server/socket/index.js +0 -166
  167. package/dist/sdk/server/utils.js +0 -19
  168. package/dist/sdk/utils/base.js +0 -22
  169. package/dist/sdk/utils/constant.js +0 -4
  170. package/dist/sdk/utils/index.js +0 -4
  171. package/dist/sdk/utils/openBrowser.js +0 -53
  172. package/dist/sdk/utils/upload.js +0 -6
  173. package/dist/sdk.js +0 -2
  174. package/dist/types/index.js +0 -4
  175. package/dist/types/loader.js +0 -1
  176. package/dist/types/plugin.js +0 -1
  177. package/dist/types/rules.js +0 -1
package/dist/index.js CHANGED
@@ -1,7 +1,1908 @@
1
- import "node:module";
2
- import * as __rspack_external__inner_plugins_index_js_64c09f4a from "./inner-plugins/index.js";
3
- export * from "./build-utils/index.js";
4
- export * from "./types/index.js";
5
- export { RsdoctorRspackPlugin } from "./rspack-plugin/plugin.js";
6
- export { RsdoctorRspackMultiplePlugin } from "./rspack-plugin/multiple.js";
7
- export { __rspack_external__inner_plugins_index_js_64c09f4a as InnerPlugins };
1
+ import { createRequire as __rspack_createRequire } from "node:module";
2
+ import node_fs from "node:fs";
3
+ import fs_extra from "fs-extra";
4
+ import path_0 from "path";
5
+ import { createRequire } from "module";
6
+ import { Client, Constants, Manifest, SDK } from "@rsdoctor/shared/types";
7
+ import { SourceMapConsumer } from "source-map";
8
+ import { ChunkGraph, ModuleGraph, PackageGraph } from "@rsdoctor/shared/graph";
9
+ import sirv from "sirv";
10
+ import { Algorithm, Bundle, Data, Loader, Lodash, decycle } from "@rsdoctor/shared/common-browser";
11
+ import fs from "fs";
12
+ import os_0 from "os";
13
+ import assert from "assert";
14
+ import cors from "cors";
15
+ import { PassThrough } from "stream";
16
+ import ws, { WebSocketServer } from "ws";
17
+ import { isIP } from "node:net";
18
+ import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
19
+ import { exec } from "node:child_process";
20
+ import node_path, { join, dirname as __rspack_dirname } from "node:path";
21
+ import { promisify } from "node:util";
22
+ import { randomBytes } from "crypto";
23
+ import raw_body from "raw-body";
24
+ import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib";
25
+ import node_process from "node:process";
26
+ import { AsyncSeriesHook } from "@rspack/lite-tapable";
27
+ import { __webpack_require__ } from "./rslib-runtime.js";
28
+ import { setSDK, logger as rsdoctorLogger, logger_time, timeEnd, color, stringify, registerSDK } from "./630.js";
29
+ import { InternalResolverPlugin, getYarnVersion, InternalPluginsPlugin, getRspackNativePlugin, InternalSummaryPlugin, ensureModulesChunksGraphFn, getNpmVersion, InternalBundlePlugin, getNodeVersion, fs_extra as external_fs_extra_fs_extra, handleBriefModeReport, processCompilerConfig, InternalLoaderPlugin, getCPUInfo, defaultPort, getPnpmVersion, FileSharding, createServer, getMemoryInfo, normalizeRspackUserOptions, defaultHost, InternalErrorReporterPlugin, getPortSync, InternalRulesPlugin, DevToolError, ProbeLoaderPlugin } from "./26.js";
30
+ import { fileURLToPath as __rspack_fileURLToPath } from "node:url";
31
+ var date, __rspack_import_meta_dirname__ = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
32
+ let __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
33
+ __webpack_require__.add({
34
+ "launch-editor" (module) {
35
+ module.exports = __rspack_createRequire_require("launch-editor");
36
+ }
37
+ });
38
+ var apis_namespaceObject = {};
39
+ __webpack_require__.r(apis_namespaceObject), __webpack_require__.d(apis_namespaceObject, {
40
+ AlertsAPI: ()=>AlertsAPI,
41
+ BundleDiffAPI: ()=>BundleDiffAPI,
42
+ DataAPI: ()=>DataAPI,
43
+ FileSystemAPI: ()=>FileSystemAPI,
44
+ GraphAPI: ()=>GraphAPI,
45
+ LoaderAPI: ()=>LoaderAPI,
46
+ PluginAPI: ()=>PluginAPI,
47
+ ProjectAPI: ()=>ProjectAPI,
48
+ RendererAPI: ()=>RendererAPI,
49
+ ResolverAPI: ()=>ResolverAPI
50
+ });
51
+ class SocketAPILoader {
52
+ constructor(options){
53
+ this.options = options, this.dataLoader = new Data.APIDataLoader(this);
54
+ }
55
+ async loadManifest() {
56
+ return this.options.sdk.getManifestData();
57
+ }
58
+ async loadData(key) {
59
+ let data = this.options.sdk.getStoreData(), res = data[key];
60
+ return key.includes('.') && (res = key.split('.').reduce((t, k)=>t[k], data)), res;
61
+ }
62
+ get loadAPIData() {
63
+ return this.dataLoader.loadAPI;
64
+ }
65
+ }
66
+ let DEFAULT_ALLOWED_CORS_ORIGINS = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/, LOCAL_HOSTNAMES = /^(?:localhost|[^:]+\.localhost)$/;
67
+ function getHostnameFromHost(host) {
68
+ if (host.startsWith('[')) {
69
+ let endIndex = host.indexOf(']');
70
+ return -1 === endIndex ? '' : host.slice(1, endIndex);
71
+ }
72
+ return host.split(':')[0];
73
+ }
74
+ function isAllowedRequestHost(host) {
75
+ if ('string' != typeof host) return !1;
76
+ let hostname = getHostnameFromHost(host).toLowerCase();
77
+ return LOCAL_HOSTNAMES.test(hostname) || 0 !== isIP(hostname);
78
+ }
79
+ class Socket {
80
+ constructor(options){
81
+ this.options = options, this.clients = new Set(), this.map = new Map(), this.clientSubscriptions = new Map(), this.loader = new SocketAPILoader({
82
+ sdk: options.sdk
83
+ });
84
+ }
85
+ bootstrap() {
86
+ this.server = new WebSocketServer({
87
+ server: this.options.server,
88
+ verifyClient: ({ req })=>{
89
+ var url, token;
90
+ return isAllowedRequestHost(req.headers.host || req.headers[':authority']) && (url = req.url, token = this.options.token, !!url && new URL(url, 'http://localhost').searchParams.get('token') === token);
91
+ }
92
+ }), this.server.on('connection', (client)=>{
93
+ this.attachClient(client);
94
+ });
95
+ }
96
+ attachClient(client) {
97
+ this.clients.add(client), 'function' == typeof client.on && (client.on('message', (message)=>{
98
+ this.handleClientMessage(message.toString(), client);
99
+ }), client.on('close', ()=>{
100
+ this.clients.delete(client), this.removeClientSubscriptions(client);
101
+ }));
102
+ }
103
+ async handleClientMessage(raw, client) {
104
+ let message;
105
+ try {
106
+ message = JSON.parse(raw);
107
+ } catch {
108
+ return;
109
+ }
110
+ if (message.api && Object.values(SDK.ServerAPI.API).includes(message.api)) {
111
+ if ('request' === message.type) return void await this.handleAPIRequestMessage(message, client);
112
+ if ('subscribe' === message.type) return void this.saveRequestToMap(message.api, message.body ?? null, client);
113
+ 'unsubscribe' === message.type && this.removeRequestFromMap(message.api, message.body ?? null, client);
114
+ }
115
+ }
116
+ async handleAPIRequestMessage(message, client) {
117
+ if (message.id && client && client.readyState === ws.OPEN) try {
118
+ let response = await this.getAPIResponse(message.api, message.body);
119
+ client.send(JSON.stringify({
120
+ type: 'response',
121
+ id: message.id,
122
+ payload: response.res
123
+ }));
124
+ } catch (err) {
125
+ client.send(JSON.stringify({
126
+ type: 'response',
127
+ id: message.id,
128
+ error: err instanceof Error ? err.message : String(err)
129
+ }));
130
+ }
131
+ }
132
+ getSubscriptions() {
133
+ return [
134
+ ...this.map.values()
135
+ ].map(({ api, body })=>({
136
+ api,
137
+ body
138
+ }));
139
+ }
140
+ saveRequestToMap(api, body = null, client) {
141
+ let key = this.getSubscriptionKey(api, body);
142
+ if (client) {
143
+ this.clientSubscriptions.has(client) || this.clientSubscriptions.set(client, new Set());
144
+ let subscriptions = this.clientSubscriptions.get(client);
145
+ if (subscriptions.has(key)) return;
146
+ subscriptions.add(key);
147
+ }
148
+ let record = this.map.get(key);
149
+ if (record) {
150
+ record.count += 1;
151
+ return;
152
+ }
153
+ this.map.set(key, {
154
+ api,
155
+ body,
156
+ count: 1
157
+ });
158
+ }
159
+ removeRequestFromMap(api, body = null, client) {
160
+ let key = this.getSubscriptionKey(api, body);
161
+ if (client) {
162
+ let subscriptions = this.clientSubscriptions.get(client);
163
+ if (!subscriptions?.has(key)) return;
164
+ subscriptions.delete(key), 0 === subscriptions.size && this.clientSubscriptions.delete(client);
165
+ }
166
+ this.removeSubscriptionKey(key);
167
+ }
168
+ removeClientSubscriptions(client) {
169
+ let subscriptions = this.clientSubscriptions.get(client);
170
+ subscriptions && (subscriptions.forEach((key)=>this.removeSubscriptionKey(key)), this.clientSubscriptions.delete(client));
171
+ }
172
+ removeSubscriptionKey(key) {
173
+ let record = this.map.get(key);
174
+ record && (record.count -= 1, record.count <= 0 && this.map.delete(key));
175
+ }
176
+ getSubscriptionKey(api, body) {
177
+ return `${api}:${JSON.stringify(body ?? null)}`;
178
+ }
179
+ async getAPIResponse(api, body) {
180
+ let data = await this.loader.loadAPIData(api, body);
181
+ return {
182
+ req: {
183
+ api,
184
+ body
185
+ },
186
+ res: data
187
+ };
188
+ }
189
+ async broadcast() {
190
+ clearImmediate(this.timer), this.timer = setImmediate(async ()=>{
191
+ let promises = [];
192
+ this.map.forEach(({ api, body })=>{
193
+ promises.push((async ()=>{
194
+ let res = await this.getAPIResponse(api, body);
195
+ this.sendAPIData(api, res);
196
+ })());
197
+ }), await Promise.all(promises);
198
+ });
199
+ }
200
+ sendAPIData(api, payload) {
201
+ let message = JSON.stringify({
202
+ api,
203
+ payload
204
+ });
205
+ this.clients.forEach((client)=>{
206
+ client.readyState === ws.OPEN && client.send(message);
207
+ });
208
+ }
209
+ dispose() {
210
+ this.clients.forEach((client)=>{
211
+ client.close();
212
+ }), this.clients.clear(), this.server?.close();
213
+ }
214
+ }
215
+ let normalizeAPIKey = (key)=>key && 'object' == typeof key && 'name' in key ? key.name : key;
216
+ class Router {
217
+ static{
218
+ this.routes = {
219
+ get: new Map(),
220
+ post: new Map()
221
+ };
222
+ }
223
+ static get(pathname) {
224
+ return (target, propertyKey, descriptor)=>{
225
+ let routes = Router.routes.get, constructor = target.constructor;
226
+ return routes.has(constructor) || routes.set(constructor, []), routes.get(constructor).push([
227
+ normalizeAPIKey(propertyKey),
228
+ pathname
229
+ ]), descriptor;
230
+ };
231
+ }
232
+ static post(pathname) {
233
+ return (target, propertyKey, descriptor)=>{
234
+ let routes = Router.routes.post, constructor = target.constructor;
235
+ return routes.has(constructor) || routes.set(constructor, []), routes.get(constructor).push([
236
+ normalizeAPIKey(propertyKey),
237
+ pathname
238
+ ]), descriptor;
239
+ };
240
+ }
241
+ constructor(options){
242
+ this.options = options;
243
+ }
244
+ async setup() {
245
+ let { apis, sdk, server } = this.options;
246
+ apis.forEach((API)=>{
247
+ let obj = new API(sdk, server);
248
+ Router.routes.get.get(API)?.forEach(([key, pathname])=>{
249
+ server.get(pathname, this.wrapAPIFunction(obj, key));
250
+ }), Router.routes.post.get(API)?.forEach(([key, pathname])=>{
251
+ server.post(pathname, this.wrapAPIFunction(obj, key));
252
+ });
253
+ });
254
+ }
255
+ wrapAPIFunction(api, key) {
256
+ let { sdk, server } = this.options;
257
+ return async (req, res)=>{
258
+ let ctx = {
259
+ req,
260
+ res,
261
+ sdk,
262
+ server
263
+ }, trap = new Proxy(api, {
264
+ get: (target, key, receiver)=>'ctx' === key ? ctx : Reflect.get(target, key, receiver),
265
+ set: (target, key, value, receiver)=>Reflect.set(target, key, value, receiver),
266
+ defineProperty: (target, p, attrs)=>Reflect.defineProperty(target, p, attrs)
267
+ }), fn = api[key], result = await fn.call(trap, trap);
268
+ return 'string' == typeof result ? Buffer.from(result, 'utf-8') : result && 'object' == typeof result ? Buffer.from(JSON.stringify(result), 'utf-8') : result;
269
+ };
270
+ }
271
+ }
272
+ class BaseAPI {
273
+ constructor(sdk, server){
274
+ this.ctx = {
275
+ sdk,
276
+ server
277
+ }, this.dataLoader = new Data.APIDataLoader(this);
278
+ }
279
+ async loadManifest() {
280
+ return this.ctx.sdk.getManifestData();
281
+ }
282
+ async loadData(key) {
283
+ let data = this.ctx.sdk.getStoreData(), res = data[key];
284
+ return key.includes('.') && (res = key.split('.').reduce((t, k)=>t[k], data)), res;
285
+ }
286
+ }
287
+ function _ts_metadata(k, v) {
288
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
289
+ }
290
+ class AlertsAPI extends BaseAPI {
291
+ async getPackageRelationAlertDetails() {
292
+ let { req } = this.ctx, { id, target } = req.body;
293
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetPackageRelationAlertDetails, {
294
+ id,
295
+ target
296
+ });
297
+ }
298
+ }
299
+ function bundle_diff_ts_decorate(decorators, target, key, desc) {
300
+ var d, c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
301
+ if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
302
+ else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
303
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
304
+ }
305
+ function bundle_diff_ts_metadata(k, v) {
306
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
307
+ }
308
+ !function(decorators, target, key, desc) {
309
+ var d, c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
310
+ if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
311
+ else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
312
+ c > 3 && r && Object.defineProperty(target, key, r);
313
+ }([
314
+ Router.post(SDK.ServerAPI.API.GetPackageRelationAlertDetails),
315
+ _ts_metadata("design:type", Function),
316
+ _ts_metadata("design:paramtypes", []),
317
+ _ts_metadata("design:returntype", Promise)
318
+ ], AlertsAPI.prototype, "getPackageRelationAlertDetails", null);
319
+ class BundleDiffAPI extends BaseAPI {
320
+ async getBundleDiffSummary() {
321
+ let { sdk } = this.ctx, { root, hash, errors, chunkGraph, moduleGraph, packageGraph, configs, moduleCodeMap, cloudManifestUrl } = sdk.getStoreData(), outputFilename = '';
322
+ return 'string' == typeof configs?.[0]?.config?.output?.filename && (outputFilename = configs?.[0]?.config?.output?.filename), {
323
+ root,
324
+ hash,
325
+ errors,
326
+ chunkGraph,
327
+ moduleGraph,
328
+ packageGraph,
329
+ outputFilename,
330
+ moduleCodeMap,
331
+ cloudManifestUrl
332
+ };
333
+ }
334
+ async bundleDiffManifest() {
335
+ let { sdk } = this.ctx;
336
+ return sdk.getStoreData();
337
+ }
338
+ }
339
+ function data_ts_decorate(decorators, target, key, desc) {
340
+ var d, c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
341
+ if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
342
+ else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
343
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
344
+ }
345
+ function data_ts_metadata(k, v) {
346
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
347
+ }
348
+ bundle_diff_ts_decorate([
349
+ Router.get(SDK.ServerAPI.API.GetBundleDiffSummary),
350
+ Router.post(SDK.ServerAPI.API.GetBundleDiffSummary),
351
+ bundle_diff_ts_metadata("design:type", Function),
352
+ bundle_diff_ts_metadata("design:paramtypes", []),
353
+ bundle_diff_ts_metadata("design:returntype", Promise)
354
+ ], BundleDiffAPI.prototype, "getBundleDiffSummary", null), bundle_diff_ts_decorate([
355
+ Router.get(SDK.ServerAPI.API.BundleDiffManifest),
356
+ bundle_diff_ts_metadata("design:type", Function),
357
+ bundle_diff_ts_metadata("design:paramtypes", []),
358
+ bundle_diff_ts_metadata("design:returntype", Promise)
359
+ ], BundleDiffAPI.prototype, "bundleDiffManifest", null);
360
+ class DataAPI extends BaseAPI {
361
+ async loadDataByKey() {
362
+ let { req } = this.ctx, { url } = req, { key } = req.body;
363
+ return !key && url && (key = new URL(url, 'http://127.0.0.1').pathname.replace(/^\//, '')), await this.loadData(key);
364
+ }
365
+ async sendMessageToClient() {
366
+ let { req, server } = this.ctx, { api, data } = req.body;
367
+ await server.sendAPIDataToClient(api, data);
368
+ }
369
+ }
370
+ function fs_ts_metadata(k, v) {
371
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
372
+ }
373
+ data_ts_decorate([
374
+ Router.post(SDK.ServerAPI.API.LoadDataByKey),
375
+ data_ts_metadata("design:type", Function),
376
+ data_ts_metadata("design:paramtypes", []),
377
+ data_ts_metadata("design:returntype", Promise)
378
+ ], DataAPI.prototype, "loadDataByKey", null), data_ts_decorate([
379
+ Router.post(SDK.ServerAPI.API.SendAPIDataToClient),
380
+ data_ts_metadata("design:type", Function),
381
+ data_ts_metadata("design:paramtypes", []),
382
+ data_ts_metadata("design:returntype", Promise)
383
+ ], DataAPI.prototype, "sendMessageToClient", null);
384
+ class FileSystemAPI extends BaseAPI {
385
+ async applyErrorFix() {
386
+ let { body } = this.ctx.req;
387
+ return await this.ctx.sdk.applyErrorFix(body.id), 'success';
388
+ }
389
+ }
390
+ function loader_ts_decorate(decorators, target, key, desc) {
391
+ var d, c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
392
+ if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
393
+ else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
394
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
395
+ }
396
+ function loader_ts_metadata(k, v) {
397
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
398
+ }
399
+ !function(decorators, target, key, desc) {
400
+ var d, c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
401
+ if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
402
+ else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
403
+ c > 3 && r && Object.defineProperty(target, key, r);
404
+ }([
405
+ Router.post(SDK.ServerAPI.API.ApplyErrorFix),
406
+ fs_ts_metadata("design:type", Function),
407
+ fs_ts_metadata("design:paramtypes", []),
408
+ fs_ts_metadata("design:returntype", Promise)
409
+ ], FileSystemAPI.prototype, "applyErrorFix", null);
410
+ class LoaderAPI extends BaseAPI {
411
+ async reportLoader() {
412
+ let { req, sdk } = this.ctx, { body } = req;
413
+ return sdk.reportLoader(body), 'ok';
414
+ }
415
+ async reportSourceMap() {
416
+ let { req: { body }, sdk } = this.ctx;
417
+ return sdk.reportSourceMap(body), 'ok';
418
+ }
419
+ async getLoaderNames() {
420
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetLoaderNames);
421
+ }
422
+ async getLoaderChartData() {
423
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetLoaderChartData);
424
+ }
425
+ async getLoaderFileTree() {
426
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetLoaderFileTree);
427
+ }
428
+ async getLoaderFileDetails() {
429
+ let { req } = this.ctx, { path } = req.body;
430
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetLoaderFileDetails, {
431
+ path
432
+ });
433
+ }
434
+ async getLoaderFolderStatistics() {
435
+ let { req } = this.ctx, { folder } = req.body;
436
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetLoaderFolderStatistics, {
437
+ folder
438
+ });
439
+ }
440
+ async getLoaderFileFirstInput() {
441
+ let { req } = this.ctx, { file } = req.body;
442
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetLoaderFileFirstInput, {
443
+ file
444
+ });
445
+ }
446
+ async getLoaderFileInputAndOutput() {
447
+ let { req } = this.ctx, { file, loader, loaderIndex } = req.body;
448
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetLoaderFileInputAndOutput, {
449
+ file,
450
+ loader,
451
+ loaderIndex
452
+ });
453
+ }
454
+ }
455
+ function graph_ts_decorate(decorators, target, key, desc) {
456
+ var d, c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
457
+ if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
458
+ else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
459
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
460
+ }
461
+ function graph_ts_metadata(k, v) {
462
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
463
+ }
464
+ loader_ts_decorate([
465
+ Router.post(SDK.ServerAPI.API.ReportLoader),
466
+ loader_ts_metadata("design:type", Function),
467
+ loader_ts_metadata("design:paramtypes", []),
468
+ loader_ts_metadata("design:returntype", Promise)
469
+ ], LoaderAPI.prototype, "reportLoader", null), loader_ts_decorate([
470
+ Router.post(SDK.ServerAPI.API.ReportSourceMap),
471
+ loader_ts_metadata("design:type", Function),
472
+ loader_ts_metadata("design:paramtypes", []),
473
+ loader_ts_metadata("design:returntype", Promise)
474
+ ], LoaderAPI.prototype, "reportSourceMap", null), loader_ts_decorate([
475
+ Router.post(SDK.ServerAPI.API.GetLoaderNames),
476
+ loader_ts_metadata("design:type", Function),
477
+ loader_ts_metadata("design:paramtypes", []),
478
+ loader_ts_metadata("design:returntype", Promise)
479
+ ], LoaderAPI.prototype, "getLoaderNames", null), loader_ts_decorate([
480
+ Router.post(SDK.ServerAPI.API.GetLoaderChartData),
481
+ loader_ts_metadata("design:type", Function),
482
+ loader_ts_metadata("design:paramtypes", []),
483
+ loader_ts_metadata("design:returntype", Promise)
484
+ ], LoaderAPI.prototype, "getLoaderChartData", null), loader_ts_decorate([
485
+ Router.post(SDK.ServerAPI.API.GetLoaderFileTree),
486
+ loader_ts_metadata("design:type", Function),
487
+ loader_ts_metadata("design:paramtypes", []),
488
+ loader_ts_metadata("design:returntype", Promise)
489
+ ], LoaderAPI.prototype, "getLoaderFileTree", null), loader_ts_decorate([
490
+ Router.post(SDK.ServerAPI.API.GetLoaderFileDetails),
491
+ loader_ts_metadata("design:type", Function),
492
+ loader_ts_metadata("design:paramtypes", []),
493
+ loader_ts_metadata("design:returntype", Promise)
494
+ ], LoaderAPI.prototype, "getLoaderFileDetails", null), loader_ts_decorate([
495
+ Router.post(SDK.ServerAPI.API.GetLoaderFolderStatistics),
496
+ loader_ts_metadata("design:type", Function),
497
+ loader_ts_metadata("design:paramtypes", []),
498
+ loader_ts_metadata("design:returntype", Promise)
499
+ ], LoaderAPI.prototype, "getLoaderFolderStatistics", null), loader_ts_decorate([
500
+ Router.post(SDK.ServerAPI.API.GetLoaderFileFirstInput),
501
+ loader_ts_metadata("design:type", Function),
502
+ loader_ts_metadata("design:paramtypes", []),
503
+ loader_ts_metadata("design:returntype", Promise)
504
+ ], LoaderAPI.prototype, "getLoaderFileFirstInput", null), loader_ts_decorate([
505
+ Router.post(SDK.ServerAPI.API.GetLoaderFileInputAndOutput),
506
+ loader_ts_metadata("design:type", Function),
507
+ loader_ts_metadata("design:paramtypes", []),
508
+ loader_ts_metadata("design:returntype", Promise)
509
+ ], LoaderAPI.prototype, "getLoaderFileInputAndOutput", null);
510
+ class GraphAPI extends BaseAPI {
511
+ async getAssetsSummary() {
512
+ let { req } = this.ctx, { withFileContent } = req.body;
513
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetAssetsSummary, {
514
+ withFileContent
515
+ });
516
+ }
517
+ async getModuleGraphForAsset() {
518
+ let { req } = this.ctx, { assetPath } = req.body;
519
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetAssetDetails, {
520
+ assetPath
521
+ });
522
+ }
523
+ async getChunksByModuleId() {
524
+ let { req } = this.ctx, { moduleId } = req.body;
525
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetChunksByModuleId, {
526
+ moduleId
527
+ });
528
+ }
529
+ async getModuleDetails() {
530
+ let { req } = this.ctx, { moduleId } = req.body;
531
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetModuleDetails, {
532
+ moduleId
533
+ });
534
+ }
535
+ async getDependencyByResolvedRequest() {
536
+ let { req } = this.ctx, { moduleIds = [] } = req.body;
537
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetModulesByModuleIds, {
538
+ moduleIds
539
+ });
540
+ }
541
+ async getModuleCodeByModuleId() {
542
+ let { req } = this.ctx, { moduleId } = req.body;
543
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetModuleCodeByModuleId, {
544
+ moduleId
545
+ });
546
+ }
547
+ async getModuleCodeByModuleIds() {
548
+ let { req } = this.ctx, { moduleIds } = req.body;
549
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetModuleCodeByModuleIds, {
550
+ moduleIds
551
+ });
552
+ }
553
+ async getEntryModulesSummary() {
554
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetEntryPoints);
555
+ }
556
+ }
557
+ function plugin_ts_decorate(decorators, target, key, desc) {
558
+ var d, c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
559
+ if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
560
+ else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
561
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
562
+ }
563
+ function plugin_ts_metadata(k, v) {
564
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
565
+ }
566
+ graph_ts_decorate([
567
+ Router.post(SDK.ServerAPI.API.GetAssetsSummary),
568
+ graph_ts_metadata("design:type", Function),
569
+ graph_ts_metadata("design:paramtypes", []),
570
+ graph_ts_metadata("design:returntype", Promise)
571
+ ], GraphAPI.prototype, "getAssetsSummary", null), graph_ts_decorate([
572
+ Router.post(SDK.ServerAPI.API.GetAssetDetails),
573
+ graph_ts_metadata("design:type", Function),
574
+ graph_ts_metadata("design:paramtypes", []),
575
+ graph_ts_metadata("design:returntype", Promise)
576
+ ], GraphAPI.prototype, "getModuleGraphForAsset", null), graph_ts_decorate([
577
+ Router.post(SDK.ServerAPI.API.GetChunksByModuleId),
578
+ graph_ts_metadata("design:type", Function),
579
+ graph_ts_metadata("design:paramtypes", []),
580
+ graph_ts_metadata("design:returntype", Promise)
581
+ ], GraphAPI.prototype, "getChunksByModuleId", null), graph_ts_decorate([
582
+ Router.post(SDK.ServerAPI.API.GetModuleDetails),
583
+ graph_ts_metadata("design:type", Function),
584
+ graph_ts_metadata("design:paramtypes", []),
585
+ graph_ts_metadata("design:returntype", Promise)
586
+ ], GraphAPI.prototype, "getModuleDetails", null), graph_ts_decorate([
587
+ Router.post(SDK.ServerAPI.API.GetModulesByModuleIds),
588
+ graph_ts_metadata("design:type", Function),
589
+ graph_ts_metadata("design:paramtypes", []),
590
+ graph_ts_metadata("design:returntype", Promise)
591
+ ], GraphAPI.prototype, "getDependencyByResolvedRequest", null), graph_ts_decorate([
592
+ Router.post(SDK.ServerAPI.API.GetModuleCodeByModuleId),
593
+ graph_ts_metadata("design:type", Function),
594
+ graph_ts_metadata("design:paramtypes", []),
595
+ graph_ts_metadata("design:returntype", Promise)
596
+ ], GraphAPI.prototype, "getModuleCodeByModuleId", null), graph_ts_decorate([
597
+ Router.post(SDK.ServerAPI.API.GetModuleCodeByModuleIds),
598
+ graph_ts_metadata("design:type", Function),
599
+ graph_ts_metadata("design:paramtypes", []),
600
+ graph_ts_metadata("design:returntype", Promise)
601
+ ], GraphAPI.prototype, "getModuleCodeByModuleIds", null), graph_ts_decorate([
602
+ Router.post(SDK.ServerAPI.API.GetEntryPoints),
603
+ graph_ts_metadata("design:type", Function),
604
+ graph_ts_metadata("design:paramtypes", []),
605
+ graph_ts_metadata("design:returntype", Promise)
606
+ ], GraphAPI.prototype, "getEntryModulesSummary", null);
607
+ class PluginAPI extends BaseAPI {
608
+ async getPluginSummary() {
609
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetPluginSummary);
610
+ }
611
+ async getPluginData() {
612
+ let { req } = this.ctx, { hooks = [], tapNames = [] } = req.body;
613
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetPluginData, {
614
+ hooks,
615
+ tapNames
616
+ });
617
+ }
618
+ }
619
+ function project_ts_decorate(decorators, target, key, desc) {
620
+ var d, c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
621
+ if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
622
+ else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
623
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
624
+ }
625
+ function project_ts_metadata(k, v) {
626
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
627
+ }
628
+ plugin_ts_decorate([
629
+ Router.post(SDK.ServerAPI.API.GetPluginSummary),
630
+ plugin_ts_metadata("design:type", Function),
631
+ plugin_ts_metadata("design:paramtypes", []),
632
+ plugin_ts_metadata("design:returntype", Promise)
633
+ ], PluginAPI.prototype, "getPluginSummary", null), plugin_ts_decorate([
634
+ Router.post(SDK.ServerAPI.API.GetPluginData),
635
+ plugin_ts_metadata("design:type", Function),
636
+ plugin_ts_metadata("design:paramtypes", []),
637
+ plugin_ts_metadata("design:returntype", Promise)
638
+ ], PluginAPI.prototype, "getPluginData", null);
639
+ class ProjectAPI extends BaseAPI {
640
+ async env() {
641
+ let { server } = this.ctx;
642
+ return {
643
+ ip: function() {
644
+ for (let iface of Object.values(os_0.networkInterfaces()))for (let alias of iface)if ('IPv4' === alias.family && !alias.internal) return alias.address;
645
+ return '127.0.0.1';
646
+ }(),
647
+ port: server.port
648
+ };
649
+ }
650
+ async manifest() {
651
+ let { sdk } = this.ctx;
652
+ return JSON.stringify(sdk.getManifestData());
653
+ }
654
+ async getProjectInfo() {
655
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetProjectInfo);
656
+ }
657
+ async getClientRoutes() {
658
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetClientRoutes);
659
+ }
660
+ }
661
+ function renderer_ts_metadata(k, v) {
662
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
663
+ }
664
+ project_ts_decorate([
665
+ Router.get(SDK.ServerAPI.API.Env),
666
+ project_ts_metadata("design:type", Function),
667
+ project_ts_metadata("design:paramtypes", []),
668
+ project_ts_metadata("design:returntype", Promise)
669
+ ], ProjectAPI.prototype, "env", null), project_ts_decorate([
670
+ Router.get(SDK.ServerAPI.API.Manifest),
671
+ project_ts_metadata("design:type", Function),
672
+ project_ts_metadata("design:paramtypes", []),
673
+ project_ts_metadata("design:returntype", Promise)
674
+ ], ProjectAPI.prototype, "manifest", null), project_ts_decorate([
675
+ Router.post(SDK.ServerAPI.API.GetProjectInfo),
676
+ project_ts_metadata("design:type", Function),
677
+ project_ts_metadata("design:paramtypes", []),
678
+ project_ts_metadata("design:returntype", Promise)
679
+ ], ProjectAPI.prototype, "getProjectInfo", null), project_ts_decorate([
680
+ Router.post(SDK.ServerAPI.API.GetClientRoutes),
681
+ project_ts_metadata("design:type", Function),
682
+ project_ts_metadata("design:paramtypes", []),
683
+ project_ts_metadata("design:returntype", Promise)
684
+ ], ProjectAPI.prototype, "getClientRoutes", null);
685
+ let renderer_require = createRequire(import.meta.url);
686
+ class RendererAPI extends BaseAPI {
687
+ async entryHtml() {
688
+ let { server, res } = this.ctx, clientHtmlPath = server.innerClientPath ? server.innerClientPath : renderer_require.resolve('@rsdoctor/client'), clientHtml = node_fs.readFileSync(clientHtmlPath, 'utf-8');
689
+ return res.setHeader('Content-Type', 'text/html'), res.setHeader('Cache-Control', 'no-store'), clientHtml;
690
+ }
691
+ }
692
+ function resolver_ts_decorate(decorators, target, key, desc) {
693
+ var d, c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
694
+ if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
695
+ else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
696
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
697
+ }
698
+ function resolver_ts_metadata(k, v) {
699
+ if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
700
+ }
701
+ !function(decorators, target, key, desc) {
702
+ var d, c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
703
+ if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
704
+ else for(var i = decorators.length - 1; i >= 0; i--)(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
705
+ c > 3 && r && Object.defineProperty(target, key, r);
706
+ }([
707
+ Router.get(SDK.ServerAPI.API.EntryHtml),
708
+ renderer_ts_metadata("design:type", Function),
709
+ renderer_ts_metadata("design:paramtypes", []),
710
+ renderer_ts_metadata("design:returntype", Promise)
711
+ ], RendererAPI.prototype, "entryHtml", null);
712
+ class ResolverAPI extends BaseAPI {
713
+ async getResolverFileTree() {
714
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetResolverFileTree);
715
+ }
716
+ async getResolverFileDetails() {
717
+ let { req } = this.ctx, { filepath } = req.body;
718
+ return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetResolverFileDetails, {
719
+ filepath
720
+ });
721
+ }
722
+ }
723
+ resolver_ts_decorate([
724
+ Router.post(SDK.ServerAPI.API.GetResolverFileTree),
725
+ resolver_ts_metadata("design:type", Function),
726
+ resolver_ts_metadata("design:paramtypes", []),
727
+ resolver_ts_metadata("design:returntype", Promise)
728
+ ], ResolverAPI.prototype, "getResolverFileTree", null), resolver_ts_decorate([
729
+ Router.post(SDK.ServerAPI.API.GetResolverFileDetails),
730
+ resolver_ts_metadata("design:type", Function),
731
+ resolver_ts_metadata("design:paramtypes", []),
732
+ resolver_ts_metadata("design:returntype", Promise)
733
+ ], ResolverAPI.prototype, "getResolverFileDetails", null);
734
+ let execAsync = promisify(exec), supportedChromiumBrowsers = [
735
+ 'Google Chrome Canary',
736
+ 'Google Chrome Dev',
737
+ 'Google Chrome Beta',
738
+ 'Google Chrome',
739
+ 'Microsoft Edge',
740
+ 'Brave Browser',
741
+ 'Vivaldi',
742
+ 'Chromium'
743
+ ], getTargetBrowser = async ()=>{
744
+ let targetBrowser = process.env.BROWSER;
745
+ if (!targetBrowser || !supportedChromiumBrowsers.includes(targetBrowser)) {
746
+ let { stdout: ps } = await execAsync('ps cax');
747
+ targetBrowser = supportedChromiumBrowsers.find((b)=>ps.includes(b));
748
+ }
749
+ return targetBrowser;
750
+ }, openWithDefaultBrowser = async (url)=>{
751
+ try {
752
+ let { default: open } = await import("open");
753
+ return await open(url), !0;
754
+ } catch (err) {
755
+ return rsdoctorLogger.error('Failed to open Rsdoctor URL.'), rsdoctorLogger.error(err), !1;
756
+ }
757
+ };
758
+ async function openBrowser(url, needEncodeURI = !0) {
759
+ if ('darwin' === process.platform) try {
760
+ let targetBrowser = await getTargetBrowser();
761
+ if (targetBrowser) return await execAsync(`osascript openChrome.applescript "${needEncodeURI ? encodeURI(url) : url}" "${targetBrowser}"`, {
762
+ cwd: join(__rspack_import_meta_dirname__, '../static')
763
+ }), !0;
764
+ rsdoctorLogger.debug('Failed to find the target browser.');
765
+ } catch (err) {
766
+ rsdoctorLogger.debug("Failed to open Rsdoctor URL with apple script."), rsdoctorLogger.debug(err);
767
+ }
768
+ return openWithDefaultBrowser(url);
769
+ }
770
+ function createHttpError(status, message, type) {
771
+ return Object.assign(Error(message), {
772
+ status,
773
+ statusCode: status,
774
+ type
775
+ });
776
+ }
777
+ function getContentType(req) {
778
+ let contentType = req.headers['content-type'];
779
+ if ('string' == typeof contentType) return contentType;
780
+ }
781
+ function normalizeReadError(error, charset) {
782
+ return error instanceof Error && 'status' in error && 'number' == typeof error.status ? charset && 'type' in error && 'encoding.unsupported' === error.type ? createHttpError(415, `unsupported charset "${charset.toUpperCase()}"`, 'charset.unsupported') : error : createHttpError(400, error instanceof Error ? error.message : 'failed to read request body', 'request.invalid');
783
+ }
784
+ let server_require = createRequire(import.meta.url), OPEN_IN_EDITOR_EDITORS = new Set(SDK.OPEN_IN_EDITOR_EDITORS), LARGE_JSON_BODY_ROUTES = new Set([
785
+ SDK.ServerAPI.API.ReportLoader,
786
+ SDK.ServerAPI.API.ReportSourceMap
787
+ ]);
788
+ class RsdoctorServer {
789
+ constructor(sdk, port = defaultPort, config){
790
+ this.sdk = sdk, this.disposed = !0, this._socketToken = randomBytes(16).toString('hex'), this.get = (route, cb)=>{
791
+ let { app } = this;
792
+ return app.use(route, this.wrapNextHandleFunction('GET', cb)), app;
793
+ }, this.post = (route, cb)=>{
794
+ let { app } = this;
795
+ return app.use(route, this.wrapNextHandleFunction('POST', cb)), app;
796
+ }, this.dispose = async (exitCode)=>{
797
+ if (this.disposed) {
798
+ void 0 !== exitCode && process.exit(exitCode);
799
+ return;
800
+ }
801
+ this.disposed = !0, this._server && await this._server.close(), this._socket && this._socket.dispose(), void 0 !== exitCode && process.exit(exitCode);
802
+ }, assert('number' == typeof port), this.port = port, this._router = new Router({
803
+ sdk,
804
+ server: this,
805
+ apis: Object.values(apis_namespaceObject)
806
+ }), this._innerClientPath = config?.innerClientPath || '', this._printServerUrl = config?.printServerUrl ?? !0, this._cors = config?.cors;
807
+ }
808
+ get app() {
809
+ return this._server.app;
810
+ }
811
+ get host() {
812
+ return defaultHost;
813
+ }
814
+ get origin() {
815
+ return `http://${this.host}:${this.port}`;
816
+ }
817
+ get socketUrl() {
818
+ return {
819
+ port: this.port,
820
+ socketUrl: `ws://localhost:${this.port}?token=${this._socketToken}`,
821
+ token: this._socketToken
822
+ };
823
+ }
824
+ get innerClientPath() {
825
+ return this._innerClientPath;
826
+ }
827
+ async createInnerServer() {
828
+ let lastError, expectedPort = this.port;
829
+ for(let retry = 0; retry < 10; retry++){
830
+ let port = getPortSync(expectedPort, this.host);
831
+ try {
832
+ return {
833
+ port,
834
+ server: await createServer(port, this.host)
835
+ };
836
+ } catch (error) {
837
+ if ('EADDRINUSE' !== error.code) throw error;
838
+ lastError = error, expectedPort = port + 1;
839
+ }
840
+ }
841
+ throw lastError;
842
+ }
843
+ resolveCorsOptions() {
844
+ return !1 !== this._cors && (!0 === this._cors ? {} : void 0 === this._cors ? {
845
+ origin: DEFAULT_ALLOWED_CORS_ORIGINS
846
+ } : {
847
+ ...this._cors,
848
+ origin: void 0 === this._cors.origin ? DEFAULT_ALLOWED_CORS_ORIGINS : this._cors.origin
849
+ });
850
+ }
851
+ async bootstrap() {
852
+ if (!this.disposed) return;
853
+ let { port, server } = await this.createInnerServer(), corsOptions = this.resolveCorsOptions();
854
+ this.port = port, this._server = server, this._socket = new Socket({
855
+ sdk: this.sdk,
856
+ server: this._server.server,
857
+ port: this.port,
858
+ token: this._socketToken
859
+ }), await this._socket.bootstrap(), function(port, builderName) {
860
+ let homeDir = os_0.homedir(), rsdoctorDir = path_0.join(homeDir, '.cache/rsdoctor'), mcpPortFilePath = path_0.join(rsdoctorDir, 'mcp.json');
861
+ fs.existsSync(rsdoctorDir) || fs.mkdirSync(rsdoctorDir, {
862
+ recursive: !0
863
+ });
864
+ let mcpJson = {
865
+ portList: {},
866
+ port: 0
867
+ };
868
+ if (fs.existsSync(mcpPortFilePath)) try {
869
+ mcpJson = JSON.parse(fs.readFileSync(mcpPortFilePath, 'utf8'));
870
+ } catch (error) {
871
+ rsdoctorLogger.debug('Failed to parse mcp.json', error);
872
+ }
873
+ mcpJson.portList || (mcpJson.portList = {}), mcpJson.portList[builderName || 'builder'] = port, mcpJson.port = port, fs.writeFileSync(mcpPortFilePath, JSON.stringify(mcpJson, null, 2), 'utf8');
874
+ }(this.port, this.sdk.name), rsdoctorLogger.debug(`Successfully wrote mcp.json for ${color.cyan(this.sdk.name)} builder`), this.disposed = !1, this.app.use((req, res, next)=>{
875
+ if (!isAllowedRequestHost(req.headers.host || req.headers[':authority'])) {
876
+ res.statusCode = 403, res.end();
877
+ return;
878
+ }
879
+ next();
880
+ }), !1 !== corsOptions && corsOptions.origin === DEFAULT_ALLOWED_CORS_ORIGINS && this.app.use((req, res, next)=>{
881
+ let host = req.headers.host || req.headers[':authority'];
882
+ if (!function(origin, host) {
883
+ if (void 0 === origin) return !0;
884
+ if ('string' != typeof origin || 'string' != typeof host || !(void 0 === origin || 'string' == typeof origin && DEFAULT_ALLOWED_CORS_ORIGINS.test(origin))) return !1;
885
+ let originHostname = function(origin) {
886
+ try {
887
+ let hostname = new URL(origin).hostname.toLowerCase();
888
+ return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;
889
+ } catch {
890
+ return '';
891
+ }
892
+ }(origin), hostHostname = getHostnameFromHost(host).toLowerCase();
893
+ return !originHostname.endsWith('.localhost') || originHostname === hostHostname;
894
+ }(req.headers.origin, host)) {
895
+ res.statusCode = 403, res.end();
896
+ return;
897
+ }
898
+ next();
899
+ }), !1 !== corsOptions && this.app.use(cors(corsOptions)), this.app.use(function(options = {}) {
900
+ return (req, _res, next)=>{
901
+ let content, limit, contentType, contentType1, match;
902
+ if ('body' in req || (req.body = void 0), !(void 0 !== req.headers['transfer-encoding'] || !Number.isNaN(Number(req.headers['content-length']))) || !(contentType = getContentType(req)) || 'application/json' !== contentType.split(';', 1)[0].trim().toLowerCase()) return void next();
903
+ let charset = (contentType1 = getContentType(req), match = contentType1?.match(/(?:^|;)\s*charset\s*=\s*(?:"([^"]+)"|([^;\s]+))/i), (match?.[1] || match?.[2] || 'utf-8').toLowerCase());
904
+ if (!charset.startsWith('utf-')) {
905
+ req.resume(), next(createHttpError(415, `unsupported charset "${charset.toUpperCase()}"`, 'charset.unsupported'));
906
+ return;
907
+ }
908
+ try {
909
+ content = function(req) {
910
+ let stream, contentEncoding = req.headers['content-encoding'], encoding = 'string' == typeof contentEncoding ? contentEncoding.toLowerCase() : 'identity';
911
+ if ('identity' === encoding) return {
912
+ stream: req,
913
+ length: req.headers['content-length']
914
+ };
915
+ switch(encoding){
916
+ case 'gzip':
917
+ stream = createGunzip();
918
+ break;
919
+ case 'deflate':
920
+ stream = createInflate();
921
+ break;
922
+ case 'br':
923
+ stream = createBrotliDecompress();
924
+ break;
925
+ default:
926
+ throw createHttpError(415, `unsupported content encoding "${encoding}"`, 'encoding.unsupported');
927
+ }
928
+ let cleanup = ()=>{
929
+ req.removeListener('aborted', onAborted), req.removeListener('close', onClose), req.removeListener('error', onError), stream.removeListener('close', cleanup);
930
+ }, destroy = (error)=>{
931
+ stream.destroyed || stream.destroy(error);
932
+ }, onAborted = ()=>{
933
+ destroy(createHttpError(400, 'request aborted', 'request.aborted'));
934
+ }, onClose = ()=>{
935
+ !1 === req.complete && onAborted();
936
+ }, onError = (error)=>{
937
+ destroy(error);
938
+ };
939
+ return req.once('aborted', onAborted), req.once('close', onClose), req.once('error', onError), stream.once('close', cleanup), req.pipe(stream), {
940
+ stream,
941
+ cleanup,
942
+ decompressor: stream
943
+ };
944
+ }(req);
945
+ } catch (error) {
946
+ req.resume(), next(normalizeReadError(error));
947
+ return;
948
+ }
949
+ let handleError = (error)=>{
950
+ content.cleanup?.(), content.decompressor && (req.unpipe(content.decompressor), content.decompressor.destroy()), req.resume(), next(normalizeReadError(error, charset));
951
+ };
952
+ try {
953
+ limit = 'function' == typeof options.limit ? options.limit(req) : options.limit;
954
+ } catch (error) {
955
+ handleError(error);
956
+ return;
957
+ }
958
+ raw_body(content.stream, {
959
+ encoding: charset,
960
+ length: content.length,
961
+ limit
962
+ }).then((body)=>{
963
+ try {
964
+ req.body = function(body) {
965
+ let value;
966
+ if (0 === body.length) return {};
967
+ try {
968
+ value = JSON.parse(body);
969
+ } catch (error) {
970
+ throw createHttpError(400, error.message, 'entity.parse.failed');
971
+ }
972
+ if (null === value || 'object' != typeof value) throw createHttpError(400, 'JSON body must be an object or array', 'entity.parse.failed');
973
+ return value;
974
+ }(body);
975
+ } catch (error) {
976
+ handleError(error);
977
+ return;
978
+ }
979
+ content.cleanup?.(), next();
980
+ }, handleError);
981
+ };
982
+ }({
983
+ limit: (req)=>{
984
+ let pathname = new URL(req.url || '/', 'http://localhost').pathname;
985
+ return LARGE_JSON_BODY_ROUTES.has(pathname) ? '500mb' : '10mb';
986
+ }
987
+ })), await this._router.setup();
988
+ let clientHtmlPath = this._innerClientPath ? this._innerClientPath : server_require.resolve('@rsdoctor/client'), clientDistPath = path_0.resolve(clientHtmlPath, '..');
989
+ this.app.use(sirv(clientDistPath, {
990
+ dev: !0
991
+ })), this.app.use('/__open-in-editor', (req, res, next)=>{
992
+ if ('GET' !== req.method && 'HEAD' !== req.method) return next();
993
+ let url = new URL(req.url || '', "http://localhost"), file = url.searchParams.get('file'), editor = url.searchParams.get('editor');
994
+ if (!function(token, expectedToken) {
995
+ if ('string' != typeof token || !expectedToken) return !1;
996
+ let tokenBuffer = Buffer.from(token), expectedTokenBuffer = Buffer.from(expectedToken);
997
+ return tokenBuffer.length === expectedTokenBuffer.length && timingSafeEqual(tokenBuffer, expectedTokenBuffer);
998
+ }(url.searchParams.get('token'), this._socketToken)) {
999
+ res.statusCode = 403, res.end();
1000
+ return;
1001
+ }
1002
+ if (!file) {
1003
+ res.statusCode = 400, res.end('Missing file parameter');
1004
+ return;
1005
+ }
1006
+ if (!('string' == typeof editor && OPEN_IN_EDITOR_EDITORS.has(editor))) {
1007
+ res.statusCode = 400, res.end('Unsupported editor parameter');
1008
+ return;
1009
+ }
1010
+ try {
1011
+ let launch = __webpack_require__("launch-editor"), responded = !1, safeEnd = (code, body)=>{
1012
+ responded || (responded = !0, res.statusCode = code, res.end(body));
1013
+ };
1014
+ launch(file, editor, (_fileName, errorMessage)=>{
1015
+ errorMessage && safeEnd(500, errorMessage);
1016
+ }), setTimeout(()=>{
1017
+ safeEnd(200, '');
1018
+ }, 200);
1019
+ } catch (err) {
1020
+ res.writableEnded || (res.statusCode = 500, res.end(err.message));
1021
+ }
1022
+ }), process.once('exit', ()=>this.dispose()), process.once('SIGINT', ()=>this.dispose(0)), process.once('SIGTERM', ()=>this.dispose(0)), process.once('unhandledRejection', (reason)=>{
1023
+ console.error('Unhandled promise rejection:', reason), this.dispose(1);
1024
+ }), process.once('uncaughtException', (err, origin)=>{
1025
+ console.error('Uncaught exception:', err), origin && console.error('Exception origin:', origin), this.dispose(1);
1026
+ });
1027
+ }
1028
+ wrapNextHandleFunction(method, cb) {
1029
+ return async (req, res, next)=>{
1030
+ if (req.method?.toUpperCase() === method) {
1031
+ try {
1032
+ let body = await cb(req, res, next);
1033
+ if (res.statusCode = 200, Buffer.isBuffer(body)) {
1034
+ res.setHeader('Content-Length', body.byteLength);
1035
+ let ps = new PassThrough();
1036
+ ps.write(body), ps.end(), ps.pipe(res);
1037
+ } else body && 'object' == typeof body ? (res.writeHead(200, {
1038
+ 'Content-Type': 'application/json;utf-8'
1039
+ }), res.write(JSON.stringify(body)), res.end()) : res.writeHead(200).end(body);
1040
+ } catch (error) {
1041
+ return res.statusCode = 500, res.end(error.message), next(error);
1042
+ }
1043
+ return;
1044
+ }
1045
+ await next();
1046
+ };
1047
+ }
1048
+ proxy(api, method, cb) {
1049
+ let idx = this.app.stack.findIndex((e)=>e.route === api);
1050
+ -1 === idx && (idx = this.app.stack.length - 1), this.app.stack.splice(idx, 0, {
1051
+ route: api,
1052
+ handle: this.wrapNextHandleFunction(method, cb)
1053
+ });
1054
+ }
1055
+ getClientUrl(route = 'homepage', ...args) {
1056
+ let relativeUrl = SDK.ServerAPI.API.EntryHtml;
1057
+ if (route !== Client.RsdoctorClientRoutes.BundleDiff) return relativeUrl;
1058
+ {
1059
+ let [baseline, current] = args, qs = Bundle.getBundleDiffPageQueryString([
1060
+ baseline,
1061
+ current
1062
+ ]);
1063
+ return `${relativeUrl}${qs}#${Client.RsdoctorClientRoutes.BundleDiff}`;
1064
+ }
1065
+ }
1066
+ async openClientPage(...args) {
1067
+ let relativeUrl = this.getClientUrl(...args), needEncodeURI = args[0] === Client.RsdoctorClientRoutes.BundleDiff, url = `http://${this.host}:${this.port}${relativeUrl}`, localhostUrl = `http://localhost:${this.port}${relativeUrl}`;
1068
+ await openBrowser(localhostUrl, !needEncodeURI), this._printServerUrl && rsdoctorLogger.info(`${color.green(`${this.sdk.name} compiler's`)} analyzer running on: ${color.cyan(url)}`);
1069
+ }
1070
+ sendAPIDataToClient(api, msg) {
1071
+ this._socket?.sendAPIData(api, msg);
1072
+ }
1073
+ async broadcast() {
1074
+ await this._socket?.broadcast();
1075
+ }
1076
+ }
1077
+ class RsdoctorFakeServer extends RsdoctorServer {
1078
+ constructor(sdk, port = defaultPort){
1079
+ super(sdk, port), this.sdk = sdk, this.dispose = async ()=>{}, this.sdk = sdk;
1080
+ }
1081
+ async bootstrap() {}
1082
+ async openClientPage() {}
1083
+ }
1084
+ function findRoot(startDir = process.cwd()) {
1085
+ let dir = startDir, firstPkgDir = null;
1086
+ for(; dir !== path_0.parse(dir).root;){
1087
+ if (fs.existsSync(path_0.join(dir, 'pnpm-workspace.yaml')) || fs.existsSync(path_0.join(dir, 'yarn.lock')) || fs.existsSync(path_0.join(dir, 'lerna.json'))) return dir;
1088
+ let pkgPath = path_0.join(dir, 'package.json');
1089
+ if (fs.existsSync(pkgPath) && (firstPkgDir || (firstPkgDir = dir), JSON.parse(fs.readFileSync(pkgPath, 'utf8')).workspaces)) return dir;
1090
+ dir = path_0.dirname(dir);
1091
+ }
1092
+ return firstPkgDir || null;
1093
+ }
1094
+ String((date = new Date()).getMonth() + 1).padStart(2, '0'), String(date.getDate()).padStart(2, '0'), date.getFullYear();
1095
+ class SDKCore {
1096
+ constructor({ name, root }){
1097
+ this.hooks = {
1098
+ afterSaveManifest: new AsyncSeriesHook([
1099
+ 'result'
1100
+ ])
1101
+ }, this._envinfo = {}, this._clientRoutes = new Set([
1102
+ Manifest.RsdoctorManifestClientRoutes.Overall
1103
+ ]), this.diskManifestPath = '', this._name = name, this.root = root, this.pid = node_process.pid, this._outputDir = node_path.join(this.outputDir || this.root, Constants.RsdoctorOutputFolder);
1104
+ }
1105
+ get outputDir() {
1106
+ return this._outputDir;
1107
+ }
1108
+ get name() {
1109
+ return this._name;
1110
+ }
1111
+ async bootstrap() {
1112
+ let [cpu, memory, nodeVersion, yarnVersion, npmVersion, pnpmVersion] = await Promise.all([
1113
+ getCPUInfo(),
1114
+ getMemoryInfo(),
1115
+ getNodeVersion(),
1116
+ getYarnVersion(),
1117
+ getNpmVersion(),
1118
+ getPnpmVersion()
1119
+ ]);
1120
+ this._envinfo = {
1121
+ ...this._envinfo,
1122
+ cpu,
1123
+ memory,
1124
+ nodeVersion,
1125
+ yarnVersion,
1126
+ npmVersion,
1127
+ pnpmVersion
1128
+ };
1129
+ let hash = createHash('md5').update([
1130
+ this.name,
1131
+ this.root,
1132
+ JSON.stringify(this._envinfo),
1133
+ Date.now()
1134
+ ].join('_')).digest('hex');
1135
+ this.setHash(hash);
1136
+ }
1137
+ async dispose() {}
1138
+ setOutputDir(outputDir) {
1139
+ this._outputDir = outputDir;
1140
+ }
1141
+ setName(name) {
1142
+ this._name = name;
1143
+ }
1144
+ setHash(hash) {
1145
+ this.hash = hash;
1146
+ }
1147
+ getHash() {
1148
+ return this.hash;
1149
+ }
1150
+ getClientRoutes() {
1151
+ return [
1152
+ ...this._clientRoutes
1153
+ ];
1154
+ }
1155
+ addClientRoutes(routes) {
1156
+ routes.forEach((route)=>{
1157
+ this._clientRoutes.add(route);
1158
+ }), this.onDataReport();
1159
+ }
1160
+ async writePieces(storeData, _options) {
1161
+ let { outputDir } = this, manifest = node_path.resolve(outputDir, Constants.RsdoctorOutputManifest);
1162
+ this.diskManifestPath = manifest, await external_fs_extra_fs_extra.ensureDir(outputDir);
1163
+ let urlsPromiseList = [];
1164
+ for (let key of Object.keys(storeData)){
1165
+ let data = storeData[key];
1166
+ if ('object' != typeof data) {
1167
+ urlsPromiseList.push({
1168
+ name: key,
1169
+ files: data
1170
+ });
1171
+ continue;
1172
+ }
1173
+ let jsonStr = await (async ()=>{
1174
+ try {
1175
+ if ('configs' === key) return JSON.stringify(decycle(data));
1176
+ return JSON.stringify(data);
1177
+ } catch {
1178
+ return stringify(data);
1179
+ }
1180
+ })();
1181
+ if (Array.isArray(jsonStr)) {
1182
+ let fileOffset = 0;
1183
+ for (let str of jsonStr){
1184
+ let result = await this.writeToFolder(str, outputDir, key, fileOffset);
1185
+ fileOffset += result.files.length, urlsPromiseList.push(result);
1186
+ }
1187
+ } else urlsPromiseList.push(this.writeToFolder(jsonStr, outputDir, key));
1188
+ }
1189
+ let dataUrls = await Promise.all(urlsPromiseList);
1190
+ rsdoctorLogger.debug(`SDKCore.writePieces extraConfig: ${JSON.stringify(this.extraConfig)}`, '[SDKCore.writePieces]'), this.cloudData = {
1191
+ client: {
1192
+ enableRoutes: this.getClientRoutes()
1193
+ },
1194
+ data: dataUrls.reduce((t, item)=>(t[item.name] = Array.isArray(item.files) ? item.files.map((e)=>e.path).concat(t[item.name] || []) : item.files, t), {})
1195
+ };
1196
+ }
1197
+ async writeManifest() {
1198
+ let { cloudData: data, diskManifestPath } = this, dataStr = JSON.stringify(data, null, 2);
1199
+ rsdoctorLogger.debug(`SDKCore.writeManifest extraConfig: ${this.extraConfig}`, '[SDKCore.writeManifest]');
1200
+ let dir = node_path.dirname(diskManifestPath), base = node_path.basename(diskManifestPath), tmpPath = node_path.join(dir, `${base}.${Date.now()}.${randomUUID()}.tmp`);
1201
+ return await external_fs_extra_fs_extra.outputFile(tmpPath, dataStr), node_fs.renameSync(tmpPath, diskManifestPath), diskManifestPath;
1202
+ }
1203
+ async saveManifest(data, options) {
1204
+ await this.writePieces(data, options);
1205
+ let manifestDiskPath = await this.writeManifest();
1206
+ return await this.hooks.afterSaveManifest.promise({
1207
+ manifestWithShardingFiles: this.cloudData,
1208
+ manifestDiskPath
1209
+ }), manifestDiskPath;
1210
+ }
1211
+ writeToFolder(jsonStr, dir, key, index) {
1212
+ let sharding = new FileSharding(Algorithm.compressText(jsonStr)), folder = node_path.resolve(dir, key);
1213
+ return sharding.writeStringToFolder(folder, '', index).then((item)=>({
1214
+ name: key,
1215
+ files: item.map((el)=>({
1216
+ path: node_path.resolve(folder, el.filename),
1217
+ basename: el.filename,
1218
+ content: el.content
1219
+ }))
1220
+ }));
1221
+ }
1222
+ }
1223
+ let client_require = createRequire(import.meta.url), resolveClientDiffHtmlPath = (innerClientPath)=>{
1224
+ let innerClientPath1;
1225
+ return path_0.resolve((innerClientPath1 = innerClientPath, path_0.dirname(innerClientPath1 || client_require.resolve('@rsdoctor/client'))), 'diff.html');
1226
+ }, sdk_require = createRequire(import.meta.url);
1227
+ class RsdoctorSDK extends SDKCore {
1228
+ constructor(options){
1229
+ super(options), this._summary = {
1230
+ costs: []
1231
+ }, this._configs = [], this._errors = [], this._loader = [], this._loaderStart = [], this._resolver = [], this._plugin = {}, this._moduleGraph = new ModuleGraph(), this._chunkGraph = new ChunkGraph(), this._rawSourceMapCache = new Map(), this._sourceMap = new Map();
1232
+ let serverConfig = options.config?.server, port = serverConfig?.port ?? options.port;
1233
+ this.server = options.config?.noServer ? new RsdoctorFakeServer(this, port) : new RsdoctorServer(this, port, {
1234
+ innerClientPath: options.config?.innerClientPath || '',
1235
+ printServerUrl: options.config?.printLog?.serverUrls,
1236
+ cors: serverConfig?.cors
1237
+ }), this.type = Lodash.isNumber(options.type) ? options.type : SDK.ToDataType.Normal, this.extraConfig = options.config, this.root = findRoot() ?? '';
1238
+ }
1239
+ async bootstrap() {
1240
+ rsdoctorLogger.debug(`${Date.now()}`, '[RsdoctorSDK][bootstrap start]'), this.server && await this.server.bootstrap(), await super.bootstrap(), rsdoctorLogger.debug(`${Date.now()} ${this.server.origin}`, '[RsdoctorSDK][bootstrap end]');
1241
+ }
1242
+ async dispose() {
1243
+ rsdoctorLogger.debug(`${Date.now()}`, '[RsdoctorSDK][dispose start]'), this.server && await this.server.dispose(), await super.dispose(), rsdoctorLogger.debug(`${Date.now()}`, '[RsdoctorSDK][dispose end]');
1244
+ }
1245
+ async applyErrorFix(id) {
1246
+ let { _errors: errors } = this, error = errors.find((err)=>err.id === id);
1247
+ if (!error || !error.path || !error.fixData || error.fixData.isFixed) return;
1248
+ let { path: filePath, fixData } = error, sameFileErrors = errors.filter((item)=>item.path === filePath && item !== error), content = (await node_fs.promises.readFile(filePath, 'utf-8')).toString(), startTxt = content.substring(0, fixData.start), endTxt = content.substring(fixData.end, content.length), offset = (fixData.newText ?? '').length - (fixData.end - fixData.start);
1249
+ for (let other of (content = startTxt + fixData.newText + endTxt, sameFileErrors)){
1250
+ let { fixData: otherFixData } = other;
1251
+ otherFixData && otherFixData.start >= fixData.end && (otherFixData.start += offset, otherFixData.end += offset);
1252
+ }
1253
+ await node_fs.promises.writeFile(filePath, content);
1254
+ }
1255
+ clear() {
1256
+ this._errors = [], this._loader = [], this._resolver = [], this._plugin = {}, this._moduleGraph = new ModuleGraph(), this._chunkGraph = new ChunkGraph();
1257
+ }
1258
+ clearSourceMapCache() {
1259
+ this._rawSourceMapCache = new Map(), this._sourceMap = new Map();
1260
+ }
1261
+ async getSourceMap(file) {
1262
+ let { _sourceMap: sourceMap, _rawSourceMapCache: rawMap } = this;
1263
+ if (sourceMap.has(file)) return sourceMap.get(file);
1264
+ let rawData = rawMap.get(file);
1265
+ if (!rawData || rawData.version < 0 || !rawData.sourcesContent?.[0] || !rawData.mappings) return Promise.resolve(void 0);
1266
+ try {
1267
+ let result = await new SourceMapConsumer(rawData);
1268
+ return sourceMap.set(file, result), result;
1269
+ } catch {
1270
+ return Promise.resolve(void 0);
1271
+ }
1272
+ }
1273
+ reportSourceMap(data) {
1274
+ this._rawSourceMapCache.set(data.file, data);
1275
+ }
1276
+ reportConfiguration(config) {
1277
+ config.root ??= this.root, this._configs.push(config), this.onDataReport();
1278
+ }
1279
+ reportError(errors) {
1280
+ errors.forEach((item)=>{
1281
+ this._errors.push(DevToolError.from(item, {
1282
+ code: this.name
1283
+ }));
1284
+ }), this.onDataReport();
1285
+ }
1286
+ reportLoader(data) {
1287
+ data.forEach((item)=>{
1288
+ this.extraConfig?.mode === SDK.IMode[SDK.IMode.brief] && item.loaders.forEach((_loader)=>{
1289
+ _loader.input = void 0, _loader.result = void 0;
1290
+ });
1291
+ let match = this._loader.find((e)=>e.resource.path === item.resource.path);
1292
+ match ? match.loaders.push(...item.loaders) : (match = item, this._loader.push(item)), match.loaders.sort((a, b)=>a.startAt !== b.startAt ? a.startAt - b.startAt : a.isPitch ? b.isPitch ? a.loaderIndex - b.loaderIndex : -1 : b.isPitch ? 1 : b.loaderIndex - a.loaderIndex);
1293
+ }), this.onDataReport();
1294
+ }
1295
+ reportLoaderStartOrEnd(data) {
1296
+ let _builtinLoader = data.loaders[0];
1297
+ if (_builtinLoader.startAt) this._loaderStart.push(data);
1298
+ else if (_builtinLoader.endAt) {
1299
+ let matchLoaderStart = this._loaderStart.find((e)=>e.resource.path === data.resource.path && e.loaders[0].loader === _builtinLoader.loader);
1300
+ matchLoaderStart && (matchLoaderStart.loaders[0].result = _builtinLoader.result, matchLoaderStart.loaders[0].endAt = _builtinLoader.endAt, this.reportLoader([
1301
+ matchLoaderStart
1302
+ ]));
1303
+ }
1304
+ }
1305
+ reportResolver(data) {
1306
+ data.forEach((item)=>this._resolver.push(item)), this.onDataReport();
1307
+ }
1308
+ reportPlugin(data) {
1309
+ Object.keys(data).forEach((hook)=>{
1310
+ this._plugin[hook] ? data[hook].forEach((item)=>{
1311
+ this._plugin[hook].push(item || void 0);
1312
+ }) : this._plugin[hook] = data[hook];
1313
+ }), this.onDataReport();
1314
+ }
1315
+ reportModuleGraph(data) {
1316
+ rsdoctorLogger.debug(`data size: ${data.size()}`, '[SDK.reportModuleGraph][start]'), this._moduleGraph.fromInstance(data), this.createPackageGraph(), this.onDataReport(), rsdoctorLogger.debug(`sdk._moduleGraph size: ${this._moduleGraph.size()}`, '[SDK reportModuleGraph][end]');
1317
+ }
1318
+ reportPackageGraph(data) {
1319
+ rsdoctorLogger.debug('[SDK.reportPackageGraph][start]'), this._packageGraph || (this._packageGraph = data), this.onDataReport(), rsdoctorLogger.debug(`sdk._packageGraph size: ${this._packageGraph.getPackages().length}`, '[SDK reportPackageGraph][end]');
1320
+ }
1321
+ reportChunkGraph(data) {
1322
+ this._chunkGraph.addAsset(...data.getAssets()), this._chunkGraph.addChunk(...data.getChunks()), this._chunkGraph.addEntryPoint(...data.getEntryPoints()), this.onDataReport();
1323
+ }
1324
+ reportSummaryData(part) {
1325
+ for (let key of [
1326
+ 'costs'
1327
+ ]){
1328
+ let v = part[key];
1329
+ v && ('object' == typeof v ? Array.isArray(v) ? this._summary[key] = [
1330
+ ...this._summary[key] || [],
1331
+ ...v
1332
+ ] : this._summary[key] = {
1333
+ ...this._summary[key] || {},
1334
+ ...v
1335
+ } : this._summary[key] = v);
1336
+ }
1337
+ this.onDataReport();
1338
+ }
1339
+ createPackageGraph() {
1340
+ if (rsdoctorLogger.debug(`sdk._moduleGraph size: ${this._moduleGraph.size()}`, '[SDK.createPackageGraph][start]'), !this._packageGraph) {
1341
+ let pkgGraph = PackageGraph.fromModuleGraph(this._moduleGraph, this.root, (path)=>{
1342
+ try {
1343
+ if (node_fs.existsSync(path)) return fs_extra.readJsonSync(path);
1344
+ } catch (error) {
1345
+ let { message, stack } = error;
1346
+ rsdoctorLogger.debug(()=>`sdk.createPackageGraph error, path: ${path}, error message: ${stack || message}`, '[SDK.createPackageGraph][error]');
1347
+ }
1348
+ });
1349
+ this._packageGraph = pkgGraph, rsdoctorLogger.debug(`sdk._packageGraph packages: ${this._packageGraph.getPackages().length}`, '[SDK.createPackageGraph][end]');
1350
+ }
1351
+ }
1352
+ async writeStore(options) {
1353
+ rsdoctorLogger.debug("sdk.writeStore has run.", '[SDK.writeStore][end]');
1354
+ let htmlPath = '';
1355
+ if (this.extraConfig?.mode === SDK.IMode[SDK.IMode.brief]) {
1356
+ let clientHtmlPath = this.extraConfig.innerClientPath ? this.extraConfig.innerClientPath : sdk_require.resolve('@rsdoctor/client');
1357
+ if (this.extraConfig?.brief?.type?.includes('json')) {
1358
+ let data = this.getStoreData(), clientRoutes = this.getClientRoutes();
1359
+ node_fs.mkdirSync(this.outputDir, {
1360
+ recursive: !0
1361
+ }), node_fs.writeFileSync(path_0.resolve(this.outputDir, this.extraConfig.brief.jsonOptions?.fileName ?? 'rsdoctor-data.json'), JSON.stringify({
1362
+ data,
1363
+ clientRoutes
1364
+ }));
1365
+ }
1366
+ return this.extraConfig.brief?.type?.includes('html') && (htmlPath = this.inlineScriptsAndStyles(clientHtmlPath)), htmlPath;
1367
+ }
1368
+ return this.saveManifest(this.getStoreData(), options || {});
1369
+ }
1370
+ getStoreData() {
1371
+ let ctx = this, briefOptions = this.extraConfig?.brief, sections = briefOptions?.jsonOptions?.sections, isJsonType = briefOptions?.type?.includes('json');
1372
+ return {
1373
+ get hash () {
1374
+ return ctx.hash;
1375
+ },
1376
+ get root () {
1377
+ return ctx.root;
1378
+ },
1379
+ get envinfo () {
1380
+ return ctx._envinfo;
1381
+ },
1382
+ get pid () {
1383
+ return ctx.pid;
1384
+ },
1385
+ get errors () {
1386
+ if (isJsonType && sections && !sections.rules) return [];
1387
+ return ctx._errors.map((err)=>err.toData());
1388
+ },
1389
+ get configs () {
1390
+ return ctx._configs.slice();
1391
+ },
1392
+ get summary () {
1393
+ return {
1394
+ ...ctx._summary
1395
+ };
1396
+ },
1397
+ get resolver () {
1398
+ return ctx._resolver.slice();
1399
+ },
1400
+ get loader () {
1401
+ return ctx._loader.slice();
1402
+ },
1403
+ get moduleGraph () {
1404
+ if (isJsonType && sections && !sections.moduleGraph) return {
1405
+ dependencies: [],
1406
+ modules: [],
1407
+ moduleGraphModules: [],
1408
+ exports: [],
1409
+ sideEffects: [],
1410
+ variables: [],
1411
+ layers: []
1412
+ };
1413
+ return ctx._moduleGraph.toData({
1414
+ contextPath: ctx._configs?.[0]?.config?.context || '',
1415
+ briefOptions
1416
+ });
1417
+ },
1418
+ get chunkGraph () {
1419
+ if (isJsonType && sections && !sections.chunkGraph) return {
1420
+ assets: [],
1421
+ chunks: [],
1422
+ entrypoints: []
1423
+ };
1424
+ return ctx._chunkGraph.toData(ctx.type);
1425
+ },
1426
+ get moduleCodeMap () {
1427
+ if (ctx.extraConfig?.mode === SDK.IMode[SDK.IMode.brief]) return {};
1428
+ return ctx._moduleGraph.toCodeData(ctx.type);
1429
+ },
1430
+ get plugin () {
1431
+ return {
1432
+ ...ctx._plugin
1433
+ };
1434
+ },
1435
+ get packageGraph () {
1436
+ return ctx._packageGraph ? ctx._packageGraph.toData() : {
1437
+ packages: [],
1438
+ dependencies: []
1439
+ };
1440
+ },
1441
+ get treeShaking () {
1442
+ if (ctx.extraConfig?.mode === SDK.IMode[SDK.IMode.brief] || !ctx.extraConfig?.features?.treeShaking) return;
1443
+ return ctx._moduleGraph.toTreeShakingData();
1444
+ },
1445
+ get otherReports () {
1446
+ return {
1447
+ treemapReportHtml: ''
1448
+ };
1449
+ }
1450
+ };
1451
+ }
1452
+ getManifestData() {
1453
+ let dataValue = this.getStoreData();
1454
+ return {
1455
+ client: {
1456
+ enableRoutes: this.getClientRoutes()
1457
+ },
1458
+ data: Object.keys(dataValue).reduce((t, e)=>(dataValue[e] && 'object' == typeof dataValue[e] ? t[e] = [
1459
+ `${this.server.origin}${SDK.ServerAPI.API.LoadDataByKey}/${e}`
1460
+ ] : t[e] = dataValue[e], t), {}),
1461
+ __LOCAL__SERVER__: !0,
1462
+ __SOCKET__PORT__: this.server.socketUrl.port.toString(),
1463
+ __SOCKET__URL__: this.server.socketUrl.socketUrl
1464
+ };
1465
+ }
1466
+ getRuleContext(_options) {
1467
+ return this.createPackageGraph(), {
1468
+ root: this.root,
1469
+ errors: this._errors.slice(),
1470
+ configs: this._configs.slice(),
1471
+ moduleGraph: this._moduleGraph,
1472
+ chunkGraph: this._chunkGraph,
1473
+ packageGraph: this._packageGraph,
1474
+ loader: this._loader.slice(),
1475
+ otherReports: {
1476
+ treemapReportHtml: ''
1477
+ }
1478
+ };
1479
+ }
1480
+ onDataReport() {
1481
+ this.server.broadcast();
1482
+ }
1483
+ addRsdoctorDataToHTML(storeData, htmlContent) {
1484
+ let compressTextScripts = `<script>window.${Constants.WINDOW_RSDOCTOR_TAG}={}</script>`;
1485
+ for (let key of Object.keys(storeData)){
1486
+ let data = storeData[key], jsonStrFn = ()=>{
1487
+ try {
1488
+ if ('configs' === key) return JSON.stringify(decycle(data));
1489
+ return JSON.stringify(data);
1490
+ } catch (error) {
1491
+ return console.error(error), '';
1492
+ }
1493
+ }, compressText = Algorithm.compressText(jsonStrFn());
1494
+ compressTextScripts = `${compressTextScripts} <script>window.${Constants.WINDOW_RSDOCTOR_TAG}.${key}=${JSON.stringify(compressText)}</script>`;
1495
+ }
1496
+ return compressTextScripts = `${compressTextScripts} <script>window.${Constants.WINDOW_RSDOCTOR_TAG}.enableRoutes=${JSON.stringify(this.getClientRoutes())}</script>`, htmlContent = htmlContent.replace('<body>', `<body>${compressTextScripts}`);
1497
+ }
1498
+ inlineScriptsAndStyles(htmlFilePath) {
1499
+ function resolveFilePath(basePath, filePath) {
1500
+ return filePath.startsWith('/') ? path_0.resolve(basePath, filePath.slice(1)) : path_0.resolve(basePath, filePath);
1501
+ }
1502
+ let htmlContent = node_fs.readFileSync(htmlFilePath, 'utf-8'), basePath = path_0.dirname(htmlFilePath), scriptSrcs = Array.from(htmlContent.matchAll(/<script\s+(?:defer="defer"|defer)\s+src=["'](.+?)["']><\/script>/g), (m)=>m[1]), cssHrefs = Array.from(htmlContent.matchAll(/<link\s+href=["'](.+?)["']\s+rel="stylesheet">/g), (m)=>m[1]);
1503
+ htmlContent = (htmlContent = htmlContent.replace(/<script\s+.*?src=["'].*?["']><\/script>/g, '')).replace(/<link\s+.*?rel=["']stylesheet["'].*?>/g, '');
1504
+ let inlinedScripts = scriptSrcs.map((src)=>{
1505
+ let scriptPath = resolveFilePath(basePath, src);
1506
+ try {
1507
+ let scriptContent = node_fs.readFileSync(scriptPath, 'utf-8');
1508
+ return `<script>${scriptContent}</script>`;
1509
+ } catch (error) {
1510
+ return console.error(`Could not read script at ${scriptPath}:`, error), '';
1511
+ }
1512
+ }).join(''), inlinedCss = cssHrefs.map((href)=>{
1513
+ let cssPath = resolveFilePath(basePath, href);
1514
+ try {
1515
+ let cssContent = node_fs.readFileSync(cssPath, 'utf-8');
1516
+ return `<style>${cssContent}</style>`;
1517
+ } catch (error) {
1518
+ return console.error(`Could not read CSS at ${cssPath}:`, error), '';
1519
+ }
1520
+ }).join(''), index = htmlContent.indexOf('</body>');
1521
+ htmlContent = htmlContent.slice(0, index) + inlinedCss + inlinedScripts + htmlContent.slice(index), htmlContent = this.addRsdoctorDataToHTML(this.getStoreData(), htmlContent);
1522
+ let outputFilePath = path_0.resolve(this.outputDir, this.extraConfig?.brief?.htmlOptions?.reportHtmlName || 'rsdoctor-report.html');
1523
+ return node_fs.mkdirSync(path_0.dirname(outputFilePath), {
1524
+ recursive: !0
1525
+ }), node_fs.writeFileSync(outputFilePath, htmlContent, {
1526
+ encoding: 'utf-8',
1527
+ flag: 'w'
1528
+ }), outputFilePath;
1529
+ }
1530
+ }
1531
+ class RsdoctorSlaveServer extends RsdoctorServer {
1532
+ constructor(sdk, port = defaultPort, config){
1533
+ super(sdk, port, config), this.sdk = sdk;
1534
+ }
1535
+ async openClientPage(...args) {
1536
+ return this.sdk.isMaster ? super.openClientPage(...args) : Promise.resolve();
1537
+ }
1538
+ }
1539
+ let primary_id = 1;
1540
+ class RsdoctorPrimarySDK extends RsdoctorSDK {
1541
+ constructor({ name, displayName, compilerPath, parentCompilerPath, isChild, stage, controller, extraConfig, type }){
1542
+ super({
1543
+ name,
1544
+ root: controller.root,
1545
+ config: extraConfig
1546
+ }), this.reportFileName = '';
1547
+ let lastSdk = controller.getLastSdk(), port = lastSdk ? lastSdk.server.port + 1 : extraConfig?.server?.port ?? this.server.port;
1548
+ this.id = primary_id++, this.stage = 'number' == typeof stage ? stage : 1, this.displayName = displayName || name, this.compilerPath = compilerPath || '', this.parentCompilerPath = parentCompilerPath, this.isChild = !!isChild, this.extraConfig = extraConfig, this.parent = controller, lastSdk && (this.server = new RsdoctorSlaveServer(this, port, {
1549
+ cors: extraConfig?.server?.cors
1550
+ })), this.type = type, this.setName(name);
1551
+ }
1552
+ get isMaster() {
1553
+ return this.parent.master === this;
1554
+ }
1555
+ async writePieces() {
1556
+ this.setOutputDir(this.parent.getCompilerOutputDir(this)), await super.writePieces(this.getStoreData());
1557
+ }
1558
+ async writeManifest() {
1559
+ let { parent, cloudData } = this;
1560
+ cloudData && parent.isMultiple && (cloudData.name = this.name, cloudData.series = parent.getSeriesData());
1561
+ let result = await super.writeManifest();
1562
+ return await parent.refreshManifestSeries(), result;
1563
+ }
1564
+ async refreshManifestSeries() {
1565
+ this.parent.isMultiple && this.cloudData && this.diskManifestPath && (this.cloudData.name = this.name, this.cloudData.series = this.parent.getSeriesData(), await super.writeManifest());
1566
+ }
1567
+ getSeriesData(serverUrl = !1) {
1568
+ return this.parent.getSeriesData(serverUrl);
1569
+ }
1570
+ setName(name) {
1571
+ let baseName = name || `compiler-${this.id}`;
1572
+ if (!this.parent.hasName(baseName, this)) {
1573
+ this._name = baseName;
1574
+ return;
1575
+ }
1576
+ let suffix = 2;
1577
+ for(; this.parent.hasName(`${baseName}-${suffix}`, this);)suffix += 1;
1578
+ this._name = `${baseName}-${suffix}`;
1579
+ }
1580
+ getManifestData() {
1581
+ let data = super.getManifestData();
1582
+ return this.parent.isMultiple && (data.name = this.name, data.series = this.getSeriesData(!0)), data;
1583
+ }
1584
+ addRsdoctorDataToHTML(storeData, htmlContent) {
1585
+ let result = super.addRsdoctorDataToHTML(storeData, htmlContent);
1586
+ if (!this.parent.isMultiple) return result;
1587
+ let metadata = `<script>window.${Constants.WINDOW_RSDOCTOR_TAG}.name=${JSON.stringify(this.name)};window.${Constants.WINDOW_RSDOCTOR_TAG}.series=${JSON.stringify(this.parent.getBriefSeriesData(this))}</script>`;
1588
+ return result.replace('</body>', `${metadata}</body>`);
1589
+ }
1590
+ }
1591
+ class RsdoctorSDKController {
1592
+ constructor(root = process.cwd()){
1593
+ this.slaves = [], this.activeSlaves = new Set(), this.outputDir = '', this.refreshManifestTask = Promise.resolve(), this.root = '', this.root = root;
1594
+ }
1595
+ get master() {
1596
+ return this.getActiveSlaves()[0];
1597
+ }
1598
+ get isMultiple() {
1599
+ return this.activeSlaves.size > 1;
1600
+ }
1601
+ getLastSdk() {
1602
+ return this.slaves[this.slaves.length - 1];
1603
+ }
1604
+ hasName(name, exclude) {
1605
+ return !!this.slaves.find((item)=>item !== exclude && item.name === name);
1606
+ }
1607
+ registerSlave(slave) {
1608
+ this.activeSlaves.add(slave);
1609
+ }
1610
+ setOutputDir(slave, outputDir) {
1611
+ slave === this.master && slave !== this.outputOwner && (this.outputDir = outputDir, this.outputOwner = slave, slave.setOutputDir(outputDir));
1612
+ }
1613
+ getCompilerOutputDir(slave) {
1614
+ if (slave === this.master) return this.outputDir || slave.outputDir;
1615
+ let rootOutputDir = this.outputDir || this.master?.outputDir || slave.outputDir;
1616
+ if (slave.isChild) return node_path.join(rootOutputDir, '.slaves', slave.name.replace(/\s+/g, '-'));
1617
+ let name = slave.name.replace(/[^a-zA-Z0-9_$-]+/g, '-').replace(/^-+|-+$/g, '') || `compiler-${slave.id}`;
1618
+ return node_path.join(rootOutputDir, 'compilers', name);
1619
+ }
1620
+ getSeriesData(serverUrl = !1) {
1621
+ return this.getActiveSlaves().map((item)=>{
1622
+ let data = {
1623
+ name: item.name,
1624
+ displayName: item.displayName,
1625
+ path: item.reportFileName ? node_path.join(this.getCompilerOutputDir(item), item.reportFileName) : item.diskManifestPath || node_path.resolve(this.getCompilerOutputDir(item), Constants.RsdoctorOutputManifest),
1626
+ stage: item.stage,
1627
+ compilerPath: item.compilerPath,
1628
+ parentCompilerPath: item.parentCompilerPath,
1629
+ isChild: item.isChild
1630
+ };
1631
+ return serverUrl && (data.origin = item.server.origin), data;
1632
+ });
1633
+ }
1634
+ getBriefSeriesData(current) {
1635
+ let currentOutputDir = this.getCompilerOutputDir(current);
1636
+ return this.getActiveSlaves().map((item)=>({
1637
+ name: item.name,
1638
+ path: node_path.relative(currentOutputDir, node_path.join(this.getCompilerOutputDir(item), item.reportFileName || 'rsdoctor-report.html')).split(node_path.sep).map((segment)=>encodeURIComponent(segment)).join('/'),
1639
+ stage: item.stage
1640
+ }));
1641
+ }
1642
+ createSlave({ name, displayName, compilerPath, parentCompilerPath, isChild, stage, extraConfig, type }) {
1643
+ let slave = new RsdoctorPrimarySDK({
1644
+ name,
1645
+ displayName,
1646
+ compilerPath,
1647
+ parentCompilerPath,
1648
+ isChild,
1649
+ stage: 'number' == typeof stage ? stage : this.slaves.length,
1650
+ controller: this,
1651
+ extraConfig,
1652
+ type
1653
+ });
1654
+ return this.slaves.push(slave), this.slaves.sort((a, b)=>a.stage - b.stage), slave;
1655
+ }
1656
+ refreshManifestSeries() {
1657
+ return this.isMultiple ? (this.refreshManifestTask = this.refreshManifestTask.then(async ()=>{
1658
+ for (let slave of this.getActiveSlaves())await slave.refreshManifestSeries();
1659
+ }), this.refreshManifestTask) : Promise.resolve();
1660
+ }
1661
+ getActiveSlaves() {
1662
+ return this.slaves.filter((item)=>this.activeSlaves.has(item));
1663
+ }
1664
+ }
1665
+ var package_namespaceObject = JSON.parse('{"name":"@rsdoctor/core","version":"2.0.0-beta.0","repository":{"type":"git","url":"https://github.com/web-infra-dev/rsdoctor","directory":"packages/core"},"license":"MIT","engines":{"node":">=22.18.0"},"main":"dist/index.js","types":"dist/index.d.ts","files":["dist","static"],"type":"module","exports":{".":{"types":"./dist/index.d.ts","default":"./dist/index.js"},"./proxy-loader":{"types":"./dist/proxy-loader.d.ts","default":"./dist/proxy-loader.js"}},"typesVersions":{"*":{".":["./dist/index.d.ts"],"proxy-loader":["./dist/proxy-loader.d.ts"]}},"scripts":{"dev":"npm run start","build":"rslib build","start":"rslib build -w","test":"rstest run"},"dependencies":{"@babel/code-frame":"7.26.2","@rspack/lite-tapable":"catalog:","@rsdoctor/shared":"workspace:*","@types/estree":"catalog:","acorn":"^8.10.0","acorn-import-attributes":"^1.9.5","acorn-walk":"8.3.5","browserslist-load-config":"^1.0.3","caniuse-lite":"^1.0.30001809","connect-next":"catalog:","envinfo":"7.21.0","fs-extra":"catalog:","get-port":"5.1.1","lines-and-columns":"2.0.4","open":"^11.0.0","raw-body":"3.0.2","rslog":"^2.1.3","semver":"^7.8.5","source-map":"catalog:","@rsdoctor/client":"workspace:*","cors":"2.8.6","launch-editor":"^2.14.1","sirv":"catalog:","ws":"8.21.3"},"devDependencies":{"@rsbuild/plugin-check-syntax":"catalog:","@rspack/core":"catalog:","@scripts/test-helper":"workspace:*","@types/babel__code-frame":"7.27.0","@types/envinfo":"7.8.4","@types/fs-extra":"catalog:","@types/node":"catalog:","@types/semver":"^7.8.0","babel-loader":"10.1.1","filesize":"catalog:","json-stream-stringify":"3.0.1","string-loader":"0.0.1","ts-loader":"^9.6.2","tslib":"catalog:","typescript":"catalog:","@types/cors":"2.8.19","@types/ws":"^8.18.1"},"peerDependencies":{"@rspack/core":"^2.0.0"},"peerDependenciesMeta":{"@rspack/core":{"optional":true}},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"}}');
1666
+ let pluginTapName = 'RsdoctorRspackPlugin', pluginTapPostOptions = {
1667
+ name: pluginTapName,
1668
+ stage: 999
1669
+ }, pendingSessions = new Map(), hasGreeted = !1;
1670
+ class RsdoctorCompilerContext {
1671
+ constructor(sdk, options){
1672
+ this.sdk = sdk, this.options = options, this.name = pluginTapName, this.isRsdoctorPlugin = !0, this.modulesGraph = new ModuleGraph(), this.applied = !1;
1673
+ }
1674
+ apply() {}
1675
+ ensureModulesChunksGraphApplied(compiler) {
1676
+ ensureModulesChunksGraphFn(compiler, this);
1677
+ }
1678
+ }
1679
+ class RsdoctorRspackPlugin {
1680
+ constructor(options){
1681
+ if (this.name = pluginTapName, this.isRsdoctorPlugin = !0, this.compilerContexts = new WeakMap(), this.childPlugins = new Map(), this.appliedCompilerCount = 0, this.afterPlugins = (compiler, context = this.getCompilerContext(compiler))=>{
1682
+ logger_time('RsdoctorRspackPlugin.afterPlugins');
1683
+ try {
1684
+ this.getRspackConfig(compiler, context);
1685
+ } finally{
1686
+ timeEnd('RsdoctorRspackPlugin.afterPlugins');
1687
+ }
1688
+ }, this.done = async (compiler, context = this.getCompilerContext(compiler))=>{
1689
+ logger_time('RsdoctorRspackPlugin.done');
1690
+ try {
1691
+ rsdoctorLogger.debug('[RsdoctorRspackPlugin] bootstrap(start) in done()'), await context.bootstrapTask, rsdoctorLogger.debug('[RsdoctorRspackPlugin] bootstrap(end) in done()'), context.sdk.addClientRoutes([
1692
+ Manifest.RsdoctorManifestClientRoutes.Overall
1693
+ ]), context.sdk instanceof RsdoctorPrimarySDK ? context.sdk.setOutputDir(context.sdk.parent.getCompilerOutputDir(context.sdk)) : context.sdk.setOutputDir(this.getOutputDir(compiler)), await context.sdk.writeStore();
1694
+ let isPrimaryCompiler = !(context.sdk instanceof RsdoctorPrimarySDK) || context.sdk.isMaster;
1695
+ !this.options.disableClientServer && isPrimaryCompiler && (this.options.output.mode === SDK.IMode[SDK.IMode.brief] ? await handleBriefModeReport(context.sdk, this.options, this.options.disableClientServer) : await context.sdk.server.openClientPage('homepage')), this.shouldDisposeSDK() && await context.sdk.dispose();
1696
+ } finally{
1697
+ timeEnd('RsdoctorRspackPlugin.done');
1698
+ }
1699
+ }, this.childDone = async (compiler, context)=>{
1700
+ await context.bootstrapTask, context.sdk.addClientRoutes([
1701
+ Manifest.RsdoctorManifestClientRoutes.Overall
1702
+ ]), context.sdk instanceof RsdoctorPrimarySDK ? context.sdk.setOutputDir(context.sdk.parent.getCompilerOutputDir(context.sdk)) : context.sdk.setOutputDir(this.getOutputDir(compiler)), await context.sdk.writeStore(), this.shouldDisposeSDK() && await context.sdk.dispose();
1703
+ }, this.childOptions = {
1704
+ ...options,
1705
+ supports: {
1706
+ ...options?.supports
1707
+ }
1708
+ }, this.options = normalizeRspackUserOptions(this.childOptions), this.outsideInstance = !!this.options.sdkInstance, this.defaultName = options?.name || pluginTapName, this.defaultStage = options?.stage, this.options.sdkInstance) {
1709
+ this.options.sdkInstance instanceof RsdoctorPrimarySDK && (this.controller = this.options.sdkInstance.parent), this.primaryContext = new RsdoctorCompilerContext(this.options.sdkInstance, this.options);
1710
+ return;
1711
+ }
1712
+ this.sessionLease = function(options) {
1713
+ if (!options.multiCompiler.enabled) return {
1714
+ controller: new RsdoctorSDKController(),
1715
+ release () {}
1716
+ };
1717
+ let key = function(options) {
1718
+ let root = process.cwd(), { group } = options.multiCompiler;
1719
+ return group ? [
1720
+ 'group',
1721
+ root,
1722
+ group
1723
+ ].join('\0') : [
1724
+ 'auto',
1725
+ root,
1726
+ options.output.mode,
1727
+ options.output.reportDir,
1728
+ options.server.port ?? options.port ?? ''
1729
+ ].join('\0');
1730
+ }(options), session = pendingSessions.get(key);
1731
+ if (!session) {
1732
+ let controller = new RsdoctorSDKController(), timer = setTimeout(()=>{
1733
+ pendingSessions.get(key)?.controller === controller && pendingSessions.delete(key);
1734
+ }, 0);
1735
+ timer.unref?.(), session = {
1736
+ controller,
1737
+ timer
1738
+ }, pendingSessions.set(key, session);
1739
+ }
1740
+ let { controller } = session;
1741
+ return {
1742
+ controller,
1743
+ release () {
1744
+ let current = pendingSessions.get(key);
1745
+ current?.controller === controller && (clearTimeout(current.timer), pendingSessions.delete(key));
1746
+ }
1747
+ };
1748
+ }(this.options), this.controller = this.sessionLease.controller, this.primaryContext = this.createCompilerContext(this.defaultStage);
1749
+ }
1750
+ get sdk() {
1751
+ return this.primaryContext.sdk;
1752
+ }
1753
+ get modulesGraph() {
1754
+ return this.primaryContext.modulesGraph;
1755
+ }
1756
+ get _bootstrapTask() {
1757
+ return this.primaryContext.bootstrapTask;
1758
+ }
1759
+ getCompilerSDK(name) {
1760
+ return this.sdk.name === name ? this.sdk : this.sdk instanceof RsdoctorPrimarySDK ? this.sdk.parent.slaves.find((sdk)=>sdk.name === name) : void 0;
1761
+ }
1762
+ apply(compiler) {
1763
+ let context = this.getCompilerContext(compiler);
1764
+ if (!context.applied) {
1765
+ context.applied = !0, logger_time('RsdoctorRspackPlugin.apply');
1766
+ try {
1767
+ hasGreeted || compiler.isChild() || (hasGreeted = !0, rsdoctorLogger.greet(`
1768
+ \nRsdoctor v${package_namespaceObject.version}\n`)), this.releasePendingSessionOnRun(compiler), context.bootstrapTask || (context.bootstrapTask = context.sdk.bootstrap());
1769
+ let compilerName = compiler.name || compiler.options.name || (1 === this.appliedCompilerCount ? this.defaultName : `${this.defaultName}-${this.appliedCompilerCount}`);
1770
+ compiler.isChild() || context.sdk.setName(compilerName), context.sdk instanceof RsdoctorPrimarySDK && (compiler.isChild() || (context.sdk.displayName = compiler.name || compiler.options.name || (1 === this.appliedCompilerCount ? 'Main compiler' : compilerName)), 'dependencies' in compiler.options && (context.sdk.dependencies = compiler.options.dependencies), context.sdk.parent.registerSlave(context.sdk), context.sdk.parent.setOutputDir(context.sdk, this.getOutputDir(compiler)), this.options.output.mode === SDK.IMode[SDK.IMode.brief] && (context.sdk.reportFileName = this.getBriefReportFileName())), compiler.isChild() ? registerSDK(context.sdk) : setSDK(context.sdk), this.applyChildCompilerSupport(compiler, context), compiler.isChild() ? (this.getRspackConfig(compiler, context), compiler.hooks.afterCompile.tapPromise({
1771
+ ...pluginTapPostOptions,
1772
+ stage: pluginTapPostOptions.stage + 100
1773
+ }, ()=>this.childDone(compiler, context))) : (compiler.hooks.afterPlugins.tap(pluginTapPostOptions, ()=>this.afterPlugins(compiler, context)), compiler.hooks.done.tapPromise({
1774
+ ...pluginTapPostOptions,
1775
+ stage: pluginTapPostOptions.stage + 100
1776
+ }, ()=>this.done(compiler, context))), new InternalSummaryPlugin(context).apply(compiler), this.options.features.loader && (compiler.isChild() || new ProbeLoaderPlugin().apply(compiler), context.sdk.addClientRoutes([
1777
+ Manifest.RsdoctorManifestClientRoutes.Loaders
1778
+ ]), Loader.isVue(compiler) || new InternalLoaderPlugin(context).apply(compiler)), this.options.features.plugins && new InternalPluginsPlugin(context).apply(compiler), this.options.features.bundle && new InternalBundlePlugin(context).apply(compiler), this.options.features.resolver && new InternalResolverPlugin(context).apply(compiler), new InternalRulesPlugin(context).apply(compiler), new InternalErrorReporterPlugin(context).apply(compiler);
1779
+ let RsdoctorRspackNativePlugin = getRspackNativePlugin(compiler);
1780
+ rsdoctorLogger.debug('[RspackNativePlugin] Enabled'), new RsdoctorRspackNativePlugin({
1781
+ moduleGraphFeatures: !0,
1782
+ chunkGraphFeatures: !0,
1783
+ sourceMapFeatures: {
1784
+ cheap: !1,
1785
+ module: !1
1786
+ }
1787
+ }).apply(compiler);
1788
+ } finally{
1789
+ timeEnd('RsdoctorRspackPlugin.apply');
1790
+ }
1791
+ }
1792
+ }
1793
+ ensureModulesChunksGraphApplied(compiler) {
1794
+ this.getCompilerContext(compiler).ensureModulesChunksGraphApplied(compiler);
1795
+ }
1796
+ getRspackConfig(compiler, context = this.getCompilerContext(compiler)) {
1797
+ logger_time('RsdoctorRspackPlugin.getRspackConfig');
1798
+ try {
1799
+ let configuration = processCompilerConfig(compiler.options);
1800
+ compiler.isChild() && compiler.name && (configuration.name = compiler.name);
1801
+ let { rspackVersion } = compiler.rspack;
1802
+ context.sdk.reportConfiguration({
1803
+ name: 'rspack',
1804
+ version: rspackVersion || 'unknown',
1805
+ config: configuration,
1806
+ root: findRoot() || ''
1807
+ });
1808
+ } finally{
1809
+ timeEnd('RsdoctorRspackPlugin.getRspackConfig');
1810
+ }
1811
+ }
1812
+ createCompilerContext(stage) {
1813
+ let controller = this.controller, { output, innerClientPath, printLog, server, features } = this.options;
1814
+ return new RsdoctorCompilerContext(controller.createSlave({
1815
+ name: this.defaultName,
1816
+ stage,
1817
+ extraConfig: {
1818
+ innerClientPath,
1819
+ printLog,
1820
+ server,
1821
+ mode: output.mode || void 0,
1822
+ brief: output.mode === SDK.IMode[SDK.IMode.brief] && output.options || void 0,
1823
+ features: {
1824
+ treeShaking: features.treeShaking
1825
+ }
1826
+ },
1827
+ type: output.reportCodeType
1828
+ }), this.options);
1829
+ }
1830
+ getCompilerContext(compiler) {
1831
+ let context, existing = this.compilerContexts.get(compiler);
1832
+ if (existing) return existing;
1833
+ if (0 === this.appliedCompilerCount) context = this.primaryContext;
1834
+ else {
1835
+ if (!this.controller) throw Error('[RsdoctorRspackPlugin] A fixed sdkInstance cannot be shared by multiple compilers. Create one plugin instance per compiler with a separate sdkInstance.');
1836
+ if (!this.options.multiCompiler.enabled) throw Error('[RsdoctorRspackPlugin] This plugin instance was applied to multiple compilers while multiCompiler is disabled.');
1837
+ context = this.createCompilerContext();
1838
+ }
1839
+ return this.appliedCompilerCount += 1, this.compilerContexts.set(compiler, context), context;
1840
+ }
1841
+ getOutputDir(compiler) {
1842
+ return node_path.resolve(this.options.output.reportDir || compiler.options.output?.path || compiler.outputPath, this.options.output.mode === SDK.IMode[SDK.IMode.brief] ? '' : `./${Constants.RsdoctorOutputFolder}`);
1843
+ }
1844
+ getBriefReportFileName() {
1845
+ let options = this.options.output.options;
1846
+ return options.type?.includes('html') ? options.htmlOptions?.reportHtmlName || 'rsdoctor-report.html' : options.jsonOptions?.fileName || 'rsdoctor-data.json';
1847
+ }
1848
+ applyChildCompilerSupport(compiler, context) {
1849
+ compiler.hooks.thisCompilation.tap({
1850
+ name: `${pluginTapName}:childCompiler`,
1851
+ stage: -999
1852
+ }, (compilation)=>{
1853
+ compilation.hooks.childCompiler.tap(`${pluginTapName}:childCompiler`, (childCompiler, compilerName, compilerIndex)=>{
1854
+ this.registerChildCompiler(compiler, childCompiler, compilerName, compilerIndex, context);
1855
+ });
1856
+ });
1857
+ }
1858
+ registerChildCompiler(parentCompiler, childCompiler, compilerName, compilerIndex, parentContext) {
1859
+ if (!(parentContext.sdk instanceof RsdoctorPrimarySDK)) return;
1860
+ let parentSDK = parentContext.sdk, controller = parentSDK.parent, compilerPath = childCompiler.compilerPath || `${parentCompiler.compilerPath}${compilerName}|${compilerIndex}|`, childKey = `${parentSDK.id}:${compilerPath}`, registeredChild = this.childPlugins.get(childKey);
1861
+ if (registeredChild?.compiler === childCompiler) return;
1862
+ controller.setOutputDir(parentSDK, this.getOutputDir(parentCompiler));
1863
+ let childSDK = (()=>{
1864
+ if (registeredChild) return registeredChild.sdk;
1865
+ let safeCompilerPath = compilerPath.replace(/[^a-zA-Z0-9._-]+/g, '-') || `${compilerName}-${compilerIndex}`, displayName = childCompiler.name || compilerName || `Child compiler ${compilerIndex}`, sdk = controller.createSlave({
1866
+ name: `child-${safeCompilerPath}`,
1867
+ displayName,
1868
+ compilerPath,
1869
+ parentCompilerPath: parentCompiler.compilerPath || '',
1870
+ isChild: !0,
1871
+ stage: parentSDK.stage + (controller.slaves.length + 1) / 1000,
1872
+ extraConfig: parentSDK.extraConfig,
1873
+ type: parentSDK.type
1874
+ });
1875
+ return sdk.dependencies = [
1876
+ parentSDK.name
1877
+ ], sdk;
1878
+ })();
1879
+ this.removeInheritedRsdoctorTaps(childCompiler);
1880
+ let childPlugin = new RsdoctorRspackPlugin({
1881
+ ...this.childOptions,
1882
+ sdkInstance: childSDK
1883
+ });
1884
+ this.childPlugins.set(childKey, {
1885
+ compiler: childCompiler,
1886
+ sdk: childSDK
1887
+ }), childPlugin.apply(childCompiler);
1888
+ }
1889
+ removeInheritedRsdoctorTaps(compiler) {
1890
+ for (let hook of Object.values(compiler.hooks))Array.isArray(hook.taps) && (hook.taps = hook.taps.filter((tap)=>tap.name !== pluginTapName && !tap.name.startsWith(`${pluginTapName}:`)));
1891
+ }
1892
+ shouldDisposeSDK() {
1893
+ return this.options.disableClientServer || this.options.output.mode === SDK.IMode[SDK.IMode.brief] && Array.isArray(this.options.output.options?.type) && 1 === this.options.output.options.type.length && 'json' === this.options.output.options.type[0];
1894
+ }
1895
+ releasePendingSessionOnRun(compiler) {
1896
+ if (!this.sessionLease) return;
1897
+ let release = this.sessionLease.release;
1898
+ compiler.hooks.beforeRun.tap(pluginTapName, release), compiler.hooks.watchRun.tap(pluginTapName, release);
1899
+ }
1900
+ }
1901
+ class RsdoctorRspackMultiplePlugin extends RsdoctorRspackPlugin {
1902
+ constructor(options = {}){
1903
+ super(options);
1904
+ }
1905
+ }
1906
+ export { Linter, LinterRule, LinterType, defineRule, rules } from "./26.js";
1907
+ export { logger } from "./630.js";
1908
+ export { RsdoctorRspackMultiplePlugin, RsdoctorRspackPlugin, RsdoctorSDK, resolveClientDiffHtmlPath };