@transcend-io/cli 12.1.1 → 12.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/dist/{app-BAx2hvcN.mjs → app-CnGAV_Tf.mjs} +16 -16
  2. package/dist/{app-BAx2hvcN.mjs.map → app-CnGAV_Tf.mjs.map} +1 -1
  3. package/dist/{approvePrivacyRequests-B-4o7QMG.mjs → approvePrivacyRequests-fmkUKYAm.mjs} +2 -2
  4. package/dist/{approvePrivacyRequests-B-4o7QMG.mjs.map → approvePrivacyRequests-fmkUKYAm.mjs.map} +1 -1
  5. package/dist/bin/bash-complete.mjs +1 -1
  6. package/dist/bin/cli.mjs +1 -1
  7. package/dist/bin/deprecated-command.mjs +1 -1
  8. package/dist/{buildExamples-kR5_7dkU.mjs → buildExamples-DB_puA14.mjs} +2 -2
  9. package/dist/{buildExamples-kR5_7dkU.mjs.map → buildExamples-DB_puA14.mjs.map} +1 -1
  10. package/dist/{buildXdiSyncEndpoint-BSYwJ2vc.mjs → buildXdiSyncEndpoint-CwABTp_y.mjs} +2 -2
  11. package/dist/{buildXdiSyncEndpoint-BSYwJ2vc.mjs.map → buildXdiSyncEndpoint-CwABTp_y.mjs.map} +1 -1
  12. package/dist/{bulkRestartRequests-DhOfMz0S.mjs → bulkRestartRequests-3OpVNSrk.mjs} +2 -2
  13. package/dist/{bulkRestartRequests-DhOfMz0S.mjs.map → bulkRestartRequests-3OpVNSrk.mjs.map} +1 -1
  14. package/dist/{bulkRetryEnrichers-Cj94ftnY.mjs → bulkRetryEnrichers-CdcXcHsx.mjs} +2 -2
  15. package/dist/{bulkRetryEnrichers-Cj94ftnY.mjs.map → bulkRetryEnrichers-CdcXcHsx.mjs.map} +1 -1
  16. package/dist/{cancelPrivacyRequests-DgAhfcmg.mjs → cancelPrivacyRequests-Dcl2KZfB.mjs} +2 -2
  17. package/dist/{cancelPrivacyRequests-DgAhfcmg.mjs.map → cancelPrivacyRequests-Dcl2KZfB.mjs.map} +1 -1
  18. package/dist/{command-gwG8sQwM.mjs → command-BcxEDvsy.mjs} +2 -2
  19. package/dist/{command-gwG8sQwM.mjs.map → command-BcxEDvsy.mjs.map} +1 -1
  20. package/dist/{constants-BCmVqlrM.mjs → constants-boymUaFC.mjs} +2 -2
  21. package/dist/{constants-BCmVqlrM.mjs.map → constants-boymUaFC.mjs.map} +1 -1
  22. package/dist/{createPoolingCommandUi-ByyTeJx5.mjs → createPoolingCommandUi-D7gyxeTT.mjs} +2 -2
  23. package/dist/{createPoolingCommandUi-ByyTeJx5.mjs.map → createPoolingCommandUi-D7gyxeTT.mjs.map} +1 -1
  24. package/dist/{downloadPrivacyRequestFiles-yiE6NzXz.mjs → downloadPrivacyRequestFiles-930ENWDi.mjs} +2 -2
  25. package/dist/{downloadPrivacyRequestFiles-yiE6NzXz.mjs.map → downloadPrivacyRequestFiles-930ENWDi.mjs.map} +1 -1
  26. package/dist/{generateCrossAccountApiKeys-CoSsZwSz.mjs → generateCrossAccountApiKeys-B_p8gQ2C.mjs} +2 -2
  27. package/dist/{generateCrossAccountApiKeys-CoSsZwSz.mjs.map → generateCrossAccountApiKeys-B_p8gQ2C.mjs.map} +1 -1
  28. package/dist/{impl-DdUe8ClA.mjs → impl-2VeGCbJq.mjs} +2 -2
  29. package/dist/{impl-DdUe8ClA.mjs.map → impl-2VeGCbJq.mjs.map} +1 -1
  30. package/dist/{impl-tYHONQMu.mjs → impl-2YeOxW2m.mjs} +2 -2
  31. package/dist/{impl-tYHONQMu.mjs.map → impl-2YeOxW2m.mjs.map} +1 -1
  32. package/dist/{impl-BCP4X_zk.mjs → impl-5Pko18bX.mjs} +2 -2
  33. package/dist/{impl-BCP4X_zk.mjs.map → impl-5Pko18bX.mjs.map} +1 -1
  34. package/dist/{impl-pA1b-G6B.mjs → impl-7YqcGwra.mjs} +2 -2
  35. package/dist/{impl-pA1b-G6B.mjs.map → impl-7YqcGwra.mjs.map} +1 -1
  36. package/dist/{impl-DSPxdc-T.mjs → impl-B5-UipRP.mjs} +2 -2
  37. package/dist/{impl-DSPxdc-T.mjs.map → impl-B5-UipRP.mjs.map} +1 -1
  38. package/dist/{impl-DE_cRfz52.mjs → impl-B8PyNdje2.mjs} +2 -2
  39. package/dist/{impl-DE_cRfz52.mjs.map → impl-B8PyNdje2.mjs.map} +1 -1
  40. package/dist/{impl-C1vn0Y7f.mjs → impl-BIYT-9BY.mjs} +2 -2
  41. package/dist/{impl-C1vn0Y7f.mjs.map → impl-BIYT-9BY.mjs.map} +1 -1
  42. package/dist/{impl-CyDdvH5a.mjs → impl-BP110k4H.mjs} +2 -2
  43. package/dist/{impl-CyDdvH5a.mjs.map → impl-BP110k4H.mjs.map} +1 -1
  44. package/dist/{impl-C0R2azuF.mjs → impl-BPdvRtQ9.mjs} +2 -2
  45. package/dist/{impl-C0R2azuF.mjs.map → impl-BPdvRtQ9.mjs.map} +1 -1
  46. package/dist/{impl-D0cf-epj.mjs → impl-BUJbKCd4.mjs} +2 -2
  47. package/dist/{impl-D0cf-epj.mjs.map → impl-BUJbKCd4.mjs.map} +1 -1
  48. package/dist/{impl-BKKBmXv4.mjs → impl-BbzX8auO.mjs} +2 -2
  49. package/dist/{impl-BKKBmXv4.mjs.map → impl-BbzX8auO.mjs.map} +1 -1
  50. package/dist/{impl-4WoLxjdU.mjs → impl-Bs4T0u8t.mjs} +2 -2
  51. package/dist/{impl-4WoLxjdU.mjs.map → impl-Bs4T0u8t.mjs.map} +1 -1
  52. package/dist/{impl-BRCAL4RM.mjs → impl-BtIse0WU.mjs} +2 -2
  53. package/dist/{impl-BRCAL4RM.mjs.map → impl-BtIse0WU.mjs.map} +1 -1
  54. package/dist/{impl-CuDZY6y7.mjs → impl-C4AjYGSc.mjs} +2 -2
  55. package/dist/{impl-CuDZY6y7.mjs.map → impl-C4AjYGSc.mjs.map} +1 -1
  56. package/dist/{impl-DqnzZv43.mjs → impl-CFyD51rZ.mjs} +2 -2
  57. package/dist/{impl-DqnzZv43.mjs.map → impl-CFyD51rZ.mjs.map} +1 -1
  58. package/dist/{impl-F2lRJEqw.mjs → impl-CKeiISid.mjs} +2 -2
  59. package/dist/{impl-F2lRJEqw.mjs.map → impl-CKeiISid.mjs.map} +1 -1
  60. package/dist/{impl-DCF3CF3O.mjs → impl-CKlQglut.mjs} +2 -2
  61. package/dist/{impl-DCF3CF3O.mjs.map → impl-CKlQglut.mjs.map} +1 -1
  62. package/dist/{impl-DNRA5i0w.mjs → impl-CPyd-ahE.mjs} +2 -2
  63. package/dist/{impl-DNRA5i0w.mjs.map → impl-CPyd-ahE.mjs.map} +1 -1
  64. package/dist/{impl-CxpGBeJ0.mjs → impl-CtMcCdUA.mjs} +2 -2
  65. package/dist/{impl-CxpGBeJ0.mjs.map → impl-CtMcCdUA.mjs.map} +1 -1
  66. package/dist/{impl-BaGN4J-w.mjs → impl-CwWY8MCP.mjs} +2 -2
  67. package/dist/{impl-BaGN4J-w.mjs.map → impl-CwWY8MCP.mjs.map} +1 -1
  68. package/dist/{impl-DrlfmH8g.mjs → impl-CwjhuIx0.mjs} +2 -2
  69. package/dist/{impl-DrlfmH8g.mjs.map → impl-CwjhuIx0.mjs.map} +1 -1
  70. package/dist/{impl-u1nIo2-E.mjs → impl-Cx97QWq8.mjs} +2 -2
  71. package/dist/{impl-u1nIo2-E.mjs.map → impl-Cx97QWq8.mjs.map} +1 -1
  72. package/dist/{impl-BJnxahnW.mjs → impl-D-Cz399O.mjs} +2 -2
  73. package/dist/{impl-BJnxahnW.mjs.map → impl-D-Cz399O.mjs.map} +1 -1
  74. package/dist/{impl-BM2SWSKF.mjs → impl-D3LHj5lS.mjs} +2 -2
  75. package/dist/{impl-BM2SWSKF.mjs.map → impl-D3LHj5lS.mjs.map} +1 -1
  76. package/dist/{impl-Dl8xSx8K.mjs → impl-D9kZ4naw.mjs} +2 -2
  77. package/dist/{impl-Dl8xSx8K.mjs.map → impl-D9kZ4naw.mjs.map} +1 -1
  78. package/dist/{impl-f59q7WnK.mjs → impl-DBMuhicF.mjs} +2 -2
  79. package/dist/{impl-f59q7WnK.mjs.map → impl-DBMuhicF.mjs.map} +1 -1
  80. package/dist/{impl-LDY2dgtc.mjs → impl-DDsOdK7O.mjs} +2 -2
  81. package/dist/{impl-LDY2dgtc.mjs.map → impl-DDsOdK7O.mjs.map} +1 -1
  82. package/dist/{impl-BFSZEQ2s.mjs → impl-DFhAp1Ky.mjs} +2 -2
  83. package/dist/{impl-BFSZEQ2s.mjs.map → impl-DFhAp1Ky.mjs.map} +1 -1
  84. package/dist/{impl-C1hh_5On.mjs → impl-DGm6q0bm.mjs} +2 -2
  85. package/dist/{impl-C1hh_5On.mjs.map → impl-DGm6q0bm.mjs.map} +1 -1
  86. package/dist/{impl-BMX6B40F.mjs → impl-DPb4YZxb.mjs} +2 -2
  87. package/dist/{impl-BMX6B40F.mjs.map → impl-DPb4YZxb.mjs.map} +1 -1
  88. package/dist/{impl-DbddBTRj2.mjs → impl-DRmJog0S2.mjs} +2 -2
  89. package/dist/{impl-DbddBTRj2.mjs.map → impl-DRmJog0S2.mjs.map} +1 -1
  90. package/dist/{impl-Bf2Qli6c2.mjs → impl-DT4VbZ-Q2.mjs} +2 -2
  91. package/dist/{impl-Bf2Qli6c2.mjs.map → impl-DT4VbZ-Q2.mjs.map} +1 -1
  92. package/dist/{impl-D8YS5Bge.mjs → impl-Ds6ROQi7.mjs} +2 -2
  93. package/dist/{impl-D8YS5Bge.mjs.map → impl-Ds6ROQi7.mjs.map} +1 -1
  94. package/dist/{impl-ClhMRgQZ.mjs → impl-P1hltmA6.mjs} +2 -2
  95. package/dist/{impl-ClhMRgQZ.mjs.map → impl-P1hltmA6.mjs.map} +1 -1
  96. package/dist/{impl-BrdCuU0I.mjs → impl-XztvsE6N.mjs} +2 -2
  97. package/dist/{impl-BrdCuU0I.mjs.map → impl-XztvsE6N.mjs.map} +1 -1
  98. package/dist/{impl-C54oUOeM2.mjs → impl-qTeP2Voo2.mjs} +2 -2
  99. package/dist/{impl-C54oUOeM2.mjs.map → impl-qTeP2Voo2.mjs.map} +1 -1
  100. package/dist/{impl-OXGlZyUo.mjs → impl-xR4iG_u5.mjs} +2 -2
  101. package/dist/{impl-OXGlZyUo.mjs.map → impl-xR4iG_u5.mjs.map} +1 -1
  102. package/dist/{impl-CKg5Xu-r.mjs → impl-yJETNVcT.mjs} +2 -2
  103. package/dist/{impl-CKg5Xu-r.mjs.map → impl-yJETNVcT.mjs.map} +1 -1
  104. package/dist/index.mjs +1 -1
  105. package/dist/{markRequestDataSiloIdsCompleted-B-Dgme2r.mjs → markRequestDataSiloIdsCompleted-CU0ba_mE.mjs} +2 -2
  106. package/dist/{markRequestDataSiloIdsCompleted-B-Dgme2r.mjs.map → markRequestDataSiloIdsCompleted-CU0ba_mE.mjs.map} +1 -1
  107. package/dist/{markSilentPrivacyRequests-CPU4Q2lF.mjs → markSilentPrivacyRequests-Bf_4pCaq.mjs} +2 -2
  108. package/dist/{markSilentPrivacyRequests-CPU4Q2lF.mjs.map → markSilentPrivacyRequests-Bf_4pCaq.mjs.map} +1 -1
  109. package/dist/{notifyPrivacyRequestsAdditionalTime-BWsm5Y5K.mjs → notifyPrivacyRequestsAdditionalTime-rnUXdvBR.mjs} +2 -2
  110. package/dist/{notifyPrivacyRequestsAdditionalTime-BWsm5Y5K.mjs.map → notifyPrivacyRequestsAdditionalTime-rnUXdvBR.mjs.map} +1 -1
  111. package/dist/{policy-bundle-manifest-BDey6EBs.mjs → policy-bundle-manifest-B1Herd_n.mjs} +2 -2
  112. package/dist/{policy-bundle-manifest-BDey6EBs.mjs.map → policy-bundle-manifest-B1Herd_n.mjs.map} +1 -1
  113. package/dist/{policy-project-discovery-DV5PnFJq.mjs → policy-project-discovery-oc49b2gr.mjs} +2 -2
  114. package/dist/{policy-project-discovery-DV5PnFJq.mjs.map → policy-project-discovery-oc49b2gr.mjs.map} +1 -1
  115. package/dist/{policy-scaffold-config-DtRELUZx.mjs → policy-scaffold-config-CpXR9KgF.mjs} +2 -2
  116. package/dist/{policy-scaffold-config-DtRELUZx.mjs.map → policy-scaffold-config-CpXR9KgF.mjs.map} +1 -1
  117. package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-BaHp-jxs.mjs → pullChunkedCustomSiloOutstandingIdentifiers-BcBj9prQ.mjs} +2 -2
  118. package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-BaHp-jxs.mjs.map → pullChunkedCustomSiloOutstandingIdentifiers-BcBj9prQ.mjs.map} +1 -1
  119. package/dist/{pullManualEnrichmentIdentifiersToCsv-CiEFIvl_.mjs → pullManualEnrichmentIdentifiersToCsv-BSUXUp8v.mjs} +2 -2
  120. package/dist/{pullManualEnrichmentIdentifiersToCsv-CiEFIvl_.mjs.map → pullManualEnrichmentIdentifiersToCsv-BSUXUp8v.mjs.map} +1 -1
  121. package/dist/{pushCronIdentifiersFromCsv-DeS78zyp.mjs → pushCronIdentifiersFromCsv-D-l3erLO.mjs} +2 -2
  122. package/dist/{pushCronIdentifiersFromCsv-DeS78zyp.mjs.map → pushCronIdentifiersFromCsv-D-l3erLO.mjs.map} +1 -1
  123. package/dist/{pushManualEnrichmentIdentifiersFromCsv-B3iVwuvs.mjs → pushManualEnrichmentIdentifiersFromCsv-CqLIw5MV.mjs} +2 -2
  124. package/dist/{pushManualEnrichmentIdentifiersFromCsv-B3iVwuvs.mjs.map → pushManualEnrichmentIdentifiersFromCsv-CqLIw5MV.mjs.map} +1 -1
  125. package/dist/{removeUnverifiedRequestIdentifiers-qS5A_eRZ.mjs → removeUnverifiedRequestIdentifiers-B-Az2HJ8.mjs} +2 -2
  126. package/dist/{removeUnverifiedRequestIdentifiers-qS5A_eRZ.mjs.map → removeUnverifiedRequestIdentifiers-B-Az2HJ8.mjs.map} +1 -1
  127. package/dist/{retryRequestDataSilos-Cxaka-kA.mjs → retryRequestDataSilos-D70pC9JF.mjs} +2 -2
  128. package/dist/{retryRequestDataSilos-Cxaka-kA.mjs.map → retryRequestDataSilos-D70pC9JF.mjs.map} +1 -1
  129. package/dist/{skipPreflightJobs-FdIm_Imj.mjs → skipPreflightJobs-B0YG7mhP.mjs} +2 -2
  130. package/dist/{skipPreflightJobs-FdIm_Imj.mjs.map → skipPreflightJobs-B0YG7mhP.mjs.map} +1 -1
  131. package/dist/{skipRequestDataSilos-MTbj-OfW.mjs → skipRequestDataSilos-DV5Dy5Dw.mjs} +2 -2
  132. package/dist/{skipRequestDataSilos-MTbj-OfW.mjs.map → skipRequestDataSilos-DV5Dy5Dw.mjs.map} +1 -1
  133. package/dist/{streamPrivacyRequestsToCsv-BVzYSXNY.mjs → streamPrivacyRequestsToCsv-Qm2r7Iy2.mjs} +2 -2
  134. package/dist/{streamPrivacyRequestsToCsv-BVzYSXNY.mjs.map → streamPrivacyRequestsToCsv-Qm2r7Iy2.mjs.map} +1 -1
  135. package/dist/{updateConsentManagerVersionToLatest-Udi7Iazb.mjs → updateConsentManagerVersionToLatest-cryDInky.mjs} +2 -2
  136. package/dist/{updateConsentManagerVersionToLatest-Udi7Iazb.mjs.map → updateConsentManagerVersionToLatest-cryDInky.mjs.map} +1 -1
  137. package/dist/{uploadConsents-w7FE65Zg.mjs → uploadConsents-Din2Qdws.mjs} +2 -2
  138. package/dist/{uploadConsents-w7FE65Zg.mjs.map → uploadConsents-Din2Qdws.mjs.map} +1 -1
  139. package/dist/{uploadPrivacyRequestsFromCsv-B__QsguT.mjs → uploadPrivacyRequestsFromCsv-DHYbgV8h.mjs} +2 -2
  140. package/dist/{uploadPrivacyRequestsFromCsv-B__QsguT.mjs.map → uploadPrivacyRequestsFromCsv-DHYbgV8h.mjs.map} +1 -1
  141. package/package.json +5 -5
