@transcend-io/cli 10.5.4 → 10.5.7

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 (183) hide show
  1. package/dist/app-DzXC3o66.mjs +131 -0
  2. package/dist/{app-CGrl8jGp.mjs.map → app-DzXC3o66.mjs.map} +1 -1
  3. package/dist/{approvePrivacyRequests-B-pGYZ3B.mjs → approvePrivacyRequests-CiJJar6N.mjs} +2 -2
  4. package/dist/{approvePrivacyRequests-B-pGYZ3B.mjs.map → approvePrivacyRequests-CiJJar6N.mjs.map} +1 -1
  5. package/dist/bin/bash-complete.mjs +1 -1
  6. package/dist/bin/cli.mjs +1 -1
  7. package/dist/bin/deprecated-command.mjs +1 -1
  8. package/dist/bin/deprecated-command.mjs.map +1 -1
  9. package/dist/{buildXdiSyncEndpoint-3C-ODh2I.mjs → buildXdiSyncEndpoint-CSOGLrEh.mjs} +2 -2
  10. package/dist/{buildXdiSyncEndpoint-3C-ODh2I.mjs.map → buildXdiSyncEndpoint-CSOGLrEh.mjs.map} +1 -1
  11. package/dist/{bulkRestartRequests-DTBSNfe1.mjs → bulkRestartRequests-BFYgQddg.mjs} +2 -2
  12. package/dist/{bulkRestartRequests-DTBSNfe1.mjs.map → bulkRestartRequests-BFYgQddg.mjs.map} +1 -1
  13. package/dist/{bulkRetryEnrichers-DP8sSSyj.mjs → bulkRetryEnrichers-C1TsWVFy.mjs} +2 -2
  14. package/dist/{bulkRetryEnrichers-DP8sSSyj.mjs.map → bulkRetryEnrichers-C1TsWVFy.mjs.map} +1 -1
  15. package/dist/{cancelPrivacyRequests-B96uHF1A.mjs → cancelPrivacyRequests-CpECjTPR.mjs} +2 -2
  16. package/dist/{cancelPrivacyRequests-B96uHF1A.mjs.map → cancelPrivacyRequests-CpECjTPR.mjs.map} +1 -1
  17. package/dist/codecs-Dnq-rEcB.mjs +2 -0
  18. package/dist/codecs-Dnq-rEcB.mjs.map +1 -0
  19. package/dist/collectCsvFilesOrExit-CbtyKAzu.mjs.map +1 -1
  20. package/dist/collectParquetFilesOrExit-BJiAyaQ5.mjs.map +1 -1
  21. package/dist/{command-CNHVi3X1.mjs → command-BVxNkJEw.mjs} +2 -2
  22. package/dist/{command-CNHVi3X1.mjs.map → command-BVxNkJEw.mjs.map} +1 -1
  23. package/dist/constants-BmwXDQu9.mjs.map +1 -1
  24. package/dist/constants-CLxPXlJM.mjs +2 -0
  25. package/dist/{constants-ClkQQhJs.mjs.map → constants-CLxPXlJM.mjs.map} +1 -1
  26. package/dist/constants-zytGRR9s.mjs +2 -0
  27. package/dist/{constants-BOycJ_AQ.mjs.map → constants-zytGRR9s.mjs.map} +1 -1
  28. package/dist/{createExtraKeyHandler-Dz15OUvs.mjs → createExtraKeyHandler-2BcgOSo8.mjs} +3 -3
  29. package/dist/{createExtraKeyHandler-Dz15OUvs.mjs.map → createExtraKeyHandler-2BcgOSo8.mjs.map} +1 -1
  30. package/dist/dataFlowsToDataSilos-Ca2DtTsd.mjs.map +1 -1
  31. package/dist/{downloadPrivacyRequestFiles-Aneyb8TU.mjs → downloadPrivacyRequestFiles-B1rI73ok.mjs} +2 -2
  32. package/dist/{downloadPrivacyRequestFiles-Aneyb8TU.mjs.map → downloadPrivacyRequestFiles-B1rI73ok.mjs.map} +1 -1
  33. package/dist/fetchAllRequests-CHHdyb4Q.mjs.map +1 -1
  34. package/dist/{generateCrossAccountApiKeys-wIS5jh1i.mjs → generateCrossAccountApiKeys-FUo_wsSM.mjs} +2 -2
  35. package/dist/{generateCrossAccountApiKeys-wIS5jh1i.mjs.map → generateCrossAccountApiKeys-FUo_wsSM.mjs.map} +1 -1
  36. package/dist/{impl-8WdsvXOc.mjs → impl-AgujmepV.mjs} +2 -2
  37. package/dist/{impl-8WdsvXOc.mjs.map → impl-AgujmepV.mjs.map} +1 -1
  38. package/dist/{impl-CzUXWrgQ.mjs → impl-B3-wUMSZ.mjs} +2 -2
  39. package/dist/{impl-CzUXWrgQ.mjs.map → impl-B3-wUMSZ.mjs.map} +1 -1
  40. package/dist/{impl-zTKleu53.mjs → impl-B78f1YnE.mjs} +2 -2
  41. package/dist/{impl-zTKleu53.mjs.map → impl-B78f1YnE.mjs.map} +1 -1
  42. package/dist/{impl-HSoEoM66.mjs → impl-BTTzSg7k.mjs} +2 -2
  43. package/dist/{impl-HSoEoM66.mjs.map → impl-BTTzSg7k.mjs.map} +1 -1
  44. package/dist/{impl-Ph9niRN-.mjs → impl-BUjfG4eC.mjs} +2 -2
  45. package/dist/{impl-Ph9niRN-.mjs.map → impl-BUjfG4eC.mjs.map} +1 -1
  46. package/dist/{impl-piZKrouV.mjs → impl-BW0nZQcf.mjs} +2 -2
  47. package/dist/{impl-piZKrouV.mjs.map → impl-BW0nZQcf.mjs.map} +1 -1
  48. package/dist/{impl-CFYxHmDT.mjs → impl-BhNnDVWM.mjs} +2 -2
  49. package/dist/{impl-CFYxHmDT.mjs.map → impl-BhNnDVWM.mjs.map} +1 -1
  50. package/dist/impl-BjCQSRLu.mjs.map +1 -1
  51. package/dist/{impl-Cg9TvlD0.mjs → impl-Bjf36di3.mjs} +2 -2
  52. package/dist/{impl-Cg9TvlD0.mjs.map → impl-Bjf36di3.mjs.map} +1 -1
  53. package/dist/{impl-C3B_DbVl.mjs → impl-BnME6ASm.mjs} +2 -2
  54. package/dist/{impl-C3B_DbVl.mjs.map → impl-BnME6ASm.mjs.map} +1 -1
  55. package/dist/{impl-D0_1vCyS.mjs → impl-BwKFPCHn.mjs} +2 -2
  56. package/dist/{impl-D0_1vCyS.mjs.map → impl-BwKFPCHn.mjs.map} +1 -1
  57. package/dist/{impl-DCC9QQh4.mjs → impl-C08anQRz.mjs} +2 -2
  58. package/dist/{impl-DCC9QQh4.mjs.map → impl-C08anQRz.mjs.map} +1 -1
  59. package/dist/{impl-CPPvCxrg.mjs → impl-C2to-OHX.mjs} +2 -2
  60. package/dist/{impl-CPPvCxrg.mjs.map → impl-C2to-OHX.mjs.map} +1 -1
  61. package/dist/{impl-v4FNox3W.mjs → impl-C9By5dWV.mjs} +2 -2
  62. package/dist/{impl-v4FNox3W.mjs.map → impl-C9By5dWV.mjs.map} +1 -1
  63. package/dist/{impl-E3r8gzm6.mjs → impl-CA4HCgZH.mjs} +2 -2
  64. package/dist/{impl-E3r8gzm6.mjs.map → impl-CA4HCgZH.mjs.map} +1 -1
  65. package/dist/{impl-y6OJgoDw.mjs → impl-CCw9Nk9s.mjs} +2 -2
  66. package/dist/{impl-y6OJgoDw.mjs.map → impl-CCw9Nk9s.mjs.map} +1 -1
  67. package/dist/{impl-uxQT5IZV.mjs → impl-CEhKFcOU.mjs} +2 -2
  68. package/dist/{impl-uxQT5IZV.mjs.map → impl-CEhKFcOU.mjs.map} +1 -1
  69. package/dist/{impl-DfKBJwNF.mjs → impl-CH0jeBtq.mjs} +2 -2
  70. package/dist/{impl-DfKBJwNF.mjs.map → impl-CH0jeBtq.mjs.map} +1 -1
  71. package/dist/{impl-Ca9jo1uf.mjs → impl-CTre0PAy.mjs} +2 -2
  72. package/dist/{impl-Ca9jo1uf.mjs.map → impl-CTre0PAy.mjs.map} +1 -1
  73. package/dist/{impl-CldmgMzS.mjs → impl-CWGE0wkZ.mjs} +2 -2
  74. package/dist/{impl-CldmgMzS.mjs.map → impl-CWGE0wkZ.mjs.map} +1 -1
  75. package/dist/{impl-B0XDaW-q.mjs → impl-CWIKNmbA.mjs} +2 -2
  76. package/dist/{impl-B0XDaW-q.mjs.map → impl-CWIKNmbA.mjs.map} +1 -1
  77. package/dist/{impl-8BvKYax5.mjs → impl-CWxFcw0g.mjs} +2 -2
  78. package/dist/{impl-8BvKYax5.mjs.map → impl-CWxFcw0g.mjs.map} +1 -1
  79. package/dist/{impl-CN7qqr0l.mjs → impl-CXOR_MZL.mjs} +2 -2
  80. package/dist/{impl-CN7qqr0l.mjs.map → impl-CXOR_MZL.mjs.map} +1 -1
  81. package/dist/{impl-DHW1Tt2p.mjs → impl-CkCbsgWr.mjs} +2 -2
  82. package/dist/{impl-DHW1Tt2p.mjs.map → impl-CkCbsgWr.mjs.map} +1 -1
  83. package/dist/impl-Cw3_0zqC.mjs.map +1 -1
  84. package/dist/{impl-CUly8WpU.mjs → impl-CyNmrj6z.mjs} +2 -2
  85. package/dist/{impl-CUly8WpU.mjs.map → impl-CyNmrj6z.mjs.map} +1 -1
  86. package/dist/{impl-DVpGoSQ9.mjs → impl-D2TC7ZOH.mjs} +2 -2
  87. package/dist/{impl-DVpGoSQ9.mjs.map → impl-D2TC7ZOH.mjs.map} +1 -1
  88. package/dist/{impl-BZIZuD4O.mjs → impl-D5kcMRqr.mjs} +2 -2
  89. package/dist/{impl-BZIZuD4O.mjs.map → impl-D5kcMRqr.mjs.map} +1 -1
  90. package/dist/impl-DKIBerx4.mjs +4 -0
  91. package/dist/{impl-BjIylEKQ.mjs.map → impl-DKIBerx4.mjs.map} +1 -1
  92. package/dist/impl-DQQ_nI25.mjs.map +1 -1
  93. package/dist/{impl-DmFYqMyc.mjs → impl-DT3pE3Ze.mjs} +2 -2
  94. package/dist/{impl-DmFYqMyc.mjs.map → impl-DT3pE3Ze.mjs.map} +1 -1
  95. package/dist/{impl-DXHqqWJb.mjs → impl-DiHeNVFr.mjs} +2 -2
  96. package/dist/{impl-DXHqqWJb.mjs.map → impl-DiHeNVFr.mjs.map} +1 -1
  97. package/dist/{impl-BZQ0KiYZ.mjs → impl-Dk94fgeK.mjs} +2 -2
  98. package/dist/{impl-BZQ0KiYZ.mjs.map → impl-Dk94fgeK.mjs.map} +1 -1
  99. package/dist/{impl-BuxT4Cx2.mjs → impl-Dm6ITkBn.mjs} +2 -2
  100. package/dist/{impl-BuxT4Cx2.mjs.map → impl-Dm6ITkBn.mjs.map} +1 -1
  101. package/dist/{impl-j0jL7UnC.mjs → impl-EgoVUcWR.mjs} +2 -2
  102. package/dist/{impl-j0jL7UnC.mjs.map → impl-EgoVUcWR.mjs.map} +1 -1
  103. package/dist/{impl-Clog0IsW.mjs → impl-WDt81-Vk.mjs} +2 -2
  104. package/dist/{impl-Clog0IsW.mjs.map → impl-WDt81-Vk.mjs.map} +1 -1
  105. package/dist/{impl-BW3HCdPO.mjs → impl-Xona8YN1.mjs} +2 -2
  106. package/dist/{impl-BW3HCdPO.mjs.map → impl-Xona8YN1.mjs.map} +1 -1
  107. package/dist/{impl-DgRkDJIM.mjs → impl-dQg1-ZW6.mjs} +2 -2
  108. package/dist/{impl-DgRkDJIM.mjs.map → impl-dQg1-ZW6.mjs.map} +1 -1
  109. package/dist/{impl-DxAtF6i2.mjs → impl-qO0ED4q4.mjs} +2 -2
  110. package/dist/{impl-DxAtF6i2.mjs.map → impl-qO0ED4q4.mjs.map} +1 -1
  111. package/dist/{impl-CFuzHw_V.mjs → impl-qemxdloz.mjs} +2 -2
  112. package/dist/{impl-CFuzHw_V.mjs.map → impl-qemxdloz.mjs.map} +1 -1
  113. package/dist/{impl-CetnLzsu.mjs → impl-s0EM9fea.mjs} +2 -2
  114. package/dist/{impl-CetnLzsu.mjs.map → impl-s0EM9fea.mjs.map} +1 -1
  115. package/dist/{impl-tJanHDLi.mjs → impl-uxbaFgZT.mjs} +2 -2
  116. package/dist/{impl-tJanHDLi.mjs.map → impl-uxbaFgZT.mjs.map} +1 -1
  117. package/dist/impl-xtlx25UP.mjs.map +1 -1
  118. package/dist/index.d.mts +462 -15
  119. package/dist/index.d.mts.map +1 -1
  120. package/dist/index.mjs +1 -1
  121. package/dist/index.mjs.map +1 -1
  122. package/dist/{inquirer-BqZXFEt1.mjs → inquirer-B4iEodLy.mjs} +2 -2
  123. package/dist/{inquirer-BqZXFEt1.mjs.map → inquirer-B4iEodLy.mjs.map} +1 -1
  124. package/dist/{markRequestDataSiloIdsCompleted-hvdftA2o.mjs → markRequestDataSiloIdsCompleted-_VvJoVTL.mjs} +2 -2
  125. package/dist/{markRequestDataSiloIdsCompleted-hvdftA2o.mjs.map → markRequestDataSiloIdsCompleted-_VvJoVTL.mjs.map} +1 -1
  126. package/dist/{markSilentPrivacyRequests-DZKKnSo0.mjs → markSilentPrivacyRequests-KYqGzjta.mjs} +2 -2
  127. package/dist/{markSilentPrivacyRequests-DZKKnSo0.mjs.map → markSilentPrivacyRequests-KYqGzjta.mjs.map} +1 -1
  128. package/dist/{notifyPrivacyRequestsAdditionalTime-BG0X2G1i.mjs → notifyPrivacyRequestsAdditionalTime-CygA3uum.mjs} +2 -2
  129. package/dist/{notifyPrivacyRequestsAdditionalTime-BG0X2G1i.mjs.map → notifyPrivacyRequestsAdditionalTime-CygA3uum.mjs.map} +1 -1
  130. package/dist/parquetToCsvOneFile-B84XXInh.mjs.map +1 -1
  131. package/dist/{parseAttributesFromString-D1Yl0xwT.mjs → parseAttributesFromString-q4-59nEN.mjs} +2 -2
  132. package/dist/{parseAttributesFromString-D1Yl0xwT.mjs.map → parseAttributesFromString-q4-59nEN.mjs.map} +1 -1
  133. package/dist/parseVariablesFromString-BeKOGw5n.mjs.map +1 -1
  134. package/dist/pullAllDatapoints-Bbmky50p.mjs.map +1 -1
  135. package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-D2oMDSTM.mjs → pullChunkedCustomSiloOutstandingIdentifiers-Bz1EGQOW.mjs} +2 -2
  136. package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-D2oMDSTM.mjs.map → pullChunkedCustomSiloOutstandingIdentifiers-Bz1EGQOW.mjs.map} +1 -1
  137. package/dist/pullConsentManagerMetrics-zKgjc3Ap.mjs.map +1 -1
  138. package/dist/{pullManualEnrichmentIdentifiersToCsv-CuMrsy2E.mjs → pullManualEnrichmentIdentifiersToCsv-BWxxJ2Qi.mjs} +2 -2
  139. package/dist/{pullManualEnrichmentIdentifiersToCsv-CuMrsy2E.mjs.map → pullManualEnrichmentIdentifiersToCsv-BWxxJ2Qi.mjs.map} +1 -1
  140. package/dist/pullTranscendConfiguration-BHP6t_Nq.mjs +58 -0
  141. package/dist/pullTranscendConfiguration-BHP6t_Nq.mjs.map +1 -0
  142. package/dist/pullUnstructuredSubDataPointRecommendations-D0z-vPgq.mjs.map +1 -1
  143. package/dist/{pushCronIdentifiersFromCsv-Diqe_40J.mjs → pushCronIdentifiersFromCsv-DUZv9xss.mjs} +2 -2
  144. package/dist/{pushCronIdentifiersFromCsv-Diqe_40J.mjs.map → pushCronIdentifiersFromCsv-DUZv9xss.mjs.map} +1 -1
  145. package/dist/{pushManualEnrichmentIdentifiersFromCsv-DTc5tZta.mjs → pushManualEnrichmentIdentifiersFromCsv-QnSf70JE.mjs} +2 -2
  146. package/dist/{pushManualEnrichmentIdentifiersFromCsv-DTc5tZta.mjs.map → pushManualEnrichmentIdentifiersFromCsv-QnSf70JE.mjs.map} +1 -1
  147. package/dist/readCsv-C4TyEs-r.mjs.map +1 -1
  148. package/dist/{readTranscendYaml-BbnEGgVD.mjs → readTranscendYaml-CGb2UUyM.mjs} +2 -2
  149. package/dist/{readTranscendYaml-BbnEGgVD.mjs.map → readTranscendYaml-CGb2UUyM.mjs.map} +1 -1
  150. package/dist/{removeUnverifiedRequestIdentifiers-CjXqxX3q.mjs → removeUnverifiedRequestIdentifiers-Bh8EQEts.mjs} +2 -2
  151. package/dist/{removeUnverifiedRequestIdentifiers-CjXqxX3q.mjs.map → removeUnverifiedRequestIdentifiers-Bh8EQEts.mjs.map} +1 -1
  152. package/dist/{retryRequestDataSilos-B-dCsMNC.mjs → retryRequestDataSilos-BPORd8Q4.mjs} +2 -2
  153. package/dist/{retryRequestDataSilos-B-dCsMNC.mjs.map → retryRequestDataSilos-BPORd8Q4.mjs.map} +1 -1
  154. package/dist/{skipPreflightJobs-CoTI1wuB.mjs → skipPreflightJobs-DFDwnE32.mjs} +2 -2
  155. package/dist/{skipPreflightJobs-CoTI1wuB.mjs.map → skipPreflightJobs-DFDwnE32.mjs.map} +1 -1
  156. package/dist/{skipRequestDataSilos-CbdhNiBV.mjs → skipRequestDataSilos-DQkZn9Wx.mjs} +2 -2
  157. package/dist/{skipRequestDataSilos-CbdhNiBV.mjs.map → skipRequestDataSilos-DQkZn9Wx.mjs.map} +1 -1
  158. package/dist/{streamPrivacyRequestsToCsv-B6-4KjP_.mjs → streamPrivacyRequestsToCsv-B0GqwHNz.mjs} +2 -2
  159. package/dist/{streamPrivacyRequestsToCsv-B6-4KjP_.mjs.map → streamPrivacyRequestsToCsv-B0GqwHNz.mjs.map} +1 -1
  160. package/dist/syncCodePackages-CAk_Hjyl.mjs.map +1 -1
  161. package/dist/{updateConsentManagerVersionToLatest-Bo0g8BLm.mjs → updateConsentManagerVersionToLatest-D3ms_fBZ.mjs} +2 -2
  162. package/dist/{updateConsentManagerVersionToLatest-Bo0g8BLm.mjs.map → updateConsentManagerVersionToLatest-D3ms_fBZ.mjs.map} +1 -1
  163. package/dist/{uploadConsents-GNPBOA3B.mjs → uploadConsents-DA8DR8pb.mjs} +2 -2
  164. package/dist/{uploadConsents-GNPBOA3B.mjs.map → uploadConsents-DA8DR8pb.mjs.map} +1 -1
  165. package/dist/{uploadCookiesFromCsv-C5n0dIZs.mjs → uploadCookiesFromCsv-dHTagDcv.mjs} +2 -2
  166. package/dist/{uploadCookiesFromCsv-C5n0dIZs.mjs.map → uploadCookiesFromCsv-dHTagDcv.mjs.map} +1 -1
  167. package/dist/{uploadDataFlowsFromCsv-Dnh7n6R0.mjs → uploadDataFlowsFromCsv-Db7cxXcH.mjs} +2 -2
  168. package/dist/{uploadDataFlowsFromCsv-Dnh7n6R0.mjs.map → uploadDataFlowsFromCsv-Db7cxXcH.mjs.map} +1 -1
  169. package/dist/uploadPrivacyRequestsFromCsv-Cs9e4fgB.mjs +2 -0
  170. package/dist/{uploadPrivacyRequestsFromCsv-7KNlE6Et.mjs.map → uploadPrivacyRequestsFromCsv-Cs9e4fgB.mjs.map} +1 -1
  171. package/dist/{validateTranscendAuth-BHw0WQu1.mjs → validateTranscendAuth-DJ8qHb9B.mjs} +2 -2
  172. package/dist/{validateTranscendAuth-BHw0WQu1.mjs.map → validateTranscendAuth-DJ8qHb9B.mjs.map} +1 -1
  173. package/dist/writeCsv-C4pjXGsD.mjs.map +1 -1
  174. package/package.json +9 -9
  175. package/dist/app-CGrl8jGp.mjs +0 -131
  176. package/dist/codecs-B2mV72Wn.mjs +0 -2
  177. package/dist/codecs-B2mV72Wn.mjs.map +0 -1
  178. package/dist/constants-BOycJ_AQ.mjs +0 -2
  179. package/dist/constants-ClkQQhJs.mjs +0 -2
  180. package/dist/impl-BjIylEKQ.mjs +0 -4
  181. package/dist/pullTranscendConfiguration-CofsMdIn.mjs +0 -58
  182. package/dist/pullTranscendConfiguration-CofsMdIn.mjs.map +0 -1
  183. package/dist/uploadPrivacyRequestsFromCsv-7KNlE6Et.mjs +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"impl-BjIylEKQ.mjs","names":[],"sources":["../src/lib/oneTrust/helpers/oneTrustAssessmentToJson.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentToDisk.ts","../src/lib/oneTrust/endpoints/getListOfOneTrustAssessments.ts","../src/lib/oneTrust/endpoints/getOneTrustAssessment.ts","../src/lib/oneTrust/endpoints/getOneTrustRisk.ts","../src/lib/oneTrust/endpoints/getOneTrustUser.ts","../src/lib/oneTrust/helpers/enrichOneTrustAssessment.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentToTranscend.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentsFromOneTrust.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentsFromFile.ts","../src/lib/oneTrust/createOneTrustGotInstance.ts","../src/commands/migration/sync-ot/impl.ts"],"sourcesContent":["import { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\n\n/**\n * Converts the assessment into a json entry.\n *\n * @param param - information about the assessment and amount of entries\n * @returns a stringified json entry ready to be appended to a file\n */\nexport const oneTrustAssessmentToJson = ({\n assessment,\n index,\n total,\n wrap = true,\n}: {\n /** The assessment to convert */\n assessment: OneTrustEnrichedAssessment;\n /** The position of the assessment in the final Json object */\n index: number;\n /** The total amount of the assessments in the final Json object */\n total?: number;\n /** Whether to wrap every entry in brackets */\n wrap?: boolean;\n}): string => {\n let jsonEntry = '';\n // start with an opening bracket\n if (index === 0 || wrap) {\n jsonEntry = '[\\n';\n }\n\n const stringifiedAssessment = JSON.stringify(assessment);\n\n // Add comma for all items except the last one\n const comma = total && index < total - 1 && !wrap ? ',' : '';\n\n // write to file\n jsonEntry = `${jsonEntry + stringifiedAssessment + comma}\\n`;\n\n // end with closing bracket\n if ((total && index === total - 1) || wrap) {\n jsonEntry += '\\n]';\n }\n\n return jsonEntry;\n};\n","import fs from 'node:fs';\n\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport colors from 'colors';\n\nimport { logger } from '../../../logger.js';\nimport { oneTrustAssessmentToJson } from './oneTrustAssessmentToJson.js';\n\n/**\n * Write the assessment to disk at the specified file path.\n *\n *\n * @param param - information about the assessment to write\n */\nexport const syncOneTrustAssessmentToDisk = ({\n file,\n assessment,\n index,\n total,\n}: {\n /** The file path to write the assessment to */\n file: string;\n /** The basic assessment */\n assessment: OneTrustEnrichedAssessment;\n /** The index of the assessment being written to the file */\n index: number;\n /** The total amount of assessments that we will write */\n total: number;\n}): void => {\n logger.info(\n colors.magenta(`Writing enriched assessment ${index + 1} of ${total} to file \"${file}\"...`),\n );\n\n if (index === 0) {\n fs.writeFileSync(\n file,\n oneTrustAssessmentToJson({\n assessment,\n index,\n total,\n wrap: false,\n }),\n );\n } else {\n fs.appendFileSync(\n file,\n oneTrustAssessmentToJson({\n assessment,\n index,\n total,\n wrap: false,\n }),\n );\n }\n};\n","import {\n OneTrustAssessment,\n OneTrustGetListOfAssessmentsResponse,\n} from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\nimport { logger } from '../../../logger.js';\n\n/**\n * Fetch a list of all assessments from the OneTrust client.\n * ref: https://developer.onetrust.com/onetrust/reference/getallassessmentbasicdetailsusingget\n *\n * @param param - the information about the OneTrust client\n * @returns a list of OneTrustAssessment\n */\nexport const getListOfOneTrustAssessments = async ({\n oneTrust,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n}): Promise<OneTrustAssessment[]> => {\n let currentPage = 0;\n let totalPages = 1;\n let totalElements = 0;\n\n const allAssessments: OneTrustAssessment[] = [];\n\n while (currentPage < totalPages) {\n const { body } = await oneTrust.get(\n `api/assessment/v2/assessments?page=${currentPage}&size=2000`,\n );\n\n const { page, content } = decodeCodec(OneTrustGetListOfAssessmentsResponse, body);\n allAssessments.push(...(content ?? []));\n if (currentPage === 0) {\n totalPages = page?.totalPages ?? 0;\n totalElements = page?.totalElements ?? 0;\n }\n currentPage += 1;\n\n // log progress\n logger.info(`Fetched ${allAssessments.length} of ${totalElements} assessments.`);\n }\n\n return allAssessments;\n};\n","import { OneTrustGetAssessmentResponse } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\n/**\n * Retrieve details about a particular assessment.\n * ref: https://developer.onetrust.com/onetrust/reference/exportassessmentusingget\n *\n * @param param - the information about the OneTrust client and assessment to retrieve\n * @returns details about the assessment\n */\nexport const getOneTrustAssessment = async ({\n oneTrust,\n assessmentId,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n /** The ID of the assessment to retrieve */\n assessmentId: string;\n}): Promise<OneTrustGetAssessmentResponse> => {\n const { body } = await oneTrust.get(\n `api/assessment/v2/assessments/${assessmentId}/export?ExcludeSkippedQuestions=false`,\n );\n\n return decodeCodec(OneTrustGetAssessmentResponse, body);\n};\n","import { OneTrustGetRiskResponse } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\n/**\n * Retrieve details about a particular risk.\n * ref: https://developer.onetrust.com/onetrust/reference/getriskusingget\n *\n * @param param - the information about the OneTrust client and risk to retrieve\n * @returns the OneTrust risk\n */\nexport const getOneTrustRisk = async ({\n oneTrust,\n riskId,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n /** The ID of the OneTrust risk to retrieve */\n riskId: string;\n}): Promise<OneTrustGetRiskResponse> => {\n const { body } = await oneTrust.get(`api/risk/v2/risks/${riskId}`);\n\n return decodeCodec(OneTrustGetRiskResponse, body);\n};\n","import { OneTrustGetUserResponse } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\n/**\n * Retrieve details about a particular user.\n * ref: https://developer.onetrust.com/onetrust/reference/getriskusingget\n *\n * @param param - the information about the OneTrust client and risk to retrieve\n * @returns the OneTrust risk\n */\nexport const getOneTrustUser = async ({\n oneTrust,\n userId,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n /** The ID of the OneTrust user to retrieve */\n userId: string;\n}): Promise<OneTrustGetUserResponse> => {\n const { body } = await oneTrust.get(`api/scim/v2/Users/${userId}`);\n\n return decodeCodec(OneTrustGetUserResponse, body);\n};\n","import {\n OneTrustAssessment,\n OneTrustEnrichedAssessment,\n OneTrustGetAssessmentResponse,\n OneTrustGetRiskResponse,\n OneTrustGetUserResponse,\n} from '@transcend-io/privacy-types';\nimport { keyBy } from 'lodash-es';\n\n/**\n * Merge the assessment, assessmentDetails, and riskDetails into one object.\n *\n * @param param - the assessment and risk information\n * @returns the assessment enriched with details and risk information\n */\nexport const enrichOneTrustAssessment = ({\n assessment,\n assessmentDetails,\n riskDetails,\n creatorDetails,\n approversDetails,\n respondentsDetails,\n}: {\n /** The OneTrust risk details */\n riskDetails: OneTrustGetRiskResponse[];\n /** The OneTrust assessment as returned from Get List of Assessments endpoint */\n assessment: OneTrustAssessment;\n /** The OneTrust assessment details */\n assessmentDetails: OneTrustGetAssessmentResponse;\n /** The OneTrust assessment creator details */\n creatorDetails: OneTrustGetUserResponse;\n /** The OneTrust assessment approvers details */\n approversDetails: OneTrustGetUserResponse[];\n /** The OneTrust assessment internal respondents details */\n respondentsDetails: OneTrustGetUserResponse[];\n}): OneTrustEnrichedAssessment => {\n const riskDetailsById = keyBy(riskDetails, 'id');\n const { sections, createdBy, ...restAssessmentDetails } = assessmentDetails;\n const sectionsWithEnrichedRisk = sections.map((section) => {\n const { questions, ...restSection } = section;\n const enrichedQuestions = questions.map((question) => {\n const { risks, ...restQuestion } = question;\n const enrichedRisks = (risks ?? []).map((risk) => {\n const details = riskDetailsById[risk.riskId];\n return {\n ...risk,\n ...details,\n level: risk.level,\n impactLevel: risk.impactLevel ?? 0,\n };\n });\n return {\n ...restQuestion,\n risks: enrichedRisks,\n };\n });\n return {\n ...restSection,\n questions: enrichedQuestions,\n };\n });\n\n // grab creator details\n const enrichedCreatedBy = {\n ...createdBy,\n active: creatorDetails?.active ?? false,\n userType: creatorDetails?.userType ?? 'Internal',\n emails: creatorDetails?.emails ?? [],\n title: creatorDetails?.title ?? null,\n givenName: creatorDetails?.name.givenName ?? null,\n familyName: creatorDetails?.name.familyName ?? null,\n };\n\n // grab approvers details\n const approverDetailsById = keyBy(approversDetails, 'id');\n const enrichedApprovers = assessmentDetails.approvers.flatMap((originalApprover) =>\n approverDetailsById[originalApprover.id]\n ? [\n {\n ...originalApprover,\n approver: {\n ...originalApprover.approver,\n active: approverDetailsById[originalApprover.id].active,\n userType: approverDetailsById[originalApprover.id].userType,\n emails: approverDetailsById[originalApprover.id].emails,\n title: approverDetailsById[originalApprover.id].title,\n givenName: approverDetailsById[originalApprover.id].name.givenName ?? null,\n familyName: approverDetailsById[originalApprover.id].name.familyName ?? null,\n },\n },\n ]\n : [],\n );\n\n // grab respondents details\n const respondentsDetailsById = keyBy(respondentsDetails, 'id');\n const enrichedRespondents = assessmentDetails.respondents\n .filter((r) => !r.name.includes('@')) // search only internal respondents\n .flatMap((respondent) =>\n respondentsDetailsById[respondent.id]\n ? [\n {\n ...respondent,\n active: respondentsDetailsById[respondent.id].active,\n userType: respondentsDetailsById[respondent.id].userType,\n emails: respondentsDetailsById[respondent.id].emails,\n title: respondentsDetailsById[respondent.id].title,\n givenName: respondentsDetailsById[respondent.id].name.givenName ?? null,\n familyName: respondentsDetailsById[respondent.id].name.familyName ?? null,\n },\n ]\n : [],\n );\n\n // combine everything into a single enriched assessment\n return {\n ...assessment,\n ...restAssessmentDetails,\n approvers: enrichedApprovers,\n respondents: enrichedRespondents,\n createdBy: enrichedCreatedBy,\n sections: sectionsWithEnrichedRisk,\n };\n};\n","import { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport { makeGraphQLRequest, IMPORT_ONE_TRUST_ASSESSMENT_FORMS } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport { GraphQLClient } from 'graphql-request';\n\nimport { ImportOnetrustAssessmentsInput } from '../../../codecs.js';\nimport { logger } from '../../../logger.js';\nimport { oneTrustAssessmentToJson } from './oneTrustAssessmentToJson.js';\n\nexport interface AssessmentForm {\n /** ID of Assessment Form */\n id: string;\n /** Title of Assessment Form */\n name: string;\n}\n\n/**\n * Write the assessment to a Transcend instance.\n *\n *\n * @param param - information about the assessment and Transcend instance to write to\n */\nexport const syncOneTrustAssessmentToTranscend = async ({\n transcend,\n assessment,\n total,\n index,\n}: {\n /** the Transcend client instance */\n transcend: GraphQLClient;\n /** the assessment to sync to Transcend */\n assessment: OneTrustEnrichedAssessment;\n /** The index of the assessment being written to the file */\n index: number;\n /** The total amount of assessments that we will write */\n total?: number;\n}): Promise<void> => {\n logger.info(\n colors.magenta(\n `Writing enriched assessment ${index + 1} ${total ? `of ${total} ` : ' '}to Transcend...`,\n ),\n );\n\n // convert the OneTrust assessment object into a json record\n const json = oneTrustAssessmentToJson({\n assessment,\n index,\n total,\n });\n\n // transform the json record into a valid input to the mutation\n const input: ImportOnetrustAssessmentsInput = {\n json,\n };\n\n try {\n await makeGraphQLRequest<{\n /** the importOneTrustAssessmentForms mutation */\n importOneTrustAssessmentForms: {\n /** Created Assessment Forms */\n assessmentForms: AssessmentForm[];\n };\n }>(transcend, IMPORT_ONE_TRUST_ASSESSMENT_FORMS, {\n variables: { input },\n logger,\n });\n } catch (error) {\n logger.error(\n colors.red(\n `Failed to sync assessment ${index + 1} ${total ? `of ${total} ` : ' '}to Transcend.\\n` +\n `\\tAssessment Title: ${assessment.name}. Template Title: ${assessment.template.name}\\n`,\n ),\n error,\n );\n }\n};\n","import {\n OneTrustAssessmentQuestion,\n OneTrustAssessmentSection,\n OneTrustEnrichedAssessment,\n OneTrustGetRiskResponse,\n OneTrustGetUserResponse,\n} from '@transcend-io/privacy-types';\nimport { mapSeries, map } from '@transcend-io/utils';\nimport colors from 'colors';\nimport type { Got } from 'got';\nimport { GraphQLClient } from 'graphql-request';\nimport { uniq } from 'lodash-es';\n\nimport { logger } from '../../../logger.js';\nimport {\n getListOfOneTrustAssessments,\n getOneTrustAssessment,\n getOneTrustRisk,\n getOneTrustUser,\n} from '../endpoints/index.js';\nimport { enrichOneTrustAssessment } from './enrichOneTrustAssessment.js';\nimport { syncOneTrustAssessmentToDisk } from './syncOneTrustAssessmentToDisk.js';\nimport { syncOneTrustAssessmentToTranscend } from './syncOneTrustAssessmentToTranscend.js';\n\nexport interface AssessmentForm {\n /** ID of Assessment Form */\n id: string;\n /** Title of Assessment Form */\n name: string;\n}\n\n/**\n * Reads all the assessments from a OneTrust instance and syncs them to Transcend or to Disk.\n *\n * @param param - the information about the assessment, its OneTrust source, and destination (disk or Transcend)\n */\nexport const syncOneTrustAssessmentsFromOneTrust = async ({\n oneTrust,\n file,\n dryRun,\n transcend,\n}: {\n /** the OneTrust client instance */\n oneTrust: Got;\n /** the Transcend client instance */\n transcend?: GraphQLClient;\n /** Whether to write to file instead of syncing to Transcend */\n dryRun: boolean;\n /** the path to the file in case dryRun is true */\n file?: string;\n}): Promise<void> => {\n // fetch the list of all assessments in the OneTrust organization\n logger.info('Getting list of all assessments from OneTrust...');\n const assessments = await getListOfOneTrustAssessments({ oneTrust });\n\n // a cache of OneTrust users so we avoid requesting already fetched users\n const oneTrustCachedUsers: Record<string, OneTrustGetUserResponse> = {};\n\n // split all assessments in batches, so we can process some of steps in parallel\n const BATCH_SIZE = 5;\n const assessmentBatches = Array.from(\n {\n length: Math.ceil(assessments.length / BATCH_SIZE),\n },\n (_, i) => assessments.slice(i * BATCH_SIZE, (i + 1) * BATCH_SIZE),\n );\n\n // process each batch and sync the batch right away so it's garbage collected and we don't run out of memory\n await mapSeries(assessmentBatches, async (assessmentBatch, batch) => {\n const batchEnrichedAssessments: OneTrustEnrichedAssessment[] = [];\n\n // fetch assessment details from OneTrust in parallel\n await map(\n assessmentBatch,\n async (assessment, index) => {\n const assessmentNumber = BATCH_SIZE * batch + index + 1;\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching details...`,\n );\n const { templateName, assessmentId } = assessment;\n const assessmentDetails = await getOneTrustAssessment({\n oneTrust,\n assessmentId,\n });\n // fetch assessment's creator information\n const creatorId = assessmentDetails.createdBy.id;\n let creator = oneTrustCachedUsers[creatorId];\n if (!creator) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching creator...`,\n );\n try {\n creator = await getOneTrustUser({\n oneTrust,\n userId: creatorId,\n });\n oneTrustCachedUsers[creatorId] = creator;\n } catch (error) {\n logger.warn(\n colors.yellow(\n `[assessment ${assessmentNumber} of ${assessments.length}]: failed to fetch form creator.` +\n `\\tcreatorId: ${creatorId}. Assessment Title: ${assessment.name}. Template Title: ${templateName}`,\n ),\n error,\n );\n }\n }\n\n // fetch assessment approvers information\n const { approvers } = assessmentDetails;\n let approversDetails: OneTrustGetUserResponse[][] = [];\n if (approvers.length > 0) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching approvers...`,\n );\n approversDetails = await map(\n approvers.map(({ id }) => id),\n async (userId) => {\n try {\n let approver = oneTrustCachedUsers[userId];\n if (!approver) {\n approver = await getOneTrustUser({ oneTrust, userId });\n oneTrustCachedUsers[userId] = approver;\n }\n return [approver];\n } catch (error) {\n logger.warn(\n colors.yellow(\n `[assessment ${assessmentNumber} of ${assessments.length}]: failed to fetch a form approver.` +\n `\\tapproverId: ${userId}. Assessment Title: ${assessment.name}. Template Title: ${templateName}`,\n ),\n error,\n );\n return [];\n }\n },\n { concurrency: 5 },\n );\n }\n\n // fetch assessment internal respondents information\n const { respondents } = assessmentDetails;\n // if a user is an internal respondents, their 'name' field can't be an email.\n const internalRespondents = respondents.filter((r) => !r.name.includes('@'));\n let respondentsDetails: OneTrustGetUserResponse[][] = [];\n if (internalRespondents.length > 0) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching respondents...`,\n );\n respondentsDetails = await map(\n internalRespondents.map(({ id }) => id),\n async (userId) => {\n try {\n let respondent = oneTrustCachedUsers[userId];\n if (!respondent) {\n respondent = await getOneTrustUser({ oneTrust, userId });\n oneTrustCachedUsers[userId] = respondent;\n }\n return [respondent];\n } catch (error) {\n logger.warn(\n colors.yellow(\n `[assessment ${assessmentNumber} of ${assessments.length}]: failed to fetch a respondent.` +\n `\\trespondentId: ${userId}. Assessment Title: ${assessment.name}. Template Title: ${templateName}`,\n ),\n error,\n );\n return [];\n }\n },\n { concurrency: 5 },\n );\n }\n\n // fetch assessment risk information\n let riskDetails: OneTrustGetRiskResponse[] = [];\n const riskIds = uniq(\n assessmentDetails.sections.flatMap((s: OneTrustAssessmentSection) =>\n s.questions.flatMap((q: OneTrustAssessmentQuestion) =>\n (q.risks ?? []).flatMap((r) => r.riskId),\n ),\n ),\n );\n if (riskIds.length > 0) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching risks...`,\n );\n riskDetails = await map(\n riskIds,\n (riskId) => getOneTrustRisk({ oneTrust, riskId: riskId as string }),\n {\n concurrency: 5,\n },\n );\n }\n\n // enrich the assessments with user and risk details\n const enrichedAssessment = enrichOneTrustAssessment({\n assessment,\n assessmentDetails,\n riskDetails,\n creatorDetails: creator,\n approversDetails: approversDetails.flat(),\n respondentsDetails: respondentsDetails.flat(),\n });\n\n batchEnrichedAssessments.push(enrichedAssessment);\n },\n { concurrency: BATCH_SIZE },\n );\n\n // sync assessments in series to avoid concurrency bugs\n await mapSeries(batchEnrichedAssessments, async (enrichedAssessment, index) => {\n // the assessment's global index takes its batch into consideration\n const globalIndex = batch * BATCH_SIZE + index;\n\n if (dryRun && file) {\n // sync to file\n syncOneTrustAssessmentToDisk({\n assessment: enrichedAssessment,\n index: globalIndex,\n total: assessments.length,\n file,\n });\n } else if (transcend) {\n // sync to transcend\n await syncOneTrustAssessmentToTranscend({\n assessment: enrichedAssessment,\n transcend,\n total: assessments.length,\n index: globalIndex,\n });\n }\n });\n });\n};\n","import { createReadStream } from 'node:fs';\n\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport colors from 'colors';\nimport { GraphQLClient } from 'graphql-request';\nimport JSONStream from 'JSONStream';\n\nimport { logger } from '../../../logger.js';\nimport { syncOneTrustAssessmentToTranscend } from './syncOneTrustAssessmentToTranscend.js';\n\n/**\n * Reads assessments from a file and syncs them to Transcend.\n *\n * @param param - the information about the source file and Transcend instance to write them to.\n */\nexport const syncOneTrustAssessmentsFromFile = ({\n transcend,\n file,\n}: {\n /** the Transcend client instance */\n transcend: GraphQLClient;\n /** The name of the file from which to read the OneTrust assessments */\n file: string;\n}): Promise<void> => {\n logger.info(`Getting list of all assessments from file ${file}...`);\n\n return new Promise((resolve, reject) => {\n // Create a readable stream from the file\n const fileStream = createReadStream(file, {\n encoding: 'utf-8',\n highWaterMark: 64 * 1024, // 64KB chunks\n });\n\n // Create a JSONStream parser to parse the array of OneTrust assessments from the file\n const parser = JSONStream.parse('*'); // '*' matches each element in the root array\n\n let index = 0;\n\n // Pipe the file stream into the JSON parser\n fileStream.pipe(parser);\n\n // Handle each parsed assessment object\n parser.on('data', async (assessment) => {\n try {\n // Pause the stream while processing to avoid overwhelming memory\n parser.pause();\n\n // Decode and validate the assessment\n const parsedAssessment = decodeCodec(OneTrustEnrichedAssessment, assessment);\n\n // Sync the assessment to transcend\n await syncOneTrustAssessmentToTranscend({\n assessment: parsedAssessment,\n transcend,\n index,\n });\n\n index += 1;\n\n // Resume the stream after processing\n parser.resume();\n } catch (e) {\n // if failed to parse a line, report error and continue\n logger.error(\n colors.red(`Failed to parse the assessment ${index} from file '${file}': ${e.message}.`),\n );\n }\n });\n\n // Handle completion\n parser.on('end', () => {\n logger.info(`Finished processing ${index} assessments from file ${file}`);\n resolve();\n });\n\n // Handle stream or parsing errors\n parser.on('error', (error) => {\n logger.error(colors.red(`Error parsing file '${file}': ${error.message}`));\n reject(error);\n });\n\n fileStream.on('error', (error) => {\n logger.error(colors.red(`Error reading file '${file}': ${error.message}`));\n reject(error);\n });\n });\n};\n","import got, { Got } from 'got';\n\n/**\n * Instantiate an instance of got that is capable of making requests to OneTrust\n *\n * @param param - information about the OneTrust URL\n * @returns The instance of got that is capable of making requests to the customer ingress\n */\nexport const createOneTrustGotInstance = ({\n hostname,\n auth,\n}: {\n /** Hostname of the OneTrust API */\n hostname: string;\n /** The OAuth access token */\n auth: string;\n}): Got =>\n got.extend({\n prefixUrl: `https://${hostname}`,\n headers: {\n accept: 'application/json',\n 'content-type': 'application/json',\n authorization: `Bearer ${auth}`,\n },\n });\n","import { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { OneTrustFileFormat, OneTrustPullResource, OneTrustPullSource } from '../../../enums.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport {\n syncOneTrustAssessmentsFromFile,\n syncOneTrustAssessmentsFromOneTrust,\n} from '../../../lib/oneTrust/helpers/index.js';\nimport { createOneTrustGotInstance } from '../../../lib/oneTrust/index.js';\nimport { logger } from '../../../logger.js';\n\n// Command flag interface\nexport interface SyncOtCommandFlags {\n hostname?: string;\n oneTrustAuth?: string;\n source: OneTrustPullSource;\n transcendAuth?: string;\n transcendUrl: string;\n file?: string;\n resource: OneTrustPullResource;\n dryRun: boolean;\n debug: boolean;\n}\n\n// Command implementation\nexport async function syncOt(\n this: LocalContext,\n {\n hostname,\n oneTrustAuth,\n source,\n transcendAuth,\n transcendUrl,\n resource,\n file,\n dryRun,\n debug,\n }: SyncOtCommandFlags,\n): Promise<void> {\n // Must be able to authenticate to transcend to sync resources to it\n if (!dryRun && !transcendAuth) {\n throw new Error(\n // eslint-disable-next-line no-template-curly-in-string\n 'Must specify a \"transcendAuth\" parameter to sync resources to Transcend. e.g. --transcendAuth=${TRANSCEND_API_KEY}',\n );\n }\n\n // If trying to sync to disk, must specify a file path\n if (dryRun && !file) {\n throw new Error(\n 'Must set a \"file\" parameter when \"dryRun\" is \"true\". e.g. --file=./oneTrustAssessments.json',\n );\n }\n\n if (file) {\n const splitFile = file.split('.');\n if (splitFile.length < 2) {\n throw new Error(\n 'The \"file\" parameter has an invalid format. Expected a path with extensions. e.g. --file=./pathToFile.json.',\n );\n }\n if (splitFile.at(-1) !== OneTrustFileFormat.Json) {\n throw new Error(\n `Expected the format of the \"file\" parameters '${file}' to be '${\n OneTrustFileFormat.Json\n }', but got '${splitFile.at(-1)}'.`,\n );\n }\n }\n\n // if reading assessments from a OneTrust\n if (source === OneTrustPullSource.OneTrust) {\n // must specify the OneTrust hostname\n if (!hostname) {\n throw new Error(\n 'Missing required parameter \"hostname\". e.g. --hostname=customer.my.onetrust.com',\n );\n }\n // must specify the OneTrust auth\n if (!oneTrustAuth) {\n throw new Error(\n 'Missing required parameter \"oneTrustAuth\". e.g. --oneTrustAuth=$ONE_TRUST_AUTH_TOKEN',\n );\n }\n } else {\n // if reading the assessments from a file, must specify a file to read from\n if (!file) {\n throw new Error(\n 'Must specify a \"file\" parameter to read the OneTrust assessments from. e.g. --source=./oneTrustAssessments.json',\n );\n }\n\n // Cannot try reading from file and save assessments to a file simultaneously\n if (dryRun) {\n throw new Error(\n 'Cannot read and write to a file simultaneously.' +\n ` Emit the \"source\" parameter or set it to ${OneTrustPullSource.OneTrust} if \"dryRun\" is enabled.`,\n );\n }\n }\n\n doneInputValidation(this.process.exit);\n\n // instantiate a client to talk to OneTrust\n const oneTrust =\n hostname && oneTrustAuth\n ? createOneTrustGotInstance({\n hostname,\n auth: oneTrustAuth,\n })\n : undefined;\n\n // instantiate a client to talk to Transcend\n const transcend =\n transcendUrl && transcendAuth\n ? buildTranscendGraphQLClient(transcendUrl, transcendAuth)\n : undefined;\n\n try {\n if (resource === OneTrustPullResource.Assessments) {\n if (source === OneTrustPullSource.OneTrust && oneTrust) {\n await syncOneTrustAssessmentsFromOneTrust({\n oneTrust,\n file,\n dryRun,\n ...(transcend && { transcend }),\n });\n } else if (source === OneTrustPullSource.File && file && transcend) {\n await syncOneTrustAssessmentsFromFile({ file, transcend });\n }\n }\n } catch (err) {\n throw new Error(\n `An error occurred syncing the resource ${resource} from OneTrust: ${\n debug ? err.stack : err.message\n }`,\n );\n }\n\n // Indicate success\n logger.info(\n colors.green(\n `Successfully synced OneTrust ${resource} to ${dryRun ? `disk at \"${file}\"` : 'Transcend'}!`,\n ),\n );\n}\n"],"mappings":"svBAQA,MAAa,GAA4B,CACvC,aACA,QACA,QACA,OAAO,MAUK,CACZ,IAAI,EAAY,IAEZ,IAAU,GAAK,KACjB,EAAY;GAGd,IAAM,EAAwB,KAAK,UAAU,EAAW,CAGlD,EAAQ,GAAS,EAAQ,EAAQ,GAAK,CAAC,EAAO,IAAM,GAU1D,MAPA,GAAY,GAAG,EAAY,EAAwB,EAAM,KAGpD,GAAS,IAAU,EAAQ,GAAM,KACpC,GAAa;IAGR,GC5BI,GAAgC,CAC3C,OACA,aACA,QACA,WAUU,CACV,EAAO,KACL,EAAO,QAAQ,+BAA+B,EAAQ,EAAE,MAAM,EAAM,YAAY,EAAK,MAAM,CAC5F,CAEG,IAAU,EACZ,EAAG,cACD,EACA,EAAyB,CACvB,aACA,QACA,QACA,KAAM,GACP,CAAC,CACH,CAED,EAAG,eACD,EACA,EAAyB,CACvB,aACA,QACA,QACA,KAAM,GACP,CAAC,CACH,ECpCQ,EAA+B,MAAO,CACjD,cAImC,CACnC,IAAI,EAAc,EACd,EAAa,EACb,EAAgB,EAEd,EAAuC,EAAE,CAE/C,KAAO,EAAc,GAAY,CAC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IAAW,EAAmB,MAAQ,GAAQ,GACvD,MAAM,EAAgC,CAAE,OAAM,YAAW,CAAC,QAGvD,EAAK,CACZ,MAAU,MACR,0CAA0C,EAAS,kBACjD,EAAQ,EAAI,MAAQ,EAAI,UAE3B,CAIH,EAAO,KACL,EAAO,MACL,gCAAgC,EAAS,MAAM,EAAS,YAAY,EAAK,GAAK,YAAY,GAC3F,CACF"}
