@blocklet/pages-kit-block-studio 0.4.82 → 0.4.84

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.
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DEFAULT_BLOCK_ENTRY_FILES_PATTERN = exports.NANOID_LENGTH = exports.PREVIEW_IMAGE_DIR = exports.METADATA_FILE_NAME = exports.libDir = exports.NEW_BLOCK_TEMPLATE_METADATA_PATH = exports.NEW_BLOCK_TEMPLATE_PATH = exports.MEDIA_KIT_RESOURCE_TYPE = exports.MEDIA_KIT_DID = exports.PAGES_KIT_BLOCK_STUDIO_RESOURCE_TYPE = exports.PAGES_KIT_BLOCK_STUDIO_DID = exports.PAGES_KIT_RESOURCE_TYPE = exports.PAGES_KIT_DID = void 0;
6
+ exports.PAGES_KIT_STATE_STATE_DIR = exports.IGNORE_WATCH_PREFIX = exports.DEFAULT_BLOCK_ENTRY_FILES_PATTERN = exports.NANOID_LENGTH = exports.PREVIEW_IMAGE_DIR = exports.METADATA_FILE_NAME = exports.libDir = exports.NEW_BLOCK_TEMPLATE_METADATA_PATH = exports.NEW_BLOCK_TEMPLATE_PATH = exports.MEDIA_KIT_RESOURCE_TYPE = exports.MEDIA_KIT_DID = exports.PAGES_KIT_BLOCK_STUDIO_RESOURCE_TYPE = exports.PAGES_KIT_BLOCK_STUDIO_DID = exports.PAGES_KIT_RESOURCE_TYPE = exports.PAGES_KIT_DID = void 0;
7
7
  const path_1 = __importDefault(require("path"));
8
8
  exports.PAGES_KIT_DID = 'z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o';
9
9
  exports.PAGES_KIT_RESOURCE_TYPE = 'page';
@@ -18,3 +18,5 @@ exports.METADATA_FILE_NAME = '@metadata.json';
18
18
  exports.PREVIEW_IMAGE_DIR = '@preview-images';
19
19
  exports.NANOID_LENGTH = 16;
20
20
  exports.DEFAULT_BLOCK_ENTRY_FILES_PATTERN = 'src/**/index.{ts,tsx}';
21
+ exports.IGNORE_WATCH_PREFIX = ['@del-*', '@tmp-*', '.*', 'staging', 'production', '@backup-*'];
22
+ exports.PAGES_KIT_STATE_STATE_DIR = 'site-state';
@@ -171,17 +171,21 @@ exports.initResourceRouter.post('/', async (req, res) => {
171
171
  fs_1.default.mkdirSync(componentsDir, { recursive: true });
172
172
  const chunksDir = (0, path_1.join)(tmpPackage, 'chunks');
173
173
  fs_1.default.mkdirSync(chunksDir, { recursive: true });
174
+ const chunksMapPath = (0, path_1.join)(codeDir, 'chunks-map.json');
175
+ const chunksMap = JSON.parse(fs_1.default.readFileSync(chunksMapPath, 'utf8'));
174
176
  // get @metadata.json by glob
175
177
  const canUseComponents = (0, helper_1.findComponentFiles)({ cwd: rootDir, filter: componentIds });
176
178
  // Filter and process metadata files
177
179
  const metadataList = canUseComponents.map(({ fullPath, blockName, metadata: _metadata }) => {
178
180
  // get metadata
179
181
  const metadata = _metadata;
182
+ const jsName = `${blockName}.js`;
180
183
  // get code to metadata
181
- const code = fs_1.default.readFileSync((0, path_1.join)(codeDir, `${blockName}.js`), 'utf8');
184
+ const code = fs_1.default.readFileSync((0, path_1.join)(codeDir, jsName), 'utf8');
182
185
  if (code) {
183
186
  (0, set_1.default)(metadata, 'renderer.script', code);
184
187
  (0, set_1.default)(metadata, 'renderer.type', 'react-component');
188
+ (0, set_1.default)(metadata, 'renderer.chunks', chunksMap[jsName] || []);
185
189
  }
186
190
  // write metadata to metadataPath
187
191
  const metadataYmlPath = path_1.default.join(componentsDir, `${metadata.name || 'unnamed'}.${metadata.id}.yml`);
@@ -196,8 +200,8 @@ exports.initResourceRouter.post('/', async (req, res) => {
196
200
  }
197
201
  return metadata;
198
202
  });
199
- // cp _chunks dir
200
- await copyRecursive((0, path_1.join)(codeDir, '_chunks'), chunksDir);
203
+ // cp chunks dir
204
+ await copyRecursive((0, path_1.join)(codeDir, 'chunks'), chunksDir);
201
205
  // write pages.config.yml
202
206
  const pagesConfigPath = path_1.default.join(tmpPackage, '.blocklet/pages/pages.config.yml');
203
207
  fs_1.default.mkdirSync(path_1.default.dirname(pagesConfigPath), { recursive: true });
@@ -32,10 +32,15 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
35
38
  Object.defineProperty(exports, "__esModule", { value: true });
36
39
  exports.initUploaderRouter = void 0;
40
+ const config_1 = __importDefault(require("@blocklet/sdk/lib/config"));
37
41
  const uploader_server_1 = require("@blocklet/uploader-server");
38
42
  const express_1 = __importStar(require("express"));
43
+ const path_1 = require("path");
39
44
  const constants_1 = require("../constants");
40
45
  // init uploader router
41
46
  exports.initUploaderRouter = (0, express_1.Router)();
@@ -63,12 +68,31 @@ const staticResourceMiddleware = (0, uploader_server_1.initStaticResourceMiddlew
63
68
  },
64
69
  ],
65
70
  });
