@transcend-io/cli 12.1.0 → 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 (158) hide show
  1. package/README.md +2 -0
  2. package/dist/{app-CfJlhIn8.mjs → app-CnGAV_Tf.mjs} +19 -17
  3. package/dist/{app-CfJlhIn8.mjs.map → app-CnGAV_Tf.mjs.map} +1 -1
  4. package/dist/{approvePrivacyRequests-BWj6SsgX.mjs → approvePrivacyRequests-fmkUKYAm.mjs} +2 -2
  5. package/dist/{approvePrivacyRequests-BWj6SsgX.mjs.map → approvePrivacyRequests-fmkUKYAm.mjs.map} +1 -1
  6. package/dist/bin/bash-complete.mjs +1 -1
  7. package/dist/bin/cli.mjs +1 -1
  8. package/dist/bin/deprecated-command.mjs +1 -1
  9. package/dist/{buildExamples-1I3xKR1X.mjs → buildExamples-DB_puA14.mjs} +2 -2
  10. package/dist/{buildExamples-1I3xKR1X.mjs.map → buildExamples-DB_puA14.mjs.map} +1 -1
  11. package/dist/{buildXdiSyncEndpoint-CAal3Xc4.mjs → buildXdiSyncEndpoint-CwABTp_y.mjs} +2 -2
  12. package/dist/{buildXdiSyncEndpoint-CAal3Xc4.mjs.map → buildXdiSyncEndpoint-CwABTp_y.mjs.map} +1 -1
  13. package/dist/{bulkRestartRequests-B3wupylo.mjs → bulkRestartRequests-3OpVNSrk.mjs} +2 -2
  14. package/dist/{bulkRestartRequests-B3wupylo.mjs.map → bulkRestartRequests-3OpVNSrk.mjs.map} +1 -1
  15. package/dist/{bulkRetryEnrichers-D801tBcB.mjs → bulkRetryEnrichers-CdcXcHsx.mjs} +2 -2
  16. package/dist/{bulkRetryEnrichers-D801tBcB.mjs.map → bulkRetryEnrichers-CdcXcHsx.mjs.map} +1 -1
  17. package/dist/{cancelPrivacyRequests-CAKTZF47.mjs → cancelPrivacyRequests-Dcl2KZfB.mjs} +2 -2
  18. package/dist/{cancelPrivacyRequests-CAKTZF47.mjs.map → cancelPrivacyRequests-Dcl2KZfB.mjs.map} +1 -1
  19. package/dist/{command-BDQOL_MQ.mjs → command-BcxEDvsy.mjs} +2 -2
  20. package/dist/{command-BDQOL_MQ.mjs.map → command-BcxEDvsy.mjs.map} +1 -1
  21. package/dist/constants-DlH2vWm_.mjs +2 -0
  22. package/dist/constants-DlH2vWm_.mjs.map +1 -0
  23. package/dist/{constants-BlKpAm3R.mjs → constants-boymUaFC.mjs} +2 -2
  24. package/dist/{constants-BlKpAm3R.mjs.map → constants-boymUaFC.mjs.map} +1 -1
  25. package/dist/{createPoolingCommandUi-JBOW5UxY.mjs → createPoolingCommandUi-D7gyxeTT.mjs} +2 -2
  26. package/dist/{createPoolingCommandUi-JBOW5UxY.mjs.map → createPoolingCommandUi-D7gyxeTT.mjs.map} +1 -1
  27. package/dist/{downloadPrivacyRequestFiles-Cf14MQR4.mjs → downloadPrivacyRequestFiles-930ENWDi.mjs} +2 -2
  28. package/dist/{downloadPrivacyRequestFiles-Cf14MQR4.mjs.map → downloadPrivacyRequestFiles-930ENWDi.mjs.map} +1 -1
  29. package/dist/{extractClientError-DUJxHv07.mjs → extractClientError-BQgmnp3e.mjs} +2 -2
  30. package/dist/{extractClientError-DUJxHv07.mjs.map → extractClientError-BQgmnp3e.mjs.map} +1 -1
  31. package/dist/{fuzzyMatchColumns-2NmQqCZI.mjs → fuzzyMatchColumns-D18n9Beu.mjs} +2 -2
  32. package/dist/{fuzzyMatchColumns-2NmQqCZI.mjs.map → fuzzyMatchColumns-D18n9Beu.mjs.map} +1 -1
  33. package/dist/{generateCrossAccountApiKeys-CVdsJFOe.mjs → generateCrossAccountApiKeys-B_p8gQ2C.mjs} +2 -2
  34. package/dist/{generateCrossAccountApiKeys-CVdsJFOe.mjs.map → generateCrossAccountApiKeys-B_p8gQ2C.mjs.map} +1 -1
  35. package/dist/{impl-BTvZxws5.mjs → impl-2VeGCbJq.mjs} +2 -2
  36. package/dist/{impl-BTvZxws5.mjs.map → impl-2VeGCbJq.mjs.map} +1 -1
  37. package/dist/{impl-BVcy_GYa.mjs → impl-2YeOxW2m.mjs} +2 -2
  38. package/dist/{impl-BVcy_GYa.mjs.map → impl-2YeOxW2m.mjs.map} +1 -1
  39. package/dist/{impl-QdSegO65.mjs → impl-5Pko18bX.mjs} +2 -2
  40. package/dist/{impl-QdSegO65.mjs.map → impl-5Pko18bX.mjs.map} +1 -1
  41. package/dist/{impl-b4KAEVci.mjs → impl-7YqcGwra.mjs} +2 -2
  42. package/dist/{impl-b4KAEVci.mjs.map → impl-7YqcGwra.mjs.map} +1 -1
  43. package/dist/{impl-DUg1sDwg.mjs → impl-B5-UipRP.mjs} +2 -2
  44. package/dist/{impl-DUg1sDwg.mjs.map → impl-B5-UipRP.mjs.map} +1 -1
  45. package/dist/{impl-Dr9Jezjh2.mjs → impl-B8PyNdje2.mjs} +2 -2
  46. package/dist/{impl-Dr9Jezjh2.mjs.map → impl-B8PyNdje2.mjs.map} +1 -1
  47. package/dist/{impl-Bh02zrTq.mjs → impl-BIYT-9BY.mjs} +2 -2
  48. package/dist/{impl-Bh02zrTq.mjs.map → impl-BIYT-9BY.mjs.map} +1 -1
  49. package/dist/{impl-BQe6vddz.mjs → impl-BP110k4H.mjs} +2 -2
  50. package/dist/{impl-BQe6vddz.mjs.map → impl-BP110k4H.mjs.map} +1 -1
  51. package/dist/{impl-C-PvYlFE.mjs → impl-BPdvRtQ9.mjs} +2 -2
  52. package/dist/{impl-C-PvYlFE.mjs.map → impl-BPdvRtQ9.mjs.map} +1 -1
  53. package/dist/{impl-B_CRtRo8.mjs → impl-BUJbKCd4.mjs} +2 -2
  54. package/dist/{impl-B_CRtRo8.mjs.map → impl-BUJbKCd4.mjs.map} +1 -1
  55. package/dist/{impl-BxvKe9_7.mjs → impl-BbzX8auO.mjs} +2 -2
  56. package/dist/{impl-BxvKe9_7.mjs.map → impl-BbzX8auO.mjs.map} +1 -1
  57. package/dist/{impl-hRK54juc.mjs → impl-Bs4T0u8t.mjs} +2 -2
  58. package/dist/{impl-hRK54juc.mjs.map → impl-Bs4T0u8t.mjs.map} +1 -1
  59. package/dist/{impl-BgD7TeMD.mjs → impl-BtIse0WU.mjs} +2 -2
  60. package/dist/{impl-BgD7TeMD.mjs.map → impl-BtIse0WU.mjs.map} +1 -1
  61. package/dist/{impl-BQRP9NIv.mjs → impl-C4AjYGSc.mjs} +2 -2
  62. package/dist/{impl-BQRP9NIv.mjs.map → impl-C4AjYGSc.mjs.map} +1 -1
  63. package/dist/{impl-DtTfsHtL.mjs → impl-CFyD51rZ.mjs} +2 -2
  64. package/dist/{impl-DtTfsHtL.mjs.map → impl-CFyD51rZ.mjs.map} +1 -1
  65. package/dist/{impl-fg0UZYw6.mjs → impl-CKeiISid.mjs} +2 -2
  66. package/dist/{impl-fg0UZYw6.mjs.map → impl-CKeiISid.mjs.map} +1 -1
  67. package/dist/{impl-2sYR_UFO.mjs → impl-CKlQglut.mjs} +2 -2
  68. package/dist/{impl-2sYR_UFO.mjs.map → impl-CKlQglut.mjs.map} +1 -1
  69. package/dist/{impl-DldrBJEa.mjs → impl-CPyd-ahE.mjs} +2 -2
  70. package/dist/{impl-DldrBJEa.mjs.map → impl-CPyd-ahE.mjs.map} +1 -1
  71. package/dist/{impl-Cq-GARM1.mjs → impl-CtMcCdUA.mjs} +2 -2
  72. package/dist/{impl-Cq-GARM1.mjs.map → impl-CtMcCdUA.mjs.map} +1 -1
  73. package/dist/{impl-CG3f4B6u.mjs → impl-CwWY8MCP.mjs} +2 -2
  74. package/dist/{impl-CG3f4B6u.mjs.map → impl-CwWY8MCP.mjs.map} +1 -1
  75. package/dist/{impl-Dmn1CWts.mjs → impl-CwjhuIx0.mjs} +2 -2
  76. package/dist/{impl-Dmn1CWts.mjs.map → impl-CwjhuIx0.mjs.map} +1 -1
  77. package/dist/{impl-BD03bzB-.mjs → impl-Cx97QWq8.mjs} +2 -2
  78. package/dist/{impl-BD03bzB-.mjs.map → impl-Cx97QWq8.mjs.map} +1 -1
  79. package/dist/{impl-BgkovGOz.mjs → impl-D-Cz399O.mjs} +2 -2
  80. package/dist/{impl-BgkovGOz.mjs.map → impl-D-Cz399O.mjs.map} +1 -1
  81. package/dist/{impl-Tr08dgdk.mjs → impl-D3LHj5lS.mjs} +2 -2
  82. package/dist/{impl-Tr08dgdk.mjs.map → impl-D3LHj5lS.mjs.map} +1 -1
  83. package/dist/{impl-CFB_508q.mjs → impl-D9kZ4naw.mjs} +2 -2
  84. package/dist/{impl-CFB_508q.mjs.map → impl-D9kZ4naw.mjs.map} +1 -1
  85. package/dist/{impl-BzIyVAg_.mjs → impl-DBMuhicF.mjs} +2 -2
  86. package/dist/{impl-BzIyVAg_.mjs.map → impl-DBMuhicF.mjs.map} +1 -1
  87. package/dist/{impl-BRFL8xp7.mjs → impl-DDsOdK7O.mjs} +2 -2
  88. package/dist/{impl-BRFL8xp7.mjs.map → impl-DDsOdK7O.mjs.map} +1 -1
  89. package/dist/{impl-DTvnDByz.mjs → impl-DFhAp1Ky.mjs} +2 -2
  90. package/dist/{impl-DTvnDByz.mjs.map → impl-DFhAp1Ky.mjs.map} +1 -1
  91. package/dist/{impl-CC-yFYWt.mjs → impl-DGm6q0bm.mjs} +2 -2
  92. package/dist/{impl-CC-yFYWt.mjs.map → impl-DGm6q0bm.mjs.map} +1 -1
  93. package/dist/{impl-BGtup1F9.mjs → impl-DPb4YZxb.mjs} +2 -2
  94. package/dist/{impl-BGtup1F9.mjs.map → impl-DPb4YZxb.mjs.map} +1 -1
  95. package/dist/{impl-DzNEfRoS2.mjs → impl-DRmJog0S2.mjs} +2 -2
  96. package/dist/{impl-DzNEfRoS2.mjs.map → impl-DRmJog0S2.mjs.map} +1 -1
  97. package/dist/{impl-B-Oe7DcE2.mjs → impl-DT4VbZ-Q2.mjs} +2 -2
  98. package/dist/{impl-B-Oe7DcE2.mjs.map → impl-DT4VbZ-Q2.mjs.map} +1 -1
  99. package/dist/{impl-HnrcGt_T.mjs → impl-Ds6ROQi7.mjs} +2 -2
  100. package/dist/{impl-HnrcGt_T.mjs.map → impl-Ds6ROQi7.mjs.map} +1 -1
  101. package/dist/{impl-BQj1Ien4.mjs → impl-P1hltmA6.mjs} +2 -2
  102. package/dist/{impl-BQj1Ien4.mjs.map → impl-P1hltmA6.mjs.map} +1 -1
  103. package/dist/{impl-mjDxMEDR.mjs → impl-XztvsE6N.mjs} +2 -2
  104. package/dist/{impl-mjDxMEDR.mjs.map → impl-XztvsE6N.mjs.map} +1 -1
  105. package/dist/{impl-CVUD-7mJ.mjs → impl-agm4lpyq.mjs} +2 -2
  106. package/dist/{impl-CVUD-7mJ.mjs.map → impl-agm4lpyq.mjs.map} +1 -1
  107. package/dist/{impl-D6Lzwd-R2.mjs → impl-qTeP2Voo2.mjs} +2 -2
  108. package/dist/{impl-D6Lzwd-R2.mjs.map → impl-qTeP2Voo2.mjs.map} +1 -1
  109. package/dist/{impl-S90NUBGm.mjs → impl-xR4iG_u5.mjs} +2 -2
  110. package/dist/{impl-S90NUBGm.mjs.map → impl-xR4iG_u5.mjs.map} +1 -1
  111. package/dist/{impl-BopWGXnH.mjs → impl-yJETNVcT.mjs} +2 -2
  112. package/dist/{impl-BopWGXnH.mjs.map → impl-yJETNVcT.mjs.map} +1 -1
  113. package/dist/index.d.mts +6 -2
  114. package/dist/index.d.mts.map +1 -1
  115. package/dist/index.mjs +1 -1
  116. package/dist/{inquirer-BU5IpgA8.mjs → inquirer-jzIQWAvq.mjs} +2 -2
  117. package/dist/{inquirer-BU5IpgA8.mjs.map → inquirer-jzIQWAvq.mjs.map} +1 -1
  118. package/dist/{markRequestDataSiloIdsCompleted-C6lV_My-.mjs → markRequestDataSiloIdsCompleted-CU0ba_mE.mjs} +2 -2
  119. package/dist/{markRequestDataSiloIdsCompleted-C6lV_My-.mjs.map → markRequestDataSiloIdsCompleted-CU0ba_mE.mjs.map} +1 -1
  120. package/dist/{markSilentPrivacyRequests-D3bFOMLh.mjs → markSilentPrivacyRequests-Bf_4pCaq.mjs} +2 -2
  121. package/dist/{markSilentPrivacyRequests-D3bFOMLh.mjs.map → markSilentPrivacyRequests-Bf_4pCaq.mjs.map} +1 -1
  122. package/dist/{notifyPrivacyRequestsAdditionalTime-BGUxsWLN.mjs → notifyPrivacyRequestsAdditionalTime-rnUXdvBR.mjs} +2 -2
  123. package/dist/{notifyPrivacyRequestsAdditionalTime-BGUxsWLN.mjs.map → notifyPrivacyRequestsAdditionalTime-rnUXdvBR.mjs.map} +1 -1
  124. package/dist/{policy-bundle-manifest-RgsjPnfI.mjs → policy-bundle-manifest-B1Herd_n.mjs} +2 -2
  125. package/dist/{policy-bundle-manifest-RgsjPnfI.mjs.map → policy-bundle-manifest-B1Herd_n.mjs.map} +1 -1
  126. package/dist/{policy-project-discovery-B4cFXUlA.mjs → policy-project-discovery-oc49b2gr.mjs} +2 -2
  127. package/dist/{policy-project-discovery-B4cFXUlA.mjs.map → policy-project-discovery-oc49b2gr.mjs.map} +1 -1
  128. package/dist/{policy-scaffold-config-CwlygiTz.mjs → policy-scaffold-config-CpXR9KgF.mjs} +2 -2
  129. package/dist/{policy-scaffold-config-CwlygiTz.mjs.map → policy-scaffold-config-CpXR9KgF.mjs.map} +1 -1
  130. package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-BfNNWqeI.mjs → pullChunkedCustomSiloOutstandingIdentifiers-BcBj9prQ.mjs} +2 -2
  131. package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-BfNNWqeI.mjs.map → pullChunkedCustomSiloOutstandingIdentifiers-BcBj9prQ.mjs.map} +1 -1
  132. package/dist/{pullManualEnrichmentIdentifiersToCsv-B_lWa6Yg.mjs → pullManualEnrichmentIdentifiersToCsv-BSUXUp8v.mjs} +2 -2
  133. package/dist/{pullManualEnrichmentIdentifiersToCsv-B_lWa6Yg.mjs.map → pullManualEnrichmentIdentifiersToCsv-BSUXUp8v.mjs.map} +1 -1
  134. package/dist/{pushCronIdentifiersFromCsv-CDhlEf6n.mjs → pushCronIdentifiersFromCsv-D-l3erLO.mjs} +2 -2
  135. package/dist/{pushCronIdentifiersFromCsv-CDhlEf6n.mjs.map → pushCronIdentifiersFromCsv-D-l3erLO.mjs.map} +1 -1
  136. package/dist/{pushManualEnrichmentIdentifiersFromCsv-Bn_028w5.mjs → pushManualEnrichmentIdentifiersFromCsv-CqLIw5MV.mjs} +2 -2
  137. package/dist/{pushManualEnrichmentIdentifiersFromCsv-Bn_028w5.mjs.map → pushManualEnrichmentIdentifiersFromCsv-CqLIw5MV.mjs.map} +1 -1
  138. package/dist/{removeUnverifiedRequestIdentifiers-DcI9ut4q.mjs → removeUnverifiedRequestIdentifiers-B-Az2HJ8.mjs} +2 -2
  139. package/dist/{removeUnverifiedRequestIdentifiers-DcI9ut4q.mjs.map → removeUnverifiedRequestIdentifiers-B-Az2HJ8.mjs.map} +1 -1
  140. package/dist/{retryRequestDataSilos-ZdY2PM0S.mjs → retryRequestDataSilos-D70pC9JF.mjs} +2 -2
  141. package/dist/{retryRequestDataSilos-ZdY2PM0S.mjs.map → retryRequestDataSilos-D70pC9JF.mjs.map} +1 -1
  142. package/dist/{skipPreflightJobs-KdcSw8Td.mjs → skipPreflightJobs-B0YG7mhP.mjs} +2 -2
  143. package/dist/{skipPreflightJobs-KdcSw8Td.mjs.map → skipPreflightJobs-B0YG7mhP.mjs.map} +1 -1
  144. package/dist/{skipRequestDataSilos-Cy2NfP47.mjs → skipRequestDataSilos-DV5Dy5Dw.mjs} +2 -2
  145. package/dist/{skipRequestDataSilos-Cy2NfP47.mjs.map → skipRequestDataSilos-DV5Dy5Dw.mjs.map} +1 -1
  146. package/dist/{streamPrivacyRequestsToCsv-ByRBG8Mb.mjs → streamPrivacyRequestsToCsv-Qm2r7Iy2.mjs} +2 -2
  147. package/dist/{streamPrivacyRequestsToCsv-ByRBG8Mb.mjs.map → streamPrivacyRequestsToCsv-Qm2r7Iy2.mjs.map} +1 -1
  148. package/dist/{updateConsentManagerVersionToLatest-KwMaAkwh.mjs → updateConsentManagerVersionToLatest-cryDInky.mjs} +2 -2
  149. package/dist/{updateConsentManagerVersionToLatest-KwMaAkwh.mjs.map → updateConsentManagerVersionToLatest-cryDInky.mjs.map} +1 -1
  150. package/dist/{uploadConsents-C5LmI-9T.mjs → uploadConsents-Din2Qdws.mjs} +2 -2
  151. package/dist/{uploadConsents-C5LmI-9T.mjs.map → uploadConsents-Din2Qdws.mjs.map} +1 -1
  152. package/dist/uploadPrivacyRequestsFromCsv-DHYbgV8h.mjs +2 -0
  153. package/dist/uploadPrivacyRequestsFromCsv-DHYbgV8h.mjs.map +1 -0
  154. package/package.json +4 -4
  155. package/dist/constants-qvGk0wlN.mjs +0 -2
  156. package/dist/constants-qvGk0wlN.mjs.map +0 -1
  157. package/dist/uploadPrivacyRequestsFromCsv-BsYnCgbl.mjs +0 -2
  158. package/dist/uploadPrivacyRequestsFromCsv-BsYnCgbl.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"generateCrossAccountApiKeys-CVdsJFOe.mjs","names":[],"sources":["../src/lib/api-keys/generateCrossAccountApiKeys.ts"],"sourcesContent":["import { ScopeName } from '@transcend-io/privacy-types';\nimport {\n buildTranscendGraphQLClientGeneric,\n loginUser,\n createApiKey,\n fetchAllApiKeys,\n deleteApiKey,\n assumeRole,\n} from '@transcend-io/sdk';\nimport { mapSeries } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport { StoredApiKey } from '../../codecs.js';\nimport { DEFAULT_TRANSCEND_API } from '../../constants.js';\nimport { logger } from '../../logger.js';\n\nexport interface ApiKeyGenerateError {\n /** Name of instance */\n organizationName: string;\n /** Error */\n error: string;\n /** Organization ID API key is for */\n organizationId: string;\n}\n\n/**\n * Generate API keys across multiple transcend accounts\n *\n * @param options - Options\n * @returns Number of API keys created\n */\nexport async function generateCrossAccountApiKeys({\n email,\n password,\n scopes,\n apiKeyTitle,\n parentOrganizationId,\n deleteExistingApiKey = true,\n createNewApiKey = true,\n transcendUrl = DEFAULT_TRANSCEND_API,\n}: {\n /** Email address of user generating API keys */\n email: string;\n /** Password of user generating API keys */\n password: string;\n /** Filter for organizations that match this parent organization ID */\n parentOrganizationId?: string;\n /** Title of the API create to create */\n apiKeyTitle: string;\n /** Title of the API create to create */\n scopes: ScopeName[];\n /** API URL for Transcend backend */\n transcendUrl?: string;\n /** When true delete existing API keys with that title, if set to false an API key exists with that title, an error is thrown */\n deleteExistingApiKey?: boolean;\n /** When true, generate new API keys, otherwise only will delete past API keys */\n createNewApiKey?: boolean;\n}): Promise<{\n /** Successfully generated */\n apiKeys: StoredApiKey[];\n /** Error results */\n errors: ApiKeyGenerateError[];\n}> {\n // Create GraphQL client\n const client = await buildTranscendGraphQLClientGeneric(transcendUrl, {});\n\n // Login the user\n logger.info(colors.magenta('Logging in using email and password.'));\n const { roles, loginCookie } = await loginUser(client, { email, password, logger });\n logger.info(\n colors.green(\n `Successfully logged in and found ${roles.length} role${roles.length === 1 ? '' : 's'}!`,\n ),\n );\n\n // Filter down by parentOrganizationId\n const filteredRoles = parentOrganizationId\n ? roles.filter(\n (role) =>\n role.organization.id === parentOrganizationId ||\n role.organization.parentOrganizationId === parentOrganizationId,\n )\n : roles;\n\n // Save cookie to call route subsequent times\n client.setHeaders({\n Cookie: loginCookie,\n });\n\n // Save the resulting API keys\n const results: StoredApiKey[] = [];\n const errors: ApiKeyGenerateError[] = [];\n\n // Generate API keys\n logger.info(\n colors.magenta(`Generating API keys with title: ${apiKeyTitle}, scopes: ${scopes.join(',')}.`),\n );\n\n // Map over each role\n await mapSeries(filteredRoles, async (role) => {\n try {\n // Log into the other instance\n await assumeRole(client, { roleId: role.id, email, logger });\n\n // Grab API keys with that title\n logger.info(\n colors.magenta(\n `Checking if API key already exists in organization \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n\n // Delete existing API key\n const [apiKeyWithTitle] = await fetchAllApiKeys(client, {\n logger,\n filterBy: { titles: [apiKeyTitle] },\n });\n if (apiKeyWithTitle && deleteExistingApiKey) {\n logger.info(\n colors.yellow(\n `Deleting existing API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n await deleteApiKey(client, { id: apiKeyWithTitle.id, logger });\n logger.info(\n colors.green(\n `Successfully deleted API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n } else if (apiKeyWithTitle) {\n // throw error if one exists but not configured to delete\n throw new Error(`API key already exists with title: \"${apiKeyTitle}\"`);\n }\n\n // Create the API key\n if (createNewApiKey) {\n logger.info(\n colors.magenta(\n `Creating API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n const { apiKey } = await createApiKey(client, {\n input: { title: apiKeyTitle, scopes },\n logger,\n });\n results.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n apiKey,\n });\n logger.info(\n colors.green(\n `Successfully created API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n } else {\n // Delete only\n results.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n apiKey: '',\n });\n }\n } catch (err) {\n logger.error(\n colors.red(\n `Failed to create API key in organization \"${role.organization.name}\"! - ${err.message}`,\n ),\n );\n errors.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n error: err.message,\n });\n }\n });\n logger.info(\n colors.green(\n `Successfully created ${results.length} API key${results.length === 1 ? '' : 's'}`,\n ),\n );\n\n if (errors.length > 0) {\n logger.error(\n colors.red(`Failed to create ${errors.length} API key${errors.length === 1 ? '' : 's'}!`),\n );\n }\n\n return { errors, apiKeys: results };\n}\n"],"mappings":"uTA+BA,eAAsB,EAA4B,CAChD,QACA,WACA,SACA,cACA,uBACA,uBAAuB,GACvB,kBAAkB,GAClB,eAAe,GAuBd,CAED,IAAM,EAAS,MAAM,EAAmC,EAAc,EAAE,CAAC,CAGzE,EAAO,KAAK,EAAO,QAAQ,uCAAuC,CAAC,CACnE,GAAM,CAAE,QAAO,eAAgB,MAAM,EAAU,EAAQ,CAAE,QAAO,WAAU,SAAQ,CAAC,CACnF,EAAO,KACL,E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AC,CACF,EAAO,KACL,EAAO,MACL,oCAAoC,EAAK,aAAa,KAAK,iBAAiB,EAAY,IACzF,CACF,MAGD,EAAQ,KAAK,CACX,iBAAkB,EAAK,aAAa,KACpC,eAAgB,EAAK,aAAa,GAClC,OAAQ,GACT,CAAC,OAEG,EAAK,CACZ,EAAO,MACL,EAAO,IACL,6CAA6C,EAAK,aAAa,KAAK,OAAO,EAAI,UAChF,CACF,CACD,EAAO,KAAK,CACV,iBAAkB,EAAK,aAAa,KACpC,eAAgB,EAAK,aAAa,GAClC,MAAO,EAAI,QACZ,CAAC,GAEJ,CACF,EAAO,KACL,EAAO,MACL,wBAAwB,EAAQ,OAAO,UAAU,EAAQ,SAAW,EAAI,GAAK,MAC9E,CACF,CAEG,EAAO,OAAS,GAClB,EAAO,MACL,EAAO,IAAI,oBAAoB,EAAO,OAAO,UAAU,EAAO,SAAW,EAAI,GAAK,IAAI,GAAG,CAC1F,CAGI,CAAE,SAAQ,QAAS,EAAS"}
