@wkgeo/cli 1.1.0 → 1.1.1
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/CHANGELOG.md +31 -0
- package/README.md +151 -19
- package/SKILL.md +108 -27
- package/lib/args.mjs +2 -2
- package/lib/asset-role.mjs +68 -0
- package/lib/cms.mjs +2 -2
- package/lib/commands/billing.mjs +56 -10
- package/lib/commands/cms.mjs +49 -13
- package/lib/commands/content.mjs +108 -0
- package/lib/commands/crawl.mjs +219 -0
- package/lib/commands/geo.mjs +1673 -0
- package/lib/commands/index.mjs +640 -541
- package/lib/commands/member.mjs +930 -0
- package/lib/commands/seo.mjs +1386 -0
- package/lib/commands/siteops.mjs +3 -3
- package/lib/commands/sites.mjs +21 -125
- package/lib/commands/template.mjs +1222 -6
- package/lib/config.mjs +16 -13
- package/lib/content-apply.mjs +664 -0
- package/lib/content-check.mjs +887 -0
- package/lib/content-contract.mjs +957 -0
- package/lib/errors.mjs +6 -0
- package/lib/format.mjs +5 -1
- package/lib/manifest-apply.mjs +1499 -0
- package/lib/manifest-schema.json +476 -0
- package/lib/manifest.mjs +1082 -0
- package/lib/oauth-urls.mjs +1 -1
- package/lib/runtime.mjs +5 -1
- package/lib/site-create.mjs +536 -0
- package/lib/template-anim.mjs +1338 -0
- package/lib/template-animation.mjs +232 -0
- package/lib/template-capture.mjs +700 -0
- package/lib/template-gen.mjs +1204 -0
- package/lib/template-pack.mjs +206 -0
- package/lib/template-publish.mjs +733 -0
- package/lib/template-score.mjs +865 -0
- package/lib/template-validate.mjs +368 -0
- package/lib/template-verify.mjs +434 -0
- package/lib/templates-sync.mjs +616 -0
- package/package.json +2 -2
|
@@ -0,0 +1,733 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* **模板发布闭环** —— `wkgeo template publish --dir <模板目录> [--key <k>] [--confirm]`。
|
|
3
|
+
*
|
|
4
|
+
* 一次跑完四步(默认只打印计划,`--confirm` 才真写):
|
|
5
|
+
* ① 打包:读 `template.json.files`(顺序即清单)→ 每个文件 `{path, content}` + sha256;
|
|
6
|
+
* ② 传 OSS:`templates/<key>/<path>` + `templates/<key>/template.json`(桶 `wkgeocom`);
|
|
7
|
+
* ③ upsert 市场行 `public.cms_template_market`(files 就是可预览产物,见 `wkgeo-preview/template-preview.js`);
|
|
8
|
+
* ④ 回读校验:market 行在 + templateId + files 条数与目录一致 + OSS 对象 HEAD 200 + 公网短链可访问。
|
|
9
|
+
*
|
|
10
|
+
* ## 为什么手写签名
|
|
11
|
+
* `cli/package.json` 是 `"dependencies": {}`(CLI 零第三方依赖,任何人 `npx` 即用),
|
|
12
|
+
* 所以**不引 `ali-oss`**,用 `node:crypto` 手写 OSS V1 签名(HMAC-SHA1)——云函数侧
|
|
13
|
+
* `aliyun/fc/wkgeo-cms/src/template-oss.js` 出于同样理由也是手写的。
|
|
14
|
+
*
|
|
15
|
+
* ## 安全
|
|
16
|
+
* * 凭据只从 env 或本机 `.env` 读,**永不打印**(只报"已配置 / 来源路径");
|
|
17
|
+
* * `--confirm` 之前把**市场行 + OSS 前缀清单**存档到 `.tmp-build/t144/`(`--archive` 可改),
|
|
18
|
+
* 真写后再存一份,前后可比;
|
|
19
|
+
* * 发布默认 **prune**:删掉该前缀下不在本次清单里的旧对象(AGENTS.md §2.8「新替旧 + 同批清理」),
|
|
20
|
+
* `--no-prune` 可关;dry-run 只列出将被删的对象,不动手。
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import fs from 'node:fs';
|
|
24
|
+
import fsp from 'node:fs/promises';
|
|
25
|
+
import path from 'node:path';
|
|
26
|
+
import crypto from 'node:crypto';
|
|
27
|
+
|
|
28
|
+
import { CliError } from './errors.mjs';
|
|
29
|
+
|
|
30
|
+
/** 市场表(发布上游:模板市场) */
|
|
31
|
+
export const MARKET_TABLE = 'public.cms_template_market';
|
|
32
|
+
|
|
33
|
+
/** 模板文件白名单(与云函数 `template-oss.js` 保持一致) */
|
|
34
|
+
export const FILE_PATTERN = /\.(html|json|css|js|min\.css|min\.js)$/i;
|
|
35
|
+
|
|
36
|
+
/** 单文件上限(云函数侧同口径:400KB) */
|
|
37
|
+
export const MAX_FILE_BYTES = 400 * 1024;
|
|
38
|
+
|
|
39
|
+
const MIME = {
|
|
40
|
+
'.html': 'text/html; charset=utf-8',
|
|
41
|
+
'.json': 'application/json; charset=utf-8',
|
|
42
|
+
'.css': 'text/css; charset=utf-8',
|
|
43
|
+
'.js': 'application/javascript; charset=utf-8',
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const DEFAULT_BUCKET = 'wkgeocom';
|
|
47
|
+
const DEFAULT_REGION = 'oss-cn-shanghai';
|
|
48
|
+
|
|
49
|
+
const mimeOf = (rel) => MIME[path.extname(rel).toLowerCase()] || 'application/octet-stream';
|
|
50
|
+
const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest('hex');
|
|
51
|
+
const gmtDate = () => new Date().toUTCString();
|
|
52
|
+
|
|
53
|
+
/** 从 `dir` 往上找第一个含 `name` 的目录(最多 8 层),找不到返回 null */
|
|
54
|
+
function findUp(startDir, name) {
|
|
55
|
+
let cur = path.resolve(startDir);
|
|
56
|
+
for (let i = 0; i < 8; i += 1) {
|
|
57
|
+
if (fs.existsSync(path.join(cur, name))) return cur;
|
|
58
|
+
const parent = path.dirname(cur);
|
|
59
|
+
if (parent === cur) break;
|
|
60
|
+
cur = parent;
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 极简 .env 解析(KEY=VALUE / # 注释 / 去引号),**不打印任何值** */
|
|
66
|
+
export function parseEnvFile(file) {
|
|
67
|
+
const out = {};
|
|
68
|
+
let raw = '';
|
|
69
|
+
try {
|
|
70
|
+
raw = fs.readFileSync(file, 'utf8');
|
|
71
|
+
} catch {
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
75
|
+
const s = line.trim();
|
|
76
|
+
if (!s || s.startsWith('#')) continue;
|
|
77
|
+
const i = s.indexOf('=');
|
|
78
|
+
if (i <= 0) continue;
|
|
79
|
+
const k = s.slice(0, i).trim();
|
|
80
|
+
let v = s.slice(i + 1).trim();
|
|
81
|
+
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1);
|
|
82
|
+
out[k] = v;
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* 解析 OSS 凭据:env 优先,其次本机 `oss.env`(沿 cwd 向上找)。
|
|
89
|
+
* 返回值里的 `source` 只写文件路径,不含任何密钥。
|
|
90
|
+
*/
|
|
91
|
+
export function resolveOssCreds({ cwd = process.cwd(), env = process.env } = {}) {
|
|
92
|
+
const fileEnv = (() => {
|
|
93
|
+
const explicit = env.WKGEO_OSS_ENV;
|
|
94
|
+
if (explicit && fs.existsSync(explicit)) return { file: path.resolve(explicit), vars: parseEnvFile(explicit) };
|
|
95
|
+
const root = findUp(cwd, 'oss.env');
|
|
96
|
+
if (!root) return { file: null, vars: {} };
|
|
97
|
+
const file = path.join(root, 'oss.env');
|
|
98
|
+
return { file, vars: parseEnvFile(file) };
|
|
99
|
+
})();
|
|
100
|
+
const pick = (k, fallback = '') => env[k] || fileEnv.vars[k] || fallback;
|
|
101
|
+
return {
|
|
102
|
+
accessKeyId: pick('OSS_ACCESS_KEY_ID'),
|
|
103
|
+
accessKeySecret: pick('OSS_ACCESS_KEY_SECRET'),
|
|
104
|
+
bucket: pick('OSS_BUCKET', DEFAULT_BUCKET),
|
|
105
|
+
region: pick('OSS_REGION', DEFAULT_REGION),
|
|
106
|
+
source: fileEnv.file,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* 解析数据库凭据:env 优先,其次 `tencent/cloudbase/.env`(沿 cwd 向上找)。
|
|
112
|
+
*/
|
|
113
|
+
export function resolveDbCreds({ cwd = process.cwd(), env = process.env } = {}) {
|
|
114
|
+
const explicit = env.WKGEO_CLOUDBASE_ENV;
|
|
115
|
+
const root = explicit && fs.existsSync(explicit) ? explicit : findUp(cwd, path.join('tencent', 'cloudbase', '.env'));
|
|
116
|
+
const file = explicit && fs.existsSync(explicit) ? path.resolve(explicit) : root ? path.join(root, 'tencent', 'cloudbase', '.env') : null;
|
|
117
|
+
const vars = file ? parseEnvFile(file) : {};
|
|
118
|
+
const pick = (k) => env[k] || vars[k] || '';
|
|
119
|
+
return {
|
|
120
|
+
envId: pick('CLOUDBASE_ENV_ID'),
|
|
121
|
+
apiKey: pick('CLOUDBASE_APIKEY'),
|
|
122
|
+
source: file,
|
|
123
|
+
gateway: pick('CLOUDBASE_GATEWAY'),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** 只报"有没有配",不报值 */
|
|
128
|
+
export function credsSummary(creds) {
|
|
129
|
+
return {
|
|
130
|
+
oss: {
|
|
131
|
+
configured: !!(creds.oss.accessKeyId && creds.oss.accessKeySecret),
|
|
132
|
+
bucket: creds.oss.bucket,
|
|
133
|
+
region: creds.oss.region,
|
|
134
|
+
source: creds.oss.source,
|
|
135
|
+
access_key_id_tail: creds.oss.accessKeyId ? creds.oss.accessKeyId.slice(-4) : '',
|
|
136
|
+
},
|
|
137
|
+
db: {
|
|
138
|
+
configured: !!(creds.db.envId && creds.db.apiKey),
|
|
139
|
+
env_id: creds.db.envId,
|
|
140
|
+
source: creds.db.source,
|
|
141
|
+
api_key_tail: creds.db.apiKey ? creds.db.apiKey.slice(-4) : '',
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/* ------------------------------------------------------------------ OSS(V1 签名) */
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* OSS V1 签名:
|
|
150
|
+
* Authorization: OSS <AK>:<base64(HMAC-SHA1(SK, VERB\nContent-MD5\nContent-Type\nDate\n/bucket/key))>
|
|
151
|
+
*
|
|
152
|
+
* 关键坑(已实测踩过):**只有真正的"子资源"才进 CanonicalizedResource**。
|
|
153
|
+
* `prefix` / `marker` / `max-keys` / `delimiter` 是普通查询参数,**不进签名**——
|
|
154
|
+
* 进了会得到 `SignatureDoesNotMatch`(OSS 回包里的 `<StringToSign>` 会显示它只算了 `/bucket/`)。
|
|
155
|
+
* 所以这里 `subresources` 必须显式传(默认空),不跟 URL 的 query 混在一起。
|
|
156
|
+
*/
|
|
157
|
+
export function ossSignature({ method, objectKey = '', subresources = [], contentType = '', contentMd5 = '', date, creds }) {
|
|
158
|
+
const canonResource = `/${creds.bucket}/${objectKey}${subresources.length ? `?${[...subresources].sort().join('&')}` : ''}`;
|
|
159
|
+
const toSign = `${method}\n${contentMd5}\n${contentType}\n${date}\n${canonResource}`;
|
|
160
|
+
const sig = crypto.createHmac('sha1', creds.accessKeySecret).update(toSign, 'utf8').digest('base64');
|
|
161
|
+
return `OSS ${creds.accessKeyId}:${sig}`;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* 发一个 OSS 请求。
|
|
166
|
+
* @param {string} [opts.query] URL 查询串(`prefix=…&max-keys=…`,不参与签名)
|
|
167
|
+
* @param {string[]} [opts.subresources] 真正参与签名的子资源(`versionId=…` 之类,默认空)
|
|
168
|
+
* @returns {Promise<{status:number, headers:Headers, body:Buffer, text:string}>}
|
|
169
|
+
*/
|
|
170
|
+
export async function ossRequest({ creds, method, objectKey = '', query = '', subresources = [], body = null, contentType = '', md5 = null, date = gmtDate(), fetchImpl = fetch }) {
|
|
171
|
+
const host = `https://${creds.bucket}.${creds.region}.aliyuncs.com`;
|
|
172
|
+
const headers = { Date: date };
|
|
173
|
+
if (contentType) headers['Content-Type'] = contentType;
|
|
174
|
+
if (md5) headers['Content-MD5'] = md5;
|
|
175
|
+
headers.Authorization = ossSignature({ method, objectKey, subresources, contentType, contentMd5: md5 || '', date, creds });
|
|
176
|
+
const url = `${host}/${objectKey}${query ? (query.startsWith('?') ? query : `?${query}`) : ''}`;
|
|
177
|
+
const res = await fetchImpl(url, { method, headers, body: body || undefined });
|
|
178
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
179
|
+
return { status: res.status, headers: res.headers, body: buf, text: buf.toString('utf8') };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** PUT 一个对象(带 Content-MD5,传输损坏能立刻发现) */
|
|
183
|
+
export async function ossPut({ creds, objectKey, content, fetchImpl = fetch }) {
|
|
184
|
+
const buf = Buffer.isBuffer(content) ? content : Buffer.from(String(content), 'utf8');
|
|
185
|
+
const md5 = crypto.createHash('md5').update(buf).digest('base64');
|
|
186
|
+
const r = await ossRequest({ creds, method: 'PUT', objectKey, body: buf, contentType: mimeOf(objectKey), md5, fetchImpl });
|
|
187
|
+
if (r.status !== 200) {
|
|
188
|
+
throw new CliError(`OSS 上传失败 ${r.status}:${objectKey}`, {
|
|
189
|
+
kind: 'oss',
|
|
190
|
+
code: 'EOSS',
|
|
191
|
+
hint: (r.text || '').slice(0, 200),
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
return { status: r.status, bytes: buf.length, etag: r.headers.get('etag') || '' };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** HEAD 一个对象(回读校验用;404 → exists:false) */
|
|
198
|
+
export async function ossHead({ creds, objectKey, fetchImpl = fetch }) {
|
|
199
|
+
const r = await ossRequest({ creds, method: 'HEAD', objectKey, fetchImpl });
|
|
200
|
+
return {
|
|
201
|
+
status: r.status,
|
|
202
|
+
exists: r.status === 200,
|
|
203
|
+
bytes: Number(r.headers.get('content-length') || 0),
|
|
204
|
+
etag: r.headers.get('etag') || '',
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** 列前缀下的对象(回读 / 归档 / prune 用),返回 `[{key, bytes, lastModified}]`(按 key 排序) */
|
|
209
|
+
export async function ossList({ creds, prefix, fetchImpl = fetch, maxKeys = 1000 }) {
|
|
210
|
+
const q = `prefix=${prefix}&max-keys=${maxKeys}`;
|
|
211
|
+
const r = await ossRequest({ creds, method: 'GET', objectKey: '', query: q, fetchImpl });
|
|
212
|
+
if (r.status !== 200) {
|
|
213
|
+
throw new CliError(`OSS 列举失败 ${r.status}(prefix=${prefix})`, { kind: 'oss', code: 'EOSS', hint: r.text.slice(0, 200) });
|
|
214
|
+
}
|
|
215
|
+
const xml = r.text || '';
|
|
216
|
+
const out = [];
|
|
217
|
+
for (const m of xml.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)) {
|
|
218
|
+
const seg = m[1];
|
|
219
|
+
const key = (seg.match(/<Key>([\s\S]*?)<\/Key>/) || [])[1] || '';
|
|
220
|
+
const size = Number((seg.match(/<Size>(\d+)<\/Size>/) || [])[1] || 0);
|
|
221
|
+
const lm = (seg.match(/<LastModified>([^<]+)<\/LastModified>/) || [])[1] || '';
|
|
222
|
+
if (key) out.push({ key, bytes: size, lastModified: lm });
|
|
223
|
+
}
|
|
224
|
+
out.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
|
|
225
|
+
return { keys: out, truncated: /<IsTruncated>true<\/IsTruncated>/.test(xml) };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** 删一个对象 */
|
|
229
|
+
export async function ossDelete({ creds, objectKey, fetchImpl = fetch }) {
|
|
230
|
+
const r = await ossRequest({ creds, method: 'DELETE', objectKey, fetchImpl });
|
|
231
|
+
return { status: r.status, ok: r.status === 204 || r.status === 200 || r.status === 404 };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** 公网直链(不签名;桶为公共读时可直接 GET) */
|
|
235
|
+
export function ossPublicUrl({ creds, objectKey }) {
|
|
236
|
+
return `https://${creds.bucket}.${creds.region}.aliyuncs.com/${objectKey}`;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/* ------------------------------------------------------------------ 数据库(CloudBase PG 网关,只读/写都走它) */
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* 执行一条 PG 语句。
|
|
243
|
+
* 通道与 `.tmp-build/qbk/pg.mjs` 相同:POST `<gateway>/v1/rdb/exec-pgsql`
|
|
244
|
+
* body `{sql, parameters, role:'cloudbase_postgres'}`,响应取 `data ?? rows ?? 自身`。
|
|
245
|
+
*/
|
|
246
|
+
export async function dbExec({ creds, sql, parameters = [], fetchImpl = fetch }) {
|
|
247
|
+
const host = creds.gateway || `https://${creds.envId}.api.tcloudbasegateway.com`;
|
|
248
|
+
const res = await fetchImpl(`${host.replace(/\/$/, '')}/v1/rdb/exec-pgsql`, {
|
|
249
|
+
method: 'POST',
|
|
250
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${creds.apiKey}` },
|
|
251
|
+
body: JSON.stringify({ sql, parameters, role: 'cloudbase_postgres' }),
|
|
252
|
+
});
|
|
253
|
+
const text = await res.text();
|
|
254
|
+
let json = null;
|
|
255
|
+
try {
|
|
256
|
+
json = JSON.parse(text);
|
|
257
|
+
} catch {
|
|
258
|
+
json = null;
|
|
259
|
+
}
|
|
260
|
+
if (!res.ok) {
|
|
261
|
+
throw new CliError(`数据库请求失败 ${res.status}`, {
|
|
262
|
+
kind: 'db',
|
|
263
|
+
code: 'EDB',
|
|
264
|
+
hint: (text || '').slice(0, 300),
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
const data = json && (json.data ?? json.rows ?? json.result ?? json);
|
|
268
|
+
const rows = Array.isArray(data) ? data : data && Array.isArray(data.rows) ? data.rows : [];
|
|
269
|
+
return { rows, raw: json };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** 读一行市场模板(不存在返回 null) */
|
|
273
|
+
export async function readMarketRow({ creds, key, fetchImpl = fetch }) {
|
|
274
|
+
const { rows } = await dbExec({
|
|
275
|
+
creds,
|
|
276
|
+
sql: `select id::text as id, key, name, sort, price_cents, coalesce(version, 0) as version, sha256, jsonb_array_length(files) as files_count, enabled, updated_at::text as updated_at from ${MARKET_TABLE} where key = $1 limit 1`,
|
|
277
|
+
parameters: [key],
|
|
278
|
+
fetchImpl,
|
|
279
|
+
});
|
|
280
|
+
return rows[0] || null;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** 删一行市场模板(清理测试用;调用方负责确认 key) */
|
|
284
|
+
export async function deleteMarketRow({ creds, key, fetchImpl = fetch }) {
|
|
285
|
+
const { rows } = await dbExec({
|
|
286
|
+
creds,
|
|
287
|
+
sql: `delete from ${MARKET_TABLE} where key = $1 returning id::text as id, key`,
|
|
288
|
+
parameters: [key],
|
|
289
|
+
fetchImpl,
|
|
290
|
+
});
|
|
291
|
+
return rows[0] || null;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** upsert:`files` 就是这个 key 的完整清单(覆盖写),`version` 自增 */
|
|
295
|
+
export async function upsertMarketRow({ creds, row, fetchImpl = fetch }) {
|
|
296
|
+
const { rows } = await dbExec({
|
|
297
|
+
creds,
|
|
298
|
+
sql: `insert into ${MARKET_TABLE}
|
|
299
|
+
(key, name, summary, files, sort, enabled, price_cents, demo, industries, visible_scope, requires_plugins, version, sha256)
|
|
300
|
+
values ($1, $2, $3, $4::jsonb, $5, true, $6, $7::jsonb, $8::jsonb, 'all', '[]'::jsonb, 1, $9)
|
|
301
|
+
on conflict (key) do update set
|
|
302
|
+
name = excluded.name,
|
|
303
|
+
summary = excluded.summary,
|
|
304
|
+
files = excluded.files,
|
|
305
|
+
sort = excluded.sort,
|
|
306
|
+
enabled = true,
|
|
307
|
+
price_cents = excluded.price_cents,
|
|
308
|
+
demo = excluded.demo,
|
|
309
|
+
industries = excluded.industries,
|
|
310
|
+
version = coalesce(${MARKET_TABLE}.version, 0) + 1,
|
|
311
|
+
sha256 = excluded.sha256,
|
|
312
|
+
updated_at = now()
|
|
313
|
+
returning id::text as id, key, name, sort, price_cents, coalesce(version, 0) as version, sha256, jsonb_array_length(files) as files_count, updated_at::text as updated_at`,
|
|
314
|
+
parameters: [
|
|
315
|
+
row.key,
|
|
316
|
+
row.name,
|
|
317
|
+
row.summary,
|
|
318
|
+
JSON.stringify(row.files),
|
|
319
|
+
row.sort,
|
|
320
|
+
row.price_cents,
|
|
321
|
+
row.demo === null ? null : JSON.stringify(row.demo),
|
|
322
|
+
JSON.stringify(row.industries || []),
|
|
323
|
+
row.sha256,
|
|
324
|
+
],
|
|
325
|
+
fetchImpl,
|
|
326
|
+
});
|
|
327
|
+
return rows[0] || null;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/* ------------------------------------------------------------------ 打包(清单 + 内容) */
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* 读模板目录 → 发布清单。
|
|
334
|
+
* 以 `template.json.files` 为**顺序与范围**(与 `pack` 同口径),另把 `template.json` 本身
|
|
335
|
+
* 也放进 OSS(云函数 `ensureMarketTemplates()` 靠它反推 name/sort/demo/industries)。
|
|
336
|
+
*
|
|
337
|
+
* @returns {Promise<{key, name, summary, sort, price_cents, demo, industries, files:Array<{path,content,bytes,sha256}>, manifest, totalBytes, digest, problems:string[], warnings:string[]}>}
|
|
338
|
+
*/
|
|
339
|
+
export async function collectTemplate({ dir, key = null, maxBytes = MAX_FILE_BYTES } = {}) {
|
|
340
|
+
const root = path.resolve(dir);
|
|
341
|
+
const manifestFile = path.join(root, 'template.json');
|
|
342
|
+
let manifest;
|
|
343
|
+
try {
|
|
344
|
+
manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
|
|
345
|
+
} catch (e) {
|
|
346
|
+
throw new CliError(`读不到 template.json:${manifestFile}`, { kind: 'usage', code: 'ENOTEMPLATE', exitCode: 2, cause: e });
|
|
347
|
+
}
|
|
348
|
+
const outKey = key || manifest.key || path.basename(root);
|
|
349
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(outKey)) {
|
|
350
|
+
throw new CliError(`非法模板 key:${outKey}`, {
|
|
351
|
+
kind: 'usage',
|
|
352
|
+
code: 'EBADKEY',
|
|
353
|
+
exitCode: 2,
|
|
354
|
+
hint: '只允许字母 / 数字 / 下划线 / 连字符,且以字母或数字开头(与云函数文件白名单同口径)',
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
const listed = Array.isArray(manifest.files) ? manifest.files : [];
|
|
358
|
+
const problems = [];
|
|
359
|
+
const warnings = [];
|
|
360
|
+
const files = [];
|
|
361
|
+
for (const rel of listed) {
|
|
362
|
+
const clean = String(rel).replace(/\\/g, '/').replace(/^\/+/, '');
|
|
363
|
+
if (!FILE_PATTERN.test(clean)) {
|
|
364
|
+
problems.push(`不在白名单内:${clean}`);
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
const abs = path.join(root, clean);
|
|
368
|
+
let buf;
|
|
369
|
+
try {
|
|
370
|
+
buf = fs.readFileSync(abs);
|
|
371
|
+
} catch {
|
|
372
|
+
problems.push(`清单里的文件不存在:${clean}`);
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
if (buf.length > maxBytes) problems.push(`${clean} 超过单文件上限 ${maxBytes}B(实际 ${buf.length}B)`);
|
|
376
|
+
files.push({ path: clean, content: buf.toString('utf8'), bytes: buf.length, sha256: sha256(buf) });
|
|
377
|
+
}
|
|
378
|
+
if (!files.some((f) => f.path === 'pages/index.html')) problems.push('清单里没有 pages/index.html');
|
|
379
|
+
const manifestBytes = fs.readFileSync(manifestFile);
|
|
380
|
+
const digest = sha256(
|
|
381
|
+
[...files]
|
|
382
|
+
.sort((a, b) => (a.path < b.path ? -1 : 1))
|
|
383
|
+
.map((f) => `${f.path}\0${f.sha256}\n`)
|
|
384
|
+
.join('')
|
|
385
|
+
);
|
|
386
|
+
if (!manifest.name) warnings.push('template.json 没有 name(市场行会退化成 key)');
|
|
387
|
+
return {
|
|
388
|
+
root,
|
|
389
|
+
key: outKey,
|
|
390
|
+
manifestKey: manifest.key || null,
|
|
391
|
+
name: manifest.name || outKey,
|
|
392
|
+
summary: manifest.summary || '',
|
|
393
|
+
sort: Number.isFinite(manifest.sort) ? manifest.sort : 0,
|
|
394
|
+
price_cents: Number.isFinite(manifest.price_cents) ? manifest.price_cents : 0,
|
|
395
|
+
demoKey: manifest.demoKey || null,
|
|
396
|
+
demo: manifest.demoKey ? { key: manifest.demoKey, name: manifest.name || outKey } : null,
|
|
397
|
+
industries: Array.isArray(manifest.industries) ? manifest.industries : [],
|
|
398
|
+
files,
|
|
399
|
+
manifest,
|
|
400
|
+
manifestBytes: manifestBytes.length,
|
|
401
|
+
totalBytes: files.reduce((n, f) => n + f.bytes, 0) + manifestBytes.length,
|
|
402
|
+
digest,
|
|
403
|
+
problems,
|
|
404
|
+
warnings,
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** 发布计划(dry-run 打印的就是它;`--json` 原样给出) */
|
|
409
|
+
export function buildPlan({ collected, bucket, region, prefix = null, prune = true, ossExisting = null }) {
|
|
410
|
+
const ossPrefix = prefix || `templates/${collected.key}/`;
|
|
411
|
+
const uploads = [
|
|
412
|
+
...collected.files.map((f) => ({ key: `${ossPrefix}${f.path}`, bytes: f.bytes, sha256: f.sha256, source: f.path })),
|
|
413
|
+
{
|
|
414
|
+
key: `${ossPrefix}template.json`,
|
|
415
|
+
bytes: collected.manifestBytes,
|
|
416
|
+
sha256: sha256(Buffer.from(JSON.stringify(collected.manifest, null, 2))),
|
|
417
|
+
source: 'template.json',
|
|
418
|
+
},
|
|
419
|
+
].sort((a, b) => (a.key < b.key ? -1 : 1));
|
|
420
|
+
const existing = ossExisting ? ossExisting.keys : null;
|
|
421
|
+
const stale = existing && prune ? existing.filter((o) => !uploads.some((u) => u.key === o.key)) : [];
|
|
422
|
+
return {
|
|
423
|
+
key: collected.key,
|
|
424
|
+
bucket,
|
|
425
|
+
region,
|
|
426
|
+
oss_prefix: ossPrefix,
|
|
427
|
+
file_count: collected.files.length,
|
|
428
|
+
oss_object_count: uploads.length,
|
|
429
|
+
total_bytes: collected.totalBytes,
|
|
430
|
+
digest: collected.digest,
|
|
431
|
+
uploads,
|
|
432
|
+
market: {
|
|
433
|
+
key: collected.key,
|
|
434
|
+
name: collected.name,
|
|
435
|
+
summary: (collected.summary || '').slice(0, 200),
|
|
436
|
+
sort: collected.sort,
|
|
437
|
+
price_cents: collected.price_cents,
|
|
438
|
+
demo: collected.demo,
|
|
439
|
+
industries: collected.industries,
|
|
440
|
+
files_count: collected.files.length,
|
|
441
|
+
},
|
|
442
|
+
prune: { enabled: prune, existing_count: existing ? existing.length : null, stale },
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/* ------------------------------------------------------------------ 存档 */
|
|
447
|
+
|
|
448
|
+
function archivePaths(archiveDir, key) {
|
|
449
|
+
const base = path.resolve(archiveDir);
|
|
450
|
+
return {
|
|
451
|
+
dir: base,
|
|
452
|
+
plan: path.join(base, `publish-${key}.plan.json`),
|
|
453
|
+
marketBefore: path.join(base, `publish-${key}.market-before.json`),
|
|
454
|
+
ossBefore: path.join(base, `publish-${key}.oss-before.json`),
|
|
455
|
+
marketAfter: path.join(base, `publish-${key}.market-after.json`),
|
|
456
|
+
ossAfter: path.join(base, `publish-${key}.oss-after.json`),
|
|
457
|
+
readback: path.join(base, `publish-${key}.readback.json`),
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
async function writeJson(file, data) {
|
|
462
|
+
await fsp.mkdir(path.dirname(file), { recursive: true });
|
|
463
|
+
await fsp.writeFile(file, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
|
|
464
|
+
return file;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/* ------------------------------------------------------------------ 主流程 */
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* 发布(或 dry-run)。
|
|
471
|
+
*
|
|
472
|
+
* @param {object} opts
|
|
473
|
+
* @param {string} opts.dir 模板目录
|
|
474
|
+
* @param {string} [opts.key] 覆盖 template.json 的 key
|
|
475
|
+
* @param {boolean} [opts.confirm=false] 真写;false = dry-run
|
|
476
|
+
* @param {boolean} [opts.prune=true] 删掉前缀下不在清单里的旧对象
|
|
477
|
+
* @param {string} [opts.archiveDir] 存档目录(默认 `.tmp-build/t144`)
|
|
478
|
+
* @param {boolean} [opts.preview=true] 回读时试一下预览短链
|
|
479
|
+
* @param {object} [opts.creds] 复用已解析凭据(测试用)
|
|
480
|
+
* @param {Function} [opts.fetchImpl]
|
|
481
|
+
* @param {Function} [opts.onStep] 步骤回调(CLI 打进度)
|
|
482
|
+
*/
|
|
483
|
+
export async function publishTemplate({
|
|
484
|
+
dir,
|
|
485
|
+
key = null,
|
|
486
|
+
confirm = false,
|
|
487
|
+
prune = true,
|
|
488
|
+
archiveDir = path.join(process.cwd(), '.tmp-build', 't144'),
|
|
489
|
+
preview = true,
|
|
490
|
+
creds = null,
|
|
491
|
+
fetchImpl = fetch,
|
|
492
|
+
cwd = process.cwd(),
|
|
493
|
+
onStep = () => {},
|
|
494
|
+
} = {}) {
|
|
495
|
+
const collected = await collectTemplate({ dir, key });
|
|
496
|
+
const resolved = creds || { oss: resolveOssCreds({ cwd }), db: resolveDbCreds({ cwd }) };
|
|
497
|
+
if (!resolved.oss.accessKeyId || !resolved.oss.accessKeySecret) {
|
|
498
|
+
throw new CliError('OSS 凭据缺失(OSS_ACCESS_KEY_ID / OSS_ACCESS_KEY_SECRET)', {
|
|
499
|
+
kind: 'usage',
|
|
500
|
+
code: 'ENOCREDS',
|
|
501
|
+
exitCode: 2,
|
|
502
|
+
hint: '写到 oss.env(仓库根)或设进环境变量;本命令不打印任何密钥',
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
if (!resolved.db.envId || !resolved.db.apiKey) {
|
|
506
|
+
throw new CliError('数据库凭据缺失(CLOUDBASE_ENV_ID / CLOUDBASE_APIKEY)', {
|
|
507
|
+
kind: 'usage',
|
|
508
|
+
code: 'ENOCREDS',
|
|
509
|
+
exitCode: 2,
|
|
510
|
+
hint: '写到 tencent/cloudbase/.env 或设进环境变量',
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
const ossCreds = {
|
|
514
|
+
accessKeyId: resolved.oss.accessKeyId,
|
|
515
|
+
accessKeySecret: resolved.oss.accessKeySecret,
|
|
516
|
+
bucket: resolved.oss.bucket,
|
|
517
|
+
region: resolved.oss.region,
|
|
518
|
+
};
|
|
519
|
+
const dbCreds = { envId: resolved.db.envId, apiKey: resolved.db.apiKey, gateway: resolved.db.gateway };
|
|
520
|
+
const paths = archivePaths(archiveDir, collected.key);
|
|
521
|
+
const steps = [];
|
|
522
|
+
const step = (name, status, detail = null) => {
|
|
523
|
+
const item = { step: name, status, detail };
|
|
524
|
+
steps.push(item);
|
|
525
|
+
onStep(item);
|
|
526
|
+
return item;
|
|
527
|
+
};
|
|
528
|
+
|
|
529
|
+
// ① 读目录 + 计划(含现有市场行 / OSS 清单 = "前"存档)
|
|
530
|
+
step('collect', 'ok', { files: collected.files.length, bytes: collected.totalBytes, problems: collected.problems.length });
|
|
531
|
+
const marketBefore = await readMarketRow({ creds: dbCreds, key: collected.key, fetchImpl });
|
|
532
|
+
const ossBefore = await ossList({ creds: ossCreds, prefix: `templates/${collected.key}/`, fetchImpl });
|
|
533
|
+
step('archive-before', 'ok', { market: !!marketBefore, oss_objects: ossBefore.keys.length });
|
|
534
|
+
const plan = buildPlan({
|
|
535
|
+
collected,
|
|
536
|
+
bucket: ossCreds.bucket,
|
|
537
|
+
region: ossCreds.region,
|
|
538
|
+
prune,
|
|
539
|
+
ossExisting: ossBefore,
|
|
540
|
+
});
|
|
541
|
+
await writeJson(paths.plan, plan);
|
|
542
|
+
await writeJson(paths.marketBefore, { taken_at: new Date().toISOString(), row: marketBefore });
|
|
543
|
+
await writeJson(paths.ossBefore, { taken_at: new Date().toISOString(), prefix: plan.oss_prefix, objects: ossBefore.keys });
|
|
544
|
+
|
|
545
|
+
if (collected.problems.length) {
|
|
546
|
+
step('precheck', 'failed', collected.problems);
|
|
547
|
+
throw new CliError(`发布前检查未通过(${collected.problems.length} 项)`, {
|
|
548
|
+
kind: 'publish',
|
|
549
|
+
code: 'EPRECHECK',
|
|
550
|
+
exitCode: 1,
|
|
551
|
+
hint: collected.problems.slice(0, 6).join(';'),
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
if (!confirm) {
|
|
556
|
+
step('dry-run', 'ok', { uploads: plan.uploads.length, would_delete: plan.prune.stale.length });
|
|
557
|
+
return {
|
|
558
|
+
dryRun: true,
|
|
559
|
+
ok: true,
|
|
560
|
+
key: collected.key,
|
|
561
|
+
plan,
|
|
562
|
+
steps,
|
|
563
|
+
archive: paths,
|
|
564
|
+
warnings: collected.warnings,
|
|
565
|
+
before: { market: marketBefore, oss_objects: ossBefore.keys.length },
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// ② 传 OSS
|
|
570
|
+
const uploaded = [];
|
|
571
|
+
for (const up of plan.uploads) {
|
|
572
|
+
const content =
|
|
573
|
+
up.source === 'template.json'
|
|
574
|
+
? Buffer.from(`${JSON.stringify(collected.manifest, null, 2)}\n`, 'utf8')
|
|
575
|
+
: Buffer.from(collected.files.find((f) => f.path === up.source).content, 'utf8');
|
|
576
|
+
const r = await ossPut({ creds: ossCreds, objectKey: up.key, content, fetchImpl });
|
|
577
|
+
uploaded.push({ key: up.key, bytes: r.bytes, etag: r.etag });
|
|
578
|
+
}
|
|
579
|
+
step('oss-upload', 'ok', { objects: uploaded.length, bytes: uploaded.reduce((n, u) => n + u.bytes, 0) });
|
|
580
|
+
|
|
581
|
+
// ③ prune(新替旧;AGENTS.md §2.8)
|
|
582
|
+
const deleted = [];
|
|
583
|
+
for (const stale of plan.prune.stale) {
|
|
584
|
+
const r = await ossDelete({ creds: ossCreds, objectKey: stale.key, fetchImpl });
|
|
585
|
+
if (r.ok) deleted.push(stale.key);
|
|
586
|
+
}
|
|
587
|
+
step('oss-prune', plan.prune.stale.length ? (deleted.length === plan.prune.stale.length ? 'ok' : 'partial') : 'skipped', {
|
|
588
|
+
stale: plan.prune.stale.length,
|
|
589
|
+
deleted: deleted.length,
|
|
590
|
+
});
|
|
591
|
+
|
|
592
|
+
// ④ upsert 市场行(files 顺序 = template.json.files 顺序)
|
|
593
|
+
const row = await upsertMarketRow({
|
|
594
|
+
creds: dbCreds,
|
|
595
|
+
row: {
|
|
596
|
+
key: collected.key,
|
|
597
|
+
name: collected.name,
|
|
598
|
+
summary: collected.summary,
|
|
599
|
+
files: collected.files.map((f) => ({ path: f.path, content: f.content })),
|
|
600
|
+
sort: collected.sort,
|
|
601
|
+
price_cents: collected.price_cents,
|
|
602
|
+
demo: collected.demo,
|
|
603
|
+
industries: collected.industries,
|
|
604
|
+
sha256: collected.digest,
|
|
605
|
+
},
|
|
606
|
+
fetchImpl,
|
|
607
|
+
});
|
|
608
|
+
step('market-upsert', 'ok', row);
|
|
609
|
+
|
|
610
|
+
// ⑤ 回读校验
|
|
611
|
+
const marketAfter = await readMarketRow({ creds: dbCreds, key: collected.key, fetchImpl });
|
|
612
|
+
const ossAfter = await ossList({ creds: ossCreds, prefix: `templates/${collected.key}/`, fetchImpl });
|
|
613
|
+
const heads = [];
|
|
614
|
+
for (const up of plan.uploads) {
|
|
615
|
+
const h = await ossHead({ creds: ossCreds, objectKey: up.key, fetchImpl });
|
|
616
|
+
heads.push({ key: up.key, status: h.status, exists: h.exists, bytes: h.bytes });
|
|
617
|
+
}
|
|
618
|
+
// 桶 `wkgeocom` 是**私有桶**:匿名直链 403 是预期结果(模板由云函数带签名读),
|
|
619
|
+
// 所以这里只当"匿名可读性"信息记录,不据此判失败——"OSS 路径可访问"由上面的逐对象 HEAD 200 证明。
|
|
620
|
+
const publicUrl = ossPublicUrl({ creds: ossCreds, objectKey: `${plan.oss_prefix}template.json` });
|
|
621
|
+
let publicCheck = null;
|
|
622
|
+
try {
|
|
623
|
+
const res = await fetchImpl(publicUrl, { method: 'GET' });
|
|
624
|
+
const body = Buffer.from(await res.arrayBuffer());
|
|
625
|
+
const privateBucket = res.status === 403;
|
|
626
|
+
publicCheck = {
|
|
627
|
+
url: publicUrl,
|
|
628
|
+
status: res.status,
|
|
629
|
+
bytes: body.length,
|
|
630
|
+
anonymous_readable: res.status === 200 && body.length > 0,
|
|
631
|
+
bucket_private: privateBucket,
|
|
632
|
+
ok: (res.status === 200 && body.length > 0) || privateBucket,
|
|
633
|
+
note: privateBucket ? '私有桶,匿名直链 403 属预期;可访问性看 oss_all_head_200' : null,
|
|
634
|
+
};
|
|
635
|
+
} catch (e) {
|
|
636
|
+
publicCheck = { url: publicUrl, status: 0, bytes: 0, ok: false, error: String(e && e.message) };
|
|
637
|
+
}
|
|
638
|
+
let previewCheck = null;
|
|
639
|
+
if (preview) {
|
|
640
|
+
const url = `https://wkgeo.cn/cms/template/preview?key=${encodeURIComponent(collected.key)}&device=desktop`;
|
|
641
|
+
try {
|
|
642
|
+
const res = await fetchImpl(url, { method: 'GET', redirect: 'follow' });
|
|
643
|
+
const body = Buffer.from(await res.arrayBuffer());
|
|
644
|
+
previewCheck = { url, status: res.status, bytes: body.length, ok: res.status === 200 && body.length > 1000 };
|
|
645
|
+
} catch (e) {
|
|
646
|
+
previewCheck = { url, status: 0, bytes: 0, ok: false, error: String(e && e.message) };
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
const checks = {
|
|
651
|
+
market_row_exists: !!marketAfter,
|
|
652
|
+
template_id: marketAfter ? marketAfter.id : null,
|
|
653
|
+
files_count_matches: marketAfter ? Number(marketAfter.files_count) === collected.files.length : false,
|
|
654
|
+
files_count_expected: collected.files.length,
|
|
655
|
+
files_count_actual: marketAfter ? Number(marketAfter.files_count) : null,
|
|
656
|
+
oss_object_count_expected: plan.uploads.length,
|
|
657
|
+
oss_object_count_actual: ossAfter.keys.length,
|
|
658
|
+
oss_all_head_200: heads.every((h) => h.exists),
|
|
659
|
+
oss_head_missing: heads.filter((h) => !h.exists).map((h) => h.key),
|
|
660
|
+
public_object: publicCheck,
|
|
661
|
+
preview_page: previewCheck,
|
|
662
|
+
digest_matches: marketAfter ? String(marketAfter.sha256 || '') === collected.digest : false,
|
|
663
|
+
};
|
|
664
|
+
const ok =
|
|
665
|
+
checks.market_row_exists &&
|
|
666
|
+
checks.files_count_matches &&
|
|
667
|
+
checks.oss_object_count_actual === plan.uploads.length &&
|
|
668
|
+
checks.oss_all_head_200 &&
|
|
669
|
+
(!publicCheck || publicCheck.ok);
|
|
670
|
+
step('readback', ok ? 'ok' : 'failed', checks);
|
|
671
|
+
|
|
672
|
+
await writeJson(paths.marketAfter, { taken_at: new Date().toISOString(), row: marketAfter });
|
|
673
|
+
await writeJson(paths.ossAfter, { taken_at: new Date().toISOString(), prefix: plan.oss_prefix, objects: ossAfter.keys });
|
|
674
|
+
await writeJson(paths.readback, { taken_at: new Date().toISOString(), ok, checks, steps, uploaded, deleted });
|
|
675
|
+
|
|
676
|
+
return {
|
|
677
|
+
dryRun: false,
|
|
678
|
+
ok,
|
|
679
|
+
key: collected.key,
|
|
680
|
+
plan,
|
|
681
|
+
steps,
|
|
682
|
+
archive: paths,
|
|
683
|
+
warnings: collected.warnings,
|
|
684
|
+
before: { market: marketBefore, oss_objects: ossBefore.keys.length },
|
|
685
|
+
after: { market: marketAfter, oss_objects: ossAfter.keys.length },
|
|
686
|
+
uploaded,
|
|
687
|
+
deleted,
|
|
688
|
+
checks,
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/** 清理一个测试 key:删市场行 + 删 OSS 前缀下所有对象(只给测试 / 回滚用) */
|
|
693
|
+
export async function cleanupTemplate({ key, creds = null, cwd = process.cwd(), fetchImpl = fetch }) {
|
|
694
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(String(key || ''))) {
|
|
695
|
+
throw new CliError(`非法 key:${key}`, { kind: 'usage', code: 'EBADKEY', exitCode: 2 });
|
|
696
|
+
}
|
|
697
|
+
const resolved = creds || { oss: resolveOssCreds({ cwd }), db: resolveDbCreds({ cwd }) };
|
|
698
|
+
const ossCreds = resolved.oss;
|
|
699
|
+
const dbCreds = resolved.db;
|
|
700
|
+
const before = await ossList({ creds: ossCreds, prefix: `templates/${key}/`, fetchImpl });
|
|
701
|
+
const removed = [];
|
|
702
|
+
for (const obj of before.keys) {
|
|
703
|
+
const r = await ossDelete({ creds: ossCreds, objectKey: obj.key, fetchImpl });
|
|
704
|
+
if (r.ok) removed.push(obj.key);
|
|
705
|
+
}
|
|
706
|
+
const row = await deleteMarketRow({ creds: dbCreds, key, fetchImpl });
|
|
707
|
+
const after = await ossList({ creds: ossCreds, prefix: `templates/${key}/`, fetchImpl });
|
|
708
|
+
const rowAfter = await readMarketRow({ creds: dbCreds, key, fetchImpl });
|
|
709
|
+
return { key, removed, row, oss_before: before.keys.length, oss_after: after.keys.length, market_before: !!row, market_after: !!rowAfter };
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
export default {
|
|
713
|
+
publishTemplate,
|
|
714
|
+
collectTemplate,
|
|
715
|
+
buildPlan,
|
|
716
|
+
cleanupTemplate,
|
|
717
|
+
resolveOssCreds,
|
|
718
|
+
resolveDbCreds,
|
|
719
|
+
credsSummary,
|
|
720
|
+
ossPut,
|
|
721
|
+
ossHead,
|
|
722
|
+
ossList,
|
|
723
|
+
ossDelete,
|
|
724
|
+
ossPublicUrl,
|
|
725
|
+
ossSignature,
|
|
726
|
+
readMarketRow,
|
|
727
|
+
upsertMarketRow,
|
|
728
|
+
deleteMarketRow,
|
|
729
|
+
dbExec,
|
|
730
|
+
FILE_PATTERN,
|
|
731
|
+
MAX_FILE_BYTES,
|
|
732
|
+
MARKET_TABLE,
|
|
733
|
+
};
|