scripting-cli 1.0.3 → 1.0.5

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.
package/dist/build.js CHANGED
@@ -1,4 +1,27 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
2
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
27
  };
@@ -6,9 +29,21 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
29
  exports.buildApp = void 0;
7
30
  const chalk_1 = __importDefault(require("chalk"));
8
31
  const webpack_1 = __importDefault(require("webpack"));
32
+ const cross_zip_1 = require("cross-zip");
33
+ const qrcode_terminal_1 = __importDefault(require("qrcode-terminal"));
34
+ const node_path_1 = __importDefault(require("node:path"));
35
+ const node_http_1 = __importDefault(require("node:http"));
36
+ const express_1 = __importDefault(require("express"));
9
37
  const webpack_config_1 = __importDefault(require("./config/webpack.config"));
38
+ const utils = __importStar(require("./utils"));
39
+ const minimist_1 = __importDefault(require("minimist"));
10
40
  function buildApp() {
11
- const compiler = (0, webpack_1.default)(webpack_config_1.default);
41
+ const webpackConfig = (0, webpack_config_1.default)();
42
+ const appName = Object.keys(webpackConfig.entry)[0];
43
+ const appFile = `${appName}.zip`;
44
+ const outputDir = node_path_1.default.resolve(process.cwd(), appName);
45
+ webpackConfig.output.path = outputDir;
46
+ const compiler = (0, webpack_1.default)(webpackConfig);
12
47
  console.log('Start running build...\n'
13
48
  // +
14
49
  // chalk.green(
@@ -26,7 +61,38 @@ function buildApp() {
26
61
  chunks: false,
27
62
  colors: false,
28
63
  }));
64
+ createAppFile();
29
65
  }
30
66
  });
67
+ function createAppFile() {
68
+ console.log(` ~ Creating ${appFile}....`);
69
+ (0, cross_zip_1.zip)(outputDir, node_path_1.default.resolve(outputDir, appFile), (error) => {
70
+ if (error != null) {
71
+ console.log(chalk_1.default.red('Error zipping app files: \n') + error);
72
+ }
73
+ else {
74
+ console.log(chalk_1.default.green(` ✔️ ${appFile} created.`));
75
+ startServer();
76
+ }
77
+ });
78
+ }
79
+ function startServer() {
80
+ const app = (0, express_1.default)();
81
+ const server = node_http_1.default.createServer(app);
82
+ const args = (0, minimist_1.default)(process.argv.slice(2));
83
+ const ipAddress = utils.getIpAddress();
84
+ const port = args['port'] || 8000;
85
+ app.all('*', function (req, res, next) {
86
+ res.header('Access-Control-Allow-Origin', '*');
87
+ res.header('Access-Control-Allow-Headers', '*');
88
+ res.header('Access-Control-Allow-Methods', 'GET, POST, PATCH, OPTIONS, PUT, DELETE');
89
+ next();
90
+ });
91
+ app.use('/', express_1.default.static(outputDir));
92
+ server.listen(port);
93
+ console.log(`Server running at ${chalk_1.default.bold(chalk_1.default.green(`http://${ipAddress}:${port}`))}`);
94
+ console.log(`Use the Scripting app to scan the QR code below to install:`);
95
+ qrcode_terminal_1.default.generate(`http://${ipAddress}:${port}`, { small: true });
96
+ }
31
97
  }
32
98
  exports.buildApp = buildApp;
