@blocklet/pages-kit-block-studio 0.1.38 → 0.1.40

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.
@@ -79,9 +79,11 @@ function copyDirectory(src, dest) {
79
79
  const srcPath = path_1.default.join(src, entry.name);
80
80
  const destPath = path_1.default.join(dest, entry.name);
81
81
  if (entry.isDirectory()) {
82
+ // eslint-disable-next-line no-await-in-loop
82
83
  yield copyDirectory(srcPath, destPath);
83
84
  }
84
85
  else {
86
+ // eslint-disable-next-line no-await-in-loop
85
87
  yield copyFile(srcPath, destPath);
86
88
  }
87
89
  }
@@ -46,54 +46,59 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
46
46
  };
47
47
  Object.defineProperty(exports, "__esModule", { value: true });
48
48
  exports.initBlockStudioPlugins = initBlockStudioPlugins;
49
- // eslint-disable-next-line import/no-unresolved
50
49
  // import typescript from '@rollup/plugin-typescript';
50
+ const builtin_module_transformer_1 = require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer");
51
51
  const fs_1 = require("fs");
52
52
  const camelCase_1 = __importDefault(require("lodash/camelCase"));
53
53
  const upperFirst_1 = __importDefault(require("lodash/upperFirst"));
54
+ const p_limit_1 = __importDefault(require("p-limit"));
54
55
  const path = __importStar(require("path"));
55
56
  const rollup_plugin_external_globals_1 = __importDefault(require("rollup-plugin-external-globals"));
57
+ // import { visualizer } from 'rollup-plugin-visualizer';
58
+ const typescript_1 = __importDefault(require("typescript"));
56
59
  const ufo_1 = require("ufo");
60
+ const vite_plugin_node_polyfills_1 = require("vite-plugin-node-polyfills");
57
61
  const vite_plugin_react_pages_1 = __importStar(require("vite-plugin-react-pages"));
58
62
  const helper_1 = require("../utils/helper");
59
63
  const vite_plugin_html_transform_1 = require("./vite-plugin-html-transform");
