All files / packages/design-system/scripts/scs scs.js

0% Statements 0/133
0% Branches 0/50
0% Functions 0/18
0% Lines 0/130

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
#!/usr/bin/env node
/**
 * SCS (Static Content Service) Release Script
 *
 * Assembles a new slds-scs release directly in packages/slds-scs/. SFCI
 * publishes the org.sfs:slds-scs JAR + slds-modules npm package from that
 * package on the core-*-patch branches (see the root .strata.yml publish
 * legs); this script's only job is to produce and commit the payload.
 *
 * Assemble:
 *   Copies versioned CSS files from SLDS1 and SLDS2 dist outputs into
 *   packages/slds-scs/slds/ (including slds-plus and scoped-slds-plus), runs
 *   FileParser to update scs/files.json with version retention, bumps the
 *   package version, and optionally updates the scs-client JAR. All of these
 *   files are tracked in this monorepo;
 *   the run finishes by committing them on the current branch.
 *
 * Configuration sources (in priority order):
 *   1. CLI arguments (--key=value)
 *   2. Environment variables
 *   3. .release-config (versions, WI)
 *   4. .distrc.json (nexusCreds)
 *   5. Interactive prompts
 *
 * Usage:
 *   yarn workspace @salesforce-ux/design-system scs
 *   yarn workspace @salesforce-ux/design-system scs -- --wi W-9925295 --case=29996318
 *
 * Prerequisites:
 *   - TMP Auth (for Nexus scs-client lookup)
 *   - .distrc.json with nexusCreds (or provide via CLI/prompt)
 *   - .release-config with version info (or provide via CLI/prompt)
 */
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import process from 'node:process';
import fs from 'fs-extra';
import execa from './exec-adapter.js';
import enquirer from 'enquirer';
const { prompt } = enquirer;
 
import { FileParser } from './file-parser.js';
import { loadConfig } from './config-loader.js';
import * as autoVersion from './version-utils.js';
import { bumpScsVersionFromNexus, commitInMonorepo, releaseCommitMessage } from './scs-helpers.js';
import {
  assertReleaseArtifactVersion,
  copyVerifiedReleaseArtifacts,
  writeScsPublicationMap,
  writeScsAssemblyManifest,
} from './artifact-provenance.js';
 
// ------------------------------------------------------------------
// Path setup
// ------------------------------------------------------------------
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
 
// packages/design-system (two levels up from scripts/scs/)
const packageRoot = path.resolve(__dirname, '../..');
const rootPath = (...args) => path.resolve(packageRoot, ...args);
 
// Monorepo root (two levels up from packages/design-system)
const monorepoRoot = path.resolve(packageRoot, '../..');
 
// packages/slds-scs — in-monorepo sub-package and source of truth for the release
const scsPackageDir = path.resolve(monorepoRoot, 'packages/slds-scs');
 
// ------------------------------------------------------------------
// Configuration
// ------------------------------------------------------------------
const config = loadConfig(packageRoot);
 
// Source paths resolved locally within the monorepo
const SLDS1_DIST_PATH = rootPath('dist');
const SLDS2_DIST_PATH = rootPath('../design-system-2/dist');
const SLDS1_RECEIPT_PATH = rootPath('.scs-slds1-artifact-provenance.json');
const SLDS2_RECEIPT_PATH = rootPath('../design-system-2/.scs-slds2-artifact-provenance.json');
const PEARL_RECEIPT_PATH = rootPath('../design-system-2/.scs-pearl-artifact-provenance.json');
const ASSEMBLY_MANIFEST_PATH = path.join(scsPackageDir, 'scs', 'assembly-provenance.json');
 
// Read SLDS1 version from dist package.json
let slds1DistVersion = null;
try {
  slds1DistVersion = autoVersion.getVersion(path.join(SLDS1_DIST_PATH, 'package.json'));
} catch { /* dist not built yet — will prompt */ }
 
