scripting-cli 1.0.7 → 1.0.9

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/src/build.ts DELETED
@@ -1,110 +0,0 @@
1
- import chalk from 'chalk'
2
- import Webpack from "webpack"
3
- import { zip } from 'cross-zip'
4
- import qrcode from 'qrcode-terminal'
5
-
6
- import path from 'node:path'
7
- import http from 'node:http'
8
- import express from 'express'
9
-
10
- import getConfig from './config/webpack.config'
11
- import * as utils from './utils'
12
- import minimist from 'minimist'
13
-
14
- export function buildApp() {
15
- const webpackConfig = getConfig()
16
-
17
- const appName = Object.keys(webpackConfig.entry as any)[0]
18
- const appFile = `${appName}.zip`
19
-
20
- const outputDir = path.resolve(process.cwd(), appName)
21
-
22
- webpackConfig.output!.path = outputDir
23
-
24
- const compiler = Webpack(webpackConfig)
25
-
26
- console.log(
27
- 'Start running build...\n'
28
- // +
29
- // chalk.green(
30
- // Object.keys(webpackConfig.entry).map(e => ` - ${e}`).join('\n')
31
- // )
32
- // +
33
- // '\n'
34
- )
35
-
36
- compiler.run((err, stats) => {
37
- if (err) {
38
- console.log(
39
- chalk.red('Webpack compile error: \n') + err
40
- )
41
- } else {
42
- console.log(stats?.toString({
43
- chunks: false,
44
- colors: false,
45
- }))
46
-
47
- createAppFile()
48
- }
49
- })
50
-
51
-
52
-
53
- function createAppFile() {
54
- console.log(
55
- ` ~ Creating ${appFile}....`
56
- )
57
-
58
- zip(
59
- outputDir,
60
- path.resolve(outputDir, appFile),
61
- (error) => {
62
- if (error != null) {
63
- console.log(
64
- chalk.red('Error zipping app files: \n') + error
65
- )
66
- } else {
67
- console.log(
68
- chalk.green(` ✔️ ${appFile} created.`)
69
- )
70
-
71
- startServer()
72
- }
73
- }
74
- )
75
- }
76
-
77
- function startServer() {
78
- const app = express()
79
- const server = http.createServer(app)
80
-
81
- const args = minimist(process.argv.slice(2))
82
- const ipAddress = utils.getIpAddress()
83
- const port = args['port'] || 8000
84
-
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
-
92
- app.use(
93
- '/',
94
- express.static(
95
- outputDir
96
- )
97
- )
98
-
99
- server.listen(port)
100
-
101
- console.log(`Server running at ${chalk.bold(
102
- chalk.green(
103
- `http://${ipAddress}:${port}`
104
- ),
105
- )}`)
106
- console.log(`Use the Scripting app to scan the QR code below to install:`)
107
- qrcode.generate(`http://${ipAddress}:${port}`, { small: true })
108
- }
109
-
110
- }
@@ -1,139 +0,0 @@
1
- import { Compiler, WebpackPluginInstance } from "webpack"
2
-
3
- export default class AppJsonPlugin implements WebpackPluginInstance {
4
-
5
- apply(compiler: Compiler) {
6
- const pluginName = 'AppJsonPlugin'
7
-
8
- // webpack 模块实例,可以通过 compiler 对象访问,
9
- // 这样确保使用的是模块的正确版本
10
- // (不要直接 require/import webpack)
11
- const { webpack } = compiler
12
-
13
- // Compilation 对象提供了对一些有用常量的访问。
14
- const { Compilation } = webpack
15
-
16
- // RawSource 是其中一种 “源码”("sources") 类型,
17
- // 用来在 compilation 中表示资源的源码
18
- const { RawSource } = webpack.sources
19
-
20
- // 绑定到 “thisCompilation” 钩子,
21
- // 以便进一步绑定到 compilation 过程更早期的阶段
22
- compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
23
- // 绑定到资源处理流水线(assets processing pipeline)
24
- compilation.hooks.processAssets.tap(
25
- {
26
- name: pluginName,
27
-
28
- // 用某个靠后的资源处理阶段,
29
- // 确保所有资源已被插件添加到 compilation
30
- stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE,
31
- },
32
- (assets) => {
33
-
34
- const scriptJson: {
35
- name: string
36
- index: string
37
- hash: string
38
- assets: string[]
39
- } = {
40
- name: '',
41
- index: '',
42
- hash: '',
43
- assets: Object.keys(assets),
44
- }
45
-
46
- const indexJs = scriptJson.assets.find(
47
- filePath => filePath.match(/\.js$/i) != null
48
- )
49
-
50
- if (indexJs != null) {
51
- const [appName, ...others] = indexJs.split('/')
52
- const filePath = others[others.length - 1]
53
- scriptJson.name = appName
54
- scriptJson.index = filePath
55
- scriptJson.hash = filePath.replace('.js', '')
56
-
57
- const indexJsSource = assets[indexJs]
58
-
59
- scriptJson.assets = [
60
- ...scriptJson.assets.filter(e => e !== indexJs),
61
- filePath,
62
- ]
63
-
64
- compilation.deleteAsset(indexJs)
65
- compilation.emitAsset(filePath, indexJsSource)
66
-
67
- }
68
-
69
- compilation.emitAsset(
70
- 'script.json',
71
- new RawSource(JSON.stringify(scriptJson, null, 2))
72
- )
73
-
74
- // const appMap: {
75
- // [appName: string]: {
76
- // appName: string
77
- // index: string
78
- // hash: string
79
- // }
80
- // } = {}
81
-
82
-
83
- // Object.keys(assets).forEach(path => {
84
- // const [appName, ...others] = path.split('/')
85
- // const filePath = others[others.length - 1]
86
-
87
- // // console.log(appName, filePath)
88
-
89
- // // if (appMap[appName] == null) {
90
- // // appMap[appName] = {
91
- // // appName,
92
- // // // assets: [],
93
- // // }
94
- // // }
95
-
96
- // if (filePath.match(/\.js$/i)) {
97
- // appMap[appName] = {
98
- // appName,
99
- // index: filePath,
100
- // hash: filePath.replace('.js', '')
101
- // }
102
- // // appMap[appName].index = filePath
103
- // // appMap[appName].hash = filePath.replace('.js', '')
104
- // }
105
- // // else if (filePath.match(/\.(png|jpe?g|gif|svg)$/i)) {
106
- // // appMap[appName].assets.push(path.replace(appName + '/', ''))
107
- // // }
108
- // })
109
-
110
- // Object.entries(appMap).forEach(([appName, content]) => {
111
- // compilation.emitAsset(
112
- // appName + '/script.json',
113
- // new RawSource(JSON.stringify(content, null, 2))
114
- // )
115
- // })
116
-
117
- // "assets" 是一个包含 compilation 中所有资源(assets)的对象。
118
- // 该对象的键是资源的路径,
119
- // 值是文件的源码
120
-
121
- // 遍历所有资源,
122
- // 生成 Markdown 文件的内容
123
- // const content =
124
- // '# In this build:\n\n' +
125
- // Object.keys(assets)
126
- // .map((filename) => `- ${filename}`)
127
- // .join('\n');
128
-
129
- // // 向 compilation 添加新的资源,
130
- // // 这样 webpack 就会自动生成并输出到 output 目录
131
- // compilation.emitAsset(
132
- // this.options.outputFile,
133
- // new RawSource(content)
134
- // );
135
- }
136
- )
137
- })
138
- }
139
- }
@@ -1,115 +0,0 @@
1
- import path from 'node:path'
2
- import fs from 'node:fs'
3
-
4
- import chalk from 'chalk'
5
-
6
- import TerserPlugin from 'terser-webpack-plugin'
7
- import webpack from 'webpack'
8
-
9
- import AppJsonPlugin from './AppJsonPlugin'
10
-
11
- export default function getConfig() {
12
-
13
- const baseDir = process.cwd()
14
- const srcDir = path.resolve(baseDir, 'src')
15
- const outputDir = path.resolve(baseDir, 'build')
16
-
17
- const pkgPath = path.resolve(baseDir, 'package.json')
18
-
19
- if (!fs.existsSync(pkgPath)) {
20
- console.log(
21
- chalk.red('✖️ package.json not found.')
22
- )
23
- process.exit(404)
24
- }
25
-
26
- const pkg = JSON.parse(
27
- fs.readFileSync(
28
- pkgPath,
29
- 'utf8'
30
- )
31
- )
32
-
33
- const entry = {
34
- [pkg.name]: path.join(srcDir, 'index.tsx'),
35
- }
36
-
37
- const config: webpack.Configuration = {
38
- mode: 'production',
39
- entry,
40
- optimization: {
41
- moduleIds: 'deterministic',
42
- chunkIds: 'named',
43
- minimizer: [
44
- new TerserPlugin({
45
- extractComments: false,
46
- terserOptions: {
47
- format: {
48
- comments: false,
49
- },
50
- },
51
- }),
52
- ],
53
- },
54
- module: {
55
- rules: [
56
- {
57
- test: /\.tsx?$/,
58
- use: 'ts-loader',
59
- exclude: /node_modules/,
60
- },
61
- {
62
- test: /\.(png|jpe?g|gif|svg)$/i,
63
- loader: 'file-loader',
64
- options: {
65
- name: '[path][contenthash:8].[ext]',
66
- outputPath: (url: string, resourcePath: string, context: any) => {
67
- // if (url.startsWith('src/app/')) {
68
- // return url.replace('src/app/', '')
69
- // }
70
- return url.replace('src/', '')
71
- // return url.replace(/src\/([^/]+)\//, '')
72
- },
73
- publicPath: (url: string, resourcePath: string, context: any) => {
74
- // console.log([url, resourcePath])
75
- // return url.replace(/.*src\/app\/(\w+\/)?/, '')
76
- // if (url.startsWith('src/app/')) {
77
- // return url.replace('src/app/', '')
78
- // }
79
- return url.replace('src/', '')
80
- },
81
- },
82
- },
83
- ],
84
- },
85
- resolve: {
86
- extensions: ['.tsx', '.ts', '.js'],
87
- modules: [
88
- 'node_modules',
89
- srcDir,
90
- ],
91
- alias: {
92
- '@': srcDir,
93
- }
94
- },
95
- output: {
96
- filename: '[name]/[contenthash:8].js',
97
- // filename: '[contenthash:8].js',
98
- path: outputDir,
99
- clean: true,
100
- },
101
- plugins: [
102
- new AppJsonPlugin(),
103
- new webpack.BannerPlugin({
104
- banner: 'const Scripting = require("scripting");',
105
- raw: true
106
- }),
107
- ],
108
- devtool: false,
109
- externals: {
110
- 'scripting': 'Scripting',
111
- }
112
- }
113
-
114
- return config
115
- }
@@ -1,257 +0,0 @@
1
- import chalk from 'chalk'
2
- import path from 'node:path'
3
- import { execSync } from 'node:child_process'
4
- import fs from 'node:fs'
5
- import { mkdir, writeFile, copyFile } from 'node:fs/promises'
6
-
7
- function getScriptDir(scriptName: string) {
8
- return path.join(process.cwd(), scriptName)
9
- }
10
-
11
- async function createScriptDir(scriptName: string) {
12
- const appDir = getScriptDir(scriptName)
13
-
14
- if (fs.existsSync(appDir)) {
15
- throw new Error(`Directory "./${scriptName}" already exists.`)
16
- }
17
-
18
- // const dir = path.resolve(appDir, 'src/svgs')
19
- const srcDir = path.resolve(appDir, 'src')
20
- // const typesDir = path.resolve(appDir, 'types')
21
- await Promise.all([
22
- mkdir(srcDir, { recursive: true }),
23
- // mkdir(typesDir, { recursive: true })
24
- ])
25
- }
26
-
27
- async function createEntryFile(scriptName: string) {
28
- console.log(` > Creating ${scriptName}/src/index.tsx ...`)
29
-
30
- const filePath = path.join(getScriptDir(scriptName), '/src/index.tsx')
31
-
32
- await writeFile(
33
- filePath,
34
- `import { Column, CupertinoNavigationBar, CupertinoPageScaffold, Text, Container, useCupertinoColors, navigator, GestureDetector, Script, Center, CupertinoButton, } from 'scripting'
35
-
36
- function App() {
37
- const cupertinoColors = useCupertinoColors()
38
- const backgroundColor = cupertinoColors.systemBackground
39
-
40
- return (
41
- <CupertinoPageScaffold
42
- navigationBar={
43
- <CupertinoNavigationBar
44
- middle={
45
- <Text>My Script</Text>
46
- }
47
- backgroundColor={backgroundColor}
48
- />
49
- }
50
- >
51
- <Center>
52
- <Text
53
- color={cupertinoColors.label}
54
- >Welcome to Scripting!</Text>
55
- </Center>
56
- </CupertinoPageScaffold>
57
- )
58
- }
59
-
60
- async function run() {
61
- const result = await navigator.push({
62
- element: <App />
63
- })
64
-
65
- Script.exit(result)
66
- }
67
-
68
- run()
69
- `,
70
- 'utf-8'
71
- )
72
-
73
- console.log(
74
- chalk.green(` ✔️ Created ${scriptName}/src/index.tsx`)
75
- )
76
- }
77
-
78
- async function createPackageJson(scriptName: string) {
79
- console.log(` > Creating ${scriptName}/package.json ...`)
80
-
81
- const filePath = path.join(getScriptDir(scriptName), 'package.json')
82
-
83
- await writeFile(
84
- filePath,
85
- `{
86
- "name": "${scriptName}",
87
- "version": "0.0.1",
88
- "private": true,
89
- "scripts": {
90
- "dev": "npx scripting-cli dev",
91
- "build": "npx scripting-cli build"
92
- }
93
- }`,
94
- 'utf-8'
95
- )
96
-
97
- console.log(
98
- chalk.green(` ✔️ Created ${scriptName}/package.json`)
99
- )
100
- }
101
-
102
- async function createReadme(scriptName: string) {
103
-
104
- console.log(` > Creating ${scriptName}/README.md ...`)
105
-
106
- const filePath = path.join(getScriptDir(scriptName), 'README.md')
107
-
108
- await writeFile(
109
- filePath,
110
- `# ${scriptName} - A Scripting script
111
-
112
- ## Start dev server
113
-
114
- \`npm run dev\`
115
-
116
- ## Build App
117
-
118
- \`npm run build\`
119
- `,
120
- 'utf-8'
121
- )
122
-
123
- console.log(
124
- chalk.green(` ✔️ Created ${scriptName}/README.md`)
125
- )
126
- }
127
-
128
- async function createTSConfig(scriptName: string) {
129
-
130
- console.log(` > Creating ${scriptName}/tsconfig.json ...`)
131
-
132
- const filePath = path.join(getScriptDir(scriptName), 'tsconfig.json')
133
-
134
- await writeFile(
135
- filePath,
136
- `{
137
- "compilerOptions": {
138
- "target": "ESNext",
139
- "lib": [
140
- "esnext"
141
- ],
142
- "allowJs": true,
143
- "strict": true,
144
- "esModuleInterop": true,
145
- "allowSyntheticDefaultImports": true,
146
- "forceConsistentCasingInFileNames": true,
147
- "noFallthroughCasesInSwitch": true,
148
- "module": "CommonJS",
149
- "resolveJsonModule": true,
150
- "skipLibCheck": true,
151
- "jsx": "react",
152
- "jsxFactory": "createElement",
153
- "baseUrl": "src",
154
- // "typeRoots": ["./types"],
155
- // "paths": {
156
- // "@/*": [
157
- // "src/*"
158
- // ]
159
- // }
160
- },
161
- "include": [
162
- "src"
163
- ],
164
- }`,
165
- 'utf-8'
166
- )
167
-
168
- console.log(
169
- chalk.green(` ✔️ Created ${scriptName}/tsconfig.json`)
170
- )
171
- }
172
-
173
- async function copyAsset(scriptName: string, fileName: string) {
174
- console.log(` > Creating ${scriptName}/src/${fileName}.d.ts ...`)
175
- await copyFile(
176
- path.join(__dirname, `../public/${fileName}.d.ts`),
177
- path.join(getScriptDir(scriptName), `src/${fileName}.d.ts`)
178
- )
179
- console.log(
180
- chalk.green(` ✔️ Created ${scriptName}/src/${fileName}.d.ts`)
181
- )
182
- }
183
-
184
- async function copyAssets(scriptName: string) {
185
- await copyAsset(scriptName, 'scripting')
186
- await copyAsset(scriptName, 'global')
187
- await copyAsset(scriptName, 'assets')
188
-
189
- // console.log(` > Creating ${scriptName}/src/svgs/logo.svg ...`)
190
- // await copyFile(
191
- // path.join(__dirname, '../public/logo.svg'),
192
- // path.join(getScriptDir(scriptName), 'src/svgs/logo.svg')
193
- // )
194
- // console.log(
195
- // chalk.green(` ✔️ Created ${scriptName}/src/svgs/logo.svg`)
196
- // )
197
- }
198
-
199
- async function createVSCodeSettings(scriptName: string) {
200
- const destDir = path.join(getScriptDir(scriptName), '.vscode')
201
-
202
- if (!fs.existsSync(destDir)) {
203
- await mkdir(destDir, { recursive: true })
204
- }
205
-
206
- await copyFile(
207
- path.join(__dirname, '../.vscode/settings.json'),
208
- path.join(destDir, 'settings.json')
209
- )
210
- }
211
-
212
- function installDeps(scriptName: string) {
213
- console.log(
214
- ` > cd ${scriptName} && npm i -D ts-loader typescript file-loader`
215
- )
216
- execSync(`cd ${scriptName} && npm i -D ts-loader typescript file-loader`)
217
-
218
- console.log(
219
- chalk.green(` ✔️ Scripting script ${chalk.bold(scriptName)} is ready!`)
220
- )
221
- }
222
-
223
- export async function createScript(scriptName: string) {
224
- if (!/^[a-zA-Z]+[a-zA-Z0-9-_]+$/.test(scriptName)) {
225
- console.log(
226
- chalk.red(`✖️ Invalid Scripting script name "${scriptName}"`)
227
- )
228
- return
229
- }
230
-
231
- console.log(
232
- `Start creating ${scriptName} ...`
233
- )
234
-
235
- try {
236
- await createScriptDir(scriptName)
237
- await createPackageJson(scriptName)
238
- await createTSConfig(scriptName)
239
- await createReadme(scriptName)
240
- await createEntryFile(scriptName)
241
- await copyAssets(scriptName)
242
- await createVSCodeSettings(scriptName)
243
-
244
- installDeps(scriptName)
245
-
246
- console.log(
247
- `All done! Run ${chalk.bold(
248
- chalk.green(`cd ${scriptName} && npm run dev`)
249
- )} to start the dev server.`
250
- )
251
-
252
- } catch (e: any) {
253
- console.log(
254
- chalk.red(`✖️ Create script failed: ${e.message}`)
255
- )
256
- }
257
- }