60
- // const BUILTIN_MODULES_VAR = '__PAGES_KIT_BUILTIN_MODULES__';
61
- // import initRemoteScriptLocalizerPlugin from './vite-plugin-remote-script-localizer';
64
+ const BUILTIN_MODULES_VAR = '__PAGES_KIT_BUILTIN_MODULES__';
65
+ helper_1.logger.log('BUILTIN_MODULES_VAR', BUILTIN_MODULES_VAR);
62
66
  const defaultBlockExternals = {
63
67
  // 核心 React 相关
64
- react: `@blocklet/pages-kit/builtin/react`,
65
- // 'react-dom': `@blocklet/pages-kit/builtin/react-dom`,
66
- 'react-router-dom': `@blocklet/pages-kit/builtin/react-router-dom`,
67
- // 'react-hook-form': `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/react-hook-form"]`,
68
- // 'react-wrap-balancer': `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/react-wrap-balancer"]`,
68
+ react: '@blocklet/pages-kit/builtin/react',
69
+ 'react-router-dom': '@blocklet/pages-kit/builtin/react-router-dom',
70
+ 'react-hook-form': '@blocklet/pages-kit/builtin/react-hook-form',
71
+ 'react-wrap-balancer': '@blocklet/pages-kit/builtin/react-wrap-balancer',
69
72
  // // ArcBlock 相关
70
- // '@arcblock/ux': `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/arcblock/ux"]`,
71
- // '@arcblock/did-connect/lib/Session': `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/session"]`,
72
- // '@arcblock/ux/lib/Locale/context': `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/locale"]`,
73
- // // MUI 相关
74
- // // '@mui/material': `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/mui/material"]`,
75
- // // '@mui/lab': `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/mui/lab"]`,
76
- // // 其他工具库
77
- // dayjs: `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/dayjs"]`,
78
- // zustand: `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/zustand"]`,
79
- // 'zustand/middleware/immer': `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/zustand/middleware/immer"]`,
80
- // immer: `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/immer"]`,
81
- // stream: `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/stream"]`,
82
- // '@iconify/react': `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/iconify/react"]`,
83
- // // 页面相关组件
84
- // '@blocklet/pages-kit/builtin/components': `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/components"]`,
85
- // '@blocklet/pages-kit/builtin/page/header': `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/page/header"]`,
86
- // '@blocklet/pages-kit/builtin/pages-kit': `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/pages-kit"]`,
87
- // // 异步组件
88
- // 'react-markdown': `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/async/react-markdown"]`,
89
- // 'react-syntax-highlighter': `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/async/react-syntax-highlighter"]`,
90
- // 'react-scroll-to-bottom': `window.${BUILTIN_MODULES_VAR}.modules["@blocklet/pages-kit/builtin/async/react-scroll-to-bottom"]`,
91
- // // 浏览器原生
92
- crypto: 'window.crypto',
73
+ '@arcblock/ux': '@blocklet/pages-kit/builtin/arcblock/ux',
74
+ '@arcblock/did-connect/lib/Session': '@blocklet/pages-kit/builtin/session',
75
+ '@arcblock/ux/lib/Locale/context': '@blocklet/pages-kit/builtin/locale',
76
+ // MUI 相关
77
+ '@mui/material': '@blocklet/pages-kit/builtin/mui/material',
78
+ '@mui/lab': '@blocklet/pages-kit/builtin/mui/lab',
79
+ // 其他工具库
80
+ dayjs: '@blocklet/pages-kit/builtin/dayjs',
81
+ zustand: '@blocklet/pages-kit/builtin/zustand',
82
+ 'zustand/middleware/immer': '@blocklet/pages-kit/builtin/zustand/middleware/immer',
83
+ immer: '@blocklet/pages-kit/builtin/immer',
84
+ stream: '@blocklet/pages-kit/builtin/stream',
85
+ '@iconify/react': '@blocklet/pages-kit/builtin/iconify/react',
86
+ // 页面相关组件
87
+ '@blocklet/pages-kit/builtin/components': '@blocklet/pages-kit/builtin/components',
88
+ '@blocklet/pages-kit/builtin/page/header': '@blocklet/pages-kit/builtin/page/header',
89
+ '@blocklet/pages-kit/builtin/pages-kit': '@blocklet/pages-kit/builtin/pages-kit',
90
+ '@blocklet/pages-kit/builtin/async/ai-runtime': '@blocklet/pages-kit/builtin/async/ai-runtime',
91
+ // 异步组件
92
+ 'react-markdown': '@blocklet/pages-kit/builtin/async/react-markdown',
93
+ 'react-syntax-highlighter': '@blocklet/pages-kit/builtin/async/react-syntax-highlighter',
94
+ 'react-scroll-to-bottom': '@blocklet/pages-kit/builtin/async/react-scroll-to-bottom',
95
+ '@blocklet/pages-kit': '@blocklet/pages-kit',
93
96
  };
