build-used-car-request-slim.mjs 7.85 KB
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import {
  copyFileSync,
  existsSync,
  mkdtempSync,
  readFileSync,
  readdirSync,
  rmSync,
  writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const packageSpec = 'glsk-toolkit@1.0.5';
const expectedIntegrity =
  'sha512-BUWYTM5NWzN0n2jho6b5nbTwfCiQHBz+Ce5DN6MmJi8pQxI+AXFqgD5DDY1BfRdXjAVsHXdyBauw1VJjFX3Tqw==';
const lockPath = path.join(projectRoot, 'scripts/used-car-request-slim.package-lock.json');
const outputPath = path.join(projectRoot, 'packageUsedCar/newRequestIndex.js');
const npmCommand = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const refreshLock = process.argv.includes('--refresh-lock');

function run(command, args, cwd) {
  const result = spawnSync(command, args, {
    cwd,
    encoding: 'utf8',
    shell: process.platform === 'win32' && command === npmCommand,
    stdio: ['ignore', 'pipe', 'pipe'],
  });
  if (result.status !== 0) {
    throw new Error(
      `${command} ${args.join(' ')} failed\n${result.stdout || ''}\n${result.stderr || ''}`,
    );
  }
  return result.stdout;
}

function readNormalized(filePath) {
  return readFileSync(filePath, 'utf8').replace(/\r\n/g, '\n');
}

function replaceOnce(filePath, before, after) {
  const source = readNormalized(filePath);
  const first = source.indexOf(before);
  assert.notEqual(first, -1, `missing source anchor in ${filePath}: ${before}`);
  assert.equal(
    source.indexOf(before, first + before.length),
    -1,
    `duplicate source anchor in ${filePath}: ${before}`,
  );
  writeFileSync(filePath, source.replace(before, after), 'utf8');
}

function removeSectionOnce(filePath, start, end) {
  const source = readNormalized(filePath);
  const startIndex = source.indexOf(start);
  assert.notEqual(startIndex, -1, `missing section start in ${filePath}: ${start}`);
  assert.equal(
    source.indexOf(start, startIndex + start.length),
    -1,
    `duplicate section start in ${filePath}: ${start}`,
  );
  const endIndex = source.indexOf(end, startIndex + start.length);
  assert.notEqual(endIndex, -1, `missing section end in ${filePath}: ${end}`);
  writeFileSync(filePath, source.slice(0, startIndex) + source.slice(endIndex), 'utf8');
}

function collectFiles(directory) {
  return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
    const entryPath = path.join(directory, entry.name);
    return entry.isDirectory() ? collectFiles(entryPath) : [entryPath];
  });
}