71
+ // will proxy to pages kit data dir each project's chunks folder
72
+ const dynamicResourceMiddleware = (0, uploader_server_1.initDynamicResourceMiddleware)({
73
+ // 这个中间件只会作用到 PAGES_KIT_DID 的资源
74
+ componentDid: constants_1.PAGES_KIT_DID,
75
+ resourcePaths: [
76
+ {
77
+ // * is project id
78
+ path: (0, path_1.join)(config_1.default.env.dataDir, constants_1.PAGES_KIT_STATE_STATE_DIR, '*', 'production', 'chunks'),
79
+ whitelist: ['.js', '.css', '.png', '.json'], // 可选,只处理这些后缀的文件
80
+ },
81
+ ],
82
+ watchOptions: {
83
+ ignorePatterns: constants_1.IGNORE_WATCH_PREFIX, // 使用 IGNORE_WATCH_PREFIX 作为忽略模式, 忽略一些临时路径
84
+ },
85
+ cacheOptions: {
86
+ maxAge: '365d',
87
+ immutable: true,
88
+ },
89
+ });
66
90
  exports.initUploaderRouter.use('/uploads', (0, uploader_server_1.initProxyToMediaKitUploadsMiddleware)({
67
91
  express: express_1.default,
68
92
  }), staticResourceMiddleware, (_req, res) => {
69
93
  res.status(404).send('404 NOT FOUND').end();
70
94
  });