94
97
  function initBlockStudioPlugins(options) {
98
+ var _a, _b;
95
99
  const workingDir = (options === null || options === void 0 ? void 0 : options.cwd) || process.cwd();
96
100
  const entryFilesPattern = (options === null || options === void 0 ? void 0 : options.entryFilesPattern) || (0, helper_1.getBlockEntryFilesPattern)();
101
+ const transpileBuiltinModule = (_a = options === null || options === void 0 ? void 0 : options.transpileBuiltinModule) !== null && _a !== void 0 ? _a : true;
97
102
  // 处理 blockExternals 参数
98
103
  let externalMappings = defaultBlockExternals;
99
104
  if (typeof (options === null || options === void 0 ? void 0 : options.blockExternals) === 'function') {
@@ -112,14 +117,41 @@ function initBlockStudioPlugins(options) {
112
117
  entryFilesPattern: (0, helper_1.getBlockEntryFilesPattern)(),
113
118
  pagesDir,
114
119
  blockExternals: externalMappings, // 添加日志输出
120
+ transpileBuiltinModule,
115
121
  });
116
122
  // 为 globals 创建一个无前缀的版本
117
- const externalMappingsWithoutWindow = Object.fromEntries(Object.entries(externalMappings).filter(([, value]) => !value.startsWith('window.')));
118
- const externalMappingsWithWindow = Object.fromEntries(Object.entries(externalMappings).filter(([, value]) => value.startsWith('window.')));
119
- console.warn({
120
- externalMappingsWithoutWindow,
121
- externalMappingsWithWindow,
122
- });
123
+ const pathMappings = Object.fromEntries(Object.entries(externalMappings).filter(([, value]) => !value.startsWith('window.') && value.length > 0));
124
+ const externalGlobalMappings = Object.fromEntries(Object.entries(externalMappings).filter(([, value]) => value.startsWith('window.') && value.length > 0));
125
+ const globalsMappings = Object.fromEntries(Object.entries(externalMappings)
126
+ .map(([key, value]) => {
127
+ if (!(value === null || value === void 0 ? void 0 : value.length)) {
128
+ return [];
129
+ }
130
+ // 移除 "window." 前缀并转换为首字母大写的驼峰式
131
+ const rawName = String(key);
132
+ const globalName = (0, upperFirst_1.default)((0, camelCase_1.default)(rawName));
133
+ return [key, globalName];
134
+ })
135
+ .filter((item) => item.length > 0));
136
+ const filterModules = process.argv.includes('--filter')
137
+ ? (_b = process.argv[process.argv.indexOf('--filter') + 1]) === null || _b === void 0 ? void 0 : _b.split(',')
138
+ : null;
139
+ const entryList = (0, helper_1.findComponentFiles)({ cwd: workingDir })
140
+ .map((entry) => {
141
+ const { blockName } = entry;
142
+ const { isHtml } = entry;
143
+ const { file } = entry;
144
+ if (isHtml) {
145
+ return [blockName, `${vite_plugin_html_transform_1.VIRTUAL_MODULE_ID}?dir=${path.dirname(file)}`];
146
+ }
147
+ return [blockName, path.resolve(workingDir, file)];
148
+ })
149
+ .filter(Boolean)
150
+ .filter(([blockName]) => !filterModules || filterModules.includes(blockName || ''));
151
+ // @ts-ignore
152
+ const multiMode = entryList.length > 1;
153
+ const formats = (options === null || options === void 0 ? void 0 : options.formats) || ['es', multiMode ? 'cjs' : 'umd'];
154
+ // @ts-ignore
123
155
  return [
124
156
  // {
125
157
  // name: 'vite-plugin-block-studio-dev',
@@ -135,6 +167,9 @@ function initBlockStudioPlugins(options) {
135
167
  // return html;
136
168
  // },
137
169
  // },
170
+ (0, vite_plugin_node_polyfills_1.nodePolyfills)({
171
+ include: ['crypto'],
172
+ }),
138
173
  {
139
174
  name: 'vite-plugin-block-studio-build',
140
175
  apply: 'build',
@@ -142,50 +177,53 @@ function initBlockStudioPlugins(options) {
142
177
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
143
178
  config(_config) {
144
179
  return __awaiter(this, void 0, void 0, function* () {
145
- var _a, _b, _c, _d;
146
- const filterModules = process.argv.includes('--filter')
147
- ? (_a = process.argv[process.argv.indexOf('--filter') + 1]) === null || _a === void 0 ? void 0 : _a.split(',')
148
- : null;
180
+ var _a, _b, _c, _d, _e;
149
181
  const name = yield Promise.resolve(`${`${workingDir}/package.json`}`).then(s => __importStar(require(s))).then((res) => res.name).catch(() => 'MyLib');
150
- const entryList = (0, helper_1.findComponentFiles)({ cwd: workingDir })
151
- .map((entry) => {
152
- const { blockName } = entry;
153
- const { isHtml } = entry;
154
- const { file } = entry;
155
- if (isHtml) {
156
- return [blockName, `${vite_plugin_html_transform_1.VIRTUAL_MODULE_ID}?dir=${path.dirname(file)}`];
157
- }
158
- return [blockName, path.resolve(workingDir, file)];
159
- })
160
- .filter(Boolean)
161
- .filter(([blockName]) => !filterModules || filterModules.includes(blockName || ''));
162
- const multiMode = entryList.length > 1;
163
182
  return {
164
- build: Object.assign(Object.assign({}, _config === null || _config === void 0 ? void 0 : _config.build), { cssCodeSplit: false, lib: {
183
+ resolve: {
184
+ alias: {
185
+ // crypto: 'crypto-browserify',
186
+ },
187
+ },
188
+ optimizeDeps: {
189
+ // include: ['crypto-browserify'],
190
+ },
191
+ build: Object.assign(Object.assign({}, _config === null || _config === void 0 ? void 0 : _config.build), {
192
+ // sourcemap: true,
193
+ cssCodeSplit: false, lib: {
165
194
  name,
166
195
  entry: Object.assign({}, Object.fromEntries(entryList)),
167
- formats: ['es', !multiMode ? 'umd' : 'cjs'],
196
+ formats,
168
197
  fileName: (format, entryName) => `${format}/${entryName}.js`,
169
- }, rollupOptions: Object.assign(Object.assign({}, (_b = _config === null || _config === void 0 ? void 0 : _config.build) === null || _b === void 0 ? void 0 : _b.rollupOptions), { external: [...Object.keys(externalMappings)], output: Object.assign(Object.assign({}, (_d = (_c = _config === null || _config === void 0 ? void 0 : _config.build) === null || _c === void 0 ? void 0 : _c.rollupOptions) === null || _d === void 0 ? void 0 : _d.output), { chunkFileNames: () => {
198
+ }, terserOptions: {
199
+ // 保留导出名
200
+ keep_fnames: true,
201
+ keep_classnames: true,
202
+ }, rollupOptions: Object.assign(Object.assign({}, (_a = _config === null || _config === void 0 ? void 0 : _config.build) === null || _a === void 0 ? void 0 : _a.rollupOptions), { external: ((_c = (_b = _config === null || _config === void 0 ? void 0 : _config.build) === null || _b === void 0 ? void 0 : _b.rollupOptions) === null || _c === void 0 ? void 0 : _c.external) ||
203
+ ((id) => {
204
+ // 是否匹配后缀
205
+ const isMatchAfterSlash = false;
206
+ const skipList = [...Object.keys(externalMappings)];
207
+ if (skipList.some((item) => (isMatchAfterSlash && id.startsWith(`${item}/`)) || id === item)) {
208
+ return true;
209
+ }
210
+ return false;
211
+ }), treeshake: true, output: Object.assign(Object.assign({}, (_e = (_d = _config === null || _config === void 0 ? void 0 : _config.build) === null || _d === void 0 ? void 0 : _d.rollupOptions) === null || _e === void 0 ? void 0 : _e.output), { chunkFileNames: () => {
170
212
  return '[format]/_chunks/[name]-[hash].js';
171
213
  },
172
214
  // 使用没有 window. 前缀的映射用于 globals 配置
173
- globals: Object.fromEntries(Object.entries(externalMappings).map(([key]) => {
174
- // 移除 "window." 前缀并转换为首字母大写的驼峰式
175
- const rawName = String(key);
176
- const globalName = (0, upperFirst_1.default)((0, camelCase_1.default)(rawName));
177
- return [key, globalName];
178
- })),
215
+ globals: globalsMappings,
179
216
  // 确保正确处理命名导出和默认导出
180
- interop: 'auto', paths: externalMappingsWithoutWindow }) }) }),
217
+ interop: 'auto', paths: pathMappings, esModule: true }) }) }),
181
218
  };
182
219
  });
183
220
  },
184
221
  configResolved(config) {
185
- console.info(config.build.rollupOptions);
222
+ helper_1.logger.info('config.build', config.build);
186
223
  },
187
224
  },
188
- Object.assign(Object.assign({}, (0, rollup_plugin_external_globals_1.default)(externalMappingsWithWindow)), { apply: 'build', enforce: 'post' }),
225
+ transpileBuiltinModule
226
+ ? Object.assign(Object.assign({}, (0, rollup_plugin_external_globals_1.default)(externalGlobalMappings)), { apply: 'build', enforce: 'pre' }) : undefined,
189
227
  // @ts-ignore
190
228
  (0, vite_plugin_react_pages_1.default)({
191
229
  pagesDir,
@@ -240,11 +278,74 @@ function initBlockStudioPlugins(options) {
240
278
  name: 'build-force-exit',
241
279
  apply: 'build',
242
280
  enforce: 'post',
281
+ writeBundle(options) {
282
+ // 对所有生成的 JavaScript 文件进行 transpileModule 处理
283
+ const transpileBuiltinModuleFn = (dir, format) => {
284
+ const files = (0, fs_1.readdirSync)(dir);
285
+ files.forEach((file) => {
286
+ const filePath = path.join(dir, file);
287
+ const stats = (0, fs_1.statSync)(filePath);
288
+ if (stats.isDirectory()) {
289
+ transpileBuiltinModuleFn(filePath, format); // 递归处理子目录
290
+ }
291
+ else if (file.endsWith('.js')) {
292
+ try {
293
+ const script = (0, fs_1.readFileSync)(filePath, 'utf8');
294
+ const moduleMap = {
295
+ es: typescript_1.default.ModuleKind.ESNext,
296
+ cjs: typescript_1.default.ModuleKind.CommonJS,
297
+ umd: typescript_1.default.ModuleKind.ESNext,
298
+ };
299
+ const code = typescript_1.default.transpileModule(script, {
300
+ compilerOptions: {
301
+ jsx: typescript_1.default.JsxEmit.React,
302
+ target: typescript_1.default.ScriptTarget.ES2016,
303
+ module: moduleMap[format],
304
+ },
305
+ transformers: {
306
+ // @ts-ignore
307
+ before: [(0, builtin_module_transformer_1.createBuiltinModuleTransformer)(typescript_1.default)],
308
+ },
309
+ }).outputText;
310
+ (0, fs_1.writeFileSync)(filePath, code);
311
+ helper_1.logger.info(`Transpiled: ${filePath}`);
312
+ // updateStatus(`Transpiled: ${filePath}`);
313
+ }
314
+ catch (error) {
315
+ helper_1.logger.error(`Failed to transpile ${filePath}:`, error);
316
+ }
317
+ }
318
+ });
319
+ };
320
+ // 获取输出目录
321
+ const outDir = options.dir || 'dist';
322
+ const limit = (0, p_limit_1.default)(20);
323
+ formats.forEach((format) => {
324
+ const formatDir = path.resolve(outDir, `${format}`);
325
+ const chunkDir = path.resolve(formatDir, '_chunks');
326
+ // if not exists, create it
327
+ if (!(0, fs_1.existsSync)(chunkDir)) {
328
+ (0, fs_1.mkdirSync)(chunkDir, { recursive: true });
329
+ }
330
+ if (transpileBuiltinModule) {
331
+ limit(() => transpileBuiltinModuleFn(formatDir, format));
332
+ }
333
+ });
334
+ },
243
335
  closeBundle() {
244
336
  // ensure vite build exit
245
- process.exit(0);
337
+ setTimeout(() => {
338
+ // wait for 1 second, to ensure all logs are flushed
339
+ process.exit(0);
340
+ }, 1000);
246
341
  },
247
342
  },
248
- ];
343
+ // visualizer({
344
+ // filename: 'dist/stats.html',
345
+ // open: true,
346
+ // gzipSize: true,
347
+ // brotliSize: true,
348
+ // }),
349
+ ].filter(Boolean);
249
350
  }
250
351
  exports.default = initBlockStudioPlugins;
@@ -111,6 +111,7 @@ function initRemoteScriptLocalizerPlugin(options = {}) {
111
111
  }
112
112
  }));
113
113
  downloadQueue.push(...promises);
114
+ // eslint-disable-next-line no-await-in-loop
114
115
  yield Promise.all(promises);
115
116
  }
116
117
  return results;