@wkgeo/cli 2.0.3 → 2.1.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.
@@ -0,0 +1,386 @@
1
+ /**
2
+ * 工作区差异(本地 ↔ 线上基线)—— 「差异检验」第一步:**只读**、零网络请求、零写盘。
3
+ *
4
+ * ## 老板的原始问题(2026-11-22)
5
+ * > 「差异检验:本地与网上有哪些区别,多少文件待发布、多少待下载」
6
+ *
7
+ * 这一步只回答「**模板通道**」上的差异(内容 / 栏目 / 素材的差异是后续的另几条通道,
8
+ * 不在本模块里)。回答分两类:
9
+ * * `added` / `changed` → **待发布**(本地有、基线没有 or 内容变了,push 才会生效);
10
+ * * `removed` → **待下载 / 待确认**(基线(= 线上快照)还有、本地已删 ——
11
+ * push 没有删除动作,只能重新 pull 或人工确认)。
12
+ *
13
+ * ## 为什么是「跟 manifest 比」而不是「跟线上实时比」
14
+ * 1. 本命令的合同是**只读、零写请求**,也**不要求登录**(`templates push --dry-run`
15
+ * 才是「本地 vs 线上实时」的权威口,因为它必须调 `templateGet`);
16
+ * 2. `templates pull` 落盘的 `template-manifest.json` 里记着**拉取当时线上每个文件的
17
+ * sha256 / bytes / contentHash** —— 它就是「上次同步时的线上快照」;
18
+ * 3. 单测 / 验收要能**离线、确定性**地断言计数(线上模板会被人改,不能当断言基线)。
19
+ *
20
+ * ⇒ 口径写清楚:这是「**上次 pull 之后**,本地改了哪些」;要「线上实时差异」请跑
21
+ * `wkgeo templates push --dir <目录>/template --dry-run`。命令的 `notes` 里也这么说。
22
+ *
23
+ * ## 复用与重复
24
+ * `templates-sync.mjs` 里 `scanLocal` **没有导出**(本单写范围也不含那个文件),所以这里
25
+ * 用**它导出的同一套原语**(`assertSafePath` / `sha256Hex` / `isBinaryPath` / `oversizeOf` /
26
+ * `readManifest` / `contentHashOf`)重写了一遍同样的递归遍历 —— 跳过目录 / 路径校验 /
27
+ * 超限跳过 / 排序规则都对齐 `scanLocal`,差别只有「不读正文(text 字段)」,本命令不需要。
28
+ *
29
+ * @typedef {{path:string, bytes:number, sha256:string, encoding:string, binary:boolean}} DiffEntry
30
+ */
31
+
32
+ import fs from 'node:fs';
33
+ import path from 'node:path';
34
+
35
+ import { UsageError } from './errors.mjs';
36
+ import {
37
+ MANIFEST_FILE,
38
+ MAX_FILE_BYTES,
39
+ MAX_FILE_CHARS,
40
+ assertSafePath,
41
+ contentHashOf,
42
+ isBinaryPath,
43
+ oversizeOf,
44
+ oversizeWarning,
45
+ readManifest,
46
+ sha256Hex,
47
+ } from './templates-sync.mjs';
48
+
49
+ /** 工作区里的模板目录名:`<dir>/template/` */
50
+ export const WORKSPACE_TEMPLATE_DIR = 'template';
51
+
52
+ /** 扫描时**不进**的目录(与 `templates-sync.mjs#scanLocal` 的 SKIP_DIRS 保持一致) */
53
+ const SKIP_DIRS = new Set(['.git', 'node_modules', '.tmp-build']);
54
+
55
+ const SHA256_RE = /^[0-9a-f]{64}$/;
56
+
57
+ /** 结构化失败(**不抛栈**:调用方按 code 决定提示 / 退出码) */
58
+ function fail(code, dir, message, extra = {}) {
59
+ return { ok: false, code, dir, message, ...extra };
60
+ }
61
+
62
+ function isFile(abs) {
63
+ try {
64
+ return fs.statSync(abs).isFile();
65
+ } catch {
66
+ return false;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * `--dir` 的解析与安全校验。
72
+ *
73
+ * 拒绝相对路径里的 `..` 段:工作区必须在本命令的工作目录**之内**(要放别处请写绝对路径,
74
+ * 绝对路径是"明确指定"、不是穿越)。这样 `--dir ../x` 不会把差异算到工作区外面去。
75
+ *
76
+ * @returns {{ok:true, root:string, templateDir:string} | {ok:false, ...}}
77
+ */
78
+ function resolveWorkspace({ dir, cwd }) {
79
+ const raw = String(dir === undefined || dir === null ? '' : dir).trim();
80
+ if (!raw) {
81
+ return fail('NO_DIR', path.resolve(cwd), '必须给工作区目录 --dir <目录>(模板在 <目录>/template/)', {
82
+ hint: '例:wkgeo site sync diff --dir .tmp-build/my-site',
83
+ });
84
+ }
85
+ if (raw.includes('\u0000')) return fail('UNSAFE_PATH', raw, '工作区目录含控制字符');
86
+ if (!path.isAbsolute(raw)) {
87
+ const segments = raw.split(/[\\/]+/);
88
+ if (segments.includes('..')) {
89
+ return fail('UNSAFE_PATH', raw, `工作区目录不许用 .. 往上跑:${raw}`, {
90
+ hint: '工作区必须在本命令的工作目录之内;确实在别处就写绝对路径(如 D:\\sites\\my-site)。',
91
+ });
92
+ }
93
+ }
94
+ const root = path.resolve(cwd, raw);
95
+ let stat = null;
96
+ try {
97
+ stat = fs.statSync(root);
98
+ } catch {
99
+ stat = null;
100
+ }
101
+ if (!stat || !stat.isDirectory()) {
102
+ return fail('NO_DIR', root, `工作区目录不存在(或不是目录):${root}`, {
103
+ hint: '先建工作区并 `wkgeo templates pull --dir <工作区>/template` 拉一套模板下来。',
104
+ });
105
+ }
106
+ const templateDir = path.join(root, WORKSPACE_TEMPLATE_DIR);
107
+ let tplStat = null;
108
+ try {
109
+ tplStat = fs.statSync(templateDir);
110
+ } catch {
111
+ tplStat = null;
112
+ }
113
+ if (!tplStat || !tplStat.isDirectory()) {
114
+ return fail('NO_DIR', root, `工作区里没有 ${WORKSPACE_TEMPLATE_DIR}/ 目录:${templateDir}`, {
115
+ hint: `先 \`wkgeo templates pull --dir ${templateDir}\` 把线上模板拉下来。`,
116
+ template_dir: templateDir,
117
+ });
118
+ }
119
+ return { ok: true, root, templateDir };
120
+ }
121
+
122
+ /**
123
+ * 递归扫 `<工作区>/template/`(跳过 manifest / .git / node_modules / .tmp-build,不跟符号链接)。
124
+ * 返回 brief 条目(不存正文,diff 不需要)。
125
+ *
126
+ * @returns {{files: DiffEntry[], skipped: Array<{path:string,bytes:number,measured:number,reason:string}>}}
127
+ * @throws {UsageError} 本地文件路径不安全(与 push 时同一套校验,签名不同就两边一起坏)
128
+ */
129
+ function scanTemplateDir(templateDir) {
130
+ const root = path.resolve(templateDir);
131
+ const absPaths = [];
132
+ const walk = (current) => {
133
+ let entries = [];
134
+ try {
135
+ entries = fs.readdirSync(current, { withFileTypes: true });
136
+ } catch (err) {
137
+ const e = new Error(`读目录失败:${current}——${(err && err.message) || err}`);
138
+ e.code = 'FS_ERROR';
139
+ throw e;
140
+ }
141
+ for (const ent of entries) {
142
+ const abs = path.join(current, ent.name);
143
+ if (ent.isDirectory()) {
144
+ if (SKIP_DIRS.has(ent.name)) continue;
145
+ walk(abs);
146
+ } else if (ent.isFile()) {
147
+ absPaths.push(abs);
148
+ }
149
+ }
150
+ };
151
+ walk(root);
152
+
153
+ const files = [];
154
+ const skipped = [];
155
+ for (const abs of absPaths) {
156
+ const rel = path.relative(root, abs).split(path.sep).join('/');
157
+ if (rel === MANIFEST_FILE) continue;
158
+ const safe = assertSafePath(rel);
159
+ const buf = fs.readFileSync(abs);
160
+ const binary = isBinaryPath(safe);
161
+ const oversize = oversizeOf(safe, buf);
162
+ if (oversize) {
163
+ skipped.push({ path: safe, bytes: buf.length, measured: oversize.measured, reason: oversize.reason });
164
+ continue;
165
+ }
166
+ files.push({
167
+ path: safe,
168
+ bytes: buf.length,
169
+ sha256: sha256Hex(buf),
170
+ encoding: binary ? 'base64' : 'utf8',
171
+ binary,
172
+ });
173
+ }
174
+ files.sort((a, b) => a.path.localeCompare(b.path));
175
+ skipped.sort((a, b) => a.path.localeCompare(b.path));
176
+ return { files, skipped };
177
+ }
178
+
179
+ /**
180
+ * manifest 里的基线文件行 → 可比较的 Map。
181
+ *
182
+ * `../x` 这类路径在**这里**被拒(`assertSafePath`),不读盘、不抛到调用栈。
183
+ */
184
+ function baselineRowsOf(manifest) {
185
+ const rows = [];
186
+ const list = Array.isArray(manifest && manifest.files) ? manifest.files : [];
187
+ list.forEach((one, index) => {
188
+ if (!one || typeof one !== 'object') {
189
+ throw Object.assign(new Error(`${MANIFEST_FILE} 里的 files[${index}] 不是对象`), { code: 'BAD_MANIFEST' });
190
+ }
191
+ const sha = String(one.sha256 || '').toLowerCase();
192
+ if (!SHA256_RE.test(sha)) {
193
+ throw Object.assign(new Error(`${MANIFEST_FILE} 里的 files[${index}].sha256 不是 64 位十六进制(path=${one.path || '(空)'})`), {
194
+ code: 'BAD_MANIFEST',
195
+ });
196
+ }
197
+ const safe = assertSafePath(one.path);
198
+ rows.push({
199
+ path: safe,
200
+ bytes: Number.isFinite(Number(one.bytes)) && Number(one.bytes) >= 0 ? Number(one.bytes) : 0,
201
+ sha256: sha,
202
+ encoding: String(one.encoding || (isBinaryPath(safe) ? 'base64' : 'utf8')),
203
+ binary: isBinaryPath(safe),
204
+ });
205
+ });
206
+ return rows;
207
+ }
208
+
209
+ /**
210
+ * 算「本地工作区 template/ ↔ 上次 pull 的线上基线」的四类差异。
211
+ *
212
+ * 纯本地:**不发任何网络请求、不写任何文件**(连 manifest 都不回写)。
213
+ * 目录 / manifest 的问题都以 `{ok:false, code}` 返回(不抛栈);只有 manifest 是坏 JSON /
214
+ * 坏版本时由 `readManifest` 抛 `CliError`(那条已经带 hint,CLI 会照原样提示),这里翻成
215
+ * `BAD_MANIFEST` 返回,保持"函数只返回、不抛"的一致性。
216
+ *
217
+ * @param {object} opts
218
+ * @param {string} [opts.dir=''] 工作区目录(模板读 `<dir>/template/`)
219
+ * @param {string} [opts.siteId=''] 本次站点(只用于「是不是从别的站拉的」告警,不联网)
220
+ * @param {string} [opts.cwd] 相对 `dir` 的基准目录(默认 `process.cwd()`)
221
+ * @returns {object} ok:true 时形如
222
+ * `{ok, dir, template_dir, site_id, template:{added,changed,removed,unchanged,counts}, workspace:{…}, warnings, baseline}`
223
+ */
224
+ export async function diffWorkspace({ dir = '', siteId = '', cwd = process.cwd() } = {}) {
225
+ const resolved = resolveWorkspace({ dir, cwd });
226
+ if (!resolved.ok) return resolved;
227
+ const { root, templateDir } = resolved;
228
+
229
+ let scanned;
230
+ try {
231
+ scanned = scanTemplateDir(templateDir);
232
+ } catch (err) {
233
+ if (err instanceof UsageError) {
234
+ return fail('UNSAFE_PATH', root, err.message, { hint: err.hint, template_dir: templateDir });
235
+ }
236
+ return fail('FS_ERROR', root, (err && err.message) || String(err), { template_dir: templateDir });
237
+ }
238
+ const local = scanned.files;
239
+ const skipped = scanned.skipped;
240
+ const manifestPath = path.join(templateDir, MANIFEST_FILE);
241
+
242
+ /** 不管有没有 manifest 都先给「工作区里有什么」,面板 / 人都能直接看 */
243
+ const workspace = {
244
+ hasManifest: isFile(manifestPath),
245
+ manifestPath,
246
+ contentHash: null,
247
+ files: local.map((f) => f.path),
248
+ file_count: local.length,
249
+ skipped,
250
+ };
251
+
252
+ if (!workspace.hasManifest) {
253
+ return fail('NO_MANIFEST', root, `工作区里没有模板基线(缺 ${MANIFEST_FILE}):${templateDir}`, {
254
+ template_dir: templateDir,
255
+ workspace,
256
+ hint: `先 \`wkgeo templates pull --dir ${templateDir}\` 拉一套模板下来:manifest 会记住线上每个文件的 sha256,本命令就靠它对账。`,
257
+ });
258
+ }
259
+
260
+ let read = null;
261
+ try {
262
+ read = readManifest(templateDir);
263
+ } catch (err) {
264
+ return fail('BAD_MANIFEST', root, (err && err.message) || String(err), {
265
+ template_dir: templateDir,
266
+ workspace,
267
+ hint: (err && err.hint) || `删掉 ${MANIFEST_FILE} 重新 templates pull 一份`,
268
+ });
269
+ }
270
+ const manifest = read.manifest;
271
+
272
+ let baselineRows;
273
+ try {
274
+ baselineRows = baselineRowsOf(manifest);
275
+ } catch (err) {
276
+ const code = err && err.code === 'BAD_MANIFEST' ? 'BAD_MANIFEST' : 'UNSAFE_PATH';
277
+ return fail(code, root, (err && err.message) || String(err), {
278
+ template_dir: templateDir,
279
+ workspace,
280
+ hint:
281
+ code === 'UNSAFE_PATH'
282
+ ? `manifest 里的文件路径跑出模板目录了(${MANIFEST_FILE} 可能被手改过):重新 templates pull 一份`
283
+ : `重新 templates pull 一份(${MANIFEST_FILE} 被改坏了)`,
284
+ });
285
+ }
286
+
287
+ const warnings = [];
288
+ const baselineSiteId = String((manifest && manifest.siteId) || '');
289
+ const wantedSiteId = String(siteId || '');
290
+ if (wantedSiteId && baselineSiteId && wantedSiteId !== baselineSiteId) {
291
+ warnings.push(
292
+ `这个工作区是从**别的站**拉的(manifest.siteId=${baselineSiteId},本次站点=${wantedSiteId})——` +
293
+ '差异只对 manifest 里那个站有意义,别拿它去推当前站',
294
+ );
295
+ }
296
+
297
+ /** manifest 里的 contentHash 有就信它(并顺手校验),没有就按文件 sha256 重算 */
298
+ const recomputedHash = contentHashOf(baselineRows);
299
+ const declaredHash = String((manifest && manifest.contentHash) || '');
300
+ const contentHash = declaredHash || recomputedHash;
301
+ if (declaredHash && declaredHash !== recomputedHash) {
302
+ warnings.push(
303
+ `manifest.contentHash 与按文件 sha256 重算的对不上(manifest 可能被手改过):以每个文件的 sha256 为准`,
304
+ );
305
+ }
306
+
307
+ for (const one of skipped) {
308
+ warnings.push(
309
+ oversizeWarning(one.path, {
310
+ reason: one.reason,
311
+ measured: one.measured,
312
+ limit: one.reason === 'binary-bytes' ? MAX_FILE_BYTES : MAX_FILE_CHARS,
313
+ }),
314
+ );
315
+ }
316
+
317
+ const localMap = new Map(local.map((f) => [f.path, f]));
318
+ const baselineMap = new Map(baselineRows.map((f) => [f.path, f]));
319
+ const added = [];
320
+ const changed = [];
321
+ const removed = [];
322
+ const unchanged = [];
323
+ for (const f of local) {
324
+ const brief = { path: f.path, bytes: f.bytes, sha256: f.sha256, encoding: f.encoding, binary: f.binary };
325
+ const base = baselineMap.get(f.path);
326
+ if (!base) added.push(brief);
327
+ else if (base.sha256 !== f.sha256) {
328
+ changed.push({ ...brief, baseline_sha256: base.sha256, baseline_bytes: base.bytes });
329
+ } else unchanged.push(brief);
330
+ }
331
+ for (const base of baselineMap.values()) {
332
+ if (localMap.has(base.path)) continue;
333
+ removed.push({
334
+ path: base.path,
335
+ bytes: base.bytes,
336
+ sha256: base.sha256,
337
+ encoding: base.encoding,
338
+ binary: base.binary,
339
+ });
340
+ }
341
+ const byPath = (a, b) => a.path.localeCompare(b.path);
342
+ added.sort(byPath);
343
+ changed.sort(byPath);
344
+ removed.sort(byPath);
345
+ unchanged.sort(byPath);
346
+
347
+ workspace.contentHash = contentHash;
348
+
349
+ const counts = {
350
+ added: added.length,
351
+ changed: changed.length,
352
+ removed: removed.length,
353
+ unchanged: unchanged.length,
354
+ /** 待发布 = 本地新增 + 本地改动(push --confirm 会写的那些) */
355
+ pending_publish: added.length + changed.length,
356
+ /** 待下载 / 待确认 = 线上快照里还有、本地已删(push 没有删除动作) */
357
+ pending_download: removed.length,
358
+ };
359
+
360
+ return {
361
+ ok: true,
362
+ dir: root,
363
+ template_dir: templateDir,
364
+ site_id: wantedSiteId || baselineSiteId || '',
365
+ template: { added, changed, removed, unchanged, counts },
366
+ workspace,
367
+ /** 基线的出处(给人 / 面板看"这是什么时候的线上快照") */
368
+ baseline: {
369
+ source: 'manifest',
370
+ manifest_file: manifestPath,
371
+ site_id: baselineSiteId,
372
+ template_id: String((manifest && manifest.templateId) || ''),
373
+ template_key: String((manifest && manifest.key) || ''),
374
+ pulled_at: String((manifest && manifest.pulledAt) || ''),
375
+ content_hash: contentHash,
376
+ },
377
+ /**
378
+ * 口径提醒(不是错误):本命令只对「上次 pull 的线上快照」,线上在那之后的改动这里看不到。
379
+ * 实时口径交给 `templates push --dry-run`(只算计划、零写请求)。
380
+ */
381
+ baseline_note:
382
+ '基线来自 template-manifest.json(上次 templates pull 的线上快照);要看线上实时差异用 `wkgeo templates push --dir <模板目录> --dry-run`。',
383
+ read_only: true,
384
+ warnings,
385
+ };
386
+ }
package/package.json CHANGED
@@ -1,56 +1,56 @@
1
- {
2
- "name": "@wkgeo/cli",
3
- "version": "2.0.3",
4
- "description": "云站平台官方命令行客户端(@wkgeo/cli):授权登录一次,之后建站 / 下单 / 钱包支付 / 查余额都不用再登录(OAuth 授权码 + PKCE,公共客户端,零第三方依赖)",
5
- "keywords": [
6
- "wkgeo",
7
- "云站",
8
- "cli",
9
- "oauth",
10
- "pkce",
11
- "cloudbase",
12
- "website-builder"
13
- ],
14
- "license": "MIT",
15
- "private": false,
16
- "type": "module",
17
- "bin": {
18
- "wkgeo": "wkgeo.mjs"
19
- },
20
- "main": "./lib/index.mjs",
21
- "exports": {
22
- ".": "./lib/index.mjs"
23
- },
24
- "files": [
25
- "wkgeo.mjs",
26
- "lib",
27
- "spec",
28
- "README.md",
29
- "SKILL.md",
30
- "CHANGELOG.md",
31
- "LICENSE"
32
- ],
33
- "engines": {
34
- "node": ">=18"
35
- },
36
- "scripts": {
37
- "test": "node --test \"test/*.test.mjs\"",
38
- "start": "node wkgeo.mjs",
39
- "build:zip": "node scripts/build-zip.mjs",
40
- "build:exe": "node scripts/build-exe.mjs",
41
- "verify:live": "node scripts/live-verify.mjs",
42
- "verify:live:sql": "node scripts/live-sql.mjs",
43
- "prepublishOnly": "node --test \"test/*.test.mjs\""
44
- },
45
- "dependencies": {},
46
- "optionalDependencies": {},
47
- "publishConfig": {
48
- "access": "public"
49
- },
50
- "repository": {
51
- "type": "git",
52
- "url": "git+https://github.com/kingple/webbuilder.git",
53
- "directory": "cli"
54
- },
55
- "homepage": "https://wkgeo.cn/"
56
- }
1
+ {
2
+ "name": "@wkgeo/cli",
3
+ "version": "2.1.0",
4
+ "description": "云站平台官方命令行客户端(@wkgeo/cli):授权登录一次,之后建站 / 下单 / 钱包支付 / 查余额都不用再登录(OAuth 授权码 + PKCE,公共客户端,零第三方依赖)",
5
+ "keywords": [
6
+ "wkgeo",
7
+ "云站",
8
+ "cli",
9
+ "oauth",
10
+ "pkce",
11
+ "cloudbase",
12
+ "website-builder"
13
+ ],
14
+ "license": "MIT",
15
+ "private": false,
16
+ "type": "module",
17
+ "bin": {
18
+ "wkgeo": "wkgeo.mjs"
19
+ },
20
+ "main": "./lib/index.mjs",
21
+ "exports": {
22
+ ".": "./lib/index.mjs"
23
+ },
24
+ "files": [
25
+ "wkgeo.mjs",
26
+ "lib",
27
+ "spec",
28
+ "README.md",
29
+ "SKILL.md",
30
+ "CHANGELOG.md",
31
+ "LICENSE"
32
+ ],
33
+ "engines": {
34
+ "node": ">=18"
35
+ },
36
+ "scripts": {
37
+ "test": "node --test \"test/*.test.mjs\"",
38
+ "start": "node wkgeo.mjs",
39
+ "build:zip": "node scripts/build-zip.mjs",
40
+ "build:exe": "node scripts/build-exe.mjs",
41
+ "verify:live": "node scripts/live-verify.mjs",
42
+ "verify:live:sql": "node scripts/live-sql.mjs",
43
+ "prepublishOnly": "node --test \"test/*.test.mjs\""
44
+ },
45
+ "dependencies": {},
46
+ "optionalDependencies": {},
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "repository": {
51
+ "type": "git",
52
+ "url": "git+https://github.com/kingple/webbuilder.git",
53
+ "directory": "cli"
54
+ },
55
+ "homepage": "https://wkgeo.cn/"
56
+ }