// ------------------------------------------------------------------
// Interactive prompts (fills in anything not provided via config)
// ------------------------------------------------------------------
async function ask() {
  const prompts = [];
 
  if (!config.pearlOnly) {
    prompts.push(
      config.nexusCreds || {
        type: 'input',
        name: 'nexusCreds',
        message: 'Please provide your Nexus token in user:pass format\n ',
        result(creds) {
          return creds;
        },
      },
      config.sldsVersion || {
        type: 'input',
        name: 'sldsVersion',
        message: `SLDS1 Version?\n `,
        initial: slds1DistVersion || '',
        result(version) {
          return version;
        },
      },
      config.slds2Version || {
        type: 'input',
        name: 'slds2Version',
        message: `SLDS2 Version (for slds-plus files)?\n `,
        initial: '',
        result(version) {
          return version;
        },
      },
    );
  }
 
  prompts.push(
    config.wi || {
      type: 'input',
      name: 'wi',
      message: 'GUS Work Item Number?\n ',
      result(wiNumber) {
        return wiNumber;
      },
    },
    config.case || {
      type: 'input',
      name: 'case',
      message: 'GUS Change Case Number?\n ',
      result(caseNumber) {
        return caseNumber;
      },
    },
  );
 
  return prompt(prompts).catch(console.error);
}
 
// ------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------
const gitInMonorepo = (cmd) =>
  execa.commandSync(cmd, { cwd: monorepoRoot });
 
const scsPath = (...segments) => path.join(scsPackageDir, ...segments);
 
const writeAssemblyManifest = (sourceSha, filesJsonPath, generatedArtifacts) => {
  const publicationMap = fs.readFileSync(filesJsonPath);
  const files = JSON.parse(publicationMap).files;
  const generatedArtifactsByPath = new Map(
    generatedArtifacts.map((artifact) => [path.resolve(artifact.destinationPath), artifact]),
  );
  writeScsAssemblyManifest({
    manifestPath: ASSEMBLY_MANIFEST_PATH,
    destinationRoot: scsPackageDir,
    trustedRoot: monorepoRoot,
    sourceSha,
    publicationMap,
    artifacts: files.map(({ filePath }) => {
      const destinationPath = scsPath(filePath);
      const generatedArtifact = generatedArtifactsByPath.get(path.resolve(destinationPath));
      return {
        destinationPath,
        contents: generatedArtifact?.contents || fs.readFileSync(destinationPath),
        sourceSha: generatedArtifact ? sourceSha : undefined,
      };
    }),
  });
};
 