const buildRoot = mkdtempSync(path.join(tmpdir(), 'glsk-toolkit-slim-'));
try {
  const packOutput = run(
    npmCommand,
    ['pack', packageSpec, '--json', '--pack-destination', buildRoot],
    projectRoot,
  );
  const [packed] = JSON.parse(packOutput);
  assert.equal(packed.integrity, expectedIntegrity, 'npm metadata integrity mismatch');

  const tarballPath = path.join(buildRoot, packed.filename);
  const actualIntegrity = `sha512-${createHash('sha512')
    .update(readFileSync(tarballPath))
    .digest('base64')}`;
  assert.equal(actualIntegrity, expectedIntegrity, 'tarball integrity mismatch');
  run('tar', ['-xf', tarballPath, '-C', buildRoot], projectRoot);

  const sourceRoot = path.join(buildRoot, 'package');
  const packageJsonPath = path.join(sourceRoot, 'package.json');
  const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
  assert.equal(packageJson.dependencies['@sentry/browser'], '^7.101.1');
  delete packageJson.dependencies['@sentry/browser'];
  writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}\n`, 'utf8');

  const indexPath = path.join(sourceRoot, 'src/index.ts');
  replaceOnce(indexPath, "import * as Sentry from './monitoring/sentry';\n", '');
  replaceOnce(
    indexPath,
    'export { Request, Defaults, Sentry, simpleGet, generateUUID };',
    'export { Request, Defaults, simpleGet, generateUUID };',
  );
  replaceOnce(
    indexPath,
    "export type { SentryOptions, ErrorReportOptions } from './monitoring/sentry';",
    '',
  );

  const requestPath = path.join(sourceRoot, 'src/core/request.ts');
  replaceOnce(requestPath, 'import { initSentry } from "../monitoring/sentry";\n', '');
  replaceOnce(
    requestPath,
    '    // 根据配置决定是否初始化 Sentry\n    if (this.defaults.sentry.enable && this.defaults.sentry.dsn) {\n      initSentry(this.defaults.sentry.dsn, this.defaults.sentry.options || {});\n    }\n',
    '',
  );

  const defaultsPath = path.join(sourceRoot, 'src/core/defaults.ts');
  replaceOnce(
    defaultsPath,
    '  // Sentry 配置\n  sentry: {\n    enable: boolean;\n    dsn?: string;\n    options?: Record<string, any>;\n  };\n',
    '',
  );
  replaceOnce(
    defaultsPath,
    '    // 检查必填参数\n    if (config.sentry?.enable && !config.sentry?.dsn) {\n      throw new Error("sentry.dsn is required when sentry is enabled");\n    }\n',
    '',
  );
  replaceOnce(
    defaultsPath,
    '    this.sentry = {\n      enable: config.sentry?.enable ?? false,\n      dsn: config.sentry?.dsn,\n      options: config.sentry?.options || {},\n    };\n',
    '',
  );

  const libsIndexPath = path.join(sourceRoot, 'src/libs/index.ts');
  replaceOnce(libsIndexPath, "import * as Sentry from './sentry-miniapp'\n", '');
  replaceOnce(libsIndexPath, 'export { Sentry, stringify }', 'export { stringify }');

  const errorPath = path.join(sourceRoot, 'src/utils/error.ts');
  replaceOnce(errorPath, "import { reportNetworkError } from '../monitoring/sentry';\n\n", '');
  replaceOnce(
    errorPath,
    '    // 如果配置中包含 sentry.dsn,则上报错误到 Sentry\n  if (config && config.sentry?.dsn) {\n      this.reportToSentry();\n    }\n',
    '',
  );
  removeSectionOnce(
    errorPath,
    '  /**\n   * 将错误上报到 Sentry\n',
    '  /**\n   * 创建网络错误\n',
  );

  const typesPath = path.join(sourceRoot, 'src/types/index.d.ts');
  removeSectionOnce(
    typesPath,
    'export interface SentryConfig {\n',
    'export interface ResponseConfig {\n',
  );
  replaceOnce(
    typesPath,
    '  sentry?: SentryConfig; // Sentry配置,包含错误上报开关、DSN和选项\n',
    '',
  );

  for (const relativePath of [
    'src/monitoring/sentry.ts',
    'src/libs/sentry-miniapp.js',
    'src/libs/sentry-miniapp.d.ts',
  ]) {
    const sentrySourcePath = path.join(sourceRoot, relativePath);
    assert.ok(existsSync(sentrySourcePath), `missing Sentry source: ${relativePath}`);
    rmSync(sentrySourcePath);
  }

  const sentryResidues = [packageJsonPath, ...collectFiles(path.join(sourceRoot, 'src'))]
    .filter((filePath) => /sentry/i.test(readFileSync(filePath, 'utf8')))
    .map((filePath) => path.relative(sourceRoot, filePath));
  assert.deepEqual(sentryResidues, [], `Sentry source residues: ${sentryResidues.join(', ')}`);

  if (refreshLock) {
    run(
      npmCommand,
      ['install', '--package-lock-only', '--ignore-scripts', '--no-audit', '--no-fund'],
      sourceRoot,
    );
    copyFileSync(path.join(sourceRoot, 'package-lock.json'), lockPath);
  }

  assert.ok(existsSync(lockPath), 'dedicated build lock is missing; run with --refresh-lock once');
  copyFileSync(lockPath, path.join(sourceRoot, 'package-lock.json'));
  run(npmCommand, ['ci', '--ignore-scripts', '--no-audit', '--no-fund'], sourceRoot);
  run(npmCommand, ['run', 'build'], sourceRoot);

  const generatedPath = path.join(sourceRoot, 'dist/index.js');
  const generated = readFileSync(generatedPath, 'utf8');
  assert.doesNotMatch(generated, /sentry/i, 'generated bundle still contains Sentry');
  copyFileSync(generatedPath, outputPath);
  console.log(
    `[build-used-car-request-slim] wrote ${Buffer.byteLength(generated)} bytes to ${path.relative(
      projectRoot,
      outputPath,
    )}`,
  );
} finally {
  rmSync(buildRoot, { recursive: true, force: true });
}