@blocklet/pages-kit-block-studio 0.6.1 → 0.6.3

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.
@@ -39,7 +39,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
39
39
  return (mod && mod.__esModule) ? mod : { "default": mod };
40
40
  };
41
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
- exports.getEditComponentBlockName = exports.EDIT_COMPONENT_BUNDLE_FLAG = exports.EDIT_COMPONENT_NAME = exports.safeParse = exports.getBlockCode = exports.getPreviewImageRelativePath = exports.downloadAsset = exports.isMetadataFile = exports.isDev = exports.isPathSafe = exports.logger = void 0;
42
+ exports.getGetServerSidePropsBlockName = exports.GET_SERVER_SIDE_PROPS_NAME = exports.getAigneOutputValueSchemaBlockName = exports.AIGNE_OUTPUT_VALUE_SCHEMA_NAME = exports.getPropertiesSchemaBlockName = exports.PROPERTIES_SCHEMA_NAME = exports.getEditComponentBlockName = exports.EDIT_COMPONENT_NAME = exports.safeParse = exports.getBlockCode = exports.getPreviewImageRelativePath = exports.downloadAsset = exports.isMetadataFile = exports.isDev = exports.isPathSafe = exports.logger = void 0;
43
43
  exports.setBlockEntryFilesPattern = setBlockEntryFilesPattern;
44
44
  exports.getBlockEntryFilesPattern = getBlockEntryFilesPattern;
45
45
  exports.getWatchFilesDir = getWatchFilesDir;
@@ -240,8 +240,22 @@ const safeParse = (text) => {
240
240
  };
241
241
  exports.safeParse = safeParse;
242
242
  exports.EDIT_COMPONENT_NAME = 'EditComponent';
243
- exports.EDIT_COMPONENT_BUNDLE_FLAG = `(${exports.EDIT_COMPONENT_NAME})`;
244
243
  const getEditComponentBlockName = (blockName) => {
245
- return `${blockName}${exports.EDIT_COMPONENT_BUNDLE_FLAG}`;
244
+ return `${blockName}(${exports.EDIT_COMPONENT_NAME})`;
246
245
  };
247
246
  exports.getEditComponentBlockName = getEditComponentBlockName;
247
+ exports.PROPERTIES_SCHEMA_NAME = 'PROPERTIES_SCHEMA';
248
+ const getPropertiesSchemaBlockName = (blockName) => {
249
+ return `${blockName}(${exports.PROPERTIES_SCHEMA_NAME})`;
250
+ };
251
+ exports.getPropertiesSchemaBlockName = getPropertiesSchemaBlockName;
252
+ exports.AIGNE_OUTPUT_VALUE_SCHEMA_NAME = 'aigneOutputValueSchema';
253
+ const getAigneOutputValueSchemaBlockName = (blockName) => {
254
+ return `${blockName}(${exports.AIGNE_OUTPUT_VALUE_SCHEMA_NAME})`;
255
+ };
256
+ exports.getAigneOutputValueSchemaBlockName = getAigneOutputValueSchemaBlockName;
257
+ exports.GET_SERVER_SIDE_PROPS_NAME = 'getServerSideProps';
258
+ const getGetServerSidePropsBlockName = (blockName) => {
259
+ return `${blockName}(${exports.GET_SERVER_SIDE_PROPS_NAME})`;
260
+ };
261
+ exports.getGetServerSidePropsBlockName = getGetServerSidePropsBlockName;
@@ -6,7 +6,7 @@ import fs from 'fs';
6
6
  import get from 'lodash/get';
7
7
  import set from 'lodash/set';
8
8
  import path, { join, basename } from 'path';
9
- import { findComponentFiles, libDir, getPreviewImageRelativePath, generateYaml, logger, getEditComponentBlockName, } from '../utils/helper';
9
+ import { findComponentFiles, libDir, getPreviewImageRelativePath, generateYaml, logger, getEditComponentBlockName, getAigneOutputValueSchemaBlockName, getPropertiesSchemaBlockName, getGetServerSidePropsBlockName, } from '../utils/helper';
10
10
  const DID = 'z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM';
11
11
  const RESOURCE_TYPE = 'page';
12
12
  const allTag = '@ALL_COMPONENTS';
