The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | // @effect-diagnostics nodeBuiltinImport:off globalFetch:off - Vite's build plugin runs before an Effect runtime exists. |
| 2 | |
| 3 | import * as NodeFSP from "node:fs/promises"; |
| 4 | import * as NodePath from "node:path"; |
| 5 | import * as NodeURL from "node:url"; |
| 6 | import * as NodeModule from "node:module"; |
| 7 | |
| 8 | import type { Plugin } from "vite-plus"; |
| 9 | |
| 10 | const THIRD_PARTY_LICENSES_FILE_NAME = "third-party-licenses.json"; |
| 11 | const SPDX_LICENSE_LIST_VERSION = "v3.28.0"; |
| 12 | const SPDX_LICENSE_LIST_REVISION = "c4a7237ec8f4654e867546f9f409749300f1bf4c"; |
| 13 | const SPDX_TEMPLATE_DIRECTORY = "third-party-licenses/spdx"; |
| 14 | |
| 15 | export interface ThirdPartyLicenseEntry { |
| 16 | readonly bundles: ReadonlyArray<string>; |
| 17 | readonly kind: "custom" | "package"; |
| 18 | readonly license: string; |
| 19 | readonly name: string; |
| 20 | readonly noticeText: string; |
| 21 | readonly sourceUrl: string | null; |
| 22 | readonly version: string | null; |
| 23 | } |
| 24 | |
| 25 | export interface ThirdPartyLicenseManifest { |
| 26 | readonly schemaVersion: 1; |
| 27 | readonly entries: ReadonlyArray<ThirdPartyLicenseEntry>; |
| 28 | } |
| 29 | |
| 30 | export interface ThirdPartyLicensePackageManifest { |
| 31 | readonly bundle: string; |
| 32 | readonly path: string | URL; |
| 33 | } |
| 34 | |
| 35 | export interface ThirdPartyLicensesPluginOptions { |
| 36 | readonly configFile?: string | URL; |
| 37 | readonly packageManifests: ReadonlyArray<ThirdPartyLicensePackageManifest>; |
| 38 | readonly bundleName: string; |
| 39 | } |
| 40 | |
| 41 | interface GeneratedNoticeConfigEntry { |
| 42 | readonly copyrights?: ReadonlyArray<string>; |
| 43 | readonly licenseId: string; |
| 44 | readonly preamble?: ReadonlyArray<string>; |
| 45 | } |
| 46 | |
| 47 | interface PackageJson { |
| 48 | readonly bin?: unknown; |
| 49 | readonly browser?: unknown; |
| 50 | readonly dependencies?: Readonly<Record<string, string>>; |
| 51 | readonly exports?: unknown; |
| 52 | readonly homepage?: unknown; |
| 53 | readonly license?: unknown; |
| 54 | readonly licenses?: unknown; |
| 55 | readonly main?: unknown; |
| 56 | readonly module?: unknown; |
| 57 | readonly name?: unknown; |
| 58 | readonly optionalDependencies?: Readonly<Record<string, string>>; |
| 59 | readonly "react-native"?: unknown; |
| 60 | readonly repository?: unknown; |
| 61 | readonly sass?: unknown; |
| 62 | readonly style?: unknown; |
| 63 | readonly types?: unknown; |
| 64 | readonly typings?: unknown; |
| 65 | readonly version?: unknown; |
| 66 | } |
| 67 | |
| 68 | interface CustomNoticeConfigEntry { |
| 69 | readonly bundles?: ReadonlyArray<string>; |
| 70 | readonly includeInBundles?: ReadonlyArray<string>; |
| 71 | readonly license: string; |
| 72 | readonly name: string; |
| 73 | readonly generatedNotices?: ReadonlyArray<GeneratedNoticeConfigEntry>; |
| 74 | readonly noticeFiles?: ReadonlyArray<string>; |
| 75 | readonly sourceUrl?: string; |
| 76 | readonly version?: string; |
| 77 | } |
| 78 | |
| 79 | interface PackageNoticeOverrideConfigEntry { |
| 80 | readonly generatedNotices?: ReadonlyArray<GeneratedNoticeConfigEntry>; |
| 81 | readonly license?: string; |
| 82 | readonly name?: string; |
| 83 | readonly noticeFile?: string; |
| 84 | readonly repositoryUrl?: string; |
| 85 | readonly sourceUrl?: string; |
| 86 | readonly version?: string; |
| 87 | } |
| 88 | |
| 89 | interface ThirdPartyLicensesConfig { |
| 90 | readonly customNotices: ReadonlyArray<CustomNoticeConfigEntry>; |
| 91 | readonly packageOverrides: ReadonlyArray<PackageNoticeOverrideConfigEntry>; |
| 92 | } |
| 93 | |
| 94 | interface SpdxLicenseDetails { |
| 95 | readonly licenseId: string; |
| 96 | readonly licenseText: string; |
| 97 | } |
| 98 | |
| 99 | interface CollectedPackage { |
| 100 | readonly bundles: Set<string>; |
| 101 | readonly packageJson: PackageJson; |
| 102 | readonly packageRoot: string; |
| 103 | } |
| 104 | |
| 105 | interface PackageCollection { |
| 106 | readonly byIdentity: Map<string, CollectedPackage>; |
| 107 | } |
| 108 | |
| 109 | const EMPTY_CONFIG: ThirdPartyLicensesConfig = { |
| 110 | customNotices: [], |
| 111 | packageOverrides: [], |
| 112 | }; |
| 113 | |
| 114 | const NOTICE_FILE_PATTERN = /^(?:licen[cs]e|copying|notice)(?:[._-].*)?$/i; |
| 115 | const NOTICE_TEXT_EXTENSIONS = new Set([ |
| 116 | "", |
| 117 | ".0bsd", |
| 118 | ".agpl", |
| 119 | ".apache2", |
| 120 | ".bsd", |
| 121 | ".gpl", |
| 122 | ".isc", |
| 123 | ".lgpl", |
| 124 | ".markdown", |
| 125 | ".md", |
| 126 | ".mit", |
| 127 | ".mpl", |
| 128 | ".mpl2", |
| 129 | ".rst", |
| 130 | ".txt", |
| 131 | ".unlicense", |
| 132 | ]); |
| 133 | const FIRST_PARTY_PACKAGE_PREFIX = "@t3tools/"; |
| 134 | |
| 135 | function isNoticeTextFile(fileName: string): boolean { |
| 136 | return ( |
| 137 | NOTICE_FILE_PATTERN.test(fileName) && |
| 138 | NOTICE_TEXT_EXTENSIONS.has(NodePath.extname(fileName).toLowerCase()) |
| 139 | ); |
| 140 | } |
| 141 | |
| 142 | function asPath(value: string | URL): string { |
| 143 | return value instanceof URL ? NodeURL.fileURLToPath(value) : NodePath.resolve(value); |
| 144 | } |
| 145 | |
| 146 | function isRecord(value: unknown): value is Record<string, unknown> { |
| 147 | return typeof value === "object" && value !== null && !Array.isArray(value); |
| 148 | } |
| 149 | |
| 150 | function readRequiredString(value: Record<string, unknown>, key: string, context: string): string { |
| 151 | const field = value[key]; |
| 152 | if (typeof field !== "string" || field.trim().length === 0) { |
| 153 | throw new Error(`${context} must define a non-empty "${key}" string.`); |
| 154 | } |
| 155 | return field.trim(); |
| 156 | } |
| 157 | |
| 158 | function readOptionalString( |
| 159 | value: Record<string, unknown>, |
| 160 | key: string, |
| 161 | context: string, |
| 162 | ): string | undefined { |
| 163 | const field = value[key]; |
| 164 | if (field === undefined) return undefined; |
| 165 | if (typeof field !== "string" || field.trim().length === 0) { |
| 166 | throw new Error(`${context} must define "${key}" as a non-empty string when present.`); |
| 167 | } |
| 168 | return field.trim(); |
| 169 | } |
| 170 | |
| 171 | function readOptionalStringArray( |
| 172 | value: Record<string, unknown>, |
| 173 | key: string, |
| 174 | context: string, |
| 175 | ): ReadonlyArray<string> | undefined { |
| 176 | const field = value[key]; |
| 177 | if (field === undefined) return undefined; |
| 178 | if ( |
| 179 | !Array.isArray(field) || |
| 180 | field.length === 0 || |
| 181 | field.some((entry) => typeof entry !== "string" || entry.trim().length === 0) |
| 182 | ) { |
| 183 | throw new Error(`${context} must define "${key}" as a non-empty string array.`); |
| 184 | } |
| 185 | return field.map((entry) => (entry as string).trim()); |
| 186 | } |
| 187 | |
| 188 | function decodeGeneratedNotice(value: unknown, context: string): GeneratedNoticeConfigEntry { |
| 189 | if (!isRecord(value)) throw new Error(`${context} must be an object.`); |
| 190 | const copyrights = readOptionalStringArray(value, "copyrights", context); |
| 191 | const preamble = readOptionalStringArray(value, "preamble", context); |
| 192 | return { |
| 193 | licenseId: readRequiredString(value, "licenseId", context), |
| 194 | ...(copyrights !== undefined ? { copyrights } : {}), |
| 195 | ...(preamble !== undefined ? { preamble } : {}), |
| 196 | }; |
| 197 | } |
| 198 | |
| 199 | function decodeGeneratedNotices( |
| 200 | value: unknown, |
| 201 | context: string, |
| 202 | ): ReadonlyArray<GeneratedNoticeConfigEntry> | undefined { |
| 203 | if (value === undefined) return undefined; |
| 204 | if (!Array.isArray(value) || value.length === 0) { |
| 205 | throw new Error(`${context} must define "generatedNotices" as a non-empty array.`); |
| 206 | } |
| 207 | return value.map((entry, index) => |
| 208 | decodeGeneratedNotice(entry, `${context} generated notice at index ${String(index)}`), |
| 209 | ); |
| 210 | } |
| 211 | |
| 212 | function decodeCustomNotices(value: unknown): ReadonlyArray<CustomNoticeConfigEntry> { |
| 213 | if (value === undefined) return []; |
| 214 | if (!Array.isArray(value)) { |
| 215 | throw new Error('Third-party license config field "customNotices" must be an array.'); |
| 216 | } |
| 217 | return value.map((entry, index) => { |
| 218 | const context = `Third-party custom notice at index ${String(index)}`; |
| 219 | if (!isRecord(entry)) throw new Error(`${context} must be an object.`); |
| 220 | const version = readOptionalString(entry, "version", context); |
| 221 | const sourceUrl = readOptionalString(entry, "sourceUrl", context); |
| 222 | const bundles = readOptionalStringArray(entry, "bundles", context); |
| 223 | const includeInBundles = readOptionalStringArray(entry, "includeInBundles", context); |
| 224 | const noticeFile = readOptionalString(entry, "noticeFile", context); |
| 225 | const noticeFiles = readOptionalStringArray(entry, "noticeFiles", context); |
| 226 | const generatedNotices = decodeGeneratedNotices(entry.generatedNotices, context); |
| 227 | const noticeSourceCount = |
| 228 | Number(noticeFile !== undefined) + |
| 229 | Number(noticeFiles !== undefined) + |
| 230 | Number(generatedNotices !== undefined); |
| 231 | if (noticeSourceCount !== 1) { |
| 232 | throw new Error( |
| 233 | `${context} must define exactly one of "noticeFile", "noticeFiles", or "generatedNotices".`, |
| 234 | ); |
| 235 | } |
| 236 | return { |
| 237 | name: readRequiredString(entry, "name", context), |
| 238 | license: readRequiredString(entry, "license", context), |
| 239 | ...(noticeFile !== undefined ? { noticeFiles: [noticeFile] } : {}), |
| 240 | ...(noticeFiles !== undefined ? { noticeFiles } : {}), |
| 241 | ...(generatedNotices !== undefined ? { generatedNotices } : {}), |
| 242 | ...(version !== undefined ? { version } : {}), |
| 243 | ...(sourceUrl !== undefined ? { sourceUrl } : {}), |
| 244 | ...(bundles !== undefined ? { bundles } : {}), |
| 245 | ...(includeInBundles !== undefined ? { includeInBundles } : {}), |
| 246 | }; |
| 247 | }); |
| 248 | } |
| 249 | |
| 250 | function decodePackageOverrides(value: unknown): ReadonlyArray<PackageNoticeOverrideConfigEntry> { |
| 251 | if (value === undefined) return []; |
| 252 | if (!Array.isArray(value)) { |
| 253 | throw new Error('Third-party license config field "packageOverrides" must be an array.'); |
| 254 | } |
| 255 | return value.map((entry, index) => { |
| 256 | const context = `Third-party package override at index ${String(index)}`; |
| 257 | if (!isRecord(entry)) throw new Error(`${context} must be an object.`); |
| 258 | const name = readOptionalString(entry, "name", context); |
| 259 | const repositoryUrl = readOptionalString(entry, "repositoryUrl", context); |
| 260 | if ((name === undefined) === (repositoryUrl === undefined)) { |
| 261 | throw new Error(`${context} must define exactly one of "name" or "repositoryUrl".`); |
| 262 | } |
| 263 | const version = readOptionalString(entry, "version", context); |
| 264 | const license = readOptionalString(entry, "license", context); |
| 265 | const noticeFile = readOptionalString(entry, "noticeFile", context); |
| 266 | const generatedNotice = |
| 267 | entry.generatedNotice === undefined |
| 268 | ? undefined |
| 269 | : decodeGeneratedNotice(entry.generatedNotice, `${context} generated notice`); |
| 270 | const generatedNotices = decodeGeneratedNotices(entry.generatedNotices, context); |
| 271 | if ( |
| 272 | Number(noticeFile !== undefined) + |
| 273 | Number(generatedNotice !== undefined) + |
| 274 | Number(generatedNotices !== undefined) > |
| 275 | 1 |
| 276 | ) { |
| 277 | throw new Error( |
| 278 | `${context} can define only one of "noticeFile", "generatedNotice", or "generatedNotices".`, |
| 279 | ); |
| 280 | } |
| 281 | const sourceUrl = readOptionalString(entry, "sourceUrl", context); |
| 282 | return { |
| 283 | ...(name !== undefined ? { name } : {}), |
| 284 | ...(repositoryUrl !== undefined ? { repositoryUrl } : {}), |
| 285 | ...(version !== undefined ? { version } : {}), |
| 286 | ...(license !== undefined ? { license } : {}), |
| 287 | ...(noticeFile !== undefined ? { noticeFile } : {}), |
| 288 | ...(generatedNotice !== undefined ? { generatedNotices: [generatedNotice] } : {}), |
| 289 | ...(generatedNotices !== undefined ? { generatedNotices } : {}), |
| 290 | ...(sourceUrl !== undefined ? { sourceUrl } : {}), |
| 291 | }; |
| 292 | }); |
| 293 | } |
| 294 | |
| 295 | async function readConfig(configFile: string | URL | undefined): Promise<{ |
| 296 | readonly config: ThirdPartyLicensesConfig; |
| 297 | readonly directory: string; |
| 298 | }> { |
| 299 | if (configFile === undefined) { |
| 300 | return { config: EMPTY_CONFIG, directory: NodePath.resolve(".") }; |
| 301 | } |
| 302 | const configPath = asPath(configFile); |
| 303 | const source = await NodeFSP.readFile(configPath, "utf8"); |
| 304 | const decoded = JSON.parse(source) as unknown; |
| 305 | if (!isRecord(decoded)) throw new Error("Third-party license config must contain an object."); |
| 306 | return { |
| 307 | config: { |
| 308 | customNotices: decodeCustomNotices(decoded.customNotices), |
| 309 | packageOverrides: decodePackageOverrides(decoded.packageOverrides), |
| 310 | }, |
| 311 | directory: NodePath.dirname(configPath), |
| 312 | }; |
| 313 | } |
| 314 | |
| 315 | function spdxTemplatePath(configDirectory: string, licenseId: string): string { |
| 316 | return NodePath.join( |
| 317 | configDirectory, |
| 318 | SPDX_TEMPLATE_DIRECTORY, |
| 319 | SPDX_LICENSE_LIST_VERSION, |
| 320 | `${licenseId}.json`, |
| 321 | ); |
| 322 | } |
| 323 | |
| 324 | function decodeSpdxLicenseDetails(value: unknown, expectedLicenseId: string): SpdxLicenseDetails { |
| 325 | if ( |
| 326 | !isRecord(value) || |
| 327 | value.licenseId !== expectedLicenseId || |
| 328 | typeof value.licenseText !== "string" || |
| 329 | value.licenseText.trim().length === 0 |
| 330 | ) { |
| 331 | throw new Error(`SPDX returned invalid license details for ${expectedLicenseId}.`); |
| 332 | } |
| 333 | return { licenseId: expectedLicenseId, licenseText: value.licenseText.trim() }; |
| 334 | } |
| 335 | |
| 336 | async function readSpdxLicense( |
| 337 | configDirectory: string, |
| 338 | licenseId: string, |
| 339 | ): Promise<SpdxLicenseDetails | null> { |
| 340 | try { |
| 341 | const source = await NodeFSP.readFile(spdxTemplatePath(configDirectory, licenseId), "utf8"); |
| 342 | return decodeSpdxLicenseDetails(JSON.parse(source) as unknown, licenseId); |
| 343 | } catch (error) { |
| 344 | const code = isRecord(error) && typeof error.code === "string" ? error.code : null; |
| 345 | if (code === "ENOENT") return null; |
| 346 | throw error; |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | async function downloadSpdxLicense(configDirectory: string, licenseId: string): Promise<void> { |
| 351 | const url = `https://raw.githubusercontent.com/spdx/license-list-data/${SPDX_LICENSE_LIST_REVISION}/json/details/${encodeURIComponent(licenseId)}.json`; |
| 352 | const response = await fetch(url); |
| 353 | if (!response.ok) { |
| 354 | throw new Error( |
| 355 | `Could not download SPDX license ${licenseId}: HTTP ${String(response.status)}.`, |
| 356 | ); |
| 357 | } |
| 358 | const details = decodeSpdxLicenseDetails((await response.json()) as unknown, licenseId); |
| 359 | const templatePath = spdxTemplatePath(configDirectory, licenseId); |
| 360 | await NodeFSP.mkdir(NodePath.dirname(templatePath), { recursive: true }); |
| 361 | await NodeFSP.writeFile(templatePath, `${JSON.stringify(details, null, 2)}\n`, "utf8"); |
| 362 | } |
| 363 | |
| 364 | function renderGeneratedNotice(config: GeneratedNoticeConfigEntry, licenseText: string): string { |
| 365 | const copyrights = config.copyrights ?? []; |
| 366 | let renderedLicense = licenseText; |
| 367 | if (copyrights.length > 0) { |
| 368 | const placeholderPattern = /^Copyright[^\n]*(?:<year>|<copyright holders>|<owner>)[^\n]*$/m; |
| 369 | if (placeholderPattern.test(renderedLicense)) { |
| 370 | renderedLicense = renderedLicense.replace(placeholderPattern, copyrights.join("\n")); |
| 371 | } else if (config.licenseId === "ISC") { |
| 372 | renderedLicense = renderedLicense.replace( |
| 373 | /^(?:Copyright[^\n]*\n)+/m, |
| 374 | `${copyrights.join("\n")}\n`, |
| 375 | ); |
| 376 | } else { |
| 377 | renderedLicense = `${copyrights.join("\n")}\n\n${renderedLicense}`; |
| 378 | } |
| 379 | } |
| 380 | return [...(config.preamble ?? []), renderedLicense].join("\n\n").trim(); |
| 381 | } |
| 382 | |
| 383 | async function generatedNoticeText( |
| 384 | configs: ReadonlyArray<GeneratedNoticeConfigEntry>, |
| 385 | configDirectory: string, |
| 386 | ): Promise<string> { |
| 387 | const sections = await Promise.all( |
| 388 | configs.map(async (config) => { |
| 389 | const details = await readSpdxLicense(configDirectory, config.licenseId); |
| 390 | if (!details) { |
| 391 | throw new Error( |
| 392 | `SPDX license template ${config.licenseId} is missing. Run \`vp run licenses:sync\` and commit ${SPDX_TEMPLATE_DIRECTORY}.`, |
| 393 | ); |
| 394 | } |
| 395 | return renderGeneratedNotice(config, details.licenseText); |
| 396 | }), |
| 397 | ); |
| 398 | return sections.join("\n\n---\n\n"); |
| 399 | } |
| 400 | |
| 401 | function configuredGeneratedNotices( |
| 402 | config: ThirdPartyLicensesConfig, |
| 403 | ): ReadonlyArray<GeneratedNoticeConfigEntry> { |
| 404 | return [ |
| 405 | ...config.customNotices.flatMap((notice) => notice.generatedNotices ?? []), |
| 406 | ...config.packageOverrides.flatMap((override) => override.generatedNotices ?? []), |
| 407 | ]; |
| 408 | } |
| 409 | |
| 410 | async function syncConfiguredGeneratedNotices( |
| 411 | config: ThirdPartyLicensesConfig, |
| 412 | directory: string, |
| 413 | ): Promise<void> { |
| 414 | const licenseIds = [ |
| 415 | ...new Set(configuredGeneratedNotices(config).map((notice) => notice.licenseId)), |
| 416 | ].sort((left, right) => left.localeCompare(right)); |
| 417 | await Promise.all( |
| 418 | licenseIds.map(async (licenseId) => { |
| 419 | if (!(await readSpdxLicense(directory, licenseId))) { |
| 420 | await downloadSpdxLicense(directory, licenseId); |
| 421 | } |
| 422 | }), |
| 423 | ); |
| 424 | } |
| 425 | |
| 426 | export async function syncThirdPartyLicenseNotices(configFile: string | URL): Promise<void> { |
| 427 | const { config, directory } = await readConfig(configFile); |
| 428 | await syncConfiguredGeneratedNotices(config, directory); |
| 429 | } |
| 430 | |
| 431 | async function readPackageJson(packageJsonPath: string): Promise<PackageJson> { |
| 432 | const source = await NodeFSP.readFile(packageJsonPath, "utf8"); |
| 433 | const value = JSON.parse(source) as unknown; |
| 434 | if (!isRecord(value)) throw new Error(`Package manifest is not an object: ${packageJsonPath}`); |
| 435 | return value as PackageJson; |
| 436 | } |
| 437 | |
| 438 | function packageIdentity(packageJson: PackageJson, packageRoot: string): string { |
| 439 | const name = |
| 440 | typeof packageJson.name === "string" ? packageJson.name : NodePath.basename(packageRoot); |
| 441 | const version = typeof packageJson.version === "string" ? packageJson.version : "unknown"; |
| 442 | return `${name}@${version}`; |
| 443 | } |
| 444 | |
| 445 | async function findPackageRoot( |
| 446 | resolvedPath: string, |
| 447 | expectedName?: string, |
| 448 | ): Promise<{ readonly packageJson: PackageJson; readonly packageRoot: string } | null> { |
| 449 | let current = NodePath.dirname(resolvedPath); |
| 450 | const root = NodePath.parse(current).root; |
| 451 | |
| 452 | while (current !== root) { |
| 453 | const packageJsonPath = NodePath.join(current, "package.json"); |
| 454 | try { |
| 455 | const packageJson = await readPackageJson(packageJsonPath); |
| 456 | const matchesExpectedPackage = |
| 457 | expectedName !== undefined |
| 458 | ? packageJson.name === expectedName |
| 459 | : typeof packageJson.name === "string" && typeof packageJson.version === "string"; |
| 460 | if (matchesExpectedPackage) { |
| 461 | return { packageJson, packageRoot: await NodeFSP.realpath(current) }; |
| 462 | } |
| 463 | } catch (error) { |
| 464 | const code = isRecord(error) && typeof error.code === "string" ? error.code : null; |
| 465 | if (code !== "ENOENT" && code !== "ENOTDIR") throw error; |
| 466 | } |
| 467 | current = NodePath.dirname(current); |
| 468 | } |
| 469 | return null; |
| 470 | } |
| 471 | |
| 472 | async function resolveDependencyPackage( |
| 473 | dependencyName: string, |
| 474 | fromPackageJsonPath: string, |
| 475 | ): Promise<{ readonly packageJson: PackageJson; readonly packageRoot: string } | null> { |
| 476 | const requireFromPackage = NodeModule.createRequire(fromPackageJsonPath); |
| 477 | const candidates = [`${dependencyName}/package.json`, dependencyName]; |
| 478 | for (const candidate of candidates) { |
| 479 | try { |
| 480 | const resolved = requireFromPackage.resolve(candidate); |
| 481 | const found = await findPackageRoot(resolved, dependencyName); |
| 482 | if (found) return found; |
| 483 | } catch (error) { |
| 484 | const code = isRecord(error) && typeof error.code === "string" ? error.code : null; |
| 485 | if (code !== "MODULE_NOT_FOUND" && code !== "ERR_PACKAGE_PATH_NOT_EXPORTED") throw error; |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | let current = NodePath.dirname(fromPackageJsonPath); |
| 490 | const root = NodePath.parse(current).root; |
| 491 | while (true) { |
| 492 | const packageRoot = NodePath.join(current, "node_modules", dependencyName); |
| 493 | try { |
| 494 | const packageJson = await readPackageJson(NodePath.join(packageRoot, "package.json")); |
| 495 | if (packageJson.name === dependencyName) { |
| 496 | return { packageJson, packageRoot: await NodeFSP.realpath(packageRoot) }; |
| 497 | } |
| 498 | } catch (error) { |
| 499 | const code = isRecord(error) && typeof error.code === "string" ? error.code : null; |
| 500 | if (code !== "ENOENT" && code !== "ENOTDIR") throw error; |
| 501 | } |
| 502 | if (current === root) break; |
| 503 | current = NodePath.dirname(current); |
| 504 | } |
| 505 | return null; |
| 506 | } |
| 507 | |
| 508 | function dependencyNames(packageJson: PackageJson): ReadonlyArray<string> { |
| 509 | return [ |
| 510 | ...new Set([ |
| 511 | ...Object.keys(packageJson.dependencies ?? {}), |
| 512 | ...Object.keys(packageJson.optionalDependencies ?? {}), |
| 513 | ]), |
| 514 | ].sort((left, right) => left.localeCompare(right)); |
| 515 | } |
| 516 | |
| 517 | interface ExportTarget { |
| 518 | readonly path: string; |
| 519 | readonly underTypesCondition: boolean; |
| 520 | } |
| 521 | |
| 522 | function exportTargets(value: unknown, underTypesCondition = false): ReadonlyArray<ExportTarget> { |
| 523 | if (typeof value === "string") return [{ path: value, underTypesCondition }]; |
| 524 | if (Array.isArray(value)) |
| 525 | return value.flatMap((item) => exportTargets(item, underTypesCondition)); |
| 526 | if (value === null || typeof value !== "object") return []; |
| 527 | return Object.entries(value).flatMap(([key, item]) => |
| 528 | exportTargets(item, underTypesCondition || key.startsWith("types") || key === "typings"), |
| 529 | ); |
| 530 | } |
| 531 | |
| 532 | function isTypeDeclaration(target: ExportTarget): boolean { |
| 533 | return ( |
| 534 | target.underTypesCondition || |
| 535 | /\.d\.[cm]?ts$/u.test(target.path) || |
| 536 | target.path === "./package.json" |
| 537 | ); |
| 538 | } |
| 539 | |
| 540 | function isDeclared(value: unknown): boolean { |
| 541 | if (typeof value === "string") return value.trim() !== ""; |
| 542 | return value !== null && typeof value === "object" && Object.keys(value).length > 0; |
| 543 | } |
| 544 | |
| 545 | async function fileExists(path: string): Promise<boolean> { |
| 546 | try { |
| 547 | await NodeFSP.access(path); |
| 548 | return true; |
| 549 | } catch { |
| 550 | return false; |
| 551 | } |
| 552 | } |
| 553 | |
| 554 | /** Type declarations plus no JS entry mean nothing ships; a types name/condition alone does not prove that. */ |
| 555 | async function isTypeOnlyPackage(packageJson: PackageJson, packageRoot: string): Promise<boolean> { |
| 556 | const targets = exportTargets(packageJson.exports); |
| 557 | const declaresTypes = |
| 558 | isDeclared(packageJson.types) || |
| 559 | isDeclared(packageJson.typings) || |
| 560 | targets.some(isTypeDeclaration); |
| 561 | if (!declaresTypes) return false; |
| 562 | const entries = [ |
| 563 | packageJson.main, |
| 564 | packageJson.module, |
| 565 | packageJson.browser, |
| 566 | packageJson["react-native"], |
| 567 | packageJson.bin, |
| 568 | packageJson.style, |
| 569 | packageJson.sass, |
| 570 | ]; |
| 571 | if (entries.some(isDeclared) || targets.some((target) => !isTypeDeclaration(target))) { |
| 572 | return false; |
| 573 | } |
| 574 | // Without `exports`, Node still loads the package's index file, an empty `main` included. |
| 575 | if (packageJson.exports !== undefined && packageJson.exports !== null) return true; |
| 576 | for (const indexFile of ["index.js", "index.json", "index.node"]) { |
| 577 | if (await fileExists(NodePath.join(packageRoot, indexFile))) return false; |
| 578 | } |
| 579 | return true; |
| 580 | } |
| 581 | |
| 582 | async function collectProductionDependencyPackages( |
| 583 | packageManifests: ReadonlyArray<ThirdPartyLicensePackageManifest>, |
| 584 | ): Promise<PackageCollection> { |
| 585 | const collection: PackageCollection = { |
| 586 | byIdentity: new Map(), |
| 587 | }; |
| 588 | const visited = new Set<string>(); |
| 589 | |
| 590 | const visitManifest = async (packageJsonPath: string, bundle: string): Promise<void> => { |
| 591 | const packageJson = await readPackageJson(packageJsonPath); |
| 592 | for (const dependencyName of dependencyNames(packageJson)) { |
| 593 | const resolved = await resolveDependencyPackage(dependencyName, packageJsonPath); |
| 594 | if (!resolved) continue; |
| 595 | const visitKey = `${bundle}:${resolved.packageRoot}`; |
| 596 | if (visited.has(visitKey)) continue; |
| 597 | visited.add(visitKey); |
| 598 | |
| 599 | const dependencyPackageJsonPath = NodePath.join(resolved.packageRoot, "package.json"); |
| 600 | const name = |
| 601 | typeof resolved.packageJson.name === "string" ? resolved.packageJson.name : dependencyName; |
| 602 | // Type-only packages ship nothing, but what they depend on may, so the walk goes on below. |
| 603 | if ( |
| 604 | !name.startsWith(FIRST_PARTY_PACKAGE_PREFIX) && |
| 605 | !(await isTypeOnlyPackage(resolved.packageJson, resolved.packageRoot)) |
| 606 | ) { |
| 607 | const identity = packageIdentity(resolved.packageJson, resolved.packageRoot); |
| 608 | const existing = collection.byIdentity.get(identity); |
| 609 | if (existing) { |
| 610 | existing.bundles.add(bundle); |
| 611 | } else { |
| 612 | collection.byIdentity.set(identity, { |
| 613 | bundles: new Set([bundle]), |
| 614 | packageJson: resolved.packageJson, |
| 615 | packageRoot: resolved.packageRoot, |
| 616 | }); |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | await visitManifest(dependencyPackageJsonPath, bundle); |
| 621 | } |
| 622 | }; |
| 623 | |
| 624 | for (const manifest of packageManifests) { |
| 625 | await visitManifest(asPath(manifest.path), manifest.bundle); |
| 626 | } |
| 627 | return collection; |
| 628 | } |
| 629 | |
| 630 | function moduleFilePath(moduleId: string): string | null { |
| 631 | if (moduleId.startsWith("\0") || moduleId.includes("\0")) return null; |
| 632 | const withoutQuery = moduleId.split(/[?#]/, 1)[0] ?? moduleId; |
| 633 | const viteFilePath = withoutQuery.startsWith("/@fs/") |
| 634 | ? withoutQuery.slice("/@fs/".length) |
| 635 | : withoutQuery; |
| 636 | const filePath = withoutQuery.startsWith("file:") |
| 637 | ? NodeURL.fileURLToPath(withoutQuery) |
| 638 | : /^[A-Za-z]:[\\/]/.test(viteFilePath) |
| 639 | ? viteFilePath |
| 640 | : NodePath.resolve("/", viteFilePath); |
| 641 | const normalized = filePath.replaceAll("\\", "/"); |
| 642 | return normalized.includes("/node_modules/") ? filePath : null; |
| 643 | } |
| 644 | |
| 645 | async function addBundledModulePackages( |
| 646 | collection: PackageCollection, |
| 647 | moduleIds: ReadonlyArray<string>, |
| 648 | bundle: string, |
| 649 | ): Promise<void> { |
| 650 | for (const moduleId of moduleIds) { |
| 651 | const filePath = moduleFilePath(moduleId); |
| 652 | if (!filePath) continue; |
| 653 | let found: Awaited<ReturnType<typeof findPackageRoot>>; |
| 654 | try { |
| 655 | found = await findPackageRoot(await NodeFSP.realpath(filePath)); |
| 656 | } catch (error) { |
| 657 | const code = isRecord(error) && typeof error.code === "string" ? error.code : null; |
| 658 | if (code === "ENOENT" || code === "ENOTDIR") continue; |
| 659 | throw error; |
| 660 | } |
| 661 | if (!found || typeof found.packageJson.name !== "string") continue; |
| 662 | if (found.packageJson.name.startsWith(FIRST_PARTY_PACKAGE_PREFIX)) continue; |
| 663 | const identity = packageIdentity(found.packageJson, found.packageRoot); |
| 664 | const existing = collection.byIdentity.get(identity); |
| 665 | if (existing) { |
| 666 | existing.bundles.add(bundle); |
| 667 | } else { |
| 668 | collection.byIdentity.set(identity, { |
| 669 | bundles: new Set([bundle]), |
| 670 | packageJson: found.packageJson, |
| 671 | packageRoot: found.packageRoot, |
| 672 | }); |
| 673 | } |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | function normalizeLicense(packageJson: PackageJson): string | null { |
| 678 | if (typeof packageJson.license === "string" && packageJson.license.trim().length > 0) { |
| 679 | return packageJson.license.trim(); |
| 680 | } |
| 681 | if (isRecord(packageJson.license) && typeof packageJson.license.type === "string") { |
| 682 | return packageJson.license.type.trim() || null; |
| 683 | } |
| 684 | const declaredLicenses = Array.isArray(packageJson.license) |
| 685 | ? packageJson.license |
| 686 | : packageJson.licenses; |
| 687 | if (Array.isArray(declaredLicenses)) { |
| 688 | const licenses = declaredLicenses |
| 689 | .map((entry) => { |
| 690 | if (typeof entry === "string") return entry.trim(); |
| 691 | if (isRecord(entry) && typeof entry.type === "string") return entry.type.trim(); |
| 692 | return ""; |
| 693 | }) |
| 694 | .filter((entry) => entry.length > 0); |
| 695 | if (licenses.length > 0) return licenses.join(" OR "); |
| 696 | } |
| 697 | return null; |
| 698 | } |
| 699 | |
| 700 | function normalizeRepositoryUrl(value: unknown): string | null { |
| 701 | const raw = |
| 702 | typeof value === "string" |
| 703 | ? value |
| 704 | : isRecord(value) && typeof value.url === "string" |
| 705 | ? value.url |
| 706 | : null; |
| 707 | if (!raw) return null; |
| 708 | const trimmed = raw.trim(); |
| 709 | if (trimmed.startsWith("github:")) return `https://github.com/${trimmed.slice(7)}`; |
| 710 | const normalized = trimmed |
| 711 | .replace(/^git\+ssh:\/\/git@github\.com\//, "https://github.com/") |
| 712 | .replace(/^git\+/, "") |
| 713 | .replace(/^git@github\.com:/, "https://github.com/") |
| 714 | .replace(/^ssh:\/\/(?:git@)?github\.com\//, "https://github.com/") |
| 715 | .replace(/^git:\/\/github\.com\//, "https://github.com/") |
| 716 | .replace(/#.*$/, "") |
| 717 | .replace(/\.git$/, ""); |
| 718 | if (/^[\w.-]+\/[\w.-]+$/.test(normalized)) return `https://github.com/${normalized}`; |
| 719 | return normalized; |
| 720 | } |
| 721 | |
| 722 | function packageSourceUrl(packageJson: PackageJson): string | null { |
| 723 | if (typeof packageJson.homepage === "string" && packageJson.homepage.trim().length > 0) { |
| 724 | return packageJson.homepage.trim(); |
| 725 | } |
| 726 | return normalizeRepositoryUrl(packageJson.repository); |
| 727 | } |
| 728 | |
| 729 | async function readPackageNoticeText(packageRoot: string): Promise<string | null> { |
| 730 | const noticeFiles: string[] = []; |
| 731 | const rootEntries = await NodeFSP.readdir(packageRoot, { withFileTypes: true }); |
| 732 | noticeFiles.push( |
| 733 | ...rootEntries |
| 734 | .filter((entry) => entry.isFile() && isNoticeTextFile(entry.name)) |
| 735 | .map((entry) => entry.name), |
| 736 | ); |
| 737 | |
| 738 | const collectNestedNoticeFiles = async (directory: string, depth: number): Promise<void> => { |
| 739 | const directoryEntries = await NodeFSP.readdir(NodePath.join(packageRoot, directory), { |
| 740 | withFileTypes: true, |
| 741 | }); |
| 742 | await Promise.all( |
| 743 | directoryEntries.map(async (entry) => { |
| 744 | const relativePath = NodePath.join(directory, entry.name); |
| 745 | if (entry.isFile() && isNoticeTextFile(entry.name)) { |
| 746 | noticeFiles.push(relativePath); |
| 747 | return; |
| 748 | } |
| 749 | if ( |
| 750 | depth > 0 && |
| 751 | entry.isDirectory() && |
| 752 | entry.name !== "node_modules" && |
| 753 | entry.name !== ".git" |
| 754 | ) { |
| 755 | await collectNestedNoticeFiles(relativePath, depth - 1); |
| 756 | } |
| 757 | }), |
| 758 | ); |
| 759 | }; |
| 760 | await Promise.all( |
| 761 | rootEntries |
| 762 | .filter( |
| 763 | (entry) => entry.isDirectory() && entry.name !== "node_modules" && entry.name !== ".git", |
| 764 | ) |
| 765 | .map((entry) => collectNestedNoticeFiles(entry.name, 2)), |
| 766 | ); |
| 767 | noticeFiles.sort((left, right) => left.localeCompare(right)); |
| 768 | if (noticeFiles.length === 0) return null; |
| 769 | |
| 770 | const sections: string[] = []; |
| 771 | for (const fileName of noticeFiles) { |
| 772 | const contents = (await NodeFSP.readFile(NodePath.join(packageRoot, fileName), "utf8")).trim(); |
| 773 | if (contents.length === 0) continue; |
| 774 | sections.push(noticeFiles.length === 1 ? contents : `${fileName}\n\n${contents}`); |
| 775 | } |
| 776 | return sections.length > 0 ? sections.join("\n\n---\n\n") : null; |
| 777 | } |
| 778 | |
| 779 | function repositoryNoticeKey(packageJson: PackageJson, license: string): string | null { |
| 780 | const repositoryUrl = normalizeRepositoryUrl(packageJson.repository); |
| 781 | return repositoryUrl ? `${repositoryUrl.toLowerCase()}\n${license.toLowerCase()}` : null; |
| 782 | } |
| 783 | |
| 784 | async function collectRepositoryNotices( |
| 785 | collection: PackageCollection, |
| 786 | packageNotices: Map<string, Promise<string | null>>, |
| 787 | ): Promise<ReadonlyMap<string, string>> { |
| 788 | const notices = new Map<string, string>(); |
| 789 | const candidates = await Promise.all( |
| 790 | [...collection.byIdentity.values()].map(async (collected) => { |
| 791 | const license = normalizeLicense(collected.packageJson); |
| 792 | if (!license) return null; |
| 793 | const key = repositoryNoticeKey(collected.packageJson, license); |
| 794 | if (!key) return null; |
| 795 | const noticeText = await packageNoticeText(collected.packageRoot, packageNotices); |
| 796 | return noticeText ? { key, noticeText } : null; |
| 797 | }), |
| 798 | ); |
| 799 | for (const candidate of candidates) { |
| 800 | if (candidate && !notices.has(candidate.key)) notices.set(candidate.key, candidate.noticeText); |
| 801 | } |
| 802 | return notices; |
| 803 | } |
| 804 | |
| 805 | function packageNoticeText( |
| 806 | packageRoot: string, |
| 807 | cache: Map<string, Promise<string | null>>, |
| 808 | ): Promise<string | null> { |
| 809 | const existing = cache.get(packageRoot); |
| 810 | if (existing) return existing; |
| 811 | const notice = readPackageNoticeText(packageRoot); |
| 812 | cache.set(packageRoot, notice); |
| 813 | return notice; |
| 814 | } |
| 815 | |
| 816 | function findPackageOverride( |
| 817 | overrides: ReadonlyArray<PackageNoticeOverrideConfigEntry>, |
| 818 | name: string, |
| 819 | version: string, |
| 820 | packageJson: PackageJson, |
| 821 | ): PackageNoticeOverrideConfigEntry | undefined { |
| 822 | const repositoryUrl = normalizeRepositoryUrl(packageJson.repository)?.toLowerCase(); |
| 823 | const matchesRepository = (override: PackageNoticeOverrideConfigEntry) => |
| 824 | repositoryUrl !== undefined && |
| 825 | override.repositoryUrl !== undefined && |
| 826 | normalizeRepositoryUrl(override.repositoryUrl)?.toLowerCase() === repositoryUrl; |
| 827 | return ( |
| 828 | overrides.find((override) => override.name === name && override.version === version) ?? |
| 829 | overrides.find((override) => override.name === name && override.version === undefined) ?? |
| 830 | overrides.find((override) => matchesRepository(override) && override.version === version) ?? |
| 831 | overrides.find((override) => matchesRepository(override) && override.version === undefined) |
| 832 | ); |
| 833 | } |
| 834 | |
| 835 | async function packageEntry( |
| 836 | collected: CollectedPackage, |
| 837 | config: ThirdPartyLicensesConfig, |
| 838 | configDirectory: string, |
| 839 | packageNotices: Map<string, Promise<string | null>>, |
| 840 | repositoryNotices: ReadonlyMap<string, string>, |
| 841 | ): Promise<ThirdPartyLicenseEntry> { |
| 842 | const name = |
| 843 | typeof collected.packageJson.name === "string" |
| 844 | ? collected.packageJson.name |
| 845 | : NodePath.basename(collected.packageRoot); |
| 846 | const version = |
| 847 | typeof collected.packageJson.version === "string" ? collected.packageJson.version : "unknown"; |
| 848 | const override = findPackageOverride( |
| 849 | config.packageOverrides, |
| 850 | name, |
| 851 | version, |
| 852 | collected.packageJson, |
| 853 | ); |
| 854 | const license = override?.license ?? normalizeLicense(collected.packageJson); |
| 855 | if (!license || /^(?:unlicensed|proprietary)$/i.test(license)) { |
| 856 | throw new Error( |
| 857 | `${name}@${version} does not declare a distributable license. Add a package override in the third-party license config if the package publishes its notice elsewhere.`, |
| 858 | ); |
| 859 | } |
| 860 | |
| 861 | const repositoryKey = repositoryNoticeKey(collected.packageJson, license); |
| 862 | const noticeText = override?.generatedNotices |
| 863 | ? await generatedNoticeText(override.generatedNotices, configDirectory) |
| 864 | : override?.noticeFile |
| 865 | ? ( |
| 866 | await NodeFSP.readFile(NodePath.resolve(configDirectory, override.noticeFile), "utf8") |
| 867 | ).trim() |
| 868 | : ((await packageNoticeText(collected.packageRoot, packageNotices)) ?? |
| 869 | (repositoryKey ? repositoryNotices.get(repositoryKey) : undefined)); |
| 870 | if (!noticeText) { |
| 871 | throw new Error( |
| 872 | `${name}@${version} does not include a license or notice file. Add a package override with "noticeFile" or "generatedNotice" in the third-party license config.`, |
| 873 | ); |
| 874 | } |
| 875 | |
| 876 | return { |
| 877 | bundles: [...collected.bundles].sort((left, right) => left.localeCompare(right)), |
| 878 | kind: "package", |
| 879 | license, |
| 880 | name, |
| 881 | noticeText, |
| 882 | sourceUrl: override?.sourceUrl ?? packageSourceUrl(collected.packageJson), |
| 883 | version, |
| 884 | }; |
| 885 | } |
| 886 | |
| 887 | async function customEntries( |
| 888 | config: ThirdPartyLicensesConfig, |
| 889 | configDirectory: string, |
| 890 | includedBundles: ReadonlySet<string>, |
| 891 | ): Promise<ReadonlyArray<ThirdPartyLicenseEntry>> { |
| 892 | const deviceToolVersions: unknown = JSON.parse( |
| 893 | await NodeFSP.readFile( |
| 894 | new URL("../../apps/server/src/device/deviceToolVersions.json", import.meta.url), |
| 895 | "utf8", |
| 896 | ), |
| 897 | ); |
| 898 | if (!isRecord(deviceToolVersions)) throw new Error("Device tool versions must be an object."); |
| 899 | const entries = await Promise.all( |
| 900 | config.customNotices |
| 901 | .filter( |
| 902 | (notice) => |
| 903 | (notice.includeInBundles ?? notice.bundles) === undefined || |
| 904 | (notice.includeInBundles ?? notice.bundles)?.some((bundle) => |
| 905 | includedBundles.has(bundle), |
| 906 | ), |
| 907 | ) |
| 908 | .map(async (notice) => { |
| 909 | const noticeText = notice.generatedNotices |
| 910 | ? await generatedNoticeText(notice.generatedNotices, configDirectory) |
| 911 | : ( |
| 912 | await Promise.all( |
| 913 | notice.noticeFiles!.map(async (noticeFile) => { |
| 914 | const contents = ( |
| 915 | await NodeFSP.readFile(NodePath.resolve(configDirectory, noticeFile), "utf8") |
| 916 | ).trim(); |
| 917 | if (contents.length === 0) { |
| 918 | throw new Error(`Custom third-party notice "${notice.name}" is empty.`); |
| 919 | } |
| 920 | return contents; |
| 921 | }), |
| 922 | ) |
| 923 | ).join("\n\n---\n\n"); |
| 924 | if (noticeText.length === 0) { |
| 925 | throw new Error(`Custom third-party notice "${notice.name}" is empty.`); |
| 926 | } |
| 927 | return { |
| 928 | bundles: [...(notice.bundles ?? ["assets"])].sort((left, right) => |
| 929 | left.localeCompare(right), |
| 930 | ), |
| 931 | kind: "custom" as const, |
| 932 | license: notice.license, |
| 933 | name: notice.name, |
| 934 | noticeText, |
| 935 | sourceUrl: notice.sourceUrl ?? null, |
| 936 | version: |
| 937 | readOptionalString(deviceToolVersions, notice.name, "Device tool versions") ?? |
| 938 | notice.version ?? |
| 939 | null, |
| 940 | }; |
| 941 | }), |
| 942 | ); |
| 943 | return entries; |
| 944 | } |
| 945 | |
| 946 | function entrySort(left: ThirdPartyLicenseEntry, right: ThirdPartyLicenseEntry): number { |
| 947 | return ( |
| 948 | left.name.localeCompare(right.name) || |
| 949 | (left.version ?? "").localeCompare(right.version ?? "") || |
| 950 | left.kind.localeCompare(right.kind) |
| 951 | ); |
| 952 | } |
| 953 | |
| 954 | function assertUniqueEntries(entries: ReadonlyArray<ThirdPartyLicenseEntry>): void { |
| 955 | const identities = new Set<string>(); |
| 956 | for (const entry of entries) { |
| 957 | const identity = JSON.stringify([entry.kind, entry.name, entry.version]); |
| 958 | if (identities.has(identity)) { |
| 959 | throw new Error( |
| 960 | `Third-party license generation found a duplicate ${entry.kind} notice for ${entry.name}${entry.version ? `@${entry.version}` : ""}.`, |
| 961 | ); |
| 962 | } |
| 963 | identities.add(identity); |
| 964 | } |
| 965 | } |
| 966 | |
| 967 | export async function generateThirdPartyLicenseManifest(input: { |
| 968 | readonly configFile?: string | URL; |
| 969 | readonly packageManifests: ReadonlyArray<ThirdPartyLicensePackageManifest>; |
| 970 | readonly bundledModuleIds?: ReadonlyArray<string>; |
| 971 | readonly bundleName?: string; |
| 972 | }): Promise<ThirdPartyLicenseManifest> { |
| 973 | const [{ config, directory }, collection] = await Promise.all([ |
| 974 | readConfig(input.configFile), |
| 975 | collectProductionDependencyPackages(input.packageManifests), |
| 976 | ]); |
| 977 | if (input.bundledModuleIds && input.bundleName) { |
| 978 | await addBundledModulePackages(collection, input.bundledModuleIds, input.bundleName); |
| 979 | } |
| 980 | |
| 981 | const packageNotices = new Map<string, Promise<string | null>>(); |
| 982 | const repositoryNotices = await collectRepositoryNotices(collection, packageNotices); |
| 983 | |
| 984 | const packageEntryResults = await Promise.allSettled( |
| 985 | [...collection.byIdentity.values()].map((collected) => |
| 986 | packageEntry(collected, config, directory, packageNotices, repositoryNotices), |
| 987 | ), |
| 988 | ); |
| 989 | const failures = packageEntryResults.flatMap((result) => |
| 990 | result.status === "rejected" |
| 991 | ? [result.reason instanceof Error ? result.reason.message : String(result.reason)] |
| 992 | : [], |
| 993 | ); |
| 994 | if (failures.length > 0) { |
| 995 | throw new Error( |
| 996 | `Third-party license generation found ${String(failures.length)} invalid package notice${failures.length === 1 ? "" : "s"}:\n${failures.map((failure) => `- ${failure}`).join("\n")}`, |
| 997 | ); |
| 998 | } |
| 999 | const packageEntries = packageEntryResults.flatMap((result) => |
| 1000 | result.status === "fulfilled" ? [result.value] : [], |
| 1001 | ); |
| 1002 | const includedBundles = new Set(input.packageManifests.map((manifest) => manifest.bundle)); |
| 1003 | if (input.bundleName) includedBundles.add(input.bundleName); |
| 1004 | const manualEntries = await customEntries(config, directory, includedBundles); |
| 1005 | const entries = [...packageEntries, ...manualEntries].sort(entrySort); |
| 1006 | assertUniqueEntries(entries); |
| 1007 | return { |
| 1008 | schemaVersion: 1, |
| 1009 | entries, |
| 1010 | }; |
| 1011 | } |
| 1012 | |
| 1013 | function moduleIdsFromBundle(bundle: unknown): ReadonlyArray<string> { |
| 1014 | const ids = new Set<string>(); |
| 1015 | if (!isRecord(bundle)) return []; |
| 1016 | for (const output of Object.values(bundle)) { |
| 1017 | if (!isRecord(output) || output.type !== "chunk" || !isRecord(output.modules)) continue; |
| 1018 | for (const id of Object.keys(output.modules)) ids.add(id); |
| 1019 | } |
| 1020 | return [...ids]; |
| 1021 | } |
| 1022 | |
| 1023 | function serializeManifest(manifest: ThirdPartyLicenseManifest): string { |
| 1024 | return `${JSON.stringify(manifest)}\n`; |
| 1025 | } |
| 1026 | |
| 1027 | export function thirdPartyLicensesPlugin(options: ThirdPartyLicensesPluginOptions): Plugin { |
| 1028 | return { |
| 1029 | name: "t3code:third-party-licenses", |
| 1030 | configureServer(server) { |
| 1031 | let manifestPromise: Promise<ThirdPartyLicenseManifest> | null = null; |
| 1032 | server.middlewares.use((request, response, next) => { |
| 1033 | if (request.url?.split("?", 1)[0] !== `/${THIRD_PARTY_LICENSES_FILE_NAME}`) { |
| 1034 | next(); |
| 1035 | return; |
| 1036 | } |
| 1037 | manifestPromise ??= generateThirdPartyLicenseManifest({ |
| 1038 | packageManifests: options.packageManifests, |
| 1039 | bundleName: options.bundleName, |
| 1040 | ...(options.configFile !== undefined ? { configFile: options.configFile } : {}), |
| 1041 | }).catch((error: unknown) => { |
| 1042 | manifestPromise = null; |
| 1043 | throw error; |
| 1044 | }); |
| 1045 | void manifestPromise.then( |
| 1046 | (manifest) => { |
| 1047 | response.statusCode = 200; |
| 1048 | response.setHeader("Content-Type", "application/json; charset=utf-8"); |
| 1049 | response.setHeader("Cache-Control", "no-store"); |
| 1050 | response.end(serializeManifest(manifest)); |
| 1051 | }, |
| 1052 | (error: unknown) => { |
| 1053 | next(error instanceof Error ? error : new Error(String(error))); |
| 1054 | }, |
| 1055 | ); |
| 1056 | }); |
| 1057 | }, |
| 1058 | async generateBundle(_outputOptions, bundle) { |
| 1059 | const manifest = await generateThirdPartyLicenseManifest({ |
| 1060 | packageManifests: options.packageManifests, |
| 1061 | bundledModuleIds: moduleIdsFromBundle(bundle), |
| 1062 | bundleName: options.bundleName, |
| 1063 | ...(options.configFile !== undefined ? { configFile: options.configFile } : {}), |
| 1064 | }); |
| 1065 | this.emitFile({ |
| 1066 | type: "asset", |
| 1067 | fileName: THIRD_PARTY_LICENSES_FILE_NAME, |
| 1068 | source: serializeManifest(manifest), |
| 1069 | }); |
| 1070 | }, |
| 1071 | }; |
| 1072 | } |