@transcend-io/cli 9.0.0 → 9.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{api-keys-C7JLTDUZ.mjs → api-keys-CxvKdj2v.mjs} +2 -2
- package/dist/{api-keys-C7JLTDUZ.mjs.map → api-keys-CxvKdj2v.mjs.map} +1 -1
- package/dist/{app-Dti3qTxV.mjs → app-BKMxG7RO.mjs} +18 -18
- package/dist/{app-Dti3qTxV.mjs.map → app-BKMxG7RO.mjs.map} +1 -1
- package/dist/bin/bash-complete.mjs +1 -1
- package/dist/bin/cli.mjs +1 -1
- package/dist/bin/deprecated-command.mjs +1 -1
- package/dist/{code-scanning-3tLsE1W5.mjs → code-scanning-Cx1kpssH.mjs} +2 -2
- package/dist/{code-scanning-3tLsE1W5.mjs.map → code-scanning-Cx1kpssH.mjs.map} +1 -1
- package/dist/{command-BlHM1nCd.mjs → command-Bzyj3M2G.mjs} +2 -2
- package/dist/{command-BlHM1nCd.mjs.map → command-Bzyj3M2G.mjs.map} +1 -1
- package/dist/{consent-manager-BoaaMjRQ.mjs → consent-manager-c4bgQF1N.mjs} +2 -2
- package/dist/{consent-manager-BoaaMjRQ.mjs.map → consent-manager-c4bgQF1N.mjs.map} +1 -1
- package/dist/{constants-DdeeX81W.mjs → constants-CnLQtIBn.mjs} +2 -2
- package/dist/{constants-DdeeX81W.mjs.map → constants-CnLQtIBn.mjs.map} +1 -1
- package/dist/{cron-DOicA1l8.mjs → cron-BvxWyvDu.mjs} +2 -2
- package/dist/{cron-DOicA1l8.mjs.map → cron-BvxWyvDu.mjs.map} +1 -1
- package/dist/{data-inventory-OeEcogPl.mjs → data-inventory-CkS_kmus.mjs} +2 -2
- package/dist/{data-inventory-OeEcogPl.mjs.map → data-inventory-CkS_kmus.mjs.map} +1 -1
- package/dist/{impl-fESuqAH1.mjs → impl-8dOatHnF.mjs} +2 -2
- package/dist/{impl-fESuqAH1.mjs.map → impl-8dOatHnF.mjs.map} +1 -1
- package/dist/{impl-DzSmriDw.mjs → impl-Ah-1lwzr.mjs} +2 -2
- package/dist/{impl-DzSmriDw.mjs.map → impl-Ah-1lwzr.mjs.map} +1 -1
- package/dist/{impl-BI4zCNs0.mjs → impl-B5lTeRbn.mjs} +2 -2
- package/dist/{impl-BI4zCNs0.mjs.map → impl-B5lTeRbn.mjs.map} +1 -1
- package/dist/{impl-D2HalFgB2.mjs → impl-B6UhzQcY2.mjs} +2 -2
- package/dist/{impl-D2HalFgB2.mjs.map → impl-B6UhzQcY2.mjs.map} +1 -1
- package/dist/{impl-BvZai1Pf2.mjs → impl-BFf_CotE2.mjs} +2 -2
- package/dist/{impl-BvZai1Pf2.mjs.map → impl-BFf_CotE2.mjs.map} +1 -1
- package/dist/{impl-iwjvzA7a.mjs → impl-BGQ0EGS0.mjs} +2 -2
- package/dist/{impl-iwjvzA7a.mjs.map → impl-BGQ0EGS0.mjs.map} +1 -1
- package/dist/{impl-B8CoAX4t.mjs → impl-B__p3_wC.mjs} +2 -2
- package/dist/{impl-B8CoAX4t.mjs.map → impl-B__p3_wC.mjs.map} +1 -1
- package/dist/{impl-CaTnsoDi.mjs → impl-BcayRe6a.mjs} +2 -2
- package/dist/{impl-CaTnsoDi.mjs.map → impl-BcayRe6a.mjs.map} +1 -1
- package/dist/{impl-CTPHR7O62.mjs → impl-BkYKsEVG2.mjs} +2 -2
- package/dist/{impl-CTPHR7O62.mjs.map → impl-BkYKsEVG2.mjs.map} +1 -1
- package/dist/{impl-gYrR3kIh.mjs → impl-Bl2yVgh0.mjs} +2 -2
- package/dist/{impl-gYrR3kIh.mjs.map → impl-Bl2yVgh0.mjs.map} +1 -1
- package/dist/{impl-CoZhgLjC.mjs → impl-BmAMgEEM.mjs} +2 -2
- package/dist/{impl-CoZhgLjC.mjs.map → impl-BmAMgEEM.mjs.map} +1 -1
- package/dist/{impl-Bh04BLeU2.mjs → impl-BsttzxTN2.mjs} +2 -2
- package/dist/{impl-Bh04BLeU2.mjs.map → impl-BsttzxTN2.mjs.map} +1 -1
- package/dist/{impl--Ov8Om49.mjs → impl-BtnySmbi.mjs} +2 -2
- package/dist/{impl--Ov8Om49.mjs.map → impl-BtnySmbi.mjs.map} +1 -1
- package/dist/{impl-BraVBCrF2.mjs → impl-BwX-evfW2.mjs} +2 -2
- package/dist/{impl-BraVBCrF2.mjs.map → impl-BwX-evfW2.mjs.map} +1 -1
- package/dist/impl-C-wzeAib2.mjs +2 -0
- package/dist/{impl-BEzyqD_12.mjs.map → impl-C-wzeAib2.mjs.map} +1 -1
- package/dist/{impl-B40z0Aoz2.mjs → impl-C61PYfk12.mjs} +2 -2
- package/dist/{impl-B40z0Aoz2.mjs.map → impl-C61PYfk12.mjs.map} +1 -1
- package/dist/impl-CAuNpuF2.mjs +2 -0
- package/dist/impl-CAuNpuF2.mjs.map +1 -0
- package/dist/{impl-CvxsioT4.mjs → impl-CSKrBIuV.mjs} +2 -2
- package/dist/{impl-CvxsioT4.mjs.map → impl-CSKrBIuV.mjs.map} +1 -1
- package/dist/{impl-CIJ6P1GD.mjs → impl-CZP2l3Ds.mjs} +2 -2
- package/dist/{impl-CIJ6P1GD.mjs.map → impl-CZP2l3Ds.mjs.map} +1 -1
- package/dist/{impl-J-dQqTZJ2.mjs → impl-CiJ8hE5W2.mjs} +2 -2
- package/dist/{impl-J-dQqTZJ2.mjs.map → impl-CiJ8hE5W2.mjs.map} +1 -1
- package/dist/{impl-DP757pBT.mjs → impl-Cj3H-m2Z.mjs} +2 -2
- package/dist/{impl-DP757pBT.mjs.map → impl-Cj3H-m2Z.mjs.map} +1 -1
- package/dist/{impl-qiK6VF4F2.mjs → impl-Cm8pUfBU2.mjs} +2 -2
- package/dist/{impl-qiK6VF4F2.mjs.map → impl-Cm8pUfBU2.mjs.map} +1 -1
- package/dist/{impl-CNiEzL3_2.mjs → impl-CpzS9LVu2.mjs} +2 -2
- package/dist/{impl-CNiEzL3_2.mjs.map → impl-CpzS9LVu2.mjs.map} +1 -1
- package/dist/{impl-BpMKYqSR.mjs → impl-CwfamZ1c.mjs} +2 -2
- package/dist/{impl-BpMKYqSR.mjs.map → impl-CwfamZ1c.mjs.map} +1 -1
- package/dist/{impl-BDKBhSiG2.mjs → impl-D81et1Yb2.mjs} +2 -2
- package/dist/{impl-BDKBhSiG2.mjs.map → impl-D81et1Yb2.mjs.map} +1 -1
- package/dist/{impl-DgsWGnhH.mjs → impl-D92PTNk3.mjs} +2 -2
- package/dist/{impl-DgsWGnhH.mjs.map → impl-D92PTNk3.mjs.map} +1 -1
- package/dist/{impl-DVDN007x.mjs → impl-DTXDVeo6.mjs} +2 -2
- package/dist/{impl-DVDN007x.mjs.map → impl-DTXDVeo6.mjs.map} +1 -1
- package/dist/{impl-B0d5M861.mjs → impl-DWoysXup.mjs} +2 -2
- package/dist/{impl-B0d5M861.mjs.map → impl-DWoysXup.mjs.map} +1 -1
- package/dist/{impl-BhMd6_J22.mjs → impl-DX3JHZ4v2.mjs} +2 -2
- package/dist/{impl-BhMd6_J22.mjs.map → impl-DX3JHZ4v2.mjs.map} +1 -1
- package/dist/{impl-DfKI4fmI.mjs → impl-DhuUrzxQ.mjs} +2 -2
- package/dist/{impl-DfKI4fmI.mjs.map → impl-DhuUrzxQ.mjs.map} +1 -1
- package/dist/{impl-CiQeM677.mjs → impl-DqMYLKjU.mjs} +2 -2
- package/dist/{impl-CiQeM677.mjs.map → impl-DqMYLKjU.mjs.map} +1 -1
- package/dist/{impl-BiWrlucD.mjs → impl-DqQ6CIj0.mjs} +2 -2
- package/dist/{impl-BiWrlucD.mjs.map → impl-DqQ6CIj0.mjs.map} +1 -1
- package/dist/{impl-BJ9Ge6Wf2.mjs → impl-Duaq6iWI2.mjs} +2 -2
- package/dist/{impl-BJ9Ge6Wf2.mjs.map → impl-Duaq6iWI2.mjs.map} +1 -1
- package/dist/{impl-DOgLpdLw.mjs → impl-O5gz8qcm.mjs} +2 -2
- package/dist/{impl-DOgLpdLw.mjs.map → impl-O5gz8qcm.mjs.map} +1 -1
- package/dist/{impl-C73Uh2Ze.mjs → impl-PH0AoC7i.mjs} +2 -2
- package/dist/{impl-C73Uh2Ze.mjs.map → impl-PH0AoC7i.mjs.map} +1 -1
- package/dist/{impl-CU29SrJb2.mjs → impl-S8p6toVb2.mjs} +2 -2
- package/dist/{impl-CU29SrJb2.mjs.map → impl-S8p6toVb2.mjs.map} +1 -1
- package/dist/{impl-4BP7gY61.mjs → impl-X2MSb8Ij.mjs} +2 -2
- package/dist/{impl-4BP7gY61.mjs.map → impl-X2MSb8Ij.mjs.map} +1 -1
- package/dist/{impl-SxwaNC4m2.mjs → impl-bo95wZIU2.mjs} +2 -2
- package/dist/{impl-SxwaNC4m2.mjs.map → impl-bo95wZIU2.mjs.map} +1 -1
- package/dist/{impl-DFNq8PBe.mjs → impl-cfdCesro.mjs} +2 -2
- package/dist/{impl-DFNq8PBe.mjs.map → impl-cfdCesro.mjs.map} +1 -1
- package/dist/{impl-EhTHDCC1.mjs → impl-iZoXu4nV.mjs} +2 -2
- package/dist/{impl-EhTHDCC1.mjs.map → impl-iZoXu4nV.mjs.map} +1 -1
- package/dist/{impl-BPz3SpXo2.mjs → impl-lebl6Zek2.mjs} +2 -2
- package/dist/{impl-BPz3SpXo2.mjs.map → impl-lebl6Zek2.mjs.map} +1 -1
- package/dist/{impl-BvTvjK72.mjs → impl-p0YN9e2e.mjs} +2 -2
- package/dist/{impl-BvTvjK72.mjs.map → impl-p0YN9e2e.mjs.map} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{manual-enrichment-CYoZNBjO.mjs → manual-enrichment-B6lW5kAX.mjs} +2 -2
- package/dist/{manual-enrichment-CYoZNBjO.mjs.map → manual-enrichment-B6lW5kAX.mjs.map} +1 -1
- package/dist/{pooling-BkZAO1Zs.mjs → pooling-CazydwlD.mjs} +2 -2
- package/dist/{pooling-BkZAO1Zs.mjs.map → pooling-CazydwlD.mjs.map} +1 -1
- package/dist/{preference-management-BHj26bmE.mjs → preference-management-8gj7aSJB.mjs} +2 -2
- package/dist/{preference-management-BHj26bmE.mjs.map → preference-management-8gj7aSJB.mjs.map} +1 -1
- package/dist/{syncConfigurationToTranscend-wWSbGVrI.mjs → syncConfigurationToTranscend-VJd0PnaZ.mjs} +2 -2
- package/dist/{syncConfigurationToTranscend-wWSbGVrI.mjs.map → syncConfigurationToTranscend-VJd0PnaZ.mjs.map} +1 -1
- package/dist/{uploadConsents-nsjKy1I4.mjs → uploadConsents-C1S-BNzw.mjs} +2 -2
- package/dist/{uploadConsents-nsjKy1I4.mjs.map → uploadConsents-C1S-BNzw.mjs.map} +1 -1
- package/package.json +1 -1
- package/dist/impl-BEzyqD_12.mjs +0 -2
- package/dist/impl-nKY3m-Vx.mjs +0 -2
- package/dist/impl-nKY3m-Vx.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-B__p3_wC.mjs","names":[],"sources":["../src/commands/request/upload/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport {\n splitCsvToList,\n uploadPrivacyRequestsFromCsv,\n} from '../../../lib/requests';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface UploadCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n cacheFilepath: string;\n requestReceiptFolder: string;\n sombraAuth?: string;\n concurrency: number;\n attributes: string;\n isTest: boolean;\n isSilent: boolean;\n skipSendingReceipt: boolean;\n emailIsVerified: boolean;\n skipFilterStep: boolean;\n dryRun: boolean;\n debug: boolean;\n defaultPhoneCountryCode: string;\n}\n\nexport async function upload(\n this: LocalContext,\n {\n auth,\n file,\n transcendUrl,\n cacheFilepath,\n requestReceiptFolder,\n sombraAuth,\n concurrency,\n attributes,\n isTest,\n isSilent,\n skipSendingReceipt,\n emailIsVerified,\n skipFilterStep,\n dryRun,\n debug,\n defaultPhoneCountryCode,\n }: UploadCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await uploadPrivacyRequestsFromCsv({\n cacheFilepath,\n requestReceiptFolder,\n file,\n auth,\n sombraAuth,\n concurrency,\n transcendUrl,\n defaultPhoneCountryCode,\n attributes: splitCsvToList(attributes),\n debug,\n skipFilterStep,\n isSilent,\n skipSendingReceipt,\n emailIsVerified,\n isTest,\n dryRun,\n });\n}\n"],"mappings":"2QA0BA,eAAsB,EAEpB,CACE,OACA,OACA,eACA,gBACA,uBACA,aACA,cACA,aACA,SACA,WACA,qBACA,kBACA,iBACA,SACA,QACA,2BAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAM,EAA6B,CACjC,gBACA,uBACA,OACA,OACA,aACA,cACA,eACA,0BACA,WAAY,EAAe,EAAW,CACtC,QACA,iBACA,WACA,qBACA,kBACA,SACA,SACD,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./enums-CyFTrzXY.mjs";import"./constants-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import"./enums-CyFTrzXY.mjs";import"./constants-CnLQtIBn.mjs";import"./logger-Bj782ZYD.mjs";import"./buildAIIntegrationType-Bk0EbFKV.mjs";import"./codecs-TR6p48v3.mjs";import"./syncConfigurationToTranscend-VJd0PnaZ.mjs";import{s as e}from"./consent-manager-c4bgQF1N.mjs";import"./uploadConsents-C1S-BNzw.mjs";import{t}from"./done-input-validation-CcZtaz03.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-BcayRe6a.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-BcayRe6a.mjs","names":["uploadDataFlowsFromCsvHelper"],"sources":["../src/commands/consent/upload-data-flows-from-csv/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport { uploadDataFlowsFromCsv as uploadDataFlowsFromCsvHelper } from '../../../lib/consent-manager';\nimport { ConsentTrackerStatus } from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\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 {\n auth,\n trackerStatus,\n file,\n classifyService,\n transcendUrl,\n }: 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":"yWAaA,eAAsB,EAEpB,CACE,OACA,gBACA,OACA,kBACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAMA,EAA6B,CACjC,OACA,gBACA,OACA,kBACA,eACD,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./enums-CyFTrzXY.mjs";import"./constants-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import"./enums-CyFTrzXY.mjs";import"./constants-CnLQtIBn.mjs";import"./logger-Bj782ZYD.mjs";import"./buildAIIntegrationType-Bk0EbFKV.mjs";import{$ as e}from"./syncConfigurationToTranscend-VJd0PnaZ.mjs";import{t}from"./done-input-validation-CcZtaz03.mjs";import{RequestStatus as n}from"@transcend-io/privacy-types";async function r({auth:r,transcendUrl:i,folderPath:a,requestIds:o,statuses:s=[n.Approving,n.Downloadable],concurrency:c,createdAtBefore:l,createdAtAfter:u,updatedAtBefore:d,updatedAtAfter:f,approveAfterDownload:p}){t(this.process.exit),await e({transcendUrl:i,auth:r,folderPath:a,requestIds:o,statuses:s,concurrency:c,createdAtBefore:l,createdAtAfter:u,updatedAtBefore:d,updatedAtAfter:f,approveAfterDownload:p})}export{r as downloadFiles};
|
|
2
|
+
//# sourceMappingURL=impl-BkYKsEVG2.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-BkYKsEVG2.mjs","names":[],"sources":["../src/commands/request/download-files/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport { downloadPrivacyRequestFiles } from '../../../lib/requests';\nimport { RequestStatus } from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface DownloadFilesCommandFlags {\n auth: string;\n sombraAuth?: string;\n concurrency: number;\n requestIds?: string[];\n statuses?: RequestStatus[];\n folderPath: string;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n approveAfterDownload: boolean;\n transcendUrl: string;\n}\n\nexport async function downloadFiles(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n folderPath,\n requestIds,\n statuses = [RequestStatus.Approving, RequestStatus.Downloadable],\n concurrency,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n approveAfterDownload,\n }: DownloadFilesCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await downloadPrivacyRequestFiles({\n transcendUrl,\n auth,\n folderPath,\n requestIds,\n statuses,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n approveAfterDownload,\n });\n}\n"],"mappings":"0TAoBA,eAAsB,EAEpB,CACE,OACA,eACA,aACA,aACA,WAAW,CAAC,EAAc,UAAW,EAAc,aAAa,CAChE,cACA,kBACA,iBACA,kBACA,iBACA,wBAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAM,EAA4B,CAChC,eACA,OACA,aACA,aACA,WACA,cACA,kBACA,iBACA,kBACA,iBACA,uBACD,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./enums-CyFTrzXY.mjs";import{t as e}from"./constants-
|
|
1
|
+
import"./enums-CyFTrzXY.mjs";import{t as e}from"./constants-CnLQtIBn.mjs";import{t}from"./logger-Bj782ZYD.mjs";import"./buildAIIntegrationType-Bk0EbFKV.mjs";import"./codecs-TR6p48v3.mjs";import{ai as n,ei as r,ft as i}from"./syncConfigurationToTranscend-VJd0PnaZ.mjs";import"./api-keys-CxvKdj2v.mjs";import{t as a}from"./done-input-validation-CcZtaz03.mjs";import{n as o}from"./code-scanning-Cx1kpssH.mjs";import s from"colors";import c from"fast-glob";import{stringify as l}from"query-string";async function u({scanPath:e,fileGlobs:n,ignoreDirs:r,config:i}){let{ignoreDirs:a,supportedFiles:o,scanFunction:s}=i,l=n===``?o:o.concat(n.split(`,`)),d=[...r.split(`,`),...a].filter(e=>e.length>0);try{let n=await c(`${e}/**/${l.join(`|`)}`,{ignore:d.map(t=>`${e}/**/${t}`),unique:!0,onlyFiles:!0});t.info(`Scanning: ${n.length} files`);let r=n.map(e=>s(e)).flat().map(e=>e.softwareDevelopmentKits||[]).flat(),i=[...new Set(r.map(e=>e.name))];return t.info(`Found: ${i.length} unique dependencies`),i.map(t=>({name:t,resourceId:`${e}/**/${t}`,useStrictClassifier:!0}))}catch(e){throw Error(`Error scanning globs ${u} with error: ${e}`)}}async function d({scanPath:c,dataSiloId:d,auth:f,fileGlobs:p,ignoreDirs:m,transcendUrl:h}){a(this.process.exit);let g=n(h,f),_=await r(g,d),v=o[_.dataSilo.type];v||(t.error(s.red(`This plugin "${_.dataSilo.type}" is not supported for offline silo discovery.`)),this.process.exit(1));let y=await u({scanPath:c,fileGlobs:p,ignoreDirs:m,config:v});await i(g,_.id,y);let b=new URL(e);b.pathname=`/data-map/data-inventory/silo-discovery/triage`,b.search=l({filters:JSON.stringify({pluginIds:[_.id]})}),t.info(s.green(`Scan found ${y.length} potential data silos at ${c}! View at '${b.href}'
|
|
2
2
|
|
|
3
3
|
NOTE: it may take 2-3 minutes for scan results to appear in the UI.`))}export{d as discoverSilos};
|
|
4
|
-
//# sourceMappingURL=impl-
|
|
4
|
+
//# sourceMappingURL=impl-Bl2yVgh0.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-Bl2yVgh0.mjs","names":[],"sources":["../src/lib/code-scanning/findFilesToScan.ts","../src/commands/inventory/discover-silos/impl.ts"],"sourcesContent":["import fastGlob from 'fast-glob';\nimport { logger } from '../../logger';\nimport { CodeScanningConfig } from './types';\n\nexport interface SiloDiscoveryRawResults {\n /** The name of the potential data silo entry */\n name: string;\n /** A unique UUID (represents the same resource across different silo discovery runs) */\n resourceId: string;\n /** Any hosts associated with the entry */\n host?: string;\n /** Type of data silo */\n type?: string | undefined;\n}\n\n/**\n * Helper to scan for data silos in all package.json files that it can find in a directory\n *\n * @deprecated TODO: https://transcend.height.app/T-32325 - use code scanning instead\n * @param options - Options\n * @returns the list of integrations\n */\nexport async function findFilesToScan({\n scanPath,\n fileGlobs,\n ignoreDirs,\n config,\n}: {\n /** Where to look for package.json files */\n scanPath: string;\n /** Globs to look for */\n fileGlobs: string;\n /** The directories to ignore (excludes node_modules and serverless-build) */\n ignoreDirs: string;\n /** Silo Discovery configuration */\n config: CodeScanningConfig;\n}): Promise<SiloDiscoveryRawResults[]> {\n const { ignoreDirs: IGNORE_DIRS, supportedFiles, scanFunction } = config;\n const globsToSupport =\n fileGlobs === ''\n ? supportedFiles\n : supportedFiles.concat(fileGlobs.split(','));\n const dirsToIgnore = [...ignoreDirs.split(','), ...IGNORE_DIRS].filter(\n (dir) => dir.length > 0,\n );\n try {\n const filesToScan: string[] = await fastGlob(\n `${scanPath}/**/${globsToSupport.join('|')}`,\n {\n ignore: dirsToIgnore.map((dir: string) => `${scanPath}/**/${dir}`),\n unique: true,\n onlyFiles: true,\n },\n );\n logger.info(`Scanning: ${filesToScan.length} files`);\n const allPackages = filesToScan\n .map((filePath: string) => scanFunction(filePath))\n .flat();\n const allSdks = allPackages\n .map((appPackage) => appPackage.softwareDevelopmentKits || [])\n .flat();\n const uniqueDeps = new Set(allSdks.map((sdk) => sdk.name));\n const deps = [...uniqueDeps];\n logger.info(`Found: ${deps.length} unique dependencies`);\n return deps.map((dep) => ({\n name: dep,\n resourceId: `${scanPath}/**/${dep}`,\n useStrictClassifier: true,\n }));\n } catch (error) {\n throw new Error(\n `Error scanning globs ${findFilesToScan} with error: ${error}`,\n );\n }\n}\n","import type { LocalContext } from '../../../context';\nimport { stringify } from 'query-string';\nimport { logger } from '../../../logger';\nimport colors from 'colors';\nimport { ADMIN_DASH } from '../../../constants';\nimport {\n fetchActiveSiloDiscoPlugin,\n buildTranscendGraphQLClient,\n uploadSiloDiscoveryResults,\n} from '../../../lib/graphql';\nimport { findFilesToScan } from '../../../lib/code-scanning/findFilesToScan';\nimport { SILO_DISCOVERY_CONFIGS } from '../../../lib/code-scanning';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface DiscoverSilosCommandFlags {\n scanPath: string;\n dataSiloId: string;\n auth: string;\n fileGlobs: string;\n ignoreDirs: string;\n transcendUrl: string;\n}\n\nexport async function discoverSilos(\n this: LocalContext,\n {\n scanPath,\n dataSiloId,\n auth,\n fileGlobs,\n ignoreDirs,\n transcendUrl,\n }: DiscoverSilosCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const plugin = await fetchActiveSiloDiscoPlugin(client, dataSiloId);\n\n const config = SILO_DISCOVERY_CONFIGS[plugin.dataSilo.type];\n if (!config) {\n logger.error(\n colors.red(\n `This plugin \"${plugin.dataSilo.type}\" is not supported for offline silo discovery.`,\n ),\n );\n this.process.exit(1);\n }\n\n const results = await findFilesToScan({\n scanPath,\n fileGlobs,\n ignoreDirs,\n config,\n });\n\n await uploadSiloDiscoveryResults(client, plugin.id, results);\n\n const newUrl = new URL(ADMIN_DASH);\n newUrl.pathname = '/data-map/data-inventory/silo-discovery/triage';\n newUrl.search = stringify({\n filters: JSON.stringify({ pluginIds: [plugin.id] }),\n });\n\n // Indicate success\n logger.info(\n colors.green(\n `Scan found ${results.length} potential data silos at ${scanPath}! ` +\n `View at '${newUrl.href}' ` +\n '\\n\\n NOTE: it may take 2-3 minutes for scan results to appear in the UI.',\n ),\n );\n}\n"],"mappings":"8eAsBA,eAAsB,EAAgB,CACpC,WACA,YACA,aACA,UAUqC,CACrC,GAAM,CAAE,WAAY,EAAa,iBAAgB,gBAAiB,EAC5D,EACJ,IAAc,GACV,EACA,EAAe,OAAO,EAAU,MAAM,IAAI,CAAC,CAC3C,EAAe,CAAC,GAAG,EAAW,MAAM,IAAI,CAAE,GAAG,EAAY,CAAC,OAC7D,GAAQ,EAAI,OAAS,EACvB,CACD,GAAI,CACF,IAAM,EAAwB,MAAM,EAClC,GAAG,EAAS,MAAM,EAAe,KAAK,IAAI,GAC1C,CACE,OAAQ,EAAa,IAAK,GAAgB,GAAG,EAAS,MAAM,IAAM,CAClE,OAAQ,GACR,UAAW,GACZ,CACF,CACD,EAAO,KAAK,aAAa,EAAY,OAAO,QAAQ,CAIpD,IAAM,EAHc,EACjB,IAAK,GAAqB,EAAa,EAAS,CAAC,CACjD,MAAM,CAEN,IAAK,GAAe,EAAW,yBAA2B,EAAE,CAAC,CAC7D,MAAM,CAEH,EAAO,CAAC,GADK,IAAI,IAAI,EAAQ,IAAK,GAAQ,EAAI,KAAK,CAAC,CAC9B,CAE5B,OADA,EAAO,KAAK,UAAU,EAAK,OAAO,sBAAsB,CACjD,EAAK,IAAK,IAAS,CACxB,KAAM,EACN,WAAY,GAAG,EAAS,MAAM,IAC9B,oBAAqB,GACtB,EAAE,OACI,EAAO,CACd,MAAU,MACR,wBAAwB,EAAgB,eAAe,IACxD,ECjDL,eAAsB,EAEpB,CACE,WACA,aACA,OACA,YACA,aACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAGtC,IAAM,EAAS,EAA4B,EAAc,EAAK,CAExD,EAAS,MAAM,EAA2B,EAAQ,EAAW,CAE7D,EAAS,EAAuB,EAAO,SAAS,MACjD,IACH,EAAO,MACL,EAAO,IACL,gBAAgB,EAAO,SAAS,KAAK,gDACtC,CACF,CACD,KAAK,QAAQ,KAAK,EAAE,EAGtB,IAAM,EAAU,MAAM,EAAgB,CACpC,WACA,YACA,aACA,SACD,CAAC,CAEF,MAAM,EAA2B,EAAQ,EAAO,GAAI,EAAQ,CAE5D,IAAM,EAAS,IAAI,IAAI,EAAW,CAClC,EAAO,SAAW,iDAClB,EAAO,OAAS,EAAU,CACxB,QAAS,KAAK,UAAU,CAAE,UAAW,CAAC,EAAO,GAAG,CAAE,CAAC,CACpD,CAAC,CAGF,EAAO,KACL,EAAO,MACL,cAAc,EAAQ,OAAO,2BAA2B,EAAS,aACnD,EAAO,KAAK;;sEAE3B,CACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./enums-CyFTrzXY.mjs";import"./constants-
|
|
1
|
+
import"./enums-CyFTrzXY.mjs";import"./constants-CnLQtIBn.mjs";import{t as e}from"./logger-Bj782ZYD.mjs";import"./buildAIIntegrationType-Bk0EbFKV.mjs";import{As as t,ii as n,l as r}from"./syncConfigurationToTranscend-VJd0PnaZ.mjs";import{t as i}from"./done-input-validation-CcZtaz03.mjs";import{t as a}from"./preference-management-8gj7aSJB.mjs";import{readdirSync as o}from"node:fs";import{join as s}from"node:path";import c from"colors";import l from"cli-progress";async function u({auth:u,partition:d,sombraAuth:f,file:p=``,directory:m,transcendUrl:h,timestamp:g,maxConcurrency:_,maxItemsInChunk:v,receiptDirectory:y,fileConcurrency:b}){m&&p&&(e.error(c.red(`Cannot provide both a directory and a file. Please provide only one.`)),this.process.exit(1)),!p&&!m&&(e.error(c.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(m)try{let t=o(m).filter(e=>e.endsWith(`.csv`));t.length===0&&(e.error(c.red(`No CSV files found in directory: ${m}`)),this.process.exit(1)),x.push(...t.map(e=>s(m,e)))}catch(t){e.error(c.red(`Failed to read directory: ${m}`)),e.error(c.red(t.message)),this.process.exit(1)}else try{p.endsWith(`.csv`)||(e.error(c.red(`File must be a CSV file`)),this.process.exit(1)),x.push(p)}catch(t){e.error(c.red(`Failed to access file: ${p}`)),e.error(c.red(t.message)),this.process.exit(1)}e.debug(c.green(`Processing ${x.length} consent preferences files for partition: ${d}`)),e.debug(`\nFiles to process: ${x.join(`, `)}\n`);let S=await n(h,u,f),C=new l.SingleBar({format:`Deletion Progress |${c.cyan(`[{bar}]`)}| Duration: ${c.red(`{duration_formatted}`)} | {value}/{total} Files Processed `},l.Presets.shades_classic);C.start(x.length,0);let w=await t(x,async e=>{let t=await a(S,{partition:d,filePath:e,timestamp:g,maxItemsInChunk:v,maxConcurrency:_});return C.increment(),t},{concurrency:b});C.stop();let T=w.flat(),E=``;T.length>0&&(E=s(y,`deletion-failures-${Date.now()}.csv`),r(E,T,!0)),e.info(c.green(`
|
|
2
2
|
|
|
3
3
|
==================================
|
|
4
4
|
|
|
@@ -9,4 +9,4 @@ import"./enums-CyFTrzXY.mjs";import"./constants-DdeeX81W.mjs";import{t as e}from
|
|
|
9
9
|
==================================
|
|
10
10
|
|
|
11
11
|
`))}export{u as deletePreferenceRecords};
|
|
12
|
-
//# sourceMappingURL=impl-
|
|
12
|
+
//# sourceMappingURL=impl-BmAMgEEM.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-BmAMgEEM.mjs","names":[],"sources":["../src/commands/consent/delete-preference-records/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport colors from 'colors';\n\nimport { createSombraGotInstance } from '../../../lib/graphql';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\nimport { logger } from '../../../logger';\nimport { readdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { map } from '../../../lib/bluebird';\nimport { bulkDeletePreferenceRecords } from '../../../lib/preference-management';\nimport cliProgress from 'cli-progress';\nimport { writeCsv } from '../../../lib/helpers';\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(\n 'Cannot provide both a directory and a file. Please provide only one.',\n ),\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(\n colors.red(`No CSV files found in directory: ${directory}`),\n );\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, sombraAuth);\n const globalProgressBar = new cliProgress.SingleBar(\n {\n format: `Deletion Progress |${colors.cyan(\n '[{bar}]',\n )}| 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":"idAsCA,eAAsB,EAEpB,CACE,OACA,YACA,aACA,OAAO,GACP,YACA,eACA,YACA,iBACA,kBACA,mBACA,mBAEa,CAC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ACD,EAAkB,MAAM,EAAM,OAAQ,EAAE,CAGxC,IAAM,EAAsB,MAAM,EAChC,EACA,KAAO,IAAa,CAClB,IAAM,EAAS,MAAM,EAA4B,EAAQ,CACvD,YACA,WACA,YACA,kBACA,iBACD,CAAC,CAEF,OADA,EAAkB,WAAW,CACtB,GAET,CAAE,YAAa,EAAiB,CACjC,CACD,EAAkB,MAAM,CACxB,IAAM,EAAgB,EAAoB,MAAM,CAG5C,EAAc,GACd,EAAc,OAAS,IACzB,EAAc,EAAK,EAAkB,qBAAqB,KAAK,KAAK,CAAC,MAAM,CAC3E,EAAS,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"./enums-CyFTrzXY.mjs";import"./constants-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import"./enums-CyFTrzXY.mjs";import"./constants-CnLQtIBn.mjs";import"./logger-Bj782ZYD.mjs";import"./buildAIIntegrationType-Bk0EbFKV.mjs";import{P as e}from"./syncConfigurationToTranscend-VJd0PnaZ.mjs";import{t}from"./done-input-validation-CcZtaz03.mjs";async function n({auth:n,transcendUrl:r,identifierNames:i,actions:a=[]}){t(this.process.exit),await e({requestActions:a,transcendUrl:r,auth:n,identifierNames:i})}export{n as rejectUnverifiedIdentifiers};
|
|
2
|
+
//# sourceMappingURL=impl-BsttzxTN2.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-BsttzxTN2.mjs","names":[],"sources":["../src/commands/request/reject-unverified-identifiers/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport { removeUnverifiedRequestIdentifiers } from '../../../lib/requests';\nimport type { RequestAction } from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface RejectUnverifiedIdentifiersCommandFlags {\n auth: string;\n identifierNames: string[];\n actions?: RequestAction[];\n transcendUrl: string;\n}\n\nexport async function rejectUnverifiedIdentifiers(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n identifierNames,\n actions = [],\n }: RejectUnverifiedIdentifiersCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await removeUnverifiedRequestIdentifiers({\n requestActions: actions,\n transcendUrl,\n auth,\n identifierNames,\n });\n}\n"],"mappings":"8PAYA,eAAsB,EAEpB,CACE,OACA,eACA,kBACA,UAAU,EAAE,EAEC,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAM,EAAmC,CACvC,eAAgB,EAChB,eACA,OACA,kBACD,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./enums-CyFTrzXY.mjs";import"./constants-
|
|
2
|
-
//# sourceMappingURL=impl
|
|
1
|
+
import"./enums-CyFTrzXY.mjs";import"./constants-CnLQtIBn.mjs";import{t as e}from"./logger-Bj782ZYD.mjs";import"./buildAIIntegrationType-Bk0EbFKV.mjs";import{ui as t}from"./syncConfigurationToTranscend-VJd0PnaZ.mjs";import{n}from"./cron-BvxWyvDu.mjs";import{t as r}from"./done-input-validation-CcZtaz03.mjs";import i from"colors";import*as a from"io-ts";const o=a.type({"Request Id":a.string});async function s({auth:a,dataSiloId:s,file:c,transcendUrl:l}){r(this.process.exit),e.info(i.magenta(`Reading "${c}" from disk`)),await n({requestIds:t(c,o).map(e=>e[`Request Id`]),transcendUrl:l,auth:a,dataSiloId:s})}export{s as markRequestDataSilosCompleted};
|
|
2
|
+
//# sourceMappingURL=impl-BtnySmbi.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl
|
|
1
|
+
{"version":3,"file":"impl-BtnySmbi.mjs","names":[],"sources":["../src/commands/request/system/mark-request-data-silos-completed/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../../context';\nimport colors from 'colors';\nimport * as t from 'io-ts';\n\nimport { logger } from '../../../../logger';\nimport { markRequestDataSiloIdsCompleted } from '../../../../lib/cron';\nimport { readCsv } from '../../../../lib/requests';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation';\n\nconst RequestIdRow = t.type({\n 'Request Id': t.string,\n});\n\nexport interface MarkRequestDataSilosCompletedCommandFlags {\n auth: string;\n dataSiloId: string;\n file: string;\n transcendUrl: string;\n}\n\nexport async function markRequestDataSilosCompleted(\n this: LocalContext,\n {\n auth,\n dataSiloId,\n file,\n transcendUrl,\n }: MarkRequestDataSilosCompletedCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n logger.info(colors.magenta(`Reading \"${file}\" from disk`));\n const activeResults = readCsv(file, RequestIdRow);\n\n await markRequestDataSiloIdsCompleted({\n requestIds: activeResults.map((request) => request['Request Id']),\n transcendUrl,\n auth,\n dataSiloId,\n });\n}\n"],"mappings":"iWASA,MAAM,EAAe,EAAE,KAAK,CAC1B,aAAc,EAAE,OACjB,CAAC,CASF,eAAsB,EAEpB,CACE,OACA,aACA,OACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,EAAO,KAAK,EAAO,QAAQ,YAAY,EAAK,aAAa,CAAC,CAG1D,MAAM,EAAgC,CACpC,WAHoB,EAAQ,EAAM,EAAa,CAGrB,IAAK,GAAY,EAAQ,cAAc,CACjE,eACA,OACA,aACD,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e,r as t,t as n}from"./enums-CyFTrzXY.mjs";import"./constants-
|
|
1
|
+
import{n as e,r as t,t as n}from"./enums-CyFTrzXY.mjs";import"./constants-CnLQtIBn.mjs";import{t as r}from"./logger-Bj782ZYD.mjs";import"./buildAIIntegrationType-Bk0EbFKV.mjs";import{As as i,ai as a,i as o,js as s,wo as c}from"./syncConfigurationToTranscend-VJd0PnaZ.mjs";import{t as l}from"./done-input-validation-CcZtaz03.mjs";import{OneTrustEnrichedAssessment as u,OneTrustGetAssessmentResponse as d,OneTrustGetListOfAssessmentsResponse as f,OneTrustGetRiskResponse as p,OneTrustGetUserResponse as m}from"@transcend-io/privacy-types";import{keyBy as h,uniq as g}from"lodash-es";import{decodeCodec as _}from"@transcend-io/type-utils";import v,{createReadStream as y}from"node:fs";import b from"colors";import"yargs-parser";import x from"got";import S from"JSONStream";const C=({hostname:e,auth:t})=>x.extend({prefixUrl:`https://${e}`,headers:{accept:`application/json`,"content-type":`application/json`,authorization:`Bearer ${t}`}});Object.values(e);const w=({assessment:e,index:t,total:n,wrap:r=!0})=>{let i=``;(t===0||r)&&(i=`[
|
|
2
2
|
`);let a=JSON.stringify(e),o=n&&t<n-1&&!r?`,`:``;return i=`${i+a+o}\n`,(n&&t===n-1||r)&&(i+=`
|
|
3
3
|
]`),i},T=({file:e,assessment:t,index:n,total:i})=>{r.info(b.magenta(`Writing enriched assessment ${n+1} of ${i} to file "${e}"...`)),n===0?v.writeFileSync(e,w({assessment:t,index:n,total:i,wrap:!1})):v.appendFileSync(e,w({assessment:t,index:n,total:i,wrap:!1}))},E=async({oneTrust:e})=>{let t=0,n=1,i=0,a=[];for(;t<n;){let{body:o}=await e.get(`api/assessment/v2/assessments?page=${t}&size=2000`),{page:s,content:c}=_(f,o);a.push(...c??[]),t===0&&(n=s?.totalPages??0,i=s?.totalElements??0),t+=1,r.info(`Fetched ${a.length} of ${i} assessments.`)}return a},D=async({oneTrust:e,assessmentId:t})=>{let{body:n}=await e.get(`api/assessment/v2/assessments/${t}/export?ExcludeSkippedQuestions=false`);return _(d,n)},O=async({oneTrust:e,riskId:t})=>{let{body:n}=await e.get(`api/risk/v2/risks/${t}`);return _(p,n)},k=async({oneTrust:e,userId:t})=>{let{body:n}=await e.get(`api/scim/v2/Users/${t}`);return _(m,n)},A=({assessment:e,assessmentDetails:t,riskDetails:n,creatorDetails:r,approversDetails:i,respondentsDetails:a})=>{let o=h(n,`id`),{sections:s,createdBy:c,...l}=t,u=s.map(e=>{let{questions:t,...n}=e,r=t.map(e=>{let{risks:t,...n}=e,r=(t??[]).map(e=>{let t=o[e.riskId];return{...e,...t,level:e.level,impactLevel:e.impactLevel??0}});return{...n,risks:r}});return{...n,questions:r}}),d={...c,active:r?.active??!1,userType:r?.userType??`Internal`,emails:r?.emails??[],title:r?.title??null,givenName:r?.name.givenName??null,familyName:r?.name.familyName??null},f=h(i,`id`),p=t.approvers.flatMap(e=>f[e.id]?[{...e,approver:{...e.approver,active:f[e.id].active,userType:f[e.id].userType,emails:f[e.id].emails,title:f[e.id].title,givenName:f[e.id].name.givenName??null,familyName:f[e.id].name.familyName??null}}]:[]),m=h(a,`id`),g=t.respondents.filter(e=>!e.name.includes(`@`)).flatMap(e=>m[e.id]?[{...e,active:m[e.id].active,userType:m[e.id].userType,emails:m[e.id].emails,title:m[e.id].title,givenName:m[e.id].name.givenName??null,familyName:m[e.id].name.familyName??null}]:[]);return{...e,...l,approvers:p,respondents:g,createdBy:d,sections:u}},j=async({transcend:e,assessment:t,total:n,index:i})=>{r.info(b.magenta(`Writing enriched assessment ${i+1} ${n?`of ${n} `:` `}to Transcend...`));let a={json:w({assessment:t,index:i,total:n})};try{await o(e,c,{input:a})}catch{r.error(b.red(`Failed to sync assessment ${i+1} ${n?`of ${n} `:` `}to Transcend.\n\tAssessment Title: ${t.name}. Template Title: ${t.template.name}\n`))}},M=async({oneTrust:e,file:t,dryRun:n,transcend:a})=>{r.info(`Getting list of all assessments from OneTrust...`);let o=await E({oneTrust:e}),c={};await s(Array.from({length:Math.ceil(o.length/5)},(e,t)=>o.slice(t*5,(t+1)*5)),async(l,u)=>{let d=[];await i(l,async(t,n)=>{let a=5*u+n+1;r.info(`[assessment ${a} of ${o.length}]: fetching details...`);let{templateName:s,assessmentId:l}=t,f=await D({oneTrust:e,assessmentId:l}),p=f.createdBy.id,m=c[p];if(!m){r.info(`[assessment ${a} of ${o.length}]: fetching creator...`);try{m=await k({oneTrust:e,userId:p}),c[p]=m}catch{r.warn(b.yellow(`[assessment ${a} of ${o.length}]: failed to fetch form creator.\tcreatorId: ${p}. Assessment Title: ${t.name}. Template Title: ${s}`))}}let{approvers:h}=f,_=[];h.length>0&&(r.info(`[assessment ${a} of ${o.length}]: fetching approvers...`),_=await i(h.map(({id:e})=>e),async n=>{try{let t=c[n];return t||(t=await k({oneTrust:e,userId:n}),c[n]=t),[t]}catch{return r.warn(b.yellow(`[assessment ${a} of ${o.length}]: failed to fetch a form approver.\tapproverId: ${n}. Assessment Title: ${t.name}. Template Title: ${s}`)),[]}},{concurrency:5}));let{respondents:v}=f,y=v.filter(e=>!e.name.includes(`@`)),x=[];y.length>0&&(r.info(`[assessment ${a} of ${o.length}]: fetching respondents...`),x=await i(y.map(({id:e})=>e),async n=>{try{let t=c[n];return t||(t=await k({oneTrust:e,userId:n}),c[n]=t),[t]}catch{return r.warn(b.yellow(`[assessment ${a} of ${o.length}]: failed to fetch a respondent.\trespondentId: ${n}. Assessment Title: ${t.name}. Template Title: ${s}`)),[]}},{concurrency:5}));let S=[],C=g(f.sections.flatMap(e=>e.questions.flatMap(e=>(e.risks??[]).flatMap(e=>e.riskId))));C.length>0&&(r.info(`[assessment ${a} of ${o.length}]: fetching risks...`),S=await i(C,t=>O({oneTrust:e,riskId:t}),{concurrency:5}));let w=A({assessment:t,assessmentDetails:f,riskDetails:S,creatorDetails:m,approversDetails:_.flat(),respondentsDetails:x.flat()});d.push(w)},{concurrency:5}),await s(d,async(e,r)=>{let i=u*5+r;n&&t?T({assessment:e,index:i,total:o.length,file:t}):a&&await j({assessment:e,transcend:a,total:o.length,index:i})})})},N=({transcend:e,file:t})=>(r.info(`Getting list of all assessments from file ${t}...`),new Promise((n,i)=>{let a=y(t,{encoding:`utf-8`,highWaterMark:64*1024}),o=S.parse(`*`),s=0;a.pipe(o),o.on(`data`,async n=>{try{o.pause(),await j({assessment:_(u,n),transcend:e,index:s}),s+=1,o.resume()}catch(e){r.error(b.red(`Failed to parse the assessment ${s} from file '${t}': ${e.message}.`))}}),o.on(`end`,()=>{r.info(`Finished processing ${s} assessments from file ${t}`),n()}),o.on(`error`,e=>{r.error(b.red(`Error parsing file '${t}': ${e.message}`)),i(e)}),a.on(`error`,e=>{r.error(b.red(`Error reading file '${t}': ${e.message}`)),i(e)})}));async function P({hostname:i,oneTrustAuth:o,source:s,transcendAuth:c,transcendUrl:u,resource:d,file:f,dryRun:p,debug:m}){if(!p&&!c)throw Error('Must specify a "transcendAuth" parameter to sync resources to Transcend. e.g. --transcendAuth=${TRANSCEND_API_KEY}');if(p&&!f)throw Error(`Must set a "file" parameter when "dryRun" is "true". e.g. --file=./oneTrustAssessments.json`);if(f){let e=f.split(`.`);if(e.length<2)throw Error(`The "file" parameter has an invalid format. Expected a path with extensions. e.g. --file=./pathToFile.json.`);if(e.at(-1)!==n.Json)throw Error(`Expected the format of the "file" parameters '${f}' to be '${n.Json}', but got '${e.at(-1)}'.`)}if(s===t.OneTrust){if(!i)throw Error(`Missing required parameter "hostname". e.g. --hostname=customer.my.onetrust.com`);if(!o)throw Error(`Missing required parameter "oneTrustAuth". e.g. --oneTrustAuth=$ONE_TRUST_AUTH_TOKEN`)}else{if(!f)throw Error(`Must specify a "file" parameter to read the OneTrust assessments from. e.g. --source=./oneTrustAssessments.json`);if(p)throw Error(`Cannot read and write to a file simultaneously. Emit the "source" parameter or set it to ${t.OneTrust} if "dryRun" is enabled.`)}l(this.process.exit);let h=i&&o?C({hostname:i,auth:o}):void 0,g=u&&c?a(u,c):void 0;try{d===e.Assessments&&(s===t.OneTrust&&h?await M({oneTrust:h,file:f,dryRun:p,...g&&{transcend:g}}):s===t.File&&f&&g&&await N({file:f,transcend:g}))}catch(e){throw Error(`An error occurred syncing the resource ${d} from OneTrust: ${m?e.stack:e.message}`)}r.info(b.green(`Successfully synced OneTrust ${d} to ${p?`disk at "${f}"`:`Transcend`}!`))}export{P as syncOt};
|
|
4
|
-
//# sourceMappingURL=impl-
|
|
4
|
+
//# sourceMappingURL=impl-BwX-evfW2.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-BraVBCrF2.mjs","names":[],"sources":["../src/lib/oneTrust/createOneTrustGotInstance.ts","../src/lib/oneTrust/helpers/parseCliSyncOtArguments.ts","../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/commands/migration/sync-ot/impl.ts"],"sourcesContent":["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 { logger } from '../../../logger';\nimport colors from 'colors';\nimport yargs from 'yargs-parser';\nimport {\n OneTrustFileFormat,\n OneTrustPullResource,\n OneTrustPullSource,\n} from '../../../enums';\n\nconst VALID_RESOURCES = Object.values(OneTrustPullResource);\n\ninterface OneTrustCliArguments {\n /** The name of the file to write the resources to */\n file: string;\n /** The OneTrust hostname to send the requests to */\n hostname?: string;\n /** The OAuth Bearer token used to authenticate the requests to OneTrust */\n oneTrustAuth?: string;\n /** The Transcend API key to authenticate the requests to Transcend */\n transcendAuth: string;\n /** The Transcend URL where to forward requests */\n transcendUrl: string;\n /** The resource to pull from OneTrust */\n resource: OneTrustPullResource;\n /** Whether to enable debugging while reporting errors */\n debug: boolean;\n /** Whether to export the resource into a file rather than push to transcend */\n dryRun: boolean;\n /** Where to read the OneTrust resource from */\n source: OneTrustPullSource;\n}\n\n/**\n * Parse the command line arguments\n *\n * @returns the parsed arguments\n */\nexport const parseCliSyncOtArguments = (): OneTrustCliArguments => {\n const {\n file,\n hostname,\n oneTrustAuth,\n resource,\n debug,\n dryRun,\n transcendAuth,\n transcendUrl,\n source,\n } = yargs(process.argv.slice(2), {\n string: [\n 'file',\n 'hostname',\n 'oneTrustAuth',\n 'resource',\n 'dryRun',\n 'transcendAuth',\n 'transcendUrl',\n 'source',\n ],\n boolean: ['debug', 'dryRun'],\n default: {\n resource: OneTrustPullResource.Assessments,\n debug: false,\n dryRun: false,\n transcendUrl: 'https://api.transcend.io',\n source: OneTrustPullSource.OneTrust,\n },\n });\n\n // Must be able to authenticate to transcend to sync resources to it\n if (!dryRun && !transcendAuth) {\n logger.error(\n colors.red(\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 return process.exit(1);\n }\n if (!dryRun && !transcendUrl) {\n logger.error(\n colors.red(\n // eslint-disable-next-line max-len\n 'Must specify a \"transcendUrl\" parameter to sync resources to Transcend. e.g. --transcendUrl=https://api.transcend.io',\n ),\n );\n return process.exit(1);\n }\n\n // If trying to sync to disk, must specify a file path\n if (dryRun && !file) {\n logger.error(\n colors.red(\n 'Must set a \"file\" parameter when \"dryRun\" is \"true\". e.g. --file=./oneTrustAssessments.json',\n ),\n );\n return process.exit(1);\n }\n\n if (file) {\n const splitFile = file.split('.');\n if (splitFile.length < 2) {\n logger.error(\n colors.red(\n 'The \"file\" parameter has an invalid format. Expected a path with extensions. e.g. --file=./pathToFile.json.',\n ),\n );\n return process.exit(1);\n }\n if (splitFile.at(-1) !== OneTrustFileFormat.Json) {\n logger.error(\n colors.red(\n `Expected the format of the \"file\" parameters '${file}' to be '${\n OneTrustFileFormat.Json\n }', but got '${splitFile.at(-1)}'.`,\n ),\n );\n return process.exit(1);\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 logger.error(\n colors.red(\n 'Missing required parameter \"hostname\". e.g. --hostname=customer.my.onetrust.com',\n ),\n );\n return process.exit(1);\n }\n // must specify the OneTrust auth\n if (!oneTrustAuth) {\n logger.error(\n colors.red(\n 'Missing required parameter \"oneTrustAuth\". e.g. --oneTrustAuth=$ONE_TRUST_AUTH_TOKEN',\n ),\n );\n return process.exit(1);\n }\n } else {\n // if reading the assessments from a file, must specify a file to read from\n if (!file) {\n logger.error(\n colors.red(\n 'Must specify a \"file\" parameter to read the OneTrust assessments from. e.g. --source=./oneTrustAssessments.json',\n ),\n );\n return process.exit(1);\n }\n\n // Cannot try reading from file and save assessments to a file simultaneously\n if (dryRun) {\n logger.error(\n colors.red(\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 return process.exit(1);\n }\n }\n\n if (!VALID_RESOURCES.includes(resource)) {\n logger.error(\n colors.red(\n `Received invalid resource value: \"${resource}\". Allowed: ${VALID_RESOURCES.join(\n ',',\n )}`,\n ),\n );\n return process.exit(1);\n }\n\n return {\n file,\n ...(hostname && { hostname }),\n ...(oneTrustAuth && { oneTrustAuth }),\n resource,\n debug,\n dryRun,\n transcendAuth,\n transcendUrl,\n source,\n };\n};\n","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 { logger } from '../../../logger';\nimport colors from 'colors';\nimport fs from 'node:fs';\nimport { oneTrustAssessmentToJson } from './oneTrustAssessmentToJson';\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\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(\n `Writing enriched assessment ${\n index + 1\n } of ${total} to file \"${file}\"...`,\n ),\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 { Got } from 'got';\nimport { logger } from '../../../logger';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport {\n OneTrustAssessment,\n OneTrustGetListOfAssessmentsResponse,\n} from '@transcend-io/privacy-types';\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(\n OneTrustGetListOfAssessmentsResponse,\n body,\n );\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(\n `Fetched ${allAssessments.length} of ${totalElements} assessments.`,\n );\n }\n\n return allAssessments;\n};\n","import { Got } from 'got';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { OneTrustGetAssessmentResponse } from '@transcend-io/privacy-types';\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 { Got } from 'got';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { OneTrustGetRiskResponse } from '@transcend-io/privacy-types';\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 { Got } from 'got';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { OneTrustGetUserResponse } from '@transcend-io/privacy-types';\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(\n (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:\n approverDetailsById[originalApprover.id].name.givenName ??\n null,\n familyName:\n approverDetailsById[originalApprover.id].name.familyName ??\n 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:\n respondentsDetailsById[respondent.id].name.givenName ?? null,\n familyName:\n 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 { logger } from '../../../logger';\nimport colors from 'colors';\nimport { GraphQLClient } from 'graphql-request';\nimport {\n IMPORT_ONE_TRUST_ASSESSMENT_FORMS,\n makeGraphQLRequest,\n} from '../../graphql';\nimport { ImportOnetrustAssessmentsInput } from '../../../codecs';\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport { oneTrustAssessmentToJson } from './oneTrustAssessmentToJson';\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} ${\n total ? `of ${total} ` : ' '\n }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 input,\n });\n } catch (e) {\n logger.error(\n colors.red(\n `Failed to sync assessment ${index + 1} ${\n total ? `of ${total} ` : ' '\n }to Transcend.\\n` +\n `\\tAssessment Title: ${assessment.name}. Template Title: ${assessment.template.name}\\n`,\n ),\n );\n }\n};\n","import type { Got } from 'got';\nimport colors from 'colors';\nimport {\n getListOfOneTrustAssessments,\n getOneTrustAssessment,\n getOneTrustRisk,\n getOneTrustUser,\n} from '../endpoints';\nimport { mapSeries, map } from '../../bluebird';\nimport { logger } from '../../../logger';\nimport {\n OneTrustAssessmentQuestion,\n OneTrustAssessmentSection,\n OneTrustEnrichedAssessment,\n OneTrustGetRiskResponse,\n OneTrustGetUserResponse,\n} from '@transcend-io/privacy-types';\nimport { uniq } from 'lodash-es';\nimport { enrichOneTrustAssessment } from './enrichOneTrustAssessment';\nimport { syncOneTrustAssessmentToDisk } from './syncOneTrustAssessmentToDisk';\nimport { GraphQLClient } from 'graphql-request';\nimport { syncOneTrustAssessmentToTranscend } from './syncOneTrustAssessmentToTranscend';\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 (e) {\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 );\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 (e) {\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 );\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(\n (r) => !r.name.includes('@'),\n );\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 (e) {\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 );\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(\n batchEnrichedAssessments,\n 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};\n","import { decodeCodec } from '@transcend-io/type-utils';\nimport colors from 'colors';\nimport { logger } from '../../../logger';\nimport JSONStream from 'JSONStream';\n\nimport { createReadStream } from 'node:fs';\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport { syncOneTrustAssessmentToTranscend } from './syncOneTrustAssessmentToTranscend';\nimport { GraphQLClient } from 'graphql-request';\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(\n OneTrustEnrichedAssessment,\n assessment,\n );\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(\n `Failed to parse the assessment ${index} from file '${file}': ${e.message}.`,\n ),\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(\n colors.red(`Error parsing file '${file}': ${error.message}`),\n );\n reject(error);\n });\n\n fileStream.on('error', (error) => {\n logger.error(\n colors.red(`Error reading file '${file}': ${error.message}`),\n );\n reject(error);\n });\n });\n};\n","import type { LocalContext } from '../../../context';\nimport { logger } from '../../../logger';\nimport colors from 'colors';\nimport { createOneTrustGotInstance } from '../../../lib/oneTrust';\nimport {\n OneTrustFileFormat,\n OneTrustPullResource,\n OneTrustPullSource,\n} from '../../../enums';\nimport { buildTranscendGraphQLClient } from '../../../lib/graphql';\nimport {\n syncOneTrustAssessmentsFromFile,\n syncOneTrustAssessmentsFromOneTrust,\n} from '../../../lib/oneTrust/helpers';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\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 ${\n dryRun ? `disk at \"${file}\"` : 'Transcend'\n }!`,\n ),\n );\n}\n"],"mappings":"kwBAQA,MAAa,GAA6B,CACxC,WACA,UAOA,EAAI,OAAO,CACT,UAAW,WAAW,IACtB,QAAS,CACP,OAAQ,mBACR,eAAgB,mBAChB,cAAe,UAAU,IAC1B,CACF,CAAC,CCfoB,OAAO,OAAO,EAAqB,CCD3D,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,GC9BI,GAAgC,CAC3C,OACA,aACA,QACA,WAUU,CACV,EAAO,KACL,EAAO,QACL,+BACE,EAAQ,EACT,MAAM,EAAM,YAAY,EAAK,MAC/B,CACF,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,ECvCQ,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D,EAAQ,EAAI,MAAQ,EAAI,UAE3B,CAIH,EAAO,KACL,EAAO,MACL,gCAAgC,EAAS,MACvC,EAAS,YAAY,EAAK,GAAK,YAChC,GACF,CACF"}
|
|
1
|
+
{"version":3,"file":"impl-BwX-evfW2.mjs","names":[],"sources":["../src/lib/oneTrust/createOneTrustGotInstance.ts","../src/lib/oneTrust/helpers/parseCliSyncOtArguments.ts","../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/commands/migration/sync-ot/impl.ts"],"sourcesContent":["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 { logger } from '../../../logger';\nimport colors from 'colors';\nimport yargs from 'yargs-parser';\nimport {\n OneTrustFileFormat,\n OneTrustPullResource,\n OneTrustPullSource,\n} from '../../../enums';\n\nconst VALID_RESOURCES = Object.values(OneTrustPullResource);\n\ninterface OneTrustCliArguments {\n /** The name of the file to write the resources to */\n file: string;\n /** The OneTrust hostname to send the requests to */\n hostname?: string;\n /** The OAuth Bearer token used to authenticate the requests to OneTrust */\n oneTrustAuth?: string;\n /** The Transcend API key to authenticate the requests to Transcend */\n transcendAuth: string;\n /** The Transcend URL where to forward requests */\n transcendUrl: string;\n /** The resource to pull from OneTrust */\n resource: OneTrustPullResource;\n /** Whether to enable debugging while reporting errors */\n debug: boolean;\n /** Whether to export the resource into a file rather than push to transcend */\n dryRun: boolean;\n /** Where to read the OneTrust resource from */\n source: OneTrustPullSource;\n}\n\n/**\n * Parse the command line arguments\n *\n * @returns the parsed arguments\n */\nexport const parseCliSyncOtArguments = (): OneTrustCliArguments => {\n const {\n file,\n hostname,\n oneTrustAuth,\n resource,\n debug,\n dryRun,\n transcendAuth,\n transcendUrl,\n source,\n } = yargs(process.argv.slice(2), {\n string: [\n 'file',\n 'hostname',\n 'oneTrustAuth',\n 'resource',\n 'dryRun',\n 'transcendAuth',\n 'transcendUrl',\n 'source',\n ],\n boolean: ['debug', 'dryRun'],\n default: {\n resource: OneTrustPullResource.Assessments,\n debug: false,\n dryRun: false,\n transcendUrl: 'https://api.transcend.io',\n source: OneTrustPullSource.OneTrust,\n },\n });\n\n // Must be able to authenticate to transcend to sync resources to it\n if (!dryRun && !transcendAuth) {\n logger.error(\n colors.red(\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 return process.exit(1);\n }\n if (!dryRun && !transcendUrl) {\n logger.error(\n colors.red(\n // eslint-disable-next-line max-len\n 'Must specify a \"transcendUrl\" parameter to sync resources to Transcend. e.g. --transcendUrl=https://api.transcend.io',\n ),\n );\n return process.exit(1);\n }\n\n // If trying to sync to disk, must specify a file path\n if (dryRun && !file) {\n logger.error(\n colors.red(\n 'Must set a \"file\" parameter when \"dryRun\" is \"true\". e.g. --file=./oneTrustAssessments.json',\n ),\n );\n return process.exit(1);\n }\n\n if (file) {\n const splitFile = file.split('.');\n if (splitFile.length < 2) {\n logger.error(\n colors.red(\n 'The \"file\" parameter has an invalid format. Expected a path with extensions. e.g. --file=./pathToFile.json.',\n ),\n );\n return process.exit(1);\n }\n if (splitFile.at(-1) !== OneTrustFileFormat.Json) {\n logger.error(\n colors.red(\n `Expected the format of the \"file\" parameters '${file}' to be '${\n OneTrustFileFormat.Json\n }', but got '${splitFile.at(-1)}'.`,\n ),\n );\n return process.exit(1);\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 logger.error(\n colors.red(\n 'Missing required parameter \"hostname\". e.g. --hostname=customer.my.onetrust.com',\n ),\n );\n return process.exit(1);\n }\n // must specify the OneTrust auth\n if (!oneTrustAuth) {\n logger.error(\n colors.red(\n 'Missing required parameter \"oneTrustAuth\". e.g. --oneTrustAuth=$ONE_TRUST_AUTH_TOKEN',\n ),\n );\n return process.exit(1);\n }\n } else {\n // if reading the assessments from a file, must specify a file to read from\n if (!file) {\n logger.error(\n colors.red(\n 'Must specify a \"file\" parameter to read the OneTrust assessments from. e.g. --source=./oneTrustAssessments.json',\n ),\n );\n return process.exit(1);\n }\n\n // Cannot try reading from file and save assessments to a file simultaneously\n if (dryRun) {\n logger.error(\n colors.red(\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 return process.exit(1);\n }\n }\n\n if (!VALID_RESOURCES.includes(resource)) {\n logger.error(\n colors.red(\n `Received invalid resource value: \"${resource}\". Allowed: ${VALID_RESOURCES.join(\n ',',\n )}`,\n ),\n );\n return process.exit(1);\n }\n\n return {\n file,\n ...(hostname && { hostname }),\n ...(oneTrustAuth && { oneTrustAuth }),\n resource,\n debug,\n dryRun,\n transcendAuth,\n transcendUrl,\n source,\n };\n};\n","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 { logger } from '../../../logger';\nimport colors from 'colors';\nimport fs from 'node:fs';\nimport { oneTrustAssessmentToJson } from './oneTrustAssessmentToJson';\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\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(\n `Writing enriched assessment ${\n index + 1\n } of ${total} to file \"${file}\"...`,\n ),\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 { Got } from 'got';\nimport { logger } from '../../../logger';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport {\n OneTrustAssessment,\n OneTrustGetListOfAssessmentsResponse,\n} from '@transcend-io/privacy-types';\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(\n OneTrustGetListOfAssessmentsResponse,\n body,\n );\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(\n `Fetched ${allAssessments.length} of ${totalElements} assessments.`,\n );\n }\n\n return allAssessments;\n};\n","import { Got } from 'got';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { OneTrustGetAssessmentResponse } from '@transcend-io/privacy-types';\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 { Got } from 'got';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { OneTrustGetRiskResponse } from '@transcend-io/privacy-types';\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 { Got } from 'got';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { OneTrustGetUserResponse } from '@transcend-io/privacy-types';\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(\n (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:\n approverDetailsById[originalApprover.id].name.givenName ??\n null,\n familyName:\n approverDetailsById[originalApprover.id].name.familyName ??\n 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:\n respondentsDetailsById[respondent.id].name.givenName ?? null,\n familyName:\n 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 { logger } from '../../../logger';\nimport colors from 'colors';\nimport { GraphQLClient } from 'graphql-request';\nimport {\n IMPORT_ONE_TRUST_ASSESSMENT_FORMS,\n makeGraphQLRequest,\n} from '../../graphql';\nimport { ImportOnetrustAssessmentsInput } from '../../../codecs';\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport { oneTrustAssessmentToJson } from './oneTrustAssessmentToJson';\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} ${\n total ? `of ${total} ` : ' '\n }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 input,\n });\n } catch (e) {\n logger.error(\n colors.red(\n `Failed to sync assessment ${index + 1} ${\n total ? `of ${total} ` : ' '\n }to Transcend.\\n` +\n `\\tAssessment Title: ${assessment.name}. Template Title: ${assessment.template.name}\\n`,\n ),\n );\n }\n};\n","import type { Got } from 'got';\nimport colors from 'colors';\nimport {\n getListOfOneTrustAssessments,\n getOneTrustAssessment,\n getOneTrustRisk,\n getOneTrustUser,\n} from '../endpoints';\nimport { mapSeries, map } from '../../bluebird';\nimport { logger } from '../../../logger';\nimport {\n OneTrustAssessmentQuestion,\n OneTrustAssessmentSection,\n OneTrustEnrichedAssessment,\n OneTrustGetRiskResponse,\n OneTrustGetUserResponse,\n} from '@transcend-io/privacy-types';\nimport { uniq } from 'lodash-es';\nimport { enrichOneTrustAssessment } from './enrichOneTrustAssessment';\nimport { syncOneTrustAssessmentToDisk } from './syncOneTrustAssessmentToDisk';\nimport { GraphQLClient } from 'graphql-request';\nimport { syncOneTrustAssessmentToTranscend } from './syncOneTrustAssessmentToTranscend';\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 (e) {\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 );\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 (e) {\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 );\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(\n (r) => !r.name.includes('@'),\n );\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 (e) {\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 );\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(\n batchEnrichedAssessments,\n 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};\n","import { decodeCodec } from '@transcend-io/type-utils';\nimport colors from 'colors';\nimport { logger } from '../../../logger';\nimport JSONStream from 'JSONStream';\n\nimport { createReadStream } from 'node:fs';\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport { syncOneTrustAssessmentToTranscend } from './syncOneTrustAssessmentToTranscend';\nimport { GraphQLClient } from 'graphql-request';\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(\n OneTrustEnrichedAssessment,\n assessment,\n );\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(\n `Failed to parse the assessment ${index} from file '${file}': ${e.message}.`,\n ),\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(\n colors.red(`Error parsing file '${file}': ${error.message}`),\n );\n reject(error);\n });\n\n fileStream.on('error', (error) => {\n logger.error(\n colors.red(`Error reading file '${file}': ${error.message}`),\n );\n reject(error);\n });\n });\n};\n","import type { LocalContext } from '../../../context';\nimport { logger } from '../../../logger';\nimport colors from 'colors';\nimport { createOneTrustGotInstance } from '../../../lib/oneTrust';\nimport {\n OneTrustFileFormat,\n OneTrustPullResource,\n OneTrustPullSource,\n} from '../../../enums';\nimport { buildTranscendGraphQLClient } from '../../../lib/graphql';\nimport {\n syncOneTrustAssessmentsFromFile,\n syncOneTrustAssessmentsFromOneTrust,\n} from '../../../lib/oneTrust/helpers';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\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 ${\n dryRun ? `disk at \"${file}\"` : 'Transcend'\n }!`,\n ),\n );\n}\n"],"mappings":"kwBAQA,MAAa,GAA6B,CACxC,WACA,UAOA,EAAI,OAAO,CACT,UAAW,WAAW,IACtB,QAAS,CACP,OAAQ,mBACR,eAAgB,mBAChB,cAAe,UAAU,IAC1B,CACF,CAAC,CCfoB,OAAO,OAAO,EAAqB,CCD3D,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,GC9BI,GAAgC,CAC3C,OACA,aACA,QACA,WAUU,CACV,EAAO,KACL,EAAO,QACL,+BACE,EAAQ,EACT,MAAM,EAAM,YAAY,EAAK,MAC/B,CACF,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,ECvCQ,EAA+B,MAAO,CACjD,c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,EAAI,UAE3B,CAIH,EAAO,KACL,EAAO,MACL,gCAAgC,EAAS,MACvC,EAAS,YAAY,EAAK,GAAK,YAChC,GACF,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import"./enums-CyFTrzXY.mjs";import"./constants-CnLQtIBn.mjs";import"./logger-Bj782ZYD.mjs";import"./buildAIIntegrationType-Bk0EbFKV.mjs";import{V as e}from"./syncConfigurationToTranscend-VJd0PnaZ.mjs";import{t}from"./done-input-validation-CcZtaz03.mjs";async function n({auth:n,transcendUrl:r,enricherIds:i}){t(this.process.exit),await e({transcendUrl:r,auth:n,enricherIds:i})}export{n as skipPreflightJobs};
|
|
2
|
+
//# sourceMappingURL=impl-C-wzeAib2.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-C-wzeAib2.mjs","names":["skipPreflightJobsHelper"],"sources":["../src/commands/request/skip-preflight-jobs/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport { skipPreflightJobs as skipPreflightJobsHelper } from '../../../lib/requests';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface SkipPreflightJobsCommandFlags {\n auth: string;\n enricherIds: string[];\n transcendUrl: string;\n}\n\nexport async function skipPreflightJobs(\n this: LocalContext,\n { auth, transcendUrl, enricherIds }: SkipPreflightJobsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await skipPreflightJobsHelper({\n transcendUrl,\n auth,\n enricherIds,\n });\n}\n"],"mappings":"8PAUA,eAAsB,EAEpB,CAAE,OAAM,eAAc,eACP,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAMA,EAAwB,CAC5B,eACA,OACA,cACD,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./enums-CyFTrzXY.mjs";import"./constants-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import"./enums-CyFTrzXY.mjs";import"./constants-CnLQtIBn.mjs";import"./logger-Bj782ZYD.mjs";import"./buildAIIntegrationType-Bk0EbFKV.mjs";import"./syncConfigurationToTranscend-VJd0PnaZ.mjs";import{t as e}from"./manual-enrichment-B6lW5kAX.mjs";import{t}from"./done-input-validation-CcZtaz03.mjs";async function n({auth:n,transcendUrl:r,file:i,enricherId:a,concurrency:o,markSilent:s,sombraAuth:c}){t(this.process.exit),await e({file:i,transcendUrl:r,enricherId:a,concurrency:o,markSilent:s,auth:n,sombraAuth:c})}export{n as pushIdentifiers};
|
|
2
|
+
//# sourceMappingURL=impl-C61PYfk12.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-C61PYfk12.mjs","names":[],"sources":["../src/commands/request/preflight/push-identifiers/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../../context';\nimport { pushManualEnrichmentIdentifiersFromCsv } from '../../../../lib/manual-enrichment';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation';\n\nexport interface PushIdentifiersCommandFlags {\n auth: string;\n enricherId: string;\n sombraAuth?: string;\n transcendUrl: string;\n file: string;\n markSilent: boolean;\n concurrency: number;\n}\n\nexport async function pushIdentifiers(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n file,\n enricherId,\n concurrency,\n markSilent,\n sombraAuth,\n }: PushIdentifiersCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await pushManualEnrichmentIdentifiersFromCsv({\n file,\n transcendUrl,\n enricherId,\n concurrency,\n markSilent,\n auth,\n sombraAuth,\n });\n}\n"],"mappings":"uSAcA,eAAsB,EAEpB,CACE,OACA,eACA,OACA,aACA,cACA,aACA,cAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAM,EAAuC,CAC3C,OACA,eACA,aACA,cACA,aACA,OACA,aACD,CAAC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import"./enums-CyFTrzXY.mjs";import"./constants-CnLQtIBn.mjs";import{t as e}from"./logger-Bj782ZYD.mjs";import"./buildAIIntegrationType-Bk0EbFKV.mjs";import{O as t}from"./syncConfigurationToTranscend-VJd0PnaZ.mjs";import{a as n,i as r,n as i,o as a,r as o,s,t as c}from"./pooling-CazydwlD.mjs";import{t as l}from"./done-input-validation-CcZtaz03.mjs";import{createReadStream as u,createWriteStream as d,readdirSync as f,statSync as p}from"node:fs";import{basename as m,dirname as h,join as g}from"node:path";import _ from"colors";import*as v from"fast-csv";import{once as y}from"node:events";import{mkdir as b,readdir as x,stat as S,unlink as C}from"node:fs/promises";import{pipeline as w}from"node:stream/promises";import{Transform as T}from"node:stream";import{Parser as E}from"csv-parse";function D(t,n){t||(e.error(_.red(`A --directory must be provided.`)),n.process.exit(1));let r=[];try{r=f(t).filter(e=>e.endsWith(`.csv`)).map(e=>g(t,e)).filter(e=>{try{return p(e).isFile()}catch{return!1}})}catch(r){e.error(_.red(`Failed to read directory: ${t}`)),e.error(_.red(r.message)),n.process.exit(1)}return r.length===0&&(e.error(_.red(`No CSV files found in directory: ${t}`)),n.process.exit(1)),e.info(_.green(`Found ${r.length} CSV files in ${t}`)),r}function O(e,t){let n=d(e),r=v.format({headers:t,writeHeaders:!0,objectMode:!0});return r.pipe(n),{async write(e){r.write(e)||await y(r,`drain`)},async end(){let e=Promise.all([y(n,`finish`)]);r.end(),await e}}}function k(e){return String(e).padStart(4,`0`)}function A(e){return Buffer.byteLength(Object.values(e).map(e=>e==null?``:String(e)).join(`,`),`utf8`)}async function j(t){let{filePath:n,outputDir:r,clearOutputDir:i,chunkSizeMB:a,onProgress:o,reportEveryMs:s=500}=t,{size:c}=await S(n),l=0;e.info(_.magenta(`Chunking ${n} into ~${a}MB files...`));let d=Math.floor(a*1024*1024),f=m(n,`.csv`),p=r||h(n);if(e.info(_.magenta(`Output directory: ${p}`)),await b(p,{recursive:!0}),i){e.warn(_.yellow(`Clearing output directory: ${p}`));let t=await x(p);await Promise.all(t.filter(e=>e.startsWith(`${f}_chunk_`)&&e.endsWith(`.csv`)).map(e=>C(g(p,e))))}let v=null,y=null,D=0,j=1,M=0,N=new E({columns:!1,skip_empty_lines:!0}),P=0,F=0,I=()=>{let e=F>0?P/F:0,t=e>0?Math.max(D,Math.ceil(c/e)):void 0;o(D,t),l=Date.now()};I();let L=null,R=()=>g(p,`${f}_chunk_${k(j)}.csv`),z=new T({objectMode:!0,async transform(t,n,r){try{if(!v){v=t.slice(0),y=v.length,L=O(R(),v),r();return}y!==null&&t.length!==y&&e.warn(_.yellow(`Row has ${t.length} cols; expected ${y}`)),D+=1,D%25e4==0&&o(D);let n=Object.fromEntries(v.map((e,n)=>[e,t[n]])),i=A(n);P+=i,F+=1,Date.now()-l>=s&&I(),L&&M>0&&M+i>d&&(await L.end(),j+=1,M=0,e.info(_.green(`Rolling to chunk ${j} after ${D.toLocaleString()} rows.`)),L=O(R(),v)),L||=O(R(),v),await L.write(n),M+=i,r()}catch(e){r(e)}},async flush(e){try{L&&=(await L.end(),null),I(),e()}catch(t){e(t)}}});await w(u(n),N,z),o(D),e.info(_.green(`Chunked ${n} into ${j} file(s); processed ${D.toLocaleString()} rows.`))}async function M(){let n=Number(process.env.WORKER_ID||`0`);e.info(`[w${n}] ready pid=${process.pid}`),process.send?.({type:`ready`}),process.on(`message`,async r=>{if(!r||typeof r!=`object`||(r.type===`shutdown`&&process.exit(0),r.type!==`task`))return;let{filePath:i,options:a}=r.payload,{outputDir:o,clearOutputDir:s,chunkSizeMB:c}=a;try{await j({filePath:i,outputDir:o,clearOutputDir:s,chunkSizeMB:c,onProgress:(e,t)=>process.send?.({type:`progress`,payload:{filePath:i,processed:e,total:t}})}),process.send?.({type:`result`,payload:{ok:!0,filePath:i}})}catch(r){let a=t(r);e.error(`[w${n}] ERROR ${i}: ${a}`),process.send?.({type:`result`,payload:{ok:!1,filePath:i,error:a}})}}),await new Promise(()=>{})}function N(e){return o(e)}function P(e){return r(e)}const F={renderHeader:N,renderWorkers:P};function I(){return typeof __filename<`u`?__filename:process.argv[1]}async function L(t){l(this.process.exit);let{directory:r,outputDir:o,clearOutputDir:u,chunkSizeMB:d,concurrency:f,viewerMode:p}=t,m=D(r,this),{poolSize:h,cpuCount:g}=s(f,m.length);e.info(_.green(`Chunking ${m.length} CSV file(s) with pool size ${h} (CPU=${g})`));let v=m.map(e=>({filePath:e,options:{outputDir:o,clearOutputDir:u,chunkSizeMB:d}}));await i({title:`Chunk CSV - ${r}`,baseDir:r||o||process.cwd(),childFlag:a,childModulePath:I(),poolSize:h,cpuCount:g,filesTotal:m.length,hooks:{nextTask:()=>v.shift(),taskLabel:e=>e.filePath,initTotals:()=>({}),initSlotProgress:()=>void 0,onProgress:e=>e,onResult:(e,t)=>({totals:e,ok:!!t.ok}),postProcess:async()=>{}},viewerMode:p,render:e=>n(e,F,p),extraKeyHandler:({logsBySlot:e,repaint:t,setPaused:n})=>c({logsBySlot:e,repaint:t,setPaused:n})})}process.argv.includes(`--as-child`)&&M().catch(t=>{e.error(t),process.exit(1)});export{L as chunkCsv};
|
|
2
|
+
//# sourceMappingURL=impl-CAuNpuF2.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"impl-CAuNpuF2.mjs","names":[],"sources":["../src/lib/helpers/collectCsvFilesOrExit.ts","../src/lib/helpers/chunkOneCsvFile.ts","../src/commands/admin/chunk-csv/worker.ts","../src/commands/admin/chunk-csv/ui/plugin.ts","../src/commands/admin/chunk-csv/impl.ts"],"sourcesContent":["import { join } from 'node:path';\nimport { readdirSync, statSync } from 'node:fs';\nimport colors from 'colors';\nimport { logger } from '../../logger';\nimport type { LocalContext } from '../../context';\n\n/**\n * Validate flags and collect CSV file paths from a directory.\n * On validation error, the provided `exit` function is called.\n *\n * @param directory - the directory containing CSV files\n * @param localContext - the context of the command, used for logging and exit\n * @returns an array of valid CSV file paths\n */\nexport function collectCsvFilesOrExit(\n directory: string | undefined,\n localContext: LocalContext,\n): string[] {\n if (!directory) {\n logger.error(colors.red('A --directory must be provided.'));\n localContext.process.exit(1);\n }\n\n let files: string[] = [];\n try {\n const entries = readdirSync(directory);\n files = entries\n .filter((f) => f.endsWith('.csv'))\n .map((f) => join(directory, f))\n .filter((p) => {\n try {\n return statSync(p).isFile();\n } catch {\n return false;\n }\n });\n } catch (err) {\n logger.error(colors.red(`Failed to read directory: ${directory}`));\n logger.error(colors.red((err as Error).message));\n localContext.process.exit(1);\n }\n\n if (files.length === 0) {\n logger.error(colors.red(`No CSV files found in directory: ${directory}`));\n localContext.process.exit(1);\n }\n logger.info(colors.green(`Found ${files.length} CSV files in ${directory}`));\n return files;\n}\n","import { createReadStream, createWriteStream } from 'node:fs';\nimport { mkdir, readdir, unlink, stat } from 'node:fs/promises';\nimport { pipeline } from 'node:stream/promises';\nimport { Transform } from 'node:stream';\nimport { once } from 'node:events';\nimport { Parser } from 'csv-parse';\nimport { basename, dirname, join } from 'node:path';\nimport colors from 'colors';\nimport * as fastcsv from 'fast-csv';\nimport { logger } from '../../logger';\n\n/**\n * Options for chunking a single CSV file\n */\nexport type ChunkOpts = {\n /** Path to the CSV file to chunk */\n filePath: string;\n /** Output directory for chunk files; defaults to the same directory as the input file */\n outputDir?: string;\n /** Clear output directory before starting */\n clearOutputDir: boolean;\n /** Chunk size in MB */\n chunkSizeMB: number;\n /** Optional report interval in milliseconds for progress updates */\n reportEveryMs?: number;\n /** Callback for progress updates */\n onProgress: (processed: number, total?: number) => void;\n};\n\n/**\n * Create a CSV writer (fast-csv formatter piped to a write stream) that writes\n * a header line first, and then accepts object rows. Returns a tiny API to\n * write rows with backpressure handling and to close the file cleanly.\n *\n * @param filePath - The path to the output CSV file\n * @param headers - The headers for the CSV file\n * @returns An object with `write` and `end` methods\n */\nfunction createCsvChunkWriter(\n filePath: string,\n headers: string[],\n): {\n /** Write a row object to the CSV file */\n write: (row: Record<string, unknown>) => Promise<void>;\n /** Close the CSV file, ensuring all data is flushed */\n end: () => Promise<void>;\n} {\n const ws = createWriteStream(filePath);\n const csv = fastcsv.format({ headers, writeHeaders: true, objectMode: true });\n // Pipe csv → file stream\n csv.pipe(ws);\n\n return {\n /**\n * Write a row object to the CSV file.\n *\n * @param row - The row data as an object\n */\n async write(row) {\n // Respect backpressure from fast-csv formatter\n const ok = csv.write(row);\n if (!ok) {\n await once(csv, 'drain');\n }\n },\n /**\n * Close the CSV file, ensuring all data is flushed.\n */\n async end() {\n // End formatter; wait for underlying file stream to finish flush/close\n const finished = Promise.all([once(ws, 'finish')]);\n csv.end();\n await finished;\n },\n };\n}\n\n/**\n * Zero-pad chunk numbers to four digits (e.g., 1 → \"0001\").\n *\n * @param n - The chunk number to pad\n * @returns The padded chunk number as a string\n */\nfunction pad4(n: number): string {\n return String(n).padStart(4, '0');\n}\n\n/**\n * Approximate row size in bytes using comma-joined field values.\n *\n * @param obj - The row object to estimate size for\n * @returns Approximate byte size of the row when serialized as CSV\n */\nfunction approxRowBytes(obj: Record<string, unknown>): number {\n // naive but fast; adequate for chunk rollover thresholding\n return Buffer.byteLength(\n Object.values(obj)\n .map((v) => (v == null ? '' : String(v)))\n .join(','),\n 'utf8',\n );\n}\n\n/**\n * Stream a single CSV file and write chunk files of roughly chunkSizeMB.\n * - Writes header to each chunk.\n * - Logs periodic progress via onProgress.\n *\n * @param opts - Options for chunking the file\n * @returns Promise that resolves when done\n */\nexport async function chunkOneCsvFile(opts: ChunkOpts): Promise<void> {\n const {\n filePath,\n outputDir,\n clearOutputDir,\n chunkSizeMB,\n onProgress,\n reportEveryMs = 500,\n } = opts;\n const { size: fileBytes } = await stat(filePath); // total bytes on disk\n let lastTick = 0;\n\n logger.info(\n colors.magenta(`Chunking ${filePath} into ~${chunkSizeMB}MB files...`),\n );\n\n const chunkSizeBytes = Math.floor(chunkSizeMB * 1024 * 1024);\n const baseName = basename(filePath, '.csv');\n const outDir = outputDir || dirname(filePath);\n logger.info(colors.magenta(`Output directory: ${outDir}`));\n await mkdir(outDir, { recursive: true });\n\n // Clear previous chunk files for this base\n if (clearOutputDir) {\n logger.warn(colors.yellow(`Clearing output directory: ${outDir}`));\n const files = await readdir(outDir);\n await Promise.all(\n files\n .filter((f) => f.startsWith(`${baseName}_chunk_`) && f.endsWith('.csv'))\n .map((f) => unlink(join(outDir, f))),\n );\n }\n\n let headerRow: string[] | null = null;\n let expectedCols: number | null = null;\n let totalLines = 0;\n let currentChunk = 1;\n let currentSize = 0;\n\n const parser = new Parser({\n columns: false,\n skip_empty_lines: true,\n });\n\n // running sample to estimate avg row bytes\n let sampleBytes = 0;\n let sampleRows = 0;\n\n const emit = (): void => {\n const avg = sampleRows > 0 ? sampleBytes / sampleRows : 0;\n const estTotal =\n avg > 0 ? Math.max(totalLines, Math.ceil(fileBytes / avg)) : undefined;\n onProgress(totalLines, estTotal); // <-- now has total\n lastTick = Date.now();\n };\n\n // seed an initial 0/N as soon as we start\n emit();\n\n // Current active chunk writer; created after we know headers\n let writer: {\n /** Write a row object to the current chunk file */\n write: (row: Record<string, unknown>) => Promise<void>;\n /** Close the current chunk file */\n end: () => Promise<void>;\n } | null = null;\n\n // Returns current chunk file path — chunk number is always 4-digit padded\n const currentChunkPath = (): string =>\n join(outDir, `${baseName}_chunk_${pad4(currentChunk)}.csv`);\n\n const t = new Transform({\n objectMode: true,\n /**\n * Transform each row of the CSV file into a chunk.\n *\n * @param row - The current row being processed\n * @param _enc - Encoding (not used)\n * @param cb - Callback to signal completion or error\n */\n async transform(row: string[], _enc, cb) {\n try {\n // First row is the header\n if (!headerRow) {\n headerRow = row.slice(0);\n expectedCols = headerRow.length;\n\n // Open first chunk with header asynchronously\n writer = createCsvChunkWriter(currentChunkPath(), headerRow);\n cb();\n return;\n }\n\n // sanity check rows (non-fatal)\n if (expectedCols !== null && row.length !== expectedCols) {\n // optionally log a warning or collect metrics\n logger.warn(\n colors.yellow(\n `Row has ${row.length} cols; expected ${expectedCols}`,\n ),\n );\n }\n\n totalLines += 1;\n if (totalLines % 250_000 === 0) {\n onProgress(totalLines);\n }\n\n // Build row object using the original header\n const obj = Object.fromEntries(headerRow!.map((h, i) => [h, row[i]]));\n\n // Determine the row size up-front\n const rowBytes = approxRowBytes(obj);\n sampleBytes += rowBytes;\n sampleRows += 1;\n\n // time-based throttle for UI updates\n if (Date.now() - lastTick >= reportEveryMs) emit();\n\n // If adding this row would exceed the threshold, roll first,\n // so this row becomes the first row in the next chunk.\n if (\n writer &&\n currentSize > 0 &&\n currentSize + rowBytes > chunkSizeBytes\n ) {\n await writer.end();\n currentChunk += 1;\n currentSize = 0;\n logger.info(\n colors.green(\n `Rolling to chunk ${currentChunk} after ${totalLines.toLocaleString()} rows.`,\n ),\n );\n writer = createCsvChunkWriter(currentChunkPath(), headerRow!);\n }\n\n // Ensure writer exists (should after header)\n if (!writer) {\n writer = createCsvChunkWriter(currentChunkPath(), headerRow!);\n }\n\n // Write row and update approximate size\n await writer.write(obj);\n currentSize += rowBytes;\n\n cb();\n } catch (e) {\n cb(e as Error);\n }\n },\n\n // Ensure final file is closed\n /**\n * Flush is called when the readable has ended; we close any open writer.\n *\n * @param cb - Callback to signal completion or error\n */\n async flush(cb) {\n try {\n if (writer) {\n await writer.end();\n writer = null;\n }\n emit(); // Final progress tick\n cb();\n } catch (e) {\n cb(e as Error);\n }\n },\n });\n\n const rs = createReadStream(filePath);\n await pipeline(rs, parser, t);\n\n // Final progress tick\n onProgress(totalLines);\n logger.info(\n colors.green(\n `Chunked ${filePath} into ${currentChunk} file(s); processed ${totalLines.toLocaleString()} rows.`,\n ),\n );\n}\n","import { extractErrorMessage } from '../../../lib/helpers';\nimport { chunkOneCsvFile } from '../../../lib/helpers/chunkOneCsvFile';\nimport type { ToWorker } from '../../../lib/pooling';\nimport { logger } from '../../../logger';\n\n/**\n * A unit of work: instructs a worker to chunk a single CSV file.\n */\nexport type ChunkTask = {\n /** Absolute path of the CSV file to chunk. */\n filePath: string;\n /** Options controlling output and chunk size. */\n options: {\n /** Optional directory where chunked output files should be written. */\n outputDir?: string;\n /** Whether to clear any pre-existing output chunks before writing new ones. */\n clearOutputDir: boolean;\n /** Approximate target chunk size in MB (well under Node’s string size limits). */\n chunkSizeMB: number;\n };\n};\n\n/**\n * Per-worker progress snapshot for the chunk-csv command.\n */\nexport type ChunkProgress = {\n /** File being processed by the worker. */\n filePath: string;\n /** Number of rows processed so far. */\n processed: number;\n /** Optional total rows in the file (not always known). */\n total?: number;\n};\n\n/**\n * Worker result message once a file has finished processing.\n */\nexport type ChunkResult = {\n /** Whether the file completed successfully. */\n ok: boolean;\n /** File path for which this result applies. */\n filePath: string;\n /** Optional error message if the file failed to chunk. */\n error?: string;\n};\n\n/**\n * Worker entrypoint.\n *\n * Lifecycle:\n * 1) Announce readiness to the parent via `{ type: 'ready' }`.\n * 2) Wait for `{ type: 'task' }` messages; for each, call `chunkOneCsvFile(...)`.\n * - While chunking, forward progress to the parent via `{ type: 'progress' }`.\n * - On completion, send `{ type: 'result', ok: true }`.\n * - On error, send `{ type: 'result', ok: false, error }` and exit(1).\n * 3) On `{ type: 'shutdown' }`, exit(0) gracefully.\n *\n * Notes:\n * - This process is typically spawned by a pool manager that assigns file paths to workers.\n * - The long-lived promise at the end keeps the worker alive between tasks until the parent\n * sends an explicit shutdown.\n */\nexport async function runChild(): Promise<void> {\n const workerId = Number(process.env.WORKER_ID || '0');\n logger.info(`[w${workerId}] ready pid=${process.pid}`);\n\n // Notify the parent that the worker is ready to receive tasks.\n process.send?.({ type: 'ready' });\n\n // Main message loop: receive tasks and shutdown requests from the parent.\n process.on('message', async (msg: ToWorker<ChunkTask>) => {\n if (!msg || typeof msg !== 'object') return;\n\n // Graceful shutdown: let the parent control lifecycle.\n if (msg.type === 'shutdown') {\n process.exit(0);\n }\n\n // Only handle task messages here.\n if (msg.type !== 'task') return;\n\n const { filePath, options } = msg.payload;\n const { outputDir, clearOutputDir, chunkSizeMB } = options;\n\n try {\n // Stream the input CSV and write chunk files asynchronously.\n await chunkOneCsvFile({\n filePath,\n outputDir,\n clearOutputDir,\n chunkSizeMB,\n // Propagate incremental progress to the parent.\n onProgress: (processed, total) =>\n process.send?.({\n type: 'progress',\n payload: { filePath, processed, total },\n }),\n });\n\n // Report success to the parent.\n process.send?.({\n type: 'result',\n payload: { ok: true, filePath },\n });\n } catch (err) {\n // Log locally and report failure upstream; exit the worker with error code.\n const message = extractErrorMessage(err);\n logger.error(`[w${workerId}] ERROR ${filePath}: ${message}`);\n process.send?.({\n type: 'result',\n payload: { ok: false, filePath, error: message },\n });\n }\n });\n\n // keep alive\n await new Promise<never>(() => {\n // This promise never resolves, keeping the worker alive indefinitely\n // until the parent process instructs shutdown.\n });\n}\n","import {\n makeHeader,\n makeWorkerRows,\n type ChunkSlotProgress,\n type CommonCtx,\n type DashboardPlugin,\n} from '../../../../lib/pooling';\n\n/**\n * Header for chunk-csv (no extra totals block).\n *\n * @param ctx - Dashboard context.\n * @returns Header lines.\n */\nfunction renderHeader<TTotals>(\n ctx: CommonCtx<TTotals, ChunkSlotProgress>,\n): string[] {\n // no extra lines — reuse the shared header as-is\n return makeHeader(ctx);\n}\n\n/**\n * Worker rows for chunk-csv — share the generic row renderer.\n *\n * @param ctx - Dashboard context.\n * @returns Array of strings, each representing one worker row.\n */\nfunction renderWorkers<TTotals>(\n ctx: CommonCtx<TTotals, ChunkSlotProgress>,\n): string[] {\n return makeWorkerRows(ctx);\n}\n\nexport const chunkCsvPlugin: DashboardPlugin<unknown, ChunkSlotProgress> = {\n renderHeader,\n renderWorkers,\n // no extras\n};\n","import type { LocalContext } from '../../../context';\nimport colors from 'colors';\nimport { logger } from '../../../logger';\nimport { collectCsvFilesOrExit } from '../../../lib/helpers/collectCsvFilesOrExit';\nimport {\n computePoolSize,\n createExtraKeyHandler,\n CHILD_FLAG,\n type PoolHooks,\n runPool,\n dashboardPlugin,\n} from '../../../lib/pooling';\nimport {\n runChild,\n type ChunkProgress,\n type ChunkResult,\n type ChunkTask,\n} from './worker';\nimport { chunkCsvPlugin } from './ui';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\n/**\n * Returns the current module's path so the worker pool knows what file to re-exec.\n * In Node ESM, __filename is undefined, so we fall back to argv[1].\n *\n * @returns The current module's path as a string\n */\nfunction getCurrentModulePath(): string {\n if (typeof __filename !== 'undefined') {\n return __filename as unknown as string;\n }\n return process.argv[1];\n}\n\n/**\n * Totals aggregate for this command.\n * We don’t need custom counters since the runner already tracks\n * completed/failed counts in its header — so we just use an empty record.\n */\ntype Totals = Record<string, never>;\n\n/**\n * CLI flags accepted by the `chunk-csv` command.\n *\n * These are passed down from the CLI parser into the parent process.\n */\nexport type ChunkCsvCommandFlags = {\n directory: string;\n outputDir?: string;\n clearOutputDir: boolean;\n chunkSizeMB: number;\n concurrency?: number;\n viewerMode: boolean;\n};\n\n/**\n * Parent entrypoint for chunking many CSVs in parallel using the worker pool runner.\n *\n * Lifecycle:\n * 1) Discover CSV inputs (exit if none).\n * 2) Compute pool size (CPU-count heuristic or --concurrency).\n * 3) Build a FIFO queue of `ChunkTask`s.\n * 4) Define pool hooks to drive task assignment, progress, and result handling.\n * 5) Launch the pool with `runPool`, rendering via the `chunkCsvPlugin`.\n *\n * @param this - Bound CLI context (provides process exit + logging).\n * @param flags - CLI options for the run.\n */\nexport async function chunkCsv(\n this: LocalContext,\n flags: ChunkCsvCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n const {\n directory,\n outputDir,\n clearOutputDir,\n chunkSizeMB,\n concurrency,\n viewerMode,\n } = flags;\n\n /* 1) Discover CSV inputs */\n const files = collectCsvFilesOrExit(directory, this);\n\n /* 2) Size the pool */\n const { poolSize, cpuCount } = computePoolSize(concurrency, files.length);\n\n logger.info(\n colors.green(\n `Chunking ${files.length} CSV file(s) with pool size ${poolSize} (CPU=${cpuCount})`,\n ),\n );\n\n /* 3) Prepare a simple FIFO queue of tasks (one per file). */\n const queue = files.map<ChunkTask>((filePath) => ({\n filePath,\n options: { outputDir, clearOutputDir, chunkSizeMB },\n }));\n\n /* 4) Define pool hooks to adapt runner to this command. */\n const hooks: PoolHooks<ChunkTask, ChunkProgress, ChunkResult, Totals> = {\n nextTask: () => queue.shift(),\n taskLabel: (t) => t.filePath,\n initTotals: () => ({} as Totals),\n initSlotProgress: () => undefined,\n onProgress: (totals) => totals,\n onResult: (totals, res) => ({ totals, ok: !!res.ok }),\n // postProcess receives log context when viewerMode=true — we don’t need it here.\n postProcess: async () => {\n // nothing extra for chunk-csv\n },\n };\n\n /* 5) Launch the pool runner with our hooks and custom dashboard plugin. */\n await runPool({\n title: `Chunk CSV - ${directory}`,\n baseDir: directory || outputDir || process.cwd(),\n childFlag: CHILD_FLAG,\n childModulePath: getCurrentModulePath(),\n poolSize,\n cpuCount,\n filesTotal: files.length,\n hooks,\n viewerMode,\n render: (input) => dashboardPlugin(input, chunkCsvPlugin, viewerMode),\n extraKeyHandler: ({ logsBySlot, repaint, setPaused }) =>\n createExtraKeyHandler({\n logsBySlot,\n repaint,\n setPaused,\n }),\n });\n}\n\n/* -------------------------------------------------------------------------------------------------\n * If invoked directly as a child process, enter worker loop\n * ------------------------------------------------------------------------------------------------- */\nif (process.argv.includes(CHILD_FLAG)) {\n runChild().catch((err) => {\n logger.error(err);\n process.exit(1);\n });\n}\n"],"mappings":"uxBAcA,SAAgB,EACd,EACA,EACU,CACL,IACH,EAAO,MAAM,EAAO,IAAI,kCAAkC,CAAC,CAC3D,EAAa,QAAQ,KAAK,EAAE,EAG9B,IAAI,EAAkB,EAAE,CACxB,GAAI,CAEF,EADgB,EAAY,EAAU,CAEnC,OAAQ,GAAM,EAAE,SAAS,OAAO,CAAC,CACjC,IAAK,GAAM,EAAK,EAAW,EAAE,CAAC,CAC9B,OAAQ,GAAM,CACb,GAAI,CACF,OAAO,EAAS,EAAE,CAAC,QAAQ,MACrB,CACN,MAAO,KAET,OACG,EAAK,CACZ,EAAO,MAAM,EAAO,IAAI,6BAA6B,IAAY,CAAC,CAClE,EAAO,MAAM,EAAO,IAAK,EAAc,QAAQ,CAAC,CAChD,EAAa,QAAQ,KAAK,E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