1
+ {"version":3,"file":"generateCrossAccountApiKeys-B_p8gQ2C.mjs","names":[],"sources":["../src/lib/api-keys/generateCrossAccountApiKeys.ts"],"sourcesContent":["import { ScopeName } from '@transcend-io/privacy-types';\nimport {\n buildTranscendGraphQLClientGeneric,\n loginUser,\n createApiKey,\n fetchAllApiKeys,\n deleteApiKey,\n assumeRole,\n} from '@transcend-io/sdk';\nimport { mapSeries } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport { StoredApiKey } from '../../codecs.js';\nimport { DEFAULT_TRANSCEND_API } from '../../constants.js';\nimport { logger } from '../../logger.js';\n\nexport interface ApiKeyGenerateError {\n /** Name of instance */\n organizationName: string;\n /** Error */\n error: string;\n /** Organization ID API key is for */\n organizationId: string;\n}\n\n/**\n * Generate API keys across multiple transcend accounts\n *\n * @param options - Options\n * @returns Number of API keys created\n */\nexport async function generateCrossAccountApiKeys({\n email,\n password,\n scopes,\n apiKeyTitle,\n parentOrganizationId,\n deleteExistingApiKey = true,\n createNewApiKey = true,\n transcendUrl = DEFAULT_TRANSCEND_API,\n}: {\n /** Email address of user generating API keys */\n email: string;\n /** Password of user generating API keys */\n password: string;\n /** Filter for organizations that match this parent organization ID */\n parentOrganizationId?: string;\n /** Title of the API create to create */\n apiKeyTitle: string;\n /** Title of the API create to create */\n scopes: ScopeName[];\n /** API URL for Transcend backend */\n transcendUrl?: string;\n /** When true delete existing API keys with that title, if set to false an API key exists with that title, an error is thrown */\n deleteExistingApiKey?: boolean;\n /** When true, generate new API keys, otherwise only will delete past API keys */\n createNewApiKey?: boolean;\n}): Promise<{\n /** Successfully generated */\n apiKeys: StoredApiKey[];\n /** Error results */\n errors: ApiKeyGenerateError[];\n}> {\n // Create GraphQL client\n const client = await buildTranscendGraphQLClientGeneric(transcendUrl, {});\n\n // Login the user\n logger.info(colors.magenta('Logging in using email and password.'));\n const { roles, loginCookie } = await loginUser(client, { email, password, logger });\n logger.info(\n colors.green(\n `Successfully logged in and found ${roles.length} role${roles.length === 1 ? '' : 's'}!`,\n ),\n );\n\n // Filter down by parentOrganizationId\n const filteredRoles = parentOrganizationId\n ? roles.filter(\n (role) =>\n role.organization.id === parentOrganizationId ||\n role.organization.parentOrganizationId === parentOrganizationId,\n )\n : roles;\n\n // Save cookie to call route subsequent times\n client.setHeaders({\n Cookie: loginCookie,\n });\n\n // Save the resulting API keys\n const results: StoredApiKey[] = [];\n const errors: ApiKeyGenerateError[] = [];\n\n // Generate API keys\n logger.info(\n colors.magenta(`Generating API keys with title: ${apiKeyTitle}, scopes: ${scopes.join(',')}.`),\n );\n\n // Map over each role\n await mapSeries(filteredRoles, async (role) => {\n try {\n // Log into the other instance\n await assumeRole(client, { roleId: role.id, email, logger });\n\n // Grab API keys with that title\n logger.info(\n colors.magenta(\n `Checking if API key already exists in organization \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n\n // Delete existing API key\n const [apiKeyWithTitle] = await fetchAllApiKeys(client, {\n logger,\n filterBy: { titles: [apiKeyTitle] },\n });\n if (apiKeyWithTitle && deleteExistingApiKey) {\n logger.info(\n colors.yellow(\n `Deleting existing API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n await deleteApiKey(client, { id: apiKeyWithTitle.id, logger });\n logger.info(\n colors.green(\n `Successfully deleted API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n } else if (apiKeyWithTitle) {\n // throw error if one exists but not configured to delete\n throw new Error(`API key already exists with title: \"${apiKeyTitle}\"`);\n }\n\n // Create the API key\n if (createNewApiKey) {\n logger.info(\n colors.magenta(\n `Creating API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n const { apiKey } = await createApiKey(client, {\n input: { title: apiKeyTitle, scopes },\n logger,\n });\n results.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n apiKey,\n });\n logger.info(\n colors.green(\n `Successfully created API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n } else {\n // Delete only\n results.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n apiKey: '',\n });\n }\n } catch (err) {\n logger.error(\n colors.red(\n `Failed to create API key in organization \"${role.organization.name}\"! - ${err.message}`,\n ),\n );\n errors.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n error: err.message,\n });\n }\n });\n logger.info(\n colors.green(\n `Successfully created ${results.length} API key${results.length === 1 ? '' : 's'}`,\n ),\n );\n\n if (errors.length > 0) {\n logger.error(\n colors.red(`Failed to create ${errors.length} API key${errors.length === 1 ? '' : 's'}!`),\n );\n }\n\n return { errors, apiKeys: results };\n}\n"],"mappings":"uTA+BA,eAAsB,EAA4B,CAChD,QACA,WACA,SACA,cACA,uBACA,uBAAuB,GACvB,kBAAkB,GAClB,eAAe,GAuBd,CAED,IAAM,EAAS,MAAM,EAAmC,EAAc,EAAE,CAAC,CAGzE,EAAO,KAAK,EAAO,QAAQ,uCAAuC,CAAC,CACnE,GAAM,CAAE,QAAO,eAAgB,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AAK,CACX,iBAAkB,EAAK,aAAa,KACpC,eAAgB,EAAK,aAAa,GAClC,SACD,CAAC,CACF,EAAO,KACL,EAAO,MACL,oCAAoC,EAAK,aAAa,KAAK,iBAAiB,EAAY,IACzF,CACF,MAGD,EAAQ,KAAK,CACX,iBAAkB,EAAK,aAAa,KACpC,eAAgB,EAAK,aAAa,GAClC,OAAQ,GACT,CAAC,OAEG,EAAK,CACZ,EAAO,MACL,EAAO,IACL,6CAA6C,EAAK,aAAa,KAAK,OAAO,EAAI,UAChF,CACF,CACD,EAAO,KAAK,CACV,iBAAkB,EAAK,aAAa,KACpC,eAAgB,EAAK,aAAa,GAClC,MAAO,EAAI,QACZ,CAAC,GAEJ,CACF,EAAO,KACL,EAAO,MACL,wBAAwB,EAAQ,OAAO,UAAU,EAAQ,SAAW,EAAI,GAAK,MAC9E,CACF,CAEG,EAAO,OAAS,GAClB,EAAO,MACL,EAAO,IAAI,oBAAoB,EAAO,OAAO,UAAU,EAAO,SAAW,EAAI,GAAK,IAAI,GAAG,CAC1F,CAGI,CAAE,SAAQ,QAAS,EAAS"}
@@ -1,2 +1,2 @@
1
- import{i as e,n as t,t as n}from"./policy-project-discovery-B4cFXUlA.mjs";import{n as r,r as i}from"./runOpa-ojIqU1tO.mjs";import{t as a}from"./done-input-validation-LiTaCEzF.mjs";import o from"node:path";import s from"colors";async function c({format:c,verbose:l,run:u,coverage:d,threshold:f,timeout:p,"var-values":m,explain:h,schema:g,"exit-zero-on-skipped":_},v=n){a(this.process),i();let y=e(this.process.cwd(),v);if(!this.fs.existsSync(y)||!this.fs.statSync(y).isDirectory())throw Error(`Policy directory does not exist or is not a directory: ${y}`);if(f!==void 0&&!d)throw Error(`--threshold requires --coverage.`);if(f!==void 0){let e=Number(f);if(!Number.isFinite(e)||e<0||e>100)throw Error(`--threshold must be a number between 0 and 100, got: ${f}`)}let b=g?o.resolve(this.process.cwd(),g):void 0;if(b&&!this.fs.existsSync(b))throw Error(`Schema path not found: ${b}`);let x=t(this,y);if(x.length===0)throw Error("No publishable policy bundles found. Add one with `transcend policy new`, or pass a directory that contains a `.manifest`.");for(let e of x){this.logger.info(s.green(`Running policy tests in ${e}...`));let t=await r([`test`,`--fail-on-empty`,`-b`,e,`--format`,c,...l?[`--verbose`]:[],...u?[`--run`,u]:[],...d?[`--coverage`]:[],...f===void 0?[]:[`--threshold`,f],...p?[`--timeout`,p]:[],...m?[`--var-values`]:[],...h?[`--explain`,h]:[],...b?[`--schema`,b]:[],..._?[`--exit-zero-on-skipped`]:[]]);t!==0&&this.process.exit(t)}this.logger.info(s.green(`Policy tests passed.`))}export{c as test};
2
- //# sourceMappingURL=impl-BTvZxws5.mjs.map
1
+ import{i as e,n as t,t as n}from"./policy-project-discovery-oc49b2gr.mjs";import{n as r,r as i}from"./runOpa-ojIqU1tO.mjs";import{t as a}from"./done-input-validation-LiTaCEzF.mjs";import o from"node:path";import s from"colors";async function c({format:c,verbose:l,run:u,coverage:d,threshold:f,timeout:p,"var-values":m,explain:h,schema:g,"exit-zero-on-skipped":_},v=n){a(this.process),i();let y=e(this.process.cwd(),v);if(!this.fs.existsSync(y)||!this.fs.statSync(y).isDirectory())throw Error(`Policy directory does not exist or is not a directory: ${y}`);if(f!==void 0&&!d)throw Error(`--threshold requires --coverage.`);if(f!==void 0){let e=Number(f);if(!Number.isFinite(e)||e<0||e>100)throw Error(`--threshold must be a number between 0 and 100, got: ${f}`)}let b=g?o.resolve(this.process.cwd(),g):void 0;if(b&&!this.fs.existsSync(b))throw Error(`Schema path not found: ${b}`);let x=t(this,y);if(x.length===0)throw Error("No publishable policy bundles found. Add one with `transcend policy new`, or pass a directory that contains a `.manifest`.");for(let e of x){this.logger.info(s.green(`Running policy tests in ${e}...`));let t=await r([`test`,`--fail-on-empty`,`-b`,e,`--format`,c,...l?[`--verbose`]:[],...u?[`--run`,u]:[],...d?[`--coverage`]:[],...f===void 0?[]:[`--threshold`,f],...p?[`--timeout`,p]:[],...m?[`--var-values`]:[],...h?[`--explain`,h]:[],...b?[`--schema`,b]:[],..._?[`--exit-zero-on-skipped`]:[]]);t!==0&&this.process.exit(t)}this.logger.info(s.green(`Policy tests passed.`))}export{c as test};
2
+ //# sourceMappingURL=impl-2VeGCbJq.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-BTvZxws5.mjs","names":[],"sources":["../src/commands/policy/test/impl.ts"],"sourcesContent":["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 DEFAULT_POLICY_PROJECT_DIRECTORY,\n discoverPolicyBundleDirectories,\n resolvePolicyProjectDirectory,\n} from '../../../lib/policy/policy-project-discovery.js';\nimport { assertOpaInstalled, runOpa } from '../helpers/index.js';\nimport type { PolicyTestExplainMode, PolicyTestFormat } from './command.js';\n\n/** CLI flags for `transcend policy test`. */\nexport interface TestCommandFlags {\n /** `opa test --format` value. */\n format: PolicyTestFormat;\n /** `opa test --verbose`. */\n verbose: boolean;\n /** Optional `opa test --run` regex. */\n run?: string;\n /** `opa test --coverage`. */\n coverage: boolean;\n /** Optional `opa test --threshold` coverage percent. */\n threshold?: string;\n /** Optional `opa test --timeout` duration. */\n timeout?: string;\n /** `opa test --var-values`. */\n 'var-values': boolean;\n /** Optional `opa test --explain` mode. */\n explain?: PolicyTestExplainMode;\n /** Optional `opa test --schema` path. */\n schema?: string;\n /** `opa test --exit-zero-on-skipped`. */\n 'exit-zero-on-skipped': boolean;\n}\n\n/**\n * Run OPA tests against local policy bundles.\n *\n * With no directory (or the default workspace path), discovers every immediate\n * child that contains a `.manifest` and tests each. Pass one bundle path to\n * test a single publishable unit.\n *\n * @param this - CLI context\n * @param flags - Command flags\n * @param directory - Policy workspace or bundle directory\n */\nexport async function test(\n this: LocalContext,\n {\n format,\n verbose,\n run,\n coverage,\n threshold,\n timeout,\n 'var-values': varValues,\n explain,\n schema,\n 'exit-zero-on-skipped': exitZeroOnSkipped,\n }: TestCommandFlags,\n directory: string = DEFAULT_POLICY_PROJECT_DIRECTORY,\n): Promise<void> {\n doneInputValidation(this.process);\n\n assertOpaInstalled();\n const resolvedDir = resolvePolicyProjectDirectory(this.process.cwd(), directory);\n if (!this.fs.existsSync(resolvedDir) || !this.fs.statSync(resolvedDir).isDirectory()) {\n throw new Error(`Policy directory does not exist or is not a directory: ${resolvedDir}`);\n }\n\n if (threshold !== undefined && !coverage) {\n throw new Error('--threshold requires --coverage.');\n }\n if (threshold !== undefined) {\n const parsed = Number(threshold);\n if (!Number.isFinite(parsed) || parsed < 0 || parsed > 100) {\n throw new Error(`--threshold must be a number between 0 and 100, got: ${threshold}`);\n }\n }\n\n const schemaPath = schema ? path.resolve(this.process.cwd(), schema) : undefined;\n if (schemaPath && !this.fs.existsSync(schemaPath)) {\n throw new Error(`Schema path not found: ${schemaPath}`);\n }\n\n const bundleDirectories = discoverPolicyBundleDirectories(this, resolvedDir);\n if (bundleDirectories.length === 0) {\n throw new Error(\n 'No publishable policy bundles found. Add one with `transcend policy new`, ' +\n 'or pass a directory that contains a `.manifest`.',\n );\n }\n\n for (const bundleDirectory of bundleDirectories) {\n this.logger.info(colors.green(`Running policy tests in ${bundleDirectory}...`));\n const exitCode = await runOpa([\n 'test',\n '--fail-on-empty',\n '-b',\n bundleDirectory,\n '--format',\n format,\n ...(verbose ? ['--verbose'] : []),\n ...(run ? ['--run', run] : []),\n ...(coverage ? ['--coverage'] : []),\n ...(threshold !== undefined ? ['--threshold', threshold] : []),\n ...(timeout ? ['--timeout', timeout] : []),\n ...(varValues ? ['--var-values'] : []),\n ...(explain ? ['--explain', explain] : []),\n ...(schemaPath ? ['--schema', schemaPath] : []),\n ...(exitZeroOnSkipped ? ['--exit-zero-on-skipped'] : []),\n ]);\n if (exitCode !== 0) {\n this.process.exit(exitCode);\n }\n }\n\n this.logger.info(colors.green('Policy tests passed.'));\n}\n"],"mappings":"mOAiDA,eAAsB,EAEpB,CACE,SACA,UACA,MACA,WACA,YACA,UAC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,EAAE,CACzC,GAAI,EAAa,CAAC,WAAY,EAAW,CAAG,EAAE,CAC9C,GAAI,EAAoB,CAAC,yBAAyB,CAAG,EAAE,CACxD,CAAC,CACE,IAAa,GACf,KAAK,QAAQ,KAAK,EAAS,CAI/B,KAAK,OAAO,KAAK,EAAO,MAAM,uBAAuB,CAAC"}
1
+ {"version":3,"file":"impl-2VeGCbJq.mjs","names":[],"sources":["../src/commands/policy/test/impl.ts"],"sourcesContent":["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 DEFAULT_POLICY_PROJECT_DIRECTORY,\n discoverPolicyBundleDirectories,\n resolvePolicyProjectDirectory,\n} from '../../../lib/policy/policy-project-discovery.js';\nimport { assertOpaInstalled, runOpa } from '../helpers/index.js';\nimport type { PolicyTestExplainMode, PolicyTestFormat } from './command.js';\n\n/** CLI flags for `transcend policy test`. */\nexport interface TestCommandFlags {\n /** `opa test --format` value. */\n format: PolicyTestFormat;\n /** `opa test --verbose`. */\n verbose: boolean;\n /** Optional `opa test --run` regex. */\n run?: string;\n /** `opa test --coverage`. */\n coverage: boolean;\n /** Optional `opa test --threshold` coverage percent. */\n threshold?: string;\n /** Optional `opa test --timeout` duration. */\n timeout?: string;\n /** `opa test --var-values`. */\n 'var-values': boolean;\n /** Optional `opa test --explain` mode. */\n explain?: PolicyTestExplainMode;\n /** Optional `opa test --schema` path. */\n schema?: string;\n /** `opa test --exit-zero-on-skipped`. */\n 'exit-zero-on-skipped': boolean;\n}\n\n/**\n * Run OPA tests against local policy bundles.\n *\n * With no directory (or the default workspace path), discovers every immediate\n * child that contains a `.manifest` and tests each. Pass one bundle path to\n * test a single publishable unit.\n *\n * @param this - CLI context\n * @param flags - Command flags\n * @param directory - Policy workspace or bundle directory\n */\nexport async function test(\n this: LocalContext,\n {\n format,\n verbose,\n run,\n coverage,\n threshold,\n timeout,\n 'var-values': varValues,\n explain,\n schema,\n 'exit-zero-on-skipped': exitZeroOnSkipped,\n }: TestCommandFlags,\n directory: string = DEFAULT_POLICY_PROJECT_DIRECTORY,\n): Promise<void> {\n doneInputValidation(this.process);\n\n assertOpaInstalled();\n const resolvedDir = resolvePolicyProjectDirectory(this.process.cwd(), directory);\n if (!this.fs.existsSync(resolvedDir) || !this.fs.statSync(resolvedDir).isDirectory()) {\n throw new Error(`Policy directory does not exist or is not a directory: ${resolvedDir}`);\n }\n\n if (threshold !== undefined && !coverage) {\n throw new Error('--threshold requires --coverage.');\n }\n if (threshold !== undefined) {\n const parsed = Number(threshold);\n if (!Number.isFinite(parsed) || parsed < 0 || parsed > 100) {\n throw new Error(`--threshold must be a number between 0 and 100, got: ${threshold}`);\n }\n }\n\n const schemaPath = schema ? path.resolve(this.process.cwd(), schema) : undefined;\n if (schemaPath && !this.fs.existsSync(schemaPath)) {\n throw new Error(`Schema path not found: ${schemaPath}`);\n }\n\n const bundleDirectories = discoverPolicyBundleDirectories(this, resolvedDir);\n if (bundleDirectories.length === 0) {\n throw new Error(\n 'No publishable policy bundles found. Add one with `transcend policy new`, ' +\n 'or pass a directory that contains a `.manifest`.',\n );\n }\n\n for (const bundleDirectory of bundleDirectories) {\n this.logger.info(colors.green(`Running policy tests in ${bundleDirectory}...`));\n const exitCode = await runOpa([\n 'test',\n '--fail-on-empty',\n '-b',\n bundleDirectory,\n '--format',\n format,\n ...(verbose ? ['--verbose'] : []),\n ...(run ? ['--run', run] : []),\n ...(coverage ? ['--coverage'] : []),\n ...(threshold !== undefined ? ['--threshold', threshold] : []),\n ...(timeout ? ['--timeout', timeout] : []),\n ...(varValues ? ['--var-values'] : []),\n ...(explain ? ['--explain', explain] : []),\n ...(schemaPath ? ['--schema', schemaPath] : []),\n ...(exitZeroOnSkipped ? ['--exit-zero-on-skipped'] : []),\n ]);\n if (exitCode !== 0) {\n this.process.exit(exitCode);\n }\n }\n\n this.logger.info(colors.green('Policy tests passed.'));\n}\n"],"mappings":"mOAiDA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AAE,CACrC,GAAI,EAAU,CAAC,YAAa,EAAQ,CAAG,EAAE,CACzC,GAAI,EAAa,CAAC,WAAY,EAAW,CAAG,EAAE,CAC9C,GAAI,EAAoB,CAAC,yBAAyB,CAAG,EAAE,CACxD,CAAC,CACE,IAAa,GACf,KAAK,QAAQ,KAAK,EAAS,CAI/B,KAAK,OAAO,KAAK,EAAO,MAAM,uBAAuB,CAAC"}
@@ -1,2 +1,2 @@
1
- import{r as e}from"./constants-BlKpAm3R.mjs";import{r as t}from"./readTranscendYaml-BfqQbPiT.mjs";import{n,t as r}from"./mergeTranscendInputs-B7WjxYMN.mjs";import{t as i}from"./parseVariablesFromString-6TYW65LF.mjs";import{t as a}from"./validateTranscendAuth-D-dDINof.mjs";import{t as o}from"./listFiles-DDGCBdtx.mjs";import{t as s}from"./done-input-validation-LiTaCEzF.mjs";import c from"node:path";import l from"colors";import{mapSeries as u}from"@transcend-io/utils";import{buildTranscendGraphQLClient as d}from"@transcend-io/sdk";async function f({transcendUrl:e,auth:t,pageSize:r,publishToPrivacyCenter:i,contents:a,deleteExtraAttributeValues:o=!1,classifyService:s=!1,logger:c}){let u=d(e,t);try{let e=await n(a,u,{pageSize:r,publishToPrivacyCenter:i,classifyService:s,deleteExtraAttributeValues:o,logger:c});return e.success||e.errors.forEach(({resource:e,item:t,message:n})=>{c.error(l.red(`Failed to sync ${e}${t?` "${t}"`:``}: ${n}`))}),e.success}catch(e){return c.error(l.red(`An unexpected error occurred syncing the schema: ${e.message}`)),!1}}async function p({file:n=`./transcend.yml`,transcendUrl:d,auth:p,variables:m,pageSize:h,publishToPrivacyCenter:g,classifyService:_,deleteExtraAttributeValues:v}){s(this.process);let y=await a(p,this),b=i(m),x;if(x=Array.isArray(y)&&this.fs.lstatSync(n).isDirectory()?o(this.fs.readdirSync(n)).map(e=>c.join(n,e)):n.split(`,`),x.length<1)throw Error(`No file specified!`);let S=x.map(e=>{this.fs.existsSync(e)?this.logger.info(l.magenta(`Reading file "${e}"...`)):(this.logger.error(l.red(`The file path does not exist on disk: ${e}. You can specify the filepath using --file=./examples/transcend.yml`)),this.process.exit(1));try{let n=t(this.fs.readFileSync(e,`utf8`),b,e);return this.logger.info(l.green(`Successfully read in "${e}"`)),{content:n,name:e.split(`/`).pop().replace(`.yml`,``)}}catch(e){this.logger.error(l.red(`The shape of your yaml file is invalid with the following errors: ${e.message}`)),this.process.exit(1)}});if(typeof y==`string`){let[t,...n]=S.map(({content:e})=>e);await f({transcendUrl:d,auth:y,contents:r(t,...n),publishToPrivacyCenter:g,deleteExtraAttributeValues:v,pageSize:h,classifyService:!!_,logger:this.logger})||(this.logger.info(l.red(`Sync encountered errors. View output above for more information, or check out ${e}`)),this.process.exit(1))}else{if(S.length!==1&&S.length!==y.length)throw Error(`Expected list of yml files to be equal to the list of API keys.Got ${S.length} YML file${S.length===1?``:`s`} and ${y.length} API key${y.length===1?``:`s`}`);let t=[];await u(y,async(e,n)=>{let r=`[${n+1}/${y.length}][${e.organizationName}] `;this.logger.info(l.magenta(`~~~\n\n${r}Attempting to push configuration...\n\n~~~`));let i=S.length===1?S[0].content:S.find(t=>t.name===e.organizationName)?.content;if(!i){this.logger.error(l.red(`${r}Failed to find transcend.yml file for organization: "${e.organizationName}".`)),t.push(e.organizationName);return}await f({transcendUrl:d,auth:e.apiKey,contents:i,pageSize:h,publishToPrivacyCenter:g,deleteExtraAttributeValues:v,classifyService:_,logger:this.logger})?this.logger.info(l.green(`${r}Successfully pushed configuration!`)):(this.logger.error(l.red(`${r}Failed to sync configuration.`)),t.push(e.organizationName))}),t.length>0&&(this.logger.info(l.red(`Sync encountered errors for "${t.join(`,`)}". View output above for more information, or check out ${e}`)),this.process.exit(1))}this.logger.info(l.green(`Successfully synced yaml file to Transcend! View at ${e}`))}export{p as push};
2
- //# sourceMappingURL=impl-BVcy_GYa.mjs.map
1
+ import{r as e}from"./constants-boymUaFC.mjs";import{r as t}from"./readTranscendYaml-BfqQbPiT.mjs";import{n,t as r}from"./mergeTranscendInputs-B7WjxYMN.mjs";import{t as i}from"./parseVariablesFromString-6TYW65LF.mjs";import{t as a}from"./validateTranscendAuth-D-dDINof.mjs";import{t as o}from"./listFiles-DDGCBdtx.mjs";import{t as s}from"./done-input-validation-LiTaCEzF.mjs";import c from"node:path";import l from"colors";import{mapSeries as u}from"@transcend-io/utils";import{buildTranscendGraphQLClient as d}from"@transcend-io/sdk";async function f({transcendUrl:e,auth:t,pageSize:r,publishToPrivacyCenter:i,contents:a,deleteExtraAttributeValues:o=!1,classifyService:s=!1,logger:c}){let u=d(e,t);try{let e=await n(a,u,{pageSize:r,publishToPrivacyCenter:i,classifyService:s,deleteExtraAttributeValues:o,logger:c});return e.success||e.errors.forEach(({resource:e,item:t,message:n})=>{c.error(l.red(`Failed to sync ${e}${t?` "${t}"`:``}: ${n}`))}),e.success}catch(e){return c.error(l.red(`An unexpected error occurred syncing the schema: ${e.message}`)),!1}}async function p({file:n=`./transcend.yml`,transcendUrl:d,auth:p,variables:m,pageSize:h,publishToPrivacyCenter:g,classifyService:_,deleteExtraAttributeValues:v}){s(this.process);let y=await a(p,this),b=i(m),x;if(x=Array.isArray(y)&&this.fs.lstatSync(n).isDirectory()?o(this.fs.readdirSync(n)).map(e=>c.join(n,e)):n.split(`,`),x.length<1)throw Error(`No file specified!`);let S=x.map(e=>{this.fs.existsSync(e)?this.logger.info(l.magenta(`Reading file "${e}"...`)):(this.logger.error(l.red(`The file path does not exist on disk: ${e}. You can specify the filepath using --file=./examples/transcend.yml`)),this.process.exit(1));try{let n=t(this.fs.readFileSync(e,`utf8`),b,e);return this.logger.info(l.green(`Successfully read in "${e}"`)),{content:n,name:e.split(`/`).pop().replace(`.yml`,``)}}catch(e){this.logger.error(l.red(`The shape of your yaml file is invalid with the following errors: ${e.message}`)),this.process.exit(1)}});if(typeof y==`string`){let[t,...n]=S.map(({content:e})=>e);await f({transcendUrl:d,auth:y,contents:r(t,...n),publishToPrivacyCenter:g,deleteExtraAttributeValues:v,pageSize:h,classifyService:!!_,logger:this.logger})||(this.logger.info(l.red(`Sync encountered errors. View output above for more information, or check out ${e}`)),this.process.exit(1))}else{if(S.length!==1&&S.length!==y.length)throw Error(`Expected list of yml files to be equal to the list of API keys.Got ${S.length} YML file${S.length===1?``:`s`} and ${y.length} API key${y.length===1?``:`s`}`);let t=[];await u(y,async(e,n)=>{let r=`[${n+1}/${y.length}][${e.organizationName}] `;this.logger.info(l.magenta(`~~~\n\n${r}Attempting to push configuration...\n\n~~~`));let i=S.length===1?S[0].content:S.find(t=>t.name===e.organizationName)?.content;if(!i){this.logger.error(l.red(`${r}Failed to find transcend.yml file for organization: "${e.organizationName}".`)),t.push(e.organizationName);return}await f({transcendUrl:d,auth:e.apiKey,contents:i,pageSize:h,publishToPrivacyCenter:g,deleteExtraAttributeValues:v,classifyService:_,logger:this.logger})?this.logger.info(l.green(`${r}Successfully pushed configuration!`)):(this.logger.error(l.red(`${r}Failed to sync configuration.`)),t.push(e.organizationName))}),t.length>0&&(this.logger.info(l.red(`Sync encountered errors for "${t.join(`,`)}". View output above for more information, or check out ${e}`)),this.process.exit(1))}this.logger.info(l.green(`Successfully synced yaml file to Transcend! View at ${e}`))}export{p as push};
2
+ //# sourceMappingURL=impl-2YeOxW2m.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-BVcy_GYa.mjs","names":[],"sources":["../src/commands/inventory/push/impl.ts"],"sourcesContent":["import path from 'node:path';\n\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport { mapSeries } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport { TranscendInput } from '../../../codecs.js';\nimport { ADMIN_DASH_INTEGRATIONS } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { validateTranscendAuth, filterFileNames } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { syncConfigurationToTranscend } from '../../../lib/graphql/index.js';\nimport { parseVariablesFromString } from '../../../lib/helpers/parseVariablesFromString.js';\nimport { mergeTranscendInputs } from '../../../lib/mergeTranscendInputs.js';\nimport { parseTranscendYaml } from '../../../lib/readTranscendYaml.js';\n\n/**\n * Sync configuration to Transcend\n *\n * @param options - Options\n * @returns True if synced successfully, false if error occurs\n */\nasync function syncConfiguration({\n transcendUrl,\n auth,\n pageSize,\n publishToPrivacyCenter,\n contents,\n deleteExtraAttributeValues = false,\n classifyService = false,\n logger,\n}: {\n /** Transcend YAML */\n contents: TranscendInput;\n /** Transcend URL */\n transcendUrl: string;\n /** API key */\n auth: string;\n /** Page size */\n pageSize: number;\n /** Skip privacy center publish step */\n publishToPrivacyCenter: boolean;\n /** classify data flow service if missing */\n classifyService?: boolean;\n /** Delete attributes when syncing */\n deleteExtraAttributeValues?: boolean;\n /** Logger for reporting sync progress and errors */\n logger: LocalContext['logger'];\n}): Promise<boolean> {\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Sync to Transcend\n try {\n const result = await syncConfigurationToTranscend(contents, client, {\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n logger,\n });\n if (!result.success) {\n result.errors.forEach(({ resource, item, message }) => {\n logger.error(\n colors.red(`Failed to sync ${resource}${item ? ` \"${item}\"` : ''}: ${message}`),\n );\n });\n }\n return result.success;\n } catch (err) {\n logger.error(colors.red(`An unexpected error occurred syncing the schema: ${err.message}`));\n return false;\n }\n}\n\nexport interface PushCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n pageSize: number;\n variables: string;\n publishToPrivacyCenter: boolean;\n classifyService: boolean;\n deleteExtraAttributeValues: boolean;\n}\n\nexport async function push(\n this: LocalContext,\n {\n file = './transcend.yml',\n transcendUrl,\n auth,\n variables,\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n }: PushCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth, this);\n\n const vars = parseVariablesFromString(variables);\n\n // check if we are being passed a list of API keys and a list of files\n let fileList: string[];\n if (Array.isArray(apiKeyOrList) && this.fs.lstatSync(file).isDirectory()) {\n fileList = filterFileNames(this.fs.readdirSync(file)).map((filePath) =>\n path.join(file, filePath),\n );\n } else {\n fileList = file.split(',');\n }\n\n // Ensure at least one file is parsed\n if (fileList.length < 1) {\n throw new Error('No file specified!');\n }\n\n // eslint-disable-next-line array-callback-return,consistent-return\n const transcendInputs = fileList.map((filePath) => {\n // Ensure yaml file exists on disk\n if (!this.fs.existsSync(filePath)) {\n this.logger.error(\n colors.red(\n `The file path does not exist on disk: ${filePath}. You can specify the filepath using --file=./examples/transcend.yml`,\n ),\n );\n this.process.exit(1);\n } else {\n this.logger.info(colors.magenta(`Reading file \"${filePath}\"...`));\n }\n\n try {\n // Read in the yaml file and validate it's shape\n const newContents = parseTranscendYaml(\n this.fs.readFileSync(filePath, 'utf8'),\n vars,\n filePath,\n );\n this.logger.info(colors.green(`Successfully read in \"${filePath}\"`));\n return {\n content: newContents,\n name: filePath.split('/').pop()!.replace('.yml', ''),\n };\n } catch (err) {\n this.logger.error(\n colors.red(\n `The shape of your yaml file is invalid with the following errors: ${err.message}`,\n ),\n );\n this.process.exit(1);\n }\n });\n\n // process a single API key\n if (typeof apiKeyOrList === 'string') {\n // if passed multiple inputs, merge them together\n const [base, ...rest] = transcendInputs.map(({ content }) => content);\n const contents = mergeTranscendInputs(base, ...rest);\n\n // sync the configuration\n const success = await syncConfiguration({\n transcendUrl,\n auth: apiKeyOrList,\n contents,\n publishToPrivacyCenter,\n deleteExtraAttributeValues,\n pageSize,\n classifyService: !!classifyService,\n logger: this.logger,\n });\n\n // exist with error code\n if (!success) {\n this.logger.info(\n colors.red(\n `Sync encountered errors. View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n this.process.exit(1);\n }\n } else {\n // if passed multiple inputs, expect them to be one per instance\n if (transcendInputs.length !== 1 && transcendInputs.length !== apiKeyOrList.length) {\n throw new Error(\n 'Expected list of yml files to be equal to the list of API keys.' +\n `Got ${transcendInputs.length} YML file${\n transcendInputs.length === 1 ? '' : 's'\n } and ${apiKeyOrList.length} API key${apiKeyOrList.length === 1 ? '' : 's'}`,\n );\n }\n\n const encounteredErrors: string[] = [];\n await mapSeries(apiKeyOrList, async (apiKey, ind) => {\n const prefix = `[${ind + 1}/${apiKeyOrList.length}][${apiKey.organizationName}] `;\n this.logger.info(\n colors.magenta(`~~~\\n\\n${prefix}Attempting to push configuration...\\n\\n~~~`),\n );\n\n // use the merged contents if 1 yml passed, else use the contents that map to that organization\n const useContents =\n transcendInputs.length === 1\n ? transcendInputs[0].content\n : transcendInputs.find((input) => input.name === apiKey.organizationName)?.content;\n\n // Throw error if cannot find a yml file matching that organization name\n if (!useContents) {\n this.logger.error(\n colors.red(\n `${prefix}Failed to find transcend.yml file for organization: \"${apiKey.organizationName}\".`,\n ),\n );\n encounteredErrors.push(apiKey.organizationName);\n return;\n }\n\n const success = await syncConfiguration({\n transcendUrl,\n auth: apiKey.apiKey,\n contents: useContents,\n pageSize,\n publishToPrivacyCenter,\n deleteExtraAttributeValues,\n classifyService,\n logger: this.logger,\n });\n\n if (success) {\n this.logger.info(colors.green(`${prefix}Successfully pushed configuration!`));\n } else {\n this.logger.error(colors.red(`${prefix}Failed to sync configuration.`));\n encounteredErrors.push(apiKey.organizationName);\n }\n });\n\n if (encounteredErrors.length > 0) {\n this.logger.info(\n colors.red(\n `Sync encountered errors for \"${encounteredErrors.join(\n ',',\n )}\". View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n this.process.exit(1);\n }\n }\n\n // Indicate success\n this.logger.info(\n colors.green(`Successfully synced yaml file to Transcend! View at ${ADMIN_DASH_INTEGRATIONS}`),\n );\n}\n"],"mappings":"shBAsBA,eAAe,EAAkB,CAC/B,eACA,OACA,WACA,yBACA,WACA,6BAA6B,GAC7B,kBAAkB,GAClB,UAkBmB,CACnB,IAAM,EAAS,EAA4B,E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K,OAAO,KAAK,EAAO,MAAM,GAAG,EAAO,oCAAoC,CAAC,EAE7E,KAAK,OAAO,MAAM,EAAO,IAAI,GAAG,EAAO,+BAA+B,CAAC,CACvE,EAAkB,KAAK,EAAO,iBAAiB,GAEjD,CAEE,EAAkB,OAAS,IAC7B,KAAK,OAAO,KACV,EAAO,IACL,gCAAgC,EAAkB,KAChD,IACD,CAAC,0DAA0D,IAC7D,CACF,CAED,KAAK,QAAQ,KAAK,EAAE,EAKxB,KAAK,OAAO,KACV,EAAO,MAAM,uDAAuD,IAA0B,CAC/F"}
1
+ {"version":3,"file":"impl-2YeOxW2m.mjs","names":[],"sources":["../src/commands/inventory/push/impl.ts"],"sourcesContent":["import path from 'node:path';\n\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport { mapSeries } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport { TranscendInput } from '../../../codecs.js';\nimport { ADMIN_DASH_INTEGRATIONS } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { validateTranscendAuth, filterFileNames } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { syncConfigurationToTranscend } from '../../../lib/graphql/index.js';\nimport { parseVariablesFromString } from '../../../lib/helpers/parseVariablesFromString.js';\nimport { mergeTranscendInputs } from '../../../lib/mergeTranscendInputs.js';\nimport { parseTranscendYaml } from '../../../lib/readTranscendYaml.js';\n\n/**\n * Sync configuration to Transcend\n *\n * @param options - Options\n * @returns True if synced successfully, false if error occurs\n */\nasync function syncConfiguration({\n transcendUrl,\n auth,\n pageSize,\n publishToPrivacyCenter,\n contents,\n deleteExtraAttributeValues = false,\n classifyService = false,\n logger,\n}: {\n /** Transcend YAML */\n contents: TranscendInput;\n /** Transcend URL */\n transcendUrl: string;\n /** API key */\n auth: string;\n /** Page size */\n pageSize: number;\n /** Skip privacy center publish step */\n publishToPrivacyCenter: boolean;\n /** classify data flow service if missing */\n classifyService?: boolean;\n /** Delete attributes when syncing */\n deleteExtraAttributeValues?: boolean;\n /** Logger for reporting sync progress and errors */\n logger: LocalContext['logger'];\n}): Promise<boolean> {\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Sync to Transcend\n try {\n const result = await syncConfigurationToTranscend(contents, client, {\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n logger,\n });\n if (!result.success) {\n result.errors.forEach(({ resource, item, message }) => {\n logger.error(\n colors.red(`Failed to sync ${resource}${item ? ` \"${item}\"` : ''}: ${message}`),\n );\n });\n }\n return result.success;\n } catch (err) {\n logger.error(colors.red(`An unexpected error occurred syncing the schema: ${err.message}`));\n return false;\n }\n}\n\nexport interface PushCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n pageSize: number;\n variables: string;\n publishToPrivacyCenter: boolean;\n classifyService: boolean;\n deleteExtraAttributeValues: boolean;\n}\n\nexport async function push(\n this: LocalContext,\n {\n file = './transcend.yml',\n transcendUrl,\n auth,\n variables,\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n }: PushCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth, this);\n\n const vars = parseVariablesFromString(variables);\n\n // check if we are being passed a list of API keys and a list of files\n let fileList: string[];\n if (Array.isArray(apiKeyOrList) && this.fs.lstatSync(file).isDirectory()) {\n fileList = filterFileNames(this.fs.readdirSync(file)).map((filePath) =>\n path.join(file, filePath),\n );\n } else {\n fileList = file.split(',');\n }\n\n // Ensure at least one file is parsed\n if (fileList.length < 1) {\n throw new Error('No file specified!');\n }\n\n // eslint-disable-next-line array-callback-return,consistent-return\n const transcendInputs = fileList.map((filePath) => {\n // Ensure yaml file exists on disk\n if (!this.fs.existsSync(filePath)) {\n this.logger.error(\n colors.red(\n `The file path does not exist on disk: ${filePath}. You can specify the filepath using --file=./examples/transcend.yml`,\n ),\n );\n this.process.exit(1);\n } else {\n this.logger.info(colors.magenta(`Reading file \"${filePath}\"...`));\n }\n\n try {\n // Read in the yaml file and validate it's shape\n const newContents = parseTranscendYaml(\n this.fs.readFileSync(filePath, 'utf8'),\n vars,\n filePath,\n );\n this.logger.info(colors.green(`Successfully read in \"${filePath}\"`));\n return {\n content: newContents,\n name: filePath.split('/').pop()!.replace('.yml', ''),\n };\n } catch (err) {\n this.logger.error(\n colors.red(\n `The shape of your yaml file is invalid with the following errors: ${err.message}`,\n ),\n );\n this.process.exit(1);\n }\n });\n\n // process a single API key\n if (typeof apiKeyOrList === 'string') {\n // if passed multiple inputs, merge them together\n const [base, ...rest] = transcendInputs.map(({ content }) => content);\n const contents = mergeTranscendInputs(base, ...rest);\n\n // sync the configuration\n const success = await syncConfiguration({\n transcendUrl,\n auth: apiKeyOrList,\n contents,\n publishToPrivacyCenter,\n deleteExtraAttributeValues,\n pageSize,\n classifyService: !!classifyService,\n logger: this.logger,\n });\n\n // exist with error code\n if (!success) {\n this.logger.info(\n colors.red(\n `Sync encountered errors. View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n this.process.exit(1);\n }\n } else {\n // if passed multiple inputs, expect them to be one per instance\n if (transcendInputs.length !== 1 && transcendInputs.length !== apiKeyOrList.length) {\n throw new Error(\n 'Expected list of yml files to be equal to the list of API keys.' +\n `Got ${transcendInputs.length} YML file${\n transcendInputs.length === 1 ? '' : 's'\n } and ${apiKeyOrList.length} API key${apiKeyOrList.length === 1 ? '' : 's'}`,\n );\n }\n\n const encounteredErrors: string[] = [];\n await mapSeries(apiKeyOrList, async (apiKey, ind) => {\n const prefix = `[${ind + 1}/${apiKeyOrList.length}][${apiKey.organizationName}] `;\n this.logger.info(\n colors.magenta(`~~~\\n\\n${prefix}Attempting to push configuration...\\n\\n~~~`),\n );\n\n // use the merged contents if 1 yml passed, else use the contents that map to that organization\n const useContents =\n transcendInputs.length === 1\n ? transcendInputs[0].content\n : transcendInputs.find((input) => input.name === apiKey.organizationName)?.content;\n\n // Throw error if cannot find a yml file matching that organization name\n if (!useContents) {\n this.logger.error(\n colors.red(\n `${prefix}Failed to find transcend.yml file for organization: \"${apiKey.organizationName}\".`,\n ),\n );\n encounteredErrors.push(apiKey.organizationName);\n return;\n }\n\n const success = await syncConfiguration({\n transcendUrl,\n auth: apiKey.apiKey,\n contents: useContents,\n pageSize,\n publishToPrivacyCenter,\n deleteExtraAttributeValues,\n classifyService,\n logger: this.logger,\n });\n\n if (success) {\n this.logger.info(colors.green(`${prefix}Successfully pushed configuration!`));\n } else {\n this.logger.error(colors.red(`${prefix}Failed to sync configuration.`));\n encounteredErrors.push(apiKey.organizationName);\n }\n });\n\n if (encounteredErrors.length > 0) {\n this.logger.info(\n colors.red(\n `Sync encountered errors for \"${encounteredErrors.join(\n ',',\n )}\". View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n this.process.exit(1);\n }\n }\n\n // Indicate success\n this.logger.info(\n colors.green(`Successfully synced yaml file to Transcend! View at ${ADMIN_DASH_INTEGRATIONS}`),\n );\n}\n"],"mappings":"shBAsBA,eAAe,EAAkB,CAC/B,eACA,OACA,WACA,yBACA,WACA,6BAA6B,GAC7B,kBAAkB,GAClB,UAkBmB,CACnB,IAAM,EAAS,EAA4B,EAAc,EAAK,CAG9D,GAAI,CACF,IAAM,EAAS,MAAM,EAA6B,EAAU,EAAQ,CAClE,WACA,yBACA,kBACA,6BACA,SACD,CAAC,CAQF,OAPK,EAAO,SACV,EAAO,OAAO,SAAS,CAAE,WAAU,OAAM,aAAc,CACrD,EAAO,MACL,EAAO,IAAI,kBAAkB,IAAW,EAAO,KAAK,EAAK,GAAK,GAAG,IAAI,IAAU,CAChF,EACD,CAEG,EAAO,cACP,EAAK,CAEZ,OADA,EAAO,MAAM,EAAO,IAAI,oDAAoD,EAAI,UAAU,CAAC,CACpF,IAeX,eAAsB,EAEpB,CACE,OAAO,kBACP,eACA,OACA,YACA,WACA,yBACA,kBACA,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js";import{t}from"./done-input-validation-LiTaCEzF.mjs";async function n({auth:n,transcendUrl:r,file:i,concurrency:a,actions:o,sombraAuth:s}){t(this.process),await e({file:i,transcendUrl:r,concurrency:a,requestActions:o,auth:n,sombraAuth:s})}export{n as pullIdentifiers};
2
- //# sourceMappingURL=impl-QdSegO65.mjs.map
1
+ import{t as e}from"./pullManualEnrichmentIdentifiersToCsv-BSUXUp8v.mjs";import{t}from"./done-input-validation-LiTaCEzF.mjs";async function n({auth:n,transcendUrl:r,file:i,concurrency:a,actions:o,sombraAuth:s}){t(this.process),await e({file:i,transcendUrl:r,concurrency:a,requestActions:o,auth:n,sombraAuth:s})}export{n as pullIdentifiers};
2
+ //# sourceMappingURL=impl-5Pko18bX.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-QdSegO65.mjs","names":[],"sources":["../src/commands/request/preflight/pull-identifiers/impl.ts"],"sourcesContent":["import type { RequestAction } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../../context.js';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation.js';\nimport { pullManualEnrichmentIdentifiersToCsv } from '../../../../lib/manual-enrichment/index.js';\n\nexport interface PullIdentifiersCommandFlags {\n auth: string;\n sombraAuth?: string;\n transcendUrl: string;\n file: string;\n actions?: RequestAction[];\n concurrency: number;\n}\n\nexport async function pullIdentifiers(\n this: LocalContext,\n { auth, transcendUrl, file, concurrency, actions, sombraAuth }: PullIdentifiersCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await pullManualEnrichmentIdentifiersToCsv({\n file,\n transcendUrl,\n concurrency,\n requestActions: actions,\n auth,\n sombraAuth,\n });\n}\n"],"mappings":"4HAeA,eAAsB,EAEpB,CAAE,OAAM,eAAc,OAAM,cAAa,UAAS,cACnC,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAAqC,CACzC,OACA,eACA,cACA,eAAgB,EAChB,OACA,aACD,CAAC"}
1
+ {"version":3,"file":"impl-5Pko18bX.mjs","names":[],"sources":["../src/commands/request/preflight/pull-identifiers/impl.ts"],"sourcesContent":["import type { RequestAction } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../../context.js';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation.js';\nimport { pullManualEnrichmentIdentifiersToCsv } from '../../../../lib/manual-enrichment/index.js';\n\nexport interface PullIdentifiersCommandFlags {\n auth: string;\n sombraAuth?: string;\n transcendUrl: string;\n file: string;\n actions?: RequestAction[];\n concurrency: number;\n}\n\nexport async function pullIdentifiers(\n this: LocalContext,\n { auth, transcendUrl, file, concurrency, actions, sombraAuth }: PullIdentifiersCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await pullManualEnrichmentIdentifiersToCsv({\n file,\n transcendUrl,\n concurrency,\n requestActions: actions,\n auth,\n sombraAuth,\n });\n}\n"],"mappings":"4HAeA,eAAsB,EAEpB,CAAE,OAAM,eAAc,OAAM,cAAa,UAAS,cACnC,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAAqC,CACzC,OACA,eACA,cACA,eAAgB,EAChB,OACA,aACD,CAAC"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./skipPreflightJobs-KdcSw8Td.mjs";import{t}from"./done-input-validation-LiTaCEzF.mjs";async function n({auth:n,transcendUrl:r,enricherIds:i}){t(this.process),await e({transcendUrl:r,auth:n,enricherIds:i})}export{n as skipPreflightJobs};
2
- //# sourceMappingURL=impl-b4KAEVci.mjs.map
1
+ import{t as e}from"./skipPreflightJobs-B0YG7mhP.mjs";import{t}from"./done-input-validation-LiTaCEzF.mjs";async function n({auth:n,transcendUrl:r,enricherIds:i}){t(this.process),await e({transcendUrl:r,auth:n,enricherIds:i})}export{n as skipPreflightJobs};
2
+ //# sourceMappingURL=impl-7YqcGwra.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-b4KAEVci.mjs","names":["skipPreflightJobsHelper"],"sources":["../src/commands/request/skip-preflight-jobs/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { skipPreflightJobs as skipPreflightJobsHelper } from '../../../lib/requests/index.js';\n\nexport interface SkipPreflightJobsCommandFlags {\n auth: string;\n enricherIds: string[];\n transcendUrl: string;\n}\n\nexport async function skipPreflightJobs(\n this: LocalContext,\n { auth, transcendUrl, enricherIds }: SkipPreflightJobsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await skipPreflightJobsHelper({\n transcendUrl,\n auth,\n enricherIds,\n });\n}\n"],"mappings":"yGAUA,eAAsB,EAEpB,CAAE,OAAM,eAAc,eACP,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAMA,EAAwB,CAC5B,eACA,OACA,cACD,CAAC"}
1
+ {"version":3,"file":"impl-7YqcGwra.mjs","names":["skipPreflightJobsHelper"],"sources":["../src/commands/request/skip-preflight-jobs/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { skipPreflightJobs as skipPreflightJobsHelper } from '../../../lib/requests/index.js';\n\nexport interface SkipPreflightJobsCommandFlags {\n auth: string;\n enricherIds: string[];\n transcendUrl: string;\n}\n\nexport async function skipPreflightJobs(\n this: LocalContext,\n { auth, transcendUrl, enricherIds }: SkipPreflightJobsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await skipPreflightJobsHelper({\n transcendUrl,\n auth,\n enricherIds,\n });\n}\n"],"mappings":"yGAUA,eAAsB,EAEpB,CAAE,OAAM,eAAc,eACP,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAMA,EAAwB,CAC5B,eACA,OACA,cACD,CAAC"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./buildXdiSyncEndpoint-CAal3Xc4.mjs";import{t}from"./validateTranscendAuth-D-dDINof.mjs";import{t as n}from"./done-input-validation-LiTaCEzF.mjs";import r from"colors";async function i({auth:i,xdiLocation:a,file:o,removeIpAddresses:s,domainBlockList:c,xdiAllowedCommands:l,transcendUrl:u}){n(this.process);let{syncGroups:d,html:f}=await e(await t(i,this),{xdiLocation:a,transcendUrl:u,removeIpAddresses:s,domainBlockList:c.length>0?c:void 0,xdiAllowedCommands:l});this.logger.info(r.green(`Successfully constructed sync endpoint for sync groups: ${JSON.stringify(d,null,2)}`)),this.fs.writeFileSync(o,f),this.logger.info(r.green(`Wrote configuration to file "${o}"!`))}export{i as buildXdiSyncEndpoint};
2
- //# sourceMappingURL=impl-DUg1sDwg.mjs.map
1
+ import{n as e}from"./buildXdiSyncEndpoint-CwABTp_y.mjs";import{t}from"./validateTranscendAuth-D-dDINof.mjs";import{t as n}from"./done-input-validation-LiTaCEzF.mjs";import r from"colors";async function i({auth:i,xdiLocation:a,file:o,removeIpAddresses:s,domainBlockList:c,xdiAllowedCommands:l,transcendUrl:u}){n(this.process);let{syncGroups:d,html:f}=await e(await t(i,this),{xdiLocation:a,transcendUrl:u,removeIpAddresses:s,domainBlockList:c.length>0?c:void 0,xdiAllowedCommands:l});this.logger.info(r.green(`Successfully constructed sync endpoint for sync groups: ${JSON.stringify(d,null,2)}`)),this.fs.writeFileSync(o,f),this.logger.info(r.green(`Wrote configuration to file "${o}"!`))}export{i as buildXdiSyncEndpoint};
2
+ //# sourceMappingURL=impl-B5-UipRP.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-DUg1sDwg.mjs","names":["buildXdiSyncEndpointHelper"],"sources":["../src/commands/consent/build-xdi-sync-endpoint/impl.ts"],"sourcesContent":["import colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { validateTranscendAuth } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { buildXdiSyncEndpoint as buildXdiSyncEndpointHelper } from '../../../lib/consent-manager/index.js';\n\nexport interface BuildXdiSyncEndpointCommandFlags {\n auth: string;\n xdiLocation: string;\n file: string;\n removeIpAddresses: boolean;\n domainBlockList: string[];\n xdiAllowedCommands: string;\n transcendUrl: string;\n}\n\nexport async function buildXdiSyncEndpoint(\n this: LocalContext,\n {\n auth,\n xdiLocation,\n file,\n removeIpAddresses,\n domainBlockList,\n xdiAllowedCommands,\n transcendUrl,\n }: BuildXdiSyncEndpointCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth, this);\n\n // Build the sync endpoint\n const { syncGroups, html } = await buildXdiSyncEndpointHelper(apiKeyOrList, {\n xdiLocation,\n transcendUrl,\n removeIpAddresses,\n domainBlockList: domainBlockList.length > 0 ? domainBlockList : undefined,\n xdiAllowedCommands,\n });\n\n // Log success\n this.logger.info(\n colors.green(\n `Successfully constructed sync endpoint for sync groups: ${JSON.stringify(\n syncGroups,\n null,\n 2,\n )}`,\n ),\n );\n\n // Write to disk\n this.fs.writeFileSync(file, html);\n this.logger.info(colors.green(`Wrote configuration to file \"${file}\"!`));\n}\n"],"mappings":"2LAiBA,eAAsB,EAEpB,CACE,OACA,cACA,OACA,oBACA,kBACA,qBACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,CAMjC,GAAM,CAAE,aAAY,QAAS,MAAMA,EAA2B,MAHnC,EAAsB,EAAM,KAAK,CAGgB,CAC1E,cACA,eACA,oBACA,gBAAiB,EAAgB,OAAS,EAAI,EAAkB,IAAA,GAChE,qBACD,CAAC,CAGF,KAAK,OAAO,KACV,EAAO,MACL,2DAA2D,KAAK,UAC9D,EACA,KACA,EACD,GACF,CACF,CAGD,KAAK,GAAG,cAAc,EAAM,EAAK,CACjC,KAAK,OAAO,KAAK,EAAO,MAAM,gCAAgC,EAAK,IAAI,CAAC"}
1
+ {"version":3,"file":"impl-B5-UipRP.mjs","names":["buildXdiSyncEndpointHelper"],"sources":["../src/commands/consent/build-xdi-sync-endpoint/impl.ts"],"sourcesContent":["import colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { validateTranscendAuth } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { buildXdiSyncEndpoint as buildXdiSyncEndpointHelper } from '../../../lib/consent-manager/index.js';\n\nexport interface BuildXdiSyncEndpointCommandFlags {\n auth: string;\n xdiLocation: string;\n file: string;\n removeIpAddresses: boolean;\n domainBlockList: string[];\n xdiAllowedCommands: string;\n transcendUrl: string;\n}\n\nexport async function buildXdiSyncEndpoint(\n this: LocalContext,\n {\n auth,\n xdiLocation,\n file,\n removeIpAddresses,\n domainBlockList,\n xdiAllowedCommands,\n transcendUrl,\n }: BuildXdiSyncEndpointCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth, this);\n\n // Build the sync endpoint\n const { syncGroups, html } = await buildXdiSyncEndpointHelper(apiKeyOrList, {\n xdiLocation,\n transcendUrl,\n removeIpAddresses,\n domainBlockList: domainBlockList.length > 0 ? domainBlockList : undefined,\n xdiAllowedCommands,\n });\n\n // Log success\n this.logger.info(\n colors.green(\n `Successfully constructed sync endpoint for sync groups: ${JSON.stringify(\n syncGroups,\n null,\n 2,\n )}`,\n ),\n );\n\n // Write to disk\n this.fs.writeFileSync(file, html);\n this.logger.info(colors.green(`Wrote configuration to file \"${file}\"!`));\n}\n"],"mappings":"2LAiBA,eAAsB,EAEpB,CACE,OACA,cACA,OACA,oBACA,kBACA,qBACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,CAMjC,GAAM,CAAE,aAAY,QAAS,MAAMA,EAA2B,MAHnC,EAAsB,EAAM,KAAK,CAGgB,CAC1E,cACA,eACA,oBACA,gBAAiB,EAAgB,OAAS,EAAI,EAAkB,IAAA,GAChE,qBACD,CAAC,CAGF,KAAK,OAAO,KACV,EAAO,MACL,2DAA2D,KAAK,UAC9D,EACA,KACA,EACD,GACF,CACF,CAGD,KAAK,GAAG,cAAc,EAAM,EAAK,CACjC,KAAK,OAAO,KAAK,EAAO,MAAM,gCAAgC,EAAK,IAAI,CAAC"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./buildExamples-1I3xKR1X.mjs";import{r as t}from"./policyEngineCliError-CZrOHhLv.mjs";import{a as n,c as r,g as i,i as a}from"./policy-project-discovery-B4cFXUlA.mjs";import{r as o,t as s}from"./runOpa-ojIqU1tO.mjs";import{n as c,t as l}from"./policy-bundle-manifest-RgsjPnfI.mjs";import{i as u,n as d,t as f}from"./printResult-Dmwv78e7.mjs";import{t as p}from"./formatPolicyBundleVersionSummary-DCHl1Vhy.mjs";import{n as m}from"./resolveBundleIdByName-BPrMkU0w.mjs";import{n as h}from"./inquirer-BU5IpgA8.mjs";import{t as g}from"./done-input-validation-LiTaCEzF.mjs";import{r as _}from"./prompts-BhXfYD6g.mjs";import{t as v}from"./command-output-BJcDRXNr.mjs";import y,{join as b}from"node:path";import x from"colors";import{spawnSync as S}from"node:child_process";import C from"node:fs";import w from"node:os";import{gunzipSync as T}from"node:zlib";import{MAX_BUNDLE_COMPRESSED_BYTES as E,MAX_BUNDLE_DECOMPRESSED_BYTES as D}from"@transcend-io/utils";import O from"fast-glob";function k(e){let t=O.sync(`**/*.rego`,{cwd:e,onlyFiles:!0,dot:!1}).sort(),n=y.join(e,r),{publishableRegoPaths:i}=c(C.existsSync(n)?C.readFileSync(n,`utf8`):void 0,t.map(t=>({path:t,contents:C.readFileSync(y.join(e,t),`utf8`)})));return{entries:[r,...i]}}async function A(e){let t=y.join(w.tmpdir(),`transcend-policy-bundle-build-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`);try{let{code:n,stderr:r}=await s([`build`,`--ignore`,`*_test.rego`,`-b`,`-o`,t,`.`],{cwd:e});if(n!==0)throw Error(r.trim()||`opa build failed with exit code ${n}`)}finally{C.existsSync(t)&&C.unlinkSync(t)}}function j(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t%1==0?t.toFixed(0):t.toFixed(1)} KiB`;let n=t/1024;return`${n%1==0?n.toFixed(0):n.toFixed(1)} MiB`}async function M(e){o();let t=y.resolve(e);if(!C.existsSync(t)||!C.statSync(t).isDirectory())throw Error(`Policy directory does not exist or is not a directory: ${t}`);let{entries:n}=k(t),{code:r,stderr:i}=await s([`check`,`--strict`,t]);if(r!==0)throw Error(i.trim()||`opa check failed with exit code ${r}`);await A(t);let a=y.join(w.tmpdir(),`transcend-policy-bundle-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`),c=S(`tar`,[`-czf`,a,`-C`,t,...n],{env:{...process.env,COPYFILE_DISABLE:`1`},encoding:`utf8`});if(c.status!==0)throw Error(`Failed to create policy bundle archive: ${c.stderr.trim()||`tar failed`}`);let l=C.readFileSync(a);if(l.byteLength>E)throw C.unlinkSync(a),Error(`Policy bundle exceeds the ${j(E)} compressed upload limit (bundle is ${j(l.byteLength)}). The server also rejects decompressed bundles larger than ${j(D)}.`);let u=T(l);if(u.byteLength>D)throw C.unlinkSync(a),Error(`Policy bundle exceeds the ${j(D)} decompressed upload limit (bundle is ${j(u.byteLength)} decompressed).`);return a}function N(e){let t=C.readFileSync(e.bundlePath),n=new FormData;return n.append(`bundle`,new Blob([t],{type:`application/gzip`}),y.basename(e.bundlePath)),n.append(`version`,e.version),e.description&&n.append(`description`,e.description),e.bundleName&&n.append(`bundleName`,e.bundleName),n}function P(e){return e.toISOString().slice(0,19).replace(/[T:]/g,`-`)}function F(e,t=new Date){return`${e}-${P(t)}`}function I(e){return e.template===i.Permissions?!0:e.template===i.Generic?!1:e.roots.some(e=>e===`permissions`||e.startsWith(`permissions/`))}function L(e,t){let r=I(t),i=e===n;if(r&&!i)return`This directory looks like a Permissions API policy, but --remote-bundle-name is "${e}". Permissions API only loads the remote bundle named "${n}". Upload still succeeds; pass --remote-bundle-name=${n} if that is the intended path.`;if(!r&&i)return`--remote-bundle-name=${n} reserves the Permissions API path. Upload treats all bundles the same; only that fixed name is queried by the Permissions API. Continue only if you intend this bundle for the Permissions API.`}async function R({"remote-bundle-name":n,auth:i,"transcend-url":o,version:s,description:c,json:y,yes:S,debug:C=!1},w){g(this.process),t(C);let T=v(this.logger,y),E=a(this.process.cwd(),w),D=s??F(n),O=u(o,i),k=_({json:y,noInteractive:!1},this.process.stdin.isTTY,this.process.stderr.isTTY),A;try{T.info(x.green(`Building policy bundle from ${E}...`)),A=await M(E);try{let e=b(E,r),t=L(n,l(this.fs.readFileSync(e,`utf8`)));t&&T.warn(x.yellow(t))}catch{}let t=await m(O,n),i;if(t){T.info(x.green(`Uploading new version for bundle "${n}"...`));let e=N({bundlePath:A,version:D,description:c});i=await d(O.post(`v1/policy-engine/policy-bundles/${t}/versions`,{body:e}).json())}else{if(!k&&!S){this.logger.error(x.red(`Cannot create a new bundle in non-interactive or JSON mode; pass --yes to confirm.`)),this.process.exit(1);return}if(!S&&(T.warn(x.yellow(`No policy bundle named "${n}" exists for this organization.`)),!await h({message:`No policy bundle named "${n}" exists. Create a new bundle and upload its first version?`}))){T.info(x.yellow(`Publish cancelled.`));return}T.info(x.green(`Creating bundle "${n}" and uploading first version...`));let e=N({bundlePath:A,version:D,description:c,bundleName:n});i=await d(O.post(`v1/policy-engine/policy-bundles`,{body:e}).json())}f(this.process.stdout,{json:y,data:i,renderTable:()=>p(i.version)}),T.info(x.green(`Policy bundle version uploaded successfully.`));let a=e([`policy`,`activate`],{version:i.version.version,"remote-bundle-name":n});T.info(x.yellow(`Publishing a policy does not activate it. To activate this version, run:\n ${a}`))}finally{A&&this.fs.existsSync(A)&&this.fs.unlinkSync(A)}}export{R as publish};
2
- //# sourceMappingURL=impl-Dr9Jezjh2.mjs.map
1
+ import{t as e}from"./buildExamples-DB_puA14.mjs";import{r as t}from"./policyEngineCliError-CZrOHhLv.mjs";import{a as n,c as r,g as i,i as a}from"./policy-project-discovery-oc49b2gr.mjs";import{r as o,t as s}from"./runOpa-ojIqU1tO.mjs";import{n as c,t as l}from"./policy-bundle-manifest-B1Herd_n.mjs";import{i as u,n as d,t as f}from"./printResult-Dmwv78e7.mjs";import{t as p}from"./formatPolicyBundleVersionSummary-DCHl1Vhy.mjs";import{n as m}from"./resolveBundleIdByName-BPrMkU0w.mjs";import{n as h}from"./inquirer-jzIQWAvq.mjs";import{t as g}from"./done-input-validation-LiTaCEzF.mjs";import{r as _}from"./prompts-BhXfYD6g.mjs";import{t as v}from"./command-output-BJcDRXNr.mjs";import y,{join as b}from"node:path";import x from"colors";import{spawnSync as S}from"node:child_process";import C from"node:fs";import w from"node:os";import{gunzipSync as T}from"node:zlib";import{MAX_BUNDLE_COMPRESSED_BYTES as E,MAX_BUNDLE_DECOMPRESSED_BYTES as D}from"@transcend-io/utils";import O from"fast-glob";function k(e){let t=O.sync(`**/*.rego`,{cwd:e,onlyFiles:!0,dot:!1}).sort(),n=y.join(e,r),{publishableRegoPaths:i}=c(C.existsSync(n)?C.readFileSync(n,`utf8`):void 0,t.map(t=>({path:t,contents:C.readFileSync(y.join(e,t),`utf8`)})));return{entries:[r,...i]}}async function A(e){let t=y.join(w.tmpdir(),`transcend-policy-bundle-build-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`);try{let{code:n,stderr:r}=await s([`build`,`--ignore`,`*_test.rego`,`-b`,`-o`,t,`.`],{cwd:e});if(n!==0)throw Error(r.trim()||`opa build failed with exit code ${n}`)}finally{C.existsSync(t)&&C.unlinkSync(t)}}function j(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t%1==0?t.toFixed(0):t.toFixed(1)} KiB`;let n=t/1024;return`${n%1==0?n.toFixed(0):n.toFixed(1)} MiB`}async function M(e){o();let t=y.resolve(e);if(!C.existsSync(t)||!C.statSync(t).isDirectory())throw Error(`Policy directory does not exist or is not a directory: ${t}`);let{entries:n}=k(t),{code:r,stderr:i}=await s([`check`,`--strict`,t]);if(r!==0)throw Error(i.trim()||`opa check failed with exit code ${r}`);await A(t);let a=y.join(w.tmpdir(),`transcend-policy-bundle-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`),c=S(`tar`,[`-czf`,a,`-C`,t,...n],{env:{...process.env,COPYFILE_DISABLE:`1`},encoding:`utf8`});if(c.status!==0)throw Error(`Failed to create policy bundle archive: ${c.stderr.trim()||`tar failed`}`);let l=C.readFileSync(a);if(l.byteLength>E)throw C.unlinkSync(a),Error(`Policy bundle exceeds the ${j(E)} compressed upload limit (bundle is ${j(l.byteLength)}). The server also rejects decompressed bundles larger than ${j(D)}.`);let u=T(l);if(u.byteLength>D)throw C.unlinkSync(a),Error(`Policy bundle exceeds the ${j(D)} decompressed upload limit (bundle is ${j(u.byteLength)} decompressed).`);return a}function N(e){let t=C.readFileSync(e.bundlePath),n=new FormData;return n.append(`bundle`,new Blob([t],{type:`application/gzip`}),y.basename(e.bundlePath)),n.append(`version`,e.version),e.description&&n.append(`description`,e.description),e.bundleName&&n.append(`bundleName`,e.bundleName),n}function P(e){return e.toISOString().slice(0,19).replace(/[T:]/g,`-`)}function F(e,t=new Date){return`${e}-${P(t)}`}function I(e){return e.template===i.Permissions?!0:e.template===i.Generic?!1:e.roots.some(e=>e===`permissions`||e.startsWith(`permissions/`))}function L(e,t){let r=I(t),i=e===n;if(r&&!i)return`This directory looks like a Permissions API policy, but --remote-bundle-name is "${e}". Permissions API only loads the remote bundle named "${n}". Upload still succeeds; pass --remote-bundle-name=${n} if that is the intended path.`;if(!r&&i)return`--remote-bundle-name=${n} reserves the Permissions API path. Upload treats all bundles the same; only that fixed name is queried by the Permissions API. Continue only if you intend this bundle for the Permissions API.`}async function R({"remote-bundle-name":n,auth:i,"transcend-url":o,version:s,description:c,json:y,yes:S,debug:C=!1},w){g(this.process),t(C);let T=v(this.logger,y),E=a(this.process.cwd(),w),D=s??F(n),O=u(o,i),k=_({json:y,noInteractive:!1},this.process.stdin.isTTY,this.process.stderr.isTTY),A;try{T.info(x.green(`Building policy bundle from ${E}...`)),A=await M(E);try{let e=b(E,r),t=L(n,l(this.fs.readFileSync(e,`utf8`)));t&&T.warn(x.yellow(t))}catch{}let t=await m(O,n),i;if(t){T.info(x.green(`Uploading new version for bundle "${n}"...`));let e=N({bundlePath:A,version:D,description:c});i=await d(O.post(`v1/policy-engine/policy-bundles/${t}/versions`,{body:e}).json())}else{if(!k&&!S){this.logger.error(x.red(`Cannot create a new bundle in non-interactive or JSON mode; pass --yes to confirm.`)),this.process.exit(1);return}if(!S&&(T.warn(x.yellow(`No policy bundle named "${n}" exists for this organization.`)),!await h({message:`No policy bundle named "${n}" exists. Create a new bundle and upload its first version?`}))){T.info(x.yellow(`Publish cancelled.`));return}T.info(x.green(`Creating bundle "${n}" and uploading first version...`));let e=N({bundlePath:A,version:D,description:c,bundleName:n});i=await d(O.post(`v1/policy-engine/policy-bundles`,{body:e}).json())}f(this.process.stdout,{json:y,data:i,renderTable:()=>p(i.version)}),T.info(x.green(`Policy bundle version uploaded successfully.`));let a=e([`policy`,`activate`],{version:i.version.version,"remote-bundle-name":n});T.info(x.yellow(`Publishing a policy does not activate it. To activate this version, run:\n ${a}`))}finally{A&&this.fs.existsSync(A)&&this.fs.unlinkSync(A)}}export{R as publish};
2
+ //# sourceMappingURL=impl-B8PyNdje2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-Dr9Jezjh2.mjs","names":["fg"],"sources":["../src/commands/policy/helpers/buildOpaBundleTarball.ts","../src/commands/policy/helpers/buildPolicyBundleFormData.ts","../src/commands/policy/helpers/defaultPolicyVersionLabel.ts","../src/lib/policy/policy-publish-hints.ts","../src/commands/policy/publish/impl.ts"],"sourcesContent":["import { spawnSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { gunzipSync } from 'node:zlib';\n\nimport { MAX_BUNDLE_COMPRESSED_BYTES, MAX_BUNDLE_DECOMPRESSED_BYTES } from '@transcend-io/utils';\nimport fg from 'fast-glob';\n\nimport { validatePolicyBundleContents } from '../../../lib/policy/policy-bundle-manifest.js';\nimport { POLICY_MANIFEST_FILENAME } from '../../../lib/policy/policy-scaffold-templates.js';\nimport { assertOpaInstalled } from './assertOpaInstalled.js';\nimport { runOPACapture } from './runOpa.js';\n\n/** Result of collecting publishable entries from a policy bundle directory. */\ninterface PolicyBundleArchiveContents {\n /** Relative paths to include in the upload tarball (manifest first, then rego) */\n entries: string[];\n}\n\n/**\n * Collects `.manifest` and publishable `.rego` files from a policy directory.\n *\n * @param dir - Absolute path to the policy bundle directory\n * @returns Validated archive entries\n */\nfunction collectPolicyBundleArchiveEntries(dir: string): PolicyBundleArchiveContents {\n const regoFiles = fg\n .sync('**/*.rego', {\n cwd: dir,\n onlyFiles: true,\n dot: false,\n })\n .sort();\n const onDiskManifestPath = path.join(dir, POLICY_MANIFEST_FILENAME);\n const { publishableRegoPaths } = validatePolicyBundleContents(\n fs.existsSync(onDiskManifestPath) ? fs.readFileSync(onDiskManifestPath, 'utf8') : undefined,\n regoFiles.map((relativePath) => ({\n path: relativePath,\n contents: fs.readFileSync(path.join(dir, relativePath), 'utf8'),\n })),\n );\n\n return {\n entries: [POLICY_MANIFEST_FILENAME, ...publishableRegoPaths],\n };\n}\n\n/**\n * Verifies that a policy directory compiles end-to-end with `opa build`.\n *\n * The compiled output is discarded — the server receives the `.manifest` +\n * `.rego` archive produced by {@link buildOpaBundleTarball}, not the OPA bundle\n * — but a successful build guarantees the policies compile and link, surfacing\n * errors (syntax, missing imports, undefined references, etc.) before upload.\n *\n * @param dir - Absolute path to the policy bundle directory\n */\nasync function assertBundleCompiles(dir: string): Promise<void> {\n const buildOutputPath = path.join(\n os.tmpdir(),\n `transcend-policy-bundle-build-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`,\n );\n try {\n // Run with `cwd` set to the bundle directory and pass `.` so `opa build`\n // resolves the bundle root correctly. Bundle mode (`-b`) keeps local\n // `input.json` / `input.example.json` fixtures from merging as data.\n // `*_test.rego` files are local-only.\n const { code, stderr } = await runOPACapture(\n ['build', '--ignore', '*_test.rego', '-b', '-o', buildOutputPath, '.'],\n { cwd: dir },\n );\n if (code !== 0) {\n throw new Error(stderr.trim() || `opa build failed with exit code ${code}`);\n }\n } finally {\n if (fs.existsSync(buildOutputPath)) {\n fs.unlinkSync(buildOutputPath);\n }\n }\n}\n\n/**\n * Formats a byte count as a human-readable size with binary units.\n *\n * @param bytes - Number of bytes\n * @returns Human-readable size, e.g. `14 MiB` or `4 KiB`\n */\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) {\n return `${bytes} B`;\n }\n const kib = bytes / 1024;\n if (kib < 1024) {\n return `${kib % 1 === 0 ? kib.toFixed(0) : kib.toFixed(1)} KiB`;\n }\n const mib = kib / 1024;\n return `${mib % 1 === 0 ? mib.toFixed(0) : mib.toFixed(1)} MiB`;\n}\n\n/**\n * Builds a gzip-compressed policy bundle tarball for upload to Transcend.\n *\n * The Policy Engine API expects a plain archive containing `.manifest` and\n * one or more `.rego` files. Local projects author an OPA `.manifest` and it\n * is uploaded directly — no rename at pack time. Before packaging, the\n * manifest is validated (shape + root coverage) and the bundle is validated\n * with `opa check` (strict Rego linting) and `opa build` (full compilation) so\n * failures surface client-side rather than after upload.\n *\n * @param dir - Directory containing `.manifest` and `.rego` policy files\n * @returns Absolute path to the generated `.tar.gz` bundle\n */\nexport async function buildOpaBundleTarball(dir: string): Promise<string> {\n assertOpaInstalled();\n\n const resolvedDir = path.resolve(dir);\n if (!fs.existsSync(resolvedDir) || !fs.statSync(resolvedDir).isDirectory()) {\n throw new Error(`Policy directory does not exist or is not a directory: ${resolvedDir}`);\n }\n\n // Validate the manifest shape and that roots cover every Rego package before\n // invoking OPA, so invalid manifests surface a clear error instead of an\n // opaque `opa build failed with exit code 1`.\n const { entries: archiveEntries } = collectPolicyBundleArchiveEntries(resolvedDir);\n\n // Match the Rego v1 validation the Policy Engine API runs on upload.\n const { code: checkCode, stderr: checkStderr } = await runOPACapture([\n 'check',\n '--strict',\n resolvedDir,\n ]);\n if (checkCode !== 0) {\n throw new Error(checkStderr.trim() || `opa check failed with exit code ${checkCode}`);\n }\n\n // Ensure the bundle compiles end-to-end before packaging for upload.\n await assertBundleCompiles(resolvedDir);\n\n const outputPath = path.join(\n os.tmpdir(),\n `transcend-policy-bundle-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`,\n );\n const tarResult = spawnSync('tar', ['-czf', outputPath, '-C', resolvedDir, ...archiveEntries], {\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n encoding: 'utf8',\n });\n if (tarResult.status !== 0) {\n throw new Error(\n `Failed to create policy bundle archive: ${tarResult.stderr.trim() || 'tar failed'}`,\n );\n }\n\n const compressedBytes = fs.readFileSync(outputPath);\n if (compressedBytes.byteLength > MAX_BUNDLE_COMPRESSED_BYTES) {\n fs.unlinkSync(outputPath);\n throw new Error(\n `Policy bundle exceeds the ${formatBytes(MAX_BUNDLE_COMPRESSED_BYTES)} compressed upload limit ` +\n `(bundle is ${formatBytes(compressedBytes.byteLength)}). ` +\n `The server also rejects decompressed bundles larger than ${formatBytes(MAX_BUNDLE_DECOMPRESSED_BYTES)}.`,\n );\n }\n\n const decompressedBytes = gunzipSync(compressedBytes);\n if (decompressedBytes.byteLength > MAX_BUNDLE_DECOMPRESSED_BYTES) {\n fs.unlinkSync(outputPath);\n throw new Error(\n `Policy bundle exceeds the ${formatBytes(MAX_BUNDLE_DECOMPRESSED_BYTES)} decompressed upload limit ` +\n `(bundle is ${formatBytes(decompressedBytes.byteLength)} decompressed).`,\n );\n }\n\n return outputPath;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\n/** Fields for building a policy bundle upload form. */\nexport interface BuildPolicyBundleFormDataOptions {\n /** Absolute path to the bundle tarball */\n bundlePath: string;\n /** Version label */\n version: string;\n /** Optional description */\n description?: string;\n /** Bundle name (only for create) */\n bundleName?: string;\n}\n\n/**\n * Builds multipart form data for a policy bundle upload.\n *\n * @param options - Upload fields\n * @returns FormData ready for POST\n */\nexport function buildPolicyBundleFormData(options: BuildPolicyBundleFormDataOptions): FormData {\n const bundleBytes = fs.readFileSync(options.bundlePath);\n const form = new FormData();\n form.append(\n 'bundle',\n new Blob([bundleBytes], { type: 'application/gzip' }),\n path.basename(options.bundlePath),\n );\n form.append('version', options.version);\n if (options.description) {\n form.append('description', options.description);\n }\n if (options.bundleName) {\n form.append('bundleName', options.bundleName);\n }\n return form;\n}\n","/**\n * Formats a date as `yyyy-mm-dd-hh-mm-ss` in UTC.\n *\n * @param date - Date to format\n * @returns Timestamp label\n */\nfunction formatPolicyVersionTimestamp(date: Date): string {\n return date.toISOString().slice(0, 19).replace(/[T:]/g, '-');\n}\n\n/**\n * Returns a default version label from the bundle name and current UTC timestamp.\n *\n * @param bundleName - Tenant-unique policy bundle name\n * @param now - Current time (for testing)\n * @returns Version label in `{bundleName}-yyyy-mm-dd-hh-mm-ss` form\n */\nexport function defaultPolicyVersionLabel(bundleName: string, now: Date = new Date()): string {\n return `${bundleName}-${formatPolicyVersionTimestamp(now)}`;\n}\n","import {\n PERMISSIONS_POLICY_BUNDLE_NAME,\n PolicyTemplate,\n type PolicyTemplateName,\n} from './policy-scaffold-templates.js';\n\n/** Inputs used to soft-warn about Permissions vs generic publish naming. */\nexport interface PolicyPublishBundleNameHintInput {\n /** Optional scaffold template from `.manifest` metadata. */\n template?: PolicyTemplateName;\n /** Declared OPA package roots. */\n roots: string[];\n}\n\n/**\n * Whether local authoring signals suggest a Permissions API bundle.\n *\n * Prefers explicit `metadata.transcend.io.template`. Without metadata, falls\n * back to a root that is exactly `permissions` or nested under it.\n *\n * @param input - Manifest template hint and roots\n * @returns Whether the local tree looks Permissions-oriented\n */\nfunction looksLikePermissionsBundle(input: PolicyPublishBundleNameHintInput): boolean {\n if (input.template === PolicyTemplate.Permissions) {\n return true;\n }\n if (input.template === PolicyTemplate.Generic) {\n return false;\n }\n return input.roots.some(\n (root) =>\n root === PERMISSIONS_POLICY_BUNDLE_NAME ||\n root.startsWith(`${PERMISSIONS_POLICY_BUNDLE_NAME}/`),\n );\n}\n\n/**\n * Soft-warning when `--remote-bundle-name` disagrees with Permissions conventions.\n *\n * Upload does not enforce bundle kinds. Permissions API only loads the\n * remote bundle named {@link PERMISSIONS_POLICY_BUNDLE_NAME}.\n *\n * @param bundleName - Value of `--remote-bundle-name`\n * @param input - Local manifest template/roots\n * @returns Warning text, or undefined when names align\n */\nexport function formatPolicyPublishBundleNameHint(\n bundleName: string,\n input: PolicyPublishBundleNameHintInput,\n): string | undefined {\n const permissionsLocal = looksLikePermissionsBundle(input);\n const permissionsRemote = bundleName === PERMISSIONS_POLICY_BUNDLE_NAME;\n\n if (permissionsLocal && !permissionsRemote) {\n return (\n `This directory looks like a Permissions API policy, but --remote-bundle-name is ` +\n `\"${bundleName}\". Permissions API only loads the remote bundle named ` +\n `\"${PERMISSIONS_POLICY_BUNDLE_NAME}\". Upload still succeeds; pass ` +\n `--remote-bundle-name=${PERMISSIONS_POLICY_BUNDLE_NAME} if that is the intended path.`\n );\n }\n\n if (!permissionsLocal && permissionsRemote) {\n return (\n `--remote-bundle-name=${PERMISSIONS_POLICY_BUNDLE_NAME} reserves the Permissions API ` +\n `path. Upload treats all bundles the same; only that fixed name is queried by ` +\n `the Permissions API. Continue only if you intend this bundle for the Permissions API.`\n );\n }\n\n return undefined;\n}\n","import { join } from 'node:path';\n\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { selectCommandLogger } from '../../../lib/cli/command-output.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { buildExampleCommand } from '../../../lib/docgen/buildExamples.js';\nimport { inquirerConfirmBoolean } from '../../../lib/helpers/inquirer.js';\nimport { parsePolicyBundleManifest } from '../../../lib/policy/policy-bundle-manifest.js';\nimport { resolvePolicyProjectDirectory } from '../../../lib/policy/policy-project-discovery.js';\nimport { formatPolicyPublishBundleNameHint } from '../../../lib/policy/policy-publish-hints.js';\nimport { POLICY_MANIFEST_FILENAME } from '../../../lib/policy/policy-scaffold-templates.js';\nimport { isInteractivePromptInvocation } from '../../../lib/scaffolding/prompts.js';\nimport type { ActivateCommandFlags } from '../activate/impl.js';\nimport {\n buildPolicyBundleFormData,\n buildPolicyEngineClient,\n buildOpaBundleTarball,\n defaultPolicyVersionLabel,\n formatPolicyBundleVersionSummary,\n policyEngineRequest,\n printResult,\n resolveBundleIdByName,\n setPolicyEngineCliDebug,\n} from '../helpers/index.js';\nimport type { CreatePolicyBundleResponse, CreatePolicyBundleVersionResponse } from '../types.js';\n\n/** CLI flags for `transcend policy publish`. */\nexport interface PublishCommandFlags {\n /** Tenant-unique bundle name */\n 'remote-bundle-name': string;\n /** Transcend API key */\n auth: string;\n /** Transcend API URL */\n 'transcend-url': string;\n /** Version label (defaults to `{bundleName}-yyyy-mm-dd-hh-mm-ss`) */\n version?: string;\n /** Optional version description */\n description?: string;\n /** Print raw JSON response */\n json: boolean;\n /** Skip the \"create new bundle\" confirmation */\n yes: boolean;\n /** Include technical error details when a command fails */\n debug?: boolean;\n}\n\n/**\n * Build and upload a new immutable policy bundle version.\n *\n * @param this - CLI context\n * @param flags - Command flags\n * @param directory - Policy bundle directory containing a `.manifest`\n */\nexport async function publish(\n this: LocalContext,\n {\n 'remote-bundle-name': bundleName,\n auth,\n 'transcend-url': transcendUrl,\n version,\n description,\n json,\n yes,\n debug = false,\n }: PublishCommandFlags,\n directory: string,\n): Promise<void> {\n doneInputValidation(this.process);\n setPolicyEngineCliDebug(debug);\n\n const commandLogger = selectCommandLogger(this.logger, json);\n const resolvedDir = resolvePolicyProjectDirectory(this.process.cwd(), directory);\n const versionLabel = version ?? defaultPolicyVersionLabel(bundleName);\n const client = buildPolicyEngineClient(transcendUrl, auth);\n const interactive = isInteractivePromptInvocation(\n { json, noInteractive: false },\n this.process.stdin.isTTY,\n this.process.stderr.isTTY,\n );\n\n let bundlePath: string | undefined;\n try {\n commandLogger.info(colors.green(`Building policy bundle from ${resolvedDir}...`));\n bundlePath = await buildOpaBundleTarball(resolvedDir);\n\n try {\n const manifestPath = join(resolvedDir, POLICY_MANIFEST_FILENAME);\n const manifest = parsePolicyBundleManifest(this.fs.readFileSync(manifestPath, 'utf8'));\n const bundleNameHint = formatPolicyPublishBundleNameHint(bundleName, manifest);\n if (bundleNameHint) {\n commandLogger.warn(colors.yellow(bundleNameHint));\n }\n } catch {\n // Best-effort authoring hint; tarball build already validated the manifest.\n }\n\n const existingBundleId = await resolveBundleIdByName(client, bundleName);\n\n let responseBody: CreatePolicyBundleResponse | CreatePolicyBundleVersionResponse;\n\n if (existingBundleId) {\n commandLogger.info(colors.green(`Uploading new version for bundle \"${bundleName}\"...`));\n const form = buildPolicyBundleFormData({\n bundlePath,\n version: versionLabel,\n description,\n });\n responseBody = await policyEngineRequest(\n client\n .post(`v1/policy-engine/policy-bundles/${existingBundleId}/versions`, { body: form })\n .json<CreatePolicyBundleVersionResponse>(),\n );\n } else {\n if (!interactive && !yes) {\n this.logger.error(\n colors.red(\n 'Cannot create a new bundle in non-interactive or JSON mode; pass --yes to confirm.',\n ),\n );\n this.process.exit(1);\n return;\n }\n\n if (!yes) {\n commandLogger.warn(\n colors.yellow(`No policy bundle named \"${bundleName}\" exists for this organization.`),\n );\n const shouldCreate = await inquirerConfirmBoolean({\n message: `No policy bundle named \"${bundleName}\" exists. Create a new bundle and upload its first version?`,\n });\n if (!shouldCreate) {\n commandLogger.info(colors.yellow('Publish cancelled.'));\n return;\n }\n }\n\n commandLogger.info(\n colors.green(`Creating bundle \"${bundleName}\" and uploading first version...`),\n );\n const createForm = buildPolicyBundleFormData({\n bundlePath,\n version: versionLabel,\n description,\n bundleName,\n });\n responseBody = await policyEngineRequest(\n client\n .post('v1/policy-engine/policy-bundles', {\n body: createForm,\n })\n .json<CreatePolicyBundleResponse>(),\n );\n }\n\n printResult(this.process.stdout, {\n json,\n data: responseBody,\n renderTable: () => formatPolicyBundleVersionSummary(responseBody.version),\n });\n\n commandLogger.info(colors.green('Policy bundle version uploaded successfully.'));\n\n const activateCommand = buildExampleCommand<ActivateCommandFlags>(['policy', 'activate'], {\n version: responseBody.version.version,\n 'remote-bundle-name': bundleName,\n });\n commandLogger.info(\n colors.yellow(\n `Publishing a policy does not activate it. To activate this version, run:\\n ${activateCommand}`,\n ),\n );\n } finally {\n if (bundlePath && this.fs.existsSync(bundlePath)) {\n this.fs.unlinkSync(bundlePath);\n }\n }\n}\n"],"mappings":"o+BA0BA,SAAS,EAAkC,EAA0C,CACnF,IAAM,EAAYA,EACf,KAAK,YAAa,CACjB,IAAK,EACL,UAAW,GACX,IAAK,GACN,CAAC,CACD,MAAM,CACH,EAAqB,EAAK,KAAK,EAAK,EAAyB,CAC7D,CAAE,wBAAyB,EAC/B,EAAG,WAAW,EAAmB,CAAG,EAAG,aAAa,EAAoB,OAAO,CAAG,IAAA,GAClF,EAAU,IAAK,IAAkB,CAC/B,KAAM,EACN,SAAU,EAAG,aAAa,EAAK,KAAK,EAAK,EAAa,CAAE,OAAO,CAChE,EAAE,CACJ,CAED,MAAO,CACL,QAAS,CAAC,EAA0B,GAAG,EAAqB,CAC7D,CAaH,eAAe,EAAqB,EAA4B,CAC9D,IAAM,EAAkB,EAAK,KAC3B,EAAG,QAAQ,CACX,iCAAiC,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,CAAC,SACpF,CACD,GAAI,CAKF,GAAM,CAAE,OAAM,UAAW,MAAM,EAC7B,CAAC,QAAS,WAAY,cAAe,KAAM,KAAM,EAAiB,IAAI,CACtE,CAAE,IAAK,EAAK,CACb,CACD,GAAI,IAAS,EACX,MAAU,MAAM,EAAO,MAAM,EAAI,mCAAmC,IAAO,QAErE,CACJ,EAAG,WAAW,EAAgB,EAChC,EAAG,WAAW,EAAgB,EAWpC,SAAS,EAAY,EAAuB,CAC1C,GAAI,EAAQ,KACV,MAAO,GAAG,EAAM,IAElB,IAAM,EAAM,EAAQ,KACpB,GAAI,EAAM,KACR,MAAO,GAAG,EAAM,GAAM,EAAI,EAAI,QAAQ,EAAE,CAAG,EAAI,QAAQ,EAAE,CAAC,MAE5D,IAAM,EAAM,EAAM,KAClB,MAAO,GAAG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AM,EACN,gBAAmB,EAAiC,EAAa,QAAQ,CAC1E,CAAC,CAEF,EAAc,KAAK,EAAO,MAAM,+CAA+C,CAAC,CAEhF,IAAM,EAAkB,EAA0C,CAAC,SAAU,WAAW,CAAE,CACxF,QAAS,EAAa,QAAQ,QAC9B,qBAAsB,EACvB,CAAC,CACF,EAAc,KACZ,EAAO,OACL,+EAA+E,IAChF,CACF,QACO,CACJ,GAAc,KAAK,GAAG,WAAW,EAAW,EAC9C,KAAK,GAAG,WAAW,EAAW"}
1
+ {"version":3,"file":"impl-B8PyNdje2.mjs","names":["fg"],"sources":["../src/commands/policy/helpers/buildOpaBundleTarball.ts","../src/commands/policy/helpers/buildPolicyBundleFormData.ts","../src/commands/policy/helpers/defaultPolicyVersionLabel.ts","../src/lib/policy/policy-publish-hints.ts","../src/commands/policy/publish/impl.ts"],"sourcesContent":["import { spawnSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { gunzipSync } from 'node:zlib';\n\nimport { MAX_BUNDLE_COMPRESSED_BYTES, MAX_BUNDLE_DECOMPRESSED_BYTES } from '@transcend-io/utils';\nimport fg from 'fast-glob';\n\nimport { validatePolicyBundleContents } from '../../../lib/policy/policy-bundle-manifest.js';\nimport { POLICY_MANIFEST_FILENAME } from '../../../lib/policy/policy-scaffold-templates.js';\nimport { assertOpaInstalled } from './assertOpaInstalled.js';\nimport { runOPACapture } from './runOpa.js';\n\n/** Result of collecting publishable entries from a policy bundle directory. */\ninterface PolicyBundleArchiveContents {\n /** Relative paths to include in the upload tarball (manifest first, then rego) */\n entries: string[];\n}\n\n/**\n * Collects `.manifest` and publishable `.rego` files from a policy directory.\n *\n * @param dir - Absolute path to the policy bundle directory\n * @returns Validated archive entries\n */\nfunction collectPolicyBundleArchiveEntries(dir: string): PolicyBundleArchiveContents {\n const regoFiles = fg\n .sync('**/*.rego', {\n cwd: dir,\n onlyFiles: true,\n dot: false,\n })\n .sort();\n const onDiskManifestPath = path.join(dir, POLICY_MANIFEST_FILENAME);\n const { publishableRegoPaths } = validatePolicyBundleContents(\n fs.existsSync(onDiskManifestPath) ? fs.readFileSync(onDiskManifestPath, 'utf8') : undefined,\n regoFiles.map((relativePath) => ({\n path: relativePath,\n contents: fs.readFileSync(path.join(dir, relativePath), 'utf8'),\n })),\n );\n\n return {\n entries: [POLICY_MANIFEST_FILENAME, ...publishableRegoPaths],\n };\n}\n\n/**\n * Verifies that a policy directory compiles end-to-end with `opa build`.\n *\n * The compiled output is discarded — the server receives the `.manifest` +\n * `.rego` archive produced by {@link buildOpaBundleTarball}, not the OPA bundle\n * — but a successful build guarantees the policies compile and link, surfacing\n * errors (syntax, missing imports, undefined references, etc.) before upload.\n *\n * @param dir - Absolute path to the policy bundle directory\n */\nasync function assertBundleCompiles(dir: string): Promise<void> {\n const buildOutputPath = path.join(\n os.tmpdir(),\n `transcend-policy-bundle-build-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`,\n );\n try {\n // Run with `cwd` set to the bundle directory and pass `.` so `opa build`\n // resolves the bundle root correctly. Bundle mode (`-b`) keeps local\n // `input.json` / `input.example.json` fixtures from merging as data.\n // `*_test.rego` files are local-only.\n const { code, stderr } = await runOPACapture(\n ['build', '--ignore', '*_test.rego', '-b', '-o', buildOutputPath, '.'],\n { cwd: dir },\n );\n if (code !== 0) {\n throw new Error(stderr.trim() || `opa build failed with exit code ${code}`);\n }\n } finally {\n if (fs.existsSync(buildOutputPath)) {\n fs.unlinkSync(buildOutputPath);\n }\n }\n}\n\n/**\n * Formats a byte count as a human-readable size with binary units.\n *\n * @param bytes - Number of bytes\n * @returns Human-readable size, e.g. `14 MiB` or `4 KiB`\n */\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) {\n return `${bytes} B`;\n }\n const kib = bytes / 1024;\n if (kib < 1024) {\n return `${kib % 1 === 0 ? kib.toFixed(0) : kib.toFixed(1)} KiB`;\n }\n const mib = kib / 1024;\n return `${mib % 1 === 0 ? mib.toFixed(0) : mib.toFixed(1)} MiB`;\n}\n\n/**\n * Builds a gzip-compressed policy bundle tarball for upload to Transcend.\n *\n * The Policy Engine API expects a plain archive containing `.manifest` and\n * one or more `.rego` files. Local projects author an OPA `.manifest` and it\n * is uploaded directly — no rename at pack time. Before packaging, the\n * manifest is validated (shape + root coverage) and the bundle is validated\n * with `opa check` (strict Rego linting) and `opa build` (full compilation) so\n * failures surface client-side rather than after upload.\n *\n * @param dir - Directory containing `.manifest` and `.rego` policy files\n * @returns Absolute path to the generated `.tar.gz` bundle\n */\nexport async function buildOpaBundleTarball(dir: string): Promise<string> {\n assertOpaInstalled();\n\n const resolvedDir = path.resolve(dir);\n if (!fs.existsSync(resolvedDir) || !fs.statSync(resolvedDir).isDirectory()) {\n throw new Error(`Policy directory does not exist or is not a directory: ${resolvedDir}`);\n }\n\n // Validate the manifest shape and that roots cover every Rego package before\n // invoking OPA, so invalid manifests surface a clear error instead of an\n // opaque `opa build failed with exit code 1`.\n const { entries: archiveEntries } = collectPolicyBundleArchiveEntries(resolvedDir);\n\n // Match the Rego v1 validation the Policy Engine API runs on upload.\n const { code: checkCode, stderr: checkStderr } = await runOPACapture([\n 'check',\n '--strict',\n resolvedDir,\n ]);\n if (checkCode !== 0) {\n throw new Error(checkStderr.trim() || `opa check failed with exit code ${checkCode}`);\n }\n\n // Ensure the bundle compiles end-to-end before packaging for upload.\n await assertBundleCompiles(resolvedDir);\n\n const outputPath = path.join(\n os.tmpdir(),\n `transcend-policy-bundle-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`,\n );\n const tarResult = spawnSync('tar', ['-czf', outputPath, '-C', resolvedDir, ...archiveEntries], {\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n encoding: 'utf8',\n });\n if (tarResult.status !== 0) {\n throw new Error(\n `Failed to create policy bundle archive: ${tarResult.stderr.trim() || 'tar failed'}`,\n );\n }\n\n const compressedBytes = fs.readFileSync(outputPath);\n if (compressedBytes.byteLength > MAX_BUNDLE_COMPRESSED_BYTES) {\n fs.unlinkSync(outputPath);\n throw new Error(\n `Policy bundle exceeds the ${formatBytes(MAX_BUNDLE_COMPRESSED_BYTES)} compressed upload limit ` +\n `(bundle is ${formatBytes(compressedBytes.byteLength)}). ` +\n `The server also rejects decompressed bundles larger than ${formatBytes(MAX_BUNDLE_DECOMPRESSED_BYTES)}.`,\n );\n }\n\n const decompressedBytes = gunzipSync(compressedBytes);\n if (decompressedBytes.byteLength > MAX_BUNDLE_DECOMPRESSED_BYTES) {\n fs.unlinkSync(outputPath);\n throw new Error(\n `Policy bundle exceeds the ${formatBytes(MAX_BUNDLE_DECOMPRESSED_BYTES)} decompressed upload limit ` +\n `(bundle is ${formatBytes(decompressedBytes.byteLength)} decompressed).`,\n );\n }\n\n return outputPath;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\n/** Fields for building a policy bundle upload form. */\nexport interface BuildPolicyBundleFormDataOptions {\n /** Absolute path to the bundle tarball */\n bundlePath: string;\n /** Version label */\n version: string;\n /** Optional description */\n description?: string;\n /** Bundle name (only for create) */\n bundleName?: string;\n}\n\n/**\n * Builds multipart form data for a policy bundle upload.\n *\n * @param options - Upload fields\n * @returns FormData ready for POST\n */\nexport function buildPolicyBundleFormData(options: BuildPolicyBundleFormDataOptions): FormData {\n const bundleBytes = fs.readFileSync(options.bundlePath);\n const form = new FormData();\n form.append(\n 'bundle',\n new Blob([bundleBytes], { type: 'application/gzip' }),\n path.basename(options.bundlePath),\n );\n form.append('version', options.version);\n if (options.description) {\n form.append('description', options.description);\n }\n if (options.bundleName) {\n form.append('bundleName', options.bundleName);\n }\n return form;\n}\n","/**\n * Formats a date as `yyyy-mm-dd-hh-mm-ss` in UTC.\n *\n * @param date - Date to format\n * @returns Timestamp label\n */\nfunction formatPolicyVersionTimestamp(date: Date): string {\n return date.toISOString().slice(0, 19).replace(/[T:]/g, '-');\n}\n\n/**\n * Returns a default version label from the bundle name and current UTC timestamp.\n *\n * @param bundleName - Tenant-unique policy bundle name\n * @param now - Current time (for testing)\n * @returns Version label in `{bundleName}-yyyy-mm-dd-hh-mm-ss` form\n */\nexport function defaultPolicyVersionLabel(bundleName: string, now: Date = new Date()): string {\n return `${bundleName}-${formatPolicyVersionTimestamp(now)}`;\n}\n","import {\n PERMISSIONS_POLICY_BUNDLE_NAME,\n PolicyTemplate,\n type PolicyTemplateName,\n} from './policy-scaffold-templates.js';\n\n/** Inputs used to soft-warn about Permissions vs generic publish naming. */\nexport interface PolicyPublishBundleNameHintInput {\n /** Optional scaffold template from `.manifest` metadata. */\n template?: PolicyTemplateName;\n /** Declared OPA package roots. */\n roots: string[];\n}\n\n/**\n * Whether local authoring signals suggest a Permissions API bundle.\n *\n * Prefers explicit `metadata.transcend.io.template`. Without metadata, falls\n * back to a root that is exactly `permissions` or nested under it.\n *\n * @param input - Manifest template hint and roots\n * @returns Whether the local tree looks Permissions-oriented\n */\nfunction looksLikePermissionsBundle(input: PolicyPublishBundleNameHintInput): boolean {\n if (input.template === PolicyTemplate.Permissions) {\n return true;\n }\n if (input.template === PolicyTemplate.Generic) {\n return false;\n }\n return input.roots.some(\n (root) =>\n root === PERMISSIONS_POLICY_BUNDLE_NAME ||\n root.startsWith(`${PERMISSIONS_POLICY_BUNDLE_NAME}/`),\n );\n}\n\n/**\n * Soft-warning when `--remote-bundle-name` disagrees with Permissions conventions.\n *\n * Upload does not enforce bundle kinds. Permissions API only loads the\n * remote bundle named {@link PERMISSIONS_POLICY_BUNDLE_NAME}.\n *\n * @param bundleName - Value of `--remote-bundle-name`\n * @param input - Local manifest template/roots\n * @returns Warning text, or undefined when names align\n */\nexport function formatPolicyPublishBundleNameHint(\n bundleName: string,\n input: PolicyPublishBundleNameHintInput,\n): string | undefined {\n const permissionsLocal = looksLikePermissionsBundle(input);\n const permissionsRemote = bundleName === PERMISSIONS_POLICY_BUNDLE_NAME;\n\n if (permissionsLocal && !permissionsRemote) {\n return (\n `This directory looks like a Permissions API policy, but --remote-bundle-name is ` +\n `\"${bundleName}\". Permissions API only loads the remote bundle named ` +\n `\"${PERMISSIONS_POLICY_BUNDLE_NAME}\". Upload still succeeds; pass ` +\n `--remote-bundle-name=${PERMISSIONS_POLICY_BUNDLE_NAME} if that is the intended path.`\n );\n }\n\n if (!permissionsLocal && permissionsRemote) {\n return (\n `--remote-bundle-name=${PERMISSIONS_POLICY_BUNDLE_NAME} reserves the Permissions API ` +\n `path. Upload treats all bundles the same; only that fixed name is queried by ` +\n `the Permissions API. Continue only if you intend this bundle for the Permissions API.`\n );\n }\n\n return undefined;\n}\n","import { join } from 'node:path';\n\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { selectCommandLogger } from '../../../lib/cli/command-output.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { buildExampleCommand } from '../../../lib/docgen/buildExamples.js';\nimport { inquirerConfirmBoolean } from '../../../lib/helpers/inquirer.js';\nimport { parsePolicyBundleManifest } from '../../../lib/policy/policy-bundle-manifest.js';\nimport { resolvePolicyProjectDirectory } from '../../../lib/policy/policy-project-discovery.js';\nimport { formatPolicyPublishBundleNameHint } from '../../../lib/policy/policy-publish-hints.js';\nimport { POLICY_MANIFEST_FILENAME } from '../../../lib/policy/policy-scaffold-templates.js';\nimport { isInteractivePromptInvocation } from '../../../lib/scaffolding/prompts.js';\nimport type { ActivateCommandFlags } from '../activate/impl.js';\nimport {\n buildPolicyBundleFormData,\n buildPolicyEngineClient,\n buildOpaBundleTarball,\n defaultPolicyVersionLabel,\n formatPolicyBundleVersionSummary,\n policyEngineRequest,\n printResult,\n resolveBundleIdByName,\n setPolicyEngineCliDebug,\n} from '../helpers/index.js';\nimport type { CreatePolicyBundleResponse, CreatePolicyBundleVersionResponse } from '../types.js';\n\n/** CLI flags for `transcend policy publish`. */\nexport interface PublishCommandFlags {\n /** Tenant-unique bundle name */\n 'remote-bundle-name': string;\n /** Transcend API key */\n auth: string;\n /** Transcend API URL */\n 'transcend-url': string;\n /** Version label (defaults to `{bundleName}-yyyy-mm-dd-hh-mm-ss`) */\n version?: string;\n /** Optional version description */\n description?: string;\n /** Print raw JSON response */\n json: boolean;\n /** Skip the \"create new bundle\" confirmation */\n yes: boolean;\n /** Include technical error details when a command fails */\n debug?: boolean;\n}\n\n/**\n * Build and upload a new immutable policy bundle version.\n *\n * @param this - CLI context\n * @param flags - Command flags\n * @param directory - Policy bundle directory containing a `.manifest`\n */\nexport async function publish(\n this: LocalContext,\n {\n 'remote-bundle-name': bundleName,\n auth,\n 'transcend-url': transcendUrl,\n version,\n description,\n json,\n yes,\n debug = false,\n }: PublishCommandFlags,\n directory: string,\n): Promise<void> {\n doneInputValidation(this.process);\n setPolicyEngineCliDebug(debug);\n\n const commandLogger = selectCommandLogger(this.logger, json);\n const resolvedDir = resolvePolicyProjectDirectory(this.process.cwd(), directory);\n const versionLabel = version ?? defaultPolicyVersionLabel(bundleName);\n const client = buildPolicyEngineClient(transcendUrl, auth);\n const interactive = isInteractivePromptInvocation(\n { json, noInteractive: false },\n this.process.stdin.isTTY,\n this.process.stderr.isTTY,\n );\n\n let bundlePath: string | undefined;\n try {\n commandLogger.info(colors.green(`Building policy bundle from ${resolvedDir}...`));\n bundlePath = await buildOpaBundleTarball(resolvedDir);\n\n try {\n const manifestPath = join(resolvedDir, POLICY_MANIFEST_FILENAME);\n const manifest = parsePolicyBundleManifest(this.fs.readFileSync(manifestPath, 'utf8'));\n const bundleNameHint = formatPolicyPublishBundleNameHint(bundleName, manifest);\n if (bundleNameHint) {\n commandLogger.warn(colors.yellow(bundleNameHint));\n }\n } catch {\n // Best-effort authoring hint; tarball build already validated the manifest.\n }\n\n const existingBundleId = await resolveBundleIdByName(client, bundleName);\n\n let responseBody: CreatePolicyBundleResponse | CreatePolicyBundleVersionResponse;\n\n if (existingBundleId) {\n commandLogger.info(colors.green(`Uploading new version for bundle \"${bundleName}\"...`));\n const form = buildPolicyBundleFormData({\n bundlePath,\n version: versionLabel,\n description,\n });\n responseBody = await policyEngineRequest(\n client\n .post(`v1/policy-engine/policy-bundles/${existingBundleId}/versions`, { body: form })\n .json<CreatePolicyBundleVersionResponse>(),\n );\n } else {\n if (!interactive && !yes) {\n this.logger.error(\n colors.red(\n 'Cannot create a new bundle in non-interactive or JSON mode; pass --yes to confirm.',\n ),\n );\n this.process.exit(1);\n return;\n }\n\n if (!yes) {\n commandLogger.warn(\n colors.yellow(`No policy bundle named \"${bundleName}\" exists for this organization.`),\n );\n const shouldCreate = await inquirerConfirmBoolean({\n message: `No policy bundle named \"${bundleName}\" exists. Create a new bundle and upload its first version?`,\n });\n if (!shouldCreate) {\n commandLogger.info(colors.yellow('Publish cancelled.'));\n return;\n }\n }\n\n commandLogger.info(\n colors.green(`Creating bundle \"${bundleName}\" and uploading first version...`),\n );\n const createForm = buildPolicyBundleFormData({\n bundlePath,\n version: versionLabel,\n description,\n bundleName,\n });\n responseBody = await policyEngineRequest(\n client\n .post('v1/policy-engine/policy-bundles', {\n body: createForm,\n })\n .json<CreatePolicyBundleResponse>(),\n );\n }\n\n printResult(this.process.stdout, {\n json,\n data: responseBody,\n renderTable: () => formatPolicyBundleVersionSummary(responseBody.version),\n });\n\n commandLogger.info(colors.green('Policy bundle version uploaded successfully.'));\n\n const activateCommand = buildExampleCommand<ActivateCommandFlags>(['policy', 'activate'], {\n version: responseBody.version.version,\n 'remote-bundle-name': bundleName,\n });\n commandLogger.info(\n colors.yellow(\n `Publishing a policy does not activate it. To activate this version, run:\\n ${activateCommand}`,\n ),\n );\n } finally {\n if (bundlePath && this.fs.existsSync(bundlePath)) {\n this.fs.unlinkSync(bundlePath);\n }\n }\n}\n"],"mappings":"o+BA0BA,SAAS,EAAkC,EAA0C,CACnF,IAAM,EAAYA,EACf,KAAK,YAAa,CACjB,IAAK,EACL,UAAW,GACX,IAAK,GACN,CAAC,CACD,MAAM,CACH,EAAqB,EAAK,KAAK,EAAK,EAAyB,CAC7D,CAAE,wBAAyB,EAC/B,EAAG,WAAW,EAAmB,CAAG,EAAG,aAAa,EAAoB,OAA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YnCgbl.mjs";import{t}from"./done-input-validation-LiTaCEzF.mjs";import{splitCsvToList as n}from"@transcend-io/utils";async function r({auth:r,file:i,transcendUrl:a,cacheFilepath:o,requestReceiptFolder:s,sombraAuth:c,concurrency:l,attributes:u,isTest:d,isSilent:f,skipSendingReceipt:p,emailIsVerified:m,skipFilterStep:h,dryRun:g,debug:_,defaultPhoneCountryCode:v}){t(this.process),await e({cacheFilepath:o,requestReceiptFolder:s,file:i,auth:r,sombraAuth:c,concurrency:l,transcendUrl:a,defaultPhoneCountryCode:v,attributes:n(u),debug:_,skipFilterStep:h,isSilent:f,skipSendingReceipt:p,emailIsVerified:m,isTest:d,dryRun:g})}export{r as upload};
2
- //# sourceMappingURL=impl-Bh02zrTq.mjs.map
1
+ import{t as e}from"./uploadPrivacyRequestsFromCsv-DHYbgV8h.mjs";import{t}from"./done-input-validation-LiTaCEzF.mjs";import{splitCsvToList as n}from"@transcend-io/utils";async function r({auth:r,file:i,transcendUrl:a,cacheFilepath:o,requestReceiptFolder:s,sombraAuth:c,concurrency:l,attributes:u,isTest:d,isSilent:f,skipSendingReceipt:p,emailIsVerified:m,skipFilterStep:h,dryRun:g,debug:_,defaultPhoneCountryCode:v}){t(this.process),await e({cacheFilepath:o,requestReceiptFolder:s,file:i,auth:r,sombraAuth:c,concurrency:l,transcendUrl:a,defaultPhoneCountryCode:v,attributes:n(u),debug:_,skipFilterStep:h,isSilent:f,skipSendingReceipt:p,emailIsVerified:m,isTest:d,dryRun:g})}export{r as upload};
2
+ //# sourceMappingURL=impl-BIYT-9BY.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-Bh02zrTq.mjs","names":[],"sources":["../src/commands/request/upload/impl.ts"],"sourcesContent":["import { splitCsvToList } from '@transcend-io/utils';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { uploadPrivacyRequestsFromCsv } from '../../../lib/requests/index.js';\n\nexport interface UploadCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n cacheFilepath: string;\n requestReceiptFolder: string;\n sombraAuth?: string;\n concurrency: number;\n attributes: string;\n isTest: boolean;\n isSilent: boolean;\n skipSendingReceipt: boolean;\n emailIsVerified: boolean;\n skipFilterStep: boolean;\n dryRun: boolean;\n debug: boolean;\n defaultPhoneCountryCode: string;\n}\n\nexport async function upload(\n this: LocalContext,\n {\n auth,\n file,\n transcendUrl,\n cacheFilepath,\n requestReceiptFolder,\n sombraAuth,\n concurrency,\n attributes,\n isTest,\n isSilent,\n skipSendingReceipt,\n emailIsVerified,\n skipFilterStep,\n dryRun,\n debug,\n defaultPhoneCountryCode,\n }: UploadCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await uploadPrivacyRequestsFromCsv({\n cacheFilepath,\n requestReceiptFolder,\n file,\n auth,\n sombraAuth,\n concurrency,\n transcendUrl,\n defaultPhoneCountryCode,\n attributes: splitCsvToList(attributes),\n debug,\n skipFilterStep,\n isSilent,\n skipSendingReceipt,\n emailIsVerified,\n isTest,\n dryRun,\n });\n}\n"],"mappings":"yKAyBA,eAAsB,EAEpB,CACE,OACA,OACA,eACA,gBACA,uBACA,aACA,cACA,aACA,SACA,WACA,qBACA,kBACA,iBACA,SACA,QACA,2BAEa,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAA6B,CACjC,gBACA,uBACA,OACA,OACA,aACA,cACA,eACA,0BACA,WAAY,EAAe,EAAW,CACtC,QACA,iBACA,WACA,qBACA,kBACA,SACA,SACD,CAAC"}
1
+ {"version":3,"file":"impl-BIYT-9BY.mjs","names":[],"sources":["../src/commands/request/upload/impl.ts"],"sourcesContent":["import { splitCsvToList } from '@transcend-io/utils';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { uploadPrivacyRequestsFromCsv } from '../../../lib/requests/index.js';\n\nexport interface UploadCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n cacheFilepath: string;\n requestReceiptFolder: string;\n sombraAuth?: string;\n concurrency: number;\n attributes: string;\n isTest: boolean;\n isSilent: boolean;\n skipSendingReceipt: boolean;\n emailIsVerified: boolean;\n skipFilterStep: boolean;\n dryRun: boolean;\n debug: boolean;\n defaultPhoneCountryCode: string;\n}\n\nexport async function upload(\n this: LocalContext,\n {\n auth,\n file,\n transcendUrl,\n cacheFilepath,\n requestReceiptFolder,\n sombraAuth,\n concurrency,\n attributes,\n isTest,\n isSilent,\n skipSendingReceipt,\n emailIsVerified,\n skipFilterStep,\n dryRun,\n debug,\n defaultPhoneCountryCode,\n }: UploadCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await uploadPrivacyRequestsFromCsv({\n cacheFilepath,\n requestReceiptFolder,\n file,\n auth,\n sombraAuth,\n concurrency,\n transcendUrl,\n defaultPhoneCountryCode,\n attributes: splitCsvToList(attributes),\n debug,\n skipFilterStep,\n isSilent,\n skipSendingReceipt,\n emailIsVerified,\n isTest,\n dryRun,\n });\n}\n"],"mappings":"yKAyBA,eAAsB,EAEpB,CACE,OACA,OACA,eACA,gBACA,uBACA,aACA,cACA,aACA,SACA,WACA,qBACA,kBACA,iBACA,SACA,QACA,2BAEa,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAA6B,CACjC,gBACA,uBACA,OACA,OACA,aACA,cACA,eACA,0BACA,WAAY,EAAe,EAAW,CACtC,QACA,iBACA,WACA,qBACA,kBACA,SACA,SACD,CAAC"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./pullChunkedCustomSiloOutstandingIdentifiers-BfNNWqeI.mjs";import{i as t,s as n}from"./writeCsv-CNZrq3zU.mjs";import{t as r}from"./done-input-validation-LiTaCEzF.mjs";import{chunk as i,uniq as a}from"lodash-es";import o from"colors";import{map as s}from"@transcend-io/utils";import{buildTranscendGraphQLClient as c,fetchRequestFilesForRequest as l}from"@transcend-io/sdk";async function u({file:u,fileTarget:d,transcendUrl:f,auth:p,sombraAuth:m,cronDataSiloId:h,targetDataSiloId:g,actions:_,skipRequestCount:v,pageLimit:y,chunkSize:b}){v&&this.logger.info(o.yellow(`Skipping request count as requested. This may help speed up the call.`)),(Number.isNaN(b)||b<=0||b%y!==0)&&(this.logger.error(o.red(`Invalid chunk size: "${b}". Must be a positive integer that is a multiple of ${y}.`)),this.process.exit(1)),r(this.process);let x=c(f,p),{baseName:S,extension:C}=t(u),{baseName:w,extension:T}=t(d),E=0,D=0,O=0;await e({dataSiloId:h,auth:p,sombraAuth:m,actions:_,apiPageSize:y,savePageSize:b,onSave:async e=>{E+=e.length;let t=await s(i(a(e.map(e=>e.requestId)),y),async e=>(this.logger.info(o.magenta(`Fetching target identifiers for ${e.length} requests`)),(await l(x,{logger:this.logger,pageSize:y*2,filterBy:{requestIds:e,dataSiloIds:[g]}})).map(({fileName:e,remoteId:t})=>{if(!t)throw Error(`Failed to find remoteId for ${e}`);return{RecordId:t,Object:e.replace(`.json`,``).split(`/`).pop()?.replace(` Information`,``),Comment:`Customer data deletion request submitted via transcend.io`}})),{concurrency:1});D+=t.flat().length;let r=a(e.map(e=>Object.keys(e)).flat()),c=`${S}-${O}${C}`,f=`${w}-${O}${T}`;await n(c,e,r),this.logger.info(o.green(`Successfully wrote ${e.length} identifiers to file "${u}"`));let p=t.flat();await n(f,p,a(p.map(e=>Object.keys(e)).flat())),this.logger.info(o.green(`Successfully wrote ${p.length} identifiers to file "${d}"`)),this.logger.info(o.blue(`Processed chunk of ${i.length} identifiers, found ${p.length} target identifiers`)),O+=1},transcendUrl:f,skipRequestCount:v}),this.logger.info(o.green(`Successfully wrote ${E} identifiers to file "${u}"`)),this.logger.info(o.green(`Successfully wrote ${D} identifiers to file "${d}"`))}export{u as pullProfiles};
2
- //# sourceMappingURL=impl-BQe6vddz.mjs.map
1
+ import{t as e}from"./pullChunkedCustomSiloOutstandingIdentifiers-BcBj9prQ.mjs";import{i as t,s as n}from"./writeCsv-CNZrq3zU.mjs";import{t as r}from"./done-input-validation-LiTaCEzF.mjs";import{chunk as i,uniq as a}from"lodash-es";import o from"colors";import{map as s}from"@transcend-io/utils";import{buildTranscendGraphQLClient as c,fetchRequestFilesForRequest as l}from"@transcend-io/sdk";async function u({file:u,fileTarget:d,transcendUrl:f,auth:p,sombraAuth:m,cronDataSiloId:h,targetDataSiloId:g,actions:_,skipRequestCount:v,pageLimit:y,chunkSize:b}){v&&this.logger.info(o.yellow(`Skipping request count as requested. This may help speed up the call.`)),(Number.isNaN(b)||b<=0||b%y!==0)&&(this.logger.error(o.red(`Invalid chunk size: "${b}". Must be a positive integer that is a multiple of ${y}.`)),this.process.exit(1)),r(this.process);let x=c(f,p),{baseName:S,extension:C}=t(u),{baseName:w,extension:T}=t(d),E=0,D=0,O=0;await e({dataSiloId:h,auth:p,sombraAuth:m,actions:_,apiPageSize:y,savePageSize:b,onSave:async e=>{E+=e.length;let t=await s(i(a(e.map(e=>e.requestId)),y),async e=>(this.logger.info(o.magenta(`Fetching target identifiers for ${e.length} requests`)),(await l(x,{logger:this.logger,pageSize:y*2,filterBy:{requestIds:e,dataSiloIds:[g]}})).map(({fileName:e,remoteId:t})=>{if(!t)throw Error(`Failed to find remoteId for ${e}`);return{RecordId:t,Object:e.replace(`.json`,``).split(`/`).pop()?.replace(` Information`,``),Comment:`Customer data deletion request submitted via transcend.io`}})),{concurrency:1});D+=t.flat().length;let r=a(e.map(e=>Object.keys(e)).flat()),c=`${S}-${O}${C}`,f=`${w}-${O}${T}`;await n(c,e,r),this.logger.info(o.green(`Successfully wrote ${e.length} identifiers to file "${u}"`));let p=t.flat();await n(f,p,a(p.map(e=>Object.keys(e)).flat())),this.logger.info(o.green(`Successfully wrote ${p.length} identifiers to file "${d}"`)),this.logger.info(o.blue(`Processed chunk of ${i.length} identifiers, found ${p.length} target identifiers`)),O+=1},transcendUrl:f,skipRequestCount:v}),this.logger.info(o.green(`Successfully wrote ${E} identifiers to file "${u}"`)),this.logger.info(o.green(`Successfully wrote ${D} identifiers to file "${d}"`))}export{u as pullProfiles};
2
+ //# sourceMappingURL=impl-BP110k4H.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-BQe6vddz.mjs","names":[],"sources":["../src/commands/request/cron/pull-profiles/impl.ts"],"sourcesContent":["import type { RequestAction } from '@transcend-io/privacy-types';\nimport { buildTranscendGraphQLClient, fetchRequestFilesForRequest } from '@transcend-io/sdk';\nimport { map } from '@transcend-io/utils';\nimport colors from 'colors';\nimport { uniq, chunk } from 'lodash-es';\n\nimport type { LocalContext } from '../../../../context.js';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation.js';\nimport {\n pullChunkedCustomSiloOutstandingIdentifiers,\n type CsvFormattedIdentifier,\n} from '../../../../lib/cron/index.js';\nimport { parseFilePath, writeLargeCsv } from '../../../../lib/helpers/index.js';\n\nexport interface PullProfilesCommandFlags {\n file: string;\n fileTarget: string;\n transcendUrl: string;\n auth: string;\n sombraAuth?: string;\n cronDataSiloId: string;\n targetDataSiloId: string;\n actions: RequestAction[];\n skipRequestCount: boolean;\n pageLimit: number;\n chunkSize: number;\n}\n\nexport async function pullProfiles(\n this: LocalContext,\n {\n file,\n fileTarget,\n transcendUrl,\n auth,\n sombraAuth,\n cronDataSiloId,\n targetDataSiloId,\n actions,\n skipRequestCount,\n pageLimit,\n chunkSize,\n }: PullProfilesCommandFlags,\n): Promise<void> {\n if (skipRequestCount) {\n this.logger.info(\n colors.yellow('Skipping request count as requested. This may help speed up the call.'),\n );\n }\n\n if (Number.isNaN(chunkSize) || chunkSize <= 0 || chunkSize % pageLimit !== 0) {\n this.logger.error(\n colors.red(\n `Invalid chunk size: \"${chunkSize}\". Must be a positive integer that is a multiple of ${pageLimit}.`,\n ),\n );\n this.process.exit(1);\n }\n\n doneInputValidation(this.process);\n\n // Create GraphQL client to connect to Transcend backend\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n const { baseName, extension } = parseFilePath(file);\n const { baseName: baseNameTarget, extension: extensionTarget } = parseFilePath(fileTarget);\n\n let allIdentifiersCount = 0;\n let allTargetIdentifiersCount = 0;\n let fileCount = 0;\n // Create onSave callback to handle chunked processing\n const onSave = async (chunkToSave: CsvFormattedIdentifier[]): Promise<void> => {\n // Add to all identifiers\n allIdentifiersCount += chunkToSave.length;\n\n // Get unique request IDs from this chunk\n const requestIds = chunkToSave.map((d) => d.requestId as string);\n const uniqueRequestIds = uniq(requestIds);\n\n // Pull down target identifiers for this chunk\n const chunkedRequestIds = chunk(uniqueRequestIds, pageLimit);\n const results = await map(\n chunkedRequestIds,\n async (requestIds) => {\n this.logger.info(\n colors.magenta(`Fetching target identifiers for ${requestIds.length} requests`),\n );\n const results = await fetchRequestFilesForRequest(client, {\n logger: this.logger,\n pageSize: pageLimit * 2,\n filterBy: {\n requestIds,\n dataSiloIds: [targetDataSiloId],\n },\n });\n return results.map(({ fileName, remoteId }) => {\n if (!remoteId) {\n throw new Error(`Failed to find remoteId for ${fileName}`);\n }\n return {\n RecordId: remoteId,\n Object: fileName.replace('.json', '').split('/').pop()?.replace(' Information', ''),\n Comment: 'Customer data deletion request submitted via transcend.io',\n };\n });\n },\n // We are grabbing all the request files for the 'pageLimit' # of requests at a time\n {\n concurrency: 1,\n },\n );\n\n allTargetIdentifiersCount += results.flat().length;\n\n // Write the identifiers and target identifiers to CSV\n const headers = uniq(chunkToSave.map((d) => Object.keys(d)).flat());\n const numberedFileName = `${baseName}-${fileCount}${extension}`;\n const numberedFileNameTarget = `${baseNameTarget}-${fileCount}${extensionTarget}`;\n await writeLargeCsv(numberedFileName, chunkToSave, headers);\n this.logger.info(\n colors.green(`Successfully wrote ${chunkToSave.length} identifiers to file \"${file}\"`),\n );\n\n const targetIdentifiers = results.flat();\n const headers2 = uniq(targetIdentifiers.map((d) => Object.keys(d)).flat());\n await writeLargeCsv(numberedFileNameTarget, targetIdentifiers, headers2);\n this.logger.info(\n colors.green(\n `Successfully wrote ${targetIdentifiers.length} identifiers to file \"${fileTarget}\"`,\n ),\n );\n\n this.logger.info(\n colors.blue(\n `Processed chunk of ${chunk.length} identifiers, found ${targetIdentifiers.length} target identifiers`,\n ),\n );\n fileCount += 1;\n };\n\n // Pull down outstanding identifiers using the new chunked function\n await pullChunkedCustomSiloOutstandingIdentifiers({\n dataSiloId: cronDataSiloId,\n auth,\n sombraAuth,\n actions,\n apiPageSize: pageLimit,\n savePageSize: chunkSize,\n onSave,\n transcendUrl,\n skipRequestCount,\n });\n\n this.logger.info(\n colors.green(`Successfully wrote ${allIdentifiersCount} identifiers to file \"${file}\"`),\n );\n this.logger.info(\n colors.green(\n `Successfully wrote ${allTargetIdentifiersCount} identifiers to file \"${fileTarget}\"`,\n ),\n );\n}\n"],"mappings":"wYA4BA,eAAsB,EAEpB,CACE,OACA,aACA,eACA,OACA,aACA,iBACA,mBACA,UACA,mBACA,YACA,aAEa,CACX,GACF,KAAK,OAAO,KACV,EAAO,OAAO,wEAAwE,CACvF,EAGC,OAAO,MAAM,EAAU,EAAI,GAAa,GAAK,EAAY,IAAc,KACzE,KAAK,OAAO,MACV,EAAO,IACL,wBAAwB,EAAU,sDAAsD,EAAU,GACnG,CACF,CACD,KAAK,QAAQ,KAAK,EAAE,EAGtB,EAAoB,KAAK,QAAQ,CAGjC,IAAM,EAAS,EAA4B,EAAc,EAAK,CACxD,CAAE,WAAU,aAAc,EAAc,EAAK,CAC7C,CAAE,SAAU,EAAgB,UAAW,GAAoB,EAAc,EAAW,CAEtF,EAAsB,EACtB,EAA4B,EAC5B,EAAY,EAwEhB,MAAM,EAA4C,CAChD,WAAY,EACZ,OACA,aACA,UACA,YAAa,EACb,aAAc,EACd,YA7EoB,IAAyD,CAE7E,GAAuB,EAAY,OAQnC,IAAM,EAAU,MAAM,EADI,EAHD,EADN,EAAY,IAAK,GAAM,EAAE,UACJ,CAGQ,CAAE,EAE/B,CACjB,KAAO,KACL,KAAK,OAAO,KACV,EAAO,QAAQ,mCAAmC,EAAW,OAAO,WAAW,CAChF,EASM,MARe,EAA4B,EAAQ,CACxD,OAAQ,KAAK,OACb,SAAU,EAAY,EACtB,SAAU,CACR,aACA,YAAa,CAAC,EAAiB,CAChC,CACF,CAAC,EACa,KAAK,CAAE,WAAU,cAAe,CAC7C,GAAI,CAAC,EACH,MAAU,MAAM,+BAA+B,IAAW,CAE5D,MAAO,CACL,SAAU,EACV,OAAQ,EAAS,QAAQ,QAAS,GAAG,CAAC,MAAM,IAAI,CAAC,KAAK,EAAE,QAAQ,eAAgB,GAAG,CACnF,QAAS,4DACV,EACD,EAGJ,CACE,YAAa,EACd,CACF,CAED,GAA6B,EAAQ,MAAM,CAAC,OAG5C,IAAM,EAAU,EAAK,EAAY,IAAK,GAAM,OAAO,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC,CAC7D,EAAmB,GAAG,EAAS,GAAG,IAAY,IAC9C,EAAyB,GAAG,EAAe,GAAG,IAAY,IAChE,MAAM,EAAc,EAAkB,EAAa,EAAQ,CAC3D,KAAK,OAAO,KACV,EAAO,MAAM,sBAAsB,EAAY,OAAO,wBAAwB,EAAK,GAAG,CACvF,CAED,IAAM,EAAoB,EAAQ,MAAM,CAExC,MAAM,EAAc,EAAwB,EAD3B,EAAK,EAAkB,IAAK,GAAM,OAAO,KAAK,EAAE,CAAC,CAAC,MAAM,CACF,CAAC,CACxE,KAAK,OAAO,KACV,EAAO,MACL,sBAAsB,EAAkB,OAAO,wBAAwB,EAAW,GACnF,CACF,CAED,KAAK,OAAO,KACV,EAAO,KACL,sBAAsB,EAAM,OAAO,sBAAsB,EAAkB,OAAO,qBACnF,CACF,CACD,GAAa,GAYb,eACA,mBACD,CAAC,CAEF,KAAK,OAAO,KACV,EAAO,MAAM,sBAAsB,EAAoB,wBAAwB,EAAK,GAAG,CACxF,CACD,KAAK,OAAO,KACV,EAAO,MACL,sBAAsB,EAA0B,wBAAwB,EAAW,GACpF,CACF"}
1
+ {"version":3,"file":"impl-BP110k4H.mjs","names":[],"sources":["../src/commands/request/cron/pull-profiles/impl.ts"],"sourcesContent":["import type { RequestAction } from '@transcend-io/privacy-types';\nimport { buildTranscendGraphQLClient, fetchRequestFilesForRequest } from '@transcend-io/sdk';\nimport { map } from '@transcend-io/utils';\nimport colors from 'colors';\nimport { uniq, chunk } from 'lodash-es';\n\nimport type { LocalContext } from '../../../../context.js';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation.js';\nimport {\n pullChunkedCustomSiloOutstandingIdentifiers,\n type CsvFormattedIdentifier,\n} from '../../../../lib/cron/index.js';\nimport { parseFilePath, writeLargeCsv } from '../../../../lib/helpers/index.js';\n\nexport interface PullProfilesCommandFlags {\n file: string;\n fileTarget: string;\n transcendUrl: string;\n auth: string;\n sombraAuth?: string;\n cronDataSiloId: string;\n targetDataSiloId: string;\n actions: RequestAction[];\n skipRequestCount: boolean;\n pageLimit: number;\n chunkSize: number;\n}\n\nexport async function pullProfiles(\n this: LocalContext,\n {\n file,\n fileTarget,\n transcendUrl,\n auth,\n sombraAuth,\n cronDataSiloId,\n targetDataSiloId,\n actions,\n skipRequestCount,\n pageLimit,\n chunkSize,\n }: PullProfilesCommandFlags,\n): Promise<void> {\n if (skipRequestCount) {\n this.logger.info(\n colors.yellow('Skipping request count as requested. This may help speed up the call.'),\n );\n }\n\n if (Number.isNaN(chunkSize) || chunkSize <= 0 || chunkSize % pageLimit !== 0) {\n this.logger.error(\n colors.red(\n `Invalid chunk size: \"${chunkSize}\". Must be a positive integer that is a multiple of ${pageLimit}.`,\n ),\n );\n this.process.exit(1);\n }\n\n doneInputValidation(this.process);\n\n // Create GraphQL client to connect to Transcend backend\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n const { baseName, extension } = parseFilePath(file);\n const { baseName: baseNameTarget, extension: extensionTarget } = parseFilePath(fileTarget);\n\n let allIdentifiersCount = 0;\n let allTargetIdentifiersCount = 0;\n let fileCount = 0;\n // Create onSave callback to handle chunked processing\n const onSave = async (chunkToSave: CsvFormattedIdentifier[]): Promise<void> => {\n // Add to all identifiers\n allIdentifiersCount += chunkToSave.length;\n\n // Get unique request IDs from this chunk\n const requestIds = chunkToSave.map((d) => d.requestId as string);\n const uniqueRequestIds = uniq(requestIds);\n\n // Pull down target identifiers for this chunk\n const chunkedRequestIds = chunk(uniqueRequestIds, pageLimit);\n const results = await map(\n chunkedRequestIds,\n async (requestIds) => {\n this.logger.info(\n colors.magenta(`Fetching target identifiers for ${requestIds.length} requests`),\n );\n const results = await fetchRequestFilesForRequest(client, {\n logger: this.logger,\n pageSize: pageLimit * 2,\n filterBy: {\n requestIds,\n dataSiloIds: [targetDataSiloId],\n },\n });\n return results.map(({ fileName, remoteId }) => {\n if (!remoteId) {\n throw new Error(`Failed to find remoteId for ${fileName}`);\n }\n return {\n RecordId: remoteId,\n Object: fileName.replace('.json', '').split('/').pop()?.replace(' Information', ''),\n Comment: 'Customer data deletion request submitted via transcend.io',\n };\n });\n },\n // We are grabbing all the request files for the 'pageLimit' # of requests at a time\n {\n concurrency: 1,\n },\n );\n\n allTargetIdentifiersCount += results.flat().length;\n\n // Write the identifiers and target identifiers to CSV\n const headers = uniq(chunkToSave.map((d) => Object.keys(d)).flat());\n const numberedFileName = `${baseName}-${fileCount}${extension}`;\n const numberedFileNameTarget = `${baseNameTarget}-${fileCount}${extensionTarget}`;\n await writeLargeCsv(numberedFileName, chunkToSave, headers);\n this.logger.info(\n colors.green(`Successfully wrote ${chunkToSave.length} identifiers to file \"${file}\"`),\n );\n\n const targetIdentifiers = results.flat();\n const headers2 = uniq(targetIdentifiers.map((d) => Object.keys(d)).flat());\n await writeLargeCsv(numberedFileNameTarget, targetIdentifiers, headers2);\n this.logger.info(\n colors.green(\n `Successfully wrote ${targetIdentifiers.length} identifiers to file \"${fileTarget}\"`,\n ),\n );\n\n this.logger.info(\n colors.blue(\n `Processed chunk of ${chunk.length} identifiers, found ${targetIdentifiers.length} target identifiers`,\n ),\n );\n fileCount += 1;\n };\n\n // Pull down outstanding identifiers using the new chunked function\n await pullChunkedCustomSiloOutstandingIdentifiers({\n dataSiloId: cronDataSiloId,\n auth,\n sombraAuth,\n actions,\n apiPageSize: pageLimit,\n savePageSize: chunkSize,\n onSave,\n transcendUrl,\n skipRequestCount,\n });\n\n this.logger.info(\n colors.green(`Successfully wrote ${allIdentifiersCount} identifiers to file \"${file}\"`),\n );\n this.logger.info(\n colors.green(\n `Successfully wrote ${allTargetIdentifiersCount} identifiers to file \"${fileTarget}\"`,\n ),\n );\n}\n"],"mappings":"wYA4BA,eAAsB,EAEpB,CACE,OACA,aACA,eACA,OACA,aACA,iBACA,mBACA,UACA,mBACA,YACA,aAEa,CACX,GACF,KAAK,OAAO,KACV,EAAO,OAAO,wEAAwE,CACvF,EAGC,OAAO,MAAM,EAAU,EAAI,GAAa,GAAK,EAAY,IAAc,KACzE,KAAK,OAAO,MACV,EAAO,IACL,wBAAwB,EAAU,sDAAsD,EAAU,GACnG,CACF,CACD,KAAK,QAAQ,KAAK,EAAE,EAGtB,EAAoB,KAAK,QAAQ,CAGjC,IAAM,EAAS,EAA4B,EAAc,EAAK,CACxD,CAAE,WAAU,aAAc,EAAc,EAAK,CAC7C,CAAE,SAAU,EAAgB,UAAW,GAAoB,EAAc,EAAW,CAEtF,EAAsB,EACtB,EAA4B,EAC5B,EAAY,EAwEhB,MAAM,EAA4C,CAChD,WAAY,EACZ,OACA,aACA,UACA,YAAa,EACb,aAAc,EACd,YA7EoB,IAAyD,CAE7E,GAAuB,EAAY,OAQnC,IAAM,EAAU,MAAM,EADI,EAHD,EADN,EAAY,IAAK,GAAM,EAAE,UACJ,CAGQ,CAAE,EAE/B,CACjB,KAAO,KACL,KAAK,OAAO,KACV,EAAO,QAAQ,mCAAmC,EAAW,OAAO,WAAW,CAChF,EASM,MARe,EAA4B,EAAQ,CACxD,OAAQ,KAAK,OACb,SAAU,EAAY,EACtB,SAAU,CACR,aACA,YAAa,CAAC,EAAiB,CAChC,CACF,CAAC,EACa,KAAK,CAAE,WAAU,cAAe,CAC7C,GAAI,CAAC,EACH,MAAU,MAAM,+BAA+B,IAAW,CAE5D,MAAO,CACL,SAAU,EACV,OAAQ,EAAS,QAAQ,QAAS,GAAG,CAAC,MAAM,IAAI,CAAC,KAAK,EAAE,QAAQ,eAAgB,GAAG,CACnF,QAAS,4DACV,EACD,EAGJ,CACE,YAAa,EACd,CACF,CAED,GAA6B,EAAQ,MAAM,CAAC,OAG5C,IAAM,EAAU,EAAK,EAAY,IAAK,GAAM,OAAO,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC,CAC7D,EAAmB,GAAG,EAAS,GAAG,IAAY,IAC9C,EAAyB,GAAG,EAAe,GAAG,IAAY,IAChE,MAAM,EAAc,EAAkB,EAAa,EAAQ,CAC3D,KAAK,OAAO,KACV,EAAO,MAAM,sBAAsB,EAAY,OAAO,wBAAwB,EAAK,GAAG,CACvF,CAED,IAAM,EAAoB,EAAQ,MAAM,CAExC,MAAM,EAAc,EAAwB,EAD3B,EAAK,EAAkB,IAAK,GAAM,OAAO,KAAK,EAAE,CAAC,CAAC,MAAM,CACF,CAAC,CACxE,KAAK,OAAO,KACV,EAAO,MACL,sBAAsB,EAAkB,OAAO,wBAAwB,EAAW,GACnF,CACF,CAED,KAAK,OAAO,KACV,EAAO,KACL,sBAAsB,EAAM,OAAO,sBAAsB,EAAkB,OAAO,qBACnF,CACF,CACD,GAAa,GAYb,eACA,mBACD,CAAC,CAEF,KAAK,OAAO,KACV,EAAO,MAAM,sBAAsB,EAAoB,wBAAwB,EAAK,GAAG,CACxF,CACD,KAAK,OAAO,KACV,EAAO,MACL,sBAAsB,EAA0B,wBAAwB,EAAW,GACpF,CACF"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./constants-BlKpAm3R.mjs";import{t}from"./logger-CPu6zbyQ.mjs";import{n}from"./syncCodePackages-DJnrcX5l.mjs";import{t as r}from"./done-input-validation-LiTaCEzF.mjs";import{t as i}from"./constants-DC_bBO09.mjs";import a from"colors";import o from"fast-glob";import{getEntries as s}from"@transcend-io/type-utils";import{buildTranscendGraphQLClient as c}from"@transcend-io/sdk";import{execSync as l}from"child_process";async function u({scanPath:e,ignoreDirs:n=[],repositoryName:r}){return(await Promise.all(s(i).map(async([i,s])=>{let{ignoreDirs:c,supportedFiles:l,scanFunction:u}=s,d=[...n,...c].filter(e=>e.length>0);try{let n=await o(`${e}/**/${l.join(`|`)}`,{ignore:d.map(t=>`${e}/**/${t}`),unique:!0,onlyFiles:!0});t.info(a.magenta(`Scanning: ${n.length} files of type ${i}`));let s=n.map(t=>u(t).map(n=>({...n,relativePath:t.replace(`${e}/`,``)}))).flat();return t.info(a.green(`Found: ${s.length} packages and ${s.map(({softwareDevelopmentKits:e=[]})=>e).flat().length} sdks`)),s.map(e=>({...e,type:i,repositoryName:r}))}catch(e){throw Error(`Error scanning globs ${l} with error: ${e}`)}}))).flat()}const d=`A repository name must be provided. You can specify using --repositoryName=$REPO_NAME or by ensuring the command "git config --get remote.origin.url" returns the name of the repository`;async function f({auth:t,scanPath:i,ignoreDirs:o,repositoryName:s,transcendUrl:f}){r(this.process);let p=s;if(!p)try{let e=l(`cd ${i} && git config --get remote.origin.url`).toString(`utf-8`).trim();[p]=e.includes(`https:`)?e.split(`/`).slice(3).join(`/`).split(`.`):(e.split(`:`).pop()||``).split(`.`),p||(this.logger.error(a.red(d)),this.process.exit(1))}catch(e){this.logger.error(a.red(`${d} - Got error: ${e.message}`)),this.process.exit(1)}let m=c(f,t),h=await u({scanPath:i,ignoreDirs:o,repositoryName:p});await n(m,h);let g=new URL(e);g.pathname=`/code-scanning/code-packages`,this.logger.info(a.green(`Scan found ${h.length} packages at ${i}! View results at '${g.href}'`))}export{f as scanPackages};
2
- //# sourceMappingURL=impl-C-PvYlFE.mjs.map
1
+ import{t as e}from"./constants-boymUaFC.mjs";import{t}from"./logger-CPu6zbyQ.mjs";import{n}from"./syncCodePackages-DJnrcX5l.mjs";import{t as r}from"./done-input-validation-LiTaCEzF.mjs";import{t as i}from"./constants-DC_bBO09.mjs";import a from"colors";import o from"fast-glob";import{getEntries as s}from"@transcend-io/type-utils";import{buildTranscendGraphQLClient as c}from"@transcend-io/sdk";import{execSync as l}from"child_process";async function u({scanPath:e,ignoreDirs:n=[],repositoryName:r}){return(await Promise.all(s(i).map(async([i,s])=>{let{ignoreDirs:c,supportedFiles:l,scanFunction:u}=s,d=[...n,...c].filter(e=>e.length>0);try{let n=await o(`${e}/**/${l.join(`|`)}`,{ignore:d.map(t=>`${e}/**/${t}`),unique:!0,onlyFiles:!0});t.info(a.magenta(`Scanning: ${n.length} files of type ${i}`));let s=n.map(t=>u(t).map(n=>({...n,relativePath:t.replace(`${e}/`,``)}))).flat();return t.info(a.green(`Found: ${s.length} packages and ${s.map(({softwareDevelopmentKits:e=[]})=>e).flat().length} sdks`)),s.map(e=>({...e,type:i,repositoryName:r}))}catch(e){throw Error(`Error scanning globs ${l} with error: ${e}`)}}))).flat()}const d=`A repository name must be provided. You can specify using --repositoryName=$REPO_NAME or by ensuring the command "git config --get remote.origin.url" returns the name of the repository`;async function f({auth:t,scanPath:i,ignoreDirs:o,repositoryName:s,transcendUrl:f}){r(this.process);let p=s;if(!p)try{let e=l(`cd ${i} && git config --get remote.origin.url`).toString(`utf-8`).trim();[p]=e.includes(`https:`)?e.split(`/`).slice(3).join(`/`).split(`.`):(e.split(`:`).pop()||``).split(`.`),p||(this.logger.error(a.red(d)),this.process.exit(1))}catch(e){this.logger.error(a.red(`${d} - Got error: ${e.message}`)),this.process.exit(1)}let m=c(f,t),h=await u({scanPath:i,ignoreDirs:o,repositoryName:p});await n(m,h);let g=new URL(e);g.pathname=`/code-scanning/code-packages`,this.logger.info(a.green(`Scan found ${h.length} packages at ${i}! View results at '${g.href}'`))}export{f as scanPackages};
2
+ //# sourceMappingURL=impl-BPdvRtQ9.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-C-PvYlFE.mjs","names":[],"sources":["../src/lib/code-scanning/findCodePackagesInFolder.ts","../src/commands/inventory/scan-packages/impl.ts"],"sourcesContent":["import { getEntries } from '@transcend-io/type-utils';\nimport colors from 'colors';\nimport fastGlob from 'fast-glob';\n\nimport { CodePackageInput } from '../../codecs.js';\nimport { logger } from '../../logger.js';\nimport { CODE_SCANNING_CONFIGS } from './constants.js';\n\n/**\n * Helper to scan and discovery all of the code packages within a folder\n *\n * @param options - Options\n * @returns the list of integrations\n */\nexport async function findCodePackagesInFolder({\n scanPath,\n ignoreDirs = [],\n repositoryName,\n}: {\n /** The name of the github repository reporting packages for */\n repositoryName: string;\n /** Where to look for package.json files */\n scanPath: string;\n /** The directories to ignore (excludes node_modules and serverless-build) */\n ignoreDirs?: string[];\n}): Promise<CodePackageInput[]> {\n const allCodePackages = await Promise.all(\n getEntries(CODE_SCANNING_CONFIGS).map(async ([codePackageType, config]) => {\n const { ignoreDirs: configIgnoreDirs, supportedFiles, scanFunction } = config;\n const dirsToIgnore = [...ignoreDirs, ...configIgnoreDirs].filter((dir) => dir.length > 0);\n try {\n const filesToScan: string[] = await fastGlob(`${scanPath}/**/${supportedFiles.join('|')}`, {\n ignore: dirsToIgnore.map((dir: string) => `${scanPath}/**/${dir}`),\n unique: true,\n onlyFiles: true,\n });\n logger.info(\n colors.magenta(`Scanning: ${filesToScan.length} files of type ${codePackageType}`),\n );\n const allPackages = filesToScan\n .map((filePath) =>\n scanFunction(filePath).map((result) => ({\n ...result,\n relativePath: filePath.replace(`${scanPath}/`, ''),\n })),\n )\n .flat();\n logger.info(\n colors.green(\n `Found: ${allPackages.length} packages and ${\n allPackages.map(({ softwareDevelopmentKits = [] }) => softwareDevelopmentKits).flat()\n .length\n } sdks`,\n ),\n );\n\n return allPackages.map(\n (pkg): CodePackageInput => ({\n ...pkg,\n type: codePackageType,\n repositoryName,\n }),\n );\n } catch (error) {\n throw new Error(`Error scanning globs ${supportedFiles} with error: ${error}`);\n }\n }),\n );\n\n return allCodePackages.flat();\n}\n","import { execSync } from 'child_process';\n\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport colors from 'colors';\n\nimport { ADMIN_DASH } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { findCodePackagesInFolder } from '../../../lib/code-scanning/index.js';\nimport { syncCodePackages } from '../../../lib/graphql/index.js';\n\nconst REPO_ERROR =\n 'A repository name must be provided. ' +\n 'You can specify using --repositoryName=$REPO_NAME or by ensuring the ' +\n 'command \"git config --get remote.origin.url\" returns the name of the repository';\n\nexport interface ScanPackagesCommandFlags {\n auth: string;\n scanPath: string;\n ignoreDirs?: string[];\n repositoryName?: string;\n transcendUrl: string;\n}\n\nexport async function scanPackages(\n this: LocalContext,\n { auth, scanPath, ignoreDirs, repositoryName, transcendUrl }: ScanPackagesCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n // Ensure repository name is specified\n let gitRepositoryName = repositoryName;\n if (!gitRepositoryName) {\n try {\n const name = execSync(`cd ${scanPath} && git config --get remote.origin.url`);\n // Trim and parse the URL\n const url = name.toString('utf-8').trim();\n [gitRepositoryName] = !url.includes('https:')\n ? (url.split(':').pop() || '').split('.')\n : url.split('/').slice(3).join('/').split('.');\n if (!gitRepositoryName) {\n this.logger.error(colors.red(REPO_ERROR));\n this.process.exit(1);\n }\n } catch (err) {\n this.logger.error(colors.red(`${REPO_ERROR} - Got error: ${err.message}`));\n this.process.exit(1);\n }\n }\n\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Scan the codebase to discovery packages\n const results = await findCodePackagesInFolder({\n scanPath,\n ignoreDirs,\n repositoryName: gitRepositoryName,\n });\n\n // Report scan to Transcend\n await syncCodePackages(client, results);\n\n const newUrl = new URL(ADMIN_DASH);\n newUrl.pathname = '/code-scanning/code-packages';\n\n // Indicate success\n this.logger.info(\n colors.green(\n `Scan found ${results.length} packages at ${scanPath}! ` + `View results at '${newUrl.href}'`,\n ),\n );\n}\n"],"mappings":"qbAcA,eAAsB,EAAyB,CAC7C,WACA,aAAa,EAAE,CACf,kBAQ8B,CA4C9B,OAAO,MA3CuB,QAAQ,IACpC,EAAW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,CAAC,KAAK,EAAI,IAAI,MAAM,IAAI,CAEtC,IACH,KAAK,OAAO,MAAM,EAAO,IAAI,EAAW,CAAC,CACzC,KAAK,QAAQ,KAAK,EAAE,QAEf,EAAK,CACZ,KAAK,OAAO,MAAM,EAAO,IAAI,GAAG,EAAW,gBAAgB,EAAI,UAAU,CAAC,CAC1E,KAAK,QAAQ,KAAK,EAAE,CAKxB,IAAM,EAAS,EAA4B,EAAc,EAAK,CAGxD,EAAU,MAAM,EAAyB,CAC7C,WACA,aACA,eAAgB,EACjB,CAAC,CAGF,MAAM,EAAiB,EAAQ,EAAQ,CAEvC,IAAM,EAAS,IAAI,IAAI,EAAW,CAClC,EAAO,SAAW,+BAGlB,KAAK,OAAO,KACV,EAAO,MACL,cAAc,EAAQ,OAAO,eAAe,EAAS,qBAA0B,EAAO,KAAK,GAC5F,CACF"}
1
+ {"version":3,"file":"impl-BPdvRtQ9.mjs","names":[],"sources":["../src/lib/code-scanning/findCodePackagesInFolder.ts","../src/commands/inventory/scan-packages/impl.ts"],"sourcesContent":["import { getEntries } from '@transcend-io/type-utils';\nimport colors from 'colors';\nimport fastGlob from 'fast-glob';\n\nimport { CodePackageInput } from '../../codecs.js';\nimport { logger } from '../../logger.js';\nimport { CODE_SCANNING_CONFIGS } from './constants.js';\n\n/**\n * Helper to scan and discovery all of the code packages within a folder\n *\n * @param options - Options\n * @returns the list of integrations\n */\nexport async function findCodePackagesInFolder({\n scanPath,\n ignoreDirs = [],\n repositoryName,\n}: {\n /** The name of the github repository reporting packages for */\n repositoryName: string;\n /** Where to look for package.json files */\n scanPath: string;\n /** The directories to ignore (excludes node_modules and serverless-build) */\n ignoreDirs?: string[];\n}): Promise<CodePackageInput[]> {\n const allCodePackages = await Promise.all(\n getEntries(CODE_SCANNING_CONFIGS).map(async ([codePackageType, config]) => {\n const { ignoreDirs: configIgnoreDirs, supportedFiles, scanFunction } = config;\n const dirsToIgnore = [...ignoreDirs, ...configIgnoreDirs].filter((dir) => dir.length > 0);\n try {\n const filesToScan: string[] = await fastGlob(`${scanPath}/**/${supportedFiles.join('|')}`, {\n ignore: dirsToIgnore.map((dir: string) => `${scanPath}/**/${dir}`),\n unique: true,\n onlyFiles: true,\n });\n logger.info(\n colors.magenta(`Scanning: ${filesToScan.length} files of type ${codePackageType}`),\n );\n const allPackages = filesToScan\n .map((filePath) =>\n scanFunction(filePath).map((result) => ({\n ...result,\n relativePath: filePath.replace(`${scanPath}/`, ''),\n })),\n )\n .flat();\n logger.info(\n colors.green(\n `Found: ${allPackages.length} packages and ${\n allPackages.map(({ softwareDevelopmentKits = [] }) => softwareDevelopmentKits).flat()\n .length\n } sdks`,\n ),\n );\n\n return allPackages.map(\n (pkg): CodePackageInput => ({\n ...pkg,\n type: codePackageType,\n repositoryName,\n }),\n );\n } catch (error) {\n throw new Error(`Error scanning globs ${supportedFiles} with error: ${error}`);\n }\n }),\n );\n\n return allCodePackages.flat();\n}\n","import { execSync } from 'child_process';\n\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport colors from 'colors';\n\nimport { ADMIN_DASH } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { findCodePackagesInFolder } from '../../../lib/code-scanning/index.js';\nimport { syncCodePackages } from '../../../lib/graphql/index.js';\n\nconst REPO_ERROR =\n 'A repository name must be provided. ' +\n 'You can specify using --repositoryName=$REPO_NAME or by ensuring the ' +\n 'command \"git config --get remote.origin.url\" returns the name of the repository';\n\nexport interface ScanPackagesCommandFlags {\n auth: string;\n scanPath: string;\n ignoreDirs?: string[];\n repositoryName?: string;\n transcendUrl: string;\n}\n\nexport async function scanPackages(\n this: LocalContext,\n { auth, scanPath, ignoreDirs, repositoryName, transcendUrl }: ScanPackagesCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n // Ensure repository name is specified\n let gitRepositoryName = repositoryName;\n if (!gitRepositoryName) {\n try {\n const name = execSync(`cd ${scanPath} && git config --get remote.origin.url`);\n // Trim and parse the URL\n const url = name.toString('utf-8').trim();\n [gitRepositoryName] = !url.includes('https:')\n ? (url.split(':').pop() || '').split('.')\n : url.split('/').slice(3).join('/').split('.');\n if (!gitRepositoryName) {\n this.logger.error(colors.red(REPO_ERROR));\n this.process.exit(1);\n }\n } catch (err) {\n this.logger.error(colors.red(`${REPO_ERROR} - Got error: ${err.message}`));\n this.process.exit(1);\n }\n }\n\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Scan the codebase to discovery packages\n const results = await findCodePackagesInFolder({\n scanPath,\n ignoreDirs,\n repositoryName: gitRepositoryName,\n });\n\n // Report scan to Transcend\n await syncCodePackages(client, results);\n\n const newUrl = new URL(ADMIN_DASH);\n newUrl.pathname = '/code-scanning/code-packages';\n\n // Indicate success\n this.logger.info(\n colors.green(\n `Scan found ${results.length} packages at ${scanPath}! ` + `View results at '${newUrl.href}'`,\n ),\n );\n}\n"],"mappings":"qbAcA,eAAsB,EAAyB,CAC7C,WACA,aAAa,EAAE,CACf,kBAQ8B,CA4C9B,OAAO,MA3CuB,QAAQ,IACpC,EAAW,EAAsB,CAAC,IAAI,MAAO,CAAC,EAAiB,KAAY,CACzE,GAAM,CAAE,WAAY,EAAkB,iBAAgB,gBAAiB,EACjE,EAAe,CAAC,GAAG,EAAY,GAAG,EAAiB,CAAC,OAAQ,GAAQ,EAAI,OAAS,EAAE,CACzF,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,KACL,EAAO,QAAQ,aAAa,EAAY,OAAO,iBAAiB,IAAkB,CACnF,CACD,IAAM,EAAc,EACjB,IAAK,GACJ,EAAa,EAAS,CAAC,IAAK,IAAY,CACtC,GAAG,EACH,aAAc,EAAS,QAAQ,G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5F,CACF"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./updateConsentManagerVersionToLatest-KwMaAkwh.mjs";import{t}from"./validateTranscendAuth-D-dDINof.mjs";import{t as n}from"./done-input-validation-LiTaCEzF.mjs";import{ConsentBundleType as r}from"@transcend-io/privacy-types";import i from"colors";import{mapSeries as a}from"@transcend-io/utils";async function o({auth:o,bundleTypes:s=[r.Production,r.Test],deploy:c,transcendUrl:l}){n(this.process);let u=await t(o,this);typeof u==`string`?(await e({deploy:c,transcendUrl:l,auth:u,bundleTypes:s}),this.logger.info(i.green(`Successfully updated Consent Manager!`))):(await a(u,async t=>{this.logger.info(i.magenta(`Updating Consent Manager for organization "${t.organizationName}"...`)),await e({deploy:c,transcendUrl:l,auth:t.apiKey,bundleTypes:s}),this.logger.info(i.green(`Successfully updated Consent Manager for organization "${t.organizationName}"!`))}),this.logger.info(i.green(`Successfully updated Consent Managers!`)))}export{o as updateConsentManager};
2
- //# sourceMappingURL=impl-B_CRtRo8.mjs.map
1
+ import{t as e}from"./updateConsentManagerVersionToLatest-cryDInky.mjs";import{t}from"./validateTranscendAuth-D-dDINof.mjs";import{t as n}from"./done-input-validation-LiTaCEzF.mjs";import{ConsentBundleType as r}from"@transcend-io/privacy-types";import i from"colors";import{mapSeries as a}from"@transcend-io/utils";async function o({auth:o,bundleTypes:s=[r.Production,r.Test],deploy:c,transcendUrl:l}){n(this.process);let u=await t(o,this);typeof u==`string`?(await e({deploy:c,transcendUrl:l,auth:u,bundleTypes:s}),this.logger.info(i.green(`Successfully updated Consent Manager!`))):(await a(u,async t=>{this.logger.info(i.magenta(`Updating Consent Manager for organization "${t.organizationName}"...`)),await e({deploy:c,transcendUrl:l,auth:t.apiKey,bundleTypes:s}),this.logger.info(i.green(`Successfully updated Consent Manager for organization "${t.organizationName}"!`))}),this.logger.info(i.green(`Successfully updated Consent Managers!`)))}export{o as updateConsentManager};
2
+ //# sourceMappingURL=impl-BUJbKCd4.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-B_CRtRo8.mjs","names":[],"sources":["../src/commands/consent/update-consent-manager/impl.ts"],"sourcesContent":["import { ConsentBundleType } from '@transcend-io/privacy-types';\nimport { mapSeries } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { validateTranscendAuth } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { updateConsentManagerVersionToLatest } from '../../../lib/consent-manager/index.js';\n\nexport interface UpdateConsentManagerCommandFlags {\n auth: string;\n bundleTypes: ConsentBundleType[];\n deploy: boolean;\n transcendUrl: string;\n}\n\nexport async function updateConsentManager(\n this: LocalContext,\n {\n auth,\n bundleTypes = [ConsentBundleType.Production, ConsentBundleType.Test],\n deploy,\n transcendUrl,\n }: UpdateConsentManagerCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth, this);\n\n // Handle single update\n if (typeof apiKeyOrList === 'string') {\n // Update consent manager\n await updateConsentManagerVersionToLatest({\n deploy,\n transcendUrl,\n auth: apiKeyOrList,\n bundleTypes,\n });\n this.logger.info(colors.green('Successfully updated Consent Manager!'));\n } else {\n await mapSeries(apiKeyOrList, async (apiKey) => {\n this.logger.info(\n colors.magenta(`Updating Consent Manager for organization \"${apiKey.organizationName}\"...`),\n );\n\n await updateConsentManagerVersionToLatest({\n deploy,\n transcendUrl,\n auth: apiKey.apiKey,\n bundleTypes,\n });\n\n this.logger.info(\n colors.green(\n `Successfully updated Consent Manager for organization \"${apiKey.organizationName}\"!`,\n ),\n );\n });\n this.logger.info(colors.green('Successfully updated Consent Managers!'));\n }\n}\n"],"mappings":"0TAgBA,eAAsB,EAEpB,CACE,OACA,cAAc,CAAC,EAAkB,WAAY,EAAkB,KAAK,CACpE,SACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,CAGjC,IAAM,EAAe,MAAM,EAAsB,EAAM,KAAK,CAGxD,OAAO,GAAiB,UAE1B,MAAM,EAAoC,CACxC,SACA,eACA,KAAM,EACN,cACD,CAAC,CACF,KAAK,OAAO,KAAK,EAAO,MAAM,wCAAwC,CAAC,GAEvE,MAAM,EAAU,EAAc,KAAO,IAAW,CAC9C,KAAK,OAAO,KACV,EAAO,QAAQ,8CAA8C,EAAO,iBAAiB,MAAM,CAC5F,CAED,MAAM,EAAoC,CACxC,SACA,eACA,KAAM,EAAO,OACb,cACD,CAAC,CAEF,KAAK,OAAO,KACV,EAAO,MACL,0DAA0D,EAAO,iBAAiB,IACnF,CACF,EACD,CACF,KAAK,OAAO,KAAK,EAAO,MAAM,yCAAyC,CAAC"}
1
+ {"version":3,"file":"impl-BUJbKCd4.mjs","names":[],"sources":["../src/commands/consent/update-consent-manager/impl.ts"],"sourcesContent":["import { ConsentBundleType } from '@transcend-io/privacy-types';\nimport { mapSeries } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { validateTranscendAuth } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { updateConsentManagerVersionToLatest } from '../../../lib/consent-manager/index.js';\n\nexport interface UpdateConsentManagerCommandFlags {\n auth: string;\n bundleTypes: ConsentBundleType[];\n deploy: boolean;\n transcendUrl: string;\n}\n\nexport async function updateConsentManager(\n this: LocalContext,\n {\n auth,\n bundleTypes = [ConsentBundleType.Production, ConsentBundleType.Test],\n deploy,\n transcendUrl,\n }: UpdateConsentManagerCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth, this);\n\n // Handle single update\n if (typeof apiKeyOrList === 'string') {\n // Update consent manager\n await updateConsentManagerVersionToLatest({\n deploy,\n transcendUrl,\n auth: apiKeyOrList,\n bundleTypes,\n });\n this.logger.info(colors.green('Successfully updated Consent Manager!'));\n } else {\n await mapSeries(apiKeyOrList, async (apiKey) => {\n this.logger.info(\n colors.magenta(`Updating Consent Manager for organization \"${apiKey.organizationName}\"...`),\n );\n\n await updateConsentManagerVersionToLatest({\n deploy,\n transcendUrl,\n auth: apiKey.apiKey,\n bundleTypes,\n });\n\n this.logger.info(\n colors.green(\n `Successfully updated Consent Manager for organization \"${apiKey.organizationName}\"!`,\n ),\n );\n });\n this.logger.info(colors.green('Successfully updated Consent Managers!'));\n }\n}\n"],"mappings":"0TAgBA,eAAsB,EAEpB,CACE,OACA,cAAc,CAAC,EAAkB,WAAY,EAAkB,KAAK,CACpE,SACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,CAGjC,IAAM,EAAe,MAAM,EAAsB,EAAM,KAAK,CAGxD,OAAO,GAAiB,UAE1B,MAAM,EAAoC,CACxC,SACA,eACA,KAAM,EACN,cACD,CAAC,CACF,KAAK,OAAO,KAAK,EAAO,MAAM,wCAAwC,CAAC,GAEvE,MAAM,EAAU,EAAc,KAAO,IAAW,CAC9C,KAAK,OAAO,KACV,EAAO,QAAQ,8CAA8C,EAAO,iBAAiB,MAAM,CAC5F,CAED,MAAM,EAAoC,CACxC,SACA,eACA,KAAM,EAAO,OACb,cACD,CAAC,CAEF,KAAK,OAAO,KACV,EAAO,MACL,0DAA0D,EAAO,iBAAiB,IACnF,CACF,EACD,CACF,KAAK,OAAO,KAAK,EAAO,MAAM,yCAAyC,CAAC"}
@@ -1,2 +1,2 @@
1
- import{g as e}from"./constants-BlKpAm3R.mjs";import{r as t,t as n}from"./project-plan-output-BHHlkLxe.mjs";import{t as r}from"./project-discovery-CWRjlFnC.mjs";import{t as i}from"./done-input-validation-LiTaCEzF.mjs";import{n as a}from"./project-discovery-BkHpTXDx.mjs";import{i as o,n as s,r as c,t as l}from"./prompts-BhXfYD6g.mjs";import{t as u}from"./run-captured-process-BjaSDWXG.mjs";import{r as d,t as f}from"./deno-runtime-CB2HBach.mjs";import{t as p}from"./scaffold-model-CUZER0BC.mjs";import{t as m}from"./project-plan-apply-Bg_1eMX9.mjs";import{c as h,i as g,n as _,s as v}from"./scaffold-planning-CaetLfv8.mjs";import y from"colors";import{CUSTOM_FUNCTION_TYPES_VERSION as b}from"@transcend-io/custom-function-types";const x={[p.Deno]:`Deno configuration`,[p.Editor]:`VS Code settings`,[p.Skill]:`Agent skill`,[p.Ci]:`GitHub Actions`},S=Object.values(p);async function C(C,w){i(this.process);try{let i=a(this,{...w?{directory:w}:{},...C.manifest?{manifest:C.manifest}:{}}),l=new s(this),T=c(C,this.process.stdin.isTTY,this.process.stderr.isTTY),E=await o(l,{features:S,labels:x,enabled:{[p.Deno]:C.deno,[p.Editor]:C.editor,[p.Skill]:C.skill,[p.Ci]:C.ci},interactive:T}),D=_({state:i,snapshots:r(this,i.projectRoot,g(i,{features:E})),contractVersion:b,cliVersion:e},{features:E});if(E.includes(p.Deno)){let e=await u(`deno`,[`--version`],{cwd:this.process.cwd()},this);if(e.error?.code===`ENOENT`)D.warnings.push(`Deno 2.x is not installed. Install it from ${f}`);else if(e.code!==0)D.warnings.push(`Deno was found, but its version could not be determined. Deno 2.x is required. See ${f}`);else{let t=d(e.stdout);t.level!==`compatible`&&D.warnings.push(t.message)}}C.json||this.logger.info(t(D,{cwd:this.process.cwd(),title:`Custom Function plan`,details:[{label:`Target`,path:D.targetDirectory},{label:`Manifest`,path:D.manifestPath}]}));let O=D.changes.length===0||C.dryRun;if(D.changes.length>0&&!C.dryRun)if(C.yes)O=!0;else if(T)O=await l.confirm(`Apply this complete plan?`,!0);else throw Error(`The plan requires approval in a non-interactive invocation. Review with --dryRun, then pass --yes.`);O&&!C.dryRun&&D.changes.length>0&&await m(this,D);let k=O&&!C.dryRun&&D.changes.length>0,A=O&&!C.dryRun,j=h({targetDirectory:n(this.process.cwd(),i.targetDirectory),manifestPath:n(this.process.cwd(),i.manifestPath),cliVersion:e,hasSkill:A&&E.includes(p.Skill),hasGithubWorkflow:A&&E.includes(p.Ci)&&!!(i.repositoryRoot&&i.usesGithub)}),M=v(D,{applied:k,dryRun:C.dryRun,cwd:this.process.cwd(),aiHandoff:j});if(C.json){this.process.stdout.write(`${JSON.stringify(M)}\n`);return}if(C.dryRun){this.logger.info(y.yellow(`Dry run complete. No changes were written.`));return}if(!O){this.logger.info(y.yellow(`No changes applied.`));return}if(D.changes.length===0){this.logger.info(y.green(`Custom Function project is already initialized.`));return}this.logger.info(y.green(`Custom Function project initialized.`)),D.nextSteps.length>0&&(this.logger.info(`\n${y.bold(`Next steps`)}`),D.nextSteps.forEach(e=>this.logger.info(e))),this.logger.info(`\n${y.bold(`AI handoff — paste into your coding agent`)}`),this.logger.info(j)}catch(e){throw e instanceof l&&this.process.exit(130),e}}export{C as init};
2
- //# sourceMappingURL=impl-BxvKe9_7.mjs.map
1
+ import{g as e}from"./constants-boymUaFC.mjs";import{r as t,t as n}from"./project-plan-output-BHHlkLxe.mjs";import{t as r}from"./project-discovery-CWRjlFnC.mjs";import{t as i}from"./done-input-validation-LiTaCEzF.mjs";import{n as a}from"./project-discovery-BkHpTXDx.mjs";import{i as o,n as s,r as c,t as l}from"./prompts-BhXfYD6g.mjs";import{t as u}from"./run-captured-process-BjaSDWXG.mjs";import{r as d,t as f}from"./deno-runtime-CB2HBach.mjs";import{t as p}from"./scaffold-model-CUZER0BC.mjs";import{t as m}from"./project-plan-apply-Bg_1eMX9.mjs";import{c as h,i as g,n as _,s as v}from"./scaffold-planning-CaetLfv8.mjs";import y from"colors";import{CUSTOM_FUNCTION_TYPES_VERSION as b}from"@transcend-io/custom-function-types";const x={[p.Deno]:`Deno configuration`,[p.Editor]:`VS Code settings`,[p.Skill]:`Agent skill`,[p.Ci]:`GitHub Actions`},S=Object.values(p);async function C(C,w){i(this.process);try{let i=a(this,{...w?{directory:w}:{},...C.manifest?{manifest:C.manifest}:{}}),l=new s(this),T=c(C,this.process.stdin.isTTY,this.process.stderr.isTTY),E=await o(l,{features:S,labels:x,enabled:{[p.Deno]:C.deno,[p.Editor]:C.editor,[p.Skill]:C.skill,[p.Ci]:C.ci},interactive:T}),D=_({state:i,snapshots:r(this,i.projectRoot,g(i,{features:E})),contractVersion:b,cliVersion:e},{features:E});if(E.includes(p.Deno)){let e=await u(`deno`,[`--version`],{cwd:this.process.cwd()},this);if(e.error?.code===`ENOENT`)D.warnings.push(`Deno 2.x is not installed. Install it from ${f}`);else if(e.code!==0)D.warnings.push(`Deno was found, but its version could not be determined. Deno 2.x is required. See ${f}`);else{let t=d(e.stdout);t.level!==`compatible`&&D.warnings.push(t.message)}}C.json||this.logger.info(t(D,{cwd:this.process.cwd(),title:`Custom Function plan`,details:[{label:`Target`,path:D.targetDirectory},{label:`Manifest`,path:D.manifestPath}]}));let O=D.changes.length===0||C.dryRun;if(D.changes.length>0&&!C.dryRun)if(C.yes)O=!0;else if(T)O=await l.confirm(`Apply this complete plan?`,!0);else throw Error(`The plan requires approval in a non-interactive invocation. Review with --dryRun, then pass --yes.`);O&&!C.dryRun&&D.changes.length>0&&await m(this,D);let k=O&&!C.dryRun&&D.changes.length>0,A=O&&!C.dryRun,j=h({targetDirectory:n(this.process.cwd(),i.targetDirectory),manifestPath:n(this.process.cwd(),i.manifestPath),cliVersion:e,hasSkill:A&&E.includes(p.Skill),hasGithubWorkflow:A&&E.includes(p.Ci)&&!!(i.repositoryRoot&&i.usesGithub)}),M=v(D,{applied:k,dryRun:C.dryRun,cwd:this.process.cwd(),aiHandoff:j});if(C.json){this.process.stdout.write(`${JSON.stringify(M)}\n`);return}if(C.dryRun){this.logger.info(y.yellow(`Dry run complete. No changes were written.`));return}if(!O){this.logger.info(y.yellow(`No changes applied.`));return}if(D.changes.length===0){this.logger.info(y.green(`Custom Function project is already initialized.`));return}this.logger.info(y.green(`Custom Function project initialized.`)),D.nextSteps.length>0&&(this.logger.info(`\n${y.bold(`Next steps`)}`),D.nextSteps.forEach(e=>this.logger.info(e))),this.logger.info(`\n${y.bold(`AI handoff — paste into your coding agent`)}`),this.logger.info(j)}catch(e){throw e instanceof l&&this.process.exit(130),e}}export{C as init};
2
+ //# sourceMappingURL=impl-BbzX8auO.mjs.map