@transcend-io/cli 10.5.3 → 10.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app-Ba_-DZvM.mjs +131 -0
- package/dist/{app-D4JCT1PC.mjs.map → app-Ba_-DZvM.mjs.map} +1 -1
- package/dist/{approvePrivacyRequests-Cx6ST602.mjs → approvePrivacyRequests-BMxJtVip.mjs} +2 -2
- package/dist/{approvePrivacyRequests-Cx6ST602.mjs.map → approvePrivacyRequests-BMxJtVip.mjs.map} +1 -1
- package/dist/bin/bash-complete.mjs +1 -1
- package/dist/bin/cli.mjs +1 -1
- package/dist/bin/deprecated-command.mjs +1 -1
- package/dist/bin/deprecated-command.mjs.map +1 -1
- package/dist/{buildXdiSyncEndpoint-Ckyqj2UM.mjs → buildXdiSyncEndpoint-CoMnCoOr.mjs} +2 -2
- package/dist/{buildXdiSyncEndpoint-Ckyqj2UM.mjs.map → buildXdiSyncEndpoint-CoMnCoOr.mjs.map} +1 -1
- package/dist/{bulkRestartRequests-tkAGltVb.mjs → bulkRestartRequests-BCjIRquE.mjs} +2 -2
- package/dist/{bulkRestartRequests-tkAGltVb.mjs.map → bulkRestartRequests-BCjIRquE.mjs.map} +1 -1
- package/dist/{bulkRetryEnrichers-DbMOwMCn.mjs → bulkRetryEnrichers-B04E_eQ1.mjs} +2 -2
- package/dist/{bulkRetryEnrichers-DbMOwMCn.mjs.map → bulkRetryEnrichers-B04E_eQ1.mjs.map} +1 -1
- package/dist/{cancelPrivacyRequests-CeNZ5xYE.mjs → cancelPrivacyRequests-BHVJdn5R.mjs} +2 -2
- package/dist/{cancelPrivacyRequests-CeNZ5xYE.mjs.map → cancelPrivacyRequests-BHVJdn5R.mjs.map} +1 -1
- package/dist/collectCsvFilesOrExit-CbtyKAzu.mjs.map +1 -1
- package/dist/collectParquetFilesOrExit-BJiAyaQ5.mjs.map +1 -1
- package/dist/{command-CFdo5aJj.mjs → command-Boc-4Yl2.mjs} +2 -2
- package/dist/{command-CFdo5aJj.mjs.map → command-Boc-4Yl2.mjs.map} +1 -1
- package/dist/constants-BmwXDQu9.mjs.map +1 -1
- package/dist/constants-CLxPXlJM.mjs +2 -0
- package/dist/{constants-ClkQQhJs.mjs.map → constants-CLxPXlJM.mjs.map} +1 -1
- package/dist/constants-CeIAxxnY.mjs +2 -0
- package/dist/{constants-BnvAwpw3.mjs.map → constants-CeIAxxnY.mjs.map} +1 -1
- package/dist/{createExtraKeyHandler-8bqtQnc3.mjs → createExtraKeyHandler-CUsI4MJp.mjs} +3 -3
- package/dist/{createExtraKeyHandler-8bqtQnc3.mjs.map → createExtraKeyHandler-CUsI4MJp.mjs.map} +1 -1
- package/dist/dataFlowsToDataSilos-Ca2DtTsd.mjs.map +1 -1
- package/dist/{downloadPrivacyRequestFiles-JkLX2eZh.mjs → downloadPrivacyRequestFiles-CmXRxhiH.mjs} +2 -2
- package/dist/{downloadPrivacyRequestFiles-JkLX2eZh.mjs.map → downloadPrivacyRequestFiles-CmXRxhiH.mjs.map} +1 -1
- package/dist/fetchAllRequests-CHHdyb4Q.mjs.map +1 -1
- package/dist/{generateCrossAccountApiKeys-JsObx9gN.mjs → generateCrossAccountApiKeys-DFPlA4Xq.mjs} +2 -2
- package/dist/{generateCrossAccountApiKeys-JsObx9gN.mjs.map → generateCrossAccountApiKeys-DFPlA4Xq.mjs.map} +1 -1
- package/dist/{impl-CZsSqRpk.mjs → impl-0SyxIFWL.mjs} +2 -2
- package/dist/{impl-CZsSqRpk.mjs.map → impl-0SyxIFWL.mjs.map} +1 -1
- package/dist/{impl-0zyJsNyk.mjs → impl-B6G1l077.mjs} +2 -2
- package/dist/{impl-0zyJsNyk.mjs.map → impl-B6G1l077.mjs.map} +1 -1
- package/dist/{impl-DLTIhyet.mjs → impl-B9k51caj.mjs} +2 -2
- package/dist/{impl-DLTIhyet.mjs.map → impl-B9k51caj.mjs.map} +1 -1
- package/dist/{impl-D1kF9Dsn.mjs → impl-BF43axuw.mjs} +2 -2
- package/dist/{impl-D1kF9Dsn.mjs.map → impl-BF43axuw.mjs.map} +1 -1
- package/dist/{impl-DCvvfSiB.mjs → impl-BNlURiXP.mjs} +2 -2
- package/dist/{impl-DCvvfSiB.mjs.map → impl-BNlURiXP.mjs.map} +1 -1
- package/dist/{impl-32l0F-6y.mjs → impl-BPzWGw_C.mjs} +2 -2
- package/dist/{impl-32l0F-6y.mjs.map → impl-BPzWGw_C.mjs.map} +1 -1
- package/dist/{impl-V_psvfr9.mjs → impl-BVW11QMd.mjs} +2 -2
- package/dist/{impl-V_psvfr9.mjs.map → impl-BVW11QMd.mjs.map} +1 -1
- package/dist/impl-BW3HCdPO.mjs.map +1 -1
- package/dist/{impl-1T6-RGRm.mjs → impl-B_H7wl2s.mjs} +2 -2
- package/dist/{impl-1T6-RGRm.mjs.map → impl-B_H7wl2s.mjs.map} +1 -1
- package/dist/{impl-mapQXlwk.mjs → impl-B_sOmwwO.mjs} +2 -2
- package/dist/{impl-mapQXlwk.mjs.map → impl-B_sOmwwO.mjs.map} +1 -1
- package/dist/{impl-LQ9HIgIH.mjs → impl-BfRfETav.mjs} +2 -2
- package/dist/{impl-LQ9HIgIH.mjs.map → impl-BfRfETav.mjs.map} +1 -1
- package/dist/{impl-EqIE1xfb.mjs → impl-BhNbz52a.mjs} +2 -2
- package/dist/{impl-EqIE1xfb.mjs.map → impl-BhNbz52a.mjs.map} +1 -1
- package/dist/impl-BjCQSRLu.mjs.map +1 -1
- package/dist/{impl-C6tc6PTH.mjs → impl-BropNAtt.mjs} +2 -2
- package/dist/{impl-C6tc6PTH.mjs.map → impl-BropNAtt.mjs.map} +1 -1
- package/dist/impl-BuxT4Cx2.mjs.map +1 -1
- package/dist/{impl-DOBIvG7_.mjs → impl-C0aNrkWB.mjs} +2 -2
- package/dist/{impl-DOBIvG7_.mjs.map → impl-C0aNrkWB.mjs.map} +1 -1
- package/dist/impl-CFYxHmDT.mjs.map +1 -1
- package/dist/{impl-CHhoOhWA.mjs → impl-Cik8JUMN.mjs} +2 -2
- package/dist/{impl-CHhoOhWA.mjs.map → impl-Cik8JUMN.mjs.map} +1 -1
- package/dist/{impl-BjpmKi-f.mjs → impl-CluXp6cM.mjs} +2 -2
- package/dist/{impl-BjpmKi-f.mjs.map → impl-CluXp6cM.mjs.map} +1 -1
- package/dist/{impl-D_q6lzqv.mjs → impl-Cur6XyjJ.mjs} +2 -2
- package/dist/{impl-D_q6lzqv.mjs.map → impl-Cur6XyjJ.mjs.map} +1 -1
- package/dist/impl-Cw3_0zqC.mjs.map +1 -1
- package/dist/{impl-Cpl-jIAf.mjs → impl-D08NgYQt.mjs} +2 -2
- package/dist/{impl-Cpl-jIAf.mjs.map → impl-D08NgYQt.mjs.map} +1 -1
- package/dist/{impl-Dej-oi2M.mjs → impl-DAkC-ISt.mjs} +2 -2
- package/dist/{impl-Dej-oi2M.mjs.map → impl-DAkC-ISt.mjs.map} +1 -1
- package/dist/{impl-CabL3fjn.mjs → impl-DFQi40lD.mjs} +2 -2
- package/dist/{impl-CabL3fjn.mjs.map → impl-DFQi40lD.mjs.map} +1 -1
- package/dist/impl-DKIBerx4.mjs +4 -0
- package/dist/{impl-BjIylEKQ.mjs.map → impl-DKIBerx4.mjs.map} +1 -1
- package/dist/{impl-SOBRxcMf.mjs → impl-DM9-TSso.mjs} +2 -2
- package/dist/{impl-SOBRxcMf.mjs.map → impl-DM9-TSso.mjs.map} +1 -1
- package/dist/{impl-CV7xk_an.mjs → impl-DOOUxjYh.mjs} +2 -2
- package/dist/{impl-CV7xk_an.mjs.map → impl-DOOUxjYh.mjs.map} +1 -1
- package/dist/impl-DQQ_nI25.mjs.map +1 -1
- package/dist/{impl-BEEbAmMg.mjs → impl-DSh-TbvV.mjs} +2 -2
- package/dist/{impl-BEEbAmMg.mjs.map → impl-DSh-TbvV.mjs.map} +1 -1
- package/dist/{impl-BFsdR7JB.mjs → impl-DXJFzBeT.mjs} +2 -2
- package/dist/{impl-BFsdR7JB.mjs.map → impl-DXJFzBeT.mjs.map} +1 -1
- package/dist/{impl-X9_G1rr9.mjs → impl-DZh4_ftE.mjs} +2 -2
- package/dist/{impl-X9_G1rr9.mjs.map → impl-DZh4_ftE.mjs.map} +1 -1
- package/dist/{impl-Boeq91_R.mjs → impl-D_0xeTKV.mjs} +2 -2
- package/dist/{impl-Boeq91_R.mjs.map → impl-D_0xeTKV.mjs.map} +1 -1
- package/dist/{impl-CyxIQF7a.mjs → impl-Df2PHYFL.mjs} +2 -2
- package/dist/{impl-CyxIQF7a.mjs.map → impl-Df2PHYFL.mjs.map} +1 -1
- package/dist/{impl-DXHqqWJb.mjs → impl-DiHeNVFr.mjs} +2 -2
- package/dist/{impl-DXHqqWJb.mjs.map → impl-DiHeNVFr.mjs.map} +1 -1
- package/dist/{impl-oSzcpC-d.mjs → impl-DrrdL07c.mjs} +2 -2
- package/dist/{impl-oSzcpC-d.mjs.map → impl-DrrdL07c.mjs.map} +1 -1
- package/dist/{impl-C7ilg036.mjs → impl-DzLb8cTW.mjs} +2 -2
- package/dist/{impl-C7ilg036.mjs.map → impl-DzLb8cTW.mjs.map} +1 -1
- package/dist/{impl-C107Rsdg.mjs → impl-OB3mOEa_.mjs} +2 -2
- package/dist/{impl-C107Rsdg.mjs.map → impl-OB3mOEa_.mjs.map} +1 -1
- package/dist/{impl-Dt_JYmLa.mjs → impl-VVA4YqAf.mjs} +2 -2
- package/dist/{impl-Dt_JYmLa.mjs.map → impl-VVA4YqAf.mjs.map} +1 -1
- package/dist/{impl-BZiEZRLo.mjs → impl-YtstnAO6.mjs} +2 -2
- package/dist/{impl-BZiEZRLo.mjs.map → impl-YtstnAO6.mjs.map} +1 -1
- package/dist/{impl-Czs1f6pa.mjs → impl-oZ2tCI0C.mjs} +2 -2
- package/dist/{impl-Czs1f6pa.mjs.map → impl-oZ2tCI0C.mjs.map} +1 -1
- package/dist/{impl-CLBBpAMO.mjs → impl-sjVATWtP.mjs} +2 -2
- package/dist/{impl-CLBBpAMO.mjs.map → impl-sjVATWtP.mjs.map} +1 -1
- package/dist/impl-xtlx25UP.mjs.map +1 -1
- package/dist/index.d.mts +12 -12
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/{inquirer-BqZXFEt1.mjs → inquirer-B4iEodLy.mjs} +2 -2
- package/dist/{inquirer-BqZXFEt1.mjs.map → inquirer-B4iEodLy.mjs.map} +1 -1
- package/dist/{markRequestDataSiloIdsCompleted-CB2IoaJc.mjs → markRequestDataSiloIdsCompleted-D3e6FsGA.mjs} +2 -2
- package/dist/{markRequestDataSiloIdsCompleted-CB2IoaJc.mjs.map → markRequestDataSiloIdsCompleted-D3e6FsGA.mjs.map} +1 -1
- package/dist/{markSilentPrivacyRequests-Ork0EgjT.mjs → markSilentPrivacyRequests-DzgnobYG.mjs} +2 -2
- package/dist/{markSilentPrivacyRequests-Ork0EgjT.mjs.map → markSilentPrivacyRequests-DzgnobYG.mjs.map} +1 -1
- package/dist/{notifyPrivacyRequestsAdditionalTime-BB6Yi2p3.mjs → notifyPrivacyRequestsAdditionalTime-BcJ701Ta.mjs} +2 -2
- package/dist/{notifyPrivacyRequestsAdditionalTime-BB6Yi2p3.mjs.map → notifyPrivacyRequestsAdditionalTime-BcJ701Ta.mjs.map} +1 -1
- package/dist/parquetToCsvOneFile-B84XXInh.mjs.map +1 -1
- package/dist/{parseAttributesFromString-D1Yl0xwT.mjs → parseAttributesFromString-q4-59nEN.mjs} +2 -2
- package/dist/{parseAttributesFromString-D1Yl0xwT.mjs.map → parseAttributesFromString-q4-59nEN.mjs.map} +1 -1
- package/dist/parseVariablesFromString-BeKOGw5n.mjs.map +1 -1
- package/dist/pullAllDatapoints-Bbmky50p.mjs.map +1 -1
- package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-DuelGEsb.mjs → pullChunkedCustomSiloOutstandingIdentifiers-CPY9eRLF.mjs} +2 -2
- package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-DuelGEsb.mjs.map → pullChunkedCustomSiloOutstandingIdentifiers-CPY9eRLF.mjs.map} +1 -1
- package/dist/pullConsentManagerMetrics-zKgjc3Ap.mjs.map +1 -1
- package/dist/{pullManualEnrichmentIdentifiersToCsv-CoFubXre.mjs → pullManualEnrichmentIdentifiersToCsv-CDCL8Ju4.mjs} +2 -2
- package/dist/{pullManualEnrichmentIdentifiersToCsv-CoFubXre.mjs.map → pullManualEnrichmentIdentifiersToCsv-CDCL8Ju4.mjs.map} +1 -1
- package/dist/pullTranscendConfiguration-D_znkqJz.mjs +58 -0
- package/dist/{pullTranscendConfiguration-CofsMdIn.mjs.map → pullTranscendConfiguration-D_znkqJz.mjs.map} +1 -1
- package/dist/pullUnstructuredSubDataPointRecommendations-D0z-vPgq.mjs.map +1 -1
- package/dist/{pushCronIdentifiersFromCsv-C-nx-ud7.mjs → pushCronIdentifiersFromCsv-X5f82qIF.mjs} +2 -2
- package/dist/{pushCronIdentifiersFromCsv-C-nx-ud7.mjs.map → pushCronIdentifiersFromCsv-X5f82qIF.mjs.map} +1 -1
- package/dist/{pushManualEnrichmentIdentifiersFromCsv-Dus21ehz.mjs → pushManualEnrichmentIdentifiersFromCsv-dUpnhCWn.mjs} +2 -2
- package/dist/{pushManualEnrichmentIdentifiersFromCsv-Dus21ehz.mjs.map → pushManualEnrichmentIdentifiersFromCsv-dUpnhCWn.mjs.map} +1 -1
- package/dist/readCsv-C4TyEs-r.mjs.map +1 -1
- package/dist/readTranscendYaml-BbnEGgVD.mjs.map +1 -1
- package/dist/{removeUnverifiedRequestIdentifiers-BELumEC8.mjs → removeUnverifiedRequestIdentifiers-KDwOif_H.mjs} +2 -2
- package/dist/{removeUnverifiedRequestIdentifiers-BELumEC8.mjs.map → removeUnverifiedRequestIdentifiers-KDwOif_H.mjs.map} +1 -1
- package/dist/{retryRequestDataSilos-B8jS6TqU.mjs → retryRequestDataSilos-DDH-GkA6.mjs} +2 -2
- package/dist/{retryRequestDataSilos-B8jS6TqU.mjs.map → retryRequestDataSilos-DDH-GkA6.mjs.map} +1 -1
- package/dist/{skipPreflightJobs-DGRHqKgm.mjs → skipPreflightJobs-PFFvHaOC.mjs} +2 -2
- package/dist/{skipPreflightJobs-DGRHqKgm.mjs.map → skipPreflightJobs-PFFvHaOC.mjs.map} +1 -1
- package/dist/{skipRequestDataSilos-S_q1qW79.mjs → skipRequestDataSilos-6Pq98znw.mjs} +2 -2
- package/dist/{skipRequestDataSilos-S_q1qW79.mjs.map → skipRequestDataSilos-6Pq98znw.mjs.map} +1 -1
- package/dist/{streamPrivacyRequestsToCsv-BITHzCo3.mjs → streamPrivacyRequestsToCsv-Cf9KND_e.mjs} +2 -2
- package/dist/{streamPrivacyRequestsToCsv-BITHzCo3.mjs.map → streamPrivacyRequestsToCsv-Cf9KND_e.mjs.map} +1 -1
- package/dist/syncCodePackages-CAk_Hjyl.mjs.map +1 -1
- package/dist/{updateConsentManagerVersionToLatest-BhkjXRpM.mjs → updateConsentManagerVersionToLatest-DIDPQXSc.mjs} +2 -2
- package/dist/{updateConsentManagerVersionToLatest-BhkjXRpM.mjs.map → updateConsentManagerVersionToLatest-DIDPQXSc.mjs.map} +1 -1
- package/dist/{uploadConsents-CM0lSMlV.mjs → uploadConsents-B4PwgLpU.mjs} +2 -2
- package/dist/{uploadConsents-CM0lSMlV.mjs.map → uploadConsents-B4PwgLpU.mjs.map} +1 -1
- package/dist/{uploadCookiesFromCsv-C0IfwArv.mjs → uploadCookiesFromCsv-CQdJEOvo.mjs} +2 -2
- package/dist/{uploadCookiesFromCsv-C0IfwArv.mjs.map → uploadCookiesFromCsv-CQdJEOvo.mjs.map} +1 -1
- package/dist/{uploadDataFlowsFromCsv-BaQo3ps8.mjs → uploadDataFlowsFromCsv-COJoB65k.mjs} +2 -2
- package/dist/{uploadDataFlowsFromCsv-BaQo3ps8.mjs.map → uploadDataFlowsFromCsv-COJoB65k.mjs.map} +1 -1
- package/dist/uploadPrivacyRequestsFromCsv-CFdjDd4L.mjs +2 -0
- package/dist/{uploadPrivacyRequestsFromCsv-CfpGdgO6.mjs.map → uploadPrivacyRequestsFromCsv-CFdjDd4L.mjs.map} +1 -1
- package/dist/writeCsv-C4pjXGsD.mjs.map +1 -1
- package/package.json +9 -9
- package/dist/app-D4JCT1PC.mjs +0 -131
- package/dist/constants-BnvAwpw3.mjs +0 -2
- package/dist/constants-ClkQQhJs.mjs +0 -2
- package/dist/impl-BjIylEKQ.mjs +0 -4
- package/dist/pullTranscendConfiguration-CofsMdIn.mjs +0 -58
- package/dist/uploadPrivacyRequestsFromCsv-CfpGdgO6.mjs +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-DXHqqWJb.mjs","names":[],"sources":["../src/lib/preference-management/parsePreferenceAndPurposeValuesFromCsv.ts","../src/lib/preference-management/parsePreferenceIdentifiersFromCsv.ts","../src/lib/preference-management/parsePreferenceTimestampsFromCsv.ts","../src/lib/preference-management/parsePreferenceManagementCsv.ts","../src/lib/preference-management/uploadPreferenceManagementPreferencesInteractive.ts","../src/commands/consent/upload-preferences/impl.ts"],"sourcesContent":["import { PreferenceTopicType } from '@transcend-io/privacy-types';\nimport { FileMetadataState, type PreferenceTopic } from '@transcend-io/sdk';\nimport { mapSeries, splitCsvToList } from '@transcend-io/utils';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse out the purpose.enabled and preference values from a CSV file\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @param options - Options\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceAndPurposeValuesFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n {\n purposeSlugs,\n preferenceTopics,\n forceTriggerWorkflows,\n }: {\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const otherColumns = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...(currentState.timestampColum ? [currentState.timestampColum] : []),\n ]);\n if (otherColumns.length === 0) {\n if (forceTriggerWorkflows) {\n return currentState;\n }\n throw new Error('No other columns to process');\n }\n\n // The purpose and preferences to map to\n const purposeNames = [\n ...purposeSlugs,\n ...preferenceTopics.map((x) => `${x.purpose.trackingType}->${x.slug}`),\n ];\n\n // Ensure all columns are accounted for\n await mapSeries(otherColumns, async (col) => {\n // Determine the unique values to map in this column\n const uniqueValues = uniq(preferences.map((x) => x[col]));\n\n // Map the column to a purpose\n let purposeMapping = currentState.columnToPurposeName[col];\n if (purposeMapping) {\n logger.info(\n colors.magenta(`Column \"${col}\" is associated with purpose \"${purposeMapping.purpose}\"`),\n );\n } else {\n const { purposeName } = await inquirer.prompt<{\n /** purpose name */\n purposeName: string;\n }>([\n {\n name: 'purposeName',\n message: `Choose the purpose that column ${col} is associated with`,\n type: 'list',\n default: purposeNames.find((x) => x.startsWith(purposeSlugs[0])),\n choices: purposeNames,\n },\n ]);\n const [purposeSlug, preferenceSlug] = purposeName.split('->');\n purposeMapping = {\n purpose: purposeSlug,\n preference: preferenceSlug || null,\n valueMapping: {},\n };\n }\n\n // map each value to the purpose value\n await mapSeries(uniqueValues, async (value) => {\n if (purposeMapping.valueMapping[value] !== undefined) {\n logger.info(\n colors.magenta(\n `Value \"${value}\" is associated with purpose value \"${purposeMapping.valueMapping[value]}\"`,\n ),\n );\n return;\n }\n // if preference is null, this column is just for the purpose\n if (purposeMapping.preference === null) {\n const { purposeValue } = await inquirer.prompt<{\n /** purpose value */\n purposeValue: boolean;\n }>([\n {\n name: 'purposeValue',\n message: `Choose the purpose value for value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = purposeValue;\n }\n\n // if preference is not null, this column is for a specific preference\n if (purposeMapping.preference !== null) {\n const preferenceTopic = preferenceTopics.find((x) => x.slug === purposeMapping.preference);\n if (!preferenceTopic) {\n logger.error(colors.red(`Preference topic \"${purposeMapping.preference}\" not found`));\n return;\n }\n const preferenceOptions = preferenceTopic.preferenceOptionValues.map(({ slug }) => slug);\n\n if (preferenceTopic.type === PreferenceTopicType.Boolean) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n message:\n // eslint-disable-next-line max-len\n `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.Select) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === value),\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.MultiSelect) {\n const parsedValues = splitCsvToList(value);\n // need to do this serially\n await mapSeries(parsedValues, async (parsedValue) => {\n // if we already have a value, skip re-processing it again\n if (purposeMapping.valueMapping[parsedValue] !== undefined) {\n return;\n }\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${parsedValue}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === parsedValue),\n },\n ]);\n purposeMapping.valueMapping[parsedValue] = preferenceValue;\n });\n return;\n }\n\n throw new Error(`Unknown preference topic type: ${preferenceTopic.type}`);\n }\n });\n\n currentState.columnToPurposeName[col] = purposeMapping;\n });\n\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import { FileMetadataState } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, groupBy, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { inquirerConfirmBoolean } from '../helpers/index.js';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse identifiers from a CSV list of preferences\n *\n * Ensures that all rows have a valid identifier\n * and that all identifiers are unique.\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceIdentifiersFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<{\n /** The updated state */\n currentState: FileMetadataState;\n /** The updated preferences */\n preferences: Record<string, string>[];\n}> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const remainingColumnsForIdentifier = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the identifier column to work off of\n if (!currentState.identifierColumn) {\n const { identifierName } = await inquirer.prompt<{\n /** Identifier name */\n identifierName: string;\n }>([\n {\n name: 'identifierName',\n message:\n 'Choose the column that will be used as the identifier to upload consent preferences by',\n type: 'list',\n default:\n remainingColumnsForIdentifier.find((col) => col.toLowerCase().includes('email')) ||\n remainingColumnsForIdentifier[0],\n choices: remainingColumnsForIdentifier,\n },\n ]);\n currentState.identifierColumn = identifierName;\n }\n logger.info(colors.magenta(`Using identifier column \"${currentState.identifierColumn}\"`));\n\n // Validate that the identifier column is present for all rows and unique\n const identifierColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.identifierColumn!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (identifierColumnsMissing.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" is missing a value for the following rows: ${identifierColumnsMissing.join(', ')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to skip rows missing an identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to skip rows missing an identifier?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n\n // Filter out rows missing an identifier\n const previous = preferences.length;\n preferences = preferences.filter((pref) => pref[currentState.identifierColumn!]);\n logger.info(\n colors.yellow(`Skipped ${previous - preferences.length} rows missing an identifier`),\n );\n }\n logger.info(\n colors.magenta(\n `The identifier column \"${currentState.identifierColumn}\" is present for all rows`,\n ),\n );\n\n // Validate that all identifiers are unique\n const rowsByUserId = groupBy(preferences, currentState.identifierColumn);\n const duplicateIdentifiers = Object.entries(rowsByUserId).filter(([, rows]) => rows.length > 1);\n if (duplicateIdentifiers.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" has duplicate values for the following rows: ${duplicateIdentifiers\n .slice(0, 10)\n .map(([userId, rows]) => `${userId} (${rows.length})`)\n .join('\\n')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to take the most recent update\n // for each duplicate identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to automatically take the latest update?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n preferences = Object.entries(rowsByUserId)\n .map(([, rows]) => {\n const sorted = rows.sort(\n (a, b) =>\n new Date(b[currentState.timestampColum!]).getTime() -\n new Date(a[currentState.timestampColum!]).getTime(),\n );\n return sorted[0];\n })\n .filter((x) => x);\n }\n\n return { currentState, preferences };\n}\n/* eslint-enable no-param-reassign */\n","import { FileMetadataState } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\n\nexport const NONE_PREFERENCE_MAP = '[NONE]';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse timestamps from a CSV list of preferences\n *\n * When timestamp is requested, this script\n * ensures that all rows have a valid timestamp.\n *\n * Error is throw if timestamp is missing\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceTimestampsFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for timestamp\n const remainingColumnsForTimestamp = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the timestamp column to work off of\n if (!currentState.timestampColum) {\n const { timestampName } = await inquirer.prompt<{\n /** timestamp name */\n timestampName: string;\n }>([\n {\n name: 'timestampName',\n message: 'Choose the column that will be used as the timestamp of last preference update',\n type: 'list',\n default:\n remainingColumnsForTimestamp.find((col) => col.toLowerCase().includes('date')) ||\n remainingColumnsForTimestamp.find((col) => col.toLowerCase().includes('time')) ||\n remainingColumnsForTimestamp[0],\n choices: [...remainingColumnsForTimestamp, NONE_PREFERENCE_MAP],\n },\n ]);\n currentState.timestampColum = timestampName;\n }\n logger.info(colors.magenta(`Using timestamp column \"${currentState.timestampColum}\"`));\n\n // Validate that all rows have valid timestamp\n if (currentState.timestampColum !== NONE_PREFERENCE_MAP) {\n const timestampColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.timestampColum!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (timestampColumnsMissing.length > 0) {\n throw new Error(\n `The timestamp column \"${\n currentState.timestampColum\n }\" is missing a value for the following rows: ${timestampColumnsMissing.join('\\n')}`,\n );\n }\n logger.info(\n colors.magenta(\n `The timestamp column \"${currentState.timestampColum}\" is present for all row`,\n ),\n );\n }\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport {\n checkIfPendingPreferenceUpdatesAreNoOp,\n checkIfPendingPreferenceUpdatesCauseConflict,\n FileMetadataState,\n getPreferencesForIdentifiers,\n getPreferenceUpdatesFromRow,\n PreferenceState,\n type PreferenceTopic,\n} from '@transcend-io/sdk';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport type { Got } from 'got';\nimport * as t from 'io-ts';\nimport { keyBy } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { readCsv } from '../requests/index.js';\nimport { parsePreferenceAndPurposeValuesFromCsv } from './parsePreferenceAndPurposeValuesFromCsv.js';\nimport { parsePreferenceIdentifiersFromCsv } from './parsePreferenceIdentifiersFromCsv.js';\nimport { parsePreferenceTimestampsFromCsv } from './parsePreferenceTimestampsFromCsv.js';\n\n/**\n * Parse a file into the cache\n *\n *\n * @param options - Options\n * @param cache - The cache to store the parsed file in\n * @returns The cache with the parsed file\n */\nexport async function parsePreferenceManagementCsvWithCache(\n {\n file,\n sombra,\n purposeSlugs,\n preferenceTopics,\n partitionKey,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n }: {\n /** File to parse */\n file: string;\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Sombra got instance */\n sombra: Got;\n /** Partition key */\n partitionKey: string;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck: boolean;\n /** Whether to force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n cache: PersistedState<typeof PreferenceState>,\n): Promise<void> {\n // Start the timer\n const t0 = new Date().getTime();\n\n // Get the current metadata\n const fileMetadata = cache.getValue('fileMetadata');\n\n // Read in the file\n logger.info(colors.magenta(`Reading in file: \"${file}\"`));\n let preferences = readCsv(file, t.record(t.string, t.string));\n\n // start building the cache, can use previous cache as well\n let currentState: FileMetadataState = {\n columnToPurposeName: {},\n pendingSafeUpdates: {},\n pendingConflictUpdates: {},\n skippedUpdates: {},\n // Load in the last fetched time\n ...((fileMetadata[file] || {}) as Partial<FileMetadataState>),\n lastFetchedAt: new Date().toISOString(),\n };\n\n // Validate that all timestamps are present in the file\n currentState = await parsePreferenceTimestampsFromCsv(preferences, currentState);\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Validate that all identifiers are present and unique\n const result = await parsePreferenceIdentifiersFromCsv(preferences, currentState);\n currentState = result.currentState;\n preferences = result.preferences;\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Ensure all other columns are mapped to purpose and preference\n // slug values\n currentState = await parsePreferenceAndPurposeValuesFromCsv(preferences, currentState, {\n preferenceTopics,\n purposeSlugs,\n forceTriggerWorkflows,\n });\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Grab existing preference store records\n const identifiers = preferences.map((pref) => pref[currentState.identifierColumn!]);\n const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);\n if (!skipExistingRecordCheck) {\n progressBar.start(identifiers.length, 0);\n }\n const existingConsentRecords = skipExistingRecordCheck\n ? []\n : await getPreferencesForIdentifiers(sombra, {\n identifiers: identifiers.map((x) => ({ value: x })),\n partitionKey,\n logger,\n onProgress: (completed, total) => progressBar.update(completed, { total }),\n });\n progressBar.stop();\n const consentRecordByIdentifier = keyBy(existingConsentRecords, 'userId');\n\n // Clear out previous updates\n currentState.pendingConflictUpdates = {};\n currentState.pendingSafeUpdates = {};\n currentState.skippedUpdates = {};\n\n // Process each row\n preferences.forEach((pref) => {\n // Grab unique Id for the user\n const userId = pref[currentState.identifierColumn!];\n\n // determine updates for user\n const pendingUpdates = getPreferenceUpdatesFromRow({\n row: pref,\n columnToPurposeName: currentState.columnToPurposeName,\n preferenceTopics,\n purposeSlugs,\n });\n\n // Grab current state of the update\n const currentConsentRecord = consentRecordByIdentifier[userId];\n if (forceTriggerWorkflows && !currentConsentRecord) {\n throw new Error(\n `No existing consent record found for user with id: ${userId}.\n When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`,\n );\n }\n // Check if the update can be skipped\n // this is the case if a record exists, and the purpose\n // and preference values are all in sync\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesAreNoOp({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n }) &&\n !forceTriggerWorkflows\n ) {\n currentState.skippedUpdates[userId] = pref;\n return;\n }\n\n // Determine if there are any conflicts\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesCauseConflict({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n })\n ) {\n currentState.pendingConflictUpdates[userId] = {\n row: pref,\n record: currentConsentRecord,\n };\n return;\n }\n\n // Add to pending updates\n currentState.pendingSafeUpdates[userId] = pref;\n });\n\n // Read in the file\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n const t1 = new Date().getTime();\n logger.info(colors.green(`Successfully pre-processed file: \"${file}\" in ${(t1 - t0) / 1000}s`));\n}\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport { PreferenceUpdateItem } from '@transcend-io/privacy-types';\nimport {\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllPurposes,\n fetchAllPreferenceTopics,\n getPreferenceUpdatesFromRow,\n PreferenceState,\n} from '@transcend-io/sdk';\nimport { apply } from '@transcend-io/type-utils';\nimport { map } from '@transcend-io/utils';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport { chunk } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { parseAttributesFromString } from '../requests/index.js';\nimport { parsePreferenceManagementCsvWithCache } from './parsePreferenceManagementCsv.js';\nimport { NONE_PREFERENCE_MAP } from './parsePreferenceTimestampsFromCsv.js';\n\n/**\n * Upload a set of consent preferences\n *\n * @param options - Options\n */\nexport async function uploadPreferenceManagementPreferencesInteractive({\n auth,\n sombraAuth,\n receiptFilepath,\n file,\n partition,\n isSilent = true,\n dryRun = false,\n skipWorkflowTriggers = false,\n skipConflictUpdates = false,\n skipExistingRecordCheck = false,\n attributes = [],\n transcendUrl,\n forceTriggerWorkflows = false,\n}: {\n /** The Transcend API key */\n auth: string;\n /** Sombra API key authentication */\n sombraAuth?: string;\n /** Partition key */\n partition: string;\n /** File where to store receipt and continue from where left off */\n receiptFilepath: string;\n /** The file to process */\n file: string;\n /** API URL for Transcend backend */\n transcendUrl: string;\n /** Whether to do a dry run */\n dryRun?: boolean;\n /** Whether to upload as isSilent */\n isSilent?: boolean;\n /** Attributes string pre-parse. In format Key:Value */\n attributes?: string[];\n /** Skip workflow triggers */\n skipWorkflowTriggers?: boolean;\n /**\n * When true, only update preferences that do not conflict with existing\n * preferences. When false, update all preferences in CSV based on timestamp.\n */\n skipConflictUpdates?: boolean;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck?: boolean;\n /** Whether to force trigger workflows */\n forceTriggerWorkflows?: boolean;\n}): Promise<void> {\n // Parse out the extra attributes to apply to all requests uploaded\n const parsedAttributes = parseAttributesFromString(attributes);\n\n // Create a new state file to store the requests from this run\n const preferenceState = new PersistedState(receiptFilepath, PreferenceState, {\n fileMetadata: {},\n failingUpdates: {},\n pendingUpdates: {},\n });\n const failingRequests = preferenceState.getValue('failingUpdates');\n const pendingRequests = preferenceState.getValue('pendingUpdates');\n let fileMetadata = preferenceState.getValue('fileMetadata');\n\n logger.info(\n colors.magenta(\n 'Restored cache, there are: \\n' +\n `${Object.values(failingRequests).length} failing requests to be retried\\n` +\n `${Object.values(pendingRequests).length} pending requests to be processed\\n` +\n `The following files are stored in cache and will be used:\\n${Object.keys(fileMetadata)\n .map((x) => x)\n .join('\\n')}\\n` +\n `The following file will be processed: ${file}\\n`,\n ),\n );\n\n // Create GraphQL client to connect to Transcend backend\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const [sombra, purposes, preferenceTopics] = await Promise.all([\n // Create sombra instance to communicate with\n createSombraGotInstance(transcendUrl, auth, {\n logger,\n sombraApiKey: sombraAuth,\n sombraUrl: process.env.SOMBRA_URL,\n }),\n // get all purposes and topics\n fetchAllPurposes(client, { logger }),\n fetchAllPreferenceTopics(client, { logger }),\n ]);\n\n // Process the file\n await parsePreferenceManagementCsvWithCache(\n {\n file,\n purposeSlugs: purposes.map((x) => x.trackingType),\n preferenceTopics,\n sombra,\n partitionKey: partition,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n },\n preferenceState,\n );\n\n // Construct the pending updates\n const pendingUpdates: Record<string, PreferenceUpdateItem> = {};\n fileMetadata = preferenceState.getValue('fileMetadata');\n const metadata = fileMetadata[file];\n\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.pendingSafeUpdates).length} safe updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.pendingConflictUpdates).length} conflict updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.skippedUpdates).length} skipped updates in ${file}`,\n ),\n );\n\n // Update either safe updates only or safe + conflict\n Object.entries({\n ...metadata.pendingSafeUpdates,\n ...(skipConflictUpdates ? {} : apply(metadata.pendingConflictUpdates, ({ row }) => row)),\n }).forEach(([userId, update]) => {\n // Determine timestamp\n const timestamp =\n metadata.timestampColum === NONE_PREFERENCE_MAP\n ? new Date()\n : new Date(update[metadata.timestampColum!]);\n\n // Determine updates\n const updates = getPreferenceUpdatesFromRow({\n row: update,\n columnToPurposeName: metadata.columnToPurposeName,\n preferenceTopics,\n purposeSlugs: purposes.map((x) => x.trackingType),\n });\n pendingUpdates[userId] = {\n userId,\n partition,\n timestamp: timestamp.toISOString(),\n purposes: Object.entries(updates).map(([purpose, value]) => ({\n ...value,\n purpose,\n workflowSettings: {\n attributes: parsedAttributes,\n isSilent,\n skipWorkflowTrigger: skipWorkflowTriggers,\n ...(forceTriggerWorkflows ? { forceTriggerWorkflow: forceTriggerWorkflows } : {}),\n },\n })),\n };\n });\n await preferenceState.setValue(pendingUpdates, 'pendingUpdates');\n await preferenceState.setValue({}, 'failingUpdates');\n\n // Exist early if dry run\n if (dryRun) {\n logger.info(\n colors.green(\n `Dry run complete, exiting. ${\n Object.values(pendingUpdates).length\n } pending updates. Check file: ${receiptFilepath}`,\n ),\n );\n return;\n }\n\n logger.info(\n colors.magenta(\n `Uploading ${Object.values(pendingUpdates).length} preferences to partition: ${partition}`,\n ),\n );\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);\n\n // Build a GraphQL client\n let total = 0;\n const updatesToRun = Object.entries(pendingUpdates);\n const chunkedUpdates = chunk(updatesToRun, skipWorkflowTriggers ? 100 : 10);\n progressBar.start(updatesToRun.length, 0);\n await map(\n chunkedUpdates,\n async (currentChunk) => {\n // Make the request\n try {\n await sombra\n .put('v1/preferences', {\n json: {\n records: currentChunk.map(([, update]) => update),\n skipWorkflowTriggers,\n },\n })\n .json();\n } catch (err) {\n try {\n const parsed = JSON.parse(err?.response?.body || '{}');\n if (parsed.error) {\n logger.error(colors.red(`Error: ${parsed.error}`));\n }\n } catch {\n // continue\n }\n logger.error(\n colors.red(\n `Failed to upload ${currentChunk.length} user preferences to partition ${partition}: ${\n err?.response?.body || err?.message\n }`,\n ),\n );\n const failingUpdates = preferenceState.getValue('failingUpdates');\n currentChunk.forEach(([userId, update]) => {\n failingUpdates[userId] = {\n uploadedAt: new Date().toISOString(),\n update,\n error: err?.response?.body || err?.message || 'Unknown error',\n };\n });\n await preferenceState.setValue(failingUpdates, 'failingUpdates');\n }\n\n total += currentChunk.length;\n progressBar.update(total);\n },\n {\n concurrency: 40,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n logger.info(\n colors.green(\n `Successfully uploaded ${\n updatesToRun.length\n } user preferences to partition ${partition} in \"${totalTime / 1000}\" seconds!`,\n ),\n );\n}\n","import { readdirSync } from 'node:fs';\nimport { basename, join } from 'node:path';\n\nimport { map, splitCsvToList } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { uploadPreferenceManagementPreferencesInteractive } from '../../../lib/preference-management/index.js';\nimport { logger } from '../../../logger.js';\n\nexport interface UploadPreferencesCommandFlags {\n auth: string;\n partition: string;\n sombraAuth?: string;\n transcendUrl: string;\n file?: string;\n directory?: string;\n dryRun: boolean;\n skipExistingRecordCheck: boolean;\n receiptFileDir: string;\n skipWorkflowTriggers: boolean;\n forceTriggerWorkflows: boolean;\n skipConflictUpdates: boolean;\n isSilent: boolean;\n attributes: string;\n receiptFilepath: string;\n concurrency: number;\n}\n\nexport async function uploadPreferences(\n this: LocalContext,\n {\n auth,\n partition,\n sombraAuth,\n transcendUrl,\n file = '',\n directory,\n dryRun,\n skipExistingRecordCheck,\n receiptFileDir,\n skipWorkflowTriggers,\n forceTriggerWorkflows,\n skipConflictUpdates,\n isSilent,\n attributes,\n concurrency,\n }: UploadPreferencesCommandFlags,\n): Promise<void> {\n if (!!directory && !!file) {\n logger.error(\n colors.red('Cannot provide both a directory and a file. Please provide only one.'),\n );\n this.process.exit(1);\n }\n\n if (!file && !directory) {\n logger.error(\n colors.red(\n 'A file or directory must be provided. Please provide one using --file=./preferences.csv or --directory=./preferences',\n ),\n );\n this.process.exit(1);\n }\n\n doneInputValidation(this.process.exit);\n\n const files: string[] = [];\n\n if (directory) {\n try {\n const filesInDirectory = readdirSync(directory);\n const csvFiles = filesInDirectory.filter((file) => file.endsWith('.csv'));\n\n if (csvFiles.length === 0) {\n logger.error(colors.red(`No CSV files found in directory: ${directory}`));\n this.process.exit(1);\n }\n\n // Add full paths for each CSV file\n files.push(...csvFiles.map((file) => join(directory, file)));\n } catch (err) {\n logger.error(colors.red(`Failed to read directory: ${directory}`));\n logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n } else {\n try {\n // Verify file exists and is a CSV\n if (!file.endsWith('.csv')) {\n logger.error(colors.red('File must be a CSV file'));\n this.process.exit(1);\n }\n files.push(file);\n } catch (err) {\n logger.error(colors.red(`Failed to access file: ${file}`));\n logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n }\n\n logger.info(\n colors.green(\n `Processing ${files.length} consent preferences files for partition: ${partition}`,\n ),\n );\n logger.debug(`Files to process: ${files.join(', ')}`);\n\n if (skipExistingRecordCheck) {\n logger.info(colors.bgYellow(`Skipping existing record check: ${skipExistingRecordCheck}`));\n }\n\n await map(\n files,\n async (filePath) => {\n const fileName = basename(filePath).replace('.csv', '');\n await uploadPreferenceManagementPreferencesInteractive({\n receiptFilepath: join(receiptFileDir, `${fileName}-receipts.json`),\n auth,\n sombraAuth,\n file: filePath,\n partition,\n transcendUrl,\n skipConflictUpdates,\n skipWorkflowTriggers,\n skipExistingRecordCheck,\n isSilent,\n dryRun,\n attributes: splitCsvToList(attributes),\n forceTriggerWorkflows,\n });\n },\n { concurrency },\n );\n}\n"],"mappings":"wkCAmBA,eAAsB,EACpB,EACA,EACA,CACE,eACA,mBACA,yBAS0B,CAK5B,IAAM,EAAe,EAHD,EAAK,EAAY,IAAK,GAAM,OAAO,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC,CAG1B,CAC3C,GAAI,EAAa,iBAAmB,CAAC,EAAa,iBAAiB,CAAG,EAAE,CACxE,GAAI,EAAa,eAAiB,CAAC,EAAa,eAAe,CAAG,EAAE,CACrE,CAAC,CACF,GAAI,EAAa,SAAW,EAAG,CAC7B,GAAI,EACF,OAAO,EAET,MAAU,MAAM,8BAA8B,CAIhD,IAAM,EAAe,CACnB,GAAG,EACH,GAAG,EAAiB,IAAK,GAAM,GAAG,EAAE,QAAQ,aAAa,IAAI,EAAE,OAAO,CACvE,CA0ID,OAvIA,MAAM,EAAU,EAAc,KAAO,IAAQ,CAE3C,IAAM,EAAe,EAAK,E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AM,EAAO,IAAK,EAAc,QAAQ,CAAC,CAChD,KAAK,QAAQ,KAAK,EAAE,CAIxB,EAAO,KACL,EAAO,MACL,cAAc,EAAM,OAAO,4CAA4C,IACxE,CACF,CACD,EAAO,MAAM,qBAAqB,EAAM,KAAK,KAAK,GAAG,CAEjD,GACF,EAAO,KAAK,EAAO,SAAS,mCAAmC,IAA0B,CAAC,CAG5F,MAAM,EACJ,EACA,KAAO,IAAa,CAElB,MAAM,EAAiD,CACrD,gBAAiB,EAAK,EAAgB,GAFvB,EAAS,EAAS,CAAC,QAAQ,OAAQ,GAAG,CAEH,gBAAgB,CAClE,OACA,aACA,KAAM,EACN,YACA,eACA,sBACA,uBACA,0BACA,WACA,SACA,WAAY,EAAe,EAAW,CACtC,wBACD,CAAC,EAEJ,CAAE,cAAa,CAChB"}
|
|
1
|
+
{"version":3,"file":"impl-DiHeNVFr.mjs","names":[],"sources":["../src/lib/preference-management/parsePreferenceAndPurposeValuesFromCsv.ts","../src/lib/preference-management/parsePreferenceIdentifiersFromCsv.ts","../src/lib/preference-management/parsePreferenceTimestampsFromCsv.ts","../src/lib/preference-management/parsePreferenceManagementCsv.ts","../src/lib/preference-management/uploadPreferenceManagementPreferencesInteractive.ts","../src/commands/consent/upload-preferences/impl.ts"],"sourcesContent":["import { PreferenceTopicType } from '@transcend-io/privacy-types';\nimport { FileMetadataState, type PreferenceTopic } from '@transcend-io/sdk';\nimport { mapSeries, splitCsvToList } from '@transcend-io/utils';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse out the purpose.enabled and preference values from a CSV file\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @param options - Options\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceAndPurposeValuesFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n {\n purposeSlugs,\n preferenceTopics,\n forceTriggerWorkflows,\n }: {\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const otherColumns = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...(currentState.timestampColum ? [currentState.timestampColum] : []),\n ]);\n if (otherColumns.length === 0) {\n if (forceTriggerWorkflows) {\n return currentState;\n }\n throw new Error('No other columns to process');\n }\n\n // The purpose and preferences to map to\n const purposeNames = [\n ...purposeSlugs,\n ...preferenceTopics.map((x) => `${x.purpose.trackingType}->${x.slug}`),\n ];\n\n // Ensure all columns are accounted for\n await mapSeries(otherColumns, async (col) => {\n // Determine the unique values to map in this column\n const uniqueValues = uniq(preferences.map((x) => x[col]));\n\n // Map the column to a purpose\n let purposeMapping = currentState.columnToPurposeName[col];\n if (purposeMapping) {\n logger.info(\n colors.magenta(`Column \"${col}\" is associated with purpose \"${purposeMapping.purpose}\"`),\n );\n } else {\n const { purposeName } = await inquirer.prompt<{\n /** purpose name */\n purposeName: string;\n }>([\n {\n name: 'purposeName',\n message: `Choose the purpose that column ${col} is associated with`,\n type: 'list',\n default: purposeNames.find((x) => x.startsWith(purposeSlugs[0])),\n choices: purposeNames,\n },\n ]);\n const [purposeSlug, preferenceSlug] = purposeName.split('->');\n purposeMapping = {\n purpose: purposeSlug,\n preference: preferenceSlug || null,\n valueMapping: {},\n };\n }\n\n // map each value to the purpose value\n await mapSeries(uniqueValues, async (value) => {\n if (purposeMapping.valueMapping[value] !== undefined) {\n logger.info(\n colors.magenta(\n `Value \"${value}\" is associated with purpose value \"${purposeMapping.valueMapping[value]}\"`,\n ),\n );\n return;\n }\n // if preference is null, this column is just for the purpose\n if (purposeMapping.preference === null) {\n const { purposeValue } = await inquirer.prompt<{\n /** purpose value */\n purposeValue: boolean;\n }>([\n {\n name: 'purposeValue',\n message: `Choose the purpose value for value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = purposeValue;\n }\n\n // if preference is not null, this column is for a specific preference\n if (purposeMapping.preference !== null) {\n const preferenceTopic = preferenceTopics.find((x) => x.slug === purposeMapping.preference);\n if (!preferenceTopic) {\n logger.error(colors.red(`Preference topic \"${purposeMapping.preference}\" not found`));\n return;\n }\n const preferenceOptions = preferenceTopic.preferenceOptionValues.map(({ slug }) => slug);\n\n if (preferenceTopic.type === PreferenceTopicType.Boolean) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n message:\n // eslint-disable-next-line max-len\n `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.Select) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === value),\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.MultiSelect) {\n const parsedValues = splitCsvToList(value);\n // need to do this serially\n await mapSeries(parsedValues, async (parsedValue) => {\n // if we already have a value, skip re-processing it again\n if (purposeMapping.valueMapping[parsedValue] !== undefined) {\n return;\n }\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${parsedValue}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === parsedValue),\n },\n ]);\n purposeMapping.valueMapping[parsedValue] = preferenceValue;\n });\n return;\n }\n\n throw new Error(`Unknown preference topic type: ${preferenceTopic.type}`);\n }\n });\n\n currentState.columnToPurposeName[col] = purposeMapping;\n });\n\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import { FileMetadataState } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, groupBy, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { inquirerConfirmBoolean } from '../helpers/index.js';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse identifiers from a CSV list of preferences\n *\n * Ensures that all rows have a valid identifier\n * and that all identifiers are unique.\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceIdentifiersFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<{\n /** The updated state */\n currentState: FileMetadataState;\n /** The updated preferences */\n preferences: Record<string, string>[];\n}> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const remainingColumnsForIdentifier = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the identifier column to work off of\n if (!currentState.identifierColumn) {\n const { identifierName } = await inquirer.prompt<{\n /** Identifier name */\n identifierName: string;\n }>([\n {\n name: 'identifierName',\n message:\n 'Choose the column that will be used as the identifier to upload consent preferences by',\n type: 'list',\n default:\n remainingColumnsForIdentifier.find((col) => col.toLowerCase().includes('email')) ||\n remainingColumnsForIdentifier[0],\n choices: remainingColumnsForIdentifier,\n },\n ]);\n currentState.identifierColumn = identifierName;\n }\n logger.info(colors.magenta(`Using identifier column \"${currentState.identifierColumn}\"`));\n\n // Validate that the identifier column is present for all rows and unique\n const identifierColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.identifierColumn!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (identifierColumnsMissing.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" is missing a value for the following rows: ${identifierColumnsMissing.join(', ')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to skip rows missing an identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to skip rows missing an identifier?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n\n // Filter out rows missing an identifier\n const previous = preferences.length;\n preferences = preferences.filter((pref) => pref[currentState.identifierColumn!]);\n logger.info(\n colors.yellow(`Skipped ${previous - preferences.length} rows missing an identifier`),\n );\n }\n logger.info(\n colors.magenta(\n `The identifier column \"${currentState.identifierColumn}\" is present for all rows`,\n ),\n );\n\n // Validate that all identifiers are unique\n const rowsByUserId = groupBy(preferences, currentState.identifierColumn);\n const duplicateIdentifiers = Object.entries(rowsByUserId).filter(([, rows]) => rows.length > 1);\n if (duplicateIdentifiers.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" has duplicate values for the following rows: ${duplicateIdentifiers\n .slice(0, 10)\n .map(([userId, rows]) => `${userId} (${rows.length})`)\n .join('\\n')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to take the most recent update\n // for each duplicate identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to automatically take the latest update?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n preferences = Object.entries(rowsByUserId)\n .map(([, rows]) => {\n const sorted = rows.sort(\n (a, b) =>\n new Date(b[currentState.timestampColum!]).getTime() -\n new Date(a[currentState.timestampColum!]).getTime(),\n );\n return sorted[0];\n })\n .filter((x) => x);\n }\n\n return { currentState, preferences };\n}\n/* eslint-enable no-param-reassign */\n","import { FileMetadataState } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\n\nexport const NONE_PREFERENCE_MAP = '[NONE]';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse timestamps from a CSV list of preferences\n *\n * When timestamp is requested, this script\n * ensures that all rows have a valid timestamp.\n *\n * Error is throw if timestamp is missing\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceTimestampsFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for timestamp\n const remainingColumnsForTimestamp = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the timestamp column to work off of\n if (!currentState.timestampColum) {\n const { timestampName } = await inquirer.prompt<{\n /** timestamp name */\n timestampName: string;\n }>([\n {\n name: 'timestampName',\n message: 'Choose the column that will be used as the timestamp of last preference update',\n type: 'list',\n default:\n remainingColumnsForTimestamp.find((col) => col.toLowerCase().includes('date')) ||\n remainingColumnsForTimestamp.find((col) => col.toLowerCase().includes('time')) ||\n remainingColumnsForTimestamp[0],\n choices: [...remainingColumnsForTimestamp, NONE_PREFERENCE_MAP],\n },\n ]);\n currentState.timestampColum = timestampName;\n }\n logger.info(colors.magenta(`Using timestamp column \"${currentState.timestampColum}\"`));\n\n // Validate that all rows have valid timestamp\n if (currentState.timestampColum !== NONE_PREFERENCE_MAP) {\n const timestampColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.timestampColum!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (timestampColumnsMissing.length > 0) {\n throw new Error(\n `The timestamp column \"${\n currentState.timestampColum\n }\" is missing a value for the following rows: ${timestampColumnsMissing.join('\\n')}`,\n );\n }\n logger.info(\n colors.magenta(\n `The timestamp column \"${currentState.timestampColum}\" is present for all row`,\n ),\n );\n }\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport {\n checkIfPendingPreferenceUpdatesAreNoOp,\n checkIfPendingPreferenceUpdatesCauseConflict,\n FileMetadataState,\n getPreferencesForIdentifiers,\n getPreferenceUpdatesFromRow,\n PreferenceState,\n type PreferenceTopic,\n} from '@transcend-io/sdk';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport type { Got } from 'got';\nimport * as t from 'io-ts';\nimport { keyBy } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { readCsv } from '../requests/index.js';\nimport { parsePreferenceAndPurposeValuesFromCsv } from './parsePreferenceAndPurposeValuesFromCsv.js';\nimport { parsePreferenceIdentifiersFromCsv } from './parsePreferenceIdentifiersFromCsv.js';\nimport { parsePreferenceTimestampsFromCsv } from './parsePreferenceTimestampsFromCsv.js';\n\n/**\n * Parse a file into the cache\n *\n *\n * @param options - Options\n * @param cache - The cache to store the parsed file in\n * @returns The cache with the parsed file\n */\nexport async function parsePreferenceManagementCsvWithCache(\n {\n file,\n sombra,\n purposeSlugs,\n preferenceTopics,\n partitionKey,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n }: {\n /** File to parse */\n file: string;\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Sombra got instance */\n sombra: Got;\n /** Partition key */\n partitionKey: string;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck: boolean;\n /** Whether to force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n cache: PersistedState<typeof PreferenceState>,\n): Promise<void> {\n // Start the timer\n const t0 = new Date().getTime();\n\n // Get the current metadata\n const fileMetadata = cache.getValue('fileMetadata');\n\n // Read in the file\n logger.info(colors.magenta(`Reading in file: \"${file}\"`));\n let preferences = readCsv(file, t.record(t.string, t.string));\n\n // start building the cache, can use previous cache as well\n let currentState: FileMetadataState = {\n columnToPurposeName: {},\n pendingSafeUpdates: {},\n pendingConflictUpdates: {},\n skippedUpdates: {},\n // Load in the last fetched time\n ...((fileMetadata[file] || {}) as Partial<FileMetadataState>),\n lastFetchedAt: new Date().toISOString(),\n };\n\n // Validate that all timestamps are present in the file\n currentState = await parsePreferenceTimestampsFromCsv(preferences, currentState);\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Validate that all identifiers are present and unique\n const result = await parsePreferenceIdentifiersFromCsv(preferences, currentState);\n currentState = result.currentState;\n preferences = result.preferences;\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Ensure all other columns are mapped to purpose and preference\n // slug values\n currentState = await parsePreferenceAndPurposeValuesFromCsv(preferences, currentState, {\n preferenceTopics,\n purposeSlugs,\n forceTriggerWorkflows,\n });\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Grab existing preference store records\n const identifiers = preferences.map((pref) => pref[currentState.identifierColumn!]);\n const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);\n if (!skipExistingRecordCheck) {\n progressBar.start(identifiers.length, 0);\n }\n const existingConsentRecords = skipExistingRecordCheck\n ? []\n : await getPreferencesForIdentifiers(sombra, {\n identifiers: identifiers.map((x) => ({ value: x })),\n partitionKey,\n logger,\n onProgress: (completed, total) => progressBar.update(completed, { total }),\n });\n progressBar.stop();\n const consentRecordByIdentifier = keyBy(existingConsentRecords, 'userId');\n\n // Clear out previous updates\n currentState.pendingConflictUpdates = {};\n currentState.pendingSafeUpdates = {};\n currentState.skippedUpdates = {};\n\n // Process each row\n preferences.forEach((pref) => {\n // Grab unique Id for the user\n const userId = pref[currentState.identifierColumn!];\n\n // determine updates for user\n const pendingUpdates = getPreferenceUpdatesFromRow({\n row: pref,\n columnToPurposeName: currentState.columnToPurposeName,\n preferenceTopics,\n purposeSlugs,\n });\n\n // Grab current state of the update\n const currentConsentRecord = consentRecordByIdentifier[userId];\n if (forceTriggerWorkflows && !currentConsentRecord) {\n throw new Error(\n `No existing consent record found for user with id: ${userId}.\n When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`,\n );\n }\n // Check if the update can be skipped\n // this is the case if a record exists, and the purpose\n // and preference values are all in sync\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesAreNoOp({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n }) &&\n !forceTriggerWorkflows\n ) {\n currentState.skippedUpdates[userId] = pref;\n return;\n }\n\n // Determine if there are any conflicts\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesCauseConflict({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n })\n ) {\n currentState.pendingConflictUpdates[userId] = {\n row: pref,\n record: currentConsentRecord,\n };\n return;\n }\n\n // Add to pending updates\n currentState.pendingSafeUpdates[userId] = pref;\n });\n\n // Read in the file\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n const t1 = new Date().getTime();\n logger.info(colors.green(`Successfully pre-processed file: \"${file}\" in ${(t1 - t0) / 1000}s`));\n}\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport { PreferenceUpdateItem } from '@transcend-io/privacy-types';\nimport {\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllPurposes,\n fetchAllPreferenceTopics,\n getPreferenceUpdatesFromRow,\n PreferenceState,\n} from '@transcend-io/sdk';\nimport { apply } from '@transcend-io/type-utils';\nimport { map } from '@transcend-io/utils';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport { chunk } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { parseAttributesFromString } from '../requests/index.js';\nimport { parsePreferenceManagementCsvWithCache } from './parsePreferenceManagementCsv.js';\nimport { NONE_PREFERENCE_MAP } from './parsePreferenceTimestampsFromCsv.js';\n\n/**\n * Upload a set of consent preferences\n *\n * @param options - Options\n */\nexport async function uploadPreferenceManagementPreferencesInteractive({\n auth,\n sombraAuth,\n receiptFilepath,\n file,\n partition,\n isSilent = true,\n dryRun = false,\n skipWorkflowTriggers = false,\n skipConflictUpdates = false,\n skipExistingRecordCheck = false,\n attributes = [],\n transcendUrl,\n forceTriggerWorkflows = false,\n}: {\n /** The Transcend API key */\n auth: string;\n /** Sombra API key authentication */\n sombraAuth?: string;\n /** Partition key */\n partition: string;\n /** File where to store receipt and continue from where left off */\n receiptFilepath: string;\n /** The file to process */\n file: string;\n /** API URL for Transcend backend */\n transcendUrl: string;\n /** Whether to do a dry run */\n dryRun?: boolean;\n /** Whether to upload as isSilent */\n isSilent?: boolean;\n /** Attributes string pre-parse. In format Key:Value */\n attributes?: string[];\n /** Skip workflow triggers */\n skipWorkflowTriggers?: boolean;\n /**\n * When true, only update preferences that do not conflict with existing\n * preferences. When false, update all preferences in CSV based on timestamp.\n */\n skipConflictUpdates?: boolean;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck?: boolean;\n /** Whether to force trigger workflows */\n forceTriggerWorkflows?: boolean;\n}): Promise<void> {\n // Parse out the extra attributes to apply to all requests uploaded\n const parsedAttributes = parseAttributesFromString(attributes);\n\n // Create a new state file to store the requests from this run\n const preferenceState = new PersistedState(receiptFilepath, PreferenceState, {\n fileMetadata: {},\n failingUpdates: {},\n pendingUpdates: {},\n });\n const failingRequests = preferenceState.getValue('failingUpdates');\n const pendingRequests = preferenceState.getValue('pendingUpdates');\n let fileMetadata = preferenceState.getValue('fileMetadata');\n\n logger.info(\n colors.magenta(\n 'Restored cache, there are: \\n' +\n `${Object.values(failingRequests).length} failing requests to be retried\\n` +\n `${Object.values(pendingRequests).length} pending requests to be processed\\n` +\n `The following files are stored in cache and will be used:\\n${Object.keys(fileMetadata)\n .map((x) => x)\n .join('\\n')}\\n` +\n `The following file will be processed: ${file}\\n`,\n ),\n );\n\n // Create GraphQL client to connect to Transcend backend\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const [sombra, purposes, preferenceTopics] = await Promise.all([\n // Create sombra instance to communicate with\n createSombraGotInstance(transcendUrl, auth, {\n logger,\n sombraApiKey: sombraAuth,\n sombraUrl: process.env.SOMBRA_URL,\n }),\n // get all purposes and topics\n fetchAllPurposes(client, { logger }),\n fetchAllPreferenceTopics(client, { logger }),\n ]);\n\n // Process the file\n await parsePreferenceManagementCsvWithCache(\n {\n file,\n purposeSlugs: purposes.map((x) => x.trackingType),\n preferenceTopics,\n sombra,\n partitionKey: partition,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n },\n preferenceState,\n );\n\n // Construct the pending updates\n const pendingUpdates: Record<string, PreferenceUpdateItem> = {};\n fileMetadata = preferenceState.getValue('fileMetadata');\n const metadata = fileMetadata[file];\n\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.pendingSafeUpdates).length} safe updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.pendingConflictUpdates).length} conflict updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.skippedUpdates).length} skipped updates in ${file}`,\n ),\n );\n\n // Update either safe updates only or safe + conflict\n Object.entries({\n ...metadata.pendingSafeUpdates,\n ...(skipConflictUpdates ? {} : apply(metadata.pendingConflictUpdates, ({ row }) => row)),\n }).forEach(([userId, update]) => {\n // Determine timestamp\n const timestamp =\n metadata.timestampColum === NONE_PREFERENCE_MAP\n ? new Date()\n : new Date(update[metadata.timestampColum!]);\n\n // Determine updates\n const updates = getPreferenceUpdatesFromRow({\n row: update,\n columnToPurposeName: metadata.columnToPurposeName,\n preferenceTopics,\n purposeSlugs: purposes.map((x) => x.trackingType),\n });\n pendingUpdates[userId] = {\n userId,\n partition,\n timestamp: timestamp.toISOString(),\n purposes: Object.entries(updates).map(([purpose, value]) => ({\n ...value,\n purpose,\n workflowSettings: {\n attributes: parsedAttributes,\n isSilent,\n skipWorkflowTrigger: skipWorkflowTriggers,\n ...(forceTriggerWorkflows ? { forceTriggerWorkflow: forceTriggerWorkflows } : {}),\n },\n })),\n };\n });\n await preferenceState.setValue(pendingUpdates, 'pendingUpdates');\n await preferenceState.setValue({}, 'failingUpdates');\n\n // Exist early if dry run\n if (dryRun) {\n logger.info(\n colors.green(\n `Dry run complete, exiting. ${\n Object.values(pendingUpdates).length\n } pending updates. Check file: ${receiptFilepath}`,\n ),\n );\n return;\n }\n\n logger.info(\n colors.magenta(\n `Uploading ${Object.values(pendingUpdates).length} preferences to partition: ${partition}`,\n ),\n );\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);\n\n // Build a GraphQL client\n let total = 0;\n const updatesToRun = Object.entries(pendingUpdates);\n const chunkedUpdates = chunk(updatesToRun, skipWorkflowTriggers ? 100 : 10);\n progressBar.start(updatesToRun.length, 0);\n await map(\n chunkedUpdates,\n async (currentChunk) => {\n // Make the request\n try {\n await sombra\n .put('v1/preferences', {\n json: {\n records: currentChunk.map(([, update]) => update),\n skipWorkflowTriggers,\n },\n })\n .json();\n } catch (err) {\n try {\n const parsed = JSON.parse(err?.response?.body || '{}');\n if (parsed.error) {\n logger.error(colors.red(`Error: ${parsed.error}`));\n }\n } catch {\n // continue\n }\n logger.error(\n colors.red(\n `Failed to upload ${currentChunk.length} user preferences to partition ${partition}: ${\n err?.response?.body || err?.message\n }`,\n ),\n );\n const failingUpdates = preferenceState.getValue('failingUpdates');\n currentChunk.forEach(([userId, update]) => {\n failingUpdates[userId] = {\n uploadedAt: new Date().toISOString(),\n update,\n error: err?.response?.body || err?.message || 'Unknown error',\n };\n });\n await preferenceState.setValue(failingUpdates, 'failingUpdates');\n }\n\n total += currentChunk.length;\n progressBar.update(total);\n },\n {\n concurrency: 40,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n logger.info(\n colors.green(\n `Successfully uploaded ${\n updatesToRun.length\n } user preferences to partition ${partition} in \"${totalTime / 1000}\" seconds!`,\n ),\n );\n}\n","import { readdirSync } from 'node:fs';\nimport { basename, join } from 'node:path';\n\nimport { map, splitCsvToList } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { uploadPreferenceManagementPreferencesInteractive } from '../../../lib/preference-management/index.js';\nimport { logger } from '../../../logger.js';\n\nexport interface UploadPreferencesCommandFlags {\n auth: string;\n partition: string;\n sombraAuth?: string;\n transcendUrl: string;\n file?: string;\n directory?: string;\n dryRun: boolean;\n skipExistingRecordCheck: boolean;\n receiptFileDir: string;\n skipWorkflowTriggers: boolean;\n forceTriggerWorkflows: boolean;\n skipConflictUpdates: boolean;\n isSilent: boolean;\n attributes: string;\n receiptFilepath: string;\n concurrency: number;\n}\n\nexport async function uploadPreferences(\n this: LocalContext,\n {\n auth,\n partition,\n sombraAuth,\n transcendUrl,\n file = '',\n directory,\n dryRun,\n skipExistingRecordCheck,\n receiptFileDir,\n skipWorkflowTriggers,\n forceTriggerWorkflows,\n skipConflictUpdates,\n isSilent,\n attributes,\n concurrency,\n }: UploadPreferencesCommandFlags,\n): Promise<void> {\n if (!!directory && !!file) {\n logger.error(\n colors.red('Cannot provide both a directory and a file. Please provide only one.'),\n );\n this.process.exit(1);\n }\n\n if (!file && !directory) {\n logger.error(\n colors.red(\n 'A file or directory must be provided. Please provide one using --file=./preferences.csv or --directory=./preferences',\n ),\n );\n this.process.exit(1);\n }\n\n doneInputValidation(this.process.exit);\n\n const files: string[] = [];\n\n if (directory) {\n try {\n const filesInDirectory = readdirSync(directory);\n const csvFiles = filesInDirectory.filter((file) => file.endsWith('.csv'));\n\n if (csvFiles.length === 0) {\n logger.error(colors.red(`No CSV files found in directory: ${directory}`));\n this.process.exit(1);\n }\n\n // Add full paths for each CSV file\n files.push(...csvFiles.map((file) => join(directory, file)));\n } catch (err) {\n logger.error(colors.red(`Failed to read directory: ${directory}`));\n logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n } else {\n try {\n // Verify file exists and is a CSV\n if (!file.endsWith('.csv')) {\n logger.error(colors.red('File must be a CSV file'));\n this.process.exit(1);\n }\n files.push(file);\n } catch (err) {\n logger.error(colors.red(`Failed to access file: ${file}`));\n logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n }\n\n logger.info(\n colors.green(\n `Processing ${files.length} consent preferences files for partition: ${partition}`,\n ),\n );\n logger.debug(`Files to process: ${files.join(', ')}`);\n\n if (skipExistingRecordCheck) {\n logger.info(colors.bgYellow(`Skipping existing record check: ${skipExistingRecordCheck}`));\n }\n\n await map(\n files,\n async (filePath) => {\n const fileName = basename(filePath).replace('.csv', '');\n await uploadPreferenceManagementPreferencesInteractive({\n receiptFilepath: join(receiptFileDir, `${fileName}-receipts.json`),\n auth,\n sombraAuth,\n file: filePath,\n partition,\n transcendUrl,\n skipConflictUpdates,\n skipWorkflowTriggers,\n skipExistingRecordCheck,\n isSilent,\n dryRun,\n attributes: splitCsvToList(attributes),\n forceTriggerWorkflows,\n });\n },\n { concurrency },\n );\n}\n"],"mappings":"wkCAmBA,eAAsB,EACpB,EACA,EACA,CACE,eACA,mBACA,yBAS0B,CAK5B,IAAM,EAAe,EAHD,EAAK,EAAY,IAAK,GAAM,OAAO,KAAK,EAAE,CAAC,CAAC,MAAM,CAG3B,CAAE,CAC3C,GAAI,EAAa,iBAAmB,CAAC,EAAa,iBAAiB,CAAG,EAAE,CACxE,GAAI,EAAa,eAAiB,CAAC,EAAa,eAAe,CAAG,EAAE,CACrE,CAAC,CACF,GAAI,EAAa,SAAW,EAAG,CAC7B,GAAI,EACF,OAAO,EAET,MAAU,MAAM,8BAA8B,CAIhD,IAAM,EAAe,CACnB,GAA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,IAAI,0BAA0B,CAAC,CACnD,KAAK,QAAQ,KAAK,EAAE,EAEtB,EAAM,KAAK,EAAK,OACT,EAAK,CACZ,EAAO,MAAM,EAAO,IAAI,0BAA0B,IAAO,CAAC,CAC1D,EAAO,MAAM,EAAO,IAAK,EAAc,QAAQ,CAAC,CAChD,KAAK,QAAQ,KAAK,EAAE,CAIxB,EAAO,KACL,EAAO,MACL,cAAc,EAAM,OAAO,4CAA4C,IACxE,CACF,CACD,EAAO,MAAM,qBAAqB,EAAM,KAAK,KAAK,GAAG,CAEjD,GACF,EAAO,KAAK,EAAO,SAAS,mCAAmC,IAA0B,CAAC,CAG5F,MAAM,EACJ,EACA,KAAO,IAAa,CAElB,MAAM,EAAiD,CACrD,gBAAiB,EAAK,EAAgB,GAFvB,EAAS,EAAS,CAAC,QAAQ,OAAQ,GAED,CAAC,gBAAgB,CAClE,OACA,aACA,KAAM,EACN,YACA,eACA,sBACA,uBACA,0BACA,WACA,SACA,WAAY,EAAe,EAAW,CACtC,wBACD,CAAC,EAEJ,CAAE,cAAa,CAChB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./pushManualEnrichmentIdentifiersFromCsv-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{t as e}from"./pushManualEnrichmentIdentifiersFromCsv-dUpnhCWn.mjs";import{t}from"./done-input-validation-BcNBxhEs.mjs";async function n({auth:n,transcendUrl:r,file:i,enricherId:a,concurrency:o,markSilent:s,sombraAuth:c}){t(this.process.exit),await e({file:i,transcendUrl:r,enricherId:a,concurrency:o,markSilent:s,auth:n,sombraAuth:c})}export{n as pushIdentifiers};
|
|
2
|
+
//# sourceMappingURL=impl-DrrdL07c.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-DrrdL07c.mjs","names":[],"sources":["../src/commands/request/preflight/push-identifiers/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../../context.js';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation.js';\nimport { pushManualEnrichmentIdentifiersFromCsv } from '../../../../lib/manual-enrichment/index.js';\n\nexport interface PushIdentifiersCommandFlags {\n auth: string;\n enricherId: string;\n sombraAuth?: string;\n transcendUrl: string;\n file: string;\n markSilent: boolean;\n concurrency: number;\n}\n\nexport async function pushIdentifiers(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n file,\n enricherId,\n concurrency,\n markSilent,\n sombraAuth,\n }: PushIdentifiersCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await pushManualEnrichmentIdentifiersFromCsv({\n file,\n transcendUrl,\n enricherId,\n concurrency,\n markSilent,\n auth,\n sombraAuth,\n });\n}\n"],"mappings":"8HAcA,eAAsB,EAEpB,CACE,OACA,eACA,OACA,aACA,cACA,aACA,cAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAM,EAAuC,CAC3C,OACA,eACA,aACA,cACA,aACA,OACA,aACD,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./logger-Bj782ZYD.mjs";import{t}from"./collectCsvFilesOrExit-CbtyKAzu.mjs";import{t as n}from"./done-input-validation-BcNBxhEs.mjs";import{a as r,i,n as a,r as o,t as s}from"./createExtraKeyHandler-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{t as e}from"./logger-Bj782ZYD.mjs";import{t}from"./collectCsvFilesOrExit-CbtyKAzu.mjs";import{t as n}from"./done-input-validation-BcNBxhEs.mjs";import{a as r,i,n as a,r as o,t as s}from"./createExtraKeyHandler-CUsI4MJp.mjs";import c from"colors";import{CHILD_FLAG as l,PoolCancelledError as u,computePoolSize as d,resolveWorkerPath as f,runPool as p}from"@transcend-io/utils";function m(e){return a(e)}function h(e){return o(e)}const g={renderHeader:m,renderWorkers:h};async function _(a){n(this.process.exit);let{directory:o,outputDir:m,clearOutputDir:h,chunkSizeMB:_,concurrency:v,viewerMode:y}=a,b=t(o,this),{poolSize:x,cpuCount:S}=d(v,b.length);e.info(c.green(`Chunking ${b.length} CSV file(s) with pool size ${x} (CPU=${S})`));let C=b.map(e=>({filePath:e,options:{outputDir:m,clearOutputDir:h,chunkSizeMB:_}}));await p({title:`Chunk CSV - ${o}`,baseDir:o||m||process.cwd(),childFlag:l,childModulePath:f(import.meta.url,`commands/admin/chunk-csv/worker.mjs`),poolSize:x,cpuCount:S,filesTotal:b.length,hooks:{nextTask:()=>C.shift(),taskLabel:e=>e.filePath,initTotals:()=>({}),initSlotProgress:()=>void 0,onProgress:e=>e,onResult:(e,t)=>({totals:e,ok:!!t.ok}),postProcess:async()=>{}},viewerMode:y,render:e=>i(e,g,y),installInteractiveSwitcher:y?void 0:({workers:e,onCtrlC:t,getLogPaths:n,replayBytes:i,replayWhich:a,setPaused:o,repaint:s})=>r({workers:e,onCtrlC:t,getLogPaths:n,replayBytes:i,replayWhich:a,onAttach:()=>o(!0),onDetach:()=>{o(!1),s()},onEnterAttachScreen:e=>{o(!0),process.stdout.write(`\x1B[2J\x1B[H`),process.stdout.write(`Attached to worker ${e}. (Esc/Ctrl+] detach \u2022 Ctrl+D EOF \u2022 Ctrl+C SIGINT)\n`)}}),extraKeyHandler:({logsBySlot:e,repaint:t,setPaused:n})=>s({logsBySlot:e,repaint:t,setPaused:n})}).catch(e=>{throw e instanceof u&&process.exit(130),e})}export{_ as chunkCsv};
|
|
2
|
+
//# sourceMappingURL=impl-DzLb8cTW.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-DzLb8cTW.mjs","names":[],"sources":["../src/commands/admin/chunk-csv/ui/plugin.ts","../src/commands/admin/chunk-csv/impl.ts"],"sourcesContent":["import {\n makeHeader,\n makeWorkerRows,\n type ChunkSlotProgress,\n type CommonCtx,\n type DashboardPlugin,\n} from '../../../../lib/pooling/index.js';\n\n/**\n * Header for chunk-csv (no extra totals block).\n *\n * @param ctx - Dashboard context.\n * @returns Header lines.\n */\nfunction renderHeader<TTotals>(ctx: CommonCtx<TTotals, ChunkSlotProgress>): string[] {\n // no extra lines — reuse the shared header as-is\n return makeHeader(ctx);\n}\n\n/**\n * Worker rows for chunk-csv — share the generic row renderer.\n *\n * @param ctx - Dashboard context.\n * @returns Array of strings, each representing one worker row.\n */\nfunction renderWorkers<TTotals>(ctx: CommonCtx<TTotals, ChunkSlotProgress>): string[] {\n return makeWorkerRows(ctx);\n}\n\nexport const chunkCsvPlugin: DashboardPlugin<unknown, ChunkSlotProgress> = {\n renderHeader,\n renderWorkers,\n // no extras\n};\n","import {\n CHILD_FLAG,\n type PoolHooks,\n runPool,\n computePoolSize,\n PoolCancelledError,\n resolveWorkerPath,\n} from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { collectCsvFilesOrExit } from '../../../lib/helpers/collectCsvFilesOrExit.js';\nimport {\n createExtraKeyHandler,\n dashboardPlugin,\n installInteractiveSwitcher,\n} from '../../../lib/pooling/index.js';\nimport { logger } from '../../../logger.js';\nimport { chunkCsvPlugin } from './ui/index.js';\nimport type { ChunkProgress, ChunkResult, ChunkTask } from './worker.js';\n\n/**\n * Totals aggregate for this command.\n * We don’t need custom counters since the runner already tracks\n * completed/failed counts in its header — so we just use an empty record.\n */\ntype Totals = Record<string, never>;\n\n/**\n * CLI flags accepted by the `chunk-csv` command.\n *\n * These are passed down from the CLI parser into the parent process.\n */\nexport type ChunkCsvCommandFlags = {\n directory: string;\n outputDir?: string;\n clearOutputDir: boolean;\n chunkSizeMB: number;\n concurrency?: number;\n viewerMode: boolean;\n};\n\n/**\n * Parent entrypoint for chunking many CSVs in parallel using the worker pool runner.\n *\n * Lifecycle:\n * 1) Discover CSV inputs (exit if none).\n * 2) Compute pool size (CPU-count heuristic or --concurrency).\n * 3) Build a FIFO queue of `ChunkTask`s.\n * 4) Define pool hooks to drive task assignment, progress, and result handling.\n * 5) Launch the pool with `runPool`, rendering via the `chunkCsvPlugin`.\n *\n * @param this - Bound CLI context (provides process exit + logging).\n * @param flags - CLI options for the run.\n */\nexport async function chunkCsv(this: LocalContext, flags: ChunkCsvCommandFlags): Promise<void> {\n doneInputValidation(this.process.exit);\n\n const { directory, outputDir, clearOutputDir, chunkSizeMB, concurrency, viewerMode } = flags;\n\n /* 1) Discover CSV inputs */\n const files = collectCsvFilesOrExit(directory, this);\n\n /* 2) Size the pool */\n const { poolSize, cpuCount } = computePoolSize(concurrency, files.length);\n\n logger.info(\n colors.green(\n `Chunking ${files.length} CSV file(s) with pool size ${poolSize} (CPU=${cpuCount})`,\n ),\n );\n\n /* 3) Prepare a simple FIFO queue of tasks (one per file). */\n const queue = files.map<ChunkTask>((filePath) => ({\n filePath,\n options: { outputDir, clearOutputDir, chunkSizeMB },\n }));\n\n /* 4) Define pool hooks to adapt runner to this command. */\n const hooks: PoolHooks<ChunkTask, ChunkProgress, ChunkResult, Totals> = {\n nextTask: () => queue.shift(),\n taskLabel: (t) => t.filePath,\n initTotals: () => ({}) as Totals,\n initSlotProgress: () => undefined,\n onProgress: (totals) => totals,\n onResult: (totals, res) => ({ totals, ok: !!res.ok }),\n // postProcess receives log context when viewerMode=true — we don’t need it here.\n postProcess: async () => {\n // nothing extra for chunk-csv\n },\n };\n\n /* 5) Launch the pool runner with our hooks and custom dashboard plugin. */\n await runPool({\n title: `Chunk CSV - ${directory}`,\n baseDir: directory || outputDir || process.cwd(),\n childFlag: CHILD_FLAG,\n childModulePath: resolveWorkerPath(import.meta.url, 'commands/admin/chunk-csv/worker.mjs'),\n poolSize,\n cpuCount,\n filesTotal: files.length,\n hooks,\n viewerMode,\n render: (input) => dashboardPlugin(input, chunkCsvPlugin, viewerMode),\n installInteractiveSwitcher: viewerMode\n ? undefined\n : ({\n workers,\n onCtrlC,\n getLogPaths,\n replayBytes: rb,\n replayWhich: rw,\n setPaused,\n repaint: rp,\n }) =>\n installInteractiveSwitcher({\n workers,\n onCtrlC,\n getLogPaths,\n replayBytes: rb,\n replayWhich: rw,\n onAttach: () => setPaused(true),\n onDetach: () => {\n setPaused(false);\n rp();\n },\n onEnterAttachScreen: (id) => {\n setPaused(true);\n process.stdout.write('\\x1b[2J\\x1b[H');\n process.stdout.write(\n `Attached to worker ${id}. (Esc/Ctrl+] detach \\u2022 Ctrl+D EOF \\u2022 Ctrl+C SIGINT)\\n`,\n );\n },\n }),\n extraKeyHandler: ({ logsBySlot, repaint, setPaused }) =>\n createExtraKeyHandler({\n logsBySlot,\n repaint,\n setPaused,\n }),\n }).catch((err) => {\n if (err instanceof PoolCancelledError) {\n process.exit(130);\n }\n throw err;\n });\n}\n"],"mappings":"+XAcA,SAAS,EAAsB,EAAsD,CAEnF,OAAO,EAAW,EAAI,CASxB,SAAS,EAAuB,EAAsD,CACpF,OAAO,EAAe,EAAI,CAG5B,MAAa,EAA8D,CACzE,eACA,gBAED,CCuBD,eAAsB,EAA6B,EAA4C,CAC7F,EAAoB,KAAK,QAAQ,KAAK,CAEtC,GAAM,CAAE,YAAW,YAAW,iBAAgB,cAAa,cAAa,cAAe,EAGjF,EAAQ,EAAsB,EAAW,KAAK,CAG9C,CAAE,WAAU,YAAa,EAAgB,EAAa,EAAM,OAAO,CAEzE,EAAO,KACL,EAAO,MACL,YAAY,EAAM,OAAO,8BAA8B,EAAS,QAAQ,EAAS,GAClF,CACF,CAGD,IAAM,EAAQ,EAAM,IAAgB,IAAc,CAChD,WACA,QAAS,CAAE,YAAW,iBAAgB,cAAa,CACpD,EAAE,CAiBH,MAAM,EAAQ,CACZ,MAAO,eAAe,IACtB,QAAS,GAAa,GAAa,QAAQ,KAAK,CAChD,UAAW,EACX,gBAAiB,EAAkB,OAAO,KAAK,IAAK,sCAAsC,CAC1F,WACA,WACA,WAAY,EAAM,OAClB,MAAA,CArBA,aAAgB,EAAM,OAAO,CAC7B,UAAY,GAAM,EAAE,SACpB,gBAAmB,EAAE,EACrB,qBAAwB,IAAA,GACxB,WAAa,GAAW,EACxB,UAAW,EAAQ,KAAS,CAAE,SAAQ,GAAI,CAAC,CAAC,EAAI,GAAI,EAEpD,YAAa,SAAY,GAcpB,CACL,aACA,OAAS,GAAU,EAAgB,EAAO,EAAgB,EAAW,CACrE,2BAA4B,EACxB,IAAA,IACC,CACC,UACA,UACA,cACA,YAAa,EACb,YAAa,EACb,YACA,QAAS,KAET,EAA2B,CACzB,UACA,UACA,cACA,YAAa,EACb,YAAa,EACb,aAAgB,EAAU,GAAK,CAC/B,aAAgB,CACd,EAAU,GAAM,CAChB,GAAI,EAEN,oBAAsB,GAAO,CAC3B,EAAU,GAAK,CACf,QAAQ,OAAO,MAAM,gBAAgB,CACrC,QAAQ,OAAO,MACb,sBAAsB,EAAG,gEAC1B,EAEJ,CAAC,CACR,iBAAkB,CAAE,aAAY,UAAS,eACvC,EAAsB,CACpB,aACA,UACA,YACD,CAAC,CACL,CAAC,CAAC,MAAO,GAAQ,CAIhB,MAHI,aAAe,GACjB,QAAQ,KAAK,IAAI,CAEb,GACN"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{o as e}from"./enums-CyFTrzXY.mjs";import{r as t}from"./constants-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{o as e}from"./enums-CyFTrzXY.mjs";import{r as t}from"./constants-CeIAxxnY.mjs";import{n,t as r}from"./command-Boc-4Yl2.mjs";import{t as i}from"./logger-Bj782ZYD.mjs";import{a}from"./readTranscendYaml-BbnEGgVD.mjs";import{n as o}from"./pullTranscendConfiguration-D_znkqJz.mjs";import{t as s}from"./validateTranscendAuth-BHw0WQu1.mjs";import{t as c}from"./done-input-validation-BcNBxhEs.mjs";import l from"node:fs";import{join as u}from"node:path";import d from"colors";import{buildTranscendGraphQLClient as f}from"@transcend-io/sdk";import{mapSeries as p}from"@transcend-io/utils";async function m({auth:m,resources:h=n,file:g,transcendUrl:_,dataSiloIds:v=[],integrationNames:y=[],trackerStatuses:b=r,pageSize:x,skipDatapoints:S,skipSubDatapoints:C,includeGuessedCategories:w,debug:T}){c(this.process.exit);let E=await s(m),D=h.includes(`all`)?Object.values(e):h;if(typeof E==`string`){try{let e=await o(f(_,E),{dataSiloIds:v,integrationNames:y,resources:D,pageSize:x,debug:T,skipDatapoints:S,skipSubDatapoints:C,includeGuessedCategories:w,trackerStatuses:b});i.info(d.magenta(`Writing configuration to file "${g}"...`)),a(g,e)}catch(e){i.error(d.red(`An error occurred syncing the schema: ${T?e.stack:e.message}`)),this.process.exit(1)}i.info(d.green(`Successfully synced yaml file to disk at ${g}! View at ${t}`))}else{if(!l.lstatSync(g).isDirectory())throw Error(`File is expected to be a folder when passing in a list of API keys to pull from. e.g. --file=./working/`);let e=[];await p(E,async(t,n)=>{let r=`[${n+1}/${E.length}][${t.organizationName}] `;i.info(d.magenta(`~~~\n\n${r}Attempting to pull configuration...\n\n~~~`));let s=f(_,t.apiKey);try{let e=await o(s,{dataSiloIds:v,integrationNames:y,resources:D,pageSize:x,debug:T,skipDatapoints:S,skipSubDatapoints:C,includeGuessedCategories:w,trackerStatuses:b}),n=u(g,`${t.organizationName}.yml`);i.info(d.magenta(`Writing configuration to file "${n}"...`)),a(n,e),i.info(d.green(`${r}Successfully pulled configuration!`))}catch(n){i.error(d.red(`${r}Failed to sync configuration. - ${n.message}`)),e.push(t.organizationName)}}),e.length>0&&(i.info(d.red(`Sync encountered errors for "${e.join(`,`)}". View output above for more information, or check out ${t}`)),this.process.exit(1))}}export{m as pull};
|
|
2
|
+
//# sourceMappingURL=impl-OB3mOEa_.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-OB3mOEa_.mjs","names":[],"sources":["../src/commands/inventory/pull/impl.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { join } from 'node:path';\n\nimport { ConsentTrackerStatus } from '@transcend-io/privacy-types';\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport { mapSeries } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport { ADMIN_DASH_INTEGRATIONS } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { TranscendPullResource } from '../../../enums.js';\nimport { validateTranscendAuth } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { pullTranscendConfiguration } from '../../../lib/graphql/index.js';\nimport { writeTranscendYaml } from '../../../lib/readTranscendYaml.js';\nimport { logger } from '../../../logger.js';\nimport { DEFAULT_CONSENT_TRACKER_STATUSES, DEFAULT_TRANSCEND_PULL_RESOURCES } from './command.js';\n\nexport interface PullCommandFlags {\n auth: string;\n resources?: (TranscendPullResource | 'all')[];\n file: string;\n transcendUrl: string;\n dataSiloIds?: string[];\n integrationNames?: string[];\n trackerStatuses?: ConsentTrackerStatus[];\n pageSize: number;\n skipDatapoints: boolean;\n skipSubDatapoints: boolean;\n includeGuessedCategories: boolean;\n debug: boolean;\n}\n\nexport async function pull(\n this: LocalContext,\n {\n auth,\n resources = DEFAULT_TRANSCEND_PULL_RESOURCES,\n file,\n transcendUrl,\n dataSiloIds = [],\n integrationNames = [],\n trackerStatuses = DEFAULT_CONSENT_TRACKER_STATUSES,\n pageSize,\n skipDatapoints,\n skipSubDatapoints,\n includeGuessedCategories,\n debug,\n }: PullCommandFlags,\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 const resourcesToPull: TranscendPullResource[] = resources.includes('all')\n ? Object.values(TranscendPullResource)\n : (resources as TranscendPullResource[]);\n\n // Sync to Disk\n if (typeof apiKeyOrList === 'string') {\n try {\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, apiKeyOrList);\n\n const configuration = await pullTranscendConfiguration(client, {\n dataSiloIds,\n integrationNames,\n resources: resourcesToPull,\n pageSize,\n debug,\n skipDatapoints,\n skipSubDatapoints,\n includeGuessedCategories,\n trackerStatuses,\n });\n\n logger.info(colors.magenta(`Writing configuration to file \"${file}\"...`));\n writeTranscendYaml(file, configuration);\n } catch (err) {\n logger.error(\n colors.red(`An error occurred syncing the schema: ${debug ? err.stack : err.message}`),\n );\n this.process.exit(1);\n }\n\n // Indicate success\n logger.info(\n colors.green(\n `Successfully synced yaml file to disk at ${file}! View at ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n } else {\n if (!fs.lstatSync(file).isDirectory()) {\n throw new Error(\n 'File is expected to be a folder when passing in a list of API keys to pull from. e.g. --file=./working/',\n );\n }\n\n const encounteredErrors: string[] = [];\n await mapSeries(apiKeyOrList, async (apiKey, ind) => {\n const prefix = `[${ind + 1}/${apiKeyOrList.length}][${apiKey.organizationName}] `;\n logger.info(colors.magenta(`~~~\\n\\n${prefix}Attempting to pull configuration...\\n\\n~~~`));\n\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, apiKey.apiKey);\n\n try {\n const configuration = await pullTranscendConfiguration(client, {\n dataSiloIds,\n integrationNames,\n resources: resourcesToPull,\n pageSize,\n debug,\n skipDatapoints,\n skipSubDatapoints,\n includeGuessedCategories,\n trackerStatuses,\n });\n\n const filePath = join(file, `${apiKey.organizationName}.yml`);\n logger.info(colors.magenta(`Writing configuration to file \"${filePath}\"...`));\n writeTranscendYaml(filePath, configuration);\n\n logger.info(colors.green(`${prefix}Successfully pulled configuration!`));\n } catch (err) {\n logger.error(colors.red(`${prefix}Failed to sync configuration. - ${err.message}`));\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"],"mappings":"2kBAiCA,eAAsB,EAEpB,CACE,OACA,YAAY,EACZ,OACA,eACA,cAAc,EAAE,CAChB,mBAAmB,EAAE,C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,oCAAoC,CAAC,OACjE,EAAK,CACZ,EAAO,MAAM,EAAO,IAAI,GAAG,EAAO,kCAAkC,EAAI,UAAU,CAAC,CACnF,EAAkB,KAAK,EAAO,iBAAiB,GAEjD,CAEE,EAAkB,OAAS,IAC7B,EAAO,KACL,EAAO,IACL,gCAAgC,EAAkB,KAChD,IACD,CAAC,0DAA0D,IAC7D,CACF,CAED,KAAK,QAAQ,KAAK,EAAE"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as e}from"./constants-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{r as e}from"./constants-CeIAxxnY.mjs";import{t}from"./logger-Bj782ZYD.mjs";import{r as n}from"./readTranscendYaml-BbnEGgVD.mjs";import{n as r,r as i,t as a}from"./parseVariablesFromString-BeKOGw5n.mjs";import{t as o}from"./validateTranscendAuth-BHw0WQu1.mjs";import{t as s}from"./listFiles-D2wMHnEr.mjs";import{t as c}from"./done-input-validation-BcNBxhEs.mjs";import{existsSync as l,lstatSync as u}from"node:fs";import{join as d}from"node:path";import f from"colors";import{buildTranscendGraphQLClient as p}from"@transcend-io/sdk";import{mapSeries as m}from"@transcend-io/utils";async function h({transcendUrl:e,auth:n,pageSize:r,publishToPrivacyCenter:a,contents:o,deleteExtraAttributeValues:s=!1,classifyService:c=!1}){let l=p(e,n);try{return!await i(o,l,{pageSize:r,publishToPrivacyCenter:a,classifyService:c,deleteExtraAttributeValues:s})}catch(e){return t.error(f.red(`An unexpected error occurred syncing the schema: ${e.message}`)),!1}}async function g({file:i=`./transcend.yml`,transcendUrl:p,auth:g,variables:_,pageSize:v,publishToPrivacyCenter:y,classifyService:b,deleteExtraAttributeValues:x}){c(this.process.exit);let S=await o(g),C=a(_),w;if(w=Array.isArray(S)&&u(i).isDirectory()?s(i).map(e=>d(i,e)):i.split(`,`),w.length<1)throw Error(`No file specified!`);let T=w.map(e=>{l(e)?t.info(f.magenta(`Reading file "${e}"...`)):(t.error(f.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 r=n(e,C);return t.info(f.green(`Successfully read in "${e}"`)),{content:r,name:e.split(`/`).pop().replace(`.yml`,``)}}catch(e){t.error(f.red(`The shape of your yaml file is invalid with the following errors: ${e.message}`)),this.process.exit(1)}});if(typeof S==`string`){let[n,...i]=T.map(({content:e})=>e);await h({transcendUrl:p,auth:S,contents:r(n,...i),publishToPrivacyCenter:y,deleteExtraAttributeValues:x,pageSize:v,classifyService:!!b})||(t.info(f.red(`Sync encountered errors. View output above for more information, or check out ${e}`)),this.process.exit(1))}else{if(T.length!==1&&T.length!==S.length)throw Error(`Expected list of yml files to be equal to the list of API keys.Got ${T.length} YML file${T.length===1?``:`s`} and ${S.length} API key${S.length===1?``:`s`}`);let n=[];await m(S,async(e,r)=>{let i=`[${r+1}/${S.length}][${e.organizationName}] `;t.info(f.magenta(`~~~\n\n${i}Attempting to push configuration...\n\n~~~`));let a=T.length===1?T[0].content:T.find(t=>t.name===e.organizationName)?.content;if(!a){t.error(f.red(`${i}Failed to find transcend.yml file for organization: "${e.organizationName}".`)),n.push(e.organizationName);return}await h({transcendUrl:p,auth:e.apiKey,contents:a,pageSize:v,publishToPrivacyCenter:y,deleteExtraAttributeValues:x,classifyService:b})?t.info(f.green(`${i}Successfully pushed configuration!`)):(t.error(f.red(`${i}Failed to sync configuration.`)),n.push(e.organizationName))}),n.length>0&&(t.info(f.red(`Sync encountered errors for "${n.join(`,`)}". View output above for more information, or check out ${e}`)),this.process.exit(1))}t.info(f.green(`Successfully synced yaml file to Transcend! View at ${e}`))}export{g as push};
|
|
2
|
+
//# sourceMappingURL=impl-VVA4YqAf.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-Dt_JYmLa.mjs","names":[],"sources":["../src/commands/inventory/push/impl.ts"],"sourcesContent":["import { existsSync, lstatSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport { mapSeries } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport { TranscendInput } from '../../../codecs.js';\nimport { ADMIN_DASH_INTEGRATIONS } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { validateTranscendAuth, listFiles } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { syncConfigurationToTranscend } from '../../../lib/graphql/index.js';\nimport { parseVariablesFromString } from '../../../lib/helpers/parseVariablesFromString.js';\nimport { mergeTranscendInputs } from '../../../lib/mergeTranscendInputs.js';\nimport { readTranscendYaml } from '../../../lib/readTranscendYaml.js';\nimport { logger } from '../../../logger.js';\n\n/**\n * Sync configuration to Transcend\n *\n * @param options - Options\n * @returns True if synced successfully, false if error occurs\n */\nasync function syncConfiguration({\n transcendUrl,\n auth,\n pageSize,\n publishToPrivacyCenter,\n contents,\n deleteExtraAttributeValues = false,\n classifyService = false,\n}: {\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(contents, client, {\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n });\n return !encounteredError;\n } catch (err) {\n logger.error(colors.red(`An unexpected error occurred syncing the schema: ${err.message}`));\n return false;\n }\n}\n\nexport interface PushCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n pageSize: number;\n variables: string;\n publishToPrivacyCenter: boolean;\n classifyService: boolean;\n deleteExtraAttributeValues: boolean;\n}\n\nexport async function push(\n this: LocalContext,\n {\n file = './transcend.yml',\n transcendUrl,\n auth,\n variables,\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n }: PushCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.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 (transcendInputs.length !== 1 && transcendInputs.length !== apiKeyOrList.length) {\n throw new Error(\n 'Expected list of yml files to be equal to the list of API keys.' +\n `Got ${transcendInputs.length} YML file${\n transcendInputs.length === 1 ? '' : 's'\n } and ${apiKeyOrList.length} API key${apiKeyOrList.length === 1 ? '' : 's'}`,\n );\n }\n\n const encounteredErrors: string[] = [];\n await mapSeries(apiKeyOrList, async (apiKey, ind) => {\n const prefix = `[${ind + 1}/${apiKeyOrList.length}][${apiKey.organizationName}] `;\n logger.info(colors.magenta(`~~~\\n\\n${prefix}Attempting to push configuration...\\n\\n~~~`));\n\n // use the merged contents if 1 yml passed, else use the contents that map to that organization\n const useContents =\n transcendInputs.length === 1\n ? transcendInputs[0].content\n : transcendInputs.find((input) => input.name === apiKey.organizationName)?.content;\n\n // Throw error if cannot find a yml file matching that organization name\n if (!useContents) {\n 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(colors.green(`${prefix}Successfully pushed configuration!`));\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(`Successfully synced yaml file to Transcend! View at ${ADMIN_DASH_INTEGRATIONS}`),\n );\n}\n"],"mappings":"2kBAwBA,eAAe,EAAkB,CAC/B,eACA,OACA,WACA,yBACA,WACA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EAAO,KACL,EAAO,MAAM,uDAAuD,IAA0B,CAC/F"}
|
|
1
|
+
{"version":3,"file":"impl-VVA4YqAf.mjs","names":[],"sources":["../src/commands/inventory/push/impl.ts"],"sourcesContent":["import { existsSync, lstatSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport { mapSeries } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport { TranscendInput } from '../../../codecs.js';\nimport { ADMIN_DASH_INTEGRATIONS } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { validateTranscendAuth, listFiles } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { syncConfigurationToTranscend } from '../../../lib/graphql/index.js';\nimport { parseVariablesFromString } from '../../../lib/helpers/parseVariablesFromString.js';\nimport { mergeTranscendInputs } from '../../../lib/mergeTranscendInputs.js';\nimport { readTranscendYaml } from '../../../lib/readTranscendYaml.js';\nimport { logger } from '../../../logger.js';\n\n/**\n * Sync configuration to Transcend\n *\n * @param options - Options\n * @returns True if synced successfully, false if error occurs\n */\nasync function syncConfiguration({\n transcendUrl,\n auth,\n pageSize,\n publishToPrivacyCenter,\n contents,\n deleteExtraAttributeValues = false,\n classifyService = false,\n}: {\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(contents, client, {\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n });\n return !encounteredError;\n } catch (err) {\n logger.error(colors.red(`An unexpected error occurred syncing the schema: ${err.message}`));\n return false;\n }\n}\n\nexport interface PushCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n pageSize: number;\n variables: string;\n publishToPrivacyCenter: boolean;\n classifyService: boolean;\n deleteExtraAttributeValues: boolean;\n}\n\nexport async function push(\n this: LocalContext,\n {\n file = './transcend.yml',\n transcendUrl,\n auth,\n variables,\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n }: PushCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.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 (transcendInputs.length !== 1 && transcendInputs.length !== apiKeyOrList.length) {\n throw new Error(\n 'Expected list of yml files to be equal to the list of API keys.' +\n `Got ${transcendInputs.length} YML file${\n transcendInputs.length === 1 ? '' : 's'\n } and ${apiKeyOrList.length} API key${apiKeyOrList.length === 1 ? '' : 's'}`,\n );\n }\n\n const encounteredErrors: string[] = [];\n await mapSeries(apiKeyOrList, async (apiKey, ind) => {\n const prefix = `[${ind + 1}/${apiKeyOrList.length}][${apiKey.organizationName}] `;\n logger.info(colors.magenta(`~~~\\n\\n${prefix}Attempting to push configuration...\\n\\n~~~`));\n\n // use the merged contents if 1 yml passed, else use the contents that map to that organization\n const useContents =\n transcendInputs.length === 1\n ? transcendInputs[0].content\n : transcendInputs.find((input) => input.name === apiKey.organizationName)?.content;\n\n // Throw error if cannot find a yml file matching that organization name\n if (!useContents) {\n 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(colors.green(`${prefix}Successfully pushed configuration!`));\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(`Successfully synced yaml file to Transcend! View at ${ADMIN_DASH_INTEGRATIONS}`),\n );\n}\n"],"mappings":"2kBAwBA,eAAe,EAAkB,CAC/B,eACA,OACA,WACA,yBACA,WACA,6BAA6B,GAC7B,kBAAkB,IAgBC,CACnB,IAAM,EAAS,EAA4B,EAAc,EAAK,CAG9D,GAAI,CAOF,MAAO,CAAC,MANuB,EAA6B,EAAU,EAAQ,CAC5E,WACA,yBACA,kBACA,6BACD,CAAC,OAEK,EAAK,CAEZ,OADA,EAAO,MAAM,EAAO,IAAI,oDAAoD,EAAI,UAAU,CAAC,CACpF,IAeX,eAAsB,EAEpB,CACE,OAAO,kBACP,eACA,OACA,YACA,WACA,yBACA,kBACA,8BAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAGtC,IAAM,EAAe,MAAM,EAAsB,EAAK,CAGhD,EAAO,EAAyB,EAAU,CAG5C,EAQJ,GAPA,AAGE,EAHE,MAAM,QAAQ,EAAa,EAAI,EAAU,EAAK,CAAC,aAAa,CACnD,EAAU,EAAK,CAAC,IAAK,GAAa,EAAK,EAAM,EAAS,CAAC,CAEvD,EAAK,MAAM,IAAI,CAIxB,EAAS,OAAS,EACpB,MAAU,MAAM,qBAAqB,CAIvC,IAAM,EAAkB,EAAS,IAAK,GAAa,CAE5C,EAAW,EAAS,CAQvB,EAAO,KAAK,EAAO,QAAQ,iBAAiB,EAAS,MAAM,CAAC,EAP5D,EAAO,MACL,EAAO,IACL,yCAAyC,EAAS,sEACnD,CACF,CACD,KAAK,QAAQ,KAAK,EAAE,EAKtB,GAAI,CAEF,IAAM,EAAc,EAAkB,EAAU,EAAK,CAErD,OADA,EAAO,KAAK,EAAO,MAAM,yBAAyB,EAAS,GAAG,CAAC,CACxD,CACL,QAAS,EACT,KAAM,EAAS,MAAM,IAAI,CAAC,KAAK,CAAE,QAAQ,OAAQ,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AAI,GAAG,EAAO,+BAA+B,CAAC,CAClE,EAAkB,KAAK,EAAO,iBAAiB,GAEjD,CAEE,EAAkB,OAAS,IAC7B,EAAO,KACL,EAAO,IACL,gCAAgC,EAAkB,KAChD,IACD,CAAC,0DAA0D,IAC7D,CACF,CAED,KAAK,QAAQ,KAAK,EAAE,EAKxB,EAAO,KACL,EAAO,MAAM,uDAAuD,IAA0B,CAC/F"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./constants-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{n as e}from"./constants-CeIAxxnY.mjs";import{t}from"./logger-Bj782ZYD.mjs";import{s as n}from"./writeCsv-C4pjXGsD.mjs";import{t as r}from"./pullAllDatapoints-Bbmky50p.mjs";import{t as i}from"./done-input-validation-BcNBxhEs.mjs";import{groupBy as a,uniq as o}from"lodash-es";import s from"colors";import{buildTranscendGraphQLClient as c}from"@transcend-io/sdk";async function l({auth:l,file:u,transcendUrl:d,dataSiloIds:f,includeAttributes:p,includeGuessedCategories:m,parentCategories:h,subCategories:g=[]}){i(this.process.exit);try{let e=await r(c(d,l),{dataSiloIds:f,includeGuessedCategories:m,parentCategories:h,includeAttributes:p,subCategories:g});t.info(s.magenta(`Writing datapoints to file "${u}"...`));let i=[];await n(u,e.map(e=>{let t={"Property ID":e.id,"Data Silo":e.dataSilo.title,Object:e.dataPoint.name,"Object Path":e.dataPoint.path.join(`.`),Property:e.name,"Property Description":e.description,"Data Categories":e.categories.map(e=>`${e.category}:${e.name}`).join(`, `),"Guessed Category":e.pendingCategoryGuesses?.[0]?`${e.pendingCategoryGuesses[0].category.category}:${e.pendingCategoryGuesses[0].category.name}`:``,"Processing Purposes":e.purposes.map(e=>`${e.purpose}:${e.name}`).join(`, `),...Object.entries(a(e.attributeValues||[],({attributeKey:e})=>e.name)).reduce((e,[t,n])=>(e[t]=n.map(e=>e.name).join(`,`),e),{})};return i=o([...i,...Object.keys(t)]),t}),i)}catch(e){t.error(s.red(`An error occurred syncing the datapoints: ${e.message}`)),this.process.exit(1)}t.info(s.green(`Successfully synced datapoints to disk at ${u}! View at ${e}`))}export{l as pullDatapoints};
|
|
2
|
+
//# sourceMappingURL=impl-YtstnAO6.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-YtstnAO6.mjs","names":[],"sources":["../src/commands/inventory/pull-datapoints/impl.ts"],"sourcesContent":["import { DataCategoryType } from '@transcend-io/privacy-types';\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport { uniq, groupBy } from 'lodash-es';\n\nimport { ADMIN_DASH_DATAPOINTS } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { pullAllDatapoints } from '../../../lib/data-inventory/index.js';\nimport { writeLargeCsv } from '../../../lib/helpers/index.js';\nimport { logger } from '../../../logger.js';\n\nexport interface PullDatapointsCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n dataSiloIds?: string[];\n includeAttributes: boolean;\n includeGuessedCategories: boolean;\n parentCategories?: DataCategoryType[];\n subCategories?: string[];\n}\n\nexport async function pullDatapoints(\n this: LocalContext,\n {\n auth,\n file,\n transcendUrl,\n dataSiloIds,\n includeAttributes,\n includeGuessedCategories,\n parentCategories,\n subCategories = [],\n }: PullDatapointsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n try {\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const dataPoints = await pullAllDatapoints(client, {\n dataSiloIds,\n includeGuessedCategories,\n parentCategories,\n includeAttributes,\n subCategories, // TODO: https://transcend.height.app/T-40482 - do by name not ID\n });\n\n logger.info(colors.magenta(`Writing datapoints to file \"${file}\"...`));\n let headers: string[] = [];\n const inputs = dataPoints.map((point) => {\n const result = {\n 'Property ID': point.id,\n 'Data Silo': point.dataSilo.title,\n Object: point.dataPoint.name,\n 'Object Path': point.dataPoint.path.join('.'),\n Property: point.name,\n 'Property Description': point.description,\n 'Data Categories': point.categories\n .map((category) => `${category.category}:${category.name}`)\n .join(', '),\n 'Guessed Category': point.pendingCategoryGuesses?.[0]\n ? `${point.pendingCategoryGuesses![0]!.category.category}:${\n point.pendingCategoryGuesses![0]!.category.name\n }`\n : '',\n 'Processing Purposes': point.purposes\n .map((purpose) => `${purpose.purpose}:${purpose.name}`)\n .join(', '),\n ...Object.entries(\n groupBy(point.attributeValues || [], ({ attributeKey }) => attributeKey.name),\n ).reduce(\n (acc, [key, values]) => {\n acc[key] = values.map((value) => value.name).join(',');\n return acc;\n },\n {} as Record<string, string>,\n ),\n };\n headers = uniq([...headers, ...Object.keys(result)]);\n return result;\n });\n await writeLargeCsv(file, inputs, headers);\n } catch (err) {\n logger.error(colors.red(`An error occurred syncing the datapoints: ${err.message}`));\n this.process.exit(1);\n }\n\n // Indicate success\n logger.info(\n colors.green(\n `Successfully synced datapoints to disk at ${file}! View at ${ADMIN_DASH_DATAPOINTS}`,\n ),\n );\n}\n"],"mappings":"gXAuBA,eAAsB,EAEpB,CACE,OACA,OACA,eACA,cACA,oBACA,2BACA,mBACA,gBAAgB,EAAE,EAEL,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,GAAI,CAIF,IAAM,EAAa,MAAM,EAFV,EAA4B,EAAc,EAER,CAAE,CACjD,cACA,2BACA,mBACA,oBACA,gBACD,CAAC,CAEF,EAAO,KAAK,EAAO,QAAQ,+BAA+B,EAAK,MAAM,CAAC,CACtE,IAAI,EAAoB,EAAE,CAiC1B,MAAM,EAAc,EAhCL,EAAW,IAAK,GAAU,CACvC,IAAM,EAAS,CACb,cAAe,EAAM,GACrB,YAAa,EAAM,SAAS,MAC5B,OAAQ,EAAM,UAAU,KACxB,cAAe,EAAM,UAAU,KAAK,KAAK,IAAI,CAC7C,SAAU,EAAM,KAChB,uBAAwB,EAAM,YAC9B,kBAAmB,EAAM,WACtB,IAAK,GAAa,GAAG,EAAS,SAAS,GAAG,EAAS,OAAO,CAC1D,KAAK,KAAK,CACb,mBAAoB,EAAM,yBAAyB,GAC/C,GAAG,EAAM,uBAAwB,GAAI,SAAS,SAAS,GACrD,EAAM,uBAAwB,GAAI,SAAS,OAE7C,GACJ,sBAAuB,EAAM,SAC1B,IAAK,GAAY,GAAG,EAAQ,QAAQ,GAAG,EAAQ,OAAO,CACtD,KAAK,KAAK,CACb,GAAG,OAAO,QACR,EAAQ,EAAM,iBAAmB,EAAE,EAAG,CAAE,kBAAmB,EAAa,KAAK,CAC9E,CAAC,QACC,EAAK,CAAC,EAAK,MACV,EAAI,GAAO,EAAO,IAAK,GAAU,EAAM,KAAK,CAAC,KAAK,IAAI,CAC/C,GAET,EAAE,CACH,CACF,CAED,MADA,GAAU,EAAK,CAAC,GAAG,EAAS,GAAG,OAAO,KAAK,EAAO,CAAC,CAAC,CAC7C,GAEuB,CAAE,EAAQ,OACnC,EAAK,CACZ,EAAO,MAAM,EAAO,IAAI,6CAA6C,EAAI,UAAU,CAAC,CACpF,KAAK,QAAQ,KAAK,EAAE,CAItB,EAAO,KACL,EAAO,MACL,6CAA6C,EAAK,YAAY,IAC/D,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./bulkRetryEnrichers-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{t as e}from"./bulkRetryEnrichers-B04E_eQ1.mjs";import{t}from"./done-input-validation-BcNBxhEs.mjs";async function n({auth:n,enricherId:r,actions:i,requestEnricherStatuses:a,requestIds:o,createdAtBefore:s,createdAtAfter:c,updatedAtBefore:l,updatedAtAfter:u,concurrency:d,transcendUrl:f}){t(this.process.exit),await e({auth:n,enricherId:r,requestActions:i,requestEnricherStatuses:a,requestIds:o,createdAtBefore:s?new Date(s):void 0,createdAtAfter:c?new Date(c):void 0,updatedAtBefore:l?new Date(l):void 0,updatedAtAfter:u?new Date(u):void 0,concurrency:d,transcendUrl:f})}export{n as enricherRestart};
|
|
2
|
+
//# sourceMappingURL=impl-oZ2tCI0C.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-oZ2tCI0C.mjs","names":[],"sources":["../src/commands/request/enricher-restart/impl.ts"],"sourcesContent":["import type { RequestAction, RequestEnricherStatus } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { bulkRetryEnrichers } from '../../../lib/requests/index.js';\n\nexport interface EnricherRestartCommandFlags {\n auth: string;\n enricherId: string;\n actions?: RequestAction[];\n requestEnricherStatuses?: RequestEnricherStatus[];\n transcendUrl: string;\n concurrency: number;\n requestIds?: string[];\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n}\n\nexport async function enricherRestart(\n this: LocalContext,\n {\n auth,\n enricherId,\n actions,\n requestEnricherStatuses,\n requestIds,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n concurrency,\n transcendUrl,\n }: EnricherRestartCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await bulkRetryEnrichers({\n auth,\n enricherId,\n requestActions: actions,\n requestEnricherStatuses,\n requestIds,\n createdAtBefore: createdAtBefore ? new Date(createdAtBefore) : undefined,\n createdAtAfter: createdAtAfter ? new Date(createdAtAfter) : undefined,\n updatedAtBefore: updatedAtBefore ? new Date(updatedAtBefore) : undefined,\n updatedAtAfter: updatedAtAfter ? new Date(updatedAtAfter) : undefined,\n concurrency,\n transcendUrl,\n });\n}\n"],"mappings":"0GAoBA,eAAsB,EAEpB,CACE,OACA,aACA,UACA,0BACA,aACA,kBACA,iBACA,kBACA,iBACA,cACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAM,EAAmB,CACvB,OACA,aACA,eAAgB,EAChB,0BACA,aACA,gBAAiB,EAAkB,IAAI,KAAK,EAAgB,CAAG,IAAA,GAC/D,eAAgB,EAAiB,IAAI,KAAK,EAAe,CAAG,IAAA,GAC5D,gBAAiB,EAAkB,IAAI,KAAK,EAAgB,CAAG,IAAA,GAC/D,eAAgB,EAAiB,IAAI,KAAK,EAAe,CAAG,IAAA,GAC5D,cACA,eACD,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./skipRequestDataSilos-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{t as e}from"./skipRequestDataSilos-6Pq98znw.mjs";import{t}from"./done-input-validation-BcNBxhEs.mjs";async function n({auth:n,dataSiloId:r,status:i,statuses:a,transcendUrl:o,actionTypes:s}){t(this.process.exit),await e({transcendUrl:o,auth:n,status:i,dataSiloId:r,requestStatuses:a,actionTypes:s})}export{n as skipRequestDataSilos};
|
|
2
|
+
//# sourceMappingURL=impl-sjVATWtP.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-sjVATWtP.mjs","names":["skipRequestDataSilosHelper"],"sources":["../src/commands/request/system/skip-request-data-silos/impl.ts"],"sourcesContent":["import type {\n RequestAction,\n RequestDataSiloStatus,\n RequestStatus,\n} from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../../context.js';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation.js';\nimport { skipRequestDataSilos as skipRequestDataSilosHelper } from '../../../../lib/requests/index.js';\n\nexport interface SkipRequestDataSilosCommandFlags {\n auth: string;\n dataSiloId: string;\n transcendUrl: string;\n statuses: RequestStatus[];\n status: (typeof RequestDataSiloStatus)['Skipped'] | (typeof RequestDataSiloStatus)['Resolved'];\n actionTypes?: RequestAction[];\n}\n\nexport async function skipRequestDataSilos(\n this: LocalContext,\n {\n auth,\n dataSiloId,\n status,\n statuses,\n transcendUrl,\n actionTypes,\n }: SkipRequestDataSilosCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await skipRequestDataSilosHelper({\n transcendUrl,\n auth,\n status,\n dataSiloId,\n requestStatuses: statuses,\n actionTypes,\n });\n}\n"],"mappings":"4GAmBA,eAAsB,EAEpB,CACE,OACA,aACA,SACA,WACA,eACA,eAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAMA,EAA2B,CAC/B,eACA,OACA,SACA,aACA,gBAAiB,EACjB,cACD,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-xtlx25UP.mjs","names":[],"sources":["../src/commands/consent/generate-access-tokens/impl.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\n\nimport { SombraStandardScope } from '@transcend-io/privacy-types';\nimport {\n buildTranscendGraphQLClient,\n createPreferenceAccessTokens,\n type PreferenceAccessTokenInputWithIndex,\n} from '@transcend-io/sdk';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport * as t from 'io-ts';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { writeCsv } from '../../../lib/helpers/index.js';\nimport { readCsv } from '../../../lib/requests/index.js';\nimport { logger } from '../../../logger.js';\n\n/**\n * CLI flags accepted by the `generate-access-tokens` command.\n *\n * These are passed down from the CLI parser into the parent process.\n */\nexport type GenerateAccessTokenCommandFlags = {\n auth: string;\n file: string;\n duration: number;\n transcendUrl: string;\n subjectType: string;\n emailColumnName: string;\n coreIdentifierColumnName?: string;\n};\n\n/**\n * Take in a CSV of user identifiers and generate access tokens for each user.\n *\n * Expected CSV columns:\n * - [emailColumnName] (required)\n * - [coreIdentifierColumnName] (optional)\n *\n * @param this - Bound CLI context (provides process exit + logging).\n * @param flags - CLI options for the run.\n */\nexport async function generateAccessTokens(\n this: LocalContext,\n {\n auth,\n file,\n transcendUrl,\n duration,\n subjectType,\n emailColumnName,\n coreIdentifierColumnName,\n }: GenerateAccessTokenCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n if (!existsSync(file)) {\n logger.error(\n colors.red(`File does not exist: \"${file}\". Please provide a valid path to a CSV file.`),\n );\n this.process.exit(1);\n }\n\n try {\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Read + parse CSV\n const codec = t.type({\n [emailColumnName]: t.string,\n ...(coreIdentifierColumnName ? { [coreIdentifierColumnName]: t.string } : {}),\n });\n const rows: Array<Record<string, string>> = readCsv(file, codec);\n if (!rows.length) {\n throw new Error('Input CSV is empty.');\n }\n\n // Ensure emails and core identifiers exist\n const missingEmail = rows\n .map((r, i) => [r, i] as const)\n .filter(([r]) => !r[emailColumnName]?.trim());\n if (missingEmail.length) {\n const rowNumbers = missingEmail\n .map(([, i]) => i + 2) // +2 to account for header row and 0-indexing\n .join(', ');\n throw new Error(\n `The following rows are missing the required \"${emailColumnName}\" column: ${rowNumbers}`,\n );\n }\n if (coreIdentifierColumnName) {\n const missingCoreId = rows\n .map((r, i) => [r, i] as const)\n .filter(([r]) => !r[coreIdentifierColumnName]?.trim());\n if (missingCoreId.length) {\n const rowNumbers = missingCoreId\n .map(([, i]) => i + 2) // +2 to account for header row and 0-indexing\n .join(', ');\n throw new Error(\n `The following rows are missing the required \"${coreIdentifierColumnName}\" column: ${rowNumbers}`,\n );\n }\n }\n\n // Duration provided by CLI is in ms; GraphQL expects seconds\n const expiresInSeconds = Math.max(1, Math.floor(duration / 1000));\n\n // Build inputs for GraphQL\n const inputs = rows.map((r, index): PreferenceAccessTokenInputWithIndex => {\n const email = r[emailColumnName].trim();\n const coreIdentifier = coreIdentifierColumnName\n ? r[coreIdentifierColumnName]?.trim()\n : undefined;\n const scopes = [SombraStandardScope.PreferenceManagement];\n return {\n subjectType,\n scopes,\n expiresIn: expiresInSeconds,\n email,\n ...(coreIdentifier ? { coreIdentifier } : {}),\n index,\n };\n });\n\n // Progress bar\n const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);\n progressBar.start(inputs.length, 0);\n\n // Kick off token creation (batched internally)\n const t0 = Date.now();\n const results = await createPreferenceAccessTokens(client, {\n records: inputs,\n logger,\n emitProgress: (progress) => {\n progressBar.update(progress);\n },\n });\n progressBar.update(inputs.length);\n progressBar.stop();\n\n // Prepare output CSV rows\n const outputRows = results.map(({ accessToken, input }) => {\n if (typeof input.index !== 'number') {\n throw new Error('Internal error: missing input index.');\n }\n return {\n ...rows[input.index],\n token: accessToken,\n };\n });\n\n logger.info(colors.magenta(`Writing access tokens to file \"${file}\"...`));\n await writeCsv(file, outputRows, true);\n\n const totalTimeSec = Math.round((Date.now() - t0) / 1000);\n logger.info(\n colors.green(\n `Successfully generated ${results.length} access tokens to \"${file}\" in ${totalTimeSec}s!`,\n ),\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (err: any) {\n logger.error(\n colors.red(\n `An error occurred while generating access tokens: ${err?.message || String(err)}`,\n ),\n );\n this.process.exit(1);\n }\n}\n"],"mappings":"wcA2CA,eAAsB,EAEpB,CACE,OACA,OACA,eACA,WACA,cACA,kBACA,4BAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CACjC,EAAW,EAAK,GACnB,EAAO,MACL,EAAO,IAAI,yBAAyB,EAAK,+CAA+C,CACzF,CACD,KAAK,QAAQ,KAAK,EAAE,EAGtB,GAAI,CAEF,IAAM,EAAS,EAA4B,EAAc,EAAK,CAOxD,EAAsC,EAAQ,EAJtC,EAAE,KAAK,EAClB,GAAkB,EAAE,OACrB,GAAI,EAA2B,EAAG,GAA2B,EAAE,OAAQ,CAAG,EAAE,CAC7E,CAAC,
|
|
1
|
+
{"version":3,"file":"impl-xtlx25UP.mjs","names":[],"sources":["../src/commands/consent/generate-access-tokens/impl.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\n\nimport { SombraStandardScope } from '@transcend-io/privacy-types';\nimport {\n buildTranscendGraphQLClient,\n createPreferenceAccessTokens,\n type PreferenceAccessTokenInputWithIndex,\n} from '@transcend-io/sdk';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport * as t from 'io-ts';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { writeCsv } from '../../../lib/helpers/index.js';\nimport { readCsv } from '../../../lib/requests/index.js';\nimport { logger } from '../../../logger.js';\n\n/**\n * CLI flags accepted by the `generate-access-tokens` command.\n *\n * These are passed down from the CLI parser into the parent process.\n */\nexport type GenerateAccessTokenCommandFlags = {\n auth: string;\n file: string;\n duration: number;\n transcendUrl: string;\n subjectType: string;\n emailColumnName: string;\n coreIdentifierColumnName?: string;\n};\n\n/**\n * Take in a CSV of user identifiers and generate access tokens for each user.\n *\n * Expected CSV columns:\n * - [emailColumnName] (required)\n * - [coreIdentifierColumnName] (optional)\n *\n * @param this - Bound CLI context (provides process exit + logging).\n * @param flags - CLI options for the run.\n */\nexport async function generateAccessTokens(\n this: LocalContext,\n {\n auth,\n file,\n transcendUrl,\n duration,\n subjectType,\n emailColumnName,\n coreIdentifierColumnName,\n }: GenerateAccessTokenCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n if (!existsSync(file)) {\n logger.error(\n colors.red(`File does not exist: \"${file}\". Please provide a valid path to a CSV file.`),\n );\n this.process.exit(1);\n }\n\n try {\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Read + parse CSV\n const codec = t.type({\n [emailColumnName]: t.string,\n ...(coreIdentifierColumnName ? { [coreIdentifierColumnName]: t.string } : {}),\n });\n const rows: Array<Record<string, string>> = readCsv(file, codec);\n if (!rows.length) {\n throw new Error('Input CSV is empty.');\n }\n\n // Ensure emails and core identifiers exist\n const missingEmail = rows\n .map((r, i) => [r, i] as const)\n .filter(([r]) => !r[emailColumnName]?.trim());\n if (missingEmail.length) {\n const rowNumbers = missingEmail\n .map(([, i]) => i + 2) // +2 to account for header row and 0-indexing\n .join(', ');\n throw new Error(\n `The following rows are missing the required \"${emailColumnName}\" column: ${rowNumbers}`,\n );\n }\n if (coreIdentifierColumnName) {\n const missingCoreId = rows\n .map((r, i) => [r, i] as const)\n .filter(([r]) => !r[coreIdentifierColumnName]?.trim());\n if (missingCoreId.length) {\n const rowNumbers = missingCoreId\n .map(([, i]) => i + 2) // +2 to account for header row and 0-indexing\n .join(', ');\n throw new Error(\n `The following rows are missing the required \"${coreIdentifierColumnName}\" column: ${rowNumbers}`,\n );\n }\n }\n\n // Duration provided by CLI is in ms; GraphQL expects seconds\n const expiresInSeconds = Math.max(1, Math.floor(duration / 1000));\n\n // Build inputs for GraphQL\n const inputs = rows.map((r, index): PreferenceAccessTokenInputWithIndex => {\n const email = r[emailColumnName].trim();\n const coreIdentifier = coreIdentifierColumnName\n ? r[coreIdentifierColumnName]?.trim()\n : undefined;\n const scopes = [SombraStandardScope.PreferenceManagement];\n return {\n subjectType,\n scopes,\n expiresIn: expiresInSeconds,\n email,\n ...(coreIdentifier ? { coreIdentifier } : {}),\n index,\n };\n });\n\n // Progress bar\n const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);\n progressBar.start(inputs.length, 0);\n\n // Kick off token creation (batched internally)\n const t0 = Date.now();\n const results = await createPreferenceAccessTokens(client, {\n records: inputs,\n logger,\n emitProgress: (progress) => {\n progressBar.update(progress);\n },\n });\n progressBar.update(inputs.length);\n progressBar.stop();\n\n // Prepare output CSV rows\n const outputRows = results.map(({ accessToken, input }) => {\n if (typeof input.index !== 'number') {\n throw new Error('Internal error: missing input index.');\n }\n return {\n ...rows[input.index],\n token: accessToken,\n };\n });\n\n logger.info(colors.magenta(`Writing access tokens to file \"${file}\"...`));\n await writeCsv(file, outputRows, true);\n\n const totalTimeSec = Math.round((Date.now() - t0) / 1000);\n logger.info(\n colors.green(\n `Successfully generated ${results.length} access tokens to \"${file}\" in ${totalTimeSec}s!`,\n ),\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (err: any) {\n logger.error(\n colors.red(\n `An error occurred while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