const gitAdd = (filePath) => {
  const relPath = path.join('packages/slds-scs', filePath);
  gitInMonorepo(`git add -f ${relPath}`);
  console.log(`  staged ${relPath}`);
};
 
 
// ------------------------------------------------------------------
// Main
// ------------------------------------------------------------------
ask().then(async (answers) => {
  const nexusCredentials = config.nexusCreds || answers['nexusCreds'];
 
  const sldsVersion = config.sldsVersion || answers['sldsVersion'] || null;
  const sldsVersionSemver = sldsVersion ? autoVersion.toSemver(sldsVersion) : null;
  const slds2Version = config.slds2Version || answers['slds2Version'] || null;
  const slds2VersionSemver = slds2Version ? autoVersion.toSemver(slds2Version) : null;
  const expectedSourceSha = config.expectedSourceSha;
 
  if (!config.pearlOnly && (!sldsVersion || !slds2Version)) {
    throw new Error('Both SLDS1 and SLDS2 release versions are required.');
  }
 
  if (!config.pearlOnly) {
    console.log(`\nSLDS1: ${sldsVersion} → ${sldsVersionSemver}`);
    console.log(`SLDS2: ${slds2Version} → ${slds2VersionSemver}`);
  }
 
  // ================================================================
  // Pearl-only mode — independent release of pearl subtheme CSS
  // ================================================================
  if (config.pearlOnly) {
    const pearlVersion = config.pearlVersion || answers['pearlVersion'] || '0.0.1';
    const pearlVersionSemver = autoVersion.toSemver(pearlVersion);
    const pearlSourcePath = rootPath('../design-system-2/build/pearl-theme/modular/slds2.pearl.core.css');
 
    console.log(`\n── Pearl-only mode ──`);
    console.log(`  Pearl version: ${pearlVersion} → ${pearlVersionSemver}`);
    console.log(`  Source: ${pearlSourcePath}`);
 
    if (!fs.existsSync(pearlSourcePath)) {
      console.error(`\nError: Pearl source file not found at ${pearlSourcePath}`);
      console.error('  Run: yarn workspace @salesforce-ux/design-system-2 build:production');
      process.exit(1);
    }
 
    const scsSldsDir = scsPath('slds');
    const pearlFilename = `slds-plus-pearl-subtheme-${pearlVersionSemver}.css`;
    const verifiedPearlFiles = copyVerifiedReleaseArtifacts({
      expectedSourceSha,
      destinationRoot: scsPackageDir,
      trustedRoot: monorepoRoot,
      artifacts: [
        {
          label: 'Pearl subtheme CSS',
          sourcePath: pearlSourcePath,
          destinationPath: path.join(scsSldsDir, pearlFilename),
          receiptPath: PEARL_RECEIPT_PATH,
          receiptRoot: rootPath('../design-system-2'),
          packageName: '@salesforce-ux/design-system-2',
        },
      ],
    });
    console.log(`  ✓ ${pearlFilename}`);
 
    // Update files.json
    const filesJsonPath = scsPath('scs', 'files.json');
    const jsonData = JSON.parse(fs.readFileSync(filesJsonPath, 'utf8'));
    const [updatedFiles] = FileParser({
      originalData: jsonData,
      pearlVersionSemver,
    });
    writeScsPublicationMap({
      destinationRoot: scsPackageDir,
      publicationMapPath: filesJsonPath,
      trustedRoot: monorepoRoot,
      publicationMap: `${JSON.stringify(updatedFiles, null, 2)}\n`,
    });
    writeAssemblyManifest(expectedSourceSha, filesJsonPath, verifiedPearlFiles);
    console.log(`  Updated scs/files.json — added pearl entry ${pearlVersionSemver}`);
    gitAdd('scs/files.json');
 
    // Bump package version
    const { to: newPackageVersion } = bumpScsVersionFromNexus({ monorepoRoot, scsPackageDir, gitAdd });
 
    // Commit on the current feature branch — no export, no cross-repo PR
    const commitMsg = releaseCommitMessage(
      `update pearl subtheme [${pearlVersionSemver}] in ${newPackageVersion}`,
    );
    commitInMonorepo(commitMsg, { monorepoRoot, gitInMonorepo });
 
    console.log('\n✓ Pearl-only release complete');
    return;
  }
 
  // ================================================================
  // Phase A — Assemble new slds-scs version in the monorepo
  // ================================================================
  console.log('\n── Phase A: Assemble ──');
 
  // ------------------------------------------------------------------
  // CSS file mappings — write directly into packages/slds-scs/slds/
  // ------------------------------------------------------------------
  const scsSldsDir = scsPath('slds');
  const srcDir = SLDS1_DIST_PATH;
  assertReleaseArtifactVersion({
    label: 'SLDS1',
    selectedVersion: sldsVersion,
    artifactVersion: slds1DistVersion,
  });
 
  const scsFiles = [
    {
      label: 'SLDS1 touch CSS',
      src: path.join(srcDir, 'assets/styles/salesforce-lightning-design-system_touch.css'),
      dest: scsSldsDir,
      filename: `slds-touch-${sldsVersionSemver}.css`,
      receiptPath: SLDS1_RECEIPT_PATH,
      receiptRoot: packageRoot,
      packageName: '@salesforce-ux/design-system',
      packageVersion: sldsVersion,
    },
    {
      label: 'SLDS1 CSS',
      src: path.join(srcDir, 'assets/styles/salesforce-lightning-design-system.css'),
      dest: scsSldsDir,
      filename: `slds-${sldsVersionSemver}.css`,
      receiptPath: SLDS1_RECEIPT_PATH,
      receiptRoot: packageRoot,
      packageName: '@salesforce-ux/design-system',
      packageVersion: sldsVersion,
      requiredContent: ['@layer deprecated, defaults, shared, theme, component;'],
    },
    {
      label: 'SLDS1 legacy CSS',
      src: path.join(srcDir, 'assets/styles/salesforce-lightning-design-system-legacy.css'),
      dest: scsSldsDir,
      filename: `slds-legacy-${sldsVersionSemver}.css`,
      receiptPath: SLDS1_RECEIPT_PATH,
      receiptRoot: packageRoot,
      packageName: '@salesforce-ux/design-system',
      packageVersion: sldsVersion,
    },
    {
      label: 'SLDS1 offline CSS',
      src: path.join(srcDir, 'assets/styles/salesforce-lightning-design-system-offline.css'),
      dest: scsSldsDir,
      filename: `slds-offline-${sldsVersionSemver}.css`,
      receiptPath: SLDS1_RECEIPT_PATH,
      receiptRoot: packageRoot,
      packageName: '@salesforce-ux/design-system',
      packageVersion: sldsVersion,
      requiredContent: ['@layer deprecated, defaults, shared, theme, component;'],
    },
    {
      label: 'SLDS2 bundled CSS',
      src: path.join(SLDS2_DIST_PATH, 'css/bundled/slds2.cosmos.css'),
      dest: scsSldsDir,
      filename: `slds-plus-${slds2VersionSemver}.css`,
      receiptPath: SLDS2_RECEIPT_PATH,
      receiptRoot: rootPath('../design-system-2'),
      packageName: '@salesforce-ux/design-system-2',
      packageVersion: slds2Version,
    },
    {
      label: 'SLDS2 scoped bundled CSS',
      src: path.join(SLDS2_DIST_PATH, 'css/bundled/slds2.scoped.cosmos.css'),
      dest: scsSldsDir,
      filename: `scoped-slds-plus-${slds2VersionSemver}.css`,
      receiptPath: SLDS2_RECEIPT_PATH,
      receiptRoot: rootPath('../design-system-2'),
      packageName: '@salesforce-ux/design-system-2',
      packageVersion: slds2Version,
    },
  ];
 
  console.log('\nCopying CSS files into packages/slds-scs/slds/');
  const verifiedScsFiles = copyVerifiedReleaseArtifacts({
    expectedSourceSha,
    destinationRoot: scsPackageDir,
    trustedRoot: monorepoRoot,
    artifacts: scsFiles.map(({ src, dest, filename, ...artifact }) => ({
      ...artifact,
      filename,
      sourcePath: src,
      destinationPath: path.join(dest, filename),
    })),
  });
  verifiedScsFiles.forEach(({ filename }) => console.log(`  ✓ ${filename}`));
  console.log(`  ${verifiedScsFiles.length} copied`);
 
  // The copied CSS files are tracked in this monorepo; commitInMonorepo's
  // package-wide `git add packages/slds-scs/` stages them at the end.
 
  // ------------------------------------------------------------------
  // Update scs/files.json
  // ------------------------------------------------------------------
  const lwrMappedVersion =
    autoVersion.parse(autoVersion.getVersion(path.join(srcDir, 'package.json'))).minor - 14;
 
  const filesJsonPath = scsPath('scs', 'files.json');
  const filesJsonString = fs.readFileSync(filesJsonPath, 'utf8');
  const jsonData = JSON.parse(filesJsonString);
  const [updatedFiles, rejectFiles] = FileParser({
    sldsVersionSemver,
    lwrMappedVersion,
    originalData: jsonData,
    rejectFiles: [],
    versionRetentionLimit: [3, 3, 3],
    slds2VersionSemver,
  });
 
  writeScsPublicationMap({
    destinationRoot: scsPackageDir,
    publicationMapPath: filesJsonPath,
    trustedRoot: monorepoRoot,
    publicationMap: `${JSON.stringify(updatedFiles, null, 2)}\n`,
  });
 
  const entryCount = updatedFiles.files?.length ?? 0;
  console.log(`\nUpdated scs/files.json — ${entryCount} entries (SLDS1 ${sldsVersionSemver}, SLDS2 ${slds2VersionSemver})`);
  gitAdd('scs/files.json');
 
  if (rejectFiles.length) {
    console.log(`\nRetention policy: removing ${rejectFiles.length} old file(s)`);
    rejectFiles
      .map((f) => f.filePath)
      .forEach((filePath) => {
        fs.removeSync(scsPath(filePath));
        console.log(`  ✗ ${filePath}`);
      });
  }
  writeAssemblyManifest(expectedSourceSha, filesJsonPath, verifiedScsFiles);
 
  // ------------------------------------------------------------------
  // Bump slds-scs package version (from latest published on Nexus)
  // ------------------------------------------------------------------
  const { to: newPackageVersion } = bumpScsVersionFromNexus({ monorepoRoot, scsPackageDir, gitAdd });
 
  // ------------------------------------------------------------------
  // SCS Client — check for updates
  // ------------------------------------------------------------------
  console.log('\nChecking scs-client JAR version...');
  const cmdListScsClientVersion = `ls ${scsPath('tnrp')}/scs* | sed -E "s/..*([[:digit:]]\\.[[:digit:]]\\.[[:digit:]]{1,3})..*/\\1/g"`;
  const { stdout: scsClientVersion } = execa.sync('sh', ['-c', cmdListScsClientVersion]);
 
  const cmdLatestScsClientVersion = `curl -L -u '${nexusCredentials}' -X GET "https://nexus-dev.data.sfdc.net/nexus/service/rest/v1/search/assets?sort=version&repository=releases&maven.groupId=com.salesforce.armada&maven.artifactId=scs-client&maven.classifier=&maven.extension=jar&direction=desc" -H "accept: application/json" | jq -r ".items[0]"`;
  const { stdout: scsClientLatestVersionStdOut } = execa.sync('sh', ['-c', cmdLatestScsClientVersion]);
 
  const scsClientLatestVersionData = JSON.parse(scsClientLatestVersionStdOut);
  const scsClientLatestVersion = scsClientLatestVersionData.maven2.version;
 
  if (scsClientVersion === scsClientLatestVersion) {
    console.log(`  scs-client ${scsClientVersion} is up to date`);
  } else {
    console.log(`  scs-client ${scsClientVersion} → ${scsClientLatestVersion} (updating)`);
    const jarDest = scsPath('tnrp', `scs-client-${scsClientLatestVersion}.jar`);
    execa.sync('curl', ['-k', '-o', jarDest, '-u', nexusCredentials, scsClientLatestVersionData.downloadUrl]);
    gitAdd(`tnrp/scs-client-${scsClientLatestVersion}.jar`);
 
    const tnrpPackagePath = scsPath('tnrp', 'package');
    const scsClientRegex = `s/(scs-client-)[[:digit:]]\\.[[:digit:]]\\.[[:digit:]]{1,3}(\\.jar)/\\1${scsClientLatestVersion}\\2/`;
    execa.sync('sed', ['-i', '', '-E', scsClientRegex, tnrpPackagePath]);
    gitAdd('tnrp');
    console.log(`  updated tnrp/package to scs-client-${scsClientLatestVersion}.jar`);
  }
 
  // ------------------------------------------------------------------
  // Commit in monorepo
  // ------------------------------------------------------------------
  const commitMsg = releaseCommitMessage(`update SLDS files [${sldsVersion}] in ${newPackageVersion}`);
  commitInMonorepo(commitMsg, { monorepoRoot, gitInMonorepo });
 
  console.log('\n✓ SLDS release assembled and committed in packages/slds-scs/');
});