@module-federation/treeshake-server 0.0.1

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