71
- exports.initUploaderRouter.use('/chunks', staticResourceMiddleware, (_req, res) => {
95
+ exports.initUploaderRouter.use('/chunks', dynamicResourceMiddleware, staticResourceMiddleware, (_req, res) => {
72
96
  res.status(404).send('CHUNK NOT FOUND').end();
73
97
  });
74
98
  exports.default = exports.initUploaderRouter;
@@ -39,11 +39,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.initBlockStudioPlugins = initBlockStudioPlugins;
40
40
  // import typescript from '@rollup/plugin-typescript';
41
41
  const builtin_module_transformer_1 = require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer");
42
+ // @ts-ignore
43
+ const chunks_analyzer_transformer_1 = require("@blocklet/pages-kit/utils/typescript/chunks-analyzer-transformer");
42
44
  const fs_1 = require("fs");
43
45
  const camelCase_1 = __importDefault(require("lodash/camelCase"));
44
46
  const upperFirst_1 = __importDefault(require("lodash/upperFirst"));
45
47
  const p_limit_1 = __importDefault(require("p-limit"));
46
48
  const path = __importStar(require("path"));
49
+ const path_1 = require("path");
47
50
  const rollup_plugin_external_globals_1 = __importDefault(require("rollup-plugin-external-globals"));
48
51
  // import { visualizer } from 'rollup-plugin-visualizer';
49
52
  const typescript_1 = __importDefault(require("typescript"));
@@ -213,7 +216,7 @@ function initBlockStudioPlugins(options) {
213
216
  output: {
214
217
  ..._config?.build?.rollupOptions?.output,
215
218
  chunkFileNames: () => {
216
- return '[format]/_chunks/[name]-[hash].js';
219
+ return '[format]/chunks/[name]-[hash].js';
217
220
  },
218
221
  // 使用没有 window. 前缀的映射用于 globals 配置
219
222
  globals: globalsMappings,
@@ -304,7 +307,9 @@ function initBlockStudioPlugins(options) {
304
307
  name: 'post-build-file-transpiler',
305
308
  apply: 'build',
306
309
  enforce: 'post',
307
- writeBundle(options) {
310
+ async writeBundle(options) {
311
+ // 用于存储每个格式的 chunks 映射
312
+ const allChunksMap = {};
308
313
  // 对所有生成的 JavaScript 文件进行 transpileModule 处理
309
314
  const transpileBuiltinModuleFn = (dir, format) => {
310
315
  const files = (0, fs_1.readdirSync)(dir);
@@ -317,6 +322,10 @@ function initBlockStudioPlugins(options) {
317
322
  else if (file.endsWith('.js')) {
318
323
  try {
319
324
  const script = (0, fs_1.readFileSync)(filePath, 'utf8');
325
+ // @ts-ignore
326
+ const chunks = (0, chunks_analyzer_transformer_1.analyzeFileChunks)(typescript_1.default, script);
327
+ // ensure chunksMap is with all chunks
328
+ allChunksMap[(0, path_1.basename)(filePath)] = new Set(chunks);
320
329
  const moduleMap = {
321
330
  es: typescript_1.default.ModuleKind.ESNext,
322
331
  cjs: typescript_1.default.ModuleKind.CommonJS,
@@ -342,20 +351,70 @@ function initBlockStudioPlugins(options) {
342
351
  }
343
352
  }
344
353
  });
354
+ // 返回一个 Promise 以便 await
355
+ return new Promise((resolve, reject) => {
356
+ try {
357
+ // ... 处理文件的代码 ...
358
+ resolve();
359
+ }
360
+ catch (error) {
361
+ reject(error);
362
+ }
363
+ });
345
364
  };
346
365
  // 获取输出目录
347
366
  const outDir = options.dir || 'dist';
348
367
  const limit = (0, p_limit_1.default)(20);
349
- formats.forEach((format) => {
368
+ // 使用 Promise.all 等待所有格式处理完成
369
+ await Promise.all(formats.map(async (format) => {
350
370
  const formatDir = path.resolve(outDir, `${format}`);
351
- const chunkDir = path.resolve(formatDir, '_chunks');
371
+ const chunkDir = path.resolve(formatDir, 'chunks');
352
372
  // if not exists, create it
353
373
  if (!(0, fs_1.existsSync)(chunkDir)) {
354
374
  (0, fs_1.mkdirSync)(chunkDir, { recursive: true });
355
375
  }
356
376
  if (transpileBuiltinModule) {
357
- limit(() => transpileBuiltinModuleFn(formatDir, format));
377
+ await limit(() => transpileBuiltinModuleFn(formatDir, format));
378
+ }
379
+ }));
380
+ // 现在可以处理完整依赖链
381
+ helper_1.logger.info('all transpile tasks done, start to handle dependency chain...');
382
+ // 在这里处理 allChunksMap 的完整依赖链
383
+ Object.entries(allChunksMap).forEach(([entryFile, directDeps]) => {
384
+ // 收集所有间接依赖
385
+ const allDeps = [...directDeps];
386
+ // 递归寻找间接依赖
387
+ function findTransitiveDeps(chunks) {
388
+ chunks.forEach((chunk) => {
389
+ // 如果该chunk本身也是个入口(有依赖列表)
390
+ if (chunk in allChunksMap) {
391
+ const subDeps = allChunksMap[chunk];
392
+ // 添加未包含的依赖
393
+ if (subDeps) {
394
+ subDeps.forEach((dep) => {
395
+ if (!allDeps.includes(dep)) {
396
+ allDeps.push(dep);
397
+ // 递归寻找这个依赖的依赖
398
+ findTransitiveDeps([dep]);
399
+ }
400
+ });
401
+ }
402
+ }
403
+ });
358
404
  }
405
+ // 开始递归查找
406
+ findTransitiveDeps([...directDeps]);
407
+ // 更新为完整依赖列表
408
+ allChunksMap[entryFile] = new Set(allDeps);
409
+ });
410
+ // 转换 Set 为数组以便正确序列化
411
+ const serializedMap = Object.entries(allChunksMap).reduce((result, [key, deps]) => {
412
+ result[key] = Array.from(deps);
413
+ return result;
414
+ }, {});
415
+ formats.forEach((format) => {
416
+ // 存下来
417
+ (0, fs_1.writeFileSync)(path.join(outDir, `${format}/chunks-map.json`), JSON.stringify(serializedMap, null, 2));
359
418
  });
360
419
  },
361
420
  closeBundle() {