@dpuse/dpuse-development 0.3.806 → 0.3.808
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/README.md +15 -21
- package/dist/dpuse-development.es.js +164 -142
- package/dist/dpuse-development.es.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dpuse-development.es.js","names":["runNpmCheckUpdates","START_MARKER","END_MARKER","determineConnectorUsageId","getConnectorActionsTable","START_MARKER","END_MARKER","START_MARKER","END_MARKER","xe","resolveOwnerAndRepo","writeReadmeSection","writeJSONFile","readTextFileOrNull","spawnCommandToFile","logOperationSuccess","FALLOW_REPORT_PATH","readJSONFile","RUST_WORKSPACE_PATH","clearDirectory","execCommand","logOperationHeader","getStatsForPath","FALLOW_DIRECTORY","j","buildModuleConfig","getModuleConfig","CONTRIBUTING_LICENSE_START_MARKER","QUALITY_SECURITY_END_MARKER","getDirectoryEntries","FALLOW_BADGE_PATH","QUALITY_SECURITY_START_MARKER","CONTRIBUTING_LICENSE_END_MARKER","bumpPackageVersion","logStepHeader","spawnCommand","readTextFile","migrateGovernanceSection","path","auditDependencies","error","WASM_BUILD_SCRIPT_NAME","buildProject","bundleProject","packageJSON","stepIcon","PRETTIER_CONFIG_REFERENCE","TEMPLATE_REPOSITORY_NAME","checkConfigFiles","configJSON","isPrivate","moduleTypeConfig","moduleDirectory","fileURLToPath","checkConfigFile","checkESLintConfig","checkTSConfig","checkTSConfigScripts","checkViteConfig","checkVitestConfig","checkPrettierConfig","hasRust","checkWorkflows","content","\"prettier\"","viteConfigTemplates","checkFilePath","checkFileName","templates","templateFileNames","checkFileContent","templateFileName","templatePath","templateContent","prepareTemplate","checkDependencies","rcOptions","run","pinnedPackageNames","getPinnedPackageNames","names","allowScripts","key","isAllowed","checkProject","START_MARKER$3","END_MARKER$3","CONNECTOR_ACTIONS_INTRO","CONNECTOR_USAGE_DESCRIPTIONS","CONNECTOR_ACTIONS_TABLE_LEAD_IN","documentActions","actionNames","usageId","table","block","documentContributingLicense","authorName","resolveAuthorName","copyrightYear","resolveCopyrightYear","buildContributingLicenseContent","owner","repo","author","authorString","emailStart","emailEnd","part","currentYear","firstCreatedAt","startYear","START_MARKER$2","END_MARKER$2","LICENSES_HEADING","DEPENDENCY_TREE_INTRO","documentDependencies","rootPackage","skipDependencyDocumentation","unshippedPackages","listUnshippedPackages","options","allowedLicenses","resolve","reject","insertLicensesIntoReadme","name","message","licenses","licenseTree","licensesByKey","value","parseLicenseEntry","data","fetchNpmData","license","licensesContent","buildLicensesIntro","formatLicenseRow","treeItems","walkTreeList","treeContent","lockText","packages","shipped","unshipped","lockPath","entry","packageKey","formatLicenseListText","lastAt","installedVersion","response","distributionTags","timeMap","latestVersion","publishedDate","version","licenseLink","indent","depth","node","dependencies","nameLink","versionDetail","formatVersionDetail","items","published","determineLatestAge","latestAge","latestClause","momentString","dateString","input","now","months","START_MARKER$1","END_MARKER$1","documentOpening","resolveLicense","introduction","resolveIntroduction","buildOpeningContent","resolvePackageName","repoURL","npmPackageName","description","SCORECARD_PRACTICE_LIMITS","SCORECARD_IGNORED_CHECKS","COVERAGE_FINAL_PATH","COVERAGE_SUMMARY_PATH","COVERAGE_TARGET_PERCENT","COVERAGE_WARNING_PERCENT","COVERAGE_BADGE_PATH","CODEQL_LANGUAGE_NAMES","FALLOW_GRADE_COLOURS","FALLOW_HEALTH_PATH","asyncExecFile","promisify","execFile","documentQualitySecurity","coveragePercent","measureTestCoverage","fallowHealth","measureCodeHealth","securitySettings","readSecuritySettings","bestPracticesProjectId","scorecardResult","lookUpBestPracticesProjectId","lookUpScorecardResult","buildQualitySecurityContent","summary","writeCoverageBadge","colourNames","level","\"fallow\"","coverageArguments","health","writeFallowBadge","grade","score","ciWorkflow","codeQLWorkflow","dependabotConfig","rustWorkspace","repoDetails","privateVulnerabilityReporting","vulnerabilityAlerts","checkRuns","readGitHubAPI","securityAndAnalysis","readSetting","checkAppSlugs","checkRun","ecosystemCount","pausedEcosystemCount","language","endpoint","stdout","project","scorecardURI","isScorecardOnlyPracticeLimited","result","formatManualNote","status","formatStatus","buildTableContent","rows","heading","row","formatEndpointBadge","label","badgePath","buildChecksContent","settings","ciNote","isInCI","testingRows","sonarCloudBadge","codeQualityRows","hasCodeQL","codeQLBadge","codeQLScope","codeQLLanguages","securityAnalysisRows","dependabotLink","dependencyRows","bestPracticesURL","scorecardLimitText","bestPracticesBadge","reportingText","checksResults","START_MARKER","END_MARKER","UPLOADED_MODULE_TYPE_IDS","INTERNAL_NPM_MODULE_TYPE_IDS","INTERNAL_NPM_WARNING","DEVELOPMENT_MANAGEMENT_TEXT","SHARED_MANAGEMENT_TEXT","documentUsage","cloneURL","resolveCloneURL","directoryName","resolveDirectoryName","nodeVersion","resolveVersion","npmVersion","typescriptVersion","\"typescript\"","buildIntroductionContent","packageJSONURL","buildUsageContent","url","range","match","typeId","packageName","management","API_REFERENCE_PATH","documentAPIReference","writeAPIReference","BUNDLE_REPORT_PATH","BUNDLE_START_MARKER","BUNDLE_END_MARKER","INDENT","BAR_WIDTH","BAR_CHARACTER","PART_BAR_CHARACTER","BUNDLE_ANALYSIS_INTRO","BAR_NOTE","PART_ROW_NOTE","UNTRACED_LABEL","UNTRACED_NOTE","documentBundleSizes","json","bundleTable","buildBundleTable","rowNote","assetGroups","buildAssetGroups","buildTotal","groups","sum","group","assets","resource","asset","resourceSizes","b","a","lines","file","sizes","sortedGroups","compareGroups","fileTotal","buildShare","formatPercent","chunkSizes","renderGroupRows","isModuleLevel","groupName","groupSizes","files","fileName","getSoleFileName","formatGroupLabel","composition","renderFileRows","fileSizes","bar","bytes","barCharacter","formatBytes","dependencyPaths","buildDependencyPaths","resolveModule","zero","addTo","dependency","dependencyPath","lastPathSegment","count","pct","source","whole","documentProject","isConnector","hasAPIReference","formatCode","formatTargets","existsSync","directory","lintCode","putState","uploadDirectoryToR2","listDirectoryEntriesRecursively","sourceItemPath","currentSourceDirectory","destinationItemPath","currentDestinationDirectory","toplevelNames","sourceDirectory","uploadDirectory","uploadModuleConfigToDO","stateId","uploadModuleToR2","entries","currentDirectory","fullPath","relativePath","prefix","r2Path","uploadDirectoryPath","nonJavaScripContentType","contentType","publishProject","registerModule","moduleTypeName","releaseProject","builtConfigJSON","tagName","syncProjectWithGitHub","STEP_ICONS","TEST_TYPE_CONFIGS","testProject","stepNumber","testTypeConfig","testTypeIds","stepLabel"],"sources":["../src/actions/auditDependencies.ts","../src/actions/buildProject.ts","../src/actions/checkConfigFiles.ts","../src/actions/checkDependencies.ts","../src/actions/checkProject.ts","../src/actions/documentActions.ts","../src/actions/documentContributingLicense.ts","../src/actions/documentDependencies.ts","../src/actions/documentOpening.ts","../src/actions/documentQualitySecurity.ts","../src/actions/documentUsage.ts","../src/actions/documentApiReference.ts","../src/actions/documentBundleSizes.ts","../src/actions/documentProject.ts","../src/actions/formatCode.ts","../src/actions/lintCode.ts","../src/utilities/cloudflare.ts","../src/actions/publishProject.ts","../src/actions/releaseProject.ts","../src/actions/syncProjectWithGitHub.ts","../src/actions/testProject.ts"],"sourcesContent":["// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Audit the project's dependencies for known security vulnerabilities. */\nexport async function auditDependencies(): Promise<void> {\n try {\n logOperationHeader('Audit Dependencies');\n\n // Strict for what users install. Dev tools never ship but do run in CI, where the publish tokens are, so they fail\n // only on serious flaws; moderate ones there often wait on upstream fixes and would otherwise block every push.\n await spawnCommand('1️⃣ Check shipped dependencies for any vulnerability', 'npm', ['audit', '--omit=dev']);\n await spawnCommand('2️⃣ Check all dependencies for high or critical vulnerabilities', 'npm', ['audit', '--audit-level=high']);\n\n logOperationSuccess('Dependencies audited');\n } catch (error) {\n console.error('❌ Error auditing dependencies', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, readJSONFile, spawnCommand } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// A project with Rust code names its WebAssembly build in this script, as the crate and target differ by project.\nconst WASM_BUILD_SCRIPT_NAME = 'build:wasm';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Builds the package using Vite. Output to '/dist' directory. Builds bundle analysis reports. */\nexport async function buildProject(): Promise<void> {\n try {\n logOperationHeader('Build Project');\n\n await bundleProject('1️⃣ ', await readJSONFile<PackageJson>('package.json'));\n\n logOperationSuccess('Project built');\n } catch (error) {\n console.error('❌ Error building project', error);\n process.exit(1);\n }\n}\n\n/** Bundles the project with Vite, first building its WebAssembly where the project has a 'build:wasm' script. */\nexport async function bundleProject(stepIcon: string, packageJSON: PackageJson): Promise<void> {\n if (packageJSON.scripts?.[WASM_BUILD_SCRIPT_NAME] != null) {\n await spawnCommand(`${stepIcon} Build WebAssembly`, 'npm', ['run', WASM_BUILD_SCRIPT_NAME]);\n }\n await spawnCommand(`${stepIcon} Bundle project`, 'vite', ['build']);\n}\n","// ── External Dependencies & Registrations\nimport { fileURLToPath } from 'node:url';\nimport type { PackageJson } from 'type-fest';\nimport path from 'node:path';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport {\n getModuleConfig,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n ModuleTypeConfig,\n readJSONFile,\n readTextFile,\n readTextFileOrNull,\n RUST_WORKSPACE_PATH\n} from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst PRETTIER_CONFIG_REFERENCE = '@dpuse/dpuse-development/prettierrc';\nconst TEMPLATE_REPOSITORY_NAME = 'dpuse-development'; // Stands in for each project's own name in the SECURITY.md template.\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function checkConfigFiles(): Promise<void> {\n try {\n logOperationHeader('Check configuration files');\n\n logStepHeader('1️⃣ Check individual files');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const isPrivate = packageJSON.private === true; // Private packages have no workflows or security policy.\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n const moduleDirectory = path.dirname(fileURLToPath(import.meta.url));\n await checkConfigFile(moduleDirectory, '.editorconfig');\n await checkConfigFile(moduleDirectory, '.gitattributes');\n await checkConfigFile(moduleDirectory, '.gitignore', ['.gitignore_default']);\n await checkConfigFile(moduleDirectory, '.markdownlint.json');\n await checkConfigFile(moduleDirectory, '.ncurc.json');\n await checkESLintConfig(moduleTypeConfig, moduleDirectory);\n await checkConfigFile(moduleDirectory, 'LICENSE');\n await checkTSConfig(moduleTypeConfig, moduleDirectory);\n await checkTSConfigScripts(moduleTypeConfig, moduleDirectory);\n await checkViteConfig(moduleTypeConfig, moduleDirectory);\n await checkVitestConfig(moduleTypeConfig, moduleDirectory);\n checkPrettierConfig(moduleTypeConfig, packageJSON);\n // Projects with Rust code pin their Rust version, and have Dependabot watch Cargo as well.\n const hasRust = (await readTextFileOrNull(RUST_WORKSPACE_PATH)) !== null;\n if (hasRust) await checkConfigFile(moduleDirectory, 'rust-toolchain.toml');\n const dependabotTemplate = `.github/dependabot${isPrivate ? '.private' : ''}${hasRust ? '.rust' : ''}.yml`;\n await checkConfigFile(moduleDirectory, '.github/dependabot.yml', [dependabotTemplate]);\n if (isPrivate) {\n console.info(\"ℹ️ GitHub workflows and file 'SECURITY.md' are NOT required by this project\");\n } else {\n await checkWorkflows(moduleDirectory);\n await checkConfigFile(moduleDirectory, 'SECURITY.md', [], (content) => content.replaceAll(TEMPLATE_REPOSITORY_NAME, () => configJSON.id));\n }\n\n logOperationSuccess('Configuration files checked');\n } catch (error) {\n console.error('❌ Error checking configuration files', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nasync function checkESLintConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['github', 'kb'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'eslint.config.js' is NOT required by this project\");\n } else if (['app', 'api', 'development', 'eslint'].includes(moduleTypeConfig.typeId)) {\n console.info(\"⚠️ File 'eslint.config.js' is UNIQUE to this project\");\n } else {\n await checkConfigFile(moduleDirectory, 'eslint.config.js', ['eslint.config.default.js']);\n }\n}\nfunction checkPrettierConfig(moduleTypeConfig: ModuleTypeConfig, packageJSON: PackageJson) {\n if (moduleTypeConfig.typeId === 'development') {\n console.info(\"ℹ️ File '.prettierrc.json' is the template\"); // Every other project points to this file.\n } else if (moduleTypeConfig.typeId === 'app') {\n console.info(\"⚠️ File '.prettierrc.json' is UNIQUE to this project\");\n } else if (packageJSON['prettier'] === PRETTIER_CONFIG_REFERENCE) {\n console.info(`ℹ️ Prettier configuration is '${PRETTIER_CONFIG_REFERENCE}'`);\n } else {\n console.info(`❌ Prettier configuration is NOT '${PRETTIER_CONFIG_REFERENCE}'`);\n }\n}\n\nasync function checkTSConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['github'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'tsconfig.json' is NOT required by this project\");\n } else if (['connector', 'cookbook', 'development', 'engine', 'presenter', 'shared', 'tool'].includes(moduleTypeConfig.typeId)) {\n await checkConfigFile(moduleDirectory, 'tsconfig.json');\n } else {\n console.info(\"⚠️ File 'tsconfig.json' is UNIQUE to this project\");\n }\n}\n\nasync function checkTSConfigScripts(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['github'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'scripts/tsconfig.json' is NOT required by this project\");\n } else {\n await checkConfigFile(moduleDirectory, 'scripts/tsconfig.json'); // Type-checks the 'scripts' folder, whose files Node runs directly.\n }\n}\n\nasync function checkViteConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['eslint', 'github', 'kb'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'vite.config.ts' is NOT required by this project\");\n } else if (['app', 'api', 'development', 'engine'].includes(moduleTypeConfig.typeId)) {\n console.info(\"⚠️ File 'vite.config.ts' is UNIQUE to this project\");\n } else {\n let viteConfigTemplates: string[];\n switch (moduleTypeConfig.typeId) {\n case 'connector':\n viteConfigTemplates = ['vite.config.default.ts', 'vite.config.wasm.ts'];\n break;\n case 'presenter':\n viteConfigTemplates = ['vite.config.presenter.ts'];\n break;\n case 'tool':\n viteConfigTemplates = ['vite.config.tool.ts'];\n break;\n default:\n viteConfigTemplates = ['vite.config.default.ts'];\n }\n await checkConfigFile(moduleDirectory, 'vite.config.ts', viteConfigTemplates);\n }\n}\nasync function checkWorkflows(moduleDirectory: string) {\n await checkConfigFile(moduleDirectory, '.github/workflows/ci.yml');\n await checkConfigFile(moduleDirectory, '.github/workflows/codeql.yml');\n await checkConfigFile(moduleDirectory, '.github/workflows/publish.yml');\n await checkConfigFile(moduleDirectory, '.github/workflows/scorecard.yml');\n}\n\nasync function checkVitestConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['app', 'api', 'eslint', 'github', 'kb'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'vitest.config.ts' is NOT required by this project\");\n } else {\n await checkConfigFile(moduleDirectory, 'vitest.config.ts');\n }\n}\n\nasync function checkConfigFile(moduleDirectory: string, checkFileName: string, templateFileNames: string[] = [], prepareTemplate = (content: string) => content): Promise<void> {\n const checkFilePath = path.resolve(process.cwd(), checkFileName);\n const templates = templateFileNames.length > 0 ? templateFileNames : [checkFileName];\n\n let checkFileContent;\n try {\n checkFileContent = await readTextFile(checkFilePath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n if (checkFileContent === undefined) {\n console.info(`❌ File '${checkFileName}' is MISSING`);\n return;\n }\n\n for (const templateFileName of templates) {\n const templatePath = path.resolve(moduleDirectory, `../${templateFileName}`);\n const templateContent = prepareTemplate(await readTextFile(templatePath));\n if (checkFileContent === templateContent) {\n console.info(`ℹ️ File '${checkFileName}' is the same as '${templateFileName}'`);\n return;\n }\n }\n\n console.info(`❌ File '${checkFileName}' is NOT the same`);\n}\n","// ── External Dependencies & Registrations\nimport path from 'node:path';\nimport type { RcOptions } from 'npm-check-updates';\nimport { run as runNpmCheckUpdates } from 'npm-check-updates';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Identifies outdated dependencies using npm outdated and npm-check-updates with option to automatically install\n * latest versions. */\nexport async function checkDependencies(): Promise<void> {\n try {\n logOperationHeader('Check Dependencies');\n\n await spawnCommand(\"1️⃣ Check using 'npm outdated'\", 'npm', ['outdated'], true);\n\n logStepHeader(\"2️⃣ Check using 'npm-check-updates'\");\n let rcOptions: RcOptions = {};\n try {\n rcOptions = await readJSONFile<RcOptions>(path.resolve(process.cwd(), '.ncurc.json'));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n await runNpmCheckUpdates({ interactive: true, upgrade: true, dep: 'dev,prod,peer,optional', install: 'never', ...rcOptions });\n\n // Not strict here, otherwise an upgraded package with a pinned approval fails the install before step 5 can move its pin.\n // No audit summary, as step 4 reports what is left once it has fixed what it can.\n await spawnCommand('3️⃣ Install updated dependencies', 'npm', ['install', '--prefer-online', '--no-strict-allow-scripts', '--no-audit', '--no-fund']);\n\n // Only upgrades the version ranges in package.json already allow; never '--force', which makes breaking ones. Runs before\n // the pins move in step 5, so a package it upgrades has its pin moved too. npm exits with an error while vulnerabilities\n // it cannot fix remain, such as those waiting on an upstream release, so that is reported without stopping the check.\n await spawnCommand('4️⃣ Fix vulnerabilities where a compatible upgrade exists', 'npm', ['audit', 'fix', '--no-strict-allow-scripts', '--no-fund'], true);\n\n // Only packages already approved are re-approved, so a newly added install script still waits for review in step 8.\n // Name-only approvals already cover every version, so only pinned ones need moving. Runs before prune, which would\n // otherwise delete a pin to an upgraded version as 'not installed' before it could be moved.\n const pinnedPackageNames = await getPinnedPackageNames();\n if (pinnedPackageNames.length > 0) {\n await spawnCommand('5️⃣ Move install-script pins to installed versions', 'npm', ['install-scripts', 'approve', ...pinnedPackageNames]);\n } else {\n logStepHeader('5️⃣ No pinned install-script approvals to move');\n }\n\n // Runs before the rebuild in step 7. A rebuild leaves npm's record of 'node_modules' out of date, and prune then misses\n // install scripts that 'npm install' still sees, as with 'fsevents' (npm 12.0.1). Also macOS only, as elsewhere it drops\n // entries for macOS-only packages that are not installed.\n if (process.platform === 'darwin') {\n await spawnCommand('6️⃣ Remove unused install-script entries', 'npm', ['install-scripts', 'prune']);\n } else {\n logStepHeader('6️⃣ Skipped removing unused install-script entries (macOS only)');\n }\n\n // Not strict, so any install script still awaiting review is reported once, by step 8.\n if (pinnedPackageNames.length > 0) {\n await spawnCommand('7️⃣ Run install scripts skipped in steps 3 and 4', 'npm', ['rebuild', ...pinnedPackageNames, '--no-strict-allow-scripts']);\n }\n\n // The same check a plain 'npm install' makes, which 'npm install-scripts ls' does not always agree with. Fails listing any\n // install scripts still awaiting review. Step 4 has already reported the audit.\n await spawnCommand('8️⃣ Confirm every install script is reviewed', 'npm', ['install', '--strict-allow-scripts', '--no-audit', '--no-fund']);\n\n logOperationSuccess('Dependencies checked');\n } catch (error) {\n console.error('❌ Error checking dependencies', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Keys are 'name', 'name@version' or '@scope/name@version'. An '@' after the first character marks a pin; it and the version\n// are dropped so npm matches every installed version.\nasync function getPinnedPackageNames(): Promise<string[]> {\n const { allowScripts = {} } = await readJSONFile<{ allowScripts?: Record<string, boolean> }>(path.resolve(process.cwd(), 'package.json'));\n const names = Object.entries(allowScripts)\n .filter(([key, isAllowed]) => isAllowed && key.lastIndexOf('@') > 0)\n .map(([key]) => key.slice(0, key.lastIndexOf('@')));\n return [...new Set(names)];\n}\n","// ── Local Framework\nimport { checkConfigFiles } from '@/actions/checkConfigFiles';\nimport { checkDependencies } from '@/actions/checkDependencies';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Checks the configuration files against the DPUse templates, then lists outdated dependencies. */\nexport async function checkProject(): Promise<void> {\n await checkConfigFiles();\n await checkDependencies();\n}\n","// ── DPUse Framework\nimport type { ConnectorActionName, ConnectorUsageId } from '@dpuse/dpuse-shared';\nimport { determineConnectorUsageId, getConnectorActionsTable } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, writeReadmeSection } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- CONNECTOR_ACTIONS_START -->';\nconst END_MARKER = '<!-- CONNECTOR_ACTIONS_END -->';\n\nconst CONNECTOR_ACTIONS_INTRO =\n 'Connectors conform to a unified interface contract by implementing a specific subset of standard actions. These standardised actions allow the DPUse application to interact with any underlying data source in the same way, enabling Connectors to be built independently and loaded dynamically at runtime.';\n\nconst CONNECTOR_USAGE_DESCRIPTIONS: Record<ConnectorUsageId, string> = {\n source: 'This connector is a Source connector that supports only read actions. Connectors can also function as a Destination (write-only) or Bidirectional (read/write), depending on the actions they support.',\n destination:\n 'This connector is a Destination connector that supports only write actions. Connectors can also function as a Source (read-only) or Bidirectional (read/write), depending on the actions they support.',\n bidirectional:\n 'This connector is a Bidirectional connector that supports both read and write actions. Connectors can also function as a Source (read-only) or Destination (write-only), depending on the actions they support.',\n unknown:\n 'This connector does not yet implement any read or write actions, so its type cannot be determined. Connectors function as a Source (read-only), a Destination (write-only), or Bidirectional (read/write), depending on the actions they support.'\n};\n\nconst CONNECTOR_ACTIONS_TABLE_LEAD_IN = 'The table below lists all connector actions and highlights those supported by this connector.';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentActions(): Promise<void> {\n try {\n logOperationHeader('Document Actions');\n\n logStepHeader(\"1️⃣ Insert actions description and table into 'README.md'\");\n\n const config = await readJSONFile<{ actionNames?: string[] }>('config.json');\n const actionNames = (config.actionNames ?? []) as ConnectorActionName[];\n const usageId = determineConnectorUsageId(actionNames);\n const table = getConnectorActionsTable(actionNames);\n\n const block = `${CONNECTOR_ACTIONS_INTRO}\\n\\n${CONNECTOR_USAGE_DESCRIPTIONS[usageId]} ${CONNECTOR_ACTIONS_TABLE_LEAD_IN}\\n\\n${table}`;\n\n await writeReadmeSection(block, START_MARKER, END_MARKER);\n\n logOperationSuccess('Actions documented');\n } catch (error) {\n console.error('❌ Error documenting actions', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\nimport {\n CONTRIBUTING_LICENSE_END_MARKER,\n CONTRIBUTING_LICENSE_START_MARKER,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n migrateGovernanceSection,\n readJSONFile,\n resolveOwnerAndRepo,\n writeReadmeSection\n} from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface LicenseModuleConfig {\n firstCreatedAt?: number | null;\n}\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Regenerates the README's Contributing and License sections. */\nexport async function documentContributingLicense(): Promise<void> {\n try {\n logOperationHeader('Document Contributing & License');\n\n const [packageJSON, configJSON] = await Promise.all([readJSONFile<PackageJson>('package.json'), readJSONFile<LicenseModuleConfig>('config.json')]);\n\n const { owner, repo } = resolveOwnerAndRepo(packageJSON, 'document contributing and license');\n const authorName = resolveAuthorName(packageJSON);\n const copyrightYear = resolveCopyrightYear(configJSON.firstCreatedAt);\n\n logStepHeader(\"1️⃣ Insert contributing and license content into 'README.md'\");\n\n await migrateGovernanceSection();\n await writeReadmeSection(buildContributingLicenseContent(owner, repo, authorName, copyrightYear), CONTRIBUTING_LICENSE_START_MARKER, CONTRIBUTING_LICENSE_END_MARKER);\n\n logOperationSuccess('Contributing & license documented');\n } catch (error) {\n console.error('❌ Error documenting contributing and license', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nfunction resolveAuthorName(packageJSON: PackageJson): string {\n const author = packageJSON.author;\n const authorString = typeof author === 'string' ? author : author?.name;\n if (authorString == null || authorString === '') throw new Error(\"package.json 'author' field is required to document contributing and license.\");\n\n // Drop the first '<email>' and the spaces around it, keeping one space between what came before and after it, as in\n // npm's 'Name <email> (url)' form. Not a regex, as '\\s*<' backtracks on long runs of spaces.\n const emailStart = authorString.indexOf('<');\n const emailEnd = emailStart === -1 ? -1 : authorString.indexOf('>', emailStart);\n return emailEnd === -1 ? authorString.trim() : [authorString.slice(0, emailStart).trim(), authorString.slice(emailEnd + 1).trim()].filter((part) => part !== '').join(' ');\n}\n\nfunction resolveCopyrightYear(firstCreatedAt: number | null | undefined): string {\n const currentYear = new Date().getFullYear();\n if (firstCreatedAt == null) return String(currentYear);\n\n const startYear = new Date(firstCreatedAt).getFullYear();\n return startYear === currentYear ? String(currentYear) : `${String(startYear)}-present`;\n}\n\nfunction buildContributingLicenseContent(owner: string, repo: string, authorName: string, copyrightYear: string): string {\n const repoURL = `https://github.com/${owner}/${repo}`;\n\n return `## Contributing\n\nThis repository is maintained solely by its owner and does not, at present, accept external contributions into the canonical repo. Its source is published openly under the MIT License — every DPUse project is fully open source except DPUse Engine, which remains closed and proprietary.\n\nFor security vulnerabilities, see [Reporting Vulnerabilities](#reporting-vulnerabilities). For bugs, inconsistencies, or other feedback, [open a GitHub issue](${repoURL}/issues) — feedback is read, but responses and fixes are at the maintainer's discretion.\n\n## License\n\nThis project is licensed under the MIT License, permitting free use, modification, and distribution.\n\n[MIT](./LICENSE) © ${copyrightYear} ${authorName}`;\n}\n","// ── External Dependencies & Registrations\nimport { init as initLicenseChecker } from 'license-checker-rseidelsohn';\nimport type { InitOpts } from 'license-checker-rseidelsohn';\n\n// ── Local Framework\nimport { clearDirectory, logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, readTextFileOrNull, spawnCommandToFile, writeReadmeSection } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface License {\n name: string;\n repository: string;\n licenseTypes: string;\n installedVersion: string;\n latestVersion: string;\n latestPublishedDate: string;\n author: string;\n publishedDate: string;\n licenseFileLink?: string;\n}\n\ninterface ProductionPackageLicense {\n licenses: string;\n repository?: string;\n publisher?: string;\n email?: string;\n path?: string;\n licenseFile?: string;\n}\n\ninterface PackageLock {\n packages?: Record<string, { name?: string; version?: string; dev?: boolean; devOptional?: boolean }>;\n}\n\ninterface NpmPackageTree {\n version?: string;\n dependencies?: Record<string, NpmPackageTree>;\n}\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- DEPENDENCY_LICENSES_START -->';\nconst END_MARKER = '<!-- DEPENDENCY_LICENSES_END -->';\nconst LICENSES_HEADING = '## Dependency Licenses';\n\nconst DEPENDENCY_TREE_INTRO =\n \"The dependency tree below lists every package in this project — direct and transitive — along with its installed version, release date, and update status. Packages flagged ❗ have a newer version available; ⚠️ indicates a package that hasn't been updated in the last 6 months or longer. Neither flag necessarily indicates a problem: we let new releases stabilise before upgrading, and some packages are mature and stable (have limited or no dependencies), so they require no active development.\";\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Identify licenses of the project's production and peer dependencies. Updates the table in the Dependency Licenses\n * section of this page and summary files licenses.json and licenseTree.json in th licenses directory of this\n * repository. Also downloads a copy of dependency license to `licenses/downloads'. */\nexport async function documentDependencies(allowedLicenses = 'MIT'): Promise<void> {\n try {\n logOperationHeader('Document Dependencies');\n\n const rootPackage = await readJSONFile<{ name?: string; version?: string }>('package.json');\n\n if (rootPackage.name === '@dpuse/dpuse-development' || rootPackage.name === '@dpuse/eslint-config-dpuse') {\n await skipDependencyDocumentation(rootPackage.name);\n logOperationSuccess('Dependencies documented');\n return;\n }\n\n await clearDirectory('1️⃣ Clear downloaded licenses', 'licenses/downloads');\n const unshippedPackages = await listUnshippedPackages();\n\n logStepHeader('2️⃣ Identify production licenses');\n await new Promise<void>((resolve, reject) => {\n const options: InitOpts & { files: string; relativeModulePath: boolean } = {\n start: process.cwd(),\n production: true,\n json: true,\n files: 'licenses/downloads',\n relativeModulePath: true,\n relativeLicensePath: true,\n onlyAllow: allowedLicenses,\n excludePackages: [rootPackage.name ?? '', ...unshippedPackages].join(';'),\n out: 'licenses/licenses.json'\n };\n initLicenseChecker(options, (error: Error | undefined) => {\n if (error == null) {\n resolve();\n } else {\n reject(error);\n }\n });\n });\n\n await spawnCommandToFile('3️⃣ Identify transitive dependencies', 'npm', ['ls', '--all', '--json', '--omit=dev'], 'licenses/licenseTree.json');\n\n await insertLicensesIntoReadme('4️⃣ ', allowedLicenses, new Set(unshippedPackages));\n\n logOperationSuccess('Dependencies documented');\n } catch (error) {\n console.error('❌ Error documenting dependencies', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nasync function skipDependencyDocumentation(name: string): Promise<void> {\n logStepHeader(`1️⃣ Skip: ${name} is a development-only tool and is never part of a production release.`);\n\n const message = `> [!WARNING]\\n> Dependency licenses are not documented here: ${name} is a development-only tool and is never part of a production release.`;\n\n await writeReadmeSection(`${LICENSES_HEADING}\\n\\n${message}`, START_MARKER, END_MARKER);\n}\n\nasync function insertLicensesIntoReadme(stepIcon: string, allowedLicenses: string, unshippedPackages: Set<string>): Promise<void> {\n logStepHeader(`${stepIcon} Insert licenses into 'README.md'`);\n\n const [licenses, licenseTree] = await Promise.all([\n readJSONFile<Record<string, ProductionPackageLicense>>('licenses/licenses.json'),\n readJSONFile<NpmPackageTree>('licenses/licenseTree.json')\n ]);\n\n const licensesByKey = new Map<string, License>();\n for (const [key, value] of Object.entries(licenses)) {\n licensesByKey.set(key, parseLicenseEntry(key, value));\n }\n\n await Promise.all(\n licensesByKey.values().map(async (license) => {\n const data = await fetchNpmData(license.name, license.installedVersion);\n license.latestVersion = data.latestVersion;\n license.latestPublishedDate = data.latestPublishedDate;\n license.publishedDate = data.publishedDate;\n })\n );\n\n const licensesIntro = buildLicensesIntro(allowedLicenses);\n let licensesContent = `${licensesIntro}\\n\\n|Dependency|Version|License(s)|Document|\\n|:-|:-:|:-|:-|\\n`;\n for (const license of licensesByKey.values()) {\n licensesContent += formatLicenseRow(license);\n }\n\n const treeItems: string[] = [];\n if (licenseTree.dependencies != null) {\n walkTreeList(licenseTree.dependencies, licensesByKey, unshippedPackages, treeItems, 0);\n }\n const treeContent = `${DEPENDENCY_TREE_INTRO}\\n\\n${treeItems.join('\\n')}`;\n\n await writeReadmeSection(`${LICENSES_HEADING}\\n\\n${licensesContent.trimEnd()}\\n\\n### Dependency Tree\\n\\n${treeContent}`, START_MARKER, END_MARKER);\n}\n\n// Packages installed but never shipped, as 'name@version'. npm's lock file marks these 'dev' or 'devOptional', the latter\n// for a package needed only by development or as an optional extra, such as TypeScript as valibot's optional peer. The\n// licence checker follows optional peer links, so without this it would count such a package as a production one. A\n// package installed at the same version for a shipped reason as well is kept.\nasync function listUnshippedPackages(): Promise<string[]> {\n const lockText = await readTextFileOrNull('package-lock.json');\n const packages = lockText === null ? {} : ((JSON.parse(lockText) as PackageLock).packages ?? {});\n const shipped = new Set<string>();\n const unshipped = new Set<string>();\n for (const [lockPath, entry] of Object.entries(packages)) {\n if (lockPath === '' || entry.version === undefined) continue;\n const name = entry.name ?? lockPath.slice(lockPath.lastIndexOf('node_modules/') + 'node_modules/'.length);\n const packageKey = `${name}@${entry.version}`;\n if (entry.dev === true || entry.devOptional === true) unshipped.add(packageKey);\n else shipped.add(packageKey);\n }\n return unshipped.values().filter((packageKey) => !shipped.has(packageKey)).toArray();\n}\n\nfunction buildLicensesIntro(allowedLicenses: string): string {\n const licenseListText = formatLicenseListText(allowedLicenses.split(';'));\n return `License data is updated each time \\`npm run document\\` is run, using [license-checker](https://github.com/RSeidelsohn/license-checker-rseidelsohn). The following table lists all production dependencies. These dependencies (including transitive ones) have been checked and confirmed to use ${licenseListText} — all permissive, commercially-friendly licenses. Users of the uploaded library are covered by these checks; developers cloning this repository should independently verify development dependencies.`;\n}\n\nfunction formatLicenseListText(licenses: string[]): string {\n if (licenses.length === 1) return licenses[0] ?? '';\n return licenses.length === 2 ? `${String(licenses[0])} or ${String(licenses[1])}` : `${licenses.slice(0, -1).join(', ')}, or ${String(licenses.at(-1))}`;\n}\n\nfunction parseLicenseEntry(key: string, value: ProductionPackageLicense): License {\n const lastAt = key.lastIndexOf('@');\n const name = lastAt > 0 ? key.slice(0, lastAt) : key;\n const installedVersion = lastAt > 0 ? key.slice(lastAt + 1) : '';\n return {\n name,\n repository: value.repository ?? `https://www.npmjs.com/package/${name}`,\n licenseTypes: value.licenses,\n installedVersion,\n author: value.publisher ?? '',\n latestVersion: '',\n latestPublishedDate: '',\n publishedDate: '',\n ...(value.licenseFile != null && { licenseFileLink: value.licenseFile })\n };\n}\n\nasync function fetchNpmData(name: string, version: string): Promise<{ latestVersion: string; latestPublishedDate: string; publishedDate: string }> {\n try {\n const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(name)}`);\n if (response.ok) {\n const data = (await response.json()) as { 'dist-tags'?: Record<string, string>; time?: Record<string, string> };\n const distributionTags = new Map(Object.entries(data['dist-tags'] ?? {}));\n const timeMap = new Map(Object.entries(data.time ?? {}));\n const latestVersion = distributionTags.get('latest') ?? '';\n const publishedDate = timeMap.get(version) ?? '';\n const latestPublishedDate = latestVersion === version ? '' : (timeMap.get(latestVersion) ?? '');\n return { latestVersion, latestPublishedDate, publishedDate };\n }\n } catch {\n // Ignore network errors.\n }\n return { latestVersion: '', latestPublishedDate: '', publishedDate: '' };\n}\n\nfunction formatLicenseRow(license: License): string {\n const licenseLink = license.licenseFileLink == null || license.licenseFileLink === '' ? '⚠️ No license file' : `[LICENSE](licenses/${license.licenseFileLink})`;\n return `|[${license.name}](${license.repository})|${license.installedVersion}|${license.licenseTypes}|${licenseLink}|\\n`;\n}\n\nfunction walkTreeList(dependencies: Record<string, NpmPackageTree>, licensesByKey: Map<string, License>, unshippedPackages: Set<string>, items: string[], depth: number): void {\n const indent = ' '.repeat(depth);\n for (const [name, node] of Object.entries(dependencies)) {\n const version = node.version ?? '';\n if (unshippedPackages.has(`${name}@${version}`)) continue;\n const license = licensesByKey.get(`${name}@${version}`);\n const nameLink = license == null ? name : `[${name}](${license.repository})`;\n const versionDetail = formatVersionDetail(license);\n items.push(`${indent}- **${nameLink}** ${version}${versionDetail}`);\n if (node.dependencies != null) {\n walkTreeList(node.dependencies, licensesByKey, unshippedPackages, items, depth + 1);\n }\n }\n}\n\nfunction formatVersionDetail(license: License | undefined): string {\n if (license == null) return '';\n const published = license.publishedDate ? determineLatestAge(license.publishedDate.split('T', 1)[0]) : '';\n const isOutdated = license.latestVersion !== '' && license.latestVersion !== license.installedVersion;\n if (!isOutdated) return published === '' ? '' : ` — ${published}`;\n const latestAge = license.latestPublishedDate ? determineLatestAge(license.latestPublishedDate.split('T', 1)[0]) : '';\n const latestClause = latestAge === '' ? `**latest**: ${license.latestVersion} ❗` : `**latest**: ${license.latestVersion} — ${latestAge} ❗`;\n return published === '' ? ` — → ${latestClause}` : ` — ${published} → ${latestClause}`;\n}\n\nfunction determineLatestAge(momentString?: string): string {\n if (momentString == null || momentString === '') return 'n/a';\n\n const dateString = momentString.split('T', 1)[0];\n if (dateString == null || dateString === '') return 'n/a';\n\n const input = new Date(dateString);\n const now = new Date();\n let months = (now.getFullYear() - input.getFullYear()) * 12 + (now.getMonth() - input.getMonth());\n if (now.getDate() < input.getDate()) months -= 1;\n\n if (months === 0) return `this month: ${dateString}`;\n if (months === 1) return `**1 month** ago: ${dateString}`;\n return months <= 6 ? `**${String(months)} months** ago: ${dateString}` : `**${String(months)} months** ago: ${dateString} ⚠️`;\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { getModuleConfig, logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, resolveOwnerAndRepo, writeReadmeSection } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- OPENING_START -->';\nconst END_MARKER = '<!-- OPENING_END -->';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentOpening(): Promise<void> {\n try {\n logOperationHeader('Document Opening');\n\n logStepHeader(\"1️⃣ Insert opening content into 'README.md'\");\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n\n const { owner, repo } = resolveOwnerAndRepo(packageJSON, 'document opening');\n const license = resolveLicense(packageJSON);\n const introduction = resolveIntroduction(configJSON);\n const npmPackageName = getModuleConfig(configJSON.id).publishedTo === 'npm' ? resolvePackageName(packageJSON) : undefined;\n\n const content = buildOpeningContent(owner, repo, license, npmPackageName, packageJSON.description, introduction);\n\n await writeReadmeSection(content, START_MARKER, END_MARKER);\n\n logOperationSuccess('Opening documented');\n } catch (error) {\n console.error('❌ Error documenting opening', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nfunction resolveLicense(packageJSON: PackageJson): string {\n const license = packageJSON.license;\n if (license == null || license === '') throw new Error(\"package.json 'license' field is required to document opening.\");\n return license;\n}\n\nfunction resolvePackageName(packageJSON: PackageJson): string {\n const name = packageJSON.name;\n if (name == null || name === '') throw new Error(\"package.json 'name' field is required to document opening.\");\n return name;\n}\n\n// 'description.en' holds the introduction as one string, with a blank line between paragraphs. With none, the\n// Introduction section is left out.\nfunction resolveIntroduction(configJSON: ModuleConfig): string | undefined {\n const introduction = configJSON.description.en?.trim();\n return introduction === undefined || introduction === '' ? undefined : introduction;\n}\n\n// The package description is optional, so a project without one simply has no summary under the links. Only projects\n// published to npm get the npm badge; the rest reach people through DPUse itself.\nfunction buildOpeningContent(\n owner: string,\n repo: string,\n license: string,\n npmPackageName: string | undefined,\n description: string | undefined,\n introduction: string | undefined\n): string {\n const repoURL = `https://github.com/${owner}/${repo}`;\n const badgeLicense = license.replaceAll('-', '--');\n const npmBadge =\n npmPackageName === undefined\n ? ''\n : `\\n[](https://www.npmjs.com/package/${npmPackageName})`;\n const summary = description == null || description === '' ? '' : `\\n\\n${description}`;\n const introductionSection = introduction === undefined ? '' : `\\n\\n## Introduction\\n\\n${introduction}`;\n\n return `[](./LICENSE)\n[](${repoURL}/releases/latest)${npmBadge}\n[](${repoURL}/actions/workflows/ci.yml)\n\n[DPUse](https://www.dpuse.app) · [Report a Vulnerability](${repoURL}/security/advisories/new) · [Open an Issue](${repoURL}/issues)${summary}\n\n## About DPUse\n\nDPUse (Data Positioning & Use) is an in-browser application that positions your data for use through three core activities: sourcing, contextualising, and publishing.\n\n**Sourcing** uses a library of [Connectors](https://www.dpuse.app/connectors) to establish [Connections](https://www.dpuse.app) to applications, databases, file stores, and curated datasets; these connections are subsequently used to configure structured [Data Views](https://www.dpuse.app) from the underlying sources.\n\n**Contextualising** extracts chronological events from those [Data Views](https://www.dpuse.app) and maps them into comprehensive [Context Models](https://www.dpuse.app). This gives the DPUse Engine the structural framework needed to generate deterministic transactions, facts, or observations.\n\n**Publishing** uses a library of [Presenters](https://www.dpuse.app) to render standard [Presentations](https://www.dpuse.app) immediately using the contextualised data; additionally, [Cookbooks](https://www.dpuse.app) of [Recipes](https://www.dpuse.app) let you build Data Apps using your preferred tools.\n\nIn addition, DPUse provides [Tools](https://www.dpuse.app) used by the application, and you can use them to construct connectors and presenters.${introductionSection}`;\n}\n","// ── External Dependencies & Registrations\nimport { execFile } from 'node:child_process';\nimport type { PackageJson } from 'type-fest';\nimport { promisify } from 'node:util';\n\n// ── Local Framework\nimport {\n FALLOW_BADGE_PATH,\n FALLOW_DIRECTORY,\n FALLOW_REPORT_PATH,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n migrateGovernanceSection,\n QUALITY_SECURITY_END_MARKER,\n QUALITY_SECURITY_START_MARKER,\n readJSONFile,\n readTextFileOrNull,\n resolveOwnerAndRepo,\n RUST_WORKSPACE_PATH,\n spawnCommand,\n spawnCommandToFile,\n writeJSONFile,\n writeReadmeSection\n} from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface BestPracticesProject {\n id: number;\n repo_url: string;\n}\n\ninterface CoverageSummary {\n total: { lines: { pct: number } };\n}\n\ninterface FallowHealth {\n health_score: { score: number; grade: string };\n}\n\ninterface GitHubCheckRuns {\n check_runs: { app: { slug: string } | null }[];\n}\n\ninterface GitHubRepoDetails {\n security_and_analysis?: Record<string, { status: string } | undefined>;\n}\n\ninterface ScorecardResult {\n checks: { name: string; score: number }[];\n}\n\n// Everything the checks tables report on, gathered before the README is written.\ninterface ChecksResults {\n coveragePercent: number | undefined;\n fallowHealth: FallowHealth | undefined;\n securitySettings: SecuritySettings;\n}\n\n// On or off, or undefined where GitHub doesn't reveal the setting (some need an admin login to read).\ntype SettingStatus = boolean | undefined;\n\ninterface SecuritySettings {\n codeQLLanguages: string[];\n codeQLQueries: string | undefined; // The query suite CodeQL is told to run; without one, it runs its default suite.\n dependabotAlerts: SettingStatus;\n dependabotSecurityUpdates: SettingStatus;\n dependabotVersionUpdates: boolean;\n lintInCI: boolean;\n npmAuditInCI: boolean;\n npmAuditLevel: string | undefined; // The '--audit-level' CI passes; without one, npm audit fails on any severity.\n privateVulnerabilityReporting: SettingStatus;\n propertyTests: boolean;\n pushProtection: SettingStatus;\n secretScanning: SettingStatus;\n socket: boolean;\n sonarCloud: boolean;\n testsInCI: boolean;\n}\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Scorecard checks a solo maintainer pushing straight to 'main' can't raise, with the best score each can reach that way.\nconst SCORECARD_PRACTICE_LIMITS: Record<string, number> = { 'Branch-Protection': 3, 'Code-Review': 0, Contributors: 0 };\n// Left out when deciding whether gaps remain: the Best Practices badge shows its own progress in the same section.\nconst SCORECARD_IGNORED_CHECKS = new Set(['CII-Best-Practices']);\n\n// Coverage — only measured where the module has the Vitest coverage provider installed. 'coverage-final.json' feeds\n// Fallow's per-function scores; the summary holds the totals the Testing table reports.\nconst COVERAGE_FINAL_PATH = 'coverage/coverage-final.json';\nconst COVERAGE_SUMMARY_PATH = 'coverage/coverage-summary.json';\nconst COVERAGE_TARGET_PERCENT = 80;\nconst COVERAGE_WARNING_PERCENT = 60; // Below the target the badge turns yellow, and below this it turns red.\nconst COVERAGE_BADGE_PATH = 'code-health-reports/vitest/badge.json'; // Not under a 'coverage' folder, which '.gitignore' leaves out.\n\nconst CODEQL_LANGUAGE_NAMES: Record<string, string> = { actions: 'GitHub Actions', 'javascript-typescript': 'JavaScript/TypeScript', rust: 'Rust' };\n\n// Fallow — only run where the module has it installed. The full report is published as its own page, linked from the\n// README; the Code Quality row and the badge are both built from the one health run, so they always agree.\nconst FALLOW_GRADE_COLOURS: Record<string, string> = { A: 'brightgreen', B: 'green', C: 'yellow', D: 'orange', F: 'red' };\nconst FALLOW_HEALTH_PATH = `${FALLOW_DIRECTORY}/health.json`;\n\n// ── Initialisation ───────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst asyncExecFile = promisify(execFile);\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Regenerates the README's Quality & Security section: testing, code quality, security analysis, dependencies and OpenSSF. */\nexport async function documentQualitySecurity(): Promise<void> {\n try {\n logOperationHeader('Document Quality & Security');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n\n const coveragePercent = await measureTestCoverage(packageJSON);\n const fallowHealth = await measureCodeHealth(packageJSON, coveragePercent === undefined ? [] : ['--coverage', COVERAGE_FINAL_PATH]);\n\n const { owner, repo } = resolveOwnerAndRepo(packageJSON, 'document quality and security');\n\n logStepHeader('4️⃣ Read security checks and settings');\n const securitySettings = await readSecuritySettings(owner, repo, packageJSON);\n\n logStepHeader('5️⃣ Look up OpenSSF Best Practices badge and Scorecard results');\n const [bestPracticesProjectId, scorecardResult] = await Promise.all([\n lookUpBestPracticesProjectId(`https://github.com/${owner}/${repo}`),\n lookUpScorecardResult(`github.com/${owner}/${repo}`)\n ]);\n\n logStepHeader(\"6️⃣ Insert quality and security content into 'README.md'\");\n const content = buildQualitySecurityContent(owner, repo, { coveragePercent, fallowHealth, securitySettings }, bestPracticesProjectId, scorecardResult);\n\n await migrateGovernanceSection();\n await writeReadmeSection(content, QUALITY_SECURITY_START_MARKER, QUALITY_SECURITY_END_MARKER);\n\n logOperationSuccess('Quality & security documented');\n } catch (error) {\n console.error('❌ Error documenting quality and security', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Answers undefined where the coverage provider isn't installed, or the Vitest config doesn't write a coverage summary.\nasync function measureTestCoverage(packageJSON: PackageJson): Promise<number | undefined> {\n if (packageJSON.devDependencies?.['@vitest/coverage-v8'] == null) {\n logStepHeader(\"1️⃣ Test coverage NOT measured, as '@vitest/coverage-v8' is not installed\");\n return undefined;\n }\n\n await spawnCommand('1️⃣ Measure test coverage', 'vitest', ['run', '--passWithNoTests', '--coverage']);\n const summary = await readTextFileOrNull(COVERAGE_SUMMARY_PATH);\n if (summary === null) return undefined;\n\n const coveragePercent = (JSON.parse(summary) as CoverageSummary).total.lines.pct;\n await writeCoverageBadge(coveragePercent);\n return coveragePercent;\n}\n\n// Written in the shields.io endpoint format, like the Fallow badge, so the README shows the latest pushed figure.\nasync function writeCoverageBadge(coveragePercent: number): Promise<void> {\n const colourNames = ['red', 'yellow', 'brightgreen'];\n const level = Number(coveragePercent >= COVERAGE_WARNING_PERCENT) + Number(coveragePercent >= COVERAGE_TARGET_PERCENT);\n await writeJSONFile(COVERAGE_BADGE_PATH, { schemaVersion: 1, label: 'coverage', message: `${coveragePercent.toFixed(1)}%`, color: colourNames[level] });\n}\n\n// Fallow exits non-zero whenever it has findings, so its exit code is ignored: the findings are what gets reported.\nasync function measureCodeHealth(packageJSON: PackageJson, coverageArguments: string[]): Promise<FallowHealth | undefined> {\n if (packageJSON.devDependencies?.['fallow'] == null) {\n logStepHeader('2️⃣ Code health NOT measured, as Fallow is not installed');\n logStepHeader('3️⃣ Code health report NOT required');\n return undefined;\n }\n\n await spawnCommandToFile('2️⃣ Measure code health', 'fallow', ['health', '--report-only', '--format', 'json', ...coverageArguments], FALLOW_HEALTH_PATH);\n await spawnCommandToFile('3️⃣ Write code health report', 'fallow', ['--format', 'markdown'], FALLOW_REPORT_PATH, true);\n const health = await readJSONFile<FallowHealth>(FALLOW_HEALTH_PATH);\n await writeFallowBadge(health);\n return health;\n}\n\n// Written in the shields.io endpoint format, so the Code Quality badge shows the latest pushed grade.\nasync function writeFallowBadge(health: FallowHealth): Promise<void> {\n const { score, grade } = health.health_score;\n await writeJSONFile(FALLOW_BADGE_PATH, {\n schemaVersion: 1,\n label: 'fallow',\n message: `${grade} (${String(Math.round(score))})`,\n color: FALLOW_GRADE_COLOURS[grade] ?? 'lightgrey'\n });\n}\n\n// Read from the repository itself each time, so the README states what is actually switched on rather than what was\n// intended. Workflow and Dependabot files are read locally; repository settings come from the GitHub API through 'gh'.\nasync function readSecuritySettings(owner: string, repo: string, packageJSON: PackageJson): Promise<SecuritySettings> {\n const [ciWorkflow, codeQLWorkflow, dependabotConfig, rustWorkspace] = await Promise.all([\n readTextFileOrNull('.github/workflows/ci.yml'),\n readTextFileOrNull('.github/workflows/codeql.yml'),\n readTextFileOrNull('.github/dependabot.yml'),\n readTextFileOrNull(RUST_WORKSPACE_PATH)\n ]);\n const [repoDetails, privateVulnerabilityReporting, vulnerabilityAlerts, checkRuns] = await Promise.all([\n readGitHubAPI(`repos/${owner}/${repo}`),\n readGitHubAPI(`repos/${owner}/${repo}/private-vulnerability-reporting`),\n readGitHubAPI(`repos/${owner}/${repo}/vulnerability-alerts`),\n readGitHubAPI(`repos/${owner}/${repo}/commits/main/check-runs?per_page=100`)\n ]);\n\n const securityAndAnalysis = repoDetails === undefined ? undefined : (JSON.parse(repoDetails) as GitHubRepoDetails).security_and_analysis;\n const readSetting = (name: string): SettingStatus => (securityAndAnalysis?.[name] === undefined ? undefined : securityAndAnalysis[name].status === 'enabled');\n const checkAppSlugs = new Set((checkRuns === undefined ? [] : (JSON.parse(checkRuns) as GitHubCheckRuns).check_runs).map((checkRun) => checkRun.app?.slug));\n\n // Version updates count as off when every ecosystem is limited to 0 pull requests, the documented way to pause them.\n const ecosystemCount = dependabotConfig?.match(/package-ecosystem:/g)?.length ?? 0;\n const pausedEcosystemCount = dependabotConfig?.match(/open-pull-requests-limit: 0\\b/g)?.length ?? 0;\n\n return {\n codeQLLanguages: (codeQLWorkflow ?? '')\n .matchAll(/- language: ([\\w-]+)/g)\n .filter(([, language]) => language !== 'rust' || rustWorkspace !== null) // The workflow lists Rust for every project, but skips its scan where there is none.\n .map(([, language = '']) => CODEQL_LANGUAGE_NAMES[language] ?? language)\n .toArray(),\n codeQLQueries: /queries: ([\\w-]+)/.exec(codeQLWorkflow ?? '')?.[1],\n dependabotAlerts: vulnerabilityAlerts !== undefined, // Answers '204 No Content' when on and '404' when off.\n dependabotSecurityUpdates: readSetting('dependabot_security_updates'),\n dependabotVersionUpdates: ecosystemCount > pausedEcosystemCount,\n lintInCI: (ciWorkflow ?? '').includes('npm run lint'),\n npmAuditInCI: /npm (?:run )?audit/.test(ciWorkflow ?? ''),\n npmAuditLevel: /npm audit --audit-level=(\\w+)/.exec(ciWorkflow ?? '')?.[1],\n privateVulnerabilityReporting: privateVulnerabilityReporting === undefined ? undefined : (JSON.parse(privateVulnerabilityReporting) as { enabled: boolean }).enabled,\n propertyTests: packageJSON.devDependencies?.['fast-check'] != null,\n pushProtection: readSetting('secret_scanning_push_protection'),\n secretScanning: readSetting('secret_scanning'),\n socket: checkAppSlugs.has('socket-security'),\n sonarCloud: checkAppSlugs.has('sonarqubecloud'),\n testsInCI: ciWorkflow?.includes('npm test') ?? false\n };\n}\n\n// Answers undefined for a 404, which is how some endpoints report a switched-off feature. Any other failure throws, so a\n// missing login or network blip can't be written into the README as settings being off.\nasync function readGitHubAPI(endpoint: string): Promise<string | undefined> {\n try {\n const { stdout } = await asyncExecFile('gh', ['api', endpoint]);\n return stdout;\n } catch (error) {\n if (String((error as { stderr?: unknown }).stderr).includes('HTTP 404')) return undefined;\n throw error;\n }\n}\n\n// Found by repository URL, as OpenSSF Scorecard does, so a repo shows its badge as soon as it is registered and nothing\n// needs configuring. Failures throw rather than return nothing, so a network blip can't drop the badge from the README.\nasync function lookUpBestPracticesProjectId(repoURL: string): Promise<number | undefined> {\n const response = await fetch(`https://www.bestpractices.dev/projects.json?url=${encodeURIComponent(repoURL)}`);\n if (!response.ok) throw new Error(`OpenSSF Best Practices lookup failed with status ${String(response.status)}.`);\n\n // The search also matches home page URLs, so keep only the entry registered for this repository.\n const projects = (await response.json()) as BestPracticesProject[];\n return projects.find((project) => project.repo_url === repoURL)?.id;\n}\n\n// Answers undefined when Scorecard has no results for the repository yet. Other failures throw, as for the badge.\nasync function lookUpScorecardResult(scorecardURI: string): Promise<ScorecardResult | undefined> {\n const response = await fetch(`https://api.scorecard.dev/projects/${scorecardURI}`);\n if (response.status === 404) return undefined;\n if (!response.ok) throw new Error(`OpenSSF Scorecard lookup failed with status ${String(response.status)}.`);\n return (await response.json()) as ScorecardResult;\n}\n\n// True when every check short of 10 is one the way the project is run caps. A score of -1 means Scorecard couldn't assess\n// the check (e.g. Signed-Releases without release assets), so it isn't counted as a gap.\nfunction isScorecardOnlyPracticeLimited(result: ScorecardResult): boolean {\n return result.checks.every(\n ({ name, score }) =>\n score === -1 || score === 10 || SCORECARD_IGNORED_CHECKS.has(name) || (SCORECARD_PRACTICE_LIMITS[name] !== undefined && score >= SCORECARD_PRACTICE_LIMITS[name])\n );\n}\n\n// Where Dependabot's pull requests are switched off, dependency updates are made by hand.\nfunction formatManualNote(status: SettingStatus): string {\n return status === false ? ' These are handled manually.' : '';\n}\n\nfunction formatStatus(status: SettingStatus): string {\n if (status === undefined) return '❔ Unknown';\n return status ? '✅ On' : '❌ Off';\n}\n\nfunction buildTableContent(heading: string, rows: string[][]): string {\n if (rows.length === 0) return '';\n return `### ${heading}\n\n|Check|Status|What it does|\n|:-|:-|:-|\n${rows.map((row) => `|${row.join('|')}|`).join('\\n')}\n\n`;\n}\n\n// A badge that shields.io draws from a JSON file this action commits, so it shows the latest pushed figure.\nfunction formatEndpointBadge(owner: string, repo: string, label: string, badgePath: string): string {\n const badgeSourceURL = encodeURIComponent(`https://raw.githubusercontent.com/${owner}/${repo}/main/${badgePath}`);\n return ``;\n}\n\n// Grouped by what each check protects against, and within a group in the order the checks act on a change: before a\n// push, on every push, then continuously, and alphabetically within each. Status is only ever on, off or unknown. What\n// it does opens with the check's badge where it has one, shown only while the check is on so a badge is never broken,\n// and names and links the product doing the check.\nfunction buildChecksContent(owner: string, repo: string, { coveragePercent, fallowHealth, securitySettings: settings }: ChecksResults): string {\n const repoURL = `https://github.com/${owner}/${repo}`;\n\n const ciNote = (isInCI: boolean): string => (isInCI ? ` Part of the [CI workflow](${repoURL}/actions/workflows/ci.yml) on every push and pull request to \\`main\\`.` : '');\n\n const testingRows = [\n ['Unit tests', formatStatus(settings.testsInCI), `[Vitest](https://vitest.dev) runs the unit tests.${ciNote(settings.testsInCI)}`],\n [\n 'Property-based tests',\n formatStatus(settings.propertyTests),\n `[fast-check](https://fast-check.dev) runs many random inputs per test to find edge cases, alongside the unit tests.${ciNote(settings.propertyTests && settings.testsInCI)}`\n ]\n ];\n if (coveragePercent !== undefined) {\n testingRows.push([\n 'Test coverage',\n formatStatus(true),\n `${formatEndpointBadge(owner, repo, 'Coverage', COVERAGE_BADGE_PATH)} [Vitest's V8 coverage](https://vitest.dev/guide/coverage) measures the share of source lines the unit tests run. The target is ${String(COVERAGE_TARGET_PERCENT)}%.`\n ]);\n }\n\n const sonarCloudBadge = `[](https://sonarcloud.io/summary/new_code?id=${owner}_${repo}) `;\n const codeQualityRows = [\n [\n 'Code analysis',\n formatStatus(settings.sonarCloud),\n `${settings.sonarCloud ? sonarCloudBadge : ''}[SonarCloud](https://sonarcloud.io) checks every push for bugs, code smells and vulnerabilities.`\n ],\n ['Linting', formatStatus(settings.lintInCI), `[ESLint](https://eslint.org) checks the code for errors and style problems.${ciNote(settings.lintInCI)}`]\n ];\n // Measured when the README is regenerated, before the changes are pushed, so it comes first.\n if (fallowHealth !== undefined) {\n codeQualityRows.unshift([\n 'Code health',\n formatStatus(true),\n `[${formatEndpointBadge(owner, repo, 'Fallow code health', FALLOW_BADGE_PATH)}](./${FALLOW_REPORT_PATH}) [Fallow](https://github.com/fallow-rs/fallow) finds unused code, duplication, complexity and dependency problems.`\n ]);\n }\n\n const hasCodeQL = settings.codeQLLanguages.length > 0;\n const codeQLBadge = `[](${repoURL}/security/code-scanning) `;\n const codeQLScope = settings.codeQLQueries === 'security-extended' ? 'using the extended security queries' : 'using the default queries';\n const codeQLLanguages = hasCodeQL ? ` ${settings.codeQLLanguages.join(' and ')}` : '';\n const securityAnalysisRows = [\n [\n 'Push protection',\n formatStatus(settings.pushProtection),\n '[GitHub push protection](https://docs.github.com/en/code-security/secret-scanning/push-protection-for-repositories-and-organizations) blocks pushes that contain credentials.'\n ],\n [\n 'Static analysis',\n formatStatus(hasCodeQL),\n `${hasCodeQL ? codeQLBadge : ''}[CodeQL](https://codeql.github.com) scans${codeQLLanguages} for security vulnerabilities, ${codeQLScope}, on every push and pull request to \\`main\\` and weekly.`\n ],\n [\n 'Secret scanning',\n formatStatus(settings.secretScanning),\n '[GitHub secret scanning](https://docs.github.com/en/code-security/secret-scanning) detects credentials, such as API keys and tokens, committed to the repository.'\n ]\n ];\n\n const dependabotLink = '[Dependabot](https://docs.github.com/en/code-security/dependabot)';\n const dependencyRows = [\n [\n 'Vulnerability audit',\n formatStatus(settings.npmAuditInCI),\n settings.npmAuditLevel === undefined\n ? `[npm audit](https://docs.npmjs.com/cli/commands/npm-audit) fails when a shipped dependency has any known vulnerability, or a development dependency has a high or critical one.${ciNote(settings.npmAuditInCI)}`\n : `[npm audit](https://docs.npmjs.com/cli/commands/npm-audit) fails when a dependency has a known vulnerability of ${settings.npmAuditLevel} severity or above.${ciNote(settings.npmAuditInCI)}`\n ],\n [\n 'Supply chain risk',\n formatStatus(settings.socket), // Socket's badge service refuses requests from outside a browser, so GitHub couldn't show it.\n '[Socket](https://socket.dev) flags malicious packages, typosquatting and suspicious behaviour that may not yet have a CVE.'\n ],\n ['Security alerts', formatStatus(settings.dependabotAlerts), `${dependabotLink} alerts when a dependency has a known vulnerability, using the GitHub Advisory Database.`],\n [\n 'Security updates',\n formatStatus(settings.dependabotSecurityUpdates),\n `${dependabotLink} opens pull requests that update vulnerable dependencies.${formatManualNote(settings.dependabotSecurityUpdates)}`\n ],\n [\n 'Version updates',\n formatStatus(settings.dependabotVersionUpdates),\n `${dependabotLink} opens pull requests for new dependency versions.${formatManualNote(settings.dependabotVersionUpdates)}`\n ]\n ];\n\n return `This section is updated each time \\`npm run document\\` is run. Settings come from the repository's workflow files and GitHub. Test coverage and the Fallow score are measured at the same time.\n\n${buildTableContent('Testing', testingRows)}${buildTableContent('Code Quality', codeQualityRows)}${buildTableContent('Security Analysis', securityAnalysisRows)}${buildTableContent('Dependencies', dependencyRows)}`;\n}\n\nfunction buildQualitySecurityContent(\n owner: string,\n repo: string,\n checksResults: ChecksResults,\n bestPracticesProjectId: number | undefined,\n scorecardResult: ScorecardResult | undefined\n): string {\n const repoURL = `https://github.com/${owner}/${repo}`;\n const scorecardURI = `github.com/${owner}/${repo}`;\n const bestPracticesURL = `https://www.bestpractices.dev/projects/${String(bestPracticesProjectId)}`;\n const scorecardLimitText =\n scorecardResult !== undefined && isScorecardOnlyPracticeLimited(scorecardResult)\n ? \"\\n\\n> [!NOTE]\\n> Apart from the Best Practices badge above, the remaining Scorecard gaps need multi-person review or a pull-request workflow, which this solo-maintained project doesn't use.\"\n : '';\n const bestPracticesBadge = bestPracticesProjectId === undefined ? '' : `[](${bestPracticesURL})\\n`;\n\n // Without private reporting switched on, the advisory link leads nowhere, so point only at SECURITY.md.\n const reportingText =\n checksResults.securitySettings.privateVulnerabilityReporting === true\n ? `Use [GitHub private vulnerability reporting](${repoURL}/security/advisories/new) instead. See [SECURITY.md](./SECURITY.md) for the full disclosure policy, contact details, and expected response times.`\n : 'See [SECURITY.md](./SECURITY.md) for how to report one privately, the full disclosure policy, and expected response times.';\n\n return `## Quality & Security\n\n${buildChecksContent(owner, repo, checksResults)}### OpenSSF 🚧\n\n${bestPracticesBadge}[](https://scorecard.dev/viewer/?uri=${scorecardURI})\n\nThis project is working towards the [OpenSSF Best Practices](https://www.bestpractices.dev) Passing badge, a self-certification covering security policy, vulnerability reporting, build processes, code quality, and more. Currently the [OpenSSF Scorecard](https://scorecard.dev) provides an independent automated assessment of the project's security practices and is an ongoing area of improvement.${scorecardLimitText}\n\n### Reporting Vulnerabilities\n\nPlease do not open public GitHub issues for security vulnerabilities. ${reportingText}`;\n}\n","// ── External Dependencies & Registrations\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\nimport type { ModuleTypeConfig } from '@/utilities';\nimport { getModuleConfig, logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, writeReadmeSection } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- USAGE_START -->';\nconst END_MARKER = '<!-- USAGE_END -->';\n\n// Module types the DPUse Engine uploads to the cloud for the browser app to load. The engine itself is also uploaded, but\n// isn't something others build their own version of, so it gets the general wording.\nconst UPLOADED_MODULE_TYPE_IDS = new Set<ModuleTypeConfig['typeId']>(['connector', 'cookbook', 'presenter']);\n\n// Published to npm only so DPUse projects can install them, not for general use, so the npm wording carries a warning.\nconst INTERNAL_NPM_MODULE_TYPE_IDS = new Set<ModuleTypeConfig['typeId']>(['development', 'eslint']);\nconst INTERNAL_NPM_WARNING = `> [!WARNING]\n> This project is not designed for general use. It is custom built for the DPUse CI/CD process. You are welcome to clone and customise it for your own purposes, but you will need to adapt it to your own project structure and tooling.`;\n\n// How the repository is managed. dpuse-development provides the actions every other repository uses, and runs them on itself.\nconst DEVELOPMENT_MANAGEMENT_TEXT = 'This repository manages itself using the actions it implements.';\nconst SHARED_MANAGEMENT_TEXT = 'This repository is managed using the common set of actions provided by [@dpuse/dpuse-development](https://github.com/dpuse/dpuse-development).';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentUsage(): Promise<void> {\n try {\n logOperationHeader('Document Usage');\n\n logStepHeader(\"1️⃣ Insert usage content into 'README.md'\");\n\n const [packageJSON, configJSON] = await Promise.all([readJSONFile<PackageJson>('package.json'), readJSONFile<ModuleConfig>('config.json')]);\n\n const cloneURL = resolveCloneURL(packageJSON);\n const directoryName = resolveDirectoryName(cloneURL);\n const nodeVersion = resolveVersion(packageJSON.engines?.node);\n const npmVersion = resolveVersion(packageJSON.engines?.npm);\n const typescriptVersion = resolveVersion(packageJSON.devDependencies?.['typescript']);\n\n const introduction = buildIntroductionContent(getModuleConfig(configJSON.id), packageJSON.name);\n // A full link, so it still works where the README is shown away from GitHub, such as on npm.\n const packageJSONURL = `${cloneURL.replace(/\\.git$/, '')}/blob/main/package.json`;\n const managementText = packageJSON.name === '@dpuse/dpuse-development' ? DEVELOPMENT_MANAGEMENT_TEXT : SHARED_MANAGEMENT_TEXT;\n const management = `${managementText} See the \\`scripts\\` block in [package.json](${packageJSONURL}) for details.`;\n const content = buildUsageContent(introduction, cloneURL, directoryName, nodeVersion, npmVersion, typescriptVersion, management);\n\n await writeReadmeSection(content, START_MARKER, END_MARKER);\n\n logOperationSuccess('Usage documented');\n } catch (error) {\n console.error('❌ Error documenting usage', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nfunction resolveCloneURL(packageJSON: PackageJson): string {\n const repo = packageJSON.repository;\n const url = typeof repo === 'string' ? repo : repo?.url;\n if (url == null || url === '') throw new Error(\"package.json 'repository' field is required to document usage.\");\n return url.replace(/^git\\+/, '');\n}\n\nfunction resolveDirectoryName(cloneURL: string): string {\n const lastSegment = cloneURL.split('/').at(-1) ?? '';\n return lastSegment.replace(/\\.git$/, '');\n}\n\nfunction resolveVersion(range: string | undefined): string {\n if (range == null) throw new Error('package.json version range is required to document usage.');\n // eslint-disable-next-line security/detect-unsafe-regex -- Linear: each group repeat must start with a literal '.'.\n const match = /\\d+(?:\\.\\d+)*/.exec(range);\n if (match == null) throw new Error(`Unable to parse version from '${range}'.`);\n return match[0];\n}\n\n// Worded for how the module reaches people: uploaded to DPUse, installed from npm, or neither.\nfunction buildIntroductionContent(moduleTypeConfig: ModuleTypeConfig, packageName: string | undefined): string {\n const { typeId } = moduleTypeConfig;\n\n if (UPLOADED_MODULE_TYPE_IDS.has(typeId)) {\n return `This ${typeId} is automatically uploaded to the DPUse Engine cloud once released and becomes instantly available to all new browser app instances, with existing instances notified of the update.\n\nYou may view or clone this repository for your own purposes, such as building a new, similar ${typeId}, though there is currently no process to accept third-party ${typeId}s into DPUse at this stage.`;\n }\n\n if (moduleTypeConfig.publishedTo === 'npm') {\n if (packageName == null || packageName === '') throw new Error(\"package.json 'name' field is required to document usage.\");\n const warning = INTERNAL_NPM_MODULE_TYPE_IDS.has(typeId) ? `${INTERNAL_NPM_WARNING}\\n\\n` : ''; // Its own paragraph, or the text after it joins the warning.\n return `This [package](https://www.npmjs.com/package/${packageName}) is available on [npm](https://www.npmjs.com/). Install it with:\n\n\\`\\`\\`bash\nnpm install ${packageName}\n\\`\\`\\`\n\n${warning}To work on the source instead, clone this repository.`;\n }\n\n return `You may view or clone this repository for your own purposes.`;\n}\n\nfunction buildUsageContent(\n introduction: string,\n cloneURL: string,\n directoryName: string,\n nodeVersion: string,\n npmVersion: string,\n typescriptVersion: string,\n management: string\n): string {\n return `## Usage\n\n${introduction}\n\n\\`\\`\\`bash\ngit clone ${cloneURL}\ncd ${directoryName}\nnpm install\n\\`\\`\\`\n\n_Requires [Node.js](https://nodejs.org/) ${nodeVersion} or later, [npm](https://www.npmjs.com/) ${npmVersion} or later, and [TypeScript](https://www.typescriptlang.org/) ${typescriptVersion} or later._\n\n${management}`;\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport const API_REFERENCE_PATH = 'API_REFERENCE.md';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Lists every export of each import path in API_REFERENCE.md. Runs with the README's sections where the project has that file. */\nexport async function documentAPIReference(): Promise<void> {\n try {\n logOperationHeader('Document API Reference');\n\n // TypeScript is an optional peer, so the code that reads the source with it is loaded only when it's needed.\n const { writeAPIReference } = await import('@/utilities/apiReference');\n await writeAPIReference('1️⃣ ', API_REFERENCE_PATH);\n\n logOperationSuccess('API reference documented');\n } catch (error) {\n console.error('❌ Error documenting API reference', error);\n process.exit(1);\n }\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, writeReadmeSection } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface Sizes {\n uncompressed: number;\n gzip: number;\n}\n\ninterface SondaResource {\n kind: 'asset' | 'chunk' | 'filesystem' | 'sourcemap';\n name: string;\n uncompressed: number;\n gzip?: number;\n parent?: string | null;\n}\n\ninterface SondaDependency {\n name: string;\n paths: string[];\n}\n\ninterface SondaJson {\n resources: SondaResource[];\n dependencies: SondaDependency[];\n}\n\ninterface GroupData {\n sizes: Sizes;\n files: Map<string, Sizes>;\n}\n\ntype GroupEntry = [string, GroupData];\ntype DependencyPath = [path: string, name: string];\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport const BUNDLE_REPORT_PATH = 'bundle-analysis-reports/sonda/index.json'; // Written by Sonda during the Vite build.\n\nconst BUNDLE_START_MARKER = '<!-- BUNDLE_START -->';\nconst BUNDLE_END_MARKER = '<!-- BUNDLE_END -->';\nconst INDENT = ' ';\nconst BAR_WIDTH = 20;\nconst BAR_CHARACTER = '█';\nconst PART_BAR_CHARACTER = '▒'; // Lighter, so a '↳' row reads as part of the row above. Markdown has no colour that also shows on npm.\n\nconst BUNDLE_ANALYSIS_INTRO = `This report is updated with each release, from the bundle the release builds, using [Sonda](https://sonda.dev/), which analyses final source maps to reveal the actual effects of tree-shaking and minification rather than relying on pre-build estimates.\\n\\n_Note: Sonda's Vite reports currently exclude CSS files, since Vite does not generate source maps for CSS._`;\n\nconst BAR_NOTE = `Bars show each row's share of its output file.`;\nconst PART_ROW_NOTE = '↳ rows are part of the row above.'; // Only where the table has such rows, which module level leaves out.\n\nconst UNTRACED_LABEL = '(bundler output, whitespace & JSON)';\nconst UNTRACED_NOTE = `${UNTRACED_LABEL} = bytes Sonda can't trace to a source file: whitespace (indentation and line breaks), code the bundler generates (region comments, the combined import/export lines, its small runtime helper and wrappers), and imported JSON such as \\`config.json\\`, which the bundler doesn't map. The JSON and the generated code are real bytes that ship; the whitespace mostly disappears once compressed.`;\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentBundleSizes(options?: { moduleLevel?: boolean }): Promise<void> {\n try {\n logOperationHeader('Document Bundle Sizes');\n\n logStepHeader('1️⃣ Read bundle analysis report');\n const json = await readJSONFile<SondaJson>(BUNDLE_REPORT_PATH);\n\n logStepHeader(`2️⃣ Insert table into 'README.md'`);\n const bundleTable = buildBundleTable(json, options?.moduleLevel ?? false);\n const rowNote = bundleTable.includes('↳') ? `${BAR_NOTE} ${PART_ROW_NOTE}` : BAR_NOTE;\n\n await writeReadmeSection(`## Bundle Analysis\\n\\n${BUNDLE_ANALYSIS_INTRO}\\n\\n${bundleTable}\\n\\n${rowNote}\\n\\n${UNTRACED_NOTE}`, BUNDLE_START_MARKER, BUNDLE_END_MARKER);\n\n logOperationSuccess('Bundle sizes documented');\n } catch (error) {\n console.error('❌ Error documenting bundle sizes', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Each output file is broken down on its own, so its top-level bars add up to 100% of that file, and its heading gives its\n// share of the whole build. Rows marked '↳' are part of the row above; their bars use the same scale, so every bar in a\n// file can be compared with every other.\nfunction buildBundleTable(json: SondaJson, isModuleLevel: boolean): string {\n const assetGroups = buildAssetGroups(json);\n const buildTotal = assetGroups\n .values()\n .flatMap((groups) => groups.values().toArray())\n .reduce((sum, group) => sum + group.sizes.uncompressed, 0);\n\n const assets = json.resources\n .filter((resource) => resource.kind === 'asset')\n .map((asset): [string, Sizes] => [asset.name, resourceSizes(asset)])\n .toSorted((a, b) => b[1].uncompressed - a[1].uncompressed);\n\n const lines = ['|Chunk/Module/File|Composition|', '|:------ |:-----------|'];\n\n for (const [file, sizes] of assets) {\n const groups = assetGroups.get(file) ?? new Map<string, GroupData>();\n const sortedGroups = [...groups].toSorted(compareGroups);\n const fileTotal = sortedGroups.reduce((sum, [, group]) => sum + group.sizes.uncompressed, 0);\n\n const buildShare = fileTotal > 0 && buildTotal > 0 ? ` · ${formatPercent(fileTotal, buildTotal)} of the build` : '';\n lines.push(`| **${file}** | ${chunkSizes(sizes)}${buildShare} |`, ...renderGroupRows(sortedGroups, fileTotal, isModuleLevel));\n }\n\n return lines.join('\\n');\n}\n\n// Largest first, except the untraced bytes, which always come last as what is left over once the modules are listed.\nfunction compareGroups(a: GroupEntry, b: GroupEntry): number {\n if ((a[0] === UNTRACED_LABEL) !== (b[0] === UNTRACED_LABEL)) return a[0] === UNTRACED_LABEL ? 1 : -1;\n return b[1].sizes.uncompressed - a[1].sizes.uncompressed;\n}\n\nfunction renderGroupRows(sortedGroups: GroupEntry[], fileTotal: number, isModuleLevel: boolean): string[] {\n const lines: string[] = [];\n\n for (const [groupName, { sizes: groupSizes, files }] of sortedGroups) {\n if (files.size === 1) {\n const fileName = getSoleFileName(files);\n lines.push(`| ${INDENT}${formatGroupLabel(groupName, fileName)} | ${composition(groupSizes.uncompressed, fileTotal)} |`);\n continue;\n }\n\n lines.push(`| ${INDENT}${groupName} | ${composition(groupSizes.uncompressed, fileTotal)} |`);\n if (!isModuleLevel) lines.push(...renderFileRows(files, fileTotal));\n }\n\n return lines;\n}\n\nfunction renderFileRows(files: Map<string, Sizes>, fileTotal: number): string[] {\n const sortedFiles = [...files].toSorted((a, b) => b[1].uncompressed - a[1].uncompressed);\n return sortedFiles.map(([fileName, fileSizes]) => `| ${INDENT}${INDENT}↳ ${fileName} | ${composition(fileSizes.uncompressed, fileTotal, PART_BAR_CHARACTER)} |`);\n}\n\n// A bar and percentage of the output file, then the size, so the share and the bytes behind it read together.\nfunction composition(bytes: number, fileTotal: number, barCharacter = BAR_CHARACTER): string {\n return `${bar(fileTotal > 0 ? (bytes / fileTotal) * 100 : 0, barCharacter)} · ${formatBytes(bytes)}`;\n}\n\n// A group with no file name, such as the untraced bytes, is shown on its own rather than as 'group → '.\nfunction formatGroupLabel(groupName: string, fileName: string): string {\n return fileName === '' ? groupName : `${groupName} → ${fileName}`;\n}\n\nfunction getSoleFileName(files: Map<string, Sizes>): string {\n const [fileName] = files.keys();\n if (fileName === undefined) throw new Error('Expected exactly one file');\n return fileName;\n}\n\n// Builds, per output asset, the size totals grouped by dependency (or 'src'/'wasm'/'(runtime)'), and by file within each group.\nfunction buildAssetGroups(json: SondaJson): Map<string, Map<string, GroupData>> {\n const dependencyPaths = buildDependencyPaths(json.dependencies);\n const assets = new Map<string, Map<string, GroupData>>();\n\n for (const resource of json.resources) {\n if (resource.kind !== 'chunk' || !resource.parent) continue;\n const { group: groupName, file: fileName } = resolveModule(resource.name, dependencyPaths);\n const sizes = resourceSizes(resource);\n\n const groups = assets.get(resource.parent) ?? new Map<string, GroupData>();\n assets.set(resource.parent, groups);\n\n const group = groups.get(groupName) ?? { sizes: zero(), files: new Map<string, Sizes>() };\n groups.set(groupName, group);\n addTo(group.sizes, sizes);\n\n const fileSizes = group.files.get(fileName) ?? zero();\n group.files.set(fileName, fileSizes);\n addTo(fileSizes, sizes);\n }\n\n return assets;\n}\n\n// Flattens `dependencies[].paths` into `[path, dependencyName]` pairs, longest path first so scoped/nested packages match before their parents.\nfunction buildDependencyPaths(dependencies: SondaDependency[]): DependencyPath[] {\n return dependencies.flatMap((dependency): DependencyPath[] => dependency.paths.map((path) => [path, dependency.name])).toSorted((a, b) => b[0].length - a[0].length);\n}\n\nfunction resolveModule(path: string, dependencyPaths: DependencyPath[]): { group: string; file: string } {\n const match = dependencyPaths.find(([dependencyPath]) => path === dependencyPath || path.startsWith(`${dependencyPath}/`));\n if (match) {\n const [dependencyPath, name] = match;\n return { group: name, file: path.slice(dependencyPath.length + 1) };\n }\n if (path === '[unassigned]') return { group: UNTRACED_LABEL, file: '' }; // Sonda's marker for chunk bytes it can't trace back to a source module.\n if (path.startsWith('\\u{0}')) return { group: '(runtime)', file: path.slice(1) };\n return { group: path.startsWith('rust/') || path.includes('vite-plugin-wasm') ? 'wasm' : 'src', file: lastPathSegment(path) };\n}\n\nfunction lastPathSegment(path: string): string {\n return path.split('/').at(-1) ?? path;\n}\n\nfunction resourceSizes(resource: SondaResource): Sizes {\n return { uncompressed: resource.uncompressed, gzip: resource.gzip ?? 0 };\n}\n\nfunction chunkSizes(sizes: Sizes): string {\n return `${formatBytes(sizes.uncompressed)} · gzip ${formatBytes(sizes.gzip)}`;\n}\n\nfunction bar(pct: number, barCharacter = BAR_CHARACTER): string {\n const count = Math.round((pct / 100) * BAR_WIDTH);\n return `\\`${barCharacter.repeat(count)}${'░'.repeat(BAR_WIDTH - count)}\\` ${pct.toFixed(1)}%`;\n}\n\nfunction zero(): Sizes {\n return { uncompressed: 0, gzip: 0 };\n}\n\nfunction addTo(target: Sizes, source: Sizes): void {\n target.uncompressed += source.uncompressed;\n target.gzip += source.gzip;\n}\n\nfunction formatPercent(part: number, whole: number): string {\n return `${((part / whole) * 100).toFixed(1)}%`;\n}\n\nfunction formatBytes(bytes: number): string {\n return bytes < 1024 ? `${String(bytes)} B` : `${(bytes / 1024).toFixed(1)} kB`;\n}\n","// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { documentActions } from '@/actions/documentActions';\nimport { documentContributingLicense } from '@/actions/documentContributingLicense';\nimport { documentDependencies } from '@/actions/documentDependencies';\nimport { documentOpening } from '@/actions/documentOpening';\nimport { documentQualitySecurity } from '@/actions/documentQualitySecurity';\nimport { documentUsage } from '@/actions/documentUsage';\nimport { API_REFERENCE_PATH, documentAPIReference } from '@/actions/documentApiReference';\nimport { BUNDLE_REPORT_PATH, documentBundleSizes } from '@/actions/documentBundleSizes';\nimport { getModuleConfig, logStepHeader, readJSONFile, readTextFileOrNull, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Regenerates every generated section of the README, in the order they appear, then the API reference where the project keeps one. */\n// 'allowedLicenses' lists the licences dependencies may use, separated by ';'. 'isModuleLevel' breaks bundle sizes\n// down by module rather than by package.\nexport async function documentProject(allowedLicenses = 'MIT', isModuleLevel = false): Promise<void> {\n try {\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const isConnector = getModuleConfig(configJSON.id).typeId === 'connector'; // Only connectors have an actions table.\n\n await documentOpening();\n if (isConnector) await documentActions();\n await documentUsage();\n await documentDependencies(allowedLicenses);\n\n // Bundle sizes come from the report the last build wrote, so they wait until there is one, as on a fresh clone.\n if ((await readTextFileOrNull(BUNDLE_REPORT_PATH)) === null) {\n logStepHeader(`ℹ️ Bundle sizes NOT documented, as there is no '${BUNDLE_REPORT_PATH}' yet. Build the project first.`);\n } else {\n await documentBundleSizes({ moduleLevel: isModuleLevel });\n }\n\n await documentQualitySecurity();\n await documentContributingLicense();\n\n // Only where the project keeps an API reference, so projects opt in by adding the file.\n const hasAPIReference = (await readTextFileOrNull(API_REFERENCE_PATH)) !== null;\n if (hasAPIReference) {\n await documentAPIReference();\n } else {\n logStepHeader(`ℹ️ '${API_REFERENCE_PATH}' NOT required by this project`);\n }\n\n // Saved as Prettier would format them, so 'npm run format' has nothing left to change. Only the files written here\n // are formatted, so documenting never touches the source.\n await spawnCommand('ℹ️ Format generated files', 'prettier', ['--write', 'README.md', ...(hasAPIReference ? [API_REFERENCE_PATH] : [])]);\n } catch (error) {\n console.error('❌ Error documenting project', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport { existsSync } from 'node:fs';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Uses prettier to enforce formatting style rules. */\nexport async function formatCode(): Promise<void> {\n try {\n logOperationHeader('Format Code');\n\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- specified directories, no user input.\n const optionalGlobs = ['app', 'src', 'tests'].filter((directory) => existsSync(directory)).map((directory) => `${directory}/**`);\n const formatTargets = ['--write', '*.json', '*.md', '*.ts', ...optionalGlobs];\n await spawnCommand('1️⃣ Format', 'prettier', formatTargets);\n\n logOperationSuccess('Code formatted');\n } catch (error) {\n console.error('❌ Error formatting code', error);\n process.exit(1);\n }\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Uses eslint to check the code for potential errors and enforces coding style rules. */\nexport async function lintCode(): Promise<void> {\n try {\n logOperationHeader('Lint Code');\n\n await spawnCommand('1️⃣ Lint', 'eslint', ['.']);\n\n logOperationSuccess('Code linted');\n } catch (error) {\n console.error('❌ Error linting code', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport type { ObjectEncodingOptions } from 'node:fs';\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { execCommand, getDirectoryEntries, getStatsForPath, readJSONFile } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function putState(): Promise<void> {\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const options = {\n body: JSON.stringify(configJSON),\n headers: { 'Content-Type': 'application/json' },\n method: 'PUT'\n };\n const response = await fetch(`https://api.dpuse.app/configs/${configJSON.id}`, options);\n if (!response.ok) throw new Error(await response.text());\n}\n\nexport async function uploadDirectoryToR2(sourceDirectory: string, uploadDirectory: string): Promise<void> {\n async function listDirectoryEntriesRecursively(currentSourceDirectory: string, currentDestinationDirectory: string, names: string[]): Promise<void> {\n for (const name of names) {\n const sourceItemPath = `${currentSourceDirectory}/${name}`;\n const destinationItemPath = `${currentDestinationDirectory}/${name}`;\n const stats = await getStatsForPath(sourceItemPath);\n if (stats.isDirectory()) {\n const nextLevelChildren = await getDirectoryEntries(sourceItemPath);\n await listDirectoryEntriesRecursively(sourceItemPath, destinationItemPath, nextLevelChildren);\n } else {\n console.info(`⚙️ Uploading '${currentSourceDirectory}/${name}'...`);\n await execCommand(undefined, 'wrangler', [\n 'r2',\n 'object',\n 'put',\n `dpuse-sample-data-eu/${currentDestinationDirectory}/${name}`,\n `--file=${currentSourceDirectory}/${name}`,\n '--jurisdiction=eu',\n '--remote'\n ]);\n }\n }\n }\n const toplevelNames = await getDirectoryEntries(`${sourceDirectory}/${uploadDirectory}/`);\n await listDirectoryEntriesRecursively(`${sourceDirectory}/${uploadDirectory}`, uploadDirectory, toplevelNames);\n}\n\nexport async function uploadModuleConfigToDO(configJSON: ModuleConfig): Promise<void> {\n const stateId = configJSON.id;\n const options = {\n body: JSON.stringify(configJSON),\n headers: { 'Content-Type': 'application/json' },\n method: 'PUT'\n };\n const response = await fetch(`https://api.dpuse.app/configs/${stateId}`, options);\n if (!response.ok) throw new Error(await response.text());\n}\n\nexport async function uploadModuleToR2(packageJSON: PackageJson, uploadDirectoryPath: string): Promise<void> {\n const version = `v${packageJSON.version ?? 'unknown'}`;\n async function uploadDirectory(currentDirectory: string, prefix = ''): Promise<void> {\n const entries = await getDirectoryEntries(currentDirectory, { withFileTypes: true } as ObjectEncodingOptions);\n for (const entry of entries) {\n if (entry.isDirectory() || entry.name.endsWith('.map')) continue;\n const fullPath = `${currentDirectory}/${entry.name}`;\n const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;\n const r2Path = `${uploadDirectoryPath}_${version}/${relativePath}`.replaceAll('\\\\', '/');\n const nonJavaScripContentType = entry.name.endsWith('.css') ? 'text/css' : 'application/octet-stream';\n const contentType = entry.name.endsWith('.js') ? 'application/javascript' : nonJavaScripContentType;\n console.info(`⚙️ Uploading '${relativePath}' → '${r2Path}'...`);\n await execCommand(undefined, 'wrangler', ['r2', 'object', 'put', r2Path, `--file=${fullPath}`, '--content-type', contentType, '--jurisdiction=eu', '--remote']);\n }\n }\n await uploadDirectory('dist');\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { getModuleConfig, logOperationHeader, logOperationSuccess, logStepHeader, type ModuleTypeConfig, readJSONFile, spawnCommand } from '@/utilities';\nimport { putState, uploadModuleConfigToDO, uploadModuleToR2 } from '@/utilities/cloudflare';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Publishes the project to npm, uploads it to DPUse, or both, as its module type requires. Run by the 'publish.yml' workflow. */\nexport async function publishProject(): Promise<void> {\n try {\n logOperationHeader('Publish Project');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n\n // Where a module goes is set by its type, so every project calls this the same way. Tools go to both places: npm\n // first, so the app is never told of a version whose npm publish failed.\n if (moduleTypeConfig.publishedTo === 'npm') {\n await spawnCommand('1️⃣ Publish to npm', 'npm', ['publish', '--provenance']);\n } else {\n logStepHeader('1️⃣ Publishing to npm NOT required');\n }\n\n await registerModule('2️⃣ ', packageJSON, configJSON, moduleTypeConfig);\n\n logOperationSuccess(`Project version '${packageJSON.version ?? 'unknown'}' published.`);\n } catch (error) {\n console.error('❌ Error publishing project', error);\n process.exit(1);\n }\n}\n\n// Also run as the last step of 'releaseProject'.\nexport async function registerModule(stepIcon: string, packageJSON: PackageJson, configJSON: ModuleConfig, moduleTypeConfig: ModuleTypeConfig): Promise<void> {\n if (moduleTypeConfig.typeId === 'app') {\n logStepHeader(`${stepIcon} Register module`);\n await putState();\n } else if (moduleTypeConfig.typeId === 'engine') {\n logStepHeader(`${stepIcon} Register module`);\n await uploadModuleToR2(packageJSON, `dpuse-engine-eu/${moduleTypeConfig.uploadGroupName ?? 'unknown'}`);\n await uploadModuleConfigToDO(configJSON); // This MUST follow 'uploadModuleToR2', otherwise the app will receive a message a new engine is available and try to access it before it is uploaded to R2.\n } else if (moduleTypeConfig.uploadGroupName === undefined) {\n logStepHeader(`${stepIcon} Registration NOT required`);\n } else {\n logStepHeader(`${stepIcon} Register module`);\n const moduleTypeName = configJSON.id.split('-').slice(2).join('-');\n await uploadModuleToR2(packageJSON, `dpuse-engine-eu/${moduleTypeConfig.uploadGroupName}/${moduleTypeName}`);\n await uploadModuleConfigToDO(configJSON); // This MUST follow 'uploadModuleToR2', otherwise the app will receive a message a new module is available and try to access it before it is uploaded to R2.\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { bundleProject } from '@/actions/buildProject';\nimport { documentProject } from '@/actions/documentProject';\nimport { registerModule } from '@/actions/publishProject';\nimport {\n buildModuleConfig,\n bumpPackageVersion,\n execCommand,\n getModuleConfig,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n readJSONFile,\n spawnCommand\n} from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Bump version, builds config, builds project, regenerates the README, synchronise with GitHub and publish to npm or Cloudflare. */\nexport async function releaseProject(allowedLicenses = 'MIT', isModuleLevel = false): Promise<void> {\n try {\n logOperationHeader('Release Project');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n\n await bumpPackageVersion('1️⃣ ', packageJSON);\n\n const builtConfigJSON = await buildModuleConfig('2️⃣ ', packageJSON, moduleTypeConfig);\n\n await bundleProject('3️⃣ ', packageJSON);\n\n // After the build, so the bundle sizes are the released bundle's, and before staging, so the README is committed\n // with the release. Its governance step runs the tests, so a failing test stops the release before anything is pushed.\n logStepHeader('4️⃣ Regenerate README');\n await documentProject(allowedLicenses, isModuleLevel);\n\n await execCommand('5️⃣ Stage changes', 'git', ['add', '.']);\n\n await execCommand('6️⃣ Commit changes', 'git', ['commit', '-m', `v${packageJSON.version ?? 'unknown'}`]);\n\n await execCommand('7️⃣ Push changes', 'git', ['push', 'origin', 'main:main']);\n\n await registerModule('8️⃣ ', packageJSON, builtConfigJSON, moduleTypeConfig);\n\n // The release triggers the 'publish.yml' workflow, which publishes to npm through trusted publishing, so no token is needed here.\n if (moduleTypeConfig.publishedTo === 'npm') {\n const tagName = `v${packageJSON.version ?? 'unknown'}`;\n await spawnCommand('9️⃣ Create GitHub release', 'gh', ['release', 'create', tagName, '--target', 'main', '--generate-notes', '--latest']);\n } else {\n logStepHeader(`9️⃣ Publishing NOT required for package with type identifier of '${moduleTypeConfig.typeId}'.`);\n }\n\n logOperationSuccess(`Project version '${packageJSON.version ?? 'unknown'}' released.`);\n } catch (error) {\n console.error('❌ Error releasing project', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { buildModuleConfig, bumpPackageVersion, execCommand, getModuleConfig, logOperationHeader, logOperationSuccess, readJSONFile } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Synchronise the local repository with the main GitHub repository. */\nexport async function syncProjectWithGitHub(): Promise<void> {\n try {\n logOperationHeader('Synchronise Project with GitHub');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n\n await bumpPackageVersion('1️⃣ ', packageJSON);\n\n await buildModuleConfig('2️⃣ ', packageJSON, moduleTypeConfig);\n\n await execCommand('3️⃣ Stage changes', 'git', ['add', '.']);\n\n await execCommand('4️⃣ Commit changes', 'git', ['commit', '-m', `v${packageJSON.version ?? 'unknown'}`]);\n\n await execCommand('5️⃣ Push changes', 'git', ['push', 'origin', 'main:main']);\n\n logOperationSuccess(`Project version '${packageJSON.version ?? 'unknown'}' synchronised with GitHub.`);\n } catch (error) {\n console.error('❌ Error synchronising project with GitHub', error);\n process.exit(1);\n }\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, readTextFileOrNull, spawnCommand } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface TestTypeConfig {\n id: TestTypeId;\n label: string;\n command: string;\n arguments: string[];\n configFileName: string; // Having this file is how a project says it runs this type of test.\n}\n\nexport type TestTypeId = 'e2e' | 'unit';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst STEP_ICONS = ['1️⃣ ', '2️⃣ ', '3️⃣ ', '4️⃣ '];\n\n// In the order they run. Unit tests go first so a failure stops the run before the slow browser tests start.\n// Both runners are told to pass when they find nothing, so a project that has set up a runner but not yet written\n// any tests reports green rather than red, and a real failure stands out.\nconst TEST_TYPE_CONFIGS: TestTypeConfig[] = [\n { id: 'unit', label: 'Run unit tests', command: 'vitest', arguments: ['run', '--passWithNoTests'], configFileName: 'vitest.config.ts' },\n { id: 'e2e', label: 'Run end-to-end tests', command: 'playwright', arguments: ['test', '--pass-with-no-tests'], configFileName: 'playwright.config.ts' }\n];\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Runs the requested types of test, skipping any type this project has not configured. */\nexport async function testProject(testTypeIds: TestTypeId[] = ['unit']): Promise<void> {\n try {\n logOperationHeader('Test Project');\n\n let stepNumber = 0;\n for (const testTypeConfig of TEST_TYPE_CONFIGS) {\n if (!testTypeIds.includes(testTypeConfig.id)) continue;\n\n // Without its configuration file the project does not run this type of test, so pass over it quietly.\n if ((await readTextFileOrNull(testTypeConfig.configFileName)) === null) continue;\n\n const stepLabel = `${STEP_ICONS[stepNumber] ?? ''} ${testTypeConfig.label}`;\n await spawnCommand(stepLabel, testTypeConfig.command, testTypeConfig.arguments);\n stepNumber += 1;\n }\n\n if (stepNumber === 0) {\n console.warn('\\n⚠️ No tests configured for this project.\\n');\n return;\n }\n\n logOperationSuccess('Project tested');\n } catch (error) {\n console.error('❌ Error testing project', error);\n process.exit(1);\n }\n}\n"],"mappings":";;;;;;;;;AAMA,eAAsBuC,KAAmC;CACrD,IAAI;EAQA,AAPAlB,EAAmB,oBAAoB,GAIvC,MAAMc,EAAa,yDAAyD,OAAO,CAAC,SAAS,YAAY,CAAC,GAC1G,MAAMA,EAAa,oEAAoE,OAAO,CAAC,SAAS,oBAAoB,CAAC,GAE7HpB,EAAoB,sBAAsB;CAC9C,SAASyB,GAAO;EAEZ,AADA,QAAQ,MAAM,kCAAkCA,CAAK,GACrD,QAAQ,KAAK,CAAC;CAClB;AACJ;;;ACXA,IAAMC,IAAyB;AAK/B,eAAsBC,KAA8B;CACh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sB;CAAG,gBAAgB;AAAuB,CAC3J;AAKA,eAAsBC,GAAY,IAA4B,CAAC,MAAM,GAAkB;CACnF,IAAI;EACA,EAAmB,cAAc;EAEjC,IAAIC,IAAa;EACjB,KAAK,IAAMC,KAAkBH,IAAmB;GAI5C,IAHI,CAACI,EAAY,SAASD,EAAe,EAAE,KAGtC,MAAM1Y,EAAmB0Y,EAAe,cAAc,MAAO,MAAM;GAExE,IAAME,IAAY,GAAGN,GAAWG,MAAe,GAAG,GAAGC,EAAe;GAEpE,AADA,MAAMpX,EAAasX,GAAWF,EAAe,SAASA,EAAe,SAAS,GAC9E,KAAc;EAClB;EAEA,IAAID,MAAe,GAAG;GAClB,QAAQ,KAAK,+CAA+C;GAC5D;EACJ;EAEA,EAAoB,gBAAgB;CACxC,SAAS9W,GAAO;EAEZ,AADA,QAAQ,MAAM,4BAA4BA,CAAK,GAC/C,QAAQ,KAAK,CAAC;CAClB;AACJ"}
|
|
1
|
+
{"version":3,"file":"dpuse-development.es.js","names":["runNpmCheckUpdates","START_MARKER","END_MARKER","determineConnectorUsageId","getConnectorActionsTable","START_MARKER","END_MARKER","START_MARKER","END_MARKER","xe","resolveOwnerAndRepo","writeReadmeSection","writeJSONFile","readTextFileOrNull","spawnCommandToFile","logOperationSuccess","FALLOW_REPORT_PATH","readJSONFile","RUST_WORKSPACE_PATH","clearDirectory","execCommand","logOperationHeader","getStatsForPath","FALLOW_DIRECTORY","j","buildModuleConfig","getModuleConfig","CONTRIBUTING_LICENSE_START_MARKER","QUALITY_SECURITY_END_MARKER","getDirectoryEntries","FALLOW_BADGE_PATH","QUALITY_SECURITY_START_MARKER","CONTRIBUTING_LICENSE_END_MARKER","bumpPackageVersion","logStepHeader","spawnCommand","readTextFile","migrateGovernanceSection","path","auditDependencies","error","WASM_BUILD_SCRIPT_NAME","buildProject","bundleProject","packageJSON","stepIcon","PRETTIER_CONFIG_REFERENCE","TEMPLATE_REPOSITORY_NAME","checkConfigFiles","configJSON","isPrivate","moduleTypeConfig","moduleDirectory","fileURLToPath","checkConfigFile","checkESLintConfig","checkTSConfig","checkTSConfigScripts","checkViteConfig","checkVitestConfig","checkPrettierConfig","hasRust","checkWorkflows","content","\"prettier\"","viteConfigTemplates","checkFilePath","checkFileName","templates","templateFileNames","checkFileContent","templateFileName","templatePath","templateContent","prepareTemplate","checkDependencies","rcOptions","run","pinnedPackageNames","getPinnedPackageNames","names","allowScripts","key","isAllowed","checkProject","START_MARKER$3","END_MARKER$3","CONNECTOR_ACTIONS_INTRO","CONNECTOR_USAGE_DESCRIPTIONS","CONNECTOR_ACTIONS_TABLE_LEAD_IN","documentActions","actionNames","usageId","table","block","documentContributingLicense","authorName","resolveAuthorName","copyrightYear","resolveCopyrightYear","buildContributingLicenseContent","owner","repo","author","authorString","emailStart","emailEnd","part","currentYear","firstCreatedAt","startYear","START_MARKER$2","END_MARKER$2","LICENSES_HEADING","DEPENDENCY_TREE_INTRO","documentDependencies","rootPackage","skipDependencyDocumentation","unshippedPackages","listUnshippedPackages","options","allowedLicenses","resolve","reject","insertLicensesIntoReadme","name","message","licenses","licenseTree","licensesByKey","value","parseLicenseEntry","data","fetchNpmData","license","licensesContent","buildLicensesIntro","formatLicenseRow","treeItems","walkTreeList","treeContent","lockText","packages","shipped","unshipped","lockPath","entry","packageKey","formatLicenseListText","lastAt","installedVersion","response","distributionTags","timeMap","latestVersion","publishedDate","version","licenseLink","indent","depth","node","dependencies","nameLink","versionDetail","formatVersionDetail","items","published","determineLatestAge","latestAge","latestClause","momentString","dateString","input","now","months","START_MARKER$1","END_MARKER$1","documentOpening","resolveLicense","introduction","resolveIntroduction","buildOpeningContent","resolvePackageName","repoURL","npmPackageName","description","SCORECARD_PRACTICE_LIMITS","SCORECARD_IGNORED_CHECKS","COVERAGE_FINAL_PATH","COVERAGE_SUMMARY_PATH","COVERAGE_TARGET_PERCENT","COVERAGE_WARNING_PERCENT","COVERAGE_BADGE_PATH","CODEQL_LANGUAGE_NAMES","FALLOW_GRADE_COLOURS","FALLOW_HEALTH_PATH","asyncExecFile","promisify","execFile","documentQualitySecurity","coveragePercent","measureTestCoverage","fallowHealth","measureCodeHealth","securitySettings","readSecuritySettings","bestPracticesProjectId","scorecardResult","lookUpBestPracticesProjectId","lookUpScorecardResult","buildQualitySecurityContent","summary","writeCoverageBadge","colourNames","level","\"fallow\"","coverageArguments","health","writeFallowBadge","grade","score","ciWorkflow","codeQLWorkflow","dependabotConfig","rustWorkspace","repoDetails","privateVulnerabilityReporting","vulnerabilityAlerts","checkRuns","readGitHubAPI","securityAndAnalysis","readSetting","checkAppSlugs","checkRun","ecosystemCount","pausedEcosystemCount","language","endpoint","stdout","project","scorecardURI","isScorecardOnlyPracticeLimited","result","formatManualNote","status","formatStatus","buildTableContent","rows","heading","row","formatEndpointBadge","label","badgePath","buildChecksContent","settings","ciNote","isInCI","testingRows","sonarCloudBadge","codeQualityRows","hasCodeQL","codeQLBadge","codeQLScope","codeQLLanguages","securityAnalysisRows","dependabotLink","dependencyRows","bestPracticesURL","scorecardLimitText","bestPracticesBadge","reportingText","checksResults","START_MARKER","END_MARKER","UPLOADED_MODULE_TYPE_IDS","INTERNAL_NPM_MODULE_TYPE_IDS","INTERNAL_NPM_WARNING","DEVELOPMENT_MANAGEMENT_TEXT","SHARED_MANAGEMENT_TEXT","documentUsage","cloneURL","resolveCloneURL","directoryName","resolveDirectoryName","nodeVersion","resolveVersion","npmVersion","typescriptVersion","\"typescript\"","buildIntroductionContent","packageJSONURL","buildUsageContent","url","range","match","typeId","packageName","management","API_REFERENCE_PATH","documentAPIReference","writeAPIReference","BUNDLE_REPORT_PATH","BUNDLE_START_MARKER","BUNDLE_END_MARKER","INDENT","BAR_WIDTH","BAR_CHARACTER","PART_BAR_CHARACTER","MIN_VISIBLE_PERCENT","SMALL_FILES_MAX_PERCENT","BUNDLE_ANALYSIS_INTRO","BAR_NOTE","PART_ROW_NOTE","UNTRACED_LABEL","UNTRACED_NOTE","documentBundleSizes","json","bundleTable","buildBundleTable","rowNote","assetGroups","buildAssetGroups","buildTotal","groups","sum","group","assets","resource","asset","resourceSizes","b","a","lines","file","sizes","sortedGroups","compareGroups","fileTotal","buildShare","formatPercent","chunkSizes","renderGroupRows","isModuleLevel","groupName","groupSizes","files","fileName","getSoleFileName","formatGroupLabel","composition","renderFileRows","sortedFiles","smallCount","countSmallFiles","fileSizes","smallBytes","count","bytes","isTooSmallToShow","isCombinedRowStillSmall","bar","barCharacter","formatBytes","dependencyPaths","buildDependencyPaths","resolveModule","zero","addTo","dependency","dependencyPath","shortenCrateFileName","lastPathSegment","crateName","pct","source","whole","documentProject","isConnector","hasAPIReference","formatCode","formatTargets","existsSync","directory","lintCode","putState","uploadDirectoryToR2","listDirectoryEntriesRecursively","sourceItemPath","currentSourceDirectory","destinationItemPath","currentDestinationDirectory","toplevelNames","sourceDirectory","uploadDirectory","uploadModuleConfigToDO","stateId","uploadModuleToR2","entries","currentDirectory","fullPath","relativePath","prefix","r2Path","uploadDirectoryPath","nonJavaScripContentType","contentType","publishProject","registerModule","moduleTypeName","releaseProject","builtConfigJSON","tagName","syncProjectWithGitHub","STEP_ICONS","TEST_TYPE_CONFIGS","testProject","stepNumber","testTypeConfig","testTypeIds","stepLabel"],"sources":["../src/actions/auditDependencies.ts","../src/actions/buildProject.ts","../src/actions/checkConfigFiles.ts","../src/actions/checkDependencies.ts","../src/actions/checkProject.ts","../src/actions/documentActions.ts","../src/actions/documentContributingLicense.ts","../src/actions/documentDependencies.ts","../src/actions/documentOpening.ts","../src/actions/documentQualitySecurity.ts","../src/actions/documentUsage.ts","../src/actions/documentApiReference.ts","../src/actions/documentBundleSizes.ts","../src/actions/documentProject.ts","../src/actions/formatCode.ts","../src/actions/lintCode.ts","../src/utilities/cloudflare.ts","../src/actions/publishProject.ts","../src/actions/releaseProject.ts","../src/actions/syncProjectWithGitHub.ts","../src/actions/testProject.ts"],"sourcesContent":["// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Audit the project's dependencies for known security vulnerabilities. */\nexport async function auditDependencies(): Promise<void> {\n try {\n logOperationHeader('Audit Dependencies');\n\n // Strict for what users install. Dev tools never ship but do run in CI, where the publish tokens are, so they fail\n // only on serious flaws; moderate ones there often wait on upstream fixes and would otherwise block every push.\n await spawnCommand('1️⃣ Check shipped dependencies for any vulnerability', 'npm', ['audit', '--omit=dev']);\n await spawnCommand('2️⃣ Check all dependencies for high or critical vulnerabilities', 'npm', ['audit', '--audit-level=high']);\n\n logOperationSuccess('Dependencies audited');\n } catch (error) {\n console.error('❌ Error auditing dependencies', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, readJSONFile, spawnCommand } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// A project with Rust code names its WebAssembly build in this script, as the crate and target differ by project.\nconst WASM_BUILD_SCRIPT_NAME = 'build:wasm';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Builds the package using Vite. Output to '/dist' directory. Builds bundle analysis reports. */\nexport async function buildProject(): Promise<void> {\n try {\n logOperationHeader('Build Project');\n\n await bundleProject('1️⃣ ', await readJSONFile<PackageJson>('package.json'));\n\n logOperationSuccess('Project built');\n } catch (error) {\n console.error('❌ Error building project', error);\n process.exit(1);\n }\n}\n\n/** Bundles the project with Vite, first building its WebAssembly where the project has a 'build:wasm' script. */\nexport async function bundleProject(stepIcon: string, packageJSON: PackageJson): Promise<void> {\n if (packageJSON.scripts?.[WASM_BUILD_SCRIPT_NAME] != null) {\n await spawnCommand(`${stepIcon} Build WebAssembly`, 'npm', ['run', WASM_BUILD_SCRIPT_NAME]);\n }\n await spawnCommand(`${stepIcon} Bundle project`, 'vite', ['build']);\n}\n","// ── External Dependencies & Registrations\nimport { fileURLToPath } from 'node:url';\nimport type { PackageJson } from 'type-fest';\nimport path from 'node:path';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport {\n getModuleConfig,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n ModuleTypeConfig,\n readJSONFile,\n readTextFile,\n readTextFileOrNull,\n RUST_WORKSPACE_PATH\n} from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst PRETTIER_CONFIG_REFERENCE = '@dpuse/dpuse-development/prettierrc';\nconst TEMPLATE_REPOSITORY_NAME = 'dpuse-development'; // Stands in for each project's own name in the SECURITY.md template.\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function checkConfigFiles(): Promise<void> {\n try {\n logOperationHeader('Check configuration files');\n\n logStepHeader('1️⃣ Check individual files');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const isPrivate = packageJSON.private === true; // Private packages have no workflows or security policy.\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n const moduleDirectory = path.dirname(fileURLToPath(import.meta.url));\n await checkConfigFile(moduleDirectory, '.editorconfig');\n await checkConfigFile(moduleDirectory, '.gitattributes');\n await checkConfigFile(moduleDirectory, '.gitignore', ['.gitignore_default']);\n await checkConfigFile(moduleDirectory, '.markdownlint.json');\n await checkConfigFile(moduleDirectory, '.ncurc.json');\n await checkESLintConfig(moduleTypeConfig, moduleDirectory);\n await checkConfigFile(moduleDirectory, 'LICENSE');\n await checkTSConfig(moduleTypeConfig, moduleDirectory);\n await checkTSConfigScripts(moduleTypeConfig, moduleDirectory);\n await checkViteConfig(moduleTypeConfig, moduleDirectory);\n await checkVitestConfig(moduleTypeConfig, moduleDirectory);\n checkPrettierConfig(moduleTypeConfig, packageJSON);\n // Projects with Rust code pin their Rust version, and have Dependabot watch Cargo as well.\n const hasRust = (await readTextFileOrNull(RUST_WORKSPACE_PATH)) !== null;\n if (hasRust) await checkConfigFile(moduleDirectory, 'rust-toolchain.toml');\n const dependabotTemplate = `.github/dependabot${isPrivate ? '.private' : ''}${hasRust ? '.rust' : ''}.yml`;\n await checkConfigFile(moduleDirectory, '.github/dependabot.yml', [dependabotTemplate]);\n if (isPrivate) {\n console.info(\"ℹ️ GitHub workflows and file 'SECURITY.md' are NOT required by this project\");\n } else {\n await checkWorkflows(moduleDirectory);\n await checkConfigFile(moduleDirectory, 'SECURITY.md', [], (content) => content.replaceAll(TEMPLATE_REPOSITORY_NAME, () => configJSON.id));\n }\n\n logOperationSuccess('Configuration files checked');\n } catch (error) {\n console.error('❌ Error checking configuration files', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nasync function checkESLintConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['github', 'kb'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'eslint.config.js' is NOT required by this project\");\n } else if (['app', 'api', 'development', 'eslint'].includes(moduleTypeConfig.typeId)) {\n console.info(\"⚠️ File 'eslint.config.js' is UNIQUE to this project\");\n } else {\n await checkConfigFile(moduleDirectory, 'eslint.config.js', ['eslint.config.default.js']);\n }\n}\nfunction checkPrettierConfig(moduleTypeConfig: ModuleTypeConfig, packageJSON: PackageJson) {\n if (moduleTypeConfig.typeId === 'development') {\n console.info(\"ℹ️ File '.prettierrc.json' is the template\"); // Every other project points to this file.\n } else if (moduleTypeConfig.typeId === 'app') {\n console.info(\"⚠️ File '.prettierrc.json' is UNIQUE to this project\");\n } else if (packageJSON['prettier'] === PRETTIER_CONFIG_REFERENCE) {\n console.info(`ℹ️ Prettier configuration is '${PRETTIER_CONFIG_REFERENCE}'`);\n } else {\n console.info(`❌ Prettier configuration is NOT '${PRETTIER_CONFIG_REFERENCE}'`);\n }\n}\n\nasync function checkTSConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['github'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'tsconfig.json' is NOT required by this project\");\n } else if (['connector', 'cookbook', 'development', 'engine', 'presenter', 'shared', 'tool'].includes(moduleTypeConfig.typeId)) {\n await checkConfigFile(moduleDirectory, 'tsconfig.json');\n } else {\n console.info(\"⚠️ File 'tsconfig.json' is UNIQUE to this project\");\n }\n}\n\nasync function checkTSConfigScripts(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['github'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'scripts/tsconfig.json' is NOT required by this project\");\n } else {\n await checkConfigFile(moduleDirectory, 'scripts/tsconfig.json'); // Type-checks the 'scripts' folder, whose files Node runs directly.\n }\n}\n\nasync function checkViteConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['eslint', 'github', 'kb'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'vite.config.ts' is NOT required by this project\");\n } else if (['app', 'api', 'development', 'engine'].includes(moduleTypeConfig.typeId)) {\n console.info(\"⚠️ File 'vite.config.ts' is UNIQUE to this project\");\n } else {\n let viteConfigTemplates: string[];\n switch (moduleTypeConfig.typeId) {\n case 'connector':\n viteConfigTemplates = ['vite.config.default.ts', 'vite.config.wasm.ts'];\n break;\n case 'presenter':\n viteConfigTemplates = ['vite.config.presenter.ts'];\n break;\n case 'tool':\n viteConfigTemplates = ['vite.config.tool.ts'];\n break;\n default:\n viteConfigTemplates = ['vite.config.default.ts'];\n }\n await checkConfigFile(moduleDirectory, 'vite.config.ts', viteConfigTemplates);\n }\n}\nasync function checkWorkflows(moduleDirectory: string) {\n await checkConfigFile(moduleDirectory, '.github/workflows/ci.yml');\n await checkConfigFile(moduleDirectory, '.github/workflows/codeql.yml');\n await checkConfigFile(moduleDirectory, '.github/workflows/publish.yml');\n await checkConfigFile(moduleDirectory, '.github/workflows/scorecard.yml');\n}\n\nasync function checkVitestConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['app', 'api', 'eslint', 'github', 'kb'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'vitest.config.ts' is NOT required by this project\");\n } else {\n await checkConfigFile(moduleDirectory, 'vitest.config.ts');\n }\n}\n\nasync function checkConfigFile(moduleDirectory: string, checkFileName: string, templateFileNames: string[] = [], prepareTemplate = (content: string) => content): Promise<void> {\n const checkFilePath = path.resolve(process.cwd(), checkFileName);\n const templates = templateFileNames.length > 0 ? templateFileNames : [checkFileName];\n\n let checkFileContent;\n try {\n checkFileContent = await readTextFile(checkFilePath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n if (checkFileContent === undefined) {\n console.info(`❌ File '${checkFileName}' is MISSING`);\n return;\n }\n\n for (const templateFileName of templates) {\n const templatePath = path.resolve(moduleDirectory, `../${templateFileName}`);\n const templateContent = prepareTemplate(await readTextFile(templatePath));\n if (checkFileContent === templateContent) {\n console.info(`ℹ️ File '${checkFileName}' is the same as '${templateFileName}'`);\n return;\n }\n }\n\n console.info(`❌ File '${checkFileName}' is NOT the same`);\n}\n","// ── External Dependencies & Registrations\nimport path from 'node:path';\nimport type { RcOptions } from 'npm-check-updates';\nimport { run as runNpmCheckUpdates } from 'npm-check-updates';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Identifies outdated dependencies using npm outdated and npm-check-updates with option to automatically install\n * latest versions. */\nexport async function checkDependencies(): Promise<void> {\n try {\n logOperationHeader('Check Dependencies');\n\n await spawnCommand(\"1️⃣ Check using 'npm outdated'\", 'npm', ['outdated'], true);\n\n logStepHeader(\"2️⃣ Check using 'npm-check-updates'\");\n let rcOptions: RcOptions = {};\n try {\n rcOptions = await readJSONFile<RcOptions>(path.resolve(process.cwd(), '.ncurc.json'));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n await runNpmCheckUpdates({ interactive: true, upgrade: true, dep: 'dev,prod,peer,optional', install: 'never', ...rcOptions });\n\n // Not strict here, otherwise an upgraded package with a pinned approval fails the install before step 5 can move its pin.\n // No audit summary, as step 4 reports what is left once it has fixed what it can.\n await spawnCommand('3️⃣ Install updated dependencies', 'npm', ['install', '--prefer-online', '--no-strict-allow-scripts', '--no-audit', '--no-fund']);\n\n // Only upgrades the version ranges in package.json already allow; never '--force', which makes breaking ones. Runs before\n // the pins move in step 5, so a package it upgrades has its pin moved too. npm exits with an error while vulnerabilities\n // it cannot fix remain, such as those waiting on an upstream release, so that is reported without stopping the check.\n await spawnCommand('4️⃣ Fix vulnerabilities where a compatible upgrade exists', 'npm', ['audit', 'fix', '--no-strict-allow-scripts', '--no-fund'], true);\n\n // Only packages already approved are re-approved, so a newly added install script still waits for review in step 8.\n // Name-only approvals already cover every version, so only pinned ones need moving. Runs before prune, which would\n // otherwise delete a pin to an upgraded version as 'not installed' before it could be moved.\n const pinnedPackageNames = await getPinnedPackageNames();\n if (pinnedPackageNames.length > 0) {\n await spawnCommand('5️⃣ Move install-script pins to installed versions', 'npm', ['install-scripts', 'approve', ...pinnedPackageNames]);\n } else {\n logStepHeader('5️⃣ No pinned install-script approvals to move');\n }\n\n // Runs before the rebuild in step 7. A rebuild leaves npm's record of 'node_modules' out of date, and prune then misses\n // install scripts that 'npm install' still sees, as with 'fsevents' (npm 12.0.1). Also macOS only, as elsewhere it drops\n // entries for macOS-only packages that are not installed.\n if (process.platform === 'darwin') {\n await spawnCommand('6️⃣ Remove unused install-script entries', 'npm', ['install-scripts', 'prune']);\n } else {\n logStepHeader('6️⃣ Skipped removing unused install-script entries (macOS only)');\n }\n\n // Not strict, so any install script still awaiting review is reported once, by step 8.\n if (pinnedPackageNames.length > 0) {\n await spawnCommand('7️⃣ Run install scripts skipped in steps 3 and 4', 'npm', ['rebuild', ...pinnedPackageNames, '--no-strict-allow-scripts']);\n }\n\n // The same check a plain 'npm install' makes, which 'npm install-scripts ls' does not always agree with. Fails listing any\n // install scripts still awaiting review. Step 4 has already reported the audit.\n await spawnCommand('8️⃣ Confirm every install script is reviewed', 'npm', ['install', '--strict-allow-scripts', '--no-audit', '--no-fund']);\n\n logOperationSuccess('Dependencies checked');\n } catch (error) {\n console.error('❌ Error checking dependencies', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Keys are 'name', 'name@version' or '@scope/name@version'. An '@' after the first character marks a pin; it and the version\n// are dropped so npm matches every installed version.\nasync function getPinnedPackageNames(): Promise<string[]> {\n const { allowScripts = {} } = await readJSONFile<{ allowScripts?: Record<string, boolean> }>(path.resolve(process.cwd(), 'package.json'));\n const names = Object.entries(allowScripts)\n .filter(([key, isAllowed]) => isAllowed && key.lastIndexOf('@') > 0)\n .map(([key]) => key.slice(0, key.lastIndexOf('@')));\n return [...new Set(names)];\n}\n","// ── Local Framework\nimport { checkConfigFiles } from '@/actions/checkConfigFiles';\nimport { checkDependencies } from '@/actions/checkDependencies';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Checks the configuration files against the DPUse templates, then lists outdated dependencies. */\nexport async function checkProject(): Promise<void> {\n await checkConfigFiles();\n await checkDependencies();\n}\n","// ── DPUse Framework\nimport type { ConnectorActionName, ConnectorUsageId } from '@dpuse/dpuse-shared';\nimport { determineConnectorUsageId, getConnectorActionsTable } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, writeReadmeSection } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- CONNECTOR_ACTIONS_START -->';\nconst END_MARKER = '<!-- CONNECTOR_ACTIONS_END -->';\n\nconst CONNECTOR_ACTIONS_INTRO =\n 'Connectors conform to a unified interface contract by implementing a specific subset of standard actions. These standardised actions allow the DPUse application to interact with any underlying data source in the same way, enabling Connectors to be built independently and loaded dynamically at runtime.';\n\nconst CONNECTOR_USAGE_DESCRIPTIONS: Record<ConnectorUsageId, string> = {\n source: 'This connector is a Source connector that supports only read actions. Connectors can also function as a Destination (write-only) or Bidirectional (read/write), depending on the actions they support.',\n destination:\n 'This connector is a Destination connector that supports only write actions. Connectors can also function as a Source (read-only) or Bidirectional (read/write), depending on the actions they support.',\n bidirectional:\n 'This connector is a Bidirectional connector that supports both read and write actions. Connectors can also function as a Source (read-only) or Destination (write-only), depending on the actions they support.',\n unknown:\n 'This connector does not yet implement any read or write actions, so its type cannot be determined. Connectors function as a Source (read-only), a Destination (write-only), or Bidirectional (read/write), depending on the actions they support.'\n};\n\nconst CONNECTOR_ACTIONS_TABLE_LEAD_IN = 'The table below lists all connector actions and highlights those supported by this connector.';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentActions(): Promise<void> {\n try {\n logOperationHeader('Document Actions');\n\n logStepHeader(\"1️⃣ Insert actions description and table into 'README.md'\");\n\n const config = await readJSONFile<{ actionNames?: string[] }>('config.json');\n const actionNames = (config.actionNames ?? []) as ConnectorActionName[];\n const usageId = determineConnectorUsageId(actionNames);\n const table = getConnectorActionsTable(actionNames);\n\n const block = `${CONNECTOR_ACTIONS_INTRO}\\n\\n${CONNECTOR_USAGE_DESCRIPTIONS[usageId]} ${CONNECTOR_ACTIONS_TABLE_LEAD_IN}\\n\\n${table}`;\n\n await writeReadmeSection(block, START_MARKER, END_MARKER);\n\n logOperationSuccess('Actions documented');\n } catch (error) {\n console.error('❌ Error documenting actions', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\nimport {\n CONTRIBUTING_LICENSE_END_MARKER,\n CONTRIBUTING_LICENSE_START_MARKER,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n migrateGovernanceSection,\n readJSONFile,\n resolveOwnerAndRepo,\n writeReadmeSection\n} from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface LicenseModuleConfig {\n firstCreatedAt?: number | null;\n}\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Regenerates the README's Contributing and License sections. */\nexport async function documentContributingLicense(): Promise<void> {\n try {\n logOperationHeader('Document Contributing & License');\n\n const [packageJSON, configJSON] = await Promise.all([readJSONFile<PackageJson>('package.json'), readJSONFile<LicenseModuleConfig>('config.json')]);\n\n const { owner, repo } = resolveOwnerAndRepo(packageJSON, 'document contributing and license');\n const authorName = resolveAuthorName(packageJSON);\n const copyrightYear = resolveCopyrightYear(configJSON.firstCreatedAt);\n\n logStepHeader(\"1️⃣ Insert contributing and license content into 'README.md'\");\n\n await migrateGovernanceSection();\n await writeReadmeSection(buildContributingLicenseContent(owner, repo, authorName, copyrightYear), CONTRIBUTING_LICENSE_START_MARKER, CONTRIBUTING_LICENSE_END_MARKER);\n\n logOperationSuccess('Contributing & license documented');\n } catch (error) {\n console.error('❌ Error documenting contributing and license', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nfunction resolveAuthorName(packageJSON: PackageJson): string {\n const author = packageJSON.author;\n const authorString = typeof author === 'string' ? author : author?.name;\n if (authorString == null || authorString === '') throw new Error(\"package.json 'author' field is required to document contributing and license.\");\n\n // Drop the first '<email>' and the spaces around it, keeping one space between what came before and after it, as in\n // npm's 'Name <email> (url)' form. Not a regex, as '\\s*<' backtracks on long runs of spaces.\n const emailStart = authorString.indexOf('<');\n const emailEnd = emailStart === -1 ? -1 : authorString.indexOf('>', emailStart);\n return emailEnd === -1 ? authorString.trim() : [authorString.slice(0, emailStart).trim(), authorString.slice(emailEnd + 1).trim()].filter((part) => part !== '').join(' ');\n}\n\nfunction resolveCopyrightYear(firstCreatedAt: number | null | undefined): string {\n const currentYear = new Date().getFullYear();\n if (firstCreatedAt == null) return String(currentYear);\n\n const startYear = new Date(firstCreatedAt).getFullYear();\n return startYear === currentYear ? String(currentYear) : `${String(startYear)}-present`;\n}\n\nfunction buildContributingLicenseContent(owner: string, repo: string, authorName: string, copyrightYear: string): string {\n const repoURL = `https://github.com/${owner}/${repo}`;\n\n return `## Contributing\n\nThis repository is maintained solely by its owner and does not, at present, accept external contributions into the canonical repo. Its source is published openly under the MIT License — every DPUse project is fully open source except DPUse Engine, which remains closed and proprietary.\n\nFor security vulnerabilities, see [Reporting Vulnerabilities](#reporting-vulnerabilities). For bugs, inconsistencies, or other feedback, [open a GitHub issue](${repoURL}/issues) — feedback is read, but responses and fixes are at the maintainer's discretion.\n\n## License\n\nThis project is licensed under the MIT License, permitting free use, modification, and distribution.\n\n[MIT](./LICENSE) © ${copyrightYear} ${authorName}`;\n}\n","// ── External Dependencies & Registrations\nimport { init as initLicenseChecker } from 'license-checker-rseidelsohn';\nimport type { InitOpts } from 'license-checker-rseidelsohn';\n\n// ── Local Framework\nimport { clearDirectory, logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, readTextFileOrNull, spawnCommandToFile, writeReadmeSection } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface License {\n name: string;\n repository: string;\n licenseTypes: string;\n installedVersion: string;\n latestVersion: string;\n latestPublishedDate: string;\n author: string;\n publishedDate: string;\n licenseFileLink?: string;\n}\n\ninterface ProductionPackageLicense {\n licenses: string;\n repository?: string;\n publisher?: string;\n email?: string;\n path?: string;\n licenseFile?: string;\n}\n\ninterface PackageLock {\n packages?: Record<string, { name?: string; version?: string; dev?: boolean; devOptional?: boolean }>;\n}\n\ninterface NpmPackageTree {\n version?: string;\n dependencies?: Record<string, NpmPackageTree>;\n}\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- DEPENDENCY_LICENSES_START -->';\nconst END_MARKER = '<!-- DEPENDENCY_LICENSES_END -->';\nconst LICENSES_HEADING = '## Dependency Licenses';\n\nconst DEPENDENCY_TREE_INTRO =\n \"The dependency tree below lists every package in this project — direct and transitive — along with its installed version, release date, and update status. Packages flagged ❗ have a newer version available; ⚠️ indicates a package that hasn't been updated in the last 6 months or longer. Neither flag necessarily indicates a problem: we let new releases stabilise before upgrading, and some packages are mature and stable (have limited or no dependencies), so they require no active development.\";\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Identify licenses of the project's production and peer dependencies. Updates the table in the Dependency Licenses\n * section of this page and summary files licenses.json and licenseTree.json in th licenses directory of this\n * repository. Also downloads a copy of dependency license to `licenses/downloads'. */\nexport async function documentDependencies(allowedLicenses = 'MIT'): Promise<void> {\n try {\n logOperationHeader('Document Dependencies');\n\n const rootPackage = await readJSONFile<{ name?: string; version?: string }>('package.json');\n\n if (rootPackage.name === '@dpuse/dpuse-development' || rootPackage.name === '@dpuse/eslint-config-dpuse') {\n await skipDependencyDocumentation(rootPackage.name);\n logOperationSuccess('Dependencies documented');\n return;\n }\n\n await clearDirectory('1️⃣ Clear downloaded licenses', 'licenses/downloads');\n const unshippedPackages = await listUnshippedPackages();\n\n logStepHeader('2️⃣ Identify production licenses');\n await new Promise<void>((resolve, reject) => {\n const options: InitOpts & { files: string; relativeModulePath: boolean } = {\n start: process.cwd(),\n production: true,\n json: true,\n files: 'licenses/downloads',\n relativeModulePath: true,\n relativeLicensePath: true,\n onlyAllow: allowedLicenses,\n excludePackages: [rootPackage.name ?? '', ...unshippedPackages].join(';'),\n out: 'licenses/licenses.json'\n };\n initLicenseChecker(options, (error: Error | undefined) => {\n if (error == null) {\n resolve();\n } else {\n reject(error);\n }\n });\n });\n\n await spawnCommandToFile('3️⃣ Identify transitive dependencies', 'npm', ['ls', '--all', '--json', '--omit=dev'], 'licenses/licenseTree.json');\n\n await insertLicensesIntoReadme('4️⃣ ', allowedLicenses, new Set(unshippedPackages));\n\n logOperationSuccess('Dependencies documented');\n } catch (error) {\n console.error('❌ Error documenting dependencies', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nasync function skipDependencyDocumentation(name: string): Promise<void> {\n logStepHeader(`1️⃣ Skip: ${name} is a development-only tool and is never part of a production release.`);\n\n const message = `> [!WARNING]\\n> Dependency licenses are not documented here: ${name} is a development-only tool and is never part of a production release.`;\n\n await writeReadmeSection(`${LICENSES_HEADING}\\n\\n${message}`, START_MARKER, END_MARKER);\n}\n\nasync function insertLicensesIntoReadme(stepIcon: string, allowedLicenses: string, unshippedPackages: Set<string>): Promise<void> {\n logStepHeader(`${stepIcon} Insert licenses into 'README.md'`);\n\n const [licenses, licenseTree] = await Promise.all([\n readJSONFile<Record<string, ProductionPackageLicense>>('licenses/licenses.json'),\n readJSONFile<NpmPackageTree>('licenses/licenseTree.json')\n ]);\n\n const licensesByKey = new Map<string, License>();\n for (const [key, value] of Object.entries(licenses)) {\n licensesByKey.set(key, parseLicenseEntry(key, value));\n }\n\n await Promise.all(\n licensesByKey.values().map(async (license) => {\n const data = await fetchNpmData(license.name, license.installedVersion);\n license.latestVersion = data.latestVersion;\n license.latestPublishedDate = data.latestPublishedDate;\n license.publishedDate = data.publishedDate;\n })\n );\n\n const licensesIntro = buildLicensesIntro(allowedLicenses);\n let licensesContent = `${licensesIntro}\\n\\n|Dependency|Version|License(s)|Document|\\n|:-|:-:|:-|:-|\\n`;\n for (const license of licensesByKey.values()) {\n licensesContent += formatLicenseRow(license);\n }\n\n const treeItems: string[] = [];\n if (licenseTree.dependencies != null) {\n walkTreeList(licenseTree.dependencies, licensesByKey, unshippedPackages, treeItems, 0);\n }\n const treeContent = `${DEPENDENCY_TREE_INTRO}\\n\\n${treeItems.join('\\n')}`;\n\n await writeReadmeSection(`${LICENSES_HEADING}\\n\\n${licensesContent.trimEnd()}\\n\\n### Dependency Tree\\n\\n${treeContent}`, START_MARKER, END_MARKER);\n}\n\n// Packages installed but never shipped, as 'name@version'. npm's lock file marks these 'dev' or 'devOptional', the latter\n// for a package needed only by development or as an optional extra, such as TypeScript as valibot's optional peer. The\n// licence checker follows optional peer links, so without this it would count such a package as a production one. A\n// package installed at the same version for a shipped reason as well is kept.\nasync function listUnshippedPackages(): Promise<string[]> {\n const lockText = await readTextFileOrNull('package-lock.json');\n const packages = lockText === null ? {} : ((JSON.parse(lockText) as PackageLock).packages ?? {});\n const shipped = new Set<string>();\n const unshipped = new Set<string>();\n for (const [lockPath, entry] of Object.entries(packages)) {\n if (lockPath === '' || entry.version === undefined) continue;\n const name = entry.name ?? lockPath.slice(lockPath.lastIndexOf('node_modules/') + 'node_modules/'.length);\n const packageKey = `${name}@${entry.version}`;\n if (entry.dev === true || entry.devOptional === true) unshipped.add(packageKey);\n else shipped.add(packageKey);\n }\n return unshipped.values().filter((packageKey) => !shipped.has(packageKey)).toArray();\n}\n\nfunction buildLicensesIntro(allowedLicenses: string): string {\n const licenseListText = formatLicenseListText(allowedLicenses.split(';'));\n return `License data is updated each time \\`npm run document\\` is run, using [license-checker](https://github.com/RSeidelsohn/license-checker-rseidelsohn). The following table lists all production dependencies. These dependencies (including transitive ones) have been checked and confirmed to use ${licenseListText} — all permissive, commercially-friendly licenses. Users of the uploaded library are covered by these checks; developers cloning this repository should independently verify development dependencies.`;\n}\n\nfunction formatLicenseListText(licenses: string[]): string {\n if (licenses.length === 1) return licenses[0] ?? '';\n return licenses.length === 2 ? `${String(licenses[0])} or ${String(licenses[1])}` : `${licenses.slice(0, -1).join(', ')}, or ${String(licenses.at(-1))}`;\n}\n\nfunction parseLicenseEntry(key: string, value: ProductionPackageLicense): License {\n const lastAt = key.lastIndexOf('@');\n const name = lastAt > 0 ? key.slice(0, lastAt) : key;\n const installedVersion = lastAt > 0 ? key.slice(lastAt + 1) : '';\n return {\n name,\n repository: value.repository ?? `https://www.npmjs.com/package/${name}`,\n licenseTypes: value.licenses,\n installedVersion,\n author: value.publisher ?? '',\n latestVersion: '',\n latestPublishedDate: '',\n publishedDate: '',\n ...(value.licenseFile != null && { licenseFileLink: value.licenseFile })\n };\n}\n\nasync function fetchNpmData(name: string, version: string): Promise<{ latestVersion: string; latestPublishedDate: string; publishedDate: string }> {\n try {\n const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(name)}`);\n if (response.ok) {\n const data = (await response.json()) as { 'dist-tags'?: Record<string, string>; time?: Record<string, string> };\n const distributionTags = new Map(Object.entries(data['dist-tags'] ?? {}));\n const timeMap = new Map(Object.entries(data.time ?? {}));\n const latestVersion = distributionTags.get('latest') ?? '';\n const publishedDate = timeMap.get(version) ?? '';\n const latestPublishedDate = latestVersion === version ? '' : (timeMap.get(latestVersion) ?? '');\n return { latestVersion, latestPublishedDate, publishedDate };\n }\n } catch {\n // Ignore network errors.\n }\n return { latestVersion: '', latestPublishedDate: '', publishedDate: '' };\n}\n\nfunction formatLicenseRow(license: License): string {\n const licenseLink = license.licenseFileLink == null || license.licenseFileLink === '' ? '⚠️ No license file' : `[LICENSE](licenses/${license.licenseFileLink})`;\n return `|[${license.name}](${license.repository})|${license.installedVersion}|${license.licenseTypes}|${licenseLink}|\\n`;\n}\n\nfunction walkTreeList(dependencies: Record<string, NpmPackageTree>, licensesByKey: Map<string, License>, unshippedPackages: Set<string>, items: string[], depth: number): void {\n const indent = ' '.repeat(depth);\n for (const [name, node] of Object.entries(dependencies)) {\n const version = node.version ?? '';\n if (unshippedPackages.has(`${name}@${version}`)) continue;\n const license = licensesByKey.get(`${name}@${version}`);\n const nameLink = license == null ? name : `[${name}](${license.repository})`;\n const versionDetail = formatVersionDetail(license);\n items.push(`${indent}- **${nameLink}** ${version}${versionDetail}`);\n if (node.dependencies != null) {\n walkTreeList(node.dependencies, licensesByKey, unshippedPackages, items, depth + 1);\n }\n }\n}\n\nfunction formatVersionDetail(license: License | undefined): string {\n if (license == null) return '';\n const published = license.publishedDate ? determineLatestAge(license.publishedDate.split('T', 1)[0]) : '';\n const isOutdated = license.latestVersion !== '' && license.latestVersion !== license.installedVersion;\n if (!isOutdated) return published === '' ? '' : ` — ${published}`;\n const latestAge = license.latestPublishedDate ? determineLatestAge(license.latestPublishedDate.split('T', 1)[0]) : '';\n const latestClause = latestAge === '' ? `**latest**: ${license.latestVersion} ❗` : `**latest**: ${license.latestVersion} — ${latestAge} ❗`;\n return published === '' ? ` — → ${latestClause}` : ` — ${published} → ${latestClause}`;\n}\n\nfunction determineLatestAge(momentString?: string): string {\n if (momentString == null || momentString === '') return 'n/a';\n\n const dateString = momentString.split('T', 1)[0];\n if (dateString == null || dateString === '') return 'n/a';\n\n const input = new Date(dateString);\n const now = new Date();\n let months = (now.getFullYear() - input.getFullYear()) * 12 + (now.getMonth() - input.getMonth());\n if (now.getDate() < input.getDate()) months -= 1;\n\n if (months === 0) return `this month: ${dateString}`;\n if (months === 1) return `**1 month** ago: ${dateString}`;\n return months <= 6 ? `**${String(months)} months** ago: ${dateString}` : `**${String(months)} months** ago: ${dateString} ⚠️`;\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { getModuleConfig, logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, resolveOwnerAndRepo, writeReadmeSection } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- OPENING_START -->';\nconst END_MARKER = '<!-- OPENING_END -->';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentOpening(): Promise<void> {\n try {\n logOperationHeader('Document Opening');\n\n logStepHeader(\"1️⃣ Insert opening content into 'README.md'\");\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n\n const { owner, repo } = resolveOwnerAndRepo(packageJSON, 'document opening');\n const license = resolveLicense(packageJSON);\n const introduction = resolveIntroduction(configJSON);\n const npmPackageName = getModuleConfig(configJSON.id).publishedTo === 'npm' ? resolvePackageName(packageJSON) : undefined;\n\n const content = buildOpeningContent(owner, repo, license, npmPackageName, packageJSON.description, introduction);\n\n await writeReadmeSection(content, START_MARKER, END_MARKER);\n\n logOperationSuccess('Opening documented');\n } catch (error) {\n console.error('❌ Error documenting opening', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nfunction resolveLicense(packageJSON: PackageJson): string {\n const license = packageJSON.license;\n if (license == null || license === '') throw new Error(\"package.json 'license' field is required to document opening.\");\n return license;\n}\n\nfunction resolvePackageName(packageJSON: PackageJson): string {\n const name = packageJSON.name;\n if (name == null || name === '') throw new Error(\"package.json 'name' field is required to document opening.\");\n return name;\n}\n\n// 'description.en' holds the introduction as one string, with a blank line between paragraphs. With none, the\n// Introduction section is left out.\nfunction resolveIntroduction(configJSON: ModuleConfig): string | undefined {\n const introduction = configJSON.description.en?.trim();\n return introduction === undefined || introduction === '' ? undefined : introduction;\n}\n\n// The package description is optional, so a project without one simply has no summary under the links. Only projects\n// published to npm get the npm badge; the rest reach people through DPUse itself.\nfunction buildOpeningContent(\n owner: string,\n repo: string,\n license: string,\n npmPackageName: string | undefined,\n description: string | undefined,\n introduction: string | undefined\n): string {\n const repoURL = `https://github.com/${owner}/${repo}`;\n const badgeLicense = license.replaceAll('-', '--');\n const npmBadge =\n npmPackageName === undefined\n ? ''\n : `\\n[](https://www.npmjs.com/package/${npmPackageName})`;\n const summary = description == null || description === '' ? '' : `\\n\\n${description}`;\n const introductionSection = introduction === undefined ? '' : `\\n\\n## Introduction\\n\\n${introduction}`;\n\n return `[](./LICENSE)\n[](${repoURL}/releases/latest)${npmBadge}\n[](${repoURL}/actions/workflows/ci.yml)\n\n[DPUse](https://www.dpuse.app) · [Report a Vulnerability](${repoURL}/security/advisories/new) · [Open an Issue](${repoURL}/issues)${summary}\n\n## About DPUse\n\nDPUse (Data Positioning & Use) is an in-browser application that positions your data for use through three core activities: sourcing, contextualising, and publishing.\n\n**Sourcing** uses a library of [Connectors](https://www.dpuse.app/connectors) to establish [Connections](https://www.dpuse.app) to applications, databases, file stores, and curated datasets; these connections are subsequently used to configure structured [Data Views](https://www.dpuse.app) from the underlying sources.\n\n**Contextualising** extracts chronological events from those [Data Views](https://www.dpuse.app) and maps them into comprehensive [Context Models](https://www.dpuse.app). This gives the DPUse Engine the structural framework needed to generate deterministic transactions, facts, or observations.\n\n**Publishing** uses a library of [Presenters](https://www.dpuse.app) to render standard [Presentations](https://www.dpuse.app) immediately using the contextualised data; additionally, [Cookbooks](https://www.dpuse.app) of [Recipes](https://www.dpuse.app) let you build Data Apps using your preferred tools.\n\nIn addition, DPUse provides [Tools](https://www.dpuse.app) used by the application, and you can use them to construct connectors and presenters.${introductionSection}`;\n}\n","// ── External Dependencies & Registrations\nimport { execFile } from 'node:child_process';\nimport type { PackageJson } from 'type-fest';\nimport { promisify } from 'node:util';\n\n// ── Local Framework\nimport {\n FALLOW_BADGE_PATH,\n FALLOW_DIRECTORY,\n FALLOW_REPORT_PATH,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n migrateGovernanceSection,\n QUALITY_SECURITY_END_MARKER,\n QUALITY_SECURITY_START_MARKER,\n readJSONFile,\n readTextFileOrNull,\n resolveOwnerAndRepo,\n RUST_WORKSPACE_PATH,\n spawnCommand,\n spawnCommandToFile,\n writeJSONFile,\n writeReadmeSection\n} from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface BestPracticesProject {\n id: number;\n repo_url: string;\n}\n\ninterface CoverageSummary {\n total: { lines: { pct: number } };\n}\n\ninterface FallowHealth {\n health_score: { score: number; grade: string };\n}\n\ninterface GitHubCheckRuns {\n check_runs: { app: { slug: string } | null }[];\n}\n\ninterface GitHubRepoDetails {\n security_and_analysis?: Record<string, { status: string } | undefined>;\n}\n\ninterface ScorecardResult {\n checks: { name: string; score: number }[];\n}\n\n// Everything the checks tables report on, gathered before the README is written.\ninterface ChecksResults {\n coveragePercent: number | undefined;\n fallowHealth: FallowHealth | undefined;\n securitySettings: SecuritySettings;\n}\n\n// On or off, or undefined where GitHub doesn't reveal the setting (some need an admin login to read).\ntype SettingStatus = boolean | undefined;\n\ninterface SecuritySettings {\n codeQLLanguages: string[];\n codeQLQueries: string | undefined; // The query suite CodeQL is told to run; without one, it runs its default suite.\n dependabotAlerts: SettingStatus;\n dependabotSecurityUpdates: SettingStatus;\n dependabotVersionUpdates: boolean;\n lintInCI: boolean;\n npmAuditInCI: boolean;\n npmAuditLevel: string | undefined; // The '--audit-level' CI passes; without one, npm audit fails on any severity.\n privateVulnerabilityReporting: SettingStatus;\n propertyTests: boolean;\n pushProtection: SettingStatus;\n secretScanning: SettingStatus;\n socket: boolean;\n sonarCloud: boolean;\n testsInCI: boolean;\n}\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Scorecard checks a solo maintainer pushing straight to 'main' can't raise, with the best score each can reach that way.\nconst SCORECARD_PRACTICE_LIMITS: Record<string, number> = { 'Branch-Protection': 3, 'Code-Review': 0, Contributors: 0 };\n// Left out when deciding whether gaps remain: the Best Practices badge shows its own progress in the same section.\nconst SCORECARD_IGNORED_CHECKS = new Set(['CII-Best-Practices']);\n\n// Coverage — only measured where the module has the Vitest coverage provider installed. 'coverage-final.json' feeds\n// Fallow's per-function scores; the summary holds the totals the Testing table reports.\nconst COVERAGE_FINAL_PATH = 'coverage/coverage-final.json';\nconst COVERAGE_SUMMARY_PATH = 'coverage/coverage-summary.json';\nconst COVERAGE_TARGET_PERCENT = 80;\nconst COVERAGE_WARNING_PERCENT = 60; // Below the target the badge turns yellow, and below this it turns red.\nconst COVERAGE_BADGE_PATH = 'code-health-reports/vitest/badge.json'; // Not under a 'coverage' folder, which '.gitignore' leaves out.\n\nconst CODEQL_LANGUAGE_NAMES: Record<string, string> = { actions: 'GitHub Actions', 'javascript-typescript': 'JavaScript/TypeScript', rust: 'Rust' };\n\n// Fallow — only run where the module has it installed. The full report is published as its own page, linked from the\n// README; the Code Quality row and the badge are both built from the one health run, so they always agree.\nconst FALLOW_GRADE_COLOURS: Record<string, string> = { A: 'brightgreen', B: 'green', C: 'yellow', D: 'orange', F: 'red' };\nconst FALLOW_HEALTH_PATH = `${FALLOW_DIRECTORY}/health.json`;\n\n// ── Initialisation ───────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst asyncExecFile = promisify(execFile);\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Regenerates the README's Quality & Security section: testing, code quality, security analysis, dependencies and OpenSSF. */\nexport async function documentQualitySecurity(): Promise<void> {\n try {\n logOperationHeader('Document Quality & Security');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n\n const coveragePercent = await measureTestCoverage(packageJSON);\n const fallowHealth = await measureCodeHealth(packageJSON, coveragePercent === undefined ? [] : ['--coverage', COVERAGE_FINAL_PATH]);\n\n const { owner, repo } = resolveOwnerAndRepo(packageJSON, 'document quality and security');\n\n logStepHeader('4️⃣ Read security checks and settings');\n const securitySettings = await readSecuritySettings(owner, repo, packageJSON);\n\n logStepHeader('5️⃣ Look up OpenSSF Best Practices badge and Scorecard results');\n const [bestPracticesProjectId, scorecardResult] = await Promise.all([\n lookUpBestPracticesProjectId(`https://github.com/${owner}/${repo}`),\n lookUpScorecardResult(`github.com/${owner}/${repo}`)\n ]);\n\n logStepHeader(\"6️⃣ Insert quality and security content into 'README.md'\");\n const content = buildQualitySecurityContent(owner, repo, { coveragePercent, fallowHealth, securitySettings }, bestPracticesProjectId, scorecardResult);\n\n await migrateGovernanceSection();\n await writeReadmeSection(content, QUALITY_SECURITY_START_MARKER, QUALITY_SECURITY_END_MARKER);\n\n logOperationSuccess('Quality & security documented');\n } catch (error) {\n console.error('❌ Error documenting quality and security', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Answers undefined where the coverage provider isn't installed, or the Vitest config doesn't write a coverage summary.\nasync function measureTestCoverage(packageJSON: PackageJson): Promise<number | undefined> {\n if (packageJSON.devDependencies?.['@vitest/coverage-v8'] == null) {\n logStepHeader(\"1️⃣ Test coverage NOT measured, as '@vitest/coverage-v8' is not installed\");\n return undefined;\n }\n\n await spawnCommand('1️⃣ Measure test coverage', 'vitest', ['run', '--passWithNoTests', '--coverage']);\n const summary = await readTextFileOrNull(COVERAGE_SUMMARY_PATH);\n if (summary === null) return undefined;\n\n const coveragePercent = (JSON.parse(summary) as CoverageSummary).total.lines.pct;\n await writeCoverageBadge(coveragePercent);\n return coveragePercent;\n}\n\n// Written in the shields.io endpoint format, like the Fallow badge, so the README shows the latest pushed figure.\nasync function writeCoverageBadge(coveragePercent: number): Promise<void> {\n const colourNames = ['red', 'yellow', 'brightgreen'];\n const level = Number(coveragePercent >= COVERAGE_WARNING_PERCENT) + Number(coveragePercent >= COVERAGE_TARGET_PERCENT);\n await writeJSONFile(COVERAGE_BADGE_PATH, { schemaVersion: 1, label: 'coverage', message: `${coveragePercent.toFixed(1)}%`, color: colourNames[level] });\n}\n\n// Fallow exits non-zero whenever it has findings, so its exit code is ignored: the findings are what gets reported.\nasync function measureCodeHealth(packageJSON: PackageJson, coverageArguments: string[]): Promise<FallowHealth | undefined> {\n if (packageJSON.devDependencies?.['fallow'] == null) {\n logStepHeader('2️⃣ Code health NOT measured, as Fallow is not installed');\n logStepHeader('3️⃣ Code health report NOT required');\n return undefined;\n }\n\n await spawnCommandToFile('2️⃣ Measure code health', 'fallow', ['health', '--report-only', '--format', 'json', ...coverageArguments], FALLOW_HEALTH_PATH);\n await spawnCommandToFile('3️⃣ Write code health report', 'fallow', ['--format', 'markdown'], FALLOW_REPORT_PATH, true);\n const health = await readJSONFile<FallowHealth>(FALLOW_HEALTH_PATH);\n await writeFallowBadge(health);\n return health;\n}\n\n// Written in the shields.io endpoint format, so the Code Quality badge shows the latest pushed grade.\nasync function writeFallowBadge(health: FallowHealth): Promise<void> {\n const { score, grade } = health.health_score;\n await writeJSONFile(FALLOW_BADGE_PATH, {\n schemaVersion: 1,\n label: 'fallow',\n message: `${grade} (${String(Math.round(score))})`,\n color: FALLOW_GRADE_COLOURS[grade] ?? 'lightgrey'\n });\n}\n\n// Read from the repository itself each time, so the README states what is actually switched on rather than what was\n// intended. Workflow and Dependabot files are read locally; repository settings come from the GitHub API through 'gh'.\nasync function readSecuritySettings(owner: string, repo: string, packageJSON: PackageJson): Promise<SecuritySettings> {\n const [ciWorkflow, codeQLWorkflow, dependabotConfig, rustWorkspace] = await Promise.all([\n readTextFileOrNull('.github/workflows/ci.yml'),\n readTextFileOrNull('.github/workflows/codeql.yml'),\n readTextFileOrNull('.github/dependabot.yml'),\n readTextFileOrNull(RUST_WORKSPACE_PATH)\n ]);\n const [repoDetails, privateVulnerabilityReporting, vulnerabilityAlerts, checkRuns] = await Promise.all([\n readGitHubAPI(`repos/${owner}/${repo}`),\n readGitHubAPI(`repos/${owner}/${repo}/private-vulnerability-reporting`),\n readGitHubAPI(`repos/${owner}/${repo}/vulnerability-alerts`),\n readGitHubAPI(`repos/${owner}/${repo}/commits/main/check-runs?per_page=100`)\n ]);\n\n const securityAndAnalysis = repoDetails === undefined ? undefined : (JSON.parse(repoDetails) as GitHubRepoDetails).security_and_analysis;\n const readSetting = (name: string): SettingStatus => (securityAndAnalysis?.[name] === undefined ? undefined : securityAndAnalysis[name].status === 'enabled');\n const checkAppSlugs = new Set((checkRuns === undefined ? [] : (JSON.parse(checkRuns) as GitHubCheckRuns).check_runs).map((checkRun) => checkRun.app?.slug));\n\n // Version updates count as off when every ecosystem is limited to 0 pull requests, the documented way to pause them.\n const ecosystemCount = dependabotConfig?.match(/package-ecosystem:/g)?.length ?? 0;\n const pausedEcosystemCount = dependabotConfig?.match(/open-pull-requests-limit: 0\\b/g)?.length ?? 0;\n\n return {\n codeQLLanguages: (codeQLWorkflow ?? '')\n .matchAll(/- language: ([\\w-]+)/g)\n .filter(([, language]) => language !== 'rust' || rustWorkspace !== null) // The workflow lists Rust for every project, but skips its scan where there is none.\n .map(([, language = '']) => CODEQL_LANGUAGE_NAMES[language] ?? language)\n .toArray(),\n codeQLQueries: /queries: ([\\w-]+)/.exec(codeQLWorkflow ?? '')?.[1],\n dependabotAlerts: vulnerabilityAlerts !== undefined, // Answers '204 No Content' when on and '404' when off.\n dependabotSecurityUpdates: readSetting('dependabot_security_updates'),\n dependabotVersionUpdates: ecosystemCount > pausedEcosystemCount,\n lintInCI: (ciWorkflow ?? '').includes('npm run lint'),\n npmAuditInCI: /npm (?:run )?audit/.test(ciWorkflow ?? ''),\n npmAuditLevel: /npm audit --audit-level=(\\w+)/.exec(ciWorkflow ?? '')?.[1],\n privateVulnerabilityReporting: privateVulnerabilityReporting === undefined ? undefined : (JSON.parse(privateVulnerabilityReporting) as { enabled: boolean }).enabled,\n propertyTests: packageJSON.devDependencies?.['fast-check'] != null,\n pushProtection: readSetting('secret_scanning_push_protection'),\n secretScanning: readSetting('secret_scanning'),\n socket: checkAppSlugs.has('socket-security'),\n sonarCloud: checkAppSlugs.has('sonarqubecloud'),\n testsInCI: ciWorkflow?.includes('npm test') ?? false\n };\n}\n\n// Answers undefined for a 404, which is how some endpoints report a switched-off feature. Any other failure throws, so a\n// missing login or network blip can't be written into the README as settings being off.\nasync function readGitHubAPI(endpoint: string): Promise<string | undefined> {\n try {\n const { stdout } = await asyncExecFile('gh', ['api', endpoint]);\n return stdout;\n } catch (error) {\n if (String((error as { stderr?: unknown }).stderr).includes('HTTP 404')) return undefined;\n throw error;\n }\n}\n\n// Found by repository URL, as OpenSSF Scorecard does, so a repo shows its badge as soon as it is registered and nothing\n// needs configuring. Failures throw rather than return nothing, so a network blip can't drop the badge from the README.\nasync function lookUpBestPracticesProjectId(repoURL: string): Promise<number | undefined> {\n const response = await fetch(`https://www.bestpractices.dev/projects.json?url=${encodeURIComponent(repoURL)}`);\n if (!response.ok) throw new Error(`OpenSSF Best Practices lookup failed with status ${String(response.status)}.`);\n\n // The search also matches home page URLs, so keep only the entry registered for this repository.\n const projects = (await response.json()) as BestPracticesProject[];\n return projects.find((project) => project.repo_url === repoURL)?.id;\n}\n\n// Answers undefined when Scorecard has no results for the repository yet. Other failures throw, as for the badge.\nasync function lookUpScorecardResult(scorecardURI: string): Promise<ScorecardResult | undefined> {\n const response = await fetch(`https://api.scorecard.dev/projects/${scorecardURI}`);\n if (response.status === 404) return undefined;\n if (!response.ok) throw new Error(`OpenSSF Scorecard lookup failed with status ${String(response.status)}.`);\n return (await response.json()) as ScorecardResult;\n}\n\n// True when every check short of 10 is one the way the project is run caps. A score of -1 means Scorecard couldn't assess\n// the check (e.g. Signed-Releases without release assets), so it isn't counted as a gap.\nfunction isScorecardOnlyPracticeLimited(result: ScorecardResult): boolean {\n return result.checks.every(\n ({ name, score }) =>\n score === -1 || score === 10 || SCORECARD_IGNORED_CHECKS.has(name) || (SCORECARD_PRACTICE_LIMITS[name] !== undefined && score >= SCORECARD_PRACTICE_LIMITS[name])\n );\n}\n\n// Where Dependabot's pull requests are switched off, dependency updates are made by hand.\nfunction formatManualNote(status: SettingStatus): string {\n return status === false ? ' These are handled manually.' : '';\n}\n\nfunction formatStatus(status: SettingStatus): string {\n if (status === undefined) return '❔ Unknown';\n return status ? '✅ On' : '❌ Off';\n}\n\nfunction buildTableContent(heading: string, rows: string[][]): string {\n if (rows.length === 0) return '';\n return `### ${heading}\n\n|Check|Status|What it does|\n|:-|:-|:-|\n${rows.map((row) => `|${row.join('|')}|`).join('\\n')}\n\n`;\n}\n\n// A badge that shields.io draws from a JSON file this action commits, so it shows the latest pushed figure.\nfunction formatEndpointBadge(owner: string, repo: string, label: string, badgePath: string): string {\n const badgeSourceURL = encodeURIComponent(`https://raw.githubusercontent.com/${owner}/${repo}/main/${badgePath}`);\n return ``;\n}\n\n// Grouped by what each check protects against, and within a group in the order the checks act on a change: before a\n// push, on every push, then continuously, and alphabetically within each. Status is only ever on, off or unknown. What\n// it does opens with the check's badge where it has one, shown only while the check is on so a badge is never broken,\n// and names and links the product doing the check.\nfunction buildChecksContent(owner: string, repo: string, { coveragePercent, fallowHealth, securitySettings: settings }: ChecksResults): string {\n const repoURL = `https://github.com/${owner}/${repo}`;\n\n const ciNote = (isInCI: boolean): string => (isInCI ? ` Part of the [CI workflow](${repoURL}/actions/workflows/ci.yml) on every push and pull request to \\`main\\`.` : '');\n\n const testingRows = [\n ['Unit tests', formatStatus(settings.testsInCI), `[Vitest](https://vitest.dev) runs the unit tests.${ciNote(settings.testsInCI)}`],\n [\n 'Property-based tests',\n formatStatus(settings.propertyTests),\n `[fast-check](https://fast-check.dev) runs many random inputs per test to find edge cases, alongside the unit tests.${ciNote(settings.propertyTests && settings.testsInCI)}`\n ]\n ];\n if (coveragePercent !== undefined) {\n testingRows.push([\n 'Test coverage',\n formatStatus(true),\n `${formatEndpointBadge(owner, repo, 'Coverage', COVERAGE_BADGE_PATH)} [Vitest's V8 coverage](https://vitest.dev/guide/coverage) measures the share of source lines the unit tests run. The target is ${String(COVERAGE_TARGET_PERCENT)}%.`\n ]);\n }\n\n const sonarCloudBadge = `[](https://sonarcloud.io/summary/new_code?id=${owner}_${repo}) `;\n const codeQualityRows = [\n [\n 'Code analysis',\n formatStatus(settings.sonarCloud),\n `${settings.sonarCloud ? sonarCloudBadge : ''}[SonarCloud](https://sonarcloud.io) checks every push for bugs, code smells and vulnerabilities.`\n ],\n ['Linting', formatStatus(settings.lintInCI), `[ESLint](https://eslint.org) checks the code for errors and style problems.${ciNote(settings.lintInCI)}`]\n ];\n // Measured when the README is regenerated, before the changes are pushed, so it comes first.\n if (fallowHealth !== undefined) {\n codeQualityRows.unshift([\n 'Code health',\n formatStatus(true),\n `[${formatEndpointBadge(owner, repo, 'Fallow code health', FALLOW_BADGE_PATH)}](./${FALLOW_REPORT_PATH}) [Fallow](https://github.com/fallow-rs/fallow) finds unused code, duplication, complexity and dependency problems.`\n ]);\n }\n\n const hasCodeQL = settings.codeQLLanguages.length > 0;\n const codeQLBadge = `[](${repoURL}/security/code-scanning) `;\n const codeQLScope = settings.codeQLQueries === 'security-extended' ? 'using the extended security queries' : 'using the default queries';\n const codeQLLanguages = hasCodeQL ? ` ${settings.codeQLLanguages.join(' and ')}` : '';\n const securityAnalysisRows = [\n [\n 'Push protection',\n formatStatus(settings.pushProtection),\n '[GitHub push protection](https://docs.github.com/en/code-security/secret-scanning/push-protection-for-repositories-and-organizations) blocks pushes that contain credentials.'\n ],\n [\n 'Static analysis',\n formatStatus(hasCodeQL),\n `${hasCodeQL ? codeQLBadge : ''}[CodeQL](https://codeql.github.com) scans${codeQLLanguages} for security vulnerabilities, ${codeQLScope}, on every push and pull request to \\`main\\` and weekly.`\n ],\n [\n 'Secret scanning',\n formatStatus(settings.secretScanning),\n '[GitHub secret scanning](https://docs.github.com/en/code-security/secret-scanning) detects credentials, such as API keys and tokens, committed to the repository.'\n ]\n ];\n\n const dependabotLink = '[Dependabot](https://docs.github.com/en/code-security/dependabot)';\n const dependencyRows = [\n [\n 'Vulnerability audit',\n formatStatus(settings.npmAuditInCI),\n settings.npmAuditLevel === undefined\n ? `[npm audit](https://docs.npmjs.com/cli/commands/npm-audit) fails when a shipped dependency has any known vulnerability, or a development dependency has a high or critical one.${ciNote(settings.npmAuditInCI)}`\n : `[npm audit](https://docs.npmjs.com/cli/commands/npm-audit) fails when a dependency has a known vulnerability of ${settings.npmAuditLevel} severity or above.${ciNote(settings.npmAuditInCI)}`\n ],\n [\n 'Supply chain risk',\n formatStatus(settings.socket), // Socket's badge service refuses requests from outside a browser, so GitHub couldn't show it.\n '[Socket](https://socket.dev) flags malicious packages, typosquatting and suspicious behaviour that may not yet have a CVE.'\n ],\n ['Security alerts', formatStatus(settings.dependabotAlerts), `${dependabotLink} alerts when a dependency has a known vulnerability, using the GitHub Advisory Database.`],\n [\n 'Security updates',\n formatStatus(settings.dependabotSecurityUpdates),\n `${dependabotLink} opens pull requests that update vulnerable dependencies.${formatManualNote(settings.dependabotSecurityUpdates)}`\n ],\n [\n 'Version updates',\n formatStatus(settings.dependabotVersionUpdates),\n `${dependabotLink} opens pull requests for new dependency versions.${formatManualNote(settings.dependabotVersionUpdates)}`\n ]\n ];\n\n return `This section is updated each time \\`npm run document\\` is run. Settings come from the repository's workflow files and GitHub. Test coverage and the Fallow score are measured at the same time.\n\n${buildTableContent('Testing', testingRows)}${buildTableContent('Code Quality', codeQualityRows)}${buildTableContent('Security Analysis', securityAnalysisRows)}${buildTableContent('Dependencies', dependencyRows)}`;\n}\n\nfunction buildQualitySecurityContent(\n owner: string,\n repo: string,\n checksResults: ChecksResults,\n bestPracticesProjectId: number | undefined,\n scorecardResult: ScorecardResult | undefined\n): string {\n const repoURL = `https://github.com/${owner}/${repo}`;\n const scorecardURI = `github.com/${owner}/${repo}`;\n const bestPracticesURL = `https://www.bestpractices.dev/projects/${String(bestPracticesProjectId)}`;\n const scorecardLimitText =\n scorecardResult !== undefined && isScorecardOnlyPracticeLimited(scorecardResult)\n ? \"\\n\\n> [!NOTE]\\n> Apart from the Best Practices badge above, the remaining Scorecard gaps need multi-person review or a pull-request workflow, which this solo-maintained project doesn't use.\"\n : '';\n const bestPracticesBadge = bestPracticesProjectId === undefined ? '' : `[](${bestPracticesURL})\\n`;\n\n // Without private reporting switched on, the advisory link leads nowhere, so point only at SECURITY.md.\n const reportingText =\n checksResults.securitySettings.privateVulnerabilityReporting === true\n ? `Use [GitHub private vulnerability reporting](${repoURL}/security/advisories/new) instead. See [SECURITY.md](./SECURITY.md) for the full disclosure policy, contact details, and expected response times.`\n : 'See [SECURITY.md](./SECURITY.md) for how to report one privately, the full disclosure policy, and expected response times.';\n\n return `## Quality & Security\n\n${buildChecksContent(owner, repo, checksResults)}### OpenSSF 🚧\n\n${bestPracticesBadge}[](https://scorecard.dev/viewer/?uri=${scorecardURI})\n\nThis project is working towards the [OpenSSF Best Practices](https://www.bestpractices.dev) Passing badge, a self-certification covering security policy, vulnerability reporting, build processes, code quality, and more. Currently the [OpenSSF Scorecard](https://scorecard.dev) provides an independent automated assessment of the project's security practices and is an ongoing area of improvement.${scorecardLimitText}\n\n### Reporting Vulnerabilities\n\nPlease do not open public GitHub issues for security vulnerabilities. ${reportingText}`;\n}\n","// ── External Dependencies & Registrations\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\nimport type { ModuleTypeConfig } from '@/utilities';\nimport { getModuleConfig, logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, writeReadmeSection } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- USAGE_START -->';\nconst END_MARKER = '<!-- USAGE_END -->';\n\n// Module types the DPUse Engine uploads to the cloud for the browser app to load. The engine itself is also uploaded, but\n// isn't something others build their own version of, so it gets the general wording.\nconst UPLOADED_MODULE_TYPE_IDS = new Set<ModuleTypeConfig['typeId']>(['connector', 'cookbook', 'presenter']);\n\n// Published to npm only so DPUse projects can install them, not for general use, so the npm wording carries a warning.\nconst INTERNAL_NPM_MODULE_TYPE_IDS = new Set<ModuleTypeConfig['typeId']>(['development', 'eslint']);\nconst INTERNAL_NPM_WARNING = `> [!WARNING]\n> This project is not designed for general use. It is custom built for the DPUse CI/CD process. You are welcome to clone and customise it for your own purposes, but you will need to adapt it to your own project structure and tooling.`;\n\n// How the repository is managed. dpuse-development provides the actions every other repository uses, and runs them on itself.\nconst DEVELOPMENT_MANAGEMENT_TEXT = 'This repository manages itself using the actions it implements.';\nconst SHARED_MANAGEMENT_TEXT = 'This repository is managed using the common set of actions provided by [@dpuse/dpuse-development](https://github.com/dpuse/dpuse-development).';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentUsage(): Promise<void> {\n try {\n logOperationHeader('Document Usage');\n\n logStepHeader(\"1️⃣ Insert usage content into 'README.md'\");\n\n const [packageJSON, configJSON] = await Promise.all([readJSONFile<PackageJson>('package.json'), readJSONFile<ModuleConfig>('config.json')]);\n\n const cloneURL = resolveCloneURL(packageJSON);\n const directoryName = resolveDirectoryName(cloneURL);\n const nodeVersion = resolveVersion(packageJSON.engines?.node);\n const npmVersion = resolveVersion(packageJSON.engines?.npm);\n const typescriptVersion = resolveVersion(packageJSON.devDependencies?.['typescript']);\n\n const introduction = buildIntroductionContent(getModuleConfig(configJSON.id), packageJSON.name);\n // A full link, so it still works where the README is shown away from GitHub, such as on npm.\n const packageJSONURL = `${cloneURL.replace(/\\.git$/, '')}/blob/main/package.json`;\n const managementText = packageJSON.name === '@dpuse/dpuse-development' ? DEVELOPMENT_MANAGEMENT_TEXT : SHARED_MANAGEMENT_TEXT;\n const management = `${managementText} See the \\`scripts\\` block in [package.json](${packageJSONURL}) for details.`;\n const content = buildUsageContent(introduction, cloneURL, directoryName, nodeVersion, npmVersion, typescriptVersion, management);\n\n await writeReadmeSection(content, START_MARKER, END_MARKER);\n\n logOperationSuccess('Usage documented');\n } catch (error) {\n console.error('❌ Error documenting usage', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nfunction resolveCloneURL(packageJSON: PackageJson): string {\n const repo = packageJSON.repository;\n const url = typeof repo === 'string' ? repo : repo?.url;\n if (url == null || url === '') throw new Error(\"package.json 'repository' field is required to document usage.\");\n return url.replace(/^git\\+/, '');\n}\n\nfunction resolveDirectoryName(cloneURL: string): string {\n const lastSegment = cloneURL.split('/').at(-1) ?? '';\n return lastSegment.replace(/\\.git$/, '');\n}\n\nfunction resolveVersion(range: string | undefined): string {\n if (range == null) throw new Error('package.json version range is required to document usage.');\n // eslint-disable-next-line security/detect-unsafe-regex -- Linear: each group repeat must start with a literal '.'.\n const match = /\\d+(?:\\.\\d+)*/.exec(range);\n if (match == null) throw new Error(`Unable to parse version from '${range}'.`);\n return match[0];\n}\n\n// Worded for how the module reaches people: uploaded to DPUse, installed from npm, or neither.\nfunction buildIntroductionContent(moduleTypeConfig: ModuleTypeConfig, packageName: string | undefined): string {\n const { typeId } = moduleTypeConfig;\n\n if (UPLOADED_MODULE_TYPE_IDS.has(typeId)) {\n return `This ${typeId} is automatically uploaded to the DPUse Engine cloud once released and becomes instantly available to all new browser app instances, with existing instances notified of the update.\n\nYou may view or clone this repository for your own purposes, such as building a new, similar ${typeId}, though there is currently no process to accept third-party ${typeId}s into DPUse at this stage.`;\n }\n\n if (moduleTypeConfig.publishedTo === 'npm') {\n if (packageName == null || packageName === '') throw new Error(\"package.json 'name' field is required to document usage.\");\n const warning = INTERNAL_NPM_MODULE_TYPE_IDS.has(typeId) ? `${INTERNAL_NPM_WARNING}\\n\\n` : ''; // Its own paragraph, or the text after it joins the warning.\n return `This [package](https://www.npmjs.com/package/${packageName}) is available on [npm](https://www.npmjs.com/). Install it with:\n\n\\`\\`\\`bash\nnpm install ${packageName}\n\\`\\`\\`\n\n${warning}To work on the source instead, clone this repository.`;\n }\n\n return `You may view or clone this repository for your own purposes.`;\n}\n\nfunction buildUsageContent(\n introduction: string,\n cloneURL: string,\n directoryName: string,\n nodeVersion: string,\n npmVersion: string,\n typescriptVersion: string,\n management: string\n): string {\n return `## Usage\n\n${introduction}\n\n\\`\\`\\`bash\ngit clone ${cloneURL}\ncd ${directoryName}\nnpm install\n\\`\\`\\`\n\n_Requires [Node.js](https://nodejs.org/) ${nodeVersion} or later, [npm](https://www.npmjs.com/) ${npmVersion} or later, and [TypeScript](https://www.typescriptlang.org/) ${typescriptVersion} or later._\n\n${management}`;\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport const API_REFERENCE_PATH = 'API_REFERENCE.md';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Lists every export of each import path in API_REFERENCE.md. Runs with the README's sections where the project has that file. */\nexport async function documentAPIReference(): Promise<void> {\n try {\n logOperationHeader('Document API Reference');\n\n // TypeScript is an optional peer, so the code that reads the source with it is loaded only when it's needed.\n const { writeAPIReference } = await import('@/utilities/apiReference');\n await writeAPIReference('1️⃣ ', API_REFERENCE_PATH);\n\n logOperationSuccess('API reference documented');\n } catch (error) {\n console.error('❌ Error documenting API reference', error);\n process.exit(1);\n }\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, writeReadmeSection } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface Sizes {\n uncompressed: number;\n gzip: number;\n}\n\ninterface SondaResource {\n kind: 'asset' | 'chunk' | 'filesystem' | 'sourcemap';\n name: string;\n uncompressed: number;\n gzip?: number;\n parent?: string | null;\n}\n\ninterface SondaDependency {\n name: string;\n paths: string[];\n}\n\ninterface SondaJson {\n resources: SondaResource[];\n dependencies: SondaDependency[];\n}\n\ninterface GroupData {\n sizes: Sizes;\n files: Map<string, Sizes>;\n}\n\ntype GroupEntry = [string, GroupData];\ntype DependencyPath = [path: string, name: string];\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport const BUNDLE_REPORT_PATH = 'bundle-analysis-reports/sonda/index.json'; // Written by Sonda during the Vite build.\n\nconst BUNDLE_START_MARKER = '<!-- BUNDLE_START -->';\nconst BUNDLE_END_MARKER = '<!-- BUNDLE_END -->';\nconst INDENT = ' ';\nconst BAR_WIDTH = 20;\nconst BAR_CHARACTER = '█';\nconst PART_BAR_CHARACTER = '▒'; // Lighter, so a '↳' row reads as part of the row above. Markdown has no colour that also shows on npm.\nconst MIN_VISIBLE_PERCENT = 100 / BAR_WIDTH / 2; // Below this a bar rounds to no characters at all.\nconst SMALL_FILES_MAX_PERCENT = 100 / BAR_WIDTH; // The combined row for small files stays within one bar character.\n\nconst BUNDLE_ANALYSIS_INTRO = `This report is updated with each release, from the bundle the release builds, using [Sonda](https://sonda.dev/), which analyses final source maps to reveal the actual effects of tree-shaking and minification rather than relying on pre-build estimates.\\n\\n_Note: Sonda's Vite reports currently exclude CSS files, since Vite does not generate source maps for CSS._`;\n\nconst BAR_NOTE = `Bars show each row's share of its output file.`;\nconst PART_ROW_NOTE = '↳ rows are part of the row above.'; // Only where the table has such rows, which module level leaves out.\n\nconst UNTRACED_LABEL = '(bundler output, whitespace & JSON)';\nconst UNTRACED_NOTE = `${UNTRACED_LABEL} = bytes Sonda can't trace to a source file: whitespace (indentation and line breaks), code the bundler generates (region comments, the combined import/export lines, its small runtime helper and wrappers), and imported JSON such as \\`config.json\\`, which the bundler doesn't map. The JSON and the generated code are real bytes that ship; the whitespace mostly disappears once compressed.`;\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentBundleSizes(options?: { moduleLevel?: boolean }): Promise<void> {\n try {\n logOperationHeader('Document Bundle Sizes');\n\n logStepHeader('1️⃣ Read bundle analysis report');\n const json = await readJSONFile<SondaJson>(BUNDLE_REPORT_PATH);\n\n logStepHeader(`2️⃣ Insert table into 'README.md'`);\n const bundleTable = buildBundleTable(json, options?.moduleLevel ?? false);\n const rowNote = bundleTable.includes('↳') ? `${BAR_NOTE} ${PART_ROW_NOTE}` : BAR_NOTE;\n\n await writeReadmeSection(`## Bundle Analysis\\n\\n${BUNDLE_ANALYSIS_INTRO}\\n\\n${bundleTable}\\n\\n${rowNote}\\n\\n${UNTRACED_NOTE}`, BUNDLE_START_MARKER, BUNDLE_END_MARKER);\n\n logOperationSuccess('Bundle sizes documented');\n } catch (error) {\n console.error('❌ Error documenting bundle sizes', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Each output file is broken down on its own, so its top-level bars add up to 100% of that file, and its heading gives its\n// share of the whole build. Rows marked '↳' are part of the row above; their bars use the same scale, so every bar in a\n// file can be compared with every other.\nfunction buildBundleTable(json: SondaJson, isModuleLevel: boolean): string {\n const assetGroups = buildAssetGroups(json);\n const buildTotal = assetGroups\n .values()\n .flatMap((groups) => groups.values().toArray())\n .reduce((sum, group) => sum + group.sizes.uncompressed, 0);\n\n const assets = json.resources\n .filter((resource) => resource.kind === 'asset')\n .map((asset): [string, Sizes] => [asset.name, resourceSizes(asset)])\n .toSorted((a, b) => b[1].uncompressed - a[1].uncompressed);\n\n const lines = ['|Chunk/Module/File|Composition|', '|:------ |:-----------|'];\n\n for (const [file, sizes] of assets) {\n const groups = assetGroups.get(file) ?? new Map<string, GroupData>();\n const sortedGroups = [...groups].toSorted(compareGroups);\n const fileTotal = sortedGroups.reduce((sum, [, group]) => sum + group.sizes.uncompressed, 0);\n\n const buildShare = fileTotal > 0 && buildTotal > 0 ? ` · ${formatPercent(fileTotal, buildTotal)} of the build` : '';\n lines.push(`| **${file}** | ${chunkSizes(sizes)}${buildShare} |`, ...renderGroupRows(sortedGroups, fileTotal, isModuleLevel));\n }\n\n return lines.join('\\n');\n}\n\n// Largest first, except the untraced bytes, which always come last as what is left over once the modules are listed.\nfunction compareGroups(a: GroupEntry, b: GroupEntry): number {\n if ((a[0] === UNTRACED_LABEL) !== (b[0] === UNTRACED_LABEL)) return a[0] === UNTRACED_LABEL ? 1 : -1;\n return b[1].sizes.uncompressed - a[1].sizes.uncompressed;\n}\n\nfunction renderGroupRows(sortedGroups: GroupEntry[], fileTotal: number, isModuleLevel: boolean): string[] {\n const lines: string[] = [];\n\n for (const [groupName, { sizes: groupSizes, files }] of sortedGroups) {\n if (files.size === 1) {\n const fileName = getSoleFileName(files);\n lines.push(`| ${INDENT}${formatGroupLabel(groupName, fileName)} | ${composition(groupSizes.uncompressed, fileTotal)} |`);\n continue;\n }\n\n lines.push(`| ${INDENT}${groupName} | ${composition(groupSizes.uncompressed, fileTotal)} |`);\n if (!isModuleLevel) lines.push(...renderFileRows(files, fileTotal));\n }\n\n return lines;\n}\n\nfunction renderFileRows(files: Map<string, Sizes>, fileTotal: number): string[] {\n const sortedFiles = [...files].toSorted((a, b) => b[1].uncompressed - a[1].uncompressed);\n const smallCount = countSmallFiles(sortedFiles, fileTotal);\n const namedFiles = smallCount > 0 ? sortedFiles.slice(0, -smallCount) : sortedFiles;\n\n const rows = namedFiles.map(([fileName, fileSizes]) => `| ${INDENT}${INDENT}↳ ${fileName} | ${composition(fileSizes.uncompressed, fileTotal, PART_BAR_CHARACTER)} |`);\n if (smallCount > 0) {\n const smallBytes = sortedFiles.slice(-smallCount).reduce((sum, [, fileSizes]) => sum + fileSizes.uncompressed, 0);\n rows.push(`| ${INDENT}${INDENT}↳ ${String(smallCount)} smaller files | ${composition(smallBytes, fileTotal, PART_BAR_CHARACTER)} |`);\n }\n return rows;\n}\n\n// Files too small to show any bar are combined into one row, smallest first, stopping before that row would pass one bar\n// character, so it never hides much. A lone small file keeps its name, as combining one file would hide it for nothing.\nfunction countSmallFiles(sortedFiles: [string, Sizes][], fileTotal: number): number {\n if (fileTotal <= 0) return 0;\n let count = 0;\n let bytes = 0;\n for (const [, fileSizes] of sortedFiles.toReversed()) {\n const isTooSmallToShow = (fileSizes.uncompressed / fileTotal) * 100 < MIN_VISIBLE_PERCENT;\n const isCombinedRowStillSmall = ((bytes + fileSizes.uncompressed) / fileTotal) * 100 <= SMALL_FILES_MAX_PERCENT;\n if (!isTooSmallToShow || !isCombinedRowStillSmall) break;\n count++;\n bytes += fileSizes.uncompressed;\n }\n return count >= 2 ? count : 0;\n}\n\n// A bar and percentage of the output file, then the size, so the share and the bytes behind it read together.\nfunction composition(bytes: number, fileTotal: number, barCharacter = BAR_CHARACTER): string {\n return `${bar(fileTotal > 0 ? (bytes / fileTotal) * 100 : 0, barCharacter)} · ${formatBytes(bytes)}`;\n}\n\n// A group with no file name, such as the untraced bytes, is shown on its own rather than as 'group → '.\nfunction formatGroupLabel(groupName: string, fileName: string): string {\n return fileName === '' ? groupName : `${groupName} → ${fileName}`;\n}\n\nfunction getSoleFileName(files: Map<string, Sizes>): string {\n const [fileName] = files.keys();\n if (fileName === undefined) throw new Error('Expected exactly one file');\n return fileName;\n}\n\n// Builds, per output asset, the size totals grouped by dependency (or 'src'/'wasm'/'(runtime)'), and by file within each group.\nfunction buildAssetGroups(json: SondaJson): Map<string, Map<string, GroupData>> {\n const dependencyPaths = buildDependencyPaths(json.dependencies);\n const assets = new Map<string, Map<string, GroupData>>();\n\n for (const resource of json.resources) {\n if (resource.kind !== 'chunk' || !resource.parent) continue;\n const { group: groupName, file: fileName } = resolveModule(resource.name, dependencyPaths);\n const sizes = resourceSizes(resource);\n\n const groups = assets.get(resource.parent) ?? new Map<string, GroupData>();\n assets.set(resource.parent, groups);\n\n const group = groups.get(groupName) ?? { sizes: zero(), files: new Map<string, Sizes>() };\n groups.set(groupName, group);\n addTo(group.sizes, sizes);\n\n const fileSizes = group.files.get(fileName) ?? zero();\n group.files.set(fileName, fileSizes);\n addTo(fileSizes, sizes);\n }\n\n return assets;\n}\n\n// Flattens `dependencies[].paths` into `[path, dependencyName]` pairs, longest path first so scoped/nested packages match before their parents.\nfunction buildDependencyPaths(dependencies: SondaDependency[]): DependencyPath[] {\n return dependencies.flatMap((dependency): DependencyPath[] => dependency.paths.map((path) => [path, dependency.name])).toSorted((a, b) => b[0].length - a[0].length);\n}\n\nfunction resolveModule(path: string, dependencyPaths: DependencyPath[]): { group: string; file: string } {\n const match = dependencyPaths.find(([dependencyPath]) => path === dependencyPath || path.startsWith(`${dependencyPath}/`));\n if (match) {\n const [dependencyPath, name] = match;\n return { group: name, file: path.slice(dependencyPath.length + 1) };\n }\n if (path === '[unassigned]') return { group: UNTRACED_LABEL, file: '' }; // Sonda's marker for chunk bytes it can't trace back to a source module.\n if (path.startsWith('\\u{0}')) return { group: '(runtime)', file: path.slice(1) };\n if (path.startsWith('rust/')) return { group: 'wasm', file: shortenCrateFileName(path) };\n return { group: path.includes('vite-plugin-wasm') ? 'wasm' : 'src', file: lastPathSegment(path) };\n}\n\n// wasm-pack names every generated file after the crate, so the shared part is shortened to '…', leaving what differs.\nfunction shortenCrateFileName(path: string): string {\n const crateName = path.split('/', 2)[1] ?? '';\n const fileName = lastPathSegment(path);\n return crateName !== '' && fileName.startsWith(crateName) ? `…${fileName.slice(crateName.length)}` : fileName;\n}\n\nfunction lastPathSegment(path: string): string {\n return path.split('/').at(-1) ?? path;\n}\n\nfunction resourceSizes(resource: SondaResource): Sizes {\n return { uncompressed: resource.uncompressed, gzip: resource.gzip ?? 0 };\n}\n\nfunction chunkSizes(sizes: Sizes): string {\n return `${formatBytes(sizes.uncompressed)} · gzip ${formatBytes(sizes.gzip)}`;\n}\n\nfunction bar(pct: number, barCharacter = BAR_CHARACTER): string {\n const count = Math.round((pct / 100) * BAR_WIDTH);\n return `\\`${barCharacter.repeat(count)}${'░'.repeat(BAR_WIDTH - count)}\\` ${pct.toFixed(1)}%`;\n}\n\nfunction zero(): Sizes {\n return { uncompressed: 0, gzip: 0 };\n}\n\nfunction addTo(target: Sizes, source: Sizes): void {\n target.uncompressed += source.uncompressed;\n target.gzip += source.gzip;\n}\n\nfunction formatPercent(part: number, whole: number): string {\n return `${((part / whole) * 100).toFixed(1)}%`;\n}\n\nfunction formatBytes(bytes: number): string {\n return bytes < 1024 ? `${String(bytes)} B` : `${(bytes / 1024).toFixed(1)} kB`;\n}\n","// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { documentActions } from '@/actions/documentActions';\nimport { documentContributingLicense } from '@/actions/documentContributingLicense';\nimport { documentDependencies } from '@/actions/documentDependencies';\nimport { documentOpening } from '@/actions/documentOpening';\nimport { documentQualitySecurity } from '@/actions/documentQualitySecurity';\nimport { documentUsage } from '@/actions/documentUsage';\nimport { API_REFERENCE_PATH, documentAPIReference } from '@/actions/documentApiReference';\nimport { BUNDLE_REPORT_PATH, documentBundleSizes } from '@/actions/documentBundleSizes';\nimport { getModuleConfig, logStepHeader, readJSONFile, readTextFileOrNull, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Regenerates every generated section of the README, in the order they appear, then the API reference where the project keeps one. */\n// 'allowedLicenses' lists the licences dependencies may use, separated by ';'. 'isModuleLevel' breaks bundle sizes\n// down by module rather than by package.\nexport async function documentProject(allowedLicenses = 'MIT', isModuleLevel = false): Promise<void> {\n try {\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const isConnector = getModuleConfig(configJSON.id).typeId === 'connector'; // Only connectors have an actions table.\n\n await documentOpening();\n if (isConnector) await documentActions();\n await documentUsage();\n await documentDependencies(allowedLicenses);\n\n // Bundle sizes come from the report the last build wrote, so they wait until there is one, as on a fresh clone.\n if ((await readTextFileOrNull(BUNDLE_REPORT_PATH)) === null) {\n logStepHeader(`ℹ️ Bundle sizes NOT documented, as there is no '${BUNDLE_REPORT_PATH}' yet. Build the project first.`);\n } else {\n await documentBundleSizes({ moduleLevel: isModuleLevel });\n }\n\n await documentQualitySecurity();\n await documentContributingLicense();\n\n // Only where the project keeps an API reference, so projects opt in by adding the file.\n const hasAPIReference = (await readTextFileOrNull(API_REFERENCE_PATH)) !== null;\n if (hasAPIReference) {\n await documentAPIReference();\n } else {\n logStepHeader(`ℹ️ '${API_REFERENCE_PATH}' NOT required by this project`);\n }\n\n // Saved as Prettier would format them, so 'npm run format' has nothing left to change. Only the files written here\n // are formatted, so documenting never touches the source.\n await spawnCommand('ℹ️ Format generated files', 'prettier', ['--write', 'README.md', ...(hasAPIReference ? [API_REFERENCE_PATH] : [])]);\n } catch (error) {\n console.error('❌ Error documenting project', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport { existsSync } from 'node:fs';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Uses prettier to enforce formatting style rules. */\nexport async function formatCode(): Promise<void> {\n try {\n logOperationHeader('Format Code');\n\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- specified directories, no user input.\n const optionalGlobs = ['app', 'src', 'tests'].filter((directory) => existsSync(directory)).map((directory) => `${directory}/**`);\n const formatTargets = ['--write', '*.json', '*.md', '*.ts', ...optionalGlobs];\n await spawnCommand('1️⃣ Format', 'prettier', formatTargets);\n\n logOperationSuccess('Code formatted');\n } catch (error) {\n console.error('❌ Error formatting code', error);\n process.exit(1);\n }\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Uses eslint to check the code for potential errors and enforces coding style rules. */\nexport async function lintCode(): Promise<void> {\n try {\n logOperationHeader('Lint Code');\n\n await spawnCommand('1️⃣ Lint', 'eslint', ['.']);\n\n logOperationSuccess('Code linted');\n } catch (error) {\n console.error('❌ Error linting code', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport type { ObjectEncodingOptions } from 'node:fs';\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { execCommand, getDirectoryEntries, getStatsForPath, readJSONFile } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function putState(): Promise<void> {\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const options = {\n body: JSON.stringify(configJSON),\n headers: { 'Content-Type': 'application/json' },\n method: 'PUT'\n };\n const response = await fetch(`https://api.dpuse.app/configs/${configJSON.id}`, options);\n if (!response.ok) throw new Error(await response.text());\n}\n\nexport async function uploadDirectoryToR2(sourceDirectory: string, uploadDirectory: string): Promise<void> {\n async function listDirectoryEntriesRecursively(currentSourceDirectory: string, currentDestinationDirectory: string, names: string[]): Promise<void> {\n for (const name of names) {\n const sourceItemPath = `${currentSourceDirectory}/${name}`;\n const destinationItemPath = `${currentDestinationDirectory}/${name}`;\n const stats = await getStatsForPath(sourceItemPath);\n if (stats.isDirectory()) {\n const nextLevelChildren = await getDirectoryEntries(sourceItemPath);\n await listDirectoryEntriesRecursively(sourceItemPath, destinationItemPath, nextLevelChildren);\n } else {\n console.info(`⚙️ Uploading '${currentSourceDirectory}/${name}'...`);\n await execCommand(undefined, 'wrangler', [\n 'r2',\n 'object',\n 'put',\n `dpuse-sample-data-eu/${currentDestinationDirectory}/${name}`,\n `--file=${currentSourceDirectory}/${name}`,\n '--jurisdiction=eu',\n '--remote'\n ]);\n }\n }\n }\n const toplevelNames = await getDirectoryEntries(`${sourceDirectory}/${uploadDirectory}/`);\n await listDirectoryEntriesRecursively(`${sourceDirectory}/${uploadDirectory}`, uploadDirectory, toplevelNames);\n}\n\nexport async function uploadModuleConfigToDO(configJSON: ModuleConfig): Promise<void> {\n const stateId = configJSON.id;\n const options = {\n body: JSON.stringify(configJSON),\n headers: { 'Content-Type': 'application/json' },\n method: 'PUT'\n };\n const response = await fetch(`https://api.dpuse.app/configs/${stateId}`, options);\n if (!response.ok) throw new Error(await response.text());\n}\n\nexport async function uploadModuleToR2(packageJSON: PackageJson, uploadDirectoryPath: string): Promise<void> {\n const version = `v${packageJSON.version ?? 'unknown'}`;\n async function uploadDirectory(currentDirectory: string, prefix = ''): Promise<void> {\n const entries = await getDirectoryEntries(currentDirectory, { withFileTypes: true } as ObjectEncodingOptions);\n for (const entry of entries) {\n if (entry.isDirectory() || entry.name.endsWith('.map')) continue;\n const fullPath = `${currentDirectory}/${entry.name}`;\n const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;\n const r2Path = `${uploadDirectoryPath}_${version}/${relativePath}`.replaceAll('\\\\', '/');\n const nonJavaScripContentType = entry.name.endsWith('.css') ? 'text/css' : 'application/octet-stream';\n const contentType = entry.name.endsWith('.js') ? 'application/javascript' : nonJavaScripContentType;\n console.info(`⚙️ Uploading '${relativePath}' → '${r2Path}'...`);\n await execCommand(undefined, 'wrangler', ['r2', 'object', 'put', r2Path, `--file=${fullPath}`, '--content-type', contentType, '--jurisdiction=eu', '--remote']);\n }\n }\n await uploadDirectory('dist');\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { getModuleConfig, logOperationHeader, logOperationSuccess, logStepHeader, type ModuleTypeConfig, readJSONFile, spawnCommand } from '@/utilities';\nimport { putState, uploadModuleConfigToDO, uploadModuleToR2 } from '@/utilities/cloudflare';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Publishes the project to npm, uploads it to DPUse, or both, as its module type requires. Run by the 'publish.yml' workflow. */\nexport async function publishProject(): Promise<void> {\n try {\n logOperationHeader('Publish Project');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n\n // Where a module goes is set by its type, so every project calls this the same way. Tools go to both places: npm\n // first, so the app is never told of a version whose npm publish failed.\n if (moduleTypeConfig.publishedTo === 'npm') {\n await spawnCommand('1️⃣ Publish to npm', 'npm', ['publish', '--provenance']);\n } else {\n logStepHeader('1️⃣ Publishing to npm NOT required');\n }\n\n await registerModule('2️⃣ ', packageJSON, configJSON, moduleTypeConfig);\n\n logOperationSuccess(`Project version '${packageJSON.version ?? 'unknown'}' published.`);\n } catch (error) {\n console.error('❌ Error publishing project', error);\n process.exit(1);\n }\n}\n\n// Also run as the last step of 'releaseProject'.\nexport async function registerModule(stepIcon: string, packageJSON: PackageJson, configJSON: ModuleConfig, moduleTypeConfig: ModuleTypeConfig): Promise<void> {\n if (moduleTypeConfig.typeId === 'app') {\n logStepHeader(`${stepIcon} Register module`);\n await putState();\n } else if (moduleTypeConfig.typeId === 'engine') {\n logStepHeader(`${stepIcon} Register module`);\n await uploadModuleToR2(packageJSON, `dpuse-engine-eu/${moduleTypeConfig.uploadGroupName ?? 'unknown'}`);\n await uploadModuleConfigToDO(configJSON); // This MUST follow 'uploadModuleToR2', otherwise the app will receive a message a new engine is available and try to access it before it is uploaded to R2.\n } else if (moduleTypeConfig.uploadGroupName === undefined) {\n logStepHeader(`${stepIcon} Registration NOT required`);\n } else {\n logStepHeader(`${stepIcon} Register module`);\n const moduleTypeName = configJSON.id.split('-').slice(2).join('-');\n await uploadModuleToR2(packageJSON, `dpuse-engine-eu/${moduleTypeConfig.uploadGroupName}/${moduleTypeName}`);\n await uploadModuleConfigToDO(configJSON); // This MUST follow 'uploadModuleToR2', otherwise the app will receive a message a new module is available and try to access it before it is uploaded to R2.\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { bundleProject } from '@/actions/buildProject';\nimport { documentProject } from '@/actions/documentProject';\nimport { registerModule } from '@/actions/publishProject';\nimport {\n buildModuleConfig,\n bumpPackageVersion,\n execCommand,\n getModuleConfig,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n readJSONFile,\n spawnCommand\n} from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Bump version, builds config, builds project, regenerates the README, synchronise with GitHub and publish to npm or Cloudflare. */\nexport async function releaseProject(allowedLicenses = 'MIT', isModuleLevel = false): Promise<void> {\n try {\n logOperationHeader('Release Project');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n\n await bumpPackageVersion('1️⃣ ', packageJSON);\n\n const builtConfigJSON = await buildModuleConfig('2️⃣ ', packageJSON, moduleTypeConfig);\n\n await bundleProject('3️⃣ ', packageJSON);\n\n // After the build, so the bundle sizes are the released bundle's, and before staging, so the README is committed\n // with the release. Its governance step runs the tests, so a failing test stops the release before anything is pushed.\n logStepHeader('4️⃣ Regenerate README');\n await documentProject(allowedLicenses, isModuleLevel);\n\n await execCommand('5️⃣ Stage changes', 'git', ['add', '.']);\n\n await execCommand('6️⃣ Commit changes', 'git', ['commit', '-m', `v${packageJSON.version ?? 'unknown'}`]);\n\n await execCommand('7️⃣ Push changes', 'git', ['push', 'origin', 'main:main']);\n\n await registerModule('8️⃣ ', packageJSON, builtConfigJSON, moduleTypeConfig);\n\n // The release triggers the 'publish.yml' workflow, which publishes to npm through trusted publishing, so no token is needed here.\n if (moduleTypeConfig.publishedTo === 'npm') {\n const tagName = `v${packageJSON.version ?? 'unknown'}`;\n await spawnCommand('9️⃣ Create GitHub release', 'gh', ['release', 'create', tagName, '--target', 'main', '--generate-notes', '--latest']);\n } else {\n logStepHeader(`9️⃣ Publishing NOT required for package with type identifier of '${moduleTypeConfig.typeId}'.`);\n }\n\n logOperationSuccess(`Project version '${packageJSON.version ?? 'unknown'}' released.`);\n } catch (error) {\n console.error('❌ Error releasing project', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { buildModuleConfig, bumpPackageVersion, execCommand, getModuleConfig, logOperationHeader, logOperationSuccess, readJSONFile } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Synchronise the local repository with the main GitHub repository. */\nexport async function syncProjectWithGitHub(): Promise<void> {\n try {\n logOperationHeader('Synchronise Project with GitHub');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n\n await bumpPackageVersion('1️⃣ ', packageJSON);\n\n await buildModuleConfig('2️⃣ ', packageJSON, moduleTypeConfig);\n\n await execCommand('3️⃣ Stage changes', 'git', ['add', '.']);\n\n await execCommand('4️⃣ Commit changes', 'git', ['commit', '-m', `v${packageJSON.version ?? 'unknown'}`]);\n\n await execCommand('5️⃣ Push changes', 'git', ['push', 'origin', 'main:main']);\n\n logOperationSuccess(`Project version '${packageJSON.version ?? 'unknown'}' synchronised with GitHub.`);\n } catch (error) {\n console.error('❌ Error synchronising project with GitHub', error);\n process.exit(1);\n }\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, readTextFileOrNull, spawnCommand } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface TestTypeConfig {\n id: TestTypeId;\n label: string;\n command: string;\n arguments: string[];\n configFileName: string; // Having this file is how a project says it runs this type of test.\n}\n\nexport type TestTypeId = 'e2e' | 'unit';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst STEP_ICONS = ['1️⃣ ', '2️⃣ ', '3️⃣ ', '4️⃣ '];\n\n// In the order they run. Unit tests go first so a failure stops the run before the slow browser tests start.\n// Both runners are told to pass when they find nothing, so a project that has set up a runner but not yet written\n// any tests reports green rather than red, and a real failure stands out.\nconst TEST_TYPE_CONFIGS: TestTypeConfig[] = [\n { id: 'unit', label: 'Run unit tests', command: 'vitest', arguments: ['run', '--passWithNoTests'], configFileName: 'vitest.config.ts' },\n { id: 'e2e', label: 'Run end-to-end tests', command: 'playwright', arguments: ['test', '--pass-with-no-tests'], configFileName: 'playwright.config.ts' }\n];\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Runs the requested types of test, skipping any type this project has not configured. */\nexport async function testProject(testTypeIds: TestTypeId[] = ['unit']): Promise<void> {\n try {\n logOperationHeader('Test Project');\n\n let stepNumber = 0;\n for (const testTypeConfig of TEST_TYPE_CONFIGS) {\n if (!testTypeIds.includes(testTypeConfig.id)) continue;\n\n // Without its configuration file the project does not run this type of test, so pass over it quietly.\n if ((await readTextFileOrNull(testTypeConfig.configFileName)) === null) continue;\n\n const stepLabel = `${STEP_ICONS[stepNumber] ?? ''} ${testTypeConfig.label}`;\n await spawnCommand(stepLabel, testTypeConfig.command, testTypeConfig.arguments);\n stepNumber += 1;\n }\n\n if (stepNumber === 0) {\n console.warn('\\n⚠️ No tests configured for this project.\\n');\n return;\n }\n\n logOperationSuccess('Project tested');\n } catch (error) {\n console.error('❌ Error testing project', error);\n process.exit(1);\n }\n}\n"],"mappings":";;;;;;;;;AAMA,eAAsBuC,KAAmC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