sfscanner 0.0.0-stage → 0.2.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.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +131 -3
  3. package/THIRD_PARTY_NOTICES.md +48 -0
  4. package/dist/index.d.ts +4 -0
  5. package/dist/index.js +10766 -0
  6. package/dist/index.js.map +7 -0
  7. package/dist/main.js +11941 -0
  8. package/dist/main.js.map +7 -0
  9. package/dist/mcp.js +10468 -0
  10. package/dist/mcp.js.map +7 -0
  11. package/dist/scan-worker.js +11800 -0
  12. package/dist/scan-worker.js.map +7 -0
  13. package/dist/v2/arguments.d.ts +87 -0
  14. package/dist/v2/arguments.js +403 -0
  15. package/dist/v2/arguments.js.map +7 -0
  16. package/dist/v2/atomic-output.d.ts +34 -0
  17. package/dist/v2/batch-runner.d.ts +50 -0
  18. package/dist/v2/cli-runner-internal.d.ts +28 -0
  19. package/dist/v2/cli-runner.d.ts +22 -0
  20. package/dist/v2/cli-runner.js +10037 -0
  21. package/dist/v2/cli-runner.js.map +7 -0
  22. package/dist/v2/commands.d.ts +155 -0
  23. package/dist/v2/config.d.ts +16 -0
  24. package/dist/v2/contracts.d.ts +97 -0
  25. package/dist/v2/exit-reducer.d.ts +23 -0
  26. package/dist/v2/help.d.ts +33 -0
  27. package/dist/v2/help.js +325 -0
  28. package/dist/v2/help.js.map +7 -0
  29. package/dist/v2/input-read.d.ts +26 -0
  30. package/dist/v2/input-selection.d.ts +38 -0
  31. package/dist/v2/json-output.d.ts +97 -0
  32. package/dist/v2/metadata-output.d.ts +37 -0
  33. package/dist/v2/metadata-output.js +7523 -0
  34. package/dist/v2/metadata-output.js.map +7 -0
  35. package/dist/v2/metadata-validation.d.ts +4 -0
  36. package/dist/v2/ndjson-output.d.ts +3 -0
  37. package/dist/v2/path-admission.d.ts +8 -0
  38. package/dist/v2/scan-config-load.d.ts +21 -0
  39. package/dist/v2/scan-worker-host.d.ts +29 -0
  40. package/dist/v2/table-output.d.ts +2 -0
  41. package/dist/v2/worker-host.d.ts +24 -0
  42. package/package.json +74 -6
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/help.ts", "../src/input.ts", "../../../contracts/scanner-result.ts", "../../../contracts/exclusion-registry.ts", "../../../contracts/limits.ts", "../../../contracts/scanner-limits.ts", "../../../contracts/scanner-limits-v2.ts", "../../../contracts/stable-order.ts", "../../scanner-core/src/provider-token-patterns.ts", "../../scanner-core/src/redaction/structured-redaction.ts", "../../scanner-core/src/redaction/redaction.ts", "../../scanner-core/src/result/canonical-findings.ts", "../../scanner-core/src/result/analysis-completeness.ts", "../../scanner-core/src/result/analysis-diagnostics-collection.ts", "../../scanner-core/src/analyzers/expression/expression-islands.ts", "../../scanner-core/src/analyzers/secrets/provider-token-registry.ts", "../../scanner-core/src/analyzers/expression/placeholder-classifier.ts", "../../scanner-core/src/secret-classifier.ts", "../../scanner-core/src/policy/policy-helpers.ts", "../../scanner-core/src/policies/domain-policy.ts", "../../scanner-core/src/policies/secret-indicators.ts", "../../scanner-core/src/policies/credential-policies.ts", "../../scanner-core/src/policies/execution-policies.ts", "../../scanner-core/src/policies/package-and-webhook-policies.ts", "../../scanner-core/src/policies/beta-policies.ts", "../../scanner-core/src/stable-order.ts", "../../scanner-core/src/workflow-insights.ts", "../../scanner-core/src/scan-insights.ts", "../../scanner-core/src/workflow-graph-views.ts", "../../scanner-core/src/json-pointer.ts", "../../scanner-core/src/workflow-graph.ts", "../../scanner-core/src/capabilities/adapter-workflow.ts", "../../../node_modules/@noble/hashes/_u64.js", "../../../node_modules/@noble/hashes/utils.js", "../../../node_modules/@noble/hashes/_md.js", "../../../node_modules/@noble/hashes/sha2.js", "../../scanner-core/src/canonical-json.ts", "../../scanner-core/src/workflow-v2/node-edge-identity.ts", "../../../node_modules/@humanwhocodes/momoa/dist/momoa.js", "../../scanner-core/src/source/source-preflight.ts", "../../scanner-core/src/source/source-identities.ts", "../../scanner-core/src/source/source-tree-helpers.ts", "../../scanner-core/src/source/source-tree.ts", "../../scanner-core/src/source/scanner-limit-resolution.ts", "../../scanner-core/src/source/source-document-provenance.ts", "../../scanner-core/src/source/source-parser.ts", "../../scanner-core/src/admission/snapshot.ts", "../../scanner-core/src/facts/safe-fact-registry.ts", "../../scanner-core/src/facts/safe-fact-validator.ts", "../../scanner-core/src/diagnostics/registry.ts", "../../scanner-core/src/diagnostics/identity.ts", "../../scanner-core/src/rules-v2/rule-authority.ts", "../../scanner-core/src/capabilities/adapter-evidence.ts", "../../scanner-core/src/policy/rule-catalog.ts", "../../scanner-core/src/capabilities/profile-manifest.ts", "../../scanner-core/src/capabilities/candidate-validator.ts", "../../scanner-core/src/capabilities/context-view.ts", "../../scanner-core/src/capabilities/scheduler.ts", "../../scanner-core/src/capabilities/beta-default.ts", "../../scanner-core/src/scanner-version.ts", "../../scanner-core/src/policies/profile.ts", "../../scanner-core/src/engine/engine.ts", "../../scanner-core/src/presentation-redaction.ts", "../../scanner-core/src/result/finding-source-spans.ts", "../../scanner-core/src/workflow-budgets.ts", "../../scanner-core/src/workflow-diagnostics.ts", "../../scanner-core/src/workflow-source-locations.ts", "../../scanner-core/src/workflow.ts", "../src/scan.ts", "../../scanner-core/src/report/sarif-tags.ts", "../../scanner-core/src/report/sarif-document.ts", "../src/sarif.ts", "../src/cli.ts", "../src/v2/contracts.ts", "../src/v2/path-admission.ts", "../src/v2/arguments.ts", "../src/v2/metadata-output.ts", "../src/v2/commands.ts", "../../scanner-core/src/workflow-v2/ambiguity.ts", "../../scanner-core/src/semantics/semver.ts", "../../scanner-core/src/semantics/target-context.ts", "../../scanner-core/src/semantics/version-range.ts", "../../scanner-core/src/semantics/catalogue-admission.ts", "../../../docs/scanner/semantic-source-receipts.json", "../../scanner-core/src/semantics/builtin-provenance.ts", "../../scanner-core/src/semantics/builtin-catalogue.ts", "../../scanner-core/src/semantics/generic-fallback.ts", "../../scanner-core/src/capabilities/semantic-context.ts", "../../../contracts/scanner-v2-diagnostics.generated.ts", "../../../contracts/scanner-v2-result.ts", "../../scanner-core/src/result-v2/canonical-bytes.ts", "../../scanner-core/src/result-v2/identities.ts", "../../scanner-core/src/v2/admitted-registry.ts", "../../scanner-core/src/workflow-v2/budget-outcomes.ts", "../../scanner-core/src/v2/span-loss-classification.ts", "../../scanner-core/src/v2/scan-workflow.ts", "../src/v2/config.ts", "../src/v2/metadata-validation.ts", "../src/v2/help.ts", "../src/v2/input-selection.ts", "../src/v2/scan-config-load.ts", "../src/v2/input-read.ts", "../src/v2/scan-worker-host.ts", "../src/v2/worker-host.ts", "../src/v2/batch-runner.ts", "../src/v2/json-output.ts", "../src/v2/ndjson-output.ts", "../../scanner-core/src/compat/v1-registry.ts", "../../scanner-core/src/report/sarif-v2/helpers.ts", "../../scanner-core/src/report/sarif-v2/output.ts", "../src/v2/table-output.ts", "../src/v2/exit-reducer.ts", "../src/v2/atomic-output.ts", "../src/v2/cli-runner-internal.ts", "../src/v2/cli-runner.ts", "../src/main.ts"],
4
+ "sourcesContent": ["export const HELP_TEXT = [\n 'sfscanner \u2014 deterministic offline n8n workflow scanner',\n '',\n 'Usage:',\n ' sfscanner <file|->',\n ' sfscanner scan <file|->',\n ' sfscanner scan <file|-> --format sarif',\n ' sfscanner --version',\n ' sfscanner --version --json',\n '',\n 'Inputs:',\n ' file Read one n8n workflow JSON document from a file.',\n ' - Read one n8n workflow JSON document from stdin.',\n '',\n 'Options:',\n ' --format <json|sarif> Select the output format. Defaults to json.',\n '',\n 'Output:',\n ' json (default): a stable, versioned JSON document on stdout.',\n ' sarif: SARIF 2.1.0, with CWE tags GitHub code scanning reads, for one input.',\n ' Exit 0 means no findings; exit 1 means findings were returned.',\n ' Exit 2 means usage error; exit 3 means input error.',\n '',\n 'This public package currently supports one input and the beta-default profile.',\n 'Batch scanning, hardened analyzers, and pipeline enrichment remain outside this',\n 'minimal offline contract.',\n '',\n].join('\\n');\n", "import { open } from 'node:fs/promises';\nimport { LIMITS } from '@hub/contracts';\n\nexport type CliStdin = string | AsyncIterable<Uint8Array | string>;\n\n/** The v1 ceiling is the shared workflow-byte authority, not a second number. */\nexport const MAX_V1_INPUT_BYTES = LIMITS.maxWorkflowBytes;\n\nexport async function readWorkflowInput(input: string, stdin: CliStdin = process.stdin): Promise<string> {\n if (input !== '-') {\n const handle = await open(input, 'r');\n try {\n const stat = await handle.stat();\n if (!stat.isFile()) throw new RangeError('NOT_REGULAR_FILE');\n if (stat.size > MAX_V1_INPUT_BYTES) throw new RangeError('OVERSIZED');\n const bytes = new Uint8Array(stat.size);\n let offset = 0;\n while (offset < bytes.length) {\n const { bytesRead } = await handle.read(bytes, offset, bytes.length - offset, offset);\n if (bytesRead === 0) break;\n offset += bytesRead;\n }\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, offset));\n } finally {\n await handle.close();\n }\n }\n if (typeof stdin === 'string') {\n if (Buffer.byteLength(stdin, 'utf8') > MAX_V1_INPUT_BYTES) throw new RangeError('OVERSIZED');\n return stdin;\n }\n const chunks: Uint8Array[] = [];\n let total = 0;\n for await (const chunk of stdin) {\n const bytes = typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk;\n total += bytes.byteLength;\n if (total > MAX_V1_INPUT_BYTES) throw new RangeError('OVERSIZED');\n chunks.push(bytes);\n }\n const combined = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) { combined.set(chunk, offset); offset += chunk.byteLength; }\n return new TextDecoder('utf-8', { fatal: true }).decode(combined);\n}\n", "/**\r\n * Identity for the serialized deterministic scanner result. Bump this when\r\n * result fields or their semantics change incompatibly.\r\n */\r\nexport const SCANNER_RESULT_SCHEMA_VERSION = 'scanner-result-v1' as const;\r\n\r\nexport type ScannerResultSchemaVersion = typeof SCANNER_RESULT_SCHEMA_VERSION;\r\n\r\nexport type ScannerResultIdentity = {\r\n schemaVersion: ScannerResultSchemaVersion;\r\n};\r\n\r\n/** Fails closed before an authoritative result is projected or published. */\r\nexport function parseScannerResultSchemaVersion(value: unknown): ScannerResultSchemaVersion {\r\n if (value === undefined || value === null || value === '') {\r\n throw new Error('Scanner result is missing schemaVersion');\r\n }\r\n if (value !== SCANNER_RESULT_SCHEMA_VERSION) {\r\n throw new Error(`Scanner result has unsupported schemaVersion: ${String(value)}`);\r\n }\r\n return SCANNER_RESULT_SCHEMA_VERSION;\r\n}\r\n", "/**\n * The exclusion registry: an immutable, append-only list of workflow\n * identities withheld from every downstream artifact, keyed by reason and\n * date.\n *\n * **Identity.** A record is keyed by the same canonical id every `Entry`/\n * `Candidate` already carries \u2014 the 16-hex-character output of\n * `pipeline/acquire/entry-id.ts`'s `entryId(kind, ref, path)`. No second\n * identity scheme is introduced: a title or slug can change on a re-scrape or\n * a re-describe, but `entryId` is a hash of the source coordinates\n * (kind + ref + path) that never changes for the same workflow, which is\n * exactly the stability an exclusion needs \u2014 an exclusion recorded against a\n * workflow must still match it after its title, tags, or description change.\n *\n * **Registry vs. rights status.** This module answers a different question\n * than `rights.ts`'s `excluded` status does. The registry is the *cause* and\n * the *authority*: it is consulted at the earliest possible pipeline point\n * (immediately after acquisition, before rights are even decided \u2014 see\n * `pipeline/rights/exclusion-filter.ts`), so an excluded workflow is dropped\n * before it becomes a `Candidate` that anything downstream can see. A record\n * never becomes a full `Entry` at all in the ordinary path, so\n * `EntryRights.status === 'excluded'` is not how exclusion normally\n * propagates \u2014 it exists in the rights union as a second, independent gate:\n * if a record ever reaches rights decision or entry construction carrying an\n * id this registry recognizes, that code path can name it `excluded` instead\n * of guessing, rather than treating an already-answered question as still\n * open. Two gates, not one, because the registry's contents can change\n * (append-only growth) independently of any single pipeline run, and a\n * resumed or partially-cached run is exactly the case where the earlier gate\n * could be bypassed by stale state.\n *\n * **Immutable, append-only.** A registry value is frozen and exposes no\n * mutation method. Growing it means calling `appendExclusion`, which returns\n * a *new* registry with strictly one more record \u2014 it never edits or removes\n * an existing one. There is deliberately no `remove`/`update` API: a\n * retraction is a policy decision ([B]-blocked per\n * `openspec/changes/legal-rights-and-release-integrity/tasks.md`), not a data\n * operation this module should make easy to do quietly.\n */\n\nconst ENTRY_ID_PATTERN = /^[0-9a-f]{16}$/;\n\nexport type ExclusionRecord = {\n /** Canonical `entryId(kind, ref, path)` output \u2014 see module doc comment. */\n id: string;\n /** Human-readable, non-empty. Evidence, not a legal conclusion. */\n reason: string;\n /** ISO 8601 timestamp the exclusion was recorded. */\n excludedAt: string;\n};\n\nexport type ExclusionRegistry = {\n readonly records: readonly ExclusionRecord[];\n isExcluded(id: string): boolean;\n recordFor(id: string): ExclusionRecord | undefined;\n};\n\nfunction validateRecord(record: ExclusionRecord): void {\n if (!ENTRY_ID_PATTERN.test(record.id)) {\n throw new Error(\n `Exclusion registry record has a malformed id \"${record.id}\": expected the 16-hex-character ` +\n 'output of entryId(kind, ref, path), not a title, slug, or free-text identifier.',\n );\n }\n if (!record.reason.trim()) {\n throw new Error(`Exclusion registry record for id \"${record.id}\" has no reason recorded.`);\n }\n if (!Number.isFinite(Date.parse(record.excludedAt))) {\n throw new Error(\n `Exclusion registry record for id \"${record.id}\" has an invalid excludedAt timestamp: \"${record.excludedAt}\".`,\n );\n }\n}\n\n/**\n * Builds a frozen registry from a list of records, validating every one and\n * rejecting a duplicate id outright \u2014 the registry has exactly one record per\n * excluded identity, so two different reasons for the same id is a data bug,\n * not a merge to resolve silently.\n */\nexport function createExclusionRegistry(records: readonly ExclusionRecord[]): ExclusionRegistry {\n const seen = new Set<string>();\n for (const record of records) {\n validateRecord(record);\n if (seen.has(record.id)) {\n throw new Error(`Exclusion registry has more than one record for id \"${record.id}\".`);\n }\n seen.add(record.id);\n }\n const frozenRecords = Object.freeze(records.map((record) => Object.freeze({ ...record })));\n const byId = new Map(frozenRecords.map((record) => [record.id, record]));\n\n return Object.freeze({\n records: frozenRecords,\n isExcluded: (id: string) => byId.has(id),\n recordFor: (id: string) => byId.get(id),\n });\n}\n\n/** The starting registry: no exclusions recorded yet (owner decision [B]-blocked). */\nexport const EMPTY_EXCLUSION_REGISTRY: ExclusionRegistry = createExclusionRegistry([]);\n\n/**\n * Returns a *new* registry with `record` appended. Never mutates `registry`.\n * Throws if `record.id` is already present \u2014 append-only means every id is\n * recorded once, with one reason and one date; changing either requires a\n * conscious new record kept separately, not an overwrite of this one.\n */\nexport function appendExclusion(registry: ExclusionRegistry, record: ExclusionRecord): ExclusionRegistry {\n if (registry.isExcluded(record.id)) {\n throw new Error(\n `Id \"${record.id}\" is already recorded in the exclusion registry (reason: ` +\n `\"${registry.recordFor(record.id)?.reason}\"). Append-only: it cannot be re-added or overwritten.`,\n );\n }\n return createExclusionRegistry([...registry.records, record]);\n}\n", "/** SPDX ids we treat as redistributable. Static allowlist, deliberately short. */\nexport const REDISTRIBUTABLE_LICENCES: Record<string, true> = {\n 'MIT': true,\n 'Apache-2.0': true,\n 'BSD-2-Clause': true,\n 'BSD-3-Clause': true,\n 'ISC': true,\n 'CC0-1.0': true,\n 'Unlicense': true,\n};\n\n/** Hard limits. Shared by acquisition, the worker, and the browser scanner. */\nexport const LIMITS = {\n maxWorkflowBytes: 1_536_000,\n maxNodes: 5_000,\n scanTimeoutMs: 30_000,\n packSize: 250,\n shardSize: 2_000,\n maxPublicFindings: 20,\n} as const;\n", "import { LIMITS } from './limits';\n\n/**\n * The one versioned scanner-limits contract browser, worker, and pipeline\n * callers share. `LIMITS` (limits.ts) stays the source for the three numbers\n * it already owned (maxWorkflowBytes/maxNodes/scanTimeoutMs are read from it\n * below, not re-declared) so this cannot silently drift from it.\n */\nexport const SCANNER_LIMITS_SCHEMA_VERSION = 'scanner-limits-v1' as const;\n\nexport type ScannerLimitsV1 = {\n schemaVersion: typeof SCANNER_LIMITS_SCHEMA_VERSION;\n maxBytes: number;\n maxNodes: number;\n maxEdges: number;\n maxConnectionDepth: number;\n maxParameterDepth: number;\n maxParameterLeaves: number;\n workerDeadlineMs: number;\n};\n\nconst SCANNER_LIMITS_FIELDS = [\n 'schemaVersion',\n 'maxBytes',\n 'maxNodes',\n 'maxEdges',\n 'maxConnectionDepth',\n 'maxParameterDepth',\n 'maxParameterLeaves',\n 'workerDeadlineMs',\n] as const satisfies readonly (keyof ScannerLimitsV1)[];\n\nexport const DEFAULT_SCANNER_LIMITS: ScannerLimitsV1 = Object.freeze({\n schemaVersion: SCANNER_LIMITS_SCHEMA_VERSION,\n maxBytes: LIMITS.maxWorkflowBytes,\n maxNodes: LIMITS.maxNodes,\n maxEdges: 10_000,\n // Previously declared as a `workflow.ts` option but never wired to any\n // production caller (see scanner-contract-and-calibration tasks.md P1.1) \u2014\n // this is the first real default for it.\n maxConnectionDepth: 64,\n maxParameterDepth: 64,\n maxParameterLeaves: 10_000,\n workerDeadlineMs: LIMITS.scanTimeoutMs,\n});\n\nexport type ScannerLimitsValidationResult =\n | { ok: true; limits: ScannerLimitsV1 }\n | { ok: false; errors: string[] };\n\n/** Fails closed and reports every violation, not just the first, so a bad config is fully diagnosable. */\nexport function validateScannerLimits(candidate: unknown): ScannerLimitsValidationResult {\n if (typeof candidate !== 'object' || candidate === null || Array.isArray(candidate)) {\n return { ok: false, errors: ['limits must be an object'] };\n }\n\n const value = candidate as Record<string, unknown>;\n const errors: string[] = [];\n const knownFields = new Set<string>(SCANNER_LIMITS_FIELDS);\n\n for (const field of Object.keys(value)) {\n if (!knownFields.has(field)) errors.push(`unknown field: ${field}`);\n }\n\n if (value.schemaVersion !== SCANNER_LIMITS_SCHEMA_VERSION) {\n errors.push(`unsupported schemaVersion: ${String(value.schemaVersion)}`);\n }\n\n for (const field of SCANNER_LIMITS_FIELDS) {\n if (field === 'schemaVersion') continue;\n if (!(field in value)) {\n errors.push(`missing field: ${field}`);\n continue;\n }\n const raw = value[field];\n if (typeof raw !== 'number' || !Number.isInteger(raw) || raw < 0) {\n errors.push(`${field} must be a non-negative integer`);\n }\n }\n\n if (errors.length > 0) return { ok: false, errors };\n\n return {\n ok: true,\n limits: {\n schemaVersion: SCANNER_LIMITS_SCHEMA_VERSION,\n maxBytes: value.maxBytes as number,\n maxNodes: value.maxNodes as number,\n maxEdges: value.maxEdges as number,\n maxConnectionDepth: value.maxConnectionDepth as number,\n maxParameterDepth: value.maxParameterDepth as number,\n maxParameterLeaves: value.maxParameterLeaves as number,\n workerDeadlineMs: value.workerDeadlineMs as number,\n },\n };\n}\n\n/** Stable key order regardless of the input object's own construction order. */\nexport function serializeScannerLimits(limits: ScannerLimitsV1): string {\n return JSON.stringify(limits, SCANNER_LIMITS_FIELDS as unknown as string[]);\n}\n\n/** The exact option shape `parseWorkflowJson` accepts \u2014 one mapping, not one per caller. */\nexport function toWorkflowParseOptions(limits: ScannerLimitsV1): {\n maxBytes: number;\n maxNodes: number;\n maxEdges: number;\n maxConnectionDepth: number;\n maxParameterDepth: number;\n maxParameterLeaves: number;\n} {\n return {\n maxBytes: limits.maxBytes,\n maxNodes: limits.maxNodes,\n maxEdges: limits.maxEdges,\n maxConnectionDepth: limits.maxConnectionDepth,\n maxParameterDepth: limits.maxParameterDepth,\n maxParameterLeaves: limits.maxParameterLeaves,\n };\n}\n", "import {\n DEFAULT_SCANNER_LIMITS,\n type ScannerLimitsV1,\n} from './scanner-limits';\n\nexport const SCANNER_LIMITS_V2_SCHEMA_VERSION = 'scanner-limits-v2' as const;\n\nconst SCANNER_LIMITS_V2_NUMERIC_FIELDS = [\n 'maxBytes',\n 'maxNodes',\n 'maxEdges',\n 'maxConnectionDepth',\n 'maxParameterDepth',\n 'maxParameterLeaves',\n 'workerDeadlineMs',\n 'maxSyntaxNodes',\n 'maxDocumentDepth',\n 'maxMembersAndElements',\n 'maxRawEdges',\n 'maxDuplicateKeys',\n 'maxDiagnostics',\n 'maxStoredSourceSpans',\n 'maxSourceWork',\n 'maxExpressionTokens',\n 'maxCodeSyntaxNodes',\n 'maxGraphOperations',\n 'maxTaintStates',\n 'maxTraceStepsPerFinding',\n 'maxFindings',\n 'maxRedactionPatches',\n 'maxRedactedArtifactBytes',\n 'maxEvidenceBytes',\n 'maxSerializedResultBytes',\n 'maxRuleOperations',\n] as const;\n\nconst SCANNER_LIMITS_V2_FIELDS = [\n 'schemaVersion',\n ...SCANNER_LIMITS_V2_NUMERIC_FIELDS,\n] as const;\n\nexport type ScannerLimitsV2 = Omit<ScannerLimitsV1, 'schemaVersion'> & {\n schemaVersion: typeof SCANNER_LIMITS_V2_SCHEMA_VERSION;\n maxSyntaxNodes: number;\n maxDocumentDepth: number;\n maxMembersAndElements: number;\n maxRawEdges: number;\n maxDuplicateKeys: number;\n maxDiagnostics: number;\n maxStoredSourceSpans: number;\n maxSourceWork: number;\n maxExpressionTokens: number;\n maxCodeSyntaxNodes: number;\n maxGraphOperations: number;\n maxTaintStates: number;\n maxTraceStepsPerFinding: number;\n maxFindings: number;\n maxRedactionPatches: number;\n maxRedactedArtifactBytes: number;\n maxEvidenceBytes: number;\n maxSerializedResultBytes: number;\n maxRuleOperations: number;\n};\n\nexport const DEFAULT_SCANNER_LIMITS_V2: ScannerLimitsV2 = Object.freeze({\n ...DEFAULT_SCANNER_LIMITS,\n schemaVersion: SCANNER_LIMITS_V2_SCHEMA_VERSION,\n maxSyntaxNodes: 250_000,\n maxDocumentDepth: 256,\n maxMembersAndElements: 250_000,\n maxRawEdges: 50_000,\n maxDuplicateKeys: 1_000,\n maxDiagnostics: 1_000,\n maxStoredSourceSpans: 25_000,\n maxSourceWork: 1_000_000,\n maxExpressionTokens: 100_000,\n maxCodeSyntaxNodes: 250_000,\n maxGraphOperations: 1_000_000,\n maxTaintStates: 250_000,\n maxTraceStepsPerFinding: 100,\n maxFindings: 5_000,\n maxRedactionPatches: 10_000,\n maxRedactedArtifactBytes: 1_536_000,\n maxEvidenceBytes: 1_536_000,\n maxSerializedResultBytes: 5_000_000,\n maxRuleOperations: 1_000_000,\n});\n\nexport type ScannerLimitsV2ValidationResult =\n | { ok: true; limits: ScannerLimitsV2 }\n | { ok: false; errors: string[] };\n\nexport type AdmittedLimitStateV2 = 'WIRED' | 'DORMANT' | 'UNWIRED';\nexport type ScannerLimitNameV2 = (typeof SCANNER_LIMITS_V2_NUMERIC_FIELDS)[number];\n\n/**\n * The one authority every help surface and usage row reads. `WIRED` is consumed by the admitted\n * beta-default path, `DORMANT` only by an unadmitted profile (the hardened code, value-flow, taint\n * and graph analyzers), and `UNWIRED` by no shipped path (redaction-v2 is development-only).\n * `workerDeadlineMs` is wired because the CLI worker host enforces it.\n */\nexport const ADMITTED_LIMIT_STATES: Readonly<Record<ScannerLimitNameV2, AdmittedLimitStateV2>> = Object.freeze({\n maxBytes: 'WIRED',\n maxNodes: 'WIRED',\n maxEdges: 'WIRED',\n maxConnectionDepth: 'WIRED',\n maxParameterDepth: 'WIRED',\n maxParameterLeaves: 'WIRED',\n workerDeadlineMs: 'WIRED',\n maxSyntaxNodes: 'WIRED',\n maxDocumentDepth: 'WIRED',\n maxMembersAndElements: 'WIRED',\n maxRawEdges: 'WIRED',\n maxDuplicateKeys: 'WIRED',\n maxDiagnostics: 'WIRED',\n maxStoredSourceSpans: 'WIRED',\n maxSourceWork: 'WIRED',\n maxExpressionTokens: 'DORMANT',\n maxCodeSyntaxNodes: 'DORMANT',\n maxGraphOperations: 'DORMANT',\n maxTaintStates: 'DORMANT',\n maxTraceStepsPerFinding: 'DORMANT',\n maxFindings: 'WIRED',\n maxRedactionPatches: 'UNWIRED',\n maxRedactedArtifactBytes: 'UNWIRED',\n maxEvidenceBytes: 'WIRED',\n maxSerializedResultBytes: 'WIRED',\n maxRuleOperations: 'WIRED',\n});\n\n/**\n * The subset with a real per-scan counter. The narrow tuple is deliberate: a wide annotation would\n * make every one of the 26 names assignable, so the 13-key counter object below would not typecheck.\n * A budget without a counter is enforced where it is consumed but has no honest `usage` row.\n */\nexport const MEASURED_LIMIT_IDS = [\n 'maxBytes', 'maxNodes', 'maxEdges', 'maxConnectionDepth', 'maxParameterDepth',\n 'maxParameterLeaves', 'maxSyntaxNodes', 'maxRawEdges', 'maxDuplicateKeys',\n 'maxDiagnostics', 'maxStoredSourceSpans', 'maxSourceWork', 'maxFindings',\n] as const satisfies readonly ScannerLimitNameV2[];\n\nexport function validateScannerLimitsV2(candidate: unknown): ScannerLimitsV2ValidationResult {\n if (typeof candidate !== 'object' || candidate === null || Array.isArray(candidate)) {\n return { ok: false, errors: ['limits must be an object'] };\n }\n\n const value = candidate as Record<string, unknown>;\n const knownFields = new Set<string>(SCANNER_LIMITS_V2_FIELDS);\n const errors = Object.keys(value)\n .filter((field) => !knownFields.has(field))\n .sort()\n .map((field) => `unknown field: ${field}`);\n\n if (!Object.prototype.hasOwnProperty.call(value, 'schemaVersion')) {\n errors.push('missing field: schemaVersion');\n } else if (value.schemaVersion !== SCANNER_LIMITS_V2_SCHEMA_VERSION) {\n errors.push(`unsupported schemaVersion: ${String(value.schemaVersion)}`);\n }\n\n for (const field of SCANNER_LIMITS_V2_NUMERIC_FIELDS) {\n if (!Object.prototype.hasOwnProperty.call(value, field)) {\n errors.push(`missing field: ${field}`);\n continue;\n }\n const raw = value[field];\n if (!Number.isSafeInteger(raw) || (raw as number) < 0) {\n errors.push(`${field} must be a non-negative safe integer`);\n } else if (field === 'maxDiagnostics' && (raw as number) < 1) {\n errors.push('maxDiagnostics must be at least 1');\n }\n }\n\n if (errors.length > 0) return { ok: false, errors };\n return {\n ok: true,\n limits: {\n schemaVersion: SCANNER_LIMITS_V2_SCHEMA_VERSION,\n ...Object.fromEntries(SCANNER_LIMITS_V2_NUMERIC_FIELDS.map((field) => [field, value[field]])),\n } as ScannerLimitsV2,\n };\n}\n\nexport function toWorkflowParseOptionsV2(limits: ScannerLimitsV2): {\n maxBytes: number;\n maxNodes: number;\n maxEdges: number;\n maxConnectionDepth: number;\n maxParameterDepth: number;\n maxParameterLeaves: number;\n} {\n return {\n maxBytes: limits.maxBytes,\n maxNodes: limits.maxNodes,\n maxEdges: limits.maxEdges,\n maxConnectionDepth: limits.maxConnectionDepth,\n maxParameterDepth: limits.maxParameterDepth,\n maxParameterLeaves: limits.maxParameterLeaves,\n };\n}\n", "/**\n * Locale-independent ordering for serialized artifacts.\n *\n * Relational string comparison is deliberate: it follows JavaScript's stable\n * UTF-16 code-unit ordering and does not depend on the host locale or ICU data.\n */\nexport function compareCanonicalStrings(left: string, right: string): number {\n if (left === right) return 0;\n return left < right ? -1 : 1;\n}\n", "/**\n * Provider token shapes shared by scanner classification and evidence redaction.\n *\n * Bodies are intentionally unanchored. Classifiers wrap them as complete values,\n * while redaction finds a token inside arbitrary text.\n */\nexport type ProviderTokenSurface = 'classify' | 'redact';\n\nexport type ProviderTokenProvenance =\n | { kind: 'VENDOR_DOCS'; url: string }\n | { kind: 'FIRST_PARTY'; ref: string };\n\nexport type ProviderTokenPattern = {\n kind: string;\n body: string;\n flags: '' | 'i';\n redactionBoundary?: 'start' | 'both';\n surfaces: readonly ProviderTokenSurface[];\n provenance: ProviderTokenProvenance;\n canary: { positive: string; nearMiss: string };\n};\n\nexport const PROVIDER_TOKEN_PATTERNS = [\n {\n kind: 'bearer token',\n body: 'Bearer[ \\t]+[A-Za-z0-9._~+/=-]{8,}',\n flags: 'i',\n redactionBoundary: 'start',\n surfaces: ['classify', 'redact'],\n provenance: { kind: 'VENDOR_DOCS', url: 'https://www.rfc-editor.org/rfc/rfc6750' },\n canary: { positive: 'Bearer opaque-token-value-123', nearMiss: 'Bearer short' },\n },\n {\n kind: 'basic auth',\n body: 'Basic[ \\t]+[A-Za-z0-9+/=-]{8,}',\n flags: 'i',\n redactionBoundary: 'start',\n surfaces: ['classify', 'redact'],\n provenance: { kind: 'VENDOR_DOCS', url: 'https://www.rfc-editor.org/rfc/rfc7617' },\n canary: { positive: 'Basic YWJjZGVmZw==', nearMiss: 'Basic short' },\n },\n {\n kind: 'Stripe API key',\n body: 'sk_(?:live|test)_[A-Za-z0-9_]{8,}',\n flags: '',\n surfaces: ['classify', 'redact'],\n provenance: { kind: 'VENDOR_DOCS', url: 'https://docs.stripe.com/keys' },\n canary: { positive: 'sk_live_12345678', nearMiss: 'sk_live_1234567' },\n },\n {\n kind: 'Google API key',\n body: 'AIza[0-9A-Za-z_-]{35}',\n flags: '',\n surfaces: ['classify', 'redact'],\n provenance: { kind: 'VENDOR_DOCS', url: 'https://cloud.google.com/docs/authentication/api-keys' },\n canary: { positive: `AIza${'A'.repeat(35)}`, nearMiss: `AIza${'A'.repeat(34)}` },\n },\n {\n kind: 'AWS access key',\n body: '(?:AKIA|ASIA)[0-9A-Z]{16}',\n flags: '',\n surfaces: ['classify', 'redact'],\n provenance: { kind: 'VENDOR_DOCS', url: 'https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html' },\n canary: { positive: `AKIA${'A'.repeat(16)}`, nearMiss: `AKIA${'A'.repeat(15)}` },\n },\n {\n kind: 'Slack token',\n body: 'xox[baprs]-[A-Za-z0-9-]{10,}',\n flags: '',\n surfaces: ['classify', 'redact'],\n provenance: { kind: 'VENDOR_DOCS', url: 'https://api.slack.com/authentication/token-types' },\n canary: { positive: 'xoxb-1234567890', nearMiss: 'xoxb-123456789' },\n },\n {\n kind: 'GitHub token',\n // GitHub documents token types by prefix, not complete grammars. These\n // minimum shapes are local precision heuristics informed by its examples.\n // Example bodies: https://docs.github.com/en/rest/credentials/revoke.\n // For ghs_, use GitHub's opaque matcher for stateful and stateless formats;\n // see https://github.blog/changelog/2026-05-15-github-app-installation-tokens-per-request-override-header/.\n body: '(?:(?:ghp|gho|ghu)_[A-Za-z0-9_]{36,}(?![A-Za-z0-9_.-])|ghr_[A-Za-z0-9_]{76,}(?![A-Za-z0-9_.-])|github_pat_[A-Za-z0-9]{22}_[A-Za-z0-9]{59,}(?![A-Za-z0-9_.-])|ghs_[A-Za-z0-9._-]{36,})',\n flags: '',\n surfaces: ['classify', 'redact'],\n provenance: { kind: 'VENDOR_DOCS', url: 'https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/about-authentication-to-github' },\n canary: { positive: `ghp_${'A'.repeat(36)}`, nearMiss: `ghp_${'A'.repeat(35)}` },\n },\n {\n kind: 'JWT',\n body: 'eyJ[A-Za-z0-9_-]+\\\\.[A-Za-z0-9_-]+\\\\.[A-Za-z0-9_-]+',\n flags: '',\n surfaces: ['classify', 'redact'],\n provenance: { kind: 'VENDOR_DOCS', url: 'https://www.rfc-editor.org/rfc/rfc7519' },\n canary: { positive: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJl', nearMiss: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.' },\n },\n {\n kind: 'Anthropic API key',\n body: 'sk-ant-[A-Za-z0-9_-]{20,}',\n flags: '',\n surfaces: ['classify', 'redact'],\n provenance: { kind: 'VENDOR_DOCS', url: 'https://docs.anthropic.com/en/api/getting-started' },\n canary: { positive: `sk-ant-api03-${'A'.repeat(20)}`, nearMiss: `sk-ant-api03-${'A'.repeat(13)}` },\n },\n {\n kind: 'OpenAI API key',\n body: 'sk-(?!ant-)[A-Za-z0-9_-]{20,}',\n flags: '',\n surfaces: ['classify', 'redact'],\n provenance: { kind: 'VENDOR_DOCS', url: 'https://platform.openai.com/docs/api-reference/authentication' },\n canary: { positive: `sk-proj-${'A'.repeat(20)}`, nearMiss: `sk-proj-${'A'.repeat(14)}` },\n },\n {\n kind: 'Hugging Face token',\n body: 'hf_[A-Za-z0-9]{20,}',\n flags: '',\n surfaces: ['classify', 'redact'],\n provenance: { kind: 'VENDOR_DOCS', url: 'https://huggingface.co/docs/hub/security-tokens' },\n canary: { positive: `hf_${'A'.repeat(20)}`, nearMiss: `hf_${'A'.repeat(19)}` },\n },\n {\n kind: 'Replicate API token',\n body: 'r8_[A-Za-z0-9]{37}',\n flags: '',\n surfaces: ['classify', 'redact'],\n provenance: { kind: 'VENDOR_DOCS', url: 'https://replicate.com/docs/topics/security/api-tokens' },\n canary: { positive: `r8_${'A'.repeat(37)}`, nearMiss: `r8_${'A'.repeat(36)}` },\n },\n {\n kind: 'SecureFlow API key',\n body: 'sfk_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}_[A-Za-z0-9_-]{8,16}\\\\.[A-Za-z0-9_-]{32,128}(?![A-Za-z0-9_-])',\n flags: 'i',\n redactionBoundary: 'start',\n surfaces: ['redact'],\n provenance: { kind: 'FIRST_PARTY', ref: 'src/auth/api-keys.ts:139-141' },\n canary: {\n positive: `sfk_22222222-2222-4222-8222-222222222222_AbCdEf12345.${'s'.repeat(43)}`,\n nearMiss: `sfk_22222222-2222-4222-8222-222222222222_AbCdEf12345.${'s'.repeat(31)}`,\n },\n },\n {\n kind: 'Stripe restricted key',\n body: 'rk_(?:live|test)_[A-Za-z0-9_]{8,}',\n flags: '',\n surfaces: ['classify', 'redact'],\n provenance: { kind: 'VENDOR_DOCS', url: 'https://docs.stripe.com/keys#limit-access' },\n canary: { positive: 'rk_live_12345678', nearMiss: 'rk_live_1234567' },\n },\n] as const satisfies readonly ProviderTokenPattern[];\n\nexport function classifierPattern(entry: ProviderTokenPattern): RegExp {\n return new RegExp(`^(?:${entry.body})$`, entry.flags);\n}\n\nexport function redactionPattern(entry: ProviderTokenPattern): RegExp {\n const suffix = entry.redactionBoundary === 'start' ? '' : '\\\\b';\n return new RegExp(`\\\\b(?:${entry.body})${suffix}`, `${entry.flags}g`);\n}\n", "export const REDACTED = '[REDACTED]';\n\nconst urlPattern = /\\b(?:https?|postgres(?:ql)?|mysql|mariadb|redis|rediss|mongodb(?:\\+srv)?|amqp|amqps|smtp|smtps|ftp|ftps|sftp|ssh):\\/\\/[^\\s\"'<>]+/gi;\nconst sensitiveQueryKey = /^(?:api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|id[-_ ]?token|token|secret|password|credential|authorization|client[-_ ]?secret)$/i;\nconst queryAssignment = /([?&])((?:api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|id[-_ ]?token|token|secret|password|credential|authorization|client[-_ ]?secret))=([^&#\\s]*)/gi;\nconst emailPattern = /\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b/gi;\nconst phonePattern = /(?<![\\w+])(?:\\+?\\d[\\d .()-]{7,}\\d)(?!\\w)/g;\n\nexport function redactStructuredUrlText(value: string): string {\n return redactQueryAssignments(value.replace(urlPattern, redactUrl));\n}\n\nexport function redactContextualPii(value: string): string {\n return value.replace(emailPattern, REDACTED).replace(phonePattern, REDACTED);\n}\n\nexport function isPiiContainerKey(key: string): boolean {\n return key.toLowerCase() === 'pindata' || key.toLowerCase() === 'pinneddata';\n}\n\nexport function isStickyNoteRecord(value: Record<string, unknown>): boolean {\n return value.type === 'n8n-nodes-base.stickyNote';\n}\n\nfunction redactUrl(match: string): string {\n try {\n const url = new URL(match);\n if (url.username || url.password) {\n url.username = REDACTED;\n url.password = '';\n }\n for (const [key] of url.searchParams) {\n if (sensitiveQueryKey.test(key)) url.searchParams.set(key, REDACTED);\n }\n if (url.hash) url.hash = REDACTED;\n return url.toString();\n } catch {\n // WHATWG rejects malformed hosts such as postgres://user:pass@[bad. Re-running only the\n // query rule would leave both the password and the fragment in place, so redact the\n // authority structurally and then redact the fragment exactly as the parsed path does.\n return redactQueryAssignments(redactMalformedUrl(match));\n }\n}\n\n/**\n * The authority starts after `://` and ends at the first `/`, `?`, or `#`. The last `@` before\n * that boundary separates userinfo from the host; an `@` in the path or query is therefore not\n * userinfo. This is a linear scan with no regex and no parser call, so a malformed URI cannot\n * throw.\n */\nfunction redactMalformedUrl(value: string): string {\n const schemeEnd = value.indexOf('://');\n if (schemeEnd < 0) return value;\n const authorityStart = schemeEnd + 3;\n const authorityEnd = firstIndexOf(value, authorityStart, '/?#');\n const at = value.lastIndexOf('@', authorityEnd < 0 ? value.length - 1 : authorityEnd);\n const withoutUserinfo = at < authorityStart\n ? value\n : `${value.slice(0, authorityStart)}${REDACTED}${value.slice(at)}`;\n const hash = withoutUserinfo.indexOf('#');\n return hash < 0 ? withoutUserinfo : `${withoutUserinfo.slice(0, hash)}#${REDACTED}`;\n}\n\nfunction firstIndexOf(value: string, from: number, needles: string): number {\n for (let index = from; index < value.length; index += 1) {\n if (needles.includes(value[index]!)) return index;\n }\n return -1;\n}\n\nfunction redactQueryAssignments(value: string): string {\n return value.replace(queryAssignment, (_, prefix: string, key: string) => `${prefix}${key}=${REDACTED}`);\n}\n", "import { PROVIDER_TOKEN_PATTERNS, redactionPattern } from '../provider-token-patterns';\nimport {\n REDACTED,\n isPiiContainerKey,\n isStickyNoteRecord,\n redactContextualPii,\n redactStructuredUrlText,\n} from './structured-redaction';\n\nexport type ScannerFinding = {\n policyId: string;\n title: string;\n severity: string;\n location: {\n nodeId?: string;\n nodeName?: string;\n path?: string;\n sourceSpan?: unknown;\n };\n evidence: Record<string, unknown>;\n message: string;\n explanation: string;\n whyItMatters: string;\n possibleImpact: string;\n remediation: string;\n remediationSteps: string[];\n confidence: string;\n};\n\nconst sensitiveKeyPatterns = [\n /authorization/i, /^auth$/i, /api[-_ ]?key/i, /access[-_ ]?token/i,\n /refresh[-_ ]?token/i, /id[-_ ]?token/i, /token$/i, /secret/i, /password/i,\n /passwd/i, /^pass(?:phrase)?$/i, /^pwd$/i, /credential/i, /cookie/i,\n /private[-_ ]?key/i, /client[-_ ]?secret/i,\n];\nconst PAIRED_SENSITIVE_FIELDS: Readonly<Record<string, true>> = {\n value: true, val: true, headervalue: true, content: true,\n};\n// `redactionPattern` already returns a global (`/g`, `/gi`) matcher, so compile each pattern once\n// here instead of rebuilding an equivalent RegExp on every call, pattern and string.\nconst sensitiveValueMatchers = PROVIDER_TOKEN_PATTERNS\n .filter((entry) => entry.surfaces.some((surface) => surface === 'redact'))\n .map(redactionPattern);\n\nexport function redactFinding(finding: ScannerFinding): ScannerFinding {\n return {\n ...finding,\n title: redactText(finding.title),\n location: {\n nodeId: redactOptionalText(finding.location.nodeId),\n nodeName: redactOptionalText(finding.location.nodeName),\n path: redactOptionalText(finding.location.path),\n },\n evidence: redactEvidence(finding.evidence),\n message: redactText(finding.message),\n explanation: redactText(finding.explanation),\n whyItMatters: redactText(finding.whyItMatters),\n possibleImpact: redactText(finding.possibleImpact),\n remediation: redactText(finding.remediation),\n remediationSteps: finding.remediationSteps.map(redactText),\n };\n}\n\nexport function redactEvidence<T>(value: T): T {\n return redactValue(value, undefined, false) as T;\n}\n\nexport function redactWorkflowJson(raw: string): string {\n return JSON.stringify(redactValue(JSON.parse(raw), undefined, false));\n}\n\nexport function redactText(value: string): string {\n return sensitiveValueMatchers.reduce((redacted, matcher) => {\n // The matcher is module-scope and stateful (`/g`), so reset its cursor before every use; a\n // leaked `lastIndex` would make a later call skip the match at the stale offset.\n matcher.lastIndex = 0;\n return redacted.replace(matcher, REDACTED);\n }, redactStructuredUrlText(value));\n}\n\nfunction redactValue(value: unknown, key: string | undefined, piiContext: boolean): unknown {\n if (isSensitiveKey(key)) return REDACTED;\n if (typeof value === 'string') {\n const redacted = redactText(value);\n return piiContext ? redactContextualPii(redacted) : redacted;\n }\n if (Array.isArray(value)) return value.map((child) => redactValue(child, undefined, piiContext));\n if (!isRecord(value)) return value;\n return redactRecord(value, piiContext);\n}\n\nfunction redactRecord(value: Record<string, unknown>, piiContext: boolean): Record<string, unknown> {\n const sensitiveName = getSensitiveNameValue(value);\n const nextPiiContext = piiContext || isStickyNoteRecord(value);\n return Object.fromEntries(Object.entries(value).map(([key, child]) => [\n key,\n sensitiveName !== null && PAIRED_SENSITIVE_FIELDS[key.toLowerCase()] === true\n ? REDACTED\n : redactValue(child, key, nextPiiContext || isPiiContainerKey(key)),\n ]));\n}\n\nfunction getSensitiveNameValue(value: Record<string, unknown>): string | null {\n const name = value.name;\n return typeof name === 'string' && isSensitiveKey(name.trim()) ? name.trim() : null;\n}\n\nfunction isSensitiveKey(key: string | undefined): boolean {\n return Boolean(key && key !== 'secretKind' && sensitiveKeyPatterns.some((pattern) => pattern.test(key)));\n}\n\nfunction redactOptionalText(value: string | undefined): string | undefined {\n return value === undefined ? undefined : redactText(value);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n", "import type { CanonicalScanFinding, ScanFinding } from '../policy/policy';\nimport type { RuleCatalogEntry } from '../policy/rule-catalog';\nimport { redactFinding } from '../redaction/redaction';\n\nexport type CanonicalizeFindingsOptions = {\n /** The first `legacyFindingCount` entries are not subject to the analyzer cap. */\n legacyFindingCount?: number;\n maxAnalyzerFindings?: number;\n ambiguousNodeIds?: ReadonlySet<string>;\n};\n\nexport type CanonicalFindingsResult = {\n findings: CanonicalScanFinding[];\n rejectedCount: number;\n collapsedCount: number;\n};\n\n/** Validates, deduplicates, redacts, and stamps the effect of each finding. */\nexport function canonicalizeFindings(\n findings: unknown[],\n ruleCatalog: readonly RuleCatalogEntry[],\n options: CanonicalizeFindingsOptions = {},\n): CanonicalFindingsResult {\n const effectsByPolicyId = new Map(ruleCatalog.map((rule) => [rule.policyId, rule.policyEffect]));\n const canonicalFindings: CanonicalScanFinding[] = [];\n const seen = new Set<string>();\n const legacyFindingCount = Math.max(0, Math.min(options.legacyFindingCount ?? findings.length, findings.length));\n const maxAnalyzerFindings = options.maxAnalyzerFindings ?? Number.POSITIVE_INFINITY;\n let analyzerFindingCount = 0;\n let rejectedCount = 0;\n let collapsedCount = 0;\n\n for (const [index, value] of findings.entries()) {\n try {\n if (!isScanFinding(value) || hasCycle(value)) {\n rejectedCount += 1;\n continue;\n }\n\n const finding = value;\n const ambiguous = finding.location.nodeId !== undefined &&\n options.ambiguousNodeIds?.has(finding.location.nodeId);\n const key = ambiguous ? undefined : createMergeKey(finding);\n if (key !== undefined && seen.has(key)) {\n collapsedCount += 1;\n continue;\n }\n\n const isAnalyzerFinding = index >= legacyFindingCount;\n if (isAnalyzerFinding && analyzerFindingCount >= maxAnalyzerFindings) continue;\n\n const redacted = redactFinding(finding);\n canonicalFindings.push({\n ...redacted,\n severity: finding.severity,\n confidence: finding.confidence,\n location: {\n nodeId: redacted.location.nodeId,\n nodeName: redacted.location.nodeName,\n path: redacted.location.path,\n },\n policyEffect: effectsByPolicyId.get(finding.policyId) ?? 'LEGACY_SCORE',\n });\n if (key !== undefined) seen.add(key);\n if (isAnalyzerFinding) analyzerFindingCount += 1;\n } catch {\n rejectedCount += 1;\n }\n }\n\n return { findings: canonicalFindings, rejectedCount, collapsedCount };\n}\n\nfunction createMergeKey(finding: ScanFinding): string | undefined {\n try {\n return stableSerialize({\n policyId: finding.policyId,\n title: finding.title,\n severity: finding.severity,\n location: finding.location,\n evidence: finding.evidence,\n message: finding.message,\n explanation: finding.explanation,\n whyItMatters: finding.whyItMatters,\n possibleImpact: finding.possibleImpact,\n remediation: finding.remediation,\n remediationSteps: finding.remediationSteps,\n confidence: finding.confidence,\n });\n } catch {\n return undefined;\n }\n}\n\nfunction stableSerialize(value: unknown, seen = new Set<object>()): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (typeof value === 'string') return `string:${JSON.stringify(value)}`;\n if (typeof value === 'boolean') return `boolean:${value}`;\n if (typeof value === 'number') {\n if (Number.isNaN(value)) return 'number:NaN';\n if (Object.is(value, -0)) return 'number:-0';\n return `number:${value}`;\n }\n if (typeof value === 'bigint') return `bigint:${value}`;\n if (typeof value !== 'object') throw new Error('Unsupported merge-key value');\n if (seen.has(value)) throw new Error('Cyclic merge-key value');\n seen.add(value);\n const serialized = Array.isArray(value)\n ? `[${value.map((entry) => stableSerialize(entry, seen)).join(',')}]`\n : `{${Object.keys(value).sort().map((key) =>\n `${JSON.stringify(key)}:${stableSerialize((value as Record<string, unknown>)[key], seen)}`).join(',')}}`;\n seen.delete(value);\n return serialized;\n}\n\nfunction isScanFinding(value: unknown): value is ScanFinding {\n return isRecord(value) && isString(value.policyId) && isString(value.title) &&\n isSeverity(value.severity) && isLocation(value.location) && isRecord(value.evidence) &&\n ['message', 'explanation', 'whyItMatters', 'possibleImpact', 'remediation'].every(\n (key) => isString(value[key]),\n ) && isStringArray(value.remediationSteps) && isConfidence(value.confidence);\n}\n\nfunction hasCycle(value: unknown, ancestors = new Set<object>()): boolean {\n if (typeof value !== 'object' || value === null) return false;\n if (ancestors.has(value)) return true;\n ancestors.add(value);\n const cyclic = Array.isArray(value)\n ? value.some((entry) => hasCycle(entry, ancestors))\n : Object.keys(value).some((key) => hasCycle((value as Record<string, unknown>)[key], ancestors));\n ancestors.delete(value);\n return cyclic;\n}\n\nfunction isLocation(value: unknown): boolean {\n return isRecord(value) && ['nodeId', 'nodeName', 'path'].every(\n (key) => value[key] === undefined || isString(value[key]),\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every(isString);\n}\n\nfunction isSeverity(value: unknown): boolean {\n return value === 'CRITICAL' || value === 'HIGH' || value === 'MEDIUM' || value === 'LOW' || value === 'INFO';\n}\n\nfunction isConfidence(value: unknown): boolean {\n return value === 'LOW' || value === 'MEDIUM' || value === 'HIGH';\n}\n", "import type { AnalysisDiagnostic, AnalysisDiagnosticCode, AnalysisStatus } from '../policy/policy';\n\n/** Every diagnostic must be reviewed as either a degraded or required-stage omission. */\nexport const ANALYSIS_DIAGNOSTIC_COMPLETENESS: Record<\n AnalysisDiagnosticCode,\n 'DEGRADED' | 'INDETERMINATE'\n> = {\n ANALYSIS_LIMIT_EXCEEDED: 'DEGRADED',\n SOURCE_SPAN_UNAVAILABLE: 'DEGRADED',\n DUPLICATE_JSON_KEY: 'DEGRADED',\n MALFORMED_NODE_PARAMETERS: 'INDETERMINATE',\n UNSUPPORTED_CODE_NODE_VARIANT: 'DEGRADED',\n JAVASCRIPT_PARSE_FAILED: 'DEGRADED',\n JAVASCRIPT_SOURCE_UNAVAILABLE: 'DEGRADED',\n PYTHON_SOURCE_UNAVAILABLE: 'DEGRADED',\n PYTHON_PARSE_FAILED: 'DEGRADED',\n PYTHON_PARSER_UNAVAILABLE: 'DEGRADED',\n EXPRESSION_PARSE_FAILED: 'DEGRADED',\n POLICY_EXECUTION_FAILED: 'INDETERMINATE',\n GRAPH_ANALYSIS_DEGRADED: 'DEGRADED',\n DUPLICATE_FINDING_COLLAPSED: 'DEGRADED',\n UNCLASSIFIED_CONNECTION_TYPE: 'DEGRADED',\n // A malformed connection target index drops one edge from an otherwise-usable graph \u2014\n // the same class of graph-structural omission as GRAPH_ANALYSIS_DEGRADED (e.g. an\n // unresolved connection target), so it is graded the same way rather than as\n // INDETERMINATE (reserved for cases like MALFORMED_NODE_PARAMETERS/\n // POLICY_EXECUTION_FAILED where a whole unit of analysis could not run at all).\n MALFORMED_CONNECTION_INDEX: 'DEGRADED',\n // A required stage that could not run at all leaves the result without the evidence that\n // stage exists to produce, so the grade is suppressed (INDETERMINATE) rather than reported\n // over a scan of unknown coverage \u2014 unlike the cosmetic omissions above.\n REQUIRED_STAGE_FAILURE: 'INDETERMINATE',\n};\n\nexport function classifyAnalysisStatus(diagnostics: readonly AnalysisDiagnostic[]): AnalysisStatus {\n if (diagnostics.length === 0) return 'COMPLETE';\n return diagnostics.some(\n (diagnostic) => ANALYSIS_DIAGNOSTIC_COMPLETENESS[diagnostic.code] === 'INDETERMINATE',\n ) ? 'INDETERMINATE' : 'DEGRADED';\n}\n\n/**\n * Failure-vs-omission ladder \u2014 the frozen v1 engine LOGIC contract, declared once for every v1\n * surface (the browser engine and the pipeline CLI both call `asRequiredStageFailure`).\n *\n * These analyzer diagnostics state a *failure*, not a bounded omission: the analyzer that the\n * hardened profile configures to read a unit could not read it at all (unreadable source,\n * unparseable source, an unparseable expression, a code-node variant the scanner does not\n * analyse). The coverage claim rests on that stage, so its loss leaves the scan without the\n * evidence the stage exists to produce, and v1 has no per-diagnostic requiredness flag the way v2\n * does (`classifyDiagnostic` is fixed-row for this class, so the emitter chooses the code). Each\n * one is therefore emitted as the Slice-0 `REQUIRED_STAGE_FAILURE` code, which v1 grades\n * INDETERMINATE, so the grade is suppressed rather than reported over unknown coverage.\n *\n * Cosmetic omissions keep their own DEGRADED-class codes and stay graded: unavailable source\n * spans, duplicate JSON keys, unclassified connection labels, graph-shape omissions\n * (`GRAPH_ANALYSIS_DEGRADED`, `MALFORMED_CONNECTION_INDEX`) and analyzer caps\n * (`ANALYSIS_LIMIT_EXCEEDED`) are bounded losses the scan still scores.\n */\nexport const REQUIRED_STAGE_FAILURES: Readonly<Partial<Record<AnalysisDiagnosticCode, true>>> = {\n EXPRESSION_PARSE_FAILED: true,\n JAVASCRIPT_PARSE_FAILED: true,\n JAVASCRIPT_SOURCE_UNAVAILABLE: true,\n PYTHON_PARSER_UNAVAILABLE: true,\n PYTHON_PARSE_FAILED: true,\n PYTHON_SOURCE_UNAVAILABLE: true,\n UNSUPPORTED_CODE_NODE_VARIANT: true,\n};\n\n/** Emits the explicit failure code for a stage that could not read its unit, keeping where. */\nexport function asRequiredStageFailure(diagnostic: AnalysisDiagnostic): AnalysisDiagnostic {\n return REQUIRED_STAGE_FAILURES[diagnostic.code] === true\n ? { ...diagnostic, code: 'REQUIRED_STAGE_FAILURE', category: 'POLICY' }\n : diagnostic;\n}\n", "import type { NormalizedWorkflow } from '../workflow';\nimport type { AnalysisDiagnostic } from '../policy/policy';\n\nexport type AnalysisDiagnosticsInput = {\n workflow: NormalizedWorkflow;\n analyzerDiagnostics: readonly AnalysisDiagnostic[];\n spanUnresolvedCount: number;\n policyRejectedCount: number;\n policyFailedCount: number;\n findingCollapsedCount: number;\n scanCapExceeded: boolean;\n};\n\n/** Converts stage-level omissions into the versioned diagnostic vocabulary. */\nexport function collectAnalysisDiagnostics(input: AnalysisDiagnosticsInput): AnalysisDiagnostic[] {\n const diagnostics: AnalysisDiagnostic[] = [...input.analyzerDiagnostics];\n if (input.workflow.graph.diagnostics.length > 0) {\n diagnostics.push({ code: 'GRAPH_ANALYSIS_DEGRADED', category: 'GRAPH' });\n }\n if (input.workflow.graph.views.unknown.length > 0) {\n diagnostics.push({ code: 'UNCLASSIFIED_CONNECTION_TYPE', category: 'GRAPH' });\n }\n for (const diagnostic of input.workflow.graph.diagnostics) {\n if (diagnostic.code === 'MALFORMED_CONNECTION_INDEX') {\n diagnostics.push({ code: diagnostic.code, category: 'GRAPH', location: { path: diagnostic.pointer } });\n }\n }\n if (input.spanUnresolvedCount > 0) {\n diagnostics.push({ code: 'SOURCE_SPAN_UNAVAILABLE', category: 'SOURCE' });\n }\n if (input.workflow.parseDiagnostics.some(({ code }) => code === 'DUPLICATE_JSON_KEY')) {\n diagnostics.push({ code: 'DUPLICATE_JSON_KEY', category: 'SOURCE' });\n }\n for (const diagnostic of input.workflow.parseDiagnostics) {\n if (diagnostic.code === 'MALFORMED_NODE_PARAMETERS') {\n diagnostics.push({ code: diagnostic.code, category: 'SOURCE', location: { path: diagnostic.pointer } });\n }\n }\n if (input.policyRejectedCount > 0 || input.policyFailedCount > 0) {\n diagnostics.push({ code: 'POLICY_EXECUTION_FAILED', category: 'POLICY' });\n }\n if (input.findingCollapsedCount > 0) {\n diagnostics.push({ code: 'DUPLICATE_FINDING_COLLAPSED', category: 'POLICY' });\n }\n if (input.scanCapExceeded) {\n diagnostics.push({ code: 'ANALYSIS_LIMIT_EXCEEDED', category: 'LIMIT' });\n }\n return diagnostics;\n}\n", "export type ExpressionIslandV2 = Readonly<{\n kind: 'LITERAL' | 'EXPRESSION';\n start: number;\n end: number;\n}>;\n\nconst MAX_LEXER_STACK_DEPTH = 256;\n\ntype Frame =\n | { kind: 'EXPRESSION' | 'TEMPLATE_EXPRESSION'; braces: number }\n | { kind: 'TEMPLATE' | 'SINGLE' | 'DOUBLE' };\n\nconst literal = (start: number, end: number): ExpressionIslandV2 => Object.freeze({ kind: 'LITERAL', start, end });\nconst expression = (start: number, end: number): ExpressionIslandV2 => Object.freeze({ kind: 'EXPRESSION', start, end });\n\n/** Segment n8n expression islands without evaluating or exposing their contents. */\nexport function segmentExpressionIslands(value: string): readonly ExpressionIslandV2[] {\n if (typeof value !== 'string' || value.length === 0) return Object.freeze([]);\n const segments: ExpressionIslandV2[] = [];\n let cursor = 0;\n while (cursor < value.length) {\n const open = value.indexOf('{{', cursor);\n if (open < 0) break;\n if (open > cursor) segments.push(literal(cursor, open));\n const end = scanIsland(value, open + 2);\n segments.push(expression(open, end));\n cursor = end;\n if (end >= value.length) break;\n }\n if (cursor < value.length) segments.push(literal(cursor, value.length));\n if (segments.length === 0) segments.push(literal(0, value.length));\n return Object.freeze(segments);\n}\n\nfunction scanIsland(source: string, start: number): number {\n const frames: Frame[] = [{ kind: 'EXPRESSION', braces: 0 }];\n let index = start;\n while (index < source.length && frames.length > 0) {\n const frame = frames[frames.length - 1];\n const character = source[index];\n if (frame.kind === 'SINGLE' || frame.kind === 'DOUBLE') {\n if (character === '\\\\') { index += 2; continue; }\n const quote = frame.kind === 'SINGLE' ? \"'\" : '\"';\n if (character === quote) frames.pop();\n index += 1;\n continue;\n }\n if (frame.kind === 'TEMPLATE') {\n if (character === '\\\\') { index += 2; continue; }\n if (character === '`') { frames.pop(); index += 1; continue; }\n if (character === '$' && source[index + 1] === '{') {\n if (frames.length >= MAX_LEXER_STACK_DEPTH) return source.length;\n frames.push({ kind: 'TEMPLATE_EXPRESSION', braces: 0 }); index += 2; continue;\n }\n index += 1;\n continue;\n }\n if (character === \"'\") { frames.push({ kind: 'SINGLE' }); index += 1; continue; }\n if (character === '\"') { frames.push({ kind: 'DOUBLE' }); index += 1; continue; }\n if (character === '`') { frames.push({ kind: 'TEMPLATE' }); index += 1; continue; }\n if (frame.kind !== 'EXPRESSION' && frame.kind !== 'TEMPLATE_EXPRESSION') {\n index += 1;\n continue;\n }\n if (character === '{') { frame.braces += 1; index += 1; continue; }\n if (character === '}') {\n if (frame.braces > 0) { frame.braces -= 1; index += 1; continue; }\n if (frame.kind === 'TEMPLATE_EXPRESSION') { frames.pop(); index += 1; continue; }\n if (source[index + 1] === '}') return index + 2;\n }\n index += 1;\n }\n return source.length;\n}\n", "import {\n PROVIDER_TOKEN_PATTERNS,\n classifierPattern,\n type ProviderTokenPattern,\n} from '../../provider-token-patterns';\n\nconst MAX_PROVIDER_TOKEN_CHARS = 4_096;\nconst wrapperPattern = /^(?:<([^>\\r\\n]{1,512})>|\\[([^\\]\\r\\n]{1,512})\\])$/;\n\nexport type ProviderTokenClassification = Readonly<{ kind: string }>;\nexport type ProviderTokenGrammar = Readonly<ProviderTokenPattern>;\n\nfunction freezeGrammar(entry: ProviderTokenPattern): ProviderTokenGrammar {\n return Object.freeze({\n ...entry,\n surfaces: Object.freeze([...entry.surfaces]),\n provenance: Object.freeze({ ...entry.provenance }),\n canary: Object.freeze({ ...entry.canary }),\n });\n}\n\n/** Reviewed provider grammars. SecureFlow's own key remains redaction-only by policy. */\nexport const PROVIDER_TOKEN_GRAMMARS_V2 = Object.freeze(\n PROVIDER_TOKEN_PATTERNS.map(freezeGrammar),\n);\n\nconst classifiedGrammars = PROVIDER_TOKEN_GRAMMARS_V2\n .filter((entry) => entry.surfaces.includes('classify'))\n .map((entry) => ({ kind: entry.kind, pattern: classifierPattern(entry) }));\n\n/** Return a provider label only when the entire value (or one reviewed wrapper) matches. */\nexport function classifyProviderToken(value: unknown): ProviderTokenClassification | undefined {\n if (typeof value !== 'string') return undefined;\n const candidate = value.trim();\n if (candidate.length === 0 || candidate.length > MAX_PROVIDER_TOKEN_CHARS) return undefined;\n\n const direct = matchClassifiedGrammar(candidate);\n if (direct) return Object.freeze({ kind: direct });\n\n const wrapper = wrapperPattern.exec(candidate);\n if (!wrapper) return undefined;\n const inner = (wrapper[1] ?? wrapper[2]).trim();\n const wrapped = matchClassifiedGrammar(inner);\n return wrapped ? Object.freeze({ kind: wrapped }) : undefined;\n}\n\nfunction matchClassifiedGrammar(value: string): string | undefined {\n let matched: string | undefined;\n for (const grammar of classifiedGrammars) {\n if (!grammar.pattern.test(value)) continue;\n if (matched !== undefined) return undefined;\n matched = grammar.kind;\n }\n return matched;\n}\n", "import { classifierPattern, PROVIDER_TOKEN_PATTERNS } from '../../provider-token-patterns';\n\nexport type PlaceholderClassificationV2 = Readonly<{\n kind: 'PLACEHOLDER';\n indicator: string;\n}>;\n\nconst MAX_PLACEHOLDER_LENGTH = 256;\nconst MAX_DYNAMIC_PROPERTY_LENGTH = 128;\nconst dynamicRootNames = new Set(['json', 'node', 'env', 'credentials', 'secrets', 'vars', 'parameter']);\nconst placeholderWords = '(?:your|my|example|sample|placeholder|dummy|test|fake|changeme|todo|insert|replace|enter|add)';\nconst placeholderNouns = '(?:api|access|auth|secret|token|key|password|credential|value|here|id|url|name)';\nconst wordPlaceholder = new RegExp(`^${placeholderWords}(?:[\\\\s_-]+(?:${placeholderWords}|${placeholderNouns}))*$`, 'i');\nconst nounPlaceholder = new RegExp(`^${placeholderNouns}(?:[\\\\s_-]+(?:${placeholderWords}|${placeholderNouns}))*$`, 'i');\nconst wrappedPlaceholder = /^<([^>\\r\\n]{1,256})>$/;\nconst bracketPlaceholder = /^\\[([^\\]\\r\\n]{1,256})\\]$/;\nconst namedPlaceholder = new RegExp(`^__(?:${placeholderWords}|${placeholderNouns})(?:[_-](?:${placeholderWords}|${placeholderNouns}))*__$`, 'i');\nconst maskPlaceholder = /^[*x._-]{3,64}$/i;\nconst classifiedProviderPatterns = PROVIDER_TOKEN_PATTERNS.filter((entry) => entry.surfaces.some((surface) => surface === 'classify'));\n\n/** Classify only complete, reviewed placeholder forms; never return the input text. */\nexport function classifyAnchoredPlaceholder(value: unknown): PlaceholderClassificationV2 | undefined {\n if (typeof value !== 'string') return undefined;\n const candidate = value.trim();\n if (candidate.length === 0 || candidate.length > MAX_PLACEHOLDER_LENGTH) return undefined;\n const angle = wrappedPlaceholder.exec(candidate);\n if (angle && isReviewedPlaceholderInner(angle[1]) && !isProviderToken(angle[1])) return Object.freeze({ kind: 'PLACEHOLDER', indicator: 'ANGLE_WRAPPED' });\n const square = bracketPlaceholder.exec(candidate);\n if (square && isReviewedPlaceholderInner(square[1]) && !isProviderToken(square[1])) return Object.freeze({ kind: 'PLACEHOLDER', indicator: 'SQUARE_WRAPPED' });\n const indicator = namedPlaceholder.test(candidate)\n ? 'NAMED_PLACEHOLDER'\n : maskPlaceholder.test(candidate)\n ? 'MASK'\n : isDynamicRootPlaceholder(candidate)\n ? 'DYNAMIC_ROOT'\n : wordPlaceholder.test(candidate) || nounPlaceholder.test(candidate)\n ? 'PLACEHOLDER_WORD'\n : undefined;\n return indicator === undefined ? undefined : Object.freeze({ kind: 'PLACEHOLDER', indicator });\n}\n\nfunction isReviewedPlaceholderInner(value: string): boolean {\n return namedPlaceholder.test(value) || maskPlaceholder.test(value) || isDynamicRootPlaceholder(value)\n || wordPlaceholder.test(value) || nounPlaceholder.test(value);\n}\n\nfunction isProviderToken(value: string): boolean {\n return classifiedProviderPatterns.some((entry) => classifierPattern(entry).test(value));\n}\n\nfunction isDynamicRootPlaceholder(value: string): boolean {\n if (value.length > MAX_PLACEHOLDER_LENGTH) return false;\n let cursor = value.startsWith('$') ? 1 : 0;\n const rootStart = cursor;\n while (cursor < value.length && isDynamicIdentifierPart(value[cursor])) cursor += 1;\n if (!dynamicRootNames.has(value.slice(rootStart, cursor).toLowerCase())) return false;\n\n while (cursor < value.length) {\n if (value[cursor] === '.') {\n cursor += 1;\n if (cursor >= value.length || !isDynamicIdentifierStart(value[cursor])) return false;\n cursor += 1;\n while (cursor < value.length && isDynamicIdentifierPart(value[cursor])) cursor += 1;\n continue;\n }\n if (value[cursor] !== '[') return false;\n const quote = value[cursor + 1];\n if (quote !== '\"' && quote !== \"'\") return false;\n cursor += 2;\n const propertyStart = cursor;\n let escaped = false;\n while (cursor < value.length) {\n const character = value[cursor];\n if (character === '\\r' || character === '\\n') return false;\n if (escaped) {\n escaped = false;\n } else if (character === '\\\\') {\n escaped = true;\n } else if (character === quote) {\n break;\n }\n cursor += 1;\n }\n if (cursor >= value.length || cursor - propertyStart === 0 || cursor - propertyStart > MAX_DYNAMIC_PROPERTY_LENGTH) return false;\n if (value[cursor + 1] !== ']') return false;\n cursor += 2;\n }\n return true;\n}\n\nfunction isDynamicIdentifierStart(character: string): boolean {\n return character === '$' || character === '_' || isAsciiLetter(character);\n}\n\nfunction isDynamicIdentifierPart(character: string): boolean {\n return isDynamicIdentifierStart(character) || isAsciiDigit(character);\n}\n\nfunction isAsciiLetter(character: string): boolean {\n const code = character.charCodeAt(0);\n return code >= 65 && code <= 90 || code >= 97 && code <= 122;\n}\n\nfunction isAsciiDigit(character: string): boolean {\n const code = character.charCodeAt(0);\n return code >= 48 && code <= 57;\n}\n", "import { segmentExpressionIslands } from './analyzers/expression/expression-islands';\nimport { classifyAnchoredPlaceholder } from './analyzers/expression/placeholder-classifier';\nimport { classifyProviderToken } from './analyzers/secrets/provider-token-registry';\n\nconst MAX_SECRET_VALUE_CHARS = 4_096;\nexport const MAX_SECRET_INDICATORS = 10;\nconst opaqueSecretSyntax = /^[A-Za-z0-9~+/=_!$.-]{20,512}$/;\nconst sensitiveContext = /(?:api[-_ ]?key|token|secret|password|credential|authorization|cookie)/i;\n\nexport type SecretClassification = Readonly<{ kind: string }>;\nexport type LiteralClassification = Readonly<{\n classification?: SecretClassification;\n indicatorCount: number;\n omitted: boolean;\n}>;\n\n/**\n * Classifies bounded literal values without returning their contents. Expression code is not\n * evaluated; complete provider tokens in quoted string values are classified, while each\n * surrounding literal is considered independently.\n */\nexport function classifySecretValue(\n value: string,\n contextKey?: string,\n): SecretClassification | undefined {\n if (typeof value !== 'string') return undefined;\n const candidate = value.trim();\n if (candidate.length === 0 || candidate.length > MAX_SECRET_VALUE_CHARS) return undefined;\n return classifyLiteralSegments(candidate, contextKey).classification;\n}\n\nexport function classifyLiteralSegments(value: string, contextKey?: string): LiteralClassification {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_SECRET_VALUE_CHARS) {\n return Object.freeze({ classification: undefined, indicatorCount: 0, omitted: false });\n }\n // n8n marks expression mode with a leading `=`; the marker is not part of the value.\n const body = value.startsWith('=') ? value.slice(1) : value;\n let classification: SecretClassification | undefined;\n let indicatorCount = 0;\n let omitted = false;\n for (const segment of segmentExpressionIslands(body)) {\n if (segment.kind === 'EXPRESSION') {\n const found: SecretClassification[] = [];\n collectQuotedExpressionTokens(body, segment.start, segment.end, found);\n for (const providerClassification of found) {\n if (indicatorCount >= MAX_SECRET_INDICATORS) { omitted = true; continue; }\n indicatorCount += 1;\n classification ??= providerClassification;\n }\n continue;\n }\n if (segment.end <= segment.start) continue;\n const found = classifyLiteral(body.slice(segment.start, segment.end), contextKey);\n if (found === undefined) continue;\n if (indicatorCount >= MAX_SECRET_INDICATORS) { omitted = true; continue; }\n indicatorCount += 1;\n classification ??= found;\n }\n return Object.freeze({ classification, indicatorCount, omitted });\n}\n\n/**\n * Classifies complete provider tokens inside single- or double-quoted string values of n8n\n * expressions. The expression is never evaluated; unquoted template-literal text and quoted\n * property names are not scanned, and escape sequences are not decoded (the raw two-character\n * escape is kept, so an escaped fragment cannot be spliced into a token).\n */\nexport function classifyQuotedExpressionTokens(value: string): readonly SecretClassification[] {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_SECRET_VALUE_CHARS) {\n return Object.freeze([]);\n }\n const classifications: SecretClassification[] = [];\n for (const segment of segmentExpressionIslands(value)) {\n if (segment.kind !== 'EXPRESSION') continue;\n collectQuotedExpressionTokens(value, segment.start, segment.end, classifications);\n if (classifications.length >= MAX_SECRET_INDICATORS) break;\n }\n return Object.freeze(classifications);\n}\n\nfunction collectQuotedExpressionTokens(\n source: string,\n start: number,\n end: number,\n output: SecretClassification[],\n): void {\n let index = start;\n while (index < end && output.length < MAX_SECRET_INDICATORS) {\n const quote = source[index];\n if (quote !== '\"' && quote !== \"'\") { index += 1; continue; }\n const opening = index;\n let literal = '';\n index += 1;\n while (index < end) {\n const character = source[index];\n if (character === '\\\\') {\n // Keep the backslash with its escaped character: dropping it turns `\\n` into `n` and\n // can splice two fragments into a provider token the runtime never holds.\n if (index + 1 < end) literal += source.slice(index, index + 2);\n index += 2;\n continue;\n }\n if (character === quote) break;\n literal += character;\n index += 1;\n }\n const closing = index;\n const closed = closing < end && source[closing] === quote;\n index += 1;\n if (!closed || isQuotedPropertyName(source, opening, closing, start, end)) continue;\n const classification = classifyProviderToken(literal);\n if (classification) output.push(classification);\n }\n}\n\nfunction isQuotedPropertyName(\n source: string,\n opening: number,\n closing: number,\n start: number,\n end: number,\n): boolean {\n const previous = previousNonWhitespace(source, opening - 1, start);\n const next = nextNonWhitespace(source, closing + 1, end);\n if (next === ':' && (previous === '{' || previous === ',')) return true;\n if (previous !== '[') return false;\n const owner = previousNonWhitespace(source, opening - 2, start);\n return owner !== undefined && /[A-Za-z0-9_$.)\\].'\"`]/.test(owner);\n}\n\nfunction previousNonWhitespace(source: string, index: number, lowerBound: number): string | undefined {\n for (let cursor = index; cursor >= lowerBound; cursor -= 1) {\n if (!/\\s/.test(source[cursor])) return source[cursor];\n }\n return undefined;\n}\n\nfunction nextNonWhitespace(source: string, index: number, upperBound: number): string | undefined {\n for (let cursor = index; cursor < upperBound; cursor += 1) {\n if (!/\\s/.test(source[cursor])) return source[cursor];\n }\n return undefined;\n}\n\nfunction classifyLiteral(value: string, contextKey?: string): SecretClassification | undefined {\n const candidate = value.trim();\n if (candidate.length === 0 || isDynamicReference(candidate)) return undefined;\n const provider = classifyProviderToken(candidate);\n if (provider) return provider;\n if (classifyAnchoredPlaceholder(candidate)) return undefined;\n if (!contextKey || !sensitiveContext.test(contextKey) || !opaqueSecretSyntax.test(candidate)) return undefined;\n return shannonEntropy(candidate) >= 3.5 ? Object.freeze({ kind: 'opaque secret' }) : undefined;\n}\n\nfunction isDynamicReference(value: string): boolean {\n return value.includes('${') || value.startsWith('=');\n}\n\nfunction shannonEntropy(value: string): number {\n const counts = new Map<string, number>();\n for (const character of value) counts.set(character, (counts.get(character) ?? 0) + 1);\n return [...counts.values()].reduce((entropy, count) => {\n const probability = count / value.length;\n return entropy - probability * Math.log2(probability);\n }, 0);\n}\n", "import type { FindingConfidence, NormalizedWorkflowNode, ScanFinding, ScanSeverity } from './policy';\nimport { segmentExpressionIslands } from '../analyzers/expression/expression-islands';\nimport { classifyProviderToken } from '../analyzers/secrets/provider-token-registry';\nimport { classifyQuotedExpressionTokens } from '../secret-classifier';\n\nexport type SecretIndicator = {\n path: string;\n kind: string;\n indicator: 'sensitive_key' | 'sensitive_value';\n hasLiteralValue: boolean;\n};\n\n/** n8n runtime references, which make a surrounding literal a template rather than raw material. */\nconst RUNTIME_REFERENCE =\n /\\$(?:json|node|nodeVersion|env|credentials|secrets|vars|parameter|execution|workflow|item|items|thisItem|input|binary|now|today|prevNode|runIndex|position|jmespath|if|loop|max|min|randomInt|request|response|body|data|pageCount|itemIndex|self|evaluateExpression|getWorkflowStaticData)\\b/i;\n\ntype LiteralIslands = Readonly<{ literals: string[]; templated: boolean }>;\n\nconst PLACEHOLDER_PREFIXES = new Set([\n 'your', 'my', 'example', 'sample', 'placeholder', 'dummy', 'test', 'fake', 'changeme',\n 'todo', 'insert', 'replace', 'enter', 'add',\n]);\nconst PLACEHOLDER_WORDS = [\n ...PLACEHOLDER_PREFIXES, 'api', 'access', 'auth', 'secret', 'token', 'key', 'password', 'here', 'value',\n].sort((left, right) => right.length - left.length);\n\n/**\n * Splits a parameter value into the literal text it ships verbatim. n8n marks expression mode\n * with a leading `=` and evaluates `{{ \u2026 }}` islands at runtime, so both are stripped.\n */\nfunction literalIslands(value: string): LiteralIslands {\n const body = value.startsWith('=') ? value.slice(1) : value;\n const segments = segmentExpressionIslands(body);\n const literals = segments\n .filter((segment) => segment.kind === 'LITERAL' && segment.end > segment.start)\n .map((segment) => body.slice(segment.start, segment.end))\n .filter((island) => island.trim().length > 0);\n return { literals, templated: segments.some((segment) => segment.kind === 'EXPRESSION') };\n}\n\n/**\n * Public RFC 7235 authentication-scheme tokens. A scheme-only literal island is protocol text,\n * not credential material; any additional literal text keeps the fail-closed result.\n */\nconst AUTH_SCHEME_ONLY = /^(?:bearer|basic|digest|negotiate|hoba|mutual|token)$/i;\n\n/** Expressions and conventional placeholders are not literal secret material. */\nexport function isNonSecretLiteral(value: string): boolean {\n const candidate = value.trim();\n if (candidate.length === 0) return true;\n if (classifyProviderToken(candidate) !== undefined) return false;\n if (classifyQuotedExpressionTokens(candidate).length > 0) return false;\n const { literals } = literalIslands(candidate);\n // Only expression-mode text may hide a literal behind a runtime-reference token; an unmarked\n // value such as `mySecret $json` is still literal text this workflow ships.\n const expressionMode = candidate.startsWith('=');\n const raw = literals.filter((island) => !(expressionMode && RUNTIME_REFERENCE.test(island)));\n if (raw.length === 0) return true;\n const material = raw.filter((island) => !AUTH_SCHEME_ONLY.test(island.trim()));\n return material.every(isPlaceholderLiteral);\n}\n\n/** Conventional placeholder forms that never carry secret material. */\nfunction isPlaceholderLiteral(candidate: string): boolean {\n const trimmed = candidate.trim();\n if (trimmed.length === 0) return true;\n if (/^\\$?(json|node|env|credentials|secrets|vars|parameter)\\b/i.test(trimmed)) return true;\n if (/^[*x._-]+$/i.test(trimmed)) return true;\n if (/^<[^>]*>$/.test(trimmed) || /^\\[[^\\]]*\\]$/.test(trimmed)) return true;\n return isPlaceholderPhrase(trimmed.toLowerCase());\n}\n\n/** Match the small placeholder vocabulary in one forward pass without nested quantifiers. */\nfunction isPlaceholderPhrase(value: string): boolean {\n let offset = 0;\n let firstWord = true;\n\n while (offset < value.length) {\n if (!firstWord) {\n while (offset < value.length && isPlaceholderSeparator(value[offset])) offset += 1;\n if (offset === value.length) return false;\n }\n\n const word = PLACEHOLDER_WORDS.find((candidate) => value.startsWith(candidate, offset));\n if (!word || (firstWord && !PLACEHOLDER_PREFIXES.has(word))) return false;\n offset += word.length;\n firstWord = false;\n }\n\n return !firstWord;\n}\n\nfunction isPlaceholderSeparator(character: string | undefined): boolean {\n return character === '_' || character === '-' || (character !== undefined && /\\s/.test(character));\n}\n\nexport function nodeFinding(input: {\n policyId: string;\n title?: string;\n severity: ScanSeverity;\n node: NormalizedWorkflowNode;\n evidence: Record<string, unknown>;\n message: string;\n explanation?: string;\n whyItMatters?: string;\n possibleImpact?: string;\n remediation: string;\n remediationSteps?: string[];\n confidence?: FindingConfidence;\n}): ScanFinding {\n return {\n policyId: input.policyId,\n title: input.title ?? input.message,\n severity: input.severity,\n location: { nodeId: input.node.id, nodeName: input.node.name },\n evidence: input.evidence,\n message: input.message,\n explanation: input.explanation ?? input.message,\n whyItMatters: input.whyItMatters ?? 'This issue can change the trust boundary, data exposure, or operational behavior of the workflow.',\n possibleImpact: input.possibleImpact ?? 'The workflow may be harder to review, monitor, or operate safely without additional controls.',\n remediation: input.remediation,\n remediationSteps: input.remediationSteps ?? [input.remediation],\n confidence: input.confidence ?? 'MEDIUM',\n };\n}\n\nexport function authorizationHeaderEvidence(value: unknown): { present: boolean; literal: boolean } {\n if (Array.isArray(value)) {\n return value.reduce<{ present: boolean; literal: boolean }>((result, child) => {\n const nested = authorizationHeaderEvidence(child);\n return { present: result.present || nested.present, literal: result.literal || nested.literal };\n }, { present: false, literal: false });\n }\n\n if (!isRecord(value)) return { present: false, literal: false };\n let present = false;\n let literal = false;\n const name = typeof value.name === 'string' ? value.name.trim().toLowerCase() : '';\n for (const [key, child] of Object.entries(value)) {\n if (key.trim().toLowerCase() === 'authorization') {\n present = true;\n if (typeof child === 'string' && !isNonSecretLiteral(child)) literal = true;\n }\n if (typeof child === 'string' && child.trim().toLowerCase() === 'authorization') present = true;\n const nested = authorizationHeaderEvidence(child);\n present = present || nested.present;\n literal = literal || nested.literal;\n }\n if (name === 'authorization') {\n present = true;\n for (const key of ['value', 'val', 'headerValue', 'content'] as const) {\n const paired = value[key];\n if (typeof paired === 'string' && !isNonSecretLiteral(paired)) literal = true;\n }\n }\n return { present, literal };\n}\n\nexport function collectUrls(value: unknown): URL[] {\n if (Array.isArray(value)) return value.flatMap(collectUrls);\n if (isRecord(value)) return Object.values(value).flatMap(collectUrls);\n if (typeof value !== 'string') return [];\n return literalIslands(value).literals.flatMap(parseHttpUrl);\n}\n\nfunction parseHttpUrl(value: string): URL[] {\n try {\n const url = new URL(value);\n return url.protocol === 'https:' || url.protocol === 'http:' ? [url] : [];\n } catch {\n return [];\n }\n}\n\n// The pinned n8n-nodes-base@2.15.1 Webhook description offers exactly these three\n// authenticated modes (plus `none`). `oauth2` is not an option in that version, so it\n// must not be treated as authenticated; the corrected probe and plan-owned sidecar use\n// this pinned enum.\n//\n// `validateWebhookAuthentication` (dist/nodes/Webhook/utils.js:205-289) compares the stored\n// value with strict equality, never trims or case-folds it, and has no final `else`, so an\n// unknown value fails open at runtime. Only an exact match may suppress WEBHOOK_EXPOSURE.\nconst AUTHENTICATED_WEBHOOK_METHODS: Readonly<Record<string, true>> = {\n basicAuth: true, headerAuth: true, jwtAuth: true,\n};\n\nexport function hasWebhookAuthentication(parameters: Record<string, unknown>): boolean {\n const authentication = parameters.authentication;\n return typeof authentication === 'string'\n && AUTHENTICATED_WEBHOOK_METHODS[authentication] === true;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n", "import type { ScanPolicy } from '../policy/policy';\nimport { collectUrls, nodeFinding } from '../policy/policy-helpers';\n\nexport function createUnapprovedDomainPolicy(approvedDomains: readonly string[]): ScanPolicy {\n const approved = new Set(approvedDomains.map((domain) => domain.toLowerCase()));\n\n return {\n id: 'UNAPPROVED_DOMAIN',\n name: 'Unapproved external domain',\n description: 'Flags external URLs outside the configured domain allowlist.',\n evaluate(workflow) {\n if (approved.size === 0) return [];\n\n return workflow.nodes.flatMap((node) =>\n uniqueDomains(node.parameters)\n .filter((domain) => !approved.has(domain))\n .map((domain) => nodeFinding({\n policyId: 'UNAPPROVED_DOMAIN',\n title: 'External domain is outside the approved allowlist',\n severity: 'MEDIUM',\n node,\n evidence: { domain },\n message: 'This workflow calls a domain outside the approved allowlist.',\n explanation:\n 'The node parameters contain a URL whose hostname is not present in the approved domain list supplied for this scan.',\n whyItMatters:\n 'Unexpected outbound domains can indicate data exfiltration, shadow integrations, or environment drift.',\n possibleImpact:\n 'Workflow data may be sent to an unreviewed third party or an endpoint that is not covered by enterprise controls.',\n remediation: 'Add the domain to the approved list or replace the external call.',\n remediationSteps: [\n 'Confirm the business owner and purpose for the external domain.',\n 'Add the domain to the approved list only after security and compliance review.',\n 'Replace the call if the destination is unnecessary or untrusted.',\n ],\n confidence: 'HIGH',\n })),\n );\n },\n };\n}\n\nfunction uniqueDomains(value: unknown): string[] {\n const domains = collectUrls(value).map((url) => url.hostname.toLowerCase());\n return domains.filter((domain, index) => domains.indexOf(domain) === index);\n}\n", "import { classifyProviderToken } from '../analyzers/secrets/provider-token-registry';\nimport { classifySecretValue } from '../secret-classifier';\nimport { isNonSecretLiteral } from '../policy/policy-helpers';\n\nexport type SecretIndicator = {\n path: string;\n kind: string;\n indicator: 'sensitive_key' | 'sensitive_value';\n hasLiteralValue: boolean;\n};\n\nexport function collectSecretIndicators(\n value: unknown,\n path = 'parameters',\n contextKey?: string,\n): SecretIndicator[] {\n if (Array.isArray(value)) {\n return value.flatMap((child, index) => collectSecretIndicators(child, `${path}[${index}]`, contextKey));\n }\n\n if (!isRecord(value)) {\n const classification = typeof value === 'string'\n ? classifyProviderToken(value) ?? classifySecretValue(value, contextKey)\n : undefined;\n return classification\n ? [{ path, kind: classification.kind, indicator: 'sensitive_value', hasLiteralValue: true }]\n : [];\n }\n\n return Object.entries(value).flatMap(([key, child]) => {\n const childPath = `${path}.${key}`;\n const keyKind = secretKindFromKey(key);\n const suppressed = typeof child === 'string' && isNonSecretLiteral(child);\n const nested = collectSecretIndicators(child, childPath, key);\n const valueAlreadyReported = nested.some(\n (indicator) => indicator.path === childPath && indicator.indicator === 'sensitive_value',\n );\n const keyFinding = keyKind && !suppressed && !valueAlreadyReported\n ? [{\n path: childPath,\n kind: keyKind,\n indicator: 'sensitive_key' as const,\n hasLiteralValue: typeof child === 'string' && child.trim().length > 0,\n }]\n : [];\n return [...keyFinding, ...nested];\n });\n}\n\n/**\n * n8n fields that name credential *plumbing* \u2014 which credential, or which credential type, a\n * node uses \u2014 rather than credential material, so a key named like one of them is not itself a\n * secret indicator. The comparison is a whole, case-insensitive key name, so a parameter key\n * that merely contains \"credential\" (for example `credentialName`) keeps being classified.\n *\n * - `credentials`: n8n's credential reference block (`INode.credentials`, typed\n * `INodeCredentials` = `{ [credentialType]: { id, name } }`; n8n `packages/workflow/src/interfaces.ts`).\n * Its value is a reference to the credential store, never the stored secret.\n * - `nodeCredentialType`: the credential *type* selector (the HTTP Request node's \"Predefined\n * Credential Type\" field), whose value is a credential type name such as `todoistApi` or\n * `openAiApi`.\n *\n * These keys are skipped only for the key-name signal: their children are still traversed, so a\n * literal secret nested inside a reference block is still reported as `sensitive_value`.\n */\nconst CREDENTIAL_PLUMBING_KEYS: Readonly<Record<string, true>> = {\n credentials: true,\n nodecredentialtype: true,\n};\n\nfunction secretKindFromKey(key: string): string | null {\n const normalized = key.toLowerCase();\n if (CREDENTIAL_PLUMBING_KEYS[normalized] === true) return null;\n if (normalized.includes('apikey') || normalized.includes('api_key') || normalized.includes('api-key')) return 'api key';\n if (normalized.includes('password') || normalized.includes('passwd')) return 'password';\n if (normalized.includes('token')) return 'token';\n if (normalized.includes('secret')) return 'secret';\n if (normalized.includes('credential')) return 'credential';\n if (normalized === 'authorization' || normalized === 'cookie') return normalized;\n return null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n", "import type { ScanPolicy } from '../policy/policy';\nimport {\n authorizationHeaderEvidence,\n isNonSecretLiteral,\n nodeFinding,\n} from '../policy/policy-helpers';\nimport { collectSecretIndicators } from './secret-indicators';\n\nexport const rawSecretIndicatorPolicy: ScanPolicy = {\n id: 'RAW_SECRET_INDICATOR',\n name: 'Raw secret indicator',\n description: 'Flags workflow parameters that look like embedded secrets.',\n evaluate(workflow) {\n return workflow.nodes.flatMap((node) =>\n collectSecretIndicators(node.parameters).slice(0, 10).map((indicator) => nodeFinding({\n policyId: 'RAW_SECRET_INDICATOR',\n title:\n indicator.indicator === 'sensitive_value'\n ? 'Workflow parameters contain raw secret material'\n : 'Workflow parameter is named like a secret',\n severity:\n indicator.indicator === 'sensitive_value'\n ? 'HIGH'\n : indicator.hasLiteralValue\n ? 'MEDIUM'\n : 'LOW',\n node,\n evidence: {\n parameterPath: indicator.path,\n secretKind: indicator.kind,\n indicator: indicator.indicator,\n hasLiteralValue: indicator.hasLiteralValue,\n },\n message: 'This node contains a parameter that looks like a raw secret.',\n explanation:\n 'The scanner found a parameter key or value pattern commonly used for tokens, passwords, API keys, cookies, or credentials.',\n whyItMatters:\n 'Raw secrets in workflow JSON can be exposed through exports, scan history, logs, backups, or support bundles.',\n possibleImpact:\n 'An exposed token or password can allow unauthorized access to connected systems even if the workflow itself is not malicious.',\n remediation:\n 'Move the value into n8n credentials or an approved secret manager, then rotate any exposed secret.',\n remediationSteps: [\n 'Move the raw value into n8n credentials or an approved secret manager.',\n 'Rotate the secret if it has already been exported, shared, or stored in history.',\n 'Re-scan the workflow after replacing the raw value with a managed credential reference.',\n ],\n confidence: indicator.indicator === 'sensitive_key' ? 'MEDIUM' : 'HIGH',\n })),\n );\n },\n};\n\nexport const rawAuthorizationHeaderPolicy: ScanPolicy = {\n id: 'RAW_AUTH_HEADER',\n name: 'Raw Authorization header',\n description: 'Flags manually configured Authorization headers.',\n evaluate(workflow) {\n return workflow.nodes\n .map((node) => ({ node, evidence: authorizationHeaderEvidence(node.parameters) }))\n .filter((candidate) => candidate.evidence.present)\n .map(({ node, evidence }) => nodeFinding({\n policyId: 'RAW_AUTH_HEADER',\n title: evidence.literal\n ? 'Raw Authorization header may expose credentials'\n : 'Authorization header is set from an expression',\n severity: evidence.literal ? 'HIGH' : 'INFO',\n node,\n evidence: { header: 'Authorization', literalValue: evidence.literal },\n message: 'This node configures a raw Authorization header.',\n explanation:\n 'The workflow parameters appear to define an Authorization header directly instead of using managed n8n credentials.',\n whyItMatters:\n 'Raw credential material in node parameters is easier to copy, persist, log, or expose in exported workflow JSON.',\n possibleImpact:\n 'API keys or bearer tokens can be leaked through workflow exports, scan history, logs, or support bundles.',\n remediation: 'Use n8n credentials or a managed secret reference instead of raw headers.',\n remediationSteps: [\n 'Move the secret into n8n credentials or an approved secret manager.',\n 'Rotate any token that has already been stored in raw workflow JSON.',\n 'Re-scan after replacing the raw header with a managed credential reference.',\n ],\n confidence: 'MEDIUM',\n }));\n },\n};\n\nexport { isNonSecretLiteral };\n", "import type { ScanPolicy } from '../policy/policy';\nimport { nodeFinding } from '../policy/policy-helpers';\n\nexport const executeCommandPolicy: ScanPolicy = {\n id: 'N8N_EXECUTE_COMMAND',\n name: 'Execute Command node',\n description: 'Flags shell command execution from n8n workflows.',\n evaluate(workflow) {\n return workflow.nodes\n .filter((node) => node.type === 'n8n-nodes-base.executeCommand')\n .map((node) => nodeFinding({\n policyId: 'N8N_EXECUTE_COMMAND',\n title: 'Execute Command node can run shell commands',\n severity: 'CRITICAL',\n node,\n evidence: { nodeType: node.type },\n message: 'This workflow can execute shell commands.',\n explanation:\n 'The Execute Command node allows the workflow to launch shell commands from the n8n runtime environment.',\n whyItMatters:\n 'Shell command access can cross from workflow automation into the host or worker environment that runs n8n.',\n possibleImpact:\n 'A malicious or compromised workflow path could lead to command execution, file access, lateral movement, or service disruption.',\n remediation: 'Remove the Execute Command node or isolate it behind strict approval.',\n remediationSteps: [\n 'Remove the Execute Command node when shell access is not explicitly required.',\n 'Replace shell logic with a narrow, reviewed integration or managed service call.',\n 'If it must remain, isolate the workflow runner and require manual approval before execution.',\n ],\n confidence: 'HIGH',\n }));\n },\n};\n\nconst codeNodeTypes = new Set([\n 'n8n-nodes-base.code',\n 'n8n-nodes-base.function',\n 'n8n-nodes-base.functionItem',\n '@n8n/n8n-nodes-langchain.code',\n '@n8n/n8n-nodes-langchain.toolCode',\n]);\n\nexport const codeNodePolicy: ScanPolicy = {\n id: 'N8N_CODE_NODE',\n name: 'Code node',\n description: 'Flags JavaScript, legacy Function, and LangChain code nodes.',\n evaluate(workflow) {\n return workflow.nodes\n .filter((node) => codeNodeTypes.has(node.type))\n .map((node) => nodeFinding({\n policyId: 'N8N_CODE_NODE',\n title: 'Custom code node requires security review',\n severity: 'LOW',\n node,\n evidence: { nodeType: node.type },\n message: 'This workflow contains custom script execution.',\n explanation:\n 'Code and legacy Function nodes can transform data with arbitrary JavaScript inside the workflow runtime.',\n whyItMatters:\n 'Custom code is harder to audit than declarative node configuration and may handle secrets or external data.',\n possibleImpact:\n 'Unsafe code can leak data, mishandle credentials, or create behavior that reviewers cannot understand from node settings alone.',\n remediation: 'Review the code path, remove unnecessary scripting, and require approval.',\n remediationSteps: [\n 'Review the node source code for secret access, outbound requests, and unsafe parsing.',\n 'Move repeatable logic into a reviewed service or reusable library when possible.',\n 'Require approval for changes to custom code nodes in production workflows.',\n ],\n confidence: 'HIGH',\n }));\n },\n};\n", "import type { ScanPolicy } from '../policy/policy';\nimport { hasWebhookAuthentication, nodeFinding } from '../policy/policy-helpers';\n\nconst officialNodeNamespaces = ['n8n-nodes-base.', '@n8n/'];\n\nexport const unknownNodePackagePolicy: ScanPolicy = {\n id: 'UNKNOWN_NODE_PACKAGE',\n name: 'Unknown node package',\n description: 'Flags nodes that do not come from an official n8n package namespace.',\n evaluate(workflow) {\n const seen = new Set<string>();\n return workflow.nodes\n .filter((node) => !officialNodeNamespaces.some((namespace) => node.type.startsWith(namespace)))\n .filter((node) => {\n const packageName = node.type.split('.')[0] ?? node.type;\n if (seen.has(packageName)) return false;\n seen.add(packageName);\n return true;\n })\n .map((node) => nodeFinding({\n policyId: 'UNKNOWN_NODE_PACKAGE',\n title: 'Node package is not from an official n8n namespace',\n severity: 'LOW',\n node,\n evidence: { nodeType: node.type, nodePackage: node.type.split('.')[0] ?? node.type },\n message: 'This workflow uses a community or custom node package.',\n explanation:\n 'The node type does not start with an official n8n package namespace, so it comes from a community or custom package.',\n whyItMatters:\n 'Community and custom packages can add supply-chain, maintenance, and permission risks that differ from core nodes.',\n possibleImpact:\n 'A vulnerable or unmaintained package could process sensitive workflow data or run unexpected code.',\n remediation: 'Review the package source, version, permissions, and maintenance status.',\n remediationSteps: [\n 'Verify the package source, maintainer, and version history.',\n 'Check whether the node requires credentials or broad runtime permissions.',\n 'Pin approved versions and remove packages that are not actively maintained.',\n ],\n confidence: 'MEDIUM',\n }));\n },\n};\n\nexport const webhookExposurePolicy: ScanPolicy = {\n id: 'WEBHOOK_EXPOSURE',\n name: 'Webhook exposure',\n description: 'Flags webhook triggers without clear authentication markers.',\n evaluate(workflow) {\n return workflow.nodes\n .filter((node) => node.type === 'n8n-nodes-base.webhook')\n .filter((node) => !hasWebhookAuthentication(node.parameters))\n .map((node) => nodeFinding({\n policyId: 'WEBHOOK_EXPOSURE',\n title: 'Webhook trigger lacks clear authentication',\n severity: 'MEDIUM',\n node,\n evidence: { authentication: node.parameters.authentication ?? null },\n message: 'This webhook does not show a clear authentication marker.',\n explanation:\n 'The webhook node appears to accept inbound requests without an explicit authentication mode in the workflow parameters.',\n whyItMatters:\n 'Unauthenticated inbound endpoints can be abused for spam, data injection, or unexpected workflow execution.',\n possibleImpact:\n 'External callers may trigger automations, create records, or send data into connected systems without authorization.',\n remediation: 'Require webhook authentication or place the endpoint behind trusted controls.',\n remediationSteps: [\n 'Enable webhook authentication in n8n when the endpoint is not intentionally public.',\n 'Place the endpoint behind a gateway, allowlist, or rate limiter for production use.',\n 'Monitor webhook usage for unexpected request volume or payloads.',\n ],\n confidence: 'MEDIUM',\n }));\n },\n};\n", "import type { ScanPolicy } from '../policy/policy';\nimport { createUnapprovedDomainPolicy } from './domain-policy';\nimport { rawAuthorizationHeaderPolicy, rawSecretIndicatorPolicy } from './credential-policies';\nimport { codeNodePolicy, executeCommandPolicy } from './execution-policies';\nimport { unknownNodePackagePolicy, webhookExposurePolicy } from './package-and-webhook-policies';\n\nexport type BetaPolicyOptions = {\n approvedDomains?: readonly string[];\n};\n\nexport function createBetaDefaultPolicies(options: BetaPolicyOptions = {}): ScanPolicy[] {\n return [\n executeCommandPolicy,\n codeNodePolicy,\n rawAuthorizationHeaderPolicy,\n rawSecretIndicatorPolicy,\n createUnapprovedDomainPolicy(options.approvedDomains ?? []),\n unknownNodePackagePolicy,\n webhookExposurePolicy,\n ];\n}\n", "/** Locale-independent UTF-16 ordering for deterministic scanner output. */\nexport function compareCanonicalStrings(left: string, right: string): number {\n if (left === right) return 0;\n return left < right ? -1 : 1;\n}\n", "import type { NormalizedWorkflowNode } from './workflow';\nimport { compareCanonicalStrings } from './stable-order';\n\nexport type WorkflowComplexity = 'LOW' | 'MEDIUM' | 'HIGH';\n\nexport type WorkflowIntegration = {\n service: string;\n nodeTypes: string[];\n nodeCount: number;\n usage: string;\n riskNotes: string[];\n};\n\nconst serviceLabels: Record<string, string> = {\n code: 'Code',\n executeCommand: 'Execute Command',\n function: 'Function',\n functionItem: 'Function Item',\n httpRequest: 'HTTP Request',\n manualTrigger: 'Manual Trigger',\n scheduleTrigger: 'Schedule Trigger',\n slack: 'Slack',\n webhook: 'Webhook',\n};\n\nexport function summarizeIntegrations(nodes: NormalizedWorkflowNode[]): WorkflowIntegration[] {\n const byService = new Map<string, NormalizedWorkflowNode[]>();\n\n for (const node of nodes) {\n const service = serviceNameFromType(node.type);\n byService.set(service, [...(byService.get(service) ?? []), node]);\n }\n\n return [...byService.entries()]\n .map(([service, serviceNodes]) => ({\n service,\n nodeTypes: unique(serviceNodes.map((node) => node.type)),\n nodeCount: serviceNodes.length,\n usage: usageForService(service, serviceNodes),\n riskNotes: riskNotesForService(service, serviceNodes),\n }))\n .sort((left, right) => compareCanonicalStrings(left.service, right.service));\n}\n\nexport function classifyComplexity(\n nodeCount: number,\n connectionCount: number,\n integrationCount: number,\n): WorkflowComplexity {\n if (nodeCount >= 15 || connectionCount >= 20 || integrationCount >= 8) {\n return 'HIGH';\n }\n\n if (nodeCount >= 6 || connectionCount >= 8 || integrationCount >= 4) {\n return 'MEDIUM';\n }\n\n return 'LOW';\n}\n\nexport function complexityWeight(complexity: WorkflowComplexity): number {\n switch (complexity) {\n case 'HIGH':\n return 20;\n case 'MEDIUM':\n return 10;\n case 'LOW':\n return 0;\n }\n}\n\n/** Shared with app-only trigger prose so service labels cannot drift. */\nexport function serviceNameFromType(type: string): string {\n const compactType = compactNodeType(type);\n return serviceLabels[compactType] ?? titleCase(splitCamelCase(compactType));\n}\n\nfunction compactNodeType(type: string): string {\n const segments = type.split('.');\n return segments[segments.length - 1] ?? type;\n}\n\nfunction usageForService(service: string, nodes: NormalizedWorkflowNode[]): string {\n if (service === 'Webhook') return 'Receives external HTTP requests into the workflow.';\n if (service === 'HTTP Request') return 'Calls external HTTP APIs or internal web services.';\n if (service === 'Slack') return 'Sends or manages Slack workspace messages and notifications.';\n if (service === 'Execute Command') return 'Runs operating-system commands from a workflow node.';\n if (service === 'Code' || service === 'Function' || service === 'Function Item') {\n return 'Runs custom JavaScript logic inside the workflow.';\n }\n return `Uses ${nodes.length} ${service} node(s) in the workflow.`;\n}\n\nfunction riskNotesForService(service: string, nodes: NormalizedWorkflowNode[]): string[] {\n if (service === 'Execute Command') return ['Can run shell commands on the n8n host or worker environment.'];\n if (service === 'HTTP Request') return ['Can send workflow data to external URLs configured in node parameters.'];\n if (service === 'Webhook') return ['Can expose an inbound endpoint that may need authentication and rate limits.'];\n if (service === 'Code' || service === 'Function' || service === 'Function Item') {\n return ['Custom code should be reviewed for secret handling and data exfiltration.'];\n }\n return nodes.some((node) => !node.type.startsWith('n8n-nodes-base.'))\n ? ['This integration comes from a non-core or community package namespace.']\n : [];\n}\n\nfunction titleCase(value: string): string {\n return value\n .split(' ')\n .filter(Boolean)\n .map((word) => `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`)\n .join(' ');\n}\n\nfunction splitCamelCase(value: string): string {\n return value.replace(/([a-z0-9])([A-Z])/g, '$1 $2');\n}\n\nfunction unique(values: string[]): string[] {\n return values.filter((value, index) => values.indexOf(value) === index);\n}\n", "import type { NormalizedWorkflow, NormalizedWorkflowNode } from './workflow';\nimport {\n classifyComplexity,\n serviceNameFromType,\n summarizeIntegrations,\n type WorkflowComplexity,\n type WorkflowIntegration,\n} from './workflow-insights';\n\nexport type WorkflowRiskGrade = 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';\n\nexport type WorkflowOverview = {\n name: string | null;\n nodeCount: number;\n rawNodeCount: number;\n annotationNodeCount: number;\n triggerCount: number;\n actionCount: number;\n integrationCount: number;\n connectionCount: number;\n payloadBytes: number;\n complexity: WorkflowComplexity;\n isSubWorkflow: boolean;\n};\n\nexport type WorkflowFunctionSummary = {\n basicPurpose: string;\n triggerDescription: string;\n dataFlowSummary: string;\n businessCategory:\n | 'MANUAL_AUTOMATION'\n | 'WEBHOOK_API'\n | 'SCHEDULED_AUTOMATION'\n | 'DATA_SYNC'\n | 'NOTIFICATION'\n | 'CUSTOM_LOGIC'\n | 'GENERAL_AUTOMATION';\n confidence: 'LOW' | 'MEDIUM' | 'HIGH';\n};\n\nexport type WorkflowInsights = {\n workflow: WorkflowOverview;\n functionSummary: WorkflowFunctionSummary;\n integrations: WorkflowIntegration[];\n};\n\nexport type WorkflowRiskAssessment = {\n score: number;\n grade: WorkflowRiskGrade;\n topRisks: string[];\n dataExposure: string;\n complexityDrivers: string[];\n};\n\nconst triggerHints = ['trigger', 'webhook', 'cron', 'schedule', 'formtrigger', 'manualtrigger'];\n\n/** Builds the browser and CLI workflow description from the same pure contract. */\nexport function analyzeWorkflowInsights(workflow: NormalizedWorkflow): WorkflowInsights {\n const nodes = functionalNodes(workflow.nodes);\n const integrations = summarizeIntegrations(nodes);\n const triggerCount = nodes.filter(isTriggerNode).length;\n const nodeCount = nodes.length;\n const connectionCount = workflow.graph.edges.length;\n const overview: WorkflowOverview = {\n name: workflow.name ?? null,\n nodeCount,\n rawNodeCount: workflow.nodeCount,\n annotationNodeCount: workflow.nodeCount - nodeCount,\n triggerCount,\n actionCount: Math.max(nodeCount - triggerCount, 0),\n integrationCount: integrations.length,\n connectionCount,\n payloadBytes: workflow.payloadBytes,\n complexity: classifyComplexity(nodeCount, connectionCount, integrations.length),\n isSubWorkflow: isSubWorkflow(workflow.nodes),\n };\n\n return {\n workflow: overview,\n functionSummary: summarizeFunction(nodes, overview, integrations),\n integrations,\n };\n}\n\nfunction summarizeFunction(\n nodes: NormalizedWorkflowNode[],\n overview: WorkflowOverview,\n integrations: WorkflowIntegration[],\n): WorkflowFunctionSummary {\n const triggers = nodes.filter(isTriggerNode).map((node) => serviceNameFromType(node.type));\n const services = integrations\n .filter((integration) => !integration.service.toLowerCase().includes('trigger'))\n .slice(0, 3)\n .map((integration) => integration.service);\n const prefix = isWebhookWorkflow(nodes)\n ? 'Webhook-triggered workflow'\n : isScheduledWorkflow(nodes)\n ? 'Scheduled workflow'\n : overview.triggerCount > 0\n ? 'Manual workflow'\n : 'Workflow';\n\n return {\n basicPurpose: `${prefix} with ${overview.nodeCount} node(s) that ${services.length > 0 ? `uses ${formatList(services)}` : 'does not use a recognized external service'}.`,\n triggerDescription: triggers.length > 0\n ? `Triggered by ${formatList(unique(triggers))}.`\n : 'No explicit trigger node was detected.',\n dataFlowSummary: overview.connectionCount > 0\n ? `The workflow has ${overview.connectionCount} configured connection(s) linking ${overview.nodeCount} node(s).`\n : 'No explicit node-to-node connections were found in the workflow JSON.',\n businessCategory: categorizeWorkflow(nodes, integrations),\n confidence: overview.nodeCount > 1 ? 'MEDIUM' : 'LOW',\n };\n}\n\nfunction isTriggerNode(node: NormalizedWorkflowNode): boolean {\n return triggerHints.some((hint) => compactNodeType(node.type).toLowerCase().includes(hint));\n}\n\nfunction isWebhookWorkflow(nodes: NormalizedWorkflowNode[]): boolean {\n return nodes.some((node) => compactNodeType(node.type).toLowerCase().includes('webhook'));\n}\n\nfunction isScheduledWorkflow(nodes: NormalizedWorkflowNode[]): boolean {\n return nodes.some((node) => {\n const type = compactNodeType(node.type).toLowerCase();\n return type.includes('schedule') || type.includes('cron');\n });\n}\n\nfunction categorizeWorkflow(\n nodes: NormalizedWorkflowNode[],\n integrations: WorkflowIntegration[],\n): WorkflowFunctionSummary['businessCategory'] {\n if (isWebhookWorkflow(nodes)) return 'WEBHOOK_API';\n if (isScheduledWorkflow(nodes)) return 'SCHEDULED_AUTOMATION';\n if (integrations.some((integration) => integration.service === 'Slack')) return 'NOTIFICATION';\n if (integrations.some((integration) => integration.service === 'HTTP Request')) return 'DATA_SYNC';\n if (integrations.some((integration) => integration.service === 'Code')) return 'CUSTOM_LOGIC';\n if (nodes.some((node) => compactNodeType(node.type) === 'manualTrigger')) return 'MANUAL_AUTOMATION';\n return 'GENERAL_AUTOMATION';\n}\n\nfunction isSubWorkflow(nodes: NormalizedWorkflowNode[]): boolean {\n const triggers = nodes.filter(isTriggerLikeType);\n return triggers.length > 0 && triggers.every(\n (node) => compactNodeType(node.type).toLowerCase() === 'executeworkflowtrigger',\n );\n}\n\nfunction isTriggerLikeType(node: NormalizedWorkflowNode): boolean {\n return triggerHints.some((hint) => compactNodeType(node.type).toLowerCase().includes(hint));\n}\n\nfunction functionalNodes(nodes: NormalizedWorkflowNode[]): NormalizedWorkflowNode[] {\n return nodes.filter((node) => !['stickynote', 'noop'].includes(compactNodeType(node.type).toLowerCase()));\n}\n\nfunction compactNodeType(type: string): string {\n const segments = type.split('.');\n return segments[segments.length - 1] ?? type;\n}\n\nfunction formatList(values: string[]): string {\n if (values.length <= 1) return values[0] ?? '';\n if (values.length === 2) return `${values[0]} and ${values[1]}`;\n return `${values.slice(0, -1).join(', ')}, and ${values[values.length - 1]}`;\n}\n\nfunction unique(values: string[]): string[] {\n return values.filter((value, index) => values.indexOf(value) === index);\n}\n", "import type { RawWorkflowEdge, WorkflowGraphViews } from './workflow-graph';\n\nconst EXECUTION_TYPES = new Set(['main']);\nconst CAPABILITY_TYPES = new Set(['ai_tool']);\nconst CONTEXT_TYPES = new Set([\n 'ai_document',\n 'ai_embedding',\n 'ai_languageModel',\n 'ai_memory',\n 'ai_outputParser',\n 'ai_retriever',\n 'ai_reranker',\n 'ai_textSplitter',\n 'ai_vectorStore',\n]);\n\n/** Classify edges only when their connection type has been reviewed. */\nexport function deriveGraphViews(edges: readonly RawWorkflowEdge[]): WorkflowGraphViews {\n return {\n execution: edges.filter((edge) => EXECUTION_TYPES.has(edge.connectionType)),\n capability: edges.filter((edge) => CAPABILITY_TYPES.has(edge.connectionType)),\n context: edges.filter((edge) => CONTEXT_TYPES.has(edge.connectionType)),\n unknown: edges.filter((edge) => !EXECUTION_TYPES.has(edge.connectionType)\n && !CAPABILITY_TYPES.has(edge.connectionType)\n && !CONTEXT_TYPES.has(edge.connectionType)),\n };\n}\n", "export function toJsonPointer(segments: Array<string | number>): string {\n return `/${segments.map((segment) => escapeJsonPointerSegment(String(segment))).join('/')}`;\n}\n\nexport function escapeJsonPointerSegment(segment: string): string {\n return segment.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n", "import { deriveGraphViews } from './workflow-graph-views';\nimport { toJsonPointer } from './json-pointer';\n\nexport type WorkflowGraphDiagnostic =\n | {\n code:\n | 'UNKNOWN_CONNECTION_SOURCE'\n | 'AMBIGUOUS_CONNECTION_SOURCE'\n | 'UNKNOWN_CONNECTION_TARGET'\n | 'AMBIGUOUS_CONNECTION_TARGET'\n | 'MALFORMED_CONNECTION_ENTRY';\n }\n // The target `index` was present but not a finite non-negative integer (e.g. -1, 1.5,\n // NaN, a numeric string, or an object). Rejected rather than coerced: a coerced index\n // would silently change which taint edges hardened analysis can see. `pointer` locates\n // the offending `index` value in the source connections object.\n | { code: 'MALFORMED_CONNECTION_INDEX'; pointer: string };\n\nexport type RawWorkflowEdge = {\n ordinal: number;\n connectionType: string;\n fromNodeIndex: number;\n fromOutputIndex: number;\n toNodeIndex: number;\n toInputIndex: number;\n};\n\nexport type WorkflowGraphViews = {\n execution: RawWorkflowEdge[];\n capability: RawWorkflowEdge[];\n context: RawWorkflowEdge[];\n unknown: RawWorkflowEdge[];\n};\n\nexport type WorkflowGraph = {\n edges: RawWorkflowEdge[];\n views: WorkflowGraphViews;\n diagnostics: WorkflowGraphDiagnostic[];\n limitExceeded: boolean;\n};\n\nexport function buildWorkflowGraph(\n nodes: ReadonlyArray<{ name: string }>,\n connections: Record<string, unknown>,\n options: { maxEdges?: number } = {},\n): WorkflowGraph {\n const maxEdges = options.maxEdges ?? Infinity;\n const nodeIndexesByName = indexesByName(nodes);\n const edges: RawWorkflowEdge[] = [];\n const diagnostics: WorkflowGraphDiagnostic[] = [];\n\n for (const [sourceName, byType] of Object.entries(connections)) {\n const fromNodeIndex = resolveIndex(nodeIndexesByName, sourceName, diagnostics, 'SOURCE');\n if (fromNodeIndex === undefined) continue;\n if (!isRecord(byType)) {\n diagnostics.push({ code: 'MALFORMED_CONNECTION_ENTRY' });\n continue;\n }\n\n for (const [connectionType, outputs] of Object.entries(byType)) {\n if (!Array.isArray(outputs)) {\n diagnostics.push({ code: 'MALFORMED_CONNECTION_ENTRY' });\n continue;\n }\n for (const [fromOutputIndex, targets] of outputs.entries()) {\n if (targets === null || targets === undefined) continue;\n if (!Array.isArray(targets)) {\n diagnostics.push({ code: 'MALFORMED_CONNECTION_ENTRY' });\n continue;\n }\n\n for (const [targetIndex, target] of targets.entries()) {\n if (edges.length >= maxEdges) {\n return { edges, views: deriveGraphViews(edges), diagnostics, limitExceeded: true };\n }\n if (!isRecord(target) || typeof target.node !== 'string') {\n diagnostics.push({ code: 'MALFORMED_CONNECTION_ENTRY' });\n continue;\n }\n\n const toNodeIndex = resolveIndex(nodeIndexesByName, target.node, diagnostics, 'TARGET');\n if (toNodeIndex === undefined) continue;\n\n const toInputIndex = resolveTargetInputIndex(target.index);\n if (toInputIndex === undefined) {\n diagnostics.push({\n code: 'MALFORMED_CONNECTION_INDEX',\n pointer: toJsonPointer(['connections', sourceName, connectionType, fromOutputIndex, targetIndex, 'index']),\n });\n continue;\n }\n\n edges.push({\n ordinal: edges.length,\n connectionType,\n fromNodeIndex,\n fromOutputIndex,\n toNodeIndex,\n toInputIndex,\n });\n }\n }\n }\n }\n\n return { edges, views: deriveGraphViews(edges), diagnostics, limitExceeded: false };\n}\n\nfunction resolveIndex(\n nodeIndexesByName: Map<string, number[]>,\n name: string,\n diagnostics: WorkflowGraphDiagnostic[],\n end: 'SOURCE' | 'TARGET',\n): number | undefined {\n const indexes = nodeIndexesByName.get(name);\n if (!indexes) {\n diagnostics.push({ code: end === 'SOURCE' ? 'UNKNOWN_CONNECTION_SOURCE' : 'UNKNOWN_CONNECTION_TARGET' });\n return undefined;\n }\n if (indexes.length !== 1) {\n diagnostics.push({ code: end === 'SOURCE' ? 'AMBIGUOUS_CONNECTION_SOURCE' : 'AMBIGUOUS_CONNECTION_TARGET' });\n return undefined;\n }\n return indexes[0];\n}\n\nfunction indexesByName(nodes: ReadonlyArray<{ name: string }>): Map<string, number[]> {\n const result = new Map<string, number[]>();\n nodes.forEach((node, index) => result.set(node.name, [...(result.get(node.name) ?? []), index]));\n return result;\n}\n\n// A missing `index` (the key is absent from the JSON) defaults to 0, matching real n8n\n// exports that omit it for a node's sole input. Any other value must be a strict,\n// finite, non-negative integer \u2014 including a numeric string like \"0\", which is\n// rejected rather than coerced.\nfunction resolveTargetInputIndex(rawIndex: unknown): number | undefined {\n if (rawIndex === undefined) return 0;\n return typeof rawIndex === 'number' && Number.isInteger(rawIndex) && rawIndex >= 0 ? rawIndex : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n", "import type { NormalizedWorkflow, NormalizedWorkflowNode } from '../workflow';\nimport { buildWorkflowGraph } from '../workflow-graph';\nimport type { SourceValueV2 } from '../source/source-types';\nimport type { AnalyzerContextV2 } from './scheduler';\nimport type { SemanticFieldV2, SecurityNodeV2 } from '../workflow-v2/security-workflow';\n\ntype DataRecord = Record<string, unknown>;\n\nexport function toNativeWorkflow(context: AnalyzerContextV2): NormalizedWorkflow {\n const rawRoot = sourceValue(context.source.root);\n const root = record(rawRoot);\n const rawNodes = Array.isArray(root.nodes) ? root.nodes : [];\n const nodes = Array.prototype.map.call(context.workflow.nodes, (node: SecurityNodeV2) => nativeNode(node, rawNodes[node.ref.ordinal])) as NormalizedWorkflowNode[];\n const connections = record(root.connections);\n return {\n ...(typeof root.name === 'string' ? { name: root.name } : {}),\n fingerprint: context.source.rawSha256,\n payloadBytes: context.source.utf8Bytes,\n nodeCount: nodes.length,\n nodes,\n connections,\n parseDiagnostics: [],\n graph: buildWorkflowGraph(nodes, connections, { maxEdges: context.limits.maxEdges }),\n };\n}\n\nfunction nativeNode(node: SecurityNodeV2, raw: unknown): NormalizedWorkflowNode {\n const source = record(raw);\n const parameters = record(source.parameters);\n const fallback = fieldsObject(node.parameters);\n const value = Object.keys(parameters).length === 0 && node.parameters.length > 0 ? fallback : parameters;\n return {\n id: node.ref.explicitId ?? node.ref.name ?? String(node.ref.ordinal),\n name: node.ref.name ?? String(node.ref.ordinal),\n type: node.type,\n ...(node.typeVersion !== undefined ? { typeVersion: node.typeVersion } : {}),\n parameters: value,\n sourcePath: node.ref.source.pointer,\n ...(node.ref.source.span === null ? {} : { sourceSpan: {\n start: { line: node.ref.source.span.start.line, column: node.ref.source.span.start.column, offset: node.ref.source.span.start.utf16Offset },\n end: { line: node.ref.source.span.end.line, column: node.ref.source.span.end.column, offset: node.ref.source.span.end.utf16Offset },\n } }),\n };\n}\n\nfunction sourceValue(value: SourceValueV2): unknown {\n if (value.kind === 'NULL' || value.kind === 'BOOLEAN' || value.kind === 'NUMBER' || value.kind === 'STRING') return value.value;\n if (value.kind === 'ARRAY') {\n const items: unknown[] = []; for (let index = 0; index < value.items.length; index += 1) { const item = value.items[index]; if (item) items.push(sourceValue(item)); }\n return items;\n }\n const output = Object.create(null) as DataRecord;\n for (const member of value.members) output[member.name] = sourceValue(member.value);\n return output;\n}\n\nfunction record(value: unknown): DataRecord {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as DataRecord : Object.create(null) as DataRecord;\n}\n\nfunction fieldsObject(fields: readonly SemanticFieldV2[]): DataRecord {\n const output = Object.create(null) as DataRecord;\n for (let index = 0; index < fields.length; index += 1) {\n const field = fields[index]; if (field) output[fieldName(field.pointer)] = semanticValue(field.value);\n }\n return output;\n}\n\nfunction semanticValue(value: SemanticFieldV2['value']): unknown {\n if (!Array.isArray(value)) return value;\n if (value.length === 0) return [];\n const names: string[] = [];\n for (let index = 0; index < value.length; index += 1) { const field = value[index]; if (field) names.push(fieldName(field.pointer)); }\n if (names.every((name, index) => name === String(index))) {\n const items: unknown[] = []; for (let index = 0; index < value.length; index += 1) { const field = value[index]; if (field) items.push(semanticValue(field.value)); }\n return items;\n }\n const output = Object.create(null) as DataRecord;\n for (let index = 0; index < value.length; index += 1) { const field = value[index]; if (field) output[names[index] ?? String(index)] = semanticValue(field.value); }\n return output;\n}\n\nfunction fieldName(pointer: string): string {\n const segment = pointer.split('/').at(-1) ?? '';\n return segment.replaceAll('~1', '/').replaceAll('~0', '~');\n}\n", "const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers\n// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below\n// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).\nconst fromNumH = (n) => (n / 2 ** 32) | 0;\nconst fromNumL = (n) => n >>> 0;\n// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call\n// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.\nfunction setU64FromNum(view, byteOffset, n, isLE) {\n const h = fromNumH(n);\n const l = fromNumL(n);\n view.setUint32(byteOffset, isLE ? l : h, isLE);\n view.setUint32(byteOffset + 4, isLE ? h : l, isLE);\n}\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps\n// local copies so V8 inlines them into keccakP.\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };\n", "/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('expected hash wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1 || h.blockLen < 1)\n throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\n};\nconst aopts = (value, label) => {\n aobject(value, label);\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null)\n throw new TypeError(`\"${label}\" expected plain object`);\n // Object.assign() treats an own \"__proto__\" source key as a write to the target's legacy\n // prototype setter. Reject it before merging so inherited option values cannot be injected.\n if (Object.hasOwn(value, '__proto__'))\n throw new TypeError(`\"${label}.__proto__\" is not allowed`);\n};\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\n/**\n * Yields to the host task scheduler so timers, I/O, and rendering can make progress.\n * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.\n * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so\n * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while\n * still allowing other event-loop work to proceed.\n * @param onReject - optional cleanup invoked only if the host yield fails\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport function nextTick(onReject) {\n const host = globalThis;\n if (typeof host.scheduler?.yield === 'function') {\n const promise = host.scheduler.yield();\n // Keep the original scheduler rejection; this handler exists only for cleanup.\n if (onReject)\n promise.catch(onReject);\n return promise;\n }\n return new Promise((resolve) => host.setTimeout(resolve, 0));\n}\n/**\n * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @param onReject - optional cleanup invoked only if a host yield fails\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb, onReject) {\n anumber(iters, 'iters');\n anumber(tick, 'tick');\n if (typeof cb !== 'function')\n throw new TypeError('callback must be a function');\n // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick(onReject);\n // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n ts = Date.now();\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n const encoded = new TextEncoder().encode(str);\n try {\n // Copy into the current realm for Firefox extension contexts. Callers that own the returned\n // buffer can then wipe it independently of TextEncoder's temporary result.\n return new Uint8Array(encoded); // https://bugzil.la/1681809\n }\n finally {\n clean(encoded);\n }\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\n * @returns Fresh merged option object with a null prototype.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts, title = 'opts') {\n aopts(defaults, 'defaults');\n if (opts !== undefined)\n aopts(opts, title);\n // Callers read optional fields directly, so omitted values must not fall through to ambient\n // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).\n const merged = Object.assign(Object.create(null), defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n if (typeof hashCons !== 'function')\n throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n info = checkOpts({}, info, 'info');\n const hashC = (msg, opts) => hashCons(opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 \u00A710.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n let processed = false;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n processed = true;\n continue;\n }\n // When the whole input is buffered in one go (common for short messages), passing `data`\n // directly avoids allocating a subarray view.\n buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n processed = true;\n }\n }\n this.length += data.length;\n // Shared schedule buffers only pick up input-derived words inside process(); if everything\n // was buffered without processing, there is nothing to zero.\n if (processed)\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message, then zero-pad the rest of the block\n buffer[pos++] = 0b10000000;\n buffer.fill(0, pos);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n buffer.fill(0);\n }\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an\n // integer below 2**53, so the split inside the helper stays exact).\n setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n this.process(view, 0);\n // The final block above is processed outside update(), so the shared message-schedule\n // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n this.roundClean();\n // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n const oview = out === buffer ? view : createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n const outLen = len / 4;\n const state = this.get();\n // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n if (len % 4 || outLen > state.length)\n throw new Error('invalid outputLen');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneIntoMeta(to) {\n const { buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (pos)\n to.buffer.set(buffer); // Avoid a hot modulo guard.\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 \u00A76.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 \u00A76.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 \u00A75.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 \u00A76.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 \u00A76.2. */\nclass SHA2_32B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and makes sha256 3x slower (measured).\n A = 0;\n B = 0;\n C = 0;\n D = 0;\n E = 0;\n F = 0;\n G = 0;\n H = 0;\n constructor(outputLen, IV) {\n super(64, outputLen, 8, false);\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 \u00A76.2. */\nexport class _SHA256 extends SHA2_32B {\n constructor() {\n super(32, SHA256_IV);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 \u00A76.2 and \u00A78.5. */\nexport class _SHA224 extends SHA2_32B {\n constructor() {\n super(28, SHA224_IV);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 \u00A75.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable high-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 \u00A76.4. */\nclass SHA2_64B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and slows hashing down (measured on sha256).\n Ah = 0;\n Al = 0;\n Bh = 0;\n Bl = 0;\n Ch = 0;\n Cl = 0;\n Dh = 0;\n Dl = 0;\n Eh = 0;\n El = 0;\n Fh = 0;\n Fl = 0;\n Gh = 0;\n Gl = 0;\n Hh = 0;\n Hl = 0;\n constructor(outputLen, IV) {\n super(128, outputLen, 16, false);\n this.Ah = IV[0] | 0;\n this.Al = IV[1] | 0;\n this.Bh = IV[2] | 0;\n this.Bl = IV[3] | 0;\n this.Ch = IV[4] | 0;\n this.Cl = IV[5] | 0;\n this.Dh = IV[6] | 0;\n this.Dl = IV[7] | 0;\n this.Eh = IV[8] | 0;\n this.El = IV[9] | 0;\n this.Fh = IV[10] | 0;\n this.Fl = IV[11] | 0;\n this.Gh = IV[12] | 0;\n this.Gl = IV[13] | 0;\n this.Hh = IV[14] | 0;\n this.Hl = IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA-512 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA512 extends SHA2_64B {\n constructor() {\n super(64, SHA512_IV);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA384 extends SHA2_64B {\n constructor() {\n super(48, SHA384_IV);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n constructor() {\n super(28, T224_IV);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n constructor() {\n super(32, T256_IV);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n", "/**\n * Serialize JSON-compatible values with locale-independent object ordering.\n * Arrays retain their input order; they are never treated as sets.\n */\nexport function canonicalizeJson(value: unknown): string {\n return encodeCanonical(value, new Set<object>());\n}\n\n/** Encode the canonical representation using the platform's UTF-8 encoder. */\nexport function canonicalJsonBytes(value: unknown): Uint8Array {\n return new TextEncoder().encode(canonicalizeJson(value));\n}\n\nfunction encodeCanonical(value: unknown, seen: Set<object>): string {\n if (value === null) return 'null';\n if (typeof value === 'string') return JSON.stringify(value);\n if (typeof value === 'boolean') return value ? 'true' : 'false';\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new TypeError('Cannot encode non-finite number as canonical JSON');\n return JSON.stringify(Object.is(value, -0) ? 0 : value);\n }\n if (typeof value !== 'object' || value === undefined) {\n throw new TypeError(`Cannot encode ${typeof value} as canonical JSON`);\n }\n if (seen.has(value)) throw new TypeError('Cannot encode cyclic value as canonical JSON');\n seen.add(value);\n\n try {\n if (Array.isArray(value)) return encodeArray(value, seen);\n return encodeObject(value as Record<string, unknown>, seen);\n } finally {\n seen.delete(value);\n }\n}\n\nfunction encodeArray(value: readonly unknown[], seen: Set<object>): string {\n const values = Array.from({ length: value.length }, (_, index) => {\n if (!Object.prototype.hasOwnProperty.call(value, index)) {\n throw new TypeError('Cannot encode sparse array as canonical JSON');\n }\n return encodeCanonical(value[index], seen);\n });\n return `[${values.join(',')}]`;\n}\n\nfunction encodeObject(value: Record<string, unknown>, seen: Set<object>): string {\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError('Cannot encode a non-plain object as canonical JSON');\n }\n if (Object.getOwnPropertySymbols(value).some((symbol) =>\n Object.prototype.propertyIsEnumerable.call(value, symbol))) {\n throw new TypeError('Cannot encode symbol properties as canonical JSON');\n }\n\n const pairs = Object.keys(value)\n .sort(compareCanonicalStrings)\n .map((key) => `${JSON.stringify(key)}:${encodeCanonical(value[key], seen)}`);\n return `{${pairs.join(',')}}`;\n}\n\nfunction compareCanonicalStrings(left: string, right: string): number {\n if (left === right) return 0;\n return left < right ? -1 : 1;\n}\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport type { SourceMemberRefV2 } from '../source/source-types';\nimport type { EdgeRefV2, NodeRefV2 } from './security-workflow';\n\nconst encoder = new TextEncoder();\n\n/** The tuple format is deliberately byte-length-prefixed and locale independent. */\nexport function encodeIdentityTuple(parts: readonly string[]): string {\n return parts.map(encodeIdentityPart).join('');\n}\n\nfunction encodeIdentityPart(part: string): string {\n if (!containsLoneSurrogate(part)) {\n const tagged = `N${encoder.encode(part).byteLength}:${part}`;\n return `${encoder.encode(tagged).byteLength}:${tagged}`;\n }\n let codeUnits = '';\n for (let index = 0; index < part.length; index += 1) codeUnits += part.charCodeAt(index).toString(16).padStart(4, '0');\n const tagged = `C${part.length}:${codeUnits}`;\n return `${encoder.encode(tagged).byteLength}:${tagged}`;\n}\n\nfunction containsLoneSurrogate(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) return true;\n index += 1;\n } else if (code >= 0xdc00 && code <= 0xdfff) return true;\n }\n return false;\n}\n\nexport function createNodeIdentityDigest(ordinal: number, source: SourceMemberRefV2): string {\n if (!Number.isSafeInteger(ordinal) || ordinal < 0) throw new TypeError('Invalid node ordinal');\n return digest(['secureflow-node-ref-v2', String(ordinal), source.astNodeId]);\n}\n\nexport function createNodeRef(input: {\n ordinal: number;\n source: SourceMemberRefV2;\n explicitId?: unknown;\n name?: unknown;\n}): NodeRefV2 {\n const ref: NodeRefV2 = {\n ordinal: input.ordinal,\n source: input.source,\n ...(typeof input.explicitId === 'string' ? { explicitId: input.explicitId } : {}),\n ...(typeof input.name === 'string' ? { name: input.name } : {}),\n identityDigest: createNodeIdentityDigest(input.ordinal, input.source),\n };\n return Object.freeze(ref);\n}\n\nexport function createEdgeIdentityDigest(edge: Pick<\n EdgeRefV2,\n 'ordinal' | 'sourceNode' | 'sourceLabel' | 'targetNode' | 'targetLabel' | 'connectionType' | 'sourcePort' | 'targetPort' | 'source' | 'resolution'\n>): string {\n return digest([\n 'secureflow-edge-ref-v2',\n unsigned(edge.ordinal),\n edge.sourceNode?.identityDigest ?? 'NONE',\n edge.sourceLabel,\n edge.targetNode?.identityDigest ?? 'NONE',\n edge.targetLabel ?? 'NONE',\n edge.connectionType,\n unsigned(edge.sourcePort),\n unsigned(edge.targetPort),\n edge.source.astNodeId,\n edge.resolution,\n ]);\n}\n\nfunction unsigned(value: number): string {\n if (!Number.isSafeInteger(value) || value < 0) throw new TypeError('Invalid identity ordinal');\n return String(value);\n}\n\nfunction digest(parts: readonly string[]): string {\n return bytesToHex(sha256(encoder.encode(encodeIdentityTuple(parts))));\n}\n", "/**\n * @fileoverview Character codes.\n * @author Nicholas C. Zakas\n */\n\nconst CHAR_0 = 48; // 0\nconst CHAR_1 = 49; // 1\nconst CHAR_9 = 57; // 9\nconst CHAR_BACKSLASH = 92; // \\\nconst CHAR_DOLLAR = 36; // $\nconst CHAR_DOT = 46; // .\nconst CHAR_DOUBLE_QUOTE = 34; // \"\nconst CHAR_LOWER_A = 97; // a\nconst CHAR_LOWER_E = 101; // e\nconst CHAR_LOWER_F = 102; // f\nconst CHAR_LOWER_N = 110; // n\nconst CHAR_LOWER_T = 116; // t\nconst CHAR_LOWER_U = 117; // u\nconst CHAR_LOWER_X = 120; // x\nconst CHAR_LOWER_Z = 122; // z\nconst CHAR_MINUS = 45; // -\nconst CHAR_NEWLINE = 10; // newline\nconst CHAR_PLUS = 43; // +\nconst CHAR_RETURN = 13; // return\nconst CHAR_SINGLE_QUOTE = 39; // '\nconst CHAR_SLASH = 47; // /\nconst CHAR_SPACE = 32; // space\nconst CHAR_TAB = 9; // tab\nconst CHAR_UNDERSCORE = 95; // _\nconst CHAR_UPPER_A = 65; // A\nconst CHAR_UPPER_E = 69; // E\nconst CHAR_UPPER_F = 70; // F\nconst CHAR_UPPER_N = 78; // N\nconst CHAR_UPPER_X = 88; // X\nconst CHAR_UPPER_Z = 90; // Z\nconst CHAR_LOWER_B = 98; // b\nconst CHAR_LOWER_R = 114; // r\nconst CHAR_LOWER_V = 118; // v\nconst CHAR_LINE_SEPARATOR = 0x2028;\nconst CHAR_PARAGRAPH_SEPARATOR = 0x2029;\nconst CHAR_UPPER_I = 73; // I\nconst CHAR_STAR = 42; // *\nconst CHAR_VTAB = 11; // U+000B Vertical tab\nconst CHAR_FORM_FEED = 12; // U+000C Form feed\nconst CHAR_NBSP = 160; // U+00A0 Non-breaking space\nconst CHAR_BOM = 65279; // U+FEFF\nconst CHAR_NON_BREAKING_SPACE = 160;\nconst CHAR_EN_QUAD = 8192;\nconst CHAR_EM_QUAD = 8193;\nconst CHAR_EN_SPACE = 8194;\nconst CHAR_EM_SPACE = 8195;\nconst CHAR_THREE_PER_EM_SPACE = 8196;\nconst CHAR_FOUR_PER_EM_SPACE = 8197;\nconst CHAR_SIX_PER_EM_SPACE = 8198;\nconst CHAR_FIGURE_SPACE = 8199;\nconst CHAR_PUNCTUATION_SPACE = 8200;\nconst CHAR_THIN_SPACE = 8201;\nconst CHAR_HAIR_SPACE = 8202;\nconst CHAR_NARROW_NO_BREAK_SPACE = 8239;\nconst CHAR_MEDIUM_MATHEMATICAL_SPACE = 8287;\nconst CHAR_IDEOGRAPHIC_SPACE = 12288;\n\n/**\n * @fileoverview JSON syntax helpers\n * @author Nicholas C. Zakas\n */\n\n\n//-----------------------------------------------------------------------------\n// Types\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").TokenType} TokenType */\n\n//-----------------------------------------------------------------------------\n// Predefined Tokens\n//-----------------------------------------------------------------------------\n\nconst LBRACKET = \"[\";\nconst RBRACKET = \"]\";\nconst LBRACE = \"{\";\nconst RBRACE = \"}\";\nconst COLON = \":\";\nconst COMMA = \",\";\n\nconst TRUE = \"true\";\nconst FALSE = \"false\";\nconst NULL = \"null\";\nconst NAN$1 = \"NaN\";\nconst INFINITY$1 = \"Infinity\";\nconst QUOTE = \"\\\"\";\n\nconst escapeToChar = new Map([\n [CHAR_DOUBLE_QUOTE, QUOTE],\n [CHAR_BACKSLASH, \"\\\\\"],\n [CHAR_SLASH, \"/\"],\n [CHAR_LOWER_B, \"\\b\"],\n [CHAR_LOWER_N, \"\\n\"],\n [CHAR_LOWER_F, \"\\f\"],\n [CHAR_LOWER_R, \"\\r\"],\n [CHAR_LOWER_T, \"\\t\"]\n]);\n\nconst json5EscapeToChar = new Map([\n ...escapeToChar,\n [CHAR_LOWER_V, \"\\v\"],\n [CHAR_0, \"\\0\"]\n]);\n\nconst charToEscape = new Map([\n [QUOTE, QUOTE],\n [\"\\\\\", \"\\\\\"],\n [\"/\", \"/\"],\n [\"\\b\", \"b\"],\n [\"\\n\", \"n\"],\n [\"\\f\", \"f\"],\n [\"\\r\", \"r\"],\n [\"\\t\", \"t\"]\n]);\n\nconst json5CharToEscape = new Map([\n ...charToEscape,\n [\"\\v\", \"v\"],\n [\"\\0\", \"0\"],\n [\"\\u2028\", \"u2028\"],\n [\"\\u2029\", \"u2029\"]\n]);\n\n/** @type {Map<string,TokenType>} */\nconst knownTokenTypes = new Map([\n [LBRACKET, \"LBracket\"],\n [RBRACKET, \"RBracket\"],\n [LBRACE, \"LBrace\"],\n [RBRACE, \"RBrace\"],\n [COLON, \"Colon\"],\n [COMMA, \"Comma\"],\n [TRUE, \"Boolean\"],\n [FALSE, \"Boolean\"],\n [NULL, \"Null\"]\n]);\n\n/** @type {Map<string,TokenType>} */\nconst knownJSON5TokenTypes = new Map([\n ...knownTokenTypes,\n [NAN$1, \"Number\"],\n [INFINITY$1, \"Number\"]\n]);\n\n// JSON5\nconst json5LineTerminators = new Set([\n CHAR_NEWLINE,\n CHAR_RETURN,\n CHAR_LINE_SEPARATOR,\n CHAR_PARAGRAPH_SEPARATOR\n]);\n\n/**\n * @fileoverview JSON tokenization/parsing errors\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").Location} Location */\n/** @typedef {import(\"./typedefs.js\").Token} Token */\n\n//-----------------------------------------------------------------------------\n// Errors\n//-----------------------------------------------------------------------------\n\n/**\n * Base class that attaches location to an error.\n */\nclass ErrorWithLocation extends Error {\n\n /**\n * Creates a new instance.\n * @param {string} message The error message to report. \n * @param {Location} loc The location information for the error.\n */\n constructor(message, { line, column, offset }) {\n super(`${ message } (${ line }:${ column})`);\n\n /**\n * The line on which the error occurred.\n * @type {number}\n */\n this.line = line;\n\n /**\n * The column on which the error occurred.\n * @type {number}\n */\n this.column = column;\n \n /**\n * The index into the string where the error occurred.\n * @type {number}\n */\n this.offset = offset;\n }\n\n}\n\n/**\n * Error thrown when an unexpected character is found during tokenizing.\n */\nclass UnexpectedChar extends ErrorWithLocation {\n\n /**\n * Creates a new instance.\n * @param {number} unexpected The character that was found.\n * @param {Location} loc The location information for the found character.\n */\n constructor(unexpected, loc) {\n super(`Unexpected character '${ String.fromCharCode(unexpected) }' found.`, loc);\n }\n}\n\n/**\n * Error thrown when an unexpected identifier is found during tokenizing.\n */\nclass UnexpectedIdentifier extends ErrorWithLocation {\n\n /**\n * Creates a new instance.\n * @param {string} unexpected The character that was found.\n * @param {Location} loc The location information for the found character.\n */\n constructor(unexpected, loc) {\n super(`Unexpected identifier '${ unexpected }' found.`, loc);\n }\n}\n\n/**\n * Error thrown when an unexpected token is found during parsing.\n */\nclass UnexpectedToken extends ErrorWithLocation {\n\n /**\n * Creates a new instance.\n * @param {Token} token The token that was found. \n */\n constructor(token) {\n super(`Unexpected token ${ token.type } found.`, token.loc.start);\n }\n}\n\n/**\n * Error thrown when the end of input is found where it isn't expected.\n */\nclass UnexpectedEOF extends ErrorWithLocation {\n\n /**\n * Creates a new instance.\n * @param {Location} loc The location information for the found character.\n */\n constructor(loc) {\n super(\"Unexpected end of input found.\", loc);\n }\n}\n\n/*\n * The following is extracted from https://github.com/json5/json5/\n *\n * MIT License\n * \n * Copyright (c) 2012-2018 Aseem Kishore, and others.\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\nconst ID_Start = /[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA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E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uA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5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]/;\n// eslint-disable-next-line no-misleading-character-class\nconst ID_Continue = /[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u08D4-\\u08E1\\u08E3-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09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\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19D9\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABD\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1C80-\\u1C88\\u1CD0-\\u1CD2\\u1CD4-\\u1CF9\\u1D00-\\u1DF9\\u1DFB-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u209C\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66F\\uA674-\\uA67D\\uA67F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA827\\uA840-\\uA873\\uA880-\\uA8C5\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA8FD\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABEA\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uDE47\\uDE50-\\uDE83\\uDE86-\\uDE99\\uDEC0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC36\\uDC38-\\uDC40\\uDC50-\\uDC59\\uDC72-\\uDC8F\\uDC92-\\uDCA7\\uDCA9-\\uDCB6\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD36\\uDD3A\\uDD3C\\uDD3D\\uDD3F-\\uDD47\\uDD50-\\uDD59]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDE60-\\uDE69\\uDED0-\\uDEED\\uDEF0-\\uDEF4\\uDF00-\\uDF36\\uDF40-\\uDF43\\uDF50-\\uDF59\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDF00-\\uDF44\\uDF50-\\uDF7E\\uDF8F-\\uDF9F\\uDFE0\\uDFE1]|\\uD821[\\uDC00-\\uDFEC]|\\uD822[\\uDC00-\\uDEF2]|\\uD82C[\\uDC00-\\uDD1E\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99\\uDC9D\\uDC9E]|\\uD834[\\uDD65-\\uDD69\\uDD6D-\\uDD72\\uDD7B-\\uDD82\\uDD85-\\uDD8B\\uDDAA-\\uDDAD\\uDE42-\\uDE44]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-\\uD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\\uDE1D]|\\uDB40[\\uDD00-\\uDDEF]/;\n\n/**\n * @fileoverview A charactor code reader.\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Type Definitions\n//-----------------------------------------------------------------------------\n\n\n//-----------------------------------------------------------------------------\n// Data\n//-----------------------------------------------------------------------------\n\nconst CHAR_CR = 13; // \\r\nconst CHAR_LF = 10; // \\n\n\n//-----------------------------------------------------------------------------\n// CharCodeReader\n//-----------------------------------------------------------------------------\n\n/**\n * A reader that reads character codes from a string.\n */\nclass CharCodeReader {\n\n /**\n * The text to read from.\n * @type {string}\n */\n #text = \"\";\n\n /**\n * The current line number.\n * @type {number}\n */\n #line = 1;\n\n /**\n * The current column number.\n * @type {number}\n */\n #column = 0;\n\n /**\n * The current offset in the text.\n * @type {number}\n */\n #offset = -1;\n\n /**\n * Whether the last character read was a new line.\n * @type {boolean}\n */\n #newLine = false;\n\n /**\n * The last character code read.\n * @type {number}\n */\n #last = -1;\n\n /**\n * Whether the reader has ended.\n * @type {boolean}\n */\n #ended = false;\n\n /**\n * Creates a new instance.\n * @param {string} text The text to read from\n */\n constructor(text) {\n this.#text = text;\n }\n\n /**\n * Ends the reader.\n * @returns {void}\n */\n #end() {\n if (this.#ended) {\n return;\n }\n\n this.#column++;\n this.#offset++;\n this.#last = -1;\n this.#ended = true;\n }\n\n /**\n * Returns the current position of the reader.\n * @returns {Location} An object with line, column, and offset properties.\n */\n locate() {\n return {\n line: this.#line,\n column: this.#column,\n offset: this.#offset\n };\n }\n\n /**\n * Reads the next character code in the text.\n * @returns {number} The next character code, or -1 if there are no more characters.\n */\n next() {\n if (this.#offset >= this.#text.length - 1) {\n this.#end();\n return -1;\n }\n\n this.#offset++;\n const charCode = this.#text.charCodeAt(this.#offset);\n\n if (this.#newLine) {\n this.#line++;\n this.#column = 1;\n this.#newLine = false;\n } else {\n this.#column++;\n }\n\n if (charCode === CHAR_CR) {\n this.#newLine = true;\n\n // if we already see a \\r, just ignore upcoming \\n\n if (this.peek() === CHAR_LF) {\n this.#offset++;\n }\n } else if (charCode === CHAR_LF) {\n this.#newLine = true;\n }\n\n this.#last = charCode;\n\n return charCode;\n }\n\n /**\n * Peeks at the next character code in the text.\n * @returns {number} The next character code, or -1 if there are no more characters.\n */\n peek() {\n if (this.#offset === this.#text.length - 1) {\n return -1;\n }\n\n return this.#text.charCodeAt(this.#offset + 1);\n }\n\n /**\n * Determines if the next character code in the text matches a specific character code.\n * @param {(number) => boolean} fn A function to call on the next character.\n * @returns {boolean} True if the next character code matches, false if not.\n */ \n match(fn) {\n if (fn(this.peek())) {\n this.next();\n return true;\n }\n\n return false;\n }\n\n /**\n * Returns the last character code read.\n * @returns {number} The last character code read.\n */\n current() {\n return this.#last;\n }\n\n\n}\n\n/**\n * @fileoverview JSON tokenizer\n * @author Nicholas C. Zakas\n */\n\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").Range} Range */\n/** @typedef {import(\"./typedefs.js\").TokenizeOptions} TokenizeOptions */\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\nconst INFINITY = \"Infinity\";\nconst NAN = \"NaN\";\n\nconst keywordStarts = new Set([CHAR_LOWER_T, CHAR_LOWER_F, CHAR_LOWER_N]);\nconst whitespace = new Set([CHAR_SPACE, CHAR_TAB, CHAR_NEWLINE, CHAR_RETURN]);\nconst json5Whitespace = new Set([\n ...whitespace,\n CHAR_VTAB,\n CHAR_FORM_FEED,\n CHAR_NBSP,\n CHAR_LINE_SEPARATOR,\n CHAR_PARAGRAPH_SEPARATOR,\n CHAR_BOM,\n CHAR_NON_BREAKING_SPACE,\n CHAR_EN_QUAD,\n CHAR_EM_QUAD,\n CHAR_EN_SPACE,\n CHAR_EM_SPACE,\n CHAR_THREE_PER_EM_SPACE,\n CHAR_FOUR_PER_EM_SPACE,\n CHAR_SIX_PER_EM_SPACE,\n CHAR_FIGURE_SPACE,\n CHAR_PUNCTUATION_SPACE,\n CHAR_THIN_SPACE,\n CHAR_HAIR_SPACE,\n CHAR_NARROW_NO_BREAK_SPACE,\n CHAR_MEDIUM_MATHEMATICAL_SPACE,\n CHAR_IDEOGRAPHIC_SPACE,\n]);\n\n\n/** @type {TokenizeOptions} */\nconst DEFAULT_OPTIONS$1 = {\n mode: \"json\",\n ranges: false\n};\n\nconst jsonKeywords = new Set([\"true\", \"false\", \"null\"]);\n\nconst tt = {\n EOF: 0,\n Number: 1,\n String: 2,\n Boolean: 3,\n Null: 4,\n NaN: 5,\n Infinity: 6,\n Identifier: 7,\n Colon: 20,\n LBrace: 21,\n RBrace: 22,\n LBracket: 23,\n RBracket: 24,\n Comma: 25,\n LineComment: 40,\n BlockComment: 41\n};\n\n\n// #region Helpers\n\n\n/**\n * Determines if a given character is a decimal digit.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is a digit.\n */\nfunction isDigit(c) {\n return c >= CHAR_0 && c <= CHAR_9;\n}\n\n/**\n * Determines if a given character is a hexadecimal digit.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is a hexadecimal digit.\n */\nfunction isHexDigit(c) {\n return isDigit(c) ||\n c >= CHAR_UPPER_A && c <= CHAR_UPPER_F ||\n c >= CHAR_LOWER_A && c <= CHAR_LOWER_F;\n}\n\n/**\n * Determines if a given character is a positive digit (1-9).\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is a positive digit.\n */\nfunction isPositiveDigit(c) {\n return c >= CHAR_1 && c <= CHAR_9;\n}\n\n/**\n * Determines if a given character is the start of a keyword.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is the start of a keyword.\n */\nfunction isKeywordStart(c) {\n return keywordStarts.has(c);\n}\n\n/**\n * Determines if a given character is the start of a number.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is the start of a number.\n */\nfunction isNumberStart(c) {\n return isDigit(c) || c === CHAR_DOT || c === CHAR_MINUS;\n}\n\n/**\n * Determines if a given character is the start of a JSON5 number.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is the start of a JSON5 number.\n */\nfunction isJSON5NumberStart(c) {\n return isNumberStart(c) || c === CHAR_PLUS;\n}\n\n/**\n * Determines if a given character is the start of a string.\n * @param {number} c The character to check.\n * @param {boolean} json5 `true` if JSON5 mode is enabled.\n * @returns {boolean} `true` if the character is the start of a string.\n */\nfunction isStringStart(c, json5) {\n return c === CHAR_DOUBLE_QUOTE || (json5 && c === CHAR_SINGLE_QUOTE);\n}\n\n/**\n * Tests that a given character is a valid first character of a\n * JSON5 identifier\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is a valid first character. \n */\nfunction isJSON5IdentifierStart(c) {\n\n // test simple cases first\n\n if (c === CHAR_DOLLAR || c === CHAR_UNDERSCORE || c === CHAR_BACKSLASH) {\n return true;\n }\n\n if (c >= CHAR_LOWER_A && c <= CHAR_LOWER_Z || c >= CHAR_UPPER_A && c <= CHAR_UPPER_Z) {\n return true;\n }\n\n if (c === 0x200C || c === 0x200D) {\n return true;\n }\n \n const ct = String.fromCharCode(c);\n return ID_Start.test(ct);\n}\n\n/**\n * Tests that a given character is a valid part of a JSON5 identifier.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is a valid part of an identifier.\n */\nfunction isJSON5IdentifierPart(c) {\n\n // fast path for simple cases\n if (isJSON5IdentifierStart(c) || isDigit(c)) {\n return true;\n }\n\n const ct = String.fromCharCode(c);\n return ID_Continue.test(ct);\n}\n\n\n// #endregion\n\nclass Tokenizer {\n\n /**\n * Options for the tokenizer.\n * @type {TokenizeOptions}\n */\n #options;\n\n /**\n * The source text to tokenize.\n * @type {string}\n */\n #text;\n\n /**\n * The reader for the source text.\n * @type {CharCodeReader}\n */\n #reader;\n\n /**\n * Indicates if the tokenizer is in JSON5 mode.\n * @type {boolean}\n */\n #json5;\n\n /**\n * Indicates if comments are allowed.\n * @type {boolean}\n */\n #allowComments;\n\n /**\n * Indicates if ranges should be included in the tokens.\n * @type {boolean}\n */\n #ranges;\n\n /**\n * The last token type read.\n * @type {Token}\n */\n #token;\n\n /**\n * Determines if a character is an escaped character.\n * @type {(c:number) => boolean}\n */\n #isEscapedCharacter;\n\n /**\n * Determines if a character is a JSON5 line terminator.\n * @type {(c:number) => boolean}\n */\n #isJSON5LineTerminator;\n\n\n /**\n * Determines if a character is a JSON5 hex escape.\n * @type {(c:number) => boolean}\n */\n #isJSON5HexEscape;\n\n /**\n * Determines if a character is whitespace.\n * @type {(c:number) => boolean}\n */\n #isWhitespace;\n\n /**\n * Creates a new instance of the tokenizer.\n * @param {string} text The source text\n * @param {TokenizeOptions} [options] Options for the tokenizer.\n */ \n constructor(text, options) {\n this.#text = text;\n this.#options = {\n ...DEFAULT_OPTIONS$1,\n ...options\n };\n\n this.#reader = new CharCodeReader(text);\n this.#json5 = this.#options.mode === \"json5\";\n this.#allowComments = this.#options.mode !== \"json\";\n this.#ranges = this.#options.ranges;\n\n // TODO: Clean this up\n this.#isEscapedCharacter = this.#json5 ? json5EscapeToChar.has.bind(json5EscapeToChar) : escapeToChar.has.bind(escapeToChar);\n this.#isJSON5LineTerminator = this.#json5 ? json5LineTerminators.has.bind(json5LineTerminators) : () => false;\n this.#isJSON5HexEscape = this.#json5 ? c => c === CHAR_LOWER_X : () => false;\n this.#isWhitespace = this.#json5 ? json5Whitespace.has.bind(json5Whitespace) : whitespace.has.bind(whitespace);\n }\n\n // #region Errors\n\n /**\n * Convenience function for throwing unexpected character errors.\n * @param {number} c The unexpected character.\n * @param {Location} [loc] The location of the unexpected character.\n * @returns {never}\n * @throws {UnexpectedChar} always.\n */\n #unexpected(c, loc = this.#reader.locate()) {\n throw new UnexpectedChar(c, loc);\n }\n\n /**\n * Convenience function for throwing unexpected identifier errors.\n * @param {string} identifier The unexpected identifier.\n * @param {Location} [loc] The location of the unexpected identifier.\n * @returns {never}\n * @throws {UnexpectedIdentifier} always.\n */\n #unexpectedIdentifier(identifier, loc = this.#reader.locate()) {\n throw new UnexpectedIdentifier(identifier, loc);\n }\n\n /**\n * Convenience function for throwing unexpected EOF errors.\n * @returns {never}\n * @throws {UnexpectedEOF} always.\n */\n #unexpectedEOF() {\n throw new UnexpectedEOF(this.#reader.locate());\n }\n\n // #endregion\n\n // #region Helpers\n\n /**\n * Creates a new token.\n * @param {TokenType} tokenType The type of token to create.\n * @param {number} length The length of the token.\n * @param {Location} startLoc The start location for the token.\n * @param {Location} [endLoc] The end location for the token.\n * @returns {Token} The token.\n */\n #createToken(tokenType, length, startLoc, endLoc) {\n\n const endOffset = startLoc.offset + length;\n\n let range = this.#options.ranges ? {\n range: /** @type {Range} */ ([startLoc.offset, endOffset])\n } : undefined;\n\n return {\n type: tokenType,\n loc: {\n start: startLoc,\n end: endLoc || {\n line: startLoc.line,\n column: startLoc.column + length,\n offset: endOffset\n }\n },\n ...range\n }; \n }\n\n /**\n * Reads in a specific number of hex digits.\n * @param {number} count The number of hex digits to read.\n * @returns {string} The hex digits read.\n */\n #readHexDigits(count) {\n let value = \"\";\n let c;\n\n for (let i = 0; i < count; i++) {\n c = this.#reader.peek();\n if (isHexDigit(c)) {\n this.#reader.next();\n value += String.fromCharCode(c);\n continue;\n }\n\n this.#unexpected(c);\n }\n\n return value;\n }\n\n /**\n * Reads in a JSON5 identifier. Also used for JSON but we validate\n * the identifier later.\n * @param {number} c The first character of the identifier.\n * @returns {string} The identifier read.\n * @throws {UnexpectedChar} when the identifier cannot be read.\n */\n #readIdentifier(c) {\n let value = \"\";\n\n do {\n\n value += String.fromCharCode(c);\n\n if (c === CHAR_BACKSLASH) {\n\n c = this.#reader.next();\n\n if (c !== CHAR_LOWER_U) {\n this.#unexpected(c);\n }\n\n value += String.fromCharCode(c);\n\n const hexDigits = this.#readHexDigits(4);\n\n // check for a valid character code\n const charCode = parseInt(hexDigits, 16);\n\n if (value.length === 2 && !isJSON5IdentifierStart(charCode)) {\n const loc = this.#reader.locate();\n this.#unexpected(CHAR_BACKSLASH, { line: loc.line, column: loc.column - 5, offset: loc.offset - 5 });\n } else if (!isJSON5IdentifierPart(charCode)) {\n const loc = this.#reader.locate();\n this.#unexpected(charCode, { line: loc.line, column: loc.column - 5, offset: loc.offset - 5 });\n }\n\n value += hexDigits;\n }\n\n c = this.#reader.peek();\n\n if (!isJSON5IdentifierPart(c)) {\n break;\n }\n\n this.#reader.next();\n\n } while (true); // eslint-disable-line no-constant-condition\n\n return value;\n }\n\n /**\n * Reads in a string. Works for both JSON and JSON5.\n * @param {number} c The first character of the string (either \" or ').\n * @returns {number} The length of the string.\n * @throws {UnexpectedChar} when the string cannot be read.\n * @throws {UnexpectedEOF} when EOF is reached before the string is finalized.\n */\n #readString(c) {\n \n const delimiter = c;\n let length = 1;\n c = this.#reader.peek();\n\n while (c !== -1 && c !== delimiter) {\n\n this.#reader.next();\n length++;\n\n // escapes\n if (c === CHAR_BACKSLASH) {\n c = this.#reader.peek();\n\n if (this.#isEscapedCharacter(c) || this.#isJSON5LineTerminator(c)) {\n this.#reader.next();\n length++;\n } else if (c === CHAR_LOWER_U) {\n this.#reader.next();\n length++;\n\n const result = this.#readHexDigits(4);\n length += result.length;\n } else if (this.#isJSON5HexEscape(c)) {\n this.#reader.next();\n length++;\n\n // hex escapes: \\xHH\n const result = this.#readHexDigits(2);\n length += result.length;\n } else if (this.#json5) { // JSON doesn't allow anything else\n this.#reader.next();\n length++;\n } else {\n this.#unexpected(c);\n }\n }\n\n c = this.#reader.peek();\n }\n\n if (c === -1) {\n this.#reader.next();\n this.#unexpectedEOF();\n }\n\n // c is the delimiter\n this.#reader.next();\n length++;\n\n return length;\n \n \n }\n\n /**\n * Reads a number. Works for both JSON and JSON5.\n * @param {number} c The first character of the number.\n * @returns {number} The length of the number.\n * @throws {UnexpectedChar} when the number cannot be read.\n * @throws {UnexpectedEOF} when EOF is reached before the number is finalized.\n */\n #readNumber(c) {\n \n // we've already read the first character\n let length = 1;\n\n // JSON number may start with a minus but not a plus\n // JSON5 allows a plus.\n if (c === CHAR_MINUS || this.#json5 && c === CHAR_PLUS) {\n \n c = this.#reader.peek();\n \n /*\n * JSON5 allows Infinity or NaN preceded by a sign.\n * This blocks handles +Infinity, -Infinity, +NaN, and -NaN.\n * Standalone Infinity and NaN are handled in `readJSON5Identifier()`\n */\n if (this.#json5) {\n\n if (c === CHAR_UPPER_I || c === CHAR_UPPER_N) {\n this.#reader.next();\n const identifier = this.#readIdentifier(c);\n\n if (identifier !== INFINITY && identifier !== NAN) {\n this.#unexpected(c);\n }\n\n return length + identifier.length;\n }\n }\n\n // Next digit cannot be zero\n if (!isDigit(c)) {\n this.#unexpected(c);\n }\n\n // if we made it here, we need to continue on, so register the character\n this.#reader.next();\n length++;\n }\n\n /*\n * In JSON, a zero must be followed by a decimal point or nothing.\n * In JSON5, a zero can additionally be followed by an `x` indicating\n * that it's a hexadecimal number.\n */\n if (c === CHAR_0) {\n\n // c = this.#reader.next();\n // length++;\n c = this.#reader.peek();\n\n // check for a hex number\n if (this.#json5 && (c === CHAR_LOWER_X || c === CHAR_UPPER_X)) {\n\n this.#reader.next();\n length++;\n\n c = this.#reader.peek();\n\n if (!isHexDigit(c)) {\n this.#reader.next();\n this.#unexpected(c);\n }\n\n do {\n this.#reader.next();\n length++;\n c = this.#reader.peek();\n } while (isHexDigit(c));\n\n } else if (isDigit(c)) {\n this.#unexpected(c);\n }\n\n } else {\n\n // JSON5 allows leading decimal points\n if (!this.#json5 || c !== CHAR_DOT) {\n if (!isPositiveDigit(c)) {\n this.#unexpected(c);\n }\n\n c = this.#reader.peek();\n\n while (isDigit(c)) {\n this.#reader.next();\n length++;\n c = this.#reader.peek();\n }\n }\n }\n\n /*\n * In JSON, a decimal point must be followed by at least one digit.\n * In JSON5, a decimal point need not be followed by any digits.\n */\n if (c === CHAR_DOT) {\n \n let digitCount = -1;\n this.#reader.next();\n length++;\n digitCount++;\n\n c = this.#reader.peek();\n\n while (isDigit(c)) {\n this.#reader.next();\n length++;\n digitCount++;\n c = this.#reader.peek();\n }\n\n if (!this.#json5 && digitCount === 0) {\n this.#reader.next();\n if (c) {\n this.#unexpected(c);\n } else {\n this.#unexpectedEOF();\n }\n }\n }\n\n // Exponent is always last\n if (c === CHAR_LOWER_E || c === CHAR_UPPER_E) {\n\n this.#reader.next();\n length++;\n c = this.#reader.peek();\n\n if (c === CHAR_PLUS || c === CHAR_MINUS) {\n this.#reader.next();\n length++;\n c = this.#reader.peek();\n }\n\n /*\n * Must always have a digit in this position to avoid:\n * 5e\n * 12E+\n * 42e-\n */\n if (c === -1) {\n this.#reader.next();\n this.#unexpectedEOF();\n }\n\n if (!isDigit(c)) {\n this.#reader.next();\n this.#unexpected(c);\n }\n\n while (isDigit(c)) {\n this.#reader.next();\n length++;\n c = this.#reader.peek();\n }\n }\n\n return length;\n }\n\n /**\n * Reads a comment. Works for both JSON and JSON5.\n * @param {number} c The first character of the comment.\n * @returns {{length: number, multiline: boolean}} The length of the comment, and whether the comment is multi-line.\n * @throws {UnexpectedChar} when the comment cannot be read.\n * @throws {UnexpectedEOF} when EOF is reached before the comment is finalized.\n */ \n #readComment(c) {\n \n let length = 1;\n\n // next character determines single- or multi-line\n c = this.#reader.peek();\n\n // single-line comments\n if (c === CHAR_SLASH) {\n \n do {\n this.#reader.next();\n length += 1;\n c = this.#reader.peek();\n } while (c > -1 && c !== CHAR_RETURN && c !== CHAR_NEWLINE);\n\n return { length, multiline: false };\n }\n\n // multi-line comments\n if (c === CHAR_STAR) {\n\n this.#reader.next();\n length += 1;\n\n while (c > -1) {\n c = this.#reader.peek();\n\n // check for end of comment\n if (c === CHAR_STAR) {\n this.#reader.next();\n length += 1;\n c = this.#reader.peek();\n \n //end of comment\n if (c === CHAR_SLASH) {\n this.#reader.next();\n length += 1;\n\n return { length, multiline: true };\n }\n } else {\n this.#reader.next();\n length += 1;\n }\n }\n\n this.#reader.next();\n this.#unexpectedEOF();\n \n }\n\n // if we've made it here, there's an invalid character\n this.#reader.next();\n this.#unexpected(c); \n }\n // #endregion\n\n /**\n * Returns the next token in the source text.\n * @returns {number} The code for the next token.\n */\n next() {\n\n let c = this.#reader.next();\n\n while (this.#isWhitespace(c)) {\n c = this.#reader.next();\n }\n\n if (c === -1) {\n return tt.EOF;\n }\n\n const start = this.#reader.locate();\n const ct = String.fromCharCode(c);\n\n // check for JSON5 syntax only\n if (this.#json5) {\n \n if (knownJSON5TokenTypes.has(ct)) {\n this.#token = this.#createToken(knownJSON5TokenTypes.get(ct), 1, start);\n } else if (isJSON5IdentifierStart(c)) {\n const value = this.#readIdentifier(c);\n\n if (knownJSON5TokenTypes.has(value)) {\n this.#token = this.#createToken(knownJSON5TokenTypes.get(value), value.length, start);\n } else {\n this.#token = this.#createToken(\"Identifier\", value.length, start);\n }\n } else if (isJSON5NumberStart(c)) {\n const result = this.#readNumber(c);\n this.#token = this.#createToken(\"Number\", result, start);\n } else if (isStringStart(c, this.#json5)) {\n const result = this.#readString(c);\n const lastCharLoc = this.#reader.locate();\n this.#token = this.#createToken(\"String\", result, start, {\n line: lastCharLoc.line,\n column: lastCharLoc.column + 1,\n offset: lastCharLoc.offset + 1\n });\n } else if (c === CHAR_SLASH && this.#allowComments) {\n const result = this.#readComment(c);\n const lastCharLoc = this.#reader.locate();\n this.#token = this.#createToken(!result.multiline ? \"LineComment\" : \"BlockComment\", result.length, start, {\n line: lastCharLoc.line,\n column: lastCharLoc.column + 1,\n offset: lastCharLoc.offset + 1\n });\n } else {\n this.#unexpected(c);\n }\n\n } else {\n\n // check for JSON/JSONC syntax only\n if (knownTokenTypes.has(ct)) {\n this.#token = this.#createToken(knownTokenTypes.get(ct), 1, start);\n } else if (isKeywordStart(c)) {\n const value = this.#readIdentifier(c);\n\n if (!jsonKeywords.has(value)) {\n this.#unexpectedIdentifier(value, start);\n }\n\n this.#token = this.#createToken(knownTokenTypes.get(value), value.length, start);\n } else if (isNumberStart(c)) {\n const result = this.#readNumber(c);\n this.#token = this.#createToken(\"Number\", result, start);\n } else if (isStringStart(c, this.#json5)) {\n const result = this.#readString(c);\n this.#token = this.#createToken(\"String\", result, start);\n } else if (c === CHAR_SLASH && this.#allowComments) {\n const result = this.#readComment(c);\n const lastCharLoc = this.#reader.locate();\n this.#token = this.#createToken(!result.multiline ? \"LineComment\" : \"BlockComment\", result.length, start, {\n line: lastCharLoc.line,\n column: lastCharLoc.column + 1,\n offset: lastCharLoc.offset + 1\n });\n } else {\n this.#unexpected(c);\n }\n }\n return tt[this.#token.type];\n }\n\n /**\n * Returns the current token in the source text.\n * @returns {Token} The current token.\n */\n get token() {\n return this.#token;\n }\n}\n\n//-----------------------------------------------------------------------------\n// Main\n//-----------------------------------------------------------------------------\n\n/**\n * Creates an iterator over the tokens representing the source text.\n * @param {string} text The source text to tokenize.\n * @param {TokenizeOptions} [options] Options for doing the tokenization.\n * @returns {Array<Token>} An iterator over the tokens. \n */\nfunction tokenize(text, options) {\n\n const tokenizer = new Tokenizer(text, options);\n const tokens = [];\n\n while (tokenizer.next() !== tt.EOF) {\n tokens.push(tokenizer.token);\n }\n\n return tokens;\n\n}\n\n/**\n * @fileoverview JSON AST types\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").LocationRange} LocationRange */\n/** @typedef {import(\"./typedefs.js\").NodeParts} NodeParts */\n/** @typedef {import(\"./typedefs.js\").DocumentNode} DocumentNode */\n/** @typedef {import(\"./typedefs.js\").StringNode} StringNode */\n/** @typedef {import(\"./typedefs.js\").NumberNode} NumberNode */\n/** @typedef {import(\"./typedefs.js\").BooleanNode} BooleanNode */\n/** @typedef {import(\"./typedefs.js\").MemberNode} MemberNode */\n/** @typedef {import(\"./typedefs.js\").ObjectNode} ObjectNode */\n/** @typedef {import(\"./typedefs.js\").ElementNode} ElementNode */\n/** @typedef {import(\"./typedefs.js\").ArrayNode} ArrayNode */\n/** @typedef {import(\"./typedefs.js\").NullNode} NullNode */\n/** @typedef {import(\"./typedefs.js\").ValueNode} ValueNode */\n/** @typedef {import(\"./typedefs.js\").IdentifierNode} IdentifierNode */\n/** @typedef {import(\"./typedefs.js\").NaNNode} NaNNode */\n/** @typedef {import(\"./typedefs.js\").InfinityNode} InfinityNode */\n/** @typedef {import(\"./typedefs.js\").Sign} Sign */\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\nconst types = {\n\n /**\n * Creates a document node.\n * @param {ValueNode} body The body of the document.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {DocumentNode} The document node.\n */\n document(body, parts = {}) {\n return {\n type: \"Document\",\n body,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a string node.\n * @param {string} value The value for the string.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {StringNode} The string node.\n */\n string(value, parts = {}) {\n return {\n type: \"String\",\n value,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a number node.\n * @param {number} value The value for the number.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {NumberNode} The number node.\n */\n number(value, parts = {}) {\n return {\n type: \"Number\",\n value,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a boolean node.\n * @param {boolean} value The value for the boolean.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {BooleanNode} The boolean node.\n */\n boolean(value, parts = {}) {\n return {\n type: \"Boolean\",\n value,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a null node.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {NullNode} The null node.\n */\n null(parts = {}) {\n return {\n type: \"Null\",\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates an array node.\n * @param {Array<ElementNode>} elements The elements to add.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {ArrayNode} The array node.\n */\n array(elements, parts = {}) {\n return {\n type: \"Array\",\n elements,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates an element node.\n * @param {ValueNode} value The value for the element.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {ElementNode} The element node.\n */\n element(value, parts = {}) {\n return {\n type: \"Element\",\n value,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates an object node.\n * @param {Array<MemberNode>} members The members to add.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {ObjectNode} The object node.\n */\n object(members, parts = {}) {\n return {\n type: \"Object\",\n members,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a member node.\n * @param {StringNode|IdentifierNode} name The name for the member.\n * @param {ValueNode} value The value for the member.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {MemberNode} The member node.\n */\n member(name, value, parts = {}) {\n return {\n type: \"Member\",\n name,\n value,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates an identifier node.\n * @param {string} name The name for the identifier.\n * @param {NodeParts} parts Additional properties for the node.\n * @returns {IdentifierNode} The identifier node.\n */\n identifier(name, parts = {}) {\n return {\n type: \"Identifier\",\n name,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a NaN node.\n * @param {Sign} sign The sign for the Infinity.\n * @param {NodeParts} parts Additional properties for the node.\n * @returns {NaNNode} The NaN node.\n */ \n nan(sign = \"\", parts = {}) {\n return {\n type: \"NaN\",\n sign,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates an Infinity node.\n * @param {Sign} sign The sign for the Infinity.\n * @param {NodeParts} parts Additional properties for the node.\n * @returns {InfinityNode} The Infinity node.\n */\n infinity(sign = \"\", parts = {}) {\n return {\n type: \"Infinity\",\n sign,\n loc: parts.loc,\n ...parts\n };\n },\n\n};\n\n/**\n * @fileoverview JSON parser\n * @author Nicholas C. Zakas\n */\n\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").Node} Node */\n/** @typedef {import(\"./typedefs.js\").Mode} Mode */\n/** @typedef {import(\"./typedefs.js\").ParseOptions} ParseOptions */\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/** @type {ParseOptions} */\nconst DEFAULT_OPTIONS = {\n mode: \"json\",\n ranges: false,\n tokens: false,\n allowTrailingCommas: false\n};\n\nconst UNICODE_SEQUENCE = /\\\\u[\\da-fA-F]{4}/gu;\n\n/**\n * Normalizes a JSON5 identifier by converting Unicode escape sequences into\n * their corresponding characters.\n * @param {string} identifier The identifier to normalize.\n * @returns {string} The normalized identifier.\n */\nfunction normalizeIdentifier(identifier) {\n return identifier.replace(UNICODE_SEQUENCE, unicodeEscape => {\n return String.fromCharCode(parseInt(unicodeEscape.slice(2), 16));\n });\n}\n\n/**\n * Calculates the location at the end of the given text.\n * @param {string} text The text to calculate the end location for.\n * @returns {Location} The location at the end of the text.\n */\nfunction getEndLocation(text) {\n let line = 1;\n let column = 1;\n \n for (let i = 0; i < text.length; i++) {\n const char = text[i];\n if (char === \"\\n\") {\n line++;\n column = 1;\n } else if (char === \"\\r\") {\n // Handle \\r\\n as a single line ending\n if (text[i + 1] === \"\\n\") {\n i++; // Skip the \\n\n }\n line++;\n column = 1;\n } else {\n column++;\n }\n }\n \n return {\n line,\n column,\n offset: text.length\n };\n}\n\n/**\n * Converts a JSON-encoded string into a JavaScript string, interpreting each\n * escape sequence.\n * @param {string} value The text for the token.\n * @param {Token} token The string token to convert into a JavaScript string.\n * @param {boolean} json5 `true` if parsing JSON5, `false` otherwise.\n * @returns {string} A JavaScript string.\n */\nfunction getStringValue(value, token, json5 = false) {\n \n let result = \"\";\n let escapeIndex = value.indexOf(\"\\\\\");\n let lastIndex = 0;\n\n // While there are escapes, interpret them to build up the result\n while (escapeIndex >= 0) {\n\n // append the text that happened before the escape\n result += value.slice(lastIndex, escapeIndex);\n\n // get the character immediately after the \\\n const escapeChar = value.charAt(escapeIndex + 1);\n const escapeCharCode = escapeChar.charCodeAt(0);\n \n // check for the non-Unicode escape sequences first\n if (json5 && json5EscapeToChar.has(escapeCharCode)) {\n result += json5EscapeToChar.get(escapeCharCode);\n lastIndex = escapeIndex + 2;\n } else if (escapeToChar.has(escapeCharCode)) {\n result += escapeToChar.get(escapeCharCode);\n lastIndex = escapeIndex + 2;\n } else if (escapeChar === \"u\") {\n const hexCode = value.slice(escapeIndex + 2, escapeIndex + 6);\n if (hexCode.length < 4 || /[^0-9a-f]/i.test(hexCode)) {\n throw new ErrorWithLocation(\n `Invalid unicode escape \\\\u${ hexCode}.`,\n {\n line: token.loc.start.line,\n column: token.loc.start.column + escapeIndex,\n offset: token.loc.start.offset + escapeIndex\n }\n );\n }\n\n result += String.fromCharCode(parseInt(hexCode, 16));\n lastIndex = escapeIndex + 6;\n } else if (json5 && escapeChar === \"x\") {\n const hexCode = value.slice(escapeIndex + 2, escapeIndex + 4);\n if (hexCode.length < 2 || /[^0-9a-f]/i.test(hexCode)) {\n throw new ErrorWithLocation(\n `Invalid hex escape \\\\x${ hexCode}.`,\n {\n line: token.loc.start.line,\n column: token.loc.start.column + escapeIndex,\n offset: token.loc.start.offset + escapeIndex\n }\n );\n }\n\n result += String.fromCharCode(parseInt(hexCode, 16));\n lastIndex = escapeIndex + 4;\n } else if (json5 && json5LineTerminators.has(escapeCharCode)) {\n lastIndex = escapeIndex + 2;\n\n // we also need to skip \\n after a \\r\n if (escapeChar === \"\\r\" && value.charAt(lastIndex) === \"\\n\") {\n lastIndex++;\n }\n \n } else {\n // all characters can be escaped in JSON5\n if (json5) {\n result += escapeChar;\n lastIndex = escapeIndex + 2;\n } else {\n throw new ErrorWithLocation(\n `Invalid escape \\\\${ escapeChar }.`,\n {\n line: token.loc.start.line,\n column: token.loc.start.column + escapeIndex,\n offset: token.loc.start.offset + escapeIndex\n }\n );\n }\n }\n\n // find the next escape sequence\n escapeIndex = value.indexOf(\"\\\\\", lastIndex);\n }\n\n // get the last segment of the string value\n result += value.slice(lastIndex);\n\n return result;\n}\n\n/**\n * Gets the JavaScript value represented by a JSON token.\n * @param {string} value The text value of the token.\n * @param {Token} token The JSON token to get a value for.\n * @param {boolean} json5 `true` if parsing JSON5, `false` otherwise.\n * @returns {string|boolean|number} A number, string, or boolean.\n * @throws {TypeError} If an unknown token type is found. \n */\nfunction getLiteralValue(value, token, json5 = false) {\n switch (token.type) {\n case \"Boolean\":\n return value === \"true\";\n \n case \"Number\":\n if (json5) {\n\n /*\n * Numbers like -0x1 are converted to NaN by Number(), so we need\n * to handle them separately. Rather than checking for -0x, we can\n * just check if the first character is a minus sign. The same for\n * checking for +0x.\n */\n\n if (value.charCodeAt(0) === 45) { // 45 is the char code for '-'\n return -Number(value.slice(1));\n }\n\n if (value.charCodeAt(0) === 43) { // 43 is the char code for '+'\n return Number(value.slice(1));\n }\n }\n return Number(value);\n\n case \"String\":\n return getStringValue(value.slice(1, -1), token, json5);\n\n default:\n throw new TypeError(`Unknown token type \"${token.type}.`);\n }\n}\n\n//-----------------------------------------------------------------------------\n// Main Function\n//-----------------------------------------------------------------------------\n\n/**\n * \n * @param {string} text The text to parse.\n * @param {ParseOptions} [options] The options object.\n * @returns {DocumentNode} The AST representing the parsed JSON.\n * @throws {Error} When there is a parsing error. \n */\nfunction parse(text, options) {\n\n options = Object.freeze({\n ...DEFAULT_OPTIONS,\n ...options\n });\n\n const tokens = [];\n const tokenizer = new Tokenizer(text, {\n mode: options.mode,\n ranges: options.ranges\n });\n\n const json5 = options.mode === \"json5\";\n const allowTrailingCommas = options.allowTrailingCommas || json5;\n\n /**\n * Returns the next token knowing there are no comments.\n * @returns {number} The next token type or 0 if no next token.\n */\n function nextNoComments() {\n const nextType = tokenizer.next();\n\n if (nextType && options.tokens) {\n tokens.push(tokenizer.token);\n }\n return nextType;\n }\n \n /**\n * Returns the next token knowing there are comments to skip.\n * @returns {number} The next token type or 0 if no next token.\n */\n function nextSkipComments() {\n const nextType = tokenizer.next();\n if (nextType && options.tokens) {\n tokens.push(tokenizer.token);\n }\n\n if (nextType >= tt.LineComment) {\n return nextSkipComments();\n }\n\n return nextType;\n\n }\n\n // determine correct way to evaluate tokens based on presence of comments\n const next = options.mode === \"json\" ? nextNoComments : nextSkipComments;\n\n /**\n * Asserts a token has the given type.\n * @param {number} token The token to check.\n * @param {number} type The token type.\n * @throws {UnexpectedToken} If the token type isn't expected.\n * @returns {void}\n */\n function assertTokenType(token, type) {\n if (token !== type) {\n throw new UnexpectedToken(tokenizer.token);\n }\n }\n\n /**\n * Asserts a token has one of the given types.\n * @param {number} token The token to check.\n * @param {number[]} types The token types.\n * @returns {void}\n * @throws {UnexpectedToken} If the token type isn't expected.\n */ \n function assertTokenTypes(token, types) {\n if (!types.includes(token)) {\n throw new UnexpectedToken(tokenizer.token);\n }\n }\n\n /**\n * Creates a range only if ranges are specified.\n * @param {Location} start The start offset for the range.\n * @param {Location} end The end offset for the range.\n * @returns {{range:[number,number]}|undefined} An object with a \n */\n function createRange(start, end) {\n // @ts-ignore tsc incorrect - options might be undefined\n return options.ranges ? {\n range: [start.offset, end.offset]\n } : undefined;\n }\n\n /**\n * Creates a node for a string, boolean, or number.\n * @param {number} tokenType The token representing the literal. \n * @returns {StringNode|NumberNode|BooleanNode} The node representing\n * the value.\n */\n function createLiteralNode(tokenType) {\n const token = tokenizer.token;\n const range = createRange(token.loc.start, token.loc.end);\n const value = getLiteralValue(\n text.slice(token.loc.start.offset, token.loc.end.offset),\n token,\n json5\n );\n const loc = {\n start: {\n ...token.loc.start\n },\n end: {\n ...token.loc.end\n }\n };\n const parts = { loc, ...range };\n\n switch (tokenType) {\n case tt.String:\n return types.string(/** @type {string} */ (value), parts);\n\n case tt.Number:\n return types.number(/** @type {number} */ (value), parts);\n \n case tt.Boolean:\n return types.boolean(/** @type {boolean} */ (value), parts);\n\n default:\n throw new TypeError(`Unknown token type ${token.type}.`);\n }\n }\n\n /**\n * Creates a node for a JSON5 identifier.\n * @param {Token} token The token representing the identifer. \n * @returns {NaNNode|InfinityNode|IdentifierNode} The node representing\n * the value.\n */\n function createJSON5IdentifierNode(token) {\n const range = createRange(token.loc.start, token.loc.end);\n const identifier = text.slice(token.loc.start.offset, token.loc.end.offset);\n const loc = {\n start: {\n ...token.loc.start\n },\n end: {\n ...token.loc.end\n }\n };\n const parts = { loc, ...range };\n\n // Check for NaN or Infinity\n if (token.type !== \"Identifier\") {\n\n let sign = \"\";\n\n // check if the first character in the token is a plus or minus\n if (identifier[0] === \"+\" || identifier[0] === \"-\") {\n sign = identifier[0];\n }\n\n // check if the token is NaN or Infinity\n return types[identifier.includes(\"NaN\") ? \"nan\" : \"infinity\"](/** @type {Sign} */ (sign), parts);\n }\n return types.identifier(normalizeIdentifier(identifier), parts);\n }\n\n /**\n * Creates a node for a null.\n * @param {Token} token The token representing null. \n * @returns {NullNode} The node representing null.\n */\n function createNullNode(token) {\n const range = createRange(token.loc.start, token.loc.end);\n\n return types.null({\n loc: {\n start: {\n ...token.loc.start\n },\n end: {\n ...token.loc.end\n }\n },\n ...range\n });\n }\n\n\n /**\n * Parses a property in an object.\n * @param {number} tokenType The token representing the property.\n * @returns {MemberNode} The node representing the property.\n * @throws {UnexpectedToken} When an unexpected token is found.\n * @throws {UnexpectedEOF} When the end of the file is reached.\n */\n function parseProperty(tokenType) {\n\n if (json5) {\n assertTokenTypes(tokenType, [tt.String, tt.Identifier, tt.Number]);\n } else {\n assertTokenType(tokenType, tt.String);\n }\n\n const token = tokenizer.token;\n\n // check for -NaN, +NaN, -Infinity, +Infinity, and any number\n if (json5 && tokenType === tt.Number && /[+\\-0-9]/.test(text[token.loc.start.offset])) {\n throw new UnexpectedToken(token);\n }\n\n // TODO: Clean this up a bit\n let key = tokenType === tt.String\n ? /** @type {StringNode} */ (createLiteralNode(tokenType))\n : /** @type {IdentifierNode|NaNNode|InfinityNode} */ (createJSON5IdentifierNode(token));\n\n // in JSON5, need to check for NaN and Infinity and create identifier nodes\n if (json5 && (key.type === \"NaN\" || key.type === \"Infinity\")) {\n\n // NaN and Infinity cannot be signed and be a property key\n if (key.sign !== \"\") {\n throw new UnexpectedToken(tokenizer.token);\n }\n\n key = types.identifier(key.type, { loc: key.loc, ...createRange(key.loc.start, key.loc.end) });\n }\n\n tokenType = next();\n assertTokenType(tokenType, tt.Colon);\n const value = parseValue();\n const range = createRange(key.loc.start, value.loc.end);\n\n return types.member(\n /** @type {StringNode|IdentifierNode} */ (key),\n /** @type {ValueNode} */ (value),\n {\n loc: {\n start: {\n ...key.loc.start\n },\n end: {\n ...value.loc.end\n }\n },\n ...range\n }\n );\n }\n\n /**\n * Parses an object literal.\n * @param {number} firstTokenType The first token type in the object.\n * @returns {ObjectNode} The object node.\n * @throws {UnexpectedEOF} When the end of the file is reached.\n * @throws {UnexpectedToken} When an unexpected token is found.\n */\n function parseObject(firstTokenType) {\n\n // The first token must be a { or else it's an error\n assertTokenType(firstTokenType, tt.LBrace);\n\n const firstToken = tokenizer.token;\n const members = [];\n let tokenType = next();\n\n if (tokenType !== tt.RBrace) {\n do {\n \n // add the value into the array\n members.push(parseProperty(tokenType));\n \n tokenType = next();\n\n if (!tokenType) {\n throw new UnexpectedEOF(members[members.length-1].loc.end);\n }\n \n if (tokenType === tt.Comma) {\n tokenType = next();\n\n /*\n * Trailing commas.\n * So we need to check if the token is a comma,\n * and if so, then we need to check if the next\n * token is a RBrace. If it is, then we need to\n * break out of the loop.\n */\n if (allowTrailingCommas && tokenType === tt.RBrace) {\n break;\n } \n } else {\n break;\n }\n } while (tokenType);\n }\n\n assertTokenType(tokenType, tt.RBrace);\n const lastToken = tokenizer.token;\n const range = createRange(firstToken.loc.start, lastToken.loc.end);\n\n return types.object(members, {\n loc: {\n start: {\n ...firstToken.loc.start\n },\n end: {\n ...lastToken.loc.end\n }\n },\n ...range\n });\n\n }\n\n /**\n * Parses an array literal.\n * @param {number} firstTokenType The first token in the array.\n * @returns {ArrayNode} The array node.\n * @throws {UnexpectedToken} When an unexpected token is found.\n * @throws {UnexpectedEOF} When the end of the file is reached.\n */\n function parseArray(firstTokenType) {\n\n // The first token must be a [ or else it's an error\n assertTokenType(firstTokenType, tt.LBracket);\n\n const firstToken = tokenizer.token;\n const elements = [];\n let tokenType = next();\n \n if (tokenType !== tt.RBracket) {\n\n do {\n\n // add the value into the array\n const value = parseValue(tokenType);\n\n elements.push(types.element(\n /** @type {ValueNode} */ (value),\n { loc: value.loc }\n ));\n\n tokenType = next();\n \n if (tokenType === tt.Comma) {\n tokenType = next();\n\n /*\n * Trailing commas.\n * So we need to check if the token is a comma,\n * and if so, then we need to check if the next\n * token is a RBracket. If it is, then we need to\n * break out of the loop.\n */\n if (allowTrailingCommas && tokenType === tt.RBracket) {\n break;\n } \n } else {\n break;\n }\n } while (tokenType);\n }\n\n assertTokenType(tokenType, tt.RBracket);\n\n const lastToken = tokenizer.token;\n const range = createRange(firstToken.loc.start, lastToken.loc.end);\n\n return types.array(elements, {\n loc: {\n start: {\n ...firstToken.loc.start\n },\n end: {\n ...lastToken.loc.end\n }\n },\n ...range\n });\n\n }\n\n /**\n * Parses a JSON value.\n * @param {number} [tokenType] The token type to parse.\n * @returns {ValueNode|IdentifierNode} The node representing the value.\n */\n function parseValue(tokenType) {\n\n tokenType = tokenType ?? next();\n const token = tokenizer.token;\n \n switch (tokenType) {\n case tt.String:\n case tt.Boolean:\n return createLiteralNode(tokenType);\n\n case tt.Number:\n if (json5) {\n let tokenText = text.slice(token.loc.start.offset, token.loc.end.offset);\n if (tokenText[0] === \"+\" || tokenText[0] === \"-\") {\n tokenText = tokenText.slice(1);\n }\n\n if (tokenText === \"NaN\" || tokenText === \"Infinity\") {\n return createJSON5IdentifierNode(token);\n }\n }\n return createLiteralNode(tokenType);\n\n case tt.Null:\n return createNullNode(token);\n\n case tt.LBrace:\n return parseObject(tokenType);\n\n case tt.LBracket:\n return parseArray(tokenType);\n\n default:\n throw new UnexpectedToken(token);\n }\n\n }\n\n \n const docBody = parseValue();\n \n const unexpectedToken = next();\n if (unexpectedToken) {\n throw new UnexpectedToken(tokenizer.token);\n }\n \n \n const textEndLocation = getEndLocation(text);\n const docParts = {\n loc: {\n start: {\n line: 1,\n column: 1,\n offset: 0\n },\n end: {\n ...textEndLocation\n }\n }\n };\n \n if (options.tokens) {\n docParts.tokens = tokens;\n }\n\n if (options.ranges) {\n docParts.range = [\n docParts.loc.start.offset,\n docParts.loc.end.offset\n ];\n }\n\n return types.document(/** @type {ValueNode} */ (docBody), docParts);\n}\n\n/**\n * @fileoverview Traversal approaches for Momoa JSON AST.\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").TraversalPhase} TraversalPhase */\n/**\n * @typedef {Object} TraversalVisitor\n * @property {(node: Node, parent?: Node) => void} [enter]\n * @property {(node: Node, parent?: Node) => void} [exit]\n */\n\n//-----------------------------------------------------------------------------\n// Data\n//-----------------------------------------------------------------------------\n\nconst childKeys = new Map([\n [\"Document\", [\"body\"]],\n [\"Object\", [\"members\"]],\n [\"Member\", [\"name\", \"value\"]],\n [\"Element\", [\"value\"]],\n [\"Array\", [\"elements\"]],\n [\"String\", []],\n [\"Number\", []],\n [\"Boolean\", []],\n [\"Null\", []],\n [\"NaN\", []],\n [\"Infinity\", []],\n [\"Identifier\", []],\n]);\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/**\n * Determines if a given value is an object.\n * @param {*} value The value to check.\n * @returns {boolean} True if the value is an object, false if not. \n */\nfunction isObject(value) {\n return value && (typeof value === \"object\");\n}\n\n/**\n * Determines if a given value is an AST node.\n * @param {*} value The value to check.\n * @returns {boolean} True if the value is a node, false if not. \n */\nfunction isNode(value) {\n return isObject(value) && (typeof value.type === \"string\");\n}\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\n/**\n * Traverses an AST from the given node.\n * @param {Node} root The node to traverse from \n * @param {TraversalVisitor} visitor An object with an `enter` and `exit` method. \n */\nfunction traverse(root, visitor) {\n\n /**\n * Recursively visits a node.\n * @param {Node} node The node to visit.\n * @param {Node} [parent] The parent of the node to visit.\n * @returns {void}\n */\n function visitNode(node, parent) {\n\n if (typeof visitor.enter === \"function\") {\n visitor.enter(node, parent);\n }\n\n for (const key of childKeys.get(node.type)) {\n const value = node[key];\n\n if (isObject(value)) {\n if (Array.isArray(value)) {\n value.forEach(child => visitNode(child, node));\n } else if (isNode(value)) {\n visitNode(value, node);\n }\n }\n }\n\n if (typeof visitor.exit === \"function\") {\n visitor.exit(node, parent);\n }\n }\n\n visitNode(root);\n}\n\n/**\n * @callback FilterPredicate\n * @param {{node: Node, parent?: Node, phase: TraversalPhase}} item\n * @param {number} index\n * @param {Array<{node: Node, parent?: Node, phase: TraversalPhase}>} array\n * @returns {boolean}\n */\n\n/**\n * Creates an iterator over the given AST.\n * @param {Node} root The root AST node to traverse. \n * @param {FilterPredicate} [filter] A filter function to determine which steps to\n * return;\n * @returns {IterableIterator<{node: Node, parent?: Node, phase: TraversalPhase}>} An iterator over the AST. \n */\nfunction iterator(root, filter = () => true) {\n\n /** @type {Array<{node: Node, parent?: Node, phase: TraversalPhase}>} */\n const traversal = [];\n\n traverse(root, {\n enter(node, parent) {\n traversal.push({ node, parent, phase: \"enter\" });\n },\n exit(node, parent) {\n traversal.push({ node, parent, phase: \"exit\" });\n }\n });\n\n return traversal.filter(filter).values();\n}\n\n/**\n * @fileoverview Evaluator for Momoa AST.\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").AnyNode} AnyNode */\n/** @typedef {import(\"./typedefs.js\").JSONValue} JSONValue */\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\n/**\n * Evaluates a Momoa AST node into a JavaScript value.\n * @param {AnyNode} node The node to interpet.\n * @returns {JSONValue} The JavaScript value for the node. \n */\nfunction evaluate(node) {\n switch (node.type) {\n case \"String\":\n return node.value;\n\n case \"Number\":\n return node.value;\n\n case \"Boolean\":\n return node.value;\n\n case \"Null\":\n return null;\n\n case \"NaN\":\n return NaN;\n \n case \"Infinity\":\n return node.sign === \"-\" ? -Infinity : Infinity;\n\n case \"Identifier\":\n return node.name;\n\n case \"Array\": {\n // const arrayNode = /** @type {ArrayNode} */ (node);\n return node.elements.map(element => evaluate(element.value));\n }\n\n case \"Object\": {\n\n /** @type {{[property: string]: JSONValue}} */\n const object = {};\n\n node.members.forEach(member => {\n object[/** @type {string} */ (evaluate(member.name))] = evaluate(member.value);\n }); \n\n return object;\n } \n\n case \"Document\": {\n return evaluate(node.body);\n }\n\n case \"Element\":\n throw new Error(\"Cannot evaluate array element outside of an array.\");\n\n case \"Member\":\n throw new Error(\"Cannot evaluate object member outside of an object.\");\n\n default:\n // @ts-ignore tsc doesn't know about the type property here?\n throw new Error(`Unknown node type ${ node.type }.`);\n }\n}\n\n/**\n * @fileoverview Printer for Momoa AST.\n * @author Nicholas C. Zakas\n */\n\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/**\n * Prints the string representation of a Boolean node.\n * @param {BooleanNode} node The node to print.\n * @returns {string} The boolean value.\n */\nfunction printBoolean(node) {\n return node.value ? \"true\" : \"false\";\n}\n\n/**\n * Prints the string representation of a null node.\n * @returns {string} The string \"null\".\n */\nfunction printNull() {\n return \"null\";\n}\n\n/**\n * Prints the string representation of a number node.\n * @param {NumberNode} node The node to print.\n * @returns {string} The number value.\n */\nfunction printNumber(node) {\n return node.value.toString();\n}\n\n/**\n * Prints the string representation of a NaN node.\n * @returns {string} The string \"NaN\".\n */\nfunction printNaN() {\n return \"NaN\";\n}\n\n/**\n * Prints the string representation of an Infinity node.\n * @param {InfinityNode} node The node to print.\n * @returns {string} The string \"Infinity\" or \"-Infinity\".\n */\nfunction printInfinity(node) {\n return node.sign + \"Infinity\";\n}\n\n/**\n * Prints the string representation of a string node.\n * @param {StringNode} node The node to print.\n * @returns {string} The string value.\n */\nfunction printString(node) {\n\n let result = \"\\\"\";\n\n // escape all characters that need escaping\n for (const c of node.value) {\n\n const newChar = json5CharToEscape.get(c);\n\n if (newChar) {\n result += \"\\\\\" + newChar;\n continue;\n }\n\n // if it's a double quote, escape it\n if (c === \"\\\"\") {\n result += \"\\\\\\\"\";\n continue;\n }\n\n // if it's a control character, escape it\n if (c < \" \" || c === \"\\u007F\") {\n const hex = c.codePointAt(0).toString(16).toUpperCase();\n result += `\\\\u${\"0000\".substring(hex.length)}${hex}`;\n continue;\n }\n\n // otherwise, just add the character\n result += c;\n\n }\n \n return result + \"\\\"\";\n}\n\n/**\n * Prints the string representation of an identifier node.\n * @param {IdentifierNode} node The node to print.\n * @returns {string} The identifier name.\n */\nfunction printIdentifier(node) {\n return node.name;\n}\n\n/**\n * Prints the string representation of an array node.\n * @param {ArrayNode} node The node to print.\n * @param {string} indent The string to use for indentation.\n * @param {number} indentLevel The current level of indentation.\n * @returns {string} The array value.\n */\nfunction printArray(node, indent, indentLevel) {\n const newLine = indent ? \"\\n\" : \"\";\n const indentString = indent.repeat(indentLevel);\n const elementIndentString = indent.repeat(indentLevel + 1);\n\n return `[${newLine}${\n node.elements.map(element =>\n `${elementIndentString}${printValue(element.value, indent, indentLevel + 1)}`\n ).join(`,${newLine}`)\n }${newLine}${indentString}]`;\n}\n\n/**\n * Prints the string representation of a member node.\n * @param {MemberNode} node The node to print.\n * @param {string} indent The string to use for indentation.\n * @param {number} indentLevel The current level of indentation.\n * @returns {string} The member value.\n */\nfunction printMember(node, indent, indentLevel) {\n const space = indent ? \" \" : \"\";\n return `${printValue(node.name, indent, indentLevel)}:${space}${printValue(node.value, indent, indentLevel + 1)}`;\n}\n\n/**\n * Prints the string representation of an object node.\n * @param {ObjectNode} node The node to print.\n * @param {string} indent The string to use for indentation.\n * @param {number} indentLevel The current level of indentation.\n * @returns {string} The object value.\n */\nfunction printObject(node, indent, indentLevel) {\n const newLine = indent ? \"\\n\" : \"\";\n const indentString = indent.repeat(indentLevel);\n const memberIndentString = indent.repeat(indentLevel + 1);\n\n return `{${newLine}${\n node.members.map(member => \n `${memberIndentString}${printMember(member, indent, indentLevel)}`\n ).join(`,${newLine}`)\n }${newLine}${indentString}}`;\n}\n\n/**\n * Prints the string representation of a node.\n * @param {AnyNode} node The node to print.\n * @param {string} indentString The string to use for indentation.\n * @param {number} indentLevel The current level of indentation.\n * @returns {string} The string representation of the node.\n * @throws {TypeError} If the node type is unknown.\n\n */\nfunction printValue(node, indentString, indentLevel) {\n switch (node.type) {\n case \"String\":\n return printString(node);\n case \"Number\":\n return printNumber(node);\n case \"Boolean\":\n return printBoolean(node);\n case \"Null\":\n return printNull();\n case \"NaN\":\n return printNaN();\n case \"Infinity\":\n return printInfinity(node);\n case \"Identifier\":\n return printIdentifier(node);\n case \"Array\":\n return printArray(node, indentString, indentLevel);\n case \"Object\":\n return printObject(node, indentString, indentLevel);\n case \"Document\":\n return printValue(node.body, indentString, indentLevel);\n default:\n throw new TypeError(`Unknown node type: ${node.type}`);\n }\n}\n\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\n/**\n * Converts a Momoa AST back into a JSON string.\n * @param {AnyNode} node The node to print.\n * @param {Object} options Options for the print.\n * @param {number} [options.indent=0] The number of spaces to indent each line. If\n * greater than 0, then newlines and indents will be added to output. \n * @returns {string} The JSON representation of the AST.\n */\nfunction print(node, { indent = 0 } = {}) {\n\n const indentLevel = 0;\n const indentString = \" \".repeat(indent);\n\n return printValue(node, indentString, indentLevel);\n}\n\nexport { evaluate, iterator, parse, print, tokenize, traverse, types, childKeys as visitorKeys };\n", "/**\n * Finds JSON container depth without building an AST. Strings and escapes are\n * skipped so attacker-controlled brackets inside string values do not charge.\n */\nexport const MAX_SOURCE_PARSER_DEPTH = 512;\n\nexport function exceedsJsonDocumentDepth(text: string, maximum: number): boolean {\n let depth = 0;\n let sawValue = false;\n let inString = false;\n let escaped = false;\n\n for (let index = 0; index < text.length; index += 1) {\n const character = text[index];\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (character === '\\\\') {\n escaped = true;\n } else if (character === '\"') {\n inString = false;\n }\n continue;\n }\n if (character === '\"') {\n inString = true;\n sawValue = true;\n } else if (character === '{' || character === '[') {\n sawValue = true;\n depth += 1;\n if (depth > maximum) return true;\n } else if (character === '}' || character === ']') {\n depth -= 1;\n } else if (!/\\s/.test(character) && character !== ',' && character !== ':') {\n sawValue = true;\n }\n }\n return sawValue && maximum < 1;\n}\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport type { SourceMemberRefV2 } from './source-types';\n\nconst encoder = new TextEncoder();\n\nexport type SourceSlot =\n | { readonly kind: 'ROOT' }\n | { readonly kind: 'ARRAY'; readonly index: number }\n | { readonly kind: 'MEMBER'; readonly nameLexeme: string; readonly occurrence: number };\n\nexport function encodeSourceTuple(parts: readonly string[]): string {\n return parts.map(encodeIdentityPart).join('');\n}\n\nfunction encodeIdentityPart(part: string): string {\n if (!containsLoneSurrogate(part)) {\n const tagged = `N${encoder.encode(part).byteLength}:${part}`;\n return `${encoder.encode(tagged).byteLength}:${tagged}`;\n }\n let codeUnits = '';\n for (let index = 0; index < part.length; index += 1) codeUnits += part.charCodeAt(index).toString(16).padStart(4, '0');\n const tagged = `C${part.length}:${codeUnits}`;\n return `${encoder.encode(tagged).byteLength}:${tagged}`;\n}\n\nfunction containsLoneSurrogate(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) return true;\n index += 1;\n } else if (code >= 0xdc00 && code <= 0xdfff) return true;\n }\n return false;\n}\n\nexport function encodeSourceSlot(slot: SourceSlot): string {\n if (slot.kind === 'ROOT') return 'ROOT';\n if (slot.kind === 'ARRAY') return encodeSourceTuple(['ARRAY', String(slot.index)]);\n return encodeSourceTuple(['MEMBER', slot.nameLexeme, String(slot.occurrence)]);\n}\n\nexport function createSourceAstNodeId(input: {\n readonly occurrencePath: readonly number[];\n readonly slot: string;\n readonly kind: string;\n readonly payload: string;\n}): string {\n const path = encodeSourceTuple(input.occurrencePath.map(String));\n return bytesToHex(sha256(encoder.encode(encodeSourceTuple([\n 'secureflow-source-member-v2', path, input.slot, input.kind, input.payload,\n ]))));\n}\n\nexport function createSourceMemberRef(input: {\n readonly pointer: string;\n readonly occurrencePath: readonly number[];\n readonly slot: SourceSlot;\n readonly kind: string;\n readonly payload: string;\n readonly span: SourceMemberRefV2['span'];\n readonly astNodeId?: string;\n readonly reuseOccurrencePath?: boolean;\n}): SourceMemberRefV2 {\n const occurrencePath = input.reuseOccurrencePath\n ? Object.freeze(input.occurrencePath)\n : Object.freeze([...input.occurrencePath]);\n return Object.freeze({\n pointer: input.pointer,\n occurrencePath,\n astNodeId: input.astNodeId ?? createSourceAstNodeId({\n occurrencePath, slot: encodeSourceSlot(input.slot), kind: input.kind, payload: input.payload,\n }),\n span: input.span,\n });\n}\n", "import type { IdentifierNode, StringNode, ValueNode } from '@humanwhocodes/momoa';\nimport type { SourceMemberRefV2, SourceParseResult, SourceValueV2 } from './source-types';\n\nexport function memberName(node: StringNode | IdentifierNode): string {\n return node.type === 'String' ? node.value : node.name;\n}\n\nexport function sourceKind(node: ValueNode): SourceValueV2['kind'] {\n return node.type === 'Null' ? 'NULL' : node.type.toUpperCase() as SourceValueV2['kind'];\n}\n\nexport function scalarValue(node: ValueNode): string | number | boolean | null {\n if (node.type === 'Null') return null;\n if (node.type === 'Number') {\n if (!Number.isFinite(node.value)) throw new TypeError('Non-finite JSON number');\n return node.value;\n }\n if (node.type === 'String' || node.type === 'Boolean') return node.value;\n throw new TypeError('Unexpected non-JSON scalar');\n}\n\nexport function syntaxContribution(node: ValueNode): number {\n if (node.type === 'Object') return 1 + (node.members.length * 2);\n if (node.type === 'Array') return 1 + node.elements.length;\n return 1;\n}\n\nexport function countDuplicates(names: readonly string[]): number {\n const seen = new Set<string>();\n let count = 0;\n for (const name of names) seen.has(name) ? count += 1 : seen.add(name);\n return count;\n}\n\nexport function sliceNode(text: string, node: { range?: [number, number] }): string {\n if (!node.range) throw new TypeError('Source range missing');\n return text.slice(node.range[0], node.range[1]);\n}\n\nexport function createUtf8OffsetMap(text: string): Uint32Array {\n const offsets = new Uint32Array(text.length + 1);\n let bytes = 0;\n for (let index = 0; index < text.length;) {\n offsets[index] = bytes;\n const codePoint = text.codePointAt(index) ?? 0;\n const width = codePoint > 0xffff ? 2 : 1;\n if (width === 2) offsets[index + 1] = bytes;\n bytes += codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4;\n index += width;\n offsets[index] = bytes;\n }\n return offsets;\n}\n\nexport function sourceSpan(\n node: ValueNode,\n byteOffsets: Uint32Array,\n): SourceMemberRefV2['span'] {\n if (!node.range) throw new TypeError('Source range missing');\n const [start, end] = node.range;\n return Object.freeze({\n start: Object.freeze({\n line: node.loc.start.line,\n column: node.loc.start.column,\n utf16Offset: start,\n utf8ByteOffset: byteOffsets[start],\n }),\n end: Object.freeze({\n line: node.loc.end.line,\n column: node.loc.end.column,\n utf16Offset: end,\n utf8ByteOffset: byteOffsets[end],\n }),\n });\n}\n\nexport function complex(\n cause: 'SYNTAX_NODE_LIMIT' | 'DOCUMENT_DEPTH_LIMIT' | 'MEMBER_ELEMENT_LIMIT' | 'DUPLICATE_KEY_LIMIT' | 'SOURCE_WORK_LIMIT',\n): SourceParseResult {\n return {\n ok: false,\n code: 'WORKFLOW_TOO_COMPLEX',\n cause,\n message: 'Workflow bytes exceed the configured source complexity limit.',\n };\n}\n", "import type { ValueNode } from '@humanwhocodes/momoa';\nimport type { ScannerLimitsV2 } from '@hub/contracts';\nimport { escapeJsonPointerSegment } from '../json-pointer';\nimport {\n createSourceAstNodeId,\n createSourceMemberRef,\n encodeSourceSlot,\n encodeSourceTuple,\n type SourceSlot,\n} from './source-identities';\nimport {\n complex,\n countDuplicates,\n createUtf8OffsetMap,\n memberName,\n scalarValue,\n sliceNode,\n sourceKind,\n sourceSpan,\n syntaxContribution,\n} from './source-tree-helpers';\nimport type {\n SourceMemberRefV2,\n SourceParseResult,\n SourceSpanUsageV2,\n SourceValueV2,\n} from './source-types';\n\nexport type NodeContext = {\n node: ValueNode;\n pointer: string;\n occurrencePath: readonly number[];\n slot: SourceSlot;\n depth: number;\n};\n\nexport type SourceAnalysis = {\n contexts: NodeContext[];\n duplicateCount: number;\n syntaxNodeCount: number;\n sourceWorkUnits: number;\n};\n\ntype NodeIdentity = { astNodeId: string; payload: string };\n\nexport function analyzeSource(\n root: ValueNode,\n text: string,\n limits: ScannerLimitsV2,\n): SourceAnalysis | SourceParseResult {\n const contexts: NodeContext[] = [];\n const pending: NodeContext[] = [{\n node: root, pointer: '', occurrencePath: [], slot: { kind: 'ROOT' }, depth: 1,\n }];\n let duplicateCount = 0;\n let syntaxNodeCount = 1;\n let membersAndElements = 0;\n let sourceWorkUnits = 0;\n\n while (pending.length > 0) {\n const context = pending.pop()!;\n if (context.depth > limits.maxDocumentDepth) return complex('DOCUMENT_DEPTH_LIMIT');\n contexts.push(context);\n syntaxNodeCount += syntaxContribution(context.node);\n if (syntaxNodeCount > limits.maxSyntaxNodes) return complex('SYNTAX_NODE_LIMIT');\n\n const childCount = directChildCount(context.node);\n membersAndElements += childCount;\n if (membersAndElements > limits.maxMembersAndElements) return complex('MEMBER_ELEMENT_LIMIT');\n if (context.node.type === 'Object') {\n duplicateCount += countDuplicates(context.node.members.map((member) => memberName(member.name)));\n if (duplicateCount > limits.maxDuplicateKeys) return complex('DUPLICATE_KEY_LIMIT');\n }\n if (contexts.length === 1) {\n if (context.depth > limits.maxSourceWork) return complex('SOURCE_WORK_LIMIT');\n sourceWorkUnits += context.depth;\n }\n const childDepth = context.depth + 1;\n const childWorkUnits = childCount * childDepth;\n if (sourceWorkUnits > limits.maxSourceWork - childWorkUnits) return complex('SOURCE_WORK_LIMIT');\n sourceWorkUnits += childWorkUnits;\n const children = childContexts(context, text);\n for (let index = children.length - 1; index >= 0; index -= 1) pending.push(children[index]);\n }\n return { contexts, duplicateCount, syntaxNodeCount, sourceWorkUnits };\n}\n\nfunction directChildCount(node: ValueNode): number {\n if (node.type === 'Array') return node.elements.length;\n if (node.type === 'Object') return node.members.length;\n return 0;\n}\n\nexport function buildSourceTree(\n contexts: NodeContext[],\n text: string,\n spanLimit: number,\n): Readonly<{ value: SourceValueV2; usage: SourceSpanUsageV2 }> {\n const identities = new WeakMap<ValueNode, NodeIdentity>();\n for (let index = contexts.length - 1; index >= 0; index -= 1) {\n const context = contexts[index];\n const payload = sourcePayload(context.node, text, identities);\n const astNodeId = createSourceAstNodeId({\n occurrencePath: context.occurrencePath,\n slot: encodeSourceSlot(context.slot),\n kind: sourceKind(context.node),\n payload,\n });\n identities.set(context.node, { astNodeId, payload });\n }\n const retained = new Set(contexts.slice(0, spanLimit).map((context) => context.node));\n const values = new WeakMap<ValueNode, SourceValueV2>();\n const byteOffsets = createUtf8OffsetMap(text);\n for (let index = contexts.length - 1; index >= 0; index -= 1) {\n const context = contexts[index];\n const identity = identities.get(context.node)!;\n const ref = createSourceMemberRef({\n pointer: context.pointer,\n occurrencePath: context.occurrencePath,\n slot: context.slot,\n kind: sourceKind(context.node),\n payload: identity.payload,\n astNodeId: identity.astNodeId,\n reuseOccurrencePath: true,\n span: retained.has(context.node) ? sourceSpan(context.node, byteOffsets) : null,\n });\n values.set(context.node, materializeValue(context.node, text, ref, values));\n }\n return Object.freeze({\n value: values.get(contexts[0].node)!,\n usage: Object.freeze({ examined: contexts.length, omitted: contexts.length - retained.size }),\n });\n}\n\nfunction childContexts(parent: NodeContext, text: string): NodeContext[] {\n if (parent.node.type === 'Array') return parent.node.elements.map((element, index) => ({\n node: element.value,\n pointer: `${parent.pointer}/${index}`,\n occurrencePath: [...parent.occurrencePath, index],\n slot: { kind: 'ARRAY', index },\n depth: parent.depth + 1,\n }));\n if (parent.node.type !== 'Object') return [];\n const seen = new Map<string, number>();\n return parent.node.members.map((member, index) => {\n const name = memberName(member.name);\n const occurrence = seen.get(name) ?? 0;\n seen.set(name, occurrence + 1);\n return {\n node: member.value,\n pointer: `${parent.pointer}/${escapeJsonPointerSegment(name)}`,\n occurrencePath: [...parent.occurrencePath, index],\n slot: { kind: 'MEMBER', nameLexeme: sliceNode(text, member.name), occurrence },\n depth: parent.depth + 1,\n };\n });\n}\n\nfunction materializeValue(\n node: ValueNode,\n text: string,\n ref: SourceMemberRefV2,\n values: WeakMap<ValueNode, SourceValueV2>,\n): SourceValueV2 {\n if (node.type === 'Array') return Object.freeze({\n kind: 'ARRAY',\n ref,\n items: Object.freeze(node.elements.map((element) => values.get(element.value)!)),\n });\n if (node.type === 'Object') {\n const seen = new Map<string, number>();\n const members = node.members.map((member) => {\n const name = memberName(member.name);\n const occurrence = seen.get(name) ?? 0;\n seen.set(name, occurrence + 1);\n const value = values.get(member.value)!;\n return Object.freeze({\n nameLexeme: sliceNode(text, member.name),\n name,\n occurrence,\n ref: value.ref,\n value,\n });\n });\n return Object.freeze({ kind: 'OBJECT', ref, members: Object.freeze(members) });\n }\n return Object.freeze({\n kind: sourceKind(node),\n lexeme: sliceNode(text, node),\n value: scalarValue(node),\n ref,\n }) as SourceValueV2;\n}\n\nfunction sourcePayload(node: ValueNode, text: string, identities: WeakMap<ValueNode, NodeIdentity>): string {\n if (node.type === 'Array') {\n return encodeSourceTuple(node.elements.map((element) => identities.get(element.value)!.astNodeId));\n }\n if (node.type === 'Object') {\n return encodeSourceTuple(node.members.map((member) => identities.get(member.value)!.astNodeId));\n }\n return sliceNode(text, node);\n}\n", "import {\n DEFAULT_SCANNER_LIMITS_V2,\n validateScannerLimitsV2,\n type ScannerLimitsV2,\n} from '@hub/contracts';\n\nconst LIMIT_FIELDS = Object.freeze(Object.getOwnPropertyNames(DEFAULT_SCANNER_LIMITS_V2));\n\nexport function resolveScannerLimits(partial: unknown): ScannerLimitsV2 | undefined {\n try {\n if (partial === undefined) return DEFAULT_SCANNER_LIMITS_V2;\n if (!plainDataRecord(partial)) return undefined;\n const candidate = Object.create(null) as Record<string, unknown>;\n for (const field of LIMIT_FIELDS) candidate[field] = DEFAULT_SCANNER_LIMITS_V2[field as keyof ScannerLimitsV2];\n for (const field of Object.getOwnPropertyNames(partial)) {\n if (!LIMIT_FIELDS.includes(field)) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(partial, field);\n if (!descriptor || !Object.prototype.hasOwnProperty.call(descriptor, 'value')) return undefined;\n candidate[field] = descriptor.value;\n }\n if (Object.getOwnPropertySymbols(partial).length > 0) return undefined;\n const result = validateScannerLimitsV2(candidate);\n return result.ok ? result.limits : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction plainDataRecord(value: unknown): value is object {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return false;\n if (Object.getOwnPropertySymbols(value).length > 0) return false;\n for (const field of Object.getOwnPropertyNames(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, field);\n if (!descriptor || !Object.prototype.hasOwnProperty.call(descriptor, 'value')) return false;\n }\n return true;\n}\n", "import type { ReadonlySourceDocumentV2 } from './source-types';\n\nconst parserDocuments = new WeakSet<object>();\n\nexport function markParsedSourceDocument(document: ReadonlySourceDocumentV2): void {\n parserDocuments.add(document as object);\n}\n\nexport function isParsedSourceDocument(value: unknown): value is ReadonlySourceDocumentV2 {\n return typeof value === 'object' && value !== null && parserDocuments.has(value);\n}\n", "import { parse, type ValueNode } from '@humanwhocodes/momoa';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport type { ScannerLimitsV2 } from '@hub/contracts';\nimport { exceedsJsonDocumentDepth, MAX_SOURCE_PARSER_DEPTH } from './source-preflight';\nimport { analyzeSource, buildSourceTree } from './source-tree';\nimport { resolveScannerLimits } from './scanner-limit-resolution';\nimport { markParsedSourceDocument } from './source-document-provenance';\nimport type { SourceParseResult } from './source-types';\n\nconst INVALID_JSON = Object.freeze({\n ok: false,\n code: 'INVALID_JSON',\n message: 'Workflow bytes are not valid JSON.',\n} as const);\n\nexport function parseSourceDocument(bytes: Uint8Array, partialLimits?: Partial<ScannerLimitsV2>): SourceParseResult {\n try {\n if (!(bytes instanceof Uint8Array)) return INVALID_JSON;\n const limits = resolveScannerLimits(partialLimits);\n if (!limits) return INVALID_JSON;\n return parseSourceDocumentWithLimits(bytes, limits);\n } catch {\n return INVALID_JSON;\n }\n}\n\nfunction parseSourceDocumentWithLimits(bytes: Uint8Array, limits: ScannerLimitsV2): SourceParseResult {\n if (bytes.length > limits.maxBytes) {\n return {\n ok: false,\n code: 'WORKFLOW_TOO_LARGE',\n message: 'Workflow bytes exceed the configured payload limit.',\n };\n }\n const hasBom = bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;\n const payload = hasBom ? bytes.subarray(3) : bytes;\n let text: string;\n try {\n text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(payload);\n } catch {\n return {\n ok: false,\n code: 'UTF8_DECODING_FAILED',\n message: 'Workflow bytes are not valid UTF-8.',\n };\n }\n const effectiveDepth = Math.min(limits.maxDocumentDepth, MAX_SOURCE_PARSER_DEPTH);\n if (exceedsJsonDocumentDepth(text, effectiveDepth)) {\n return {\n ok: false,\n code: 'WORKFLOW_TOO_COMPLEX',\n cause: 'DOCUMENT_DEPTH_LIMIT',\n message: 'Workflow bytes exceed the configured source complexity limit.',\n };\n }\n\n let root: ValueNode;\n try {\n root = parse(text, { mode: 'json', ranges: true }).body;\n } catch {\n return INVALID_JSON;\n }\n let analysis: ReturnType<typeof analyzeSource>;\n try {\n analysis = analyzeSource(root, text, limits);\n } catch {\n return INVALID_JSON;\n }\n if ('ok' in analysis) return analysis;\n\n try {\n const tree = buildSourceTree(analysis.contexts, text, limits.maxStoredSourceSpans);\n const document = Object.freeze({\n rawSha256: bytesToHex(sha256(bytes)),\n utf8Bytes: bytes.length,\n bom: hasBom ? 'UTF8' : 'NONE',\n root: tree.value,\n duplicateCount: analysis.duplicateCount,\n syntaxNodeCount: analysis.syntaxNodeCount,\n });\n markParsedSourceDocument(document);\n return {\n ok: true,\n document,\n sourceWorkUnits: analysis.sourceWorkUnits,\n sourceSpanUsage: tree.usage,\n };\n } catch {\n return INVALID_JSON;\n }\n}\n", "import { SCANNER_LIMITS_V2_SCHEMA_VERSION, type ScannerLimitsV2 } from '@hub/contracts';\nimport type { AnalysisDiagnosticV2 } from '../diagnostics/registry';\nimport { parseSourceDocument } from '../source/source-parser';\nimport type { ReadonlySourceDocumentV2, SourceMemberRefV2, SourcePositionV2 } from '../source/source-types';\nimport type { EdgeRefV2, NodeRefV2 } from '../workflow-v2/security-workflow';\nimport type { CapabilityCandidateV2, FindingCandidateV2, SafeFactV2, SubjectV2, TraceV2 } from '../capabilities/scheduler';\n\ndeclare const scannerAdmissionBrandV2: unique symbol;\nexport type ScannerAdmissionSnapshotV2<T> = Readonly<T> & { readonly [scannerAdmissionBrandV2]: 'private' };\nexport type AdmissionSnapshotResultV2<T> =\n | { ok: true; snapshot: ScannerAdmissionSnapshotV2<T> }\n | { ok: false; code: 'UNSAFE_INPUT' | 'LIMIT_EXCEEDED' };\nexport type ParserOwnedAdmissionBoundaryV2 = {\n fromBoundedBytes(bytes: Uint8Array, limits: ScannerLimitsV2): AdmissionSnapshotResultV2<ReadonlySourceDocumentV2>;\n};\n\nconst admittedSnapshotsV2 = new WeakSet<object>();\nconst unsafeInput = Object.freeze({ ok: false, code: 'UNSAFE_INPUT' } as const);\nconst limitExceeded = Object.freeze({ ok: false, code: 'LIMIT_EXCEEDED' } as const);\nexport function isScannerAdmissionSnapshotV2<T = unknown>(value: unknown): value is ScannerAdmissionSnapshotV2<T> {\n return typeof value === 'object' && value !== null && admittedSnapshotsV2.has(value);\n}\nfunction brandSnapshot<T extends object>(value: T): ScannerAdmissionSnapshotV2<T> {\n admittedSnapshotsV2.add(value);\n if (!isScannerAdmissionSnapshotV2<T>(value)) throw new TypeError();\n return value;\n}\n\nfunction freezeGraph<T extends object>(value: T): T {\n const stack: object[] = [value]; const seen = new Set<object>();\n while (stack.length > 0) {\n const current = stack.pop()!;\n if (seen.has(current)) continue;\n seen.add(current);\n for (const key of Object.getOwnPropertyNames(current)) {\n const descriptor = Object.getOwnPropertyDescriptor(current, key);\n if (descriptor && 'value' in descriptor && descriptor.value !== null && typeof descriptor.value === 'object') stack.push(descriptor.value);\n }\n Object.freeze(current);\n }\n return value;\n}\n\nfunction readLimitNumber(input: object, field: string): number | undefined {\n const descriptor = Object.getOwnPropertyDescriptor(input, field);\n if (!descriptor || !('value' in descriptor) || !Number.isSafeInteger(descriptor.value) || descriptor.value < 0) return undefined;\n return descriptor.value;\n}\nfunction readLimitSchemaVersion(input: object): typeof SCANNER_LIMITS_V2_SCHEMA_VERSION | undefined {\n const descriptor = Object.getOwnPropertyDescriptor(input, 'schemaVersion');\n return descriptor && 'value' in descriptor && descriptor.value === SCANNER_LIMITS_V2_SCHEMA_VERSION ? SCANNER_LIMITS_V2_SCHEMA_VERSION : undefined;\n}\nfunction normalizeLimits(input: unknown): ScannerLimitsV2 | undefined {\n if (typeof input !== 'object' || input === null || Array.isArray(input) || Object.getPrototypeOf(input) !== Object.prototype) return undefined;\n const schemaVersion = readLimitSchemaVersion(input);\n const maxBytes = readLimitNumber(input, 'maxBytes'); const maxNodes = readLimitNumber(input, 'maxNodes');\n const maxEdges = readLimitNumber(input, 'maxEdges'); const maxConnectionDepth = readLimitNumber(input, 'maxConnectionDepth');\n const maxParameterDepth = readLimitNumber(input, 'maxParameterDepth'); const maxParameterLeaves = readLimitNumber(input, 'maxParameterLeaves');\n const workerDeadlineMs = readLimitNumber(input, 'workerDeadlineMs'); const maxSyntaxNodes = readLimitNumber(input, 'maxSyntaxNodes');\n const maxDocumentDepth = readLimitNumber(input, 'maxDocumentDepth'); const maxMembersAndElements = readLimitNumber(input, 'maxMembersAndElements');\n const maxRawEdges = readLimitNumber(input, 'maxRawEdges'); const maxDuplicateKeys = readLimitNumber(input, 'maxDuplicateKeys');\n const maxDiagnostics = readLimitNumber(input, 'maxDiagnostics'); const maxStoredSourceSpans = readLimitNumber(input, 'maxStoredSourceSpans');\n const maxSourceWork = readLimitNumber(input, 'maxSourceWork');\n const maxExpressionTokens = readLimitNumber(input, 'maxExpressionTokens'); const maxCodeSyntaxNodes = readLimitNumber(input, 'maxCodeSyntaxNodes');\n const maxGraphOperations = readLimitNumber(input, 'maxGraphOperations'); const maxTaintStates = readLimitNumber(input, 'maxTaintStates');\n const maxTraceStepsPerFinding = readLimitNumber(input, 'maxTraceStepsPerFinding'); const maxFindings = readLimitNumber(input, 'maxFindings');\n const maxRedactionPatches = readLimitNumber(input, 'maxRedactionPatches'); const maxRedactedArtifactBytes = readLimitNumber(input, 'maxRedactedArtifactBytes');\n const maxEvidenceBytes = readLimitNumber(input, 'maxEvidenceBytes'); const maxSerializedResultBytes = readLimitNumber(input, 'maxSerializedResultBytes');\n const maxRuleOperations = readLimitNumber(input, 'maxRuleOperations');\n if (schemaVersion === undefined || maxDiagnostics === undefined || maxDiagnostics < 1 || maxBytes === undefined || maxNodes === undefined ||\n maxEdges === undefined || maxConnectionDepth === undefined || maxParameterDepth === undefined || maxParameterLeaves === undefined ||\n workerDeadlineMs === undefined || maxSyntaxNodes === undefined || maxDocumentDepth === undefined || maxMembersAndElements === undefined ||\n maxRawEdges === undefined || maxDuplicateKeys === undefined || maxStoredSourceSpans === undefined || maxSourceWork === undefined || maxExpressionTokens === undefined ||\n maxCodeSyntaxNodes === undefined || maxGraphOperations === undefined || maxTaintStates === undefined || maxTraceStepsPerFinding === undefined ||\n maxFindings === undefined || maxRedactionPatches === undefined || maxRedactedArtifactBytes === undefined || maxEvidenceBytes === undefined ||\n maxSerializedResultBytes === undefined || maxRuleOperations === undefined) return undefined;\n return Object.freeze({ schemaVersion, maxBytes, maxNodes, maxEdges, maxConnectionDepth, maxParameterDepth, maxParameterLeaves, workerDeadlineMs,\n maxSyntaxNodes, maxDocumentDepth, maxMembersAndElements, maxRawEdges, maxDuplicateKeys, maxDiagnostics, maxStoredSourceSpans,\n maxSourceWork, maxExpressionTokens, maxCodeSyntaxNodes, maxGraphOperations, maxTaintStates, maxTraceStepsPerFinding, maxFindings, maxRedactionPatches,\n maxRedactedArtifactBytes, maxEvidenceBytes, maxSerializedResultBytes, maxRuleOperations });\n}\n\nfunction fromBoundedBytes(bytes: Uint8Array, limits: ScannerLimitsV2): AdmissionSnapshotResultV2<ReadonlySourceDocumentV2> {\n try {\n const normalizedLimits = normalizeLimits(limits);\n if (normalizedLimits === undefined) return unsafeInput;\n const parsed = parseSourceDocument(bytes, normalizedLimits);\n if (!parsed.ok) return parsed.code === 'WORKFLOW_TOO_LARGE' || parsed.code === 'WORKFLOW_TOO_COMPLEX' ? limitExceeded : unsafeInput;\n return Object.freeze({ ok: true, snapshot: brandSnapshot(freezeGraph(parsed.document)) });\n } catch { return unsafeInput; }\n}\n\nfunction copyPosition(input: SourcePositionV2): SourcePositionV2 {\n return Object.freeze({ line: input.line, column: input.column, utf16Offset: input.utf16Offset, utf8ByteOffset: input.utf8ByteOffset });\n}\nfunction copyMemberRef(input: SourceMemberRefV2): SourceMemberRefV2 {\n const span = input.span === null ? null : Object.freeze({ start: copyPosition(input.span.start), end: copyPosition(input.span.end) });\n return Object.freeze({ pointer: input.pointer, occurrencePath: Object.freeze(input.occurrencePath.map((item) => item)), astNodeId: input.astNodeId, span });\n}\nfunction copyNode(input: NodeRefV2): NodeRefV2 {\n const copy: NodeRefV2 = { ordinal: input.ordinal, source: copyMemberRef(input.source), identityDigest: input.identityDigest };\n if (input.explicitId !== undefined) copy.explicitId = input.explicitId;\n if (input.name !== undefined) copy.name = input.name;\n return Object.freeze(copy);\n}\nfunction copyEdge(input: EdgeRefV2): EdgeRefV2 {\n const copy: EdgeRefV2 = { ordinal: input.ordinal, sourceLabel: input.sourceLabel, connectionType: input.connectionType, sourcePort: input.sourcePort,\n targetPort: input.targetPort, source: copyMemberRef(input.source), resolution: input.resolution };\n if (input.sourceNode !== undefined) copy.sourceNode = copyNode(input.sourceNode);\n if (input.targetNode !== undefined) copy.targetNode = copyNode(input.targetNode);\n if (input.targetLabel !== undefined) copy.targetLabel = input.targetLabel;\n return Object.freeze(copy);\n}\nfunction copySubject(input: SubjectV2): SubjectV2 {\n if (input.kind === 'WORKFLOW') return Object.freeze({ kind: 'WORKFLOW' });\n if (input.kind === 'NODE') return Object.freeze({ kind: 'NODE', node: copyNode(input.node) });\n if (input.kind === 'EDGE') return Object.freeze({ kind: 'EDGE', edge: copyEdge(input.edge) });\n return Object.freeze({ kind: 'SOURCE', source: copyMemberRef(input.source) });\n}\n\ntype SafeFactScalarV2 = string | number | boolean | null;\ntype SafeFactPropertyV2 = SafeFactScalarV2 | readonly SafeFactScalarV2[];\nfunction copyFact(input: SafeFactV2): SafeFactV2 {\n const properties: Record<string, SafeFactPropertyV2> = {};\n for (const key of Object.keys(input.properties)) {\n const value = input.properties[key]; properties[key] = Array.isArray(value) ? Object.freeze(value.map((item) => item)) : value;\n }\n return Object.freeze({ factId: input.factId, kind: input.kind, subject: copySubject(input.subject), properties: Object.freeze(properties) });\n}\nfunction copyFinding(input: FindingCandidateV2): FindingCandidateV2 {\n return Object.freeze({ ruleId: input.ruleId, evidenceClass: input.evidenceClass, conclusion: input.conclusion, applicability: input.applicability,\n subject: copySubject(input.subject), factRefs: Object.freeze(input.factRefs.map((item) => item)), traceRefs: Object.freeze(input.traceRefs.map((item) => item)), remediationId: input.remediationId });\n}\ntype MutableDiagnosticV2 = { -readonly [K in keyof AnalysisDiagnosticV2]: AnalysisDiagnosticV2[K] };\nfunction copyDiagnostic(input: AnalysisDiagnosticV2): AnalysisDiagnosticV2 {\n const copy: MutableDiagnosticV2 = { id: input.id, code: input.code, category: input.category, capabilityId: input.capabilityId,\n aggregateEffect: input.aggregateEffect, assessmentEligible: input.assessmentEligible };\n if (input.location !== undefined) copy.location = copyMemberRef(input.location);\n if (input.observed !== undefined) copy.observed = input.observed;\n if (input.maximum !== undefined) copy.maximum = input.maximum;\n if (input.omitted !== undefined) copy.omitted = input.omitted;\n return Object.freeze(copy);\n}\ntype TraceStepV2 = TraceV2['steps'][number];\ntype MutableTraceStepV2 = { -readonly [K in keyof TraceStepV2]: TraceStepV2[K] };\nfunction copyTraceStep(input: TraceStepV2): TraceStepV2 {\n const copy: MutableTraceStepV2 = { ordinal: input.ordinal, kind: input.kind, subject: copySubject(input.subject), factRefs: Object.freeze(input.factRefs.map((item) => item)) };\n return Object.freeze(copy);\n}\nfunction copyTrace(input: TraceV2): TraceV2 {\n return Object.freeze({ traceId: input.traceId, kind: input.kind, steps: Object.freeze(input.steps.map(copyTraceStep)) });\n}\n\nexport function createSafeFactAdmissionSnapshotV2(fact: SafeFactV2): ScannerAdmissionSnapshotV2<SafeFactV2> {\n return brandSnapshot(freezeGraph(copyFact(fact)));\n}\nexport function createCapabilityCandidateAdmissionSnapshotV2(candidate: CapabilityCandidateV2): ScannerAdmissionSnapshotV2<CapabilityCandidateV2> {\n const copy = { findings: Object.freeze(candidate.findings.map(copyFinding)), diagnostics: Object.freeze(candidate.diagnostics.map(copyDiagnostic)),\n facts: Object.freeze(candidate.facts.map(copyFact)), traces: Object.freeze(candidate.traces.map(copyTrace)),\n seen: candidate.seen, analyzed: candidate.analyzed, skipped: candidate.skipped, omitted: candidate.omitted };\n return brandSnapshot(freezeGraph(Object.freeze(copy)));\n}\nexport const ParserOwnedAdmissionBoundaryV2: ParserOwnedAdmissionBoundaryV2 = Object.freeze({ fromBoundedBytes });\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { canonicalizeJson } from '../canonical-json';\n\nexport type SafePropertyTypeV2 =\n | 'STRING' | 'INTEGER' | 'BOOLEAN' | 'NULLABLE_STRING' | 'STRING_LIST' | 'INTEGER_LIST';\nexport type SafeFactSchemaV2 = Readonly<{\n kind: string; ownerCapabilityId: string;\n properties: Readonly<Record<string, SafePropertyTypeV2>>;\n maxStringBytes: number; maxItems: number;\n sensitivity: 'PUBLIC_METADATA' | 'REDACTED_SECURITY';\n}>;\nexport type SafeFactRegistryV2 = Readonly<{\n schemaVersion: 'scanner-safe-facts-v2'; version: string;\n schemas: readonly SafeFactSchemaV2[]; digest: string;\n}>;\n\nexport type SafeFactEvidenceMappingV2 = Readonly<{\n ruleId: string; ownerCapabilityId: string; evidenceSchemaId: string;\n factKinds: readonly string[]; factProperties: readonly string[];\n factPropertiesByKind: Readonly<Record<string, readonly string[]>>;\n evidenceClass: 'CAPABILITY' | 'CONFIGURATION' | 'SUSPICIOUS_SYNTAX' | 'POTENTIAL_DATAFLOW';\n}>;\n\nexport type SafeFactSubjectKindV2 = 'WORKFLOW' | 'NODE' | 'EDGE' | 'SOURCE';\nexport type SafeFactSpanPolicyV2 = 'NONE' | 'OPTIONAL_HALF_OPEN';\n\nconst frozenList = <T>(values: readonly T[]): readonly T[] => Object.freeze([...values]);\n\nexport const SAFE_FACT_ENUMS_V2: Readonly<Record<string, readonly string[]>> = Object.freeze({\n businessCategory: frozenList(['MANUAL_AUTOMATION', 'WEBHOOK_API', 'SCHEDULED_AUTOMATION', 'DATA_SYNC', 'NOTIFICATION', 'CUSTOM_LOGIC', 'GENERAL_AUTOMATION']),\n confidence: frozenList(['LOW', 'MEDIUM', 'HIGH']), namespaceClass: frozenList(['OFFICIAL_BASE', 'OFFICIAL_SCOPED', 'NON_OFFICIAL']),\n language: frozenList(['JAVASCRIPT', 'PYTHON']), parseState: frozenList(['VERIFIED', 'RECOVERED']), flowKind: frozenList(['TAINT_SINK', 'AGENT_INFLUENCE']),\n sink: frozenList(['SQL', 'COMMAND', 'SSRF', 'HEADER', 'PATH', 'CODE', 'PROMPT']), scheme: frozenList(['HTTP', 'HTTPS', 'UNKNOWN']),\n authorityState: frozenList(['KNOWN', 'UNKNOWN']), valueMode: frozenList(['LITERAL', 'DYNAMIC', 'UNKNOWN']),\n authenticationState: frozenList(['MISSING', 'NONE', 'AUTHENTICATED', 'UNKNOWN']), applicability: frozenList(['APPLICABLE', 'NOT_APPLICABLE', 'UNKNOWN']),\n reviewState: frozenList(['ADMITTED', 'QUARANTINED', 'WITHDRAWN', 'REJECTED']), observation: frozenList(['AUTH_HEADER', 'SECRET_INDICATOR']),\n secretKind: frozenList(['api key', 'password', 'token', 'secret', 'credential', 'authorization', 'cookie', 'bearer token', 'basic auth', 'Stripe API key', 'Google API key', 'AWS access key', 'Slack token', 'GitHub token', 'JWT', 'Anthropic API key', 'OpenAI API key', 'Hugging Face token', 'Replicate API token', 'opaque secret']),\n capability: frozenList(['EXECUTE_COMMAND', 'CUSTOM_CODE', 'WEBHOOK', 'AI_AGENT', 'AI_TOOL']), taintLabel: frozenList(['WEBHOOK_BODY', 'WEBHOOK_QUERY', 'WEBHOOK_HEADER', 'INBOUND_MESSAGE', 'EXTERNAL_HTTP_RESPONSE', 'EXTERNAL_FILE', 'AI_MODEL_OUTPUT']),\n indicator: frozenList(['EVAL', 'FUNCTION_CONSTRUCTOR', 'EXEC', 'DYNAMIC_IMPORT', 'SECRET_ACCESS', 'ENVIRONMENT_ACCESS', 'NETWORK_ACCESS', 'CHILD_PROCESS_METHOD', 'FILESYSTEM_ACCESS', 'SHELL_SUBPROCESS', 'CHILD_PROCESS_REQUIRE', 'CHILD_PROCESS_IMPORT', 'CHILD_PROCESS_DYNAMIC_IMPORT', 'FILESYSTEM_REQUIRE', 'FILESYSTEM_IMPORT', 'FILESYSTEM_DYNAMIC_IMPORT', 'NETWORK_REQUIRE', 'NETWORK_IMPORT', 'NETWORK_DYNAMIC_IMPORT']),\n configurationIndicator: frozenList(['SENSITIVE_KEY', 'SENSITIVE_VALUE']),\n});\n\nexport const SAFE_FACT_SUBJECT_KINDS_V2: Readonly<Record<string, readonly SafeFactSubjectKindV2[]>> = Object.freeze({\n 'workflow.summary.v1': frozenList<SafeFactSubjectKindV2>(['WORKFLOW']), 'workflow.function.v1': frozenList<SafeFactSubjectKindV2>(['WORKFLOW']), 'workflow.risk-summary.v1': frozenList<SafeFactSubjectKindV2>(['WORKFLOW']),\n 'workflow.fingerprint.v1': frozenList<SafeFactSubjectKindV2>(['WORKFLOW']), 'integration.v1': frozenList<SafeFactSubjectKindV2>(['WORKFLOW']), 'node.capability.v2': frozenList<SafeFactSubjectKindV2>(['NODE']),\n 'node.configuration.v2': frozenList<SafeFactSubjectKindV2>(['SOURCE']), 'code.indicator.v2': frozenList<SafeFactSubjectKindV2>(['SOURCE']), 'dataflow.summary.v2': frozenList<SafeFactSubjectKindV2>(['SOURCE', 'NODE']),\n 'destination.v2': frozenList<SafeFactSubjectKindV2>(['SOURCE']), 'ingress.v2': frozenList<SafeFactSubjectKindV2>(['NODE']), 'advisory.applicability.v2': frozenList<SafeFactSubjectKindV2>(['WORKFLOW']),\n});\n\nexport const SAFE_FACT_SPAN_POLICIES_V2: Readonly<Record<string, SafeFactSpanPolicyV2>> = Object.freeze({\n 'workflow.summary.v1': 'NONE', 'workflow.function.v1': 'NONE', 'workflow.risk-summary.v1': 'NONE', 'workflow.fingerprint.v1': 'NONE',\n 'integration.v1': 'NONE', 'node.capability.v2': 'OPTIONAL_HALF_OPEN', 'node.configuration.v2': 'OPTIONAL_HALF_OPEN',\n 'code.indicator.v2': 'OPTIONAL_HALF_OPEN', 'dataflow.summary.v2': 'OPTIONAL_HALF_OPEN', 'destination.v2': 'OPTIONAL_HALF_OPEN',\n 'ingress.v2': 'OPTIONAL_HALF_OPEN', 'advisory.applicability.v2': 'NONE',\n});\n\nexport const SAFE_FACT_REQUIRED_PROPERTIES_V2: Readonly<Record<string, readonly string[]>> = Object.freeze({\n 'workflow.summary.v1': frozenList(['connectionCount']), 'workflow.function.v1': frozenList(['basicPurpose', 'triggerDescription', 'dataFlowSummary', 'businessCategory', 'confidence']),\n 'workflow.risk-summary.v1': frozenList(['topRisks', 'dataExposure', 'complexityDrivers']), 'workflow.fingerprint.v1': frozenList(['value']),\n 'integration.v1': frozenList(['service', 'usage', 'nodeTypes', 'nodeCount', 'riskNotes']), 'node.capability.v2': frozenList(['nodeType', 'nodePackage', 'namespaceClass', 'capabilities', 'toolCount', 'contextCount']),\n 'node.configuration.v2': frozenList(['observation']), 'code.indicator.v2': frozenList(['language', 'indicator', 'start', 'end', 'parseState']),\n 'dataflow.summary.v2': frozenList(['flowKind', 'propertyPathComplete', 'humanGatePresent', 'humanGateDominates', 'taintLabels']),\n 'destination.v2': frozenList(['parameterPath', 'scheme', 'hostname', 'authorityState', 'valueMode']), 'ingress.v2': frozenList(['authentication', 'authenticationState', 'legacyAuthenticated']),\n 'advisory.applicability.v2': frozenList(['advisoryId', 'applicability', 'reviewState', 'matchedPrerequisites', 'unknownPrerequisites']),\n});\n\nconst STRING_BYTES = 4_096;\nconst schema = (\n kind: string, ownerCapabilityId: string,\n properties: Record<string, SafePropertyTypeV2>,\n sensitivity: SafeFactSchemaV2['sensitivity'],\n): SafeFactSchemaV2 => Object.freeze({\n kind, ownerCapabilityId, properties: Object.freeze(properties),\n maxStringBytes: STRING_BYTES, maxItems: STRING_BYTES, sensitivity,\n});\n\nconst schemas: readonly SafeFactSchemaV2[] = Object.freeze([\n schema('workflow.summary.v1', 'workflow-insights', { connectionCount: 'INTEGER' }, 'PUBLIC_METADATA'),\n schema('workflow.function.v1', 'workflow-insights', {\n basicPurpose: 'STRING', triggerDescription: 'STRING', dataFlowSummary: 'STRING',\n businessCategory: 'STRING', confidence: 'STRING',\n }, 'PUBLIC_METADATA'),\n schema('workflow.risk-summary.v1', 'workflow-insights', {\n topRisks: 'STRING_LIST', dataExposure: 'STRING', complexityDrivers: 'STRING_LIST',\n }, 'REDACTED_SECURITY'),\n schema('workflow.fingerprint.v1', 'source-normalization', { value: 'STRING' }, 'PUBLIC_METADATA'),\n schema('integration.v1', 'workflow-insights', {\n service: 'STRING', usage: 'STRING', nodeTypes: 'STRING_LIST', nodeCount: 'INTEGER', riskNotes: 'STRING_LIST',\n }, 'REDACTED_SECURITY'),\n schema('node.capability.v2', 'structural-policies', {\n nodeType: 'STRING', nodePackage: 'STRING', namespaceClass: 'STRING', capabilities: 'STRING_LIST',\n toolCount: 'INTEGER', contextCount: 'INTEGER',\n }, 'REDACTED_SECURITY'),\n schema('node.configuration.v2', 'structural-policies', {\n observation: 'STRING', header: 'NULLABLE_STRING', literalValue: 'BOOLEAN', parameterPath: 'STRING',\n secretKind: 'STRING', indicator: 'STRING', hasLiteralValue: 'BOOLEAN',\n }, 'REDACTED_SECURITY'),\n schema('code.indicator.v2', 'expression-security', {\n language: 'STRING', indicator: 'STRING', member: 'STRING', start: 'INTEGER', end: 'INTEGER', parseState: 'STRING',\n }, 'REDACTED_SECURITY'),\n schema('dataflow.summary.v2', 'graph-semantics', {\n flowKind: 'STRING', sink: 'STRING', parameterPath: 'STRING', referenceRoot: 'STRING', propertyPath: 'STRING',\n sourceNodeId: 'STRING', sourceNodeName: 'STRING', propertyPathComplete: 'BOOLEAN',\n humanGatePresent: 'BOOLEAN', humanGateDominates: 'BOOLEAN', taintLabels: 'STRING_LIST',\n }, 'REDACTED_SECURITY'),\n schema('destination.v2', 'structural-policies', {\n parameterPath: 'STRING', scheme: 'STRING', hostname: 'NULLABLE_STRING', authorityState: 'STRING', valueMode: 'STRING',\n }, 'REDACTED_SECURITY'),\n schema('ingress.v2', 'structural-policies', {\n authentication: 'NULLABLE_STRING', authenticationState: 'STRING', legacyAuthenticated: 'BOOLEAN',\n }, 'REDACTED_SECURITY'),\n schema('advisory.applicability.v2', 'assessment', {\n advisoryId: 'STRING', applicability: 'STRING', reviewState: 'STRING',\n matchedPrerequisites: 'STRING_LIST', unknownPrerequisites: 'STRING_LIST',\n }, 'REDACTED_SECURITY'),\n]);\n\nconst mapping = (\n ruleId: string, ownerCapabilityId: string, evidenceSchemaId: string,\n factKinds: readonly string[], factProperties: readonly string[],\n evidenceClass: SafeFactEvidenceMappingV2['evidenceClass'],\n factPropertiesByKind: Readonly<Record<string, readonly string[]>> = Object.fromEntries(factKinds.map((kind) => [kind, factProperties])),\n): SafeFactEvidenceMappingV2 => Object.freeze({\n ruleId, ownerCapabilityId, evidenceSchemaId,\n factKinds: Object.freeze([...factKinds]), factProperties: Object.freeze([...factProperties]),\n factPropertiesByKind: Object.freeze(Object.fromEntries(Object.entries(factPropertiesByKind).map(([kind, properties]) => [kind, Object.freeze([...properties])]))) as Readonly<Record<string, readonly string[]>>,\n evidenceClass,\n});\n\nexport const SAFE_FACT_EVIDENCE_MAPPINGS_V2: readonly SafeFactEvidenceMappingV2[] = Object.freeze([\n mapping('N8N_EXECUTE_COMMAND', 'structural-policies', 'v1.node-type', ['node.capability.v2'], ['nodeType'], 'CAPABILITY'),\n mapping('N8N_CODE_NODE', 'structural-policies', 'v1.node-type', ['node.capability.v2'], ['nodeType'], 'CAPABILITY'),\n mapping('RAW_AUTH_HEADER', 'structural-policies', 'v1.auth-header', ['node.configuration.v2'], ['header', 'literalValue'], 'CONFIGURATION'),\n mapping('RAW_SECRET_INDICATOR', 'structural-policies', 'v1.secret-indicator', ['node.configuration.v2'], ['parameterPath', 'secretKind', 'indicator', 'hasLiteralValue'], 'CONFIGURATION'),\n mapping('UNAPPROVED_DOMAIN', 'structural-policies', 'v1.domain', ['destination.v2'], ['hostname'], 'CONFIGURATION'),\n mapping('UNKNOWN_NODE_PACKAGE', 'structural-policies', 'v1.node-package', ['node.capability.v2'], ['nodeType', 'nodePackage'], 'CONFIGURATION'),\n mapping('WEBHOOK_EXPOSURE', 'structural-policies', 'v1.webhook-auth', ['ingress.v2'], ['authentication'], 'CONFIGURATION'),\n mapping('JAVASCRIPT_DYNAMIC_EXECUTION', 'javascript-security', 'v1.code-indicator', ['code.indicator.v2'], ['indicator', 'member', 'start', 'end'], 'SUSPICIOUS_SYNTAX'),\n mapping('PYTHON_DYNAMIC_EXECUTION', 'python-security', 'v1.code-indicator', ['code.indicator.v2'], ['indicator', 'member', 'start', 'end'], 'SUSPICIOUS_SYNTAX'),\n mapping('TAINTED_COMMAND', 'taint-integrity', 'v1.taint', ['dataflow.summary.v2'], ['sink', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'taintLabels', 'sourceNodeId', 'sourceNodeName'], 'POTENTIAL_DATAFLOW', { 'dataflow.summary.v2': ['sink', 'taintLabels', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'sourceNodeId', 'sourceNodeName'] }),\n mapping('TAINTED_SQL_QUERY', 'taint-integrity', 'v1.taint', ['dataflow.summary.v2'], ['sink', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'taintLabels', 'sourceNodeId', 'sourceNodeName'], 'POTENTIAL_DATAFLOW', { 'dataflow.summary.v2': ['sink', 'taintLabels', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'sourceNodeId', 'sourceNodeName'] }),\n mapping('TAINTED_REQUEST_URL', 'taint-integrity', 'v1.taint', ['dataflow.summary.v2'], ['sink', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'taintLabels', 'sourceNodeId', 'sourceNodeName'], 'POTENTIAL_DATAFLOW', { 'dataflow.summary.v2': ['sink', 'taintLabels', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'sourceNodeId', 'sourceNodeName'] }),\n mapping('TAINTED_FILE_PATH', 'taint-integrity', 'v1.taint', ['dataflow.summary.v2'], ['sink', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'taintLabels', 'sourceNodeId', 'sourceNodeName'], 'POTENTIAL_DATAFLOW', { 'dataflow.summary.v2': ['sink', 'taintLabels', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'sourceNodeId', 'sourceNodeName'] }),\n mapping('TAINTED_CODE_INPUT', 'taint-integrity', 'v1.taint', ['dataflow.summary.v2'], ['sink', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'taintLabels', 'sourceNodeId', 'sourceNodeName'], 'POTENTIAL_DATAFLOW', { 'dataflow.summary.v2': ['sink', 'taintLabels', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'sourceNodeId', 'sourceNodeName'] }),\n mapping('TAINTED_REQUEST_HEADER', 'taint-integrity', 'v1.taint', ['dataflow.summary.v2'], ['sink', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'taintLabels', 'sourceNodeId', 'sourceNodeName'], 'POTENTIAL_DATAFLOW', { 'dataflow.summary.v2': ['sink', 'taintLabels', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'sourceNodeId', 'sourceNodeName'] }),\n mapping('TAINTED_AI_PROMPT', 'taint-integrity', 'v1.taint', ['dataflow.summary.v2'], ['sink', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'taintLabels', 'sourceNodeId', 'sourceNodeName'], 'POTENTIAL_DATAFLOW', { 'dataflow.summary.v2': ['sink', 'taintLabels', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'sourceNodeId', 'sourceNodeName'] }),\n mapping('AI_AGENT_UNGATED_TOOL', 'agentic-control', 'v1.agent-control', ['node.capability.v2', 'dataflow.summary.v2'], ['toolCount', 'contextCount', 'taintLabels', 'humanGatePresent', 'humanGateDominates'], 'CAPABILITY', { 'node.capability.v2': ['toolCount', 'contextCount'], 'dataflow.summary.v2': ['taintLabels', 'humanGatePresent', 'humanGateDominates'] }),\n]);\n\nconst body = Object.freeze({ schemaVersion: 'scanner-safe-facts-v2' as const, version: '2.0.0', schemas });\nexport const SAFE_FACT_REGISTRY_V2: SafeFactRegistryV2 = Object.freeze({\n ...body, digest: bytesToHex(sha256(new TextEncoder().encode(canonicalizeJson(body)))),\n});\n\nconst authorityBody = Object.freeze({\n ...body, enums: SAFE_FACT_ENUMS_V2, subjects: SAFE_FACT_SUBJECT_KINDS_V2, spans: SAFE_FACT_SPAN_POLICIES_V2,\n requiredProperties: SAFE_FACT_REQUIRED_PROPERTIES_V2, evidenceMappings: SAFE_FACT_EVIDENCE_MAPPINGS_V2,\n});\nexport const SAFE_FACT_AUTHORITY_DIGEST_V2 = bytesToHex(sha256(new TextEncoder().encode(canonicalizeJson(authorityBody))));\n", "import type { ScannerLimitsV2 } from '@hub/contracts';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { canonicalizeJson } from '../canonical-json';\nimport { createEdgeIdentityDigest, createNodeIdentityDigest } from '../workflow-v2/node-edge-identity';\nimport type { SafeFactV2, SubjectV2 } from '../capabilities/scheduler';\nimport type { EdgeRefV2, NodeRefV2 } from '../workflow-v2/security-workflow';\nimport type { SourceMemberRefV2, SourcePositionV2, SourceSpanV2 } from '../source/source-types';\nimport { createSafeFactAdmissionSnapshotV2, isScannerAdmissionSnapshotV2 } from '../admission/snapshot';\nimport {\n SAFE_FACT_ENUMS_V2, SAFE_FACT_REGISTRY_V2, SAFE_FACT_REQUIRED_PROPERTIES_V2, SAFE_FACT_SPAN_POLICIES_V2,\n SAFE_FACT_SUBJECT_KINDS_V2, type SafeFactSchemaV2,\n} from './safe-fact-registry';\n\nexport type SafeFactRejectionReasonV2 = 'UNKNOWN_FACT_KIND' | 'UNKNOWN_PROPERTY' | 'INVALID_PROPERTY' | 'INVALID_SUBJECT' | 'FORBIDDEN_CONTENT' | 'LIMIT_EXCEEDED' | 'UNSAFE_INPUT' | 'REGISTRY_MISMATCH';\nexport type SafeFactValidationResultV2 = Readonly<{ ok: true; fact: SafeFactV2 } | { ok: false; code: 'SAFE_FACT_REJECTED'; reason: SafeFactRejectionReasonV2 }>;\nexport type SafeFactSubjectV2 = Readonly<SubjectV2>;\ntype Bad = SafeFactRejectionReasonV2;\ntype Property = string | number | boolean | null | readonly (string | number | boolean | null)[];\ntype RecordValue = Record<string, unknown>;\n\nconst LIMITS = ['schemaVersion', 'maxBytes', 'maxNodes', 'maxEdges', 'maxConnectionDepth', 'maxParameterDepth', 'maxParameterLeaves', 'workerDeadlineMs', 'maxSyntaxNodes', 'maxDocumentDepth', 'maxMembersAndElements', 'maxRawEdges', 'maxDuplicateKeys', 'maxDiagnostics', 'maxStoredSourceSpans', 'maxSourceWork', 'maxExpressionTokens', 'maxCodeSyntaxNodes', 'maxGraphOperations', 'maxTaintStates', 'maxTraceStepsPerFinding', 'maxFindings', 'maxRedactionPatches', 'maxRedactedArtifactBytes', 'maxEvidenceBytes', 'maxSerializedResultBytes', 'maxRuleOperations'] as const;\nconst FACT_KEYS = ['factId', 'kind', 'subject', 'properties'];\nconst SECRET = /\\bsecureflow[-_ ]?token\\b|\\b(?:sk[-_]?(?:live|test|proj)[-_][\\w-]+|AIza[\\w-]{35}|AKIA[0-9A-Z]{16}|eyJ[\\w-]{12,}\\.[\\w-]{8,}|(?:api[ _-]*key|password|secret|credential|authorization|cookie|bearer(?:[ _-]*token)?|basic[ _-]*auth|access[ _-]*(?:key|token)|token)\\s*[:=]\\s*[^\\s,;]+|[A-Za-z][\\w-]*(?:api[ _-]*key|password|secret|credential|authorization|cookie|bearer(?:[ _-]*token)?|basic[ _-]*auth|access[ _-]*(?:key|token))\\s*[:=])/i;\nconst CODE = /\\b(?:require|import|export|const|let|var|function|return|class)\\b|\\bprocess\\.env\\b|\\bconsole\\.[A-Za-z_$][\\w$]*\\s*\\(|\\b[A-Za-z_$][\\w$]*\\.[A-Za-z_$][\\w$]*\\s*\\(|\\(\\s*[\"']/;\nconst PATH = /(?:^|[/\\\\])\\.\\.(?:[/\\\\]|$)|^(?:[/\\\\]|~[/\\\\]|[A-Za-z]:[/\\\\]|\\\\\\\\)/;\nconst PROSE = /\\b(?:source\\s+(?:code|snippet|prose|text)|snippet\\s+(?:code|prose|text))\\b|\\b(?:source|snippet)\\s*[:=]|(?:https?|ftp):\\/\\/|\\bAuthorization\\s*:|\\b(?:DROP\\s+TABLE|DELETE\\s+FROM|INSERT\\s+INTO|UPDATE\\s+\\w+\\s+SET|SELECT\\s+.+\\s+FROM)\\b/i;\nfunction fail(reason: Bad): never { throw reason; }\nexport function readPlainRecord(input: unknown, allowed: readonly string[], required: readonly string[] = allowed, rejectSymbols = true): RecordValue { const value = record(input, allowed, 'UNKNOWN_PROPERTY'); if (!rejectSymbols && Object.getOwnPropertySymbols(value).length !== 0) fail('UNSAFE_INPUT'); for (const key of required) data(value, key, 'INVALID_PROPERTY'); return value; }\nexport function readArrayLength(input: unknown, maximum: number, dense = true): number { if (!Array.isArray(input) || Object.getPrototypeOf(input) !== Array.prototype) fail('UNSAFE_INPUT'); const descriptor = Object.getOwnPropertyDescriptor(input, 'length'); if (!descriptor || !('value' in descriptor)) fail('UNSAFE_INPUT'); const length = integer(descriptor.value, 0, 'UNSAFE_INPUT'); if (length > maximum) fail('LIMIT_EXCEEDED'); if (dense) readDenseArray(input, maximum); return length; }\nexport function readArrayItem(input: unknown, index: number): unknown { if (!Array.isArray(input) || Object.getPrototypeOf(input) !== Array.prototype) fail('UNSAFE_INPUT'); return data(input, String(index), 'UNSAFE_INPUT'); }\nexport function readDenseArray(input: unknown, maximum: number): unknown[] { const length = readArrayLength(input, maximum, false); const names = Object.getOwnPropertyNames(input as object); if (names.length !== length + 1 || Object.getOwnPropertySymbols(input as object).length !== 0) fail('UNSAFE_INPUT'); for (const name of names) if (name !== 'length' && (!/^(0|[1-9]\\d*)$/.test(name) || Number(name) >= length)) fail('UNSAFE_INPUT'); const output: unknown[] = []; for (let index = 0; index < length; index += 1) output.push(readArrayItem(input, index)); return output; }\nexport function readSourceMemberRef(input: unknown, limits: ScannerLimitsV2): SourceMemberRefV2 { return sourceRef(input, { maxMembersAndElements: limits.maxMembersAndElements, maxStoredSourceSpans: limits.maxStoredSourceSpans }, true); }\nexport function readSubject(input: unknown, limits: ScannerLimitsV2): SafeFactSubjectV2 { return subject(input, '', { maxNodes: limits.maxNodes, maxMembersAndElements: limits.maxMembersAndElements, maxStoredSourceSpans: limits.maxStoredSourceSpans }); }\nexport function freezeData<T>(value: T): T { if (value !== null && typeof value === 'object') { for (const key of Object.getOwnPropertyNames(value)) { const descriptor = Object.getOwnPropertyDescriptor(value, key); if (descriptor && 'value' in descriptor) freezeData(descriptor.value); } Object.freeze(value); } return value; }\nfunction data(input: object, key: string, missing: Bad = 'UNSAFE_INPUT'): unknown { const descriptor = Object.getOwnPropertyDescriptor(input, key); if (!descriptor) fail(missing); if (!('value' in descriptor)) fail('UNSAFE_INPUT'); return descriptor.value; }\nfunction record(input: unknown, allowed: readonly string[], unknownReason: Bad, maximum?: number): RecordValue {\n if (input === null || typeof input !== 'object' || Array.isArray(input) || Object.getPrototypeOf(input) !== Object.prototype) fail('UNSAFE_INPUT');\n const value = input as RecordValue; const names = Object.getOwnPropertyNames(value);\n if (maximum !== undefined && names.length > maximum) fail('LIMIT_EXCEEDED'); if (Object.getOwnPropertySymbols(value).length !== 0) fail('UNSAFE_INPUT');\n for (const name of names) if (!allowed.includes(name)) fail(unknownReason); for (const name of names) data(value, name);\n return value;\n}\nfunction exactRecord(input: unknown, keys: readonly string[], reason: Bad): RecordValue { const value = record(input, keys, reason); if (Object.getOwnPropertyNames(value).length !== keys.length) fail(reason); return value; }\nfunction integer(input: unknown, minimum = 0, reason: Bad = 'INVALID_PROPERTY'): number { if (typeof input !== 'number' || !Number.isSafeInteger(input) || input < minimum) fail(reason); return input; }\nfunction utf8Bytes(value: string, maximum: number): number {\n let bytes = 0;\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index); const next = value.charCodeAt(index + 1);\n if (code === 0 || code >= 0xdc00 && code <= 0xdfff || code >= 0xd800 && code <= 0xdbff && (Number.isNaN(next) || next < 0xdc00 || next > 0xdfff)) fail('FORBIDDEN_CONTENT');\n if (code >= 0xd800) { bytes += 4; index += 1; } else bytes += code <= 0x7f ? 1 : code <= 0x7ff ? 2 : 3;\n if (bytes > maximum) fail('LIMIT_EXCEEDED');\n } return bytes; }\nfunction stringValue(input: unknown, maximum: number): string { if (typeof input !== 'string') fail('INVALID_PROPERTY'); utf8Bytes(input, maximum); return input; }\nfunction safeText(input: unknown, maximum: number): string { const value = stringValue(input, maximum); if (SECRET.test(value) || PROSE.test(value) || PATH.test(value) || CODE.test(value)) fail('FORBIDDEN_CONTENT'); return value; }\n// A display name is text the user chose, so every visible class is admissible: letters, marks,\n// numbers, punctuation, symbols, and spaces. Only the invisible classes stay refused \u2014 control,\n// format, surrogate, private-use, unassigned, and line/paragraph separators \u2014 with the two text\n// joiners exempted because ZWJ and ZWNJ compose real scripts and emoji sequences. `INVISIBLE`\n// exempts them by inspection, so `JOINERS_ONLY` keeps an all-joiner string (invisible content) out.\nconst INVISIBLE = /(?![\\u200C\\u200D])[\\p{C}\\p{Zl}\\p{Zp}]/u;\nconst JOINERS_ONLY = /^[\\u200C\\u200D]*$/u;\nfunction display(input: unknown, maximum: number): string { const value = safeText(input, maximum); if (INVISIBLE.test(value) || JOINERS_ONLY.test(value)) fail('FORBIDDEN_CONTENT'); return value; }\nfunction pointer(input: unknown): string { const value = stringValue(input, 2_048); if (!/^(?:|\\/(?:[^~]|~0|~1)*)$/.test(value)) fail('INVALID_PROPERTY'); return value; }\nfunction field(kind: string, key: string, input: unknown, maximum: number): string {\n if (key === 'member') { const value = stringValue(input, maximum); if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(value) || SECRET.test(value)) fail('FORBIDDEN_CONTENT'); return value; }\n if (key === 'header') { const value = stringValue(input, maximum); if (!/^[A-Za-z][A-Za-z0-9-]{0,62}$/.test(value)) fail('FORBIDDEN_CONTENT'); return value; }\n if (key === 'parameterPath' || key === 'propertyPath') return pointer(input);\n if (key === 'referenceRoot') { const value = stringValue(input, maximum); const parts = value.split('.'); const first = parts.shift() ?? ''; const valid = (/^\\$[A-Za-z_][A-Za-z0-9_]*$/.test(first) || /^[A-Z][A-Z0-9_]*$/.test(first)) && parts.every((part) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(part)); if (!valid) fail('FORBIDDEN_CONTENT'); return value; }\n if (key === 'nodeType' || key === 'nodeTypes') { const value = stringValue(input, maximum); if (!/^@?[A-Za-z0-9][A-Za-z0-9._/@-]*\\.[A-Za-z0-9_$-]+$/.test(value) || SECRET.test(value)) fail('FORBIDDEN_CONTENT'); return value; }\n if (key === 'nodePackage') { const value = stringValue(input, maximum); if (!/^@?[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(value) || SECRET.test(value)) fail('FORBIDDEN_CONTENT'); return value; }\n if (key === 'sourceNodeId') { const value = stringValue(input, maximum); if (!/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/.test(value) || SECRET.test(value)) fail('FORBIDDEN_CONTENT'); return value; }\n if (key === 'sourceNodeName' || key === 'sourceLabel' || key === 'targetLabel' || key === 'connectionType') return display(input, maximum);\n if (kind === 'integration.v1' && key === 'service') { const value = display(input, maximum); if (/\\b(?:api[ _-]*key|password|secret|credential|authorization|cookie|bearer|basic auth|token)\\b/i.test(value)) fail('FORBIDDEN_CONTENT'); return value; }\n if (kind === 'advisory.applicability.v2' && ['advisoryId', 'matchedPrerequisites', 'unknownPrerequisites'].includes(key)) { const value = stringValue(input, maximum); if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/.test(value) || /(?:https?|ftp):\\/\\//i.test(value) || /\\b\\d+\\.\\d+\\.\\d+[-~^]\\d+\\.\\d+\\.\\d+\\b/.test(value)) fail('FORBIDDEN_CONTENT'); return value; }\n return safeText(input, maximum);\n}\nfunction enumValue(input: unknown, key: string, kind: string, maximum: number): string { const value = stringValue(input, maximum); const enumKey = kind === 'node.configuration.v2' && key === 'indicator' ? 'configurationIndicator' : key === 'capabilities' ? 'capability' : key === 'taintLabels' ? 'taintLabel' : key; const values = SAFE_FACT_ENUMS_V2[enumKey]; if (values === undefined || !values.includes(value)) fail('INVALID_PROPERTY'); return value; }\nfunction boundedLimit(input: unknown, key: string): number {\n if (input === null || typeof input !== 'object' || Array.isArray(input) || Object.getPrototypeOf(input) !== Object.prototype) fail('UNSAFE_INPUT');\n const value = data(input, key);\n if (key === 'schemaVersion') { if (value !== 'scanner-limits-v2') fail('UNSAFE_INPUT'); return 0; }\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0 || key === 'maxDiagnostics' && value < 1) fail('UNSAFE_INPUT');\n return value;\n}\nfunction limitsSnapshot(input: unknown): Record<string, number> { const result: Record<string, number> = {}; for (const key of LIMITS) result[key] = boundedLimit(input, key); return result; }\nfunction arrayValue(input: unknown, maximum: number): unknown[] {\n if (!Array.isArray(input) || Object.getPrototypeOf(input) !== Array.prototype) fail('UNSAFE_INPUT');\n const lengthDescriptor = Object.getOwnPropertyDescriptor(input, 'length'); if (!lengthDescriptor || !('value' in lengthDescriptor)) fail('UNSAFE_INPUT'); const length = integer(lengthDescriptor.value, 0, 'UNSAFE_INPUT'); if (length > maximum) fail('LIMIT_EXCEEDED');\n const names = Object.getOwnPropertyNames(input); if (names.length !== length + 1 || Object.getOwnPropertySymbols(input).length !== 0) fail('UNSAFE_INPUT'); for (const name of names) if (name !== 'length' && (!/^(0|[1-9]\\d*)$/.test(name) || Number(name) >= length)) fail('UNSAFE_INPUT');\n const result: unknown[] = []; for (let index = 0; index < length; index += 1) result.push(data(input, String(index), 'UNSAFE_INPUT')); return result;\n}\nfunction position(input: unknown): SourcePositionV2 { const value = exactRecord(input, ['line', 'column', 'utf16Offset', 'utf8ByteOffset'], 'INVALID_SUBJECT'); return { line: integer(data(value, 'line', 'INVALID_SUBJECT'), 1), column: integer(data(value, 'column', 'INVALID_SUBJECT'), 1), utf16Offset: integer(data(value, 'utf16Offset', 'INVALID_SUBJECT')), utf8ByteOffset: integer(data(value, 'utf8ByteOffset', 'INVALID_SUBJECT')) }; }\nfunction sourceRef(input: unknown, limits: Record<string, number>, allowSpan: boolean): SourceMemberRefV2 { const value = exactRecord(input, ['pointer', 'occurrencePath', 'astNodeId', 'span'], 'INVALID_SUBJECT');\n const occurrencePath = arrayValue(data(value, 'occurrencePath', 'INVALID_SUBJECT'), limits.maxMembersAndElements).map((item) => integer(item, 0, 'INVALID_SUBJECT'));\n const astNodeId = stringValue(data(value, 'astNodeId', 'INVALID_SUBJECT'), 64);\n if (!/^[0-9a-f]{64}$/.test(astNodeId)) fail('INVALID_SUBJECT');\n const rawSpan = data(value, 'span', 'INVALID_SUBJECT'); let span: SourceSpanV2 | null = null;\n if (rawSpan !== null) {\n if (!allowSpan) fail('INVALID_SUBJECT'); if (limits.maxStoredSourceSpans < 1) fail('LIMIT_EXCEEDED');\n const spanValue = exactRecord(rawSpan, ['start', 'end'], 'INVALID_SUBJECT'); const start = position(data(spanValue, 'start', 'INVALID_SUBJECT')); const end = position(data(spanValue, 'end', 'INVALID_SUBJECT'));\n if (!(end.line > start.line || end.line === start.line && end.column > start.column) || end.utf16Offset <= start.utf16Offset || end.utf8ByteOffset <= start.utf8ByteOffset) fail('INVALID_SUBJECT'); span = { start, end };\n }\n return { pointer: pointer(data(value, 'pointer', 'INVALID_SUBJECT')), occurrencePath, astNodeId, span };\n}\nfunction nodeRef(input: unknown, limits: Record<string, number>, allowSpan: boolean): NodeRefV2 { const value = record(input, ['ordinal', 'source', 'identityDigest', 'explicitId', 'name'], 'INVALID_SUBJECT');\n const ordinal = integer(data(value, 'ordinal', 'INVALID_SUBJECT'));\n if (ordinal >= limits.maxNodes) fail('LIMIT_EXCEEDED');\n const source = sourceRef(data(value, 'source', 'INVALID_SUBJECT'), limits, allowSpan);\n const identityDigest = stringValue(data(value, 'identityDigest', 'INVALID_SUBJECT'), 64);\n if (!/^[0-9a-f]{64}$/.test(identityDigest) || identityDigest !== createNodeIdentityDigest(ordinal, source)) fail('INVALID_SUBJECT');\n const result: NodeRefV2 = { ordinal, source, identityDigest };\n if (Object.prototype.hasOwnProperty.call(value, 'explicitId')) result.explicitId = display(data(value, 'explicitId'), 4_096);\n if (Object.prototype.hasOwnProperty.call(value, 'name')) result.name = display(data(value, 'name'), 4_096);\n return result;\n}\nfunction subject(input: unknown, kind: string, limits: Record<string, number>): SafeFactSubjectV2 {\n const value = record(input, ['kind', 'node', 'source'], 'INVALID_SUBJECT');\n const subjectKind = data(value, 'kind', 'INVALID_SUBJECT');\n const allowSpan = kind === '' || SAFE_FACT_SPAN_POLICIES_V2[kind] === 'OPTIONAL_HALF_OPEN';\n if (subjectKind === 'WORKFLOW') { exactRecord(value, ['kind'], 'INVALID_SUBJECT'); return { kind: 'WORKFLOW' }; }\n if (subjectKind === 'NODE') { exactRecord(value, ['kind', 'node'], 'INVALID_SUBJECT'); return { kind: 'NODE', node: nodeRef(data(value, 'node', 'INVALID_SUBJECT'), limits, allowSpan) }; }\n if (subjectKind === 'SOURCE') { exactRecord(value, ['kind', 'source'], 'INVALID_SUBJECT'); return { kind: 'SOURCE', source: sourceRef(data(value, 'source', 'INVALID_SUBJECT'), limits, allowSpan) }; }\n fail('INVALID_SUBJECT');\n}\nfunction properties(kind: string, schema: SafeFactSchemaV2, input: unknown, limits: Record<string, number>): Record<string, Property> {\n const allowed = Object.getOwnPropertyNames(schema.properties);\n const value = record(input, allowed, 'UNKNOWN_PROPERTY', limits.maxMembersAndElements);\n const required = SAFE_FACT_REQUIRED_PROPERTIES_V2[kind]; if (required === undefined) fail('UNKNOWN_FACT_KIND');\n for (const key of required) data(value, key, 'INVALID_PROPERTY');\n const observation = kind === 'node.configuration.v2' ? enumValue(data(value, 'observation', 'INVALID_PROPERTY'), 'observation', kind, schema.maxStringBytes) : undefined;\n if (observation === 'AUTH_HEADER') exactRecord(value, ['observation', 'header', 'literalValue'], 'INVALID_PROPERTY');\n if (observation === 'SECRET_INDICATOR') exactRecord(value, ['observation', 'parameterPath', 'secretKind', 'indicator', 'hasLiteralValue'], 'INVALID_PROPERTY');\n let malformedAuth = false;\n if (kind === 'ingress.v2') {\n const auth = data(value, 'authentication', 'INVALID_PROPERTY');\n if (auth !== null) { try { const text = stringValue(auth, schema.maxStringBytes); malformedAuth = !/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(text) || SECRET.test(text) || PATH.test(text); } catch { malformedAuth = true; } }\n }\n const output: Record<string, Property> = {};\n for (const key of allowed) {\n if (!Object.prototype.hasOwnProperty.call(value, key) || malformedAuth && key !== 'authentication') continue;\n const raw = data(value, key); const type = schema.properties[key];\n if (kind === 'code.indicator.v2' && key === 'member') {\n if (typeof raw !== 'string') continue;\n try { output[key] = field(kind, key, raw, schema.maxStringBytes); } catch (error) {\n if (error === 'LIMIT_EXCEEDED' || raw.includes('\\0') || /(?:https?|ftp):\\/\\//i.test(raw)) continue;\n throw error;\n }\n continue;\n }\n if (kind === 'ingress.v2' && key === 'authentication' && malformedAuth) { output[key] = null; continue; }\n if (type === 'STRING') output[key] = ['businessCategory', 'confidence', 'namespaceClass', 'language', 'parseState', 'flowKind', 'sink', 'scheme', 'authorityState', 'valueMode', 'authenticationState', 'applicability', 'reviewState', 'observation', 'secretKind', 'indicator'].includes(key) ? enumValue(raw, key, kind, schema.maxStringBytes) : field(kind, key, raw, schema.maxStringBytes);\n else if (type === 'NULLABLE_STRING') output[key] = raw === null ? null : key === 'hostname' ? stringValue(raw, 253) : field(kind, key, raw, schema.maxStringBytes);\n else if (type === 'BOOLEAN') { if (typeof raw !== 'boolean') fail('INVALID_PROPERTY'); output[key] = raw; }\n else if (type === 'INTEGER') output[key] = integer(raw, key === 'nodeCount' ? 1 : 0);\n else if (type === 'STRING_LIST') {\n const maximum = kind === 'workflow.risk-summary.v1' || key === 'riskNotes' ? 3 : kind === 'integration.v1' && key === 'nodeTypes' ? Math.min(schema.maxItems, limits.maxNodes) : Math.min(schema.maxItems, limits.maxMembersAndElements);\n output[key] = Object.freeze(arrayValue(raw, maximum).map((item) => ['capabilities', 'taintLabels'].includes(key) ? enumValue(item, key, kind, schema.maxStringBytes) : field(kind, key, item, schema.maxStringBytes)));\n } else if (type === 'INTEGER_LIST') output[key] = Object.freeze(arrayValue(raw, Math.min(schema.maxItems, limits.maxMembersAndElements)).map((item) => integer(item)));\n else fail('REGISTRY_MISMATCH');\n }\n if (malformedAuth) return { authentication: null, authenticationState: 'UNKNOWN', legacyAuthenticated: false };\n if (kind === 'code.indicator.v2' && typeof output.start === 'number' && typeof output.end === 'number' && output.start >= output.end) fail('INVALID_PROPERTY');\n if (kind === 'workflow.fingerprint.v1' && (typeof output.value !== 'string' || !/^[0-9a-f]{64}$/.test(output.value))) fail('INVALID_PROPERTY');\n if (kind === 'destination.v2' && typeof output.hostname === 'string' && !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/.test(output.hostname)) fail('INVALID_PROPERTY');\n return output;\n}\n/**\n * The producer-side half of the invariant `validateSafeFact` enforces when it recomputes a fact's\n * ID: the ID hashes the canonical properties, not the ones a capability handed in. Property values\n * that survive validation are returned unchanged, so every admissible fact keeps the ID it had.\n *\n * The one rewrite is the ingress quarantine: a value the ingress rule refuses becomes\n * `{ authentication: null, authenticationState: 'UNKNOWN', legacyAuthenticated: false }`, and\n * `code.indicator.v2` drops an inadmissible `member`. A producer that hashed the raw value was\n * rejected for an ID mismatch and its whole capability was dropped (65-F1), even though the policy\n * had already reported the finding.\n *\n * `undefined` means the validator would refuse these properties outright. The caller hashes them\n * unchanged then, so the fact still fails closed at validation exactly as before. The collection\n * bounds here are deliberately unbounded: the validator applies the real limit before any ID is\n * compared, so binding here could only manufacture a second, different refusal.\n */\nexport function canonicalSafeFactProperties(kind: string, input: unknown): Record<string, string | number | boolean | null | readonly (string | number | boolean | null)[]> | undefined {\n const schema = SAFE_FACT_REGISTRY_V2.schemas.find((item) => item.kind === kind);\n if (schema === undefined) return undefined;\n const unbounded = { maxMembersAndElements: Number.MAX_SAFE_INTEGER, maxNodes: Number.MAX_SAFE_INTEGER };\n try { return properties(kind, schema, input, unbounded); } catch { return undefined; }\n}\nfunction writeUtf8(hash: ReturnType<typeof sha256.create>, value: string): void {\n const chunk = new Uint8Array(4_096); let used = 0; const push = (byte: number): void => { chunk[used] = byte; used += 1; if (used === chunk.length) { hash.update(chunk); used = 0; } };\n for (let index = 0; index < value.length; index += 1) { let code = value.charCodeAt(index); if (code >= 0xd800) { code = 0x10000 + ((code - 0xd800) << 10) + value.charCodeAt(index + 1) - 0xdc00; index += 1; } if (code <= 0x7f) push(code); else if (code <= 0x7ff) { push(0xc0 | code >> 6); push(0x80 | code & 63); } else if (code <= 0xffff) { push(0xe0 | code >> 12); push(0x80 | code >> 6 & 63); push(0x80 | code & 63); } else { push(0xf0 | code >> 18); push(0x80 | code >> 12 & 63); push(0x80 | code >> 6 & 63); push(0x80 | code & 63); } }\n if (used) hash.update(chunk.subarray(0, used));\n}\nfunction factDigest(parts: readonly string[]): string {\n const hash = sha256.create();\n for (const part of parts) { const tagged = `N${utf8Bytes(part, 64 * 1024 * 1024)}:${part}`; const framed = `${utf8Bytes(tagged, 64 * 1024 * 1024)}:${tagged}`; writeUtf8(hash, framed); }\n return bytesToHex(hash.digest());\n}\nexport function canonicalSafeFactSubjectIdentity(subject: SafeFactSubjectV2): string {\n if (subject.kind === 'WORKFLOW') return 'WORKFLOW';\n if (subject.kind === 'SOURCE') return `SOURCE${subject.source.astNodeId}`;\n if (subject.kind === 'NODE') return `NODE${subject.node.identityDigest}`;\n return `EDGE${createEdgeIdentityDigest(subject.edge)}`;\n}\nfunction knownReason(value: unknown): value is Bad {\n return value === 'UNKNOWN_FACT_KIND' || value === 'UNKNOWN_PROPERTY' || value === 'INVALID_PROPERTY' || value === 'INVALID_SUBJECT' || value === 'FORBIDDEN_CONTENT' || value === 'LIMIT_EXCEEDED' || value === 'UNSAFE_INPUT' || value === 'REGISTRY_MISMATCH';\n}\nexport function validateSafeFact(candidate: unknown, schema: SafeFactSchemaV2, limits: ScannerLimitsV2): SafeFactValidationResultV2 {\n if (!isScannerAdmissionSnapshotV2<SafeFactV2>(candidate)) return Object.freeze({ ok: false, code: 'SAFE_FACT_REJECTED', reason: 'UNSAFE_INPUT' });\n try {\n const value = record(candidate, FACT_KEYS, 'UNKNOWN_PROPERTY');\n const kind = data(value, 'kind'); if (typeof kind !== 'string') fail('UNKNOWN_FACT_KIND');\n const expected = SAFE_FACT_REGISTRY_V2.schemas.find((item) => item.kind === kind);\n if (expected === undefined) fail('UNKNOWN_FACT_KIND');\n if (schema !== expected) fail('REGISTRY_MISMATCH');\n const effective = limitsSnapshot(limits);\n const subjectValue = subject(data(value, 'subject'), kind, effective);\n const subjects = SAFE_FACT_SUBJECT_KINDS_V2[kind]; if (subjects === undefined || !subjects.includes(subjectValue.kind)) fail('INVALID_SUBJECT');\n const propertiesValue = properties(kind, expected, data(value, 'properties'), effective);\n const expectedId = factDigest(['secureflow-fact-id-v2', kind, canonicalSafeFactSubjectIdentity(subjectValue), canonicalizeJson(propertiesValue)]);\n if (data(value, 'factId') !== expectedId) fail('INVALID_PROPERTY');\n const fact: SafeFactV2 = { factId: expectedId, kind, subject: subjectValue, properties: propertiesValue };\n return Object.freeze({ ok: true, fact: createSafeFactAdmissionSnapshotV2(fact) });\n } catch (error) {\n return Object.freeze({ ok: false, code: 'SAFE_FACT_REJECTED', reason: knownReason(error) ? error : 'UNSAFE_INPUT' });\n }\n}\n", "// Generated by scripts/generate-diagnostic-registry.mjs; DO NOT EDIT.\n// diagnostic-registry:version=diagnostic-registry-v1\n// diagnostic-registry:source=openspec/changes/world-class-scanner-cli/diagnostic-and-exit-registry.md\n// diagnostic-registry:rows=28\n// diagnostic-registry:digest=f66f90ea2cca06ddccefeff924fcb8abe672050fcee861ceb9b4e66551ddfc3c\n// Regenerate with `npm run generate:diagnostic-registry` after editing the registry table.\n// Every code, category, effect mode, assessment mode, and v1 projection below is projected from it.\nimport type { SourceMemberRefV2 } from '../source/source-types';\n\nexport type DiagnosticCategoryV2 = 'LIMIT' | 'SOURCE' | 'PARSER' | 'POLICY' | 'GRAPH' | 'CATALOGUE' | 'COMPATIBILITY';\nexport type DiagnosticAggregateEffectV2 = 'NONE' | 'DEGRADED' | 'INDETERMINATE';\nexport type DiagnosticAggregateEffectModeV2 = DiagnosticAggregateEffectV2 | 'BY_CAPABILITY';\nexport type DiagnosticAssessmentEligibilityModeV2 = boolean | 'BY_CAPABILITY';\nexport type DiagnosticV1ProjectionV2 = 'SAME' | 'MIGRATED' | 'PROJECTION_LOSS' | 'SENTINEL';\n\nexport type DiagnosticCodeV2 =\n | 'SOURCE_SPAN_UNAVAILABLE' | 'DUPLICATE_FINDING_COLLAPSED' | 'UNCLASSIFIED_CONNECTION_TYPE'\n | 'DUPLICATE_METADATA_KEY' | 'OPTIONAL_LIMIT_EXCEEDED' | 'UNSUPPORTED_CODE_NODE_VARIANT'\n | 'JAVASCRIPT_PARSE_FAILED' | 'JAVASCRIPT_SOURCE_UNAVAILABLE' | 'PYTHON_SOURCE_UNAVAILABLE'\n | 'PYTHON_PARSE_FAILED' | 'PYTHON_PARSER_UNAVAILABLE' | 'EXPRESSION_PARSE_FAILED'\n | 'GRAPH_ENTRY_UNRESOLVED' | 'GRAPH_WORK_LIMIT_EXCEEDED' | 'GRAPH_ANALYSIS_DEGRADED'\n | 'SEMANTIC_CATALOGUE_MISS' | 'GENERIC_NODE_UNMODELED_CAPABILITY' | 'POLICY_EXECUTION_FAILED'\n | 'DEPENDENCY_UNAVAILABLE' | 'UNKNOWN_REPORT_ONLY_RULE' | 'REQUIRED_LIMIT_EXCEEDED'\n | 'DUPLICATE_SECURITY_KEY' | 'MALFORMED_NODE_PARAMETERS' | 'MALFORMED_CONNECTION_INDEX'\n | 'REQUIRED_CAPABILITY_FAILED' | 'UNKNOWN_SCORING_RULE' | 'COMPATIBILITY_PROJECTION_LOSS'\n | 'REQUIRED_STAGE_FAILURE';\n\nexport type AnalysisDiagnosticV2 = Readonly<{\n id: string;\n code: DiagnosticCodeV2;\n category: DiagnosticCategoryV2;\n capabilityId: string;\n aggregateEffect: DiagnosticAggregateEffectV2;\n assessmentEligible: boolean;\n location?: SourceMemberRefV2;\n observed?: number;\n maximum?: number;\n omitted?: number;\n}>;\n\nexport type DiagnosticRegistryEntryV2 = Readonly<{\n code: DiagnosticCodeV2;\n category: DiagnosticCategoryV2;\n aggregateEffect: DiagnosticAggregateEffectModeV2;\n assessmentEligible: DiagnosticAssessmentEligibilityModeV2;\n v1Code: string | null;\n v1Projection: DiagnosticV1ProjectionV2;\n}>;\n\nconst row = (\n code: DiagnosticCodeV2,\n category: DiagnosticCategoryV2,\n aggregateEffect: DiagnosticAggregateEffectModeV2,\n assessmentEligible: DiagnosticAssessmentEligibilityModeV2,\n v1Code: string | null,\n v1Projection: DiagnosticV1ProjectionV2,\n): DiagnosticRegistryEntryV2 => Object.freeze({\n code, category, aggregateEffect, assessmentEligible, v1Code, v1Projection,\n});\n\nexport const DIAGNOSTIC_REGISTRY: readonly DiagnosticRegistryEntryV2[] = Object.freeze([\n row('SOURCE_SPAN_UNAVAILABLE', 'SOURCE', 'DEGRADED', true, 'SOURCE_SPAN_UNAVAILABLE', 'SAME'),\n row('DUPLICATE_FINDING_COLLAPSED', 'POLICY', 'DEGRADED', true, 'DUPLICATE_FINDING_COLLAPSED', 'SAME'),\n row('UNCLASSIFIED_CONNECTION_TYPE', 'GRAPH', 'DEGRADED', true, 'UNCLASSIFIED_CONNECTION_TYPE', 'SAME'),\n row('DUPLICATE_METADATA_KEY', 'PARSER', 'DEGRADED', true, 'DUPLICATE_JSON_KEY', 'MIGRATED'),\n row('OPTIONAL_LIMIT_EXCEEDED', 'LIMIT', 'DEGRADED', true, 'ANALYSIS_LIMIT_EXCEEDED', 'MIGRATED'),\n row('UNSUPPORTED_CODE_NODE_VARIANT', 'PARSER', 'BY_CAPABILITY', 'BY_CAPABILITY', 'UNSUPPORTED_CODE_NODE_VARIANT', 'SAME'),\n row('JAVASCRIPT_PARSE_FAILED', 'PARSER', 'BY_CAPABILITY', 'BY_CAPABILITY', 'JAVASCRIPT_PARSE_FAILED', 'SAME'),\n row('JAVASCRIPT_SOURCE_UNAVAILABLE', 'SOURCE', 'BY_CAPABILITY', 'BY_CAPABILITY', 'JAVASCRIPT_SOURCE_UNAVAILABLE', 'SAME'),\n row('PYTHON_SOURCE_UNAVAILABLE', 'SOURCE', 'BY_CAPABILITY', 'BY_CAPABILITY', 'PYTHON_SOURCE_UNAVAILABLE', 'SAME'),\n row('PYTHON_PARSE_FAILED', 'PARSER', 'BY_CAPABILITY', 'BY_CAPABILITY', 'PYTHON_PARSE_FAILED', 'SAME'),\n row('PYTHON_PARSER_UNAVAILABLE', 'PARSER', 'BY_CAPABILITY', 'BY_CAPABILITY', 'PYTHON_PARSER_UNAVAILABLE', 'SAME'),\n row('EXPRESSION_PARSE_FAILED', 'PARSER', 'BY_CAPABILITY', 'BY_CAPABILITY', 'EXPRESSION_PARSE_FAILED', 'SAME'),\n row('GRAPH_ENTRY_UNRESOLVED', 'GRAPH', 'BY_CAPABILITY', 'BY_CAPABILITY', 'GRAPH_ANALYSIS_DEGRADED', 'MIGRATED'),\n row('GRAPH_WORK_LIMIT_EXCEEDED', 'GRAPH', 'BY_CAPABILITY', 'BY_CAPABILITY', 'ANALYSIS_LIMIT_EXCEEDED', 'MIGRATED'),\n row('GRAPH_ANALYSIS_DEGRADED', 'GRAPH', 'BY_CAPABILITY', 'BY_CAPABILITY', 'GRAPH_ANALYSIS_DEGRADED', 'SAME'),\n row('SEMANTIC_CATALOGUE_MISS', 'CATALOGUE', 'BY_CAPABILITY', 'BY_CAPABILITY', null, 'PROJECTION_LOSS'),\n row('GENERIC_NODE_UNMODELED_CAPABILITY', 'CATALOGUE', 'DEGRADED', true, null, 'PROJECTION_LOSS'),\n row('POLICY_EXECUTION_FAILED', 'POLICY', 'BY_CAPABILITY', 'BY_CAPABILITY', 'POLICY_EXECUTION_FAILED', 'SAME'),\n row('DEPENDENCY_UNAVAILABLE', 'POLICY', 'BY_CAPABILITY', 'BY_CAPABILITY', null, 'PROJECTION_LOSS'),\n row('UNKNOWN_REPORT_ONLY_RULE', 'POLICY', 'DEGRADED', true, null, 'PROJECTION_LOSS'),\n row('REQUIRED_LIMIT_EXCEEDED', 'LIMIT', 'INDETERMINATE', false, 'ANALYSIS_LIMIT_EXCEEDED', 'MIGRATED'),\n row('DUPLICATE_SECURITY_KEY', 'PARSER', 'INDETERMINATE', false, 'DUPLICATE_JSON_KEY', 'MIGRATED'),\n row('MALFORMED_NODE_PARAMETERS', 'PARSER', 'INDETERMINATE', false, 'MALFORMED_NODE_PARAMETERS', 'SAME'),\n row('MALFORMED_CONNECTION_INDEX', 'GRAPH', 'INDETERMINATE', false, 'MALFORMED_CONNECTION_INDEX', 'SAME'),\n row('REQUIRED_CAPABILITY_FAILED', 'POLICY', 'INDETERMINATE', false, null, 'PROJECTION_LOSS'),\n row('UNKNOWN_SCORING_RULE', 'POLICY', 'INDETERMINATE', false, null, 'PROJECTION_LOSS'),\n row('COMPATIBILITY_PROJECTION_LOSS', 'COMPATIBILITY', 'INDETERMINATE', false, 'POLICY_EXECUTION_FAILED', 'SENTINEL'),\n row('REQUIRED_STAGE_FAILURE', 'POLICY', 'INDETERMINATE', false, 'REQUIRED_STAGE_FAILURE', 'SAME'),\n]);\n\nexport const DIAGNOSTIC_CODES_V2: readonly DiagnosticCodeV2[] = Object.freeze(\n DIAGNOSTIC_REGISTRY.map((entry) => entry.code),\n);\n\nconst categorySet: Readonly<Record<DiagnosticCategoryV2, true>> = Object.freeze({ 'LIMIT': true, 'SOURCE': true, 'PARSER': true, 'POLICY': true, 'GRAPH': true, 'CATALOGUE': true, 'COMPATIBILITY': true });\nconst effectSet: Readonly<Record<DiagnosticAggregateEffectModeV2, true>> = Object.freeze({ 'NONE': true, 'DEGRADED': true, 'INDETERMINATE': true, 'BY_CAPABILITY': true });\nconst projectionSet: Readonly<Record<DiagnosticV1ProjectionV2, true>> = Object.freeze({ 'SAME': true, 'MIGRATED': true, 'PROJECTION_LOSS': true, 'SENTINEL': true });\nconst byCode = new Map<string, DiagnosticRegistryEntryV2>(DIAGNOSTIC_REGISTRY.map((entry) => [entry.code, entry]));\n\nif (DIAGNOSTIC_REGISTRY.length !== 28 || byCode.size !== DIAGNOSTIC_REGISTRY.length) throw new TypeError('Invalid diagnostic registry');\nfor (const entry of DIAGNOSTIC_REGISTRY) {\n if (categorySet[entry.category] !== true || effectSet[entry.aggregateEffect] !== true || projectionSet[entry.v1Projection] !== true) {\n throw new TypeError('Invalid diagnostic registry');\n }\n if (entry.assessmentEligible !== 'BY_CAPABILITY' && typeof entry.assessmentEligible !== 'boolean') {\n throw new TypeError('Invalid diagnostic registry');\n }\n}\n\n/**\n * The status mapping (aggregate effect) and the assessment mapping. A `BY_CAPABILITY`\n * row is resolved by the owning capability's registry-fixed requiredness: required loss\n * is `INDETERMINATE`/ineligible, optional or report-only loss is `DEGRADED`/eligible.\n */\nexport function classifyDiagnostic(code: DiagnosticCodeV2, capabilityRequiredness?: boolean): Readonly<{\n category: DiagnosticCategoryV2;\n aggregateEffect: DiagnosticAggregateEffectV2;\n assessmentEligible: boolean;\n}> {\n const entry = byCode.get(code);\n if (!entry) throw new TypeError('Unknown diagnostic code');\n if (entry.aggregateEffect === 'BY_CAPABILITY' && typeof capabilityRequiredness !== 'boolean') {\n throw new TypeError('Diagnostic capability requiredness is not fixed');\n }\n const required = entry.aggregateEffect === 'BY_CAPABILITY' && capabilityRequiredness === true;\n return Object.freeze({\n category: entry.category,\n aggregateEffect: entry.aggregateEffect === 'BY_CAPABILITY' ? (required ? 'INDETERMINATE' : 'DEGRADED') : entry.aggregateEffect,\n assessmentEligible: entry.assessmentEligible === 'BY_CAPABILITY' ? !required : entry.assessmentEligible,\n });\n}\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { encodeIdentityTuple } from '../workflow-v2/node-edge-identity';\nimport type { SourceMemberRefV2, SourcePositionV2 } from '../source/source-types';\nimport { classifyDiagnostic, DIAGNOSTIC_REGISTRY, type AnalysisDiagnosticV2,\n type DiagnosticAggregateEffectV2, type DiagnosticCategoryV2, type DiagnosticCodeV2 } from './registry';\n\nexport type DiagnosticIdentityInputV2 = Readonly<{\n code: DiagnosticCodeV2; capabilityId: string; aggregateEffect: DiagnosticAggregateEffectV2;\n category?: DiagnosticCategoryV2; assessmentEligible?: boolean; location?: SourceMemberRefV2;\n observed?: number; maximum?: number; omitted?: number;\n}>;\ntype NormalizedIdentity = { code: DiagnosticCodeV2; capabilityId: string; category: DiagnosticCategoryV2;\n aggregateEffect: DiagnosticAggregateEffectV2; assessmentEligible: boolean; location?: SourceMemberRefV2;\n observed?: number; maximum?: number; omitted?: number; astNodeId: string };\nconst encoder = new TextEncoder();\nconst registryOrder = new Map(DIAGNOSTIC_REGISTRY.map((entry, index) => [entry.code, index]));\nconst identityKeys = ['code', 'capabilityId', 'aggregateEffect', 'category', 'assessmentEligible', 'location', 'observed', 'maximum', 'omitted'] as const;\nconst diagnosticKeys = ['id', ...identityKeys] as const;\nconst locationKeys = ['pointer', 'occurrencePath', 'astNodeId', 'span'] as const;\nconst spanKeys = ['start', 'end'] as const;\nconst positionKeys = ['line', 'column', 'utf16Offset', 'utf8ByteOffset'] as const;\n\nexport function createDiagnosticId(input: DiagnosticIdentityInputV2): string {\n try { return identityDigest(normalizeIdentity(input)); }\n catch { throw new TypeError('Invalid diagnostic identity'); }\n}\nexport function sortDiagnostics(diagnostics: readonly AnalysisDiagnosticV2[], capabilityOrder: readonly string[] = []): readonly AnalysisDiagnosticV2[] {\n try {\n assertDenseArray(diagnostics); const order = capabilityRanks(capabilityOrder);\n const groups = new Map<string, AnalysisDiagnosticV2[]>();\n for (const diagnostic of diagnostics) {\n const normalized = normalizeDiagnostic(diagnostic); const group = groups.get(normalized.id);\n if (group) group.push(normalized); else groups.set(normalized.id, [normalized]);\n }\n const unique = [...groups.values()].map((group) => duplicateRepresentative(group, order));\n return Object.freeze(unique.sort((left, right) => compareDiagnostics(left, right, order)));\n } catch { throw new TypeError('Invalid diagnostic collection'); }\n}\nfunction normalizeIdentity(input: DiagnosticIdentityInputV2): NormalizedIdentity {\n const value = record(input, identityKeys); const code = required(value, 'code') as DiagnosticCodeV2;\n const capabilityId = required(value, 'capabilityId'); const effect = required(value, 'aggregateEffect');\n const category = optional(value, 'category'); const eligible = optional(value, 'assessmentEligible');\n if (typeof capabilityId !== 'string' || capabilityId.length === 0) throw new TypeError();\n if (eligible !== undefined && typeof eligible !== 'boolean') throw new TypeError();\n const classification = eligible === undefined ? classifyDiagnostic(code) : classifyDiagnostic(code, !eligible);\n if (eligible !== undefined && eligible !== classification.assessmentEligible) throw new TypeError();\n if (effect !== classification.aggregateEffect || category !== undefined && category !== classification.category) throw new TypeError();\n const locationValue = optional(value, 'location'); const location = locationValue === undefined ? undefined : cloneLocation(locationValue);\n return { code, capabilityId, category: classification.category, aggregateEffect: classification.aggregateEffect,\n assessmentEligible: classification.assessmentEligible, location, observed: optionalNumber(value, 'observed'),\n maximum: optionalNumber(value, 'maximum'), omitted: optionalNumber(value, 'omitted'), astNodeId: location?.astNodeId ?? 'NONE' };\n}\nfunction normalizeDiagnostic(input: AnalysisDiagnosticV2): AnalysisDiagnosticV2 {\n const value = record(input, diagnosticKeys); const identity = normalizeIdentity({\n code: required(value, 'code') as DiagnosticCodeV2, capabilityId: required(value, 'capabilityId') as string,\n aggregateEffect: required(value, 'aggregateEffect') as DiagnosticAggregateEffectV2,\n category: required(value, 'category') as DiagnosticCategoryV2, assessmentEligible: required(value, 'assessmentEligible') as boolean,\n location: optional(value, 'location') as SourceMemberRefV2 | undefined, observed: optionalNumber(value, 'observed'),\n maximum: optionalNumber(value, 'maximum'), omitted: optionalNumber(value, 'omitted') });\n const id = required(value, 'id'); if (typeof id !== 'string' || id !== identityDigest(identity)) throw new TypeError();\n return Object.freeze({ id, code: identity.code, category: identity.category, capabilityId: identity.capabilityId,\n aggregateEffect: identity.aggregateEffect, assessmentEligible: identity.assessmentEligible,\n ...(identity.location === undefined ? {} : { location: identity.location }),\n ...(identity.observed === undefined ? {} : { observed: identity.observed }),\n ...(identity.maximum === undefined ? {} : { maximum: identity.maximum }),\n ...(identity.omitted === undefined ? {} : { omitted: identity.omitted }) });\n}\nfunction identityDigest(input: NormalizedIdentity): string {\n return bytesToHex(sha256(encoder.encode(encodeIdentityTuple(['secureflow-diagnostic-id-v2', input.capabilityId, input.code,\n input.aggregateEffect, input.astNodeId, input.observed === undefined ? 'NONE' : String(input.observed),\n input.maximum === undefined ? 'NONE' : String(input.maximum), input.omitted === undefined ? 'NONE' : String(input.omitted)]))));\n}\nfunction duplicateRepresentative(group: readonly AnalysisDiagnosticV2[], order: Map<string, number>): AnalysisDiagnosticV2 {\n let representative = group[0];\n for (const candidate of group.slice(1)) if (compareDiagnostics(candidate, representative, order) < 0) representative = candidate;\n if (group.length === 1 || representative.location === undefined) return representative;\n return Object.freeze({ ...representative, location: Object.freeze({ ...representative.location, span: null }) });\n}\nfunction cloneLocation(input: unknown): SourceMemberRefV2 {\n const value = record(input, locationKeys); const pointer = required(value, 'pointer'); const astNodeId = required(value, 'astNodeId');\n if (typeof pointer !== 'string' || typeof astNodeId !== 'string' || astNodeId.length === 0) throw new TypeError();\n const path = required(value, 'occurrencePath'); assertDenseArray(path);\n const occurrencePath = Object.freeze((path as readonly unknown[]).map(numericValue)); const span = required(value, 'span');\n return Object.freeze({ pointer, occurrencePath, astNodeId, span: span === null ? null : cloneSpan(span) });\n}\nfunction cloneSpan(input: unknown): NonNullable<SourceMemberRefV2['span']> {\n const value = record(input, spanKeys); return Object.freeze({ start: clonePosition(required(value, 'start')), end: clonePosition(required(value, 'end')) });\n}\nfunction clonePosition(input: unknown): SourcePositionV2 {\n const value = record(input, positionKeys); return Object.freeze({ line: numericValue(required(value, 'line')), column: numericValue(required(value, 'column')),\n utf16Offset: numericValue(required(value, 'utf16Offset')), utf8ByteOffset: numericValue(required(value, 'utf8ByteOffset')) });\n}\nfunction optionalNumber(value: Record<string, unknown>, key: string): number | undefined {\n const number = optional(value, key); return number === undefined ? undefined : numericValue(number);\n}\nfunction numericValue(value: unknown): number {\n if (!Number.isSafeInteger(value) || (value as number) < 0) throw new TypeError(); return value as number;\n}\nfunction capabilityRanks(order: readonly string[]): Map<string, number> {\n assertDenseArray(order); const ranks = new Map<string, number>();\n for (const [index, capability] of order.entries()) { if (typeof capability !== 'string' || ranks.has(capability)) throw new TypeError(); ranks.set(capability, index); }\n return ranks;\n}\nfunction compareDiagnostics(left: AnalysisDiagnosticV2, right: AnalysisDiagnosticV2, ranks: Map<string, number>): number {\n const leftRank = ranks.get(left.capabilityId); const rightRank = ranks.get(right.capabilityId);\n if (leftRank !== undefined || rightRank !== undefined) {\n if (leftRank === undefined) return 1; if (rightRank === undefined) return -1; if (leftRank !== rightRank) return leftRank - rightRank;\n } else if (left.capabilityId !== right.capabilityId) return compareCodePoints(left.capabilityId, right.capabilityId);\n const codeOrder = (registryOrder.get(left.code) ?? Number.MAX_SAFE_INTEGER) - (registryOrder.get(right.code) ?? Number.MAX_SAFE_INTEGER);\n if (codeOrder !== 0) return codeOrder; const locationOrder = compareLocations(left.location, right.location);\n return locationOrder !== 0 ? locationOrder : left.id === right.id ? 0 : compareCodePoints(left.id, right.id);\n}\nfunction compareLocations(left: SourceMemberRefV2 | undefined, right: SourceMemberRefV2 | undefined): number {\n if (left === undefined) return right === undefined ? 0 : 1; if (right === undefined) return -1;\n const pointerOrder = compareCodePoints(left.pointer, right.pointer); return pointerOrder !== 0 ? pointerOrder : comparePaths(left.occurrencePath, right.occurrencePath);\n}\nfunction comparePaths(left: readonly number[], right: readonly number[]): number {\n for (let index = 0; index < Math.min(left.length, right.length); index += 1) if (left[index] !== right[index]) return left[index] - right[index];\n return left.length - right.length;\n}\nfunction compareCodePoints(left: string, right: string): number {\n const leftPoints = Array.from(left, (value) => value.codePointAt(0)!); const rightPoints = Array.from(right, (value) => value.codePointAt(0)!);\n for (let index = 0; index < Math.min(leftPoints.length, rightPoints.length); index += 1) if (leftPoints[index] !== rightPoints[index]) return leftPoints[index] - rightPoints[index];\n return leftPoints.length - rightPoints.length;\n}\nfunction record(input: unknown, allowed: readonly string[]): Record<string, unknown> {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) throw new TypeError(); const prototype = Object.getPrototypeOf(input);\n if (prototype !== Object.prototype && prototype !== null || Object.getOwnPropertySymbols(input).length > 0) throw new TypeError();\n for (const key of Object.getOwnPropertyNames(input)) { const descriptor = Object.getOwnPropertyDescriptor(input, key);\n if (!allowed.includes(key) || !descriptor || !('value' in descriptor)) throw new TypeError(); }\n return input as Record<string, unknown>;\n}\nfunction required(value: Record<string, unknown>, key: string): unknown { if (!Object.prototype.hasOwnProperty.call(value, key)) throw new TypeError(); return value[key]; }\nfunction optional(value: Record<string, unknown>, key: string): unknown { return Object.prototype.hasOwnProperty.call(value, key) ? value[key] : undefined; }\nfunction assertDenseArray(input: unknown): asserts input is readonly unknown[] {\n if (!Array.isArray(input) || Object.getPrototypeOf(input) !== Array.prototype || Object.getOwnPropertySymbols(input).length > 0) throw new TypeError();\n const names = Object.getOwnPropertyNames(input); if (names.length !== input.length + 1 || !names.includes('length')) throw new TypeError();\n for (let index = 0; index < input.length; index += 1) { const descriptor = Object.getOwnPropertyDescriptor(input, String(index)); if (!descriptor || !('value' in descriptor)) throw new TypeError(); }\n if (names.some((name) => name !== 'length' && !/^\\d+$/.test(name))) throw new TypeError();\n}\n", "import type { AdmittedRuleV2 } from '../capabilities/scheduler';\n\n/**\n * The admitted rule catalogue is the only authority for what a rule is.\n *\n * A rule id that is not in the admitted catalogue is never neutral. It is either a rule that\n * would have been scored or one that would only have been reported, and those are not the same\n * failure: a scoring unknown must fail closed \u2014 the finding is refused, the owning capability is\n * refused, and the run cannot publish an assessment \u2014 while a report-only unknown may degrade the\n * run and let the assessment stand without that rule.\n *\n * The burden of proof is on \"report-only\". Only a declared, non-required owner proves it, because\n * a capability becomes required/scoring only in a new admitted profile version\n * (`core-registry-contracts.md`). An id whose owner cannot be established \u2014 a finding at the result\n * boundary, a pack body, a synthetic catalogue lookup \u2014 is treated as scoring.\n *\n * This module is the reason those rules cannot drift: the case, its registry code, and the\n * fields the catalogue owns are declared once here and consumed by the pack admission boundary,\n * the scheduler, the analyzer adapter, and the result composer.\n */\nexport type UnknownRuleCaseV2 = 'SCORING' | 'REPORT_ONLY';\n\n/** The closed-registry codes the two cases map to (`diagnostic-and-exit-registry.md`). */\nexport const UNKNOWN_RULE_DIAGNOSTIC_V2 = Object.freeze({\n SCORING: 'UNKNOWN_SCORING_RULE',\n REPORT_ONLY: 'UNKNOWN_REPORT_ONLY_RULE',\n} as const);\nexport type UnknownRuleDiagnosticCodeV2 = (typeof UNKNOWN_RULE_DIAGNOSTIC_V2)[UnknownRuleCaseV2];\n\n/**\n * The identity fields the admitted catalogue owns. A rule body, a safe fact, or a caller may\n * repeat them; none of them may set them.\n */\nexport const RULE_AUTHORITY_FIELDS_V2 = Object.freeze([\n 'revision', 'capabilityId', 'effect', 'severity', 'confidence', 'evidenceSchemaId', 'remediationId',\n] as const);\nexport type RuleAuthorityFieldV2 = (typeof RULE_AUTHORITY_FIELDS_V2)[number];\nexport type RuleAuthorityClaimV2 = Readonly<Partial<Record<RuleAuthorityFieldV2, string>>>;\n\n/** A capability that declares rules, and therefore an owner an unknown id can be attributed to. */\nexport type UnknownRuleOwnerV2 = Readonly<{ required: boolean }>;\n\n/**\n * Which unknown case an id is. Every boundary asks this one question, so the answer lives once:\n * only a declared, non-required owner makes an unknown id report-only.\n */\nexport function unknownRuleCaseV2(owner: UnknownRuleOwnerV2 | undefined): UnknownRuleCaseV2 {\n return owner !== undefined && owner.required === false ? 'REPORT_ONLY' : 'SCORING';\n}\n\n/** True when every field the claim repeats is the admitted value. A claim may omit, never override. */\nexport function ruleAuthorityMatchesV2(rule: AdmittedRuleV2, claim: RuleAuthorityClaimV2): boolean {\n for (const field of RULE_AUTHORITY_FIELDS_V2) {\n const claimed = claim[field];\n if (claimed !== undefined && claimed !== rule[field]) return false;\n }\n return true;\n}\n\n/**\n * Read an admitted rule from a catalogue. Real `Map` instances and the scheduler's frozen\n * immutable map view are the only admitted shapes; anything else yields no rule rather than a\n * caller-defined lookup.\n */\nexport function admittedRuleV2(rules: ReadonlyMap<string, AdmittedRuleV2>, ruleId: string): AdmittedRuleV2 | undefined {\n if (rules instanceof Map && Object.getPrototypeOf(rules) === Map.prototype) return Map.prototype.get.call(rules, ruleId);\n const descriptor = Object.getOwnPropertyDescriptor(rules, 'get');\n if (Object.getPrototypeOf(rules) !== null || !Object.isFrozen(rules) || descriptor === undefined || !('value' in descriptor) || typeof descriptor.value !== 'function') return undefined;\n return (descriptor.value as (key: string) => AdmittedRuleV2 | undefined).call(rules, ruleId);\n}\n\nexport type RuleResolutionV2 = Readonly<\n | { ok: true; rule: AdmittedRuleV2 }\n | { ok: false; ruleId: string; case: UnknownRuleCaseV2; diagnosticCode: UnknownRuleDiagnosticCodeV2 }\n>;\n\nexport function resolveRuleAuthorityV2(rules: ReadonlyMap<string, AdmittedRuleV2>, ruleId: string, owner?: UnknownRuleOwnerV2): RuleResolutionV2 {\n const rule = admittedRuleV2(rules, ruleId);\n if (rule !== undefined) return Object.freeze({ ok: true as const, rule });\n const ruleCase = unknownRuleCaseV2(owner);\n return Object.freeze({ ok: false as const, ruleId, case: ruleCase, diagnosticCode: UNKNOWN_RULE_DIAGNOSTIC_V2[ruleCase] });\n}\n\nexport type DeclaredRulesResolutionV2 = Readonly<\n | { ok: true; rules: ReadonlyMap<string, AdmittedRuleV2> }\n | { ok: false; ruleId: string; case: UnknownRuleCaseV2; diagnosticCode: UnknownRuleDiagnosticCodeV2 }\n>;\n\n/**\n * Resolve every rule a capability declares. A capability may not run against a catalogue that is\n * missing a rule it declares: the first unknown id decides the case for the whole declaration.\n */\nexport function resolveDeclaredRulesV2(declared: readonly string[], rules: ReadonlyMap<string, AdmittedRuleV2>, owner: UnknownRuleOwnerV2): DeclaredRulesResolutionV2 {\n const resolved = new Map<string, AdmittedRuleV2>();\n for (const ruleId of declared) {\n const resolution = resolveRuleAuthorityV2(rules, ruleId, owner);\n if (!resolution.ok) return resolution;\n resolved.set(ruleId, resolution.rule);\n }\n return Object.freeze({ ok: true as const, rules: resolved });\n}\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { segmentExpressionIslands } from '../analyzers/expression/expression-islands';\nimport type { AnalysisDiagnostic, ScanFinding } from '../policy/policy';\nimport { canonicalizeJson } from '../canonical-json';\nimport { canonicalSafeFactProperties } from '../facts/safe-fact-validator';\nimport { createDiagnosticId } from '../diagnostics/identity';\nimport { classifyDiagnostic, type AnalysisDiagnosticV2, type DiagnosticCodeV2 } from '../diagnostics/registry';\nimport { UNKNOWN_RULE_DIAGNOSTIC_V2, resolveRuleAuthorityV2, unknownRuleCaseV2 } from '../rules-v2/rule-authority';\nimport { createCapabilityCandidateAdmissionSnapshotV2, type ScannerAdmissionSnapshotV2 } from '../admission/snapshot';\nimport type { SecurityNodeV2, SemanticFieldV2 } from '../workflow-v2/security-workflow';\nimport type { AnalyzerContextV2, CapabilityCandidateV2, FindingCandidateV2, SafeFactV2, SubjectV2 } from './scheduler';\nimport type { ProfileCapabilityV2 } from './profile-manifest';\n\nexport type AdmittedCapabilityCandidateV2 = ScannerAdmissionSnapshotV2<CapabilityCandidateV2>;\n\nexport function admitCandidate(candidate: CapabilityCandidateV2): AdmittedCapabilityCandidateV2 {\n return createCapabilityCandidateAdmissionSnapshotV2(candidate);\n}\n\nconst digest = (parts: readonly string[]): string => bytesToHex(sha256(new TextEncoder().encode(requireTuple(parts))));\nconst requireTuple = (parts: readonly string[]): string => parts.map((part) => {\n const tagged = `N${new TextEncoder().encode(part).byteLength}:${part}`;\n return `${new TextEncoder().encode(tagged).byteLength}:${tagged}`;\n}).join('');\n\ntype FactProperties = Record<string, string | number | boolean | null | readonly (string | number | boolean | null)[]>;\n\nexport function makeFact(kind: string, subject: SubjectV2, properties: FactProperties): SafeFactV2 {\n const subjectId = subject.kind === 'WORKFLOW' ? 'WORKFLOW' : subject.kind === 'SOURCE' ? `SOURCE${subject.source.astNodeId}` : subject.kind === 'NODE' ? `NODE${subject.node.identityDigest}` : `EDGE${subject.edge.ordinal}`;\n // The ID must hash the properties `validateSafeFact` will admit, not the ones a policy handed\n // over: an ingress fact quarantines malformed authentication, so hashing the raw value made the\n // validator reject its own producer's fact and drop the finding's whole capability (65-F1).\n // `undefined` keeps the raw properties, which fails closed at validation exactly as before.\n const admitted = canonicalSafeFactProperties(kind, properties) ?? properties;\n return { factId: digest(['secureflow-fact-id-v2', kind, subjectId, canonicalizeJson(admitted)]), kind, subject, properties: admitted };\n}\n\nexport function emptyCandidate(seen = 0, analyzed = seen): CapabilityCandidateV2 {\n return createCapabilityCandidateAdmissionSnapshotV2({ findings: [], diagnostics: [], facts: [], traces: [], seen, analyzed, skipped: 0, omitted: 0 });\n}\n\nexport function createDiagnostic(code: DiagnosticCodeV2, capabilityId: string, required: boolean, location?: SecurityNodeV2['ref']['source'], counts?: Pick<AnalysisDiagnosticV2, 'observed' | 'maximum' | 'omitted'>): AnalysisDiagnosticV2 {\n const classification = classifyDiagnostic(code, required);\n const identity = { code, capabilityId, ...classification, ...(location === undefined ? {} : { location }), ...counts };\n return Object.freeze({ ...identity, id: createDiagnosticId(identity) });\n}\n\nexport function adaptDiagnostic(input: AnalysisDiagnostic, context: AnalyzerContextV2, capability: ProfileCapabilityV2): AnalysisDiagnosticV2 {\n const isLimit = input.code === 'ANALYSIS_LIMIT_EXCEEDED';\n const code = isLimit ? capability.required ? 'REQUIRED_LIMIT_EXCEEDED' : 'OPTIONAL_LIMIT_EXCEEDED' : input.code === 'DUPLICATE_JSON_KEY' ? 'DUPLICATE_SECURITY_KEY' : input.code as DiagnosticCodeV2;\n const nodeIndex = input.location?.path?.match(/^\\/nodes\\/(\\d+)$/)?.[1];\n const node = nodeIndex === undefined ? undefined : Array.prototype.at.call(context.workflow.nodes, Number(nodeIndex)) as SecurityNodeV2 | undefined;\n const counts = isLimit ? { observed: 1, maximum: 0, omitted: 1 } : undefined;\n return createDiagnostic(code, capability.id, capability.required, node === undefined ? undefined : admittedSource(node.ref.source), counts);\n}\n\nexport function unknownRuleDiagnostic(capability: ProfileCapabilityV2): AnalysisDiagnosticV2 {\n const ruleCase = unknownRuleCaseV2(capability);\n return createDiagnostic(UNKNOWN_RULE_DIAGNOSTIC_V2[ruleCase], capability.id, capability.required);\n}\n\nexport function policyFailureDiagnostic(capability: ProfileCapabilityV2): AnalysisDiagnosticV2 {\n return createDiagnostic('POLICY_EXECUTION_FAILED', capability.id, capability.required);\n}\n\nexport function candidateFinding(\n finding: ScanFinding,\n node: SecurityNodeV2,\n context: AnalyzerContextV2,\n capability: ProfileCapabilityV2,\n facts: SafeFactV2[],\n): FindingCandidateV2 | undefined {\n const resolution = resolveRuleAuthorityV2(context.rules.rules, finding.policyId, capability);\n if (!resolution.ok || !capability.ruleIds.includes(finding.policyId) || resolution.rule.capabilityId !== capability.id) return undefined;\n const rule = resolution.rule;\n const subject: SubjectV2 = { kind: 'NODE', node: admittedNode(node.ref) };\n const evidence = finding.evidence;\n const add = (kind: string, properties: FactProperties, factSubject: SubjectV2 = subject): string => {\n const created = makeFact(kind, factSubject, properties); if (!facts.some((item) => item.factId === created.factId)) facts.push(created); return created.factId;\n };\n const factRefs = findingFactRefs(finding, node, add);\n if (factRefs === undefined) return undefined;\n const conclusion = rule.effect === 'SCORING' && node.scoringEligibility === 'INDETERMINATE' ? 'UNKNOWN' : 'OBSERVED';\n const evidenceClass = finding.policyId.startsWith('TAINTED_') ? 'POTENTIAL_DATAFLOW' : finding.policyId.includes('DYNAMIC_EXECUTION') ? 'SUSPICIOUS_SYNTAX' : ['RAW_AUTH_HEADER', 'RAW_SECRET_INDICATOR', 'UNAPPROVED_DOMAIN', 'UNKNOWN_NODE_PACKAGE', 'WEBHOOK_EXPOSURE'].includes(finding.policyId) ? 'CONFIGURATION' : 'CAPABILITY';\n return { ruleId: finding.policyId, evidenceClass, conclusion, applicability: 'APPLICABLE', subject, factRefs, traceRefs: [], remediationId: 'r' };\n}\n\nexport function candidateFacts(finding: ScanFinding, node: SecurityNodeV2, facts: SafeFactV2[]): readonly string[] {\n const subject: SubjectV2 = { kind: 'NODE', node: admittedNode(node.ref) };\n const add = (kind: string, properties: FactProperties, factSubject: SubjectV2 = subject): string => {\n const created = makeFact(kind, factSubject, properties); if (!facts.some((item) => item.factId === created.factId)) facts.push(created); return created.factId;\n };\n return findingFactRefs(finding, node, add) ?? [];\n}\n\nfunction admittedSource(source: SecurityNodeV2['ref']['source']): SecurityNodeV2['ref']['source'] {\n const span = source.span === null ? null : { start: { ...source.span.start }, end: { ...source.span.end } };\n return { pointer: source.pointer, occurrencePath: Array.prototype.slice.call(source.occurrencePath) as number[], astNodeId: source.astNodeId, span };\n}\n\nfunction admittedNode(ref: SecurityNodeV2['ref']): SecurityNodeV2['ref'] {\n return { ...ref, source: admittedSource(ref.source) };\n}\n\nfunction findingFactRefs(finding: ScanFinding, node: SecurityNodeV2, add: (kind: string, properties: FactProperties, subject?: SubjectV2) => string): string[] | undefined {\n const e = finding.evidence; const source: SubjectV2 = { kind: 'SOURCE', source: admittedSource(node.ref.source) };\n if (finding.policyId === 'N8N_EXECUTE_COMMAND' || finding.policyId === 'N8N_CODE_NODE' || finding.policyId === 'UNKNOWN_NODE_PACKAGE') return [add('node.capability.v2', nodeCapability(node, e))];\n if (finding.policyId === 'RAW_AUTH_HEADER') return [add('node.configuration.v2', { observation: 'AUTH_HEADER', header: 'Authorization', literalValue: e.literalValue === true }, source)];\n if (finding.policyId === 'RAW_SECRET_INDICATOR') return [add('node.configuration.v2', { observation: 'SECRET_INDICATOR', parameterPath: pointer(String(e.parameterPath ?? '')), secretKind: String(e.secretKind ?? 'opaque secret'), indicator: e.indicator === 'sensitive_key' ? 'SENSITIVE_KEY' : 'SENSITIVE_VALUE', hasLiteralValue: e.hasLiteralValue === true }, source)];\n if (finding.policyId === 'UNAPPROVED_DOMAIN') {\n const destination = destinationEvidence(finding, node);\n return [add('destination.v2', destination.properties, { kind: 'SOURCE', source: destination.source })];\n }\n if (finding.policyId === 'WEBHOOK_EXPOSURE') return [add('ingress.v2', { authentication: typeof e.authentication === 'string' ? e.authentication : null, authenticationState: 'MISSING', legacyAuthenticated: false })];\n if (finding.policyId === 'JAVASCRIPT_DYNAMIC_EXECUTION' || finding.policyId === 'PYTHON_DYNAMIC_EXECUTION') return [add('code.indicator.v2', { language: finding.policyId.startsWith('JAVA') ? 'JAVASCRIPT' : 'PYTHON', indicator: String(e.indicator), ...(typeof e.member === 'string' ? { member: e.member } : {}), start: Number(e.start), end: Number(e.end), parseState: 'VERIFIED' }, source)];\n if (finding.policyId.startsWith('TAINTED_')) return [add('dataflow.summary.v2', taintProperties(finding), source)];\n if (finding.policyId === 'AI_AGENT_UNGATED_TOOL') return [add('node.capability.v2', nodeCapability(node, e)), add('dataflow.summary.v2', { flowKind: 'AGENT_INFLUENCE', propertyPathComplete: true, humanGatePresent: e.humanGatePresent === true, humanGateDominates: e.humanGateDominates === true, taintLabels: labels(e.taintLabels) }, source)];\n return undefined;\n}\nfunction destinationEvidence(finding: ScanFinding, node: SecurityNodeV2): Readonly<{ properties: FactProperties; source: SecurityNodeV2['ref']['source'] }> {\n const domain = typeof finding.evidence.domain === 'string' ? finding.evidence.domain.toLowerCase() : null;\n if (domain !== null) {\n const fields: SemanticFieldV2[] = [];\n collectSemanticFields(node.parameters, fields);\n let match: Readonly<{ path: string; source: SecurityNodeV2['ref']['source']; scheme: 'HTTP' | 'HTTPS'; hostname: string | null; authorityState: 'KNOWN' | 'UNKNOWN'; valueMode: 'LITERAL' | 'DYNAMIC' }> | undefined;\n for (const field of fields) {\n if (typeof field.value !== 'string') continue;\n let url: URL;\n try { url = new URL(field.value); } catch { continue; }\n if (url.protocol !== 'http:' && url.protocol !== 'https:' || url.hostname.toLowerCase() !== domain) continue;\n const prefix = `${node.ref.source.pointer}/parameters`;\n if (!field.pointer.startsWith(`${prefix}/`)) continue;\n const path = field.pointer.slice(prefix.length);\n for (let occurrenceIndex = 0; occurrenceIndex < field.occurrences.length; occurrenceIndex += 1) {\n const source = field.occurrences[occurrenceIndex];\n if (match === undefined || path < match.path || path === match.path && source.astNodeId < match.source.astNodeId) {\n const islands = segmentExpressionIslands(field.value);\n const valueMode = field.classification === 'EXPRESSION' || islands.some((part) => part.kind === 'EXPRESSION') ? 'DYNAMIC' : 'LITERAL';\n const masked = maskExpressions(field.value, islands);\n const authorityBoundary = authorityEnd(masked);\n const dynamicAuthority = valueMode === 'DYNAMIC' && (authorityBoundary === 0 || islands.some((part) => part.kind === 'EXPRESSION' && part.start < authorityBoundary));\n const hostname = dynamicAuthority ? null : url.hostname.toLowerCase();\n const authorityState = dynamicAuthority || hostname === null ? 'UNKNOWN' : 'KNOWN';\n match = { path, source: admittedSource(source), scheme: url.protocol === 'https:' ? 'HTTPS' : 'HTTP', hostname, authorityState, valueMode };\n }\n }\n }\n if (match !== undefined) return { source: match.source, properties: { parameterPath: match.path, scheme: match.scheme, hostname: match.hostname, authorityState: match.authorityState, valueMode: match.valueMode } };\n }\n return { source: admittedSource(node.ref.source), properties: { parameterPath: '', scheme: 'UNKNOWN', hostname: domain, authorityState: 'KNOWN', valueMode: 'UNKNOWN' } };\n}\n\nfunction maskExpressions(value: string, islands: readonly { kind: string; start: number; end: number }[]): string {\n let output = '';\n let cursor = 0;\n for (const island of islands) {\n if (island.kind !== 'EXPRESSION') continue;\n output += `${value.slice(cursor, island.start)}x`;\n cursor = island.end;\n }\n return output + value.slice(cursor);\n}\n\nfunction authorityEnd(value: string): number {\n const match = /^([A-Za-z][A-Za-z0-9+.-]*:)?\\/\\//.exec(value);\n if (!match) return 0;\n const start = match[0].length;\n const offset = value.slice(start).search(/[/?#]/);\n return offset < 0 ? value.length : start + offset;\n}\n\nfunction collectSemanticFields(fields: readonly SemanticFieldV2[], output: SemanticFieldV2[]): void {\n for (let fieldIndex = 0; fieldIndex < fields.length; fieldIndex += 1) {\n const field = fields[fieldIndex];\n output.push(field);\n if (Array.isArray(field.value)) collectSemanticFields(field.value, output);\n }\n}\nfunction nodeCapability(node: SecurityNodeV2, evidence: Record<string, unknown>): FactProperties {\n const type = node.type; const namespaceClass = type.startsWith('n8n-nodes-base.') ? 'OFFICIAL_BASE' : type.startsWith('@n8n/') ? 'OFFICIAL_SCOPED' : 'NON_OFFICIAL';\n const capabilities = type.endsWith('executeCommand') ? ['EXECUTE_COMMAND'] : type.endsWith('.code') || type.endsWith('.function') || type.endsWith('.functionItem') ? ['CUSTOM_CODE'] : type.endsWith('.webhook') ? ['WEBHOOK'] : Number(evidence.toolCount ?? 0) > 0 ? ['AI_AGENT'] : Array.isArray(evidence.capabilities) ? labels(evidence.capabilities) : [];\n return { nodeType: type, nodePackage: type.split('.')[0] ?? type, namespaceClass, capabilities, toolCount: Number(evidence.toolCount ?? 0), contextCount: Number(evidence.contextCount ?? 0) };\n}\n\nfunction taintProperties(finding: ScanFinding): FactProperties {\n const e = finding.evidence; const sink = finding.policyId === 'TAINTED_SQL_QUERY' ? 'SQL' : finding.policyId === 'TAINTED_COMMAND' ? 'COMMAND' : finding.policyId === 'TAINTED_REQUEST_URL' ? 'SSRF' : finding.policyId === 'TAINTED_FILE_PATH' ? 'PATH' : finding.policyId === 'TAINTED_CODE_INPUT' ? 'CODE' : finding.policyId === 'TAINTED_REQUEST_HEADER' ? 'HEADER' : 'PROMPT';\n return { flowKind: 'TAINT_SINK', sink, parameterPath: pointer(String(e.parameterPath ?? '')), referenceRoot: String(e.referenceRoot ?? 'DYNAMIC_NODE'), ...(typeof e.propertyPath === 'string' ? { propertyPath: pointer(e.propertyPath) } : {}), ...(typeof e.sourceNodeId === 'string' ? { sourceNodeId: e.sourceNodeId } : {}), ...(typeof e.sourceNodeName === 'string' ? { sourceNodeName: e.sourceNodeName } : {}), propertyPathComplete: e.propertyPathComplete === true, humanGatePresent: false, humanGateDominates: false, taintLabels: labels(e.taintLabels) };\n}\n\nfunction labels(value: unknown): readonly string[] { return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []; }\nfunction pointer(value: string): string { if (value === '') return ''; const parts = value.replace(/^parameters(?:\\.|$)/, '').split('.').filter(Boolean).flatMap((part) => part.match(/^[^\\[]+/)?.[0] ? [part.match(/^[^\\[]+/)![0], ...(part.match(/\\[(\\d+)\\]/g) ?? []).map((item) => item.slice(1, -1))] : []); return parts.length === 0 ? '' : `/${parts.map((part) => part.replaceAll('~', '~0').replaceAll('/', '~1')).join('/')}`; }\n", "import type { FindingConfidence, PolicyEffect, ScanSeverity } from './policy';\n\nexport type RuleCatalogEntry = {\n policyId: string;\n defaultSeverity: ScanSeverity;\n defaultConfidence: FindingConfidence;\n precision: 'HIGH' | 'MEDIUM' | 'LOW';\n policyEffect: PolicyEffect;\n curationAction: 'NONE' | 'REVIEW';\n serveAction: 'DISPLAY' | 'HIDE';\n /** CWE identifiers (`CWE-###`) this rule's finding maps to. See docs/scanner/policy-inventory.md\n * for the reviewed rationale behind each mapping, including the ones this catalog deliberately\n * narrows or rejects. Empty only for a policy ID listed in `RULES_WITHOUT_CWE`. */\n cweIds: readonly string[];\n /** OWASP Agentic Top 10 category names. Only the two agentic rules carry this; every other\n * rule leaves it undefined rather than an empty array, so \"not agentic\" and \"agentic with an\n * unresolved mapping\" stay distinguishable. */\n owaspAgenticIds?: readonly string[];\n};\n\n/**\n * Policy IDs with no CWE mapping, on purpose, not by omission. `UNAPPROVED_DOMAIN` was reviewed\n * against CWE-918 (SSRF) and that mapping was rejected: SSRF requires an attacker-influenced\n * destination, but this rule fires on any URL outside an allowlist, including one hardcoded by\n * the workflow's own author with no external input involved. CWE-918 is reserved for\n * `TAINTED_REQUEST_URL`, the rule with an actual tainted-destination claim. See the `[^domain]`\n * footnote in docs/scanner/policy-inventory.md for the full rationale.\n */\nexport const RULES_WITHOUT_CWE = ['UNAPPROVED_DOMAIN'] as const;\n\nconst betaRule = (\n policyId: string,\n defaultSeverity: ScanSeverity,\n defaultConfidence: FindingConfidence,\n precision: RuleCatalogEntry['precision'],\n cweIds: readonly string[],\n): RuleCatalogEntry => ({\n policyId,\n defaultSeverity,\n defaultConfidence,\n precision,\n policyEffect: 'LEGACY_SCORE',\n curationAction: 'NONE',\n serveAction: 'DISPLAY',\n cweIds,\n});\n\nexport const betaDefaultRuleCatalog: readonly RuleCatalogEntry[] = [\n betaRule('N8N_EXECUTE_COMMAND', 'CRITICAL', 'HIGH', 'HIGH', ['CWE-78']),\n betaRule('N8N_CODE_NODE', 'LOW', 'HIGH', 'HIGH', ['CWE-94']),\n // Literal Authorization values are a hardcoded credential (CWE-798); expression/credential-\n // driven values that still leaked as a raw header are an insufficiently protected transmission\n // (CWE-522). Both apply to this rule depending on evidence shape, so both are catalogued.\n betaRule('RAW_AUTH_HEADER', 'HIGH', 'MEDIUM', 'MEDIUM', ['CWE-798', 'CWE-522']),\n betaRule('RAW_SECRET_INDICATOR', 'HIGH', 'MEDIUM', 'MEDIUM', ['CWE-798']),\n betaRule('UNAPPROVED_DOMAIN', 'MEDIUM', 'HIGH', 'HIGH', []),\n betaRule('UNKNOWN_NODE_PACKAGE', 'LOW', 'MEDIUM', 'MEDIUM', ['CWE-1357']),\n betaRule('WEBHOOK_EXPOSURE', 'MEDIUM', 'MEDIUM', 'MEDIUM', ['CWE-306']),\n];\n\nconst reportOnlyRule = (\n policyId: string,\n defaultSeverity: ScanSeverity,\n defaultConfidence: FindingConfidence,\n precision: RuleCatalogEntry['precision'],\n cweIds: readonly string[],\n owaspAgenticIds?: readonly string[],\n): RuleCatalogEntry => ({\n policyId,\n defaultSeverity,\n defaultConfidence,\n precision,\n policyEffect: 'REPORT_ONLY',\n curationAction: 'REVIEW',\n serveAction: 'DISPLAY',\n cweIds,\n ...(owaspAgenticIds ? { owaspAgenticIds } : {}),\n});\n\nexport const TAINT_POLICY_IDS = [\n 'TAINTED_COMMAND',\n 'TAINTED_SQL_QUERY',\n 'TAINTED_REQUEST_URL',\n 'TAINTED_FILE_PATH',\n 'TAINTED_CODE_INPUT',\n 'TAINTED_REQUEST_HEADER',\n 'TAINTED_AI_PROMPT',\n 'AI_AGENT_UNGATED_TOOL',\n] as const;\n\nexport type TaintPolicyId = (typeof TAINT_POLICY_IDS)[number];\n\nexport const betaHardenedRuleCatalog: readonly RuleCatalogEntry[] = [\n ...betaDefaultRuleCatalog,\n // CWE-95 (\"Eval Injection\") precisely fits only this rule's EVAL/FUNCTION_CONSTRUCTOR\n // indicators; CHILD_PROCESS_* is closer to CWE-78 and FILESYSTEM_ACCESS to CWE-73. One CWE per\n // policy ID is a simplification of the eight indicators this rule reports under; see the\n // `[^js]`/`[^py]` footnotes in docs/scanner/policy-inventory.md.\n reportOnlyRule('JAVASCRIPT_DYNAMIC_EXECUTION', 'HIGH', 'HIGH', 'HIGH', ['CWE-95']),\n reportOnlyRule('PYTHON_DYNAMIC_EXECUTION', 'HIGH', 'MEDIUM', 'MEDIUM', ['CWE-95']),\n reportOnlyRule('TAINTED_COMMAND', 'CRITICAL', 'MEDIUM', 'MEDIUM', ['CWE-78']),\n reportOnlyRule('TAINTED_SQL_QUERY', 'HIGH', 'MEDIUM', 'MEDIUM', ['CWE-89']),\n reportOnlyRule('TAINTED_REQUEST_URL', 'HIGH', 'MEDIUM', 'MEDIUM', ['CWE-918']),\n reportOnlyRule('TAINTED_FILE_PATH', 'HIGH', 'MEDIUM', 'MEDIUM', ['CWE-22']),\n reportOnlyRule('TAINTED_CODE_INPUT', 'HIGH', 'MEDIUM', 'MEDIUM', ['CWE-94']),\n reportOnlyRule('TAINTED_REQUEST_HEADER', 'MEDIUM', 'MEDIUM', 'MEDIUM', ['CWE-113']),\n // No CWE is dedicated to LLM prompt injection; CWE-77 (\"Command Injection\") is the nearest\n // structural analogy (untrusted data reaching an interpreter that blends instructions and\n // data). OWASP Agentic's \"Prompt Injection\" is the precise, purpose-built taxonomy tag and\n // should be treated as primary; CWE-77 is a bridge for CWE-only tooling.\n reportOnlyRule('TAINTED_AI_PROMPT', 'MEDIUM', 'LOW', 'LOW', ['CWE-77'], ['Prompt Injection']),\n // CWE-269 (Improper Privilege Management) frames the agent as holding privilege it should not\n // autonomously exercise; the alternative CWE-862 (Missing Authorization) was reviewed and is\n // also defensible, but the OWASP Agentic \"Excessive Agency\" pairing does the precise work\n // either way, so CWE-269 is kept per docs/scanner/policy-inventory.md.\n reportOnlyRule('AI_AGENT_UNGATED_TOOL', 'MEDIUM', 'LOW', 'LOW', ['CWE-269'], ['Excessive Agency']),\n];\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { canonicalizeJson } from '../canonical-json';\nimport { SAFE_FACT_EVIDENCE_MAPPINGS_V2 } from '../facts/safe-fact-registry';\nimport type { AnalyzerContextV2, CapabilityCandidateV2 } from './scheduler';\n\nexport type ProfileCapabilityV2 = Readonly<{ id: string; version: string; required: boolean; dependsOn: readonly string[]; ruleIds: readonly string[] }>;\nexport type ProfileManifestV2 = Readonly<{ schemaVersion: 'scanner-profile-v2'; id: string; version: string; capabilities: readonly ProfileCapabilityV2[]; scoringPolicyVersion: string; digest: string }>;\nexport type ProfileRegistryEntryV2 = Readonly<ProfileCapabilityV2 & { run(context: AnalyzerContextV2): CapabilityCandidateV2 }>;\nexport type ProfileManifestInvalidReason = 'UNKNOWN_CAPABILITY' | 'DUPLICATE_CAPABILITY' | 'DUPLICATE_RULE_OWNER' | 'MISSING_RULE_OWNER' | 'UNKNOWN_RULE' | 'MISSING_DEPENDENCY' | 'FORWARD_DEPENDENCY' | 'DEPENDENCY_CYCLE' | 'MANIFEST_DIGEST_MISMATCH' | 'PROFILE_NOT_ADMITTED';\nexport type ProfileManifestValidationResult = Readonly<\n | { ok: true; manifest: ProfileManifestV2 }\n | { ok: false; code: 'PROFILE_MANIFEST_INVALID' | 'PROFILE_MANIFEST_NOT_ADMITTED'; reason: ProfileManifestInvalidReason }\n>;\n\nconst CAPABILITY_KEYS = ['id', 'version', 'required', 'dependsOn', 'ruleIds'] as const;\nconst MANIFEST_KEYS = ['schemaVersion', 'id', 'version', 'capabilities', 'scoringPolicyVersion', 'digest'] as const;\nconst RUN_KEYS = [...CAPABILITY_KEYS, 'run'] as const;\n/**\n * Rule ownership is a property of the rule, not a second declaration: the safe-fact evidence\n * registry (`SAFE_FACT_EVIDENCE_MAPPINGS_V2`) is the single owner authority behind the admitted\n * rule's `capabilityId`, so a capability's `ruleIds` is projected from it in registry order.\n * Nothing here may hand-declare an owner, claim a rule the registry does not know, or leave a\n * registry rule unowned.\n */\nconst KNOWN_RULE_IDS: ReadonlySet<string> = new Set(SAFE_FACT_EVIDENCE_MAPPINGS_V2.map(({ ruleId }) => ruleId));\nconst NO_RULES: readonly string[] = Object.freeze([]);\nconst RULE_IDS_BY_CAPABILITY: ReadonlyMap<string, readonly string[]> = (() => {\n const owned = new Map<string, string[]>();\n for (const { ruleId, ownerCapabilityId } of SAFE_FACT_EVIDENCE_MAPPINGS_V2) {\n const rules = owned.get(ownerCapabilityId);\n if (rules) rules.push(ruleId); else owned.set(ownerCapabilityId, [ruleId]);\n }\n return new Map([...owned].map(([capabilityId, rules]) => [capabilityId, Object.freeze(rules)] as const));\n})();\n\nconst SCORING_POLICY_VERSION = 'secureflow-risk-v2@2.0.0';\nconst MAX_CAPABILITIES = 32;\nconst MAX_LIST_ITEMS = 17;\nconst MAX_STRING_LENGTH = 128;\n\nfunction capability(id: string, required: boolean, dependsOn: readonly string[]): ProfileCapabilityV2 {\n return Object.freeze({ id, version: '2.0.0', required, dependsOn: Object.freeze([...dependsOn]), ruleIds: RULE_IDS_BY_CAPABILITY.get(id) ?? NO_RULES });\n}\nfunction buildManifest(id: string, capabilities: readonly ProfileCapabilityV2[]): ProfileManifestV2 {\n const body = { schemaVersion: 'scanner-profile-v2' as const, id, version: '2.0.0', capabilities: Object.freeze([...capabilities]), scoringPolicyVersion: SCORING_POLICY_VERSION };\n return Object.freeze({ ...body, digest: computeProfileManifestDigest(body) });\n}\n\nconst source = capability('source-normalization', true, []);\nconst insights = capability('workflow-insights', true, ['source-normalization']);\nconst structural = capability('structural-policies', true, ['source-normalization']);\nconst assessment = capability('assessment', true, ['workflow-insights', 'structural-policies']);\nconst presentation = capability('presentation-facts', true, ['assessment']);\n\nexport const BETA_DEFAULT_PROFILE_MANIFEST = buildManifest('beta-default', [source, insights, structural, assessment, presentation]);\nexport const BETA_HARDENED_PROFILE_MANIFEST = buildManifest('beta-hardened', [\n source, insights, structural, capability('expression-security', false, ['source-normalization']),\n capability('javascript-security', false, ['source-normalization']),\n capability('python-security', false, ['source-normalization']),\n capability('graph-semantics', false, ['source-normalization']),\n capability('taint-confidentiality', false, ['graph-semantics', 'expression-security', 'javascript-security', 'python-security']),\n capability('taint-integrity', false, ['graph-semantics', 'expression-security', 'javascript-security', 'python-security']),\n capability('agentic-control', false, ['graph-semantics', 'taint-confidentiality', 'taint-integrity']), assessment, presentation,\n]);\nexport const PROFILE_MANIFEST_REGISTRY_V2 = Object.freeze([BETA_DEFAULT_PROFILE_MANIFEST, BETA_HARDENED_PROFILE_MANIFEST]);\nexport const ADMITTED_PROFILE_MANIFESTS_V2 = Object.freeze([BETA_DEFAULT_PROFILE_MANIFEST]);\nexport const PROFILE_MANIFEST_REGISTRY = PROFILE_MANIFEST_REGISTRY_V2;\nexport const ADMITTED_PROFILE_REGISTRY_V2 = ADMITTED_PROFILE_MANIFESTS_V2;\nexport const BETA_DEFAULT_MANIFEST = BETA_DEFAULT_PROFILE_MANIFEST;\nexport const BETA_HARDENED_MANIFEST = BETA_HARDENED_PROFILE_MANIFEST;\n\nexport function computeProfileManifestDigest(manifest: Omit<ProfileManifestV2, 'digest'>): string {\n return bytesToHex(sha256(new TextEncoder().encode(canonicalizeJson(manifest))));\n}\n\nexport function isProfileAdmitted(candidate: unknown): boolean {\n try {\n const manifest = readManifest(candidate, true);\n const { digest, ...body } = manifest;\n return sameManifest(manifest, BETA_DEFAULT_PROFILE_MANIFEST) && computeProfileManifestDigest(body) === digest;\n } catch { return false; }\n}\n\nexport function validateProfileManifest(candidate: unknown, registry: ReadonlyMap<string, ProfileRegistryEntryV2>): ProfileManifestValidationResult {\n try {\n const manifest = readManifest(candidate, false);\n const expected = PROFILE_MANIFEST_REGISTRY_V2.find((item) => item.id === manifest.id && item.version === manifest.version);\n if (!expected) return invalid('UNKNOWN_CAPABILITY');\n const ids = new Set<string>();\n for (const item of manifest.capabilities) { if (ids.has(item.id)) return invalid('DUPLICATE_CAPABILITY'); ids.add(item.id); }\n const index = new Map(manifest.capabilities.map((item, position) => [item.id, position]));\n for (const item of manifest.capabilities) for (const dependency of item.dependsOn) {\n if (!ids.has(dependency)) return invalid('MISSING_DEPENDENCY');\n }\n if (hasCycle(manifest.capabilities)) return invalid('DEPENDENCY_CYCLE');\n for (const item of manifest.capabilities) if (item.dependsOn.some((dependency) => index.get(dependency)! >= index.get(item.id)!)) return invalid('FORWARD_DEPENDENCY');\n const owners = new Map<string, string>();\n for (const item of manifest.capabilities) for (const ruleId of item.ruleIds) {\n if (!KNOWN_RULE_IDS.has(ruleId)) return invalid('UNKNOWN_RULE');\n if (owners.has(ruleId)) return invalid('DUPLICATE_RULE_OWNER');\n owners.set(ruleId, item.id);\n }\n for (const item of manifest.capabilities) for (const ruleId of RULE_IDS_BY_CAPABILITY.get(item.id) ?? NO_RULES) {\n if (owners.get(ruleId) !== item.id) return invalid('MISSING_RULE_OWNER');\n }\n if (!sameCapabilities(manifest.capabilities, expected.capabilities)) return invalid('UNKNOWN_CAPABILITY');\n if (manifest.scoringPolicyVersion !== SCORING_POLICY_VERSION) return invalid('UNKNOWN_CAPABILITY');\n const { digest: _digest, ...body } = manifest;\n if (computeProfileManifestDigest(body) !== manifest.digest) return invalid('MANIFEST_DIGEST_MISMATCH');\n const normalized = freezeManifest(manifest);\n if (!isProfileAdmitted(normalized)) return Object.freeze({ ok: false, code: 'PROFILE_MANIFEST_NOT_ADMITTED', reason: 'PROFILE_NOT_ADMITTED' });\n for (const item of normalized.capabilities) {\n const spec = registryEntry(registry, item.id);\n if (!spec || !sameCapability(item, readCapability(spec, true, false))) return invalid('UNKNOWN_CAPABILITY');\n }\n return Object.freeze({ ok: true, manifest: normalized });\n } catch { return invalid('UNKNOWN_CAPABILITY'); }\n}\n\nfunction invalid(reason: ProfileManifestInvalidReason): ProfileManifestValidationResult { return Object.freeze({ ok: false, code: 'PROFILE_MANIFEST_INVALID', reason }); }\nfunction registryEntry(registry: ReadonlyMap<string, ProfileRegistryEntryV2>, id: string): ProfileRegistryEntryV2 | undefined {\n if (!(registry instanceof Map) || Object.getPrototypeOf(registry) !== Map.prototype) throw new TypeError();\n ownNames(registry, 0, 0);\n return Map.prototype.get.call(registry, id) as ProfileRegistryEntryV2 | undefined;\n}\nfunction readManifest(input: unknown, requireFrozen: boolean): ProfileManifestV2 {\n const value = record(input, MANIFEST_KEYS, requireFrozen); const capabilities = dense(value.capabilities, MAX_CAPABILITIES, requireFrozen).map((item) => readCapability(item, false, requireFrozen));\n if (value.schemaVersion !== 'scanner-profile-v2' || typeof value.id !== 'string' || typeof value.version !== 'string' || typeof value.scoringPolicyVersion !== 'string' || typeof value.digest !== 'string') throw new TypeError();\n return { schemaVersion: value.schemaVersion, id: value.id, version: value.version, capabilities, scoringPolicyVersion: value.scoringPolicyVersion, digest: value.digest };\n}\nfunction readCapability(input: unknown, withRunner: boolean, requireFrozen: boolean): ProfileCapabilityV2 {\n const value = record(input, withRunner ? RUN_KEYS : CAPABILITY_KEYS, requireFrozen); const id = boundedString(value.id); const version = boundedString(value.version);\n const dependsOn = stringList(value.dependsOn, requireFrozen); const ruleIds = stringList(value.ruleIds, requireFrozen);\n if (typeof value.required !== 'boolean' || withRunner && typeof value.run !== 'function') throw new TypeError();\n return { id, version, required: value.required, dependsOn, ruleIds };\n}\nfunction record(input: unknown, allowed: readonly string[], requireFrozen: boolean): Record<string, unknown> {\n if (input === null || typeof input !== 'object' || Array.isArray(input) || Object.getPrototypeOf(input) !== Object.prototype && Object.getPrototypeOf(input) !== null) throw new TypeError();\n if (requireFrozen && !Object.isFrozen(input)) throw new TypeError();\n const names = ownNames(input, allowed.length, 0);\n const result = Object.create(null) as Record<string, unknown>;\n for (const name of names) { if (!allowed.includes(name)) throw new TypeError(); const descriptor = Object.getOwnPropertyDescriptor(input, name); if (!descriptor || !('value' in descriptor)) throw new TypeError(); result[name] = descriptor.value; }\n for (const name of allowed) if (!Object.prototype.hasOwnProperty.call(result, name)) throw new TypeError();\n return result;\n}\nfunction dense(input: unknown, maximum: number, requireFrozen: boolean): unknown[] {\n if (!Array.isArray(input) || Object.getPrototypeOf(input) !== Array.prototype) throw new TypeError();\n if (requireFrozen && !Object.isFrozen(input)) throw new TypeError();\n const lengthDescriptor = Object.getOwnPropertyDescriptor(input, 'length');\n if (!lengthDescriptor || !('value' in lengthDescriptor) || !Number.isSafeInteger(lengthDescriptor.value) || lengthDescriptor.value < 0 || lengthDescriptor.value > maximum) throw new TypeError();\n const names = ownNames(input, lengthDescriptor.value + 1, 0); if (names.length !== lengthDescriptor.value + 1) throw new TypeError();\n const values: unknown[] = [];\n for (let index = 0; index < lengthDescriptor.value; index += 1) { const descriptor = Object.getOwnPropertyDescriptor(input, String(index)); if (!descriptor || !('value' in descriptor)) throw new TypeError(); values.push(descriptor.value); }\n for (const name of names) if (name !== 'length' && (!/^\\d+$/.test(name) || Number(name) >= lengthDescriptor.value)) throw new TypeError();\n return values;\n}\nfunction stringList(input: unknown, requireFrozen: boolean): readonly string[] {\n const values = dense(input, MAX_LIST_ITEMS, requireFrozen); return Object.freeze(values.map((value) => boundedString(value)));\n}\nfunction ownNames(input: object, maximum: number, maximumSymbols: number): readonly string[] {\n const names = Object.getOwnPropertyNames(input); if (names.length > maximum) throw new TypeError();\n if (Object.getOwnPropertySymbols(input).length > maximumSymbols) throw new TypeError(); return names;\n}\nfunction boundedString(value: unknown): string { if (typeof value !== 'string' || value.length === 0 || value.length > MAX_STRING_LENGTH) throw new TypeError(); return value; }\nfunction hasCycle(capabilities: readonly ProfileCapabilityV2[]): boolean {\n const indegree = new Map(capabilities.map((item) => [item.id, item.dependsOn.length])); const dependents = new Map(capabilities.map((item) => [item.id, [] as string[]]));\n for (const item of capabilities) for (const dependency of item.dependsOn) dependents.get(dependency)!.push(item.id);\n const queue = capabilities.filter((item) => indegree.get(item.id) === 0).map(({ id }) => id); let visited = 0;\n for (let cursor = 0; cursor < queue.length; cursor += 1) { const id = queue[cursor]; visited += 1; for (const dependent of dependents.get(id)!) { const next = indegree.get(dependent)! - 1; indegree.set(dependent, next); if (next === 0) queue.push(dependent); } }\n return visited !== capabilities.length;\n}\nfunction sameCapability(left: ProfileCapabilityV2, right: ProfileCapabilityV2): boolean { return left.id === right.id && left.version === right.version && left.required === right.required && sameList(left.dependsOn, right.dependsOn) && sameList(left.ruleIds, right.ruleIds); }\nfunction sameCapabilities(left: readonly ProfileCapabilityV2[], right: readonly ProfileCapabilityV2[]): boolean { return left.length === right.length && left.every((item, index) => sameCapability(item, right[index])); }\nfunction sameManifest(left: ProfileManifestV2, right: ProfileManifestV2): boolean { return left.schemaVersion === right.schemaVersion && left.id === right.id && left.version === right.version && left.scoringPolicyVersion === right.scoringPolicyVersion && left.digest === right.digest && sameCapabilities(left.capabilities, right.capabilities); }\nfunction sameList(left: readonly string[], right: readonly string[]): boolean { return left.length === right.length && left.every((item, index) => item === right[index]); }\nfunction freezeManifest(manifest: ProfileManifestV2): ProfileManifestV2 {\n const capabilities = Object.freeze(manifest.capabilities.map((item) => Object.freeze({ ...item, dependsOn: Object.freeze([...item.dependsOn]), ruleIds: Object.freeze([...item.ruleIds]) })));\n return Object.freeze({ ...manifest, capabilities });\n}\n", "import type { ScannerLimitsV2 } from '@hub/contracts';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { canonicalizeJson } from '../canonical-json';\nimport { createDiagnosticId } from '../diagnostics/identity';\nimport { DIAGNOSTIC_CODES_V2, classifyDiagnostic, type AnalysisDiagnosticV2 } from '../diagnostics/registry';\nimport { countInconsistency, omissionInconsistency } from './count-lattice';\nimport { createEdgeIdentityDigest, encodeIdentityTuple } from '../workflow-v2/node-edge-identity';\nimport type { EdgeRefV2 } from '../workflow-v2/security-workflow';\nimport { freezeData, readArrayItem, readArrayLength, readDenseArray, readPlainRecord, readSourceMemberRef, readSubject, type SafeFactValidationResultV2, validateSafeFact } from '../facts/safe-fact-validator';\nimport { createSafeFactAdmissionSnapshotV2, isScannerAdmissionSnapshotV2 } from '../admission/snapshot';\nimport { betaHardenedRuleCatalog } from '../policy/rule-catalog';\nimport { PROFILE_MANIFEST_REGISTRY_V2 } from './profile-manifest';\nimport { SAFE_FACT_AUTHORITY_DIGEST_V2, SAFE_FACT_EVIDENCE_MAPPINGS_V2, SAFE_FACT_REGISTRY_V2, type SafeFactEvidenceMappingV2, type SafeFactRegistryV2, type SafeFactSchemaV2, type SafePropertyTypeV2 } from '../facts/safe-fact-registry';\nimport type { AdmittedRuleV2, CapabilityCandidateV2, CapabilitySpecV2, FindingCandidateV2, SafeFactV2, SubjectV2, TraceV2 } from './scheduler';\n\ntype RuleRegistryV2 = ReadonlyMap<string, AdmittedRuleV2>;\ntype MutableCandidateCountersV2 = { seen: number; analyzed: number; skipped: number; omitted: number };\ntype CandidateCountersV2 = Readonly<MutableCandidateCountersV2>;\ntype CandidateLimitNumbersV2 = Readonly<{ observed: number; maximum: number }>;\ntype MutableDiagnosticCountersV2 = { observed?: number; maximum?: number; omitted?: number };\ntype SafeFactScalarV2 = string | number | boolean | null;\ntype SafeFactValueV2 = SafeFactScalarV2 | readonly SafeFactScalarV2[];\ntype EvidenceBudgetV2 = { bytes: number; counts: [number, number, number, number]; maximum: number };\nconst getOwnPropertyNames = Object.getOwnPropertyNames;\nconst getOwnPropertySymbols = Object.getOwnPropertySymbols;\nexport type CandidateRegistriesV2 = Readonly<{ facts: SafeFactRegistryV2; rules: RuleRegistryV2 }>;\nexport type CandidateRejectionReasonV2 = 'MALFORMED_CANDIDATE' | 'UNKNOWN_KEY' | 'DUPLICATE_ID' | 'DANGLING_REFERENCE' | 'UNKNOWN_RULE' | 'UNOWNED_RULE' | 'INVALID_COUNTER' | 'LIMIT_EXCEEDED' | 'FORBIDDEN_CONTENT' | 'UNSAFE_INPUT';\nexport type CapabilityCandidateValidationResultV2 = Readonly<{ ok: true; candidate: CapabilityCandidateV2 } | { ok: false; code: 'CAPABILITY_CANDIDATE_REJECTED'; reason: CandidateRejectionReasonV2; counters: Readonly<CandidateCountersV2>; limit?: CandidateLimitNumbersV2 }>;\ntype AuxiliaryRejectionReasonV2 = 'UNKNOWN_PROPERTY' | 'INVALID_PROPERTY' | 'INVALID_SUBJECT' | 'UNKNOWN_FACT_KIND' | 'REGISTRY_MISMATCH';\ntype Reason = CandidateRejectionReasonV2 | AuxiliaryRejectionReasonV2;\nfunction fail(reason: Reason): never { throw reason; }\n/**\n * A limit refusal that carries the numbers the scheduler publishes. The shared array readers throw\n * the bare reason, so the checks below re-read a collection's size before delegating and report the\n * refusal as `observed` (the real size that crossed, or the one item over a zero allowance) against\n * `maximum` (the bound that fired) \u2014 the numbers `readDiagnostics` here already demands of\n * capability-emitted LIMIT diagnostics, and previously missing from the validator's own refusals.\n */\nclass CandidateLimitExceededV2 extends TypeError {\n readonly observed: number;\n readonly maximum: number;\n constructor(observed: number, maximum: number) { super('Limit exceeded'); this.observed = observed; this.maximum = maximum; }\n}\nfunction limitExceeded(observed: number, maximum: number): never { throw new CandidateLimitExceededV2(observed > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : observed, maximum); }\n/** The length a shared array reader compares, read for the refusal's numbers only. */\nfunction observedArrayLength(input: unknown): number | undefined {\n if (!Array.isArray(input) || Object.getPrototypeOf(input) !== Array.prototype) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(input, 'length');\n return descriptor !== undefined && 'value' in descriptor && Number.isSafeInteger(descriptor.value) && descriptor.value >= 0 ? descriptor.value : undefined;\n}\nfunction readBoundedLength(input: unknown, maximum: number, dense = true): number {\n const observed = observedArrayLength(input);\n if (observed !== undefined && observed > maximum) limitExceeded(observed, maximum);\n return readArrayLength(input, maximum, dense);\n}\nfunction readBoundedArray(input: unknown, maximum: number): unknown[] {\n const observed = observedArrayLength(input);\n if (observed !== undefined && observed > maximum) limitExceeded(observed, maximum);\n return readDenseArray(input, maximum);\n}\nconst knownReasons: Readonly<Record<string, true>> = { MALFORMED_CANDIDATE: true, UNKNOWN_KEY: true, DUPLICATE_ID: true, DANGLING_REFERENCE: true, UNKNOWN_RULE: true, UNOWNED_RULE: true, INVALID_COUNTER: true, LIMIT_EXCEEDED: true, FORBIDDEN_CONTENT: true, UNSAFE_INPUT: true };\nconst auxiliaryReasons: readonly AuxiliaryRejectionReasonV2[] = ['UNKNOWN_PROPERTY', 'INVALID_PROPERTY', 'INVALID_SUBJECT', 'UNKNOWN_FACT_KIND', 'REGISTRY_MISMATCH'];\nconst isReason = (value: string): value is Reason => knownReasons[value] === true || auxiliaryReasons.some((reason) => reason === value);\nconst has = (value: Readonly<Record<string, unknown>>, key: string): boolean => Object.prototype.hasOwnProperty.call(value, key);\nconst keys = ['findings', 'diagnostics', 'facts', 'traces', 'seen', 'analyzed', 'skipped', 'omitted'] as const;\nconst text = (value: unknown, maximum = 4_096): string => { if (typeof value !== 'string') return fail('MALFORMED_CANDIDATE'); let bytes = 0; for (let index = 0; index < value.length; index += 1) { const code = value.charCodeAt(index); if (code === 0) return fail('FORBIDDEN_CONTENT'); if (code >= 0xd800 && code <= 0xdbff) { if (index + 1 >= value.length || value.charCodeAt(index + 1) < 0xdc00 || value.charCodeAt(index + 1) > 0xdfff) return fail('FORBIDDEN_CONTENT'); bytes += 4; index += 1; } else if (code >= 0xdc00 && code <= 0xdfff) return fail('FORBIDDEN_CONTENT'); else bytes += code <= 0x7f ? 1 : code <= 0x7ff ? 2 : 3; if (bytes > maximum) return fail('FORBIDDEN_CONTENT'); } return value; };\nconst absolutePath = (value: string): boolean => value.startsWith('/') || value.startsWith('\\\\') || value.startsWith('~/') || /^(?:\\.\\.[\\\\/]|[A-Za-z]:[\\\\/])/.test(value) || /(?:^|[\\\\/])\\.\\.(?:[\\\\/]|$)/.test(value);\nconst sourceLike = (value: string): boolean => /[=;{}[\\]`\\\\]/.test(value) || /\\b(?:require|import|export|const|let|var|function)\\b/.test(value) || /\\(\\s*[\"']/.test(value) || /^\\\\\\\\/.test(value);\nconst secretLike = /(?:\\b(?:api[ _-]*key|password|secret|credential|authorization|cookie|bearer(?:[ _-]+token)?|basic[ _-]+auth|access[ _-]*(?:key|token)|token)\\s*[:=]\\s*[^\\s,;]+|\\b(?:sk|gh[pousr]|xox[baprs])[-_][A-Za-z0-9_-]{8,}|\\beyJ[A-Za-z0-9_-]{12,}\\.[A-Za-z0-9_-]{8,})/i;\nfunction validateSubjectContent(subject: SubjectV2): void { const walk = (value: unknown, key = ''): void => { if (typeof value === 'string') { if (!['kind', 'resolution', 'astNodeId', 'pointer'].includes(key) && (absolutePath(value) || sourceLike(value) || secretLike.test(value))) fail('FORBIDDEN_CONTENT'); return; } if (Array.isArray(value)) { value.forEach((item) => walk(item, key)); return; } if (value !== null && typeof value === 'object') for (const name of Object.keys(value)) walk((value as Record<string, unknown>)[name], name); }; walk(subject); }\nfunction fieldText(value: unknown, field: string, maximum = 4_096): string { const result = text(value, maximum); if (secretLike.test(result)) return fail('FORBIDDEN_CONTENT'); if (field === 'member' && !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(result)) return fail('FORBIDDEN_CONTENT'); if (field === 'header' && result !== '' && !/^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/.test(result)) return fail('FORBIDDEN_CONTENT'); if (field === 'authentication' && !/^[A-Za-z0-9_.:-]*$/.test(result)) return fail('FORBIDDEN_CONTENT'); if (['member', 'sourceNodeName', 'nodeType', 'nodePackage', 'service'].includes(field) && absolutePath(result)) return fail('FORBIDDEN_CONTENT'); return result; }\nconst id = (value: unknown): string => { const result = text(value, 64); if (!/^[0-9a-f]{64}$/.test(result)) fail('MALFORMED_CANDIDATE'); return result; };\nconst integer = (value: unknown): number => { if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) return fail('INVALID_COUNTER'); return value; };\nconst compare = (left: string, right: string): number => { const a = Array.from(left, (c) => c.codePointAt(0)!); const b = Array.from(right, (c) => c.codePointAt(0)!); for (let i = 0; i < Math.min(a.length, b.length); i += 1) if (a[i] !== b[i]) return a[i] - b[i]; return a.length - b.length; };\nconst digest = (parts: readonly string[]): string => bytesToHex(sha256(new TextEncoder().encode(encodeIdentityTuple(parts))));\nconst enums = { evidenceClass: ['CAPABILITY', 'CONFIGURATION', 'SUSPICIOUS_SYNTAX', 'POTENTIAL_DATAFLOW', 'VERSION_APPLICABILITY'], conclusion: ['OBSERVED', 'POTENTIAL', 'UNKNOWN'], applicability: ['APPLICABLE', 'NOT_APPLICABLE', 'UNKNOWN'], trace: ['CONFIDENTIALITY', 'INTEGRITY', 'CONTROL'], step: ['SOURCE', 'PROPAGATION', 'SANITIZER', 'SINK'] } as const;\nfunction enumValue<T extends string>(value: unknown, values: readonly T[]): T { const candidate = text(value); const match = values.find((item) => item === candidate); if (match !== undefined) return match; return fail('MALFORMED_CANDIDATE'); }\nfunction rejected(reason: Reason, counters: CandidateCountersV2, limit?: CandidateLimitNumbersV2): CapabilityCandidateValidationResultV2 {\n let normalized: CandidateRejectionReasonV2;\n switch (reason) {\n case 'UNKNOWN_PROPERTY': normalized = 'UNKNOWN_KEY'; break;\n case 'INVALID_PROPERTY':\n case 'INVALID_SUBJECT':\n case 'UNKNOWN_FACT_KIND':\n case 'REGISTRY_MISMATCH': normalized = 'MALFORMED_CANDIDATE'; break;\n default: normalized = reason;\n }\n return Object.freeze({ ok: false as const, code: 'CAPABILITY_CANDIDATE_REJECTED' as const, reason: normalized, counters: Object.freeze({ ...counters }), ...(limit === undefined ? {} : { limit: Object.freeze({ observed: limit.observed, maximum: limit.maximum }) }) });\n}\nfunction counters(value: Record<string, unknown>): MutableCandidateCountersV2 { for (const key of ['seen', 'analyzed', 'skipped', 'omitted']) if (typeof value[key] === 'string') text(value[key]); return { seen: integer(value.seen), analyzed: integer(value.analyzed), skipped: integer(value.skipped), omitted: integer(value.omitted) }; }\nfunction ownRecord(input: unknown, allowed: readonly string[], unknownReason: Reason, required = allowed): Record<string, unknown> { void unknownReason; return readPlainRecord(input, allowed, required, true); } function candidateRecord(input: unknown): Record<string, unknown> { if (input === null || typeof input !== 'object') return fail('UNSAFE_INPUT'); const value: Record<string, unknown> = {}; for (const key of keys) { const descriptor = Object.getOwnPropertyDescriptor(input, key); if (!descriptor || !('value' in descriptor)) return fail('UNSAFE_INPUT'); value[key] = descriptor.value; } return value; }\nfunction capabilityRecord(input: unknown): Record<string, unknown> { return ownRecord(input, ['id', 'version', 'required', 'dependsOn', 'ruleIds', 'run'], 'MALFORMED_CANDIDATE'); }\nconst capabilityAuthorities = PROFILE_MANIFEST_REGISTRY_V2.flatMap((profile) => profile.capabilities);\nconst sameList = (left: readonly string[], right: readonly string[]): boolean => left.length === right.length && left.every((item, index) => item === right[index]);\nfunction capabilityView(input: CapabilitySpecV2, limits: ScannerLimitsV2): { id: string; version: string; required: boolean; dependsOn: readonly string[]; ruleIds: ReadonlySet<string> } { const value = capabilityRecord(input); const capabilityId = text(value.id); const version = text(value.version); const required = value.required; const run = value.run; if (typeof required !== 'boolean' || typeof run !== 'function') return fail('MALFORMED_CANDIDATE'); const dependencies = readBoundedArray(value.dependsOn, limits.maxMembersAndElements).map((item) => text(item)); const ruleValues = readBoundedArray(value.ruleIds, limits.maxMembersAndElements).map((item) => text(item)); const authority = capabilityAuthorities.find((item) => item.id === capabilityId && item.version === version && item.required === required && sameList(dependencies, item.dependsOn) && sameList(ruleValues, item.ruleIds)); if (!authority) return fail('MALFORMED_CANDIDATE'); const ruleIds = new Set(ruleValues); return { id: capabilityId, version, required, dependsOn: Object.freeze(dependencies), ruleIds }; }\nconst propertyTypes = ['STRING', 'INTEGER', 'BOOLEAN', 'NULLABLE_STRING', 'STRING_LIST', 'INTEGER_LIST'] as const;\nconst sensitivities = ['PUBLIC_METADATA', 'REDACTED_SECURITY'] as const;\nfunction schemaProperties(input: unknown, expected: SafeFactSchemaV2): Readonly<Record<string, SafePropertyTypeV2>> { const value = ownRecord(input, Object.keys(expected.properties), 'MALFORMED_CANDIDATE'); const properties: Record<string, SafePropertyTypeV2> = {}; for (const key of Object.keys(expected.properties)) properties[key] = enumValue(value[key], propertyTypes); return Object.freeze(properties); }\nfunction snapshotRegistry(input: unknown): readonly SafeFactSchemaV2[] { const value = ownRecord(input, ['schemaVersion', 'version', 'schemas', 'digest'], 'MALFORMED_CANDIDATE'); if (value.schemaVersion !== 'scanner-safe-facts-v2' || value.version !== SAFE_FACT_REGISTRY_V2.version) return fail('MALFORMED_CANDIDATE'); const rawSchemas = readBoundedArray(value.schemas, SAFE_FACT_REGISTRY_V2.schemas.length); if (rawSchemas.length !== SAFE_FACT_REGISTRY_V2.schemas.length) return fail('MALFORMED_CANDIDATE'); const schemas = rawSchemas.map((raw) => { const schema = ownRecord(raw, ['kind', 'ownerCapabilityId', 'properties', 'maxStringBytes', 'maxItems', 'sensitivity'], 'MALFORMED_CANDIDATE'); const expected = SAFE_FACT_REGISTRY_V2.schemas.find((item) => item.kind === schema.kind); if (expected === undefined) return fail('MALFORMED_CANDIDATE'); const copy: SafeFactSchemaV2 = Object.freeze({ kind: text(schema.kind), ownerCapabilityId: text(schema.ownerCapabilityId), properties: schemaProperties(schema.properties, expected), maxStringBytes: integer(schema.maxStringBytes), maxItems: integer(schema.maxItems), sensitivity: enumValue(schema.sensitivity, sensitivities) }); if (canonicalizeJson(copy) !== canonicalizeJson(expected)) return fail('MALFORMED_CANDIDATE'); return expected; }); const body = { schemaVersion: 'scanner-safe-facts-v2' as const, version: text(value.version), schemas }; const expectedDigest = bytesToHex(sha256(new TextEncoder().encode(canonicalizeJson(body)))); if (id(value.digest) !== expectedDigest || id(value.digest) !== SAFE_FACT_REGISTRY_V2.digest) return fail('MALFORMED_CANDIDATE'); return Object.freeze(schemas); }\ntype RuleAuthorityV2 = Omit<AdmittedRuleV2, 'packDigest'>;\nconst ruleAuthorities = new Map(SAFE_FACT_EVIDENCE_MAPPINGS_V2.map((mapping) => { const catalog = betaHardenedRuleCatalog.find((entry) => entry.policyId === mapping.ruleId); if (!catalog) throw new TypeError('Incomplete rule authority'); return [mapping.ruleId, Object.freeze({ ruleId: mapping.ruleId, revision: '1', capabilityId: mapping.ownerCapabilityId, effect: mapping.ownerCapabilityId === 'structural-policies' ? 'SCORING' : 'REPORT_ONLY', severity: catalog.defaultSeverity, confidence: catalog.defaultConfidence, evidenceSchemaId: mapping.evidenceSchemaId, remediationId: 'r', cweIds: Object.freeze([...catalog.cweIds]), owaspAgenticIds: Object.freeze([...(catalog.owaspAgenticIds ?? [])]) }) as RuleAuthorityV2] as const; }));\nconst ruleAuthorityBody = Object.freeze([...ruleAuthorities.values()].sort((left, right) => left.ruleId < right.ruleId ? -1 : 1));\nexport const RULE_PACK_DIGEST_V2 = digest(['secureflow-rule-pack-v2', '2.0.0', SAFE_FACT_AUTHORITY_DIGEST_V2, canonicalizeJson(ruleAuthorityBody)]);\nfunction sameRule(left: RuleAuthorityV2, right: RuleAuthorityV2): boolean {\n return canonicalizeJson(left) === canonicalizeJson(right);\n}\nfunction normalizeRule(key: unknown, raw: unknown, limits: ScannerLimitsV2): AdmittedRuleV2 { if (typeof key !== 'string') return fail('UNSAFE_INPUT'); const expected = ruleAuthorities.get(key); if (!expected) return fail('MALFORMED_CANDIDATE'); const value = ownRecord(raw, ['ruleId', 'revision', 'capabilityId', 'effect', 'severity', 'confidence', 'evidenceSchemaId', 'remediationId', 'cweIds', 'owaspAgenticIds', 'packDigest'], 'MALFORMED_CANDIDATE'); const effect = enumValue(value.effect, ['SCORING', 'REPORT_ONLY']); const severity = enumValue(value.severity, ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'INFO']); const confidence = enumValue(value.confidence, ['HIGH', 'MEDIUM', 'LOW']); const list = (input: unknown): readonly string[] => Object.freeze(readBoundedArray(input, Math.min(4_096, limits.maxMembersAndElements)).map((item) => fieldText(item, 'registry'))); const actual: AdmittedRuleV2 = Object.freeze({ ruleId: fieldText(value.ruleId, 'ruleId'), revision: fieldText(value.revision, 'revision'), capabilityId: fieldText(value.capabilityId, 'capabilityId'), effect, severity, confidence, evidenceSchemaId: fieldText(value.evidenceSchemaId, 'evidenceSchemaId'), remediationId: fieldText(value.remediationId, 'remediationId'), cweIds: list(value.cweIds), owaspAgenticIds: list(value.owaspAgenticIds), packDigest: id(value.packDigest) }); const { packDigest, ...metadata } = actual; if (actual.ruleId !== key || packDigest !== RULE_PACK_DIGEST_V2 || !sameRule(metadata, expected)) return fail('MALFORMED_CANDIDATE'); return actual; }\nfunction ruleRegistry(input: unknown, limits: ScannerLimitsV2, required: ReadonlySet<string>): RuleRegistryV2 {\n try {\n if (input === null || typeof input !== 'object') return fail('UNSAFE_INPUT');\n const sizeDescriptor = Object.getOwnPropertyDescriptor(Map.prototype, 'size');\n if (!sizeDescriptor || typeof sizeDescriptor.get !== 'function') return fail('UNSAFE_INPUT');\n let size: unknown; try { size = sizeDescriptor.get.call(input); } catch { return fail('UNSAFE_INPUT'); }\n if (!Number.isSafeInteger(size) || (size as number) < 0) return fail('UNSAFE_INPUT');\n if ((size as number) > limits.maxRuleOperations) return limitExceeded(size as number, limits.maxRuleOperations);\n let ownNames: string[]; let ownSymbols: symbol[];\n try { ownNames = getOwnPropertyNames(input); ownSymbols = getOwnPropertySymbols(input); } catch { return fail('UNSAFE_INPUT'); }\n if (ownNames.length !== 0) return fail('UNKNOWN_KEY');\n if (ownSymbols.length !== 0) return fail('UNSAFE_INPUT');\n const snapshot = new Map<string, unknown>();\n const entries = Map.prototype.entries.call(input) as Iterator<[unknown, unknown]>;\n for (let index = 0; index < (size as number); index += 1) {\n const next = entries.next(); if (next.done) return fail('UNSAFE_INPUT'); const [key, raw] = next.value;\n if (typeof key !== 'string') return fail('UNSAFE_INPUT');\n snapshot.set(key, normalizeRule(key, raw, limits));\n }\n if (snapshot.size !== required.size || [...required].some((ruleId) => !snapshot.has(ruleId))) return fail('MALFORMED_CANDIDATE');\n return Object.freeze(snapshot) as RuleRegistryV2;\n } catch (error) {\n if (error instanceof CandidateLimitExceededV2) throw error;\n if (typeof error === 'string') throw error;\n return fail('UNSAFE_INPUT');\n }\n}\nfunction ruleEntry(registry: RuleRegistryV2, ruleId: string): AdmittedRuleV2 { const rule = Map.prototype.get.call(registry, ruleId); if (rule === undefined) return fail('UNKNOWN_RULE'); return rule; }\nfunction stringListContains(value: unknown, expected: string): boolean { if (!Array.isArray(value)) return false; for (const item of value) if (typeof item !== 'string') return false; return value.includes(expected); }\nfunction projection(capability: { id: string; dependsOn: readonly string[] }, schema: SafeFactSchemaV2, fact: SafeFactV2): boolean { if (schema.ownerCapabilityId === capability.id) return true; const depends = (id: string): boolean => capability.dependsOn.includes(id); if (capability.id === 'javascript-security') return depends('source-normalization') && schema.kind === 'code.indicator.v2' && schema.ownerCapabilityId === 'expression-security' && fact.properties.language === 'JAVASCRIPT'; if (capability.id === 'python-security') return depends('source-normalization') && schema.kind === 'code.indicator.v2' && schema.ownerCapabilityId === 'expression-security' && fact.properties.language === 'PYTHON'; if (capability.id === 'taint-integrity' || capability.id === 'taint-confidentiality') return depends('graph-semantics') && schema.kind === 'dataflow.summary.v2' && schema.ownerCapabilityId === 'graph-semantics' && fact.properties.flowKind === 'TAINT_SINK'; if (capability.id === 'agentic-control') return depends('graph-semantics') && ((schema.kind === 'node.capability.v2' && schema.ownerCapabilityId === 'structural-policies' && stringListContains(fact.properties.capabilities, 'AI_AGENT')) || (schema.kind === 'dataflow.summary.v2' && schema.ownerCapabilityId === 'graph-semantics' && fact.properties.flowKind === 'AGENT_INFLUENCE' && fact.properties.humanGatePresent === false && fact.properties.humanGateDominates === false)); return false; }\nfunction factLimit(kind: string, limits: ScannerLimitsV2): number { if (kind.startsWith('workflow.')) return 1; if (kind === 'advisory.applicability.v2') return 0; if (kind === 'integration.v1' || kind === 'node.capability.v2' || kind === 'ingress.v2') return limits.maxNodes; if (kind === 'node.configuration.v2') return Math.min(limits.maxMembersAndElements, limits.maxFindings); if (kind === 'destination.v2') return limits.maxMembersAndElements; return limits.maxFindings; }\nfunction refs(input: unknown, maximum: number): string[] { const values = readBoundedArray(input, maximum).map(id); const unique = new Set(values); if (unique.size !== values.length) fail('DUPLICATE_ID'); return values.sort(compare); }\nfunction candidateSubject(input: unknown, limits: ScannerLimitsV2): SubjectV2 { const value = readPlainRecord(input, ['kind', 'node', 'edge', 'source'], [], true); if (value.kind !== 'EDGE') return readSubject(input, limits); if (has(value, 'node') || has(value, 'source')) fail('UNKNOWN_PROPERTY'); const raw = readPlainRecord(value.edge, ['ordinal', 'sourceNode', 'targetNode', 'sourceLabel', 'targetLabel', 'connectionType', 'sourcePort', 'targetPort', 'source', 'resolution'], ['ordinal', 'sourceLabel', 'connectionType', 'sourcePort', 'targetPort', 'source', 'resolution'], true); const ordinal = integer(raw.ordinal); if (ordinal >= limits.maxEdges) limitExceeded(ordinal + 1, limits.maxEdges); const node = (nodeInput: unknown): EdgeRefV2['sourceNode'] => { const subject = readSubject({ kind: 'NODE', node: nodeInput }, limits); if (subject.kind !== 'NODE') return fail('INVALID_SUBJECT'); return subject.node; }; const edge: EdgeRefV2 = { ordinal, sourceLabel: text(raw.sourceLabel), connectionType: text(raw.connectionType), sourcePort: integer(raw.sourcePort), targetPort: integer(raw.targetPort), source: readSourceMemberRef(raw.source, limits), resolution: enumValue(raw.resolution, ['RESOLVED', 'AMBIGUOUS', 'UNRESOLVED']) }; if (has(raw, 'sourceNode')) edge.sourceNode = node(raw.sourceNode); if (has(raw, 'targetNode')) edge.targetNode = node(raw.targetNode); if (has(raw, 'targetLabel')) edge.targetLabel = text(raw.targetLabel); return { kind: 'EDGE', edge }; }\nfunction subjectKey(subject: SubjectV2): string { if (subject.kind === 'WORKFLOW') return 'WORKFLOW'; if (subject.kind === 'SOURCE') return `SOURCE${subject.source.astNodeId}`; if (subject.kind === 'NODE') return `NODE${subject.node.identityDigest}`; return `EDGE${createEdgeIdentityDigest(subject.edge)}`; } function schemaFor(schemas: readonly SafeFactSchemaV2[], kind: string): SafeFactSchemaV2 { const schema = schemas.find((item) => item.kind === kind); if (schema === undefined) return fail('MALFORMED_CANDIDATE'); return schema; }\nfunction typedFact(raw: unknown, schema: SafeFactSchemaV2, limits: ScannerLimitsV2): SafeFactV2 { const value = ownRecord(raw, ['factId', 'kind', 'subject', 'properties'], 'MALFORMED_CANDIDATE'); const source = readPlainRecord(value.properties, Object.keys(schema.properties), [], true); const properties: Record<string, SafeFactValueV2> = {}; for (const key of Object.keys(source)) { const item = source[key]; if (item === null || typeof item === 'string' || typeof item === 'number' || typeof item === 'boolean') properties[key] = item; else if (Array.isArray(item)) properties[key] = Object.freeze(readBoundedArray(item, limits.maxMembersAndElements).map((scalar) => { if (scalar === null || typeof scalar === 'string' || typeof scalar === 'number' || typeof scalar === 'boolean') return scalar; return fail('UNSAFE_INPUT'); })); else fail('UNSAFE_INPUT'); } return { factId: text(value.factId), kind: text(value.kind), subject: readSubject(value.subject, limits), properties: Object.freeze(properties) }; }\n/**\n * A refusal the shared safe-fact validator produced reports the bare reason: its result type\n * carries no numbers, and the bound it refused against is the schema-property bound\n * `facts/safe-fact-validator.ts` applies (two key-specific cases included). Re-deriving that rule\n * here would create a second source of truth that can disagree with the first, so the crossing is\n * left unpublished; the scheduler still classifies the refusal as a LIMIT failure, only without an\n * `observed`/`maximum` pair. Every crossing this module measures itself publishes both numbers.\n */\nfunction admittedFact(result: SafeFactValidationResultV2): SafeFactV2 { if (result.ok) return result.fact; if (result.reason === 'LIMIT_EXCEEDED') return fail('LIMIT_EXCEEDED'); if (result.reason === 'FORBIDDEN_CONTENT') return fail('FORBIDDEN_CONTENT'); if (result.reason === 'UNSAFE_INPUT') return fail('UNSAFE_INPUT'); if (result.reason === 'UNKNOWN_PROPERTY') return fail('UNKNOWN_KEY'); return fail('MALFORMED_CANDIDATE'); }\nfunction readFacts(input: unknown, schemas: readonly SafeFactSchemaV2[], limits: ScannerLimitsV2, budget: EvidenceBudgetV2): { facts: SafeFactV2[]; ids: Set<string>; recovered: Set<string> } { const facts: SafeFactV2[] = []; const ids = new Set<string>(); const counts = new Map<string, number>(); const services = new Set<string>(); const sourceCounts = new Map<string, number>(); const length = readBoundedLength(input, limits.maxMembersAndElements); for (let index = 0; index < length; index += 1) { const raw = readArrayItem(input, index); const header = ownRecord(raw, ['factId', 'kind', 'subject', 'properties'], 'UNKNOWN_KEY'); const kind = text(header.kind); const schema = schemaFor(schemas, kind); const maximum = factLimit(kind, limits); if (maximum === 0) limitExceeded(1, 0); const admittedInput = createSafeFactAdmissionSnapshotV2(typedFact(raw, schema, limits)); const fact = admittedFact(validateSafeFact(admittedInput, schema, limits)); validateSubjectContent(fact.subject); if (ids.has(fact.factId)) fail('DUPLICATE_ID'); const count = (counts.get(kind) ?? 0) + 1; if (count > maximum) limitExceeded(count, maximum); let serviceKey: string | undefined; if (kind === 'integration.v1') { const service = fact.properties.service; serviceKey = typeof service === 'string' ? service : fail('DUPLICATE_ID'); if (services.has(serviceKey)) fail('DUPLICATE_ID'); } let sourceId: string | undefined; let sourceCount: number | undefined; if (kind === 'code.indicator.v2' && fact.subject.kind === 'SOURCE') { sourceId = fact.subject.source.astNodeId; sourceCount = (sourceCounts.get(sourceId) ?? 0) + 1; if (sourceCount > 10) limitExceeded(sourceCount, 10); } chargeEvidence(budget, 2, fact); if (sourceId !== undefined && sourceCount !== undefined) sourceCounts.set(sourceId, sourceCount); ids.add(fact.factId); counts.set(kind, count); if (serviceKey !== undefined) services.add(serviceKey); facts.push(fact); } const recovered = new Set<string>(); for (let index = 0; index < facts.length; index += 1) if (facts[index].kind === 'code.indicator.v2' && facts[index].properties.parseState === 'RECOVERED') recovered.add(facts[index].factId); return { facts, ids, recovered }; }\nfunction traceId(kind: string, steps: readonly unknown[]): string { return digest(['secureflow-trace-id-v2', kind, canonicalizeJson(steps)]); }\nfunction readTraces(input: unknown, limits: ScannerLimitsV2, budget: EvidenceBudgetV2): { traces: TraceV2[]; ids: Set<string> } { const traces: TraceV2[] = []; const ids = new Set<string>(); const length = readBoundedLength(input, limits.maxMembersAndElements); for (let index = 0; index < length; index += 1) { const raw = readArrayItem(input, index); const value = ownRecord(raw, ['traceId', 'kind', 'steps'], 'MALFORMED_CANDIDATE'); const kind = enumValue(value.kind, enums.trace); const rawSteps = readBoundedArray(value.steps, Math.min(limits.maxTraceStepsPerFinding, limits.maxMembersAndElements)); const steps = rawSteps.map((rawStep, ordinal) => { const step = ownRecord(rawStep, ['ordinal', 'kind', 'subject', 'factRefs'], 'MALFORMED_CANDIDATE'); if (step.ordinal !== ordinal) fail('MALFORMED_CANDIDATE'); const stepKind = enumValue(step.kind, enums.step); const subject = candidateSubject(step.subject, limits); validateSubjectContent(subject); return { ordinal, kind: stepKind, subject, factRefs: Object.freeze(refs(step.factRefs, limits.maxMembersAndElements)) }; }); const valueId = id(value.traceId); if (valueId !== traceId(kind, steps)) fail('MALFORMED_CANDIDATE'); if (ids.has(valueId)) fail('DUPLICATE_ID'); const trace = { traceId: valueId, kind, steps: Object.freeze(steps) }; chargeEvidence(budget, 3, trace); ids.add(valueId); traces.push(trace); } return { traces: traces.sort((a, b) => compare(a.traceId, b.traceId)), ids }; }\nfunction mappingFor(ruleId: string): SafeFactEvidenceMappingV2 { const mapping = SAFE_FACT_EVIDENCE_MAPPINGS_V2.find((item) => item.ruleId === ruleId); if (mapping !== undefined) return mapping; return fail('UNKNOWN_RULE'); }\nfunction optionalEvidenceProperty(mapping: SafeFactEvidenceMappingV2, factKind: string, property: string): boolean { return mapping.evidenceSchemaId === 'v1.taint' && factKind === 'dataflow.summary.v2' && ['propertyPath', 'sourceNodeId', 'sourceNodeName'].includes(property); }\nfunction evidenceFact(facts: Map<string, SafeFactV2>, mapping: SafeFactEvidenceMappingV2, ref: string): SafeFactV2 { const fact = facts.get(ref); if (fact === undefined || !mapping.factKinds.includes(fact.kind)) return fail('DANGLING_REFERENCE'); return fact; }\nfunction validateEvidence(finding: FindingCandidateV2, rule: AdmittedRuleV2, mapping: SafeFactEvidenceMappingV2, facts: Map<string, SafeFactV2>, recovered: ReadonlySet<string>): void { const referenced = finding.factRefs.map((ref) => evidenceFact(facts, mapping, ref)); if (rule.capabilityId !== mapping.ownerCapabilityId || rule.evidenceSchemaId !== mapping.evidenceSchemaId || rule.remediationId !== finding.remediationId || finding.evidenceClass !== mapping.evidenceClass) fail('UNOWNED_RULE'); const seenKinds = new Set<string>(); for (const fact of referenced) { const properties = mapping.factPropertiesByKind[fact.kind] ?? []; for (const property of properties) if (!(fact.kind === 'code.indicator.v2' && property === 'member') && !optionalEvidenceProperty(mapping, fact.kind, property) && !has(fact.properties, property)) fail('DANGLING_REFERENCE'); seenKinds.add(fact.kind); if (finding.ruleId === 'RAW_AUTH_HEADER' && fact.properties.observation !== 'AUTH_HEADER') fail('DANGLING_REFERENCE'); if (finding.ruleId === 'RAW_SECRET_INDICATOR' && fact.properties.observation !== 'SECRET_INDICATOR') fail('DANGLING_REFERENCE'); if ((finding.ruleId === 'JAVASCRIPT_DYNAMIC_EXECUTION' && fact.properties.language !== 'JAVASCRIPT') || (finding.ruleId === 'PYTHON_DYNAMIC_EXECUTION' && fact.properties.language !== 'PYTHON')) fail('DANGLING_REFERENCE'); if (finding.ruleId.startsWith('TAINTED_')) { const sink = finding.ruleId === 'TAINTED_SQL_QUERY' ? 'SQL' : finding.ruleId.slice(8).replace('REQUEST_URL', 'SSRF').replace('FILE_PATH', 'PATH').replace('CODE_INPUT', 'CODE').replace('REQUEST_HEADER', 'HEADER').replace('AI_PROMPT', 'PROMPT'); if (fact.properties.flowKind !== 'TAINT_SINK' || fact.properties.sink !== sink) fail('DANGLING_REFERENCE'); } if (finding.ruleId === 'AI_AGENT_UNGATED_TOOL' && ((fact.kind === 'dataflow.summary.v2' && (fact.properties.flowKind !== 'AGENT_INFLUENCE' || fact.properties.humanGatePresent !== false || fact.properties.humanGateDominates !== false)) || (fact.kind === 'node.capability.v2' && (!stringListContains(fact.properties.capabilities, 'AI_AGENT') || fact.properties.toolCount === 0)))) fail('DANGLING_REFERENCE'); if (finding.ruleId === 'UNAPPROVED_DOMAIN' && (fact.properties.authorityState !== 'KNOWN' || fact.properties.hostname === null)) fail('DANGLING_REFERENCE'); if (fact.kind === 'code.indicator.v2' && recovered.has(fact.factId) && (rule.effect !== 'REPORT_ONLY' || finding.conclusion !== 'POTENTIAL')) fail('FORBIDDEN_CONTENT'); } for (const kind of mapping.factKinds) if (!seenKinds.has(kind)) fail('DANGLING_REFERENCE'); }\nfunction findingId(finding: FindingCandidateV2, rule: AdmittedRuleV2): string { return digest(['secureflow-finding-id-v2', finding.ruleId, rule.revision, finding.evidenceClass, finding.conclusion, finding.applicability, subjectKey(finding.subject), ...[...finding.factRefs].sort(compare), ...[...finding.traceRefs].sort(compare)]); }\nfunction readFindings(input: unknown, capability: { id: string; ruleIds: ReadonlySet<string> }, rules: RuleRegistryV2, facts: Map<string, SafeFactV2>, recovered: ReadonlySet<string>, limits: ScannerLimitsV2, budget: EvidenceBudgetV2): FindingCandidateV2[] { const output: Array<{ item: FindingCandidateV2; id: string; severity: number }> = []; const ids = new Set<string>(); const ranks: Readonly<Record<AdmittedRuleV2['severity'], number>> = { CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3, INFO: 4 }; const length = readBoundedLength(input, limits.maxFindings); for (let index = 0; index < length; index += 1) { const raw = readArrayItem(input, index); const value = ownRecord(raw, ['ruleId', 'evidenceClass', 'conclusion', 'applicability', 'subject', 'factRefs', 'traceRefs', 'remediationId'], 'MALFORMED_CANDIDATE'); const ruleId = text(value.ruleId); const rule = ruleEntry(rules, ruleId); if (!capability.ruleIds.has(ruleId)) fail('UNOWNED_RULE'); if (rule.capabilityId !== capability.id) fail('UNOWNED_RULE'); const mapping = mappingFor(ruleId); const subject = candidateSubject(value.subject, limits); validateSubjectContent(subject); const item: FindingCandidateV2 = { ruleId, evidenceClass: enumValue(value.evidenceClass, enums.evidenceClass), conclusion: enumValue(value.conclusion, enums.conclusion), applicability: enumValue(value.applicability, enums.applicability), subject, factRefs: Object.freeze(refs(value.factRefs, limits.maxMembersAndElements)), traceRefs: Object.freeze(refs(value.traceRefs, limits.maxMembersAndElements)), remediationId: text(value.remediationId) }; validateEvidence(item, rule, mapping, facts, recovered); const itemId = findingId(item, rule); if (ids.has(itemId)) fail('DUPLICATE_ID'); chargeEvidence(budget, 0, item); ids.add(itemId); output.push({ item, id: itemId, severity: ranks[rule.severity] }); } return output.sort((a, b) => a.severity - b.severity || compare(a.item.ruleId, b.item.ruleId) || compare(subjectKey(a.item.subject), subjectKey(b.item.subject)) || compare(a.id, b.id)).map(({ item }) => item); }\nfunction compareDiagnosticLocations(left: AnalysisDiagnosticV2['location'], right: AnalysisDiagnosticV2['location']): number {\n if (left === undefined) return right === undefined ? 0 : 1;\n if (right === undefined) return -1;\n const pointerOrder = compare(left.pointer, right.pointer);\n if (pointerOrder !== 0) return pointerOrder;\n for (let index = 0; index < Math.min(left.occurrencePath.length, right.occurrencePath.length); index += 1) {\n if (left.occurrencePath[index] !== right.occurrencePath[index]) return left.occurrencePath[index] - right.occurrencePath[index];\n }\n return left.occurrencePath.length - right.occurrencePath.length;\n}\nfunction compareDiagnostics(left: AnalysisDiagnosticV2, right: AnalysisDiagnosticV2): number {\n const capabilityOrder = compare(left.capabilityId, right.capabilityId);\n if (capabilityOrder !== 0) return capabilityOrder;\n const codeOrder = DIAGNOSTIC_CODES_V2.indexOf(left.code) - DIAGNOSTIC_CODES_V2.indexOf(right.code);\n if (codeOrder !== 0) return codeOrder;\n const locationOrder = compareDiagnosticLocations(left.location, right.location);\n return locationOrder !== 0 ? locationOrder : compare(left.id, right.id);\n}\nfunction readDiagnostics(input: readonly unknown[], capabilityId: string, required: boolean, limits: ScannerLimitsV2, diagnosticsBudget: EvidenceBudgetV2): AnalysisDiagnosticV2[] {\n const output: AnalysisDiagnosticV2[] = []; const ids = new Set<string>();\n const length = readBoundedLength(input, limits.maxDiagnostics);\n for (let index = 0; index < length; index += 1) {\n const raw = readArrayItem(input, index);\n const value = ownRecord(raw, ['id', 'code', 'category', 'capabilityId', 'aggregateEffect', 'assessmentEligible', 'location', 'observed', 'maximum', 'omitted'], 'MALFORMED_CANDIDATE', ['id', 'code', 'category', 'capabilityId', 'aggregateEffect', 'assessmentEligible']);\n const code = enumValue(value.code, DIAGNOSTIC_CODES_V2); const classification = classifyDiagnostic(code, required);\n if ((code === 'REQUIRED_LIMIT_EXCEEDED' || code === 'OPTIONAL_LIMIT_EXCEEDED') && !(['observed', 'maximum', 'omitted'] as const).every((key) => has(value, key))) fail('MALFORMED_CANDIDATE');\n if (text(value.capabilityId) !== capabilityId || value.category !== classification.category || value.aggregateEffect !== classification.aggregateEffect || value.assessmentEligible !== classification.assessmentEligible) fail('MALFORMED_CANDIDATE');\n const location = has(value, 'location') ? readSourceMemberRef(value.location, limits) : undefined; const counts: MutableDiagnosticCountersV2 = {};\n for (const key of ['observed', 'maximum', 'omitted'] as const) if (has(value, key)) counts[key] = integer(value[key]);\n const identity = { code, capabilityId, aggregateEffect: classification.aggregateEffect, category: classification.category, assessmentEligible: classification.assessmentEligible, ...(location ? { location } : {}), ...counts };\n const diagnosticId = id(value.id); if (diagnosticId !== createDiagnosticId(identity)) fail('MALFORMED_CANDIDATE'); if (ids.has(diagnosticId)) fail('DUPLICATE_ID');\n const diagnostic = Object.freeze({ id: diagnosticId, ...identity }); chargeEvidence(diagnosticsBudget, 1, diagnostic); output.push(diagnostic);\n }\n return output.sort(compareDiagnostics);\n}\nconst utf8Bytes = (value: string): number => new TextEncoder().encode(value).length;\nconst isSafeFactScalar = (value: unknown): value is SafeFactScalarV2 => value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';\nconst scalarJson = (value: SafeFactScalarV2): string => canonicalizeJson(value);\nconst safeValueJson = (value: SafeFactValueV2): string => { if (isSafeFactScalar(value)) return scalarJson(value); const arrayValue: readonly SafeFactScalarV2[] = value; return `[${arrayValue.map((item) => scalarJson(item)).join(',')}]`; };\nfunction canonicalBytes(value: SafeFactValueV2 | Readonly<Record<string, unknown>>): number {\n if (isSafeFactScalar(value)) return utf8Bytes(scalarJson(value));\n if (Array.isArray(value)) return utf8Bytes(safeValueJson(value as readonly SafeFactScalarV2[]));\n return utf8Bytes(canonicalizeJson(value));\n}\nconst limitNumber = (input: object, key: string, minimum = 0): number => { const descriptor = Object.getOwnPropertyDescriptor(input, key); if (!descriptor || !('value' in descriptor) || typeof descriptor.value !== 'number' || !Number.isSafeInteger(descriptor.value) || descriptor.value < minimum) fail('UNSAFE_INPUT'); return descriptor.value; };\nfunction snapshotLimits(input: unknown): ScannerLimitsV2 { if (typeof input !== 'object' || input === null || Array.isArray(input) || Object.getPrototypeOf(input) !== Object.prototype) fail('UNSAFE_INPUT'); const schema = Object.getOwnPropertyDescriptor(input, 'schemaVersion'); if (!schema || !('value' in schema) || schema.value !== 'scanner-limits-v2') fail('UNSAFE_INPUT'); const maxBytes = limitNumber(input, 'maxBytes'); const maxNodes = limitNumber(input, 'maxNodes'); const maxEdges = limitNumber(input, 'maxEdges'); const maxConnectionDepth = limitNumber(input, 'maxConnectionDepth'); const maxParameterDepth = limitNumber(input, 'maxParameterDepth'); const maxParameterLeaves = limitNumber(input, 'maxParameterLeaves'); const workerDeadlineMs = limitNumber(input, 'workerDeadlineMs'); const maxSyntaxNodes = limitNumber(input, 'maxSyntaxNodes'); const maxDocumentDepth = limitNumber(input, 'maxDocumentDepth'); const maxMembersAndElements = limitNumber(input, 'maxMembersAndElements'); const maxRawEdges = limitNumber(input, 'maxRawEdges'); const maxDuplicateKeys = limitNumber(input, 'maxDuplicateKeys'); const maxDiagnostics = limitNumber(input, 'maxDiagnostics', 1); const maxStoredSourceSpans = limitNumber(input, 'maxStoredSourceSpans'); const maxSourceWork = limitNumber(input, 'maxSourceWork'); const maxExpressionTokens = limitNumber(input, 'maxExpressionTokens'); const maxCodeSyntaxNodes = limitNumber(input, 'maxCodeSyntaxNodes'); const maxGraphOperations = limitNumber(input, 'maxGraphOperations'); const maxTaintStates = limitNumber(input, 'maxTaintStates'); const maxTraceStepsPerFinding = limitNumber(input, 'maxTraceStepsPerFinding'); const maxFindings = limitNumber(input, 'maxFindings'); const maxRedactionPatches = limitNumber(input, 'maxRedactionPatches'); const maxRedactedArtifactBytes = limitNumber(input, 'maxRedactedArtifactBytes'); const maxEvidenceBytes = limitNumber(input, 'maxEvidenceBytes'); const maxSerializedResultBytes = limitNumber(input, 'maxSerializedResultBytes'); const maxRuleOperations = limitNumber(input, 'maxRuleOperations'); return Object.freeze({ schemaVersion: 'scanner-limits-v2', maxBytes, maxNodes, maxEdges, maxConnectionDepth, maxParameterDepth, maxParameterLeaves, workerDeadlineMs, maxSyntaxNodes, maxDocumentDepth, maxMembersAndElements, maxRawEdges, maxDuplicateKeys, maxDiagnostics, maxStoredSourceSpans, maxSourceWork, maxExpressionTokens, maxCodeSyntaxNodes, maxGraphOperations, maxTaintStates, maxTraceStepsPerFinding, maxFindings, maxRedactionPatches, maxRedactedArtifactBytes, maxEvidenceBytes, maxSerializedResultBytes, maxRuleOperations }); }\nfunction evidenceBudget(maximum: number): EvidenceBudgetV2 { const bytes = utf8Length(canonicalizeJson({ findings: [], diagnostics: [], facts: [], traces: [] })); if (bytes > maximum) limitExceeded(bytes, maximum); return { bytes, counts: [0, 0, 0, 0], maximum }; }\nfunction chargeEvidence(budget: EvidenceBudgetV2, section: 0 | 1 | 2 | 3, value: Readonly<Record<string, unknown>>): void { budget.bytes += canonicalBytes(value) + (budget.counts[section] === 0 ? 0 : 1); budget.counts[section] += 1; if (budget.bytes > budget.maximum) limitExceeded(budget.bytes, budget.maximum); }\ntype EvidenceCollectionV2 = Readonly<Pick<CapabilityCandidateV2, 'findings' | 'diagnostics' | 'facts' | 'traces'>>;\nfunction sharedEvidence(value: EvidenceCollectionV2): number { return canonicalBytes({ findings: value.findings, diagnostics: value.diagnostics, facts: value.facts, traces: value.traces }); }\nfunction utf8Length(value: string): number { let bytes = 0; for (let index = 0; index < value.length; index += 1) { const code = value.charCodeAt(index); if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length && value.charCodeAt(index + 1) >= 0xdc00 && value.charCodeAt(index + 1) <= 0xdfff) { bytes += 4; index += 1; } else bytes += code <= 0x7f ? 1 : code <= 0x7ff ? 2 : 3; } return bytes; }\nfunction jsonStringBytes(value: string): number { let bytes = 2; for (let index = 0; index < value.length; index += 1) { const code = value.charCodeAt(index); if (code === 0x22 || code === 0x5c || code === 8 || code === 9 || code === 10 || code === 12 || code === 13) bytes += 2; else if (code <= 0x1f) bytes += 6; else if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length && value.charCodeAt(index + 1) >= 0xdc00 && value.charCodeAt(index + 1) <= 0xdfff) { bytes += 4; index += 1; } else if (code >= 0xd800 && code <= 0xdfff) bytes += 6; else bytes += code <= 0x7f ? 1 : code <= 0x7ff ? 2 : 3; } return bytes; }\nfunction scalarLowerBound(value: unknown): number { if (typeof value === 'string') return jsonStringBytes(value); if (value === null) return 4; if (typeof value === 'boolean') return value ? 4 : 5; if (typeof value === 'number') return Number.isFinite(value) ? String(Object.is(value, -0) ? 0 : value).length : 1; return 0; }\nconst structureFields: Readonly<Record<string, readonly string[]>> = { subject: ['kind', 'node', 'edge', 'source'], node: ['ordinal', 'source', 'explicitId', 'name', 'identityDigest'], edge: ['ordinal', 'sourceNode', 'sourceLabel', 'targetNode', 'targetLabel', 'connectionType', 'sourcePort', 'targetPort', 'source', 'resolution'], source: ['pointer', 'occurrencePath', 'astNodeId', 'span'], location: ['pointer', 'occurrencePath', 'astNodeId', 'span'], span: ['start', 'end'], start: ['line', 'column', 'utf16Offset', 'utf8ByteOffset'], end: ['line', 'column', 'utf16Offset', 'utf8ByteOffset'], finding: ['ruleId', 'evidenceClass', 'conclusion', 'applicability', 'subject', 'factRefs', 'traceRefs', 'remediationId'], trace: ['traceId', 'kind', 'steps'], step: ['ordinal', 'kind', 'subject', 'factRefs'], diagnostic: ['id', 'code', 'category', 'capabilityId', 'aggregateEffect', 'assessmentEligible', 'location', 'observed', 'maximum', 'omitted'] };\nconst fieldShape = (key: string): readonly string[] => structureFields[key] ?? [];\nconst fit = (value: number, maximum: number): number => value > maximum ? limitExceeded(value, maximum) : value;\nconst PREFLIGHT_MAX_DEPTH = 512; const PREFLIGHT_MAX_WORK = 1_000_000; type PreflightFrame = { value: object; fields: readonly string[]; itemFields: readonly string[]; propertyFields: readonly string[]; index: number; length: number; present: number; array: boolean; depth: number };\nfunction boundedValue(value: unknown, maximum: number, fields: readonly string[] = [], itemFields: readonly string[] = [], propertyFields: readonly string[] = [], cap = Number.MAX_SAFE_INTEGER): number {\n let total = 0; let work = 0; const active = new Set<object>(); const stack: Array<PreflightFrame | { leave: object }> = [];\n const add = (amount: number): void => { if (!Number.isSafeInteger(amount) || amount < 0) fail('LIMIT_EXCEEDED'); if (total > cap - amount) limitExceeded(total + amount, cap); total += amount; };\n const push = (next: unknown, nextFields: readonly string[], nextItems: readonly string[], nextProperties: readonly string[], depth: number): void => {\n const workCap = Math.min(PREFLIGHT_MAX_WORK, Math.max(1_024, maximum * 64));\n if (++work > workCap) limitExceeded(work, workCap); if (depth > PREFLIGHT_MAX_DEPTH) fail('UNSAFE_INPUT');\n if (isSafeFactScalar(next)) { add(scalarLowerBound(next)); return; }\n if (next === null || typeof next !== 'object') return; if (active.has(next)) fail('UNSAFE_INPUT'); active.add(next); add(2);\n if (Array.isArray(next)) { const length = readBoundedLength(next, maximum, false); stack.push({ leave: next }); stack.push({ value: next, fields: [], itemFields: nextItems, propertyFields: [], index: 0, length, present: 0, array: true, depth }); }\n else { stack.push({ leave: next }); stack.push({ value: next, fields: nextFields, itemFields: [], propertyFields: nextProperties, index: 0, length: nextFields.length, present: 0, array: false, depth }); }\n };\n push(value, fields, itemFields, propertyFields, 0);\n while (stack.length) {\n const frame = stack[stack.length - 1]; if ('leave' in frame) { stack.pop(); active.delete(frame.leave); continue; }\n if (frame.index >= frame.length) { stack.pop(); continue; }\n const index = frame.index++; if (frame.array) { add(index ? 1 : 0); push(readArrayItem(frame.value, index), frame.itemFields, [], [], frame.depth + 1); continue; }\n const key = frame.fields[index]; const descriptor = Object.getOwnPropertyDescriptor(frame.value, key); if (descriptor === undefined) continue; if (!('value' in descriptor)) fail('UNSAFE_INPUT'); add((frame.present ? 1 : 0) + jsonStringBytes(key) + 1); frame.present += 1; push(descriptor.value, key === 'properties' ? frame.propertyFields : fieldShape(key), key === 'steps' ? fieldShape('step') : [], [], frame.depth + 1);\n }\n return total; }\nfunction boundedItem(value: unknown, section: string, maximum: number, cap = Number.MAX_SAFE_INTEGER): number { if (section === 'facts') { const kind = Object.getOwnPropertyDescriptor(value as object, 'kind'); const schema = kind && 'value' in kind && typeof kind.value === 'string' ? SAFE_FACT_REGISTRY_V2.schemas.find((item) => item.kind === kind.value) : undefined; return boundedValue(value, maximum, ['factId', 'kind', 'subject', 'properties'], [], schema ? Object.keys(schema.properties) : [], cap); } return boundedValue(value, maximum, fieldShape(section === 'findings' ? 'finding' : section === 'traces' ? 'trace' : 'diagnostic'), [], [], cap); }\nfunction preflightSection(input: unknown, section: string, maximum: number, cap: number): number { const length = readBoundedLength(input, maximum, false); let total = 0; for (let index = 0; index < length; index += 1) { const separator = index ? 1 : 0; total = fit(total + separator, cap); total += boundedItem(readArrayItem(input, index), section, maximum, cap - total); total = fit(total, cap); } return total; }\nfunction preflightCandidate(input: unknown, limits: ScannerLimitsV2, budget: EvidenceBudgetV2): void { if (input === null || typeof input !== 'object' || Array.isArray(input)) return fail('UNSAFE_INPUT'); let minimum = 0; for (const section of ['findings', 'diagnostics', 'facts', 'traces']) { const descriptor = Object.getOwnPropertyDescriptor(input, section); if (descriptor === undefined || !('value' in descriptor)) return fail('UNSAFE_INPUT'); const maximum = section === 'findings' ? limits.maxFindings : section === 'diagnostics' ? limits.maxDiagnostics : limits.maxMembersAndElements; minimum += preflightSection(descriptor.value, section, maximum, budget.maximum - budget.bytes - minimum); if (budget.bytes + minimum > budget.maximum) limitExceeded(budget.bytes + minimum, budget.maximum); } }\nexport function validateCapabilityCandidate(candidate: unknown, capability: CapabilitySpecV2, registries: CandidateRegistriesV2, limits: ScannerLimitsV2, eligibleUnits: number): CapabilityCandidateValidationResultV2 { let safeCounters: MutableCandidateCountersV2 = { seen: 0, analyzed: 0, skipped: 0, omitted: 0 }; if (!isScannerAdmissionSnapshotV2<CapabilityCandidateV2>(candidate)) return rejected('UNSAFE_INPUT', safeCounters); try { const safeLimits = snapshotLimits(limits); const budget = evidenceBudget(safeLimits.maxEvidenceBytes); const value = candidateRecord(candidate); safeCounters = counters(value); if (countInconsistency(safeCounters, eligibleUnits) !== null) fail('INVALID_COUNTER'); preflightCandidate(value, safeLimits, budget); const capabilityViewValue = capabilityView(capability, safeLimits); const registryValue = ownRecord(registries, ['facts', 'rules'], 'MALFORMED_CANDIDATE'); const schemas = snapshotRegistry(registryValue.facts); const admittedFacts = readFacts(value.facts, schemas, safeLimits, budget); const rules = ruleRegistry(registryValue.rules, safeLimits, capabilityViewValue.ruleIds); const factMap = new Map(admittedFacts.facts.map((fact) => [fact.factId, fact])); const admittedTraces = readTraces(value.traces, safeLimits, budget); const findings = readFindings(value.findings, capabilityViewValue, rules, factMap, admittedFacts.recovered, safeLimits, budget); for (let index = 0; index < findings.length; index += 1) { const finding = findings[index]; for (const ref of finding.traceRefs) if (!admittedTraces.ids.has(ref)) fail('DANGLING_REFERENCE'); for (const ref of finding.factRefs) if (!admittedFacts.ids.has(ref)) fail('DANGLING_REFERENCE'); } for (let index = 0; index < admittedTraces.traces.length; index += 1) for (const step of admittedTraces.traces[index].steps) for (const ref of step.factRefs) if (!admittedFacts.ids.has(ref)) fail('DANGLING_REFERENCE'); for (let index = 0; index < admittedFacts.facts.length; index += 1) { const fact = admittedFacts.facts[index]; const schema = schemaFor(schemas, fact.kind); if (!projection(capabilityViewValue, schema, fact)) fail('MALFORMED_CANDIDATE'); } const diagnostics = readDiagnostics(readBoundedArray(value.diagnostics, safeLimits.maxDiagnostics), capabilityViewValue.id, capabilityViewValue.required, safeLimits, budget); if (omissionInconsistency(safeCounters, diagnostics) !== null) fail('INVALID_COUNTER'); const ordered = { findings, diagnostics, facts: [...admittedFacts.facts].sort((a, b) => compare(a.factId, b.factId)), traces: admittedTraces.traces }; if (sharedEvidence(ordered) !== budget.bytes) fail('UNSAFE_INPUT'); const normalized: CapabilityCandidateV2 = { findings: Object.freeze(ordered.findings), diagnostics: Object.freeze(ordered.diagnostics), facts: Object.freeze(ordered.facts), traces: Object.freeze(ordered.traces), ...safeCounters }; return freezeData({ ok: true as const, candidate: freezeData(normalized) }); } catch (error) { if (error instanceof CandidateLimitExceededV2) return rejected('LIMIT_EXCEEDED', safeCounters, { observed: error.observed, maximum: error.maximum }); const reason = typeof error === 'string' && isReason(error) ? error : 'UNSAFE_INPUT'; return rejected(reason, safeCounters); } }\n", "/**\n * The immutable view the scheduler hands each capability: the per-field copy budgets derived from\n * the documented limits, and the bounded copy walk that enforces them. Extracted from\n * `scheduler.ts` (2026-10-17 file-size remediation) with no behaviour change: every function,\n * bound, comment and refusal path below is the reviewed D-1 implementation, moved verbatim.\n */\nimport { DEFAULT_SCANNER_LIMITS_V2, type ScannerLimitsV2 } from '@hub/contracts';\nimport { isParsedSourceDocument } from '../source/source-document-provenance';\nimport { MAX_SOURCE_PARSER_DEPTH } from '../source/source-preflight';\nimport type { AnalyzerContextV2 } from './scheduler';\n/**\n * The bounds on the immutable view the scheduler hands each capability. They are a guard against a\n * runaway walk, never an admission limit: everything they bound is already bounded by the\n * documented limits the parser and normalizer enforce, so exporting a constant here would refuse a\n * workflow the documentation says is admissible. D-1 (2026-10-17): the constant was\n * `{ depth: 64, objects: 8192, items: 4096 }`, and it refused every workflow of roughly 2,500\n * source members as `REQUIRED_CAPABILITY_FAILED` while every limit row reported `exhausted: false`\n * \u2014 a ceiling two orders of magnitude below the documented `maxMembersAndElements = 250000`, and\n * one no operator could see or raise.\n *\n * The floor keeps the original tightness for the context fields whose admissible size is a constant\n * (`limits`, `rules`, `priorOutcomes`, the parser-owned `source`), where an oversized graph is\n * always hostile rather than admissible. `target` is not one of those: the target admission admits\n * far more than the floor, so it carries its own budget below (D-1 review, finding 3).\n */\nconst CONTEXT_SNAPSHOT_FLOOR_V2: SnapshotBudgetV2 = Object.freeze({ objects: 8_192, items: 4_096, depth: 64 });\n/**\n * What the target admission admits, which the floor must not undercut: `semantics/target-context.ts`\n * bounds `communityPackages` and `configuration` at `MAX_COLLECTION_ITEMS = 100_000` items each, so\n * a target that passes `validateTargetContextV2` can sit far above the floor and is not a hostile\n * graph. Both constants must stay in step with that file.\n */\nconst CONTEXT_TARGET_COLLECTION_ITEMS_V2 = 100_000;\nconst CONTEXT_TARGET_UNITS_V2 = 2 * CONTEXT_TARGET_COLLECTION_ITEMS_V2;\n/**\n * The copy cost of one admissible unit, measured on the D-1 fixtures. The normalized workflow\n * mirrors every source member at least twice \u2014 once in `workflowFields`, once under the owning\n * node's `parameters`/`credentials`/`settings` \u2014 and each mirror costs two copied objects (the\n * semantic field and its occurrence list), so one member costs about four objects before refs and\n * spans. The factor of two over that measurement is headroom for the retained spans (the span\n * object, its two positions and its occurrence path), the node and edge refs, identity and label\n * objects that share those members; the seven measured shapes ran 1.73\u20132.65 objects per unit\n * against this factor of 8 (D1-FIX-REVIEW.md).\n */\nconst CONTEXT_OBJECTS_PER_UNIT_V2 = 8;\nconst CONTEXT_DEPTH_PER_DOCUMENT_LEVEL_V2 = 2;\nconst CONTEXT_DEPTH_OVERHEAD_V2 = 16;\nconst CONTEXT_SEMANTIC_OBJECTS_PER_NODE_V2 = 64;\nconst LIMIT_KEYS = Object.getOwnPropertyNames(DEFAULT_SCANNER_LIMITS_V2);\n/** `Map.prototype.size` through its intrinsic getter: an instance cannot lie about its own size. */\nconst MAP_SIZE_V2 = Object.getOwnPropertyDescriptor(Map.prototype, 'size')!.get as (this: ReadonlyMap<unknown, unknown>) => number;\ntype SnapshotBudgetV2 = Readonly<{ objects: number; items: number; depth: number }>;\nexport type SnapshotBoundV2 = Readonly<{ observed: number; maximum: number; omitted: number }>;\ntype SnapshotState = { nodes: number; budget: SnapshotBudgetV2 };\n/**\n * The numbers one limit refusal publishes. `observed` is the real size of the collection that\n * crossed a per-container bound (`omitted` is the part that bound saw and refused); for the two\n * cumulative budgets \u2014 which stop the walk at the first crossing and cannot say how far past it the\n * document goes \u2014 it is the bound that fired, because `maximum + 1` would dress a design stop as a\n * size measurement and tell an operator nothing about the document.\n */\nexport const snapshotBound = (observed: number, maximum: number): SnapshotBoundV2 => ({ observed, maximum, omitted: Math.max(0, observed - maximum) });\n/**\n * The wrapped failure of a context-view walk. It carries the numbers the diagnostic publishes, so a\n * refused view reports the size that fired and the bound it fired against instead of an opaque\n * capability failure (D-1).\n */\nexport class ContextSnapshotLimitV2 extends TypeError {\n readonly observed: number;\n readonly maximum: number;\n constructor(observed: number, maximum: number) {\n super('Context snapshot bound exceeded');\n this.observed = observed;\n this.maximum = maximum;\n }\n}\n/**\n * The per-field copy budgets of one context view, derived from the documented limits that bound the\n * field's content. `workflow` is the only field that carries the normalized document: its arrays are\n * bounded by `maxNodes`, `maxEdges`, `maxStoredSourceSpans` and `maxMembersAndElements`, its depth by\n * `maxDocumentDepth` (each document level costs two levels in the semantic mirror), and its object\n * count by the per-unit copy cost measured above. `semantics` carries one resolved catalogue entry\n * per node, and `target` carries what its own admission admits (at most two collections of\n * `CONTEXT_TARGET_COLLECTION_ITEMS_V2` items each); every other field is request metadata whose\n * admissible size is a constant.\n */\nfunction contextSnapshotBudgets(limits: ScannerLimitsV2): Readonly<Record<string, SnapshotBudgetV2>> {\n const units = limits.maxMembersAndElements + limits.maxStoredSourceSpans + limits.maxNodes + limits.maxEdges;\n return Object.freeze({\n target: Object.freeze({\n objects: CONTEXT_SNAPSHOT_FLOOR_V2.objects + CONTEXT_OBJECTS_PER_UNIT_V2 * CONTEXT_TARGET_UNITS_V2,\n items: Math.max(CONTEXT_SNAPSHOT_FLOOR_V2.items, CONTEXT_TARGET_COLLECTION_ITEMS_V2),\n depth: CONTEXT_SNAPSHOT_FLOOR_V2.depth,\n }),\n workflow: Object.freeze({\n objects: CONTEXT_SNAPSHOT_FLOOR_V2.objects + CONTEXT_OBJECTS_PER_UNIT_V2 * units,\n items: Math.max(CONTEXT_SNAPSHOT_FLOOR_V2.items, limits.maxMembersAndElements, limits.maxStoredSourceSpans, limits.maxNodes, limits.maxEdges, limits.maxParameterLeaves),\n depth: CONTEXT_SNAPSHOT_FLOOR_V2.depth + CONTEXT_DEPTH_OVERHEAD_V2 + CONTEXT_DEPTH_PER_DOCUMENT_LEVEL_V2 * Math.min(limits.maxDocumentDepth, MAX_SOURCE_PARSER_DEPTH),\n }),\n semantics: Object.freeze({\n objects: CONTEXT_SNAPSHOT_FLOOR_V2.objects + CONTEXT_SEMANTIC_OBJECTS_PER_NODE_V2 * limits.maxNodes,\n items: Math.max(CONTEXT_SNAPSHOT_FLOOR_V2.items, limits.maxNodes),\n depth: CONTEXT_SNAPSHOT_FLOOR_V2.depth,\n }),\n });\n}\n/**\n * The top-level record guard the walk applied to its own root before this view existed: a plain\n * prototype, no symbols, no more own names than the floor admits, and every own property a data\n * property. It cannot be left to the walk \u2014 `contextSnapshotBudgets(input.limits)` reads a property\n * and the spread copies the rest, so either would touch an accessor before any check \u2014 and it is not\n * the spread's job: `...` invokes accessors and silently drops symbol keys.\n */\nfunction assertContextRecord(input: unknown): void {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) throw new TypeError();\n const prototype = Object.getPrototypeOf(input);\n const names = ownNames(input, CONTEXT_SNAPSHOT_FLOOR_V2.items, 0);\n if (prototype !== Object.prototype && prototype !== null) throw new TypeError();\n for (const name of names) { const descriptor = Object.getOwnPropertyDescriptor(input, name); if (!descriptor || !('value' in descriptor)) throw new TypeError(); }\n}\nexport function contextView(input: AnalyzerContextV2): AnalyzerContextV2 {\n assertContextRecord(input);\n const budgets = contextSnapshotBudgets(input.limits);\n const seen = new Map<object, unknown>();\n const view = Object.create(null) as Record<string, unknown>;\n for (const [key, value] of Object.entries({ ...input })) {\n const budget = budgets[key] ?? CONTEXT_SNAPSHOT_FLOOR_V2;\n Object.defineProperty(view, key, {\n value: key === 'limits' ? snapshotLimits(value) : snapshot(value, seen, { nodes: 0, budget }, 0),\n enumerable: true, writable: true, configurable: true,\n });\n }\n return Object.freeze(view) as AnalyzerContextV2;\n}\n\nfunction snapshot(input: unknown, seen: Map<object, unknown>, state: SnapshotState, depth: number): unknown {\n if (typeof input === 'function') throw new TypeError(); if (input === null || typeof input !== 'object') return input;\n if (isParsedSourceDocument(input)) return input;\n const existing = seen.get(input);\n if (existing !== undefined) return existing;\n // The two cumulative budgets stop the walk at the first crossing and cannot know how far past it\n // the document goes, so they publish the bound that fired rather than `maximum + 1`.\n if (depth > state.budget.depth) throw new ContextSnapshotLimitV2(state.budget.depth, state.budget.depth);\n if (state.nodes >= state.budget.objects) throw new ContextSnapshotLimitV2(state.budget.objects, state.budget.objects);\n state.nodes += 1;\n if (input instanceof Map) return snapshotMap(input, seen, state, depth);\n if (Array.isArray(input)) return snapshotArray(input, seen, state, depth);\n return snapshotRecord(input, seen, state, depth);\n}\nfunction snapshotMap(input: ReadonlyMap<unknown, unknown>, seen: Map<object, unknown>, state: SnapshotState, depth: number): ReadonlyMap<unknown, unknown> {\n ownNames(input as object, 0, 1, [Symbol.iterator]);\n // The map's entry count is known before the walk, so the refusal publishes the real collection\n // size and the entries the bound refuses, not the first crossing.\n const size = MAP_SIZE_V2.call(input);\n if (size > state.budget.items) throw new ContextSnapshotLimitV2(size, state.budget.items);\n const target = new Map<unknown, unknown>(); const view = immutableMap(target);\n seen.set(input as object, view);\n Map.prototype.forEach.call(input, (value: unknown, key: unknown) => { target.set(snapshot(key, seen, state, depth + 1), snapshot(value, seen, state, depth + 1)); });\n return view;\n}\nfunction snapshotArray(input: readonly unknown[], seen: Map<object, unknown>, state: SnapshotState, depth: number): readonly unknown[] {\n const length = Object.getOwnPropertyDescriptor(input, 'length');\n if (!length || !('value' in length) || !Number.isSafeInteger(length.value) || length.value < 0) throw new TypeError();\n if (length.value > state.budget.items) throw new ContextSnapshotLimitV2(length.value, state.budget.items);\n const names = ownNames(input, length.value + 1, 0); if (names.length !== length.value + 1 || names.some((name) => name !== 'length' && (!/^(0|[1-9]\\d*)$/.test(name) || Number(name) >= length.value))) throw new TypeError();\n const output = new Array<unknown>(length.value); Object.setPrototypeOf(output, null); seen.set(input as object, output);\n for (let index = 0; index < length.value; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(input, String(index));\n if (!descriptor || !('value' in descriptor)) throw new TypeError();\n Object.defineProperty(output, String(index), { value: snapshot(descriptor.value, seen, state, depth + 1), enumerable: descriptor.enumerable, writable: true, configurable: true });\n }\n return Object.freeze(output);\n}\nfunction snapshotLimits(input: unknown): object {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) throw new TypeError();\n const output = Object.create(null) as Record<string, unknown>;\n for (const key of LIMIT_KEYS) {\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n if (!descriptor || !('value' in descriptor)) throw new TypeError();\n Object.defineProperty(output, key, { value: descriptor.value, enumerable: true, writable: false, configurable: false });\n }\n return Object.freeze(output);\n}\nfunction snapshotRecord(input: object, seen: Map<object, unknown>, state: SnapshotState, depth: number): object {\n const prototype = Object.getPrototypeOf(input);\n const names = ownNames(input, state.budget.items, 0);\n if (prototype !== Object.prototype && prototype !== null) throw new TypeError();\n const output = Object.create(null) as Record<string, unknown>; seen.set(input, output);\n for (const name of names) {\n const descriptor = Object.getOwnPropertyDescriptor(input, name);\n if (!descriptor || !('value' in descriptor)) throw new TypeError();\n Object.defineProperty(output, name, { value: name === 'limits' ? snapshotLimits(descriptor.value) : snapshot(descriptor.value, seen, state, depth + 1), enumerable: true, writable: true, configurable: true });\n }\n return Object.freeze(output);\n}\nfunction immutableMap<K, V>(input: Map<K, V>): ReadonlyMap<K, V> {\n const view = Object.create(null) as ReadonlyMap<K, V> & { set(key: K, value: V): unknown; delete(key: K): boolean; clear(): void };\n Object.defineProperties(view, {\n size: { value: input.size }, get: { value: (key: K) => input.get(key) }, has: { value: (key: K) => input.has(key) },\n entries: { value: () => input.entries() }, keys: { value: () => input.keys() }, values: { value: () => input.values() },\n forEach: { value: (callback: (value: V, key: K, map: ReadonlyMap<K, V>) => void, thisArg?: unknown) => input.forEach((value, key) => callback.call(thisArg, value, key, view)) },\n set: { value: () => view }, delete: { value: () => false }, clear: { value: () => undefined },\n [Symbol.iterator]: { value: () => input.entries() },\n });\n return Object.freeze(view);\n}\nexport function ownNames(input: object, maximum: number, maximumSymbols: number, allowedSymbols: readonly symbol[] | null = []): readonly string[] {\n const names = Object.getOwnPropertyNames(input); if (names.length > maximum) throw new TypeError();\n const symbols = Object.getOwnPropertySymbols(input); if (symbols.length > maximumSymbols) throw new TypeError();\n for (const symbol of symbols) if (allowedSymbols !== null && !allowedSymbols.includes(symbol)) throw new TypeError(); return names;\n}\n", "import type { ScannerLimitsV2 } from '@hub/contracts';\nimport { createDiagnosticId, sortDiagnostics } from '../diagnostics/identity';\nimport { classifyDiagnostic, type AnalysisDiagnosticV2, type DiagnosticCodeV2 } from '../diagnostics/registry';\nimport { isScannerAdmissionSnapshotV2 } from '../admission/snapshot';\nimport { SAFE_FACT_REGISTRY_V2 } from '../facts/safe-fact-registry';\nimport { isParsedSourceDocument } from '../source/source-document-provenance';\nimport type { EdgeRefV2, NodeRefV2, SecurityWorkflowV2 } from '../workflow-v2/security-workflow';\nimport type { ReadonlySourceDocumentV2, SourceMemberRefV2 } from '../source/source-types';\nimport { validateCapabilityCandidate } from './candidate-validator';\nimport { corroboratedCapabilityStatus, type CapabilityOutcomeStatusV2 } from './count-lattice';\nimport { resolveDeclaredRulesV2 } from '../rules-v2/rule-authority';\nimport { PROFILE_MANIFEST_REGISTRY_V2, validateProfileManifest, type ProfileCapabilityV2, type ProfileManifestV2 } from './profile-manifest';\nimport { ContextSnapshotLimitV2, contextView, ownNames, snapshotBound, type SnapshotBoundV2 } from './context-view';\ntype VersionComparatorV2 = Readonly<{ op: 'EQ' | 'LT' | 'LTE' | 'GT' | 'GTE'; version: string }>;\ntype VersionRangeV2 = Readonly<{ clauses: readonly (readonly VersionComparatorV2[])[] }>;\ntype SemanticPathV2 = Readonly<{ pointer: string; valueType: 'ANY' | 'STRING' | 'BOOLEAN' | 'NUMBER' | 'OBJECT' | 'ARRAY'; required: boolean }>;\ntype SemanticEndpointV2 = Readonly<{ path: string; channel: 'DATA' | 'CONTROL' | 'ERROR' | 'MODEL' | 'TOOL' | 'CONTEXT'; direction: 'SOURCE' | 'SINK' | 'SANITIZER'; taint: 'CONFIDENTIALITY' | 'INTEGRITY' | 'BOTH'; scope?: string }>;\ntype ResolvedNodeSemanticsV2 = Readonly<{ semanticId: string; nodeType: string; versionRange: VersionRangeV2; operation: string | null; entry: 'TRIGGER' | 'MANUAL' | 'SUBWORKFLOW' | 'NONE'; parameterPaths: readonly SemanticPathV2[]; authentication: Readonly<{ path: string; noneValues: readonly string[]; authenticatedValues: readonly string[]; unknownValueEffect: 'UNKNOWN' | 'EXPOSED' }> | null; credentialPaths: readonly string[]; destinationPaths: readonly string[]; effects: readonly ('READ_EXTERNAL' | 'WRITE_EXTERNAL' | 'EXECUTE_CODE' | 'EXECUTE_COMMAND' | 'READ_FILE' | 'WRITE_FILE' | 'DATABASE_READ' | 'DATABASE_WRITE' | 'SEND_MESSAGE' | 'CALL_TOOL' | 'START_SUBWORKFLOW')[]; endpoints: readonly SemanticEndpointV2[]; ports: readonly Readonly<{ type: string; index: number; itemMode: 'EACH' | 'ALL' | 'PAIRWISE' | 'UNKNOWN' }>[]; overwritePaths: readonly string[]; errorMode: 'STOP' | 'CONTINUE' | 'OUTPUT' | 'UNKNOWN'; retryMode: 'NONE' | 'BOUNDED' | 'PLATFORM' | 'UNKNOWN'; disabledMode: 'SKIP' | 'UNKNOWN'; provenance: Readonly<{ sourceUrl: string; sourceDigest: string; reviewedAt: string; reviewer: string }> }>;\nexport type AdmittedRuleV2 = Readonly<{ ruleId: string; revision: string; capabilityId: string; effect: 'SCORING' | 'REPORT_ONLY'; severity: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO'; confidence: 'HIGH' | 'MEDIUM' | 'LOW'; evidenceSchemaId: string; remediationId: string; cweIds: readonly string[]; owaspAgenticIds: readonly string[]; packDigest: string }>;\nexport type SemanticCatalogueViewV2 = Readonly<{ id: string; version: string; digest: string; resolvedNodeSemantics: ReadonlyMap<string, ResolvedNodeSemanticsV2> }>;\nexport type RuleCatalogueViewV2 = Readonly<{ id: string; version: string; digest: string; rules: ReadonlyMap<string, AdmittedRuleV2> }>;\nexport type SubjectV2 = Readonly<{ kind: 'WORKFLOW' } | { kind: 'NODE'; node: NodeRefV2 } | { kind: 'EDGE'; edge: EdgeRefV2 } | { kind: 'SOURCE'; source: SourceMemberRefV2 }>;\nexport type FindingCandidateV2 = Readonly<{ ruleId: string; evidenceClass: 'CAPABILITY' | 'CONFIGURATION' | 'SUSPICIOUS_SYNTAX' | 'POTENTIAL_DATAFLOW' | 'VERSION_APPLICABILITY'; conclusion: 'OBSERVED' | 'POTENTIAL' | 'UNKNOWN'; applicability: 'APPLICABLE' | 'NOT_APPLICABLE' | 'UNKNOWN'; subject: SubjectV2; factRefs: readonly string[]; traceRefs: readonly string[]; remediationId: string }>;\ntype SafeFactScalarV2 = string | number | boolean | null;\ntype SafeFactValueV2 = SafeFactScalarV2 | readonly SafeFactScalarV2[];\nexport type SafeFactV2 = Readonly<{ factId: string; kind: string; subject: SubjectV2; properties: Readonly<Record<string, SafeFactValueV2>> }>;\ntype TraceStepV2 = Readonly<{ ordinal: number; kind: 'SOURCE' | 'PROPAGATION' | 'SANITIZER' | 'SINK'; subject: SubjectV2; factRefs: readonly string[] }>;\nexport type TraceV2 = Readonly<{ traceId: string; kind: 'CONFIDENTIALITY' | 'INTEGRITY' | 'CONTROL'; steps: readonly TraceStepV2[] }>;\nexport type CapabilityCandidateV2 = Readonly<{ findings: readonly FindingCandidateV2[]; diagnostics: readonly AnalysisDiagnosticV2[]; facts: readonly SafeFactV2[]; traces: readonly TraceV2[]; seen: number; analyzed: number; skipped: number; omitted: number }>;\nexport type CapabilityExecutionV2 = Readonly<{ id: string; version: string; required: boolean; status: CapabilityOutcomeStatusV2; seen: number; analyzed: number; skipped: number; omitted: number; diagnosticIds: readonly string[] }>;\nexport type TargetContextV2 = Readonly<{ n8nVersion?: string; edition: 'COMMUNITY' | 'ENTERPRISE' | 'CLOUD' | 'UNKNOWN'; deployment: 'SELF_HOSTED' | 'CLOUD' | 'UNKNOWN'; role: 'OWNER' | 'ADMIN' | 'MEMBER' | 'UNKNOWN'; taskRunner: 'LEGACY' | 'NATIVE' | 'UNKNOWN'; communityPackages: readonly Readonly<{ name: string; version?: string }>[]; configuration: readonly Readonly<{ key: string; state: 'ENABLED' | 'DISABLED' | 'UNKNOWN' }>[]; contextDigest: string }>;\nexport type AnalyzerContextV2 = Readonly<{ source: ReadonlySourceDocumentV2; workflow: SecurityWorkflowV2; target: TargetContextV2; limits: ScannerLimitsV2; semantics: SemanticCatalogueViewV2; rules: RuleCatalogueViewV2; priorOutcomes: ReadonlyMap<string, CapabilityExecutionV2> }>;\nexport type CapabilitySpecV2 = Readonly<ProfileCapabilityV2 & { run(context: AnalyzerContextV2): CapabilityCandidateV2 }>;\nexport type CapabilityRegistryV2 = ReadonlyMap<string, CapabilitySpecV2>;\nexport type CapabilityScheduleV2 = Readonly<{ executions: readonly CapabilityExecutionV2[]; candidates: readonly CapabilityCandidateV2[]; diagnostics: readonly AnalysisDiagnosticV2[] }>;\nconst SPEC_KEYS = ['id', 'version', 'required', 'dependsOn', 'ruleIds', 'run'] as const;\ntype CounterValues = Readonly<{ seen: number; analyzed: number; skipped: number; omitted: number }>;\ntype MutableExecution = { id: string; version: string; required: boolean; status: CapabilityExecutionV2['status']; seen: number; analyzed: number; skipped: number; omitted: number; diagnosticIds: string[] };\ntype EligibilityUnitScopeV2 = 'SOURCE_DOCUMENT' | 'WORKFLOW' | 'NODE';\n// Keep this parser-owned work contract aligned with the admitted capability registry. Source\n// normalization has one parsed-document unit, node-scoped analyzers inspect the normalized node\n// list, and other workflow-level stages have one unit even when the workflow contains no nodes.\nconst CAPABILITY_ELIGIBILITY_SCOPE_V2: Readonly<Record<string, EligibilityUnitScopeV2>> = Object.freeze({\n 'source-normalization': 'SOURCE_DOCUMENT', 'workflow-insights': 'WORKFLOW', 'structural-policies': 'NODE',\n 'expression-security': 'NODE', 'javascript-security': 'NODE', 'python-security': 'NODE',\n 'graph-semantics': 'NODE', 'taint-confidentiality': 'NODE', 'taint-integrity': 'NODE',\n 'agentic-control': 'NODE', assessment: 'WORKFLOW', 'presentation-facts': 'WORKFLOW',\n});\n\nexport function scheduleCapabilities(context: AnalyzerContextV2, manifest: ProfileManifestV2, registry: CapabilityRegistryV2): CapabilityScheduleV2 {\n const executions: MutableExecution[] = []; const candidates: CapabilityCandidateV2[] = []; const rawDiagnostics: AnalysisDiagnosticV2[] = []; const byId = new Map<string, MutableExecution>();\n const admission = validateProfileManifest(manifest, registry); if (!admission.ok) return closedSchedule(manifest); manifest = admission.manifest;\n const selectedSpecs = snapshotSpecs(manifest, registry);\n // One frozen view serves every capability: the view is deeply frozen and immutable, so a second\n // copy would only repeat the walk. On the D-1 fixtures the copy measured 20.6\u201327.5% of the\n // pipeline across seven shapes (D1-FIX-REVIEW.md), and the beta-default profile runs five\n // capabilities (twelve under beta-hardened) over the same context, so without the cache every\n // capability would pay that share again. It is still built inside the capability loop, so a\n // context the walk refuses fails that capability closed instead of escaping the scheduler.\n let cachedView: AnalyzerContextV2 | undefined;\n for (const capability of manifest.capabilities) {\n const unavailable = capability.dependsOn.find((dependency) => byId.get(dependency)?.status !== 'COMPLETED');\n if (unavailable !== undefined) {\n const execution = failedExecution(capability, 'SKIPPED', { seen: 0, analyzed: 0, skipped: 1, omitted: 0 }, 1);\n executions.push(execution); byId.set(capability.id, execution); rawDiagnostics.push(schedulerDiagnostic('DEPENDENCY_UNAVAILABLE', capability)); continue;\n }\n try {\n const declared = resolveDeclaredRulesV2(capability.ruleIds, context.rules.rules, capability);\n if (!declared.ok) {\n // A declared rule id the catalogue does not admit is refused, never silently filtered out\n // of the registry this capability would run with. The consequence follows the case the\n // authority resolved: a scoring unknown fails the run closed (FAILED, and the registry row\n // is INDETERMINATE/ineligible so no assessment can be published), while a report-only\n // unknown degrades its owner and lets everything else still score.\n const refused = failedExecution(capability, declared.case === 'SCORING' ? 'FAILED' : 'DEGRADED', { seen: 0, analyzed: 0, skipped: 0, omitted: 0 }, 1);\n executions.push(refused); byId.set(capability.id, refused);\n rawDiagnostics.push(schedulerDiagnostic(declared.diagnosticCode, capability));\n continue;\n }\n const spec = selectedSpecs.get(capability.id); if (!spec) throw new TypeError();\n const runnerContext = cachedView ?? contextView(context);\n cachedView = runnerContext;\n const eligibleUnits = capabilityEligibleUnits(capability.id, runnerContext);\n const output: unknown = spec.run(runnerContext);\n if (!isScannerAdmissionSnapshotV2<CapabilityCandidateV2>(output)) throw new TypeError();\n const validation = validateCapabilityCandidate(output, spec, { facts: SAFE_FACT_REGISTRY_V2, rules: declared.rules }, context.limits, eligibleUnits);\n if (!validation.ok) {\n const status = capability.required ? 'FAILED' : 'DEGRADED';\n const execution = failedExecution(capability, status, validation.counters, 1);\n executions.push(execution); byId.set(capability.id, execution);\n const bound = validation.limit === undefined ? undefined : snapshotBound(validation.limit.observed, validation.limit.maximum);\n rawDiagnostics.push(capabilityFailureDiagnostic(capability, bound === undefined ? { limit: validation.reason === 'LIMIT_EXCEEDED' } : { limit: true, bound }));\n continue;\n }\n candidates.push(validation.candidate); const execution = completedExecution(capability, validation.candidate);\n executions.push(execution); byId.set(capability.id, execution);\n } catch (error) {\n const status = capability.required ? 'FAILED' : 'DEGRADED';\n const execution = failedExecution(capability, status, { seen: 0, analyzed: 0, skipped: 0, omitted: 0 }, 1);\n executions.push(execution); byId.set(capability.id, execution);\n const bound = error instanceof ContextSnapshotLimitV2 ? snapshotBound(error.observed, error.maximum) : undefined;\n rawDiagnostics.push(capabilityFailureDiagnostic(capability, bound === undefined ? { limit: false } : { limit: true, bound }));\n }\n }\n return finalizeSchedule(executions, candidates, rawDiagnostics, manifest.capabilities.map(({ id }) => id));\n}\n\nfunction closedSchedule(manifest: ProfileManifestV2): CapabilityScheduleV2 { const capabilities = safeFailureCapabilities(manifest); const executions = capabilities.map((capability) => failedExecution(capability, capability.required ? 'FAILED' : 'DEGRADED', { seen: 0, analyzed: 0, skipped: 0, omitted: 0 }, 1)); return finalizeSchedule(executions, [], capabilities.map((capability) => schedulerDiagnostic(capability.required ? 'REQUIRED_CAPABILITY_FAILED' : 'POLICY_EXECUTION_FAILED', capability)), capabilities.map(({ id }) => id)); }\nfunction capabilityEligibleUnits(capabilityId: string, context: AnalyzerContextV2): number {\n const scope = CAPABILITY_ELIGIBILITY_SCOPE_V2[capabilityId];\n if (scope === undefined || !isParsedSourceDocument(context.source) || !Array.isArray(context.workflow?.nodes)) throw new TypeError();\n return scope === 'NODE' ? context.workflow.nodes.length : 1;\n}\nfunction safeFailureCapabilities(input: unknown): readonly ProfileCapabilityV2[] { try { if (input === null || typeof input !== 'object' || Array.isArray(input)) throw new TypeError(); const id = safeManifestString(input, 'id'); const version = safeManifestString(input, 'version'); if (id === undefined || version === undefined) return []; return PROFILE_MANIFEST_REGISTRY_V2.find((profile) => profile.id === id && profile.version === version)?.capabilities ?? []; } catch { return []; } }\nfunction safeManifestString(input: object, key: 'id' | 'version'): string | undefined { const descriptor = Object.getOwnPropertyDescriptor(input, key); return descriptor && 'value' in descriptor && typeof descriptor.value === 'string' ? descriptor.value : undefined; }\nfunction finalizeSchedule(executions: readonly MutableExecution[], candidates: readonly CapabilityCandidateV2[], rawDiagnostics: readonly AnalysisDiagnosticV2[], capabilityOrder: readonly string[]): CapabilityScheduleV2 { const diagnostics = sortDiagnostics(rawDiagnostics, capabilityOrder); const idsByCapability = new Map<string, string[]>(); for (const diagnostic of diagnostics) (idsByCapability.get(diagnostic.capabilityId) ?? (idsByCapability.set(diagnostic.capabilityId, []), idsByCapability.get(diagnostic.capabilityId)!)).push(diagnostic.id); const frozenExecutions = Object.freeze(executions.map((execution) => Object.freeze({ ...execution, diagnosticIds: Object.freeze(idsByCapability.get(execution.id) ?? []) }))); return Object.freeze({ executions: frozenExecutions, candidates: Object.freeze(candidates), diagnostics: Object.freeze(diagnostics) }); }\n\nfunction snapshotSpecs(manifest: ProfileManifestV2, registry: CapabilityRegistryV2): ReadonlyMap<string, CapabilitySpecV2 | undefined> {\n const snapshots = new Map<string, CapabilitySpecV2 | undefined>();\n for (const capability of manifest.capabilities) {\n try {\n const entry = registryEntry(registry, capability.id);\n snapshots.set(capability.id, entry === undefined ? undefined : snapshotSpec(entry, capability));\n } catch { snapshots.set(capability.id, undefined); }\n }\n return snapshots;\n}\nfunction snapshotSpec(input: unknown, capability: ProfileCapabilityV2): CapabilitySpecV2 {\n const value = record(input, SPEC_KEYS, true);\n if (value.id !== capability.id || value.version !== capability.version || value.required !== capability.required\n || !sameList(value.dependsOn, capability.dependsOn) || !sameList(value.ruleIds, capability.ruleIds) || typeof value.run !== 'function') throw new TypeError();\n return Object.freeze({ ...capability, dependsOn: Object.freeze([...capability.dependsOn]), ruleIds: Object.freeze([...capability.ruleIds]), run: value.run as CapabilitySpecV2['run'] });\n}\n\nfunction registryEntry(registry: CapabilityRegistryV2, id: string): CapabilitySpecV2 | undefined {\n if (!(registry instanceof Map) || Object.getPrototypeOf(registry) !== Map.prototype) throw new TypeError();\n ownNames(registry, 0, 0);\n return Map.prototype.get.call(registry, id) as CapabilitySpecV2 | undefined;\n}\nfunction completedExecution(capability: ProfileCapabilityV2, candidate: CapabilityCandidateV2): MutableExecution {\n return { id: capability.id, version: capability.version, required: capability.required, status: corroboratedCapabilityStatus('COMPLETED', candidate), seen: candidate.seen, analyzed: candidate.analyzed, skipped: candidate.skipped, omitted: candidate.omitted, diagnosticIds: [] };\n}\nfunction failedExecution(capability: ProfileCapabilityV2, status: 'SKIPPED' | 'DEGRADED' | 'FAILED', counters: CounterValues, omission: number): MutableExecution {\n return { id: capability.id, version: capability.version, required: capability.required, status, seen: counters.seen, analyzed: counters.analyzed, skipped: counters.skipped, omitted: safeAdd(counters.omitted, omission), diagnosticIds: [] };\n}\nfunction schedulerDiagnostic(code: DiagnosticCodeV2, capability: ProfileCapabilityV2, bound?: SnapshotBoundV2): AnalysisDiagnosticV2 {\n const classification = classifyDiagnostic(code, capability.required);\n const identity = { code, capabilityId: capability.id, ...classification, ...(bound === undefined ? {} : { observed: bound.observed, maximum: bound.maximum, omitted: bound.omitted }) };\n return Object.freeze({ ...identity, id: createDiagnosticId(identity) });\n}\n/**\n * The diagnostic of a capability that could not publish its result. D-1: both failure branches used\n * to publish `REQUIRED_CAPABILITY_FAILED`/`POLICY_EXECUTION_FAILED` whatever the cause, so an\n * operator could not tell a candidate the validator refused for exceeding a limit from a capability\n * that broke, and a context view the scheduler refused for size from either. The cause now selects\n * the code: a limit refusal is published as the registry's limit code (LIMIT category) and carries\n * the bound's numbers (`observed`/`maximum`/`omitted`), whether the refusal came from the context\n * walk or from `validateCapabilityCandidate` \u2014 the validator requires exactly those numbers of\n * capability-emitted LIMIT diagnostics (`candidate-validator.ts`), so its own refusals report them\n * too. The remaining vocabulary is unchanged, because the diagnostic record is a closed shape pinned by\n * `contracts/scanner-v2-result.ts`: no free-form reason can be added to it without a contract and\n * diagnostic-registry change.\n */\nfunction capabilityFailureDiagnostic(capability: ProfileCapabilityV2, cause: Readonly<{ limit: boolean; bound?: SnapshotBoundV2 }>): AnalysisDiagnosticV2 {\n const code: DiagnosticCodeV2 = cause.limit\n ? capability.required ? 'REQUIRED_LIMIT_EXCEEDED' : 'OPTIONAL_LIMIT_EXCEEDED'\n : capability.required ? 'REQUIRED_CAPABILITY_FAILED' : 'POLICY_EXECUTION_FAILED';\n return schedulerDiagnostic(code, capability, cause.bound);\n}\nfunction record(input: unknown, allowed: readonly string[], allowNullPrototype = false): Record<string, unknown> {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) throw new TypeError();\n const prototype = Object.getPrototypeOf(input); if (prototype !== Object.prototype && (!allowNullPrototype || prototype !== null)) throw new TypeError();\n const names = ownNames(input, allowed.length, 0); const value = Object.create(null) as Record<string, unknown>;\n for (const name of names) { if (!allowed.includes(name)) throw new TypeError(); const descriptor = Object.getOwnPropertyDescriptor(input, name); if (!descriptor || !('value' in descriptor)) throw new TypeError(); value[name] = descriptor.value; }\n for (const name of allowed) if (!Object.prototype.hasOwnProperty.call(value, name)) throw new TypeError(); return value;\n}\nfunction safeAdd(left: number, right: number): number { return left > Number.MAX_SAFE_INTEGER - right ? Number.MAX_SAFE_INTEGER : left + right; }\nfunction sameList(left: unknown, right: readonly string[]): boolean {\n if (!Array.isArray(left) || Object.getPrototypeOf(left) !== Array.prototype) return false;\n const length = Object.getOwnPropertyDescriptor(left, 'length');\n if (!length || !('value' in length) || length.value !== right.length) return false;\n const names = ownNames(left, right.length + 1, 0); if (names.length !== right.length + 1) return false;\n for (let index = 0; index < right.length; index += 1) { const descriptor = Object.getOwnPropertyDescriptor(left, String(index)); if (!descriptor || !('value' in descriptor) || descriptor.value !== right[index]) return false; }\n return true;\n}\n", "import type { ScanFinding, ScanPolicy } from '../policy/policy';\nimport { createBetaDefaultPolicies } from '../policies/beta-policies';\nimport { analyzeWorkflowInsights } from '../scan-insights';\nimport type { AnalysisDiagnosticV2 } from '../diagnostics/registry';\nimport { toNativeWorkflow } from './adapter-workflow';\nimport { candidateFinding, createDiagnostic, emptyCandidate, makeFact, policyFailureDiagnostic, unknownRuleDiagnostic, admitCandidate } from './adapter-evidence';\nimport { scheduleCapabilities, type AnalyzerContextV2, type CapabilityCandidateV2, type CapabilityRegistryV2, type CapabilityScheduleV2, type CapabilitySpecV2, type FindingCandidateV2, type SafeFactV2 } from './scheduler';\nimport { BETA_DEFAULT_PROFILE_MANIFEST, type ProfileCapabilityV2, type ProfileManifestV2 } from './profile-manifest';\nimport type { SecurityNodeV2 } from '../workflow-v2/security-workflow';\n\nexport type BetaDefaultAdapterOptions = Readonly<{ policies?: readonly ScanPolicy[]; maxFindings?: number }>;\n\nexport function createBetaDefaultCapabilityRegistry(options: BetaDefaultAdapterOptions = {}): CapabilityRegistryV2 {\n const policies = options.policies ?? createBetaDefaultPolicies();\n const specs = BETA_DEFAULT_PROFILE_MANIFEST.capabilities.map((capability): readonly [string, CapabilitySpecV2] => [capability.id, {\n ...capability,\n run: capability.id === 'source-normalization' ? (context) => sourceCandidate(context) : capability.id === 'workflow-insights' ? (context) => insightCandidate(context) : capability.id === 'structural-policies' ? (context) => structuralCandidate(context, capability, policies, options.maxFindings) : () => emptyCandidate(1),\n }]);\n return new Map(specs);\n}\n\nexport function scanCapabilitiesV2(context: AnalyzerContextV2, profile: ProfileManifestV2 = BETA_DEFAULT_PROFILE_MANIFEST, registry: CapabilityRegistryV2 = createBetaDefaultCapabilityRegistry()): CapabilityScheduleV2 {\n return scheduleCapabilities(context, profile, registry);\n}\n\nfunction sourceCandidate(context: AnalyzerContextV2): CapabilityCandidateV2 {\n const fact = makeFact('workflow.fingerprint.v1', { kind: 'WORKFLOW' }, { value: context.source.rawSha256 });\n return admitCandidate({ findings: [], diagnostics: [], facts: [fact], traces: [], seen: 1, analyzed: 1, skipped: 0, omitted: 0 });\n}\n\nfunction insightCandidate(context: AnalyzerContextV2): CapabilityCandidateV2 {\n const workflow = toNativeWorkflow(context); const insights = analyzeWorkflowInsights(workflow); const facts: SafeFactV2[] = [];\n const subject = { kind: 'WORKFLOW' as const };\n facts.push(makeFact('workflow.summary.v1', subject, { connectionCount: insights.workflow.connectionCount }));\n facts.push(makeFact('workflow.function.v1', subject, { basicPurpose: insights.functionSummary.basicPurpose, triggerDescription: insights.functionSummary.triggerDescription, dataFlowSummary: insights.functionSummary.dataFlowSummary, businessCategory: insights.functionSummary.businessCategory, confidence: insights.functionSummary.confidence }));\n for (const integration of insights.integrations) facts.push(makeFact('integration.v1', subject, { service: integration.service, usage: integration.usage, nodeTypes: integration.nodeTypes, nodeCount: integration.nodeCount, riskNotes: integration.riskNotes }));\n return admitCandidate({ findings: [], diagnostics: [], facts, traces: [], seen: 1, analyzed: 1, skipped: 0, omitted: 0 });\n}\n\nfunction structuralCandidate(context: AnalyzerContextV2, capability: ProfileCapabilityV2, policies: readonly ScanPolicy[], maxFindings?: number): CapabilityCandidateV2 {\n const workflow = toNativeWorkflow(context); const facts: SafeFactV2[] = []; const findings: FindingCandidateV2[] = []; const diagnostics = []; let omitted = 0;\n for (const policy of policies) {\n let produced: readonly ScanFinding[];\n try { produced = policy.evaluate(workflow); } catch { diagnostics.push(policyFailureDiagnostic(capability)); omitted += 1; continue; }\n for (const finding of produced) {\n const node = findNode(context.workflow.nodes, finding.location.nodeId, finding.location.nodeName);\n if (!node) { diagnostics.push(unknownRuleDiagnostic(capability)); omitted += 1; continue; }\n const candidate = candidateFinding(finding, node, context, capability, facts);\n if (candidate) findings.push(candidate); else { diagnostics.push(unknownRuleDiagnostic(capability)); omitted += 1; }\n }\n }\n const cap = maxFindings === undefined ? findings.length : Math.max(0, Math.min(maxFindings, findings.length));\n if (cap < findings.length) { omitted += findings.length - cap; diagnostics.push(createDiagnostic('REQUIRED_LIMIT_EXCEEDED', capability.id, capability.required, undefined, { observed: findings.length, maximum: cap, omitted: findings.length - cap })); }\n const kept = findings.slice(0, cap); const refs = new Set(kept.flatMap((finding) => finding.factRefs));\n return admitCandidate({ findings: kept, diagnostics: uniqueDiagnostics(diagnostics), facts: facts.filter((fact) => refs.has(fact.factId)), traces: [], seen: workflow.nodes.length, analyzed: workflow.nodes.length, skipped: 0, omitted });\n}\n\nfunction findNode(nodes: readonly SecurityNodeV2[], id: string | undefined, name: string | undefined): SecurityNodeV2 | undefined {\n if (id === undefined && name === undefined) return undefined;\n for (let index = 0; index < nodes.length; index += 1) {\n const node = nodes[index]; if (node && (id === undefined || node.ref.explicitId === id) && (name === undefined || node.ref.name === name)) return node;\n }\n for (let index = 0; index < nodes.length; index += 1) {\n const node = nodes[index]; if (node && ((id !== undefined && node.ref.explicitId === id) || (name !== undefined && node.ref.name === name))) return node;\n }\n return undefined;\n}\n\nfunction uniqueDiagnostics(diagnostics: readonly AnalysisDiagnosticV2[]): AnalysisDiagnosticV2[] {\n const seen = new Set<string>(); return diagnostics.filter((diagnostic) => seen.has(diagnostic.id) ? false : (seen.add(diagnostic.id), true));\n}\n\nexport const BETA_DEFAULT_CAPABILITY_REGISTRY = createBetaDefaultCapabilityRegistry();\n", "/** Canonical identity for deterministic scanner behavior and generated data. */\nexport const SCANNER_VERSION = 'scanner-beta-1' as const;\n", "import type { ScanPolicy } from '../policy/policy';\nimport {\n betaDefaultRuleCatalog,\n betaHardenedRuleCatalog,\n type RuleCatalogEntry,\n} from '../policy/rule-catalog';\nimport { createBetaDefaultCapabilityRegistry } from '../capabilities/beta-default';\nimport { BETA_DEFAULT_PROFILE_MANIFEST, type ProfileManifestV2 } from '../capabilities/profile-manifest';\nimport type { CapabilityRegistryV2 } from '../capabilities/scheduler';\nimport { createBetaDefaultPolicies, type BetaPolicyOptions } from './beta-policies';\nimport { SCANNER_VERSION } from '../scanner-version';\n\nexport type PolicyProfileId = 'beta-default' | 'beta-hardened';\n\nexport type PolicyProfileEntry = Readonly<{\n ok: true;\n profileId: PolicyProfileId;\n version: typeof SCANNER_VERSION;\n createPolicies: (options?: BetaPolicyOptions) => ScanPolicy[];\n ruleCatalog: readonly RuleCatalogEntry[];\n includesSourceSpans: boolean;\n includesJavaScriptAnalysis: boolean;\n includesPythonAnalysis: boolean;\n includesTaintAnalysis: boolean;\n capabilityManifest: ProfileManifestV2 | null;\n createCapabilityRegistry: (() => CapabilityRegistryV2) | null;\n}>;\n\nexport type PolicyProfileMissing = {\n ok: false;\n code: 'UNKNOWN_PROFILE';\n profileId: string;\n};\n\nexport type PolicyProfileResult = PolicyProfileEntry | PolicyProfileMissing;\n\nconst registry = Object.create(null) as Record<string, PolicyProfileEntry>;\n\nregistry['beta-default'] = Object.freeze({\n ok: true,\n profileId: 'beta-default',\n version: SCANNER_VERSION,\n createPolicies: createBetaDefaultPolicies,\n ruleCatalog: betaDefaultRuleCatalog,\n includesSourceSpans: false,\n includesJavaScriptAnalysis: false,\n includesPythonAnalysis: false,\n includesTaintAnalysis: false,\n capabilityManifest: BETA_DEFAULT_PROFILE_MANIFEST,\n createCapabilityRegistry: () => createBetaDefaultCapabilityRegistry(),\n});\n\nregistry['beta-hardened'] = Object.freeze({\n ...registry['beta-default'],\n profileId: 'beta-hardened',\n includesSourceSpans: true,\n includesJavaScriptAnalysis: true,\n includesPythonAnalysis: true,\n includesTaintAnalysis: true,\n ruleCatalog: betaHardenedRuleCatalog,\n capabilityManifest: null,\n createCapabilityRegistry: null,\n});\n\nObject.freeze(registry);\n\nexport function resolvePolicyProfile(profileId: string): PolicyProfileResult {\n const entry = registry[profileId];\n if (entry) return entry;\n return { ok: false, code: 'UNKNOWN_PROFILE', profileId };\n}\n", "import type { NormalizedWorkflow } from '../workflow';\nimport {\n canonicalizeFindings,\n type CanonicalFindingsResult,\n} from '../result/canonical-findings';\nimport { asRequiredStageFailure, classifyAnalysisStatus } from '../result/analysis-completeness';\nimport { collectAnalysisDiagnostics } from '../result/analysis-diagnostics-collection';\nimport type {\n AnalysisDiagnostic,\n AnalysisStatus,\n CanonicalScanFinding,\n ScanFinding,\n ScanPolicy,\n ScanSummary,\n} from '../policy/policy';\nimport type { RuleCatalogEntry } from '../policy/rule-catalog';\nimport { scanCapabilitiesV2 as scanCapabilitiesAdapter } from '../capabilities/beta-default';\nimport type { AnalyzerContextV2, CapabilityScheduleV2 } from '../capabilities/scheduler';\nimport { resolvePolicyProfile, type PolicyProfileResult } from '../policies/profile';\n\nexport type ScanCapabilitiesV2Failure =\n | { ok: false; code: 'UNKNOWN_PROFILE'; profileId: string }\n | { ok: false; code: 'PROFILE_NOT_ADMITTED'; profileId: string };\n\nexport type ScanCapabilitiesV2Result = CapabilityScheduleV2 | ScanCapabilitiesV2Failure;\n\nexport function scanCapabilitiesV2(\n context: AnalyzerContextV2,\n profile: PolicyProfileResult,\n): ScanCapabilitiesV2Result {\n if (!profile || !profile.ok) return profile;\n\n const canonical = resolvePolicyProfile(profile.profileId);\n if (!canonical.ok) return canonical;\n if (canonical !== profile) {\n return { ok: false, code: 'PROFILE_NOT_ADMITTED', profileId: profile.profileId };\n }\n if (canonical.capabilityManifest === null || typeof canonical.createCapabilityRegistry !== 'function') {\n return { ok: false, code: 'PROFILE_NOT_ADMITTED', profileId: canonical.profileId };\n }\n\n try {\n return scanCapabilitiesAdapter(\n context,\n canonical.capabilityManifest,\n canonical.createCapabilityRegistry(),\n );\n } catch {\n return { ok: false, code: 'PROFILE_NOT_ADMITTED', profileId: canonical.profileId };\n }\n}\n\nexport type CoreAnalyzerResult = {\n findings: readonly ScanFinding[];\n diagnostics: readonly AnalysisDiagnostic[];\n};\n\nexport type CoreAnalyzer = (workflow: NormalizedWorkflow) => CoreAnalyzerResult;\n\nexport type ScanWorkflowCoreOptions = {\n policies: readonly ScanPolicy[];\n analyzers?: readonly CoreAnalyzer[];\n ruleCatalog: readonly RuleCatalogEntry[];\n maxAnalyzerFindings?: number;\n ambiguousNodeIds?: ReadonlySet<string>;\n};\n\nexport type ScanWorkflowCoreResult = {\n findings: CanonicalScanFinding[];\n diagnostics: AnalysisDiagnostic[];\n analysisStatus: AnalysisStatus;\n summary: ScanSummary;\n policyFailureCount: number;\n rejectedCount: number;\n collapsedCount: number;\n};\n\nexport function scanWorkflowCore(\n workflow: NormalizedWorkflow,\n options: ScanWorkflowCoreOptions,\n): ScanWorkflowCoreResult {\n const policyEvaluation = evaluatePolicies(options.policies, workflow);\n const analyzerFindings: ScanFinding[] = [];\n const analyzerDiagnostics: AnalysisDiagnostic[] = [];\n\n for (const analyzer of options.analyzers ?? []) {\n const result = analyzer(workflow);\n analyzerFindings.push(...result.findings);\n analyzerDiagnostics.push(...result.diagnostics.map(asRequiredStageFailure));\n }\n\n const maxAnalyzerFindings = Math.max(0, options.maxAnalyzerFindings ?? Number.POSITIVE_INFINITY);\n const canonical = canonicalizeFindings(\n [...policyEvaluation.findings, ...analyzerFindings],\n options.ruleCatalog,\n {\n legacyFindingCount: policyEvaluation.findings.length,\n maxAnalyzerFindings,\n ambiguousNodeIds: options.ambiguousNodeIds,\n },\n );\n const diagnostics = collectAnalysisDiagnostics({\n workflow,\n analyzerDiagnostics,\n spanUnresolvedCount: 0,\n policyRejectedCount: canonical.rejectedCount,\n policyFailedCount: policyEvaluation.failureCount,\n findingCollapsedCount: canonical.collapsedCount,\n scanCapExceeded: analyzerFindings.length > maxAnalyzerFindings,\n });\n\n return {\n findings: canonical.findings,\n diagnostics,\n analysisStatus: classifyAnalysisStatus(diagnostics),\n summary: summarizeFindings(canonical),\n policyFailureCount: policyEvaluation.failureCount,\n rejectedCount: canonical.rejectedCount,\n collapsedCount: canonical.collapsedCount,\n };\n}\n\nfunction evaluatePolicies(\n policies: readonly ScanPolicy[],\n workflow: NormalizedWorkflow,\n): { findings: ScanFinding[]; failureCount: number } {\n const findings: ScanFinding[] = [];\n let failureCount = 0;\n for (const policy of policies) {\n try {\n findings.push(...policy.evaluate(workflow));\n } catch {\n failureCount += 1;\n }\n }\n return { findings, failureCount };\n}\n\nfunction summarizeFindings(canonical: CanonicalFindingsResult): ScanSummary {\n const summary: ScanSummary = { critical: 0, high: 0, medium: 0, low: 0, info: 0 };\n for (const finding of canonical.findings) {\n const key = finding.severity.toLowerCase() as keyof ScanSummary;\n summary[key] += 1;\n }\n return summary;\n}\n", "import { redactText } from './redaction/redaction';\n\n/**\n * R6-F2. Redaction removes secrets but said nothing about length, so a\n * user-controlled string arrived at the JSON sinks at whatever size it was\n * authored. `AnalysisDiagnostic.location.path` is a JSON pointer built from raw\n * node names, and a 5,000-character node name produced a 5,028-character\n * pointer in the browser's downloadable report and the CLI's `--format=json`.\n *\n * The SARIF exporter already bounded these (240 for `path`, 160 for\n * `nodeName`/`nodeId`), so the two JSON sinks were the asymmetric ones. Bound\n * them here, at the shared boundary every sink passes through, rather than\n * repeating the cap per exporter \u2014 SARIF's own bound then becomes belt and\n * braces rather than the only guard.\n *\n * Only location-ish fields are bounded. Findings' evidence and display text are\n * deliberately left alone: they have their own truncation rules, and silently\n * shortening them here would change what a report says a policy found.\n */\nconst LOCATION_FIELD_LIMITS: Readonly<Record<string, number>> = {\n path: 240,\n nodeName: 160,\n nodeId: 160,\n};\n\nconst TRUNCATION_SUFFIX = '\u2026';\n\n/** Redacts every string in a scanner result without changing its object shape. */\nexport function redactScanPresentation<T>(value: T): T {\n return redactStrings(value) as T;\n}\n\nfunction boundLocationField(key: string, value: string): string {\n const limit = LOCATION_FIELD_LIMITS[key];\n if (limit === undefined || value.length <= limit) return value;\n return value.slice(0, limit - TRUNCATION_SUFFIX.length) + TRUNCATION_SUFFIX;\n}\n\nfunction redactStrings(value: unknown, key?: string): unknown {\n if (typeof value === 'string') {\n return key === undefined ? redactText(value) : boundLocationField(key, redactText(value));\n }\n if (Array.isArray(value)) return value.map((child) => redactStrings(child));\n if (typeof value === 'object' && value !== null) {\n return Object.fromEntries(\n Object.entries(value).map(([childKey, child]) => [childKey, redactStrings(child, childKey)]),\n );\n }\n return value;\n}\n", "import type { CanonicalScanFinding } from '../policy/policy';\nimport type { NormalizedWorkflowNode } from '../workflow';\n\nexport type SourceSpanAttachment = {\n findings: CanonicalScanFinding[];\n unresolvedCount: number;\n};\n\n/**\n * Sole authority for v1 finding-to-source span attachment; the browser engine and the pipeline\n * CLI both call it and neither may restate it.\n *\n * Ambiguity is id-level duplication: a node id carried by more than one normalized node names no\n * single source, so the finding stays without a span and the caller raises\n * `SOURCE_SPAN_UNAVAILABLE` from `unresolvedCount`. That is the same condition the parser records\n * as `DUPLICATE_NODE_ID`, derived here from the node list so both surfaces derive it identically.\n */\nexport function attachFindingSourceSpans(\n findings: CanonicalScanFinding[],\n nodes: ReadonlyArray<NormalizedWorkflowNode>,\n): SourceSpanAttachment {\n const nodesById = new Map<string, NormalizedWorkflowNode[]>();\n for (const node of nodes) {\n nodesById.set(node.id, [...(nodesById.get(node.id) ?? []), node]);\n }\n\n let unresolvedCount = 0;\n const attached = findings.map((finding) => {\n const nodeId = finding.location.nodeId;\n if (nodeId === undefined) return finding;\n\n const matches = nodesById.get(nodeId);\n const sourceSpan = matches && matches.length === 1 ? matches[0].sourceSpan : undefined;\n if (!sourceSpan) {\n unresolvedCount += 1;\n return finding;\n }\n return { ...finding, location: { ...finding.location, sourceSpan } };\n });\n\n return { findings: attached, unresolvedCount };\n}\n", "export function exceedsNestingDepth(value: unknown, maxDepth: number): boolean {\n const pending: Array<{ value: unknown; depth: number }> = [{ value, depth: 0 }];\n const visited = new WeakSet<object>();\n\n while (pending.length > 0) {\n const current = pending.pop();\n if (!current || current.depth > maxDepth) return current !== undefined;\n if (!isContainer(current.value) || visited.has(current.value)) continue;\n\n visited.add(current.value);\n for (const child of Object.values(current.value)) {\n pending.push({ value: child, depth: current.depth + 1 });\n }\n }\n\n return false;\n}\n\nexport function exceedsParameterBudget(\n value: unknown,\n limits: { maxDepth?: number; maxLeaves?: number },\n): boolean {\n const pending: Array<{ value: unknown; depth: number }> = [{ value, depth: 0 }];\n const visited = new WeakSet<object>();\n let leaves = 0;\n\n while (pending.length > 0) {\n const current = pending.pop();\n if (!current) continue;\n if (limits.maxDepth !== undefined && current.depth > limits.maxDepth) return true;\n if (!isContainer(current.value)) {\n leaves += 1;\n if (limits.maxLeaves !== undefined && leaves > limits.maxLeaves) return true;\n continue;\n }\n if (visited.has(current.value)) continue;\n\n visited.add(current.value);\n for (const child of Object.values(current.value)) {\n pending.push({ value: child, depth: current.depth + 1 });\n }\n }\n\n return false;\n}\n\nfunction isContainer(value: unknown): value is Record<string, unknown> | unknown[] {\n return typeof value === 'object' && value !== null;\n}\n", "import type { DuplicateJsonKeyLocation } from './workflow-source-locations';\n\nexport type MalformedNodeParametersLocation = { nodeIndex: number; pointer: string };\n\nexport type WorkflowParseDiagnostic =\n | { code: 'DUPLICATE_NODE_NAME'; nodeIndexes: number[] }\n | { code: 'DUPLICATE_NODE_ID'; nodeIndexes: number[] }\n | { code: 'DUPLICATE_JSON_KEY'; pointer: string; key: string }\n | { code: 'MALFORMED_NODE_PARAMETERS'; nodeIndex: number; pointer: string };\n\ntype IdentifiedNode = { id: string; name: string };\n\nexport function collectParseDiagnostics(\n nodes: ReadonlyArray<IdentifiedNode>,\n duplicateKeys: ReadonlyArray<DuplicateJsonKeyLocation>,\n malformedParameters: ReadonlyArray<MalformedNodeParametersLocation> = [],\n): WorkflowParseDiagnostic[] {\n return [\n ...duplicateGroups(nodes, (node) => node.name)\n .map((nodeIndexes) => ({ code: 'DUPLICATE_NODE_NAME' as const, nodeIndexes })),\n ...duplicateGroups(nodes, (node) => node.id)\n .map((nodeIndexes) => ({ code: 'DUPLICATE_NODE_ID' as const, nodeIndexes })),\n ...duplicateKeys.map((location) => ({ code: 'DUPLICATE_JSON_KEY' as const, ...location })),\n ...malformedParameters.map((location) => ({ code: 'MALFORMED_NODE_PARAMETERS' as const, ...location })),\n ];\n}\n\nfunction duplicateGroups(\n nodes: ReadonlyArray<IdentifiedNode>,\n key: (node: IdentifiedNode) => string,\n): number[][] {\n const byKey = new Map<string, number[]>();\n nodes.forEach((node, index) => byKey.set(key(node), [...(byKey.get(key(node)) ?? []), index]));\n return [...byKey.values()].filter((nodeIndexes) => nodeIndexes.length > 1);\n}\n", "import { parse, type ArrayNode, type ObjectNode } from '@humanwhocodes/momoa';\nimport { escapeJsonPointerSegment } from './json-pointer';\nimport { compareCanonicalStrings } from './stable-order';\nimport { MAX_SOURCE_PARSER_DEPTH } from './source/source-preflight';\n\nexport type SourcePosition = { line: number; column: number; offset: number };\n\nexport type SourceSpan = { start: SourcePosition; end: SourcePosition };\n\nexport type DuplicateJsonKeyLocation = { pointer: string; key: string };\n\nexport type SourceMappedWorkflow = {\n value: unknown;\n nodeSpans: Array<SourceSpan | undefined>;\n duplicateKeys: DuplicateJsonKeyLocation[];\n};\n\nexport class DuplicateKeyLocationLimitError extends Error {\n readonly code = 'DUPLICATE_KEY_LOCATION_LIMIT';\n\n constructor() {\n super('Duplicate-key source location output exceeds its configured limit.');\n this.name = 'DuplicateKeyLocationLimitError';\n }\n}\n\n/** Caps pointer construction work, including candidates later coalesced to an existing location. */\nexport const MAX_DUPLICATE_KEY_LOCATIONS = 16_384;\n/** UTF-8 bytes across all candidate RFC 6901 pointers constructed for one document. */\nexport const MAX_DUPLICATE_KEY_POINTER_BYTES = 1_048_576;\n\nexport function parseWorkflowSource(workflowJson: string): SourceMappedWorkflow {\n const hasLeadingBom = workflowJson.charCodeAt(0) === 0xfeff;\n const source = hasLeadingBom ? workflowJson.slice(1) : workflowJson;\n const document = parse(source, { mode: 'json', ranges: true });\n const nodes = findNodesArray(document.body);\n\n return {\n // Keep momoa responsible for syntax and source metadata, but use the\n // platform JSON parser for values. momoa evaluates object members with\n // `object[key] = value`; a JSON key named `__proto__` would therefore\n // invoke Object.prototype's setter instead of becoming data.\n value: JSON.parse(source),\n nodeSpans: nodes?.elements.map((element) => toSourceSpan(element.value.loc, hasLeadingBom)) ?? [],\n duplicateKeys: findDuplicateJsonKeys(document.body),\n };\n}\n\nfunction findNodesArray(value: unknown): ArrayNode | undefined {\n if (!isObjectNode(value)) return undefined;\n const nodesMembers = value.members.filter((member) => memberName(member.name) === 'nodes');\n const lastMember = nodesMembers[nodesMembers.length - 1];\n return lastMember && isArrayNode(lastMember.value) ? lastMember.value : undefined;\n}\n\nconst MAX_DUPLICATE_KEY_SCAN_DEPTH = MAX_SOURCE_PARSER_DEPTH;\n\ntype ContainerNode = ArrayNode | ObjectNode;\ntype PointerPath = { parent?: PointerPath; segment: string; pointerBytes: number };\ntype PendingNode = { node: ContainerNode; pointer?: PointerPath; depth: number };\n\nfunction findDuplicateJsonKeys(root: unknown): DuplicateJsonKeyLocation[] {\n const results: DuplicateJsonKeyLocation[] = [];\n const reportedLocations = new Set<string>();\n const pending: PendingNode[] = isContainerNode(root)\n ? [{ node: root, depth: 0 }]\n : [];\n let duplicateLocationCount = 0;\n let duplicatePointerBytes = 0;\n\n while (pending.length > 0) {\n const current = pending.pop();\n if (!current || current.depth > MAX_DUPLICATE_KEY_SCAN_DEPTH) continue;\n\n if (isObjectNode(current.node)) {\n const seen = new Set<string>();\n const reportedDuplicates = new Set<string>();\n for (const member of current.node.members) {\n const key = memberName(member.name);\n if (key === undefined) continue;\n if (seen.has(key) && !reportedDuplicates.has(key)) {\n const pointerBytes = (current.pointer?.pointerBytes ?? 0) + pointerSegmentUtf8Bytes(key);\n if (\n duplicateLocationCount >= MAX_DUPLICATE_KEY_LOCATIONS\n || pointerBytes > MAX_DUPLICATE_KEY_POINTER_BYTES - duplicatePointerBytes\n ) {\n throw new DuplicateKeyLocationLimitError();\n }\n duplicateLocationCount += 1;\n duplicatePointerBytes += pointerBytes;\n const pointer = materializePointer(current.pointer, key);\n // The escaped final pointer segment is the key, so the pointer identifies this location.\n if (!reportedLocations.has(pointer)) {\n results.push({ pointer, key });\n reportedLocations.add(pointer);\n }\n reportedDuplicates.add(key);\n }\n seen.add(key);\n if (isContainerNode(member.value)) {\n pending.push({\n node: member.value,\n pointer: extendPointer(current.pointer, key),\n depth: current.depth + 1,\n });\n }\n }\n } else if (isArrayNode(current.node)) {\n current.node.elements.forEach((element, index) => {\n if (isContainerNode(element.value)) {\n pending.push({\n node: element.value,\n pointer: extendPointer(current.pointer, String(index)),\n depth: current.depth + 1,\n });\n }\n });\n }\n }\n\n return results.sort((a, b) => compareCanonicalStrings(a.pointer, b.pointer));\n}\n\nfunction materializePointer(parent: PointerPath | undefined, segment: string): string {\n const segments = [escapeJsonPointerSegment(segment)];\n for (let current = parent; current; current = current.parent) {\n segments.push(escapeJsonPointerSegment(current.segment));\n }\n return `/${segments.reverse().join('/')}`;\n}\n\nfunction extendPointer(parent: PointerPath | undefined, segment: string): PointerPath {\n return {\n parent,\n segment,\n pointerBytes: (parent?.pointerBytes ?? 0) + pointerSegmentUtf8Bytes(segment),\n };\n}\n\n/** Counts the slash and RFC 6901 escaped segment without building a pointer string. */\nfunction pointerSegmentUtf8Bytes(segment: string): number {\n let bytes = 1;\n for (let index = 0; index < segment.length; index += 1) {\n const code = segment.charCodeAt(index);\n if (code === 0x2f || code === 0x7e) {\n bytes += 2;\n } else if (code <= 0x7f) {\n bytes += 1;\n } else if (code <= 0x7ff) {\n bytes += 2;\n } else if (code >= 0xd800 && code <= 0xdbff && index + 1 < segment.length) {\n const next = segment.charCodeAt(index + 1);\n if (next >= 0xdc00 && next <= 0xdfff) {\n bytes += 4;\n index += 1;\n } else {\n bytes += 3;\n }\n } else {\n // Includes lone surrogates, which TextEncoder represents as U+FFFD.\n bytes += 3;\n }\n }\n return bytes;\n}\n\nfunction isContainerNode(value: unknown): value is ContainerNode {\n return isObjectNode(value) || isArrayNode(value);\n}\n\nfunction isObjectNode(value: unknown): value is ObjectNode {\n return typeof value === 'object' && value !== null && 'type' in value && value.type === 'Object';\n}\n\nfunction isArrayNode(value: unknown): value is ArrayNode {\n return typeof value === 'object' && value !== null && 'type' in value && value.type === 'Array';\n}\n\nfunction memberName(value: { type: string; value?: string; name?: string }): string | undefined {\n return value.type === 'String' ? value.value : value.name;\n}\n\nfunction toSourceSpan(\n location: { start: SourcePosition; end: SourcePosition },\n hasLeadingBom: boolean,\n): SourceSpan {\n const originalPosition = (position: SourcePosition): SourcePosition => hasLeadingBom\n ? { ...position, column: position.column + (position.line === 1 ? 1 : 0), offset: position.offset + 1 }\n : { ...position };\n return { start: originalPosition(location.start), end: originalPosition(location.end) };\n}\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { canonicalizeJson } from './canonical-json';\nimport { toJsonPointer } from './json-pointer';\nimport { exceedsNestingDepth, exceedsParameterBudget } from './workflow-budgets';\nimport { exceedsJsonDocumentDepth, MAX_SOURCE_PARSER_DEPTH } from './source/source-preflight';\nimport {\n collectParseDiagnostics,\n type MalformedNodeParametersLocation,\n type WorkflowParseDiagnostic,\n} from './workflow-diagnostics';\nimport { buildWorkflowGraph, type WorkflowGraph } from './workflow-graph';\nimport {\n DuplicateKeyLocationLimitError,\n parseWorkflowSource,\n type DuplicateJsonKeyLocation,\n type SourceSpan,\n} from './workflow-source-locations';\n\nexport { toJsonPointer };\nexport type { SourceSpan } from './workflow-source-locations';\n\nexport type WorkflowParseErrorCode =\n | 'INVALID_JSON'\n | 'MALFORMED_WORKFLOW'\n | 'WORKFLOW_TOO_LARGE'\n | 'WORKFLOW_TOO_COMPLEX';\n\n/**\n * Which budget or parser-safety boundary a `WORKFLOW_TOO_COMPLEX` rejection\n * actually violated. A closed\n * union \u2014 one member per rejection site below \u2014 so consumers (the scan\n * worker's error mapping in particular) can switch over it exhaustively\n * instead of substring-matching the human-readable `message`.\n */\nexport type WorkflowTooComplexCause =\n | 'NODE_LIMIT'\n | 'EDGE_LIMIT'\n | 'CONNECTION_DEPTH_LIMIT'\n | 'PARAMETER_COMPLEXITY_LIMIT'\n | 'DOCUMENT_DEPTH_LIMIT'\n | 'DUPLICATE_KEY_LOCATION_LIMIT';\n\nexport type NormalizedWorkflowNode = {\n id: string;\n name: string;\n type: string;\n typeVersion?: string | number;\n parameters: Record<string, unknown>;\n sourcePath: string;\n sourceSpan?: SourceSpan;\n};\n\nexport type NormalizedWorkflow = {\n name?: string;\n fingerprint: string;\n payloadBytes: number;\n nodeCount: number;\n nodes: NormalizedWorkflowNode[];\n connections: Record<string, unknown>;\n parseDiagnostics: WorkflowParseDiagnostic[];\n graph: WorkflowGraph;\n};\n\nexport type WorkflowParseResult =\n | { ok: true; workflow: NormalizedWorkflow }\n | { ok: false; code: 'WORKFLOW_TOO_COMPLEX'; cause: WorkflowTooComplexCause; message: string }\n | { ok: false; code: Exclude<WorkflowParseErrorCode, 'WORKFLOW_TOO_COMPLEX'>; message: string };\n\nexport type WorkflowParseOptions = {\n maxBytes: number;\n maxNodes: number;\n maxConnectionDepth: number;\n maxParameterDepth: number;\n maxParameterLeaves: number;\n maxEdges: number;\n};\n\n/** Frozen locally to keep scanner-core browser-safe and free of a contracts runtime dependency. */\nexport const DEFAULT_WORKFLOW_PARSE_OPTIONS: WorkflowParseOptions = Object.freeze({\n maxBytes: 1_536_000,\n maxNodes: 5_000,\n maxEdges: 10_000,\n maxConnectionDepth: 64,\n maxParameterDepth: 64,\n maxParameterLeaves: 10_000,\n});\n\nexport function parseWorkflowJson(\n workflowJson: string,\n options: Partial<WorkflowParseOptions> = {},\n): WorkflowParseResult {\n const effectiveOptions: WorkflowParseOptions = {\n maxBytes: options.maxBytes ?? DEFAULT_WORKFLOW_PARSE_OPTIONS.maxBytes,\n maxNodes: options.maxNodes ?? DEFAULT_WORKFLOW_PARSE_OPTIONS.maxNodes,\n maxConnectionDepth: options.maxConnectionDepth ?? DEFAULT_WORKFLOW_PARSE_OPTIONS.maxConnectionDepth,\n maxParameterDepth: options.maxParameterDepth ?? DEFAULT_WORKFLOW_PARSE_OPTIONS.maxParameterDepth,\n maxParameterLeaves: options.maxParameterLeaves ?? DEFAULT_WORKFLOW_PARSE_OPTIONS.maxParameterLeaves,\n maxEdges: options.maxEdges ?? DEFAULT_WORKFLOW_PARSE_OPTIONS.maxEdges,\n };\n const byteLength = new TextEncoder().encode(workflowJson).length;\n if (byteLength > effectiveOptions.maxBytes) {\n return { ok: false, code: 'WORKFLOW_TOO_LARGE', message: 'Workflow JSON exceeds the configured payload limit.' };\n }\n if (exceedsJsonDocumentDepth(workflowJson, MAX_SOURCE_PARSER_DEPTH)) {\n return workflowTooComplex('document depth limit', 'DOCUMENT_DEPTH_LIMIT');\n }\n\n let parsed: unknown;\n let nodeSpans: Array<SourceSpan | undefined>;\n let duplicateKeys: DuplicateJsonKeyLocation[];\n try {\n ({ value: parsed, nodeSpans, duplicateKeys } = parseWorkflowSource(workflowJson));\n } catch (error) {\n if (error instanceof DuplicateKeyLocationLimitError) {\n return workflowTooComplex('duplicate-key source location output limit', 'DUPLICATE_KEY_LOCATION_LIMIT');\n }\n return { ok: false, code: 'INVALID_JSON', message: 'Workflow JSON is not valid JSON.' };\n }\n\n if (!isRecord(parsed)) return malformedWorkflow('Workflow JSON must be an object.');\n const nodes = parsed.nodes;\n const connections = parsed.connections;\n if (!Array.isArray(nodes) || !isRecord(connections)) {\n return malformedWorkflow('Workflow JSON must include nodes array and connections object.');\n }\n if (nodes.length > effectiveOptions.maxNodes) {\n return workflowTooComplex('node limit', 'NODE_LIMIT');\n }\n if (exceedsNestingDepth(connections, effectiveOptions.maxConnectionDepth)) {\n return workflowTooComplex('connection nesting limit', 'CONNECTION_DEPTH_LIMIT');\n }\n\n const normalizedNodes: NormalizedWorkflowNode[] = [];\n const malformedParameters: MalformedNodeParametersLocation[] = [];\n for (const [nodeIndex, node] of nodes.entries()) {\n if (!isRecord(node) || typeof node.name !== 'string' || typeof node.type !== 'string') {\n return malformedWorkflow('Each workflow node must include string name and type fields.');\n }\n const parameters = isRecord(node.parameters) ? node.parameters : {};\n if ('parameters' in node && !isRecord(node.parameters)) {\n malformedParameters.push({ nodeIndex, pointer: toJsonPointer(['nodes', nodeIndex, 'parameters']) });\n }\n if (exceedsParameterBudget(parameters, {\n maxDepth: effectiveOptions.maxParameterDepth,\n maxLeaves: effectiveOptions.maxParameterLeaves,\n })) return workflowTooComplex('parameter complexity limit', 'PARAMETER_COMPLEXITY_LIMIT');\n\n normalizedNodes.push({\n id: typeof node.id === 'string' ? node.id : node.name,\n name: node.name,\n type: node.type,\n typeVersion: normalizeTypeVersion(node.typeVersion),\n parameters,\n sourcePath: toJsonPointer(['nodes', nodeIndex]),\n ...(nodeSpans[nodeIndex] ? { sourceSpan: nodeSpans[nodeIndex] } : {}),\n });\n }\n\n const graph = buildWorkflowGraph(normalizedNodes, connections, { maxEdges: effectiveOptions.maxEdges });\n if (graph.limitExceeded) return workflowTooComplex('edge limit', 'EDGE_LIMIT');\n\n return {\n ok: true,\n workflow: {\n ...(typeof parsed.name === 'string' ? { name: parsed.name } : {}),\n fingerprint: fingerprintJson(parsed),\n payloadBytes: byteLength,\n nodeCount: normalizedNodes.length,\n nodes: normalizedNodes,\n connections,\n parseDiagnostics: collectParseDiagnostics(normalizedNodes, duplicateKeys, malformedParameters),\n graph,\n },\n };\n}\n\nfunction malformedWorkflow(message: string): WorkflowParseResult {\n return { ok: false, code: 'MALFORMED_WORKFLOW', message };\n}\n\nfunction workflowTooComplex(limit: string, cause: WorkflowTooComplexCause): WorkflowParseResult {\n return {\n ok: false,\n code: 'WORKFLOW_TOO_COMPLEX',\n cause,\n message: `Workflow JSON exceeds the configured ${limit}.`,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction normalizeTypeVersion(value: unknown): string | number | undefined {\n return typeof value === 'string' || typeof value === 'number' ? value : undefined;\n}\n\nexport function fingerprintJson(value: unknown): string {\n return bytesToHex(sha256(new TextEncoder().encode(canonicalizeJson(value))));\n}\n", "import {\n DEFAULT_SCANNER_LIMITS,\n SCANNER_RESULT_SCHEMA_VERSION,\n toWorkflowParseOptions,\n} from '@hub/contracts';\nimport { scanWorkflowCore } from '@hub/scanner-core/engine';\nimport { redactScanPresentation } from '@hub/scanner-core/presentation-redaction';\nimport { SCANNER_VERSION } from '@hub/scanner-core/scanner-version';\nimport type { AnalysisDiagnostic, CanonicalScanFinding, ScanSummary } from '@hub/scanner-core/policy';\nimport { resolvePolicyProfile } from '@hub/scanner-core/policies/profile';\nimport { attachFindingSourceSpans } from '@hub/scanner-core/result/finding-source-spans';\nimport { parseWorkflowJson, type WorkflowParseErrorCode } from '@hub/scanner-core/workflow';\n\nexport const CLI_SCHEMA_VERSION = 'n8n-scan-v1' as const;\nexport const CLI_VERSION = '0.1.0' as const;\nexport const CLI_PROFILE = 'beta-default' as const;\nexport type ScanErrorCode = WorkflowParseErrorCode | 'INPUT_READ_FAILED' | 'INTERNAL';\n\nexport type ScanDocument = ScanSuccessDocument | ScanErrorDocument;\n\ntype ScanSuccessDocument = {\n schemaVersion: typeof CLI_SCHEMA_VERSION;\n scannerResultSchemaVersion: typeof SCANNER_RESULT_SCHEMA_VERSION;\n scannerVersion: typeof SCANNER_VERSION;\n profile: typeof CLI_PROFILE;\n input: string;\n ok: true;\n workflow: {\n name: string | null;\n fingerprint: string;\n nodeCount: number;\n payloadBytes: number;\n };\n analysis: { status: string; diagnostics: AnalysisDiagnostic[] };\n summary: ScanSummary;\n findings: CanonicalScanFinding[];\n stats: { policyFailures: number; rejectedFindings: number; collapsedFindings: number };\n};\n\ntype ScanErrorDocument = {\n schemaVersion: typeof CLI_SCHEMA_VERSION;\n scannerVersion: typeof SCANNER_VERSION;\n profile: typeof CLI_PROFILE;\n input: string;\n ok: false;\n error: { code: ScanErrorCode; message: string };\n};\n\nexport function scanText(input: string, workflowJson: string): ScanDocument {\n const parsed = parseWorkflowJson(workflowJson, toWorkflowParseOptions(DEFAULT_SCANNER_LIMITS));\n if (!parsed.ok) return errorDocument(input, parsed.code, parsed.message);\n\n const profile = resolvePolicyProfile(CLI_PROFILE);\n if (!profile.ok) return errorDocument(input, 'INTERNAL', 'The configured scanner profile is unavailable.');\n\n try {\n const core = scanWorkflowCore(parsed.workflow, {\n policies: profile.createPolicies(),\n ruleCatalog: profile.ruleCatalog,\n });\n const attached = attachFindingSourceSpans(core.findings, parsed.workflow.nodes);\n const alreadyReported = core.diagnostics.some((diagnostic) => diagnostic.code === 'SOURCE_SPAN_UNAVAILABLE');\n const diagnostics = attached.unresolvedCount > 0 && !alreadyReported\n ? [...core.diagnostics, { code: 'SOURCE_SPAN_UNAVAILABLE', category: 'SOURCE' } as const]\n : core.diagnostics;\n const analysisStatus = attached.unresolvedCount > 0 && core.analysisStatus === 'COMPLETE'\n ? 'DEGRADED'\n : core.analysisStatus;\n return redactScanPresentation({\n schemaVersion: CLI_SCHEMA_VERSION,\n scannerResultSchemaVersion: SCANNER_RESULT_SCHEMA_VERSION,\n scannerVersion: SCANNER_VERSION,\n profile: CLI_PROFILE,\n input,\n ok: true,\n workflow: {\n name: parsed.workflow.name ?? null,\n fingerprint: parsed.workflow.fingerprint,\n nodeCount: parsed.workflow.nodeCount,\n payloadBytes: parsed.workflow.payloadBytes,\n },\n analysis: { status: analysisStatus, diagnostics },\n summary: core.summary,\n findings: attached.findings,\n stats: {\n policyFailures: core.policyFailureCount,\n rejectedFindings: core.rejectedCount,\n collapsedFindings: core.collapsedCount,\n },\n });\n } catch {\n return errorDocument(input, 'INTERNAL', 'The scanner failed while analyzing the workflow.');\n }\n}\n\nexport function versionDocument(): Record<string, string> {\n return {\n schemaVersion: CLI_SCHEMA_VERSION,\n cliVersion: CLI_VERSION,\n scannerVersion: SCANNER_VERSION,\n profile: CLI_PROFILE,\n mode: 'offline',\n };\n}\n\nfunction errorDocument(\n input: string,\n code: ScanErrorCode,\n message: string,\n): ScanErrorDocument {\n return {\n schemaVersion: CLI_SCHEMA_VERSION,\n scannerVersion: SCANNER_VERSION,\n profile: CLI_PROFILE,\n input,\n ok: false,\n error: { code, message },\n };\n}\n", "import { betaDefaultRuleCatalog, betaHardenedRuleCatalog, type RuleCatalogEntry } from '../policy/rule-catalog';\n\n/**\n * SARIF `properties.tags` for a rule's CWE and OWASP Agentic metadata.\n *\n * This lives in scanner-core, not beside an emitter, because there are two\n * emitters \u2014 the browser report and the CLI \u2014 and only one of them had the tags\n * when they were written separately. The same finding carried its CWE in the\n * place a person reads it and lost it in the place a machine reads it.\n *\n * The CWE form matters. GitHub code scanning surfaces the CWE badge for the\n * `external/cwe/cwe-###` tag that CodeQL emits, zero-padded to three digits; a\n * plain `CWE-78` string is accepted, displayed nowhere, and looks correct in a\n * diff. There is no equivalent published convention for the OWASP Agentic Top\n * 10, so that tag is a readable slug and is not claimed to do anything in the\n * GitHub UI.\n */\nconst ruleByPolicyId: ReadonlyMap<string, RuleCatalogEntry> = new Map(\n [...betaDefaultRuleCatalog, ...betaHardenedRuleCatalog].map((rule) => [rule.policyId, rule]),\n);\n\nexport const RULES_DOCUMENTATION_URI = 'https://github.com/jitwark/n8n-Secureflow/blob/main/docs/scanner/policy-inventory.md';\n\n/** GitHub preserves the underscores in the per-rule `### \\`RULE_ID\\`` headings. */\nexport function sarifHelpUriFor(policyId: string): string {\n return `${RULES_DOCUMENTATION_URI}#${policyId.toLowerCase()}`;\n}\n\nexport function cweTag(cweId: string): string {\n return `external/cwe/cwe-${cweId.slice('CWE-'.length).padStart(3, '0')}`;\n}\n\nexport function owaspAgenticTag(category: string): string {\n return `owasp-agentic/${category.toLowerCase().replace(/\\s+/g, '-')}`;\n}\n\n/**\n * Tags for a policy ID, or `undefined` when there are none.\n *\n * `undefined` rather than `[]` on purpose, in both the unknown-policy case and\n * the deliberately-unmapped one (`UNAPPROVED_DOMAIN`). An empty `tags` array in\n * a published SARIF document reads as \"reviewed, and no CWE applies\", which is\n * a claim; absence is not.\n */\nexport function sarifTagsFor(policyId: string): string[] | undefined {\n const rule = ruleByPolicyId.get(policyId);\n if (!rule) return undefined;\n const tags = [...rule.cweIds.map(cweTag), ...(rule.owaspAgenticIds ?? []).map(owaspAgenticTag)];\n return tags.length > 0 ? tags : undefined;\n}\n", "import { compareCanonicalStrings } from '../stable-order.js';\nimport { sarifHelpUriFor, sarifTagsFor } from './sarif-tags.js';\nimport type { CanonicalScanFinding, ScanSeverity } from '../policy/policy.js';\n\n/**\n * Shared SARIF 2.1.0 document assembly for the two CLIs that scan a batch of\n * `CanonicalScanFinding`s located by source span: the pipeline-workspace\n * `pipeline/cli/` adapter and the standalone `packages/scanner-cli` package.\n * Before this module existed, both had their own copy of the same\n * rules/results/notifications assembly, and only one of the two ever grew a\n * `--format sarif` flag \u2014 the exact way `sarif-tags.ts` describes the CWE tag\n * logic itself drifting between emitters. Only the tag lookup is delegated\n * here rather than rewritten.\n *\n * The browser report (`app/src/scanner/report/report-sarif.ts`) is\n * deliberately not built on this: it redacts text, reports logical locations\n * instead of physical source spans, and adds finding fingerprints and a risk\n * grade for a single workflow. Those needs are particular to one caller, so\n * folding them into a \"generic\" builder would inflate this shared shape to\n * serve a consumer that does not share it \u2014 it already reuses `sarifTagsFor`,\n * which was the actual duplication risk.\n */\n\nconst SEVERITY_ORDER: Record<ScanSeverity, number> = { CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3, INFO: 4 };\n\nexport type SarifFindingEntry = { input: string; finding: CanonicalScanFinding };\n\nexport type SarifNotification = {\n descriptor: { id: string };\n message: { text: string };\n properties?: Record<string, unknown>;\n};\n\nexport type SarifDocumentInput = {\n toolName: string;\n toolVersion: string;\n informationUri: string;\n findings: readonly SarifFindingEntry[];\n /** Pre-sorted by the caller: each caller's notification shape carries different fields to order by. */\n notifications?: readonly SarifNotification[];\n executionSuccessful: boolean;\n};\n\nexport function buildSarifDocument(input: SarifDocumentInput): Record<string, unknown> {\n const findings = [...input.findings].sort(compareSarifFindings);\n return {\n version: '2.1.0',\n $schema: 'https://json.schemastore.org/sarif-2.1.0.json',\n runs: [{\n tool: { driver: {\n name: input.toolName, version: input.toolVersion, informationUri: input.informationUri,\n rules: sarifRules(findings),\n } },\n results: findings.map(({ input: source, finding }) => sarifFinding(source, finding)),\n invocations: [{\n executionSuccessful: input.executionSuccessful,\n toolExecutionNotifications: [...(input.notifications ?? [])],\n }],\n }],\n };\n}\n\nfunction sarifRules(findings: readonly SarifFindingEntry[]): Record<string, unknown>[] {\n const rules = new Map<string, CanonicalScanFinding>();\n for (const { finding } of findings) if (!rules.has(finding.policyId)) rules.set(finding.policyId, finding);\n return [...rules.entries()].sort(([left], [right]) => compareCanonicalStrings(left, right)).map(([id, finding]) => {\n const tags = sarifTagsFor(id);\n return {\n id,\n shortDescription: { text: finding.title },\n helpUri: sarifHelpUriFor(id),\n ...(tags ? { properties: { tags } } : {}),\n };\n });\n}\n\nfunction sarifFinding(input: string, finding: CanonicalScanFinding): Record<string, unknown> {\n const sourceSpan = finding.location.sourceSpan;\n const locations = sourceSpan ? [{\n physicalLocation: {\n artifactLocation: { uri: input },\n region: {\n startLine: sourceSpan.start.line,\n startColumn: sourceSpan.start.column,\n endLine: sourceSpan.end.line,\n endColumn: sourceSpan.end.column,\n charOffset: sourceSpan.start.offset,\n charLength: Math.max(0, sourceSpan.end.offset - sourceSpan.start.offset),\n },\n },\n }] : undefined;\n return {\n ruleId: finding.policyId,\n level: sarifLevel(finding.severity),\n message: { text: finding.title },\n ...(locations ? { locations } : {}),\n };\n}\n\nfunction compareSarifFindings(left: SarifFindingEntry, right: SarifFindingEntry): number {\n return compareCanonicalStrings(left.input, right.input) ||\n SEVERITY_ORDER[left.finding.severity] - SEVERITY_ORDER[right.finding.severity] ||\n compareCanonicalStrings(left.finding.policyId, right.finding.policyId) ||\n compareCanonicalStrings(locationKey(left.finding), locationKey(right.finding)) ||\n compareCanonicalStrings(left.finding.title, right.finding.title) ||\n compareCanonicalStrings(left.finding.message, right.finding.message);\n}\n\nfunction locationKey(finding: CanonicalScanFinding): string {\n const location = finding.location;\n const span = location.sourceSpan;\n return [\n location.nodeId ?? '', location.nodeName ?? '', location.path ?? '',\n span ? `${span.start.line}:${span.start.column}:${span.start.offset}:${span.end.line}:${span.end.column}:${span.end.offset}` : '',\n ].join('|');\n}\n\nfunction sarifLevel(severity: string): 'error' | 'warning' | 'note' {\n if (severity === 'CRITICAL' || severity === 'HIGH') return 'error';\n if (severity === 'MEDIUM') return 'warning';\n return 'note';\n}\n", "import { buildSarifDocument, type SarifNotification } from '@hub/scanner-core/report/sarif-document';\nimport { CLI_VERSION, type ScanDocument } from './scan.js';\n\nconst TOOL_NAME = 'n8n-scan';\nconst INFORMATION_URI = 'https://github.com/jitwark/n8n-Secureflow';\n\n/**\n * SARIF for the standalone package: one input, so there is no batch to sort\n * and at most one notification. Document assembly (rules, CWE tags, sorted\n * results) is shared with the pipeline-workspace CLI through\n * @hub/scanner-core/report/sarif-document \u2014 see that module's header comment\n * for why the two agree on shape and the browser report does not.\n */\nexport function toSarifDocument(document: ScanDocument): Record<string, unknown> {\n if (!document.ok) {\n return buildSarifDocument({\n toolName: TOOL_NAME,\n toolVersion: CLI_VERSION,\n informationUri: INFORMATION_URI,\n findings: [],\n notifications: [errorNotification(document)],\n executionSuccessful: false,\n });\n }\n\n return buildSarifDocument({\n toolName: TOOL_NAME,\n toolVersion: CLI_VERSION,\n informationUri: INFORMATION_URI,\n findings: document.findings.map((finding) => ({ input: document.input, finding })),\n executionSuccessful: true,\n });\n}\n\nfunction errorNotification(document: Extract<ScanDocument, { ok: false }>): SarifNotification {\n return {\n descriptor: { id: document.error.code },\n message: { text: `${document.input}: ${document.error.message}` },\n properties: { input: document.input, code: document.error.code },\n };\n}\n", "import { HELP_TEXT } from './help.js';\nimport { readWorkflowInput, type CliStdin } from './input.js';\nimport {\n CLI_SCHEMA_VERSION,\n scanText,\n versionDocument,\n type ScanDocument,\n} from './scan.js';\nimport { toSarifDocument } from './sarif.js';\nimport { SCANNER_VERSION } from '@hub/scanner-core/scanner-version';\n\nconst CLI_FORMATS = ['json', 'sarif'] as const;\ntype CliFormat = (typeof CLI_FORMATS)[number];\n\nexport type CliRunResult = {\n exitCode: 0 | 1 | 2 | 3 | 4;\n stdout: string;\n stderr: string;\n};\n\nexport type CliRunOptions = { stdin?: CliStdin };\n\nexport async function runCli(argv: readonly string[], options: CliRunOptions = {}): Promise<CliRunResult> {\n const command = parseArguments(argv);\n if (command.kind === 'help') return { exitCode: 0, stdout: HELP_TEXT, stderr: '' };\n if (command.kind === 'version') {\n const output = command.json ? formatJson(versionDocument()) : `sfscanner 0.1.0 (${SCANNER_VERSION})\\n`;\n return { exitCode: 0, stdout: output, stderr: '' };\n }\n if (command.kind === 'usage') return { exitCode: 2, stdout: '', stderr: `${command.message}\\n\\n${HELP_TEXT}` };\n\n let workflowJson: string;\n try {\n workflowJson = await readWorkflowInput(command.input, options.stdin);\n } catch (error) {\n const tooLarge = error instanceof RangeError && error.message === 'OVERSIZED';\n return {\n exitCode: 3,\n stdout: formatOutput(inputError(command.input, tooLarge ? 'WORKFLOW_TOO_LARGE' : 'INPUT_READ_FAILED'), command.format),\n stderr: '',\n };\n }\n\n const document = scanText(command.input, workflowJson);\n return {\n exitCode: exitCodeFor(document),\n stdout: formatOutput(document, command.format),\n stderr: '',\n };\n}\n\ntype ParsedCommand =\n | { kind: 'help' }\n | { kind: 'version'; json: boolean }\n | { kind: 'scan'; input: string; format: CliFormat }\n | { kind: 'usage'; message: string };\n\nfunction parseArguments(argv: readonly string[]): ParsedCommand {\n if (argv.length === 1 && argv[0] === '--help') return { kind: 'help' };\n if (argv[0] === '--version') {\n if (argv.length === 1) return { kind: 'version', json: false };\n if (argv.length === 2 && argv[1] === '--json') return { kind: 'version', json: true };\n return { kind: 'usage', message: 'Usage: sfscanner --version [--json]' };\n }\n\n const afterCommand = argv[0] === 'scan' ? argv.slice(1) : argv;\n const extracted = extractFormat(afterCommand);\n if ('error' in extracted) return { kind: 'usage', message: extracted.error };\n const { rest: inputs, format } = extracted;\n if (inputs.length !== 1 || !inputs[0] || inputs[0].startsWith('-') && inputs[0] !== '-') {\n return { kind: 'usage', message: 'Exactly one workflow input is required. Use a file path or - for stdin.' };\n }\n if (inputs[0] === '--help') return { kind: 'help' };\n return { kind: 'scan', input: inputs[0], format };\n}\n\n/**\n * Pulls `--format <json|sarif>` out of the input arguments wherever it\n * appears (before or after the file/stdin token), so the single-input check\n * below never sees it and mistakes it for a second, ambiguous input.\n */\nfunction extractFormat(args: readonly string[]): { rest: string[]; format: CliFormat } | { error: string } {\n const rest: string[] = [];\n let format: CliFormat = 'json';\n for (let index = 0; index < args.length; index++) {\n const arg = args[index]!;\n if (arg !== '--format') {\n rest.push(arg);\n continue;\n }\n const value = args[index + 1];\n if (!value || !(CLI_FORMATS as readonly string[]).includes(value)) {\n return { error: `--format must be one of: ${CLI_FORMATS.join(', ')}` };\n }\n format = value as CliFormat;\n index += 1;\n }\n return { rest, format };\n}\n\nfunction formatOutput(document: ScanDocument, format: CliFormat): string {\n return format === 'sarif' ? formatJson(toSarifDocument(document)) : formatJson(document);\n}\n\nfunction exitCodeFor(document: ScanDocument): 0 | 1 | 3 {\n if (!document.ok) return 3;\n return document.findings.length > 0 ? 1 : 0;\n}\n\nfunction inputError(input: string, code: 'INPUT_READ_FAILED' | 'WORKFLOW_TOO_LARGE' = 'INPUT_READ_FAILED'): ScanDocument {\n return {\n schemaVersion: CLI_SCHEMA_VERSION,\n scannerVersion: SCANNER_VERSION,\n profile: 'beta-default',\n input,\n ok: false,\n error: {\n code,\n message: code === 'WORKFLOW_TOO_LARGE'\n ? 'Workflow exceeds maximum byte limit.'\n : 'Unable to read workflow input.',\n },\n };\n}\n\nfunction formatJson(value: unknown): string {\n return `${JSON.stringify(value, null, 2)}\\n`;\n}\n", "import { createHash } from 'node:crypto';\nimport { canonicalizeJson } from '@hub/scanner-core/canonical-json';\n\nexport const SCAN_CONFIG_SCHEMA_V2 = 'n8n-scan-config-v2' as const;\nexport type ScanFormatV2 = 'json' | 'ndjson' | 'sarif' | 'table';\nexport type ScanSeverityV2 = 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';\nexport type ScanConfigV2 = Readonly<{\n schemaVersion: typeof SCAN_CONFIG_SCHEMA_V2;\n format?: ScanFormatV2;\n profile?: string;\n output?: string;\n inputs?: readonly string[];\n configPath?: string;\n failOn?: ScanSeverityV2;\n requireComplete?: boolean;\n concurrency?: number;\n rules?: string;\n catalogue?: string;\n limits?: string;\n target?: string;\n include?: readonly string[];\n exclude?: readonly string[];\n approvedDomains?: readonly string[];\n allowUnsignedDevelopmentRules?: boolean;\n noColor?: boolean;\n}>;\n\nexport const ADMITTED_PROFILE_V2 = Object.freeze({ id: 'beta-default', version: '2.0.0', digest: '3ca5d69db2554383e22c44afe507cc98e381ea58a7e42aaac0ee8f7497fb4f44' });\n\n/**\n * The profile spellings a caller may write, and the one place they are listed. Both the\n * config loader and the MCP tool read this, so a profile cannot be admitted on one\n * surface and refused on the other; the bare id and its `id@version` pin are the same\n * admission, and both canonicalize to `ADMITTED_PROFILE_V2.id`.\n */\nexport const ADMITTED_PROFILE_SPECIFIERS_V2: readonly string[] = Object.freeze([\n ADMITTED_PROFILE_V2.id,\n `${ADMITTED_PROFILE_V2.id}@${ADMITTED_PROFILE_V2.version}`,\n]);\n\nexport function isAdmittedProfileSpecifierV2(value: unknown): value is string {\n return typeof value === 'string' && ADMITTED_PROFILE_SPECIFIERS_V2.includes(value);\n}\nexport const BUILTIN_AUTHORITIES_V2 = Object.freeze({\n profile: ADMITTED_PROFILE_V2,\n rules: Object.freeze({ id: 'scanner-core-builtins', version: '2.0.0', digest: 'a36d00564bbf8e8c38f05820480782cdc53fdbd3712558850066c4e3f5c3413d', signatureStatus: 'VERIFIED' as const }),\n semantics: Object.freeze({ id: 'scanner-core-builtins', version: '2.2.0', digest: 'bc6fdecc34e460b5b01973ef7a8ce06b27b9b100ae03b480110f11f2a63ac328' }),\n limits: Object.freeze({ schemaVersion: 'scanner-limits-v2' as const, digest: 'fca787753ca88f71cf0d174427f4ac730a7aef1c823aaf73aa1ea72af92b4077' }),\n});\nexport const PROFILE_MANIFEST_DIGEST_V2 = ADMITTED_PROFILE_V2.digest;\nexport const BUILTIN_RULESET_AUTHORITY_V2 = BUILTIN_AUTHORITIES_V2.rules;\nexport const BUILTIN_SEMANTICS_AUTHORITY_V2 = BUILTIN_AUTHORITIES_V2.semantics;\nexport const BUILTIN_LIMITS_AUTHORITY_V2 = BUILTIN_AUTHORITIES_V2.limits;\nexport const RULE_PACK_DIGEST_V2 = BUILTIN_RULESET_AUTHORITY_V2.digest;\nexport const SEMANTIC_CATALOGUE_DIGEST_V2 = BUILTIN_SEMANTICS_AUTHORITY_V2.digest;\n\n/**\n * One tool identity for every machine surface: the JSON/NDJSON scan envelopes and the\n * rules/explain/profiles metadata documents. The digest folds the admitted engine, profile,\n * ruleset, and semantics authorities, so a re-pin moves every surface together instead of\n * leaving a frozen literal behind on one of them.\n */\nexport const CLI_VERSION_V2 = '0.1.0' as const;\nexport type CliToolIdentityV2 = Readonly<{ name: 'n8n-scan'; version: string; buildDigest: string }>;\nexport const CLI_TOOL_V2: CliToolIdentityV2 = Object.freeze({\n name: 'n8n-scan',\n version: CLI_VERSION_V2,\n buildDigest: createHash('sha256').update(canonicalizeJson({\n engine: 'secureflow-scanner', version: '2.0.0', profile: ADMITTED_PROFILE_V2,\n ruleset: BUILTIN_RULESET_AUTHORITY_V2.digest, semantics: BUILTIN_SEMANTICS_AUTHORITY_V2.digest,\n })).digest('hex'),\n});\n\nexport const DEFAULT_SCAN_CONFIG_V2: ScanConfigV2 = Object.freeze({\n schemaVersion: SCAN_CONFIG_SCHEMA_V2,\n format: 'json', profile: ADMITTED_PROFILE_V2.id, failOn: 'INFO', requireComplete: false, concurrency: 1,\n rules: 'builtin', catalogue: 'builtin', limits: 'builtin',\n include: Object.freeze(['**/*.json']), exclude: Object.freeze(['.git/**', 'node_modules/**']),\n approvedDomains: Object.freeze([]),\n allowUnsignedDevelopmentRules: false, noColor: false,\n});\n\nexport const SCAN_CONFIG_V2_FIELDS = Object.freeze([\n 'schemaVersion', 'format', 'profile', 'output', 'inputs', 'configPath', 'failOn', 'requireComplete', 'concurrency',\n 'rules', 'catalogue', 'limits', 'target', 'include', 'exclude', 'approvedDomains',\n 'allowUnsignedDevelopmentRules', 'noColor',\n] as const);\nexport const SCAN_CONFIG_V2_MAX_STRING = 4096;\nexport const SCAN_CONFIG_V2_MAX_PATTERNS = 1024;\nexport const SCAN_CONFIG_V2_MAX_CONCURRENCY = 16;\nexport const SCAN_CONFIG_V2_MAX_DOMAINS = 1_000;\nexport const DOMAIN_V2 = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;\nexport function isApprovedDomainV2(value: unknown): value is string {\n return typeof value === 'string' && DOMAIN_V2.test(value);\n}\n", "import { posix, win32 } from 'node:path';\n\nconst CONTROL = /[\\u0000-\\u001f\\u007f]/u;\nconst SCHEME = /^[a-z][a-z\\d+.-]*:/iu;\nconst DRIVE = /^[a-z]:\\//iu;\nconst MAX_PATH = 4096;\n\n/** Normalizes backslashes before classifying, so a Windows drive path is absolute in both forms. */\nexport function isAbsoluteAdmittedPathV2(value: string): boolean {\n const normalized = value.replaceAll('\\\\', '/');\n if (normalized.startsWith('//')) return false; // UNC and protocol-relative are not local absolutes\n return normalized.startsWith('/') || DRIVE.test(normalized);\n}\n\nexport function isAdmittedLocalPath(value: unknown): value is string {\n return admitLocal(value, false) !== undefined;\n}\n\nexport function isAdmittedRelativePath(value: unknown): value is string {\n return admitLocal(value, true) !== undefined;\n}\n\nexport function normalizeAdmittedPathV2(value: unknown, relativeOnly = false): string | undefined {\n return admitLocal(value, relativeOnly);\n}\n\nfunction admitLocal(value: unknown, relativeOnly: boolean): string | undefined {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_PATH || CONTROL.test(value)) return undefined;\n const normalized = value.replaceAll('\\\\', '/');\n if (normalized.startsWith('//')) return undefined;\n const drive = /^([a-z]):(?:\\/|$)/iu.exec(normalized);\n if (SCHEME.test(normalized) && drive === null) return undefined;\n const absolute = drive !== null || normalized.startsWith('/');\n if (relativeOnly && absolute) return undefined;\n const body = drive === null ? normalized : normalized.slice(2);\n const parts: string[] = [];\n for (const part of body.split('/')) {\n if (part === '' || part === '.') continue;\n if (part === '..') return undefined;\n parts.push(part);\n }\n if (drive !== null) return parts.length === 0 ? `${drive[1]!.toUpperCase()}:/` : `${drive[1]!.toUpperCase()}:/${parts.join('/')}`;\n if (normalized.startsWith('/')) return parts.length === 0 ? '/' : `/${parts.join('/')}`;\n if (relativeOnly && parts.length === 0) return undefined;\n return parts.length === 0 ? '.' : parts.join('/');\n}\n\nexport function admittedLabelV2(raw: string, baseDirectory: string): string {\n const normalized = normalizeAdmittedPathV2(raw) ?? 'input';\n if (!isAbsoluteAdmittedPathV2(normalized)) return normalized;\n const base = normalizeAdmittedPathV2(baseDirectory) ?? '.';\n if (isAbsoluteAdmittedPathV2(base)) {\n const relative = relativeAdmitted(base, normalized);\n if (relative !== undefined && relative !== '..'\n && !relative.startsWith('../') && !relative.startsWith('/')\n && !isAbsoluteAdmittedPathV2(relative)) return relative;\n }\n const parts = normalized.split('/');\n return parts[parts.length - 1] || 'input';\n}\n\nexport function toFsPathV2(baseDirectory: string, normalized: string): string {\n if (isAbsoluteAdmittedPathV2(normalized)) return normalized;\n const base = baseDirectory.replaceAll('\\\\', '/');\n if (base === '/' || /^[a-z]:\\/$/iu.test(base)) return `${base}${normalized}`;\n const trimmed = base.replace(/\\/+$/u, '');\n return trimmed === '' || trimmed === '.' ? normalized : `${trimmed}/${normalized}`;\n}\n\nexport function isWithinBaseV2(target: string, baseDirectory: string): boolean {\n const targetPath = normalizeAdmittedPathV2(target);\n const base = normalizeAdmittedPathV2(baseDirectory);\n if (targetPath === undefined || base === undefined\n || !isAbsoluteAdmittedPathV2(targetPath) || !isAbsoluteAdmittedPathV2(base)) return false;\n const relative = relativeAdmitted(base, targetPath);\n return relative !== undefined && relative !== '..'\n && !relative.startsWith('../') && !relative.startsWith('/')\n && !isAbsoluteAdmittedPathV2(relative);\n}\n\nfunction relativeAdmitted(base: string, target: string): string | undefined {\n try {\n if (/^[a-z]:\\//iu.test(base) || /^[a-z]:\\//iu.test(target)) {\n return win32.relative(base.replaceAll('/', '\\\\'), target.replaceAll('/', '\\\\')).replaceAll('\\\\', '/');\n }\n return posix.relative(base, target);\n } catch { return undefined; }\n}\n", "import { ADMITTED_PROFILE_V2, isAdmittedProfileSpecifierV2, isApprovedDomainV2, type ScanConfigV2, type ScanSeverityV2 } from './contracts.js';\nimport { isAdmittedLocalPath, isAdmittedRelativePath, normalizeAdmittedPathV2 } from './path-admission.js';\nimport type { V2CommandName } from './help.js';\n\nexport type CliFormatV2 = 'json' | 'ndjson' | 'sarif' | 'table';\nexport type CliProfileV2 = typeof ADMITTED_PROFILE_V2.id;\nexport type CliTargetEnumV2 = 'UNKNOWN' | 'COMMUNITY' | 'ENTERPRISE' | 'CLOUD' | 'SELF_HOSTED' | 'OWNER' | 'ADMIN' | 'MEMBER' | 'LEGACY' | 'NATIVE';\nexport type CliParseErrorCodeV2 = 'NO_COMMAND' | 'UNKNOWN_COMMAND' | 'UNKNOWN_OPTION' | 'MISSING_VALUE' | 'INVALID_VALUE' | 'DUPLICATE_OPTION' | 'UNEXPECTED_ARGUMENT' | 'REMOTE_PATH' | 'RULE_PACK_INVALID' | 'SEMANTIC_CATALOGUE_INVALID' | 'PROFILE_NOT_ADMITTED';\nexport type CliParseErrorV2 = Readonly<{ code: CliParseErrorCodeV2; message: string; argument?: string }>;\n\ntype ScanCommandV2 = Readonly<{\n kind: 'scan'; schema: 'v2'; inputs: readonly string[]; format: CliFormatV2; profile: CliProfileV2; failOn: ScanSeverityV2;\n requireComplete: boolean; concurrency: number; timeoutMs?: number; output?: string; configPath?: string;\n rules: 'builtin'; catalogue: 'builtin'; limits: string; target?: string; n8nVersion?: string;\n edition: 'COMMUNITY' | 'ENTERPRISE' | 'CLOUD' | 'UNKNOWN'; deployment: 'SELF_HOSTED' | 'CLOUD' | 'UNKNOWN';\n role: 'OWNER' | 'ADMIN' | 'MEMBER' | 'UNKNOWN'; taskRunner: 'LEGACY' | 'NATIVE' | 'UNKNOWN';\n communityPackages: readonly string[]; configuration: readonly string[]; approvedDomains: readonly string[]; include: readonly string[]; exclude: readonly string[];\n allowUnsignedDevelopmentRules: boolean; noColor: boolean; cliOverrides: Readonly<Partial<ScanConfigV2>>;\n}>;\nexport type CliHelpCommandV2 = Readonly<{ kind: 'help'; schema: 'v2'; command?: V2CommandName }>;\nexport type CliCommandV2 = ScanCommandV2\n | Readonly<{ kind: 'rules'; schema: 'v2'; format: 'json' | 'table' }>\n | Readonly<{ kind: 'explain'; schema: 'v2'; format: 'json' | 'table'; ruleId: string }>\n | Readonly<{ kind: 'profiles'; schema: 'v2'; format: 'json' | 'table' }>\n | Readonly<{ kind: 'validate-config'; schema: 'v2'; format: 'json' | 'table'; path: string }>\n | Readonly<{ kind: 'version'; schema: 'v2'; format: 'json' | 'table' }>;\ntype ParsedCommandV2 = CliCommandV2 | CliHelpCommandV2;\nexport type CliParseResultV2 = Readonly<{ ok: true; command: ParsedCommandV2 } | { ok: false; error: CliParseErrorV2 }>;\nexport type CliArgumentDispatch = Readonly<{ mode: 'v1'; argv: readonly string[] } | { mode: 'v2'; result: CliParseResultV2 }>;\n\nconst severities: readonly ScanSeverityV2[] = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'INFO'];\nconst commands: Record<string, true> = Object.freeze({ scan: true, rules: true, explain: true, profiles: true, 'validate-config': true, version: true, '--version': true });\nconst implicitV2Commands: Record<string, true> = Object.freeze({ rules: true, explain: true, profiles: true, 'validate-config': true, version: true });\nconst scalarOptions: Record<string, true> = Object.freeze({ '--format': true, '--profile': true, '--fail-on': true, '--max-concurrency': true, '--concurrency': true, '--timeout': true, '--output': true, '--config': true, '--rules': true, '--catalogue': true, '--limits': true, '--target': true, '--n8n-version': true, '--edition': true, '--deployment': true, '--role': true, '--task-runner': true });\nconst repeatableOptions: Record<string, true> = Object.freeze({ '--community-package': true, '--configuration': true, '--approved-domain': true, '--include': true, '--exclude': true });\nconst configFields: Record<string, keyof ScanConfigV2> = Object.freeze({ '--format': 'format', '--profile': 'profile', '--fail-on': 'failOn', '--max-concurrency': 'concurrency', '--concurrency': 'concurrency', '--output': 'output', '--config': 'configPath', '--rules': 'rules', '--catalogue': 'catalogue', '--limits': 'limits', '--target': 'target', '--approved-domain': 'approvedDomains', '--include': 'include', '--exclude': 'exclude', 'inputs': 'inputs', '--require-complete': 'requireComplete', '--allow-unsigned-development-rules': 'allowUnsignedDevelopmentRules', '--no-color': 'noColor' });\nconst overrideOrder: readonly (keyof ScanConfigV2)[] = ['format', 'profile', 'output', 'inputs', 'configPath', 'failOn', 'requireComplete', 'concurrency', 'rules', 'catalogue', 'limits', 'target', 'include', 'exclude', 'approvedDomains', 'allowUnsignedDevelopmentRules', 'noColor'];\n\nexport function parseArgumentsV2(argv: readonly string[]): CliParseResultV2 {\n const stripped = stripSchema(argv); if (!stripped.ok) return stripped.result;\n const args = stripped.args; const raw = args[0];\n if (!raw) return failure('NO_COMMAND', 'A v2 command is required.');\n if (raw === '--help') return success({ kind: 'help', schema: 'v2' });\n if (commands[raw] !== true) return failure('UNKNOWN_COMMAND', 'Unknown v2 command.');\n const kind = raw === '--version' ? 'version' : raw;\n if (kind !== 'scan') return parseMetadata(kind as Exclude<CliCommandV2['kind'], 'scan' | 'help'>, args.slice(1));\n if (args.length === 2 && args[1] === '--help') return success({ kind: 'help', schema: 'v2', command: 'scan' });\n const value: Record<string, unknown> = {\n kind: 'scan', schema: 'v2', inputs: [], format: 'json', profile: 'beta-default', failOn: 'INFO', requireComplete: false,\n concurrency: 1, rules: 'builtin', catalogue: 'builtin', limits: 'builtin', edition: 'UNKNOWN', deployment: 'UNKNOWN',\n role: 'UNKNOWN', taskRunner: 'UNKNOWN', communityPackages: [], configuration: [], include: ['**/*.json'],\n exclude: ['.git/**', 'node_modules/**'], allowUnsignedDevelopmentRules: false, noColor: false,\n };\n const overrides: Record<string, unknown> = {}; const inputs: string[] = []; const repeatable: Record<string, string[]> = { '--community-package': [], '--configuration': [], '--approved-domain': [], '--include': [], '--exclude': [] }; const seen = new Set<string>();\n for (let index = 1; index < args.length; index += 1) {\n const token = args[index]!;\n if (token === '--') {\n for (const rawInput of args.slice(index + 1)) {\n const input = rawInput === '-' ? '-' : normalizeAdmittedPathV2(rawInput);\n if (input === undefined) return failure('REMOTE_PATH', 'Input path is not admitted.');\n inputs.push(input);\n }\n break;\n }\n if (token === '-' || !token.startsWith('-')) {\n const input = token === '-' ? '-' : normalizeAdmittedPathV2(token);\n if (input === undefined) return failure('REMOTE_PATH', 'Input path is not admitted.');\n inputs.push(input);\n continue;\n }\n const [name, inline] = splitOption(token);\n if (name === '--require-complete' || name === '--allow-unsigned-development-rules' || name === '--no-color') {\n if (inline !== undefined || seen.has(name)) return failure('DUPLICATE_OPTION', 'Option supplied more than once.', name);\n seen.add(name); value[name === '--require-complete' ? 'requireComplete' : name === '--no-color' ? 'noColor' : 'allowUnsignedDevelopmentRules'] = true; overrides[configFields[name]!] = true; continue;\n }\n if (scalarOptions[name] !== true && repeatableOptions[name] !== true) return failure('UNKNOWN_OPTION', 'Unknown option.', name);\n const duplicateKey = name === '--max-concurrency' ? '--concurrency' : name;\n if (seen.has(duplicateKey) && scalarOptions[name] === true) return failure('DUPLICATE_OPTION', 'Option supplied more than once.', name);\n const read = inline === undefined ? args[index + 1] : inline;\n if (read === undefined || read.length === 0 || (inline === undefined && read.startsWith('-') && !(name === '--output' && read === '-'))) return failure('MISSING_VALUE', 'Option requires a value.', name);\n if (inline === undefined) index += 1;\n if (repeatableOptions[name] === true) {\n if (name === '--approved-domain' && !isApprovedDomainV2(read)) return failure('INVALID_VALUE', 'Approved domain is invalid.', name);\n if (!isAdmittedRelativePath(read)) return failure('REMOTE_PATH', 'Option value is not admitted.', name);\n repeatable[name]!.push(read);\n if (configFields[name]) overrides[configFields[name]!] = Object.freeze([...repeatable[name]!]);\n continue;\n }\n if (name === '--format' && !['json', 'ndjson', 'sarif', 'table'].includes(read)) return failure('INVALID_VALUE', 'Format is invalid.', name);\n if (name === '--profile' && !isAdmittedProfileSpecifierV2(read)) return failure('PROFILE_NOT_ADMITTED', 'Profile is not admitted.', name);\n if (name === '--fail-on' && !severities.includes(read as ScanSeverityV2)) return failure('INVALID_VALUE', 'Fail threshold is invalid.', name);\n if ((name === '--max-concurrency' || name === '--concurrency' || name === '--timeout') && !positiveInteger(read, name === '--timeout' ? 2 ** 31 - 1 : 16)) return failure('INVALID_VALUE', 'Numeric option is invalid.', name);\n if (name === '--n8n-version' && !/^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$/.test(read)) return failure('INVALID_VALUE', 'n8n version is invalid.', name);\n if (name === '--edition' && !['COMMUNITY', 'ENTERPRISE', 'CLOUD', 'UNKNOWN'].includes(read)) return failure('INVALID_VALUE', 'Edition is invalid.', name);\n if (name === '--deployment' && !['SELF_HOSTED', 'CLOUD', 'UNKNOWN'].includes(read)) return failure('INVALID_VALUE', 'Deployment is invalid.', name);\n if (name === '--role' && !['OWNER', 'ADMIN', 'MEMBER', 'UNKNOWN'].includes(read)) return failure('INVALID_VALUE', 'Role is invalid.', name);\n if (name === '--task-runner' && !['LEGACY', 'NATIVE', 'UNKNOWN'].includes(read)) return failure('INVALID_VALUE', 'Task runner is invalid.', name);\n if (name === '--rules' || name === '--catalogue') { if (read !== 'builtin') return failure(name === '--rules' ? 'RULE_PACK_INVALID' : 'SEMANTIC_CATALOGUE_INVALID', 'Only built-in authority is available.', name); }\n else if (['--limits', '--target', '--config'].includes(name) && (read === '-' || !isAdmittedRelativePath(read))) return failure('REMOTE_PATH', 'Option value is not admitted.', name);\n else if (name === '--output' && read !== '-' && !isAdmittedRelativePath(read)) return failure('REMOTE_PATH', 'Option value is not admitted.', name);\n else if (['--n8n-version', '--edition', '--deployment', '--role', '--task-runner'].includes(name) && !safeText(read)) return failure('INVALID_VALUE', 'Option value is not admitted.', name);\n seen.add(duplicateKey); assign(value, name, read); if (name === '--profile') value.profile = ADMITTED_PROFILE_V2.id; if (configFields[name]) overrides[configFields[name]!] = ['--max-concurrency', '--concurrency'].includes(name) ? Number(read) : read;\n }\n // No external rule pack is admittable: `--rules`/`--catalogue` accept only the built-in authority,\n // so the unsigned development escape hatch has nothing it could admit. It is refused as a usage\n // error instead of being left to imply that a local pack would be loaded.\n if (value.allowUnsignedDevelopmentRules === true) return failure('RULE_PACK_INVALID', 'External rule packs are not admitted in this release.', '--allow-unsigned-development-rules');\n if (inputs.length === 0) return failure('UNEXPECTED_ARGUMENT', 'At least one workflow input is required.');\n if (inputs.some((input) => input !== '-' && !isAdmittedLocalPath(input))) return failure('REMOTE_PATH', 'Input path is not admitted.');\n if (inputs.includes('-') && inputs.length > 1) return failure('UNEXPECTED_ARGUMENT', 'Standard input cannot be combined with file inputs.');\n overrides.inputs = Object.freeze([...inputs]);\n const cliOverrides: Partial<ScanConfigV2> = {}; const sparse = cliOverrides as Record<string, unknown>; for (const field of overrideOrder) if (Object.prototype.hasOwnProperty.call(overrides, field)) sparse[field] = overrides[field];\n const command: ScanCommandV2 = {\n kind: 'scan', schema: 'v2', inputs: Object.freeze([...inputs]), format: value.format as CliFormatV2, profile: ADMITTED_PROFILE_V2.id, failOn: value.failOn as ScanSeverityV2, requireComplete: value.requireComplete as boolean, concurrency: value.concurrency as number,\n ...(typeof value.timeoutMs === 'number' ? { timeoutMs: value.timeoutMs } : {}), ...(typeof value.output === 'string' ? { output: value.output } : {}), ...(typeof value.configPath === 'string' ? { configPath: value.configPath } : {}), rules: value.rules as 'builtin', catalogue: value.catalogue as 'builtin', limits: value.limits as string,\n ...(typeof value.target === 'string' ? { target: value.target } : {}), ...(typeof value.n8nVersion === 'string' ? { n8nVersion: value.n8nVersion } : {}), edition: value.edition as ScanCommandV2['edition'], deployment: value.deployment as ScanCommandV2['deployment'], role: value.role as ScanCommandV2['role'], taskRunner: value.taskRunner as ScanCommandV2['taskRunner'], communityPackages: arrayFor(repeatable['--community-package']), configuration: arrayFor(repeatable['--configuration']), approvedDomains: arrayFor(repeatable['--approved-domain']), include: repeatable['--include']!.length > 0 ? arrayFor(repeatable['--include']) : Object.freeze(['**/*.json']), exclude: repeatable['--exclude']!.length > 0 ? arrayFor(repeatable['--exclude']) : Object.freeze(['.git/**', 'node_modules/**']), allowUnsignedDevelopmentRules: value.allowUnsignedDevelopmentRules as boolean, noColor: value.noColor as boolean, cliOverrides,\n };\n return success(command);\n}\n\nfunction arrayFor(values: readonly string[] | undefined): readonly string[] { return Object.freeze([...(values ?? [])]); }\nexport function parseCliArguments(argv: readonly string[]): CliArgumentDispatch { const hasSchema = hasSchemaMarker(argv); const implicit = argv[0] !== undefined && implicitV2Commands[argv[0]!] === true; return hasSchema || implicit ? freeze({ mode: 'v2', result: parseArgumentsV2(argv) }) : freeze({ mode: 'v1', argv: Object.freeze([...argv]) }); }\nfunction parseMetadata(kind: Exclude<CliCommandV2['kind'], 'scan' | 'help'>, args: readonly string[]): CliParseResultV2 {\n if (args.length === 1 && args[0] === '--help') return success({ kind: 'help', schema: 'v2', command: kind });\n let format: 'json' | 'table' = 'json';\n const rest: string[] = [];\n let seen = false;\n for (let index = 0; index < args.length; index += 1) {\n const token = args[index]!;\n if (token.startsWith('-')) {\n const [name, inline] = splitOption(token);\n if (name !== '--format' || seen) return failure(seen ? 'DUPLICATE_OPTION' : 'UNKNOWN_OPTION', seen ? 'Option supplied more than once.' : 'Unknown option.', name);\n const value = inline ?? args[++index];\n if (!value) return failure('MISSING_VALUE', 'Option requires a value.', name);\n if (value !== 'json' && value !== 'table') return failure('INVALID_VALUE', 'Format is invalid.', name);\n format = value;\n seen = true;\n } else rest.push(token);\n }\n if (kind === 'rules' || kind === 'profiles' || kind === 'version') {\n if (rest.length > 0) return failure('UNEXPECTED_ARGUMENT', 'Command does not accept positional arguments.');\n return success({ kind, schema: 'v2', format });\n }\n if (kind === 'explain') return rest.length === 1 && safeText(rest[0]!) ? success({ kind, schema: 'v2', format, ruleId: rest[0]! }) : failure('UNEXPECTED_ARGUMENT', 'explain requires one rule ID.');\n if (rest.length !== 1 || !isAdmittedRelativePath(rest[0]!)) return failure('UNEXPECTED_ARGUMENT', 'validate-config requires one local file.');\n return success({ kind, schema: 'v2', format, path: rest[0]! });\n}\nfunction assign(value: Record<string, unknown>, name: string, read: string): void { const fields: Record<string, string> = { '--format': 'format', '--profile': 'profile', '--fail-on': 'failOn', '--max-concurrency': 'concurrency', '--concurrency': 'concurrency', '--timeout': 'timeoutMs', '--output': 'output', '--config': 'configPath', '--rules': 'rules', '--catalogue': 'catalogue', '--limits': 'limits', '--target': 'target', '--n8n-version': 'n8nVersion', '--edition': 'edition', '--deployment': 'deployment', '--role': 'role', '--task-runner': 'taskRunner' }; value[fields[name]!] = ['--max-concurrency', '--concurrency', '--timeout'].includes(name) ? Number(read) : read; }\nfunction splitOption(token: string): [string, string | undefined] { const at = token.indexOf('='); return at < 0 ? [token, undefined] : [token.slice(0, at), token.slice(at + 1)]; }\nfunction positiveInteger(value: string, maximum: number): boolean { if (!/^\\d+$/.test(value)) return false; const number = Number(value); return Number.isSafeInteger(number) && number > 0 && number <= maximum; }\nfunction safeText(value: string): boolean { return value.length > 0 && value.length <= 4096 && !/[\\u0000-\\u001f\\u007f]/.test(value) && !/^(?:[a-z][a-z\\d+.-]*:|\\/|[a-z]:|\\\\\\\\)/i.test(value); }\nfunction hasSchemaMarker(argv: readonly string[]): boolean { for (const token of argv) { if (token === '--') break; if (token === '--schema' || token.startsWith('--schema=')) return true; } return false; }\nfunction stripSchema(argv: readonly string[]): { ok: true; args: readonly string[] } | { ok: false; result: CliParseResultV2 } { const args: string[] = []; let seen = false; for (let index = 0; index < argv.length; index += 1) { const token = argv[index]!; if (token === '--') { args.push(...argv.slice(index)); break; } if (token === '--schema') { if (seen || argv[index + 1] !== 'v2') return { ok: false, result: failure(seen ? 'DUPLICATE_OPTION' : 'INVALID_VALUE', seen ? 'Option supplied more than once.' : 'Schema must be v2.', '--schema') }; seen = true; index += 1; continue; } if (token.startsWith('--schema=')) { if (seen || token.slice(9) !== 'v2') return { ok: false, result: failure(seen ? 'DUPLICATE_OPTION' : 'INVALID_VALUE', seen ? 'Option supplied more than once.' : 'Schema must be v2.', '--schema') }; seen = true; continue; } args.push(token); } return { ok: true, args }; }\nfunction success(command: ParsedCommandV2): CliParseResultV2 { return freeze({ ok: true as const, command }); }\nfunction failure(code: CliParseErrorCodeV2, message: string, argument?: string): CliParseResultV2 { const safe = argument !== undefined && /^--[A-Za-z0-9][A-Za-z0-9-]{0,63}$/.test(argument) ? argument : undefined; return freeze({ ok: false as const, error: { code, message, ...(safe === undefined ? {} : { argument: safe }) } }); }\nfunction freeze<T>(value: T, seen = new WeakSet<object>()): T { if (value && typeof value === 'object') { if (seen.has(value as object)) return value; seen.add(value as object); for (const name of Object.getOwnPropertyNames(value as object)) freeze((value as Record<string, unknown>)[name], seen); Object.freeze(value); } return value; }\n", "import { readFileSync } from 'node:fs';\nimport type {\n CliExplainDocumentV2,\n CliMetadataDocumentV2,\n CliProfilesDocumentV2,\n CliRulesDocumentV2,\n CliVersionDocumentV2,\n} from './commands.js';\nimport {\n explainDocumentV2,\n isAdmittedConfigPathV2,\n profilesDocumentV2,\n rulesDocumentV2,\n runCommandV2,\n validateConfigDocumentV2,\n versionDocumentV2,\n} from './commands.js';\nimport type { CliCommandV2 } from './arguments.js';\nimport { validateDocumentShape } from './metadata-validation.js';\n\nexport type MetadataFormatV2 = 'json' | 'table';\nexport type MetadataOutputOptionsV2 = Readonly<{ color?: boolean; configDirectory?: string }>;\n\nfunction formatTable(headers: readonly string[], rows: readonly (readonly string[])[]): string {\n const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)));\n const sep = widths.map((w) => '-'.repeat(w)).join(' ');\n const formatRow = (cells: readonly string[]) => cells.map((c, i) => c.padEnd(widths[i]!)).join(' ');\n const body = rows.map(formatRow).join('\\n');\n return `${formatRow(headers)}\\n${sep}${body ? `\\n${body}` : ''}\\n`;\n}\n\nfunction renderExplainTable(doc: CliExplainDocumentV2): string {\n const { rule: r, prose: p } = doc;\n const steps = p.remediationSteps.map((s, i) => ` ${i + 1}. ${s}`).join('\\n');\n const ev = doc.evidenceProperties.length ? doc.evidenceProperties.join(', ') : 'none';\n return [`Rule: ${r.ruleId} (${r.severity}, ${r.confidence}, ${r.effect})`, `Title: ${p.title}`, `Message: ${p.message}`, `Explanation: ${p.explanation}`, `Why it matters: ${p.whyItMatters}`, `Possible impact: ${p.possibleImpact}`, `Remediation: ${p.remediation}`, `Remediation steps:\\n${steps}`, `Evidence properties: ${ev}`].join('\\n\\n') + '\\n';\n}\n\nexport function renderMetadataTableV2(document: CliMetadataDocumentV2, _options?: MetadataOutputOptionsV2): string {\n validateDocumentShape(document);\n if (document.schemaVersion === 'n8n-scan-rules-v2') return formatTable(['Rule ID', 'Severity', 'Confidence', 'Effect', 'CWE'], document.rules.map((r) => [r.ruleId, r.severity, r.confidence, r.effect, r.cweIds.join(',') || '-']));\n if (document.schemaVersion === 'n8n-scan-explain-v2') return renderExplainTable(document);\n if (document.schemaVersion === 'n8n-scan-profiles-v2') return formatTable(['Profile', 'Version', 'Admitted', 'Capabilities', 'Digest'], document.profiles.map((p) => [p.id, p.version, p.admitted ? 'yes' : 'no', String(p.capabilities.length), p.digest.slice(0, 16)]));\n if (document.schemaVersion === 'n8n-scan-version-v2') return [`${document.name} v${document.cliVersion} (mode: ${document.mode})`, `Engine: ${document.engine.id} v${document.engine.version} (${document.engine.buildDigest.slice(0, 16)})`, `Config schema: ${document.configSchema}`, `Ruleset digest: ${document.rulesetDigest.slice(0, 16)}`, `Semantics digest: ${document.semanticsDigest.slice(0, 16)}`].join('\\n') + '\\n';\n return 'Configuration is valid.\\n';\n}\n\nexport function serializeMetadataJsonV2(document: CliMetadataDocumentV2): string {\n validateDocumentShape(document);\n return `${JSON.stringify(document, null, 2)}\\n`;\n}\n\nexport function serializeMetadataV2(document: CliMetadataDocumentV2, format: MetadataFormatV2 = 'json', options?: MetadataOutputOptionsV2): string {\n if (format === 'table') return renderMetadataTableV2(document, options);\n if (format === 'json') return serializeMetadataJsonV2(document);\n throw new TypeError('Invalid format');\n}\n\nexport function emitRulesDocumentV2(format: MetadataFormatV2 = 'json', options?: MetadataOutputOptionsV2): string { return serializeMetadataV2(rulesDocumentV2(), format, options); }\nexport function emitExplainDocumentV2(ruleId: string, format: MetadataFormatV2 = 'json', options?: MetadataOutputOptionsV2): Readonly<{ ok: true; output: string } | { ok: false; code: 'USAGE'; message: string }> {\n const res = explainDocumentV2(ruleId); if (!res.ok) return res;\n return Object.freeze({ ok: true as const, output: serializeMetadataV2(res.document, format, options) });\n}\nexport function emitProfilesDocumentV2(format: MetadataFormatV2 = 'json', options?: MetadataOutputOptionsV2): string { return serializeMetadataV2(profilesDocumentV2(), format, options); }\nexport function emitVersionDocumentV2(format: MetadataFormatV2 = 'json', options?: MetadataOutputOptionsV2): string { return serializeMetadataV2(versionDocumentV2(), format, options); }\nexport function emitConfigValidationDocumentV2(input: unknown, format: MetadataFormatV2 = 'json', options?: MetadataOutputOptionsV2): Readonly<{ ok: true; output: string } | { ok: false; code: 'USAGE'; message: string }> {\n const res = validateConfigDocumentV2(input, options?.configDirectory); if (!res.ok) return res;\n return Object.freeze({ ok: true as const, output: serializeMetadataV2(res.document, format, options) });\n}\n\nexport function emitMetadataCommandResultV2(command: CliCommandV2, configInput?: unknown, options?: MetadataOutputOptionsV2): Readonly<{ ok: true; output: string } | { ok: false; code: 'USAGE'; message: string }> {\n if (command.kind === 'scan') return Object.freeze({ ok: false as const, code: 'USAGE', message: 'Scan command is not a metadata command.' });\n if (command.kind === 'validate-config') {\n if (!isAdmittedConfigPathV2(command.path)) {\n return Object.freeze({ ok: false as const, code: 'USAGE', message: 'Configuration path is not admitted.' });\n }\n let input = configInput;\n if (input === undefined) {\n try { input = readFileSync(command.path, 'utf8'); } catch { return Object.freeze({ ok: false, code: 'USAGE', message: 'Configuration could not be read.' }); }\n }\n const res = validateConfigDocumentV2(input, options?.configDirectory);\n if (!res.ok) return res;\n return Object.freeze({ ok: true as const, output: serializeMetadataV2(res.document, command.format, options) });\n }\n const res = runCommandV2(command, configInput, options?.configDirectory);\n if (!res.ok) return res;\n if ('command' in res) return Object.freeze({ ok: false as const, code: 'USAGE', message: 'Unexpected scan command.' });\n return Object.freeze({ ok: true as const, output: serializeMetadataV2(res.document, command.format, options) });\n}\n", "import { createHash } from 'node:crypto';\nimport { readFileSync } from 'node:fs';\nimport { canonicalizeJson } from '@hub/scanner-core/canonical-json';\nimport { ENGINE_BUILD_DIGEST_V2 } from '@hub/scanner-core/v2';\nimport { betaDefaultRuleCatalog, type RuleCatalogEntry } from '@hub/scanner-core/rule-catalog';\nimport { ADMITTED_PROFILE_V2, BUILTIN_LIMITS_AUTHORITY_V2, BUILTIN_RULESET_AUTHORITY_V2, BUILTIN_SEMANTICS_AUTHORITY_V2, CLI_TOOL_V2, loadExplicitConfig } from './config.js';\nimport type { CliCommandV2 } from './arguments.js';\n\ntype CliSeverityV2 = 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';\ntype CliConfidenceV2 = 'LOW' | 'MEDIUM' | 'HIGH';\nexport type CliRuleSummaryV2 = Readonly<{ ruleId: string; revision: string; effect: 'SCORING' | 'REPORT_ONLY'; severity: CliSeverityV2; confidence: CliConfidenceV2; capabilityId: string; evidenceSchemaId: string; remediationId: string; cweIds: readonly string[]; owaspAgenticIds: readonly string[] }>;\nexport type CliArtifactIdentityV2 = Readonly<{ profile: { id: string; version: string }; ruleset: { id: string; version: string; digest: string; signatureStatus: 'VERIFIED' | 'UNVERIFIED' }; semantics: { id: string; version: string; digest: string }; target: { edition: 'UNKNOWN'; deployment: 'UNKNOWN'; role: 'UNKNOWN'; taskRunner: 'UNKNOWN'; communityPackages: readonly never[]; configuration: readonly never[]; contextDigest: string }; limits: { schemaVersion: 'scanner-limits-v2'; digest: string } }>;\nexport type CliRulesDocumentV2 = Readonly<{ schemaVersion: 'n8n-scan-rules-v2'; tool: ToolV2; artifacts: CliArtifactIdentityV2; rules: readonly CliRuleSummaryV2[] }>;\nexport type CliExplainDocumentV2 = Readonly<{ schemaVersion: 'n8n-scan-explain-v2'; tool: ToolV2; artifacts: CliArtifactIdentityV2; rule: CliRuleSummaryV2; prose: ProseV2; evidenceProperties: readonly string[]; provenance: { packDigest: string; semanticsDigest: string } }>;\nexport type CliProfileSummaryV2 = Readonly<{ id: string; version: string; admitted: boolean; advertised: boolean; digest: string; scoringPolicyVersion: string; capabilities: readonly CapabilityV2[] }>;\nexport type CliProfilesDocumentV2 = Readonly<{ schemaVersion: 'n8n-scan-profiles-v2'; tool: ToolV2; profiles: readonly CliProfileSummaryV2[] }>;\nexport type CliVersionDocumentV2 = Readonly<{ schemaVersion: 'n8n-scan-version-v2'; name: 'n8n-scan'; cliVersion: string; engine: { id: 'secureflow-scanner'; version: '2.0.0'; buildDigest: string }; resultSchemas: readonly ['scanner-result-v1', 'scanner-result-v2']; configSchema: 'n8n-scan-config-v2'; rulesetDigest: string; semanticsDigest: string; trustStoreDigest: string; mode: 'offline' }>;\nexport type CliConfigValidationDocumentV2 = Readonly<{ schemaVersion: 'n8n-scan-config-validation-v2'; valid: true; artifacts: CliArtifactIdentityV2 }>;\nexport type CliMetadataDocumentV2 = CliRulesDocumentV2 | CliExplainDocumentV2 | CliProfilesDocumentV2 | CliVersionDocumentV2 | CliConfigValidationDocumentV2;\nexport type CliCommandResultV2 = Readonly<{ ok: true; document: CliMetadataDocumentV2 } | { ok: true; command: Extract<CliCommandV2, { kind: 'scan' }> } | { ok: false; code: 'USAGE'; message: string }>;\n\ntype ToolV2 = Readonly<{ name: 'n8n-scan'; version: string; buildDigest: string }>;\ntype ProseV2 = Readonly<{ title: string; message: string; explanation: string; whyItMatters: string; possibleImpact: string; remediation: string; remediationSteps: readonly string[] }>;\ntype CapabilityV2 = Readonly<{ id: string; version: string; required: boolean; dependsOn: readonly string[]; ruleIds: readonly string[] }>;\nconst hash = (value: unknown): string => createHash('sha256').update(canonicalizeJson(value)).digest('hex');\nconst targetBody = Object.freeze({ edition: 'UNKNOWN' as const, deployment: 'UNKNOWN' as const, role: 'UNKNOWN' as const, taskRunner: 'UNKNOWN' as const, communityPackages: Object.freeze([]), configuration: Object.freeze([]) });\nconst EVIDENCE: Record<string, readonly string[]> = { N8N_EXECUTE_COMMAND: ['nodeType'], N8N_CODE_NODE: ['nodeType'], RAW_AUTH_HEADER: ['header', 'literalValue'], RAW_SECRET_INDICATOR: ['parameterPath', 'secretKind', 'indicator', 'hasLiteralValue'], UNAPPROVED_DOMAIN: ['hostname'], UNKNOWN_NODE_PACKAGE: ['nodeType', 'nodePackage'], WEBHOOK_EXPOSURE: ['authentication'] };\nconst EVIDENCE_SCHEMA: Record<string, string> = { N8N_EXECUTE_COMMAND: 'v1.node-type', N8N_CODE_NODE: 'v1.node-type', RAW_AUTH_HEADER: 'v1.auth-header', RAW_SECRET_INDICATOR: 'v1.secret-indicator', UNAPPROVED_DOMAIN: 'v1.domain', UNKNOWN_NODE_PACKAGE: 'v1.node-package', WEBHOOK_EXPOSURE: 'v1.webhook-auth' };\nconst PROSE: Record<string, ProseV2> = {\n N8N_EXECUTE_COMMAND: { title: 'Execute Command node can run shell commands', message: 'This workflow can execute shell commands.', explanation: 'The Execute Command node allows the workflow to launch shell commands from the n8n runtime environment.', whyItMatters: 'Shell command access can cross from workflow automation into the host or worker environment that runs n8n.', possibleImpact: 'A malicious or compromised workflow path could lead to command execution, file access, lateral movement, or service disruption.', remediation: 'Remove the Execute Command node or isolate it behind strict approval.', remediationSteps: ['Remove the Execute Command node when shell access is not explicitly required.', 'Replace shell logic with a narrow, reviewed integration or managed service call.', 'If it must remain, isolate the workflow runner and require manual approval before execution.'] },\n N8N_CODE_NODE: { title: 'Custom code node requires security review', message: 'This workflow contains custom script execution.', explanation: 'Code and legacy Function nodes can transform data with arbitrary JavaScript inside the workflow runtime.', whyItMatters: 'Custom code is harder to audit than declarative node configuration and may handle secrets or external data.', possibleImpact: 'Unsafe code can leak data, mishandle credentials, or create behavior that reviewers cannot understand from node settings alone.', remediation: 'Review the code path, remove unnecessary scripting, and require approval.', remediationSteps: ['Review the node source code for secret access, outbound requests, and unsafe parsing.', 'Move repeatable logic into a reviewed service or reusable library when possible.', 'Require approval for changes to custom code nodes in production workflows.'] },\n RAW_AUTH_HEADER: { title: 'Raw Authorization header may expose credentials', message: 'This node configures a raw Authorization header.', explanation: 'The workflow parameters appear to define an Authorization header directly instead of using managed n8n credentials.', whyItMatters: 'Raw credential material in node parameters is easier to copy, persist, log, or expose in exported workflow JSON.', possibleImpact: 'API keys or bearer tokens can be leaked through workflow exports, scan history, logs, or support bundles.', remediation: 'Use n8n credentials or a managed secret reference instead of raw headers.', remediationSteps: ['Move the secret into n8n credentials or an approved secret manager.', 'Rotate any token that has already been stored in raw workflow JSON.', 'Re-scan after replacing the raw header with a managed credential reference.'] },\n RAW_SECRET_INDICATOR: { title: 'Workflow parameters contain raw secret material', message: 'This node contains a parameter that looks like a raw secret.', explanation: 'The scanner found a parameter key or value pattern commonly used for tokens, passwords, API keys, cookies, or credentials.', whyItMatters: 'Raw secrets in workflow JSON can be exposed through exports, scan history, logs, backups, or support bundles.', possibleImpact: 'An exposed token or password can allow unauthorized access to connected systems even if the workflow itself is not malicious.', remediation: 'Move the value into n8n credentials or an approved secret manager, then rotate any exposed secret.', remediationSteps: ['Move the raw value into n8n credentials or an approved secret manager.', 'Rotate the secret if it has already been exported, shared, or stored in history.', 'Re-scan the workflow after replacing the raw value with a managed credential reference.'] },\n UNAPPROVED_DOMAIN: { title: 'External domain is outside the approved allowlist', message: 'This workflow calls a domain outside the approved allowlist.', explanation: 'The node parameters contain a URL whose hostname is not present in the approved domain list supplied for this scan.', whyItMatters: 'Unexpected outbound domains can indicate data exfiltration, shadow integrations, or environment drift.', possibleImpact: 'Workflow data may be sent to an unreviewed third party or an endpoint that is not covered by enterprise controls.', remediation: 'Add the domain to the approved list or replace the external call.', remediationSteps: ['Confirm the business owner and purpose for the external domain.', 'Add the domain to the approved list only after security and compliance review.', 'Replace the call if the destination is unnecessary or untrusted.'] },\n UNKNOWN_NODE_PACKAGE: { title: 'Node package is not from an official n8n namespace', message: 'This workflow uses a community or custom node package.', explanation: 'The node type does not start with an official n8n package namespace, so it comes from a community or custom package.', whyItMatters: 'Community and custom packages can add supply-chain, maintenance, and permission risks that differ from core nodes.', possibleImpact: 'A vulnerable or unmaintained package could process sensitive workflow data or run unexpected code.', remediation: 'Review the package source, version, permissions, and maintenance status.', remediationSteps: ['Verify the package source, maintainer, and version history.', 'Check whether the node requires credentials or broad runtime permissions.', 'Pin approved versions and remove packages that are not actively maintained.'] },\n WEBHOOK_EXPOSURE: { title: 'Webhook trigger lacks clear authentication', message: 'This webhook does not show a clear authentication marker.', explanation: 'The webhook node appears to accept inbound requests without an explicit authentication mode in the workflow parameters.', whyItMatters: 'Unauthenticated inbound endpoints can be abused for spam, data injection, or unexpected workflow execution.', possibleImpact: 'External callers may trigger automations, create records, or send data into connected systems without authorization.', remediation: 'Require webhook authentication or place the endpoint behind trusted controls.', remediationSteps: ['Enable webhook authentication in n8n when the endpoint is not intentionally public.', 'Place the endpoint behind a gateway, allowlist, or rate limiter for production use.', 'Monitor webhook usage for unexpected request volume or payloads.'] },\n};\nconst CAPABILITIES: readonly CapabilityV2[] = Object.freeze([\n { id: 'source-normalization', version: '2.0.0', required: true, dependsOn: [], ruleIds: [] }, { id: 'workflow-insights', version: '2.0.0', required: true, dependsOn: ['source-normalization'], ruleIds: [] },\n { id: 'structural-policies', version: '2.0.0', required: true, dependsOn: ['source-normalization'], ruleIds: Object.freeze(betaDefaultRuleCatalog.map(({ policyId }) => policyId)) }, { id: 'assessment', version: '2.0.0', required: true, dependsOn: ['workflow-insights', 'structural-policies'], ruleIds: [] }, { id: 'presentation-facts', version: '2.0.0', required: true, dependsOn: ['assessment'], ruleIds: [] },\n]);\nconst HARDENED_CAPABILITIES: readonly CapabilityV2[] = Object.freeze([\n CAPABILITIES[0]!, CAPABILITIES[1]!, CAPABILITIES[2]!,\n { id: 'expression-security', version: '2.0.0', required: false, dependsOn: ['source-normalization'], ruleIds: [] },\n { id: 'javascript-security', version: '2.0.0', required: false, dependsOn: ['source-normalization'], ruleIds: ['JAVASCRIPT_DYNAMIC_EXECUTION'] },\n { id: 'python-security', version: '2.0.0', required: false, dependsOn: ['source-normalization'], ruleIds: ['PYTHON_DYNAMIC_EXECUTION'] },\n { id: 'graph-semantics', version: '2.0.0', required: false, dependsOn: ['source-normalization'], ruleIds: [] },\n { id: 'taint-confidentiality', version: '2.0.0', required: false, dependsOn: ['graph-semantics', 'expression-security', 'javascript-security', 'python-security'], ruleIds: [] },\n { id: 'taint-integrity', version: '2.0.0', required: false, dependsOn: ['graph-semantics', 'expression-security', 'javascript-security', 'python-security'], ruleIds: ['TAINTED_COMMAND', 'TAINTED_SQL_QUERY', 'TAINTED_REQUEST_URL', 'TAINTED_FILE_PATH', 'TAINTED_CODE_INPUT', 'TAINTED_REQUEST_HEADER', 'TAINTED_AI_PROMPT'] },\n { id: 'agentic-control', version: '2.0.0', required: false, dependsOn: ['graph-semantics', 'taint-confidentiality', 'taint-integrity'], ruleIds: ['AI_AGENT_UNGATED_TOOL'] },\n CAPABILITIES[3]!, CAPABILITIES[4]!,\n]);\n\nfunction artifacts(profile = ADMITTED_PROFILE_V2.id): CliArtifactIdentityV2 { const target = Object.freeze({ ...targetBody, contextDigest: hash(targetBody) }); return Object.freeze({ profile: Object.freeze({ id: profile, version: '2.0.0' }), ruleset: Object.freeze({ ...BUILTIN_RULESET_AUTHORITY_V2 }), semantics: Object.freeze({ ...BUILTIN_SEMANTICS_AUTHORITY_V2 }), target, limits: Object.freeze({ schemaVersion: 'scanner-limits-v2', digest: BUILTIN_LIMITS_AUTHORITY_V2.digest }) }); }\nfunction ruleSummary(entry: RuleCatalogEntry): CliRuleSummaryV2 { const capabilityId = 'structural-policies'; return Object.freeze({ ruleId: entry.policyId, revision: '1', effect: entry.policyEffect === 'REPORT_ONLY' ? 'REPORT_ONLY' : 'SCORING', severity: entry.defaultSeverity, confidence: entry.defaultConfidence, capabilityId, evidenceSchemaId: EVIDENCE_SCHEMA[entry.policyId] ?? 'v1.policy', remediationId: 'r', cweIds: Object.freeze([...entry.cweIds].sort()), owaspAgenticIds: Object.freeze([...(entry.owaspAgenticIds ?? [])].sort()) }); }\nexport function rulesDocumentV2(): CliRulesDocumentV2 { return Object.freeze({ schemaVersion: 'n8n-scan-rules-v2', tool: CLI_TOOL_V2, artifacts: artifacts(), rules: Object.freeze(betaDefaultRuleCatalog.map(ruleSummary)) }); }\nexport function explainDocumentV2(ruleId: string): Readonly<{ ok: true; document: CliExplainDocumentV2 } | { ok: false; code: 'USAGE'; message: string }> { const entry = betaDefaultRuleCatalog.find((item) => item.policyId === ruleId); const prose = PROSE[ruleId]; if (!entry || !prose) return Object.freeze({ ok: false as const, code: 'USAGE', message: 'Unknown rule.' }); const rule = ruleSummary(entry); return Object.freeze({ ok: true as const, document: Object.freeze({ schemaVersion: 'n8n-scan-explain-v2', tool: CLI_TOOL_V2, artifacts: artifacts(), rule, prose: Object.freeze({ ...prose, remediationSteps: Object.freeze([...prose.remediationSteps]) }), evidenceProperties: Object.freeze([...(EVIDENCE[ruleId] ?? [])]), provenance: Object.freeze({ packDigest: BUILTIN_RULESET_AUTHORITY_V2.digest, semanticsDigest: BUILTIN_SEMANTICS_AUTHORITY_V2.digest }) }) }); }\nexport function profilesDocumentV2(): CliProfilesDocumentV2 { const body = (id: string, admitted: boolean, capabilities: readonly CapabilityV2[], advertised = true) => Object.freeze({ id, version: '2.0.0', admitted, advertised, digest: hash({ schemaVersion: 'scanner-profile-v2', id, version: '2.0.0', capabilities, scoringPolicyVersion: 'secureflow-risk-v2@2.0.0' }), scoringPolicyVersion: 'secureflow-risk-v2@2.0.0', capabilities: Object.freeze(capabilities.map((item) => Object.freeze({ ...item, dependsOn: Object.freeze([...item.dependsOn]), ruleIds: Object.freeze([...item.ruleIds]) }))) }); return Object.freeze({ schemaVersion: 'n8n-scan-profiles-v2', tool: CLI_TOOL_V2, profiles: Object.freeze([body('beta-default', true, CAPABILITIES), body('beta-hardened', false, HARDENED_CAPABILITIES)]) }); }\nexport function versionDocumentV2(): CliVersionDocumentV2 { return Object.freeze({ schemaVersion: 'n8n-scan-version-v2', name: 'n8n-scan', cliVersion: CLI_TOOL_V2.version, engine: Object.freeze({ id: 'secureflow-scanner', version: '2.0.0', buildDigest: ENGINE_BUILD_DIGEST_V2 }), resultSchemas: Object.freeze(['scanner-result-v1', 'scanner-result-v2']) as CliVersionDocumentV2['resultSchemas'], configSchema: 'n8n-scan-config-v2', rulesetDigest: BUILTIN_RULESET_AUTHORITY_V2.digest, semanticsDigest: BUILTIN_SEMANTICS_AUTHORITY_V2.digest, trustStoreDigest: hash({ schemaVersion: 'scanner-trust-store-v2', version: '2.0.0', keys: [] }), mode: 'offline' }); }\nexport function validateConfigDocumentV2(input: unknown, configDirectory?: string): Readonly<{ ok: true; document: CliConfigValidationDocumentV2 } | { ok: false; code: 'USAGE'; message: string }> { const result = loadExplicitConfig(input, { configDirectory }); if (!result.ok) return Object.freeze({ ok: false, code: 'USAGE', message: 'Configuration is invalid.' }); return Object.freeze({ ok: true, document: Object.freeze({ schemaVersion: 'n8n-scan-config-validation-v2', valid: true, artifacts: artifacts() }) }); }\nexport function isAdmittedConfigPathV2(path: unknown): path is string {\n if (typeof path !== 'string' || path.length === 0 || path.length > 4096 || /[\\u0000-\\u001f\\u007f]/.test(path)) return false;\n const normalized = path.replaceAll('\\\\', '/');\n if (/^(?:[a-z][a-z\\d+.-]*:|\\/|[a-z]:|\\\\\\\\)/i.test(normalized) || /(?:^|\\/)\\.\\.(?:\\/|$)/.test(normalized) || /(?:^|\\/)%2e(?:%2e)?(?:\\/|$)/i.test(normalized)) return false;\n return normalized.split('/').some((part) => part !== '' && part !== '.');\n}\nexport function runCommandV2(command: CliCommandV2, configInput?: unknown, configDirectory?: string): CliCommandResultV2 {\n if (command.kind === 'scan') return command.profile === 'beta-default' ? Object.freeze({ ok: true, command }) : Object.freeze({ ok: false, code: 'USAGE', message: 'Profile is not admitted.' });\n if (command.kind === 'rules') return Object.freeze({ ok: true, document: rulesDocumentV2() });\n if (command.kind === 'profiles') return Object.freeze({ ok: true, document: profilesDocumentV2() });\n if (command.kind === 'version') return Object.freeze({ ok: true, document: versionDocumentV2() });\n if (command.kind === 'explain') return explainDocumentV2(command.ruleId);\n if (!isAdmittedConfigPathV2(command.path)) return Object.freeze({ ok: false, code: 'USAGE', message: 'Configuration path is not admitted.' });\n let input = configInput;\n if (input === undefined) {\n try { input = readFileSync(command.path, 'utf8'); } catch { return Object.freeze({ ok: false, code: 'USAGE', message: 'Configuration could not be read.' }); }\n }\n return validateConfigDocumentV2(input, configDirectory);\n}\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport type { SourceMemberRefV2 } from '../source/source-types';\nimport { encodeIdentityTuple } from './node-edge-identity';\nimport type {\n NormalizationAmbiguityKind,\n NormalizationAmbiguityV2,\n NormalizationResolution,\n NormalizationSecurityImpact,\n} from './security-workflow';\n\nconst encoder = new TextEncoder();\nconst KIND_ORDER: Record<NormalizationAmbiguityKind, number> = {\n DUPLICATE_MEMBER: 0,\n AMBIGUOUS_NODE: 1,\n AMBIGUOUS_EDGE: 2,\n UNRESOLVED_EDGE: 3,\n MALFORMED_SECURITY_VALUE: 4,\n};\n\nexport function createAmbiguity(input: {\n kind: NormalizationAmbiguityKind;\n subject: SourceMemberRefV2;\n related?: readonly SourceMemberRefV2[];\n securityImpact: NormalizationSecurityImpact;\n resolution: NormalizationResolution;\n}): NormalizationAmbiguityV2 {\n const related = [...(input.related ?? [])].sort(compareRefs);\n const ambiguityId = bytesToHex(sha256(encoder.encode(encodeIdentityTuple([\n 'secureflow-normalization-ambiguity-v2',\n input.kind,\n input.subject.astNodeId,\n ...related.map((ref) => ref.astNodeId),\n input.securityImpact,\n input.resolution,\n ]))));\n return Object.freeze({\n ambiguityId,\n kind: input.kind,\n subject: input.subject,\n related: Object.freeze(related),\n securityImpact: input.securityImpact,\n resolution: input.resolution,\n });\n}\n\nexport function sortAmbiguities(items: readonly NormalizationAmbiguityV2[]): NormalizationAmbiguityV2[] {\n return [...items].sort((left, right) => {\n const occurrence = comparePath(left.subject.occurrencePath, right.subject.occurrencePath);\n if (occurrence !== 0) return occurrence;\n const kind = KIND_ORDER[left.kind] - KIND_ORDER[right.kind];\n if (kind !== 0) return kind;\n const related = compareStrings(left.related.map((ref) => ref.astNodeId).join('\\u0000'), right.related.map((ref) => ref.astNodeId).join('\\u0000'));\n if (related !== 0) return related;\n return compareStrings(left.ambiguityId, right.ambiguityId);\n });\n}\n\nfunction compareRefs(left: SourceMemberRefV2, right: SourceMemberRefV2): number {\n const ids = compareStrings(left.astNodeId, right.astNodeId);\n return ids === 0 ? comparePath(left.occurrencePath, right.occurrencePath) : ids;\n}\n\nfunction comparePath(left: readonly number[], right: readonly number[]): number {\n const length = Math.min(left.length, right.length);\n for (let index = 0; index < length; index += 1) {\n if (left[index] !== right[index]) return left[index] < right[index] ? -1 : 1;\n }\n return left.length - right.length;\n}\n\nfunction compareStrings(left: string, right: string): number {\n return left === right ? 0 : left < right ? -1 : 1;\n}\n", "export type StrictSemver = Readonly<{\n major: number;\n minor: number;\n patch: number;\n prerelease: readonly string[];\n build: readonly string[];\n}>;\n\n/** Alias matching the SemVer spelling used by some catalogue contracts. */\nexport type StrictSemVer = StrictSemver;\n\ntype SemverParts = Readonly<{\n major: string;\n minor: string;\n patch: string;\n prerelease: readonly string[];\n build: readonly string[];\n}>;\n\nconst NUMERIC = /^[0-9]+$/;\nconst parsedParts = new WeakMap<object, SemverParts>();\n\nfunction invalid(): TypeError {\n return new TypeError('Invalid strict SemVer 2.0.0 value');\n}\n\nfunction compareAscii(left: string, right: string): number {\n if (left === right) return 0;\n const length = Math.min(left.length, right.length);\n for (let index = 0; index < length; index += 1) {\n const difference = left.charCodeAt(index) - right.charCodeAt(index);\n if (difference !== 0) return difference < 0 ? -1 : 1;\n }\n return left.length < right.length ? -1 : 1;\n}\n\nfunction compareNumericStrings(left: string, right: string): number {\n if (left.length !== right.length) return left.length < right.length ? -1 : 1;\n return compareAscii(left, right);\n}\n\nfunction identifier(value: string, prerelease: boolean): string {\n if (!/^[0-9A-Za-z-]+$/.test(value)) throw invalid();\n if (prerelease && NUMERIC.test(value) && value.length > 1 && value[0] === '0') throw invalid();\n return value;\n}\n\nfunction numberPart(value: string): string {\n if (value.length > 1 && value[0] === '0') throw invalid();\n return value;\n}\nfunction isDigit(code: number): boolean { return code >= 48 && code <= 57; }\nfunction readNumber(input: string, index: number): { value: string; next: number } {\n const start = index;\n while (index < input.length && isDigit(input.charCodeAt(index))) index += 1;\n if (index === start) throw invalid();\n const value = input.slice(start, index); numberPart(value);\n return { value, next: index };\n}\nfunction readVersionIdentifiers(input: string, index: number, prerelease: boolean): { values: readonly string[]; next: number } {\n const values: string[] = [];\n while (true) {\n const start = index;\n while (index < input.length) {\n const code = input.charCodeAt(index);\n if (code === 46 || (prerelease && code === 43)) break;\n index += 1;\n }\n if (index === start) throw invalid();\n values.push(identifier(input.slice(start, index), prerelease));\n if (index >= input.length || input.charCodeAt(index) !== 46) return { values, next: index };\n index += 1;\n }\n}\nfunction parseParts(input: unknown): SemverParts {\n if (typeof input !== 'string') throw invalid();\n let index = 0;\n const major = readNumber(input, index);\n index = major.next;\n if (input.charCodeAt(index) !== 46) throw invalid();\n index += 1;\n const minor = readNumber(input, index);\n index = minor.next;\n if (input.charCodeAt(index) !== 46) throw invalid();\n index += 1;\n const patch = readNumber(input, index);\n index = patch.next;\n let prerelease: readonly string[] = [];\n if (input.charCodeAt(index) === 45) {\n const parsed = readVersionIdentifiers(input, index + 1, true);\n prerelease = parsed.values;\n index = parsed.next;\n }\n let build: readonly string[] = [];\n if (input.charCodeAt(index) === 43) {\n const parsed = readVersionIdentifiers(input, index + 1, false);\n build = parsed.values;\n index = parsed.next;\n }\n\n if (index !== input.length) throw invalid();\n return { major: major.value, minor: minor.value, patch: patch.value, prerelease, build };\n}\n\n/** Parse a strict, complete SemVer 2.0.0 string into immutable numeric parts. */\nexport function parseStrictSemver(input: unknown): StrictSemver {\n const parts = parseParts(input);\n const result = Object.freeze({\n major: Number(parts.major),\n minor: Number(parts.minor),\n patch: Number(parts.patch),\n prerelease: Object.freeze([...parts.prerelease]),\n build: Object.freeze([...parts.build]),\n });\n parsedParts.set(result, parts);\n return result;\n}\n\nfunction readIdentifiers(input: unknown, prerelease: boolean): readonly string[] {\n if (!Array.isArray(input) || Object.getPrototypeOf(input) !== Array.prototype) throw invalid();\n const names = Object.getOwnPropertyNames(input);\n if (names.length !== input.length + 1 || !names.includes('length')) throw invalid();\n if (Object.getOwnPropertySymbols(input).length !== 0) throw invalid();\n const result: string[] = [];\n for (let index = 0; index < input.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(input, String(index));\n if (descriptor === undefined || !('value' in descriptor) || typeof descriptor.value !== 'string') throw invalid();\n result.push(identifier(descriptor.value, prerelease));\n }\n return result;\n}\n\nfunction readParts(input: unknown): SemverParts {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) throw invalid();\n const known = parsedParts.get(input);\n if (known !== undefined) return known;\n if (Object.getPrototypeOf(input) !== Object.prototype && Object.getPrototypeOf(input) !== null) throw invalid();\n const names = Object.getOwnPropertyNames(input);\n const fields = ['major', 'minor', 'patch', 'prerelease', 'build'];\n if (names.length !== fields.length || fields.some((field) => !names.includes(field)) || Object.getOwnPropertySymbols(input).length !== 0) throw invalid();\n const read = (field: string): unknown => {\n const descriptor = Object.getOwnPropertyDescriptor(input, field);\n if (descriptor === undefined || !('value' in descriptor)) throw invalid();\n return descriptor.value;\n };\n const major = read('major');\n const minor = read('minor');\n const patch = read('patch');\n if (typeof major !== 'number' || !Number.isSafeInteger(major) || major < 0 || Object.is(major, -0) || typeof minor !== 'number' || !Number.isSafeInteger(minor) || minor < 0 || Object.is(minor, -0) || typeof patch !== 'number' || !Number.isSafeInteger(patch) || patch < 0 || Object.is(patch, -0)) throw invalid();\n return { major: String(major), minor: String(minor), patch: String(patch), prerelease: readIdentifiers(read('prerelease'), true), build: readIdentifiers(read('build'), false) };\n}\n\n/** Compare two parsed SemVer values; build metadata is intentionally ignored. */\nexport function compareSemver(left: StrictSemver, right: StrictSemver): number {\n try {\n const first = readParts(left);\n const second = readParts(right);\n for (const key of ['major', 'minor', 'patch'] as const) {\n const result = compareNumericStrings(first[key], second[key]);\n if (result !== 0) return result;\n }\n if (first.prerelease.length === 0 && second.prerelease.length === 0) return 0;\n if (first.prerelease.length === 0) return 1;\n if (second.prerelease.length === 0) return -1;\n const length = Math.min(first.prerelease.length, second.prerelease.length);\n for (let index = 0; index < length; index += 1) {\n const leftIdentifier = first.prerelease[index];\n const rightIdentifier = second.prerelease[index];\n const leftNumeric = NUMERIC.test(leftIdentifier);\n const rightNumeric = NUMERIC.test(rightIdentifier);\n if (leftNumeric && rightNumeric) {\n const result = compareNumericStrings(leftIdentifier, rightIdentifier);\n if (result !== 0) return result;\n } else if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;\n else {\n const result = compareAscii(leftIdentifier, rightIdentifier);\n if (result !== 0) return result;\n }\n }\n return first.prerelease.length === second.prerelease.length ? 0 : first.prerelease.length < second.prerelease.length ? -1 : 1;\n } catch (error) {\n if (error instanceof TypeError) throw error;\n throw invalid();\n }\n}\n\n/** Compare only MAJOR.MINOR.PATCH, preserving arbitrary-length numeric identifiers. */\nexport function sameSemverBase(left: StrictSemver, right: StrictSemver): boolean {\n try {\n const first = readParts(left);\n const second = readParts(right);\n return first.major === second.major && first.minor === second.minor && first.patch === second.patch;\n } catch (error) {\n if (error instanceof TypeError) throw error;\n throw invalid();\n }\n}\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { canonicalJsonBytes } from '../canonical-json';\nimport { parseStrictSemver } from './semver';\n\nexport type TargetContextV2 = Readonly<{\n n8nVersion?: string;\n edition: 'COMMUNITY' | 'ENTERPRISE' | 'CLOUD' | 'UNKNOWN';\n deployment: 'SELF_HOSTED' | 'CLOUD' | 'UNKNOWN';\n role: 'OWNER' | 'ADMIN' | 'MEMBER' | 'UNKNOWN';\n taskRunner: 'LEGACY' | 'NATIVE' | 'UNKNOWN';\n communityPackages: readonly Readonly<{ name: string; version?: string }>[];\n configuration: readonly Readonly<{ key: string; state: 'ENABLED' | 'DISABLED' | 'UNKNOWN' }>[];\n contextDigest: string;\n}>;\n\nexport type TargetContextValidationOptions = Readonly<{\n allowedConfigurationKeys?: ReadonlySet<string> | readonly string[];\n}>;\ntype Plain = Record<string, unknown>;\ntype Body = Omit<TargetContextV2, 'contextDigest'>;\nconst TOP = ['n8nVersion', 'edition', 'deployment', 'role', 'taskRunner', 'communityPackages', 'configuration', 'contextDigest'] as const;\nconst DIGEST = /^[0-9a-f]{64}$/;\nconst BAD_KEY = /[%\\\\]/;\nconst PACKAGE_NAME = /^(?:[a-z0-9][a-z0-9._-]*|@[a-z0-9][a-z0-9._-]*\\/[a-z0-9][a-z0-9._-]*)$/;\nconst MAX_TEXT_LENGTH = 4096;\nconst MAX_COLLECTION_ITEMS = 100_000;\nconst ENUMS = {\n edition: ['COMMUNITY', 'ENTERPRISE', 'CLOUD', 'UNKNOWN'],\n deployment: ['SELF_HOSTED', 'CLOUD', 'UNKNOWN'],\n role: ['OWNER', 'ADMIN', 'MEMBER', 'UNKNOWN'],\n taskRunner: ['LEGACY', 'NATIVE', 'UNKNOWN'],\n} as const;\n\nclass TargetContextError extends TypeError {}\nfunction invalid(reason: string): never { throw new TargetContextError(reason); }\nfunction has(value: Plain, key: string): boolean { return Object.prototype.hasOwnProperty.call(value, key); }\nfunction ownRecord(input: unknown, allowed: readonly string[], label: string): Plain {\n try {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) return invalid(`UNSAFE_INPUT: ${label}`);\n const prototype = Object.getPrototypeOf(input);\n if (prototype !== Object.prototype && prototype !== null) return invalid(`UNSAFE_INPUT: ${label}`);\n const names = Object.getOwnPropertyNames(input);\n if (Object.getOwnPropertySymbols(input).length !== 0) return invalid(`UNSAFE_INPUT: ${label}`);\n for (const name of names) if (!allowed.includes(name)) return invalid(`UNKNOWN_KEY: ${label}.${name}`);\n const result: Plain = Object.create(null);\n for (const name of names) {\n const descriptor = Object.getOwnPropertyDescriptor(input, name);\n if (descriptor === undefined || !('value' in descriptor)) return invalid(`UNSAFE_INPUT: ${label}.${name}`);\n result[name] = descriptor.value;\n }\n return result;\n } catch (error) {\n if (error instanceof TargetContextError) throw error;\n return invalid(`UNSAFE_INPUT: ${label}`);\n }\n}\nfunction denseArray(input: unknown, label: string): readonly unknown[] {\n try {\n if (!Array.isArray(input) || Object.getPrototypeOf(input) !== Array.prototype) return invalid(`UNSAFE_INPUT: ${label}`);\n const length = Object.getOwnPropertyDescriptor(input, 'length');\n if (length === undefined || !('value' in length) || typeof length.value !== 'number' || !Number.isSafeInteger(length.value) || length.value < 0 || length.value > MAX_COLLECTION_ITEMS) return invalid(`UNSAFE_INPUT: ${label}`);\n const names = Object.getOwnPropertyNames(input);\n if (names.length !== length.value + 1 || !names.includes('length') || Object.getOwnPropertySymbols(input).length !== 0) return invalid(`UNSAFE_INPUT: ${label}`);\n const result: unknown[] = [];\n for (let index = 0; index < length.value; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(input, String(index));\n if (descriptor === undefined || !('value' in descriptor)) return invalid(`UNSAFE_INPUT: ${label}[${index}]`);\n result.push(descriptor.value);\n }\n return result;\n } catch (error) {\n if (error instanceof TargetContextError) throw error;\n return invalid(`UNSAFE_INPUT: ${label}`);\n }\n}\nfunction safeText(value: unknown, label: string): string {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_TEXT_LENGTH || value !== value.normalize('NFC') || BAD_KEY.test(value)) return invalid(`INVALID_TEXT: ${label}`);\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code <= 0x1f || code === 0x7f) return invalid(`INVALID_TEXT: ${label}`);\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) return invalid(`INVALID_TEXT: ${label}`);\n index += 1;\n } else if (code >= 0xdc00 && code <= 0xdfff) return invalid(`INVALID_TEXT: ${label}`);\n }\n return value;\n}\nfunction packageName(value: unknown): string {\n const name = safeText(value, 'package.name');\n if (name.length > 214 || !PACKAGE_NAME.test(name)) return invalid('INVALID_PACKAGE_NAME');\n return name;\n}\nfunction compareCodePoints(left: string, right: string): number {\n if (left === right) return 0;\n const a = [...left], b = [...right];\n for (let index = 0; index < Math.min(a.length, b.length); index += 1) { const difference = a[index].codePointAt(0)! - b[index].codePointAt(0)!; if (difference !== 0) return difference < 0 ? -1 : 1; }\n return a.length < b.length ? -1 : 1;\n}\nfunction allowedKeys(options?: TargetContextValidationOptions): ReadonlySet<string> | undefined {\n if (options === undefined) return undefined;\n const safeOptions = ownRecord(options, ['allowedConfigurationKeys'], 'options');\n const candidate = has(safeOptions, 'allowedConfigurationKeys') ? safeOptions.allowedConfigurationKeys : undefined;\n if (candidate === undefined) return undefined;\n const values = Array.isArray(candidate) ? denseArray(candidate, 'allowedConfigurationKeys') : candidate instanceof Set ? setValues(candidate) : invalid('UNSAFE_INPUT: allowedConfigurationKeys');\n const result = new Set<string>();\n for (const value of values) { const key = safeText(value, 'allowedConfigurationKeys'); if (result.has(key)) return invalid('DUPLICATE_CONFIGURATION_KEY'); result.add(key); }\n return result;\n}\nfunction setValues(value: Set<unknown>): readonly unknown[] {\n const result: unknown[] = [];\n Set.prototype.forEach.call(value, (item) => result.push(item));\n return result;\n}\nfunction enumValue(value: Plain, key: keyof typeof ENUMS): string {\n if (!has(value, key)) return 'UNKNOWN';\n if (typeof value[key] !== 'string' || !(ENUMS[key] as readonly string[]).includes(value[key] as string)) return invalid(`INVALID_${key.toUpperCase()}`);\n return value[key] as string;\n}\nfunction body(input: unknown, options?: TargetContextValidationOptions): Body {\n const value = ownRecord(input, TOP, 'target');\n const output: Plain = {};\n if (has(value, 'n8nVersion')) { if (typeof value.n8nVersion !== 'string') return invalid('INVALID_N8N_VERSION'); try { parseStrictSemver(value.n8nVersion); } catch { return invalid('INVALID_N8N_VERSION'); } output.n8nVersion = value.n8nVersion; }\n output.edition = enumValue(value, 'edition'); output.deployment = enumValue(value, 'deployment'); output.role = enumValue(value, 'role'); output.taskRunner = enumValue(value, 'taskRunner');\n const packages = has(value, 'communityPackages') ? denseArray(value.communityPackages, 'communityPackages') : [];\n const packageNames = new Set<string>();\n output.communityPackages = packages.map((raw, index) => { const item = ownRecord(raw, ['name', 'version'], `communityPackages[${index}]`); if (!has(item, 'name')) return invalid('MISSING_KEY: package.name'); const name = packageName(item.name); if (packageNames.has(name)) return invalid('DUPLICATE_PACKAGE'); packageNames.add(name); const result: Plain = { name }; if (has(item, 'version')) { if (typeof item.version !== 'string') return invalid('INVALID_PACKAGE_VERSION'); try { parseStrictSemver(item.version); } catch { return invalid('INVALID_PACKAGE_VERSION'); } result.version = item.version; } return result; }).sort((left, right) => compareCodePoints(left.name as string, right.name as string) || compareCodePoints((left.version as string | undefined) ?? '', (right.version as string | undefined) ?? ''));\n const vocabulary = allowedKeys(options);\n const configs = has(value, 'configuration') ? denseArray(value.configuration, 'configuration') : [];\n const configKeys = new Set<string>();\n output.configuration = configs.map((raw, index) => { const item = ownRecord(raw, ['key', 'state'], `configuration[${index}]`); if (!has(item, 'key')) return invalid('MISSING_KEY: configuration.key'); const key = safeText(item.key, 'configuration.key'); if (vocabulary && !vocabulary.has(key)) return invalid('UNKNOWN_CONFIGURATION_KEY'); if (configKeys.has(key)) return invalid('DUPLICATE_CONFIGURATION_KEY'); configKeys.add(key); const state = has(item, 'state') ? item.state : 'UNKNOWN'; if (typeof state !== 'string' || !['ENABLED', 'DISABLED', 'UNKNOWN'].includes(state)) return invalid('INVALID_CONFIGURATION_STATE'); return { key, state } as Plain; }).sort((left, right) => compareCodePoints(left.key as string, right.key as string) || compareCodePoints(left.state as string, right.state as string));\n return output as Body;\n}\nfunction digestBody(value: Body): string { return bytesToHex(sha256(canonicalJsonBytes(value))); }\nfunction freeze<T>(value: T, seen = new WeakSet<object>()): T { if (value !== null && typeof value === 'object') { if (seen.has(value)) return value; seen.add(value); for (const key of Object.getOwnPropertyNames(value)) freeze((value as Plain)[key], seen); Object.freeze(value); } return value; }\n\nexport function createTargetDigest(targetWithoutDigest: Omit<TargetContextV2, 'contextDigest'>): string {\n return digestBody(body(targetWithoutDigest));\n}\nexport function validateTargetContextV2(input: unknown, options?: TargetContextValidationOptions): TargetContextV2 {\n try {\n const normalized = body(input, options); const digest = digestBody(normalized); const value = ownRecord(input, TOP, 'target');\n if (has(value, 'contextDigest')) { if (typeof value.contextDigest !== 'string' || !DIGEST.test(value.contextDigest)) return invalid('INVALID_CONTEXT_DIGEST'); if (value.contextDigest !== digest) return invalid('CONTEXT_DIGEST_MISMATCH'); }\n return freeze({ ...normalized, contextDigest: digest }) as TargetContextV2;\n } catch (error) { if (error instanceof TargetContextError) throw error; return invalid('UNSAFE_INPUT'); }\n}\n", "import { compareSemver, parseStrictSemver, sameSemverBase, type StrictSemver } from './semver';\n\nexport type VersionOperator = 'EQ' | 'LT' | 'LTE' | 'GT' | 'GTE';\nexport type VersionComparatorV2 = Readonly<{ op: VersionOperator; version: string }>;\nexport type VersionRangeV2 = Readonly<{ clauses: readonly (readonly VersionComparatorV2[])[] }>;\n\nconst operators: Readonly<Record<VersionOperator, number>> = { EQ: 0, LT: 1, LTE: 2, GT: 3, GTE: 4 };\nconst validOperators: Readonly<Record<VersionOperator, true>> = { EQ: true, LT: true, LTE: true, GT: true, GTE: true };\n\ntype CheckedComparator = Readonly<{ value: VersionComparatorV2; parsed: StrictSemver }>;\ntype CheckedClause = readonly CheckedComparator[];\n\nfunction invalid(): TypeError {\n return new TypeError('Invalid or noncanonical comparator version range');\n}\n\nfunction asciiCompare(left: string, right: string): number {\n if (left === right) return 0;\n const length = Math.min(left.length, right.length);\n for (let index = 0; index < length; index += 1) {\n const difference = left.charCodeAt(index) - right.charCodeAt(index);\n if (difference !== 0) return difference < 0 ? -1 : 1;\n }\n return left.length < right.length ? -1 : 1;\n}\n\nfunction ownRecord(input: unknown, fields: readonly string[]): Record<string, unknown> {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) throw invalid();\n const prototype = Object.getPrototypeOf(input);\n if (prototype !== Object.prototype && prototype !== null) throw invalid();\n const names = Object.getOwnPropertyNames(input);\n if (names.length !== fields.length || fields.some((field) => !names.includes(field)) || Object.getOwnPropertySymbols(input).length !== 0) throw invalid();\n const result: Record<string, unknown> = {};\n for (const field of fields) {\n const descriptor = Object.getOwnPropertyDescriptor(input, field);\n if (descriptor === undefined || !('value' in descriptor)) throw invalid();\n result[field] = descriptor.value;\n }\n return result;\n}\n\nfunction denseArray(input: unknown): readonly unknown[] {\n if (!Array.isArray(input) || Object.getPrototypeOf(input) !== Array.prototype) throw invalid();\n const length = Object.getOwnPropertyDescriptor(input, 'length');\n if (length === undefined || !('value' in length) || typeof length.value !== 'number' || !Number.isSafeInteger(length.value) || length.value < 0) throw invalid();\n const names = Object.getOwnPropertyNames(input);\n if (names.length !== length.value + 1 || !names.includes('length') || Object.getOwnPropertySymbols(input).length !== 0) throw invalid();\n const result: unknown[] = [];\n for (let index = 0; index < length.value; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(input, String(index));\n if (descriptor === undefined || !('value' in descriptor)) throw invalid();\n result.push(descriptor.value);\n }\n return result;\n}\n\nfunction comparator(input: unknown): CheckedComparator {\n const value = ownRecord(input, ['op', 'version']);\n if (typeof value.op !== 'string' || !Object.prototype.hasOwnProperty.call(validOperators, value.op) || typeof value.version !== 'string') throw invalid();\n const parsed = parseStrictSemver(value.version);\n return { value: { op: value.op as VersionOperator, version: value.version }, parsed };\n}\n\nfunction compareComparator(left: CheckedComparator, right: CheckedComparator): number {\n const byVersion = compareSemver(left.parsed, right.parsed);\n if (byVersion !== 0) return byVersion;\n const byText = asciiCompare(left.value.version, right.value.version);\n if (byText !== 0) return byText;\n return operators[left.value.op] - operators[right.value.op];\n}\n\nfunction compareClause(left: CheckedClause, right: CheckedClause): number {\n const length = Math.min(left.length, right.length);\n for (let index = 0; index < length; index += 1) {\n const result = compareComparator(left[index], right[index]);\n if (result !== 0) return result;\n }\n return left.length === right.length ? 0 : left.length < right.length ? -1 : 1;\n}\n\ntype CheckedRange = Readonly<{ range: VersionRangeV2; clauses: readonly CheckedClause[] }>;\n\nfunction checkedRange(input: unknown): CheckedRange {\n const value = ownRecord(input, ['clauses']);\n const rawClauses = denseArray(value.clauses);\n const checked: CheckedClause[] = [];\n for (const rawClause of rawClauses) {\n const rawComparators = denseArray(rawClause);\n if (rawComparators.length === 0) throw invalid();\n const clause = rawComparators.map(comparator);\n for (let index = 1; index < clause.length; index += 1) if (compareComparator(clause[index - 1], clause[index]) >= 0) throw invalid();\n checked.push(Object.freeze(clause));\n }\n for (let index = 1; index < checked.length; index += 1) if (compareClause(checked[index - 1], checked[index]) >= 0) throw invalid();\n const clauses = checked.map((clause) => Object.freeze(clause.map((item) => Object.freeze({ ...item.value }))));\n return Object.freeze({ range: Object.freeze({ clauses: Object.freeze(clauses) }), clauses: Object.freeze(checked) });\n}\n\n/** Validate a closed, sorted comparator-clause range and return immutable data. */\nexport function validateVersionRange(input: unknown): VersionRangeV2 {\n try {\n return checkedRange(input).range;\n } catch (error) {\n if (error instanceof TypeError) throw error;\n throw invalid();\n }\n}\n\nfunction candidateHasPrerelease(version: StrictSemver): boolean {\n compareSemver(version, version);\n if (version === null || typeof version !== 'object' || Array.isArray(version)) throw invalid();\n const prerelease = Object.getOwnPropertyDescriptor(version, 'prerelease');\n if (prerelease === undefined || !('value' in prerelease) || !Array.isArray(prerelease.value)) throw invalid();\n const length = Object.getOwnPropertyDescriptor(prerelease.value, 'length');\n if (length === undefined || !('value' in length) || typeof length.value !== 'number' || !Number.isSafeInteger(length.value) || length.value < 0) throw invalid();\n return length.value > 0;\n}\n\nfunction satisfies(version: StrictSemver, comparatorValue: CheckedComparator): boolean {\n const comparison = compareSemver(version, comparatorValue.parsed);\n switch (comparatorValue.value.op) {\n case 'EQ': return comparison === 0;\n case 'LT': return comparison < 0;\n case 'LTE': return comparison <= 0;\n case 'GT': return comparison > 0;\n case 'GTE': return comparison >= 0;\n }\n}\n\n/** Match a parsed version against a validated canonical range. */\nexport function matchesVersionRange(version: StrictSemver, range: VersionRangeV2): boolean {\n try {\n const candidate = version;\n const candidatePrerelease = candidateHasPrerelease(candidate);\n const checked = checkedRange(range);\n if (checked.clauses.length === 0) return !candidatePrerelease;\n return checked.clauses.some((clause) => {\n if (candidatePrerelease && !clause.some((item) => item.parsed.prerelease.length > 0 && sameSemverBase(candidate, item.parsed))) return false;\n return clause.every((item) => satisfies(candidate, item));\n });\n } catch (error) {\n if (error instanceof TypeError) throw error;\n throw invalid();\n }\n}\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { canonicalJsonBytes, canonicalizeJson } from '../canonical-json';\nimport { validateVersionRange, matchesVersionRange, type VersionRangeV2 } from './version-range';\nimport { parseStrictSemver, type StrictSemver } from './semver';\nimport type {\n ResolvedNodeSemanticsV2, SemanticAuthenticationV2, SemanticCatalogueBodyV2, SemanticCatalogueV2, SemanticEndpointV2,\n SemanticEffectV2, SemanticPathV2, SemanticPortV2, SemanticProvenanceV2,\n} from './catalogue-schema';\n\ntype Dict = Record<string, unknown>;\nexport type SemanticCatalogueErrorCode = 'UNSAFE_INPUT' | 'UNKNOWN_KEY' | 'MISSING_KEY' | 'INVALID_SCHEMA_VERSION' | 'INVALID_VERSION' | 'INVALID_TEXT' | 'INVALID_ENUM' | 'INVALID_RANGE' | 'INVALID_PROVENANCE' | 'INVALID_AUTHENTICATION' | 'DUPLICATE_ID' | 'DUPLICATE_RECORD' | 'DUPLICATE_CONFIGURATION_KEY' | 'DIGEST_MISMATCH' | 'SEMANTIC_CATALOGUE_AMBIGUOUS';\nexport class SemanticCatalogueAdmissionError extends TypeError {\n readonly code: SemanticCatalogueErrorCode;\n constructor(code: SemanticCatalogueErrorCode, label?: string) { super(`${code}${label ? `: ${label}` : ''}`); this.name = 'SemanticCatalogueAdmissionError'; this.code = code; }\n}\nconst TOP = ['schemaVersion', 'id', 'version', 'records', 'configurationKeys', 'digest'] as const;\nconst RECORD = ['semanticId', 'nodeType', 'versionRange', 'operation', 'entry', 'parameterPaths', 'authentication', 'credentialPaths', 'destinationPaths', 'effects', 'endpoints', 'ports', 'overwritePaths', 'errorMode', 'retryMode', 'disabledMode', 'provenance'] as const;\nconst PROVENANCE = ['sourceUrl', 'sourceDigest', 'reviewedAt', 'reviewer'] as const;\nconst MAX_ITEMS = 100_000;\nconst MAX_TEXT = 4_096;\nconst DIGEST = /^[0-9a-f]{64}$/;\nconst REVIEWED_AT = /^(\\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])(?:T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d{1,3})?Z)?$/;\nconst enums = {\n entry: ['TRIGGER', 'MANUAL', 'SUBWORKFLOW', 'NONE'], valueType: ['ANY', 'STRING', 'BOOLEAN', 'NUMBER', 'OBJECT', 'ARRAY'],\n effect: ['READ_EXTERNAL', 'WRITE_EXTERNAL', 'EXECUTE_CODE', 'EXECUTE_COMMAND', 'READ_FILE', 'WRITE_FILE', 'DATABASE_READ', 'DATABASE_WRITE', 'SEND_MESSAGE', 'CALL_TOOL', 'START_SUBWORKFLOW'],\n channel: ['DATA', 'CONTROL', 'ERROR', 'MODEL', 'TOOL', 'CONTEXT'], direction: ['SOURCE', 'SINK', 'SANITIZER'], taint: ['CONFIDENTIALITY', 'INTEGRITY', 'BOTH'],\n itemMode: ['EACH', 'ALL', 'PAIRWISE', 'UNKNOWN'], errorMode: ['STOP', 'CONTINUE', 'OUTPUT', 'UNKNOWN'], retryMode: ['NONE', 'BOUNDED', 'PLATFORM', 'UNKNOWN'], disabledMode: ['SKIP', 'UNKNOWN'], unknownValueEffect: ['UNKNOWN', 'EXPOSED'],\n} as const;\nconst has = (value: Dict, key: string): boolean => Object.prototype.hasOwnProperty.call(value, key);\nfunction fail(code: SemanticCatalogueErrorCode, label?: string): never { throw new SemanticCatalogueAdmissionError(code, label); }\nfunction own(input: unknown, allowed: readonly string[], label: string): Dict {\n try {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) return fail('UNSAFE_INPUT', label);\n const proto = Object.getPrototypeOf(input); if (proto !== Object.prototype && proto !== null) return fail('UNSAFE_INPUT', label);\n const names = Object.getOwnPropertyNames(input); if (Object.getOwnPropertySymbols(input).length !== 0) return fail('UNSAFE_INPUT', label);\n for (const name of names) if (!allowed.includes(name)) return fail('UNKNOWN_KEY', `${label}.${name}`);\n const output: Dict = Object.create(null);\n for (const name of names) { const descriptor = Object.getOwnPropertyDescriptor(input, name); if (!descriptor || !('value' in descriptor)) return fail('UNSAFE_INPUT', `${label}.${name}`); output[name] = descriptor.value; }\n return output;\n } catch (error) { if (error instanceof SemanticCatalogueAdmissionError) throw error; return fail('UNSAFE_INPUT', label); }\n}\nfunction required(value: Dict, keys: readonly string[], label: string): void { for (const key of keys) if (!has(value, key)) fail('MISSING_KEY', `${label}.${key}`); }\nfunction dense(input: unknown, label: string): unknown[] {\n try {\n if (!Array.isArray(input) || Object.getPrototypeOf(input) !== Array.prototype) return fail('UNSAFE_INPUT', label);\n const length = Object.getOwnPropertyDescriptor(input, 'length'); if (!length || !('value' in length) || typeof length.value !== 'number' || !Number.isSafeInteger(length.value) || length.value < 0 || length.value > MAX_ITEMS) return fail('UNSAFE_INPUT', label);\n const names = Object.getOwnPropertyNames(input); if (names.length !== length.value + 1 || Object.getOwnPropertySymbols(input).length !== 0) return fail('UNSAFE_INPUT', label);\n for (const name of names) if (name !== 'length' && (!/^(0|[1-9]\\d*)$/.test(name) || Number(name) >= length.value)) return fail('UNSAFE_INPUT', label);\n const output: unknown[] = []; for (let index = 0; index < length.value; index += 1) { const descriptor = Object.getOwnPropertyDescriptor(input, String(index)); if (!descriptor || !('value' in descriptor)) return fail('UNSAFE_INPUT', `${label}[${index}]`); output.push(descriptor.value); } return output;\n } catch (error) { if (error instanceof SemanticCatalogueAdmissionError) throw error; return fail('UNSAFE_INPUT', label); }\n}\nfunction text(input: unknown, label: string, maximum = MAX_TEXT, allowEmpty = false): string {\n if (typeof input !== 'string' || (!allowEmpty && input.length === 0) || input.length > maximum || input !== input.normalize('NFC')) return fail('INVALID_TEXT', label);\n for (let index = 0; index < input.length; index += 1) { const code = input.charCodeAt(index); if (code <= 0x1f || code >= 0x7f && code <= 0x9f) return fail('INVALID_TEXT', label); if (code >= 0xd800 && code <= 0xdbff) { const next = input.charCodeAt(index + 1); if (next < 0xdc00 || next > 0xdfff) return fail('INVALID_TEXT', label); index += 1; } else if (code >= 0xdc00 && code <= 0xdfff) return fail('INVALID_TEXT', label); }\n if (new TextEncoder().encode(input).length > maximum) return fail('INVALID_TEXT', label); return input;\n}\nfunction enumValue<T extends string>(input: unknown, values: readonly T[], label: string): T { if (typeof input !== 'string' || !values.includes(input as T)) return fail('INVALID_ENUM', label); return input as T; }\nfunction pointer(input: unknown, label: string): string { const value = text(input, label, 2_048, true); if (!/^(?:|\\/(?:[^~]|~0|~1)*)$/.test(value)) return fail('INVALID_TEXT', label); return value; }\nfunction compare(left: string, right: string): number { return left === right ? 0 : left < right ? -1 : 1; }\nfunction sortedUnique(values: string[], label: string): readonly string[] { const unique = new Set(values); if (unique.size !== values.length) return fail(label === 'configurationKeys' ? 'DUPLICATE_CONFIGURATION_KEY' : 'DUPLICATE_RECORD', label); return Object.freeze([...unique].sort()); }\nfunction baseText(value: StrictSemver): string { return `${value.major}.${value.minor}.${value.patch}`; }\nfunction versionText(value: StrictSemver): string {\n const prerelease = value.prerelease.length ? `-${value.prerelease.join('.')}` : '';\n const build = value.build.length ? `+${value.build.join('.')}` : '';\n return `${baseText(value)}${prerelease}${build}`;\n}\nfunction addPrereleaseSamples(result: Set<string>, value: StrictSemver): void {\n if (value.prerelease.length === 0) return;\n const base = baseText(value); const ids = [...value.prerelease];\n result.add(versionText(value));\n for (let index = 0; index < ids.length; index += 1) {\n const item = ids[index];\n if (/^\\d+$/.test(item)) {\n const number = Number(item);\n if (Number.isSafeInteger(number)) {\n if (number > 0) result.add(`${base}-${ids.slice(0, index).concat(String(number - 1)).join('.')}`);\n if (number < Number.MAX_SAFE_INTEGER) result.add(`${base}-${ids.slice(0, index).concat(String(number + 1)).join('.')}`);\n }\n } else {\n for (const replacement of ['a', 'b', 'z']) result.add(`${base}-${ids.slice(0, index).concat(replacement).join('.')}`);\n }\n for (const suffix of ['0', '1', 'z']) result.add(`${base}-${ids.slice(0, index + 1).concat(suffix).join('.')}`);\n }\n}\nfunction addVersionSamples(result: Set<string>, value: StrictSemver): void {\n const base = baseText(value);\n result.add(versionText(value)); result.add(base); result.add(`${base}-0`); result.add(`${base}-z`); addPrereleaseSamples(result, value);\n if (value.patch < Number.MAX_SAFE_INTEGER) result.add(`${value.major}.${value.minor}.${value.patch + 1}`);\n if (value.minor < Number.MAX_SAFE_INTEGER) result.add(`${value.major}.${value.minor + 1}.0`);\n if (value.major < Number.MAX_SAFE_INTEGER) result.add(`${value.major + 1}.0.0`);\n if (value.patch > 0) result.add(`${value.major}.${value.minor}.${value.patch - 1}`);\n if (value.minor > 0) result.add(`${value.major}.${value.minor - 1}.0`);\n if (value.major > 0) result.add(`${value.major - 1}.0.0`);\n}\nfunction rangeSamples(left: VersionRangeV2, right: VersionRangeV2): readonly string[] {\n const result = new Set(['0.0.0', '1.0.0', '2.0.0', '999999.0.0']);\n for (const range of [left, right]) for (const clause of range.clauses) for (const item of clause) addVersionSamples(result, parseStrictSemver(item.version));\n return [...result];\n}\nfunction subset(left: VersionRangeV2, right: VersionRangeV2): boolean {\n let rightOnly = false;\n for (const textValue of rangeSamples(left, right)) { const value = parseStrictSemver(textValue); const leftMatch = matchesVersionRange(value, left); const rightMatch = matchesVersionRange(value, right); if (leftMatch && !rightMatch) return false; if (rightMatch && !leftMatch) rightOnly = true; }\n return rightOnly;\n}\nfunction overlap(left: VersionRangeV2, right: VersionRangeV2): boolean {\n return rangeSamples(left, right).some((textValue) => {\n const value = parseStrictSemver(textValue);\n return matchesVersionRange(value, left) && matchesVersionRange(value, right);\n });\n}\n\nfunction stringList(input: unknown, label: string, isPointer = false): readonly string[] { const values = dense(input, label).map((item, index) => isPointer ? pointer(item, `${label}[${index}]`) : text(item, `${label}[${index}]`)); return sortedUnique(values, label); }\nfunction path(input: unknown, label: string): SemanticPathV2 { const value = own(input, ['pointer', 'valueType', 'required'], label); required(value, ['pointer', 'valueType', 'required'], label); return Object.freeze({ pointer: pointer(value.pointer, `${label}.pointer`), valueType: enumValue(value.valueType, enums.valueType, `${label}.valueType`), required: typeof value.required === 'boolean' ? value.required : fail('INVALID_TEXT', `${label}.required`) }); }\nfunction paths(input: unknown, label: string): readonly SemanticPathV2[] {\n const output = dense(input, label).map((item, index) => path(item, `${label}[${index}]`));\n const keys = output.map((item) => canonicalizeJson(item));\n if (new Set(keys).size !== keys.length) return fail('DUPLICATE_RECORD', label);\n return Object.freeze(output.sort((a, b) => compare(canonicalizeJson(a), canonicalizeJson(b))));\n}\nfunction authentication(input: unknown, label: string): SemanticAuthenticationV2 | null {\n if (input === null) return null;\n const value = own(input, ['path', 'noneValues', 'authenticatedValues', 'unknownValueEffect'], label);\n required(value, ['path', 'noneValues', 'authenticatedValues', 'unknownValueEffect'], label);\n const noneValues = stringList(value.noneValues, `${label}.noneValues`);\n const authenticatedValues = stringList(value.authenticatedValues, `${label}.authenticatedValues`);\n if (noneValues.some((item) => authenticatedValues.includes(item))) return fail('INVALID_AUTHENTICATION', label);\n return Object.freeze({ path: pointer(value.path, `${label}.path`), noneValues, authenticatedValues, unknownValueEffect: enumValue(value.unknownValueEffect, enums.unknownValueEffect, `${label}.unknownValueEffect`) });\n}\nfunction endpoint(input: unknown, label: string): SemanticEndpointV2 { const value = own(input, ['path', 'channel', 'direction', 'taint', 'scope'], label); required(value, ['path', 'channel', 'direction', 'taint'], label); const result: Dict = { path: pointer(value.path, `${label}.path`), channel: enumValue(value.channel, enums.channel, `${label}.channel`), direction: enumValue(value.direction, enums.direction, `${label}.direction`), taint: enumValue(value.taint, enums.taint, `${label}.taint`) }; if (has(value, 'scope')) result.scope = text(value.scope, `${label}.scope`); return Object.freeze(result) as SemanticEndpointV2; }\nfunction endpoints(input: unknown, label: string): readonly SemanticEndpointV2[] { const output = dense(input, label).map((item, index) => endpoint(item, `${label}[${index}]`)); const keys = output.map((item) => canonicalizeJson(item)); if (new Set(keys).size !== keys.length) return fail('DUPLICATE_RECORD', label); return Object.freeze(output.sort((a, b) => compare(canonicalizeJson(a), canonicalizeJson(b)))); }\nfunction ports(input: unknown, label: string): readonly SemanticPortV2[] { const output = dense(input, label).map((item, index) => { const value = own(item, ['type', 'index', 'itemMode'], `${label}[${index}]`); required(value, ['type', 'index', 'itemMode'], `${label}[${index}]`); if (typeof value.index !== 'number' || !Number.isSafeInteger(value.index) || value.index < 0) return fail('INVALID_TEXT', `${label}[${index}].index`); return Object.freeze({ type: text(value.type, `${label}[${index}].type`, 256), index: value.index, itemMode: enumValue(value.itemMode, enums.itemMode, `${label}[${index}].itemMode`) }); }); const keys = output.map((item) => canonicalizeJson(item)); if (new Set(keys).size !== keys.length) return fail('DUPLICATE_RECORD', label); return Object.freeze(output.sort((a, b) => compare(canonicalizeJson(a), canonicalizeJson(b)))); }\nfunction reviewedAt(input: unknown, label: string): string {\n const value = text(input, label, 24);\n const match = REVIEWED_AT.exec(value);\n if (!match) return fail('INVALID_PROVENANCE', label);\n const year = Number(match[1]); const month = Number(match[2]); const day = Number(match[3]);\n const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n const days = month === 2 ? (leap ? 29 : 28) : [4, 6, 9, 11].includes(month) ? 30 : 31;\n if (day > days) return fail('INVALID_PROVENANCE', label);\n return value;\n}\nfunction provenance(input: unknown, label: string): SemanticProvenanceV2 { const value = own(input, PROVENANCE, label); required(value, PROVENANCE, label); const sourceUrl = text(value.sourceUrl, `${label}.sourceUrl`, 2_048); try { const parsed = new URL(sourceUrl); if (parsed.protocol !== 'https:' || parsed.username || parsed.password || !parsed.hostname) return fail('INVALID_PROVENANCE', `${label}.sourceUrl`); } catch { return fail('INVALID_PROVENANCE', `${label}.sourceUrl`); } const sourceDigest = text(value.sourceDigest, `${label}.sourceDigest`, 64); if (!DIGEST.test(sourceDigest)) return fail('INVALID_PROVENANCE', `${label}.sourceDigest`); return Object.freeze({ sourceUrl, sourceDigest, reviewedAt: reviewedAt(value.reviewedAt, `${label}.reviewedAt`), reviewer: text(value.reviewer, `${label}.reviewer`) }); }\nfunction nodeType(input: unknown, label: string): string { const value = text(input, label, 512); if (value !== '*' && !/^@?[A-Za-z0-9][A-Za-z0-9._/@-]*\\.[A-Za-z0-9_$-]+$/.test(value)) return fail('INVALID_TEXT', label); return value; }\nfunction record(input: unknown, label: string): ResolvedNodeSemanticsV2 { const value = own(input, RECORD, label); required(value, RECORD, label); const operation = value.operation === null ? null : text(value.operation, `${label}.operation`, 256); const range = (() => { try { return validateVersionRange(value.versionRange); } catch { return fail('INVALID_RANGE', `${label}.versionRange`); } })(); const result: Dict = { semanticId: text(value.semanticId, `${label}.semanticId`, 512), nodeType: nodeType(value.nodeType, `${label}.nodeType`), versionRange: range, operation, entry: enumValue(value.entry, enums.entry, `${label}.entry`), parameterPaths: paths(value.parameterPaths, `${label}.parameterPaths`), authentication: authentication(value.authentication, `${label}.authentication`), credentialPaths: stringList(value.credentialPaths, `${label}.credentialPaths`, true), destinationPaths: stringList(value.destinationPaths, `${label}.destinationPaths`, true), effects: sortedUnique(dense(value.effects, `${label}.effects`).map((item, index) => enumValue(item, enums.effect, `${label}.effects[${index}]`)), `${label}.effects`) as readonly SemanticEffectV2[], endpoints: endpoints(value.endpoints, `${label}.endpoints`), ports: ports(value.ports, `${label}.ports`), overwritePaths: stringList(value.overwritePaths, `${label}.overwritePaths`, true), errorMode: enumValue(value.errorMode, enums.errorMode, `${label}.errorMode`), retryMode: enumValue(value.retryMode, enums.retryMode, `${label}.retryMode`), disabledMode: enumValue(value.disabledMode, enums.disabledMode, `${label}.disabledMode`), provenance: provenance(value.provenance, `${label}.provenance`) }; return Object.freeze(result) as ResolvedNodeSemanticsV2; }\nfunction freeze<T>(value: T, seen = new WeakSet<object>()): T { if (value !== null && typeof value === 'object') { if (seen.has(value)) return value; seen.add(value); for (const name of Object.getOwnPropertyNames(value)) { const descriptor = Object.getOwnPropertyDescriptor(value, name); if (descriptor && 'value' in descriptor) freeze(descriptor.value, seen); } Object.freeze(value); } return value; }\nfunction preflight(input: unknown, seen = new Set<object>(), depth = 0): void {\n if (input === null || typeof input !== 'object') return;\n if (depth > 256 || seen.has(input)) return fail('UNSAFE_INPUT');\n seen.add(input);\n try {\n const proto = Object.getPrototypeOf(input); if (Array.isArray(input) ? proto !== Array.prototype : proto !== Object.prototype && proto !== null) return fail('UNSAFE_INPUT');\n const names = Object.getOwnPropertyNames(input); if (names.length > MAX_ITEMS || Object.getOwnPropertySymbols(input).length !== 0) return fail('UNSAFE_INPUT');\n if (Array.isArray(input)) {\n const length = Object.getOwnPropertyDescriptor(input, 'length');\n if (!length || !('value' in length) || typeof length.value !== 'number' || !Number.isSafeInteger(length.value) || length.value < 0 || length.value > MAX_ITEMS || names.length !== length.value + 1) return fail('UNSAFE_INPUT');\n for (const name of names) if (name !== 'length' && (!/^(0|[1-9]\\d*)$/.test(name) || Number(name) >= length.value)) return fail('UNSAFE_INPUT');\n }\n for (const name of names) { if (name === 'length' && Array.isArray(input)) continue; const descriptor = Object.getOwnPropertyDescriptor(input, name); if (!descriptor || !('value' in descriptor)) return fail('UNSAFE_INPUT'); preflight(descriptor.value, seen, depth + 1); }\n } catch (error) { if (error instanceof SemanticCatalogueAdmissionError) throw error; return fail('UNSAFE_INPUT'); } finally { seen.delete(input); }\n}\nfunction body(input: unknown): SemanticCatalogueBodyV2 {\n const value = own(input, TOP, 'catalogue'); required(value, TOP.slice(0, -1), 'catalogue');\n if (value.schemaVersion !== 'scanner-semantics-v2') return fail('INVALID_SCHEMA_VERSION');\n const version = text(value.version, 'catalogue.version', 128);\n try { parseStrictSemver(version); } catch { return fail('INVALID_VERSION', 'catalogue.version'); }\n const records = dense(value.records, 'catalogue.records').map((item, index) => record(item, `catalogue.records[${index}]`));\n const ids = new Set<string>(); const recordsByKey = new Map<string, ResolvedNodeSemanticsV2>(); const recordsByScope = new Map<string, ResolvedNodeSemanticsV2[]>();\n for (const item of records) {\n if (ids.has(item.semanticId)) return fail('DUPLICATE_ID', item.semanticId); ids.add(item.semanticId);\n const scope = `${item.nodeType}\\0${item.operation ?? ''}`;\n const key = `${scope}\\0${canonicalizeJson(item.versionRange)}`;\n const prior = recordsByKey.get(key);\n if (prior !== undefined) return fail(canonicalizeJson(prior) === canonicalizeJson(item) ? 'DUPLICATE_RECORD' : 'SEMANTIC_CATALOGUE_AMBIGUOUS', item.semanticId);\n const scoped = recordsByScope.get(scope) ?? [];\n for (const candidate of scoped) {\n if (overlap(candidate.versionRange, item.versionRange) && !subset(candidate.versionRange, item.versionRange) && !subset(item.versionRange, candidate.versionRange)) {\n return fail('SEMANTIC_CATALOGUE_AMBIGUOUS', item.semanticId);\n }\n }\n recordsByKey.set(key, item); scoped.push(item); recordsByScope.set(scope, scoped);\n }\n records.sort((a, b) => compare(canonicalizeJson(a), canonicalizeJson(b)));\n return Object.freeze({ schemaVersion: 'scanner-semantics-v2', id: text(value.id, 'catalogue.id', 512), version, records: Object.freeze(records), configurationKeys: sortedUnique(dense(value.configurationKeys, 'configurationKeys').map((item, index) => text(item, `configurationKeys[${index}]`)), 'configurationKeys') });\n}\nexport function createSemanticCatalogueDigest(value: SemanticCatalogueBodyV2): string { return bytesToHex(sha256(canonicalJsonBytes(body(value)))); }\nexport const createCatalogueDigest = createSemanticCatalogueDigest;\nexport function admitSemanticCatalogue(input: unknown): SemanticCatalogueV2 { try { preflight(input); const normalized = body(input); const value = own(input, TOP, 'catalogue'); const digest = text(value.digest, 'catalogue.digest', 64); if (!DIGEST.test(digest)) return fail('DIGEST_MISMATCH', 'catalogue.digest'); const expected = createSemanticCatalogueDigest(normalized); if (digest !== expected) return fail('DIGEST_MISMATCH'); return freeze({ ...normalized, digest }) as SemanticCatalogueV2; } catch (error) { if (error instanceof SemanticCatalogueAdmissionError) throw error; return fail('UNSAFE_INPUT'); } }\n", "{\n \"schemaVersion\": \"semantic-source-receipts-v1\",\n \"note\": \"Identity-only provenance receipts for the two pinned upstream packages that the built-in semantic catalogue records describe. Every file digest below is a SHA-256 computed from the published npm tarball on 2026-10-17 by the AI review worker for packet B1a (review identity: scanner-core-semantics-review; this is an agent review, not a human sign-off); the upstream bytes are deliberately not retained in this repository. Deviation from the plan's retained-snapshot wording, with reason: n8n-nodes-base and @n8n/n8n-nodes-langchain are published under 'SEE LICENSE IN LICENSE.md', which is not an OSI licence, so no upstream source bytes may be copied into this repository and the repository's link-only rights posture applies (same class of reason as RULING-2). The receipt therefore binds package name, version, tarball URL and digest, registry integrity, per-file path, byte length and SHA-256, review date and review identity, with a documented re-fetch command in docs/audit/2026-10-17-remediation/B1a-report.md, without retaining the bytes. documentsRecords maps each catalogue semanticId to the upstream files that were reviewed for that record's claims.\",\n \"packages\": [\n {\n \"package\": \"n8n-nodes-base\",\n \"version\": \"2.15.1\",\n \"registry\": \"https://registry.npmjs.org\",\n \"tarballUrl\": \"https://registry.npmjs.org/n8n-nodes-base/-/n8n-nodes-base-2.15.1.tgz\",\n \"tarballSha256\": \"43e200c1cbe1c4a9f967efa079facb00cc3cbe51ede23c9a3cfc66c9a4051406\",\n \"distIntegrity\": \"sha512-E4/vb8sBb4tzZSFoBAP2EigAHSc3uEn52RdfyTu1C7xPBNLYDfw5y5OxvMmHBQ8of9YQwcK9AQsoEsggyu7ztQ==\",\n \"fetchedAt\": \"2026-10-17\",\n \"files\": [\n {\n \"path\": \"dist/credentials/MySql.credentials.js\",\n \"bytes\": 2661,\n \"sha256\": \"2b887261e175c08a804577a13dad6cd2dc160668cb480ae668f2d04a56b61380\"\n },\n {\n \"path\": \"dist/credentials/Postgres.credentials.js\",\n \"bytes\": 2485,\n \"sha256\": \"8d2f881eb6fa169b1b1fb34059424767df54e717850008274308c08a4077e905\"\n },\n {\n \"path\": \"dist/nodes/Code/Code.node.js\",\n \"bytes\": 7874,\n \"sha256\": \"b86fceda544451fce8dbdadf7f68c0417b79f1d6f3a79d6986d5f0f2d0027289\"\n },\n {\n \"path\": \"dist/nodes/Code/descriptions/JavascriptCodeDescription.js\",\n \"bytes\": 2136,\n \"sha256\": \"8ac750eb00492b3cb8ffbb7d4165489370f965aab45b1cb50b72ace59dbd8452\"\n },\n {\n \"path\": \"dist/nodes/EmailSend/EmailSend.node.js\",\n \"bytes\": 1004,\n \"sha256\": \"d76e18808343c4d0a7c35db3213e8e69bdb684cdda5c613e60b184da12c76b4c\"\n },\n {\n \"path\": \"dist/nodes/EmailSend/v2/EmailSendV2.node.js\",\n \"bytes\": 4489,\n \"sha256\": \"712169b216a6edc2d2a10ec378bd6ae8871a1ecb76387e670eacb78a113bc37a\"\n },\n {\n \"path\": \"dist/nodes/EmailSend/v2/descriptions.js\",\n \"bytes\": 759,\n \"sha256\": \"5516434cbebe759f4620cd1d06453e01e0a19f09282b9726467ea3274f8bfefa\"\n },\n {\n \"path\": \"dist/nodes/EmailSend/v2/send.operation.js\",\n \"bytes\": 8807,\n \"sha256\": \"6faad70b99bc41f757bb53f02784a5925cba8b9d33246d785ba613a47ff13134\"\n },\n {\n \"path\": \"dist/nodes/ExecuteCommand/ExecuteCommand.node.js\",\n \"bytes\": 3666,\n \"sha256\": \"e710b4f054ecb8002dd3fe6d02f977bce00fb0722d23b7cc7c2c8bcc8834338a\"\n },\n {\n \"path\": \"dist/nodes/ExecuteWorkflow/ExecuteWorkflow/ExecuteWorkflow.node.js\",\n \"bytes\": 19378,\n \"sha256\": \"5f351ab2c88cfc14d192530ccdb869ccaee135d8267a1491535037b4011b28a0\"\n },\n {\n \"path\": \"dist/nodes/ExecuteWorkflow/ExecuteWorkflowTrigger/ExecuteWorkflowTrigger.node.js\",\n \"bytes\": 10448,\n \"sha256\": \"e75d626746d865a458d57c496d85c444fa72a73a7ade7e6018f91e2f6b9e7195\"\n },\n {\n \"path\": \"dist/nodes/Form/FormTrigger.node.js\",\n \"bytes\": 1372,\n \"sha256\": \"86c7128a1256494968b7fff4908e36956447eb23b09cfca8c5cfb15f6b008a9f\"\n },\n {\n \"path\": \"dist/nodes/Form/common.descriptions.js\",\n \"bytes\": 24412,\n \"sha256\": \"36e8efc3f3f2cb6030aaeec30bac9ac3c564fc6fa54607c209adf7c708c0b6fa\"\n },\n {\n \"path\": \"dist/nodes/Form/v2/FormTriggerV2.node.js\",\n \"bytes\": 7991,\n \"sha256\": \"4c20e9dd7b48d7019c1f30762dfa6e0261f050c7328a38901dcf0b64b3585941\"\n },\n {\n \"path\": \"dist/nodes/Git/Git.node.js\",\n \"bytes\": 28226,\n \"sha256\": \"c42647afb36dcf5abe558c29090d8edeb26932f3e53c01db250b58fa35b2a9f7\"\n },\n {\n \"path\": \"dist/nodes/Git/descriptions/CloneDescription.js\",\n \"bytes\": 567,\n \"sha256\": \"d7931770204f7d8416124ea47e62ef8afbb8b86a64d98af6adfdbe0a2538e270\"\n },\n {\n \"path\": \"dist/nodes/Git/descriptions/CommitDescription.js\",\n \"bytes\": 1492,\n \"sha256\": \"022963b6ed776114e1e5f488019a912651b5e14f3d40c559ab9d8857066bf540\"\n },\n {\n \"path\": \"dist/nodes/Git/descriptions/PushDescription.js\",\n \"bytes\": 1106,\n \"sha256\": \"710634a4f149c7f6e57b72ad3ce99c261d62f0fb4bf0fc430f6c602ca7b36540\"\n },\n {\n \"path\": \"dist/nodes/HttpRequest/HttpRequest.node.js\",\n \"bytes\": 2163,\n \"sha256\": \"7a516ec8527fbb7c209c489fc05cb7fd6f2b32baff838ac4f5230a08e9d2e6db\"\n },\n {\n \"path\": \"dist/nodes/HttpRequest/V3/Description.js\",\n \"bytes\": 45912,\n \"sha256\": \"8b9f0334842600a60d9f23bd07de163142b66075fda9f0d191433cb86b9ace2f\"\n },\n {\n \"path\": \"dist/nodes/HttpRequest/V3/HttpRequestV3.node.js\",\n \"bytes\": 45490,\n \"sha256\": \"00b6f6963b3487b1607dd4731a877fa4e7ce1d8822795a27fb6c4bcf1f902885\"\n },\n {\n \"path\": \"dist/nodes/ManualTrigger/ManualTrigger.node.js\",\n \"bytes\": 1509,\n \"sha256\": \"aa3151c441a98c2b047ddbb64266bdee8d383aea890b29368124ff4e831af1e4\"\n },\n {\n \"path\": \"dist/nodes/MySql/MySql.node.js\",\n \"bytes\": 1259,\n \"sha256\": \"11f0dd39f78221f9f6e0c4dce4e024c7ea9db47268dca640a0d5f25b32f94ea3\"\n },\n {\n \"path\": \"dist/nodes/MySql/v2/actions/database/Database.resource.js\",\n \"bytes\": 4320,\n \"sha256\": \"bf7a1c2d5b1231fc7e11f3cefee10b7e0f38606826df57beff7bc6277b76eb4a\"\n },\n {\n \"path\": \"dist/nodes/MySql/v2/actions/database/executeQuery.operation.js\",\n \"bytes\": 2918,\n \"sha256\": \"4c1c388c764f4ed8fd4802d48da3a162a19a4d730c2e783e2a8e5a6a64e63db8\"\n },\n {\n \"path\": \"dist/nodes/MySql/v2/actions/versionDescription.js\",\n \"bytes\": 2745,\n \"sha256\": \"3a9307265ff4d0c8197883da853dd664a494cd2b8230449e135a6309ea434c82\"\n },\n {\n \"path\": \"dist/nodes/NoOp/NoOp.node.js\",\n \"bytes\": 813,\n \"sha256\": \"015ada9acac98a289039faf2ee2f55ba6c0f3f414f467c269cc6c65a5bdd045e\"\n },\n {\n \"path\": \"dist/nodes/NoOp/NoOp.node.json\",\n \"bytes\": 2666,\n \"sha256\": \"ec5012a56869016dc99ecdddd3df25ffe630a8ec5a3398141d75e06fc9dbc6a4\"\n },\n {\n \"path\": \"dist/nodes/OpenAi/ChatDescription.js\",\n \"bytes\": 14151,\n \"sha256\": \"540f8dd69bb38c25eb82c514c688fc21161f711de404e146306cd4fbf9c01903\"\n },\n {\n \"path\": \"dist/nodes/OpenAi/OpenAi.node.js\",\n \"bytes\": 2803,\n \"sha256\": \"a2e5f5722375b520c2c689670d6b3b16c0f693e0f16300a8c1ca47e57d3089dd\"\n },\n {\n \"path\": \"dist/nodes/OpenAi/TextDescription.js\",\n \"bytes\": 17012,\n \"sha256\": \"f2d22bf998130bd40c034a58fdb6a06c48bf7c98e6af250bc2e0187cdce86cee\"\n },\n {\n \"path\": \"dist/nodes/Postgres/Postgres.node.js\",\n \"bytes\": 1368,\n \"sha256\": \"54c0194e046a08723991d4baa747bbade7ea95e2e6713ef2218329f6e0bed260\"\n },\n {\n \"path\": \"dist/nodes/Postgres/v2/actions/database/Database.resource.js\",\n \"bytes\": 4404,\n \"sha256\": \"629948e576cdba7cbe1e5d16b9622f7f72bff2161d52533033aa5b82b1ff250d\"\n },\n {\n \"path\": \"dist/nodes/Postgres/v2/actions/database/executeQuery.operation.js\",\n \"bytes\": 4985,\n \"sha256\": \"0de44810a69b1c89d2d430882a064a39f1587fd0f565e2997506f37070fc7b38\"\n },\n {\n \"path\": \"dist/nodes/Postgres/v2/actions/versionDescription.js\",\n \"bytes\": 2731,\n \"sha256\": \"71cd65f264791a3debf9db37320903f3e7726cdb96e426eb9099c5aa23a702c7\"\n },\n {\n \"path\": \"dist/nodes/ReadBinaryFile/ReadBinaryFile.node.js\",\n \"bytes\": 3211,\n \"sha256\": \"ff3b4d896ab2a0b72be74497a0bff1ae134e700db0f697eed310863a455a3576\"\n },\n {\n \"path\": \"dist/nodes/Slack/Slack.node.js\",\n \"bytes\": 1193,\n \"sha256\": \"852da1fc867bfc03d01ddac6e1acdf96c1b8e185db4c556aef89984c40591069\"\n },\n {\n \"path\": \"dist/nodes/Slack/V2/MessageDescription.js\",\n \"bytes\": 37505,\n \"sha256\": \"d1583a16230dad669ccc91acb2ab5c422850d652ccfbfd0adf5593b58b596103\"\n },\n {\n \"path\": \"dist/nodes/Slack/V2/SlackV2.node.js\",\n \"bytes\": 58179,\n \"sha256\": \"902cff7c1bcb4ce3c5fc601cc977d29702558abfa0c9673ebe0716f304b5a49d\"\n },\n {\n \"path\": \"dist/nodes/Webhook/Webhook.node.js\",\n \"bytes\": 13110,\n \"sha256\": \"402d01fdd04a2a71738c189e0b76a87415978bb414660f13fd9c2ece96ee3e37\"\n },\n {\n \"path\": \"dist/nodes/Webhook/description.js\",\n \"bytes\": 15348,\n \"sha256\": \"0bca9f9b690a9965bc8ce05c56c7532430eb4c839198b07eafd4b175850595cb\"\n },\n {\n \"path\": \"dist/nodes/WriteBinaryFile/WriteBinaryFile.node.js\",\n \"bytes\": 4588,\n \"sha256\": \"c495d4696d5f051ffed6a622442405429c344593bee70d4b129997c33334d11f\"\n },\n {\n \"path\": \"dist/utils/workflowInputsResourceMapping/constants.js\",\n \"bytes\": 1022,\n \"sha256\": \"14930146d4c928a51815eeba1f057f2d86de0243578e62512ebd6e43b56eeefd\"\n },\n {\n \"path\": \"dist/nodes/Set/Set.node.js\",\n \"bytes\": 1161,\n \"sha256\": \"05fb602270c01e7244291b7e9fa04d60d7aa9ba0f2ecfc2dbd11741c71cc6722\"\n },\n {\n \"path\": \"dist/nodes/Set/v1/SetV1.node.js\",\n \"bytes\": 8069,\n \"sha256\": \"8a2c21be95ce48161465e787a6a7ccaf3f90c15010af19ce23626d8b470db146\"\n },\n {\n \"path\": \"dist/nodes/Set/v2/SetV2.node.js\",\n \"bytes\": 14293,\n \"sha256\": \"cc71e353359e4107787cfaafb0f5ec6fc5c7416efb4f43f61139f835d32593ec\"\n },\n {\n \"path\": \"dist/nodes/If/If.node.js\",\n \"bytes\": 1044,\n \"sha256\": \"8690fc5d4a28a6267a21e95adeffd0d48f36ea28ff1657943a48eae81d7cc6f4\"\n },\n {\n \"path\": \"dist/nodes/If/V1/IfV1.node.js\",\n \"bytes\": 22171,\n \"sha256\": \"790fc1cb6065f24eb670e15ada6876ad1f21d21006f94c290f855a39d10cb036\"\n },\n {\n \"path\": \"dist/nodes/If/V2/IfV2.node.js\",\n \"bytes\": 5145,\n \"sha256\": \"6b7ed12d8da084049c4ffb7cd04bb5529c0ea757c7dd7aeb103123d9e38b40ad\"\n },\n {\n \"path\": \"dist/nodes/Switch/Switch.node.js\",\n \"bytes\": 1320,\n \"sha256\": \"d71978230704fb4cc865d3ee0e00b824273324d5196991aba202584cd034c080\"\n },\n {\n \"path\": \"dist/nodes/Switch/V1/SwitchV1.node.js\",\n \"bytes\": 28845,\n \"sha256\": \"3f97bb96782c26c2299fd98ead79e5ae9585ad3d8e01b58def3813a9dac4f5dd\"\n },\n {\n \"path\": \"dist/nodes/Switch/V2/SwitchV2.node.js\",\n \"bytes\": 29354,\n \"sha256\": \"124637d7cf57fa6b61323bdd4c9bff9b4b2cc26e7c5d4fd472f47f378497f289\"\n },\n {\n \"path\": \"dist/nodes/Switch/V3/SwitchV3.node.js\",\n \"bytes\": 18071,\n \"sha256\": \"7cdfe9d3773fa7f78d8ffc7ce0a66f85f48d30dc4cf2d87c1ed63f747dc63fbf\"\n },\n {\n \"path\": \"dist/nodes/Merge/Merge.node.js\",\n \"bytes\": 1257,\n \"sha256\": \"3c32794aae7af1277d689bbaa6b013f4d5f80141625a61d363d45937215bb777\"\n },\n {\n \"path\": \"dist/nodes/Merge/v1/MergeV1.node.js\",\n \"bytes\": 19431,\n \"sha256\": \"e6ffc04766805f99950dbe5710a727755c7fb222a4fb4d36ea5951a7072e1d67\"\n },\n {\n \"path\": \"dist/nodes/Merge/v2/MergeV2.node.js\",\n \"bytes\": 23341,\n \"sha256\": \"b280182890e773550276b809ba1d9f8ee353372c89079a74e2a3086afb38e28c\"\n },\n {\n \"path\": \"dist/nodes/Merge/v3/MergeV3.node.js\",\n \"bytes\": 674,\n \"sha256\": \"d5c9edbb8c4a7b12e238f22bbecd3081a3ab846f94d83239b3c1295c61e56c2d\"\n },\n {\n \"path\": \"dist/nodes/SplitInBatches/SplitInBatches.node.js\",\n \"bytes\": 1172,\n \"sha256\": \"93c3f12852542f08f58f2d71277916eba6f524898b8e410c9b7466f06cc144b9\"\n },\n {\n \"path\": \"dist/nodes/SplitInBatches/v1/SplitInBatchesV1.node.js\",\n \"bytes\": 4673,\n \"sha256\": \"25ccdb50dd10f982af270c8681d727924460ef989ae49123eb198608308c5002\"\n },\n {\n \"path\": \"dist/nodes/SplitInBatches/v2/SplitInBatchesV2.node.js\",\n \"bytes\": 5350,\n \"sha256\": \"279f601f57541c2a2598b79a8eac0d505a0ce09c0471048216fe8ea6d49202be\"\n },\n {\n \"path\": \"dist/nodes/SplitInBatches/v3/SplitInBatchesV3.node.js\",\n \"bytes\": 5471,\n \"sha256\": \"753a1ecaa7f2e9de387212b26e5b6b3e0d827b4190184e32947aad7bdb8ef2bb\"\n },\n {\n \"path\": \"dist/nodes/Schedule/ScheduleTrigger.node.js\",\n \"bytes\": 23132,\n \"sha256\": \"bac9111de5ea6cf97cbfbcf4253f524eadb94979586b253962723a23110c3919\"\n },\n {\n \"path\": \"dist/nodes/Google/Sheet/GoogleSheets.node.js\",\n \"bytes\": 2229,\n \"sha256\": \"af00ac359dfefa93783bc9f559259d1ebc5f4c41065077547f89cec1d7a1b94a\"\n },\n {\n \"path\": \"dist/nodes/Google/Sheet/v1/GoogleSheetsV1.node.js\",\n \"bytes\": 18853,\n \"sha256\": \"ade3d4012749f407ba3370318b6a7c5538bc78596ef130103e397499ce5b31ad\"\n },\n {\n \"path\": \"dist/nodes/Google/Sheet/v2/GoogleSheetsV2.node.js\",\n \"bytes\": 853,\n \"sha256\": \"de4c47cdaeb1019a8711ed385a24ed690ce1498123ef2426d3bf70472b96ca91\"\n },\n {\n \"path\": \"dist/nodes/Google/Sheet/v2/actions/versionDescription.js\",\n \"bytes\": 5546,\n \"sha256\": \"71408af602bd2f915426b963d3e2d88f197e80bf528cca2ec1400fa01b0d97c7\"\n },\n {\n \"path\": \"dist/nodes/Google/Sheet/v2/actions/sheet/read.operation.js\",\n \"bytes\": 5830,\n \"sha256\": \"3dace7a812e6c322b92572cef4d47429c0112931096203d4313c306cfe39edbb\"\n },\n {\n \"path\": \"dist/nodes/Google/Sheet/v2/actions/sheet/append.operation.js\",\n \"bytes\": 9449,\n \"sha256\": \"be18d376b86460f5e884de130705bb317d9a35011a3fdd3ac2fec06b05e8a993\"\n },\n {\n \"path\": \"dist/nodes/Google/Sheet/v2/actions/sheet/update.operation.js\",\n \"bytes\": 15965,\n \"sha256\": \"29c92be3cd21dfd117134700911d3511b69d3f4cdb9308dc96af9b9ecc5d565f\"\n },\n {\n \"path\": \"dist/nodes/Google/Sheet/v2/helpers/GoogleSheet.js\",\n \"bytes\": 24180,\n \"sha256\": \"70e477ba7d00aaf39290e4b53b9134c5ef4a4771cba78b17156c94c3a23100c5\"\n },\n {\n \"path\": \"dist/nodes/Google/Sheet/v2/actions/router.js\",\n \"bytes\": 3948,\n \"sha256\": \"c78e0e050f752b04d286cf3d1e0231fa5d16061abc0676ae9bc72e78c6df399c\"\n },\n {\n \"path\": \"dist/nodes/Google/Gmail/Gmail.node.js\",\n \"bytes\": 1474,\n \"sha256\": \"51d583d04cfa9ed2f8e71e0ebb1ea4c68545470f673fa53467f4ee17fcb6db5b\"\n },\n {\n \"path\": \"dist/nodes/Google/Gmail/v2/GmailV2.node.js\",\n \"bytes\": 33094,\n \"sha256\": \"43ab5dff34987ab01175fc832a35190f0c9a1d172a0830a05c538c9a6c7071a7\"\n },\n {\n \"path\": \"dist/node-definitions/nodes/n8n-nodes-base/gmail/v1/index.schema.js\",\n \"bytes\": 1128,\n \"sha256\": \"78a51412dbf0119e846a137b4ca3855cca480deb5a7f54694d3965b5b2008376\"\n },\n {\n \"path\": \"dist/node-definitions/nodes/n8n-nodes-base/gmail/v2/index.schema.js\",\n \"bytes\": 1111,\n \"sha256\": \"346a9b3f9166c8b1a4749c49cdb6729a4c8a14490524067d4aadbdbb58bd66d8\"\n },\n {\n \"path\": \"dist/node-definitions/nodes/n8n-nodes-base/gmail/v21/index.schema.js\",\n \"bytes\": 1113,\n \"sha256\": \"ebcad04fe71130c425d963bf7fa0ed69ea692e3a9fa6e2f17d9c8b7002a6d9df\"\n },\n {\n \"path\": \"dist/node-definitions/nodes/n8n-nodes-base/gmail/v22/index.schema.js\",\n \"bytes\": 1113,\n \"sha256\": \"cea2ae376538c3009fd94346ded5f10a8fd4c85fde1121edd82540436f39de5c\"\n },\n {\n \"path\": \"dist/credentials/GmailOAuth2Api.credentials.js\",\n \"bytes\": 917,\n \"sha256\": \"d26a4ac3387ceec1f0edfe09c9d9a375dda82825b4588c8a35edf9e5ff5e4fb6\"\n },\n {\n \"path\": \"dist/nodes/Wait/Wait.node.js\",\n \"bytes\": 21116,\n \"sha256\": \"8b45af6d1167e83ae2c39e0778a07863080806cd7844dce613689ecf09a0f63f\"\n },\n {\n \"path\": \"dist/node-definitions/nodes/n8n-nodes-base/wait/v1.schema.js\",\n \"bytes\": 7719,\n \"sha256\": \"1d136e35600febc0124585e6483e4e453101b748947455c4275973ff69f5e355\"\n },\n {\n \"path\": \"dist/node-definitions/nodes/n8n-nodes-base/wait/v11.schema.js\",\n \"bytes\": 7721,\n \"sha256\": \"6dc663befce6251b1ecc7906510460b9a5dc260209858f6c8e4ce4e140f8ab65\"\n },\n {\n \"path\": \"dist/nodes/Telegram/Telegram.node.js\",\n \"bytes\": 92819,\n \"sha256\": \"9e3d1e7db6df87ac6ee7648e2d67d52ab9aafdf87e09503fb2f0ce774c206a9a\"\n },\n {\n \"path\": \"dist/node-definitions/nodes/n8n-nodes-base/telegram/v1/index.schema.js\",\n \"bytes\": 1114,\n \"sha256\": \"0b6219091e0481eff54e45098dd86d233da61954b24d3fa9a7dc52de3a9b3351\"\n },\n {\n \"path\": \"dist/node-definitions/nodes/n8n-nodes-base/telegram/v11/index.schema.js\",\n \"bytes\": 1116,\n \"sha256\": \"06d4c646a0aeee2f4d01674e3ab725aef3377253e33061cd02d169791e0d5dce\"\n },\n {\n \"path\": \"dist/node-definitions/nodes/n8n-nodes-base/telegram/v12/index.schema.js\",\n \"bytes\": 1116,\n \"sha256\": \"7ee3807d5b76829555b55ab27bb459f2ccbd43e8e489fbaa678a55af852307c7\"\n },\n {\n \"path\": \"dist/credentials/TelegramApi.credentials.js\",\n \"bytes\": 1034,\n \"sha256\": \"5b14055bf4688b6a56cac314e9c6ca7937bdd6e7a9067f043ccadaae33016fe5\"\n },\n {\n \"path\": \"dist/nodes/Transform/SplitOut/SplitOut.node.js\",\n \"bytes\": 10605,\n \"sha256\": \"9b367f65f121c5571d9daecd9df9bb609d7c2de013555bfa2af2fab62d5bd057\"\n },\n {\n \"path\": \"dist/node-definitions/nodes/n8n-nodes-base/splitOut/v1.schema.js\",\n \"bytes\": 1431,\n \"sha256\": \"b4937c0a04a9ef31a9a4deb6628d7a84c64b468163e909b9df1fd603a83a5f31\"\n }\n ]\n },\n {\n \"package\": \"@n8n/n8n-nodes-langchain\",\n \"version\": \"2.43.5\",\n \"registry\": \"https://registry.npmjs.org\",\n \"tarballUrl\": \"https://registry.npmjs.org/@n8n/n8n-nodes-langchain/-/n8n-nodes-langchain-2.43.5.tgz\",\n \"tarballSha256\": \"63a7a9108d2c944e278ed1389c4eacf8e8dc309a649442d704e316d266c360b7\",\n \"distIntegrity\": \"sha512-TuAopltLsyCBbalz4fUvD0/Bdcvjl4MaoWAz2XvijP4fDR7dkbzYXhuKYwBU/rZg7LioouAktR8t3djG0m766w==\",\n \"fetchedAt\": \"2026-10-17\",\n \"files\": [\n {\n \"path\": \"dist/nodes/agents/Agent/Agent.node.js\",\n \"bytes\": 7126,\n \"sha256\": \"4b37709cb6c170e5a92d54870d6d7b75b7df7f8931ee4c84c5d5123b4a14c777\"\n },\n {\n \"path\": \"dist/nodes/agents/Agent/agents/ToolsAgent/V3/description.js\",\n \"bytes\": 1742,\n \"sha256\": \"17a8b4999dd8ae7199cf8527e0501cb1b68cbaa953e338f6486be60d5a6dc2b6\"\n },\n {\n \"path\": \"dist/nodes/agents/Agent/agents/ToolsAgent/options.js\",\n \"bytes\": 6352,\n \"sha256\": \"bcf373fa125fa545ef1c98972a21db70834dc792d9f7b20d29543a6411ac41fe\"\n },\n {\n \"path\": \"dist/nodes/code/Code.node.js\",\n \"bytes\": 16924,\n \"sha256\": \"fe6912416ed6ccf16ff777162681c00bceaffe76284c809f8e5096aa14a3e123\"\n },\n {\n \"path\": \"dist/nodes/llms/LMChatOpenAi/LmChatOpenAi.node.js\",\n \"bytes\": 40036,\n \"sha256\": \"5fdb1f45f58b27a75baee66ad066316dacd79c2585684fd9b292b9b312f43562\"\n },\n {\n \"path\": \"dist/nodes/mcp/McpClientTool/McpClientTool.node.js\",\n \"bytes\": 10891,\n \"sha256\": \"19eaeece51b0e6fc56d02c9704c77da1eedf53226e2663efb7be30aab3d1e1d5\"\n },\n {\n \"path\": \"dist/nodes/tools/ToolCode/ToolCode.node.js\",\n \"bytes\": 11554,\n \"sha256\": \"f7d0886d66ed93533a577fa415dc2dadb66e4493eec97b27dd6f27dbca31ed7b\"\n },\n {\n \"path\": \"dist/nodes/tools/ToolWorkflow/ToolWorkflow.node.js\",\n \"bytes\": 1985,\n \"sha256\": \"98e79b8f438ac669b0635a7c921be418dade424c6531bfd5dd21de6a68b1d692\"\n },\n {\n \"path\": \"dist/nodes/tools/ToolWorkflow/v2/versionDescription.js\",\n \"bytes\": 4790,\n \"sha256\": \"02b194c5da74b3c238eee4b6d904eceaa8b823d7a0e92e1e284d7514ae727d7c\"\n },\n {\n \"path\": \"dist/nodes/trigger/ChatTrigger/ChatTrigger.node.js\",\n \"bytes\": 48392,\n \"sha256\": \"498f05b57eb73e9f2a00f330c37a12a696016a7808480d332fe883c58d17eaca\"\n },\n {\n \"path\": \"dist/nodes/output_parser/OutputParserStructured/OutputParserStructured.node.js\",\n \"bytes\": 8612,\n \"sha256\": \"1de5e957d3f4d8f89638d18c15b718c8ebd5c20624d471953cdc5109e9b54c32\"\n },\n {\n \"path\": \"dist/node-definitions/nodes/n8n-nodes-langchain/outputParserStructured/v1.schema.js\",\n \"bytes\": 2172,\n \"sha256\": \"1da2069dbc726eca4af1859fa5bc86ef89acb05d00eefa9deb9a6cb9c5854dc8\"\n }\n ]\n }\n ],\n \"documentsRecords\": {\n \"ingress.webhook\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/Webhook/Webhook.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Webhook/description.js\"\n ],\n \"ingress.form-trigger\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/Form/FormTrigger.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Form/v2/FormTriggerV2.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Form/common.descriptions.js\"\n ],\n \"ingress.chat-trigger\": [\n \"@n8n/n8n-nodes-langchain@2.43.5:dist/nodes/trigger/ChatTrigger/ChatTrigger.node.js\"\n ],\n \"ingress.manual-trigger\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/ManualTrigger/ManualTrigger.node.js\"\n ],\n \"http-ai.http-request\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/HttpRequest/HttpRequest.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/HttpRequest/V3/Description.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/HttpRequest/V3/HttpRequestV3.node.js\"\n ],\n \"http-ai.http-request.request\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/HttpRequest/HttpRequest.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/HttpRequest/V3/Description.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/HttpRequest/V3/HttpRequestV3.node.js\"\n ],\n \"http-ai.openai\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/OpenAi/OpenAi.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/OpenAi/TextDescription.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/OpenAi/ChatDescription.js\"\n ],\n \"http-ai.ai-agent\": [\n \"@n8n/n8n-nodes-langchain@2.43.5:dist/nodes/agents/Agent/Agent.node.js\",\n \"@n8n/n8n-nodes-langchain@2.43.5:dist/nodes/agents/Agent/agents/ToolsAgent/options.js\",\n \"@n8n/n8n-nodes-langchain@2.43.5:dist/nodes/agents/Agent/agents/ToolsAgent/V3/description.js\"\n ],\n \"http-ai.chat-model\": [\n \"@n8n/n8n-nodes-langchain@2.43.5:dist/nodes/llms/LMChatOpenAi/LmChatOpenAi.node.js\"\n ],\n \"database-file.postgres\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/Postgres/Postgres.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Postgres/v2/actions/database/Database.resource.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Postgres/v2/actions/database/executeQuery.operation.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Postgres/v2/actions/versionDescription.js\",\n \"n8n-nodes-base@2.15.1:dist/credentials/Postgres.credentials.js\"\n ],\n \"database-file.mysql\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/MySql/MySql.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/MySql/v2/actions/database/Database.resource.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/MySql/v2/actions/database/executeQuery.operation.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/MySql/v2/actions/versionDescription.js\",\n \"n8n-nodes-base@2.15.1:dist/credentials/MySql.credentials.js\"\n ],\n \"database-file.read-binary-file\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/ReadBinaryFile/ReadBinaryFile.node.js\"\n ],\n \"database-file.write-binary-file\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/WriteBinaryFile/WriteBinaryFile.node.js\"\n ],\n \"code-command.execute-command\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/ExecuteCommand/ExecuteCommand.node.js\"\n ],\n \"code-command.code\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/Code/Code.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Code/descriptions/JavascriptCodeDescription.js\"\n ],\n \"code-command.langchain-tool-code\": [\n \"@n8n/n8n-nodes-langchain@2.43.5:dist/nodes/tools/ToolCode/ToolCode.node.js\"\n ],\n \"code-command.langchain-code\": [\n \"@n8n/n8n-nodes-langchain@2.43.5:dist/nodes/code/Code.node.js\"\n ],\n \"message-mcp.slack\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/Slack/Slack.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Slack/V2/SlackV2.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Slack/V2/MessageDescription.js\"\n ],\n \"message-mcp.email-send\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/EmailSend/EmailSend.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/EmailSend/v2/EmailSendV2.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/EmailSend/v2/descriptions.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/EmailSend/v2/send.operation.js\"\n ],\n \"message-mcp.tool-mcp\": [\n \"@n8n/n8n-nodes-langchain@2.43.5:dist/nodes/mcp/McpClientTool/McpClientTool.node.js\"\n ],\n \"subworkflow.execute-workflow-trigger\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/ExecuteWorkflow/ExecuteWorkflowTrigger/ExecuteWorkflowTrigger.node.js\",\n \"n8n-nodes-base@2.15.1:dist/utils/workflowInputsResourceMapping/constants.js\"\n ],\n \"subworkflow.execute-workflow\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/ExecuteWorkflow/ExecuteWorkflow/ExecuteWorkflow.node.js\"\n ],\n \"subworkflow.tool-workflow\": [\n \"@n8n/n8n-nodes-langchain@2.43.5:dist/nodes/tools/ToolWorkflow/ToolWorkflow.node.js\",\n \"@n8n/n8n-nodes-langchain@2.43.5:dist/nodes/tools/ToolWorkflow/v2/versionDescription.js\"\n ],\n \"git.git\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/Git/Git.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Git/descriptions/CloneDescription.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Git/descriptions/CommitDescription.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Git/descriptions/PushDescription.js\"\n ],\n \"noop.passthrough\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/NoOp/NoOp.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/NoOp/NoOp.node.json\"\n ],\n \"flow-control.set\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/Set/Set.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Set/v1/SetV1.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Set/v2/SetV2.node.js\"\n ],\n \"flow-control.if\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/If/If.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/If/V1/IfV1.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/If/V2/IfV2.node.js\"\n ],\n \"flow-control.switch\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/Switch/Switch.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Switch/V1/SwitchV1.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Switch/V2/SwitchV2.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Switch/V3/SwitchV3.node.js\"\n ],\n \"flow-control.merge\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/Merge/Merge.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Merge/v1/MergeV1.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Merge/v2/MergeV2.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Merge/v3/MergeV3.node.js\"\n ],\n \"flow-control.split-in-batches\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/SplitInBatches/SplitInBatches.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/SplitInBatches/v1/SplitInBatchesV1.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/SplitInBatches/v2/SplitInBatchesV2.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/SplitInBatches/v3/SplitInBatchesV3.node.js\"\n ],\n \"flow-control.schedule-trigger\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/Schedule/ScheduleTrigger.node.js\"\n ],\n \"google-workspace.google-sheets\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/Google/Sheet/GoogleSheets.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Google/Sheet/v1/GoogleSheetsV1.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Google/Sheet/v2/GoogleSheetsV2.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Google/Sheet/v2/actions/versionDescription.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Google/Sheet/v2/actions/sheet/read.operation.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Google/Sheet/v2/actions/sheet/append.operation.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Google/Sheet/v2/actions/sheet/update.operation.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Google/Sheet/v2/helpers/GoogleSheet.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Google/Sheet/v2/actions/router.js\"\n ],\n \"message-mcp.gmail\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/Google/Gmail/Gmail.node.js\",\n \"n8n-nodes-base@2.15.1:dist/nodes/Google/Gmail/v2/GmailV2.node.js\",\n \"n8n-nodes-base@2.15.1:dist/node-definitions/nodes/n8n-nodes-base/gmail/v1/index.schema.js\",\n \"n8n-nodes-base@2.15.1:dist/node-definitions/nodes/n8n-nodes-base/gmail/v2/index.schema.js\",\n \"n8n-nodes-base@2.15.1:dist/node-definitions/nodes/n8n-nodes-base/gmail/v21/index.schema.js\",\n \"n8n-nodes-base@2.15.1:dist/node-definitions/nodes/n8n-nodes-base/gmail/v22/index.schema.js\",\n \"n8n-nodes-base@2.15.1:dist/credentials/GmailOAuth2Api.credentials.js\"\n ],\n \"flow-control.wait\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/Wait/Wait.node.js\",\n \"n8n-nodes-base@2.15.1:dist/node-definitions/nodes/n8n-nodes-base/wait/v1.schema.js\",\n \"n8n-nodes-base@2.15.1:dist/node-definitions/nodes/n8n-nodes-base/wait/v11.schema.js\"\n ],\n \"message-mcp.telegram\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/Telegram/Telegram.node.js\",\n \"n8n-nodes-base@2.15.1:dist/node-definitions/nodes/n8n-nodes-base/telegram/v1/index.schema.js\",\n \"n8n-nodes-base@2.15.1:dist/node-definitions/nodes/n8n-nodes-base/telegram/v11/index.schema.js\",\n \"n8n-nodes-base@2.15.1:dist/node-definitions/nodes/n8n-nodes-base/telegram/v12/index.schema.js\",\n \"n8n-nodes-base@2.15.1:dist/credentials/TelegramApi.credentials.js\"\n ],\n \"transform.split-out\": [\n \"n8n-nodes-base@2.15.1:dist/nodes/Transform/SplitOut/SplitOut.node.js\",\n \"n8n-nodes-base@2.15.1:dist/node-definitions/nodes/n8n-nodes-base/splitOut/v1.schema.js\"\n ],\n \"ai.output-parser-structured\": [\n \"@n8n/n8n-nodes-langchain@2.43.5:dist/nodes/output_parser/OutputParserStructured/OutputParserStructured.node.js\",\n \"@n8n/n8n-nodes-langchain@2.43.5:dist/node-definitions/nodes/n8n-nodes-langchain/outputParserStructured/v1.schema.js\"\n ]\n }\n}\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport receiptDocument from '../../../../docs/scanner/semantic-source-receipts.json';\nimport { SemanticCatalogueAdmissionError } from './catalogue-admission';\nimport type { SemanticProvenanceV2 } from './catalogue-schema';\n\n/**\n * Built-in semantic catalogue provenance binding (packet B1b, subpacket 1).\n *\n * Before this module, every record's `provenance.sourceDigest` was one of two repeated\n * placeholder strings. The digest is now *derived* from\n * `docs/scanner/semantic-source-receipts.json` (packet B1a), so a changed upstream byte or a\n * changed supporting-file list changes that record's digest, and with it the catalogue digest.\n *\n * Frozen binding rule, pinned by `builtin-catalogue.test.ts`:\n *\n * - `sourceUrl` stays the human-facing n8n documentation page for the node family\n * (`CORE_DOCS`/`LANGCHAIN_DOCS` in the catalogue). This is a deliberate split between the\n * *documentation* URL and the *provenance* digest: the admission contract requires an https\n * URL without credentials, and the receipt's tarball URL is not a page a reader can use.\n * - `sourceDigest` is the canonical digest over the record's supporting files: take the\n * record's `documentsRecords` entries (`<package>@<version>:<path>`), sort them as strings,\n * emit `<entry>:<sha256>` per entry, join with `\\n` and no trailing newline, and hash the\n * UTF-8 bytes. Sorting makes the digest order-insensitive; every entry and every digest\n * inside it changes the result.\n * - `reviewedAt` is the `fetchedAt` of the receipt packages the record's files come from (all\n * of them must agree), and `reviewer` is `REVIEW_IDENTITY` \u2014 an explicit *agent*-review\n * label. The B1a receipt records an AI review worker, so no human sign-off is claimed.\n *\n * Fail closed: a record with no `documentsRecords` entry, an empty entry, an entry whose file is\n * absent from the receipt packages, a non-string entry, a package entry missing fields, or a\n * malformed digest throws `SemanticCatalogueAdmissionError('INVALID_PROVENANCE')` \u2014 the typed\n * error the catalogue admission path already raises for invalid input. There is no silent\n * fallback to a placeholder.\n *\n * The receipt is a static JSON import rather than a `loadSemanticSourceReceipts(...)` call:\n * this module is reachable from the browser worker bundle (`app/src/scanner/scan.worker.ts` ->\n * `@hub/scanner-core/v2` -> `builtin-catalogue.ts`), and `packages/scanner-core/src` is a\n * browser-safe tree that must not import node builtins (`pipeline/check-browser-safe.mjs`).\n * `scripts/lib/semantic-source-receipts.mjs` remains the shape authority for the receipt file;\n * this module revalidates the subset of it that the binding depends on.\n */\nexport type SourceReceiptFile = { readonly path: string; readonly sha256: string };\nexport type SourceReceiptPackage = {\n readonly package: string;\n readonly version: string;\n readonly fetchedAt: string;\n readonly files: readonly SourceReceiptFile[];\n};\nexport type SourceReceipts = {\n readonly packages: readonly SourceReceiptPackage[];\n readonly documentsRecords?: Readonly<Record<string, readonly string[]>>;\n};\nexport type SourceProvenanceBinding = (semanticId: string, sourceUrl: string) => SemanticProvenanceV2;\n\nconst DIGEST = /^[0-9a-f]{64}$/;\nconst REVIEW_IDENTITY = 'scanner-core-semantics-agent-review';\n\nfunction fail(label: string, reason: string): never {\n throw new SemanticCatalogueAdmissionError('INVALID_PROVENANCE', `${label}: ${reason}`);\n}\n\nfunction receiptIndex(receipts: SourceReceipts): Map<string, { sha256: string; fetchedAt: string }> {\n const index = new Map<string, { sha256: string; fetchedAt: string }>();\n for (const entry of receipts?.packages ?? []) {\n const usable = typeof entry?.package === 'string' && typeof entry.version === 'string' && typeof entry.fetchedAt === 'string';\n if (!usable || !Array.isArray(entry.files) || entry.files.length === 0) fail('receipt', 'a package entry is missing package, version, fetchedAt or files');\n for (const file of entry.files) {\n if (typeof file?.path !== 'string' || typeof file.sha256 !== 'string') fail('receipt', 'a package file entry is missing path or sha256');\n index.set(`${entry.package}@${entry.version}:${file.path}`, { sha256: file.sha256, fetchedAt: entry.fetchedAt });\n }\n }\n return index;\n}\n\nexport function createSourceProvenanceBinding(receipts: SourceReceipts): SourceProvenanceBinding {\n const index = receiptIndex(receipts);\n return (semanticId, sourceUrl) => {\n const refs = receipts?.documentsRecords?.[semanticId];\n if (refs === undefined) fail(semanticId, 'the receipt documents no supporting files for this record');\n if (!Array.isArray(refs) || refs.length === 0) fail(semanticId, 'the documentsRecords entry lists no supporting files');\n const files = [...refs].sort().map((ref) => {\n if (typeof ref !== 'string') fail(semanticId, 'a documentsRecords entry is not a string');\n const file = index.get(ref);\n if (file === undefined) fail(semanticId, `${ref} is absent from the receipt packages`);\n if (!DIGEST.test(file.sha256)) fail(semanticId, `${ref} carries a malformed digest`);\n return { ref, sha256: file.sha256, fetchedAt: file.fetchedAt };\n });\n if (new Set(files.map((file) => file.fetchedAt)).size !== 1) fail(semanticId, 'supporting files were fetched on different dates');\n const lines = files.map((file) => `${file.ref}:${file.sha256}`);\n return Object.freeze({\n sourceUrl,\n sourceDigest: bytesToHex(sha256(new TextEncoder().encode(lines.join('\\n')))),\n reviewedAt: files[0].fetchedAt,\n reviewer: REVIEW_IDENTITY,\n });\n };\n}\n\n/** Provenance for the built-in catalogue, bound to the committed receipt. */\nexport const builtinSourceProvenance: SourceProvenanceBinding = createSourceProvenanceBinding(receiptDocument as SourceReceipts);\n", "import { admitSemanticCatalogue, createSemanticCatalogueDigest } from './catalogue-admission';\nimport { builtinSourceProvenance } from './builtin-provenance';\nimport type {\n ResolvedNodeSemanticsV2, SemanticAuthenticationV2, SemanticCatalogueBodyV2, SemanticCatalogueV2,\n SemanticChannelV2, SemanticDirectionV2, SemanticEndpointV2, SemanticItemModeV2,\n SemanticPathV2, SemanticPathValueTypeV2, SemanticPortV2, SemanticProvenanceV2, SemanticTaintV2,\n} from './catalogue-schema';\nimport type { VersionRangeV2 } from './version-range';\n\nconst CORE_DOCS = 'https://docs.n8n.io/integrations/builtin/core-nodes/';\nconst LANGCHAIN_DOCS = 'https://docs.n8n.io/integrations/builtin/cluster-nodes/';\n\ntype OptionalFields = Partial<Omit<ResolvedNodeSemanticsV2, 'semanticId' | 'nodeType'>>;\nconst range = (op: 'GTE' | 'EQ' = 'GTE', version = '1.0.0'): VersionRangeV2 => ({ clauses: [[{ op, version }]] });\nconst versions = (values: readonly string[]): VersionRangeV2 => ({\n clauses: values.map((version) => [{ op: 'EQ' as const, version }]),\n});\nconst provenance = (semanticId: string, sourceUrl: string): SemanticProvenanceV2 => builtinSourceProvenance(semanticId, sourceUrl);\nconst parameter = (pointer: string, valueType: SemanticPathValueTypeV2 = 'ANY', required = false): SemanticPathV2 => ({ pointer, valueType, required });\nconst endpoint = (path: string, channel: SemanticChannelV2 = 'DATA', direction: SemanticDirectionV2 = 'SINK', taint: SemanticTaintV2 = 'BOTH'): SemanticEndpointV2 => ({ path, channel, direction, taint });\nconst port = (type = 'main', index = 0, itemMode: SemanticItemModeV2 = 'EACH'): SemanticPortV2 => ({ type, index, itemMode });\nconst auth = (path: string, noneValues: readonly string[], authenticatedValues: readonly string[]): SemanticAuthenticationV2 => ({ path, noneValues, authenticatedValues, unknownValueEffect: 'EXPOSED' });\nconst record = (semanticId: string, nodeType: string, fields: OptionalFields = {}, sourceUrl = nodeType.startsWith('@') ? LANGCHAIN_DOCS : CORE_DOCS): ResolvedNodeSemanticsV2 => ({\n semanticId, nodeType, versionRange: fields.versionRange ?? range(), operation: fields.operation ?? null, entry: fields.entry ?? 'NONE',\n parameterPaths: fields.parameterPaths ?? [], authentication: fields.authentication ?? null, credentialPaths: fields.credentialPaths ?? [],\n destinationPaths: fields.destinationPaths ?? [], effects: fields.effects ?? [], endpoints: fields.endpoints ?? [], ports: fields.ports ?? [port()],\n overwritePaths: fields.overwritePaths ?? [], errorMode: fields.errorMode ?? 'UNKNOWN', retryMode: fields.retryMode ?? 'UNKNOWN',\n disabledMode: fields.disabledMode ?? 'SKIP', provenance: fields.provenance ?? provenance(semanticId, sourceUrl),\n});\n\nconst records: ResolvedNodeSemanticsV2[] = [\n record('ingress.webhook', 'n8n-nodes-base.webhook', { entry: 'TRIGGER', parameterPaths: [parameter('/path', 'STRING', true), parameter('/authentication', 'STRING')], authentication: auth('/authentication', ['none'], ['basicAuth', 'headerAuth', 'jwtAuth']), endpoints: [endpoint('/body', 'DATA', 'SOURCE')], ports: [port()], errorMode: 'STOP', retryMode: 'PLATFORM' }),\n record('ingress.form-trigger', 'n8n-nodes-base.formTrigger', { entry: 'TRIGGER', parameterPaths: [parameter('/path', 'STRING', true), parameter('/authentication', 'STRING')], authentication: auth('/authentication', ['none'], ['basicAuth']), endpoints: [endpoint('/form', 'DATA', 'SOURCE')], ports: [port()], errorMode: 'STOP', retryMode: 'PLATFORM' }),\n record('ingress.chat-trigger', '@n8n/n8n-nodes-langchain.chatTrigger', { entry: 'TRIGGER', parameterPaths: [parameter('/path', 'STRING', true), parameter('/authentication', 'STRING')], authentication: auth('/authentication', ['none'], ['basicAuth']), endpoints: [endpoint('/chatInput', 'DATA', 'SOURCE')], ports: [port()], errorMode: 'STOP', retryMode: 'PLATFORM' }),\n record('ingress.manual-trigger', 'n8n-nodes-base.manualTrigger', { entry: 'MANUAL', ports: [port()], errorMode: 'STOP', retryMode: 'NONE' }),\n\n record('http-ai.http-request', 'n8n-nodes-base.httpRequest', { parameterPaths: [parameter('/url', 'STRING', true), parameter('/method', 'STRING')], credentialPaths: ['/credentials/httpRequestAuth'], destinationPaths: ['/url'], effects: ['READ_EXTERNAL', 'WRITE_EXTERNAL'], endpoints: [endpoint('/url', 'DATA', 'SINK', 'BOTH')], ports: [port()], retryMode: 'PLATFORM' }),\n record('http-ai.http-request.request', 'n8n-nodes-base.httpRequest', { versionRange: range('EQ'), operation: 'request', parameterPaths: [parameter('/url', 'STRING', true), parameter('/method', 'STRING')], credentialPaths: ['/credentials/httpRequestAuth'], destinationPaths: ['/url'], effects: ['READ_EXTERNAL', 'WRITE_EXTERNAL'], endpoints: [endpoint('/url', 'DATA', 'SINK', 'BOTH')], ports: [port()], errorMode: 'CONTINUE', retryMode: 'BOUNDED' }),\n record('http-ai.openai', 'n8n-nodes-base.openAi', { parameterPaths: [parameter('/resource', 'STRING', true), parameter('/operation', 'STRING', true), parameter('/prompt', 'STRING')], credentialPaths: ['/credentials/openAiApi'], destinationPaths: ['/options/baseURL'], effects: ['READ_EXTERNAL', 'WRITE_EXTERNAL'], endpoints: [endpoint('/prompt', 'MODEL', 'SINK', 'BOTH')], ports: [port()], retryMode: 'PLATFORM' }),\n record('http-ai.ai-agent', '@n8n/n8n-nodes-langchain.agent', { parameterPaths: [parameter('/options/systemMessage', 'STRING')], credentialPaths: ['/credentials'], destinationPaths: ['/options/baseURL'], effects: ['CALL_TOOL', 'READ_EXTERNAL', 'WRITE_EXTERNAL'], endpoints: [endpoint('/options/systemMessage', 'MODEL', 'SINK', 'BOTH')], ports: [port(), port('ai_tool', 0, 'ALL')], retryMode: 'PLATFORM' }),\n record('http-ai.chat-model', '@n8n/n8n-nodes-langchain.lmChatOpenAi', { parameterPaths: [parameter('/modelName', 'STRING', true), parameter('/options', 'OBJECT')], credentialPaths: ['/credentials/openAiApi'], destinationPaths: ['/options/baseURL'], effects: ['READ_EXTERNAL', 'WRITE_EXTERNAL'], endpoints: [endpoint('/modelName', 'MODEL', 'SINK', 'BOTH')], ports: [port()], retryMode: 'PLATFORM' }),\n\n record('database-file.postgres', 'n8n-nodes-base.postgres', { parameterPaths: [parameter('/operation', 'STRING', true), parameter('/query', 'STRING')], credentialPaths: ['/credentials/postgres'], destinationPaths: ['/options/host', '/options/database'], effects: ['DATABASE_READ', 'DATABASE_WRITE'], endpoints: [endpoint('/query', 'DATA', 'SINK', 'BOTH')], ports: [port()], retryMode: 'BOUNDED' }),\n record('database-file.mysql', 'n8n-nodes-base.mySql', { parameterPaths: [parameter('/operation', 'STRING', true), parameter('/query', 'STRING')], credentialPaths: ['/credentials/mySql'], destinationPaths: ['/options/host', '/options/database'], effects: ['DATABASE_READ', 'DATABASE_WRITE'], endpoints: [endpoint('/query', 'DATA', 'SINK', 'BOTH')], ports: [port()], retryMode: 'BOUNDED' }),\n record('database-file.read-binary-file', 'n8n-nodes-base.readBinaryFile', { parameterPaths: [parameter('/filePath', 'STRING', true)], destinationPaths: ['/filePath'], effects: ['READ_FILE'], endpoints: [endpoint('/filePath', 'DATA', 'SINK', 'CONFIDENTIALITY')], ports: [port()], retryMode: 'NONE' }),\n record('database-file.write-binary-file', 'n8n-nodes-base.writeBinaryFile', { parameterPaths: [parameter('/fileName', 'STRING', true)], destinationPaths: ['/fileName'], effects: ['WRITE_FILE'], endpoints: [endpoint('/fileName', 'DATA', 'SINK', 'INTEGRITY')], ports: [port()], overwritePaths: ['/fileName'], retryMode: 'NONE' }),\n\n record('code-command.execute-command', 'n8n-nodes-base.executeCommand', { parameterPaths: [parameter('/command', 'STRING', true)], effects: ['EXECUTE_COMMAND'], ports: [port()], errorMode: 'STOP', retryMode: 'NONE' }),\n record('code-command.code', 'n8n-nodes-base.code', { parameterPaths: [parameter('/jsCode', 'STRING', true), parameter('/mode', 'STRING')], effects: ['EXECUTE_CODE'], ports: [port()], errorMode: 'STOP', retryMode: 'NONE' }),\n record('code-command.langchain-tool-code', '@n8n/n8n-nodes-langchain.toolCode', { parameterPaths: [parameter('/jsCode', 'STRING'), parameter('/pythonCode', 'STRING'), parameter('/language', 'STRING')], effects: ['EXECUTE_CODE'], ports: [port(), port('ai_tool', 0, 'ALL')], errorMode: 'STOP', retryMode: 'NONE' }),\n record('code-command.langchain-code', '@n8n/n8n-nodes-langchain.code', { parameterPaths: [parameter('/code/execute/code', 'STRING'), parameter('/code/supplyData/code', 'STRING')], effects: ['EXECUTE_CODE'], ports: [], errorMode: 'UNKNOWN', retryMode: 'NONE' }),\n\n record('message-mcp.slack', 'n8n-nodes-base.slack', { parameterPaths: [parameter('/channelId', 'STRING', true), parameter('/text', 'STRING', true)], credentialPaths: ['/credentials/slackApi'], destinationPaths: ['/channelId'], effects: ['SEND_MESSAGE'], endpoints: [endpoint('/text', 'DATA', 'SINK', 'CONFIDENTIALITY')], ports: [port()], errorMode: 'CONTINUE', retryMode: 'BOUNDED' }),\n record('message-mcp.email-send', 'n8n-nodes-base.emailSend', { parameterPaths: [parameter('/to', 'STRING', true), parameter('/subject', 'STRING'), parameter('/text', 'STRING')], credentialPaths: ['/credentials/smtp'], destinationPaths: ['/to'], effects: ['SEND_MESSAGE'], endpoints: [endpoint('/text', 'DATA', 'SINK', 'CONFIDENTIALITY')], ports: [port()], errorMode: 'CONTINUE', retryMode: 'BOUNDED' }),\n record('message-mcp.tool-mcp', '@n8n/n8n-nodes-langchain.toolMcp', { parameterPaths: [parameter('/serverUrl', 'STRING', true), parameter('/tool', 'STRING')], credentialPaths: ['/credentials'], destinationPaths: ['/serverUrl'], effects: ['CALL_TOOL'], endpoints: [endpoint('/serverUrl', 'TOOL', 'SINK', 'BOTH')], ports: [port(), port('ai_tool', 0, 'ALL')], errorMode: 'STOP', retryMode: 'BOUNDED' }),\n\n record('subworkflow.execute-workflow-trigger', 'n8n-nodes-base.executeWorkflowTrigger', { entry: 'SUBWORKFLOW', parameterPaths: [parameter('/workflowInputs', 'OBJECT')], endpoints: [], ports: [port()], errorMode: 'STOP', retryMode: 'NONE' }),\n record('subworkflow.execute-workflow', 'n8n-nodes-base.executeWorkflow', { parameterPaths: [parameter('/workflowId', 'STRING', true), parameter('/workflowInputs', 'OBJECT')], destinationPaths: ['/workflowId'], effects: ['START_SUBWORKFLOW'], endpoints: [], ports: [port()], errorMode: 'STOP', retryMode: 'BOUNDED' }),\n record('subworkflow.tool-workflow', '@n8n/n8n-nodes-langchain.toolWorkflow', { parameterPaths: [parameter('/workflowId', 'STRING', true), parameter('/workflowInputs', 'OBJECT')], destinationPaths: ['/workflowId'], effects: ['START_SUBWORKFLOW'], endpoints: [], ports: [port(), port('ai_tool', 0, 'ALL')], errorMode: 'STOP', retryMode: 'BOUNDED' }),\n record('git.git', 'n8n-nodes-base.git', { parameterPaths: [parameter('/operation', 'STRING', true), parameter('/repositoryUrl', 'STRING', true), parameter('/branch', 'STRING')], credentialPaths: ['/credentials'], destinationPaths: ['/repositoryUrl'], effects: ['READ_EXTERNAL', 'WRITE_EXTERNAL'], endpoints: [endpoint('/repositoryUrl')], ports: [port()], errorMode: 'UNKNOWN', retryMode: 'BOUNDED' }),\n\n // Flow-control and trigger records. Versions are the exact `nodeVersions` keys in the pinned\n // wrapper files, rendered as canonical strict semver; they are EQ clauses because behaviour and\n // parameters differ by version. `switch` has no fixed port list: its output count is rule-driven.\n record('flow-control.set', 'n8n-nodes-base.set', {\n versionRange: versions(['1.0.0', '2.0.0', '3.0.0', '3.1.0', '3.2.0', '3.3.0', '3.4.0']),\n parameterPaths: [parameter('/keepOnlySet', 'BOOLEAN'), parameter('/values', 'OBJECT'),\n parameter('/mode', 'STRING'), parameter('/duplicateItem', 'BOOLEAN'),\n parameter('/fields/values', 'OBJECT'), parameter('/assignments', 'OBJECT'),\n parameter('/includeOtherFields', 'BOOLEAN'), parameter('/options', 'OBJECT')],\n ports: [port()],\n }),\n record('flow-control.if', 'n8n-nodes-base.if', {\n versionRange: versions(['1.0.0', '2.0.0', '2.1.0', '2.2.0', '2.3.0']),\n parameterPaths: [parameter('/conditions', 'OBJECT'), parameter('/options', 'OBJECT')],\n ports: [port(), port('main', 1)],\n }),\n record('flow-control.switch', 'n8n-nodes-base.switch', {\n versionRange: versions(['1.0.0', '2.0.0', '3.0.0', '3.1.0', '3.2.0', '3.3.0', '3.4.0']),\n parameterPaths: [parameter('/mode', 'STRING'), parameter('/rules', 'OBJECT'),\n parameter('/value1', 'STRING'), parameter('/numberOutputs', 'NUMBER'),\n parameter('/output', 'STRING'), parameter('/options', 'OBJECT')],\n // Output count is rule-driven; an empty list is the honest claim.\n ports: [],\n }),\n record('flow-control.merge', 'n8n-nodes-base.merge', {\n versionRange: versions(['1.0.0', '2.0.0', '2.1.0', '3.0.0', '3.1.0', '3.2.0']),\n parameterPaths: [parameter('/mode', 'STRING'), parameter('/join', 'STRING'),\n parameter('/combinationMode', 'STRING'), parameter('/joinMode', 'STRING'),\n parameter('/options', 'OBJECT')],\n ports: [port('main', 0, 'ALL')],\n }),\n record('flow-control.split-in-batches', 'n8n-nodes-base.splitInBatches', {\n versionRange: versions(['1.0.0', '2.0.0', '3.0.0']),\n parameterPaths: [parameter('/batchSize', 'NUMBER'), parameter('/options', 'OBJECT')],\n ports: [port(), port('main', 1)],\n }),\n record('flow-control.schedule-trigger', 'n8n-nodes-base.scheduleTrigger', {\n entry: 'TRIGGER', versionRange: versions(['1.0.0', '1.1.0', '1.2.0', '1.3.0']),\n parameterPaths: [parameter('/rule', 'OBJECT')], ports: [port()],\n }),\n // Google Sheets is a network integration, not flow control: conservative read+write effects and\n // the v2 destination parameters, no operation-specific claim. It is not a pure-flow record.\n record('google-workspace.google-sheets', 'n8n-nodes-base.googleSheets', {\n versionRange: versions(['1.0.0', '2.0.0', '3.0.0', '4.0.0', '4.1.0', '4.2.0', '4.3.0', '4.4.0', '4.5.0', '4.6.0', '4.7.0']),\n parameterPaths: [parameter('/resource', 'STRING'), parameter('/operation', 'STRING'),\n parameter('/documentId', 'STRING'), parameter('/sheetName', 'STRING'),\n parameter('/range', 'STRING'), parameter('/columns', 'OBJECT')],\n credentialPaths: ['/credentials/googleApi', '/credentials/googleSheetsOAuth2Api'],\n destinationPaths: ['/documentId', '/sheetName', '/range', '/columns'],\n effects: ['READ_EXTERNAL', 'WRITE_EXTERNAL'],\n endpoints: [endpoint('/documentId')],\n ports: [port()],\n }),\n\n // Five frequent, previously unmodelled families. Versions are EQ clauses taken from the\n // `typeVersion` values actually present in the 11,394 bound readable inputs; anything else\n // (for example telegram typeVersion 2, which upstream does not declare) stays generic fallback.\n // Effects, credential names, destination parameters and ports are read from the pinned\n // `n8n-nodes-base@2.15.1` / `@n8n/n8n-nodes-langchain@2.43.5` files in the source receipts.\n record('message-mcp.gmail', 'n8n-nodes-base.gmail', {\n versionRange: versions(['1.0.0', '2.0.0', '2.1.0', '2.2.0']),\n parameterPaths: [parameter('/resource', 'STRING'), parameter('/operation', 'STRING'),\n parameter('/sendTo', 'STRING'), parameter('/messageId', 'STRING')],\n credentialPaths: ['/credentials/gmailOAuth2'],\n destinationPaths: ['/sendTo', '/messageId', '/threadId'],\n effects: ['READ_EXTERNAL', 'WRITE_EXTERNAL', 'SEND_MESSAGE'],\n endpoints: [endpoint('/sendTo', 'DATA', 'SINK', 'CONFIDENTIALITY')],\n ports: [port()],\n }),\n record('flow-control.wait', 'n8n-nodes-base.wait', {\n versionRange: versions(['1.0.0', '1.1.0']),\n parameterPaths: [parameter('/resume', 'STRING'), parameter('/amount', 'NUMBER'),\n parameter('/unit', 'STRING'), parameter('/dateTime', 'STRING'),\n parameter('/httpMethod', 'STRING'), parameter('/incomingAuthentication', 'STRING')],\n ports: [port()],\n }),\n record('message-mcp.telegram', 'n8n-nodes-base.telegram', {\n versionRange: versions(['1.0.0', '1.1.0', '1.2.0']),\n parameterPaths: [parameter('/resource', 'STRING'), parameter('/operation', 'STRING'),\n parameter('/chatId', 'STRING')],\n credentialPaths: ['/credentials/telegramApi'],\n destinationPaths: ['/chatId'],\n effects: ['READ_EXTERNAL', 'SEND_MESSAGE'],\n endpoints: [endpoint('/chatId', 'DATA', 'SINK', 'BOTH')],\n ports: [port()],\n }),\n record('transform.split-out', 'n8n-nodes-base.splitOut', {\n versionRange: versions(['1.0.0']),\n parameterPaths: [parameter('/fieldToSplitOut', 'STRING', true), parameter('/include', 'STRING'),\n parameter('/options', 'OBJECT')],\n ports: [port()],\n }),\n record('ai.output-parser-structured', '@n8n/n8n-nodes-langchain.outputParserStructured', {\n versionRange: versions(['1.0.0', '1.1.0', '1.2.0', '1.3.0']),\n parameterPaths: [parameter('/schemaType', 'STRING'), parameter('/jsonSchema', 'STRING'),\n parameter('/inputSchema', 'STRING'), parameter('/autoFix', 'BOOLEAN')],\n ports: [port('ai_outputParser', 0, 'EACH'), port('ai_languageModel', 0, 'EACH')],\n }),\n\n // NoOp v1 is a pure passthrough: `properties: []`, no credentials, and `execute()` returns\n // `this.getInputData()` (pinned NoOp.node.js). The pinned file declares no error, retry, or\n // disabled handling of its own, so errorMode/retryMode stay at the catalogue's conservative\n // `UNKNOWN` defaults and disabledMode at `SKIP`.\n record('noop.passthrough', 'n8n-nodes-base.noOp', { versionRange: range('EQ') }),\n];\n\nconst catalogueBody: SemanticCatalogueBodyV2 = { schemaVersion: 'scanner-semantics-v2', id: 'scanner-core-builtins', version: '2.2.0', records, configurationKeys: ['allowNetwork', 'approvedDomains'] };\nexport const BUILTIN_SEMANTIC_CATALOGUE_V2: SemanticCatalogueV2 = admitSemanticCatalogue({ ...catalogueBody, digest: createSemanticCatalogueDigest(catalogueBody) });\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { resolveNodeSemantics } from './catalogue-resolver';\nimport type { ResolvedNodeSemanticsV2, SemanticCatalogueV2, SemanticProvenanceV2 } from './catalogue-schema';\n\n/**\n * Generic semantic fallback for node types the admitted catalogue does not model.\n *\n * Before this module, an unmodelled node resolved to nothing: it was absent from the semantic view\n * and `capabilities/semantic-context.ts` raised `SEMANTIC_CATALOGUE_MISS` at requiredness, which\n * withheld the whole workflow's verdict (`assessment: null`). The catalogued node families are a\n * small subset of n8n's node types, so that refusal applied to nearly every real workflow even\n * though the parameter, credential and destination audits had already run.\n *\n * The fallback states the *assumption* instead of refusing: main-in \u2192 main-out passthrough, both\n * external effects, no claim about destinations, credentials kept where n8n keeps them, and\n * error/retry modes left at the catalogue's own conservative `UNKNOWN`. Parameter auditing does not\n * depend on this record \u2014 the structural policies read node parameters directly \u2014 so the fallback\n * changes what the engine assumes about data flow, never whether it looks. The workflow still\n * receives a coverage diagnostic per fallback node (`SEMANTIC_CATALOGUE_MISS` at degraded\n * requiredness, rendered by the report as `SEMANTIC_CATALOGUE_MISS \u00B7 DEGRADED`); the decision record\n * is `docs/decisions/ADR-generic-node-semantic-fallback.md`.\n *\n * The record is not part of the admitted catalogue: adding it there would move the catalogue digest\n * pinned by the CLI, and the fallback is not a claim about n8n (no upstream page exists for it).\n * Provenance therefore binds to the contract text below rather than to source bytes.\n */\nexport const GENERIC_FALLBACK_SEMANTIC_ID = 'generic.fallback';\n\nconst CONTRACT = 'scanner-core generic node semantic fallback v1: main-in/main-out passthrough, READ_EXTERNAL + WRITE_EXTERNAL, unknown error/retry modes, no destination claim, parameters audited by the structural policies';\nconst PROVENANCE: SemanticProvenanceV2 = Object.freeze({\n sourceUrl: 'https://docs.n8n.io/',\n sourceDigest: bytesToHex(sha256(new TextEncoder().encode(CONTRACT))),\n reviewedAt: '2026-10-17',\n reviewer: 'scanner-core-generic-fallback',\n});\n\nexport type NodeSemanticsQueryV2 = Readonly<{\n type: string;\n typeVersion?: string;\n /** The scanned node's parameter fields, in the normalized engine shape. */\n parameters: readonly Readonly<{ pointer: string; value: unknown }>[];\n scoringEligibility: 'ELIGIBLE' | 'INDETERMINATE';\n}>;\nexport type NodeSemanticsResolutionV2 = Readonly<{\n semantics: ResolvedNodeSemanticsV2;\n origin: 'CATALOGUE' | 'GENERIC_FALLBACK';\n}>;\n\n/** Deep-freezes the record: the semantic view's consumers validate frozen plain data. */\nfunction deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {\n if (value !== null && typeof value === 'object') {\n if (seen.has(value)) return value;\n seen.add(value);\n for (const name of Object.getOwnPropertyNames(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, name);\n if (descriptor && 'value' in descriptor) deepFreeze(descriptor.value, seen);\n }\n Object.freeze(value);\n }\n return value;\n}\n\n/**\n * The conservative record for one unmodelled node type. `nodeType` must be the scanned node's own\n * type: `analyzers/destinations/inventory.ts` refuses a record whose `nodeType` does not match.\n */\nexport function createGenericFallbackSemantics(nodeType: string): ResolvedNodeSemanticsV2 {\n return deepFreeze<ResolvedNodeSemanticsV2>({\n semanticId: GENERIC_FALLBACK_SEMANTIC_ID,\n nodeType,\n versionRange: { clauses: [[{ op: 'GTE', version: '1.0.0' }]] },\n operation: null,\n entry: 'NONE',\n parameterPaths: [],\n authentication: null,\n credentialPaths: ['/credentials'],\n destinationPaths: [],\n effects: ['READ_EXTERNAL', 'WRITE_EXTERNAL'],\n endpoints: [],\n ports: [{ type: 'main', index: 0, itemMode: 'EACH' }],\n overwritePaths: [],\n errorMode: 'UNKNOWN',\n retryMode: 'UNKNOWN',\n disabledMode: 'SKIP',\n provenance: PROVENANCE,\n });\n}\n\n/**\n * The one per-node resolution both seams use (`v2/scan-workflow.ts` builds the admitted view from\n * it; `capabilities/semantic-context.ts` derives the coverage diagnostics from it), so a node can\n * never be fallback-covered in one seam and missing in the other.\n *\n * `null` means genuinely unresolvable: the node's fields were not readable\n * (`scoringEligibility: 'INDETERMINATE'`), and the caller keeps the fail-closed miss. A node whose\n * `type` member itself was unreadable never reaches this decision \u2014 the resolver refuses an empty\n * node type and the scan fails closed with `SEMANTIC_CATALOGUE_INVALID`.\n */\nexport function resolveNodeSemanticsForScan(\n catalogue: SemanticCatalogueV2,\n query: NodeSemanticsQueryV2,\n): NodeSemanticsResolutionV2 | null {\n // The shipped pointer match is a suffix match, not pointer equality. It is unchanged here: the\n // per-node resolution seam only needs the top-level parameter and no consumer has demonstrated\n // an ambiguous nested pointer. A string operation always wins; a non-string operation falls\n // through to the action value. A conflicting pair resolves operation-first with no extra\n // diagnostic, and a non-string value on either pointer is never passed to the resolver.\n const operationField = query.parameters.find((field) => field.pointer.endsWith('/operation'));\n const actionField = query.parameters.find((field) => field.pointer.endsWith('/action'));\n const operation = typeof operationField?.value === 'string' ? operationField.value : actionField?.value;\n const semantics = resolveNodeSemantics(catalogue, {\n nodeType: query.type,\n version: query.typeVersion ?? '1.0.0',\n operation: typeof operation === 'string' ? operation : null,\n });\n if (semantics !== null) return Object.freeze({ semantics, origin: 'CATALOGUE' as const });\n if (query.scoringEligibility !== 'ELIGIBLE') return null;\n return Object.freeze({ semantics: createGenericFallbackSemantics(query.type), origin: 'GENERIC_FALLBACK' as const });\n}\n", "import type { AdvisoryRecordV2 } from '../advisories/advisory-schema';\nimport { evaluateAdvisoryApplicability } from '../advisories/advisory-applicability';\nimport { createDiagnostic, makeFact } from './adapter-evidence';\nimport type { AnalysisDiagnosticV2 } from '../diagnostics/registry';\nimport { inventoryDestinations, type DestinationInventoryRecord } from '../analyzers/destinations/inventory';\nimport { sortDiagnostics } from '../diagnostics/identity';\nimport { resolveNodeSemanticsForScan } from '../semantics/generic-fallback';\nimport type { ResolvedNodeSemanticsV2, SemanticCatalogueV2 } from '../semantics/catalogue-schema';\nimport type { TargetContextV2 } from '../semantics/target-context';\nimport type { ReadonlySourceDocumentV2, SourceMemberRefV2 } from '../source/source-types';\nimport type { SemanticFieldV2, SecurityWorkflowV2 } from '../workflow-v2/security-workflow';\nimport type { SafeFactV2 } from './scheduler';\n\nexport type SemanticContextV2 = Readonly<{\n facts: readonly SafeFactV2[];\n diagnostics: readonly AnalysisDiagnosticV2[];\n}>;\n\nexport const EMPTY_ADVISORY_CATALOGUE_V2: Readonly<{\n records: readonly AdvisoryRecordV2[];\n}> = Object.freeze({ records: Object.freeze([]) });\n\nexport function resolveAnalyzerSemanticContext(input: Readonly<{\n source: ReadonlySourceDocumentV2;\n workflow: SecurityWorkflowV2;\n target: TargetContextV2;\n catalogue: SemanticCatalogueV2;\n advisories: Readonly<{ records: readonly AdvisoryRecordV2[] }>;\n capabilityId: string;\n required: boolean;\n}>): SemanticContextV2 {\n const diagnostics: AnalysisDiagnosticV2[] = [];\n const resolved = new Map<string, ResolvedNodeSemanticsV2>();\n for (const node of input.workflow.nodes) {\n const resolution = resolveNodeSemanticsForScan(input.catalogue, node);\n if (resolution === null) diagnostics.push(createDiagnostic('SEMANTIC_CATALOGUE_MISS', input.capabilityId, input.required, node.ref.source));\n else {\n resolved.set(node.ref.identityDigest, resolution.semantics);\n // Two meanings, never one substitute for the other. The miss says the node type has no\n // admitted catalogue record (the same code the fail-closed path uses at caller requiredness);\n // the capability code says the verdict rests on unmodelled-capability defaults whose\n // destinations are unknown, not audited-and-empty. Both are per node at that node's source\n // location and both are degraded/eligible, so the report's coverage section names exactly\n // which nodes rest on the assumption without withholding the workflow's verdict.\n if (resolution.origin === 'GENERIC_FALLBACK') {\n diagnostics.push(createDiagnostic('SEMANTIC_CATALOGUE_MISS', input.capabilityId, false, node.ref.source));\n diagnostics.push(createDiagnostic('GENERIC_NODE_UNMODELED_CAPABILITY', input.capabilityId, false, node.ref.source));\n }\n }\n }\n const factsById = new Map<string, SafeFactV2>();\n for (const advisory of input.advisories.records) {\n const applicability = evaluateAdvisoryApplicability(advisory, input.target);\n const fact = createAdvisoryApplicabilityFact({\n advisoryId: advisory.id,\n applicability,\n reviewState: advisory.reviewState,\n matchedPrerequisites: [],\n unknownPrerequisites: applicability === 'UNKNOWN' ? ['target'] : [],\n });\n if (!factsById.has(fact.factId)) factsById.set(fact.factId, fact);\n }\n for (const fact of destinationFacts(input.workflow, resolved)) if (!factsById.has(fact.factId)) factsById.set(fact.factId, fact);\n const facts = [...factsById.values()];\n facts.sort((left, right) => compareStrings(left.factId, right.factId));\n return Object.freeze({\n facts: Object.freeze(facts),\n diagnostics: sortDiagnostics(diagnostics, [input.capabilityId]),\n });\n}\n\nfunction createAdvisoryApplicabilityFact(input: Readonly<{\n advisoryId: string;\n applicability: 'APPLICABLE' | 'NOT_APPLICABLE' | 'UNKNOWN';\n reviewState: AdvisoryRecordV2['reviewState'];\n matchedPrerequisites: readonly string[];\n unknownPrerequisites: readonly string[];\n}>): SafeFactV2 {\n const subject = Object.freeze({ kind: 'WORKFLOW' as const });\n const properties = Object.freeze({\n advisoryId: input.advisoryId,\n applicability: input.applicability,\n reviewState: input.reviewState,\n matchedPrerequisites: Object.freeze([...input.matchedPrerequisites]),\n unknownPrerequisites: Object.freeze([...input.unknownPrerequisites]),\n });\n const fact = makeFact('advisory.applicability.v2', subject, properties);\n return Object.freeze({ factId: fact.factId, kind: fact.kind, subject, properties });\n}\n\nfunction destinationFacts(workflow: SecurityWorkflowV2, semantics: ReadonlyMap<string, ResolvedNodeSemanticsV2>): SafeFactV2[] {\n const sources = new Map<string, SourceMemberRefV2[]>();\n for (const node of workflow.nodes) {\n const fields: SemanticFieldV2[] = [];\n collectFields(node.parameters, fields);\n for (const field of fields) {\n const parameterPath = relativeParameterPath(node.ref.source.pointer, field.pointer);\n if (parameterPath === undefined) continue;\n for (const source of field.occurrences) {\n const key = `${node.ref.identityDigest}\\u0000${parameterPath}`;\n const values = sources.get(key);\n if (values === undefined) sources.set(key, [source]);\n else values.push(source);\n }\n }\n }\n const inventory = inventoryDestinations(workflow, semantics);\n const facts: SafeFactV2[] = [];\n for (const record of inventory.records) {\n const node = workflow.nodes.find((candidate) => candidate.ref.identityDigest === record.nodeIdentity);\n if (node === undefined) continue;\n const key = `${record.nodeIdentity}\\u0000${record.parameterPath}`;\n const source = sources.get(key)?.shift() ?? node.ref.source;\n facts.push(createDestinationFact(record, source));\n }\n return facts;\n}\n\nfunction relativeParameterPath(nodePointer: string, fieldPointer: string): string | undefined {\n const prefix = `${nodePointer}/parameters`;\n return fieldPointer.startsWith(`${prefix}/`) ? fieldPointer.slice(prefix.length) : undefined;\n}\n\nfunction collectFields(fields: readonly SemanticFieldV2[], output: SemanticFieldV2[]): void {\n for (const field of fields) {\n output.push(field);\n if (Array.isArray(field.value)) collectFields(field.value, output);\n }\n}\n\nfunction createDestinationFact(record: DestinationInventoryRecord, source: SourceMemberRefV2): SafeFactV2 {\n const subject = Object.freeze({ kind: 'SOURCE' as const, source });\n const properties = Object.freeze({\n parameterPath: record.parameterPath,\n scheme: record.scheme,\n hostname: record.hostname,\n authorityState: record.authorityState,\n valueMode: record.valueMode,\n });\n const fact = makeFact('destination.v2', subject, properties);\n return Object.freeze({ factId: fact.factId, kind: fact.kind, subject, properties });\n}\n\nfunction compareStrings(left: string, right: string): number {\n if (left === right) return 0;\n return left < right ? -1 : 1;\n}\n", "// Generated by scripts/generate-diagnostic-registry.mjs; DO NOT EDIT.\n// diagnostic-registry:version=diagnostic-registry-v1\n// diagnostic-registry:source=openspec/changes/world-class-scanner-cli/diagnostic-and-exit-registry.md\n// diagnostic-registry:rows=28\n// diagnostic-registry:digest=f66f90ea2cca06ddccefeff924fcb8abe672050fcee861ceb9b4e66551ddfc3c\n// Regenerate with `npm run generate:diagnostic-registry` after editing the registry table.\n// The result validator reads this instead of keeping its own copy of the vocabulary.\nexport type DiagnosticCodeV2 =\n | 'SOURCE_SPAN_UNAVAILABLE' | 'DUPLICATE_FINDING_COLLAPSED' | 'UNCLASSIFIED_CONNECTION_TYPE'\n | 'DUPLICATE_METADATA_KEY' | 'OPTIONAL_LIMIT_EXCEEDED' | 'UNSUPPORTED_CODE_NODE_VARIANT'\n | 'JAVASCRIPT_PARSE_FAILED' | 'JAVASCRIPT_SOURCE_UNAVAILABLE' | 'PYTHON_SOURCE_UNAVAILABLE'\n | 'PYTHON_PARSE_FAILED' | 'PYTHON_PARSER_UNAVAILABLE' | 'EXPRESSION_PARSE_FAILED'\n | 'GRAPH_ENTRY_UNRESOLVED' | 'GRAPH_WORK_LIMIT_EXCEEDED' | 'GRAPH_ANALYSIS_DEGRADED'\n | 'SEMANTIC_CATALOGUE_MISS' | 'GENERIC_NODE_UNMODELED_CAPABILITY' | 'POLICY_EXECUTION_FAILED'\n | 'DEPENDENCY_UNAVAILABLE' | 'UNKNOWN_REPORT_ONLY_RULE' | 'REQUIRED_LIMIT_EXCEEDED'\n | 'DUPLICATE_SECURITY_KEY' | 'MALFORMED_NODE_PARAMETERS' | 'MALFORMED_CONNECTION_INDEX'\n | 'REQUIRED_CAPABILITY_FAILED' | 'UNKNOWN_SCORING_RULE' | 'COMPATIBILITY_PROJECTION_LOSS'\n | 'REQUIRED_STAGE_FAILURE';\n\nexport type DiagnosticCategoryV2 = 'LIMIT' | 'SOURCE' | 'PARSER' | 'POLICY' | 'GRAPH' | 'CATALOGUE' | 'COMPATIBILITY';\nexport type DiagnosticAggregateEffectModeV2 = 'DEGRADED' | 'INDETERMINATE' | 'BY_CAPABILITY';\nexport type DiagnosticAssessmentEligibilityModeV2 = boolean | 'BY_CAPABILITY';\n\n/** [category, aggregate effect, assessment eligibility], one entry per registered code. */\nexport const DIAGNOSTIC_REGISTRY_V2: Readonly<Record<DiagnosticCodeV2, readonly [DiagnosticCategoryV2, DiagnosticAggregateEffectModeV2, DiagnosticAssessmentEligibilityModeV2]>> = Object.freeze({\n SOURCE_SPAN_UNAVAILABLE: ['SOURCE', 'DEGRADED', true],\n DUPLICATE_FINDING_COLLAPSED: ['POLICY', 'DEGRADED', true],\n UNCLASSIFIED_CONNECTION_TYPE: ['GRAPH', 'DEGRADED', true],\n DUPLICATE_METADATA_KEY: ['PARSER', 'DEGRADED', true],\n OPTIONAL_LIMIT_EXCEEDED: ['LIMIT', 'DEGRADED', true],\n UNSUPPORTED_CODE_NODE_VARIANT: ['PARSER', 'BY_CAPABILITY', 'BY_CAPABILITY'],\n JAVASCRIPT_PARSE_FAILED: ['PARSER', 'BY_CAPABILITY', 'BY_CAPABILITY'],\n JAVASCRIPT_SOURCE_UNAVAILABLE: ['SOURCE', 'BY_CAPABILITY', 'BY_CAPABILITY'],\n PYTHON_SOURCE_UNAVAILABLE: ['SOURCE', 'BY_CAPABILITY', 'BY_CAPABILITY'],\n PYTHON_PARSE_FAILED: ['PARSER', 'BY_CAPABILITY', 'BY_CAPABILITY'],\n PYTHON_PARSER_UNAVAILABLE: ['PARSER', 'BY_CAPABILITY', 'BY_CAPABILITY'],\n EXPRESSION_PARSE_FAILED: ['PARSER', 'BY_CAPABILITY', 'BY_CAPABILITY'],\n GRAPH_ENTRY_UNRESOLVED: ['GRAPH', 'BY_CAPABILITY', 'BY_CAPABILITY'],\n GRAPH_WORK_LIMIT_EXCEEDED: ['GRAPH', 'BY_CAPABILITY', 'BY_CAPABILITY'],\n GRAPH_ANALYSIS_DEGRADED: ['GRAPH', 'BY_CAPABILITY', 'BY_CAPABILITY'],\n SEMANTIC_CATALOGUE_MISS: ['CATALOGUE', 'BY_CAPABILITY', 'BY_CAPABILITY'],\n GENERIC_NODE_UNMODELED_CAPABILITY: ['CATALOGUE', 'DEGRADED', true],\n POLICY_EXECUTION_FAILED: ['POLICY', 'BY_CAPABILITY', 'BY_CAPABILITY'],\n DEPENDENCY_UNAVAILABLE: ['POLICY', 'BY_CAPABILITY', 'BY_CAPABILITY'],\n UNKNOWN_REPORT_ONLY_RULE: ['POLICY', 'DEGRADED', true],\n REQUIRED_LIMIT_EXCEEDED: ['LIMIT', 'INDETERMINATE', false],\n DUPLICATE_SECURITY_KEY: ['PARSER', 'INDETERMINATE', false],\n MALFORMED_NODE_PARAMETERS: ['PARSER', 'INDETERMINATE', false],\n MALFORMED_CONNECTION_INDEX: ['GRAPH', 'INDETERMINATE', false],\n REQUIRED_CAPABILITY_FAILED: ['POLICY', 'INDETERMINATE', false],\n UNKNOWN_SCORING_RULE: ['POLICY', 'INDETERMINATE', false],\n COMPATIBILITY_PROJECTION_LOSS: ['COMPATIBILITY', 'INDETERMINATE', false],\n REQUIRED_STAGE_FAILURE: ['POLICY', 'INDETERMINATE', false],\n});\n\n/** The codes whose effect and eligibility the owning capability's requiredness decides. */\nexport const BY_CAPABILITY_DIAGNOSTIC_CODES_V2: Readonly<Partial<Record<DiagnosticCodeV2, true>>> = Object.freeze({\n 'UNSUPPORTED_CODE_NODE_VARIANT': true,\n 'JAVASCRIPT_PARSE_FAILED': true,\n 'JAVASCRIPT_SOURCE_UNAVAILABLE': true,\n 'PYTHON_SOURCE_UNAVAILABLE': true,\n 'PYTHON_PARSE_FAILED': true,\n 'PYTHON_PARSER_UNAVAILABLE': true,\n 'EXPRESSION_PARSE_FAILED': true,\n 'GRAPH_ENTRY_UNRESOLVED': true,\n 'GRAPH_WORK_LIMIT_EXCEEDED': true,\n 'GRAPH_ANALYSIS_DEGRADED': true,\n 'SEMANTIC_CATALOGUE_MISS': true,\n 'POLICY_EXECUTION_FAILED': true,\n 'DEPENDENCY_UNAVAILABLE': true,\n});\n", "import type { EdgeRefV2, NodeRefV2, SourceMemberRefV2, SubjectV2 } from './scanner-v2-source';\nimport type { AnalysisDiagnosticV2, CapabilityExecutionV2, FindingV2, SafeFactV2, TraceV2 } from './scanner-v2-evidence';\nimport { BY_CAPABILITY_DIAGNOSTIC_CODES_V2, DIAGNOSTIC_REGISTRY_V2, type DiagnosticCodeV2 } from './scanner-v2-diagnostics.generated';\n\nexport type TargetContextV2 = { n8nVersion?: string; edition: 'COMMUNITY' | 'ENTERPRISE' | 'CLOUD' | 'UNKNOWN'; deployment: 'SELF_HOSTED' | 'CLOUD' | 'UNKNOWN'; role: 'OWNER' | 'ADMIN' | 'MEMBER' | 'UNKNOWN'; taskRunner: 'LEGACY' | 'NATIVE' | 'UNKNOWN'; communityPackages: readonly { name: string; version?: string }[]; configuration: readonly { key: string; state: 'ENABLED' | 'DISABLED' | 'UNKNOWN' }[]; contextDigest: string };\nexport type LimitUsageV2 = { id: string; maximum: number; examined: number; omitted: number; exhausted: boolean };\nexport type ScannerResultV2 = {\n schemaVersion: 'scanner-result-v2';\n engine: { id: 'secureflow-scanner'; version: string; buildDigest: string };\n input: { rawSha256: string; semanticSha256: string; ambiguitySha256: string; ambiguityCount: number; utf8Bytes: number };\n profile: { id: string; version: string };\n ruleset: { id: string; version: string; digest: string; signatureStatus: 'VERIFIED' | 'UNVERIFIED' };\n semantics: { id: string; version: string; digest: string };\n target: TargetContextV2;\n limits: { schemaVersion: 'scanner-limits-v2'; digest: string; usage: LimitUsageV2[] };\n analysis: { status: 'COMPLETE' | 'DEGRADED' | 'INDETERMINATE'; capabilities: CapabilityExecutionV2[]; diagnostics: AnalysisDiagnosticV2[] };\n workflow: { name: string | null; nodeCount: number; rawNodeCount: number; annotationNodeCount: number; triggerCount: number; actionCount: number; integrationCount: number; edgeCount: number; resolvedEdgeCount: number; payloadBytes: number; complexity: 'LOW' | 'MEDIUM' | 'HIGH'; isSubWorkflow: boolean };\n facts: SafeFactV2[]; traces: TraceV2[]; findings: FindingV2[];\n assessment: null | { score: number; grade: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'; scoringPolicyVersion: string; basisFindingIds: string[]; excludedReportOnlyFindingIds: string[]; excludedUncertainFindingIds: string[]; excludedNotApplicableFindingIds: string[]; unknownEvidenceCount: number };\n stats: { rejectedCandidates: number; collapsedCandidates: number; omittedFindings: number; serializedBytes: number };\n};\nexport type ScannerResultV2Validation = { ok: true; result: ScannerResultV2 } | { ok: false; errors: string[] };\n\nconst TOP = ['schemaVersion', 'engine', 'input', 'profile', 'ruleset', 'semantics', 'target', 'limits', 'analysis', 'workflow', 'facts', 'traces', 'findings', 'assessment', 'stats'] as const;\nconst DIGEST = /^[0-9a-f]{64}$/;\nconst POINTER = /^(?:|(?:\\/(?:[^~/]|~0|~1)*)+)$/;\nconst SECRET = /(?:api[ _-]*key|password|secret|credential|authorization|cookie|bearer|token)\\s*[:=]|\\b(?:sk[-_][\\w-]+|AKIA[0-9A-Z]{16}|eyJ[\\w-]{12,}\\.[\\w-]{8,})\\b/i;\nconst UNSAFE = /(?:https?|ftp):\\/\\/|(?:^|[/\\\\])\\.\\.(?:[/\\\\]|$)|(?:^[/\\\\]|^[A-Za-z]:[/\\\\])|\\b(?:exception|stack trace|traceback|error:| at [A-Za-z]:[/\\\\])/i;\nconst FACT_KINDS = new Set(['workflow.summary.v1', 'workflow.function.v1', 'workflow.risk-summary.v1', 'workflow.fingerprint.v1', 'integration.v1', 'node.capability.v2', 'node.configuration.v2', 'code.indicator.v2', 'dataflow.summary.v2', 'destination.v2', 'ingress.v2', 'advisory.applicability.v2']);\nconst FACT_PROPERTIES: Record<string, readonly string[]> = { 'workflow.summary.v1': ['connectionCount'], 'workflow.function.v1': ['basicPurpose', 'triggerDescription', 'dataFlowSummary', 'businessCategory', 'confidence'], 'workflow.risk-summary.v1': ['topRisks', 'dataExposure', 'complexityDrivers'], 'workflow.fingerprint.v1': ['value'], 'integration.v1': ['service', 'usage', 'nodeTypes', 'nodeCount', 'riskNotes'], 'node.capability.v2': ['nodeType', 'nodePackage', 'namespaceClass', 'capabilities', 'toolCount', 'contextCount'], 'node.configuration.v2': ['observation', 'header', 'literalValue', 'parameterPath', 'secretKind', 'indicator', 'hasLiteralValue'], 'code.indicator.v2': ['language', 'indicator', 'member', 'start', 'end', 'parseState'], 'dataflow.summary.v2': ['flowKind', 'sink', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'sourceNodeId', 'sourceNodeName', 'humanGatePresent', 'humanGateDominates', 'taintLabels'], 'destination.v2': ['parameterPath', 'scheme', 'hostname', 'authorityState', 'valueMode'], 'ingress.v2': ['authentication', 'authenticationState', 'legacyAuthenticated'], 'advisory.applicability.v2': ['advisoryId', 'applicability', 'reviewState', 'matchedPrerequisites', 'unknownPrerequisites'] };\nconst CAPABILITY_ORDER = ['source-normalization', 'workflow-insights', 'structural-policies', 'expression-security', 'javascript-security', 'python-security', 'graph-semantics', 'taint-confidentiality', 'taint-integrity', 'agentic-control', 'assessment', 'presentation-facts'] as const;\n\ntype PlainRecord = Record<string, unknown>;\nconst isRecord = (v: unknown): v is PlainRecord => { try { return v !== null && typeof v === 'object' && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype; } catch { return false; } };\nfunction object(v: unknown, keys: readonly string[], required: readonly string[], errors: string[], path: string): PlainRecord | undefined {\n if (!isRecord(v)) { errors.push(`${path} must be an object`); return undefined; }\n try { if (Object.getOwnPropertySymbols(v).length) { errors.push(`${path} has symbols`); return undefined; } const names = Object.getOwnPropertyNames(v); const out = Object.create(Object.prototype) as PlainRecord;\n for (const name of names) { const d = Object.getOwnPropertyDescriptor(v, name); if (!d || !('value' in d)) { errors.push(`${path}.${name} must be data`); return undefined; } if (!keys.includes(name)) errors.push(`${path}.${name} is unknown`); Object.defineProperty(out, name, { value: d.value, writable: true, enumerable: true, configurable: true }); }\n for (const name of required) if (!names.includes(name)) errors.push(`${path}.${name} is missing`); return out;\n } catch { errors.push(`${path} cannot be inspected`); return undefined; }\n}\nfunction array(v: unknown, errors: string[], path: string, max = 100_000): unknown[] {\n if (!Array.isArray(v)) { errors.push(`${path} must be an array`); return []; }\n try { const length = v.length; if (!Number.isSafeInteger(length) || length < 0 || length > max) { errors.push(`${path} has an unsafe shape`); return []; } if (Object.getPrototypeOf(v) !== Array.prototype) { errors.push(`${path} must be an array`); return []; }\n const names = Object.getOwnPropertyNames(v); if (Object.getOwnPropertySymbols(v).length || names.length !== length + 1) { errors.push(`${path} has an unsafe shape`); return []; } const out = new Array<unknown>(length);\n for (const name of names) { if (name === 'length') continue; if (!/^(?:0|[1-9]\\d*)$/.test(name) || Number(name) >= length) { errors.push(`${path} is sparse`); return []; } const d = Object.getOwnPropertyDescriptor(v, name); if (!d || !('value' in d)) { errors.push(`${path}[${name}] must be data`); return []; } out[Number(name)] = d.value; } return out;\n } catch { errors.push(`${path} cannot be inspected`); return []; }\n}\nfunction text(v: unknown, errors: string[], path: string, unsafe = true, max = 4096): v is string { if (typeof v !== 'string' || v.length > max || v.includes('\\0') || /[\\u0001-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]/.test(v) || /[\\ud800-\\udfff]/.test(v) && !/^[\\u0000-\\ud7ff\\ue000-\\uffff]*(?:[\\ud800-\\udbff][\\udc00-\\udfff][\\u0000-\\ud7ff\\ue000-\\uffff]*)*$/.test(v) || unsafe && (SECRET.test(v) || UNSAFE.test(v))) { errors.push(`${path} has unsafe text`); return false; } return true; }\nfunction digest(v: unknown, errors: string[], path: string): v is string { if (typeof v !== 'string' || !DIGEST.test(v)) { errors.push(`${path} must be lowercase sha256`); return false; } return true; }\nfunction integer(v: unknown, errors: string[], path: string, min = 0): v is number { if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < min) { errors.push(`${path} must be a safe integer`); return false; } return true; }\nfunction en(v: unknown, values: readonly string[], errors: string[], path: string): boolean { if (typeof v !== 'string' || !values.includes(v)) { errors.push(`${path} has an invalid enum`); return false; } return true; }\nfunction refs(v: unknown, errors: string[], path: string): string[] { const out = array(v, errors, path); const seen = new Set<string>(); const result: string[] = []; for (const [i, item] of out.entries()) { if (digest(item, errors, `${path}[${i}]`) && seen.has(item)) errors.push(`${path} has a duplicate reference`); if (typeof item === 'string') { seen.add(item); result.push(item); } } return result; }\nfunction position(v: unknown, errors: string[], path: string): PlainRecord | undefined { const o = object(v, ['line', 'column', 'utf16Offset', 'utf8ByteOffset'], ['line', 'column', 'utf16Offset', 'utf8ByteOffset'], errors, path); if (!o) return; integer(o.line, errors, `${path}.line`, 1); integer(o.column, errors, `${path}.column`, 1); integer(o.utf16Offset, errors, `${path}.utf16Offset`); integer(o.utf8ByteOffset, errors, `${path}.utf8ByteOffset`); return o; }\nfunction source(v: unknown, errors: string[], path: string): void { const o = object(v, ['pointer', 'occurrencePath', 'astNodeId', 'span'], ['pointer', 'occurrencePath', 'astNodeId', 'span'], errors, path); if (!o) return; if (text(o.pointer, errors, `${path}.pointer`, false, 2048) && !POINTER.test(o.pointer as string)) errors.push(`${path}.pointer is not RFC6901`); const p = array(o.occurrencePath, errors, `${path}.occurrencePath`); p.forEach((x, i) => integer(x, errors, `${path}.occurrencePath[${i}]`)); digest(o.astNodeId, errors, `${path}.astNodeId`); if (o.span !== null) { const s = object(o.span, ['start', 'end'], ['start', 'end'], errors, `${path}.span`); if (s) { const a = position(s.start, errors, `${path}.span.start`); const b = position(s.end, errors, `${path}.span.end`); if (a && b && typeof a.utf16Offset === 'number' && typeof b.utf16Offset === 'number' && typeof a.utf8ByteOffset === 'number' && typeof b.utf8ByteOffset === 'number' && typeof a.line === 'number' && typeof b.line === 'number' && typeof a.column === 'number' && typeof b.column === 'number' && (b.utf16Offset <= a.utf16Offset || b.utf8ByteOffset <= a.utf8ByteOffset || b.line < a.line || b.line === a.line && b.column <= a.column)) errors.push(`${path}.span is empty or reversed`); } } }\nfunction node(v: unknown, errors: string[], path: string): void { const o = object(v, ['ordinal', 'source', 'explicitId', 'name', 'identityDigest'], ['ordinal', 'source', 'identityDigest'], errors, path); if (!o) return; integer(o.ordinal, errors, `${path}.ordinal`); source(o.source, errors, `${path}.source`); if ('explicitId' in o) text(o.explicitId, errors, `${path}.explicitId`); if ('name' in o) text(o.name, errors, `${path}.name`); digest(o.identityDigest, errors, `${path}.identityDigest`); }\nfunction edge(v: unknown, errors: string[], path: string): void { const o = object(v, ['ordinal', 'sourceNode', 'targetNode', 'sourceLabel', 'targetLabel', 'connectionType', 'sourcePort', 'targetPort', 'source', 'resolution'], ['ordinal', 'sourceLabel', 'connectionType', 'sourcePort', 'targetPort', 'source', 'resolution'], errors, path); if (!o) return; integer(o.ordinal, errors, `${path}.ordinal`); if ('sourceNode' in o) node(o.sourceNode, errors, `${path}.sourceNode`); if ('targetNode' in o) node(o.targetNode, errors, `${path}.targetNode`); text(o.sourceLabel, errors, `${path}.sourceLabel`); if ('targetLabel' in o) text(o.targetLabel, errors, `${path}.targetLabel`); text(o.connectionType, errors, `${path}.connectionType`); integer(o.sourcePort, errors, `${path}.sourcePort`); integer(o.targetPort, errors, `${path}.targetPort`); source(o.source, errors, `${path}.source`); en(o.resolution, ['RESOLVED', 'AMBIGUOUS', 'UNRESOLVED'], errors, `${path}.resolution`); }\nfunction subject(v: unknown, errors: string[], path: string): void { const o = object(v, ['kind', 'node', 'edge', 'source'], ['kind'], errors, path); if (!o) return; if (o.kind === 'WORKFLOW') { if (Object.getOwnPropertyNames(o).length !== 1) errors.push(`${path} has unknown subject fields`); } else if (o.kind === 'NODE') { const n = object(o, ['kind', 'node'], ['kind', 'node'], errors, path); if (n) node(n.node, errors, `${path}.node`); } else if (o.kind === 'EDGE') { const e = object(o, ['kind', 'edge'], ['kind', 'edge'], errors, path); if (e) edge(e.edge, errors, `${path}.edge`); } else if (o.kind === 'SOURCE') { const s = object(o, ['kind', 'source'], ['kind', 'source'], errors, path); if (s) source(s.source, errors, `${path}.source`); } else errors.push(`${path}.kind has an invalid enum`); }\nfunction propertyObject(v: unknown, errors: string[], path: string): PlainRecord | undefined { if (!isRecord(v)) { errors.push(`${path} must be an object`); return undefined; } try { if (Object.getOwnPropertySymbols(v).length) { errors.push(`${path} has symbols`); return undefined; } const out = Object.create(Object.prototype) as PlainRecord; for (const key of Object.getOwnPropertyNames(v)) { const d = Object.getOwnPropertyDescriptor(v, key); if (!d || !('value' in d)) { errors.push(`${path}.${key} must be data`); return undefined; } Object.defineProperty(out, key, { value: d.value, writable: true, enumerable: true, configurable: true }); } return out; } catch { errors.push(`${path} cannot be inspected`); return undefined; } }\nfunction propertyText(value: unknown, key: string, errors: string[], path: string): value is string {\n const pointerProperty = key === 'parameterPath' || key === 'propertyPath';\n if (!text(value, errors, path, !pointerProperty)) return false;\n if (pointerProperty && !POINTER.test(value)) { errors.push(`${path} is not RFC6901`); return false; }\n return true;\n}\nfunction fact(v: unknown, errors: string[], path: string): string | undefined { const o = object(v, ['factId', 'kind', 'subject', 'properties'], ['factId', 'kind', 'subject', 'properties'], errors, path); if (!o) return; digest(o.factId, errors, `${path}.factId`); if (typeof o.kind !== 'string' || !FACT_KINDS.has(o.kind)) errors.push(`${path}.kind is not registered`); else text(o.kind, errors, `${path}.kind`, false); subject(o.subject, errors, `${path}.subject`); const p = propertyObject(o.properties, errors, `${path}.properties`); if (!p) return typeof o.factId === 'string' ? o.factId : undefined; for (const key of Object.getOwnPropertyNames(p)) { if (!/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(key)) errors.push(`${path}.properties.${key} is invalid`); if (typeof o.kind === 'string' && FACT_PROPERTIES[o.kind] && !FACT_PROPERTIES[o.kind].includes(key)) errors.push(`${path}.properties.${key} is not registered`); const value = p[key]; if (Array.isArray(value)) { const a = array(value, errors, `${path}.properties.${key}`, 1000); a.forEach((x, i) => { if (!(x === null || typeof x === 'boolean' || typeof x === 'number' && Number.isFinite(x) && Number.isSafeInteger(x) || typeof x === 'string' && text(x, errors, `${path}.properties.${key}[${i}]`))) errors.push(`${path}.properties.${key}[${i}] is unsafe`); }); } else if (!(value === null || typeof value === 'boolean' || typeof value === 'number' && Number.isFinite(value) && Number.isSafeInteger(value) || typeof value === 'string' && propertyText(value, key, errors, `${path}.properties.${key}`))) errors.push(`${path}.properties.${key} is unsafe`); } return typeof o.factId === 'string' ? o.factId : undefined; }\nfunction trace(v: unknown, facts: Set<string>, errors: string[], path: string): string | undefined { const o = object(v, ['traceId', 'kind', 'steps'], ['traceId', 'kind', 'steps'], errors, path); if (!o) return; digest(o.traceId, errors, `${path}.traceId`); en(o.kind, ['CONFIDENTIALITY', 'INTEGRITY', 'CONTROL'], errors, `${path}.kind`); const steps = array(o.steps, errors, `${path}.steps`, 10000); const ordinals = new Set<number>(); steps.forEach((item, i) => { const s = object(item, ['ordinal', 'kind', 'subject', 'factRefs'], ['ordinal', 'kind', 'subject', 'factRefs'], errors, `${path}.steps[${i}]`); if (!s) return; integer(s.ordinal, errors, `${path}.steps[${i}].ordinal`); if (typeof s.ordinal === 'number' && ordinals.has(s.ordinal)) errors.push(`${path}.steps has duplicate ordinal`); if (typeof s.ordinal === 'number') ordinals.add(s.ordinal); en(s.kind, ['SOURCE', 'PROPAGATION', 'SANITIZER', 'SINK'], errors, `${path}.steps[${i}].kind`); subject(s.subject, errors, `${path}.steps[${i}].subject`); for (const ref of refs(s.factRefs, errors, `${path}.steps[${i}].factRefs`)) if (!facts.has(ref)) errors.push(`${path}.steps[${i}] has dangling fact reference`); }); return typeof o.traceId === 'string' ? o.traceId : undefined; }\nfunction finding(v: unknown, facts: Set<string>, traces: Set<string>, errors: string[], path: string): string | undefined { const o = object(v, ['findingId', 'ruleId', 'ruleRevision', 'effect', 'severity', 'confidence', 'evidenceClass', 'conclusion', 'applicability', 'subject', 'factRefs', 'traceRefs', 'remediationId'], ['findingId', 'ruleId', 'ruleRevision', 'effect', 'severity', 'confidence', 'evidenceClass', 'conclusion', 'applicability', 'subject', 'factRefs', 'traceRefs', 'remediationId'], errors, path); if (!o) return; digest(o.findingId, errors, `${path}.findingId`); for (const k of ['ruleId', 'ruleRevision', 'remediationId']) text(o[k], errors, `${path}.${k}`); en(o.effect, ['SCORING', 'REPORT_ONLY'], errors, `${path}.effect`); en(o.severity, ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'INFO'], errors, `${path}.severity`); en(o.confidence, ['HIGH', 'MEDIUM', 'LOW'], errors, `${path}.confidence`); en(o.evidenceClass, ['CAPABILITY', 'CONFIGURATION', 'SUSPICIOUS_SYNTAX', 'POTENTIAL_DATAFLOW', 'VERSION_APPLICABILITY'], errors, `${path}.evidenceClass`); en(o.conclusion, ['OBSERVED', 'POTENTIAL', 'UNKNOWN'], errors, `${path}.conclusion`); en(o.applicability, ['APPLICABLE', 'NOT_APPLICABLE', 'UNKNOWN'], errors, `${path}.applicability`); subject(o.subject, errors, `${path}.subject`); for (const ref of refs(o.factRefs, errors, `${path}.factRefs`)) if (!facts.has(ref)) errors.push(`${path} has dangling fact reference`); for (const ref of refs(o.traceRefs, errors, `${path}.traceRefs`)) if (!traces.has(ref)) errors.push(`${path} has dangling trace reference`); return typeof o.findingId === 'string' ? o.findingId : undefined; }\ntype DiagnosticInfo = { id?: string; capabilityId?: string; aggregateEffect?: string; omitted?: number };\nfunction diagnostic(v: unknown, capabilities: Set<string>, errors: string[], path: string): DiagnosticInfo { const o = object(v, ['id', 'code', 'category', 'capabilityId', 'aggregateEffect', 'assessmentEligible', 'location', 'observed', 'maximum', 'omitted'], ['id', 'code', 'category', 'capabilityId', 'aggregateEffect', 'assessmentEligible'], errors, path); if (!o) return {}; digest(o.id, errors, `${path}.id`); if (!en(o.code, Object.keys(DIAGNOSTIC_REGISTRY_V2), errors, `${path}.code`)) return {}; const expected = DIAGNOSTIC_REGISTRY_V2[o.code as DiagnosticCodeV2]; en(o.category, ['LIMIT', 'SOURCE', 'PARSER', 'POLICY', 'GRAPH', 'CATALOGUE', 'COMPATIBILITY'], errors, `${path}.category`); text(o.capabilityId, errors, `${path}.capabilityId`); if (typeof o.capabilityId !== 'string' || !capabilities.has(o.capabilityId)) errors.push(`${path}.capabilityId is dangling`); en(o.aggregateEffect, ['NONE', 'DEGRADED', 'INDETERMINATE'], errors, `${path}.aggregateEffect`); if (typeof o.assessmentEligible !== 'boolean') errors.push(`${path}.assessmentEligible must be boolean`); if (BY_CAPABILITY_DIAGNOSTIC_CODES_V2[o.code as DiagnosticCodeV2] === true) { if (o.category !== expected[0] || !['DEGRADED', 'INDETERMINATE'].includes(String(o.aggregateEffect)) || o.assessmentEligible !== (o.aggregateEffect === 'DEGRADED')) errors.push(`${path} has invalid registry effect`); } else if (o.category !== expected[0] || o.aggregateEffect !== expected[1] || o.assessmentEligible !== expected[2]) errors.push(`${path} disagrees with diagnostic registry`); if ('location' in o) source(o.location, errors, `${path}.location`); for (const k of ['observed', 'maximum', 'omitted']) if (k in o) integer(o[k], errors, `${path}.${k}`); return { id: typeof o.id === 'string' ? o.id : undefined, capabilityId: typeof o.capabilityId === 'string' ? o.capabilityId : undefined, aggregateEffect: typeof o.aggregateEffect === 'string' ? o.aggregateEffect : undefined, omitted: typeof o.omitted === 'number' ? o.omitted : undefined }; }\ntype CapabilityInfo = { id?: string; required?: boolean; status?: string; skipped?: number; omitted?: number; diagnosticIds: string[] };\n/** Exact `total > sum(parts)`, subtracting one part at a time so no intermediate can round past 2^53. */\nfunction exceeds(total: number, parts: readonly [number, number, number]): boolean { let remaining = total; for (const part of parts) { if (remaining <= part) return false; remaining -= part; } return true; }\n/**\n * The count arithmetic of the completeness lattice, restated because `contracts/` cannot import the\n * scanner core; `count-lattice-contract-pin.test.ts` pins this restatement to the producer over every\n * count set. A row cannot analyze units it never accounted for (`UNSEEN_ANALYSIS`) and cannot leave\n * observed units unaccounted for (`UNACCOUNTED_SEEN`): either way a `COMPLETED` row publishes a\n * completeness its own record does not support. The counters are deliberately not required to\n * partition `seen`, because analyzers count in their own units, so only these two directions - which\n * no run can produce - are refused.\n */\nfunction countConsistency(counts: readonly (number | undefined)[], path: string, errors: string[]): void {\n const [seen, analyzed, skipped, omitted] = counts;\n if (seen === undefined || analyzed === undefined || skipped === undefined || omitted === undefined) return;\n if (exceeds(analyzed, [seen, skipped, omitted])) errors.push(`${path} counters record UNSEEN_ANALYSIS: analyzed exceeds seen + skipped + omitted`);\n else if (exceeds(seen, [analyzed, skipped, omitted])) errors.push(`${path} counters record UNACCOUNTED_SEEN: seen exceeds analyzed + skipped + omitted`);\n}\nfunction capability(v: unknown, errors: string[], path: string): CapabilityInfo { const o = object(v, ['id', 'version', 'required', 'status', 'seen', 'analyzed', 'skipped', 'omitted', 'diagnosticIds'], ['id', 'version', 'required', 'status', 'seen', 'analyzed', 'skipped', 'omitted', 'diagnosticIds'], errors, path); if (!o) return { diagnosticIds: [] }; text(o.id, errors, `${path}.id`); text(o.version, errors, `${path}.version`); if (typeof o.required !== 'boolean') errors.push(`${path}.required must be boolean`); en(o.status, ['COMPLETED', 'SKIPPED', 'DEGRADED', 'FAILED'], errors, `${path}.status`); const counts: Array<number | undefined> = []; for (const k of ['seen', 'analyzed', 'skipped', 'omitted']) { const value = o[k]; counts.push(integer(value, errors, `${path}.${k}`) ? value : undefined); } countConsistency(counts, path, errors); const diagnosticIds = refs(o.diagnosticIds, errors, `${path}.diagnosticIds`); return { id: typeof o.id === 'string' ? o.id : undefined, required: typeof o.required === 'boolean' ? o.required : undefined, status: typeof o.status === 'string' ? o.status : undefined, skipped: typeof o.skipped === 'number' ? o.skipped : undefined, omitted: typeof o.omitted === 'number' ? o.omitted : undefined, diagnosticIds }; }\nfunction target(v: unknown, errors: string[]): void { const o = object(v, ['n8nVersion', 'edition', 'deployment', 'role', 'taskRunner', 'communityPackages', 'configuration', 'contextDigest'], ['edition', 'deployment', 'role', 'taskRunner', 'communityPackages', 'configuration', 'contextDigest'], errors, 'target'); if (!o) return; if ('n8nVersion' in o) text(o.n8nVersion, errors, 'target.n8nVersion'); en(o.edition, ['COMMUNITY', 'ENTERPRISE', 'CLOUD', 'UNKNOWN'], errors, 'target.edition'); en(o.deployment, ['SELF_HOSTED', 'CLOUD', 'UNKNOWN'], errors, 'target.deployment'); en(o.role, ['OWNER', 'ADMIN', 'MEMBER', 'UNKNOWN'], errors, 'target.role'); en(o.taskRunner, ['LEGACY', 'NATIVE', 'UNKNOWN'], errors, 'target.taskRunner'); digest(o.contextDigest, errors, 'target.contextDigest'); const packs = array(o.communityPackages, errors, 'target.communityPackages'); const names = new Set<string>(); packs.forEach((v, i) => { const p = object(v, ['name', 'version'], ['name'], errors, `target.communityPackages[${i}]`); if (p) { text(p.name, errors, `target.communityPackages[${i}].name`); if ('version' in p) text(p.version, errors, `target.communityPackages[${i}].version`); if (typeof p.name === 'string' && names.has(p.name)) errors.push('target.communityPackages has duplicates'); if (typeof p.name === 'string') names.add(p.name); } }); const cfg = array(o.configuration, errors, 'target.configuration'); const configKeys = new Set<string>(); cfg.forEach((v, i) => { const p = object(v, ['key', 'state'], ['key', 'state'], errors, `target.configuration[${i}]`); if (p) { text(p.key, errors, `target.configuration[${i}].key`); en(p.state, ['ENABLED', 'DISABLED', 'UNKNOWN'], errors, `target.configuration[${i}].state`); if (typeof p.key === 'string' && configKeys.has(p.key)) errors.push('target.configuration has duplicates'); if (typeof p.key === 'string') configKeys.add(p.key); } }); }\nfunction assessment(v: unknown, findings: Set<string>, errors: string[]): void { if (v === null) return; const o = object(v, ['score', 'grade', 'scoringPolicyVersion', 'basisFindingIds', 'excludedReportOnlyFindingIds', 'excludedUncertainFindingIds', 'excludedNotApplicableFindingIds', 'unknownEvidenceCount'], ['score', 'grade', 'scoringPolicyVersion', 'basisFindingIds', 'excludedReportOnlyFindingIds', 'excludedUncertainFindingIds', 'excludedNotApplicableFindingIds', 'unknownEvidenceCount'], errors, 'assessment'); if (!o) return; integer(o.score, errors, 'assessment.score'); if (typeof o.score === 'number' && o.score > 100) errors.push('assessment.score must be at most 100'); if (typeof o.score === 'number') { const grade = o.score >= 80 ? 'CRITICAL' : o.score >= 55 ? 'HIGH' : o.score >= 25 ? 'MEDIUM' : 'LOW'; if (o.grade !== grade) errors.push('assessment.grade disagrees with score'); } en(o.grade, ['LOW', 'MEDIUM', 'HIGH', 'CRITICAL'], errors, 'assessment.grade'); text(o.scoringPolicyVersion, errors, 'assessment.scoringPolicyVersion'); const all = new Set<string>(); let uncertainCount = 0; for (const k of ['basisFindingIds', 'excludedReportOnlyFindingIds', 'excludedUncertainFindingIds', 'excludedNotApplicableFindingIds']) { const ids = refs(o[k], errors, `assessment.${k}`); if (k === 'excludedUncertainFindingIds') uncertainCount = ids.length; for (const id of ids) { if (!findings.has(id)) errors.push(`assessment.${k} has dangling finding reference`); if (all.has(id)) errors.push('assessment finding classes overlap'); all.add(id); } } integer(o.unknownEvidenceCount, errors, 'assessment.unknownEvidenceCount'); if (typeof o.unknownEvidenceCount === 'number' && o.unknownEvidenceCount !== uncertainCount) errors.push('assessment.unknownEvidenceCount is inconsistent'); if (all.size !== findings.size) errors.push('assessment does not classify every finding'); }\n/**\n * A capability row may claim `COMPLETED` only when its counters record no unperformed units, and the\n * published analysis status must be the strongest effect those rows and the diagnostics impose:\n * a required row that dropped omitted units, failed, or was skipped makes the result indeterminate,\n * while any other recorded skip or omission degrades it.\n */\nfunction analysisStatus(status: unknown, capabilities: readonly CapabilityInfo[], diagnostics: readonly DiagnosticInfo[], resultOmitted: boolean, errors: string[]): void {\n let expected: 'COMPLETE' | 'DEGRADED' | 'INDETERMINATE' = 'COMPLETE';\n capabilities.forEach((item, index) => {\n // `skipped` and `omitted` are the units the row recorded but did not perform.\n const unperformed = (item.skipped ?? 0) > 0 || (item.omitted ?? 0) > 0;\n const unsafeTruncation = item.required === true && (item.omitted ?? 0) > 0;\n if (item.status === 'COMPLETED' && unperformed) errors.push(`analysis.capabilities[${index}] claims COMPLETED while recording skipped or omitted units`);\n if (item.required === true && (item.status === 'FAILED' || item.status === 'SKIPPED')) expected = 'INDETERMINATE';\n else if (unsafeTruncation) expected = 'INDETERMINATE';\n else if (expected === 'COMPLETE' && (item.status !== 'COMPLETED' || unperformed)) expected = 'DEGRADED';\n });\n for (const item of diagnostics) { if (item.aggregateEffect === 'INDETERMINATE') expected = 'INDETERMINATE'; else if (expected === 'COMPLETE' && item.aggregateEffect === 'DEGRADED') expected = 'DEGRADED'; }\n if (resultOmitted && expected === 'COMPLETE') expected = 'DEGRADED';\n if (status !== expected) errors.push('analysis.status disagrees with capability/diagnostic effects');\n}\nfunction resultOmitted(limitsOmitted: boolean, stats: PlainRecord | undefined, diagnostics: readonly DiagnosticInfo[]): boolean { if (limitsOmitted || typeof stats?.omittedFindings === 'number' && stats.omittedFindings > 0) return true; return diagnostics.some((item) => typeof item.omitted === 'number' && item.omitted > 0); }\nconst MAX_CLONE_DEPTH = 128;\nconst MAX_CLONE_NODES = 1_000_000;\nconst MAX_CLONE_PROPERTIES = 5_000_000;\nfunction cloneGraph(root: unknown): unknown {\n const active = new Set<object>(); const copies = new Map<object, PlainRecord | unknown[]>();\n let nodes = 0; let properties = 0;\n const clone = (value: unknown, depth: number): unknown => {\n if (value === null) return null;\n if (typeof value !== 'object') {\n if (typeof value === 'string' || typeof value === 'number' && Number.isFinite(value) || typeof value === 'boolean') return value;\n throw new Error('unsafe scalar');\n }\n if (depth > MAX_CLONE_DEPTH) throw new Error('clone depth exceeded');\n if (copies.has(value)) {\n if (active.has(value)) throw new Error('cyclic graph');\n return copies.get(value);\n }\n if (++nodes > MAX_CLONE_NODES) throw new Error('clone node limit exceeded');\n active.add(value);\n try {\n const isArray = Array.isArray(value);\n if (Object.getPrototypeOf(value) !== (isArray ? Array.prototype : Object.prototype)) throw new Error('unsafe prototype');\n if (Object.getOwnPropertySymbols(value).length) throw new Error('symbols are not supported');\n const names = Object.getOwnPropertyNames(value); properties += names.length;\n if (properties > MAX_CLONE_PROPERTIES) throw new Error('clone property limit exceeded');\n if (isArray) {\n const lengthDescriptor = Object.getOwnPropertyDescriptor(value, 'length');\n if (!lengthDescriptor || !('value' in lengthDescriptor) || !Number.isSafeInteger(lengthDescriptor.value) || lengthDescriptor.value < 0 || lengthDescriptor.value > 100_000 || names.length !== lengthDescriptor.value + 1) throw new Error('unsafe array shape');\n const out = new Array<unknown>(lengthDescriptor.value); copies.set(value, out);\n for (const name of names) {\n if (name === 'length') continue;\n if (!/^(?:0|[1-9]\\d*)$/.test(name) || Number(name) >= lengthDescriptor.value) throw new Error('unsafe array index');\n const descriptor = Object.getOwnPropertyDescriptor(value, name);\n if (!descriptor || !('value' in descriptor)) throw new Error('accessor is not supported');\n Object.defineProperty(out, name, { value: clone(descriptor.value, depth + 1), writable: true, enumerable: true, configurable: true });\n }\n return Object.freeze(out);\n }\n const out = Object.create(Object.prototype) as PlainRecord; copies.set(value, out);\n for (const name of names) {\n const descriptor = Object.getOwnPropertyDescriptor(value, name);\n if (!descriptor || !('value' in descriptor)) throw new Error('accessor is not supported');\n Object.defineProperty(out, name, { value: clone(descriptor.value, depth + 1), writable: true, enumerable: true, configurable: true });\n }\n return Object.freeze(out);\n } finally { active.delete(value); }\n };\n return clone(root, 0);\n}\nexport function validateScannerResultV2(candidate: unknown): ScannerResultV2Validation {\n const errors: string[] = []; let snapshot: unknown; try { snapshot = cloneGraph(candidate); } catch { return { ok: false, errors: ['result cannot be safely copied'] }; } const root = object(snapshot, TOP, TOP, errors, 'result'); if (!root) return { ok: false, errors };\n if (root.schemaVersion !== 'scanner-result-v2') errors.push('result.schemaVersion is unsupported');\n const e = object(root.engine, ['id', 'version', 'buildDigest'], ['id', 'version', 'buildDigest'], errors, 'engine'); if (e) { if (e.id !== 'secureflow-scanner') errors.push('engine.id is unsupported'); text(e.version, errors, 'engine.version'); digest(e.buildDigest, errors, 'engine.buildDigest'); }\n const input = object(root.input, ['rawSha256', 'semanticSha256', 'ambiguitySha256', 'ambiguityCount', 'utf8Bytes'], ['rawSha256', 'semanticSha256', 'ambiguitySha256', 'ambiguityCount', 'utf8Bytes'], errors, 'input'); if (input) { digest(input.rawSha256, errors, 'input.rawSha256'); digest(input.semanticSha256, errors, 'input.semanticSha256'); digest(input.ambiguitySha256, errors, 'input.ambiguitySha256'); integer(input.ambiguityCount, errors, 'input.ambiguityCount'); integer(input.utf8Bytes, errors, 'input.utf8Bytes'); }\n for (const k of ['profile', 'ruleset', 'semantics'] as const) { const o = object(root[k], k === 'profile' ? ['id', 'version'] : ['id', 'version', 'digest', ...(k === 'ruleset' ? ['signatureStatus'] : [])], ['id', 'version', ...(k === 'profile' ? [] : ['digest']), ...(k === 'ruleset' ? ['signatureStatus'] : [])], errors, k); if (o) { text(o.id, errors, `${k}.id`); text(o.version, errors, `${k}.version`); if (k !== 'profile') digest(o.digest, errors, `${k}.digest`); if (k === 'ruleset') en(o.signatureStatus, ['VERIFIED', 'UNVERIFIED'], errors, 'ruleset.signatureStatus'); } }\n target(root.target, errors);\n const lim = object(root.limits, ['schemaVersion', 'digest', 'usage'], ['schemaVersion', 'digest', 'usage'], errors, 'limits'); let limitsOmitted = false; if (lim) { if (lim.schemaVersion !== 'scanner-limits-v2') errors.push('limits.schemaVersion is unsupported'); digest(lim.digest, errors, 'limits.digest'); const ids = new Set<string>(); array(lim.usage, errors, 'limits.usage').forEach((v, i) => { const u = object(v, ['id', 'maximum', 'examined', 'omitted', 'exhausted'], ['id', 'maximum', 'examined', 'omitted', 'exhausted'], errors, `limits.usage[${i}]`); if (u) { text(u.id, errors, `limits.usage[${i}].id`); integer(u.maximum, errors, `limits.usage[${i}].maximum`); integer(u.examined, errors, `limits.usage[${i}].examined`); integer(u.omitted, errors, `limits.usage[${i}].omitted`); if (typeof u.omitted === 'number' && u.omitted > 0) limitsOmitted = true; if (typeof u.maximum === 'number' && typeof u.examined === 'number' && u.examined < u.maximum && u.exhausted === true) errors.push('limits.usage exhausted before maximum'); if (typeof u.id === 'string' && ids.has(u.id)) errors.push('limits.usage has duplicate id'); if (typeof u.id === 'string') ids.add(u.id); if (typeof u.exhausted !== 'boolean') errors.push(`limits.usage[${i}].exhausted must be boolean`); } }); }\n const stats = object(root.stats, ['rejectedCandidates', 'collapsedCandidates', 'omittedFindings', 'serializedBytes'], ['rejectedCandidates', 'collapsedCandidates', 'omittedFindings', 'serializedBytes'], errors, 'stats'); if (stats) for (const k of ['rejectedCandidates', 'collapsedCandidates', 'omittedFindings', 'serializedBytes']) integer(stats[k], errors, `stats.${k}`);\n const facts = new Set<string>(); const factIds = new Set<string>(); array(root.facts, errors, 'facts').forEach((v, i) => { const id = fact(v, errors, `facts[${i}]`); if (id && factIds.has(id)) errors.push('facts has duplicate factId'); if (id) { factIds.add(id); facts.add(id); } });\n const traces = new Set<string>(); const traceIds = new Set<string>(); array(root.traces, errors, 'traces').forEach((v, i) => { const id = trace(v, facts, errors, `traces[${i}]`); if (id && traceIds.has(id)) errors.push('traces has duplicate traceId'); if (id) { traceIds.add(id); traces.add(id); } });\n const findings = new Set<string>(); const findingIds = new Set<string>(); array(root.findings, errors, 'findings').forEach((v, i) => { const id = finding(v, facts, traces, errors, `findings[${i}]`); if (id && findingIds.has(id)) errors.push('findings has duplicate findingId'); if (id) { findingIds.add(id); findings.add(id); } });\n const analysis = object(root.analysis, ['status', 'capabilities', 'diagnostics'], ['status', 'capabilities', 'diagnostics'], errors, 'analysis');\n if (analysis) {\n en(analysis.status, ['COMPLETE', 'DEGRADED', 'INDETERMINATE'], errors, 'analysis.status'); const caps = array(analysis.capabilities, errors, 'analysis.capabilities'); const capIds = new Set<string>(); let lastOrder = -1; const capInfos: CapabilityInfo[] = []; const ownership = new Map<string, string[]>();\n caps.forEach((v, i) => { const x = capability(v, errors, `analysis.capabilities[${i}]`); capInfos.push(x); if (x.id) { if (capIds.has(x.id)) errors.push('analysis.capabilities has duplicate id'); const order = CAPABILITY_ORDER.indexOf(x.id as typeof CAPABILITY_ORDER[number]); if (order < 0) errors.push(`analysis.capabilities[${i}].id is not registered`); else if (order <= lastOrder) errors.push('analysis.capabilities are out of registry order'); else lastOrder = order; capIds.add(x.id); for (const id of x.diagnosticIds) ownership.set(id, [...(ownership.get(id) ?? []), x.id]); } });\n const ds = array(analysis.diagnostics, errors, 'analysis.diagnostics'); const diagInfos: DiagnosticInfo[] = []; const diagIds = new Set<string>(); const diagOwners = new Map<string, string>(); ds.forEach((v, i) => { const info = diagnostic(v, capIds, errors, `analysis.diagnostics[${i}]`); diagInfos.push(info); if (info.id && diagIds.has(info.id)) errors.push('analysis.diagnostics has duplicate id'); if (info.id) { diagIds.add(info.id); if (info.capabilityId) diagOwners.set(info.id, info.capabilityId); } });\n for (const [id, owners] of ownership) { if (!diagIds.has(id)) errors.push('capability diagnostic reference is dangling'); if (owners.length !== 1) errors.push('diagnostic has multiple capability owners'); else if (diagOwners.get(id) !== owners[0]) errors.push('diagnostic ownership disagrees with capabilityId'); }\n for (const id of diagIds) if (!ownership.has(id)) errors.push('diagnostic is unreferenced by capabilities');\n /**\n * A diagnostic that names the units it omitted is the capability's own record of unperformed work, so\n * the row that owns it has to record the same loss. Counters claiming nothing was omitted while their\n * diagnostic records truncation is the reachable form of silent truncation, and it is the one\n * counter/diagnostic pairing no run can produce.\n */\n const omittedByCapability = new Map<string, number>();\n for (const info of capInfos) if (info.id !== undefined && info.omitted !== undefined) omittedByCapability.set(info.id, info.omitted);\n diagInfos.forEach((info, index) => { if (info.capabilityId !== undefined && (info.omitted ?? 0) > 0 && omittedByCapability.get(info.capabilityId) === 0) errors.push(`analysis.diagnostics[${index}] counters record UNRECORDED_OMISSION: omitted exceeds the owning capability omitted count`); });\n analysisStatus(analysis.status, capInfos, diagInfos, resultOmitted(limitsOmitted, stats, diagInfos), errors); if (analysis.status === 'INDETERMINATE' && root.assessment !== null) errors.push('indeterminate analysis must have null assessment'); if (analysis.status === 'COMPLETE' && root.assessment === null) errors.push('complete analysis requires assessment');\n }\n const workflow = object(root.workflow, ['name', 'nodeCount', 'rawNodeCount', 'annotationNodeCount', 'triggerCount', 'actionCount', 'integrationCount', 'edgeCount', 'resolvedEdgeCount', 'payloadBytes', 'complexity', 'isSubWorkflow'], ['name', 'nodeCount', 'rawNodeCount', 'annotationNodeCount', 'triggerCount', 'actionCount', 'integrationCount', 'edgeCount', 'resolvedEdgeCount', 'payloadBytes', 'complexity', 'isSubWorkflow'], errors, 'workflow'); if (workflow) { if (workflow.name !== null) text(workflow.name, errors, 'workflow.name'); for (const k of ['nodeCount', 'rawNodeCount', 'annotationNodeCount', 'triggerCount', 'actionCount', 'integrationCount', 'edgeCount', 'resolvedEdgeCount', 'payloadBytes']) integer(workflow[k], errors, `workflow.${k}`); en(workflow.complexity, ['LOW', 'MEDIUM', 'HIGH'], errors, 'workflow.complexity'); if (typeof workflow.isSubWorkflow !== 'boolean') errors.push('workflow.isSubWorkflow must be boolean'); }\n assessment(root.assessment, findings, errors);\n if (errors.length) return { ok: false, errors }; return { ok: true, result: snapshot as ScannerResultV2 };\n}\nexport type { AnalysisDiagnosticV2, CapabilityExecutionV2, EdgeRefV2, FindingV2, NodeRefV2, SafeFactV2, SourceMemberRefV2, SubjectV2 };", "const encoder = new TextEncoder();\n\n/** Encode secureflow-canonical-json-v1 as deterministic UTF-8 bytes. */\nexport function canonicalBytesV1(value: unknown): Uint8Array {\n return encoder.encode(encodeValue(value, new Set<object>()));\n}\n\nfunction encodeValue(value: unknown, seen: Set<object>): string {\n if (value === null) return 'null';\n switch (typeof value) {\n case 'string': return encodeString(value);\n case 'boolean': return value ? 'true' : 'false';\n case 'number':\n if (!Number.isFinite(value)) throw new TypeError('Invalid canonical JSON number');\n return JSON.stringify(Object.is(value, -0) ? 0 : value) as string;\n case 'object': break;\n default: throw new TypeError('Invalid canonical JSON value');\n }\n if (seen.has(value)) throw new TypeError('Cyclic canonical JSON value');\n seen.add(value);\n try {\n return Array.isArray(value) ? encodeArray(value, seen) : encodeObject(value, seen);\n } finally {\n seen.delete(value);\n }\n}\n\nfunction encodeArray(value: readonly unknown[], seen: Set<object>): string {\n if (Object.getPrototypeOf(value) !== Array.prototype) throw new TypeError('Non-plain canonical JSON array');\n const names = ownNames(value);\n const length = dataDescriptor(value, 'length');\n if (typeof length !== 'number' || !Number.isSafeInteger(length) || length < 0) throw new TypeError('Invalid array length');\n if (names.length !== length + 1 || names.some((name) => name !== 'length' && !isArrayIndex(name, length))) {\n throw new TypeError('Unsafe array properties');\n }\n const items: string[] = [];\n for (let index = 0; index < length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n if (!descriptor || !('value' in descriptor)) throw new TypeError('Sparse canonical JSON array');\n items.push(encodeValue(descriptor.value, seen));\n }\n return `[${items.join(',')}]`;\n}\n\nfunction encodeObject(value: object, seen: Set<object>): string {\n let prototype: object | null;\n try { prototype = Object.getPrototypeOf(value); } catch { throw new TypeError('Unsafe canonical JSON object'); }\n if (prototype !== Object.prototype && prototype !== null) throw new TypeError('Non-plain canonical JSON object');\n const names = ownNames(value);\n names.sort(compareCodePointStrings);\n const entries: string[] = [];\n for (const name of names) {\n const descriptor = Object.getOwnPropertyDescriptor(value, name);\n if (!descriptor || !('value' in descriptor) || !descriptor.enumerable) {\n throw new TypeError('Unsafe canonical JSON property');\n }\n entries.push(`${encodeString(name)}:${encodeValue(descriptor.value, seen)}`);\n }\n return `{${entries.join(',')}}`;\n}\nfunction ownNames(value: object): string[] {\n let names: string[];\n let symbols: symbol[];\n try {\n names = Object.getOwnPropertyNames(value);\n symbols = Object.getOwnPropertySymbols(value);\n } catch { throw new TypeError('Unsafe canonical JSON object'); }\n if (symbols.length !== 0) throw new TypeError('Symbol-bearing canonical JSON object');\n return names;\n}\n\nfunction dataDescriptor(value: object, name: string): unknown {\n const descriptor = Object.getOwnPropertyDescriptor(value, name);\n if (!descriptor || !('value' in descriptor)) throw new TypeError('Accessor in canonical JSON value');\n return descriptor.value;\n}\n\nfunction isArrayIndex(name: string, length: number): boolean {\n if (!/^(?:0|[1-9][0-9]*)$/.test(name)) return false;\n const index = Number(name);\n return Number.isSafeInteger(index) && index < length;\n}\n\nfunction encodeString(value: string): string {\n let output = '\"';\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code === 0x22) output += '\\\\\"';\n else if (code === 0x5c) output += '\\\\\\\\';\n else if (code === 0x08) output += '\\\\b';\n else if (code === 0x09) output += '\\\\t';\n else if (code === 0x0a) output += '\\\\n';\n else if (code === 0x0c) output += '\\\\f';\n else if (code === 0x0d) output += '\\\\r';\n else if (code < 0x20) output += `\\\\u${code.toString(16).padStart(4, '0')}`;\n else if (code >= 0xd800 && code <= 0xdfff) {\n const next = value.charCodeAt(index + 1);\n if (code <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) { output += value[index] + value[index + 1]; index += 1; }\n else output += `\\\\u${code.toString(16).padStart(4, '0')}`;\n } else output += value[index];\n }\n return `${output}\"`;\n}\n\nfunction compareCodePointStrings(left: string, right: string): number {\n const a = Array.from(left, (char) => char.codePointAt(0)!);\n const b = Array.from(right, (char) => char.codePointAt(0)!);\n for (let index = 0; index < Math.min(a.length, b.length); index += 1) {\n if (a[index] !== b[index]) return a[index] - b[index];\n }\n return a.length - b.length;\n}\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport type { FindingV2, SafeFactV2, TraceStepV2, TraceV2 } from '../../../../contracts/scanner-v2-evidence';\nimport type { SubjectV2 } from '../../../../contracts/scanner-v2-source';\nimport { canonicalBytesV1 } from './canonical-bytes';\nimport { createEdgeIdentityDigest, encodeIdentityTuple } from '../workflow-v2/node-edge-identity';\n\ntype Subject = SubjectV2;\nexport type IdentityContextV2 = Readonly<{ semanticSha256: string }>;\nexport type FactIdentityInputV2 = Readonly<Pick<SafeFactV2, 'kind' | 'subject' | 'properties'>>;\nexport type TraceIdentityInputV2 = Readonly<Pick<TraceV2, 'kind' | 'steps'>>;\nexport type FindingIdentityInputV2 = Readonly<Pick<FindingV2,\n 'ruleId' | 'ruleRevision' | 'evidenceClass' | 'conclusion' | 'applicability' | 'subject' | 'factRefs' | 'traceRefs'>>;\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst DIGEST = /^[0-9a-f]{64}$/;\n\nexport function canonicalSubjectIdentity(subject: Subject, context?: IdentityContextV2): string {\n const record = exactRecord(subject, ['kind', 'node', 'edge', 'source']);\n if (record.kind === 'WORKFLOW') {\n const semanticSha256 = context?.semanticSha256;\n if (!DIGEST.test(semanticSha256 ?? '')) throw new TypeError('Workflow identity needs semanticSha256');\n if (Object.keys(record).length !== 1) throw new TypeError('Invalid workflow subject');\n return `WORKFLOW${semanticSha256}`;\n }\n if (record.kind === 'SOURCE') {\n if (Object.keys(record).length !== 2) throw new TypeError('Invalid source subject');\n const source = exactRecord(record.source, ['pointer', 'occurrencePath', 'astNodeId', 'span']);\n if (typeof source.astNodeId !== 'string' || !DIGEST.test(source.astNodeId)) throw new TypeError('Invalid source identity');\n return `SOURCE${source.astNodeId}`;\n }\n if (record.kind === 'NODE') {\n if (Object.keys(record).length !== 2) throw new TypeError('Invalid node subject');\n const node = exactRecord(record.node, ['ordinal', 'source', 'explicitId', 'name', 'identityDigest']);\n if (typeof node.identityDigest !== 'string' || !DIGEST.test(node.identityDigest)) throw new TypeError('Invalid node identity');\n return `NODE${node.identityDigest}`;\n }\n if (record.kind === 'EDGE') {\n if (Object.keys(record).length !== 2) throw new TypeError('Invalid edge subject');\n const edge = exactRecord(record.edge, ['ordinal', 'sourceNode', 'targetNode', 'sourceLabel', 'targetLabel', 'connectionType', 'sourcePort', 'targetPort', 'source', 'resolution']);\n return `EDGE${createEdgeIdentityDigest(normalizeEdge(edge))}`;\n }\n throw new TypeError('Invalid subject kind');\n}\n\nfunction normalizeEdge(edge: Record<string, unknown>): Parameters<typeof createEdgeIdentityDigest>[0] {\n const source = sourceDigestRecord(edge.source);\n const sourceNode = edge.sourceNode === undefined ? undefined : nodeDigestRecord(edge.sourceNode);\n const targetNode = edge.targetNode === undefined ? undefined : nodeDigestRecord(edge.targetNode);\n if (!Number.isSafeInteger(edge.ordinal) || (edge.ordinal as number) < 0 || typeof edge.sourceLabel !== 'string'\n || edge.targetLabel !== undefined && typeof edge.targetLabel !== 'string' || typeof edge.connectionType !== 'string'\n || !Number.isSafeInteger(edge.sourcePort) || (edge.sourcePort as number) < 0\n || !Number.isSafeInteger(edge.targetPort) || (edge.targetPort as number) < 0\n || !['RESOLVED', 'AMBIGUOUS', 'UNRESOLVED'].includes(edge.resolution as string)) throw new TypeError('Invalid edge identity');\n return { ordinal: edge.ordinal as number, sourceNode, targetNode, sourceLabel: edge.sourceLabel as string,\n targetLabel: edge.targetLabel as string | undefined, connectionType: edge.connectionType as string, sourcePort: edge.sourcePort as number,\n targetPort: edge.targetPort as number, source, resolution: edge.resolution as 'RESOLVED' | 'AMBIGUOUS' | 'UNRESOLVED' };\n}\n\nfunction sourceDigestRecord(value: unknown): Parameters<typeof createEdgeIdentityDigest>[0]['source'] {\n const source = exactRecord(value, ['pointer', 'occurrencePath', 'astNodeId', 'span']);\n if (typeof source.astNodeId !== 'string' || !DIGEST.test(source.astNodeId)) throw new TypeError('Invalid source identity');\n return source as Parameters<typeof createEdgeIdentityDigest>[0]['source'];\n}\n\nfunction nodeDigestRecord(value: unknown): NonNullable<Parameters<typeof createEdgeIdentityDigest>[0]['sourceNode']> {\n const node = exactRecord(value, ['ordinal', 'source', 'explicitId', 'name', 'identityDigest']);\n if (typeof node.identityDigest !== 'string' || !DIGEST.test(node.identityDigest)) throw new TypeError('Invalid node identity');\n return node as NonNullable<Parameters<typeof createEdgeIdentityDigest>[0]['sourceNode']>;\n}\n\nexport function createFactId(input: FactIdentityInputV2, context?: IdentityContextV2): string {\n const value = exactRecord(input, ['factId', 'kind', 'subject', 'properties']);\n if (typeof value.kind !== 'string' || value.kind.length === 0) throw new TypeError('Invalid fact identity');\n const subject = canonicalSubjectIdentity(value.subject as Subject, context);\n const properties = text(canonicalBytesV1(value.properties));\n return digest(['secureflow-fact-id-v2', value.kind, subject, properties]);\n}\n\nexport function createTraceId(input: TraceIdentityInputV2, context?: IdentityContextV2): string {\n const value = exactRecord(input, ['traceId', 'kind', 'steps']);\n if (typeof value.kind !== 'string' || !Array.isArray(value.steps)) throw new TypeError('Invalid trace identity');\n const steps = denseArray(value.steps).map((step) => canonicalTraceStep(step as TraceStepV2, context));\n const encoded = text(canonicalBytesV1(steps));\n return digest(['secureflow-trace-id-v2', value.kind, encoded]);\n}\n\nexport function createFindingId(input: FindingIdentityInputV2, context?: IdentityContextV2): string {\n const value = exactRecord(input, ['findingId', 'ruleId', 'ruleRevision', 'effect', 'severity', 'confidence', 'evidenceClass', 'conclusion', 'applicability', 'subject', 'factRefs', 'traceRefs', 'remediationId']);\n for (const key of ['ruleId', 'ruleRevision', 'evidenceClass', 'conclusion', 'applicability'] as const) if (typeof value[key] !== 'string') throw new TypeError('Invalid finding identity');\n const factRefs = sortedReferences(value.factRefs);\n const traceRefs = sortedReferences(value.traceRefs);\n return digest(['secureflow-finding-id-v2', value.ruleId, value.ruleRevision, value.evidenceClass,\n value.conclusion, value.applicability, canonicalSubjectIdentity(value.subject as Subject, context), ...factRefs, ...traceRefs]);\n}\n\nfunction canonicalTraceStep(step: TraceStepV2, context?: IdentityContextV2): Record<string, unknown> {\n const value = exactRecord(step, ['ordinal', 'kind', 'subject', 'factRefs']);\n if (!Number.isSafeInteger(value.ordinal) || value.ordinal < 0 || typeof value.kind !== 'string') throw new TypeError('Invalid trace step');\n return { ordinal: value.ordinal, kind: value.kind, subject: canonicalSubjectIdentity(value.subject as Subject, context), factRefs: sortedReferences(value.factRefs) };\n}\n\nfunction sortedReferences(value: unknown): string[] {\n const result = denseArray(value);\n if (result.some((item) => typeof item !== 'string' || !DIGEST.test(item as string))) throw new TypeError('Invalid identity reference');\n const strings = result as string[];\n strings.sort();\n for (let index = 1; index < strings.length; index += 1) if (strings[index] === strings[index - 1]) throw new TypeError('Duplicate identity reference');\n return strings;\n}\n\nfunction denseArray(value: unknown): unknown[] {\n if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype || Object.getOwnPropertySymbols(value).length !== 0) throw new TypeError('Invalid identity array');\n const length = Object.getOwnPropertyDescriptor(value, 'length');\n if (!length || !('value' in length) || !Number.isSafeInteger(length.value) || length.value < 0) throw new TypeError('Invalid identity array');\n const names = Object.getOwnPropertyNames(value);\n if (names.length !== length.value + 1 || names.some((name) => name !== 'length' && !/^(?:0|[1-9][0-9]*)$/.test(name) || Number(name) >= length.value)) throw new TypeError('Invalid identity array');\n const result: unknown[] = [];\n for (let index = 0; index < length.value; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n if (!descriptor || !('value' in descriptor)) throw new TypeError('Invalid identity array');\n result.push(descriptor.value);\n }\n return result;\n}\n\nfunction exactRecord(value: unknown, allowed: readonly string[]): Record<string, any> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('Invalid identity record');\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null || Object.getOwnPropertySymbols(value).length !== 0) throw new TypeError('Unsafe identity record');\n const output: Record<string, any> = {};\n for (const name of Object.getOwnPropertyNames(value)) {\n if (!allowed.includes(name)) throw new TypeError('Unknown identity property');\n const descriptor = Object.getOwnPropertyDescriptor(value, name);\n if (!descriptor || !('value' in descriptor) || !descriptor.enumerable) throw new TypeError('Accessor identity property');\n output[name] = descriptor.value;\n }\n return output;\n}\n\nfunction text(bytes: Uint8Array): string {\n return decoder.decode(bytes);\n}\n\nfunction digest(parts: readonly string[]): string {\n return bytesToHex(sha256(encoder.encode(encodeIdentityTuple(parts))));\n}\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { DEFAULT_SCANNER_LIMITS_V2 } from '@hub/contracts';\nimport { canonicalJsonBytes, canonicalizeJson } from '../canonical-json';\nimport { encodeIdentityTuple } from '../workflow-v2/node-edge-identity';\nimport { SAFE_FACT_AUTHORITY_DIGEST_V2, SAFE_FACT_EVIDENCE_MAPPINGS_V2 } from '../facts/safe-fact-registry';\nimport { betaHardenedRuleCatalog } from '../policy/rule-catalog';\nimport { RULE_PACK_DIGEST_V2 } from '../capabilities/candidate-validator';\nimport { BETA_DEFAULT_PROFILE_MANIFEST, computeProfileManifestDigest } from '../capabilities/profile-manifest';\nimport { createBetaDefaultCapabilityRegistry } from '../capabilities/beta-default';\nimport { createBetaDefaultPolicies } from '../policies/beta-policies';\nimport { BUILTIN_SEMANTIC_CATALOGUE_V2 } from '../semantics/builtin-catalogue';\nimport { createSemanticCatalogueDigest } from '../semantics/catalogue-admission';\nimport type { ResolvedNodeSemanticsV2 } from '../semantics/catalogue-schema';\nimport type { AdmittedRuleV2, CapabilityRegistryV2, RuleCatalogueViewV2, SemanticCatalogueViewV2 } from '../capabilities/scheduler';\n\nexport const ADMITTED_PROFILE_ID = 'beta-default' as const;\nexport const ADMITTED_PROFILE_VERSION = '2.0.0' as const;\nexport const ADMITTED_ENGINE_ID = 'secureflow-scanner' as const;\nexport const ADMITTED_ENGINE_VERSION = '2.0.0' as const;\nexport const RULESET_ID_V2 = 'scanner-core-builtins' as const;\nexport const RULESET_VERSION_V2 = '2.0.0' as const;\nexport const RULESET_SIGNATURE_STATUS_V2 = 'VERIFIED' as const;\nexport const RULE_KEYS = Object.freeze(SAFE_FACT_EVIDENCE_MAPPINGS_V2.map(({ ruleId }) => ruleId));\n\nconst ruleById = new Map(betaHardenedRuleCatalog.map((entry) => [entry.policyId, entry]));\nconst authorityRules: readonly AdmittedRuleV2[] = Object.freeze(SAFE_FACT_EVIDENCE_MAPPINGS_V2.map((mapping) => {\n const catalog = ruleById.get(mapping.ruleId);\n if (!catalog) throw new TypeError(`Missing built-in rule authority: ${mapping.ruleId}`);\n return Object.freeze({\n ruleId: mapping.ruleId, revision: '1', capabilityId: mapping.ownerCapabilityId,\n effect: mapping.ownerCapabilityId === 'structural-policies' ? 'SCORING' : 'REPORT_ONLY',\n severity: catalog.defaultSeverity, confidence: catalog.defaultConfidence,\n evidenceSchemaId: mapping.evidenceSchemaId, remediationId: 'r', cweIds: Object.freeze([...catalog.cweIds]),\n owaspAgenticIds: Object.freeze([...(catalog.owaspAgenticIds ?? [])]), packDigest: RULE_PACK_DIGEST_V2,\n });\n}));\nconst authorityRuleBody = Object.freeze(authorityRules.map(({ packDigest: _packDigest, ...rule }) => rule).sort((left, right) => left.ruleId < right.ruleId ? -1 : left.ruleId > right.ruleId ? 1 : 0));\n\nexport const PROFILE_MANIFEST_DIGEST_V2 = BETA_DEFAULT_PROFILE_MANIFEST.digest;\nexport { RULE_PACK_DIGEST_V2 };\nexport const RULE_PACK_DIGEST = RULE_PACK_DIGEST_V2;\nexport const LIMITS_AUTHORITY_DIGEST_V2 = bytesToHex(sha256(canonicalJsonBytes(DEFAULT_SCANNER_LIMITS_V2)));\nexport const SEMANTIC_CATALOGUE_DIGEST_V2 = BUILTIN_SEMANTIC_CATALOGUE_V2.digest;\nexport const ENGINE_BUILD_DIGEST_V2 = bytesToHex(sha256(canonicalJsonBytes({\n engine: ADMITTED_ENGINE_ID, version: ADMITTED_ENGINE_VERSION, profile: ADMITTED_PROFILE_ID,\n profileVersion: ADMITTED_PROFILE_VERSION, manifest: PROFILE_MANIFEST_DIGEST_V2,\n ruleset: RULE_PACK_DIGEST_V2, facts: SAFE_FACT_AUTHORITY_DIGEST_V2, semantics: SEMANTIC_CATALOGUE_DIGEST_V2,\n})));\n\nexport const BUILTIN_RULESET_AUTHORITY_V2 = Object.freeze({\n id: RULESET_ID_V2, version: RULESET_VERSION_V2, digest: RULE_PACK_DIGEST_V2,\n signatureStatus: RULESET_SIGNATURE_STATUS_V2,\n});\nexport const BUILTIN_SEMANTICS_AUTHORITY_V2 = Object.freeze({\n id: BUILTIN_SEMANTIC_CATALOGUE_V2.id, version: BUILTIN_SEMANTIC_CATALOGUE_V2.version,\n digest: BUILTIN_SEMANTIC_CATALOGUE_V2.digest,\n});\n/** The engine's own configuration vocabulary, read by the CLI before any item runs. */\nexport const ADMITTED_CONFIGURATION_KEYS_V2 = BUILTIN_SEMANTIC_CATALOGUE_V2.configurationKeys;\n\n/**\n * An empty allowlist is the no-argument path, so a scan that supplies none \u2014 or supplies `[]`, which\n * the request validator treats as absent \u2014 builds exactly the registry it built before the\n * allowlist was admitted, and its result stays byte-identical.\n */\nexport function createAdmittedCapabilityRegistry(approvedDomains: readonly string[] = []): CapabilityRegistryV2 {\n return approvedDomains.length === 0\n ? createBetaDefaultCapabilityRegistry()\n : createBetaDefaultCapabilityRegistry({ policies: createBetaDefaultPolicies({ approvedDomains }) });\n}\nexport function createAdmittedRuleView(): RuleCatalogueViewV2 {\n return Object.freeze({ id: RULESET_ID_V2, version: RULESET_VERSION_V2, digest: RULE_PACK_DIGEST_V2, rules: new Map(authorityRules.map((rule) => [rule.ruleId, rule])) });\n}\nexport function createAdmittedSemanticView(resolved: ReadonlyMap<string, ResolvedNodeSemanticsV2>): SemanticCatalogueViewV2 {\n return Object.freeze({ id: BUILTIN_SEMANTIC_CATALOGUE_V2.id, version: BUILTIN_SEMANTIC_CATALOGUE_V2.version, digest: BUILTIN_SEMANTIC_CATALOGUE_V2.digest, resolvedNodeSemantics: new Map(resolved) });\n}\nexport function authorityIsIntact(): boolean {\n try {\n const { digest, ...manifestBody } = BETA_DEFAULT_PROFILE_MANIFEST;\n const { digest: semanticDigest, ...semanticBody } = BUILTIN_SEMANTIC_CATALOGUE_V2;\n const rulePackDigest = bytesToHex(sha256(new TextEncoder().encode(encodeIdentityTuple(['secureflow-rule-pack-v2', RULESET_VERSION_V2, SAFE_FACT_AUTHORITY_DIGEST_V2, canonicalizeJson(authorityRuleBody)]))));\n return computeProfileManifestDigest(manifestBody) === PROFILE_MANIFEST_DIGEST_V2\n && authorityRules.length === RULE_KEYS.length\n && authorityRules.every((rule, index) => rule.ruleId === RULE_KEYS[index] && rule.packDigest === RULE_PACK_DIGEST_V2)\n && rulePackDigest === RULE_PACK_DIGEST_V2\n && createSemanticCatalogueDigest(semanticBody) === semanticDigest\n && semanticDigest === SEMANTIC_CATALOGUE_DIGEST_V2;\n } catch { return false; }\n}\n", "export const BUDGET_KEYS_V2 = Object.freeze([\n 'maxBytes',\n 'maxNodes',\n 'maxEdges',\n 'maxConnectionDepth',\n 'maxParameterDepth',\n 'maxParameterLeaves',\n 'workerDeadlineMs',\n 'maxSyntaxNodes',\n 'maxDocumentDepth',\n 'maxMembersAndElements',\n 'maxRawEdges',\n 'maxDuplicateKeys',\n 'maxDiagnostics',\n 'maxStoredSourceSpans',\n 'maxSourceWork',\n 'maxExpressionTokens',\n 'maxCodeSyntaxNodes',\n 'maxGraphOperations',\n 'maxTaintStates',\n 'maxTraceStepsPerFinding',\n 'maxFindings',\n 'maxRedactionPatches',\n 'maxRedactedArtifactBytes',\n 'maxEvidenceBytes',\n 'maxSerializedResultBytes',\n 'maxRuleOperations',\n] as const);\n\nexport type BudgetKeyV2 = (typeof BUDGET_KEYS_V2)[number];\nexport type BudgetAggregateEffectV2 = 'DEGRADED' | 'INDETERMINATE';\n\nexport type BudgetOutcomeV2 = Readonly<\n | { kind: 'ITEM_ERROR'; code: 'WORKFLOW_TOO_LARGE' | 'WORKFLOW_TOO_COMPLEX' }\n | {\n kind: 'DIAGNOSTIC';\n code: 'OPTIONAL_LIMIT_EXCEEDED' | 'REQUIRED_LIMIT_EXCEEDED' | 'GRAPH_WORK_LIMIT_EXCEEDED';\n aggregateEffect: BudgetAggregateEffectV2;\n assessmentEligible: boolean;\n reservedDiagnosticSlots?: 1;\n }\n | { kind: 'REDACTION_ERROR'; code: 'REDACTION_LIMIT_EXCEEDED' }\n | { kind: 'HOST_ERROR'; code: 'SCAN_TIMEOUT' }\n>;\n\nexport type BudgetOutcomeContextV2 = Readonly<{\n budget: BudgetKeyV2;\n capabilityRequired?: boolean;\n securityRequired?: boolean;\n}>;\n\nconst KNOWN_BUDGETS = new Set<string>(BUDGET_KEYS_V2);\n\nconst SHAPE_BUDGETS = new Set<BudgetKeyV2>([\n 'maxSyntaxNodes', 'maxDocumentDepth', 'maxMembersAndElements', 'maxNodes',\n 'maxRawEdges', 'maxEdges', 'maxConnectionDepth', 'maxParameterDepth',\n 'maxParameterLeaves', 'maxDuplicateKeys', 'maxSerializedResultBytes', 'maxSourceWork',\n]);\n\nconst CAPABILITY_BUDGETS = new Set<BudgetKeyV2>([\n 'maxExpressionTokens', 'maxCodeSyntaxNodes', 'maxTaintStates',\n 'maxTraceStepsPerFinding', 'maxFindings', 'maxEvidenceBytes', 'maxRuleOperations',\n]);\n\nexport function classifyBudgetOutcome(context: BudgetOutcomeContextV2): BudgetOutcomeV2 {\n const { budget } = context;\n if (!KNOWN_BUDGETS.has(budget)) throw new TypeError('Unknown scanner budget');\n if (budget === 'maxBytes') return frozen({ kind: 'ITEM_ERROR', code: 'WORKFLOW_TOO_LARGE' });\n if (SHAPE_BUDGETS.has(budget)) return frozen({ kind: 'ITEM_ERROR', code: 'WORKFLOW_TOO_COMPLEX' });\n if (budget === 'maxDiagnostics') return frozen({\n kind: 'DIAGNOSTIC', code: 'REQUIRED_LIMIT_EXCEEDED', aggregateEffect: 'INDETERMINATE',\n assessmentEligible: false, reservedDiagnosticSlots: 1,\n });\n if (budget === 'maxStoredSourceSpans') {\n return context.securityRequired ? requiredLimit() : optionalLimit();\n }\n if (CAPABILITY_BUDGETS.has(budget)) return byCapability(context.capabilityRequired);\n if (budget === 'maxGraphOperations') {\n const required = requireCapabilityRequired(context.capabilityRequired);\n return frozen({\n kind: 'DIAGNOSTIC', code: 'GRAPH_WORK_LIMIT_EXCEEDED',\n aggregateEffect: required ? 'INDETERMINATE' : 'DEGRADED', assessmentEligible: !required,\n });\n }\n if (budget === 'maxRedactionPatches' || budget === 'maxRedactedArtifactBytes') {\n return frozen({ kind: 'REDACTION_ERROR', code: 'REDACTION_LIMIT_EXCEEDED' });\n }\n return frozen({ kind: 'HOST_ERROR', code: 'SCAN_TIMEOUT' });\n}\n\nexport function diagnosticCapacity(maxDiagnostics: number): number {\n if (!Number.isSafeInteger(maxDiagnostics) || maxDiagnostics < 1) {\n throw new TypeError('maxDiagnostics must reserve at least one diagnostic slot');\n }\n return maxDiagnostics - 1;\n}\n\nfunction byCapability(requiredness: boolean | undefined): BudgetOutcomeV2 {\n return requireCapabilityRequired(requiredness) ? requiredLimit() : optionalLimit();\n}\n\nfunction requireCapabilityRequired(value: boolean | undefined): boolean {\n if (typeof value !== 'boolean') throw new TypeError('capabilityRequired must be fixed before execution');\n return value;\n}\n\nfunction requiredLimit(): BudgetOutcomeV2 {\n return frozen({\n kind: 'DIAGNOSTIC', code: 'REQUIRED_LIMIT_EXCEEDED',\n aggregateEffect: 'INDETERMINATE', assessmentEligible: false,\n });\n}\n\nfunction optionalLimit(): BudgetOutcomeV2 {\n return frozen({\n kind: 'DIAGNOSTIC', code: 'OPTIONAL_LIMIT_EXCEEDED',\n aggregateEffect: 'DEGRADED', assessmentEligible: true,\n });\n}\n\nfunction frozen<const T extends object>(value: T): Readonly<T> {\n return Object.freeze(value);\n}\n", "import type { ProfileManifestV2 } from '../capabilities/profile-manifest';\nimport { SAFE_FACT_EVIDENCE_MAPPINGS_V2 } from '../facts/safe-fact-registry';\n\n/**\n * Whether an omitted stored span is presentation-only or security-required.\n *\n * Identity never depends on a span. `astNodeId` is a structural digest of occurrence path, slot,\n * kind, and a payload that recurses through child ids or the token lexeme; node and edge digests\n * read those ids (`createNodeIdentityDigest`, `createEdgeIdentityDigest`), and fact, finding and\n * trace ids canonicalise the resulting subject. The evidence registry's span policies are `NONE` or\n * `OPTIONAL_HALF_OPEN`, so no fact kind demands a span either \u2014 a fact with a location-less subject\n * is still classified exactly the same way.\n *\n * Trace evidence is the exception, because a trace step states *where* the classification was\n * observed: a step's subject is resolved through the taint subject validator, which refuses a source\n * member without a stored span, and `materializeTraceV2` answers an unresolvable step with an UNKNOWN\n * trace rather than a partial one. A span budget that drops those spans therefore does not leave a\n * location-less record behind; it removes the classification the trace was carrying, which is the\n * result contract's \"identity/security classification depends on an omitted span\" case.\n */\nconst TRACE_EVIDENCE_SCHEMA_IDS: readonly string[] = Object.freeze(['v1.taint', 'v1.agent-control']);\n\nexport function spanLossIsSecurityRequired(manifest: ProfileManifestV2): boolean {\n return manifest.capabilities.some((capability) => capability.ruleIds.some((ruleId) => {\n const mapping = SAFE_FACT_EVIDENCE_MAPPINGS_V2.find((entry) => entry.ruleId === ruleId);\n return mapping !== undefined && TRACE_EVIDENCE_SCHEMA_IDS.includes(mapping.evidenceSchemaId);\n }));\n}\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { DEFAULT_SCANNER_LIMITS_V2, MEASURED_LIMIT_IDS, type ScannerLimitsV2 } from '@hub/contracts';\nimport { canonicalJsonBytes } from '../canonical-json';\nimport { parseSourceDocument } from '../source/source-parser';\nimport { resolveScannerLimits } from '../source/scanner-limit-resolution';\nimport type { ReadonlySourceDocumentV2, SourceSpanUsageV2 } from '../source/source-types';\nimport { normalizeSecurityWorkflow } from '../workflow-v2/normalize-security-workflow';\nimport type { SecurityWorkflowResult, SecurityWorkflowV2 } from '../workflow-v2/security-workflow';\nimport { validateTargetContextV2, type TargetContextV2 } from '../semantics/target-context';\nimport { BUILTIN_SEMANTIC_CATALOGUE_V2 } from '../semantics/builtin-catalogue';\nimport { resolveNodeSemanticsForScan } from '../semantics/generic-fallback';\nimport { SemanticCatalogueAdmissionError } from '../semantics/catalogue-admission';\nimport type { ResolvedNodeSemanticsV2 } from '../semantics/catalogue-schema';\nimport { createDiagnostic } from '../capabilities/adapter-evidence';\nimport { EMPTY_ADVISORY_CATALOGUE_V2, resolveAnalyzerSemanticContext, type SemanticContextV2 } from '../capabilities/semantic-context';\nimport { toNativeWorkflow } from '../capabilities/adapter-workflow';\nimport { scanCapabilitiesV2 } from '../capabilities/beta-default';\nimport type { AdmittedRuleV2, AnalyzerContextV2, CapabilityCandidateV2, CapabilityExecutionV2, SemanticCatalogueViewV2 } from '../capabilities/scheduler';\nimport type { SafeFactV2 } from '../capabilities/scheduler';\nimport { composeScannerResultV2 } from '../result-v2/compose-result';\nimport { createFactId, createFindingId, createTraceId } from '../result-v2/identities';\nimport { resolveRuleAuthorityV2 } from '../rules-v2/rule-authority';\nimport { analyzeWorkflowInsights } from '../scan-insights';\nimport { scoreFindingsV2 } from '../result-v2/scoring';\nimport type { FindingV2, AnalysisDiagnosticV2 } from '../../../../contracts/scanner-v2-evidence';\nimport type { ScannerResultV2 } from '../../../../contracts/scanner-v2-result';\nimport {\n ADMITTED_ENGINE_ID, ADMITTED_ENGINE_VERSION, ADMITTED_PROFILE_ID, ADMITTED_PROFILE_VERSION,\n BUILTIN_RULESET_AUTHORITY_V2, BUILTIN_SEMANTICS_AUTHORITY_V2, ENGINE_BUILD_DIGEST_V2,\n authorityIsIntact, createAdmittedCapabilityRegistry, createAdmittedRuleView, createAdmittedSemanticView,\n PROFILE_MANIFEST_DIGEST_V2,\n} from './admitted-registry';\nimport { BETA_DEFAULT_PROFILE_MANIFEST } from '../capabilities/profile-manifest';\nimport { classifyBudgetOutcome } from '../workflow-v2/budget-outcomes';\nimport { spanLossIsSecurityRequired } from './span-loss-classification';\nexport type ScanWorkflowV2FailureCode = 'UTF8_DECODING_FAILED' | 'INVALID_JSON' | 'MALFORMED_WORKFLOW' | 'WORKFLOW_TOO_LARGE' | 'WORKFLOW_TOO_COMPLEX' | 'INVALID_CONFIG' | 'UNKNOWN_CONFIGURATION_KEY' | 'PROFILE_NOT_ADMITTED' | 'SEMANTIC_CATALOGUE_INVALID' | 'SEMANTIC_CATALOGUE_AMBIGUOUS' | 'RULE_PACK_INVALID' | 'RULE_PACK_UNTRUSTED' | 'TOOL_INVARIANT_FAILED' | 'SERIALIZATION_FAILED' | 'SCAN_TIMEOUT' | 'SCAN_CANCELLED';\nexport type ScanWorkflowV2Failure = Readonly<{ ok: false; code: ScanWorkflowV2FailureCode; message: string; cause?: string; errors?: readonly string[] }>;\nexport type ScanWorkflowV2Success = Readonly<{ ok: true; result: ScannerResultV2 }>;\nexport type ScanWorkflowV2Request = Readonly<{ bytes: Uint8Array; profile: Readonly<{ id: string; version: string }>; target?: unknown; limits?: unknown; approvedDomains?: readonly string[] }>;\nexport type ScanWorkflowV2Result = ScanWorkflowV2Success | ScanWorkflowV2Failure;\n\ntype Plain = Record<string, unknown>;\ntype PreparedRequest = { bytes: Uint8Array; target: TargetContextV2; limits: ScannerLimitsV2; approvedDomains: readonly string[] };\ntype NormalizedSuccess = Extract<SecurityWorkflowResult, { ok: true }>;\nconst REQUEST_KEYS = ['bytes', 'profile', 'target', 'limits', 'approvedDomains'] as const;\nconst PROFILE_KEYS = ['id', 'version'] as const;\nconst LIMIT_KEYS = Object.freeze(Object.getOwnPropertyNames(DEFAULT_SCANNER_LIMITS_V2));\n\nconst failure = (code: ScanWorkflowV2FailureCode, message: string, cause?: string): ScanWorkflowV2Failure => Object.freeze({ ok: false, code, message, ...(cause === undefined ? {} : { cause }) });\n\nfunction record(value: unknown, allowed: readonly string[], required: readonly string[] = []): Plain | undefined {\n try {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined;\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return undefined;\n if (Object.getOwnPropertySymbols(value).length > 0) return undefined;\n const names = Object.getOwnPropertyNames(value); const output = Object.create(null) as Plain;\n for (const name of names) { if (!allowed.includes(name)) return undefined; const descriptor = Object.getOwnPropertyDescriptor(value, name); if (!descriptor || !('value' in descriptor) || !descriptor.enumerable) return undefined; output[name] = descriptor.value; }\n if (required.some((name) => !names.includes(name))) return undefined;\n return output;\n } catch { return undefined; }\n}\nfunction bytesCopy(value: unknown): Uint8Array | undefined {\n try {\n if (!(value instanceof Uint8Array) || Object.getPrototypeOf(value) !== Uint8Array.prototype || Object.getOwnPropertySymbols(value).length > 0) return undefined;\n for (const name of Object.getOwnPropertyNames(value)) { const descriptor = Object.getOwnPropertyDescriptor(value, name); if (!descriptor || !('value' in descriptor)) return undefined; }\n return Uint8Array.prototype.slice.call(value) as Uint8Array;\n } catch { return undefined; }\n}\n/** A dense array of strings, or `undefined`: a sparse array or any non-string member is malformed. */\nfunction domainList(value: unknown): readonly string[] | undefined {\n try {\n if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype || Object.getOwnPropertySymbols(value).length !== 0) return undefined;\n const names = Object.getOwnPropertyNames(value); const length = value.length;\n if (!Number.isSafeInteger(length) || length < 0 || names.length !== length + 1 || !names.includes('length')) return undefined;\n const output: string[] = [];\n for (let index = 0; index < length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n if (!descriptor || !('value' in descriptor) || typeof descriptor.value !== 'string') return undefined;\n output.push(descriptor.value);\n }\n return output;\n } catch { return undefined; }\n}\nfunction prepared(input: unknown): PreparedRequest | ScanWorkflowV2Failure {\n const root = record(input, REQUEST_KEYS, ['bytes', 'profile']); if (!root) return failure('INVALID_CONFIG', 'Scanner request is not a closed data object.');\n const profile = record(root.profile, PROFILE_KEYS, ['id', 'version']);\n if (!profile || typeof profile.id !== 'string' || typeof profile.version !== 'string') return failure('INVALID_CONFIG', 'Scanner profile reference is malformed.');\n if (profile.id !== ADMITTED_PROFILE_ID || profile.version !== ADMITTED_PROFILE_VERSION) return failure('PROFILE_NOT_ADMITTED', 'Scanner profile is not admitted.');\n const bytes = bytesCopy(root.bytes); if (!bytes) return failure('INVALID_CONFIG', 'Scanner bytes must be a Uint8Array.');\n const partialLimits = root.limits === undefined ? undefined : record(root.limits, LIMIT_KEYS);\n if (root.limits !== undefined && !partialLimits) return failure('INVALID_CONFIG', 'Scanner limits are malformed.');\n const limits = resolveScannerLimits(partialLimits); if (!limits) return failure('INVALID_CONFIG', 'Scanner limits are invalid.');\n const approvedDomains = root.approvedDomains === undefined ? [] : domainList(root.approvedDomains);\n if (approvedDomains === undefined) return failure('INVALID_CONFIG', 'Scanner approved domains are malformed.');\n const rawTarget = root.target === undefined ? { edition: 'UNKNOWN', deployment: 'UNKNOWN', role: 'UNKNOWN', taskRunner: 'UNKNOWN', communityPackages: [], configuration: [] } : record(root.target, ['n8nVersion', 'edition', 'deployment', 'role', 'taskRunner', 'communityPackages', 'configuration', 'contextDigest']);\n if (!rawTarget) return failure('INVALID_CONFIG', 'Scanner target is malformed.');\n try { return { bytes, limits, approvedDomains, target: validateTargetContextV2(rawTarget, { allowedConfigurationKeys: BUILTIN_SEMANTIC_CATALOGUE_V2.configurationKeys }) }; }\n catch (error) { const reason = error instanceof Error ? error.message : ''; return failure(reason.includes('UNKNOWN_CONFIGURATION_KEY') ? 'UNKNOWN_CONFIGURATION_KEY' : 'INVALID_CONFIG', 'Scanner target is invalid.'); }\n}\nfunction semanticView(workflow: SecurityWorkflowV2): { view: SemanticCatalogueViewV2 } | ScanWorkflowV2Failure {\n const resolved = new Map<string, ResolvedNodeSemanticsV2>();\n try {\n for (const node of workflow.nodes) {\n const resolution = resolveNodeSemanticsForScan(BUILTIN_SEMANTIC_CATALOGUE_V2, node);\n if (resolution) resolved.set(node.ref.identityDigest, resolution.semantics);\n }\n return { view: createAdmittedSemanticView(resolved) };\n } catch (error) { return semanticCatalogueFailure(error); }\n}\nfunction semanticCatalogueFailure(error: unknown): ScanWorkflowV2Failure {\n const ambiguous = error instanceof SemanticCatalogueAdmissionError ? error.code === 'SEMANTIC_CATALOGUE_AMBIGUOUS' : error instanceof Error && error.message.includes('SEMANTIC_CATALOGUE_AMBIGUOUS');\n return failure(ambiguous ? 'SEMANTIC_CATALOGUE_AMBIGUOUS' : 'SEMANTIC_CATALOGUE_INVALID', 'Built-in semantic catalogue admission failed.');\n}\nfunction ambiguityDiagnostics(workflow: SecurityWorkflowV2): readonly AnalysisDiagnosticV2[] {\n return workflow.ambiguities.map((ambiguity) => createDiagnostic(ambiguity.kind === 'UNRESOLVED_EDGE' || ambiguity.kind === 'AMBIGUOUS_EDGE' ? 'MALFORMED_CONNECTION_INDEX' : ambiguity.kind === 'DUPLICATE_MEMBER' && ambiguity.securityImpact === 'METADATA_ONLY' ? 'DUPLICATE_METADATA_KEY' : ambiguity.kind === 'MALFORMED_SECURITY_VALUE' ? 'MALFORMED_NODE_PARAMETERS' : 'DUPLICATE_SECURITY_KEY', 'source-normalization', true, ambiguity.subject));\n}\nfunction addDiagnostics(schedule: { executions: readonly CapabilityExecutionV2[]; candidates: readonly CapabilityCandidateV2[]; diagnostics: readonly AnalysisDiagnosticV2[] }, diagnostics: readonly AnalysisDiagnosticV2[], semanticSha256?: string): typeof schedule {\n const candidates = semanticSha256 === undefined ? schedule.candidates : rekeyCandidates(schedule.candidates, semanticSha256);\n if (diagnostics.length === 0) return { ...schedule, candidates };\n const executions = schedule.executions.map((execution) => { const owned = diagnostics.filter((diagnostic) => diagnostic.capabilityId === execution.id).map(({ id }) => id); return owned.length === 0 ? execution : Object.freeze({ ...execution, diagnosticIds: Object.freeze([...execution.diagnosticIds, ...owned]) }); });\n return { executions: Object.freeze(executions), candidates, diagnostics: Object.freeze([...schedule.diagnostics, ...diagnostics.filter(({ id }) => !schedule.diagnostics.some((prior) => prior.id === id))]) };\n}\n/**\n * The stored-span budget is the one bound a successful run can truncate against, so its loss is\n * classified by the budget registry rather than assumed: a presentation-only loss degrades, while a\n * loss that removed the spans a security classification is stated through withholds the assessment.\n * The outcome classifies; the diagnostic registry supplies the effect the record must carry.\n */\nfunction spanLossDiagnostics(usage: SourceSpanUsageV2): Readonly<{ diagnostics: readonly AnalysisDiagnosticV2[] }> | ScanWorkflowV2Failure {\n if (usage.omitted === 0) return { diagnostics: [] };\n const outcome = classifyBudgetOutcome({ budget: 'maxStoredSourceSpans', securityRequired: spanLossIsSecurityRequired(BETA_DEFAULT_PROFILE_MANIFEST) });\n if (outcome.kind !== 'DIAGNOSTIC') return failure('TOOL_INVARIANT_FAILED', 'Stored-span exhaustion has no diagnostic outcome.');\n return { diagnostics: [createDiagnostic(outcome.code, 'source-normalization', true)] };\n}\nfunction limitUsage(limits: ScannerLimitsV2, source: ReadonlySourceDocumentV2, sourceWorkUnits: number, workflow: NormalizedSuccess, findings: number, diagnostics: number, spanUsage: SourceSpanUsageV2) {\n const examined: Readonly<Record<(typeof MEASURED_LIMIT_IDS)[number], number>> = {\n maxBytes: source.utf8Bytes,\n maxNodes: workflow.counters.nodesExamined,\n maxEdges: workflow.counters.edgesRetained,\n maxConnectionDepth: workflow.counters.connectionDepth,\n maxParameterDepth: workflow.counters.parameterDepth,\n maxParameterLeaves: workflow.counters.parameterLeaves,\n maxSyntaxNodes: source.syntaxNodeCount,\n maxRawEdges: workflow.counters.rawEdgesExamined,\n maxDuplicateKeys: source.duplicateCount,\n maxDiagnostics: diagnostics,\n maxStoredSourceSpans: spanUsage.examined,\n maxSourceWork: sourceWorkUnits,\n maxFindings: findings,\n };\n // Only budgets with a real counter appear. Emitting a row for a dormant, unwired or unmeasured\n // budget would state a maximum it never enforced and an `examined: 0` it never measured. The\n // stored-span row stays the one budget a successful run can truncate against, so it carries the\n // parser's own omitted/exhausted accounting.\n return [...MEASURED_LIMIT_IDS].sort().map((id) => Object.freeze({\n id,\n maximum: limits[id],\n examined: examined[id],\n omitted: id === 'maxStoredSourceSpans' ? spanUsage.omitted : 0,\n exhausted: id === 'maxStoredSourceSpans' && spanUsage.omitted > 0,\n }));\n}\nfunction rekeyCandidates(candidates: readonly CapabilityCandidateV2[], semanticSha256: string): readonly CapabilityCandidateV2[] {\n return candidates.map((candidate) => {\n const factIds = new Map<string, string>();\n const facts = candidate.facts.map((fact) => { const factId = createFactId(fact, { semanticSha256 }); factIds.set(fact.factId, factId); return Object.freeze({ ...fact, factId }); });\n const traceIds = new Map<string, string>();\n const traces = candidate.traces.map((trace) => {\n const steps = trace.steps.map((step) => Object.freeze({ ...step, factRefs: Object.freeze(step.factRefs.map((ref) => factIds.get(ref) ?? ref)) }));\n const traceId = createTraceId({ kind: trace.kind, steps }, { semanticSha256 });\n traceIds.set(trace.traceId, traceId);\n return Object.freeze({ ...trace, traceId, steps: Object.freeze(steps) });\n });\n const findings = candidate.findings.map((finding) => Object.freeze({\n ...finding,\n factRefs: Object.freeze(finding.factRefs.map((ref) => factIds.get(ref) ?? ref)),\n traceRefs: Object.freeze(finding.traceRefs.map((ref) => traceIds.get(ref) ?? ref)),\n }));\n return Object.freeze({ ...candidate, facts: Object.freeze(facts), traces: Object.freeze(traces), findings: Object.freeze(findings) });\n });\n}\nfunction rekeyFacts(facts: readonly SafeFactV2[], semanticSha256: string): readonly SafeFactV2[] {\n return facts.map((fact) => Object.freeze({ ...fact, factId: createFactId(fact, { semanticSha256 }) }));\n}\nfunction safeName(name: string | null): string | null { return name !== null && name.length <= 512 && !/[\\u0000-\\u001f\\u007f]|(?:https?|ftp):\\/\\/|(?:password|secret|token|api[ _-]*key)\\s*[:=]|(?:^|[/\\\\])\\.\\.(?:[/\\\\]|$)/i.test(name) ? name : null; }\nfunction finalFindings(candidates: readonly CapabilityCandidateV2[], rules: ReadonlyMap<string, AdmittedRuleV2>, semanticSha256: string): FindingV2[] {\n const output = new Map<string, FindingV2>();\n for (const candidate of candidates) for (const item of candidate.findings) {\n // A rule the admitted catalogue does not carry is refused here, never dropped: the candidate\n // boundary already rejects such a finding, so reaching this point is a scanner invariant\n // failure, and silently omitting it would publish a clean-looking result over hidden evidence.\n const resolution = resolveRuleAuthorityV2(rules, item.ruleId);\n if (!resolution.ok) throw new TypeError('Unadmitted rule at the finding boundary');\n const rule = resolution.rule;\n const body = { ruleId: item.ruleId, ruleRevision: rule.revision, effect: rule.effect, severity: rule.severity, confidence: rule.confidence, evidenceClass: item.evidenceClass, conclusion: item.conclusion, applicability: item.applicability, subject: item.subject, factRefs: [...item.factRefs], traceRefs: [...item.traceRefs], remediationId: rule.remediationId }; const finding = { ...body, findingId: createFindingId(body, { semanticSha256 }) }; output.set(finding.findingId, finding);\n }\n return [...output.values()];\n}\nexport function scanWorkflowV2(input: unknown): ScanWorkflowV2Result {\n try {\n const request = prepared(input); if ('ok' in request) return request;\n if (!authorityIsIntact() || BETA_DEFAULT_PROFILE_MANIFEST.digest !== PROFILE_MANIFEST_DIGEST_V2) return failure('TOOL_INVARIANT_FAILED', 'Scanner built-in authority is inconsistent.');\n const parsed = parseSourceDocument(request.bytes, request.limits); if (!parsed.ok) return failure(parsed.code, parsed.message, 'cause' in parsed ? parsed.cause : undefined);\n const normalizedResult = normalizeSecurityWorkflow(parsed.document, request.limits); if (!normalizedResult.ok) return failure(normalizedResult.code, normalizedResult.message, 'cause' in normalizedResult ? normalizedResult.cause : undefined);\n const normalized = { ...normalizedResult, semanticSha256: bytesToHex(sha256(canonicalJsonBytes({ workflow: normalizedResult.semanticSha256, target: request.target.contextDigest }))) };\n const semantics = semanticView(normalized.workflow); if ('ok' in semantics) return semantics;\n let semanticContext: SemanticContextV2;\n try {\n semanticContext = resolveAnalyzerSemanticContext({ source: parsed.document, workflow: normalized.workflow, target: request.target, catalogue: BUILTIN_SEMANTIC_CATALOGUE_V2, advisories: EMPTY_ADVISORY_CATALOGUE_V2, capabilityId: 'structural-policies', required: true });\n } catch (error) {\n if (error instanceof SemanticCatalogueAdmissionError) return semanticCatalogueFailure(error);\n throw error;\n }\n const context: AnalyzerContextV2 = Object.freeze({ source: parsed.document, workflow: normalized.workflow, target: request.target, limits: request.limits, semantics: semantics.view, rules: createAdmittedRuleView(), priorOutcomes: new Map() });\n const schedule = scanCapabilitiesV2(context, BETA_DEFAULT_PROFILE_MANIFEST, createAdmittedCapabilityRegistry(request.approvedDomains));\n const spanLoss = spanLossDiagnostics(parsed.sourceSpanUsage); if ('ok' in spanLoss) return spanLoss;\n const extra = [...spanLoss.diagnostics, ...ambiguityDiagnostics(normalized.workflow), ...semanticContext.diagnostics];\n const completed = addDiagnostics(schedule, extra, normalized.semanticSha256);\n const native = awaitableInsights(context);\n const findings = finalFindings(completed.candidates, context.rules.rules, normalized.semanticSha256);\n const assessment = scoreFindingsV2(findings, native.complexity);\n const limits = { schemaVersion: request.limits.schemaVersion, digest: bytesToHex(sha256(canonicalJsonBytes(request.limits))), usage: limitUsage(request.limits, parsed.document, parsed.sourceWorkUnits, normalized, findings.length, completed.diagnostics.length, parsed.sourceSpanUsage) };\n const composed = composeScannerResultV2({ engine: { id: ADMITTED_ENGINE_ID, version: ADMITTED_ENGINE_VERSION, buildDigest: ENGINE_BUILD_DIGEST_V2 }, input: { rawSha256: parsed.document.rawSha256, semanticSha256: normalized.semanticSha256, ambiguitySha256: normalized.ambiguitySha256, ambiguityCount: normalized.ambiguityCount, utf8Bytes: parsed.document.utf8Bytes }, profile: { id: ADMITTED_PROFILE_ID, version: ADMITTED_PROFILE_VERSION }, ruleset: { ...BUILTIN_RULESET_AUTHORITY_V2, rules: context.rules.rules }, semantics: BUILTIN_SEMANTICS_AUTHORITY_V2, target: request.target, limits, analysis: { executions: completed.executions, diagnostics: completed.diagnostics, candidates: completed.candidates }, facts: rekeyFacts(semanticContext.facts, normalized.semanticSha256), workflow: native.workflow, assessment, stats: { rejectedCandidates: 0, collapsedCandidates: 0, omittedFindings: completed.candidates.reduce((sum, candidate) => sum + candidate.omitted, 0) } });\n if (!composed.ok) return failure('TOOL_INVARIANT_FAILED', 'Scanner result composition failed.');\n if (composed.result.stats.serializedBytes > request.limits.maxSerializedResultBytes) return failure('WORKFLOW_TOO_COMPLEX', 'Scanner result exceeds the configured serialization limit.', 'SERIALIZED_RESULT_LIMIT');\n return { ok: true, result: composed.result };\n } catch { return failure('TOOL_INVARIANT_FAILED', 'Scanner encountered an internal invariant failure.'); }\n}\nfunction awaitableInsights(context: AnalyzerContextV2): { workflow: ScannerResultV2['workflow']; complexity: ScannerResultV2['workflow']['complexity'] } {\n const native = toNativeWorkflow(context); const insights = analyzeWorkflowInsights(native);\n const { connectionCount: _connectionCount, ...overview } = insights.workflow;\n return { workflow: { ...overview, name: safeName(insights.workflow.name), edgeCount: context.workflow.edges.length, resolvedEdgeCount: context.workflow.edges.filter((edge) => edge.resolution === 'RESOLVED').length }, complexity: insights.workflow.complexity };\n}\n", "import {\n ADMITTED_PROFILE_V2, BUILTIN_AUTHORITIES_V2, DEFAULT_SCAN_CONFIG_V2, SCAN_CONFIG_V2_FIELDS,\n SCAN_CONFIG_V2_MAX_CONCURRENCY, SCAN_CONFIG_V2_MAX_DOMAINS, SCAN_CONFIG_V2_MAX_PATTERNS, SCAN_CONFIG_V2_MAX_STRING,\n isAdmittedProfileSpecifierV2, isApprovedDomainV2,\n type ScanConfigV2,\n} from './contracts';\nimport { normalizeAdmittedPathV2 } from './path-admission';\n\nexport type ConfigLoadOptions = Readonly<{ configDirectory?: string; cli?: unknown }>;\nexport type ConfigLoadResult = Readonly<{ ok: true; config: ScanConfigV2 } | { ok: false; code: 'INVALID_CONFIG'; errors: readonly string[] }>;\ntype Plain = Record<string, unknown>;\nconst BUILTIN: Record<string, true> = { builtin: true };\nconst CLI_NAMES: Readonly<Record<string, string>> = Object.freeze({\n 'fail-on': 'failOn', 'require-complete': 'requireComplete', 'max-concurrency': 'concurrency',\n 'allow-unsigned-development-rules': 'allowUnsignedDevelopmentRules',\n 'no-color': 'noColor', config: 'configPath',\n});\nconst REPEATABLE_CLI: Record<string, true> = { inputs: true, include: true, exclude: true, approvedDomains: true };\n\nexport function loadExplicitConfig(input: unknown, options: ConfigLoadOptions = {}): ConfigLoadResult {\n const errors: string[] = [];\n const config = parseConfig(input, errors);\n const cli = readCli(options.cli, errors);\n if (typeof options.configDirectory !== 'undefined' && typeof options.configDirectory !== 'string') errors.push('config directory is invalid');\n if (!config || !cli) return failure(errors);\n const configPathCount = Number(Object.prototype.hasOwnProperty.call(config, 'configPath'))\n + Number(Object.prototype.hasOwnProperty.call(cli, 'configPath'))\n + Number(Object.prototype.hasOwnProperty.call(cli, '_configPath'));\n if (configPathCount > 1) errors.push('config path supplied more than once');\n const merged: Plain = Object.assign(Object.create(null), DEFAULT_SCAN_CONFIG_V2, config);\n for (const key of Object.keys(cli)) if (key !== 'configPath' && key !== '_configPath') merged[key] = cli[key];\n if (Object.prototype.hasOwnProperty.call(cli, 'configPath')) merged.configPath = cli.configPath;\n else if (Object.prototype.hasOwnProperty.call(cli, '_configPath')) merged.configPath = cli._configPath;\n const result = normalize(merged, config, cli, errors);\n return result ? Object.freeze({ ok: true as const, config: deepFreeze(result) }) : failure(errors);\n}\n\nexport function validateScanConfigV2(input: unknown): ConfigLoadResult { return loadExplicitConfig(input); }\n\nfunction parseConfig(input: unknown, errors: string[]): Plain | undefined {\n if (typeof input === 'string') {\n if (input.length > SCAN_CONFIG_V2_MAX_STRING * 16 || duplicateKeys(input)) { errors.push('configuration JSON is invalid'); return undefined; }\n try { input = JSON.parse(input) as unknown; } catch { errors.push('configuration JSON is invalid'); return undefined; }\n }\n const value = record(input);\n if (!value) { errors.push('configuration must be a closed object'); return undefined; }\n for (const key of Object.keys(value)) if (!(SCAN_CONFIG_V2_FIELDS as readonly string[]).includes(key)) errors.push(`unknown configuration key: ${safeErrorKey(key)}`);\n if (value.schemaVersion !== 'n8n-scan-config-v2') errors.push('unsupported schemaVersion');\n return Object.keys(value).every((key) => (SCAN_CONFIG_V2_FIELDS as readonly string[]).includes(key)) ? value : undefined;\n}\n\nfunction readCli(input: unknown, errors: string[]): Plain | undefined {\n if (input === undefined) return {};\n const value = record(input); if (!value) { errors.push('CLI configuration is invalid'); return undefined; }\n const out: Plain = Object.create(null);\n for (const [rawKey, rawValue] of Object.entries(value)) {\n if (rawKey === 'config') {\n if (Object.prototype.hasOwnProperty.call(out, '_configPath')) errors.push('config path supplied more than once');\n out._configPath = rawValue;\n continue;\n }\n const key = CLI_NAMES[rawKey] ?? rawKey;\n if (!(SCAN_CONFIG_V2_FIELDS as readonly string[]).includes(key)) { errors.push(`unknown CLI configuration key: ${safeErrorKey(rawKey)}`); continue; }\n out[key] = REPEATABLE_CLI[key] === true && typeof rawValue === 'string' ? [rawValue] : rawValue;\n }\n return out;\n}\nfunction normalize(value: Plain, config: Plain, cli: Plain, errors: string[]): ScanConfigV2 | undefined {\n const out: Plain = Object.assign(Object.create(null), { schemaVersion: 'n8n-scan-config-v2' });\n const format = value.format; if (format !== 'json' && format !== 'ndjson' && format !== 'sarif' && format !== 'table') errors.push('format is invalid'); else out.format = format;\n const profile = value.profile;\n if (!isAdmittedProfileSpecifierV2(profile)) errors.push('profile is not admitted'); else out.profile = ADMITTED_PROFILE_V2.id;\n if (value.failOn !== 'CRITICAL' && value.failOn !== 'HIGH' && value.failOn !== 'MEDIUM' && value.failOn !== 'LOW' && value.failOn !== 'INFO') errors.push('failOn is invalid'); else out.failOn = value.failOn;\n for (const key of ['requireComplete', 'allowUnsignedDevelopmentRules', 'noColor']) {\n if (typeof value[key] !== 'boolean') errors.push(`${key} is invalid`); else out[key] = value[key];\n }\n if (!Number.isSafeInteger(value.concurrency) || (value.concurrency as number) < 1 || (value.concurrency as number) > SCAN_CONFIG_V2_MAX_CONCURRENCY) errors.push('concurrency is outside the admitted range'); else out.concurrency = value.concurrency;\n for (const key of ['rules', 'catalogue'] as const) {\n const raw = value[key];\n if (typeof raw !== 'string' || BUILTIN[raw] !== true) errors.push(`${key} is not admitted in built-in-only v2`); else out[key] = 'builtin';\n }\n for (const key of ['limits', 'target', 'output', 'configPath'] as const) if (value[key] !== undefined || Object.prototype.hasOwnProperty.call(value, key)) {\n const raw = value[key]; if (typeof raw !== 'string') errors.push(`${key} is invalid`); else { const path = localPath(raw, false, errors, key === 'limits'); if (path) out[key] = path; }\n }\n for (const key of ['inputs', 'include', 'exclude'] as const) {\n const raw = value[key]; if (raw === undefined) { if (Object.prototype.hasOwnProperty.call(value, key)) errors.push(`${key} is invalid`); continue; }\n const items = arrayValues(raw);\n if (!items || items.length > SCAN_CONFIG_V2_MAX_PATTERNS) { errors.push(`${key} is outside the admitted limit`); continue; }\n const paths: string[] = [];\n for (const item of items) {\n if (typeof item !== 'string') errors.push(`${key} contains an invalid path`);\n else if (key === 'inputs') {\n const path = normalizeAdmittedPathV2(item);\n if (path === undefined) errors.push('inputs contains an invalid path'); else paths.push(path);\n } else {\n const path = localPath(item, true, errors);\n if (path) paths.push(path);\n }\n }\n out[key] = Object.freeze(paths);\n }\n const rawDomains = value.approvedDomains;\n const domainItems = arrayValues(rawDomains);\n if (!domainItems || domainItems.length > SCAN_CONFIG_V2_MAX_DOMAINS) errors.push('approvedDomains is outside the admitted limit');\n else {\n const domains: string[] = [];\n for (const item of domainItems) {\n if (!isApprovedDomainV2(item)) errors.push('approvedDomains contains an invalid domain');\n else domains.push(item.toLowerCase());\n }\n out.approvedDomains = Object.freeze([...new Set(domains)].sort());\n }\n if (!Object.prototype.hasOwnProperty.call(config, 'include') && !Object.prototype.hasOwnProperty.call(cli, 'include')) out.include = DEFAULT_SCAN_CONFIG_V2.include;\n if (!Object.prototype.hasOwnProperty.call(config, 'exclude') && !Object.prototype.hasOwnProperty.call(cli, 'exclude')) out.exclude = DEFAULT_SCAN_CONFIG_V2.exclude;\n return errors.length === 0 ? out as ScanConfigV2 : undefined;\n}\n\nfunction localPath(raw: string, pattern: boolean, errors: string[], allowBuiltin = false): string | undefined {\n if (raw.length === 0 || raw.length > SCAN_CONFIG_V2_MAX_STRING || /[\\u0000-\\u001f\\u007f]/.test(raw)) { errors.push('path is invalid'); return undefined; }\n if (BUILTIN[raw] === true) { if (allowBuiltin) return 'builtin'; errors.push('built-in marker is not valid for this path'); return undefined; }\n const normalized = raw.replaceAll('\\\\', '/');\n if (/^(?:[a-z][a-z\\d+.-]*:|\\/|[a-z]:)/i.test(normalized)) { errors.push('absolute or remote path is not admitted'); return undefined; }\n const parts: string[] = [];\n for (const part of normalized.split('/')) {\n if (!part || part === '.') continue;\n if (part === '..') { if (pattern || parts.length === 0) { errors.push('path escapes its config directory'); return undefined; } parts.pop(); continue; }\n parts.push(part);\n }\n if (parts.length === 0) { errors.push('path is invalid'); return undefined; }\n return parts.join('/');\n}\nfunction arrayValues(value: unknown): readonly unknown[] | undefined {\n try {\n if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype || Object.getOwnPropertySymbols(value).length > 0) return undefined;\n const names = Object.getOwnPropertyNames(value);\n if (names.length !== value.length + 1) return undefined;\n const output: unknown[] = [];\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n if (!descriptor || !('value' in descriptor)) return undefined;\n output.push(descriptor.value);\n }\n return output;\n } catch { return undefined; }\n}\nfunction safeErrorKey(value: string): string {\n return /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(value) ? value : 'field';\n}\n\nexport {\n ADMITTED_PROFILE_V2,\n BUILTIN_AUTHORITIES_V2,\n BUILTIN_LIMITS_AUTHORITY_V2,\n BUILTIN_RULESET_AUTHORITY_V2,\n BUILTIN_SEMANTICS_AUTHORITY_V2,\n CLI_TOOL_V2,\n DEFAULT_SCAN_CONFIG_V2,\n PROFILE_MANIFEST_DIGEST_V2,\n RULE_PACK_DIGEST_V2,\n SCAN_CONFIG_SCHEMA_V2,\n SEMANTIC_CATALOGUE_DIGEST_V2,\n type ScanConfigV2,\n} from './contracts';\n\nfunction record(value: unknown): Plain | undefined {\n try {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined;\n const proto = Object.getPrototypeOf(value); if (proto !== Object.prototype && proto !== null) return undefined;\n if (Object.getOwnPropertySymbols(value).length > 0) return undefined;\n const out: Plain = Object.create(null);\n for (const key of Object.getOwnPropertyNames(value)) { const descriptor = Object.getOwnPropertyDescriptor(value, key); if (!descriptor || !('value' in descriptor) || !descriptor.enumerable) return undefined; out[key] = descriptor.value; }\n return out;\n } catch { return undefined; }\n}\n\nfunction duplicateKeys(text: string): boolean {\n let index = 0;\n const skip = () => { while (/\\s/.test(text[index] ?? '')) index += 1; };\n const string = () => { index += 1; while (index < text.length) { const char = text[index++]; if (char === '\\\\') index += 1; else if (char === '\"') return; } throw new Error(); };\n const value = (): void => { skip(); const char = text[index]; if (char === '{') return object(); if (char === '[') return array(); if (char === '\"') { string(); return; } const start = index; while (index < text.length && !/[\\s,\\]}]/.test(text[index]!)) index += 1; if (start === index) throw new Error(); };\n const object = (): void => { index += 1; const keys = new Set<string>(); skip(); if (text[index] === '}') { index += 1; return; } while (index < text.length) { skip(); if (text[index] !== '\"') throw new Error(); const start = index; string(); const key = text.slice(start, index); if (keys.has(key)) throw new Error(); keys.add(key); skip(); if (text[index++] !== ':') throw new Error(); value(); skip(); if (text[index] === '}') { index += 1; return; } if (text[index++] !== ',') throw new Error(); } throw new Error(); };\n const array = (): void => { index += 1; skip(); if (text[index] === ']') { index += 1; return; } while (index < text.length) { value(); skip(); if (text[index] === ']') { index += 1; return; } if (text[index++] !== ',') throw new Error(); } throw new Error(); };\n try { value(); skip(); if (index !== text.length) throw new Error(); return false; } catch { return true; }\n}\nfunction failure(errors: readonly string[]): ConfigLoadResult {\n return Object.freeze({ ok: false, code: 'INVALID_CONFIG' as const, errors: Object.freeze([...new Set(errors)].sort()) });\n}\nfunction deepFreeze<T>(value: T, seen = new WeakSet<object>()): T { if (value && typeof value === 'object') { if (seen.has(value)) return value; seen.add(value); for (const key of Object.getOwnPropertyNames(value)) deepFreeze((value as Plain)[key], seen); Object.freeze(value); } return value; }\n\n", "import { compareCanonicalStrings } from '@hub/contracts/stable-order';\nimport type { CliMetadataDocumentV2 } from './commands.js';\nimport {\n explainDocumentV2,\n profilesDocumentV2,\n rulesDocumentV2,\n validateConfigDocumentV2,\n versionDocumentV2,\n} from './commands.js';\n\nconst KEYS: Record<string, readonly string[]> = {\n 'n8n-scan-rules-v2': ['schemaVersion', 'tool', 'artifacts', 'rules'],\n 'n8n-scan-explain-v2': ['schemaVersion', 'tool', 'artifacts', 'rule', 'prose', 'evidenceProperties', 'provenance'],\n 'n8n-scan-profiles-v2': ['schemaVersion', 'tool', 'profiles'],\n 'n8n-scan-version-v2': ['schemaVersion', 'name', 'cliVersion', 'engine', 'resultSchemas', 'configSchema', 'rulesetDigest', 'semanticsDigest', 'trustStoreDigest', 'mode'],\n 'n8n-scan-config-validation-v2': ['schemaVersion', 'valid', 'artifacts'],\n tool: ['name', 'version', 'buildDigest'], artifacts: ['profile', 'ruleset', 'semantics', 'target', 'limits'],\n profileId: ['id', 'version'], ruleset: ['id', 'version', 'digest', 'signatureStatus'], semantics: ['id', 'version', 'digest'],\n target: ['edition', 'deployment', 'role', 'taskRunner', 'communityPackages', 'configuration', 'contextDigest'],\n limits: ['schemaVersion', 'digest'], rule: ['ruleId', 'revision', 'effect', 'severity', 'confidence', 'capabilityId', 'evidenceSchemaId', 'remediationId', 'cweIds', 'owaspAgenticIds'],\n prose: ['title', 'message', 'explanation', 'whyItMatters', 'possibleImpact', 'remediation', 'remediationSteps'],\n provenance: ['packDigest', 'semanticsDigest'], profile: ['id', 'version', 'admitted', 'advertised', 'digest', 'scoringPolicyVersion', 'capabilities'],\n capability: ['id', 'version', 'required', 'dependsOn', 'ruleIds'], engine: ['id', 'version', 'buildDigest'],\n};\nconst DIGEST = /^[0-9a-f]{64}$/;\nconst fail = (): never => { throw new TypeError('Invalid metadata document'); };\n\nexport function checkPlain(o: unknown): Record<string, unknown> {\n if (!o || typeof o !== 'object' || Array.isArray(o)) return fail();\n if (Object.getPrototypeOf(o) !== Object.prototype && Object.getPrototypeOf(o) !== null) return fail();\n if (Object.getOwnPropertySymbols(o).length > 0) return fail();\n for (const key of Object.getOwnPropertyNames(o)) {\n const descriptor = Object.getOwnPropertyDescriptor(o, key);\n if (!descriptor || !('value' in descriptor) || !descriptor.enumerable) return fail();\n }\n return o as Record<string, unknown>;\n}\n\nexport function checkDenseArray<T>(arr: unknown): T[] {\n if (!Array.isArray(arr) || Object.getPrototypeOf(arr) !== Array.prototype || Object.getOwnPropertySymbols(arr).length > 0) return fail();\n const names = Object.getOwnPropertyNames(arr);\n if (names.length !== arr.length + 1) return fail();\n for (const name of names) {\n if (name === 'length') continue;\n if (!/^(?:0|[1-9]\\d*)$/.test(name) || Number(name) >= arr.length) return fail();\n const descriptor = Object.getOwnPropertyDescriptor(arr, name);\n if (!descriptor || !('value' in descriptor) || !descriptor.enumerable) return fail();\n }\n const length = Object.getOwnPropertyDescriptor(arr, 'length');\n if (!length || !('value' in length) || !Number.isSafeInteger(length.value)) return fail();\n return arr as T[];\n}\n\nfunction safeString(value: unknown): void {\n if (typeof value !== 'string' || value.length === 0 || value.length > 4096 || /[\\u0000-\\u001f\\u007f\\ud800-\\udfff]/.test(value)\n || /^[a-z][a-z0-9+.-]*:\\/\\//i.test(value) || /^[A-Za-z]:[\\\\/]|^\\/|^\\\\\\\\/.test(value)\n || /(?:^|[\\\\/])\\.\\.(?:[\\\\/]|$)/.test(value)) return fail();\n}\n\nfunction walk(value: unknown, seen = new WeakSet<object>()): void {\n if (value === null) return;\n if (typeof value === 'string') return safeString(value);\n if (typeof value === 'boolean') return;\n if (typeof value === 'number') { if (!Number.isFinite(value)) fail(); return; }\n if (typeof value !== 'object') return fail();\n if (seen.has(value)) return fail();\n seen.add(value);\n if (Array.isArray(value)) for (const item of checkDenseArray<unknown>(value)) walk(item, seen);\n else for (const item of Object.values(checkPlain(value))) walk(item, seen);\n seen.delete(value);\n}\n\nfunction checkKeys(value: unknown, expected: readonly string[]): Record<string, unknown> {\n const object = checkPlain(value); const actual = Object.keys(object);\n if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) return fail();\n return object;\n}\nfunction digest(value: unknown): void { if (typeof value !== 'string' || !DIGEST.test(value)) fail(); }\nfunction sortedStrings(value: unknown): void {\n const values = checkDenseArray<unknown>(value);\n if (values.some((item) => typeof item !== 'string')) return fail();\n for (let i = 1; i < values.length; i += 1) if (compareCanonicalStrings(values[i - 1] as string, values[i] as string) >= 0) return fail();\n}\nfunction artifacts(value: unknown): void {\n const object = checkKeys(value, KEYS.artifacts!);\n checkKeys(object.profile, KEYS.profileId!);\n const ruleset = checkKeys(object.ruleset, KEYS.ruleset!);\n digest(ruleset.digest); if (ruleset.signatureStatus !== 'VERIFIED' && ruleset.signatureStatus !== 'UNVERIFIED') return fail();\n checkKeys(object.semantics, KEYS.semantics!);\n const target = checkKeys(object.target, KEYS.target!);\n checkDenseArray(target.communityPackages); checkDenseArray(target.configuration); digest(target.contextDigest);\n const limits = checkKeys(object.limits, KEYS.limits!); if (limits.schemaVersion !== 'scanner-limits-v2') return fail(); digest(limits.digest);\n}\nfunction exact(left: unknown, right: unknown): boolean {\n if (left === right) return true;\n if (typeof left !== typeof right || left === null || right === null) return false;\n if (Array.isArray(left) || Array.isArray(right)) {\n if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;\n return left.every((item, index) => exact(item, right[index]));\n }\n if (typeof left !== 'object' || typeof right !== 'object') return Object.is(left, right);\n const a = Object.keys(left as object); const b = Object.keys(right as object);\n return a.length === b.length && a.every((key, index) => key === b[index] && exact((left as Record<string, unknown>)[key], (right as Record<string, unknown>)[key]));\n}\n\nfunction authority(schema: string, root: Record<string, unknown>): CliMetadataDocumentV2 {\n if (schema === 'n8n-scan-rules-v2') return rulesDocumentV2();\n if (schema === 'n8n-scan-explain-v2') {\n const result = explainDocumentV2(String((root.rule as Record<string, unknown>).ruleId));\n if (!result.ok) return fail();\n return result.document;\n }\n if (schema === 'n8n-scan-profiles-v2') return profilesDocumentV2();\n if (schema === 'n8n-scan-version-v2') return versionDocumentV2();\n const result = validateConfigDocumentV2({ schemaVersion: 'n8n-scan-config-v2' });\n if (!result.ok) return fail();\n return result.document;\n}\n\nexport function validateDocumentShape(doc: unknown): asserts doc is CliMetadataDocumentV2 {\n walk(doc);\n const root = checkPlain(doc); const schema = root.schemaVersion;\n if (typeof schema !== 'string' || !Object.prototype.hasOwnProperty.call(KEYS, schema)) return fail();\n checkKeys(root, KEYS[schema]!);\n if (schema === 'n8n-scan-rules-v2') {\n checkKeys(root.tool, KEYS.tool!); artifacts(root.artifacts);\n const rules = checkDenseArray(root.rules); for (const rule of rules) { const item = checkKeys(rule, KEYS.rule!); sortedStrings(item.cweIds); sortedStrings(item.owaspAgenticIds); }\n } else if (schema === 'n8n-scan-explain-v2') {\n checkKeys(root.tool, KEYS.tool!); artifacts(root.artifacts); checkKeys(root.rule, KEYS.rule!); const prose = checkKeys(root.prose, KEYS.prose!); checkDenseArray(prose.remediationSteps); checkDenseArray(root.evidenceProperties); checkKeys(root.provenance, KEYS.provenance!);\n } else if (schema === 'n8n-scan-profiles-v2') {\n checkKeys(root.tool, KEYS.tool!); const profiles = checkDenseArray(root.profiles);\n for (const profile of profiles) { const item = checkKeys(profile, KEYS.profile!); for (const capability of checkDenseArray(item.capabilities)) { const value = checkKeys(capability, KEYS.capability!); checkDenseArray(value.dependsOn); checkDenseArray(value.ruleIds); } }\n } else if (schema === 'n8n-scan-version-v2') {\n checkKeys(root.engine, KEYS.engine!); checkDenseArray(root.resultSchemas); digest(root.rulesetDigest); digest(root.semanticsDigest); digest(root.trustStoreDigest);\n } else {\n if (root.valid !== true) return fail(); artifacts(root.artifacts);\n }\n if (!exact(root, authority(schema, root))) return fail();\n}\n", "import { ADMITTED_LIMIT_STATES, DEFAULT_SCANNER_LIMITS_V2, MEASURED_LIMIT_IDS } from '@hub/contracts';\n\nexport const V2_COMMANDS = Object.freeze([\n 'scan', 'rules', 'explain', 'profiles', 'validate-config', 'version',\n] as const);\nexport type V2CommandName = (typeof V2_COMMANDS)[number];\n\nexport type V2OptionName =\n | '--help' | '--schema' | '--format' | '--profile' | '--fail-on' | '--require-complete'\n | '--max-concurrency' | '--concurrency' | '--timeout' | '--output' | '--config'\n | '--rules' | '--catalogue' | '--limits' | '--target' | '--n8n-version' | '--edition'\n | '--deployment' | '--role' | '--task-runner' | '--community-package' | '--configuration'\n | '--approved-domain' | '--include' | '--exclude' | '--allow-unsigned-development-rules' | '--no-color';\n\nexport type V2HelpOption = Readonly<{\n name: V2OptionName;\n value: string;\n commands: readonly V2CommandName[];\n description: string;\n default?: string;\n}>;\n\nconst SCAN = Object.freeze(['scan'] as const);\nconst ALL = V2_COMMANDS;\n\nexport const V2_OPTIONS: readonly V2HelpOption[] = Object.freeze([\n { name: '--help', value: '', commands: ALL, description: 'Show deterministic help for the selected v2 command.' },\n { name: '--schema', value: '<v2>', commands: ALL, description: 'Select the versioned v2 grammar.' },\n { name: '--format', value: '<json|ndjson|sarif|table>', commands: ALL, description: 'Select the output format.', default: 'json for scan; json for metadata' },\n { name: '--profile', value: '<beta-default>', commands: SCAN, description: 'Select the admitted analysis profile.', default: 'beta-default' },\n { name: '--fail-on', value: '<CRITICAL|HIGH|MEDIUM|LOW|INFO>', commands: SCAN, description: 'Fail when a finding meets or exceeds this severity.', default: 'INFO' },\n { name: '--require-complete', value: '', commands: SCAN, description: 'Treat DEGRADED analysis as a failure.', default: 'false' },\n { name: '--max-concurrency', value: '<1..16>', commands: SCAN, description: 'Bound concurrent inputs; --concurrency is an equivalent spelling.', default: '1' },\n { name: '--concurrency', value: '<1..16>', commands: SCAN, description: 'Bound concurrent inputs; --max-concurrency is an equivalent spelling.', default: '1' },\n { name: '--timeout', value: '<1..2147483647>', commands: SCAN, description: 'Set the per-input timeout in milliseconds.', default: '30000 (workerDeadlineMs)' },\n { name: '--output', value: '<local-file|->', commands: SCAN, description: 'Write to a local file atomically, or use - for stdout.', default: 'stdout' },\n { name: '--config', value: '<local-file>', commands: SCAN, description: 'Load one explicit versioned config file.' },\n { name: '--rules', value: '<builtin>', commands: SCAN, description: 'Select the embedded built-in ruleset; the only admitted authority.', default: 'builtin' },\n { name: '--catalogue', value: '<builtin>', commands: SCAN, description: 'Select the embedded semantic catalogue.', default: 'builtin' },\n { name: '--limits', value: '<local-file|builtin>', commands: SCAN, description: 'Select embedded or local scanner limits.', default: 'builtin' },\n { name: '--target', value: '<local-file>', commands: SCAN, description: 'Load a local target context.' },\n { name: '--n8n-version', value: '<semver>', commands: SCAN, description: 'Set the n8n version fact.' },\n { name: '--edition', value: '<COMMUNITY|ENTERPRISE|CLOUD|UNKNOWN>', commands: SCAN, description: 'Set the deployment edition fact.', default: 'UNKNOWN' },\n { name: '--deployment', value: '<SELF_HOSTED|CLOUD|UNKNOWN>', commands: SCAN, description: 'Set the deployment fact.', default: 'UNKNOWN' },\n { name: '--role', value: '<OWNER|ADMIN|MEMBER|UNKNOWN>', commands: SCAN, description: 'Set the operator role fact.', default: 'UNKNOWN' },\n { name: '--task-runner', value: '<LEGACY|NATIVE|UNKNOWN>', commands: SCAN, description: 'Set the task-runner fact.', default: 'UNKNOWN' },\n { name: '--community-package', value: '<package>', commands: SCAN, description: 'Record a community package in target context; repeatable.' },\n { name: '--configuration', value: '<name>', commands: SCAN, description: 'Record a configuration fact; repeatable.' },\n { name: '--approved-domain', value: '<host>', commands: SCAN, description: 'Treat this hostname as approved for UNAPPROVED_DOMAIN; repeatable.' },\n { name: '--include', value: '<posix-glob>', commands: SCAN, description: 'Replace config includes with a case-sensitive POSIX glob; repeatable.', default: '**/*.json' },\n { name: '--exclude', value: '<posix-glob>', commands: SCAN, description: 'Replace config excludes with a case-sensitive POSIX glob; repeatable.', default: '.git/**, node_modules/**' },\n { name: '--allow-unsigned-development-rules', value: '', commands: SCAN, description: 'Refused: external rule packs are not admitted, so no pack can be selected.', default: 'false' },\n { name: '--no-color', value: '', commands: SCAN, description: 'Disable color in human output.', default: 'false (also disabled for non-TTY)' },\n]);\n\n/**\n * The published limit vocabulary, restated because a shipped declaration must not name the private,\n * unpublished contracts workspace: a strict NodeNext consumer of the packed package fails `TS2307`\n * on that import. The values below still come from the contract, and the two vocabularies stay\n * exhaustive against each other at compile time.\n */\nexport type V2LimitName =\n | 'maxBytes' | 'maxNodes' | 'maxEdges' | 'maxConnectionDepth' | 'maxParameterDepth' | 'maxParameterLeaves'\n | 'workerDeadlineMs' | 'maxSyntaxNodes' | 'maxDocumentDepth' | 'maxMembersAndElements' | 'maxRawEdges'\n | 'maxDuplicateKeys' | 'maxDiagnostics' | 'maxStoredSourceSpans' | 'maxSourceWork' | 'maxExpressionTokens'\n | 'maxCodeSyntaxNodes' | 'maxGraphOperations' | 'maxTaintStates' | 'maxTraceStepsPerFinding' | 'maxFindings'\n | 'maxRedactionPatches' | 'maxRedactedArtifactBytes' | 'maxEvidenceBytes' | 'maxSerializedResultBytes'\n | 'maxRuleOperations';\n\nexport const V2_LIMITS: Readonly<Record<V2LimitName, number>> = Object.freeze({\n maxBytes: DEFAULT_SCANNER_LIMITS_V2.maxBytes,\n maxNodes: DEFAULT_SCANNER_LIMITS_V2.maxNodes,\n maxEdges: DEFAULT_SCANNER_LIMITS_V2.maxEdges,\n maxConnectionDepth: DEFAULT_SCANNER_LIMITS_V2.maxConnectionDepth,\n maxParameterDepth: DEFAULT_SCANNER_LIMITS_V2.maxParameterDepth,\n maxParameterLeaves: DEFAULT_SCANNER_LIMITS_V2.maxParameterLeaves,\n workerDeadlineMs: DEFAULT_SCANNER_LIMITS_V2.workerDeadlineMs,\n maxSyntaxNodes: DEFAULT_SCANNER_LIMITS_V2.maxSyntaxNodes,\n maxDocumentDepth: DEFAULT_SCANNER_LIMITS_V2.maxDocumentDepth,\n maxMembersAndElements: DEFAULT_SCANNER_LIMITS_V2.maxMembersAndElements,\n maxRawEdges: DEFAULT_SCANNER_LIMITS_V2.maxRawEdges,\n maxDuplicateKeys: DEFAULT_SCANNER_LIMITS_V2.maxDuplicateKeys,\n maxDiagnostics: DEFAULT_SCANNER_LIMITS_V2.maxDiagnostics,\n maxStoredSourceSpans: DEFAULT_SCANNER_LIMITS_V2.maxStoredSourceSpans,\n maxSourceWork: DEFAULT_SCANNER_LIMITS_V2.maxSourceWork,\n maxExpressionTokens: DEFAULT_SCANNER_LIMITS_V2.maxExpressionTokens,\n maxCodeSyntaxNodes: DEFAULT_SCANNER_LIMITS_V2.maxCodeSyntaxNodes,\n maxGraphOperations: DEFAULT_SCANNER_LIMITS_V2.maxGraphOperations,\n maxTaintStates: DEFAULT_SCANNER_LIMITS_V2.maxTaintStates,\n maxTraceStepsPerFinding: DEFAULT_SCANNER_LIMITS_V2.maxTraceStepsPerFinding,\n maxFindings: DEFAULT_SCANNER_LIMITS_V2.maxFindings,\n maxRedactionPatches: DEFAULT_SCANNER_LIMITS_V2.maxRedactionPatches,\n maxRedactedArtifactBytes: DEFAULT_SCANNER_LIMITS_V2.maxRedactedArtifactBytes,\n maxEvidenceBytes: DEFAULT_SCANNER_LIMITS_V2.maxEvidenceBytes,\n maxSerializedResultBytes: DEFAULT_SCANNER_LIMITS_V2.maxSerializedResultBytes,\n maxRuleOperations: DEFAULT_SCANNER_LIMITS_V2.maxRuleOperations,\n});\n\n/**\n * Type-only parity guard: every limit the contract gains must be published here. `Exclude` is\n * `never` while the two vocabularies agree, and the type-parameter default stops satisfying its\n * constraint the moment they diverge. Erased at emit, so it costs no runtime lookup and never\n * reaches `help.d.ts`; the reverse direction is enforced by indexing `ADMITTED_LIMIT_STATES`.\n */\ntype AssertEveryContractLimitIsPublished<Gap extends never = Exclude<keyof typeof ADMITTED_LIMIT_STATES, V2LimitName>> = Gap;\n\n/** The help marker for one budget, derived from the contract authority rather than a copy. */\nfunction limitStateMarker(name: V2LimitName): string {\n const state = ADMITTED_LIMIT_STATES[name];\n if (state === 'WIRED') {\n return MEASURED_LIMIT_IDS.some((id) => id === name) ? ' (enforced; usage row)' : ' (enforced; no usage row)';\n }\n return state === 'DORMANT' ? ' (dormant in beta-default; hardened-only)' : ' (development-only, unwired)';\n}\n\nexport const V2_EXIT_CODES = Object.freeze([0, 1, 2, 3, 4, 130] as const);\nexport type V2ExitCode = (typeof V2_EXIT_CODES)[number];\nexport const V2_EXIT_REASONS = Object.freeze([\n 'CANCELLED', 'INTERNAL', 'USAGE', 'FINDING_THRESHOLD', 'REQUIRE_COMPLETE', 'ITEM_FAILURE', 'UNDER_THRESHOLD',\n] as const);\nexport type V2ExitReason = (typeof V2_EXIT_REASONS)[number];\n\nexport const V2_CANONICAL_CLAIMS = Object.freeze([\n 'v2 is offline and never initiates network requests (HTTP, DNS, sockets, telemetry, or remote imports).',\n 'Labels and output identities never contain absolute paths or workflow source content.',\n 'File output uses a same-directory temporary file and atomic replace; failures and cancellation preserve the prior file.',\n 'beta-default@2.0.0 is admitted; beta-hardened@2.0.0 is defined but not admitted or selectable.',\n 'No shipped path produces a redacted artifact: maxRedactionPatches and maxRedactedArtifactBytes bound redaction-v2, which is development-only and unwired.',\n 'No shipped path admits an external rule pack: --rules and --catalogue accept only builtin, and --allow-unsigned-development-rules is refused because Ed25519 trust-store admission is deferred.',\n 'Published on npm as sfscanner.',\n] as const);\n\nexport type V2CommandHelp = Readonly<{ command: V2CommandName; usage: readonly string[]; text: string }>;\n\nfunction optionLine(option: V2HelpOption, command?: V2CommandName): string {\n const value = option.name === '--format' && command !== undefined && command !== 'scan' ? '<json|table>' : option.value;\n const syntax = value ? ` ${value}` : '';\n const defaultText = option.default ? ` Default: ${option.default}.` : '';\n return ` ${option.name}${syntax} ${option.description}${defaultText}`;\n}\nfunction renderCommand(command: V2CommandName): V2CommandHelp {\n const usage = command === 'scan'\n ? [`sfscanner --schema v2 scan <file|directory|-> [options]`]\n : command === 'explain'\n ? [`sfscanner --schema v2 explain <rule-id> [--format json|table]`]\n : command === 'validate-config'\n ? [`sfscanner --schema v2 validate-config <local-file> [--format json|table]`]\n : [`sfscanner --schema v2 ${command} [--format json|table]`];\n const options = V2_OPTIONS.filter((option) => option.commands.includes(command));\n const lines = [`sfscanner v2 ${command}`, '', 'Usage:', ...usage, '', 'Options:', ...options.map((option) => optionLine(option, command))];\n if (command === 'scan') lines.push('', 'Inputs are sorted by normalized relative label; stdin (-) cannot join a batch.');\n if (command === 'profiles') lines.push('', 'beta-default is admitted. beta-hardened is defined but not admitted or selectable.');\n if (command === 'validate-config') lines.push('', 'Only the explicitly supplied local config file is read.');\n return Object.freeze({ command, usage: Object.freeze(usage), text: `${lines.join('\\n')}\\n` });\n}\n\nexport const COMMAND_HELP_V2: Readonly<Record<V2CommandName, string>> = Object.freeze(\n Object.fromEntries(V2_COMMANDS.map((command) => [command, renderCommand(command).text])) as Record<V2CommandName, string>,\n);\n\nconst generalLines = [\n 'sfscanner \u2014 deterministic offline n8n workflow scanner (v2)', '', 'Usage:',\n ' sfscanner --schema v2 scan <file|directory|-> [options]',\n ' sfscanner --schema v2 rules [--format json|table]',\n ' sfscanner --schema v2 explain <rule-id> [--format json|table]',\n ' sfscanner --schema v2 profiles [--format json|table]',\n ' sfscanner --schema v2 validate-config <local-file> [--format json|table]',\n ' sfscanner --schema v2 version [--format json|table]', '', 'Commands:',\n 'Defaults:', ' format: json; profile: beta-default; fail-on: INFO; require-complete: false; concurrency: 1 (maximum 16); timeout: 30000ms.',\n ' include: **/*.json; exclude: .git/**, node_modules/**; rules/catalogue/limits: builtin.',\n ' target facts: edition UNKNOWN; deployment UNKNOWN; role UNKNOWN; task-runner UNKNOWN.',\n '', 'Profiles:', ' beta-default@2.0.0: admitted and selectable.',\n ' beta-hardened@2.0.0: defined but not admitted or selectable.', '', 'Limits:',\n ...Object.entries(V2_LIMITS).map(([name, value]) => ` ${name}=${value}${limitStateMarker(name as V2LimitName)}`), '',\n 'Exit codes and precedence:', ' 130 CANCELLED; 4 INTERNAL; 2 USAGE; 1 FINDING_THRESHOLD or REQUIRE_COMPLETE; 3 ITEM_FAILURE; 0 UNDER_THRESHOLD.',\n ' Pre-scan usage/configuration/admission failures emit no machine envelope and exit 2; stdout cancellation emits a valid envelope and exits 130.',\n ' When finding threshold and require-complete both fire, FINDING_THRESHOLD wins. Indeterminate never exits 0.', '',\n ...V2_CANONICAL_CLAIMS,\n];\nexport const GENERAL_HELP_V2 = `${generalLines.join('\\n')}\\n`;\nexport const HELP_TEXT_V2 = GENERAL_HELP_V2;\n\nexport function getHelpV2(command?: V2CommandName): string {\n return command === undefined ? GENERAL_HELP_V2 : COMMAND_HELP_V2[command];\n}\n", "import { readdir, stat, lstat, realpath } from 'node:fs/promises';\nimport { admittedLabelV2, isAdmittedLocalPath, isAdmittedRelativePath, normalizeAdmittedPathV2, toFsPathV2 } from './path-admission.js';\n\nexport type HostEntry = Readonly<{ name: string; isDirectory: () => boolean; isFile: () => boolean; isSymbolicLink: () => boolean }>;\nexport type InputSelectionHost = Readonly<{ readdir: (path: string) => Promise<readonly HostEntry[]>; stat: (path: string) => Promise<Pick<HostEntry, 'isDirectory' | 'isFile' | 'isSymbolicLink'>>; lstat: (path: string) => Promise<Pick<HostEntry, 'isDirectory' | 'isFile' | 'isSymbolicLink'>>; realpath: (path: string) => Promise<string>; }>;\nexport const defaultInputSelectionHost: InputSelectionHost = Object.freeze({ readdir: async (p) => (await readdir(p, { withFileTypes: true })) as unknown as readonly HostEntry[], stat: async (p) => stat(p), lstat: async (p) => lstat(p), realpath: async (p) => realpath(p) });\n\nexport type CollectInputsOptions = Readonly<{ inputs: readonly string[]; include?: readonly string[]; exclude?: readonly string[]; baseDirectory?: string; outputPath?: string; host?: InputSelectionHost; signal?: AbortSignal }>;\nexport type SelectedInputV2 = Readonly<{ label: string; realPath?: string; isStdin: boolean }>;\nexport type CollectInputsResult = Readonly<{ ok: true; inputs: readonly SelectedInputV2[] }> | Readonly<{ ok: false; code: 'INVALID_CONFIG' | 'INPUT_READ_FAILED' | 'CANCELLED'; message: string }>;\n\nconst fail = <C extends 'INVALID_CONFIG' | 'INPUT_READ_FAILED' | 'CANCELLED'>(code: C, message: string): Readonly<{ ok: false; code: C; message: string }> => Object.freeze({ ok: false, code, message });\n\nfunction sameIdentity(a: unknown, b: unknown): boolean {\n if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false;\n const aObj = a as Record<string, unknown>, bObj = b as Record<string, unknown>;\n return (!('ino' in aObj && 'ino' in bObj) || aObj.ino === bObj.ino) && (!('dev' in aObj && 'dev' in bObj) || aObj.dev === bObj.dev);\n}\n\nexport async function collectInputs(options: CollectInputsOptions): Promise<CollectInputsResult> {\n const host = options.host ?? defaultInputSelectionHost, baseDir = (options.baseDirectory ?? '.').replaceAll('\\\\', '/'), inputs = options.inputs ?? [], signal = options.signal;\n if (signal?.aborted) return fail('CANCELLED', 'Scan was cancelled.');\n if (options.outputPath !== undefined) {\n if (options.outputPath === '') return fail('INVALID_CONFIG', 'Output path is not admitted.');\n if (options.outputPath !== '-') { const c = validatePath(options.outputPath, 'output'); if (!c.ok) return c; }\n }\n if (inputs.length === 0) return fail('INVALID_CONFIG', 'At least one workflow input is required.');\n if (inputs.includes('-')) return inputs.length > 1 ? fail('INVALID_CONFIG', 'Standard input cannot be combined with file inputs.') : Object.freeze({ ok: true, inputs: Object.freeze([{ label: '-', isStdin: true }]) });\n\n const inc = (options.include !== undefined ? options.include : ['**/*.json']).map(compilePosixGlob);\n const exc = (options.exclude !== undefined ? options.exclude : ['.git/**', 'node_modules/**']).map(compilePosixGlob);\n const collected: Array<{ label: string; realPath: string }> = [], budget = { entries: 0, files: 0 };\n\n for (const raw of inputs) {\n if (signal?.aborted) return fail('CANCELLED', 'Scan was cancelled.');\n if (++budget.entries > 100_000) return fail('INPUT_READ_FAILED', 'Directory entry limit exceeded.');\n const check = validatePath(raw, 'input');\n if (!check.ok) return check;\n const norm = check.normalized, fsPath = toFsPathV2(baseDir, norm), label = admittedLabelV2(norm, baseDir);\n\n let lst: Pick<HostEntry, 'isDirectory' | 'isFile' | 'isSymbolicLink'>;\n try { lst = await host.lstat(fsPath); } catch { return fail('INPUT_READ_FAILED', 'Input path does not exist or cannot be accessed.'); }\n\n if (lst.isSymbolicLink()) {\n let tgt: Pick<HostEntry, 'isDirectory' | 'isFile' | 'isSymbolicLink'>;\n try { tgt = await host.stat(fsPath); } catch { return fail('INPUT_READ_FAILED', 'Direct symlink could not be resolved.'); }\n if (tgt.isDirectory() || !tgt.isFile()) return fail('INVALID_CONFIG', 'Direct symlink must resolve to a regular file.');\n try { const r = await host.lstat(fsPath); if (!r.isSymbolicLink() || !sameIdentity(lst, r)) return fail('INPUT_READ_FAILED', 'File modified during scan.'); } catch { return fail('INPUT_READ_FAILED', 'Input path does not exist or cannot be accessed.'); }\n let real: string;\n try { real = (await host.realpath(fsPath)).replaceAll('\\\\', '/'); } catch { return fail('INPUT_READ_FAILED', 'Failed to resolve input path.'); }\n try { const t2 = await host.stat(fsPath); if (!t2.isFile() || t2.isDirectory() || !sameIdentity(tgt, t2)) return fail('INPUT_READ_FAILED', 'File modified during scan.'); } catch { return fail('INPUT_READ_FAILED', 'File modified during scan.'); }\n if (inc.some((re) => re.test(label)) && !exc.some((re) => re.test(label))) {\n if (++budget.files > 10_000) return fail('INPUT_READ_FAILED', 'File limit exceeded.');\n collected.push({ label, realPath: real });\n }\n continue;\n }\n if (lst.isFile()) {\n try { const r = await host.lstat(fsPath); if (r.isSymbolicLink() || !r.isFile() || !sameIdentity(lst, r)) return fail('INPUT_READ_FAILED', 'File modified during scan.'); } catch { return fail('INPUT_READ_FAILED', 'Input path does not exist or cannot be accessed.'); }\n let real: string;\n try { real = (await host.realpath(fsPath)).replaceAll('\\\\', '/'); } catch { return fail('INPUT_READ_FAILED', 'Failed to resolve input path.'); }\n try { const r2 = await host.lstat(fsPath); if (r2.isSymbolicLink() || !r2.isFile() || !sameIdentity(lst, r2)) return fail('INPUT_READ_FAILED', 'File modified during scan.'); } catch { return fail('INPUT_READ_FAILED', 'Failed to read directory.'); }\n if (inc.some((re) => re.test(label)) && !exc.some((re) => re.test(label))) {\n if (++budget.files > 10_000) return fail('INPUT_READ_FAILED', 'File limit exceeded.');\n collected.push({ label, realPath: real });\n }\n continue;\n }\n if (lst.isDirectory()) {\n const walk = await walkDir(fsPath, label, host, inc, exc, 0, budget, signal);\n if (!walk.ok) return walk;\n collected.push(...walk.files);\n continue;\n }\n return fail('INVALID_CONFIG', 'Input must be a regular file or directory.');\n }\n\n const byPath = new Map<string, { label: string; realPath: string }>();\n for (const item of collected) {\n const prev = byPath.get(item.realPath);\n if (!prev || item.label < prev.label) byPath.set(item.realPath, item);\n }\n const sorted = Array.from(byPath.values()).sort((a, b) => (a.label < b.label ? -1 : a.label > b.label ? 1 : 0));\n if (signal?.aborted) return fail('CANCELLED', 'Scan was cancelled.');\n const result = sorted.map((item) => Object.freeze({ label: item.label, realPath: item.realPath, isStdin: false }));\n if (result.length === 0) return fail('INVALID_CONFIG', 'No matching workflow inputs found.');\n\n if (options.outputPath && options.outputPath !== '-') {\n const checkOut = validatePath(options.outputPath, 'output');\n if (!checkOut.ok) return checkOut;\n const collision = await detectOutputCollision(options.outputPath, result, host, baseDir, signal);\n if (signal?.aborted) return fail('CANCELLED', 'Scan was cancelled.');\n if (collision) return fail('INVALID_CONFIG', 'Output path collides with an input file.');\n }\n return Object.freeze({ ok: true, inputs: Object.freeze(result) });\n}\n\nexport async function detectOutputCollision(outputPath: string, inputs: readonly SelectedInputV2[], host: InputSelectionHost = defaultInputSelectionHost, baseDir = '.', signal?: AbortSignal): Promise<boolean> {\n if (!outputPath || outputPath === '-' || signal?.aborted) return false;\n const check = validatePath(outputPath, 'output');\n if (!check.ok) return false;\n let outReal: string | undefined;\n try { outReal = (await host.realpath(toFsPathV2(baseDir, check.normalized))).replaceAll('\\\\', '/'); } catch { /* ignore absent */ }\n if (signal?.aborted) return false;\n return inputs.some((item) => (outReal && item.realPath && outReal === item.realPath) || item.label === check.normalized);\n}\n\nasync function walkDir(\n dirFsPath: string, dirLabel: string, host: InputSelectionHost, inc: readonly RegExp[], exc: readonly RegExp[], depth: number, budget: { entries: number; files: number }, signal?: AbortSignal,\n): Promise<{ ok: true; files: Array<{ label: string; realPath: string }> } | { ok: false; code: 'INPUT_READ_FAILED' | 'CANCELLED'; message: string }> {\n if (signal?.aborted) return fail('CANCELLED', 'Scan was cancelled.');\n if (depth > 64) return fail('INPUT_READ_FAILED', 'Directory recursion limit exceeded.');\n let chk: Pick<HostEntry, 'isDirectory' | 'isFile' | 'isSymbolicLink'>;\n try { chk = await host.lstat(dirFsPath); } catch { return fail('INPUT_READ_FAILED', 'Failed to read directory.'); }\n if (chk.isSymbolicLink() || !chk.isDirectory()) return fail('INPUT_READ_FAILED', 'Directory structure modified during scan.');\n\n let entries: readonly HostEntry[];\n try { entries = await host.readdir(dirFsPath); } catch { return fail('INPUT_READ_FAILED', 'Failed to read directory.'); }\n if (entries.length > 50_000 || budget.entries + entries.length > 100_000) return fail('INPUT_READ_FAILED', 'Directory entry limit exceeded.');\n\n let afterReaddir: Pick<HostEntry, 'isDirectory' | 'isFile' | 'isSymbolicLink'>;\n try { afterReaddir = await host.lstat(dirFsPath); } catch { return fail('INPUT_READ_FAILED', 'Failed to read directory.'); }\n if (afterReaddir.isSymbolicLink() || !afterReaddir.isDirectory() || !sameIdentity(chk, afterReaddir)) return fail('INPUT_READ_FAILED', 'Directory structure modified during scan.');\n\n const files: Array<{ label: string; realPath: string }> = [];\n if (signal?.aborted) return fail('CANCELLED', 'Scan was cancelled.');\n const sorted = [...entries].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n for (const entry of sorted) {\n if (++budget.entries > 100_000) return fail('INPUT_READ_FAILED', 'Directory entry limit exceeded.');\n if (/[\\/\\\\\\u0000-\\u001f\\u007f]/.test(entry.name) || entry.name === '.' || entry.name === '..') continue;\n const childFs = toFsPathV2(dirFsPath, entry.name), childLabel = dirLabel === '.' || dirLabel === '' ? entry.name : `${dirLabel}/${entry.name}`;\n if (childLabel.length > 4096) return fail('INPUT_READ_FAILED', 'Input label exceeds maximum length.');\n\n if (entry.isSymbolicLink()) {\n let tgt: Pick<HostEntry, 'isDirectory' | 'isFile' | 'isSymbolicLink'>;\n try { tgt = await host.stat(childFs); } catch { continue; }\n if (tgt.isDirectory()) continue;\n if (tgt.isFile() && inc.some((re) => re.test(childLabel)) && !exc.some((re) => re.test(childLabel))) {\n if (++budget.files > 10_000) return fail('INPUT_READ_FAILED', 'File limit exceeded.');\n try { const r = await host.lstat(childFs); if (!r.isSymbolicLink() || !sameIdentity(entry, r)) return fail('INPUT_READ_FAILED', 'File modified during scan.'); } catch { continue; }\n let real: string;\n try { real = (await host.realpath(childFs)).replaceAll('\\\\', '/'); } catch { return fail('INPUT_READ_FAILED', 'Failed to resolve input path.'); }\n try { const t2 = await host.stat(childFs); if (!t2.isFile() || t2.isDirectory() || !sameIdentity(tgt, t2)) return fail('INPUT_READ_FAILED', 'File modified during scan.'); } catch { continue; }\n files.push({ label: childLabel, realPath: real });\n }\n continue;\n }\n if (entry.isDirectory()) {\n if (exc.some((re) => re.test(`${childLabel}/`) || re.test(childLabel))) continue;\n let checkLst: Pick<HostEntry, 'isDirectory' | 'isFile' | 'isSymbolicLink'>;\n try { checkLst = await host.lstat(childFs); } catch { return fail('INPUT_READ_FAILED', 'Failed to read directory.'); }\n if (checkLst.isSymbolicLink() || !checkLst.isDirectory() || !sameIdentity(entry, checkLst)) return fail('INPUT_READ_FAILED', 'Directory structure modified during scan.');\n const sub = await walkDir(childFs, childLabel, host, inc, exc, depth + 1, budget, signal);\n if (!sub.ok) return sub;\n files.push(...sub.files);\n continue;\n }\n if (entry.isFile() && inc.some((re) => re.test(childLabel)) && !exc.some((re) => re.test(childLabel))) {\n if (++budget.files > 10_000) return fail('INPUT_READ_FAILED', 'File limit exceeded.');\n try { const r = await host.lstat(childFs); if (r.isSymbolicLink() || !r.isFile() || !sameIdentity(entry, r)) return fail('INPUT_READ_FAILED', 'File modified during scan.'); } catch { return fail('INPUT_READ_FAILED', 'Failed to read directory.'); }\n let real: string;\n try { real = (await host.realpath(childFs)).replaceAll('\\\\', '/'); } catch { return fail('INPUT_READ_FAILED', 'Failed to resolve input path.'); }\n try { const r2 = await host.lstat(childFs); if (r2.isSymbolicLink() || !r2.isFile() || !sameIdentity(entry, r2)) return fail('INPUT_READ_FAILED', 'File modified during scan.'); } catch { return fail('INPUT_READ_FAILED', 'Failed to read directory.'); }\n files.push({ label: childLabel, realPath: real });\n }\n }\n return { ok: true, files };\n}\n\nfunction validatePath(raw: string, kind: 'input' | 'output' = 'input'): { ok: true; normalized: string } | { ok: false; code: 'INVALID_CONFIG'; message: string } {\n const message = kind === 'output' ? 'Output path is not admitted.' : 'Input path is not admitted.';\n const admitted = kind === 'output' ? isAdmittedRelativePath(raw) : isAdmittedLocalPath(raw);\n if (!admitted) return fail('INVALID_CONFIG', message);\n const normalized = normalizeAdmittedPathV2(raw, kind === 'output');\n if (normalized === undefined) return fail('INVALID_CONFIG', message);\n return { ok: true, normalized };\n}\n\nexport function compilePosixGlob(pattern: string): RegExp {\n let s = '^', i = 0; const p = pattern.replaceAll('\\\\', '/');\n while (i < p.length) {\n if (p.startsWith('**/', i)) { s += '(?:.+/)?'; i += 3; }\n else if (p.startsWith('/**', i)) { s += '(?:/.*)?'; i += 3; }\n else if (p.startsWith('**', i)) { s += '.*'; i += 2; }\n else if (p[i] === '*') { s += '[^/]*'; i += 1; }\n else if (p[i] === '?') { s += '[^/]'; i += 1; }\n else if (p[i] === '[') {\n const close = p.indexOf(']', i + 1);\n if (close > i) { const inside = p.slice(i + 1, close); s += `[${inside.startsWith('!') ? '^' + inside.slice(1) : inside}]`; i = close + 1; }\n else { s += '\\\\['; i += 1; }\n } else { s += '()+{}.^$|\\\\'.includes(p[i]!) ? '\\\\' + p[i] : p[i]; i += 1; }\n }\n try { return new RegExp(`${s}$`); } catch { return /$^/; }\n}\n", "import { readFile, open } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { validateScannerLimitsV2, type ScannerLimitsV2 } from '@hub/contracts';\nimport { ADMITTED_CONFIGURATION_KEYS_V2, validateTargetContextV2 } from '@hub/scanner-core/v2';\nimport type { CliCommandV2 } from './arguments';\nimport { loadExplicitConfig, type ScanConfigV2 } from './config';\nimport type { ProjectionSourceV2 } from './json-output';\nimport type { ExitCodeV2 } from './exit-reducer';\n\ntype ScanCommand = Extract<CliCommandV2, { kind: 'scan' }>;\nconst MAX_INPUT_DOCUMENT_BYTES = 1_048_576;\ntype JsonDocumentRead = Readonly<{ ok: true; value: unknown } | { ok: false }>;\n\nexport type LoadedScanConfig = Readonly<{\n ok: true;\n config: ScanConfigV2;\n limitsDocument?: ScannerLimitsV2;\n targetDocument?: unknown;\n sources: ProjectionSourceV2;\n}> | Readonly<{ ok: false; exitCode: ExitCodeV2; message: string }>;\n\n/** Bounded before allocation; invalid UTF-8/JSON fails closed. */\nasync function readJson(baseDirectory: string, relative: string): Promise<JsonDocumentRead> {\n const handle = await open(resolve(baseDirectory, relative), 'r').catch(() => undefined);\n if (handle === undefined) return Object.freeze({ ok: false as const });\n try {\n const stat = await handle.stat();\n if (!stat.isFile() || stat.size > MAX_INPUT_DOCUMENT_BYTES) return Object.freeze({ ok: false as const });\n const bytes = new Uint8Array(stat.size);\n let offset = 0;\n while (offset < bytes.length) {\n const { bytesRead } = await handle.read(bytes, offset, bytes.length - offset, offset);\n if (bytesRead === 0) break;\n offset += bytesRead;\n }\n const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, offset));\n return Object.freeze({ ok: true as const, value: JSON.parse(text) as unknown });\n } catch {\n return Object.freeze({ ok: false as const });\n } finally {\n await handle.close().catch(() => undefined);\n }\n}\n\nexport async function readScanConfig(command: ScanCommand, baseDirectory: string): Promise<LoadedScanConfig> {\n let source: unknown = { schemaVersion: 'n8n-scan-config-v2' };\n if (command.configPath !== undefined) {\n try {\n source = await readFile(resolve(baseDirectory, command.configPath), 'utf8');\n } catch {\n return Object.freeze({ ok: false as const, exitCode: 2 as const, message: 'Configuration could not be read.' });\n }\n }\n const loaded = loadExplicitConfig(source, { configDirectory: baseDirectory, cli: command.cliOverrides });\n if (!loaded.ok) return Object.freeze({ ok: false as const, exitCode: 2 as const, message: 'Configuration is invalid.' });\n\n const invalid = (message: string): LoadedScanConfig => Object.freeze({ ok: false as const, exitCode: 2 as const, message });\n\n let limitsDocument: ScannerLimitsV2 | undefined;\n if (loaded.config.limits !== undefined && loaded.config.limits !== 'builtin') {\n const file = await readJson(baseDirectory, loaded.config.limits);\n if (!file.ok) return invalid('Limits could not be read.');\n const checked = validateScannerLimitsV2(file.value);\n if (!checked.ok) return invalid('Limits are invalid.');\n limitsDocument = checked.limits;\n }\n\n let targetDocument: unknown;\n if (loaded.config.target !== undefined) {\n const file = await readJson(baseDirectory, loaded.config.target);\n if (!file.ok) return invalid('Target context could not be read.');\n targetDocument = file.value;\n }\n const targetOverrides = targetFromCommand(command);\n const hasTargetOverrides = Object.keys(targetOverrides).length > 0;\n if (targetDocument !== undefined || hasTargetOverrides) {\n if (targetDocument !== undefined && (typeof targetDocument !== 'object' || targetDocument === null || Array.isArray(targetDocument))) {\n return invalid('Target context is invalid.');\n }\n const base = (targetDocument ?? {}) as Record<string, unknown>;\n const merged: Record<string, unknown> = { ...base, ...targetOverrides };\n if (hasTargetOverrides) delete merged.contextDigest;\n try {\n targetDocument = validateTargetContextV2(merged, {\n allowedConfigurationKeys: ADMITTED_CONFIGURATION_KEYS_V2,\n });\n } catch { return invalid('Target context is invalid.'); }\n }\n\n let configRecord: Record<string, unknown> = {};\n if (typeof source === 'string') {\n try {\n const parsed: unknown = JSON.parse(source);\n if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) configRecord = parsed as Record<string, unknown>;\n } catch {\n configRecord = {};\n }\n } else if (source !== null && typeof source === 'object' && !Array.isArray(source)) {\n configRecord = source as Record<string, unknown>;\n }\n const cliRecord = command.cliOverrides as Record<string, unknown>;\n const sourceFor = (key: string): 'BUILT_IN' | 'CONFIG' | 'CLI' => Object.prototype.hasOwnProperty.call(cliRecord, key)\n ? 'CLI'\n : Object.prototype.hasOwnProperty.call(configRecord, key) ? 'CONFIG' : 'BUILT_IN';\n const targetFlagged = hasTargetOverrides || command.approvedDomains.length > 0;\n const targetSource = sourceFor('target');\n const unsignedSource = sourceFor('allowUnsignedDevelopmentRules');\n return Object.freeze({\n ok: true as const,\n config: loaded.config,\n ...(limitsDocument === undefined ? {} : { limitsDocument }),\n ...(targetDocument === undefined ? {} : { targetDocument }),\n sources: Object.freeze({\n profile: sourceFor('profile'),\n rules: sourceFor('rules'),\n semantics: sourceFor('catalogue'),\n limits: sourceFor('limits'),\n target: targetFlagged ? 'CLI' : targetSource === 'BUILT_IN' ? 'DEFAULT' : targetSource,\n unsignedDevelopment: unsignedSource === 'BUILT_IN' ? 'DEFAULT' : unsignedSource,\n }),\n });\n}\n\nfunction targetFromCommand(command: ScanCommand): Record<string, unknown> {\n const target: Record<string, unknown> = {};\n if (command.n8nVersion !== undefined) target.n8nVersion = command.n8nVersion;\n if (command.edition !== 'UNKNOWN') target.edition = command.edition;\n if (command.deployment !== 'UNKNOWN') target.deployment = command.deployment;\n if (command.role !== 'UNKNOWN') target.role = command.role;\n if (command.taskRunner !== 'UNKNOWN') target.taskRunner = command.taskRunner;\n if (command.communityPackages.length > 0) {\n target.communityPackages = command.communityPackages.map((value) => {\n const at = value.lastIndexOf('@');\n return at > 0 ? { name: value.slice(0, at), version: value.slice(at + 1) } : { name: value };\n });\n }\n if (command.configuration.length > 0) target.configuration = command.configuration.map((key) => ({ key, state: 'UNKNOWN' }));\n return target;\n}\n", "import { open } from 'node:fs/promises';\nimport type { SelectedInputV2 } from './input-selection';\nimport { toFsPathV2 } from './path-admission.js';\n\nexport const DEFAULT_MAX_INPUT_BYTES = 1_536_000;\nexport type CliStdin = string | Uint8Array | AsyncIterable<Uint8Array | string>;\nexport type InputReadHost = Readonly<{ readFile: (path: string, maxBytes?: number) => Promise<Uint8Array> }>;\n\nexport const defaultInputReadHost: InputReadHost = Object.freeze({\n readFile: async (p: string, maxBytes = DEFAULT_MAX_INPUT_BYTES) => {\n let handle;\n try {\n handle = await open(p, 'r');\n const st = await handle.stat();\n if (!st.isFile()) throw new Error('NOT_REGULAR_FILE');\n if (st.size > maxBytes) throw new RangeError('OVERSIZED');\n const alloc = st.size > 0 ? Math.min(st.size, maxBytes + 1) : Math.min(65536, maxBytes + 1);\n const chunks: Uint8Array[] = [];\n let total = 0;\n while (total <= maxBytes) {\n const buf = new Uint8Array(alloc);\n const { bytesRead } = await handle.read(buf, 0, alloc, total);\n if (bytesRead === 0) break;\n total += bytesRead;\n if (total > maxBytes) throw new RangeError('OVERSIZED');\n chunks.push(buf.subarray(0, bytesRead));\n }\n if (chunks.length === 1) return chunks[0]!;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const c of chunks) { out.set(c, offset); offset += c.byteLength; }\n return out;\n } finally {\n if (handle) await handle.close();\n }\n },\n});\n\nexport type ReadInputOptions = Readonly<{ stdin?: CliStdin; maxBytes?: number; baseDirectory?: string; host?: InputReadHost }>;\nexport type ReadInputSuccess = Readonly<{ ok: true; bytes: Uint8Array; label: string }>;\nexport type ReadInputFailure = Readonly<{ ok: false; code: 'WORKFLOW_TOO_LARGE' | 'INPUT_READ_FAILED' | 'INVALID_CONFIG'; message: string; label: string }>;\nexport type ReadInputResult = ReadInputSuccess | ReadInputFailure;\n\nfunction isValidSelectedInput(input: unknown): input is SelectedInputV2 {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) return false;\n const obj = input as Record<string, unknown>;\n for (const k of Object.keys(obj)) {\n if (k !== 'label' && k !== 'isStdin' && k !== 'realPath') return false;\n }\n if (typeof obj.label !== 'string' || typeof obj.isStdin !== 'boolean') return false;\n if (obj.isStdin) {\n if (obj.label !== '-' || obj.realPath !== undefined) return false;\n } else if (obj.realPath !== undefined && typeof obj.realPath !== 'string') {\n return false;\n }\n return true;\n}\n\nexport async function readInputBytes(input: SelectedInputV2 | string, options: ReadInputOptions = {}): Promise<ReadInputResult> {\n const isString = typeof input === 'string';\n if (!isString && !isValidSelectedInput(input)) {\n return Object.freeze({ ok: false, code: 'INVALID_CONFIG', message: 'Input configuration is invalid.', label: 'input' });\n }\n const isStdin = isString ? input === '-' : input.isStdin;\n const safeLabel = isString ? (input === '-' ? '-' : sanitizeLabel(input)) : sanitizeLabel(input.label);\n const rawMax = options.maxBytes ?? DEFAULT_MAX_INPUT_BYTES;\n if (typeof rawMax !== 'number' || !Number.isSafeInteger(rawMax) || rawMax < 0) {\n return Object.freeze({ ok: false, code: 'INVALID_CONFIG', message: 'Byte limit is invalid.', label: safeLabel });\n }\n const maxBytes = rawMax;\n if (isStdin) return readStdinBytes(options.stdin ?? process.stdin, maxBytes);\n\n const baseDir = (options.baseDirectory ?? '.').replaceAll('\\\\', '/');\n let targetFsPath: string;\n\n if (isString) {\n const valid = validateReadPath(input);\n if (!valid.ok) return Object.freeze({ ok: false, code: 'INVALID_CONFIG', message: 'Input path is not admitted.', label: 'input' });\n targetFsPath = toFsPathV2(baseDir, valid.normalized);\n } else {\n const validLabel = validateReadPath(input.label);\n if (!validLabel.ok) return Object.freeze({ ok: false, code: 'INVALID_CONFIG', message: 'Input path is not admitted.', label: 'input' });\n if (input.realPath !== undefined) {\n const validReal = validateRealPath(input.realPath);\n if (!validReal.ok) return Object.freeze({ ok: false, code: 'INVALID_CONFIG', message: 'Input path is not admitted.', label: 'input' });\n }\n // A validated `realPath` is the selected file identity; the label is display data.\n targetFsPath = typeof input.realPath === 'string' ? input.realPath : toFsPathV2(baseDir, validLabel.normalized);\n }\n\n const host = options.host ?? defaultInputReadHost;\n let rawBytes: Uint8Array;\n try {\n rawBytes = await host.readFile(targetFsPath, maxBytes);\n } catch (err: unknown) {\n if (err instanceof RangeError && err.message === 'OVERSIZED') {\n return Object.freeze({ ok: false, code: 'WORKFLOW_TOO_LARGE', message: 'Workflow exceeds maximum byte limit.', label: safeLabel });\n }\n return Object.freeze({ ok: false, code: 'INPUT_READ_FAILED', message: 'Failed to read input.', label: safeLabel });\n }\n\n if (rawBytes.byteLength > maxBytes) {\n return Object.freeze({ ok: false, code: 'WORKFLOW_TOO_LARGE', message: 'Workflow exceeds maximum byte limit.', label: safeLabel });\n }\n\n const bytes = new Uint8Array(rawBytes.buffer, rawBytes.byteOffset, rawBytes.byteLength);\n return Object.freeze({ ok: true, bytes, label: safeLabel });\n}\n\nasync function readStdinBytes(stdin: CliStdin, maxBytes: number): Promise<ReadInputResult> {\n if (stdin instanceof Uint8Array) {\n if (stdin.byteLength > maxBytes) return Object.freeze({ ok: false, code: 'WORKFLOW_TOO_LARGE', message: 'Workflow exceeds maximum byte limit.', label: '-' });\n return Object.freeze({ ok: true, bytes: new Uint8Array(stdin.buffer, stdin.byteOffset, stdin.byteLength), label: '-' });\n }\n\n if (typeof stdin === 'string') {\n const encoded = new TextEncoder().encode(stdin);\n if (encoded.byteLength > maxBytes) return Object.freeze({ ok: false, code: 'WORKFLOW_TOO_LARGE', message: 'Workflow exceeds maximum byte limit.', label: '-' });\n return Object.freeze({ ok: true, bytes: encoded, label: '-' });\n }\n\n const chunks: Uint8Array[] = [];\n let total = 0;\n const encoder = new TextEncoder();\n try {\n for await (const chunk of stdin) {\n const b = typeof chunk === 'string' ? encoder.encode(chunk) : chunk;\n total += b.byteLength;\n if (total > maxBytes) return Object.freeze({ ok: false, code: 'WORKFLOW_TOO_LARGE', message: 'Workflow exceeds maximum byte limit.', label: '-' });\n chunks.push(b);\n }\n } catch {\n return Object.freeze({ ok: false, code: 'INPUT_READ_FAILED', message: 'Failed to read input.', label: '-' });\n }\n\n const combined = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) { combined.set(chunk, offset); offset += chunk.byteLength; }\n return Object.freeze({ ok: true, bytes: combined, label: '-' });\n}\n\nfunction sanitizeLabel(raw: string): string {\n const norm = raw.replaceAll('\\\\', '/').replace(/[\\u0000-\\u001f\\u007f]/g, '');\n const parts: string[] = [];\n for (const p of norm.split('/')) {\n if (!p || p === '.') continue;\n parts.push(p);\n }\n return parts.length === 0 ? '.' : parts.join('/').slice(0, 4096);\n}\n\nfunction validateReadPath(raw: string): { ok: true; normalized: string } | { ok: false } {\n if (!raw || raw.length === 0 || raw.length > 4096 || /[\\u0000-\\u001f\\u007f]/.test(raw)) return { ok: false };\n const norm = raw.replaceAll('\\\\', '/');\n if (/^(?:[a-z][a-z\\d+.-]*:|\\/|[a-z]:|\\\\\\\\)/i.test(norm) || norm.startsWith('//')) return { ok: false };\n const parts: string[] = [];\n for (const p of norm.split('/')) {\n if (!p || p === '.') continue;\n if (p === '..') {\n if (parts.length === 0) return { ok: false };\n parts.pop();\n continue;\n }\n parts.push(p);\n }\n return { ok: true, normalized: parts.length === 0 ? '.' : parts.join('/') };\n}\n\nfunction validateRealPath(raw: string): { ok: true; normalized: string } | { ok: false } {\n if (!raw || raw.length === 0 || raw.length > 4096 || /[\\u0000-\\u001f\\u007f]/.test(raw)) return { ok: false };\n const norm = raw.replaceAll('\\\\', '/');\n if (norm.startsWith('//') || norm.startsWith('\\\\\\\\')) return { ok: false };\n if (/^[a-z][a-z\\d+.-]*:/i.test(norm) && !/^[a-z]:\\//i.test(norm)) return { ok: false };\n const parts = norm.split('/');\n for (const p of parts) {\n if (p === '..' || p === '.') return { ok: false };\n }\n return { ok: true, normalized: norm };\n}\n", "import { createRequire } from 'node:module';\nimport { pathToFileURL } from 'node:url';\nimport { Worker } from 'node:worker_threads';\nimport type { WorkerHostRun } from './worker-host';\n\nexport type ScanWorkerData = Readonly<{\n bytes: Uint8Array;\n profile: Readonly<{ id: string; version: string }>;\n target?: unknown;\n limits?: unknown;\n approvedDomains?: readonly string[];\n}>;\nexport type ScanWorkerFactory = () => Worker;\nexport type ScanWorkerOptions = Readonly<{ timeoutMs?: number; signal?: AbortSignal; workerFactory?: ScanWorkerFactory }>;\n\nconst requireFromPackage = createRequire(import.meta.url);\n\n/**\n * `#sfscanner-worker` is the package's private imports map to the one built\n * `dist/scan-worker.js`. `createRequire(...).resolve` uses the same native\n * package-imports resolution as `import.meta.resolve` (unavailable in\n * vite-node) and checks the target exists, so the same call works from the\n * root bundle, the v2 subpath bundle, and the unbundled source tree after one\n * build. A missing asset throws MODULE_NOT_FOUND; there is no fallback.\n */\nexport function scanWorkerUrl(): URL {\n return pathToFileURL(requireFromPackage.resolve('#sfscanner-worker'));\n}\n\nexport function createScanWorker(data: ScanWorkerData): Worker {\n return new Worker(scanWorkerUrl(), { workerData: data });\n}\n\nexport async function runScanInWorker<T = unknown>(data: ScanWorkerData, options: ScanWorkerOptions = {}): Promise<WorkerHostRun<T>> {\n const { timeoutMs, signal } = options;\n if (signal?.aborted) return Object.freeze({ status: 'CANCELLED' as const });\n if (timeoutMs !== undefined && (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2_147_483_647)) return Object.freeze({ status: 'FAILED' as const });\n if (timeoutMs === 0) return Object.freeze({ status: 'TIMEOUT' as const });\n let worker: Worker;\n try {\n worker = (options.workerFactory ?? (() => createScanWorker(data)))();\n } catch {\n // Missing #sfscanner-worker or a failed construction is a closed per-item FAILED, never a\n // rejected promise and never an in-process fallback.\n return Object.freeze({ status: 'FAILED' as const });\n }\n const { promise, resolve } = Promise.withResolvers<WorkerHostRun<T>>();\n let settled = false;\n let timer: NodeJS.Timeout | undefined;\n // Settlement means `terminate()` fulfilled for the owned thread, not merely that termination\n // was requested: the batch may start the next item as soon as this promise resolves. A\n // fulfilled terminate is not independent proof of exit on native Node 22; the rejection path\n // below already reports FAILED when that call rejects (60 / 64-F3).\n const settleAfterExit = (result: WorkerHostRun<T>): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n signal?.removeEventListener('abort', onAbort);\n void worker.terminate().then(\n () => resolve(Object.freeze(result)),\n // A rejected termination leaves the exit unproven for every status. TIMEOUT, CANCELLED, and\n // FAILED must not be reported as their normal result once the thread's exit is unproven.\n () => resolve(Object.freeze({ status: 'FAILED' as const })),\n );\n };\n const onAbort = (): void => { settleAfterExit({ status: 'CANCELLED' }); };\n signal?.addEventListener('abort', onAbort, { once: true });\n // Arm the worker handlers before the post-construction abort check can terminate, so an\n // error/exit emitted in that window is still owned by this promise instead of escaping.\n worker.once('message', (value) => { settleAfterExit({ status: 'COMPLETED', value: value as T }); });\n worker.once('error', () => { settleAfterExit({ status: 'FAILED' }); });\n worker.once('exit', () => { settleAfterExit({ status: 'FAILED' }); });\n // The signal may abort between the caller's check and listener installation.\n if (signal?.aborted) { onAbort(); return promise; }\n if (timeoutMs !== undefined) timer = setTimeout(() => { settleAfterExit({ status: 'TIMEOUT' }); }, timeoutMs);\n return promise;\n}\n", "export type WorkerHostStatus = 'COMPLETED' | 'FAILED' | 'CANCELLED' | 'TIMEOUT';\nexport type WorkerHostRun<T> = Readonly<{ status: 'COMPLETED'; value: T } | { status: Exclude<WorkerHostStatus, 'COMPLETED'> }>;\nexport type SigintSource = Readonly<{ on: (event: 'SIGINT', listener: () => void) => unknown; off?: (event: 'SIGINT', listener: () => void) => unknown; removeListener?: (event: 'SIGINT', listener: () => void) => unknown }>;\nexport type SigintController = Readonly<{ signal: AbortSignal; dispose: () => void }>;\nexport type WorkerHostOptions = Readonly<{ signal?: AbortSignal; sigint?: SigintSource; timeoutMs?: number; now?: () => number }>;\ntype Deferred<T> = Readonly<{ promise: Promise<T>; resolve: (value: T | PromiseLike<T>) => void; reject: (reason?: unknown) => void }>;\n\nfunction createDeferred<T>(): Deferred<T> {\n let resolve!: Deferred<T>['resolve'];\n let reject!: Deferred<T>['reject'];\n const promise = new Promise<T>((promiseResolve, promiseReject) => {\n resolve = promiseResolve;\n reject = promiseReject;\n });\n return { promise, resolve, reject };\n}\n\nexport function createSigintController(source: SigintSource = process): SigintController {\n const controller = new AbortController();\n const onSigint = (): void => controller.abort();\n source.on('SIGINT', onSigint);\n return Object.freeze({\n signal: controller.signal,\n dispose: (): void => {\n if (source.off) source.off('SIGINT', onSigint);\n else if (source.removeListener) source.removeListener('SIGINT', onSigint);\n },\n });\n}\n\nexport async function runHostedScan<T>(task: () => T | PromiseLike<T>, options: WorkerHostOptions = {}): Promise<WorkerHostRun<T>> {\n const timeout = options.timeoutMs;\n if (timeout !== undefined && (!Number.isSafeInteger(timeout) || timeout < 0 || timeout > 2_147_483_647)) return Object.freeze({ status: 'FAILED' });\n if (options.signal?.aborted) return Object.freeze({ status: 'CANCELLED' });\n if (timeout === 0) return Object.freeze({ status: 'TIMEOUT' });\n const now = options.now ?? Date.now;\n const sigint = options.sigint === undefined ? undefined : createSigintController(options.sigint);\n if (sigint?.signal.aborted || options.signal?.aborted) { sigint?.dispose(); return Object.freeze({ status: 'CANCELLED' }); }\n const { promise, resolve } = createDeferred<WorkerHostRun<T>>();\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const started = now();\n const finish = (result: WorkerHostRun<T>): void => {\n if (settled) return;\n settled = true;\n if (timer !== undefined) clearTimeout(timer);\n options.signal?.removeEventListener('abort', onAbort);\n sigint?.signal.removeEventListener('abort', onAbort);\n sigint?.dispose();\n resolve(Object.freeze(result));\n };\n const onAbort = (): void => finish({ status: 'CANCELLED' });\n options.signal?.addEventListener('abort', onAbort, { once: true });\n sigint?.signal.addEventListener('abort', onAbort, { once: true });\n if (timeout !== undefined) timer = setTimeout(() => finish({ status: 'TIMEOUT' }), timeout);\n void Promise.resolve().then(task).then((value) => {\n let expired = false;\n if (timeout !== undefined) { try { expired = now() - started >= timeout; } catch { expired = false; } }\n finish(expired ? { status: 'TIMEOUT' } : { status: 'COMPLETED', value });\n }, () => finish({ status: 'FAILED' }));\n return promise;\n}\n", "import { DEFAULT_SCANNER_LIMITS_V2, type ScannerLimitsV2 } from '@hub/contracts';\nimport type { ScanWorkflowV2FailureCode, ScanWorkflowV2Result } from '@hub/scanner-core/v2';\nimport { ADMITTED_PROFILE_V2, loadExplicitConfig, type ConfigLoadResult, type ScanConfigV2 } from './config';\nimport { SCAN_CONFIG_V2_MAX_CONCURRENCY } from './contracts';\nimport { readInputBytes, type CliStdin, type InputReadHost, type ReadInputFailure, type ReadInputResult } from './input-read';\nimport type { SelectedInputV2 } from './input-selection';\nimport { runScanInWorker, type ScanWorkerFactory } from './scan-worker-host';\nimport { createSigintController, runHostedScan, type SigintSource, type WorkerHostRun } from './worker-host';\n\nexport type BatchErrorCodeV2 = ScanWorkflowV2FailureCode | 'INPUT_READ_FAILED';\nexport type BatchItemStatusV2 = 'COMPLETED' | 'FAILED' | 'CANCELLED' | 'TIMEOUT';\nexport type BatchItemV2 = Readonly<{ label: string; status: BatchItemStatusV2; result?: ScanWorkflowV2Result; error?: Readonly<{ code: BatchErrorCodeV2 }> }>;\nexport type BatchResultV2 =\n | Readonly<{ ok: true; items: readonly BatchItemV2[]; cancelled: boolean; completed: number; failed: number; concurrency: number }>\n | Readonly<{ ok: false; code: 'INVALID_CONFIG' | 'CANCELLED'; message: string }>;\nexport type BatchScanV2 = (bytes: Uint8Array, item: SelectedInputV2) => ScanWorkflowV2Result | PromiseLike<ScanWorkflowV2Result>;\nexport type BatchReadV2 = (item: SelectedInputV2) => Uint8Array | ReadInputResult | PromiseLike<Uint8Array | ReadInputResult>;\nexport type BatchRunnerInput = Readonly<{ items: readonly SelectedInputV2[]; config: ScanConfigV2; scan?: BatchScanV2; read?: BatchReadV2; stdin?: CliStdin; readHost?: InputReadHost; baseDirectory?: string; maxInputBytes?: number; limitsDocument?: ScannerLimitsV2; targetDocument?: unknown; approvedDomains?: readonly string[]; scanWorker?: ScanWorkerFactory; timeoutMs?: number; signal?: AbortSignal; sigint?: SigintSource; now?: () => number }>;\n\ntype NormalizedInput = Readonly<{ item: SelectedInputV2; invalid: boolean }>;\nconst failureCodes: Readonly<Record<string, true>> = Object.freeze({\n UTF8_DECODING_FAILED: true, INVALID_JSON: true, MALFORMED_WORKFLOW: true, WORKFLOW_TOO_LARGE: true, WORKFLOW_TOO_COMPLEX: true,\n INVALID_CONFIG: true, UNKNOWN_CONFIGURATION_KEY: true, PROFILE_NOT_ADMITTED: true, SEMANTIC_CATALOGUE_INVALID: true,\n SEMANTIC_CATALOGUE_AMBIGUOUS: true, RULE_PACK_INVALID: true, RULE_PACK_UNTRUSTED: true, TOOL_INVARIANT_FAILED: true,\n SERIALIZATION_FAILED: true, SCAN_TIMEOUT: true, SCAN_CANCELLED: true, INPUT_READ_FAILED: true,\n});\n\nexport async function runBatchV2(input: BatchRunnerInput): Promise<BatchResultV2> {\n let loaded: ConfigLoadResult;\n try { loaded = loadExplicitConfig(input?.config); } catch { return invalidConfig(); }\n if (!loaded.ok || !Array.isArray(input?.items) || input.items.length === 0 || input.items.length > 100_000) return invalidConfig();\n const config = loaded.config;\n if (config.rules !== 'builtin' || config.catalogue !== 'builtin') return invalidConfig();\n if (config.limits !== 'builtin' && input.limitsDocument === undefined) return invalidConfig();\n const limitsDocument = input.limitsDocument;\n if (limitsDocument !== undefined && (\n !Number.isSafeInteger(limitsDocument.maxBytes) || limitsDocument.maxBytes < 0\n || !Number.isSafeInteger(limitsDocument.workerDeadlineMs) || limitsDocument.workerDeadlineMs < 0\n )) return invalidConfig();\n const maxBytes = input.maxInputBytes ?? limitsDocument?.maxBytes ?? DEFAULT_SCANNER_LIMITS_V2.maxBytes;\n const timeoutMs = input.timeoutMs ?? limitsDocument?.workerDeadlineMs ?? DEFAULT_SCANNER_LIMITS_V2.workerDeadlineMs;\n if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2_147_483_647) return invalidConfig();\n const normalized = normalizeItems(input.items);\n if (!normalized || (normalized.some(({ item }) => item.isStdin) && normalized.length > 1)) return invalidConfig();\n const ordered = [...normalized].sort((a, b) => compareItems(a.item, b.item));\n const sigint = input.sigint === undefined ? undefined : createSigintController(input.sigint);\n const combined = combineSignals(input.signal, sigint?.signal);\n const results = new Array<BatchItemV2 | undefined>(ordered.length);\n let next = 0;\n const concurrency = Math.min(config.concurrency ?? 1, SCAN_CONFIG_V2_MAX_CONCURRENCY, ordered.length);\n const scan = input.scan;\n const work = async (): Promise<void> => {\n while (true) {\n const index = next++;\n if (index >= ordered.length) return;\n const current = ordered[index]!;\n results[index] = combined.signal?.aborted ? cancelled(current.item.label) : await scanOne(current, scan, input, config, maxBytes, timeoutMs, combined.signal, input.now ?? Date.now);\n }\n };\n await Promise.all(Array.from({ length: concurrency }, () => work().catch(() => undefined)));\n for (let index = 0; index < results.length; index += 1) if (!results[index]) results[index] = failed(ordered[index]!.item.label, 'TOOL_INVARIANT_FAILED');\n combined.dispose(); sigint?.dispose();\n const items = Object.freeze(results.map((item) => Object.freeze(item ?? cancelled('input'))));\n const completed = items.filter(({ status }) => status === 'COMPLETED').length;\n const failedCount = items.filter(({ status }) => status === 'FAILED' || status === 'TIMEOUT').length;\n return Object.freeze({ ok: true as const, items, cancelled: items.some(({ status }) => status === 'CANCELLED'), completed, failed: failedCount, concurrency });\n}\n\nasync function scanOne(current: NormalizedInput, scan: BatchScanV2 | undefined, input: BatchRunnerInput, config: ScanConfigV2, maxBytes: number, timeoutMs: number, signal: AbortSignal | undefined, now: () => number): Promise<BatchItemV2> {\n if (current.invalid) return failed(current.item.label, 'INVALID_CONFIG');\n const deadline = timeoutMs === 0 ? now() : now() + timeoutMs;\n const remaining = (): number => Math.max(0, deadline - now());\n let read: Uint8Array | ReadInputFailure;\n let inputRun: WorkerHostRun<Uint8Array | ReadInputResult>;\n try {\n inputRun = await runHostedScan(\n () => input.read\n ? input.read(current.item)\n : readInputBytes(current.item, { stdin: input.stdin, maxBytes, baseDirectory: input.baseDirectory, host: input.readHost }),\n { signal, timeoutMs: remaining(), now },\n );\n } catch { return failed(current.item.label, 'INPUT_READ_FAILED'); }\n if (inputRun.status === 'CANCELLED') return cancelled(current.item.label);\n if (inputRun.status === 'TIMEOUT') return failed(current.item.label, 'SCAN_TIMEOUT');\n if (inputRun.status !== 'COMPLETED') return failed(current.item.label, 'INPUT_READ_FAILED');\n try {\n const value = inputRun.value;\n if (value instanceof Uint8Array) read = value;\n else if (value && typeof value === 'object' && value.ok === true && value.bytes instanceof Uint8Array) read = value.bytes;\n else if (value && typeof value === 'object' && value.ok === false) read = value as ReadInputFailure;\n else return failed(current.item.label, 'INPUT_READ_FAILED');\n } catch { return failed(current.item.label, 'INPUT_READ_FAILED'); }\n if (!(read instanceof Uint8Array)) return failed(current.item.label, safeReadCode(read.code));\n if (read.byteLength > maxBytes) return failed(current.item.label, 'WORKFLOW_TOO_LARGE');\n let completed: WorkerHostRun<ScanWorkflowV2Result>;\n if (scan !== undefined) {\n try {\n completed = await runHostedScan(() => scan(read, current.item), { signal, timeoutMs: remaining(), now });\n } catch { return failed(current.item.label, 'TOOL_INVARIANT_FAILED'); }\n } else {\n completed = await runScanInWorker<ScanWorkflowV2Result>(\n {\n bytes: read,\n profile: { id: ADMITTED_PROFILE_V2.id, version: ADMITTED_PROFILE_V2.version },\n ...(input.targetDocument === undefined ? {} : { target: input.targetDocument }),\n ...(input.limitsDocument === undefined ? {} : { limits: input.limitsDocument }),\n ...(input.approvedDomains === undefined ? {} : { approvedDomains: input.approvedDomains }),\n },\n { signal, timeoutMs: remaining(), workerFactory: input.scanWorker },\n );\n }\n if (completed.status === 'CANCELLED') return cancelled(current.item.label);\n if (completed.status === 'TIMEOUT') return failed(current.item.label, 'SCAN_TIMEOUT');\n if (completed.status !== 'COMPLETED') return failed(current.item.label, 'TOOL_INVARIANT_FAILED');\n return toBatchItem(current.item.label, completed.value, config);\n}\n\nfunction toBatchItem(label: string, result: ScanWorkflowV2Result, config: ScanConfigV2): BatchItemV2 {\n try {\n if (!result || typeof result !== 'object' || typeof result.ok !== 'boolean') return failed(label, 'TOOL_INVARIANT_FAILED');\n if (!result.ok) return failed(label, safeScanCode(result.code));\n const profile = result.result && typeof result.result === 'object' ? result.result.profile : undefined;\n if (!profile || profile.id !== config.profile || profile.version !== ADMITTED_PROFILE_V2.version) return failed(label, 'TOOL_INVARIANT_FAILED');\n return Object.freeze({ label, status: 'COMPLETED' as const, result: freezeValue(result) });\n } catch { return failed(label, 'TOOL_INVARIANT_FAILED'); }\n}\nfunction normalizeItems(items: readonly SelectedInputV2[]): NormalizedInput[] | undefined {\n try {\n const output: NormalizedInput[] = [];\n for (const raw of items) {\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const value = raw as Record<string, unknown>;\n const names = Object.getOwnPropertyNames(value);\n const closed = Object.getOwnPropertySymbols(value).length === 0 && names.every((name) => { const descriptor = Object.getOwnPropertyDescriptor(value, name); return descriptor !== undefined && 'value' in descriptor; });\n const valid = closed && typeof value.label === 'string' && value.label.length > 0 && value.label.length <= 4096 && typeof value.isStdin === 'boolean' && (value.isStdin ? value.label === '-' && value.realPath === undefined : value.label !== '-') && (value.realPath === undefined || typeof value.realPath === 'string') && names.every((key) => key === 'label' || key === 'realPath' || key === 'isStdin') && !/[\\u0000-\\u001f\\u007f]/.test(value.label) && !/^(?:[a-z][a-z\\d+.-]*:|\\/|[a-z]:|\\\\)|(?:^|[/\\\\])\\.\\.(?:[/\\\\]|$)/i.test(value.label);\n const item = valid ? Object.freeze({ label: value.label as string, ...(typeof value.realPath === 'string' ? { realPath: value.realPath } : {}), isStdin: value.isStdin as boolean }) : Object.freeze({ label: 'input', isStdin: false });\n output.push({ item, invalid: !valid });\n }\n return output;\n } catch { return undefined; }\n}\nfunction compareItems(a: SelectedInputV2, b: SelectedInputV2): number { return a.label < b.label ? -1 : a.label > b.label ? 1 : (a.realPath ?? '') < (b.realPath ?? '') ? -1 : (a.realPath ?? '') > (b.realPath ?? '') ? 1 : 0; }\nfunction failed(label: string, code: BatchErrorCodeV2): BatchItemV2 { return Object.freeze({ label, status: code === 'SCAN_TIMEOUT' ? 'TIMEOUT' as const : 'FAILED' as const, error: Object.freeze({ code }) }); }\nfunction cancelled(label: string): BatchItemV2 { return Object.freeze({ label, status: 'CANCELLED' as const, error: Object.freeze({ code: 'SCAN_CANCELLED' as const }) }); }\nfunction safeScanCode(code: unknown): BatchErrorCodeV2 { return typeof code === 'string' && failureCodes[code] === true ? code as BatchErrorCodeV2 : 'TOOL_INVARIANT_FAILED'; }\nfunction safeReadCode(code: unknown): BatchErrorCodeV2 { return code === 'WORKFLOW_TOO_LARGE' || code === 'INPUT_READ_FAILED' || code === 'INVALID_CONFIG' ? code : 'INPUT_READ_FAILED'; }\nfunction invalidConfig(): BatchResultV2 { return Object.freeze({ ok: false as const, code: 'INVALID_CONFIG' as const, message: 'Configuration is invalid.' }); }\nfunction combineSignals(first?: AbortSignal, second?: AbortSignal): { signal?: AbortSignal; dispose: () => void } {\n if (!first) return { signal: second, dispose: () => undefined };\n if (!second) return { signal: first, dispose: () => undefined };\n const controller = new AbortController(); const abort = (): void => controller.abort();\n if (first.aborted || second.aborted) controller.abort();\n first.addEventListener('abort', abort, { once: true }); second.addEventListener('abort', abort, { once: true });\n return { signal: controller.signal, dispose: (): void => { first.removeEventListener('abort', abort); second.removeEventListener('abort', abort); } };\n}\nfunction freezeValue<T>(value: T, seen = new WeakSet<object>()): T { if (value !== null && typeof value === 'object') { if (seen.has(value)) return value; seen.add(value); for (const key of Object.getOwnPropertyNames(value)) freezeValue((value as Record<string, unknown>)[key], seen); Object.freeze(value); } return value; }\n", "import { canonicalizeJson } from '@hub/scanner-core/canonical-json';\nimport { validateScannerResultV2, type ScannerResultV2 } from '@hub/contracts/scanner-v2-result';\nimport { ADMITTED_PROFILE_V2, BUILTIN_LIMITS_AUTHORITY_V2, BUILTIN_RULESET_AUTHORITY_V2, BUILTIN_SEMANTICS_AUTHORITY_V2, CLI_TOOL_V2 } from './contracts';\nimport type { BatchErrorCodeV2, BatchItemV2, BatchResultV2 } from './batch-runner';\n\nexport type ProjectionFormatV2 = 'json' | 'ndjson' | 'sarif' | 'table';\nexport type ProjectionSourceV2 = Readonly<{\n profile: 'BUILT_IN' | 'CONFIG' | 'CLI';\n rules: 'BUILT_IN' | 'CONFIG' | 'CLI';\n semantics: 'BUILT_IN' | 'CONFIG' | 'CLI';\n limits: 'BUILT_IN' | 'CONFIG' | 'CLI';\n target: 'DEFAULT' | 'CONFIG' | 'CLI';\n unsignedDevelopment: 'DEFAULT' | 'CONFIG' | 'CLI';\n}>;\nexport type ProjectionOptionsV2 = Readonly<{\n format: ProjectionFormatV2;\n profile: string;\n failOn: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';\n requireComplete: boolean;\n concurrency: number;\n allowUnsignedDevelopmentRules: boolean;\n sources: ProjectionSourceV2;\n}>;\ntype ArtifactV2 = Readonly<{ profile: { id: string; version: string }; ruleset: { id: string; version: string; digest: string; signatureStatus: 'VERIFIED' | 'UNVERIFIED' }; semantics: { id: string; version: string; digest: string }; target: ScannerResultV2['target']; limits: { schemaVersion: 'scanner-limits-v2'; digest: string } }>;\ntype CliErrorCodeV2 = BatchErrorCodeV2 | 'OUTPUT_WRITE_FAILED';\ntype CliErrorV2 = Readonly<{ kind: 'INPUT' | 'INCOMPLETE' | 'INTERNAL' | 'CANCELLED'; code: CliErrorCodeV2; message: string }>;\ntype CliItemV2 = Readonly<{ input: string; ok: true; result: ScannerResultV2 } | { input: string; ok: false; error: CliErrorV2 }>;\ntype SummaryV2 = Readonly<{ total: number; complete: number; degraded: number; indeterminate: number; inputErrors: number; internalErrors: number; cancelled: number; findings: number }>;\ntype BatchState = Readonly<{ ok: boolean; items: readonly BatchItemV2[]; code?: string; cancelled: boolean; concurrency: number }>;\nexport type CliEnvelopeV2 = Readonly<{ schemaVersion: 'n8n-scan-v2'; tool: Readonly<{ name: 'n8n-scan'; version: string; buildDigest: string }>; artifacts: ArtifactV2; invocation: Readonly<{ schema: 'v2'; format: 'json' | 'ndjson' | 'sarif' | 'table'; profile: string; failOn: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO'; requireComplete: boolean; concurrency: number; allowUnsignedDevelopmentRules: boolean; sources: ProjectionSourceV2 }>; results: readonly CliItemV2[]; summary: SummaryV2; exitReason: 'UNDER_THRESHOLD' | 'FINDING_THRESHOLD' | 'REQUIRE_COMPLETE' | 'ITEM_FAILURE' | 'USAGE' | 'INTERNAL' | 'CANCELLED' }>;\nexport type ProjectedBatchV2 = Readonly<{ envelope: CliEnvelopeV2; items: readonly CliItemV2[] }>;\n\nexport const DEFAULT_PROJECTION_OPTIONS: ProjectionOptionsV2 = Object.freeze({\n format: 'json',\n profile: ADMITTED_PROFILE_V2.id,\n failOn: 'INFO',\n requireComplete: false,\n concurrency: 1,\n allowUnsignedDevelopmentRules: false,\n sources: Object.freeze({\n profile: 'BUILT_IN',\n rules: 'BUILT_IN',\n semantics: 'BUILT_IN',\n limits: 'BUILT_IN',\n target: 'DEFAULT',\n unsignedDevelopment: 'DEFAULT',\n }),\n});\n\nconst ERROR_CODES: Readonly<Record<string, true>> = Object.freeze({\n UTF8_DECODING_FAILED: true, INVALID_JSON: true, MALFORMED_WORKFLOW: true, WORKFLOW_TOO_LARGE: true,\n WORKFLOW_TOO_COMPLEX: true, INPUT_READ_FAILED: true, SCAN_TIMEOUT: true, SCAN_CANCELLED: true,\n INVALID_CONFIG: true, UNKNOWN_CONFIGURATION_KEY: true, PROFILE_NOT_ADMITTED: true,\n SEMANTIC_CATALOGUE_INVALID: true, SEMANTIC_CATALOGUE_AMBIGUOUS: true, RULE_PACK_INVALID: true,\n RULE_PACK_UNTRUSTED: true, TOOL_INVARIANT_FAILED: true, SERIALIZATION_FAILED: true, OUTPUT_WRITE_FAILED: true,\n});\n\nconst TARGET = Object.freeze({ edition: 'UNKNOWN' as const, deployment: 'UNKNOWN' as const, role: 'UNKNOWN' as const, taskRunner: 'UNKNOWN' as const, communityPackages: Object.freeze([]), configuration: Object.freeze([]), contextDigest: '37375ccade6e19ae23ed985b406d460082f3481fd2c97347e0131fc4003b9a56' });\nconst ERROR_MESSAGES: Readonly<Record<string, string>> = Object.freeze({ UTF8_DECODING_FAILED: 'Input is not valid UTF-8.', INVALID_JSON: 'Input is not valid JSON.', MALFORMED_WORKFLOW: 'Input is not a valid workflow.', WORKFLOW_TOO_LARGE: 'Input exceeds the admitted size limit.', WORKFLOW_TOO_COMPLEX: 'Input exceeds the admitted complexity limit.', INPUT_READ_FAILED: 'Input could not be read.', SCAN_TIMEOUT: 'Scan timed out.', SCAN_CANCELLED: 'Scan was cancelled.', INVALID_CONFIG: 'Configuration is invalid.', UNKNOWN_CONFIGURATION_KEY: 'Configuration contains an unknown key.', PROFILE_NOT_ADMITTED: 'Profile is not admitted.', SEMANTIC_CATALOGUE_INVALID: 'Semantic catalogue is invalid.', SEMANTIC_CATALOGUE_AMBIGUOUS: 'Semantic catalogue is ambiguous.', RULE_PACK_INVALID: 'Rule pack is invalid.', RULE_PACK_UNTRUSTED: 'Rule pack is untrusted.', TOOL_INVARIANT_FAILED: 'Scanner invariant failed.', SERIALIZATION_FAILED: 'Serialization failed.', OUTPUT_WRITE_FAILED: 'Output could not be written.' });\nconst SECRET = /(?:api[ _-]*key|password|secret|credential|authorization|cookie|bearer|token)\\s*[:=]|\\b(?:sk[-_][\\w-]+|AKIA[0-9A-Z]{16}|eyJ[\\w-]{12,}\\.[\\w-]{8,})\\b/i;\nconst ABSOLUTE = /^(?:[a-z][a-z\\d+.-]*:|\\/|\\\\|[a-z]:[\\\\/])/i;\nconst TRAVERSAL = /(?:^|[\\\\/])\\.\\.(?:[\\\\/]|$)/;\n\nexport function serializeEnvelopeV2(batch: BatchResultV2, options: ProjectionOptionsV2 = DEFAULT_PROJECTION_OPTIONS): string {\n try { return canonicalizeJson(projectBatchV2(batch, options).envelope); } catch { return canonicalizeJson(projectBatchV2({ ok: false, code: 'INVALID_CONFIG', message: 'Configuration is invalid.' }, options).envelope); }\n}\n\nexport function projectBatchV2(batch: BatchResultV2, options: ProjectionOptionsV2 | ProjectionFormatV2 = DEFAULT_PROJECTION_OPTIONS): ProjectedBatchV2 {\n const projection = typeof options === 'string' ? Object.freeze({ ...DEFAULT_PROJECTION_OPTIONS, format: options }) : options;\n const state = readBatch(batch);\n const rawItems = state.ok ? state.items : [];\n const validResults = rawItems.map(readScannerResult).filter((value): value is ScannerResultV2 => value !== undefined);\n const artifacts = Object.freeze(validResults.length ? artifact(validResults[0]!) : defaults());\n const items = Object.freeze(rawItems.map((item) => normalizeItem(item, artifacts)));\n const summary = summarize(items);\n const envelope = Object.freeze({ schemaVersion: 'n8n-scan-v2' as const, tool: CLI_TOOL_V2, artifacts, invocation: invocation(projection), results: items, summary, exitReason: exitReason(state, summary, items, projection) });\n return Object.freeze({ envelope, items });\n}\n\nfunction readBatch(input: unknown): BatchState {\n try {\n if (!input || typeof input !== 'object') return { ok: false, items: [], code: 'INVALID_CONFIG', cancelled: false, concurrency: 1 };\n const value = input as Record<string, unknown>;\n if (value.ok === false) return { ok: false, items: [], code: value.code === 'CANCELLED' ? 'CANCELLED' : 'INVALID_CONFIG', cancelled: value.code === 'CANCELLED', concurrency: 1 };\n if (value.ok !== true || !Array.isArray(value.items) || value.items.length > 100_000) return { ok: false, items: [], code: 'INVALID_CONFIG', cancelled: false, concurrency: 1 };\n for (let index = 0; index < value.items.length; index += 1) if (!Object.prototype.hasOwnProperty.call(value.items, index)) return { ok: false, items: [], code: 'INVALID_CONFIG', cancelled: false, concurrency: 1 };\n const concurrency = Number.isSafeInteger(value.concurrency) && (value.concurrency as number) > 0 ? Math.min(value.concurrency as number, 16) : 1;\n return { ok: true, items: value.items as BatchItemV2[], cancelled: value.cancelled === true, concurrency };\n } catch { return { ok: false, items: [], code: 'INVALID_CONFIG', cancelled: false, concurrency: 1 }; }\n}\n\nfunction readScannerResult(item: BatchItemV2): ScannerResultV2 | undefined {\n try {\n if (!item || typeof item !== 'object' || item.status !== 'COMPLETED' || !item.result || typeof item.result !== 'object' || item.result.ok !== true) return undefined;\n const checked = validateScannerResultV2(item.result.result);\n if (!checked.ok || checked.result.profile.id !== ADMITTED_PROFILE_V2.id || checked.result.profile.version !== ADMITTED_PROFILE_V2.version) return undefined;\n return freezeValue(checked.result);\n } catch { return undefined; }\n}\nfunction freezeValue<T>(value: T, seen = new WeakSet<object>()): T {\n if (value && typeof value === 'object') {\n if (seen.has(value)) return value;\n seen.add(value);\n for (const key of Object.getOwnPropertyNames(value)) freezeValue((value as Record<string, unknown>)[key], seen);\n Object.freeze(value);\n }\n return value;\n}\nfunction artifact(result: ScannerResultV2): ArtifactV2 { return Object.freeze({ profile: Object.freeze({ ...result.profile }), ruleset: Object.freeze({ ...result.ruleset }), semantics: Object.freeze({ ...result.semantics }), target: Object.freeze({ ...result.target, communityPackages: Object.freeze(result.target.communityPackages.map((item) => Object.freeze({ ...item }))), configuration: Object.freeze(result.target.configuration.map((item) => Object.freeze({ ...item }))) }), limits: Object.freeze({ schemaVersion: result.limits.schemaVersion, digest: result.limits.digest }) }); }\nfunction defaults(): ArtifactV2 { return Object.freeze({ profile: Object.freeze({ id: ADMITTED_PROFILE_V2.id, version: ADMITTED_PROFILE_V2.version }), ruleset: Object.freeze({ ...BUILTIN_RULESET_AUTHORITY_V2 }), semantics: Object.freeze({ ...BUILTIN_SEMANTICS_AUTHORITY_V2 }), target: TARGET, limits: Object.freeze({ schemaVersion: BUILTIN_LIMITS_AUTHORITY_V2.schemaVersion, digest: BUILTIN_LIMITS_AUTHORITY_V2.digest }) }); }\nfunction normalizeItem(raw: BatchItemV2, artifacts: ArtifactV2): CliItemV2 {\n let label: unknown;\n try { label = raw && typeof raw === 'object' ? raw.label : undefined; } catch { label = undefined; }\n const input = safeLabel(label);\n const result = readScannerResult(raw);\n if (result && sameIdentity(artifact(result), artifacts)) return Object.freeze({ input, ok: true as const, result });\n const code = errorCode(raw, 'TOOL_INVARIANT_FAILED');\n return Object.freeze({ input, ok: false as const, error: error(code) });\n}\nfunction errorCode(item: BatchItemV2, fallback: BatchErrorCodeV2): CliErrorCodeV2 {\n try {\n const code = item && typeof item === 'object' && item.error && typeof item.error.code === 'string' ? item.error.code : undefined;\n if (code && ERROR_CODES[code] === true) return code as CliErrorCodeV2;\n if (item?.result && typeof item.result === 'object' && item.result.ok === false && ERROR_CODES[item.result.code] === true) return item.result.code;\n if (item?.status === 'TIMEOUT') return 'SCAN_TIMEOUT';\n if (item?.status === 'CANCELLED') return 'SCAN_CANCELLED';\n } catch { /* fail closed */ }\n return fallback;\n}\nfunction error(code: CliErrorCodeV2): CliErrorV2 { const kind = code === 'SCAN_CANCELLED' ? 'CANCELLED' : code === 'SCAN_TIMEOUT' ? 'INCOMPLETE' : code === 'TOOL_INVARIANT_FAILED' || code === 'SERIALIZATION_FAILED' || code === 'OUTPUT_WRITE_FAILED' ? 'INTERNAL' : 'INPUT'; return Object.freeze({ kind, code, message: ERROR_MESSAGES[code] ?? ERROR_MESSAGES.TOOL_INVARIANT_FAILED }); }\nfunction sameIdentity(left: ArtifactV2, right: ArtifactV2): boolean { return canonicalizeJson(left) === canonicalizeJson(right); }\nfunction safeLabel(value: unknown): string {\n try {\n if (typeof value !== 'string' || value.length === 0 || value.length > 4096 || SECRET.test(value)) return 'input';\n const normalized = value.replaceAll('\\\\', '/');\n if (ABSOLUTE.test(normalized) || TRAVERSAL.test(normalized)) return 'input';\n const clean = normalized.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, (char) => `\\\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);\n return new TextEncoder().encode(clean).byteLength <= 16_384 ? clean : 'input';\n } catch { return 'input'; }\n}\nfunction summarize(items: readonly CliItemV2[]): SummaryV2 { let complete = 0; let degraded = 0; let indeterminate = 0; let inputErrors = 0; let internalErrors = 0; let cancelled = 0; let findings = 0; for (const item of items) { if (item.ok) { const status = item.result.analysis.status; if (status === 'COMPLETE') complete += 1; else if (status === 'DEGRADED') degraded += 1; else indeterminate += 1; findings += item.result.findings.length; } else if (item.error.kind === 'CANCELLED') cancelled += 1; else if (item.error.kind === 'INTERNAL') internalErrors += 1; else inputErrors += 1; } return Object.freeze({ total: items.length, complete, degraded, indeterminate, inputErrors, internalErrors, cancelled, findings }); }\nconst FINDING_SEVERITY: Readonly<Record<ProjectionOptionsV2['failOn'], number>> = Object.freeze({ CRITICAL: 5, HIGH: 4, MEDIUM: 3, LOW: 2, INFO: 1 });\nfunction invocation(options: ProjectionOptionsV2) {\n return Object.freeze({\n schema: 'v2' as const,\n format: options.format,\n profile: options.profile,\n failOn: options.failOn,\n requireComplete: options.requireComplete,\n concurrency: options.concurrency,\n allowUnsignedDevelopmentRules: options.allowUnsignedDevelopmentRules,\n sources: options.sources,\n });\n}\nfunction exitReason(state: BatchState, summary: SummaryV2, items: readonly CliItemV2[], options: ProjectionOptionsV2): CliEnvelopeV2['exitReason'] {\n if (!state.ok) return state.code === 'CANCELLED' ? 'CANCELLED' : 'USAGE';\n if (state.cancelled || summary.cancelled > 0) return 'CANCELLED';\n if (summary.internalErrors > 0) return 'INTERNAL';\n if (items.some((item) => item.ok && item.result.findings.some((finding) => typeof finding.severity === 'string' && FINDING_SEVERITY[finding.severity as ProjectionOptionsV2['failOn']] >= FINDING_SEVERITY[options.failOn]))) return 'FINDING_THRESHOLD';\n if (summary.degraded > 0 && options.requireComplete) return 'REQUIRE_COMPLETE';\n if (summary.indeterminate > 0 || summary.inputErrors > 0 || items.some((item) => !item.ok && item.error.kind === 'INCOMPLETE')) return 'ITEM_FAILURE';\n return 'UNDER_THRESHOLD';\n}\n", "import { canonicalizeJson } from '@hub/scanner-core/canonical-json';\nimport type { BatchResultV2 } from './batch-runner';\nimport { DEFAULT_PROJECTION_OPTIONS, projectBatchV2, type CliEnvelopeV2, type ProjectedBatchV2, type ProjectionOptionsV2 } from './json-output';\n\ntype HeaderV2 = Readonly<{ schemaVersion: 'n8n-scan-v2-ndjson'; type: 'header'; tool: CliEnvelopeV2['tool']; artifacts: CliEnvelopeV2['artifacts']; invocation: CliEnvelopeV2['invocation'] }>;\ntype ResultLineV2 = Readonly<{ schemaVersion: 'n8n-scan-v2-ndjson'; type: 'result'; item: ProjectedBatchV2['items'][number] }>;\ntype SummaryLineV2 = Readonly<{ schemaVersion: 'n8n-scan-v2-ndjson'; type: 'summary'; summary: CliEnvelopeV2['summary']; exitReason: CliEnvelopeV2['exitReason'] }>;\n\nexport function serializeNdjsonV2(batch: BatchResultV2, options: ProjectionOptionsV2 = { ...DEFAULT_PROJECTION_OPTIONS, format: 'ndjson' }): string {\n const projected = projectBatchV2(batch, options);\n const envelope = projected.envelope;\n const header: HeaderV2 = { schemaVersion: 'n8n-scan-v2-ndjson', type: 'header', tool: envelope.tool, artifacts: envelope.artifacts, invocation: envelope.invocation };\n const lines: string[] = [canonicalizeJson(header)];\n for (const item of projected.items) lines.push(canonicalizeJson({ schemaVersion: 'n8n-scan-v2-ndjson' as const, type: 'result' as const, item } satisfies ResultLineV2));\n const summary: SummaryLineV2 = { schemaVersion: 'n8n-scan-v2-ndjson', type: 'summary', summary: envelope.summary, exitReason: envelope.exitReason };\n lines.push(canonicalizeJson(summary));\n return `${lines.join('\\n')}\\n`;\n}\n", "import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { canonicalizeJson } from '../canonical-json';\nimport type { AnalysisDiagnosticCategory, AnalysisDiagnosticCode, FindingConfidence, ScanSeverity } from '../policy/policy';\n\nexport const SUPPORTED_SCANNER_VERSIONS = Object.freeze(['scanner-beta-1', '2.0.0'] as const);\nexport type SupportedScannerVersion = (typeof SUPPORTED_SCANNER_VERSIONS)[number];\nexport const SUPPORTED_SCANNER_VERSION_REGISTRY = SUPPORTED_SCANNER_VERSIONS;\nexport const PROJECTED_V2_PROFILES = Object.freeze([Object.freeze({ id: 'beta-default', version: '2.0.0' })] as const);\nexport const PROJECTED_PROFILE_REGISTRY = PROJECTED_V2_PROFILES;\nexport const PROJECTED_V2_PROFILE_REGISTRY = PROJECTED_V2_PROFILES;\n\nexport type V1RuleRegistryEntry = Readonly<{\n ruleId: string; revision: string; capabilityId: string; effect: 'SCORING' | 'REPORT_ONLY';\n severity: ScanSeverity; confidence: FindingConfidence; evidenceSchemaId: string; remediationId: string;\n}>;\nexport type V1RuleTemplate = Readonly<V1RuleRegistryEntry & {\n title: string; message: string; explanation: string; whyItMatters: string; possibleImpact: string;\n remediation: string; remediationSteps: readonly string[];\n}>;\nexport type V1EvidenceProjection = Readonly<{\n ruleId: string; evidenceSchemaId: string; properties: readonly { v1Key: string; factKind: string; factProperty: string; required: boolean }[];\n}>;\nexport type V1DiagnosticMapping = Readonly<{\n v2Code: string; v1Code: AnalysisDiagnosticCode; category: AnalysisDiagnosticCategory; status: 'DEGRADED' | 'INDETERMINATE';\n}>;\n\nconst entry = (ruleId: string, capabilityId: string, effect: 'SCORING' | 'REPORT_ONLY', severity: ScanSeverity, confidence: FindingConfidence, evidenceSchemaId: string): V1RuleRegistryEntry => Object.freeze({ ruleId, revision: '1', capabilityId, effect, severity, confidence, evidenceSchemaId, remediationId: 'r' });\nexport const V1_RULE_REGISTRY: readonly V1RuleRegistryEntry[] = Object.freeze([\n entry('N8N_EXECUTE_COMMAND', 'structural-policies', 'SCORING', 'CRITICAL', 'HIGH', 'v1.node-type'),\n entry('N8N_CODE_NODE', 'structural-policies', 'SCORING', 'LOW', 'HIGH', 'v1.node-type'),\n entry('RAW_AUTH_HEADER', 'structural-policies', 'SCORING', 'HIGH', 'MEDIUM', 'v1.auth-header'),\n entry('RAW_SECRET_INDICATOR', 'structural-policies', 'SCORING', 'HIGH', 'MEDIUM', 'v1.secret-indicator'),\n entry('UNAPPROVED_DOMAIN', 'structural-policies', 'SCORING', 'MEDIUM', 'HIGH', 'v1.domain'),\n entry('UNKNOWN_NODE_PACKAGE', 'structural-policies', 'SCORING', 'LOW', 'MEDIUM', 'v1.node-package'),\n entry('WEBHOOK_EXPOSURE', 'structural-policies', 'SCORING', 'MEDIUM', 'MEDIUM', 'v1.webhook-auth'),\n entry('JAVASCRIPT_DYNAMIC_EXECUTION', 'javascript-security', 'REPORT_ONLY', 'HIGH', 'HIGH', 'v1.code-indicator'),\n entry('PYTHON_DYNAMIC_EXECUTION', 'python-security', 'REPORT_ONLY', 'HIGH', 'MEDIUM', 'v1.code-indicator'),\n entry('TAINTED_COMMAND', 'taint-integrity', 'REPORT_ONLY', 'CRITICAL', 'MEDIUM', 'v1.taint'),\n entry('TAINTED_SQL_QUERY', 'taint-integrity', 'REPORT_ONLY', 'HIGH', 'MEDIUM', 'v1.taint'),\n entry('TAINTED_REQUEST_URL', 'taint-integrity', 'REPORT_ONLY', 'HIGH', 'MEDIUM', 'v1.taint'),\n entry('TAINTED_FILE_PATH', 'taint-integrity', 'REPORT_ONLY', 'HIGH', 'MEDIUM', 'v1.taint'),\n entry('TAINTED_CODE_INPUT', 'taint-integrity', 'REPORT_ONLY', 'HIGH', 'MEDIUM', 'v1.taint'),\n entry('TAINTED_REQUEST_HEADER', 'taint-integrity', 'REPORT_ONLY', 'MEDIUM', 'MEDIUM', 'v1.taint'),\n entry('TAINTED_AI_PROMPT', 'taint-integrity', 'REPORT_ONLY', 'MEDIUM', 'LOW', 'v1.taint'),\n entry('AI_AGENT_UNGATED_TOOL', 'agentic-control', 'REPORT_ONLY', 'MEDIUM', 'LOW', 'v1.agent-control'),\n]);\n\nconst copy = (base: V1RuleRegistryEntry, title: string, message: string, explanation: string, whyItMatters: string, possibleImpact: string, remediation: string, remediationSteps: readonly string[]): V1RuleTemplate => Object.freeze({ ...base, title, message, explanation, whyItMatters, possibleImpact, remediation, remediationSteps: Object.freeze([...remediationSteps]) });\nconst byId = (id: string): V1RuleRegistryEntry => { const value = V1_RULE_REGISTRY.find((item) => item.ruleId === id); if (!value) throw new Error(`Missing v1 rule ${id}`); return value; };\nconst review = 'Confirm the upstream data is validated against an allowlist before it reaches this node.';\nexport const V1_RULE_TEMPLATES: readonly V1RuleTemplate[] = Object.freeze([\n copy(byId('N8N_EXECUTE_COMMAND'), 'Execute Command node can run shell commands', 'This workflow can execute shell commands.', 'The Execute Command node allows the workflow to launch shell commands from the n8n runtime environment.', 'Shell command access can cross from workflow automation into the host or worker environment that runs n8n.', 'A malicious or compromised workflow path could lead to command execution, file access, lateral movement, or service disruption.', 'Remove the Execute Command node or isolate it behind strict approval.', ['Remove the Execute Command node when shell access is not explicitly required.', 'Replace shell logic with a narrow, reviewed integration or managed service call.', 'If it must remain, isolate the workflow runner and require manual approval before execution.']),\n copy(byId('N8N_CODE_NODE'), 'Custom code node requires security review', 'This workflow contains custom script execution.', 'Code and legacy Function nodes can transform data with arbitrary JavaScript inside the workflow runtime.', 'Custom code is harder to audit than declarative node configuration and may handle secrets or external data.', 'Unsafe code can leak data, mishandle credentials, or create behavior that reviewers cannot understand from node settings alone.', 'Review the code path, remove unnecessary scripting, and require approval.', ['Review the node source code for secret access, outbound requests, and unsafe parsing.', 'Move repeatable logic into a reviewed service or reusable library when possible.', 'Require approval for changes to custom code nodes in production workflows.']),\n copy(byId('RAW_AUTH_HEADER'), 'Raw Authorization header may expose credentials', 'This node configures a raw Authorization header.', 'The workflow parameters appear to define an Authorization header directly instead of using managed n8n credentials.', 'Raw credential material in node parameters is easier to copy, persist, log, or expose in exported workflow JSON.', 'API keys or bearer tokens can be leaked through workflow exports, scan history, logs, or support bundles.', 'Use n8n credentials or a managed secret reference instead of raw headers.', ['Move the secret into n8n credentials or an approved secret manager.', 'Rotate any token that has already been stored in raw workflow JSON.', 'Re-scan after replacing the raw header with a managed credential reference.']),\n copy(byId('RAW_SECRET_INDICATOR'), 'Workflow parameters contain raw secret material', 'This node contains a parameter that looks like a raw secret.', 'The scanner found a parameter key or value pattern commonly used for tokens, passwords, API keys, cookies, or credentials.', 'Raw secrets in workflow JSON can be exposed through exports, scan history, logs, backups, or support bundles.', 'An exposed token or password can allow unauthorized access to connected systems even if the workflow itself is not malicious.', 'Move the value into n8n credentials or an approved secret manager, then rotate any exposed secret.', ['Move the raw value into n8n credentials or an approved secret manager.', 'Rotate the secret if it has already been exported, shared, or stored in history.', 'Re-scan the workflow after replacing the raw value with a managed credential reference.']),\n copy(byId('UNAPPROVED_DOMAIN'), 'External domain is outside the approved allowlist', 'This workflow calls a domain outside the approved allowlist.', 'The node parameters contain a URL whose hostname is not present in the approved domain list supplied for this scan.', 'Unexpected outbound domains can indicate data exfiltration, shadow integrations, or environment drift.', 'Workflow data may be sent to an unreviewed third party or an endpoint that is not covered by enterprise controls.', 'Add the domain to the approved list or replace the external call.', ['Confirm the business owner and purpose for the external domain.', 'Add the domain to the approved list only after security and compliance review.', 'Replace the call if the destination is unnecessary or untrusted.']),\n copy(byId('UNKNOWN_NODE_PACKAGE'), 'Node package is not from an official n8n namespace', 'This workflow uses a community or custom node package.', 'The node type does not start with an official n8n package namespace, so it comes from a community or custom package.', 'Community and custom packages can add supply-chain, maintenance, and permission risks that differ from core nodes.', 'A vulnerable or unmaintained package could process sensitive workflow data or run unexpected code.', 'Review the package source, version, permissions, and maintenance status.', ['Verify the package source, maintainer, and version history.', 'Check whether the node requires credentials or broad runtime permissions.', 'Pin approved versions and remove packages that are not actively maintained.']),\n copy(byId('WEBHOOK_EXPOSURE'), 'Webhook trigger lacks clear authentication', 'This webhook does not show a clear authentication marker.', 'The webhook node appears to accept inbound requests without an explicit authentication mode in the workflow parameters.', 'Unauthenticated inbound endpoints can be abused for spam, data injection, or unexpected workflow execution.', 'External callers may trigger automations, create records, or send data into connected systems without authorization.', 'Require webhook authentication or place the endpoint behind trusted controls.', ['Enable webhook authentication in n8n when the endpoint is not intentionally public.', 'Place the endpoint behind a gateway, allowlist, or rate limiter for production use.', 'Monitor webhook usage for unexpected request volume or payloads.']),\n copy(byId('JAVASCRIPT_DYNAMIC_EXECUTION'), 'Custom JavaScript uses a dynamic execution primitive', 'Custom JavaScript uses a dynamic execution primitive.', 'The parser found an executable API that can construct or invoke code or access process, file, network, or child-process capabilities.', 'Dynamic execution can make code review less reliable and may expand workflow runtime capabilities.', 'A compromised or unsafe code path could execute unexpected JavaScript or access operating-system process controls.', 'Replace dynamic execution with reviewed static logic and narrow integrations.', ['Replace dynamic execution with reviewed static logic.', 'Keep process access outside workflow code and behind reviewed services.']),\n copy(byId('PYTHON_DYNAMIC_EXECUTION'), 'Custom Python uses a dynamic execution primitive', 'Custom Python uses a dynamic execution primitive.', 'The parser found a direct dynamic-code or shell-subprocess structure.', 'Dynamic execution makes code review less reliable and may expand workflow runtime capabilities.', 'Unsafe runtime configuration or untrusted input could lead to unexpected code or command execution.', 'Replace dynamic execution with reviewed static logic and avoid shell invocation from workflow code.', ['Replace dynamic execution with reviewed static logic.', 'Use reviewed services instead of shell invocation from workflow code.']),\n copy(byId('TAINTED_COMMAND'), 'Untrusted data reaches a shell command', 'This shell command is built from data that entered the workflow from outside.', 'A parameter interpreted as a shell command reads from a node carrying untrusted input, and the expression does not neutralize it for that use.', 'Shell commands assembled from external input are the shortest path from workflow automation to the host environment.', 'A caller who controls the upstream data may be able to influence which command runs.', 'Pass untrusted values as arguments to a fixed command rather than building the command string.', ['Build the command from a fixed template and pass data as separate arguments.', review]),\n copy(byId('TAINTED_SQL_QUERY'), 'Untrusted data reaches a SQL query', 'This SQL query is built from data that entered the workflow from outside.', 'A parameter interpreted as SQL reads from a node carrying untrusted input, and no wrapper call can make a value safe for SQL.', 'String-built SQL is the classic injection path, and encoding helpers do not close it.', 'A caller who controls the upstream data may be able to change what the query reads or writes.', 'Use query parameters instead of interpolating values into the statement.', [\"Replace interpolation with the node's parameterized query option.\", review]),\n copy(byId('TAINTED_REQUEST_URL'), 'Untrusted data reaches a request URL', 'This request URL is built from data that entered the workflow from outside.', 'A parameter interpreted as a request destination reads from a node carrying untrusted input. Percent-encoding a component does not constrain the host.', 'A caller who influences the destination can redirect the request to internal services the workflow can reach but they cannot.', 'The workflow may issue requests to unintended internal or external hosts on a caller\\'s behalf.', 'Fix the host and path, and allow untrusted data only in values the destination cannot change.', ['Pin the host and path, and pass untrusted values as query or body parameters.', review]),\n copy(byId('TAINTED_FILE_PATH'), 'Untrusted data reaches a filesystem path', 'This file path is built from data that entered the workflow from outside.', 'A parameter interpreted as a filesystem path reads from a node carrying untrusted input. Percent-encoding does not help, because the path is decoded before use.', 'Path segments from outside the workflow can escape the directory the automation was meant to touch.', 'The workflow may read or write files outside its intended location.', 'Derive the path from a fixed directory plus a validated identifier.', ['Join a fixed base directory with a validated identifier rather than an external string.', review]),\n copy(byId('TAINTED_CODE_INPUT'), 'Untrusted data is interpolated into custom code', 'This code parameter is built from data that entered the workflow from outside.', 'An expression interpolates untrusted data into a code parameter before the code node runs, so the executed source is not fixed at review time.', 'Code assembled at run time cannot be reviewed, and the review that did happen covered a different program.', 'The code that executes may differ from the code that was reviewed.', 'Read untrusted data inside the code from the incoming item instead of interpolating it into the source.', ['Reference the incoming item inside the code rather than building the source from an expression.', review]),\n copy(byId('TAINTED_REQUEST_HEADER'), 'Untrusted data reaches a request header', 'This request header value is built from data that entered the workflow from outside.', 'A parameter interpreted as a header value reads from a node carrying untrusted input without an encoding that removes control characters.', 'Header values carry authentication and routing meaning, and unencoded control characters can split a request.', 'A caller who controls the upstream data may be able to add or alter headers on the outbound request.', 'Encode the value, or send untrusted data in the body instead of a header.', ['Percent-encode the value before placing it in a header.', review]),\n copy(byId('TAINTED_AI_PROMPT'), 'Untrusted data reaches a model prompt', 'This model prompt is built from data that entered the workflow from outside.', 'A parameter interpreted as a prompt reads from a node carrying untrusted input, so instructions can arrive with the data.', 'A model cannot reliably separate instructions from content, and this agent may hold tools.', 'A caller who controls the upstream data may be able to influence what the model is asked to do.', 'Keep untrusted content in a clearly delimited field and constrain the tools the agent can reach.', ['Place untrusted content in a delimited input field separate from the instructions.', 'Limit which tools the agent can invoke.']),\n copy(byId('AI_AGENT_UNGATED_TOOL'), 'An AI agent can act on untrusted input without a human gate', 'This agent holds tools and receives data that entered the workflow from outside.', 'Untrusted data reaches this agent, the agent has connected tools it can invoke, and no wait or approval node stands on every execution path into it.', 'A model cannot reliably separate instructions from content, so whoever controls the incoming data has partial influence over which tools the agent decides to use.', 'The agent may take an action a caller asked for rather than one the workflow author intended.', 'Require human approval before the agent acts, or narrow the tools it can reach.', ['Place a wait or approval node on every path into the agent, not only on one branch.', 'Reduce the connected tools to the minimum the automation needs.', 'Keep untrusted content in a delimited field separate from the instructions.']),\n]);\nexport const V1_TEMPLATE_REGISTRY = V1_RULE_TEMPLATES;\n\nconst projection = (ruleId: string, evidenceSchemaId: string, properties: readonly { v1Key: string; factKind: string; factProperty: string; required: boolean }[]): V1EvidenceProjection => Object.freeze({ ruleId, evidenceSchemaId, properties: Object.freeze(properties.map((item) => Object.freeze({ ...item }))) });\nconst props = (factKind: string, names: readonly string[], optional: readonly string[] = []): readonly { v1Key: string; factKind: string; factProperty: string; required: boolean }[] => names.map((name) => ({ v1Key: name, factKind, factProperty: name, required: !optional.includes(name) }));\nexport const V1_EVIDENCE_PROJECTIONS: readonly V1EvidenceProjection[] = Object.freeze([\n projection('N8N_EXECUTE_COMMAND', 'v1.node-type', props('node.capability.v2', ['nodeType'])), projection('N8N_CODE_NODE', 'v1.node-type', props('node.capability.v2', ['nodeType'])),\n projection('RAW_AUTH_HEADER', 'v1.auth-header', props('node.configuration.v2', ['header', 'literalValue'])), projection('RAW_SECRET_INDICATOR', 'v1.secret-indicator', props('node.configuration.v2', ['parameterPath', 'secretKind', 'indicator', 'hasLiteralValue'])),\n projection('UNAPPROVED_DOMAIN', 'v1.domain', [{ v1Key: 'domain', factKind: 'destination.v2', factProperty: 'hostname', required: true }]), projection('UNKNOWN_NODE_PACKAGE', 'v1.node-package', props('node.capability.v2', ['nodeType', 'nodePackage'])), projection('WEBHOOK_EXPOSURE', 'v1.webhook-auth', props('ingress.v2', ['authentication'])),\n projection('JAVASCRIPT_DYNAMIC_EXECUTION', 'v1.code-indicator', props('code.indicator.v2', ['indicator', 'member', 'start', 'end'], ['member'])), projection('PYTHON_DYNAMIC_EXECUTION', 'v1.code-indicator', props('code.indicator.v2', ['indicator', 'member', 'start', 'end'], ['member'])),\n ...(['TAINTED_COMMAND', 'TAINTED_SQL_QUERY', 'TAINTED_REQUEST_URL', 'TAINTED_FILE_PATH', 'TAINTED_CODE_INPUT', 'TAINTED_REQUEST_HEADER', 'TAINTED_AI_PROMPT'] as const).map((ruleId) => projection(ruleId, 'v1.taint', props('dataflow.summary.v2', ['sink', 'parameterPath', 'referenceRoot', 'propertyPath', 'propertyPathComplete', 'taintLabels', 'sourceNodeId', 'sourceNodeName'], ['propertyPath', 'sourceNodeId', 'sourceNodeName']))),\n projection('AI_AGENT_UNGATED_TOOL', 'v1.agent-control', [...props('node.capability.v2', ['toolCount', 'contextCount']), ...props('dataflow.summary.v2', ['taintLabels', 'humanGatePresent', 'humanGateDominates'])]),\n]);\n\nconst V1_DIAGNOSTIC_CROSSWALK_ENTRIES = [\n { v2Code: 'SOURCE_SPAN_UNAVAILABLE', v1Code: 'SOURCE_SPAN_UNAVAILABLE', category: 'SOURCE', status: 'DEGRADED' }, { v2Code: 'DUPLICATE_FINDING_COLLAPSED', v1Code: 'DUPLICATE_FINDING_COLLAPSED', category: 'POLICY', status: 'DEGRADED' }, { v2Code: 'UNCLASSIFIED_CONNECTION_TYPE', v1Code: 'UNCLASSIFIED_CONNECTION_TYPE', category: 'GRAPH', status: 'DEGRADED' },\n { v2Code: 'DUPLICATE_METADATA_KEY', v1Code: 'DUPLICATE_JSON_KEY', category: 'PARSER', status: 'DEGRADED' }, { v2Code: 'DUPLICATE_SECURITY_KEY', v1Code: 'DUPLICATE_JSON_KEY', category: 'PARSER', status: 'INDETERMINATE' }, { v2Code: 'OPTIONAL_LIMIT_EXCEEDED', v1Code: 'ANALYSIS_LIMIT_EXCEEDED', category: 'LIMIT', status: 'DEGRADED' },\n { v2Code: 'REQUIRED_LIMIT_EXCEEDED', v1Code: 'ANALYSIS_LIMIT_EXCEEDED', category: 'LIMIT', status: 'INDETERMINATE' }, { v2Code: 'UNSUPPORTED_CODE_NODE_VARIANT', v1Code: 'UNSUPPORTED_CODE_NODE_VARIANT', category: 'PARSER', status: 'DEGRADED' },\n { v2Code: 'JAVASCRIPT_PARSE_FAILED', v1Code: 'JAVASCRIPT_PARSE_FAILED', category: 'PARSER', status: 'DEGRADED' }, { v2Code: 'JAVASCRIPT_SOURCE_UNAVAILABLE', v1Code: 'JAVASCRIPT_SOURCE_UNAVAILABLE', category: 'SOURCE', status: 'DEGRADED' }, { v2Code: 'PYTHON_SOURCE_UNAVAILABLE', v1Code: 'PYTHON_SOURCE_UNAVAILABLE', category: 'SOURCE', status: 'DEGRADED' },\n { v2Code: 'PYTHON_PARSE_FAILED', v1Code: 'PYTHON_PARSE_FAILED', category: 'PARSER', status: 'DEGRADED' }, { v2Code: 'PYTHON_PARSER_UNAVAILABLE', v1Code: 'PYTHON_PARSER_UNAVAILABLE', category: 'PARSER', status: 'DEGRADED' }, { v2Code: 'EXPRESSION_PARSE_FAILED', v1Code: 'EXPRESSION_PARSE_FAILED', category: 'PARSER', status: 'DEGRADED' },\n { v2Code: 'GRAPH_ENTRY_UNRESOLVED', v1Code: 'GRAPH_ANALYSIS_DEGRADED', category: 'GRAPH', status: 'DEGRADED' }, { v2Code: 'GRAPH_WORK_LIMIT_EXCEEDED', v1Code: 'ANALYSIS_LIMIT_EXCEEDED', category: 'LIMIT', status: 'DEGRADED' }, { v2Code: 'GRAPH_ANALYSIS_DEGRADED', v1Code: 'GRAPH_ANALYSIS_DEGRADED', category: 'GRAPH', status: 'DEGRADED' },\n { v2Code: 'MALFORMED_NODE_PARAMETERS', v1Code: 'MALFORMED_NODE_PARAMETERS', category: 'PARSER', status: 'INDETERMINATE' }, { v2Code: 'MALFORMED_CONNECTION_INDEX', v1Code: 'MALFORMED_CONNECTION_INDEX', category: 'GRAPH', status: 'INDETERMINATE' }, { v2Code: 'POLICY_EXECUTION_FAILED', v1Code: 'POLICY_EXECUTION_FAILED', category: 'POLICY', status: 'INDETERMINATE' },\n { v2Code: 'REQUIRED_CAPABILITY_FAILED', v1Code: 'POLICY_EXECUTION_FAILED', category: 'POLICY', status: 'INDETERMINATE' }, { v2Code: 'DEPENDENCY_UNAVAILABLE', v1Code: 'POLICY_EXECUTION_FAILED', category: 'POLICY', status: 'INDETERMINATE' }, { v2Code: 'UNKNOWN_SCORING_RULE', v1Code: 'POLICY_EXECUTION_FAILED', category: 'POLICY', status: 'INDETERMINATE' },\n { v2Code: 'SEMANTIC_CATALOGUE_MISS', v1Code: 'POLICY_EXECUTION_FAILED', category: 'POLICY', status: 'INDETERMINATE' }, { v2Code: 'GENERIC_NODE_UNMODELED_CAPABILITY', v1Code: 'POLICY_EXECUTION_FAILED', category: 'POLICY', status: 'DEGRADED' }, { v2Code: 'UNKNOWN_REPORT_ONLY_RULE', v1Code: 'POLICY_EXECUTION_FAILED', category: 'POLICY', status: 'DEGRADED' },\n { v2Code: 'COMPATIBILITY_PROJECTION_LOSS', v1Code: 'POLICY_EXECUTION_FAILED', category: 'POLICY', status: 'INDETERMINATE' },\n { v2Code: 'REQUIRED_STAGE_FAILURE', v1Code: 'REQUIRED_STAGE_FAILURE', category: 'POLICY', status: 'INDETERMINATE' },\n] as const satisfies readonly V1DiagnosticMapping[];\nexport const V1_DIAGNOSTIC_CROSSWALK: readonly V1DiagnosticMapping[] = Object.freeze(V1_DIAGNOSTIC_CROSSWALK_ENTRIES.map((item) => Object.freeze(item)));\n\nexport const V1_SUMMARY_TEMPLATES = Object.freeze([\n Object.freeze({ field: 'headline', template: 'registered-risk-headline-v1' }), Object.freeze({ field: 'verdict', template: 'registered-risk-verdict-v1' }),\n Object.freeze({ field: 'plainLanguageOverview', template: 'registered-workflow-overview-v1' }), Object.freeze({ field: 'riskNarrative', template: 'registered-risk-narrative-v1' }),\n] as const);\nexport const V1_REMEDIATION_TEMPLATES = Object.freeze([Object.freeze({ remediationId: 'r', summary: 'Rule-specific registered remediation', steps: Object.freeze([] as string[]) })] as const);\n\nconst digestBody = Object.freeze({ schemaVersion: 'scanner-v1-templates-v2' as const, version: '2.0.0', rules: V1_RULE_REGISTRY, templates: V1_RULE_TEMPLATES, evidence: V1_EVIDENCE_PROJECTIONS, diagnostics: V1_DIAGNOSTIC_CROSSWALK, summary: V1_SUMMARY_TEMPLATES, remediation: V1_REMEDIATION_TEMPLATES });\nexport const V1_REGISTRY_DIGEST = bytesToHex(sha256(new TextEncoder().encode(canonicalizeJson(digestBody))));\nexport const V1_REGISTRY_VERSION = '2.0.0' as const;\nexport const V1_RULE_IDS = Object.freeze(V1_RULE_REGISTRY.map((item) => item.ruleId));\nexport const V1_REGISTRY = Object.freeze({ schemaVersion: digestBody.schemaVersion, version: V1_REGISTRY_VERSION, rules: V1_RULE_REGISTRY, ruleTemplates: V1_RULE_TEMPLATES, remediationTemplates: V1_REMEDIATION_TEMPLATES, summaryTemplates: V1_SUMMARY_TEMPLATES, evidenceProjections: V1_EVIDENCE_PROJECTIONS, diagnosticCrosswalk: V1_DIAGNOSTIC_CROSSWALK, digest: V1_REGISTRY_DIGEST });\n", "import { validateScannerResultV2, type ScannerResultV2 } from '@hub/contracts/scanner-v2-result';\nimport type { SourceSpanV2, SubjectV2 } from '@hub/contracts/scanner-v2-source';\nimport type { BatchSarifEnvelopeV2, BatchSarifInputV2, SarifV2Limits } from './output';\n\nexport type Bounds = { rules: number; results: number; notifications: number; taxonomies: number; taxa: number; tags: number; flows: number; steps: number };\nexport type NotifItem = { code: string; level: 'warning' | 'error'; location?: Record<string, unknown>; locKey: string; id?: string; label?: string };\nexport type BatchId = {\n engineId: string; engineVersion: string; engineBuildDigest: string;\n profileId: string; profileVersion: string;\n rulesetId: string; rulesetVersion: string; rulesetDigest: string; rulesetSig: string;\n semanticsId: string; semanticsVersion: string; semanticsDigest: string;\n targetContextDigest: string; targetEdition: string; targetDeployment: string; targetRole: string; targetTaskRunner: string;\n limitsSchemaVersion: string; limitsDigest: string;\n};\nexport type InputIdentity = { rawUri: unknown; label: string };\n\nexport const FALLBACK: Bounds = { rules: 1024, results: 5000, notifications: 256, taxonomies: 8, taxa: 512, tags: 32, flows: 512, steps: 100 };\nexport const SEV_ORDER: Record<string, number> = { CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3, INFO: 4 };\nexport const LEVELS: Record<string, 'error' | 'warning' | 'note'> = { CRITICAL: 'error', HIGH: 'error', MEDIUM: 'warning', LOW: 'note', INFO: 'note' };\nexport const ALLOWED_ERRORS = new Set<string>(['UTF8_DECODING_FAILED', 'INVALID_JSON', 'MALFORMED_WORKFLOW', 'WORKFLOW_TOO_LARGE', 'WORKFLOW_TOO_COMPLEX', 'INPUT_READ_FAILED', 'SCAN_TIMEOUT', 'SCAN_CANCELLED', 'INVALID_CONFIG', 'UNKNOWN_CONFIGURATION_KEY', 'PROFILE_NOT_ADMITTED', 'SEMANTIC_CATALOGUE_INVALID', 'SEMANTIC_CATALOGUE_AMBIGUOUS', 'RULE_PACK_INVALID', 'RULE_PACK_UNTRUSTED', 'TOOL_INVARIANT_FAILED', 'SERIALIZATION_FAILED', 'OUTPUT_WRITE_FAILED']);\nexport const prop = (v: unknown, k: string): unknown => {\n if (v === null || typeof v !== 'object' || Array.isArray(v) || !Object.prototype.hasOwnProperty.call(v, k)) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(v, k);\n return descriptor && 'value' in descriptor ? descriptor.value : undefined;\n};\nexport const inv = (): never => { throw new TypeError('Invalid SARIF input'); };\n\nfunction closed(value: unknown, allowed: readonly string[]): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value) || (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) || Object.getOwnPropertySymbols(value).length) return inv();\n const out = value as Record<string, unknown>;\n for (const key of Object.getOwnPropertyNames(out)) {\n const descriptor = Object.getOwnPropertyDescriptor(out, key);\n if (!descriptor || !('value' in descriptor) || !descriptor.enumerable || !allowed.includes(key)) return inv();\n }\n return out;\n}\nfunction dense(value: unknown): readonly unknown[] {\n if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype || Object.getOwnPropertySymbols(value).length) return inv();\n const names = Object.getOwnPropertyNames(value);\n if (names.length !== value.length + 1) return inv();\n for (const name of names) {\n if (name === 'length') continue;\n if (!/^(?:0|[1-9]\\d*)$/.test(name) || Number(name) >= value.length) return inv();\n const descriptor = Object.getOwnPropertyDescriptor(value, name);\n if (!descriptor || !('value' in descriptor) || !descriptor.enumerable) return inv();\n }\n return value as readonly unknown[];\n}\nfunction validateLimitObject(value: unknown): SarifV2Limits | undefined {\n if (value === undefined) return undefined;\n const object = closed(value, ['maxRules', 'maxResults', 'maxNotifications', 'maxTaxonomies', 'maxTaxa', 'maxTags', 'maxFlows', 'maxTraceSteps']);\n for (const key of Object.keys(object)) if (!Number.isSafeInteger(object[key]) || (object[key] as number) < 0) return inv();\n return object as SarifV2Limits;\n}\n\nexport function checkResult(r: unknown): ScannerResultV2 {\n const v = validateScannerResultV2(r);\n if (!v.ok) return inv();\n return v.result;\n}\nexport function inputIdentity(value: unknown): InputIdentity {\n const item = closed(value, ['input', 'uri', 'label', 'result', 'status', 'ok', 'error']);\n const nested = prop(item, 'input');\n const nestedObject = nested === undefined ? undefined : closed(nested, ['label', 'uri']);\n const uri = typeof prop(item, 'uri') === 'string' ? prop(item, 'uri') : prop(nestedObject, 'uri');\n const labelValue = typeof prop(item, 'label') === 'string' ? prop(item, 'label') : prop(nestedObject, 'label');\n const label = typeof labelValue === 'string' ? labelValue : typeof uri === 'string' ? uri : '';\n return { rawUri: uri ?? label, label };\n}\nexport function extractItems(input: BatchSarifInputV2): { items: readonly unknown[]; repoRoot?: string; selRoot?: string; limits?: SarifV2Limits } {\n if (!input || typeof input !== 'object') return inv();\n if (Array.isArray(input)) return { items: dense(input) };\n const env = closed(input, ['items', 'results', 'input', 'result', 'repositoryRoot', 'selectionRoot', 'limits']) as BatchSarifEnvelopeV2;\n const limits = validateLimitObject(env.limits);\n if (env.repositoryRoot !== undefined && !safePath(env.repositoryRoot)) return inv();\n if (env.selectionRoot !== undefined && !safePath(env.selectionRoot)) return inv();\n const nested = env.input === undefined ? undefined : inputIdentity({ input: env.input });\n const items = env.items !== undefined ? dense(env.items) : env.results !== undefined ? dense(env.results) : (env.result && nested) ? [{ label: nested.label, uri: nested.rawUri, result: env.result, status: 'COMPLETED' }] : undefined;\n if (!items) return inv();\n return { items: items as readonly unknown[], repoRoot: env.repositoryRoot, selRoot: env.selectionRoot, limits };\n}\n\nexport function safePath(v: unknown): v is string {\n return typeof v === 'string' && v.length > 0 && v.length <= 4096 && !v.includes('\\0') && !/[\\u0000-\\u001f\\u007f\\ud800-\\udfff]/.test(v) && !/^(?:[A-Za-z]:|[\\\\/]{1,2}|[A-Za-z][A-Za-z0-9+.-]*:)/.test(v) && !/(?:^|[\\\\/])\\.\\.(?:[\\\\/]|$)/.test(v) && !/[?#]/.test(v);\n}\nexport function safeUri(raw: unknown, repoRoot?: string, selRoot?: string): string | undefined {\n if (!safePath(raw)) return undefined;\n try {\n let p = raw.replaceAll('\\\\', '/').split('/').filter((part) => part && part !== '.').join('/');\n const roots = [repoRoot, selRoot].filter((r): r is string => r !== undefined);\n let matched = roots.length === 0;\n for (const root of roots) {\n if (!safePath(root)) return undefined;\n const base = root.replaceAll('\\\\', '/').split('/').filter((part) => part && part !== '.').join('/');\n if (!base) { matched = true; continue; }\n if (p === base) return undefined;\n if (p.startsWith(`${base}/`)) { p = p.slice(base.length + 1); matched = true; }\n }\n if (!matched) return undefined;\n const parts = p.split('/');\n return parts.length && !parts.some((part) => !part || part === '.' || part === '..' || /%2e/i.test(part)) ? parts.map(encodeURIComponent).join('/') : undefined;\n } catch { return undefined; }\n}\n\nexport function readPos(v: unknown): SourceSpanV2['start'] | undefined {\n if (!v || typeof v !== 'object') return undefined;\n const l = prop(v, 'line'); const c = prop(v, 'column'); const so = prop(v, 'utf16Offset'); const bo = prop(v, 'utf8ByteOffset');\n return (!Number.isSafeInteger(l) || (l as number) < 1 || !Number.isSafeInteger(c) || (c as number) < 1 || !Number.isSafeInteger(so) || (so as number) < 0 || !Number.isSafeInteger(bo) || (bo as number) < 0) ? undefined : { line: l as number, column: c as number, utf16Offset: so as number, utf8ByteOffset: bo as number };\n}\nexport function readSpan(source: unknown): SourceSpanV2 | undefined {\n const span = prop(source, 'span');\n if (!span || typeof span !== 'object' || prop(span, 'verified') === false || prop(span, 'status') === 'UNVERIFIED') return undefined;\n const st = readPos(prop(span, 'start')); const en = readPos(prop(span, 'end'));\n return (!st || !en || en.utf16Offset <= st.utf16Offset || en.utf8ByteOffset <= st.utf8ByteOffset || en.line < st.line || (en.line === st.line && en.column <= st.column)) ? undefined : { start: st, end: en };\n}\nexport function subjectKey(s: SubjectV2): string {\n if (s.kind === 'WORKFLOW') return 'WORKFLOW';\n if (s.kind === 'NODE') return `NODE:${s.node.identityDigest}`;\n if (s.kind === 'SOURCE') return `SOURCE:${s.source.astNodeId}`;\n return `EDGE:${s.edge.ordinal}:${s.edge.source.astNodeId}:${s.edge.connectionType}`;\n}\nexport function subjectSpan(subj: SubjectV2): SourceSpanV2 | undefined {\n const owner = subj.kind === 'NODE' ? subj.node : subj.kind === 'EDGE' ? subj.edge : subj.kind === 'SOURCE' ? subj : undefined;\n return owner && prop(owner, 'source') ? readSpan(prop(owner, 'source')) : undefined;\n}\nexport function physical(uri: string, s: SourceSpanV2): Record<string, unknown> {\n const charLength = s.end.utf16Offset - s.start.utf16Offset;\n return { physicalLocation: { artifactLocation: { uri }, region: { startLine: s.start.line, startColumn: s.start.column, endLine: s.end.line, endColumn: s.end.column, charOffset: s.start.utf16Offset, charLength } } };\n}\nexport function freeze<T>(v: T, seen = new WeakSet<object>()): T {\n if (v && typeof v === 'object' && !seen.has(v as object)) { seen.add(v as object); for (const k of Object.getOwnPropertyNames(v)) freeze((v as Record<string, unknown>)[k], seen); Object.freeze(v); }\n return v;\n}\nexport function sameId(a: BatchId, b: BatchId): boolean {\n return a.engineId === b.engineId && a.engineVersion === b.engineVersion && a.engineBuildDigest === b.engineBuildDigest && a.profileId === b.profileId && a.profileVersion === b.profileVersion && a.rulesetId === b.rulesetId && a.rulesetVersion === b.rulesetVersion && a.rulesetDigest === b.rulesetDigest && a.rulesetSig === b.rulesetSig && a.semanticsId === b.semanticsId && a.semanticsVersion === b.semanticsVersion && a.semanticsDigest === b.semanticsDigest && a.targetContextDigest === b.targetContextDigest && a.targetEdition === b.targetEdition && a.targetDeployment === b.targetDeployment && a.targetRole === b.targetRole && a.targetTaskRunner === b.targetTaskRunner && a.limitsSchemaVersion === b.limitsSchemaVersion && a.limitsDigest === b.limitsDigest;\n}\n", "/**\n * Sole v2 SARIF document authority: this module assembles the log and `helpers.ts` declares\n * its bounds/severity tables. It adapts core's authorities \u2014 `report/sarif-tags`,\n * `diagnostics/registry` and `compat/v1-registry` \u2014 rather than restating them, and no second\n * document builder may exist (core's unwired `report/sarif-v2.ts` was deleted as that duplicate).\n */\nimport type { FindingV2, SafeFactV2, TraceV2 } from '@hub/contracts/scanner-v2-evidence';\nimport type { ScannerResultV2 } from '@hub/contracts/scanner-v2-result';\nimport { V1_EVIDENCE_PROJECTIONS, V1_RULE_REGISTRY, V1_RULE_TEMPLATES } from '../../compat/v1-registry';\nimport { DIAGNOSTIC_CODES_V2 } from '../../diagnostics/registry';\nimport { sarifHelpUriFor, sarifTagsFor } from '../sarif-tags';\nimport { compareCanonicalStrings } from '@hub/contracts/stable-order';\nimport {\n ALLOWED_ERRORS, checkResult, extractItems, FALLBACK, freeze, inputIdentity, inv, LEVELS, physical, prop, readSpan, safeUri,\n sameId, SEV_ORDER, subjectKey, subjectSpan, type BatchId, type Bounds, type NotifItem,\n} from './helpers';\n\nexport type SarifLog = Readonly<{ version: '2.1.0'; $schema: string; runs: readonly SarifRun[] }>;\nexport type SarifRun = Readonly<{ tool: { driver: Record<string, unknown> }; results: readonly Record<string, unknown>[]; invocations: readonly Record<string, unknown>[]; taxonomies?: readonly Record<string, unknown>[] }>;\nexport type SarifV2Limits = Readonly<{ maxRules?: number; maxResults?: number; maxNotifications?: number; maxTaxonomies?: number; maxTaxa?: number; maxTags?: number; maxFlows?: number; maxTraceSteps?: number }>;\nexport type BatchSarifEnvelopeV2 = Readonly<{ items?: readonly unknown[]; results?: readonly unknown[]; input?: Readonly<{ label: string; uri?: string }>; result?: ScannerResultV2; repositoryRoot?: string; selectionRoot?: string; limits?: SarifV2Limits }>;\nexport type BatchSarifInputV2 = BatchSarifEnvelopeV2 | readonly unknown[];\n\ntype CollectedFinding = { finding: FindingV2; uri?: string; traces: Map<string, TraceV2>; stepsLimit?: number };\nconst diagCodes = new Set<string>(DIAGNOSTIC_CODES_V2);\nconst templates = new Map(V1_RULE_TEMPLATES.map((item) => [item.ruleId, item]));\nconst registry = new Map(V1_RULE_REGISTRY.map((item) => [item.ruleId, item]));\nconst configurationRules = new Set(['RAW_AUTH_HEADER', 'RAW_SECRET_INDICATOR', 'UNAPPROVED_DOMAIN', 'UNKNOWN_NODE_PACKAGE', 'WEBHOOK_EXPOSURE']);\n\nfunction evidenceClass(ruleId: string): FindingV2['evidenceClass'] {\n if (ruleId.startsWith('TAINTED_')) return 'POTENTIAL_DATAFLOW';\n if (ruleId === 'JAVASCRIPT_DYNAMIC_EXECUTION' || ruleId === 'PYTHON_DYNAMIC_EXECUTION') return 'SUSPICIOUS_SYNTAX';\n if (configurationRules.has(ruleId)) return 'CONFIGURATION';\n return 'CAPABILITY';\n}\nfunction checkFindingAuthority(finding: FindingV2, facts: ReadonlyMap<string, SafeFactV2>): void {\n const rule = registry.get(finding.ruleId); const template = templates.get(finding.ruleId);\n const projection = V1_EVIDENCE_PROJECTIONS.find((item) => item.ruleId === finding.ruleId);\n if (!rule || !template || !projection) throw new TypeError('Invalid SARIF input');\n if (projection.evidenceSchemaId !== rule.evidenceSchemaId\n || finding.ruleRevision !== rule.revision || finding.effect !== rule.effect || finding.severity !== rule.severity\n || finding.confidence !== rule.confidence || finding.remediationId !== rule.remediationId || finding.evidenceClass !== evidenceClass(finding.ruleId)) inv();\n if (!finding.factRefs.length) return;\n const referenced = finding.factRefs.map((ref) => facts.get(ref));\n if (referenced.some((fact) => !fact || !projection.properties.some((item) => item.factKind === fact.kind))) inv();\n for (const property of projection.properties) {\n const matches = referenced.filter((fact) => fact?.kind === property.factKind && Object.prototype.hasOwnProperty.call(fact.properties, property.factProperty));\n if (matches.length > 1 || property.required && matches.length !== 1) inv();\n }\n}\nconst getLimit = (explicit: number | undefined, aggregate: number, fallback: number, seen: boolean): number => {\n const base = seen ? aggregate : fallback;\n return explicit === undefined ? base : Math.min(explicit, base);\n};\n\nexport function buildBatchSarifV2(input: BatchSarifInputV2): SarifLog {\n const { items, repoRoot, selRoot, limits: inputLimits } = extractItems(input);\n const rawNotifs: NotifItem[] = []; const collected: CollectedFinding[] = []; const unknownRules = new Set<string>();\n let spanLoss = false; let invocationFailed = false; let identity: BatchId | undefined; let limitExceeded = false;\n let findingsBudget = 0; let findingsBudgetSeen = false; let diagnosticsBudget = 0; let diagnosticsBudgetSeen = false;\n let taxaBudget = 0; let taxaBudgetSeen = false; let flowBudget = 0; let flowBudgetSeen = false;\n for (const item of items) {\n const inputIdentityValue = inputIdentity(item); const label = inputIdentityValue.label; const uri = safeUri(inputIdentityValue.rawUri, repoRoot, selRoot);\n const rawResult = prop(item, 'result'); const resultCandidate = rawResult && typeof rawResult === 'object' && prop(rawResult, 'result') ? prop(rawResult, 'result') : rawResult;\n const completed = prop(item, 'status') === 'COMPLETED' || prop(item, 'ok') === true || (resultCandidate && prop(item, 'status') === undefined && prop(item, 'ok') === undefined);\n if (completed && resultCandidate) {\n const result = checkResult(resultCandidate); const current: BatchId = {\n engineId: result.engine.id, engineVersion: result.engine.version, engineBuildDigest: result.engine.buildDigest,\n profileId: result.profile.id, profileVersion: result.profile.version, rulesetId: result.ruleset.id, rulesetVersion: result.ruleset.version,\n rulesetDigest: result.ruleset.digest, rulesetSig: result.ruleset.signatureStatus, semanticsId: result.semantics.id, semanticsVersion: result.semantics.version,\n semanticsDigest: result.semantics.digest, targetContextDigest: result.target.contextDigest, targetEdition: result.target.edition,\n targetDeployment: result.target.deployment, targetRole: result.target.role, targetTaskRunner: result.target.taskRunner,\n limitsSchemaVersion: result.limits.schemaVersion, limitsDigest: result.limits.digest,\n };\n if (!identity) identity = current; else if (!sameId(identity, current)) inv();\n const facts = new Map<string, SafeFactV2>(result.facts.map((fact) => [fact.factId, fact])); const traces = new Map<string, TraceV2>(result.traces.map((trace) => [trace.traceId, trace])); let stepsLimit: number | undefined;\n for (const usage of result.limits.usage) {\n if (usage.omitted > 0) limitExceeded = true;\n if (usage.id === 'maxFindings') { findingsBudget += usage.maximum; findingsBudgetSeen = true; }\n if (usage.id === 'maxDiagnostics') { diagnosticsBudget += usage.maximum; diagnosticsBudgetSeen = true; }\n if (usage.id === 'maxTaxa') { taxaBudget += usage.maximum; taxaBudgetSeen = true; }\n if (usage.id === 'maxFlows') { flowBudget += usage.maximum; flowBudgetSeen = true; }\n if (usage.id === 'maxTraceStepsPerFinding') stepsLimit = usage.maximum;\n }\n for (const finding of result.findings) {\n if (registry.has(finding.ruleId)) checkFindingAuthority(finding, facts); else unknownRules.add(finding.effect === 'SCORING' ? 'UNKNOWN_SCORING_RULE' : 'UNKNOWN_REPORT_ONLY_RULE');\n collected.push({ finding, uri, traces, stepsLimit });\n }\n for (const diagnostic of result.analysis.diagnostics) {\n if (!diagCodes.has(diagnostic.code)) continue;\n const locationSpan = readSpan(diagnostic.location); const location = uri && locationSpan ? physical(uri, locationSpan) : undefined;\n const key = location ? `${uri}:${locationSpan!.start.line}:${locationSpan!.start.column}:${locationSpan!.end.line}:${locationSpan!.end.column}` : '';\n rawNotifs.push({ code: diagnostic.code, level: diagnostic.aggregateEffect === 'INDETERMINATE' ? 'error' : 'warning', location, locKey: key, id: diagnostic.id, label });\n }\n } else {\n invocationFailed = true;\n const rawCode = prop(prop(item, 'error'), 'code') ?? (prop(item, 'status') === 'TIMEOUT' ? 'SCAN_TIMEOUT' : prop(item, 'status') === 'CANCELLED' ? 'SCAN_CANCELLED' : 'TOOL_INVARIANT_FAILED');\n const code = typeof rawCode === 'string' && ALLOWED_ERRORS.has(rawCode) ? rawCode : 'TOOL_INVARIANT_FAILED';\n rawNotifs.push({ code, level: code === 'SCAN_TIMEOUT' || code === 'SCAN_CANCELLED' ? 'warning' : 'error', location: uri ? { physicalLocation: { artifactLocation: { uri } } } : undefined, locKey: uri ?? '', label });\n }\n }\n for (const code of unknownRules) rawNotifs.push({ code, level: code === 'UNKNOWN_SCORING_RULE' ? 'error' : 'warning', locKey: '' });\n const bounds: Bounds = {\n rules: getLimit(inputLimits?.maxRules, 0, FALLBACK.rules, false), results: getLimit(inputLimits?.maxResults, findingsBudget, FALLBACK.results, findingsBudgetSeen),\n notifications: getLimit(inputLimits?.maxNotifications, diagnosticsBudget, FALLBACK.notifications, diagnosticsBudgetSeen), taxonomies: getLimit(inputLimits?.maxTaxonomies, 0, FALLBACK.taxonomies, false),\n taxa: getLimit(inputLimits?.maxTaxa, taxaBudget, FALLBACK.taxa, taxaBudgetSeen), tags: getLimit(inputLimits?.maxTags, 0, FALLBACK.tags, false),\n flows: getLimit(inputLimits?.maxFlows, flowBudget, FALLBACK.flows, flowBudgetSeen), steps: inputLimits?.maxTraceSteps ?? FALLBACK.steps,\n };\n const sorted = [...collected].sort((a, b) => (SEV_ORDER[a.finding.severity] ?? 9) - (SEV_ORDER[b.finding.severity] ?? 9) || compareCanonicalStrings(a.finding.ruleId, b.finding.ruleId) || compareCanonicalStrings(subjectKey(a.finding.subject), subjectKey(b.finding.subject)) || compareCanonicalStrings(a.finding.findingId, b.finding.findingId) || compareCanonicalStrings(a.uri ?? '', b.uri ?? ''));\n const admitted = sorted.filter((item) => registry.has(item.finding.ruleId)); const selected = admitted.slice(0, bounds.results); if (selected.length < admitted.length) limitExceeded = true;\n const ruleIdsAll = [...new Set(selected.map((item) => item.finding.ruleId))].sort(compareCanonicalStrings); if (ruleIdsAll.length > bounds.rules) limitExceeded = true;\n const ruleIds = ruleIdsAll.slice(0, bounds.rules); const admittedRules = new Set(ruleIds); const active = selected.filter((item) => admittedRules.has(item.finding.ruleId)); if (active.length < selected.length) limitExceeded = true;\n\n const tagsByRule = new Map<string, readonly string[]>(); const admittedTags = new Set<string>();\n const rules = ruleIds.map((id) => { const template = templates.get(id)!; const allTags = [...new Set(sarifTagsFor(id) ?? [])].filter((tag) => /^external\\/cwe\\/cwe-\\d{3}$/.test(tag) || /^owasp-agentic\\/[a-z0-9-]+$/.test(tag)).sort(compareCanonicalStrings); if (allTags.length > bounds.tags) limitExceeded = true; const tags = allTags.slice(0, bounds.tags); tags.forEach((tag) => admittedTags.add(tag)); tagsByRule.set(id, tags); return { id, helpUri: sarifHelpUriFor(id), shortDescription: { text: template.title }, fullDescription: { text: template.explanation }, help: { text: template.remediation }, ...(tags.length ? { properties: { tags } } : {}) }; });\n const taxonomies: Record<string, unknown>[] = []; const taxRefs = new Set<string>(); const cwe = [...admittedTags].filter((tag) => tag.startsWith('external/cwe/')).sort(compareCanonicalStrings); const owasp = [...admittedTags].filter((tag) => tag.startsWith('owasp-agentic/')).sort(compareCanonicalStrings);\n const cweTags = cwe.slice(0, bounds.taxa); const owaspTags = owasp.slice(0, Math.max(0, bounds.taxa - cweTags.length)); if (cweTags.length < cwe.length || owaspTags.length < owasp.length) limitExceeded = true;\n if (cweTags.length && taxonomies.length < bounds.taxonomies) { taxonomies.push({ name: 'CWE', taxa: cweTags.map((id) => ({ id })) }); cweTags.forEach((id) => taxRefs.add(`CWE\\0${id}`)); } else if (cweTags.length) limitExceeded = true;\n if (owaspTags.length && taxonomies.length < bounds.taxonomies) { taxonomies.push({ name: 'OWASP Agentic', taxa: owaspTags.map((id) => ({ id })) }); owaspTags.forEach((id) => taxRefs.add(`OWASP Agentic\\0${id}`)); } else if (owaspTags.length) limitExceeded = true;\n let flowCount = 0; let taxaCount = 0;\n const results = active.map(({ finding, uri, traces, stepsLimit }) => {\n const span = subjectSpan(finding.subject); const location = uri && span ? physical(uri, span) : undefined; if (!location) spanLoss = true; const flows: Record<string, unknown>[] = [];\n for (const traceId of [...finding.traceRefs].sort(compareCanonicalStrings)) {\n const trace = traces.get(traceId); const steps = trace ? [...trace.steps].sort((a, b) => a.ordinal - b.ordinal) : []; const spans = steps.map((step) => subjectSpan(step.subject));\n const allowedSteps = Math.min(bounds.steps, stepsLimit ?? FALLBACK.steps);\n if (!trace || !steps.length || !uri || spans.some((value) => !value)) { spanLoss = true; continue; }\n if (steps.length > allowedSteps) { spanLoss = true; limitExceeded = true; continue; }\n if (flowCount >= bounds.flows) { limitExceeded = true; continue; }\n flows.push({ threadFlows: [{ locations: spans.map((value) => ({ location: physical(uri, value!) })) }] }); flowCount += 1;\n }\n const template = templates.get(finding.ruleId)!; const available = Math.max(0, bounds.taxa - taxaCount); const allTaxa = (tagsByRule.get(finding.ruleId) ?? []).filter((id) => taxRefs.has(`${id.startsWith('external/cwe/') ? 'CWE' : 'OWASP Agentic'}\\0${id}`)); const taxa = allTaxa.slice(0, available).map((id) => ({ toolComponent: { name: id.startsWith('external/cwe/') ? 'CWE' : 'OWASP Agentic' }, id })); if (taxa.length < allTaxa.length) limitExceeded = true; taxaCount += taxa.length;\n return { ruleId: finding.ruleId, level: LEVELS[finding.severity], message: { text: template.message }, partialFingerprints: { secureflowFindingId: finding.findingId }, properties: { severity: finding.severity, confidence: finding.confidence, effect: finding.effect, evidenceClass: finding.evidenceClass, conclusion: finding.conclusion, applicability: finding.applicability, capabilityId: registry.get(finding.ruleId)!.capabilityId }, ...(taxa.length ? { taxa } : {}), ...(location ? { locations: [location] } : {}), ...(flows.length ? { codeFlows: flows } : {}) };\n });\n if (spanLoss) rawNotifs.push({ code: 'SOURCE_SPAN_UNAVAILABLE', level: 'warning', locKey: '' });\n if (rawNotifs.length > bounds.notifications) limitExceeded = true;\n if (limitExceeded && !rawNotifs.some((item) => item.code === 'OPTIONAL_LIMIT_EXCEEDED')) rawNotifs.push({ code: 'OPTIONAL_LIMIT_EXCEEDED', level: 'warning', locKey: '' });\n const orderedNotifs = [...rawNotifs].sort((a, b) => compareCanonicalStrings(a.code, b.code) || (a.level === 'error' && b.level !== 'error' ? -1 : b.level === 'error' && a.level !== 'error' ? 1 : 0) || compareCanonicalStrings(a.locKey, b.locKey) || compareCanonicalStrings(a.id ?? '', b.id ?? '') || compareCanonicalStrings(a.label ?? '', b.label ?? ''));\n let emittedNotifs = orderedNotifs.slice(0, bounds.notifications);\n if (limitExceeded && bounds.notifications > 0 && orderedNotifs.some((item) => item.code === 'OPTIONAL_LIMIT_EXCEEDED') && !emittedNotifs.some((item) => item.code === 'OPTIONAL_LIMIT_EXCEEDED')) emittedNotifs = [...orderedNotifs.filter((item) => item.code !== 'OPTIONAL_LIMIT_EXCEEDED').slice(0, bounds.notifications - 1), orderedNotifs.find((item) => item.code === 'OPTIONAL_LIMIT_EXCEEDED')!].sort((a, b) => compareCanonicalStrings(a.code, b.code) || (a.level === 'error' && b.level !== 'error' ? -1 : b.level === 'error' && a.level !== 'error' ? 1 : 0) || compareCanonicalStrings(a.locKey, b.locKey) || compareCanonicalStrings(a.id ?? '', b.id ?? '') || compareCanonicalStrings(a.label ?? '', b.label ?? ''));\n const notifications = emittedNotifs.map((item) => ({ descriptor: { id: item.code }, level: item.level, message: { text: `Analysis diagnostic ${item.code}.` }, ...(item.location ? { locations: [item.location] } : {}) }));\n return freeze({ version: '2.1.0', $schema: 'https://json.schemastore.org/sarif-2.1.0.json', runs: [{ tool: { driver: { name: identity?.engineId ?? 'secureflow-scanner', version: identity?.engineVersion ?? '2.0.0', rules } }, ...(taxonomies.length ? { taxonomies } : {}), results, invocations: [{ executionSuccessful: !invocationFailed, toolExecutionNotifications: notifications }] }] });\n}\nexport function buildSarifV2(input: BatchSarifInputV2): SarifLog { return buildBatchSarifV2(input); }\nexport function serializeSarifV2(input: BatchSarifInputV2): string { return `${JSON.stringify(buildBatchSarifV2(input), null, 2)}\\n`; }\n", "import type { BatchResultV2 } from './batch-runner';\nimport { projectBatchV2 } from './json-output';\n\ntype Row = readonly [string, string, string, string];\n\nexport function renderTableV2(batch: BatchResultV2): string {\n const projected = projectBatchV2(batch, 'json');\n const headers: Row = ['Input', 'Status', 'Findings', 'Error'];\n const rows: Row[] = projected.items.map((item) => {\n if (item.ok) return [item.input, item.result.analysis.status, String(item.result.findings.length), ''];\n const status = item.error.kind === 'CANCELLED' ? 'CANCELLED' : item.error.kind === 'INCOMPLETE' ? 'INCOMPLETE' : item.error.kind === 'INTERNAL' ? 'INTERNAL' : 'ERROR';\n return [item.input, status, '-', item.error.code];\n });\n const escaped = [headers, ...rows].map((row) => row.map(escapeCell));\n const widths = headers.map((_header, column) => Math.max(...escaped.map((row) => row[column]!.length)));\n const line = (row: readonly string[]): string => row.map((value, column) => column === row.length - 1 ? value : value.padEnd(widths[column]!)).join(' ');\n const divider = widths.map((width) => '-'.repeat(width)).join(' ');\n return `${line(escaped[0]!)}\\n${divider}\\n${rows.map((_row, index) => line(escaped[index + 1]!)).join('\\n')}${rows.length ? '\\n' : ''}`;\n}\n\nfunction escapeCell(value: string): string {\n return value.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, (character) => {\n const escapes: Readonly<Record<string, string>> = { '\\b': '\\\\b', '\\t': '\\\\t', '\\n': '\\\\n', '\\f': '\\\\f', '\\r': '\\\\r' };\n return escapes[character] ?? `\\\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`;\n });\n}\n", "import type { BatchItemV2, BatchResultV2 } from './batch-runner';\nimport type { ScanSeverityV2 } from './contracts';\n\nexport type ExitReasonV2 = 'UNDER_THRESHOLD' | 'FINDING_THRESHOLD' | 'REQUIRE_COMPLETE' | 'ITEM_FAILURE' | 'USAGE' | 'INTERNAL' | 'CANCELLED';\nexport type ExitCodeV2 = 0 | 1 | 2 | 3 | 4 | 130;\nexport type ExitReductionV2 = Readonly<{ reason: ExitReasonV2; code: ExitCodeV2 }>;\nexport type ExitReducerOptionsV2 = Readonly<{ failOn?: ScanSeverityV2; requireComplete?: boolean; interrupted?: boolean; outputFailed?: boolean }>;\nexport type ExitReducerInputV2 = Readonly<{ batch: BatchResultV2; failOn?: ScanSeverityV2; requireComplete?: boolean; interrupted?: boolean; outputFailed?: boolean }>;\n\nconst EXITS: Readonly<Record<ExitReasonV2, ExitReductionV2>> = Object.freeze({\n UNDER_THRESHOLD: Object.freeze({ reason: 'UNDER_THRESHOLD', code: 0 }),\n FINDING_THRESHOLD: Object.freeze({ reason: 'FINDING_THRESHOLD', code: 1 }),\n REQUIRE_COMPLETE: Object.freeze({ reason: 'REQUIRE_COMPLETE', code: 1 }),\n ITEM_FAILURE: Object.freeze({ reason: 'ITEM_FAILURE', code: 3 }),\n USAGE: Object.freeze({ reason: 'USAGE', code: 2 }),\n INTERNAL: Object.freeze({ reason: 'INTERNAL', code: 4 }),\n CANCELLED: Object.freeze({ reason: 'CANCELLED', code: 130 }),\n});\nconst SEVERITY: Readonly<Record<ScanSeverityV2, number>> = Object.freeze({ CRITICAL: 5, HIGH: 4, MEDIUM: 3, LOW: 2, INFO: 1 });\nconst USAGE_CODES: Readonly<Record<string, true>> = Object.freeze({\n INVALID_CONFIG: true, UNKNOWN_CONFIGURATION_KEY: true, PROFILE_NOT_ADMITTED: true,\n SEMANTIC_CATALOGUE_INVALID: true, SEMANTIC_CATALOGUE_AMBIGUOUS: true, RULE_PACK_INVALID: true, RULE_PACK_UNTRUSTED: true,\n});\nconst INTERNAL_CODES: Readonly<Record<string, true>> = Object.freeze({ TOOL_INVARIANT_FAILED: true, SERIALIZATION_FAILED: true, OUTPUT_WRITE_FAILED: true });\n\nexport function reduceExitV2(batch: BatchResultV2, options?: ExitReducerOptionsV2): ExitReductionV2;\nexport function reduceExitV2(input: ExitReducerInputV2): ExitReductionV2;\nexport function reduceExitV2(value: unknown, supplied?: ExitReducerOptionsV2): ExitReductionV2 {\n try { return reduceExitV2Unsafe(value, supplied); } catch { return EXITS.USAGE; }\n}\nfunction reduceExitV2Unsafe(value: unknown, supplied?: ExitReducerOptionsV2): ExitReductionV2 {\n const parsed = readInput(value, supplied);\n if (!parsed) return EXITS.USAGE;\n const { batch, options } = parsed;\n if (options.interrupted === true) return EXITS.CANCELLED;\n if (hasCancellation(value)) return EXITS.CANCELLED;\n if (options.outputFailed === true) return EXITS.INTERNAL;\n if (options.failOn !== undefined && !Object.prototype.hasOwnProperty.call(SEVERITY, options.failOn)) return EXITS.USAGE;\n if (options.requireComplete !== undefined && typeof options.requireComplete !== 'boolean') return EXITS.USAGE;\n\n if (!isRecord(batch) || typeof batch.ok !== 'boolean') return EXITS.USAGE;\n if (!batch.ok) {\n const code = typeof batch.code === 'string' ? batch.code : '';\n return code === 'CANCELLED' ? EXITS.CANCELLED : INTERNAL_CODES[code] ? EXITS.INTERNAL : EXITS.USAGE;\n }\n if (!Array.isArray(batch.items)) return EXITS.USAGE;\n\n let threshold = false;\n let degraded = false;\n let itemFailure = false;\n let usage = false;\n let internal = false;\n let cancelled = batch.cancelled === true;\n for (const item of batch.items) {\n if (!isRecord(item)) { usage = true; continue; }\n const status = item.status;\n if (status === 'CANCELLED') { cancelled = true; continue; }\n if (status !== 'COMPLETED' && status !== 'FAILED' && status !== 'TIMEOUT') { usage = true; continue; }\n const errorCode = readErrorCode(item);\n if (errorCode === 'SCAN_CANCELLED') { cancelled = true; continue; }\n if (INTERNAL_CODES[errorCode]) { internal = true; continue; }\n if (USAGE_CODES[errorCode]) { itemFailure = true; continue; }\n if (status !== 'COMPLETED') { itemFailure = true; continue; }\n const scan = isRecord(item.result) && item.result.ok === true && isRecord(item.result.result) ? item.result.result : undefined;\n if (!scan) { itemFailure = true; continue; }\n const analysis = isRecord(scan.analysis) ? scan.analysis : undefined;\n if (analysis?.status === 'INDETERMINATE') itemFailure = true;\n else if (analysis?.status === 'DEGRADED') degraded = true;\n else if (analysis?.status !== 'COMPLETE') itemFailure = true;\n if (Array.isArray(scan.findings)) {\n const failOn = options.failOn ?? 'INFO';\n const minimum = SEVERITY[failOn];\n for (const finding of scan.findings) {\n if (isRecord(finding) && typeof finding.severity === 'string' && SEVERITY[finding.severity as ScanSeverityV2] >= minimum) threshold = true;\n }\n }\n }\n if (cancelled) return EXITS.CANCELLED;\n if (internal) return EXITS.INTERNAL;\n if (usage) return EXITS.USAGE;\n if (threshold) return EXITS.FINDING_THRESHOLD;\n if (degraded && options.requireComplete === true) return EXITS.REQUIRE_COMPLETE;\n if (itemFailure) return EXITS.ITEM_FAILURE;\n return EXITS.UNDER_THRESHOLD;\n}\n\nfunction readInput(value: unknown, supplied?: ExitReducerOptionsV2): { batch: unknown; options: ExitReducerOptionsV2 } | undefined {\n if (isRecord(value) && 'batch' in value) {\n const input = value as Record<string, unknown>;\n return { batch: input.batch, options: { failOn: input.failOn as ScanSeverityV2 | undefined, requireComplete: input.requireComplete as boolean | undefined, interrupted: input.interrupted as boolean | undefined, outputFailed: input.outputFailed as boolean | undefined } };\n }\n return supplied === undefined || isRecord(supplied) ? { batch: value, options: supplied ?? {} } : undefined;\n}\nfunction readErrorCode(item: Record<string, unknown>): string { const error = item.error; return isRecord(error) && typeof error.code === 'string' ? error.code : ''; }\nfunction isRecord(value: unknown): value is Record<string, unknown> { return value !== null && typeof value === 'object' && !Array.isArray(value); }\nfunction hasCancellation(value: unknown): boolean {\n const candidate = isRecord(value) && 'batch' in value ? value.batch : value;\n if (!isRecord(candidate)) return false;\n if (candidate.ok === false && candidate.code === 'CANCELLED') return true;\n if (candidate.cancelled === true) return true;\n return Array.isArray(candidate.items) && candidate.items.some((item) => isRecord(item) && (item.status === 'CANCELLED' || isRecord(item.error) && item.error.code === 'SCAN_CANCELLED'));\n}\n", "import { lstat, open, realpath, rename, unlink } from 'node:fs/promises';\nimport type { FileHandle } from 'node:fs/promises';\nimport type { Stats } from 'node:fs';\nimport { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path';\n\nexport type AtomicOutputFailureCodeV2 = 'INVALID_CONFIG' | 'SERIALIZATION_FAILED' | 'OUTPUT_WRITE_FAILED' | 'CANCELLED';\nexport type AtomicOutputResultV2 = Readonly<{ ok: true } | { ok: false; code: AtomicOutputFailureCodeV2; message: string }>;\nexport type AtomicOutputHandleV2 = Readonly<{ write: (bytes: Uint8Array) => Promise<void>; sync: () => Promise<void>; close: () => Promise<void> }>;\nexport type AtomicOutputStatV2 = Pick<Stats, 'isFile' | 'isDirectory' | 'isSymbolicLink'>;\nexport type AtomicOutputHostV2 = Readonly<{\n lstat?: (path: string) => Promise<AtomicOutputStatV2>;\n realpath?: (path: string) => Promise<string>;\n open?: (path: string) => Promise<AtomicOutputHandleV2>;\n write?: (path: string, bytes: Uint8Array) => Promise<void>;\n sync?: (path: string) => Promise<void>;\n rename?: (from: string, to: string) => Promise<void>;\n unlink?: (path: string) => Promise<void>;\n}>;\nexport type AtomicOutputOptionsV2 = Readonly<{ baseDirectory?: string; inputPaths?: readonly string[]; signal?: AbortSignal; maxTempAttempts?: number; host?: AtomicOutputHostV2 }>;\n\nconst INVALID = 'Output path is not admitted.';\nconst COLLISION = 'Output path collides with an input file.';\nconst WRITE_FAILED = 'Output could not be written.';\nconst CANCELLED = 'Output was cancelled.';\nconst DEFAULT_ATTEMPTS = 8;\nconst CONTROL = /[\\u0000-\\u001f\\u007f]/;\nconst ABSOLUTE = /^(?:[a-z][a-z\\d+.-]*:|\\/|[a-z]:|\\\\\\\\)/i;\n\nexport async function writeAtomicUtf8V2(target: string, text: string, options: AtomicOutputOptionsV2 = {}): Promise<AtomicOutputResultV2> {\n if (typeof text !== 'string' || /[\\ud800-\\udfff]/.test(text) && !/^(?:[\\u0000-\\ud7ff\\ue000-\\uffff]|[\\ud800-\\udbff][\\udc00-\\udfff])*$/.test(text)) return fail('SERIALIZATION_FAILED', WRITE_FAILED);\n return writeAtomicOutputV2(target, new TextEncoder().encode(text), options);\n}\n\nexport async function writeAtomicBytesV2(target: string, bytes: Uint8Array, options: AtomicOutputOptionsV2 = {}): Promise<AtomicOutputResultV2> {\n return bytes instanceof Uint8Array ? writeAtomicOutputV2(target, bytes, options) : fail('SERIALIZATION_FAILED', WRITE_FAILED);\n}\n\nexport async function writeAtomicOutputV2(target: string, content: string | Uint8Array, options: AtomicOutputOptionsV2 = {}): Promise<AtomicOutputResultV2> {\n if (options === null || typeof options !== 'object') return fail('INVALID_CONFIG', INVALID);\n const normalized = normalizeTarget(target);\n const bytes = typeof content === 'string' ? encodeText(content) : content instanceof Uint8Array ? new Uint8Array(content) : undefined;\n const attempts = options.maxTempAttempts ?? DEFAULT_ATTEMPTS;\n if (!normalized || !bytes || !validOptions(options, attempts)) return fail(!bytes ? 'SERIALIZATION_FAILED' : 'INVALID_CONFIG', !bytes ? WRITE_FAILED : INVALID);\n const baseDirectory = resolve(options.baseDirectory ?? '.');\n const output = resolve(baseDirectory, normalized);\n const host = options.host ?? {};\n const fsLstat = host.lstat ?? (async (path: string) => lstat(path));\n const fsRealpath = host.realpath ?? (async (path: string) => realpath(path));\n const fsRename = host.rename ?? (async (from: string, to: string) => rename(from, to));\n const fsUnlink = host.unlink ?? (async (path: string) => unlink(path));\n try {\n const parent = dirname(output);\n // The destination is contained by the resolved base, not by lexical spelling: an ancestor\n // link that resolves outside the base is refused before any temp file or rename happens.\n const realBase = await fsRealpath(baseDirectory).catch(() => undefined);\n const realParent = await fsRealpath(parent).catch(() => undefined);\n if (!realBase || !realParent || !withinResolvedRoot(realBase, realParent)) return fail('INVALID_CONFIG', INVALID);\n const parentStat = await fsLstat(realParent).catch(() => undefined);\n if (!parentStat?.isDirectory()) return fail('INVALID_CONFIG', INVALID);\n const safeOutput = join(realParent, basename(output));\n const inputIds = await inputIdentities(options.inputPaths ?? [], baseDirectory, fsLstat, fsRealpath);\n if (!inputIds) return fail('INVALID_CONFIG', INVALID);\n const existing = await existingTarget(safeOutput, fsLstat, fsRealpath);\n if (existing?.kind === 'directory' || existing?.kind === 'special') return fail('INVALID_CONFIG', INVALID);\n if (existing?.realPath && inputIds.has(identity(existing.realPath))) return fail('INVALID_CONFIG', COLLISION);\n if (inputIds.has(identity(safeOutput))) return fail('INVALID_CONFIG', COLLISION);\n if (existing?.kind === 'symlink') return fail('INVALID_CONFIG', INVALID);\n if (options.signal?.aborted) return fail('CANCELLED', CANCELLED);\n\n let handle: AtomicOutputHandleV2 | undefined;\n let temporary: string | undefined;\n for (let index = 0; index < attempts; index += 1) {\n const candidate = join(realParent, `.${basename(output)}.tmp-${index}`);\n try { handle = await openExclusive(candidate, host); temporary = candidate; break; }\n catch (error) { if (errorCode(error) !== 'EEXIST') return fail('OUTPUT_WRITE_FAILED', WRITE_FAILED); }\n }\n if (!handle || !temporary) return fail('OUTPUT_WRITE_FAILED', WRITE_FAILED);\n try {\n if (options.signal?.aborted) return fail('CANCELLED', CANCELLED);\n if (host.write) await host.write(temporary, bytes); else await handle.write(bytes);\n if (options.signal?.aborted) return fail('CANCELLED', CANCELLED);\n if (host.sync) await host.sync(temporary); else await handle.sync();\n await handle.close(); handle = undefined;\n if (options.signal?.aborted) return fail('CANCELLED', CANCELLED);\n await fsRename(temporary, safeOutput);\n temporary = undefined;\n return Object.freeze({ ok: true as const });\n } catch (error) {\n return errorCode(error) === 'ABORT_ERR' || options.signal?.aborted ? fail('CANCELLED', CANCELLED) : fail('OUTPUT_WRITE_FAILED', WRITE_FAILED);\n } finally {\n try { if (handle) await handle.close(); } catch { /* cleanup remains best effort */ }\n if (temporary) try { await fsUnlink(temporary); } catch { /* preserve the original failure */ }\n }\n } catch { return fail('OUTPUT_WRITE_FAILED', WRITE_FAILED); }\n}\n\nasync function openExclusive(path: string, host: AtomicOutputHostV2): Promise<AtomicOutputHandleV2> {\n if (host.open) return host.open(path);\n const file = await open(path, 'wx');\n return fileHandle(file);\n}\nfunction fileHandle(file: FileHandle): AtomicOutputHandleV2 { return { write: async (bytes) => { await file.writeFile(bytes); }, sync: async () => { await file.sync(); }, close: async () => { await file.close(); } }; }\nfunction stripVerbatim(pathValue: string): string {\n if (pathValue.startsWith('\\\\\\\\?\\\\UNC\\\\')) return `\\\\\\\\${pathValue.slice(8)}`;\n return pathValue.startsWith('\\\\\\\\?\\\\') ? pathValue.slice(4) : pathValue;\n}\nfunction withinResolvedRoot(root: string, candidate: string): boolean {\n const remainder = relative(stripVerbatim(root), stripVerbatim(candidate));\n return remainder === '' || (!isAbsolute(remainder) && remainder !== '..'\n && !remainder.startsWith(`..${sep}`) && !remainder.startsWith('../'));\n}\nasync function directoryChainIsSafe(\n directory: string,\n check: (path: string) => Promise<AtomicOutputStatV2>,\n resolvePath: (path: string) => Promise<string>,\n): Promise<boolean> {\n const pathRoot = parse(directory).root;\n let current = pathRoot;\n for (const part of relative(pathRoot, directory).split(sep).filter(Boolean)) {\n current = join(current, part);\n try {\n const stat = await check(current);\n if (stat.isSymbolicLink()) {\n const target = await check(await resolvePath(current));\n if (!target.isDirectory()) return false;\n } else if (!stat.isDirectory()) return false;\n } catch { return false; }\n }\n return true;\n}\nasync function inputIdentities(inputs: readonly string[], base: string, check: (path: string) => Promise<AtomicOutputStatV2>, resolvePath: (path: string) => Promise<string>): Promise<Set<string> | undefined> {\n const result = new Set<string>();\n if (!Array.isArray(inputs)) return undefined;\n for (const raw of inputs) {\n if (typeof raw !== 'string' || raw.length === 0 || raw.length > 4096 || CONTROL.test(raw)) return undefined;\n const path = resolveInputPath(raw, base);\n if (!path || !(await directoryChainIsSafe(dirname(path), check, resolvePath))) return undefined;\n try {\n const stat = await check(path);\n if (!stat.isFile() && !stat.isSymbolicLink()) return undefined;\n const resolved = await resolvePath(path);\n const targetStat = await check(resolved);\n if (!targetStat.isFile()) return undefined;\n result.add(identity(resolved));\n } catch { return undefined; }\n }\n return result;\n}\nasync function existingTarget(path: string, check: (path: string) => Promise<AtomicOutputStatV2>, resolvePath: (path: string) => Promise<string>): Promise<{ kind: 'directory' | 'special' | 'symlink' | 'file'; realPath?: string } | undefined> {\n try {\n const stat = await check(path);\n if (stat.isDirectory()) return { kind: 'directory' };\n if (stat.isSymbolicLink()) {\n try { return { kind: 'symlink', realPath: await resolvePath(path) }; } catch { return { kind: 'symlink' }; }\n }\n if (!stat.isFile()) return { kind: 'special' };\n return { kind: 'file', realPath: await resolvePath(path) };\n } catch (error) { return errorCode(error) === 'ENOENT' ? undefined : { kind: 'special' }; }\n}\nfunction normalizeTarget(raw: unknown): string | undefined {\n if (typeof raw !== 'string' || raw.length === 0 || raw.length > 4096 || CONTROL.test(raw)) return undefined;\n const normalized = raw.replaceAll('\\\\', '/'); if (ABSOLUTE.test(normalized)) return undefined;\n const parts: string[] = []; for (const part of normalized.split('/')) { if (!part || part === '.') continue; if (part === '..') { if (!parts.length) return undefined; parts.pop(); } else parts.push(part); }\n return parts.length ? parts.join('/') : undefined;\n}\nfunction encodeText(value: string): Uint8Array | undefined { try { if (/[\\ud800-\\udfff]/.test(value) && !/^(?:[\\u0000-\\ud7ff\\ue000-\\uffff]|[\\ud800-\\udbff][\\udc00-\\udfff])*$/.test(value)) return undefined; return new TextEncoder().encode(value); } catch { return undefined; } }\nfunction validOptions(options: AtomicOutputOptionsV2, attempts: number): boolean { return options !== null && typeof options === 'object' && Number.isSafeInteger(attempts) && attempts > 0 && attempts <= 64 && (options.baseDirectory === undefined || typeof options.baseDirectory === 'string' && options.baseDirectory.length > 0 && !CONTROL.test(options.baseDirectory)) && (options.inputPaths === undefined || Array.isArray(options.inputPaths)); }\nfunction resolveInputPath(raw: string, base: string): string | undefined {\n const normalized = raw.replaceAll('\\\\', '/');\n if (ABSOLUTE.test(normalized)) return /^(?:\\/|[a-z]:[\\\\/]|\\\\\\\\)/i.test(raw) ? resolve(raw) : undefined;\n const parts: string[] = [];\n for (const part of normalized.split('/')) {\n if (!part || part === '.') continue;\n if (part === '..') { if (!parts.length) return undefined; parts.pop(); } else parts.push(part);\n }\n return parts.length ? resolve(base, parts.join('/')) : undefined;\n}\nfunction identity(value: string): string { const normalized = value.replaceAll('\\\\', '/'); return process.platform === 'win32' ? normalized.toLowerCase() : normalized; }\nfunction errorCode(error: unknown): string | undefined { return error && typeof error === 'object' && 'code' in error && typeof (error as { code?: unknown }).code === 'string' ? (error as { code: string }).code : undefined; }\nfunction fail(code: AtomicOutputFailureCodeV2, message: string): AtomicOutputResultV2 { return Object.freeze({ ok: false as const, code, message }); }\n", "import type { CliStdin, InputReadHost } from './input-read';\nimport { collectInputs, type InputSelectionHost } from './input-selection';\nimport type { CliCommandV2 } from './arguments';\nimport { readScanConfig } from './scan-config-load';\nimport type { ScanConfigV2 } from './config';\nimport { runBatchV2, type BatchReadV2, type BatchScanV2, type BatchResultV2 } from './batch-runner';\nimport { serializeEnvelopeV2, projectBatchV2, type CliEnvelopeV2, type ProjectionOptionsV2, type ProjectionSourceV2 } from './json-output';\nimport { serializeNdjsonV2 } from './ndjson-output';\nimport { serializeSarifV2 } from '@hub/scanner-core/report/sarif-v2/output';\nimport { renderTableV2 } from './table-output';\nimport { reduceExitV2, type ExitCodeV2 } from './exit-reducer';\nimport { writeAtomicOutputV2 } from './atomic-output';\nimport type { SigintSource } from './worker-host';\n\nexport type V2CliRunOptions = Readonly<{\n cwd?: string;\n stdin?: CliStdin;\n signal?: AbortSignal;\n read?: BatchReadV2;\n scan?: BatchScanV2;\n readHost?: InputReadHost;\n selectionHost?: InputSelectionHost;\n sigint?: SigintSource;\n}>;\n\nexport type V2CliRunResult = Readonly<{\n exitCode: ExitCodeV2;\n stdout: string;\n stderr: string;\n document?: CliEnvelopeV2 | string;\n}>;\n\ntype ScanCommand = Extract<CliCommandV2, { kind: 'scan' }>;\ntype SerializedDocument = Readonly<{ output: string; document: CliEnvelopeV2 | string }>;\ntype SuccessfulBatch = Extract<BatchResultV2, { ok: true }>;\n\nexport async function runCliV2Internal(command: ScanCommand, options: V2CliRunOptions = {}): Promise<V2CliRunResult> {\n const baseDirectory = options.cwd ?? process.cwd();\n const config = await readScanConfig(command, baseDirectory);\n if (!config.ok) return failure(config.exitCode, config.message);\n\n const selected = await collectInputs({\n inputs: config.config.inputs ?? [],\n include: config.config.include,\n exclude: config.config.exclude,\n baseDirectory,\n host: options.selectionHost,\n outputPath: config.config.output,\n signal: options.signal,\n });\n if (!selected.ok) {\n if (selected.code !== 'CANCELLED') return failure(2, selected.message);\n const cancelled: SuccessfulBatch = Object.freeze({ ok: true as const, items: Object.freeze([]), cancelled: true, completed: 0, failed: 0, concurrency: config.config.concurrency ?? 1 });\n const serialized = serializeBatch(cancelled, config.config.format ?? command.format, config.config, config.sources);\n return config.config.output !== undefined && config.config.output !== '-'\n ? Object.freeze({ exitCode: 130 as const, stdout: '', stderr: '', document: serialized.document })\n : Object.freeze({ exitCode: 130 as const, stdout: serialized.output, stderr: '', document: serialized.document });\n }\n\n let batch: BatchResultV2;\n try {\n batch = await runBatchV2({\n items: selected.inputs,\n config: config.config,\n read: options.read,\n scan: options.scan,\n stdin: options.stdin,\n readHost: options.readHost,\n baseDirectory,\n limitsDocument: config.limitsDocument,\n targetDocument: config.targetDocument,\n approvedDomains: config.config.approvedDomains,\n timeoutMs: command.timeoutMs,\n signal: options.signal,\n sigint: options.sigint ?? process,\n });\n } catch {\n return failure(4, 'Internal scanner failure.');\n }\n\n const reduction = reduceExitV2(batch, { failOn: config.config.failOn, requireComplete: config.config.requireComplete });\n if (!batch.ok) return failure(reduction.code, reduction.reason === 'CANCELLED' ? '' : 'Configuration is invalid.');\n\n let serialized: SerializedDocument;\n try {\n serialized = serializeBatch(batch, config.config.format ?? command.format, config.config, config.sources);\n } catch {\n const exit = reduceExitV2(batch, { failOn: config.config.failOn, requireComplete: config.config.requireComplete, outputFailed: true });\n return failure(exit.code, 'Output could not be written.');\n }\n\n if (config.config.output !== undefined && config.config.output !== '-') {\n if (reduction.reason === 'CANCELLED') return Object.freeze({ exitCode: reduction.code, stdout: '', stderr: '', document: serialized.document });\n const output = await writeAtomicOutputV2(config.config.output, serialized.output, {\n baseDirectory,\n inputPaths: selected.inputs.filter((item) => !item.isStdin).map((item) => item.realPath ?? item.label),\n signal: options.signal,\n });\n if (!output.ok) {\n const exit = reduceExitV2(batch, {\n failOn: config.config.failOn,\n requireComplete: config.config.requireComplete,\n interrupted: output.code === 'CANCELLED',\n outputFailed: output.code !== 'CANCELLED',\n });\n return Object.freeze({ exitCode: exit.code, stdout: '', stderr: output.code === 'CANCELLED' ? '' : `${output.message}\\n` });\n }\n return Object.freeze({ exitCode: reduction.code, stdout: '', stderr: '', document: serialized.document });\n }\n\n return Object.freeze({ exitCode: reduction.code, stdout: serialized.output, stderr: '', document: serialized.document });\n}\n\nfunction serializeBatch(batch: SuccessfulBatch, format: ScanConfigV2['format'], config: ScanConfigV2, sources: ProjectionSourceV2): SerializedDocument {\n const projection = projectionOptions(config, format, sources);\n if (format === 'json' || format === undefined) {\n return Object.freeze({ output: serializeEnvelopeV2(batch, projection), document: projectBatchV2(batch, projection).envelope });\n }\n if (format === 'ndjson') {\n const output = serializeNdjsonV2(batch, projection);\n return Object.freeze({ output, document: output });\n }\n if (format === 'sarif') {\n const output = serializeSarifV2({ items: batch.items });\n return Object.freeze({ output, document: output });\n }\n if (format === 'table') {\n const output = renderTableV2(batch);\n return Object.freeze({ output, document: output });\n }\n throw new TypeError('Invalid format');\n}\n\nfunction projectionOptions(config: ScanConfigV2, format: ScanConfigV2['format'], sources: ProjectionSourceV2): ProjectionOptionsV2 {\n return Object.freeze({\n format: format === 'ndjson' ? 'ndjson' : 'json',\n profile: config.profile ?? 'beta-default',\n failOn: config.failOn ?? 'INFO',\n requireComplete: config.requireComplete ?? false,\n concurrency: config.concurrency ?? 1,\n allowUnsignedDevelopmentRules: config.allowUnsignedDevelopmentRules ?? false,\n sources: Object.freeze({ ...sources }),\n });\n}\n\nfunction failure(exitCode: ExitCodeV2, message: string): V2CliRunResult {\n return Object.freeze({ exitCode, stdout: '', stderr: message ? `${message}\\n` : '' });\n}\n", "import type { CliCommandV2 } from './arguments.js';\nimport { runCliV2Internal } from './cli-runner-internal.js';\n\n/** The scan member only: the internal runner does not dispatch metadata commands. */\nexport type PublicScanCommandV2 = Extract<CliCommandV2, { kind: 'scan' }>;\nexport type PublicRunOptionsV2 = Readonly<{\n cwd?: string;\n stdin?: string | Uint8Array | AsyncIterable<Uint8Array | string>;\n signal?: AbortSignal;\n}>;\nexport type PublicRunResultV2 = Readonly<{\n exitCode: number;\n stdout: string;\n stderr: string;\n document?: unknown;\n}>;\n\n/**\n * Library entry. The `sfscanner` bin remains the side-effecting CLI; this wrapper forwards only\n * the three consumer options, so an internal read/scan/selection hook is never part of the\n * published surface.\n */\nexport async function runCliV2(command: PublicScanCommandV2, options: PublicRunOptionsV2 = {}): Promise<PublicRunResultV2> {\n return runCliV2Internal(command, { cwd: options.cwd, stdin: options.stdin, signal: options.signal });\n}\n", "#!/usr/bin/env node\nimport { runCli } from './cli.js';\nimport { parseCliArguments } from './v2/arguments.js';\nimport { emitMetadataCommandResultV2 } from './v2/metadata-output.js';\nimport { getHelpV2 } from './v2/help.js';\nimport { runCliV2 } from './v2/cli-runner.js';\n\nconst dispatch = parseCliArguments(process.argv.slice(2));\nif (dispatch.mode === 'v1') {\n const result = await runCli(dispatch.argv);\n if (result.stdout) process.stdout.write(result.stdout);\n if (result.stderr) process.stderr.write(result.stderr);\n process.exitCode = result.exitCode;\n} else if (!dispatch.result.ok) {\n const detail = dispatch.result.error.argument === undefined ? dispatch.result.error.message : `${dispatch.result.error.message} (${dispatch.result.error.argument})`;\n process.stderr.write(`Invalid command usage: ${detail}\\n`);\n process.exitCode = 2;\n} else if (dispatch.result.command.kind === 'help') {\n process.stdout.write(getHelpV2(dispatch.result.command.command));\n process.exitCode = 0;\n} else if (dispatch.result.command.kind === 'scan') {\n const controller = new AbortController();\n const onSigint = (): void => controller.abort();\n process.on('SIGINT', onSigint);\n try {\n const result = await runCliV2(dispatch.result.command, { signal: controller.signal });\n if (result.stdout) process.stdout.write(result.stdout);\n if (result.stderr) process.stderr.write(result.stderr);\n process.exitCode = result.exitCode;\n } finally {\n process.off('SIGINT', onSigint);\n }\n} else {\n const result = emitMetadataCommandResultV2(dispatch.result.command, undefined, { configDirectory: process.cwd() });\n if (!result.ok) {\n process.stderr.write(`${result.message}\\n`);\n process.exitCode = 2;\n } else {\n process.stdout.write(result.output);\n process.exitCode = 0;\n }\n}\n"],
5
+ "mappings": ";;;AAAO,IAAM,YAAY;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,EAAE,KAAK,IAAI;;;AC3BX,SAAS,YAAY;;;ACId,IAAM,gCAAgC;;;ACoC7C,IAAM,mBAAmB;AAiBzB,SAAS,eAAeA,SAA+B;AACrD,MAAI,CAAC,iBAAiB,KAAKA,QAAO,EAAE,GAAG;AACrC,UAAM,IAAI;AAAA,MACR,iDAAiDA,QAAO,EAAE;AAAA,IAE5D;AAAA,EACF;AACA,MAAI,CAACA,QAAO,OAAO,KAAK,GAAG;AACzB,UAAM,IAAI,MAAM,qCAAqCA,QAAO,EAAE,2BAA2B;AAAA,EAC3F;AACA,MAAI,CAAC,OAAO,SAAS,KAAK,MAAMA,QAAO,UAAU,CAAC,GAAG;AACnD,UAAM,IAAI;AAAA,MACR,qCAAqCA,QAAO,EAAE,2CAA2CA,QAAO,UAAU;AAAA,IAC5G;AAAA,EACF;AACF;AAQO,SAAS,wBAAwBC,UAAwD;AAC9F,QAAM,OAAO,oBAAI,IAAY;AAC7B,aAAWD,WA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AAW;AAAA,EACrB;AACF;",
6
+ "names": ["record", "records", "byId", "field", "stat", "offset", "entry", "authorityEnd", "hash", "entry", "finding", "finding", "entry", "isRecord", "diagnostic", "diagnostic", "open", "source", "entry", "entry", "body", "found", "source", "literal", "closed", "body", "isRecord", "literal", "authentication", "node", "path", "isRecord", "node", "node", "node", "packageName", "compareCanonicalStrings", "node", "compareCanonicalStrings", "node", "node", "unique", "compactNodeType", "edge", "isRecord", "target", "node", "node", "source", "field", "pointer", "defaults", "data", "compareCanonicalStrings", "tagged", "text", "identifier", "range", "body", "identifier", "text", "types", "range", "text", "encoder", "encodeIdentityPart", "containsLoneSurrogate", "tagged", "path", "node", "text", "text", "node", "identity", "field", "text", "field", "copy", "properties", "copy", "properties", "evidenceClass", "record", "schema", "record", "required", "auth", "text", "error", "entry", "required", "encoder", "entry", "record", "encoder", "record", "pointer", "path", "record", "subject", "properties", "required", "identity", "capability", "finding", "node", "subject", "properties", "evidenceClass", "source", "finding", "node", "pointer", "field", "path", "required", "body", "digest", "mapping", "entry", "digest", "capability", "fact", "insights", "subject", "capability", "finding", "node", "refs", "diagnostic", "entry", "finding", "node", "finding", "sourceSpan", "duplicateKeys", "node", "source", "memberName", "pointer", "compareCanonicalStrings", "position", "duplicateKeys", "error", "isRecord", "node", "diagnostic", "analysisStatus", "source", "finding", "compareCanonicalStrings", "sourceSpan", "finding", "error", "RULE_PACK_DIGEST_V2", "body", "relative", "target", "safeText", "field", "readFileSync", "createHash", "encoder", "isDigit", "field", "error", "invalid", "error", "safeText", "enumValue", "body", "freeze", "body", "digest", "invalid", "freeze", "error", "invalid", "ownRecord", "field", "denseArray", "error", "range", "TOP", "DIGEST", "has", "fail", "error", "required", "enumValue", "pointer", "unique", "range", "record", "freeze", "body", "records", "body", "TOP", "digest", "DIGEST", "fail", "freeze", "error", "DIGEST", "fail", "entry", "refs", "provenance", "pointer", "required", "endpoint", "path", "record", "nodeType", "PROVENANCE", "TOP", "DIGEST", "SECRET", "isRecord", "required", "path", "text", "digest", "integer", "source", "capability", "v", "assessment", "resultOmitted", "properties", "out", "encoder", "encoder", "entry", "mapping", "PROFILE_MANIFEST_DIGEST_V2", "SEMANTIC_CATALOGUE_DIGEST_V2", "PROFILE_MANIFEST_DIGEST_V2", "BUILTIN_RULESET_AUTHORITY_V2", "BUILTIN_SEMANTICS_AUTHORITY_V2", "LIMIT_KEYS", "failure", "record", "path", "paths", "text", "object", "array", "failure", "createHash", "PROSE", "target", "entry", "body", "path", "DIGEST", "fail", "object", "digest", "artifacts", "target", "schema", "result", "capability", "sep", "body", "readFileSync", "res", "fail", "walk", "entry", "open", "relative", "open", "stat", "text", "source", "invalid", "target", "open", "open", "isString", "safeLabel", "encoder", "data", "resolve", "resolve", "source", "closed", "SECRET", "projection", "artifacts", "freezeValue", "sameIdentity", "clean", "cancelled", "finding", "properties", "optional", "digestBody", "dense", "object", "source", "en", "freeze", "registry", "finding", "projection", "fact", "identity", "limitExceeded", "trace", "diagnostic", "freeze", "row", "isRecord", "cancelled", "errorCode", "finding", "error", "lstat", "open", "realpath", "parse", "resolve", "CONTROL", "ABSOLUTE", "target", "fail", "resolve", "path", "lstat", "realpath", "error", "errorCode", "open", "parse", "stat", "CONTROL", "ABSOLUTE", "failure", "cancelled", "serialized", "projection"]
7
+ }