@@ -1,4 +1,4 @@
1
- import{t as e}from"./constants-BCmVqlrM.mjs";import{t}from"./logger-CPu6zbyQ.mjs";import{t as n}from"./done-input-validation-LiTaCEzF.mjs";import{n as r}from"./constants-DC_bBO09.mjs";import i from"colors";import a from"fast-glob";import{buildTranscendGraphQLClient as o,fetchActiveSiloDiscoPlugin as s,uploadSiloDiscoveryResults as c}from"@transcend-io/sdk";import{stringify as l}from"query-string";async function u({scanPath:e,fileGlobs:n,ignoreDirs:r,config:i}){let{ignoreDirs:o,supportedFiles:s,scanFunction:c}=i,l=n===``?s:s.concat(n.split(`,`)),d=[...r.split(`,`),...o].filter(e=>e.length>0);try{let n=await a(`${e}/**/${l.join(`|`)}`,{ignore:d.map(t=>`${e}/**/${t}`),unique:!0,onlyFiles:!0});t.info(`Scanning: ${n.length} files`);let r=n.map(e=>c(e)).flat().map(e=>e.softwareDevelopmentKits||[]).flat(),i=[...new Set(r.map(e=>e.name))];return t.info(`Found: ${i.length} unique dependencies`),i.map(t=>({name:t,resourceId:`${e}/**/${t}`,useStrictClassifier:!0}))}catch(e){throw Error(`Error scanning globs ${u} with error: ${e}`)}}async function d({scanPath:t,dataSiloId:a,auth:d,fileGlobs:f,ignoreDirs:p,transcendUrl:m}){n(this.process);let h=o(m,d),g=await s(h,{logger:this.logger,filterBy:{dataSiloId:a}}),_=r[g.dataSilo.type];_||(this.logger.error(i.red(`This plugin "${g.dataSilo.type}" is not supported for offline silo discovery.`)),this.process.exit(1));let v=await u({scanPath:t,fileGlobs:f,ignoreDirs:p,config:_});await c(h,{pluginId:g.id,results:v,logger:this.logger});let y=new URL(e);y.pathname=`/data-map/data-inventory/silo-discovery/triage`,y.search=l({filters:JSON.stringify({pluginIds:[g.id]})}),this.logger.info(i.green(`Scan found ${v.length} potential data silos at ${t}! View at '${y.href}'
1
+ import{t as e}from"./constants-boymUaFC.mjs";import{t}from"./logger-CPu6zbyQ.mjs";import{t as n}from"./done-input-validation-LiTaCEzF.mjs";import{n as r}from"./constants-DC_bBO09.mjs";import i from"colors";import a from"fast-glob";import{buildTranscendGraphQLClient as o,fetchActiveSiloDiscoPlugin as s,uploadSiloDiscoveryResults as c}from"@transcend-io/sdk";import{stringify as l}from"query-string";async function u({scanPath:e,fileGlobs:n,ignoreDirs:r,config:i}){let{ignoreDirs:o,supportedFiles:s,scanFunction:c}=i,l=n===``?s:s.concat(n.split(`,`)),d=[...r.split(`,`),...o].filter(e=>e.length>0);try{let n=await a(`${e}/**/${l.join(`|`)}`,{ignore:d.map(t=>`${e}/**/${t}`),unique:!0,onlyFiles:!0});t.info(`Scanning: ${n.length} files`);let r=n.map(e=>c(e)).flat().map(e=>e.softwareDevelopmentKits||[]).flat(),i=[...new Set(r.map(e=>e.name))];return t.info(`Found: ${i.length} unique dependencies`),i.map(t=>({name:t,resourceId:`${e}/**/${t}`,useStrictClassifier:!0}))}catch(e){throw Error(`Error scanning globs ${u} with error: ${e}`)}}async function d({scanPath:t,dataSiloId:a,auth:d,fileGlobs:f,ignoreDirs:p,transcendUrl:m}){n(this.process);let h=o(m,d),g=await s(h,{logger:this.logger,filterBy:{dataSiloId:a}}),_=r[g.dataSilo.type];_||(this.logger.error(i.red(`This plugin "${g.dataSilo.type}" is not supported for offline silo discovery.`)),this.process.exit(1));let v=await u({scanPath:t,fileGlobs:f,ignoreDirs:p,config:_});await c(h,{pluginId:g.id,results:v,logger:this.logger});let y=new URL(e);y.pathname=`/data-map/data-inventory/silo-discovery/triage`,y.search=l({filters:JSON.stringify({pluginIds:[g.id]})}),this.logger.info(i.green(`Scan found ${v.length} potential data silos at ${t}! View at '${y.href}'
2
2
 
3
3
  NOTE: it may take 2-3 minutes for scan results to appear in the UI.`))}export{d as discoverSilos};
4
- //# sourceMappingURL=impl-DbddBTRj2.mjs.map
4
+ //# sourceMappingURL=impl-DRmJog0S2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-DbddBTRj2.mjs","names":[],"sources":["../src/lib/code-scanning/findFilesToScan.ts","../src/commands/inventory/discover-silos/impl.ts"],"sourcesContent":["import fastGlob from 'fast-glob';\n\nimport { logger } from '../../logger.js';\nimport { CodeScanningConfig } from './types.js';\n\nexport interface SiloDiscoveryRawResults {\n /** The name of the potential data silo entry */\n name: string;\n /** A unique UUID (represents the same resource across different silo discovery runs) */\n resourceId: string;\n /** Any hosts associated with the entry */\n host?: string;\n /** Type of data silo */\n type?: string | undefined;\n}\n\n/**\n * Helper to scan for data silos in all package.json files that it can find in a directory\n *\n * @deprecated TODO: https://transcend.height.app/T-32325 - use code scanning instead\n * @param options - Options\n * @returns the list of integrations\n */\nexport async function findFilesToScan({\n scanPath,\n fileGlobs,\n ignoreDirs,\n config,\n}: {\n /** Where to look for package.json files */\n scanPath: string;\n /** Globs to look for */\n fileGlobs: string;\n /** The directories to ignore (excludes node_modules and serverless-build) */\n ignoreDirs: string;\n /** Silo Discovery configuration */\n config: CodeScanningConfig;\n}): Promise<SiloDiscoveryRawResults[]> {\n const { ignoreDirs: IGNORE_DIRS, supportedFiles, scanFunction } = config;\n const globsToSupport =\n fileGlobs === '' ? supportedFiles : supportedFiles.concat(fileGlobs.split(','));\n const dirsToIgnore = [...ignoreDirs.split(','), ...IGNORE_DIRS].filter((dir) => dir.length > 0);\n try {\n const filesToScan: string[] = await fastGlob(`${scanPath}/**/${globsToSupport.join('|')}`, {\n ignore: dirsToIgnore.map((dir: string) => `${scanPath}/**/${dir}`),\n unique: true,\n onlyFiles: true,\n });\n logger.info(`Scanning: ${filesToScan.length} files`);\n const allPackages = filesToScan.map((filePath: string) => scanFunction(filePath)).flat();\n const allSdks = allPackages\n .map((appPackage) => appPackage.softwareDevelopmentKits || [])\n .flat();\n const uniqueDeps = new Set(allSdks.map((sdk) => sdk.name));\n const deps = [...uniqueDeps];\n logger.info(`Found: ${deps.length} unique dependencies`);\n return deps.map((dep) => ({\n name: dep,\n resourceId: `${scanPath}/**/${dep}`,\n useStrictClassifier: true,\n }));\n } catch (error) {\n throw new Error(`Error scanning globs ${findFilesToScan} with error: ${error}`);\n }\n}\n","import {\n buildTranscendGraphQLClient,\n fetchActiveSiloDiscoPlugin,\n uploadSiloDiscoveryResults,\n} from '@transcend-io/sdk';\nimport colors from 'colors';\nimport { stringify } from 'query-string';\n\nimport { ADMIN_DASH } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { findFilesToScan } from '../../../lib/code-scanning/findFilesToScan.js';\nimport { SILO_DISCOVERY_CONFIGS } from '../../../lib/code-scanning/index.js';\n\nexport interface DiscoverSilosCommandFlags {\n scanPath: string;\n dataSiloId: string;\n auth: string;\n fileGlobs: string;\n ignoreDirs: string;\n transcendUrl: string;\n}\n\nexport async function discoverSilos(\n this: LocalContext,\n { scanPath, dataSiloId, auth, fileGlobs, ignoreDirs, transcendUrl }: DiscoverSilosCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const plugin = await fetchActiveSiloDiscoPlugin(client, {\n logger: this.logger,\n filterBy: { dataSiloId },\n });\n\n const config = SILO_DISCOVERY_CONFIGS[plugin.dataSilo.type];\n if (!config) {\n this.logger.error(\n colors.red(\n `This plugin \"${plugin.dataSilo.type}\" is not supported for offline silo discovery.`,\n ),\n );\n this.process.exit(1);\n }\n\n const results = await findFilesToScan({\n scanPath,\n fileGlobs,\n ignoreDirs,\n config,\n });\n\n await uploadSiloDiscoveryResults(client, {\n pluginId: plugin.id,\n results,\n logger: this.logger,\n });\n\n const newUrl = new URL(ADMIN_DASH);\n newUrl.pathname = '/data-map/data-inventory/silo-discovery/triage';\n newUrl.search = stringify({\n filters: JSON.stringify({ pluginIds: [plugin.id] }),\n });\n\n // Indicate success\n this.logger.info(\n colors.green(\n `Scan found ${results.length} potential data silos at ${scanPath}! ` +\n `View at '${newUrl.href}' ` +\n '\\n\\n NOTE: it may take 2-3 minutes for scan results to appear in the UI.',\n ),\n );\n}\n"],"mappings":"gZAuBA,eAAsB,EAAgB,CACpC,WACA,YACA,aACA,UAUqC,CACrC,GAAM,CAAE,WAAY,EAAa,iBAAgB,gBAAiB,EAC5D,EACJ,IAAc,GAAK,EAAiB,EAAe,OAAO,EAAU,MAAM,IAAI,CAAC,CAC3E,EAAe,CAAC,GAAG,EAAW,MAAM,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O,SAAW,iDAClB,EAAO,OAAS,EAAU,CACxB,QAAS,KAAK,UAAU,CAAE,UAAW,CAAC,EAAO,GAAG,CAAE,CAAC,CACpD,CAAC,CAGF,KAAK,OAAO,KACV,EAAO,MACL,cAAc,EAAQ,OAAO,2BAA2B,EAAS,aACnD,EAAO,KAAK;;sEAE3B,CACF"}
1
+ {"version":3,"file":"impl-DRmJog0S2.mjs","names":[],"sources":["../src/lib/code-scanning/findFilesToScan.ts","../src/commands/inventory/discover-silos/impl.ts"],"sourcesContent":["import fastGlob from 'fast-glob';\n\nimport { logger } from '../../logger.js';\nimport { CodeScanningConfig } from './types.js';\n\nexport interface SiloDiscoveryRawResults {\n /** The name of the potential data silo entry */\n name: string;\n /** A unique UUID (represents the same resource across different silo discovery runs) */\n resourceId: string;\n /** Any hosts associated with the entry */\n host?: string;\n /** Type of data silo */\n type?: string | undefined;\n}\n\n/**\n * Helper to scan for data silos in all package.json files that it can find in a directory\n *\n * @deprecated TODO: https://transcend.height.app/T-32325 - use code scanning instead\n * @param options - Options\n * @returns the list of integrations\n */\nexport async function findFilesToScan({\n scanPath,\n fileGlobs,\n ignoreDirs,\n config,\n}: {\n /** Where to look for package.json files */\n scanPath: string;\n /** Globs to look for */\n fileGlobs: string;\n /** The directories to ignore (excludes node_modules and serverless-build) */\n ignoreDirs: string;\n /** Silo Discovery configuration */\n config: CodeScanningConfig;\n}): Promise<SiloDiscoveryRawResults[]> {\n const { ignoreDirs: IGNORE_DIRS, supportedFiles, scanFunction } = config;\n const globsToSupport =\n fileGlobs === '' ? supportedFiles : supportedFiles.concat(fileGlobs.split(','));\n const dirsToIgnore = [...ignoreDirs.split(','), ...IGNORE_DIRS].filter((dir) => dir.length > 0);\n try {\n const filesToScan: string[] = await fastGlob(`${scanPath}/**/${globsToSupport.join('|')}`, {\n ignore: dirsToIgnore.map((dir: string) => `${scanPath}/**/${dir}`),\n unique: true,\n onlyFiles: true,\n });\n logger.info(`Scanning: ${filesToScan.length} files`);\n const allPackages = filesToScan.map((filePath: string) => scanFunction(filePath)).flat();\n const allSdks = allPackages\n .map((appPackage) => appPackage.softwareDevelopmentKits || [])\n .flat();\n const uniqueDeps = new Set(allSdks.map((sdk) => sdk.name));\n const deps = [...uniqueDeps];\n logger.info(`Found: ${deps.length} unique dependencies`);\n return deps.map((dep) => ({\n name: dep,\n resourceId: `${scanPath}/**/${dep}`,\n useStrictClassifier: true,\n }));\n } catch (error) {\n throw new Error(`Error scanning globs ${findFilesToScan} with error: ${error}`);\n }\n}\n","import {\n buildTranscendGraphQLClient,\n fetchActiveSiloDiscoPlugin,\n uploadSiloDiscoveryResults,\n} from '@transcend-io/sdk';\nimport colors from 'colors';\nimport { stringify } from 'query-string';\n\nimport { ADMIN_DASH } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { findFilesToScan } from '../../../lib/code-scanning/findFilesToScan.js';\nimport { SILO_DISCOVERY_CONFIGS } from '../../../lib/code-scanning/index.js';\n\nexport interface DiscoverSilosCommandFlags {\n scanPath: string;\n dataSiloId: string;\n auth: string;\n fileGlobs: string;\n ignoreDirs: string;\n transcendUrl: string;\n}\n\nexport async function discoverSilos(\n this: LocalContext,\n { scanPath, dataSiloId, auth, fileGlobs, ignoreDirs, transcendUrl }: DiscoverSilosCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const plugin = await fetchActiveSiloDiscoPlugin(client, {\n logger: this.logger,\n filterBy: { dataSiloId },\n });\n\n const config = SILO_DISCOVERY_CONFIGS[plugin.dataSilo.type];\n if (!config) {\n this.logger.error(\n colors.red(\n `This plugin \"${plugin.dataSilo.type}\" is not supported for offline silo discovery.`,\n ),\n );\n this.process.exit(1);\n }\n\n const results = await findFilesToScan({\n scanPath,\n fileGlobs,\n ignoreDirs,\n config,\n });\n\n await uploadSiloDiscoveryResults(client, {\n pluginId: plugin.id,\n results,\n logger: this.logger,\n });\n\n const newUrl = new URL(ADMIN_DASH);\n newUrl.pathname = '/data-map/data-inventory/silo-discovery/triage';\n newUrl.search = stringify({\n filters: JSON.stringify({ pluginIds: [plugin.id] }),\n });\n\n // Indicate success\n this.logger.info(\n colors.green(\n `Scan found ${results.length} potential data silos at ${scanPath}! ` +\n `View at '${newUrl.href}' ` +\n '\\n\\n NOTE: it may take 2-3 minutes for scan results to appear in the UI.',\n ),\n );\n}\n"],"mappings":"gZAuBA,eAAsB,EAAgB,CACpC,WACA,YACA,aACA,UAUqC,CACrC,GAAM,CAAE,WAAY,EAAa,iBAAgB,gBAAiB,EAC5D,EACJ,IAAc,GAAK,EAAiB,EAAe,OAAO,EAAU,MAAM,IAAI,CAAC,CAC3E,EAAe,CAAC,GAAG,EAAW,MAAM,IAAI,CAAE,GAAG,EAAY,CAAC,OAAQ,GAAQ,EAAI,OAAS,EAAE,CAC/F,GAAI,CACF,IAAM,EAAwB,MAAM,EAAS,GAAG,EAAS,MAAM,EAAe,KAAK,IAAI,GAAI,CACzF,OAAQ,EAAa,IAAK,GAAgB,GAAG,EAAS,MAAM,IAAM,CAClE,OAAQ,GACR,UAAW,GACZ,CAAC,CACF,EAAO,KAAK,aAAa,EAAY,OAAO,QAAQ,CAEpD,IAAM,EADc,EAAY,IAAK,GAAqB,EAAa,EAAS,CAAC,CAAC,MACvD,CACxB,IAAK,GAAe,EAAW,yBAA2B,EAAE,CAAC,CAC7D,MAAM,CAEH,EAAO,CAAC,GAAG,IADM,IAAI,EAAQ,IAAK,GAAQ,EAAI,KAAK,CAC9B,CAAC,CAE5B,OADA,EAAO,KAAK,UAAU,EAAK,OAAO,sBAAsB,CACjD,EAAK,IAAK,IAAS,CACxB,KAAM,EACN,WAAY,GAAG,EAAS,MAAM,IAC9B,oBAAqB,GACtB,EAAE,OACI,EAAO,CACd,MAAU,MAAM,wBAAwB,EAAgB,eAAe,IAAQ,ECvCnF,eAAsB,EAEpB,CAAE,WAAU,aAAY,OAAM,YAAW,aAAY,gBACtC,CACf,EAAoB,KAAK,QAAQ,CAGjC,IAAM,EAAS,EAA4B,EAAc,EAAK,CAExD,EAAS,MAAM,EAA2B,EAAQ,CACtD,OAAQ,KAAK,OACb,SAAU,CAAE,aAAY,CACzB,CAAC,CAEI,EAAS,EAAuB,EAAO,SAAS,MACjD,IACH,KAAK,OAAO,MACV,EAAO,IACL,gBAAgB,EAAO,SAAS,KAAK,gDACtC,CACF,CACD,KAAK,QAAQ,KAAK,EAAE,EAGtB,IAAM,EAAU,MAAM,EAAgB,CACpC,WACA,YACA,aACA,SACD,CAAC,CAEF,MAAM,EAA2B,EAAQ,CACvC,SAAU,EAAO,GACjB,UACA,OAAQ,KAAK,OACd,CAAC,CAEF,IAAM,EAAS,IAAI,IAAI,EAAW,CAClC,EAAO,SAAW,iDAClB,EAAO,OAAS,EAAU,CACxB,QAAS,KAAK,UAAU,CAAE,UAAW,CAAC,EAAO,GAAG,CAAE,CAAC,CACpD,CAAC,CAGF,KAAK,OAAO,KACV,EAAO,MACL,cAAc,EAAQ,OAAO,2BAA2B,EAAS,aACnD,EAAO,KAAK;;sEAE3B,CACF"}
@@ -1,4 +1,4 @@
1
- import{g as e}from"./constants-BCmVqlrM.mjs";import{i as t,n,r,t as i}from"./project-plan-output-BHHlkLxe.mjs";import{c as a,d as o,f as s,l as c,t as l,u}from"./project-discovery-CWRjlFnC.mjs";import{b as d,d as f,r as p,t as m,u as h}from"./policy-project-discovery-DV5PnFJq.mjs";import{a as g,c as _,i as v,l as y,o as b,r as x,s as S,t as C}from"./policy-runtime-6jmkXlBk.mjs";import{t as w}from"./done-input-validation-LiTaCEzF.mjs";import{i as T,n as E,r as D,t as O}from"./prompts-BhXfYD6g.mjs";import{t as k}from"./run-captured-process-BjaSDWXG.mjs";import{t as A}from"./project-plan-apply-Bg_1eMX9.mjs";import{a as j,n as ee,o as te,r as ne,t as re}from"./policy-scaffold-config-DtRELUZx.mjs";import{isAbsolute as M,join as N,posix as P,relative as F,sep as I}from"node:path";import L from"colors";const R={Editor:`editor`,Skill:`skill`,Ci:`ci`};var z=`# Idiomatic Rego and document-tree authoring
1
+ import{g as e}from"./constants-boymUaFC.mjs";import{i as t,n,r,t as i}from"./project-plan-output-BHHlkLxe.mjs";import{c as a,d as o,f as s,l as c,t as l,u}from"./project-discovery-CWRjlFnC.mjs";import{b as d,d as f,r as p,t as m,u as h}from"./policy-project-discovery-oc49b2gr.mjs";import{a as g,c as _,i as v,l as y,o as b,r as x,s as S,t as C}from"./policy-runtime-6jmkXlBk.mjs";import{t as w}from"./done-input-validation-LiTaCEzF.mjs";import{i as T,n as E,r as D,t as O}from"./prompts-BhXfYD6g.mjs";import{t as k}from"./run-captured-process-BjaSDWXG.mjs";import{t as A}from"./project-plan-apply-Bg_1eMX9.mjs";import{a as j,n as ee,o as te,r as ne,t as re}from"./policy-scaffold-config-CpXR9KgF.mjs";import{isAbsolute as M,join as N,posix as P,relative as F,sep as I}from"node:path";import L from"colors";const R={Editor:`editor`,Skill:`skill`,Ci:`ci`};var z=`# Idiomatic Rego and document-tree authoring
2
2
 
3
3
  ## Start from the document tree
4
4
 
@@ -418,4 +418,4 @@ transcend policy lint --noInteractive
418
418
  products into a single \`.manifest\` unless they share activation and callers.
419
419
  `;const W=`transcend-policy-engine`,G=[{path:`SKILL.md`,contents:U},{path:`references/setup-tooling.md`,contents:V},{path:`references/authoring.md`,contents:z},{path:`references/testing-debugging.md`,contents:H},{path:`references/publishing.md`,contents:B}];function K(e){return`${e.hasSkill?`Use the \`${W}\` skill and run`:`Run`} ${e.newCommand} to add a bundle from a template, then adapt the policy document tree and input/output contract to the intended application.`}function q(e,n){return{version:e.version,command:e.command,applied:n.applied,dryRun:n.dryRun,targetDirectory:e.targetDirectory,manifestPath:e.manifestPath,changes:e.changes.map(e=>t(n.cwd,e)),warnings:e.warnings,nextSteps:e.nextSteps,features:[...e.features],aiHandoff:n.aiHandoff,tools:n.tools}}const J={name:W,displayName:`Policy Engine`,owner:`@transcend-io/cli`,files:G};function Y(e,t){let n=new Set(d().map(({path:t})=>N(e.targetDirectory,t))),r=new Set(t.features);return r.has(R.Editor)&&(n.add(N(e.projectRoot,`.vscode`,`settings.json`)),n.add(N(e.projectRoot,`.vscode`,`extensions.json`)),n.add(N(e.projectRoot,`.vscode`,`tasks.json`))),r.has(R.Skill)&&a(e.projectRoot,e.existingSkillDirectories,J).forEach(e=>n.add(e)),r.has(R.Ci)&&e.repositoryRoot&&e.usesGithub&&n.add(N(e.repositoryRoot,j)),[...n].sort((e,t)=>e.localeCompare(t))}function X(e,t){let n=F(e,t);if(n===`..`||n.startsWith(`..${I}`)||M(n))throw Error(`Refusing to modify path outside project root: ${t}`)}function ie(e){let t=new Set([`${h}/input.json`]);return e.forEach(({path:e})=>{t.add(e);let n=P.dirname(e);for(;n!==`.`;)t.add(n),n=P.dirname(n)}),t}function Z(e,t,n){let r=s({snapshot:u(t.snapshots,n.path),after:n.contents,description:n.description,...n.createOnly===void 0?{}:{createOnly:n.createOnly}});r?e.changes.push(r):e.unchanged.push(n.path)}function ae(e,t,n,r,a,o){Z(e,t,{path:n,contents:r.contents,description:a}),e.warnings.push(...r.warnings.map(e=>`${e} (${i(o,n)})`))}function oe(e,t){let{state:n}=e,r=d(),a=`transcend policy new`,s={version:3,command:`init`,rootDirectory:n.projectRoot,targetDirectory:n.targetDirectory,manifestPath:n.targetDirectory,changes:[],unchanged:[],warnings:[],nextSteps:[a],features:[...t.features]},l=Y(n,t);if(X(n.projectRoot,n.targetDirectory),l.forEach(e=>X(n.projectRoot,e)),n.relativeFilePaths.length===0)s.directoryPreconditions=[{path:n.targetDirectory,relativePaths:[...n.relativePaths]}],r.forEach(t=>{let r=N(n.targetDirectory,t.path);if(o(e.snapshots,r).kind!==`absent`)throw Error(`Expected an empty policy target, but found an entry at: ${r}`);Z(s,e,{path:r,contents:t.contents,description:t.description,createOnly:!0})});else{let t=!0;r.forEach(r=>{let a=N(n.targetDirectory,r.path),c=o(e.snapshots,a);if(c.kind===`file`&&c.contents===r.contents){s.unchanged.push(a);return}t=!1,c.kind!==`absent`&&(s.unchanged.push(a),s.warnings.push(`Existing policy scaffold path was left unchanged: ${i(n.invocationDirectory,a)}`))});let c=ie(r),l=n.relativeFilePaths.some(e=>!c.has(e));(!t||l)&&s.warnings.push(`Existing policy target contains custom or partial content, so no workspace files were added or overwritten. Review ${i(n.invocationDirectory,n.targetDirectory)} manually, then run \`${a}\`.`)}let u=new Set(t.features),f=n.projectRoot;if(u.has(R.Editor)){let t=N(f,`.vscode`,`settings.json`),r=N(f,`.vscode`,`extensions.json`),a=N(f,`.vscode`,`tasks.json`);[{path:t,description:`Merge strict target-scoped OPA and Rego editor settings`,merge:(e,t,n)=>ee(e,t,n)},{path:r,description:`Recommend the OPA extension and discourage its syntax-only conflict`,merge:e=>re(e)},{path:a,description:`Create the VS Code task configuration`,merge:(e,t,n)=>ne(e,t,n)}].forEach(({path:t,description:r,merge:a})=>{let c=o(e.snapshots,t);if(c.kind!==`absent`&&c.kind!==`file`){s.unchanged.push(t),s.warnings.push(`Existing VS Code artifact is not a regular file and was left unchanged: ${i(n.invocationDirectory,t)}`);return}ae(s,e,t,a(c.kind===`file`?c.contents:null,f,n.targetDirectory),r,n.invocationDirectory)})}if(u.has(R.Skill)){let t=c({rootDirectory:f,existingDirectories:n.existingSkillDirectories,snapshots:e.snapshots,skill:J,preserveModified:!0});s.changes.push(...t.changes),s.unchanged.push(...t.unchanged),s.warnings.push(...t.warnings.map(e=>t.unchanged.reduce((e,t)=>e.replace(t,i(n.invocationDirectory,t)),e)))}if(u.has(R.Ci))if(!n.repositoryRoot||!n.usesGithub)s.warnings.push(`GitHub Actions setup was selected, but this target is not inside a detected GitHub repository.`);else{let r=N(n.repositoryRoot,j),a=F(n.repositoryRoot,n.targetDirectory).split(I).join(`/`)||`.`,c=te({cliVersion:t.cliVersion,workspaceDirectory:a,bundleDirectories:[]}),l=o(e.snapshots,r);l.kind===`absent`?Z(s,e,{path:r,contents:c,description:`Add credential-free Policy Engine validation`,createOnly:!0}):l.kind===`file`&&l.contents===c?s.unchanged.push(r):(s.unchanged.push(r),s.warnings.push(`Existing GitHub Actions workflow was left unchanged: ${i(n.invocationDirectory,r)}. Adapt it manually to validate each policy bundle.`))}return s.changes.forEach(({path:e})=>X(n.projectRoot,e)),s}const se={[R.Editor]:`VS Code settings and lint task`,[R.Skill]:`Policy Engine Agent Skill`,[R.Ci]:`Validation-only GitHub Actions`},ce=Object.values(R);function Q(e,t){let n=[t.stdout.trim(),t.stderr.trim()].filter(Boolean).join(`
420
420
  `),r=e===`OPA`?x:g;return`${e===`OPA`?`OPA 1.x`:`Regal ${C} or newer`} is required, but \`${e.toLowerCase()} version\` exited with code ${t.code}${n?`: ${n}`:`.`} Install or upgrade it using the official instructions: ${r}`}async function le(e,t,n){let r={opa:null,regal:null},i=[],a=await n(`opa`,[`version`],{cwd:t},e);if(a.error?.code===`ENOENT`)i.push(v);else{let e=`${a.stdout}\n${a.stderr}`,t=_(e);a.code===0?t?i.push(t):r.opa=S(e).version:i.push(t??Q(`OPA`,a))}let o=await n(`regal`,[`version`],{cwd:t},e);if(o.error?.code===`ENOENT`)i.push(b);else{let e=`${o.stdout}\n${o.stderr}`,t=y(e,C,`the generated OPA ${f} capabilities configuration`);o.code===0?t?i.push(t):r.regal=S(e).version:i.push(t??Q(`Regal`,o))}return{tools:r,warnings:i}}async function $(t,a=m,o=k){w(this.process);try{let s=await le(this,this.process.cwd(),o),c=p(this,a),u=new E(this),d=D(t,this.process.stdin.isTTY,this.process.stderr.isTTY),f=await T(u,{features:ce,labels:se,enabled:{[R.Editor]:t.editor,[R.Skill]:t.skill,[R.Ci]:t.ci},interactive:d}),m=Y(c,{features:f}),h=oe({state:c,snapshots:l(this,c.projectRoot,m)},{features:f,cliVersion:e});h.warnings.push(...s.warnings),t.json||this.logger.info(r(h,{cwd:this.process.cwd(),title:`Policy initialization plan`,details:[{label:`Target`,path:h.targetDirectory}]}));let g=h.changes.length===0||t.dryRun;if(h.changes.length>0&&!t.dryRun)if(t.yes)g=!0;else if(d)g=await u.confirm(`Apply this complete plan?`,!0);else throw Error(`The plan requires approval in a non-interactive invocation. Review with --dryRun, then pass --yes.`);g&&!t.dryRun&&h.changes.length>0&&await A(this,h);let _=g&&!t.dryRun&&h.changes.length>0,v=g&&!t.dryRun,y=K({projectPath:n(i(this.process.cwd(),c.targetDirectory)),hasSkill:v&&f.includes(R.Skill),newCommand:h.nextSteps[0]}),b=q(h,{applied:_,dryRun:t.dryRun,cwd:this.process.cwd(),aiHandoff:y,tools:s.tools});if(t.json){this.process.stdout.write(`${JSON.stringify(b)}\n`);return}if(t.dryRun){this.logger.info(L.yellow(`Dry run complete. No changes were written.`));return}if(!g){this.logger.info(L.yellow(`No changes applied.`));return}if(h.changes.length===0){let e=h.warnings.length===s.warnings.length?`Policy project is already initialized.`:`Existing policy project was left unchanged.`;this.logger.info(L.green(e))}else this.logger.info(L.green(`Policy project initialized.`));h.nextSteps.length>0&&(this.logger.info(`\n${L.bold(`Next steps`)}`),h.nextSteps.forEach(e=>this.logger.info(e))),this.logger.info(`\n${L.bold(`AI handoff — paste into your coding agent`)}`),this.logger.info(y)}catch(e){if(e instanceof O)return this.process.exit(130);throw e}}export{$ as init};
