@transcend-io/cli 10.29.0 → 10.29.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{app-C5baDSA2.mjs → app-B9yoXd7q.mjs} +16 -16
- package/dist/{app-C5baDSA2.mjs.map → app-B9yoXd7q.mjs.map} +1 -1
- package/dist/{approvePrivacyRequests-B8x7oxTn.mjs → approvePrivacyRequests-DDT8Zjhc.mjs} +2 -2
- package/dist/{approvePrivacyRequests-B8x7oxTn.mjs.map → approvePrivacyRequests-DDT8Zjhc.mjs.map} +1 -1
- package/dist/bin/bash-complete.mjs +1 -1
- package/dist/bin/cli.mjs +1 -1
- package/dist/bin/deprecated-command.mjs +1 -1
- package/dist/{buildExamples-7KXBjl-b.mjs → buildExamples-DLDlrgWE.mjs} +2 -2
- package/dist/{buildExamples-7KXBjl-b.mjs.map → buildExamples-DLDlrgWE.mjs.map} +1 -1
- package/dist/{buildXdiSyncEndpoint-DcrkZ2Gu.mjs → buildXdiSyncEndpoint-uSDQEXT2.mjs} +2 -2
- package/dist/{buildXdiSyncEndpoint-DcrkZ2Gu.mjs.map → buildXdiSyncEndpoint-uSDQEXT2.mjs.map} +1 -1
- package/dist/{bulkRestartRequests-CysUfl98.mjs → bulkRestartRequests-C4wyNZ65.mjs} +2 -2
- package/dist/{bulkRestartRequests-CysUfl98.mjs.map → bulkRestartRequests-C4wyNZ65.mjs.map} +1 -1
- package/dist/{bulkRetryEnrichers-DaLE67Ht.mjs → bulkRetryEnrichers-VbIb-WIs.mjs} +2 -2
- package/dist/{bulkRetryEnrichers-DaLE67Ht.mjs.map → bulkRetryEnrichers-VbIb-WIs.mjs.map} +1 -1
- package/dist/{cancelPrivacyRequests-D0zNUNdS.mjs → cancelPrivacyRequests-Ds6HKabX.mjs} +2 -2
- package/dist/{cancelPrivacyRequests-D0zNUNdS.mjs.map → cancelPrivacyRequests-Ds6HKabX.mjs.map} +1 -1
- package/dist/{command-CIv9yk86.mjs → command-BVK929yJ.mjs} +2 -2
- package/dist/{command-CIv9yk86.mjs.map → command-BVK929yJ.mjs.map} +1 -1
- package/dist/{constants-jjHIzHGm.mjs → constants-X60pMfSm.mjs} +2 -2
- package/dist/{constants-jjHIzHGm.mjs.map → constants-X60pMfSm.mjs.map} +1 -1
- package/dist/{createPoolingCommandUi-uiDjLlqf.mjs → createPoolingCommandUi-Dr6Cmq63.mjs} +2 -2
- package/dist/{createPoolingCommandUi-uiDjLlqf.mjs.map → createPoolingCommandUi-Dr6Cmq63.mjs.map} +1 -1
- package/dist/{downloadPrivacyRequestFiles-B_BVxW5Z.mjs → downloadPrivacyRequestFiles-BZjAtiKF.mjs} +2 -2
- package/dist/{downloadPrivacyRequestFiles-B_BVxW5Z.mjs.map → downloadPrivacyRequestFiles-BZjAtiKF.mjs.map} +1 -1
- package/dist/{generateCrossAccountApiKeys-Bnqgmj-H.mjs → generateCrossAccountApiKeys-POFAc7bo.mjs} +2 -2
- package/dist/{generateCrossAccountApiKeys-Bnqgmj-H.mjs.map → generateCrossAccountApiKeys-POFAc7bo.mjs.map} +1 -1
- package/dist/{impl-B-j5ACi02.mjs → impl-BDgc5PEC2.mjs} +2 -2
- package/dist/{impl-B-j5ACi02.mjs.map → impl-BDgc5PEC2.mjs.map} +1 -1
- package/dist/{impl-Dx_TfvW1.mjs → impl-BPzANN8n.mjs} +2 -2
- package/dist/{impl-Dx_TfvW1.mjs.map → impl-BPzANN8n.mjs.map} +1 -1
- package/dist/{impl-BqWQh9Ss.mjs → impl-BScGBm2o.mjs} +2 -2
- package/dist/{impl-BqWQh9Ss.mjs.map → impl-BScGBm2o.mjs.map} +1 -1
- package/dist/{impl-RPG-BTmX.mjs → impl-BT0N2HwU.mjs} +2 -2
- package/dist/{impl-RPG-BTmX.mjs.map → impl-BT0N2HwU.mjs.map} +1 -1
- package/dist/{impl-CuDs6SsI.mjs → impl-BTff-yNX.mjs} +2 -2
- package/dist/{impl-CuDs6SsI.mjs.map → impl-BTff-yNX.mjs.map} +1 -1
- package/dist/{impl-DypttZd6.mjs → impl-BeHsB-Zk.mjs} +2 -2
- package/dist/{impl-DypttZd6.mjs.map → impl-BeHsB-Zk.mjs.map} +1 -1
- package/dist/{impl-DuZjI6p0.mjs → impl-Bg7zZ_F_.mjs} +2 -2
- package/dist/{impl-DuZjI6p0.mjs.map → impl-Bg7zZ_F_.mjs.map} +1 -1
- package/dist/{impl-DMe_OqJx.mjs → impl-Bguphgoc.mjs} +2 -2
- package/dist/{impl-DMe_OqJx.mjs.map → impl-Bguphgoc.mjs.map} +1 -1
- package/dist/{impl-CXTBcYo6.mjs → impl-BkqQI3vZ.mjs} +2 -2
- package/dist/{impl-CXTBcYo6.mjs.map → impl-BkqQI3vZ.mjs.map} +1 -1
- package/dist/{impl-BDrvzlpf2.mjs → impl-BnvfuqEA2.mjs} +2 -2
- package/dist/{impl-BDrvzlpf2.mjs.map → impl-BnvfuqEA2.mjs.map} +1 -1
- package/dist/{impl-DEhw1iNn.mjs → impl-C1xIUoJS.mjs} +2 -2
- package/dist/{impl-DEhw1iNn.mjs.map → impl-C1xIUoJS.mjs.map} +1 -1
- package/dist/{impl-DEJpYLPB.mjs → impl-C8sWVJUG.mjs} +2 -2
- package/dist/{impl-DEJpYLPB.mjs.map → impl-C8sWVJUG.mjs.map} +1 -1
- package/dist/{impl-KmCNH-yw.mjs → impl-CE_nprLV.mjs} +2 -2
- package/dist/{impl-KmCNH-yw.mjs.map → impl-CE_nprLV.mjs.map} +1 -1
- package/dist/{impl-hwpT9u5o2.mjs → impl-CF0ts8Fz2.mjs} +2 -2
- package/dist/{impl-hwpT9u5o2.mjs.map → impl-CF0ts8Fz2.mjs.map} +1 -1
- package/dist/{impl-DK7nSMle2.mjs → impl-CMK8Qm_I2.mjs} +2 -2
- package/dist/{impl-DK7nSMle2.mjs.map → impl-CMK8Qm_I2.mjs.map} +1 -1
- package/dist/{impl-CQVy2k3o.mjs → impl-CQtMFz1O.mjs} +2 -2
- package/dist/{impl-CQVy2k3o.mjs.map → impl-CQtMFz1O.mjs.map} +1 -1
- package/dist/{impl-CyQRmuM72.mjs → impl-CSRal4Rj2.mjs} +2 -2
- package/dist/{impl-CyQRmuM72.mjs.map → impl-CSRal4Rj2.mjs.map} +1 -1
- package/dist/{impl-Bc6p8A1l2.mjs → impl-CSmFd6iO2.mjs} +2 -2
- package/dist/{impl-Bc6p8A1l2.mjs.map → impl-CSmFd6iO2.mjs.map} +1 -1
- package/dist/{impl-CwKYKBYb.mjs → impl-CfMrFWb_.mjs} +2 -2
- package/dist/{impl-CwKYKBYb.mjs.map → impl-CfMrFWb_.mjs.map} +1 -1
- package/dist/{impl-Dw8NYkzw.mjs → impl-DInF5q00.mjs} +2 -2
- package/dist/{impl-Dw8NYkzw.mjs.map → impl-DInF5q00.mjs.map} +1 -1
- package/dist/{impl-xq89cSSz2.mjs → impl-DKNJFnFv2.mjs} +2 -2
- package/dist/{impl-xq89cSSz2.mjs.map → impl-DKNJFnFv2.mjs.map} +1 -1
- package/dist/{impl-BXUYpR27.mjs → impl-DOuVyX0O.mjs} +2 -2
- package/dist/{impl-BXUYpR27.mjs.map → impl-DOuVyX0O.mjs.map} +1 -1
- package/dist/{impl-2iVTxNn4.mjs → impl-DRW2qfyk.mjs} +2 -2
- package/dist/{impl-2iVTxNn4.mjs.map → impl-DRW2qfyk.mjs.map} +1 -1
- package/dist/{impl-DVQmuZQY.mjs → impl-DkHzw1nR.mjs} +2 -2
- package/dist/{impl-DVQmuZQY.mjs.map → impl-DkHzw1nR.mjs.map} +1 -1
- package/dist/{impl-XrTL-TDl.mjs → impl-Dv8ecMWN.mjs} +2 -2
- package/dist/{impl-XrTL-TDl.mjs.map → impl-Dv8ecMWN.mjs.map} +1 -1
- package/dist/{impl-DNzkRayg.mjs → impl-IFoIxW9s.mjs} +2 -2
- package/dist/{impl-DNzkRayg.mjs.map → impl-IFoIxW9s.mjs.map} +1 -1
- package/dist/{impl-INhq_CiK.mjs → impl-WxoE0bN_.mjs} +2 -2
- package/dist/{impl-INhq_CiK.mjs.map → impl-WxoE0bN_.mjs.map} +1 -1
- package/dist/{impl-BOawPhYE.mjs → impl-Z_ZuLfFK.mjs} +2 -2
- package/dist/{impl-BOawPhYE.mjs.map → impl-Z_ZuLfFK.mjs.map} +1 -1
- package/dist/{impl-DNe-gRXe2.mjs → impl-_erU3Uzt2.mjs} +2 -2
- package/dist/{impl-DNe-gRXe2.mjs.map → impl-_erU3Uzt2.mjs.map} +1 -1
- package/dist/{impl-CwXp3Tbr.mjs → impl-dXDmiiG6.mjs} +2 -2
- package/dist/{impl-CwXp3Tbr.mjs.map → impl-dXDmiiG6.mjs.map} +1 -1
- package/dist/{impl-CvLI_Jig.mjs → impl-lcLJ4Wp-.mjs} +2 -2
- package/dist/{impl-CvLI_Jig.mjs.map → impl-lcLJ4Wp-.mjs.map} +1 -1
- package/dist/{impl-DLG0Egy6.mjs → impl-nvYE0p_K.mjs} +2 -2
- package/dist/{impl-DLG0Egy6.mjs.map → impl-nvYE0p_K.mjs.map} +1 -1
- package/dist/{impl-BH_A5rgL.mjs → impl-xKt-NwTT.mjs} +2 -2
- package/dist/{impl-BH_A5rgL.mjs.map → impl-xKt-NwTT.mjs.map} +1 -1
- package/dist/{impl-CL29fOWM.mjs → impl-ymZeayvp.mjs} +2 -2
- package/dist/{impl-CL29fOWM.mjs.map → impl-ymZeayvp.mjs.map} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{markRequestDataSiloIdsCompleted-B5N-cQWr.mjs → markRequestDataSiloIdsCompleted-2DHClQ32.mjs} +2 -2
- package/dist/{markRequestDataSiloIdsCompleted-B5N-cQWr.mjs.map → markRequestDataSiloIdsCompleted-2DHClQ32.mjs.map} +1 -1
- package/dist/{markSilentPrivacyRequests-BiaButWF.mjs → markSilentPrivacyRequests-BUYzKbhW.mjs} +2 -2
- package/dist/{markSilentPrivacyRequests-BiaButWF.mjs.map → markSilentPrivacyRequests-BUYzKbhW.mjs.map} +1 -1
- package/dist/{notifyPrivacyRequestsAdditionalTime-D3Vtvg5G.mjs → notifyPrivacyRequestsAdditionalTime-G8IZ0Ooy.mjs} +2 -2
- package/dist/{notifyPrivacyRequestsAdditionalTime-D3Vtvg5G.mjs.map → notifyPrivacyRequestsAdditionalTime-G8IZ0Ooy.mjs.map} +1 -1
- package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-D85P1W_8.mjs → pullChunkedCustomSiloOutstandingIdentifiers-BxolFAfF.mjs} +2 -2
- package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-D85P1W_8.mjs.map → pullChunkedCustomSiloOutstandingIdentifiers-BxolFAfF.mjs.map} +1 -1
- package/dist/{pullManualEnrichmentIdentifiersToCsv-DbNSrKEk.mjs → pullManualEnrichmentIdentifiersToCsv-DcLZeqF2.mjs} +2 -2
- package/dist/{pullManualEnrichmentIdentifiersToCsv-DbNSrKEk.mjs.map → pullManualEnrichmentIdentifiersToCsv-DcLZeqF2.mjs.map} +1 -1
- package/dist/{pushCronIdentifiersFromCsv-5ruUKHtL.mjs → pushCronIdentifiersFromCsv-CVTCk6s3.mjs} +2 -2
- package/dist/{pushCronIdentifiersFromCsv-5ruUKHtL.mjs.map → pushCronIdentifiersFromCsv-CVTCk6s3.mjs.map} +1 -1
- package/dist/{pushManualEnrichmentIdentifiersFromCsv-B0i2239u.mjs → pushManualEnrichmentIdentifiersFromCsv-BIkBbKfs.mjs} +2 -2
- package/dist/{pushManualEnrichmentIdentifiersFromCsv-B0i2239u.mjs.map → pushManualEnrichmentIdentifiersFromCsv-BIkBbKfs.mjs.map} +1 -1
- package/dist/{removeUnverifiedRequestIdentifiers-QmeqrmxM.mjs → removeUnverifiedRequestIdentifiers-CzEvT_WR.mjs} +2 -2
- package/dist/{removeUnverifiedRequestIdentifiers-QmeqrmxM.mjs.map → removeUnverifiedRequestIdentifiers-CzEvT_WR.mjs.map} +1 -1
- package/dist/{retryRequestDataSilos-BfckLjOJ.mjs → retryRequestDataSilos-C2csdZmC.mjs} +2 -2
- package/dist/{retryRequestDataSilos-BfckLjOJ.mjs.map → retryRequestDataSilos-C2csdZmC.mjs.map} +1 -1
- package/dist/{skipPreflightJobs-Do_kwu3m.mjs → skipPreflightJobs-CB_lGpri.mjs} +2 -2
- package/dist/{skipPreflightJobs-Do_kwu3m.mjs.map → skipPreflightJobs-CB_lGpri.mjs.map} +1 -1
- package/dist/{skipRequestDataSilos-BNDhdllD.mjs → skipRequestDataSilos-Bf85wXUC.mjs} +2 -2
- package/dist/{skipRequestDataSilos-BNDhdllD.mjs.map → skipRequestDataSilos-Bf85wXUC.mjs.map} +1 -1
- package/dist/{streamPrivacyRequestsToCsv-CbJfhV6A.mjs → streamPrivacyRequestsToCsv-CPwLKjTm.mjs} +2 -2
- package/dist/{streamPrivacyRequestsToCsv-CbJfhV6A.mjs.map → streamPrivacyRequestsToCsv-CPwLKjTm.mjs.map} +1 -1
- package/dist/{updateConsentManagerVersionToLatest-DEFwH4Se.mjs → updateConsentManagerVersionToLatest-ikIE5dHp.mjs} +2 -2
- package/dist/{updateConsentManagerVersionToLatest-DEFwH4Se.mjs.map → updateConsentManagerVersionToLatest-ikIE5dHp.mjs.map} +1 -1
- package/dist/{uploadConsents-ChmFIw_j.mjs → uploadConsents-BrWpoV6_.mjs} +2 -2
- package/dist/{uploadConsents-ChmFIw_j.mjs.map → uploadConsents-BrWpoV6_.mjs.map} +1 -1
- package/dist/{uploadPrivacyRequestsFromCsv-D3KSb1qH.mjs → uploadPrivacyRequestsFromCsv-BuB0-XpH.mjs} +2 -2
- package/dist/{uploadPrivacyRequestsFromCsv-D3KSb1qH.mjs.map → uploadPrivacyRequestsFromCsv-BuB0-XpH.mjs.map} +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-DK7nSMle2.mjs","names":["POLICY_SKILL_MD","POLICY_SETUP_TOOLING_REFERENCE_MD","POLICY_AUTHORING_REFERENCE_MD","POLICY_TESTING_DEBUGGING_REFERENCE_MD","POLICY_PUBLISHING_REFERENCE_MD","CLI_VERSION"],"sources":["../src/lib/policy/policy-project-discovery.ts","../src/lib/policy/policy-scaffold-model.ts","../../../skills/transcend-policy-engine/references/authoring.md","../../../skills/transcend-policy-engine/references/publishing.md","../../../skills/transcend-policy-engine/references/setup-tooling.md","../../../skills/transcend-policy-engine/references/testing-debugging.md","../../../skills/transcend-policy-engine/SKILL.md","../src/lib/policy/policy-skill.ts","../src/lib/policy/policy-scaffold-output.ts","../src/lib/policy/policy-scaffold-templates.ts","../src/lib/policy/policy-scaffold-artifacts.ts","../src/lib/policy/policy-scaffold-config.ts","../src/lib/policy/policy-scaffold-planning.ts","../src/commands/policy/init/impl.ts"],"sourcesContent":["import { join, resolve } from 'node:path';\n\nimport type { LocalContext } from '../../context.js';\nimport {\n collectProjectRelativePaths,\n discoverProjectRepository,\n} from '../scaffolding/project-discovery.js';\nimport type { PolicyProjectState } from './policy-scaffold-model.js';\n\n/** Default local policy project directory. */\nexport const DEFAULT_POLICY_PROJECT_DIRECTORY = 'transcend/policy';\n\n/**\n * Collect repository state required by the pure policy planner.\n *\n * @param context - CLI context\n * @param directory - User-selected target directory\n * @returns Policy project discovery state\n */\nexport function discoverPolicyProject(\n context: LocalContext,\n directory: string = DEFAULT_POLICY_PROJECT_DIRECTORY,\n): PolicyProjectState {\n const invocationDirectory = context.process.cwd();\n const targetDirectory = resolve(invocationDirectory, directory);\n if (\n context.fs.existsSync(targetDirectory) &&\n !context.fs.statSync(targetDirectory).isDirectory()\n ) {\n throw new Error(`Policy target is not a directory: ${targetDirectory}`);\n }\n const repository = discoverProjectRepository(context, {\n invocationDirectory,\n targetDirectory,\n standaloneProjectRoot: invocationDirectory,\n });\n return {\n invocationDirectory,\n targetDirectory,\n ...repository,\n relativePaths: collectProjectRelativePaths(context, targetDirectory),\n relativeFilePaths: collectProjectRelativePaths(context, targetDirectory, {\n includeDirectories: false,\n }),\n };\n}\n\n/**\n * Resolve the bundle manifest path for a discovered project.\n *\n * @param state - Policy project state\n * @returns Absolute manifest path\n */\nexport function getPolicyManifestPath(state: PolicyProjectState): string {\n return join(state.targetDirectory, 'manifest.json');\n}\n","import type { ExistingProjectSkillDirectory } from '../scaffolding/agent-skill.js';\nimport type { ProjectPlan } from '../scaffolding/project-plan.js';\n\n/** Version of the stable policy initialization JSON result. */\nexport const POLICY_INIT_RESULT_VERSION = 1 as const;\n\n/** Optional repository integrations for policy authoring. */\nexport const PolicySetupFeature = {\n /** Repository-level editor configuration. */\n Editor: 'editor',\n /** Managed policy authoring skill. */\n Skill: 'skill',\n /** Credential-free continuous integration. */\n Ci: 'ci',\n} as const;\n\n/** Optional repository integration for policy authoring. */\nexport type PolicySetupFeature = (typeof PolicySetupFeature)[keyof typeof PolicySetupFeature];\n\n/** Repository and target state collected before policy planning. */\nexport interface PolicyProjectState {\n /** Directory from which the CLI was invoked. */\n invocationDirectory: string;\n /** Absolute user-selected policy directory. */\n targetDirectory: string;\n /** Repository or invocation root that owns setup artifacts. */\n projectRoot: string;\n /** Nearest repository root, when present. */\n repositoryRoot?: string;\n /** Existing project-level skill directories. */\n existingSkillDirectories: ExistingProjectSkillDirectory[];\n /** Whether the repository appears to use GitHub. */\n usesGithub: boolean;\n /** Case-preserving relative paths below the policy directory. */\n relativePaths: string[];\n /** Relative file and link paths below the policy directory. */\n relativeFilePaths: string[];\n}\n\n/** A complete, validated policy initialization plan. */\nexport interface PolicyInitProjectPlan extends ProjectPlan {\n /** JSON contract version. */\n version: typeof POLICY_INIT_RESULT_VERSION;\n /** Command that produced the plan. */\n command: 'init';\n /** Absolute policy project directory. */\n targetDirectory: string;\n /** Absolute policy manifest path. */\n manifestPath: string;\n /** Files inspected and deliberately left unchanged. */\n unchanged: string[];\n /** Non-fatal plan warnings. */\n warnings: string[];\n /** Raw commands shown after a successful apply. */\n nextSteps: string[];\n /** Exact generated example that remains safe to replace. */\n disposableExamplePath?: string;\n /** Selected repository integrations. */\n features: PolicySetupFeature[];\n}\n",null,null,null,null,null,"import POLICY_AUTHORING_REFERENCE_MD from '../../../../../skills/transcend-policy-engine/references/authoring.md';\nimport POLICY_PUBLISHING_REFERENCE_MD from '../../../../../skills/transcend-policy-engine/references/publishing.md';\nimport POLICY_SETUP_TOOLING_REFERENCE_MD from '../../../../../skills/transcend-policy-engine/references/setup-tooling.md';\nimport POLICY_TESTING_DEBUGGING_REFERENCE_MD from '../../../../../skills/transcend-policy-engine/references/testing-debugging.md';\nimport POLICY_SKILL_MD from '../../../../../skills/transcend-policy-engine/SKILL.md';\nimport type { AgentSkillFile } from '../scaffolding/agent-skill.js';\n\n/** Namespaced directory and frontmatter name for the installed Agent Skill. */\nexport const POLICY_SKILL_NAME = 'transcend-policy-engine';\n\nexport {\n POLICY_AUTHORING_REFERENCE_MD,\n POLICY_PUBLISHING_REFERENCE_MD,\n POLICY_SETUP_TOOLING_REFERENCE_MD,\n POLICY_SKILL_MD,\n POLICY_TESTING_DEBUGGING_REFERENCE_MD,\n};\n\n/** Complete portable Policy Engine Agent Skill file set. */\nexport const POLICY_SKILL_FILES: readonly AgentSkillFile[] = [\n { path: 'SKILL.md', contents: POLICY_SKILL_MD },\n { path: 'references/setup-tooling.md', contents: POLICY_SETUP_TOOLING_REFERENCE_MD },\n { path: 'references/authoring.md', contents: POLICY_AUTHORING_REFERENCE_MD },\n { path: 'references/testing-debugging.md', contents: POLICY_TESTING_DEBUGGING_REFERENCE_MD },\n { path: 'references/publishing.md', contents: POLICY_PUBLISHING_REFERENCE_MD },\n];\n","import {\n toPublicPlannedChange,\n type PublicPlannedChange,\n} from '../scaffolding/project-plan-output.js';\nimport type { PolicyInitProjectPlan, PolicySetupFeature } from './policy-scaffold-model.js';\nimport { POLICY_SKILL_NAME } from './policy-skill.js';\n\n/** Detected local policy tool versions. */\nexport interface PolicyInitToolVersions {\n /** OPA version, or null when missing or incompatible. */\n opa: string | null;\n /** Regal version, or null when missing or incompatible. */\n regal: string | null;\n}\n\n/** Stable machine-readable policy initialization result. */\nexport interface PolicyInitPlanResult {\n /** JSON contract version. */\n version: number;\n /** Command that produced the result. */\n command: 'init';\n /** Whether the plan was applied. */\n applied: boolean;\n /** Whether this was a dry run. */\n dryRun: boolean;\n /** Absolute policy target directory. */\n targetDirectory: string;\n /** Absolute policy manifest path. */\n manifestPath: string;\n /** Planned mutations without file contents. */\n changes: PublicPlannedChange[];\n /** Non-fatal preservation and runtime warnings. */\n warnings: string[];\n /** Suggested raw one-line follow-up commands. */\n nextSteps: string[];\n /** Explicitly selected repository integrations. */\n features: PolicySetupFeature[];\n /** Compact prompt for continuing with a coding agent. */\n aiHandoff: string;\n /** Compatible local policy tool versions. */\n tools: PolicyInitToolVersions;\n}\n\n/**\n * Build the compact policy implementation and CI handoff.\n *\n * @param options - Portable example path and lint command\n * @returns Raw one-line prompt\n */\nexport function buildPolicyInitAiHandoff(options: {\n /** Display path to the policy project. */\n projectPath: string;\n /** Display path to an exact disposable example. */\n examplePath?: string;\n /** Whether the policy authoring skill was installed. */\n hasSkill: boolean;\n /** Copyable lint command. */\n lintCommand: string;\n}): string {\n if (!options.examplePath) {\n const instruction = options.hasSkill\n ? `Use the \\`${POLICY_SKILL_NAME}\\` skill to review`\n : 'Review';\n return (\n `${instruction} the existing policy project in ${options.projectPath}, ` +\n `align its document tree and input/output contract with the intended application, adapt ` +\n `repository validation as needed, and rerun ${options.lintCommand}.`\n );\n }\n const instruction = options.hasSkill\n ? `Use the \\`${POLICY_SKILL_NAME}\\` skill to replace`\n : 'Replace';\n return (\n `${instruction} the disposable example in ${options.examplePath} with ` +\n `the intended policy document tree and input/output contract, adapt repository validation ` +\n `to local conventions, and rerun ${options.lintCommand}.`\n );\n}\n\n/**\n * Build the stable machine-readable initialization result.\n *\n * @param plan - Policy project plan\n * @param options - Apply and runtime state\n * @returns Public JSON result\n */\nexport function buildPolicyInitPlanResult(\n plan: PolicyInitProjectPlan,\n options: {\n /** Whether the plan was applied. */\n applied: boolean;\n /** Whether this was a dry run. */\n dryRun: boolean;\n /** Working directory for portable paths. */\n cwd: string;\n /** Compact coding-agent prompt. */\n aiHandoff: string;\n /** Compatible local policy tool versions. */\n tools: PolicyInitToolVersions;\n },\n): PolicyInitPlanResult {\n return {\n version: plan.version,\n command: plan.command,\n applied: options.applied,\n dryRun: options.dryRun,\n targetDirectory: plan.targetDirectory,\n manifestPath: plan.manifestPath,\n changes: plan.changes.map((change) => toPublicPlannedChange(options.cwd, change)),\n warnings: plan.warnings,\n nextSteps: plan.nextSteps,\n features: [...plan.features],\n aiHandoff: options.aiHandoff,\n tools: options.tools,\n };\n}\n","/** OPA version targeted by generated policy authoring configuration. */\nexport const POLICY_STARTER_OPA_VERSION = '1.13.1';\n\n/** One deterministic file in the safe policy starter. */\nexport interface PolicyStarterFile {\n /** POSIX-style path relative to the policy directory. */\n path: string;\n /** Complete UTF-8 file contents. */\n contents: string;\n /** Human-readable reason shown in the plan. */\n description: string;\n}\n\n/** Publishable Policy Engine bundle manifest. */\nexport const POLICY_MANIFEST_TEMPLATE = `{\n \"roots\": [\"policy_engine\"]\n}\n`;\n\n/** Strict Regal project configuration pinned to the deployed OPA capabilities. */\nexport const POLICY_REGAL_CONFIG_TEMPLATE = `capabilities:\n from:\n engine: opa\n version: v${POLICY_STARTER_OPA_VERSION}\nproject:\n roots:\n - .\n rego-version: 1\n`;\n\n/** Disposable, fail-closed example policy. */\nexport const POLICY_RESULT_REGO_TEMPLATE = `package policy_engine.example\n\nimport rego.v1\n\n# METADATA\n# title: Disposable example result\n# description: |\n# A fail-closed teaching entrypoint. Replace this example with the document\n# tree and result contract required by your application.\n# entrypoint: true\ndefault result := {\n\t\"decision\": \"deny\",\n\t\"reason_code\": \"untrusted_or_invalid_input\",\n}\n\nresult := {\n\t\"decision\": \"allow\",\n\t\"reason_code\": \"trusted_subject\",\n} if {\n\tinput.subject.trusted == true\n}\n`;\n\n/** Executable tests adjacent to the disposable example policy. */\nexport const POLICY_RESULT_TEST_REGO_TEMPLATE = `package policy_engine.example_test\n\nimport data.policy_engine.example\nimport rego.v1\n\ntest_denies_untrusted_subject if {\n\tresult := example.result with input as {\"subject\": {\"trusted\": false}}\n\tresult == {\n\t\t\"decision\": \"deny\",\n\t\t\"reason_code\": \"untrusted_or_invalid_input\",\n\t}\n}\n\ntest_fails_closed_for_missing_subject if {\n\tresult := example.result with input as {}\n\tresult == {\n\t\t\"decision\": \"deny\",\n\t\t\"reason_code\": \"untrusted_or_invalid_input\",\n\t}\n}\n\ntest_allows_trusted_subject if {\n\tresult := example.result with input as {\"subject\": {\"trusted\": true}}\n\tresult == {\n\t\t\"decision\": \"allow\",\n\t\t\"reason_code\": \"trusted_subject\",\n\t}\n}\n`;\n\n/** Sanitized local input example containing no credentials or personal data. */\nexport const POLICY_INPUT_EXAMPLE_TEMPLATE = `{\n \"subject\": {\n \"trusted\": false\n }\n}\n`;\n\n/** Target-local ignore rules for private evaluation input only. */\nexport const POLICY_GITIGNORE_TEMPLATE = `# Local policy evaluation input.\n/input.json\n`;\n\n/** Concise project-local authoring guide. */\nexport const POLICY_README_TEMPLATE = `# Transcend Policy Project\n\nThis directory is an OPA document tree that can be published to Transcend Policy Engine.\n\nThe policy under \\`policy_engine/example\\` is disposable teaching material. Replace it with your intended package tree, input shape, and extensible result documents. Keep decisions fail-closed and cover every non-test package with \\`manifest.json\\`.\n\nValidate formatting, strict Rego v1 compatibility, Regal lint, tests, and the publish contract:\n\n\\`\\`\\`sh\ntranscend policy lint --dir .\n\\`\\`\\`\n`;\n\n/** Complete safe starter in deterministic plan order. */\nconst POLICY_STARTER_FILES: readonly PolicyStarterFile[] = [\n {\n path: 'manifest.json',\n contents: POLICY_MANIFEST_TEMPLATE,\n description: 'Create the publishable Policy Engine manifest',\n },\n {\n path: '.regal/config.yaml',\n contents: POLICY_REGAL_CONFIG_TEMPLATE,\n description: 'Pin strict Rego v1 linting to OPA 1.13.1 capabilities',\n },\n {\n path: 'policy_engine/example/result.rego',\n contents: POLICY_RESULT_REGO_TEMPLATE,\n description: 'Create a documented fail-closed result entrypoint',\n },\n {\n path: 'policy_engine/example/result_test.rego',\n contents: POLICY_RESULT_TEST_REGO_TEMPLATE,\n description: 'Create executable tests for allow and fail-closed decisions',\n },\n {\n path: 'input.example.json',\n contents: POLICY_INPUT_EXAMPLE_TEMPLATE,\n description: 'Create a sanitized local evaluation input',\n },\n {\n path: '.gitignore',\n contents: POLICY_GITIGNORE_TEMPLATE,\n description: 'Ignore only the private local input file',\n },\n {\n path: 'README.md',\n contents: POLICY_README_TEMPLATE,\n description: 'Create the concise policy project guide',\n },\n];\n\n/**\n * Generate an independent copy of the safe policy starter.\n *\n * @returns Deterministic relative files\n */\nexport function generatePolicyStarterFiles(): PolicyStarterFile[] {\n return POLICY_STARTER_FILES.map((file) => ({ ...file }));\n}\n","import { posix } from 'node:path';\n\nimport { POLICY_STARTER_OPA_VERSION } from './policy-scaffold-templates.js';\n\n/** Regal version pinned by generated policy validation. */\nexport const POLICY_STARTER_REGAL_VERSION = '0.42.0';\n\n/** Repository-relative generated workflow path. */\nexport const POLICY_CI_WORKFLOW_PATH = '.github/workflows/transcend-policy.yml';\n\n/** Immutable actions/checkout v6 release commit. */\nexport const ACTIONS_CHECKOUT_SHA = 'd23441a48e516b6c34aea4fa41551a30e30af803';\n\n/** Immutable open-policy-agent/setup-opa v2.4.0 release commit. */\nexport const SETUP_OPA_SHA = 'b2b258e089860efaadaaf71bf6e3aecb4a3eeff1';\n\n/** Immutable open-policy-agent/setup-regal v2.0.0 release commit. */\nexport const SETUP_REGAL_SHA = '761188c3b435761fa254beca508a44875619648f';\n\n/**\n * Prefix a path below the repository-relative policy target.\n *\n * @param targetDirectory - POSIX repository-relative target\n * @param child - POSIX target-relative path or pattern\n * @returns Repository-relative path or pattern\n */\nfunction targetPath(targetDirectory: string, child: string): string {\n return targetDirectory === '.' ? child : posix.join(targetDirectory, child);\n}\n\n/**\n * Generate credential-free, validation-only Policy Engine CI.\n *\n * @param options - Repository paths and exact CLI release\n * @returns Complete GitHub Actions workflow YAML\n */\nexport function generatePolicyGithubActionsWorkflow(options: {\n /** Exact released Transcend CLI version. */\n cliVersion: string;\n /** Policy directory relative to the repository root. */\n targetDirectory: string;\n}): string {\n const watchedPaths = [\n targetPath(options.targetDirectory, '**/*.rego'),\n targetPath(options.targetDirectory, '**/*.json'),\n targetPath(options.targetDirectory, '**/*.yaml'),\n targetPath(options.targetDirectory, '**/*.yml'),\n targetPath(options.targetDirectory, '.regal/config.yaml'),\n targetPath(options.targetDirectory, '.regal.yaml'),\n POLICY_CI_WORKFLOW_PATH,\n ];\n const pathFilters = watchedPaths.map((path) => ` - ${JSON.stringify(path)}`).join('\\n');\n\n return `# Generated by transcend policy init.\nname: Transcend Policy\n\non:\n pull_request:\n paths:\n${pathFilters}\n push:\n paths:\n${pathFilters}\n\npermissions:\n contents: read\n\njobs:\n lint:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@${ACTIONS_CHECKOUT_SHA} # v6\n - name: Set up OPA\n uses: open-policy-agent/setup-opa@${SETUP_OPA_SHA} # v2.4.0\n with:\n version: ${JSON.stringify(POLICY_STARTER_OPA_VERSION)}\n - name: Set up Regal\n uses: open-policy-agent/setup-regal@${SETUP_REGAL_SHA} # v2.0.0\n with:\n version: ${JSON.stringify(POLICY_STARTER_REGAL_VERSION)}\n - name: Install the Transcend CLI\n run: npm install --global @transcend-io/cli@${options.cliVersion}\n - name: Validate Policy Engine project\n env:\n POLICY_DIRECTORY: ${JSON.stringify(options.targetDirectory)}\n run: >-\n transcend policy lint\n --dir \"$POLICY_DIRECTORY\"\n --noInteractive\n --json\n`;\n}\n","import { relative, sep } from 'node:path';\n\nimport {\n mergeJsonc,\n mergeStringArray,\n parseJsoncObject,\n type JsoncUpdate,\n} from '../scaffolding/jsonc.js';\n\n/** Recommended VS Code extension for OPA and Regal authoring. */\nexport const POLICY_VSCODE_EXTENSION = 'tsandall.opa';\n\n/** Conflicting syntax-only VS Code extension. */\nexport const CONFLICTING_POLICY_VSCODE_EXTENSION = 'glebbash.opa-highlight-only';\n\n/** Result of safely merging one repository editor artifact. */\nexport interface PolicyEditorMergeResult {\n /** Complete merged contents, or the unchanged original when unsafe. */\n contents: string;\n /** Actionable preservation warnings. */\n warnings: string[];\n}\n\n/** One desired scalar setting that must not replace a customization. */\ninterface DesiredSetting {\n /** JSONC object path. */\n path: string[];\n /** Desired generated value. */\n value: unknown;\n /** Human-readable setting key. */\n label: string;\n}\n\n/**\n * Compare JSON-compatible configuration values.\n *\n * @param left - Existing value\n * @param right - Desired value\n * @returns Whether the values are structurally equal\n */\nfunction configurationValuesEqual(left: unknown, right: unknown): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\n/**\n * Parse an editor object while preserving malformed existing content.\n *\n * @param contents - Existing JSONC, or null\n * @param label - Configuration label\n * @returns Parsed object or a preservation result\n */\nfunction parseEditorObject(\n contents: string | null,\n label: string,\n):\n | {\n /** Parsed JSONC object. */\n current: Record<string, unknown>;\n }\n | {\n /** Complete unchanged contents. */\n contents: string;\n /** Actionable warning. */\n warning: string;\n } {\n try {\n return { current: parseJsoncObject(contents ?? '{}\\n', label) };\n } catch (error) {\n return {\n contents: contents ?? '{}\\n',\n warning: `${error instanceof Error ? error.message : String(error)} Existing content was left unchanged.`,\n };\n }\n}\n\n/**\n * Apply safe JSONC updates or preserve the existing file when comments prevent it.\n *\n * @param contents - Existing JSONC\n * @param updates - Proven-safe updates\n * @param label - Configuration label\n * @param warnings - Existing merge warnings\n * @returns Complete contents and warnings\n */\nfunction applyEditorUpdates(\n contents: string | null,\n updates: readonly JsoncUpdate[],\n label: string,\n warnings: string[],\n): PolicyEditorMergeResult {\n if (updates.length === 0) {\n return { contents: contents ?? '{}\\n', warnings };\n }\n try {\n return {\n contents: mergeJsonc(contents, updates, label),\n warnings,\n };\n } catch (error) {\n return {\n contents: contents ?? '{}\\n',\n warnings: [\n ...warnings,\n `${error instanceof Error ? error.message : String(error)} Existing content was left unchanged.`,\n ],\n };\n }\n}\n\n/**\n * Add absent scalar settings without replacing repository customizations.\n *\n * @param current - Parsed editor object\n * @param desired - Desired settings\n * @param updates - Safe updates to append to\n * @param warnings - Conflict warnings to append to\n */\nfunction collectSafeScalarUpdates(\n current: Record<string, unknown>,\n desired: readonly DesiredSetting[],\n updates: JsoncUpdate[],\n warnings: string[],\n): void {\n desired.forEach(({ path, value, label }) => {\n const existing = path.reduce<unknown>((parent, key) => {\n return parent && typeof parent === 'object' && !Array.isArray(parent)\n ? (parent as Record<string, unknown>)[key]\n : undefined;\n }, current);\n if (existing === undefined) {\n updates.push({ path, value });\n } else if (!configurationValuesEqual(existing, value)) {\n warnings.push(\n `VS Code setting \"${label}\" has a repository-specific value and was left unchanged.`,\n );\n }\n });\n}\n\n/**\n * Build the workspace-relative OPA bundle root.\n *\n * @param repositoryRoot - Root that owns `.vscode`\n * @param targetDirectory - Selected policy project directory\n * @returns VS Code workspace path\n */\nfunction buildOpaWorkspaceRoot(repositoryRoot: string, targetDirectory: string): string {\n const target = relative(repositoryRoot, targetDirectory).split(sep).join('/') || '.';\n return target === '.' ? '${workspaceFolder}' : `\\${workspaceFolder}/${target}`;\n}\n\n/**\n * Merge strict target-scoped OPA and Rego editor settings.\n *\n * Setting names match the authoritative `open-policy-agent/vscode-opa`\n * extension metadata. Existing conflicting values are preserved and reported.\n *\n * @param contents - Existing `.vscode/settings.json` JSONC\n * @param repositoryRoot - Root that owns `.vscode`\n * @param targetDirectory - Selected policy project directory\n * @returns Merged settings and conflict warnings\n */\nexport function mergePolicyEditorSettings(\n contents: string | null,\n repositoryRoot: string,\n targetDirectory: string,\n): PolicyEditorMergeResult {\n const parsed = parseEditorObject(contents, 'VS Code policy settings');\n if ('warning' in parsed) {\n return { contents: parsed.contents, warnings: [parsed.warning] };\n }\n const { current } = parsed;\n const updates: JsoncUpdate[] = [];\n const warnings: string[] = [];\n\n const roots = current['opa.roots'];\n const desiredRoot = buildOpaWorkspaceRoot(repositoryRoot, targetDirectory);\n if (roots === undefined) {\n updates.push({ path: ['opa.roots'], value: [desiredRoot] });\n } else if (Array.isArray(roots) && roots.every((value) => typeof value === 'string')) {\n const merged = mergeStringArray(roots, [desiredRoot]);\n if (!configurationValuesEqual(merged, roots)) {\n updates.push({ path: ['opa.roots'], value: merged });\n }\n } else {\n warnings.push('VS Code setting \"opa.roots\" is customized and was left unchanged.');\n }\n\n collectSafeScalarUpdates(\n current,\n [\n { path: ['opa.checkOnSave'], value: true, label: 'opa.checkOnSave' },\n { path: ['opa.strictMode'], value: true, label: 'opa.strictMode' },\n { path: ['opa.bundleMode'], value: true, label: 'opa.bundleMode' },\n { path: ['opa.formatter'], value: 'opa-fmt-rego-v1', label: 'opa.formatter' },\n ],\n updates,\n warnings,\n );\n\n const regoSettings = current['[rego]'];\n if (regoSettings === undefined) {\n updates.push({\n path: ['[rego]'],\n value: {\n 'editor.defaultFormatter': POLICY_VSCODE_EXTENSION,\n 'editor.formatOnSave': true,\n 'editor.insertSpaces': false,\n 'editor.tabSize': 4,\n },\n });\n } else if (\n regoSettings !== null &&\n typeof regoSettings === 'object' &&\n !Array.isArray(regoSettings)\n ) {\n collectSafeScalarUpdates(\n current,\n [\n {\n path: ['[rego]', 'editor.defaultFormatter'],\n value: POLICY_VSCODE_EXTENSION,\n label: '[rego].editor.defaultFormatter',\n },\n {\n path: ['[rego]', 'editor.formatOnSave'],\n value: true,\n label: '[rego].editor.formatOnSave',\n },\n {\n path: ['[rego]', 'editor.insertSpaces'],\n value: false,\n label: '[rego].editor.insertSpaces',\n },\n {\n path: ['[rego]', 'editor.tabSize'],\n value: 4,\n label: '[rego].editor.tabSize',\n },\n ],\n updates,\n warnings,\n );\n } else {\n warnings.push('VS Code language setting \"[rego]\" is customized and was left unchanged.');\n }\n\n return applyEditorUpdates(contents, updates, 'VS Code policy settings', warnings);\n}\n\n/**\n * Merge OPA extension recommendations without disturbing unknown entries.\n *\n * VS Code's `extensions.json` schema supports `unwantedRecommendations`, so\n * the syntax-only extension can be removed from recommendations and discouraged.\n *\n * @param contents - Existing `.vscode/extensions.json` JSONC\n * @returns Merged extension recommendations and warnings\n */\nexport function mergePolicyEditorExtensions(contents: string | null): PolicyEditorMergeResult {\n const parsed = parseEditorObject(contents, 'VS Code policy extension recommendations');\n if ('warning' in parsed) {\n return { contents: parsed.contents, warnings: [parsed.warning] };\n }\n const { current } = parsed;\n const updates: JsoncUpdate[] = [];\n const warnings: string[] = [];\n\n const recommendations = current.recommendations;\n if (\n recommendations === undefined ||\n (Array.isArray(recommendations) && recommendations.every((value) => typeof value === 'string'))\n ) {\n const existing = recommendations ?? [];\n const desired = mergeStringArray(existing, [POLICY_VSCODE_EXTENSION]).filter(\n (value) => value !== CONFLICTING_POLICY_VSCODE_EXTENSION,\n );\n if (!configurationValuesEqual(existing, desired)) {\n updates.push({ path: ['recommendations'], value: desired });\n }\n } else {\n warnings.push(\n 'VS Code extension recommendations use an unknown shape and were left unchanged.',\n );\n }\n\n const unwanted = current.unwantedRecommendations;\n if (\n unwanted === undefined ||\n (Array.isArray(unwanted) && unwanted.every((value) => typeof value === 'string'))\n ) {\n const existing = unwanted ?? [];\n const desired = mergeStringArray(existing, [CONFLICTING_POLICY_VSCODE_EXTENSION]);\n if (!configurationValuesEqual(existing, desired)) {\n updates.push({ path: ['unwantedRecommendations'], value: desired });\n }\n } else {\n warnings.push(\n 'VS Code unwanted extension recommendations use an unknown shape and were left unchanged.',\n );\n }\n\n return applyEditorUpdates(\n contents,\n updates,\n 'VS Code policy extension recommendations',\n warnings,\n );\n}\n\n/**\n * Build the generated target-scoped VS Code lint task.\n *\n * @param repositoryRoot - Root that owns `.vscode`\n * @param targetDirectory - Selected policy project directory\n * @returns VS Code task object\n */\nexport function buildPolicyLintTask(\n repositoryRoot: string,\n targetDirectory: string,\n): Record<string, unknown> {\n const target = relative(repositoryRoot, targetDirectory).split(sep).join('/') || '.';\n return {\n label: 'policy: lint',\n type: 'process',\n command: 'transcend',\n args: ['policy', 'lint', '--dir', target, '--noInteractive'],\n group: {\n kind: 'test',\n isDefault: true,\n },\n problemMatcher: [],\n };\n}\n\n/**\n * Merge the default policy lint task while preserving custom tasks.\n *\n * @param contents - Existing `.vscode/tasks.json` JSONC\n * @param repositoryRoot - Root that owns `.vscode`\n * @param targetDirectory - Selected policy project directory\n * @returns Merged task configuration and warnings\n */\nexport function mergePolicyEditorTasks(\n contents: string | null,\n repositoryRoot: string,\n targetDirectory: string,\n): PolicyEditorMergeResult {\n const parsed = parseEditorObject(contents, 'VS Code policy tasks');\n if ('warning' in parsed) {\n return { contents: parsed.contents, warnings: [parsed.warning] };\n }\n const { current } = parsed;\n const updates: JsoncUpdate[] = [];\n const warnings: string[] = [];\n const version = current.version;\n if (version === undefined) {\n updates.push({ path: ['version'], value: '2.0.0' });\n } else if (version !== '2.0.0') {\n warnings.push('VS Code task schema version is customized and was left unchanged.');\n }\n\n const desiredTask = buildPolicyLintTask(repositoryRoot, targetDirectory);\n const tasks = current.tasks;\n if (tasks === undefined) {\n updates.push({ path: ['tasks'], value: [desiredTask] });\n } else if (Array.isArray(tasks)) {\n const matchingTask = tasks.find(\n (task) =>\n task !== null &&\n typeof task === 'object' &&\n !Array.isArray(task) &&\n (task as Record<string, unknown>).label === 'policy: lint',\n );\n if (matchingTask === undefined) {\n updates.push({ path: ['tasks'], value: [...tasks, desiredTask] });\n } else if (!configurationValuesEqual(matchingTask, desiredTask)) {\n warnings.push(\n 'VS Code task \"policy: lint\" has repository-specific customization and was left unchanged.',\n );\n }\n } else {\n warnings.push('VS Code tasks use an unknown shape and were left unchanged.');\n }\n\n return applyEditorUpdates(contents, updates, 'VS Code policy tasks', warnings);\n}\n","import { isAbsolute, join, posix, relative, sep } from 'node:path';\n\nimport {\n getManagedAgentSkillCandidatePaths,\n planManagedAgentSkill,\n type ManagedAgentSkillDefinition,\n} from '../scaffolding/agent-skill.js';\nimport { displayProjectPath, quoteShellArgument } from '../scaffolding/project-plan-output.js';\nimport {\n getPlanningPathSnapshot,\n getPlanningFileSnapshot,\n planFileChange,\n type PlanningPathSnapshot,\n} from '../scaffolding/project-plan.js';\nimport { getPolicyManifestPath } from './policy-project-discovery.js';\nimport {\n generatePolicyGithubActionsWorkflow,\n POLICY_CI_WORKFLOW_PATH,\n} from './policy-scaffold-artifacts.js';\nimport {\n mergePolicyEditorExtensions,\n mergePolicyEditorSettings,\n mergePolicyEditorTasks,\n type PolicyEditorMergeResult,\n} from './policy-scaffold-config.js';\nimport {\n POLICY_INIT_RESULT_VERSION,\n PolicySetupFeature,\n type PolicyInitProjectPlan,\n type PolicyProjectState,\n type PolicySetupFeature as PolicySetupFeatureType,\n} from './policy-scaffold-model.js';\nimport { generatePolicyStarterFiles, type PolicyStarterFile } from './policy-scaffold-templates.js';\nimport { POLICY_SKILL_FILES, POLICY_SKILL_NAME } from './policy-skill.js';\n\n/** Managed Policy Engine Agent Skill definition. */\nconst POLICY_MANAGED_SKILL: ManagedAgentSkillDefinition = {\n name: POLICY_SKILL_NAME,\n displayName: 'Policy Engine',\n owner: '@transcend-io/cli',\n files: POLICY_SKILL_FILES,\n};\n\n/** In-memory input consumed by the pure policy initializer. */\nexport interface PolicyInitPlanningInput {\n /** Project discovery state. */\n state: PolicyProjectState;\n /** Potential mutation paths keyed by absolute path. */\n snapshots: Readonly<Record<string, PlanningPathSnapshot>>;\n}\n\n/** Optional repository setup selected for policy initialization. */\nexport interface PolicyInitPlanOptions {\n /** Selected setup features. */\n features: readonly PolicySetupFeatureType[];\n /** Exact released Transcend CLI version for generated CI. */\n cliVersion: string;\n}\n\n/**\n * Build the copyable policy lint command for one target.\n *\n * @param state - Discovered project state\n * @returns Raw one-line command\n */\nexport function buildPolicyLintCommand(state: PolicyProjectState): string {\n const directory = displayProjectPath(state.invocationDirectory, state.targetDirectory);\n return `transcend policy lint --dir ${quoteShellArgument(directory)} --noInteractive`;\n}\n\n/**\n * Enumerate all core starter paths that could be created.\n *\n * @param state - Policy project state\n * @param options - Selected repository setup\n * @returns Absolute candidate paths\n */\nexport function getPolicyInitPlanningCandidatePaths(\n state: PolicyProjectState,\n options: Pick<PolicyInitPlanOptions, 'features'>,\n): string[] {\n const paths = new Set(\n generatePolicyStarterFiles().map(({ path }) => join(state.targetDirectory, path)),\n );\n const selected = new Set(options.features);\n if (selected.has(PolicySetupFeature.Editor)) {\n paths.add(join(state.projectRoot, '.vscode', 'settings.json'));\n paths.add(join(state.projectRoot, '.vscode', 'extensions.json'));\n paths.add(join(state.projectRoot, '.vscode', 'tasks.json'));\n }\n if (selected.has(PolicySetupFeature.Skill)) {\n getManagedAgentSkillCandidatePaths(\n state.projectRoot,\n state.existingSkillDirectories,\n POLICY_MANAGED_SKILL,\n ).forEach((path) => paths.add(path));\n }\n if (selected.has(PolicySetupFeature.Ci) && state.repositoryRoot && state.usesGithub) {\n paths.add(join(state.repositoryRoot, POLICY_CI_WORKFLOW_PATH));\n }\n return [...paths].sort((left, right) => left.localeCompare(right));\n}\n\n/**\n * Ensure a destination stays below an approved project root.\n *\n * @param root - Approved root\n * @param path - Candidate path\n */\nfunction assertContained(root: string, path: string): void {\n const child = relative(root, path);\n if (child === '..' || child.startsWith(`..${sep}`) || isAbsolute(child)) {\n throw new Error(`Refusing to modify path outside project root: ${path}`);\n }\n}\n\n/**\n * Enumerate generated file and directory paths allowed in an exact starter.\n *\n * @param files - Starter files\n * @returns POSIX relative paths\n */\nfunction starterRelativePaths(files: readonly PolicyStarterFile[]): Set<string> {\n const paths = new Set<string>(['input.json']);\n files.forEach(({ path }) => {\n paths.add(path);\n let parent = posix.dirname(path);\n while (parent !== '.') {\n paths.add(parent);\n parent = posix.dirname(parent);\n }\n });\n return paths;\n}\n\n/**\n * Add or classify one regular-file mutation.\n *\n * @param plan - Policy plan being assembled\n * @param input - Collected snapshots\n * @param options - Desired file\n */\nfunction addFileChange(\n plan: PolicyInitProjectPlan,\n input: PolicyInitPlanningInput,\n options: {\n /** Absolute destination path. */\n path: string;\n /** Complete desired contents. */\n contents: string;\n /** Human-readable plan description. */\n description: string;\n /** Refuse existing contents. */\n createOnly?: boolean;\n },\n): void {\n const change = planFileChange({\n snapshot: getPlanningFileSnapshot(input.snapshots, options.path),\n after: options.contents,\n description: options.description,\n ...(options.createOnly === undefined ? {} : { createOnly: options.createOnly }),\n });\n if (change) {\n plan.changes.push(change);\n } else {\n plan.unchanged.push(options.path);\n }\n}\n\n/**\n * Add one safe editor merge and its preservation warnings.\n *\n * @param plan - Policy plan being assembled\n * @param input - Collected snapshots\n * @param path - Absolute editor artifact path\n * @param result - Pure JSONC merge result\n * @param description - Human-readable plan description\n * @param cwd - Invocation directory for portable warning paths\n */\nfunction addEditorMerge(\n plan: PolicyInitProjectPlan,\n input: PolicyInitPlanningInput,\n path: string,\n result: PolicyEditorMergeResult,\n description: string,\n cwd: string,\n): void {\n addFileChange(plan, input, {\n path,\n contents: result.contents,\n description,\n });\n plan.warnings.push(\n ...result.warnings.map((warning) => `${warning} (${displayProjectPath(cwd, path)})`),\n );\n}\n\n/**\n * Build a safe policy project plan without reading the filesystem.\n *\n * Empty targets receive the complete starter. Existing targets are classified\n * only; no domain file is added, merged, or overwritten.\n *\n * @param input - Collected project state and path snapshots\n * @param options - Selected setup and pinned CLI version\n * @returns Validated policy initialization plan\n */\nexport function buildPolicyInitPlan(\n input: PolicyInitPlanningInput,\n options: PolicyInitPlanOptions,\n): PolicyInitProjectPlan {\n const { state } = input;\n const files = generatePolicyStarterFiles();\n const manifestPath = getPolicyManifestPath(state);\n const lintCommand = buildPolicyLintCommand(state);\n const resultPath = join(state.targetDirectory, 'policy_engine', 'example', 'result.rego');\n const plan: PolicyInitProjectPlan = {\n version: POLICY_INIT_RESULT_VERSION,\n command: 'init',\n rootDirectory: state.projectRoot,\n targetDirectory: state.targetDirectory,\n manifestPath,\n changes: [],\n unchanged: [],\n warnings: [],\n nextSteps: [lintCommand],\n features: [...options.features],\n };\n\n const candidatePaths = getPolicyInitPlanningCandidatePaths(state, options);\n assertContained(state.projectRoot, state.targetDirectory);\n candidatePaths.forEach((path) => assertContained(state.projectRoot, path));\n\n let hasDisposableExample = false;\n if (state.relativeFilePaths.length === 0) {\n hasDisposableExample = true;\n plan.directoryPreconditions = [\n {\n path: state.targetDirectory,\n relativePaths: [...state.relativePaths],\n },\n ];\n files.forEach((file) => {\n const path = join(state.targetDirectory, file.path);\n const snapshot = getPlanningPathSnapshot(input.snapshots, path);\n if (snapshot.kind !== 'absent') {\n throw new Error(`Expected an empty policy target, but found an entry at: ${path}`);\n }\n addFileChange(plan, input, {\n path,\n contents: file.contents,\n description: file.description,\n createOnly: true,\n });\n });\n } else {\n let allStarterFilesMatch = true;\n files.forEach((file) => {\n const path = join(state.targetDirectory, file.path);\n const snapshot = getPlanningPathSnapshot(input.snapshots, path);\n if (snapshot.kind === 'file' && snapshot.contents === file.contents) {\n plan.unchanged.push(path);\n return;\n }\n allStarterFilesMatch = false;\n if (snapshot.kind !== 'absent') {\n plan.unchanged.push(path);\n plan.warnings.push(\n `Existing policy scaffold path was left unchanged: ${displayProjectPath(\n state.invocationDirectory,\n path,\n )}`,\n );\n }\n });\n hasDisposableExample = allStarterFilesMatch;\n\n const allowedPaths = starterRelativePaths(files);\n const hasCustomPaths = state.relativeFilePaths.some((path) => !allowedPaths.has(path));\n if (!allStarterFilesMatch || hasCustomPaths) {\n plan.warnings.push(\n `Existing policy target contains custom or partial content, so no starter files were added or overwritten. ` +\n `Review ${displayProjectPath(\n state.invocationDirectory,\n state.targetDirectory,\n )} manually, then run \\`${lintCommand}\\`.`,\n );\n }\n }\n if (hasDisposableExample) {\n plan.disposableExamplePath = resultPath;\n plan.nextSteps.push(\n `Edit ${quoteShellArgument(displayProjectPath(state.invocationDirectory, resultPath))}`,\n );\n }\n\n const selected = new Set(options.features);\n const root = state.projectRoot;\n if (selected.has(PolicySetupFeature.Editor)) {\n const settingsPath = join(root, '.vscode', 'settings.json');\n const extensionsPath = join(root, '.vscode', 'extensions.json');\n const tasksPath = join(root, '.vscode', 'tasks.json');\n const editorArtifacts = [\n {\n path: settingsPath,\n description: 'Merge strict target-scoped OPA and Rego editor settings',\n merge: mergePolicyEditorSettings,\n },\n {\n path: extensionsPath,\n description: 'Recommend the OPA extension and discourage its syntax-only conflict',\n merge: (\n contents: string | null,\n _repositoryRoot: string,\n _targetDirectory: string,\n ): PolicyEditorMergeResult => mergePolicyEditorExtensions(contents),\n },\n {\n path: tasksPath,\n description: 'Add the default target-scoped policy lint task',\n merge: mergePolicyEditorTasks,\n },\n ];\n editorArtifacts.forEach(({ path, description, merge }) => {\n const snapshot = getPlanningPathSnapshot(input.snapshots, path);\n if (snapshot.kind !== 'absent' && snapshot.kind !== 'file') {\n plan.unchanged.push(path);\n plan.warnings.push(\n `Existing VS Code artifact is not a regular file and was left unchanged: ${displayProjectPath(\n state.invocationDirectory,\n path,\n )}`,\n );\n return;\n }\n addEditorMerge(\n plan,\n input,\n path,\n merge(snapshot.kind === 'file' ? snapshot.contents : null, root, state.targetDirectory),\n description,\n state.invocationDirectory,\n );\n });\n }\n\n if (selected.has(PolicySetupFeature.Skill)) {\n const skillPlan = planManagedAgentSkill({\n rootDirectory: root,\n existingDirectories: state.existingSkillDirectories,\n snapshots: input.snapshots,\n skill: POLICY_MANAGED_SKILL,\n preserveModified: true,\n });\n plan.changes.push(...skillPlan.changes);\n plan.unchanged.push(...skillPlan.unchanged);\n plan.warnings.push(\n ...skillPlan.warnings.map((warning) => {\n return skillPlan.unchanged.reduce(\n (rendered, path) =>\n rendered.replace(path, displayProjectPath(state.invocationDirectory, path)),\n warning,\n );\n }),\n );\n }\n\n if (selected.has(PolicySetupFeature.Ci)) {\n if (!state.repositoryRoot || !state.usesGithub) {\n plan.warnings.push(\n 'GitHub Actions setup was selected, but this target is not inside a detected GitHub repository.',\n );\n } else {\n const workflowPath = join(state.repositoryRoot, POLICY_CI_WORKFLOW_PATH);\n const target =\n relative(state.repositoryRoot, state.targetDirectory).split(sep).join('/') || '.';\n const workflowContents = generatePolicyGithubActionsWorkflow({\n cliVersion: options.cliVersion,\n targetDirectory: target,\n });\n const workflowSnapshot = getPlanningPathSnapshot(input.snapshots, workflowPath);\n if (workflowSnapshot.kind === 'absent') {\n addFileChange(plan, input, {\n path: workflowPath,\n contents: workflowContents,\n description: 'Add credential-free Policy Engine validation',\n createOnly: true,\n });\n } else if (\n workflowSnapshot.kind === 'file' &&\n workflowSnapshot.contents === workflowContents\n ) {\n plan.unchanged.push(workflowPath);\n } else {\n plan.unchanged.push(workflowPath);\n plan.warnings.push(\n `Existing GitHub Actions workflow was left unchanged: ${displayProjectPath(\n state.invocationDirectory,\n workflowPath,\n )}. Adapt it manually to run \\`${lintCommand}\\`.`,\n );\n }\n }\n }\n\n plan.changes.forEach(({ path }) => assertContained(state.projectRoot, path));\n return plan;\n}\n","import colors from 'colors';\n\nimport { version as CLI_VERSION } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport {\n runCapturedProcess,\n type CapturedProcessResult,\n type CapturedProcessRunner,\n} from '../../../lib/cli/run-captured-process.js';\nimport {\n DEFAULT_POLICY_PROJECT_DIRECTORY,\n discoverPolicyProject,\n} from '../../../lib/policy/policy-project-discovery.js';\nimport {\n OPA_INSTALL_URL,\n OPA_MISSING_MESSAGE,\n parsePolicyToolVersion,\n MINIMUM_POLICY_STARTER_REGAL_VERSION,\n REGAL_INSTALL_URL,\n REGAL_MISSING_MESSAGE,\n unsupportedOpaVersionMessage,\n unsupportedRegalVersionMessage,\n} from '../../../lib/policy/policy-runtime.js';\nimport {\n PolicySetupFeature,\n type PolicySetupFeature as PolicySetupFeatureType,\n} from '../../../lib/policy/policy-scaffold-model.js';\nimport {\n buildPolicyInitAiHandoff,\n buildPolicyInitPlanResult,\n type PolicyInitToolVersions,\n} from '../../../lib/policy/policy-scaffold-output.js';\nimport {\n buildPolicyInitPlan,\n getPolicyInitPlanningCandidatePaths,\n} from '../../../lib/policy/policy-scaffold-planning.js';\nimport { collectPlanningSnapshots } from '../../../lib/scaffolding/project-discovery.js';\nimport { applyProjectPlan } from '../../../lib/scaffolding/project-plan-apply.js';\nimport {\n displayProjectPath,\n quoteShellArgument,\n renderProjectPlan,\n} from '../../../lib/scaffolding/project-plan-output.js';\nimport {\n PromptCancelledError,\n type PromptChoice,\n ScaffoldPrompts,\n} from '../../../lib/scaffolding/prompts.js';\n\n/** Flags for `transcend policy init`. */\nexport interface PolicyInitFlags {\n /** Install repository-level VS Code setup. */\n editor?: boolean;\n /** Install the Policy Engine Agent Skill. */\n skill?: boolean;\n /** Install validation-only GitHub Actions CI. */\n ci?: boolean;\n /** Disable prompts. */\n noInteractive: boolean;\n /** Render but do not apply the plan. */\n dryRun: boolean;\n /** Approve the final displayed plan. */\n yes: boolean;\n /** Emit one stable JSON result on stdout. */\n json: boolean;\n}\n\n/** User-facing optional setup labels. */\nconst SETUP_LABELS: Readonly<Record<PolicySetupFeatureType, string>> = {\n [PolicySetupFeature.Editor]: 'VS Code settings and lint task',\n [PolicySetupFeature.Skill]: 'Policy Engine Agent Skill',\n [PolicySetupFeature.Ci]: 'Validation-only GitHub Actions',\n};\n\n/** All optional setup features in stable prompt order. */\nconst ALL_SETUP_FEATURES = Object.values(PolicySetupFeature);\n\n/** Runtime compatibility detected before policy planning. */\ninterface PolicyRuntimeProbe {\n /** Compatible tool versions. */\n tools: PolicyInitToolVersions;\n /** Missing or incompatible runtime guidance. */\n warnings: string[];\n}\n\n/**\n * Whether this invocation can ask questions.\n *\n * @param flags - Interaction flags\n * @param stdinIsTTY - Whether standard input is interactive\n * @param stderrIsTTY - Whether prompt output is interactive\n * @returns Whether prompts are enabled\n */\nfunction isInteractiveInvocation(\n flags: Pick<PolicyInitFlags, 'json' | 'noInteractive'>,\n stdinIsTTY: boolean | undefined,\n stderrIsTTY: boolean | undefined,\n): boolean {\n return !flags.json && !flags.noInteractive && Boolean(stdinIsTTY && stderrIsTTY);\n}\n\n/**\n * Resolve setup from explicit flags or one default-selected checklist.\n *\n * @param prompts - Prompt adapters\n * @param flags - Setup flags\n * @param options - Interaction state\n * @returns Explicitly selected setup features\n */\nasync function resolveFeatures(\n prompts: ScaffoldPrompts,\n flags: PolicyInitFlags,\n options: {\n /** Whether prompts are available. */\n interactive: boolean;\n },\n): Promise<PolicySetupFeatureType[]> {\n const enabled: Readonly<Record<PolicySetupFeatureType, boolean | undefined>> = {\n [PolicySetupFeature.Editor]: flags.editor,\n [PolicySetupFeature.Skill]: flags.skill,\n [PolicySetupFeature.Ci]: flags.ci,\n };\n if (!options.interactive) {\n return ALL_SETUP_FEATURES.filter((feature) => enabled[feature] === true);\n }\n const choices: PromptChoice<PolicySetupFeatureType>[] = ALL_SETUP_FEATURES.map((feature) => ({\n name: SETUP_LABELS[feature],\n value: feature,\n checked: enabled[feature] !== false,\n }));\n return prompts.checkbox('Choose repository setup:', choices);\n}\n\n/**\n * Explain a failed version subprocess with official installation guidance.\n *\n * @param tool - Policy tool name\n * @param result - Failed captured process\n * @returns Actionable warning\n */\nfunction failedVersionProbeMessage(tool: 'OPA' | 'Regal', result: CapturedProcessResult): string {\n const detail = [result.stdout.trim(), result.stderr.trim()].filter(Boolean).join('\\n');\n const url = tool === 'OPA' ? OPA_INSTALL_URL : REGAL_INSTALL_URL;\n const requirement =\n tool === 'OPA' ? 'OPA 1.x' : `Regal ${MINIMUM_POLICY_STARTER_REGAL_VERSION} or newer`;\n return (\n `${requirement} is required, but \\`${tool.toLowerCase()} version\\` exited with code ` +\n `${result.code}${detail ? `: ${detail}` : '.'} ` +\n `Install or upgrade it using the official instructions: ${url}`\n );\n}\n\n/**\n * Probe both local policy runtimes without installing or modifying them.\n *\n * @param context - CLI context\n * @param cwd - Invocation working directory\n * @param runner - Captured subprocess runner\n * @returns Compatible versions and exact runtime guidance\n */\nasync function probePolicyRuntimes(\n context: LocalContext,\n cwd: string,\n runner: CapturedProcessRunner,\n): Promise<PolicyRuntimeProbe> {\n const tools: PolicyInitToolVersions = { opa: null, regal: null };\n const warnings: string[] = [];\n\n const opaResult = await runner('opa', ['version'], { cwd }, context);\n if (opaResult.error?.code === 'ENOENT') {\n warnings.push(OPA_MISSING_MESSAGE);\n } else {\n const output = `${opaResult.stdout}\\n${opaResult.stderr}`;\n const unsupported = unsupportedOpaVersionMessage(output);\n if (opaResult.code !== 0) {\n warnings.push(unsupported ?? failedVersionProbeMessage('OPA', opaResult));\n } else if (unsupported) {\n warnings.push(unsupported);\n } else {\n tools.opa = parsePolicyToolVersion(output)!.version;\n }\n }\n\n const regalResult = await runner('regal', ['version'], { cwd }, context);\n if (regalResult.error?.code === 'ENOENT') {\n warnings.push(REGAL_MISSING_MESSAGE);\n } else {\n const output = `${regalResult.stdout}\\n${regalResult.stderr}`;\n const unsupported = unsupportedRegalVersionMessage(\n output,\n MINIMUM_POLICY_STARTER_REGAL_VERSION,\n 'the generated OPA 1.13.1 capabilities configuration',\n );\n if (regalResult.code !== 0) {\n warnings.push(unsupported ?? failedVersionProbeMessage('Regal', regalResult));\n } else if (unsupported) {\n warnings.push(unsupported);\n } else {\n tools.regal = parsePolicyToolVersion(output)!.version;\n }\n }\n\n return { tools, warnings };\n}\n\n/**\n * Initialize a credential-free local Policy Engine project.\n *\n * @param this - CLI context\n * @param flags - Scaffold and interaction flags\n * @param directory - Target policy directory\n * @param runner - Captured policy tool runner\n */\nexport async function init(\n this: LocalContext,\n flags: PolicyInitFlags,\n directory: string = DEFAULT_POLICY_PROJECT_DIRECTORY,\n runner: CapturedProcessRunner = runCapturedProcess,\n): Promise<void> {\n doneInputValidation(this.process);\n try {\n const runtime = await probePolicyRuntimes(this, this.process.cwd(), runner);\n const state = discoverPolicyProject(this, directory);\n const prompts = new ScaffoldPrompts(this);\n const interactive = isInteractiveInvocation(\n flags,\n this.process.stdin.isTTY,\n this.process.stderr.isTTY,\n );\n const features = await resolveFeatures(prompts, flags, { interactive });\n const candidatePaths = getPolicyInitPlanningCandidatePaths(state, { features });\n const snapshots = collectPlanningSnapshots(this, state.projectRoot, candidatePaths);\n\n const plan = buildPolicyInitPlan(\n { state, snapshots },\n {\n features,\n cliVersion: CLI_VERSION,\n },\n );\n plan.warnings.push(...runtime.warnings);\n\n if (!flags.json) {\n this.logger.info(\n renderProjectPlan(plan, {\n cwd: this.process.cwd(),\n title: 'Policy initialization plan',\n details: [\n { label: 'Target', path: plan.targetDirectory },\n { label: 'Manifest', path: plan.manifestPath },\n ],\n }),\n );\n }\n\n let approved = plan.changes.length === 0 || flags.dryRun;\n if (plan.changes.length > 0 && !flags.dryRun) {\n if (flags.yes) {\n approved = true;\n } else if (interactive) {\n approved = await prompts.confirm('Apply this complete plan?', true);\n } else {\n throw new Error(\n 'The plan requires approval in a non-interactive invocation. Review with --dryRun, then pass --yes.',\n );\n }\n }\n\n if (approved && !flags.dryRun && plan.changes.length > 0) {\n await applyProjectPlan(this, plan);\n }\n const applied = approved && !flags.dryRun && plan.changes.length > 0;\n const setupAvailable = approved && !flags.dryRun;\n const aiHandoff = buildPolicyInitAiHandoff({\n projectPath: quoteShellArgument(\n displayProjectPath(this.process.cwd(), state.targetDirectory),\n ),\n ...(plan.disposableExamplePath\n ? {\n examplePath: quoteShellArgument(\n displayProjectPath(this.process.cwd(), plan.disposableExamplePath),\n ),\n }\n : {}),\n hasSkill: setupAvailable && features.includes(PolicySetupFeature.Skill),\n lintCommand: plan.nextSteps[0]!,\n });\n const result = buildPolicyInitPlanResult(plan, {\n applied,\n dryRun: flags.dryRun,\n cwd: this.process.cwd(),\n aiHandoff,\n tools: runtime.tools,\n });\n if (flags.json) {\n this.process.stdout.write(`${JSON.stringify(result)}\\n`);\n return;\n }\n if (flags.dryRun) {\n this.logger.info(colors.yellow('Dry run complete. No changes were written.'));\n return;\n }\n if (!approved) {\n this.logger.info(colors.yellow('No changes applied.'));\n return;\n }\n if (plan.changes.length === 0) {\n const message =\n plan.warnings.length === runtime.warnings.length\n ? 'Policy project is already initialized.'\n : 'Existing policy project was left unchanged.';\n this.logger.info(colors.green(message));\n } else {\n this.logger.info(colors.green('Policy project initialized.'));\n }\n if (plan.nextSteps.length > 0) {\n this.logger.info(`\\n${colors.bold('Next steps')}`);\n plan.nextSteps.forEach((step) => this.logger.info(step));\n }\n this.logger.info(`\\n${colors.bold('AI handoff — paste into your coding agent')}`);\n this.logger.info(aiHandoff);\n } catch (error) {\n if (error instanceof PromptCancelledError) {\n return this.process.exit(130);\n }\n throw error;\n }\n}\n"],"mappings":"umBAUA,MAAa,EAAmC,mBAShD,SAAgB,GACd,EACA,EAAoB,EACA,CACpB,IAAM,EAAsB,EAAQ,QAAQ,KAAK,CAC3C,EAAkB,GAAQ,EAAqB,EAAU,CAC/D,GACE,EAAQ,GAAG,WAAW,EAAgB,EACtC,CAAC,EAAQ,GAAG,SAAS,EAAgB,CAAC,aAAa,CAEnD,MAAU,MAAM,qCAAqC,IAAkB,CAOzE,MAAO,CACL,sBACA,kBACA,GARiB,EAA0B,EAAS,CACpD,sBACA,kBACA,sBAAuB,EACxB,CAIc,CACb,cAAe,EAA4B,EAAS,EAAgB,CACpE,kBAAmB,EAA4B,EAAS,EAAiB,CACvE,mBAAoB,GACrB,CAAC,CACH,CASH,SAAgB,GAAsB,EAAmC,CACvE,OAAO,EAAK,EAAM,gBAAiB,gBAAgB,CC/CrD,MAAa,EAAqB,CAEhC,OAAQ,SAER,MAAO,QAEP,GAAI,KACL,QCdD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KCAA;;;;;;;;;;;;;;;;;;;;KCAA,ywDCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECQA,MAAa,EAAoB,0BAWpB,EAAgD,CAC3D,CAAE,KAAM,WAAY,SAAUA,GAAiB,CAC/C,CAAE,KAAM,8BAA+B,SAAUC,GAAmC,CACpF,CAAE,KAAM,0BAA2B,SAAUC,GAA+B,CAC5E,CAAE,KAAM,kCAAmC,SAAUC,GAAuC,CAC5F,CAAE,KAAM,2BAA4B,SAAUC,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MD","CLI_VERSION"],"sources":["../src/lib/policy/policy-project-discovery.ts","../src/lib/policy/policy-scaffold-model.ts","../../../skills/transcend-policy-engine/references/authoring.md","../../../skills/transcend-policy-engine/references/publishing.md","../../../skills/transcend-policy-engine/references/setup-tooling.md","../../../skills/transcend-policy-engine/references/testing-debugging.md","../../../skills/transcend-policy-engine/SKILL.md","../src/lib/policy/policy-skill.ts","../src/lib/policy/policy-scaffold-output.ts","../src/lib/policy/policy-scaffold-templates.ts","../src/lib/policy/policy-scaffold-artifacts.ts","../src/lib/policy/policy-scaffold-config.ts","../src/lib/policy/policy-scaffold-planning.ts","../src/commands/policy/init/impl.ts"],"sourcesContent":["import { join, resolve } from 'node:path';\n\nimport type { LocalContext } from '../../context.js';\nimport {\n collectProjectRelativePaths,\n discoverProjectRepository,\n} from '../scaffolding/project-discovery.js';\nimport type { PolicyProjectState } from './policy-scaffold-model.js';\n\n/** Default local policy project directory. */\nexport const DEFAULT_POLICY_PROJECT_DIRECTORY = 'transcend/policy';\n\n/**\n * Collect repository state required by the pure policy planner.\n *\n * @param context - CLI context\n * @param directory - User-selected target directory\n * @returns Policy project discovery state\n */\nexport function discoverPolicyProject(\n context: LocalContext,\n directory: string = DEFAULT_POLICY_PROJECT_DIRECTORY,\n): PolicyProjectState {\n const invocationDirectory = context.process.cwd();\n const targetDirectory = resolve(invocationDirectory, directory);\n if (\n context.fs.existsSync(targetDirectory) &&\n !context.fs.statSync(targetDirectory).isDirectory()\n ) {\n throw new Error(`Policy target is not a directory: ${targetDirectory}`);\n }\n const repository = discoverProjectRepository(context, {\n invocationDirectory,\n targetDirectory,\n standaloneProjectRoot: invocationDirectory,\n });\n return {\n invocationDirectory,\n targetDirectory,\n ...repository,\n relativePaths: collectProjectRelativePaths(context, targetDirectory),\n relativeFilePaths: collectProjectRelativePaths(context, targetDirectory, {\n includeDirectories: false,\n }),\n };\n}\n\n/**\n * Resolve the bundle manifest path for a discovered project.\n *\n * @param state - Policy project state\n * @returns Absolute manifest path\n */\nexport function getPolicyManifestPath(state: PolicyProjectState): string {\n return join(state.targetDirectory, 'manifest.json');\n}\n","import type { ExistingProjectSkillDirectory } from '../scaffolding/agent-skill.js';\nimport type { ProjectPlan } from '../scaffolding/project-plan.js';\n\n/** Version of the stable policy initialization JSON result. */\nexport const POLICY_INIT_RESULT_VERSION = 1 as const;\n\n/** Optional repository integrations for policy authoring. */\nexport const PolicySetupFeature = {\n /** Repository-level editor configuration. */\n Editor: 'editor',\n /** Managed policy authoring skill. */\n Skill: 'skill',\n /** Credential-free continuous integration. */\n Ci: 'ci',\n} as const;\n\n/** Optional repository integration for policy authoring. */\nexport type PolicySetupFeature = (typeof PolicySetupFeature)[keyof typeof PolicySetupFeature];\n\n/** Repository and target state collected before policy planning. */\nexport interface PolicyProjectState {\n /** Directory from which the CLI was invoked. */\n invocationDirectory: string;\n /** Absolute user-selected policy directory. */\n targetDirectory: string;\n /** Repository or invocation root that owns setup artifacts. */\n projectRoot: string;\n /** Nearest repository root, when present. */\n repositoryRoot?: string;\n /** Existing project-level skill directories. */\n existingSkillDirectories: ExistingProjectSkillDirectory[];\n /** Whether the repository appears to use GitHub. */\n usesGithub: boolean;\n /** Case-preserving relative paths below the policy directory. */\n relativePaths: string[];\n /** Relative file and link paths below the policy directory. */\n relativeFilePaths: string[];\n}\n\n/** A complete, validated policy initialization plan. */\nexport interface PolicyInitProjectPlan extends ProjectPlan {\n /** JSON contract version. */\n version: typeof POLICY_INIT_RESULT_VERSION;\n /** Command that produced the plan. */\n command: 'init';\n /** Absolute policy project directory. */\n targetDirectory: string;\n /** Absolute policy manifest path. */\n manifestPath: string;\n /** Files inspected and deliberately left unchanged. */\n unchanged: string[];\n /** Non-fatal plan warnings. */\n warnings: string[];\n /** Raw commands shown after a successful apply. */\n nextSteps: string[];\n /** Exact generated example that remains safe to replace. */\n disposableExamplePath?: string;\n /** Selected repository integrations. */\n features: PolicySetupFeature[];\n}\n",null,null,null,null,null,"import POLICY_AUTHORING_REFERENCE_MD from '../../../../../skills/transcend-policy-engine/references/authoring.md';\nimport POLICY_PUBLISHING_REFERENCE_MD from '../../../../../skills/transcend-policy-engine/references/publishing.md';\nimport POLICY_SETUP_TOOLING_REFERENCE_MD from '../../../../../skills/transcend-policy-engine/references/setup-tooling.md';\nimport POLICY_TESTING_DEBUGGING_REFERENCE_MD from '../../../../../skills/transcend-policy-engine/references/testing-debugging.md';\nimport POLICY_SKILL_MD from '../../../../../skills/transcend-policy-engine/SKILL.md';\nimport type { AgentSkillFile } from '../scaffolding/agent-skill.js';\n\n/** Namespaced directory and frontmatter name for the installed Agent Skill. */\nexport const POLICY_SKILL_NAME = 'transcend-policy-engine';\n\nexport {\n POLICY_AUTHORING_REFERENCE_MD,\n POLICY_PUBLISHING_REFERENCE_MD,\n POLICY_SETUP_TOOLING_REFERENCE_MD,\n POLICY_SKILL_MD,\n POLICY_TESTING_DEBUGGING_REFERENCE_MD,\n};\n\n/** Complete portable Policy Engine Agent Skill file set. */\nexport const POLICY_SKILL_FILES: readonly AgentSkillFile[] = [\n { path: 'SKILL.md', contents: POLICY_SKILL_MD },\n { path: 'references/setup-tooling.md', contents: POLICY_SETUP_TOOLING_REFERENCE_MD },\n { path: 'references/authoring.md', contents: POLICY_AUTHORING_REFERENCE_MD },\n { path: 'references/testing-debugging.md', contents: POLICY_TESTING_DEBUGGING_REFERENCE_MD },\n { path: 'references/publishing.md', contents: POLICY_PUBLISHING_REFERENCE_MD },\n];\n","import {\n toPublicPlannedChange,\n type PublicPlannedChange,\n} from '../scaffolding/project-plan-output.js';\nimport type { PolicyInitProjectPlan, PolicySetupFeature } from './policy-scaffold-model.js';\nimport { POLICY_SKILL_NAME } from './policy-skill.js';\n\n/** Detected local policy tool versions. */\nexport interface PolicyInitToolVersions {\n /** OPA version, or null when missing or incompatible. */\n opa: string | null;\n /** Regal version, or null when missing or incompatible. */\n regal: string | null;\n}\n\n/** Stable machine-readable policy initialization result. */\nexport interface PolicyInitPlanResult {\n /** JSON contract version. */\n version: number;\n /** Command that produced the result. */\n command: 'init';\n /** Whether the plan was applied. */\n applied: boolean;\n /** Whether this was a dry run. */\n dryRun: boolean;\n /** Absolute policy target directory. */\n targetDirectory: string;\n /** Absolute policy manifest path. */\n manifestPath: string;\n /** Planned mutations without file contents. */\n changes: PublicPlannedChange[];\n /** Non-fatal preservation and runtime warnings. */\n warnings: string[];\n /** Suggested raw one-line follow-up commands. */\n nextSteps: string[];\n /** Explicitly selected repository integrations. */\n features: PolicySetupFeature[];\n /** Compact prompt for continuing with a coding agent. */\n aiHandoff: string;\n /** Compatible local policy tool versions. */\n tools: PolicyInitToolVersions;\n}\n\n/**\n * Build the compact policy implementation and CI handoff.\n *\n * @param options - Portable example path and lint command\n * @returns Raw one-line prompt\n */\nexport function buildPolicyInitAiHandoff(options: {\n /** Display path to the policy project. */\n projectPath: string;\n /** Display path to an exact disposable example. */\n examplePath?: string;\n /** Whether the policy authoring skill was installed. */\n hasSkill: boolean;\n /** Copyable lint command. */\n lintCommand: string;\n}): string {\n if (!options.examplePath) {\n const instruction = options.hasSkill\n ? `Use the \\`${POLICY_SKILL_NAME}\\` skill to review`\n : 'Review';\n return (\n `${instruction} the existing policy project in ${options.projectPath}, ` +\n `align its document tree and input/output contract with the intended application, adapt ` +\n `repository validation as needed, and rerun ${options.lintCommand}.`\n );\n }\n const instruction = options.hasSkill\n ? `Use the \\`${POLICY_SKILL_NAME}\\` skill to replace`\n : 'Replace';\n return (\n `${instruction} the disposable example in ${options.examplePath} with ` +\n `the intended policy document tree and input/output contract, adapt repository validation ` +\n `to local conventions, and rerun ${options.lintCommand}.`\n );\n}\n\n/**\n * Build the stable machine-readable initialization result.\n *\n * @param plan - Policy project plan\n * @param options - Apply and runtime state\n * @returns Public JSON result\n */\nexport function buildPolicyInitPlanResult(\n plan: PolicyInitProjectPlan,\n options: {\n /** Whether the plan was applied. */\n applied: boolean;\n /** Whether this was a dry run. */\n dryRun: boolean;\n /** Working directory for portable paths. */\n cwd: string;\n /** Compact coding-agent prompt. */\n aiHandoff: string;\n /** Compatible local policy tool versions. */\n tools: PolicyInitToolVersions;\n },\n): PolicyInitPlanResult {\n return {\n version: plan.version,\n command: plan.command,\n applied: options.applied,\n dryRun: options.dryRun,\n targetDirectory: plan.targetDirectory,\n manifestPath: plan.manifestPath,\n changes: plan.changes.map((change) => toPublicPlannedChange(options.cwd, change)),\n warnings: plan.warnings,\n nextSteps: plan.nextSteps,\n features: [...plan.features],\n aiHandoff: options.aiHandoff,\n tools: options.tools,\n };\n}\n","/** OPA version targeted by generated policy authoring configuration. */\nexport const POLICY_STARTER_OPA_VERSION = '1.13.1';\n\n/** One deterministic file in the safe policy starter. */\nexport interface PolicyStarterFile {\n /** POSIX-style path relative to the policy directory. */\n path: string;\n /** Complete UTF-8 file contents. */\n contents: string;\n /** Human-readable reason shown in the plan. */\n description: string;\n}\n\n/** Publishable Policy Engine bundle manifest. */\nexport const POLICY_MANIFEST_TEMPLATE = `{\n \"roots\": [\"policy_engine\"]\n}\n`;\n\n/** Strict Regal project configuration pinned to the deployed OPA capabilities. */\nexport const POLICY_REGAL_CONFIG_TEMPLATE = `capabilities:\n from:\n engine: opa\n version: v${POLICY_STARTER_OPA_VERSION}\nproject:\n roots:\n - .\n rego-version: 1\n`;\n\n/** Disposable, fail-closed example policy. */\nexport const POLICY_RESULT_REGO_TEMPLATE = `package policy_engine.example\n\nimport rego.v1\n\n# METADATA\n# title: Disposable example result\n# description: |\n# A fail-closed teaching entrypoint. Replace this example with the document\n# tree and result contract required by your application.\n# entrypoint: true\ndefault result := {\n\t\"decision\": \"deny\",\n\t\"reason_code\": \"untrusted_or_invalid_input\",\n}\n\nresult := {\n\t\"decision\": \"allow\",\n\t\"reason_code\": \"trusted_subject\",\n} if {\n\tinput.subject.trusted == true\n}\n`;\n\n/** Executable tests adjacent to the disposable example policy. */\nexport const POLICY_RESULT_TEST_REGO_TEMPLATE = `package policy_engine.example_test\n\nimport data.policy_engine.example\nimport rego.v1\n\ntest_denies_untrusted_subject if {\n\tresult := example.result with input as {\"subject\": {\"trusted\": false}}\n\tresult == {\n\t\t\"decision\": \"deny\",\n\t\t\"reason_code\": \"untrusted_or_invalid_input\",\n\t}\n}\n\ntest_fails_closed_for_missing_subject if {\n\tresult := example.result with input as {}\n\tresult == {\n\t\t\"decision\": \"deny\",\n\t\t\"reason_code\": \"untrusted_or_invalid_input\",\n\t}\n}\n\ntest_allows_trusted_subject if {\n\tresult := example.result with input as {\"subject\": {\"trusted\": true}}\n\tresult == {\n\t\t\"decision\": \"allow\",\n\t\t\"reason_code\": \"trusted_subject\",\n\t}\n}\n`;\n\n/** Sanitized local input example containing no credentials or personal data. */\nexport const POLICY_INPUT_EXAMPLE_TEMPLATE = `{\n \"subject\": {\n \"trusted\": false\n }\n}\n`;\n\n/** Target-local ignore rules for private evaluation input only. */\nexport const POLICY_GITIGNORE_TEMPLATE = `# Local policy evaluation input.\n/input.json\n`;\n\n/** Concise project-local authoring guide. */\nexport const POLICY_README_TEMPLATE = `# Transcend Policy Project\n\nThis directory is an OPA document tree that can be published to Transcend Policy Engine.\n\nThe policy under \\`policy_engine/example\\` is disposable teaching material. Replace it with your intended package tree, input shape, and extensible result documents. Keep decisions fail-closed and cover every non-test package with \\`manifest.json\\`.\n\nValidate formatting, strict Rego v1 compatibility, Regal lint, tests, and the publish contract:\n\n\\`\\`\\`sh\ntranscend policy lint --dir .\n\\`\\`\\`\n`;\n\n/** Complete safe starter in deterministic plan order. */\nconst POLICY_STARTER_FILES: readonly PolicyStarterFile[] = [\n {\n path: 'manifest.json',\n contents: POLICY_MANIFEST_TEMPLATE,\n description: 'Create the publishable Policy Engine manifest',\n },\n {\n path: '.regal/config.yaml',\n contents: POLICY_REGAL_CONFIG_TEMPLATE,\n description: 'Pin strict Rego v1 linting to OPA 1.13.1 capabilities',\n },\n {\n path: 'policy_engine/example/result.rego',\n contents: POLICY_RESULT_REGO_TEMPLATE,\n description: 'Create a documented fail-closed result entrypoint',\n },\n {\n path: 'policy_engine/example/result_test.rego',\n contents: POLICY_RESULT_TEST_REGO_TEMPLATE,\n description: 'Create executable tests for allow and fail-closed decisions',\n },\n {\n path: 'input.example.json',\n contents: POLICY_INPUT_EXAMPLE_TEMPLATE,\n description: 'Create a sanitized local evaluation input',\n },\n {\n path: '.gitignore',\n contents: POLICY_GITIGNORE_TEMPLATE,\n description: 'Ignore only the private local input file',\n },\n {\n path: 'README.md',\n contents: POLICY_README_TEMPLATE,\n description: 'Create the concise policy project guide',\n },\n];\n\n/**\n * Generate an independent copy of the safe policy starter.\n *\n * @returns Deterministic relative files\n */\nexport function generatePolicyStarterFiles(): PolicyStarterFile[] {\n return POLICY_STARTER_FILES.map((file) => ({ ...file }));\n}\n","import { posix } from 'node:path';\n\nimport { POLICY_STARTER_OPA_VERSION } from './policy-scaffold-templates.js';\n\n/** Regal version pinned by generated policy validation. */\nexport const POLICY_STARTER_REGAL_VERSION = '0.42.0';\n\n/** Repository-relative generated workflow path. */\nexport const POLICY_CI_WORKFLOW_PATH = '.github/workflows/transcend-policy.yml';\n\n/** Immutable actions/checkout v6 release commit. */\nexport const ACTIONS_CHECKOUT_SHA = 'd23441a48e516b6c34aea4fa41551a30e30af803';\n\n/** Immutable open-policy-agent/setup-opa v2.4.0 release commit. */\nexport const SETUP_OPA_SHA = 'b2b258e089860efaadaaf71bf6e3aecb4a3eeff1';\n\n/** Immutable open-policy-agent/setup-regal v2.0.0 release commit. */\nexport const SETUP_REGAL_SHA = '761188c3b435761fa254beca508a44875619648f';\n\n/**\n * Prefix a path below the repository-relative policy target.\n *\n * @param targetDirectory - POSIX repository-relative target\n * @param child - POSIX target-relative path or pattern\n * @returns Repository-relative path or pattern\n */\nfunction targetPath(targetDirectory: string, child: string): string {\n return targetDirectory === '.' ? child : posix.join(targetDirectory, child);\n}\n\n/**\n * Generate credential-free, validation-only Policy Engine CI.\n *\n * @param options - Repository paths and exact CLI release\n * @returns Complete GitHub Actions workflow YAML\n */\nexport function generatePolicyGithubActionsWorkflow(options: {\n /** Exact released Transcend CLI version. */\n cliVersion: string;\n /** Policy directory relative to the repository root. */\n targetDirectory: string;\n}): string {\n const watchedPaths = [\n targetPath(options.targetDirectory, '**/*.rego'),\n targetPath(options.targetDirectory, '**/*.json'),\n targetPath(options.targetDirectory, '**/*.yaml'),\n targetPath(options.targetDirectory, '**/*.yml'),\n targetPath(options.targetDirectory, '.regal/config.yaml'),\n targetPath(options.targetDirectory, '.regal.yaml'),\n POLICY_CI_WORKFLOW_PATH,\n ];\n const pathFilters = watchedPaths.map((path) => ` - ${JSON.stringify(path)}`).join('\\n');\n\n return `# Generated by transcend policy init.\nname: Transcend Policy\n\non:\n pull_request:\n paths:\n${pathFilters}\n push:\n paths:\n${pathFilters}\n\npermissions:\n contents: read\n\njobs:\n lint:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@${ACTIONS_CHECKOUT_SHA} # v6\n - name: Set up OPA\n uses: open-policy-agent/setup-opa@${SETUP_OPA_SHA} # v2.4.0\n with:\n version: ${JSON.stringify(POLICY_STARTER_OPA_VERSION)}\n - name: Set up Regal\n uses: open-policy-agent/setup-regal@${SETUP_REGAL_SHA} # v2.0.0\n with:\n version: ${JSON.stringify(POLICY_STARTER_REGAL_VERSION)}\n - name: Install the Transcend CLI\n run: npm install --global @transcend-io/cli@${options.cliVersion}\n - name: Validate Policy Engine project\n env:\n POLICY_DIRECTORY: ${JSON.stringify(options.targetDirectory)}\n run: >-\n transcend policy lint\n --dir \"$POLICY_DIRECTORY\"\n --noInteractive\n --json\n`;\n}\n","import { relative, sep } from 'node:path';\n\nimport {\n mergeJsonc,\n mergeStringArray,\n parseJsoncObject,\n type JsoncUpdate,\n} from '../scaffolding/jsonc.js';\n\n/** Recommended VS Code extension for OPA and Regal authoring. */\nexport const POLICY_VSCODE_EXTENSION = 'tsandall.opa';\n\n/** Conflicting syntax-only VS Code extension. */\nexport const CONFLICTING_POLICY_VSCODE_EXTENSION = 'glebbash.opa-highlight-only';\n\n/** Result of safely merging one repository editor artifact. */\nexport interface PolicyEditorMergeResult {\n /** Complete merged contents, or the unchanged original when unsafe. */\n contents: string;\n /** Actionable preservation warnings. */\n warnings: string[];\n}\n\n/** One desired scalar setting that must not replace a customization. */\ninterface DesiredSetting {\n /** JSONC object path. */\n path: string[];\n /** Desired generated value. */\n value: unknown;\n /** Human-readable setting key. */\n label: string;\n}\n\n/**\n * Compare JSON-compatible configuration values.\n *\n * @param left - Existing value\n * @param right - Desired value\n * @returns Whether the values are structurally equal\n */\nfunction configurationValuesEqual(left: unknown, right: unknown): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\n/**\n * Parse an editor object while preserving malformed existing content.\n *\n * @param contents - Existing JSONC, or null\n * @param label - Configuration label\n * @returns Parsed object or a preservation result\n */\nfunction parseEditorObject(\n contents: string | null,\n label: string,\n):\n | {\n /** Parsed JSONC object. */\n current: Record<string, unknown>;\n }\n | {\n /** Complete unchanged contents. */\n contents: string;\n /** Actionable warning. */\n warning: string;\n } {\n try {\n return { current: parseJsoncObject(contents ?? '{}\\n', label) };\n } catch (error) {\n return {\n contents: contents ?? '{}\\n',\n warning: `${error instanceof Error ? error.message : String(error)} Existing content was left unchanged.`,\n };\n }\n}\n\n/**\n * Apply safe JSONC updates or preserve the existing file when comments prevent it.\n *\n * @param contents - Existing JSONC\n * @param updates - Proven-safe updates\n * @param label - Configuration label\n * @param warnings - Existing merge warnings\n * @returns Complete contents and warnings\n */\nfunction applyEditorUpdates(\n contents: string | null,\n updates: readonly JsoncUpdate[],\n label: string,\n warnings: string[],\n): PolicyEditorMergeResult {\n if (updates.length === 0) {\n return { contents: contents ?? '{}\\n', warnings };\n }\n try {\n return {\n contents: mergeJsonc(contents, updates, label),\n warnings,\n };\n } catch (error) {\n return {\n contents: contents ?? '{}\\n',\n warnings: [\n ...warnings,\n `${error instanceof Error ? error.message : String(error)} Existing content was left unchanged.`,\n ],\n };\n }\n}\n\n/**\n * Add absent scalar settings without replacing repository customizations.\n *\n * @param current - Parsed editor object\n * @param desired - Desired settings\n * @param updates - Safe updates to append to\n * @param warnings - Conflict warnings to append to\n */\nfunction collectSafeScalarUpdates(\n current: Record<string, unknown>,\n desired: readonly DesiredSetting[],\n updates: JsoncUpdate[],\n warnings: string[],\n): void {\n desired.forEach(({ path, value, label }) => {\n const existing = path.reduce<unknown>((parent, key) => {\n return parent && typeof parent === 'object' && !Array.isArray(parent)\n ? (parent as Record<string, unknown>)[key]\n : undefined;\n }, current);\n if (existing === undefined) {\n updates.push({ path, value });\n } else if (!configurationValuesEqual(existing, value)) {\n warnings.push(\n `VS Code setting \"${label}\" has a repository-specific value and was left unchanged.`,\n );\n }\n });\n}\n\n/**\n * Build the workspace-relative OPA bundle root.\n *\n * @param repositoryRoot - Root that owns `.vscode`\n * @param targetDirectory - Selected policy project directory\n * @returns VS Code workspace path\n */\nfunction buildOpaWorkspaceRoot(repositoryRoot: string, targetDirectory: string): string {\n const target = relative(repositoryRoot, targetDirectory).split(sep).join('/') || '.';\n return target === '.' ? '${workspaceFolder}' : `\\${workspaceFolder}/${target}`;\n}\n\n/**\n * Merge strict target-scoped OPA and Rego editor settings.\n *\n * Setting names match the authoritative `open-policy-agent/vscode-opa`\n * extension metadata. Existing conflicting values are preserved and reported.\n *\n * @param contents - Existing `.vscode/settings.json` JSONC\n * @param repositoryRoot - Root that owns `.vscode`\n * @param targetDirectory - Selected policy project directory\n * @returns Merged settings and conflict warnings\n */\nexport function mergePolicyEditorSettings(\n contents: string | null,\n repositoryRoot: string,\n targetDirectory: string,\n): PolicyEditorMergeResult {\n const parsed = parseEditorObject(contents, 'VS Code policy settings');\n if ('warning' in parsed) {\n return { contents: parsed.contents, warnings: [parsed.warning] };\n }\n const { current } = parsed;\n const updates: JsoncUpdate[] = [];\n const warnings: string[] = [];\n\n const roots = current['opa.roots'];\n const desiredRoot = buildOpaWorkspaceRoot(repositoryRoot, targetDirectory);\n if (roots === undefined) {\n updates.push({ path: ['opa.roots'], value: [desiredRoot] });\n } else if (Array.isArray(roots) && roots.every((value) => typeof value === 'string')) {\n const merged = mergeStringArray(roots, [desiredRoot]);\n if (!configurationValuesEqual(merged, roots)) {\n updates.push({ path: ['opa.roots'], value: merged });\n }\n } else {\n warnings.push('VS Code setting \"opa.roots\" is customized and was left unchanged.');\n }\n\n collectSafeScalarUpdates(\n current,\n [\n { path: ['opa.checkOnSave'], value: true, label: 'opa.checkOnSave' },\n { path: ['opa.strictMode'], value: true, label: 'opa.strictMode' },\n { path: ['opa.bundleMode'], value: true, label: 'opa.bundleMode' },\n { path: ['opa.formatter'], value: 'opa-fmt-rego-v1', label: 'opa.formatter' },\n ],\n updates,\n warnings,\n );\n\n const regoSettings = current['[rego]'];\n if (regoSettings === undefined) {\n updates.push({\n path: ['[rego]'],\n value: {\n 'editor.defaultFormatter': POLICY_VSCODE_EXTENSION,\n 'editor.formatOnSave': true,\n 'editor.insertSpaces': false,\n 'editor.tabSize': 4,\n },\n });\n } else if (\n regoSettings !== null &&\n typeof regoSettings === 'object' &&\n !Array.isArray(regoSettings)\n ) {\n collectSafeScalarUpdates(\n current,\n [\n {\n path: ['[rego]', 'editor.defaultFormatter'],\n value: POLICY_VSCODE_EXTENSION,\n label: '[rego].editor.defaultFormatter',\n },\n {\n path: ['[rego]', 'editor.formatOnSave'],\n value: true,\n label: '[rego].editor.formatOnSave',\n },\n {\n path: ['[rego]', 'editor.insertSpaces'],\n value: false,\n label: '[rego].editor.insertSpaces',\n },\n {\n path: ['[rego]', 'editor.tabSize'],\n value: 4,\n label: '[rego].editor.tabSize',\n },\n ],\n updates,\n warnings,\n );\n } else {\n warnings.push('VS Code language setting \"[rego]\" is customized and was left unchanged.');\n }\n\n return applyEditorUpdates(contents, updates, 'VS Code policy settings', warnings);\n}\n\n/**\n * Merge OPA extension recommendations without disturbing unknown entries.\n *\n * VS Code's `extensions.json` schema supports `unwantedRecommendations`, so\n * the syntax-only extension can be removed from recommendations and discouraged.\n *\n * @param contents - Existing `.vscode/extensions.json` JSONC\n * @returns Merged extension recommendations and warnings\n */\nexport function mergePolicyEditorExtensions(contents: string | null): PolicyEditorMergeResult {\n const parsed = parseEditorObject(contents, 'VS Code policy extension recommendations');\n if ('warning' in parsed) {\n return { contents: parsed.contents, warnings: [parsed.warning] };\n }\n const { current } = parsed;\n const updates: JsoncUpdate[] = [];\n const warnings: string[] = [];\n\n const recommendations = current.recommendations;\n if (\n recommendations === undefined ||\n (Array.isArray(recommendations) && recommendations.every((value) => typeof value === 'string'))\n ) {\n const existing = recommendations ?? [];\n const desired = mergeStringArray(existing, [POLICY_VSCODE_EXTENSION]).filter(\n (value) => value !== CONFLICTING_POLICY_VSCODE_EXTENSION,\n );\n if (!configurationValuesEqual(existing, desired)) {\n updates.push({ path: ['recommendations'], value: desired });\n }\n } else {\n warnings.push(\n 'VS Code extension recommendations use an unknown shape and were left unchanged.',\n );\n }\n\n const unwanted = current.unwantedRecommendations;\n if (\n unwanted === undefined ||\n (Array.isArray(unwanted) && unwanted.every((value) => typeof value === 'string'))\n ) {\n const existing = unwanted ?? [];\n const desired = mergeStringArray(existing, [CONFLICTING_POLICY_VSCODE_EXTENSION]);\n if (!configurationValuesEqual(existing, desired)) {\n updates.push({ path: ['unwantedRecommendations'], value: desired });\n }\n } else {\n warnings.push(\n 'VS Code unwanted extension recommendations use an unknown shape and were left unchanged.',\n );\n }\n\n return applyEditorUpdates(\n contents,\n updates,\n 'VS Code policy extension recommendations',\n warnings,\n );\n}\n\n/**\n * Build the generated target-scoped VS Code lint task.\n *\n * @param repositoryRoot - Root that owns `.vscode`\n * @param targetDirectory - Selected policy project directory\n * @returns VS Code task object\n */\nexport function buildPolicyLintTask(\n repositoryRoot: string,\n targetDirectory: string,\n): Record<string, unknown> {\n const target = relative(repositoryRoot, targetDirectory).split(sep).join('/') || '.';\n return {\n label: 'policy: lint',\n type: 'process',\n command: 'transcend',\n args: ['policy', 'lint', '--dir', target, '--noInteractive'],\n group: {\n kind: 'test',\n isDefault: true,\n },\n problemMatcher: [],\n };\n}\n\n/**\n * Merge the default policy lint task while preserving custom tasks.\n *\n * @param contents - Existing `.vscode/tasks.json` JSONC\n * @param repositoryRoot - Root that owns `.vscode`\n * @param targetDirectory - Selected policy project directory\n * @returns Merged task configuration and warnings\n */\nexport function mergePolicyEditorTasks(\n contents: string | null,\n repositoryRoot: string,\n targetDirectory: string,\n): PolicyEditorMergeResult {\n const parsed = parseEditorObject(contents, 'VS Code policy tasks');\n if ('warning' in parsed) {\n return { contents: parsed.contents, warnings: [parsed.warning] };\n }\n const { current } = parsed;\n const updates: JsoncUpdate[] = [];\n const warnings: string[] = [];\n const version = current.version;\n if (version === undefined) {\n updates.push({ path: ['version'], value: '2.0.0' });\n } else if (version !== '2.0.0') {\n warnings.push('VS Code task schema version is customized and was left unchanged.');\n }\n\n const desiredTask = buildPolicyLintTask(repositoryRoot, targetDirectory);\n const tasks = current.tasks;\n if (tasks === undefined) {\n updates.push({ path: ['tasks'], value: [desiredTask] });\n } else if (Array.isArray(tasks)) {\n const matchingTask = tasks.find(\n (task) =>\n task !== null &&\n typeof task === 'object' &&\n !Array.isArray(task) &&\n (task as Record<string, unknown>).label === 'policy: lint',\n );\n if (matchingTask === undefined) {\n updates.push({ path: ['tasks'], value: [...tasks, desiredTask] });\n } else if (!configurationValuesEqual(matchingTask, desiredTask)) {\n warnings.push(\n 'VS Code task \"policy: lint\" has repository-specific customization and was left unchanged.',\n );\n }\n } else {\n warnings.push('VS Code tasks use an unknown shape and were left unchanged.');\n }\n\n return applyEditorUpdates(contents, updates, 'VS Code policy tasks', warnings);\n}\n","import { isAbsolute, join, posix, relative, sep } from 'node:path';\n\nimport {\n getManagedAgentSkillCandidatePaths,\n planManagedAgentSkill,\n type ManagedAgentSkillDefinition,\n} from '../scaffolding/agent-skill.js';\nimport { displayProjectPath, quoteShellArgument } from '../scaffolding/project-plan-output.js';\nimport {\n getPlanningPathSnapshot,\n getPlanningFileSnapshot,\n planFileChange,\n type PlanningPathSnapshot,\n} from '../scaffolding/project-plan.js';\nimport { getPolicyManifestPath } from './policy-project-discovery.js';\nimport {\n generatePolicyGithubActionsWorkflow,\n POLICY_CI_WORKFLOW_PATH,\n} from './policy-scaffold-artifacts.js';\nimport {\n mergePolicyEditorExtensions,\n mergePolicyEditorSettings,\n mergePolicyEditorTasks,\n type PolicyEditorMergeResult,\n} from './policy-scaffold-config.js';\nimport {\n POLICY_INIT_RESULT_VERSION,\n PolicySetupFeature,\n type PolicyInitProjectPlan,\n type PolicyProjectState,\n type PolicySetupFeature as PolicySetupFeatureType,\n} from './policy-scaffold-model.js';\nimport { generatePolicyStarterFiles, type PolicyStarterFile } from './policy-scaffold-templates.js';\nimport { POLICY_SKILL_FILES, POLICY_SKILL_NAME } from './policy-skill.js';\n\n/** Managed Policy Engine Agent Skill definition. */\nconst POLICY_MANAGED_SKILL: ManagedAgentSkillDefinition = {\n name: POLICY_SKILL_NAME,\n displayName: 'Policy Engine',\n owner: '@transcend-io/cli',\n files: POLICY_SKILL_FILES,\n};\n\n/** In-memory input consumed by the pure policy initializer. */\nexport interface PolicyInitPlanningInput {\n /** Project discovery state. */\n state: PolicyProjectState;\n /** Potential mutation paths keyed by absolute path. */\n snapshots: Readonly<Record<string, PlanningPathSnapshot>>;\n}\n\n/** Optional repository setup selected for policy initialization. */\nexport interface PolicyInitPlanOptions {\n /** Selected setup features. */\n features: readonly PolicySetupFeatureType[];\n /** Exact released Transcend CLI version for generated CI. */\n cliVersion: string;\n}\n\n/**\n * Build the copyable policy lint command for one target.\n *\n * @param state - Discovered project state\n * @returns Raw one-line command\n */\nexport function buildPolicyLintCommand(state: PolicyProjectState): string {\n const directory = displayProjectPath(state.invocationDirectory, state.targetDirectory);\n return `transcend policy lint --dir ${quoteShellArgument(directory)} --noInteractive`;\n}\n\n/**\n * Enumerate all core starter paths that could be created.\n *\n * @param state - Policy project state\n * @param options - Selected repository setup\n * @returns Absolute candidate paths\n */\nexport function getPolicyInitPlanningCandidatePaths(\n state: PolicyProjectState,\n options: Pick<PolicyInitPlanOptions, 'features'>,\n): string[] {\n const paths = new Set(\n generatePolicyStarterFiles().map(({ path }) => join(state.targetDirectory, path)),\n );\n const selected = new Set(options.features);\n if (selected.has(PolicySetupFeature.Editor)) {\n paths.add(join(state.projectRoot, '.vscode', 'settings.json'));\n paths.add(join(state.projectRoot, '.vscode', 'extensions.json'));\n paths.add(join(state.projectRoot, '.vscode', 'tasks.json'));\n }\n if (selected.has(PolicySetupFeature.Skill)) {\n getManagedAgentSkillCandidatePaths(\n state.projectRoot,\n state.existingSkillDirectories,\n POLICY_MANAGED_SKILL,\n ).forEach((path) => paths.add(path));\n }\n if (selected.has(PolicySetupFeature.Ci) && state.repositoryRoot && state.usesGithub) {\n paths.add(join(state.repositoryRoot, POLICY_CI_WORKFLOW_PATH));\n }\n return [...paths].sort((left, right) => left.localeCompare(right));\n}\n\n/**\n * Ensure a destination stays below an approved project root.\n *\n * @param root - Approved root\n * @param path - Candidate path\n */\nfunction assertContained(root: string, path: string): void {\n const child = relative(root, path);\n if (child === '..' || child.startsWith(`..${sep}`) || isAbsolute(child)) {\n throw new Error(`Refusing to modify path outside project root: ${path}`);\n }\n}\n\n/**\n * Enumerate generated file and directory paths allowed in an exact starter.\n *\n * @param files - Starter files\n * @returns POSIX relative paths\n */\nfunction starterRelativePaths(files: readonly PolicyStarterFile[]): Set<string> {\n const paths = new Set<string>(['input.json']);\n files.forEach(({ path }) => {\n paths.add(path);\n let parent = posix.dirname(path);\n while (parent !== '.') {\n paths.add(parent);\n parent = posix.dirname(parent);\n }\n });\n return paths;\n}\n\n/**\n * Add or classify one regular-file mutation.\n *\n * @param plan - Policy plan being assembled\n * @param input - Collected snapshots\n * @param options - Desired file\n */\nfunction addFileChange(\n plan: PolicyInitProjectPlan,\n input: PolicyInitPlanningInput,\n options: {\n /** Absolute destination path. */\n path: string;\n /** Complete desired contents. */\n contents: string;\n /** Human-readable plan description. */\n description: string;\n /** Refuse existing contents. */\n createOnly?: boolean;\n },\n): void {\n const change = planFileChange({\n snapshot: getPlanningFileSnapshot(input.snapshots, options.path),\n after: options.contents,\n description: options.description,\n ...(options.createOnly === undefined ? {} : { createOnly: options.createOnly }),\n });\n if (change) {\n plan.changes.push(change);\n } else {\n plan.unchanged.push(options.path);\n }\n}\n\n/**\n * Add one safe editor merge and its preservation warnings.\n *\n * @param plan - Policy plan being assembled\n * @param input - Collected snapshots\n * @param path - Absolute editor artifact path\n * @param result - Pure JSONC merge result\n * @param description - Human-readable plan description\n * @param cwd - Invocation directory for portable warning paths\n */\nfunction addEditorMerge(\n plan: PolicyInitProjectPlan,\n input: PolicyInitPlanningInput,\n path: string,\n result: PolicyEditorMergeResult,\n description: string,\n cwd: string,\n): void {\n addFileChange(plan, input, {\n path,\n contents: result.contents,\n description,\n });\n plan.warnings.push(\n ...result.warnings.map((warning) => `${warning} (${displayProjectPath(cwd, path)})`),\n );\n}\n\n/**\n * Build a safe policy project plan without reading the filesystem.\n *\n * Empty targets receive the complete starter. Existing targets are classified\n * only; no domain file is added, merged, or overwritten.\n *\n * @param input - Collected project state and path snapshots\n * @param options - Selected setup and pinned CLI version\n * @returns Validated policy initialization plan\n */\nexport function buildPolicyInitPlan(\n input: PolicyInitPlanningInput,\n options: PolicyInitPlanOptions,\n): PolicyInitProjectPlan {\n const { state } = input;\n const files = generatePolicyStarterFiles();\n const manifestPath = getPolicyManifestPath(state);\n const lintCommand = buildPolicyLintCommand(state);\n const resultPath = join(state.targetDirectory, 'policy_engine', 'example', 'result.rego');\n const plan: PolicyInitProjectPlan = {\n version: POLICY_INIT_RESULT_VERSION,\n command: 'init',\n rootDirectory: state.projectRoot,\n targetDirectory: state.targetDirectory,\n manifestPath,\n changes: [],\n unchanged: [],\n warnings: [],\n nextSteps: [lintCommand],\n features: [...options.features],\n };\n\n const candidatePaths = getPolicyInitPlanningCandidatePaths(state, options);\n assertContained(state.projectRoot, state.targetDirectory);\n candidatePaths.forEach((path) => assertContained(state.projectRoot, path));\n\n let hasDisposableExample = false;\n if (state.relativeFilePaths.length === 0) {\n hasDisposableExample = true;\n plan.directoryPreconditions = [\n {\n path: state.targetDirectory,\n relativePaths: [...state.relativePaths],\n },\n ];\n files.forEach((file) => {\n const path = join(state.targetDirectory, file.path);\n const snapshot = getPlanningPathSnapshot(input.snapshots, path);\n if (snapshot.kind !== 'absent') {\n throw new Error(`Expected an empty policy target, but found an entry at: ${path}`);\n }\n addFileChange(plan, input, {\n path,\n contents: file.contents,\n description: file.description,\n createOnly: true,\n });\n });\n } else {\n let allStarterFilesMatch = true;\n files.forEach((file) => {\n const path = join(state.targetDirectory, file.path);\n const snapshot = getPlanningPathSnapshot(input.snapshots, path);\n if (snapshot.kind === 'file' && snapshot.contents === file.contents) {\n plan.unchanged.push(path);\n return;\n }\n allStarterFilesMatch = false;\n if (snapshot.kind !== 'absent') {\n plan.unchanged.push(path);\n plan.warnings.push(\n `Existing policy scaffold path was left unchanged: ${displayProjectPath(\n state.invocationDirectory,\n path,\n )}`,\n );\n }\n });\n hasDisposableExample = allStarterFilesMatch;\n\n const allowedPaths = starterRelativePaths(files);\n const hasCustomPaths = state.relativeFilePaths.some((path) => !allowedPaths.has(path));\n if (!allStarterFilesMatch || hasCustomPaths) {\n plan.warnings.push(\n `Existing policy target contains custom or partial content, so no starter files were added or overwritten. ` +\n `Review ${displayProjectPath(\n state.invocationDirectory,\n state.targetDirectory,\n )} manually, then run \\`${lintCommand}\\`.`,\n );\n }\n }\n if (hasDisposableExample) {\n plan.disposableExamplePath = resultPath;\n plan.nextSteps.push(\n `Edit ${quoteShellArgument(displayProjectPath(state.invocationDirectory, resultPath))}`,\n );\n }\n\n const selected = new Set(options.features);\n const root = state.projectRoot;\n if (selected.has(PolicySetupFeature.Editor)) {\n const settingsPath = join(root, '.vscode', 'settings.json');\n const extensionsPath = join(root, '.vscode', 'extensions.json');\n const tasksPath = join(root, '.vscode', 'tasks.json');\n const editorArtifacts = [\n {\n path: settingsPath,\n description: 'Merge strict target-scoped OPA and Rego editor settings',\n merge: mergePolicyEditorSettings,\n },\n {\n path: extensionsPath,\n description: 'Recommend the OPA extension and discourage its syntax-only conflict',\n merge: (\n contents: string | null,\n _repositoryRoot: string,\n _targetDirectory: string,\n ): PolicyEditorMergeResult => mergePolicyEditorExtensions(contents),\n },\n {\n path: tasksPath,\n description: 'Add the default target-scoped policy lint task',\n merge: mergePolicyEditorTasks,\n },\n ];\n editorArtifacts.forEach(({ path, description, merge }) => {\n const snapshot = getPlanningPathSnapshot(input.snapshots, path);\n if (snapshot.kind !== 'absent' && snapshot.kind !== 'file') {\n plan.unchanged.push(path);\n plan.warnings.push(\n `Existing VS Code artifact is not a regular file and was left unchanged: ${displayProjectPath(\n state.invocationDirectory,\n path,\n )}`,\n );\n return;\n }\n addEditorMerge(\n plan,\n input,\n path,\n merge(snapshot.kind === 'file' ? snapshot.contents : null, root, state.targetDirectory),\n description,\n state.invocationDirectory,\n );\n });\n }\n\n if (selected.has(PolicySetupFeature.Skill)) {\n const skillPlan = planManagedAgentSkill({\n rootDirectory: root,\n existingDirectories: state.existingSkillDirectories,\n snapshots: input.snapshots,\n skill: POLICY_MANAGED_SKILL,\n preserveModified: true,\n });\n plan.changes.push(...skillPlan.changes);\n plan.unchanged.push(...skillPlan.unchanged);\n plan.warnings.push(\n ...skillPlan.warnings.map((warning) => {\n return skillPlan.unchanged.reduce(\n (rendered, path) =>\n rendered.replace(path, displayProjectPath(state.invocationDirectory, path)),\n warning,\n );\n }),\n );\n }\n\n if (selected.has(PolicySetupFeature.Ci)) {\n if (!state.repositoryRoot || !state.usesGithub) {\n plan.warnings.push(\n 'GitHub Actions setup was selected, but this target is not inside a detected GitHub repository.',\n );\n } else {\n const workflowPath = join(state.repositoryRoot, POLICY_CI_WORKFLOW_PATH);\n const target =\n relative(state.repositoryRoot, state.targetDirectory).split(sep).join('/') || '.';\n const workflowContents = generatePolicyGithubActionsWorkflow({\n cliVersion: options.cliVersion,\n targetDirectory: target,\n });\n const workflowSnapshot = getPlanningPathSnapshot(input.snapshots, workflowPath);\n if (workflowSnapshot.kind === 'absent') {\n addFileChange(plan, input, {\n path: workflowPath,\n contents: workflowContents,\n description: 'Add credential-free Policy Engine validation',\n createOnly: true,\n });\n } else if (\n workflowSnapshot.kind === 'file' &&\n workflowSnapshot.contents === workflowContents\n ) {\n plan.unchanged.push(workflowPath);\n } else {\n plan.unchanged.push(workflowPath);\n plan.warnings.push(\n `Existing GitHub Actions workflow was left unchanged: ${displayProjectPath(\n state.invocationDirectory,\n workflowPath,\n )}. Adapt it manually to run \\`${lintCommand}\\`.`,\n );\n }\n }\n }\n\n plan.changes.forEach(({ path }) => assertContained(state.projectRoot, path));\n return plan;\n}\n","import colors from 'colors';\n\nimport { version as CLI_VERSION } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport {\n runCapturedProcess,\n type CapturedProcessResult,\n type CapturedProcessRunner,\n} from '../../../lib/cli/run-captured-process.js';\nimport {\n DEFAULT_POLICY_PROJECT_DIRECTORY,\n discoverPolicyProject,\n} from '../../../lib/policy/policy-project-discovery.js';\nimport {\n OPA_INSTALL_URL,\n OPA_MISSING_MESSAGE,\n parsePolicyToolVersion,\n MINIMUM_POLICY_STARTER_REGAL_VERSION,\n REGAL_INSTALL_URL,\n REGAL_MISSING_MESSAGE,\n unsupportedOpaVersionMessage,\n unsupportedRegalVersionMessage,\n} from '../../../lib/policy/policy-runtime.js';\nimport {\n PolicySetupFeature,\n type PolicySetupFeature as PolicySetupFeatureType,\n} from '../../../lib/policy/policy-scaffold-model.js';\nimport {\n buildPolicyInitAiHandoff,\n buildPolicyInitPlanResult,\n type PolicyInitToolVersions,\n} from '../../../lib/policy/policy-scaffold-output.js';\nimport {\n buildPolicyInitPlan,\n getPolicyInitPlanningCandidatePaths,\n} from '../../../lib/policy/policy-scaffold-planning.js';\nimport { collectPlanningSnapshots } from '../../../lib/scaffolding/project-discovery.js';\nimport { applyProjectPlan } from '../../../lib/scaffolding/project-plan-apply.js';\nimport {\n displayProjectPath,\n quoteShellArgument,\n renderProjectPlan,\n} from '../../../lib/scaffolding/project-plan-output.js';\nimport {\n PromptCancelledError,\n type PromptChoice,\n ScaffoldPrompts,\n} from '../../../lib/scaffolding/prompts.js';\n\n/** Flags for `transcend policy init`. */\nexport interface PolicyInitFlags {\n /** Install repository-level VS Code setup. */\n editor?: boolean;\n /** Install the Policy Engine Agent Skill. */\n skill?: boolean;\n /** Install validation-only GitHub Actions CI. */\n ci?: boolean;\n /** Disable prompts. */\n noInteractive: boolean;\n /** Render but do not apply the plan. */\n dryRun: boolean;\n /** Approve the final displayed plan. */\n yes: boolean;\n /** Emit one stable JSON result on stdout. */\n json: boolean;\n}\n\n/** User-facing optional setup labels. */\nconst SETUP_LABELS: Readonly<Record<PolicySetupFeatureType, string>> = {\n [PolicySetupFeature.Editor]: 'VS Code settings and lint task',\n [PolicySetupFeature.Skill]: 'Policy Engine Agent Skill',\n [PolicySetupFeature.Ci]: 'Validation-only GitHub Actions',\n};\n\n/** All optional setup features in stable prompt order. */\nconst ALL_SETUP_FEATURES = Object.values(PolicySetupFeature);\n\n/** Runtime compatibility detected before policy planning. */\ninterface PolicyRuntimeProbe {\n /** Compatible tool versions. */\n tools: PolicyInitToolVersions;\n /** Missing or incompatible runtime guidance. */\n warnings: string[];\n}\n\n/**\n * Whether this invocation can ask questions.\n *\n * @param flags - Interaction flags\n * @param stdinIsTTY - Whether standard input is interactive\n * @param stderrIsTTY - Whether prompt output is interactive\n * @returns Whether prompts are enabled\n */\nfunction isInteractiveInvocation(\n flags: Pick<PolicyInitFlags, 'json' | 'noInteractive'>,\n stdinIsTTY: boolean | undefined,\n stderrIsTTY: boolean | undefined,\n): boolean {\n return !flags.json && !flags.noInteractive && Boolean(stdinIsTTY && stderrIsTTY);\n}\n\n/**\n * Resolve setup from explicit flags or one default-selected checklist.\n *\n * @param prompts - Prompt adapters\n * @param flags - Setup flags\n * @param options - Interaction state\n * @returns Explicitly selected setup features\n */\nasync function resolveFeatures(\n prompts: ScaffoldPrompts,\n flags: PolicyInitFlags,\n options: {\n /** Whether prompts are available. */\n interactive: boolean;\n },\n): Promise<PolicySetupFeatureType[]> {\n const enabled: Readonly<Record<PolicySetupFeatureType, boolean | undefined>> = {\n [PolicySetupFeature.Editor]: flags.editor,\n [PolicySetupFeature.Skill]: flags.skill,\n [PolicySetupFeature.Ci]: flags.ci,\n };\n if (!options.interactive) {\n return ALL_SETUP_FEATURES.filter((feature) => enabled[feature] === true);\n }\n const choices: PromptChoice<PolicySetupFeatureType>[] = ALL_SETUP_FEATURES.map((feature) => ({\n name: SETUP_LABELS[feature],\n value: feature,\n checked: enabled[feature] !== false,\n }));\n return prompts.checkbox('Choose repository setup:', choices);\n}\n\n/**\n * Explain a failed version subprocess with official installation guidance.\n *\n * @param tool - Policy tool name\n * @param result - Failed captured process\n * @returns Actionable warning\n */\nfunction failedVersionProbeMessage(tool: 'OPA' | 'Regal', result: CapturedProcessResult): string {\n const detail = [result.stdout.trim(), result.stderr.trim()].filter(Boolean).join('\\n');\n const url = tool === 'OPA' ? OPA_INSTALL_URL : REGAL_INSTALL_URL;\n const requirement =\n tool === 'OPA' ? 'OPA 1.x' : `Regal ${MINIMUM_POLICY_STARTER_REGAL_VERSION} or newer`;\n return (\n `${requirement} is required, but \\`${tool.toLowerCase()} version\\` exited with code ` +\n `${result.code}${detail ? `: ${detail}` : '.'} ` +\n `Install or upgrade it using the official instructions: ${url}`\n );\n}\n\n/**\n * Probe both local policy runtimes without installing or modifying them.\n *\n * @param context - CLI context\n * @param cwd - Invocation working directory\n * @param runner - Captured subprocess runner\n * @returns Compatible versions and exact runtime guidance\n */\nasync function probePolicyRuntimes(\n context: LocalContext,\n cwd: string,\n runner: CapturedProcessRunner,\n): Promise<PolicyRuntimeProbe> {\n const tools: PolicyInitToolVersions = { opa: null, regal: null };\n const warnings: string[] = [];\n\n const opaResult = await runner('opa', ['version'], { cwd }, context);\n if (opaResult.error?.code === 'ENOENT') {\n warnings.push(OPA_MISSING_MESSAGE);\n } else {\n const output = `${opaResult.stdout}\\n${opaResult.stderr}`;\n const unsupported = unsupportedOpaVersionMessage(output);\n if (opaResult.code !== 0) {\n warnings.push(unsupported ?? failedVersionProbeMessage('OPA', opaResult));\n } else if (unsupported) {\n warnings.push(unsupported);\n } else {\n tools.opa = parsePolicyToolVersion(output)!.version;\n }\n }\n\n const regalResult = await runner('regal', ['version'], { cwd }, context);\n if (regalResult.error?.code === 'ENOENT') {\n warnings.push(REGAL_MISSING_MESSAGE);\n } else {\n const output = `${regalResult.stdout}\\n${regalResult.stderr}`;\n const unsupported = unsupportedRegalVersionMessage(\n output,\n MINIMUM_POLICY_STARTER_REGAL_VERSION,\n 'the generated OPA 1.13.1 capabilities configuration',\n );\n if (regalResult.code !== 0) {\n warnings.push(unsupported ?? failedVersionProbeMessage('Regal', regalResult));\n } else if (unsupported) {\n warnings.push(unsupported);\n } else {\n tools.regal = parsePolicyToolVersion(output)!.version;\n }\n }\n\n return { tools, warnings };\n}\n\n/**\n * Initialize a credential-free local Policy Engine project.\n *\n * @param this - CLI context\n * @param flags - Scaffold and interaction flags\n * @param directory - Target policy directory\n * @param runner - Captured policy tool runner\n */\nexport async function init(\n this: LocalContext,\n flags: PolicyInitFlags,\n directory: string = DEFAULT_POLICY_PROJECT_DIRECTORY,\n runner: CapturedProcessRunner = runCapturedProcess,\n): Promise<void> {\n doneInputValidation(this.process);\n try {\n const runtime = await probePolicyRuntimes(this, this.process.cwd(), runner);\n const state = discoverPolicyProject(this, directory);\n const prompts = new ScaffoldPrompts(this);\n const interactive = isInteractiveInvocation(\n flags,\n this.process.stdin.isTTY,\n this.process.stderr.isTTY,\n );\n const features = await resolveFeatures(prompts, flags, { interactive });\n const candidatePaths = getPolicyInitPlanningCandidatePaths(state, { features });\n const snapshots = collectPlanningSnapshots(this, state.projectRoot, candidatePaths);\n\n const plan = buildPolicyInitPlan(\n { state, snapshots },\n {\n features,\n cliVersion: CLI_VERSION,\n },\n );\n plan.warnings.push(...runtime.warnings);\n\n if (!flags.json) {\n this.logger.info(\n renderProjectPlan(plan, {\n cwd: this.process.cwd(),\n title: 'Policy initialization plan',\n details: [\n { label: 'Target', path: plan.targetDirectory },\n { label: 'Manifest', path: plan.manifestPath },\n ],\n }),\n );\n }\n\n let approved = plan.changes.length === 0 || flags.dryRun;\n if (plan.changes.length > 0 && !flags.dryRun) {\n if (flags.yes) {\n approved = true;\n } else if (interactive) {\n approved = await prompts.confirm('Apply this complete plan?', true);\n } else {\n throw new Error(\n 'The plan requires approval in a non-interactive invocation. Review with --dryRun, then pass --yes.',\n );\n }\n }\n\n if (approved && !flags.dryRun && plan.changes.length > 0) {\n await applyProjectPlan(this, plan);\n }\n const applied = approved && !flags.dryRun && plan.changes.length > 0;\n const setupAvailable = approved && !flags.dryRun;\n const aiHandoff = buildPolicyInitAiHandoff({\n projectPath: quoteShellArgument(\n displayProjectPath(this.process.cwd(), state.targetDirectory),\n ),\n ...(plan.disposableExamplePath\n ? {\n examplePath: quoteShellArgument(\n displayProjectPath(this.process.cwd(), plan.disposableExamplePath),\n ),\n }\n : {}),\n hasSkill: setupAvailable && features.includes(PolicySetupFeature.Skill),\n lintCommand: plan.nextSteps[0]!,\n });\n const result = buildPolicyInitPlanResult(plan, {\n applied,\n dryRun: flags.dryRun,\n cwd: this.process.cwd(),\n aiHandoff,\n tools: runtime.tools,\n });\n if (flags.json) {\n this.process.stdout.write(`${JSON.stringify(result)}\\n`);\n return;\n }\n if (flags.dryRun) {\n this.logger.info(colors.yellow('Dry run complete. No changes were written.'));\n return;\n }\n if (!approved) {\n this.logger.info(colors.yellow('No changes applied.'));\n return;\n }\n if (plan.changes.length === 0) {\n const message =\n plan.warnings.length === runtime.warnings.length\n ? 'Policy project is already initialized.'\n : 'Existing policy project was left unchanged.';\n this.logger.info(colors.green(message));\n } else {\n this.logger.info(colors.green('Policy project initialized.'));\n }\n if (plan.nextSteps.length > 0) {\n this.logger.info(`\\n${colors.bold('Next steps')}`);\n plan.nextSteps.forEach((step) => this.logger.info(step));\n }\n this.logger.info(`\\n${colors.bold('AI handoff — paste into your coding agent')}`);\n this.logger.info(aiHandoff);\n } catch (error) {\n if (error instanceof PromptCancelledError) {\n return this.process.exit(130);\n }\n throw error;\n }\n}\n"],"mappings":"umBAUA,MAAa,EAAmC,mBAShD,SAAgB,GACd,EACA,EAAoB,EACA,CACpB,IAAM,EAAsB,EAAQ,QAAQ,KAAK,CAC3C,EAAkB,GAAQ,EAAqB,EAAU,CAC/D,GACE,EAAQ,GAAG,WAAW,EAAgB,EACtC,CAAC,EAAQ,GAAG,SAAS,EAAgB,CAAC,aAAa,CAEnD,MAAU,MAAM,qCAAqC,IAAkB,CAOzE,MAAO,CACL,sBACA,kBACA,GARiB,EAA0B,EAAS,CACpD,sBACA,kBACA,sBAAuB,EACxB,CAIc,CACb,cAAe,EAA4B,EAAS,EAAgB,CACpE,kBAAmB,EAA4B,EAAS,EAAiB,CACvE,mBAAoB,GACrB,CAAC,CACH,CASH,SAAgB,GAAsB,EAAmC,CACvE,OAAO,EAAK,EAAM,gBAAiB,gBAAgB,CC/CrD,MAAa,EAAqB,CAEhC,OAAQ,SAER,MAAO,QAEP,GAAI,KACL,QCdD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KCAA;;;;;;;;;;;;;;;;;;;;KCAA,ywDCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECQA,MAAa,EAAoB,0BAWpB,EAAgD,CAC3D,CAAE,KAAM,WAAY,SAAUA,GAAiB,CAC/C,CAAE,KAAM,8BAA+B,SAAUC,GAAmC,CACpF,CAAE,KAAM,0BAA2B,SAAUC,GAA+B,CAC5E,CAAE,KAAM,kCAAmC,SAAUC,GAAuC,CAC5F,CAAE,KAAM,2BAA4B,SAAUC,GAAgC,CAC/E,CCwB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AmB,KAAK,QAAQ,KAAK,CAAE,EAAK,sBAAsB,CACnE,CACF,CACD,EAAE,CACN,SAAU,GAAkB,EAAS,SAAS,EAAmB,MAAM,CACvE,YAAa,EAAK,UAAU,GAC7B,CAAC,CACI,EAAS,EAA0B,EAAM,CAC7C,UACA,OAAQ,EAAM,OACd,IAAK,KAAK,QAAQ,KAAK,CACvB,YACA,MAAO,EAAQ,MAChB,CAAC,CACF,GAAI,EAAM,KAAM,CACd,KAAK,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,EAAO,CAAC,IAAI,CACxD,OAEF,GAAI,EAAM,OAAQ,CAChB,KAAK,OAAO,KAAK,EAAO,OAAO,6CAA6C,CAAC,CAC7E,OAEF,GAAI,CAAC,EAAU,CACb,KAAK,OAAO,KAAK,EAAO,OAAO,sBAAsB,CAAC,CACtD,OAEF,GAAI,EAAK,QAAQ,SAAW,EAAG,CAC7B,IAAM,EACJ,EAAK,SAAS,SAAW,EAAQ,SAAS,OACtC,yCACA,8CACN,KAAK,OAAO,KAAK,EAAO,MAAM,EAAQ,CAAC,MAEvC,KAAK,OAAO,KAAK,EAAO,MAAM,8BAA8B,CAAC,CAE3D,EAAK,UAAU,OAAS,IAC1B,KAAK,OAAO,KAAK,KAAK,EAAO,KAAK,aAAa,GAAG,CAClD,EAAK,UAAU,QAAS,GAAS,KAAK,OAAO,KAAK,EAAK,CAAC,EAE1D,KAAK,OAAO,KAAK,KAAK,EAAO,KAAK,4CAA4C,GAAG,CACjF,KAAK,OAAO,KAAK,EAAU,OACpB,EAAO,CACd,GAAI,aAAiB,GACnB,OAAO,KAAK,QAAQ,KAAK,IAAI,CAE/B,MAAM"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./markSilentPrivacyRequests-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{t as e}from"./markSilentPrivacyRequests-BUYzKbhW.mjs";import{t}from"./done-input-validation-BUz-aVC5.mjs";async function n({auth:n,transcendUrl:r,actions:i,statuses:a,requestIds:o,createdAtBefore:s,createdAtAfter:c,updatedAtBefore:l,updatedAtAfter:u,concurrency:d}){t(this.process),await e({transcendUrl:r,requestActions:i,auth:n,requestIds:o,statuses:a,concurrency:d,createdAtBefore:s,createdAtAfter:c,updatedAtBefore:l,updatedAtAfter:u})}export{n as markSilent};
|
|
2
|
+
//# sourceMappingURL=impl-CQtMFz1O.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-CQtMFz1O.mjs","names":[],"sources":["../src/commands/request/mark-silent/impl.ts"],"sourcesContent":["import type { RequestAction, RequestStatus } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { markSilentPrivacyRequests } from '../../../lib/requests/index.js';\n\nexport interface MarkSilentCommandFlags {\n auth: string;\n actions: RequestAction[];\n statuses?: RequestStatus[];\n requestIds?: string[];\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n transcendUrl: string;\n concurrency: number;\n}\n\nexport async function markSilent(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n actions,\n statuses,\n requestIds,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n concurrency,\n }: MarkSilentCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await markSilentPrivacyRequests({\n transcendUrl,\n requestActions: actions,\n auth,\n requestIds,\n statuses,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n });\n}\n"],"mappings":"iHAmBA,eAAsB,EAEpB,CACE,OACA,eACA,UACA,WACA,aACA,kBACA,iBACA,kBACA,iBACA,eAEa,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAA0B,CAC9B,eACA,eAAgB,EAChB,OACA,aACA,WACA,cACA,kBACA,iBACA,kBACA,iBACD,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./cancelPrivacyRequests-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{t as e}from"./cancelPrivacyRequests-Ds6HKabX.mjs";import{t}from"./done-input-validation-BUz-aVC5.mjs";async function n({auth:n,actions:r,statuses:i=[],requestIds:a,silentModeBefore:o,createdAtBefore:s,createdAtAfter:c,updatedAtBefore:l,updatedAtAfter:u,cancellationTitle:d,transcendUrl:f,concurrency:p}){t(this.process),await e({transcendUrl:f,requestActions:r,auth:n,cancellationTitle:d,requestIds:a,statuses:i,concurrency:p,silentModeBefore:o?new Date(o):void 0,createdAtBefore:s?new Date(s):void 0,createdAtAfter:c?new Date(c):void 0,updatedAtBefore:l?new Date(l):void 0,updatedAtAfter:u?new Date(u):void 0})}export{n as cancel};
|
|
2
|
+
//# sourceMappingURL=impl-CSRal4Rj2.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-CSRal4Rj2.mjs","names":[],"sources":["../src/commands/request/cancel/impl.ts"],"sourcesContent":["import { RequestAction, RequestStatus } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { cancelPrivacyRequests } from '../../../lib/requests/index.js';\n\nexport interface CancelCommandFlags {\n auth: string;\n actions: RequestAction[];\n statuses?: RequestStatus[];\n requestIds?: string[];\n silentModeBefore?: Date;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n cancellationTitle: string;\n transcendUrl: string;\n concurrency: number;\n}\n\nexport async function cancel(\n this: LocalContext,\n {\n auth,\n actions,\n statuses = [],\n requestIds,\n silentModeBefore,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n cancellationTitle,\n transcendUrl,\n concurrency,\n }: CancelCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await cancelPrivacyRequests({\n transcendUrl,\n requestActions: actions,\n auth,\n cancellationTitle,\n requestIds,\n statuses,\n concurrency,\n silentModeBefore: silentModeBefore ? new Date(silentModeBefore) : undefined,\n createdAtBefore: createdAtBefore ? new Date(createdAtBefore) : undefined,\n createdAtAfter: createdAtAfter ? new Date(createdAtAfter) : undefined,\n updatedAtBefore: updatedAtBefore ? new Date(updatedAtBefore) : undefined,\n updatedAtAfter: updatedAtAfter ? new Date(updatedAtAfter) : undefined,\n });\n}\n"],"mappings":"6GAqBA,eAAsB,EAEpB,CACE,OACA,UACA,WAAW,EAAE,CACb,aACA,mBACA,kBACA,iBACA,kBACA,iBACA,oBACA,eACA,eAEa,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAAsB,CAC1B,eACA,eAAgB,EAChB,OACA,oBACA,aACA,WACA,cACA,iBAAkB,EAAmB,IAAI,KAAK,EAAiB,CAAG,IAAA,GAClE,gBAAiB,EAAkB,IAAI,KAAK,EAAgB,CAAG,IAAA,GAC/D,eAAgB,EAAiB,IAAI,KAAK,EAAe,CAAG,IAAA,GAC5D,gBAAiB,EAAkB,IAAI,KAAK,EAAgB,CAAG,IAAA,GAC/D,eAAgB,EAAiB,IAAI,KAAK,EAAe,CAAG,IAAA,GAC7D,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./pullChunkedCustomSiloOutstandingIdentifiers-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{t as e}from"./pullChunkedCustomSiloOutstandingIdentifiers-BxolFAfF.mjs";import{i as t,s as n}from"./writeCsv-D-2siSwE.mjs";import{t as r}from"./done-input-validation-BUz-aVC5.mjs";import{chunk as i,uniq as a}from"lodash-es";import o from"colors";import{buildTranscendGraphQLClient as s,fetchRequestFilesForRequest as c}from"@transcend-io/sdk";import{map as l}from"@transcend-io/utils";async function u({file:u,fileTarget:d,transcendUrl:f,auth:p,sombraAuth:m,cronDataSiloId:h,targetDataSiloId:g,actions:_,skipRequestCount:v,pageLimit:y,chunkSize:b}){v&&this.logger.info(o.yellow(`Skipping request count as requested. This may help speed up the call.`)),(Number.isNaN(b)||b<=0||b%y!==0)&&(this.logger.error(o.red(`Invalid chunk size: "${b}". Must be a positive integer that is a multiple of ${y}.`)),this.process.exit(1)),r(this.process);let x=s(f,p),{baseName:S,extension:C}=t(u),{baseName:w,extension:T}=t(d),E=0,D=0,O=0;await e({dataSiloId:h,auth:p,sombraAuth:m,actions:_,apiPageSize:y,savePageSize:b,onSave:async e=>{E+=e.length;let t=await l(i(a(e.map(e=>e.requestId)),y),async e=>(this.logger.info(o.magenta(`Fetching target identifiers for ${e.length} requests`)),(await c(x,{logger:this.logger,pageSize:y*2,filterBy:{requestIds:e,dataSiloIds:[g]}})).map(({fileName:e,remoteId:t})=>{if(!t)throw Error(`Failed to find remoteId for ${e}`);return{RecordId:t,Object:e.replace(`.json`,``).split(`/`).pop()?.replace(` Information`,``),Comment:`Customer data deletion request submitted via transcend.io`}})),{concurrency:1});D+=t.flat().length;let r=a(e.map(e=>Object.keys(e)).flat()),s=`${S}-${O}${C}`,f=`${w}-${O}${T}`;await n(s,e,r),this.logger.info(o.green(`Successfully wrote ${e.length} identifiers to file "${u}"`));let p=t.flat();await n(f,p,a(p.map(e=>Object.keys(e)).flat())),this.logger.info(o.green(`Successfully wrote ${p.length} identifiers to file "${d}"`)),this.logger.info(o.blue(`Processed chunk of ${i.length} identifiers, found ${p.length} target identifiers`)),O+=1},transcendUrl:f,skipRequestCount:v}),this.logger.info(o.green(`Successfully wrote ${E} identifiers to file "${u}"`)),this.logger.info(o.green(`Successfully wrote ${D} identifiers to file "${d}"`))}export{u as pullProfiles};
|
|
2
|
+
//# sourceMappingURL=impl-CSmFd6iO2.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-CSmFd6iO2.mjs","names":[],"sources":["../src/commands/request/cron/pull-profiles/impl.ts"],"sourcesContent":["import type { RequestAction } from '@transcend-io/privacy-types';\nimport { buildTranscendGraphQLClient, fetchRequestFilesForRequest } from '@transcend-io/sdk';\nimport { map } from '@transcend-io/utils';\nimport colors from 'colors';\nimport { uniq, chunk } from 'lodash-es';\n\nimport type { LocalContext } from '../../../../context.js';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation.js';\nimport {\n pullChunkedCustomSiloOutstandingIdentifiers,\n type CsvFormattedIdentifier,\n} from '../../../../lib/cron/index.js';\nimport { parseFilePath, writeLargeCsv } from '../../../../lib/helpers/index.js';\n\nexport interface PullProfilesCommandFlags {\n file: string;\n fileTarget: string;\n transcendUrl: string;\n auth: string;\n sombraAuth?: string;\n cronDataSiloId: string;\n targetDataSiloId: string;\n actions: RequestAction[];\n skipRequestCount: boolean;\n pageLimit: number;\n chunkSize: number;\n}\n\nexport async function pullProfiles(\n this: LocalContext,\n {\n file,\n fileTarget,\n transcendUrl,\n auth,\n sombraAuth,\n cronDataSiloId,\n targetDataSiloId,\n actions,\n skipRequestCount,\n pageLimit,\n chunkSize,\n }: PullProfilesCommandFlags,\n): Promise<void> {\n if (skipRequestCount) {\n this.logger.info(\n colors.yellow('Skipping request count as requested. This may help speed up the call.'),\n );\n }\n\n if (Number.isNaN(chunkSize) || chunkSize <= 0 || chunkSize % pageLimit !== 0) {\n this.logger.error(\n colors.red(\n `Invalid chunk size: \"${chunkSize}\". Must be a positive integer that is a multiple of ${pageLimit}.`,\n ),\n );\n this.process.exit(1);\n }\n\n doneInputValidation(this.process);\n\n // Create GraphQL client to connect to Transcend backend\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n const { baseName, extension } = parseFilePath(file);\n const { baseName: baseNameTarget, extension: extensionTarget } = parseFilePath(fileTarget);\n\n let allIdentifiersCount = 0;\n let allTargetIdentifiersCount = 0;\n let fileCount = 0;\n // Create onSave callback to handle chunked processing\n const onSave = async (chunkToSave: CsvFormattedIdentifier[]): Promise<void> => {\n // Add to all identifiers\n allIdentifiersCount += chunkToSave.length;\n\n // Get unique request IDs from this chunk\n const requestIds = chunkToSave.map((d) => d.requestId as string);\n const uniqueRequestIds = uniq(requestIds);\n\n // Pull down target identifiers for this chunk\n const chunkedRequestIds = chunk(uniqueRequestIds, pageLimit);\n const results = await map(\n chunkedRequestIds,\n async (requestIds) => {\n this.logger.info(\n colors.magenta(`Fetching target identifiers for ${requestIds.length} requests`),\n );\n const results = await fetchRequestFilesForRequest(client, {\n logger: this.logger,\n pageSize: pageLimit * 2,\n filterBy: {\n requestIds,\n dataSiloIds: [targetDataSiloId],\n },\n });\n return results.map(({ fileName, remoteId }) => {\n if (!remoteId) {\n throw new Error(`Failed to find remoteId for ${fileName}`);\n }\n return {\n RecordId: remoteId,\n Object: fileName.replace('.json', '').split('/').pop()?.replace(' Information', ''),\n Comment: 'Customer data deletion request submitted via transcend.io',\n };\n });\n },\n // We are grabbing all the request files for the 'pageLimit' # of requests at a time\n {\n concurrency: 1,\n },\n );\n\n allTargetIdentifiersCount += results.flat().length;\n\n // Write the identifiers and target identifiers to CSV\n const headers = uniq(chunkToSave.map((d) => Object.keys(d)).flat());\n const numberedFileName = `${baseName}-${fileCount}${extension}`;\n const numberedFileNameTarget = `${baseNameTarget}-${fileCount}${extensionTarget}`;\n await writeLargeCsv(numberedFileName, chunkToSave, headers);\n this.logger.info(\n colors.green(`Successfully wrote ${chunkToSave.length} identifiers to file \"${file}\"`),\n );\n\n const targetIdentifiers = results.flat();\n const headers2 = uniq(targetIdentifiers.map((d) => Object.keys(d)).flat());\n await writeLargeCsv(numberedFileNameTarget, targetIdentifiers, headers2);\n this.logger.info(\n colors.green(\n `Successfully wrote ${targetIdentifiers.length} identifiers to file \"${fileTarget}\"`,\n ),\n );\n\n this.logger.info(\n colors.blue(\n `Processed chunk of ${chunk.length} identifiers, found ${targetIdentifiers.length} target identifiers`,\n ),\n );\n fileCount += 1;\n };\n\n // Pull down outstanding identifiers using the new chunked function\n await pullChunkedCustomSiloOutstandingIdentifiers({\n dataSiloId: cronDataSiloId,\n auth,\n sombraAuth,\n actions,\n apiPageSize: pageLimit,\n savePageSize: chunkSize,\n onSave,\n transcendUrl,\n skipRequestCount,\n });\n\n this.logger.info(\n colors.green(`Successfully wrote ${allIdentifiersCount} identifiers to file \"${file}\"`),\n );\n this.logger.info(\n colors.green(\n `Successfully wrote ${allTargetIdentifiersCount} identifiers to file \"${fileTarget}\"`,\n ),\n );\n}\n"],"mappings":"wYA4BA,eAAsB,EAEpB,CACE,OACA,aACA,eACA,OACA,aACA,iBACA,mBACA,UACA,mBACA,YACA,aAEa,CACX,GACF,KAAK,OAAO,KACV,EAAO,OAAO,wEAAwE,CACvF,EAGC,OAAO,MAAM,EAAU,EAAI,GAAa,GAAK,EAAY,IAAc,KACzE,KAAK,OAAO,MACV,EAAO,IACL,wBAAwB,EAAU,sDAAsD,EAAU,GACnG,CACF,CACD,KAAK,QAAQ,KAAK,EAAE,EAGtB,EAAoB,KAAK,QAAQ,CAGjC,IAAM,EAAS,EAA4B,EAAc,EAAK,CACxD,CAAE,WAAU,aAAc,EAAc,EAAK,CAC7C,CAAE,SAAU,EAAgB,UAAW,GAAoB,EAAc,EAAW,CAEtF,EAAsB,EACtB,EAA4B,EAC5B,EAAY,EAwEhB,MAAM,EAA4C,CAChD,WAAY,EACZ,OACA,aACA,UACA,YAAa,EACb,aAAc,EACd,YA7EoB,IAAyD,CAE7E,GAAuB,EAAY,OAQnC,IAAM,EAAU,MAAM,EADI,EAHD,EADN,EAAY,IAAK,GAAM,EAAE,UACJ,CAGQ,CAAE,EAE/B,CACjB,KAAO,KACL,KAAK,OAAO,KACV,EAAO,QAAQ,mCAAmC,EAAW,OAAO,WAAW,CAChF,EASM,MARe,EAA4B,EAAQ,CACxD,OAAQ,KAAK,OACb,SAAU,EAAY,EACtB,SAAU,CACR,aACA,YAAa,CAAC,EAAiB,CAChC,CACF,CAAC,EACa,KAAK,CAAE,WAAU,cAAe,CAC7C,GAAI,CAAC,EACH,MAAU,MAAM,+BAA+B,IAAW,CAE5D,MAAO,CACL,SAAU,EACV,OAAQ,EAAS,QAAQ,QAAS,GAAG,CAAC,MAAM,IAAI,CAAC,KAAK,EAAE,QAAQ,eAAgB,GAAG,CACnF,QAAS,4DACV,EACD,EAGJ,CACE,YAAa,EACd,CACF,CAED,GAA6B,EAAQ,MAAM,CAAC,OAG5C,IAAM,EAAU,EAAK,EAAY,IAAK,GAAM,OAAO,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC,CAC7D,EAAmB,GAAG,EAAS,GAAG,IAAY,IAC9C,EAAyB,GAAG,EAAe,GAAG,IAAY,IAChE,MAAM,EAAc,EAAkB,EAAa,EAAQ,CAC3D,KAAK,OAAO,KACV,EAAO,MAAM,sBAAsB,EAAY,OAAO,wBAAwB,EAAK,GAAG,CACvF,CAED,IAAM,EAAoB,EAAQ,MAAM,CAExC,MAAM,EAAc,EAAwB,EAD3B,EAAK,EAAkB,IAAK,GAAM,OAAO,KAAK,EAAE,CAAC,CAAC,MAAM,CACF,CAAC,CACxE,KAAK,OAAO,KACV,EAAO,MACL,sBAAsB,EAAkB,OAAO,wBAAwB,EAAW,GACnF,CACF,CAED,KAAK,OAAO,KACV,EAAO,KACL,sBAAsB,EAAM,OAAO,sBAAsB,EAAkB,OAAO,qBACnF,CACF,CACD,GAAa,GAYb,eACA,mBACD,CAAC,CAEF,KAAK,OAAO,KACV,EAAO,MAAM,sBAAsB,EAAoB,wBAAwB,EAAK,GAAG,CACxF,CACD,KAAK,OAAO,KACV,EAAO,MACL,sBAAsB,EAA0B,wBAAwB,EAAW,GACpF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./downloadPrivacyRequestFiles-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{t as e}from"./downloadPrivacyRequestFiles-BZjAtiKF.mjs";import{t}from"./done-input-validation-BUz-aVC5.mjs";import{RequestStatus as n}from"@transcend-io/privacy-types";async function r({auth:r,transcendUrl:i,folderPath:a,requestIds:o,statuses:s=[n.Approving,n.Downloadable],concurrency:c,createdAtBefore:l,createdAtAfter:u,updatedAtBefore:d,updatedAtAfter:f,approveAfterDownload:p}){t(this.process),await e({transcendUrl:i,auth:r,folderPath:a,requestIds:o,statuses:s,concurrency:c,createdAtBefore:l,createdAtAfter:u,updatedAtBefore:d,updatedAtAfter:f,approveAfterDownload:p})}export{r as downloadFiles};
|
|
2
|
+
//# sourceMappingURL=impl-CfMrFWb_.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-CfMrFWb_.mjs","names":[],"sources":["../src/commands/request/download-files/impl.ts"],"sourcesContent":["import { RequestStatus } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { downloadPrivacyRequestFiles } from '../../../lib/requests/index.js';\n\nexport interface DownloadFilesCommandFlags {\n auth: string;\n sombraAuth?: string;\n concurrency: number;\n requestIds?: string[];\n statuses?: RequestStatus[];\n folderPath: string;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n approveAfterDownload: boolean;\n transcendUrl: string;\n}\n\nexport async function downloadFiles(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n folderPath,\n requestIds,\n statuses = [RequestStatus.Approving, RequestStatus.Downloadable],\n concurrency,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n approveAfterDownload,\n }: DownloadFilesCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await downloadPrivacyRequestFiles({\n transcendUrl,\n auth,\n folderPath,\n requestIds,\n statuses,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n approveAfterDownload,\n });\n}\n"],"mappings":"+KAqBA,eAAsB,EAEpB,CACE,OACA,eACA,aACA,aACA,WAAW,CAAC,EAAc,UAAW,EAAc,aAAa,CAChE,cACA,kBACA,iBACA,kBACA,iBACA,wBAEa,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAA4B,CAChC,eACA,OACA,aACA,aACA,WACA,cACA,kBACA,iBACA,kBACA,iBACA,uBACD,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./pullManualEnrichmentIdentifiersToCsv-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{t as e}from"./pullManualEnrichmentIdentifiersToCsv-DcLZeqF2.mjs";import{t}from"./done-input-validation-BUz-aVC5.mjs";async function n({auth:n,transcendUrl:r,file:i,concurrency:a,actions:o,sombraAuth:s}){t(this.process),await e({file:i,transcendUrl:r,concurrency:a,requestActions:o,auth:n,sombraAuth:s})}export{n as pullIdentifiers};
|
|
2
|
+
//# sourceMappingURL=impl-DInF5q00.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-DInF5q00.mjs","names":[],"sources":["../src/commands/request/preflight/pull-identifiers/impl.ts"],"sourcesContent":["import type { RequestAction } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../../context.js';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation.js';\nimport { pullManualEnrichmentIdentifiersToCsv } from '../../../../lib/manual-enrichment/index.js';\n\nexport interface PullIdentifiersCommandFlags {\n auth: string;\n sombraAuth?: string;\n transcendUrl: string;\n file: string;\n actions?: RequestAction[];\n concurrency: number;\n}\n\nexport async function pullIdentifiers(\n this: LocalContext,\n { auth, transcendUrl, file, concurrency, actions, sombraAuth }: PullIdentifiersCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await pullManualEnrichmentIdentifiersToCsv({\n file,\n transcendUrl,\n concurrency,\n requestActions: actions,\n auth,\n sombraAuth,\n });\n}\n"],"mappings":"4HAeA,eAAsB,EAEpB,CAAE,OAAM,eAAc,OAAM,cAAa,UAAS,cACnC,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAAqC,CACzC,OACA,eACA,cACA,eAAgB,EAChB,OACA,aACD,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./approvePrivacyRequests-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{t as e}from"./approvePrivacyRequests-DDT8Zjhc.mjs";import{t}from"./done-input-validation-BUz-aVC5.mjs";async function n({auth:n,actions:r,origins:i,silentModeBefore:a,createdAtBefore:o,createdAtAfter:s,updatedAtBefore:c,updatedAtAfter:l,transcendUrl:u,concurrency:d}){t(this.process),await e({transcendUrl:u,requestActions:r,auth:n,requestOrigins:i,concurrency:d,silentModeBefore:a,createdAtBefore:o,createdAtAfter:s,updatedAtBefore:c,updatedAtAfter:l})}export{n as approve};
|
|
2
|
+
//# sourceMappingURL=impl-DKNJFnFv2.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-DKNJFnFv2.mjs","names":[],"sources":["../src/commands/request/approve/impl.ts"],"sourcesContent":["import { RequestAction, RequestOrigin } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { approvePrivacyRequests } from '../../../lib/requests/index.js';\n\nexport interface ApproveCommandFlags {\n auth: string;\n actions: RequestAction[];\n origins?: RequestOrigin[];\n silentModeBefore?: Date;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n transcendUrl: string;\n concurrency: number;\n}\n\nexport async function approve(\n this: LocalContext,\n {\n auth,\n actions,\n origins,\n silentModeBefore,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n transcendUrl,\n concurrency,\n }: ApproveCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await approvePrivacyRequests({\n transcendUrl,\n requestActions: actions,\n auth,\n requestOrigins: origins,\n concurrency,\n silentModeBefore,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n });\n}\n"],"mappings":"8GAmBA,eAAsB,EAEpB,CACE,OACA,UACA,UACA,mBACA,kBACA,iBACA,kBACA,iBACA,eACA,eAEa,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAAuB,CAC3B,eACA,eAAgB,EAChB,OACA,eAAgB,EAChB,cACA,mBACA,kBACA,iBACA,kBACA,iBACD,CAAC"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{r as e}from"./constants-
|
|
1
|
+
import{r as e}from"./constants-X60pMfSm.mjs";import{a as t}from"./writeCsv-D-2siSwE.mjs";import{t as n}from"./pullConsentManagerMetrics-Dv5n1ZGp.mjs";import{t as r}from"./validateTranscendAuth-D6Wr1cxY.mjs";import{t as i}from"./done-input-validation-BUz-aVC5.mjs";import{ConsentManagerMetricBin as a}from"@transcend-io/privacy-types";import o from"node:path";import s from"colors";import{buildTranscendGraphQLClient as c}from"@transcend-io/sdk";import{map as l,mapSeries as u}from"@transcend-io/utils";async function d({auth:d,start:f,end:p,folder:m,bin:h,transcendUrl:g}){let _=h;Object.values(a).includes(_)||(this.logger.error(s.red(`Failed to parse argument "bin" with value "${h}"\nExpected one of: \n${Object.values(a).join(`
|
|
2
2
|
`)}`)),this.process.exit(1));let v=new Date(f),y=p?new Date(p):new Date;Number.isNaN(v.getTime())&&(this.logger.error(s.red(`Start date provided is invalid date. Got --start="${f}" expected --start="01/01/2023"`)),this.process.exit(1)),Number.isNaN(y.getTime())&&(this.logger.error(s.red(`End date provided is invalid date. Got --end="${p}" expected --end="01/01/2023"`)),this.process.exit(1)),v>y&&(this.logger.error(s.red(`Got a start date "${v.toISOString()}" that was larger than the end date "${y.toISOString()}". Start date must be before end date.`)),this.process.exit(1)),i(this.process);let b=await r(d,this);if(this.fs.existsSync(m)&&!this.fs.lstatSync(m).isDirectory()&&(this.logger.error(s.red(`The provided argument "folder" was passed a file. expected: folder="./consent-metrics/"`)),this.process.exit(1)),this.fs.existsSync(m)||this.fs.mkdirSync(m),this.logger.info(s.magenta(`Pulling consent metrics from start=${v.toString()} to end=${y.toISOString()} with bin size "${h}"`)),typeof b==`string`){try{let e=await n(c(g,b),{bin:_,start:v,end:y});await l(Object.entries(e),async([e,n])=>{await l(n,async({points:n,name:r})=>{let i=o.join(m,`${e}_${r}.csv`);this.logger.info(s.magenta(`Writing configuration to file "${i}"...`)),await t(i,n.map(({key:e,value:t})=>({timestamp:e,value:t})))},{concurrency:5})},{concurrency:5})}catch(e){this.logger.error(s.red(`An error occurred syncing the schema: ${e.message}`)),this.process.exit(1)}this.logger.info(s.green(`Successfully synced consent metrics to disk in folder "${m}"! View at ${e}`))}else{let r=[];await u(b,async(e,i)=>{let a=`[${i+1}/${b.length}][${e.organizationName}] `;this.logger.info(s.magenta(`~~~\n\n${a}Attempting to pull consent metrics...\n\n~~~`));let l=c(g,e.apiKey);try{let r=await n(l,{bin:_,start:v,end:y}),i=o.join(m,e.organizationName);this.fs.existsSync(i)||this.fs.mkdirSync(i),Object.entries(r).forEach(([e,n])=>{n.forEach(({points:n,name:r})=>{let a=o.join(i,`${e}_${r}.csv`);this.logger.info(s.magenta(`Writing configuration to file "${a}"...`)),t(a,n.map(({key:e,value:t})=>({timestamp:e,value:t})))})}),this.logger.info(s.green(`${a}Successfully pulled configuration!`))}catch(t){this.logger.error(s.red(`${a}Failed to sync configuration.`),t),r.push(e.organizationName)}}),r.length>0&&(this.logger.info(s.red(`Sync encountered errors for "${r.join(`,`)}". View output above for more information, or check out ${e}`)),this.process.exit(1))}}export{d as pullConsentMetrics};
|
|
3
|
-
//# sourceMappingURL=impl-
|
|
3
|
+
//# sourceMappingURL=impl-DOuVyX0O.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-DOuVyX0O.mjs","names":[],"sources":["../src/commands/consent/pull-consent-metrics/impl.ts"],"sourcesContent":["import path from 'node:path';\n\nimport { ConsentManagerMetricBin } from '@transcend-io/privacy-types';\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport { map, mapSeries } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport { ADMIN_DASH_INTEGRATIONS } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { validateTranscendAuth } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { pullConsentManagerMetrics } from '../../../lib/consent-manager/index.js';\nimport { writeCsv } from '../../../lib/helpers/index.js';\n\nexport interface PullConsentMetricsCommandFlags {\n auth: string;\n start: Date;\n end?: Date;\n folder: string;\n bin: string;\n transcendUrl: string;\n}\n\nexport async function pullConsentMetrics(\n this: LocalContext,\n { auth, start, end, folder, bin, transcendUrl }: PullConsentMetricsCommandFlags,\n): Promise<void> {\n // Validate bin\n const parsedBin = bin as ConsentManagerMetricBin;\n if (!Object.values(ConsentManagerMetricBin).includes(parsedBin)) {\n this.logger.error(\n colors.red(\n `Failed to parse argument \"bin\" with value \"${bin}\"\\n` +\n `Expected one of: \\n${Object.values(ConsentManagerMetricBin).join('\\n')}`,\n ),\n );\n this.process.exit(1);\n }\n\n // Parse the dates\n const startDate = new Date(start);\n const endDate = end ? new Date(end) : new Date();\n if (Number.isNaN(startDate.getTime())) {\n this.logger.error(\n colors.red(\n `Start date provided is invalid date. Got --start=\"${start}\" expected --start=\"01/01/2023\"`,\n ),\n );\n this.process.exit(1);\n }\n if (Number.isNaN(endDate.getTime())) {\n this.logger.error(\n colors.red(\n `End date provided is invalid date. Got --end=\"${end}\" expected --end=\"01/01/2023\"`,\n ),\n );\n this.process.exit(1);\n }\n if (startDate > endDate) {\n this.logger.error(\n colors.red(\n `Got a start date \"${startDate.toISOString()}\" that was larger than the end date \"${endDate.toISOString()}\". ` +\n 'Start date must be before end date.',\n ),\n );\n this.process.exit(1);\n }\n\n doneInputValidation(this.process);\n\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth, this);\n\n // Ensure folder either does not exist or is not a file\n if (this.fs.existsSync(folder) && !this.fs.lstatSync(folder).isDirectory()) {\n this.logger.error(\n colors.red(\n 'The provided argument \"folder\" was passed a file. expected: folder=\"./consent-metrics/\"',\n ),\n );\n this.process.exit(1);\n }\n\n // Create the folder if it does not exist\n if (!this.fs.existsSync(folder)) {\n this.fs.mkdirSync(folder);\n }\n\n this.logger.info(\n colors.magenta(\n `Pulling consent metrics from start=${startDate.toString()} to end=${endDate.toISOString()} with bin size \"${bin}\"`,\n ),\n );\n\n // Sync to Disk\n if (typeof apiKeyOrList === 'string') {\n try {\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, apiKeyOrList);\n\n // Pull the metrics\n const configuration = await pullConsentManagerMetrics(client, {\n bin: parsedBin,\n start: startDate,\n end: endDate,\n });\n\n // Write to file\n await map(\n Object.entries(configuration),\n async ([metricName, metrics]) => {\n await map(\n metrics,\n async ({ points, name }) => {\n const file = path.join(folder, `${metricName}_${name}.csv`);\n this.logger.info(colors.magenta(`Writing configuration to file \"${file}\"...`));\n await writeCsv(\n file,\n points.map(({ key, value }: { key: string; value: string }) => ({\n timestamp: key,\n value,\n })),\n );\n },\n {\n concurrency: 5,\n },\n );\n },\n { concurrency: 5 },\n );\n } catch (err) {\n this.logger.error(colors.red(`An error occurred syncing the schema: ${err.message}`));\n this.process.exit(1);\n }\n\n // Indicate success\n this.logger.info(\n colors.green(\n `Successfully synced consent metrics to disk in folder \"${folder}\"! View at ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n } else {\n const encounteredErrors: string[] = [];\n await mapSeries(apiKeyOrList, async (apiKey, ind) => {\n const prefix = `[${ind + 1}/${apiKeyOrList.length}][${apiKey.organizationName}] `;\n this.logger.info(\n colors.magenta(`~~~\\n\\n${prefix}Attempting to pull consent metrics...\\n\\n~~~`),\n );\n\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, apiKey.apiKey);\n\n try {\n const configuration = await pullConsentManagerMetrics(client, {\n bin: parsedBin,\n start: startDate,\n end: endDate,\n });\n\n // ensure folder exists for that organization\n const subFolder = path.join(folder, apiKey.organizationName);\n if (!this.fs.existsSync(subFolder)) {\n this.fs.mkdirSync(subFolder);\n }\n\n // Write to file\n Object.entries(configuration).forEach(([metricName, metrics]) => {\n metrics.forEach(({ points, name }) => {\n const file = path.join(subFolder, `${metricName}_${name}.csv`);\n this.logger.info(colors.magenta(`Writing configuration to file \"${file}\"...`));\n writeCsv(\n file,\n points.map(({ key, value }: { key: string; value: string }) => ({\n timestamp: key,\n value,\n })),\n );\n });\n });\n\n this.logger.info(colors.green(`${prefix}Successfully pulled configuration!`));\n } catch (err) {\n this.logger.error(colors.red(`${prefix}Failed to sync configuration.`), err);\n encounteredErrors.push(apiKey.organizationName);\n }\n });\n\n if (encounteredErrors.length > 0) {\n this.logger.info(\n colors.red(\n `Sync encountered errors for \"${encounteredErrors.join(\n ',',\n )}\". View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n this.process.exit(1);\n }\n }\n}\n"],"mappings":"sfAuBA,eAAsB,EAEpB,CAAE,OAAM,QAAO,MAAK,SAAQ,MAAK,gBAClB,CAEf,IAAM,EAAY,EACb,OAAO,OAAO,EAAwB,CAAC,SAAS,EAAU,GAC7D,KAAK,OAAO,MACV,EAAO,IACL,8CAA8C,EAAI,wBAC1B,OAAO,OAAO,EAAwB,CAAC,KAAK;EAAK,GAC1E,CACF,CACD,KAAK,QAAQ,KAAK,EAAE,EAItB,IAAM,EAAY,IAAI,KAAK,EAAM,CAC3B,EAAU,EAAM,IAAI,KAAK,EAAI,CAAG,IAAI,KACtC,OAAO,MAAM,EAAU,SAAS,CAAC,GACnC,KAAK,OAAO,MACV,EAAO,IACL,qDAAqD,EAAM,iCAC5D,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