@transcend-io/cli 8.33.1 → 8.34.0
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/README.md +18 -17
- package/dist/{api-keys-BY5LoEwO.cjs → api-keys-CDp8NUhN.cjs} +2 -2
- package/dist/{api-keys-BY5LoEwO.cjs.map → api-keys-CDp8NUhN.cjs.map} +1 -1
- package/dist/{app-BlzWBy2v.cjs → app-rVGy2Ks-.cjs} +18 -18
- package/dist/app-rVGy2Ks-.cjs.map +1 -0
- package/dist/bin/bash-complete.cjs +1 -1
- package/dist/bin/cli.cjs +1 -1
- package/dist/bin/deprecated-command.cjs +1 -1
- package/dist/{code-scanning-Bvs5QHcn.cjs → code-scanning-BwfVNIHr.cjs} +2 -2
- package/dist/{code-scanning-Bvs5QHcn.cjs.map → code-scanning-BwfVNIHr.cjs.map} +1 -1
- package/dist/{command-d4zv2BeF.cjs → command-3fhEz5PC.cjs} +2 -2
- package/dist/{command-d4zv2BeF.cjs.map → command-3fhEz5PC.cjs.map} +1 -1
- package/dist/{consent-manager-BjsU0NzZ.cjs → consent-manager-DXWjvCtI.cjs} +2 -2
- package/dist/{consent-manager-BjsU0NzZ.cjs.map → consent-manager-DXWjvCtI.cjs.map} +1 -1
- package/dist/{constants-KUUI8R0B.cjs → constants-B-TmLA0w.cjs} +2 -2
- package/dist/{constants-KUUI8R0B.cjs.map → constants-B-TmLA0w.cjs.map} +1 -1
- package/dist/{cron-trHmh4Ul.cjs → cron-DQHN57v7.cjs} +2 -2
- package/dist/{cron-trHmh4Ul.cjs.map → cron-DQHN57v7.cjs.map} +1 -1
- package/dist/{data-inventory-CTgo5IAK.cjs → data-inventory-flXV6qPl.cjs} +2 -2
- package/dist/{data-inventory-CTgo5IAK.cjs.map → data-inventory-flXV6qPl.cjs.map} +1 -1
- package/dist/{dataFlowsToDataSilos-CKr7XUmU.cjs → dataFlowsToDataSilos-Lk7WQ39V.cjs} +2 -2
- package/dist/{dataFlowsToDataSilos-CKr7XUmU.cjs.map → dataFlowsToDataSilos-Lk7WQ39V.cjs.map} +1 -1
- package/dist/{impl-BQuhNgNA.cjs → impl-2u3q0rji.cjs} +2 -2
- package/dist/{impl-BQuhNgNA.cjs.map → impl-2u3q0rji.cjs.map} +1 -1
- package/dist/{impl-BkoQZksU.cjs → impl-3ih-x09b.cjs} +2 -2
- package/dist/{impl-BkoQZksU.cjs.map → impl-3ih-x09b.cjs.map} +1 -1
- package/dist/{impl-oSvrDwzY.cjs → impl-80GXtjmz.cjs} +2 -2
- package/dist/{impl-oSvrDwzY.cjs.map → impl-80GXtjmz.cjs.map} +1 -1
- package/dist/{impl-D2Rar4JL.cjs → impl-8PlQ3Cvy.cjs} +2 -2
- package/dist/{impl-D2Rar4JL.cjs.map → impl-8PlQ3Cvy.cjs.map} +1 -1
- package/dist/{impl-BVXrPQ1G.cjs → impl-B1p9GNrM.cjs} +2 -2
- package/dist/{impl-BVXrPQ1G.cjs.map → impl-B1p9GNrM.cjs.map} +1 -1
- package/dist/{impl-wBfm0THj.cjs → impl-B4iI3rcF.cjs} +2 -2
- package/dist/{impl-wBfm0THj.cjs.map → impl-B4iI3rcF.cjs.map} +1 -1
- package/dist/{impl-CSfCo7EY.cjs → impl-B6qG10UZ.cjs} +2 -2
- package/dist/{impl-CSfCo7EY.cjs.map → impl-B6qG10UZ.cjs.map} +1 -1
- package/dist/{impl-DuaKD2ga.cjs → impl-BJ8i_gqQ.cjs} +2 -2
- package/dist/{impl-DuaKD2ga.cjs.map → impl-BJ8i_gqQ.cjs.map} +1 -1
- package/dist/{impl-_pb_69kE.cjs → impl-BZc5cmdE.cjs} +2 -2
- package/dist/{impl-_pb_69kE.cjs.map → impl-BZc5cmdE.cjs.map} +1 -1
- package/dist/{impl-BTXtq2nD.cjs → impl-Bc9DMV-V.cjs} +2 -2
- package/dist/{impl-BTXtq2nD.cjs.map → impl-Bc9DMV-V.cjs.map} +1 -1
- package/dist/{impl-D5zl_Mu5.cjs → impl-BjsBvvGF.cjs} +2 -2
- package/dist/{impl-D5zl_Mu5.cjs.map → impl-BjsBvvGF.cjs.map} +1 -1
- package/dist/{impl-3m5kiYs0.cjs → impl-BqyO4vYa.cjs} +2 -2
- package/dist/{impl-3m5kiYs0.cjs.map → impl-BqyO4vYa.cjs.map} +1 -1
- package/dist/{impl-DBAX5Mjz.cjs → impl-Bsqlw8_g.cjs} +2 -2
- package/dist/{impl-DBAX5Mjz.cjs.map → impl-Bsqlw8_g.cjs.map} +1 -1
- package/dist/{impl-DPzcKPpu.cjs → impl-BuJNWbOW.cjs} +2 -2
- package/dist/{impl-DPzcKPpu.cjs.map → impl-BuJNWbOW.cjs.map} +1 -1
- package/dist/{impl-l01EW7nc.cjs → impl-C2_oQebA.cjs} +2 -2
- package/dist/{impl-l01EW7nc.cjs.map → impl-C2_oQebA.cjs.map} +1 -1
- package/dist/{impl-k_N4BSHb.cjs → impl-CCeEUy6z.cjs} +2 -2
- package/dist/{impl-k_N4BSHb.cjs.map → impl-CCeEUy6z.cjs.map} +1 -1
- package/dist/impl-CUkxcZrf.cjs +2 -0
- package/dist/impl-CUkxcZrf.cjs.map +1 -0
- package/dist/{impl-CL4UPQTF.cjs → impl-CZmlwib3.cjs} +2 -2
- package/dist/{impl-CL4UPQTF.cjs.map → impl-CZmlwib3.cjs.map} +1 -1
- package/dist/{impl-DlHm8Nk9.cjs → impl-CaSO2LPb.cjs} +2 -2
- package/dist/{impl-DlHm8Nk9.cjs.map → impl-CaSO2LPb.cjs.map} +1 -1
- package/dist/{impl-BATmiMYN.cjs → impl-CaUSDPuW.cjs} +2 -2
- package/dist/{impl-BATmiMYN.cjs.map → impl-CaUSDPuW.cjs.map} +1 -1
- package/dist/{impl-BJCXAnkF.cjs → impl-Cc-Lfiig.cjs} +2 -2
- package/dist/{impl-BJCXAnkF.cjs.map → impl-Cc-Lfiig.cjs.map} +1 -1
- package/dist/{impl-Bthcogve.cjs → impl-CpoSlP1o.cjs} +2 -2
- package/dist/{impl-Bthcogve.cjs.map → impl-CpoSlP1o.cjs.map} +1 -1
- package/dist/{impl-CIkV6OPL.cjs → impl-CrsHy3BZ.cjs} +2 -2
- package/dist/{impl-CIkV6OPL.cjs.map → impl-CrsHy3BZ.cjs.map} +1 -1
- package/dist/{impl-BMnyINiQ.cjs → impl-CtMVi5m1.cjs} +2 -2
- package/dist/{impl-BMnyINiQ.cjs.map → impl-CtMVi5m1.cjs.map} +1 -1
- package/dist/{impl-BdqGR4Db.cjs → impl-Cw7Jxx0V.cjs} +2 -2
- package/dist/{impl-BdqGR4Db.cjs.map → impl-Cw7Jxx0V.cjs.map} +1 -1
- package/dist/{impl-D9degodL.cjs → impl-CwPRkBc0.cjs} +2 -2
- package/dist/{impl-D9degodL.cjs.map → impl-CwPRkBc0.cjs.map} +1 -1
- package/dist/{impl-DLlHf0f5.cjs → impl-CzO7dqsL.cjs} +2 -2
- package/dist/{impl-DLlHf0f5.cjs.map → impl-CzO7dqsL.cjs.map} +1 -1
- package/dist/{impl-Bks9LY66.cjs → impl-D0r4dSxM.cjs} +2 -2
- package/dist/{impl-Bks9LY66.cjs.map → impl-D0r4dSxM.cjs.map} +1 -1
- package/dist/{impl-BicjL2jn.cjs → impl-DBnRvkUi.cjs} +2 -2
- package/dist/{impl-BicjL2jn.cjs.map → impl-DBnRvkUi.cjs.map} +1 -1
- package/dist/{impl-DZWafiRw.cjs → impl-DOmKR8yz.cjs} +2 -2
- package/dist/{impl-DZWafiRw.cjs.map → impl-DOmKR8yz.cjs.map} +1 -1
- package/dist/{impl-wC9NKk7V.cjs → impl-DX7gLoTo.cjs} +2 -2
- package/dist/{impl-wC9NKk7V.cjs.map → impl-DX7gLoTo.cjs.map} +1 -1
- package/dist/{impl-NxZOP7L7.cjs → impl-DcQ_HfDZ.cjs} +2 -2
- package/dist/{impl-NxZOP7L7.cjs.map → impl-DcQ_HfDZ.cjs.map} +1 -1
- package/dist/{impl-BrjAmeGI.cjs → impl-DjTjLgew.cjs} +2 -2
- package/dist/{impl-BrjAmeGI.cjs.map → impl-DjTjLgew.cjs.map} +1 -1
- package/dist/{impl-CQ1Eg1Gs.cjs → impl-DoP4FUJI.cjs} +2 -2
- package/dist/{impl-CQ1Eg1Gs.cjs.map → impl-DoP4FUJI.cjs.map} +1 -1
- package/dist/{impl-GBzXG1_z.cjs → impl-DrNWIvMG.cjs} +2 -2
- package/dist/{impl-GBzXG1_z.cjs.map → impl-DrNWIvMG.cjs.map} +1 -1
- package/dist/{impl-ECqWmX0a.cjs → impl-DvlAq8xf.cjs} +2 -2
- package/dist/{impl-ECqWmX0a.cjs.map → impl-DvlAq8xf.cjs.map} +1 -1
- package/dist/{impl-DGql4qi2.cjs → impl-E1vzeNmp.cjs} +2 -2
- package/dist/{impl-DGql4qi2.cjs.map → impl-E1vzeNmp.cjs.map} +1 -1
- package/dist/{impl-DQ67TBSS.cjs → impl-EEKe6HmF.cjs} +2 -2
- package/dist/{impl-DQ67TBSS.cjs.map → impl-EEKe6HmF.cjs.map} +1 -1
- package/dist/{impl-BdrUgBNn.cjs → impl-NdV_MRsm.cjs} +2 -2
- package/dist/{impl-BdrUgBNn.cjs.map → impl-NdV_MRsm.cjs.map} +1 -1
- package/dist/{impl-d01YGIfB.cjs → impl-TQVXJemY.cjs} +2 -2
- package/dist/{impl-d01YGIfB.cjs.map → impl-TQVXJemY.cjs.map} +1 -1
- package/dist/{impl-DB2kHDaA.cjs → impl-b6KwZ74o.cjs} +2 -2
- package/dist/{impl-DB2kHDaA.cjs.map → impl-b6KwZ74o.cjs.map} +1 -1
- package/dist/{impl-DrBeb50_.cjs → impl-t_fZSUcj.cjs} +2 -2
- package/dist/{impl-DrBeb50_.cjs.map → impl-t_fZSUcj.cjs.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/{manual-enrichment-D0Bhyycl.cjs → manual-enrichment-Y_BQaSZQ.cjs} +2 -2
- package/dist/{manual-enrichment-D0Bhyycl.cjs.map → manual-enrichment-Y_BQaSZQ.cjs.map} +1 -1
- package/dist/{pooling-CWVm4ilp.cjs → pooling-Ct83vfEh.cjs} +2 -2
- package/dist/{pooling-CWVm4ilp.cjs.map → pooling-Ct83vfEh.cjs.map} +1 -1
- package/dist/{preference-management-Dhmm0sgq.cjs → preference-management-5uJDKuMK.cjs} +3 -3
- package/dist/{preference-management-Dhmm0sgq.cjs.map → preference-management-5uJDKuMK.cjs.map} +1 -1
- package/dist/{syncConfigurationToTranscend-DWM5Kkl4.cjs → syncConfigurationToTranscend-Bpge5AcC.cjs} +2 -2
- package/dist/{syncConfigurationToTranscend-DWM5Kkl4.cjs.map → syncConfigurationToTranscend-Bpge5AcC.cjs.map} +1 -1
- package/dist/{uploadConsents-BhsOWa3P.cjs → uploadConsents-CJc_6Qwd.cjs} +2 -2
- package/dist/{uploadConsents-BhsOWa3P.cjs.map → uploadConsents-CJc_6Qwd.cjs.map} +1 -1
- package/package.json +1 -1
- package/dist/app-BlzWBy2v.cjs.map +0 -1
- package/dist/impl-hWCNtvcN.cjs +0 -2
- package/dist/impl-hWCNtvcN.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-Cw7Jxx0V.cjs","names":["fetchAndIndexCatalogs","buildTranscendGraphQLClient","readTranscendYaml","dataFlowsToDataSilos"],"sources":["../src/commands/inventory/derive-data-silos-from-data-flows/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport {\n fetchAndIndexCatalogs,\n buildTranscendGraphQLClient,\n} from '../../../lib/graphql';\nimport { join } from 'node:path';\nimport colors from 'colors';\nimport { logger } from '../../../logger';\nimport { dataFlowsToDataSilos } from '../../../lib/consent-manager/dataFlowsToDataSilos';\nimport { DataFlowInput } from '../../../codecs';\nimport { existsSync, lstatSync } from 'node:fs';\nimport { listFiles } from '../../../lib/api-keys';\nimport {\n readTranscendYaml,\n writeTranscendYaml,\n} from '../../../lib/readTranscendYaml';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface DeriveDataSilosFromDataFlowsCommandFlags {\n auth: string;\n dataFlowsYmlFolder: string;\n dataSilosYmlFolder: string;\n ignoreYmls?: string[];\n transcendUrl: string;\n}\n\nexport async function deriveDataSilosFromDataFlows(\n this: LocalContext,\n {\n auth,\n dataFlowsYmlFolder,\n dataSilosYmlFolder,\n ignoreYmls = [],\n transcendUrl,\n }: DeriveDataSilosFromDataFlowsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n // Ensure folder is passed\n if (\n !existsSync(dataFlowsYmlFolder) ||\n !lstatSync(dataFlowsYmlFolder).isDirectory()\n ) {\n logger.error(colors.red(`Folder does not exist: \"${dataFlowsYmlFolder}\"`));\n this.process.exit(1);\n }\n\n // Ensure folder is passed\n if (\n !existsSync(dataSilosYmlFolder) ||\n !lstatSync(dataSilosYmlFolder).isDirectory()\n ) {\n logger.error(colors.red(`Folder does not exist: \"${dataSilosYmlFolder}\"`));\n this.process.exit(1);\n }\n\n // Fetch all integrations in the catalog\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n const { serviceToTitle, serviceToSupportedIntegration } =\n await fetchAndIndexCatalogs(client);\n\n // List of each data flow yml file\n listFiles(dataFlowsYmlFolder).forEach((directory) => {\n // read in the data flows for a specific instance\n const { 'data-flows': dataFlows = [] } = readTranscendYaml(\n join(dataFlowsYmlFolder, directory),\n );\n\n // map the data flows to data silos\n const { adTechDataSilos, siteTechDataSilos } = dataFlowsToDataSilos(\n dataFlows as DataFlowInput[],\n {\n serviceToSupportedIntegration,\n serviceToTitle,\n },\n );\n\n // combine and write to yml file\n const dataSilos = [...adTechDataSilos, ...siteTechDataSilos];\n logger.log(`Total Services: ${dataSilos.length}`);\n logger.log(`Ad Tech Services: ${adTechDataSilos.length}`);\n logger.log(`Site Tech Services: ${siteTechDataSilos.length}`);\n writeTranscendYaml(join(dataSilosYmlFolder, directory), {\n 'data-silos': ignoreYmls.includes(directory) ? [] : dataSilos,\n });\n });\n}\n"],"mappings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enums-CBXlBJii.cjs`);require(`./constants-B-TmLA0w.cjs`);const t=require(`./syncConfigurationToTranscend-Bpge5AcC.cjs`);require(`./logger-BaHHbWVd.cjs`),require(`./buildAIIntegrationType-n_Qlv8wG.cjs`);const n=require(`./done-input-validation-Cgk5kNBs.cjs`);let r=require(`@transcend-io/privacy-types`);async function i({auth:e,transcendUrl:i,folderPath:a,requestIds:o,statuses:s=[r.RequestStatus.Approving,r.RequestStatus.Downloadable],concurrency:c,createdAtBefore:l,createdAtAfter:u,approveAfterDownload:d}){n.t(this.process.exit),await t.Z({transcendUrl:i,auth:e,folderPath:a,requestIds:o,statuses:s,concurrency:c,createdAtBefore:l,createdAtAfter:u,approveAfterDownload:d})}exports.downloadFiles=i;
|
|
2
|
+
//# sourceMappingURL=impl-CwPRkBc0.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-CwPRkBc0.cjs","names":["RequestStatus","downloadPrivacyRequestFiles"],"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 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 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 approveAfterDownload,\n });\n}\n"],"mappings":"kUAkBA,eAAsB,EAEpB,CACE,OACA,eACA,aACA,aACA,WAAW,CAACA,EAAAA,cAAc,UAAWA,EAAAA,cAAc,aAAa,CAChE,cACA,kBACA,iBACA,wBAEa,CACf,EAAA,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAMC,EAAAA,EAA4B,CAChC,eACA,OACA,aACA,aACA,WACA,cACA,kBACA,iBACA,uBACD,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e=require(`./enums-CBXlBJii.cjs`),t=require(`./constants-
|
|
1
|
+
const e=require(`./enums-CBXlBJii.cjs`),t=require(`./constants-B-TmLA0w.cjs`),n=require(`./syncConfigurationToTranscend-Bpge5AcC.cjs`),r=require(`./logger-BaHHbWVd.cjs`);require(`./buildAIIntegrationType-n_Qlv8wG.cjs`);const i=require(`./done-input-validation-Cgk5kNBs.cjs`);let a=require(`@transcend-io/privacy-types`),o=require(`@transcend-io/type-utils`),s=require(`node:fs`);s=e.s(s);let c=require(`colors`);c=e.s(c);let l=require(`yargs-parser`);l=e.s(l);let u=require(`got`);u=e.s(u);let d=require(`JSONStream`);d=e.s(d);const f=({hostname:e,auth:t})=>u.default.extend({prefixUrl:`https://${e}`,headers:{accept:`application/json`,"content-type":`application/json`,authorization:`Bearer ${t}`}}),p=Object.values(e.n),m=({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},h=({file:e,assessment:t,index:n,total:i})=>{r.t.info(c.default.magenta(`Writing enriched assessment ${n+1} of ${i} to file "${e}"...`)),n===0?s.default.writeFileSync(e,m({assessment:t,index:n,total:i,wrap:!1})):s.default.appendFileSync(e,m({assessment:t,index:n,total:i,wrap:!1}))},g=async({oneTrust:e})=>{let t=0,n=1,i=0,s=[];for(;t<n;){let{body:c}=await e.get(`api/assessment/v2/assessments?page=${t}&size=2000`),{page:l,content:u}=(0,o.decodeCodec)(a.OneTrustGetListOfAssessmentsResponse,c);s.push(...u??[]),t===0&&(n=l?.totalPages??0,i=l?.totalElements??0),t+=1,r.t.info(`Fetched ${s.length} of ${i} assessments.`)}return s},_=async({oneTrust:e,assessmentId:t})=>{let{body:n}=await e.get(`api/assessment/v2/assessments/${t}/export?ExcludeSkippedQuestions=false`);return(0,o.decodeCodec)(a.OneTrustGetAssessmentResponse,n)},v=async({oneTrust:e,riskId:t})=>{let{body:n}=await e.get(`api/risk/v2/risks/${t}`);return(0,o.decodeCodec)(a.OneTrustGetRiskResponse,n)},y=async({oneTrust:e,userId:t})=>{let{body:n}=await e.get(`api/scim/v2/Users/${t}`);return(0,o.decodeCodec)(a.OneTrustGetUserResponse,n)},b=({assessment:e,assessmentDetails:n,riskDetails:r,creatorDetails:i,approversDetails:a,respondentsDetails:o})=>{let s=t.g(r,`id`),{sections:c,createdBy:l,...u}=n,d=c.map(e=>{let{questions:t,...n}=e,r=t.map(e=>{let{risks:t,...n}=e,r=(t??[]).map(e=>{let t=s[e.riskId];return{...e,...t,level:e.level,impactLevel:e.impactLevel??0}});return{...n,risks:r}});return{...n,questions:r}}),f={...l,active:i?.active??!1,userType:i?.userType??`Internal`,emails:i?.emails??[],title:i?.title??null,givenName:i?.name.givenName??null,familyName:i?.name.familyName??null},p=t.g(a,`id`),m=n.approvers.flatMap(e=>p[e.id]?[{...e,approver:{...e.approver,active:p[e.id].active,userType:p[e.id].userType,emails:p[e.id].emails,title:p[e.id].title,givenName:p[e.id].name.givenName??null,familyName:p[e.id].name.familyName??null}}]:[]),h=t.g(o,`id`),g=n.respondents.filter(e=>!e.name.includes(`@`)).flatMap(e=>h[e.id]?[{...e,active:h[e.id].active,userType:h[e.id].userType,emails:h[e.id].emails,title:h[e.id].title,givenName:h[e.id].name.givenName??null,familyName:h[e.id].name.familyName??null}]:[]);return{...e,...u,approvers:m,respondents:g,createdBy:f,sections:d}},x=async({transcend:e,assessment:t,total:i,index:a})=>{r.t.info(c.default.magenta(`Writing enriched assessment ${a+1} ${i?`of ${i} `:` `}to Transcend...`));let o={json:m({assessment:t,index:a,total:i})};try{await n.i(e,n.bo,{input:o})}catch{r.t.error(c.default.red(`Failed to sync assessment ${a+1} ${i?`of ${i} `:` `}to Transcend.\n\tAssessment Title: ${t.name}. Template Title: ${t.template.name}\n`))}},S=async({oneTrust:e,file:t,dryRun:i,transcend:a})=>{r.t.info(`Getting list of all assessments from OneTrust...`);let o=await g({oneTrust:e}),s={};await n.Es(Array.from({length:Math.ceil(o.length/5)},(e,t)=>o.slice(t*5,(t+1)*5)),async(l,u)=>{let d=[];await n.Ts(l,async(t,i)=>{let a=5*u+i+1;r.t.info(`[assessment ${a} of ${o.length}]: fetching details...`);let{templateName:l,assessmentId:f}=t,p=await _({oneTrust:e,assessmentId:f}),m=p.createdBy.id,h=s[m];if(!h){r.t.info(`[assessment ${a} of ${o.length}]: fetching creator...`);try{h=await y({oneTrust:e,userId:m}),s[m]=h}catch{r.t.warn(c.default.yellow(`[assessment ${a} of ${o.length}]: failed to fetch form creator.\tcreatorId: ${m}. Assessment Title: ${t.name}. Template Title: ${l}`))}}let{approvers:g}=p,x=[];g.length>0&&(r.t.info(`[assessment ${a} of ${o.length}]: fetching approvers...`),x=await n.Ts(g.map(({id:e})=>e),async n=>{try{let t=s[n];return t||(t=await y({oneTrust:e,userId:n}),s[n]=t),[t]}catch{return r.t.warn(c.default.yellow(`[assessment ${a} of ${o.length}]: failed to fetch a form approver.\tapproverId: ${n}. Assessment Title: ${t.name}. Template Title: ${l}`)),[]}},{concurrency:5}));let{respondents:S}=p,C=S.filter(e=>!e.name.includes(`@`)),w=[];C.length>0&&(r.t.info(`[assessment ${a} of ${o.length}]: fetching respondents...`),w=await n.Ts(C.map(({id:e})=>e),async n=>{try{let t=s[n];return t||(t=await y({oneTrust:e,userId:n}),s[n]=t),[t]}catch{return r.t.warn(c.default.yellow(`[assessment ${a} of ${o.length}]: failed to fetch a respondent.\trespondentId: ${n}. Assessment Title: ${t.name}. Template Title: ${l}`)),[]}},{concurrency:5}));let T=[],E=n.Ds(p.sections.flatMap(e=>e.questions.flatMap(e=>(e.risks??[]).flatMap(e=>e.riskId))));E.length>0&&(r.t.info(`[assessment ${a} of ${o.length}]: fetching risks...`),T=await n.Ts(E,t=>v({oneTrust:e,riskId:t}),{concurrency:5}));let D=b({assessment:t,assessmentDetails:p,riskDetails:T,creatorDetails:h,approversDetails:x.flat(),respondentsDetails:w.flat()});d.push(D)},{concurrency:5}),await n.Es(d,async(e,n)=>{let r=u*5+n;i&&t?h({assessment:e,index:r,total:o.length,file:t}):a&&await x({assessment:e,transcend:a,total:o.length,index:r})})})},C=({transcend:e,file:t})=>(r.t.info(`Getting list of all assessments from file ${t}...`),new Promise((n,i)=>{let l=(0,s.createReadStream)(t,{encoding:`utf-8`,highWaterMark:64*1024}),u=d.default.parse(`*`),f=0;l.pipe(u),u.on(`data`,async n=>{try{u.pause(),await x({assessment:(0,o.decodeCodec)(a.OneTrustEnrichedAssessment,n),transcend:e,index:f}),f+=1,u.resume()}catch(e){r.t.error(c.default.red(`Failed to parse the assessment ${f} from file '${t}': ${e.message}.`))}}),u.on(`end`,()=>{r.t.info(`Finished processing ${f} assessments from file ${t}`),n()}),u.on(`error`,e=>{r.t.error(c.default.red(`Error parsing file '${t}': ${e.message}`)),i(e)}),l.on(`error`,e=>{r.t.error(c.default.red(`Error reading file '${t}': ${e.message}`)),i(e)})}));async function w({hostname:t,oneTrustAuth:a,source:o,transcendAuth:s,transcendUrl:l,resource:u,file:d,dryRun:p,debug:m}){if(!p&&!s)throw Error('Must specify a "transcendAuth" parameter to sync resources to Transcend. e.g. --transcendAuth=${TRANSCEND_API_KEY}');if(p&&!d)throw Error(`Must set a "file" parameter when "dryRun" is "true". e.g. --file=./oneTrustAssessments.json`);if(d){let t=d.split(`.`);if(t.length<2)throw Error(`The "file" parameter has an invalid format. Expected a path with extensions. e.g. --file=./pathToFile.json.`);if(t.at(-1)!==e.t.Json)throw Error(`Expected the format of the "file" parameters '${d}' to be '${e.t.Json}', but got '${t.at(-1)}'.`)}if(o===e.r.OneTrust){if(!t)throw Error(`Missing required parameter "hostname". e.g. --hostname=customer.my.onetrust.com`);if(!a)throw Error(`Missing required parameter "oneTrustAuth". e.g. --oneTrustAuth=$ONE_TRUST_AUTH_TOKEN`)}else{if(!d)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 ${e.r.OneTrust} if "dryRun" is enabled.`)}i.t(this.process.exit);let h=t&&a?f({hostname:t,auth:a}):void 0,g=l&&s?n.ti(l,s):void 0;try{u===e.n.Assessments&&(o===e.r.OneTrust&&h?await S({oneTrust:h,file:d,dryRun:p,...g&&{transcend:g}}):o===e.r.File&&d&&g&&await C({file:d,transcend:g}))}catch(e){throw Error(`An error occurred syncing the resource ${u} from OneTrust: ${m?e.stack:e.message}`)}r.t.info(c.default.green(`Successfully synced OneTrust ${u} to ${p?`disk at "${d}"`:`Transcend`}!`))}exports.syncOt=w;
|
|
4
|
-
//# sourceMappingURL=impl-
|
|
4
|
+
//# sourceMappingURL=impl-CzO7dqsL.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-DLlHf0f5.cjs","names":["OneTrustPullResource","OneTrustGetListOfAssessmentsResponse","OneTrustGetAssessmentResponse","OneTrustGetRiskResponse","OneTrustGetUserResponse","keyBy","makeGraphQLRequest","IMPORT_ONE_TRUST_ASSESSMENT_FORMS","mapSeries","map","uniq","OneTrustEnrichedAssessment","OneTrustFileFormat","OneTrustPullSource","buildTranscendGraphQLClient","OneTrustPullResource"],"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":"+gBAQA,MAAa,GAA6B,CACxC,WACA,UAOA,EAAA,QAAI,OAAO,CACT,UAAW,WAAW,IACtB,QAAS,CACP,OAAQ,mBACR,eAAgB,mBAChB,cAAe,UAAU,IAC1B,CACF,CAAC,CCfE,EAAkB,OAAO,OAAOA,EAAAA,EAAqB,CCD9C,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,EAAA,EAAO,KACL,EAAA,QAAO,QACL,+BACE,EAAQ,EACT,MAAM,EAAM,YAAY,EAAK,MAC/B,CACF,CAEG,IAAU,EACZ,EAAA,QAAG,cACD,EACA,EAAyB,CACvB,aACA,QACA,QACA,KAAM,GACP,CAAC,CACH,CAED,EAAA,QAAG,eACD,EACA,EAAyB,CACvB,aACA,QACA,QACA,KAAM,GACP,CAAC,CACH,ECvCQ,EAA+B,MAAO,CACjD,cAImC,CACnC,IAAI,EAAc,EACd,EAAa,EACb,EAAgB,EAEd,EAAuC,EAAE,CAE/C,KAAO,EAAc,GAAY,CAC/B,GAAM,CAAE,QAAS,MAAM,EAAS,IAC9B,sCAAsC,EAAY,YACnD,CAEK,CAAE,OAAM,YAAA,EAAA,EAAA,aACZC,EAA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AAA,EAAmB,UAAY,EAC5C,MAAM,EAAoC,CACxC,WACA,OACA,SACA,GAAI,GAAa,CAAE,YAAW,CAC/B,CAAC,CACO,IAAWA,EAAAA,EAAmB,MAAQ,GAAQ,GACvD,MAAM,EAAgC,CAAE,OAAM,YAAW,CAAC,QAGvD,EAAK,CACZ,MAAU,MACR,0CAA0C,EAAS,kBACjD,EAAQ,EAAI,MAAQ,EAAI,UAE3B,CAIH,EAAA,EAAO,KACL,EAAA,QAAO,MACL,gCAAgC,EAAS,MACvC,EAAS,YAAY,EAAK,GAAK,YAChC,GACF,CACF"}
|
|
1
|
+
{"version":3,"file":"impl-CzO7dqsL.cjs","names":["OneTrustPullResource","OneTrustGetListOfAssessmentsResponse","OneTrustGetAssessmentResponse","OneTrustGetRiskResponse","OneTrustGetUserResponse","keyBy","makeGraphQLRequest","IMPORT_ONE_TRUST_ASSESSMENT_FORMS","mapSeries","map","uniq","OneTrustEnrichedAssessment","OneTrustFileFormat","OneTrustPullSource","buildTranscendGraphQLClient","OneTrustPullResource"],"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":"+gBAQA,MAAa,GAA6B,CACxC,WACA,UAOA,EAAA,QAAI,OAAO,CACT,UAAW,WAAW,IACtB,QAAS,CACP,OAAQ,mBACR,eAAgB,mBAChB,cAAe,UAAU,IAC1B,CACF,CAAC,CCfE,EAAkB,OAAO,OAAOA,EAAAA,EAAqB,CCD9C,GAA4B,CACvC,aACA,QACA,QACA,OAAO,MAUK,CACZ,IAAI,EAAY,IAEZ,IAAU,GAAK,KACjB,EAAY;GAGd,IAAM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GH,GAAI,EAAM,CACR,IAAM,EAAY,EAAK,MAAM,IAAI,CACjC,GAAI,EAAU,OAAS,EACrB,MAAU,MACR,8GACD,CAEH,GAAI,EAAU,GAAG,GAAG,GAAKC,EAAAA,EAAmB,KAC1C,MAAU,MACR,iDAAiD,EAAK,WACpDA,EAAAA,EAAmB,KACpB,cAAc,EAAU,GAAG,GAAG,CAAC,IACjC,CAKL,GAAI,IAAWC,EAAAA,EAAmB,SAAU,CAE1C,GAAI,CAAC,EACH,MAAU,MACR,kFACD,CAGH,GAAI,CAAC,EACH,MAAU,MACR,uFACD,KAEE,CAEL,GAAI,CAAC,EACH,MAAU,MACR,kHACD,CAIH,GAAI,EACF,MAAU,MACR,4FAC+CA,EAAAA,EAAmB,SAAS,0BAC5E,CAIL,EAAA,EAAoB,KAAK,QAAQ,KAAK,CAGtC,IAAM,EACJ,GAAY,EACR,EAA0B,CACxB,WACA,KAAM,EACP,CAAC,CACF,IAAA,GAGA,EACJ,GAAgB,EACZC,EAAAA,GAA4B,EAAc,EAAc,CACxD,IAAA,GAEN,GAAI,CACE,IAAaC,EAAAA,EAAqB,cAChC,IAAWF,EAAAA,EAAmB,UAAY,EAC5C,MAAM,EAAoC,CACxC,WACA,OACA,SACA,GAAI,GAAa,CAAE,YAAW,CAC/B,CAAC,CACO,IAAWA,EAAAA,EAAmB,MAAQ,GAAQ,GACvD,MAAM,EAAgC,CAAE,OAAM,YAAW,CAAC,QAGvD,EAAK,CACZ,MAAU,MACR,0CAA0C,EAAS,kBACjD,EAAQ,EAAI,MAAQ,EAAI,UAE3B,CAIH,EAAA,EAAO,KACL,EAAA,QAAO,MACL,gCAAgC,EAAS,MACvC,EAAS,YAAY,EAAK,GAAK,YAChC,GACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`./enums-CBXlBJii.cjs`);require(`./constants-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
const e=require(`./enums-CBXlBJii.cjs`);require(`./constants-B-TmLA0w.cjs`),require(`./syncConfigurationToTranscend-Bpge5AcC.cjs`);const t=require(`./logger-BaHHbWVd.cjs`);require(`./buildAIIntegrationType-n_Qlv8wG.cjs`),require(`./codecs-JSDJgtyL.cjs`);const n=require(`./readTranscendYaml-CL9nujUr.cjs`),r=require(`./consent-manager-DXWjvCtI.cjs`);require(`./uploadConsents-CJc_6Qwd.cjs`);const i=require(`./api-keys-CDp8NUhN.cjs`),a=require(`./done-input-validation-Cgk5kNBs.cjs`);let o=require(`node:fs`),s=require(`node:path`),c=require(`colors`);c=e.s(c);function l({consentManagerYmlFolder:e,output:l}){a.t(this.process.exit),(!(0,o.existsSync)(e)||!(0,o.lstatSync)(e).isDirectory())&&(t.t.error(c.default.red(`Folder does not exist: "${e}"`)),this.process.exit(1));let u=r.t(i.n(e).map(t=>{let{"consent-manager":r}=n.r((0,s.join)(e,t));return{name:t,input:r}}));n.a(l,{"business-entities":u}),t.t.info(c.default.green(`Successfully wrote ${u.length} business entities to file "${l}"`))}exports.consentManagersToBusinessEntities=l;
|
|
2
|
+
//# sourceMappingURL=impl-D0r4dSxM.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-D0r4dSxM.cjs","names":["consentManagersToBusinessEntitiesHelper","listFiles","readTranscendYaml"],"sources":["../src/commands/inventory/consent-managers-to-business-entities/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport { listFiles } from '../../../lib/api-keys';\nimport { consentManagersToBusinessEntities as consentManagersToBusinessEntitiesHelper } from '../../../lib/consent-manager';\nimport {\n readTranscendYaml,\n writeTranscendYaml,\n} from '../../../lib/readTranscendYaml';\nimport { join } from 'node:path';\n\nimport colors from 'colors';\nimport { logger } from '../../../logger';\nimport { existsSync, lstatSync } from 'node:fs';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface ConsentManagersToBusinessEntitiesCommandFlags {\n consentManagerYmlFolder: string;\n output: string;\n}\n\nexport function consentManagersToBusinessEntities(\n this: LocalContext,\n {\n consentManagerYmlFolder,\n output,\n }: ConsentManagersToBusinessEntitiesCommandFlags,\n): void {\n doneInputValidation(this.process.exit);\n\n // Ensure folder is passed\n if (\n !existsSync(consentManagerYmlFolder) ||\n !lstatSync(consentManagerYmlFolder).isDirectory()\n ) {\n logger.error(\n colors.red(`Folder does not exist: \"${consentManagerYmlFolder}\"`),\n );\n this.process.exit(1);\n }\n\n // Read in each consent manager configuration\n const inputs = listFiles(consentManagerYmlFolder).map((directory) => {\n const { 'consent-manager': consentManager } = readTranscendYaml(\n join(consentManagerYmlFolder, directory),\n );\n return { name: directory, input: consentManager };\n });\n\n // Convert to business entities\n const businessEntities = consentManagersToBusinessEntitiesHelper(inputs);\n\n // write to disk\n writeTranscendYaml(output, {\n 'business-entities': businessEntities,\n });\n\n logger.info(\n colors.green(\n `Successfully wrote ${businessEntities.length} business entities to file \"${output}\"`,\n ),\n );\n}\n"],"mappings":"ijBAmBA,SAAgB,EAEd,CACE,0BACA,UAEI,CACN,EAAA,EAAoB,KAAK,QAAQ,KAAK,EAIpC,EAAA,EAAA,EAAA,YAAY,EAAwB,EACpC,EAAA,EAAA,EAAA,WAAW,EAAwB,CAAC,aAAa,IAEjD,EAAA,EAAO,MACL,EAAA,QAAO,IAAI,2BAA2B,EAAwB,GAAG,CAClE,CACD,KAAK,QAAQ,KAAK,EAAE,EAYtB,IAAM,EAAmBA,EAAAA,EARVC,EAAAA,EAAU,EAAwB,CAAC,IAAK,GAAc,CACnE,GAAM,CAAE,kBAAmB,GAAmBC,EAAAA,GAAAA,EAAAA,EAAAA,MACvC,EAAyB,EAAU,CACzC,CACD,MAAO,CAAE,KAAM,EAAW,MAAO,EAAgB,EACjD,CAGsE,CAGxE,EAAA,EAAmB,EAAQ,CACzB,oBAAqB,EACtB,CAAC,CAEF,EAAA,EAAO,KACL,EAAA,QAAO,MACL,sBAAsB,EAAiB,OAAO,8BAA8B,EAAO,GACpF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`./enums-CBXlBJii.cjs`),t=require(`./constants-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
const e=require(`./enums-CBXlBJii.cjs`),t=require(`./constants-B-TmLA0w.cjs`),n=require(`./syncConfigurationToTranscend-Bpge5AcC.cjs`),r=require(`./logger-BaHHbWVd.cjs`);require(`./buildAIIntegrationType-n_Qlv8wG.cjs`),require(`./codecs-JSDJgtyL.cjs`);const i=require(`./readTranscendYaml-CL9nujUr.cjs`),a=require(`./mergeTranscendInputs-PPpGbYgG.cjs`),o=require(`./api-keys-CDp8NUhN.cjs`),s=require(`./done-input-validation-Cgk5kNBs.cjs`);let c=require(`node:fs`),l=require(`node:path`),u=require(`colors`);u=e.s(u);async function d({transcendUrl:e,auth:t,pageSize:i,publishToPrivacyCenter:a,contents:o,deleteExtraAttributeValues:s=!1,classifyService:c=!1}){let l=n.ti(e,t);try{return!await n.t(o,l,{pageSize:i,publishToPrivacyCenter:a,classifyService:c,deleteExtraAttributeValues:s})}catch(e){return r.t.error(u.default.red(`An unexpected error occurred syncing the schema: ${e.message}`)),!1}}async function f({file:e=`./transcend.yml`,transcendUrl:f,auth:p,variables:m,pageSize:h,publishToPrivacyCenter:g,classifyService:_,deleteExtraAttributeValues:v}){s.t(this.process.exit);let y=await o.r(p),b=n.A(m),x;if(x=Array.isArray(y)&&(0,c.lstatSync)(e).isDirectory()?o.n(e).map(t=>(0,l.join)(e,t)):e.split(`,`),x.length<1)throw Error(`No file specified!`);let S=x.map(e=>{(0,c.existsSync)(e)?r.t.info(u.default.magenta(`Reading file "${e}"...`)):(r.t.error(u.default.red(`The file path does not exist on disk: ${e}. You can specify the filepath using --file=./examples/transcend.yml`)),this.process.exit(1));try{let t=i.r(e,b);return r.t.info(u.default.green(`Successfully read in "${e}"`)),{content:t,name:e.split(`/`).pop().replace(`.yml`,``)}}catch(e){r.t.error(u.default.red(`The shape of your yaml file is invalid with the following errors: ${e.message}`)),this.process.exit(1)}});if(typeof y==`string`){let[e,...n]=S.map(({content:e})=>e);await d({transcendUrl:f,auth:y,contents:a.t(e,...n),publishToPrivacyCenter:g,deleteExtraAttributeValues:v,pageSize:h,classifyService:!!_})||(r.t.info(u.default.red(`Sync encountered errors. View output above for more information, or check out ${t.r}`)),this.process.exit(1))}else{if(S.length!==1&&S.length!==y.length)throw Error(`Expected list of yml files to be equal to the list of API keys.Got ${S.length} YML file${S.length===1?``:`s`} and ${y.length} API key${y.length===1?``:`s`}`);let e=[];await n.Es(y,async(t,n)=>{let i=`[${n+1}/${y.length}][${t.organizationName}] `;r.t.info(u.default.magenta(`~~~\n\n${i}Attempting to push configuration...\n\n~~~`));let a=S.length===1?S[0].content:S.find(e=>e.name===t.organizationName)?.content;if(!a){r.t.error(u.default.red(`${i}Failed to find transcend.yml file for organization: "${t.organizationName}".`)),e.push(t.organizationName);return}await d({transcendUrl:f,auth:t.apiKey,contents:a,pageSize:h,publishToPrivacyCenter:g,deleteExtraAttributeValues:v,classifyService:_})?r.t.info(u.default.green(`${i}Successfully pushed configuration!`)):(r.t.error(u.default.red(`${i}Failed to sync configuration.`)),e.push(t.organizationName))}),e.length>0&&(r.t.info(u.default.red(`Sync encountered errors for "${e.join(`,`)}". View output above for more information, or check out ${t.r}`)),this.process.exit(1))}r.t.info(u.default.green(`Successfully synced yaml file to Transcend! View at ${t.r}`))}exports.push=f;
|
|
2
|
+
//# sourceMappingURL=impl-DBnRvkUi.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-BicjL2jn.cjs","names":["buildTranscendGraphQLClient","syncConfigurationToTranscend","validateTranscendAuth","parseVariablesFromString","listFiles","readTranscendYaml","mergeTranscendInputs","ADMIN_DASH_INTEGRATIONS","mapSeries"],"sources":["../src/commands/inventory/push/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\n\nimport { logger } from '../../../logger';\nimport { mapSeries } from '../../../lib/bluebird';\nimport { existsSync, lstatSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { readTranscendYaml } from '../../../lib/readTranscendYaml';\nimport colors from 'colors';\nimport {\n buildTranscendGraphQLClient,\n syncConfigurationToTranscend,\n} from '../../../lib/graphql';\n\nimport { ADMIN_DASH_INTEGRATIONS } from '../../../constants';\nimport { TranscendInput } from '../../../codecs';\nimport { validateTranscendAuth, listFiles } from '../../../lib/api-keys';\nimport { mergeTranscendInputs } from '../../../lib/mergeTranscendInputs';\nimport { parseVariablesFromString } from '../../../lib/helpers/parseVariablesFromString';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\n/**\n * Sync configuration to Transcend\n *\n * @param options - Options\n * @returns True if synced successfully, false if error occurs\n */\nasync function syncConfiguration({\n transcendUrl,\n auth,\n pageSize,\n publishToPrivacyCenter,\n contents,\n deleteExtraAttributeValues = false,\n classifyService = false,\n}: {\n /** Transcend YAML */\n contents: TranscendInput;\n /** Transcend URL */\n transcendUrl: string;\n /** API key */\n auth: string;\n /** Page size */\n pageSize: number;\n /** Skip privacy center publish step */\n publishToPrivacyCenter: boolean;\n /** classify data flow service if missing */\n classifyService?: boolean;\n /** Delete attributes when syncing */\n deleteExtraAttributeValues?: boolean;\n}): Promise<boolean> {\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Sync to Transcend\n try {\n const encounteredError = await syncConfigurationToTranscend(\n contents,\n client,\n {\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n },\n );\n return !encounteredError;\n } catch (err) {\n logger.error(\n colors.red(\n `An unexpected error occurred syncing the schema: ${err.message}`,\n ),\n );\n return false;\n }\n}\n\nexport interface PushCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n pageSize: number;\n variables: string;\n publishToPrivacyCenter: boolean;\n classifyService: boolean;\n deleteExtraAttributeValues: boolean;\n}\n\nexport async function push(\n this: LocalContext,\n {\n file = './transcend.yml',\n transcendUrl,\n auth,\n variables,\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n }: PushCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth);\n\n // Parse out the variables\n const vars = parseVariablesFromString(variables);\n\n // check if we are being passed a list of API keys and a list of files\n let fileList: string[];\n if (Array.isArray(apiKeyOrList) && lstatSync(file).isDirectory()) {\n fileList = listFiles(file).map((filePath) => join(file, filePath));\n } else {\n fileList = file.split(',');\n }\n\n // Ensure at least one file is parsed\n if (fileList.length < 1) {\n throw new Error('No file specified!');\n }\n\n // eslint-disable-next-line array-callback-return,consistent-return\n const transcendInputs = fileList.map((filePath) => {\n // Ensure yaml file exists on disk\n if (!existsSync(filePath)) {\n logger.error(\n colors.red(\n `The file path does not exist on disk: ${filePath}. You can specify the filepath using --file=./examples/transcend.yml`,\n ),\n );\n this.process.exit(1);\n } else {\n logger.info(colors.magenta(`Reading file \"${filePath}\"...`));\n }\n\n try {\n // Read in the yaml file and validate it's shape\n const newContents = readTranscendYaml(filePath, vars);\n logger.info(colors.green(`Successfully read in \"${filePath}\"`));\n return {\n content: newContents,\n name: filePath.split('/').pop()!.replace('.yml', ''),\n };\n } catch (err) {\n logger.error(\n colors.red(\n `The shape of your yaml file is invalid with the following errors: ${err.message}`,\n ),\n );\n this.process.exit(1);\n }\n });\n\n // process a single API key\n if (typeof apiKeyOrList === 'string') {\n // if passed multiple inputs, merge them together\n const [base, ...rest] = transcendInputs.map(({ content }) => content);\n const contents = mergeTranscendInputs(base, ...rest);\n\n // sync the configuration\n const success = await syncConfiguration({\n transcendUrl,\n auth: apiKeyOrList,\n contents,\n publishToPrivacyCenter,\n deleteExtraAttributeValues,\n pageSize,\n classifyService: !!classifyService,\n });\n\n // exist with error code\n if (!success) {\n logger.info(\n colors.red(\n `Sync encountered errors. View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n this.process.exit(1);\n }\n } else {\n // if passed multiple inputs, expect them to be one per instance\n if (\n transcendInputs.length !== 1 &&\n transcendInputs.length !== apiKeyOrList.length\n ) {\n throw new Error(\n 'Expected list of yml files to be equal to the list of API keys.' +\n `Got ${transcendInputs.length} YML file${\n transcendInputs.length === 1 ? '' : 's'\n } and ${apiKeyOrList.length} API key${\n apiKeyOrList.length === 1 ? '' : 's'\n }`,\n );\n }\n\n const encounteredErrors: string[] = [];\n await mapSeries(apiKeyOrList, async (apiKey, ind) => {\n const prefix = `[${ind + 1}/${apiKeyOrList.length}][${\n apiKey.organizationName\n }] `;\n logger.info(\n colors.magenta(\n `~~~\\n\\n${prefix}Attempting to push configuration...\\n\\n~~~`,\n ),\n );\n\n // use the merged contents if 1 yml passed, else use the contents that map to that organization\n const useContents =\n transcendInputs.length === 1\n ? transcendInputs[0].content\n : transcendInputs.find(\n (input) => input.name === apiKey.organizationName,\n )?.content;\n\n // Throw error if cannot find a yml file matching that organization name\n if (!useContents) {\n logger.error(\n colors.red(\n `${prefix}Failed to find transcend.yml file for organization: \"${apiKey.organizationName}\".`,\n ),\n );\n encounteredErrors.push(apiKey.organizationName);\n return;\n }\n\n const success = await syncConfiguration({\n transcendUrl,\n auth: apiKey.apiKey,\n contents: useContents,\n pageSize,\n publishToPrivacyCenter,\n deleteExtraAttributeValues,\n classifyService,\n });\n\n if (success) {\n logger.info(\n colors.green(`${prefix}Successfully pushed configuration!`),\n );\n } else {\n logger.error(colors.red(`${prefix}Failed to sync configuration.`));\n encounteredErrors.push(apiKey.organizationName);\n }\n });\n\n if (encounteredErrors.length > 0) {\n logger.info(\n colors.red(\n `Sync encountered errors for \"${encounteredErrors.join(\n ',',\n )}\". View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n this.process.exit(1);\n }\n }\n\n // Indicate success\n logger.info(\n colors.green(\n `Successfully synced yaml file to Transcend! View at ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n}\n"],"mappings":"qgBA0BA,eAAe,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D,EAED,EAAA,EAAO,MAAM,EAAA,QAAO,IAAI,GAAG,EAAO,+BAA+B,CAAC,CAClE,EAAkB,KAAK,EAAO,iBAAiB,GAEjD,CAEE,EAAkB,OAAS,IAC7B,EAAA,EAAO,KACL,EAAA,QAAO,IACL,gCAAgC,EAAkB,KAChD,IACD,CAAC,0DAA0DD,EAAAA,IAC7D,CACF,CAED,KAAK,QAAQ,KAAK,EAAE,EAKxB,EAAA,EAAO,KACL,EAAA,QAAO,MACL,uDAAuDA,EAAAA,IACxD,CACF"}
|
|
1
|
+
{"version":3,"file":"impl-DBnRvkUi.cjs","names":["buildTranscendGraphQLClient","syncConfigurationToTranscend","validateTranscendAuth","parseVariablesFromString","listFiles","readTranscendYaml","mergeTranscendInputs","ADMIN_DASH_INTEGRATIONS","mapSeries"],"sources":["../src/commands/inventory/push/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\n\nimport { logger } from '../../../logger';\nimport { mapSeries } from '../../../lib/bluebird';\nimport { existsSync, lstatSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { readTranscendYaml } from '../../../lib/readTranscendYaml';\nimport colors from 'colors';\nimport {\n buildTranscendGraphQLClient,\n syncConfigurationToTranscend,\n} from '../../../lib/graphql';\n\nimport { ADMIN_DASH_INTEGRATIONS } from '../../../constants';\nimport { TranscendInput } from '../../../codecs';\nimport { validateTranscendAuth, listFiles } from '../../../lib/api-keys';\nimport { mergeTranscendInputs } from '../../../lib/mergeTranscendInputs';\nimport { parseVariablesFromString } from '../../../lib/helpers/parseVariablesFromString';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\n/**\n * Sync configuration to Transcend\n *\n * @param options - Options\n * @returns True if synced successfully, false if error occurs\n */\nasync function syncConfiguration({\n transcendUrl,\n auth,\n pageSize,\n publishToPrivacyCenter,\n contents,\n deleteExtraAttributeValues = false,\n classifyService = false,\n}: {\n /** Transcend YAML */\n contents: TranscendInput;\n /** Transcend URL */\n transcendUrl: string;\n /** API key */\n auth: string;\n /** Page size */\n pageSize: number;\n /** Skip privacy center publish step */\n publishToPrivacyCenter: boolean;\n /** classify data flow service if missing */\n classifyService?: boolean;\n /** Delete attributes when syncing */\n deleteExtraAttributeValues?: boolean;\n}): Promise<boolean> {\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Sync to Transcend\n try {\n const encounteredError = await syncConfigurationToTranscend(\n contents,\n client,\n {\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n },\n );\n return !encounteredError;\n } catch (err) {\n logger.error(\n colors.red(\n `An unexpected error occurred syncing the schema: ${err.message}`,\n ),\n );\n return false;\n }\n}\n\nexport interface PushCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n pageSize: number;\n variables: string;\n publishToPrivacyCenter: boolean;\n classifyService: boolean;\n deleteExtraAttributeValues: boolean;\n}\n\nexport async function push(\n this: LocalContext,\n {\n file = './transcend.yml',\n transcendUrl,\n auth,\n variables,\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n }: PushCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth);\n\n // Parse out the variables\n const vars = parseVariablesFromString(variables);\n\n // check if we are being passed a list of API keys and a list of files\n let fileList: string[];\n if (Array.isArray(apiKeyOrList) && lstatSync(file).isDirectory()) {\n fileList = listFiles(file).map((filePath) => join(file, filePath));\n } else {\n fileList = file.split(',');\n }\n\n // Ensure at least one file is parsed\n if (fileList.length < 1) {\n throw new Error('No file specified!');\n }\n\n // eslint-disable-next-line array-callback-return,consistent-return\n const transcendInputs = fileList.map((filePath) => {\n // Ensure yaml file exists on disk\n if (!existsSync(filePath)) {\n logger.error(\n colors.red(\n `The file path does not exist on disk: ${filePath}. You can specify the filepath using --file=./examples/transcend.yml`,\n ),\n );\n this.process.exit(1);\n } else {\n logger.info(colors.magenta(`Reading file \"${filePath}\"...`));\n }\n\n try {\n // Read in the yaml file and validate it's shape\n const newContents = readTranscendYaml(filePath, vars);\n logger.info(colors.green(`Successfully read in \"${filePath}\"`));\n return {\n content: newContents,\n name: filePath.split('/').pop()!.replace('.yml', ''),\n };\n } catch (err) {\n logger.error(\n colors.red(\n `The shape of your yaml file is invalid with the following errors: ${err.message}`,\n ),\n );\n this.process.exit(1);\n }\n });\n\n // process a single API key\n if (typeof apiKeyOrList === 'string') {\n // if passed multiple inputs, merge them together\n const [base, ...rest] = transcendInputs.map(({ content }) => content);\n const contents = mergeTranscendInputs(base, ...rest);\n\n // sync the configuration\n const success = await syncConfiguration({\n transcendUrl,\n auth: apiKeyOrList,\n contents,\n publishToPrivacyCenter,\n deleteExtraAttributeValues,\n pageSize,\n classifyService: !!classifyService,\n });\n\n // exist with error code\n if (!success) {\n logger.info(\n colors.red(\n `Sync encountered errors. View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n this.process.exit(1);\n }\n } else {\n // if passed multiple inputs, expect them to be one per instance\n if (\n transcendInputs.length !== 1 &&\n transcendInputs.length !== apiKeyOrList.length\n ) {\n throw new Error(\n 'Expected list of yml files to be equal to the list of API keys.' +\n `Got ${transcendInputs.length} YML file${\n transcendInputs.length === 1 ? '' : 's'\n } and ${apiKeyOrList.length} API key${\n apiKeyOrList.length === 1 ? '' : 's'\n }`,\n );\n }\n\n const encounteredErrors: string[] = [];\n await mapSeries(apiKeyOrList, async (apiKey, ind) => {\n const prefix = `[${ind + 1}/${apiKeyOrList.length}][${\n apiKey.organizationName\n }] `;\n logger.info(\n colors.magenta(\n `~~~\\n\\n${prefix}Attempting to push configuration...\\n\\n~~~`,\n ),\n );\n\n // use the merged contents if 1 yml passed, else use the contents that map to that organization\n const useContents =\n transcendInputs.length === 1\n ? transcendInputs[0].content\n : transcendInputs.find(\n (input) => input.name === apiKey.organizationName,\n )?.content;\n\n // Throw error if cannot find a yml file matching that organization name\n if (!useContents) {\n logger.error(\n colors.red(\n `${prefix}Failed to find transcend.yml file for organization: \"${apiKey.organizationName}\".`,\n ),\n );\n encounteredErrors.push(apiKey.organizationName);\n return;\n }\n\n const success = await syncConfiguration({\n transcendUrl,\n auth: apiKey.apiKey,\n contents: useContents,\n pageSize,\n publishToPrivacyCenter,\n deleteExtraAttributeValues,\n classifyService,\n });\n\n if (success) {\n logger.info(\n colors.green(`${prefix}Successfully pushed configuration!`),\n );\n } else {\n logger.error(colors.red(`${prefix}Failed to sync configuration.`));\n encounteredErrors.push(apiKey.organizationName);\n }\n });\n\n if (encounteredErrors.length > 0) {\n logger.info(\n colors.red(\n `Sync encountered errors for \"${encounteredErrors.join(\n ',',\n )}\". View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n this.process.exit(1);\n }\n }\n\n // Indicate success\n logger.info(\n colors.green(\n `Successfully synced yaml file to Transcend! View at ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n}\n"],"mappings":"qgBA0BA,eAAe,EAAkB,CAC/B,eACA,OACA,WACA,yBACA,WACA,6BAA6B,GAC7B,kBAAkB,IAgBC,CACnB,IAAM,EAASA,EAAAA,GAA4B,EAAc,EAAK,CAG9D,GAAI,CAWF,MAAO,CAVkB,MAAMC,EAAAA,EAC7B,EACA,EACA,CACE,WACA,yBACA,kBACA,6BACD,CACF,OAEM,EAAK,CAMZ,OALA,EAAA,EAAO,MACL,EAAA,QAAO,IACL,oDAAoD,EAAI,UACzD,CACF,CACM,IAeX,eAAsB,EAEpB,CACE,OAAO,kBACP,eACA,OACA,YACA,WACA,yBACA,kBACA,8BAEa,CACf,EAAA,EAAoB,KAAK,QAAQ,KAAK,CAGtC,IAAM,EAAe,MAAMC,EAAAA,EAAsB,EAAK,CAGhD,EAAOC,EAAAA,EAAyB,EAAU,CAG5C,EAQJ,GAPA,AAGE,EAHE,MAAM,QAAQ,EAAa,GAAA,EAAA,EAAA,WAAc,EAAK,CAAC,aAAa,CACnDC,EAAAA,EAAU,EAAK,CAAC,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,EAA8B,EAAE,CACtC,MAAMC,EAAAA,GAAU,EAAc,MAAO,EAAQ,IAAQ,CACnD,IAAM,EAAS,IAAI,EAAM,EAAE,GAAG,EAAa,OAAO,IAChD,EAAO,iBACR,IACD,EAAA,EAAO,KACL,EAAA,QAAO,QACL,UAAU,EAAO,4CAClB,CACF,CAGD,IAAM,EACJ,EAAgB,SAAW,EACvB,EAAgB,GAAG,QACnB,EAAgB,KACb,GAAU,EAAM,OAAS,EAAO,iBAClC,EAAE,QAGT,GAAI,CAAC,EAAa,CAChB,EAAA,EAAO,MACL,EAAA,QAAO,IACL,GAAG,EAAO,uDAAuD,EAAO,iBAAiB,IAC1F,CACF,CACD,EAAkB,KAAK,EAAO,iBAAiB,CAC/C,OAGc,MAAM,EAAkB,CACtC,eACA,KAAM,EAAO,OACb,SAAU,EACV,WACA,yBACA,6BACA,kBACD,CAAC,CAGA,EAAA,EAAO,KACL,EAAA,QAAO,MAAM,GAAG,EAAO,oCAAoC,CAC5D,EAED,EAAA,EAAO,MAAM,EAAA,QAAO,IAAI,GAAG,EAAO,+BAA+B,CAAC,CAClE,EAAkB,KAAK,EAAO,iBAAiB,GAEjD,CAEE,EAAkB,OAAS,IAC7B,EAAA,EAAO,KACL,EAAA,QAAO,IACL,gCAAgC,EAAkB,KAChD,IACD,CAAC,0DAA0DD,EAAAA,IAC7D,CACF,CAED,KAAK,QAAQ,KAAK,EAAE,EAKxB,EAAA,EAAO,KACL,EAAA,QAAO,MACL,uDAAuDA,EAAAA,IACxD,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
require(`./enums-CBXlBJii.cjs`),require(`./constants-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
require(`./enums-CBXlBJii.cjs`),require(`./constants-B-TmLA0w.cjs`);const e=require(`./syncConfigurationToTranscend-Bpge5AcC.cjs`);require(`./logger-BaHHbWVd.cjs`),require(`./buildAIIntegrationType-n_Qlv8wG.cjs`);const t=require(`./done-input-validation-Cgk5kNBs.cjs`);async function n({auth:n,dataSiloId:r,actions:i,transcendUrl:a}){t.t(this.process.exit),await e.L({requestActions:i,transcendUrl:a,auth:n,dataSiloId:r})}exports.retryRequestDataSilos=n;
|
|
2
|
+
//# sourceMappingURL=impl-DOmKR8yz.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-DOmKR8yz.cjs","names":["retryRequestDataSilosHelper"],"sources":["../src/commands/request/system/retry-request-data-silos/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../../context';\nimport type { RequestAction } from '@transcend-io/privacy-types';\nimport { retryRequestDataSilos as retryRequestDataSilosHelper } from '../../../../lib/requests';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation';\n\nexport interface RetryRequestDataSilosCommandFlags {\n auth: string;\n dataSiloId: string;\n actions: RequestAction[];\n transcendUrl: string;\n}\n\nexport async function retryRequestDataSilos(\n this: LocalContext,\n {\n auth,\n dataSiloId,\n actions,\n transcendUrl,\n }: RetryRequestDataSilosCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await retryRequestDataSilosHelper({\n requestActions: actions,\n transcendUrl,\n auth,\n dataSiloId,\n });\n}\n"],"mappings":"6QAYA,eAAsB,EAEpB,CACE,OACA,aACA,UACA,gBAEa,CACf,EAAA,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAMA,EAAAA,EAA4B,CAChC,eAAgB,EAChB,eACA,OACA,aACD,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`./enums-CBXlBJii.cjs`),t=require(`./constants-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
const e=require(`./enums-CBXlBJii.cjs`),t=require(`./constants-B-TmLA0w.cjs`),n=require(`./syncConfigurationToTranscend-Bpge5AcC.cjs`),r=require(`./logger-BaHHbWVd.cjs`);require(`./buildAIIntegrationType-n_Qlv8wG.cjs`),require(`./codecs-JSDJgtyL.cjs`),require(`./api-keys-CDp8NUhN.cjs`);const i=require(`./done-input-validation-Cgk5kNBs.cjs`),a=require(`./code-scanning-BwfVNIHr.cjs`);let o=require(`colors`);o=e.s(o);let s=require(`child_process`);const c=`A repository name must be provided. You can specify using --repositoryName=$REPO_NAME or by ensuring the command "git config --get remote.origin.url" returns the name of the repository`;async function l({auth:e,scanPath:l,ignoreDirs:u,repositoryName:d,transcendUrl:f}){i.t(this.process.exit);let p=d;if(!p)try{let e=(0,s.execSync)(`cd ${l} && git config --get remote.origin.url`).toString(`utf-8`).trim();[p]=e.includes(`https:`)?e.split(`/`).slice(3).join(`/`).split(`.`):(e.split(`:`).pop()||``).split(`.`),p||(r.t.error(o.default.red(c)),this.process.exit(1))}catch(e){r.t.error(o.default.red(`${c} - Got error: ${e.message}`)),this.process.exit(1)}let m=n.ti(f,e),h=await a.t({scanPath:l,ignoreDirs:u,repositoryName:p});await n.zt(m,h);let g=new URL(t.t);g.pathname=`/code-scanning/code-packages`,r.t.info(o.default.green(`Scan found ${h.length} packages at ${l}! View results at '${g.href}'`))}exports.scanPackages=l;
|
|
2
|
+
//# sourceMappingURL=impl-DX7gLoTo.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-DX7gLoTo.cjs","names":["buildTranscendGraphQLClient","findCodePackagesInFolder","syncCodePackages","ADMIN_DASH"],"sources":["../src/commands/inventory/scan-packages/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport { logger } from '../../../logger';\nimport colors from 'colors';\nimport { ADMIN_DASH } from '../../../constants';\nimport { findCodePackagesInFolder } from '../../../lib/code-scanning';\nimport {\n buildTranscendGraphQLClient,\n syncCodePackages,\n} from '../../../lib/graphql';\nimport { execSync } from 'child_process';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nconst REPO_ERROR =\n 'A repository name must be provided. ' +\n 'You can specify using --repositoryName=$REPO_NAME or by ensuring the ' +\n 'command \"git config --get remote.origin.url\" returns the name of the repository';\n\nexport interface ScanPackagesCommandFlags {\n auth: string;\n scanPath: string;\n ignoreDirs?: string[];\n repositoryName?: string;\n transcendUrl: string;\n}\n\nexport async function scanPackages(\n this: LocalContext,\n {\n auth,\n scanPath,\n ignoreDirs,\n repositoryName,\n transcendUrl,\n }: ScanPackagesCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n // Ensure repository name is specified\n let gitRepositoryName = repositoryName;\n if (!gitRepositoryName) {\n try {\n const name = execSync(\n `cd ${scanPath} && git config --get remote.origin.url`,\n );\n // Trim and parse the URL\n const url = name.toString('utf-8').trim();\n [gitRepositoryName] = !url.includes('https:')\n ? (url.split(':').pop() || '').split('.')\n : url.split('/').slice(3).join('/').split('.');\n if (!gitRepositoryName) {\n logger.error(colors.red(REPO_ERROR));\n this.process.exit(1);\n }\n } catch (err) {\n logger.error(colors.red(`${REPO_ERROR} - Got error: ${err.message}`));\n this.process.exit(1);\n }\n }\n\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Scan the codebase to discovery packages\n const results = await findCodePackagesInFolder({\n scanPath,\n ignoreDirs,\n repositoryName: gitRepositoryName,\n });\n\n // Report scan to Transcend\n await syncCodePackages(client, results);\n\n const newUrl = new URL(ADMIN_DASH);\n newUrl.pathname = '/code-scanning/code-packages';\n\n // Indicate success\n logger.info(\n colors.green(\n `Scan found ${results.length} packages at ${scanPath}! ` +\n `View results at '${newUrl.href}'`,\n ),\n );\n}\n"],"mappings":"icAYA,MAAM,EACJ,2LAYF,eAAsB,EAEpB,CACE,OACA,WACA,aACA,iBACA,gBAEa,CACf,EAAA,EAAoB,KAAK,QAAQ,KAAK,CAGtC,IAAI,EAAoB,EACxB,GAAI,CAAC,EACH,GAAI,CAKF,IAAM,GAAA,EAAA,EAAA,UAHJ,MAAM,EAAS,wCAChB,CAEgB,SAAS,QAAQ,CAAC,MAAM,CACzC,CAAC,GAAsB,EAAI,SAAS,SAAS,CAEzC,EAAI,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC,KAAK,IAAI,CAAC,MAAM,IAAI,EAD3C,EAAI,MAAM,IAAI,CAAC,KAAK,EAAI,IAAI,MAAM,IAAI,CAEtC,IACH,EAAA,EAAO,MAAM,EAAA,QAAO,IAAI,EAAW,CAAC,CACpC,KAAK,QAAQ,KAAK,EAAE,QAEf,EAAK,CACZ,EAAA,EAAO,MAAM,EAAA,QAAO,IAAI,GAAG,EAAW,gBAAgB,EAAI,UAAU,CAAC,CACrE,KAAK,QAAQ,KAAK,EAAE,CAKxB,IAAM,EAASA,EAAAA,GAA4B,EAAc,EAAK,CAGxD,EAAU,MAAMC,EAAAA,EAAyB,CAC7C,WACA,aACA,eAAgB,EACjB,CAAC,CAGF,MAAMC,EAAAA,GAAiB,EAAQ,EAAQ,CAEvC,IAAM,EAAS,IAAI,IAAIC,EAAAA,EAAW,CAClC,EAAO,SAAW,+BAGlB,EAAA,EAAO,KACL,EAAA,QAAO,MACL,cAAc,EAAQ,OAAO,eAAe,EAAS,qBAC/B,EAAO,KAAK,GACnC,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`./enums-CBXlBJii.cjs`);require(`./constants-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
const e=require(`./enums-CBXlBJii.cjs`);require(`./constants-B-TmLA0w.cjs`);const t=require(`./syncConfigurationToTranscend-Bpge5AcC.cjs`),n=require(`./logger-BaHHbWVd.cjs`);require(`./buildAIIntegrationType-n_Qlv8wG.cjs`);const r=require(`./pooling-Ct83vfEh.cjs`),i=require(`./done-input-validation-Cgk5kNBs.cjs`);let a=require(`node:fs`),o=require(`node:path`),s=require(`colors`);s=e.s(s);let c=require(`fast-csv`);c=e.s(c);let l=require(`node:events`),u=require(`node:fs/promises`),d=require(`node:stream/promises`),f=require(`node:stream`),p=require(`csv-parse`);function m(e,t){e||(n.t.error(s.default.red(`A --directory must be provided.`)),t.process.exit(1));let r=[];try{r=(0,a.readdirSync)(e).filter(e=>e.endsWith(`.csv`)).map(t=>(0,o.join)(e,t)).filter(e=>{try{return(0,a.statSync)(e).isFile()}catch{return!1}})}catch(r){n.t.error(s.default.red(`Failed to read directory: ${e}`)),n.t.error(s.default.red(r.message)),t.process.exit(1)}return r.length===0&&(n.t.error(s.default.red(`No CSV files found in directory: ${e}`)),t.process.exit(1)),n.t.info(s.default.green(`Found: ${r.join(`, `)} CSV files`)),r}function h(e,t){let n=(0,a.createWriteStream)(e),r=c.format({headers:t,writeHeaders:!0,objectMode:!0});return r.pipe(n),{async write(e){r.write(e)||await(0,l.once)(r,`drain`)},async end(){let e=Promise.all([(0,l.once)(n,`finish`)]);r.end(),await e}}}function g(e){return String(e).padStart(4,`0`)}function _(e){return Buffer.byteLength(Object.values(e).map(e=>e==null?``:String(e)).join(`,`),`utf8`)}async function v(e){let{filePath:t,outputDir:r,clearOutputDir:i,chunkSizeMB:c,onProgress:l,reportEveryMs:m=500}=e,{size:v}=await(0,u.stat)(t),y=0;n.t.info(s.default.magenta(`Chunking ${t} into ~${c}MB files...`));let b=Math.floor(c*1024*1024),x=(0,o.basename)(t,`.csv`),S=r||(0,o.dirname)(t);if(n.t.info(s.default.magenta(`Output directory: ${S}`)),await(0,u.mkdir)(S,{recursive:!0}),i){n.t.warn(s.default.yellow(`Clearing output directory: ${S}`));let e=await(0,u.readdir)(S);await Promise.all(e.filter(e=>e.startsWith(`${x}_chunk_`)&&e.endsWith(`.csv`)).map(e=>(0,u.unlink)((0,o.join)(S,e))))}let C=null,w=null,T=0,E=1,D=0,O=new p.Parser({columns:!1,skip_empty_lines:!0}),k=0,A=0,j=()=>{let e=A>0?k/A:0,t=e>0?Math.max(T,Math.ceil(v/e)):void 0;l(T,t),y=Date.now()};j();let M=null,N=()=>(0,o.join)(S,`${x}_chunk_${g(E)}.csv`),P=new f.Transform({objectMode:!0,async transform(e,t,r){try{if(!C){C=e.slice(0),w=C.length,M=h(N(),C),r();return}w!==null&&e.length!==w&&n.t.warn(s.default.yellow(`Row has ${e.length} cols; expected ${w}`)),T+=1,T%25e4==0&&l(T);let t=Object.fromEntries(C.map((t,n)=>[t,e[n]])),i=_(t);k+=i,A+=1,Date.now()-y>=m&&j(),M&&D>0&&D+i>b&&(await M.end(),E+=1,D=0,n.t.info(s.default.green(`Rolling to chunk ${E} after ${T.toLocaleString()} rows.`)),M=h(N(),C)),M||=h(N(),C),await M.write(t),D+=i,r()}catch(e){r(e)}},async flush(e){try{M&&=(await M.end(),null),j(),e()}catch(t){e(t)}}});await(0,d.pipeline)((0,a.createReadStream)(t),O,P),l(T),n.t.info(s.default.green(`Chunked ${t} into ${E} file(s); processed ${T.toLocaleString()} rows.`))}async function y(){let e=Number(process.env.WORKER_ID||`0`);n.t.info(`[w${e}] 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 v({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.O(r);n.t.error(`[w${e}] ERROR ${i}: ${a}`),process.send?.({type:`result`,payload:{ok:!1,filePath:i,error:a}})}}),await new Promise(()=>{})}function b(e){return r.r(e)}function x(e){return r.i(e)}const S={renderHeader:b,renderWorkers:x};function C(){return typeof __filename<`u`?__filename:process.argv[1]}async function w(e){i.t(this.process.exit);let{directory:t,outputDir:a,clearOutputDir:o,chunkSizeMB:c,concurrency:l,viewerMode:u}=e,d=m(t,this),{poolSize:f,cpuCount:p}=r.s(l,d.length);n.t.info(s.default.green(`Chunking ${d.length} CSV file(s) with pool size ${f} (CPU=${p})`));let h=d.map(e=>({filePath:e,options:{outputDir:a,clearOutputDir:o,chunkSizeMB:c}}));await r.n({title:`Chunk CSV - ${t}`,baseDir:t||a||process.cwd(),childFlag:r.o,childModulePath:C(),poolSize:f,cpuCount:p,filesTotal:d.length,hooks:{nextTask:()=>h.shift(),taskLabel:e=>e.filePath,initTotals:()=>({}),initSlotProgress:()=>void 0,onProgress:e=>e,onResult:(e,t)=>({totals:e,ok:!!t.ok}),postProcess:async()=>{}},viewerMode:u,render:e=>r.a(e,S,u),extraKeyHandler:({logsBySlot:e,repaint:t,setPaused:n})=>r.t({logsBySlot:e,repaint:t,setPaused:n})})}process.argv.includes(r.o)&&y().catch(e=>{n.t.error(e),process.exit(1)}),exports.chunkCsv=w;
|
|
2
|
+
//# sourceMappingURL=impl-DcQ_HfDZ.cjs.map
|