@module-federation/treeshake-server 0.0.0-chore-bump-node-22-20260710161714

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 (65) hide show
  1. package/README.md +65 -0
  2. package/bin/treeshake-server.js +35 -0
  3. package/dist/876.mjs +940 -0
  4. package/dist/adapters/createAdapterDeps.d.ts +10 -0
  5. package/dist/adapters/local/adapter.d.ts +10 -0
  6. package/dist/adapters/local/index.d.ts +3 -0
  7. package/dist/adapters/local/localObjectStore.d.ts +12 -0
  8. package/dist/adapters/registry.d.ts +7 -0
  9. package/dist/adapters/types.d.ts +70 -0
  10. package/dist/app.d.ts +18 -0
  11. package/dist/cli/ossEnv.d.ts +18 -0
  12. package/dist/domain/build/constant.d.ts +1 -0
  13. package/dist/domain/build/normalize-config.d.ts +22 -0
  14. package/dist/domain/build/retrieve-global-name.d.ts +1 -0
  15. package/dist/domain/build/schema.d.ts +31 -0
  16. package/dist/domain/upload/constant.d.ts +2 -0
  17. package/dist/domain/upload/retrieve-cdn-path.d.ts +4 -0
  18. package/dist/frontend/adapter/index.d.ts +13 -0
  19. package/dist/frontend/adapter/index.js +132 -0
  20. package/dist/frontend/adapter/index.mjs +83 -0
  21. package/dist/frontend/favicon.ico +0 -0
  22. package/dist/frontend/index.html +1 -0
  23. package/dist/frontend/static/css/index.513418ff5d.css +1 -0
  24. package/dist/frontend/static/js/637.b47e0403af.js +2 -0
  25. package/dist/frontend/static/js/637.b47e0403af.js.LICENSE.txt +16 -0
  26. package/dist/frontend/static/js/async/427.dbb8b74259.js +2 -0
  27. package/dist/frontend/static/js/async/427.dbb8b74259.js.LICENSE.txt +6 -0
  28. package/dist/frontend/static/js/async/503.7bd056737e.js +12 -0
  29. package/dist/frontend/static/js/async/503.7bd056737e.js.LICENSE.txt +6 -0
  30. package/dist/frontend/static/js/async/515.1b7f26d7ec.js +2 -0
  31. package/dist/frontend/static/js/index.ace3fa3d0e.js +88 -0
  32. package/dist/frontend/static/js/lib-react.7c43a84261.js +2 -0
  33. package/dist/frontend/static/js/lib-react.7c43a84261.js.LICENSE.txt +39 -0
  34. package/dist/frontend/static/js/lib-router.5077a93d5a.js +4 -0
  35. package/dist/frontend/static/js/lib-router.5077a93d5a.js.LICENSE.txt +10 -0
  36. package/dist/http/env.d.ts +10 -0
  37. package/dist/http/middlewares/di.middleware.d.ts +4 -0
  38. package/dist/http/middlewares/logger.middleware.d.ts +3 -0
  39. package/dist/http/routes/build.d.ts +3 -0
  40. package/dist/http/routes/index.d.ts +2 -0
  41. package/dist/http/routes/maintenance.d.ts +3 -0
  42. package/dist/http/routes/static.d.ts +5 -0
  43. package/dist/index.d.ts +10 -0
  44. package/dist/index.js +1015 -0
  45. package/dist/index.mjs +1 -0
  46. package/dist/infra/logger.d.ts +6 -0
  47. package/dist/nodeServer.d.ts +7 -0
  48. package/dist/ports/objectStore.d.ts +1 -0
  49. package/dist/ports/projectPublisher.d.ts +1 -0
  50. package/dist/server.d.ts +2 -0
  51. package/dist/server.js +1144 -0
  52. package/dist/server.mjs +170 -0
  53. package/dist/services/buildService.d.ts +8 -0
  54. package/dist/services/cacheService.d.ts +15 -0
  55. package/dist/services/pnpmMaintenance.d.ts +4 -0
  56. package/dist/services/uploadService.d.ts +36 -0
  57. package/dist/template/re-shake-share/Collect.js +115 -0
  58. package/dist/template/re-shake-share/EmitManifest.js +49 -0
  59. package/dist/template/re-shake-share/index.ts +1 -0
  60. package/dist/template/re-shake-share/package.json +23 -0
  61. package/dist/template/re-shake-share/rspack.config.ts +33 -0
  62. package/dist/utils/runCommand.d.ts +20 -0
  63. package/dist/utils/runtimeEnv.d.ts +3 -0
  64. package/dist/utils/uploadSdk.d.ts +10 -0
  65. package/package.json +68 -0