1
+ {"version":3,"file":"impl-DKIBerx4.mjs","names":[],"sources":["../src/lib/oneTrust/helpers/oneTrustAssessmentToJson.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentToDisk.ts","../src/lib/oneTrust/endpoints/getListOfOneTrustAssessments.ts","../src/lib/oneTrust/endpoints/getOneTrustAssessment.ts","../src/lib/oneTrust/endpoints/getOneTrustRisk.ts","../src/lib/oneTrust/endpoints/getOneTrustUser.ts","../src/lib/oneTrust/helpers/enrichOneTrustAssessment.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentToTranscend.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentsFromOneTrust.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentsFromFile.ts","../src/lib/oneTrust/createOneTrustGotInstance.ts","../src/commands/migration/sync-ot/impl.ts"],"sourcesContent":["import { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\n\n/**\n * Converts the assessment into a json entry.\n *\n * @param param - information about the assessment and amount of entries\n * @returns a stringified json entry ready to be appended to a file\n */\nexport const oneTrustAssessmentToJson = ({\n assessment,\n index,\n total,\n wrap = true,\n}: {\n /** The assessment to convert */\n assessment: OneTrustEnrichedAssessment;\n /** The position of the assessment in the final Json object */\n index: number;\n /** The total amount of the assessments in the final Json object */\n total?: number;\n /** Whether to wrap every entry in brackets */\n wrap?: boolean;\n}): string => {\n let jsonEntry = '';\n // start with an opening bracket\n if (index === 0 || wrap) {\n jsonEntry = '[\\n';\n }\n\n const stringifiedAssessment = JSON.stringify(assessment);\n\n // Add comma for all items except the last one\n const comma = total && index < total - 1 && !wrap ? ',' : '';\n\n // write to file\n jsonEntry = `${jsonEntry + stringifiedAssessment + comma}\\n`;\n\n // end with closing bracket\n if ((total && index === total - 1) || wrap) {\n jsonEntry += '\\n]';\n }\n\n return jsonEntry;\n};\n","import fs from 'node:fs';\n\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport colors from 'colors';\n\nimport { logger } from '../../../logger.js';\nimport { oneTrustAssessmentToJson } from './oneTrustAssessmentToJson.js';\n\n/**\n * Write the assessment to disk at the specified file path.\n *\n *\n * @param param - information about the assessment to write\n */\nexport const syncOneTrustAssessmentToDisk = ({\n file,\n assessment,\n index,\n total,\n}: {\n /** The file path to write the assessment to */\n file: string;\n /** The basic assessment */\n assessment: OneTrustEnrichedAssessment;\n /** The index of the assessment being written to the file */\n index: number;\n /** The total amount of assessments that we will write */\n total: number;\n}): void => {\n logger.info(\n colors.magenta(`Writing enriched assessment ${index + 1} of ${total} to file \"${file}\"...`),\n );\n\n if (index === 0) {\n fs.writeFileSync(\n file,\n oneTrustAssessmentToJson({\n assessment,\n index,\n total,\n wrap: false,\n }),\n );\n } else {\n fs.appendFileSync(\n file,\n oneTrustAssessmentToJson({\n assessment,\n index,\n total,\n wrap: false,\n }),\n );\n }\n};\n","import {\n OneTrustAssessment,\n OneTrustGetListOfAssessmentsResponse,\n} from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\nimport { logger } from '../../../logger.js';\n\n/**\n * Fetch a list of all assessments from the OneTrust client.\n * ref: https://developer.onetrust.com/onetrust/reference/getallassessmentbasicdetailsusingget\n *\n * @param param - the information about the OneTrust client\n * @returns a list of OneTrustAssessment\n */\nexport const getListOfOneTrustAssessments = async ({\n oneTrust,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n}): Promise<OneTrustAssessment[]> => {\n let currentPage = 0;\n let totalPages = 1;\n let totalElements = 0;\n\n const allAssessments: OneTrustAssessment[] = [];\n\n while (currentPage < totalPages) {\n const { body } = await oneTrust.get(\n `api/assessment/v2/assessments?page=${currentPage}&size=2000`,\n );\n\n const { page, content } = decodeCodec(OneTrustGetListOfAssessmentsResponse, body);\n allAssessments.push(...(content ?? []));\n if (currentPage === 0) {\n totalPages = page?.totalPages ?? 0;\n totalElements = page?.totalElements ?? 0;\n }\n currentPage += 1;\n\n // log progress\n logger.info(`Fetched ${allAssessments.length} of ${totalElements} assessments.`);\n }\n\n return allAssessments;\n};\n","import { OneTrustGetAssessmentResponse } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\n/**\n * Retrieve details about a particular assessment.\n * ref: https://developer.onetrust.com/onetrust/reference/exportassessmentusingget\n *\n * @param param - the information about the OneTrust client and assessment to retrieve\n * @returns details about the assessment\n */\nexport const getOneTrustAssessment = async ({\n oneTrust,\n assessmentId,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n /** The ID of the assessment to retrieve */\n assessmentId: string;\n}): Promise<OneTrustGetAssessmentResponse> => {\n const { body } = await oneTrust.get(\n `api/assessment/v2/assessments/${assessmentId}/export?ExcludeSkippedQuestions=false`,\n );\n\n return decodeCodec(OneTrustGetAssessmentResponse, body);\n};\n","import { OneTrustGetRiskResponse } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\n/**\n * Retrieve details about a particular risk.\n * ref: https://developer.onetrust.com/onetrust/reference/getriskusingget\n *\n * @param param - the information about the OneTrust client and risk to retrieve\n * @returns the OneTrust risk\n */\nexport const getOneTrustRisk = async ({\n oneTrust,\n riskId,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n /** The ID of the OneTrust risk to retrieve */\n riskId: string;\n}): Promise<OneTrustGetRiskResponse> => {\n const { body } = await oneTrust.get(`api/risk/v2/risks/${riskId}`);\n\n return decodeCodec(OneTrustGetRiskResponse, body);\n};\n","import { OneTrustGetUserResponse } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\n/**\n * Retrieve details about a particular user.\n * ref: https://developer.onetrust.com/onetrust/reference/getriskusingget\n *\n * @param param - the information about the OneTrust client and risk to retrieve\n * @returns the OneTrust risk\n */\nexport const getOneTrustUser = async ({\n oneTrust,\n userId,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n /** The ID of the OneTrust user to retrieve */\n userId: string;\n}): Promise<OneTrustGetUserResponse> => {\n const { body } = await oneTrust.get(`api/scim/v2/Users/${userId}`);\n\n return decodeCodec(OneTrustGetUserResponse, body);\n};\n","import {\n OneTrustAssessment,\n OneTrustEnrichedAssessment,\n OneTrustGetAssessmentResponse,\n OneTrustGetRiskResponse,\n OneTrustGetUserResponse,\n} from '@transcend-io/privacy-types';\nimport { keyBy } from 'lodash-es';\n\n/**\n * Merge the assessment, assessmentDetails, and riskDetails into one object.\n *\n * @param param - the assessment and risk information\n * @returns the assessment enriched with details and risk information\n */\nexport const enrichOneTrustAssessment = ({\n assessment,\n assessmentDetails,\n riskDetails,\n creatorDetails,\n approversDetails,\n respondentsDetails,\n}: {\n /** The OneTrust risk details */\n riskDetails: OneTrustGetRiskResponse[];\n /** The OneTrust assessment as returned from Get List of Assessments endpoint */\n assessment: OneTrustAssessment;\n /** The OneTrust assessment details */\n assessmentDetails: OneTrustGetAssessmentResponse;\n /** The OneTrust assessment creator details */\n creatorDetails: OneTrustGetUserResponse;\n /** The OneTrust assessment approvers details */\n approversDetails: OneTrustGetUserResponse[];\n /** The OneTrust assessment internal respondents details */\n respondentsDetails: OneTrustGetUserResponse[];\n}): OneTrustEnrichedAssessment => {\n const riskDetailsById = keyBy(riskDetails, 'id');\n const { sections, createdBy, ...restAssessmentDetails } = assessmentDetails;\n const sectionsWithEnrichedRisk = sections.map((section) => {\n const { questions, ...restSection } = section;\n const enrichedQuestions = questions.map((question) => {\n const { risks, ...restQuestion } = question;\n const enrichedRisks = (risks ?? []).map((risk) => {\n const details = riskDetailsById[risk.riskId];\n return {\n ...risk,\n ...details,\n level: risk.level,\n impactLevel: risk.impactLevel ?? 0,\n };\n });\n return {\n ...restQuestion,\n risks: enrichedRisks,\n };\n });\n return {\n ...restSection,\n questions: enrichedQuestions,\n };\n });\n\n // grab creator details\n const enrichedCreatedBy = {\n ...createdBy,\n active: creatorDetails?.active ?? false,\n userType: creatorDetails?.userType ?? 'Internal',\n emails: creatorDetails?.emails ?? [],\n title: creatorDetails?.title ?? null,\n givenName: creatorDetails?.name.givenName ?? null,\n familyName: creatorDetails?.name.familyName ?? null,\n };\n\n // grab approvers details\n const approverDetailsById = keyBy(approversDetails, 'id');\n const enrichedApprovers = assessmentDetails.approvers.flatMap((originalApprover) =>\n approverDetailsById[originalApprover.id]\n ? [\n {\n ...originalApprover,\n approver: {\n ...originalApprover.approver,\n active: approverDetailsById[originalApprover.id].active,\n userType: approverDetailsById[originalApprover.id].userType,\n emails: approverDetailsById[originalApprover.id].emails,\n title: approverDetailsById[originalApprover.id].title,\n givenName: approverDetailsById[originalApprover.id].name.givenName ?? null,\n familyName: approverDetailsById[originalApprover.id].name.familyName ?? null,\n },\n },\n ]\n : [],\n );\n\n // grab respondents details\n const respondentsDetailsById = keyBy(respondentsDetails, 'id');\n const enrichedRespondents = assessmentDetails.respondents\n .filter((r) => !r.name.includes('@')) // search only internal respondents\n .flatMap((respondent) =>\n respondentsDetailsById[respondent.id]\n ? [\n {\n ...respondent,\n active: respondentsDetailsById[respondent.id].active,\n userType: respondentsDetailsById[respondent.id].userType,\n emails: respondentsDetailsById[respondent.id].emails,\n title: respondentsDetailsById[respondent.id].title,\n givenName: respondentsDetailsById[respondent.id].name.givenName ?? null,\n familyName: respondentsDetailsById[respondent.id].name.familyName ?? null,\n },\n ]\n : [],\n );\n\n // combine everything into a single enriched assessment\n return {\n ...assessment,\n ...restAssessmentDetails,\n approvers: enrichedApprovers,\n respondents: enrichedRespondents,\n createdBy: enrichedCreatedBy,\n sections: sectionsWithEnrichedRisk,\n };\n};\n","import { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport { makeGraphQLRequest, IMPORT_ONE_TRUST_ASSESSMENT_FORMS } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport { GraphQLClient } from 'graphql-request';\n\nimport { ImportOnetrustAssessmentsInput } from '../../../codecs.js';\nimport { logger } from '../../../logger.js';\nimport { oneTrustAssessmentToJson } from './oneTrustAssessmentToJson.js';\n\nexport interface AssessmentForm {\n /** ID of Assessment Form */\n id: string;\n /** Title of Assessment Form */\n name: string;\n}\n\n/**\n * Write the assessment to a Transcend instance.\n *\n *\n * @param param - information about the assessment and Transcend instance to write to\n */\nexport const syncOneTrustAssessmentToTranscend = async ({\n transcend,\n assessment,\n total,\n index,\n}: {\n /** the Transcend client instance */\n transcend: GraphQLClient;\n /** the assessment to sync to Transcend */\n assessment: OneTrustEnrichedAssessment;\n /** The index of the assessment being written to the file */\n index: number;\n /** The total amount of assessments that we will write */\n total?: number;\n}): Promise<void> => {\n logger.info(\n colors.magenta(\n `Writing enriched assessment ${index + 1} ${total ? `of ${total} ` : ' '}to Transcend...`,\n ),\n );\n\n // convert the OneTrust assessment object into a json record\n const json = oneTrustAssessmentToJson({\n assessment,\n index,\n total,\n });\n\n // transform the json record into a valid input to the mutation\n const input: ImportOnetrustAssessmentsInput = {\n json,\n };\n\n try {\n await makeGraphQLRequest<{\n /** the importOneTrustAssessmentForms mutation */\n importOneTrustAssessmentForms: {\n /** Created Assessment Forms */\n assessmentForms: AssessmentForm[];\n };\n }>(transcend, IMPORT_ONE_TRUST_ASSESSMENT_FORMS, {\n variables: { input },\n logger,\n });\n } catch (error) {\n logger.error(\n colors.red(\n `Failed to sync assessment ${index + 1} ${total ? `of ${total} ` : ' '}to Transcend.\\n` +\n `\\tAssessment Title: ${assessment.name}. Template Title: ${assessment.template.name}\\n`,\n ),\n error,\n );\n }\n};\n","import {\n OneTrustAssessmentQuestion,\n OneTrustAssessmentSection,\n OneTrustEnrichedAssessment,\n OneTrustGetRiskResponse,\n OneTrustGetUserResponse,\n} from '@transcend-io/privacy-types';\nimport { mapSeries, map } from '@transcend-io/utils';\nimport colors from 'colors';\nimport type { Got } from 'got';\nimport { GraphQLClient } from 'graphql-request';\nimport { uniq } from 'lodash-es';\n\nimport { logger } from '../../../logger.js';\nimport {\n getListOfOneTrustAssessments,\n getOneTrustAssessment,\n getOneTrustRisk,\n getOneTrustUser,\n} from '../endpoints/index.js';\nimport { enrichOneTrustAssessment } from './enrichOneTrustAssessment.js';\nimport { syncOneTrustAssessmentToDisk } from './syncOneTrustAssessmentToDisk.js';\nimport { syncOneTrustAssessmentToTranscend } from './syncOneTrustAssessmentToTranscend.js';\n\nexport interface AssessmentForm {\n /** ID of Assessment Form */\n id: string;\n /** Title of Assessment Form */\n name: string;\n}\n\n/**\n * Reads all the assessments from a OneTrust instance and syncs them to Transcend or to Disk.\n *\n * @param param - the information about the assessment, its OneTrust source, and destination (disk or Transcend)\n */\nexport const syncOneTrustAssessmentsFromOneTrust = async ({\n oneTrust,\n file,\n dryRun,\n transcend,\n}: {\n /** the OneTrust client instance */\n oneTrust: Got;\n /** the Transcend client instance */\n transcend?: GraphQLClient;\n /** Whether to write to file instead of syncing to Transcend */\n dryRun: boolean;\n /** the path to the file in case dryRun is true */\n file?: string;\n}): Promise<void> => {\n // fetch the list of all assessments in the OneTrust organization\n logger.info('Getting list of all assessments from OneTrust...');\n const assessments = await getListOfOneTrustAssessments({ oneTrust });\n\n // a cache of OneTrust users so we avoid requesting already fetched users\n const oneTrustCachedUsers: Record<string, OneTrustGetUserResponse> = {};\n\n // split all assessments in batches, so we can process some of steps in parallel\n const BATCH_SIZE = 5;\n const assessmentBatches = Array.from(\n {\n length: Math.ceil(assessments.length / BATCH_SIZE),\n },\n (_, i) => assessments.slice(i * BATCH_SIZE, (i + 1) * BATCH_SIZE),\n );\n\n // process each batch and sync the batch right away so it's garbage collected and we don't run out of memory\n await mapSeries(assessmentBatches, async (assessmentBatch, batch) => {\n const batchEnrichedAssessments: OneTrustEnrichedAssessment[] = [];\n\n // fetch assessment details from OneTrust in parallel\n await map(\n assessmentBatch,\n async (assessment, index) => {\n const assessmentNumber = BATCH_SIZE * batch + index + 1;\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching details...`,\n );\n const { templateName, assessmentId } = assessment;\n const assessmentDetails = await getOneTrustAssessment({\n oneTrust,\n assessmentId,\n });\n // fetch assessment's creator information\n const creatorId = assessmentDetails.createdBy.id;\n let creator = oneTrustCachedUsers[creatorId];\n if (!creator) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching creator...`,\n );\n try {\n creator = await getOneTrustUser({\n oneTrust,\n userId: creatorId,\n });\n oneTrustCachedUsers[creatorId] = creator;\n } catch (error) {\n logger.warn(\n colors.yellow(\n `[assessment ${assessmentNumber} of ${assessments.length}]: failed to fetch form creator.` +\n `\\tcreatorId: ${creatorId}. Assessment Title: ${assessment.name}. Template Title: ${templateName}`,\n ),\n error,\n );\n }\n }\n\n // fetch assessment approvers information\n const { approvers } = assessmentDetails;\n let approversDetails: OneTrustGetUserResponse[][] = [];\n if (approvers.length > 0) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching approvers...`,\n );\n approversDetails = await map(\n approvers.map(({ id }) => id),\n async (userId) => {\n try {\n let approver = oneTrustCachedUsers[userId];\n if (!approver) {\n approver = await getOneTrustUser({ oneTrust, userId });\n oneTrustCachedUsers[userId] = approver;\n }\n return [approver];\n } catch (error) {\n logger.warn(\n colors.yellow(\n `[assessment ${assessmentNumber} of ${assessments.length}]: failed to fetch a form approver.` +\n `\\tapproverId: ${userId}. Assessment Title: ${assessment.name}. Template Title: ${templateName}`,\n ),\n error,\n );\n return [];\n }\n },\n { concurrency: 5 },\n );\n }\n\n // fetch assessment internal respondents information\n const { respondents } = assessmentDetails;\n // if a user is an internal respondents, their 'name' field can't be an email.\n const internalRespondents = respondents.filter((r) => !r.name.includes('@'));\n let respondentsDetails: OneTrustGetUserResponse[][] = [];\n if (internalRespondents.length > 0) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching respondents...`,\n );\n respondentsDetails = await map(\n internalRespondents.map(({ id }) => id),\n async (userId) => {\n try {\n let respondent = oneTrustCachedUsers[userId];\n if (!respondent) {\n respondent = await getOneTrustUser({ oneTrust, userId });\n oneTrustCachedUsers[userId] = respondent;\n }\n return [respondent];\n } catch (error) {\n logger.warn(\n colors.yellow(\n `[assessment ${assessmentNumber} of ${assessments.length}]: failed to fetch a respondent.` +\n `\\trespondentId: ${userId}. Assessment Title: ${assessment.name}. Template Title: ${templateName}`,\n ),\n error,\n );\n return [];\n }\n },\n { concurrency: 5 },\n );\n }\n\n // fetch assessment risk information\n let riskDetails: OneTrustGetRiskResponse[] = [];\n const riskIds = uniq(\n assessmentDetails.sections.flatMap((s: OneTrustAssessmentSection) =>\n s.questions.flatMap((q: OneTrustAssessmentQuestion) =>\n (q.risks ?? []).flatMap((r) => r.riskId),\n ),\n ),\n );\n if (riskIds.length > 0) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching risks...`,\n );\n riskDetails = await map(\n riskIds,\n (riskId) => getOneTrustRisk({ oneTrust, riskId: riskId as string }),\n {\n concurrency: 5,\n },\n );\n }\n\n // enrich the assessments with user and risk details\n const enrichedAssessment = enrichOneTrustAssessment({\n assessment,\n assessmentDetails,\n riskDetails,\n creatorDetails: creator,\n approversDetails: approversDetails.flat(),\n respondentsDetails: respondentsDetails.flat(),\n });\n\n batchEnrichedAssessments.push(enrichedAssessment);\n },\n { concurrency: BATCH_SIZE },\n );\n\n // sync assessments in series to avoid concurrency bugs\n await mapSeries(batchEnrichedAssessments, async (enrichedAssessment, index) => {\n // the assessment's global index takes its batch into consideration\n const globalIndex = batch * BATCH_SIZE + index;\n\n if (dryRun && file) {\n // sync to file\n syncOneTrustAssessmentToDisk({\n assessment: enrichedAssessment,\n index: globalIndex,\n total: assessments.length,\n file,\n });\n } else if (transcend) {\n // sync to transcend\n await syncOneTrustAssessmentToTranscend({\n assessment: enrichedAssessment,\n transcend,\n total: assessments.length,\n index: globalIndex,\n });\n }\n });\n });\n};\n","import { createReadStream } from 'node:fs';\n\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport colors from 'colors';\nimport { GraphQLClient } from 'graphql-request';\nimport JSONStream from 'JSONStream';\n\nimport { logger } from '../../../logger.js';\nimport { syncOneTrustAssessmentToTranscend } from './syncOneTrustAssessmentToTranscend.js';\n\n/**\n * Reads assessments from a file and syncs them to Transcend.\n *\n * @param param - the information about the source file and Transcend instance to write them to.\n */\nexport const syncOneTrustAssessmentsFromFile = ({\n transcend,\n file,\n}: {\n /** the Transcend client instance */\n transcend: GraphQLClient;\n /** The name of the file from which to read the OneTrust assessments */\n file: string;\n}): Promise<void> => {\n logger.info(`Getting list of all assessments from file ${file}...`);\n\n return new Promise((resolve, reject) => {\n // Create a readable stream from the file\n const fileStream = createReadStream(file, {\n encoding: 'utf-8',\n highWaterMark: 64 * 1024, // 64KB chunks\n });\n\n // Create a JSONStream parser to parse the array of OneTrust assessments from the file\n const parser = JSONStream.parse('*'); // '*' matches each element in the root array\n\n let index = 0;\n\n // Pipe the file stream into the JSON parser\n fileStream.pipe(parser);\n\n // Handle each parsed assessment object\n parser.on('data', async (assessment) => {\n try {\n // Pause the stream while processing to avoid overwhelming memory\n parser.pause();\n\n // Decode and validate the assessment\n const parsedAssessment = decodeCodec(OneTrustEnrichedAssessment, assessment);\n\n // Sync the assessment to transcend\n await syncOneTrustAssessmentToTranscend({\n assessment: parsedAssessment,\n transcend,\n index,\n });\n\n index += 1;\n\n // Resume the stream after processing\n parser.resume();\n } catch (e) {\n // if failed to parse a line, report error and continue\n logger.error(\n colors.red(`Failed to parse the assessment ${index} from file '${file}': ${e.message}.`),\n );\n }\n });\n\n // Handle completion\n parser.on('end', () => {\n logger.info(`Finished processing ${index} assessments from file ${file}`);\n resolve();\n });\n\n // Handle stream or parsing errors\n parser.on('error', (error) => {\n logger.error(colors.red(`Error parsing file '${file}': ${error.message}`));\n reject(error);\n });\n\n fileStream.on('error', (error) => {\n logger.error(colors.red(`Error reading file '${file}': ${error.message}`));\n reject(error);\n });\n });\n};\n","import got, { Got } from 'got';\n\n/**\n * Instantiate an instance of got that is capable of making requests to OneTrust\n *\n * @param param - information about the OneTrust URL\n * @returns The instance of got that is capable of making requests to the customer ingress\n */\nexport const createOneTrustGotInstance = ({\n hostname,\n auth,\n}: {\n /** Hostname of the OneTrust API */\n hostname: string;\n /** The OAuth access token */\n auth: string;\n}): Got =>\n got.extend({\n prefixUrl: `https://${hostname}`,\n headers: {\n accept: 'application/json',\n 'content-type': 'application/json',\n authorization: `Bearer ${auth}`,\n },\n });\n","import { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { OneTrustFileFormat, OneTrustPullResource, OneTrustPullSource } from '../../../enums.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport {\n syncOneTrustAssessmentsFromFile,\n syncOneTrustAssessmentsFromOneTrust,\n} from '../../../lib/oneTrust/helpers/index.js';\nimport { createOneTrustGotInstance } from '../../../lib/oneTrust/index.js';\nimport { logger } from '../../../logger.js';\n\n// Command flag interface\nexport interface SyncOtCommandFlags {\n hostname?: string;\n oneTrustAuth?: string;\n source: OneTrustPullSource;\n transcendAuth?: string;\n transcendUrl: string;\n file?: string;\n resource: OneTrustPullResource;\n dryRun: boolean;\n debug: boolean;\n}\n\n// Command implementation\nexport async function syncOt(\n this: LocalContext,\n {\n hostname,\n oneTrustAuth,\n source,\n transcendAuth,\n transcendUrl,\n resource,\n file,\n dryRun,\n debug,\n }: SyncOtCommandFlags,\n): Promise<void> {\n // Must be able to authenticate to transcend to sync resources to it\n if (!dryRun && !transcendAuth) {\n throw new Error(\n // eslint-disable-next-line no-template-curly-in-string\n 'Must specify a \"transcendAuth\" parameter to sync resources to Transcend. e.g. --transcendAuth=${TRANSCEND_API_KEY}',\n );\n }\n\n // If trying to sync to disk, must specify a file path\n if (dryRun && !file) {\n throw new Error(\n 'Must set a \"file\" parameter when \"dryRun\" is \"true\". e.g. --file=./oneTrustAssessments.json',\n );\n }\n\n if (file) {\n const splitFile = file.split('.');\n if (splitFile.length < 2) {\n throw new Error(\n 'The \"file\" parameter has an invalid format. Expected a path with extensions. e.g. --file=./pathToFile.json.',\n );\n }\n if (splitFile.at(-1) !== OneTrustFileFormat.Json) {\n throw new Error(\n `Expected the format of the \"file\" parameters '${file}' to be '${\n OneTrustFileFormat.Json\n }', but got '${splitFile.at(-1)}'.`,\n );\n }\n }\n\n // if reading assessments from a OneTrust\n if (source === OneTrustPullSource.OneTrust) {\n // must specify the OneTrust hostname\n if (!hostname) {\n throw new Error(\n 'Missing required parameter \"hostname\". e.g. --hostname=customer.my.onetrust.com',\n );\n }\n // must specify the OneTrust auth\n if (!oneTrustAuth) {\n throw new Error(\n 'Missing required parameter \"oneTrustAuth\". e.g. --oneTrustAuth=$ONE_TRUST_AUTH_TOKEN',\n );\n }\n } else {\n // if reading the assessments from a file, must specify a file to read from\n if (!file) {\n throw new Error(\n 'Must specify a \"file\" parameter to read the OneTrust assessments from. e.g. --source=./oneTrustAssessments.json',\n );\n }\n\n // Cannot try reading from file and save assessments to a file simultaneously\n if (dryRun) {\n throw new Error(\n 'Cannot read and write to a file simultaneously.' +\n ` Emit the \"source\" parameter or set it to ${OneTrustPullSource.OneTrust} if \"dryRun\" is enabled.`,\n );\n }\n }\n\n doneInputValidation(this.process.exit);\n\n // instantiate a client to talk to OneTrust\n const oneTrust =\n hostname && oneTrustAuth\n ? createOneTrustGotInstance({\n hostname,\n auth: oneTrustAuth,\n })\n : undefined;\n\n // instantiate a client to talk to Transcend\n const transcend =\n transcendUrl && transcendAuth\n ? buildTranscendGraphQLClient(transcendUrl, transcendAuth)\n : undefined;\n\n try {\n if (resource === OneTrustPullResource.Assessments) {\n if (source === OneTrustPullSource.OneTrust && oneTrust) {\n await syncOneTrustAssessmentsFromOneTrust({\n oneTrust,\n file,\n dryRun,\n ...(transcend && { transcend }),\n });\n } else if (source === OneTrustPullSource.File && file && transcend) {\n await syncOneTrustAssessmentsFromFile({ file, transcend });\n }\n }\n } catch (err) {\n throw new Error(\n `An error occurred syncing the resource ${resource} from OneTrust: ${\n debug ? err.stack : err.message\n }`,\n );\n }\n\n // Indicate success\n logger.info(\n colors.green(\n `Successfully synced OneTrust ${resource} to ${dryRun ? `disk at \"${file}\"` : 'Transcend'}!`,\n ),\n );\n}\n"],"mappings":"utBAQA,MAAa,GAA4B,CACvC,aACA,QACA,QACA,OAAO,MAUK,CACZ,IAAI,EAAY,IAEZ,IAAU,GAAK,KACjB,EAAY;GAGd,IAAM,EAAwB,KAAK,UAAU,EAAW,CAGlD,EAAQ,GAAS,EAAQ,EAAQ,GAAK,CAAC,EAAO,IAAM,GAU1D,MAPA,GAAY,GAAG,EAAY,EAAwB,EAAM,KAGpD,GAAS,IAAU,EAAQ,GAAM,KACpC,GAAa;IAGR,GC5BI,GAAgC,CAC3C,OACA,aACA,QACA,WAUU,CACV,EAAO,KACL,EAAO,QAAQ,+BAA+B,EAAQ,EAAE,MAAM,EAAM,YAAY,EAAK,MAAM,CAC5F,CAEG,IAAU,EACZ,EAAG,cACD,EACA,EAAyB,CACvB,aACA,QACA,QACA,KAAM,GACP,CAAC,CACH,CAED,EAAG,eACD,EACA,EAAyB,CACvB,aACA,QACA,QACA,KAAM,GACP,CAAC,CACH,ECpCQ,EAA+B,MAAO,CACjD,cAImC,CACnC,IAAI,EAAc,EACd,EAAa,EACb,EAAgB,EAEd,EAAuC,EAAE,CAE/C,KAAO,EAAc,GAAY,CAC/B,GAAM,CAAE,QAAS,MAAM,EAAS,IAC9B,sCAAsC,EAAY,YACnD,CAEK,CAAE,OAAM,WAAY,EAAY,EAAsC,EAAK,CACjF,EAAe,KAAK,GAAI,GAAW,EAAE,CAAE,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AAK,YAAY,GAC3F,CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"impl-DQQ_nI25.mjs","names":[],"sources":["../src/lib/preference-management/bulkDeletePreferenceRecords.ts","../src/commands/consent/delete-preference-records/impl.ts"],"sourcesContent":["import {\n DeletePreferenceRecordCliCsvRow,\n DeletePreferenceRecordsResponse,\n withTransientRetry,\n} from '@transcend-io/sdk';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { map } from '@transcend-io/utils';\nimport colors from 'colors';\nimport type { Got } from 'got';\nimport { chunk } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { readCsv } from '../requests/index.js';\n\ninterface FailedResult extends DeletePreferenceRecordCliCsvRow {\n /** Error message describing the failure */\n error: string;\n}\n\ninterface DeletePreferenceRecordsRepositoryOptions {\n /** The partition to delete from */\n partition: string;\n /** Chunk of identifiers to delete */\n identifierChunk: DeletePreferenceRecordCliCsvRow[];\n /** the timestamp for the deletion operation */\n timestamp: Date;\n}\n\n/**\n * Options for deleting preference records\n */\ntype DeletePreferenceRecordsOptions = Omit<\n DeletePreferenceRecordsRepositoryOptions,\n 'identifierChunk'\n> & {\n /** The file path to read CSV rows from */\n filePath: string;\n /** Maximum items to include in each deletion chunk */\n maxItemsInChunk: number;\n /** Maximum concurrency for deletion requests */\n maxConcurrency: number;\n};\n\n/**\n *\n * Delete a chunk of preference records\n *\n * @param sombra - Sombra instance (must include auth headers)\n * @param options - Options for deletion\n * @param options.partition - The partition to delete from\n * @param options.identifierChunk - Chunk of identifiers to delete\n * @param options.timestamp - The timestamp for the deletion operation\n * @returns List of failed deletions\n */\nasync function deletePreferenceRecordsRepository(\n sombra: Got,\n { partition, identifierChunk: chunk, timestamp }: DeletePreferenceRecordsRepositoryOptions,\n): Promise<FailedResult[]> {\n try {\n const response = await withTransientRetry(\n 'Delete Preference Records',\n () =>\n sombra\n .post(`v1/preferences/${partition}/delete`, {\n json: {\n records: chunk.map((record) => ({\n anchorIdentifier: record,\n timestamp: timestamp.toISOString(),\n })),\n },\n })\n .json(),\n {\n logger,\n maxAttempts: 3,\n onRetry: (attempt, _err, msg) => {\n logger.warn(\n colors.yellow(`Attempt ${attempt} to delete preference records failed: ${msg}`),\n );\n },\n },\n );\n const { failures } = decodeCodec(DeletePreferenceRecordsResponse, response);\n if (failures.length > 0) {\n return failures.map(({ index, error }) => ({\n ...chunk[index],\n error,\n }));\n }\n return [];\n } catch (err) {\n return chunk.map((record) => ({\n ...record,\n error: (err as Error).message,\n }));\n }\n}\n\n/**\n * Delete consent preferences for the managed consent database (delete endpoint)\n *\n * Uses POST /v1/preferences/{partition}/delete.\n *\n *\n * @param sombra - Sombra instance (must include auth headers)\n * @param options - Query options\n * @returns All nodes (only when onItems is not provided)\n */\nexport async function bulkDeletePreferenceRecords(\n sombra: Got,\n {\n partition,\n filePath,\n timestamp,\n maxItemsInChunk,\n maxConcurrency,\n }: DeletePreferenceRecordsOptions,\n): Promise<FailedResult[]> {\n const anchorIdentifiers = readCsv(filePath, DeletePreferenceRecordCliCsvRow);\n const chunks = chunk(anchorIdentifiers, maxItemsInChunk);\n\n const failedResults = await map(\n chunks,\n async (identifierChunk) => {\n const failedResults = await deletePreferenceRecordsRepository(sombra, {\n partition,\n identifierChunk,\n timestamp,\n });\n return failedResults;\n },\n { concurrency: maxConcurrency },\n );\n return failedResults.flat();\n}\n","import { readdirSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { createSombraGotInstance } from '@transcend-io/sdk';\nimport { map } from '@transcend-io/utils';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { writeCsv } from '../../../lib/helpers/index.js';\nimport { bulkDeletePreferenceRecords } from '../../../lib/preference-management/index.js';\nimport { logger } from '../../../logger.js';\n\nexport interface DeletePreferenceRecordsCommandFlags {\n /** Transcend API key for authentication */\n auth: string;\n /** Partition ID to delete preference records from */\n partition: string;\n /** Optional Sombra internal key for self-hosted instances */\n sombraAuth?: string;\n /** Path to the CSV file used to identify preference records to delete */\n file?: string;\n /** Path to the directory of CSV files to load preferences from */\n directory?: string;\n /** Base URL for the Transcend API */\n transcendUrl: string;\n /** The timestamp when the deletion operation is made. Used for logging purposes. */\n timestamp: Date;\n /** Maximum items to include in each deletion chunk */\n maxItemsInChunk: number;\n /** Maximum concurrency for deletion requests */\n maxConcurrency: number;\n /** Directory to write receipts of failed deletions to */\n receiptDirectory: string;\n /** Number of files to process concurrently when deleting preference records from multiple files */\n fileConcurrency: number;\n}\n\nexport async function deletePreferenceRecords(\n this: LocalContext,\n {\n auth,\n partition,\n sombraAuth,\n file = '',\n directory,\n transcendUrl,\n timestamp,\n maxConcurrency,\n maxItemsInChunk,\n receiptDirectory,\n fileConcurrency,\n }: DeletePreferenceRecordsCommandFlags,\n): Promise<void> {\n if (!!directory && !!file) {\n logger.error(\n colors.red('Cannot provide both a directory and a file. Please provide only one.'),\n );\n this.process.exit(1);\n }\n\n if (!file && !directory) {\n logger.error(\n colors.red(\n 'A file or directory must be provided. Please provide one using --file=./preferences.csv or --directory=./preferences',\n ),\n );\n this.process.exit(1);\n }\n doneInputValidation(this.process.exit);\n\n const files: string[] = [];\n\n if (directory) {\n try {\n const filesInDirectory = readdirSync(directory);\n const csvFiles = filesInDirectory.filter((file) => file.endsWith('.csv'));\n\n if (csvFiles.length === 0) {\n logger.error(colors.red(`No CSV files found in directory: ${directory}`));\n this.process.exit(1);\n }\n\n // Add full paths for each CSV file\n files.push(...csvFiles.map((file) => join(directory, file)));\n } catch (err) {\n logger.error(colors.red(`Failed to read directory: ${directory}`));\n logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n } else {\n try {\n // Verify file exists and is a CSV\n if (!file.endsWith('.csv')) {\n logger.error(colors.red('File must be a CSV file'));\n this.process.exit(1);\n }\n files.push(file);\n } catch (err) {\n logger.error(colors.red(`Failed to access file: ${file}`));\n logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n }\n\n logger.debug(\n colors.green(\n `Processing ${files.length} consent preferences files for partition: ${partition}`,\n ),\n );\n logger.debug(`\\nFiles to process: ${files.join(', ')}\\n`);\n\n // Create sombra instance to communicate with\n const sombra = await createSombraGotInstance(transcendUrl, auth, {\n logger,\n sombraApiKey: sombraAuth,\n sombraUrl: process.env.SOMBRA_URL,\n });\n const globalProgressBar = new cliProgress.SingleBar(\n {\n format: `Deletion Progress |${colors.cyan('[{bar}]')}| Duration: ${colors.red(\n '{duration_formatted}',\n )} | {value}/{total} Files Processed `,\n },\n cliProgress.Presets.shades_classic,\n );\n globalProgressBar.start(files.length, 0);\n\n // Process batch of files with concurrency\n const failedResultsArrays = await map(\n files,\n async (filePath) => {\n const result = await bulkDeletePreferenceRecords(sombra, {\n partition,\n filePath,\n timestamp,\n maxItemsInChunk,\n maxConcurrency,\n });\n globalProgressBar.increment();\n return result;\n },\n { concurrency: fileConcurrency },\n );\n globalProgressBar.stop();\n const failedResults = failedResultsArrays.flat();\n\n // Check for failed results and write receipt if any\n let receiptPath = '';\n if (failedResults.length > 0) {\n receiptPath = join(receiptDirectory, `deletion-failures-${Date.now()}.csv`);\n writeCsv(receiptPath, failedResults, true);\n }\n\n logger.info(colors.green('\\n\\n ================================== \\n\\n'));\n logger.info(colors.green('\\n#### Deletion Summary Report #####\\n'));\n logger.info(\n colors.green(\n `📁 Total Files Processed: ${files.length} \\n` +\n `❌ Errors: ${failedResults.length} \\n` +\n `📝 Receipt Path: ${receiptPath || 'N/A'}`,\n ),\n );\n logger.info(colors.green('\\n\\n==================================\\n\\n'));\n}\n"],"mappings":"+kBAsDA,eAAe,EACb,EACA,CAAE,YAAW,gBAAiB,EAAO,aACZ,CACzB,GAAI,CAwBF,GAAM,CAAE,YAAa,EAAY,EAvBhB,MAAM,EACrB,gCAEE,EACG,KAAK,kBAAkB,EAAU,SAAU,CAC1C,KAAM,CACJ,QAAS,EAAM,IAAK,IAAY,CAC9B,iBAAkB,EAClB,UAAW,EAA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,CAAC,CACnE,EAAO,KACL,EAAO,MACL,6BAA6B,EAAM,OAAO,eAC3B,EAAc,OAAO,sBACd,GAAe,QACtC,CACF,CACD,EAAO,KAAK,EAAO,MAAM;;;;EAA6C,CAAC"}
1
+ {"version":3,"file":"impl-DQQ_nI25.mjs","names":[],"sources":["../src/lib/preference-management/bulkDeletePreferenceRecords.ts","../src/commands/consent/delete-preference-records/impl.ts"],"sourcesContent":["import {\n DeletePreferenceRecordCliCsvRow,\n DeletePreferenceRecordsResponse,\n withTransientRetry,\n} from '@transcend-io/sdk';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { map } from '@transcend-io/utils';\nimport colors from 'colors';\nimport type { Got } from 'got';\nimport { chunk } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { readCsv } from '../requests/index.js';\n\ninterface FailedResult extends DeletePreferenceRecordCliCsvRow {\n /** Error message describing the failure */\n error: string;\n}\n\ninterface DeletePreferenceRecordsRepositoryOptions {\n /** The partition to delete from */\n partition: string;\n /** Chunk of identifiers to delete */\n identifierChunk: DeletePreferenceRecordCliCsvRow[];\n /** the timestamp for the deletion operation */\n timestamp: Date;\n}\n\n/**\n * Options for deleting preference records\n */\ntype DeletePreferenceRecordsOptions = Omit<\n DeletePreferenceRecordsRepositoryOptions,\n 'identifierChunk'\n> & {\n /** The file path to read CSV rows from */\n filePath: string;\n /** Maximum items to include in each deletion chunk */\n maxItemsInChunk: number;\n /** Maximum concurrency for deletion requests */\n maxConcurrency: number;\n};\n\n/**\n *\n * Delete a chunk of preference records\n *\n * @param sombra - Sombra instance (must include auth headers)\n * @param options - Options for deletion\n * @param options.partition - The partition to delete from\n * @param options.identifierChunk - Chunk of identifiers to delete\n * @param options.timestamp - The timestamp for the deletion operation\n * @returns List of failed deletions\n */\nasync function deletePreferenceRecordsRepository(\n sombra: Got,\n { partition, identifierChunk: chunk, timestamp }: DeletePreferenceRecordsRepositoryOptions,\n): Promise<FailedResult[]> {\n try {\n const response = await withTransientRetry(\n 'Delete Preference Records',\n () =>\n sombra\n .post(`v1/preferences/${partition}/delete`, {\n json: {\n records: chunk.map((record) => ({\n anchorIdentifier: record,\n timestamp: timestamp.toISOString(),\n })),\n },\n })\n .json(),\n {\n logger,\n maxAttempts: 3,\n onRetry: (attempt, _err, msg) => {\n logger.warn(\n colors.yellow(`Attempt ${attempt} to delete preference records failed: ${msg}`),\n );\n },\n },\n );\n const { failures } = decodeCodec(DeletePreferenceRecordsResponse, response);\n if (failures.length > 0) {\n return failures.map(({ index, error }) => ({\n ...chunk[index],\n error,\n }));\n }\n return [];\n } catch (err) {\n return chunk.map((record) => ({\n ...record,\n error: (err as Error).message,\n }));\n }\n}\n\n/**\n * Delete consent preferences for the managed consent database (delete endpoint)\n *\n * Uses POST /v1/preferences/{partition}/delete.\n *\n *\n * @param sombra - Sombra instance (must include auth headers)\n * @param options - Query options\n * @returns All nodes (only when onItems is not provided)\n */\nexport async function bulkDeletePreferenceRecords(\n sombra: Got,\n {\n partition,\n filePath,\n timestamp,\n maxItemsInChunk,\n maxConcurrency,\n }: DeletePreferenceRecordsOptions,\n): Promise<FailedResult[]> {\n const anchorIdentifiers = readCsv(filePath, DeletePreferenceRecordCliCsvRow);\n const chunks = chunk(anchorIdentifiers, maxItemsInChunk);\n\n const failedResults = await map(\n chunks,\n async (identifierChunk) => {\n const failedResults = await deletePreferenceRecordsRepository(sombra, {\n partition,\n identifierChunk,\n timestamp,\n });\n return failedResults;\n },\n { concurrency: maxConcurrency },\n );\n return failedResults.flat();\n}\n","import { readdirSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { createSombraGotInstance } from '@transcend-io/sdk';\nimport { map } from '@transcend-io/utils';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { writeCsv } from '../../../lib/helpers/index.js';\nimport { bulkDeletePreferenceRecords } from '../../../lib/preference-management/index.js';\nimport { logger } from '../../../logger.js';\n\nexport interface DeletePreferenceRecordsCommandFlags {\n /** Transcend API key for authentication */\n auth: string;\n /** Partition ID to delete preference records from */\n partition: string;\n /** Optional Sombra internal key for self-hosted instances */\n sombraAuth?: string;\n /** Path to the CSV file used to identify preference records to delete */\n file?: string;\n /** Path to the directory of CSV files to load preferences from */\n directory?: string;\n /** Base URL for the Transcend API */\n transcendUrl: string;\n /** The timestamp when the deletion operation is made. Used for logging purposes. */\n timestamp: Date;\n /** Maximum items to include in each deletion chunk */\n maxItemsInChunk: number;\n /** Maximum concurrency for deletion requests */\n maxConcurrency: number;\n /** Directory to write receipts of failed deletions to */\n receiptDirectory: string;\n /** Number of files to process concurrently when deleting preference records from multiple files */\n fileConcurrency: number;\n}\n\nexport async function deletePreferenceRecords(\n this: LocalContext,\n {\n auth,\n partition,\n sombraAuth,\n file = '',\n directory,\n transcendUrl,\n timestamp,\n maxConcurrency,\n maxItemsInChunk,\n receiptDirectory,\n fileConcurrency,\n }: DeletePreferenceRecordsCommandFlags,\n): Promise<void> {\n if (!!directory && !!file) {\n logger.error(\n colors.red('Cannot provide both a directory and a file. Please provide only one.'),\n );\n this.process.exit(1);\n }\n\n if (!file && !directory) {\n logger.error(\n colors.red(\n 'A file or directory must be provided. Please provide one using --file=./preferences.csv or --directory=./preferences',\n ),\n );\n this.process.exit(1);\n }\n doneInputValidation(this.process.exit);\n\n const files: string[] = [];\n\n if (directory) {\n try {\n const filesInDirectory = readdirSync(directory);\n const csvFiles = filesInDirectory.filter((file) => file.endsWith('.csv'));\n\n if (csvFiles.length === 0) {\n logger.error(colors.red(`No CSV files found in directory: ${directory}`));\n this.process.exit(1);\n }\n\n // Add full paths for each CSV file\n files.push(...csvFiles.map((file) => join(directory, file)));\n } catch (err) {\n logger.error(colors.red(`Failed to read directory: ${directory}`));\n logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n } else {\n try {\n // Verify file exists and is a CSV\n if (!file.endsWith('.csv')) {\n logger.error(colors.red('File must be a CSV file'));\n this.process.exit(1);\n }\n files.push(file);\n } catch (err) {\n logger.error(colors.red(`Failed to access file: ${file}`));\n logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n }\n\n logger.debug(\n colors.green(\n `Processing ${files.length} consent preferences files for partition: ${partition}`,\n ),\n );\n logger.debug(`\\nFiles to process: ${files.join(', ')}\\n`);\n\n // Create sombra instance to communicate with\n const sombra = await createSombraGotInstance(transcendUrl, auth, {\n logger,\n sombraApiKey: sombraAuth,\n sombraUrl: process.env.SOMBRA_URL,\n });\n const globalProgressBar = new cliProgress.SingleBar(\n {\n format: `Deletion Progress |${colors.cyan('[{bar}]')}| Duration: ${colors.red(\n '{duration_formatted}',\n )} | {value}/{total} Files Processed `,\n },\n cliProgress.Presets.shades_classic,\n );\n globalProgressBar.start(files.length, 0);\n\n // Process batch of files with concurrency\n const failedResultsArrays = await map(\n files,\n async (filePath) => {\n const result = await bulkDeletePreferenceRecords(sombra, {\n partition,\n filePath,\n timestamp,\n maxItemsInChunk,\n maxConcurrency,\n });\n globalProgressBar.increment();\n return result;\n },\n { concurrency: fileConcurrency },\n );\n globalProgressBar.stop();\n const failedResults = failedResultsArrays.flat();\n\n // Check for failed results and write receipt if any\n let receiptPath = '';\n if (failedResults.length > 0) {\n receiptPath = join(receiptDirectory, `deletion-failures-${Date.now()}.csv`);\n writeCsv(receiptPath, failedResults, true);\n }\n\n logger.info(colors.green('\\n\\n ================================== \\n\\n'));\n logger.info(colors.green('\\n#### Deletion Summary Report #####\\n'));\n logger.info(\n colors.green(\n `📁 Total Files Processed: ${files.length} \\n` +\n `❌ Errors: ${failedResults.length} \\n` +\n `📝 Receipt Path: ${receiptPath || 'N/A'}`,\n ),\n );\n logger.info(colors.green('\\n\\n==================================\\n\\n'));\n}\n"],"mappings":"+kBAsDA,eAAe,EACb,EACA,CAAE,YAAW,gBAAiB,EAAO,aACZ,CACzB,GAAI,CAwBF,GAAM,CAAE,YAAa,EAAY,EAAiC,MAvB3C,EACrB,gCAE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,EAAa,EAAe,GAAK,EAG5C,EAAO,KAAK,EAAO,MAAM;;;;EAA+C,CAAC,CACzE,EAAO,KAAK,EAAO,MAAM;;EAAyC,CAAC,CACnE,EAAO,KACL,EAAO,MACL,6BAA6B,EAAM,OAAO,eAC3B,EAAc,OAAO,sBACd,GAAe,QACtC,CACF,CACD,EAAO,KAAK,EAAO,MAAM;;;;EAA6C,CAAC"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./uploadDataFlowsFromCsv-Dnh7n6R0.mjs";import{t}from"./done-input-validation-BcNBxhEs.mjs";async function n({auth:n,trackerStatus:r,file:i,classifyService:a,transcendUrl:o}){t(this.process.exit),await e({auth:n,trackerStatus:r,file:i,classifyService:a,transcendUrl:o})}export{n as uploadDataFlowsFromCsv};
2
- //# sourceMappingURL=impl-DmFYqMyc.mjs.map
1
+ import{t as e}from"./uploadDataFlowsFromCsv-Db7cxXcH.mjs";import{t}from"./done-input-validation-BcNBxhEs.mjs";async function n({auth:n,trackerStatus:r,file:i,classifyService:a,transcendUrl:o}){t(this.process.exit),await e({auth:n,trackerStatus:r,file:i,classifyService:a,transcendUrl:o})}export{n as uploadDataFlowsFromCsv};
2
+ //# sourceMappingURL=impl-DT3pE3Ze.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-DmFYqMyc.mjs","names":["uploadDataFlowsFromCsvHelper"],"sources":["../src/commands/consent/upload-data-flows-from-csv/impl.ts"],"sourcesContent":["import { ConsentTrackerStatus } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { uploadDataFlowsFromCsv as uploadDataFlowsFromCsvHelper } from '../../../lib/consent-manager/index.js';\n\nexport interface UploadDataFlowsFromCsvCommandFlags {\n auth: string;\n trackerStatus: ConsentTrackerStatus;\n file: string;\n classifyService: boolean;\n transcendUrl: string;\n}\n\nexport async function uploadDataFlowsFromCsv(\n this: LocalContext,\n { auth, trackerStatus, file, classifyService, transcendUrl }: UploadDataFlowsFromCsvCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await uploadDataFlowsFromCsvHelper({\n auth,\n trackerStatus,\n file,\n classifyService,\n transcendUrl,\n });\n}\n"],"mappings":"8GAcA,eAAsB,EAEpB,CAAE,OAAM,gBAAe,OAAM,kBAAiB,gBAC/B,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAMA,EAA6B,CACjC,OACA,gBACA,OACA,kBACA,eACD,CAAC"}
1
+ {"version":3,"file":"impl-DT3pE3Ze.mjs","names":["uploadDataFlowsFromCsvHelper"],"sources":["../src/commands/consent/upload-data-flows-from-csv/impl.ts"],"sourcesContent":["import { ConsentTrackerStatus } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { uploadDataFlowsFromCsv as uploadDataFlowsFromCsvHelper } from '../../../lib/consent-manager/index.js';\n\nexport interface UploadDataFlowsFromCsvCommandFlags {\n auth: string;\n trackerStatus: ConsentTrackerStatus;\n file: string;\n classifyService: boolean;\n transcendUrl: string;\n}\n\nexport async function uploadDataFlowsFromCsv(\n this: LocalContext,\n { auth, trackerStatus, file, classifyService, transcendUrl }: UploadDataFlowsFromCsvCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await uploadDataFlowsFromCsvHelper({\n auth,\n trackerStatus,\n file,\n classifyService,\n transcendUrl,\n });\n}\n"],"mappings":"8GAcA,eAAsB,EAEpB,CAAE,OAAM,gBAAe,OAAM,kBAAiB,gBAC/B,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAMA,EAA6B,CACjC,OACA,gBACA,OACA,kBACA,eACD,CAAC"}
@@ -1,7 +1,7 @@
1
- import{t as e}from"./logger-Bj782ZYD.mjs";import{n as t}from"./parseAttributesFromString-D1Yl0xwT.mjs";import{t as n}from"./readCsv-C4TyEs-r.mjs";import{n as r}from"./inquirer-BqZXFEt1.mjs";import{t as i}from"./done-input-validation-BcNBxhEs.mjs";import{PreferenceTopicType as a}from"@transcend-io/privacy-types";import{chunk as o,difference as s,groupBy as c,keyBy as l,uniq as u}from"lodash-es";import{apply as d}from"@transcend-io/type-utils";import{readdirSync as f}from"node:fs";import{basename as p,join as m}from"node:path";import h from"colors";import*as g from"io-ts";import{PreferenceState as _,buildTranscendGraphQLClient as v,checkIfPendingPreferenceUpdatesAreNoOp as y,checkIfPendingPreferenceUpdatesCauseConflict as b,createSombraGotInstance as x,fetchAllPreferenceTopics as S,fetchAllPurposes as C,getPreferenceUpdatesFromRow as w,getPreferencesForIdentifiers as T}from"@transcend-io/sdk";import{map as E,mapSeries as D,splitCsvToList as O}from"@transcend-io/utils";import k from"cli-progress";import A from"inquirer";import{PersistedState as j}from"@transcend-io/persisted-state";async function M(t,n,{purposeSlugs:r,preferenceTopics:i,forceTriggerWorkflows:o}){let c=s(u(t.map(e=>Object.keys(e)).flat()),[...n.identifierColumn?[n.identifierColumn]:[],...n.timestampColum?[n.timestampColum]:[]]);if(c.length===0){if(o)return n;throw Error(`No other columns to process`)}let l=[...r,...i.map(e=>`${e.purpose.trackingType}->${e.slug}`)];return await D(c,async o=>{let s=u(t.map(e=>e[o])),c=n.columnToPurposeName[o];if(c)e.info(h.magenta(`Column "${o}" is associated with purpose "${c.purpose}"`));else{let{purposeName:e}=await A.prompt([{name:`purposeName`,message:`Choose the purpose that column ${o} is associated with`,type:`list`,default:l.find(e=>e.startsWith(r[0])),choices:l}]),[t,n]=e.split(`->`);c={purpose:t,preference:n||null,valueMapping:{}}}await D(s,async t=>{if(c.valueMapping[t]!==void 0){e.info(h.magenta(`Value "${t}" is associated with purpose value "${c.valueMapping[t]}"`));return}if(c.preference===null){let{purposeValue:e}=await A.prompt([{name:`purposeValue`,message:`Choose the purpose value for value "${t}" associated with purpose "${c.purpose}"`,type:`confirm`,default:t!==`false`}]);c.valueMapping[t]=e}if(c.preference!==null){let n=i.find(e=>e.slug===c.preference);if(!n){e.error(h.red(`Preference topic "${c.preference}" not found`));return}let r=n.preferenceOptionValues.map(({slug:e})=>e);if(n.type===a.Boolean){let{preferenceValue:e}=await A.prompt([{name:`preferenceValue`,message:`Choose the preference value for "${n.slug}" value "${t}" associated with purpose "${c.purpose}"`,type:`confirm`,default:t!==`false`}]);c.valueMapping[t]=e;return}if(n.type===a.Select){let{preferenceValue:e}=await A.prompt([{name:`preferenceValue`,message:`Choose the preference value for "${n.slug}" value "${t}" associated with purpose "${c.purpose}"`,type:`list`,choices:r,default:r.find(e=>e===t)}]);c.valueMapping[t]=e;return}if(n.type===a.MultiSelect){await D(O(t),async e=>{if(c.valueMapping[e]!==void 0)return;let{preferenceValue:t}=await A.prompt([{name:`preferenceValue`,message:`Choose the preference value for "${n.slug}" value "${e}" associated with purpose "${c.purpose}"`,type:`list`,choices:r,default:r.find(t=>t===e)}]);c.valueMapping[e]=t});return}throw Error(`Unknown preference topic type: ${n.type}`)}}),n.columnToPurposeName[o]=c}),n}async function N(t,n){let i=s(u(t.map(e=>Object.keys(e)).flat()),[...n.identifierColumn?[n.identifierColumn]:[],...Object.keys(n.columnToPurposeName)]);if(!n.identifierColumn){let{identifierName:e}=await A.prompt([{name:`identifierName`,message:`Choose the column that will be used as the identifier to upload consent preferences by`,type:`list`,default:i.find(e=>e.toLowerCase().includes(`email`))||i[0],choices:i}]);n.identifierColumn=e}e.info(h.magenta(`Using identifier column "${n.identifierColumn}"`));let a=t.map((e,t)=>e[n.identifierColumn]?null:[t]).filter(e=>!!e).flat();if(a.length>0){let i=`The identifier column "${n.identifierColumn}" is missing a value for the following rows: ${a.join(`, `)}`;if(e.warn(h.yellow(i)),!await r({message:`Would you like to skip rows missing an identifier?`}))throw Error(i);let o=t.length;t=t.filter(e=>e[n.identifierColumn]),e.info(h.yellow(`Skipped ${o-t.length} rows missing an identifier`))}e.info(h.magenta(`The identifier column "${n.identifierColumn}" is present for all rows`));let o=c(t,n.identifierColumn),l=Object.entries(o).filter(([,e])=>e.length>1);if(l.length>0){let i=`The identifier column "${n.identifierColumn}" has duplicate values for the following rows: ${l.slice(0,10).map(([e,t])=>`${e} (${t.length})`).join(`
1
+ import{t as e}from"./logger-Bj782ZYD.mjs";import{n as t}from"./parseAttributesFromString-q4-59nEN.mjs";import{t as n}from"./readCsv-C4TyEs-r.mjs";import{n as r}from"./inquirer-B4iEodLy.mjs";import{t as i}from"./done-input-validation-BcNBxhEs.mjs";import{PreferenceTopicType as a}from"@transcend-io/privacy-types";import{chunk as o,difference as s,groupBy as c,keyBy as l,uniq as u}from"lodash-es";import{apply as d}from"@transcend-io/type-utils";import{readdirSync as f}from"node:fs";import{basename as p,join as m}from"node:path";import h from"colors";import*as g from"io-ts";import{PreferenceState as _,buildTranscendGraphQLClient as v,checkIfPendingPreferenceUpdatesAreNoOp as y,checkIfPendingPreferenceUpdatesCauseConflict as b,createSombraGotInstance as x,fetchAllPreferenceTopics as S,fetchAllPurposes as C,getPreferenceUpdatesFromRow as w,getPreferencesForIdentifiers as T}from"@transcend-io/sdk";import{map as E,mapSeries as D,splitCsvToList as O}from"@transcend-io/utils";import k from"cli-progress";import A from"inquirer";import{PersistedState as j}from"@transcend-io/persisted-state";async function M(t,n,{purposeSlugs:r,preferenceTopics:i,forceTriggerWorkflows:o}){let c=s(u(t.map(e=>Object.keys(e)).flat()),[...n.identifierColumn?[n.identifierColumn]:[],...n.timestampColum?[n.timestampColum]:[]]);if(c.length===0){if(o)return n;throw Error(`No other columns to process`)}let l=[...r,...i.map(e=>`${e.purpose.trackingType}->${e.slug}`)];return await D(c,async o=>{let s=u(t.map(e=>e[o])),c=n.columnToPurposeName[o];if(c)e.info(h.magenta(`Column "${o}" is associated with purpose "${c.purpose}"`));else{let{purposeName:e}=await A.prompt([{name:`purposeName`,message:`Choose the purpose that column ${o} is associated with`,type:`list`,default:l.find(e=>e.startsWith(r[0])),choices:l}]),[t,n]=e.split(`->`);c={purpose:t,preference:n||null,valueMapping:{}}}await D(s,async t=>{if(c.valueMapping[t]!==void 0){e.info(h.magenta(`Value "${t}" is associated with purpose value "${c.valueMapping[t]}"`));return}if(c.preference===null){let{purposeValue:e}=await A.prompt([{name:`purposeValue`,message:`Choose the purpose value for value "${t}" associated with purpose "${c.purpose}"`,type:`confirm`,default:t!==`false`}]);c.valueMapping[t]=e}if(c.preference!==null){let n=i.find(e=>e.slug===c.preference);if(!n){e.error(h.red(`Preference topic "${c.preference}" not found`));return}let r=n.preferenceOptionValues.map(({slug:e})=>e);if(n.type===a.Boolean){let{preferenceValue:e}=await A.prompt([{name:`preferenceValue`,message:`Choose the preference value for "${n.slug}" value "${t}" associated with purpose "${c.purpose}"`,type:`confirm`,default:t!==`false`}]);c.valueMapping[t]=e;return}if(n.type===a.Select){let{preferenceValue:e}=await A.prompt([{name:`preferenceValue`,message:`Choose the preference value for "${n.slug}" value "${t}" associated with purpose "${c.purpose}"`,type:`list`,choices:r,default:r.find(e=>e===t)}]);c.valueMapping[t]=e;return}if(n.type===a.MultiSelect){await D(O(t),async e=>{if(c.valueMapping[e]!==void 0)return;let{preferenceValue:t}=await A.prompt([{name:`preferenceValue`,message:`Choose the preference value for "${n.slug}" value "${e}" associated with purpose "${c.purpose}"`,type:`list`,choices:r,default:r.find(t=>t===e)}]);c.valueMapping[e]=t});return}throw Error(`Unknown preference topic type: ${n.type}`)}}),n.columnToPurposeName[o]=c}),n}async function N(t,n){let i=s(u(t.map(e=>Object.keys(e)).flat()),[...n.identifierColumn?[n.identifierColumn]:[],...Object.keys(n.columnToPurposeName)]);if(!n.identifierColumn){let{identifierName:e}=await A.prompt([{name:`identifierName`,message:`Choose the column that will be used as the identifier to upload consent preferences by`,type:`list`,default:i.find(e=>e.toLowerCase().includes(`email`))||i[0],choices:i}]);n.identifierColumn=e}e.info(h.magenta(`Using identifier column "${n.identifierColumn}"`));let a=t.map((e,t)=>e[n.identifierColumn]?null:[t]).filter(e=>!!e).flat();if(a.length>0){let i=`The identifier column "${n.identifierColumn}" is missing a value for the following rows: ${a.join(`, `)}`;if(e.warn(h.yellow(i)),!await r({message:`Would you like to skip rows missing an identifier?`}))throw Error(i);let o=t.length;t=t.filter(e=>e[n.identifierColumn]),e.info(h.yellow(`Skipped ${o-t.length} rows missing an identifier`))}e.info(h.magenta(`The identifier column "${n.identifierColumn}" is present for all rows`));let o=c(t,n.identifierColumn),l=Object.entries(o).filter(([,e])=>e.length>1);if(l.length>0){let i=`The identifier column "${n.identifierColumn}" has duplicate values for the following rows: ${l.slice(0,10).map(([e,t])=>`${e} (${t.length})`).join(`
2
2
  `)}`;if(e.warn(h.yellow(i)),!await r({message:`Would you like to automatically take the latest update?`}))throw Error(i);t=Object.entries(o).map(([,e])=>e.sort((e,t)=>new Date(t[n.timestampColum]).getTime()-new Date(e[n.timestampColum]).getTime())[0]).filter(e=>e)}return{currentState:n,preferences:t}}async function P(t,n){let r=s(u(t.map(e=>Object.keys(e)).flat()),[...n.identifierColumn?[n.identifierColumn]:[],...Object.keys(n.columnToPurposeName)]);if(!n.timestampColum){let{timestampName:e}=await A.prompt([{name:`timestampName`,message:`Choose the column that will be used as the timestamp of last preference update`,type:`list`,default:r.find(e=>e.toLowerCase().includes(`date`))||r.find(e=>e.toLowerCase().includes(`time`))||r[0],choices:[...r,`[NONE]`]}]);n.timestampColum=e}if(e.info(h.magenta(`Using timestamp column "${n.timestampColum}"`)),n.timestampColum!==`[NONE]`){let r=t.map((e,t)=>e[n.timestampColum]?null:[t]).filter(e=>!!e).flat();if(r.length>0)throw Error(`The timestamp column "${n.timestampColum}" is missing a value for the following rows: ${r.join(`
3
3
  `)}`);e.info(h.magenta(`The timestamp column "${n.timestampColum}" is present for all row`))}return n}async function F({file:t,sombra:r,purposeSlugs:i,preferenceTopics:a,partitionKey:o,skipExistingRecordCheck:s,forceTriggerWorkflows:c},u){let d=new Date().getTime(),f=u.getValue(`fileMetadata`);e.info(h.magenta(`Reading in file: "${t}"`));let p=n(t,g.record(g.string,g.string)),m={columnToPurposeName:{},pendingSafeUpdates:{},pendingConflictUpdates:{},skippedUpdates:{},...f[t]||{},lastFetchedAt:new Date().toISOString()};m=await P(p,m),f[t]=m,await u.setValue(f,`fileMetadata`);let _=await N(p,m);m=_.currentState,p=_.preferences,f[t]=m,await u.setValue(f,`fileMetadata`),m=await M(p,m,{preferenceTopics:a,purposeSlugs:i,forceTriggerWorkflows:c}),f[t]=m,await u.setValue(f,`fileMetadata`);let v=p.map(e=>e[m.identifierColumn]),x=new k.SingleBar({},k.Presets.shades_classic);s||x.start(v.length,0);let S=s?[]:await T(r,{identifiers:v.map(e=>({value:e})),partitionKey:o,logger:e,onProgress:(e,t)=>x.update(e,{total:t})});x.stop();let C=l(S,`userId`);m.pendingConflictUpdates={},m.pendingSafeUpdates={},m.skippedUpdates={},p.forEach(e=>{let t=e[m.identifierColumn],n=w({row:e,columnToPurposeName:m.columnToPurposeName,preferenceTopics:a,purposeSlugs:i}),r=C[t];if(c&&!r)throw Error(`No existing consent record found for user with id: ${t}.
4
4
  When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`);if(r&&y({currentConsentRecord:r,pendingUpdates:n,preferenceTopics:a})&&!c){m.skippedUpdates[t]=e;return}if(r&&b({currentConsentRecord:r,pendingUpdates:n,preferenceTopics:a})){m.pendingConflictUpdates[t]={row:e,record:r};return}m.pendingSafeUpdates[t]=e}),f[t]=m,await u.setValue(f,`fileMetadata`);let E=new Date().getTime();e.info(h.green(`Successfully pre-processed file: "${t}" in ${(E-d)/1e3}s`))}async function I({auth:n,sombraAuth:r,receiptFilepath:i,file:a,partition:s,isSilent:c=!0,dryRun:l=!1,skipWorkflowTriggers:u=!1,skipConflictUpdates:f=!1,skipExistingRecordCheck:p=!1,attributes:m=[],transcendUrl:g,forceTriggerWorkflows:y=!1}){let b=t(m),T=new j(i,_,{fileMetadata:{},failingUpdates:{},pendingUpdates:{}}),D=T.getValue(`failingUpdates`),O=T.getValue(`pendingUpdates`),A=T.getValue(`fileMetadata`);e.info(h.magenta(`Restored cache, there are:
5
5
  ${Object.values(D).length} failing requests to be retried\n${Object.values(O).length} pending requests to be processed\nThe following files are stored in cache and will be used:\n${Object.keys(A).map(e=>e).join(`
6
6
  `)}\nThe following file will be processed: ${a}\n`));let M=v(g,n),[N,P,I]=await Promise.all([x(g,n,{logger:e,sombraApiKey:r,sombraUrl:process.env.SOMBRA_URL}),C(M,{logger:e}),S(M,{logger:e})]);await F({file:a,purposeSlugs:P.map(e=>e.trackingType),preferenceTopics:I,sombra:N,partitionKey:s,skipExistingRecordCheck:p,forceTriggerWorkflows:y},T);let L={};A=T.getValue(`fileMetadata`);let R=A[a];if(e.info(h.magenta(`Found ${Object.entries(R.pendingSafeUpdates).length} safe updates in ${a}`)),e.info(h.magenta(`Found ${Object.entries(R.pendingConflictUpdates).length} conflict updates in ${a}`)),e.info(h.magenta(`Found ${Object.entries(R.skippedUpdates).length} skipped updates in ${a}`)),Object.entries({...R.pendingSafeUpdates,...f?{}:d(R.pendingConflictUpdates,({row:e})=>e)}).forEach(([e,t])=>{let n=R.timestampColum===`[NONE]`?new Date:new Date(t[R.timestampColum]),r=w({row:t,columnToPurposeName:R.columnToPurposeName,preferenceTopics:I,purposeSlugs:P.map(e=>e.trackingType)});L[e]={userId:e,partition:s,timestamp:n.toISOString(),purposes:Object.entries(r).map(([e,t])=>({...t,purpose:e,workflowSettings:{attributes:b,isSilent:c,skipWorkflowTrigger:u,...y?{forceTriggerWorkflow:y}:{}}}))}}),await T.setValue(L,`pendingUpdates`),await T.setValue({},`failingUpdates`),l){e.info(h.green(`Dry run complete, exiting. ${Object.values(L).length} pending updates. Check file: ${i}`));return}e.info(h.magenta(`Uploading ${Object.values(L).length} preferences to partition: ${s}`));let z=new Date().getTime(),B=new k.SingleBar({},k.Presets.shades_classic),V=0,H=Object.entries(L),U=o(H,u?100:10);B.start(H.length,0),await E(U,async t=>{try{await N.put(`v1/preferences`,{json:{records:t.map(([,e])=>e),skipWorkflowTriggers:u}}).json()}catch(n){try{let t=JSON.parse(n?.response?.body||`{}`);t.error&&e.error(h.red(`Error: ${t.error}`))}catch{}e.error(h.red(`Failed to upload ${t.length} user preferences to partition ${s}: ${n?.response?.body||n?.message}`));let r=T.getValue(`failingUpdates`);t.forEach(([e,t])=>{r[e]={uploadedAt:new Date().toISOString(),update:t,error:n?.response?.body||n?.message||`Unknown error`}}),await T.setValue(r,`failingUpdates`)}V+=t.length,B.update(V)},{concurrency:40}),B.stop();let W=new Date().getTime()-z;e.info(h.green(`Successfully uploaded ${H.length} user preferences to partition ${s} in "${W/1e3}" seconds!`))}async function L({auth:t,partition:n,sombraAuth:r,transcendUrl:a,file:o=``,directory:s,dryRun:c,skipExistingRecordCheck:l,receiptFileDir:u,skipWorkflowTriggers:d,forceTriggerWorkflows:g,skipConflictUpdates:_,isSilent:v,attributes:y,concurrency:b}){s&&o&&(e.error(h.red(`Cannot provide both a directory and a file. Please provide only one.`)),this.process.exit(1)),!o&&!s&&(e.error(h.red(`A file or directory must be provided. Please provide one using --file=./preferences.csv or --directory=./preferences`)),this.process.exit(1)),i(this.process.exit);let x=[];if(s)try{let t=f(s).filter(e=>e.endsWith(`.csv`));t.length===0&&(e.error(h.red(`No CSV files found in directory: ${s}`)),this.process.exit(1)),x.push(...t.map(e=>m(s,e)))}catch(t){e.error(h.red(`Failed to read directory: ${s}`)),e.error(h.red(t.message)),this.process.exit(1)}else try{o.endsWith(`.csv`)||(e.error(h.red(`File must be a CSV file`)),this.process.exit(1)),x.push(o)}catch(t){e.error(h.red(`Failed to access file: ${o}`)),e.error(h.red(t.message)),this.process.exit(1)}e.info(h.green(`Processing ${x.length} consent preferences files for partition: ${n}`)),e.debug(`Files to process: ${x.join(`, `)}`),l&&e.info(h.bgYellow(`Skipping existing record check: ${l}`)),await E(x,async e=>{await I({receiptFilepath:m(u,`${p(e).replace(`.csv`,``)}-receipts.json`),auth:t,sombraAuth:r,file:e,partition:n,transcendUrl:a,skipConflictUpdates:_,skipWorkflowTriggers:d,skipExistingRecordCheck:l,isSilent:v,dryRun:c,attributes:O(y),forceTriggerWorkflows:g})},{concurrency:b})}export{L as uploadPreferences};
7
- //# sourceMappingURL=impl-DXHqqWJb.mjs.map
7
+ //# sourceMappingURL=impl-DiHeNVFr.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-DXHqqWJb.mjs","names":[],"sources":["../src/lib/preference-management/parsePreferenceAndPurposeValuesFromCsv.ts","../src/lib/preference-management/parsePreferenceIdentifiersFromCsv.ts","../src/lib/preference-management/parsePreferenceTimestampsFromCsv.ts","../src/lib/preference-management/parsePreferenceManagementCsv.ts","../src/lib/preference-management/uploadPreferenceManagementPreferencesInteractive.ts","../src/commands/consent/upload-preferences/impl.ts"],"sourcesContent":["import { PreferenceTopicType } from '@transcend-io/privacy-types';\nimport { FileMetadataState, type PreferenceTopic } from '@transcend-io/sdk';\nimport { mapSeries, splitCsvToList } from '@transcend-io/utils';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse out the purpose.enabled and preference values from a CSV file\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @param options - Options\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceAndPurposeValuesFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n {\n purposeSlugs,\n preferenceTopics,\n forceTriggerWorkflows,\n }: {\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const otherColumns = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...(currentState.timestampColum ? [currentState.timestampColum] : []),\n ]);\n if (otherColumns.length === 0) {\n if (forceTriggerWorkflows) {\n return currentState;\n }\n throw new Error('No other columns to process');\n }\n\n // The purpose and preferences to map to\n const purposeNames = [\n ...purposeSlugs,\n ...preferenceTopics.map((x) => `${x.purpose.trackingType}->${x.slug}`),\n ];\n\n // Ensure all columns are accounted for\n await mapSeries(otherColumns, async (col) => {\n // Determine the unique values to map in this column\n const uniqueValues = uniq(preferences.map((x) => x[col]));\n\n // Map the column to a purpose\n let purposeMapping = currentState.columnToPurposeName[col];\n if (purposeMapping) {\n logger.info(\n colors.magenta(`Column \"${col}\" is associated with purpose \"${purposeMapping.purpose}\"`),\n );\n } else {\n const { purposeName } = await inquirer.prompt<{\n /** purpose name */\n purposeName: string;\n }>([\n {\n name: 'purposeName',\n message: `Choose the purpose that column ${col} is associated with`,\n type: 'list',\n default: purposeNames.find((x) => x.startsWith(purposeSlugs[0])),\n choices: purposeNames,\n },\n ]);\n const [purposeSlug, preferenceSlug] = purposeName.split('->');\n purposeMapping = {\n purpose: purposeSlug,\n preference: preferenceSlug || null,\n valueMapping: {},\n };\n }\n\n // map each value to the purpose value\n await mapSeries(uniqueValues, async (value) => {\n if (purposeMapping.valueMapping[value] !== undefined) {\n logger.info(\n colors.magenta(\n `Value \"${value}\" is associated with purpose value \"${purposeMapping.valueMapping[value]}\"`,\n ),\n );\n return;\n }\n // if preference is null, this column is just for the purpose\n if (purposeMapping.preference === null) {\n const { purposeValue } = await inquirer.prompt<{\n /** purpose value */\n purposeValue: boolean;\n }>([\n {\n name: 'purposeValue',\n message: `Choose the purpose value for value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = purposeValue;\n }\n\n // if preference is not null, this column is for a specific preference\n if (purposeMapping.preference !== null) {\n const preferenceTopic = preferenceTopics.find((x) => x.slug === purposeMapping.preference);\n if (!preferenceTopic) {\n logger.error(colors.red(`Preference topic \"${purposeMapping.preference}\" not found`));\n return;\n }\n const preferenceOptions = preferenceTopic.preferenceOptionValues.map(({ slug }) => slug);\n\n if (preferenceTopic.type === PreferenceTopicType.Boolean) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n message:\n // eslint-disable-next-line max-len\n `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.Select) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === value),\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.MultiSelect) {\n const parsedValues = splitCsvToList(value);\n // need to do this serially\n await mapSeries(parsedValues, async (parsedValue) => {\n // if we already have a value, skip re-processing it again\n if (purposeMapping.valueMapping[parsedValue] !== undefined) {\n return;\n }\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${parsedValue}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === parsedValue),\n },\n ]);\n purposeMapping.valueMapping[parsedValue] = preferenceValue;\n });\n return;\n }\n\n throw new Error(`Unknown preference topic type: ${preferenceTopic.type}`);\n }\n });\n\n currentState.columnToPurposeName[col] = purposeMapping;\n });\n\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import { FileMetadataState } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, groupBy, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { inquirerConfirmBoolean } from '../helpers/index.js';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse identifiers from a CSV list of preferences\n *\n * Ensures that all rows have a valid identifier\n * and that all identifiers are unique.\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceIdentifiersFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<{\n /** The updated state */\n currentState: FileMetadataState;\n /** The updated preferences */\n preferences: Record<string, string>[];\n}> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const remainingColumnsForIdentifier = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the identifier column to work off of\n if (!currentState.identifierColumn) {\n const { identifierName } = await inquirer.prompt<{\n /** Identifier name */\n identifierName: string;\n }>([\n {\n name: 'identifierName',\n message:\n 'Choose the column that will be used as the identifier to upload consent preferences by',\n type: 'list',\n default:\n remainingColumnsForIdentifier.find((col) => col.toLowerCase().includes('email')) ||\n remainingColumnsForIdentifier[0],\n choices: remainingColumnsForIdentifier,\n },\n ]);\n currentState.identifierColumn = identifierName;\n }\n logger.info(colors.magenta(`Using identifier column \"${currentState.identifierColumn}\"`));\n\n // Validate that the identifier column is present for all rows and unique\n const identifierColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.identifierColumn!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (identifierColumnsMissing.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" is missing a value for the following rows: ${identifierColumnsMissing.join(', ')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to skip rows missing an identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to skip rows missing an identifier?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n\n // Filter out rows missing an identifier\n const previous = preferences.length;\n preferences = preferences.filter((pref) => pref[currentState.identifierColumn!]);\n logger.info(\n colors.yellow(`Skipped ${previous - preferences.length} rows missing an identifier`),\n );\n }\n logger.info(\n colors.magenta(\n `The identifier column \"${currentState.identifierColumn}\" is present for all rows`,\n ),\n );\n\n // Validate that all identifiers are unique\n const rowsByUserId = groupBy(preferences, currentState.identifierColumn);\n const duplicateIdentifiers = Object.entries(rowsByUserId).filter(([, rows]) => rows.length > 1);\n if (duplicateIdentifiers.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" has duplicate values for the following rows: ${duplicateIdentifiers\n .slice(0, 10)\n .map(([userId, rows]) => `${userId} (${rows.length})`)\n .join('\\n')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to take the most recent update\n // for each duplicate identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to automatically take the latest update?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n preferences = Object.entries(rowsByUserId)\n .map(([, rows]) => {\n const sorted = rows.sort(\n (a, b) =>\n new Date(b[currentState.timestampColum!]).getTime() -\n new Date(a[currentState.timestampColum!]).getTime(),\n );\n return sorted[0];\n })\n .filter((x) => x);\n }\n\n return { currentState, preferences };\n}\n/* eslint-enable no-param-reassign */\n","import { FileMetadataState } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\n\nexport const NONE_PREFERENCE_MAP = '[NONE]';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse timestamps from a CSV list of preferences\n *\n * When timestamp is requested, this script\n * ensures that all rows have a valid timestamp.\n *\n * Error is throw if timestamp is missing\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceTimestampsFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for timestamp\n const remainingColumnsForTimestamp = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the timestamp column to work off of\n if (!currentState.timestampColum) {\n const { timestampName } = await inquirer.prompt<{\n /** timestamp name */\n timestampName: string;\n }>([\n {\n name: 'timestampName',\n message: 'Choose the column that will be used as the timestamp of last preference update',\n type: 'list',\n default:\n remainingColumnsForTimestamp.find((col) => col.toLowerCase().includes('date')) ||\n remainingColumnsForTimestamp.find((col) => col.toLowerCase().includes('time')) ||\n remainingColumnsForTimestamp[0],\n choices: [...remainingColumnsForTimestamp, NONE_PREFERENCE_MAP],\n },\n ]);\n currentState.timestampColum = timestampName;\n }\n logger.info(colors.magenta(`Using timestamp column \"${currentState.timestampColum}\"`));\n\n // Validate that all rows have valid timestamp\n if (currentState.timestampColum !== NONE_PREFERENCE_MAP) {\n const timestampColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.timestampColum!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (timestampColumnsMissing.length > 0) {\n throw new Error(\n `The timestamp column \"${\n currentState.timestampColum\n }\" is missing a value for the following rows: ${timestampColumnsMissing.join('\\n')}`,\n );\n }\n logger.info(\n colors.magenta(\n `The timestamp column \"${currentState.timestampColum}\" is present for all row`,\n ),\n );\n }\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport {\n checkIfPendingPreferenceUpdatesAreNoOp,\n checkIfPendingPreferenceUpdatesCauseConflict,\n FileMetadataState,\n getPreferencesForIdentifiers,\n getPreferenceUpdatesFromRow,\n PreferenceState,\n type PreferenceTopic,\n} from '@transcend-io/sdk';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport type { Got } from 'got';\nimport * as t from 'io-ts';\nimport { keyBy } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { readCsv } from '../requests/index.js';\nimport { parsePreferenceAndPurposeValuesFromCsv } from './parsePreferenceAndPurposeValuesFromCsv.js';\nimport { parsePreferenceIdentifiersFromCsv } from './parsePreferenceIdentifiersFromCsv.js';\nimport { parsePreferenceTimestampsFromCsv } from './parsePreferenceTimestampsFromCsv.js';\n\n/**\n * Parse a file into the cache\n *\n *\n * @param options - Options\n * @param cache - The cache to store the parsed file in\n * @returns The cache with the parsed file\n */\nexport async function parsePreferenceManagementCsvWithCache(\n {\n file,\n sombra,\n purposeSlugs,\n preferenceTopics,\n partitionKey,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n }: {\n /** File to parse */\n file: string;\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Sombra got instance */\n sombra: Got;\n /** Partition key */\n partitionKey: string;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck: boolean;\n /** Whether to force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n cache: PersistedState<typeof PreferenceState>,\n): Promise<void> {\n // Start the timer\n const t0 = new Date().getTime();\n\n // Get the current metadata\n const fileMetadata = cache.getValue('fileMetadata');\n\n // Read in the file\n logger.info(colors.magenta(`Reading in file: \"${file}\"`));\n let preferences = readCsv(file, t.record(t.string, t.string));\n\n // start building the cache, can use previous cache as well\n let currentState: FileMetadataState = {\n columnToPurposeName: {},\n pendingSafeUpdates: {},\n pendingConflictUpdates: {},\n skippedUpdates: {},\n // Load in the last fetched time\n ...((fileMetadata[file] || {}) as Partial<FileMetadataState>),\n lastFetchedAt: new Date().toISOString(),\n };\n\n // Validate that all timestamps are present in the file\n currentState = await parsePreferenceTimestampsFromCsv(preferences, currentState);\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Validate that all identifiers are present and unique\n const result = await parsePreferenceIdentifiersFromCsv(preferences, currentState);\n currentState = result.currentState;\n preferences = result.preferences;\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Ensure all other columns are mapped to purpose and preference\n // slug values\n currentState = await parsePreferenceAndPurposeValuesFromCsv(preferences, currentState, {\n preferenceTopics,\n purposeSlugs,\n forceTriggerWorkflows,\n });\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Grab existing preference store records\n const identifiers = preferences.map((pref) => pref[currentState.identifierColumn!]);\n const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);\n if (!skipExistingRecordCheck) {\n progressBar.start(identifiers.length, 0);\n }\n const existingConsentRecords = skipExistingRecordCheck\n ? []\n : await getPreferencesForIdentifiers(sombra, {\n identifiers: identifiers.map((x) => ({ value: x })),\n partitionKey,\n logger,\n onProgress: (completed, total) => progressBar.update(completed, { total }),\n });\n progressBar.stop();\n const consentRecordByIdentifier = keyBy(existingConsentRecords, 'userId');\n\n // Clear out previous updates\n currentState.pendingConflictUpdates = {};\n currentState.pendingSafeUpdates = {};\n currentState.skippedUpdates = {};\n\n // Process each row\n preferences.forEach((pref) => {\n // Grab unique Id for the user\n const userId = pref[currentState.identifierColumn!];\n\n // determine updates for user\n const pendingUpdates = getPreferenceUpdatesFromRow({\n row: pref,\n columnToPurposeName: currentState.columnToPurposeName,\n preferenceTopics,\n purposeSlugs,\n });\n\n // Grab current state of the update\n const currentConsentRecord = consentRecordByIdentifier[userId];\n if (forceTriggerWorkflows && !currentConsentRecord) {\n throw new Error(\n `No existing consent record found for user with id: ${userId}.\n When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`,\n );\n }\n // Check if the update can be skipped\n // this is the case if a record exists, and the purpose\n // and preference values are all in sync\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesAreNoOp({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n }) &&\n !forceTriggerWorkflows\n ) {\n currentState.skippedUpdates[userId] = pref;\n return;\n }\n\n // Determine if there are any conflicts\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesCauseConflict({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n })\n ) {\n currentState.pendingConflictUpdates[userId] = {\n row: pref,\n record: currentConsentRecord,\n };\n return;\n }\n\n // Add to pending updates\n currentState.pendingSafeUpdates[userId] = pref;\n });\n\n // Read in the file\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n const t1 = new Date().getTime();\n logger.info(colors.green(`Successfully pre-processed file: \"${file}\" in ${(t1 - t0) / 1000}s`));\n}\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport { PreferenceUpdateItem } from '@transcend-io/privacy-types';\nimport {\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllPurposes,\n fetchAllPreferenceTopics,\n getPreferenceUpdatesFromRow,\n PreferenceState,\n} from '@transcend-io/sdk';\nimport { apply } from '@transcend-io/type-utils';\nimport { map } from '@transcend-io/utils';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport { chunk } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { parseAttributesFromString } from '../requests/index.js';\nimport { parsePreferenceManagementCsvWithCache } from './parsePreferenceManagementCsv.js';\nimport { NONE_PREFERENCE_MAP } from './parsePreferenceTimestampsFromCsv.js';\n\n/**\n * Upload a set of consent preferences\n *\n * @param options - Options\n */\nexport async function uploadPreferenceManagementPreferencesInteractive({\n auth,\n sombraAuth,\n receiptFilepath,\n file,\n partition,\n isSilent = true,\n dryRun = false,\n skipWorkflowTriggers = false,\n skipConflictUpdates = false,\n skipExistingRecordCheck = false,\n attributes = [],\n transcendUrl,\n forceTriggerWorkflows = false,\n}: {\n /** The Transcend API key */\n auth: string;\n /** Sombra API key authentication */\n sombraAuth?: string;\n /** Partition key */\n partition: string;\n /** File where to store receipt and continue from where left off */\n receiptFilepath: string;\n /** The file to process */\n file: string;\n /** API URL for Transcend backend */\n transcendUrl: string;\n /** Whether to do a dry run */\n dryRun?: boolean;\n /** Whether to upload as isSilent */\n isSilent?: boolean;\n /** Attributes string pre-parse. In format Key:Value */\n attributes?: string[];\n /** Skip workflow triggers */\n skipWorkflowTriggers?: boolean;\n /**\n * When true, only update preferences that do not conflict with existing\n * preferences. When false, update all preferences in CSV based on timestamp.\n */\n skipConflictUpdates?: boolean;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck?: boolean;\n /** Whether to force trigger workflows */\n forceTriggerWorkflows?: boolean;\n}): Promise<void> {\n // Parse out the extra attributes to apply to all requests uploaded\n const parsedAttributes = parseAttributesFromString(attributes);\n\n // Create a new state file to store the requests from this run\n const preferenceState = new PersistedState(receiptFilepath, PreferenceState, {\n fileMetadata: {},\n failingUpdates: {},\n pendingUpdates: {},\n });\n const failingRequests = preferenceState.getValue('failingUpdates');\n const pendingRequests = preferenceState.getValue('pendingUpdates');\n let fileMetadata = preferenceState.getValue('fileMetadata');\n\n logger.info(\n colors.magenta(\n 'Restored cache, there are: \\n' +\n `${Object.values(failingRequests).length} failing requests to be retried\\n` +\n `${Object.values(pendingRequests).length} pending requests to be processed\\n` +\n `The following files are stored in cache and will be used:\\n${Object.keys(fileMetadata)\n .map((x) => x)\n .join('\\n')}\\n` +\n `The following file will be processed: ${file}\\n`,\n ),\n );\n\n // Create GraphQL client to connect to Transcend backend\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const [sombra, purposes, preferenceTopics] = await Promise.all([\n // Create sombra instance to communicate with\n createSombraGotInstance(transcendUrl, auth, {\n logger,\n sombraApiKey: sombraAuth,\n sombraUrl: process.env.SOMBRA_URL,\n }),\n // get all purposes and topics\n fetchAllPurposes(client, { logger }),\n fetchAllPreferenceTopics(client, { logger }),\n ]);\n\n // Process the file\n await parsePreferenceManagementCsvWithCache(\n {\n file,\n purposeSlugs: purposes.map((x) => x.trackingType),\n preferenceTopics,\n sombra,\n partitionKey: partition,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n },\n preferenceState,\n );\n\n // Construct the pending updates\n const pendingUpdates: Record<string, PreferenceUpdateItem> = {};\n fileMetadata = preferenceState.getValue('fileMetadata');\n const metadata = fileMetadata[file];\n\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.pendingSafeUpdates).length} safe updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.pendingConflictUpdates).length} conflict updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.skippedUpdates).length} skipped updates in ${file}`,\n ),\n );\n\n // Update either safe updates only or safe + conflict\n Object.entries({\n ...metadata.pendingSafeUpdates,\n ...(skipConflictUpdates ? {} : apply(metadata.pendingConflictUpdates, ({ row }) => row)),\n }).forEach(([userId, update]) => {\n // Determine timestamp\n const timestamp =\n metadata.timestampColum === NONE_PREFERENCE_MAP\n ? new Date()\n : new Date(update[metadata.timestampColum!]);\n\n // Determine updates\n const updates = getPreferenceUpdatesFromRow({\n row: update,\n columnToPurposeName: metadata.columnToPurposeName,\n preferenceTopics,\n purposeSlugs: purposes.map((x) => x.trackingType),\n });\n pendingUpdates[userId] = {\n userId,\n partition,\n timestamp: timestamp.toISOString(),\n purposes: Object.entries(updates).map(([purpose, value]) => ({\n ...value,\n purpose,\n workflowSettings: {\n attributes: parsedAttributes,\n isSilent,\n skipWorkflowTrigger: skipWorkflowTriggers,\n ...(forceTriggerWorkflows ? { forceTriggerWorkflow: forceTriggerWorkflows } : {}),\n },\n })),\n };\n });\n await preferenceState.setValue(pendingUpdates, 'pendingUpdates');\n await preferenceState.setValue({}, 'failingUpdates');\n\n // Exist early if dry run\n if (dryRun) {\n logger.info(\n colors.green(\n `Dry run complete, exiting. ${\n Object.values(pendingUpdates).length\n } pending updates. Check file: ${receiptFilepath}`,\n ),\n );\n return;\n }\n\n logger.info(\n colors.magenta(\n `Uploading ${Object.values(pendingUpdates).length} preferences to partition: ${partition}`,\n ),\n );\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);\n\n // Build a GraphQL client\n let total = 0;\n const updatesToRun = Object.entries(pendingUpdates);\n const chunkedUpdates = chunk(updatesToRun, skipWorkflowTriggers ? 100 : 10);\n progressBar.start(updatesToRun.length, 0);\n await map(\n chunkedUpdates,\n async (currentChunk) => {\n // Make the request\n try {\n await sombra\n .put('v1/preferences', {\n json: {\n records: currentChunk.map(([, update]) => update),\n skipWorkflowTriggers,\n },\n })\n .json();\n } catch (err) {\n try {\n const parsed = JSON.parse(err?.response?.body || '{}');\n if (parsed.error) {\n logger.error(colors.red(`Error: ${parsed.error}`));\n }\n } catch {\n // continue\n }\n logger.error(\n colors.red(\n `Failed to upload ${currentChunk.length} user preferences to partition ${partition}: ${\n err?.response?.body || err?.message\n }`,\n ),\n );\n const failingUpdates = preferenceState.getValue('failingUpdates');\n currentChunk.forEach(([userId, update]) => {\n failingUpdates[userId] = {\n uploadedAt: new Date().toISOString(),\n update,\n error: err?.response?.body || err?.message || 'Unknown error',\n };\n });\n await preferenceState.setValue(failingUpdates, 'failingUpdates');\n }\n\n total += currentChunk.length;\n progressBar.update(total);\n },\n {\n concurrency: 40,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n logger.info(\n colors.green(\n `Successfully uploaded ${\n updatesToRun.length\n } user preferences to partition ${partition} in \"${totalTime / 1000}\" seconds!`,\n ),\n );\n}\n","import { readdirSync } from 'node:fs';\nimport { basename, join } from 'node:path';\n\nimport { map, splitCsvToList } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { uploadPreferenceManagementPreferencesInteractive } from '../../../lib/preference-management/index.js';\nimport { logger } from '../../../logger.js';\n\nexport interface UploadPreferencesCommandFlags {\n auth: string;\n partition: string;\n sombraAuth?: string;\n transcendUrl: string;\n file?: string;\n directory?: string;\n dryRun: boolean;\n skipExistingRecordCheck: boolean;\n receiptFileDir: string;\n skipWorkflowTriggers: boolean;\n forceTriggerWorkflows: boolean;\n skipConflictUpdates: boolean;\n isSilent: boolean;\n attributes: string;\n receiptFilepath: string;\n concurrency: number;\n}\n\nexport async function uploadPreferences(\n this: LocalContext,\n {\n auth,\n partition,\n sombraAuth,\n transcendUrl,\n file = '',\n directory,\n dryRun,\n skipExistingRecordCheck,\n receiptFileDir,\n skipWorkflowTriggers,\n forceTriggerWorkflows,\n skipConflictUpdates,\n isSilent,\n attributes,\n concurrency,\n }: UploadPreferencesCommandFlags,\n): Promise<void> {\n if (!!directory && !!file) {\n logger.error(\n colors.red('Cannot provide both a directory and a file. Please provide only one.'),\n );\n this.process.exit(1);\n }\n\n if (!file && !directory) {\n logger.error(\n colors.red(\n 'A file or directory must be provided. Please provide one using --file=./preferences.csv or --directory=./preferences',\n ),\n );\n this.process.exit(1);\n }\n\n doneInputValidation(this.process.exit);\n\n const files: string[] = [];\n\n if (directory) {\n try {\n const filesInDirectory = readdirSync(directory);\n const csvFiles = filesInDirectory.filter((file) => file.endsWith('.csv'));\n\n if (csvFiles.length === 0) {\n logger.error(colors.red(`No CSV files found in directory: ${directory}`));\n this.process.exit(1);\n }\n\n // Add full paths for each CSV file\n files.push(...csvFiles.map((file) => join(directory, file)));\n } catch (err) {\n logger.error(colors.red(`Failed to read directory: ${directory}`));\n logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n } else {\n try {\n // Verify file exists and is a CSV\n if (!file.endsWith('.csv')) {\n logger.error(colors.red('File must be a CSV file'));\n this.process.exit(1);\n }\n files.push(file);\n } catch (err) {\n logger.error(colors.red(`Failed to access file: ${file}`));\n logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n }\n\n logger.info(\n colors.green(\n `Processing ${files.length} consent preferences files for partition: ${partition}`,\n ),\n );\n logger.debug(`Files to process: ${files.join(', ')}`);\n\n if (skipExistingRecordCheck) {\n logger.info(colors.bgYellow(`Skipping existing record check: ${skipExistingRecordCheck}`));\n }\n\n await map(\n files,\n async (filePath) => {\n const fileName = basename(filePath).replace('.csv', '');\n await uploadPreferenceManagementPreferencesInteractive({\n receiptFilepath: join(receiptFileDir, `${fileName}-receipts.json`),\n auth,\n sombraAuth,\n file: filePath,\n partition,\n transcendUrl,\n skipConflictUpdates,\n skipWorkflowTriggers,\n skipExistingRecordCheck,\n isSilent,\n dryRun,\n attributes: splitCsvToList(attributes),\n forceTriggerWorkflows,\n });\n },\n { concurrency },\n );\n}\n"],"mappings":"wkCAmBA,eAAsB,EACpB,EACA,EACA,CACE,eACA,mBACA,yBAS0B,CAK5B,IAAM,EAAe,EAHD,EAAK,EAAY,IAAK,GAAM,OAAO,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC,CAG1B,CAC3C,GAAI,EAAa,iBAAmB,CAAC,EAAa,iBAAiB,CAAG,EAAE,CACxE,GAAI,EAAa,eAAiB,CAAC,EAAa,eAAe,CAAG,EAAE,CACrE,CAAC,CACF,GAAI,EAAa,SAAW,EAAG,CAC7B,GAAI,EACF,OAAO,EAET,MAAU,MAAM,8BAA8B,CAIhD,IAAM,EAAe,CACnB,GAAG,EACH,GAAG,EAAiB,IAAK,GAAM,GAAG,EAAE,QAAQ,aAAa,IAAI,EAAE,OAAO,CACvE,CA0ID,OAvIA,MAAM,EAAU,EAAc,KAAO,IAAQ,CAE3C,IAAM,EAAe,EAAK,EAAY,IAAK,GAAM,EAAE,GAAK,CAAC,CAGrD,EAAiB,EAAa,oBAAoB,GACtD,GAAI,EACF,EAAO,KACL,EAAO,QAAQ,WAAW,EAAI,gCAAgC,EAAe,QAAQ,GAAG,CACzF,KACI,CACL,GAAM,CAAE,eAAgB,MAAM,EAAS,OAGpC,CACD,CACE,KAAM,cACN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mCAAmC,IAA0B,CAAC,CAG5F,MAAM,EACJ,EACA,KAAO,IAAa,CAElB,MAAM,EAAiD,CACrD,gBAAiB,EAAK,EAAgB,GAFvB,EAAS,EAAS,CAAC,QAAQ,OAAQ,GAAG,CAEH,gBAAgB,CAClE,OACA,aACA,KAAM,EACN,YACA,eACA,sBACA,uBACA,0BACA,WACA,SACA,WAAY,EAAe,EAAW,CACtC,wBACD,CAAC,EAEJ,CAAE,cAAa,CAChB"}
1
+ {"version":3,"file":"impl-DiHeNVFr.mjs","names":[],"sources":["../src/lib/preference-management/parsePreferenceAndPurposeValuesFromCsv.ts","../src/lib/preference-management/parsePreferenceIdentifiersFromCsv.ts","../src/lib/preference-management/parsePreferenceTimestampsFromCsv.ts","../src/lib/preference-management/parsePreferenceManagementCsv.ts","../src/lib/preference-management/uploadPreferenceManagementPreferencesInteractive.ts","../src/commands/consent/upload-preferences/impl.ts"],"sourcesContent":["import { PreferenceTopicType } from '@transcend-io/privacy-types';\nimport { FileMetadataState, type PreferenceTopic } from '@transcend-io/sdk';\nimport { mapSeries, splitCsvToList } from '@transcend-io/utils';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse out the purpose.enabled and preference values from a CSV file\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @param options - Options\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceAndPurposeValuesFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n {\n purposeSlugs,\n preferenceTopics,\n forceTriggerWorkflows,\n }: {\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const otherColumns = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...(currentState.timestampColum ? [currentState.timestampColum] : []),\n ]);\n if (otherColumns.length === 0) {\n if (forceTriggerWorkflows) {\n return currentState;\n }\n throw new Error('No other columns to process');\n }\n\n // The purpose and preferences to map to\n const purposeNames = [\n ...purposeSlugs,\n ...preferenceTopics.map((x) => `${x.purpose.trackingType}->${x.slug}`),\n ];\n\n // Ensure all columns are accounted for\n await mapSeries(otherColumns, async (col) => {\n // Determine the unique values to map in this column\n const uniqueValues = uniq(preferences.map((x) => x[col]));\n\n // Map the column to a purpose\n let purposeMapping = currentState.columnToPurposeName[col];\n if (purposeMapping) {\n logger.info(\n colors.magenta(`Column \"${col}\" is associated with purpose \"${purposeMapping.purpose}\"`),\n );\n } else {\n const { purposeName } = await inquirer.prompt<{\n /** purpose name */\n purposeName: string;\n }>([\n {\n name: 'purposeName',\n message: `Choose the purpose that column ${col} is associated with`,\n type: 'list',\n default: purposeNames.find((x) => x.startsWith(purposeSlugs[0])),\n choices: purposeNames,\n },\n ]);\n const [purposeSlug, preferenceSlug] = purposeName.split('->');\n purposeMapping = {\n purpose: purposeSlug,\n preference: preferenceSlug || null,\n valueMapping: {},\n };\n }\n\n // map each value to the purpose value\n await mapSeries(uniqueValues, async (value) => {\n if (purposeMapping.valueMapping[value] !== undefined) {\n logger.info(\n colors.magenta(\n `Value \"${value}\" is associated with purpose value \"${purposeMapping.valueMapping[value]}\"`,\n ),\n );\n return;\n }\n // if preference is null, this column is just for the purpose\n if (purposeMapping.preference === null) {\n const { purposeValue } = await inquirer.prompt<{\n /** purpose value */\n purposeValue: boolean;\n }>([\n {\n name: 'purposeValue',\n message: `Choose the purpose value for value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = purposeValue;\n }\n\n // if preference is not null, this column is for a specific preference\n if (purposeMapping.preference !== null) {\n const preferenceTopic = preferenceTopics.find((x) => x.slug === purposeMapping.preference);\n if (!preferenceTopic) {\n logger.error(colors.red(`Preference topic \"${purposeMapping.preference}\" not found`));\n return;\n }\n const preferenceOptions = preferenceTopic.preferenceOptionValues.map(({ slug }) => slug);\n\n if (preferenceTopic.type === PreferenceTopicType.Boolean) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n message:\n // eslint-disable-next-line max-len\n `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.Select) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === value),\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.MultiSelect) {\n const parsedValues = splitCsvToList(value);\n // need to do this serially\n await mapSeries(parsedValues, async (parsedValue) => {\n // if we already have a value, skip re-processing it again\n if (purposeMapping.valueMapping[parsedValue] !== undefined) {\n return;\n }\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${parsedValue}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === parsedValue),\n },\n ]);\n purposeMapping.valueMapping[parsedValue] = preferenceValue;\n });\n return;\n }\n\n throw new Error(`Unknown preference topic type: ${preferenceTopic.type}`);\n }\n });\n\n currentState.columnToPurposeName[col] = purposeMapping;\n });\n\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import { FileMetadataState } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, groupBy, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { inquirerConfirmBoolean } from '../helpers/index.js';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse identifiers from a CSV list of preferences\n *\n * Ensures that all rows have a valid identifier\n * and that all identifiers are unique.\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceIdentifiersFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<{\n /** The updated state */\n currentState: FileMetadataState;\n /** The updated preferences */\n preferences: Record<string, string>[];\n}> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const remainingColumnsForIdentifier = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the identifier column to work off of\n if (!currentState.identifierColumn) {\n const { identifierName } = await inquirer.prompt<{\n /** Identifier name */\n identifierName: string;\n }>([\n {\n name: 'identifierName',\n message:\n 'Choose the column that will be used as the identifier to upload consent preferences by',\n type: 'list',\n default:\n remainingColumnsForIdentifier.find((col) => col.toLowerCase().includes('email')) ||\n remainingColumnsForIdentifier[0],\n choices: remainingColumnsForIdentifier,\n },\n ]);\n currentState.identifierColumn = identifierName;\n }\n logger.info(colors.magenta(`Using identifier column \"${currentState.identifierColumn}\"`));\n\n // Validate that the identifier column is present for all rows and unique\n const identifierColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.identifierColumn!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (identifierColumnsMissing.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" is missing a value for the following rows: ${identifierColumnsMissing.join(', ')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to skip rows missing an identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to skip rows missing an identifier?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n\n // Filter out rows missing an identifier\n const previous = preferences.length;\n preferences = preferences.filter((pref) => pref[currentState.identifierColumn!]);\n logger.info(\n colors.yellow(`Skipped ${previous - preferences.length} rows missing an identifier`),\n );\n }\n logger.info(\n colors.magenta(\n `The identifier column \"${currentState.identifierColumn}\" is present for all rows`,\n ),\n );\n\n // Validate that all identifiers are unique\n const rowsByUserId = groupBy(preferences, currentState.identifierColumn);\n const duplicateIdentifiers = Object.entries(rowsByUserId).filter(([, rows]) => rows.length > 1);\n if (duplicateIdentifiers.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" has duplicate values for the following rows: ${duplicateIdentifiers\n .slice(0, 10)\n .map(([userId, rows]) => `${userId} (${rows.length})`)\n .join('\\n')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to take the most recent update\n // for each duplicate identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to automatically take the latest update?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n preferences = Object.entries(rowsByUserId)\n .map(([, rows]) => {\n const sorted = rows.sort(\n (a, b) =>\n new Date(b[currentState.timestampColum!]).getTime() -\n new Date(a[currentState.timestampColum!]).getTime(),\n );\n return sorted[0];\n })\n .filter((x) => x);\n }\n\n return { currentState, preferences };\n}\n/* eslint-enable no-param-reassign */\n","import { FileMetadataState } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\n\nexport const NONE_PREFERENCE_MAP = '[NONE]';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse timestamps from a CSV list of preferences\n *\n * When timestamp is requested, this script\n * ensures that all rows have a valid timestamp.\n *\n * Error is throw if timestamp is missing\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceTimestampsFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for timestamp\n const remainingColumnsForTimestamp = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the timestamp column to work off of\n if (!currentState.timestampColum) {\n const { timestampName } = await inquirer.prompt<{\n /** timestamp name */\n timestampName: string;\n }>([\n {\n name: 'timestampName',\n message: 'Choose the column that will be used as the timestamp of last preference update',\n type: 'list',\n default:\n remainingColumnsForTimestamp.find((col) => col.toLowerCase().includes('date')) ||\n remainingColumnsForTimestamp.find((col) => col.toLowerCase().includes('time')) ||\n remainingColumnsForTimestamp[0],\n choices: [...remainingColumnsForTimestamp, NONE_PREFERENCE_MAP],\n },\n ]);\n currentState.timestampColum = timestampName;\n }\n logger.info(colors.magenta(`Using timestamp column \"${currentState.timestampColum}\"`));\n\n // Validate that all rows have valid timestamp\n if (currentState.timestampColum !== NONE_PREFERENCE_MAP) {\n const timestampColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.timestampColum!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (timestampColumnsMissing.length > 0) {\n throw new Error(\n `The timestamp column \"${\n currentState.timestampColum\n }\" is missing a value for the following rows: ${timestampColumnsMissing.join('\\n')}`,\n );\n }\n logger.info(\n colors.magenta(\n `The timestamp column \"${currentState.timestampColum}\" is present for all row`,\n ),\n );\n }\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport {\n checkIfPendingPreferenceUpdatesAreNoOp,\n checkIfPendingPreferenceUpdatesCauseConflict,\n FileMetadataState,\n getPreferencesForIdentifiers,\n getPreferenceUpdatesFromRow,\n PreferenceState,\n type PreferenceTopic,\n} from '@transcend-io/sdk';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport type { Got } from 'got';\nimport * as t from 'io-ts';\nimport { keyBy } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { readCsv } from '../requests/index.js';\nimport { parsePreferenceAndPurposeValuesFromCsv } from './parsePreferenceAndPurposeValuesFromCsv.js';\nimport { parsePreferenceIdentifiersFromCsv } from './parsePreferenceIdentifiersFromCsv.js';\nimport { parsePreferenceTimestampsFromCsv } from './parsePreferenceTimestampsFromCsv.js';\n\n/**\n * Parse a file into the cache\n *\n *\n * @param options - Options\n * @param cache - The cache to store the parsed file in\n * @returns The cache with the parsed file\n */\nexport async function parsePreferenceManagementCsvWithCache(\n {\n file,\n sombra,\n purposeSlugs,\n preferenceTopics,\n partitionKey,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n }: {\n /** File to parse */\n file: string;\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Sombra got instance */\n sombra: Got;\n /** Partition key */\n partitionKey: string;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck: boolean;\n /** Whether to force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n cache: PersistedState<typeof PreferenceState>,\n): Promise<void> {\n // Start the timer\n const t0 = new Date().getTime();\n\n // Get the current metadata\n const fileMetadata = cache.getValue('fileMetadata');\n\n // Read in the file\n logger.info(colors.magenta(`Reading in file: \"${file}\"`));\n let preferences = readCsv(file, t.record(t.string, t.string));\n\n // start building the cache, can use previous cache as well\n let currentState: FileMetadataState = {\n columnToPurposeName: {},\n pendingSafeUpdates: {},\n pendingConflictUpdates: {},\n skippedUpdates: {},\n // Load in the last fetched time\n ...((fileMetadata[file] || {}) as Partial<FileMetadataState>),\n lastFetchedAt: new Date().toISOString(),\n };\n\n // Validate that all timestamps are present in the file\n currentState = await parsePreferenceTimestampsFromCsv(preferences, currentState);\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Validate that all identifiers are present and unique\n const result = await parsePreferenceIdentifiersFromCsv(preferences, currentState);\n currentState = result.currentState;\n preferences = result.preferences;\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Ensure all other columns are mapped to purpose and preference\n // slug values\n currentState = await parsePreferenceAndPurposeValuesFromCsv(preferences, currentState, {\n preferenceTopics,\n purposeSlugs,\n forceTriggerWorkflows,\n });\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Grab existing preference store records\n const identifiers = preferences.map((pref) => pref[currentState.identifierColumn!]);\n const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);\n if (!skipExistingRecordCheck) {\n progressBar.start(identifiers.length, 0);\n }\n const existingConsentRecords = skipExistingRecordCheck\n ? []\n : await getPreferencesForIdentifiers(sombra, {\n identifiers: identifiers.map((x) => ({ value: x })),\n partitionKey,\n logger,\n onProgress: (completed, total) => progressBar.update(completed, { total }),\n });\n progressBar.stop();\n const consentRecordByIdentifier = keyBy(existingConsentRecords, 'userId');\n\n // Clear out previous updates\n currentState.pendingConflictUpdates = {};\n currentState.pendingSafeUpdates = {};\n currentState.skippedUpdates = {};\n\n // Process each row\n preferences.forEach((pref) => {\n // Grab unique Id for the user\n const userId = pref[currentState.identifierColumn!];\n\n // determine updates for user\n const pendingUpdates = getPreferenceUpdatesFromRow({\n row: pref,\n columnToPurposeName: currentState.columnToPurposeName,\n preferenceTopics,\n purposeSlugs,\n });\n\n // Grab current state of the update\n const currentConsentRecord = consentRecordByIdentifier[userId];\n if (forceTriggerWorkflows && !currentConsentRecord) {\n throw new Error(\n `No existing consent record found for user with id: ${userId}.\n When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`,\n );\n }\n // Check if the update can be skipped\n // this is the case if a record exists, and the purpose\n // and preference values are all in sync\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesAreNoOp({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n }) &&\n !forceTriggerWorkflows\n ) {\n currentState.skippedUpdates[userId] = pref;\n return;\n }\n\n // Determine if there are any conflicts\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesCauseConflict({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n })\n ) {\n currentState.pendingConflictUpdates[userId] = {\n row: pref,\n record: currentConsentRecord,\n };\n return;\n }\n\n // Add to pending updates\n currentState.pendingSafeUpdates[userId] = pref;\n });\n\n // Read in the file\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n const t1 = new Date().getTime();\n logger.info(colors.green(`Successfully pre-processed file: \"${file}\" in ${(t1 - t0) / 1000}s`));\n}\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport { PreferenceUpdateItem } from '@transcend-io/privacy-types';\nimport {\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllPurposes,\n fetchAllPreferenceTopics,\n getPreferenceUpdatesFromRow,\n PreferenceState,\n} from '@transcend-io/sdk';\nimport { apply } from '@transcend-io/type-utils';\nimport { map } from '@transcend-io/utils';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport { chunk } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { parseAttributesFromString } from '../requests/index.js';\nimport { parsePreferenceManagementCsvWithCache } from './parsePreferenceManagementCsv.js';\nimport { NONE_PREFERENCE_MAP } from './parsePreferenceTimestampsFromCsv.js';\n\n/**\n * Upload a set of consent preferences\n *\n * @param options - Options\n */\nexport async function uploadPreferenceManagementPreferencesInteractive({\n auth,\n sombraAuth,\n receiptFilepath,\n file,\n partition,\n isSilent = true,\n dryRun = false,\n skipWorkflowTriggers = false,\n skipConflictUpdates = false,\n skipExistingRecordCheck = false,\n attributes = [],\n transcendUrl,\n forceTriggerWorkflows = false,\n}: {\n /** The Transcend API key */\n auth: string;\n /** Sombra API key authentication */\n sombraAuth?: string;\n /** Partition key */\n partition: string;\n /** File where to store receipt and continue from where left off */\n receiptFilepath: string;\n /** The file to process */\n file: string;\n /** API URL for Transcend backend */\n transcendUrl: string;\n /** Whether to do a dry run */\n dryRun?: boolean;\n /** Whether to upload as isSilent */\n isSilent?: boolean;\n /** Attributes string pre-parse. In format Key:Value */\n attributes?: string[];\n /** Skip workflow triggers */\n skipWorkflowTriggers?: boolean;\n /**\n * When true, only update preferences that do not conflict with existing\n * preferences. When false, update all preferences in CSV based on timestamp.\n */\n skipConflictUpdates?: boolean;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck?: boolean;\n /** Whether to force trigger workflows */\n forceTriggerWorkflows?: boolean;\n}): Promise<void> {\n // Parse out the extra attributes to apply to all requests uploaded\n const parsedAttributes = parseAttributesFromString(attributes);\n\n // Create a new state file to store the requests from this run\n const preferenceState = new PersistedState(receiptFilepath, PreferenceState, {\n fileMetadata: {},\n failingUpdates: {},\n pendingUpdates: {},\n });\n const failingRequests = preferenceState.getValue('failingUpdates');\n const pendingRequests = preferenceState.getValue('pendingUpdates');\n let fileMetadata = preferenceState.getValue('fileMetadata');\n\n logger.info(\n colors.magenta(\n 'Restored cache, there are: \\n' +\n `${Object.values(failingRequests).length} failing requests to be retried\\n` +\n `${Object.values(pendingRequests).length} pending requests to be processed\\n` +\n `The following files are stored in cache and will be used:\\n${Object.keys(fileMetadata)\n .map((x) => x)\n .join('\\n')}\\n` +\n `The following file will be processed: ${file}\\n`,\n ),\n );\n\n // Create GraphQL client to connect to Transcend backend\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const [sombra, purposes, preferenceTopics] = await Promise.all([\n // Create sombra instance to communicate with\n createSombraGotInstance(transcendUrl, auth, {\n logger,\n sombraApiKey: sombraAuth,\n sombraUrl: process.env.SOMBRA_URL,\n }),\n // get all purposes and topics\n fetchAllPurposes(client, { logger }),\n fetchAllPreferenceTopics(client, { logger }),\n ]);\n\n // Process the file\n await parsePreferenceManagementCsvWithCache(\n {\n file,\n purposeSlugs: purposes.map((x) => x.trackingType),\n preferenceTopics,\n sombra,\n partitionKey: partition,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n },\n preferenceState,\n );\n\n // Construct the pending updates\n const pendingUpdates: Record<string, PreferenceUpdateItem> = {};\n fileMetadata = preferenceState.getValue('fileMetadata');\n const metadata = fileMetadata[file];\n\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.pendingSafeUpdates).length} safe updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.pendingConflictUpdates).length} conflict updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.skippedUpdates).length} skipped updates in ${file}`,\n ),\n );\n\n // Update either safe updates only or safe + conflict\n Object.entries({\n ...metadata.pendingSafeUpdates,\n ...(skipConflictUpdates ? {} : apply(metadata.pendingConflictUpdates, ({ row }) => row)),\n }).forEach(([userId, update]) => {\n // Determine timestamp\n const timestamp =\n metadata.timestampColum === NONE_PREFERENCE_MAP\n ? new Date()\n : new Date(update[metadata.timestampColum!]);\n\n // Determine updates\n const updates = getPreferenceUpdatesFromRow({\n row: update,\n columnToPurposeName: metadata.columnToPurposeName,\n preferenceTopics,\n purposeSlugs: purposes.map((x) => x.trackingType),\n });\n pendingUpdates[userId] = {\n userId,\n partition,\n timestamp: timestamp.toISOString(),\n purposes: Object.entries(updates).map(([purpose, value]) => ({\n ...value,\n purpose,\n workflowSettings: {\n attributes: parsedAttributes,\n isSilent,\n skipWorkflowTrigger: skipWorkflowTriggers,\n ...(forceTriggerWorkflows ? { forceTriggerWorkflow: forceTriggerWorkflows } : {}),\n },\n })),\n };\n });\n await preferenceState.setValue(pendingUpdates, 'pendingUpdates');\n await preferenceState.setValue({}, 'failingUpdates');\n\n // Exist early if dry run\n if (dryRun) {\n logger.info(\n colors.green(\n `Dry run complete, exiting. ${\n Object.values(pendingUpdates).length\n } pending updates. Check file: ${receiptFilepath}`,\n ),\n );\n return;\n }\n\n logger.info(\n colors.magenta(\n `Uploading ${Object.values(pendingUpdates).length} preferences to partition: ${partition}`,\n ),\n );\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);\n\n // Build a GraphQL client\n let total = 0;\n const updatesToRun = Object.entries(pendingUpdates);\n const chunkedUpdates = chunk(updatesToRun, skipWorkflowTriggers ? 100 : 10);\n progressBar.start(updatesToRun.length, 0);\n await map(\n chunkedUpdates,\n async (currentChunk) => {\n // Make the request\n try {\n await sombra\n .put('v1/preferences', {\n json: {\n records: currentChunk.map(([, update]) => update),\n skipWorkflowTriggers,\n },\n })\n .json();\n } catch (err) {\n try {\n const parsed = JSON.parse(err?.response?.body || '{}');\n if (parsed.error) {\n logger.error(colors.red(`Error: ${parsed.error}`));\n }\n } catch {\n // continue\n }\n logger.error(\n colors.red(\n `Failed to upload ${currentChunk.length} user preferences to partition ${partition}: ${\n err?.response?.body || err?.message\n }`,\n ),\n );\n const failingUpdates = preferenceState.getValue('failingUpdates');\n currentChunk.forEach(([userId, update]) => {\n failingUpdates[userId] = {\n uploadedAt: new Date().toISOString(),\n update,\n error: err?.response?.body || err?.message || 'Unknown error',\n };\n });\n await preferenceState.setValue(failingUpdates, 'failingUpdates');\n }\n\n total += currentChunk.length;\n progressBar.update(total);\n },\n {\n concurrency: 40,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n logger.info(\n colors.green(\n `Successfully uploaded ${\n updatesToRun.length\n } user preferences to partition ${partition} in \"${totalTime / 1000}\" seconds!`,\n ),\n );\n}\n","import { readdirSync } from 'node:fs';\nimport { basename, join } from 'node:path';\n\nimport { map, splitCsvToList } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { uploadPreferenceManagementPreferencesInteractive } from '../../../lib/preference-management/index.js';\nimport { logger } from '../../../logger.js';\n\nexport interface UploadPreferencesCommandFlags {\n auth: string;\n partition: string;\n sombraAuth?: string;\n transcendUrl: string;\n file?: string;\n directory?: string;\n dryRun: boolean;\n skipExistingRecordCheck: boolean;\n receiptFileDir: string;\n skipWorkflowTriggers: boolean;\n forceTriggerWorkflows: boolean;\n skipConflictUpdates: boolean;\n isSilent: boolean;\n attributes: string;\n receiptFilepath: string;\n concurrency: number;\n}\n\nexport async function uploadPreferences(\n this: LocalContext,\n {\n auth,\n partition,\n sombraAuth,\n transcendUrl,\n file = '',\n directory,\n dryRun,\n skipExistingRecordCheck,\n receiptFileDir,\n skipWorkflowTriggers,\n forceTriggerWorkflows,\n skipConflictUpdates,\n isSilent,\n attributes,\n concurrency,\n }: UploadPreferencesCommandFlags,\n): Promise<void> {\n if (!!directory && !!file) {\n logger.error(\n colors.red('Cannot provide both a directory and a file. Please provide only one.'),\n );\n this.process.exit(1);\n }\n\n if (!file && !directory) {\n logger.error(\n colors.red(\n 'A file or directory must be provided. Please provide one using --file=./preferences.csv or --directory=./preferences',\n ),\n );\n this.process.exit(1);\n }\n\n doneInputValidation(this.process.exit);\n\n const files: string[] = [];\n\n if (directory) {\n try {\n const filesInDirectory = readdirSync(directory);\n const csvFiles = filesInDirectory.filter((file) => file.endsWith('.csv'));\n\n if (csvFiles.length === 0) {\n logger.error(colors.red(`No CSV files found in directory: ${directory}`));\n this.process.exit(1);\n }\n\n // Add full paths for each CSV file\n files.push(...csvFiles.map((file) => join(directory, file)));\n } catch (err) {\n logger.error(colors.red(`Failed to read directory: ${directory}`));\n logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n } else {\n try {\n // Verify file exists and is a CSV\n if (!file.endsWith('.csv')) {\n logger.error(colors.red('File must be a CSV file'));\n this.process.exit(1);\n }\n files.push(file);\n } catch (err) {\n logger.error(colors.red(`Failed to access file: ${file}`));\n logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n }\n\n logger.info(\n colors.green(\n `Processing ${files.length} consent preferences files for partition: ${partition}`,\n ),\n );\n logger.debug(`Files to process: ${files.join(', ')}`);\n\n if (skipExistingRecordCheck) {\n logger.info(colors.bgYellow(`Skipping existing record check: ${skipExistingRecordCheck}`));\n }\n\n await map(\n files,\n async (filePath) => {\n const fileName = basename(filePath).replace('.csv', '');\n await uploadPreferenceManagementPreferencesInteractive({\n receiptFilepath: join(receiptFileDir, `${fileName}-receipts.json`),\n auth,\n sombraAuth,\n file: filePath,\n partition,\n transcendUrl,\n skipConflictUpdates,\n skipWorkflowTriggers,\n skipExistingRecordCheck,\n isSilent,\n dryRun,\n attributes: splitCsvToList(attributes),\n forceTriggerWorkflows,\n });\n },\n { concurrency },\n );\n}\n"],"mappings":"wkCAmBA,eAAsB,EACpB,EACA,EACA,CACE,eACA,mBACA,yBAS0B,CAK5B,IAAM,EAAe,EAHD,EAAK,EAAY,IAAK,GAAM,OAAO,KAAK,EAAE,CAAC,CAAC,MAAM,CAG3B,CAAE,CAC3C,GAAI,EAAa,iBAAmB,CAAC,EAAa,iBAAiB,CAAG,EAAE,CACxE,GAAI,EAAa,eAAiB,CAAC,EAAa,eAAe,CAAG,EAAE,CACrE,CAAC,CACF,GAAI,EAAa,SAAW,EAAG,CAC7B,GAAI,EACF,OAAO,EAET,MAAU,MAAM,8BAA8B,CAIhD,IAAM,EAAe,CACnB,GAAG,EACH,GAAG,EAAiB,IAAK,GAAM,GAAG,EAAE,QAAQ,aAAa,IAAI,EAAE,OAAO,CACvE,CA0ID,OAvIA,MAAM,EAAU,EAAc,KAAO,IAAQ,CAE3C,IAAM,EAAe,EAAK,EAAY,IAAK,GAAM,EAAE,GAAK,CAAC,CAGrD,EAAiB,EAAa,oBAAoB,GACtD,G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xB,EAAO,KACL,EAAO,MACL,cAAc,EAAM,OAAO,4CAA4C,IACxE,CACF,CACD,EAAO,MAAM,qBAAqB,EAAM,KAAK,KAAK,GAAG,CAEjD,GACF,EAAO,KAAK,EAAO,SAAS,mCAAmC,IAA0B,CAAC,CAG5F,MAAM,EACJ,EACA,KAAO,IAAa,CAElB,MAAM,EAAiD,CACrD,gBAAiB,EAAK,EAAgB,GAFvB,EAAS,EAAS,CAAC,QAAQ,OAAQ,GAED,CAAC,gBAAgB,CAClE,OACA,aACA,KAAM,EACN,YACA,eACA,sBACA,uBACA,0BACA,WACA,SACA,WAAY,EAAe,EAAW,CACtC,wBACD,CAAC,EAEJ,CAAE,cAAa,CAChB"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./skipRequestDataSilos-CbdhNiBV.mjs";import{t}from"./done-input-validation-BcNBxhEs.mjs";async function n({auth:n,dataSiloId:r,status:i,statuses:a,transcendUrl:o,actionTypes:s}){t(this.process.exit),await e({transcendUrl:o,auth:n,status:i,dataSiloId:r,requestStatuses:a,actionTypes:s})}export{n as skipRequestDataSilos};
2
- //# sourceMappingURL=impl-BZQ0KiYZ.mjs.map
1
+ import{t as e}from"./skipRequestDataSilos-DQkZn9Wx.mjs";import{t}from"./done-input-validation-BcNBxhEs.mjs";async function n({auth:n,dataSiloId:r,status:i,statuses:a,transcendUrl:o,actionTypes:s}){t(this.process.exit),await e({transcendUrl:o,auth:n,status:i,dataSiloId:r,requestStatuses:a,actionTypes:s})}export{n as skipRequestDataSilos};
2
+ //# sourceMappingURL=impl-Dk94fgeK.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-BZQ0KiYZ.mjs","names":["skipRequestDataSilosHelper"],"sources":["../src/commands/request/system/skip-request-data-silos/impl.ts"],"sourcesContent":["import type {\n RequestAction,\n RequestDataSiloStatus,\n RequestStatus,\n} from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../../context.js';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation.js';\nimport { skipRequestDataSilos as skipRequestDataSilosHelper } from '../../../../lib/requests/index.js';\n\nexport interface SkipRequestDataSilosCommandFlags {\n auth: string;\n dataSiloId: string;\n transcendUrl: string;\n statuses: RequestStatus[];\n status: (typeof RequestDataSiloStatus)['Skipped'] | (typeof RequestDataSiloStatus)['Resolved'];\n actionTypes?: RequestAction[];\n}\n\nexport async function skipRequestDataSilos(\n this: LocalContext,\n {\n auth,\n dataSiloId,\n status,\n statuses,\n transcendUrl,\n actionTypes,\n }: SkipRequestDataSilosCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await skipRequestDataSilosHelper({\n transcendUrl,\n auth,\n status,\n dataSiloId,\n requestStatuses: statuses,\n actionTypes,\n });\n}\n"],"mappings":"4GAmBA,eAAsB,EAEpB,CACE,OACA,aACA,SACA,WACA,eACA,eAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAMA,EAA2B,CAC/B,eACA,OACA,SACA,aACA,gBAAiB,EACjB,cACD,CAAC"}
1
+ {"version":3,"file":"impl-Dk94fgeK.mjs","names":["skipRequestDataSilosHelper"],"sources":["../src/commands/request/system/skip-request-data-silos/impl.ts"],"sourcesContent":["import type {\n RequestAction,\n RequestDataSiloStatus,\n RequestStatus,\n} from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../../context.js';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation.js';\nimport { skipRequestDataSilos as skipRequestDataSilosHelper } from '../../../../lib/requests/index.js';\n\nexport interface SkipRequestDataSilosCommandFlags {\n auth: string;\n dataSiloId: string;\n transcendUrl: string;\n statuses: RequestStatus[];\n status: (typeof RequestDataSiloStatus)['Skipped'] | (typeof RequestDataSiloStatus)['Resolved'];\n actionTypes?: RequestAction[];\n}\n\nexport async function skipRequestDataSilos(\n this: LocalContext,\n {\n auth,\n dataSiloId,\n status,\n statuses,\n transcendUrl,\n actionTypes,\n }: SkipRequestDataSilosCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await skipRequestDataSilosHelper({\n transcendUrl,\n auth,\n status,\n dataSiloId,\n requestStatuses: statuses,\n actionTypes,\n });\n}\n"],"mappings":"4GAmBA,eAAsB,EAEpB,CACE,OACA,aACA,SACA,WACA,eACA,eAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAMA,EAA2B,CAC/B,eACA,OACA,SACA,aACA,gBAAiB,EACjB,cACD,CAAC"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./logger-Bj782ZYD.mjs";import{a as t,r as n}from"./readTranscendYaml-BbnEGgVD.mjs";import{t as r}from"./consentManagersToBusinessEntities-BdKDganK.mjs";import{t as i}from"./listFiles-D2wMHnEr.mjs";import{t as a}from"./done-input-validation-BcNBxhEs.mjs";import{existsSync as o,lstatSync as s}from"node:fs";import{join as c}from"node:path";import l from"colors";function u({consentManagerYmlFolder:u,output:d}){a(this.process.exit),(!o(u)||!s(u).isDirectory())&&(e.error(l.red(`Folder does not exist: "${u}"`)),this.process.exit(1));let f=r(i(u).map(e=>{let{"consent-manager":t}=n(c(u,e));return{name:e,input:t}}));t(d,{"business-entities":f}),e.info(l.green(`Successfully wrote ${f.length} business entities to file "${d}"`))}export{u as consentManagersToBusinessEntities};
2
- //# sourceMappingURL=impl-BuxT4Cx2.mjs.map
1
+ import{t as e}from"./logger-Bj782ZYD.mjs";import{a as t,r as n}from"./readTranscendYaml-CGb2UUyM.mjs";import{t as r}from"./consentManagersToBusinessEntities-BdKDganK.mjs";import{t as i}from"./listFiles-D2wMHnEr.mjs";import{t as a}from"./done-input-validation-BcNBxhEs.mjs";import{existsSync as o,lstatSync as s}from"node:fs";import{join as c}from"node:path";import l from"colors";function u({consentManagerYmlFolder:u,output:d}){a(this.process.exit),(!o(u)||!s(u).isDirectory())&&(e.error(l.red(`Folder does not exist: "${u}"`)),this.process.exit(1));let f=r(i(u).map(e=>{let{"consent-manager":t}=n(c(u,e));return{name:e,input:t}}));t(d,{"business-entities":f}),e.info(l.green(`Successfully wrote ${f.length} business entities to file "${d}"`))}export{u as consentManagersToBusinessEntities};
2
+ //# sourceMappingURL=impl-Dm6ITkBn.mjs.map