onboarding-cloud-patch.mjs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /** Surgical source transform shared by local preview and the single-function deployment. */
  2. import fs from 'node:fs';
  3. import assert from 'node:assert/strict';
  4. import vm from 'node:vm';
  5. export const BEGIN = '// FMODE_SELF_HOSTED_ONBOARDING_BEGIN';
  6. export const END = '// FMODE_SELF_HOSTED_ONBOARDING_END';
  7. export function patchOnboarding(source, bundle) {
  8. assert.match(bundle.url, /^https:\/\/s3\.fmode\.cn\//);
  9. assert.match(bundle.sha256, /^[a-f0-9]{64}$/);
  10. const newline = source.includes('\r\n') ? '\r\n' : '\n';
  11. const helper = fs.readFileSync(new URL('../cloud/onboarding/prompt.js', import.meta.url), 'utf8').trim().replace(/\r?\n/g, newline);
  12. const owned = [BEGIN, 'var CONTAINER_ONBOARDING_BUNDLE = ' + JSON.stringify(bundle) + ';', helper, END, ''].join(newline);
  13. if (source.includes(BEGIN)) {
  14. const start = source.indexOf(BEGIN), end = source.indexOf(END, start);
  15. assert.ok(end > start && source.indexOf(BEGIN, start + BEGIN.length) < 0, '已有提示词区域不明确');
  16. source = source.slice(0, start) + owned + source.slice(end + END.length).replace(/^\r?\n/, '');
  17. } else {
  18. const anchor = "var CLASS_JOB = 'FmodeProvisionJob';";
  19. assert.equal(source.split(anchor).length, 2, '云函数头部结构发生变化,停止定向更新');
  20. source = source.replace(anchor, owned + newline + anchor);
  21. }
  22. const call = ' var instruction = _buildSelfHostedInstruction(oa.id, containerName, prov0, derivedPass, token0, ownerMx, CONTAINER_ONBOARDING_BUNDLE);';
  23. const start = source.indexOf(' var mxPass = derivedPass ||');
  24. if (start >= 0) {
  25. const end = source.indexOf("].join('\\n');", start);
  26. assert.ok(end > start && source.slice(start, end).includes('【Fmode 接入提示词】'), '原试用提示词片段不匹配,停止更新');
  27. source = source.slice(0, start) + call + source.slice(end + "].join('\\n');".length);
  28. } else assert.ok(source.includes(call), '没有找到已知试用接入分支');
  29. if (!source.includes('onboardingBundle: CONTAINER_ONBOARDING_BUNDLE')) {
  30. const marker = " mode: 'onboarding',";
  31. assert.equal(source.split(marker).length, 2, '试用响应结构发生变化');
  32. source = source.replace(marker, marker + newline + ' onboardingBundle: CONTAINER_ONBOARDING_BUNDLE,');
  33. }
  34. new vm.Script(source);
  35. return source;
  36. }