@heavenlydemon/sill-cli 0.0.0-stage → 0.2.0

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.
Files changed (3) hide show
  1. package/README.md +26 -2
  2. package/bin/sill.js +379 -0
  3. package/package.json +18 -4
package/README.md CHANGED
@@ -1,3 +1,27 @@
1
- # Temporary Holding Version
1
+ # @sill/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Sill 组件开发命令行。不需要 clone Sill 源码。
4
+
5
+ ```bash
6
+ # 尚未发 npm:用 GitHub release 的 tarball
7
+ npm i -g .\sill-cli-0.2.0.tgz
8
+ # 发 npm 后:npm i -g @sill/cli
9
+ sill new com.example.clock
10
+ cd com.example.clock
11
+ sill dev
12
+ sill pack
13
+ ```
14
+
15
+ - `sill dev` 找已安装的 `Sill.exe`,用独立开发数据和 `SILL_DEV_WIDGET` 启动;
16
+ - 找不到安装版时,`SILL_EXE` 指向便携版;再不行才回退源码仓库的 `pnpm dev`;
17
+ - `sill new` 默认生成 `type: "web"`、`trust: "trusted"`,`--template` 生成旧模板;
18
+ - `sill pack` 输出 `.sill`;web 组件可带 `ui/assets/**`(trusted 用包目录)。
19
+
20
+ 环境变量:
21
+
22
+ | 变量 | 用途 |
23
+ |---|---|
24
+ | `SILL_EXE` | Sill.exe 路径 |
25
+ | `SILL_DEV_DATA` | 开发用 userData,默认 `%APPDATA%\Sill-dev` |
26
+
27
+ Node.js >= 20。
package/bin/sill.js ADDED
@@ -0,0 +1,379 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process'
3
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
4
+ import { dirname, join, resolve } from 'node:path'
5
+ import { homedir } from 'node:os'
6
+ import { fileURLToPath } from 'node:url'
7
+ import AdmZip from 'adm-zip'
8
+
9
+ const BASE_FILES = ['widget.json', 'ui/index.html', 'ui/style.css']
10
+ const WEB_FILES = [...BASE_FILES, 'ui/main.js']
11
+ const MAX_FILE = 20 * 1024 * 1024
12
+ const PERMISSIONS = new Set([
13
+ 'data.time',
14
+ 'data.system',
15
+ 'data.media',
16
+ 'data.weather',
17
+ 'data.todo',
18
+ 'action.media',
19
+ 'action.todo'
20
+ ])
21
+ const ID = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/
22
+ const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?$/
23
+
24
+ function usage() {
25
+ console.log(`sill <command>
26
+
27
+ validate <dir> 校验组件
28
+ pack <dir> [-o file] 打成 .sill
29
+ new <id> [dir] [--template] 生成组件(默认 web/trusted)
30
+ dev <dir> 启动已安装 Sill / SILL_EXE,独立开发数据
31
+
32
+ 示例:
33
+ sill new com.example.clock
34
+ sill dev ./com.example.clock
35
+ sill pack ./com.example.clock -o clock.sill
36
+
37
+ 环境变量:
38
+ SILL_EXE 便携版 Sill.exe
39
+ SILL_DEV_DATA 开发 userData(默认 %APPDATA%\\Sill-dev)`)
40
+ }
41
+
42
+ function fail(message) {
43
+ console.error(`sill: ${message}`)
44
+ process.exitCode = 1
45
+ }
46
+
47
+ function readJson(file) {
48
+ return JSON.parse(readFileSync(file, 'utf8'))
49
+ }
50
+
51
+ function allowedFiles(kind) {
52
+ return kind === 'web' ? WEB_FILES : BASE_FILES
53
+ }
54
+
55
+ function validateDir(dir) {
56
+ const root = resolve(dir)
57
+ const errors = []
58
+ const widgetFile = join(root, 'widget.json')
59
+
60
+ if (!existsSync(widgetFile)) return [`缺少 ${widgetFile}`]
61
+
62
+ let raw
63
+ try {
64
+ raw = readJson(widgetFile)
65
+ } catch {
66
+ return ['widget.json 不是合法 JSON']
67
+ }
68
+
69
+ const id = typeof raw.id === 'string' ? raw.id : ''
70
+ const name = typeof raw.name === 'string' ? raw.name.trim() : ''
71
+ const version = typeof raw.version === 'string' ? raw.version : ''
72
+ const author = typeof raw.author === 'string' ? raw.author.trim() : ''
73
+ const license = typeof raw.license === 'string' ? raw.license.trim() : ''
74
+ const runtime = typeof raw.runtime === 'string' ? raw.runtime.trim() : ''
75
+ const engine = typeof raw.engine === 'string' ? raw.engine.trim() : ''
76
+ const kind = raw.type === 'web' ? 'web' : raw.type === 'template' ? 'template' : ''
77
+ const trust = kind === 'web' && raw.trust === 'trusted' ? 'trusted' : 'sandboxed'
78
+ const permissions = Array.isArray(raw.permissions) ? raw.permissions : []
79
+ const span = Number(raw.span?.default)
80
+
81
+ if (raw.schema !== 1) errors.push('schema 必须是 1')
82
+ if (!ID.test(id)) errors.push('id 至少两段,只能用小写字母、数字、点和短横线')
83
+ if (!name || name.length > 24) errors.push('name 必须 1–24 字')
84
+ if (!SEMVER.test(version)) errors.push('version 必须是 semver')
85
+ if (!author) errors.push('author 不能为空')
86
+ if (!license) errors.push('license 不能为空')
87
+ if (!runtime) errors.push('runtime 不能为空')
88
+ if (!engine) errors.push('engine 不能为空')
89
+ if (!kind) errors.push('type 必须是 template 或 web')
90
+ if (raw.ui !== 'ui/index.html') errors.push('ui 必须是 ui/index.html')
91
+ if (!Number.isFinite(span) || span < 1 || span > 3) errors.push('span.default 必须在 1–3')
92
+ if (!Array.isArray(raw.permissions)) errors.push('permissions 必须是数组')
93
+ for (const permission of permissions) {
94
+ if (!PERMISSIONS.has(permission)) errors.push(`未知权限 ${permission}`)
95
+ }
96
+ if (raw.data !== undefined && !Array.isArray(raw.data)) errors.push('data 必须是数组')
97
+ if (raw.strings !== undefined) {
98
+ if (!raw.strings || typeof raw.strings !== 'object' || Array.isArray(raw.strings)) {
99
+ errors.push('strings 必须是对象')
100
+ } else {
101
+ for (const [language, table] of Object.entries(raw.strings)) {
102
+ if (!table || typeof table !== 'object' || Array.isArray(table)) {
103
+ errors.push(`strings.${language} 必须是对象`)
104
+ continue
105
+ }
106
+ for (const [key, text] of Object.entries(table)) {
107
+ if (typeof text !== 'string') errors.push(`strings.${language}.${key} 必须是字符串`)
108
+ }
109
+ }
110
+ }
111
+ }
112
+
113
+ const files = allowedFiles(kind)
114
+ const allowed = new Set([...files, 'README.md'])
115
+ const walk = (current) => {
116
+ for (const entry of readdirSync(current)) {
117
+ const file = join(current, entry)
118
+ const relative = file.slice(root.length + 1).replace(/\\/g, '/')
119
+ if (statSync(file).isDirectory()) {
120
+ walk(file)
121
+ } else if (relative.endsWith('.sill') && !relative.includes('/')) {
122
+ // 允许把打包产物放在项目根目录;它不会进 .sill。
123
+ continue
124
+ } else if (relative.startsWith('ui/assets/') && kind === 'web') {
125
+ // web 组件可以带 assets;trusted 用包目录,sandboxed 以后走协议。
126
+ continue
127
+ } else if (!allowed.has(relative)) {
128
+ errors.push(`不允许的文件:${relative}`)
129
+ }
130
+ }
131
+ }
132
+ walk(root)
133
+
134
+ for (const relative of files) {
135
+ const file = join(root, relative)
136
+ if (!existsSync(file)) {
137
+ errors.push(`缺少 ${relative}`)
138
+ continue
139
+ }
140
+ if (!statSync(file).isFile()) {
141
+ errors.push(`${relative} 不是文件`)
142
+ continue
143
+ }
144
+ if (statSync(file).size > MAX_FILE) errors.push(`${relative} 超过 20 MB`)
145
+ }
146
+
147
+ if (kind === 'template') {
148
+ const htmlPath = join(root, 'ui/index.html')
149
+ const cssPath = join(root, 'ui/style.css')
150
+ if (existsSync(htmlPath)) {
151
+ const html = readFileSync(htmlPath, 'utf8')
152
+ if (/<script\b/i.test(html)) errors.push('HTML 不能包含 <script>')
153
+ if (/\son\w+\s*=/i.test(html)) errors.push('HTML 不能包含 on* 属性')
154
+ if (/\sstyle\s*=/i.test(html)) errors.push('HTML 不能包含 style 属性')
155
+ if (/\b(href|src)\s*=/i.test(html)) errors.push('HTML 不能包含 href / src')
156
+ }
157
+ if (existsSync(cssPath)) {
158
+ const css = readFileSync(cssPath, 'utf8')
159
+ if (/@import/i.test(css)) errors.push('CSS 不能包含 @import')
160
+ if (/url\s*\(/i.test(css)) errors.push('CSS 不能包含 url()')
161
+ if (/expression\s*\(/i.test(css)) errors.push('CSS 不能包含 expression()')
162
+ }
163
+ }
164
+
165
+ return errors
166
+ }
167
+
168
+ function readManifest(dir) {
169
+ return readJson(join(resolve(dir), 'widget.json'))
170
+ }
171
+
172
+ function collectPackageFiles(root, kind) {
173
+ const files = []
174
+ const walk = (current) => {
175
+ for (const entry of readdirSync(current)) {
176
+ const file = join(current, entry)
177
+ const relative = file.slice(root.length + 1).replace(/\\/g, '/')
178
+ if (statSync(file).isDirectory()) {
179
+ walk(file)
180
+ continue
181
+ }
182
+ if (relative === 'README.md' || relative.endsWith('.sill')) continue
183
+ if (allowedFiles(kind).includes(relative) || (kind === 'web' && relative.startsWith('ui/assets/'))) {
184
+ files.push(relative)
185
+ }
186
+ }
187
+ }
188
+ walk(root)
189
+ return files
190
+ }
191
+
192
+ function pack(dir, out) {
193
+ const root = resolve(dir)
194
+ const errors = validateDir(root)
195
+ if (errors.length) {
196
+ for (const error of errors) console.error(` ${error}`)
197
+ return fail('校验失败,未打包')
198
+ }
199
+ const manifest = readManifest(root)
200
+ const kind = manifest.type === 'web' ? 'web' : 'template'
201
+ const target = resolve(out || `${manifest.id}-${manifest.version}.sill`)
202
+ const zip = new AdmZip()
203
+ for (const relative of collectPackageFiles(root, kind)) {
204
+ zip.addFile(relative, readFileSync(join(root, relative)))
205
+ }
206
+ zip.writeZip(target)
207
+ console.log(target)
208
+ }
209
+
210
+ function newWidget(id, dir, template) {
211
+ if (!ID.test(id)) return fail('id 至少两段,只能用小写字母、数字、点和短横线')
212
+ const target = resolve(dir || id)
213
+ if (existsSync(target)) return fail(`目录已存在:${target}`)
214
+ mkdirSync(join(target, 'ui'), { recursive: true })
215
+ const name = id.split('.').pop().replace(/-/g, ' ')
216
+ const web = !template
217
+ const manifest = {
218
+ schema: 1,
219
+ id,
220
+ name,
221
+ version: '1.0.0',
222
+ author: 'you',
223
+ license: 'MIT',
224
+ runtime: '>=0.5.4',
225
+ engine: '>=0.1.0',
226
+ type: web ? 'web' : 'template',
227
+ ...(web ? { trust: 'trusted', size: { w: 384, h: 180 } } : {}),
228
+ span: { default: 1 },
229
+ permissions: ['data.time'],
230
+ data: [{ id: 'now', source: 'time.now' }],
231
+ ui: 'ui/index.html'
232
+ }
233
+ writeFileSync(join(target, 'widget.json'), `${JSON.stringify(manifest, null, 2)}\n`)
234
+ writeFileSync(
235
+ join(target, 'ui/index.html'),
236
+ web
237
+ ? '<div class="widget">\n <div class="widget__label">HELLO</div>\n <div class="widget__host" id="host">—</div>\n <div class="widget__time" id="time">--:--</div>\n</div>\n'
238
+ : '<div class="widget">\n <div class="widget__label">HELLO</div>\n <div class="widget__time" data-sill-text="now.time">--:--</div>\n</div>\n'
239
+ )
240
+ writeFileSync(
241
+ join(target, 'ui/style.css'),
242
+ ':host { display: block; }\n\n.widget {\n color: var(--ink);\n}\n\n.widget__label {\n color: var(--ink-faint);\n font-size: 10px;\n letter-spacing: 0.17em;\n}\n\n.widget__time {\n font-family: var(--serif);\n font-size: 44px;\n font-style: italic;\n}\n'
243
+ )
244
+ if (web) {
245
+ writeFileSync(
246
+ join(target, 'ui/main.js'),
247
+ "const os = require('node:os')\n\ndocument.querySelector('#host').textContent = os.hostname()\n\nsill.ready(({ data }) => {\n document.querySelector('#time').textContent = data.now?.time ?? '--:--'\n})\n"
248
+ )
249
+ }
250
+ console.log(target)
251
+ }
252
+
253
+ function findSillExe() {
254
+ const explicit = process.env.SILL_EXE?.trim()
255
+ if (explicit && existsSync(explicit)) return explicit
256
+ const candidates = []
257
+ if (process.env.LOCALAPPDATA) {
258
+ candidates.push(join(process.env.LOCALAPPDATA, 'Programs', 'Sill', 'Sill.exe'))
259
+ }
260
+ if (process.env.ProgramFiles) {
261
+ candidates.push(join(process.env.ProgramFiles, 'Sill', 'Sill.exe'))
262
+ }
263
+ if (process.env['ProgramFiles(x86)']) {
264
+ candidates.push(join(process.env['ProgramFiles(x86)'], 'Sill', 'Sill.exe'))
265
+ }
266
+ candidates.push(join(homedir(), 'AppData', 'Local', 'Programs', 'Sill', 'Sill.exe'))
267
+ return candidates.find((path) => existsSync(path)) ?? null
268
+ }
269
+
270
+ function devData() {
271
+ const explicit = process.env.SILL_DEV_DATA?.trim()
272
+ if (explicit) return explicit
273
+ return join(process.env.APPDATA || join(homedir(), 'AppData', 'Roaming'), 'Sill-dev')
274
+ }
275
+
276
+ function dev(dir) {
277
+ const root = resolve(dir)
278
+ const errors = validateDir(root)
279
+ if (errors.length) {
280
+ for (const error of errors) console.error(` ${error}`)
281
+ return fail('校验失败,未启动')
282
+ }
283
+
284
+ const data = devData()
285
+ mkdirSync(data, { recursive: true })
286
+ const baseEnv = { ...process.env }
287
+ delete baseEnv.ELECTRON_RUN_AS_NODE
288
+ const exe = findSillExe()
289
+ if (exe) {
290
+ console.log(`sill: dev ${root}`)
291
+ console.log(`sill: Sill ${exe}`)
292
+ console.log(`sill: data ${data}`)
293
+ const child = spawn(exe, [], {
294
+ env: {
295
+ ...baseEnv,
296
+ SILL_DEV_WIDGET: root,
297
+ SILL_USER_DATA: data,
298
+ SILL_DEV: '1'
299
+ },
300
+ stdio: 'inherit'
301
+ })
302
+ child.on('exit', (code) => {
303
+ process.exitCode = code ?? 0
304
+ })
305
+ return
306
+ }
307
+
308
+ const sillRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..')
309
+ if (!existsSync(join(sillRoot, 'package.json'))) {
310
+ return fail('没有找到 Sill.exe。安装 Sill,或设置 SILL_EXE 指向便携版 Sill.exe。')
311
+ }
312
+ console.log('sill: 没有找到已安装的 Sill,回退到源码 pnpm dev')
313
+ const child = spawn('pnpm', ['dev'], {
314
+ cwd: sillRoot,
315
+ env: { ...baseEnv, SILL_DEV_WIDGET: root, SILL_USER_DATA: data, SILL_DEV: '1' },
316
+ stdio: 'inherit',
317
+ shell: process.platform === 'win32'
318
+ })
319
+ child.on('exit', (code) => {
320
+ process.exitCode = code ?? 0
321
+ })
322
+ }
323
+ function main() {
324
+ const [command, ...args] = process.argv.slice(2)
325
+ if (!command || command === 'help' || command === '--help' || command === '-h') {
326
+ usage()
327
+ return
328
+ }
329
+
330
+ if (command === 'validate') {
331
+ const dir = args[0] && !args[0].startsWith('-') ? args[0] : process.cwd()
332
+ const errors = validateDir(dir)
333
+ if (errors.length) {
334
+ for (const error of errors) console.error(` ${error}`)
335
+ return fail('校验失败')
336
+ }
337
+ console.log('ok')
338
+ return
339
+ }
340
+
341
+ if (command === 'pack') {
342
+ let dir = process.cwd()
343
+ for (let index = 0; index < args.length; index += 1) {
344
+ const arg = args[index]
345
+ if (arg === '-o' || arg === '--out') {
346
+ index += 1
347
+ continue
348
+ }
349
+ if (!arg.startsWith('-')) {
350
+ dir = arg
351
+ break
352
+ }
353
+ }
354
+ const outIndex = args.findIndex((arg) => arg === '-o' || arg === '--out')
355
+ const out = outIndex >= 0 ? args[outIndex + 1] : undefined
356
+ if (outIndex >= 0 && !out) return fail('-o 需要文件路径')
357
+ pack(dir, out)
358
+ return
359
+ }
360
+
361
+ if (command === 'new') {
362
+ const template = args.includes('--template')
363
+ const positional = args.filter((arg) => !arg.startsWith('-'))
364
+ if (!positional[0]) return fail('缺少 id')
365
+ newWidget(positional[0], positional[1], template)
366
+ return
367
+ }
368
+
369
+ if (command === 'dev') {
370
+ const dir = args[0] && !args[0].startsWith('-') ? args[0] : process.cwd()
371
+ dev(dir)
372
+ return
373
+ }
374
+
375
+ usage()
376
+ process.exitCode = 1
377
+ }
378
+
379
+ main()
package/package.json CHANGED
@@ -1,6 +1,20 @@
1
1
  {
2
2
  "name": "@heavenlydemon/sill-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "Standalone Sill component CLI: new / validate / pack / dev.",
7
+ "bin": {
8
+ "sill": "bin/sill.js"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "README.md"
13
+ ],
14
+ "engines": {
15
+ "node": ">=20"
16
+ },
17
+ "dependencies": {
18
+ "adm-zip": "^0.6.1"
19
+ }
20
+ }