package/dist/server.js ADDED
@@ -0,0 +1,1144 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __webpack_require__ = {};
4
+ (()=>{
5
+ __webpack_require__.n = (module)=>{
6
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
7
+ __webpack_require__.d(getter, {
8
+ a: getter
9
+ });
10
+ return getter;
11
+ };
12
+ })();
13
+ (()=>{
14
+ __webpack_require__.d = (exports1, getters, values)=>{
15
+ var define = (defs, kind)=>{
16
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
17
+ enumerable: true,
18
+ [kind]: defs[key]
19
+ });
20
+ };
21
+ define(getters, "get");
22
+ define(values, "value");
23
+ };
24
+ })();
25
+ (()=>{
26
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ const external_node_fs_namespaceObject = require("node:fs");
30
+ var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
31
+ const external_node_path_namespaceObject = require("node:path");
32
+ var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
33
+ const SERVER_VERSION = 'v0-0205';
34
+ const UPLOADED_DIR = '_shared-tree-shaking';
35
+ const external_pino_namespaceObject = require("pino");
36
+ var external_pino_default = /*#__PURE__*/ __webpack_require__.n(external_pino_namespaceObject);
37
+ const createLogger = (opts)=>external_pino_default()({
38
+ level: opts?.level ?? 'info',
39
+ formatters: {
40
+ level (label) {
41
+ return {
42
+ level: label
43
+ };
44
+ }
45
+ }
46
+ });
47
+ let logger_logger = createLogger();
48
+ const setLogger = (next)=>{
49
+ logger_logger = next;
50
+ };
51
+ async function createAdapterDeps(params) {
52
+ const adapterId = params.adapterId;
53
+ const adapter = params.registry.getAdapterById(adapterId);
54
+ return adapter.create(params.adapterConfig ?? {}, {
55
+ logger: params.logger ?? logger_logger,
56
+ uploadedDir: params.uploadedDir ?? UPLOADED_DIR
57
+ });
58
+ }
59
+ function _define_property(obj, key, value) {
60
+ if (key in obj) Object.defineProperty(obj, key, {
61
+ value: value,
62
+ enumerable: true,
63
+ configurable: true,
64
+ writable: true
65
+ });
66
+ else obj[key] = value;
67
+ return obj;
68
+ }
69
+ class LocalObjectStore {
70
+ async exists(key) {
71
+ const filePath = external_node_path_default().join(this.rootDir, key.replace(/^\//, ''));
72
+ try {
73
+ const stat = await external_node_fs_default().promises.stat(filePath);
74
+ return stat.isFile();
75
+ } catch {
76
+ return false;
77
+ }
78
+ }
79
+ async uploadFile(localPath, key) {
80
+ const rel = key.replace(/^\//, '');
81
+ const dest = external_node_path_default().join(this.rootDir, rel);
82
+ await external_node_fs_default().promises.mkdir(external_node_path_default().dirname(dest), {
83
+ recursive: true
84
+ });
85
+ await external_node_fs_default().promises.copyFile(localPath, dest);
86
+ }
87
+ publicUrl(key) {
88
+ return `${this.publicBaseUrl}${key.replace(/^\//, '')}`;
89
+ }
90
+ constructor(opts){
91
+ _define_property(this, "rootDir", void 0);
92
+ _define_property(this, "publicBaseUrl", void 0);
93
+ this.rootDir = opts?.rootDir ?? external_node_path_default().join(process.cwd(), 'log', 'static');
94
+ const port = process.env.PORT || 3000;
95
+ const base = opts?.publicBaseUrl === '/' ? `http://localhost:${port}/` : opts?.publicBaseUrl ?? '/';
96
+ this.publicBaseUrl = base.endsWith('/') ? base : `${base}/`;
97
+ }
98
+ }
99
+ function adapter_define_property(obj, key, value) {
100
+ if (key in obj) Object.defineProperty(obj, key, {
101
+ value: value,
102
+ enumerable: true,
103
+ configurable: true,
104
+ writable: true
105
+ });
106
+ else obj[key] = value;
107
+ return obj;
108
+ }
109
+ function envStr(env, name, fallback) {
110
+ const v = env[name];
111
+ if (void 0 === v || '' === v) return fallback;
112
+ return v;
113
+ }
114
+ class LocalAdapter {
115
+ fromEnv(env) {
116
+ return {
117
+ rootDir: envStr(env, 'LOCAL_STORE_DIR', external_node_path_default().join(process.cwd(), 'log', 'static')),
118
+ publicBaseUrl: envStr(env, 'LOCAL_STORE_BASE_URL', '/')
119
+ };
120
+ }
121
+ async create(config, _context) {
122
+ const objectStore = new LocalObjectStore({
123
+ rootDir: config.rootDir,
124
+ publicBaseUrl: config.publicBaseUrl
125
+ });
126
+ return {
127
+ objectStore
128
+ };
129
+ }
130
+ constructor(){
131
+ adapter_define_property(this, "id", 'local');
132
+ }
133
+ }
134
+ function createAdapterRegistry(adapters) {
135
+ return {
136
+ adapters,
137
+ getAdapterById: (id)=>{
138
+ const found = adapters.find((a)=>a.id === id);
139
+ if (!found) throw new Error(`Unknown ADAPTER_ID: ${id}`);
140
+ return found;
141
+ }
142
+ };
143
+ }
144
+ function createOssAdapterRegistry() {
145
+ return createAdapterRegistry([
146
+ new LocalAdapter()
147
+ ]);
148
+ }
149
+ const external_hono_namespaceObject = require("hono");
150
+ function contentTypeByExt(filePath) {
151
+ if (filePath.endsWith('.js')) return "application/javascript";
152
+ if (filePath.endsWith('.json')) return 'application/json';
153
+ return 'application/octet-stream';
154
+ }
155
+ const DEFAULT_STATIC_ROOT = external_node_path_default().join(process.cwd(), 'log', 'static');
156
+ async function serveLocalFile(c, rootDir) {
157
+ let requestPath = c.req.path;
158
+ try {
159
+ requestPath = decodeURIComponent(requestPath);
160
+ } catch {
161
+ return c.text('Not Found', 404);
162
+ }
163
+ const relPath = requestPath.replace(/^\/+/, '');
164
+ const rootResolved = external_node_path_default().resolve(rootDir);
165
+ const filePath = external_node_path_default().resolve(rootResolved, relPath);
166
+ if (filePath !== rootResolved && !filePath.startsWith(`${rootResolved}${external_node_path_default().sep}`)) return c.text('Not Found', 404);
167
+ try {
168
+ const buf = await external_node_fs_default().promises.readFile(filePath);
169
+ return new Response(new Uint8Array(buf), {
170
+ status: 200,
171
+ headers: {
172
+ 'Content-Type': contentTypeByExt(filePath)
173
+ }
174
+ });
175
+ } catch {
176
+ return c.text('Not Found', 404);
177
+ }
178
+ }
179
+ function createStaticRoute(opts) {
180
+ const staticRoute = new external_hono_namespaceObject.Hono();
181
+ const rootDir = opts?.rootDir ?? DEFAULT_STATIC_ROOT;
182
+ staticRoute.get('/tree-shaking-shared/*', async (c)=>serveLocalFile(c, rootDir));
183
+ return staticRoute;
184
+ }
185
+ const DEFAULT_PRUNE_INTERVAL_MS = 3600000;
186
+ function ossEnv_envStr(env, name, fallback) {
187
+ const v = env[name];
188
+ if (void 0 === v || '' === v) return fallback;
189
+ return v;
190
+ }
191
+ function envNum(env, name, fallback) {
192
+ const v = ossEnv_envStr(env, name);
193
+ if (!v) return fallback;
194
+ const n = Number(v);
195
+ return Number.isFinite(n) ? n : fallback;
196
+ }
197
+ function resolveOssEnv(params) {
198
+ const adapterId = ossEnv_envStr(params.env, 'ADAPTER_ID', params.defaultAdapterId) ?? 'local';
199
+ const adapter = params.registry.getAdapterById(adapterId);
200
+ const adapterConfig = adapter.fromEnv ? adapter.fromEnv(params.env) : {};
201
+ return {
202
+ adapterId,
203
+ adapterConfig,
204
+ corsOrigin: ossEnv_envStr(params.env, 'CORS_ORIGIN', '*') ?? '*',
205
+ staticRootDir: ossEnv_envStr(params.env, 'LOCAL_STORE_DIR', DEFAULT_STATIC_ROOT) ?? DEFAULT_STATIC_ROOT,
206
+ logLevel: ossEnv_envStr(params.env, 'LOG_LEVEL', 'info') ?? 'info',
207
+ port: envNum(params.env, 'PORT', 3000),
208
+ hostname: ossEnv_envStr(params.env, 'HOST', '0.0.0.0') ?? '0.0.0.0',
209
+ pruneIntervalMs: envNum(params.env, 'PNPM_PRUNE_INTERVAL_MS', DEFAULT_PRUNE_INTERVAL_MS),
210
+ runtimeEnv: params.env
211
+ };
212
+ }
213
+ const cors_namespaceObject = require("hono/cors");
214
+ function createDiMiddleware(deps) {
215
+ return async (c, next)=>{
216
+ c.set('objectStore', deps.objectStore);
217
+ if (deps.projectPublisher) c.set('projectPublisher', deps.projectPublisher);
218
+ await next();
219
+ };
220
+ }
221
+ const loggerMiddleware = async (c, next)=>{
222
+ const category = c.req.path.split('/')[1] || 'root';
223
+ const child = logger_logger.child({
224
+ category,
225
+ path: c.req.path,
226
+ method: c.req.method
227
+ });
228
+ c.set('logger', child);
229
+ await next();
230
+ };
231
+ const external_node_os_namespaceObject = require("node:os");
232
+ var external_node_os_default = /*#__PURE__*/ __webpack_require__.n(external_node_os_namespaceObject);
233
+ const zod_validator_namespaceObject = require("@hono/zod-validator");
234
+ const external_nanoid_namespaceObject = require("nanoid");
235
+ const external_p_limit_namespaceObject = require("p-limit");
236
+ var external_p_limit_default = /*#__PURE__*/ __webpack_require__.n(external_p_limit_namespaceObject);
237
+ const parseNormalizedKey = (key)=>{
238
+ const res = key.split('@');
239
+ return {
240
+ name: res.slice(0, -1).join('@'),
241
+ version: res[res.length - 1]
242
+ };
243
+ };
244
+ const normalizedKey = (name, v)=>`${name}@${v}`;
245
+ function normalizeConfig(config) {
246
+ const { shared, plugins, target, libraryType, hostName, uploadOptions } = config;
247
+ const commonNormalizedConfig = {
248
+ plugins: plugins?.sort(([a], [b])=>a.localeCompare(b)) ?? [],
249
+ target: Array.isArray(target) ? [
250
+ ...target
251
+ ].sort() : [
252
+ target
253
+ ],
254
+ uploadOptions,
255
+ libraryType,
256
+ hostName
257
+ };
258
+ const normalizedConfig = {};
259
+ shared.forEach(([sharedName, version, usedExports], index)=>{
260
+ const key = normalizedKey(sharedName, version);
261
+ normalizedConfig[key] = {
262
+ ...commonNormalizedConfig,
263
+ shared: shared.slice(0, index).concat(shared.slice(index + 1)).sort(([s, v, u], [b, v2, u2])=>`${s}${v}${u.sort().join('')}`.localeCompare(`${b}${v2}${u2.sort().join('')}`)),
264
+ usedExports
265
+ };
266
+ });
267
+ return normalizedConfig;
268
+ }
269
+ function extractBuildConfig(config, type) {
270
+ const { shared, plugins, target, libraryType, usedExports, hostName } = config;
271
+ return {
272
+ shared,
273
+ plugins,
274
+ target,
275
+ libraryType,
276
+ usedExports,
277
+ type,
278
+ hostName
279
+ };
280
+ }
281
+ const external_zod_namespaceObject = require("zod");
282
+ const UploadOptionsSchema = external_zod_namespaceObject.z.object({
283
+ scmName: external_zod_namespaceObject.z.string(),
284
+ bucketName: external_zod_namespaceObject.z.string(),
285
+ publicFilePath: external_zod_namespaceObject.z.string(),
286
+ publicPath: external_zod_namespaceObject.z.string(),
287
+ cdnRegion: external_zod_namespaceObject.z.string()
288
+ });
289
+ const BasicSchema = external_zod_namespaceObject.z.object({
290
+ shared: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.tuple([
291
+ external_zod_namespaceObject.z.string(),
292
+ external_zod_namespaceObject.z.string(),
293
+ external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string())
294
+ ])).describe('List of plugins: [name, version, usedExports]'),
295
+ plugins: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.tuple([
296
+ external_zod_namespaceObject.z.string(),
297
+ external_zod_namespaceObject.z.string().optional()
298
+ ])).describe('Specify extra build plugin names, support specify version in second item').optional(),
299
+ target: external_zod_namespaceObject.z.union([
300
+ external_zod_namespaceObject.z.string(),
301
+ external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string())
302
+ ]).describe('Used to configure the target environment of Rspack output and the ECMAScript version of Rspack runtime code, the same with rspack#target'),
303
+ libraryType: external_zod_namespaceObject.z.string(),
304
+ hostName: external_zod_namespaceObject.z.string().describe('The name of the host app / mf')
305
+ });
306
+ const ConfigSchema = BasicSchema.extend({
307
+ uploadOptions: UploadOptionsSchema.optional()
308
+ });
309
+ const CheckTreeShakingSchema = ConfigSchema.extend({
310
+ uploadOptions: UploadOptionsSchema.optional()
311
+ });
312
+ const external_node_crypto_namespaceObject = require("node:crypto");
313
+ const promises_namespaceObject = require("node:fs/promises");
314
+ var promises_default = /*#__PURE__*/ __webpack_require__.n(promises_namespaceObject);
315
+ const STATS_NAME = 'mf-stats.json';
316
+ const external_node_child_process_namespaceObject = require("node:child_process");
317
+ let runtimeEnv = {};
318
+ const setRuntimeEnv = (env)=>{
319
+ runtimeEnv = env;
320
+ };
321
+ const getRuntimeEnv = ()=>runtimeEnv;
322
+ function runCommand_define_property(obj, key, value) {
323
+ if (key in obj) Object.defineProperty(obj, key, {
324
+ value: value,
325
+ enumerable: true,
326
+ configurable: true,
327
+ writable: true
328
+ });
329
+ else obj[key] = value;
330
+ return obj;
331
+ }
332
+ class CommandExecutionError extends Error {
333
+ constructor(command, exitCode, stdout, stderr){
334
+ super(`Command "${command}" exited with code ${exitCode}`), runCommand_define_property(this, "command", void 0), runCommand_define_property(this, "exitCode", void 0), runCommand_define_property(this, "stdout", void 0), runCommand_define_property(this, "stderr", void 0);
335
+ this.name = 'CommandExecutionError';
336
+ this.command = command;
337
+ this.exitCode = exitCode;
338
+ this.stdout = stdout;
339
+ this.stderr = stderr;
340
+ }
341
+ }
342
+ const runCommand = (command, options = {})=>new Promise((resolve, reject)=>{
343
+ const stdoutChunks = [];
344
+ const stderrChunks = [];
345
+ const child = (0, external_node_child_process_namespaceObject.spawn)(command, {
346
+ cwd: options.cwd,
347
+ env: {
348
+ ...getRuntimeEnv(),
349
+ ...options.env
350
+ },
351
+ shell: true,
352
+ stdio: [
353
+ 'ignore',
354
+ 'pipe',
355
+ 'pipe'
356
+ ]
357
+ });
358
+ child.stdout.on('data', (chunk)=>{
359
+ stdoutChunks.push(chunk.toString());
360
+ });
361
+ child.stderr.on('data', (chunk)=>{
362
+ stderrChunks.push(chunk.toString());
363
+ });
364
+ child.on('error', (error)=>{
365
+ reject(error);
366
+ });
367
+ child.on('close', (exitCode)=>{
368
+ const stdout = stdoutChunks.join('');
369
+ const stderr = stderrChunks.join('');
370
+ if (0 === exitCode) return void resolve({
371
+ stdout,
372
+ stderr,
373
+ exitCode
374
+ });
375
+ reject(new CommandExecutionError(command, exitCode ?? -1, stdout, stderr));
376
+ });
377
+ });
378
+ let installs = 0;
379
+ let pruneScheduled = false;
380
+ let pruning = false;
381
+ const DEFAULT_INTERVAL = 3600000;
382
+ const markInstallStart = ()=>{
383
+ installs++;
384
+ };
385
+ const markInstallEnd = ()=>{
386
+ installs = Math.max(0, installs - 1);
387
+ schedulePruneSoon();
388
+ };
389
+ const schedulePruneSoon = (delay = 30000)=>{
390
+ if (pruneScheduled) return;
391
+ pruneScheduled = true;
392
+ setTimeout(()=>{
393
+ pruneScheduled = false;
394
+ maybePrune();
395
+ }, delay);
396
+ };
397
+ const maybePrune = async ()=>{
398
+ if (pruning || installs > 0) return void schedulePruneSoon(60000);
399
+ pruning = true;
400
+ try {
401
+ await runCommand('pnpm store prune');
402
+ } catch {} finally{
403
+ pruning = false;
404
+ }
405
+ };
406
+ const startPeriodicPrune = (intervalMs = DEFAULT_INTERVAL)=>{
407
+ if (intervalMs <= 0) return;
408
+ setInterval(()=>{
409
+ maybePrune();
410
+ }, intervalMs);
411
+ };
412
+ const createUniqueTempDirByKey = async (key)=>{
413
+ const base = external_node_path_default().join(external_node_os_default().tmpdir(), `re-shake-share-${key}`);
414
+ let candidate = base;
415
+ for(;;)try {
416
+ await promises_default().mkdir(candidate, {
417
+ recursive: false
418
+ });
419
+ return candidate;
420
+ } catch {
421
+ const rand = Math.floor(1e9 * Math.random());
422
+ candidate = `${base}-${rand}`;
423
+ }
424
+ };
425
+ const prepareProject = async (config, excludeShared)=>{
426
+ const key = (0, external_node_crypto_namespaceObject.createHash)('sha256').update(JSON.stringify(config)).digest('hex');
427
+ const dir = await createUniqueTempDirByKey(key);
428
+ const templateDir = external_node_path_default().join(__dirname, '.', 'template', 're-shake-share');
429
+ await promises_default().cp(templateDir, dir, {
430
+ recursive: true
431
+ });
432
+ const pkgPath = external_node_path_default().join(dir, 'package.json');
433
+ const indexPath = external_node_path_default().join(dir, 'index.ts');
434
+ const rspackConfigPath = external_node_path_default().join(dir, 'rspack.config.ts');
435
+ const [pkgContent, indexContent, rspackConfigContent] = await Promise.all([
436
+ promises_default().readFile(pkgPath, 'utf-8'),
437
+ promises_default().readFile(indexPath, 'utf-8'),
438
+ promises_default().readFile(rspackConfigPath, 'utf-8')
439
+ ]);
440
+ const pkg = JSON.parse(pkgContent);
441
+ const deps = {
442
+ ...pkg.dependencies || {}
443
+ };
444
+ const shared = {};
445
+ const mfConfig = {
446
+ name: 're_shake',
447
+ library: {
448
+ type: 'global'
449
+ },
450
+ manifest: true,
451
+ shared
452
+ };
453
+ let pluginImportStr = '';
454
+ let pluginOptionStr = '[\n';
455
+ let sharedImport = '';
456
+ Object.entries(config).forEach(([key, { plugins = [], libraryType, usedExports, hostName }], index)=>{
457
+ const { name, version } = parseNormalizedKey(key);
458
+ deps[name] = version;
459
+ if (!index) {
460
+ plugins.forEach(([pluginName, pluginVersion], pIndex)=>{
461
+ deps[pluginName] = pluginVersion ?? 'latest';
462
+ const pluginImportName = `plugin_${pIndex}`;
463
+ pluginImportStr += `import ${pluginImportName} from '${pluginName}';\n`;
464
+ pluginOptionStr += `new ${pluginImportName}(),`;
465
+ });
466
+ mfConfig.library.type = libraryType;
467
+ mfConfig.name = hostName;
468
+ }
469
+ shared[name] = {
470
+ requiredVersion: version,
471
+ version,
472
+ treeShaking: excludeShared.some(([n, v])=>n === name && v === version) ? void 0 : {
473
+ usedExports,
474
+ mode: 'server-calc'
475
+ }
476
+ };
477
+ sharedImport += `import shared_${index} from '${name}';\n`;
478
+ });
479
+ pluginOptionStr += '\n]';
480
+ pkg.dependencies = deps;
481
+ const newPkgContent = JSON.stringify(pkg, null, 2);
482
+ const sharedImportPlaceholder = "${SHARED_IMPORT}";
483
+ const newIndexContent = indexContent.replace(sharedImportPlaceholder, sharedImport);
484
+ const pluginsPlaceholder = "${ PLUGINS }";
485
+ const mfConfigPlaceholder = "${ MF_CONFIG }";
486
+ let cfg = rspackConfigContent;
487
+ cfg += pluginImportStr;
488
+ cfg = cfg.replace(pluginsPlaceholder, pluginOptionStr);
489
+ cfg = cfg.replace(mfConfigPlaceholder, JSON.stringify(mfConfig, null, 2));
490
+ await Promise.all([
491
+ promises_default().writeFile(pkgPath, newPkgContent),
492
+ promises_default().writeFile(indexPath, newIndexContent),
493
+ promises_default().writeFile(rspackConfigPath, cfg)
494
+ ]);
495
+ return dir;
496
+ };
497
+ const installDependencies = async (cwd)=>{
498
+ markInstallStart();
499
+ try {
500
+ await runCommand("pnpm i --ignore-scripts --prefer-offline --reporter=silent ", {
501
+ cwd,
502
+ env: {
503
+ npm_config_registry: process.env.MF_NPM_REGISTRY || 'https://registry.npmjs.org/'
504
+ }
505
+ });
506
+ } finally{
507
+ markInstallEnd();
508
+ }
509
+ };
510
+ const buildProject = async (cwd, type)=>{
511
+ const scripts = [];
512
+ if ('re-shake' === type) scripts.push('pnpm build');
513
+ else scripts.push('pnpm build:full');
514
+ await Promise.all(scripts.map((script)=>runCommand(script, {
515
+ cwd
516
+ })));
517
+ };
518
+ const retrieveSharedFilepaths = async (projectDir, type)=>{
519
+ const sharedFilepaths = [];
520
+ const collectSharedFilepaths = async (t)=>{
521
+ const dir = 'full' === t ? 'full-shared' : 'dist';
522
+ const distDir = external_node_path_default().join(projectDir, dir);
523
+ const statsContent = await promises_default().readFile(external_node_path_default().join(distDir, STATS_NAME), 'utf-8');
524
+ const stats = JSON.parse(statsContent);
525
+ stats.shared.forEach((s)=>{
526
+ const { name, version, fallback, fallbackName } = s;
527
+ if (fallback && fallbackName) {
528
+ const filepath = external_node_path_default().join(distDir, fallback);
529
+ sharedFilepaths.push({
530
+ name,
531
+ version,
532
+ filepath,
533
+ globalName: fallbackName,
534
+ type: t,
535
+ modules: s.usedExports,
536
+ canTreeShaking: s.canTreeShaking ?? s.usedExports?.length !== 0
537
+ });
538
+ }
539
+ });
540
+ };
541
+ await collectSharedFilepaths(type);
542
+ return sharedFilepaths;
543
+ };
544
+ const runBuild = async (normalizedConfig, excludeShared, type)=>{
545
+ const tStart = Date.now();
546
+ const tmpDir = await prepareProject(normalizedConfig, excludeShared);
547
+ const tPrepare = Date.now();
548
+ logger_logger.info(`prepareProject took ${tPrepare - tStart}ms`);
549
+ await installDependencies(tmpDir);
550
+ const tInstall = Date.now();
551
+ logger_logger.info(`installDependencies took ${tInstall - tPrepare}ms`);
552
+ await buildProject(tmpDir, type);
553
+ const tBuild = Date.now();
554
+ logger_logger.info(`buildProject took ${tBuild - tInstall}ms`);
555
+ const sharedFilePaths = await retrieveSharedFilepaths(tmpDir, type);
556
+ const tRetrieve = Date.now();
557
+ logger_logger.info(`retrieveSharedFilepaths took ${tRetrieve - tBuild}ms`);
558
+ return {
559
+ sharedFilePaths,
560
+ dir: tmpDir
561
+ };
562
+ };
563
+ async function cleanUp(tmpDir) {
564
+ if (!tmpDir) return;
565
+ await promises_default().rm(tmpDir, {
566
+ recursive: true,
567
+ force: true
568
+ });
569
+ }
570
+ const external_json_stable_stringify_namespaceObject = require("json-stable-stringify");
571
+ var external_json_stable_stringify_default = /*#__PURE__*/ __webpack_require__.n(external_json_stable_stringify_namespaceObject);
572
+ const encodeName = function(name, prefix = '', withExt = false) {
573
+ const ext = withExt ? '.js' : '';
574
+ return `${prefix}${name.replace(/@/g, 'scope_').replace(/-/g, '_').replace(/\//g, '__').replace(/\./g, '')}${ext}`;
575
+ };
576
+ function retrieveGlobalName(mfName, sharedName, version) {
577
+ return encodeName(`${mfName}_${sharedName}_${version}`);
578
+ }
579
+ function createCacheHash(config, type) {
580
+ const relevant = extractBuildConfig({
581
+ ...config,
582
+ usedExports: 'full' === type ? [] : config.usedExports
583
+ }, type);
584
+ const json = external_json_stable_stringify_default()(relevant);
585
+ if (!json) throw new Error('Can not stringify build config!');
586
+ return (0, external_node_crypto_namespaceObject.createHash)('sha256').update(json).digest('hex');
587
+ }
588
+ function retrieveCDNPath({ config, sharedKey, type }) {
589
+ const configHash = createCacheHash(config, type);
590
+ return `tree-shaking-shared/${SERVER_VERSION}/${sharedKey}/${configHash}.js`;
591
+ }
592
+ async function cacheService_hitCache(sharedKey, config, type, store) {
593
+ const cdnPath = retrieveCDNPath({
594
+ config,
595
+ sharedKey,
596
+ type
597
+ });
598
+ const exists = await store.exists(cdnPath);
599
+ return exists ? store.publicUrl(cdnPath) : null;
600
+ }
601
+ const retrieveCacheItems = async (normalizedConfig, type, store)=>{
602
+ const cacheItems = [];
603
+ const restConfig = {};
604
+ const excludeShared = [];
605
+ for (const [sharedKey, config] of Object.entries(normalizedConfig)){
606
+ let cache = false;
607
+ const { name, version } = parseNormalizedKey(sharedKey);
608
+ const cdnUrl = await cacheService_hitCache(sharedKey, config, type, store);
609
+ if (cdnUrl) {
610
+ cache = true;
611
+ cacheItems.push({
612
+ type,
613
+ name,
614
+ version,
615
+ cdnUrl,
616
+ globalName: retrieveGlobalName(config.hostName, name, version)
617
+ });
618
+ }
619
+ if (cache) excludeShared.push([
620
+ name,
621
+ version
622
+ ]);
623
+ else if (config.usedExports.length || 're-shake' !== type) restConfig[sharedKey] = config;
624
+ else excludeShared.push([
625
+ name,
626
+ version
627
+ ]);
628
+ }
629
+ return {
630
+ cacheItems,
631
+ excludeShared,
632
+ restConfig
633
+ };
634
+ };
635
+ async function uploadToCacheStore(sharedFilePaths, normalizedConfig, store) {
636
+ const results = [];
637
+ for (const file of sharedFilePaths){
638
+ const { name, version, filepath, globalName, type, modules, canTreeShaking } = file;
639
+ try {
640
+ const sharedKey = normalizedKey(name, version);
641
+ logger_logger.info(`Uploading ${sharedKey} to CDN`);
642
+ const config = normalizedConfig[sharedKey];
643
+ const cdnPath = retrieveCDNPath({
644
+ config,
645
+ sharedKey,
646
+ type
647
+ });
648
+ const t0 = Date.now();
649
+ await store.uploadFile(filepath, cdnPath);
650
+ const tUpload = Date.now() - t0;
651
+ const cdnUrl = store.publicUrl(cdnPath);
652
+ const res = {
653
+ name: name,
654
+ version: version,
655
+ globalName: globalName,
656
+ cdnUrl,
657
+ type,
658
+ modules,
659
+ canTreeShaking
660
+ };
661
+ try {
662
+ const jsonFilePath = filepath.replace(/\.js$/, '.json');
663
+ const jsonFile = JSON.stringify(res);
664
+ const jsonCdnUrl = cdnPath.replace(/\.js$/, '.json');
665
+ await promises_default().writeFile(jsonFilePath, jsonFile);
666
+ await store.uploadFile(jsonFilePath, jsonCdnUrl);
667
+ } catch (error) {
668
+ logger_logger.error(`Failed to upload ${name}@${version} json file: ${error}`);
669
+ }
670
+ results.push(res);
671
+ logger_logger.info(`Successfully uploaded ${name}@${version} to ${cdnUrl} in ${tUpload}ms`);
672
+ } catch (error) {
673
+ logger_logger.error(`Failed to upload ${name}@${version}: ${error}`);
674
+ throw error;
675
+ }
676
+ }
677
+ return results;
678
+ }
679
+ const downloadToFile = async (url, destPath)=>{
680
+ const res = await fetch(url);
681
+ if (!res.ok) throw new Error(`Download failed: ${res.status} ${res.statusText} - ${url}`);
682
+ const buf = Buffer.from(await res.arrayBuffer());
683
+ await promises_default().mkdir(external_node_path_default().dirname(destPath), {
684
+ recursive: true
685
+ });
686
+ await promises_default().writeFile(destPath, buf);
687
+ return destPath;
688
+ };
689
+ async function uploadProject(uploadResults, sharedFilePaths, normalizedConfig, publisher, store) {
690
+ const tmpDir = await createUniqueTempDirByKey(`upload-project${Date.now().toString()}`);
691
+ const uploaded = [];
692
+ try {
693
+ for (const item of uploadResults)try {
694
+ const sharedKey = normalizedKey(item.name, item.version);
695
+ const config = normalizedConfig[sharedKey];
696
+ if (!config) {
697
+ logger_logger.error(`No config found for ${item.name}`);
698
+ continue;
699
+ }
700
+ const { uploadOptions } = config;
701
+ if (!uploadOptions) throw new Error(`No uploadOptions found for ${item.name}`);
702
+ const filename = external_node_path_default().basename(new URL(item.cdnUrl, 'http://dummy.com').pathname);
703
+ const localPath = external_node_path_default().join(tmpDir, filename);
704
+ const hash = createCacheHash({
705
+ ...config,
706
+ plugins: config.plugins || []
707
+ }, item.type);
708
+ const cdnUrl = publisher.publicUrl({
709
+ sharedName: item.name,
710
+ hash,
711
+ fileName: filename,
712
+ options: uploadOptions
713
+ });
714
+ const hitCache = await publisher.exists(cdnUrl);
715
+ if (hitCache) {
716
+ logger_logger.info(`Hit cache for ${item.name}@${item.version} -> ${cdnUrl}`);
717
+ uploaded.push({
718
+ ...item,
719
+ cdnUrl
720
+ });
721
+ continue;
722
+ }
723
+ logger_logger.info(`Downloading ${item.name}@${item.version} -> ${localPath}`);
724
+ const t0 = Date.now();
725
+ await downloadToFile(item.cdnUrl, localPath);
726
+ const tDownload = Date.now() - t0;
727
+ logger_logger.info(`Downloaded ${item.name}@${item.version} in ${tDownload}ms`);
728
+ const newCdnUrl = await publisher.publishFile({
729
+ localPath,
730
+ sharedName: item.name,
731
+ hash,
732
+ options: uploadOptions
733
+ });
734
+ uploaded.push({
735
+ ...item,
736
+ cdnUrl: newCdnUrl
737
+ });
738
+ } catch (error) {
739
+ logger_logger.error(`Failed to upload ${item.name}@${item.version}: ${error}`);
740
+ }
741
+ for (const s of sharedFilePaths)try {
742
+ const config = normalizedConfig[normalizedKey(s.name, s.version)];
743
+ if (!config) {
744
+ logger_logger.error(`No config found for ${s.name}`);
745
+ continue;
746
+ }
747
+ const { uploadOptions } = config;
748
+ if (!uploadOptions) throw new Error(`No uploadOptions found for ${s.name}`);
749
+ const hash = createCacheHash({
750
+ ...config,
751
+ plugins: config.plugins || []
752
+ }, s.type);
753
+ const cdnUrl = await publisher.publishFile({
754
+ localPath: s.filepath,
755
+ sharedName: s.name,
756
+ hash,
757
+ options: uploadOptions
758
+ });
759
+ uploaded.push({
760
+ name: s.name,
761
+ version: s.version,
762
+ globalName: s.globalName,
763
+ cdnUrl,
764
+ type: s.type,
765
+ modules: s.modules,
766
+ canTreeShaking: s.canTreeShaking
767
+ });
768
+ } catch (error) {
769
+ logger_logger.error(`Failed to upload ${s.name}@${s.version}: ${error}`);
770
+ }
771
+ return uploaded;
772
+ } finally{
773
+ promises_default().rm(tmpDir, {
774
+ recursive: true,
775
+ force: true
776
+ }).catch((err)=>{
777
+ logger_logger.error(`Failed to cleanup dir ${tmpDir}: ${err}`);
778
+ });
779
+ }
780
+ }
781
+ async function upload(sharedFilePaths, uploadResults, normalizedConfig, uploadOptions, store, publisher) {
782
+ const cacheUploaded = await uploadToCacheStore(sharedFilePaths, normalizedConfig, store);
783
+ if (!uploadOptions) {
784
+ const hydrated = await Promise.all(uploadResults.map(async (item)=>{
785
+ if ('full' !== item.type) return item;
786
+ const tmpDir = await createUniqueTempDirByKey(`download-full-json${Date.now().toString()}`);
787
+ const jsonPath = external_node_path_default().join(tmpDir, `${item.name}-${item.version}.json`);
788
+ try {
789
+ const tJson0 = Date.now();
790
+ await downloadToFile(item.cdnUrl.replace('.js', '.json'), jsonPath);
791
+ const tJson = Date.now() - tJson0;
792
+ logger_logger.info(`Downloaded ${item.name}@${item.version} json in ${tJson}ms`);
793
+ const jsonContent = JSON.parse(await promises_default().readFile(jsonPath, 'utf8'));
794
+ return {
795
+ ...item,
796
+ canTreeShaking: jsonContent.canTreeShaking,
797
+ modules: jsonContent.modules
798
+ };
799
+ } catch (jsonError) {
800
+ logger_logger.error(`Failed to download ${item.name}@${item.version} json: ${jsonError}`);
801
+ return {
802
+ ...item,
803
+ canTreeShaking: item.canTreeShaking ?? true
804
+ };
805
+ } finally{
806
+ await promises_default().rm(tmpDir, {
807
+ recursive: true,
808
+ force: true
809
+ });
810
+ }
811
+ }));
812
+ return [
813
+ ...cacheUploaded,
814
+ ...hydrated
815
+ ];
816
+ }
817
+ if (!publisher) throw new Error('uploadOptions provided but no projectPublisher configured (configure the selected adapter to enable it or omit uploadOptions)');
818
+ const projectUploadResults = await uploadProject(uploadResults, sharedFilePaths, normalizedConfig, publisher, store);
819
+ return projectUploadResults;
820
+ }
821
+ const buildLimit = external_p_limit_default()(Math.max(1, external_node_os_default().cpus().length));
822
+ const buildRoute = new external_hono_namespaceObject.Hono();
823
+ buildRoute.post('/', (0, zod_validator_namespaceObject.zValidator)('json', ConfigSchema), async (c)=>{
824
+ const logger = c.get('logger');
825
+ const startTime = Date.now();
826
+ const jobId = (0, external_nanoid_namespaceObject.nanoid)();
827
+ logger.info(jobId);
828
+ const body = c.req.valid('json');
829
+ logger.info(JSON.stringify(body));
830
+ const normalizedConfig = normalizeConfig(body);
831
+ const store = c.get('objectStore');
832
+ const publisher = c.get('projectPublisher');
833
+ try {
834
+ const t0 = Date.now();
835
+ const { cacheItems, excludeShared, restConfig } = await retrieveCacheItems(normalizedConfig, 're-shake', store);
836
+ const tRetrieveCache = Date.now();
837
+ logger.info(`retrieveCacheItems took ${tRetrieveCache - t0}ms`);
838
+ let sharedFilePaths = [];
839
+ let dir;
840
+ if (Object.keys(restConfig).length > 0) {
841
+ const buildResult = await buildLimit(()=>runBuild(normalizedConfig, excludeShared, 're-shake'));
842
+ sharedFilePaths = buildResult.sharedFilePaths;
843
+ dir = buildResult.dir;
844
+ }
845
+ const tBuild = Date.now();
846
+ logger.info(`runBuild took ${tBuild - tRetrieveCache}ms`);
847
+ const uploadResults = await upload(sharedFilePaths, cacheItems, normalizedConfig, body.uploadOptions, store, publisher);
848
+ const tUpload = Date.now();
849
+ logger.info(`upload took ${tUpload - tBuild}ms`);
850
+ cleanUp(dir).catch((err)=>{
851
+ logger.error(`Failed to cleanup dir ${dir}: ${err}`);
852
+ });
853
+ const tCleanUp = Date.now();
854
+ logger.info(`cleanUp scheduled (non-blocking) took ${tCleanUp - tUpload}ms`);
855
+ return c.json({
856
+ jobId,
857
+ status: 'success',
858
+ data: uploadResults,
859
+ cached: cacheItems,
860
+ duration: Date.now() - startTime
861
+ });
862
+ } catch (error) {
863
+ if (error instanceof CommandExecutionError) {
864
+ if (137 === error.exitCode) maybePrune();
865
+ return c.json({
866
+ jobId,
867
+ status: 'failed',
868
+ error: error.message,
869
+ command: error.command,
870
+ exitCode: error.exitCode,
871
+ stdout: error.stdout,
872
+ stderr: error.stderr
873
+ });
874
+ }
875
+ return c.json({
876
+ jobId,
877
+ status: 'failed',
878
+ error: error instanceof Error ? error.message : 'Unknown error'
879
+ });
880
+ }
881
+ });
882
+ async function handleCheckTreeshake(c, body) {
883
+ const logger = c.get('logger');
884
+ const startTime = Date.now();
885
+ const jobId = (0, external_nanoid_namespaceObject.nanoid)();
886
+ logger.info(jobId);
887
+ logger.info(JSON.stringify(body));
888
+ const normalizedConfig = normalizeConfig(body);
889
+ const store = c.get('objectStore');
890
+ const publisher = c.get('projectPublisher');
891
+ try {
892
+ const t0 = Date.now();
893
+ const { cacheItems, excludeShared, restConfig } = await retrieveCacheItems(normalizedConfig, 'full', store);
894
+ const tRetrieveCache = Date.now();
895
+ logger.info(`retrieveCacheItems took ${tRetrieveCache - t0}ms`);
896
+ let sharedFilePaths = [];
897
+ let dir;
898
+ if (Object.keys(restConfig).length > 0) {
899
+ const buildResult = await buildLimit(()=>runBuild(normalizedConfig, excludeShared, 'full'));
900
+ sharedFilePaths = buildResult.sharedFilePaths;
901
+ dir = buildResult.dir;
902
+ }
903
+ const tBuild = Date.now();
904
+ logger.info(`runBuild took ${tBuild - tRetrieveCache}ms`);
905
+ const uploadResults = await upload(sharedFilePaths, cacheItems, normalizedConfig, body.uploadOptions, store, publisher);
906
+ const tUpload = Date.now();
907
+ logger.info(`upload took ${tUpload - tBuild}ms`);
908
+ cleanUp(dir).catch((err)=>{
909
+ logger.error(`Failed to cleanup dir ${dir}: ${err}`);
910
+ });
911
+ const tCleanUp = Date.now();
912
+ logger.info(`cleanUp scheduled (non-blocking) took ${tCleanUp - tUpload}ms`);
913
+ return c.json({
914
+ jobId,
915
+ status: 'success',
916
+ data: uploadResults,
917
+ cached: cacheItems,
918
+ duration: Date.now() - startTime
919
+ });
920
+ } catch (error) {
921
+ if (error instanceof CommandExecutionError) {
922
+ if (137 === error.exitCode) maybePrune();
923
+ return c.json({
924
+ jobId,
925
+ status: 'failed',
926
+ error: error.message,
927
+ command: error.command,
928
+ exitCode: error.exitCode,
929
+ stdout: error.stdout,
930
+ stderr: error.stderr
931
+ });
932
+ }
933
+ return c.json({
934
+ jobId,
935
+ status: 'failed',
936
+ error: error instanceof Error ? error.message : 'Unknown error'
937
+ });
938
+ }
939
+ }
940
+ buildRoute.post('/check-tree-shaking', (0, zod_validator_namespaceObject.zValidator)('json', CheckTreeShakingSchema), async (c)=>handleCheckTreeshake(c, c.req.valid('json')));
941
+ const maintenanceRoute = new external_hono_namespaceObject.Hono();
942
+ maintenanceRoute.post('/', async (c)=>{
943
+ const logger = c.get('logger');
944
+ const jobId = (0, external_nanoid_namespaceObject.nanoid)();
945
+ const startTime = Date.now();
946
+ logger.info(jobId);
947
+ await maybePrune();
948
+ return c.json({
949
+ jobId,
950
+ status: 'success',
951
+ duration: Date.now() - startTime
952
+ });
953
+ });
954
+ const routes = new external_hono_namespaceObject.Hono();
955
+ routes.route('/build', buildRoute);
956
+ routes.route('/clean-cache', maintenanceRoute);
957
+ const timeout_namespaceObject = require("hono/timeout");
958
+ function createApp(deps, opts) {
959
+ if (opts?.logger) setLogger(opts.logger);
960
+ setRuntimeEnv(opts?.runtimeEnv ?? process.env);
961
+ const app = new external_hono_namespaceObject.Hono();
962
+ const corsOrigin = opts?.corsOrigin ?? '*';
963
+ const staticRootDir = opts?.staticRootDir ?? DEFAULT_STATIC_ROOT;
964
+ app.use('*', (0, cors_namespaceObject.cors)({
965
+ origin: corsOrigin,
966
+ allowMethods: [
967
+ 'GET',
968
+ 'POST',
969
+ 'OPTIONS'
970
+ ],
971
+ allowHeaders: [
972
+ 'Content-Type',
973
+ 'Authorization'
974
+ ]
975
+ }));
976
+ app.use('*', loggerMiddleware);
977
+ app.use('*', createDiMiddleware(deps));
978
+ app.use('*', (0, timeout_namespaceObject.timeout)(60000));
979
+ if (opts?.appExtensions?.length) for (const extend of opts.appExtensions)extend(app);
980
+ app.get('/tree-shaking-shared/healthz', (c)=>c.json({
981
+ status: 'ok',
982
+ timestamp: new Date().toISOString()
983
+ }));
984
+ app.route('/tree-shaking-shared', routes);
985
+ app.route('/', createStaticRoute({
986
+ rootDir: staticRootDir
987
+ }));
988
+ if (opts?.frontendAdapters?.length) for (const adapter of opts.frontendAdapters)adapter.register(app);
989
+ startPeriodicPrune(opts?.pruneIntervalMs);
990
+ return app;
991
+ }
992
+ const defaultBasePath = '/tree-shaking';
993
+ const embeddedAdapter_contentTypeByExt = (filePath)=>{
994
+ if (filePath.endsWith('.html')) return 'text/html; charset=utf-8';
995
+ if (filePath.endsWith('.js')) return "application/javascript";
996
+ if (filePath.endsWith('.css')) return 'text/css';
997
+ if (filePath.endsWith('.json')) return 'application/json';
998
+ if (filePath.endsWith('.svg')) return 'image/svg+xml';
999
+ if (filePath.endsWith('.png')) return 'image/png';
1000
+ if (filePath.endsWith('.jpg') || filePath.endsWith('.jpeg')) return 'image/jpeg';
1001
+ if (filePath.endsWith('.webp')) return 'image/webp';
1002
+ if (filePath.endsWith('.ico')) return 'image/x-icon';
1003
+ return 'application/octet-stream';
1004
+ };
1005
+ const safeResolve = (rootDir, requestPath)=>{
1006
+ const rootResolved = external_node_path_default().resolve(rootDir);
1007
+ const rel = requestPath.replace(/^\/+/, '');
1008
+ const filePath = external_node_path_default().resolve(rootResolved, rel);
1009
+ if (filePath !== rootResolved && !filePath.startsWith(`${rootResolved}${external_node_path_default().sep}`)) return null;
1010
+ return filePath;
1011
+ };
1012
+ function createEmbeddedFrontendAdapter(opts) {
1013
+ const basePath = opts.basePath ?? defaultBasePath;
1014
+ const normalizedBase = '/' === basePath ? '' : basePath.replace(/\/$/, '');
1015
+ const distDir = opts.distDir;
1016
+ const indexFile = opts.indexFile ?? 'index.html';
1017
+ const spaFallback = opts.spaFallback ?? true;
1018
+ const handler = async (c)=>{
1019
+ let requestPath = c.req.path;
1020
+ try {
1021
+ requestPath = decodeURIComponent(requestPath);
1022
+ } catch {
1023
+ return c.text('Not Found', 404);
1024
+ }
1025
+ let relPath = requestPath;
1026
+ if (normalizedBase && requestPath.startsWith(normalizedBase)) relPath = requestPath.slice(normalizedBase.length);
1027
+ if (!relPath || '/' === relPath) relPath = `/${indexFile}`;
1028
+ const filePath = safeResolve(distDir, relPath);
1029
+ if (filePath) try {
1030
+ const stat = await external_node_fs_default().promises.stat(filePath);
1031
+ if (stat.isFile()) {
1032
+ const buf = await external_node_fs_default().promises.readFile(filePath);
1033
+ return new Response(new Uint8Array(buf), {
1034
+ status: 200,
1035
+ headers: {
1036
+ 'Content-Type': embeddedAdapter_contentTypeByExt(filePath)
1037
+ }
1038
+ });
1039
+ }
1040
+ } catch {}
1041
+ if (!spaFallback) return c.text('Not Found', 404);
1042
+ const fallbackPath = safeResolve(distDir, `/${indexFile}`);
1043
+ if (!fallbackPath) return c.text('Not Found', 404);
1044
+ try {
1045
+ const buf = await external_node_fs_default().promises.readFile(fallbackPath);
1046
+ return new Response(new Uint8Array(buf), {
1047
+ status: 200,
1048
+ headers: {
1049
+ 'Content-Type': embeddedAdapter_contentTypeByExt(fallbackPath)
1050
+ }
1051
+ });
1052
+ } catch {
1053
+ return c.text('Not Found', 404);
1054
+ }
1055
+ };
1056
+ return {
1057
+ id: 'treeshake-embedded-frontend',
1058
+ register (app) {
1059
+ const base = normalizedBase || '/';
1060
+ app.get(base, handler);
1061
+ app.get(`${base}/*`, handler);
1062
+ }
1063
+ };
1064
+ }
1065
+ const node_server_namespaceObject = require("@hono/node-server");
1066
+ function createServer(opts) {
1067
+ const port = opts.port ?? 3000;
1068
+ const hostname = opts.hostname ?? '0.0.0.0';
1069
+ return (0, node_server_namespaceObject.serve)({
1070
+ fetch: opts.app.fetch,
1071
+ port,
1072
+ hostname,
1073
+ overrideGlobalObjects: false
1074
+ });
1075
+ }
1076
+ const hasIndexHtml = (dir)=>Boolean(dir && external_node_fs_default().existsSync(external_node_path_default().join(dir, 'index.html')));
1077
+ const resolveFrontendDistDir = ()=>{
1078
+ const envDir = process.env.TREESHAKE_FRONTEND_DIST;
1079
+ if (envDir) {
1080
+ if (hasIndexHtml(envDir)) return envDir;
1081
+ throw new Error(`TREESHAKE_FRONTEND_DIST is set but index.html is missing: ${envDir}`);
1082
+ }
1083
+ const candidates = [
1084
+ external_node_path_default().resolve(__dirname, 'frontend'),
1085
+ external_node_path_default().resolve(__dirname, '..', 'frontend')
1086
+ ];
1087
+ for (const candidate of candidates)if (hasIndexHtml(candidate)) return candidate;
1088
+ const workspaceCandidates = [
1089
+ external_node_path_default().resolve(process.cwd(), 'packages', 'treeshake-frontend', 'dist'),
1090
+ external_node_path_default().resolve(process.cwd(), 'treeshake-frontend', 'dist')
1091
+ ];
1092
+ for (const candidate of workspaceCandidates)if (hasIndexHtml(candidate)) return candidate;
1093
+ };
1094
+ async function main() {
1095
+ const registry = createOssAdapterRegistry();
1096
+ const resolved = resolveOssEnv({
1097
+ env: {
1098
+ ...process.env,
1099
+ ADAPTER_ID: 'local'
1100
+ },
1101
+ registry,
1102
+ defaultAdapterId: 'local'
1103
+ });
1104
+ const logger = createLogger({
1105
+ level: resolved.logLevel
1106
+ });
1107
+ const deps = await createAdapterDeps({
1108
+ registry,
1109
+ adapterId: resolved.adapterId,
1110
+ adapterConfig: resolved.adapterConfig,
1111
+ logger
1112
+ });
1113
+ const frontendAdapters = [];
1114
+ const distDir = resolveFrontendDistDir();
1115
+ if (!distDir) throw new Error('Treeshake UI dist not found. Rebuild the CLI bundle or set TREESHAKE_FRONTEND_DIST.');
1116
+ frontendAdapters.push(createEmbeddedFrontendAdapter({
1117
+ basePath: process.env.TREESHAKE_FRONTEND_BASE_PATH ?? '/tree-shaking',
1118
+ distDir,
1119
+ spaFallback: '0' !== process.env.TREESHAKE_FRONTEND_SPA_FALLBACK && 'false' !== process.env.TREESHAKE_FRONTEND_SPA_FALLBACK
1120
+ }));
1121
+ const app = createApp(deps, {
1122
+ corsOrigin: resolved.corsOrigin,
1123
+ staticRootDir: resolved.staticRootDir,
1124
+ pruneIntervalMs: resolved.pruneIntervalMs,
1125
+ logger,
1126
+ runtimeEnv: resolved.runtimeEnv,
1127
+ frontendAdapters
1128
+ });
1129
+ createServer({
1130
+ app,
1131
+ port: resolved.port,
1132
+ hostname: resolved.hostname
1133
+ });
1134
+ console.log('Build service listening.');
1135
+ if (frontendAdapters.length) console.log('Treeshake UI available.');
1136
+ }
1137
+ main().catch((err)=>{
1138
+ console.error(err);
1139
+ process.exit(1);
1140
+ });
1141
+ for(var __rspack_i in __webpack_exports__)exports[__rspack_i] = __webpack_exports__[__rspack_i];
1142
+ Object.defineProperty(exports, '__esModule', {
1143
+ value: true
1144
+ });