@@ -144,6 +144,8 @@ initResourceRouter.post('/', async (req, res) => {
144
144
  // get metadata
145
145
  const metadata = _metadata;
146
146
  const jsName = `${blockName}.js`;
147
+ // set version to 2
148
+ set(metadata, 'version', 2);
147
149
  // get code to metadata
148
150
  const code = fs.readFileSync(join(codeDir, jsName), 'utf8');
149
151
  if (code) {
@@ -165,6 +167,39 @@ initResourceRouter.post('/', async (req, res) => {
165
167
  catch (error) {
166
168
  // ignore error
167
169
  }
170
+ // get aigne output value schema
171
+ try {
172
+ const aigneOutputValueSchemaJsName = `${getAigneOutputValueSchemaBlockName(blockName)}.js`;
173
+ const aigneOutputValueSchemaCode = fs.readFileSync(join(codeDir, aigneOutputValueSchemaJsName), 'utf8');
174
+ if (aigneOutputValueSchemaCode) {
175
+ set(metadata, 'renderer.aigneOutputValueSchema', aigneOutputValueSchemaCode);
176
+ }
177
+ }
178
+ catch (error) {
179
+ // ignore error
180
+ }
181
+ // get properties schema
182
+ try {
183
+ const propertiesSchemaJsName = `${getPropertiesSchemaBlockName(blockName)}.js`;
184
+ const propertiesSchemaCode = fs.readFileSync(join(codeDir, propertiesSchemaJsName), 'utf8');
185
+ if (propertiesSchemaCode) {
186
+ set(metadata, 'renderer.PROPERTIES_SCHEMA', propertiesSchemaCode);
187
+ }
188
+ }
189
+ catch (error) {
190
+ // ignore error
191
+ }
192
+ // get getServerSideProps
193
+ try {
194
+ const getServerSidePropsJsName = `${getGetServerSidePropsBlockName(blockName)}.js`;
195
+ const getServerSidePropsCode = fs.readFileSync(join(codeDir, getServerSidePropsJsName), 'utf8');
196
+ if (getServerSidePropsCode) {
197
+ set(metadata, 'renderer.getServerSideProps', getServerSidePropsCode);
198
+ }
199
+ }
200
+ catch (error) {
201
+ // ignore error
202
+ }
168
203
  // Handle preview image if exists
169
204
  if (metadata.previewImage) {
170
205
  const imagePath = path.join(path.dirname(fullPath), getPreviewImageRelativePath(metadata.previewImage));
@@ -67,7 +67,4 @@ initUploaderRouter.use('/uploads', initProxyToMediaKitUploadsMiddleware({
67
67
  initUploaderRouter.use('/chunks', dynamicResourceMiddleware, staticResourceMiddleware, (_req, res) => {
68
68
  res.status(404).send('CHUNK NOT FOUND').end();
69
69
  });
70
- initUploaderRouter.use('/.well-known/chunks', dynamicResourceMiddleware, staticResourceMiddleware, (_req, res) => {
71
- res.status(404).send('CHUNK NOT FOUND').end();
72
- });
73
70
  export default initUploaderRouter;
@@ -7,7 +7,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
7
7
  // add tailwindcss css to the head
8
8
  import { createAuthServiceSessionContext } from '@arcblock/did-connect/lib/Session';
9
9
  import { useConfig } from '@arcblock/ux/lib/Config';
10
- import { LocaleProvider, useLocaleContext } from '@arcblock/ux/lib/Locale/context';
10
+ import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
11
11
  import Toast, { ToastProvider } from '@arcblock/ux/lib/Toast';
12
12
  import { createAxios } from '@blocklet/js-sdk';
13
13
  import { PagesKitThemeProvider } from '@blocklet/pages-kit-inner-components/theme';
@@ -27,7 +27,7 @@ import LaptopMacIcon from '@mui/icons-material/LaptopMac';
27
27
  import PhoneAndroidIcon from '@mui/icons-material/PhoneAndroid';
28
28
  import SettingsIcon from '@mui/icons-material/Settings';
29
29
  import SortByAlphaIcon from '@mui/icons-material/SortByAlpha';
30
- import { Alert, Box, Button, CircularProgress, Dialog, DialogContent, DialogTitle, IconButton, List, ListItem, ListItemButton, Skeleton, Stack, StyledEngineProvider, TextField, ToggleButton, ToggleButtonGroup, Tooltip, Typography, backdropClasses, circularProgressClasses, styled, } from '@mui/material';
30
+ import { Alert, Box, Button, CircularProgress, Dialog, DialogContent, DialogTitle, IconButton, List, ListItem, ListItemButton, Skeleton, Stack, TextField, ToggleButton, ToggleButtonGroup, Tooltip, Typography, backdropClasses, circularProgressClasses, styled, } from '@mui/material';
31
31
  import { useDebounceFn, useLocalStorageState, useReactive } from 'ahooks';
32
32
  import { useUpdateEffect } from 'ahooks';
33
33
  import cloneDeep from 'lodash/cloneDeep';
@@ -51,7 +51,7 @@ const api = createAxios({
51
51
  }, {
52
52
  componentDid: PAGES_KIT_BLOCK_STUDIO_BLOCKLET_DID,
53
53
  });
54
- const { SessionProvider, SessionContext } = createAuthServiceSessionContext();
54
+ const { SessionContext } = createAuthServiceSessionContext();
55
55
  function useIsInsideIframe() {
56
56
  const location = useLocation();
57
57
  const isInsideIframe = useMemo(() => {
@@ -191,6 +191,7 @@ const DraggableRouteItem = ({ route, staticDataInRoute, currentPageId, onNavigat
191
191
  opacity: isHovered ? 0.7 : 0,
192
192
  visibility: isHovered ? 'visible' : 'hidden',
193
193
  transition: 'opacity 0.2s ease',
194
+ color: currentPageId === route ? 'white' : '',
194
195
  '&:hover': {
195
196
  bgcolor: 'error.main',
196
197
  color: 'error.contrastText',
@@ -1181,7 +1182,7 @@ const StyledDashboard = styled(Dashboard) `
1181
1182
  `;
1182
1183
  function LayoutWrapper({ loadState, loadedData, ...rest }) {
1183
1184
  const isInsideIframe = useIsInsideIframe();
1184
- return (_jsx(StyledEngineProvider, { injectFirst: true, children: _jsx(PagesKitThemeProvider, { isDashboard: isInsideIframe, children: _jsx(ToastProvider, { children: _jsx(LocaleProvider, { translations: translations, fallbackLocale: "en", children: _jsx(SessionProvider, { serviceHost: basename, protectedRoutes: [`${basename}/*`], children: _jsx(Layout, { loadState: loadState, loadedData: loadedData }) }) }) }) }) }));
1185
+ return (_jsx(PagesKitThemeProvider, { isDashboard: !isInsideIframe, children: _jsx(ToastProvider, { children: _jsx(Layout, { loadState: loadState, loadedData: loadedData }) }) }));
1185
1186
  }
1186
1187
  export default LayoutWrapper;
1187
1188
  function CreateResource({ open, onClose }) {
@@ -1,16 +1,10 @@
1
1
  // import typescript from '@rollup/plugin-typescript';
2
- import { createBuiltinModuleTransformer } from '@blocklet/pages-kit/utils/typescript/builtin-module-transformer';
3
- // @ts-ignore
4
- import { analyzeFileChunks } from '@blocklet/pages-kit/utils/typescript/chunks-analyzer-transformer';
5
- import { readFileSync, existsSync, mkdirSync, writeFileSync, readdirSync, statSync } from 'fs';
2
+ import { readFileSync, existsSync } from 'fs';
6
3
  import camelCase from 'lodash/camelCase';
7
4
  import upperFirst from 'lodash/upperFirst';
8
- import pLimit from 'p-limit';
9
5
  import * as path from 'path';
10
- import { basename } from 'path';
11
6
  import externalGlobals from 'rollup-plugin-external-globals';
12
7
  // import { visualizer } from 'rollup-plugin-visualizer';
13
- import ts from 'typescript';
14
8
  import { joinURL } from 'ufo';
15
9
  import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';
16
10
  import { nodePolyfills } from 'vite-plugin-node-polyfills';
@@ -37,12 +31,6 @@ const isMatchAfterSlachExternals = (id, externals) => {
37
31
  return true;
38
32
  }
39
33
  }
40
- // 检查其他外部依赖的子路径
41
- for (const externalModule of Object.keys(externals)) {
42
- if (id.startsWith(`${externalModule}/`)) {
43
- return true;
44
- }
45
- }
46
34
  return false;
47
35
  };
48
36
  const defaultBlockExternals = {
@@ -101,7 +89,6 @@ export function initBlockStudioPlugins(options) {
101
89
  const workingDir = options?.cwd || process.cwd();
102
90
  const entryFilesPattern = options?.entryFilesPattern || getBlockEntryFilesPattern();
103
91
  const transpileBuiltinModule = options?.transpileBuiltinModule ?? true;
104
- const ignoreSplitEditComponent = options?.ignoreSplitEditComponent ?? false;
105
92
  const watchFilesDir = options?.watchFilesDir || getWatchFilesDir() || workingDir;
106
93
  // default fallback to __dirname if _theme.tsx not exists
107
94
  let pagesDir = __dirname.replace('cjs', 'esm');
@@ -325,121 +312,14 @@ export function initBlockStudioPlugins(options) {
325
312
  }),
326
313
  // initHtmlPreviewTransformPlugin(),
327
314
  cssInjectedByJsPlugin(),
328
- ignoreSplitEditComponent ? undefined : vitePluginCodeSplitter(),
315
+ vitePluginCodeSplitter({
316
+ formats,
317
+ transpileBuiltinModule,
318
+ }),
329
319
  {
330
- name: 'post-build-file-transpiler',
320
+ name: 'vite-plugin-build-exit',
331
321
  apply: 'build',
332
322
  enforce: 'post',
333
- async writeBundle(options) {
334
- // 用于存储每个格式的 chunks 映射
335
- const allChunksMap = {};
336
- // 对所有生成的 JavaScript 文件进行 transpileModule 处理
337
- const transpileBuiltinModuleFn = (dir, format) => {
338
- const files = readdirSync(dir);
339
- files.forEach((file) => {
340
- const filePath = path.join(dir, file);
341
- const stats = statSync(filePath);
342
- if (stats.isDirectory()) {
343
- transpileBuiltinModuleFn(filePath, format); // 递归处理子目录
344
- }
345
- else if (file.endsWith('.js')) {
346
- try {
347
- const script = readFileSync(filePath, 'utf8');
348
- // @ts-ignore
349
- const chunks = analyzeFileChunks(ts, script);
350
- // ensure chunksMap is with all chunks
351
- allChunksMap[basename(filePath)] = new Set(chunks);
352
- const moduleMap = {
353
- es: ts.ModuleKind.ESNext,
354
- cjs: ts.ModuleKind.CommonJS,
355
- umd: ts.ModuleKind.ESNext,
356
- };
357
- const code = ts.transpileModule(script, {
358
- compilerOptions: {
359
- jsx: ts.JsxEmit.React,
360
- target: ts.ScriptTarget.ES2016,
361
- module: moduleMap[format],
362
- },
363
- transformers: {
364
- // @ts-ignore
365
- before: [createBuiltinModuleTransformer(ts)],
366
- },
367
- }).outputText;
368
- writeFileSync(filePath, code);
369
- logger.info(`Transpiled: ${filePath}`);
370
- // updateStatus(`Transpiled: ${filePath}`);
371
- }
372
- catch (error) {
373
- logger.error(`Failed to transpile ${filePath}:`, error);
374
- }
375
- }
376
- });
377
- // 返回一个 Promise 以便 await
378
- return new Promise((resolve, reject) => {
379
- try {
380
- // ... 处理文件的代码 ...
381
- resolve();
382
- }
383
- catch (error) {
384
- reject(error);
385
- }
386
- });
387
- };
388
- // 获取输出目录
389
- const outDir = options.dir || 'dist';
390
- const limit = pLimit(20);
391
- // 使用 Promise.all 等待所有格式处理完成
392
- await Promise.all(formats.map(async (format) => {
393
- const formatDir = path.resolve(outDir, `${format}`);
394
- const chunkDir = path.resolve(formatDir, 'chunks');
395
- // if not exists, create it
396
- if (!existsSync(chunkDir)) {
397
- mkdirSync(chunkDir, { recursive: true });
398
- }
399
- if (transpileBuiltinModule) {
400
- await limit(() => transpileBuiltinModuleFn(formatDir, format));
401
- }
402
- }));
403
- // 现在可以处理完整依赖链
404
- logger.info('all transpile tasks done, start to handle dependency chain...');
405
- // 在这里处理 allChunksMap 的完整依赖链
406
- Object.entries(allChunksMap).forEach(([entryFile, directDeps]) => {
407
- // 收集所有间接依赖
408
- const allDeps = [...directDeps];
409
- // 递归寻找间接依赖
410
- function findTransitiveDeps(chunks) {
411
- chunks.forEach((chunk) => {
412
- // 如果该chunk本身也是个入口(有依赖列表)
413
- if (chunk in allChunksMap) {
414
- const subDeps = allChunksMap[chunk];
415
- // 添加未包含的依赖
416
- if (subDeps) {
417
- subDeps.forEach((dep) => {
418
- if (!allDeps.includes(dep)) {
419
- allDeps.push(dep);
420
- // 递归寻找这个依赖的依赖
421
- findTransitiveDeps([dep]);
422
- }
423
- });
424
- }
425
- }
426
- });
427
- }
428
- // 开始递归查找
429
- findTransitiveDeps([...directDeps]);
430
- // 更新为完整依赖列表
431
- allChunksMap[entryFile] = new Set(allDeps);
432
- });
433
- // 转换 Set 为数组以便正确序列化
434
- const serializedMap = Object.entries(allChunksMap).reduce((result, [key, deps]) => {
435
- result[key] = Array.from(deps);
436
- return result;
437
- }, {});
438
- formats.forEach((format) => {
439
- // 存下来
440
- writeFileSync(path.join(outDir, `${format}/chunks-map.json`), JSON.stringify(serializedMap, null, 2));
441
- });
442
- },
443
323
  closeBundle() {
444
324
  // ensure vite build exit
445
325
  setTimeout(() => {