@@ -22,33 +22,64 @@ class AppJsonPlugin {
22
22
  // 确保所有资源已被插件添加到 compilation
23
23
  stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE,
24
24
  }, (assets) => {
25
- const appMap = {};
26
- Object.keys(assets).forEach(path => {
27
- const [appName, ...others] = path.split('/');
25
+ const appJson = {
26
+ name: '',
27
+ index: '',
28
+ hash: '',
29
+ assets: Object.keys(assets),
30
+ };
31
+ const indexJs = appJson.assets.find(filePath => filePath.match(/\.js$/i) != null);
32
+ if (indexJs != null) {
33
+ const [appName, ...others] = indexJs.split('/');
28
34
  const filePath = others[others.length - 1];
29
- // console.log(appName, filePath)
30
- // if (appMap[appName] == null) {
31
- // appMap[appName] = {
32
- // appName,
33
- // // assets: [],
34
- // }
35
- // }
36
- if (filePath.match(/\.js$/i)) {
37
- appMap[appName] = {
38
- appName,
39
- index: filePath,
40
- hash: filePath.replace('.js', '')
41
- };
42
- // appMap[appName].index = filePath
43
- // appMap[appName].hash = filePath.replace('.js', '')
44
- }
45
- // else if (filePath.match(/\.(png|jpe?g|gif|svg)$/i)) {
46
- // appMap[appName].assets.push(path.replace(appName + '/', ''))
47
- // }
48
- });
49
- Object.entries(appMap).forEach(([appName, content]) => {
50
- compilation.emitAsset(appName + '/app.json', new RawSource(JSON.stringify(content, null, 2)));
51
- });
35
+ appJson.name = appName;
36
+ appJson.index = filePath;
37
+ appJson.hash = filePath.replace('.js', '');
38
+ const indexJsSource = assets[indexJs];
39
+ appJson.assets = [
40
+ ...appJson.assets.filter(e => e !== indexJs),
41
+ filePath,
42
+ ];
43
+ compilation.deleteAsset(indexJs);
44
+ compilation.emitAsset(filePath, indexJsSource);
45
+ }
46
+ compilation.emitAsset('app.json', new RawSource(JSON.stringify(appJson, null, 2)));
47
+ // const appMap: {
48
+ // [appName: string]: {
49
+ // appName: string
50
+ // index: string
51
+ // hash: string
52
+ // }
53
+ // } = {}
54
+ // Object.keys(assets).forEach(path => {
55
+ // const [appName, ...others] = path.split('/')
56
+ // const filePath = others[others.length - 1]
57
+ // // console.log(appName, filePath)
58
+ // // if (appMap[appName] == null) {
59
+ // // appMap[appName] = {
60
+ // // appName,
61
+ // // // assets: [],
62
+ // // }
63
+ // // }
64
+ // if (filePath.match(/\.js$/i)) {
65
+ // appMap[appName] = {
66
+ // appName,
67
+ // index: filePath,
68
+ // hash: filePath.replace('.js', '')
69
+ // }
70
+ // // appMap[appName].index = filePath
71
+ // // appMap[appName].hash = filePath.replace('.js', '')
72
+ // }
73
+ // // else if (filePath.match(/\.(png|jpe?g|gif|svg)$/i)) {
74
+ // // appMap[appName].assets.push(path.replace(appName + '/', ''))
75
+ // // }
76
+ // })
77
+ // Object.entries(appMap).forEach(([appName, content]) => {
78
+ // compilation.emitAsset(
79
+ // appName + '/app.json',
80
+ // new RawSource(JSON.stringify(content, null, 2))
81
+ // )
82
+ // })
52
83
  // "assets" 是一个包含 compilation 中所有资源(assets)的对象。
53
84
  // 该对象的键是资源的路径,
54
85
  // 值是文件的源码
@@ -3,80 +3,96 @@ 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
- const path_1 = __importDefault(require("path"));
6
+ const node_path_1 = __importDefault(require("node:path"));
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const chalk_1 = __importDefault(require("chalk"));
7
9
  const terser_webpack_plugin_1 = __importDefault(require("terser-webpack-plugin"));
8
10
  const AppJsonPlugin_1 = __importDefault(require("./AppJsonPlugin"));
9
- const baseDir = process.cwd();
10
- const srcDir = path_1.default.resolve(baseDir, 'src');
11
- const buildDir = path_1.default.resolve(baseDir, 'build');
12
- const config = {
13
- mode: 'production',
14
- entry: path_1.default.join(srcDir, 'index.tsx'),
15
- optimization: {
16
- moduleIds: 'deterministic',
17
- chunkIds: 'named',
18
- minimizer: [
19
- new terser_webpack_plugin_1.default({
20
- extractComments: false,
21
- terserOptions: {
22
- format: {
23
- comments: false,
11
+ function getConfig() {
12
+ const baseDir = process.cwd();
13
+ const srcDir = node_path_1.default.resolve(baseDir, 'src');
14
+ const outputDir = node_path_1.default.resolve(baseDir, 'build');
15
+ const pkgPath = node_path_1.default.resolve(baseDir, 'package.json');
16
+ if (!node_fs_1.default.existsSync(pkgPath)) {
17
+ console.log(chalk_1.default.red('✖️ package.json not found.'));
18
+ process.exit(404);
19
+ }
20
+ const pkg = JSON.parse(node_fs_1.default.readFileSync(pkgPath, 'utf8'));
21
+ const entry = {
22
+ [pkg.name]: node_path_1.default.join(srcDir, 'index.tsx'),
23
+ };
24
+ const config = {
25
+ mode: 'production',
26
+ entry,
27
+ optimization: {
28
+ moduleIds: 'deterministic',
29
+ chunkIds: 'named',
30
+ minimizer: [
31
+ new terser_webpack_plugin_1.default({
32
+ extractComments: false,
33
+ terserOptions: {
34
+ format: {
35
+ comments: false,
36
+ },
24
37
  },
38
+ }),
39
+ ],
40
+ },
41
+ module: {
42
+ rules: [
43
+ {
44
+ test: /\.tsx?$/,
45
+ use: 'ts-loader',
46
+ exclude: /node_modules/,
25
47
  },
26
- }),
27
- ],
28
- },
29
- module: {
30
- rules: [
31
- {
32
- test: /\.tsx?$/,
33
- use: 'ts-loader',
34
- exclude: /node_modules/,
35
- },
36
- {
37
- test: /\.(png|jpe?g|gif|svg)$/i,
38
- loader: 'file-loader',
39
- options: {
40
- name: '[path][contenthash:8].[ext]',
41
- outputPath: (url, resourcePath, context) => {
42
- // if (url.startsWith('src/app/')) {
43
- // return url.replace('src/app/', '')
44
- // }
45
- return url.replace('src/', '');
46
- // return url.replace(/src\/([^/]+)\//, '')
47
- },
48
- publicPath: (url, resourcePath, context) => {
49
- // console.log([url, resourcePath])
50
- // return url.replace(/.*src\/app\/(\w+\/)?/, '')
51
- // if (url.startsWith('src/app/')) {
52
- // return url.replace('src/app/', '')
53
- // }
54
- return url.replace('src/', '');
48
+ {
49
+ test: /\.(png|jpe?g|gif|svg)$/i,
50
+ loader: 'file-loader',
51
+ options: {
52
+ name: '[path][contenthash:8].[ext]',
53
+ outputPath: (url, resourcePath, context) => {
54
+ // if (url.startsWith('src/app/')) {
55
+ // return url.replace('src/app/', '')
56
+ // }
57
+ return url.replace('src/', '');
58
+ // return url.replace(/src\/([^/]+)\//, '')
59
+ },
60
+ publicPath: (url, resourcePath, context) => {
61
+ // console.log([url, resourcePath])
62
+ // return url.replace(/.*src\/app\/(\w+\/)?/, '')
63
+ // if (url.startsWith('src/app/')) {
64
+ // return url.replace('src/app/', '')
65
+ // }
66
+ return url.replace('src/', '');
67
+ },
55
68
  },
56
69
  },
57
- },
70
+ ],
71
+ },
72
+ resolve: {
73
+ extensions: ['.tsx', '.ts', '.js'],
74
+ modules: [
75
+ 'node_modules',
76
+ srcDir,
77
+ ],
78
+ alias: {
79
+ '@': srcDir,
80
+ }
81
+ },
82
+ output: {
83
+ filename: '[name]/[contenthash:8].js',
84
+ // filename: '[contenthash:8].js',
85
+ path: outputDir,
86
+ clean: true,
87
+ },
88
+ plugins: [
89
+ new AppJsonPlugin_1.default(),
58
90
  ],
59
- },
60
- resolve: {
61
- extensions: ['.tsx', '.ts', '.js'],
62
- modules: [
63
- 'node_modules',
64
- srcDir,
65
- ],
66
- alias: {
67
- '@': srcDir,
91
+ devtool: false,
92
+ externals: {
93
+ 'scripting': 'Scripting',
68
94
  }
69
- },
70
- output: {
71
- // filename: 'index.js',
72
- // filename: '[name]/index.js',
73
- filename: '[name]/[contenthash:8].js',
74
- path: buildDir,
75
- clean: true,
76
- },
77
- plugins: [
78
- new AppJsonPlugin_1.default(),
79
- ],
80
- devtool: false,
81
- };
82
- exports.default = config;
95
+ };
96
+ return config;
97
+ }
98
+ exports.default = getConfig;
package/dist/createApp.js CHANGED
@@ -18,16 +18,16 @@ const node_path_1 = __importDefault(require("node:path"));
18
18
  const node_child_process_1 = require("node:child_process");
19
19
  const node_fs_1 = __importDefault(require("node:fs"));
20
20
  const promises_1 = require("node:fs/promises");
21
- console.log(process.cwd());
22
21
  function getAppDir(appName) {
23
22
  return node_path_1.default.join(process.cwd(), appName);
24
23
  }
25
24
  function createAppDir(appName) {
26
25
  return __awaiter(this, void 0, void 0, function* () {
27
- const dir = node_path_1.default.join(getAppDir(appName), 'src');
28
- if (node_fs_1.default.existsSync(dir)) {
26
+ const appDir = getAppDir(appName);
27
+ if (node_fs_1.default.existsSync(appDir)) {
29
28
  throw new Error(`Directory "./${appName}" already exists.`);
30
29
  }
30
+ const dir = node_path_1.default.resolve(appDir, 'src/svgs');
31
31
  yield (0, promises_1.mkdir)(dir, { recursive: true });
32
32
  });
33
33
  }
@@ -35,11 +35,29 @@ function createEntryFile(appName) {
35
35
  return __awaiter(this, void 0, void 0, function* () {
36
36
  console.log(` > Creating ${appName}/src/index.tsx ...`);
37
37
  const filePath = node_path_1.default.join(getAppDir(appName), '/src/index.tsx');
38
- yield (0, promises_1.writeFile)(filePath, `
39
- const { runApp, createElement, RouterProvider, Router, } = Scripting
40
- const { Center, Text, CupertinoPageScaffold, CupertinoNavigationBar, } = Scripting.Widgets
38
+ yield (0, promises_1.writeFile)(filePath, `import { runApp, createElement, RouterProvider, Router, Column, CupertinoNavigationBar, CupertinoPageScaffold, Svg, Text, Container, useCupertinoColors } from 'scripting'
39
+ import Logo from './svgs/logo.svg'
40
+
41
+ function ScriptingLogo() {
42
+ return (
43
+ <Container
44
+ clipBehavior={'hardEdge'}
45
+ width={80}
46
+ height={80}
47
+ margin={{
48
+ vertical: 100,
49
+ }}
50
+ borderRadius={16}
51
+ >
52
+ <Svg src={Logo} />
53
+ </Container>
54
+ )
55
+ }
56
+
57
+ function HomePage() {
58
+ const cupertinoColors = useCupertinoColors()
59
+ const backgroundColor = cupertinoColors.systemBackground
41
60
 
42
- function IndexPage() {
43
61
  return (
44
62
  <CupertinoPageScaffold
45
63
  navigationBar={
@@ -47,12 +65,24 @@ function IndexPage() {
47
65
  middle={
48
66
  <Text>${appName}</Text>
49
67
  }
68
+ backgroundColor={backgroundColor}
50
69
  />
51
70
  }
52
71
  >
53
- <Center>
54
- <Text>Welcome to Scripting!</Text>
55
- </Center>
72
+ <Container
73
+ width={'infinity'}
74
+ height={'infinity'}
75
+ color={backgroundColor}
76
+ >
77
+ <Column
78
+ crossAxisAlignment={'center'}
79
+ >
80
+ <ScriptingLogo />
81
+ <Text
82
+ color={cupertinoColors.label}
83
+ >Welcome to Scripting!</Text>
84
+ </Column>
85
+ </Container>
56
86
  </CupertinoPageScaffold>
57
87
  )
58
88
  }
@@ -60,14 +90,13 @@ function IndexPage() {
60
90
  const router = new Router([
61
91
  {
62
92
  path: '/',
63
- element: <IndexPage />,
93
+ element: <HomePage />,
64
94
  },
65
95
  ])
66
96
 
67
97
  runApp(
68
98
  <RouterProvider router={router} />
69
- )
70
- `, 'utf-8');
99
+ )`, 'utf-8');
71
100
  console.log(chalk_1.default.green(` ✔️ Created ${appName}/src/index.tsx`));
72
101
  });
73
102
  }
@@ -93,17 +122,11 @@ function createReadme(appName) {
93
122
  const filePath = node_path_1.default.join(getAppDir(appName), 'README.md');
94
123
  yield (0, promises_1.writeFile)(filePath, `# ${appName} - A Scripting application
95
124
 
96
- ## Quick Start
97
-
98
- ### Installation
99
-
100
- \`npm install\`
101
-
102
- ### Start dev server
125
+ ## Start dev server
103
126
 
104
127
  \`npm run dev\`
105
128
 
106
- ### Build App
129
+ ## Build App
107
130
 
108
131
  \`npm run build\`
109
132
  `, 'utf-8');
@@ -147,18 +170,32 @@ function createTSConfig(appName) {
147
170
  console.log(chalk_1.default.green(` ✔️ Created ${appName}/tsconfig.json`));
148
171
  });
149
172
  }
150
- function createScriptingDeclaration(appName) {
173
+ function copyAssets(appName) {
151
174
  return __awaiter(this, void 0, void 0, function* () {
152
175
  console.log(` > Creating ${appName}/src/scripting.d.ts ...`);
153
- const srcPath = node_path_1.default.join(__dirname, '../public/scripting.d.ts');
154
- const destPath = node_path_1.default.join(getAppDir(appName), 'src/scripting.d.ts');
155
- yield (0, promises_1.copyFile)(srcPath, destPath);
176
+ yield (0, promises_1.copyFile)(node_path_1.default.join(__dirname, '../public/scripting.d.ts'), node_path_1.default.join(getAppDir(appName), 'src/scripting.d.ts'));
156
177
  console.log(chalk_1.default.green(` ✔️ Created ${appName}/src/scripting.d.ts`));
178
+ console.log(` > Creating ${appName}/src/assets.d.ts ...`);
179
+ yield (0, promises_1.copyFile)(node_path_1.default.join(__dirname, '../public/assets.d.ts'), node_path_1.default.join(getAppDir(appName), 'src/assets.d.ts'));
180
+ console.log(chalk_1.default.green(` ✔️ Created ${appName}/src/assets.d.ts`));
181
+ console.log(` > Creating ${appName}/src/svgs/logo.svg ...`);
182
+ yield (0, promises_1.copyFile)(node_path_1.default.join(__dirname, '../public/logo.svg'), node_path_1.default.join(getAppDir(appName), 'src/svgs/logo.svg'));
183
+ console.log(chalk_1.default.green(` ✔️ Created ${appName}/src/svgs/logo.svg`));
184
+ });
185
+ }
186
+ function createVSCodeSettings(appName) {
187
+ return __awaiter(this, void 0, void 0, function* () {
188
+ const destDir = node_path_1.default.join(getAppDir(appName), '.vscode');
189
+ if (!node_fs_1.default.existsSync(destDir)) {
190
+ yield (0, promises_1.mkdir)(destDir, { recursive: true });
191
+ }
192
+ yield (0, promises_1.copyFile)(node_path_1.default.join(__dirname, '../.vscode/settings.json'), node_path_1.default.join(destDir, 'settings.json'));
157
193
  });
158
194
  }
159
195
  function installDeps(appName) {
196
+ console.log(` > cd ${appName} && npm i -D ts-loader typescript file-loader`);
160
197
  (0, node_child_process_1.execSync)(`cd ${appName} && npm i -D ts-loader typescript file-loader`);
161
- console.log(chalk_1.default.green(` ✔️ Scripting application ${chalk_1.default.bold(appName)} created!`));
198
+ console.log(chalk_1.default.green(` ✔️ Scripting application ${chalk_1.default.bold(appName)} is ready!`));
162
199
  }
163
200
  function createApp(appName) {
164
201
  return __awaiter(this, void 0, void 0, function* () {
@@ -166,14 +203,17 @@ function createApp(appName) {
166
203
  console.log(chalk_1.default.red(`✖️ Invalid Scripting application name "${appName}"`));
167
204
  return;
168
205
  }
206
+ console.log(`Start creating ${appName} ...`);
169
207
  try {
170
208
  yield createAppDir(appName);
171
209
  yield createPackageJson(appName);
172
210
  yield createTSConfig(appName);
173
211
  yield createReadme(appName);
174
212
  yield createEntryFile(appName);
175
- yield createScriptingDeclaration(appName);
213
+ yield copyAssets(appName);
214
+ yield createVSCodeSettings(appName);
176
215
  installDeps(appName);
216
+ console.log(`All done! Run ${chalk_1.default.bold(chalk_1.default.green(`cd ${appName} && npm run dev`))} to start the dev server.`);
177
217
  }
178
218
  catch (e) {
179
219
  console.log(chalk_1.default.red(`✖️ Create Scripting application failed: ${e.message}`));
package/dist/index.js CHANGED
@@ -10,7 +10,6 @@ const build_1 = require("./build");
10
10
  const createApp_1 = require("./createApp");
11
11
  function run() {
12
12
  const args = (0, minimist_1.default)(process.argv.slice(2));
13
- // console.log(args)
14
13
  if (args['create'] != null) {
15
14
  (0, createApp_1.createApp)(args['create']);
16
15
  }
@@ -22,6 +22,15 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
25
34
  var __importDefault = (this && this.__importDefault) || function (mod) {
26
35
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
36
  };
@@ -29,9 +38,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
29
38
  exports.startDevServer = void 0;
30
39
  const node_http_1 = __importDefault(require("node:http"));
31
40
  const node_path_1 = __importDefault(require("node:path"));
41
+ const promises_1 = require("node:fs/promises");
32
42
  const chalk_1 = __importDefault(require("chalk"));
33
43
  const express_1 = __importDefault(require("express"));
34
44
  const minimist_1 = __importDefault(require("minimist"));
45
+ const qrcode_terminal_1 = __importDefault(require("qrcode-terminal"));
35
46
  const socket_io_1 = require("socket.io");
36
47
  const utils = __importStar(require("./utils"));
37
48
  const webpack_1 = __importDefault(require("webpack"));
@@ -45,13 +56,14 @@ function startDevServer() {
45
56
  const io = new socket_io_1.Server(server);
46
57
  let isStarted = false;
47
58
  let connectedSockets = [];
48
- webpack_config_1.default.mode = 'development';
49
- const compiler = (0, webpack_1.default)(webpack_config_1.default);
59
+ const webpackConfig = (0, webpack_config_1.default)();
60
+ webpackConfig.mode = 'development';
61
+ const compiler = (0, webpack_1.default)(webpackConfig);
50
62
  console.log('Start running webpack compiler in watch mode...');
51
63
  compiler.watch({}, (err, stats) => {
52
64
  utils.clearConsole();
53
65
  if (err) {
54
- console.log(chalk_1.default.red('[DevServer] webpack compile error: \n') + err);
66
+ console.log(chalk_1.default.red(' ✖️ webpack compile error: \n') + err);
55
67
  }
56
68
  else {
57
69
  console.log(stats === null || stats === void 0 ? void 0 : stats.toString({
@@ -64,19 +76,24 @@ function startDevServer() {
64
76
  }
65
77
  });
66
78
  function onCompileDone() {
67
- if (isStarted) {
68
- printDevServerAddress();
69
- console.log(chalk_1.default.gray(`[DevServer] Sent update event to ${connectedSockets.length} client(s)`));
70
- connectedSockets.forEach(socket => {
71
- socket.emit('update');
72
- });
73
- }
74
- else {
75
- start();
76
- }
79
+ return __awaiter(this, void 0, void 0, function* () {
80
+ if (isStarted) {
81
+ printDevServerAddress();
82
+ console.log(chalk_1.default.gray(` ~ Sent update event to ${connectedSockets.length} client(s)`));
83
+ const appJson = yield (0, promises_1.readFile)(node_path_1.default.resolve(process.cwd(), 'build/app.json'), 'utf-8');
84
+ for (const socket of connectedSockets) {
85
+ socket.emit('update', appJson);
86
+ }
87
+ }
88
+ else {
89
+ start();
90
+ }
91
+ });
77
92
  }
78
93
  function printDevServerAddress() {
79
94
  console.log(`Server running at ${chalk_1.default.bold(chalk_1.default.green(`http://${ipAddress}:${port}`))}`);
95
+ console.log(`Use the Scripting app to scan the QR code below:`);
96
+ qrcode_terminal_1.default.generate(`http://${ipAddress}:${port}`, { small: true });
80
97
  }
81
98
  function start() {
82
99
  if (isStarted) {
@@ -85,23 +102,22 @@ function startDevServer() {
85
102
  app.all('*', function (req, res, next) {
86
103
  res.header('Access-Control-Allow-Origin', '*');
87
104
  res.header('Access-Control-Allow-Headers', '*');
88
- // res.header('Content-Type', 'application/jsoncharset=utf-8')
89
105
  res.header('Access-Control-Allow-Methods', 'GET, POST, PATCH, OPTIONS, PUT, DELETE');
90
106
  next();
91
107
  });
92
- app.use('/', express_1.default.static(node_path_1.default.resolve(process.cwd(), '../build')));
108
+ app.use('/', express_1.default.static(node_path_1.default.resolve(process.cwd(), 'build')));
93
109
  //有新的客户端连接时触发
94
110
  io.on('connection', function (socket) {
95
- console.log(chalk_1.default.green('[DevServer] A client connected.'));
111
+ console.log(chalk_1.default.green(` + A client(${socket.id}) connected.`));
96
112
  connectedSockets.push(socket);
97
113
  socket.on('error', function (err) {
98
- console.log(chalk_1.default.red('[DevServer] Error: ', err));
114
+ console.log(chalk_1.default.red(' ✖️ Server Error: ', err));
99
115
  });
100
116
  socket.on('disconnect', function () {
101
117
  var index = connectedSockets.indexOf(socket);
102
118
  if (index > -1) {
103
119
  connectedSockets.splice(index, 1);
104
- console.log(chalk_1.default.gray('[DevServer] A client disconnected.'));
120
+ console.log(chalk_1.default.gray(` - A client(${socket.id}) disconnected.`));
105
121
  }
106
122
  });
107
123
  });