@determinate-systems/detsys-ts 1.0.0 → 2.0.0
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/dist/index.d.mts +263 -31
- package/dist/index.mjs +1069 -451
- package/dist/index.mjs.map +1 -1
- package/package.json +11 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["fs","os","exec","exec","actionsExec","correlation.identify","platform.getArchOs","platform.getNixPlatform","stringifyError","os","fsConstants"],"sources":["../src/linux-release-info.ts","../src/actions-core-platform.ts","../src/errors.ts","../src/backtrace.ts","../src/checksums.ts","../src/correlation.ts","../src/ids-host.ts","../src/inputs.ts","../src/platform.ts","../src/sourcedef.ts","../src/index.ts"],"sourcesContent":["/*!\n * linux-release-info\n * Get Linux release info (distribution name, version, arch, release, etc.)\n * from '/etc/os-release' or '/usr/lib/os-release' files and from native os\n * module. On Windows and Darwin platforms it only returns common node os module\n * info (platform, hostname, release, and arch)\n *\n * Licensed under MIT\n * Copyright (c) 2018-2020 [Samuel Carreira]\n */\n// NOTE: we depend on this directly to get around some un-fun issues with mixing CommonJS\n// and ESM in the bundle. We've modified the original logic to improve things like typing\n// and fixing ESLint issues. Originally drawn from:\n// https://github.com/samuelcarreira/linux-release-info/blob/84a91aa5442b47900da03020c590507545d3dc74/src/index.ts\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport { promisify } from \"node:util\";\n\nconst readFileAsync = promisify(fs.readFile);\n\nexport interface LinuxReleaseInfoOptions {\n /**\n * read mode, possible values: 'async' and 'sync'\n *\n * @default 'async'\n */\n mode?: \"async\" | \"sync\";\n /**\n * custom complete file path with os info default null/none\n * if not provided the system will search on the '/etc/os-release'\n * and '/usr/lib/os-release' files\n *\n * @default null\n */\n customFile?: string | null | undefined;\n /**\n * if true, show console debug messages\n *\n * @default false\n */\n debug?: boolean;\n}\n\nconst linuxReleaseInfoOptionsDefaults: LinuxReleaseInfoOptions = {\n mode: \"async\",\n customFile: null,\n debug: false,\n};\n\n/**\n * Get OS release info from 'os-release' file and from native os module\n * on Windows or Darwin it only returns common os module info\n * (uses native fs module)\n * @returns {object} info from the current os\n */\nexport function releaseInfo(infoOptions: LinuxReleaseInfoOptions): object {\n const options = { ...linuxReleaseInfoOptionsDefaults, ...infoOptions };\n\n const searchOsReleaseFileList: string[] = osReleaseFileList(\n options.customFile,\n );\n\n if (os.type() !== \"Linux\") {\n if (options.mode === \"sync\") {\n return getOsInfo();\n } else {\n return Promise.resolve(getOsInfo());\n }\n }\n\n if (options.mode === \"sync\") {\n return readSyncOsreleaseFile(searchOsReleaseFileList, options);\n } else {\n return Promise.resolve(\n readAsyncOsReleaseFile(searchOsReleaseFileList, options),\n );\n }\n}\n\n/**\n * Format file data: convert data to object keys/values\n *\n * @param {object} sourceData Source object to be appended\n * @param {string} srcParseData Input file data to be parsed\n * @returns {object} Formated object\n */\nfunction formatFileData(sourceData: OsInfo, srcParseData: string): OsInfo {\n const lines: string[] = srcParseData.split(\"\\n\");\n\n for (const line of lines) {\n const lineData = line.split(\"=\");\n\n if (lineData.length === 2) {\n lineData[1] = lineData[1].replace(/[\"'\\r]/gi, \"\"); // remove quotes and return character\n\n Object.defineProperty(sourceData, lineData[0].toLowerCase(), {\n value: lineData[1],\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n }\n\n return sourceData;\n}\n\n/**\n * Export a list of os-release files\n *\n * @param {string} customFile optional custom complete filepath\n * @returns {array} list of os-release files\n */\nfunction osReleaseFileList(customFile: string | null | undefined): string[] {\n const DEFAULT_OS_RELEASE_FILES = [\"/etc/os-release\", \"/usr/lib/os-release\"];\n\n if (!customFile) {\n return DEFAULT_OS_RELEASE_FILES;\n } else {\n return Array(customFile);\n }\n}\n\n/**\n * Operating system info.\n */\ntype OsInfo = {\n type: string;\n platform: string;\n hostname: string;\n arch: string;\n release: string;\n};\n\n/**\n * Get OS Basic Info\n * (uses node 'os' native module)\n *\n * @returns {OsInfo} os basic info\n */\nfunction getOsInfo(): OsInfo {\n return {\n type: os.type(),\n platform: os.platform(),\n hostname: os.hostname(),\n arch: os.arch(),\n release: os.release(),\n };\n}\n\n/* Helper functions */\n\nasync function readAsyncOsReleaseFile(\n fileList: string[],\n options: LinuxReleaseInfoOptions,\n): Promise<OsInfo> {\n let fileData = null;\n\n for (const osReleaseFile of fileList) {\n try {\n if (options.debug) {\n /* eslint-disable no-console */\n console.log(`Trying to read '${osReleaseFile}'...`);\n }\n\n fileData = await readFileAsync(osReleaseFile, \"binary\");\n\n if (options.debug) {\n console.log(`Read data:\\n${fileData}`);\n }\n\n break;\n } catch (error) {\n if (options.debug) {\n console.error(error);\n }\n }\n }\n\n if (fileData === null) {\n throw new Error(\"Cannot read os-release file!\");\n //return getOsInfo();\n }\n\n return formatFileData(getOsInfo(), fileData);\n}\n\nfunction readSyncOsreleaseFile(\n releaseFileList: string[],\n options: LinuxReleaseInfoOptions,\n): OsInfo {\n let fileData = null;\n\n for (const osReleaseFile of releaseFileList) {\n try {\n if (options.debug) {\n console.log(`Trying to read '${osReleaseFile}'...`);\n }\n\n fileData = fs.readFileSync(osReleaseFile, \"binary\");\n\n if (options.debug) {\n console.log(`Read data:\\n${fileData}`);\n }\n\n break;\n } catch (error) {\n if (options.debug) {\n console.error(error);\n }\n }\n }\n\n if (fileData === null) {\n throw new Error(\"Cannot read os-release file!\");\n //return getOsInfo();\n }\n\n return formatFileData(getOsInfo(), fileData);\n}\n","// MIT, mostly lifted from https://github.com/actions/toolkit/blob/5a736647a123ecf8582376bdaee833fbae5b3847/packages/core/src/platform.ts\n// since it isn't in @actions/core 1.10.1 which is their current release as 2024-04-19.\n// Changes: Replaced the lsb_release call in Linux with `linux-release-info` to parse the os-release file directly.\nimport { releaseInfo } from \"./linux-release-info.js\";\nimport * as actionsCore from \"@actions/core\";\nimport * as exec from \"@actions/exec\";\nimport os from \"os\";\n\n/**\n * The name and version of the Action runner's system.\n */\ntype SystemInfo = {\n name: string;\n version: string;\n};\n\n/**\n * Get the name and version of the current Windows system.\n */\nconst getWindowsInfo = async (): Promise<SystemInfo> => {\n const { stdout: version } = await exec.getExecOutput(\n 'powershell -command \"(Get-CimInstance -ClassName Win32_OperatingSystem).Version\"',\n undefined,\n {\n silent: true,\n },\n );\n\n const { stdout: name } = await exec.getExecOutput(\n 'powershell -command \"(Get-CimInstance -ClassName Win32_OperatingSystem).Caption\"',\n undefined,\n {\n silent: true,\n },\n );\n\n return {\n name: name.trim(),\n version: version.trim(),\n };\n};\n\n/**\n * Get the name and version of the current macOS system.\n */\nconst getMacOsInfo = async (): Promise<SystemInfo> => {\n const { stdout } = await exec.getExecOutput(\"sw_vers\", undefined, {\n silent: true,\n });\n\n const version = stdout.match(/ProductVersion:\\s*(.+)/)?.[1] ?? \"\";\n const name = stdout.match(/ProductName:\\s*(.+)/)?.[1] ?? \"\";\n\n return {\n name,\n version,\n };\n};\n\n/**\n * Get the name and version of the current Linux system.\n */\nconst getLinuxInfo = async (): Promise<SystemInfo> => {\n let data: object = {};\n\n try {\n data = releaseInfo({ mode: \"sync\" });\n actionsCore.debug(`Identified release info: ${JSON.stringify(data)}`);\n } catch (e) {\n actionsCore.debug(`Error collecting release info: ${e}`);\n }\n\n return {\n name: getPropertyViaWithDefault(\n data,\n [\"id\", \"name\", \"pretty_name\", \"id_like\"],\n \"unknown\",\n ),\n version: getPropertyViaWithDefault(\n data,\n [\"version_id\", \"version\", \"version_codename\"],\n \"unknown\",\n ),\n };\n};\n\nfunction getPropertyViaWithDefault<T, Property extends string>(\n data: object,\n names: Property[],\n defaultValue: T,\n): T {\n for (const name of names) {\n const ret: T = getPropertyWithDefault(data, name, defaultValue);\n\n if (ret !== defaultValue) {\n return ret;\n }\n }\n\n return defaultValue;\n}\n\nfunction getPropertyWithDefault<T, Property extends string>(\n data: object,\n name: Property,\n defaultValue: T,\n): T {\n if (!data.hasOwnProperty(name)) {\n return defaultValue;\n }\n\n const value = (data as { [K in Property]: T })[name];\n\n // NB. this check won't work for object instances\n if (typeof value !== typeof defaultValue) {\n return defaultValue;\n }\n\n return value;\n}\n\n/**\n * The Action runner's platform.\n */\nexport const platform = os.platform();\n\n/**\n * The Action runner's architecture.\n */\nexport const arch = os.arch();\n\n/**\n * Whether the Action runner is a Windows system.\n */\nexport const isWindows = platform === \"win32\";\n\n/**\n * Whether the Action runner is a macOS system.\n */\nexport const isMacOS = platform === \"darwin\";\n\n/**\n * Whether the Action runner is a Linux system.\n */\nexport const isLinux = platform === \"linux\";\n\n/**\n * System-level information about the current host (platform, architecture, etc.).\n */\ntype SystemDetails = {\n name: string;\n platform: string;\n arch: string;\n version: string;\n isWindows: boolean;\n isMacOS: boolean;\n isLinux: boolean;\n};\n\n/**\n * Get system-level information about the current host (platform, architecture, etc.).\n */\nexport async function getDetails(): Promise<SystemDetails> {\n return {\n ...(await (isWindows\n ? getWindowsInfo()\n : isMacOS\n ? getMacOsInfo()\n : getLinuxInfo())),\n platform,\n arch,\n isWindows,\n isMacOS,\n isLinux,\n };\n}\n","/**\n * Coerce a value of type `unknown` into a string.\n */\nexport function stringifyError(e: unknown): string {\n if (e instanceof Error) {\n return e.message;\n } else if (typeof e === \"string\") {\n return e;\n } else {\n return JSON.stringify(e);\n }\n}\n","/**\n * @packageDocumentation\n * Collects backtraces for executables for diagnostics\n */\nimport { isLinux, isMacOS } from \"./actions-core-platform.js\";\nimport { stringifyError } from \"./errors.js\";\nimport * as actionsCore from \"@actions/core\";\nimport * as exec from \"@actions/exec\";\nimport { readFile, readdir, stat } from \"node:fs/promises\";\nimport { promisify } from \"node:util\";\nimport { gzip } from \"node:zlib\";\n\n// Give a few seconds buffer, capturing traces that happened a few seconds earlier.\nconst START_SLOP_SECONDS = 5;\n\nexport async function collectBacktraces(\n prefixes: string[],\n programNameDenyList: string[],\n startTimestampMs: number,\n): Promise<Map<string, string>> {\n if (isMacOS) {\n return await collectBacktracesMacOS(\n prefixes,\n programNameDenyList,\n startTimestampMs,\n );\n }\n if (isLinux) {\n return await collectBacktracesSystemd(\n prefixes,\n programNameDenyList,\n startTimestampMs,\n );\n }\n\n return new Map();\n}\n\nexport async function collectBacktracesMacOS(\n prefixes: string[],\n programNameDenyList: string[],\n startTimestampMs: number,\n): Promise<Map<string, string>> {\n const backtraces: Map<string, string> = new Map();\n\n try {\n const { stdout: logJson } = await exec.getExecOutput(\n \"log\",\n [\n \"show\",\n \"--style\",\n \"json\",\n \"--last\",\n // Note we collect the last 1m only, because it should only take a few seconds to write the crash log.\n // Therefore, any crashes before this 1m should be long done by now.\n \"1m\",\n \"--no-info\",\n \"--predicate\",\n \"sender = 'ReportCrash'\",\n ],\n {\n silent: true,\n },\n );\n\n const sussyArray: unknown = JSON.parse(logJson);\n if (!Array.isArray(sussyArray)) {\n throw new Error(`Log json isn't an array: ${logJson}`);\n }\n\n if (sussyArray.length > 0) {\n actionsCore.info(`Collecting crash data...`);\n const delay = async (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n await delay(5000);\n }\n } catch {\n actionsCore.debug(\n \"Failed to check logs for in-progress crash dumps; now proceeding with the assumption that all crash dumps completed.\",\n );\n }\n\n const dirs = [\n [\"system\", \"/Library/Logs/DiagnosticReports/\"],\n [\"user\", `${process.env[\"HOME\"]}/Library/Logs/DiagnosticReports/`],\n ];\n\n for (const [source, dir] of dirs) {\n const fileNames = (await readdir(dir))\n .filter((fileName) => {\n return prefixes.some((prefix) => fileName.startsWith(prefix));\n })\n .filter((fileName) => {\n return !programNameDenyList.some((programName) =>\n fileName.startsWith(programName),\n );\n })\n .filter((fileName) => {\n // macOS creates .diag files periodically, which are called \"microstackshots\".\n // We don't necessarily want those, and they're definitely not crashes.\n // See: https://patents.google.com/patent/US20140237219A1/en\n return !fileName.endsWith(\".diag\");\n });\n\n const doGzip = promisify(gzip);\n for (const fileName of fileNames) {\n try {\n if ((await stat(`${dir}/${fileName}`)).ctimeMs >= startTimestampMs) {\n const logText = await readFile(`${dir}/${fileName}`);\n const buf = await doGzip(logText);\n backtraces.set(\n `backtrace_value_${source}_${fileName}`,\n buf.toString(\"base64\"),\n );\n }\n } catch (innerError: unknown) {\n backtraces.set(\n `backtrace_failure_${source}_${fileName}`,\n stringifyError(innerError),\n );\n }\n }\n }\n\n return backtraces;\n}\n\ntype SystemdCoreDumpInfo = {\n exe: string;\n pid: number;\n};\n\nexport async function collectBacktracesSystemd(\n prefixes: string[],\n programNameDenyList: string[],\n startTimestampMs: number,\n): Promise<Map<string, string>> {\n const sinceSeconds =\n Math.ceil((Date.now() - startTimestampMs) / 1000) + START_SLOP_SECONDS;\n const backtraces: Map<string, string> = new Map();\n\n const coredumps: SystemdCoreDumpInfo[] = [];\n\n try {\n const { stdout: coredumpjson } = await exec.getExecOutput(\n \"coredumpctl\",\n [\"--json=pretty\", \"list\", \"--since\", `${sinceSeconds} seconds ago`],\n {\n silent: true,\n },\n );\n\n const sussyArray: unknown = JSON.parse(coredumpjson);\n if (!Array.isArray(sussyArray)) {\n throw new Error(`Coredump isn't an array: ${coredumpjson}`);\n }\n\n for (const sussyObject of sussyArray) {\n const keys = Object.keys(sussyObject);\n\n if (keys.includes(\"exe\") && keys.includes(\"pid\")) {\n if (\n typeof sussyObject.exe == \"string\" &&\n typeof sussyObject.pid == \"number\"\n ) {\n const execParts = sussyObject.exe.split(\"/\");\n const binaryName = execParts[execParts.length - 1];\n\n if (\n prefixes.some((prefix) => binaryName.startsWith(prefix)) &&\n !programNameDenyList.includes(binaryName)\n ) {\n coredumps.push({\n exe: sussyObject.exe,\n pid: sussyObject.pid,\n });\n }\n } else {\n actionsCore.debug(\n `Mysterious coredump entry missing exe string and/or pid number: ${JSON.stringify(sussyObject)}`,\n );\n }\n } else {\n actionsCore.debug(\n `Mysterious coredump entry missing exe value and/or pid value: ${JSON.stringify(sussyObject)}`,\n );\n }\n }\n } catch (innerError: unknown) {\n actionsCore.debug(\n `Cannot collect backtraces: ${stringifyError(innerError)}`,\n );\n\n return backtraces;\n }\n\n const doGzip = promisify(gzip);\n for (const coredump of coredumps) {\n try {\n const { stdout: logText } = await exec.getExecOutput(\n \"coredumpctl\",\n [\"info\", `${coredump.pid}`],\n {\n silent: true,\n },\n );\n\n const buf = await doGzip(logText);\n backtraces.set(`backtrace_value_${coredump.pid}`, buf.toString(\"base64\"));\n } catch (innerError: unknown) {\n backtraces.set(\n `backtrace_failure_${coredump.pid}`,\n stringifyError(innerError),\n );\n }\n }\n\n return backtraces;\n}\n","/**\n * @packageDocumentation\n * Parsing and hashing helpers for `shasum`-format checksum files, used to\n * hash-lock downloaded artifacts.\n */\nimport { createHash } from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\n\nconst HEX_STRING_RE = /^[0-9a-fA-F]+$/;\n\n/**\n * Parse a `shasum`-format checksums file into a map of filename -> hex digest.\n *\n * Each non-empty line has the shape `<hex-digest><space(s)><filename>`. Lines\n * without a space delimiter are skipped. Invalid hex digests throw, so a\n * malformed file fails loudly rather than silently skipping the entry we\n * care about.\n */\nexport function parseChecksumsFile(text: string): Map<string, string> {\n const result = new Map<string, string>();\n\n for (const record of text.split(/\\r\\n|\\n|\\r/).filter(Boolean)) {\n const delimIndex = record.indexOf(\" \");\n if (delimIndex === -1) {\n continue;\n }\n\n const digest = record.slice(0, delimIndex);\n if (!HEX_STRING_RE.test(digest)) {\n throw new Error(`Invalid digest in checksums file: ${digest}`);\n }\n\n const name = record.slice(delimIndex + 1).trim();\n if (name === \"\") {\n continue;\n }\n\n result.set(name, digest.toLowerCase());\n }\n\n return result;\n}\n\n/**\n * Compute the SHA-256 of a file on disk and return its lowercase hex digest.\n * Streams the file so memory use is constant regardless of size.\n */\nexport async function sha256OfFile(filePath: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const hash = createHash(\"sha256\").setEncoding(\"hex\");\n createReadStream(filePath)\n .once(\"error\", reject)\n .pipe(hash)\n .once(\"finish\", () => resolve(hash.read() as string));\n });\n}\n\n/**\n * Compute the SHA-256 of an in-memory buffer or string and return its\n * lowercase hex digest.\n */\nexport function sha256OfBuffer(data: Buffer | string): string {\n return createHash(\"sha256\").update(data).digest(\"hex\");\n}\n","import * as actionsCore from \"@actions/core\";\nimport { createHash, randomUUID } from \"node:crypto\";\n\nconst OPTIONAL_VARIABLES = [\"INVOCATION_ID\"];\n\n/* eslint-disable camelcase */\n/**\n * JSON sent to server.\n */\nexport type CorrelationProperties = {\n $anon_distinct_id: string;\n $groups: Record<string, string | undefined>;\n $session_id?: string;\n correlation_source: string;\n github_repository_hash?: string;\n github_workflow_hash?: string;\n github_workflow_job_hash?: string;\n github_workflow_run_differentiator_hash?: string;\n github_workflow_run_hash?: string;\n is_ci: boolean;\n};\n\nexport function identify(): CorrelationProperties {\n const repository = hashEnvironmentVariables(\"GHR\", [\n \"GITHUB_SERVER_URL\",\n \"GITHUB_REPOSITORY_OWNER\",\n \"GITHUB_REPOSITORY_OWNER_ID\",\n \"GITHUB_REPOSITORY\",\n \"GITHUB_REPOSITORY_ID\",\n ]);\n\n const run_differentiator = hashEnvironmentVariables(\"GHWJA\", [\n \"GITHUB_SERVER_URL\",\n \"GITHUB_REPOSITORY_OWNER\",\n \"GITHUB_REPOSITORY_OWNER_ID\",\n \"GITHUB_REPOSITORY\",\n \"GITHUB_REPOSITORY_ID\",\n \"GITHUB_WORKFLOW\",\n \"GITHUB_JOB\",\n \"GITHUB_RUN_ID\",\n \"GITHUB_RUN_NUMBER\",\n \"GITHUB_RUN_ATTEMPT\",\n \"INVOCATION_ID\",\n ]);\n\n const ident: CorrelationProperties = {\n $anon_distinct_id: process.env[\"RUNNER_TRACKING_ID\"] || randomUUID(),\n\n correlation_source: \"github-actions\",\n\n github_repository_hash: repository,\n github_workflow_hash: hashEnvironmentVariables(\"GHW\", [\n \"GITHUB_SERVER_URL\",\n \"GITHUB_REPOSITORY_OWNER\",\n \"GITHUB_REPOSITORY_OWNER_ID\",\n \"GITHUB_REPOSITORY\",\n \"GITHUB_REPOSITORY_ID\",\n \"GITHUB_WORKFLOW\",\n ]),\n github_workflow_job_hash: hashEnvironmentVariables(\"GHWJ\", [\n \"GITHUB_SERVER_URL\",\n \"GITHUB_REPOSITORY_OWNER\",\n \"GITHUB_REPOSITORY_OWNER_ID\",\n \"GITHUB_REPOSITORY\",\n \"GITHUB_REPOSITORY_ID\",\n \"GITHUB_WORKFLOW\",\n \"GITHUB_JOB\",\n ]),\n github_workflow_run_hash: hashEnvironmentVariables(\"GHWJR\", [\n \"GITHUB_SERVER_URL\",\n \"GITHUB_REPOSITORY_OWNER\",\n \"GITHUB_REPOSITORY_OWNER_ID\",\n \"GITHUB_REPOSITORY\",\n \"GITHUB_REPOSITORY_ID\",\n \"GITHUB_WORKFLOW\",\n \"GITHUB_JOB\",\n \"GITHUB_RUN_ID\",\n ]),\n github_workflow_run_differentiator_hash: run_differentiator,\n $session_id: run_differentiator,\n $groups: {\n github_repository: repository,\n github_organization: hashEnvironmentVariables(\"GHO\", [\n \"GITHUB_SERVER_URL\",\n \"GITHUB_REPOSITORY_OWNER\",\n \"GITHUB_REPOSITORY_OWNER_ID\",\n ]),\n },\n is_ci: true,\n };\n\n actionsCore.debug(\"Correlation data:\");\n actionsCore.debug(JSON.stringify(ident, null, 2));\n\n return ident;\n}\n\nfunction hashEnvironmentVariables(\n prefix: string,\n variables: string[],\n): undefined | string {\n const hash = createHash(\"sha256\");\n\n for (const varName of variables) {\n let value = process.env[varName];\n\n if (value === undefined) {\n if (OPTIONAL_VARIABLES.includes(varName)) {\n actionsCore.debug(\n `Optional environment variable not set: ${varName} -- substituting with the variable name`,\n );\n value = varName;\n } else {\n actionsCore.debug(\n `Environment variable not set: ${varName} -- can't generate the requested identity`,\n );\n return undefined;\n }\n }\n\n hash.update(value);\n hash.update(\"\\0\");\n }\n\n return `${prefix}-${hash.digest(\"hex\")}`;\n}\n","/**\n * @packageDocumentation\n * Identifies and discovers backend servers for install.determinate.systems\n */\nimport { stringifyError } from \"./errors.js\";\nimport * as actionsCore from \"@actions/core\";\nimport got, { type Got } from \"got\";\nimport type { SrvRecord } from \"node:dns\";\nimport { resolveSrv } from \"node:dns/promises\";\n\nconst DEFAULT_LOOKUP = \"_detsys_ids._tcp.install.determinate.systems.\";\nconst ALLOWED_SUFFIXES = [\n \".install.determinate.systems\",\n \".install.detsys.dev\",\n];\n\nconst DEFAULT_IDS_HOST = \"https://install.determinate.systems\";\nconst LOOKUP = process.env[\"IDS_LOOKUP\"] ?? DEFAULT_LOOKUP;\n\nconst DEFAULT_TIMEOUT = 10_000; // 10 seconds in ms\n\n/**\n * Host information for install.determinate.systems.\n */\nexport class IdsHost {\n private idsProjectName: string;\n private diagnosticsSuffix?: string;\n private runtimeDiagnosticsUrl?: string;\n private prioritizedURLs?: URL[];\n private client?: Got;\n private timeout: number;\n\n constructor(\n idsProjectName: string,\n diagnosticsSuffix: string | undefined,\n runtimeDiagnosticsUrl: string | undefined,\n timeout: number = DEFAULT_TIMEOUT,\n ) {\n this.idsProjectName = idsProjectName;\n this.diagnosticsSuffix = diagnosticsSuffix;\n this.runtimeDiagnosticsUrl = runtimeDiagnosticsUrl;\n this.client = undefined;\n this.timeout = timeout;\n }\n\n async getGot(\n recordFailoverCallback?: (\n incitingError: unknown,\n prevUrl: URL,\n nextUrl: URL,\n ) => void,\n ): Promise<Got> {\n if (this.client === undefined) {\n this.client = got.extend({\n timeout: {\n request: this.timeout,\n },\n\n retry: {\n limit: Math.max((await this.getUrlsByPreference()).length, 3),\n methods: [\"GET\", \"HEAD\"],\n },\n\n hooks: {\n beforeRetry: [\n async (error, retryCount) => {\n const prevUrl = await this.getRootUrl();\n this.markCurrentHostBroken();\n const nextUrl = await this.getRootUrl();\n\n if (recordFailoverCallback !== undefined) {\n recordFailoverCallback(error, prevUrl, nextUrl);\n }\n\n actionsCore.info(\n `Retrying after error ${error.code}, retry #: ${retryCount}`,\n );\n },\n ],\n\n beforeRequest: [\n async (options) => {\n // The getter always returns a URL, even though the setter accepts a string\n const currentUrl: URL = options.url as URL;\n\n if (this.isUrlSubjectToDynamicUrls(currentUrl)) {\n const newUrl: URL = new URL(currentUrl);\n\n const url: URL = await this.getRootUrl();\n newUrl.host = url.host;\n\n options.url = newUrl;\n actionsCore.debug(`Transmuted ${currentUrl} into ${newUrl}`);\n } else {\n actionsCore.debug(`No transmutations on ${currentUrl}`);\n }\n },\n ],\n },\n });\n }\n\n return this.client;\n }\n\n markCurrentHostBroken(): void {\n this.prioritizedURLs?.shift();\n }\n\n setPrioritizedUrls(urls: URL[]): void {\n this.prioritizedURLs = urls;\n }\n\n isUrlSubjectToDynamicUrls(url: URL): boolean {\n if (url.origin === DEFAULT_IDS_HOST) {\n return true;\n }\n\n for (const suffix of ALLOWED_SUFFIXES) {\n if (url.host.endsWith(suffix)) {\n return true;\n }\n }\n\n return false;\n }\n\n async getDynamicRootUrl(): Promise<URL | undefined> {\n const idsHost = process.env[\"IDS_HOST\"];\n if (idsHost !== undefined) {\n try {\n return new URL(idsHost);\n } catch (err: unknown) {\n actionsCore.error(\n `IDS_HOST environment variable is not a valid URL. Ignoring. ${stringifyError(err)}`,\n );\n }\n }\n\n let url: URL | undefined = undefined;\n try {\n const urls = await this.getUrlsByPreference();\n url = urls[0];\n } catch (err: unknown) {\n actionsCore.error(\n `Error collecting IDS URLs by preference: ${stringifyError(err)}`,\n );\n }\n\n if (url === undefined) {\n return undefined;\n } else {\n // This is a load-bearing `new URL(url)` so that callers can't mutate\n // getRootUrl's return value.\n return new URL(url);\n }\n }\n\n async getRootUrl(): Promise<URL> {\n const url = await this.getDynamicRootUrl();\n\n if (url === undefined) {\n return new URL(DEFAULT_IDS_HOST);\n }\n\n return url;\n }\n\n async getDiagnosticsUrl(): Promise<URL | undefined> {\n if (this.runtimeDiagnosticsUrl === \"\") {\n // User specifically set the diagnostics URL to an empty string\n // so disable diagnostics\n return undefined;\n }\n\n if (\n this.runtimeDiagnosticsUrl !== \"-\" &&\n this.runtimeDiagnosticsUrl !== undefined\n ) {\n try {\n // Caller specified a specific diagnostics URL\n return new URL(this.runtimeDiagnosticsUrl);\n } catch (err: unknown) {\n actionsCore.info(\n `User-provided diagnostic endpoint ignored: not a valid URL: ${stringifyError(err)}`,\n );\n }\n }\n\n try {\n const diagnosticUrl = await this.getRootUrl();\n diagnosticUrl.pathname += \"events/batch\";\n return diagnosticUrl;\n } catch (err: unknown) {\n actionsCore.info(\n `Generated diagnostic endpoint ignored, and diagnostics are disabled: not a valid URL: ${stringifyError(err)}`,\n );\n return undefined;\n }\n }\n\n private async getUrlsByPreference(): Promise<URL[]> {\n if (this.prioritizedURLs === undefined) {\n this.prioritizedURLs = orderRecordsByPriorityWeight(\n await discoverServiceRecords(),\n ).flatMap((record) => recordToUrl(record) || []);\n }\n\n return this.prioritizedURLs;\n }\n}\n\nexport function recordToUrl(record: SrvRecord): URL | undefined {\n const urlStr = `https://${record.name}:${record.port}`;\n try {\n return new URL(urlStr);\n } catch (err: unknown) {\n actionsCore.debug(\n `Record ${JSON.stringify(record)} produced an invalid URL: ${urlStr} (${err})`,\n );\n return undefined;\n }\n}\n\nasync function discoverServiceRecords(): Promise<SrvRecord[]> {\n return await discoverServicesStub(resolveSrv(LOOKUP), 1_000);\n}\n\nexport async function discoverServicesStub(\n lookup: Promise<SrvRecord[]>,\n timeout: number,\n): Promise<SrvRecord[]> {\n const defaultFallback: Promise<SrvRecord[]> = new Promise(\n (resolve, _reject) => {\n setTimeout(resolve, timeout, []);\n },\n );\n\n let records: SrvRecord[];\n\n try {\n records = await Promise.race([lookup, defaultFallback]);\n } catch (reason: unknown) {\n actionsCore.debug(`Error resolving SRV records: ${stringifyError(reason)}`);\n records = [];\n }\n\n const acceptableRecords = records.filter((record: SrvRecord): boolean => {\n for (const suffix of ALLOWED_SUFFIXES) {\n if (record.name.endsWith(suffix)) {\n return true;\n }\n }\n\n actionsCore.debug(\n `Unacceptable domain due to an invalid suffix: ${record.name}`,\n );\n\n return false;\n });\n\n if (acceptableRecords.length === 0) {\n actionsCore.debug(`No records found for ${LOOKUP}`);\n } else {\n actionsCore.debug(\n `Resolved ${LOOKUP} to ${JSON.stringify(acceptableRecords)}`,\n );\n }\n\n return acceptableRecords;\n}\n\nexport function orderRecordsByPriorityWeight(\n records: SrvRecord[],\n): SrvRecord[] {\n const byPriorityWeight: Map<number, SrvRecord[]> = new Map();\n for (const record of records) {\n const existing = byPriorityWeight.get(record.priority);\n if (existing) {\n existing.push(record);\n } else {\n byPriorityWeight.set(record.priority, [record]);\n }\n }\n\n const prioritizedRecords: SrvRecord[] = [];\n const keys: number[] = Array.from(byPriorityWeight.keys()).sort(\n (a, b) => a - b,\n );\n\n for (const priority of keys) {\n const recordsByPrio = byPriorityWeight.get(priority);\n if (recordsByPrio === undefined) {\n continue;\n }\n\n prioritizedRecords.push(...weightedRandom(recordsByPrio));\n }\n\n return prioritizedRecords;\n}\n\nexport function weightedRandom(records: SrvRecord[]): SrvRecord[] {\n // Duplicate records so we don't accidentally change our caller's data\n const scratchRecords: SrvRecord[] = records.slice();\n const result: SrvRecord[] = [];\n\n while (scratchRecords.length > 0) {\n const weights: number[] = [];\n\n {\n for (let i = 0; i < scratchRecords.length; i++) {\n weights.push(\n scratchRecords[i].weight + (i > 0 ? scratchRecords[i - 1].weight : 0),\n );\n }\n }\n\n const point = Math.random() * weights[weights.length - 1];\n\n for (\n let selectedIndex = 0;\n selectedIndex < weights.length;\n selectedIndex++\n ) {\n if (weights[selectedIndex] > point) {\n // Remove our selected record and add it to the result\n result.push(scratchRecords.splice(selectedIndex, 1)[0]);\n break;\n }\n }\n }\n\n return result;\n}\n","/**\n * @packageDocumentation\n * Helpers for getting values from an Action's configuration.\n */\nimport * as actionsCore from \"@actions/core\";\n\n/**\n * Get a Boolean input from the Action's configuration by name.\n */\nconst getBool = (name: string): boolean => {\n return actionsCore.getBooleanInput(name);\n};\n\n/**\n * Get a Boolean input from the Action's configuration by name, or undefined if it is unset.\n */\nconst getBoolOrUndefined = (name: string): boolean | undefined => {\n if (getStringOrUndefined(name) === undefined) {\n return undefined;\n }\n\n return actionsCore.getBooleanInput(name);\n};\n\n/**\n * The character used to separate values in the input string.\n */\nexport type Separator = \"space\" | \"comma\";\n\n/**\n * Convert a comma-separated string input into an array of strings. If `comma` is selected,\n * all whitespace is removed from the string before converting to an array.\n */\nconst getArrayOfStrings = (name: string, separator: Separator): string[] => {\n const original = getString(name);\n return handleString(original, separator);\n};\n\n/**\n * Convert a string input into an array of strings or `null` if no value is set.\n */\nconst getArrayOfStringsOrNull = (\n name: string,\n separator: Separator,\n): string[] | null => {\n const original = getStringOrNull(name);\n if (original === null) {\n return null;\n } else {\n return handleString(original, separator);\n }\n};\n\n// Split out this function for use in testing\nexport const handleString = (input: string, separator: Separator): string[] => {\n const sepChar = separator === \"comma\" ? \",\" : /\\s+/;\n const trimmed = input.trim(); // Remove whitespace at the beginning and end\n if (trimmed === \"\") {\n return [];\n }\n\n return trimmed.split(sepChar).map((s: string) => s.trim());\n};\n\n/**\n * Get a multi-line string input from the Action's configuration by name or return `null` if not set.\n */\nconst getMultilineStringOrNull = (name: string): string[] | null => {\n const value = actionsCore.getMultilineInput(name);\n if (value.length === 0) {\n return null;\n } else {\n return value;\n }\n};\n\n/**\n * Get a number input from the Action's configuration by name or return `null` if not set.\n */\nconst getNumberOrNull = (name: string): number | null => {\n const value = actionsCore.getInput(name);\n if (value === \"\") {\n return null;\n } else {\n return Number(value);\n }\n};\n\n/**\n * Get a Number input from the Action's configuration by name, or undefined if it is unset.\n */\nconst getNumberOrUndefined = (name: string): number | undefined => {\n const value = getStringOrUndefined(name);\n if (value === undefined) {\n return undefined;\n }\n\n return Number(value);\n};\n\n/**\n * Get a string input from the Action's configuration.\n */\nconst getString = (name: string): string => {\n return actionsCore.getInput(name);\n};\n\n/**\n * Get a string input from the Action's configuration by name or return `null` if not set.\n */\nconst getStringOrNull = (name: string): string | null => {\n const value = actionsCore.getInput(name);\n if (value === \"\") {\n return null;\n } else {\n return value;\n }\n};\n\n/**\n * Get a string input from the Action's configuration by name or return `undefined` if not set.\n */\nconst getStringOrUndefined = (name: string): string | undefined => {\n const value = actionsCore.getInput(name);\n if (value === \"\") {\n return undefined;\n } else {\n return value;\n }\n};\n\nexport {\n getBool,\n getBoolOrUndefined,\n getArrayOfStrings,\n getArrayOfStringsOrNull,\n getMultilineStringOrNull,\n getNumberOrNull,\n getNumberOrUndefined,\n getString,\n getStringOrNull,\n getStringOrUndefined,\n};\n","/**\n * @packageDocumentation\n * Helpers for determining system attributes of the current runner.\n */\nimport * as actionsCore from \"@actions/core\";\n\n/**\n * Get the current architecture plus OS. Examples include `X64-Linux` and `ARM64-macOS`.\n */\nexport function getArchOs(): string {\n const envArch = process.env.RUNNER_ARCH;\n const envOs = process.env.RUNNER_OS;\n\n if (envArch && envOs) {\n return `${envArch}-${envOs}`;\n } else {\n actionsCore.error(\n `Can't identify the platform: RUNNER_ARCH or RUNNER_OS undefined (${envArch}-${envOs})`,\n );\n throw new Error(\"RUNNER_ARCH and/or RUNNER_OS is not defined\");\n }\n}\n\n/**\n * Get the current Nix system. Examples include `x86_64-linux` and `aarch64-darwin`.\n */\nexport function getNixPlatform(archOs: string): string {\n const archOsMap: Map<string, string> = new Map([\n [\"X64-macOS\", \"x86_64-darwin\"],\n [\"ARM64-macOS\", \"aarch64-darwin\"],\n [\"X64-Linux\", \"x86_64-linux\"],\n [\"ARM64-Linux\", \"aarch64-linux\"],\n ]);\n\n const mappedTo = archOsMap.get(archOs);\n if (mappedTo) {\n return mappedTo;\n } else {\n actionsCore.error(\n `ArchOs (${archOs}) doesn't map to a supported Nix platform.`,\n );\n throw new Error(\n `Cannot convert ArchOs (${archOs}) to a supported Nix platform.`,\n );\n }\n}\n","import { getStringOrUndefined } from \"./inputs.js\";\nimport * as actionsCore from \"@actions/core\";\n\nexport type SourceDef = {\n path?: string;\n url?: string;\n tag?: string;\n pr?: string;\n branch?: string;\n revision?: string;\n};\n\n/**\n * Throw if hash-locking is requested against a source that is not pinned to a\n * fixed version. `source-tag`, `source-revision`, and `source-url` are\n * immutable (or caller-controlled); any other selector resolves to a moving\n * target (`branch`, `pr`, or the `stable` fallback) where the pinned checksum\n * would break the moment a new release is published.\n */\nexport function assertChecksumSourceIsPinned(source: SourceDef): void {\n if (\n source.url === undefined &&\n source.tag === undefined &&\n source.revision === undefined\n ) {\n throw new Error(\n \"Hash-locking via `source-checksums-url`/`source-checksums-sha256` requires a pinned source: set `source-tag`, `source-revision`, or `source-url`. Without one the action resolves to a moving target (e.g. `stable`) and the checksum will break the next time a release is published.\",\n );\n }\n}\n\nexport function constructSourceParameters(legacyPrefix?: string): SourceDef {\n return {\n path: noisilyGetInput(\"path\", legacyPrefix),\n url: noisilyGetInput(\"url\", legacyPrefix),\n tag: noisilyGetInput(\"tag\", legacyPrefix),\n pr: noisilyGetInput(\"pr\", legacyPrefix),\n branch: noisilyGetInput(\"branch\", legacyPrefix),\n revision: noisilyGetInput(\"revision\", legacyPrefix),\n };\n}\n\nfunction noisilyGetInput(\n suffix: string,\n legacyPrefix: string | undefined,\n): string | undefined {\n const preferredInput = getStringOrUndefined(`source-${suffix}`);\n\n if (!legacyPrefix) {\n return preferredInput;\n }\n\n // Remaining is for handling cases where the legacy prefix\n // should be examined.\n const legacyInput = getStringOrUndefined(`${legacyPrefix}-${suffix}`);\n\n if (preferredInput && legacyInput) {\n actionsCore.warning(\n `The supported option source-${suffix} and the legacy option ${legacyPrefix}-${suffix} are both set. Preferring source-${suffix}. Please stop setting ${legacyPrefix}-${suffix}.`,\n );\n return preferredInput;\n } else if (legacyInput) {\n actionsCore.warning(\n `The legacy option ${legacyPrefix}-${suffix} is set. Please migrate to source-${suffix}.`,\n );\n return legacyInput;\n } else {\n return preferredInput;\n }\n}\n","/**\n * @packageDocumentation\n * Determinate Systems' TypeScript library for creating GitHub Actions logic.\n */\n// import { version as pkgVersion } from \"../package.json\";\nimport * as ghActionsCorePlatform from \"./actions-core-platform.js\";\nimport { collectBacktraces } from \"./backtrace.js\";\nimport type { CheckIn, Feature } from \"./check-in.js\";\nimport {\n parseChecksumsFile,\n sha256OfBuffer,\n sha256OfFile,\n} from \"./checksums.js\";\nimport * as correlation from \"./correlation.js\";\nimport { IdsHost } from \"./ids-host.js\";\nimport {\n getBool,\n getBoolOrUndefined,\n getNumberOrUndefined,\n getStringOrNull,\n} from \"./inputs.js\";\nimport * as platform from \"./platform.js\";\nimport type { SourceDef } from \"./sourcedef.js\";\nimport {\n assertChecksumSourceIsPinned,\n constructSourceParameters,\n} from \"./sourcedef.js\";\nimport * as actionsCache from \"@actions/cache\";\nimport * as actionsCore from \"@actions/core\";\nimport * as actionsExec from \"@actions/exec\";\nimport { type Got, type Request, TimeoutError } from \"got\";\nimport { exec } from \"node:child_process\";\nimport type { UUID } from \"node:crypto\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n PathLike,\n WriteStream,\n createWriteStream,\n constants as fsConstants,\n readFileSync,\n} from \"node:fs\";\nimport fs, { chmod, copyFile, mkdir } from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport { tmpdir } from \"node:os\";\nimport * as path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { gzip } from \"node:zlib\";\n\nconst pkgVersion = \"1.0\";\n\nconst EVENT_BACKTRACES = \"backtrace\";\nconst EVENT_EXCEPTION = \"exception\";\nconst EVENT_ARTIFACT_CACHE_HIT = \"artifact_cache_hit\";\nconst EVENT_ARTIFACT_CACHE_MISS = \"artifact_cache_miss\";\nconst EVENT_ARTIFACT_CACHE_PERSIST = \"artifact_cache_persist\";\nconst EVENT_PREFLIGHT_REQUIRE_NIX_DENIED = \"preflight-require-nix-denied\";\nconst EVENT_STORE_IDENTITY_FAILED = \"store_identity_failed\";\n\nconst FACT_ARTIFACT_FETCHED_FROM_CACHE = \"artifact_fetched_from_cache\";\nconst FACT_ENDED_WITH_EXCEPTION = \"ended_with_exception\";\nconst FACT_FINAL_EXCEPTION = \"final_exception\";\nconst FACT_OS = \"$os\";\nconst FACT_OS_VERSION = \"$os_version\";\nconst FACT_SOURCE_URL = \"source_url\";\nconst FACT_SOURCE_URL_ETAG = \"source_url_etag\";\nconst FACT_SOURCE_CHECKSUMS_SHA256 = \"source_checksums_sha256\";\nconst FACT_NIX_VERSION = \"nix_version\";\n\nconst FACT_NIX_LOCATION = \"nix_location\";\nconst FACT_NIX_STORE_TRUST = \"nix_store_trusted\";\nconst FACT_NIX_STORE_VERSION = \"nix_store_version\";\nconst FACT_NIX_STORE_CHECK_METHOD = \"nix_store_check_method\";\nconst FACT_NIX_STORE_CHECK_ERROR = \"nix_store_check_error\";\n\nconst STATE_KEY_EXECUTION_PHASE = \"detsys_action_execution_phase\";\nconst STATE_KEY_NIX_NOT_FOUND = \"detsys_action_nix_not_found\";\nconst STATE_NOT_FOUND = \"not-found\";\nconst STATE_KEY_CROSS_PHASE_ID = \"detsys_cross_phase_id\";\nconst STATE_BACKTRACE_START_TIMESTAMP = \"detsys_backtrace_start_timestamp\";\n\nconst DIAGNOSTIC_ENDPOINT_TIMEOUT_MS = 10_000; // 10 seconds in ms\nconst CHECK_IN_ENDPOINT_TIMEOUT_MS = 1_000; // 1 second in ms\nconst PROGRAM_NAME_CRASH_DENY_LIST = [\n \"nix-expr-tests\",\n \"nix-store-tests\",\n \"nix-util-tests\",\n];\n\n/**\n * An enum for describing different \"fetch suffixes\" for i.d.s.\n *\n * - `nix-style` means that system names like `x86_64-linux` and `aarch64-darwin` are used\n * - `gh-env-style` means that names like `X64-Linux` and `ARM64-macOS` are used\n * - `universal` means that the suffix is the static `universal` (for non-system-specific things)\n */\nexport type FetchSuffixStyle = \"nix-style\" | \"gh-env-style\" | \"universal\";\n\n/**\n * GitHub Actions has two possible execution phases: `main` and `post`.\n */\nexport type ExecutionPhase = \"main\" | \"post\";\n\n/**\n * How to handle whether Nix is currently installed on the runner.\n *\n * - `fail` means that the workflow fails if Nix isn't installed\n * - `warn` means that a warning is logged if Nix isn't installed\n * - `ignore` means that Nix will not be checked\n */\nexport type NixRequirementHandling = \"fail\" | \"warn\" | \"ignore\";\n\n/**\n * Whether the Nix store on the runner is trusted.\n *\n * - `trusted` means yes\n * - `untrusted` means no\n * - `unknown` means that the status couldn't be determined\n *\n * This is determined via the output of `nix store info --json`.\n */\nexport type NixStoreTrust = \"trusted\" | \"untrusted\" | \"unknown\";\n\nexport type ActionOptions = {\n // Name of the project generally, and the name of the binary on disk.\n name: string;\n\n // Defaults to `name`, Corresponds to the ProjectHost entry on i.d.s.\n idsProjectName?: string;\n\n // Defaults to `action:`\n eventPrefix?: string;\n\n // The \"architecture\" URL component expected by I.D.S. for the ProjectHost.\n fetchStyle: FetchSuffixStyle;\n\n // IdsToolbox assumes the GitHub Action exposes source overrides, like branch/pr/etc. to be named `source-*`.\n // This prefix adds a fallback name, prefixed by `${legacySourcePrefix}-`.\n // Users who configure legacySourcePrefix will get warnings asking them to change to `source-*`.\n legacySourcePrefix?: string;\n\n // Check if Nix is installed before running this action.\n // If Nix isn't installed, this action will not fail, and will instead do nothing.\n // The action will emit a user-visible warning instructing them to install Nix.\n requireNix: NixRequirementHandling;\n\n // The URL suffix to send diagnostics events to.\n //\n // The final URL is constructed via IDS_HOST/idsProjectName/diagnosticsSuffix.\n //\n // Default: `diagnostics`.\n diagnosticsSuffix?: string;\n\n // Collect backtraces from segfaults and other failures from binaries that start with these names.\n //\n // Default: `[ \"nix\", \"determinate-nixd\", ActionOptions.name ]`.\n binaryNamePrefixes?: string[];\n\n // Do NOT collect backtraces from segfaults and other failures from binaries with exact these names.\n //\n // Default: `[ \"nix-expr-tests\" ]`.\n binaryNamesDenyList?: string[];\n};\n\n/**\n * A confident version of Options, where defaults have been resolved into final values.\n */\nexport type ConfidentActionOptions = {\n name: string;\n idsProjectName: string;\n eventPrefix: string;\n fetchStyle: FetchSuffixStyle;\n legacySourcePrefix?: string;\n requireNix: NixRequirementHandling;\n providedDiagnosticsUrl?: URL;\n binaryNamePrefixes: string[];\n binaryNamesDenyList: string[];\n};\n\n/**\n * An event to send to the diagnostic endpoint of i.d.s.\n */\nexport type DiagnosticEvent = {\n // Note: putting a Map in here won't serialize to json properly.\n // It'll just be {} on serialization.\n name: string;\n distinct_id?: string;\n uuid: UUID;\n timestamp: Date;\n\n properties: Record<string, unknown>;\n};\n\nconst determinateStateDir = \"/var/lib/determinate\";\nconst determinateIdentityFile = path.join(determinateStateDir, \"identity.json\");\n\nconst isRoot = typeof process.geteuid === \"function\" && process.geteuid() === 0;\n\n/** Create the Determinate state directory by escalating via sudo */\nasync function sudoEnsureDeterminateStateDir(): Promise<void> {\n const code = await actionsExec.exec(\"sudo\", [\n \"mkdir\",\n \"-p\",\n determinateStateDir,\n ]);\n\n if (code !== 0) {\n throw new Error(`sudo mkdir -p exit: ${code}`);\n }\n}\n\n/** Ensures the Determinate state directory exists, escalating if necessary */\nasync function ensureDeterminateStateDir(): Promise<void> {\n if (isRoot) {\n await mkdir(determinateStateDir, { recursive: true });\n } else {\n return sudoEnsureDeterminateStateDir();\n }\n}\n\n/** Writes correlation hashes to the Determinate state directory by writing to a `sudo tee` pipe */\nasync function sudoWriteCorrelationHashes(hashes: string): Promise<void> {\n const buffer = Buffer.from(hashes);\n\n const code = await actionsExec.exec(\n \"sudo\",\n [\"tee\", determinateIdentityFile],\n {\n input: buffer,\n\n // Ignore output from tee\n outStream: createWriteStream(\"/dev/null\"),\n },\n );\n\n if (code !== 0) {\n throw new Error(`sudo tee exit: ${code}`);\n }\n}\n\n/** Writes correlation hashes to the Determinate state directory, escalating if necessary */\nasync function writeCorrelationHashes(hashes: string): Promise<void> {\n await ensureDeterminateStateDir();\n\n if (isRoot) {\n await fs.writeFile(determinateIdentityFile, hashes, \"utf-8\");\n } else {\n return sudoWriteCorrelationHashes(hashes);\n }\n}\n\nexport abstract class DetSysAction {\n nixStoreTrust: NixStoreTrust;\n strictMode: boolean;\n\n private actionOptions: ConfidentActionOptions;\n private exceptionAttachments: Map<string, PathLike>;\n private archOs: string;\n private executionPhase: ExecutionPhase;\n private nixSystem: string;\n private architectureFetchSuffix: string;\n private sourceParameters: SourceDef;\n private facts: Record<string, string | boolean | number>;\n private events: DiagnosticEvent[];\n private identity: correlation.CorrelationProperties;\n private idsHost: IdsHost;\n private features: { [k: string]: Feature };\n private featureEventMetadata: { [k: string]: string | boolean };\n\n private determineExecutionPhase(): ExecutionPhase {\n const currentPhase = actionsCore.getState(STATE_KEY_EXECUTION_PHASE);\n if (currentPhase === \"\") {\n actionsCore.saveState(STATE_KEY_EXECUTION_PHASE, \"post\");\n return \"main\";\n } else {\n return \"post\";\n }\n }\n\n constructor(actionOptions: ActionOptions) {\n this.actionOptions = makeOptionsConfident(actionOptions);\n this.idsHost = new IdsHost(\n this.actionOptions.idsProjectName,\n actionOptions.diagnosticsSuffix,\n // Note: we don't use actionsCore.getInput('diagnostic-endpoint') on purpose:\n // getInput silently converts absent data to an empty string.\n process.env[\"INPUT_DIAGNOSTIC-ENDPOINT\"],\n getNumberOrUndefined(\"timeout-request\"),\n );\n this.exceptionAttachments = new Map();\n this.nixStoreTrust = \"unknown\";\n this.strictMode = getBool(\"_internal-strict-mode\");\n\n if (\n getBoolOrUndefined(\n \"_internal-obliterate-actions-id-token-request-variables\",\n ) === true\n ) {\n process.env[\"ACTIONS_ID_TOKEN_REQUEST_URL\"] = undefined;\n process.env[\"ACTIONS_ID_TOKEN_REQUEST_TOKEN\"] = undefined;\n }\n\n this.features = {};\n this.featureEventMetadata = {};\n this.events = [];\n\n this.getCrossPhaseId();\n this.collectBacktraceSetup();\n\n // JSON sent to server\n /* eslint-disable camelcase */\n this.facts = {\n $lib: \"idslib\",\n $lib_version: pkgVersion,\n project: this.actionOptions.name,\n ids_project: this.actionOptions.idsProjectName,\n };\n\n const params = [\n [\"github_action_ref\", \"GITHUB_ACTION_REF\"],\n [\"github_action_repository\", \"GITHUB_ACTION_REPOSITORY\"],\n [\"github_event_name\", \"GITHUB_EVENT_NAME\"],\n [\"$os\", \"RUNNER_OS\"],\n [\"arch\", \"RUNNER_ARCH\"],\n ];\n for (const [target, env] of params) {\n const value = process.env[env];\n if (value) {\n this.facts[target] = value;\n }\n }\n\n this.identity = correlation.identify();\n this.archOs = platform.getArchOs();\n this.nixSystem = platform.getNixPlatform(this.archOs);\n\n this.facts.$app_name = `${this.actionOptions.name}/action`;\n this.facts.arch_os = this.archOs;\n this.facts.nix_system = this.nixSystem;\n\n {\n ghActionsCorePlatform\n .getDetails()\n // eslint-disable-next-line github/no-then\n .then((details) => {\n if (details.name !== \"unknown\") {\n this.addFact(FACT_OS, details.name);\n }\n if (details.version !== \"unknown\") {\n this.addFact(FACT_OS_VERSION, details.version);\n }\n })\n // eslint-disable-next-line github/no-then\n .catch((e: unknown) => {\n actionsCore.debug(\n `Failure getting platform details: ${stringifyError(e)}`,\n );\n });\n }\n\n this.executionPhase = this.determineExecutionPhase();\n this.facts.execution_phase = this.executionPhase;\n\n if (this.actionOptions.fetchStyle === \"gh-env-style\") {\n this.architectureFetchSuffix = this.archOs;\n } else if (this.actionOptions.fetchStyle === \"nix-style\") {\n this.architectureFetchSuffix = this.nixSystem;\n } else if (this.actionOptions.fetchStyle === \"universal\") {\n this.architectureFetchSuffix = \"universal\";\n } else {\n throw new Error(\n `fetchStyle ${this.actionOptions.fetchStyle} is not a valid style`,\n );\n }\n\n this.sourceParameters = constructSourceParameters(\n this.actionOptions.legacySourcePrefix,\n );\n\n this.recordEvent(`begin_${this.executionPhase}`);\n }\n\n /**\n * Attach a file to the diagnostics data in error conditions.\n *\n * The file at `location` doesn't need to exist when stapleFile is called.\n *\n * If the file doesn't exist or is unreadable when trying to staple the attachments, the JS error will be stored in a context value at `staple_failure_{name}`.\n * If the file is readable, the file's contents will be stored in a context value at `staple_value_{name}`.\n */\n stapleFile(name: string, location: string): void {\n this.exceptionAttachments.set(name, location);\n }\n\n /**\n * The main execution phase.\n */\n abstract main(): Promise<void>;\n\n /**\n * The post execution phase.\n */\n abstract post(): Promise<void>;\n\n /**\n * Execute the Action as defined.\n */\n execute(): void {\n // eslint-disable-next-line github/no-then\n this.executeAsync().catch((error: Error) => {\n // eslint-disable-next-line no-console\n console.log(error);\n process.exitCode = 1;\n });\n }\n\n getTemporaryName(): string {\n const tmpDir = process.env[\"RUNNER_TEMP\"] || tmpdir();\n return path.join(tmpDir, `${this.actionOptions.name}-${randomUUID()}`);\n }\n\n addFact(key: string, value: string | boolean | number): void {\n this.facts[key] = value;\n }\n\n async getDiagnosticsUrl(): Promise<URL | undefined> {\n return await this.idsHost.getDiagnosticsUrl();\n }\n\n getUniqueId(): string {\n return (\n this.identity.github_workflow_run_differentiator_hash ||\n process.env.RUNNER_TRACKING_ID ||\n randomUUID()\n );\n }\n\n // This ID will be saved in the action's state, to be persisted across phase steps\n getCrossPhaseId(): string {\n let crossPhaseId = actionsCore.getState(STATE_KEY_CROSS_PHASE_ID);\n\n if (crossPhaseId === \"\") {\n crossPhaseId = randomUUID();\n actionsCore.saveState(STATE_KEY_CROSS_PHASE_ID, crossPhaseId);\n }\n\n return crossPhaseId;\n }\n\n getCorrelationHashes(): correlation.CorrelationProperties {\n return this.identity;\n }\n\n recordEvent(\n eventName: string,\n context: Record<\n string,\n | boolean\n | string\n | number\n | undefined\n | Record<string, boolean | string | number | undefined>\n > = {},\n ): void {\n const prefixedName =\n eventName === \"$feature_flag_called\" || eventName === \"$groupidentify\"\n ? eventName\n : `${this.actionOptions.eventPrefix}${eventName}`;\n\n this.events.push({\n name: prefixedName,\n\n // Use the anon distinct ID as the distinct ID until we actually have a distinct ID in the future\n distinct_id: this.identity.$anon_distinct_id,\n\n // distinct_id\n uuid: randomUUID(),\n timestamp: new Date(),\n\n properties: {\n ...context,\n ...this.identity,\n ...this.facts,\n ...Object.fromEntries(\n Object.entries(this.featureEventMetadata).map<\n [string, string | boolean]\n >(([name, variant]) => [`$feature/${name}`, variant]),\n ),\n },\n });\n }\n\n /**\n * Unpacks the closure returned by `fetchArtifact()`, imports the\n * contents into the Nix store, and returns the path of the executable at\n * `/nix/store/STORE_PATH/bin/${bin}`.\n */\n async unpackClosure(bin: string): Promise<string> {\n const artifact = await this.fetchArtifact();\n const { stdout } = await promisify(exec)(\n `cat \"${artifact}\" | xz -d | nix-store --import`,\n );\n const paths = stdout.split(os.EOL);\n const lastPath = paths.at(-2);\n return `${lastPath}/bin/${bin}`;\n }\n\n /**\n * Fetches the executable at the URL determined by the `source-*` inputs and\n * other facts, `chmod`s it, and returns the path to the executable on disk.\n */\n async fetchExecutable(): Promise<string> {\n const binaryPath = await this.fetchArtifact();\n await chmod(binaryPath, fsConstants.S_IXUSR | fsConstants.S_IXGRP);\n return binaryPath;\n }\n\n private get isMain(): boolean {\n return this.executionPhase === \"main\";\n }\n\n private get isPost(): boolean {\n return this.executionPhase === \"post\";\n }\n\n private async executeAsync(): Promise<void> {\n try {\n await this.checkIn();\n\n const correlationHashes = JSON.stringify(this.getCorrelationHashes());\n process.env.DETSYS_CORRELATION = correlationHashes;\n try {\n await writeCorrelationHashes(correlationHashes);\n } catch (error) {\n this.recordEvent(EVENT_STORE_IDENTITY_FAILED, { error: String(error) });\n }\n\n if (!(await this.preflightRequireNix())) {\n this.recordEvent(EVENT_PREFLIGHT_REQUIRE_NIX_DENIED);\n return;\n } else {\n await this.preflightNixStoreInfo();\n await this.preflightNixVersion();\n this.addFact(FACT_NIX_STORE_TRUST, this.nixStoreTrust);\n }\n\n if (this.isMain) {\n this.recordGroup();\n await this.main();\n\n // Run the preflight of the nix version a second time so our \"shutdown\" events have updated version info.\n await this.preflightNixVersion();\n } else if (this.isPost) {\n await this.post();\n }\n this.addFact(FACT_ENDED_WITH_EXCEPTION, false);\n } catch (e: unknown) {\n this.addFact(FACT_ENDED_WITH_EXCEPTION, true);\n\n const reportable = stringifyError(e);\n\n this.addFact(FACT_FINAL_EXCEPTION, reportable);\n\n if (this.isPost) {\n actionsCore.warning(reportable);\n } else {\n actionsCore.setFailed(reportable);\n }\n\n const doGzip = promisify(gzip);\n\n const exceptionContext: Map<string, string> = new Map();\n for (const [attachmentLabel, filePath] of this.exceptionAttachments) {\n try {\n const logText = readFileSync(filePath);\n const buf = await doGzip(logText);\n exceptionContext.set(\n `staple_value_${attachmentLabel}`,\n buf.toString(\"base64\"),\n );\n } catch (innerError: unknown) {\n exceptionContext.set(\n `staple_failure_${attachmentLabel}`,\n stringifyError(innerError),\n );\n }\n }\n\n this.recordEvent(EVENT_EXCEPTION, Object.fromEntries(exceptionContext));\n } finally {\n if (this.isPost) {\n await this.collectBacktraces();\n }\n\n await this.complete();\n }\n }\n\n async getClient(): Promise<Got> {\n return await this.idsHost.getGot(\n (incitingError: unknown, prevUrl: URL, nextUrl: URL) => {\n this.recordPlausibleTimeout(incitingError);\n\n this.recordEvent(\"ids-failover\", {\n previousUrl: prevUrl.toString(),\n nextUrl: nextUrl.toString(),\n });\n },\n );\n }\n\n private async checkIn(): Promise<void> {\n const checkin = await this.requestCheckIn();\n if (checkin === undefined) {\n return;\n }\n\n this.features = checkin.options;\n for (const [key, feature] of Object.entries(this.features)) {\n this.featureEventMetadata[key] = feature.variant;\n }\n\n const impactSymbol: Map<string, string> = new Map([\n [\"none\", \"⚪\"],\n [\"maintenance\", \"🛠️\"],\n [\"minor\", \"🟡\"],\n [\"major\", \"🟠\"],\n [\"critical\", \"🔴\"],\n ]);\n const defaultImpactSymbol = \"🔵\";\n\n if (checkin.status !== null) {\n const summaries: string[] = [];\n\n for (const incident of checkin.status.incidents) {\n summaries.push(\n `${impactSymbol.get(incident.impact) || defaultImpactSymbol} ${incident.status.replace(\"_\", \" \")}: ${incident.name} (${incident.shortlink})`,\n );\n }\n\n for (const maintenance of checkin.status.scheduled_maintenances) {\n summaries.push(\n `${impactSymbol.get(maintenance.impact) || defaultImpactSymbol} ${maintenance.status.replace(\"_\", \" \")}: ${maintenance.name} (${maintenance.shortlink})`,\n );\n }\n\n if (summaries.length > 0) {\n actionsCore.info(\n // Bright red, Bold, Underline\n `${\"\\u001b[0;31m\"}${\"\\u001b[1m\"}${\"\\u001b[4m\"}${checkin.status.page.name} Status`,\n );\n for (const notice of summaries) {\n actionsCore.info(notice);\n }\n actionsCore.info(`See: ${checkin.status.page.url}`);\n actionsCore.info(``);\n }\n }\n }\n\n getFeature(name: string): Feature | undefined {\n if (!this.features.hasOwnProperty(name)) {\n return undefined;\n }\n\n const result = this.features[name];\n if (result === undefined) {\n return undefined;\n }\n\n this.recordEvent(\"$feature_flag_called\", {\n $feature_flag: name,\n $feature_flag_response: result.variant,\n });\n\n return result;\n }\n\n private recordGroup(): void {\n const ghorg_hash = this.identity.$groups[\"github_organization\"];\n const ghorg_name = process.env[\"GITHUB_REPOSITORY_OWNER\"];\n\n if (ghorg_hash !== undefined && ghorg_name !== undefined) {\n this.recordEvent(\"$groupidentify\", {\n $group_type: \"github_organization\",\n $group_key: ghorg_hash,\n $group_set: {\n name: ghorg_name,\n },\n });\n }\n }\n\n /**\n * Check in to install.determinate.systems, to accomplish three things:\n *\n * 1. Preflight the server selected from IdsHost, to increase the chances of success.\n * 2. Fetch any incidents and maintenance events to let users know in case things are weird.\n * 3. Get feature flag data so we can gently roll out new features.\n */\n private async requestCheckIn(): Promise<CheckIn | undefined> {\n for (\n let attemptsRemaining = 5;\n attemptsRemaining > 0;\n attemptsRemaining--\n ) {\n const checkInUrl = await this.getCheckInUrl();\n if (checkInUrl === undefined) {\n return undefined;\n }\n\n try {\n actionsCore.debug(`Preflighting via ${checkInUrl}`);\n\n const props = {\n // Use a distinct_id when we actually have one\n distinct_id: this.identity.$anon_distinct_id,\n anon_distinct_id: this.identity.$anon_distinct_id,\n groups: this.identity.$groups,\n person_properties: {\n ci: \"github\",\n\n ...this.identity,\n ...this.facts,\n },\n };\n\n return await (\n await this.getClient()\n )\n .post(checkInUrl, {\n json: props,\n timeout: {\n request: CHECK_IN_ENDPOINT_TIMEOUT_MS,\n },\n })\n .json();\n } catch (e: unknown) {\n this.recordPlausibleTimeout(e);\n actionsCore.debug(`Error checking in: ${stringifyError(e)}`);\n this.idsHost.markCurrentHostBroken();\n }\n }\n\n return undefined;\n }\n\n private recordPlausibleTimeout(e: unknown): void {\n // see: https://github.com/sindresorhus/got/blob/895e463fa699d6f2e4b2fc01ceb3b2bb9e157f4c/documentation/8-errors.md\n if (e instanceof TimeoutError && \"timings\" in e && \"request\" in e) {\n const reportContext: {\n [index: string]: string | number | undefined;\n } = {\n url: e.request.requestUrl?.toString(),\n retry_count: e.request.retryCount,\n };\n\n for (const [key, value] of Object.entries(e.timings.phases)) {\n if (Number.isFinite(value)) {\n reportContext[`timing_phase_${key}`] = value;\n }\n }\n\n this.recordEvent(\"timeout\", reportContext);\n }\n }\n\n /**\n * Fetch an artifact, such as a tarball, from the location determined by the\n * `source-*` inputs. If `source-binary` is specified, this will return a path\n * to a binary on disk; otherwise, the artifact will be downloaded from the\n * URL determined by the other `source-*` inputs (`source-url`, `source-pr`,\n * etc.).\n *\n * When `source-checksums-url` and `source-checksums-sha256` are both set,\n * the downloaded artifact is verified against the per-arch hash in the\n * checksums file, which is itself verified against the pinned\n * `source-checksums-sha256`. Both inputs must be set together.\n */\n private async fetchArtifact(): Promise<string> {\n const sourceBinary = getStringOrNull(\"source-binary\");\n\n // If source-binary is set, use that. Otherwise fall back to the source-* parameters.\n if (sourceBinary !== null && sourceBinary !== \"\") {\n actionsCore.debug(`Using the provided source binary at ${sourceBinary}`);\n return sourceBinary;\n }\n\n const expectedArtifactHash = await this.resolveExpectedArtifactHash();\n\n actionsCore.startGroup(\n `Downloading ${this.actionOptions.name} for ${this.architectureFetchSuffix}`,\n );\n\n try {\n actionsCore.info(`Fetching from ${await this.getSourceUrl()}`);\n\n const correlatedUrl = await this.getSourceUrl();\n correlatedUrl.searchParams.set(\"ci\", \"github\");\n correlatedUrl.searchParams.set(\n \"correlation\",\n JSON.stringify(this.identity),\n );\n\n const versionCheckup = await (await this.getClient()).head(correlatedUrl);\n if (versionCheckup.headers.etag) {\n const v = versionCheckup.headers.etag;\n this.addFact(FACT_SOURCE_URL_ETAG, v);\n\n actionsCore.debug(\n `Checking the tool cache for ${await this.getSourceUrl()} at ${v}`,\n );\n const cached = await this.getCachedVersion(v, expectedArtifactHash);\n if (cached) {\n this.facts[FACT_ARTIFACT_FETCHED_FROM_CACHE] = true;\n actionsCore.debug(`Tool cache hit.`);\n await this.verifyArtifactHash(cached, expectedArtifactHash);\n return cached;\n }\n }\n\n this.facts[FACT_ARTIFACT_FETCHED_FROM_CACHE] = false;\n\n actionsCore.debug(\n `No match from the cache, re-fetching from the redirect: ${versionCheckup.url}`,\n );\n\n const destFile = this.getTemporaryName();\n\n const fetchStream = await this.downloadFile(\n new URL(versionCheckup.url),\n destFile,\n );\n\n await this.verifyArtifactHash(destFile, expectedArtifactHash);\n\n if (fetchStream.response?.headers.etag) {\n const v = fetchStream.response.headers.etag;\n\n try {\n await this.saveCachedVersion(v, destFile, expectedArtifactHash);\n } catch (e: unknown) {\n actionsCore.debug(`Error caching the artifact: ${stringifyError(e)}`);\n }\n }\n\n return destFile;\n } catch (e: unknown) {\n this.recordPlausibleTimeout(e);\n throw e;\n } finally {\n actionsCore.endGroup();\n }\n }\n\n /**\n * Read the `source-checksums-url` and `source-checksums-sha256` inputs and,\n * if both are set, fetch the checksums file, verify its hash matches the\n * pin, parse it, and return the expected hash for the artifact matching\n * this runner's `${name}-${architectureFetchSuffix}`. Returns `null` when\n * verification is opted out (both inputs unset).\n */\n private async resolveExpectedArtifactHash(): Promise<string | null> {\n const checksumsUrl = getStringOrNull(\"source-checksums-url\");\n const checksumsSha256 = getStringOrNull(\"source-checksums-sha256\");\n\n if (checksumsUrl === null && checksumsSha256 === null) {\n return null;\n }\n if (checksumsUrl === null || checksumsSha256 === null) {\n throw new Error(\n \"`source-checksums-url` and `source-checksums-sha256` must be set together\",\n );\n }\n\n assertChecksumSourceIsPinned(this.sourceParameters);\n\n const expectedFileHash = checksumsSha256.toLowerCase();\n this.addFact(FACT_SOURCE_CHECKSUMS_SHA256, expectedFileHash);\n\n const parsedUrl = new URL(checksumsUrl);\n const safeUrl = parsedUrl.origin + parsedUrl.pathname;\n\n actionsCore.info(`Fetching checksums file from ${safeUrl}`);\n const response = await (await this.getClient()).get(checksumsUrl);\n const body = response.body;\n\n const actualFileHash = sha256OfBuffer(body);\n if (actualFileHash !== expectedFileHash) {\n throw new Error(\n `Checksums file hash mismatch at ${safeUrl}: expected ${expectedFileHash}, got ${actualFileHash}`,\n );\n }\n\n const wanted = `${this.actionOptions.name}-${this.architectureFetchSuffix}`;\n const hashes = parseChecksumsFile(body);\n const artifactHash = hashes.get(wanted);\n if (artifactHash === undefined) {\n throw new Error(`No entry for ${wanted} in checksums file at ${safeUrl}`);\n }\n return artifactHash;\n }\n\n /**\n * Verify a downloaded artifact's SHA-256 matches the expected hash. No-op\n * when `expected` is `null` (verification disabled).\n */\n private async verifyArtifactHash(\n filePath: string,\n expected: string | null,\n ): Promise<void> {\n if (expected === null) {\n return;\n }\n const actual = await sha256OfFile(filePath);\n if (actual !== expected) {\n throw new Error(\n `Artifact hash mismatch for ${this.architectureFetchSuffix}: expected ${expected}, got ${actual}`,\n );\n }\n }\n\n /**\n * A helper function for failing on error only if strict mode is enabled.\n * This is intended only for CI environments testing Actions themselves.\n */\n failOnError(msg: string): void {\n if (this.strictMode) {\n actionsCore.setFailed(`strict mode failure: ${msg}`);\n }\n }\n\n private async downloadFile(\n url: URL,\n destination: PathLike,\n ): Promise<Request> {\n const client = await this.getClient();\n\n return new Promise((resolve, reject) => {\n // Current stream handle\n let writeStream: WriteStream | undefined;\n\n // Sentinel condition in case we want to abort retrying due to FS issues\n let failed = false;\n\n const retry = (stream: Request): void => {\n if (writeStream) {\n writeStream.destroy();\n }\n\n writeStream = createWriteStream(destination, {\n encoding: \"binary\",\n mode: 0o755,\n });\n\n writeStream.once(\"error\", (error) => {\n // Set failed here since promise rejections don't impact control flow\n failed = true;\n reject(error);\n });\n\n writeStream.on(\"finish\", () => {\n if (!failed) {\n resolve(stream);\n }\n });\n\n stream.once(\"retry\", (_count, _error, createRetryStream) => {\n // Optional: check `failed' here in case you want to stop retrying\n retry(createRetryStream());\n });\n\n // Now that all the handlers have been set up we can pipe from the HTTP\n // stream to disk\n stream.pipe(writeStream);\n };\n\n // Begin the retry logic by giving it a fresh got.Request\n retry(client.stream(url));\n });\n }\n\n private async complete(): Promise<void> {\n this.recordEvent(`complete_${this.executionPhase}`);\n await this.submitEvents();\n }\n\n private async getCheckInUrl(): Promise<URL | undefined> {\n const checkInUrl = await this.idsHost.getDynamicRootUrl();\n\n if (checkInUrl === undefined) {\n return undefined;\n }\n\n checkInUrl.pathname += \"check-in\";\n return checkInUrl;\n }\n\n private async getSourceUrl(): Promise<URL> {\n const p = this.sourceParameters;\n\n if (p.url) {\n this.addFact(FACT_SOURCE_URL, p.url);\n return new URL(p.url);\n }\n\n const fetchUrl = await this.idsHost.getRootUrl();\n fetchUrl.pathname += this.actionOptions.idsProjectName;\n\n if (p.tag) {\n fetchUrl.pathname += `/tag/${p.tag}`;\n } else if (p.pr) {\n fetchUrl.pathname += `/pr/${p.pr}`;\n } else if (p.branch) {\n fetchUrl.pathname += `/branch/${p.branch}`;\n } else if (p.revision) {\n fetchUrl.pathname += `/rev/${p.revision}`;\n } else {\n fetchUrl.pathname += `/stable`;\n }\n\n fetchUrl.pathname += `/${this.architectureFetchSuffix}`;\n\n this.addFact(FACT_SOURCE_URL, fetchUrl.toString());\n\n return fetchUrl;\n }\n\n private cacheKey(version: string, expectedHash: string | null): string {\n const cleanedVersion = version.replace(/[^a-zA-Z0-9-+.]/g, \"\");\n const hashSuffix = expectedHash ? `-h${expectedHash}` : \"\";\n return `determinatesystem-${this.actionOptions.name}-${this.architectureFetchSuffix}-${cleanedVersion}${hashSuffix}`;\n }\n\n private async getCachedVersion(\n version: string,\n expectedHash: string | null,\n ): Promise<undefined | string> {\n const startCwd = process.cwd();\n\n try {\n const tempDir = this.getTemporaryName();\n await mkdir(tempDir);\n process.chdir(tempDir);\n\n // extremely evil shit right here:\n process.env.GITHUB_WORKSPACE_BACKUP = process.env.GITHUB_WORKSPACE;\n delete process.env.GITHUB_WORKSPACE;\n\n if (\n await actionsCache.restoreCache(\n [this.actionOptions.name],\n this.cacheKey(version, expectedHash),\n [],\n undefined,\n true,\n )\n ) {\n this.recordEvent(EVENT_ARTIFACT_CACHE_HIT);\n return `${tempDir}/${this.actionOptions.name}`;\n }\n\n this.recordEvent(EVENT_ARTIFACT_CACHE_MISS);\n return undefined;\n } finally {\n process.env.GITHUB_WORKSPACE = process.env.GITHUB_WORKSPACE_BACKUP;\n delete process.env.GITHUB_WORKSPACE_BACKUP;\n process.chdir(startCwd);\n }\n }\n\n private async saveCachedVersion(\n version: string,\n toolPath: string,\n expectedHash: string | null,\n ): Promise<void> {\n const startCwd = process.cwd();\n\n try {\n const tempDir = this.getTemporaryName();\n await mkdir(tempDir);\n process.chdir(tempDir);\n await copyFile(toolPath, `${tempDir}/${this.actionOptions.name}`);\n\n // extremely evil shit right here:\n process.env.GITHUB_WORKSPACE_BACKUP = process.env.GITHUB_WORKSPACE;\n delete process.env.GITHUB_WORKSPACE;\n\n await actionsCache.saveCache(\n [this.actionOptions.name],\n this.cacheKey(version, expectedHash),\n undefined,\n true,\n );\n this.recordEvent(EVENT_ARTIFACT_CACHE_PERSIST);\n } finally {\n process.env.GITHUB_WORKSPACE = process.env.GITHUB_WORKSPACE_BACKUP;\n delete process.env.GITHUB_WORKSPACE_BACKUP;\n process.chdir(startCwd);\n }\n }\n\n private collectBacktraceSetup(): void {\n if (!process.env.DETSYS_BACKTRACE_COLLECTOR) {\n actionsCore.exportVariable(\n \"DETSYS_BACKTRACE_COLLECTOR\",\n this.getCrossPhaseId(),\n );\n\n actionsCore.saveState(STATE_BACKTRACE_START_TIMESTAMP, Date.now());\n }\n }\n\n private async collectBacktraces(): Promise<void> {\n try {\n if (process.env.DETSYS_BACKTRACE_COLLECTOR !== this.getCrossPhaseId()) {\n return;\n }\n\n const backtraces = await collectBacktraces(\n this.actionOptions.binaryNamePrefixes,\n this.actionOptions.binaryNamesDenyList,\n parseInt(actionsCore.getState(STATE_BACKTRACE_START_TIMESTAMP)),\n );\n actionsCore.debug(`Backtraces identified: ${backtraces.size}`);\n if (backtraces.size > 0) {\n this.recordEvent(EVENT_BACKTRACES, Object.fromEntries(backtraces));\n }\n } catch (innerError: unknown) {\n actionsCore.debug(\n `Error collecting backtraces: ${stringifyError(innerError)}`,\n );\n }\n }\n\n private async preflightRequireNix(): Promise<boolean> {\n let nixLocation: string | undefined;\n\n const pathParts = (process.env[\"PATH\"] || \"\").split(\":\");\n for (const location of pathParts) {\n const candidateNix = path.join(location, \"nix\");\n\n try {\n await fs.access(candidateNix, fs.constants.X_OK);\n actionsCore.debug(`Found Nix at ${candidateNix}`);\n nixLocation = candidateNix;\n break;\n } catch {\n actionsCore.debug(`Nix not at ${candidateNix}`);\n }\n }\n this.addFact(FACT_NIX_LOCATION, nixLocation || \"\");\n\n if (this.actionOptions.requireNix === \"ignore\") {\n return true;\n }\n\n const currentNotFoundState = actionsCore.getState(STATE_KEY_NIX_NOT_FOUND);\n if (currentNotFoundState === STATE_NOT_FOUND) {\n // It was previously not found, so don't run subsequent actions\n return false;\n }\n\n if (nixLocation !== undefined) {\n return true;\n }\n actionsCore.saveState(STATE_KEY_NIX_NOT_FOUND, STATE_NOT_FOUND);\n\n switch (this.actionOptions.requireNix) {\n case \"fail\":\n actionsCore.setFailed(\n [\n \"This action can only be used when Nix is installed.\",\n \"Add `- uses: DeterminateSystems/determinate-nix-action@v3` earlier in your workflow.\",\n ].join(\" \"),\n );\n break;\n case \"warn\":\n actionsCore.warning(\n [\n \"This action is in no-op mode because Nix is not installed.\",\n \"Add `- uses: DeterminateSystems/determinate-nix-action@v3` earlier in your workflow.\",\n ].join(\" \"),\n );\n break;\n }\n\n return false;\n }\n\n private async preflightNixStoreInfo(): Promise<void> {\n let output = \"\";\n\n const options: actionsExec.ExecOptions = {};\n options.silent = true;\n options.listeners = {\n stdout: (data) => {\n output += data.toString();\n },\n };\n\n try {\n output = \"\";\n await actionsExec.exec(\"nix\", [\"store\", \"info\", \"--json\"], options);\n this.addFact(FACT_NIX_STORE_CHECK_METHOD, \"info\");\n } catch {\n try {\n // reset output\n output = \"\";\n await actionsExec.exec(\"nix\", [\"store\", \"ping\", \"--json\"], options);\n this.addFact(FACT_NIX_STORE_CHECK_METHOD, \"ping\");\n } catch {\n this.addFact(FACT_NIX_STORE_CHECK_METHOD, \"none\");\n return;\n }\n }\n\n try {\n const parsed = JSON.parse(output);\n if (parsed.trusted === true || parsed.trusted === 1) {\n this.nixStoreTrust = \"trusted\";\n } else if (parsed.trusted === false || parsed.trusted === 0) {\n this.nixStoreTrust = \"untrusted\";\n } else if (parsed.trusted !== undefined) {\n this.addFact(\n FACT_NIX_STORE_CHECK_ERROR,\n `Mysterious trusted value: ${JSON.stringify(parsed.trusted)}`,\n );\n }\n\n this.addFact(FACT_NIX_STORE_VERSION, JSON.stringify(parsed.version));\n } catch (e: unknown) {\n this.addFact(FACT_NIX_STORE_CHECK_ERROR, stringifyError(e));\n }\n }\n\n private async preflightNixVersion(): Promise<void> {\n let output = \"unknown\";\n\n try {\n ({ stdout: output } = await actionsExec.getExecOutput(\n \"nix\",\n [\"--version\"],\n {\n silent: true,\n },\n ));\n output = output.trim() || \"unknown\";\n } catch {\n // That's fine.\n }\n\n this.addFact(FACT_NIX_VERSION, output);\n }\n\n private async submitEvents(): Promise<void> {\n const diagnosticsUrl = await this.idsHost.getDiagnosticsUrl();\n if (diagnosticsUrl === undefined) {\n actionsCore.debug(\n \"Diagnostics are disabled. Not sending the following events:\",\n );\n actionsCore.debug(JSON.stringify(this.events, undefined, 2));\n return;\n }\n\n const batch = {\n sent_at: new Date(),\n batch: this.events,\n };\n\n try {\n await (\n await this.getClient()\n ).post(diagnosticsUrl, {\n json: batch,\n timeout: {\n request: DIAGNOSTIC_ENDPOINT_TIMEOUT_MS,\n },\n });\n } catch (err: unknown) {\n this.recordPlausibleTimeout(err);\n\n actionsCore.debug(\n `Error submitting diagnostics event to ${diagnosticsUrl}: ${stringifyError(err)}`,\n );\n }\n this.events = [];\n }\n}\n\nfunction stringifyError(error: unknown): string {\n return error instanceof Error || typeof error == \"string\"\n ? error.toString()\n : JSON.stringify(error);\n}\n\nfunction makeOptionsConfident(\n actionOptions: ActionOptions,\n): ConfidentActionOptions {\n const idsProjectName = actionOptions.idsProjectName ?? actionOptions.name;\n\n const finalOpts: ConfidentActionOptions = {\n name: actionOptions.name,\n idsProjectName,\n eventPrefix: actionOptions.eventPrefix || \"action:\",\n fetchStyle: actionOptions.fetchStyle,\n legacySourcePrefix: actionOptions.legacySourcePrefix,\n requireNix: actionOptions.requireNix,\n binaryNamePrefixes: actionOptions.binaryNamePrefixes ?? [\n \"nix\",\n \"determinate-nixd\",\n actionOptions.name,\n ],\n binaryNamesDenyList:\n actionOptions.binaryNamesDenyList ?? PROGRAM_NAME_CRASH_DENY_LIST,\n };\n\n actionsCore.debug(\"idslib options:\");\n actionsCore.debug(JSON.stringify(finalOpts, undefined, 2));\n\n return finalOpts;\n}\n\n// Public exports from other files\nexport type {\n CheckIn,\n Feature,\n Incident,\n Maintenance,\n Page,\n StatusSummary,\n} from \"./check-in.js\";\nexport type { CorrelationProperties } from \"./correlation.js\";\nexport { stringifyError } from \"./errors.js\";\nexport { IdsHost } from \"./ids-host.js\";\nexport type { SourceDef } from \"./sourcedef.js\";\nexport * as inputs from \"./inputs.js\";\nexport * as platform from \"./platform.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAM,gBAAgB,UAAUA,KAAG,QAAQ;AAyB3C,MAAM,kCAA2D;CAC/D,MAAM;CACN,YAAY;CACZ,OAAO;AACT;;;;;;;AAQA,SAAgB,YAAY,aAA8C;CACxE,MAAM,UAAU;EAAE,GAAG;EAAiC,GAAG;CAAY;CAErE,MAAM,0BAAoC,kBACxC,QAAQ,UACV;CAEA,IAAIC,KAAG,KAAK,MAAM,SAAS;EACzB,IAAI,QAAQ,SAAS,QACnB,OAAO,UAAU;OAEjB,OAAO,QAAQ,QAAQ,UAAU,CAAC;CAEtC;CAEA,IAAI,QAAQ,SAAS,QACnB,OAAO,sBAAsB,yBAA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GAAW,CAAC,CAAC;GAC3D;EACF;EAEA,MAAM,QAAQ;GACZ,yBAAS,IAAI,KAAK;GAClB,OAAO,KAAK;EACd;EAEA,IAAI;GACF,OACE,MAAM,KAAK,UAAU,EAAA,CACrB,KAAK,gBAAgB;IACrB,MAAM;IACN,SAAS,EACP,SAAS,+BACX;GACF,CAAC;EACH,SAAS,KAAc;GACrB,KAAK,uBAAuB,GAAG;GAE/B,YAAY,MACV,yCAAyC,eAAe,IAAII,iBAAe,GAAG,GAChF;EACF;EACA,KAAK,SAAS,CAAC;CACjB;AACF;AAEA,SAASA,iBAAe,OAAwB;CAC9C,OAAO,iBAAiB,SAAS,OAAO,SAAS,WAC7C,MAAM,SAAS,IACf,KAAK,UAAU,KAAK;AAC1B;AAEA,SAAS,qBACP,eACwB;CACxB,MAAM,iBAAiB,cAAc,kBAAkB,cAAc;CAErE,MAAM,YAAoC;EACxC,MAAM,cAAc;EACpB;EACA,aAAa,cAAc,eAAe;EAC1C,YAAY,cAAc;EAC1B,oBAAoB,cAAc;EAClC,YAAY,cAAc;EAC1B,oBAAoB,cAAc,sBAAsB;GACtD;GACA;GACA,cAAc;EAChB;EACA,qBACE,cAAc,uBAAuB;CACzC;CAEA,YAAY,MAAM,iBAAiB;CACnC,YAAY,MAAM,KAAK,UAAU,WAAW,KAAA,GAAW,CAAC,CAAC;CAEzD,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["exec","os","actionsExec","fs","inputs.getNumberOrUndefined","otel.Telemetry","inputs.getBool","inputs.getBoolOrUndefined","correlation.identify","platform.getArchOs","platform.getNixPlatform","ghActionsCorePlatform\n .getDetails","stringifyError","sourcedef.constructSourceParameters","otel.withSpan","otel.exportEnabled","otel.newTraceparent","otel\n .getTracer","otel.contextFromTraceparent","otel.traceparentOf","otel.otlpExportEnvironment","inputs.getStringOrNull","checksums.sha256OfBuffer","checksums.parseChecksumsFile","checksums.sha256OfFile","ghActionsCorePlatform.platform","ghActionsCorePlatform.arch"],"sources":["../src/linux-release-info.ts","../src/actions-core-platform.ts","../src/checksums.ts","../src/correlation.ts","../src/errors.ts","../src/telemetry.ts","../src/ids-host.ts","../src/inputs.ts","../src/log.ts","../src/platform.ts","../src/sourcedef.ts","../src/index.ts"],"sourcesContent":["/*!\n * linux-release-info\n * Get Linux release info (distribution name, version, arch, release, etc.)\n * from '/etc/os-release' or '/usr/lib/os-release' files and from native os\n * module. On Windows and Darwin platforms it only returns common node os module\n * info (platform, hostname, release, and arch)\n *\n * Licensed under MIT\n * Copyright (c) 2018-2020 [Samuel Carreira]\n */\n// NOTE: we depend on this directly to get around some un-fun issues with mixing CommonJS\n// and ESM in the bundle. We've modified the original logic to improve things like typing\n// and fixing ESLint issues. Originally drawn from:\n// https://github.com/samuelcarreira/linux-release-info/blob/84a91aa5442b47900da03020c590507545d3dc74/src/index.ts\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport { promisify } from \"node:util\";\n\nconst readFileAsync = promisify(fs.readFile);\n\nexport interface LinuxReleaseInfoOptions {\n /**\n * read mode, possible values: 'async' and 'sync'\n *\n * @default 'async'\n */\n mode?: \"async\" | \"sync\";\n /**\n * custom complete file path with os info default null/none\n * if not provided the system will search on the '/etc/os-release'\n * and '/usr/lib/os-release' files\n *\n * @default null\n */\n customFile?: string | null | undefined;\n /**\n * if true, show console debug messages\n *\n * @default false\n */\n debug?: boolean;\n}\n\nconst linuxReleaseInfoOptionsDefaults: LinuxReleaseInfoOptions = {\n mode: \"async\",\n customFile: null,\n debug: false,\n};\n\n/**\n * Get OS release info from 'os-release' file and from native os module\n * on Windows or Darwin it only returns common os module info\n * (uses native fs module)\n * @returns {object} info from the current os\n */\nexport function releaseInfo(infoOptions: LinuxReleaseInfoOptions): object {\n const options = { ...linuxReleaseInfoOptionsDefaults, ...infoOptions };\n\n const searchOsReleaseFileList: string[] = osReleaseFileList(\n options.customFile,\n );\n\n if (os.type() !== \"Linux\") {\n if (options.mode === \"sync\") {\n return getOsInfo();\n } else {\n return Promise.resolve(getOsInfo());\n }\n }\n\n if (options.mode === \"sync\") {\n return readSyncOsreleaseFile(searchOsReleaseFileList, options);\n } else {\n return Promise.resolve(\n readAsyncOsReleaseFile(searchOsReleaseFileList, options),\n );\n }\n}\n\n/**\n * Format file data: convert data to object keys/values\n *\n * @param {object} sourceData Source object to be appended\n * @param {string} srcParseData Input file data to be parsed\n * @returns {object} Formated object\n */\nfunction formatFileData(sourceData: OsInfo, srcParseData: string): OsInfo {\n const lines: string[] = srcParseData.split(\"\\n\");\n\n for (const line of lines) {\n const lineData = line.split(\"=\");\n\n if (lineData.length === 2) {\n lineData[1] = lineData[1].replace(/[\"'\\r]/gi, \"\"); // remove quotes and return character\n\n Object.defineProperty(sourceData, lineData[0].toLowerCase(), {\n value: lineData[1],\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n }\n\n return sourceData;\n}\n\n/**\n * Export a list of os-release files\n *\n * @param {string} customFile optional custom complete filepath\n * @returns {array} list of os-release files\n */\nfunction osReleaseFileList(customFile: string | null | undefined): string[] {\n const DEFAULT_OS_RELEASE_FILES = [\"/etc/os-release\", \"/usr/lib/os-release\"];\n\n if (!customFile) {\n return DEFAULT_OS_RELEASE_FILES;\n } else {\n return Array(customFile);\n }\n}\n\n/**\n * Operating system info.\n */\ntype OsInfo = {\n type: string;\n platform: string;\n hostname: string;\n arch: string;\n release: string;\n};\n\n/**\n * Get OS Basic Info\n * (uses node 'os' native module)\n *\n * @returns {OsInfo} os basic info\n */\nfunction getOsInfo(): OsInfo {\n return {\n type: os.type(),\n platform: os.platform(),\n hostname: os.hostname(),\n arch: os.arch(),\n release: os.release(),\n };\n}\n\n/* Helper functions */\n\nasync function readAsyncOsReleaseFile(\n fileList: string[],\n options: LinuxReleaseInfoOptions,\n): Promise<OsInfo> {\n let fileData = null;\n\n for (const osReleaseFile of fileList) {\n try {\n if (options.debug) {\n /* eslint-disable no-console */\n console.log(`Trying to read '${osReleaseFile}'...`);\n }\n\n fileData = await readFileAsync(osReleaseFile, \"binary\");\n\n if (options.debug) {\n console.log(`Read data:\\n${fileData}`);\n }\n\n break;\n } catch (error) {\n if (options.debug) {\n console.error(error);\n }\n }\n }\n\n if (fileData === null) {\n throw new Error(\"Cannot read os-release file!\");\n //return getOsInfo();\n }\n\n return formatFileData(getOsInfo(), fileData);\n}\n\nfunction readSyncOsreleaseFile(\n releaseFileList: string[],\n options: LinuxReleaseInfoOptions,\n): OsInfo {\n let fileData = null;\n\n for (const osReleaseFile of releaseFileList) {\n try {\n if (options.debug) {\n console.log(`Trying to read '${osReleaseFile}'...`);\n }\n\n fileData = fs.readFileSync(osReleaseFile, \"binary\");\n\n if (options.debug) {\n console.log(`Read data:\\n${fileData}`);\n }\n\n break;\n } catch (error) {\n if (options.debug) {\n console.error(error);\n }\n }\n }\n\n if (fileData === null) {\n throw new Error(\"Cannot read os-release file!\");\n //return getOsInfo();\n }\n\n return formatFileData(getOsInfo(), fileData);\n}\n","// MIT, mostly lifted from https://github.com/actions/toolkit/blob/5a736647a123ecf8582376bdaee833fbae5b3847/packages/core/src/platform.ts\n// since it isn't in @actions/core 1.10.1 which is their current release as 2024-04-19.\n// Changes: Replaced the lsb_release call in Linux with `linux-release-info` to parse the os-release file directly.\nimport { releaseInfo } from \"./linux-release-info.js\";\nimport * as actionsCore from \"@actions/core\";\nimport * as exec from \"@actions/exec\";\nimport os from \"os\";\n\n/**\n * The name and version of the Action runner's system.\n */\ntype SystemInfo = {\n name: string;\n version: string;\n};\n\n/**\n * Get the name and version of the current Windows system.\n */\nconst getWindowsInfo = async (): Promise<SystemInfo> => {\n const { stdout: version } = await exec.getExecOutput(\n 'powershell -command \"(Get-CimInstance -ClassName Win32_OperatingSystem).Version\"',\n undefined,\n {\n silent: true,\n },\n );\n\n const { stdout: name } = await exec.getExecOutput(\n 'powershell -command \"(Get-CimInstance -ClassName Win32_OperatingSystem).Caption\"',\n undefined,\n {\n silent: true,\n },\n );\n\n return {\n name: name.trim(),\n version: version.trim(),\n };\n};\n\n/**\n * Get the name and version of the current macOS system.\n */\nconst getMacOsInfo = async (): Promise<SystemInfo> => {\n const { stdout } = await exec.getExecOutput(\"sw_vers\", undefined, {\n silent: true,\n });\n\n const version = stdout.match(/ProductVersion:\\s*(.+)/)?.[1] ?? \"\";\n const name = stdout.match(/ProductName:\\s*(.+)/)?.[1] ?? \"\";\n\n return {\n name,\n version,\n };\n};\n\n/**\n * Get the name and version of the current Linux system.\n */\nconst getLinuxInfo = async (): Promise<SystemInfo> => {\n let data: object = {};\n\n try {\n data = releaseInfo({ mode: \"sync\" });\n actionsCore.debug(`Identified release info: ${JSON.stringify(data)}`);\n } catch (e) {\n actionsCore.debug(`Error collecting release info: ${e}`);\n }\n\n return {\n name: getPropertyViaWithDefault(\n data,\n [\"id\", \"name\", \"pretty_name\", \"id_like\"],\n \"unknown\",\n ),\n version: getPropertyViaWithDefault(\n data,\n [\"version_id\", \"version\", \"version_codename\"],\n \"unknown\",\n ),\n };\n};\n\nfunction getPropertyViaWithDefault<T, Property extends string>(\n data: object,\n names: Property[],\n defaultValue: T,\n): T {\n for (const name of names) {\n const ret: T = getPropertyWithDefault(data, name, defaultValue);\n\n if (ret !== defaultValue) {\n return ret;\n }\n }\n\n return defaultValue;\n}\n\nfunction getPropertyWithDefault<T, Property extends string>(\n data: object,\n name: Property,\n defaultValue: T,\n): T {\n if (!data.hasOwnProperty(name)) {\n return defaultValue;\n }\n\n const value = (data as { [K in Property]: T })[name];\n\n // NB. this check won't work for object instances\n if (typeof value !== typeof defaultValue) {\n return defaultValue;\n }\n\n return value;\n}\n\n/**\n * The Action runner's platform.\n */\nexport const platform = os.platform();\n\n/**\n * The Action runner's architecture.\n */\nexport const arch = os.arch();\n\n/**\n * Whether the Action runner is a Windows system.\n */\nexport const isWindows = platform === \"win32\";\n\n/**\n * Whether the Action runner is a macOS system.\n */\nexport const isMacOS = platform === \"darwin\";\n\n/**\n * Whether the Action runner is a Linux system.\n */\nexport const isLinux = platform === \"linux\";\n\n/**\n * System-level information about the current host (platform, architecture, etc.).\n */\ntype SystemDetails = {\n name: string;\n platform: string;\n arch: string;\n version: string;\n isWindows: boolean;\n isMacOS: boolean;\n isLinux: boolean;\n};\n\n/**\n * Get system-level information about the current host (platform, architecture, etc.).\n */\nexport async function getDetails(): Promise<SystemDetails> {\n return {\n ...(await (isWindows\n ? getWindowsInfo()\n : isMacOS\n ? getMacOsInfo()\n : getLinuxInfo())),\n platform,\n arch,\n isWindows,\n isMacOS,\n isLinux,\n };\n}\n","/**\n * @packageDocumentation\n * Parsing and hashing helpers for `shasum`-format checksum files, used to\n * hash-lock downloaded artifacts.\n */\nimport { createHash } from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\n\nconst HEX_STRING_RE = /^[0-9a-fA-F]+$/;\n\n/**\n * Parse a `shasum`-format checksums file into a map of filename -> hex digest.\n *\n * Each non-empty line has the shape `<hex-digest><space(s)><filename>`. Lines\n * without a space delimiter are skipped. Invalid hex digests throw, so a\n * malformed file fails loudly rather than silently skipping the entry we\n * care about.\n */\nexport function parseChecksumsFile(text: string): Map<string, string> {\n const result = new Map<string, string>();\n\n for (const record of text.split(/\\r\\n|\\n|\\r/).filter(Boolean)) {\n const delimIndex = record.indexOf(\" \");\n if (delimIndex === -1) {\n continue;\n }\n\n const digest = record.slice(0, delimIndex);\n if (!HEX_STRING_RE.test(digest)) {\n throw new Error(`Invalid digest in checksums file: ${digest}`);\n }\n\n const name = record.slice(delimIndex + 1).trim();\n if (name === \"\") {\n continue;\n }\n\n result.set(name, digest.toLowerCase());\n }\n\n return result;\n}\n\n/**\n * Compute the SHA-256 of a file on disk and return its lowercase hex digest.\n * Streams the file so memory use is constant regardless of size.\n */\nexport async function sha256OfFile(filePath: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const hash = createHash(\"sha256\").setEncoding(\"hex\");\n createReadStream(filePath)\n .once(\"error\", reject)\n .pipe(hash)\n .once(\"finish\", () => resolve(hash.read() as string));\n });\n}\n\n/**\n * Compute the SHA-256 of an in-memory buffer or string and return its\n * lowercase hex digest.\n */\nexport function sha256OfBuffer(data: Buffer | string): string {\n return createHash(\"sha256\").update(data).digest(\"hex\");\n}\n","import * as actionsCore from \"@actions/core\";\nimport { createHash, randomUUID } from \"node:crypto\";\n\nconst OPTIONAL_VARIABLES = [\"INVOCATION_ID\"];\n\n/* eslint-disable camelcase */\n/**\n * The hashed, non-identifying description of this run.\n *\n * Two consumers fix these names. The check-in evaluates feature flags against\n * them, and the programs an Action runs read them from\n * `$DETSYS_CORRELATION`. The OpenTelemetry data carries the same values under\n * `detsys.` attribute names.\n */\nexport type CorrelationProperties = {\n $anon_distinct_id: string;\n $groups: Record<string, string | undefined>;\n $session_id?: string;\n correlation_source: string;\n github_repository_hash?: string;\n github_workflow_hash?: string;\n github_workflow_job_hash?: string;\n github_workflow_run_differentiator_hash?: string;\n github_workflow_run_hash?: string;\n is_ci: boolean;\n};\n\nexport function identify(): CorrelationProperties {\n const repository = hashEnvironmentVariables(\"GHR\", [\n \"GITHUB_SERVER_URL\",\n \"GITHUB_REPOSITORY_OWNER\",\n \"GITHUB_REPOSITORY_OWNER_ID\",\n \"GITHUB_REPOSITORY\",\n \"GITHUB_REPOSITORY_ID\",\n ]);\n\n const run_differentiator = hashEnvironmentVariables(\"GHWJA\", [\n \"GITHUB_SERVER_URL\",\n \"GITHUB_REPOSITORY_OWNER\",\n \"GITHUB_REPOSITORY_OWNER_ID\",\n \"GITHUB_REPOSITORY\",\n \"GITHUB_REPOSITORY_ID\",\n \"GITHUB_WORKFLOW\",\n \"GITHUB_JOB\",\n \"GITHUB_RUN_ID\",\n \"GITHUB_RUN_NUMBER\",\n \"GITHUB_RUN_ATTEMPT\",\n \"INVOCATION_ID\",\n ]);\n\n const ident: CorrelationProperties = {\n $anon_distinct_id: process.env[\"RUNNER_TRACKING_ID\"] || randomUUID(),\n\n correlation_source: \"github-actions\",\n\n github_repository_hash: repository,\n github_workflow_hash: hashEnvironmentVariables(\"GHW\", [\n \"GITHUB_SERVER_URL\",\n \"GITHUB_REPOSITORY_OWNER\",\n \"GITHUB_REPOSITORY_OWNER_ID\",\n \"GITHUB_REPOSITORY\",\n \"GITHUB_REPOSITORY_ID\",\n \"GITHUB_WORKFLOW\",\n ]),\n github_workflow_job_hash: hashEnvironmentVariables(\"GHWJ\", [\n \"GITHUB_SERVER_URL\",\n \"GITHUB_REPOSITORY_OWNER\",\n \"GITHUB_REPOSITORY_OWNER_ID\",\n \"GITHUB_REPOSITORY\",\n \"GITHUB_REPOSITORY_ID\",\n \"GITHUB_WORKFLOW\",\n \"GITHUB_JOB\",\n ]),\n github_workflow_run_hash: hashEnvironmentVariables(\"GHWJR\", [\n \"GITHUB_SERVER_URL\",\n \"GITHUB_REPOSITORY_OWNER\",\n \"GITHUB_REPOSITORY_OWNER_ID\",\n \"GITHUB_REPOSITORY\",\n \"GITHUB_REPOSITORY_ID\",\n \"GITHUB_WORKFLOW\",\n \"GITHUB_JOB\",\n \"GITHUB_RUN_ID\",\n ]),\n github_workflow_run_differentiator_hash: run_differentiator,\n $session_id: run_differentiator,\n $groups: {\n github_repository: repository,\n github_organization: hashEnvironmentVariables(\"GHO\", [\n \"GITHUB_SERVER_URL\",\n \"GITHUB_REPOSITORY_OWNER\",\n \"GITHUB_REPOSITORY_OWNER_ID\",\n ]),\n },\n is_ci: true,\n };\n\n actionsCore.debug(\"Correlation data:\");\n actionsCore.debug(JSON.stringify(ident, null, 2));\n\n return ident;\n}\n\nfunction hashEnvironmentVariables(\n prefix: string,\n variables: string[],\n): undefined | string {\n const hash = createHash(\"sha256\");\n\n for (const varName of variables) {\n let value = process.env[varName];\n\n if (value === undefined) {\n if (OPTIONAL_VARIABLES.includes(varName)) {\n actionsCore.debug(\n `Optional environment variable not set: ${varName} -- substituting with the variable name`,\n );\n value = varName;\n } else {\n actionsCore.debug(\n `Environment variable not set: ${varName} -- can't generate the requested identity`,\n );\n return undefined;\n }\n }\n\n hash.update(value);\n hash.update(\"\\0\");\n }\n\n return `${prefix}-${hash.digest(\"hex\")}`;\n}\n","/**\n * Coerce a value of type `unknown` into a string.\n */\nexport function stringifyError(e: unknown): string {\n if (e instanceof Error) {\n return e.message;\n } else if (typeof e === \"string\") {\n return e;\n } else {\n return JSON.stringify(e);\n }\n}\n","/**\n * @packageDocumentation\n * OpenTelemetry traces and logs for Determinate Systems' GitHub Actions.\n *\n * The OpenTelemetry API is a no-op until a provider is registered globally.\n * That means instrumentation call sites -- spans, log records -- can be\n * written unconditionally: when export is disabled they cost nothing and no\n * branching is needed at the call site.\n *\n * The SDK configures itself from the standard `OTEL_*` environment variables.\n * This module only supplies defaults for the variables the user has not set,\n * so every documented OpenTelemetry knob works here as it does anywhere else.\n */\nimport { stringifyError } from \"./errors.js\";\nimport * as actionsCore from \"@actions/core\";\nimport * as otelApi from \"@opentelemetry/api\";\nimport { type Logger, SeverityNumber, logs } from \"@opentelemetry/api-logs\";\nimport { AsyncLocalStorageContextManager } from \"@opentelemetry/context-async-hooks\";\nimport * as otelCore from \"@opentelemetry/core\";\nimport { OTLPLogExporter } from \"@opentelemetry/exporter-logs-otlp-http\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\";\nimport * as otelResources from \"@opentelemetry/resources\";\nimport * as sdkLogs from \"@opentelemetry/sdk-logs\";\nimport * as sdkTrace from \"@opentelemetry/sdk-trace-base\";\nimport * as semconv from \"@opentelemetry/semantic-conventions\";\nimport { randomBytes } from \"node:crypto\";\n\n/** The instrumentation scope name for everything this library emits. */\nexport const SCOPE_NAME = \"detsys-ts\";\n\n/** The version reported as the instrumentation scope's version. */\nexport const LIBRARY_VERSION = \"1.0\";\n\n/**\n * The OTLP/HTTP collector for all Actions.\n * The exporters add `/v1/traces` and `/v1/logs` to this URL.\n *\n * This collector is a fixed service.\n * It is not one of the install.determinate.systems backends.\n * Thus it does not use their SRV failover.\n */\nconst DEFAULT_OTLP_ENDPOINT = \"https://otel.determinate.systems\";\n\n/**\n * The token for {@link DEFAULT_OTLP_ENDPOINT}.\n * The exporters send it as `Authorization: Bearer <token>`.\n * That is the default scheme of the collector's `bearertokenauth` extension.\n *\n * This token is public.\n * It ships in `dist/`, on npm, and in each workflow that uses this library.\n * It permits telemetry writes and no other operation.\n * Change it in the collector configuration and in this file at the same time.\n */\nconst OTLP_INGEST_TOKEN =\n \"8bfa2d8b689352981286f0149c4e55cc0dff30a4f7a735b560e31479904a74e1\";\n\n/**\n * How long to wait for buffered spans and logs to reach the collector before\n * giving up. The Action's process exits immediately afterward, so this is a\n * hard ceiling on how much a slow collector can delay a workflow.\n */\nconst SHUTDOWN_TIMEOUT_MS = 5_000;\n\n/**\n * The default for `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`.\n *\n * The SDK's own default is unlimited. Attributes here can carry pasted\n * command output and other unbounded text, which the collector should not\n * have to absorb, so cap them. File-sized payloads go out as log records\n * instead: a log record's body is not an attribute and is not truncated.\n */\nconst DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = 8_192;\n\n/** The OTLP environment variables a child process inherits from this run. */\nconst OTLP_EXPORT_VARIABLES = [\n \"OTEL_EXPORTER_OTLP_ENDPOINT\",\n \"OTEL_EXPORTER_OTLP_HEADERS\",\n \"OTEL_EXPORTER_OTLP_COMPRESSION\",\n] as const;\n\n/**\n * Our own propagator instance, rather than the global one.\n *\n * The global propagator only exists once {@link Telemetry.start} has\n * registered it, which would make traceparent handling silently depend on\n * start-up ordering. Owning an instance keeps {@link traceparentOf} and {@link\n * contextFromTraceparent} correct no matter when they're called.\n */\nconst PROPAGATOR = new otelCore.W3CTraceContextPropagator();\n\n/** The severities we map GitHub Actions' log levels onto. */\nexport type LogLevel = \"debug\" | \"info\" | \"notice\" | \"warning\" | \"error\";\n\nconst SEVERITY: Record<LogLevel, SeverityNumber> = {\n debug: SeverityNumber.DEBUG,\n info: SeverityNumber.INFO,\n notice: SeverityNumber.INFO2,\n warning: SeverityNumber.WARN,\n error: SeverityNumber.ERROR,\n};\n\nexport type TelemetryOptions = {\n /** The `service.name` for this run, unless `OTEL_SERVICE_NAME` overrides it. */\n serviceName: string;\n\n /** The `service.version` for this run, when it is known. */\n serviceVersion?: string;\n\n /** Resource attributes for this run, added to each span and log record. */\n resourceAttributes: otelApi.Attributes;\n};\n\n/**\n * Whether this run exports telemetry at all.\n *\n * `OTEL_SDK_DISABLED=true` is the standard way to turn the export off. An\n * empty `OTEL_EXPORTER_OTLP_ENDPOINT` does the same, which is what this\n * library documented before `OTEL_SDK_DISABLED` was in the specification.\n */\nexport function exportEnabled(): boolean {\n if (otelCore.getBooleanFromEnv(\"OTEL_SDK_DISABLED\")) {\n return false;\n }\n\n const endpoint = process.env[\"OTEL_EXPORTER_OTLP_ENDPOINT\"];\n if (endpoint !== undefined && endpoint.trim() === \"\") {\n return false;\n }\n\n return true;\n}\n\n/**\n * Fill in the `OTEL_*` variables this run needs and the user has not set.\n *\n * From here on the exporters read their whole configuration from the\n * environment, exactly as they would in any other OpenTelemetry program.\n * Child processes inherit the same variables, so their telemetry reaches the\n * same collector without any further arrangement.\n */\nexport function applyOtlpEnvironmentDefaults(): void {\n if (otelCore.getStringFromEnv(\"OTEL_EXPORTER_OTLP_ENDPOINT\") === undefined) {\n process.env[\"OTEL_EXPORTER_OTLP_ENDPOINT\"] = DEFAULT_OTLP_ENDPOINT;\n }\n\n if (exportsToDefaultCollector()) {\n // The collector refuses data that carries no token. Leave a token the\n // user supplied alone: theirs is the one they meant to use.\n const headers = otelCore.parseKeyPairsIntoRecord(\n otelCore.getStringFromEnv(\"OTEL_EXPORTER_OTLP_HEADERS\"),\n );\n\n const authorized = Object.keys(headers).some(\n (name) => name.toLowerCase() === \"authorization\",\n );\n\n if (!authorized) {\n headers[\"Authorization\"] = `Bearer ${OTLP_INGEST_TOKEN}`;\n process.env[\"OTEL_EXPORTER_OTLP_HEADERS\"] = encodeOtlpHeaders(headers);\n }\n }\n\n if (\n otelCore.getStringFromEnv(\"OTEL_EXPORTER_OTLP_COMPRESSION\") === undefined\n ) {\n // Installer logs go out as log records, so the bodies are large and\n // highly compressible.\n process.env[\"OTEL_EXPORTER_OTLP_COMPRESSION\"] = \"gzip\";\n }\n\n if (\n otelCore.getNumberFromEnv(\"OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT\") === undefined\n ) {\n process.env[\"OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT\"] =\n `${DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT}`;\n }\n}\n\n/**\n * Whether this run sends its data to {@link DEFAULT_OTLP_ENDPOINT}.\n *\n * Only that collector gets {@link OTLP_INGEST_TOKEN}. A collector the user\n * chose must not receive our credentials.\n */\nfunction exportsToDefaultCollector(): boolean {\n const endpoint = otelCore.getStringFromEnv(\"OTEL_EXPORTER_OTLP_ENDPOINT\");\n\n if (endpoint === undefined) {\n return false;\n }\n\n try {\n return (\n new URL(endpoint).toString() === new URL(DEFAULT_OTLP_ENDPOINT).toString()\n );\n } catch {\n return false;\n }\n}\n\n/**\n * The OTLP variables in the environment, for a child process that does not\n * inherit ours.\n */\nexport function otlpExportEnvironment(): Record<string, string> {\n const environment: Record<string, string> = {};\n\n for (const name of OTLP_EXPORT_VARIABLES) {\n const value = otelCore.getStringFromEnv(name);\n if (value !== undefined) {\n environment[name] = value;\n }\n }\n\n return environment;\n}\n\n/**\n * Make the value of `OTEL_EXPORTER_OTLP_HEADERS`.\n *\n * The variable uses the W3C baggage format.\n * The reader decodes each percent-encoded value.\n * Thus you must encode the space in `Bearer <token>`.\n * If you do not encode it, the scheme and the token become two entries.\n */\nexport function encodeOtlpHeaders(headers: Record<string, string>): string {\n return Object.entries(headers)\n .map(\n ([name, value]) =>\n `${encodeURIComponent(name)}=${encodeURIComponent(value)}`,\n )\n .join(\",\");\n}\n\n/**\n * The generator of the trace and span IDs of this run.\n *\n * It makes random IDs, as the default generator does.\n * It can also give one span an identity that you supply.\n * That is how a span that one process announces starts in a different process.\n * See {@link Telemetry.startAnnouncedSpan}.\n */\nclass PinnedIdGenerator implements sdkTrace.IdGenerator {\n private traceId?: string;\n private spanId?: string;\n\n /** Give the next span this identity. */\n pin(traceId: string, spanId: string): void {\n this.traceId = traceId;\n this.spanId = spanId;\n }\n\n /** Give each subsequent span a random identity again. */\n unpin(): void {\n this.traceId = undefined;\n this.spanId = undefined;\n }\n\n generateTraceId(): string {\n return this.traceId ?? randomHex(16);\n }\n\n generateSpanId(): string {\n return this.spanId ?? randomHex(8);\n }\n}\n\n/**\n * Owns the OpenTelemetry SDK's lifecycle. Constructing this does nothing on\n * its own; `start()` registers the global providers and `shutdown()` flushes\n * whatever is buffered.\n */\nexport class Telemetry {\n private tracerProvider?: sdkTrace.BasicTracerProvider;\n private loggerProvider?: sdkLogs.LoggerProvider;\n private idGenerator?: PinnedIdGenerator;\n\n /** Whether OTLP export is actually running. */\n get enabled(): boolean {\n return this.tracerProvider !== undefined;\n }\n\n /**\n * Register the global tracer and logger providers.\n *\n * Safe to call at most once. If it throws, telemetry stays disabled and the\n * Action carries on: instrumentation degrades to the API's no-ops rather\n * than failing the workflow.\n */\n start(options: TelemetryOptions): void {\n if (this.enabled || !exportEnabled()) {\n return;\n }\n\n try {\n applyOtlpEnvironmentDefaults();\n\n // `envDetector` comes last, so `OTEL_SERVICE_NAME` and\n // `OTEL_RESOURCE_ATTRIBUTES` win over what the Action decided.\n const resource = otelResources\n .defaultResource()\n .merge(\n otelResources.resourceFromAttributes({\n [semconv.ATTR_SERVICE_NAME]: options.serviceName,\n ...(options.serviceVersion === undefined\n ? {}\n : { [semconv.ATTR_SERVICE_VERSION]: options.serviceVersion }),\n ...options.resourceAttributes,\n }),\n )\n .merge(\n otelResources.detectResources({\n detectors: [otelResources.envDetector],\n }),\n );\n\n this.idGenerator = new PinnedIdGenerator();\n\n // The exporters read the endpoint, the headers, the compression, and\n // the timeouts from the environment.\n this.tracerProvider = new sdkTrace.BasicTracerProvider({\n resource,\n idGenerator: this.idGenerator,\n spanProcessors: [\n new sdkTrace.BatchSpanProcessor(new OTLPTraceExporter()),\n ],\n });\n\n this.loggerProvider = new sdkLogs.LoggerProvider({\n resource,\n // Unlike the tracer provider, this one does not read the limit from\n // the environment itself.\n logRecordLimits: {\n attributeValueLengthLimit: otelCore.getNumberFromEnv(\n \"OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT\",\n ),\n },\n processors: [\n new sdkLogs.BatchLogRecordProcessor({\n exporter: new OTLPLogExporter(),\n }),\n ],\n });\n\n // AsyncLocalStorage keeps the active span attached across `await`s, so\n // nested spans parent themselves correctly without threading a Context\n // argument through every function.\n otelApi.context.setGlobalContextManager(\n new AsyncLocalStorageContextManager().enable(),\n );\n otelApi.propagation.setGlobalPropagator(PROPAGATOR);\n otelApi.trace.setGlobalTracerProvider(this.tracerProvider);\n logs.setGlobalLoggerProvider(this.loggerProvider);\n\n actionsCore.debug(\n `OpenTelemetry export enabled to ${otelCore.getStringFromEnv(\"OTEL_EXPORTER_OTLP_ENDPOINT\")}`,\n );\n } catch (e: unknown) {\n this.tracerProvider = undefined;\n this.loggerProvider = undefined;\n this.idGenerator = undefined;\n actionsCore.debug(\n `Failed to start OpenTelemetry export, continuing without it: ${stringifyError(e)}`,\n );\n }\n }\n\n /**\n * Start the span that {@link newTraceparent} announced.\n *\n * A workflow job runs each Action as a process of its own.\n * Thus a span that covers more than one Action can only start in one of them.\n * The Action that announces such a span makes its identity known first, and\n * starts the span itself last, in the process that runs at the end.\n * The spans that already point at that identity then find their parent.\n *\n * The span starts at `startTime`, which is the moment of the announcement.\n * It is a child of the span in `parentContext`, and a root span if that\n * context holds no span.\n *\n * Returns undefined if the export is off, or if `traceparent` does not name a\n * usable span.\n */\n startAnnouncedSpan(\n name: string,\n traceparent: string,\n startTime: Date,\n parentContext: otelApi.Context = otelApi.ROOT_CONTEXT,\n ): otelApi.Span | undefined {\n const generator = this.idGenerator;\n const spanContext = otelApi.trace.getSpanContext(\n contextFromTraceparent(traceparent),\n );\n\n if (\n generator === undefined ||\n this.tracerProvider === undefined ||\n spanContext === undefined ||\n !otelApi.isSpanContextValid(spanContext)\n ) {\n return undefined;\n }\n\n // The tracer comes from this provider, and not from the global one,\n // because the identity is pinned in this provider's ID generator.\n const tracer = this.tracerProvider.getTracer(SCOPE_NAME, LIBRARY_VERSION);\n\n try {\n generator.pin(spanContext.traceId, spanContext.spanId);\n return tracer.startSpan(name, { startTime }, parentContext);\n } finally {\n generator.unpin();\n }\n }\n\n /**\n * Flush buffered spans and logs and tear the SDK down.\n *\n * Never throws and never hangs: the Action calls this on its way out, so a\n * broken or slow collector must not be able to fail or stall the workflow.\n */\n async shutdown(): Promise<void> {\n const providers = [this.tracerProvider, this.loggerProvider].flatMap(\n (p) => p ?? [],\n );\n\n if (providers.length === 0) {\n return;\n }\n\n try {\n await withTimeout(\n Promise.all(providers.map(async (p) => p.shutdown())),\n SHUTDOWN_TIMEOUT_MS,\n );\n } catch (e: unknown) {\n actionsCore.debug(\n `Error flushing OpenTelemetry data: ${stringifyError(e)}`,\n );\n } finally {\n this.tracerProvider = undefined;\n this.loggerProvider = undefined;\n this.idGenerator = undefined;\n }\n }\n}\n\n/**\n * The tracer for this library. Returns a no-op tracer until {@link\n * Telemetry.start} has run, so this is always safe to call.\n */\nexport function getTracer(): otelApi.Tracer {\n return otelApi.trace.getTracer(SCOPE_NAME, LIBRARY_VERSION);\n}\n\n/**\n * The logger for this library. Returns a no-op logger until {@link\n * Telemetry.start} has run, so this is always safe to call.\n */\nexport function getLogger(): Logger {\n return logs.getLogger(SCOPE_NAME, LIBRARY_VERSION);\n}\n\n/**\n * Emit a log record at `level`, correlated to whatever span is currently\n * active.\n */\nexport function emitLogRecord(\n level: LogLevel,\n message: string,\n attributes?: otelApi.Attributes,\n): void {\n getLogger().emit({\n severityNumber: SEVERITY[level],\n severityText: level.toUpperCase(),\n body: message,\n attributes,\n context: otelApi.context.active(),\n });\n}\n\n/**\n * Serialize a span as a W3C `traceparent` header value, suitable for stashing\n * in the Action's state or handing to a child process.\n *\n * Returns undefined when telemetry is disabled, since the no-op span's context\n * is all zeroes and would not be a valid parent.\n */\nexport function traceparentOf(\n span: otelApi.Span | undefined,\n): string | undefined {\n if (span === undefined || !otelApi.isSpanContextValid(span.spanContext())) {\n return undefined;\n }\n\n const carrier: Record<string, string> = {};\n PROPAGATOR.inject(\n otelApi.trace.setSpan(otelApi.ROOT_CONTEXT, span),\n carrier,\n otelApi.defaultTextMapSetter,\n );\n\n return carrier[\"traceparent\"];\n}\n\n/**\n * Make the identity of a span, but do not start the span.\n *\n * Announce the result to whatever must point at the span before it starts:\n * a different process, or a request this process makes too early to record.\n * Start the span itself with {@link Telemetry.startAnnouncedSpan}.\n *\n * The span is in the trace of `parent`, or in a new trace of its own if there\n * is no usable parent.\n * A new trace is sampled, because a process that only forwards an identity\n * cannot ask the sampler, and an unsampled parent would discard the work of\n * each process that joins.\n */\nexport function newTraceparent(parent?: string): string {\n const parentContext = otelApi.trace.getSpanContext(\n contextFromTraceparent(parent),\n );\n\n if (\n parentContext !== undefined &&\n otelApi.isSpanContextValid(parentContext)\n ) {\n const flags = parentContext.traceFlags.toString(16).padStart(2, \"0\");\n return `00-${parentContext.traceId}-${randomHex(8)}-${flags}`;\n }\n\n return `00-${randomHex(16)}-${randomHex(8)}-01`;\n}\n\n/**\n * The W3C trace context headers of the operation in progress, for an outgoing\n * HTTP request.\n *\n * Put these headers on the request.\n * The service that answers it can then put its own work in this trace.\n *\n * The headers describe the span that is active now.\n * When no span is active yet -- a request the Action makes before it starts a\n * span of its own -- they describe the span that `$TRACEPARENT` names, which is\n * the span the Action announced, or the span of the workflow job.\n *\n * The result is empty when the export is off.\n * A no-op span's context is all zeroes, and is not a valid parent.\n */\nexport function traceContextHeaders(): Record<string, string> {\n const active = otelApi.context.active();\n const context =\n otelApi.trace.getSpanContext(active) === undefined\n ? contextFromTraceparent(process.env[\"TRACEPARENT\"])\n : active;\n\n const carrier: Record<string, string> = {};\n PROPAGATOR.inject(context, carrier, otelApi.defaultTextMapSetter);\n\n return carrier;\n}\n\n/**\n * Rebuild a Context from a W3C `traceparent` value, so a span started in one\n * process can parent spans started in another. Falls back to the root context\n * when `traceparent` is absent or unparseable.\n */\nexport function contextFromTraceparent(\n traceparent: string | undefined,\n): otelApi.Context {\n if (traceparent === undefined || traceparent === \"\") {\n return otelApi.ROOT_CONTEXT;\n }\n\n return PROPAGATOR.extract(\n otelApi.ROOT_CONTEXT,\n { traceparent },\n otelApi.defaultTextMapGetter,\n );\n}\n\n/**\n * Mark `span` as failed and attach the exception to it.\n */\nexport function recordSpanError(span: otelApi.Span, error: unknown): void {\n span.recordException(\n error instanceof Error ? error : new Error(stringifyError(error)),\n );\n span.setStatus({\n code: otelApi.SpanStatusCode.ERROR,\n message: stringifyError(error),\n });\n}\n\n/**\n * Run `fn` inside a new active span, ending the span when it settles and\n * marking it failed if it throws. The error is always re-thrown: this records,\n * it does not swallow.\n */\nexport async function withSpan<T>(\n name: string,\n fn: (span: otelApi.Span) => Promise<T>,\n attributes?: otelApi.Attributes,\n): Promise<T> {\n return await getTracer().startActiveSpan(\n name,\n { attributes },\n async (span) => {\n try {\n return await fn(span);\n } catch (e: unknown) {\n recordSpanError(span, e);\n throw e;\n } finally {\n span.end();\n }\n },\n );\n}\n\n/** A random ID of `bytes` bytes, in the lowercase hex the W3C format uses. */\nfunction randomHex(bytes: number): string {\n return randomBytes(bytes).toString(\"hex\");\n}\n\n/** Reject if `promise` has not settled within `timeoutMs`. */\nasync function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(\n () => reject(new Error(`timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n }),\n ]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n}\n","/**\n * @packageDocumentation\n * Identifies and discovers backend servers for install.determinate.systems\n */\nimport { stringifyError } from \"./errors.js\";\nimport { traceContextHeaders } from \"./telemetry.js\";\nimport * as actionsCore from \"@actions/core\";\nimport got, { type Got } from \"got\";\nimport type { SrvRecord } from \"node:dns\";\nimport { resolveSrv } from \"node:dns/promises\";\n\nconst DEFAULT_LOOKUP = \"_detsys_ids._tcp.install.determinate.systems.\";\nconst ALLOWED_SUFFIXES = [\n \".install.determinate.systems\",\n \".install.detsys.dev\",\n];\n\nconst DEFAULT_IDS_HOST = \"https://install.determinate.systems\";\nconst LOOKUP = process.env[\"IDS_LOOKUP\"] ?? DEFAULT_LOOKUP;\n\nconst DEFAULT_TIMEOUT = 10_000; // 10 seconds in ms\n\n/**\n * Host information for install.determinate.systems.\n */\nexport class IdsHost {\n private idsProjectName: string;\n private diagnosticsSuffix?: string;\n private runtimeDiagnosticsUrl?: string;\n private prioritizedURLs?: URL[];\n private client?: Got;\n private timeout: number;\n\n constructor(\n idsProjectName: string,\n diagnosticsSuffix: string | undefined,\n runtimeDiagnosticsUrl: string | undefined,\n timeout: number = DEFAULT_TIMEOUT,\n ) {\n this.idsProjectName = idsProjectName;\n this.diagnosticsSuffix = diagnosticsSuffix;\n this.runtimeDiagnosticsUrl = runtimeDiagnosticsUrl;\n this.client = undefined;\n this.timeout = timeout;\n }\n\n async getGot(\n recordFailoverCallback?: (\n incitingError: unknown,\n prevUrl: URL,\n nextUrl: URL,\n ) => void,\n ): Promise<Got> {\n if (this.client === undefined) {\n this.client = got.extend({\n timeout: {\n request: this.timeout,\n },\n\n retry: {\n limit: Math.max((await this.getUrlsByPreference()).length, 3),\n methods: [\"GET\", \"HEAD\"],\n },\n\n hooks: {\n beforeRetry: [\n async (error, retryCount) => {\n const prevUrl = await this.getRootUrl();\n this.markCurrentHostBroken();\n const nextUrl = await this.getRootUrl();\n\n if (recordFailoverCallback !== undefined) {\n recordFailoverCallback(error, prevUrl, nextUrl);\n }\n\n actionsCore.info(\n `Retrying after error ${error.code}, retry #: ${retryCount}`,\n );\n },\n ],\n\n beforeRequest: [\n async (options) => {\n // Send the trace context, so the service puts the work it does\n // for this request in this Action's trace.\n for (const [name, value] of Object.entries(\n traceContextHeaders(),\n )) {\n options.headers[name] = value;\n }\n\n // The getter always returns a URL, even though the setter accepts a string\n const currentUrl: URL = options.url as URL;\n\n if (this.isUrlSubjectToDynamicUrls(currentUrl)) {\n const newUrl: URL = new URL(currentUrl);\n\n const url: URL = await this.getRootUrl();\n newUrl.host = url.host;\n\n options.url = newUrl;\n actionsCore.debug(`Transmuted ${currentUrl} into ${newUrl}`);\n } else {\n actionsCore.debug(`No transmutations on ${currentUrl}`);\n }\n },\n ],\n },\n });\n }\n\n return this.client;\n }\n\n markCurrentHostBroken(): void {\n this.prioritizedURLs?.shift();\n }\n\n setPrioritizedUrls(urls: URL[]): void {\n this.prioritizedURLs = urls;\n }\n\n isUrlSubjectToDynamicUrls(url: URL): boolean {\n if (url.origin === DEFAULT_IDS_HOST) {\n return true;\n }\n\n for (const suffix of ALLOWED_SUFFIXES) {\n if (url.host.endsWith(suffix)) {\n return true;\n }\n }\n\n return false;\n }\n\n async getDynamicRootUrl(): Promise<URL | undefined> {\n const idsHost = process.env[\"IDS_HOST\"];\n if (idsHost !== undefined) {\n try {\n return new URL(idsHost);\n } catch (err: unknown) {\n actionsCore.error(\n `IDS_HOST environment variable is not a valid URL. Ignoring. ${stringifyError(err)}`,\n );\n }\n }\n\n let url: URL | undefined = undefined;\n try {\n const urls = await this.getUrlsByPreference();\n url = urls[0];\n } catch (err: unknown) {\n actionsCore.error(\n `Error collecting IDS URLs by preference: ${stringifyError(err)}`,\n );\n }\n\n if (url === undefined) {\n return undefined;\n } else {\n // This is a load-bearing `new URL(url)` so that callers can't mutate\n // getRootUrl's return value.\n return new URL(url);\n }\n }\n\n async getRootUrl(): Promise<URL> {\n const url = await this.getDynamicRootUrl();\n\n if (url === undefined) {\n return new URL(DEFAULT_IDS_HOST);\n }\n\n return url;\n }\n\n /**\n * The diagnostics endpoint of the current backend.\n *\n * This library reports nothing there: its telemetry is OpenTelemetry. The\n * URL is for the programs an Action runs, which have diagnostics of their\n * own.\n */\n async getDiagnosticsUrl(): Promise<URL | undefined> {\n if (this.runtimeDiagnosticsUrl === \"\") {\n // User specifically set the diagnostics URL to an empty string\n // so disable diagnostics\n return undefined;\n }\n\n if (\n this.runtimeDiagnosticsUrl !== \"-\" &&\n this.runtimeDiagnosticsUrl !== undefined\n ) {\n try {\n // Caller specified a specific diagnostics URL\n return new URL(this.runtimeDiagnosticsUrl);\n } catch (err: unknown) {\n actionsCore.info(\n `User-provided diagnostic endpoint ignored: not a valid URL: ${stringifyError(err)}`,\n );\n }\n }\n\n try {\n const diagnosticUrl = await this.getRootUrl();\n diagnosticUrl.pathname += \"events/batch\";\n return diagnosticUrl;\n } catch (err: unknown) {\n actionsCore.info(\n `Generated diagnostic endpoint ignored, and diagnostics are disabled: not a valid URL: ${stringifyError(err)}`,\n );\n return undefined;\n }\n }\n\n private async getUrlsByPreference(): Promise<URL[]> {\n if (this.prioritizedURLs === undefined) {\n this.prioritizedURLs = orderRecordsByPriorityWeight(\n await discoverServiceRecords(),\n ).flatMap((record) => recordToUrl(record) || []);\n }\n\n return this.prioritizedURLs;\n }\n}\n\nexport function recordToUrl(record: SrvRecord): URL | undefined {\n const urlStr = `https://${record.name}:${record.port}`;\n try {\n return new URL(urlStr);\n } catch (err: unknown) {\n actionsCore.debug(\n `Record ${JSON.stringify(record)} produced an invalid URL: ${urlStr} (${err})`,\n );\n return undefined;\n }\n}\n\nasync function discoverServiceRecords(): Promise<SrvRecord[]> {\n return await discoverServicesStub(resolveSrv(LOOKUP), 1_000);\n}\n\nexport async function discoverServicesStub(\n lookup: Promise<SrvRecord[]>,\n timeout: number,\n): Promise<SrvRecord[]> {\n const defaultFallback: Promise<SrvRecord[]> = new Promise(\n (resolve, _reject) => {\n setTimeout(resolve, timeout, []);\n },\n );\n\n let records: SrvRecord[];\n\n try {\n records = await Promise.race([lookup, defaultFallback]);\n } catch (reason: unknown) {\n actionsCore.debug(`Error resolving SRV records: ${stringifyError(reason)}`);\n records = [];\n }\n\n const acceptableRecords = records.filter((record: SrvRecord): boolean => {\n for (const suffix of ALLOWED_SUFFIXES) {\n if (record.name.endsWith(suffix)) {\n return true;\n }\n }\n\n actionsCore.debug(\n `Unacceptable domain due to an invalid suffix: ${record.name}`,\n );\n\n return false;\n });\n\n if (acceptableRecords.length === 0) {\n actionsCore.debug(`No records found for ${LOOKUP}`);\n } else {\n actionsCore.debug(\n `Resolved ${LOOKUP} to ${JSON.stringify(acceptableRecords)}`,\n );\n }\n\n return acceptableRecords;\n}\n\nexport function orderRecordsByPriorityWeight(\n records: SrvRecord[],\n): SrvRecord[] {\n const byPriorityWeight: Map<number, SrvRecord[]> = new Map();\n for (const record of records) {\n const existing = byPriorityWeight.get(record.priority);\n if (existing) {\n existing.push(record);\n } else {\n byPriorityWeight.set(record.priority, [record]);\n }\n }\n\n const prioritizedRecords: SrvRecord[] = [];\n const keys: number[] = Array.from(byPriorityWeight.keys()).sort(\n (a, b) => a - b,\n );\n\n for (const priority of keys) {\n const recordsByPrio = byPriorityWeight.get(priority);\n if (recordsByPrio === undefined) {\n continue;\n }\n\n prioritizedRecords.push(...weightedRandom(recordsByPrio));\n }\n\n return prioritizedRecords;\n}\n\nexport function weightedRandom(records: SrvRecord[]): SrvRecord[] {\n // Duplicate records so we don't accidentally change our caller's data\n const scratchRecords: SrvRecord[] = records.slice();\n const result: SrvRecord[] = [];\n\n while (scratchRecords.length > 0) {\n const weights: number[] = [];\n\n {\n for (let i = 0; i < scratchRecords.length; i++) {\n weights.push(\n scratchRecords[i].weight + (i > 0 ? scratchRecords[i - 1].weight : 0),\n );\n }\n }\n\n const point = Math.random() * weights[weights.length - 1];\n\n for (\n let selectedIndex = 0;\n selectedIndex < weights.length;\n selectedIndex++\n ) {\n if (weights[selectedIndex] > point) {\n // Remove our selected record and add it to the result\n result.push(scratchRecords.splice(selectedIndex, 1)[0]);\n break;\n }\n }\n }\n\n return result;\n}\n","/**\n * @packageDocumentation\n * Helpers for getting values from an Action's configuration.\n */\nimport * as actionsCore from \"@actions/core\";\n\n/**\n * Get a Boolean input from the Action's configuration by name.\n */\nconst getBool = (name: string): boolean => {\n return actionsCore.getBooleanInput(name);\n};\n\n/**\n * Get a Boolean input from the Action's configuration by name, or undefined if it is unset.\n */\nconst getBoolOrUndefined = (name: string): boolean | undefined => {\n if (getStringOrUndefined(name) === undefined) {\n return undefined;\n }\n\n return actionsCore.getBooleanInput(name);\n};\n\n/**\n * The character used to separate values in the input string.\n */\nexport type Separator = \"space\" | \"comma\";\n\n/**\n * Convert a comma-separated string input into an array of strings. If `comma` is selected,\n * all whitespace is removed from the string before converting to an array.\n */\nconst getArrayOfStrings = (name: string, separator: Separator): string[] => {\n const original = getString(name);\n return handleString(original, separator);\n};\n\n/**\n * Convert a string input into an array of strings or `null` if no value is set.\n */\nconst getArrayOfStringsOrNull = (\n name: string,\n separator: Separator,\n): string[] | null => {\n const original = getStringOrNull(name);\n if (original === null) {\n return null;\n } else {\n return handleString(original, separator);\n }\n};\n\n// Split out this function for use in testing\nexport const handleString = (input: string, separator: Separator): string[] => {\n const sepChar = separator === \"comma\" ? \",\" : /\\s+/;\n const trimmed = input.trim(); // Remove whitespace at the beginning and end\n if (trimmed === \"\") {\n return [];\n }\n\n return trimmed.split(sepChar).map((s: string) => s.trim());\n};\n\n/**\n * Get a multi-line string input from the Action's configuration by name or return `null` if not set.\n */\nconst getMultilineStringOrNull = (name: string): string[] | null => {\n const value = actionsCore.getMultilineInput(name);\n if (value.length === 0) {\n return null;\n } else {\n return value;\n }\n};\n\n/**\n * Get a number input from the Action's configuration by name or return `null` if not set.\n */\nconst getNumberOrNull = (name: string): number | null => {\n const value = actionsCore.getInput(name);\n if (value === \"\") {\n return null;\n } else {\n return Number(value);\n }\n};\n\n/**\n * Get a Number input from the Action's configuration by name, or undefined if it is unset.\n */\nconst getNumberOrUndefined = (name: string): number | undefined => {\n const value = getStringOrUndefined(name);\n if (value === undefined) {\n return undefined;\n }\n\n return Number(value);\n};\n\n/**\n * Get a string input from the Action's configuration.\n */\nconst getString = (name: string): string => {\n return actionsCore.getInput(name);\n};\n\n/**\n * Get a string input from the Action's configuration by name or return `null` if not set.\n */\nconst getStringOrNull = (name: string): string | null => {\n const value = actionsCore.getInput(name);\n if (value === \"\") {\n return null;\n } else {\n return value;\n }\n};\n\n/**\n * Get a string input from the Action's configuration by name or return `undefined` if not set.\n */\nconst getStringOrUndefined = (name: string): string | undefined => {\n const value = actionsCore.getInput(name);\n if (value === \"\") {\n return undefined;\n } else {\n return value;\n }\n};\n\nexport {\n getBool,\n getBoolOrUndefined,\n getArrayOfStrings,\n getArrayOfStringsOrNull,\n getMultilineStringOrNull,\n getNumberOrNull,\n getNumberOrUndefined,\n getString,\n getStringOrNull,\n getStringOrUndefined,\n};\n","/**\n * @packageDocumentation\n * Logging that tees to both the GitHub Actions console and OpenTelemetry.\n *\n * These are drop-in replacements for the `@actions/core` logging functions.\n * Every call still writes to the workflow log exactly as it did before -- the\n * user-visible output is unchanged -- and additionally emits an OpenTelemetry\n * LogRecord correlated to the currently active span.\n *\n * When telemetry is disabled the OpenTelemetry half is a no-op, so these\n * behave identically to calling `@actions/core` directly.\n */\nimport { stringifyError } from \"./errors.js\";\nimport { type LogLevel, emitLogRecord, withSpan } from \"./telemetry.js\";\nimport * as actionsCore from \"@actions/core\";\nimport type { Attributes } from \"@opentelemetry/api\";\n\n/**\n * `@actions/core` accepts an Error in place of a message for the annotation\n * functions, and renders it via `toString()`.\n */\ntype Message = string | Error;\n\nfunction tee(\n level: LogLevel,\n message: Message,\n attributes?: Attributes,\n): string {\n const text = typeof message === \"string\" ? message : stringifyError(message);\n\n emitLogRecord(level, text, attributes);\n\n return text;\n}\n\n/**\n * Write a debug message. Only visible in the workflow log when the user has\n * enabled step debug logging, but always exported to OpenTelemetry.\n */\nexport function debug(message: string, attributes?: Attributes): void {\n actionsCore.debug(tee(\"debug\", message, attributes));\n}\n\n/** Write an informational message to the workflow log. */\nexport function info(message: string, attributes?: Attributes): void {\n actionsCore.info(tee(\"info\", message, attributes));\n}\n\n/** Write a notice annotation to the workflow log. */\nexport function notice(\n message: Message,\n properties?: actionsCore.AnnotationProperties,\n attributes?: Attributes,\n): void {\n tee(\"notice\", message, attributes);\n actionsCore.notice(message, properties);\n}\n\n/** Write a warning annotation to the workflow log. */\nexport function warning(\n message: Message,\n properties?: actionsCore.AnnotationProperties,\n attributes?: Attributes,\n): void {\n tee(\"warning\", message, attributes);\n actionsCore.warning(message, properties);\n}\n\n/** Write an error annotation to the workflow log. */\nexport function error(\n message: Message,\n properties?: actionsCore.AnnotationProperties,\n attributes?: Attributes,\n): void {\n tee(\"error\", message, attributes);\n actionsCore.error(message, properties);\n}\n\n/**\n * Fail the workflow step, recording the reason as an OpenTelemetry error log.\n */\nexport function setFailed(message: Message, attributes?: Attributes): void {\n tee(\"error\", message, attributes);\n actionsCore.setFailed(message);\n}\n\n/**\n * Run `fn` inside both a collapsible group in the workflow log and an active\n * OpenTelemetry span of the same name.\n *\n * This is the replacement for a `startGroup`/`endGroup` pair: the group closes\n * and the span ends even if `fn` throws, and a throwing `fn` marks the span\n * failed before re-throwing.\n */\nexport async function group<T>(\n name: string,\n fn: () => Promise<T>,\n attributes?: Attributes,\n): Promise<T> {\n return await withSpan(\n name,\n async () => {\n actionsCore.startGroup(name);\n try {\n return await fn();\n } finally {\n actionsCore.endGroup();\n }\n },\n attributes,\n );\n}\n","/**\n * @packageDocumentation\n * Helpers for determining system attributes of the current runner.\n */\nimport * as actionsCore from \"@actions/core\";\n\n/**\n * Get the current architecture plus OS. Examples include `X64-Linux` and `ARM64-macOS`.\n */\nexport function getArchOs(): string {\n const envArch = process.env.RUNNER_ARCH;\n const envOs = process.env.RUNNER_OS;\n\n if (envArch && envOs) {\n return `${envArch}-${envOs}`;\n } else {\n actionsCore.error(\n `Can't identify the platform: RUNNER_ARCH or RUNNER_OS undefined (${envArch}-${envOs})`,\n );\n throw new Error(\"RUNNER_ARCH and/or RUNNER_OS is not defined\");\n }\n}\n\n/**\n * Get the current Nix system. Examples include `x86_64-linux` and `aarch64-darwin`.\n */\nexport function getNixPlatform(archOs: string): string {\n const archOsMap: Map<string, string> = new Map([\n [\"X64-macOS\", \"x86_64-darwin\"],\n [\"ARM64-macOS\", \"aarch64-darwin\"],\n [\"X64-Linux\", \"x86_64-linux\"],\n [\"ARM64-Linux\", \"aarch64-linux\"],\n ]);\n\n const mappedTo = archOsMap.get(archOs);\n if (mappedTo) {\n return mappedTo;\n } else {\n actionsCore.error(\n `ArchOs (${archOs}) doesn't map to a supported Nix platform.`,\n );\n throw new Error(\n `Cannot convert ArchOs (${archOs}) to a supported Nix platform.`,\n );\n }\n}\n","import { getStringOrUndefined } from \"./inputs.js\";\nimport * as actionsCore from \"@actions/core\";\n\nexport type SourceDef = {\n path?: string;\n url?: string;\n tag?: string;\n pr?: string;\n branch?: string;\n revision?: string;\n};\n\n/**\n * Throw if hash-locking is requested against a source that is not pinned to a\n * fixed version. `source-tag`, `source-revision`, and `source-url` are\n * immutable (or caller-controlled); any other selector resolves to a moving\n * target (`branch`, `pr`, or the `stable` fallback) where the pinned checksum\n * would break the moment a new release is published.\n */\nexport function assertChecksumSourceIsPinned(source: SourceDef): void {\n if (\n source.url === undefined &&\n source.tag === undefined &&\n source.revision === undefined\n ) {\n throw new Error(\n \"Hash-locking via `source-checksums-url`/`source-checksums-sha256` requires a pinned source: set `source-tag`, `source-revision`, or `source-url`. Without one the action resolves to a moving target (e.g. `stable`) and the checksum will break the next time a release is published.\",\n );\n }\n}\n\nexport function constructSourceParameters(legacyPrefix?: string): SourceDef {\n return {\n path: noisilyGetInput(\"path\", legacyPrefix),\n url: noisilyGetInput(\"url\", legacyPrefix),\n tag: noisilyGetInput(\"tag\", legacyPrefix),\n pr: noisilyGetInput(\"pr\", legacyPrefix),\n branch: noisilyGetInput(\"branch\", legacyPrefix),\n revision: noisilyGetInput(\"revision\", legacyPrefix),\n };\n}\n\nfunction noisilyGetInput(\n suffix: string,\n legacyPrefix: string | undefined,\n): string | undefined {\n const preferredInput = getStringOrUndefined(`source-${suffix}`);\n\n if (!legacyPrefix) {\n return preferredInput;\n }\n\n // Remaining is for handling cases where the legacy prefix\n // should be examined.\n const legacyInput = getStringOrUndefined(`${legacyPrefix}-${suffix}`);\n\n if (preferredInput && legacyInput) {\n actionsCore.warning(\n `The supported option source-${suffix} and the legacy option ${legacyPrefix}-${suffix} are both set. Preferring source-${suffix}. Please stop setting ${legacyPrefix}-${suffix}.`,\n );\n return preferredInput;\n } else if (legacyInput) {\n actionsCore.warning(\n `The legacy option ${legacyPrefix}-${suffix} is set. Please migrate to source-${suffix}.`,\n );\n return legacyInput;\n } else {\n return preferredInput;\n }\n}\n","/**\n * @packageDocumentation\n * Determinate Systems' TypeScript library for creating GitHub Actions logic.\n */\n// import { version as pkgVersion } from \"../package.json\";\nimport * as ghActionsCorePlatform from \"./actions-core-platform.js\";\nimport type { CheckIn, Feature } from \"./check-in.js\";\nimport * as checksums from \"./checksums.js\";\nimport * as correlation from \"./correlation.js\";\nimport { IdsHost } from \"./ids-host.js\";\nimport * as inputs from \"./inputs.js\";\nimport * as log from \"./log.js\";\nimport * as platform from \"./platform.js\";\nimport type { SourceDef } from \"./sourcedef.js\";\nimport * as sourcedef from \"./sourcedef.js\";\nimport * as otel from \"./telemetry.js\";\nimport * as actionsCache from \"@actions/cache\";\nimport * as actionsCore from \"@actions/core\";\nimport * as actionsExec from \"@actions/exec\";\nimport * as otelApi from \"@opentelemetry/api\";\nimport * as semconv from \"@opentelemetry/semantic-conventions\";\nimport * as semconvIncubating from \"@opentelemetry/semantic-conventions/incubating\";\nimport { type Got, type Request, TimeoutError } from \"got\";\nimport { exec } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport * as nodeFs from \"node:fs\";\nimport fs, { chmod, copyFile, mkdir, readFile } from \"node:fs/promises\";\nimport os, { tmpdir } from \"node:os\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\n\n// Span events this library records itself. Names a caller passes to\n// `addEvent` are used as given.\nconst EVENT_IDS_FAILOVER = \"detsys.ids_failover\";\nconst EVENT_PREFLIGHT_REQUIRE_NIX_DENIED =\n \"detsys.preflight_require_nix_denied\";\nconst EVENT_REQUEST_TIMEOUT = \"detsys.request_timeout\";\nconst EVENT_STORE_IDENTITY_FAILED = \"detsys.store_identity_failed\";\n\n// Attributes describing the run. Where the OpenTelemetry semantic conventions\n// already name a value, they win; everything else lives under `detsys.`.\nconst ATTR_PROJECT = \"detsys.project\";\nconst ATTR_IDS_PROJECT = \"detsys.ids_project\";\nconst ATTR_EXECUTION_PHASE = \"detsys.execution_phase\";\nconst ATTR_CROSS_PHASE_ID = \"detsys.cross_phase_id\";\nconst ATTR_ANONYMOUS_ID = \"detsys.anonymous_id\";\nconst ATTR_CORRELATION_SOURCE = \"detsys.correlation_source\";\nconst ATTR_ARCH_OS = \"detsys.arch_os\";\nconst ATTR_NIX_SYSTEM = \"detsys.nix_system\";\nconst ATTR_FEATURE_PREFIX = \"detsys.feature.\";\n\nconst ATTR_GITHUB_EVENT_NAME = \"detsys.github.event_name\";\nconst ATTR_GITHUB_ACTION_REPOSITORY = \"detsys.github.action_repository\";\nconst ATTR_GITHUB_REPOSITORY_HASH = \"detsys.github.repository_hash\";\nconst ATTR_GITHUB_ORGANIZATION_HASH = \"detsys.github.organization_hash\";\nconst ATTR_GITHUB_WORKFLOW_HASH = \"detsys.github.workflow_hash\";\nconst ATTR_GITHUB_WORKFLOW_JOB_HASH = \"detsys.github.workflow_job_hash\";\nconst ATTR_GITHUB_WORKFLOW_RUN_HASH = \"detsys.github.workflow_run_hash\";\nconst ATTR_GITHUB_WORKFLOW_RUN_DIFFERENTIATOR_HASH =\n \"detsys.github.workflow_run_differentiator_hash\";\n\nconst ATTR_ARTIFACT_NAME = \"detsys.artifact.name\";\nconst ATTR_ARTIFACT_FETCH_SUFFIX = \"detsys.artifact.fetch_suffix\";\nconst ATTR_ARTIFACT_CACHE_HIT = \"detsys.artifact.cache_hit\";\nconst ATTR_SOURCE_URL = \"detsys.source.url\";\nconst ATTR_SOURCE_ETAG = \"detsys.source.etag\";\nconst ATTR_SOURCE_CHECKSUMS_SHA256 = \"detsys.source.checksums_sha256\";\n\nconst ATTR_NIX_LOCATION = \"detsys.nix.location\";\nconst ATTR_NIX_VERSION = \"detsys.nix.version\";\nconst ATTR_NIX_STORE_TRUST = \"detsys.nix.store_trust\";\nconst ATTR_NIX_STORE_VERSION = \"detsys.nix.store_version\";\nconst ATTR_NIX_STORE_CHECK_METHOD = \"detsys.nix.store_check_method\";\nconst ATTR_NIX_STORE_CHECK_ERROR = \"detsys.nix.store_check_error\";\n\n// Log records, not span attributes, carry stapled files: a record's body is\n// not truncated the way an attribute value is.\nconst ATTR_ATTACHMENT_NAME = \"detsys.attachment.name\";\nconst ATTR_ATTACHMENT_PATH = \"detsys.attachment.path\";\n\nconst STATE_KEY_EXECUTION_PHASE = \"detsys_action_execution_phase\";\nconst STATE_KEY_NIX_NOT_FOUND = \"detsys_action_nix_not_found\";\nconst STATE_NOT_FOUND = \"not-found\";\nconst STATE_KEY_CROSS_PHASE_ID = \"detsys_cross_phase_id\";\nconst STATE_KEY_TRACEPARENT = \"detsys_otel_traceparent\";\nconst STATE_KEY_JOB_TRACEPARENT = \"detsys_otel_job_traceparent\";\nconst STATE_KEY_JOB_SPAN_START = \"detsys_otel_job_span_start\";\n\n// The standard variable that carries the trace context between programs.\n// Every step of the job reads it, and so does each program the steps run.\nconst ENV_TRACEPARENT = \"TRACEPARENT\";\n\n// The span that covers the whole workflow job, and thus every Action in it.\nconst SPAN_JOB = \"github_actions_job\";\n\n// The check-in, which is the first thing each phase does.\nconst SPAN_CHECK_IN = \"check_in\";\n\nconst CHECK_IN_ENDPOINT_TIMEOUT_MS = 1_000; // 1 second in ms\n\n/**\n * An enum for describing different \"fetch suffixes\" for i.d.s.\n *\n * - `nix-style` means that system names like `x86_64-linux` and `aarch64-darwin` are used\n * - `gh-env-style` means that names like `X64-Linux` and `ARM64-macOS` are used\n * - `universal` means that the suffix is the static `universal` (for non-system-specific things)\n */\nexport type FetchSuffixStyle = \"nix-style\" | \"gh-env-style\" | \"universal\";\n\n/**\n * GitHub Actions has two possible execution phases: `main` and `post`.\n */\nexport type ExecutionPhase = \"main\" | \"post\";\n\n/**\n * How to handle whether Nix is currently installed on the runner.\n *\n * - `fail` means that the workflow fails if Nix isn't installed\n * - `warn` means that a warning is logged if Nix isn't installed\n * - `ignore` means that Nix will not be checked\n */\nexport type NixRequirementHandling = \"fail\" | \"warn\" | \"ignore\";\n\n/**\n * Whether the Nix store on the runner is trusted.\n *\n * - `trusted` means yes\n * - `untrusted` means no\n * - `unknown` means that the status couldn't be determined\n *\n * This is determined via the output of `nix store info --json`.\n */\nexport type NixStoreTrust = \"trusted\" | \"untrusted\" | \"unknown\";\n\nexport type ActionOptions = {\n // Name of the project generally, and the name of the binary on disk.\n name: string;\n\n // Defaults to `name`, Corresponds to the ProjectHost entry on i.d.s.\n idsProjectName?: string;\n\n // The \"architecture\" URL component expected by I.D.S. for the ProjectHost.\n fetchStyle: FetchSuffixStyle;\n\n // IdsToolbox assumes the GitHub Action exposes source overrides, like branch/pr/etc. to be named `source-*`.\n // This prefix adds a fallback name, prefixed by `${legacySourcePrefix}-`.\n // Users who configure legacySourcePrefix will get warnings asking them to change to `source-*`.\n legacySourcePrefix?: string;\n\n // Check if Nix is installed before running this action.\n // If Nix isn't installed, this action will not fail, and will instead do nothing.\n // The action will emit a user-visible warning instructing them to install Nix.\n requireNix: NixRequirementHandling;\n\n // The URL suffix of the diagnostics endpoint this project's own binaries\n // report to. This library does not report there: its telemetry is\n // OpenTelemetry, and this only supplies `getDiagnosticsUrl()` for the\n // programs an Action runs.\n //\n // The final URL is constructed via IDS_HOST/idsProjectName/diagnosticsSuffix.\n //\n // Default: `diagnostics`.\n diagnosticsSuffix?: string;\n};\n\n/**\n * A confident version of Options, where defaults have been resolved into final values.\n */\nexport type ConfidentActionOptions = {\n name: string;\n idsProjectName: string;\n fetchStyle: FetchSuffixStyle;\n legacySourcePrefix?: string;\n requireNix: NixRequirementHandling;\n providedDiagnosticsUrl?: URL;\n};\n\nconst determinateStateDir = \"/var/lib/determinate\";\nconst determinateIdentityFile = path.join(determinateStateDir, \"identity.json\");\n\nconst isRoot = typeof process.geteuid === \"function\" && process.geteuid() === 0;\n\n/** Create the Determinate state directory by escalating via sudo */\nasync function sudoEnsureDeterminateStateDir(): Promise<void> {\n const code = await actionsExec.exec(\"sudo\", [\n \"mkdir\",\n \"-p\",\n determinateStateDir,\n ]);\n\n if (code !== 0) {\n throw new Error(`sudo mkdir -p exit: ${code}`);\n }\n}\n\n/** Ensures the Determinate state directory exists, escalating if necessary */\nasync function ensureDeterminateStateDir(): Promise<void> {\n if (isRoot) {\n await mkdir(determinateStateDir, { recursive: true });\n } else {\n return sudoEnsureDeterminateStateDir();\n }\n}\n\n/** Writes correlation hashes to the Determinate state directory by writing to a `sudo tee` pipe */\nasync function sudoWriteCorrelationHashes(hashes: string): Promise<void> {\n const buffer = Buffer.from(hashes);\n\n const code = await actionsExec.exec(\n \"sudo\",\n [\"tee\", determinateIdentityFile],\n {\n input: buffer,\n\n // Ignore output from tee\n outStream: nodeFs.createWriteStream(\"/dev/null\"),\n },\n );\n\n if (code !== 0) {\n throw new Error(`sudo tee exit: ${code}`);\n }\n}\n\n/** Writes correlation hashes to the Determinate state directory, escalating if necessary */\nasync function writeCorrelationHashes(hashes: string): Promise<void> {\n await ensureDeterminateStateDir();\n\n if (isRoot) {\n await fs.writeFile(determinateIdentityFile, hashes, \"utf-8\");\n } else {\n return sudoWriteCorrelationHashes(hashes);\n }\n}\n\nexport abstract class DetSysAction {\n nixStoreTrust: NixStoreTrust;\n strictMode: boolean;\n\n private actionOptions: ConfidentActionOptions;\n private exceptionAttachments: Map<string, nodeFs.PathLike>;\n private archOs: string;\n private executionPhase: ExecutionPhase;\n private nixSystem: string;\n private architectureFetchSuffix: string;\n private sourceParameters: SourceDef;\n private identity: correlation.CorrelationProperties;\n private idsHost: IdsHost;\n private features: { [k: string]: Feature };\n private telemetry: otel.Telemetry;\n\n // The name and version of the runner's operating system, in flight from the\n // moment the Action is constructed so that it is ready by the time the\n // resource attributes are assembled.\n private systemDetails: Promise<{ name: string; version: string } | undefined>;\n\n // The root span for this execution phase. Undefined until the phase span is\n // opened, and when OpenTelemetry export is disabled.\n private phaseSpan?: otelApi.Span;\n\n // Attributes set before the phase span exists, replayed onto it when it\n // opens.\n private pendingAttributes: otelApi.Attributes;\n\n private determineExecutionPhase(): ExecutionPhase {\n const currentPhase = actionsCore.getState(STATE_KEY_EXECUTION_PHASE);\n if (currentPhase === \"\") {\n actionsCore.saveState(STATE_KEY_EXECUTION_PHASE, \"post\");\n return \"main\";\n } else {\n return \"post\";\n }\n }\n\n constructor(actionOptions: ActionOptions) {\n this.actionOptions = makeOptionsConfident(actionOptions);\n this.idsHost = new IdsHost(\n this.actionOptions.idsProjectName,\n actionOptions.diagnosticsSuffix,\n // Note: we don't use actionsCore.getInput('diagnostic-endpoint') on purpose:\n // getInput silently converts absent data to an empty string.\n process.env[\"INPUT_DIAGNOSTIC-ENDPOINT\"],\n inputs.getNumberOrUndefined(\"timeout-request\"),\n );\n this.telemetry = new otel.Telemetry();\n this.exceptionAttachments = new Map();\n this.nixStoreTrust = \"unknown\";\n this.strictMode = inputs.getBool(\"_internal-strict-mode\");\n\n if (\n inputs.getBoolOrUndefined(\n \"_internal-obliterate-actions-id-token-request-variables\",\n ) === true\n ) {\n process.env[\"ACTIONS_ID_TOKEN_REQUEST_URL\"] = undefined;\n process.env[\"ACTIONS_ID_TOKEN_REQUEST_TOKEN\"] = undefined;\n }\n\n this.features = {};\n this.pendingAttributes = {};\n\n this.getCrossPhaseId();\n\n this.identity = correlation.identify();\n this.archOs = platform.getArchOs();\n this.nixSystem = platform.getNixPlatform(this.archOs);\n\n this.systemDetails = ghActionsCorePlatform\n .getDetails()\n // eslint-disable-next-line github/no-then\n .then((details) => ({ name: details.name, version: details.version }))\n // eslint-disable-next-line github/no-then\n .catch((e: unknown) => {\n actionsCore.debug(\n `Failure getting platform details: ${stringifyError(e)}`,\n );\n return undefined;\n });\n\n this.executionPhase = this.determineExecutionPhase();\n\n if (this.actionOptions.fetchStyle === \"gh-env-style\") {\n this.architectureFetchSuffix = this.archOs;\n } else if (this.actionOptions.fetchStyle === \"nix-style\") {\n this.architectureFetchSuffix = this.nixSystem;\n } else if (this.actionOptions.fetchStyle === \"universal\") {\n this.architectureFetchSuffix = \"universal\";\n } else {\n throw new Error(\n `fetchStyle ${this.actionOptions.fetchStyle} is not a valid style`,\n );\n }\n\n this.sourceParameters = sourcedef.constructSourceParameters(\n this.actionOptions.legacySourcePrefix,\n );\n }\n\n /**\n * Attach a file to the telemetry for this run, to be emitted if the Action\n * fails.\n *\n * The file at `location` doesn't need to exist when stapleFile is called.\n *\n * Each attachment becomes one OpenTelemetry log record, correlated to the\n * phase's span: the file's contents as the body if it can be read, the\n * reason it could not be read otherwise.\n */\n stapleFile(name: string, location: string): void {\n this.exceptionAttachments.set(name, location);\n }\n\n /**\n * The main execution phase.\n */\n abstract main(): Promise<void>;\n\n /**\n * The post execution phase.\n */\n abstract post(): Promise<void>;\n\n /**\n * Execute the Action as defined.\n */\n execute(): void {\n // eslint-disable-next-line github/no-then\n this.executeAsync().catch((error: Error) => {\n // eslint-disable-next-line no-console\n console.log(error);\n process.exitCode = 1;\n });\n }\n\n getTemporaryName(): string {\n const tmpDir = process.env[\"RUNNER_TEMP\"] || tmpdir();\n return path.join(tmpDir, `${this.actionOptions.name}-${randomUUID()}`);\n }\n\n /**\n * Describe this run with an attribute.\n *\n * The attribute lands on the phase's root span, not on whichever span\n * happens to be active, because it describes the run as a whole. Set it\n * whenever the value becomes known: attributes set before the span opens\n * are replayed onto it.\n *\n * Namespace your keys, as OpenTelemetry expects: `detsys.nix.version`, not\n * `nix_version`.\n */\n setAttribute(key: string, value: otelApi.AttributeValue): void {\n if (this.phaseSpan === undefined) {\n this.pendingAttributes[key] = value;\n } else {\n this.phaseSpan.setAttribute(key, value);\n }\n }\n\n /**\n * The diagnostics endpoint for the programs this Action runs, such as\n * `nix-installer` and `magic-nix-cache`.\n *\n * This library reports nothing there. Its own telemetry is OpenTelemetry;\n * see {@link getTelemetryEnvironment} for putting a child process's\n * telemetry in this run's trace.\n */\n async getDiagnosticsUrl(): Promise<URL | undefined> {\n return await this.idsHost.getDiagnosticsUrl();\n }\n\n getUniqueId(): string {\n return (\n this.identity.github_workflow_run_differentiator_hash ||\n process.env.RUNNER_TRACKING_ID ||\n randomUUID()\n );\n }\n\n // This ID will be saved in the action's state, to be persisted across phase steps\n getCrossPhaseId(): string {\n let crossPhaseId = actionsCore.getState(STATE_KEY_CROSS_PHASE_ID);\n\n if (crossPhaseId === \"\") {\n crossPhaseId = randomUUID();\n actionsCore.saveState(STATE_KEY_CROSS_PHASE_ID, crossPhaseId);\n }\n\n return crossPhaseId;\n }\n\n getCorrelationHashes(): correlation.CorrelationProperties {\n return this.identity;\n }\n\n /**\n * Record that something happened, as a span event.\n *\n * The event lands on whichever span is active, so that it sits on the\n * operation that produced it, and on the phase's root span when there is no\n * nested span in progress.\n *\n * Namespace your attribute keys, as OpenTelemetry expects.\n */\n addEvent(name: string, attributes?: otelApi.Attributes): void {\n const span = otelApi.trace.getActiveSpan() ?? this.phaseSpan;\n span?.addEvent(name, attributes);\n }\n\n /**\n * Unpacks the closure returned by `fetchArtifact()`, imports the\n * contents into the Nix store, and returns the path of the executable at\n * `/nix/store/STORE_PATH/bin/${bin}`.\n */\n async unpackClosure(bin: string): Promise<string> {\n const artifact = await this.fetchArtifact();\n const { stdout } = await promisify(exec)(\n `cat \"${artifact}\" | xz -d | nix-store --import`,\n );\n const paths = stdout.split(os.EOL);\n const lastPath = paths.at(-2);\n return `${lastPath}/bin/${bin}`;\n }\n\n /**\n * Fetches the executable at the URL determined by the `source-*` inputs and\n * other facts, `chmod`s it, and returns the path to the executable on disk.\n */\n async fetchExecutable(): Promise<string> {\n const binaryPath = await this.fetchArtifact();\n await chmod(\n binaryPath,\n nodeFs.constants.S_IXUSR | nodeFs.constants.S_IXGRP,\n );\n return binaryPath;\n }\n\n private get isMain(): boolean {\n return this.executionPhase === \"main\";\n }\n\n private get isPost(): boolean {\n return this.executionPhase === \"post\";\n }\n\n private async executeAsync(): Promise<void> {\n // The SDK starts after this moment, thus record the true start time here\n // and backdate the phase's span to it.\n const phaseStartTime = new Date();\n\n try {\n // The job's span covers each Action of the job, thus the first Action to\n // run announces it before it does anything else.\n this.announceJobTrace(phaseStartTime);\n\n await this.startTelemetry();\n this.startPhaseSpan(phaseStartTime);\n\n await this.withPhaseSpanActive(async () => {\n await otel.withSpan(SPAN_CHECK_IN, async () => {\n await this.checkIn();\n });\n\n const correlationHashes = JSON.stringify(this.getCorrelationHashes());\n process.env.DETSYS_CORRELATION = correlationHashes;\n try {\n await writeCorrelationHashes(correlationHashes);\n } catch (error) {\n this.addEvent(EVENT_STORE_IDENTITY_FAILED, {\n [semconv.ATTR_EXCEPTION_MESSAGE]: stringifyError(error),\n });\n }\n\n if (!(await this.preflightRequireNix())) {\n this.addEvent(EVENT_PREFLIGHT_REQUIRE_NIX_DENIED);\n return;\n } else {\n await this.preflightNixStoreInfo();\n await this.preflightNixVersion();\n this.setAttribute(ATTR_NIX_STORE_TRUST, this.nixStoreTrust);\n }\n\n if (this.isMain) {\n await this.main();\n\n // Run the preflight of the nix version a second time so our final\n // telemetry has updated version info.\n await this.preflightNixVersion();\n } else if (this.isPost) {\n await this.post();\n }\n });\n } catch (e: unknown) {\n const reportable = stringifyError(e);\n\n // The span's status and its `exception` event say the phase failed.\n if (this.phaseSpan !== undefined) {\n otel.recordSpanError(this.phaseSpan, e);\n }\n\n if (this.isPost) {\n log.warning(reportable);\n } else {\n log.setFailed(reportable);\n }\n\n await this.withPhaseSpanActive(async () => {\n await this.emitAttachments();\n });\n } finally {\n await this.complete();\n }\n }\n\n /**\n * Run `fn` with the phase's root span as the active span, so anything it\n * starts is parented into this phase's trace.\n */\n private async withPhaseSpanActive<T>(fn: () => Promise<T>): Promise<T> {\n const span = this.phaseSpan;\n\n if (span === undefined) {\n return await fn();\n }\n\n return await otelApi.context.with(\n otelApi.trace.setSpan(otelApi.context.active(), span),\n fn,\n );\n }\n\n /**\n * Start the OpenTelemetry export.\n *\n * All runs export their data.\n * To stop the export, set `OTEL_SDK_DISABLED` to `true`, or set\n * `OTEL_EXPORTER_OTLP_ENDPOINT` to an empty value.\n * The SDK then does not start.\n * The OpenTelemetry API stays in its no-op state.\n * Each span and log record then does nothing.\n * Thus the call sites do not test if the export is on.\n */\n private async startTelemetry(): Promise<void> {\n this.telemetry.start({\n // The `-action` suffix says this service is the Action, not the tool it runs.\n serviceName: `${this.actionOptions.name}-action`,\n // The Action's own version, which is the ref the workflow pinned.\n serviceVersion: process.env[\"GITHUB_ACTION_REF\"],\n resourceAttributes: await this.telemetryResourceAttributes(),\n });\n }\n\n /**\n * Put every Action of this workflow job in one trace.\n *\n * A job runs each Action as a process of its own.\n * Thus the Actions can only agree on a trace through the job's environment.\n * The first Action to run makes the identity of the job's span and exports it\n * as `$TRACEPARENT`.\n * Each later step finds it there: the other Actions, and the programs the\n * workflow runs, such as Nix.\n *\n * The span itself starts and ends in the post phase of the Action that\n * announced it.\n * GitHub Actions runs the post phases in the reverse of the order of the main\n * phases, thus that phase is the last one of the job.\n * The span then covers the whole job.\n * See {@link endJobSpan}.\n *\n * A `$TRACEPARENT` that is already set belongs to an earlier Action, or to the\n * system that started the workflow.\n * Do not change it, and join that trace.\n */\n private announceJobTrace(startTime: Date): void {\n if (!this.isMain || !otel.exportEnabled()) {\n return;\n }\n\n if (process.env[ENV_TRACEPARENT]) {\n return;\n }\n\n const traceparent = otel.newTraceparent();\n\n // `exportVariable` sets the variable in this process, and in each\n // subsequent step of the job.\n actionsCore.exportVariable(ENV_TRACEPARENT, traceparent);\n\n actionsCore.saveState(STATE_KEY_JOB_TRACEPARENT, traceparent);\n actionsCore.saveState(STATE_KEY_JOB_SPAN_START, `${startTime.getTime()}`);\n }\n\n /**\n * End the job's span, if this Action is the one that announced it.\n *\n * The span also starts here.\n * A span belongs to the process that ends it, and the process that made the\n * announcement stopped long ago.\n * See {@link announceJobTrace}.\n */\n private endJobSpan(): void {\n if (!this.isPost) {\n return;\n }\n\n const traceparent = actionsCore.getState(STATE_KEY_JOB_TRACEPARENT);\n if (traceparent === \"\") {\n return;\n }\n\n const startTime = parseInt(\n actionsCore.getState(STATE_KEY_JOB_SPAN_START),\n 10,\n );\n\n this.telemetry\n .startAnnouncedSpan(\n SPAN_JOB,\n traceparent,\n new Date(Number.isFinite(startTime) ? startTime : Date.now()),\n )\n ?.end();\n }\n\n /**\n * Start the root span of this execution phase.\n *\n * The span starts at the moment the phase did, and thus covers the start of\n * the SDK, which comes before it.\n *\n * `main` and `post` are separate processes.\n * Thus the main phase saves the identity of its span in the Action's state,\n * and the post phase makes its span a child of it.\n * A `$TRACEPARENT` in the environment is the span of the workflow job, or of\n * the system that started the workflow.\n */\n private startPhaseSpan(startTime: Date): void {\n if (!this.telemetry.enabled) {\n return;\n }\n\n const parent =\n actionsCore.getState(STATE_KEY_TRACEPARENT) ||\n process.env[ENV_TRACEPARENT] ||\n undefined;\n\n const span = otel\n .getTracer()\n .startSpan(\n `${this.actionOptions.name}:${this.executionPhase}`,\n { startTime },\n otel.contextFromTraceparent(parent),\n );\n\n span.setAttributes(this.pendingAttributes);\n this.pendingAttributes = {};\n\n const traceparent = otel.traceparentOf(span);\n if (traceparent !== undefined) {\n // Each program this Action runs is part of this phase, and not of the\n // workflow job. The variable changes in this process only: the later\n // steps of the job keep the identity of the job's span.\n process.env[ENV_TRACEPARENT] = traceparent;\n\n if (this.isMain) {\n actionsCore.saveState(STATE_KEY_TRACEPARENT, traceparent);\n }\n }\n\n this.phaseSpan = span;\n }\n\n /**\n * The stable, run-scoped attributes attached to every span and log record.\n *\n * The correlation data here is hashed and does not identify a repository,\n * an organization, or a person.\n */\n private async telemetryResourceAttributes(): Promise<otelApi.Attributes> {\n const details = await this.systemDetails;\n\n return {\n [semconvIncubating.ATTR_OS_TYPE]: osType(),\n [semconvIncubating.ATTR_HOST_ARCH]: hostArch(),\n ...(details?.name === undefined || details.name === \"unknown\"\n ? {}\n : { [semconvIncubating.ATTR_OS_NAME]: details.name }),\n ...(details?.version === undefined || details.version === \"unknown\"\n ? {}\n : { [semconvIncubating.ATTR_OS_VERSION]: details.version }),\n\n [ATTR_PROJECT]: this.actionOptions.name,\n [ATTR_IDS_PROJECT]: this.actionOptions.idsProjectName,\n [ATTR_EXECUTION_PHASE]: this.executionPhase,\n [ATTR_CROSS_PHASE_ID]: this.getCrossPhaseId(),\n [ATTR_ANONYMOUS_ID]: this.identity.$anon_distinct_id,\n [ATTR_CORRELATION_SOURCE]: this.identity.correlation_source,\n [ATTR_ARCH_OS]: this.archOs,\n [ATTR_NIX_SYSTEM]: this.nixSystem,\n\n [ATTR_GITHUB_EVENT_NAME]: process.env[\"GITHUB_EVENT_NAME\"],\n [ATTR_GITHUB_ACTION_REPOSITORY]: process.env[\"GITHUB_ACTION_REPOSITORY\"],\n [ATTR_GITHUB_REPOSITORY_HASH]: this.identity.github_repository_hash,\n [ATTR_GITHUB_ORGANIZATION_HASH]:\n this.identity.$groups[\"github_organization\"],\n [ATTR_GITHUB_WORKFLOW_HASH]: this.identity.github_workflow_hash,\n [ATTR_GITHUB_WORKFLOW_JOB_HASH]: this.identity.github_workflow_job_hash,\n [ATTR_GITHUB_WORKFLOW_RUN_HASH]: this.identity.github_workflow_run_hash,\n [ATTR_GITHUB_WORKFLOW_RUN_DIFFERENTIATOR_HASH]:\n this.identity.github_workflow_run_differentiator_hash,\n };\n }\n\n /**\n * The W3C `traceparent` identifying the span currently in progress.\n *\n * Hand this to a child process -- as `$TRACEPARENT` -- so that its own\n * OpenTelemetry data joins this Action's trace. Returns undefined when\n * OpenTelemetry export is disabled for this run.\n */\n getTraceparent(): string | undefined {\n return otel.traceparentOf(otelApi.trace.getActiveSpan() ?? this.phaseSpan);\n }\n\n /**\n * The environment variables that let a child process add data to this\n * Action's trace: the current `$TRACEPARENT` and the OTLP export settings.\n *\n * Add these variables to the environment of each child process to trace.\n * A child that inherits this process's environment already has the OTLP\n * settings; only `$TRACEPARENT` changes as the run proceeds.\n *\n * The result is empty if the OpenTelemetry export is off.\n * Thus it is always safe to add them.\n */\n async getTelemetryEnvironment(): Promise<Record<string, string>> {\n if (!this.telemetry.enabled) {\n return {};\n }\n\n const environment: Record<string, string> = otel.otlpExportEnvironment();\n\n const traceparent = this.getTraceparent();\n if (traceparent !== undefined) {\n environment[ENV_TRACEPARENT] = traceparent;\n }\n\n return environment;\n }\n\n async getClient(): Promise<Got> {\n return await this.idsHost.getGot(\n (incitingError: unknown, prevUrl: URL, nextUrl: URL) => {\n this.recordPlausibleTimeout(incitingError);\n\n this.addEvent(EVENT_IDS_FAILOVER, {\n \"detsys.ids.previous_url\": prevUrl.toString(),\n \"detsys.ids.next_url\": nextUrl.toString(),\n });\n },\n );\n }\n\n /**\n * Check in, and tell the user about the incidents and the maintenance the\n * check-in reports.\n */\n private async checkIn(): Promise<void> {\n const checkin = await this.requestCheckIn();\n if (checkin === undefined) {\n return;\n }\n\n this.features = checkin.options;\n\n const impactSymbol: Map<string, string> = new Map([\n [\"none\", \"⚪\"],\n [\"maintenance\", \"🛠️\"],\n [\"minor\", \"🟡\"],\n [\"major\", \"🟠\"],\n [\"critical\", \"🔴\"],\n ]);\n const defaultImpactSymbol = \"🔵\";\n\n if (checkin.status !== null) {\n const summaries: string[] = [];\n\n for (const incident of checkin.status.incidents) {\n summaries.push(\n `${impactSymbol.get(incident.impact) || defaultImpactSymbol} ${incident.status.replace(\"_\", \" \")}: ${incident.name} (${incident.shortlink})`,\n );\n }\n\n for (const maintenance of checkin.status.scheduled_maintenances) {\n summaries.push(\n `${impactSymbol.get(maintenance.impact) || defaultImpactSymbol} ${maintenance.status.replace(\"_\", \" \")}: ${maintenance.name} (${maintenance.shortlink})`,\n );\n }\n\n if (summaries.length > 0) {\n actionsCore.info(\n // Bright red, Bold, Underline\n `${\"\\u001b[0;31m\"}${\"\\u001b[1m\"}${\"\\u001b[4m\"}${checkin.status.page.name} Status`,\n );\n for (const notice of summaries) {\n actionsCore.info(notice);\n }\n actionsCore.info(`See: ${checkin.status.page.url}`);\n actionsCore.info(``);\n }\n }\n }\n\n /**\n * The variant of a feature flag this run resolved, if the check-in returned\n * one.\n *\n * Each variant this Action asks for becomes an attribute of the run, under\n * `detsys.feature.`, so the telemetry can be sliced by the flags that\n * changed what the run did.\n */\n getFeature(name: string): Feature | undefined {\n if (!this.features.hasOwnProperty(name)) {\n return undefined;\n }\n\n const feature = this.features[name];\n this.setAttribute(`${ATTR_FEATURE_PREFIX}${name}`, feature.variant);\n\n return feature;\n }\n\n /**\n * The person properties the check-in evaluates feature flags against.\n *\n * These names are the flag-targeting contract with the feature flag\n * service, which is why they keep their `$`-prefixed spelling. They are not\n * telemetry: nothing here is reported anywhere. The telemetry for this run\n * is OpenTelemetry, and it names the same values the way OpenTelemetry\n * does.\n */\n private async checkInPersonProperties(): Promise<Record<string, unknown>> {\n /* eslint-disable camelcase */\n const properties: Record<string, string | boolean | number> = {\n ci: \"github\",\n $lib: \"idslib\",\n $lib_version: otel.LIBRARY_VERSION,\n $app_name: `${this.actionOptions.name}/action`,\n project: this.actionOptions.name,\n ids_project: this.actionOptions.idsProjectName,\n arch_os: this.archOs,\n nix_system: this.nixSystem,\n execution_phase: this.executionPhase,\n };\n\n const fromEnvironment = [\n [\"github_action_ref\", \"GITHUB_ACTION_REF\"],\n [\"github_action_repository\", \"GITHUB_ACTION_REPOSITORY\"],\n [\"github_event_name\", \"GITHUB_EVENT_NAME\"],\n [\"$os\", \"RUNNER_OS\"],\n [\"arch\", \"RUNNER_ARCH\"],\n ];\n for (const [target, variable] of fromEnvironment) {\n const value = process.env[variable];\n if (value) {\n properties[target] = value;\n }\n }\n\n const details = await this.systemDetails;\n if (details !== undefined) {\n if (details.name !== \"unknown\") {\n properties.$os = details.name;\n }\n if (details.version !== \"unknown\") {\n properties.$os_version = details.version;\n }\n }\n /* eslint-enable camelcase */\n\n return { ...properties, ...this.identity };\n }\n\n /**\n * Check in to install.determinate.systems, to accomplish three things:\n *\n * 1. Preflight the server selected from IdsHost, to increase the chances of success.\n * 2. Fetch any incidents and maintenance events to let users know in case things are weird.\n * 3. Get feature flag data so we can gently roll out new features.\n */\n private async requestCheckIn(): Promise<CheckIn | undefined> {\n for (\n let attemptsRemaining = 5;\n attemptsRemaining > 0;\n attemptsRemaining--\n ) {\n const checkInUrl = await this.getCheckInUrl();\n if (checkInUrl === undefined) {\n return undefined;\n }\n\n try {\n actionsCore.debug(`Preflighting via ${checkInUrl}`);\n\n /* eslint-disable camelcase */\n const props = {\n // Use a distinct_id when we actually have one\n distinct_id: this.identity.$anon_distinct_id,\n anon_distinct_id: this.identity.$anon_distinct_id,\n groups: this.identity.$groups,\n person_properties: await this.checkInPersonProperties(),\n };\n /* eslint-enable camelcase */\n\n return await (\n await this.getClient()\n )\n .post(checkInUrl, {\n json: props,\n timeout: {\n request: CHECK_IN_ENDPOINT_TIMEOUT_MS,\n },\n })\n .json();\n } catch (e: unknown) {\n this.recordPlausibleTimeout(e);\n actionsCore.debug(`Error checking in: ${stringifyError(e)}`);\n this.idsHost.markCurrentHostBroken();\n }\n }\n\n return undefined;\n }\n\n private recordPlausibleTimeout(e: unknown): void {\n // see: https://github.com/sindresorhus/got/blob/895e463fa699d6f2e4b2fc01ceb3b2bb9e157f4c/documentation/8-errors.md\n if (e instanceof TimeoutError && \"timings\" in e && \"request\" in e) {\n const attributes: otelApi.Attributes = {\n [semconv.ATTR_URL_FULL]: e.request.requestUrl?.toString(),\n [semconv.ATTR_HTTP_REQUEST_RESEND_COUNT]: e.request.retryCount,\n };\n\n for (const [key, value] of Object.entries(e.timings.phases)) {\n if (Number.isFinite(value)) {\n attributes[`detsys.http.timing.${key}`] = value;\n }\n }\n\n this.addEvent(EVENT_REQUEST_TIMEOUT, attributes);\n }\n }\n\n /**\n * Fetch an artifact, such as a tarball, from the location determined by the\n * `source-*` inputs. If `source-binary` is specified, this will return a path\n * to a binary on disk; otherwise, the artifact will be downloaded from the\n * URL determined by the other `source-*` inputs (`source-url`, `source-pr`,\n * etc.).\n *\n * When `source-checksums-url` and `source-checksums-sha256` are both set,\n * the downloaded artifact is verified against the per-arch hash in the\n * checksums file, which is itself verified against the pinned\n * `source-checksums-sha256`. Both inputs must be set together.\n */\n private async fetchArtifact(): Promise<string> {\n const sourceBinary = inputs.getStringOrNull(\"source-binary\");\n\n // If source-binary is set, use that. Otherwise fall back to the source-* parameters.\n if (sourceBinary !== null && sourceBinary !== \"\") {\n log.debug(`Using the provided source binary at ${sourceBinary}`);\n return sourceBinary;\n }\n\n return await otel.withSpan(\n \"fetch_artifact\",\n async (span) => {\n const expectedArtifactHash = await this.resolveExpectedArtifactHash();\n\n actionsCore.startGroup(\n `Downloading ${this.actionOptions.name} for ${this.architectureFetchSuffix}`,\n );\n\n try {\n log.info(`Fetching from ${await this.getSourceUrl()}`);\n\n const correlatedUrl = await this.getSourceUrl();\n correlatedUrl.searchParams.set(\"ci\", \"github\");\n correlatedUrl.searchParams.set(\n \"correlation\",\n JSON.stringify(this.identity),\n );\n\n const versionCheckup = await (\n await this.getClient()\n ).head(correlatedUrl);\n if (versionCheckup.headers.etag) {\n const v = versionCheckup.headers.etag;\n this.setAttribute(ATTR_SOURCE_ETAG, v);\n\n log.debug(\n `Checking the tool cache for ${await this.getSourceUrl()} at ${v}`,\n );\n const cached = await this.getCachedVersion(v, expectedArtifactHash);\n if (cached) {\n span.setAttribute(ATTR_ARTIFACT_CACHE_HIT, true);\n log.debug(`Tool cache hit.`);\n await this.verifyArtifactHash(cached, expectedArtifactHash);\n return cached;\n }\n }\n\n span.setAttribute(ATTR_ARTIFACT_CACHE_HIT, false);\n\n log.debug(\n `No match from the cache, re-fetching from the redirect: ${versionCheckup.url}`,\n );\n\n const destFile = this.getTemporaryName();\n\n const fetchStream = await this.downloadFile(\n new URL(versionCheckup.url),\n destFile,\n );\n\n await this.verifyArtifactHash(destFile, expectedArtifactHash);\n\n if (fetchStream.response?.headers.etag) {\n const v = fetchStream.response.headers.etag;\n\n try {\n await this.saveCachedVersion(v, destFile, expectedArtifactHash);\n } catch (e: unknown) {\n log.debug(`Error caching the artifact: ${stringifyError(e)}`);\n }\n }\n\n return destFile;\n } catch (e: unknown) {\n this.recordPlausibleTimeout(e);\n throw e;\n } finally {\n actionsCore.endGroup();\n }\n },\n {\n [ATTR_ARTIFACT_NAME]: this.actionOptions.name,\n [ATTR_ARTIFACT_FETCH_SUFFIX]: this.architectureFetchSuffix,\n },\n );\n }\n\n /**\n * Read the `source-checksums-url` and `source-checksums-sha256` inputs and,\n * if both are set, fetch the checksums file, verify its hash matches the\n * pin, parse it, and return the expected hash for the artifact matching\n * this runner's `${name}-${architectureFetchSuffix}`. Returns `null` when\n * verification is opted out (both inputs unset).\n */\n private async resolveExpectedArtifactHash(): Promise<string | null> {\n const checksumsUrl = inputs.getStringOrNull(\"source-checksums-url\");\n const checksumsSha256 = inputs.getStringOrNull(\"source-checksums-sha256\");\n\n if (checksumsUrl === null && checksumsSha256 === null) {\n return null;\n }\n if (checksumsUrl === null || checksumsSha256 === null) {\n throw new Error(\n \"`source-checksums-url` and `source-checksums-sha256` must be set together\",\n );\n }\n\n sourcedef.assertChecksumSourceIsPinned(this.sourceParameters);\n\n const expectedFileHash = checksumsSha256.toLowerCase();\n this.setAttribute(ATTR_SOURCE_CHECKSUMS_SHA256, expectedFileHash);\n\n const parsedUrl = new URL(checksumsUrl);\n const safeUrl = parsedUrl.origin + parsedUrl.pathname;\n\n actionsCore.info(`Fetching checksums file from ${safeUrl}`);\n const response = await (await this.getClient()).get(checksumsUrl);\n const body = response.body;\n\n const actualFileHash = checksums.sha256OfBuffer(body);\n if (actualFileHash !== expectedFileHash) {\n throw new Error(\n `Checksums file hash mismatch at ${safeUrl}: expected ${expectedFileHash}, got ${actualFileHash}`,\n );\n }\n\n const wanted = `${this.actionOptions.name}-${this.architectureFetchSuffix}`;\n const hashes = checksums.parseChecksumsFile(body);\n const artifactHash = hashes.get(wanted);\n if (artifactHash === undefined) {\n throw new Error(`No entry for ${wanted} in checksums file at ${safeUrl}`);\n }\n return artifactHash;\n }\n\n /**\n * Verify a downloaded artifact's SHA-256 matches the expected hash. No-op\n * when `expected` is `null` (verification disabled).\n */\n private async verifyArtifactHash(\n filePath: string,\n expected: string | null,\n ): Promise<void> {\n if (expected === null) {\n return;\n }\n const actual = await checksums.sha256OfFile(filePath);\n if (actual !== expected) {\n throw new Error(\n `Artifact hash mismatch for ${this.architectureFetchSuffix}: expected ${expected}, got ${actual}`,\n );\n }\n }\n\n /**\n * A helper function for failing on error only if strict mode is enabled.\n * This is intended only for CI environments testing Actions themselves.\n */\n failOnError(msg: string): void {\n if (this.strictMode) {\n actionsCore.setFailed(`strict mode failure: ${msg}`);\n }\n }\n\n private async downloadFile(\n url: URL,\n destination: nodeFs.PathLike,\n ): Promise<Request> {\n return await otel.withSpan(\"download_file\", async () =>\n this.download(url, destination),\n );\n }\n\n private async download(\n url: URL,\n destination: nodeFs.PathLike,\n ): Promise<Request> {\n const client = await this.getClient();\n\n return new Promise((resolve, reject) => {\n // Current stream handle\n let writeStream: nodeFs.WriteStream | undefined;\n\n // Sentinel condition in case we want to abort retrying due to FS issues\n let failed = false;\n\n const retry = (stream: Request): void => {\n if (writeStream) {\n writeStream.destroy();\n }\n\n writeStream = nodeFs.createWriteStream(destination, {\n encoding: \"binary\",\n mode: 0o755,\n });\n\n writeStream.once(\"error\", (error) => {\n // Set failed here since promise rejections don't impact control flow\n failed = true;\n reject(error);\n });\n\n writeStream.on(\"finish\", () => {\n if (!failed) {\n resolve(stream);\n }\n });\n\n stream.once(\"retry\", (_count, _error, createRetryStream) => {\n // Optional: check `failed' here in case you want to stop retrying\n retry(createRetryStream());\n });\n\n // Now that all the handlers have been set up we can pipe from the HTTP\n // stream to disk\n stream.pipe(writeStream);\n };\n\n // Begin the retry logic by giving it a fresh got.Request\n retry(client.stream(url));\n });\n }\n\n private async complete(): Promise<void> {\n this.phaseSpan?.end();\n this.phaseSpan = undefined;\n\n // The job's span contains this phase, so it ends after this phase does.\n this.endJobSpan();\n\n // The process exits as soon as we return, so anything still buffered has\n // to go out now.\n await this.telemetry.shutdown();\n }\n\n private async getCheckInUrl(): Promise<URL | undefined> {\n const checkInUrl = await this.idsHost.getDynamicRootUrl();\n\n if (checkInUrl === undefined) {\n return undefined;\n }\n\n checkInUrl.pathname += \"check-in\";\n return checkInUrl;\n }\n\n private async getSourceUrl(): Promise<URL> {\n const p = this.sourceParameters;\n\n if (p.url) {\n this.setAttribute(ATTR_SOURCE_URL, p.url);\n return new URL(p.url);\n }\n\n const fetchUrl = await this.idsHost.getRootUrl();\n fetchUrl.pathname += this.actionOptions.idsProjectName;\n\n if (p.tag) {\n fetchUrl.pathname += `/tag/${p.tag}`;\n } else if (p.pr) {\n fetchUrl.pathname += `/pr/${p.pr}`;\n } else if (p.branch) {\n fetchUrl.pathname += `/branch/${p.branch}`;\n } else if (p.revision) {\n fetchUrl.pathname += `/rev/${p.revision}`;\n } else {\n fetchUrl.pathname += `/stable`;\n }\n\n fetchUrl.pathname += `/${this.architectureFetchSuffix}`;\n\n this.setAttribute(ATTR_SOURCE_URL, fetchUrl.toString());\n\n return fetchUrl;\n }\n\n private cacheKey(version: string, expectedHash: string | null): string {\n const cleanedVersion = version.replace(/[^a-zA-Z0-9-+.]/g, \"\");\n const hashSuffix = expectedHash ? `-h${expectedHash}` : \"\";\n return `determinatesystem-${this.actionOptions.name}-${this.architectureFetchSuffix}-${cleanedVersion}${hashSuffix}`;\n }\n\n private async getCachedVersion(\n version: string,\n expectedHash: string | null,\n ): Promise<undefined | string> {\n return await otel.withSpan(\"artifact_cache_restore\", async (span) => {\n const startCwd = process.cwd();\n\n try {\n const tempDir = this.getTemporaryName();\n await mkdir(tempDir);\n process.chdir(tempDir);\n\n // extremely evil shit right here:\n process.env.GITHUB_WORKSPACE_BACKUP = process.env.GITHUB_WORKSPACE;\n delete process.env.GITHUB_WORKSPACE;\n\n if (\n await actionsCache.restoreCache(\n [this.actionOptions.name],\n this.cacheKey(version, expectedHash),\n [],\n undefined,\n true,\n )\n ) {\n span.setAttribute(ATTR_ARTIFACT_CACHE_HIT, true);\n return `${tempDir}/${this.actionOptions.name}`;\n }\n\n span.setAttribute(ATTR_ARTIFACT_CACHE_HIT, false);\n return undefined;\n } finally {\n process.env.GITHUB_WORKSPACE = process.env.GITHUB_WORKSPACE_BACKUP;\n delete process.env.GITHUB_WORKSPACE_BACKUP;\n process.chdir(startCwd);\n }\n });\n }\n\n private async saveCachedVersion(\n version: string,\n toolPath: string,\n expectedHash: string | null,\n ): Promise<void> {\n return await otel.withSpan(\"artifact_cache_persist\", async () => {\n const startCwd = process.cwd();\n\n try {\n const tempDir = this.getTemporaryName();\n await mkdir(tempDir);\n process.chdir(tempDir);\n await copyFile(toolPath, `${tempDir}/${this.actionOptions.name}`);\n\n // extremely evil shit right here:\n process.env.GITHUB_WORKSPACE_BACKUP = process.env.GITHUB_WORKSPACE;\n delete process.env.GITHUB_WORKSPACE;\n\n await actionsCache.saveCache(\n [this.actionOptions.name],\n this.cacheKey(version, expectedHash),\n undefined,\n true,\n );\n } finally {\n process.env.GITHUB_WORKSPACE = process.env.GITHUB_WORKSPACE_BACKUP;\n delete process.env.GITHUB_WORKSPACE_BACKUP;\n process.chdir(startCwd);\n }\n });\n }\n\n /**\n * Emit the files `stapleFile` collected, as log records correlated to this\n * phase's span. The Action has already failed by the time this runs.\n */\n private async emitAttachments(): Promise<void> {\n for (const [name, location] of this.exceptionAttachments) {\n const attributes: otelApi.Attributes = {\n [ATTR_ATTACHMENT_NAME]: name,\n [ATTR_ATTACHMENT_PATH]: location.toString(),\n };\n\n try {\n otel.emitLogRecord(\n \"error\",\n await readFile(location, \"utf-8\"),\n attributes,\n );\n } catch (innerError: unknown) {\n otel.emitLogRecord(\"error\", `Attachment unavailable`, {\n ...attributes,\n [semconv.ATTR_EXCEPTION_MESSAGE]: stringifyError(innerError),\n });\n }\n }\n }\n\n private async preflightRequireNix(): Promise<boolean> {\n return await otel.withSpan(\"preflight_require_nix\", async () => {\n let nixLocation: string | undefined;\n\n const pathParts = (process.env[\"PATH\"] || \"\").split(\":\");\n for (const location of pathParts) {\n const candidateNix = path.join(location, \"nix\");\n\n try {\n await fs.access(candidateNix, fs.constants.X_OK);\n log.debug(`Found Nix at ${candidateNix}`);\n nixLocation = candidateNix;\n break;\n } catch {\n actionsCore.debug(`Nix not at ${candidateNix}`);\n }\n }\n this.setAttribute(ATTR_NIX_LOCATION, nixLocation || \"\");\n\n if (this.actionOptions.requireNix === \"ignore\") {\n return true;\n }\n\n const currentNotFoundState = actionsCore.getState(\n STATE_KEY_NIX_NOT_FOUND,\n );\n if (currentNotFoundState === STATE_NOT_FOUND) {\n // It was previously not found, so don't run subsequent actions\n return false;\n }\n\n if (nixLocation !== undefined) {\n return true;\n }\n actionsCore.saveState(STATE_KEY_NIX_NOT_FOUND, STATE_NOT_FOUND);\n\n switch (this.actionOptions.requireNix) {\n case \"fail\":\n log.setFailed(\n [\n \"This action can only be used when Nix is installed.\",\n \"Add `- uses: DeterminateSystems/determinate-nix-action@v3` earlier in your workflow.\",\n ].join(\" \"),\n );\n break;\n case \"warn\":\n log.warning(\n [\n \"This action is in no-op mode because Nix is not installed.\",\n \"Add `- uses: DeterminateSystems/determinate-nix-action@v3` earlier in your workflow.\",\n ].join(\" \"),\n );\n break;\n }\n\n return false;\n });\n }\n\n private async preflightNixStoreInfo(): Promise<void> {\n return await otel.withSpan(\"preflight_nix_store_info\", async (span) => {\n let output = \"\";\n\n const options: actionsExec.ExecOptions = {};\n options.silent = true;\n options.listeners = {\n stdout: (data) => {\n output += data.toString();\n },\n };\n\n try {\n output = \"\";\n await actionsExec.exec(\"nix\", [\"store\", \"info\", \"--json\"], options);\n this.setAttribute(ATTR_NIX_STORE_CHECK_METHOD, \"info\");\n } catch {\n try {\n // reset output\n output = \"\";\n await actionsExec.exec(\"nix\", [\"store\", \"ping\", \"--json\"], options);\n this.setAttribute(ATTR_NIX_STORE_CHECK_METHOD, \"ping\");\n } catch {\n this.setAttribute(ATTR_NIX_STORE_CHECK_METHOD, \"none\");\n return;\n }\n }\n\n try {\n const parsed = JSON.parse(output);\n if (parsed.trusted === true || parsed.trusted === 1) {\n this.nixStoreTrust = \"trusted\";\n } else if (parsed.trusted === false || parsed.trusted === 0) {\n this.nixStoreTrust = \"untrusted\";\n } else if (parsed.trusted !== undefined) {\n this.setAttribute(\n ATTR_NIX_STORE_CHECK_ERROR,\n `Mysterious trusted value: ${JSON.stringify(parsed.trusted)}`,\n );\n }\n\n this.setAttribute(\n ATTR_NIX_STORE_VERSION,\n JSON.stringify(parsed.version),\n );\n } catch (e: unknown) {\n this.setAttribute(ATTR_NIX_STORE_CHECK_ERROR, stringifyError(e));\n }\n\n span.setAttribute(ATTR_NIX_STORE_TRUST, this.nixStoreTrust);\n });\n }\n\n private async preflightNixVersion(): Promise<void> {\n return await otel.withSpan(\"preflight_nix_version\", async (span) => {\n let output = \"unknown\";\n\n try {\n ({ stdout: output } = await actionsExec.getExecOutput(\n \"nix\",\n [\"--version\"],\n {\n silent: true,\n },\n ));\n output = output.trim() || \"unknown\";\n } catch {\n // That's fine.\n }\n\n this.setAttribute(ATTR_NIX_VERSION, output);\n span.setAttribute(ATTR_NIX_VERSION, output);\n });\n }\n}\n\nfunction stringifyError(error: unknown): string {\n return error instanceof Error || typeof error == \"string\"\n ? error.toString()\n : JSON.stringify(error);\n}\n\n/**\n * The runner's operating system, as `os.type` spells it.\n */\nfunction osType(): string {\n switch (ghActionsCorePlatform.platform) {\n case \"win32\":\n return semconvIncubating.OS_TYPE_VALUE_WINDOWS;\n case \"darwin\":\n return semconvIncubating.OS_TYPE_VALUE_DARWIN;\n case \"linux\":\n return semconvIncubating.OS_TYPE_VALUE_LINUX;\n default:\n return ghActionsCorePlatform.platform;\n }\n}\n\n/**\n * The runner's architecture, as `host.arch` spells it.\n */\nfunction hostArch(): string {\n switch (ghActionsCorePlatform.arch) {\n case \"x64\":\n return semconvIncubating.HOST_ARCH_VALUE_AMD64;\n case \"arm64\":\n return semconvIncubating.HOST_ARCH_VALUE_ARM64;\n case \"ia32\":\n return semconvIncubating.HOST_ARCH_VALUE_X86;\n case \"arm\":\n return semconvIncubating.HOST_ARCH_VALUE_ARM32;\n default:\n return ghActionsCorePlatform.arch;\n }\n}\n\nfunction makeOptionsConfident(\n actionOptions: ActionOptions,\n): ConfidentActionOptions {\n const idsProjectName = actionOptions.idsProjectName ?? actionOptions.name;\n\n const finalOpts: ConfidentActionOptions = {\n name: actionOptions.name,\n idsProjectName,\n fetchStyle: actionOptions.fetchStyle,\n legacySourcePrefix: actionOptions.legacySourcePrefix,\n requireNix: actionOptions.requireNix,\n };\n\n actionsCore.debug(\"idslib options:\");\n actionsCore.debug(JSON.stringify(finalOpts, undefined, 2));\n\n return finalOpts;\n}\n\n// Public exports from other files\nexport type {\n CheckIn,\n Feature,\n Incident,\n Maintenance,\n Page,\n StatusSummary,\n} from \"./check-in.js\";\nexport type { CorrelationProperties } from \"./correlation.js\";\nexport { stringifyError } from \"./errors.js\";\nexport { IdsHost } from \"./ids-host.js\";\nexport type { SourceDef } from \"./sourcedef.js\";\nexport * as inputs from \"./inputs.js\";\n\n/**\n * Logging that tees to both the GitHub Actions console and OpenTelemetry.\n * A drop-in replacement for the `@actions/core` logging functions.\n */\nexport * as log from \"./log.js\";\nexport * as platform from \"./platform.js\";\nexport type { LogLevel } from \"./telemetry.js\";\nexport {\n SCOPE_NAME,\n contextFromTraceparent,\n getLogger,\n getTracer,\n recordSpanError,\n traceContextHeaders,\n traceparentOf,\n withSpan,\n} from \"./telemetry.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAM,gBAAgB,UAAU,GAAG,QAA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