apply-onboarding-prompt.mjs 6.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /** Preview/apply only the onboarding text in one existing cloud function. */
  2. import { recordProgress } from './lib/project-recovery.mjs';
  3. import fs from 'node:fs';
  4. import assert from 'node:assert/strict';
  5. import { createHash } from 'node:crypto';
  6. import { patchOnboarding } from './onboarding-cloud-patch.mjs';
  7. const stage = process.argv.find(x => x.startsWith('--stage='))?.slice(8) || 'preview';
  8. const out = 'test-results/new-account-20261128';
  9. const privateDir = '.local-backup/new-account-20261128';
  10. const tag = process.argv.find(x => x.startsWith('--tag='))?.slice(6) || '';
  11. assert.match(tag, /^[a-zA-Z0-9-]*$/);
  12. const suffix = tag ? '-' + tag : '';
  13. const previewFile = out + '/cloud-prompt-preview' + suffix + '.json';
  14. const beforeFile = privateDir + '/provision-cloud-preview-before' + suffix + '.json';
  15. const candidateFile = privateDir + '/provision-cloud-candidate' + suffix + '.js';
  16. const target = 'VtW1GT93Ax';
  17. const url = 'https://server.fmode.cn/parse/classes/Function/' + target;
  18. const cfg = JSON.parse(fs.readFileSync('.claude/dev-login.json'));
  19. const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'ncloudmaster', 'X-Parse-Master-Key': cfg.masterKey };
  20. const digest = code => createHash('sha256').update(code).digest('hex');
  21. const note = text => recordProgress(process.cwd(), `[${out}] ${text}`);
  22. async function read() {
  23. const response = await fetch(url, { headers, signal: AbortSignal.timeout(25000) });
  24. assert.ok(response.ok, '云函数只读回验 HTTP ' + response.status);
  25. const row = await response.json(); assert.equal(row.name, 'fmode-provisioning'); assert.equal(typeof row.code, 'string'); return row;
  26. }
  27. let lock, state;
  28. const stateFile = out + '/state.json';
  29. const save = () => { fs.writeFileSync(stateFile + '.next', JSON.stringify(state, null, 2)); fs.renameSync(stateFile + '.next', stateFile); };
  30. try {
  31. if (stage === 'apply') { lock = fs.openSync(out + '/runner.lock', 'wx'); fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, stage: 'cloud-prompt' })); state = JSON.parse(fs.readFileSync(stateFile)); }
  32. if (stage === 'preview') {
  33. const bundle = JSON.parse(fs.readFileSync('cloud/onboarding/bundle.json'));
  34. const remote = await read();
  35. const candidate = patchOnboarding(remote.code, bundle);
  36. const local = fs.readFileSync('cloud/functions/fmode-provisioning.js', 'utf8');
  37. fs.writeFileSync(beforeFile, JSON.stringify(remote, null, 2), { flag: 'wx' });
  38. fs.writeFileSync(candidateFile, candidate, { flag: 'wx' });
  39. fs.writeFileSync('cloud/functions/fmode-provisioning.js', patchOnboarding(local, bundle));
  40. const preview = { target, name: remote.name, originalUpdatedAt: remote.updatedAt, originalVersion: remote.version,
  41. oldSha256: digest(remote.code), newSha256: digest(candidate), bundleSha256: bundle.sha256, bundle, oldBytes: Buffer.byteLength(remote.code), newBytes: Buffer.byteLength(candidate) };
  42. fs.writeFileSync(previewFile, JSON.stringify(preview, null, 2), { flag: 'wx' });
  43. note(`已生成可审查候选,目标 ${target},旧源码 ${preview.oldSha256},候选 ${preview.newSha256};仅替换试用提示词及添加通用包元数据,线上其他逻辑来自刚刚回读版本,尚未 PUT。`);
  44. console.log(JSON.stringify(preview));
  45. } else if (stage === 'apply') {
  46. assert.ok(!state.actions.cloudPrompt?.attempted, '定向更新已有动作记录,先 status 只读核实,不能重复 PUT');
  47. const preview = JSON.parse(fs.readFileSync(previewFile));
  48. assert.equal(preview.target, target, '预览不属于指定目标云函数');
  49. const bundle = JSON.parse(fs.readFileSync('cloud/onboarding/bundle.json'));
  50. assert.equal(preview.bundleSha256, bundle.sha256, '预览与当前包摘要不一致,停止更新');
  51. assert.deepEqual(preview.bundle, bundle, '预览与当前包完整元数据不一致,停止更新');
  52. const published = Object.entries(state.actions).find(([key, action]) => key.startsWith('publishBundle') && action.confirmedAt && action.sha256 === bundle.sha256)?.[1];
  53. assert.ok(published && published.receipt?.url === bundle.url, '当前包尚无同摘要公开上传回验');
  54. const asset = await fetch(bundle.url, { signal: AbortSignal.timeout(30000) });
  55. assert.ok(asset.ok, '部署前接入包公开对象不可读');
  56. assert.equal(digest(Buffer.from(await asset.arrayBuffer())), bundle.sha256, '部署前公开包摘要不一致');
  57. const candidate = fs.readFileSync(candidateFile, 'utf8');
  58. assert.equal(digest(candidate), preview.newSha256);
  59. const before = await read();
  60. assert.equal(digest(before.code), preview.oldSha256, '线上源码在预览后发生变化,停止覆盖');
  61. assert.equal(candidate, patchOnboarding(before.code, bundle), '候选不是当前线上源码的指定提示词补丁,停止覆盖');
  62. state.actions.cloudPrompt = { attempted: true, at: new Date().toISOString(), target,
  63. oldSha256: preview.oldSha256, newSha256: preview.newSha256, bundleSha256: bundle.sha256, previewFile, phase: 'before-put' }; save();
  64. note(`准备对 Function/${target} 执行一次 PUT,候选 ${preview.newSha256},备份 ${beforeFile};不批量更新云函数。`);
  65. const response = await fetch(url, { method: 'PUT', headers, body: JSON.stringify({ code: candidate, version: '0.9.2' }), signal: AbortSignal.timeout(30000) });
  66. state.actions.cloudPrompt.putHttp = response.status; save();
  67. const body = await response.json(); fs.writeFileSync(out + '/cloud-prompt-put-response' + suffix + '.json', JSON.stringify(body, null, 2), { flag: 'wx' });
  68. assert.ok(response.ok && !body.error, '定向更新未确认,先 status 核实');
  69. const after = await read(); assert.equal(digest(after.code), preview.newSha256, '云端源码回验不一致');
  70. state.actions.cloudPrompt.confirmedAt = new Date().toISOString();
  71. state.actions.cloudPrompt.receipt = { target, updatedAt: after.updatedAt, version: after.version, sha256: digest(after.code) }; save();
  72. note(`目标云函数已定向更新并回读摘要一致,版本 ${after.version},回执 ${out}/cloud-prompt-put-response${suffix}.json;待从 APK 重新取得提示词并执行下载校验安装。`);
  73. console.log(JSON.stringify(state.actions.cloudPrompt.receipt));
  74. } else if (stage === 'status') {
  75. const remote = await read();
  76. console.log(JSON.stringify({ target, version: remote.version, updatedAt: remote.updatedAt, sha256: digest(remote.code) }));
  77. } else throw Error('未知阶段:' + stage);
  78. } catch (error) {
  79. if (lock !== undefined && state) { state.lastFailure = { stage: 'cloud-prompt', at: new Date().toISOString(), message: error.message }; save(); note(`未完成:${error.message};恢复先 status,不重复更新。`); }
  80. throw error;
  81. } finally { if (lock !== undefined) { fs.closeSync(lock); fs.unlinkSync(out + '/runner.lock'); } }