421
- //# sourceMappingURL=impl-Bf2Qli6c2.mjs.map
421
+ //# sourceMappingURL=impl-DT4VbZ-Q2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-Bf2Qli6c2.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-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-planning.ts","../src/commands/policy/init/impl.ts"],"sourcesContent":["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 = 3 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 project path and next step\n * @returns Raw one-line prompt\n */\nexport function buildPolicyInitAiHandoff(options: {\n /** Display path to the policy project. */\n projectPath: string;\n /** Whether the policy authoring skill was installed. */\n hasSkill: boolean;\n /** Copyable new-bundle command. */\n newCommand: string;\n}): string {\n const instruction = options.hasSkill ? `Use the \\`${POLICY_SKILL_NAME}\\` skill and run` : 'Run';\n return (\n `${instruction} ${options.newCommand} to add a bundle from a template, ` +\n `then adapt the policy document tree and input/output contract to the intended application.`\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","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 } from '../scaffolding/project-plan-output.js';\nimport {\n getPlanningPathSnapshot,\n getPlanningFileSnapshot,\n planFileChange,\n type PlanningPathSnapshot,\n} from '../scaffolding/project-plan.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 {\n generatePolicyWorkspaceFiles,\n POLICY_STARTER_BUNDLE_DIRECTORY,\n type PolicyStarterFile,\n} 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 * 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 generatePolicyWorkspaceFiles().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>([`${POLICY_STARTER_BUNDLE_DIRECTORY}/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 = generatePolicyWorkspaceFiles();\n const newCommand = 'transcend policy new';\n const plan: PolicyInitProjectPlan = {\n version: POLICY_INIT_RESULT_VERSION,\n command: 'init',\n rootDirectory: state.projectRoot,\n targetDirectory: state.targetDirectory,\n // Init creates a workspace only; bundles (and their .manifest) come from `policy new`.\n manifestPath: state.targetDirectory,\n changes: [],\n unchanged: [],\n warnings: [],\n nextSteps: [newCommand],\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 if (state.relativeFilePaths.length === 0) {\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 allWorkspaceFilesMatch = 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 allWorkspaceFilesMatch = 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\n const allowedPaths = starterRelativePaths(files);\n const hasCustomPaths = state.relativeFilePaths.some((path) => !allowedPaths.has(path));\n if (!allWorkspaceFilesMatch || hasCustomPaths) {\n plan.warnings.push(\n `Existing policy target contains custom or partial content, so no workspace files were added or overwritten. ` +\n `Review ${displayProjectPath(\n state.invocationDirectory,\n state.targetDirectory,\n )} manually, then run \\`${newCommand}\\`.`,\n );\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\n type EditorMergeFn = (\n contents: string | null,\n repositoryRoot: string,\n targetDirectory: string,\n ) => PolicyEditorMergeResult;\n const editorArtifacts: {\n /** Absolute path. */\n path: string;\n /** Plan description. */\n description: string;\n /** Merge function. */\n merge: EditorMergeFn;\n }[] = [\n {\n path: settingsPath,\n description: 'Merge strict target-scoped OPA and Rego editor settings',\n merge: (contents, repositoryRoot, targetDirectory) =>\n mergePolicyEditorSettings(contents, repositoryRoot, targetDirectory),\n },\n {\n path: extensionsPath,\n description: 'Recommend the OPA extension and discourage its syntax-only conflict',\n merge: (contents) => mergePolicyEditorExtensions(contents),\n },\n {\n path: tasksPath,\n description: 'Create the VS Code task configuration',\n merge: (contents, repositoryRoot, targetDirectory) =>\n mergePolicyEditorTasks(contents, repositoryRoot, targetDirectory),\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 workspaceDirectory =\n relative(state.repositoryRoot, state.targetDirectory).split(sep).join('/') || '.';\n const workflowContents = generatePolicyGithubActionsWorkflow({\n cliVersion: options.cliVersion,\n workspaceDirectory,\n bundleDirectories: [],\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 validate each policy bundle.`,\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 { POLICY_STARTER_OPA_VERSION } from '../../../lib/policy/policy-scaffold-templates.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 isInteractivePromptInvocation,\n PromptCancelledError,\n resolveSetupFeatures,\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 * 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 ${POLICY_STARTER_OPA_VERSION} 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 = isInteractivePromptInvocation(\n flags,\n this.process.stdin.isTTY,\n this.process.stderr.isTTY,\n );\n const features = await resolveSetupFeatures(prompts, {\n features: ALL_SETUP_FEATURES,\n labels: SETUP_LABELS,\n enabled: {\n [PolicySetupFeature.Editor]: flags.editor,\n [PolicySetupFeature.Skill]: flags.skill,\n [PolicySetupFeature.Ci]: flags.ci,\n },\n interactive,\n });\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: [{ label: 'Target', path: plan.targetDirectory }],\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 hasSkill: setupAvailable && features.includes(PolicySetupFeature.Skill),\n newCommand: 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":"uyBAOA,MAAa,EAAqB,CAEhC,OAAQ,SAER,MAAO,QAEP,GAAI,KACL,OCdD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ICAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ICAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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vE,WAAY,EAAK,UAAU,GAC5B,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,EACnB,OAAO,KAAK,QAAQ,KAAK,IAAI,CAE/B,MAAM"}
1
+ {"version":3,"file":"impl-DT4VbZ-Q2.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-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-planning.ts","../src/commands/policy/init/impl.ts"],"sourcesContent":["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 = 3 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 project path and next step\n * @returns Raw one-line prompt\n */\nexport function buildPolicyInitAiHandoff(options: {\n /** Display path to the policy project. */\n projectPath: string;\n /** Whether the policy authoring skill was installed. */\n hasSkill: boolean;\n /** Copyable new-bundle command. */\n newCommand: string;\n}): string {\n const instruction = options.hasSkill ? `Use the \\`${POLICY_SKILL_NAME}\\` skill and run` : 'Run';\n return (\n `${instruction} ${options.newCommand} to add a bundle from a template, ` +\n `then adapt the policy document tree and input/output contract to the intended application.`\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","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 } from '../scaffolding/project-plan-output.js';\nimport {\n getPlanningPathSnapshot,\n getPlanningFileSnapshot,\n planFileChange,\n type PlanningPathSnapshot,\n} from '../scaffolding/project-plan.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 {\n generatePolicyWorkspaceFiles,\n POLICY_STARTER_BUNDLE_DIRECTORY,\n type PolicyStarterFile,\n} 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 * 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 generatePolicyWorkspaceFiles().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>([`${POLICY_STARTER_BUNDLE_DIRECTORY}/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 = generatePolicyWorkspaceFiles();\n const newCommand = 'transcend policy new';\n const plan: PolicyInitProjectPlan = {\n version: POLICY_INIT_RESULT_VERSION,\n command: 'init',\n rootDirectory: state.projectRoot,\n targetDirectory: state.targetDirectory,\n // Init creates a workspace only; bundles (and their .manifest) come from `policy new`.\n manifestPath: state.targetDirectory,\n changes: [],\n unchanged: [],\n warnings: [],\n nextSteps: [newCommand],\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 if (state.relativeFilePaths.length === 0) {\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 allWorkspaceFilesMatch = 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 allWorkspaceFilesMatch = 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\n const allowedPaths = starterRelativePaths(files);\n const hasCustomPaths = state.relativeFilePaths.some((path) => !allowedPaths.has(path));\n if (!allWorkspaceFilesMatch || hasCustomPaths) {\n plan.warnings.push(\n `Existing policy target contains custom or partial content, so no workspace files were added or overwritten. ` +\n `Review ${displayProjectPath(\n state.invocationDirectory,\n state.targetDirectory,\n )} manually, then run \\`${newCommand}\\`.`,\n );\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\n type EditorMergeFn = (\n contents: string | null,\n repositoryRoot: string,\n targetDirectory: string,\n ) => PolicyEditorMergeResult;\n const editorArtifacts: {\n /** Absolute path. */\n path: string;\n /** Plan description. */\n description: string;\n /** Merge function. */\n merge: EditorMergeFn;\n }[] = [\n {\n path: settingsPath,\n description: 'Merge strict target-scoped OPA and Rego editor settings',\n merge: (contents, repositoryRoot, targetDirectory) =>\n mergePolicyEditorSettings(contents, repositoryRoot, targetDirectory),\n },\n {\n path: extensionsPath,\n description: 'Recommend the OPA extension and discourage its syntax-only conflict',\n merge: (contents) => mergePolicyEditorExtensions(contents),\n },\n {\n path: tasksPath,\n description: 'Create the VS Code task configuration',\n merge: (contents, repositoryRoot, targetDirectory) =>\n mergePolicyEditorTasks(contents, repositoryRoot, targetDirectory),\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 workspaceDirectory =\n relative(state.repositoryRoot, state.targetDirectory).split(sep).join('/') || '.';\n const workflowContents = generatePolicyGithubActionsWorkflow({\n cliVersion: options.cliVersion,\n workspaceDirectory,\n bundleDirectories: [],\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 validate each policy bundle.`,\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 { POLICY_STARTER_OPA_VERSION } from '../../../lib/policy/policy-scaffold-templates.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 isInteractivePromptInvocation,\n PromptCancelledError,\n resolveSetupFeatures,\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 * 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 ${POLICY_STARTER_OPA_VERSION} 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 = isInteractivePromptInvocation(\n flags,\n this.process.stdin.isTTY,\n this.process.stderr.isTTY,\n );\n const features = await resolveSetupFeatures(prompts, {\n features: ALL_SETUP_FEATURES,\n labels: SETUP_LABELS,\n enabled: {\n [PolicySetupFeature.Editor]: flags.editor,\n [PolicySetupFeature.Skill]: flags.skill,\n [PolicySetupFeature.Ci]: flags.ci,\n },\n interactive,\n });\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: [{ label: 'Target', path: plan.targetDirectory }],\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 hasSkill: setupAvailable && features.includes(PolicySetupFeature.Skill),\n newCommand: 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":"uyBAOA,MAAa,EAAqB,CAEhC,OAAQ,SAER,MAAO,QAEP,GAAI,KACL,OCdD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ICAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ICAA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AU,GAAkB,EAAS,SAAS,EAAmB,MAAM,CACvE,WAAY,EAAK,UAAU,GAC5B,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,EACnB,OAAO,KAAK,QAAQ,KAAK,IAAI,CAE/B,MAAM"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./notifyPrivacyRequestsAdditionalTime-BWsm5Y5K.mjs";import{t}from"./done-input-validation-LiTaCEzF.mjs";async function n({auth:n,transcendUrl:r,createdAtBefore:i,createdAtAfter:a,updatedAtBefore:o,updatedAtAfter:s,actions:c,daysLeft:l,days:u,requestIds:d,emailTemplate:f,concurrency:p}){t(this.process),await e({transcendUrl:r,requestActions:c,auth:n,emailTemplate:f,days:u,daysLeft:l,requestIds:d,concurrency:p,createdAtBefore:i,createdAtAfter:a,updatedAtBefore:o,updatedAtAfter:s})}export{n as notifyAdditionalTime};
2
- //# sourceMappingURL=impl-D8YS5Bge.mjs.map
1
+ import{t as e}from"./notifyPrivacyRequestsAdditionalTime-rnUXdvBR.mjs";import{t}from"./done-input-validation-LiTaCEzF.mjs";async function n({auth:n,transcendUrl:r,createdAtBefore:i,createdAtAfter:a,updatedAtBefore:o,updatedAtAfter:s,actions:c,daysLeft:l,days:u,requestIds:d,emailTemplate:f,concurrency:p}){t(this.process),await e({transcendUrl:r,requestActions:c,auth:n,emailTemplate:f,days:u,daysLeft:l,requestIds:d,concurrency:p,createdAtBefore:i,createdAtAfter:a,updatedAtBefore:o,updatedAtAfter:s})}export{n as notifyAdditionalTime};
2
+ //# sourceMappingURL=impl-Ds6ROQi7.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-D8YS5Bge.mjs","names":[],"sources":["../src/commands/request/notify-additional-time/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 { notifyPrivacyRequestsAdditionalTime } from '../../../lib/requests/index.js';\n\nexport interface NotifyAdditionalTimeCommandFlags {\n auth: string;\n createdAtBefore: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n actions?: RequestAction[];\n daysLeft: number;\n days: number;\n requestIds?: string[];\n emailTemplate: string;\n transcendUrl: string;\n concurrency: number;\n}\n\nexport async function notifyAdditionalTime(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n actions,\n daysLeft,\n days,\n requestIds,\n emailTemplate,\n concurrency,\n }: NotifyAdditionalTimeCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await notifyPrivacyRequestsAdditionalTime({\n transcendUrl,\n requestActions: actions,\n auth,\n emailTemplate,\n days,\n daysLeft,\n requestIds,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n });\n}\n"],"mappings":"2HAqBA,eAAsB,EAEpB,CACE,OACA,eACA,kBACA,iBACA,kBACA,iBACA,UACA,WACA,OACA,aACA,gBACA,eAEa,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAAoC,CACxC,eACA,eAAgB,EAChB,OACA,gBACA,OACA,WACA,aACA,cACA,kBACA,iBACA,kBACA,iBACD,CAAC"}
1
+ {"version":3,"file":"impl-Ds6ROQi7.mjs","names":[],"sources":["../src/commands/request/notify-additional-time/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 { notifyPrivacyRequestsAdditionalTime } from '../../../lib/requests/index.js';\n\nexport interface NotifyAdditionalTimeCommandFlags {\n auth: string;\n createdAtBefore: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n actions?: RequestAction[];\n daysLeft: number;\n days: number;\n requestIds?: string[];\n emailTemplate: string;\n transcendUrl: string;\n concurrency: number;\n}\n\nexport async function notifyAdditionalTime(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n actions,\n daysLeft,\n days,\n requestIds,\n emailTemplate,\n concurrency,\n }: NotifyAdditionalTimeCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await notifyPrivacyRequestsAdditionalTime({\n transcendUrl,\n requestActions: actions,\n auth,\n emailTemplate,\n days,\n daysLeft,\n requestIds,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n });\n}\n"],"mappings":"2HAqBA,eAAsB,EAEpB,CACE,OACA,eACA,kBACA,iBACA,kBACA,iBACA,UACA,WACA,OACA,aACA,gBACA,eAEa,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAAoC,CACxC,eACA,eAAgB,EAChB,OACA,gBACA,OACA,WACA,aACA,cACA,kBACA,iBACA,kBACA,iBACD,CAAC"}
@@ -1,3 +1,3 @@
1
- import{c as e,i as t,n,t as r}from"./policy-project-discovery-DV5PnFJq.mjs";import{c as i,i as a,l as o,o as s,s as c}from"./policy-runtime-6jmkXlBk.mjs";import{n as l}from"./policy-bundle-manifest-BDey6EBs.mjs";import{n as u}from"./inquirer-jzIQWAvq.mjs";import{t as d}from"./done-input-validation-LiTaCEzF.mjs";import{r as f}from"./prompts-BhXfYD6g.mjs";import{t as p}from"./run-captured-process-BjaSDWXG.mjs";import m from"node:path";import h from"colors";const g=[`manifest`,`opa-version`,`regal-version`,`format`,`opa-check`,`regal-lint`,`opa-test`],_={manifest:`Manifest and package roots`,"opa-version":`OPA 1.x`,"regal-version":`Regal`,format:`OPA formatting`,"opa-check":`OPA strict check`,"regal-lint":`Regal lint`,"opa-test":`OPA tests`};function v(e,t){return[e.stdout.trim(),e.stderr.trim()].filter(Boolean).join(`
1
+ import{c as e,i as t,n,t as r}from"./policy-project-discovery-oc49b2gr.mjs";import{c as i,i as a,l as o,o as s,s as c}from"./policy-runtime-6jmkXlBk.mjs";import{n as l}from"./policy-bundle-manifest-B1Herd_n.mjs";import{n as u}from"./inquirer-jzIQWAvq.mjs";import{t as d}from"./done-input-validation-LiTaCEzF.mjs";import{r as f}from"./prompts-BhXfYD6g.mjs";import{t as p}from"./run-captured-process-BjaSDWXG.mjs";import m from"node:path";import h from"colors";const g=[`manifest`,`opa-version`,`regal-version`,`format`,`opa-check`,`regal-lint`,`opa-test`],_={manifest:`Manifest and package roots`,"opa-version":`OPA 1.x`,"regal-version":`Regal`,format:`OPA formatting`,"opa-check":`OPA strict check`,"regal-lint":`Regal lint`,"opa-test":`OPA tests`};function v(e,t){return[e.stdout.trim(),e.stderr.trim()].filter(Boolean).join(`
2
2
  `)||t}function y(e,t){return[...new Set(e.split(/\r?\n/gu).map(e=>e.trim()).filter(Boolean).map(e=>m.isAbsolute(e)?m.relative(t,e).split(m.sep).join(`/`):e.split(m.sep).join(`/`)))].sort()}function b(e,t,n=t){return e.fs.readdirSync(n,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name)).flatMap(r=>{let i=m.join(n,r.name);return r.isDirectory()?b(e,t,i):!r.isFile()||!r.name.endsWith(`.rego`)?[]:[{path:m.relative(t,i).split(m.sep).join(`/`),contents:e.fs.readFileSync(i,`utf8`)}]})}function x(e,t){let n=t;for(;;){let t=m.join(n,`.regal`,`config.yaml`);if(e.fs.existsSync(t))return t;let r=m.join(n,`.regal.yaml`);if(e.fs.existsSync(r))return r;let i=m.dirname(n);if(i===n)return;n=i}}function S(e,t,n){n?e.logger.info(`${h.bold(n)}\n`):e.logger.info(`${h.bold(`Policy verification`)}\n`),t.checks.forEach(({name:n,status:r})=>{let i=r===`passed`?`PASS`:r===`failed`?`FAIL`:`SKIP`,a=r===`passed`?h.green(i):r===`failed`?h.red(i):h.yellow(i),o=n===`opa-version`&&t.tools.opa?` (${t.tools.opa})`:n===`regal-version`&&t.tools.regal?` (${t.tools.regal})`:``;e.logger.info(`${a} ${_[n]}${o}`)}),t.diagnostics.length>0&&e.logger.error(``),t.diagnostics.forEach(t=>{let n=t.path?`${t.path}: `:``;e.logger.error(h.red(`error [${t.code}]: ${n}${t.message}`))}),t.status===`passed`?(e.logger.info(``),e.logger.info(h.green(`Policy verification passed.`))):(e.logger.error(``),e.logger.error(h.red(`Policy verification failed.`)))}async function C({fix:t,noInteractive:n,json:r},d,p){let _=g.map(e=>({name:e,status:`skipped`})),S=[],C={version:1,status:`passed`,directory:d,fix:t,tools:{opa:null,regal:null},checks:_,unformattedFiles:[],fixedFiles:[],diagnostics:S},w=(e,t)=>{_.find(t=>t.name===e).status=t},T=(e,t,n)=>{S.push({code:e,severity:`error`,message:t,...n?{path:n}:{}})};if(!this.fs.existsSync(d)||!this.fs.statSync(d).isDirectory())return w(`manifest`,`failed`),T(`project.directory`,`Policy directory does not exist or is not a directory: ${d}`,m.relative(this.process.cwd(),d)),C.status=`failed`,C;let E=m.join(d,e);try{l(this.fs.existsSync(E)?this.fs.readFileSync(E,`utf8`):void 0,b(this,d)),w(`manifest`,`passed`)}catch(e){w(`manifest`,`failed`),T(`manifest.invalid`,e instanceof Error?e.message:String(e),m.relative(this.process.cwd(),E))}let D=await p(`opa`,[`version`],{cwd:d},this);if(D.error?.code===`ENOENT`)w(`opa-version`,`failed`),T(`opa.missing`,a);else{let e=`${D.stdout}\n${D.stderr}`,t=i(e);D.code!==0||t?(w(`opa-version`,`failed`),T(`opa.version`,t??v(D,`Unable to determine the installed OPA version.`))):(C.tools.opa=c(e).version,w(`opa-version`,`passed`))}let O=await p(`regal`,[`version`],{cwd:d},this);if(O.error?.code===`ENOENT`)w(`regal-version`,`failed`),T(`regal.missing`,s);else{let e=`${O.stdout}\n${O.stderr}`,t=o(e);O.code!==0||t?(w(`regal-version`,`failed`),T(`regal.version`,t??v(O,`Unable to determine the installed Regal version.`))):(C.tools.regal=c(e).version,w(`regal-version`,`passed`))}if(C.tools.opa){let e=await p(`opa`,[`fmt`,`--list`,d],{cwd:d},this);if(e.code!==0)w(`format`,`failed`),T(`opa.format`,v(e,`opa fmt --list failed with exit code ${e.code}`));else if(C.unformattedFiles=y(e.stdout,d),C.unformattedFiles.length===0)w(`format`,`passed`);else{let e=t,i=f({json:r,noInteractive:n},this.process.stdin.isTTY,this.process.stderr.isTTY);if(!r&&!t){this.logger.error(h.red(`Policy files are not formatted:`)),C.unformattedFiles.forEach(e=>{this.logger.error(h.red(` - ${e}`))});let e=await p(`opa`,[`fmt`,`--diff`,d],{cwd:d},this),t=e.stdout.trim()||e.stderr.trim();t&&(this.logger.error(``),this.logger.error(t))}if(!t&&i)try{e=await u({message:`Format the unformatted policy files listed above?`})}catch(e){let t=e instanceof Error?e.message:String(e);throw/force closed|prompt.*cancel|user.*close|SIGINT/iu.test(t)&&this.process.exit(130),e}if(e){let e=await p(`opa`,[`fmt`,`--write`,d],{cwd:d},this);e.code===0?(C.fixedFiles=[...C.unformattedFiles],w(`format`,`passed`)):(w(`format`,`failed`),T(`opa.format-fix`,v(e,`opa fmt --write failed with exit code ${e.code}`)))}else w(`format`,`failed`),T(`opa.format-required`,"Policy files are not formatted. Re-run `transcend policy lint --fix` to repair them.")}let i=await p(`opa`,[`check`,`--strict`,`--ignore`,`*_test.rego`,d],{cwd:d},this);i.code===0?w(`opa-check`,`passed`):(w(`opa-check`,`failed`),T(`opa.check`,v(i,`opa check failed with exit code ${i.code}`)))}if(C.tools.regal){let e=x(this,d),t=await p(`regal`,[`lint`,`--fail-level`,`warning`,...e?[`--config-file`,e]:[],d],{cwd:d},this);t.code===0?w(`regal-lint`,`passed`):(w(`regal-lint`,`failed`),T(`regal.lint`,v(t,`regal lint failed with exit code ${t.code}`)))}if(C.tools.opa){let e=await p(`opa`,[`test`,`--fail-on-empty`,`-b`,d],{cwd:d},this);e.code===0?w(`opa-test`,`passed`):(w(`opa-test`,`failed`),T(`opa.test`,v(e,`opa test --fail-on-empty -b failed with exit code ${e.code}`)))}return C.status=_.some(({status:e})=>e===`failed`)?`failed`:`passed`,C}async function w(e,i=r,a=p){d(this.process);let{fix:o=!1,noInteractive:s=!1,json:c=!1}=e,l=t(this.process.cwd(),i);if(!this.fs.existsSync(l)||!this.fs.statSync(l).isDirectory()){let e={version:1,status:`failed`,directory:l,fix:o,tools:{opa:null,regal:null},checks:g.map(e=>({name:e,status:e===`manifest`?`failed`:`skipped`})),unformattedFiles:[],fixedFiles:[],diagnostics:[{code:`project.directory`,severity:`error`,message:`Policy directory does not exist or is not a directory: ${l}`,path:m.relative(this.process.cwd(),l)}]};c?this.process.stdout.write(`${JSON.stringify(e)}\n`):S(this,e),this.process.exitCode=1;return}let u=n(this,l);if(u.length===0){let e={version:1,status:`failed`,directory:l,fix:o,tools:{opa:null,regal:null},checks:g.map(e=>({name:e,status:e===`manifest`?`failed`:`skipped`})),unformattedFiles:[],fixedFiles:[],diagnostics:[{code:`project.bundles`,severity:`error`,message:"No publishable policy bundles found. Add one with `transcend policy new`, or pass a directory that contains a `.manifest`.",path:m.relative(this.process.cwd(),l)||`.`}]};c?this.process.stdout.write(`${JSON.stringify(e)}\n`):S(this,e),this.process.exitCode=1;return}let f=[];for(let e of u)f.push(await C.call(this,{fix:o,noInteractive:s,json:c},e,a));let h=f.some(e=>e.status===`failed`);if(c)if(f.length===1)this.process.stdout.write(`${JSON.stringify(f[0])}\n`);else{let e={version:2,status:h?`failed`:`passed`,directory:l,fix:o,results:f};this.process.stdout.write(`${JSON.stringify(e)}\n`)}else f.length===1?S(this,f[0]):f.forEach((e,t)=>{t>0&&this.logger.info(``);let n=m.relative(this.process.cwd(),e.directory)||e.directory;S(this,e,`Policy verification — ${n}`)});h&&(this.process.exitCode=1)}export{w as lint};
3
- //# sourceMappingURL=impl-ClhMRgQZ.mjs.map
3
+ //# sourceMappingURL=impl-P1hltmA6.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-ClhMRgQZ.mjs","names":[],"sources":["../src/lib/policy/policy-lint-model.ts","../src/lib/policy/policy-lint-output.ts","../src/commands/policy/lint/impl.ts"],"sourcesContent":["/** Stable policy lint result schema version. */\nexport const POLICY_LINT_RESULT_VERSION = 1;\n\n/** Stable multi-bundle lint result schema version. */\nexport const POLICY_LINT_MULTI_RESULT_VERSION = 2;\n\n/** Status of the full gate or an individual verification. */\nexport type PolicyLintStatus = 'passed' | 'failed' | 'skipped';\n\n/** One named policy verification. */\nexport interface PolicyLintCheck {\n /** Stable verification name. */\n name:\n | 'manifest'\n | 'opa-version'\n | 'regal-version'\n | 'format'\n | 'opa-check'\n | 'regal-lint'\n | 'opa-test';\n /** Verification outcome. */\n status: PolicyLintStatus;\n}\n\n/** Stable verification execution order. */\nexport const POLICY_LINT_CHECK_NAMES: PolicyLintCheck['name'][] = [\n 'manifest',\n 'opa-version',\n 'regal-version',\n 'format',\n 'opa-check',\n 'regal-lint',\n 'opa-test',\n];\n\n/** User-facing verification labels. */\nexport const POLICY_LINT_CHECK_LABELS: Readonly<Record<PolicyLintCheck['name'], string>> = {\n manifest: 'Manifest and package roots',\n 'opa-version': 'OPA 1.x',\n 'regal-version': 'Regal',\n format: 'OPA formatting',\n 'opa-check': 'OPA strict check',\n 'regal-lint': 'Regal lint',\n 'opa-test': 'OPA tests',\n};\n\n/** One machine-readable policy lint diagnostic. */\nexport interface PolicyLintDiagnostic {\n /** Stable diagnostic identifier. */\n code: string;\n /** Diagnostic severity. */\n severity: 'error';\n /** Human-readable detail, including captured tool output when available. */\n message: string;\n /** Optional path relative to the invocation directory. */\n path?: string;\n}\n\n/** Detected local policy tool versions. */\nexport interface PolicyLintTools {\n /** Detected OPA version, or null when missing or unsupported. */\n opa: string | null;\n /** Detected Regal version, or null when missing or unsupported. */\n regal: string | null;\n}\n\n/** Stable result emitted by `transcend policy lint --json` for one bundle. */\nexport interface PolicyLintResult {\n /** Result schema version. */\n version: typeof POLICY_LINT_RESULT_VERSION;\n /** Overall verification outcome. */\n status: Exclude<PolicyLintStatus, 'skipped'>;\n /** Absolute policy bundle directory. */\n directory: string;\n /** Whether formatting repair was explicitly requested. */\n fix: boolean;\n /** Detected supported tool versions. */\n tools: PolicyLintTools;\n /** Verification outcomes in stable execution order. */\n checks: PolicyLintCheck[];\n /** Files found to need OPA formatting, relative to the policy directory. */\n unformattedFiles: string[];\n /** Files repaired with OPA formatting, relative to the policy directory. */\n fixedFiles: string[];\n /** Ordered verification diagnostics. */\n diagnostics: PolicyLintDiagnostic[];\n}\n\n/**\n * Stable result when `transcend policy lint --json` verifies multiple bundles.\n *\n * Emitted only when the selected path is a workspace with more than one\n * publishable `*-bundle/` directory.\n */\nexport interface PolicyLintMultiResult {\n /** Result schema version. */\n version: typeof POLICY_LINT_MULTI_RESULT_VERSION;\n /** Overall verification outcome across all bundles. */\n status: Exclude<PolicyLintStatus, 'skipped'>;\n /** Absolute policy workspace directory that was searched. */\n directory: string;\n /** Whether formatting repair was explicitly requested. */\n fix: boolean;\n /** Per-bundle results in discovery order. */\n results: PolicyLintResult[];\n}\n","import path from 'node:path';\n\nimport type { CapturedProcessResult } from '../cli/run-captured-process.js';\n\n/**\n * Use captured tool output as a concise diagnostic.\n *\n * @param result - Captured process result\n * @param fallback - Message used when the tool emitted no output\n * @returns Diagnostic message\n */\nexport function getPolicyProcessFailureMessage(\n result: CapturedProcessResult,\n fallback: string,\n): string {\n const output = [result.stdout.trim(), result.stderr.trim()].filter(Boolean).join('\\n');\n return output || fallback;\n}\n\n/**\n * Convert absolute OPA formatter paths to stable project-relative paths.\n *\n * @param stdout - `opa fmt --list` output\n * @param projectDirectory - Absolute policy directory\n * @returns Sorted unique paths\n */\nexport function parseUnformattedPolicyFiles(stdout: string, projectDirectory: string): string[] {\n return [\n ...new Set(\n stdout\n .split(/\\r?\\n/gu)\n .map((file) => file.trim())\n .filter(Boolean)\n .map((file) =>\n path.isAbsolute(file)\n ? path.relative(projectDirectory, file).split(path.sep).join('/')\n : file.split(path.sep).join('/'),\n ),\n ),\n ].sort();\n}\n","import path from 'node:path';\n\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport {\n runCapturedProcess,\n type CapturedProcessRunner,\n} from '../../../lib/cli/run-captured-process.js';\nimport { inquirerConfirmBoolean } from '../../../lib/helpers/inquirer.js';\nimport {\n type PolicyBundleRegoFile,\n validatePolicyBundleContents,\n} from '../../../lib/policy/policy-bundle-manifest.js';\nimport {\n type PolicyLintCheck,\n type PolicyLintDiagnostic,\n type PolicyLintMultiResult,\n type PolicyLintResult,\n POLICY_LINT_CHECK_LABELS,\n POLICY_LINT_CHECK_NAMES,\n POLICY_LINT_MULTI_RESULT_VERSION,\n POLICY_LINT_RESULT_VERSION,\n} from '../../../lib/policy/policy-lint-model.js';\nimport {\n getPolicyProcessFailureMessage,\n parseUnformattedPolicyFiles,\n} from '../../../lib/policy/policy-lint-output.js';\nimport {\n DEFAULT_POLICY_PROJECT_DIRECTORY,\n discoverPolicyBundleDirectories,\n resolvePolicyProjectDirectory,\n} from '../../../lib/policy/policy-project-discovery.js';\nimport {\n OPA_MISSING_MESSAGE,\n parsePolicyToolVersion,\n REGAL_MISSING_MESSAGE,\n unsupportedOpaVersionMessage,\n unsupportedRegalVersionMessage,\n} from '../../../lib/policy/policy-runtime.js';\nimport { POLICY_MANIFEST_FILENAME } from '../../../lib/policy/policy-scaffold-templates.js';\nimport { isInteractivePromptInvocation } from '../../../lib/scaffolding/prompts.js';\n\n/** CLI flags for `transcend policy lint`. */\nexport interface LintCommandFlags {\n /** Apply OPA formatting. */\n fix: boolean;\n /** Disable the optional formatting confirmation. */\n noInteractive: boolean;\n /** Emit one stable JSON result on stdout. */\n json: boolean;\n}\n\n/**\n * Collect Rego source snapshots without following symlinks.\n *\n * @param context - CLI context\n * @param projectDirectory - Absolute policy directory\n * @param currentDirectory - Current recursive directory\n * @returns Deterministically ordered Rego snapshots\n */\nfunction collectRegoFiles(\n context: LocalContext,\n projectDirectory: string,\n currentDirectory: string = projectDirectory,\n): PolicyBundleRegoFile[] {\n return context.fs\n .readdirSync(currentDirectory, { withFileTypes: true })\n .sort((left, right) => left.name.localeCompare(right.name))\n .flatMap((entry) => {\n const absolutePath = path.join(currentDirectory, entry.name);\n if (entry.isDirectory()) {\n return collectRegoFiles(context, projectDirectory, absolutePath);\n }\n if (!entry.isFile() || !entry.name.endsWith('.rego')) {\n return [];\n }\n return [\n {\n path: path.relative(projectDirectory, absolutePath).split(path.sep).join('/'),\n contents: context.fs.readFileSync(absolutePath, 'utf8'),\n },\n ];\n });\n}\n\n/**\n * Resolve a Regal config file for a bundle, walking up to the workspace.\n *\n * @param context - CLI context\n * @param bundleDirectory - Absolute bundle directory\n * @returns Absolute config path, or undefined when none is found\n */\nfunction resolveRegalConfigFile(\n context: LocalContext,\n bundleDirectory: string,\n): string | undefined {\n let current = bundleDirectory;\n for (;;) {\n const nestedRegalConfig = path.join(current, '.regal', 'config.yaml');\n if (context.fs.existsSync(nestedRegalConfig)) {\n return nestedRegalConfig;\n }\n const rootRegalConfig = path.join(current, '.regal.yaml');\n if (context.fs.existsSync(rootRegalConfig)) {\n return rootRegalConfig;\n }\n const parent = path.dirname(current);\n if (parent === current) {\n return undefined;\n }\n current = parent;\n }\n}\n\n/**\n * Render the terminal summary for a policy verification result.\n *\n * @param context - CLI context\n * @param result - Completed verification result\n * @param heading - Optional section heading when linting multiple bundles\n */\nfunction renderResult(context: LocalContext, result: PolicyLintResult, heading?: string): void {\n if (heading) {\n context.logger.info(`${colors.bold(heading)}\\n`);\n } else {\n context.logger.info(`${colors.bold('Policy verification')}\\n`);\n }\n result.checks.forEach(({ name, status }) => {\n const label = status === 'passed' ? 'PASS' : status === 'failed' ? 'FAIL' : 'SKIP';\n const styledLabel =\n status === 'passed'\n ? colors.green(label)\n : status === 'failed'\n ? colors.red(label)\n : colors.yellow(label);\n const version =\n name === 'opa-version' && result.tools.opa\n ? ` (${result.tools.opa})`\n : name === 'regal-version' && result.tools.regal\n ? ` (${result.tools.regal})`\n : '';\n context.logger.info(`${styledLabel} ${POLICY_LINT_CHECK_LABELS[name]}${version}`);\n });\n if (result.diagnostics.length > 0) {\n context.logger.error('');\n }\n result.diagnostics.forEach((diagnostic) => {\n const location = diagnostic.path ? `${diagnostic.path}: ` : '';\n context.logger.error(\n colors.red(`error [${diagnostic.code}]: ${location}${diagnostic.message}`),\n );\n });\n if (result.status === 'passed') {\n context.logger.info('');\n context.logger.info(colors.green('Policy verification passed.'));\n } else {\n context.logger.error('');\n context.logger.error(colors.red('Policy verification failed.'));\n }\n}\n\n/**\n * Verify one publishable policy bundle directory.\n *\n * @param context - CLI context\n * @param flags - Command flags\n * @param resolvedDir - Absolute bundle directory\n * @param runner - Captured subprocess runner\n * @returns Completed verification result\n */\nasync function lintBundle(\n this: LocalContext,\n { fix, noInteractive, json }: LintCommandFlags,\n resolvedDir: string,\n runner: CapturedProcessRunner,\n): Promise<PolicyLintResult> {\n const checks: PolicyLintCheck[] = POLICY_LINT_CHECK_NAMES.map((name) => ({\n name,\n status: 'skipped',\n }));\n const diagnostics: PolicyLintDiagnostic[] = [];\n const result: PolicyLintResult = {\n version: POLICY_LINT_RESULT_VERSION,\n status: 'passed',\n directory: resolvedDir,\n fix,\n tools: { opa: null, regal: null },\n checks,\n unformattedFiles: [],\n fixedFiles: [],\n diagnostics,\n };\n const setStatus = (name: PolicyLintCheck['name'], status: PolicyLintCheck['status']): void => {\n checks.find((check) => check.name === name)!.status = status;\n };\n const addError = (code: string, message: string, diagnosticPath?: string): void => {\n diagnostics.push({\n code,\n severity: 'error',\n message,\n ...(diagnosticPath ? { path: diagnosticPath } : {}),\n });\n };\n\n if (!this.fs.existsSync(resolvedDir) || !this.fs.statSync(resolvedDir).isDirectory()) {\n setStatus('manifest', 'failed');\n addError(\n 'project.directory',\n `Policy directory does not exist or is not a directory: ${resolvedDir}`,\n path.relative(this.process.cwd(), resolvedDir),\n );\n result.status = 'failed';\n return result;\n }\n\n const manifestPath = path.join(resolvedDir, POLICY_MANIFEST_FILENAME);\n try {\n validatePolicyBundleContents(\n this.fs.existsSync(manifestPath) ? this.fs.readFileSync(manifestPath, 'utf8') : undefined,\n collectRegoFiles(this, resolvedDir),\n );\n setStatus('manifest', 'passed');\n } catch (error) {\n setStatus('manifest', 'failed');\n addError(\n 'manifest.invalid',\n error instanceof Error ? error.message : String(error),\n path.relative(this.process.cwd(), manifestPath),\n );\n }\n\n const opaVersionResult = await runner('opa', ['version'], { cwd: resolvedDir }, this);\n if (opaVersionResult.error?.code === 'ENOENT') {\n setStatus('opa-version', 'failed');\n addError('opa.missing', OPA_MISSING_MESSAGE);\n } else {\n const opaVersionOutput = `${opaVersionResult.stdout}\\n${opaVersionResult.stderr}`;\n const unsupportedOpa = unsupportedOpaVersionMessage(opaVersionOutput);\n if (opaVersionResult.code !== 0 || unsupportedOpa) {\n setStatus('opa-version', 'failed');\n addError(\n 'opa.version',\n unsupportedOpa ??\n getPolicyProcessFailureMessage(\n opaVersionResult,\n 'Unable to determine the installed OPA version.',\n ),\n );\n } else {\n result.tools.opa = parsePolicyToolVersion(opaVersionOutput)!.version;\n setStatus('opa-version', 'passed');\n }\n }\n\n const regalVersionResult = await runner('regal', ['version'], { cwd: resolvedDir }, this);\n if (regalVersionResult.error?.code === 'ENOENT') {\n setStatus('regal-version', 'failed');\n addError('regal.missing', REGAL_MISSING_MESSAGE);\n } else {\n const regalVersionOutput = `${regalVersionResult.stdout}\\n${regalVersionResult.stderr}`;\n const unsupportedRegal = unsupportedRegalVersionMessage(regalVersionOutput);\n if (regalVersionResult.code !== 0 || unsupportedRegal) {\n setStatus('regal-version', 'failed');\n addError(\n 'regal.version',\n unsupportedRegal ??\n getPolicyProcessFailureMessage(\n regalVersionResult,\n 'Unable to determine the installed Regal version.',\n ),\n );\n } else {\n result.tools.regal = parsePolicyToolVersion(regalVersionOutput)!.version;\n setStatus('regal-version', 'passed');\n }\n }\n\n if (result.tools.opa) {\n const formatResult = await runner(\n 'opa',\n ['fmt', '--list', resolvedDir],\n { cwd: resolvedDir },\n this,\n );\n if (formatResult.code !== 0) {\n setStatus('format', 'failed');\n addError(\n 'opa.format',\n getPolicyProcessFailureMessage(\n formatResult,\n `opa fmt --list failed with exit code ${formatResult.code}`,\n ),\n );\n } else {\n result.unformattedFiles = parseUnformattedPolicyFiles(formatResult.stdout, resolvedDir);\n if (result.unformattedFiles.length === 0) {\n setStatus('format', 'passed');\n } else {\n let shouldFormat = fix;\n const interactive = isInteractivePromptInvocation(\n { json, noInteractive },\n this.process.stdin.isTTY,\n this.process.stderr.isTTY,\n );\n if (!json && !fix) {\n this.logger.error(colors.red('Policy files are not formatted:'));\n result.unformattedFiles.forEach((file) => {\n this.logger.error(colors.red(` - ${file}`));\n });\n const diffResult = await runner(\n 'opa',\n ['fmt', '--diff', resolvedDir],\n { cwd: resolvedDir },\n this,\n );\n const diff = diffResult.stdout.trim() || diffResult.stderr.trim();\n if (diff) {\n this.logger.error('');\n this.logger.error(diff);\n }\n }\n if (!fix && interactive) {\n try {\n shouldFormat = await inquirerConfirmBoolean({\n message: 'Format the unformatted policy files listed above?',\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (/force closed|prompt.*cancel|user.*close|SIGINT/iu.test(message)) {\n this.process.exit(130);\n }\n throw error;\n }\n }\n if (shouldFormat) {\n const writeResult = await runner(\n 'opa',\n ['fmt', '--write', resolvedDir],\n { cwd: resolvedDir },\n this,\n );\n if (writeResult.code === 0) {\n result.fixedFiles = [...result.unformattedFiles];\n setStatus('format', 'passed');\n } else {\n setStatus('format', 'failed');\n addError(\n 'opa.format-fix',\n getPolicyProcessFailureMessage(\n writeResult,\n `opa fmt --write failed with exit code ${writeResult.code}`,\n ),\n );\n }\n } else {\n setStatus('format', 'failed');\n addError(\n 'opa.format-required',\n 'Policy files are not formatted. Re-run `transcend policy lint --fix` to repair them.',\n );\n }\n }\n }\n\n const checkResult = await runner(\n 'opa',\n ['check', '--strict', '--ignore', '*_test.rego', resolvedDir],\n { cwd: resolvedDir },\n this,\n );\n if (checkResult.code === 0) {\n setStatus('opa-check', 'passed');\n } else {\n setStatus('opa-check', 'failed');\n addError(\n 'opa.check',\n getPolicyProcessFailureMessage(\n checkResult,\n `opa check failed with exit code ${checkResult.code}`,\n ),\n );\n }\n }\n\n if (result.tools.regal) {\n const regalConfig = resolveRegalConfigFile(this, resolvedDir);\n const regalResult = await runner(\n 'regal',\n [\n 'lint',\n '--fail-level',\n 'warning',\n ...(regalConfig ? ['--config-file', regalConfig] : []),\n resolvedDir,\n ],\n { cwd: resolvedDir },\n this,\n );\n if (regalResult.code === 0) {\n setStatus('regal-lint', 'passed');\n } else {\n setStatus('regal-lint', 'failed');\n addError(\n 'regal.lint',\n getPolicyProcessFailureMessage(\n regalResult,\n `regal lint failed with exit code ${regalResult.code}`,\n ),\n );\n }\n }\n\n if (result.tools.opa) {\n const testResult = await runner(\n 'opa',\n ['test', '--fail-on-empty', '-b', resolvedDir],\n { cwd: resolvedDir },\n this,\n );\n if (testResult.code === 0) {\n setStatus('opa-test', 'passed');\n } else {\n setStatus('opa-test', 'failed');\n addError(\n 'opa.test',\n getPolicyProcessFailureMessage(\n testResult,\n `opa test --fail-on-empty -b failed with exit code ${testResult.code}`,\n ),\n );\n }\n }\n\n result.status = checks.some(({ status }) => status === 'failed') ? 'failed' : 'passed';\n return result;\n}\n\n/**\n * Verify local policy bundles with the shared upload contract, OPA, and Regal.\n *\n * With no directory (or the default workspace path), discovers every immediate\n * child that contains a `.manifest` and verifies each. Pass one bundle path to\n * verify a single publishable unit.\n *\n * @param this - CLI context\n * @param flags - Command flags\n * @param directory - Policy workspace or bundle directory\n * @param runner - Captured subprocess runner\n */\nexport async function lint(\n this: LocalContext,\n flags: LintCommandFlags,\n directory: string = DEFAULT_POLICY_PROJECT_DIRECTORY,\n runner: CapturedProcessRunner = runCapturedProcess,\n): Promise<void> {\n doneInputValidation(this.process);\n\n const { fix = false, noInteractive = false, json = false } = flags;\n const resolvedDir = resolvePolicyProjectDirectory(this.process.cwd(), directory);\n\n if (!this.fs.existsSync(resolvedDir) || !this.fs.statSync(resolvedDir).isDirectory()) {\n const missing: PolicyLintResult = {\n version: POLICY_LINT_RESULT_VERSION,\n status: 'failed',\n directory: resolvedDir,\n fix,\n tools: { opa: null, regal: null },\n checks: POLICY_LINT_CHECK_NAMES.map((name) => ({\n name,\n status: name === 'manifest' ? 'failed' : 'skipped',\n })),\n unformattedFiles: [],\n fixedFiles: [],\n diagnostics: [\n {\n code: 'project.directory',\n severity: 'error',\n message: `Policy directory does not exist or is not a directory: ${resolvedDir}`,\n path: path.relative(this.process.cwd(), resolvedDir),\n },\n ],\n };\n if (json) {\n this.process.stdout.write(`${JSON.stringify(missing)}\\n`);\n } else {\n renderResult(this, missing);\n }\n this.process.exitCode = 1;\n return;\n }\n\n const bundleDirectories = discoverPolicyBundleDirectories(this, resolvedDir);\n if (bundleDirectories.length === 0) {\n const empty: PolicyLintResult = {\n version: POLICY_LINT_RESULT_VERSION,\n status: 'failed',\n directory: resolvedDir,\n fix,\n tools: { opa: null, regal: null },\n checks: POLICY_LINT_CHECK_NAMES.map((name) => ({\n name,\n status: name === 'manifest' ? 'failed' : 'skipped',\n })),\n unformattedFiles: [],\n fixedFiles: [],\n diagnostics: [\n {\n code: 'project.bundles',\n severity: 'error',\n message:\n 'No publishable policy bundles found. Add one with `transcend policy new`, ' +\n 'or pass a directory that contains a `.manifest`.',\n path: path.relative(this.process.cwd(), resolvedDir) || '.',\n },\n ],\n };\n if (json) {\n this.process.stdout.write(`${JSON.stringify(empty)}\\n`);\n } else {\n renderResult(this, empty);\n }\n this.process.exitCode = 1;\n return;\n }\n\n const results: PolicyLintResult[] = [];\n for (const bundleDirectory of bundleDirectories) {\n results.push(\n await lintBundle.call(this, { fix, noInteractive, json }, bundleDirectory, runner),\n );\n }\n\n const failed = results.some((result) => result.status === 'failed');\n if (json) {\n if (results.length === 1) {\n this.process.stdout.write(`${JSON.stringify(results[0])}\\n`);\n } else {\n const multi: PolicyLintMultiResult = {\n version: POLICY_LINT_MULTI_RESULT_VERSION,\n status: failed ? 'failed' : 'passed',\n directory: resolvedDir,\n fix,\n results,\n };\n this.process.stdout.write(`${JSON.stringify(multi)}\\n`);\n }\n } else if (results.length === 1) {\n renderResult(this, results[0]!);\n } else {\n results.forEach((result, index) => {\n if (index > 0) {\n this.logger.info('');\n }\n const relative = path.relative(this.process.cwd(), result.directory) || result.directory;\n renderResult(this, result, `Policy verification — ${relative}`);\n });\n }\n\n if (failed) {\n this.process.exitCode = 1;\n }\n}\n"],"mappings":"2cAyBA,MAAa,EAAqD,CAChE,WACA,cACA,gBACA,SACA,YACA,aACA,WACD,CAGY,EAA8E,CACzF,SAAU,6BACV,cAAe,UACf,gBAAiB,QACjB,OAAQ,iBACR,YAAa,mBACb,aA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.ts","../src/commands/policy/lint/impl.ts"],"sourcesContent":["/** Stable policy lint result schema version. */\nexport const POLICY_LINT_RESULT_VERSION = 1;\n\n/** Stable multi-bundle lint result schema version. */\nexport const POLICY_LINT_MULTI_RESULT_VERSION = 2;\n\n/** Status of the full gate or an individual verification. */\nexport type PolicyLintStatus = 'passed' | 'failed' | 'skipped';\n\n/** One named policy verification. */\nexport interface PolicyLintCheck {\n /** Stable verification name. */\n name:\n | 'manifest'\n | 'opa-version'\n | 'regal-version'\n | 'format'\n | 'opa-check'\n | 'regal-lint'\n | 'opa-test';\n /** Verification outcome. */\n status: PolicyLintStatus;\n}\n\n/** Stable verification execution order. */\nexport const POLICY_LINT_CHECK_NAMES: PolicyLintCheck['name'][] = [\n 'manifest',\n 'opa-version',\n 'regal-version',\n 'format',\n 'opa-check',\n 'regal-lint',\n 'opa-test',\n];\n\n/** User-facing verification labels. */\nexport const POLICY_LINT_CHECK_LABELS: Readonly<Record<PolicyLintCheck['name'], string>> = {\n manifest: 'Manifest and package roots',\n 'opa-version': 'OPA 1.x',\n 'regal-version': 'Regal',\n format: 'OPA formatting',\n 'opa-check': 'OPA strict check',\n 'regal-lint': 'Regal lint',\n 'opa-test': 'OPA tests',\n};\n\n/** One machine-readable policy lint diagnostic. */\nexport interface PolicyLintDiagnostic {\n /** Stable diagnostic identifier. */\n code: string;\n /** Diagnostic severity. */\n severity: 'error';\n /** Human-readable detail, including captured tool output when available. */\n message: string;\n /** Optional path relative to the invocation directory. */\n path?: string;\n}\n\n/** Detected local policy tool versions. */\nexport interface PolicyLintTools {\n /** Detected OPA version, or null when missing or unsupported. */\n opa: string | null;\n /** Detected Regal version, or null when missing or unsupported. */\n regal: string | null;\n}\n\n/** Stable result emitted by `transcend policy lint --json` for one bundle. */\nexport interface PolicyLintResult {\n /** Result schema version. */\n version: typeof POLICY_LINT_RESULT_VERSION;\n /** Overall verification outcome. */\n status: Exclude<PolicyLintStatus, 'skipped'>;\n /** Absolute policy bundle directory. */\n directory: string;\n /** Whether formatting repair was explicitly requested. */\n fix: boolean;\n /** Detected supported tool versions. */\n tools: PolicyLintTools;\n /** Verification outcomes in stable execution order. */\n checks: PolicyLintCheck[];\n /** Files found to need OPA formatting, relative to the policy directory. */\n unformattedFiles: string[];\n /** Files repaired with OPA formatting, relative to the policy directory. */\n fixedFiles: string[];\n /** Ordered verification diagnostics. */\n diagnostics: PolicyLintDiagnostic[];\n}\n\n/**\n * Stable result when `transcend policy lint --json` verifies multiple bundles.\n *\n * Emitted only when the selected path is a workspace with more than one\n * publishable `*-bundle/` directory.\n */\nexport interface PolicyLintMultiResult {\n /** Result schema version. */\n version: typeof POLICY_LINT_MULTI_RESULT_VERSION;\n /** Overall verification outcome across all bundles. */\n status: Exclude<PolicyLintStatus, 'skipped'>;\n /** Absolute policy workspace directory that was searched. */\n directory: string;\n /** Whether formatting repair was explicitly requested. */\n fix: boolean;\n /** Per-bundle results in discovery order. */\n results: PolicyLintResult[];\n}\n","import path from 'node:path';\n\nimport type { CapturedProcessResult } from '../cli/run-captured-process.js';\n\n/**\n * Use captured tool output as a concise diagnostic.\n *\n * @param result - Captured process result\n * @param fallback - Message used when the tool emitted no output\n * @returns Diagnostic message\n */\nexport function getPolicyProcessFailureMessage(\n result: CapturedProcessResult,\n fallback: string,\n): string {\n const output = [result.stdout.trim(), result.stderr.trim()].filter(Boolean).join('\\n');\n return output || fallback;\n}\n\n/**\n * Convert absolute OPA formatter paths to stable project-relative paths.\n *\n * @param stdout - `opa fmt --list` output\n * @param projectDirectory - Absolute policy directory\n * @returns Sorted unique paths\n */\nexport function parseUnformattedPolicyFiles(stdout: string, projectDirectory: string): string[] {\n return [\n ...new Set(\n stdout\n .split(/\\r?\\n/gu)\n .map((file) => file.trim())\n .filter(Boolean)\n .map((file) =>\n path.isAbsolute(file)\n ? path.relative(projectDirectory, file).split(path.sep).join('/')\n : file.split(path.sep).join('/'),\n ),\n ),\n ].sort();\n}\n","import path from 'node:path';\n\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport {\n runCapturedProcess,\n type CapturedProcessRunner,\n} from '../../../lib/cli/run-captured-process.js';\nimport { inquirerConfirmBoolean } from '../../../lib/helpers/inquirer.js';\nimport {\n type PolicyBundleRegoFile,\n validatePolicyBundleContents,\n} from '../../../lib/policy/policy-bundle-manifest.js';\nimport {\n type PolicyLintCheck,\n type PolicyLintDiagnostic,\n type PolicyLintMultiResult,\n type PolicyLintResult,\n POLICY_LINT_CHECK_LABELS,\n POLICY_LINT_CHECK_NAMES,\n POLICY_LINT_MULTI_RESULT_VERSION,\n POLICY_LINT_RESULT_VERSION,\n} from '../../../lib/policy/policy-lint-model.js';\nimport {\n getPolicyProcessFailureMessage,\n parseUnformattedPolicyFiles,\n} from '../../../lib/policy/policy-lint-output.js';\nimport {\n DEFAULT_POLICY_PROJECT_DIRECTORY,\n discoverPolicyBundleDirectories,\n resolvePolicyProjectDirectory,\n} from '../../../lib/policy/policy-project-discovery.js';\nimport {\n OPA_MISSING_MESSAGE,\n parsePolicyToolVersion,\n REGAL_MISSING_MESSAGE,\n unsupportedOpaVersionMessage,\n unsupportedRegalVersionMessage,\n} from '../../../lib/policy/policy-runtime.js';\nimport { POLICY_MANIFEST_FILENAME } from '../../../lib/policy/policy-scaffold-templates.js';\nimport { isInteractivePromptInvocation } from '../../../lib/scaffolding/prompts.js';\n\n/** CLI flags for `transcend policy lint`. */\nexport interface LintCommandFlags {\n /** Apply OPA formatting. */\n fix: boolean;\n /** Disable the optional formatting confirmation. */\n noInteractive: boolean;\n /** Emit one stable JSON result on stdout. */\n json: boolean;\n}\n\n/**\n * Collect Rego source snapshots without following symlinks.\n *\n * @param context - CLI context\n * @param projectDirectory - Absolute policy directory\n * @param currentDirectory - Current recursive directory\n * @returns Deterministically ordered Rego snapshots\n */\nfunction collectRegoFiles(\n context: LocalContext,\n projectDirectory: string,\n currentDirectory: string = projectDirectory,\n): PolicyBundleRegoFile[] {\n return context.fs\n .readdirSync(currentDirectory, { withFileTypes: true })\n .sort((left, right) => left.name.localeCompare(right.name))\n .flatMap((entry) => {\n const absolutePath = path.join(currentDirectory, entry.name);\n if (entry.isDirectory()) {\n return collectRegoFiles(context, projectDirectory, absolutePath);\n }\n if (!entry.isFile() || !entry.name.endsWith('.rego')) {\n return [];\n }\n return [\n {\n path: path.relative(projectDirectory, absolutePath).split(path.sep).join('/'),\n contents: context.fs.readFileSync(absolutePath, 'utf8'),\n },\n ];\n });\n}\n\n/**\n * Resolve a Regal config file for a bundle, walking up to the workspace.\n *\n * @param context - CLI context\n * @param bundleDirectory - Absolute bundle directory\n * @returns Absolute config path, or undefined when none is found\n */\nfunction resolveRegalConfigFile(\n context: LocalContext,\n bundleDirectory: string,\n): string | undefined {\n let current = bundleDirectory;\n for (;;) {\n const nestedRegalConfig = path.join(current, '.regal', 'config.yaml');\n if (context.fs.existsSync(nestedRegalConfig)) {\n return nestedRegalConfig;\n }\n const rootRegalConfig = path.join(current, '.regal.yaml');\n if (context.fs.existsSync(rootRegalConfig)) {\n return rootRegalConfig;\n }\n const parent = path.dirname(current);\n if (parent === current) {\n return undefined;\n }\n current = parent;\n }\n}\n\n/**\n * Render the terminal summary for a policy verification result.\n *\n * @param context - CLI context\n * @param result - Completed verification result\n * @param heading - Optional section heading when linting multiple bundles\n */\nfunction renderResult(context: LocalContext, result: PolicyLintResult, heading?: string): void {\n if (heading) {\n context.logger.info(`${colors.bold(heading)}\\n`);\n } else {\n context.logger.info(`${colors.bold('Policy verification')}\\n`);\n }\n result.checks.forEach(({ name, status }) => {\n const label = status === 'passed' ? 'PASS' : status === 'failed' ? 'FAIL' : 'SKIP';\n const styledLabel =\n status === 'passed'\n ? colors.green(label)\n : status === 'failed'\n ? colors.red(label)\n : colors.yellow(label);\n const version =\n name === 'opa-version' && result.tools.opa\n ? ` (${result.tools.opa})`\n : name === 'regal-version' && result.tools.regal\n ? ` (${result.tools.regal})`\n : '';\n context.logger.info(`${styledLabel} ${POLICY_LINT_CHECK_LABELS[name]}${version}`);\n });\n if (result.diagnostics.length > 0) {\n context.logger.error('');\n }\n result.diagnostics.forEach((diagnostic) => {\n const location = diagnostic.path ? `${diagnostic.path}: ` : '';\n context.logger.error(\n colors.red(`error [${diagnostic.code}]: ${location}${diagnostic.message}`),\n );\n });\n if (result.status === 'passed') {\n context.logger.info('');\n context.logger.info(colors.green('Policy verification passed.'));\n } else {\n context.logger.error('');\n context.logger.error(colors.red('Policy verification failed.'));\n }\n}\n\n/**\n * Verify one publishable policy bundle directory.\n *\n * @param context - CLI context\n * @param flags - Command flags\n * @param resolvedDir - Absolute bundle directory\n * @param runner - Captured subprocess runner\n * @returns Completed verification result\n */\nasync function lintBundle(\n this: LocalContext,\n { fix, noInteractive, json }: LintCommandFlags,\n resolvedDir: string,\n runner: CapturedProcessRunner,\n): Promise<PolicyLintResult> {\n const checks: PolicyLintCheck[] = POLICY_LINT_CHECK_NAMES.map((name) => ({\n name,\n status: 'skipped',\n }));\n const diagnostics: PolicyLintDiagnostic[] = [];\n const result: PolicyLintResult = {\n version: POLICY_LINT_RESULT_VERSION,\n status: 'passed',\n directory: resolvedDir,\n fix,\n tools: { opa: null, regal: null },\n checks,\n unformattedFiles: [],\n fixedFiles: [],\n diagnostics,\n };\n const setStatus = (name: PolicyLintCheck['name'], status: PolicyLintCheck['status']): void => {\n checks.find((check) => check.name === name)!.status = status;\n };\n const addError = (code: string, message: string, diagnosticPath?: string): void => {\n diagnostics.push({\n code,\n severity: 'error',\n message,\n ...(diagnosticPath ? { path: diagnosticPath } : {}),\n });\n };\n\n if (!this.fs.existsSync(resolvedDir) || !this.fs.statSync(resolvedDir).isDirectory()) {\n setStatus('manifest', 'failed');\n addError(\n 'project.directory',\n `Policy directory does not exist or is not a directory: ${resolvedDir}`,\n path.relative(this.process.cwd(), resolvedDir),\n );\n result.status = 'failed';\n return result;\n }\n\n const manifestPath = path.join(resolvedDir, POLICY_MANIFEST_FILENAME);\n try {\n validatePolicyBundleContents(\n this.fs.existsSync(manifestPath) ? this.fs.readFileSync(manifestPath, 'utf8') : undefined,\n collectRegoFiles(this, resolvedDir),\n );\n setStatus('manifest', 'passed');\n } catch (error) {\n setStatus('manifest', 'failed');\n addError(\n 'manifest.invalid',\n error instanceof Error ? error.message : String(error),\n path.relative(this.process.cwd(), manifestPath),\n );\n }\n\n const opaVersionResult = await runner('opa', ['version'], { cwd: resolvedDir }, this);\n if (opaVersionResult.error?.code === 'ENOENT') {\n setStatus('opa-version', 'failed');\n addError('opa.missing', OPA_MISSING_MESSAGE);\n } else {\n const opaVersionOutput = `${opaVersionResult.stdout}\\n${opaVersionResult.stderr}`;\n const unsupportedOpa = unsupportedOpaVersionMessage(opaVersionOutput);\n if (opaVersionResult.code !== 0 || unsupportedOpa) {\n setStatus('opa-version', 'failed');\n addError(\n 'opa.version',\n unsupportedOpa ??\n getPolicyProcessFailureMessage(\n opaVersionResult,\n 'Unable to determine the installed OPA version.',\n ),\n );\n } else {\n result.tools.opa = parsePolicyToolVersion(opaVersionOutput)!.version;\n setStatus('opa-version', 'passed');\n }\n }\n\n const regalVersionResult = await runner('regal', ['version'], { cwd: resolvedDir }, this);\n if (regalVersionResult.error?.code === 'ENOENT') {\n setStatus('regal-version', 'failed');\n addError('regal.missing', REGAL_MISSING_MESSAGE);\n } else {\n const regalVersionOutput = `${regalVersionResult.stdout}\\n${regalVersionResult.stderr}`;\n const unsupportedRegal = unsupportedRegalVersionMessage(regalVersionOutput);\n if (regalVersionResult.code !== 0 || unsupportedRegal) {\n setStatus('regal-version', 'failed');\n addError(\n 'regal.version',\n unsupportedRegal ??\n getPolicyProcessFailureMessage(\n regalVersionResult,\n 'Unable to determine the installed Regal version.',\n ),\n );\n } else {\n result.tools.regal = parsePolicyToolVersion(regalVersionOutput)!.version;\n setStatus('regal-version', 'passed');\n }\n }\n\n if (result.tools.opa) {\n const formatResult = await runner(\n 'opa',\n ['fmt', '--list', resolvedDir],\n { cwd: resolvedDir },\n this,\n );\n if (formatResult.code !== 0) {\n setStatus('format', 'failed');\n addError(\n 'opa.format',\n getPolicyProcessFailureMessage(\n formatResult,\n `opa fmt --list failed with exit code ${formatResult.code}`,\n ),\n );\n } else {\n result.unformattedFiles = parseUnformattedPolicyFiles(formatResult.stdout, resolvedDir);\n if (result.unformattedFiles.length === 0) {\n setStatus('format', 'passed');\n } else {\n let shouldFormat = fix;\n const interactive = isInteractivePromptInvocation(\n { json, noInteractive },\n this.process.stdin.isTTY,\n this.process.stderr.isTTY,\n );\n if (!json && !fix) {\n this.logger.error(colors.red('Policy files are not formatted:'));\n result.unformattedFiles.forEach((file) => {\n this.logger.error(colors.red(` - ${file}`));\n });\n const diffResult = await runner(\n 'opa',\n ['fmt', '--diff', resolvedDir],\n { cwd: resolvedDir },\n this,\n );\n const diff = diffResult.stdout.trim() || diffResult.stderr.trim();\n if (diff) {\n this.logger.error('');\n this.logger.error(diff);\n }\n }\n if (!fix && interactive) {\n try {\n shouldFormat = await inquirerConfirmBoolean({\n message: 'Format the unformatted policy files listed above?',\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (/force closed|prompt.*cancel|user.*close|SIGINT/iu.test(message)) {\n this.process.exit(130);\n }\n throw error;\n }\n }\n if (shouldFormat) {\n const writeResult = await runner(\n 'opa',\n ['fmt', '--write', resolvedDir],\n { cwd: resolvedDir },\n this,\n );\n if (writeResult.code === 0) {\n result.fixedFiles = [...result.unformattedFiles];\n setStatus('format', 'passed');\n } else {\n setStatus('format', 'failed');\n addError(\n 'opa.format-fix',\n getPolicyProcessFailureMessage(\n writeResult,\n `opa fmt --write failed with exit code ${writeResult.code}`,\n ),\n );\n }\n } else {\n setStatus('format', 'failed');\n addError(\n 'opa.format-required',\n 'Policy files are not formatted. Re-run `transcend policy lint --fix` to repair them.',\n );\n }\n }\n }\n\n const checkResult = await runner(\n 'opa',\n ['check', '--strict', '--ignore', '*_test.rego', resolvedDir],\n { cwd: resolvedDir },\n this,\n );\n if (checkResult.code === 0) {\n setStatus('opa-check', 'passed');\n } else {\n setStatus('opa-check', 'failed');\n addError(\n 'opa.check',\n getPolicyProcessFailureMessage(\n checkResult,\n `opa check failed with exit code ${checkResult.code}`,\n ),\n );\n }\n }\n\n if (result.tools.regal) {\n const regalConfig = resolveRegalConfigFile(this, resolvedDir);\n const regalResult = await runner(\n 'regal',\n [\n 'lint',\n '--fail-level',\n 'warning',\n ...(regalConfig ? ['--config-file', regalConfig] : []),\n resolvedDir,\n ],\n { cwd: resolvedDir },\n this,\n );\n if (regalResult.code === 0) {\n setStatus('regal-lint', 'passed');\n } else {\n setStatus('regal-lint', 'failed');\n addError(\n 'regal.lint',\n getPolicyProcessFailureMessage(\n regalResult,\n `regal lint failed with exit code ${regalResult.code}`,\n ),\n );\n }\n }\n\n if (result.tools.opa) {\n const testResult = await runner(\n 'opa',\n ['test', '--fail-on-empty', '-b', resolvedDir],\n { cwd: resolvedDir },\n this,\n );\n if (testResult.code === 0) {\n setStatus('opa-test', 'passed');\n } else {\n setStatus('opa-test', 'failed');\n addError(\n 'opa.test',\n getPolicyProcessFailureMessage(\n testResult,\n `opa test --fail-on-empty -b failed with exit code ${testResult.code}`,\n ),\n );\n }\n }\n\n result.status = checks.some(({ status }) => status === 'failed') ? 'failed' : 'passed';\n return result;\n}\n\n/**\n * Verify local policy bundles with the shared upload contract, OPA, and Regal.\n *\n * With no directory (or the default workspace path), discovers every immediate\n * child that contains a `.manifest` and verifies each. Pass one bundle path to\n * verify a single publishable unit.\n *\n * @param this - CLI context\n * @param flags - Command flags\n * @param directory - Policy workspace or bundle directory\n * @param runner - Captured subprocess runner\n */\nexport async function lint(\n this: LocalContext,\n flags: LintCommandFlags,\n directory: string = DEFAULT_POLICY_PROJECT_DIRECTORY,\n runner: CapturedProcessRunner = runCapturedProcess,\n): Promise<void> {\n doneInputValidation(this.process);\n\n const { fix = false, noInteractive = false, json = false } = flags;\n const resolvedDir = resolvePolicyProjectDirectory(this.process.cwd(), directory);\n\n if (!this.fs.existsSync(resolvedDir) || !this.fs.statSync(resolvedDir).isDirectory()) {\n const missing: PolicyLintResult = {\n version: POLICY_LINT_RESULT_VERSION,\n status: 'failed',\n directory: resolvedDir,\n fix,\n tools: { opa: null, regal: null },\n checks: POLICY_LINT_CHECK_NAMES.map((name) => ({\n name,\n status: name === 'manifest' ? 'failed' : 'skipped',\n })),\n unformattedFiles: [],\n fixedFiles: [],\n diagnostics: [\n {\n code: 'project.directory',\n severity: 'error',\n message: `Policy directory does not exist or is not a directory: ${resolvedDir}`,\n path: path.relative(this.process.cwd(), resolvedDir),\n },\n ],\n };\n if (json) {\n this.process.stdout.write(`${JSON.stringify(missing)}\\n`);\n } else {\n renderResult(this, missing);\n }\n this.process.exitCode = 1;\n return;\n }\n\n const bundleDirectories = discoverPolicyBundleDirectories(this, resolvedDir);\n if (bundleDirectories.length === 0) {\n const empty: PolicyLintResult = {\n version: POLICY_LINT_RESULT_VERSION,\n status: 'failed',\n directory: resolvedDir,\n fix,\n tools: { opa: null, regal: null },\n checks: POLICY_LINT_CHECK_NAMES.map((name) => ({\n name,\n status: name === 'manifest' ? 'failed' : 'skipped',\n })),\n unformattedFiles: [],\n fixedFiles: [],\n diagnostics: [\n {\n code: 'project.bundles',\n severity: 'error',\n message:\n 'No publishable policy bundles found. Add one with `transcend policy new`, ' +\n 'or pass a directory that contains a `.manifest`.',\n path: path.relative(this.process.cwd(), resolvedDir) || '.',\n },\n ],\n };\n if (json) {\n this.process.stdout.write(`${JSON.stringify(empty)}\\n`);\n } else {\n renderResult(this, empty);\n }\n this.process.exitCode = 1;\n return;\n }\n\n const results: PolicyLintResult[] = [];\n for (const bundleDirectory of bundleDirectories) {\n results.push(\n await lintBundle.call(this, { fix, noInteractive, json }, bundleDirectory, runner),\n );\n }\n\n const failed = results.some((result) => result.status === 'failed');\n if (json) {\n if (results.length === 1) {\n this.process.stdout.write(`${JSON.stringify(results[0])}\\n`);\n } else {\n const multi: PolicyLintMultiResult = {\n version: POLICY_LINT_MULTI_RESULT_VERSION,\n status: failed ? 'failed' : 'passed',\n directory: resolvedDir,\n fix,\n results,\n };\n this.process.stdout.write(`${JSON.stringify(multi)}\\n`);\n }\n } else if (results.length === 1) {\n renderResult(this, results[0]!);\n } else {\n results.forEach((result, index) => {\n if (index > 0) {\n this.logger.info('');\n }\n const relative = path.relative(this.process.cwd(), result.directory) || result.directory;\n renderResult(this, result, `Policy verification — ${relative}`);\n });\n }\n\n if (failed) {\n this.process.exitCode = 1;\n }\n}\n"],"mappings":"2cAyBA,MAAa,EAAqD,CAChE,WACA,cACA,gBACA,SACA,YACA,aACA,WACD,CAGY,EAA8E,CACzF,SAAU,6BACV,cAAe,UACf,gBAAiB,QACjB,OAAQ,iBACR,YAAa,mBACb,aAAc,aACd,WAAY,YACb,CCjCD,SAAgB,EACd,EACA,EACQ,CAER,MADe,CAAC,EAAO,OAAO,MAAM,CAAE,EAAO,OAAO,MAAM,CAAC,CAAC,OAAO,QAAQ,CAAC,KAAK;EACpE,EAAI,EAUnB,SAAgB,EAA4B,EAAgB,EAAoC,CAC9F,MAAO,CACL,GAAG,IAAI,IACL,EACG,MAAM,UAAU,CAChB,IAAK,GAAS,EAAK,MAAM,CAAC,CAC1B,OAAO,QAAQ,CACf,IAAK,GACJ,EAAK,WAAW,EAAK,CACjB,EAAK,SAAS,EAAkB,EAAK,CAAC,MAAM,EAAK,IAAI,CAAC,KAAK,IAAI,CAC/D,EAAK,MAAM,EAAK,IAAI,CAAC,KAAK,IAAI,CACnC,CACJ,CACF,CAAC,MAAM,CCuBV,SAAS,EACP,EACA,EACA,EAA2B,EACH,CACxB,OAAO,EAAQ,GACZ,YAAY,EAAkB,CAAE,cAAe,GAAM,CAAC,CACtD,MAAM,EAAM,IAAU,EAAK,KAAK,cAAc,EAAM,KAAK,CAAC,CAC1D,QAAS,GAAU,CAClB,IAAM,EAAe,EAAK,KAAK,EAAkB,EAAM,KAAK,CAO5D,OANI,EAAM,aAAa,CACd,EAAiB,EAAS,EAAkB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AAW,EACX,MACA,UACD,CACD,KAAK,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,EAAM,CAAC,IAAI,MAEhD,EAAQ,SAAW,EAC5B,EAAa,KAAM,EAAQ,GAAI,CAE/B,EAAQ,SAAS,EAAQ,IAAU,CAC7B,EAAQ,GACV,KAAK,OAAO,KAAK,GAAG,CAEtB,IAAM,EAAW,EAAK,SAAS,KAAK,QAAQ,KAAK,CAAE,EAAO,UAAU,EAAI,EAAO,UAC/E,EAAa,KAAM,EAAQ,yBAAyB,IAAW,EAC/D,CAGA,IACF,KAAK,QAAQ,SAAW"}
@@ -1,2 +1,2 @@
1
- import{l as e}from"./constants-BCmVqlrM.mjs";import{t}from"./generateCrossAccountApiKeys-CoSsZwSz.mjs";import{t as n}from"./done-input-validation-LiTaCEzF.mjs";async function r({email:r,password:i,apiKeyTitle:a,file:o,scopes:s,deleteExistingApiKey:c,createNewApiKey:l,parentOrganizationId:u,transcendUrl:d}){n(this.process);let{errors:f,apiKeys:p}=await t({transcendUrl:d,password:i,email:r,parentOrganizationId:u,deleteExistingApiKey:c,createNewApiKey:l,apiKeyTitle:a,scopes:s.map(t=>e[t].name)});this.fs.writeFileSync(o,`${JSON.stringify(p,null,2)}\n`),f.length>0&&this.process.exit(1)}export{r as generateApiKeys};
2
- //# sourceMappingURL=impl-BrdCuU0I.mjs.map
1
+ import{l as e}from"./constants-boymUaFC.mjs";import{t}from"./generateCrossAccountApiKeys-B_p8gQ2C.mjs";import{t as n}from"./done-input-validation-LiTaCEzF.mjs";async function r({email:r,password:i,apiKeyTitle:a,file:o,scopes:s,deleteExistingApiKey:c,createNewApiKey:l,parentOrganizationId:u,transcendUrl:d}){n(this.process);let{errors:f,apiKeys:p}=await t({transcendUrl:d,password:i,email:r,parentOrganizationId:u,deleteExistingApiKey:c,createNewApiKey:l,apiKeyTitle:a,scopes:s.map(t=>e[t].name)});this.fs.writeFileSync(o,`${JSON.stringify(p,null,2)}\n`),f.length>0&&this.process.exit(1)}export{r as generateApiKeys};
2
+ //# sourceMappingURL=impl-XztvsE6N.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-BrdCuU0I.mjs","names":[],"sources":["../src/commands/admin/generate-api-keys/impl.ts"],"sourcesContent":["import { ScopeName } from '@transcend-io/privacy-types';\n\nimport { SCOPES_BY_TITLE } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { generateCrossAccountApiKeys } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\n\n// Command flag interface\nexport interface GenerateApiKeysCommandFlags {\n email: string;\n password: string;\n apiKeyTitle: string;\n file: string;\n scopes: string[];\n deleteExistingApiKey: boolean;\n createNewApiKey: boolean;\n parentOrganizationId?: string;\n transcendUrl: string;\n}\n\n// Command implementation\nexport async function generateApiKeys(\n this: LocalContext,\n {\n email,\n password,\n apiKeyTitle,\n file,\n scopes,\n deleteExistingApiKey,\n createNewApiKey,\n parentOrganizationId,\n transcendUrl,\n }: GenerateApiKeysCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n const scopeNames = scopes.map((scopeTitle) => SCOPES_BY_TITLE[scopeTitle].name as ScopeName);\n\n // Upload privacy requests\n const { errors, apiKeys } = await generateCrossAccountApiKeys({\n transcendUrl,\n password,\n email,\n parentOrganizationId,\n deleteExistingApiKey,\n createNewApiKey,\n apiKeyTitle,\n scopes: scopeNames,\n });\n\n // Write to disk\n this.fs.writeFileSync(file, `${JSON.stringify(apiKeys, null, 2)}\\n`);\n if (errors.length > 0) {\n this.process.exit(1);\n }\n}\n"],"mappings":"gKAqBA,eAAsB,EAEpB,CACE,QACA,WACA,cACA,OACA,SACA,uBACA,kBACA,uBACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,CAKjC,GAAM,CAAE,SAAQ,WAAY,MAAM,EAA4B,CAC5D,eACA,WACA,QACA,uBACA,uBACA,kBACA,cACA,OAXiB,EAAO,IAAK,GAAe,EAAgB,GAAY,KAWtD,CACnB,CAAC,CAGF,KAAK,GAAG,cAAc,EAAM,GAAG,KAAK,UAAU,EAAS,KAAM,EAAE,CAAC,IAAI,CAChE,EAAO,OAAS,GAClB,KAAK,QAAQ,KAAK,EAAE"}
1
+ {"version":3,"file":"impl-XztvsE6N.mjs","names":[],"sources":["../src/commands/admin/generate-api-keys/impl.ts"],"sourcesContent":["import { ScopeName } from '@transcend-io/privacy-types';\n\nimport { SCOPES_BY_TITLE } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { generateCrossAccountApiKeys } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\n\n// Command flag interface\nexport interface GenerateApiKeysCommandFlags {\n email: string;\n password: string;\n apiKeyTitle: string;\n file: string;\n scopes: string[];\n deleteExistingApiKey: boolean;\n createNewApiKey: boolean;\n parentOrganizationId?: string;\n transcendUrl: string;\n}\n\n// Command implementation\nexport async function generateApiKeys(\n this: LocalContext,\n {\n email,\n password,\n apiKeyTitle,\n file,\n scopes,\n deleteExistingApiKey,\n createNewApiKey,\n parentOrganizationId,\n transcendUrl,\n }: GenerateApiKeysCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n const scopeNames = scopes.map((scopeTitle) => SCOPES_BY_TITLE[scopeTitle].name as ScopeName);\n\n // Upload privacy requests\n const { errors, apiKeys } = await generateCrossAccountApiKeys({\n transcendUrl,\n password,\n email,\n parentOrganizationId,\n deleteExistingApiKey,\n createNewApiKey,\n apiKeyTitle,\n scopes: scopeNames,\n });\n\n // Write to disk\n this.fs.writeFileSync(file, `${JSON.stringify(apiKeys, null, 2)}\\n`);\n if (errors.length > 0) {\n this.process.exit(1);\n }\n}\n"],"mappings":"gKAqBA,eAAsB,EAEpB,CACE,QACA,WACA,cACA,OACA,SACA,uBACA,kBACA,uBACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,CAKjC,GAAM,CAAE,SAAQ,WAAY,MAAM,EAA4B,CAC5D,eACA,WACA,QACA,uBACA,uBACA,kBACA,cACA,OAXiB,EAAO,IAAK,GAAe,EAAgB,GAAY,KAWtD,CACnB,CAAC,CAGF,KAAK,GAAG,cAAc,EAAM,GAAG,KAAK,UAAU,EAAS,KAAM,EAAE,CAAC,IAAI,CAChE,EAAO,OAAS,GAClB,KAAK,QAAQ,KAAK,EAAE"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./constants-BCmVqlrM.mjs";import{s as t}from"./writeCsv-CNZrq3zU.mjs";import{t as n}from"./pullAllDatapoints-CNqQSSmF.mjs";import{t as r}from"./done-input-validation-LiTaCEzF.mjs";import{groupBy as i,uniq as a}from"lodash-es";import o from"colors";import{buildTranscendGraphQLClient as s}from"@transcend-io/sdk";async function c({auth:c,file:l,transcendUrl:u,dataSiloIds:d,includeAttributes:f,includeGuessedCategories:p,parentCategories:m,subCategories:h=[]}){r(this.process);try{let e=await n(s(u,c),{dataSiloIds:d,includeGuessedCategories:p,parentCategories:m,includeAttributes:f,subCategories:h});this.logger.info(o.magenta(`Writing datapoints to file "${l}"...`));let r=[];await t(l,e.map(e=>{let t={"Property ID":e.id,"Data Silo":e.dataSilo.title,Object:e.dataPoint.name,"Object Path":e.dataPoint.path.join(`.`),Property:e.name,"Property Description":e.description,"Data Categories":e.categories.map(e=>`${e.category}:${e.name}`).join(`, `),"Guessed Category":e.pendingCategoryGuesses?.[0]?`${e.pendingCategoryGuesses[0].category.category}:${e.pendingCategoryGuesses[0].category.name}`:``,"Processing Purposes":e.purposes.map(e=>`${e.purpose}:${e.name}`).join(`, `),...Object.entries(i(e.attributeValues||[],({attributeKey:e})=>e.name)).reduce((e,[t,n])=>(e[t]=n.map(e=>e.name).join(`,`),e),{})};return r=a([...r,...Object.keys(t)]),t}),r)}catch(e){this.logger.error(o.red(`An error occurred syncing the datapoints: ${e.message}`)),this.process.exit(1)}this.logger.info(o.green(`Successfully synced datapoints to disk at ${l}! View at ${e}`))}export{c as pullDatapoints};
2
- //# sourceMappingURL=impl-C54oUOeM2.mjs.map
1
+ import{n as e}from"./constants-boymUaFC.mjs";import{s as t}from"./writeCsv-CNZrq3zU.mjs";import{t as n}from"./pullAllDatapoints-CNqQSSmF.mjs";import{t as r}from"./done-input-validation-LiTaCEzF.mjs";import{groupBy as i,uniq as a}from"lodash-es";import o from"colors";import{buildTranscendGraphQLClient as s}from"@transcend-io/sdk";async function c({auth:c,file:l,transcendUrl:u,dataSiloIds:d,includeAttributes:f,includeGuessedCategories:p,parentCategories:m,subCategories:h=[]}){r(this.process);try{let e=await n(s(u,c),{dataSiloIds:d,includeGuessedCategories:p,parentCategories:m,includeAttributes:f,subCategories:h});this.logger.info(o.magenta(`Writing datapoints to file "${l}"...`));let r=[];await t(l,e.map(e=>{let t={"Property ID":e.id,"Data Silo":e.dataSilo.title,Object:e.dataPoint.name,"Object Path":e.dataPoint.path.join(`.`),Property:e.name,"Property Description":e.description,"Data Categories":e.categories.map(e=>`${e.category}:${e.name}`).join(`, `),"Guessed Category":e.pendingCategoryGuesses?.[0]?`${e.pendingCategoryGuesses[0].category.category}:${e.pendingCategoryGuesses[0].category.name}`:``,"Processing Purposes":e.purposes.map(e=>`${e.purpose}:${e.name}`).join(`, `),...Object.entries(i(e.attributeValues||[],({attributeKey:e})=>e.name)).reduce((e,[t,n])=>(e[t]=n.map(e=>e.name).join(`,`),e),{})};return r=a([...r,...Object.keys(t)]),t}),r)}catch(e){this.logger.error(o.red(`An error occurred syncing the datapoints: ${e.message}`)),this.process.exit(1)}this.logger.info(o.green(`Successfully synced datapoints to disk at ${l}! View at ${e}`))}export{c as pullDatapoints};
2
+ //# sourceMappingURL=impl-qTeP2Voo2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-C54oUOeM2.mjs","names":[],"sources":["../src/commands/inventory/pull-datapoints/impl.ts"],"sourcesContent":["import { DataCategoryType } from '@transcend-io/privacy-types';\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport { uniq, groupBy } from 'lodash-es';\n\nimport { ADMIN_DASH_DATAPOINTS } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { pullAllDatapoints } from '../../../lib/data-inventory/index.js';\nimport { writeLargeCsv } from '../../../lib/helpers/index.js';\n\nexport interface PullDatapointsCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n dataSiloIds?: string[];\n includeAttributes: boolean;\n includeGuessedCategories: boolean;\n parentCategories?: DataCategoryType[];\n subCategories?: string[];\n}\n\nexport async function pullDatapoints(\n this: LocalContext,\n {\n auth,\n file,\n transcendUrl,\n dataSiloIds,\n includeAttributes,\n includeGuessedCategories,\n parentCategories,\n subCategories = [],\n }: PullDatapointsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n try {\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const dataPoints = await pullAllDatapoints(client, {\n dataSiloIds,\n includeGuessedCategories,\n parentCategories,\n includeAttributes,\n subCategories, // TODO: https://transcend.height.app/T-40482 - do by name not ID\n });\n\n this.logger.info(colors.magenta(`Writing datapoints to file \"${file}\"...`));\n let headers: string[] = [];\n const inputs = dataPoints.map((point) => {\n const result = {\n 'Property ID': point.id,\n 'Data Silo': point.dataSilo.title,\n Object: point.dataPoint.name,\n 'Object Path': point.dataPoint.path.join('.'),\n Property: point.name,\n 'Property Description': point.description,\n 'Data Categories': point.categories\n .map((category) => `${category.category}:${category.name}`)\n .join(', '),\n 'Guessed Category': point.pendingCategoryGuesses?.[0]\n ? `${point.pendingCategoryGuesses![0]!.category.category}:${\n point.pendingCategoryGuesses![0]!.category.name\n }`\n : '',\n 'Processing Purposes': point.purposes\n .map((purpose) => `${purpose.purpose}:${purpose.name}`)\n .join(', '),\n ...Object.entries(\n groupBy(point.attributeValues || [], ({ attributeKey }) => attributeKey.name),\n ).reduce(\n (acc, [key, values]) => {\n acc[key] = values.map((value) => value.name).join(',');\n return acc;\n },\n {} as Record<string, string>,\n ),\n };\n headers = uniq([...headers, ...Object.keys(result)]);\n return result;\n });\n await writeLargeCsv(file, inputs, headers);\n } catch (err) {\n this.logger.error(colors.red(`An error occurred syncing the datapoints: ${err.message}`));\n this.process.exit(1);\n }\n\n // Indicate success\n this.logger.info(\n colors.green(\n `Successfully synced datapoints to disk at ${file}! View at ${ADMIN_DASH_DATAPOINTS}`,\n ),\n );\n}\n"],"mappings":"2UAsBA,eAAsB,EAEpB,CACE,OACA,OACA,eACA,cACA,oBACA,2BACA,mBACA,gBAAgB,EAAE,EAEL,CACf,EAAoB,KAAK,QAAQ,CAEjC,GAAI,CAIF,IAAM,EAAa,MAAM,EAFV,EAA4B,EAAc,EAER,CAAE,CACjD,cACA,2BACA,mBACA,oBACA,gBACD,CAAC,CAEF,KAAK,OAAO,KAAK,EAAO,QAAQ,+BAA+B,EAAK,MAAM,CAAC,CAC3E,IAAI,EAAoB,EAAE,CAiC1B,MAAM,EAAc,EAhCL,EAAW,IAAK,GAAU,CACvC,IAAM,EAAS,CACb,cAAe,EAAM,GACrB,YAAa,EAAM,SAAS,MAC5B,OAAQ,EAAM,UAAU,KACxB,cAAe,EAAM,UAAU,KAAK,KAAK,IAAI,CAC7C,SAAU,EAAM,KAChB,uBAAwB,EAAM,YAC9B,kBAAmB,EAAM,WACtB,IAAK,GAAa,GAAG,EAAS,SAAS,GAAG,EAAS,OAAO,CAC1D,KAAK,KAAK,CACb,mBAAoB,EAAM,yBAAyB,GAC/C,GAAG,EAAM,uBAAwB,GAAI,SAAS,SAAS,GACrD,EAAM,uBAAwB,GAAI,SAAS,OAE7C,GACJ,sBAAuB,EAAM,SAC1B,IAAK,GAAY,GAAG,EAAQ,QAAQ,GAAG,EAAQ,OAAO,CACtD,KAAK,KAAK,CACb,GAAG,OAAO,QACR,EAAQ,EAAM,iBAAmB,EAAE,EAAG,CAAE,kBAAmB,EAAa,KAAK,CAC9E,CAAC,QACC,EAAK,CAAC,EAAK,MACV,EAAI,GAAO,EAAO,IAAK,GAAU,EAAM,KAAK,CAAC,KAAK,IAAI,CAC/C,GAET,EAAE,CACH,CACF,CAED,MADA,GAAU,EAAK,CAAC,GAAG,EAAS,GAAG,OAAO,KAAK,EAAO,CAAC,CAAC,CAC7C,GAEuB,CAAE,EAAQ,OACnC,EAAK,CACZ,KAAK,OAAO,MAAM,EAAO,IAAI,6CAA6C,EAAI,UAAU,CAAC,CACzF,KAAK,QAAQ,KAAK,EAAE,CAItB,KAAK,OAAO,KACV,EAAO,MACL,6CAA6C,EAAK,YAAY,IAC/D,CACF"}
1
+ {"version":3,"file":"impl-qTeP2Voo2.mjs","names":[],"sources":["../src/commands/inventory/pull-datapoints/impl.ts"],"sourcesContent":["import { DataCategoryType } from '@transcend-io/privacy-types';\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport { uniq, groupBy } from 'lodash-es';\n\nimport { ADMIN_DASH_DATAPOINTS } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { pullAllDatapoints } from '../../../lib/data-inventory/index.js';\nimport { writeLargeCsv } from '../../../lib/helpers/index.js';\n\nexport interface PullDatapointsCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n dataSiloIds?: string[];\n includeAttributes: boolean;\n includeGuessedCategories: boolean;\n parentCategories?: DataCategoryType[];\n subCategories?: string[];\n}\n\nexport async function pullDatapoints(\n this: LocalContext,\n {\n auth,\n file,\n transcendUrl,\n dataSiloIds,\n includeAttributes,\n includeGuessedCategories,\n parentCategories,\n subCategories = [],\n }: PullDatapointsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n try {\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const dataPoints = await pullAllDatapoints(client, {\n dataSiloIds,\n includeGuessedCategories,\n parentCategories,\n includeAttributes,\n subCategories, // TODO: https://transcend.height.app/T-40482 - do by name not ID\n });\n\n this.logger.info(colors.magenta(`Writing datapoints to file \"${file}\"...`));\n let headers: string[] = [];\n const inputs = dataPoints.map((point) => {\n const result = {\n 'Property ID': point.id,\n 'Data Silo': point.dataSilo.title,\n Object: point.dataPoint.name,\n 'Object Path': point.dataPoint.path.join('.'),\n Property: point.name,\n 'Property Description': point.description,\n 'Data Categories': point.categories\n .map((category) => `${category.category}:${category.name}`)\n .join(', '),\n 'Guessed Category': point.pendingCategoryGuesses?.[0]\n ? `${point.pendingCategoryGuesses![0]!.category.category}:${\n point.pendingCategoryGuesses![0]!.category.name\n }`\n : '',\n 'Processing Purposes': point.purposes\n .map((purpose) => `${purpose.purpose}:${purpose.name}`)\n .join(', '),\n ...Object.entries(\n groupBy(point.attributeValues || [], ({ attributeKey }) => attributeKey.name),\n ).reduce(\n (acc, [key, values]) => {\n acc[key] = values.map((value) => value.name).join(',');\n return acc;\n },\n {} as Record<string, string>,\n ),\n };\n headers = uniq([...headers, ...Object.keys(result)]);\n return result;\n });\n await writeLargeCsv(file, inputs, headers);\n } catch (err) {\n this.logger.error(colors.red(`An error occurred syncing the datapoints: ${err.message}`));\n this.process.exit(1);\n }\n\n // Indicate success\n this.logger.info(\n colors.green(\n `Successfully synced datapoints to disk at ${file}! View at ${ADMIN_DASH_DATAPOINTS}`,\n ),\n );\n}\n"],"mappings":"2UAsBA,eAAsB,EAEpB,CACE,OACA,OACA,eACA,cACA,oBACA,2BACA,mBACA,gBAAgB,EAAE,EAEL,CACf,EAAoB,KAAK,QAAQ,CAEjC,GAAI,CAIF,IAAM,EAAa,MAAM,EAFV,EAA4B,EAAc,EAER,CAAE,CACjD,cACA,2BACA,mBACA,oBACA,gBACD,CAAC,CAEF,KAAK,OAAO,KAAK,EAAO,QAAQ,+BAA+B,EAAK,MAAM,CAAC,CAC3E,IAAI,EAAoB,EAAE,CAiC1B,MAAM,EAAc,EAhCL,EAAW,IAAK,GAAU,CACvC,IAAM,EAAS,CACb,cAAe,EAAM,GACrB,YAAa,EAAM,SAAS,MAC5B,OAAQ,EAAM,UAAU,KACxB,cAAe,EAAM,UAAU,KAAK,KAAK,IAAI,CAC7C,SAAU,EAAM,KAChB,uBAAwB,EAAM,YAC9B,kBAAmB,EAAM,WACtB,IAAK,GAAa,GAAG,EAAS,SAAS,GAAG,EAAS,OAAO,CAC1D,KAAK,KAAK,CACb,mBAAoB,EAAM,yBAAyB,GAC/C,GAAG,EAAM,uBAAwB,GAAI,SAAS,SAAS,GACrD,EAAM,uBAAwB,GAAI,SAAS,OAE7C,GACJ,sBAAuB,EAAM,SAC1B,IAAK,GAAY,GAAG,EAAQ,QAAQ,GAAG,EAAQ,OAAO,CACtD,KAAK,KAAK,CACb,GAAG,OAAO,QACR,EAAQ,EAAM,iBAAmB,EAAE,EAAG,CAAE,kBAAmB,EAAa,KAAK,CAC9E,CAAC,QACC,EAAK,CAAC,EAAK,MACV,EAAI,GAAO,EAAO,IAAK,GAAU,EAAM,KAAK,CAAC,KAAK,IAAI,CAC/C,GAET,EAAE,CACH,CACF,CAED,MADA,GAAU,EAAK,CAAC,GAAG,EAAS,GAAG,OAAO,KAAK,EAAO,CAAC,CAAC,CAC7C,GAEuB,CAAE,EAAQ,OACnC,EAAK,CACZ,KAAK,OAAO,MAAM,EAAO,IAAI,6CAA6C,EAAI,UAAU,CAAC,CACzF,KAAK,QAAQ,KAAK,EAAE,CAItB,KAAK,OAAO,KACV,EAAO,MACL,6CAA6C,EAAK,YAAY,IAC/D,CACF"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./bulkRestartRequests-DhOfMz0S.mjs";import{t}from"./done-input-validation-LiTaCEzF.mjs";async function n({auth:n,requestReceiptFolder:r,sombraAuth:i,actions:a,statuses:o,requestIds:s,createdAt:c,emailIsVerified:l,silentModeBefore:u,sendEmailReceipt:d,copyIdentifiers:f,restartIdentifierStrategy:p,skipWaitingPeriod:m,createdAtBefore:h,createdAtAfter:g,updatedAtBefore:_,updatedAtAfter:v,concurrency:y,transcendUrl:b}){t(this.process),await e({requestReceiptFolder:r,auth:n,sombraAuth:i,requestActions:a,requestStatuses:o,requestIds:s,createdAt:c,emailIsVerified:l,silentModeBefore:u,sendEmailReceipt:d,copyIdentifiers:f,restartIdentifierStrategy:p,skipWaitingPeriod:m,createdAtBefore:h,createdAtAfter:g,updatedAtBefore:_,updatedAtAfter:v,concurrency:y,transcendUrl:b})}export{n as restart};
2
- //# sourceMappingURL=impl-OXGlZyUo.mjs.map
1
+ import{t as e}from"./bulkRestartRequests-3OpVNSrk.mjs";import{t}from"./done-input-validation-LiTaCEzF.mjs";async function n({auth:n,requestReceiptFolder:r,sombraAuth:i,actions:a,statuses:o,requestIds:s,createdAt:c,emailIsVerified:l,silentModeBefore:u,sendEmailReceipt:d,copyIdentifiers:f,restartIdentifierStrategy:p,skipWaitingPeriod:m,createdAtBefore:h,createdAtAfter:g,updatedAtBefore:_,updatedAtAfter:v,concurrency:y,transcendUrl:b}){t(this.process),await e({requestReceiptFolder:r,auth:n,sombraAuth:i,requestActions:a,requestStatuses:o,requestIds:s,createdAt:c,emailIsVerified:l,silentModeBefore:u,sendEmailReceipt:d,copyIdentifiers:f,restartIdentifierStrategy:p,skipWaitingPeriod:m,createdAtBefore:h,createdAtAfter:g,updatedAtBefore:_,updatedAtAfter:v,concurrency:y,transcendUrl:b})}export{n as restart};
2
+ //# sourceMappingURL=impl-xR4iG_u5.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-OXGlZyUo.mjs","names":[],"sources":["../src/commands/request/restart/impl.ts"],"sourcesContent":["import type {\n RequestAction,\n RequestStatus,\n RestartIdentifierStrategy,\n} from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { bulkRestartRequests } from '../../../lib/requests/index.js';\n\nexport interface RestartCommandFlags {\n auth: string;\n actions: RequestAction[];\n statuses: RequestStatus[];\n transcendUrl: string;\n requestReceiptFolder: string;\n sombraAuth?: string;\n concurrency: number;\n requestIds?: string[];\n emailIsVerified: boolean;\n createdAt?: Date;\n silentModeBefore?: Date;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n sendEmailReceipt: boolean;\n copyIdentifiers: boolean;\n restartIdentifierStrategy?: RestartIdentifierStrategy;\n skipWaitingPeriod: boolean;\n}\n\nexport async function restart(\n this: LocalContext,\n {\n auth,\n requestReceiptFolder,\n sombraAuth,\n actions,\n statuses,\n requestIds,\n createdAt,\n emailIsVerified,\n silentModeBefore,\n sendEmailReceipt,\n copyIdentifiers,\n restartIdentifierStrategy,\n skipWaitingPeriod,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n concurrency,\n transcendUrl,\n }: RestartCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await bulkRestartRequests({\n requestReceiptFolder,\n auth,\n sombraAuth,\n requestActions: actions,\n requestStatuses: statuses,\n requestIds,\n createdAt,\n emailIsVerified,\n silentModeBefore,\n sendEmailReceipt,\n copyIdentifiers,\n restartIdentifierStrategy,\n skipWaitingPeriod,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n concurrency,\n transcendUrl,\n });\n}\n"],"mappings":"2GAgCA,eAAsB,EAEpB,CACE,OACA,uBACA,aACA,UACA,WACA,aACA,YACA,kBACA,mBACA,mBACA,kBACA,4BACA,oBACA,kBACA,iBACA,kBACA,iBACA,cACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAAoB,CACxB,uBACA,OACA,aACA,eAAgB,EAChB,gBAAiB,EACjB,aACA,YACA,kBACA,mBACA,mBACA,kBACA,4BACA,oBACA,kBACA,iBACA,kBACA,iBACA,cACA,eACD,CAAC"}
1
+ {"version":3,"file":"impl-xR4iG_u5.mjs","names":[],"sources":["../src/commands/request/restart/impl.ts"],"sourcesContent":["import type {\n RequestAction,\n RequestStatus,\n RestartIdentifierStrategy,\n} from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { bulkRestartRequests } from '../../../lib/requests/index.js';\n\nexport interface RestartCommandFlags {\n auth: string;\n actions: RequestAction[];\n statuses: RequestStatus[];\n transcendUrl: string;\n requestReceiptFolder: string;\n sombraAuth?: string;\n concurrency: number;\n requestIds?: string[];\n emailIsVerified: boolean;\n createdAt?: Date;\n silentModeBefore?: Date;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n sendEmailReceipt: boolean;\n copyIdentifiers: boolean;\n restartIdentifierStrategy?: RestartIdentifierStrategy;\n skipWaitingPeriod: boolean;\n}\n\nexport async function restart(\n this: LocalContext,\n {\n auth,\n requestReceiptFolder,\n sombraAuth,\n actions,\n statuses,\n requestIds,\n createdAt,\n emailIsVerified,\n silentModeBefore,\n sendEmailReceipt,\n copyIdentifiers,\n restartIdentifierStrategy,\n skipWaitingPeriod,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n concurrency,\n transcendUrl,\n }: RestartCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await bulkRestartRequests({\n requestReceiptFolder,\n auth,\n sombraAuth,\n requestActions: actions,\n requestStatuses: statuses,\n requestIds,\n createdAt,\n emailIsVerified,\n silentModeBefore,\n sendEmailReceipt,\n copyIdentifiers,\n restartIdentifierStrategy,\n skipWaitingPeriod,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n concurrency,\n transcendUrl,\n });\n}\n"],"mappings":"2GAgCA,eAAsB,EAEpB,CACE,OACA,uBACA,aACA,UACA,WACA,aACA,YACA,kBACA,mBACA,mBACA,kBACA,4BACA,oBACA,kBACA,iBACA,kBACA,iBACA,cACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAAoB,CACxB,uBACA,OACA,aACA,eAAgB,EAChB,gBAAiB,EACjB,aACA,YACA,kBACA,mBACA,mBACA,kBACA,4BACA,oBACA,kBACA,iBACA,kBACA,iBACA,cACA,eACD,CAAC"}