@transcend-io/cli 10.27.5 → 10.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +193 -24
- package/dist/app-DCY8E776.mjs +148 -0
- package/dist/app-DCY8E776.mjs.map +1 -0
- package/dist/{approvePrivacyRequests-B842tXn4.mjs → approvePrivacyRequests-80SV_94y.mjs} +2 -2
- package/dist/{approvePrivacyRequests-B842tXn4.mjs.map → approvePrivacyRequests-80SV_94y.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-CRrUU89C.mjs → buildExamples-2YDkSvtA.mjs} +2 -2
- package/dist/{buildExamples-CRrUU89C.mjs.map → buildExamples-2YDkSvtA.mjs.map} +1 -1
- package/dist/{buildXdiSyncEndpoint-B9seJTxP.mjs → buildXdiSyncEndpoint-B3zUrI16.mjs} +2 -2
- package/dist/{buildXdiSyncEndpoint-B9seJTxP.mjs.map → buildXdiSyncEndpoint-B3zUrI16.mjs.map} +1 -1
- package/dist/{bulkRestartRequests-CE7cDUMd.mjs → bulkRestartRequests-BLb8OJmf.mjs} +2 -2
- package/dist/{bulkRestartRequests-CE7cDUMd.mjs.map → bulkRestartRequests-BLb8OJmf.mjs.map} +1 -1
- package/dist/{bulkRetryEnrichers-BcSANZPC.mjs → bulkRetryEnrichers-BA9cboSe.mjs} +2 -2
- package/dist/{bulkRetryEnrichers-BcSANZPC.mjs.map → bulkRetryEnrichers-BA9cboSe.mjs.map} +1 -1
- package/dist/{cancelPrivacyRequests-BKibbagv.mjs → cancelPrivacyRequests-BEyOBJ2r.mjs} +2 -2
- package/dist/{cancelPrivacyRequests-BKibbagv.mjs.map → cancelPrivacyRequests-BEyOBJ2r.mjs.map} +1 -1
- package/dist/{codecs-zRkskjaJ.mjs → codecs-BsQFAFGT.mjs} +1 -1
- package/dist/{codecs-zRkskjaJ.mjs.map → codecs-BsQFAFGT.mjs.map} +1 -1
- package/dist/{collectCsvFilesOrExit-Dg5U3Qx_.mjs → collectCsvFilesOrExit-BqnmK63h.mjs} +1 -1
- package/dist/{collectCsvFilesOrExit-Dg5U3Qx_.mjs.map → collectCsvFilesOrExit-BqnmK63h.mjs.map} +1 -1
- package/dist/{collectParquetFilesOrExit-BlG2RRSC.mjs → collectParquetFilesOrExit-BiksFI-Q.mjs} +1 -1
- package/dist/{collectParquetFilesOrExit-BlG2RRSC.mjs.map → collectParquetFilesOrExit-BiksFI-Q.mjs.map} +1 -1
- package/dist/{command-DKNKpgUB.mjs → command-eIenZMOx.mjs} +2 -2
- package/dist/{command-DKNKpgUB.mjs.map → command-eIenZMOx.mjs.map} +1 -1
- package/dist/commands/admin/chunk-csv/worker.mjs +1 -1
- package/dist/commands/admin/parquet-to-csv/worker.mjs +1 -1
- package/dist/{consentManagersToBusinessEntities-Rv-ajWya.mjs → consentManagersToBusinessEntities-O4KBox9u.mjs} +1 -1
- package/dist/{consentManagersToBusinessEntities-Rv-ajWya.mjs.map → consentManagersToBusinessEntities-O4KBox9u.mjs.map} +1 -1
- package/dist/{constants-CdgK1myP.mjs → constants-BG53Mbi9.mjs} +2 -2
- package/dist/{constants-CdgK1myP.mjs.map → constants-BG53Mbi9.mjs.map} +1 -1
- package/dist/{constants-FbK2iR--.mjs → constants-BMAOvdcA.mjs} +1 -1
- package/dist/{constants-FbK2iR--.mjs.map → constants-BMAOvdcA.mjs.map} +1 -1
- package/dist/{constants-B6wESCW2.mjs → constants-BpQ5awGp.mjs} +2 -2
- package/dist/{constants-B6wESCW2.mjs.map → constants-BpQ5awGp.mjs.map} +1 -1
- package/dist/{constants-BuoISmXP.mjs → constants-C1seVfCu.mjs} +1 -1
- package/dist/{constants-BuoISmXP.mjs.map → constants-C1seVfCu.mjs.map} +1 -1
- package/dist/{context-4GAUnhTE.mjs → context-CZYrQfAn.mjs} +1 -1
- package/dist/{context-4GAUnhTE.mjs.map → context-CZYrQfAn.mjs.map} +1 -1
- package/dist/{createPoolingCommandUi-vTsGgYZT.mjs → createPoolingCommandUi-C39R_zo3.mjs} +2 -2
- package/dist/{createPoolingCommandUi-vTsGgYZT.mjs.map → createPoolingCommandUi-C39R_zo3.mjs.map} +1 -1
- package/dist/{dataFlowsToDataSilos-DRuAfwIn.mjs → dataFlowsToDataSilos-CLSHb1GA.mjs} +1 -1
- package/dist/{dataFlowsToDataSilos-DRuAfwIn.mjs.map → dataFlowsToDataSilos-CLSHb1GA.mjs.map} +1 -1
- package/dist/deno-runtime-QqwBDKXX.mjs +2 -0
- package/dist/deno-runtime-QqwBDKXX.mjs.map +1 -0
- package/dist/{done-input-validation-BFgMCQWH.mjs → done-input-validation-Cjk7a3jX.mjs} +1 -1
- package/dist/{done-input-validation-BFgMCQWH.mjs.map → done-input-validation-Cjk7a3jX.mjs.map} +1 -1
- package/dist/{downloadPrivacyRequestFiles-Dn3VexN2.mjs → downloadPrivacyRequestFiles-CLFgQItk.mjs} +2 -2
- package/dist/{downloadPrivacyRequestFiles-Dn3VexN2.mjs.map → downloadPrivacyRequestFiles-CLFgQItk.mjs.map} +1 -1
- package/dist/{extractClientError-DeS63kje.mjs → extractClientError-C_6ly7Gw.mjs} +1 -1
- package/dist/{extractClientError-DeS63kje.mjs.map → extractClientError-C_6ly7Gw.mjs.map} +1 -1
- package/dist/{fetchAllRequests-DUQGTJjx.mjs → fetchAllRequests-CEDKdq0c.mjs} +2 -2
- package/dist/{fetchAllRequests-DUQGTJjx.mjs.map → fetchAllRequests-CEDKdq0c.mjs.map} +1 -1
- package/dist/{formatPolicyBundleVersionSummary-Bo7DYxoy.mjs → formatPolicyBundleVersionSummary-CrFtcPwS.mjs} +1 -1
- package/dist/{formatPolicyBundleVersionSummary-Bo7DYxoy.mjs.map → formatPolicyBundleVersionSummary-CrFtcPwS.mjs.map} +1 -1
- package/dist/{fuzzyMatchColumns-BDD4a2W0.mjs → fuzzyMatchColumns-OTsFJ21f.mjs} +2 -2
- package/dist/{fuzzyMatchColumns-BDD4a2W0.mjs.map → fuzzyMatchColumns-OTsFJ21f.mjs.map} +1 -1
- package/dist/{generateCrossAccountApiKeys-QhnLqtUN.mjs → generateCrossAccountApiKeys-D6O_Qm3Y.mjs} +2 -2
- package/dist/{generateCrossAccountApiKeys-QhnLqtUN.mjs.map → generateCrossAccountApiKeys-D6O_Qm3Y.mjs.map} +1 -1
- package/dist/{impl-CrY1za0t.mjs → impl-6m7GXUAe.mjs} +2 -2
- package/dist/{impl-CrY1za0t.mjs.map → impl-6m7GXUAe.mjs.map} +1 -1
- package/dist/{impl-D33Zr0vh2.mjs → impl-B--lr5RJ2.mjs} +2 -2
- package/dist/{impl-D33Zr0vh2.mjs.map → impl-B--lr5RJ2.mjs.map} +1 -1
- package/dist/{impl-QeWNZCg4.mjs → impl-B3_hrFPX.mjs} +2 -2
- package/dist/{impl-QeWNZCg4.mjs.map → impl-B3_hrFPX.mjs.map} +1 -1
- package/dist/{impl-CbijbA-M2.mjs → impl-BFJtKA2o2.mjs} +2 -2
- package/dist/{impl-CbijbA-M2.mjs.map → impl-BFJtKA2o2.mjs.map} +1 -1
- package/dist/{impl-GnxjtYL7.mjs → impl-BJlKQJdS2.mjs} +2 -2
- package/dist/impl-BJlKQJdS2.mjs.map +1 -0
- package/dist/{impl-_rrZ0KXo.mjs → impl-BNPgYSBT.mjs} +2 -2
- package/dist/{impl-_rrZ0KXo.mjs.map → impl-BNPgYSBT.mjs.map} +1 -1
- package/dist/{impl-s5h7dIlv2.mjs → impl-BWVe4VGF2.mjs} +2 -2
- package/dist/{impl-s5h7dIlv2.mjs.map → impl-BWVe4VGF2.mjs.map} +1 -1
- package/dist/{impl-DiyWNLJq.mjs → impl-BYGNx-8W2.mjs} +2 -2
- package/dist/impl-BYGNx-8W2.mjs.map +1 -0
- package/dist/impl-BcJ019T2.mjs +2 -0
- package/dist/impl-BcJ019T2.mjs.map +1 -0
- package/dist/{impl-CMYYX3Kz.mjs → impl-BewF8tB6.mjs} +2 -2
- package/dist/{impl-CMYYX3Kz.mjs.map → impl-BewF8tB6.mjs.map} +1 -1
- package/dist/{impl-DQG3PiAW2.mjs → impl-Bq6g_xYv.mjs} +2 -2
- package/dist/impl-Bq6g_xYv.mjs.map +1 -0
- package/dist/{impl-DRimS_G8.mjs → impl-BqrSLoig.mjs} +2 -2
- package/dist/{impl-DRimS_G8.mjs.map → impl-BqrSLoig.mjs.map} +1 -1
- package/dist/{impl-CccuY3Za.mjs → impl-Bs-drNBf.mjs} +2 -2
- package/dist/{impl-CccuY3Za.mjs.map → impl-Bs-drNBf.mjs.map} +1 -1
- package/dist/impl-BsC1KVxS.mjs +2 -0
- package/dist/impl-BsC1KVxS.mjs.map +1 -0
- package/dist/{impl-BgxjEv88.mjs → impl-BvNZqLrT.mjs} +2 -2
- package/dist/{impl-BgxjEv88.mjs.map → impl-BvNZqLrT.mjs.map} +1 -1
- package/dist/{impl-BkyqCY72.mjs → impl-BwRcpAno.mjs} +2 -2
- package/dist/{impl-BkyqCY72.mjs.map → impl-BwRcpAno.mjs.map} +1 -1
- package/dist/{impl-BddyFp_q.mjs → impl-BySmbxEt.mjs} +2 -2
- package/dist/{impl-BddyFp_q.mjs.map → impl-BySmbxEt.mjs.map} +1 -1
- package/dist/{impl-BPn_YPIq2.mjs → impl-C50tdWlL2.mjs} +2 -2
- package/dist/{impl-BPn_YPIq2.mjs.map → impl-C50tdWlL2.mjs.map} +1 -1
- package/dist/{impl-CusKk_JR2.mjs → impl-C5dzaDga2.mjs} +2 -2
- package/dist/{impl-CusKk_JR2.mjs.map → impl-C5dzaDga2.mjs.map} +1 -1
- package/dist/impl-C8BmxFQ2.mjs +2 -0
- package/dist/impl-C8BmxFQ2.mjs.map +1 -0
- package/dist/{impl-CBC5K-IH.mjs → impl-CDtUusmg.mjs} +2 -2
- package/dist/{impl-CBC5K-IH.mjs.map → impl-CDtUusmg.mjs.map} +1 -1
- package/dist/{impl-Dpes0u_6.mjs → impl-CE56-wQh.mjs} +2 -2
- package/dist/{impl-Dpes0u_6.mjs.map → impl-CE56-wQh.mjs.map} +1 -1
- package/dist/{impl-DzJG5HaX.mjs → impl-CEmXPEq22.mjs} +2 -2
- package/dist/impl-CEmXPEq22.mjs.map +1 -0
- package/dist/{impl-CZ-KvZE02.mjs → impl-CHmjV-Pa.mjs} +2 -2
- package/dist/impl-CHmjV-Pa.mjs.map +1 -0
- package/dist/{impl-CXdy0YMX.mjs → impl-CQGeH47F.mjs} +2 -2
- package/dist/{impl-CXdy0YMX.mjs.map → impl-CQGeH47F.mjs.map} +1 -1
- package/dist/{impl-DG9RwTkA2.mjs → impl-CTIWliTx.mjs} +2 -2
- package/dist/impl-CTIWliTx.mjs.map +1 -0
- package/dist/{impl-DbPLuDc22.mjs → impl-CWh9H7mL.mjs} +2 -2
- package/dist/impl-CWh9H7mL.mjs.map +1 -0
- package/dist/{impl-BQTw6jpw.mjs → impl-CXUJ1eRC.mjs} +2 -2
- package/dist/{impl-BQTw6jpw.mjs.map → impl-CXUJ1eRC.mjs.map} +1 -1
- package/dist/{impl-xRwX5ZLK.mjs → impl-CfPXYgT42.mjs} +2 -2
- package/dist/impl-CfPXYgT42.mjs.map +1 -0
- package/dist/{impl-CLVMZXJo.mjs → impl-CiYKuCHV.mjs} +2 -2
- package/dist/{impl-CLVMZXJo.mjs.map → impl-CiYKuCHV.mjs.map} +1 -1
- package/dist/{impl-BoCD0t4j.mjs → impl-CqF9xIIy.mjs} +2 -2
- package/dist/{impl-BoCD0t4j.mjs.map → impl-CqF9xIIy.mjs.map} +1 -1
- package/dist/{impl-CVChVd63.mjs → impl-Cx3T0Iei.mjs} +2 -2
- package/dist/{impl-CVChVd63.mjs.map → impl-Cx3T0Iei.mjs.map} +1 -1
- package/dist/impl-CzxvoiGW.mjs +3 -0
- package/dist/impl-CzxvoiGW.mjs.map +1 -0
- package/dist/impl-D-SQJc3t.mjs +2 -0
- package/dist/impl-D-SQJc3t.mjs.map +1 -0
- package/dist/{impl-BPjGRqOL2.mjs → impl-D23kJPAQ2.mjs} +2 -2
- package/dist/{impl-BPjGRqOL2.mjs.map → impl-D23kJPAQ2.mjs.map} +1 -1
- package/dist/{impl-uKjAibIR.mjs → impl-DF8RGVlT.mjs} +2 -2
- package/dist/{impl-uKjAibIR.mjs.map → impl-DF8RGVlT.mjs.map} +1 -1
- package/dist/{impl-PYtpY5hs2.mjs → impl-DHfYO9T52.mjs} +2 -2
- package/dist/{impl-PYtpY5hs2.mjs.map → impl-DHfYO9T52.mjs.map} +1 -1
- package/dist/{impl-p0AyZWFL.mjs → impl-DIPvFKiP.mjs} +2 -2
- package/dist/{impl-p0AyZWFL.mjs.map → impl-DIPvFKiP.mjs.map} +1 -1
- package/dist/{impl-CzbVqbm0.mjs → impl-DJLlcqSg.mjs} +2 -2
- package/dist/{impl-CzbVqbm0.mjs.map → impl-DJLlcqSg.mjs.map} +1 -1
- package/dist/{impl-3IyENr9T.mjs → impl-DOoR93T6.mjs} +2 -2
- package/dist/{impl-3IyENr9T.mjs.map → impl-DOoR93T6.mjs.map} +1 -1
- package/dist/{impl-BiBNqcob.mjs → impl-DXNcD7CZ.mjs} +2 -2
- package/dist/{impl-BiBNqcob.mjs.map → impl-DXNcD7CZ.mjs.map} +1 -1
- package/dist/{impl-nJ7LzilX2.mjs → impl-DYf10-BD2.mjs} +2 -2
- package/dist/{impl-nJ7LzilX2.mjs.map → impl-DYf10-BD2.mjs.map} +1 -1
- package/dist/{impl-wf0PvJms.mjs → impl-DYwojWvN.mjs} +2 -2
- package/dist/{impl-wf0PvJms.mjs.map → impl-DYwojWvN.mjs.map} +1 -1
- package/dist/{impl-CH40t5qf.mjs → impl-DbZ1cYoR.mjs} +2 -2
- package/dist/{impl-CH40t5qf.mjs.map → impl-DbZ1cYoR.mjs.map} +1 -1
- package/dist/{impl-DbF7uw7f2.mjs → impl-Dib6Fff12.mjs} +2 -2
- package/dist/{impl-DbF7uw7f2.mjs.map → impl-Dib6Fff12.mjs.map} +1 -1
- package/dist/{impl-4rLX5Wah2.mjs → impl-Dk6TZKrp2.mjs} +2 -2
- package/dist/{impl-4rLX5Wah2.mjs.map → impl-Dk6TZKrp2.mjs.map} +1 -1
- package/dist/{impl-Cq5wI-kP.mjs → impl-Dm-Fkr392.mjs} +2 -2
- package/dist/impl-Dm-Fkr392.mjs.map +1 -0
- package/dist/{impl-BsEYMBx2.mjs → impl-DpuhHpuk.mjs} +2 -2
- package/dist/{impl-BsEYMBx2.mjs.map → impl-DpuhHpuk.mjs.map} +1 -1
- package/dist/{impl-DlaWf-oS2.mjs → impl-Drql0g72.mjs} +2 -2
- package/dist/impl-Drql0g72.mjs.map +1 -0
- package/dist/{impl-_tY0CJdZ.mjs → impl-DzNk41xd.mjs} +2 -2
- package/dist/{impl-_tY0CJdZ.mjs.map → impl-DzNk41xd.mjs.map} +1 -1
- package/dist/impl-FLj_mWLO.mjs +2 -0
- package/dist/impl-FLj_mWLO.mjs.map +1 -0
- package/dist/{impl-DxXWaXFU.mjs → impl-GHukPBnk.mjs} +2 -2
- package/dist/{impl-DxXWaXFU.mjs.map → impl-GHukPBnk.mjs.map} +1 -1
- package/dist/{impl-V_ffkzbd2.mjs → impl-KKrDTraf.mjs} +2 -2
- package/dist/impl-KKrDTraf.mjs.map +1 -0
- package/dist/{impl-BbWzTCSd2.mjs → impl-M3Eu4QjS.mjs} +2 -2
- package/dist/impl-M3Eu4QjS.mjs.map +1 -0
- package/dist/{impl-BlFBTc6f.mjs → impl-VPBEqV0w2.mjs} +2 -2
- package/dist/impl-VPBEqV0w2.mjs.map +1 -0
- package/dist/{impl-DWBQKUuq.mjs → impl-amV0wRWk.mjs} +2 -2
- package/dist/{impl-DWBQKUuq.mjs.map → impl-amV0wRWk.mjs.map} +1 -1
- package/dist/impl-m3QXCc6n.mjs +91 -0
- package/dist/impl-m3QXCc6n.mjs.map +1 -0
- package/dist/{impl-Ba8naMzu.mjs → impl-syp5hclX.mjs} +2 -2
- package/dist/{impl-Ba8naMzu.mjs.map → impl-syp5hclX.mjs.map} +1 -1
- package/dist/{impl-9TDsbGfF2.mjs → impl-zZFaSmxd2.mjs} +2 -2
- package/dist/{impl-9TDsbGfF2.mjs.map → impl-zZFaSmxd2.mjs.map} +1 -1
- package/dist/index.d.mts +4 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{initializeCliRuntime-B7zDhMok.mjs → initializeCliRuntime-802-P8MC.mjs} +1 -1
- package/dist/{initializeCliRuntime-B7zDhMok.mjs.map → initializeCliRuntime-802-P8MC.mjs.map} +1 -1
- package/dist/{inquirer-DNa31Mkx.mjs → inquirer-DkFTQU00.mjs} +2 -2
- package/dist/{inquirer-DNa31Mkx.mjs.map → inquirer-DkFTQU00.mjs.map} +1 -1
- package/dist/{listFiles-DrxRhlZ2.mjs → listFiles-CWHAdKY-.mjs} +1 -1
- package/dist/{listFiles-DrxRhlZ2.mjs.map → listFiles-CWHAdKY-.mjs.map} +1 -1
- package/dist/logger-9T6vva73.mjs +2 -0
- package/dist/logger-9T6vva73.mjs.map +1 -0
- package/dist/manifest-DVuW_vvO.mjs +2 -0
- package/dist/manifest-DVuW_vvO.mjs.map +1 -0
- package/dist/{mapConsentCsvRowsToInputs-DA7BRD7M.mjs → mapConsentCsvRowsToInputs-MMPZwzrV.mjs} +1 -1
- package/dist/{mapConsentCsvRowsToInputs-DA7BRD7M.mjs.map → mapConsentCsvRowsToInputs-MMPZwzrV.mjs.map} +1 -1
- package/dist/{markRequestDataSiloIdsCompleted-CK7PNwTz.mjs → markRequestDataSiloIdsCompleted-PKCcn5wQ.mjs} +2 -2
- package/dist/{markRequestDataSiloIdsCompleted-CK7PNwTz.mjs.map → markRequestDataSiloIdsCompleted-PKCcn5wQ.mjs.map} +1 -1
- package/dist/{markSilentPrivacyRequests-Cb-J9ckA.mjs → markSilentPrivacyRequests-7l9I99pe.mjs} +2 -2
- package/dist/{markSilentPrivacyRequests-Cb-J9ckA.mjs.map → markSilentPrivacyRequests-7l9I99pe.mjs.map} +1 -1
- package/dist/{mergeTranscendInputs-CkpitZbH.mjs → mergeTranscendInputs-CWHXH0kF.mjs} +2 -2
- package/dist/{mergeTranscendInputs-CkpitZbH.mjs.map → mergeTranscendInputs-CWHXH0kF.mjs.map} +1 -1
- package/dist/missing-manifest-BKj1j-jg.mjs +2 -0
- package/dist/missing-manifest-BKj1j-jg.mjs.map +1 -0
- package/dist/module-graph-DBC7ZvyA.mjs +2 -0
- package/dist/module-graph-DBC7ZvyA.mjs.map +1 -0
- package/dist/{notifyPrivacyRequestsAdditionalTime-it1FA62W.mjs → notifyPrivacyRequestsAdditionalTime-BPIYuCov.mjs} +2 -2
- package/dist/{notifyPrivacyRequestsAdditionalTime-it1FA62W.mjs.map → notifyPrivacyRequestsAdditionalTime-BPIYuCov.mjs.map} +1 -1
- package/dist/{parquetToCsvOneFile-Dtz90qfJ.mjs → parquetToCsvOneFile-CSVdrLvq.mjs} +2 -2
- package/dist/{parquetToCsvOneFile-Dtz90qfJ.mjs.map → parquetToCsvOneFile-CSVdrLvq.mjs.map} +1 -1
- package/dist/{parseAttributesFromString-BxJcnKmn.mjs → parseAttributesFromString-C5-KGkPH.mjs} +2 -2
- package/dist/{parseAttributesFromString-BxJcnKmn.mjs.map → parseAttributesFromString-C5-KGkPH.mjs.map} +1 -1
- package/dist/parseVariablesFromString-Cr3x2uq3.mjs +2 -0
- package/dist/parseVariablesFromString-Cr3x2uq3.mjs.map +1 -0
- package/dist/{policyEngineCliError-BnBghLd1.mjs → policyEngineCliError-DY8V-qkK.mjs} +1 -1
- package/dist/{policyEngineCliError-BnBghLd1.mjs.map → policyEngineCliError-DY8V-qkK.mjs.map} +1 -1
- package/dist/{printResult-oXnpZu_9.mjs → printResult-esxW3HhT.mjs} +2 -2
- package/dist/{printResult-oXnpZu_9.mjs.map → printResult-esxW3HhT.mjs.map} +1 -1
- package/dist/project-plan-apply-C2DfikVN.mjs +3 -0
- package/dist/project-plan-apply-C2DfikVN.mjs.map +1 -0
- package/dist/{pullAllDatapoints-XqreMBT5.mjs → pullAllDatapoints-H92qjLSx.mjs} +2 -2
- package/dist/{pullAllDatapoints-XqreMBT5.mjs.map → pullAllDatapoints-H92qjLSx.mjs.map} +1 -1
- package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-DuPDOm6f.mjs → pullChunkedCustomSiloOutstandingIdentifiers-BrDmPbvc.mjs} +2 -2
- package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-DuPDOm6f.mjs.map → pullChunkedCustomSiloOutstandingIdentifiers-BrDmPbvc.mjs.map} +1 -1
- package/dist/{pullConsentManagerMetrics-Dk5IejaY.mjs → pullConsentManagerMetrics-Cvex-gpd.mjs} +2 -2
- package/dist/{pullConsentManagerMetrics-Dk5IejaY.mjs.map → pullConsentManagerMetrics-Cvex-gpd.mjs.map} +1 -1
- package/dist/{pullManualEnrichmentIdentifiersToCsv-CAD1navz.mjs → pullManualEnrichmentIdentifiersToCsv-qjdNA75O.mjs} +2 -2
- package/dist/{pullManualEnrichmentIdentifiersToCsv-CAD1navz.mjs.map → pullManualEnrichmentIdentifiersToCsv-qjdNA75O.mjs.map} +1 -1
- package/dist/{pullTranscendConfiguration-NcFjHE8k.mjs → pullTranscendConfiguration-CD7Frn8z.mjs} +2 -2
- package/dist/{pullTranscendConfiguration-NcFjHE8k.mjs.map → pullTranscendConfiguration-CD7Frn8z.mjs.map} +1 -1
- package/dist/{pullUnstructuredSubDataPointRecommendations-Cf4irXl4.mjs → pullUnstructuredSubDataPointRecommendations-Dmh_-r95.mjs} +2 -2
- package/dist/{pullUnstructuredSubDataPointRecommendations-Cf4irXl4.mjs.map → pullUnstructuredSubDataPointRecommendations-Dmh_-r95.mjs.map} +1 -1
- package/dist/{pushCronIdentifiersFromCsv-BGaJycWo.mjs → pushCronIdentifiersFromCsv-DjeY7TtK.mjs} +2 -2
- package/dist/{pushCronIdentifiersFromCsv-BGaJycWo.mjs.map → pushCronIdentifiersFromCsv-DjeY7TtK.mjs.map} +1 -1
- package/dist/{pushManualEnrichmentIdentifiersFromCsv-B9okRkhL.mjs → pushManualEnrichmentIdentifiersFromCsv-BDtMo13j.mjs} +2 -2
- package/dist/{pushManualEnrichmentIdentifiersFromCsv-B9okRkhL.mjs.map → pushManualEnrichmentIdentifiersFromCsv-BDtMo13j.mjs.map} +1 -1
- package/dist/{readCsv-CmRYYFJc.mjs → readCsv-Cr_1t8F5.mjs} +1 -1
- package/dist/{readCsv-CmRYYFJc.mjs.map → readCsv-Cr_1t8F5.mjs.map} +1 -1
- package/dist/{readTranscendYaml-DtJz9mor.mjs → readTranscendYaml-STYnRzq-.mjs} +3 -3
- package/dist/readTranscendYaml-STYnRzq-.mjs.map +1 -0
- package/dist/{removeUnverifiedRequestIdentifiers-DJhxiy_D.mjs → removeUnverifiedRequestIdentifiers-B9uPApVR.mjs} +2 -2
- package/dist/{removeUnverifiedRequestIdentifiers-DJhxiy_D.mjs.map → removeUnverifiedRequestIdentifiers-B9uPApVR.mjs.map} +1 -1
- package/dist/{renderTable-DKXvortp.mjs → renderTable-DKTZbMjY.mjs} +1 -1
- package/dist/{renderTable-DKXvortp.mjs.map → renderTable-DKTZbMjY.mjs.map} +1 -1
- package/dist/{request-CCCU2SdV.mjs → request-B1yRTdG-.mjs} +1 -1
- package/dist/{request-CCCU2SdV.mjs.map → request-B1yRTdG-.mjs.map} +1 -1
- package/dist/{resolveBundleIdByName-By5Vl8Iz.mjs → resolveBundleIdByName-DuxWYrDF.mjs} +2 -2
- package/dist/{resolveBundleIdByName-By5Vl8Iz.mjs.map → resolveBundleIdByName-DuxWYrDF.mjs.map} +1 -1
- package/dist/{resolvePolicyBundleVersion-DO7IvEwb.mjs → resolvePolicyBundleVersion-DhXZKwb4.mjs} +2 -2
- package/dist/{resolvePolicyBundleVersion-DO7IvEwb.mjs.map → resolvePolicyBundleVersion-DhXZKwb4.mjs.map} +1 -1
- package/dist/{retryRequestDataSilos-6JfyZclD.mjs → retryRequestDataSilos-D9dBtbdl.mjs} +2 -2
- package/dist/{retryRequestDataSilos-6JfyZclD.mjs.map → retryRequestDataSilos-D9dBtbdl.mjs.map} +1 -1
- package/dist/run-captured-process-CpZBh0lG.mjs +2 -0
- package/dist/run-captured-process-CpZBh0lG.mjs.map +1 -0
- package/dist/{runOpa-Q2r3qPsi.mjs → runOpa-CkKAwsvB.mjs} +2 -2
- package/dist/{runOpa-Q2r3qPsi.mjs.map → runOpa-CkKAwsvB.mjs.map} +1 -1
- package/dist/scaffold-planning-DMACXSnX.mjs +121 -0
- package/dist/scaffold-planning-DMACXSnX.mjs.map +1 -0
- package/dist/scaffold-templates-CsHM1y80.mjs +84 -0
- package/dist/scaffold-templates-CsHM1y80.mjs.map +1 -0
- package/dist/{skipPreflightJobs-xpbtJ3dK.mjs → skipPreflightJobs-Beia_iB6.mjs} +2 -2
- package/dist/{skipPreflightJobs-xpbtJ3dK.mjs.map → skipPreflightJobs-Beia_iB6.mjs.map} +1 -1
- package/dist/{skipRequestDataSilos-B7RA6I3Z.mjs → skipRequestDataSilos-BSNLacnR.mjs} +2 -2
- package/dist/{skipRequestDataSilos-B7RA6I3Z.mjs.map → skipRequestDataSilos-BSNLacnR.mjs.map} +1 -1
- package/dist/{streamPrivacyRequestsToCsv-DT31SP6w.mjs → streamPrivacyRequestsToCsv-Cksb9D49.mjs} +2 -2
- package/dist/{streamPrivacyRequestsToCsv-DT31SP6w.mjs.map → streamPrivacyRequestsToCsv-Cksb9D49.mjs.map} +1 -1
- package/dist/{syncCodePackages-ozt9aBXf.mjs → syncCodePackages-DsC1tE8B.mjs} +2 -2
- package/dist/{syncCodePackages-ozt9aBXf.mjs.map → syncCodePackages-DsC1tE8B.mjs.map} +1 -1
- package/dist/{updateConsentManagerVersionToLatest-CCzWEBEj.mjs → updateConsentManagerVersionToLatest-CaEkTnlL.mjs} +2 -2
- package/dist/{updateConsentManagerVersionToLatest-CCzWEBEj.mjs.map → updateConsentManagerVersionToLatest-CaEkTnlL.mjs.map} +1 -1
- package/dist/{uploadConsents-CDqFNWX_.mjs → uploadConsents-CNyuYx0o.mjs} +2 -2
- package/dist/{uploadConsents-CDqFNWX_.mjs.map → uploadConsents-CNyuYx0o.mjs.map} +1 -1
- package/dist/{uploadPrivacyRequestsFromCsv-CVpBFaYB.mjs → uploadPrivacyRequestsFromCsv-BdTQOZnF.mjs} +2 -2
- package/dist/{uploadPrivacyRequestsFromCsv-CVpBFaYB.mjs.map → uploadPrivacyRequestsFromCsv-BdTQOZnF.mjs.map} +1 -1
- package/dist/{validateTranscendAuth-3guZJPKH.mjs → validateTranscendAuth-CnHMn77m.mjs} +2 -2
- package/dist/{validateTranscendAuth-3guZJPKH.mjs.map → validateTranscendAuth-CnHMn77m.mjs.map} +1 -1
- package/dist/{writeCsv-rhlEBjYp.mjs → writeCsv-D46aDkGf.mjs} +1 -1
- package/dist/{writeCsv-rhlEBjYp.mjs.map → writeCsv-D46aDkGf.mjs.map} +1 -1
- package/package.json +10 -5
- package/dist/app-dIu3pdTM.mjs +0 -148
- package/dist/app-dIu3pdTM.mjs.map +0 -1
- package/dist/impl-BbWzTCSd2.mjs.map +0 -1
- package/dist/impl-BlFBTc6f.mjs.map +0 -1
- package/dist/impl-BqiclSRZ.mjs +0 -2
- package/dist/impl-BqiclSRZ.mjs.map +0 -1
- package/dist/impl-CZ-KvZE02.mjs.map +0 -1
- package/dist/impl-CclEOdC32.mjs +0 -2
- package/dist/impl-CclEOdC32.mjs.map +0 -1
- package/dist/impl-Cq5wI-kP.mjs.map +0 -1
- package/dist/impl-DG9RwTkA2.mjs.map +0 -1
- package/dist/impl-DQG3PiAW2.mjs.map +0 -1
- package/dist/impl-DbPLuDc22.mjs.map +0 -1
- package/dist/impl-DiyWNLJq.mjs.map +0 -1
- package/dist/impl-DlaWf-oS2.mjs.map +0 -1
- package/dist/impl-DzJG5HaX.mjs.map +0 -1
- package/dist/impl-GYM4LDKp2.mjs +0 -2
- package/dist/impl-GYM4LDKp2.mjs.map +0 -1
- package/dist/impl-GnxjtYL7.mjs.map +0 -1
- package/dist/impl-V_ffkzbd2.mjs.map +0 -1
- package/dist/impl-xRwX5ZLK.mjs.map +0 -1
- package/dist/logger-CB_h_zbj.mjs +0 -2
- package/dist/logger-CB_h_zbj.mjs.map +0 -1
- package/dist/parseVariablesFromString-cu5gPC3M.mjs +0 -2
- package/dist/parseVariablesFromString-cu5gPC3M.mjs.map +0 -1
- package/dist/readTranscendYaml-DtJz9mor.mjs.map +0 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{r as e}from"./constants-
|
|
1
|
+
import{r as e}from"./constants-BG53Mbi9.mjs";import{a as t}from"./writeCsv-D46aDkGf.mjs";import{t as n}from"./pullConsentManagerMetrics-Cvex-gpd.mjs";import{t as r}from"./validateTranscendAuth-CnHMn77m.mjs";import{t as i}from"./done-input-validation-Cjk7a3jX.mjs";import{ConsentManagerMetricBin as a}from"@transcend-io/privacy-types";import o from"node:path";import s from"colors";import{buildTranscendGraphQLClient as c}from"@transcend-io/sdk";import{map as l,mapSeries as u}from"@transcend-io/utils";async function d({auth:d,start:f,end:p,folder:m,bin:h,transcendUrl:g}){let _=h;Object.values(a).includes(_)||(this.logger.error(s.red(`Failed to parse argument "bin" with value "${h}"\nExpected one of: \n${Object.values(a).join(`
|
|
2
2
|
`)}`)),this.process.exit(1));let v=new Date(f),y=p?new Date(p):new Date;Number.isNaN(v.getTime())&&(this.logger.error(s.red(`Start date provided is invalid date. Got --start="${f}" expected --start="01/01/2023"`)),this.process.exit(1)),Number.isNaN(y.getTime())&&(this.logger.error(s.red(`End date provided is invalid date. Got --end="${p}" expected --end="01/01/2023"`)),this.process.exit(1)),v>y&&(this.logger.error(s.red(`Got a start date "${v.toISOString()}" that was larger than the end date "${y.toISOString()}". Start date must be before end date.`)),this.process.exit(1)),i(this.process);let b=await r(d,this);if(this.fs.existsSync(m)&&!this.fs.lstatSync(m).isDirectory()&&(this.logger.error(s.red(`The provided argument "folder" was passed a file. expected: folder="./consent-metrics/"`)),this.process.exit(1)),this.fs.existsSync(m)||this.fs.mkdirSync(m),this.logger.info(s.magenta(`Pulling consent metrics from start=${v.toString()} to end=${y.toISOString()} with bin size "${h}"`)),typeof b==`string`){try{let e=await n(c(g,b),{bin:_,start:v,end:y});await l(Object.entries(e),async([e,n])=>{await l(n,async({points:n,name:r})=>{let i=o.join(m,`${e}_${r}.csv`);this.logger.info(s.magenta(`Writing configuration to file "${i}"...`)),await t(i,n.map(({key:e,value:t})=>({timestamp:e,value:t})))},{concurrency:5})},{concurrency:5})}catch(e){this.logger.error(s.red(`An error occurred syncing the schema: ${e.message}`)),this.process.exit(1)}this.logger.info(s.green(`Successfully synced consent metrics to disk in folder "${m}"! View at ${e}`))}else{let r=[];await u(b,async(e,i)=>{let a=`[${i+1}/${b.length}][${e.organizationName}] `;this.logger.info(s.magenta(`~~~\n\n${a}Attempting to pull consent metrics...\n\n~~~`));let l=c(g,e.apiKey);try{let r=await n(l,{bin:_,start:v,end:y}),i=o.join(m,e.organizationName);this.fs.existsSync(i)||this.fs.mkdirSync(i),Object.entries(r).forEach(([e,n])=>{n.forEach(({points:n,name:r})=>{let a=o.join(i,`${e}_${r}.csv`);this.logger.info(s.magenta(`Writing configuration to file "${a}"...`)),t(a,n.map(({key:e,value:t})=>({timestamp:e,value:t})))})}),this.logger.info(s.green(`${a}Successfully pulled configuration!`))}catch(t){this.logger.error(s.red(`${a}Failed to sync configuration.`),t),r.push(e.organizationName)}}),r.length>0&&(this.logger.info(s.red(`Sync encountered errors for "${r.join(`,`)}". View output above for more information, or check out ${e}`)),this.process.exit(1))}}export{d as pullConsentMetrics};
|
|
3
|
-
//# sourceMappingURL=impl-
|
|
3
|
+
//# sourceMappingURL=impl-CqF9xIIy.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-CqF9xIIy.mjs","names":[],"sources":["../src/commands/consent/pull-consent-metrics/impl.ts"],"sourcesContent":["import path from 'node:path';\n\nimport { ConsentManagerMetricBin } from '@transcend-io/privacy-types';\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport { map, mapSeries } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport { ADMIN_DASH_INTEGRATIONS } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { validateTranscendAuth } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { pullConsentManagerMetrics } from '../../../lib/consent-manager/index.js';\nimport { writeCsv } from '../../../lib/helpers/index.js';\n\nexport interface PullConsentMetricsCommandFlags {\n auth: string;\n start: Date;\n end?: Date;\n folder: string;\n bin: string;\n transcendUrl: string;\n}\n\nexport async function pullConsentMetrics(\n this: LocalContext,\n { auth, start, end, folder, bin, transcendUrl }: PullConsentMetricsCommandFlags,\n): Promise<void> {\n // Validate bin\n const parsedBin = bin as ConsentManagerMetricBin;\n if (!Object.values(ConsentManagerMetricBin).includes(parsedBin)) {\n this.logger.error(\n colors.red(\n `Failed to parse argument \"bin\" with value \"${bin}\"\\n` +\n `Expected one of: \\n${Object.values(ConsentManagerMetricBin).join('\\n')}`,\n ),\n );\n this.process.exit(1);\n }\n\n // Parse the dates\n const startDate = new Date(start);\n const endDate = end ? new Date(end) : new Date();\n if (Number.isNaN(startDate.getTime())) {\n this.logger.error(\n colors.red(\n `Start date provided is invalid date. Got --start=\"${start}\" expected --start=\"01/01/2023\"`,\n ),\n );\n this.process.exit(1);\n }\n if (Number.isNaN(endDate.getTime())) {\n this.logger.error(\n colors.red(\n `End date provided is invalid date. Got --end=\"${end}\" expected --end=\"01/01/2023\"`,\n ),\n );\n this.process.exit(1);\n }\n if (startDate > endDate) {\n this.logger.error(\n colors.red(\n `Got a start date \"${startDate.toISOString()}\" that was larger than the end date \"${endDate.toISOString()}\". ` +\n 'Start date must be before end date.',\n ),\n );\n this.process.exit(1);\n }\n\n doneInputValidation(this.process);\n\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth, this);\n\n // Ensure folder either does not exist or is not a file\n if (this.fs.existsSync(folder) && !this.fs.lstatSync(folder).isDirectory()) {\n this.logger.error(\n colors.red(\n 'The provided argument \"folder\" was passed a file. expected: folder=\"./consent-metrics/\"',\n ),\n );\n this.process.exit(1);\n }\n\n // Create the folder if it does not exist\n if (!this.fs.existsSync(folder)) {\n this.fs.mkdirSync(folder);\n }\n\n this.logger.info(\n colors.magenta(\n `Pulling consent metrics from start=${startDate.toString()} to end=${endDate.toISOString()} with bin size \"${bin}\"`,\n ),\n );\n\n // Sync to Disk\n if (typeof apiKeyOrList === 'string') {\n try {\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, apiKeyOrList);\n\n // Pull the metrics\n const configuration = await pullConsentManagerMetrics(client, {\n bin: parsedBin,\n start: startDate,\n end: endDate,\n });\n\n // Write to file\n await map(\n Object.entries(configuration),\n async ([metricName, metrics]) => {\n await map(\n metrics,\n async ({ points, name }) => {\n const file = path.join(folder, `${metricName}_${name}.csv`);\n this.logger.info(colors.magenta(`Writing configuration to file \"${file}\"...`));\n await writeCsv(\n file,\n points.map(({ key, value }: { key: string; value: string }) => ({\n timestamp: key,\n value,\n })),\n );\n },\n {\n concurrency: 5,\n },\n );\n },\n { concurrency: 5 },\n );\n } catch (err) {\n this.logger.error(colors.red(`An error occurred syncing the schema: ${err.message}`));\n this.process.exit(1);\n }\n\n // Indicate success\n this.logger.info(\n colors.green(\n `Successfully synced consent metrics to disk in folder \"${folder}\"! View at ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n } else {\n const encounteredErrors: string[] = [];\n await mapSeries(apiKeyOrList, async (apiKey, ind) => {\n const prefix = `[${ind + 1}/${apiKeyOrList.length}][${apiKey.organizationName}] `;\n this.logger.info(\n colors.magenta(`~~~\\n\\n${prefix}Attempting to pull consent metrics...\\n\\n~~~`),\n );\n\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, apiKey.apiKey);\n\n try {\n const configuration = await pullConsentManagerMetrics(client, {\n bin: parsedBin,\n start: startDate,\n end: endDate,\n });\n\n // ensure folder exists for that organization\n const subFolder = path.join(folder, apiKey.organizationName);\n if (!this.fs.existsSync(subFolder)) {\n this.fs.mkdirSync(subFolder);\n }\n\n // Write to file\n Object.entries(configuration).forEach(([metricName, metrics]) => {\n metrics.forEach(({ points, name }) => {\n const file = path.join(subFolder, `${metricName}_${name}.csv`);\n this.logger.info(colors.magenta(`Writing configuration to file \"${file}\"...`));\n writeCsv(\n file,\n points.map(({ key, value }: { key: string; value: string }) => ({\n timestamp: key,\n value,\n })),\n );\n });\n });\n\n this.logger.info(colors.green(`${prefix}Successfully pulled configuration!`));\n } catch (err) {\n this.logger.error(colors.red(`${prefix}Failed to sync configuration.`), err);\n encounteredErrors.push(apiKey.organizationName);\n }\n });\n\n if (encounteredErrors.length > 0) {\n this.logger.info(\n colors.red(\n `Sync encountered errors for \"${encounteredErrors.join(\n ',',\n )}\". View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n this.process.exit(1);\n }\n }\n}\n"],"mappings":"sfAuBA,eAAsB,EAEpB,CAAE,OAAM,QAAO,MAAK,SAAQ,MAAK,gBAClB,CAEf,IAAM,EAAY,EACb,OAAO,OAAO,EAAwB,CAAC,SAAS,EAAU,GAC7D,KAAK,OAAO,MACV,EAAO,IACL,8CAA8C,EAAI,wBAC1B,OAAO,OAAO,EAAwB,CAAC,KAAK;EAAK,GAC1E,CACF,CACD,KAAK,QAAQ,KAAK,EAAE,EAItB,IAAM,EAAY,IAAI,KAAK,EAAM,CAC3B,EAAU,EAAM,IAAI,KAAK,EAAI,CAAG,IAAI,KACtC,OAAO,MAAM,EAAU,SAAS,CAAC,GACnC,KAAK,OAAO,MACV,EAAO,IACL,qDAAqD,EAAM,iCAC5D,CACF,CACD,KAAK,QAAQ,KAAK,EAAE,EAElB,OAAO,MAAM,EAAQ,SAAS,CAAC,GACjC,KAAK,OAAO,MACV,EAAO,IACL,iD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"./codecs-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{C as e}from"./codecs-BsQFAFGT.mjs";import{o as t}from"./readTranscendYaml-STYnRzq-.mjs";import{t as n}from"./done-input-validation-Cjk7a3jX.mjs";import{ConsentTrackerStatus as r,DataFlowScope as i}from"@transcend-io/privacy-types";import a from"colors";import{decodeCodec as o}from"@transcend-io/type-utils";import*as s from"io-ts";function c({file:c,output:l}){n(this.process),this.fs.existsSync(c)||(this.logger.error(a.red(`File does not exist: --file="${c}"`)),this.process.exit(1));let u=o(s.array(e),this.fs.readFileSync(c,`utf-8`)),d=[],f=[];u.forEach(e=>{e.dataFlows.filter(({type:e})=>e!==i.CSP).forEach(e=>{d.push({value:e.value,type:e.type,status:r.Live,trackingPurposes:e.trackingPurposes})}),e.cookies.forEach(e=>{f.push({name:e.name,status:r.Live,trackingPurposes:e.trackingPurposes})})}),this.fs.writeFileSync(l,t({"data-flows":d,cookies:f})),this.logger.info(a.green(`Successfully wrote ${d.length} data flows and ${f.length} cookies to file "${l}"`))}export{c as consentManagerServiceJsonToYml};
|
|
2
|
+
//# sourceMappingURL=impl-Cx3T0Iei.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-Cx3T0Iei.mjs","names":[],"sources":["../src/commands/inventory/consent-manager-service-json-to-yml/impl.ts"],"sourcesContent":["import { ConsentTrackerStatus, DataFlowScope } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport colors from 'colors';\nimport * as t from 'io-ts';\n\nimport { ConsentManagerServiceMetadata, CookieInput, DataFlowInput } from '../../../codecs.js';\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { serializeTranscendYaml } from '../../../lib/readTranscendYaml.js';\n\nexport interface ConsentManagerServiceJsonToYmlCommandFlags {\n file: string;\n output: string;\n}\n\nexport function consentManagerServiceJsonToYml(\n this: LocalContext,\n { file, output }: ConsentManagerServiceJsonToYmlCommandFlags,\n): void {\n doneInputValidation(this.process);\n\n // Ensure files exist\n if (!this.fs.existsSync(file)) {\n this.logger.error(colors.red(`File does not exist: --file=\"${file}\"`));\n this.process.exit(1);\n }\n\n // Read in each consent manager configuration\n const services = decodeCodec(\n t.array(ConsentManagerServiceMetadata),\n this.fs.readFileSync(file, 'utf-8'),\n );\n\n // Create data flows and cookie configurations\n const dataFlows: DataFlowInput[] = [];\n const cookies: CookieInput[] = [];\n services.forEach((service) => {\n service.dataFlows\n .filter(({ type }) => type !== DataFlowScope.CSP)\n .forEach((dataFlow) => {\n dataFlows.push({\n value: dataFlow.value,\n type: dataFlow.type,\n status: ConsentTrackerStatus.Live,\n trackingPurposes: dataFlow.trackingPurposes,\n });\n });\n\n service.cookies.forEach((cookie) => {\n cookies.push({\n name: cookie.name,\n status: ConsentTrackerStatus.Live,\n trackingPurposes: cookie.trackingPurposes,\n });\n });\n });\n\n this.fs.writeFileSync(\n output,\n serializeTranscendYaml({\n 'data-flows': dataFlows,\n cookies,\n }),\n );\n\n this.logger.info(\n colors.green(\n `Successfully wrote ${dataFlows.length} data flows and ${cookies.length} cookies to file \"${output}\"`,\n ),\n );\n}\n"],"mappings":"mVAeA,SAAgB,EAEd,CAAE,OAAM,UACF,CACN,EAAoB,KAAK,QAAQ,CAG5B,KAAK,GAAG,WAAW,EAAK,GAC3B,KAAK,OAAO,MAAM,EAAO,IAAI,gCAAgC,EAAK,GAAG,CAAC,CACtE,KAAK,QAAQ,KAAK,EAAE,EAItB,IAAM,EAAW,EACf,EAAE,MAAM,EAA8B,CACtC,KAAK,GAAG,aAAa,EAAM,QAAQ,CACpC,CAGK,EAA6B,EAAE,CAC/B,EAAyB,EAAE,CACjC,EAAS,QAAS,GAAY,CAC5B,EAAQ,UACL,QAAQ,CAAE,UAAW,IAAS,EAAc,IAAI,CAChD,QAAS,GAAa,CACrB,EAAU,KAAK,CACb,MAAO,EAAS,MAChB,KAAM,EAAS,KACf,OAAQ,EAAqB,KAC7B,iBAAkB,EAAS,iBAC5B,CAAC,EACF,CAEJ,EAAQ,QAAQ,QAAS,GAAW,CAClC,EAAQ,KAAK,CACX,KAAM,EAAO,KACb,OAAQ,EAAqB,KAC7B,iBAAkB,EAAO,iBAC1B,CAAC,EACF,EACF,CAEF,KAAK,GAAG,cACN,EACA,EAAuB,CACrB,aAAc,EACd,UACD,CAAC,CACH,CAED,KAAK,OAAO,KACV,EAAO,MACL,sBAAsB,EAAU,OAAO,kBAAkB,EAAQ,OAAO,oBAAoB,EAAO,GACpG,CACF"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as e}from"./readTranscendYaml-STYnRzq-.mjs";import{t}from"./parseVariablesFromString-Cr3x2uq3.mjs";import{t as n}from"./done-input-validation-Cjk7a3jX.mjs";import{a as r,g as i,i as a,r as o,s,t as c}from"./deno-runtime-QqwBDKXX.mjs";import{t as l}from"./missing-manifest-BKj1j-jg.mjs";import{c as u,l as d,n as f,r as p,s as m}from"./manifest-DVuW_vvO.mjs";import{t as h}from"./run-captured-process-CpZBh0lG.mjs";import{t as g}from"./module-graph-DBC7ZvyA.mjs";import{t as _}from"./project-plan-apply-C2DfikVN.mjs";import{dirname as v,extname as y,join as b,relative as x,resolve as S,sep as C}from"node:path";import w from"colors";import{DSR_DATAPOINT_CUSTOM_FUNCTION_PAYLOAD_SCHEMA as T,DSR_REQUEST_ENRICHER_CUSTOM_FUNCTION_PAYLOAD_SCHEMA as E,GENERAL_CUSTOM_FUNCTION_PAYLOAD_SCHEMA as D}from"@transcend-io/custom-function-types";import O from"ajv";import{createTwoFilesPatch as k}from"diff";import{parse as A}from"jsonc-parser";function j(e,t){e.push({severity:`error`,...t})}function M(e,t){return x(e,t).split(C).join(`/`)||`.`}function N(e){let t=t=>e.type===`DSR`?t===`REQUEST_ENRICHER`?`dsr-enricher`:`dsr-datapoint`:`general`;return e[`test-payload`]?[{entry:e,path:e[`test-payload`],type:t(e[`test-payload-type`])}]:(e[`test-payloads`]??[]).map(n=>({entry:e,path:n.payload,type:t(n[`payload-type`])}))}function P(e,t){let n=N(e).map(({type:e})=>e),r=e.type===`DSR`&&n.length===0;return{entry:e,path:S(t,e.code),needsDefault:e.type!==`DSR`||n.includes(`dsr-datapoint`),needsEnricher:n.includes(`dsr-enricher`),needsAnyDsrExport:r}}function F(){let e=new O({allErrors:!0,strict:!1});return{general:e.compile(D),"dsr-datapoint":e.compile(T),"dsr-enricher":e.compile(E)}}function I(e){return`${e.instancePath||`/`} ${e.message??`is invalid`}`}function L(e,t,n,r){let i=F(),a=[],o=[];return n.forEach(n=>{if(/<<parameters\.[^>]+>>/u.test(n.code))j(r,{code:`manifest.unresolved-code-path`,message:`Code paths cannot contain unresolved parameter placeholders.`,path:n.code,functionName:n.name});else if(f(n.code)){let i=P(n,t);e.fs.existsSync(i.path)?d(e,t,i.path)?e.fs.statSync(i.path).isFile()?a.push(i):j(r,{code:`source.not-file`,message:`Referenced source path is not a regular file.`,path:n.code,functionName:n.name}):j(r,{code:`source.outside-project`,message:`Referenced source resolves outside the manifest directory through a symlink.`,path:n.code,functionName:n.name}):j(r,{code:`source.missing`,message:`Referenced source file does not exist.`,path:n.code,functionName:n.name})}N(n).forEach(a=>{if(/<<parameters\.[^>]+>>/u.test(a.path)){j(r,{code:`manifest.unresolved-payload-path`,message:`Payload paths cannot contain unresolved parameter placeholders.`,path:a.path,functionName:n.name});return}let s=S(t,a.path);if(!e.fs.existsSync(s)){j(r,{code:`payload.missing`,message:`Referenced test payload does not exist.`,path:a.path,functionName:n.name});return}if(!d(e,t,s)){j(r,{code:`payload.outside-project`,message:`Referenced test payload resolves outside the manifest directory through a symlink.`,path:a.path,functionName:n.name});return}if(!e.fs.statSync(s).isFile()){j(r,{code:`payload.not-file`,message:`Referenced test payload is not a regular file.`,path:a.path,functionName:n.name});return}o.push(s);let c;try{c=JSON.parse(e.fs.readFileSync(s,`utf8`))}catch(e){j(r,{code:`payload.invalid-json`,message:`Invalid JSON: ${e.message}`,path:a.path,functionName:n.name});return}let l=i[a.type];l(c)||(l.errors??[]).forEach(e=>j(r,{code:`payload.schema`,message:I(e),path:a.path,functionName:n.name}))})}),{sources:a,payloadPaths:[...new Set(o)]}}function R(e){try{let t=JSON.parse(e),n=Array.isArray(t)?t:t&&typeof t==`object`&&Array.isArray(t.nodes)?t.nodes:void 0;return n?new Set(n.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e.name;return typeof t==`string`?[t]:[]})):new Set}catch{return new Set}}function z(e){switch(y(e)){case`.ts`:case`.tsx`:return`ts`;case`.json`:case`.jsonc`:return`json`;case`.yaml`:case`.yml`:return`yaml`;default:return`ts`}}function B(e,t,n){if(!n)return;let r=A(e.fs.readFileSync(n,`utf8`));if(typeof r?.importMap==`string`){if(/^[a-z][a-z\d+.-]*:/iu.test(r.importMap))return r.importMap;let i=S(v(n),r.importMap);return u(e,t,i),i}let i={};if(r.imports!==void 0&&(i.imports=r.imports),r.scopes!==void 0&&(i.scopes=r.scopes),Object.keys(i).length!==0)return`data:application/json,${encodeURIComponent(JSON.stringify(i))}`}async function V(e,t,n,r,i){let a=[],o=[];for(let s of i){u(e,n,s);let i=e.fs.readFileSync(s,`utf8`),c=await t(`deno`,[`fmt`,...r,`--ext=${z(s)}`,`-`],{cwd:n,input:i},e);if(c.code!==0)throw Error(`Deno could not preview formatting for ${M(n,s)}.${c.stderr.trim()?`\n${c.stderr.trim()}`:``}`);if(c.stdout!==i){let t=M(n,s);a.push(k(t,t,i,c.stdout,``,``,{context:3})),o.push({kind:`file`,path:s,before:i,after:c.stdout,description:`Format ${t}`,mode:e.fs.statSync(s).mode})}}return{patch:a.join(`
|
|
2
|
+
`),changes:o}}function H(e,t,n,r){j(e,{code:t,message:`${n}${r.stderr.trim()?`\n${r.stderr.trim()}`:``}`})}async function U(t,n,r=h){let i=S(n.manifestPath),a=v(i),s=[],l=new Map([[`manifest`,`passed`],[`files`,`passed`],[`payloads`,`passed`],[`runtime`,`passed`],[`exports`,`passed`],[`typecheck`,`passed`],[`lint`,`passed`],[`format`,`passed`]]),f=()=>({version:1,status:s.some(({severity:e})=>e===`error`)?`failed`:`passed`,manifestPath:i,checks:[...l].map(([e,t])=>({name:e,status:t})),diagnostics:s});if(!t.fs.existsSync(i))return j(s,{code:`manifest.missing`,message:`Custom Function manifest does not exist.`,path:M(t.process.cwd(),i)}),l.set(`manifest`,`failed`),[`files`,`payloads`,`runtime`,`exports`,`typecheck`,`lint`,`format`].forEach(e=>l.set(e,`skipped`)),f();let y=[];try{y=p(e(t.fs.readFileSync(i,`utf8`),n.variables??{})).functions}catch(e){return j(s,{code:`manifest.invalid`,message:e.message,path:M(a,i)}),l.set(`manifest`,`failed`),[`files`,`payloads`,`runtime`,`exports`,`typecheck`,`lint`,`format`].forEach(e=>l.set(e,`skipped`)),f()}y.forEach(e=>{try{m({...e.env?{env:e.env}:{},...e[`allowed-hosts`]?{allowedHosts:e[`allowed-hosts`]}:{}})}catch(t){l.set(`manifest`,`failed`),j(s,{code:`manifest.execution-context`,message:t.message,path:M(a,i),functionName:e.name})}});let{sources:x,payloadPaths:C}=L(t,a,y,s);s.some(({code:e})=>[`source.`,`manifest.unresolved-code-path`].some(t=>e.startsWith(t)))&&(l.set(`files`,`failed`),[`exports`,`typecheck`,`lint`].forEach(e=>l.set(e,`failed`))),s.some(({code:e})=>[`payload.`,`manifest.unresolved-payload-path`].some(t=>e.startsWith(t)))&&l.set(`payloads`,`failed`);let w=b(a,`deno.jsonc`),T=b(a,`deno.json`),E=t.fs.existsSync(w)?w:t.fs.existsSync(T)?T:void 0,D=E!==void 0&&!d(t,a,E),O=D,k;if(D)j(s,{code:`deno.config-outside-project`,message:`Deno configuration resolves outside the manifest directory through a symlink.`,path:M(a,E)}),[`exports`,`typecheck`,`lint`,`format`].forEach(e=>l.set(e,`failed`));else try{k=B(t,a,E)}catch(e){O=!0,j(s,{code:`deno.import-map-outside-project`,message:e.message}),[`exports`,`typecheck`,`lint`,`format`].forEach(e=>l.set(e,`failed`))}let A=E&&!O?[`--config=${E}`]:[`--no-config`],N=()=>{[`exports`,`typecheck`,`lint`,`format`].forEach(e=>{l.get(e)!==`failed`&&l.set(e,`skipped`)})},P=await r(`deno`,[`--version`],{cwd:a},t),F=P.code===0?o(P.stdout):void 0;if(F?.level===`warning`&&s.push({code:`deno.version-mismatch`,severity:`warning`,message:F.message}),P.error?.code===`ENOENT`)l.set(`runtime`,`failed`),N(),j(s,{code:`deno.missing`,message:`Deno 2.x is required for export, type, lint, and format checks. Install it from ${c}`});else if(P.code!==0)l.set(`runtime`,`failed`),N(),H(s,`deno.unavailable`,`Deno could not be started.`,P);else if(F?.level===`error`)l.set(`runtime`,`failed`),N(),j(s,{code:`deno.unsupported-version`,message:F.message});else if(!O){for(let e of x){let n=await r(`deno`,[`info`,`--json`,...A,e.path],{cwd:a},t);if(n.code!==0)l.set(`files`,`failed`),H(s,`source.module-graph`,`Could not inspect runtime imports for ${M(a,e.path)}.`,n);else try{let t=g(n.stdout);t.length>0&&(l.set(`files`,`failed`),j(s,{code:`source.local-runtime-import`,message:`Custom Functions must be self-contained. Local or import-map runtime dependencies are not deployed: `+t.join(`, `),path:M(a,e.path),functionName:e.entry.name}))}catch(t){l.set(`files`,`failed`),j(s,{code:`source.module-graph`,message:t.message,path:M(a,e.path),functionName:e.entry.name})}let i=await r(`deno`,[`doc`,`--json`,...k?[`--import-map`,k]:[],e.path],{cwd:a},t);if(i.code!==0){l.set(`exports`,`failed`),H(s,`exports.inspect`,`Could not inspect exports for ${M(a,e.path)}.`,i);continue}let o=R(i.stdout);e.needsDefault&&!o.has(`default`)&&(l.set(`exports`,`failed`),j(s,{code:`exports.default-missing`,message:`The manifest fixtures require a default export.`,path:M(a,e.path),functionName:e.entry.name})),e.needsEnricher&&!o.has(`enricher`)&&(l.set(`exports`,`failed`),j(s,{code:`exports.enricher-missing`,message:"A REQUEST_ENRICHER fixture requires an `enricher` export.",path:M(a,e.path),functionName:e.entry.name})),e.needsAnyDsrExport&&!o.has(`default`)&&!o.has(`enricher`)&&(l.set(`exports`,`failed`),j(s,{code:`exports.dsr-missing`,message:"A DSR Custom Function requires a `default` or `enricher` export.",path:M(a,e.path),functionName:e.entry.name}))}let e=[...new Set(x.map(({path:e})=>e))];if(e.length>0){let n=await r(`deno`,[`check`,...A,...e],{cwd:a},t);n.code!==0&&(l.set(`typecheck`,`failed`),H(s,`deno.typecheck`,`Deno type checking failed.`,n));let i=await r(`deno`,[`lint`,...A,...e],{cwd:a},t);i.code!==0&&(l.set(`lint`,`failed`),H(s,`deno.lint`,`Deno linting failed.`,i))}let o=[...e,...C,i,...E?[E]:[],...k&&k!==E&&!/^[a-z][a-z\d+.-]*:/iu.test(k)?[k]:[]];o.forEach(e=>u(t,a,e));let c=await r(`deno`,[`fmt`,`--check`,...A,...o],{cwd:a},t);if(c.code!==0){let e;try{e=await V(t,r,a,A,o)}catch(e){return l.set(`format`,`failed`),j(s,{code:`deno.format-preview`,message:e.message}),f()}if(e.changes.length===0)return l.set(`format`,`failed`),H(s,`deno.format`,`Deno reported a formatting failure but did not produce a repair.`,c),f();if(n.fix||n.confirmFormat&&await n.confirmFormat(e.patch))try{await _(t,{rootDirectory:a,changes:e.changes})}catch(e){l.set(`format`,`failed`),j(s,{code:`deno.format-fix`,message:`Could not apply formatting transaction: ${e.message}`})}else l.set(`format`,`failed`),e.changes.forEach((t,r)=>{j(s,{code:`deno.format`,message:`Referenced file is not formatted.`+(r===0&&n.includeFormatPatchInDiagnostics&&e.patch?`\n${e.patch}`:``),path:M(a,t.path)})})}}return f()}async function W(e,o){n(this.process);let{manifestPath:c}=i(this.process.cwd(),{...o?{directory:o}:{},...e.manifest?{manifest:e.manifest}:{}}),u=this.fs.existsSync(c)?void 0:l({cwd:this.process.cwd(),manifestPath:c,discoveredManifestPaths:s(this,this.process.cwd()),command:`check`}),d=!e.json&&!e.noInteractive&&!!(this.process.stdin.isTTY&&this.process.stderr.isTTY),f=new a(this);try{let n=await U(this,{manifestPath:c,variables:t(e.variables),fix:e.fix,includeFormatPatchInDiagnostics:!e.json,...d&&!e.fix?{confirmFormat:async e=>(e&&this.logger.error(e),f.confirm(`Format the files shown above?`,!0))}:{}});u&&n.diagnostics.forEach(e=>{e.code===`manifest.missing`&&(e.message=u)}),e.json?this.process.stdout.write(`${JSON.stringify(n)}\n`):(this.logger.info(`${w.bold(`Custom Function checks`)}\n`),n.checks.forEach(({name:e,status:t})=>{let n=t===`passed`?`PASS`:t===`failed`?`FAIL`:`SKIP`,r=t===`passed`?w.green(n):t===`failed`?w.red(n):w.yellow(n);this.logger.info(`${r} ${e[0].toUpperCase()}${e.slice(1)}`)}),n.diagnostics.length>0&&this.logger.error(``),n.diagnostics.forEach(e=>{let t=e.path?`${e.path}: `:``,n=e.functionName?`[${e.functionName}] `:``,r=`${e.severity}: ${t}${n}${e.message}`;e.severity===`warning`?this.logger.warn(w.yellow(r)):this.logger.error(w.red(r))}),n.status===`passed`?(this.logger.info(``),this.logger.info(w.green(`Custom Function checks passed.`))):(this.logger.error(``),this.logger.error(w.red(`Custom Function checks failed.`)))),n.status===`failed`&&(this.process.exitCode=1)}catch(e){throw e instanceof r&&this.process.exit(130),e}}export{W as check};
|
|
3
|
+
//# sourceMappingURL=impl-CzxvoiGW.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"impl-CzxvoiGW.mjs","names":["parseJsonc"],"sources":["../src/commands/custom-functions/check/helpers.ts","../src/commands/custom-functions/check/impl.ts"],"sourcesContent":["import { dirname, extname, join, relative, resolve, sep } from 'node:path';\n\nimport {\n DSR_DATAPOINT_CUSTOM_FUNCTION_PAYLOAD_SCHEMA,\n DSR_REQUEST_ENRICHER_CUSTOM_FUNCTION_PAYLOAD_SCHEMA,\n GENERAL_CUSTOM_FUNCTION_PAYLOAD_SCHEMA,\n} from '@transcend-io/custom-function-types';\nimport Ajv, { type ErrorObject, type ValidateFunction } from 'ajv';\nimport { createTwoFilesPatch } from 'diff';\nimport { parse as parseJsonc } from 'jsonc-parser';\n\nimport type { LocalContext } from '../../../context.js';\nimport {\n runCapturedProcess,\n type CapturedProcessResult,\n type CapturedProcessRunner,\n} from '../../../lib/cli/run-captured-process.js';\nimport {\n type CustomFunctionCheckResult,\n type CustomFunctionCheckStatus,\n type CustomFunctionDiagnostic,\n} from '../../../lib/custom-functions/check-model.js';\nimport {\n DENO_INSTALL_URL,\n getDenoRuntimeCompatibility,\n SUPPORTED_DENO_MAJOR_VERSION,\n} from '../../../lib/custom-functions/deno-runtime.js';\nimport { validateCustomFunctionExecutionContext } from '../../../lib/custom-functions/execution-context.js';\nimport {\n isCustomFunctionManifestPathContained,\n parseCustomFunctionsManifest,\n type CustomFunctionManifestEntry,\n} from '../../../lib/custom-functions/manifest.js';\nimport { findNonSelfContainedRuntimeImports } from '../../../lib/custom-functions/module-graph.js';\nimport { CUSTOM_FUNCTION_RESULT_VERSION } from '../../../lib/custom-functions/scaffold-model.js';\nimport { replaceVariablesInYaml } from '../../../lib/readTranscendYaml.js';\nimport {\n assertPathPhysicallyContained,\n isPathPhysicallyContained,\n} from '../../../lib/scaffolding/path-safety.js';\nimport { applyProjectPlan } from '../../../lib/scaffolding/project-plan-apply.js';\nimport type { PlannedFileChange } from '../../../lib/scaffolding/project-plan.js';\n\n/** Payload file plus its validation contract. */\ninterface PayloadReference {\n /** Manifest entry. */\n entry: CustomFunctionManifestEntry;\n /** Manifest-relative payload path. */\n path: string;\n /** Schema variant. */\n type: 'general' | 'dsr-datapoint' | 'dsr-enricher';\n}\n\n/** Source file plus exports required by fixtures. */\ninterface SourceReference {\n /** Manifest entry. */\n entry: CustomFunctionManifestEntry;\n /** Absolute source path. */\n path: string;\n /** Whether a default export is required. */\n needsDefault: boolean;\n /** Whether an enricher export is required. */\n needsEnricher: boolean;\n /** Whether either DSR export is acceptable when no fixtures identify one. */\n needsAnyDsrExport: boolean;\n}\n\n/** Options for local validation. */\nexport interface RunCustomFunctionChecksOptions {\n /** Absolute manifest path. */\n manifestPath: string;\n /** Variables used to resolve manifest placeholders. */\n variables?: Record<string, string>;\n /** Apply Deno formatting. */\n fix: boolean;\n /** Ask for an interactive formatting repair after receiving a patch. */\n confirmFormat?: (patch: string) => Promise<boolean>;\n /** Include a unified format patch in human-oriented diagnostics. */\n includeFormatPatchInDiagnostics?: boolean;\n}\n\n/**\n * Add one diagnostic.\n *\n * @param diagnostics - Result collection\n * @param diagnostic - Diagnostic without severity\n */\nfunction addError(\n diagnostics: CustomFunctionDiagnostic[],\n diagnostic: Omit<CustomFunctionDiagnostic, 'severity'>,\n): void {\n diagnostics.push({ severity: 'error', ...diagnostic });\n}\n\n/**\n * Normalize an absolute path relative to the manifest.\n *\n * @param manifestDirectory - Manifest directory\n * @param path - Absolute path\n * @returns Portable display path\n */\nfunction relativePath(manifestDirectory: string, path: string): string {\n const value = relative(manifestDirectory, path).split(sep).join('/');\n return value || '.';\n}\n\n/**\n * Select all payload files and schema variants.\n *\n * @param entry - Manifest entry\n * @returns Payload references\n */\nfunction payloadReferences(entry: CustomFunctionManifestEntry): PayloadReference[] {\n const variant = (\n payloadType: 'DATA_POINT' | 'REQUEST_ENRICHER' | undefined,\n ): PayloadReference['type'] => {\n if (entry.type !== 'DSR') {\n return 'general';\n }\n return payloadType === 'REQUEST_ENRICHER' ? 'dsr-enricher' : 'dsr-datapoint';\n };\n if (entry['test-payload']) {\n return [\n {\n entry,\n path: entry['test-payload'],\n type: variant(entry['test-payload-type']),\n },\n ];\n }\n return (entry['test-payloads'] ?? []).map((item) => ({\n entry,\n path: item.payload,\n type: variant(item['payload-type']),\n }));\n}\n\n/**\n * Select export expectations from the registered fixtures.\n *\n * @param entry - Manifest entry\n * @param manifestDirectory - Manifest directory\n * @returns Source reference\n */\nfunction sourceReference(\n entry: CustomFunctionManifestEntry,\n manifestDirectory: string,\n): SourceReference {\n const payloadTypes = payloadReferences(entry).map(({ type }) => type);\n const dsrWithoutPayloads = entry.type === 'DSR' && payloadTypes.length === 0;\n return {\n entry,\n path: resolve(manifestDirectory, entry.code),\n needsDefault: entry.type !== 'DSR' || payloadTypes.includes('dsr-datapoint'),\n needsEnricher: payloadTypes.includes('dsr-enricher'),\n needsAnyDsrExport: dsrWithoutPayloads,\n };\n}\n\n/**\n * Compile published payload schemas.\n *\n * @returns Validators by local variant\n */\nfunction buildPayloadValidators(): Record<PayloadReference['type'], ValidateFunction> {\n const ajv = new Ajv({ allErrors: true, strict: false });\n return {\n general: ajv.compile(GENERAL_CUSTOM_FUNCTION_PAYLOAD_SCHEMA),\n 'dsr-datapoint': ajv.compile(DSR_DATAPOINT_CUSTOM_FUNCTION_PAYLOAD_SCHEMA),\n 'dsr-enricher': ajv.compile(DSR_REQUEST_ENRICHER_CUSTOM_FUNCTION_PAYLOAD_SCHEMA),\n };\n}\n\n/**\n * Format one Ajv failure.\n *\n * @param error - Ajv error\n * @returns Concise path and message\n */\nfunction formatSchemaError(error: ErrorObject): string {\n return `${error.instancePath || '/'} ${error.message ?? 'is invalid'}`;\n}\n\n/**\n * Validate referenced source and payload files without invoking Deno.\n *\n * @param context - CLI context\n * @param manifestDirectory - Manifest directory\n * @param entries - Parsed manifest entries\n * @param diagnostics - Result collection\n * @returns Existing source and format paths\n */\nfunction validateReferencedFiles(\n context: LocalContext,\n manifestDirectory: string,\n entries: readonly CustomFunctionManifestEntry[],\n diagnostics: CustomFunctionDiagnostic[],\n): {\n /** Existing source references. */\n sources: SourceReference[];\n /** Existing payload paths. */\n payloadPaths: string[];\n} {\n const validators = buildPayloadValidators();\n const sources: SourceReference[] = [];\n const payloadPaths: string[] = [];\n entries.forEach((entry) => {\n if (/<<parameters\\.[^>]+>>/u.test(entry.code)) {\n addError(diagnostics, {\n code: 'manifest.unresolved-code-path',\n message: 'Code paths cannot contain unresolved parameter placeholders.',\n path: entry.code,\n functionName: entry.name,\n });\n } else if (isCustomFunctionManifestPathContained(entry.code)) {\n const source = sourceReference(entry, manifestDirectory);\n if (!context.fs.existsSync(source.path)) {\n addError(diagnostics, {\n code: 'source.missing',\n message: 'Referenced source file does not exist.',\n path: entry.code,\n functionName: entry.name,\n });\n } else if (!isPathPhysicallyContained(context, manifestDirectory, source.path)) {\n addError(diagnostics, {\n code: 'source.outside-project',\n message: 'Referenced source resolves outside the manifest directory through a symlink.',\n path: entry.code,\n functionName: entry.name,\n });\n } else if (!context.fs.statSync(source.path).isFile()) {\n addError(diagnostics, {\n code: 'source.not-file',\n message: 'Referenced source path is not a regular file.',\n path: entry.code,\n functionName: entry.name,\n });\n } else {\n sources.push(source);\n }\n }\n\n payloadReferences(entry).forEach((reference) => {\n if (/<<parameters\\.[^>]+>>/u.test(reference.path)) {\n addError(diagnostics, {\n code: 'manifest.unresolved-payload-path',\n message: 'Payload paths cannot contain unresolved parameter placeholders.',\n path: reference.path,\n functionName: entry.name,\n });\n return;\n }\n const payloadPath = resolve(manifestDirectory, reference.path);\n if (!context.fs.existsSync(payloadPath)) {\n addError(diagnostics, {\n code: 'payload.missing',\n message: 'Referenced test payload does not exist.',\n path: reference.path,\n functionName: entry.name,\n });\n return;\n }\n if (!isPathPhysicallyContained(context, manifestDirectory, payloadPath)) {\n addError(diagnostics, {\n code: 'payload.outside-project',\n message:\n 'Referenced test payload resolves outside the manifest directory through a symlink.',\n path: reference.path,\n functionName: entry.name,\n });\n return;\n }\n if (!context.fs.statSync(payloadPath).isFile()) {\n addError(diagnostics, {\n code: 'payload.not-file',\n message: 'Referenced test payload is not a regular file.',\n path: reference.path,\n functionName: entry.name,\n });\n return;\n }\n payloadPaths.push(payloadPath);\n let payload: unknown;\n try {\n payload = JSON.parse(context.fs.readFileSync(payloadPath, 'utf8'));\n } catch (error) {\n addError(diagnostics, {\n code: 'payload.invalid-json',\n message: `Invalid JSON: ${(error as Error).message}`,\n path: reference.path,\n functionName: entry.name,\n });\n return;\n }\n const validate = validators[reference.type];\n if (!validate(payload)) {\n (validate.errors ?? []).forEach((error) =>\n addError(diagnostics, {\n code: 'payload.schema',\n message: formatSchemaError(error),\n path: reference.path,\n functionName: entry.name,\n }),\n );\n }\n });\n });\n return {\n sources,\n payloadPaths: [...new Set(payloadPaths)],\n };\n}\n\n/**\n * Read Deno's JSON documentation output for exported names.\n *\n * @param output - `deno doc --json` output\n * @returns Exported names\n */\nfunction exportedNames(output: string): Set<string> {\n try {\n const document = JSON.parse(output) as unknown;\n const nodes = Array.isArray(document)\n ? document\n : document &&\n typeof document === 'object' &&\n Array.isArray((document as Record<string, unknown>).nodes)\n ? ((document as Record<string, unknown>).nodes as unknown[])\n : undefined;\n if (!nodes) {\n return new Set();\n }\n return new Set(\n nodes.flatMap((node) => {\n if (!node || typeof node !== 'object') {\n return [];\n }\n const name = (node as Record<string, unknown>).name;\n return typeof name === 'string' ? [name] : [];\n }),\n );\n } catch {\n return new Set();\n }\n}\n\n/**\n * Choose the Deno formatter extension for stdin.\n *\n * @param path - Source path\n * @returns Deno extension\n */\nfunction denoExtension(path: string): string {\n switch (extname(path)) {\n case '.ts':\n case '.tsx':\n return 'ts';\n case '.json':\n case '.jsonc':\n return 'json';\n case '.yaml':\n case '.yml':\n return 'yaml';\n default:\n return 'ts';\n }\n}\n\n/**\n * Resolve the import-map input supported by `deno doc`.\n *\n * Deno 2.4 does not expose `--config` for `doc`. A full `deno.json` is not a\n * valid import map when it also has `tasks`, `lint`, `fmt`, or\n * `compilerOptions`, so inline `imports` / `scopes` are passed as a data URL.\n * An `importMap` reference is followed explicitly.\n *\n * @param context - CLI context\n * @param manifestDirectory - Approved project root\n * @param configPath - Selected Deno config\n * @returns Import map path or URL\n */\nfunction resolveDocImportMap(\n context: LocalContext,\n manifestDirectory: string,\n configPath: string | undefined,\n): string | undefined {\n if (!configPath) {\n return undefined;\n }\n const config = parseJsonc(context.fs.readFileSync(configPath, 'utf8')) as {\n /** Optional separate import map. */\n importMap?: unknown;\n /** Inline import map entries. */\n imports?: unknown;\n /** Inline import map scopes. */\n scopes?: unknown;\n };\n if (typeof config?.importMap === 'string') {\n if (/^[a-z][a-z\\d+.-]*:/iu.test(config.importMap)) {\n return config.importMap;\n }\n const importMapPath = resolve(dirname(configPath), config.importMap);\n assertPathPhysicallyContained(context, manifestDirectory, importMapPath);\n return importMapPath;\n }\n const importMap: {\n /** Bare-specifier remappings. */\n imports?: unknown;\n /** Scoped remappings. */\n scopes?: unknown;\n } = {};\n if (config.imports !== undefined) {\n importMap.imports = config.imports;\n }\n if (config.scopes !== undefined) {\n importMap.scopes = config.scopes;\n }\n if (Object.keys(importMap).length === 0) {\n return undefined;\n }\n return `data:application/json,${encodeURIComponent(JSON.stringify(importMap))}`;\n}\n\n/**\n * Render deterministic formatter patches without changing files.\n *\n * @param context - CLI context\n * @param runner - Process runner\n * @param manifestDirectory - Working directory\n * @param configArgs - Deno config arguments\n * @param paths - Target files\n * @returns Unified patches and transactional file changes\n */\nasync function buildFormatPlan(\n context: LocalContext,\n runner: CapturedProcessRunner,\n manifestDirectory: string,\n configArgs: readonly string[],\n paths: readonly string[],\n): Promise<{ patch: string; changes: PlannedFileChange[] }> {\n const patches: string[] = [];\n const changes: PlannedFileChange[] = [];\n for (const path of paths) {\n assertPathPhysicallyContained(context, manifestDirectory, path);\n const before = context.fs.readFileSync(path, 'utf8');\n const result = await runner(\n 'deno',\n ['fmt', ...configArgs, `--ext=${denoExtension(path)}`, '-'],\n { cwd: manifestDirectory, input: before },\n context,\n );\n if (result.code !== 0) {\n throw new Error(\n `Deno could not preview formatting for ${relativePath(manifestDirectory, path)}.${\n result.stderr.trim() ? `\\n${result.stderr.trim()}` : ''\n }`,\n );\n }\n if (result.stdout !== before) {\n const display = relativePath(manifestDirectory, path);\n patches.push(\n createTwoFilesPatch(display, display, before, result.stdout, '', '', { context: 3 }),\n );\n changes.push({\n kind: 'file',\n path,\n before,\n after: result.stdout,\n description: `Format ${display}`,\n mode: context.fs.statSync(path).mode,\n });\n }\n }\n return { patch: patches.join('\\n'), changes };\n}\n\n/**\n * Record one Deno command failure.\n *\n * @param diagnostics - Result collection\n * @param code - Stable code\n * @param message - Summary\n * @param result - Captured process result\n */\nfunction recordDenoFailure(\n diagnostics: CustomFunctionDiagnostic[],\n code: string,\n message: string,\n result: CapturedProcessResult,\n): void {\n addError(diagnostics, {\n code,\n message: `${message}${result.stderr.trim() ? `\\n${result.stderr.trim()}` : ''}`,\n });\n}\n\n/**\n * Run credential-free local validation without executing user modules.\n *\n * @param context - CLI context\n * @param options - Manifest and format behavior\n * @param runner - Captured process runner\n * @returns Stable check result\n */\nexport async function runCustomFunctionChecks(\n context: LocalContext,\n options: RunCustomFunctionChecksOptions,\n runner: CapturedProcessRunner = runCapturedProcess,\n): Promise<CustomFunctionCheckResult> {\n const manifestPath = resolve(options.manifestPath);\n const manifestDirectory = dirname(manifestPath);\n const diagnostics: CustomFunctionDiagnostic[] = [];\n const statuses = new Map<string, CustomFunctionCheckStatus>([\n ['manifest', 'passed'],\n ['files', 'passed'],\n ['payloads', 'passed'],\n ['runtime', 'passed'],\n ['exports', 'passed'],\n ['typecheck', 'passed'],\n ['lint', 'passed'],\n ['format', 'passed'],\n ]);\n const buildResult = (): CustomFunctionCheckResult => ({\n version: CUSTOM_FUNCTION_RESULT_VERSION,\n status: diagnostics.some(({ severity }) => severity === 'error') ? 'failed' : 'passed',\n manifestPath,\n checks: [...statuses].map(([name, status]) => ({ name, status })),\n diagnostics,\n });\n if (!context.fs.existsSync(manifestPath)) {\n addError(diagnostics, {\n code: 'manifest.missing',\n message: 'Custom Function manifest does not exist.',\n path: relativePath(context.process.cwd(), manifestPath),\n });\n statuses.set('manifest', 'failed');\n ['files', 'payloads', 'runtime', 'exports', 'typecheck', 'lint', 'format'].forEach((name) =>\n statuses.set(name, 'skipped'),\n );\n return buildResult();\n }\n\n let entries: readonly CustomFunctionManifestEntry[] = [];\n try {\n const manifestContents = replaceVariablesInYaml(\n context.fs.readFileSync(manifestPath, 'utf8'),\n options.variables ?? {},\n );\n entries = parseCustomFunctionsManifest(manifestContents).functions;\n } catch (error) {\n addError(diagnostics, {\n code: 'manifest.invalid',\n message: (error as Error).message,\n path: relativePath(manifestDirectory, manifestPath),\n });\n statuses.set('manifest', 'failed');\n ['files', 'payloads', 'runtime', 'exports', 'typecheck', 'lint', 'format'].forEach((name) =>\n statuses.set(name, 'skipped'),\n );\n return buildResult();\n }\n entries.forEach((entry) => {\n try {\n validateCustomFunctionExecutionContext({\n ...(entry.env ? { env: entry.env } : {}),\n ...(entry['allowed-hosts'] ? { allowedHosts: entry['allowed-hosts'] } : {}),\n });\n } catch (error) {\n statuses.set('manifest', 'failed');\n addError(diagnostics, {\n code: 'manifest.execution-context',\n message: (error as Error).message,\n path: relativePath(manifestDirectory, manifestPath),\n functionName: entry.name,\n });\n }\n });\n\n const { sources, payloadPaths } = validateReferencedFiles(\n context,\n manifestDirectory,\n entries,\n diagnostics,\n );\n if (\n diagnostics.some(({ code }) =>\n ['source.', 'manifest.unresolved-code-path'].some((prefix) => code.startsWith(prefix)),\n )\n ) {\n statuses.set('files', 'failed');\n ['exports', 'typecheck', 'lint'].forEach((name) => statuses.set(name, 'failed'));\n }\n if (\n diagnostics.some(({ code }) =>\n ['payload.', 'manifest.unresolved-payload-path'].some((prefix) => code.startsWith(prefix)),\n )\n ) {\n statuses.set('payloads', 'failed');\n }\n\n const denoJsonc = join(manifestDirectory, 'deno.jsonc');\n const denoJson = join(manifestDirectory, 'deno.json');\n const configPath = context.fs.existsSync(denoJsonc)\n ? denoJsonc\n : context.fs.existsSync(denoJson)\n ? denoJson\n : undefined;\n const unsafeConfig =\n configPath !== undefined && !isPathPhysicallyContained(context, manifestDirectory, configPath);\n let unsafeConfiguration = unsafeConfig;\n let docImportMap: string | undefined;\n if (unsafeConfig) {\n addError(diagnostics, {\n code: 'deno.config-outside-project',\n message: 'Deno configuration resolves outside the manifest directory through a symlink.',\n path: relativePath(manifestDirectory, configPath),\n });\n ['exports', 'typecheck', 'lint', 'format'].forEach((name) => statuses.set(name, 'failed'));\n } else {\n try {\n docImportMap = resolveDocImportMap(context, manifestDirectory, configPath);\n } catch (error) {\n unsafeConfiguration = true;\n addError(diagnostics, {\n code: 'deno.import-map-outside-project',\n message: (error as Error).message,\n });\n ['exports', 'typecheck', 'lint', 'format'].forEach((name) => statuses.set(name, 'failed'));\n }\n }\n const configArgs =\n configPath && !unsafeConfiguration ? [`--config=${configPath}`] : ['--no-config'];\n const skipPendingDenoChecks = (): void => {\n ['exports', 'typecheck', 'lint', 'format'].forEach((name) => {\n if (statuses.get(name) !== 'failed') {\n statuses.set(name, 'skipped');\n }\n });\n };\n const denoVersion = await runner('deno', ['--version'], { cwd: manifestDirectory }, context);\n const compatibility =\n denoVersion.code === 0 ? getDenoRuntimeCompatibility(denoVersion.stdout) : undefined;\n if (compatibility?.level === 'warning') {\n diagnostics.push({\n code: 'deno.version-mismatch',\n severity: 'warning',\n message: compatibility.message,\n });\n }\n if (denoVersion.error?.code === 'ENOENT') {\n statuses.set('runtime', 'failed');\n skipPendingDenoChecks();\n addError(diagnostics, {\n code: 'deno.missing',\n message: `Deno ${SUPPORTED_DENO_MAJOR_VERSION}.x is required for export, type, lint, and format checks. Install it from ${DENO_INSTALL_URL}`,\n });\n } else if (denoVersion.code !== 0) {\n statuses.set('runtime', 'failed');\n skipPendingDenoChecks();\n recordDenoFailure(diagnostics, 'deno.unavailable', 'Deno could not be started.', denoVersion);\n } else if (compatibility?.level === 'error') {\n statuses.set('runtime', 'failed');\n skipPendingDenoChecks();\n addError(diagnostics, {\n code: 'deno.unsupported-version',\n message: compatibility.message,\n });\n } else if (!unsafeConfiguration) {\n for (const source of sources) {\n const moduleGraph = await runner(\n 'deno',\n ['info', '--json', ...configArgs, source.path],\n { cwd: manifestDirectory },\n context,\n );\n if (moduleGraph.code !== 0) {\n statuses.set('files', 'failed');\n recordDenoFailure(\n diagnostics,\n 'source.module-graph',\n `Could not inspect runtime imports for ${relativePath(manifestDirectory, source.path)}.`,\n moduleGraph,\n );\n } else {\n try {\n const unsupportedImports = findNonSelfContainedRuntimeImports(moduleGraph.stdout);\n if (unsupportedImports.length > 0) {\n statuses.set('files', 'failed');\n addError(diagnostics, {\n code: 'source.local-runtime-import',\n message:\n 'Custom Functions must be self-contained. Local or import-map runtime dependencies are not deployed: ' +\n unsupportedImports.join(', '),\n path: relativePath(manifestDirectory, source.path),\n functionName: source.entry.name,\n });\n }\n } catch (error) {\n statuses.set('files', 'failed');\n addError(diagnostics, {\n code: 'source.module-graph',\n message: (error as Error).message,\n path: relativePath(manifestDirectory, source.path),\n functionName: source.entry.name,\n });\n }\n }\n const result = await runner(\n 'deno',\n ['doc', '--json', ...(docImportMap ? ['--import-map', docImportMap] : []), source.path],\n { cwd: manifestDirectory },\n context,\n );\n if (result.code !== 0) {\n statuses.set('exports', 'failed');\n recordDenoFailure(\n diagnostics,\n 'exports.inspect',\n `Could not inspect exports for ${relativePath(manifestDirectory, source.path)}.`,\n result,\n );\n continue;\n }\n const names = exportedNames(result.stdout);\n if (source.needsDefault && !names.has('default')) {\n statuses.set('exports', 'failed');\n addError(diagnostics, {\n code: 'exports.default-missing',\n message: 'The manifest fixtures require a default export.',\n path: relativePath(manifestDirectory, source.path),\n functionName: source.entry.name,\n });\n }\n if (source.needsEnricher && !names.has('enricher')) {\n statuses.set('exports', 'failed');\n addError(diagnostics, {\n code: 'exports.enricher-missing',\n message: 'A REQUEST_ENRICHER fixture requires an `enricher` export.',\n path: relativePath(manifestDirectory, source.path),\n functionName: source.entry.name,\n });\n }\n if (source.needsAnyDsrExport && !names.has('default') && !names.has('enricher')) {\n statuses.set('exports', 'failed');\n addError(diagnostics, {\n code: 'exports.dsr-missing',\n message: 'A DSR Custom Function requires a `default` or `enricher` export.',\n path: relativePath(manifestDirectory, source.path),\n functionName: source.entry.name,\n });\n }\n }\n\n const sourcePaths = [...new Set(sources.map(({ path }) => path))];\n if (sourcePaths.length > 0) {\n const typecheck = await runner(\n 'deno',\n ['check', ...configArgs, ...sourcePaths],\n { cwd: manifestDirectory },\n context,\n );\n if (typecheck.code !== 0) {\n statuses.set('typecheck', 'failed');\n recordDenoFailure(diagnostics, 'deno.typecheck', 'Deno type checking failed.', typecheck);\n }\n const lint = await runner(\n 'deno',\n ['lint', ...configArgs, ...sourcePaths],\n { cwd: manifestDirectory },\n context,\n );\n if (lint.code !== 0) {\n statuses.set('lint', 'failed');\n recordDenoFailure(diagnostics, 'deno.lint', 'Deno linting failed.', lint);\n }\n }\n\n const formatPaths = [\n ...sourcePaths,\n ...payloadPaths,\n manifestPath,\n ...(configPath ? [configPath] : []),\n ...(docImportMap && docImportMap !== configPath && !/^[a-z][a-z\\d+.-]*:/iu.test(docImportMap)\n ? [docImportMap]\n : []),\n ];\n formatPaths.forEach((path) => assertPathPhysicallyContained(context, manifestDirectory, path));\n const format = await runner(\n 'deno',\n ['fmt', '--check', ...configArgs, ...formatPaths],\n { cwd: manifestDirectory },\n context,\n );\n if (format.code !== 0) {\n let formatPlan: Awaited<ReturnType<typeof buildFormatPlan>>;\n try {\n formatPlan = await buildFormatPlan(\n context,\n runner,\n manifestDirectory,\n configArgs,\n formatPaths,\n );\n } catch (error) {\n statuses.set('format', 'failed');\n addError(diagnostics, {\n code: 'deno.format-preview',\n message: (error as Error).message,\n });\n return buildResult();\n }\n if (formatPlan.changes.length === 0) {\n statuses.set('format', 'failed');\n recordDenoFailure(\n diagnostics,\n 'deno.format',\n 'Deno reported a formatting failure but did not produce a repair.',\n format,\n );\n return buildResult();\n }\n const shouldFix =\n options.fix ||\n (options.confirmFormat ? await options.confirmFormat(formatPlan.patch) : false);\n if (shouldFix) {\n try {\n await applyProjectPlan(context, {\n rootDirectory: manifestDirectory,\n changes: formatPlan.changes,\n });\n } catch (error) {\n statuses.set('format', 'failed');\n addError(diagnostics, {\n code: 'deno.format-fix',\n message: `Could not apply formatting transaction: ${(error as Error).message}`,\n });\n }\n } else {\n statuses.set('format', 'failed');\n formatPlan.changes.forEach((change, index) => {\n addError(diagnostics, {\n code: 'deno.format',\n message:\n 'Referenced file is not formatted.' +\n (index === 0 && options.includeFormatPatchInDiagnostics && formatPlan.patch\n ? `\\n${formatPlan.patch}`\n : ''),\n path: relativePath(manifestDirectory, change.path),\n });\n });\n }\n }\n }\n\n return buildResult();\n}\n","import colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { formatMissingManifestMessage } from '../../../lib/custom-functions/missing-manifest.js';\nimport { resolveCustomFunctionProjectPaths } from '../../../lib/custom-functions/paths.js';\nimport { discoverCustomFunctionManifests } from '../../../lib/custom-functions/project-discovery.js';\nimport {\n CustomFunctionPrompts,\n PromptCancelledError,\n} from '../../../lib/custom-functions/prompts.js';\nimport { parseVariablesFromString } from '../../../lib/helpers/parseVariablesFromString.js';\nimport { runCustomFunctionChecks } from './helpers.js';\n\n/** CLI flags for `transcend custom-functions check`. */\nexport interface CustomFunctionsCheckFlags {\n /** Explicit manifest path. */\n manifest?: string;\n /** Manifest variable substitutions. */\n variables: string;\n /** Apply Deno formatting. */\n fix: boolean;\n /** Disable prompts. */\n noInteractive: boolean;\n /** Emit JSON on stdout. */\n json: boolean;\n}\n\n/**\n * Validate a local Custom Function project without credentials.\n *\n * @param this - CLI context\n * @param flags - Check and interaction flags\n * @param directory - Optional target directory\n */\nexport async function check(\n this: LocalContext,\n flags: CustomFunctionsCheckFlags,\n directory?: string,\n): Promise<void> {\n doneInputValidation(this.process);\n const { manifestPath } = resolveCustomFunctionProjectPaths(this.process.cwd(), {\n ...(directory ? { directory } : {}),\n ...(flags.manifest ? { manifest: flags.manifest } : {}),\n });\n const missingMessage = this.fs.existsSync(manifestPath)\n ? undefined\n : formatMissingManifestMessage({\n cwd: this.process.cwd(),\n manifestPath,\n discoveredManifestPaths: discoverCustomFunctionManifests(this, this.process.cwd()),\n command: 'check',\n });\n const interactive =\n !flags.json &&\n !flags.noInteractive &&\n Boolean(this.process.stdin.isTTY && this.process.stderr.isTTY);\n const prompts = new CustomFunctionPrompts(this);\n try {\n const result = await runCustomFunctionChecks(this, {\n manifestPath,\n variables: parseVariablesFromString(flags.variables),\n fix: flags.fix,\n includeFormatPatchInDiagnostics: !flags.json,\n ...(interactive && !flags.fix\n ? {\n confirmFormat: async (patch: string): Promise<boolean> => {\n if (patch) {\n this.logger.error(patch);\n }\n return prompts.confirm('Format the files shown above?', true);\n },\n }\n : {}),\n });\n if (missingMessage) {\n result.diagnostics.forEach((diagnostic) => {\n if (diagnostic.code === 'manifest.missing') {\n diagnostic.message = missingMessage;\n }\n });\n }\n if (flags.json) {\n this.process.stdout.write(`${JSON.stringify(result)}\\n`);\n } else {\n this.logger.info(`${colors.bold('Custom Function checks')}\\n`);\n result.checks.forEach(({ name, status }) => {\n const label = status === 'passed' ? 'PASS' : status === 'failed' ? 'FAIL' : 'SKIP';\n const styledLabel =\n status === 'passed'\n ? colors.green(label)\n : status === 'failed'\n ? colors.red(label)\n : colors.yellow(label);\n this.logger.info(`${styledLabel} ${name[0]!.toUpperCase()}${name.slice(1)}`);\n });\n if (result.diagnostics.length > 0) {\n this.logger.error('');\n }\n result.diagnostics.forEach((diagnostic) => {\n const location = diagnostic.path ? `${diagnostic.path}: ` : '';\n const owner = diagnostic.functionName ? `[${diagnostic.functionName}] ` : '';\n const message = `${diagnostic.severity}: ${location}${owner}${diagnostic.message}`;\n if (diagnostic.severity === 'warning') {\n this.logger.warn(colors.yellow(message));\n } else {\n this.logger.error(colors.red(message));\n }\n });\n if (result.status === 'passed') {\n this.logger.info('');\n this.logger.info(colors.green('Custom Function checks passed.'));\n } else {\n this.logger.error('');\n this.logger.error(colors.red('Custom Function checks failed.'));\n }\n }\n if (result.status === 'failed') {\n this.process.exitCode = 1;\n }\n } catch (error) {\n if (error instanceof PromptCancelledError) {\n this.process.exit(130);\n }\n throw error;\n }\n}\n"],"mappings":"66BAuFA,SAAS,EACP,EACA,EACM,CACN,EAAY,KAAK,CAAE,SAAU,QAAS,GAAG,EAAY,CAAC,CAUxD,SAAS,EAAa,EAA2B,EAAsB,CAErE,OADc,EAAS,EAAmB,EAAK,CAAC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hE,KAAK,OAAO,MAAM,GAAG,CACrB,KAAK,OAAO,MAAM,EAAO,IAAI,iCAAiC,CAAC,GAG/D,EAAO,SAAW,WACpB,KAAK,QAAQ,SAAW,SAEnB,EAAO,CAId,MAHI,aAAiB,GACnB,KAAK,QAAQ,KAAK,IAAI,CAElB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{g as e}from"./constants-BG53Mbi9.mjs";import{t}from"./done-input-validation-Cjk7a3jX.mjs";import{a as n,c as r,i,o as a,r as o,t as s}from"./deno-runtime-QqwBDKXX.mjs";import{t as c}from"./run-captured-process-CpZBh0lG.mjs";import{n as l,t as u}from"./project-plan-apply-C2DfikVN.mjs";import{c as d,i as f,l as p,n as m,s as h,u as g}from"./scaffold-planning-DMACXSnX.mjs";import _ from"colors";import{CUSTOM_FUNCTION_TYPES_VERSION as v}from"@transcend-io/custom-function-types";const y={[l.Deno]:`Deno configuration`,[l.Editor]:`VS Code settings`,[l.Skill]:`Agent skill`,[l.Ci]:`GitHub Actions`},b=Object.values(l);function x(e,t,n){return!e.json&&!e.noInteractive&&!!(t&&n)}async function S(e,t,n){let r={[l.Deno]:t.deno,[l.Editor]:t.editor,[l.Skill]:t.skill,[l.Ci]:t.ci};if(!n.interactive)return b.filter(e=>r[e]===!0);let i=b.map(e=>({name:y[e],value:e,checked:r[e]!==!1}));return e.checkbox(`Choose repository setup:`,i)}async function C(y,b){t(this.process);try{let t=r(this,{...b?{directory:b}:{},...y.manifest?{manifest:y.manifest}:{}}),n=new i(this),C=x(y,this.process.stdin.isTTY,this.process.stderr.isTTY),w=await S(n,y,{interactive:C}),T=m({state:t,snapshots:a(this,t.projectRoot,f(t,{features:w})),contractVersion:v,cliVersion:e},{features:w});if(w.includes(l.Deno)){let e=await c(`deno`,[`--version`],{cwd:this.process.cwd()},this);if(e.error?.code===`ENOENT`)T.warnings.push(`Deno 2.x is not installed. Install it from ${s}`);else if(e.code!==0)T.warnings.push(`Deno was found, but its version could not be determined. Deno 2.x is required. See ${s}`);else{let t=o(e.stdout);t.level!==`compatible`&&T.warnings.push(t.message)}}y.json||this.logger.info(p(T,this.process.cwd()));let E=T.changes.length===0||y.dryRun;if(T.changes.length>0&&!y.dryRun)if(y.yes)E=!0;else if(C)E=await n.confirm(`Apply this complete plan?`,!0);else throw Error(`The plan requires approval in a non-interactive invocation. Review with --dryRun, then pass --yes.`);E&&!y.dryRun&&T.changes.length>0&&await u(this,T);let D=E&&!y.dryRun&&T.changes.length>0,O=E&&!y.dryRun,k=g({targetDirectory:d(this.process.cwd(),t.targetDirectory),manifestPath:d(this.process.cwd(),t.manifestPath),cliVersion:e,hasSkill:O&&w.includes(l.Skill),hasGithubWorkflow:O&&w.includes(l.Ci)&&!!(t.repositoryRoot&&t.usesGithub)}),A=h(T,{applied:D,dryRun:y.dryRun,cwd:this.process.cwd(),aiHandoff:k});if(y.json){this.process.stdout.write(`${JSON.stringify(A)}\n`);return}if(y.dryRun){this.logger.info(_.yellow(`Dry run complete. No changes were written.`));return}if(!E){this.logger.info(_.yellow(`No changes applied.`));return}if(T.changes.length===0){this.logger.info(_.green(`Custom Function project is already initialized.`));return}this.logger.info(_.green(`Custom Function project initialized.`)),T.nextSteps.length>0&&(this.logger.info(`\n${_.bold(`Next steps`)}`),T.nextSteps.forEach(e=>this.logger.info(e))),this.logger.info(`\n${_.bold(`AI handoff — paste into your coding agent`)}`),this.logger.info(k)}catch(e){throw e instanceof n&&this.process.exit(130),e}}export{C as init};
|
|
2
|
+
//# sourceMappingURL=impl-D-SQJc3t.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"impl-D-SQJc3t.mjs","names":["CLI_VERSION"],"sources":["../src/commands/custom-functions/init/impl.ts"],"sourcesContent":["import { CUSTOM_FUNCTION_TYPES_VERSION } from '@transcend-io/custom-function-types';\nimport 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 { runCapturedProcess } from '../../../lib/cli/run-captured-process.js';\nimport { buildInitAiHandoff } from '../../../lib/custom-functions/ai-handoff.js';\nimport {\n DENO_INSTALL_URL,\n getDenoRuntimeCompatibility,\n SUPPORTED_DENO_MAJOR_VERSION,\n} from '../../../lib/custom-functions/deno-runtime.js';\nimport {\n collectPlanningSnapshots,\n discoverCustomFunctionProject,\n} from '../../../lib/custom-functions/project-discovery.js';\nimport {\n CustomFunctionPrompts,\n PromptCancelledError,\n type PromptChoice,\n} from '../../../lib/custom-functions/prompts.js';\nimport {\n CustomFunctionSetupFeature,\n type CustomFunctionSetupFeature as CustomFunctionSetupFeatureType,\n} from '../../../lib/custom-functions/scaffold-model.js';\nimport {\n buildPlanResult,\n displayPath,\n renderProjectPlan,\n} from '../../../lib/custom-functions/scaffold-output.js';\nimport {\n buildInitPlan,\n getInitPlanningCandidatePaths,\n} from '../../../lib/custom-functions/scaffold-planning.js';\nimport { applyProjectPlan } from '../../../lib/scaffolding/project-plan-apply.js';\n\n/** Flags for `custom-functions init`. */\nexport interface CustomFunctionInitFlags {\n /** Explicit manifest path. */\n manifest?: string;\n /** Install Deno configuration. */\n deno?: boolean;\n /** Install editor recommendations. */\n editor?: boolean;\n /** Install the coding-agent skill. */\n skill?: boolean;\n /** Install GitHub Actions validation. */\n ci?: boolean;\n /** Disable prompts. */\n noInteractive: boolean;\n /** Render but do not apply. */\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 setup labels. */\nconst SETUP_LABELS: Readonly<Record<CustomFunctionSetupFeatureType, string>> = {\n [CustomFunctionSetupFeature.Deno]: 'Deno configuration',\n [CustomFunctionSetupFeature.Editor]: 'VS Code settings',\n [CustomFunctionSetupFeature.Skill]: 'Agent skill',\n [CustomFunctionSetupFeature.Ci]: 'GitHub Actions',\n};\n\n/** All optional setup features in stable prompt order. */\nconst ALL_SETUP_FEATURES = Object.values(CustomFunctionSetupFeature);\n\n/**\n * Whether this invocation can ask questions.\n *\n * @param context - CLI context\n * @param flags - Interaction flags\n * @returns Whether prompts are enabled\n */\nfunction isInteractiveInvocation(\n flags: Pick<CustomFunctionInitFlags, 'json' | 'noInteractive'>,\n stdinIsTTY: boolean | undefined,\n stderrIsTTY: boolean | undefined,\n): boolean {\n return !flags.json && !flags.noInteractive && Boolean(stdinIsTTY && stderrIsTTY);\n}\n\n/**\n * Resolve setup directly from individual flags or one checkbox prompt.\n *\n * @param context - CLI context\n * @param prompts - Prompt adapters\n * @param flags - Setup flags\n * @param options - Interaction state\n * @returns Selected setup features\n */\nasync function resolveFeatures(\n prompts: CustomFunctionPrompts,\n flags: CustomFunctionInitFlags,\n options: {\n /** Whether prompts are available. */\n interactive: boolean;\n },\n): Promise<CustomFunctionSetupFeatureType[]> {\n const enabled: Readonly<Record<CustomFunctionSetupFeatureType, boolean | undefined>> = {\n [CustomFunctionSetupFeature.Deno]: flags.deno,\n [CustomFunctionSetupFeature.Editor]: flags.editor,\n [CustomFunctionSetupFeature.Skill]: flags.skill,\n [CustomFunctionSetupFeature.Ci]: flags.ci,\n };\n if (!options.interactive) {\n return ALL_SETUP_FEATURES.filter((feature) => enabled[feature] === true);\n }\n const choices: PromptChoice<CustomFunctionSetupFeatureType>[] = ALL_SETUP_FEATURES.map(\n (feature) => ({\n name: SETUP_LABELS[feature],\n value: feature,\n checked: enabled[feature] !== false,\n }),\n );\n return prompts.checkbox('Choose repository setup:', choices);\n}\n\n/**\n * Initialize a credential-free local Custom Function project.\n *\n * @param this - CLI context\n * @param flags - Scaffold and interaction flags\n * @param directory - Optional target directory\n */\nexport async function init(\n this: LocalContext,\n flags: CustomFunctionInitFlags,\n directory?: string,\n): Promise<void> {\n doneInputValidation(this.process);\n try {\n const state = discoverCustomFunctionProject(this, {\n ...(directory ? { directory } : {}),\n ...(flags.manifest ? { manifest: flags.manifest } : {}),\n });\n const prompts = new CustomFunctionPrompts(this);\n const interactive = isInteractiveInvocation(\n flags,\n this.process.stdin.isTTY,\n this.process.stderr.isTTY,\n );\n const features = await resolveFeatures(prompts, flags, { interactive });\n const snapshots = collectPlanningSnapshots(\n this,\n state.projectRoot,\n getInitPlanningCandidatePaths(state, { features }),\n );\n const plan = buildInitPlan(\n {\n state,\n snapshots,\n contractVersion: CUSTOM_FUNCTION_TYPES_VERSION,\n cliVersion: CLI_VERSION,\n },\n { features },\n );\n if (features.includes(CustomFunctionSetupFeature.Deno)) {\n const denoVersion = await runCapturedProcess(\n 'deno',\n ['--version'],\n { cwd: this.process.cwd() },\n this,\n );\n if (denoVersion.error?.code === 'ENOENT') {\n plan.warnings.push(\n `Deno ${SUPPORTED_DENO_MAJOR_VERSION}.x is not installed. Install it from ${DENO_INSTALL_URL}`,\n );\n } else if (denoVersion.code !== 0) {\n plan.warnings.push(\n `Deno was found, but its version could not be determined. Deno ${SUPPORTED_DENO_MAJOR_VERSION}.x is required. See ${DENO_INSTALL_URL}`,\n );\n } else {\n const compatibility = getDenoRuntimeCompatibility(denoVersion.stdout);\n if (compatibility.level !== 'compatible') {\n plan.warnings.push(compatibility.message);\n }\n }\n }\n if (!flags.json) {\n this.logger.info(renderProjectPlan(plan, this.process.cwd()));\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 = buildInitAiHandoff({\n targetDirectory: displayPath(this.process.cwd(), state.targetDirectory),\n manifestPath: displayPath(this.process.cwd(), state.manifestPath),\n cliVersion: CLI_VERSION,\n hasSkill: setupAvailable && features.includes(CustomFunctionSetupFeature.Skill),\n hasGithubWorkflow:\n setupAvailable &&\n features.includes(CustomFunctionSetupFeature.Ci) &&\n Boolean(state.repositoryRoot && state.usesGithub),\n });\n const result = buildPlanResult(plan, {\n applied,\n dryRun: flags.dryRun,\n cwd: this.process.cwd(),\n aiHandoff,\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 this.logger.info(colors.green('Custom Function project is already initialized.'));\n return;\n }\n this.logger.info(colors.green('Custom Function project initialized.'));\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 this.process.exit(130);\n }\n throw error;\n }\n}\n"],"mappings":"seA4DA,MAAM,EAAyE,EAC5E,EAA2B,MAAO,sBAClC,EAA2B,QAAS,oBACpC,EAA2B,OAAQ,eACnC,EAA2B,IAAK,iBAClC,CAGK,EAAqB,OAAO,OAAO,EAA2B,CASpE,SAAS,EACP,EACA,EACA,EACS,CACT,MAAO,CAAC,EAAM,MAAQ,CAAC,EAAM,eAAiB,GAAQ,GAAc,GAYtE,eAAe,EACb,EACA,EACA,EAI2C,CAC3C,IAAM,EAAiF,EACpF,EAA2B,MAAO,EAAM,MACxC,EAA2B,QAAS,EAAM,QAC1C,EAA2B,OAAQ,EAAM,OACzC,EAA2B,IAAK,EAAM,GACxC,CACD,GAAI,CAAC,EAAQ,YACX,OAAO,EAAmB,OAAQ,GAAY,EAAQ,KAAa,GAAK,CAE1E,IAAM,EAA0D,EAAmB,IAChF,IAAa,CACZ,KAAM,EAAa,GACnB,M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ACnB,KAAK,QAAQ,KAAK,IAAI,CAElB"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{t as e}from"./buildExamples-
|
|
1
|
+
import{t as e}from"./buildExamples-2YDkSvtA.mjs";import{r as t}from"./policyEngineCliError-DY8V-qkK.mjs";import{n,t as r}from"./constants-BMAOvdcA.mjs";import{r as i,t as a}from"./runOpa-CkKAwsvB.mjs";import{i as o,n as s,t as c}from"./printResult-esxW3HhT.mjs";import{t as l}from"./formatPolicyBundleVersionSummary-CrFtcPwS.mjs";import{n as u}from"./resolveBundleIdByName-DuxWYrDF.mjs";import{n as d}from"./inquirer-DkFTQU00.mjs";import{t as f}from"./done-input-validation-Cjk7a3jX.mjs";import{spawnSync as p}from"node:child_process";import m from"node:fs";import h from"node:os";import g from"node:path";import{gunzipSync as _}from"node:zlib";import v from"fast-glob";import y from"colors";function b(e){return e.endsWith(`.rego`)&&!e.endsWith(`_test.rego`)}function x(e){let t=g.join(e,`manifest.json`);if(!m.existsSync(t))throw Error(`Policy bundle directory must contain a manifest.json file.`);let n=m.readFileSync(t,`utf8`),r;try{r=JSON.parse(n)}catch(e){throw Error(`manifest.json is not valid JSON: ${e instanceof Error?e.message:String(e)}`,{cause:e})}if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`manifest.json must contain a JSON object.`);let i=r.roots;if(!Array.isArray(i)||i.length===0)throw Error(`manifest.json must declare "roots" as a non-empty array of strings (e.g. {"roots":["policy_engine"]}).`);if(!i.every(e=>typeof e==`string`&&e.length>0))throw Error(`manifest.json "roots" must be an array of non-empty strings.`);return{roots:i}}function S(e){let t=x(e),n=v.sync(`**/*.rego`,{cwd:e,onlyFiles:!0,dot:!1}).filter(b);if(n.length===0)throw Error(`Policy bundle directory must contain at least one .rego policy file.`);return{entries:[`manifest.json`,...n.sort()],manifest:t}}const C=/^\s*package\s+([A-Za-z_][\w.]*)/m;function w(e){return e.replace(/\//g,`.`)}function T(e){let t=m.readFileSync(e,`utf8`);return C.exec(t)?.[1]}function E(e,t,n){let r=n.map(w),i=[];for(let a of t){let t=T(g.join(e,a));t&&(r.some(e=>t===e||t.startsWith(`${e}.`))||i.push(` - ${a} (package ${t}) is not covered by roots [${n.join(`, `)}]`))}if(i.length>0)throw Error([`manifest.json "roots" do not cover all Rego packages in the bundle; uncovered packages will fail-closed at decide time. Either broaden "roots" or move the policy under a covered package:`,...i].join(`
|
|
2
2
|
`))}async function D(e){let t=g.join(h.tmpdir(),`transcend-policy-bundle-build-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`);try{let{code:n,stderr:r}=await a([`build`,`--v0-compatible`,`--ignore`,`*_test.rego`,`-o`,t,`.`],{cwd:e});if(n!==0)throw Error(r.trim()||`opa build failed with exit code ${n}`)}finally{m.existsSync(t)&&m.unlinkSync(t)}}function O(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t%1==0?t.toFixed(0):t.toFixed(1)} KiB`;let n=t/1024;return`${n%1==0?n.toFixed(0):n.toFixed(1)} MiB`}async function k(e){i();let t=g.resolve(e);if(!m.existsSync(t)||!m.statSync(t).isDirectory())throw Error(`Policy directory does not exist or is not a directory: ${t}`);let{entries:o,manifest:s}=S(t);E(t,o.filter(e=>e!==`manifest.json`),s.roots);let{code:c,stderr:l}=await a([`check`,`--strict`,`--v0-compatible`,t]);if(c!==0)throw Error(l.trim()||`opa check failed with exit code ${c}`);await D(t);let u=g.join(h.tmpdir(),`transcend-policy-bundle-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`),d=p(`tar`,[`-czf`,u,`-C`,t,...o],{env:{...process.env,COPYFILE_DISABLE:`1`},encoding:`utf8`});if(d.status!==0)throw Error(`Failed to create policy bundle archive: ${d.stderr.trim()||`tar failed`}`);let f=m.readFileSync(u);if(f.byteLength>5120)throw m.unlinkSync(u),Error(`Policy bundle exceeds the ${O(r)} compressed upload limit (bundle is ${O(f.byteLength)}). The server also rejects decompressed bundles larger than ${O(n)}.`);let v=_(f);if(v.byteLength>51200)throw m.unlinkSync(u),Error(`Policy bundle exceeds the ${O(n)} decompressed upload limit (bundle is ${O(v.byteLength)} decompressed).`);return u}function A(e){let t=m.readFileSync(e.bundlePath),n=new FormData;return n.append(`bundle`,new Blob([t],{type:`application/gzip`}),g.basename(e.bundlePath)),n.append(`version`,e.version),e.description&&n.append(`description`,e.description),e.bundleName&&n.append(`bundleName`,e.bundleName),n}function j(e){return e.toISOString().slice(0,19).replace(/[T:]/g,`-`)}function M(e,t=new Date){return`${e}-${j(t)}`}async function N({dir:n,"bundle-name":r,auth:i,"transcend-url":a,version:p,description:m,json:h,yes:_,debug:v=!1}){f(this.process),t(v);let b=g.resolve(n),x=p??M(r),S=o(a,i),C;try{this.logger.info(y.green(`Building policy bundle from ${b}...`)),C=await k(b);let t=await u(S,r),n;if(t){this.logger.info(y.green(`Uploading new version for bundle "${r}"...`));let e=A({bundlePath:C,version:x,description:m});n=await s(S.post(`v1/policy-engine/policy-bundles/${t}/versions`,{body:e}).json())}else{if(!this.process.stdin.isTTY&&!_){this.logger.error(y.red(`Cannot create a new bundle in a non-interactive environment; pass --yes to confirm.`)),this.process.exit(1);return}if(!_&&(this.logger.warn(y.yellow(`No policy bundle named "${r}" exists for this organization.`)),!await d({message:`No policy bundle named "${r}" exists. Create a new bundle and upload its first version?`}))){this.logger.info(y.yellow(`Publish cancelled.`));return}this.logger.info(y.green(`Creating bundle "${r}" and uploading first version...`));let e=A({bundlePath:C,version:x,description:m,bundleName:r});n=await s(S.post(`v1/policy-engine/policy-bundles`,{body:e}).json())}c(this.process.stdout,{json:h,data:n,renderTable:()=>l(n.version)}),this.logger.info(y.green(`Policy bundle version uploaded successfully.`));let i=e([`policy`,`activate`],{version:n.version.version,"bundle-name":r});this.logger.info(y.yellow(`Publishing a policy does not activate it. To activate this version, run:\n ${i}`))}finally{C&&this.fs.existsSync(C)&&this.fs.unlinkSync(C)}}export{N as publish};
|
|
3
|
-
//# sourceMappingURL=impl-
|
|
3
|
+
//# sourceMappingURL=impl-D23kJPAQ2.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-BPjGRqOL2.mjs","names":["fg"],"sources":["../src/commands/policy/helpers/buildOpaBundleTarball.ts","../src/commands/policy/helpers/buildPolicyBundleFormData.ts","../src/commands/policy/helpers/defaultPolicyVersionLabel.ts","../src/commands/policy/publish/impl.ts"],"sourcesContent":["import { spawnSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { gunzipSync } from 'node:zlib';\n\nimport fg from 'fast-glob';\n\nimport { MAX_BUNDLE_COMPRESSED_BYTES, MAX_BUNDLE_DECOMPRESSED_BYTES } from '../constants.js';\nimport { assertOpaInstalled } from './assertOpaInstalled.js';\nimport { runOPACapture } from './runOpa.js';\n\n/**\n * Returns whether a relative path is a publishable Rego policy file.\n *\n * OPA test files (`*_test.rego`) are excluded because they are for local\n * validation only and are not part of the upload contract.\n *\n * @param relativePath - Path relative to the bundle directory\n * @returns Whether the file should be included in the upload archive\n */\nfunction isPublishableRegoFile(relativePath: string): boolean {\n return relativePath.endsWith('.rego') && !relativePath.endsWith('_test.rego');\n}\n\n/** Shape of the OPA bundle `manifest.json` as accepted by the Policy Engine. */\ninterface PolicyBundleManifest {\n /** Roots of the bundle, e.g. `[\"policy_engine\"]` or `[\"policy_engine/transcend\"]` */\n roots: string[];\n}\n\n/**\n * Reads and validates `manifest.json` from a policy bundle directory.\n *\n * The Policy Engine requires `manifest.json` to declare `roots` as an array of\n * strings. OPA's own tooling does not always enforce this against the Rego\n * packages on upload, so we validate the shape client-side to surface a clear,\n * actionable error instead of an opaque server `400` or a decide-time\n * fail-closed footgun.\n *\n * @param dir - Absolute path to the policy bundle directory\n * @returns The parsed manifest\n */\nfunction readPolicyBundleManifest(dir: string): PolicyBundleManifest {\n const manifestPath = path.join(dir, 'manifest.json');\n if (!fs.existsSync(manifestPath)) {\n throw new Error('Policy bundle directory must contain a manifest.json file.');\n }\n\n const raw = fs.readFileSync(manifestPath, 'utf8');\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n throw new Error(\n `manifest.json is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\n\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('manifest.json must contain a JSON object.');\n }\n\n const roots = (parsed as { roots?: unknown }).roots;\n if (!Array.isArray(roots) || roots.length === 0) {\n throw new Error(\n 'manifest.json must declare \"roots\" as a non-empty array of strings (e.g. {\"roots\":[\"policy_engine\"]}).',\n );\n }\n\n if (!roots.every((root) => typeof root === 'string' && root.length > 0)) {\n throw new Error('manifest.json \"roots\" must be an array of non-empty strings.');\n }\n\n return { roots };\n}\n\n/** Result of collecting publishable entries from a policy bundle directory. */\ninterface PolicyBundleArchiveContents {\n /** Relative paths to include in the upload tarball (manifest first, then rego) */\n entries: string[];\n /** Parsed manifest */\n manifest: PolicyBundleManifest;\n}\n\n/**\n * Collects `manifest.json` and publishable `.rego` files from a policy directory.\n *\n * @param dir - Absolute path to the policy bundle directory\n * @returns Archive entries and the parsed manifest\n */\nfunction collectPolicyBundleArchiveEntries(dir: string): PolicyBundleArchiveContents {\n const manifest = readPolicyBundleManifest(dir);\n\n const regoFiles = fg\n .sync('**/*.rego', {\n cwd: dir,\n onlyFiles: true,\n dot: false,\n })\n .filter(isPublishableRegoFile);\n\n if (regoFiles.length === 0) {\n throw new Error('Policy bundle directory must contain at least one .rego policy file.');\n }\n\n return { entries: ['manifest.json', ...regoFiles.sort()], manifest };\n}\n\n/** Matches a Rego `package <path>` declaration. */\nconst PACKAGE_DECLARATION_PATTERN = /^\\s*package\\s+([A-Za-z_][\\w.]*)/m;\n\n/**\n * Normalizes an OPA manifest root to a dotted package prefix.\n *\n * Roots use `/` as the path separator (e.g. `policy_engine/transcend`); Rego\n * package paths use `.` (e.g. `policy_engine.transcend`).\n *\n * @param root - A manifest root string\n * @returns The root in dotted form\n */\nfunction normalizeRootToPackagePrefix(root: string): string {\n return root.replace(/\\//g, '.');\n}\n\n/**\n * Reads the Rego package path declared in a `.rego` file.\n *\n * @param filePath - Absolute path to the `.rego` file\n * @returns The dotted package path, or `undefined` if no `package` declaration\n */\nfunction readRegoPackagePath(filePath: string): string | undefined {\n const contents = fs.readFileSync(filePath, 'utf8');\n const match = PACKAGE_DECLARATION_PATTERN.exec(contents);\n return match?.[1];\n}\n\n/**\n * Verifies that every publishable `.rego` package is covered by a manifest root.\n *\n * A bundle whose `roots` do not cover its Rego packages will upload cleanly but\n * fail-closed at decide time — the customer only discovers the mismatch via\n * denied decisions. This surfaces the mismatch at upload with a clear message.\n *\n * @param dir - Absolute path to the policy bundle directory\n * @param regoFiles - Relative paths to publishable `.rego` files\n * @param roots - Manifest roots\n */\nfunction assertRootsCoverPackages(dir: string, regoFiles: string[], roots: string[]): void {\n const rootPrefixes = roots.map(normalizeRootToPackagePrefix);\n\n const uncovered: string[] = [];\n for (const relativeRego of regoFiles) {\n const pkg = readRegoPackagePath(path.join(dir, relativeRego));\n if (!pkg) {\n continue;\n }\n const covered = rootPrefixes.some((prefix) => pkg === prefix || pkg.startsWith(`${prefix}.`));\n if (!covered) {\n uncovered.push(\n ` - ${relativeRego} (package ${pkg}) is not covered by roots [${roots.join(', ')}]`,\n );\n }\n }\n\n if (uncovered.length > 0) {\n throw new Error(\n [\n 'manifest.json \"roots\" do not cover all Rego packages in the bundle; ' +\n 'uncovered packages will fail-closed at decide time. Either broaden \"roots\" or move the policy under a covered package:',\n ...uncovered,\n ].join('\\n'),\n );\n }\n}\n\n/**\n * Verifies that a policy directory compiles end-to-end with `opa build`.\n *\n * The compiled output is discarded — the server receives the `manifest.json` +\n * `.rego` archive produced by {@link buildOpaBundleTarball}, not the OPA bundle\n * — but a successful build guarantees the policies compile and link, surfacing\n * errors (syntax, missing imports, undefined references, etc.) before upload.\n *\n * @param dir - Absolute path to the policy bundle directory\n */\nasync function assertBundleCompiles(dir: string): Promise<void> {\n const buildOutputPath = path.join(\n os.tmpdir(),\n `transcend-policy-bundle-build-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`,\n );\n try {\n // Run with `cwd` set to the bundle directory and pass `.` so `opa build`\n // resolves the bundle root correctly. `*_test.rego` files are local-only.\n const { code, stderr } = await runOPACapture(\n ['build', '--v0-compatible', '--ignore', '*_test.rego', '-o', buildOutputPath, '.'],\n { cwd: dir },\n );\n if (code !== 0) {\n throw new Error(stderr.trim() || `opa build failed with exit code ${code}`);\n }\n } finally {\n if (fs.existsSync(buildOutputPath)) {\n fs.unlinkSync(buildOutputPath);\n }\n }\n}\n\n/**\n * Formats a byte count as a human-readable size with binary units.\n *\n * @param bytes - Number of bytes\n * @returns Human-readable size, e.g. `14 MiB` or `4 KiB`\n */\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) {\n return `${bytes} B`;\n }\n const kib = bytes / 1024;\n if (kib < 1024) {\n return `${kib % 1 === 0 ? kib.toFixed(0) : kib.toFixed(1)} KiB`;\n }\n const mib = kib / 1024;\n return `${mib % 1 === 0 ? mib.toFixed(0) : mib.toFixed(1)} MiB`;\n}\n\n/**\n * Builds a gzip-compressed policy bundle tarball for upload to Transcend.\n *\n * The Policy Engine API expects a plain archive containing `manifest.json` and\n * one or more `.rego` files. This differs from `opa build` output, which embeds\n * `.manifest`, `data.json`, and other OPA bundle metadata that the server\n * rejects. Before packaging, the manifest is validated (shape + root coverage)\n * and the bundle is validated with `opa check` (strict Rego linting) and\n * `opa build` (full compilation) so failures surface client-side rather than\n * after upload.\n *\n * @param dir - Directory containing `manifest.json` and `.rego` policy files\n * @returns Absolute path to the generated `.tar.gz` bundle\n */\nexport async function buildOpaBundleTarball(dir: string): Promise<string> {\n assertOpaInstalled();\n\n const resolvedDir = path.resolve(dir);\n if (!fs.existsSync(resolvedDir) || !fs.statSync(resolvedDir).isDirectory()) {\n throw new Error(`Policy directory does not exist or is not a directory: ${resolvedDir}`);\n }\n\n // Validate the manifest shape and that roots cover every Rego package before\n // invoking OPA, so invalid manifests surface a clear error instead of an\n // opaque `opa build failed with exit code 1`.\n const { entries: archiveEntries, manifest } = collectPolicyBundleArchiveEntries(resolvedDir);\n const regoFiles = archiveEntries.filter((entry) => entry !== 'manifest.json');\n assertRootsCoverPackages(resolvedDir, regoFiles, manifest.roots);\n\n // Match the Rego v1 validation the Policy Engine API runs on upload.\n const { code: checkCode, stderr: checkStderr } = await runOPACapture([\n 'check',\n '--strict',\n '--v0-compatible',\n resolvedDir,\n ]);\n if (checkCode !== 0) {\n throw new Error(checkStderr.trim() || `opa check failed with exit code ${checkCode}`);\n }\n\n // Ensure the bundle compiles end-to-end before packaging for upload.\n await assertBundleCompiles(resolvedDir);\n\n const outputPath = path.join(\n os.tmpdir(),\n `transcend-policy-bundle-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`,\n );\n\n const tarResult = spawnSync('tar', ['-czf', outputPath, '-C', resolvedDir, ...archiveEntries], {\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n encoding: 'utf8',\n });\n if (tarResult.status !== 0) {\n throw new Error(\n `Failed to create policy bundle archive: ${tarResult.stderr.trim() || 'tar failed'}`,\n );\n }\n\n const compressedBytes = fs.readFileSync(outputPath);\n if (compressedBytes.byteLength > MAX_BUNDLE_COMPRESSED_BYTES) {\n fs.unlinkSync(outputPath);\n throw new Error(\n `Policy bundle exceeds the ${formatBytes(MAX_BUNDLE_COMPRESSED_BYTES)} compressed upload limit ` +\n `(bundle is ${formatBytes(compressedBytes.byteLength)}). ` +\n `The server also rejects decompressed bundles larger than ${formatBytes(MAX_BUNDLE_DECOMPRESSED_BYTES)}.`,\n );\n }\n\n const decompressedBytes = gunzipSync(compressedBytes);\n if (decompressedBytes.byteLength > MAX_BUNDLE_DECOMPRESSED_BYTES) {\n fs.unlinkSync(outputPath);\n throw new Error(\n `Policy bundle exceeds the ${formatBytes(MAX_BUNDLE_DECOMPRESSED_BYTES)} decompressed upload limit ` +\n `(bundle is ${formatBytes(decompressedBytes.byteLength)} decompressed).`,\n );\n }\n\n return outputPath;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\n/** Fields for building a policy bundle upload form. */\nexport interface BuildPolicyBundleFormDataOptions {\n /** Absolute path to the bundle tarball */\n bundlePath: string;\n /** Version label */\n version: string;\n /** Optional description */\n description?: string;\n /** Bundle name (only for create) */\n bundleName?: string;\n}\n\n/**\n * Builds multipart form data for a policy bundle upload.\n *\n * @param options - Upload fields\n * @returns FormData ready for POST\n */\nexport function buildPolicyBundleFormData(options: BuildPolicyBundleFormDataOptions): FormData {\n const bundleBytes = fs.readFileSync(options.bundlePath);\n const form = new FormData();\n form.append(\n 'bundle',\n new Blob([bundleBytes], { type: 'application/gzip' }),\n path.basename(options.bundlePath),\n );\n form.append('version', options.version);\n if (options.description) {\n form.append('description', options.description);\n }\n if (options.bundleName) {\n form.append('bundleName', options.bundleName);\n }\n return form;\n}\n","/**\n * Formats a date as `yyyy-mm-dd-hh-mm-ss` in UTC.\n *\n * @param date - Date to format\n * @returns Timestamp label\n */\nfunction formatPolicyVersionTimestamp(date: Date): string {\n return date.toISOString().slice(0, 19).replace(/[T:]/g, '-');\n}\n\n/**\n * Returns a default version label from the bundle name and current UTC timestamp.\n *\n * @param bundleName - Tenant-unique policy bundle name\n * @param now - Current time (for testing)\n * @returns Version label in `{bundleName}-yyyy-mm-dd-hh-mm-ss` form\n */\nexport function defaultPolicyVersionLabel(bundleName: string, now: Date = new Date()): string {\n return `${bundleName}-${formatPolicyVersionTimestamp(now)}`;\n}\n","import path from 'node:path';\n\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { buildExampleCommand } from '../../../lib/docgen/buildExamples.js';\nimport { inquirerConfirmBoolean } from '../../../lib/helpers/inquirer.js';\nimport type { ActivateCommandFlags } from '../activate/impl.js';\nimport {\n buildPolicyBundleFormData,\n buildPolicyEngineClient,\n buildOpaBundleTarball,\n defaultPolicyVersionLabel,\n formatPolicyBundleVersionSummary,\n policyEngineRequest,\n printResult,\n resolveBundleIdByName,\n setPolicyEngineCliDebug,\n} from '../helpers/index.js';\nimport type { CreatePolicyBundleResponse, CreatePolicyBundleVersionResponse } from '../types.js';\n\n/** CLI flags for `transcend policy publish`. */\nexport interface PublishCommandFlags {\n /** Directory containing Rego policy files */\n dir: string;\n /** Tenant-unique bundle name */\n 'bundle-name': string;\n /** Transcend API key */\n auth: string;\n /** Transcend API URL */\n 'transcend-url': string;\n /** Version label (defaults to `{bundleName}-yyyy-mm-dd-hh-mm-ss`) */\n version?: string;\n /** Optional version description */\n description?: string;\n /** Print raw JSON response */\n json: boolean;\n /** Skip the \"create new bundle\" confirmation */\n yes: boolean;\n /** Include technical error details when a command fails */\n debug?: boolean;\n}\n\n/**\n * Build and upload a new immutable policy bundle version.\n *\n * @param this - CLI context\n * @param flags - Command flags\n */\nexport async function publish(\n this: LocalContext,\n {\n dir,\n 'bundle-name': bundleName,\n auth,\n 'transcend-url': transcendUrl,\n version,\n description,\n json,\n yes,\n debug = false,\n }: PublishCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n setPolicyEngineCliDebug(debug);\n\n const resolvedDir = path.resolve(dir);\n const versionLabel = version ?? defaultPolicyVersionLabel(bundleName);\n const client = buildPolicyEngineClient(transcendUrl, auth);\n\n let bundlePath: string | undefined;\n try {\n this.logger.info(colors.green(`Building policy bundle from ${resolvedDir}...`));\n bundlePath = await buildOpaBundleTarball(resolvedDir);\n\n const existingBundleId = await resolveBundleIdByName(client, bundleName);\n\n let responseBody: CreatePolicyBundleResponse | CreatePolicyBundleVersionResponse;\n\n if (existingBundleId) {\n this.logger.info(colors.green(`Uploading new version for bundle \"${bundleName}\"...`));\n const form = buildPolicyBundleFormData({\n bundlePath,\n version: versionLabel,\n description,\n });\n responseBody = await policyEngineRequest(\n client\n .post(`v1/policy-engine/policy-bundles/${existingBundleId}/versions`, { body: form })\n .json<CreatePolicyBundleVersionResponse>(),\n );\n } else {\n if (!this.process.stdin.isTTY && !yes) {\n this.logger.error(\n colors.red(\n 'Cannot create a new bundle in a non-interactive environment; pass --yes to confirm.',\n ),\n );\n this.process.exit(1);\n return;\n }\n\n if (!yes) {\n this.logger.warn(\n colors.yellow(`No policy bundle named \"${bundleName}\" exists for this organization.`),\n );\n const shouldCreate = await inquirerConfirmBoolean({\n message: `No policy bundle named \"${bundleName}\" exists. Create a new bundle and upload its first version?`,\n });\n if (!shouldCreate) {\n this.logger.info(colors.yellow('Publish cancelled.'));\n return;\n }\n }\n\n this.logger.info(\n colors.green(`Creating bundle \"${bundleName}\" and uploading first version...`),\n );\n const createForm = buildPolicyBundleFormData({\n bundlePath,\n version: versionLabel,\n description,\n bundleName,\n });\n responseBody = await policyEngineRequest(\n client\n .post('v1/policy-engine/policy-bundles', {\n body: createForm,\n })\n .json<CreatePolicyBundleResponse>(),\n );\n }\n\n printResult(this.process.stdout, {\n json,\n data: responseBody,\n renderTable: () => formatPolicyBundleVersionSummary(responseBody.version),\n });\n\n this.logger.info(colors.green('Policy bundle version uploaded successfully.'));\n\n const activateCommand = buildExampleCommand<ActivateCommandFlags>(['policy', 'activate'], {\n version: responseBody.version.version,\n 'bundle-name': bundleName,\n });\n this.logger.info(\n colors.yellow(\n `Publishing a policy does not activate it. To activate this version, run:\\n ${activateCommand}`,\n ),\n );\n } finally {\n if (bundlePath && this.fs.existsSync(bundlePath)) {\n this.fs.unlinkSync(bundlePath);\n }\n }\n}\n"],"mappings":"orBAqBA,SAAS,EAAsB,EAA+B,CAC5D,OAAO,EAAa,SAAS,QAAQ,EAAI,CAAC,EAAa,SAAS,aAAa,CAqB/E,SAAS,EAAyB,EAAmC,CACnE,IAAM,EAAe,EAAK,KAAK,EAAK,gBAAgB,CACpD,GAAI,CAAC,EAAG,WAAW,EAAa,CAC9B,MAAU,MAAM,6DAA6D,CAG/E,IAAM,EAAM,EAAG,aAAa,EAAc,OAAO,CAC7C,EACJ,GAAI,CACF,EAAS,KAAK,MAAM,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CACD,IAAM,EAAa,EAA0B,CAC3C,aACA,QAAS,EACT,cACA,aACD,CAAC,CACF,EAAe,MAAM,EACnB,EACG,KAAK,kCAAmC,CACvC,KAAM,EACP,CAAC,CACD,MAAkC,CACtC,CAGH,EAAY,KAAK,QAAQ,OAAQ,CAC/B,OACA,KAAM,EACN,gBAAmB,EAAiC,EAAa,QAAQ,CAC1E,CAAC,CAEF,KAAK,OAAO,KAAK,EAAO,MAAM,+CAA+C,CAAC,CAE9E,IAAM,EAAkB,EAA0C,CAAC,SAAU,WAAW,CAAE,CACxF,QAAS,EAAa,QAAQ,QAC9B,cAAe,EAChB,CAAC,CACF,KAAK,OAAO,KACV,EAAO,OACL,+EAA+E,IAChF,CACF,QACO,CACJ,GAAc,KAAK,GAAG,WAAW,EAAW,EAC9C,KAAK,GAAG,WAAW,EAAW"}
|
|
1
|
+
{"version":3,"file":"impl-D23kJPAQ2.mjs","names":["fg"],"sources":["../src/commands/policy/helpers/buildOpaBundleTarball.ts","../src/commands/policy/helpers/buildPolicyBundleFormData.ts","../src/commands/policy/helpers/defaultPolicyVersionLabel.ts","../src/commands/policy/publish/impl.ts"],"sourcesContent":["import { spawnSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { gunzipSync } from 'node:zlib';\n\nimport fg from 'fast-glob';\n\nimport { MAX_BUNDLE_COMPRESSED_BYTES, MAX_BUNDLE_DECOMPRESSED_BYTES } from '../constants.js';\nimport { assertOpaInstalled } from './assertOpaInstalled.js';\nimport { runOPACapture } from './runOpa.js';\n\n/**\n * Returns whether a relative path is a publishable Rego policy file.\n *\n * OPA test files (`*_test.rego`) are excluded because they are for local\n * validation only and are not part of the upload contract.\n *\n * @param relativePath - Path relative to the bundle directory\n * @returns Whether the file should be included in the upload archive\n */\nfunction isPublishableRegoFile(relativePath: string): boolean {\n return relativePath.endsWith('.rego') && !relativePath.endsWith('_test.rego');\n}\n\n/** Shape of the OPA bundle `manifest.json` as accepted by the Policy Engine. */\ninterface PolicyBundleManifest {\n /** Roots of the bundle, e.g. `[\"policy_engine\"]` or `[\"policy_engine/transcend\"]` */\n roots: string[];\n}\n\n/**\n * Reads and validates `manifest.json` from a policy bundle directory.\n *\n * The Policy Engine requires `manifest.json` to declare `roots` as an array of\n * strings. OPA's own tooling does not always enforce this against the Rego\n * packages on upload, so we validate the shape client-side to surface a clear,\n * actionable error instead of an opaque server `400` or a decide-time\n * fail-closed footgun.\n *\n * @param dir - Absolute path to the policy bundle directory\n * @returns The parsed manifest\n */\nfunction readPolicyBundleManifest(dir: string): PolicyBundleManifest {\n const manifestPath = path.join(dir, 'manifest.json');\n if (!fs.existsSync(manifestPath)) {\n throw new Error('Policy bundle directory must contain a manifest.json file.');\n }\n\n const raw = fs.readFileSync(manifestPath, 'utf8');\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n throw new Error(\n `manifest.json is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\n\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('manifest.json must contain a JSON object.');\n }\n\n const roots = (parsed as { roots?: unknown }).roots;\n if (!Array.isArray(roots) || roots.length === 0) {\n throw new Error(\n 'manifest.json must declare \"roots\" as a non-empty array of strings (e.g. {\"roots\":[\"policy_engine\"]}).',\n );\n }\n\n if (!roots.every((root) => typeof root === 'string' && root.length > 0)) {\n throw new Error('manifest.json \"roots\" must be an array of non-empty strings.');\n }\n\n return { roots };\n}\n\n/** Result of collecting publishable entries from a policy bundle directory. */\ninterface PolicyBundleArchiveContents {\n /** Relative paths to include in the upload tarball (manifest first, then rego) */\n entries: string[];\n /** Parsed manifest */\n manifest: PolicyBundleManifest;\n}\n\n/**\n * Collects `manifest.json` and publishable `.rego` files from a policy directory.\n *\n * @param dir - Absolute path to the policy bundle directory\n * @returns Archive entries and the parsed manifest\n */\nfunction collectPolicyBundleArchiveEntries(dir: string): PolicyBundleArchiveContents {\n const manifest = readPolicyBundleManifest(dir);\n\n const regoFiles = fg\n .sync('**/*.rego', {\n cwd: dir,\n onlyFiles: true,\n dot: false,\n })\n .filter(isPublishableRegoFile);\n\n if (regoFiles.length === 0) {\n throw new Error('Policy bundle directory must contain at least one .rego policy file.');\n }\n\n return { entries: ['manifest.json', ...regoFiles.sort()], manifest };\n}\n\n/** Matches a Rego `package <path>` declaration. */\nconst PACKAGE_DECLARATION_PATTERN = /^\\s*package\\s+([A-Za-z_][\\w.]*)/m;\n\n/**\n * Normalizes an OPA manifest root to a dotted package prefix.\n *\n * Roots use `/` as the path separator (e.g. `policy_engine/transcend`); Rego\n * package paths use `.` (e.g. `policy_engine.transcend`).\n *\n * @param root - A manifest root string\n * @returns The root in dotted form\n */\nfunction normalizeRootToPackagePrefix(root: string): string {\n return root.replace(/\\//g, '.');\n}\n\n/**\n * Reads the Rego package path declared in a `.rego` file.\n *\n * @param filePath - Absolute path to the `.rego` file\n * @returns The dotted package path, or `undefined` if no `package` declaration\n */\nfunction readRegoPackagePath(filePath: string): string | undefined {\n const contents = fs.readFileSync(filePath, 'utf8');\n const match = PACKAGE_DECLARATION_PATTERN.exec(contents);\n return match?.[1];\n}\n\n/**\n * Verifies that every publishable `.rego` package is covered by a manifest root.\n *\n * A bundle whose `roots` do not cover its Rego packages will upload cleanly but\n * fail-closed at decide time — the customer only discovers the mismatch via\n * denied decisions. This surfaces the mismatch at upload with a clear message.\n *\n * @param dir - Absolute path to the policy bundle directory\n * @param regoFiles - Relative paths to publishable `.rego` files\n * @param roots - Manifest roots\n */\nfunction assertRootsCoverPackages(dir: string, regoFiles: string[], roots: string[]): void {\n const rootPrefixes = roots.map(normalizeRootToPackagePrefix);\n\n const uncovered: string[] = [];\n for (const relativeRego of regoFiles) {\n const pkg = readRegoPackagePath(path.join(dir, relativeRego));\n if (!pkg) {\n continue;\n }\n const covered = rootPrefixes.some((prefix) => pkg === prefix || pkg.startsWith(`${prefix}.`));\n if (!covered) {\n uncovered.push(\n ` - ${relativeRego} (package ${pkg}) is not covered by roots [${roots.join(', ')}]`,\n );\n }\n }\n\n if (uncovered.length > 0) {\n throw new Error(\n [\n 'manifest.json \"roots\" do not cover all Rego packages in the bundle; ' +\n 'uncovered packages will fail-closed at decide time. Either broaden \"roots\" or move the policy under a covered package:',\n ...uncovered,\n ].join('\\n'),\n );\n }\n}\n\n/**\n * Verifies that a policy directory compiles end-to-end with `opa build`.\n *\n * The compiled output is discarded — the server receives the `manifest.json` +\n * `.rego` archive produced by {@link buildOpaBundleTarball}, not the OPA bundle\n * — but a successful build guarantees the policies compile and link, surfacing\n * errors (syntax, missing imports, undefined references, etc.) before upload.\n *\n * @param dir - Absolute path to the policy bundle directory\n */\nasync function assertBundleCompiles(dir: string): Promise<void> {\n const buildOutputPath = path.join(\n os.tmpdir(),\n `transcend-policy-bundle-build-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`,\n );\n try {\n // Run with `cwd` set to the bundle directory and pass `.` so `opa build`\n // resolves the bundle root correctly. `*_test.rego` files are local-only.\n const { code, stderr } = await runOPACapture(\n ['build', '--v0-compatible', '--ignore', '*_test.rego', '-o', buildOutputPath, '.'],\n { cwd: dir },\n );\n if (code !== 0) {\n throw new Error(stderr.trim() || `opa build failed with exit code ${code}`);\n }\n } finally {\n if (fs.existsSync(buildOutputPath)) {\n fs.unlinkSync(buildOutputPath);\n }\n }\n}\n\n/**\n * Formats a byte count as a human-readable size with binary units.\n *\n * @param bytes - Number of bytes\n * @returns Human-readable size, e.g. `14 MiB` or `4 KiB`\n */\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) {\n return `${bytes} B`;\n }\n const kib = bytes / 1024;\n if (kib < 1024) {\n return `${kib % 1 === 0 ? kib.toFixed(0) : kib.toFixed(1)} KiB`;\n }\n const mib = kib / 1024;\n return `${mib % 1 === 0 ? mib.toFixed(0) : mib.toFixed(1)} MiB`;\n}\n\n/**\n * Builds a gzip-compressed policy bundle tarball for upload to Transcend.\n *\n * The Policy Engine API expects a plain archive containing `manifest.json` and\n * one or more `.rego` files. This differs from `opa build` output, which embeds\n * `.manifest`, `data.json`, and other OPA bundle metadata that the server\n * rejects. Before packaging, the manifest is validated (shape + root coverage)\n * and the bundle is validated with `opa check` (strict Rego linting) and\n * `opa build` (full compilation) so failures surface client-side rather than\n * after upload.\n *\n * @param dir - Directory containing `manifest.json` and `.rego` policy files\n * @returns Absolute path to the generated `.tar.gz` bundle\n */\nexport async function buildOpaBundleTarball(dir: string): Promise<string> {\n assertOpaInstalled();\n\n const resolvedDir = path.resolve(dir);\n if (!fs.existsSync(resolvedDir) || !fs.statSync(resolvedDir).isDirectory()) {\n throw new Error(`Policy directory does not exist or is not a directory: ${resolvedDir}`);\n }\n\n // Validate the manifest shape and that roots cover every Rego package before\n // invoking OPA, so invalid manifests surface a clear error instead of an\n // opaque `opa build failed with exit code 1`.\n const { entries: archiveEntries, manifest } = collectPolicyBundleArchiveEntries(resolvedDir);\n const regoFiles = archiveEntries.filter((entry) => entry !== 'manifest.json');\n assertRootsCoverPackages(resolvedDir, regoFiles, manifest.roots);\n\n // Match the Rego v1 validation the Policy Engine API runs on upload.\n const { code: checkCode, stderr: checkStderr } = await runOPACapture([\n 'check',\n '--strict',\n '--v0-compatible',\n resolvedDir,\n ]);\n if (checkCode !== 0) {\n throw new Error(checkStderr.trim() || `opa check failed with exit code ${checkCode}`);\n }\n\n // Ensure the bundle compiles end-to-end before packaging for upload.\n await assertBundleCompiles(resolvedDir);\n\n const outputPath = path.join(\n os.tmpdir(),\n `transcend-policy-bundle-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`,\n );\n\n const tarResult = spawnSync('tar', ['-czf', outputPath, '-C', resolvedDir, ...archiveEntries], {\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n encoding: 'utf8',\n });\n if (tarResult.status !== 0) {\n throw new Error(\n `Failed to create policy bundle archive: ${tarResult.stderr.trim() || 'tar failed'}`,\n );\n }\n\n const compressedBytes = fs.readFileSync(outputPath);\n if (compressedBytes.byteLength > MAX_BUNDLE_COMPRESSED_BYTES) {\n fs.unlinkSync(outputPath);\n throw new Error(\n `Policy bundle exceeds the ${formatBytes(MAX_BUNDLE_COMPRESSED_BYTES)} compressed upload limit ` +\n `(bundle is ${formatBytes(compressedBytes.byteLength)}). ` +\n `The server also rejects decompressed bundles larger than ${formatBytes(MAX_BUNDLE_DECOMPRESSED_BYTES)}.`,\n );\n }\n\n const decompressedBytes = gunzipSync(compressedBytes);\n if (decompressedBytes.byteLength > MAX_BUNDLE_DECOMPRESSED_BYTES) {\n fs.unlinkSync(outputPath);\n throw new Error(\n `Policy bundle exceeds the ${formatBytes(MAX_BUNDLE_DECOMPRESSED_BYTES)} decompressed upload limit ` +\n `(bundle is ${formatBytes(decompressedBytes.byteLength)} decompressed).`,\n );\n }\n\n return outputPath;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\n/** Fields for building a policy bundle upload form. */\nexport interface BuildPolicyBundleFormDataOptions {\n /** Absolute path to the bundle tarball */\n bundlePath: string;\n /** Version label */\n version: string;\n /** Optional description */\n description?: string;\n /** Bundle name (only for create) */\n bundleName?: string;\n}\n\n/**\n * Builds multipart form data for a policy bundle upload.\n *\n * @param options - Upload fields\n * @returns FormData ready for POST\n */\nexport function buildPolicyBundleFormData(options: BuildPolicyBundleFormDataOptions): FormData {\n const bundleBytes = fs.readFileSync(options.bundlePath);\n const form = new FormData();\n form.append(\n 'bundle',\n new Blob([bundleBytes], { type: 'application/gzip' }),\n path.basename(options.bundlePath),\n );\n form.append('version', options.version);\n if (options.description) {\n form.append('description', options.description);\n }\n if (options.bundleName) {\n form.append('bundleName', options.bundleName);\n }\n return form;\n}\n","/**\n * Formats a date as `yyyy-mm-dd-hh-mm-ss` in UTC.\n *\n * @param date - Date to format\n * @returns Timestamp label\n */\nfunction formatPolicyVersionTimestamp(date: Date): string {\n return date.toISOString().slice(0, 19).replace(/[T:]/g, '-');\n}\n\n/**\n * Returns a default version label from the bundle name and current UTC timestamp.\n *\n * @param bundleName - Tenant-unique policy bundle name\n * @param now - Current time (for testing)\n * @returns Version label in `{bundleName}-yyyy-mm-dd-hh-mm-ss` form\n */\nexport function defaultPolicyVersionLabel(bundleName: string, now: Date = new Date()): string {\n return `${bundleName}-${formatPolicyVersionTimestamp(now)}`;\n}\n","import path from 'node:path';\n\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { buildExampleCommand } from '../../../lib/docgen/buildExamples.js';\nimport { inquirerConfirmBoolean } from '../../../lib/helpers/inquirer.js';\nimport type { ActivateCommandFlags } from '../activate/impl.js';\nimport {\n buildPolicyBundleFormData,\n buildPolicyEngineClient,\n buildOpaBundleTarball,\n defaultPolicyVersionLabel,\n formatPolicyBundleVersionSummary,\n policyEngineRequest,\n printResult,\n resolveBundleIdByName,\n setPolicyEngineCliDebug,\n} from '../helpers/index.js';\nimport type { CreatePolicyBundleResponse, CreatePolicyBundleVersionResponse } from '../types.js';\n\n/** CLI flags for `transcend policy publish`. */\nexport interface PublishCommandFlags {\n /** Directory containing Rego policy files */\n dir: string;\n /** Tenant-unique bundle name */\n 'bundle-name': string;\n /** Transcend API key */\n auth: string;\n /** Transcend API URL */\n 'transcend-url': string;\n /** Version label (defaults to `{bundleName}-yyyy-mm-dd-hh-mm-ss`) */\n version?: string;\n /** Optional version description */\n description?: string;\n /** Print raw JSON response */\n json: boolean;\n /** Skip the \"create new bundle\" confirmation */\n yes: boolean;\n /** Include technical error details when a command fails */\n debug?: boolean;\n}\n\n/**\n * Build and upload a new immutable policy bundle version.\n *\n * @param this - CLI context\n * @param flags - Command flags\n */\nexport async function publish(\n this: LocalContext,\n {\n dir,\n 'bundle-name': bundleName,\n auth,\n 'transcend-url': transcendUrl,\n version,\n description,\n json,\n yes,\n debug = false,\n }: PublishCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n setPolicyEngineCliDebug(debug);\n\n const resolvedDir = path.resolve(dir);\n const versionLabel = version ?? defaultPolicyVersionLabel(bundleName);\n const client = buildPolicyEngineClient(transcendUrl, auth);\n\n let bundlePath: string | undefined;\n try {\n this.logger.info(colors.green(`Building policy bundle from ${resolvedDir}...`));\n bundlePath = await buildOpaBundleTarball(resolvedDir);\n\n const existingBundleId = await resolveBundleIdByName(client, bundleName);\n\n let responseBody: CreatePolicyBundleResponse | CreatePolicyBundleVersionResponse;\n\n if (existingBundleId) {\n this.logger.info(colors.green(`Uploading new version for bundle \"${bundleName}\"...`));\n const form = buildPolicyBundleFormData({\n bundlePath,\n version: versionLabel,\n description,\n });\n responseBody = await policyEngineRequest(\n client\n .post(`v1/policy-engine/policy-bundles/${existingBundleId}/versions`, { body: form })\n .json<CreatePolicyBundleVersionResponse>(),\n );\n } else {\n if (!this.process.stdin.isTTY && !yes) {\n this.logger.error(\n colors.red(\n 'Cannot create a new bundle in a non-interactive environment; pass --yes to confirm.',\n ),\n );\n this.process.exit(1);\n return;\n }\n\n if (!yes) {\n this.logger.warn(\n colors.yellow(`No policy bundle named \"${bundleName}\" exists for this organization.`),\n );\n const shouldCreate = await inquirerConfirmBoolean({\n message: `No policy bundle named \"${bundleName}\" exists. Create a new bundle and upload its first version?`,\n });\n if (!shouldCreate) {\n this.logger.info(colors.yellow('Publish cancelled.'));\n return;\n }\n }\n\n this.logger.info(\n colors.green(`Creating bundle \"${bundleName}\" and uploading first version...`),\n );\n const createForm = buildPolicyBundleFormData({\n bundlePath,\n version: versionLabel,\n description,\n bundleName,\n });\n responseBody = await policyEngineRequest(\n client\n .post('v1/policy-engine/policy-bundles', {\n body: createForm,\n })\n .json<CreatePolicyBundleResponse>(),\n );\n }\n\n printResult(this.process.stdout, {\n json,\n data: responseBody,\n renderTable: () => formatPolicyBundleVersionSummary(responseBody.version),\n });\n\n this.logger.info(colors.green('Policy bundle version uploaded successfully.'));\n\n const activateCommand = buildExampleCommand<ActivateCommandFlags>(['policy', 'activate'], {\n version: responseBody.version.version,\n 'bundle-name': bundleName,\n });\n this.logger.info(\n colors.yellow(\n `Publishing a policy does not activate it. To activate this version, run:\\n ${activateCommand}`,\n ),\n );\n } finally {\n if (bundlePath && this.fs.existsSync(bundlePath)) {\n this.fs.unlinkSync(bundlePath);\n }\n }\n}\n"],"mappings":"orBAqBA,SAAS,EAAsB,EAA+B,CAC5D,OAAO,EAAa,SAAS,QAAQ,EAAI,CAAC,EAAa,SAAS,aAAa,CAqB/E,SAAS,EAAyB,EAAmC,CACnE,IAAM,EAAe,EAAK,KAAK,EAAK,gBAAgB,CACpD,GAAI,CAAC,EAAG,WAAW,EAAa,CAC9B,MAAU,MAAM,6DAA6D,CAG/E,IAAM,EAAM,EAAG,aAAa,EAAc,OAAO,CAC7C,EACJ,GAAI,CACF,EAAS,KAAK,MAAM,EAAI,OACjB,EAAK,CACZ,MAAU,MACR,oCAAoC,aAAe,MAAQ,EAAI,QAAU,OAAO,EAAI,GACpF,CAAE,MAAO,EAAK,CACf,CAGH,GAAI,CAAC,GAAU,OAAO,GAAW,UAAY,MAAM,QAAQ,EAAO,CAChE,MAAU,MAAM,4CAA4C,CAG9D,IAAM,EAAS,EAA+B,MAC9C,GAAI,CAAC,MAAM,QAAQ,EAAM,EAAI,EAAM,SAAW,EAC5C,MAAU,MACR,yGACD,CAGH,GAAI,CAAC,EAAM,MAAO,GAAS,OAAO,GAAS,UAAY,EAAK,OAAS,EAAE,CACrE,MAAU,MAAM,+DAA+D,CAGjF,MAAO,CAAE,QAAO,CAiBlB,SAAS,EAAkC,EAA0C,CACnF,IAAM,EAAW,EAAyB,EAAI,CAExC,EAAYA,EACf,KAAK,YAAa,CACjB,IAAK,EACL,UAAW,GACX,IAAK,GACN,CAAC,CACD,OAAO,EAAsB,CAEhC,GAAI,EAAU,SAAW,EACvB,MAAU,MAAM,uEAAuE,CAGzF,MAAO,CAAE,QAAS,CAAC,gBAAiB,GAAG,EAAU,MAAM,CAAC,CAAE,WAAU,CAItE,MAAM,EAA8B,mCAWpC,SAAS,EAA6B,E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mCAAmC,EAAiB,WAAY,CAAE,KAAM,EAAM,CAAC,CACpF,MAAyC,CAC7C,KACI,CACL,GAAI,CAAC,KAAK,QAAQ,MAAM,OAAS,CAAC,EAAK,CACrC,KAAK,OAAO,MACV,EAAO,IACL,sFACD,CACF,CACD,KAAK,QAAQ,KAAK,EAAE,CACpB,OAGF,GAAI,CAAC,IACH,KAAK,OAAO,KACV,EAAO,OAAO,2BAA2B,EAAW,iCAAiC,CACtF,CAIG,CAAC,MAHsB,EAAuB,CAChD,QAAS,2BAA2B,EAAW,6DAChD,CAAC,EACiB,CACjB,KAAK,OAAO,KAAK,EAAO,OAAO,qBAAqB,CAAC,CACrD,OAIJ,KAAK,OAAO,KACV,EAAO,MAAM,oBAAoB,EAAW,kCAAkC,CAC/E,CACD,IAAM,EAAa,EAA0B,CAC3C,aACA,QAAS,EACT,cACA,aACD,CAAC,CACF,EAAe,MAAM,EACnB,EACG,KAAK,kCAAmC,CACvC,KAAM,EACP,CAAC,CACD,MAAkC,CACtC,CAGH,EAAY,KAAK,QAAQ,OAAQ,CAC/B,OACA,KAAM,EACN,gBAAmB,EAAiC,EAAa,QAAQ,CAC1E,CAAC,CAEF,KAAK,OAAO,KAAK,EAAO,MAAM,+CAA+C,CAAC,CAE9E,IAAM,EAAkB,EAA0C,CAAC,SAAU,WAAW,CAAE,CACxF,QAAS,EAAa,QAAQ,QAC9B,cAAe,EAChB,CAAC,CACF,KAAK,OAAO,KACV,EAAO,OACL,+EAA+E,IAChF,CACF,QACO,CACJ,GAAc,KAAK,GAAG,WAAW,EAAW,EAC9C,KAAK,GAAG,WAAW,EAAW"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./validateTranscendAuth-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{t as e}from"./validateTranscendAuth-CnHMn77m.mjs";import{t}from"./done-input-validation-Cjk7a3jX.mjs";import n from"colors";import{buildTranscendGraphQLClient as r,fetchAllCustomFunctions as i}from"@transcend-io/sdk";async function a({auth:a,transcendUrl:o}){t(this.process);let s=e(a,this);Array.isArray(s)&&(this.logger.error(n.red(`transcend custom-functions list does not support a list of API keys — pass a single API key.`)),this.process.exit(1));let c=await i(r(o,s),{logger:this.logger});if(c.length===0){this.logger.info(n.yellow(`No custom functions found in this organization.`));return}this.logger.info(n.magenta(`Found ${c.length} custom function(s):`)),c.forEach(e=>{let t=e.activeVersion?`active v${e.activeVersion.versionNumber}`:`no active version`,r=e.hasPendingDraft&&e.draftVersion?`, pending draft v${e.draftVersion.versionNumber}`:``;this.logger.info(` - ${n.green(e.name)} [${e.type}] (${e.lifecycleState.toLowerCase()}, ${t}${r}) `+n.dim(`id: ${e.id}`))})}export{a as list};
|
|
2
|
+
//# sourceMappingURL=impl-DF8RGVlT.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-DF8RGVlT.mjs","names":[],"sources":["../src/commands/custom-functions/list/impl.ts"],"sourcesContent":["import { buildTranscendGraphQLClient, fetchAllCustomFunctions } from '@transcend-io/sdk';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { validateTranscendAuth } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\n\nexport interface CustomFunctionsListCommandFlags {\n auth: string;\n transcendUrl: string;\n}\n\nexport async function list(\n this: LocalContext,\n { auth, transcendUrl }: CustomFunctionsListCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n const apiKeyOrList = validateTranscendAuth(auth, this);\n if (Array.isArray(apiKeyOrList)) {\n this.logger.error(\n colors.red(\n 'transcend custom-functions list does not support a list of API keys — pass a single API key.',\n ),\n );\n this.process.exit(1);\n }\n\n const client = buildTranscendGraphQLClient(transcendUrl, apiKeyOrList as string);\n const customFunctions = await fetchAllCustomFunctions(client, { logger: this.logger });\n\n if (customFunctions.length === 0) {\n this.logger.info(colors.yellow('No custom functions found in this organization.'));\n return;\n }\n\n this.logger.info(colors.magenta(`Found ${customFunctions.length} custom function(s):`));\n customFunctions.forEach((customFunction) => {\n const active = customFunction.activeVersion\n ? `active v${customFunction.activeVersion.versionNumber}`\n : 'no active version';\n const draft =\n customFunction.hasPendingDraft && customFunction.draftVersion\n ? `, pending draft v${customFunction.draftVersion.versionNumber}`\n : '';\n this.logger.info(\n ` - ${colors.green(customFunction.name)} [${customFunction.type}] ` +\n `(${customFunction.lifecycleState.toLowerCase()}, ${active}${draft}) ` +\n colors.dim(`id: ${customFunction.id}`),\n );\n });\n}\n"],"mappings":"gOAYA,eAAsB,EAEpB,CAAE,OAAM,gBACO,CACf,EAAoB,KAAK,QAAQ,CAEjC,IAAM,EAAe,EAAsB,EAAM,KAAK,CAClD,MAAM,QAAQ,EAAa,GAC7B,KAAK,OAAO,MACV,EAAO,IACL,+FACD,CACF,CACD,KAAK,QAAQ,KAAK,EAAE,EAItB,IAAM,EAAkB,MAAM,EADf,EAA4B,EAAc,EACG,CAAE,CAAE,OAAQ,KAAK,OAAQ,CAAC,CAEtF,GAAI,EAAgB,SAAW,EAAG,CAChC,KAAK,OAAO,KAAK,EAAO,OAAO,kDAAkD,CAAC,CAClF,OAGF,KAAK,OAAO,KAAK,EAAO,QAAQ,SAAS,EAAgB,OAAO,sBAAsB,CAAC,CACvF,EAAgB,QAAS,GAAmB,CAC1C,IAAM,EAAS,EAAe,cAC1B,WAAW,EAAe,cAAc,gBACxC,oBACE,EACJ,EAAe,iBAAmB,EAAe,aAC7C,oBAAoB,EAAe,aAAa,gBAChD,GACN,KAAK,OAAO,KACV,OAAO,EAAO,MAAM,EAAe,KAAK,CAAC,IAAI,EAAe,KAAK,KAC3D,EAAe,eAAe,aAAa,CAAC,IAAI,IAAS,EAAM,IACnE,EAAO,IAAI,OAAO,EAAe,KAAK,CACzC,EACD"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as e}from"./policyEngineCliError-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{r as e}from"./policyEngineCliError-DY8V-qkK.mjs";import{i as t,n,t as r}from"./printResult-esxW3HhT.mjs";import{t as i}from"./renderTable-DKTZbMjY.mjs";import{n as a}from"./resolveBundleIdByName-DuxWYrDF.mjs";import{t as o}from"./done-input-validation-Cjk7a3jX.mjs";import s from"colors";async function c({"bundle-name":c,auth:l,"transcend-url":u,limit:d,after:f,json:p,debug:m=!1}){o(this.process),e(m);let h=t(u,l),g=await a(h,c);if(!g)throw Error(`Policy bundle "${c}" was not found for this organization.`);this.logger.info(s.green(`Listing versions for bundle "${c}"...`));let _={limit:d};f&&(_.after=f);let v=await n(h.get(`v1/policy-engine/policy-bundles/${g}/versions`,{searchParams:_}).json());r(this.process.stdout,{json:p,data:v,renderTable:()=>{if(v.nodes.length===0)return f?`No more versions for bundle "${c}" (end of results).`:`No versions found for bundle "${c}".`;let e=i([`id`,`version`,`createdAt`,`activatedAt`,`deactivatedAt`],v.nodes.map(e=>[e.id,e.version,e.createdAt,e.activatedAt??`-`,e.deactivatedAt??`-`]));return v.pageInfo.endCursor&&(e+=`\n\nafter: ${v.pageInfo.endCursor}`),e}})}export{c as versions};
|
|
2
|
+
//# sourceMappingURL=impl-DHfYO9T52.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-DHfYO9T52.mjs","names":[],"sources":["../src/commands/policy/versions/impl.ts"],"sourcesContent":["import colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { EMPTY_CELL } from '../constants.js';\nimport {\n buildPolicyEngineClient,\n policyEngineRequest,\n printResult,\n renderTable,\n resolveBundleIdByName,\n setPolicyEngineCliDebug,\n} from '../helpers/index.js';\nimport type { PolicyBundleVersionListResponse } from '../types.js';\n\n/** CLI flags for `transcend policy versions`. */\nexport interface VersionsCommandFlags {\n /** Tenant-unique bundle name */\n 'bundle-name': string;\n /** Transcend API key */\n auth: string;\n /** Transcend API URL */\n 'transcend-url': string;\n /** Page size */\n limit: number;\n /** Cursor from a previous page's pageInfo.endCursor */\n after?: string;\n /** Print raw JSON response */\n json: boolean;\n /** Include technical error details when a command fails */\n debug?: boolean;\n}\n\n/**\n * List versions for a policy bundle.\n *\n * @param this - CLI context\n * @param flags - Command flags\n */\nexport async function versions(\n this: LocalContext,\n {\n 'bundle-name': bundleName,\n auth,\n 'transcend-url': transcendUrl,\n limit,\n after,\n json,\n debug = false,\n }: VersionsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n setPolicyEngineCliDebug(debug);\n\n const client = buildPolicyEngineClient(transcendUrl, auth);\n const bundleId = await resolveBundleIdByName(client, bundleName);\n\n if (!bundleId) {\n throw new Error(`Policy bundle \"${bundleName}\" was not found for this organization.`);\n }\n\n this.logger.info(colors.green(`Listing versions for bundle \"${bundleName}\"...`));\n\n const searchParams: Record<string, string | number> = { limit };\n if (after) {\n searchParams.after = after;\n }\n\n const body = await policyEngineRequest(\n client\n .get(`v1/policy-engine/policy-bundles/${bundleId}/versions`, {\n searchParams,\n })\n .json<PolicyBundleVersionListResponse>(),\n );\n\n printResult(this.process.stdout, {\n json,\n data: body,\n renderTable: () => {\n if (body.nodes.length === 0) {\n // Distinguish \"this page is empty because you paginated past the end\"\n // from \"the bundle genuinely has no versions\" — the latter is already\n // surfaced during version resolution upstream.\n return after\n ? `No more versions for bundle \"${bundleName}\" (end of results).`\n : `No versions found for bundle \"${bundleName}\".`;\n }\n\n const rows = body.nodes.map((version) => [\n version.id,\n version.version,\n version.createdAt,\n version.activatedAt ?? EMPTY_CELL,\n version.deactivatedAt ?? EMPTY_CELL,\n ]);\n\n let table = renderTable(['id', 'version', 'createdAt', 'activatedAt', 'deactivatedAt'], rows);\n if (body.pageInfo.endCursor) {\n table += `\\n\\nafter: ${body.pageInfo.endCursor}`;\n }\n return table;\n },\n });\n}\n"],"mappings":"uSAuCA,eAAsB,EAEpB,CACE,cAAe,EACf,OACA,gBAAiB,EACjB,QACA,QACA,OACA,QAAQ,IAEK,CACf,EAAoB,KAAK,QAAQ,CACjC,EAAwB,EAAM,CAE9B,IAAM,EAAS,EAAwB,EAAc,EAAK,CACpD,EAAW,MAAM,EAAsB,EAAQ,EAAW,CAEhE,GAAI,CAAC,EACH,MAAU,MAAM,kBAAkB,EAAW,wCAAwC,CAGvF,KAAK,OAAO,KAAK,EAAO,MAAM,gCAAgC,EAAW,MAAM,CAAC,CAEhF,IAAM,EAAgD,CAAE,QAAO,CAC3D,IACF,EAAa,MAAQ,GAGvB,IAAM,EAAO,MAAM,EACjB,EACG,IAAI,mCAAmC,EAAS,WAAY,CAC3D,eACD,CAAC,CACD,MAAuC,CAC3C,CAED,EAAY,KAAK,QAAQ,OAAQ,CAC/B,OACA,KAAM,EACN,gBAAmB,CACjB,GAAI,EAAK,MAAM,SAAW,EAIxB,OAAO,EACH,gCAAgC,EAAW,qBAC3C,iCAAiC,EAAW,IAWlD,IAAI,EAAQ,EAAY,CAAC,KAAM,UAAW,YAAa,cAAe,gBAAgB,CARzE,EAAK,MAAM,IAAK,GAAY,CACvC,EAAQ,GACR,EAAQ,QACR,EAAQ,UACR,EAAQ,aAAA,IACR,EAAQ,eAAA,IACT,CAE2F,CAAC,CAI7F,OAHI,EAAK,SAAS,YAChB,GAAS,cAAc,EAAK,SAAS,aAEhC,GAEV,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as e}from"./policyEngineCliError-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{r as e}from"./policyEngineCliError-DY8V-qkK.mjs";import{i as t,n,t as r}from"./printResult-esxW3HhT.mjs";import{t as i}from"./renderTable-DKTZbMjY.mjs";import{t as a}from"./done-input-validation-Cjk7a3jX.mjs";import o from"colors";async function s({auth:s,"transcend-url":c,limit:l,offset:u,json:d,debug:f=!1}){a(this.process),e(f);let p=t(c,s);this.logger.info(o.green(`Listing policy bundles...`));let m=await n(p.get(`v1/policy-engine/policy-bundles`,{searchParams:{limit:l,offset:u}}).json());r(this.process.stdout,{json:d,data:m,renderTable:()=>{if(m.nodes.length===0)return`No policy bundles found.`;let e=i([`id`,`bundleName`,`activeVersionId`,`lastActivatedAt`,`createdAt`],m.nodes.map(e=>[e.id,e.bundleName,e.activeVersionId??`-`,e.lastActivatedAt??`-`,e.createdAt]));return e+=`\n\ntotalCount: ${m.totalCount}`,u+m.nodes.length<m.totalCount&&(e+=`\nnextOffset: ${u+m.nodes.length}`),e}})}export{s as bundles};
|
|
2
|
+
//# sourceMappingURL=impl-DIPvFKiP.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-DIPvFKiP.mjs","names":[],"sources":["../src/commands/policy/bundles/impl.ts"],"sourcesContent":["import colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { EMPTY_CELL } from '../constants.js';\nimport {\n buildPolicyEngineClient,\n policyEngineRequest,\n printResult,\n renderTable,\n setPolicyEngineCliDebug,\n} from '../helpers/index.js';\nimport type { PolicyBundleListResponse } from '../types.js';\n\n/** CLI flags for `transcend policy bundles`. */\nexport interface BundlesCommandFlags {\n /** Transcend API key */\n auth: string;\n /** Transcend API URL */\n 'transcend-url': string;\n /** Page size */\n limit: number;\n /** Number of records to skip */\n offset: number;\n /** Print raw JSON response */\n json: boolean;\n /** Include technical error details when a command fails */\n debug?: boolean;\n}\n\n/**\n * List policy bundles for the current organization.\n *\n * @param this - CLI context\n * @param flags - Command flags\n */\nexport async function bundles(\n this: LocalContext,\n { auth, 'transcend-url': transcendUrl, limit, offset, json, debug = false }: BundlesCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n setPolicyEngineCliDebug(debug);\n\n const client = buildPolicyEngineClient(transcendUrl, auth);\n\n this.logger.info(colors.green('Listing policy bundles...'));\n\n const body = await policyEngineRequest(\n client\n .get('v1/policy-engine/policy-bundles', {\n searchParams: { limit, offset },\n })\n .json<PolicyBundleListResponse>(),\n );\n\n printResult(this.process.stdout, {\n json,\n data: body,\n renderTable: () => {\n if (body.nodes.length === 0) {\n return 'No policy bundles found.';\n }\n\n const rows = body.nodes.map((bundle) => [\n bundle.id,\n bundle.bundleName,\n bundle.activeVersionId ?? EMPTY_CELL,\n bundle.lastActivatedAt ?? EMPTY_CELL,\n bundle.createdAt,\n ]);\n\n let table = renderTable(\n ['id', 'bundleName', 'activeVersionId', 'lastActivatedAt', 'createdAt'],\n rows,\n );\n table += `\\n\\ntotalCount: ${body.totalCount}`;\n if (offset + body.nodes.length < body.totalCount) {\n table += `\\nnextOffset: ${offset + body.nodes.length}`;\n }\n return table;\n },\n });\n}\n"],"mappings":"8OAoCA,eAAsB,EAEpB,CAAE,OAAM,gBAAiB,EAAc,QAAO,SAAQ,OAAM,QAAQ,IACrD,CACf,EAAoB,KAAK,QAAQ,CACjC,EAAwB,EAAM,CAE9B,IAAM,EAAS,EAAwB,EAAc,EAAK,CAE1D,KAAK,OAAO,KAAK,EAAO,MAAM,4BAA4B,CAAC,CAE3D,IAAM,EAAO,MAAM,EACjB,EACG,IAAI,kCAAmC,CACtC,aAAc,CAAE,QAAO,SAAQ,CAChC,CAAC,CACD,MAAgC,CACpC,CAED,EAAY,KAAK,QAAQ,OAAQ,CAC/B,OACA,KAAM,EACN,gBAAmB,CACjB,GAAI,EAAK,MAAM,SAAW,EACxB,MAAO,2BAWT,IAAI,EAAQ,EACV,CAAC,KAAM,aAAc,kBAAmB,kBAAmB,YAAY,CAT5D,EAAK,MAAM,IAAK,GAAW,CACtC,EAAO,GACP,EAAO,WACP,EAAO,iBAAA,IACP,EAAO,iBAAA,IACP,EAAO,UACR,CAIK,CACL,CAKD,MAJA,IAAS,mBAAmB,EAAK,aAC7B,EAAS,EAAK,MAAM,OAAS,EAAK,aACpC,GAAS,iBAAiB,EAAS,EAAK,MAAM,UAEzC,GAEV,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{o as e,r as t}from"./readTranscendYaml-
|
|
1
|
+
import{o as e,r as t}from"./readTranscendYaml-STYnRzq-.mjs";import{t as n}from"./consentManagersToBusinessEntities-O4KBox9u.mjs";import{t as r}from"./listFiles-CWHAdKY-.mjs";import{t as i}from"./done-input-validation-Cjk7a3jX.mjs";import a from"node:path";import o from"colors";function s({consentManagerYmlFolder:s,output:c}){i(this.process),(!this.fs.existsSync(s)||!this.fs.lstatSync(s).isDirectory())&&(this.logger.error(o.red(`Folder does not exist: "${s}"`)),this.process.exit(1));let l=n(r(this.fs.readdirSync(s)).map(e=>{let n=a.join(s,e),{"consent-manager":r}=t(this.fs.readFileSync(n,`utf8`),{},n);return{name:e,input:r}}));this.logger.info(`
|
|
2
2
|
|
|
3
3
|
~~~~~~~~~~~
|
|
4
4
|
Airgap scripts to host:`),l.forEach(({attributes:e,title:t},n)=>{e?.find(e=>e.key===`Airgap Production URL`)?.values?.forEach(e=>{this.logger.info(`${n}) ${t} - ${e}`)})}),this.fs.writeFileSync(c,e({"business-entities":l})),this.logger.info(o.green(`Successfully wrote ${l.length} business entities to file "${c}"`))}export{s as consentManagersToBusinessEntities};
|
|
5
|
-
//# sourceMappingURL=impl-
|
|
5
|
+
//# sourceMappingURL=impl-DJLlcqSg.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl-
|
|
1
|
+
{"version":3,"file":"impl-DJLlcqSg.mjs","names":["consentManagersToBusinessEntitiesHelper"],"sources":["../src/commands/inventory/consent-managers-to-business-entities/impl.ts"],"sourcesContent":["import path from 'node:path';\n\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { filterFileNames } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { consentManagersToBusinessEntities as consentManagersToBusinessEntitiesHelper } from '../../../lib/consent-manager/index.js';\nimport { parseTranscendYaml, serializeTranscendYaml } from '../../../lib/readTranscendYaml.js';\n\nexport interface ConsentManagersToBusinessEntitiesCommandFlags {\n consentManagerYmlFolder: string;\n output: string;\n}\n\nexport function consentManagersToBusinessEntities(\n this: LocalContext,\n { consentManagerYmlFolder, output }: ConsentManagersToBusinessEntitiesCommandFlags,\n): void {\n doneInputValidation(this.process);\n\n // Ensure folder is passed\n if (\n !this.fs.existsSync(consentManagerYmlFolder) ||\n !this.fs.lstatSync(consentManagerYmlFolder).isDirectory()\n ) {\n this.logger.error(colors.red(`Folder does not exist: \"${consentManagerYmlFolder}\"`));\n this.process.exit(1);\n }\n\n // Read in each consent manager configuration\n const inputs = filterFileNames(this.fs.readdirSync(consentManagerYmlFolder)).map((directory) => {\n const inputPath = path.join(consentManagerYmlFolder, directory);\n const { 'consent-manager': consentManager } = parseTranscendYaml(\n this.fs.readFileSync(inputPath, 'utf8'),\n {},\n inputPath,\n );\n return { name: directory, input: consentManager };\n });\n\n // Convert to business entities\n const businessEntities = consentManagersToBusinessEntitiesHelper(inputs);\n\n this.logger.info('\\n\\n~~~~~~~~~~~\\nAirgap scripts to host:');\n businessEntities.forEach(({ attributes, title }, index) => {\n attributes\n ?.find((attribute) => attribute.key === 'Airgap Production URL')\n ?.values?.forEach((url) => {\n this.logger.info(`${index}) ${title} - ${url}`);\n });\n });\n\n this.fs.writeFileSync(\n output,\n serializeTranscendYaml({\n 'business-entities': businessEntities,\n }),\n );\n\n this.logger.info(\n colors.green(\n `Successfully wrote ${businessEntities.length} business entities to file \"${output}\"`,\n ),\n );\n}\n"],"mappings":"sRAeA,SAAgB,EAEd,CAAE,0BAAyB,UACrB,CACN,EAAoB,KAAK,QAAQ,EAI/B,CAAC,KAAK,GAAG,WAAW,EAAwB,EAC5C,CAAC,KAAK,GAAG,UAAU,EAAwB,CAAC,aAAa,IAEzD,KAAK,OAAO,MAAM,EAAO,IAAI,2BAA2B,EAAwB,GAAG,CAAC,CACpF,KAAK,QAAQ,KAAK,EAAE,EAetB,IAAM,EAAmBA,EAXV,EAAgB,KAAK,GAAG,YAAY,EAAwB,CAAC,CAAC,IAAK,GAAc,CAC9F,IAAM,EAAY,EAAK,KAAK,EAAyB,EAAU,CACzD,CAAE,kBAAmB,GAAmB,EAC5C,KAAK,GAAG,aAAa,EAAW,OAAO,CACvC,EAAE,CACF,EACD,CACD,MAAO,CAAE,KAAM,EAAW,MAAO,EAAgB,EAIoB,CAAC,CAExE,KAAK,OAAO,KAAK;;;yBAA2C,CAC5D,EAAiB,SAAS,CAAE,aAAY,SAAS,IAAU,CACzD,GACI,KAAM,GAAc,EAAU,MAAQ,wBAAwB,EAC9D,QAAQ,QAAS,GAAQ,CACzB,KAAK,OAAO,KAAK,GAAG,EAAM,IAAI,EAAM,KAAK,IAAM,EAC/C,EACJ,CAEF,KAAK,GAAG,cACN,EACA,EAAuB,CACrB,oBAAqB,EACtB,CAAC,CACH,CAED,KAAK,OAAO,KACV,EAAO,MACL,sBAAsB,EAAiB,OAAO,8BAA8B,EAAO,GACpF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{o as e,r as t}from"./readTranscendYaml-
|
|
2
|
-
//# sourceMappingURL=impl-
|
|
1
|
+
import{o as e,r as t}from"./readTranscendYaml-STYnRzq-.mjs";import{t as n}from"./listFiles-CWHAdKY-.mjs";import{t as r}from"./done-input-validation-Cjk7a3jX.mjs";import{t as i}from"./dataFlowsToDataSilos-CLSHb1GA.mjs";import{difference as a}from"lodash-es";import o from"node:path";import s from"colors";import{buildTranscendGraphQLClient as c,fetchAndIndexCatalogs as l}from"@transcend-io/sdk";async function u({auth:u,dataFlowsYmlFolder:d,output:f,ignoreYmls:p=[],transcendUrl:m}){r(this.process),(!this.fs.existsSync(d)||!this.fs.lstatSync(d).isDirectory())&&(this.logger.error(s.red(`Folder does not exist: "${d}"`)),this.process.exit(1));let h=p.map(e=>e.split(`.`)[0]),g=n(this.fs.readdirSync(d)).map(e=>{let n=o.join(d,e),{"data-flows":r=[]}=t(this.fs.readFileSync(n,`utf8`),{},n),{adTechDataSilos:a,siteTechDataSilos:s}=i(r,{serviceToSupportedIntegration:S,serviceToTitle:x});return{adTechDataSilos:a,siteTechDataSilos:s,organizationName:e.split(`.`)[0]}}),_={};g.forEach(({adTechDataSilos:e,siteTechDataSilos:t,organizationName:n})=>{[...e,...t].forEach(e=>{let t=e[`outer-type`]||e.integrationName;_[t]||(_[t]=[]),_[t].push(n),_[t]=[...new Set(_[t])]})});let v=[...new Set(g.map(({adTechDataSilos:e})=>e.map(e=>e[`outer-type`]||e.integrationName)).flat())],y=a([...new Set(g.map(({siteTechDataSilos:e})=>e.map(e=>e[`outer-type`]||e.integrationName)).flat())],v),b={};g.forEach(({adTechDataSilos:e,siteTechDataSilos:t})=>{[...e,...t].forEach(e=>{let t=e[`outer-type`]||e.integrationName,n=e.attributes?.find(e=>e.key===`Found On Domain`);b[t]||(b[t]=[]),b[t].push(...n?.values||[]),b[t]=[...new Set(b[t])]})});let{serviceToTitle:x,serviceToSupportedIntegration:S}=await l(c(m,u),{logger:this.logger}),C=[...v,...y].map(e=>({title:x[e],...S[e]?{integrationName:e}:{integrationName:`promptAPerson`,"outer-type":e},attributes:[{key:`Tech Type`,values:[`Ad Tech`]},{key:`Business Units`,values:a(_[e]||[],h)},{key:`Found On Domain`,values:b[e]||[]}]}));this.logger.log(`Total Services: ${C.length}`),this.logger.log(`Ad Tech Services: ${v.length}`),this.logger.log(`Site Tech Services: ${y.length}`),this.fs.writeFileSync(f,e({"data-silos":C}))}export{u as deriveDataSilosFromDataFlowsCrossInstance};
|
|
2
|
+
//# sourceMappingURL=impl-DOoR93T6.mjs.map
|