@transcend-io/cli 7.0.0-alpha.13 → 7.0.0-alpha.15
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/bin/bash-complete.cjs +4 -0
- package/dist/bin/bash-complete.cjs.map +1 -0
- package/dist/bin/cli.cjs +3 -0
- package/dist/bin/cli.cjs.map +1 -0
- package/dist/bin/deprecated-command.cjs +7 -0
- package/dist/bin/deprecated-command.cjs.map +1 -0
- package/dist/chunk-5TWQU6YF.cjs +2844 -0
- package/dist/chunk-5TWQU6YF.cjs.map +1 -0
- package/dist/chunk-6HKJGDAM.cjs +2 -0
- package/dist/chunk-6HKJGDAM.cjs.map +1 -0
- package/dist/chunk-ABQQ23HK.cjs +2 -0
- package/dist/chunk-ABQQ23HK.cjs.map +1 -0
- package/dist/chunk-BY7W4UQF.cjs +2 -0
- package/dist/chunk-BY7W4UQF.cjs.map +1 -0
- package/dist/chunk-EG4L6YAJ.cjs +2 -0
- package/dist/chunk-EG4L6YAJ.cjs.map +1 -0
- package/dist/chunk-IBTP5OXE.cjs +2 -0
- package/dist/chunk-IBTP5OXE.cjs.map +1 -0
- package/dist/chunk-KEH7CZKK.cjs +75 -0
- package/dist/chunk-KEH7CZKK.cjs.map +1 -0
- package/dist/chunk-KOV2SQO2.cjs +4 -0
- package/dist/chunk-KOV2SQO2.cjs.map +1 -0
- package/dist/chunk-KXRTLA5U.cjs +94 -0
- package/dist/chunk-KXRTLA5U.cjs.map +1 -0
- package/dist/chunk-LZZZALF3.cjs +4 -0
- package/dist/chunk-LZZZALF3.cjs.map +1 -0
- package/dist/chunk-PBT4YWG7.cjs +9 -0
- package/dist/chunk-PBT4YWG7.cjs.map +1 -0
- package/dist/chunk-PUWWHSAM.cjs +2 -0
- package/dist/chunk-PUWWHSAM.cjs.map +1 -0
- package/dist/chunk-RPT6OXNL.cjs +3 -0
- package/dist/chunk-RPT6OXNL.cjs.map +1 -0
- package/dist/chunk-SAEKBZGF.cjs +2 -0
- package/dist/chunk-SAEKBZGF.cjs.map +1 -0
- package/dist/chunk-SEJ2UCU4.cjs +2 -0
- package/dist/chunk-SEJ2UCU4.cjs.map +1 -0
- package/dist/chunk-SR7OAEWS.cjs +2 -0
- package/dist/chunk-SR7OAEWS.cjs.map +1 -0
- package/dist/chunk-T462ONFX.cjs +2 -0
- package/dist/chunk-T462ONFX.cjs.map +1 -0
- package/dist/chunk-TD7ADMVO.cjs +2 -0
- package/dist/chunk-TD7ADMVO.cjs.map +1 -0
- package/dist/chunk-UEGX6GZ2.cjs +2 -0
- package/dist/chunk-UEGX6GZ2.cjs.map +1 -0
- package/dist/chunk-XWRWKB4H.cjs +12 -0
- package/dist/chunk-XWRWKB4H.cjs.map +1 -0
- package/dist/chunk-YGYXLCPI.cjs +2 -0
- package/dist/chunk-YGYXLCPI.cjs.map +1 -0
- package/dist/chunk-ZFZPE5BJ.cjs +2 -0
- package/dist/chunk-ZFZPE5BJ.cjs.map +1 -0
- package/dist/chunk-ZUNVPK23.cjs +2 -0
- package/dist/chunk-ZUNVPK23.cjs.map +1 -0
- package/dist/chunk-ZVK4HIDF.cjs +6 -0
- package/dist/chunk-ZVK4HIDF.cjs.map +1 -0
- package/dist/impl-2E3PAZHM.cjs +2 -0
- package/dist/impl-2E3PAZHM.cjs.map +1 -0
- package/dist/impl-2I7MIYNB.cjs +2 -0
- package/dist/impl-2I7MIYNB.cjs.map +1 -0
- package/dist/impl-7H4CBYYB.cjs +12 -0
- package/dist/impl-7H4CBYYB.cjs.map +1 -0
- package/dist/impl-7KOHW25M.cjs +6 -0
- package/dist/impl-7KOHW25M.cjs.map +1 -0
- package/dist/impl-7M4OQEYH.cjs +2 -0
- package/dist/impl-7M4OQEYH.cjs.map +1 -0
- package/dist/impl-AHGBQO5E.cjs +2 -0
- package/dist/impl-AHGBQO5E.cjs.map +1 -0
- package/dist/impl-AJB3VAJO.cjs +2 -0
- package/dist/impl-AJB3VAJO.cjs.map +1 -0
- package/dist/impl-B3EPOCAJ.cjs +2 -0
- package/dist/impl-B3EPOCAJ.cjs.map +1 -0
- package/dist/impl-BDRTVVF2.cjs +2 -0
- package/dist/impl-BDRTVVF2.cjs.map +1 -0
- package/dist/impl-CBBAWKT7.cjs +2 -0
- package/dist/impl-CBBAWKT7.cjs.map +1 -0
- package/dist/impl-DI7FIYZI.cjs +2 -0
- package/dist/impl-DI7FIYZI.cjs.map +1 -0
- package/dist/impl-DPLGIVNZ.cjs +2 -0
- package/dist/impl-DPLGIVNZ.cjs.map +1 -0
- package/dist/impl-DRJ7E2FN.cjs +2 -0
- package/dist/impl-DRJ7E2FN.cjs.map +1 -0
- package/dist/impl-F3CYEECC.cjs +2 -0
- package/dist/impl-F3CYEECC.cjs.map +1 -0
- package/dist/impl-FQF3AWHR.cjs +2 -0
- package/dist/impl-FQF3AWHR.cjs.map +1 -0
- package/dist/impl-FQYT2XK3.cjs +2 -0
- package/dist/impl-FQYT2XK3.cjs.map +1 -0
- package/dist/impl-HDVI2F6D.cjs +2 -0
- package/dist/impl-HDVI2F6D.cjs.map +1 -0
- package/dist/impl-HEGJOPZK.cjs +2 -0
- package/dist/impl-HEGJOPZK.cjs.map +1 -0
- package/dist/impl-ITBKGH3N.cjs +2 -0
- package/dist/impl-ITBKGH3N.cjs.map +1 -0
- package/dist/impl-K7CHXRVJ.cjs +2 -0
- package/dist/impl-K7CHXRVJ.cjs.map +1 -0
- package/dist/impl-NFRFFLXM.cjs +2 -0
- package/dist/impl-NFRFFLXM.cjs.map +1 -0
- package/dist/impl-NIMVACZO.cjs +2 -0
- package/dist/impl-NIMVACZO.cjs.map +1 -0
- package/dist/impl-OBZFKR4D.cjs +2 -0
- package/dist/impl-OBZFKR4D.cjs.map +1 -0
- package/dist/impl-P7P4PHKK.cjs +2 -0
- package/dist/impl-P7P4PHKK.cjs.map +1 -0
- package/dist/impl-PKVWUYYX.cjs +2 -0
- package/dist/impl-PKVWUYYX.cjs.map +1 -0
- package/dist/impl-PUU55WCF.cjs +2 -0
- package/dist/impl-PUU55WCF.cjs.map +1 -0
- package/dist/impl-QTYOX6E5.cjs +2 -0
- package/dist/impl-QTYOX6E5.cjs.map +1 -0
- package/dist/impl-RNWZPIFE.cjs +2 -0
- package/dist/impl-RNWZPIFE.cjs.map +1 -0
- package/dist/impl-S3OTWWYU.cjs +6 -0
- package/dist/impl-S3OTWWYU.cjs.map +1 -0
- package/dist/impl-TFECR52S.cjs +2 -0
- package/dist/impl-TFECR52S.cjs.map +1 -0
- package/dist/impl-VBCRH4YN.cjs +2 -0
- package/dist/impl-VBCRH4YN.cjs.map +1 -0
- package/dist/impl-W5XYDQXZ.cjs +6 -0
- package/dist/{impl-CCUCFOCW.js.map → impl-W5XYDQXZ.cjs.map} +1 -1
- package/dist/impl-WBDBDZHE.cjs +2 -0
- package/dist/impl-WBDBDZHE.cjs.map +1 -0
- package/dist/impl-WDYARUUL.cjs +7 -0
- package/dist/impl-WDYARUUL.cjs.map +1 -0
- package/dist/impl-WJ7VUNYC.cjs +2 -0
- package/dist/impl-WJ7VUNYC.cjs.map +1 -0
- package/dist/impl-WMHBCVAN.cjs +2 -0
- package/dist/impl-WMHBCVAN.cjs.map +1 -0
- package/dist/impl-WYJHZILF.cjs +9 -0
- package/dist/impl-WYJHZILF.cjs.map +1 -0
- package/dist/impl-ZBKQ6GRT.cjs +2 -0
- package/dist/impl-ZBKQ6GRT.cjs.map +1 -0
- package/dist/impl-ZSFEQ5UA.cjs +4 -0
- package/dist/impl-ZSFEQ5UA.cjs.map +1 -0
- package/dist/index.cjs +5 -0
- package/dist/index.cjs.map +1 -0
- package/dist/{index.d.ts → index.d.cts} +1 -1
- package/package.json +49 -45
- package/dist/bin/bash-complete.js +0 -4
- package/dist/bin/bash-complete.js.map +0 -1
- package/dist/bin/cli.js +0 -3
- package/dist/bin/cli.js.map +0 -1
- package/dist/bin/deprecated-command.js +0 -7
- package/dist/bin/deprecated-command.js.map +0 -1
- package/dist/chunk-24SSWBXM.js +0 -4
- package/dist/chunk-24SSWBXM.js.map +0 -1
- package/dist/chunk-347UQP43.js +0 -2
- package/dist/chunk-347UQP43.js.map +0 -1
- package/dist/chunk-43JWXG77.js +0 -2
- package/dist/chunk-43JWXG77.js.map +0 -1
- package/dist/chunk-4GLITB3Y.js +0 -2
- package/dist/chunk-4GLITB3Y.js.map +0 -1
- package/dist/chunk-6P4FW6XR.js +0 -3
- package/dist/chunk-6P4FW6XR.js.map +0 -1
- package/dist/chunk-72U6ETHG.js +0 -2
- package/dist/chunk-72U6ETHG.js.map +0 -1
- package/dist/chunk-7QHA6ZIV.js +0 -2
- package/dist/chunk-7QHA6ZIV.js.map +0 -1
- package/dist/chunk-ARVEJERC.js +0 -2
- package/dist/chunk-ARVEJERC.js.map +0 -1
- package/dist/chunk-CBAHSBSW.js +0 -2
- package/dist/chunk-CBAHSBSW.js.map +0 -1
- package/dist/chunk-HH2PQ3PQ.js +0 -2
- package/dist/chunk-HH2PQ3PQ.js.map +0 -1
- package/dist/chunk-INLBXSQE.js +0 -9
- package/dist/chunk-INLBXSQE.js.map +0 -1
- package/dist/chunk-KRN6Q433.js +0 -75
- package/dist/chunk-KRN6Q433.js.map +0 -1
- package/dist/chunk-L5ULN3IT.js +0 -2
- package/dist/chunk-L5ULN3IT.js.map +0 -1
- package/dist/chunk-L7ZIX4SU.js +0 -2
- package/dist/chunk-L7ZIX4SU.js.map +0 -1
- package/dist/chunk-LAYHULHH.js +0 -2
- package/dist/chunk-LAYHULHH.js.map +0 -1
- package/dist/chunk-MA4JWWRO.js +0 -6
- package/dist/chunk-MA4JWWRO.js.map +0 -1
- package/dist/chunk-MVDOKJ6J.js +0 -2
- package/dist/chunk-MVDOKJ6J.js.map +0 -1
- package/dist/chunk-OEB7WG3G.js +0 -4
- package/dist/chunk-OEB7WG3G.js.map +0 -1
- package/dist/chunk-SF46ZLPT.js +0 -2
- package/dist/chunk-SF46ZLPT.js.map +0 -1
- package/dist/chunk-TDBKATQK.js +0 -2831
- package/dist/chunk-TDBKATQK.js.map +0 -1
- package/dist/chunk-WSDWILYI.js +0 -2
- package/dist/chunk-WSDWILYI.js.map +0 -1
- package/dist/chunk-XNR74SBS.js +0 -12
- package/dist/chunk-XNR74SBS.js.map +0 -1
- package/dist/chunk-ZLRUIEVQ.js +0 -94
- package/dist/chunk-ZLRUIEVQ.js.map +0 -1
- package/dist/chunk-ZTD7APNF.js +0 -2
- package/dist/chunk-ZTD7APNF.js.map +0 -1
- package/dist/impl-25VWUB6L.js +0 -2
- package/dist/impl-25VWUB6L.js.map +0 -1
- package/dist/impl-3M5R6G5M.js +0 -6
- package/dist/impl-3M5R6G5M.js.map +0 -1
- package/dist/impl-5OEPVWPL.js +0 -2
- package/dist/impl-5OEPVWPL.js.map +0 -1
- package/dist/impl-5YV7K446.js +0 -2
- package/dist/impl-5YV7K446.js.map +0 -1
- package/dist/impl-AFRHPZGF.js +0 -2
- package/dist/impl-AFRHPZGF.js.map +0 -1
- package/dist/impl-CCUCFOCW.js +0 -6
- package/dist/impl-E36SWF4Z.js +0 -2
- package/dist/impl-E36SWF4Z.js.map +0 -1
- package/dist/impl-E5WXNV47.js +0 -2
- package/dist/impl-E5WXNV47.js.map +0 -1
- package/dist/impl-EVICJMI3.js +0 -2
- package/dist/impl-EVICJMI3.js.map +0 -1
- package/dist/impl-G5TGSB4H.js +0 -2
- package/dist/impl-G5TGSB4H.js.map +0 -1
- package/dist/impl-GNG2DOKG.js +0 -2
- package/dist/impl-GNG2DOKG.js.map +0 -1
- package/dist/impl-GNSHZ3OL.js +0 -2
- package/dist/impl-GNSHZ3OL.js.map +0 -1
- package/dist/impl-GPCURY4M.js +0 -7
- package/dist/impl-GPCURY4M.js.map +0 -1
- package/dist/impl-GZRQOFY6.js +0 -2
- package/dist/impl-GZRQOFY6.js.map +0 -1
- package/dist/impl-HEC3SVYP.js +0 -2
- package/dist/impl-HEC3SVYP.js.map +0 -1
- package/dist/impl-HH24GIMG.js +0 -2
- package/dist/impl-HH24GIMG.js.map +0 -1
- package/dist/impl-I24OLEN5.js +0 -2
- package/dist/impl-I24OLEN5.js.map +0 -1
- package/dist/impl-IAXNYDJT.js +0 -2
- package/dist/impl-IAXNYDJT.js.map +0 -1
- package/dist/impl-J33PI3PK.js +0 -2
- package/dist/impl-J33PI3PK.js.map +0 -1
- package/dist/impl-JZDUGI7W.js +0 -2
- package/dist/impl-JZDUGI7W.js.map +0 -1
- package/dist/impl-LZ3HI26W.js +0 -4
- package/dist/impl-LZ3HI26W.js.map +0 -1
- package/dist/impl-MEDPDKAE.js +0 -2
- package/dist/impl-MEDPDKAE.js.map +0 -1
- package/dist/impl-MLS6TI7N.js +0 -2
- package/dist/impl-MLS6TI7N.js.map +0 -1
- package/dist/impl-NI7KSBSS.js +0 -2
- package/dist/impl-NI7KSBSS.js.map +0 -1
- package/dist/impl-OM6EKANE.js +0 -9
- package/dist/impl-OM6EKANE.js.map +0 -1
- package/dist/impl-T4WDJSWZ.js +0 -2
- package/dist/impl-T4WDJSWZ.js.map +0 -1
- package/dist/impl-U37YTCPW.js +0 -2
- package/dist/impl-U37YTCPW.js.map +0 -1
- package/dist/impl-U5555HGJ.js +0 -12
- package/dist/impl-U5555HGJ.js.map +0 -1
- package/dist/impl-UHFSVVIS.js +0 -6
- package/dist/impl-UHFSVVIS.js.map +0 -1
- package/dist/impl-UIVTSO57.js +0 -2
- package/dist/impl-UIVTSO57.js.map +0 -1
- package/dist/impl-UQYL5PXR.js +0 -2
- package/dist/impl-UQYL5PXR.js.map +0 -1
- package/dist/impl-V5QTKTU4.js +0 -2
- package/dist/impl-V5QTKTU4.js.map +0 -1
- package/dist/impl-WDPWOOFV.js +0 -2
- package/dist/impl-WDPWOOFV.js.map +0 -1
- package/dist/impl-WZAF2LD3.js +0 -2
- package/dist/impl-WZAF2LD3.js.map +0 -1
- package/dist/impl-XF26H3HG.js +0 -2
- package/dist/impl-XF26H3HG.js.map +0 -1
- package/dist/impl-XQY2Q5R6.js +0 -2
- package/dist/impl-XQY2Q5R6.js.map +0 -1
- package/dist/impl-YB2LON7S.js +0 -2
- package/dist/impl-YB2LON7S.js.map +0 -1
- package/dist/impl-YNGQIWW7.js +0 -2
- package/dist/impl-YNGQIWW7.js.map +0 -1
- package/dist/impl-ZA3PKNQN.js +0 -2
- package/dist/impl-ZA3PKNQN.js.map +0 -1
- package/dist/index.js +0 -5
- package/dist/index.js.map +0 -1
- /package/dist/bin/{bash-complete.d.ts → bash-complete.d.cts} +0 -0
- /package/dist/bin/{cli.d.ts → cli.d.cts} +0 -0
- /package/dist/bin/{deprecated-command.d.ts → deprecated-command.d.cts} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/consent/upload-preferences/impl.ts","../src/lib/preference-management/uploadPreferenceManagementPreferencesInteractive.ts","../src/lib/preference-management/parsePreferenceManagementCsv.ts","../src/lib/preference-management/getPreferencesForIdentifiers.ts","../src/lib/preference-management/getPreferenceUpdatesFromRow.ts","../src/lib/preference-management/parsePreferenceTimestampsFromCsv.ts","../src/lib/preference-management/parsePreferenceIdentifiersFromCsv.ts","../src/lib/preference-management/parsePreferenceAndPurposeValuesFromCsv.ts","../src/lib/preference-management/checkIfPendingPreferenceUpdatesAreNoOp.ts","../src/lib/preference-management/checkIfPendingPreferenceUpdatesCauseConflict.ts","../src/lib/preference-management/codecs.ts"],"sourcesContent":["import type { LocalContext } from '@/context';\nimport colors from 'colors';\n\nimport { logger } from '@/logger';\nimport { uploadPreferenceManagementPreferencesInteractive } from '@/lib/preference-management';\nimport { splitCsvToList } from '@/lib/requests';\nimport { readdirSync } from 'fs';\nimport { map } from '@/lib/bluebird-replace';\nimport { basename, join } from 'path';\n\ninterface UploadPreferencesCommandFlags {\n auth: string;\n partition: string;\n sombraAuth?: string;\n consentUrl: 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 consentUrl,\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(\n 'Cannot provide both a directory and a file. Please provide only one.',\n ),\n );\n 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 process.exit(1);\n }\n\n const files: string[] = [];\n\n if (directory) {\n try {\n const filesInDirectory = readdirSync(directory);\n const csvFiles = filesInDirectory.filter((file) => file.endsWith('.csv'));\n\n if (csvFiles.length === 0) {\n logger.error(\n colors.red(`No CSV files found in directory: ${directory}`),\n );\n 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 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 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 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(\n colors.bgYellow(\n `Skipping existing record check: ${skipExistingRecordCheck}`,\n ),\n );\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: consentUrl,\n skipConflictUpdates,\n skipWorkflowTriggers,\n skipExistingRecordCheck,\n isSilent,\n dryRun,\n attributes: splitCsvToList(attributes),\n forceTriggerWorkflows,\n });\n },\n { concurrency },\n );\n}\n","import {\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllPurposes,\n fetchAllPreferenceTopics,\n PreferenceTopic,\n Purpose,\n} from '../graphql';\nimport colors from 'colors';\nimport { map } from '@/lib/bluebird-replace';\nimport { chunk } from 'lodash-es';\nimport { DEFAULT_TRANSCEND_CONSENT_API } from '../../constants';\nimport { logger } from '../../logger';\nimport cliProgress from 'cli-progress';\nimport { parseAttributesFromString } from '../requests';\nimport { PersistedState } from '@transcend-io/persisted-state';\nimport { parsePreferenceManagementCsvWithCache } from './parsePreferenceManagementCsv';\nimport { PreferenceState } from './codecs';\nimport { PreferenceUpdateItem } from '@transcend-io/privacy-types';\nimport { apply } from '@transcend-io/type-utils';\nimport { NONE_PREFERENCE_MAP } from './parsePreferenceTimestampsFromCsv';\nimport { getPreferenceUpdatesFromRow } from './getPreferenceUpdatesFromRow';\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 = DEFAULT_TRANSCEND_CONSENT_API,\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 `${\n Object.values(failingRequests).length\n } failing requests to be retried\\n` +\n `${\n Object.values(pendingRequests).length\n } pending requests to be processed\\n` +\n `The following files are stored in cache and will be used:\\n${Object.keys(\n fileMetadata,\n )\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, sombraAuth),\n // get all purposes and topics\n forceTriggerWorkflows\n ? Promise.resolve([] as Purpose[])\n : fetchAllPurposes(client),\n forceTriggerWorkflows\n ? Promise.resolve([] as PreferenceTopic[])\n : fetchAllPreferenceTopics(client),\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 ${\n Object.entries(metadata.pendingSafeUpdates).length\n } safe updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.pendingConflictUpdates).length\n } conflict updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.skippedUpdates).length\n } skipped updates in ${file}`,\n ),\n );\n\n // Update either safe updates only or safe + conflict\n Object.entries({\n ...metadata.pendingSafeUpdates,\n ...(skipConflictUpdates\n ? {}\n : 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 },\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 ${\n Object.values(pendingUpdates).length\n } 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(\n {},\n cliProgress.Presets.shades_classic,\n );\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 forceTriggerWorkflows,\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 (e) {\n // continue\n }\n logger.error(\n colors.red(\n `Failed to upload ${\n currentChunk.length\n } 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 \"${\n totalTime / 1000\n }\" seconds!`,\n ),\n );\n}\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport type { Got } from 'got';\nimport { keyBy } from 'lodash-es';\nimport * as t from 'io-ts';\nimport colors from 'colors';\nimport { FileMetadataState, PreferenceState } from './codecs';\nimport { logger } from '../../logger';\nimport { readCsv } from '../requests';\nimport { getPreferencesForIdentifiers } from './getPreferencesForIdentifiers';\nimport { PreferenceTopic } from '../graphql';\nimport { getPreferenceUpdatesFromRow } from './getPreferenceUpdatesFromRow';\nimport { parsePreferenceTimestampsFromCsv } from './parsePreferenceTimestampsFromCsv';\nimport { parsePreferenceIdentifiersFromCsv } from './parsePreferenceIdentifiersFromCsv';\nimport { parsePreferenceAndPurposeValuesFromCsv } from './parsePreferenceAndPurposeValuesFromCsv';\nimport { checkIfPendingPreferenceUpdatesAreNoOp } from './checkIfPendingPreferenceUpdatesAreNoOp';\nimport { checkIfPendingPreferenceUpdatesCauseConflict } from './checkIfPendingPreferenceUpdatesCauseConflict';\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 /** Wheather 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(\n preferences,\n currentState,\n );\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(\n preferences,\n currentState,\n );\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(\n preferences,\n currentState,\n {\n preferenceTopics,\n purposeSlugs,\n forceTriggerWorkflows,\n },\n );\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Grab existing preference store records\n const identifiers = preferences.map(\n (pref) => pref[currentState.identifierColumn!],\n );\n const existingConsentRecords = skipExistingRecordCheck\n ? []\n : await getPreferencesForIdentifiers(sombra, {\n identifiers: identifiers.map((x) => ({ value: x })),\n partitionKey,\n });\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(\n colors.green(\n `Successfully pre-processed file: \"${file}\" in ${(t1 - t0) / 1000}s`,\n ),\n );\n}\n","import { PreferenceQueryResponseItem } from '@transcend-io/privacy-types';\nimport type { Got } from 'got';\nimport colors from 'colors';\nimport cliProgress from 'cli-progress';\nimport { chunk } from 'lodash-es';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport * as t from 'io-ts';\nimport { map } from '@/lib/bluebird-replace';\nimport { logger } from '../../logger';\n\nconst PreferenceRecordsQueryResponse = t.intersection([\n t.type({\n nodes: t.array(PreferenceQueryResponseItem),\n }),\n t.partial({\n /** The base64 encoded(PreferenceStorePaginationKey) cursor for pagination */\n cursor: t.string,\n }),\n]);\n\nconst MSGS = [\n 'ENOTFOUND',\n 'ETIMEDOUT',\n '504 Gateway Time-out',\n 'Task timed out after',\n];\n\n/**\n * Grab the current consent preference values for a list of identifiers\n *\n * @param sombra - Backend to make API call to\n * @param options - Options\n * @returns Plaintext context information\n */\nexport async function getPreferencesForIdentifiers(\n sombra: Got,\n {\n identifiers,\n partitionKey,\n skipLogging = false,\n }: {\n /** The list of identifiers to look up */\n identifiers: {\n /** The value of the identifier */\n value: string;\n }[];\n /** The partition key to look up */\n partitionKey: string;\n /** Whether to skip logging */\n skipLogging?: boolean;\n },\n): Promise<PreferenceQueryResponseItem[]> {\n const results: PreferenceQueryResponseItem[] = [];\n const groupedIdentifiers = chunk(identifiers, 100);\n\n // create a new progress bar instance and use shades_classic theme\n const t0 = new Date().getTime();\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n if (!skipLogging) {\n progressBar.start(identifiers.length, 0);\n }\n\n let total = 0;\n await map(\n groupedIdentifiers,\n async (group) => {\n // Make the request with retry logic\n let attempts = 0;\n const maxAttempts = 3;\n while (attempts < maxAttempts) {\n try {\n const rawResult = await sombra\n .post(`v1/preferences/${partitionKey}/query`, {\n json: {\n filter: {\n identifiers: group,\n },\n limit: group.length,\n },\n })\n .json();\n\n const result = decodeCodec(PreferenceRecordsQueryResponse, rawResult);\n results.push(...result.nodes);\n total += group.length;\n progressBar.update(total);\n break; // Exit loop if successful\n } catch (err) {\n attempts += 1;\n const msg = err?.response?.body || err?.message || '';\n if (\n attempts >= maxAttempts ||\n !MSGS.some((errorMessage) => msg.includes(errorMessage))\n ) {\n throw new Error(\n `Received an error from server after ${attempts} attempts: ${msg}`,\n );\n }\n\n logger.warn(\n colors.yellow(\n `[RETRYING FAILED REQUEST - Attempt ${attempts}] ` +\n `Failed to fetch ${group.length} user preferences from partition ${partitionKey}: ${msg}`,\n ),\n );\n }\n }\n },\n {\n concurrency: 40,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n if (!skipLogging) {\n // Log completion time\n logger.info(\n colors.green(`Completed download in \"${totalTime / 1000}\" seconds.`),\n );\n }\n\n return results;\n}\n","import {\n PreferenceStorePurposeResponse,\n PreferenceTopicType,\n} from '@transcend-io/privacy-types';\nimport { PurposeRowMapping } from './codecs';\nimport { apply } from '@transcend-io/type-utils';\nimport { PreferenceTopic } from '../graphql';\nimport { splitCsvToList } from '../requests';\n\n/**\n * Parse an arbitrary object to the Transcend PUT /v1/preference update shape\n * by using a mapping of column names to purpose/preference slugs.\n *\n * columnToPurposeName looks like:\n * {\n * 'my_purpose': 'Marketing',\n * 'has_topic_1': 'Marketing->BooleanPreference1',\n * 'has_topic_2': 'Marketing->BooleanPreference2'\n * }\n *\n * row looks like:\n * {\n * 'my_purpose': 'true',\n * 'has_topic_1': 'true',\n * 'has_topic_2': 'false'\n * }\n *\n * @param options - Options\n * @returns The parsed row\n */\nexport function getPreferenceUpdatesFromRow({\n row,\n columnToPurposeName,\n purposeSlugs,\n preferenceTopics,\n}: {\n /** Row to parse */\n row: Record<string, string>;\n /** Mapping from column name ot row */\n columnToPurposeName: Record<string, PurposeRowMapping>;\n /** The set of allowed purpose slugs */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n}): {\n [k in string]: Omit<PreferenceStorePurposeResponse, 'purpose'>;\n} {\n // Create a result object to store the parsed preferences\n const result: {\n [k in string]: Partial<PreferenceStorePurposeResponse>;\n } = {};\n\n // Iterate over each column and map to the purpose or preference\n Object.entries(columnToPurposeName).forEach(\n ([columnName, { purpose, preference, valueMapping }]) => {\n // Ensure the purpose is valid\n if (!purposeSlugs.includes(purpose)) {\n throw new Error(\n `Invalid purpose slug: ${purpose}, expected: ${purposeSlugs.join(\n ', ',\n )}`,\n );\n }\n\n // CHeck if parsing a preference or just the top level purpose\n if (preference) {\n const preferenceTopic = preferenceTopics.find(\n (x) => x.slug === preference && x.purpose.trackingType === purpose,\n );\n if (!preferenceTopic) {\n const allowedTopics = preferenceTopics\n .filter((x) => x.purpose.trackingType === purpose)\n .map((x) => x.slug);\n throw new Error(\n `Invalid preference slug: ${preference} for purpose: ${purpose}. ` +\n `Allowed preference slugs for purpose are: ${allowedTopics.join(\n ',',\n )}`,\n );\n }\n\n // If parsing preferences, default to an empty array\n if (!result[purpose]) {\n result[purpose] = {\n preferences: [],\n };\n }\n if (!result[purpose].preferences) {\n result[purpose].preferences = [];\n }\n\n // The value to parse\n const rawValue = row[columnName];\n const rawMapping = valueMapping[rawValue];\n const trimmedMapping =\n typeof rawMapping === 'string' ? rawMapping.trim() || null : null;\n\n // handle each type of preference\n switch (preferenceTopic.type) {\n case PreferenceTopicType.Boolean:\n if (typeof rawMapping !== 'boolean') {\n throw new Error(\n `Invalid value for boolean preference: ${preference}, expected boolean, got: ${rawValue}`,\n );\n }\n result[purpose].preferences!.push({\n topic: preference,\n choice: {\n booleanValue: rawMapping,\n },\n });\n break;\n case PreferenceTopicType.Select:\n if (typeof rawMapping !== 'string' && rawMapping !== null) {\n throw new Error(\n `Invalid value for select preference: ${preference}, expected string or null, got: ${rawValue}`,\n );\n }\n\n if (\n trimmedMapping &&\n !preferenceTopic.preferenceOptionValues\n .map(({ slug }) => slug)\n .includes(trimmedMapping)\n ) {\n throw new Error(\n `Invalid value for select preference: ${preference}, expected one of: ` +\n `${preferenceTopic.preferenceOptionValues\n .map(({ slug }) => slug)\n .join(', ')}, got: ${rawValue}`,\n );\n }\n\n // Update preferences\n result[purpose].preferences!.push({\n topic: preference,\n choice: {\n selectValue: trimmedMapping,\n },\n });\n break;\n case PreferenceTopicType.MultiSelect:\n if (typeof rawValue !== 'string') {\n throw new Error(\n `Invalid value for multi select preference: ${preference}, expected string, got: ${rawValue}`,\n );\n }\n // Update preferences\n result[purpose].preferences!.push({\n topic: preference,\n choice: {\n selectValues: splitCsvToList(rawValue)\n .map((val) => {\n const result = valueMapping[val];\n if (typeof result !== 'string') {\n throw new Error(\n `Invalid value for multi select preference: ${preference}, ` +\n `expected one of: ${preferenceTopic.preferenceOptionValues\n .map(({ slug }) => slug)\n .join(', ')}, got: ${val}`,\n );\n }\n return result;\n })\n .sort((a, b) => a.localeCompare(b)),\n },\n });\n break;\n default:\n throw new Error(`Unknown preference type: ${preferenceTopic.type}`);\n }\n } else if (!result[purpose]) {\n // Handle updating top level purpose for the first time\n result[purpose] = {\n enabled: valueMapping[row[columnName]] === true,\n };\n } else {\n // Handle updating top level purpose but preserve preference updates\n result[purpose].enabled = valueMapping[row[columnName]] === true;\n }\n },\n );\n\n // Ensure that enabled is provided\n return apply(result, (x, purposeName) => {\n if (typeof x.enabled !== 'boolean') {\n throw new Error(\n `No mapping provided for purpose.enabled=true/false value: ${purposeName}`,\n );\n }\n return {\n ...x,\n enabled: x.enabled!,\n };\n });\n}\n","import { uniq, difference } from 'lodash-es';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { FileMetadataState } from './codecs';\nimport { logger } from '../../logger';\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:\n 'Choose the column that will be used as the timestamp of last preference update',\n type: 'list',\n default:\n remainingColumnsForTimestamp.find((col) =>\n col.toLowerCase().includes('date'),\n ) ||\n remainingColumnsForTimestamp.find((col) =>\n col.toLowerCase().includes('time'),\n ) ||\n remainingColumnsForTimestamp[0],\n choices: [...remainingColumnsForTimestamp, NONE_PREFERENCE_MAP],\n },\n ]);\n currentState.timestampColum = timestampName;\n }\n logger.info(\n colors.magenta(`Using timestamp column \"${currentState.timestampColum}\"`),\n );\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 );\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 { uniq, groupBy, difference } from 'lodash-es';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { FileMetadataState } from './codecs';\nimport { logger } from '../../logger';\nimport { inquirerConfirmBoolean } from '../helpers';\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) =>\n col.toLowerCase().includes('email'),\n ) || remainingColumnsForIdentifier[0],\n choices: remainingColumnsForIdentifier,\n },\n ]);\n currentState.identifierColumn = identifierName;\n }\n logger.info(\n colors.magenta(\n `Using identifier column \"${currentState.identifierColumn}\"`,\n ),\n );\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 ', ',\n )}`;\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(\n (pref) => pref[currentState.identifierColumn!],\n );\n logger.info(\n colors.yellow(\n `Skipped ${previous - preferences.length} rows missing an identifier`,\n ),\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(\n ([, rows]) => rows.length > 1,\n );\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 { uniq, difference } from 'lodash-es';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { FileMetadataState } from './codecs';\nimport { logger } from '../../logger';\nimport { mapSeries } from '@/lib/bluebird-replace';\nimport { PreferenceTopic } from '../graphql';\nimport { PreferenceTopicType } from '@transcend-io/privacy-types';\nimport { splitCsvToList } from '../requests';\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(\n `Column \"${col}\" is associated with purpose \"${purposeMapping.purpose}\"`,\n ),\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(\n (x) => x.slug === purposeMapping.preference,\n );\n if (!preferenceTopic) {\n logger.error(\n colors.red(\n `Preference topic \"${purposeMapping.preference}\" not found`,\n ),\n );\n return;\n }\n const preferenceOptions = preferenceTopic.preferenceOptionValues.map(\n ({ slug }) => slug,\n );\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(\n `Unknown preference topic type: ${preferenceTopic.type}`,\n );\n }\n });\n\n currentState.columnToPurposeName[col] = purposeMapping;\n });\n\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import {\n PreferenceQueryResponseItem,\n PreferenceStorePurposeResponse,\n PreferenceTopicType,\n} from '@transcend-io/privacy-types';\nimport { PreferenceTopic } from '../graphql';\n\n/**\n * Check if the pending set of updates are exactly the same as the current consent record.\n *\n * @param options - Options\n * @returns Whether the pending updates already exist in the preference store\n */\nexport function checkIfPendingPreferenceUpdatesAreNoOp({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n}: {\n /** The current consent record */\n currentConsentRecord: PreferenceQueryResponseItem;\n /** The pending updates */\n pendingUpdates: {\n [purposeName in string]: Omit<PreferenceStorePurposeResponse, 'purpose'>;\n };\n /** The preference topic configurations */\n preferenceTopics: PreferenceTopic[];\n}): boolean {\n // Check each update\n return Object.entries(pendingUpdates).every(\n ([purposeName, { preferences = [], enabled }]) => {\n // Ensure the purpose exists\n const currentPurpose = currentConsentRecord.purposes.find(\n (existingPurpose) => existingPurpose.purpose === purposeName,\n );\n\n // Ensure purpose.enabled is in sync\n // Also false if the purpose does not exist\n const enabledIsInSync =\n !!currentPurpose && currentPurpose.enabled === enabled;\n if (!enabledIsInSync) {\n return false;\n }\n\n // Compare the preferences are in sync\n return preferences.every(\n ({ topic, choice }) =>\n // ensure preferences exist on record\n currentPurpose.preferences &&\n currentPurpose.preferences.find((existingPreference) => {\n // find matching topic\n if (existingPreference.topic !== topic) {\n return false;\n }\n\n // Determine type of preference topic\n const preferenceTopic = preferenceTopics.find(\n (x) => x.slug === topic && x.purpose.trackingType === purposeName,\n );\n if (!preferenceTopic) {\n throw new Error(`Could not find preference topic for ${topic}`);\n }\n\n // Handle comparison based on type\n switch (preferenceTopic.type) {\n case PreferenceTopicType.Boolean:\n return (\n existingPreference.choice.booleanValue === choice.booleanValue\n );\n case PreferenceTopicType.Select:\n return (\n existingPreference.choice.selectValue === choice.selectValue\n );\n case PreferenceTopicType.MultiSelect:\n // eslint-disable-next-line no-case-declarations\n const sortedCurrentValues = (\n existingPreference.choice.selectValues || []\n ).sort();\n // eslint-disable-next-line no-case-declarations\n const sortedNewValues = (choice.selectValues || []).sort();\n return (\n sortedCurrentValues.length === sortedNewValues.length &&\n sortedCurrentValues.every((x, i) => x === sortedNewValues[i])\n );\n default:\n throw new Error(\n `Unknown preference topic type: ${preferenceTopic.type}`,\n );\n }\n }),\n );\n },\n );\n}\n","import {\n PreferenceQueryResponseItem,\n PreferenceStorePurposeResponse,\n PreferenceTopicType,\n} from '@transcend-io/privacy-types';\nimport { PreferenceTopic } from '../graphql';\n\n/**\n * Check if the pending set of updates will result in a change of\n * value to an existing purpose or preference in the preference store.\n *\n * @param options - Options\n * @returns True if conflict, false if no conflict and just adding new data for first time\n */\nexport function checkIfPendingPreferenceUpdatesCauseConflict({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n}: {\n /** The current consent record */\n currentConsentRecord: PreferenceQueryResponseItem;\n /** The pending updates */\n pendingUpdates: {\n [purposeName in string]: Omit<PreferenceStorePurposeResponse, 'purpose'>;\n };\n /** The preference topic configurations */\n preferenceTopics: PreferenceTopic[];\n}): boolean {\n // Check if any update has conflict\n return !!Object.entries(pendingUpdates).find(\n ([purposeName, { preferences = [], enabled }]) => {\n // Ensure the purpose exists\n const currentPurpose = currentConsentRecord.purposes.find(\n (existingPurpose) => existingPurpose.purpose === purposeName,\n );\n\n // If no purpose exists, then it is not a conflict\n if (!currentPurpose) {\n return false;\n }\n\n // If purpose.enabled value is off, this is a conflict\n if (currentPurpose.enabled !== enabled) {\n return true;\n }\n\n // Check if any preferences are out of sync\n return !!preferences.find(({ topic, choice }) => {\n // find matching topic\n const currentPreference = (currentPurpose.preferences || []).find(\n (existingPreference) => existingPreference.topic === topic,\n );\n\n // if no topic exists, no conflict\n if (!currentPreference) {\n return false;\n }\n\n // Determine type of preference topic\n const preferenceTopic = preferenceTopics.find(\n (x) => x.slug === topic && x.purpose.trackingType === purposeName,\n );\n if (!preferenceTopic) {\n throw new Error(`Could not find preference topic for ${topic}`);\n }\n\n // Handle comparison based on type\n switch (preferenceTopic.type) {\n case PreferenceTopicType.Boolean:\n return (\n currentPreference.choice.booleanValue !== choice.booleanValue\n );\n case PreferenceTopicType.Select:\n return currentPreference.choice.selectValue !== choice.selectValue;\n case PreferenceTopicType.MultiSelect:\n // eslint-disable-next-line no-case-declarations\n const sortedCurrentValues = (\n currentPreference.choice.selectValues || []\n ).sort();\n // eslint-disable-next-line no-case-declarations\n const sortedNewValues = (choice.selectValues || []).sort();\n return (\n sortedCurrentValues.length !== sortedNewValues.length ||\n !sortedCurrentValues.every((x, i) => x === sortedNewValues[i])\n );\n default:\n throw new Error(\n `Unknown preference topic type: ${preferenceTopic.type}`,\n );\n }\n });\n },\n );\n}\n","import {\n PreferenceQueryResponseItem,\n PreferenceUpdateItem,\n} from '@transcend-io/privacy-types';\nimport * as t from 'io-ts';\n\nexport const PurposeRowMapping = t.type({\n /**\n * The slug or trackingType of the purpose to map to\n *\n * e.g. `Marketing`\n */\n purpose: t.string,\n /**\n * If the column maps to a preference instead of a purpose\n * this is the slug of the purpose.\n *\n * null value indicates that this column maps to the true/false\n * value of the purpose\n */\n preference: t.union([t.string, t.null]),\n /**\n * The mapping between each row value and purpose/preference value.\n *\n * e.g. for a boolean preference or purpose\n * {\n * 'true': true,\n * 'false': false,\n * '': true,\n * }\n *\n * or for a single or multi select preference\n * {\n * '': true,\n * 'value1': 'Value1',\n * 'value2': 'Value2',\n * }\n */\n valueMapping: t.record(t.string, t.union([t.string, t.boolean, t.null])),\n});\n\n/** Override type */\nexport type PurposeRowMapping = t.TypeOf<typeof PurposeRowMapping>;\n\nexport const FileMetadataState = t.intersection([\n t.type({\n /**\n * Definition of how to map each column in the CSV to\n * the relevant purpose and preference definitions in transcend\n */\n columnToPurposeName: t.record(t.string, PurposeRowMapping),\n /** Last time the file was last parsed at */\n lastFetchedAt: t.string,\n /**\n * Mapping of userId to the rows in the file that need to be uploaded\n * These uploads are overwriting non-existent preferences and are safe\n */\n pendingSafeUpdates: t.record(t.string, t.record(t.string, t.string)),\n /**\n * Mapping of userId to the rows in the file that need to be uploaded\n * these records have conflicts with existing consent preferences\n */\n pendingConflictUpdates: t.record(\n t.string,\n t.type({\n record: PreferenceQueryResponseItem,\n row: t.record(t.string, t.string),\n }),\n ),\n /**\n * Mapping of userId to the rows in the file that can be skipped because\n * their preferences are already in the store\n */\n skippedUpdates: t.record(t.string, t.record(t.string, t.string)),\n }),\n t.partial({\n /** Determine which column name in file maps to consent record identifier to upload on */\n identifierColumn: t.string,\n /** Determine which column name in file maps to the timestamp */\n timestampColum: t.string,\n }),\n]);\n\n/** Override type */\nexport type FileMetadataState = t.TypeOf<typeof FileMetadataState>;\n\n/** Persist this data between runs of the script */\nexport const PreferenceState = t.type({\n /**\n * Store a cache of previous files read in\n */\n fileMetadata: t.record(t.string, FileMetadataState),\n /**\n * The set of successful uploads to Transcend\n * Mapping from userId to the upload metadata\n */\n failingUpdates: t.record(\n t.string,\n t.type({\n /** Time upload ran at */\n uploadedAt: t.string,\n /** Attempts to upload that resulted in an error */\n error: t.string,\n /** The update body */\n update: PreferenceUpdateItem,\n }),\n ),\n /**\n * The set of pending uploads to Transcend\n * Mapping from userId to the upload metadata\n */\n pendingUpdates: t.record(t.string, PreferenceUpdateItem),\n});\n\n/** Override type */\nexport type PreferenceState = t.TypeOf<typeof PreferenceState>;\n"],"mappings":"iXACA,OAAOA,MAAY,SCOnB,OAAOC,MAAY,SAEnB,OAAS,SAAAC,OAAa,YAGtB,OAAOC,OAAiB,eAExB,OAAS,kBAAAC,OAAsB,gCCb/B,OAAS,SAAAC,OAAa,YACtB,UAAYC,MAAO,QACnB,OAAOC,OAAY,SCJnB,OAAS,+BAAAC,OAAmC,8BAE5C,OAAOC,OAAY,SACnB,OAAOC,OAAiB,eACxB,OAAS,SAAAC,OAAa,YACtB,OAAS,eAAAC,OAAmB,2BAC5B,UAAYC,MAAO,QAInB,IAAMC,GAAmC,eAAa,CAClD,OAAK,CACL,MAAS,QAAMC,EAA2B,CAC5C,CAAC,EACC,UAAQ,CAER,OAAU,QACZ,CAAC,CACH,CAAC,EAEKC,GAAO,CACX,YACA,YACA,uBACA,sBACF,EASA,eAAsBC,GACpBC,EACA,CACE,YAAAC,EACA,aAAAC,EACA,YAAAC,EAAc,EAChB,EAWwC,CACxC,IAAMC,EAAyC,CAAC,EAC1CC,EAAqBC,GAAML,EAAa,GAAG,EAG3CM,EAAK,IAAI,KAAK,EAAE,QAAQ,EACxBC,EAAc,IAAIC,GAAY,UAClC,CAAC,EACDA,GAAY,QAAQ,cACtB,EACKN,GACHK,EAAY,MAAMP,EAAY,OAAQ,CAAC,EAGzC,IAAIS,EAAQ,EACZ,MAAMC,EACJN,EACA,MAAOO,GAAU,CAEf,IAAIC,EAAW,EACTC,EAAc,EACpB,KAAOD,EAAWC,GAChB,GAAI,CACF,IAAMC,EAAY,MAAMf,EACrB,KAAK,kBAAkBE,CAAY,SAAU,CAC5C,KAAM,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,CAAI,CAAC,CAAC,CAC7D,OAASgB,EAAK,CACZL,EAAO,MAAMC,EAAO,IAAI,6BAA6BX,CAAS,EAAE,CAAC,EACjEU,EAAO,MAAMC,EAAO,IAAKI,EAAc,OAAO,CAAC,EAC/C,QAAQ,KAAK,CAAC,CAChB,KAEA,IAAI,CAEGhB,EAAK,SAAS,MAAM,IACvBW,EAAO,MAAMC,EAAO,IAAI,yBAAyB,CAAC,EAClD,QAAQ,KAAK,CAAC,GAEhBC,EAAM,KAAKb,CAAI,CACjB,OAASgB,EAAK,CACZL,EAAO,MAAMC,EAAO,IAAI,0BAA0BZ,CAAI,EAAE,CAAC,EACzDW,EAAO,MAAMC,EAAO,IAAKI,EAAc,OAAO,CAAC,EAC/C,QAAQ,KAAK,CAAC,CAChB,CAGFL,EAAO,KACLC,EAAO,MACL,cAAcC,EAAM,MAAM,6CAA6ChB,CAAS,EAClF,CACF,EACAc,EAAO,MAAM,qBAAqBE,EAAM,KAAK,IAAI,CAAC,EAAE,EAEhDV,GACFQ,EAAO,KACLC,EAAO,SACL,mCAAmCT,CAAuB,EAC5D,CACF,EAGF,MAAMc,EACJJ,EACA,MAAOK,GAAa,CAClB,IAAMC,EAAW1B,GAASyB,CAAQ,EAAE,QAAQ,OAAQ,EAAE,EACtD,MAAME,GAAiD,CACrD,gBAAiB1B,GAAKU,EAAgB,GAAGe,CAAQ,gBAAgB,EACjE,KAAAvB,EACA,WAAAE,EACA,KAAMoB,EACN,UAAArB,EACA,aAAcE,EACd,oBAAAQ,EACA,qBAAAF,EACA,wBAAAF,EACA,SAAAK,EACA,OAAAN,EACA,WAAYmB,EAAeZ,CAAU,EACrC,sBAAAH,CACF,CAAC,CACH,EACA,CAAE,YAAAI,CAAY,CAChB,CACF","names":["colors","colors","chunk","cliProgress","PersistedState","keyBy","t","colors","PreferenceQueryResponseItem","colors","cliProgress","chunk","decodeCodec","t","PreferenceRecordsQueryResponse","PreferenceQueryResponseItem","MSGS","getPreferencesForIdentifiers","sombra","identifiers","partitionKey","skipLogging","results","groupedIdentifiers","chunk","t0","progressBar","cliProgress","total","map","group","attempts","maxAttempts","rawResult","result","decodeCodec","err","msg","errorMessage","logger","colors","totalTime","PreferenceTopicType","apply","getPreferenceUpdatesFromRow","row","columnToPurposeName","purposeSlugs","preferenceTopics","result","columnName","purpose","preference","valueMapping","preferenceTopic","x","allowedTopics","rawValue","rawMapping","trimmedMapping","PreferenceTopicType","slug","splitCsvToList","val","a","b","apply","purposeName","uniq","difference","colors","inquirer","NONE_PREFERENCE_MAP","parsePreferenceTimestampsFromCsv","preferences","currentState","columnNames","uniq","x","remainingColumnsForTimestamp","difference","timestampName","inquirer","col","logger","colors","timestampColumnsMissing","pref","ind","uniq","groupBy","difference","colors","inquirer","parsePreferenceIdentifiersFromCsv","preferences","currentState","columnNames","uniq","x","remainingColumnsForIdentifier","difference","identifierName","inquirer","col","logger","colors","identifierColumnsMissing","pref","ind","msg","inquirerConfirmBoolean","previous","rowsByUserId","groupBy","duplicateIdentifiers","rows","userId","a","b","uniq","difference","colors","inquirer","PreferenceTopicType","parsePreferenceAndPurposeValuesFromCsv","preferences","currentState","purposeSlugs","preferenceTopics","forceTriggerWorkflows","columnNames","uniq","x","otherColumns","difference","purposeNames","mapSeries","col","uniqueValues","purposeMapping","logger","colors","purposeName","inquirer","purposeSlug","preferenceSlug","value","purposeValue","preferenceTopic","preferenceOptions","slug","PreferenceTopicType","preferenceValue","parsedValues","splitCsvToList","parsedValue","PreferenceTopicType","checkIfPendingPreferenceUpdatesAreNoOp","currentConsentRecord","pendingUpdates","preferenceTopics","purposeName","preferences","enabled","currentPurpose","existingPurpose","topic","choice","existingPreference","preferenceTopic","x","sortedCurrentValues","sortedNewValues","i","PreferenceTopicType","checkIfPendingPreferenceUpdatesCauseConflict","currentConsentRecord","pendingUpdates","preferenceTopics","purposeName","preferences","enabled","currentPurpose","existingPurpose","topic","choice","currentPreference","existingPreference","preferenceTopic","x","sortedCurrentValues","sortedNewValues","i","parsePreferenceManagementCsvWithCache","file","sombra","purposeSlugs","preferenceTopics","partitionKey","skipExistingRecordCheck","forceTriggerWorkflows","cache","t0","fileMetadata","logger","colors","preferences","readCsv","currentState","parsePreferenceTimestampsFromCsv","result","parsePreferenceIdentifiersFromCsv","parsePreferenceAndPurposeValuesFromCsv","identifiers","pref","existingConsentRecords","getPreferencesForIdentifiers","x","consentRecordByIdentifier","keyBy","userId","pendingUpdates","getPreferenceUpdatesFromRow","currentConsentRecord","checkIfPendingPreferenceUpdatesAreNoOp","checkIfPendingPreferenceUpdatesCauseConflict","t1","PreferenceQueryResponseItem","PreferenceUpdateItem","t","PurposeRowMapping","FileMetadataState","PreferenceState","apply","uploadPreferenceManagementPreferencesInteractive","auth","sombraAuth","receiptFilepath","file","partition","isSilent","dryRun","skipWorkflowTriggers","skipConflictUpdates","skipExistingRecordCheck","attributes","transcendUrl","DEFAULT_TRANSCEND_CONSENT_API","forceTriggerWorkflows","parsedAttributes","parseAttributesFromString","preferenceState","PersistedState","PreferenceState","failingRequests","pendingRequests","fileMetadata","logger","colors","x","client","buildTranscendGraphQLClient","sombra","purposes","preferenceTopics","createSombraGotInstance","fetchAllPurposes","fetchAllPreferenceTopics","parsePreferenceManagementCsvWithCache","pendingUpdates","metadata","apply","row","userId","update","timestamp","NONE_PREFERENCE_MAP","updates","getPreferenceUpdatesFromRow","purpose","value","t0","progressBar","cliProgress","total","updatesToRun","chunkedUpdates","chunk","map","currentChunk","err","parsed","failingUpdates","totalTime","readdirSync","basename","join","uploadPreferences","auth","partition","sombraAuth","consentUrl","file","directory","dryRun","skipExistingRecordCheck","receiptFileDir","skipWorkflowTriggers","forceTriggerWorkflows","skipConflictUpdates","isSilent","attributes","concurrency","logger","colors","files","csvFiles","readdirSync","err","map","filePath","fileName","uploadPreferenceManagementPreferencesInteractive","splitCsvToList"]}
|
package/dist/impl-UHFSVVIS.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{a as S}from"./chunk-L7ZIX4SU.js";import{a as A}from"./chunk-4GLITB3Y.js";import{d as b}from"./chunk-OEB7WG3G.js";import{b as v,c as C}from"./chunk-MVDOKJ6J.js";import"./chunk-LAYHULHH.js";import"./chunk-347UQP43.js";import{Nd as x,a as w,pe as T}from"./chunk-TDBKATQK.js";import{a as n}from"./chunk-43JWXG77.js";import{c as d}from"./chunk-L5ULN3IT.js";import"./chunk-SF46ZLPT.js";import"./chunk-ARVEJERC.js";import{existsSync as z,lstatSync as F}from"fs";import{join as L}from"path";import o from"colors";async function I({transcendUrl:i,auth:c,pageSize:h,publishToPrivacyCenter:y,contents:l,deleteExtraAttributeValues:m=!1,classifyService:f=!1}){let u=T(i,c);try{return!await x(l,u,{pageSize:h,publishToPrivacyCenter:y,classifyService:f,deleteExtraAttributeValues:m})}catch(t){return n.error(o.red(`An unexpected error occurred syncing the schema: ${t.message}`)),!1}}async function H({file:i="./transcend.yml",transcendUrl:c,auth:h,variables:y,pageSize:l,publishToPrivacyCenter:m,classifyService:f,deleteExtraAttributeValues:u}){let t=await v(h),N=A(y),p;if(Array.isArray(t)&&F(i).isDirectory()?p=C(i).map(e=>L(i,e)):p=i.split(","),p.length<1)throw new Error("No file specified!");let s=p.map(e=>{z(e)?n.info(o.magenta(`Reading file "${e}"...`)):(n.error(o.red(`The file path does not exist on disk: ${e}. You can specify the filepath using --file=./examples/transcend.yml`)),process.exit(1));try{let r=b(e,N);return n.info(o.green(`Successfully read in "${e}"`)),{content:r,name:e.split("/").pop().replace(".yml","")}}catch(r){n.error(o.red(`The shape of your yaml file is invalid with the following errors: ${r.message}`)),process.exit(1)}});if(typeof t=="string"){let[e,...r]=s.map(({content:g})=>g),$=S(e,...r);await I({transcendUrl:c,auth:t,contents:$,publishToPrivacyCenter:m,deleteExtraAttributeValues:u,pageSize:l,classifyService:!!f})||(n.info(o.red(`Sync encountered errors. View output above for more information, or check out ${d}`)),process.exit(1))}else{if(s.length!==1&&s.length!==t.length)throw new Error(`Expected list of yml files to be equal to the list of API keys.Got ${s.length} YML file${s.length===1?"":"s"} and ${t.length} API key${t.length===1?"":"s"}`);let e=[];await w(t,async(r,$)=>{let a=`[${$+1}/${t.length}][${r.organizationName}] `;n.info(o.magenta(`~~~
|
|
2
|
-
|
|
3
|
-
${a}Attempting to push configuration...
|
|
4
|
-
|
|
5
|
-
~~~`));let g=s.length===1?s[0].content:s.find(E=>E.name===r.organizationName)?.content;if(!g){n.error(o.red(`${a}Failed to find transcend.yml file for organization: "${r.organizationName}".`)),e.push(r.organizationName);return}await I({transcendUrl:c,auth:r.apiKey,contents:g,pageSize:l,publishToPrivacyCenter:m,deleteExtraAttributeValues:u,classifyService:f})?n.info(o.green(`${a}Successfully pushed configuration!`)):(n.error(o.red(`${a}Failed to sync configuration.`)),e.push(r.organizationName))}),e.length>0&&(n.info(o.red(`Sync encountered errors for "${e.join(",")}". View output above for more information, or check out ${d}`)),process.exit(1))}n.info(o.green(`Successfully synced yaml file to Transcend! View at ${d}`))}export{H as push};
|
|
6
|
-
//# sourceMappingURL=impl-UHFSVVIS.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/inventory/push/impl.ts"],"sourcesContent":["import type { LocalContext } from '@/context';\n\nimport { logger } from '@/logger';\nimport { mapSeries } from '@/lib/bluebird-replace';\nimport { existsSync, lstatSync } from 'fs';\nimport { join } from 'path';\nimport { readTranscendYaml } from '@/lib/readTranscendYaml';\nimport colors from 'colors';\nimport {\n buildTranscendGraphQLClient,\n syncConfigurationToTranscend,\n} from '@/lib/graphql';\n\nimport { ADMIN_DASH_INTEGRATIONS } from '@/constants';\nimport { TranscendInput } from '@/codecs';\nimport { validateTranscendAuth, listFiles } from '@/lib/api-keys';\nimport { mergeTranscendInputs } from '@/lib/mergeTranscendInputs';\nimport { parseVariablesFromString } from '@/lib/helpers/parseVariablesFromString';\n\n/**\n * Sync configuration to Transcend\n *\n * @param options - Options\n * @returns True if synced successfully, false if error occurs\n */\nasync function syncConfiguration({\n transcendUrl,\n auth,\n pageSize,\n publishToPrivacyCenter,\n contents,\n deleteExtraAttributeValues = false,\n classifyService = false,\n}: {\n /** Transcend YAML */\n contents: TranscendInput;\n /** Transcend URL */\n transcendUrl: string;\n /** API key */\n auth: string;\n /** Page size */\n pageSize: number;\n /** Skip privacy center publish step */\n publishToPrivacyCenter: boolean;\n /** classify data flow service if missing */\n classifyService?: boolean;\n /** Delete attributes when syncing */\n deleteExtraAttributeValues?: boolean;\n}): Promise<boolean> {\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Sync to Transcend\n try {\n const encounteredError = await syncConfigurationToTranscend(\n contents,\n client,\n {\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n },\n );\n return !encounteredError;\n } catch (err) {\n logger.error(\n colors.red(\n `An unexpected error occurred syncing the schema: ${err.message}`,\n ),\n );\n return false;\n }\n}\n\ninterface 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 // 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 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 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 process.exit(1);\n }\n } else {\n // if passed multiple inputs, expect them to be one per instance\n if (\n transcendInputs.length !== 1 &&\n transcendInputs.length !== apiKeyOrList.length\n ) {\n throw new Error(\n 'Expected list of yml files to be equal to the list of API keys.' +\n `Got ${transcendInputs.length} YML file${\n transcendInputs.length === 1 ? '' : 's'\n } and ${apiKeyOrList.length} API key${\n apiKeyOrList.length === 1 ? '' : 's'\n }`,\n );\n }\n\n const encounteredErrors: string[] = [];\n await mapSeries(apiKeyOrList, async (apiKey, ind) => {\n const prefix = `[${ind + 1}/${apiKeyOrList.length}][${\n apiKey.organizationName\n }] `;\n logger.info(\n colors.magenta(\n `~~~\\n\\n${prefix}Attempting to push configuration...\\n\\n~~~`,\n ),\n );\n\n // use the merged contents if 1 yml passed, else use the contents that map to that organization\n const useContents =\n transcendInputs.length === 1\n ? transcendInputs[0].content\n : transcendInputs.find(\n (input) => input.name === apiKey.organizationName,\n )?.content;\n\n // Throw error if cannot find a yml file matching that organization name\n if (!useContents) {\n logger.error(\n colors.red(\n `${prefix}Failed to find transcend.yml file for organization: \"${apiKey.organizationName}\".`,\n ),\n );\n encounteredErrors.push(apiKey.organizationName);\n return;\n }\n\n const success = await syncConfiguration({\n transcendUrl,\n auth: apiKey.apiKey,\n contents: useContents,\n pageSize,\n publishToPrivacyCenter,\n deleteExtraAttributeValues,\n classifyService,\n });\n\n if (success) {\n logger.info(\n colors.green(`${prefix}Successfully pushed configuration!`),\n );\n } else {\n logger.error(colors.red(`${prefix}Failed to sync configuration.`));\n encounteredErrors.push(apiKey.organizationName);\n }\n });\n\n if (encounteredErrors.length > 0) {\n logger.info(\n colors.red(\n `Sync encountered errors for \"${encounteredErrors.join(\n ',',\n )}\". View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n process.exit(1);\n }\n }\n\n // Indicate success\n logger.info(\n colors.green(\n `Successfully synced yaml file to Transcend! View at ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n}\n"],"mappings":"+ZAIA,OAAS,cAAAA,EAAY,aAAAC,MAAiB,KACtC,OAAS,QAAAC,MAAY,OAErB,OAAOC,MAAY,SAkBnB,eAAeC,EAAkB,CAC/B,aAAAC,EACA,KAAAC,EACA,SAAAC,EACA,uBAAAC,EACA,SAAAC,EACA,2BAAAC,EAA6B,GAC7B,gBAAAC,EAAkB,EACpB,EAeqB,CACnB,IAAMC,EAASC,EAA4BR,EAAcC,CAAI,EAG7D,GAAI,CAWF,MAAO,CAVkB,MAAMQ,EAC7BL,EACAG,EACA,CACE,SAAAL,EACA,uBAAAC,EACA,gBAAAG,EACA,2BAAAD,CACF,CACF,CAEF,OAASK,EAAK,CACZ,OAAAC,EAAO,MACLC,EAAO,IACL,oDAAoDF,EAAI,OAAO,EACjE,CACF,EACO,EACT,CACF,CAaA,eAAsBG,EAEpB,CACE,KAAAC,EAAO,k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AAC,2DAA2DD,CAAuB,EACrF,CACF,EAEA,QAAQ,KAAK,CAAC,EAElB,CAGAtB,EAAO,KACLC,EAAO,MACL,uDAAuDqB,CAAuB,EAChF,CACF,CACF","names":["existsSync","lstatSync","join","colors","syncConfiguration","transcendUrl","auth","pageSize","publishToPrivacyCenter","contents","deleteExtraAttributeValues","classifyService","client","buildTranscendGraphQLClient","syncConfigurationToTranscend","err","logger","colors","push","file","variables","apiKeyOrList","validateTranscendAuth","vars","parseVariablesFromString","fileList","lstatSync","listFiles","filePath","join","transcendInputs","existsSync","newContents","readTranscendYaml","base","rest","content","mergeTranscendInputs","ADMIN_DASH_INTEGRATIONS","encounteredErrors","mapSeries","apiKey","ind","prefix","useContents","input"]}
|
package/dist/impl-UIVTSO57.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{O as t,n as e}from"./chunk-ZTD7APNF.js";import"./chunk-TDBKATQK.js";import"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-SF46ZLPT.js";import"./chunk-ARVEJERC.js";async function y({auth:o,file:i,transcendUrl:n,cacheFilepath:a,requestReceiptFolder:r,sombraAuth:s,concurrency:l,attributes:c,isTest:d,isSilent:p,skipSendingReceipt:u,emailIsVerified:m,skipFilterStep:b,dryRun:g,debug:C,defaultPhoneCountryCode:f}){await t({cacheFilepath:a,requestReceiptFolder:r,file:i,auth:o,sombraAuth:s,concurrency:l,transcendUrl:n,defaultPhoneCountryCode:f,attributes:e(c),debug:C,skipFilterStep:b,isSilent:p,skipSendingReceipt:u,emailIsVerified:m,isTest:d,dryRun:g})}export{y as upload};
|
|
2
|
-
//# sourceMappingURL=impl-UIVTSO57.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/request/upload/impl.ts"],"sourcesContent":["import type { LocalContext } from '@/context';\nimport { splitCsvToList, uploadPrivacyRequestsFromCsv } from '@/lib/requests';\n\ninterface UploadCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n cacheFilepath: string;\n requestReceiptFolder: string;\n sombraAuth?: string;\n concurrency: number;\n attributes: string;\n isTest: boolean;\n isSilent: boolean;\n skipSendingReceipt: boolean;\n emailIsVerified: boolean;\n skipFilterStep: boolean;\n dryRun: boolean;\n debug: boolean;\n defaultPhoneCountryCode: string;\n}\n\nexport async function upload(\n this: LocalContext,\n {\n auth,\n file,\n transcendUrl,\n cacheFilepath,\n requestReceiptFolder,\n sombraAuth,\n concurrency,\n attributes,\n isTest,\n isSilent,\n skipSendingReceipt,\n emailIsVerified,\n skipFilterStep,\n dryRun,\n debug,\n defaultPhoneCountryCode,\n }: UploadCommandFlags,\n): Promise<void> {\n await uploadPrivacyRequestsFromCsv({\n cacheFilepath,\n requestReceiptFolder,\n file,\n auth,\n sombraAuth,\n concurrency,\n transcendUrl,\n defaultPhoneCountryCode,\n attributes: splitCsvToList(attributes),\n debug,\n skipFilterStep,\n isSilent,\n skipSendingReceipt,\n emailIsVerified,\n isTest,\n dryRun,\n });\n}\n"],"mappings":"2LAsBA,eAAsBA,EAEpB,CACE,KAAAC,EACA,KAAAC,EACA,aAAAC,EACA,cAAAC,EACA,qBAAAC,EACA,WAAAC,EACA,YAAAC,EACA,WAAAC,EACA,OAAAC,EACA,SAAAC,EACA,mBAAAC,EACA,gBAAAC,EACA,eAAAC,EACA,OAAAC,EACA,MAAAC,EACA,wBAAAC,CACF,EACe,CACf,MAAMC,EAA6B,CACjC,cAAAb,EACA,qBAAAC,EACA,KAAAH,EACA,KAAAD,EACA,WAAAK,EACA,YAAAC,EACA,aAAAJ,EACA,wBAAAa,EACA,WAAYE,EAAeV,CAAU,EACrC,MAAAO,EACA,eAAAF,EACA,SAAAH,EACA,mBAAAC,EACA,gBAAAC,EACA,OAAAH,EACA,OAAAK,CACF,CAAC,CACH","names":["upload","auth","file","transcendUrl","cacheFilepath","requestReceiptFolder","sombraAuth","concurrency","attributes","isTest","isSilent","skipSendingReceipt","emailIsVerified","skipFilterStep","dryRun","debug","defaultPhoneCountryCode","uploadPrivacyRequestsFromCsv","splitCsvToList"]}
|
package/dist/impl-UQYL5PXR.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import"./chunk-7QHA6ZIV.js";import{c as i}from"./chunk-MA4JWWRO.js";import{j as s}from"./chunk-XNR74SBS.js";import"./chunk-WSDWILYI.js";import"./chunk-ZTD7APNF.js";import"./chunk-LAYHULHH.js";import"./chunk-347UQP43.js";import{qe as o}from"./chunk-TDBKATQK.js";import"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-SF46ZLPT.js";import"./chunk-ARVEJERC.js";async function h({auth:a,partition:m,sombraAuth:c,file:p,transcendUrl:f,timestampBefore:e,timestampAfter:r,identifiers:n=[],concurrency:l}){let g=await o(f,a,c),u=await s(g,{partition:m,filterBy:{...e?{timestampBefore:e.toISOString()}:{},...r?{timestampAfter:r.toISOString()}:{},...n.length>0?{identifiers:n}:{}},limit:l});i(p,u.map(t=>({...t,purposes:JSON.stringify(t.purposes),...t.purposes})))}export{h as pullConsentPreferences};
|
|
2
|
-
//# sourceMappingURL=impl-UQYL5PXR.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/consent/pull-consent-preferences/impl.ts"],"sourcesContent":["import type { LocalContext } from '@/context';\n\nimport { fetchConsentPreferences } from '@/lib/consent-manager';\nimport { writeCsv } from '@/lib/cron';\nimport { createSombraGotInstance } from '@/lib/graphql';\n\ninterface PullConsentPreferencesCommandFlags {\n auth: string;\n partition: string;\n sombraAuth?: string;\n file: string;\n transcendUrl: string;\n timestampBefore?: Date;\n timestampAfter?: Date;\n identifiers?: string[];\n concurrency: number;\n}\n\nexport async function pullConsentPreferences(\n this: LocalContext,\n {\n auth,\n partition,\n sombraAuth,\n file,\n transcendUrl,\n timestampBefore,\n timestampAfter,\n identifiers = [],\n concurrency,\n }: PullConsentPreferencesCommandFlags,\n): Promise<void> {\n // Create sombra instance to communicate with\n const sombra = await createSombraGotInstance(transcendUrl, auth, sombraAuth);\n\n // Fetch preferences\n const preferences = await fetchConsentPreferences(sombra, {\n partition,\n filterBy: {\n ...(timestampBefore\n ? { timestampBefore: timestampBefore.toISOString() }\n : {}),\n ...(timestampAfter\n ? { timestampAfter: timestampAfter.toISOString() }\n : {}),\n ...(identifiers.length > 0 ? { identifiers } : {}),\n },\n limit: concurrency,\n });\n\n // Write to disk\n writeCsv(\n file,\n preferences.map((pref) => ({\n ...pref,\n purposes: JSON.stringify(pref.purposes),\n ...pref.purposes,\n })),\n );\n}\n"],"mappings":"qXAkBA,eAAsBA,EAEpB,CACE,KAAAC,EACA,UAAAC,EACA,WAAAC,EACA,KAAAC,EACA,aAAAC,EACA,gBAAAC,EACA,eAAAC,EACA,YAAAC,EAAc,CAAC,EACf,YAAAC,CACF,EACe,CAEf,IAAMC,EAAS,MAAMC,EAAwBN,EAAcJ,EAAME,CAAU,EAGrES,EAAc,MAAMC,EAAwBH,EAAQ,CACxD,UAAAR,EACA,SAAU,CACR,GAAII,EACA,CAAE,gBAAiBA,EAAgB,YAAY,CAAE,EACjD,CAAC,EACL,GAAIC,EACA,CAAE,eAAgBA,EAAe,YAAY,CAAE,EAC/C,CAAC,EACL,GAAIC,EAAY,OAAS,EAAI,CAAE,YAAAA,CAAY,EAAI,CAAC,CAClD,EACA,MAAOC,CACT,CAAC,EAGDK,EACEV,EACAQ,EAAY,IAAKG,IAAU,CACzB,GAAGA,EACH,SAAU,KAAK,UAAUA,EAAK,QAAQ,EACtC,GAAGA,EAAK,QACV,EAAE,CACJ,CACF","names":["pullConsentPreferences","auth","partition","sombraAuth","file","transcendUrl","timestampBefore","timestampAfter","identifiers","concurrency","sombra","createSombraGotInstance","preferences","fetchConsentPreferences","writeCsv","pref"]}
|
package/dist/impl-V5QTKTU4.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{I as e}from"./chunk-ZTD7APNF.js";import"./chunk-TDBKATQK.js";import"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-SF46ZLPT.js";import"./chunk-ARVEJERC.js";async function m({auth:t,actions:r,origins:o,silentModeBefore:i,createdAtBefore:n,createdAtAfter:a,transcendUrl:s,concurrency:c}){await e({transcendUrl:s,requestActions:r,auth:t,requestOrigins:o,concurrency:c,silentModeBefore:i,createdAtBefore:n,createdAtAfter:a})}export{m as approve};
|
|
2
|
-
//# sourceMappingURL=impl-V5QTKTU4.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/request/approve/impl.ts"],"sourcesContent":["import type { LocalContext } from '@/context';\n\nimport { RequestAction, RequestOrigin } from '@transcend-io/privacy-types';\nimport { approvePrivacyRequests } from '@/lib/requests';\n\ninterface ApproveCommandFlags {\n auth: string;\n actions: RequestAction[];\n origins?: RequestOrigin[];\n silentModeBefore?: Date;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n transcendUrl: string;\n concurrency: number;\n}\n\nexport async function approve(\n this: LocalContext,\n {\n auth,\n actions,\n origins,\n silentModeBefore,\n createdAtBefore,\n createdAtAfter,\n transcendUrl,\n concurrency,\n }: ApproveCommandFlags,\n): Promise<void> {\n await approvePrivacyRequests({\n transcendUrl,\n requestActions: actions,\n auth,\n requestOrigins: origins,\n concurrency,\n silentModeBefore,\n createdAtBefore,\n createdAtAfter,\n });\n}\n"],"mappings":"oLAgBA,eAAsBA,EAEpB,CACE,KAAAC,EACA,QAAAC,EACA,QAAAC,EACA,iBAAAC,EACA,gBAAAC,EACA,eAAAC,EACA,aAAAC,EACA,YAAAC,CACF,EACe,CACf,MAAMC,EAAuB,CAC3B,aAAAF,EACA,eAAgBL,EAChB,KAAAD,EACA,eAAgBE,EAChB,YAAAK,EACA,iBAAAJ,EACA,gBAAAC,EACA,eAAAC,CACF,CAAC,CACH","names":["approve","auth","actions","origins","silentModeBefore","createdAtBefore","createdAtAfter","transcendUrl","concurrency","approvePrivacyRequests"]}
|
package/dist/impl-WDPWOOFV.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{T as t}from"./chunk-ZTD7APNF.js";import"./chunk-TDBKATQK.js";import"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-SF46ZLPT.js";import"./chunk-ARVEJERC.js";async function i({auth:e,dataSiloId:a,actions:o,transcendUrl:s}){await t({requestActions:o,transcendUrl:s,auth:e,dataSiloId:a})}export{i as retryRequestDataSilos};
|
|
2
|
-
//# sourceMappingURL=impl-WDPWOOFV.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/request/system/retry-request-data-silos/impl.ts"],"sourcesContent":["import type { LocalContext } from '@/context';\nimport type { RequestAction } from '@transcend-io/privacy-types';\nimport { retryRequestDataSilos as retryRequestDataSilosHelper } from '@/lib/requests';\n\ninterface RetryRequestDataSilosCommandFlags {\n auth: string;\n dataSiloId: string;\n actions: RequestAction[];\n transcendUrl: string;\n}\n\nexport async function retryRequestDataSilos(\n this: LocalContext,\n {\n auth,\n dataSiloId,\n actions,\n transcendUrl,\n }: RetryRequestDataSilosCommandFlags,\n): Promise<void> {\n await retryRequestDataSilosHelper({\n requestActions: actions,\n transcendUrl,\n auth,\n dataSiloId,\n });\n}\n"],"mappings":"oLAWA,eAAsBA,EAEpB,CACE,KAAAC,EACA,WAAAC,EACA,QAAAC,EACA,aAAAC,CACF,EACe,CACf,MAAMJ,EAA4B,CAChC,eAAgBG,EAChB,aAAAC,EACA,KAAAH,EACA,WAAAC,CACF,CAAC,CACH","names":["retryRequestDataSilos","auth","dataSiloId","actions","transcendUrl"]}
|
package/dist/impl-WZAF2LD3.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{f as s}from"./chunk-7QHA6ZIV.js";import"./chunk-MA4JWWRO.js";import{q as a}from"./chunk-ZTD7APNF.js";import"./chunk-TDBKATQK.js";import{a as o}from"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-SF46ZLPT.js";import"./chunk-ARVEJERC.js";import l from"colors";import*as t from"io-ts";var p=t.type({"Request Id":t.string});async function R({auth:r,dataSiloId:i,file:e,transcendUrl:m}){o.info(l.magenta(`Reading "${e}" from disk`));let n=a(e,p);await s({requestIds:n.map(d=>d["Request Id"]),transcendUrl:m,auth:r,dataSiloId:i})}export{R as markRequestDataSilosCompleted};
|
|
2
|
-
//# sourceMappingURL=impl-WZAF2LD3.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/request/system/mark-request-data-silos-completed/impl.ts"],"sourcesContent":["import type { LocalContext } from '@/context';\nimport colors from 'colors';\nimport * as t from 'io-ts';\n\nimport { logger } from '@/logger';\nimport { markRequestDataSiloIdsCompleted } from '@/lib/cron';\nimport { readCsv } from '@/lib/requests';\n\nconst RequestIdRow = t.type({\n 'Request Id': t.string,\n});\n\ninterface MarkRequestDataSilosCompletedCommandFlags {\n auth: string;\n dataSiloId: string;\n file: string;\n transcendUrl: string;\n}\n\nexport async function markRequestDataSilosCompleted(\n this: LocalContext,\n {\n auth,\n dataSiloId,\n file,\n transcendUrl,\n }: MarkRequestDataSilosCompletedCommandFlags,\n): Promise<void> {\n logger.info(colors.magenta(`Reading \"${file}\" from disk`));\n const activeResults = readCsv(file, RequestIdRow);\n\n await markRequestDataSiloIdsCompleted({\n requestIds: activeResults.map((request) => request['Request Id']),\n transcendUrl,\n auth,\n dataSiloId,\n });\n}\n"],"mappings":"oQACA,OAAOA,MAAY,SACnB,UAAY,MAAO,QAMnB,IAAMC,EAAiB,OAAK,CAC1B,aAAgB,QAClB,CAAC,EASD,eAAsBC,EAEpB,CACE,KAAAC,EACA,WAAAC,EACA,KAAAC,EACA,aAAAC,CACF,EACe,CACfC,EAAO,KAAKC,EAAO,QAAQ,YAAYH,CAAI,aAAa,CAAC,EACzD,IAAMI,EAAgBC,EAAQL,EAAMJ,CAAY,EAEhD,MAAMU,EAAgC,CACpC,WAAYF,EAAc,IAAKG,GAAYA,EAAQ,YAAY,CAAC,EAChE,aAAAN,EACA,KAAAH,EACA,WAAAC,CACF,CAAC,CACH","names":["colors","RequestIdRow","markRequestDataSilosCompleted","auth","dataSiloId","file","transcendUrl","logger","colors","activeResults","readCsv","markRequestDataSiloIdsCompleted","request"]}
|
package/dist/impl-XF26H3HG.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{a as t}from"./chunk-6P4FW6XR.js";import"./chunk-MA4JWWRO.js";import"./chunk-ZTD7APNF.js";import"./chunk-TDBKATQK.js";import"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-SF46ZLPT.js";import"./chunk-ARVEJERC.js";async function c({auth:n,transcendUrl:e,file:i,concurrency:r,actions:o,sombraAuth:s}){await t({file:i,transcendUrl:e,concurrency:r,requestActions:o,auth:n,sombraAuth:s})}export{c as pullIdentifiers};
|
|
2
|
-
//# sourceMappingURL=impl-XF26H3HG.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/request/preflight/pull-identifiers/impl.ts"],"sourcesContent":["import type { LocalContext } from '@/context';\nimport { pullManualEnrichmentIdentifiersToCsv } from '@/lib/manual-enrichment';\nimport type { RequestAction } from '@transcend-io/privacy-types';\n\ninterface PullIdentifiersCommandFlags {\n auth: string;\n sombraAuth?: string;\n transcendUrl: string;\n file: string;\n actions?: RequestAction[];\n concurrency: number;\n}\n\nexport async function pullIdentifiers(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n file,\n concurrency,\n actions,\n sombraAuth,\n }: PullIdentifiersCommandFlags,\n): Promise<void> {\n await pullManualEnrichmentIdentifiersToCsv({\n file,\n transcendUrl,\n concurrency,\n requestActions: actions,\n auth,\n sombraAuth,\n });\n}\n"],"mappings":"4OAaA,eAAsBA,EAEpB,CACE,KAAAC,EACA,aAAAC,EACA,KAAAC,EACA,YAAAC,EACA,QAAAC,EACA,WAAAC,CACF,EACe,CACf,MAAMC,EAAqC,CACzC,KAAAJ,EACA,aAAAD,EACA,YAAAE,EACA,eAAgBC,EAChB,KAAAJ,EACA,WAAAK,CACF,CAAC,CACH","names":["pullIdentifiers","auth","transcendUrl","file","concurrency","actions","sombraAuth","pullManualEnrichmentIdentifiersToCsv"]}
|
package/dist/impl-XQY2Q5R6.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{F as t}from"./chunk-ZTD7APNF.js";import"./chunk-TDBKATQK.js";import"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-SF46ZLPT.js";import"./chunk-ARVEJERC.js";import{RequestStatus as e}from"@transcend-io/privacy-types";async function f({auth:o,transcendUrl:a,folderPath:r,requestIds:n,statuses:s=[e.Approving,e.Downloadable],concurrency:i,createdAtBefore:l,createdAtAfter:d,approveAfterDownload:c}){await t({transcendUrl:a,auth:o,folderPath:r,requestIds:n,statuses:s,concurrency:i,createdAtBefore:l,createdAtAfter:d,approveAfterDownload:c})}export{f as downloadFiles};
|
|
2
|
-
//# sourceMappingURL=impl-XQY2Q5R6.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/request/download-files/impl.ts"],"sourcesContent":["import type { LocalContext } from '@/context';\nimport { downloadPrivacyRequestFiles } from '@/lib/requests';\nimport { RequestStatus } from '@transcend-io/privacy-types';\n\ninterface DownloadFilesCommandFlags {\n auth: string;\n sombraAuth?: string;\n concurrency: number;\n requestIds?: string[];\n statuses?: RequestStatus[];\n folderPath: string;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n approveAfterDownload: boolean;\n transcendUrl: string;\n}\n\nexport async function downloadFiles(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n folderPath,\n requestIds,\n statuses = [RequestStatus.Approving, RequestStatus.Downloadable],\n concurrency,\n createdAtBefore,\n createdAtAfter,\n approveAfterDownload,\n }: DownloadFilesCommandFlags,\n): Promise<void> {\n await downloadPrivacyRequestFiles({\n transcendUrl,\n auth,\n folderPath,\n requestIds,\n statuses,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n approveAfterDownload,\n });\n}\n"],"mappings":"oLAEA,OAAS,iBAAAA,MAAqB,8BAe9B,eAAsBC,EAEpB,CACE,KAAAC,EACA,aAAAC,EACA,WAAAC,EACA,WAAAC,EACA,SAAAC,EAAW,CAACN,EAAc,UAAWA,EAAc,YAAY,EAC/D,YAAAO,EACA,gBAAAC,EACA,eAAAC,EACA,qBAAAC,CACF,EACe,CACf,MAAMC,EAA4B,CAChC,aAAAR,EACA,KAAAD,EACA,WAAAE,EACA,WAAAC,EACA,SAAAC,EACA,YAAAC,EACA,gBAAAC,EACA,eAAAC,EACA,qBAAAC,CACF,CAAC,CACH","names":["RequestStatus","downloadFiles","auth","transcendUrl","folderPath","requestIds","statuses","concurrency","createdAtBefore","createdAtAfter","approveAfterDownload","downloadPrivacyRequestFiles"]}
|
package/dist/impl-YB2LON7S.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{b as m}from"./chunk-MVDOKJ6J.js";import{a as t}from"./chunk-XNR74SBS.js";import"./chunk-WSDWILYI.js";import"./chunk-ZTD7APNF.js";import"./chunk-LAYHULHH.js";import"./chunk-347UQP43.js";import{a as g}from"./chunk-TDBKATQK.js";import{a as n}from"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-SF46ZLPT.js";import"./chunk-ARVEJERC.js";import a from"colors";import{ConsentBundleType as p}from"@transcend-io/privacy-types";async function M({auth:f,bundleTypes:r=[p.Production,p.Test],deploy:i,transcendUrl:s}){let e=await m(f);typeof e=="string"?(await t({deploy:i,transcendUrl:s,auth:e,bundleTypes:r}),n.info(a.green("Successfully updated Consent Manager!"))):(await g(e,async o=>{n.info(a.magenta(`Updating Consent Manager for organization "${o.organizationName}"...`)),await t({deploy:i,transcendUrl:s,auth:o.apiKey,bundleTypes:r}),n.info(a.green(`Successfully updated Consent Manager for organization "${o.organizationName}"!`))}),n.info(a.green("Successfully updated Consent Managers!")))}export{M as updateConsentManager};
|
|
2
|
-
//# sourceMappingURL=impl-YB2LON7S.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/consent/update-consent-manager/impl.ts"],"sourcesContent":["import type { LocalContext } from '@/context';\nimport colors from 'colors';\nimport { ConsentBundleType } from '@transcend-io/privacy-types';\nimport { mapSeries } from '@/lib/bluebird-replace';\n\nimport { logger } from '@/logger';\nimport { updateConsentManagerVersionToLatest } from '@/lib/consent-manager';\nimport { validateTranscendAuth } from '@/lib/api-keys';\n\ninterface UpdateConsentManagerCommandFlags {\n auth: string;\n bundleTypes: ConsentBundleType[];\n deploy: boolean;\n transcendUrl: string;\n}\n\nexport async function updateConsentManager(\n this: LocalContext,\n {\n auth,\n bundleTypes = [ConsentBundleType.Production, ConsentBundleType.Test],\n deploy,\n transcendUrl,\n }: UpdateConsentManagerCommandFlags,\n): Promise<void> {\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth);\n\n // Handle single update\n if (typeof apiKeyOrList === 'string') {\n // Update consent manager\n await updateConsentManagerVersionToLatest({\n deploy,\n transcendUrl,\n auth: apiKeyOrList,\n bundleTypes,\n });\n logger.info(colors.green('Successfully updated Consent Manager!'));\n } else {\n await mapSeries(apiKeyOrList, async (apiKey) => {\n logger.info(\n colors.magenta(\n `Updating Consent Manager for organization \"${apiKey.organizationName}\"...`,\n ),\n );\n\n await updateConsentManagerVersionToLatest({\n deploy,\n transcendUrl,\n auth: apiKey.apiKey,\n bundleTypes,\n });\n\n logger.info(\n colors.green(\n `Successfully updated Consent Manager for organization \"${apiKey.organizationName}\"!`,\n ),\n );\n });\n logger.info(colors.green('Successfully updated Consent Managers!'));\n }\n}\n"],"mappings":"oWACA,OAAOA,MAAY,SACnB,OAAS,qBAAAC,MAAyB,8BAclC,eAAsBC,EAEpB,CACE,KAAAC,EACA,YAAAC,EAAc,CAACC,EAAkB,WAAYA,EAAkB,IAAI,EACnE,OAAAC,EACA,aAAAC,CACF,EACe,CAEf,IAAMC,EAAe,MAAMC,EAAsBN,CAAI,EAGjD,OAAOK,GAAiB,UAE1B,MAAME,EAAoC,CACxC,OAAAJ,EACA,aAAAC,EACA,KAAMC,EACN,YAAAJ,CACF,CAAC,EACDO,EAAO,KAAKC,EAAO,MAAM,uCAAuC,CAAC,IAEjE,MAAMC,EAAUL,EAAc,MAAOM,GAAW,CAC9CH,EAAO,KACLC,EAAO,QACL,8CAA8CE,EAAO,gBAAgB,MACvE,CACF,EAEA,MAAMJ,EAAoC,CACxC,OAAAJ,EACA,aAAAC,EACA,KAAMO,EAAO,OACb,YAAAV,CACF,CAAC,EAEDO,EAAO,KACLC,EAAO,MACL,0DAA0DE,EAAO,gBAAgB,IACnF,CACF,CACF,CAAC,EACDH,EAAO,KAAKC,EAAO,MAAM,wCAAwC,CAAC,EAEtE","names":["colors","ConsentBundleType","updateConsentManager","auth","bundleTypes","ConsentBundleType","deploy","transcendUrl","apiKeyOrList","validateTranscendAuth","updateConsentManagerVersionToLatest","logger","colors","mapSeries","apiKey"]}
|
package/dist/impl-YNGQIWW7.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{J as t}from"./chunk-ZTD7APNF.js";import"./chunk-TDBKATQK.js";import"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-SF46ZLPT.js";import"./chunk-ARVEJERC.js";async function f({auth:e,transcendUrl:i,createdAtBefore:n,createdAtAfter:o,actions:r,daysLeft:a,days:s,requestIds:m,emailTemplate:c,concurrency:d}){await t({transcendUrl:i,requestActions:r,auth:e,emailTemplate:c,days:s,daysLeft:a,requestIds:m,concurrency:d,createdAtBefore:n,createdAtAfter:o})}export{f as notifyAdditionalTime};
|
|
2
|
-
//# sourceMappingURL=impl-YNGQIWW7.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/request/notify-additional-time/impl.ts"],"sourcesContent":["import type { LocalContext } from '@/context';\nimport { notifyPrivacyRequestsAdditionalTime } from '@/lib/requests';\nimport type { RequestAction } from '@transcend-io/privacy-types';\n\ninterface NotifyAdditionalTimeCommandFlags {\n auth: string;\n createdAtBefore: Date;\n createdAtAfter?: Date;\n actions?: RequestAction[];\n daysLeft: number;\n days: number;\n requestIds?: string[];\n emailTemplate: string;\n transcendUrl: string;\n concurrency: number;\n}\n\nexport async function notifyAdditionalTime(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n createdAtBefore,\n createdAtAfter,\n actions,\n daysLeft,\n days,\n requestIds,\n emailTemplate,\n concurrency,\n }: NotifyAdditionalTimeCommandFlags,\n): Promise<void> {\n await notifyPrivacyRequestsAdditionalTime({\n transcendUrl,\n requestActions: actions,\n auth,\n emailTemplate,\n days,\n daysLeft,\n requestIds,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n });\n}\n"],"mappings":"oLAiBA,eAAsBA,EAEpB,CACE,KAAAC,EACA,aAAAC,EACA,gBAAAC,EACA,eAAAC,EACA,QAAAC,EACA,SAAAC,EACA,KAAAC,EACA,WAAAC,EACA,cAAAC,EACA,YAAAC,CACF,EACe,CACf,MAAMC,EAAoC,CACxC,aAAAT,EACA,eAAgBG,EAChB,KAAAJ,EACA,cAAAQ,EACA,KAAAF,EACA,SAAAD,EACA,WAAAE,EACA,YAAAE,EACA,gBAAAP,EACA,eAAAC,CACF,CAAC,CACH","names":["notifyAdditionalTime","auth","transcendUrl","createdAtBefore","createdAtAfter","actions","daysLeft","days","requestIds","emailTemplate","concurrency","notifyPrivacyRequestsAdditionalTime"]}
|
package/dist/impl-ZA3PKNQN.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{d as o,e as r}from"./chunk-OEB7WG3G.js";import{c as m}from"./chunk-MVDOKJ6J.js";import{h as a}from"./chunk-XNR74SBS.js";import"./chunk-WSDWILYI.js";import"./chunk-ZTD7APNF.js";import"./chunk-LAYHULHH.js";import"./chunk-347UQP43.js";import"./chunk-TDBKATQK.js";import{a as t}from"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-SF46ZLPT.js";import"./chunk-ARVEJERC.js";import{join as u}from"path";import c from"colors";import{existsSync as g,lstatSync as l}from"fs";function b({consentManagerYmlFolder:s,output:n}){(!g(s)||!l(s).isDirectory())&&(t.error(c.red(`Folder does not exist: "${s}"`)),process.exit(1));let p=m(s).map(i=>{let{"consent-manager":f}=o(u(s,i));return{name:i,input:f}}),e=a(p);r(n,{"business-entities":e}),t.info(c.green(`Successfully wrote ${e.length} business entities to file "${n}"`))}export{b as consentManagersToBusinessEntities};
|
|
2
|
-
//# sourceMappingURL=impl-ZA3PKNQN.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/inventory/consent-managers-to-business-entities/impl.ts"],"sourcesContent":["import type { LocalContext } from '@/context';\nimport { listFiles } from '@/lib/api-keys';\nimport { consentManagersToBusinessEntities as consentManagersToBusinessEntitiesHelper } from '@/lib/consent-manager';\nimport { readTranscendYaml, writeTranscendYaml } from '@/lib/readTranscendYaml';\nimport { join } from 'path';\n\nimport colors from 'colors';\nimport { logger } from '@/logger';\nimport { existsSync, lstatSync } from 'fs';\n\ninterface ConsentManagersToBusinessEntitiesCommandFlags {\n consentManagerYmlFolder: string;\n output: string;\n}\n\nexport function consentManagersToBusinessEntities(\n this: LocalContext,\n {\n consentManagerYmlFolder,\n output,\n }: ConsentManagersToBusinessEntitiesCommandFlags,\n): void {\n // Ensure folder is passed\n if (\n !existsSync(consentManagerYmlFolder) ||\n !lstatSync(consentManagerYmlFolder).isDirectory()\n ) {\n logger.error(\n colors.red(`Folder does not exist: \"${consentManagerYmlFolder}\"`),\n );\n process.exit(1);\n }\n\n // Read in each consent manager configuration\n const inputs = listFiles(consentManagerYmlFolder).map((directory) => {\n const { 'consent-manager': consentManager } = readTranscendYaml(\n join(consentManagerYmlFolder, directory),\n );\n return { name: directory, input: consentManager };\n });\n\n // Convert to business entities\n const businessEntities = consentManagersToBusinessEntitiesHelper(inputs);\n\n // write to disk\n writeTranscendYaml(output, {\n 'business-entities': businessEntities,\n });\n\n logger.info(\n colors.green(\n `Successfully wrote ${businessEntities.length} business entities to file \"${output}\"`,\n ),\n );\n}\n"],"mappings":"uYAIA,OAAS,QAAAA,MAAY,OAErB,OAAOC,MAAY,SAEnB,OAAS,cAAAC,EAAY,aAAAC,MAAiB,KAO/B,SAASC,EAEd,CACE,wBAAAC,EACA,OAAAC,CACF,EACM,EAGJ,CAACJ,EAAWG,CAAuB,GACnC,CAACF,EAAUE,CAAuB,EAAE,YAAY,KAEhDE,EAAO,MACLC,EAAO,IAAI,2BAA2BH,CAAuB,GAAG,CAClE,EACA,QAAQ,KAAK,CAAC,GAIhB,IAAMI,EAASC,EAAUL,CAAuB,EAAE,IAAKM,GAAc,CACnE,GAAM,CAAE,kBAAmBC,CAAe,EAAIC,EAC5CC,EAAKT,EAAyBM,CAAS,CACzC,EACA,MAAO,CAAE,KAAMA,EAAW,MAAOC,CAAe,CAClD,CAAC,EAGKG,EAAmBX,EAAwCK,CAAM,EAGvEO,EAAmBV,EAAQ,CACzB,oBAAqBS,CACvB,CAAC,EAEDR,EAAO,KACLC,EAAO,MACL,sBAAsBO,EAAiB,MAAM,+BAA+BT,CAAM,GACpF,CACF,CACF","names":["join","colors","existsSync","lstatSync","consentManagersToBusinessEntities","consentManagerYmlFolder","output","logger","colors","inputs","listFiles","directory","consentManager","readTranscendYaml","join","businessEntities","writeTranscendYaml"]}
|
package/dist/index.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{a as Ui,b as ji,c as Hi,d as Vi}from"./chunk-6P4FW6XR.js";import{a as Qi,b as Gi}from"./chunk-KRN6Q433.js";import{a as ta}from"./chunk-L7ZIX4SU.js";import{a as Ti,b as Ai,c as yi}from"./chunk-HH2PQ3PQ.js";import{a as xi}from"./chunk-4GLITB3Y.js";import{a as ue,b as he,c as fe,d as Pe,e as Te}from"./chunk-OEB7WG3G.js";import{a as Si,b as ki,c as Bi,d as Fi}from"./chunk-MVDOKJ6J.js";import{a as bi,b as wi,c as Ei,d as Ii,e as Oi,f as Di,g as $i}from"./chunk-7QHA6ZIV.js";import{a as Ri,b as Ci,c as Mi,d as Li,e as Ni}from"./chunk-MA4JWWRO.js";import{a as si,b as oi,c as ai,d as pi,e as ii,f as mi,g as ci,h as gi,i as li,j as ui}from"./chunk-XNR74SBS.js";import{a as di,d as hi,e as fi,f as Pi}from"./chunk-WSDWILYI.js";import{A as kp,B as Bp,C as Fp,D as Qp,E as Gp,F as Up,G as jp,H as Hp,I as Vp,J as qp,K as vp,L as _p,M as zp,N as Jp,O as Wp,P as Zp,Q as Kp,R as Xp,S as Yp,T as ti,U as ei,V as ri,W as ni,a as ea,b as ra,c as na,d as sa,e as oa,f as aa,g as pa,h as ia,i as ma,j as ca,k as ga,l as da,m as la,n as ua,o as ha,p as fa,q as Pa,r as Ta,s as Aa,t as Np,u as Ep,v as Ip,w as Op,x as Dp,y as $p,z as Sp}from"./chunk-ZTD7APNF.js";import{$ as Kt,A as Rt,B as Ct,C as Mt,D as Lt,E as Nt,F as Et,G as It,H as Ot,I as Dt,J as $t,K as St,L as kt,M as Bt,N as Ft,O as Qt,P as Gt,Q as Ut,R as jt,S as Ht,T as Vt,U as qt,V as vt,W as _t,X as zt,Y as Jt,Z as Wt,_ as Zt,a as X,aa as Xt,b as Y,ba as Yt,c as tt,ca as te,d as et,da as ee,e as rt,ea as re,f as nt,fa as ne,g as st,ga as se,h as ot,ha as oe,i as at,ia as ae,j as pt,ja as pe,k as it,ka as ie,l as mt,la as me,m as ct,ma as ce,n as gt,na as ge,o as dt,oa as de,p as lt,pa as le,q as ut,r as ht,s as ft,t as Pt,u as Tt,v as At,w as yt,x as xt,y as bt,z as wt}from"./chunk-LAYHULHH.js";import{a as Z,b as K}from"./chunk-347UQP43.js";import{$ as fr,$a as Pn,$b as hs,$c as ho,$d as $a,A as Ve,Aa as Vr,Ab as qn,Ac as Hs,Ad as Uo,Ae as ap,B as qe,Ba as qr,Bb as vn,Bc as Vs,Bd as jo,Be as pp,C as ve,Ca as vr,Cb as _n,Cc as R,Cd as Ho,Ce as ip,D as _e,Da as _r,Db as zn,Dc as qs,Dd as Vo,De as mp,E as ze,Ea as zr,Eb as Jn,Ec as vs,Ed as qo,Ee as cp,F as Je,Fa as Jr,Fb as Wn,Fc as _s,Fd as vo,Fe as gp,G as We,Ga as Wr,Gb as b,Gc as zs,Gd as _o,Ge as dp,H as Ze,Ha as Zr,Hb as Zn,Hc as Js,Hd as zo,He as lp,I as Ke,Ia as Kr,Ib as Kn,Ic as Ws,Id as Jo,Ie as up,J as Xe,Ja as Xr,Jb as Xn,Jc as Zs,Jd as Wo,Je as hp,K as Ye,Ka as Yr,Kb as Yn,Kc as Ks,Kd as Zo,Ke as fp,L as tr,La as tn,Lb as ts,Lc as Xs,Ld as Ko,Le as Pp,M as er,Ma as en,Mb as es,Mc as Ys,Md as Xo,Me as Tp,N as rr,Na as rn,Nb as rs,Nc as to,Nd as Yo,Ne as f,O as nr,Oa as nn,Ob as ns,Oc as eo,Od as ya,Oe as Ap,P as sr,Pa as sn,Pb as ss,Pc as ro,Pd as xa,Q as or,Qa as on,Qb as os,Qc as no,Qd as ba,R as ar,Ra as an,Rb as as,Rc as so,Rd as wa,S as pr,Sa as pn,Sb as ps,Sc as oo,Sd as Ra,T as ir,Ta as mn,Tb as is,Tc as ao,Td as Ca,U as mr,Ua as cn,Ub as ms,Uc as po,Ud as Ma,V as cr,Va as gn,Vb as cs,Vc as io,Vd as La,W as gr,Wa as dn,Wb as gs,Wc as mo,Wd as Na,X as dr,Xa as ln,Xb as ds,Xc as co,Xd as Ea,Y as lr,Ya as un,Yb as ls,Yc as go,Yd as Ia,Z as ur,Za as hn,Zb as us,Zc as lo,Zd as Oa,_ as hr,_a as fn,_b as w,_c as uo,_d as Da,a as x,aa as Pr,ab as Tn,ac as fs,ad as fo,ae as Sa,ba as Tr,bb as An,bc as Ps,bd as Po,be as ka,c as Ae,ca as Ar,cb as yn,cc as Ts,cd as To,ce as Ba,d as ye,da as yr,db as xn,dc as As,dd as Ao,de as Fa,e as xe,ea as xr,eb as bn,ec as ys,ed as yo,ee as Qa,f as be,fa as br,fb as wn,fc as xs,fd as xo,fe as Ga,g as we,ga as wr,gb as Rn,gc as bs,gd as bo,ge as Ua,h as Re,ha as Rr,hb as Cn,hc as ws,hd as wo,he as ja,i as Ce,ia as Cr,ib as Mn,ic as Rs,id as h,ie as Ha,j as Me,ja as Mr,jb as Ln,jc as Cs,jd as Ro,je as Va,k as Le,ka as Lr,kb as Nn,kc as Ms,kd as Co,ke as qa,l as Ne,la as Nr,lb as En,lc as Ls,ld as Mo,le as va,m as Ee,ma as Er,mb as In,mc as Ns,md as Lo,me as _a,n as Ie,na as Ir,nb as On,nc as Es,nd as No,ne as za,o as Oe,oa as Or,ob as Dn,oc as Is,od as Eo,oe as Za,p as De,pa as Dr,pb as $n,pc as Os,pd as Io,pe as M,q as $e,qa as $r,qb as Sn,qc as Ds,qd as Oo,qe as Ka,r as Se,ra as Sr,rb as kn,rc as $s,rd as Do,re as Xa,s as ke,sa as kr,sb as Bn,sc as Ss,sd as $o,se as Ya,t as Be,ta as Br,tb as Fn,tc as ks,td as So,te as L,u as Fe,ua as Fr,ub as Qn,uc as Bs,ud as ko,ue as tp,v as Qe,va as Qr,vb as Gn,vc as Fs,vd as Bo,ve as ep,w as Ge,wa as Gr,wb as Un,wc as Qs,wd as Fo,we as rp,x as Ue,xa as Ur,xb as jn,xc as Gs,xd as C,xe as np,y as je,ya as jr,yb as Hn,yc as Us,yd as Qo,ye as sp,z as He,za as Hr,zb as Vn,zc as js,zd as Go,ze as op}from"./chunk-TDBKATQK.js";import"./chunk-43JWXG77.js";import{a as yp,b as xp,c as bp,d as wp,e as N,f as Rp,g as Cp,h as Mp,i as Lp}from"./chunk-L5ULN3IT.js";import{a as Ja,b as Wa}from"./chunk-SF46ZLPT.js";import{a as q,b as v,c as _,d as z,e as J,f as W}from"./chunk-ARVEJERC.js";import{apply as k,decodeCodec as I,getValues as B}from"@transcend-io/type-utils";import{createHandlebarsWithHelpers as O}from"@transcend-io/handlebars-utils";import{PromptStatus as D,ChatCompletionRole as l,PromptRunProductArea as A,QueueStatus as y}from"@transcend-io/privacy-types";var T=20;async function E(a){let e=[],r=0,t=!1;do{let{largeLanguageModels:{nodes:s}}=await w(a,b,{first:T,offset:r});e.push(...s),r+=T,t=s.length===T}while(t);return e.sort((s,o)=>s.name.localeCompare(o.name))}import{groupBy as F,keyBy as P,uniq as Q,chunk as G}from"lodash-es";function U(a){return new RegExp(`<${a}>([\\s\\S]+?)<\\/${a}>`)}function hm(a){return a}var j=a=>{try{return JSON.parse(a)}catch{return a}},$=class{prompts;handlebarsOptions;promptContentMap;largeLanguageModels=[];agentsByName={};agentsByAgentId={};graphQLClient;defaultVariables;variables;handlebars;transcendApiKey;transcendUrl;requireApproval;cacheDuration;lastUpdatedAt;constructor({prompts:e,handlebarsOptions:r={},transcendUrl:t=N,transcendApiKey:s,requireApproval:o=!0,cacheDuration:i,defaultVariables:p={}}){this.prompts=e,this.transcendUrl=t,this.transcendApiKey=s,this.variables=p,this.defaultVariables=p,this.graphQLClient=M(t,typeof s=="object"?s.release():s),this.requireApproval=o,this.cacheDuration=i,this.handlebarsOptions=r,this.handlebars=O(r)}async fetchPromptsAndMetadata(){let e=B(this.prompts),r=e.map(({id:n})=>n).filter(n=>!!n),t=e.map(({title:n})=>n).filter(n=>!!n),s=Q(e.map(({agentNames:n})=>n||[]).flat()),[o,i,p]=await Promise.all([R(this.graphQLClient,{promptIds:r,promptTitles:t}),E(this.graphQLClient),h(this.graphQLClient,{names:s})]);this.agentsByName=P(p,"name"),this.agentsByAgentId=P(p,"agentId"),this.largeLanguageModels=i.filter(n=>n.isTranscendHosted===!1);let m=P(o.prompts,"title"),c=P(o.prompts,"id");return this.variables={...o.calculatedVariables.reduce((n,g)=>Object.assign(n,{[g.name]:g.data?JSON.parse(g.data):g.data}),{}),...this.defaultVariables},this.handlebars=O({...this.handlebarsOptions,templates:[...this.handlebarsOptions.templates||[],...o.promptPartials.map(n=>({name:n.slug,content:n.content}))]}),this.promptContentMap=k(this.prompts,({id:n,title:g})=>{let d=n?c[n]:g?m[g]:void 0;if(!d)throw new Error(`Failed to find prompt with title: "${g}" and id: "${n}"`);return d}),this.lastUpdatedAt=new Date,o}async getAgentByName(e){let r=this.agentsByName[e];if(r)return r;let[t]=await h(this.graphQLClient,{names:[e]});if(t)return this.agentsByName[t.name]=t,this.agentsByAgentId[t.agentId]=t,t}async getPromptThreadBySlackTs(e){let[r]=await L(this.graphQLClient,{slackMessageTs:[e]});return r}async getAgentsByName(e){if(e.length<1)throw new Error("Expected at least one name to be provided");let{hasCache:r=[],missingCache:t=[]}=F(e,p=>this.agentsByName[p]?"hasCache":"missingCache"),s=r.map(p=>this.agentsByName[p]);if(t.length===0)return s;let o=G(t,50),i=[];return await x(o,async p=>{let m=await h(this.graphQLClient,{names:p});m.forEach(c=>{this.agentsByName[c.name]=c,this.agentsByAgentId[c.agentId]=c}),i.push(...m)}),[...s,...i]}getAgentFiles(e){return C(this.graphQLClient,e)}getLargeLanguageModel(e){let r=this.largeLanguageModels.find(t=>typeof e=="string"?t.id===e:t.name===e.name&&t.client===e.client);if(!r)throw new Error(`Failed to find model matching: ${typeof e=="string"?e:JSON.stringify(e)}`);return r}async getPromptDefinition(e){(!this.lastUpdatedAt||this.cacheDuration===0||this.cacheDuration&&Date.now()-this.lastUpdatedAt.getTime()>this.cacheDuration)&&await this.fetchPromptsAndMetadata();let{promptContentMap:r}=this;if(!r)throw new Error("Expected this.promptContentMap to be defined");let t=r[e];if(!t)throw new Error(`Expected this.promptContentMap[${e}] to be defined`);return t}async compilePrompt(e,r){let t=await this.getPromptDefinition(e),s=this.prompts[e];if(!s)throw new Error(`Expected this.prompts[${e}] to be defined`);if(this.requireApproval&&t.status!==D.Approved)throw new Error(`Assessment "${t.title}" cannot be used because its in status: "${t.status}"`);if(t.status===D.Rejected)throw new Error(`Assessment "${t.title}" cannot be used because it's in status: "${t.status}"`);return I(s.paramCodec,r),this.handlebars.compile(t.content)({currentDate:new Date().toISOString(),...this.variables,...r})}parseAiResponse(e,r){let t=this.prompts[e];if(!t)throw new Error(`Expected this.prompts[${e}] to be defined`);let s=t.extractFromTag&&(U(t.extractFromTag).exec(r)||[])[1]||r;return I(t.outputCodec,j(s),!1)}async reportAndParsePromptRun(e,{largeLanguageModel:r,...t}){(!this.lastUpdatedAt||this.cacheDuration===0||this.cacheDuration&&Date.now()-this.lastUpdatedAt.getTime()>this.cacheDuration)&&await this.fetchPromptsAndMetadata();let s=t.name||`@transcend-io/cli-prompt-run-${new Date().toISOString()}`;if(!this.promptContentMap)throw new Error("Expected this.promptContentMap to be defined");let o=this.promptContentMap[e];if(!o)throw new Error(`Expected this.prompts[${e}] to be defined`);if(t.promptRunMessages.length===0)throw new Error("promptRunMessages is expected to have length > 0");if(t.promptRunMessages[0].role!==l.System)throw new Error(`promptRunMessages[0].role is expected to be = ${l.System}`);if(t.promptRunMessages[t.promptRunMessages.length-1].role!==l.Assistant)throw new Error(`promptRunMessages[${t.promptRunMessages.length-1}].role is expected to be = ${l.Assistant}`);let i=t.promptRunMessages[t.promptRunMessages.length-1].content,p;try{p=this.parseAiResponse(e,i)}catch(c){throw await f(this.graphQLClient,{productArea:A.PromptManager,...t,name:s,error:c.message,status:y.Error,...typeof r=="string"?{largeLanguageModelId:r}:{largeLanguageModelName:r.name,largeLanguageModelClient:r.client},promptId:o.id,promptRunMessages:t.promptRunMessages.map((n,g)=>({...n,...g===0?{template:o.content}:{}}))}),c}let m=await f(this.graphQLClient,{productArea:A.PromptManager,...t,name:s,status:y.Resolved,...typeof r=="string"?{largeLanguageModelId:r}:{largeLanguageModelName:r.name,largeLanguageModelClient:r.client},promptId:o.id,promptRunMessages:t.promptRunMessages.map((c,n)=>({...c,...n===0?{template:o.content}:{}}))});return{result:p,promptRunId:m,promptRunUrl:`https://app.transcend.io/prompts/runs/${m}`}}async reportPromptRunError(e,{largeLanguageModel:r,...t}){(!this.lastUpdatedAt||this.cacheDuration===0||this.cacheDuration&&Date.now()-this.lastUpdatedAt.getTime()>this.cacheDuration)&&await this.fetchPromptsAndMetadata();let s=t.name||`@transcend-io/cli-prompt-run-${new Date().toISOString()}`;if(!this.promptContentMap)throw new Error("Expected this.promptContentMap to be defined");let o=this.promptContentMap[e];if(!o)throw new Error(`Expected this.prompts[${e}] to be defined`);if(t.promptRunMessages.length===0)throw new Error("promptRunMessages is expected to have length > 0");if(t.promptRunMessages[0].role!==l.System)throw new Error(`promptRunMessages[0].role is expected to be = ${l.System}`);let i=await f(this.graphQLClient,{productArea:A.PromptManager,...t,name:s,status:y.Error,...typeof r=="string"?{largeLanguageModelId:r}:{largeLanguageModelName:r.name,largeLanguageModelClient:r.client},promptId:o.id,promptRunMessages:t.promptRunMessages.map((p,m)=>({...p,...m===0?{template:o.content}:{}}))});return{promptRunId:i,promptRunUrl:`https://app.transcend.io/prompts/runs/${i}`}}};function Pm(a){let e=/(https?:\/\/[^\s]+)/g;return a.replace(e,"<link-omitted>")}function Am(a){return Object.entries(a).reduce((e,[r,t])=>t!=null&&t!==""&&!(Array.isArray(t)&&t.length===0)&&!(typeof t=="object"&&Object.keys(t).length===0)?Object.assign(e,{[r]:t}):e,{})}import{difference as H}from"lodash-es";import V from"fast-glob";import{execSync as u}from"child_process";function Rm({baseBranch:a,rootDirectory:e,githubRepo:r,excludedGlob:t=[],fileBlockList:s=[]}){u(`git fetch origin ${a}`);let o=u(`git ls-remote ${r} "refs/heads/${a}" | cut -f 1`,{encoding:"utf-8"}).split(`
|
|
2
|
-
`)[0],i=u("git rev-parse HEAD",{encoding:"utf-8"}).split(`
|
|
3
|
-
`)[0];if(!o||!i)throw new Error("FAILED TO FIND COMMIT RANGE");let p=u(`git fetch && git diff --name-only "${a||o}...${i}" -- ${e}`,{encoding:"utf-8"}),m=H(p.split(`
|
|
4
|
-
`).filter(d=>d),s),c=t.length>0?V.sync(m,{ignore:t}):m,n={};c.forEach(d=>{let S=u(`git show ${i}:${d}`,{encoding:"utf-8"});n[d]=S});let g=r.split("/").pop().split(".")[0];return{changedFiles:m,fileDiffs:n,repoName:g,commit:i}}export{Qn as ACTIONS,Zr as ADD_MESSAGES_TO_PROMPT_RUN,Ke as ADD_SILO_DISCOVERY_RESULTS,xp as ADMIN_DASH,wp as ADMIN_DASH_DATAPOINTS,bp as ADMIN_DASH_INTEGRATIONS,Zn as AGENTS,Yn as AGENT_FILES,rs as AGENT_FUNCTIONS,Je as API_KEYS,lr as APPROVE_PRIVACY_REQUEST,wr as ASSESSMENTS,br as ASSESSMENT_SECTION_FIELDS,Lr as ASSESSMENT_TEMPLATES,Wn as ASSUME_ROLE,tn as ATTRIBUTES,rr as ATTRIBUTE_KEYS_REQUESTS,sn as ATTRIBUTE_VALUES,Nt as ActionInput,Gt as ActionItemCollectionInput,Ut as ActionItemInput,dt as AgentFileInput,gt as AgentFunctionInput,ct as AgentInput,tt as ApiKeyInput,Na as AssessmentAction,_t as AssessmentAnswerOptionInput,Vt as AssessmentDisplayLogicInput,Xt as AssessmentInput,La as AssessmentNestedRule,Ht as AssessmentNestedRuleInput,Kt as AssessmentResourceInput,Wt as AssessmentRetentionScheduleInput,Ia as AssessmentRiskLogic,Ma as AssessmentRule,jt as AssessmentRuleInput,Jt as AssessmentSectionInput,zt as AssessmentSectionQuestionInput,Zt as AssessmentTemplateInput,Op as AttestedExtraIdentifiers,it as AttributeInput,mt as AttributePreview,pt as AttributeValueInput,na as BLANK,ra as BULK_APPLY,kn as BUSINESS_ENTITIES,bt as BusinessEntityInput,ur as CANCEL_PRIVACY_REQUEST,pa as CAN_APPLY_IN_BULK,Be as CATALOGS,Gr as CHANGE_REQUEST_DATA_SILO_STATUS,ar as CODE_PACKAGES,Sn as CONSENT_MANAGER_ANALYTICS_DATA,cn as CONSENT_PARTITIONS,hn as COOKIES,Hn as CREATE_ACTION_ITEMS,Xr as CREATE_ACTION_ITEM_COLLECTION,Kn as CREATE_AGENT,ts as CREATE_AGENT_FILE,ns as CREATE_AGENT_FUNCTION,We as CREATE_API_KEY,on as CREATE_ATTRIBUTE,en as CREATE_ATTRIBUTE_VALUES,Bn as CREATE_BUSINESS_ENTITY,ir as CREATE_CODE_PACKAGE,Dn as CREATE_CONSENT_EXPERIENCE,An as CREATE_CONSENT_MANAGER,$n as CREATE_CONSENT_PARTITION,gn as CREATE_DATA_FLOWS,Oe as CREATE_DATA_SILOS,He as CREATE_DATA_SUBJECT,ms as CREATE_DATA_SUB_CATEGORY,Se as CREATE_ENRICHER,Ge as CREATE_IDENTIFIER,ds as CREATE_PROCESSING_PURPOSE_SUB_CATEGORY,$r as CREATE_PROMPT,Fr as CREATE_PROMPT_GROUP,kr as CREATE_PROMPT_PARTIAL,ze as CREATE_REPOSITORY,or as CREATE_SOFTWARE_DEVELOPMENT_KIT,Vr as CREATE_TEAM,tr as CREATE_TEMPLATE,as as CREATE_VENDOR,ia as CachedFileState,ca as CachedRequestState,Ct as CodePackageInput,Rt as CodePackageSdk,oa as ColumnName,Dt as ConsentManageExperienceInput,St as ConsentManagerInput,Ss as ConsentManagerMetricBin,ae as ConsentManagerServiceMetadata,li as ConsentPreferenceResponse,te as ConsentPreferenceTopic,Yt as ConsentPreferenceTopicOptionValue,ee as ConsentPurpose,oe as CookieCsvInput,Ot as CookieInput,bi as CronIdentifier,Ei as CronIdentifierPush,Ce as DATAPOINT_EXPORT,un as DATA_FLOWS,Ae as DATA_POINTS,ye as DATA_POINT_COUNT,Le as DATA_SILOS,Ee as DATA_SILOS_ENRICHED,Ne as DATA_SILO_EXPORT,je as DATA_SUBJECTS,is as DATA_SUB_CATEGORIES,N as DEFAULT_TRANSCEND_API,Rp as DEFAULT_TRANSCEND_CONSENT_API,Sa as DEFAULT_TRANSCEND_PULL_RESOURCES,Ze as DELETE_API_KEY,nn as DELETE_ATTRIBUTE_VALUE,qn as DEPLOYED_PRIVACY_CENTER_URL,bn as DEPLOY_CONSENT_MANAGER,zn as DETERMINE_LOGIN_METHOD,ot as DataCategoryGuessInput,ut as DataCategoryInput,st as DataCategoryPreviewInput,at as DataCategoryRecommendationInput,se as DataFlowCsvInput,It as DataFlowInput,Qt as DataSiloInput,Lt as DataSubjectInput,yt as DatapointInput,Xe as ENABLED_PLUGINS,De as ENRICHERS,Me as ENTRY_COUNT,mn as EXPERIENCES,ji as EnrichPrivacyRequest,rt as EnricherInput,Pn as FETCH_CONSENT_MANAGER,fn as FETCH_CONSENT_MANAGER_ID,Tn as FETCH_CONSENT_MANAGER_THEME,Vn as FETCH_PRIVACY_CENTER_ID,At as FieldInput,Un as GLOBAL_ACTION_ITEMS,Kr as GLOBAL_ACTION_ITEM_COLLECTIONS,Fe as IDENTIFIERS,sa as IDENTIFIER_BLOCK_LIST,Rr as IMPORT_ONE_TRUST_ASSESSMENT_FORMS,$e as INITIALIZER,mi as IP_ADDRESS_REGEX,aa as IS_REQUIRED,Et as IdentifierInput,le as ImportOnetrustAssessmentsInput,kp as IntlMessage,Ft as IntlMessageInput,b as LARGE_LANGUAGE_MODELS,Jn as LOGIN,Pr as MESSAGES,Qe as NEW_IDENTIFIER_TYPES,ea as NONE,fr as NOTIFY_ADDITIONAL_TIME,er as ORGANIZATION,q as OneTrustFileFormat,v as OneTrustPullResource,_ as OneTrustPullSource,ie as OpenAIEnabledRoute,me as OpenAIEnabledRoutes,ce as OpenAIIntegration,W as OpenAIRouteName,cr as POLICIES,Mr as PREFERENCE_TOPICS,vn as PRIVACY_CENTER,gs as PROCESSING_PURPOSE_SUB_CATEGORIES,Nr as PROMPTS,Or as PROMPTS_WITH_VARIABLES,Ir as PROMPT_GROUPS,Er as PROMPT_PARTIALS,mr as PROMPT_THREADS,Cr as PURPOSES,ha as ParsedAttributeInput,$t as PartitionInput,ge as PathfinderPolicy,J as PathfinderPolicyName,pe as PathfinderPolicyNameC,de as PathfinderPromptRunMetadata,Bt as PolicyInput,kt as PrivacyCenterInput,np as PrivacyRequest,Dp as PrivacyRequestInput,jp as PrivacyRequestResponse,ht as ProcessingPurposeInput,nt as ProcessingPurposePreviewInput,xt as PromptAVendorEmailSettings,Tt as PromptGroupInput,ft as PromptInput,Pt as PromptPartialInput,fi as PurposeMap,jr as REDUCED_REQUESTS_FOR_DATA_SILO_COUNT,vr as REMOVE_REQUEST_IDENTIFIERS,Wr as REPORT_PROMPT_RUN,ve as REPOSITORIES,dr as REQUESTS,Qr as REQUEST_DATA_SILOS,Ar as REQUEST_ENRICHERS,Jr as REQUEST_FILES,_r as REQUEST_IDENTIFIERS,Ur as RETRY_REQUEST_DATA_SILO,yr as RETRY_REQUEST_ENRICHER,Mt as RepositoryInput,Bp as RequestFileMetadata,Fp as RequestFileMetadataResponse,op as RequestIdentifiersResponse,qt as RiskAssignmentInput,vt as RiskLogicInput,pn as SET_RESOURCE_ATTRIBUTES,xr as SKIP_REQUEST_ENRICHER,nr as SOFTWARE_DEVELOPMENT_KITS,us as SOMBRA_VERSION,xe as SUB_DATA_POINTS,be as SUB_DATA_POINTS_COUNT,we as SUB_DATA_POINTS_WITH_GUESSES,po as SYNC_ATTRIBUTE_TYPES,wt as SoftwareDevelopmentKitInput,ne as StoredApiKey,ma as SuccessfulRequest,Hr as TEAMS,Ye as TEMPLATES,En as TOGGLE_CONSENT_PRECEDENCE,qe as TOGGLE_DATA_SUBJECT,Nn as TOGGLE_TELEMETRY_PARTITION_STRATEGY,Ln as TOGGLE_UNKNOWN_COOKIE_POLICY,Mn as TOGGLE_UNKNOWN_REQUEST_POLICY,Mp as TR_PULL_RESOURCE_SCOPE_MAP,Cp as TR_PUSH_RESOURCE_SCOPE_MAP,Lp as TR_YML_RESOURCE_TO_FIELD_NAME,et as TeamInput,X as TemplateInput,re as TranscendInput,$ as TranscendPromptManager,z as TranscendPullResource,Gn as UPDATE_ACTION,jn as UPDATE_ACTION_ITEMS,Yr as UPDATE_ACTION_ITEM_COLLECTION,Xn as UPDATE_AGENTS,es as UPDATE_AGENT_FILES,ss as UPDATE_AGENT_FUNCTIONS,an as UPDATE_ATTRIBUTE,rn as UPDATE_ATTRIBUTE_VALUES,Fn as UPDATE_BUSINESS_ENTITIES,pr as UPDATE_CODE_PACKAGES,On as UPDATE_CONSENT_EXPERIENCE,wn as UPDATE_CONSENT_MANAGER_DOMAINS,Rn as UPDATE_CONSENT_MANAGER_PARTITION,In as UPDATE_CONSENT_MANAGER_THEME,xn as UPDATE_CONSENT_MANAGER_TO_LATEST,yn as UPDATE_CONSENT_MANAGER_VERSION,dn as UPDATE_DATA_FLOWS,Ie as UPDATE_DATA_SILOS,Ve as UPDATE_DATA_SUBJECT,cs as UPDATE_DATA_SUB_CATEGORIES,ke as UPDATE_ENRICHER,Ue as UPDATE_IDENTIFIER,Tr as UPDATE_INTL_MESSAGES,ln as UPDATE_OR_CREATE_COOKIES,Re as UPDATE_OR_CREATE_DATA_POINT,gr as UPDATE_POLICIES,_n as UPDATE_PRIVACY_CENTER,hr as UPDATE_PRIVACY_REQUEST,ls as UPDATE_PROCESSING_PURPOSE_SUB_CATEGORIES,Dr as UPDATE_PROMPTS,Br as UPDATE_PROMPT_GROUPS,Sr as UPDATE_PROMPT_PARTIALS,_e as UPDATE_REPOSITORIES,sr as UPDATE_SOFTWARE_DEVELOPMENT_KITS,qr as UPDATE_TEAM,Cn as UPDATE_TOGGLE_USP_API,ps as UPDATE_VENDORS,zr as USERS,hi as USP_STRING_REGEX,he as VARIABLE_PARAMETERS_NAME,ue as VARIABLE_PARAMETERS_REGEXP,os as VENDORS,lt as VendorInput,Y as WebhookHeader,Ap as addMessagesToPromptRun,Ci as appendCsvSync,Vp as approvePrivacyRequests,dp as assumeRole,K as buildAIIntegrationType,Z as buildEnabledRouteType,M as buildTranscendGraphQLClient,Za as buildTranscendGraphQLClientGeneric,ci as buildXdiSyncEndpoint,Kp as bulkRestartRequests,Yp as bulkRetryEnrichers,_p as cancelPrivacyRequests,gi as consentManagersToBusinessEntities,Rs as convertToDataSubjectAllowlist,ws as convertToDataSubjectBlockList,Lo as createActionItemCollection,Oo as createActionItems,Ro as createAgent,Qo as createAgentFile,ko as createAgentFunction,up as createApiKey,co as createBusinessEntity,Ha as createCodePackage,di as createConsentToken,_o as createDataCategory,fo as createDataFlows,Zo as createProcessingPurpose,qs as createPrompt,U as createRegexForTag,Ga as createRepository,Ba as createSoftwareDevelopmentKit,Ka as createSombraGotInstance,cp as createTranscendConsentGotInstance,Ho as createVendor,hm as defineTranscendPrompts,hp as deleteApiKey,Pp as deployConsentManager,Ja as description,ii as domainToHost,Up as downloadPrivacyRequestFiles,Hi as enrichPrivacyRequest,bs as ensureAllDataSubjectsExist,Jp as extractClientError,ya as fetchActiveSiloDiscoPlugin,Io as fetchAllActionItems,xo as fetchAllActions,C as fetchAllAgentFiles,So as fetchAllAgentFunctions,h as fetchAllAgents,js as fetchAllApiKeys,Ca as fetchAllAssessmentTemplates,Ra as fetchAllAssessments,ao as fetchAllAttributeValues,io as fetchAllAttributes,mo as fetchAllBusinessEntities,_a as fetchAllCatalogs,wa as fetchAllCookies,vo as fetchAllDataCategories,uo as fetchAllDataFlows,Ls as fetchAllDataPoints,Cs as fetchAllDataSilos,xs as fetchAllDataSubjects,Ts as fetchAllEnrichers,hs as fetchAllIdentifiers,ba as fetchAllMessages,Ws as fetchAllPolicies,Da as fetchAllPreferenceTopics,xa as fetchAllPrivacyCenters,Wo as fetchAllProcessingPurposes,wo as fetchAllPromptGroups,bo as fetchAllPromptPartials,L as fetchAllPromptThreads,Vs as fetchAllPrompts,no as fetchAllPurposes,$a as fetchAllPurposesAndPreferences,rp as fetchAllRequestAttributeKeys,pp as fetchAllRequestEnrichers,tp as fetchAllRequestIdentifierMetadata,ap as fetchAllRequestIdentifiers,sp as fetchAllRequests,Ms as fetchAllSubDataPoints,Gs as fetchAllTeams,Ao as fetchAllTemplates,lp as fetchAllUsers,jo as fetchAllVendors,za as fetchAndIndexCatalogs,Hs as fetchApiKeys,Os as fetchConsentManager,ks as fetchConsentManagerAnalyticsData,$s as fetchConsentManagerExperiences,Ds as fetchConsentManagerId,Bs as fetchConsentManagerTheme,ui as fetchConsentPreferences,Ns as fetchEnrichedDataSilos,fs as fetchIdentifiersAndCreateMissing,eo as fetchPartitions,Js as fetchPrivacyCenterId,zs as fetchPrivacyCenterUrl,R as fetchPromptsWithVariables,mp as fetchRequestDataSilo,ep as fetchRequestDataSiloActiveCount,ip as fetchRequestDataSilos,fp as fetchRequestFilesForRequest,Am as filterNullishValuesFromObject,Aa as filterRows,da as fuzzyMatchColumns,ga as fuzzySearch,Si as generateCrossAccountApiKeys,Qp as getFileMetadataForPrivacyRequests,Rm as getGitFilesThatChanged,Ta as getUniqueValuesForColumn,yi as inquirerAutoComplete,Ti as inquirerConfirmBoolean,Ai as inquirerConfirmText,Fi as listDirectories,Bi as listFiles,gp as loginUser,w as makeGraphQLRequest,zp as mapColumnsToAttributes,vp as mapColumnsToIdentifiers,Ep as mapCsvColumnsToApi,Sp as mapCsvRowsToRequestInputs,la as mapEnumValues,Ip as mapRequestEnumValues,Ii as markCronIdentifierCompleted,Di as markRequestDataSiloIdsCompleted,Np as markSilentPrivacyRequests,ta as mergeTranscendInputs,yp as name,$p as normalizeIdentifierValue,qp as notifyPrivacyRequestsAdditionalTime,Ea as parseAssessmentDisplayLogic,Oa as parseAssessmentRiskLogic,fa as parseAttributesFromString,Li as parseFilePath,xi as parseVariablesFromString,Qi as pullAllDatapoints,$i as pullChunkedCustomSiloOutstandingIdentifiers,pi as pullConsentManagerMetrics,wi as pullCronPageOfIdentifiers,Ui as pullManualEnrichmentIdentifiersToCsv,ei as pullPrivacyRequests,ka as pullTranscendConfiguration,Gi as pullUnstructuredSubDataPointRecommendations,Oi as pushCronIdentifiersFromCsv,Vi as pushManualEnrichmentIdentifiersFromCsv,Pa as readCsv,Pe as readTranscendYaml,Pm as removeLinks,ni as removeUnverifiedRequestIdentifiers,fe as replaceVariablesInYaml,f as reportPromptRun,Zp as restartPrivacyRequest,ti as retryRequestDataSilos,Ya as retryRequestEnricher,Xa as setResourceAttributes,Xp as skipPreflightJobs,ri as skipRequestDataSilos,ua as splitCsvToList,Gp as streamPrivacyRequestFiles,Hp as submitPrivacyRequest,To as syncAction,Eo as syncActionItemCollections,$o as syncActionItems,Uo as syncAgentFiles,Fo as syncAgentFunctions,Mo as syncAgents,ys as syncAttribute,lo as syncBusinessEntities,qa as syncCodePackages,Yo as syncConfigurationToTranscend,oo as syncConsentManager,so as syncConsentManagerExperiences,Qs as syncCookies,Jo as syncDataCategories,Po as syncDataFlows,Is as syncDataSiloDependencies,Es as syncDataSilos,Us as syncDataSubject,As as syncEnricher,Ps as syncIdentifier,Ys as syncIntlMessages,ro as syncPartitions,Ks as syncPolicies,to as syncPrivacyCenter,Xo as syncProcessingPurposes,_s as syncPrompts,ja as syncRepositories,Qa as syncSoftwareDevelopmentKits,yo as syncTemplate,qo as syncVendors,Do as updateActionItem,No as updateActionItemCollection,Go as updateAgentFiles,Bo as updateAgentFunctions,Co as updateAgents,go as updateBusinessEntities,Va as updateCodePackages,Tp as updateConsentManagerToLatest,si as updateConsentManagerVersionToLatest,zo as updateDataCategories,ho as updateDataFlows,Xs as updateIntlMessages,Fs as updateOrCreateCookies,Zs as updatePolicies,Ko as updateProcessingPurposes,vs as updatePrompts,Ua as updateRepositories,Fa as updateSoftwareDevelopmentKits,Vo as updateVendors,Pi as uploadConsents,ai as uploadCookiesFromCsv,oi as uploadDataFlowsFromCsv,Wp as uploadPrivacyRequestsFromCsv,va as uploadSiloDiscoveryResults,ki as validateTranscendAuth,Wa as version,Mi as writeCsv,Ri as writeCsvSync,Ni as writeLargeCsv,Te as writeTranscendYaml};
|
|
5
|
-
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/ai/TranscendPromptManager.ts","../src/lib/graphql/fetchLargeLanguageModels.ts","../src/lib/ai/removeLinks.ts","../src/lib/ai/filterNullishValuesFromObject.ts","../src/lib/ai/getGitFilesThatChanged.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport {\n Optionalize,\n Requirize,\n apply,\n decodeCodec,\n getValues,\n} from '@transcend-io/type-utils';\nimport type { Handlebars } from '@transcend-io/handlebars-utils';\nimport { Secret } from '@transcend-io/secret-value';\nimport * as t from 'io-ts';\nimport { DEFAULT_TRANSCEND_API } from '../../constants';\nimport {\n Agent,\n AgentFile,\n AgentFileFilterBy,\n ReportPromptRunInput,\n buildTranscendGraphQLClient,\n fetchAllAgentFiles,\n fetchAllAgents,\n reportPromptRun,\n} from '../graphql';\nimport {\n HandlebarsInput,\n createHandlebarsWithHelpers,\n} from '@transcend-io/handlebars-utils';\nimport {\n TranscendPromptTemplated,\n TranscendPromptsAndVariables,\n fetchPromptsWithVariables,\n} from '../graphql/fetchPrompts';\nimport { GraphQLClient } from 'graphql-request';\nimport {\n PromptStatus,\n ChatCompletionRole,\n PromptRunProductArea,\n QueueStatus,\n LargeLanguageModelClient,\n} from '@transcend-io/privacy-types';\nimport {\n LargeLanguageModel,\n fetchAllLargeLanguageModels,\n} from '../graphql/fetchLargeLanguageModels';\nimport { groupBy, keyBy, uniq, chunk } from 'lodash-es';\nimport { mapSeries } from '@/lib/bluebird-replace';\nimport {\n PromptThread,\n fetchAllPromptThreads,\n} from '../graphql/fetchPromptThreads';\n\n/**\n * An LLM Prompt definition\n */\nexport type TranscendPrompt<\n TInputParams extends t.Any,\n TOutputCodec extends t.Any,\n> = (\n | {\n /** ID of the prompt */\n id: string;\n /** Title of the prompt */\n title?: string;\n }\n | {\n /** ID of the prompt */\n id?: string;\n /** Title of the prompt */\n title: string;\n }\n) & {\n /** The names of the agents that should be loaded along with the prompt */\n agentNames?: string[];\n /** Codec to validate runtime input shape */\n paramCodec: TInputParams;\n /** Codec to validate output response */\n outputCodec: TOutputCodec;\n /**\n * If the output that needs to be parsed is returned within a tag\n * e.g. <tag> or <json> - this is the name of the tag\n */\n extractFromTag?: string;\n};\n\nexport interface PromptRunResult {\n /** The ID of the prompt run created on Transcend */\n promptRunId: string;\n /** The URL of the prompt run on Transcend */\n promptRunUrl: string;\n}\n\n/**\n * Create a regex to extract data from a tag\n *\n * Input:\n * \"here is some data <tag>Data</tag>...\"\n *\n * @param tagName - Name of tag\n * @returns Data within the tag\n */\nexport function createRegexForTag(tagName: string): RegExp {\n return new RegExp(`<${tagName}>([\\\\s\\\\S]+?)<\\\\/${tagName}>`);\n}\n\n/**\n * Helper function to declare prompts\n *\n * @param prompts - Prompt config\n * @returns Prompts as identity function - but type enforced\n */\nexport function defineTranscendPrompts<\n TPromptNames extends string,\n TPrompts extends { [k in TPromptNames]: TranscendPrompt<t.Any, t.Any> },\n>(prompts: TPrompts): TPrompts {\n return prompts;\n}\n\n/**\n * Helper to get the type of the parameter for a given prompt\n */\nexport type GetPromptParamType<\n TPromptName extends keyof TPrompts,\n TPrompts extends { [k in TPromptName]: TranscendPrompt<t.Any, t.Any> },\n> = t.TypeOf<TPrompts[TPromptName]['paramCodec']>;\n\n/**\n * Helper to get the type of the parameter for a given prompt\n */\nexport type GetPromptResponseType<\n TPromptName extends keyof TPrompts,\n TPrompts extends { [k in TPromptName]: TranscendPrompt<t.Any, t.Any> },\n> = t.TypeOf<TPrompts[TPromptName]['outputCodec']>;\n\n/**\n * Input for reporting a prompt run\n */\nexport interface ReportPromptRunOptions\n extends Optionalize<\n Omit<ReportPromptRunInput, 'status' | 'promptId' | 'largeLanguageModelId'>,\n 'name' | 'productArea'\n > {\n /** The large language model being run. Either the ID of the LLM or the client/name pairing */\n largeLanguageModel:\n | string\n | {\n /** Name of client */\n client: LargeLanguageModelClient;\n /** Name of the model */\n name: string;\n };\n}\n\nconst jsonParseSafe = (obj: string): unknown => {\n try {\n return JSON.parse(obj);\n } catch (e) {\n return obj;\n }\n};\n\n/**\n * A class that is capable of loading and insert variables into prompts from\n * Transcend's Prompt Manager\n */\nexport class TranscendPromptManager<\n TPromptNames extends string,\n TPrompts extends { [k in TPromptNames]: TranscendPrompt<t.Any, t.Any> },\n> {\n /** Prompt definitions */\n public prompts: TPrompts;\n\n /** Options for configuring handlebars */\n public handlebarsOptions!: HandlebarsInput;\n\n /** Prompt name -> content map, populated by call to Transcend API */\n public promptContentMap?: { [k in TPromptNames]: TranscendPromptTemplated };\n\n /** The large language models that are registered to this organization for reporting */\n public largeLanguageModels: LargeLanguageModel[] = [];\n\n /** The agent definitions registered to this organization */\n private agentsByName: { [name in string]: Agent } = {};\n\n /** The agent definitions registered to this organization */\n private agentsByAgentId: { [id in string]: Agent } = {};\n\n /** The GraphQL client that can be used to call Transcend */\n public graphQLClient: GraphQLClient;\n\n /** The set of variables to expose in handlebars context specified at class initiation */\n public defaultVariables: { [k in string]: unknown };\n\n /**\n * The set of variables to expose in handlebars context,\n * merges defaults with calculated variables from the inventory\n */\n public variables: { [k in string]: unknown };\n\n /** Handlebars compiler */\n public handlebars: typeof Handlebars;\n\n /** The Transcend API key */\n public transcendApiKey: string | Secret<string>;\n\n /** API of Transcend to call */\n public transcendUrl: string;\n\n /** When true, throw an error if the prompt is not approved */\n public requireApproval: boolean;\n\n /**\n * The cache duration in ms for how long prompts and associated metadata should be cached\n * When undefined - prompts are cached indefinitely unless explicitly re-requested\n * When 0, prompts and metadata are fetched every time (not recommended)\n * Setting this to be an hour is a good rate that optimizes for performance and keeping up to date\n */\n public cacheDuration?: number;\n\n /**\n * The last time the metadata was fetched\n */\n public lastUpdatedAt?: Date;\n\n /**\n * Constructor\n *\n * @param options - Options\n */\n constructor({\n prompts,\n handlebarsOptions = {},\n transcendUrl = DEFAULT_TRANSCEND_API,\n transcendApiKey,\n requireApproval = true,\n cacheDuration,\n defaultVariables = {},\n }: {\n /** Prompt definitions to load */\n prompts: TPrompts;\n /** Options for configuring handlebars */\n handlebarsOptions?: HandlebarsInput;\n /** The Transcend API key */\n transcendApiKey: string | Secret<string>;\n /** API of Transcend to call */\n transcendUrl?: string;\n /** When true, throw an error if the prompt is not approved */\n requireApproval?: boolean;\n /** The set of variables to expose in handlebars context specified at class initiation */\n defaultVariables?: { [k in string]: unknown };\n /**\n * The cache duration in ms for how long prompts and associated metadata should be cached\n * When undefined - prompts are cached indefinitely unless explicitly re-requested\n * When 0, prompts and metadata are fetched every time (not recommended)\n * Setting this to be an hour is a good rate that optimizes for performance and keeping up to date\n */\n cacheDuration?: number;\n }) {\n this.prompts = prompts;\n this.transcendUrl = transcendUrl;\n this.transcendApiKey = transcendApiKey;\n this.variables = defaultVariables;\n this.defaultVariables = defaultVariables;\n this.graphQLClient = buildTranscendGraphQLClient(\n transcendUrl,\n typeof transcendApiKey === 'object'\n ? transcendApiKey.release()\n : transcendApiKey,\n );\n this.requireApproval = requireApproval;\n this.cacheDuration = cacheDuration;\n this.handlebarsOptions = handlebarsOptions;\n this.handlebars = createHandlebarsWithHelpers(handlebarsOptions);\n }\n\n /**\n * Fetch prompt metadata from Transcend and cache to the class definition\n *\n * @returns A function that can be used to call the prompt\n */\n async fetchPromptsAndMetadata(): Promise<TranscendPromptsAndVariables> {\n // Determine what to fetch\n const promptDefinitions = getValues(this.prompts) as TranscendPrompt<\n t.Any,\n t.Any\n >[];\n const promptIds = promptDefinitions\n .map(({ id }) => id)\n .filter((x): x is string => !!x);\n const promptTitles = promptDefinitions\n .map(({ title }) => title)\n .filter((x): x is string => !!x);\n const agentNames = uniq(\n promptDefinitions.map(({ agentNames }) => agentNames || []).flat(),\n );\n\n // Fetch prompts and data\n const [response, largeLanguageModels, agents] = await Promise.all([\n fetchPromptsWithVariables(this.graphQLClient, {\n promptIds,\n promptTitles,\n }),\n fetchAllLargeLanguageModels(this.graphQLClient),\n fetchAllAgents(this.graphQLClient, { names: agentNames }),\n ]);\n this.agentsByName = keyBy(agents, 'name');\n this.agentsByAgentId = keyBy(agents, 'agentId');\n this.largeLanguageModels = largeLanguageModels.filter(\n (model) => model.isTranscendHosted === false,\n );\n\n // Lookup prompts by id/title\n const promptByTitle = keyBy(response.prompts, 'title');\n const promptById = keyBy(response.prompts, 'id');\n\n // Update variables\n this.variables = {\n ...response.calculatedVariables.reduce(\n (acc, v) =>\n Object.assign(acc, {\n [v.name]: v.data ? JSON.parse(v.data) : v.data,\n }),\n {},\n ),\n ...this.defaultVariables,\n };\n\n // Update partials\n this.handlebars = createHandlebarsWithHelpers({\n ...this.handlebarsOptions,\n templates: [\n ...(this.handlebarsOptions.templates || []),\n ...response.promptPartials.map((partial) => ({\n name: partial.slug,\n content: partial.content,\n })),\n ],\n });\n\n // Create mapping from prompt to content\n this.promptContentMap = apply(this.prompts, ({ id, title }) => {\n const result = id\n ? promptById[id]\n : title\n ? promptByTitle[title]\n : undefined;\n if (!result) {\n throw new Error(\n `Failed to find prompt with title: \"${title}\" and id: \"${id}\"`,\n );\n }\n return result;\n });\n\n // For cache\n this.lastUpdatedAt = new Date();\n\n return response;\n }\n\n /**\n * Get an agent definition by name\n *\n * @param name - Name of the agent to grab\n * @returns Large language model configuration\n */\n async getAgentByName(name: string): Promise<Agent | undefined> {\n const agent = this.agentsByName[name];\n if (agent) {\n return agent;\n }\n const [remoteAgent] = await fetchAllAgents(this.graphQLClient, {\n names: [name],\n });\n if (!remoteAgent) {\n return undefined;\n }\n this.agentsByName[remoteAgent.name] = remoteAgent;\n this.agentsByAgentId[remoteAgent.agentId] = remoteAgent;\n return remoteAgent;\n }\n\n /**\n * Get a prompt thread by ts\n *\n * @param ts - the slack message timestamp to look up thread for\n * @returns Large language model configuration\n */\n async getPromptThreadBySlackTs(\n ts: string,\n ): Promise<PromptThread | undefined> {\n const [thread] = await fetchAllPromptThreads(this.graphQLClient, {\n slackMessageTs: [ts],\n });\n return thread;\n }\n\n /**\n * Get a list of agent definitions by name.\n * Pulls from cache and may return less agents\n * than requested if some are not found\n *\n * @param names - Names of agents to fetch\n * @returns The agents that were found matching the names\n */\n async getAgentsByName(names: string[]): Promise<Agent[]> {\n if (names.length < 1) {\n throw new Error('Expected at least one name to be provided');\n }\n const { hasCache = [], missingCache = [] } = groupBy(names, (name) =>\n this.agentsByName[name] ? 'hasCache' : 'missingCache',\n );\n const cachedAgents = hasCache.map((name) => this.agentsByName[name]);\n if (missingCache.length === 0) {\n return cachedAgents;\n }\n const chunkedNames = chunk(missingCache, 50);\n const remoteAgents: Agent[] = [];\n await mapSeries(chunkedNames, async (chunkedName) => {\n const pageOfAgents = await fetchAllAgents(this.graphQLClient, {\n names: chunkedName,\n });\n pageOfAgents.forEach((agent) => {\n this.agentsByName[agent.name] = agent;\n this.agentsByAgentId[agent.agentId] = agent;\n });\n remoteAgents.push(...pageOfAgents);\n });\n return [...cachedAgents, ...remoteAgents];\n }\n\n /**\n * Fetch metadata on agent files\n *\n * @param filterBy - Filter by parameters\n * @returns The files found matching the filter\n */\n getAgentFiles(filterBy: AgentFileFilterBy): Promise<AgentFile[]> {\n return fetchAllAgentFiles(this.graphQLClient, filterBy);\n }\n\n /**\n * Look up the large language model to report on\n *\n * @param largeLanguageModel - Input\n * @returns Large language model configuration\n */\n getLargeLanguageModel(\n largeLanguageModel: ReportPromptRunOptions['largeLanguageModel'],\n ): LargeLanguageModel {\n const matching = this.largeLanguageModels.find((model) =>\n typeof largeLanguageModel === 'string'\n ? model.id === largeLanguageModel\n : model.name === largeLanguageModel.name &&\n model.client === largeLanguageModel.client,\n );\n if (!matching) {\n throw new Error(\n `Failed to find model matching: ${\n typeof largeLanguageModel === 'string'\n ? largeLanguageModel\n : JSON.stringify(largeLanguageModel)\n }`,\n );\n }\n return matching;\n }\n\n /**\n * Get a prompt definition by name\n *\n * @param promptName - Prompt to compile\n * @returns Parsed content\n */\n async getPromptDefinition<TPromptName extends TPromptNames>(\n promptName: TPromptName,\n ): Promise<TranscendPromptTemplated> {\n // Determine if prompts need to be fetched\n if (\n // never been fetched\n !this.lastUpdatedAt ||\n // fetch every run\n this.cacheDuration === 0 ||\n // If cache duration met\n (this.cacheDuration &&\n Date.now() - this.lastUpdatedAt.getTime() > this.cacheDuration)\n ) {\n await this.fetchPromptsAndMetadata();\n }\n\n // Lookup prompt\n const { promptContentMap } = this;\n if (!promptContentMap) {\n throw new Error('Expected this.promptContentMap to be defined');\n }\n const promptTemplate = promptContentMap[promptName];\n if (!promptTemplate) {\n throw new Error(\n `Expected this.promptContentMap[${promptName}] to be defined`,\n );\n }\n return promptTemplate;\n }\n\n /**\n * Validate the shape of the response from AI\n *\n * @param promptName - Prompt to compile\n * @param params - Runtime parameters\n * @returns Parsed content\n */\n async compilePrompt<TPromptName extends TPromptNames>(\n promptName: TPromptName,\n params: t.TypeOf<TPrompts[TPromptName]['paramCodec']>,\n ): Promise<string> {\n // Grab the prompt\n const promptTemplate = await this.getPromptDefinition(promptName);\n const promptInput = this.prompts[promptName];\n if (!promptInput) {\n throw new Error(`Expected this.prompts[${promptName}] to be defined`);\n }\n\n // Ensure prompt is approved\n if (\n this.requireApproval &&\n promptTemplate.status !== PromptStatus.Approved\n ) {\n throw new Error(\n `Assessment \"${promptTemplate.title}\" cannot be used because its in status: \"${promptTemplate.status}\"`,\n );\n }\n\n // If prompt is rejected, throw error\n if (promptTemplate.status === PromptStatus.Rejected) {\n throw new Error(\n `Assessment \"${promptTemplate.title}\" cannot be used because it's in status: \"${promptTemplate.status}\"`,\n );\n }\n\n // Validate params\n decodeCodec(promptInput.paramCodec, params);\n\n // Compile prompt and template\n return this.handlebars.compile(promptTemplate.content)({\n // template in currentDate by default\n currentDate: new Date().toISOString(),\n ...this.variables,\n ...params,\n });\n }\n\n /**\n * Validate the shape of the response from AI\n *\n * @param promptName - Prompt to parse\n * @param response - AI response as string\n * @returns Parsed content\n */\n parseAiResponse<TPromptName extends TPromptNames>(\n promptName: TPromptName,\n response: string,\n ): t.TypeOf<TPrompts[TPromptName]['outputCodec']> {\n // Look up prompt info\n const promptInput = this.prompts[promptName];\n if (!promptInput) {\n throw new Error(`Expected this.prompts[${promptName}] to be defined`);\n }\n\n // Extract from tag if needed\n const extracted = promptInput.extractFromTag\n ? (createRegexForTag(promptInput.extractFromTag).exec(response) ||\n [])[1] || response\n : response;\n\n // Parse via codec\n return decodeCodec(\n promptInput.outputCodec,\n jsonParseSafe(extracted),\n false,\n );\n }\n\n /**\n * Parse the AI response and report back to Transcend\n *\n * @param promptName - Prompt to parse\n * @param options - Options for reporting\n * @returns Parsed content\n */\n async reportAndParsePromptRun<TPromptName extends TPromptNames>(\n promptName: TPromptName,\n { largeLanguageModel, ...options }: ReportPromptRunOptions,\n ): Promise<\n PromptRunResult & {\n /** Resulting prompt run */\n result: t.TypeOf<TPrompts[TPromptName]['outputCodec']>;\n }\n > {\n // Determine if prompts need to be fetched\n if (\n // never been fetched\n !this.lastUpdatedAt ||\n // fetch every run\n this.cacheDuration === 0 ||\n // If cache duration met\n (this.cacheDuration &&\n Date.now() - this.lastUpdatedAt.getTime() > this.cacheDuration)\n ) {\n await this.fetchPromptsAndMetadata();\n }\n\n const name =\n options.name ||\n `@transcend-io/cli-prompt-run-${new Date().toISOString()}`;\n\n if (!this.promptContentMap) {\n throw new Error('Expected this.promptContentMap to be defined');\n }\n // Look up prompt info\n const promptInput = this.promptContentMap[promptName];\n if (!promptInput) {\n throw new Error(`Expected this.prompts[${promptName}] to be defined`);\n }\n\n // Ensure the first message in `promptRunMessages` is of type=system\n if (options.promptRunMessages.length === 0) {\n throw new Error('promptRunMessages is expected to have length > 0');\n }\n if (options.promptRunMessages[0].role !== ChatCompletionRole.System) {\n throw new Error(\n `promptRunMessages[0].role is expected to be = ${ChatCompletionRole.System}`,\n );\n }\n if (\n options.promptRunMessages[options.promptRunMessages.length - 1].role !==\n ChatCompletionRole.Assistant\n ) {\n throw new Error(\n `promptRunMessages[${\n options.promptRunMessages.length - 1\n }].role is expected to be = ${ChatCompletionRole.Assistant}`,\n );\n }\n const response =\n options.promptRunMessages[options.promptRunMessages.length - 1].content;\n\n let parsed: t.TypeOf<TPrompts[TPromptName]['outputCodec']>;\n try {\n // Parse the response\n parsed = this.parseAiResponse(promptName, response);\n } catch (err) {\n await reportPromptRun(this.graphQLClient, {\n productArea: PromptRunProductArea.PromptManager,\n ...options,\n name,\n error: err.message,\n status: QueueStatus.Error,\n ...(typeof largeLanguageModel === 'string'\n ? { largeLanguageModelId: largeLanguageModel }\n : {\n largeLanguageModelName: largeLanguageModel.name,\n largeLanguageModelClient: largeLanguageModel.client,\n }),\n promptId: promptInput.id,\n promptRunMessages: options.promptRunMessages.map((message, ind) => ({\n ...message,\n ...(ind === 0 ? { template: promptInput.content } : {}),\n })),\n });\n throw err;\n }\n\n // report successful run\n const promptRunId = await reportPromptRun(this.graphQLClient, {\n productArea: PromptRunProductArea.PromptManager,\n ...options,\n name,\n status: QueueStatus.Resolved,\n ...(typeof largeLanguageModel === 'string'\n ? { largeLanguageModelId: largeLanguageModel }\n : {\n largeLanguageModelName: largeLanguageModel.name,\n largeLanguageModelClient: largeLanguageModel.client,\n }),\n promptId: promptInput.id,\n promptRunMessages: options.promptRunMessages.map((message, ind) => ({\n ...message,\n ...(ind === 0 ? { template: promptInput.content } : {}),\n })),\n });\n\n return {\n result: parsed,\n promptRunId,\n promptRunUrl: `https://app.transcend.io/prompts/runs/${promptRunId}`,\n };\n }\n\n /**\n * Report an error for a particular prompt\n *\n * @param promptName - Prompt to parse\n * @param options - Options for reporting\n * @returns Parsed content\n */\n async reportPromptRunError<TPromptName extends TPromptNames>(\n promptName: TPromptName,\n {\n largeLanguageModel,\n ...options\n }: Requirize<ReportPromptRunOptions, 'error'>,\n ): Promise<PromptRunResult> {\n // Determine if prompts need to be fetched\n if (\n // never been fetched\n !this.lastUpdatedAt ||\n // fetch every run\n this.cacheDuration === 0 ||\n // If cache duration met\n (this.cacheDuration &&\n Date.now() - this.lastUpdatedAt.getTime() > this.cacheDuration)\n ) {\n await this.fetchPromptsAndMetadata();\n }\n\n const name =\n options.name ||\n `@transcend-io/cli-prompt-run-${new Date().toISOString()}`;\n\n if (!this.promptContentMap) {\n throw new Error('Expected this.promptContentMap to be defined');\n }\n // Look up prompt info\n const promptInput = this.promptContentMap[promptName];\n if (!promptInput) {\n throw new Error(`Expected this.prompts[${promptName}] to be defined`);\n }\n\n // Ensure the first message in `promptRunMessages` is of type=system\n if (options.promptRunMessages.length === 0) {\n throw new Error('promptRunMessages is expected to have length > 0');\n }\n if (options.promptRunMessages[0].role !== ChatCompletionRole.System) {\n throw new Error(\n `promptRunMessages[0].role is expected to be = ${ChatCompletionRole.System}`,\n );\n }\n\n const promptRunId = await reportPromptRun(this.graphQLClient, {\n productArea: PromptRunProductArea.PromptManager,\n ...options,\n name,\n status: QueueStatus.Error,\n ...(typeof largeLanguageModel === 'string'\n ? { largeLanguageModelId: largeLanguageModel }\n : {\n largeLanguageModelName: largeLanguageModel.name,\n largeLanguageModelClient: largeLanguageModel.client,\n }),\n promptId: promptInput.id,\n promptRunMessages: options.promptRunMessages.map((message, ind) => ({\n ...message,\n ...(ind === 0 ? { template: promptInput.content } : {}),\n })),\n });\n\n return {\n promptRunId,\n promptRunUrl: `https://app.transcend.io/prompts/runs/${promptRunId}`,\n };\n }\n}\n/* eslint-enable max-lines */\n","import { GraphQLClient } from 'graphql-request';\nimport { LargeLanguageModelClient } from '@transcend-io/privacy-types';\nimport { LARGE_LANGUAGE_MODELS } from './gqls';\nimport { makeGraphQLRequest } from './makeGraphQLRequest';\n\nexport interface LargeLanguageModel {\n /** ID of prompts */\n id: string;\n /** The name of the large language model. */\n name: string;\n /** The content of the prompt template. */\n client: LargeLanguageModelClient;\n /** Whether hosted by Transcend or not */\n isTranscendHosted: boolean;\n}\n\nconst PAGE_SIZE = 20;\n\n/**\n * Fetch all LargeLanguageModels in the organization\n *\n * @param client - GraphQL client\n * @returns All LargeLanguageModels in the organization\n */\nexport async function fetchAllLargeLanguageModels(\n client: GraphQLClient,\n): Promise<LargeLanguageModel[]> {\n const largeLanguageModels: LargeLanguageModel[] = [];\n let offset = 0;\n\n // Whether to continue looping\n let shouldContinue = false;\n do {\n const {\n largeLanguageModels: { nodes },\n } = await makeGraphQLRequest<{\n /** LargeLanguageModels */\n largeLanguageModels: {\n /** List */\n nodes: LargeLanguageModel[];\n };\n }>(client, LARGE_LANGUAGE_MODELS, {\n first: PAGE_SIZE,\n offset,\n });\n largeLanguageModels.push(...nodes);\n offset += PAGE_SIZE;\n shouldContinue = nodes.length === PAGE_SIZE;\n } while (shouldContinue);\n\n return largeLanguageModels.sort((a, b) => a.name.localeCompare(b.name));\n}\n","/**\n * Remove links from a string\n *\n * @param inputString - String\n * @returns String without links\n */\nexport function removeLinks(inputString: string): string {\n const regex = /(https?:\\/\\/[^\\s]+)/g;\n return inputString.replace(regex, '<link-omitted>');\n}\n","import { ObjByString } from '@transcend-io/type-utils';\n\n/**\n * Given an object, remove all keys that are null-ish\n *\n * @param obj - Object\n * @returns Object with null-ish values removed\n */\nexport function filterNullishValuesFromObject<T extends ObjByString>(\n obj: T,\n): T {\n return Object.entries(obj).reduce(\n (acc, [k, v]) =>\n v !== null &&\n v !== undefined &&\n v !== '' &&\n !(Array.isArray(v) && v.length === 0) &&\n !(typeof v === 'object' && Object.keys(v).length === 0)\n ? Object.assign(acc, { [k]: v })\n : acc,\n {} as T,\n );\n}\n","import { difference } from 'lodash-es';\nimport fastGlob from 'fast-glob';\nimport { execSync } from 'child_process';\n\n/**\n * Function thats gets the git files that have changed\n * and returns the code\n *\n * @param options - Options\n * @returns Changes files and diffs\n */\nexport function getGitFilesThatChanged({\n baseBranch,\n rootDirectory,\n githubRepo,\n excludedGlob = [],\n fileBlockList = [],\n}: {\n /** Base branch */\n baseBranch: string;\n /** Github repo name */\n githubRepo: string;\n /** Root directory */\n rootDirectory: string;\n /** A glob that excludes files */\n excludedGlob?: string[];\n /** Block list of files to not process */\n fileBlockList?: string[];\n}): {\n /** The list of files that changed */\n changedFiles: string[];\n /** Github repo name */\n repoName: string;\n /** Current commit */\n commit: string;\n /** File diffs */\n fileDiffs: { [k in string]: string };\n} {\n // Pull base branch\n execSync(`git fetch origin ${baseBranch}`);\n\n // Latest commit on base branch. If we are on the base branch, we take the prior commit\n const latestBasedCommit = execSync(\n `git ls-remote ${githubRepo} \"refs/heads/${baseBranch}\" | cut -f 1`,\n { encoding: 'utf-8' },\n ).split('\\n')[0];\n\n // This commit\n const latestThisCommit = execSync('git rev-parse HEAD', {\n encoding: 'utf-8',\n }).split('\\n')[0];\n\n // Ensure commits are present\n if (!latestBasedCommit || !latestThisCommit) {\n throw new Error('FAILED TO FIND COMMIT RANGE');\n }\n\n // Get the diff between the given branch and base branch\n const diff = execSync(\n `git fetch && git diff --name-only \"${\n baseBranch || latestBasedCommit\n }...${latestThisCommit}\" -- ${rootDirectory}`,\n { encoding: 'utf-8' },\n );\n\n // Filter out block list\n const changedFiles = difference(\n diff.split('\\n').filter((f) => f),\n fileBlockList,\n );\n\n // Filter out globs\n const filteredChanges =\n excludedGlob.length > 0\n ? fastGlob.sync(changedFiles, { ignore: excludedGlob })\n : changedFiles;\n\n // Get the contents of only the changed files\n const fileDiffs: { [k in string]: string } = {};\n filteredChanges.forEach((file) => {\n const contents = execSync(`git show ${latestThisCommit}:${file}`, {\n encoding: 'utf-8',\n });\n fileDiffs[file] = contents;\n });\n\n // Pull the github repo name\n const repoName = githubRepo.split('/').pop()!.split('.')[0];\n\n return {\n changedFiles,\n fileDiffs,\n repoName,\n commit: latestThisCommit,\n };\n}\n"],"mappings":"2tJACA,OAGE,SAAAA,EACA,eAAAC,EACA,aAAAC,MACK,2BAeP,OAEE,+BAAAC,MACK,iCAOP,OACE,gBAAAC,EACA,sBAAAC,EACA,wBAAAC,EACA,eAAAC,MAEK,8BCtBP,IAAMC,EAAY,GAQlB,eAAsBC,EACpBC,EAC+B,CAC/B,IAAMC,EAA4C,CAAC,EAC/CC,EAAS,EAGTC,EAAiB,GACrB,EAAG,CACD,GAAM,CACJ,oBAAqB,CAAE,MAAAC,CAAM,CAC/B,EAAI,MAAMC,EAMPL,EAAQM,EAAuB,CAChC,MAAOR,EACP,OAAAI,CACF,CAAC,EACDD,EAAoB,KAAK,GAAGG,CAAK,EACjCF,GAAUJ,EACVK,EAAiBC,EAAM,SAAWN,CACpC,OAASK,GA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C7BF,EACN,CAAC,CACH,CACF,CCtBA,OAAS,cAAAG,MAAkB,YAC3B,OAAOC,MAAc,YACrB,OAAS,YAAAC,MAAgB,gBASlB,SAASC,GAAuB,CACrC,WAAAC,EACA,cAAAC,EACA,WAAAC,EACA,aAAAC,EAAe,CAAC,EAChB,cAAAC,EAAgB,CAAC,CACnB,EAoBE,CAEAN,EAAS,oBAAoBE,CAAU,EAAE,EAGzC,IAAMK,EAAoBP,EACxB,iBAAiBI,CAAU,gBAAgBF,CAAU,eACrD,CAAE,SAAU,OAAQ,CACtB,EAAE,MAAM;AAAA,CAAI,EAAE,CAAC,EAGTM,EAAmBR,EAAS,qBAAsB,CACtD,SAAU,OACZ,CAAC,EAAE,MAAM;AAAA,CAAI,EAAE,CAAC,EAGhB,GAAI,CAACO,GAAqB,CAACC,EACzB,MAAM,IAAI,MAAM,6BAA6B,EAI/C,IAAMC,EAAOT,EACX,sCACEE,GAAcK,CAChB,MAAMC,CAAgB,QAAQL,CAAa,GAC3C,CAAE,SAAU,OAAQ,CACtB,EAGMO,EAAeZ,EACnBW,EAAK,MAAM;AAAA,CAAI,EAAE,OAAQE,GAAMA,CAAC,EAChCL,CACF,EAGMM,EACJP,EAAa,OAAS,EAClBN,EAAS,KAAKW,EAAc,CAAE,OAAQL,CAAa,CAAC,EACpDK,EAGAG,EAAuC,CAAC,EAC9CD,EAAgB,QAASE,GAAS,CAChC,IAAMC,EAAWf,EAAS,YAAYQ,CAAgB,IAAIM,CAAI,GAAI,CAChE,SAAU,OACZ,CAAC,EACDD,EAAUC,CAAI,EAAIC,CACpB,CAAC,EAGD,IAAMC,EAAWZ,EAAW,MAAM,GAAG,EAAE,IAAI,EAAG,MAAM,GAAG,EAAE,CAAC,EAE1D,MAAO,CACL,aAAAM,EACA,UAAAG,EACA,SAAAG,EACA,OAAQR,CACV,CACF","names":["apply","decodeCodec","getValues","createHandlebarsWithHelpers","PromptStatus","ChatCompletionRole","PromptRunProductArea","QueueStatus","PAGE_SIZE","fetchAllLargeLanguageModels","client","largeLanguageModels","offset","shouldContinue","nodes","makeGraphQLRequest","LARGE_LANGUAGE_MODELS","a","b","groupBy","keyBy","uniq","chunk","createRegexForTag","tagName","defineTranscendPrompts","prompts","jsonParseSafe","obj","TranscendPromptManager","handlebarsOptions","transcendUrl","DEFAULT_TRANSCEND_API","transcendApiKey","requireApproval","cacheDuration","defaultVariables","buildTranscendGraphQLClient","createHandlebarsWithHelpers","promptDefinitions","getValues","promptIds","id","x","promptTitles","title","agentNames","uniq","response","largeLanguageModels","agents","fetchPromptsWithVariables","fetchAllLargeLanguageModels","fetchAllAgents","keyBy","model","promptByTitle","promptById","acc","v","partial","apply","result","name","agent","remoteAgent","ts","thread","fetchAllPromptThreads","names","hasCache","missingCache","groupBy","cachedAgents","chunkedNames","chunk","remoteAgents","mapSeries","chunkedName","pageOfAgents","filterBy","fetchAllAgentFiles","largeLanguageModel","matching","promptName","promptContentMap","promptTemplate","params","promptInput","PromptStatus","decodeCodec","extracted","options","ChatCompletionRole","parsed","err","reportPromptRun","PromptRunProductArea","QueueStatus","message","ind","promptRunId","removeLinks","inputString","regex","filterNullishValuesFromObject","obj","acc","k","v","difference","fastGlob","execSync","getGitFilesThatChanged","baseBranch","rootDirectory","githubRepo","excludedGlob","fileBlockList","latestBasedCommit","latestThisCommit","diff","changedFiles","f","filteredChanges","fileDiffs","file","contents","repoName"]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|