@transcend-io/cli 12.1.5 → 13.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +64 -14
- package/dist/{app-BMLQABJX.mjs → app-Bms-wwFP.mjs} +19 -19
- package/dist/app-Bms-wwFP.mjs.map +1 -0
- package/dist/{approvePrivacyRequests-CY6rQT4J.mjs → approvePrivacyRequests-DyLb38gV.mjs} +2 -2
- package/dist/{approvePrivacyRequests-CY6rQT4J.mjs.map → approvePrivacyRequests-DyLb38gV.mjs.map} +1 -1
- package/dist/bin/bash-complete.mjs +1 -1
- package/dist/bin/cli.mjs +1 -1
- package/dist/bin/deprecated-command.mjs +1 -1
- package/dist/{buildExamples-BNGtj-DW.mjs → buildExamples-Ck7gzWSG.mjs} +2 -2
- package/dist/{buildExamples-BNGtj-DW.mjs.map → buildExamples-Ck7gzWSG.mjs.map} +1 -1
- package/dist/{buildXdiSyncEndpoint-BNCfOc-g.mjs → buildXdiSyncEndpoint-etqb_c38.mjs} +2 -2
- package/dist/{buildXdiSyncEndpoint-BNCfOc-g.mjs.map → buildXdiSyncEndpoint-etqb_c38.mjs.map} +1 -1
- package/dist/{bulkRestartRequests-CGvODu3r.mjs → bulkRestartRequests-DWJ8N0fa.mjs} +2 -2
- package/dist/{bulkRestartRequests-CGvODu3r.mjs.map → bulkRestartRequests-DWJ8N0fa.mjs.map} +1 -1
- package/dist/{bulkRetryEnrichers-BgDd4GWH.mjs → bulkRetryEnrichers-J8CHMy_1.mjs} +2 -2
- package/dist/{bulkRetryEnrichers-BgDd4GWH.mjs.map → bulkRetryEnrichers-J8CHMy_1.mjs.map} +1 -1
- package/dist/{cancelPrivacyRequests-Ccsiwrnu.mjs → cancelPrivacyRequests-C9nFdfgW.mjs} +2 -2
- package/dist/{cancelPrivacyRequests-Ccsiwrnu.mjs.map → cancelPrivacyRequests-C9nFdfgW.mjs.map} +1 -1
- package/dist/codecs-8T8Jhxsr.mjs +2 -0
- package/dist/codecs-8T8Jhxsr.mjs.map +1 -0
- package/dist/{command-BjzdoKgJ.mjs → command-C-wEPTO5.mjs} +2 -2
- package/dist/{command-BjzdoKgJ.mjs.map → command-C-wEPTO5.mjs.map} +1 -1
- package/dist/constants-D6y_AX3P.mjs +2 -0
- package/dist/constants-D6y_AX3P.mjs.map +1 -0
- package/dist/{constants-FDjw7bPS.mjs → constants-I694qbRg.mjs} +2 -2
- package/dist/{constants-FDjw7bPS.mjs.map → constants-I694qbRg.mjs.map} +1 -1
- package/dist/{createPoolingCommandUi-BdtnLBBM.mjs → createPoolingCommandUi-BZr2HSiZ.mjs} +2 -2
- package/dist/{createPoolingCommandUi-BdtnLBBM.mjs.map → createPoolingCommandUi-BZr2HSiZ.mjs.map} +1 -1
- package/dist/{downloadPrivacyRequestFiles-C9-xSCpt.mjs → downloadPrivacyRequestFiles-CF_QjkR9.mjs} +2 -2
- package/dist/{downloadPrivacyRequestFiles-C9-xSCpt.mjs.map → downloadPrivacyRequestFiles-CF_QjkR9.mjs.map} +1 -1
- package/dist/fetchAllRequests-BV9K0wXv.mjs +2 -0
- package/dist/fetchAllRequests-BV9K0wXv.mjs.map +1 -0
- package/dist/{fuzzyMatchColumns-D18n9Beu.mjs → fuzzyMatchColumns-Djl3a7lV.mjs} +2 -2
- package/dist/{fuzzyMatchColumns-D18n9Beu.mjs.map → fuzzyMatchColumns-Djl3a7lV.mjs.map} +1 -1
- package/dist/{generateCrossAccountApiKeys-FtWwlf_L.mjs → generateCrossAccountApiKeys-BxW6xU40.mjs} +2 -2
- package/dist/{generateCrossAccountApiKeys-FtWwlf_L.mjs.map → generateCrossAccountApiKeys-BxW6xU40.mjs.map} +1 -1
- package/dist/{impl-SOebshza.mjs → impl-3VziEzJI.mjs} +2 -2
- package/dist/{impl-SOebshza.mjs.map → impl-3VziEzJI.mjs.map} +1 -1
- package/dist/{impl-DnDM9zcu.mjs → impl-7NFxUzSa.mjs} +2 -2
- package/dist/{impl-DnDM9zcu.mjs.map → impl-7NFxUzSa.mjs.map} +1 -1
- package/dist/{impl-Dg7XSQdO2.mjs → impl-7qTKg-YP2.mjs} +2 -2
- package/dist/{impl-Dg7XSQdO2.mjs.map → impl-7qTKg-YP2.mjs.map} +1 -1
- package/dist/{impl-zZd6fuXS.mjs → impl-AWYAfZ2C.mjs} +2 -2
- package/dist/{impl-zZd6fuXS.mjs.map → impl-AWYAfZ2C.mjs.map} +1 -1
- package/dist/{impl-B94dMG4x2.mjs → impl-B-BkGfqq2.mjs} +2 -2
- package/dist/{impl-B94dMG4x2.mjs.map → impl-B-BkGfqq2.mjs.map} +1 -1
- package/dist/{impl-Dd39KsYO.mjs → impl-B0NqrNcJ2.mjs} +2 -2
- package/dist/impl-B0NqrNcJ2.mjs.map +1 -0
- package/dist/{impl-C3vTm9zQ.mjs → impl-B5fkF8m2.mjs} +2 -2
- package/dist/{impl-C3vTm9zQ.mjs.map → impl-B5fkF8m2.mjs.map} +1 -1
- package/dist/{impl-xVmMN-Vt.mjs → impl-B9vbcV8J.mjs} +2 -2
- package/dist/{impl-xVmMN-Vt.mjs.map → impl-B9vbcV8J.mjs.map} +1 -1
- package/dist/{impl-CSnBFv5P.mjs → impl-BCTVuvlD.mjs} +2 -2
- package/dist/{impl-CSnBFv5P.mjs.map → impl-BCTVuvlD.mjs.map} +1 -1
- package/dist/impl-BfS6LtNo2.mjs +2 -0
- package/dist/impl-BfS6LtNo2.mjs.map +1 -0
- package/dist/{impl-qNF5eqX-.mjs → impl-BfU0GFmW.mjs} +1 -1
- package/dist/{impl-qNF5eqX-.mjs.map → impl-BfU0GFmW.mjs.map} +1 -1
- package/dist/{impl-BXGpJz21.mjs → impl-Bhmoagby.mjs} +2 -2
- package/dist/{impl-BXGpJz21.mjs.map → impl-Bhmoagby.mjs.map} +1 -1
- package/dist/{impl-COqlYiiw.mjs → impl-Bpiggf8H.mjs} +2 -2
- package/dist/{impl-COqlYiiw.mjs.map → impl-Bpiggf8H.mjs.map} +1 -1
- package/dist/{impl-D6frX-PK.mjs → impl-BsxD7toO.mjs} +2 -2
- package/dist/{impl-D6frX-PK.mjs.map → impl-BsxD7toO.mjs.map} +1 -1
- package/dist/{impl-Bs2pNgMK.mjs → impl-BvL9wElZ.mjs} +2 -2
- package/dist/{impl-Bs2pNgMK.mjs.map → impl-BvL9wElZ.mjs.map} +1 -1
- package/dist/{impl-DUYRVzMo.mjs → impl-BzzkiK_b.mjs} +1 -1
- package/dist/{impl-DUYRVzMo.mjs.map → impl-BzzkiK_b.mjs.map} +1 -1
- package/dist/{impl-DZoTWLfw2.mjs → impl-C-hBO0Wa2.mjs} +2 -2
- package/dist/{impl-DZoTWLfw2.mjs.map → impl-C-hBO0Wa2.mjs.map} +1 -1
- package/dist/{impl-bl6NF3Lr.mjs → impl-C6tbQV8G.mjs} +2 -2
- package/dist/{impl-bl6NF3Lr.mjs.map → impl-C6tbQV8G.mjs.map} +1 -1
- package/dist/{impl-BEiCEzl_2.mjs → impl-CHoglMch.mjs} +1 -1
- package/dist/impl-CHoglMch.mjs.map +1 -0
- package/dist/{impl-ClT3G845.mjs → impl-CQ3NctWn.mjs} +2 -2
- package/dist/{impl-ClT3G845.mjs.map → impl-CQ3NctWn.mjs.map} +1 -1
- package/dist/{impl-DhXzxQDN2.mjs → impl-CRif3TpB2.mjs} +2 -2
- package/dist/{impl-DhXzxQDN2.mjs.map → impl-CRif3TpB2.mjs.map} +1 -1
- package/dist/{impl-Cvyc-iTI2.mjs → impl-CWINXCFq2.mjs} +2 -2
- package/dist/{impl-Cvyc-iTI2.mjs.map → impl-CWINXCFq2.mjs.map} +1 -1
- package/dist/{impl-BLtOfbtk.mjs → impl-CaErz960.mjs} +2 -2
- package/dist/{impl-BLtOfbtk.mjs.map → impl-CaErz960.mjs.map} +1 -1
- package/dist/{impl-D6rMLiNB2.mjs → impl-CjOkPJJx.mjs} +2 -2
- package/dist/impl-CjOkPJJx.mjs.map +1 -0
- package/dist/{impl-yIVxAhCG2.mjs → impl-CpJIikeg2.mjs} +2 -2
- package/dist/{impl-yIVxAhCG2.mjs.map → impl-CpJIikeg2.mjs.map} +1 -1
- package/dist/{impl-XxYQHKO5.mjs → impl-CujcaHKR.mjs} +2 -2
- package/dist/{impl-XxYQHKO5.mjs.map → impl-CujcaHKR.mjs.map} +1 -1
- package/dist/{impl-BLOhoP-b2.mjs → impl-CzFfjx8n2.mjs} +2 -2
- package/dist/{impl-BLOhoP-b2.mjs.map → impl-CzFfjx8n2.mjs.map} +1 -1
- package/dist/{impl-QD3_9HTk.mjs → impl-CzgNvB64.mjs} +2 -2
- package/dist/{impl-QD3_9HTk.mjs.map → impl-CzgNvB64.mjs.map} +1 -1
- package/dist/{impl-B_N_fOq0.mjs → impl-D5BItJzQ.mjs} +2 -2
- package/dist/{impl-B_N_fOq0.mjs.map → impl-D5BItJzQ.mjs.map} +1 -1
- package/dist/{impl-DeCRXfAh2.mjs → impl-DEF-meSg2.mjs} +2 -2
- package/dist/{impl-DeCRXfAh2.mjs.map → impl-DEF-meSg2.mjs.map} +1 -1
- package/dist/{impl-CTOgxZFi.mjs → impl-DIz7yqDc.mjs} +2 -2
- package/dist/{impl-CTOgxZFi.mjs.map → impl-DIz7yqDc.mjs.map} +1 -1
- package/dist/{impl-DDVhG8Gf.mjs → impl-DLnVDCjy.mjs} +2 -2
- package/dist/{impl-DDVhG8Gf.mjs.map → impl-DLnVDCjy.mjs.map} +1 -1
- package/dist/{impl-DGtCNANL.mjs → impl-DMoMMAMW.mjs} +2 -2
- package/dist/{impl-DGtCNANL.mjs.map → impl-DMoMMAMW.mjs.map} +1 -1
- package/dist/{impl-ChQAmyBN.mjs → impl-DMwjar-u.mjs} +2 -2
- package/dist/{impl-ChQAmyBN.mjs.map → impl-DMwjar-u.mjs.map} +1 -1
- package/dist/{impl-Bz1wZxa-.mjs → impl-DUWlKcy6.mjs} +2 -2
- package/dist/{impl-Bz1wZxa-.mjs.map → impl-DUWlKcy6.mjs.map} +1 -1
- package/dist/{impl-D58JUOdA.mjs → impl-DY_TNWaO.mjs} +2 -2
- package/dist/{impl-D58JUOdA.mjs.map → impl-DY_TNWaO.mjs.map} +1 -1
- package/dist/{impl-Cp5o0Q2g.mjs → impl-D_8KoR4w.mjs} +2 -2
- package/dist/{impl-Cp5o0Q2g.mjs.map → impl-D_8KoR4w.mjs.map} +1 -1
- package/dist/{impl-VSo8bO-J.mjs → impl-DdL7paBD.mjs} +2 -2
- package/dist/{impl-VSo8bO-J.mjs.map → impl-DdL7paBD.mjs.map} +1 -1
- package/dist/{impl-0-_oxvck.mjs → impl-DioQW8jR.mjs} +2 -2
- package/dist/{impl-0-_oxvck.mjs.map → impl-DioQW8jR.mjs.map} +1 -1
- package/dist/{impl-EDwngLc7.mjs → impl-Dj4IYEXg.mjs} +2 -2
- package/dist/{impl-EDwngLc7.mjs.map → impl-Dj4IYEXg.mjs.map} +1 -1
- package/dist/{impl-BvwRiPSG.mjs → impl-DpW_rDzv.mjs} +2 -2
- package/dist/{impl-BvwRiPSG.mjs.map → impl-DpW_rDzv.mjs.map} +1 -1
- package/dist/{impl-Cb-7C1Ml2.mjs → impl-Dr1qLfh1.mjs} +12 -105
- package/dist/impl-Dr1qLfh1.mjs.map +1 -0
- package/dist/{impl-agm4lpyq.mjs → impl-HsRwcfRu.mjs} +2 -2
- package/dist/{impl-agm4lpyq.mjs.map → impl-HsRwcfRu.mjs.map} +1 -1
- package/dist/{impl-BHEAKFX02.mjs → impl-LT1FBKID2.mjs} +2 -2
- package/dist/{impl-BHEAKFX02.mjs.map → impl-LT1FBKID2.mjs.map} +1 -1
- package/dist/impl-Q2ZDQO_y2.mjs +2 -0
- package/dist/impl-Q2ZDQO_y2.mjs.map +1 -0
- package/dist/{impl-DFnWzZyY.mjs → impl-UtanPzK1.mjs} +2 -2
- package/dist/{impl-DFnWzZyY.mjs.map → impl-UtanPzK1.mjs.map} +1 -1
- package/dist/{impl-Ar7VAh0Z.mjs → impl-ZFp_SwYr.mjs} +2 -2
- package/dist/{impl-Ar7VAh0Z.mjs.map → impl-ZFp_SwYr.mjs.map} +1 -1
- package/dist/{impl-Hj5CgbWd.mjs → impl-eWsR0UvV.mjs} +2 -2
- package/dist/{impl-Hj5CgbWd.mjs.map → impl-eWsR0UvV.mjs.map} +1 -1
- package/dist/{impl-Ay6JeH-7.mjs → impl-kuuX5KaC.mjs} +2 -2
- package/dist/{impl-Ay6JeH-7.mjs.map → impl-kuuX5KaC.mjs.map} +1 -1
- package/dist/{impl-xY_5o78i.mjs → impl-mBJWy3lg.mjs} +2 -2
- package/dist/{impl-xY_5o78i.mjs.map → impl-mBJWy3lg.mjs.map} +1 -1
- package/dist/{impl-ojAnhhbi.mjs → impl-nWslO7Lu.mjs} +2 -2
- package/dist/{impl-ojAnhhbi.mjs.map → impl-nWslO7Lu.mjs.map} +1 -1
- package/dist/{impl-ApZGIx6l.mjs → impl-o66EB2o7.mjs} +2 -2
- package/dist/{impl-ApZGIx6l.mjs.map → impl-o66EB2o7.mjs.map} +1 -1
- package/dist/{impl-BCKUj-ko.mjs → impl-pqCx3OlD.mjs} +2 -2
- package/dist/{impl-BCKUj-ko.mjs.map → impl-pqCx3OlD.mjs.map} +1 -1
- package/dist/{impl-BpVe6fMe.mjs → impl-yxR3rwGm.mjs} +2 -2
- package/dist/{impl-BpVe6fMe.mjs.map → impl-yxR3rwGm.mjs.map} +1 -1
- package/dist/index.d.mts +36 -26
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{inquirer-jzIQWAvq.mjs → inquirer-DK1JbPA0.mjs} +2 -2
- package/dist/{inquirer-jzIQWAvq.mjs.map → inquirer-DK1JbPA0.mjs.map} +1 -1
- package/dist/{markRequestDataSiloIdsCompleted-JGJf33yp.mjs → markRequestDataSiloIdsCompleted-CRLlmf-g.mjs} +2 -2
- package/dist/{markRequestDataSiloIdsCompleted-JGJf33yp.mjs.map → markRequestDataSiloIdsCompleted-CRLlmf-g.mjs.map} +1 -1
- package/dist/{markSilentPrivacyRequests-BTI3rH-V.mjs → markSilentPrivacyRequests-CZIAGpw2.mjs} +2 -2
- package/dist/{markSilentPrivacyRequests-BTI3rH-V.mjs.map → markSilentPrivacyRequests-CZIAGpw2.mjs.map} +1 -1
- package/dist/{mergeTranscendInputs-B7WjxYMN.mjs → mergeTranscendInputs-9kQ3t5VY.mjs} +2 -2
- package/dist/{mergeTranscendInputs-B7WjxYMN.mjs.map → mergeTranscendInputs-9kQ3t5VY.mjs.map} +1 -1
- package/dist/{notifyPrivacyRequestsAdditionalTime-n5fvOJaA.mjs → notifyPrivacyRequestsAdditionalTime-KiF9dkuk.mjs} +2 -2
- package/dist/{notifyPrivacyRequestsAdditionalTime-n5fvOJaA.mjs.map → notifyPrivacyRequestsAdditionalTime-KiF9dkuk.mjs.map} +1 -1
- package/dist/{policy-bundle-manifest-DbbTXe0u.mjs → policy-bundle-manifest-DW1kUjMf.mjs} +2 -2
- package/dist/{policy-bundle-manifest-DbbTXe0u.mjs.map → policy-bundle-manifest-DW1kUjMf.mjs.map} +1 -1
- package/dist/{policy-project-discovery-DTSl0Gfl.mjs → policy-project-discovery-BSQ2Cow0.mjs} +4 -4
- package/dist/policy-project-discovery-BSQ2Cow0.mjs.map +1 -0
- package/dist/{policy-scaffold-config-RpxwwZ2H.mjs → policy-scaffold-config-B_Xbfv7q.mjs} +8 -8
- package/dist/policy-scaffold-config-B_Xbfv7q.mjs.map +1 -0
- package/dist/{project-discovery-BkHpTXDx.mjs → project-discovery-g29vd44a.mjs} +2 -2
- package/dist/{project-discovery-BkHpTXDx.mjs.map → project-discovery-g29vd44a.mjs.map} +1 -1
- package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-DbybCU2T.mjs → pullChunkedCustomSiloOutstandingIdentifiers-ekuEZlzq.mjs} +2 -2
- package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-DbybCU2T.mjs.map → pullChunkedCustomSiloOutstandingIdentifiers-ekuEZlzq.mjs.map} +1 -1
- package/dist/{pullManualEnrichmentIdentifiersToCsv-CxTPUfpV.mjs → pullManualEnrichmentIdentifiersToCsv-D710M8kt.mjs} +2 -2
- package/dist/{pullManualEnrichmentIdentifiersToCsv-CxTPUfpV.mjs.map → pullManualEnrichmentIdentifiersToCsv-D710M8kt.mjs.map} +1 -1
- package/dist/{pushCronIdentifiersFromCsv-CeRVlbFE.mjs → pushCronIdentifiersFromCsv-f8FSSFhM.mjs} +2 -2
- package/dist/{pushCronIdentifiersFromCsv-CeRVlbFE.mjs.map → pushCronIdentifiersFromCsv-f8FSSFhM.mjs.map} +1 -1
- package/dist/{pushManualEnrichmentIdentifiersFromCsv--4dYCvyv.mjs → pushManualEnrichmentIdentifiersFromCsv-6xOUhOpJ.mjs} +2 -2
- package/dist/{pushManualEnrichmentIdentifiersFromCsv--4dYCvyv.mjs.map → pushManualEnrichmentIdentifiersFromCsv-6xOUhOpJ.mjs.map} +1 -1
- package/dist/{readTranscendYaml-BfqQbPiT.mjs → readTranscendYaml-D576bvzR.mjs} +2 -2
- package/dist/{readTranscendYaml-BfqQbPiT.mjs.map → readTranscendYaml-D576bvzR.mjs.map} +1 -1
- package/dist/{removeUnverifiedRequestIdentifiers-CV6JGgt_.mjs → removeUnverifiedRequestIdentifiers-B8iIreP4.mjs} +2 -2
- package/dist/{removeUnverifiedRequestIdentifiers-CV6JGgt_.mjs.map → removeUnverifiedRequestIdentifiers-B8iIreP4.mjs.map} +1 -1
- package/dist/{retryRequestDataSilos-_OThvVwU.mjs → retryRequestDataSilos-BQuxZd4C.mjs} +2 -2
- package/dist/{retryRequestDataSilos-_OThvVwU.mjs.map → retryRequestDataSilos-BQuxZd4C.mjs.map} +1 -1
- package/dist/runRegalLintStep-DPaMm7Gg.mjs +3 -0
- package/dist/runRegalLintStep-DPaMm7Gg.mjs.map +1 -0
- package/dist/{scaffold-planning-BrX-pcz6.mjs → scaffold-planning-Bp_yqZWx.mjs} +2 -2
- package/dist/{scaffold-planning-BrX-pcz6.mjs.map → scaffold-planning-Bp_yqZWx.mjs.map} +1 -1
- package/dist/{skipPreflightJobs-D8og5pKe.mjs → skipPreflightJobs-BkTH4QOf.mjs} +2 -2
- package/dist/{skipPreflightJobs-D8og5pKe.mjs.map → skipPreflightJobs-BkTH4QOf.mjs.map} +1 -1
- package/dist/{skipRequestDataSilos-DUQ6AD_O.mjs → skipRequestDataSilos-sdfJ0gPn.mjs} +2 -2
- package/dist/{skipRequestDataSilos-DUQ6AD_O.mjs.map → skipRequestDataSilos-sdfJ0gPn.mjs.map} +1 -1
- package/dist/{streamPrivacyRequestsToCsv-BApu4dvI.mjs → streamPrivacyRequestsToCsv-D0PK8mjN.mjs} +2 -2
- package/dist/{streamPrivacyRequestsToCsv-BApu4dvI.mjs.map → streamPrivacyRequestsToCsv-D0PK8mjN.mjs.map} +1 -1
- package/dist/{updateConsentManagerVersionToLatest-BrgPZ5hX.mjs → updateConsentManagerVersionToLatest-EJaexjTY.mjs} +2 -2
- package/dist/{updateConsentManagerVersionToLatest-BrgPZ5hX.mjs.map → updateConsentManagerVersionToLatest-EJaexjTY.mjs.map} +1 -1
- package/dist/{uploadConsents-DRlDHQak.mjs → uploadConsents-DjvQVsIl.mjs} +2 -2
- package/dist/{uploadConsents-DRlDHQak.mjs.map → uploadConsents-DjvQVsIl.mjs.map} +1 -1
- package/dist/uploadPrivacyRequestsFromCsv-FvSx9zis.mjs +2 -0
- package/dist/uploadPrivacyRequestsFromCsv-FvSx9zis.mjs.map +1 -0
- package/dist/{validateTranscendAuth-D-dDINof.mjs → validateTranscendAuth-BrVGfq6X.mjs} +2 -2
- package/dist/{validateTranscendAuth-D-dDINof.mjs.map → validateTranscendAuth-BrVGfq6X.mjs.map} +1 -1
- package/package.json +6 -6
- package/dist/app-BMLQABJX.mjs.map +0 -1
- package/dist/codecs-CfcaFoZR.mjs +0 -2
- package/dist/codecs-CfcaFoZR.mjs.map +0 -1
- package/dist/constants-DlH2vWm_.mjs +0 -2
- package/dist/constants-DlH2vWm_.mjs.map +0 -1
- package/dist/fetchAllRequests-BI0tFl_a.mjs +0 -2
- package/dist/fetchAllRequests-BI0tFl_a.mjs.map +0 -1
- package/dist/impl-BEiCEzl_2.mjs.map +0 -1
- package/dist/impl-Cb-7C1Ml2.mjs.map +0 -1
- package/dist/impl-D6rMLiNB2.mjs.map +0 -1
- package/dist/impl-DNOgBcsu.mjs +0 -3
- package/dist/impl-DNOgBcsu.mjs.map +0 -1
- package/dist/impl-Dd39KsYO.mjs.map +0 -1
- package/dist/policy-project-discovery-DTSl0Gfl.mjs.map +0 -1
- package/dist/policy-scaffold-config-RpxwwZ2H.mjs.map +0 -1
- package/dist/uploadPrivacyRequestsFromCsv-FAGllBdd.mjs +0 -2
- package/dist/uploadPrivacyRequestsFromCsv-FAGllBdd.mjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{g as e}from"./constants-
|
|
1
|
+
import{g as e}from"./constants-I694qbRg.mjs";import{i as t,n,r,t as i}from"./project-plan-output-BHHlkLxe.mjs";import{c as a,d as o,f as s,l as c,t as l,u}from"./project-discovery-CWRjlFnC.mjs";import{b as d,d as f,r as p,t as m,u as h}from"./policy-project-discovery-BSQ2Cow0.mjs";import{a as g,c as _,i as v,l as y,o as b,r as x,s as S,t as C}from"./policy-runtime-6jmkXlBk.mjs";import{t as w}from"./done-input-validation-LiTaCEzF.mjs";import{i as T,n as E,r as D,t as O}from"./prompts-BhXfYD6g.mjs";import{t as k}from"./run-captured-process-BjaSDWXG.mjs";import{t as A}from"./project-plan-apply-Bg_1eMX9.mjs";import{a as j,n as ee,o as te,r as ne,t as re}from"./policy-scaffold-config-B_Xbfv7q.mjs";import{isAbsolute as M,join as N,posix as P,relative as F,sep as I}from"node:path";import L from"colors";const R={Editor:`editor`,Skill:`skill`,Ci:`ci`};var z=`# Idiomatic Rego and document-tree authoring
|
|
2
2
|
|
|
3
3
|
## Start from the document tree
|
|
4
4
|
|
|
@@ -55,7 +55,7 @@ allow if facts.subject_is_trusted
|
|
|
55
55
|
|
|
56
56
|
Do not use a fully qualified \`data.<root>…\` reference directly in a rule body.
|
|
57
57
|
Policy Engine re-namespaces package declarations and imports during activation,
|
|
58
|
-
and \`transcend policy
|
|
58
|
+
and \`transcend policy check\` rejects direct self-root references that would
|
|
59
59
|
change meaning.
|
|
60
60
|
|
|
61
61
|
## Define the contract before implementation
|
|
@@ -135,7 +135,7 @@ hints**. Upload does not branch on them.
|
|
|
135
135
|
Before publishing:
|
|
136
136
|
|
|
137
137
|
1. confirm the intended package and query paths with the consuming application;
|
|
138
|
-
2. run \`transcend policy
|
|
138
|
+
2. run \`transcend policy check <bundle-directory> --noInteractive\` and tests;
|
|
139
139
|
3. review the generated bundle name, version, description, and target Transcend environment;
|
|
140
140
|
4. keep API keys in the environment or the repository's approved secret store.
|
|
141
141
|
|
|
@@ -250,7 +250,7 @@ updates VS Code settings/tasks when \`.vscode\` is present.
|
|
|
250
250
|
|
|
251
251
|
The generated Regal configuration targets OPA 1.18.2 capabilities. Generated CI
|
|
252
252
|
installs OPA 1.18.2 and Regal 0.42.0; local tools only need to satisfy the
|
|
253
|
-
compatible versions reported by \`policy init\` and \`policy
|
|
253
|
+
compatible versions reported by \`policy init\` and \`policy check\`. Follow their
|
|
254
254
|
official installation links when a compatible tool is missing.
|
|
255
255
|
|
|
256
256
|
## Editor and CI
|
|
@@ -266,112 +266,19 @@ Repository-level VS Code settings should include:
|
|
|
266
266
|
Preserve custom settings and tasks when adapting generated editor files.
|
|
267
267
|
|
|
268
268
|
Generated GitHub Actions CI is read-only and credential-free: it installs pinned
|
|
269
|
-
tools and the pinned Transcend CLI, then runs \`transcend policy
|
|
269
|
+
tools and the pinned Transcend CLI, then runs \`transcend policy check\` per
|
|
270
270
|
publish directory (matrix when multiple bundles exist). Locally, bare
|
|
271
|
-
\`transcend policy
|
|
271
|
+
\`transcend policy check\` verifies every child under the workspace that contains
|
|
272
272
|
a \`.manifest\`:
|
|
273
273
|
|
|
274
274
|
\`\`\`sh
|
|
275
|
-
transcend policy
|
|
276
|
-
transcend policy
|
|
275
|
+
transcend policy check --noInteractive --json
|
|
276
|
+
transcend policy check transcend/policy/example-bundle --noInteractive --json
|
|
277
277
|
\`\`\`
|
|
278
278
|
|
|
279
279
|
Adapt triggers, runner labels, dependency installation, and caching to
|
|
280
280
|
established repository conventions without adding publish steps or secrets.
|
|
281
|
-
`,H
|
|
282
|
-
|
|
283
|
-
## Write executable tests
|
|
284
|
-
|
|
285
|
-
Place tests next to the package they exercise and suffix test modules with
|
|
286
|
-
\`_test.rego\`. A separate \`_test\` package makes the production API and test
|
|
287
|
-
helpers easy to distinguish. Keep the \`_test\` package under the same manifest
|
|
288
|
-
root (for example \`example.result_test\`, not a sibling root), so bundle-mode
|
|
289
|
-
loads accept it.
|
|
290
|
-
|
|
291
|
-
\`\`\`rego
|
|
292
|
-
package example.result_test
|
|
293
|
-
|
|
294
|
-
import data.example.result
|
|
295
|
-
import rego.v1
|
|
296
|
-
|
|
297
|
-
test_denies_missing_input if {
|
|
298
|
-
result.decision == "deny" with input as {}
|
|
299
|
-
result.reason_code == "untrusted_or_invalid_input" with input as {}
|
|
300
|
-
}
|
|
301
|
-
\`\`\`
|
|
302
|
-
|
|
303
|
-
Cover at least:
|
|
304
|
-
|
|
305
|
-
- the ordinary allow case;
|
|
306
|
-
- explicit deny cases;
|
|
307
|
-
- absent, malformed, and unknown input;
|
|
308
|
-
- important result fields and reason codes;
|
|
309
|
-
- interactions between packages when one policy reads another document.
|
|
310
|
-
|
|
311
|
-
\`transcend policy lint\` requires a non-empty test suite.
|
|
312
|
-
|
|
313
|
-
## Use local inputs safely
|
|
314
|
-
|
|
315
|
-
Keep a sanitized \`input.example.json\` in each publish directory. \`policy new\`
|
|
316
|
-
also writes a gitignored \`input.json\` beside it (same contents) so VS Code /
|
|
317
|
-
Regal Evaluate work immediately. Customize \`input.json\` locally; keep
|
|
318
|
-
\`input.example.json\` committed and free of credentials or personal data.
|
|
319
|
-
|
|
320
|
-
## Run the complete gate
|
|
321
|
-
|
|
322
|
-
With no directory argument, \`policy lint\` and \`policy test\` verify every
|
|
323
|
-
immediate child under the workspace (\`transcend/policy\`) that contains a
|
|
324
|
-
\`.manifest\`. Pass one bundle path to target a single unit:
|
|
325
|
-
|
|
326
|
-
\`\`\`sh
|
|
327
|
-
transcend policy lint --noInteractive
|
|
328
|
-
transcend policy test
|
|
329
|
-
transcend policy lint transcend/policy/permissions-bundle --noInteractive
|
|
330
|
-
transcend policy test transcend/policy/permissions-bundle
|
|
331
|
-
opa check --strict -b transcend/policy/permissions-bundle -s transcend/policy/permissions-bundle/input.schema.json
|
|
332
|
-
\`\`\`
|
|
333
|
-
|
|
334
|
-
\`policy lint\` and \`policy test\` run \`opa test -b\` (bundle mode) so a local
|
|
335
|
-
gitignored \`input.json\` beside \`input.example.json\` does not cause a merge
|
|
336
|
-
error. Prefer the CLI over raw directory-mode \`opa test\`. Strict OPA checks use
|
|
337
|
-
Rego v1 (no \`--v0-compatible\`).
|
|
338
|
-
|
|
339
|
-
Use \`transcend policy lint --help\` for formatter flags. Review Regal findings
|
|
340
|
-
deliberately instead of applying broad rewrites.
|
|
341
|
-
|
|
342
|
-
## Evaluate a query
|
|
343
|
-
|
|
344
|
-
\`policy eval\` requires an explicit local publish directory (\`<bundle>\`).
|
|
345
|
-
|
|
346
|
-
Generic example bundle:
|
|
347
|
-
|
|
348
|
-
\`\`\`sh
|
|
349
|
-
transcend policy eval transcend/policy/example-bundle \\
|
|
350
|
-
--package=data.example.result \\
|
|
351
|
-
--input=transcend/policy/example-bundle/input.json
|
|
352
|
-
\`\`\`
|
|
353
|
-
|
|
354
|
-
To simulate the Permissions API, pass the bundle, a purpose query (\`--package\`),
|
|
355
|
-
the local envelope (\`--input\`), and the bundle's input schema (\`--schema\`) so
|
|
356
|
-
OPA type-checks \`input\`:
|
|
357
|
-
|
|
358
|
-
\`\`\`sh
|
|
359
|
-
transcend policy eval transcend/policy/permissions-bundle \\
|
|
360
|
-
--package=data.permissions.purposes \\
|
|
361
|
-
--input=transcend/policy/permissions-bundle/input.json \\
|
|
362
|
-
--schema=transcend/policy/permissions-bundle/input.schema.json
|
|
363
|
-
\`\`\`
|
|
364
|
-
|
|
365
|
-
Or pipe the envelope with \`--stdin-input\`. \`policy eval\` ignores \`*_test.rego\`
|
|
366
|
-
(same as lint/publish — tests are not shipped). Use \`transcend policy eval --help\`
|
|
367
|
-
for curated \`opa eval\` pass-through flags (format, explain, metrics, and similar).
|
|
368
|
-
Exit-on-result flags like OPA \`--fail\` are not exposed — production Evaluate uses
|
|
369
|
-
the Data API (policy deny is a successful evaluation).
|
|
370
|
-
|
|
371
|
-
Or \`opa eval -b … -i …\` with the caller's query path. If the result differs from
|
|
372
|
-
expectations, inspect package paths, imports, defaults, input field presence,
|
|
373
|
-
and the selected bundle directory before changing policy logic.
|
|
374
|
-
`,U=`---
|
|
281
|
+
`,H='# Testing and debugging\n\n## Write executable tests\n\nPlace tests next to the package they exercise and suffix test modules with\n`_test.rego`. A separate `_test` package makes the production API and test\nhelpers easy to distinguish. Keep the `_test` package under the same manifest\nroot (for example `example.result_test`, not a sibling root), so bundle-mode\nloads accept it.\n\n```rego\npackage example.result_test\n\nimport data.example.result\nimport rego.v1\n\ntest_denies_missing_input if {\n result.decision == "deny" with input as {}\n result.reason_code == "untrusted_or_invalid_input" with input as {}\n}\n```\n\nCover at least:\n\n- the ordinary allow case;\n- explicit deny cases;\n- absent, malformed, and unknown input;\n- important result fields and reason codes;\n- interactions between packages when one policy reads another document.\n\n`transcend policy check` requires a non-empty test suite.\n\n## Use local inputs safely\n\nKeep a sanitized `input.example.json` in each publish directory. `policy new`\nalso writes a gitignored `input.json` beside it (same contents) so VS Code /\nRegal Evaluate work immediately. Customize `input.json` locally; keep\n`input.example.json` committed and free of credentials or personal data.\n\n## Run the complete gate\n\nWith no directory argument, `policy check` and `policy test` verify every\nimmediate child under the workspace (`transcend/policy`) that contains a\n`.manifest`. Pass one bundle path to target a single unit:\n\n```sh\ntranscend policy check --noInteractive\ntranscend policy test\ntranscend policy check transcend/policy/permissions-bundle --noInteractive\ntranscend policy test transcend/policy/permissions-bundle\nopa check --strict -b transcend/policy/permissions-bundle -s transcend/policy/permissions-bundle/input.schema.json\n```\n\n`policy check` and `policy test` run `opa test -b` (bundle mode) so a local\ngitignored `input.json` beside `input.example.json` does not cause a merge\nerror. Prefer the CLI over raw directory-mode `opa test`. Strict OPA checks use\nRego v1 (no `--v0-compatible`).\n\nUse `transcend policy lint` for OPA formatting and Regal only (with `--fix` to\nrepair formatting). Use `transcend policy check --help` for the full gate.\nReview Regal findings deliberately instead of applying broad rewrites.\n\n## Evaluate a query\n\n`policy eval` requires an explicit local publish directory (`<bundle>`).\n\nGeneric example bundle:\n\n```sh\ntranscend policy eval transcend/policy/example-bundle \\\n --package=data.example.result \\\n --input=transcend/policy/example-bundle/input.json\n```\n\nTo simulate the Permissions API, pass the bundle, a purpose query (`--package`),\nthe local envelope (`--input`), and the bundle\'s input schema (`--schema`) so\nOPA type-checks `input`:\n\n```sh\ntranscend policy eval transcend/policy/permissions-bundle \\\n --package=data.permissions.purposes \\\n --input=transcend/policy/permissions-bundle/input.json \\\n --schema=transcend/policy/permissions-bundle/input.schema.json\n```\n\nOr pipe the envelope with `--stdin-input`. `policy eval` ignores `*_test.rego`\n(same as lint/publish — tests are not shipped). Use `transcend policy eval --help`\nfor curated `opa eval` pass-through flags (format, explain, metrics, and similar).\nExit-on-result flags like OPA `--fail` are not exposed — production Evaluate uses\nthe Data API (policy deny is a successful evaluation).\n\nOr `opa eval -b … -i …` with the caller\'s query path. If the result differs from\nexpectations, inspect package paths, imports, defaults, input field presence,\nand the selected bundle directory before changing policy logic.\n',U=`---
|
|
375
282
|
name: transcend-policy-engine
|
|
376
283
|
description: Sets up, authors, validates, tests, and publishes Transcend Policy Engine projects backed by OPA and Rego. Use for .manifest roots, Rego v1 policy trees, Regal configuration, local policy inputs, Policy Engine CI, or transcend policy CLI commands.
|
|
377
284
|
compatibility: Requires OPA 1.x, Regal, and Transcend CLI ≥ 11 for local validation.
|
|
@@ -383,7 +290,7 @@ Use the CLI for deterministic scaffolding and validation. Treat generated
|
|
|
383
290
|
examples as disposable teaching material and derive the real policy contract
|
|
384
291
|
from repository code and product requirements.
|
|
385
292
|
|
|
386
|
-
Requires **Transcend CLI ≥ 11** (\`transcend policy
|
|
293
|
+
Requires **Transcend CLI ≥ 11** (\`transcend policy check [<directory>]\`, with
|
|
387
294
|
\`init\` available).
|
|
388
295
|
|
|
389
296
|
## Workflow
|
|
@@ -399,7 +306,7 @@ Requires **Transcend CLI ≥ 11** (\`transcend policy lint [<directory>]\`, with
|
|
|
399
306
|
6. Preserve repository conventions and finish with:
|
|
400
307
|
|
|
401
308
|
\`\`\`sh
|
|
402
|
-
transcend policy
|
|
309
|
+
transcend policy check --noInteractive
|
|
403
310
|
\`\`\`
|
|
404
311
|
|
|
405
312
|
## Documentation
|
|
@@ -418,4 +325,4 @@ transcend policy lint --noInteractive
|
|
|
418
325
|
products into a single \`.manifest\` unless they share activation and callers.
|
|
419
326
|
`;const W=`transcend-policy-engine`,G=[{path:`SKILL.md`,contents:U},{path:`references/setup-tooling.md`,contents:V},{path:`references/authoring.md`,contents:z},{path:`references/testing-debugging.md`,contents:H},{path:`references/publishing.md`,contents:B}];function K(e){return`${e.hasSkill?`Use the \`${W}\` skill and run`:`Run`} ${e.newCommand} to add a bundle from a template, then adapt the policy document tree and input/output contract to the intended application.`}function q(e,n){return{version:e.version,command:e.command,applied:n.applied,dryRun:n.dryRun,targetDirectory:e.targetDirectory,manifestPath:e.manifestPath,changes:e.changes.map(e=>t(n.cwd,e)),warnings:e.warnings,nextSteps:e.nextSteps,features:[...e.features],aiHandoff:n.aiHandoff,tools:n.tools}}const J={name:W,displayName:`Policy Engine`,owner:`@transcend-io/cli`,files:G};function Y(e,t){let n=new Set(d().map(({path:t})=>N(e.targetDirectory,t))),r=new Set(t.features);return r.has(R.Editor)&&(n.add(N(e.projectRoot,`.vscode`,`settings.json`)),n.add(N(e.projectRoot,`.vscode`,`extensions.json`)),n.add(N(e.projectRoot,`.vscode`,`tasks.json`))),r.has(R.Skill)&&a(e.projectRoot,e.existingSkillDirectories,J).forEach(e=>n.add(e)),r.has(R.Ci)&&e.repositoryRoot&&e.usesGithub&&n.add(N(e.repositoryRoot,j)),[...n].sort((e,t)=>e.localeCompare(t))}function X(e,t){let n=F(e,t);if(n===`..`||n.startsWith(`..${I}`)||M(n))throw Error(`Refusing to modify path outside project root: ${t}`)}function ie(e){let t=new Set([`${h}/input.json`]);return e.forEach(({path:e})=>{t.add(e);let n=P.dirname(e);for(;n!==`.`;)t.add(n),n=P.dirname(n)}),t}function Z(e,t,n){let r=s({snapshot:u(t.snapshots,n.path),after:n.contents,description:n.description,...n.createOnly===void 0?{}:{createOnly:n.createOnly}});r?e.changes.push(r):e.unchanged.push(n.path)}function ae(e,t,n,r,a,o){Z(e,t,{path:n,contents:r.contents,description:a}),e.warnings.push(...r.warnings.map(e=>`${e} (${i(o,n)})`))}function oe(e,t){let{state:n}=e,r=d(),a=`transcend policy new`,s={version:3,command:`init`,rootDirectory:n.projectRoot,targetDirectory:n.targetDirectory,manifestPath:n.targetDirectory,changes:[],unchanged:[],warnings:[],nextSteps:[a],features:[...t.features]},l=Y(n,t);if(X(n.projectRoot,n.targetDirectory),l.forEach(e=>X(n.projectRoot,e)),n.relativeFilePaths.length===0)s.directoryPreconditions=[{path:n.targetDirectory,relativePaths:[...n.relativePaths]}],r.forEach(t=>{let r=N(n.targetDirectory,t.path);if(o(e.snapshots,r).kind!==`absent`)throw Error(`Expected an empty policy target, but found an entry at: ${r}`);Z(s,e,{path:r,contents:t.contents,description:t.description,createOnly:!0})});else{let t=!0;r.forEach(r=>{let a=N(n.targetDirectory,r.path),c=o(e.snapshots,a);if(c.kind===`file`&&c.contents===r.contents){s.unchanged.push(a);return}t=!1,c.kind!==`absent`&&(s.unchanged.push(a),s.warnings.push(`Existing policy scaffold path was left unchanged: ${i(n.invocationDirectory,a)}`))});let c=ie(r),l=n.relativeFilePaths.some(e=>!c.has(e));(!t||l)&&s.warnings.push(`Existing policy target contains custom or partial content, so no workspace files were added or overwritten. Review ${i(n.invocationDirectory,n.targetDirectory)} manually, then run \`${a}\`.`)}let u=new Set(t.features),f=n.projectRoot;if(u.has(R.Editor)){let t=N(f,`.vscode`,`settings.json`),r=N(f,`.vscode`,`extensions.json`),a=N(f,`.vscode`,`tasks.json`);[{path:t,description:`Merge strict target-scoped OPA and Rego editor settings`,merge:(e,t,n)=>ee(e,t,n)},{path:r,description:`Recommend the OPA extension and discourage its syntax-only conflict`,merge:e=>re(e)},{path:a,description:`Create the VS Code task configuration`,merge:(e,t,n)=>ne(e,t,n)}].forEach(({path:t,description:r,merge:a})=>{let c=o(e.snapshots,t);if(c.kind!==`absent`&&c.kind!==`file`){s.unchanged.push(t),s.warnings.push(`Existing VS Code artifact is not a regular file and was left unchanged: ${i(n.invocationDirectory,t)}`);return}ae(s,e,t,a(c.kind===`file`?c.contents:null,f,n.targetDirectory),r,n.invocationDirectory)})}if(u.has(R.Skill)){let t=c({rootDirectory:f,existingDirectories:n.existingSkillDirectories,snapshots:e.snapshots,skill:J,preserveModified:!0});s.changes.push(...t.changes),s.unchanged.push(...t.unchanged),s.warnings.push(...t.warnings.map(e=>t.unchanged.reduce((e,t)=>e.replace(t,i(n.invocationDirectory,t)),e)))}if(u.has(R.Ci))if(!n.repositoryRoot||!n.usesGithub)s.warnings.push(`GitHub Actions setup was selected, but this target is not inside a detected GitHub repository.`);else{let r=N(n.repositoryRoot,j),a=F(n.repositoryRoot,n.targetDirectory).split(I).join(`/`)||`.`,c=te({cliVersion:t.cliVersion,workspaceDirectory:a,bundleDirectories:[]}),l=o(e.snapshots,r);l.kind===`absent`?Z(s,e,{path:r,contents:c,description:`Add credential-free Policy Engine validation`,createOnly:!0}):l.kind===`file`&&l.contents===c?s.unchanged.push(r):(s.unchanged.push(r),s.warnings.push(`Existing GitHub Actions workflow was left unchanged: ${i(n.invocationDirectory,r)}. Adapt it manually to validate each policy bundle.`))}return s.changes.forEach(({path:e})=>X(n.projectRoot,e)),s}const se={[R.Editor]:`VS Code settings and lint task`,[R.Skill]:`Policy Engine Agent Skill`,[R.Ci]:`Validation-only GitHub Actions`},ce=Object.values(R);function Q(e,t){let n=[t.stdout.trim(),t.stderr.trim()].filter(Boolean).join(`
|
|
420
327
|
`),r=e===`OPA`?x:g;return`${e===`OPA`?`OPA 1.x`:`Regal ${C} or newer`} is required, but \`${e.toLowerCase()} version\` exited with code ${t.code}${n?`: ${n}`:`.`} Install or upgrade it using the official instructions: ${r}`}async function le(e,t,n){let r={opa:null,regal:null},i=[],a=await n(`opa`,[`version`],{cwd:t},e);if(a.error?.code===`ENOENT`)i.push(v);else{let e=`${a.stdout}\n${a.stderr}`,t=_(e);a.code===0?t?i.push(t):r.opa=S(e).version:i.push(t??Q(`OPA`,a))}let o=await n(`regal`,[`version`],{cwd:t},e);if(o.error?.code===`ENOENT`)i.push(b);else{let e=`${o.stdout}\n${o.stderr}`,t=y(e,C,`the generated OPA ${f} capabilities configuration`);o.code===0?t?i.push(t):r.regal=S(e).version:i.push(t??Q(`Regal`,o))}return{tools:r,warnings:i}}async function $(t,a=m,o=k){w(this.process);try{let s=await le(this,this.process.cwd(),o),c=p(this,a),u=new E(this),d=D(t,this.process.stdin.isTTY,this.process.stderr.isTTY),f=await T(u,{features:ce,labels:se,enabled:{[R.Editor]:t.editor,[R.Skill]:t.skill,[R.Ci]:t.ci},interactive:d}),m=Y(c,{features:f}),h=oe({state:c,snapshots:l(this,c.projectRoot,m)},{features:f,cliVersion:e});h.warnings.push(...s.warnings),t.json||this.logger.info(r(h,{cwd:this.process.cwd(),title:`Policy initialization plan`,details:[{label:`Target`,path:h.targetDirectory}]}));let g=h.changes.length===0||t.dryRun;if(h.changes.length>0&&!t.dryRun)if(t.yes)g=!0;else if(d)g=await u.confirm(`Apply this complete plan?`,!0);else throw Error(`The plan requires approval in a non-interactive invocation. Review with --dryRun, then pass --yes.`);g&&!t.dryRun&&h.changes.length>0&&await A(this,h);let _=g&&!t.dryRun&&h.changes.length>0,v=g&&!t.dryRun,y=K({projectPath:n(i(this.process.cwd(),c.targetDirectory)),hasSkill:v&&f.includes(R.Skill),newCommand:h.nextSteps[0]}),b=q(h,{applied:_,dryRun:t.dryRun,cwd:this.process.cwd(),aiHandoff:y,tools:s.tools});if(t.json){this.process.stdout.write(`${JSON.stringify(b)}\n`);return}if(t.dryRun){this.logger.info(L.yellow(`Dry run complete. No changes were written.`));return}if(!g){this.logger.info(L.yellow(`No changes applied.`));return}if(h.changes.length===0){let e=h.warnings.length===s.warnings.length?`Policy project is already initialized.`:`Existing policy project was left unchanged.`;this.logger.info(L.green(e))}else this.logger.info(L.green(`Policy project initialized.`));h.nextSteps.length>0&&(this.logger.info(`\n${L.bold(`Next steps`)}`),h.nextSteps.forEach(e=>this.logger.info(e))),this.logger.info(`\n${L.bold(`AI handoff — paste into your coding agent`)}`),this.logger.info(y)}catch(e){if(e instanceof O)return this.process.exit(130);throw e}}export{$ as init};
|
|
421
|
-
//# sourceMappingURL=impl-
|
|
328
|
+
//# sourceMappingURL=impl-Dr1qLfh1.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"impl-Dr1qLfh1.mjs","names":["POLICY_SKILL_MD","POLICY_SETUP_TOOLING_REFERENCE_MD","POLICY_AUTHORING_REFERENCE_MD","POLICY_TESTING_DEBUGGING_REFERENCE_MD","POLICY_PUBLISHING_REFERENCE_MD","CLI_VERSION"],"sources":["../src/lib/policy/policy-scaffold-model.ts","../../../skills/transcend-policy-engine/references/authoring.md","../../../skills/transcend-policy-engine/references/publishing.md","../../../skills/transcend-policy-engine/references/setup-tooling.md","../../../skills/transcend-policy-engine/references/testing-debugging.md","../../../skills/transcend-policy-engine/SKILL.md","../src/lib/policy/policy-skill.ts","../src/lib/policy/policy-scaffold-output.ts","../src/lib/policy/policy-scaffold-planning.ts","../src/commands/policy/init/impl.ts"],"sourcesContent":["import type { ExistingProjectSkillDirectory } from '../scaffolding/agent-skill.js';\nimport type { ProjectPlan } from '../scaffolding/project-plan.js';\n\n/** Version of the stable policy initialization JSON result. */\nexport const POLICY_INIT_RESULT_VERSION = 3 as const;\n\n/** Optional repository integrations for policy authoring. */\nexport const PolicySetupFeature = {\n /** Repository-level editor configuration. */\n Editor: 'editor',\n /** Managed policy authoring skill. */\n Skill: 'skill',\n /** Credential-free continuous integration. */\n Ci: 'ci',\n} as const;\n\n/** Optional repository integration for policy authoring. */\nexport type PolicySetupFeature = (typeof PolicySetupFeature)[keyof typeof PolicySetupFeature];\n\n/** Repository and target state collected before policy planning. */\nexport interface PolicyProjectState {\n /** Directory from which the CLI was invoked. */\n invocationDirectory: string;\n /** Absolute user-selected policy directory. */\n targetDirectory: string;\n /** Repository or invocation root that owns setup artifacts. */\n projectRoot: string;\n /** Nearest repository root, when present. */\n repositoryRoot?: string;\n /** Existing project-level skill directories. */\n existingSkillDirectories: ExistingProjectSkillDirectory[];\n /** Whether the repository appears to use GitHub. */\n usesGithub: boolean;\n /** Case-preserving relative paths below the policy directory. */\n relativePaths: string[];\n /** Relative file and link paths below the policy directory. */\n relativeFilePaths: string[];\n}\n\n/** A complete, validated policy initialization plan. */\nexport interface PolicyInitProjectPlan extends ProjectPlan {\n /** JSON contract version. */\n version: typeof POLICY_INIT_RESULT_VERSION;\n /** Command that produced the plan. */\n command: 'init';\n /** Absolute policy project directory. */\n targetDirectory: string;\n /** Absolute policy manifest path. */\n manifestPath: string;\n /** Files inspected and deliberately left unchanged. */\n unchanged: string[];\n /** Non-fatal plan warnings. */\n warnings: string[];\n /** Raw commands shown after a successful apply. */\n nextSteps: string[];\n /** Exact generated example that remains safe to replace. */\n disposableExamplePath?: string;\n /** Selected repository integrations. */\n features: PolicySetupFeature[];\n}\n",null,null,null,null,null,"import POLICY_AUTHORING_REFERENCE_MD from '../../../../../skills/transcend-policy-engine/references/authoring.md';\nimport POLICY_PUBLISHING_REFERENCE_MD from '../../../../../skills/transcend-policy-engine/references/publishing.md';\nimport POLICY_SETUP_TOOLING_REFERENCE_MD from '../../../../../skills/transcend-policy-engine/references/setup-tooling.md';\nimport POLICY_TESTING_DEBUGGING_REFERENCE_MD from '../../../../../skills/transcend-policy-engine/references/testing-debugging.md';\nimport POLICY_SKILL_MD from '../../../../../skills/transcend-policy-engine/SKILL.md';\nimport type { AgentSkillFile } from '../scaffolding/agent-skill.js';\n\n/** Namespaced directory and frontmatter name for the installed Agent Skill. */\nexport const POLICY_SKILL_NAME = 'transcend-policy-engine';\n\nexport {\n POLICY_AUTHORING_REFERENCE_MD,\n POLICY_PUBLISHING_REFERENCE_MD,\n POLICY_SETUP_TOOLING_REFERENCE_MD,\n POLICY_SKILL_MD,\n POLICY_TESTING_DEBUGGING_REFERENCE_MD,\n};\n\n/** Complete portable Policy Engine Agent Skill file set. */\nexport const POLICY_SKILL_FILES: readonly AgentSkillFile[] = [\n { path: 'SKILL.md', contents: POLICY_SKILL_MD },\n { path: 'references/setup-tooling.md', contents: POLICY_SETUP_TOOLING_REFERENCE_MD },\n { path: 'references/authoring.md', contents: POLICY_AUTHORING_REFERENCE_MD },\n { path: 'references/testing-debugging.md', contents: POLICY_TESTING_DEBUGGING_REFERENCE_MD },\n { path: 'references/publishing.md', contents: POLICY_PUBLISHING_REFERENCE_MD },\n];\n","import {\n toPublicPlannedChange,\n type PublicPlannedChange,\n} from '../scaffolding/project-plan-output.js';\nimport type { PolicyInitProjectPlan, PolicySetupFeature } from './policy-scaffold-model.js';\nimport { POLICY_SKILL_NAME } from './policy-skill.js';\n\n/** Detected local policy tool versions. */\nexport interface PolicyInitToolVersions {\n /** OPA version, or null when missing or incompatible. */\n opa: string | null;\n /** Regal version, or null when missing or incompatible. */\n regal: string | null;\n}\n\n/** Stable machine-readable policy initialization result. */\nexport interface PolicyInitPlanResult {\n /** JSON contract version. */\n version: number;\n /** Command that produced the result. */\n command: 'init';\n /** Whether the plan was applied. */\n applied: boolean;\n /** Whether this was a dry run. */\n dryRun: boolean;\n /** Absolute policy target directory. */\n targetDirectory: string;\n /** Absolute policy manifest path. */\n manifestPath: string;\n /** Planned mutations without file contents. */\n changes: PublicPlannedChange[];\n /** Non-fatal preservation and runtime warnings. */\n warnings: string[];\n /** Suggested raw one-line follow-up commands. */\n nextSteps: string[];\n /** Explicitly selected repository integrations. */\n features: PolicySetupFeature[];\n /** Compact prompt for continuing with a coding agent. */\n aiHandoff: string;\n /** Compatible local policy tool versions. */\n tools: PolicyInitToolVersions;\n}\n\n/**\n * Build the compact policy implementation and CI handoff.\n *\n * @param options - Portable project path and next step\n * @returns Raw one-line prompt\n */\nexport function buildPolicyInitAiHandoff(options: {\n /** Display path to the policy project. */\n projectPath: string;\n /** Whether the policy authoring skill was installed. */\n hasSkill: boolean;\n /** Copyable new-bundle command. */\n newCommand: string;\n}): string {\n const instruction = options.hasSkill ? `Use the \\`${POLICY_SKILL_NAME}\\` skill and run` : 'Run';\n return (\n `${instruction} ${options.newCommand} to add a bundle from a template, ` +\n `then adapt the policy document tree and input/output contract to the intended application.`\n );\n}\n\n/**\n * Build the stable machine-readable initialization result.\n *\n * @param plan - Policy project plan\n * @param options - Apply and runtime state\n * @returns Public JSON result\n */\nexport function buildPolicyInitPlanResult(\n plan: PolicyInitProjectPlan,\n options: {\n /** Whether the plan was applied. */\n applied: boolean;\n /** Whether this was a dry run. */\n dryRun: boolean;\n /** Working directory for portable paths. */\n cwd: string;\n /** Compact coding-agent prompt. */\n aiHandoff: string;\n /** Compatible local policy tool versions. */\n tools: PolicyInitToolVersions;\n },\n): PolicyInitPlanResult {\n return {\n version: plan.version,\n command: plan.command,\n applied: options.applied,\n dryRun: options.dryRun,\n targetDirectory: plan.targetDirectory,\n manifestPath: plan.manifestPath,\n changes: plan.changes.map((change) => toPublicPlannedChange(options.cwd, change)),\n warnings: plan.warnings,\n nextSteps: plan.nextSteps,\n features: [...plan.features],\n aiHandoff: options.aiHandoff,\n tools: options.tools,\n };\n}\n","import { isAbsolute, join, posix, relative, sep } from 'node:path';\n\nimport {\n getManagedAgentSkillCandidatePaths,\n planManagedAgentSkill,\n type ManagedAgentSkillDefinition,\n} from '../scaffolding/agent-skill.js';\nimport { displayProjectPath } from '../scaffolding/project-plan-output.js';\nimport {\n getPlanningPathSnapshot,\n getPlanningFileSnapshot,\n planFileChange,\n type PlanningPathSnapshot,\n} from '../scaffolding/project-plan.js';\nimport {\n generatePolicyGithubActionsWorkflow,\n POLICY_CI_WORKFLOW_PATH,\n} from './policy-scaffold-artifacts.js';\nimport {\n mergePolicyEditorExtensions,\n mergePolicyEditorSettings,\n mergePolicyEditorTasks,\n type PolicyEditorMergeResult,\n} from './policy-scaffold-config.js';\nimport {\n POLICY_INIT_RESULT_VERSION,\n PolicySetupFeature,\n type PolicyInitProjectPlan,\n type PolicyProjectState,\n type PolicySetupFeature as PolicySetupFeatureType,\n} from './policy-scaffold-model.js';\nimport {\n generatePolicyWorkspaceFiles,\n POLICY_STARTER_BUNDLE_DIRECTORY,\n type PolicyStarterFile,\n} from './policy-scaffold-templates.js';\nimport { POLICY_SKILL_FILES, POLICY_SKILL_NAME } from './policy-skill.js';\n\n/** Managed Policy Engine Agent Skill definition. */\nconst POLICY_MANAGED_SKILL: ManagedAgentSkillDefinition = {\n name: POLICY_SKILL_NAME,\n displayName: 'Policy Engine',\n owner: '@transcend-io/cli',\n files: POLICY_SKILL_FILES,\n};\n\n/** In-memory input consumed by the pure policy initializer. */\nexport interface PolicyInitPlanningInput {\n /** Project discovery state. */\n state: PolicyProjectState;\n /** Potential mutation paths keyed by absolute path. */\n snapshots: Readonly<Record<string, PlanningPathSnapshot>>;\n}\n\n/** Optional repository setup selected for policy initialization. */\nexport interface PolicyInitPlanOptions {\n /** Selected setup features. */\n features: readonly PolicySetupFeatureType[];\n /** Exact released Transcend CLI version for generated CI. */\n cliVersion: string;\n}\n\n/**\n * Enumerate all core starter paths that could be created.\n *\n * @param state - Policy project state\n * @param options - Selected repository setup\n * @returns Absolute candidate paths\n */\nexport function getPolicyInitPlanningCandidatePaths(\n state: PolicyProjectState,\n options: Pick<PolicyInitPlanOptions, 'features'>,\n): string[] {\n const paths = new Set(\n generatePolicyWorkspaceFiles().map(({ path }) => join(state.targetDirectory, path)),\n );\n const selected = new Set(options.features);\n if (selected.has(PolicySetupFeature.Editor)) {\n paths.add(join(state.projectRoot, '.vscode', 'settings.json'));\n paths.add(join(state.projectRoot, '.vscode', 'extensions.json'));\n paths.add(join(state.projectRoot, '.vscode', 'tasks.json'));\n }\n if (selected.has(PolicySetupFeature.Skill)) {\n getManagedAgentSkillCandidatePaths(\n state.projectRoot,\n state.existingSkillDirectories,\n POLICY_MANAGED_SKILL,\n ).forEach((path) => paths.add(path));\n }\n if (selected.has(PolicySetupFeature.Ci) && state.repositoryRoot && state.usesGithub) {\n paths.add(join(state.repositoryRoot, POLICY_CI_WORKFLOW_PATH));\n }\n return [...paths].sort((left, right) => left.localeCompare(right));\n}\n\n/**\n * Ensure a destination stays below an approved project root.\n *\n * @param root - Approved root\n * @param path - Candidate path\n */\nfunction assertContained(root: string, path: string): void {\n const child = relative(root, path);\n if (child === '..' || child.startsWith(`..${sep}`) || isAbsolute(child)) {\n throw new Error(`Refusing to modify path outside project root: ${path}`);\n }\n}\n\n/**\n * Enumerate generated file and directory paths allowed in an exact starter.\n *\n * @param files - Starter files\n * @returns POSIX relative paths\n */\nfunction starterRelativePaths(files: readonly PolicyStarterFile[]): Set<string> {\n const paths = new Set<string>([`${POLICY_STARTER_BUNDLE_DIRECTORY}/input.json`]);\n files.forEach(({ path }) => {\n paths.add(path);\n let parent = posix.dirname(path);\n while (parent !== '.') {\n paths.add(parent);\n parent = posix.dirname(parent);\n }\n });\n return paths;\n}\n\n/**\n * Add or classify one regular-file mutation.\n *\n * @param plan - Policy plan being assembled\n * @param input - Collected snapshots\n * @param options - Desired file\n */\nfunction addFileChange(\n plan: PolicyInitProjectPlan,\n input: PolicyInitPlanningInput,\n options: {\n /** Absolute destination path. */\n path: string;\n /** Complete desired contents. */\n contents: string;\n /** Human-readable plan description. */\n description: string;\n /** Refuse existing contents. */\n createOnly?: boolean;\n },\n): void {\n const change = planFileChange({\n snapshot: getPlanningFileSnapshot(input.snapshots, options.path),\n after: options.contents,\n description: options.description,\n ...(options.createOnly === undefined ? {} : { createOnly: options.createOnly }),\n });\n if (change) {\n plan.changes.push(change);\n } else {\n plan.unchanged.push(options.path);\n }\n}\n\n/**\n * Add one safe editor merge and its preservation warnings.\n *\n * @param plan - Policy plan being assembled\n * @param input - Collected snapshots\n * @param path - Absolute editor artifact path\n * @param result - Pure JSONC merge result\n * @param description - Human-readable plan description\n * @param cwd - Invocation directory for portable warning paths\n */\nfunction addEditorMerge(\n plan: PolicyInitProjectPlan,\n input: PolicyInitPlanningInput,\n path: string,\n result: PolicyEditorMergeResult,\n description: string,\n cwd: string,\n): void {\n addFileChange(plan, input, {\n path,\n contents: result.contents,\n description,\n });\n plan.warnings.push(\n ...result.warnings.map((warning) => `${warning} (${displayProjectPath(cwd, path)})`),\n );\n}\n\n/**\n * Build a safe policy project plan without reading the filesystem.\n *\n * Empty targets receive the complete starter. Existing targets are classified\n * only; no domain file is added, merged, or overwritten.\n *\n * @param input - Collected project state and path snapshots\n * @param options - Selected setup and pinned CLI version\n * @returns Validated policy initialization plan\n */\nexport function buildPolicyInitPlan(\n input: PolicyInitPlanningInput,\n options: PolicyInitPlanOptions,\n): PolicyInitProjectPlan {\n const { state } = input;\n const files = generatePolicyWorkspaceFiles();\n const newCommand = 'transcend policy new';\n const plan: PolicyInitProjectPlan = {\n version: POLICY_INIT_RESULT_VERSION,\n command: 'init',\n rootDirectory: state.projectRoot,\n targetDirectory: state.targetDirectory,\n // Init creates a workspace only; bundles (and their .manifest) come from `policy new`.\n manifestPath: state.targetDirectory,\n changes: [],\n unchanged: [],\n warnings: [],\n nextSteps: [newCommand],\n features: [...options.features],\n };\n\n const candidatePaths = getPolicyInitPlanningCandidatePaths(state, options);\n assertContained(state.projectRoot, state.targetDirectory);\n candidatePaths.forEach((path) => assertContained(state.projectRoot, path));\n\n if (state.relativeFilePaths.length === 0) {\n plan.directoryPreconditions = [\n {\n path: state.targetDirectory,\n relativePaths: [...state.relativePaths],\n },\n ];\n files.forEach((file) => {\n const path = join(state.targetDirectory, file.path);\n const snapshot = getPlanningPathSnapshot(input.snapshots, path);\n if (snapshot.kind !== 'absent') {\n throw new Error(`Expected an empty policy target, but found an entry at: ${path}`);\n }\n addFileChange(plan, input, {\n path,\n contents: file.contents,\n description: file.description,\n createOnly: true,\n });\n });\n } else {\n let allWorkspaceFilesMatch = true;\n files.forEach((file) => {\n const path = join(state.targetDirectory, file.path);\n const snapshot = getPlanningPathSnapshot(input.snapshots, path);\n if (snapshot.kind === 'file' && snapshot.contents === file.contents) {\n plan.unchanged.push(path);\n return;\n }\n allWorkspaceFilesMatch = false;\n if (snapshot.kind !== 'absent') {\n plan.unchanged.push(path);\n plan.warnings.push(\n `Existing policy scaffold path was left unchanged: ${displayProjectPath(\n state.invocationDirectory,\n path,\n )}`,\n );\n }\n });\n\n const allowedPaths = starterRelativePaths(files);\n const hasCustomPaths = state.relativeFilePaths.some((path) => !allowedPaths.has(path));\n if (!allWorkspaceFilesMatch || hasCustomPaths) {\n plan.warnings.push(\n `Existing policy target contains custom or partial content, so no workspace files were added or overwritten. ` +\n `Review ${displayProjectPath(\n state.invocationDirectory,\n state.targetDirectory,\n )} manually, then run \\`${newCommand}\\`.`,\n );\n }\n }\n\n const selected = new Set(options.features);\n const root = state.projectRoot;\n if (selected.has(PolicySetupFeature.Editor)) {\n const settingsPath = join(root, '.vscode', 'settings.json');\n const extensionsPath = join(root, '.vscode', 'extensions.json');\n const tasksPath = join(root, '.vscode', 'tasks.json');\n\n type EditorMergeFn = (\n contents: string | null,\n repositoryRoot: string,\n targetDirectory: string,\n ) => PolicyEditorMergeResult;\n const editorArtifacts: {\n /** Absolute path. */\n path: string;\n /** Plan description. */\n description: string;\n /** Merge function. */\n merge: EditorMergeFn;\n }[] = [\n {\n path: settingsPath,\n description: 'Merge strict target-scoped OPA and Rego editor settings',\n merge: (contents, repositoryRoot, targetDirectory) =>\n mergePolicyEditorSettings(contents, repositoryRoot, targetDirectory),\n },\n {\n path: extensionsPath,\n description: 'Recommend the OPA extension and discourage its syntax-only conflict',\n merge: (contents) => mergePolicyEditorExtensions(contents),\n },\n {\n path: tasksPath,\n description: 'Create the VS Code task configuration',\n merge: (contents, repositoryRoot, targetDirectory) =>\n mergePolicyEditorTasks(contents, repositoryRoot, targetDirectory),\n },\n ];\n editorArtifacts.forEach(({ path, description, merge }) => {\n const snapshot = getPlanningPathSnapshot(input.snapshots, path);\n if (snapshot.kind !== 'absent' && snapshot.kind !== 'file') {\n plan.unchanged.push(path);\n plan.warnings.push(\n `Existing VS Code artifact is not a regular file and was left unchanged: ${displayProjectPath(\n state.invocationDirectory,\n path,\n )}`,\n );\n return;\n }\n addEditorMerge(\n plan,\n input,\n path,\n merge(snapshot.kind === 'file' ? snapshot.contents : null, root, state.targetDirectory),\n description,\n state.invocationDirectory,\n );\n });\n }\n\n if (selected.has(PolicySetupFeature.Skill)) {\n const skillPlan = planManagedAgentSkill({\n rootDirectory: root,\n existingDirectories: state.existingSkillDirectories,\n snapshots: input.snapshots,\n skill: POLICY_MANAGED_SKILL,\n preserveModified: true,\n });\n plan.changes.push(...skillPlan.changes);\n plan.unchanged.push(...skillPlan.unchanged);\n plan.warnings.push(\n ...skillPlan.warnings.map((warning) => {\n return skillPlan.unchanged.reduce(\n (rendered, path) =>\n rendered.replace(path, displayProjectPath(state.invocationDirectory, path)),\n warning,\n );\n }),\n );\n }\n\n if (selected.has(PolicySetupFeature.Ci)) {\n if (!state.repositoryRoot || !state.usesGithub) {\n plan.warnings.push(\n 'GitHub Actions setup was selected, but this target is not inside a detected GitHub repository.',\n );\n } else {\n const workflowPath = join(state.repositoryRoot, POLICY_CI_WORKFLOW_PATH);\n const workspaceDirectory =\n relative(state.repositoryRoot, state.targetDirectory).split(sep).join('/') || '.';\n const workflowContents = generatePolicyGithubActionsWorkflow({\n cliVersion: options.cliVersion,\n workspaceDirectory,\n bundleDirectories: [],\n });\n const workflowSnapshot = getPlanningPathSnapshot(input.snapshots, workflowPath);\n if (workflowSnapshot.kind === 'absent') {\n addFileChange(plan, input, {\n path: workflowPath,\n contents: workflowContents,\n description: 'Add credential-free Policy Engine validation',\n createOnly: true,\n });\n } else if (\n workflowSnapshot.kind === 'file' &&\n workflowSnapshot.contents === workflowContents\n ) {\n plan.unchanged.push(workflowPath);\n } else {\n plan.unchanged.push(workflowPath);\n plan.warnings.push(\n `Existing GitHub Actions workflow was left unchanged: ${displayProjectPath(\n state.invocationDirectory,\n workflowPath,\n )}. Adapt it manually to validate each policy bundle.`,\n );\n }\n }\n }\n\n plan.changes.forEach(({ path }) => assertContained(state.projectRoot, path));\n return plan;\n}\n","import colors from 'colors';\n\nimport { version as CLI_VERSION } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport {\n runCapturedProcess,\n type CapturedProcessResult,\n type CapturedProcessRunner,\n} from '../../../lib/cli/run-captured-process.js';\nimport {\n DEFAULT_POLICY_PROJECT_DIRECTORY,\n discoverPolicyProject,\n} from '../../../lib/policy/policy-project-discovery.js';\nimport {\n OPA_INSTALL_URL,\n OPA_MISSING_MESSAGE,\n parsePolicyToolVersion,\n MINIMUM_POLICY_STARTER_REGAL_VERSION,\n REGAL_INSTALL_URL,\n REGAL_MISSING_MESSAGE,\n unsupportedOpaVersionMessage,\n unsupportedRegalVersionMessage,\n} from '../../../lib/policy/policy-runtime.js';\nimport {\n PolicySetupFeature,\n type PolicySetupFeature as PolicySetupFeatureType,\n} from '../../../lib/policy/policy-scaffold-model.js';\nimport {\n buildPolicyInitAiHandoff,\n buildPolicyInitPlanResult,\n type PolicyInitToolVersions,\n} from '../../../lib/policy/policy-scaffold-output.js';\nimport {\n buildPolicyInitPlan,\n getPolicyInitPlanningCandidatePaths,\n} from '../../../lib/policy/policy-scaffold-planning.js';\nimport { POLICY_STARTER_OPA_VERSION } from '../../../lib/policy/policy-scaffold-templates.js';\nimport { collectPlanningSnapshots } from '../../../lib/scaffolding/project-discovery.js';\nimport { applyProjectPlan } from '../../../lib/scaffolding/project-plan-apply.js';\nimport {\n displayProjectPath,\n quoteShellArgument,\n renderProjectPlan,\n} from '../../../lib/scaffolding/project-plan-output.js';\nimport {\n isInteractivePromptInvocation,\n PromptCancelledError,\n resolveSetupFeatures,\n ScaffoldPrompts,\n} from '../../../lib/scaffolding/prompts.js';\n\n/** Flags for `transcend policy init`. */\nexport interface PolicyInitFlags {\n /** Install repository-level VS Code setup. */\n editor?: boolean;\n /** Install the Policy Engine Agent Skill. */\n skill?: boolean;\n /** Install validation-only GitHub Actions CI. */\n ci?: boolean;\n /** Disable prompts. */\n noInteractive: boolean;\n /** Render but do not apply the plan. */\n dryRun: boolean;\n /** Approve the final displayed plan. */\n yes: boolean;\n /** Emit one stable JSON result on stdout. */\n json: boolean;\n}\n\n/** User-facing optional setup labels. */\nconst SETUP_LABELS: Readonly<Record<PolicySetupFeatureType, string>> = {\n [PolicySetupFeature.Editor]: 'VS Code settings and lint task',\n [PolicySetupFeature.Skill]: 'Policy Engine Agent Skill',\n [PolicySetupFeature.Ci]: 'Validation-only GitHub Actions',\n};\n\n/** All optional setup features in stable prompt order. */\nconst ALL_SETUP_FEATURES = Object.values(PolicySetupFeature);\n\n/** Runtime compatibility detected before policy planning. */\ninterface PolicyRuntimeProbe {\n /** Compatible tool versions. */\n tools: PolicyInitToolVersions;\n /** Missing or incompatible runtime guidance. */\n warnings: string[];\n}\n\n/**\n * Explain a failed version subprocess with official installation guidance.\n *\n * @param tool - Policy tool name\n * @param result - Failed captured process\n * @returns Actionable warning\n */\nfunction failedVersionProbeMessage(tool: 'OPA' | 'Regal', result: CapturedProcessResult): string {\n const detail = [result.stdout.trim(), result.stderr.trim()].filter(Boolean).join('\\n');\n const url = tool === 'OPA' ? OPA_INSTALL_URL : REGAL_INSTALL_URL;\n const requirement =\n tool === 'OPA' ? 'OPA 1.x' : `Regal ${MINIMUM_POLICY_STARTER_REGAL_VERSION} or newer`;\n return (\n `${requirement} is required, but \\`${tool.toLowerCase()} version\\` exited with code ` +\n `${result.code}${detail ? `: ${detail}` : '.'} ` +\n `Install or upgrade it using the official instructions: ${url}`\n );\n}\n\n/**\n * Probe both local policy runtimes without installing or modifying them.\n *\n * @param context - CLI context\n * @param cwd - Invocation working directory\n * @param runner - Captured subprocess runner\n * @returns Compatible versions and exact runtime guidance\n */\nasync function probePolicyRuntimes(\n context: LocalContext,\n cwd: string,\n runner: CapturedProcessRunner,\n): Promise<PolicyRuntimeProbe> {\n const tools: PolicyInitToolVersions = { opa: null, regal: null };\n const warnings: string[] = [];\n\n const opaResult = await runner('opa', ['version'], { cwd }, context);\n if (opaResult.error?.code === 'ENOENT') {\n warnings.push(OPA_MISSING_MESSAGE);\n } else {\n const output = `${opaResult.stdout}\\n${opaResult.stderr}`;\n const unsupported = unsupportedOpaVersionMessage(output);\n if (opaResult.code !== 0) {\n warnings.push(unsupported ?? failedVersionProbeMessage('OPA', opaResult));\n } else if (unsupported) {\n warnings.push(unsupported);\n } else {\n tools.opa = parsePolicyToolVersion(output)!.version;\n }\n }\n\n const regalResult = await runner('regal', ['version'], { cwd }, context);\n if (regalResult.error?.code === 'ENOENT') {\n warnings.push(REGAL_MISSING_MESSAGE);\n } else {\n const output = `${regalResult.stdout}\\n${regalResult.stderr}`;\n const unsupported = unsupportedRegalVersionMessage(\n output,\n MINIMUM_POLICY_STARTER_REGAL_VERSION,\n `the generated OPA ${POLICY_STARTER_OPA_VERSION} capabilities configuration`,\n );\n if (regalResult.code !== 0) {\n warnings.push(unsupported ?? failedVersionProbeMessage('Regal', regalResult));\n } else if (unsupported) {\n warnings.push(unsupported);\n } else {\n tools.regal = parsePolicyToolVersion(output)!.version;\n }\n }\n\n return { tools, warnings };\n}\n\n/**\n * Initialize a credential-free local Policy Engine project.\n *\n * @param this - CLI context\n * @param flags - Scaffold and interaction flags\n * @param directory - Target policy directory\n * @param runner - Captured policy tool runner\n */\nexport async function init(\n this: LocalContext,\n flags: PolicyInitFlags,\n directory: string = DEFAULT_POLICY_PROJECT_DIRECTORY,\n runner: CapturedProcessRunner = runCapturedProcess,\n): Promise<void> {\n doneInputValidation(this.process);\n try {\n const runtime = await probePolicyRuntimes(this, this.process.cwd(), runner);\n const state = discoverPolicyProject(this, directory);\n const prompts = new ScaffoldPrompts(this);\n const interactive = isInteractivePromptInvocation(\n flags,\n this.process.stdin.isTTY,\n this.process.stderr.isTTY,\n );\n const features = await resolveSetupFeatures(prompts, {\n features: ALL_SETUP_FEATURES,\n labels: SETUP_LABELS,\n enabled: {\n [PolicySetupFeature.Editor]: flags.editor,\n [PolicySetupFeature.Skill]: flags.skill,\n [PolicySetupFeature.Ci]: flags.ci,\n },\n interactive,\n });\n const candidatePaths = getPolicyInitPlanningCandidatePaths(state, { features });\n const snapshots = collectPlanningSnapshots(this, state.projectRoot, candidatePaths);\n\n const plan = buildPolicyInitPlan(\n { state, snapshots },\n {\n features,\n cliVersion: CLI_VERSION,\n },\n );\n plan.warnings.push(...runtime.warnings);\n\n if (!flags.json) {\n this.logger.info(\n renderProjectPlan(plan, {\n cwd: this.process.cwd(),\n title: 'Policy initialization plan',\n details: [{ label: 'Target', path: plan.targetDirectory }],\n }),\n );\n }\n\n let approved = plan.changes.length === 0 || flags.dryRun;\n if (plan.changes.length > 0 && !flags.dryRun) {\n if (flags.yes) {\n approved = true;\n } else if (interactive) {\n approved = await prompts.confirm('Apply this complete plan?', true);\n } else {\n throw new Error(\n 'The plan requires approval in a non-interactive invocation. Review with --dryRun, then pass --yes.',\n );\n }\n }\n\n if (approved && !flags.dryRun && plan.changes.length > 0) {\n await applyProjectPlan(this, plan);\n }\n const applied = approved && !flags.dryRun && plan.changes.length > 0;\n const setupAvailable = approved && !flags.dryRun;\n const aiHandoff = buildPolicyInitAiHandoff({\n projectPath: quoteShellArgument(\n displayProjectPath(this.process.cwd(), state.targetDirectory),\n ),\n hasSkill: setupAvailable && features.includes(PolicySetupFeature.Skill),\n newCommand: plan.nextSteps[0]!,\n });\n const result = buildPolicyInitPlanResult(plan, {\n applied,\n dryRun: flags.dryRun,\n cwd: this.process.cwd(),\n aiHandoff,\n tools: runtime.tools,\n });\n if (flags.json) {\n this.process.stdout.write(`${JSON.stringify(result)}\\n`);\n return;\n }\n if (flags.dryRun) {\n this.logger.info(colors.yellow('Dry run complete. No changes were written.'));\n return;\n }\n if (!approved) {\n this.logger.info(colors.yellow('No changes applied.'));\n return;\n }\n if (plan.changes.length === 0) {\n const message =\n plan.warnings.length === runtime.warnings.length\n ? 'Policy project is already initialized.'\n : 'Existing policy project was left unchanged.';\n this.logger.info(colors.green(message));\n } else {\n this.logger.info(colors.green('Policy project initialized.'));\n }\n if (plan.nextSteps.length > 0) {\n this.logger.info(`\\n${colors.bold('Next steps')}`);\n plan.nextSteps.forEach((step) => this.logger.info(step));\n }\n this.logger.info(`\\n${colors.bold('AI handoff — paste into your coding agent')}`);\n this.logger.info(aiHandoff);\n } catch (error) {\n if (error instanceof PromptCancelledError) {\n return this.process.exit(130);\n }\n throw error;\n }\n}\n"],"mappings":"uyBAOA,MAAa,EAAqB,CAEhC,OAAQ,SAER,MAAO,QAEP,GAAI,KACL,OCdD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ICAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ICAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ICAA,ilHCAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECQA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AM,OAAQ,CAChB,KAAK,OAAO,KAAK,EAAO,OAAO,6CAA6C,CAAC,CAC7E,OAEF,GAAI,CAAC,EAAU,CACb,KAAK,OAAO,KAAK,EAAO,OAAO,sBAAsB,CAAC,CACtD,OAEF,GAAI,EAAK,QAAQ,SAAW,EAAG,CAC7B,IAAM,EACJ,EAAK,SAAS,SAAW,EAAQ,SAAS,OACtC,yCACA,8CACN,KAAK,OAAO,KAAK,EAAO,MAAM,EAAQ,CAAC,MAEvC,KAAK,OAAO,KAAK,EAAO,MAAM,8BAA8B,CAAC,CAE3D,EAAK,UAAU,OAAS,IAC1B,KAAK,OAAO,KAAK,KAAK,EAAO,KAAK,aAAa,GAAG,CAClD,EAAK,UAAU,QAAS,GAAS,KAAK,OAAO,KAAK,EAAK,CAAC,EAE1D,KAAK,OAAO,KAAK,KAAK,EAAO,KAAK,4CAA4C,GAAG,CACjF,KAAK,OAAO,KAAK,EAAU,OACpB,EAAO,CACd,GAAI,aAAiB,EACnB,OAAO,KAAK,QAAQ,KAAK,IAAI,CAE/B,MAAM"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{t as e}from"./logger-CPu6zbyQ.mjs";import{n as t}from"./parseAttributesFromString-C5hJMRvt.mjs";import{n}from"./readCsv-DNcJ_UfU.mjs";import{n as r}from"./inquirer-
|
|
1
|
+
import{t as e}from"./logger-CPu6zbyQ.mjs";import{n as t}from"./parseAttributesFromString-C5hJMRvt.mjs";import{n}from"./readCsv-DNcJ_UfU.mjs";import{n as r}from"./inquirer-DK1JbPA0.mjs";import{t as i}from"./done-input-validation-LiTaCEzF.mjs";import{PreferenceTopicType as a}from"@transcend-io/privacy-types";import{chunk as o,difference as s,groupBy as c,keyBy as l,uniq as u}from"lodash-es";import d from"node:path";import f from"colors";import{map as p,mapSeries as m,splitCsvToList as h}from"@transcend-io/utils";import{apply as g}from"@transcend-io/type-utils";import*as _ from"io-ts";import{PreferenceState as v,buildTranscendGraphQLClient as y,checkIfPendingPreferenceUpdatesAreNoOp as b,checkIfPendingPreferenceUpdatesCauseConflict as x,createSombraGotInstance as S,fetchAllPreferenceTopics as C,fetchAllPurposes as w,getPreferenceUpdatesFromRow as T,getPreferencesForIdentifiers as E}from"@transcend-io/sdk";import D from"cli-progress";import O from"inquirer";import{PersistedState as k}from"@transcend-io/persisted-state";async function A(t,n,{purposeSlugs:r,preferenceTopics:i,forceTriggerWorkflows:o}){let c=s(u(t.map(e=>Object.keys(e)).flat()),[...n.identifierColumn?[n.identifierColumn]:[],...n.timestampColum?[n.timestampColum]:[]]);if(c.length===0){if(o)return n;throw Error(`No other columns to process`)}let l=[...r,...i.map(e=>`${e.purpose.trackingType}->${e.slug}`)];return await m(c,async o=>{let s=u(t.map(e=>e[o])),c=n.columnToPurposeName[o];if(c)e.info(f.magenta(`Column "${o}" is associated with purpose "${c.purpose}"`));else{let{purposeName:e}=await O.prompt([{name:`purposeName`,message:`Choose the purpose that column ${o} is associated with`,type:`list`,default:l.find(e=>e.startsWith(r[0])),choices:l}]),[t,n]=e.split(`->`);c={purpose:t,preference:n||null,valueMapping:{}}}await m(s,async t=>{if(c.valueMapping[t]!==void 0){e.info(f.magenta(`Value "${t}" is associated with purpose value "${c.valueMapping[t]}"`));return}if(c.preference===null){let{purposeValue:e}=await O.prompt([{name:`purposeValue`,message:`Choose the purpose value for value "${t}" associated with purpose "${c.purpose}"`,type:`confirm`,default:t!==`false`}]);c.valueMapping[t]=e}if(c.preference!==null){let n=i.find(e=>e.slug===c.preference);if(!n){e.error(f.red(`Preference topic "${c.preference}" not found`));return}let r=n.preferenceOptionValues.map(({slug:e})=>e);if(n.type===a.Boolean){let{preferenceValue:e}=await O.prompt([{name:`preferenceValue`,message:`Choose the preference value for "${n.slug}" value "${t}" associated with purpose "${c.purpose}"`,type:`confirm`,default:t!==`false`}]);c.valueMapping[t]=e;return}if(n.type===a.Select){let{preferenceValue:e}=await O.prompt([{name:`preferenceValue`,message:`Choose the preference value for "${n.slug}" value "${t}" associated with purpose "${c.purpose}"`,type:`list`,choices:r,default:r.find(e=>e===t)}]);c.valueMapping[t]=e;return}if(n.type===a.MultiSelect){await m(h(t),async e=>{if(c.valueMapping[e]!==void 0)return;let{preferenceValue:t}=await O.prompt([{name:`preferenceValue`,message:`Choose the preference value for "${n.slug}" value "${e}" associated with purpose "${c.purpose}"`,type:`list`,choices:r,default:r.find(t=>t===e)}]);c.valueMapping[e]=t});return}throw Error(`Unknown preference topic type: ${n.type}`)}}),n.columnToPurposeName[o]=c}),n}async function j(t,n){let i=s(u(t.map(e=>Object.keys(e)).flat()),[...n.identifierColumn?[n.identifierColumn]:[],...Object.keys(n.columnToPurposeName)]);if(!n.identifierColumn){let{identifierName:e}=await O.prompt([{name:`identifierName`,message:`Choose the column that will be used as the identifier to upload consent preferences by`,type:`list`,default:i.find(e=>e.toLowerCase().includes(`email`))||i[0],choices:i}]);n.identifierColumn=e}e.info(f.magenta(`Using identifier column "${n.identifierColumn}"`));let a=t.map((e,t)=>e[n.identifierColumn]?null:[t]).filter(e=>!!e).flat();if(a.length>0){let i=`The identifier column "${n.identifierColumn}" is missing a value for the following rows: ${a.join(`, `)}`;if(e.warn(f.yellow(i)),!await r({message:`Would you like to skip rows missing an identifier?`}))throw Error(i);let o=t.length;t=t.filter(e=>e[n.identifierColumn]),e.info(f.yellow(`Skipped ${o-t.length} rows missing an identifier`))}e.info(f.magenta(`The identifier column "${n.identifierColumn}" is present for all rows`));let o=c(t,n.identifierColumn),l=Object.entries(o).filter(([,e])=>e.length>1);if(l.length>0){let i=`The identifier column "${n.identifierColumn}" has duplicate values for the following rows: ${l.slice(0,10).map(([e,t])=>`${e} (${t.length})`).join(`
|
|
2
2
|
`)}`;if(e.warn(f.yellow(i)),!await r({message:`Would you like to automatically take the latest update?`}))throw Error(i);t=Object.entries(o).map(([,e])=>e.sort((e,t)=>new Date(t[n.timestampColum]).getTime()-new Date(e[n.timestampColum]).getTime())[0]).filter(e=>e)}return{currentState:n,preferences:t}}async function M(t,n){let r=s(u(t.map(e=>Object.keys(e)).flat()),[...n.identifierColumn?[n.identifierColumn]:[],...Object.keys(n.columnToPurposeName)]);if(!n.timestampColum){let{timestampName:e}=await O.prompt([{name:`timestampName`,message:`Choose the column that will be used as the timestamp of last preference update`,type:`list`,default:r.find(e=>e.toLowerCase().includes(`date`))||r.find(e=>e.toLowerCase().includes(`time`))||r[0],choices:[...r,`[NONE]`]}]);n.timestampColum=e}if(e.info(f.magenta(`Using timestamp column "${n.timestampColum}"`)),n.timestampColum!==`[NONE]`){let r=t.map((e,t)=>e[n.timestampColum]?null:[t]).filter(e=>!!e).flat();if(r.length>0)throw Error(`The timestamp column "${n.timestampColum}" is missing a value for the following rows: ${r.join(`
|
|
3
3
|
`)}`);e.info(f.magenta(`The timestamp column "${n.timestampColum}" is present for all row`))}return n}async function N({file:t,sombra:r,purposeSlugs:i,preferenceTopics:a,partitionKey:o,skipExistingRecordCheck:s,forceTriggerWorkflows:c},u){let d=new Date().getTime(),p=u.getValue(`fileMetadata`);e.info(f.magenta(`Reading in file: "${t}"`));let m=n(t,_.record(_.string,_.string)),h={columnToPurposeName:{},pendingSafeUpdates:{},pendingConflictUpdates:{},skippedUpdates:{},...p[t]||{},lastFetchedAt:new Date().toISOString()};h=await M(m,h),p[t]=h,await u.setValue(p,`fileMetadata`);let g=await j(m,h);h=g.currentState,m=g.preferences,p[t]=h,await u.setValue(p,`fileMetadata`),h=await A(m,h,{preferenceTopics:a,purposeSlugs:i,forceTriggerWorkflows:c}),p[t]=h,await u.setValue(p,`fileMetadata`);let v=m.map(e=>e[h.identifierColumn]),y=new D.SingleBar({},D.Presets.shades_classic);s||y.start(v.length,0);let S=s?[]:await E(r,{identifiers:v.map(e=>({value:e})),partitionKey:o,logger:e,onProgress:(e,t)=>y.update(e,{total:t})});y.stop();let C=l(S,`userId`);h.pendingConflictUpdates={},h.pendingSafeUpdates={},h.skippedUpdates={},m.forEach(e=>{let t=e[h.identifierColumn],n=T({row:e,columnToPurposeName:h.columnToPurposeName,preferenceTopics:a,purposeSlugs:i}),r=C[t];if(c&&!r)throw Error(`No existing consent record found for user with id: ${t}.
|
|
4
4
|
When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`);if(r&&b({currentConsentRecord:r,pendingUpdates:n,preferenceTopics:a})&&!c){h.skippedUpdates[t]=e;return}if(r&&x({currentConsentRecord:r,pendingUpdates:n,preferenceTopics:a})){h.pendingConflictUpdates[t]={row:e,record:r};return}h.pendingSafeUpdates[t]=e}),p[t]=h,await u.setValue(p,`fileMetadata`);let w=new Date().getTime();e.info(f.green(`Successfully pre-processed file: "${t}" in ${(w-d)/1e3}s`))}async function P({auth:n,sombraAuth:r,receiptFilepath:i,file:a,partition:s,isSilent:c=!0,dryRun:l=!1,skipWorkflowTriggers:u=!1,skipConflictUpdates:d=!1,skipExistingRecordCheck:m=!1,attributes:h=[],transcendUrl:_,forceTriggerWorkflows:b=!1}){let x=t(h),E=new k(i,v,{fileMetadata:{},failingUpdates:{},pendingUpdates:{}}),O=E.getValue(`failingUpdates`),A=E.getValue(`pendingUpdates`),j=E.getValue(`fileMetadata`);e.info(f.magenta(`Restored cache, there are:
|
|
5
5
|
${Object.values(O).length} failing requests to be retried\n${Object.values(A).length} pending requests to be processed\nThe following files are stored in cache and will be used:\n${Object.keys(j).map(e=>e).join(`
|
|
6
6
|
`)}\nThe following file will be processed: ${a}\n`));let M=y(_,n),[P,F,I]=await Promise.all([S(_,n,{logger:e,sombraApiKey:r,sombraUrl:process.env.SOMBRA_URL}),w(M,{logger:e}),C(M,{logger:e})]);await N({file:a,purposeSlugs:F.map(e=>e.trackingType),preferenceTopics:I,sombra:P,partitionKey:s,skipExistingRecordCheck:m,forceTriggerWorkflows:b},E);let L={};j=E.getValue(`fileMetadata`);let R=j[a];if(e.info(f.magenta(`Found ${Object.entries(R.pendingSafeUpdates).length} safe updates in ${a}`)),e.info(f.magenta(`Found ${Object.entries(R.pendingConflictUpdates).length} conflict updates in ${a}`)),e.info(f.magenta(`Found ${Object.entries(R.skippedUpdates).length} skipped updates in ${a}`)),Object.entries({...R.pendingSafeUpdates,...d?{}:g(R.pendingConflictUpdates,({row:e})=>e)}).forEach(([e,t])=>{let n=R.timestampColum===`[NONE]`?new Date:new Date(t[R.timestampColum]),r=T({row:t,columnToPurposeName:R.columnToPurposeName,preferenceTopics:I,purposeSlugs:F.map(e=>e.trackingType)});L[e]={userId:e,partition:s,timestamp:n.toISOString(),purposes:Object.entries(r).map(([e,t])=>({...t,purpose:e,workflowSettings:{attributes:x,isSilent:c,skipWorkflowTrigger:u,...b?{forceTriggerWorkflow:b}:{}}}))}}),await E.setValue(L,`pendingUpdates`),await E.setValue({},`failingUpdates`),l){e.info(f.green(`Dry run complete, exiting. ${Object.values(L).length} pending updates. Check file: ${i}`));return}e.info(f.magenta(`Uploading ${Object.values(L).length} preferences to partition: ${s}`));let z=new Date().getTime(),B=new D.SingleBar({},D.Presets.shades_classic),V=0,H=Object.entries(L),U=o(H,u?100:10);B.start(H.length,0),await p(U,async t=>{try{await P.put(`v1/preferences`,{json:{records:t.map(([,e])=>e),skipWorkflowTriggers:u}}).json()}catch(n){try{let t=JSON.parse(n?.response?.body||`{}`);t.error&&e.error(f.red(`Error: ${t.error}`))}catch{}e.error(f.red(`Failed to upload ${t.length} user preferences to partition ${s}: ${n?.response?.body||n?.message}`));let r=E.getValue(`failingUpdates`);t.forEach(([e,t])=>{r[e]={uploadedAt:new Date().toISOString(),update:t,error:n?.response?.body||n?.message||`Unknown error`}}),await E.setValue(r,`failingUpdates`)}V+=t.length,B.update(V)},{concurrency:40}),B.stop();let W=new Date().getTime()-z;e.info(f.green(`Successfully uploaded ${H.length} user preferences to partition ${s} in "${W/1e3}" seconds!`))}async function F({auth:e,partition:t,sombraAuth:n,transcendUrl:r,file:a=``,directory:o,dryRun:s,skipExistingRecordCheck:c,receiptFileDir:l,skipWorkflowTriggers:u,forceTriggerWorkflows:m,skipConflictUpdates:g,isSilent:_,attributes:v,concurrency:y}){o&&a&&(this.logger.error(f.red(`Cannot provide both a directory and a file. Please provide only one.`)),this.process.exit(1)),!a&&!o&&(this.logger.error(f.red(`A file or directory must be provided. Please provide one using --file=./preferences.csv or --directory=./preferences`)),this.process.exit(1)),i(this.process);let b=[];if(o)try{let e=this.fs.readdirSync(o).filter(e=>e.endsWith(`.csv`));e.length===0&&(this.logger.error(f.red(`No CSV files found in directory: ${o}`)),this.process.exit(1)),b.push(...e.map(e=>d.join(o,e)))}catch(e){this.logger.error(f.red(`Failed to read directory: ${o}`)),this.logger.error(f.red(e.message)),this.process.exit(1)}else try{a.endsWith(`.csv`)||(this.logger.error(f.red(`File must be a CSV file`)),this.process.exit(1)),b.push(a)}catch(e){this.logger.error(f.red(`Failed to access file: ${a}`)),this.logger.error(f.red(e.message)),this.process.exit(1)}this.logger.info(f.green(`Processing ${b.length} consent preferences files for partition: ${t}`)),this.logger.debug(`Files to process: ${b.join(`, `)}`),c&&this.logger.info(f.bgYellow(`Skipping existing record check: ${c}`)),await p(b,async i=>{let a=d.basename(i).replace(`.csv`,``);await P({receiptFilepath:d.join(l,`${a}-receipts.json`),auth:e,sombraAuth:n,file:i,partition:t,transcendUrl:r,skipConflictUpdates:g,skipWorkflowTriggers:u,skipExistingRecordCheck:c,isSilent:_,dryRun:s,attributes:h(v),forceTriggerWorkflows:m})},{concurrency:y})}export{F as uploadPreferences};
|
|
7
|
-
//# sourceMappingURL=impl-
|
|
7
|
+
//# sourceMappingURL=impl-HsRwcfRu.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-agm4lpyq.mjs","names":[],"sources":["../src/lib/preference-management/parsePreferenceAndPurposeValuesFromCsv.ts","../src/lib/preference-management/parsePreferenceIdentifiersFromCsv.ts","../src/lib/preference-management/parsePreferenceTimestampsFromCsv.ts","../src/lib/preference-management/parsePreferenceManagementCsv.ts","../src/lib/preference-management/uploadPreferenceManagementPreferencesInteractive.ts","../src/commands/consent/upload-preferences/impl.ts"],"sourcesContent":["import { PreferenceTopicType } from '@transcend-io/privacy-types';\nimport { FileMetadataState, type PreferenceTopic } from '@transcend-io/sdk';\nimport { mapSeries, splitCsvToList } from '@transcend-io/utils';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse out the purpose.enabled and preference values from a CSV file\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @param options - Options\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceAndPurposeValuesFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n {\n purposeSlugs,\n preferenceTopics,\n forceTriggerWorkflows,\n }: {\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const otherColumns = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...(currentState.timestampColum ? [currentState.timestampColum] : []),\n ]);\n if (otherColumns.length === 0) {\n if (forceTriggerWorkflows) {\n return currentState;\n }\n throw new Error('No other columns to process');\n }\n\n // The purpose and preferences to map to\n const purposeNames = [\n ...purposeSlugs,\n ...preferenceTopics.map((x) => `${x.purpose.trackingType}->${x.slug}`),\n ];\n\n // Ensure all columns are accounted for\n await mapSeries(otherColumns, async (col) => {\n // Determine the unique values to map in this column\n const uniqueValues = uniq(preferences.map((x) => x[col]));\n\n // Map the column to a purpose\n let purposeMapping = currentState.columnToPurposeName[col];\n if (purposeMapping) {\n logger.info(\n colors.magenta(`Column \"${col}\" is associated with purpose \"${purposeMapping.purpose}\"`),\n );\n } else {\n const { purposeName } = await inquirer.prompt<{\n /** purpose name */\n purposeName: string;\n }>([\n {\n name: 'purposeName',\n message: `Choose the purpose that column ${col} is associated with`,\n type: 'list',\n default: purposeNames.find((x) => x.startsWith(purposeSlugs[0])),\n choices: purposeNames,\n },\n ]);\n const [purposeSlug, preferenceSlug] = purposeName.split('->');\n purposeMapping = {\n purpose: purposeSlug,\n preference: preferenceSlug || null,\n valueMapping: {},\n };\n }\n\n // map each value to the purpose value\n await mapSeries(uniqueValues, async (value) => {\n if (purposeMapping.valueMapping[value] !== undefined) {\n logger.info(\n colors.magenta(\n `Value \"${value}\" is associated with purpose value \"${purposeMapping.valueMapping[value]}\"`,\n ),\n );\n return;\n }\n // if preference is null, this column is just for the purpose\n if (purposeMapping.preference === null) {\n const { purposeValue } = await inquirer.prompt<{\n /** purpose value */\n purposeValue: boolean;\n }>([\n {\n name: 'purposeValue',\n message: `Choose the purpose value for value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = purposeValue;\n }\n\n // if preference is not null, this column is for a specific preference\n if (purposeMapping.preference !== null) {\n const preferenceTopic = preferenceTopics.find((x) => x.slug === purposeMapping.preference);\n if (!preferenceTopic) {\n logger.error(colors.red(`Preference topic \"${purposeMapping.preference}\" not found`));\n return;\n }\n const preferenceOptions = preferenceTopic.preferenceOptionValues.map(({ slug }) => slug);\n\n if (preferenceTopic.type === PreferenceTopicType.Boolean) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n message:\n // eslint-disable-next-line max-len\n `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.Select) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === value),\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.MultiSelect) {\n const parsedValues = splitCsvToList(value);\n // need to do this serially\n await mapSeries(parsedValues, async (parsedValue) => {\n // if we already have a value, skip re-processing it again\n if (purposeMapping.valueMapping[parsedValue] !== undefined) {\n return;\n }\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${parsedValue}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === parsedValue),\n },\n ]);\n purposeMapping.valueMapping[parsedValue] = preferenceValue;\n });\n return;\n }\n\n throw new Error(`Unknown preference topic type: ${preferenceTopic.type}`);\n }\n });\n\n currentState.columnToPurposeName[col] = purposeMapping;\n });\n\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import { FileMetadataState } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, groupBy, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { inquirerConfirmBoolean } from '../helpers/index.js';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse identifiers from a CSV list of preferences\n *\n * Ensures that all rows have a valid identifier\n * and that all identifiers are unique.\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceIdentifiersFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<{\n /** The updated state */\n currentState: FileMetadataState;\n /** The updated preferences */\n preferences: Record<string, string>[];\n}> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const remainingColumnsForIdentifier = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the identifier column to work off of\n if (!currentState.identifierColumn) {\n const { identifierName } = await inquirer.prompt<{\n /** Identifier name */\n identifierName: string;\n }>([\n {\n name: 'identifierName',\n message:\n 'Choose the column that will be used as the identifier to upload consent preferences by',\n type: 'list',\n default:\n remainingColumnsForIdentifier.find((col) => col.toLowerCase().includes('email')) ||\n remainingColumnsForIdentifier[0],\n choices: remainingColumnsForIdentifier,\n },\n ]);\n currentState.identifierColumn = identifierName;\n }\n logger.info(colors.magenta(`Using identifier column \"${currentState.identifierColumn}\"`));\n\n // Validate that the identifier column is present for all rows and unique\n const identifierColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.identifierColumn!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (identifierColumnsMissing.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" is missing a value for the following rows: ${identifierColumnsMissing.join(', ')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to skip rows missing an identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to skip rows missing an identifier?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n\n // Filter out rows missing an identifier\n const previous = preferences.length;\n preferences = preferences.filter((pref) => pref[currentState.identifierColumn!]);\n logger.info(\n colors.yellow(`Skipped ${previous - preferences.length} rows missing an identifier`),\n );\n }\n logger.info(\n colors.magenta(\n `The identifier column \"${currentState.identifierColumn}\" is present for all rows`,\n ),\n );\n\n // Validate that all identifiers are unique\n const rowsByUserId = groupBy(preferences, currentState.identifierColumn);\n const duplicateIdentifiers = Object.entries(rowsByUserId).filter(([, rows]) => rows.length > 1);\n if (duplicateIdentifiers.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" has duplicate values for the following rows: ${duplicateIdentifiers\n .slice(0, 10)\n .map(([userId, rows]) => `${userId} (${rows.length})`)\n .join('\\n')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to take the most recent update\n // for each duplicate identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to automatically take the latest update?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n preferences = Object.entries(rowsByUserId)\n .map(([, rows]) => {\n const sorted = rows.sort(\n (a, b) =>\n new Date(b[currentState.timestampColum!]).getTime() -\n new Date(a[currentState.timestampColum!]).getTime(),\n );\n return sorted[0];\n })\n .filter((x) => x);\n }\n\n return { currentState, preferences };\n}\n/* eslint-enable no-param-reassign */\n","import { FileMetadataState } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\n\nexport const NONE_PREFERENCE_MAP = '[NONE]';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse timestamps from a CSV list of preferences\n *\n * When timestamp is requested, this script\n * ensures that all rows have a valid timestamp.\n *\n * Error is throw if timestamp is missing\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceTimestampsFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for timestamp\n const remainingColumnsForTimestamp = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the timestamp column to work off of\n if (!currentState.timestampColum) {\n const { timestampName } = await inquirer.prompt<{\n /** timestamp name */\n timestampName: string;\n }>([\n {\n name: 'timestampName',\n message: 'Choose the column that will be used as the timestamp of last preference update',\n type: 'list',\n default:\n remainingColumnsForTimestamp.find((col) => col.toLowerCase().includes('date')) ||\n remainingColumnsForTimestamp.find((col) => col.toLowerCase().includes('time')) ||\n remainingColumnsForTimestamp[0],\n choices: [...remainingColumnsForTimestamp, NONE_PREFERENCE_MAP],\n },\n ]);\n currentState.timestampColum = timestampName;\n }\n logger.info(colors.magenta(`Using timestamp column \"${currentState.timestampColum}\"`));\n\n // Validate that all rows have valid timestamp\n if (currentState.timestampColum !== NONE_PREFERENCE_MAP) {\n const timestampColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.timestampColum!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (timestampColumnsMissing.length > 0) {\n throw new Error(\n `The timestamp column \"${\n currentState.timestampColum\n }\" is missing a value for the following rows: ${timestampColumnsMissing.join('\\n')}`,\n );\n }\n logger.info(\n colors.magenta(\n `The timestamp column \"${currentState.timestampColum}\" is present for all row`,\n ),\n );\n }\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport {\n checkIfPendingPreferenceUpdatesAreNoOp,\n checkIfPendingPreferenceUpdatesCauseConflict,\n FileMetadataState,\n getPreferencesForIdentifiers,\n getPreferenceUpdatesFromRow,\n PreferenceState,\n type PreferenceTopic,\n} from '@transcend-io/sdk';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport type { Got } from 'got';\nimport * as t from 'io-ts';\nimport { keyBy } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { readCsv } from '../requests/index.js';\nimport { parsePreferenceAndPurposeValuesFromCsv } from './parsePreferenceAndPurposeValuesFromCsv.js';\nimport { parsePreferenceIdentifiersFromCsv } from './parsePreferenceIdentifiersFromCsv.js';\nimport { parsePreferenceTimestampsFromCsv } from './parsePreferenceTimestampsFromCsv.js';\n\n/**\n * Parse a file into the cache\n *\n *\n * @param options - Options\n * @param cache - The cache to store the parsed file in\n * @returns The cache with the parsed file\n */\nexport async function parsePreferenceManagementCsvWithCache(\n {\n file,\n sombra,\n purposeSlugs,\n preferenceTopics,\n partitionKey,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n }: {\n /** File to parse */\n file: string;\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Sombra got instance */\n sombra: Got;\n /** Partition key */\n partitionKey: string;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck: boolean;\n /** Whether to force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n cache: PersistedState<typeof PreferenceState>,\n): Promise<void> {\n // Start the timer\n const t0 = new Date().getTime();\n\n // Get the current metadata\n const fileMetadata = cache.getValue('fileMetadata');\n\n // Read in the file\n logger.info(colors.magenta(`Reading in file: \"${file}\"`));\n let preferences = readCsv(file, t.record(t.string, t.string));\n\n // start building the cache, can use previous cache as well\n let currentState: FileMetadataState = {\n columnToPurposeName: {},\n pendingSafeUpdates: {},\n pendingConflictUpdates: {},\n skippedUpdates: {},\n // Load in the last fetched time\n ...((fileMetadata[file] || {}) as Partial<FileMetadataState>),\n lastFetchedAt: new Date().toISOString(),\n };\n\n // Validate that all timestamps are present in the file\n currentState = await parsePreferenceTimestampsFromCsv(preferences, currentState);\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Validate that all identifiers are present and unique\n const result = await parsePreferenceIdentifiersFromCsv(preferences, currentState);\n currentState = result.currentState;\n preferences = result.preferences;\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Ensure all other columns are mapped to purpose and preference\n // slug values\n currentState = await parsePreferenceAndPurposeValuesFromCsv(preferences, currentState, {\n preferenceTopics,\n purposeSlugs,\n forceTriggerWorkflows,\n });\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Grab existing preference store records\n const identifiers = preferences.map((pref) => pref[currentState.identifierColumn!]);\n const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);\n if (!skipExistingRecordCheck) {\n progressBar.start(identifiers.length, 0);\n }\n const existingConsentRecords = skipExistingRecordCheck\n ? []\n : await getPreferencesForIdentifiers(sombra, {\n identifiers: identifiers.map((x) => ({ value: x })),\n partitionKey,\n logger,\n onProgress: (completed, total) => progressBar.update(completed, { total }),\n });\n progressBar.stop();\n const consentRecordByIdentifier = keyBy(existingConsentRecords, 'userId');\n\n // Clear out previous updates\n currentState.pendingConflictUpdates = {};\n currentState.pendingSafeUpdates = {};\n currentState.skippedUpdates = {};\n\n // Process each row\n preferences.forEach((pref) => {\n // Grab unique Id for the user\n const userId = pref[currentState.identifierColumn!];\n\n // determine updates for user\n const pendingUpdates = getPreferenceUpdatesFromRow({\n row: pref,\n columnToPurposeName: currentState.columnToPurposeName,\n preferenceTopics,\n purposeSlugs,\n });\n\n // Grab current state of the update\n const currentConsentRecord = consentRecordByIdentifier[userId];\n if (forceTriggerWorkflows && !currentConsentRecord) {\n throw new Error(\n `No existing consent record found for user with id: ${userId}.\n When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`,\n );\n }\n // Check if the update can be skipped\n // this is the case if a record exists, and the purpose\n // and preference values are all in sync\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesAreNoOp({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n }) &&\n !forceTriggerWorkflows\n ) {\n currentState.skippedUpdates[userId] = pref;\n return;\n }\n\n // Determine if there are any conflicts\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesCauseConflict({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n })\n ) {\n currentState.pendingConflictUpdates[userId] = {\n row: pref,\n record: currentConsentRecord,\n };\n return;\n }\n\n // Add to pending updates\n currentState.pendingSafeUpdates[userId] = pref;\n });\n\n // Read in the file\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n const t1 = new Date().getTime();\n logger.info(colors.green(`Successfully pre-processed file: \"${file}\" in ${(t1 - t0) / 1000}s`));\n}\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport { PreferenceUpdateItem } from '@transcend-io/privacy-types';\nimport {\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllPurposes,\n fetchAllPreferenceTopics,\n getPreferenceUpdatesFromRow,\n PreferenceState,\n} from '@transcend-io/sdk';\nimport { apply } from '@transcend-io/type-utils';\nimport { map } from '@transcend-io/utils';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport { chunk } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { parseAttributesFromString } from '../requests/index.js';\nimport { parsePreferenceManagementCsvWithCache } from './parsePreferenceManagementCsv.js';\nimport { NONE_PREFERENCE_MAP } from './parsePreferenceTimestampsFromCsv.js';\n\n/**\n * Upload a set of consent preferences\n *\n * @param options - Options\n */\nexport async function uploadPreferenceManagementPreferencesInteractive({\n auth,\n sombraAuth,\n receiptFilepath,\n file,\n partition,\n isSilent = true,\n dryRun = false,\n skipWorkflowTriggers = false,\n skipConflictUpdates = false,\n skipExistingRecordCheck = false,\n attributes = [],\n transcendUrl,\n forceTriggerWorkflows = false,\n}: {\n /** The Transcend API key */\n auth: string;\n /** Sombra API key authentication */\n sombraAuth?: string;\n /** Partition key */\n partition: string;\n /** File where to store receipt and continue from where left off */\n receiptFilepath: string;\n /** The file to process */\n file: string;\n /** API URL for Transcend backend */\n transcendUrl: string;\n /** Whether to do a dry run */\n dryRun?: boolean;\n /** Whether to upload as isSilent */\n isSilent?: boolean;\n /** Attributes string pre-parse. In format Key:Value */\n attributes?: string[];\n /** Skip workflow triggers */\n skipWorkflowTriggers?: boolean;\n /**\n * When true, only update preferences that do not conflict with existing\n * preferences. When false, update all preferences in CSV based on timestamp.\n */\n skipConflictUpdates?: boolean;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck?: boolean;\n /** Whether to force trigger workflows */\n forceTriggerWorkflows?: boolean;\n}): Promise<void> {\n // Parse out the extra attributes to apply to all requests uploaded\n const parsedAttributes = parseAttributesFromString(attributes);\n\n // Create a new state file to store the requests from this run\n const preferenceState = new PersistedState(receiptFilepath, PreferenceState, {\n fileMetadata: {},\n failingUpdates: {},\n pendingUpdates: {},\n });\n const failingRequests = preferenceState.getValue('failingUpdates');\n const pendingRequests = preferenceState.getValue('pendingUpdates');\n let fileMetadata = preferenceState.getValue('fileMetadata');\n\n logger.info(\n colors.magenta(\n 'Restored cache, there are: \\n' +\n `${Object.values(failingRequests).length} failing requests to be retried\\n` +\n `${Object.values(pendingRequests).length} pending requests to be processed\\n` +\n `The following files are stored in cache and will be used:\\n${Object.keys(fileMetadata)\n .map((x) => x)\n .join('\\n')}\\n` +\n `The following file will be processed: ${file}\\n`,\n ),\n );\n\n // Create GraphQL client to connect to Transcend backend\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const [sombra, purposes, preferenceTopics] = await Promise.all([\n // Create sombra instance to communicate with\n createSombraGotInstance(transcendUrl, auth, {\n logger,\n sombraApiKey: sombraAuth,\n sombraUrl: process.env.SOMBRA_URL,\n }),\n // get all purposes and topics\n fetchAllPurposes(client, { logger }),\n fetchAllPreferenceTopics(client, { logger }),\n ]);\n\n // Process the file\n await parsePreferenceManagementCsvWithCache(\n {\n file,\n purposeSlugs: purposes.map((x) => x.trackingType),\n preferenceTopics,\n sombra,\n partitionKey: partition,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n },\n preferenceState,\n );\n\n // Construct the pending updates\n const pendingUpdates: Record<string, PreferenceUpdateItem> = {};\n fileMetadata = preferenceState.getValue('fileMetadata');\n const metadata = fileMetadata[file];\n\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.pendingSafeUpdates).length} safe updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.pendingConflictUpdates).length} conflict updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.skippedUpdates).length} skipped updates in ${file}`,\n ),\n );\n\n // Update either safe updates only or safe + conflict\n Object.entries({\n ...metadata.pendingSafeUpdates,\n ...(skipConflictUpdates ? {} : apply(metadata.pendingConflictUpdates, ({ row }) => row)),\n }).forEach(([userId, update]) => {\n // Determine timestamp\n const timestamp =\n metadata.timestampColum === NONE_PREFERENCE_MAP\n ? new Date()\n : new Date(update[metadata.timestampColum!]);\n\n // Determine updates\n const updates = getPreferenceUpdatesFromRow({\n row: update,\n columnToPurposeName: metadata.columnToPurposeName,\n preferenceTopics,\n purposeSlugs: purposes.map((x) => x.trackingType),\n });\n pendingUpdates[userId] = {\n userId,\n partition,\n timestamp: timestamp.toISOString(),\n purposes: Object.entries(updates).map(([purpose, value]) => ({\n ...value,\n purpose,\n workflowSettings: {\n attributes: parsedAttributes,\n isSilent,\n skipWorkflowTrigger: skipWorkflowTriggers,\n ...(forceTriggerWorkflows ? { forceTriggerWorkflow: forceTriggerWorkflows } : {}),\n },\n })),\n };\n });\n await preferenceState.setValue(pendingUpdates, 'pendingUpdates');\n await preferenceState.setValue({}, 'failingUpdates');\n\n // Exist early if dry run\n if (dryRun) {\n logger.info(\n colors.green(\n `Dry run complete, exiting. ${\n Object.values(pendingUpdates).length\n } pending updates. Check file: ${receiptFilepath}`,\n ),\n );\n return;\n }\n\n logger.info(\n colors.magenta(\n `Uploading ${Object.values(pendingUpdates).length} preferences to partition: ${partition}`,\n ),\n );\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);\n\n // Build a GraphQL client\n let total = 0;\n const updatesToRun = Object.entries(pendingUpdates);\n const chunkedUpdates = chunk(updatesToRun, skipWorkflowTriggers ? 100 : 10);\n progressBar.start(updatesToRun.length, 0);\n await map(\n chunkedUpdates,\n async (currentChunk) => {\n // Make the request\n try {\n await sombra\n .put('v1/preferences', {\n json: {\n records: currentChunk.map(([, update]) => update),\n skipWorkflowTriggers,\n },\n })\n .json();\n } catch (err) {\n try {\n const parsed = JSON.parse(err?.response?.body || '{}');\n if (parsed.error) {\n logger.error(colors.red(`Error: ${parsed.error}`));\n }\n } catch {\n // continue\n }\n logger.error(\n colors.red(\n `Failed to upload ${currentChunk.length} user preferences to partition ${partition}: ${\n err?.response?.body || err?.message\n }`,\n ),\n );\n const failingUpdates = preferenceState.getValue('failingUpdates');\n currentChunk.forEach(([userId, update]) => {\n failingUpdates[userId] = {\n uploadedAt: new Date().toISOString(),\n update,\n error: err?.response?.body || err?.message || 'Unknown error',\n };\n });\n await preferenceState.setValue(failingUpdates, 'failingUpdates');\n }\n\n total += currentChunk.length;\n progressBar.update(total);\n },\n {\n concurrency: 40,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n logger.info(\n colors.green(\n `Successfully uploaded ${\n updatesToRun.length\n } user preferences to partition ${partition} in \"${totalTime / 1000}\" seconds!`,\n ),\n );\n}\n","import path from 'node:path';\n\nimport { map, splitCsvToList } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { uploadPreferenceManagementPreferencesInteractive } from '../../../lib/preference-management/index.js';\n\nexport interface UploadPreferencesCommandFlags {\n auth: string;\n partition: string;\n sombraAuth?: string;\n transcendUrl: string;\n file?: string;\n directory?: string;\n dryRun: boolean;\n skipExistingRecordCheck: boolean;\n receiptFileDir: string;\n skipWorkflowTriggers: boolean;\n forceTriggerWorkflows: boolean;\n skipConflictUpdates: boolean;\n isSilent: boolean;\n attributes: string;\n receiptFilepath: string;\n concurrency: number;\n}\n\nexport async function uploadPreferences(\n this: LocalContext,\n {\n auth,\n partition,\n sombraAuth,\n transcendUrl,\n file = '',\n directory,\n dryRun,\n skipExistingRecordCheck,\n receiptFileDir,\n skipWorkflowTriggers,\n forceTriggerWorkflows,\n skipConflictUpdates,\n isSilent,\n attributes,\n concurrency,\n }: UploadPreferencesCommandFlags,\n): Promise<void> {\n if (!!directory && !!file) {\n this.logger.error(\n colors.red('Cannot provide both a directory and a file. Please provide only one.'),\n );\n this.process.exit(1);\n }\n\n if (!file && !directory) {\n this.logger.error(\n colors.red(\n 'A file or directory must be provided. Please provide one using --file=./preferences.csv or --directory=./preferences',\n ),\n );\n this.process.exit(1);\n }\n\n doneInputValidation(this.process);\n\n const files: string[] = [];\n\n if (directory) {\n try {\n const filesInDirectory = this.fs.readdirSync(directory);\n const csvFiles = filesInDirectory.filter((file) => file.endsWith('.csv'));\n\n if (csvFiles.length === 0) {\n this.logger.error(colors.red(`No CSV files found in directory: ${directory}`));\n this.process.exit(1);\n }\n\n // Add full paths for each CSV file\n files.push(...csvFiles.map((file) => path.join(directory, file)));\n } catch (err) {\n this.logger.error(colors.red(`Failed to read directory: ${directory}`));\n this.logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n } else {\n try {\n // Verify file exists and is a CSV\n if (!file.endsWith('.csv')) {\n this.logger.error(colors.red('File must be a CSV file'));\n this.process.exit(1);\n }\n files.push(file);\n } catch (err) {\n this.logger.error(colors.red(`Failed to access file: ${file}`));\n this.logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n }\n\n this.logger.info(\n colors.green(\n `Processing ${files.length} consent preferences files for partition: ${partition}`,\n ),\n );\n this.logger.debug(`Files to process: ${files.join(', ')}`);\n\n if (skipExistingRecordCheck) {\n this.logger.info(colors.bgYellow(`Skipping existing record check: ${skipExistingRecordCheck}`));\n }\n\n await map(\n files,\n async (filePath) => {\n const fileName = path.basename(filePath).replace('.csv', '');\n await uploadPreferenceManagementPreferencesInteractive({\n receiptFilepath: path.join(receiptFileDir, `${fileName}-receipts.json`),\n auth,\n sombraAuth,\n file: filePath,\n partition,\n transcendUrl,\n skipConflictUpdates,\n skipWorkflowTriggers,\n skipExistingRecordCheck,\n isSilent,\n dryRun,\n attributes: splitCsvToList(attributes),\n forceTriggerWorkflows,\n });\n },\n { concurr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":[],"sources":["../src/lib/preference-management/parsePreferenceAndPurposeValuesFromCsv.ts","../src/lib/preference-management/parsePreferenceIdentifiersFromCsv.ts","../src/lib/preference-management/parsePreferenceTimestampsFromCsv.ts","../src/lib/preference-management/parsePreferenceManagementCsv.ts","../src/lib/preference-management/uploadPreferenceManagementPreferencesInteractive.ts","../src/commands/consent/upload-preferences/impl.ts"],"sourcesContent":["import { PreferenceTopicType } from '@transcend-io/privacy-types';\nimport { FileMetadataState, type PreferenceTopic } from '@transcend-io/sdk';\nimport { mapSeries, splitCsvToList } from '@transcend-io/utils';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse out the purpose.enabled and preference values from a CSV file\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @param options - Options\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceAndPurposeValuesFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n {\n purposeSlugs,\n preferenceTopics,\n forceTriggerWorkflows,\n }: {\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const otherColumns = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...(currentState.timestampColum ? [currentState.timestampColum] : []),\n ]);\n if (otherColumns.length === 0) {\n if (forceTriggerWorkflows) {\n return currentState;\n }\n throw new Error('No other columns to process');\n }\n\n // The purpose and preferences to map to\n const purposeNames = [\n ...purposeSlugs,\n ...preferenceTopics.map((x) => `${x.purpose.trackingType}->${x.slug}`),\n ];\n\n // Ensure all columns are accounted for\n await mapSeries(otherColumns, async (col) => {\n // Determine the unique values to map in this column\n const uniqueValues = uniq(preferences.map((x) => x[col]));\n\n // Map the column to a purpose\n let purposeMapping = currentState.columnToPurposeName[col];\n if (purposeMapping) {\n logger.info(\n colors.magenta(`Column \"${col}\" is associated with purpose \"${purposeMapping.purpose}\"`),\n );\n } else {\n const { purposeName } = await inquirer.prompt<{\n /** purpose name */\n purposeName: string;\n }>([\n {\n name: 'purposeName',\n message: `Choose the purpose that column ${col} is associated with`,\n type: 'list',\n default: purposeNames.find((x) => x.startsWith(purposeSlugs[0])),\n choices: purposeNames,\n },\n ]);\n const [purposeSlug, preferenceSlug] = purposeName.split('->');\n purposeMapping = {\n purpose: purposeSlug,\n preference: preferenceSlug || null,\n valueMapping: {},\n };\n }\n\n // map each value to the purpose value\n await mapSeries(uniqueValues, async (value) => {\n if (purposeMapping.valueMapping[value] !== undefined) {\n logger.info(\n colors.magenta(\n `Value \"${value}\" is associated with purpose value \"${purposeMapping.valueMapping[value]}\"`,\n ),\n );\n return;\n }\n // if preference is null, this column is just for the purpose\n if (purposeMapping.preference === null) {\n const { purposeValue } = await inquirer.prompt<{\n /** purpose value */\n purposeValue: boolean;\n }>([\n {\n name: 'purposeValue',\n message: `Choose the purpose value for value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = purposeValue;\n }\n\n // if preference is not null, this column is for a specific preference\n if (purposeMapping.preference !== null) {\n const preferenceTopic = preferenceTopics.find((x) => x.slug === purposeMapping.preference);\n if (!preferenceTopic) {\n logger.error(colors.red(`Preference topic \"${purposeMapping.preference}\" not found`));\n return;\n }\n const preferenceOptions = preferenceTopic.preferenceOptionValues.map(({ slug }) => slug);\n\n if (preferenceTopic.type === PreferenceTopicType.Boolean) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n message:\n // eslint-disable-next-line max-len\n `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.Select) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === value),\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.MultiSelect) {\n const parsedValues = splitCsvToList(value);\n // need to do this serially\n await mapSeries(parsedValues, async (parsedValue) => {\n // if we already have a value, skip re-processing it again\n if (purposeMapping.valueMapping[parsedValue] !== undefined) {\n return;\n }\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${parsedValue}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === parsedValue),\n },\n ]);\n purposeMapping.valueMapping[parsedValue] = preferenceValue;\n });\n return;\n }\n\n throw new Error(`Unknown preference topic type: ${preferenceTopic.type}`);\n }\n });\n\n currentState.columnToPurposeName[col] = purposeMapping;\n });\n\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import { FileMetadataState } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, groupBy, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { inquirerConfirmBoolean } from '../helpers/index.js';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse identifiers from a CSV list of preferences\n *\n * Ensures that all rows have a valid identifier\n * and that all identifiers are unique.\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceIdentifiersFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<{\n /** The updated state */\n currentState: FileMetadataState;\n /** The updated preferences */\n preferences: Record<string, string>[];\n}> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const remainingColumnsForIdentifier = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the identifier column to work off of\n if (!currentState.identifierColumn) {\n const { identifierName } = await inquirer.prompt<{\n /** Identifier name */\n identifierName: string;\n }>([\n {\n name: 'identifierName',\n message:\n 'Choose the column that will be used as the identifier to upload consent preferences by',\n type: 'list',\n default:\n remainingColumnsForIdentifier.find((col) => col.toLowerCase().includes('email')) ||\n remainingColumnsForIdentifier[0],\n choices: remainingColumnsForIdentifier,\n },\n ]);\n currentState.identifierColumn = identifierName;\n }\n logger.info(colors.magenta(`Using identifier column \"${currentState.identifierColumn}\"`));\n\n // Validate that the identifier column is present for all rows and unique\n const identifierColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.identifierColumn!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (identifierColumnsMissing.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" is missing a value for the following rows: ${identifierColumnsMissing.join(', ')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to skip rows missing an identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to skip rows missing an identifier?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n\n // Filter out rows missing an identifier\n const previous = preferences.length;\n preferences = preferences.filter((pref) => pref[currentState.identifierColumn!]);\n logger.info(\n colors.yellow(`Skipped ${previous - preferences.length} rows missing an identifier`),\n );\n }\n logger.info(\n colors.magenta(\n `The identifier column \"${currentState.identifierColumn}\" is present for all rows`,\n ),\n );\n\n // Validate that all identifiers are unique\n const rowsByUserId = groupBy(preferences, currentState.identifierColumn);\n const duplicateIdentifiers = Object.entries(rowsByUserId).filter(([, rows]) => rows.length > 1);\n if (duplicateIdentifiers.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" has duplicate values for the following rows: ${duplicateIdentifiers\n .slice(0, 10)\n .map(([userId, rows]) => `${userId} (${rows.length})`)\n .join('\\n')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to take the most recent update\n // for each duplicate identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to automatically take the latest update?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n preferences = Object.entries(rowsByUserId)\n .map(([, rows]) => {\n const sorted = rows.sort(\n (a, b) =>\n new Date(b[currentState.timestampColum!]).getTime() -\n new Date(a[currentState.timestampColum!]).getTime(),\n );\n return sorted[0];\n })\n .filter((x) => x);\n }\n\n return { currentState, preferences };\n}\n/* eslint-enable no-param-reassign */\n","import { FileMetadataState } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { uniq, difference } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\n\nexport const NONE_PREFERENCE_MAP = '[NONE]';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse timestamps from a CSV list of preferences\n *\n * When timestamp is requested, this script\n * ensures that all rows have a valid timestamp.\n *\n * Error is throw if timestamp is missing\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceTimestampsFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for timestamp\n const remainingColumnsForTimestamp = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the timestamp column to work off of\n if (!currentState.timestampColum) {\n const { timestampName } = await inquirer.prompt<{\n /** timestamp name */\n timestampName: string;\n }>([\n {\n name: 'timestampName',\n message: 'Choose the column that will be used as the timestamp of last preference update',\n type: 'list',\n default:\n remainingColumnsForTimestamp.find((col) => col.toLowerCase().includes('date')) ||\n remainingColumnsForTimestamp.find((col) => col.toLowerCase().includes('time')) ||\n remainingColumnsForTimestamp[0],\n choices: [...remainingColumnsForTimestamp, NONE_PREFERENCE_MAP],\n },\n ]);\n currentState.timestampColum = timestampName;\n }\n logger.info(colors.magenta(`Using timestamp column \"${currentState.timestampColum}\"`));\n\n // Validate that all rows have valid timestamp\n if (currentState.timestampColum !== NONE_PREFERENCE_MAP) {\n const timestampColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.timestampColum!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (timestampColumnsMissing.length > 0) {\n throw new Error(\n `The timestamp column \"${\n currentState.timestampColum\n }\" is missing a value for the following rows: ${timestampColumnsMissing.join('\\n')}`,\n );\n }\n logger.info(\n colors.magenta(\n `The timestamp column \"${currentState.timestampColum}\" is present for all row`,\n ),\n );\n }\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport {\n checkIfPendingPreferenceUpdatesAreNoOp,\n checkIfPendingPreferenceUpdatesCauseConflict,\n FileMetadataState,\n getPreferencesForIdentifiers,\n getPreferenceUpdatesFromRow,\n PreferenceState,\n type PreferenceTopic,\n} from '@transcend-io/sdk';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport type { Got } from 'got';\nimport * as t from 'io-ts';\nimport { keyBy } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { readCsv } from '../requests/index.js';\nimport { parsePreferenceAndPurposeValuesFromCsv } from './parsePreferenceAndPurposeValuesFromCsv.js';\nimport { parsePreferenceIdentifiersFromCsv } from './parsePreferenceIdentifiersFromCsv.js';\nimport { parsePreferenceTimestampsFromCsv } from './parsePreferenceTimestampsFromCsv.js';\n\n/**\n * Parse a file into the cache\n *\n *\n * @param options - Options\n * @param cache - The cache to store the parsed file in\n * @returns The cache with the parsed file\n */\nexport async function parsePreferenceManagementCsvWithCache(\n {\n file,\n sombra,\n purposeSlugs,\n preferenceTopics,\n partitionKey,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n }: {\n /** File to parse */\n file: string;\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Sombra got instance */\n sombra: Got;\n /** Partition key */\n partitionKey: string;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck: boolean;\n /** Whether to force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n cache: PersistedState<typeof PreferenceState>,\n): Promise<void> {\n // Start the timer\n const t0 = new Date().getTime();\n\n // Get the current metadata\n const fileMetadata = cache.getValue('fileMetadata');\n\n // Read in the file\n logger.info(colors.magenta(`Reading in file: \"${file}\"`));\n let preferences = readCsv(file, t.record(t.string, t.string));\n\n // start building the cache, can use previous cache as well\n let currentState: FileMetadataState = {\n columnToPurposeName: {},\n pendingSafeUpdates: {},\n pendingConflictUpdates: {},\n skippedUpdates: {},\n // Load in the last fetched time\n ...((fileMetadata[file] || {}) as Partial<FileMetadataState>),\n lastFetchedAt: new Date().toISOString(),\n };\n\n // Validate that all timestamps are present in the file\n currentState = await parsePreferenceTimestampsFromCsv(preferences, currentState);\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Validate that all identifiers are present and unique\n const result = await parsePreferenceIdentifiersFromCsv(preferences, currentState);\n currentState = result.currentState;\n preferences = result.preferences;\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Ensure all other columns are mapped to purpose and preference\n // slug values\n currentState = await parsePreferenceAndPurposeValuesFromCsv(preferences, currentState, {\n preferenceTopics,\n purposeSlugs,\n forceTriggerWorkflows,\n });\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Grab existing preference store records\n const identifiers = preferences.map((pref) => pref[currentState.identifierColumn!]);\n const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);\n if (!skipExistingRecordCheck) {\n progressBar.start(identifiers.length, 0);\n }\n const existingConsentRecords = skipExistingRecordCheck\n ? []\n : await getPreferencesForIdentifiers(sombra, {\n identifiers: identifiers.map((x) => ({ value: x })),\n partitionKey,\n logger,\n onProgress: (completed, total) => progressBar.update(completed, { total }),\n });\n progressBar.stop();\n const consentRecordByIdentifier = keyBy(existingConsentRecords, 'userId');\n\n // Clear out previous updates\n currentState.pendingConflictUpdates = {};\n currentState.pendingSafeUpdates = {};\n currentState.skippedUpdates = {};\n\n // Process each row\n preferences.forEach((pref) => {\n // Grab unique Id for the user\n const userId = pref[currentState.identifierColumn!];\n\n // determine updates for user\n const pendingUpdates = getPreferenceUpdatesFromRow({\n row: pref,\n columnToPurposeName: currentState.columnToPurposeName,\n preferenceTopics,\n purposeSlugs,\n });\n\n // Grab current state of the update\n const currentConsentRecord = consentRecordByIdentifier[userId];\n if (forceTriggerWorkflows && !currentConsentRecord) {\n throw new Error(\n `No existing consent record found for user with id: ${userId}.\n When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`,\n );\n }\n // Check if the update can be skipped\n // this is the case if a record exists, and the purpose\n // and preference values are all in sync\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesAreNoOp({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n }) &&\n !forceTriggerWorkflows\n ) {\n currentState.skippedUpdates[userId] = pref;\n return;\n }\n\n // Determine if there are any conflicts\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesCauseConflict({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n })\n ) {\n currentState.pendingConflictUpdates[userId] = {\n row: pref,\n record: currentConsentRecord,\n };\n return;\n }\n\n // Add to pending updates\n currentState.pendingSafeUpdates[userId] = pref;\n });\n\n // Read in the file\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n const t1 = new Date().getTime();\n logger.info(colors.green(`Successfully pre-processed file: \"${file}\" in ${(t1 - t0) / 1000}s`));\n}\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport { PreferenceUpdateItem } from '@transcend-io/privacy-types';\nimport {\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllPurposes,\n fetchAllPreferenceTopics,\n getPreferenceUpdatesFromRow,\n PreferenceState,\n} from '@transcend-io/sdk';\nimport { apply } from '@transcend-io/type-utils';\nimport { map } from '@transcend-io/utils';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport { chunk } from 'lodash-es';\n\nimport { logger } from '../../logger.js';\nimport { parseAttributesFromString } from '../requests/index.js';\nimport { parsePreferenceManagementCsvWithCache } from './parsePreferenceManagementCsv.js';\nimport { NONE_PREFERENCE_MAP } from './parsePreferenceTimestampsFromCsv.js';\n\n/**\n * Upload a set of consent preferences\n *\n * @param options - Options\n */\nexport async function uploadPreferenceManagementPreferencesInteractive({\n auth,\n sombraAuth,\n receiptFilepath,\n file,\n partition,\n isSilent = true,\n dryRun = false,\n skipWorkflowTriggers = false,\n skipConflictUpdates = false,\n skipExistingRecordCheck = false,\n attributes = [],\n transcendUrl,\n forceTriggerWorkflows = false,\n}: {\n /** The Transcend API key */\n auth: string;\n /** Sombra API key authentication */\n sombraAuth?: string;\n /** Partition key */\n partition: string;\n /** File where to store receipt and continue from where left off */\n receiptFilepath: string;\n /** The file to process */\n file: string;\n /** API URL for Transcend backend */\n transcendUrl: string;\n /** Whether to do a dry run */\n dryRun?: boolean;\n /** Whether to upload as isSilent */\n isSilent?: boolean;\n /** Attributes string pre-parse. In format Key:Value */\n attributes?: string[];\n /** Skip workflow triggers */\n skipWorkflowTriggers?: boolean;\n /**\n * When true, only update preferences that do not conflict with existing\n * preferences. When false, update all preferences in CSV based on timestamp.\n */\n skipConflictUpdates?: boolean;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck?: boolean;\n /** Whether to force trigger workflows */\n forceTriggerWorkflows?: boolean;\n}): Promise<void> {\n // Parse out the extra attributes to apply to all requests uploaded\n const parsedAttributes = parseAttributesFromString(attributes);\n\n // Create a new state file to store the requests from this run\n const preferenceState = new PersistedState(receiptFilepath, PreferenceState, {\n fileMetadata: {},\n failingUpdates: {},\n pendingUpdates: {},\n });\n const failingRequests = preferenceState.getValue('failingUpdates');\n const pendingRequests = preferenceState.getValue('pendingUpdates');\n let fileMetadata = preferenceState.getValue('fileMetadata');\n\n logger.info(\n colors.magenta(\n 'Restored cache, there are: \\n' +\n `${Object.values(failingRequests).length} failing requests to be retried\\n` +\n `${Object.values(pendingRequests).length} pending requests to be processed\\n` +\n `The following files are stored in cache and will be used:\\n${Object.keys(fileMetadata)\n .map((x) => x)\n .join('\\n')}\\n` +\n `The following file will be processed: ${file}\\n`,\n ),\n );\n\n // Create GraphQL client to connect to Transcend backend\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const [sombra, purposes, preferenceTopics] = await Promise.all([\n // Create sombra instance to communicate with\n createSombraGotInstance(transcendUrl, auth, {\n logger,\n sombraApiKey: sombraAuth,\n sombraUrl: process.env.SOMBRA_URL,\n }),\n // get all purposes and topics\n fetchAllPurposes(client, { logger }),\n fetchAllPreferenceTopics(client, { logger }),\n ]);\n\n // Process the file\n await parsePreferenceManagementCsvWithCache(\n {\n file,\n purposeSlugs: purposes.map((x) => x.trackingType),\n preferenceTopics,\n sombra,\n partitionKey: partition,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n },\n preferenceState,\n );\n\n // Construct the pending updates\n const pendingUpdates: Record<string, PreferenceUpdateItem> = {};\n fileMetadata = preferenceState.getValue('fileMetadata');\n const metadata = fileMetadata[file];\n\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.pendingSafeUpdates).length} safe updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.pendingConflictUpdates).length} conflict updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${Object.entries(metadata.skippedUpdates).length} skipped updates in ${file}`,\n ),\n );\n\n // Update either safe updates only or safe + conflict\n Object.entries({\n ...metadata.pendingSafeUpdates,\n ...(skipConflictUpdates ? {} : apply(metadata.pendingConflictUpdates, ({ row }) => row)),\n }).forEach(([userId, update]) => {\n // Determine timestamp\n const timestamp =\n metadata.timestampColum === NONE_PREFERENCE_MAP\n ? new Date()\n : new Date(update[metadata.timestampColum!]);\n\n // Determine updates\n const updates = getPreferenceUpdatesFromRow({\n row: update,\n columnToPurposeName: metadata.columnToPurposeName,\n preferenceTopics,\n purposeSlugs: purposes.map((x) => x.trackingType),\n });\n pendingUpdates[userId] = {\n userId,\n partition,\n timestamp: timestamp.toISOString(),\n purposes: Object.entries(updates).map(([purpose, value]) => ({\n ...value,\n purpose,\n workflowSettings: {\n attributes: parsedAttributes,\n isSilent,\n skipWorkflowTrigger: skipWorkflowTriggers,\n ...(forceTriggerWorkflows ? { forceTriggerWorkflow: forceTriggerWorkflows } : {}),\n },\n })),\n };\n });\n await preferenceState.setValue(pendingUpdates, 'pendingUpdates');\n await preferenceState.setValue({}, 'failingUpdates');\n\n // Exist early if dry run\n if (dryRun) {\n logger.info(\n colors.green(\n `Dry run complete, exiting. ${\n Object.values(pendingUpdates).length\n } pending updates. Check file: ${receiptFilepath}`,\n ),\n );\n return;\n }\n\n logger.info(\n colors.magenta(\n `Uploading ${Object.values(pendingUpdates).length} preferences to partition: ${partition}`,\n ),\n );\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);\n\n // Build a GraphQL client\n let total = 0;\n const updatesToRun = Object.entries(pendingUpdates);\n const chunkedUpdates = chunk(updatesToRun, skipWorkflowTriggers ? 100 : 10);\n progressBar.start(updatesToRun.length, 0);\n await map(\n chunkedUpdates,\n async (currentChunk) => {\n // Make the request\n try {\n await sombra\n .put('v1/preferences', {\n json: {\n records: currentChunk.map(([, update]) => update),\n skipWorkflowTriggers,\n },\n })\n .json();\n } catch (err) {\n try {\n const parsed = JSON.parse(err?.response?.body || '{}');\n if (parsed.error) {\n logger.error(colors.red(`Error: ${parsed.error}`));\n }\n } catch {\n // continue\n }\n logger.error(\n colors.red(\n `Failed to upload ${currentChunk.length} user preferences to partition ${partition}: ${\n err?.response?.body || err?.message\n }`,\n ),\n );\n const failingUpdates = preferenceState.getValue('failingUpdates');\n currentChunk.forEach(([userId, update]) => {\n failingUpdates[userId] = {\n uploadedAt: new Date().toISOString(),\n update,\n error: err?.response?.body || err?.message || 'Unknown error',\n };\n });\n await preferenceState.setValue(failingUpdates, 'failingUpdates');\n }\n\n total += currentChunk.length;\n progressBar.update(total);\n },\n {\n concurrency: 40,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n logger.info(\n colors.green(\n `Successfully uploaded ${\n updatesToRun.length\n } user preferences to partition ${partition} in \"${totalTime / 1000}\" seconds!`,\n ),\n );\n}\n","import path from 'node:path';\n\nimport { map, splitCsvToList } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { uploadPreferenceManagementPreferencesInteractive } from '../../../lib/preference-management/index.js';\n\nexport interface UploadPreferencesCommandFlags {\n auth: string;\n partition: string;\n sombraAuth?: string;\n transcendUrl: string;\n file?: string;\n directory?: string;\n dryRun: boolean;\n skipExistingRecordCheck: boolean;\n receiptFileDir: string;\n skipWorkflowTriggers: boolean;\n forceTriggerWorkflows: boolean;\n skipConflictUpdates: boolean;\n isSilent: boolean;\n attributes: string;\n receiptFilepath: string;\n concurrency: number;\n}\n\nexport async function uploadPreferences(\n this: LocalContext,\n {\n auth,\n partition,\n sombraAuth,\n transcendUrl,\n file = '',\n directory,\n dryRun,\n skipExistingRecordCheck,\n receiptFileDir,\n skipWorkflowTriggers,\n forceTriggerWorkflows,\n skipConflictUpdates,\n isSilent,\n attributes,\n concurrency,\n }: UploadPreferencesCommandFlags,\n): Promise<void> {\n if (!!directory && !!file) {\n this.logger.error(\n colors.red('Cannot provide both a directory and a file. Please provide only one.'),\n );\n this.process.exit(1);\n }\n\n if (!file && !directory) {\n this.logger.error(\n colors.red(\n 'A file or directory must be provided. Please provide one using --file=./preferences.csv or --directory=./preferences',\n ),\n );\n this.process.exit(1);\n }\n\n doneInputValidation(this.process);\n\n const files: string[] = [];\n\n if (directory) {\n try {\n const filesInDirectory = this.fs.readdirSync(directory);\n const csvFiles = filesInDirectory.filter((file) => file.endsWith('.csv'));\n\n if (csvFiles.length === 0) {\n this.logger.error(colors.red(`No CSV files found in directory: ${directory}`));\n this.process.exit(1);\n }\n\n // Add full paths for each CSV file\n files.push(...csvFiles.map((file) => path.join(directory, file)));\n } catch (err) {\n this.logger.error(colors.red(`Failed to read directory: ${directory}`));\n this.logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n } else {\n try {\n // Verify file exists and is a CSV\n if (!file.endsWith('.csv')) {\n this.logger.error(colors.red('File must be a CSV file'));\n this.process.exit(1);\n }\n files.push(file);\n } catch (err) {\n this.logger.error(colors.red(`Failed to access file: ${file}`));\n this.logger.error(colors.red((err as Error).message));\n this.process.exit(1);\n }\n }\n\n this.logger.info(\n colors.green(\n `Processing ${files.length} consent preferences files for partition: ${partition}`,\n ),\n );\n this.logger.debug(`Files to process: ${files.join(', ')}`);\n\n if (skipExistingRecordCheck) {\n this.logger.info(colors.bgYellow(`Skipping existing record check: ${skipExistingRecordCheck}`));\n }\n\n await map(\n files,\n async (filePath) => {\n const fileName = path.basename(filePath).replace('.csv', '');\n await uploadPreferenceManagementPreferencesInteractive({\n receiptFilepath: path.join(receiptFileDir, `${fileName}-receipts.json`),\n auth,\n sombraAuth,\n file: filePath,\n partition,\n transcendUrl,\n skipConflictUpdates,\n skipWorkflowTriggers,\n skipExistingRecordCheck,\n isSilent,\n dryRun,\n attributes: splitCsvToList(attributes),\n forceTriggerWorkflows,\n });\n },\n { concurrency },\n );\n}\n"],"mappings":"ugCAmBA,eAAsB,EACpB,EACA,EACA,CACE,eACA,mBACA,yBAS0B,CAK5B,IAAM,EAAe,EAHD,EAAK,EAAY,IAAK,GAAM,OAAO,KAAK,EAAE,CAAC,CAAC,MAAM,CAG3B,CAAE,CAC3C,GAAI,EAAa,iBAAmB,CAAC,EAAa,iBAAiB,CAAG,EAAE,CACxE,GAAI,EAAa,eAAiB,CAAC,EAAa,eAAe,CAAG,EAAE,CACrE,CAAC,CACF,GAAI,EAAa,SAAW,EAAG,CAC7B,GAAI,EACF,OAAO,EAET,MAAU,MAAM,8BAA8B,CAIhD,IAAM,EAAe,CACnB,GAAG,EACH,GAAG,EAAiB,IAAK,GAAM,GAAG,EAAE,QAAQ,aAAa,IAAI,EAAE,OAAO,CACvE,CA0ID,OAvIA,MAAM,EAAU,EAAc,KAAO,IAAQ,CAE3C,IAAM,EAAe,EAAK,EAAY,IAAK,GAAM,EAAE,GAAK,CAAC,CAGrD,EAAiB,EAAa,oBAAoB,GACtD,GAAI,EACF,EAAO,KACL,EAAO,QAAQ,WAAW,EAAI,gCAAgC,EAAe,QAAQ,GAAG,CACzF,KACI,CACL,GAAM,CAAE,eAAgB,MAAM,EAAS,OAGpC,CACD,CACE,KAAM,cACN,QAAS,kCAAkC,EAAI,qBAC/C,KAAM,OACN,QAAS,EAAa,KAAM,GAAM,EAAE,WAAW,EAAa,GAAG,CAAC,CAChE,QAAS,EACV,CACF,CAAC,CACI,CAAC,EAAa,GAAkB,EAAY,MAAM,KAAK,CAC7D,EAAiB,CACf,QAAS,EACT,WA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AAG,CAC5D,MAAM,EAAiD,CACrD,gBAAiB,EAAK,KAAK,EAAgB,GAAG,EAAS,gBAAgB,CACvE,OACA,aACA,KAAM,EACN,YACA,eACA,sBACA,uBACA,0BACA,WACA,SACA,WAAY,EAAe,EAAW,CACtC,wBACD,CAAC,EAEJ,CAAE,cAAa,CAChB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as e,t}from"./project-plan-output-BHHlkLxe.mjs";import{n}from"./paths-J5KScOaQ.mjs";import{i as r,n as i,o as a,r as o,t as s}from"./scaffold-templates-CUL82Zf8.mjs";import{t as c}from"./project-discovery-CWRjlFnC.mjs";import{t as l}from"./done-input-validation-LiTaCEzF.mjs";import{t as u}from"./missing-manifest-D8y1VL4p.mjs";import{n as d,t as f}from"./project-discovery-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{r as e,t}from"./project-plan-output-BHHlkLxe.mjs";import{n}from"./paths-J5KScOaQ.mjs";import{i as r,n as i,o as a,r as o,t as s}from"./scaffold-templates-CUL82Zf8.mjs";import{t as c}from"./project-discovery-CWRjlFnC.mjs";import{t as l}from"./done-input-validation-LiTaCEzF.mjs";import{t as u}from"./missing-manifest-D8y1VL4p.mjs";import{n as d,t as f}from"./project-discovery-g29vd44a.mjs";import{n as p,r as m,t as h}from"./prompts-BhXfYD6g.mjs";import{t as g}from"./project-plan-apply-Bg_1eMX9.mjs";import{a as _,l as v,o as y,r as b,s as x,t as S,u as C}from"./scaffold-planning-Bp_yqZWx.mjs";import{CustomFunctionType as w}from"@transcend-io/privacy-types";import{join as T}from"node:path";import E from"colors";async function D(e){let t=await e.select(`Custom Function type:`,[{name:o[w.General],value:w.General},{name:o[w.Dsr],value:w.Dsr}],w.General),n=r[t];if(n.length<2){let[e]=n;if(e===void 0)throw Error(`No Custom Function templates are defined for type ${t}.`);return e}return e.select(`Template:`,n.map(e=>({name:i[e],value:e})),n[0])}async function O(r,i){l(this.process);try{let o=d(this,{...i?{directory:i}:{},...r.manifest?{manifest:r.manifest}:{}});if(!this.fs.existsSync(o.manifestPath)){let e=this.process.cwd();throw Error(u({cwd:e,manifestPath:o.manifestPath,discoveredManifestPaths:f(this,e),command:`new`}))}let l=new p(this),h=m(r,this.process.stdin.isTTY,this.process.stderr.isTTY),w=r.name??(h?await l.text(`Custom Function display name:`,void 0,e=>{try{return a(e),!0}catch(e){return e instanceof Error?e.message:String(e)}}):void 0);if(!w)throw Error(`Missing Custom Function name. Pass --name in a non-interactive invocation.`);let O=r.template??(h?await D(l):void 0);if(!O||!s.includes(O))throw Error(`Missing Custom Function template. Pass --template=general, --template=dsr-datapoint, --template=dsr-enricher, or --template=dsr-both.`);let k=y(w,O),A=S({state:o,snapshots:c(this,o.manifestDirectory,b(o,k))},{generated:k});this.fs.existsSync(o.denoConfigPath)||A.warnings.push(`No Deno configuration was found. Run transcend custom-functions init ${n(o.targetDirectory,o.manifestPath,this.process.cwd())} --deno --noInteractive.`),r.json||this.logger.info(e(A,{cwd:this.process.cwd(),title:`Custom Function plan`,details:[{label:`Target`,path:A.targetDirectory},{label:`Manifest`,path:A.manifestPath}]}));let j=A.changes.length===0||r.dryRun;if(A.changes.length>0&&!r.dryRun)if(r.yes)j=!0;else if(h)j=await l.confirm(`Apply this complete plan?`,!0);else throw Error(`The plan requires approval in a non-interactive invocation. Review with --dryRun, then pass --yes.`);j&&!r.dryRun&&A.changes.length>0&&await g(this,A);let M=j&&!r.dryRun&&A.changes.length>0,N=o.existingSkillDirectories.some(({path:e})=>this.fs.existsSync(T(o.projectRoot,e,C,`SKILL.md`))),P=v({displayName:k.displayName,sourcePath:t(this.process.cwd(),T(o.manifestDirectory,k.sourceFile.path)),targetDirectory:t(this.process.cwd(),o.targetDirectory),manifestPath:t(this.process.cwd(),o.manifestPath),hasSkill:N,variableNames:_(k.manifestEntry)}),F=x(A,{applied:M,dryRun:r.dryRun,cwd:this.process.cwd(),aiHandoff:P});if(r.json){this.process.stdout.write(`${JSON.stringify(F)}\n`);return}if(r.dryRun){this.logger.info(E.yellow(`Dry run complete. No changes were written.`));return}if(!j){this.logger.info(E.yellow(`No changes applied.`));return}this.logger.info(E.green(`Custom Function added.`)),A.nextSteps.length>0&&(this.logger.info(`\n${E.bold(`Next steps`)}`),A.nextSteps.forEach(e=>this.logger.info(e))),this.logger.info(`\n${E.bold(`AI handoff — paste into your coding agent`)}`),this.logger.info(P)}catch(e){throw e instanceof h&&this.process.exit(130),e}}export{O as _new,O as newCustomFunction};
|
|
2
|
+
//# sourceMappingURL=impl-LT1FBKID2.mjs.map
|