@transcend-io/cli 8.28.0 → 8.29.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.
Files changed (141) hide show
  1. package/README.md +4 -2
  2. package/dist/bin/bash-complete.cjs +1 -1
  3. package/dist/bin/cli.cjs +1 -1
  4. package/dist/bin/deprecated-command.cjs +2 -2
  5. package/dist/{chunk-4PQ4RHUG.cjs → chunk-2CAMTEJY.cjs} +4 -4
  6. package/dist/{chunk-4PQ4RHUG.cjs.map → chunk-2CAMTEJY.cjs.map} +1 -1
  7. package/dist/{chunk-FER7XKVN.cjs → chunk-4AOZYIVR.cjs} +2 -2
  8. package/dist/{chunk-FER7XKVN.cjs.map → chunk-4AOZYIVR.cjs.map} +1 -1
  9. package/dist/{chunk-7PF5VVAF.cjs → chunk-57L3G2BH.cjs} +2 -2
  10. package/dist/{chunk-7PF5VVAF.cjs.map → chunk-57L3G2BH.cjs.map} +1 -1
  11. package/dist/{chunk-AEL3DOYI.cjs → chunk-BBIQYUL2.cjs} +2 -2
  12. package/dist/{chunk-AEL3DOYI.cjs.map → chunk-BBIQYUL2.cjs.map} +1 -1
  13. package/dist/{chunk-CQT5QQ3U.cjs → chunk-BO6JY2EM.cjs} +2 -2
  14. package/dist/{chunk-CQT5QQ3U.cjs.map → chunk-BO6JY2EM.cjs.map} +1 -1
  15. package/dist/{chunk-JFZPP4VV.cjs → chunk-BQSBPO63.cjs} +3 -3
  16. package/dist/{chunk-JFZPP4VV.cjs.map → chunk-BQSBPO63.cjs.map} +1 -1
  17. package/dist/{chunk-EYOQLGDV.cjs → chunk-F7QE6D3T.cjs} +2 -2
  18. package/dist/{chunk-EYOQLGDV.cjs.map → chunk-F7QE6D3T.cjs.map} +1 -1
  19. package/dist/{chunk-LCDYXJN6.cjs → chunk-FHUHBSLE.cjs} +2 -2
  20. package/dist/{chunk-LCDYXJN6.cjs.map → chunk-FHUHBSLE.cjs.map} +1 -1
  21. package/dist/{chunk-K4TIJ3VM.cjs → chunk-GDNSAJQN.cjs} +2 -2
  22. package/dist/{chunk-K4TIJ3VM.cjs.map → chunk-GDNSAJQN.cjs.map} +1 -1
  23. package/dist/{chunk-YKGS253B.cjs → chunk-HCPNMNS3.cjs} +6 -6
  24. package/dist/{chunk-YKGS253B.cjs.map → chunk-HCPNMNS3.cjs.map} +1 -1
  25. package/dist/{chunk-RNZ72QMS.cjs → chunk-ID7MP3QD.cjs} +2 -2
  26. package/dist/{chunk-RNZ72QMS.cjs.map → chunk-ID7MP3QD.cjs.map} +1 -1
  27. package/dist/{chunk-THOOR2KA.cjs → chunk-K4IBAM5Z.cjs} +4 -4
  28. package/dist/{chunk-THOOR2KA.cjs.map → chunk-K4IBAM5Z.cjs.map} +1 -1
  29. package/dist/{chunk-ECGHWDVP.cjs → chunk-LU3DKRNK.cjs} +2 -2
  30. package/dist/chunk-LU3DKRNK.cjs.map +1 -0
  31. package/dist/{chunk-L7Z4PFRC.cjs → chunk-LWPX5LJB.cjs} +2 -2
  32. package/dist/{chunk-L7Z4PFRC.cjs.map → chunk-LWPX5LJB.cjs.map} +1 -1
  33. package/dist/{chunk-Y35YHYXP.cjs → chunk-N25PPQY4.cjs} +21 -21
  34. package/dist/{chunk-Y35YHYXP.cjs.map → chunk-N25PPQY4.cjs.map} +1 -1
  35. package/dist/chunk-NBXAOUWC.cjs +3001 -0
  36. package/dist/chunk-NBXAOUWC.cjs.map +1 -0
  37. package/dist/{chunk-Q7I37FJV.cjs → chunk-T3BBQIRY.cjs} +2 -2
  38. package/dist/chunk-T3BBQIRY.cjs.map +1 -0
  39. package/dist/{chunk-I7PFP5VB.cjs → chunk-UXYKFAP7.cjs} +2 -2
  40. package/dist/{chunk-I7PFP5VB.cjs.map → chunk-UXYKFAP7.cjs.map} +1 -1
  41. package/dist/{impl-DVE332P5.cjs → impl-333FTGNJ.cjs} +2 -2
  42. package/dist/{impl-DVE332P5.cjs.map → impl-333FTGNJ.cjs.map} +1 -1
  43. package/dist/{impl-ANXIZT7S.cjs → impl-3HWWFZLZ.cjs} +2 -2
  44. package/dist/{impl-ANXIZT7S.cjs.map → impl-3HWWFZLZ.cjs.map} +1 -1
  45. package/dist/{impl-XHO6WQ2I.cjs → impl-5IR5JVEX.cjs} +2 -2
  46. package/dist/{impl-XHO6WQ2I.cjs.map → impl-5IR5JVEX.cjs.map} +1 -1
  47. package/dist/{impl-ZTZHVQYY.cjs → impl-5JKO562Z.cjs} +2 -2
  48. package/dist/{impl-ZTZHVQYY.cjs.map → impl-5JKO562Z.cjs.map} +1 -1
  49. package/dist/impl-5NEL56EQ.cjs +2 -0
  50. package/dist/{impl-AP2ZTYJK.cjs.map → impl-5NEL56EQ.cjs.map} +1 -1
  51. package/dist/impl-6O4FILGB.cjs +2 -0
  52. package/dist/{impl-PE52QYSI.cjs.map → impl-6O4FILGB.cjs.map} +1 -1
  53. package/dist/impl-7NYN6PNG.cjs +2 -0
  54. package/dist/{impl-ALROZNDJ.cjs.map → impl-7NYN6PNG.cjs.map} +1 -1
  55. package/dist/impl-ATMXXGUO.cjs +2 -0
  56. package/dist/{impl-M5QGTDLF.cjs.map → impl-ATMXXGUO.cjs.map} +1 -1
  57. package/dist/{impl-LKJFVX7E.cjs → impl-B5HWJ3KK.cjs} +2 -2
  58. package/dist/{impl-LKJFVX7E.cjs.map → impl-B5HWJ3KK.cjs.map} +1 -1
  59. package/dist/{impl-DDQQGOQ3.cjs → impl-CGX5RD4A.cjs} +2 -2
  60. package/dist/{impl-DDQQGOQ3.cjs.map → impl-CGX5RD4A.cjs.map} +1 -1
  61. package/dist/{impl-W35DMTQV.cjs → impl-D2C22UEC.cjs} +2 -2
  62. package/dist/{impl-W35DMTQV.cjs.map → impl-D2C22UEC.cjs.map} +1 -1
  63. package/dist/{impl-3YAJ7ZV3.cjs → impl-EE3BM53W.cjs} +2 -2
  64. package/dist/{impl-3YAJ7ZV3.cjs.map → impl-EE3BM53W.cjs.map} +1 -1
  65. package/dist/{impl-SVEK74IU.cjs → impl-FTRCRS7H.cjs} +2 -2
  66. package/dist/{impl-SVEK74IU.cjs.map → impl-FTRCRS7H.cjs.map} +1 -1
  67. package/dist/impl-FXVXRV6Q.cjs +3 -0
  68. package/dist/{impl-LDOILOAQ.cjs.map → impl-FXVXRV6Q.cjs.map} +1 -1
  69. package/dist/{impl-DT5KLE2G.cjs → impl-GJB4EKPW.cjs} +3 -3
  70. package/dist/{impl-DT5KLE2G.cjs.map → impl-GJB4EKPW.cjs.map} +1 -1
  71. package/dist/{impl-7B7QDZZJ.cjs → impl-HBJ7BPEI.cjs} +2 -2
  72. package/dist/{impl-7B7QDZZJ.cjs.map → impl-HBJ7BPEI.cjs.map} +1 -1
  73. package/dist/{impl-D7R3HZEC.cjs → impl-HQICWTNR.cjs} +5 -5
  74. package/dist/{impl-D7R3HZEC.cjs.map → impl-HQICWTNR.cjs.map} +1 -1
  75. package/dist/{impl-AZYBYV3X.cjs → impl-HSD25CEC.cjs} +2 -2
  76. package/dist/{impl-AZYBYV3X.cjs.map → impl-HSD25CEC.cjs.map} +1 -1
  77. package/dist/{impl-DXAKJNLZ.cjs → impl-HXH7SZDU.cjs} +2 -2
  78. package/dist/{impl-DXAKJNLZ.cjs.map → impl-HXH7SZDU.cjs.map} +1 -1
  79. package/dist/impl-ITV3PGFS.cjs +2 -0
  80. package/dist/{impl-PXT7QNSR.cjs.map → impl-ITV3PGFS.cjs.map} +1 -1
  81. package/dist/impl-IWMRKBYP.cjs +2 -0
  82. package/dist/{impl-LQEYNOZS.cjs.map → impl-IWMRKBYP.cjs.map} +1 -1
  83. package/dist/{impl-NCUMPL6B.cjs → impl-J5DLFX22.cjs} +4 -4
  84. package/dist/{impl-NCUMPL6B.cjs.map → impl-J5DLFX22.cjs.map} +1 -1
  85. package/dist/{impl-YWJCIRTP.cjs → impl-JYAU26KS.cjs} +2 -2
  86. package/dist/{impl-YWJCIRTP.cjs.map → impl-JYAU26KS.cjs.map} +1 -1
  87. package/dist/{impl-YHBNKYSL.cjs → impl-LVPOYO4A.cjs} +2 -2
  88. package/dist/{impl-YHBNKYSL.cjs.map → impl-LVPOYO4A.cjs.map} +1 -1
  89. package/dist/{impl-H2BRV4GP.cjs → impl-M3AZLM3Y.cjs} +2 -2
  90. package/dist/{impl-H2BRV4GP.cjs.map → impl-M3AZLM3Y.cjs.map} +1 -1
  91. package/dist/{impl-YJ6UUT4D.cjs → impl-OCDURTBG.cjs} +2 -2
  92. package/dist/{impl-YJ6UUT4D.cjs.map → impl-OCDURTBG.cjs.map} +1 -1
  93. package/dist/impl-OMCKSCEI.cjs +2 -0
  94. package/dist/{impl-BDPD5CCN.cjs.map → impl-OMCKSCEI.cjs.map} +1 -1
  95. package/dist/{impl-SVPD3IHV.cjs → impl-PHYCAOK7.cjs} +2 -2
  96. package/dist/{impl-SVPD3IHV.cjs.map → impl-PHYCAOK7.cjs.map} +1 -1
  97. package/dist/{impl-VZ6NJDAV.cjs → impl-QT2HKTCP.cjs} +2 -2
  98. package/dist/{impl-VZ6NJDAV.cjs.map → impl-QT2HKTCP.cjs.map} +1 -1
  99. package/dist/{impl-A6W2KTYL.cjs → impl-SQHP2SZ4.cjs} +2 -2
  100. package/dist/{impl-A6W2KTYL.cjs.map → impl-SQHP2SZ4.cjs.map} +1 -1
  101. package/dist/{impl-SDQ6LUZD.cjs → impl-TJFUBDML.cjs} +2 -2
  102. package/dist/{impl-SDQ6LUZD.cjs.map → impl-TJFUBDML.cjs.map} +1 -1
  103. package/dist/{impl-UZPP5VK5.cjs → impl-TU3DSCLK.cjs} +2 -2
  104. package/dist/{impl-UZPP5VK5.cjs.map → impl-TU3DSCLK.cjs.map} +1 -1
  105. package/dist/{impl-NISL4HZY.cjs → impl-VV3UMWFG.cjs} +2 -2
  106. package/dist/{impl-NISL4HZY.cjs.map → impl-VV3UMWFG.cjs.map} +1 -1
  107. package/dist/{impl-BL4XQEFX.cjs → impl-VYNKYTB5.cjs} +2 -2
  108. package/dist/{impl-BL4XQEFX.cjs.map → impl-VYNKYTB5.cjs.map} +1 -1
  109. package/dist/{impl-IIIT5MSV.cjs → impl-W7AB7VQY.cjs} +2 -2
  110. package/dist/{impl-IIIT5MSV.cjs.map → impl-W7AB7VQY.cjs.map} +1 -1
  111. package/dist/{impl-UC5CCT6E.cjs → impl-WGVGJV2F.cjs} +3 -3
  112. package/dist/{impl-UC5CCT6E.cjs.map → impl-WGVGJV2F.cjs.map} +1 -1
  113. package/dist/{impl-OFRMKTX5.cjs → impl-XUD5VFQX.cjs} +2 -2
  114. package/dist/{impl-OFRMKTX5.cjs.map → impl-XUD5VFQX.cjs.map} +1 -1
  115. package/dist/{impl-55NL4KOI.cjs → impl-Y3WZAMYW.cjs} +2 -2
  116. package/dist/{impl-55NL4KOI.cjs.map → impl-Y3WZAMYW.cjs.map} +1 -1
  117. package/dist/{impl-MBEVWSPX.cjs → impl-Z4GNVM3V.cjs} +2 -2
  118. package/dist/{impl-MBEVWSPX.cjs.map → impl-Z4GNVM3V.cjs.map} +1 -1
  119. package/dist/impl-ZMX57RSP.cjs +2 -0
  120. package/dist/{impl-B7ODYIUX.cjs.map → impl-ZMX57RSP.cjs.map} +1 -1
  121. package/dist/{impl-IFDUZGZM.cjs → impl-ZSNYO6VH.cjs} +2 -2
  122. package/dist/{impl-IFDUZGZM.cjs.map → impl-ZSNYO6VH.cjs.map} +1 -1
  123. package/dist/{impl-JPVEFSJB.cjs → impl-ZWLFLVPK.cjs} +2 -2
  124. package/dist/{impl-JPVEFSJB.cjs.map → impl-ZWLFLVPK.cjs.map} +1 -1
  125. package/dist/index.cjs +3 -3
  126. package/dist/index.cjs.map +1 -1
  127. package/dist/index.d.cts +10867 -5
  128. package/package.json +1 -1
  129. package/dist/chunk-ECGHWDVP.cjs.map +0 -1
  130. package/dist/chunk-KUBXRT3V.cjs +0 -2979
  131. package/dist/chunk-KUBXRT3V.cjs.map +0 -1
  132. package/dist/chunk-Q7I37FJV.cjs.map +0 -1
  133. package/dist/impl-ALROZNDJ.cjs +0 -2
  134. package/dist/impl-AP2ZTYJK.cjs +0 -2
  135. package/dist/impl-B7ODYIUX.cjs +0 -2
  136. package/dist/impl-BDPD5CCN.cjs +0 -2
  137. package/dist/impl-LDOILOAQ.cjs +0 -3
  138. package/dist/impl-LQEYNOZS.cjs +0 -2
  139. package/dist/impl-M5QGTDLF.cjs +0 -2
  140. package/dist/impl-PE52QYSI.cjs +0 -2
  141. package/dist/impl-PXT7QNSR.cjs +0 -2
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } }var _chunkQ7I37FJVcjs = require('./chunk-Q7I37FJV.cjs');var _iots = require('io-ts'); var e = _interopRequireWildcard(_iots); var r = _interopRequireWildcard(_iots);var _typeutils = require('@transcend-io/type-utils');var d=({TRouteName:t})=>e.type({routeName:t,enabledPolicies:e.array(_typeutils.valuesOf.call(void 0, _chunkQ7I37FJVcjs.e))});var l=({TEnabledRoutes:t})=>r.type({enabledRoutes:t});exports.a = d; exports.b = l;
2
- //# sourceMappingURL=chunk-LCDYXJN6.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } }var _chunkT3BBQIRYcjs = require('./chunk-T3BBQIRY.cjs');var _iots = require('io-ts'); var e = _interopRequireWildcard(_iots); var r = _interopRequireWildcard(_iots);var _typeutils = require('@transcend-io/type-utils');var d=({TRouteName:t})=>e.type({routeName:t,enabledPolicies:e.array(_typeutils.valuesOf.call(void 0, _chunkT3BBQIRYcjs.e))});var l=({TEnabledRoutes:t})=>r.type({enabledRoutes:t});exports.a = d; exports.b = l;
2
+ //# sourceMappingURL=chunk-FHUHBSLE.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-LCDYXJN6.cjs","../src/lib/helpers/buildEnabledRouteType.ts","../src/lib/helpers/buildAIIntegrationType.ts"],"names":["buildEnabledRouteType","TRouteName","valuesOf","buildAIIntegrationType","TEnabledRoutes"],"mappings":"AAAA,mZAAwC,6GCArB,qDAEM,IASZA,CAAAA,CAAwB,CAAoB,CACvD,UAAA,CAAAC,CACF,CAAA,CAAA,EAII,CAAA,CAAA,IAAA,CAAK,CACL,SAAA,CAAWA,CAAAA,CACX,eAAA,CAAmB,CAAA,CAAA,KAAA,CAAMC,iCAAAA,mBAA6B,CAAC,CACzD,CAAC,CAAA,CCpBH,IASaC,CAAAA,CAAyB,CAGpC,CACA,cAAA,CAAAC,CACF,CAAA,CAAA,EAII,CAAA,CAAA,IAAA,CAAK,CACL,aAAA,CAAeA,CACjB,CAAC,CAAA,CAAA,6BAAA","file":"/home/runner/work/cli/cli/dist/chunk-LCDYXJN6.cjs","sourcesContent":[null,"import * as t from 'io-ts';\nimport { EnabledRouteC } from '../../codecs';\nimport { valuesOf } from '@transcend-io/type-utils';\nimport { PathfinderPolicyName } from '../../enums';\n\n/**\n * Builds a custom io-ts type that represents a route allowed by the proxy\n *\n * @param TRouteName - the string with the name of the allowed route\n * @returns custom io-ts AllowedRoute type\n */\nexport const buildEnabledRouteType = <T extends t.Mixed>({\n TRouteName,\n}: {\n /** the type of the routeName property */\n TRouteName: T;\n}): EnabledRouteC<T> =>\n t.type({\n routeName: TRouteName,\n enabledPolicies: t.array(valuesOf(PathfinderPolicyName)),\n });\n","import * as t from 'io-ts';\nimport { AIIntegrationC, EnabledRouteC } from '../../codecs';\n\n/**\n * Helper to build a custom io-ts type representing an AIIntegration\n *\n * @param TEnabledRoutes - the type of the enabledRoutes for the AIIntegration type\n * @returns an AIIntegration type\n */\nexport const buildAIIntegrationType = <\n T extends t.Mixed,\n P extends t.ArrayC<EnabledRouteC<T>>,\n>({\n TEnabledRoutes,\n}: {\n /** the type of the enabledRoutes property */\n TEnabledRoutes: P;\n}): AIIntegrationC<T> =>\n t.type({\n enabledRoutes: TEnabledRoutes,\n });\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-FHUHBSLE.cjs","../src/lib/helpers/buildEnabledRouteType.ts","../src/lib/helpers/buildAIIntegrationType.ts"],"names":["buildEnabledRouteType","TRouteName","valuesOf","buildAIIntegrationType","TEnabledRoutes"],"mappings":"AAAA,mZAAwC,6GCArB,qDAEM,IASZA,CAAAA,CAAwB,CAAoB,CACvD,UAAA,CAAAC,CACF,CAAA,CAAA,EAII,CAAA,CAAA,IAAA,CAAK,CACL,SAAA,CAAWA,CAAAA,CACX,eAAA,CAAmB,CAAA,CAAA,KAAA,CAAMC,iCAAAA,mBAA6B,CAAC,CACzD,CAAC,CAAA,CCpBH,IASaC,CAAAA,CAAyB,CAGpC,CACA,cAAA,CAAAC,CACF,CAAA,CAAA,EAII,CAAA,CAAA,IAAA,CAAK,CACL,aAAA,CAAeA,CACjB,CAAC,CAAA,CAAA,6BAAA","file":"/home/runner/work/cli/cli/dist/chunk-FHUHBSLE.cjs","sourcesContent":[null,"import * as t from 'io-ts';\nimport { EnabledRouteC } from '../../codecs';\nimport { valuesOf } from '@transcend-io/type-utils';\nimport { PathfinderPolicyName } from '../../enums';\n\n/**\n * Builds a custom io-ts type that represents a route allowed by the proxy\n *\n * @param TRouteName - the string with the name of the allowed route\n * @returns custom io-ts AllowedRoute type\n */\nexport const buildEnabledRouteType = <T extends t.Mixed>({\n TRouteName,\n}: {\n /** the type of the routeName property */\n TRouteName: T;\n}): EnabledRouteC<T> =>\n t.type({\n routeName: TRouteName,\n enabledPolicies: t.array(valuesOf(PathfinderPolicyName)),\n });\n","import * as t from 'io-ts';\nimport { AIIntegrationC, EnabledRouteC } from '../../codecs';\n\n/**\n * Helper to build a custom io-ts type representing an AIIntegration\n *\n * @param TEnabledRoutes - the type of the enabledRoutes for the AIIntegration type\n * @returns an AIIntegration type\n */\nexport const buildAIIntegrationType = <\n T extends t.Mixed,\n P extends t.ArrayC<EnabledRouteC<T>>,\n>({\n TEnabledRoutes,\n}: {\n /** the type of the enabledRoutes property */\n TEnabledRoutes: P;\n}): AIIntegrationC<T> =>\n t.type({\n enabledRoutes: TEnabledRoutes,\n });\n"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunkECGHWDVPcjs = require('./chunk-ECGHWDVP.cjs');var _chunkKUBXRT3Vcjs = require('./chunk-KUBXRT3V.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkEYOQLGDVcjs = require('./chunk-EYOQLGDV.cjs');var _bluebird = require('bluebird');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function H({email:r,password:a,scopes:f,apiKeyTitle:t,parentOrganizationId:o,deleteExistingApiKey:l=!0,createNewApiKey:I=!0,transcendUrl:x=_chunkEYOQLGDVcjs.r}){let s=await _chunkKUBXRT3Vcjs.vc.call(void 0, x,{});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Logging in using email and password."));let{roles:d,loginCookie:k}=await _chunkKUBXRT3Vcjs.Jd.call(void 0, s,{email:r,password:a});_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully logged in and found ${d.length} role${d.length===1?"":"s"}!`));let P=o?d.filter(e=>e.organization.id===o||e.organization.parentOrganizationId===o):d;s.setHeaders({Cookie:k});let m=[],c=[];return _chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Generating API keys with title: ${t}, scopes: ${f.join(",")}.`)),await _bluebird.mapSeries.call(void 0, P,async e=>{try{await _chunkKUBXRT3Vcjs.Kd.call(void 0, s,{roleId:e.id,email:r}),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Checking if API key already exists in organization "${e.organization.name}" with title: "${t}".`));let[g]=await _chunkKUBXRT3Vcjs.rd.call(void 0, s,[t]);if(g&&l)_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Deleting existing API key in "${e.organization.name}" with title: "${t}".`)),await _chunkKUBXRT3Vcjs.Md.call(void 0, s,g.id),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully deleted API key in "${e.organization.name}" with title: "${t}".`));else if(g)throw new Error(`API key already exists with title: "${t}"`);if(I){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Creating API key in "${e.organization.name}" with title: "${t}".`));let{apiKey:K}=await _chunkKUBXRT3Vcjs.Ld.call(void 0, s,{title:t,scopes:f});m.push({organizationName:e.organization.name,organizationId:e.organization.id,apiKey:K}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully created API key in "${e.organization.name}" with title: "${t}".`))}else m.push({organizationName:e.organization.name,organizationId:e.organization.id,apiKey:""})}catch(g){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to create API key in organization "${e.organization.name}"! - ${g.message}`)),c.push({organizationName:e.organization.name,organizationId:e.organization.id,error:g.message})}}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully created ${m.length} API key${m.length===1?"":"s"}`)),c.length>0&&_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to create ${c.length} API key${c.length===1?"":"s"}!`)),{errors:c,apiKeys:m}}var _typeutils = require('@transcend-io/type-utils');var _iots = require('io-ts'); var S = _interopRequireWildcard(_iots);var _fs = require('fs');function T(r){return r||(_chunkZUNVPK23cjs.a.error(_colors2.default.red("A Transcend API key must be provided. You can specify using --auth=$TRANSCEND_API_KEY")),process.exit(1)),_fs.existsSync.call(void 0, r)?_typeutils.decodeCodec.call(void 0, S.array(_chunkECGHWDVPcjs.ha),_fs.readFileSync.call(void 0, r,"utf-8")):r}function Z(r,a,f=!1){if(!_fs.existsSync.call(void 0, r))return[];let t=_fs.readdirSync.call(void 0, r).filter(o=>a?a.filter(l=>o.endsWith(l)).length:!0).filter(o=>o.indexOf(".")>0);return f?t.map(o=>o.replace(/\.[^/.]+$/,"")):t}var _path = require('path');function te(r){return _fs.readdirSync.call(void 0, r).filter(a=>_fs.statSync.call(void 0, _path.join.call(void 0, r,a)).isDirectory())}exports.a = H; exports.b = T; exports.c = Z; exports.d = te;
2
- //# sourceMappingURL=chunk-K4TIJ3VM.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunkLU3DKRNKcjs = require('./chunk-LU3DKRNK.cjs');var _chunkNBXAOUWCcjs = require('./chunk-NBXAOUWC.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkF7QE6D3Tcjs = require('./chunk-F7QE6D3T.cjs');var _bluebird = require('bluebird');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function H({email:r,password:a,scopes:f,apiKeyTitle:t,parentOrganizationId:o,deleteExistingApiKey:l=!0,createNewApiKey:I=!0,transcendUrl:x=_chunkF7QE6D3Tcjs.r}){let s=await _chunkNBXAOUWCcjs.wc.call(void 0, x,{});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Logging in using email and password."));let{roles:d,loginCookie:k}=await _chunkNBXAOUWCcjs.Kd.call(void 0, s,{email:r,password:a});_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully logged in and found ${d.length} role${d.length===1?"":"s"}!`));let P=o?d.filter(e=>e.organization.id===o||e.organization.parentOrganizationId===o):d;s.setHeaders({Cookie:k});let m=[],c=[];return _chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Generating API keys with title: ${t}, scopes: ${f.join(",")}.`)),await _bluebird.mapSeries.call(void 0, P,async e=>{try{await _chunkNBXAOUWCcjs.Ld.call(void 0, s,{roleId:e.id,email:r}),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Checking if API key already exists in organization "${e.organization.name}" with title: "${t}".`));let[g]=await _chunkNBXAOUWCcjs.sd.call(void 0, s,[t]);if(g&&l)_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Deleting existing API key in "${e.organization.name}" with title: "${t}".`)),await _chunkNBXAOUWCcjs.Nd.call(void 0, s,g.id),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully deleted API key in "${e.organization.name}" with title: "${t}".`));else if(g)throw new Error(`API key already exists with title: "${t}"`);if(I){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Creating API key in "${e.organization.name}" with title: "${t}".`));let{apiKey:K}=await _chunkNBXAOUWCcjs.Md.call(void 0, s,{title:t,scopes:f});m.push({organizationName:e.organization.name,organizationId:e.organization.id,apiKey:K}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully created API key in "${e.organization.name}" with title: "${t}".`))}else m.push({organizationName:e.organization.name,organizationId:e.organization.id,apiKey:""})}catch(g){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to create API key in organization "${e.organization.name}"! - ${g.message}`)),c.push({organizationName:e.organization.name,organizationId:e.organization.id,error:g.message})}}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully created ${m.length} API key${m.length===1?"":"s"}`)),c.length>0&&_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to create ${c.length} API key${c.length===1?"":"s"}!`)),{errors:c,apiKeys:m}}var _typeutils = require('@transcend-io/type-utils');var _iots = require('io-ts'); var S = _interopRequireWildcard(_iots);var _fs = require('fs');function T(r){return r||(_chunkZUNVPK23cjs.a.error(_colors2.default.red("A Transcend API key must be provided. You can specify using --auth=$TRANSCEND_API_KEY")),process.exit(1)),_fs.existsSync.call(void 0, r)?_typeutils.decodeCodec.call(void 0, S.array(_chunkLU3DKRNKcjs.ia),_fs.readFileSync.call(void 0, r,"utf-8")):r}function Z(r,a,f=!1){if(!_fs.existsSync.call(void 0, r))return[];let t=_fs.readdirSync.call(void 0, r).filter(o=>a?a.filter(l=>o.endsWith(l)).length:!0).filter(o=>o.indexOf(".")>0);return f?t.map(o=>o.replace(/\.[^/.]+$/,"")):t}var _path = require('path');function te(r){return _fs.readdirSync.call(void 0, r).filter(a=>_fs.statSync.call(void 0, _path.join.call(void 0, r,a)).isDirectory())}exports.a = H; exports.b = T; exports.c = Z; exports.d = te;
2
+ //# sourceMappingURL=chunk-GDNSAJQN.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-K4TIJ3VM.cjs","../src/lib/api-keys/generateCrossAccountApiKeys.ts"],"names":["generateCrossAccountApiKeys","email","password","scopes","apiKeyTitle","parentOrganizationId","deleteExistingApiKey","createNewApiKey","transcendUrl","DEFAULT_TRANSCEND_API","client","buildTranscendGraphQLClientGeneric","logger","colors","roles","loginCookie","loginUser","filteredRoles","role","results","errors","mapSeries","assumeRole","apiKeyWithTitle","fetchAllApiKeys","deleteApiKey","apiKey","createApiKey","err"],"mappings":"AAAA,mfAAyC,wDAAkF,wDAAyC,wDAAyC,oCCAnL,gFAUP,MAoBnB,SAAsBA,CAAAA,CAA4B,CAChD,KAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,MAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,oBAAA,CAAAC,CAAAA,CACA,oBAAA,CAAAC,CAAAA,CAAuB,CAAA,CAAA,CACvB,eAAA,CAAAC,CAAAA,CAAkB,CAAA,CAAA,CAClB,YAAA,CAAAC,CAAAA,CAAeC,mBACjB,CAAA,CAsBG,CAED,IAAMC,CAAAA,CAAS,MAAMC,kCAAAA,CAAmCH,CAAc,CAAC,CAAC,CAAA,CAGxEI,mBAAAA,CAAO,IAAA,CAAKC,gBAAAA,CAAO,OAAA,CAAQ,sCAAsC,CAAC,CAAA,CAClE,GAAM,CAAE,KAAA,CAAAC,CAAAA,CAAO,WAAA,CAAAC,CAAY,CAAA,CAAI,MAAMC,kCAAAA,CAAUN,CAAQ,CAAE,KAAA,CAAAT,CAAAA,CAAO,QAAA,CAAAC,CAAS,CAAC,CAAA,CAC1EU,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,KAAA,CACL,CAAA,iCAAA,EAAoCC,CAAAA,CAAM,MAAM,CAAA,KAAA,EAC9CA,CAAAA,CAAM,MAAA,GAAW,CAAA,CAAI,EAAA,CAAK,GAC5B,CAAA,CAAA,CACF,CACF,CAAA,CAGA,IAAMG,CAAAA,CAAgBZ,CAAAA,CAClBS,CAAAA,CAAM,MAAA,CACHI,CAAAA,EACCA,CAAAA,CAAK,YAAA,CAAa,EAAA,GAAOb,CAAAA,EACzBa,CAAAA,CAAK,YAAA,CAAa,oBAAA,GAAyBb,CAC/C,CAAA,CACAS,CAAAA,CAGJJ,CAAAA,CAAO,UAAA,CAAW,CAChB,MAAA,CAAQK,CACV,CAAC,CAAA,CAGD,IAAMI,CAAAA,CAA0B,CAAC,CAAA,CAC3BC,CAAAA,CAAgC,CAAC,CAAA,CAGvC,OAAAR,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,OAAA,CACL,CAAA,gCAAA,EAAmCT,CAAW,CAAA,UAAA,EAAaD,CAAAA,CAAO,IAAA,CAChE,GACF,CAAC,CAAA,CAAA,CACH,CACF,CAAA,CAGA,MAAMkB,iCAAAA,CAAUJ,CAAe,MAAOC,CAAAA,EAAS,CAC7C,GAAI,CAEF,MAAMI,kCAAAA,CAAWZ,CAAQ,CAAE,MAAA,CAAQQ,CAAAA,CAAK,EAAA,CAAI,KAAA,CAAAjB,CAAM,CAAC,CAAA,CAGnDW,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,OAAA,CACL,CAAA,oDAAA,EAAuDK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,eAAA,EAAkBd,CAAW,CAAA,EAAA,CAC5G,CACF,CAAA,CAGA,GAAM,CAACmB,CAAe,CAAA,CAAI,MAAMC,kCAAAA,CAAgBd,CAAQ,CAACN,CAAW,CAAC,CAAA,CACrE,EAAA,CAAImB,CAAAA,EAAmBjB,CAAAA,CACrBM,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,MAAA,CACL,CAAA,8BAAA,EAAiCK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,eAAA,EAAkBd,CAAW,CAAA,EAAA,CACtF,CACF,CAAA,CACA,MAAMqB,kCAAAA,CAAaf,CAAQa,CAAAA,CAAgB,EAAE,CAAA,CAC7CX,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,KAAA,CACL,CAAA,iCAAA,EAAoCK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,eAAA,EAAkBd,CAAW,CAAA,EAAA,CACzF,CACF,CAAA,CAAA,KAAA,EAAA,CACSmB,CAAAA,CAET,MAAM,IAAI,KAAA,CAAM,CAAA,oCAAA,EAAuCnB,CAAW,CAAA,CAAA,CAAG,CAAA,CAIvE,EAAA,CAAIG,CAAAA,CAAiB,CACnBK,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,OAAA,CACL,CAAA,qBAAA,EAAwBK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,eAAA,EAAkBd,CAAW,CAAA,EAAA,CAC7E,CACF,CAAA,CACA,GAAM,CAAE,MAAA,CAAAsB,CAAO,CAAA,CAAI,MAAMC,kCAAAA,CAAajB,CAAQ,CAC5C,KAAA,CAAON,CAAAA,CACP,MAAA,CAAAD,CACF,CAAC,CAAA,CACDgB,CAAAA,CAAQ,IAAA,CAAK,CACX,gBAAA,CAAkBD,CAAAA,CAAK,YAAA,CAAa,IAAA,CACpC,cAAA,CAAgBA,CAAAA,CAAK,YAAA,CAAa,EAAA,CAClC,MAAA,CAAAQ,CACF,CAAC,CAAA,CACDd,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,KAAA,CACL,CAAA,iCAAA,EAAoCK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,eAAA,EAAkBd,CAAW,CAAA,EAAA,CACzF,CACF,CACF,CAAA,KAEEe,CAAAA,CAAQ,IAAA,CAAK,CACX,gBAAA,CAAkBD,CAAAA,CAAK,YAAA,CAAa,IAAA,CACpC,cAAA,CAAgBA,CAAAA,CAAK,YAAA,CAAa,EAAA,CAClC,MAAA,CAAQ,EACV,CAAC,CAEL,CAAA,KAAA,CAASU,CAAAA,CAAK,CACZhB,mBAAAA,CAAO,KAAA,CACLC,gBAAAA,CAAO,GAAA,CACL,CAAA,0CAAA,EAA6CK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,KAAA,EAAQU,CAAAA,CAAI,OAAO,CAAA,CAAA","file":"/home/runner/work/cli/cli/dist/chunk-K4TIJ3VM.cjs","sourcesContent":[null,"import { mapSeries } from 'bluebird';\nimport {\n buildTranscendGraphQLClientGeneric,\n loginUser,\n createApiKey,\n fetchAllApiKeys,\n deleteApiKey,\n assumeRole,\n} from '../graphql';\nimport { ScopeName } from '@transcend-io/privacy-types';\nimport colors from 'colors';\nimport { StoredApiKey } from '../../codecs';\nimport { logger } from '../../logger';\nimport { DEFAULT_TRANSCEND_API } from '../../constants';\n\nexport interface ApiKeyGenerateError {\n /** Name of instance */\n organizationName: string;\n /** Error */\n error: string;\n /** Organization ID API key is for */\n organizationId: string;\n}\n\n/**\n * Generate API keys across multiple transcend accounts\n *\n * @param options - Options\n * @returns Number of API keys created\n */\nexport async function generateCrossAccountApiKeys({\n email,\n password,\n scopes,\n apiKeyTitle,\n parentOrganizationId,\n deleteExistingApiKey = true,\n createNewApiKey = true,\n transcendUrl = DEFAULT_TRANSCEND_API,\n}: {\n /** Email address of user generating API keys */\n email: string;\n /** Password of user generating API keys */\n password: string;\n /** Filter for organizations that match this parent organization ID */\n parentOrganizationId?: string;\n /** Title of the API create to create */\n apiKeyTitle: string;\n /** Title of the API create to create */\n scopes: ScopeName[];\n /** API URL for Transcend backend */\n transcendUrl?: string;\n /** When true delete existing API keys with that title, if set to false an API key exists with that title, an error is thrown */\n deleteExistingApiKey?: boolean;\n /** When true, generate new API keys, otherwise only will delete past API keys */\n createNewApiKey?: boolean;\n}): Promise<{\n /** Successfully generated */\n apiKeys: StoredApiKey[];\n /** Error results */\n errors: ApiKeyGenerateError[];\n}> {\n // Create GraphQL client\n const client = await buildTranscendGraphQLClientGeneric(transcendUrl, {});\n\n // Login the user\n logger.info(colors.magenta('Logging in using email and password.'));\n const { roles, loginCookie } = await loginUser(client, { email, password });\n logger.info(\n colors.green(\n `Successfully logged in and found ${roles.length} role${\n roles.length === 1 ? '' : 's'\n }!`,\n ),\n );\n\n // Filter down by parentOrganizationId\n const filteredRoles = parentOrganizationId\n ? roles.filter(\n (role) =>\n role.organization.id === parentOrganizationId ||\n role.organization.parentOrganizationId === parentOrganizationId,\n )\n : roles;\n\n // Save cookie to call route subsequent times\n client.setHeaders({\n Cookie: loginCookie,\n });\n\n // Save the resulting API keys\n const results: StoredApiKey[] = [];\n const errors: ApiKeyGenerateError[] = [];\n\n // Generate API keys\n logger.info(\n colors.magenta(\n `Generating API keys with title: ${apiKeyTitle}, scopes: ${scopes.join(\n ',',\n )}.`,\n ),\n );\n\n // Map over each role\n await mapSeries(filteredRoles, async (role) => {\n try {\n // Log into the other instance\n await assumeRole(client, { roleId: role.id, email });\n\n // Grab API keys with that title\n logger.info(\n colors.magenta(\n `Checking if API key already exists in organization \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n\n // Delete existing API key\n const [apiKeyWithTitle] = await fetchAllApiKeys(client, [apiKeyTitle]);\n if (apiKeyWithTitle && deleteExistingApiKey) {\n logger.info(\n colors.yellow(\n `Deleting existing API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n await deleteApiKey(client, apiKeyWithTitle.id);\n logger.info(\n colors.green(\n `Successfully deleted API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n } else if (apiKeyWithTitle) {\n // throw error if one exists but not configured to delete\n throw new Error(`API key already exists with title: \"${apiKeyTitle}\"`);\n }\n\n // Create the API key\n if (createNewApiKey) {\n logger.info(\n colors.magenta(\n `Creating API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n const { apiKey } = await createApiKey(client, {\n title: apiKeyTitle,\n scopes,\n });\n results.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n apiKey,\n });\n logger.info(\n colors.green(\n `Successfully created API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n } else {\n // Delete only\n results.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n apiKey: '',\n });\n }\n } catch (err) {\n logger.error(\n colors.red(\n `Failed to create API key in organization \"${role.organization.name}\"! - ${err.message}`,\n ),\n );\n errors.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n error: err.message,\n });\n }\n });\n logger.info(\n colors.green(\n `Successfully created ${results.length} API key${\n results.length === 1 ? '' : 's'\n }`,\n ),\n );\n\n if (errors.length > 0) {\n logger.error(\n colors.red(\n `Failed to create ${errors.length} API key${\n errors.length === 1 ? '' : 's'\n }!`,\n ),\n );\n }\n\n return { errors, apiKeys: results };\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-GDNSAJQN.cjs","../src/lib/api-keys/generateCrossAccountApiKeys.ts"],"names":["generateCrossAccountApiKeys","email","password","scopes","apiKeyTitle","parentOrganizationId","deleteExistingApiKey","createNewApiKey","transcendUrl","DEFAULT_TRANSCEND_API","client","buildTranscendGraphQLClientGeneric","logger","colors","roles","loginCookie","loginUser","filteredRoles","role","results","errors","mapSeries","assumeRole","apiKeyWithTitle","fetchAllApiKeys","deleteApiKey","apiKey","createApiKey","err"],"mappings":"AAAA,mfAAyC,wDAAkF,wDAAyC,wDAAyC,oCCAnL,gFAUP,MAoBnB,SAAsBA,CAAAA,CAA4B,CAChD,KAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,MAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,oBAAA,CAAAC,CAAAA,CACA,oBAAA,CAAAC,CAAAA,CAAuB,CAAA,CAAA,CACvB,eAAA,CAAAC,CAAAA,CAAkB,CAAA,CAAA,CAClB,YAAA,CAAAC,CAAAA,CAAeC,mBACjB,CAAA,CAsBG,CAED,IAAMC,CAAAA,CAAS,MAAMC,kCAAAA,CAAmCH,CAAc,CAAC,CAAC,CAAA,CAGxEI,mBAAAA,CAAO,IAAA,CAAKC,gBAAAA,CAAO,OAAA,CAAQ,sCAAsC,CAAC,CAAA,CAClE,GAAM,CAAE,KAAA,CAAAC,CAAAA,CAAO,WAAA,CAAAC,CAAY,CAAA,CAAI,MAAMC,kCAAAA,CAAUN,CAAQ,CAAE,KAAA,CAAAT,CAAAA,CAAO,QAAA,CAAAC,CAAS,CAAC,CAAA,CAC1EU,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,KAAA,CACL,CAAA,iCAAA,EAAoCC,CAAAA,CAAM,MAAM,CAAA,KAAA,EAC9CA,CAAAA,CAAM,MAAA,GAAW,CAAA,CAAI,EAAA,CAAK,GAC5B,CAAA,CAAA,CACF,CACF,CAAA,CAGA,IAAMG,CAAAA,CAAgBZ,CAAAA,CAClBS,CAAAA,CAAM,MAAA,CACHI,CAAAA,EACCA,CAAAA,CAAK,YAAA,CAAa,EAAA,GAAOb,CAAAA,EACzBa,CAAAA,CAAK,YAAA,CAAa,oBAAA,GAAyBb,CAC/C,CAAA,CACAS,CAAAA,CAGJJ,CAAAA,CAAO,UAAA,CAAW,CAChB,MAAA,CAAQK,CACV,CAAC,CAAA,CAGD,IAAMI,CAAAA,CAA0B,CAAC,CAAA,CAC3BC,CAAAA,CAAgC,CAAC,CAAA,CAGvC,OAAAR,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,OAAA,CACL,CAAA,gCAAA,EAAmCT,CAAW,CAAA,UAAA,EAAaD,CAAAA,CAAO,IAAA,CAChE,GACF,CAAC,CAAA,CAAA,CACH,CACF,CAAA,CAGA,MAAMkB,iCAAAA,CAAUJ,CAAe,MAAOC,CAAAA,EAAS,CAC7C,GAAI,CAEF,MAAMI,kCAAAA,CAAWZ,CAAQ,CAAE,MAAA,CAAQQ,CAAAA,CAAK,EAAA,CAAI,KAAA,CAAAjB,CAAM,CAAC,CAAA,CAGnDW,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,OAAA,CACL,CAAA,oDAAA,EAAuDK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,eAAA,EAAkBd,CAAW,CAAA,EAAA,CAC5G,CACF,CAAA,CAGA,GAAM,CAACmB,CAAe,CAAA,CAAI,MAAMC,kCAAAA,CAAgBd,CAAQ,CAACN,CAAW,CAAC,CAAA,CACrE,EAAA,CAAImB,CAAAA,EAAmBjB,CAAAA,CACrBM,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,MAAA,CACL,CAAA,8BAAA,EAAiCK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,eAAA,EAAkBd,CAAW,CAAA,EAAA,CACtF,CACF,CAAA,CACA,MAAMqB,kCAAAA,CAAaf,CAAQa,CAAAA,CAAgB,EAAE,CAAA,CAC7CX,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,KAAA,CACL,CAAA,iCAAA,EAAoCK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,eAAA,EAAkBd,CAAW,CAAA,EAAA,CACzF,CACF,CAAA,CAAA,KAAA,EAAA,CACSmB,CAAAA,CAET,MAAM,IAAI,KAAA,CAAM,CAAA,oCAAA,EAAuCnB,CAAW,CAAA,CAAA,CAAG,CAAA,CAIvE,EAAA,CAAIG,CAAAA,CAAiB,CACnBK,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,OAAA,CACL,CAAA,qBAAA,EAAwBK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,eAAA,EAAkBd,CAAW,CAAA,EAAA,CAC7E,CACF,CAAA,CACA,GAAM,CAAE,MAAA,CAAAsB,CAAO,CAAA,CAAI,MAAMC,kCAAAA,CAAajB,CAAQ,CAC5C,KAAA,CAAON,CAAAA,CACP,MAAA,CAAAD,CACF,CAAC,CAAA,CACDgB,CAAAA,CAAQ,IAAA,CAAK,CACX,gBAAA,CAAkBD,CAAAA,CAAK,YAAA,CAAa,IAAA,CACpC,cAAA,CAAgBA,CAAAA,CAAK,YAAA,CAAa,EAAA,CAClC,MAAA,CAAAQ,CACF,CAAC,CAAA,CACDd,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,KAAA,CACL,CAAA,iCAAA,EAAoCK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,eAAA,EAAkBd,CAAW,CAAA,EAAA,CACzF,CACF,CACF,CAAA,KAEEe,CAAAA,CAAQ,IAAA,CAAK,CACX,gBAAA,CAAkBD,CAAAA,CAAK,YAAA,CAAa,IAAA,CACpC,cAAA,CAAgBA,CAAAA,CAAK,YAAA,CAAa,EAAA,CAClC,MAAA,CAAQ,EACV,CAAC,CAEL,CAAA,KAAA,CAASU,CAAAA,CAAK,CACZhB,mBAAAA,CAAO,KAAA,CACLC,gBAAAA,CAAO,GAAA,CACL,CAAA,0CAAA,EAA6CK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,KAAA,EAAQU,CAAAA,CAAI,OAAO,CAAA,CAAA","file":"/home/runner/work/cli/cli/dist/chunk-GDNSAJQN.cjs","sourcesContent":[null,"import { mapSeries } from 'bluebird';\nimport {\n buildTranscendGraphQLClientGeneric,\n loginUser,\n createApiKey,\n fetchAllApiKeys,\n deleteApiKey,\n assumeRole,\n} from '../graphql';\nimport { ScopeName } from '@transcend-io/privacy-types';\nimport colors from 'colors';\nimport { StoredApiKey } from '../../codecs';\nimport { logger } from '../../logger';\nimport { DEFAULT_TRANSCEND_API } from '../../constants';\n\nexport interface ApiKeyGenerateError {\n /** Name of instance */\n organizationName: string;\n /** Error */\n error: string;\n /** Organization ID API key is for */\n organizationId: string;\n}\n\n/**\n * Generate API keys across multiple transcend accounts\n *\n * @param options - Options\n * @returns Number of API keys created\n */\nexport async function generateCrossAccountApiKeys({\n email,\n password,\n scopes,\n apiKeyTitle,\n parentOrganizationId,\n deleteExistingApiKey = true,\n createNewApiKey = true,\n transcendUrl = DEFAULT_TRANSCEND_API,\n}: {\n /** Email address of user generating API keys */\n email: string;\n /** Password of user generating API keys */\n password: string;\n /** Filter for organizations that match this parent organization ID */\n parentOrganizationId?: string;\n /** Title of the API create to create */\n apiKeyTitle: string;\n /** Title of the API create to create */\n scopes: ScopeName[];\n /** API URL for Transcend backend */\n transcendUrl?: string;\n /** When true delete existing API keys with that title, if set to false an API key exists with that title, an error is thrown */\n deleteExistingApiKey?: boolean;\n /** When true, generate new API keys, otherwise only will delete past API keys */\n createNewApiKey?: boolean;\n}): Promise<{\n /** Successfully generated */\n apiKeys: StoredApiKey[];\n /** Error results */\n errors: ApiKeyGenerateError[];\n}> {\n // Create GraphQL client\n const client = await buildTranscendGraphQLClientGeneric(transcendUrl, {});\n\n // Login the user\n logger.info(colors.magenta('Logging in using email and password.'));\n const { roles, loginCookie } = await loginUser(client, { email, password });\n logger.info(\n colors.green(\n `Successfully logged in and found ${roles.length} role${\n roles.length === 1 ? '' : 's'\n }!`,\n ),\n );\n\n // Filter down by parentOrganizationId\n const filteredRoles = parentOrganizationId\n ? roles.filter(\n (role) =>\n role.organization.id === parentOrganizationId ||\n role.organization.parentOrganizationId === parentOrganizationId,\n )\n : roles;\n\n // Save cookie to call route subsequent times\n client.setHeaders({\n Cookie: loginCookie,\n });\n\n // Save the resulting API keys\n const results: StoredApiKey[] = [];\n const errors: ApiKeyGenerateError[] = [];\n\n // Generate API keys\n logger.info(\n colors.magenta(\n `Generating API keys with title: ${apiKeyTitle}, scopes: ${scopes.join(\n ',',\n )}.`,\n ),\n );\n\n // Map over each role\n await mapSeries(filteredRoles, async (role) => {\n try {\n // Log into the other instance\n await assumeRole(client, { roleId: role.id, email });\n\n // Grab API keys with that title\n logger.info(\n colors.magenta(\n `Checking if API key already exists in organization \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n\n // Delete existing API key\n const [apiKeyWithTitle] = await fetchAllApiKeys(client, [apiKeyTitle]);\n if (apiKeyWithTitle && deleteExistingApiKey) {\n logger.info(\n colors.yellow(\n `Deleting existing API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n await deleteApiKey(client, apiKeyWithTitle.id);\n logger.info(\n colors.green(\n `Successfully deleted API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n } else if (apiKeyWithTitle) {\n // throw error if one exists but not configured to delete\n throw new Error(`API key already exists with title: \"${apiKeyTitle}\"`);\n }\n\n // Create the API key\n if (createNewApiKey) {\n logger.info(\n colors.magenta(\n `Creating API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n const { apiKey } = await createApiKey(client, {\n title: apiKeyTitle,\n scopes,\n });\n results.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n apiKey,\n });\n logger.info(\n colors.green(\n `Successfully created API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n } else {\n // Delete only\n results.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n apiKey: '',\n });\n }\n } catch (err) {\n logger.error(\n colors.red(\n `Failed to create API key in organization \"${role.organization.name}\"! - ${err.message}`,\n ),\n );\n errors.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n error: err.message,\n });\n }\n });\n logger.info(\n colors.green(\n `Successfully created ${results.length} API key${\n results.length === 1 ? '' : 's'\n }`,\n ),\n );\n\n if (errors.length > 0) {\n logger.error(\n colors.red(\n `Failed to create ${errors.length} API key${\n errors.length === 1 ? '' : 's'\n }!`,\n ),\n );\n }\n\n return { errors, apiKeys: results };\n}\n"]}
@@ -1,12 +1,12 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkKUBXRT3Vcjs = require('./chunk-KUBXRT3V.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkEYOQLGDVcjs = require('./chunk-EYOQLGDV.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _bluebird = require('bluebird');var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);var _persistedstate = require('@transcend-io/persisted-state');var _iots = require('io-ts'); var G = _interopRequireWildcard(_iots); var I = _interopRequireWildcard(_iots); var n = _interopRequireWildcard(_iots);var _typeutils = require('@transcend-io/type-utils');var ze=["ENOTFOUND","ECONNRESET","ETIMEDOUT","502 Bad Gateway","504 Gateway Time-out","Task timed out after","unknown request error"].map(a=>a.toLowerCase());async function D(a,{maxAttempts:t=3,baseDelayMs:f=250,isRetryable:u=(d,p)=>ze.some(o=>p.toLowerCase().includes(o)),onRetry:c}={}){let d=0;for(;;){d+=1;try{return await a()}catch(p){let o=_nullishCoalesce((p&&(_optionalChain([p, 'access', _2 => _2.response, 'optionalAccess', _3 => _3.body])||p.message)), () => (String(_nullishCoalesce(p, () => ("Unknown error")))));if(!(d<t&&u(p,o)))throw new Error(`Preference query failed after ${d} attempt(s): ${o}`);_optionalChain([c, 'optionalCall', _4 => _4(d,p,o)]);let r=f*2**(d-1),s=Math.floor(Math.random()*f),e=r+s;_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`[retry] attempt ${d}/${t-1}; backing off ${e}ms: ${o}`)),await _chunkKUBXRT3Vcjs.Xf.call(void 0, e)}}}var _privacytypes = require('@transcend-io/privacy-types');var V=I.intersection([I.type({nodes:I.array(_privacytypes.PreferenceQueryResponseItem)}),I.partial({cursor:I.string})]);async function Se(a,{identifiers:t,partitionKey:f,skipLogging:u=!1,concurrency:c=40}){let d=[],p=_chunkEYOQLGDVcjs.b.call(void 0, t,100),o=new Date().getTime(),i=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic);u||i.start(t.length,0);let r=0;await _bluebird.map.call(void 0, p,async l=>{let y=await D(()=>a.post(`v1/preferences/${f}/query`,{json:{filter:{identifiers:l},limit:l.length}}).json(),{onRetry:(h,C,w)=>{_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`[RETRY] group size=${l.length} partition=${f} attempt=${h}: ${w}`))}}),g=_typeutils.decodeCodec.call(void 0, V,y);d.push(...g.nodes),r+=l.length,i.update(r)},{concurrency:c}),i.stop();let e=new Date().getTime()-o;return u||_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Completed download in "${e/1e3}" seconds.`)),d}function J({row:a,columnToPurposeName:t,purposeSlugs:f,preferenceTopics:u}){let c={};return Object.entries(t).forEach(([d,{purpose:p,preference:o,valueMapping:i}])=>{if(!f.includes(p))throw new Error(`Invalid purpose slug: ${p}, expected: ${f.join(", ")}`);let r=a[d];if(o){let s=u.find(e=>e.slug===o&&e.purpose.trackingType===p);if(!s){let e=u.filter(l=>l.purpose.trackingType===p).map(l=>l.slug);throw new Error(`Invalid preference slug: ${o} for purpose: ${p}. Allowed preference slugs for purpose are: ${e.join(",")}`)}switch(c[p]||(c[p]={preferences:[]}),c[p].preferences||(c[p].preferences=[]),s.type){case _privacytypes.PreferenceTopicType.Boolean:{let e=i[r];if(e===void 0&&r!=="")throw new Error(`No preference mapping found for value "${r}" in column "${d}" (purpose=${p}, preference=${o})`);if(e==null)return;if(typeof e!="boolean")throw new Error(`Invalid value for boolean preference: ${o}, expected boolean, got: ${r}`);c[p].preferences.push({topic:o,choice:{booleanValue:e}});break}case _privacytypes.PreferenceTopicType.Select:{let e=i[r];if(e===void 0&&r!=="")throw new Error(`No preference mapping found for value "${r}" in column "${d}" (purpose=${p}, preference=${o})`);if(e==null)return;if(typeof e!="string")throw new Error(`Invalid value for select preference: ${o}, expected string, got: ${r}`);let l=e.trim()||null;if(l&&!s.preferenceOptionValues.map(({slug:y})=>y).includes(l))throw new Error(`Invalid value for select preference: ${o}, expected one of: ${s.preferenceOptionValues.map(({slug:y})=>y).join(", ")}, got: ${r}`);c[p].preferences.push({topic:o,choice:{selectValue:l}});break}case _privacytypes.PreferenceTopicType.MultiSelect:{if(typeof r!="string")throw new Error(`Invalid value for multi select preference: ${o}, expected string, got: ${r}`);let e=_chunkKUBXRT3Vcjs.oc.call(void 0, r).map(l=>{let y=i[l];if(y===void 0&&r!=="")throw new Error(`No preference mapping found for multi select token "${r}" in column "${d}" (purpose=${p}, preference=${o})`);if(y==null)return null;if(typeof y!="string")throw new Error(`Invalid value for multi select preference: ${o}, expected one of: ${s.preferenceOptionValues.map(({slug:g})=>g).join(", ")}, got: ${l}`);return y}).filter(l=>l!==null).sort((l,y)=>l.localeCompare(y));e.length>0&&c[p].preferences.push({topic:o,choice:{selectValues:e}});break}default:throw new Error(`Unknown preference type: ${s.type}`)}}else{let s=i[r];if(s===void 0&&r!=="")throw new Error(`No preference mapping found for value "${r}" in column "${d}" (purpose=${p}, preference=\u2205)`);if(s===null)return;c[p]?c[p].enabled=s===!0:c[p]={enabled:s===!0}}}),_typeutils.apply.call(void 0, c,(d,p)=>{if(typeof d.enabled!="boolean")throw new Error(`No mapping provided for purpose.enabled=true/false value: ${p}`);return{...d,enabled:d.enabled}})}var _inquirer = require('inquirer'); var _inquirer2 = _interopRequireDefault(_inquirer);var H="[NONE]";async function ke(a,t){let f=_chunkEYOQLGDVcjs.j.call(void 0, a.map(c=>Object.keys(c)).flat()),u=_chunkEYOQLGDVcjs.c.call(void 0, f,[...t.identifierColumn?[t.identifierColumn]:[],...Object.keys(t.columnToPurposeName)]);if(!t.timestampColum){let{timestampName:c}=await _inquirer2.default.prompt([{name:"timestampName",message:"Choose the column that will be used as the timestamp of last preference update",type:"list",default:u.find(d=>d.toLowerCase().includes("date"))||u.find(d=>d.toLowerCase().includes("time"))||u[0],choices:[...u,H]}]);t.timestampColum=c}if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Using timestamp column "${t.timestampColum}"`)),t.timestampColum!==H){let c=a.map((d,p)=>d[t.timestampColum]?null:[p]).filter(d=>!!d).flat();if(c.length>0)throw new Error(`The timestamp column "${t.timestampColum}" is missing a value for the following rows: ${c.join(`
2
- `)}`);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`The timestamp column "${t.timestampColum}" is present for all row`))}return t}async function Ie(a,t){let f=_chunkEYOQLGDVcjs.j.call(void 0, a.map(o=>Object.keys(o)).flat()),u=_chunkEYOQLGDVcjs.c.call(void 0, f,[...t.identifierColumn?[t.identifierColumn]:[],...Object.keys(t.columnToPurposeName)]);if(!t.identifierColumn){let{identifierName:o}=await _inquirer2.default.prompt([{name:"identifierName",message:"Choose the column that will be used as the identifier to upload consent preferences by",type:"list",default:u.find(i=>i.toLowerCase().includes("email"))||u[0],choices:u}]);t.identifierColumn=o}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Using identifier column "${t.identifierColumn}"`));let c=a.map((o,i)=>o[t.identifierColumn]?null:[i]).filter(o=>!!o).flat();if(c.length>0){let o=`The identifier column "${t.identifierColumn}" is missing a value for the following rows: ${c.join(", ")}`;if(_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(o)),!await _chunkKUBXRT3Vcjs.Rf.call(void 0, {message:"Would you like to skip rows missing an identifier?"}))throw new Error(o);let r=a.length;a=a.filter(s=>s[t.identifierColumn]),_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Skipped ${r-a.length} rows missing an identifier`))}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`The identifier column "${t.identifierColumn}" is present for all rows`));let d=_chunkEYOQLGDVcjs.d.call(void 0, a,t.identifierColumn),p=Object.entries(d).filter(([,o])=>o.length>1);if(p.length>0){let o=`The identifier column "${t.identifierColumn}" has duplicate values for the following rows: ${p.slice(0,10).map(([r,s])=>`${r} (${s.length})`).join(`
3
- `)}`;if(_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(o)),!await _chunkKUBXRT3Vcjs.Rf.call(void 0, {message:"Would you like to automatically take the latest update?"}))throw new Error(o);a=Object.entries(d).map(([,r])=>r.sort((e,l)=>new Date(l[t.timestampColum]).getTime()-new Date(e[t.timestampColum]).getTime())[0]).filter(r=>r)}return{currentState:t,preferences:a}}async function xe(a,t,{purposeSlugs:f,preferenceTopics:u,forceTriggerWorkflows:c}){let d=_chunkEYOQLGDVcjs.j.call(void 0, a.map(i=>Object.keys(i)).flat()),p=_chunkEYOQLGDVcjs.c.call(void 0, d,[...t.identifierColumn?[t.identifierColumn]:[],...t.timestampColum?[t.timestampColum]:[]]);if(p.length===0){if(c)return t;throw new Error("No other columns to process")}let o=[...f,...u.map(i=>`${i.purpose.trackingType}->${i.slug}`)];return await _bluebird.mapSeries.call(void 0, p,async i=>{let r=_chunkEYOQLGDVcjs.j.call(void 0, a.map(e=>e[i])),s=t.columnToPurposeName[i];if(s)_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Column "${i}" is associated with purpose "${s.purpose}"`));else{let{purposeName:e}=await _inquirer2.default.prompt([{name:"purposeName",message:`Choose the purpose that column ${i} is associated with`,type:"list",default:o.find(g=>g.startsWith(f[0])),choices:o}]),[l,y]=e.split("->");s={purpose:l,preference:y||null,valueMapping:{}}}await _bluebird.mapSeries.call(void 0, r,async e=>{if(s.valueMapping[e]!==void 0){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Value "${e}" is associated with purpose value "${s.valueMapping[e]}"`));return}if(s.preference===null){let{purposeValue:l}=await _inquirer2.default.prompt([{name:"purposeValue",message:`Choose the purpose value for value "${e}" associated with purpose "${s.purpose}"`,type:"confirm",default:e!=="false"}]);s.valueMapping[e]=l}if(s.preference!==null){let l=u.find(g=>g.slug===s.preference);if(!l){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Preference topic "${s.preference}" not found`));return}let y=l.preferenceOptionValues.map(({slug:g})=>g);if(l.type===_privacytypes.PreferenceTopicType.Boolean){let{preferenceValue:g}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${l.slug}" value "${e}" associated with purpose "${s.purpose}"`,type:"confirm",default:e!=="false"}]);s.valueMapping[e]=g;return}if(l.type===_privacytypes.PreferenceTopicType.Select){let{preferenceValue:g}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${l.slug}" value "${e}" associated with purpose "${s.purpose}"`,type:"list",choices:y,default:y.find(h=>h===e)}]);s.valueMapping[e]=g;return}if(l.type===_privacytypes.PreferenceTopicType.MultiSelect){let g=_chunkKUBXRT3Vcjs.oc.call(void 0, e);await _bluebird.mapSeries.call(void 0, g,async h=>{if(s.valueMapping[h]!==void 0)return;let{preferenceValue:C}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${l.slug}" value "${h}" associated with purpose "${s.purpose}"`,type:"list",choices:y,default:y.find(w=>w===h)}]);s.valueMapping[h]=C});return}throw new Error(`Unknown preference topic type: ${l.type}`)}}),t.columnToPurposeName[i]=s}),t}function Re({currentConsentRecord:a,pendingUpdates:t,preferenceTopics:f}){return Object.entries(t).every(([u,{preferences:c=[],enabled:d}])=>{let p=a.purposes.find(i=>i.purpose===u);return!!p&&p.enabled===d?c.every(({topic:i,choice:r})=>p.preferences&&p.preferences.find(s=>{if(s.topic!==i)return!1;let e=f.find(l=>l.slug===i&&l.purpose.trackingType===u);if(!e)throw new Error(`Could not find preference topic for ${i}`);switch(e.type){case _privacytypes.PreferenceTopicType.Boolean:return s.choice.booleanValue===r.booleanValue;case _privacytypes.PreferenceTopicType.Select:return s.choice.selectValue===r.selectValue;case _privacytypes.PreferenceTopicType.MultiSelect:let l=(s.choice.selectValues||[]).sort(),y=(r.selectValues||[]).sort();return l.length===y.length&&l.every((g,h)=>g===y[h]);default:throw new Error(`Unknown preference topic type: ${e.type}`)}})):!1})}function Fe({currentConsentRecord:a,pendingUpdates:t,preferenceTopics:f,log:u}){return!!Object.entries(t).find(([c,{preferences:d=[],enabled:p}])=>{let o=a.purposes.find(i=>i.purpose===c);return o?o.enabled!==p?(u&&_chunkZUNVPK23cjs.a.warn(`Purpose ${c} enabled value conflict for user ${a.userId}. Pending Value: ${p}, Current Value: ${o.enabled}`),!0):!!d.find(({topic:i,choice:r})=>{let s=(o.preferences||[]).find(g=>g.topic===i);if(!s)return u&&_chunkZUNVPK23cjs.a.warn(`No existing preference found for topic ${i} in purpose ${c} for user ${a.userId}.`),!1;let e=f.find(g=>g.slug===i&&g.purpose.trackingType===c);if(!e)throw new Error(`Could not find preference topic for ${i}`);let l,y;switch(e.type){case _privacytypes.PreferenceTopicType.Boolean:return l=s.choice.booleanValue!==r.booleanValue,u&&_chunkZUNVPK23cjs.a.warn(`Preference topic ${i} boolean value conflict for user ${a.userId}. Expected: ${r.booleanValue}, Found: ${s.choice.booleanValue}`),l;case _privacytypes.PreferenceTopicType.Select:return y=s.choice.selectValue!==r.selectValue,u&&_chunkZUNVPK23cjs.a.warn(`Preference topic ${i} select value conflict for user ${a.userId}. Expected: ${r.selectValue}, Found: ${s.choice.selectValue}`),y;case _privacytypes.PreferenceTopicType.MultiSelect:let g=(s.choice.selectValues||[]).sort(),h=(r.selectValues||[]).sort();return y=g.length!==h.length||!g.every((C,w)=>C===h[w]),u&&_chunkZUNVPK23cjs.a.warn(`Preference topic ${i} multi-select value conflict for user ${a.userId}. Expected: ${h.join(", ")}, Found: ${g.join(", ")}`),y;default:throw new Error(`Unknown preference topic type: ${e.type}`)}}):(u&&_chunkZUNVPK23cjs.a.warn(`No existing purpose found for ${c} in consent record for ${a.userId}.`),!1)})}async function ve({file:a,sombra:t,purposeSlugs:f,preferenceTopics:u,partitionKey:c,skipExistingRecordCheck:d,forceTriggerWorkflows:p},o){let i=new Date().getTime(),r=o.getValue("fileMetadata");_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading in file: "${a}"`));let s=_chunkKUBXRT3Vcjs.rc.call(void 0, a,G.record(G.string,G.string)),e={columnToPurposeName:{},pendingSafeUpdates:{},pendingConflictUpdates:{},skippedUpdates:{},...r[a]||{},lastFetchedAt:new Date().toISOString()};e=await ke(s,e),r[a]=e,await o.setValue(r,"fileMetadata");let l=await Ie(s,e);e=l.currentState,s=l.preferences,r[a]=e,await o.setValue(r,"fileMetadata"),e=await xe(s,e,{preferenceTopics:u,purposeSlugs:f,forceTriggerWorkflows:p}),r[a]=e,await o.setValue(r,"fileMetadata");let y=s.map(w=>w[e.identifierColumn]),g=d?[]:await Se(t,{identifiers:y.map(w=>({value:w})),partitionKey:c}),h=_chunkEYOQLGDVcjs.e.call(void 0, g,"userId");e.pendingConflictUpdates={},e.pendingSafeUpdates={},e.skippedUpdates={},s.forEach(w=>{let P=w[e.identifierColumn],b=J({row:w,columnToPurposeName:e.columnToPurposeName,preferenceTopics:u,purposeSlugs:f}),S=h[P];if(p&&!S)throw new Error(`No existing consent record found for user with id: ${P}.
4
- When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`);if(S&&Re({currentConsentRecord:S,pendingUpdates:b,preferenceTopics:u})&&!p){e.skippedUpdates[P]=w;return}if(S&&Fe({currentConsentRecord:S,pendingUpdates:b,preferenceTopics:u})){e.pendingConflictUpdates[P]={row:w,record:S};return}e.pendingSafeUpdates[P]=w}),r[a]=e,await o.setValue(r,"fileMetadata");let C=new Date().getTime();_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pre-processed file: "${a}" in ${(C-i)/1e3}s`))}var De=n.type({purpose:n.string,preference:n.union([n.string,n.null]),valueMapping:n.record(n.string,n.union([n.string,n.boolean,n.null,n.undefined]))}),Pr=n.record(n.string,De),et=n.type({name:n.string,isUniqueOnPreferenceStore:n.boolean}),$r=n.record(n.string,et),tt=n.intersection([n.type({columnToPurposeName:n.record(n.string,De),lastFetchedAt:n.string,pendingSafeUpdates:n.record(n.string,n.record(n.string,n.string)),pendingConflictUpdates:n.record(n.string,n.type({record:_privacytypes.PreferenceQueryResponseItem,row:n.record(n.string,n.string)})),skippedUpdates:n.record(n.string,n.record(n.string,n.string))}),n.partial({identifierColumn:n.string,timestampColum:n.string})]),br=n.record(n.string,n.union([n.boolean,_privacytypes.PreferenceUpdateItem])),Cr=n.record(n.string,n.union([n.boolean,n.record(n.string,n.string)])),Tr=n.record(n.string,n.type({uploadedAt:n.string,error:n.string,update:_privacytypes.PreferenceUpdateItem})),Sr=n.record(n.string,n.type({record:_privacytypes.PreferenceQueryResponseItem,row:n.record(n.string,n.string)})),Mr=n.record(n.string,n.record(n.string,n.string)),Ve=n.type({fileMetadata:n.record(n.string,tt),failingUpdates:n.record(n.string,n.type({uploadedAt:n.string,error:n.string,update:_privacytypes.PreferenceUpdateItem})),pendingUpdates:n.record(n.string,_privacytypes.PreferenceUpdateItem)});async function Gr({auth:a,sombraAuth:t,receiptFilepath:f,file:u,partition:c,isSilent:d=!0,dryRun:p=!1,skipWorkflowTriggers:o=!1,skipConflictUpdates:i=!1,skipExistingRecordCheck:r=!1,attributes:s=[],transcendUrl:e,forceTriggerWorkflows:l=!1}){let y=_chunkKUBXRT3Vcjs.qc.call(void 0, s),g=new (0, _persistedstate.PersistedState)(f,Ve,{fileMetadata:{},failingUpdates:{},pendingUpdates:{}}),h=g.getValue("failingUpdates"),C=g.getValue("pendingUpdates"),w=g.getValue("fileMetadata");_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Restored cache, there are:
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkNBXAOUWCcjs = require('./chunk-NBXAOUWC.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkF7QE6D3Tcjs = require('./chunk-F7QE6D3T.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _bluebird = require('bluebird');var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);var _persistedstate = require('@transcend-io/persisted-state');var _iots = require('io-ts'); var G = _interopRequireWildcard(_iots); var I = _interopRequireWildcard(_iots); var n = _interopRequireWildcard(_iots);var _typeutils = require('@transcend-io/type-utils');var ze=["ENOTFOUND","ECONNRESET","ETIMEDOUT","502 Bad Gateway","504 Gateway Time-out","Task timed out after","unknown request error"].map(a=>a.toLowerCase());async function D(a,{maxAttempts:t=3,baseDelayMs:f=250,isRetryable:u=(d,p)=>ze.some(o=>p.toLowerCase().includes(o)),onRetry:c}={}){let d=0;for(;;){d+=1;try{return await a()}catch(p){let o=_nullishCoalesce((p&&(_optionalChain([p, 'access', _2 => _2.response, 'optionalAccess', _3 => _3.body])||p.message)), () => (String(_nullishCoalesce(p, () => ("Unknown error")))));if(!(d<t&&u(p,o)))throw new Error(`Preference query failed after ${d} attempt(s): ${o}`);_optionalChain([c, 'optionalCall', _4 => _4(d,p,o)]);let r=f*2**(d-1),s=Math.floor(Math.random()*f),e=r+s;_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`[retry] attempt ${d}/${t-1}; backing off ${e}ms: ${o}`)),await _chunkNBXAOUWCcjs.Zf.call(void 0, e)}}}var _privacytypes = require('@transcend-io/privacy-types');var V=I.intersection([I.type({nodes:I.array(_privacytypes.PreferenceQueryResponseItem)}),I.partial({cursor:I.string})]);async function Se(a,{identifiers:t,partitionKey:f,skipLogging:u=!1,concurrency:c=40}){let d=[],p=_chunkF7QE6D3Tcjs.b.call(void 0, t,100),o=new Date().getTime(),i=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic);u||i.start(t.length,0);let r=0;await _bluebird.map.call(void 0, p,async l=>{let y=await D(()=>a.post(`v1/preferences/${f}/query`,{json:{filter:{identifiers:l},limit:l.length}}).json(),{onRetry:(h,C,w)=>{_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`[RETRY] group size=${l.length} partition=${f} attempt=${h}: ${w}`))}}),g=_typeutils.decodeCodec.call(void 0, V,y);d.push(...g.nodes),r+=l.length,i.update(r)},{concurrency:c}),i.stop();let e=new Date().getTime()-o;return u||_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Completed download in "${e/1e3}" seconds.`)),d}function J({row:a,columnToPurposeName:t,purposeSlugs:f,preferenceTopics:u}){let c={};return Object.entries(t).forEach(([d,{purpose:p,preference:o,valueMapping:i}])=>{if(!f.includes(p))throw new Error(`Invalid purpose slug: ${p}, expected: ${f.join(", ")}`);let r=a[d];if(o){let s=u.find(e=>e.slug===o&&e.purpose.trackingType===p);if(!s){let e=u.filter(l=>l.purpose.trackingType===p).map(l=>l.slug);throw new Error(`Invalid preference slug: ${o} for purpose: ${p}. Allowed preference slugs for purpose are: ${e.join(",")}`)}switch(c[p]||(c[p]={preferences:[]}),c[p].preferences||(c[p].preferences=[]),s.type){case _privacytypes.PreferenceTopicType.Boolean:{let e=i[r];if(e===void 0&&r!=="")throw new Error(`No preference mapping found for value "${r}" in column "${d}" (purpose=${p}, preference=${o})`);if(e==null)return;if(typeof e!="boolean")throw new Error(`Invalid value for boolean preference: ${o}, expected boolean, got: ${r}`);c[p].preferences.push({topic:o,choice:{booleanValue:e}});break}case _privacytypes.PreferenceTopicType.Select:{let e=i[r];if(e===void 0&&r!=="")throw new Error(`No preference mapping found for value "${r}" in column "${d}" (purpose=${p}, preference=${o})`);if(e==null)return;if(typeof e!="string")throw new Error(`Invalid value for select preference: ${o}, expected string, got: ${r}`);let l=e.trim()||null;if(l&&!s.preferenceOptionValues.map(({slug:y})=>y).includes(l))throw new Error(`Invalid value for select preference: ${o}, expected one of: ${s.preferenceOptionValues.map(({slug:y})=>y).join(", ")}, got: ${r}`);c[p].preferences.push({topic:o,choice:{selectValue:l}});break}case _privacytypes.PreferenceTopicType.MultiSelect:{if(typeof r!="string")throw new Error(`Invalid value for multi select preference: ${o}, expected string, got: ${r}`);let e=_chunkNBXAOUWCcjs.pc.call(void 0, r).map(l=>{let y=i[l];if(y===void 0&&r!=="")throw new Error(`No preference mapping found for multi select token "${r}" in column "${d}" (purpose=${p}, preference=${o})`);if(y==null)return null;if(typeof y!="string")throw new Error(`Invalid value for multi select preference: ${o}, expected one of: ${s.preferenceOptionValues.map(({slug:g})=>g).join(", ")}, got: ${l}`);return y}).filter(l=>l!==null).sort((l,y)=>l.localeCompare(y));e.length>0&&c[p].preferences.push({topic:o,choice:{selectValues:e}});break}default:throw new Error(`Unknown preference type: ${s.type}`)}}else{let s=i[r];if(s===void 0&&r!=="")throw new Error(`No preference mapping found for value "${r}" in column "${d}" (purpose=${p}, preference=\u2205)`);if(s===null)return;c[p]?c[p].enabled=s===!0:c[p]={enabled:s===!0}}}),_typeutils.apply.call(void 0, c,(d,p)=>{if(typeof d.enabled!="boolean")throw new Error(`No mapping provided for purpose.enabled=true/false value: ${p}`);return{...d,enabled:d.enabled}})}var _inquirer = require('inquirer'); var _inquirer2 = _interopRequireDefault(_inquirer);var H="[NONE]";async function ke(a,t){let f=_chunkF7QE6D3Tcjs.j.call(void 0, a.map(c=>Object.keys(c)).flat()),u=_chunkF7QE6D3Tcjs.c.call(void 0, f,[...t.identifierColumn?[t.identifierColumn]:[],...Object.keys(t.columnToPurposeName)]);if(!t.timestampColum){let{timestampName:c}=await _inquirer2.default.prompt([{name:"timestampName",message:"Choose the column that will be used as the timestamp of last preference update",type:"list",default:u.find(d=>d.toLowerCase().includes("date"))||u.find(d=>d.toLowerCase().includes("time"))||u[0],choices:[...u,H]}]);t.timestampColum=c}if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Using timestamp column "${t.timestampColum}"`)),t.timestampColum!==H){let c=a.map((d,p)=>d[t.timestampColum]?null:[p]).filter(d=>!!d).flat();if(c.length>0)throw new Error(`The timestamp column "${t.timestampColum}" is missing a value for the following rows: ${c.join(`
2
+ `)}`);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`The timestamp column "${t.timestampColum}" is present for all row`))}return t}async function Ie(a,t){let f=_chunkF7QE6D3Tcjs.j.call(void 0, a.map(o=>Object.keys(o)).flat()),u=_chunkF7QE6D3Tcjs.c.call(void 0, f,[...t.identifierColumn?[t.identifierColumn]:[],...Object.keys(t.columnToPurposeName)]);if(!t.identifierColumn){let{identifierName:o}=await _inquirer2.default.prompt([{name:"identifierName",message:"Choose the column that will be used as the identifier to upload consent preferences by",type:"list",default:u.find(i=>i.toLowerCase().includes("email"))||u[0],choices:u}]);t.identifierColumn=o}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Using identifier column "${t.identifierColumn}"`));let c=a.map((o,i)=>o[t.identifierColumn]?null:[i]).filter(o=>!!o).flat();if(c.length>0){let o=`The identifier column "${t.identifierColumn}" is missing a value for the following rows: ${c.join(", ")}`;if(_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(o)),!await _chunkNBXAOUWCcjs.Tf.call(void 0, {message:"Would you like to skip rows missing an identifier?"}))throw new Error(o);let r=a.length;a=a.filter(s=>s[t.identifierColumn]),_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Skipped ${r-a.length} rows missing an identifier`))}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`The identifier column "${t.identifierColumn}" is present for all rows`));let d=_chunkF7QE6D3Tcjs.d.call(void 0, a,t.identifierColumn),p=Object.entries(d).filter(([,o])=>o.length>1);if(p.length>0){let o=`The identifier column "${t.identifierColumn}" has duplicate values for the following rows: ${p.slice(0,10).map(([r,s])=>`${r} (${s.length})`).join(`
3
+ `)}`;if(_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(o)),!await _chunkNBXAOUWCcjs.Tf.call(void 0, {message:"Would you like to automatically take the latest update?"}))throw new Error(o);a=Object.entries(d).map(([,r])=>r.sort((e,l)=>new Date(l[t.timestampColum]).getTime()-new Date(e[t.timestampColum]).getTime())[0]).filter(r=>r)}return{currentState:t,preferences:a}}async function xe(a,t,{purposeSlugs:f,preferenceTopics:u,forceTriggerWorkflows:c}){let d=_chunkF7QE6D3Tcjs.j.call(void 0, a.map(i=>Object.keys(i)).flat()),p=_chunkF7QE6D3Tcjs.c.call(void 0, d,[...t.identifierColumn?[t.identifierColumn]:[],...t.timestampColum?[t.timestampColum]:[]]);if(p.length===0){if(c)return t;throw new Error("No other columns to process")}let o=[...f,...u.map(i=>`${i.purpose.trackingType}->${i.slug}`)];return await _bluebird.mapSeries.call(void 0, p,async i=>{let r=_chunkF7QE6D3Tcjs.j.call(void 0, a.map(e=>e[i])),s=t.columnToPurposeName[i];if(s)_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Column "${i}" is associated with purpose "${s.purpose}"`));else{let{purposeName:e}=await _inquirer2.default.prompt([{name:"purposeName",message:`Choose the purpose that column ${i} is associated with`,type:"list",default:o.find(g=>g.startsWith(f[0])),choices:o}]),[l,y]=e.split("->");s={purpose:l,preference:y||null,valueMapping:{}}}await _bluebird.mapSeries.call(void 0, r,async e=>{if(s.valueMapping[e]!==void 0){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Value "${e}" is associated with purpose value "${s.valueMapping[e]}"`));return}if(s.preference===null){let{purposeValue:l}=await _inquirer2.default.prompt([{name:"purposeValue",message:`Choose the purpose value for value "${e}" associated with purpose "${s.purpose}"`,type:"confirm",default:e!=="false"}]);s.valueMapping[e]=l}if(s.preference!==null){let l=u.find(g=>g.slug===s.preference);if(!l){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Preference topic "${s.preference}" not found`));return}let y=l.preferenceOptionValues.map(({slug:g})=>g);if(l.type===_privacytypes.PreferenceTopicType.Boolean){let{preferenceValue:g}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${l.slug}" value "${e}" associated with purpose "${s.purpose}"`,type:"confirm",default:e!=="false"}]);s.valueMapping[e]=g;return}if(l.type===_privacytypes.PreferenceTopicType.Select){let{preferenceValue:g}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${l.slug}" value "${e}" associated with purpose "${s.purpose}"`,type:"list",choices:y,default:y.find(h=>h===e)}]);s.valueMapping[e]=g;return}if(l.type===_privacytypes.PreferenceTopicType.MultiSelect){let g=_chunkNBXAOUWCcjs.pc.call(void 0, e);await _bluebird.mapSeries.call(void 0, g,async h=>{if(s.valueMapping[h]!==void 0)return;let{preferenceValue:C}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${l.slug}" value "${h}" associated with purpose "${s.purpose}"`,type:"list",choices:y,default:y.find(w=>w===h)}]);s.valueMapping[h]=C});return}throw new Error(`Unknown preference topic type: ${l.type}`)}}),t.columnToPurposeName[i]=s}),t}function Re({currentConsentRecord:a,pendingUpdates:t,preferenceTopics:f}){return Object.entries(t).every(([u,{preferences:c=[],enabled:d}])=>{let p=a.purposes.find(i=>i.purpose===u);return!!p&&p.enabled===d?c.every(({topic:i,choice:r})=>p.preferences&&p.preferences.find(s=>{if(s.topic!==i)return!1;let e=f.find(l=>l.slug===i&&l.purpose.trackingType===u);if(!e)throw new Error(`Could not find preference topic for ${i}`);switch(e.type){case _privacytypes.PreferenceTopicType.Boolean:return s.choice.booleanValue===r.booleanValue;case _privacytypes.PreferenceTopicType.Select:return s.choice.selectValue===r.selectValue;case _privacytypes.PreferenceTopicType.MultiSelect:let l=(s.choice.selectValues||[]).sort(),y=(r.selectValues||[]).sort();return l.length===y.length&&l.every((g,h)=>g===y[h]);default:throw new Error(`Unknown preference topic type: ${e.type}`)}})):!1})}function Fe({currentConsentRecord:a,pendingUpdates:t,preferenceTopics:f,log:u}){return!!Object.entries(t).find(([c,{preferences:d=[],enabled:p}])=>{let o=a.purposes.find(i=>i.purpose===c);return o?o.enabled!==p?(u&&_chunkZUNVPK23cjs.a.warn(`Purpose ${c} enabled value conflict for user ${a.userId}. Pending Value: ${p}, Current Value: ${o.enabled}`),!0):!!d.find(({topic:i,choice:r})=>{let s=(o.preferences||[]).find(g=>g.topic===i);if(!s)return u&&_chunkZUNVPK23cjs.a.warn(`No existing preference found for topic ${i} in purpose ${c} for user ${a.userId}.`),!1;let e=f.find(g=>g.slug===i&&g.purpose.trackingType===c);if(!e)throw new Error(`Could not find preference topic for ${i}`);let l,y;switch(e.type){case _privacytypes.PreferenceTopicType.Boolean:return l=s.choice.booleanValue!==r.booleanValue,u&&_chunkZUNVPK23cjs.a.warn(`Preference topic ${i} boolean value conflict for user ${a.userId}. Expected: ${r.booleanValue}, Found: ${s.choice.booleanValue}`),l;case _privacytypes.PreferenceTopicType.Select:return y=s.choice.selectValue!==r.selectValue,u&&_chunkZUNVPK23cjs.a.warn(`Preference topic ${i} select value conflict for user ${a.userId}. Expected: ${r.selectValue}, Found: ${s.choice.selectValue}`),y;case _privacytypes.PreferenceTopicType.MultiSelect:let g=(s.choice.selectValues||[]).sort(),h=(r.selectValues||[]).sort();return y=g.length!==h.length||!g.every((C,w)=>C===h[w]),u&&_chunkZUNVPK23cjs.a.warn(`Preference topic ${i} multi-select value conflict for user ${a.userId}. Expected: ${h.join(", ")}, Found: ${g.join(", ")}`),y;default:throw new Error(`Unknown preference topic type: ${e.type}`)}}):(u&&_chunkZUNVPK23cjs.a.warn(`No existing purpose found for ${c} in consent record for ${a.userId}.`),!1)})}async function ve({file:a,sombra:t,purposeSlugs:f,preferenceTopics:u,partitionKey:c,skipExistingRecordCheck:d,forceTriggerWorkflows:p},o){let i=new Date().getTime(),r=o.getValue("fileMetadata");_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading in file: "${a}"`));let s=_chunkNBXAOUWCcjs.sc.call(void 0, a,G.record(G.string,G.string)),e={columnToPurposeName:{},pendingSafeUpdates:{},pendingConflictUpdates:{},skippedUpdates:{},...r[a]||{},lastFetchedAt:new Date().toISOString()};e=await ke(s,e),r[a]=e,await o.setValue(r,"fileMetadata");let l=await Ie(s,e);e=l.currentState,s=l.preferences,r[a]=e,await o.setValue(r,"fileMetadata"),e=await xe(s,e,{preferenceTopics:u,purposeSlugs:f,forceTriggerWorkflows:p}),r[a]=e,await o.setValue(r,"fileMetadata");let y=s.map(w=>w[e.identifierColumn]),g=d?[]:await Se(t,{identifiers:y.map(w=>({value:w})),partitionKey:c}),h=_chunkF7QE6D3Tcjs.e.call(void 0, g,"userId");e.pendingConflictUpdates={},e.pendingSafeUpdates={},e.skippedUpdates={},s.forEach(w=>{let P=w[e.identifierColumn],b=J({row:w,columnToPurposeName:e.columnToPurposeName,preferenceTopics:u,purposeSlugs:f}),S=h[P];if(p&&!S)throw new Error(`No existing consent record found for user with id: ${P}.
4
+ When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`);if(S&&Re({currentConsentRecord:S,pendingUpdates:b,preferenceTopics:u})&&!p){e.skippedUpdates[P]=w;return}if(S&&Fe({currentConsentRecord:S,pendingUpdates:b,preferenceTopics:u})){e.pendingConflictUpdates[P]={row:w,record:S};return}e.pendingSafeUpdates[P]=w}),r[a]=e,await o.setValue(r,"fileMetadata");let C=new Date().getTime();_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pre-processed file: "${a}" in ${(C-i)/1e3}s`))}var De=n.type({purpose:n.string,preference:n.union([n.string,n.null]),valueMapping:n.record(n.string,n.union([n.string,n.boolean,n.null,n.undefined]))}),Pr=n.record(n.string,De),et=n.type({name:n.string,isUniqueOnPreferenceStore:n.boolean}),$r=n.record(n.string,et),tt=n.intersection([n.type({columnToPurposeName:n.record(n.string,De),lastFetchedAt:n.string,pendingSafeUpdates:n.record(n.string,n.record(n.string,n.string)),pendingConflictUpdates:n.record(n.string,n.type({record:_privacytypes.PreferenceQueryResponseItem,row:n.record(n.string,n.string)})),skippedUpdates:n.record(n.string,n.record(n.string,n.string))}),n.partial({identifierColumn:n.string,timestampColum:n.string})]),br=n.record(n.string,n.union([n.boolean,_privacytypes.PreferenceUpdateItem])),Cr=n.record(n.string,n.union([n.boolean,n.record(n.string,n.string)])),Tr=n.record(n.string,n.type({uploadedAt:n.string,error:n.string,update:_privacytypes.PreferenceUpdateItem})),Sr=n.record(n.string,n.type({record:_privacytypes.PreferenceQueryResponseItem,row:n.record(n.string,n.string)})),Mr=n.record(n.string,n.record(n.string,n.string)),Ve=n.type({fileMetadata:n.record(n.string,tt),failingUpdates:n.record(n.string,n.type({uploadedAt:n.string,error:n.string,update:_privacytypes.PreferenceUpdateItem})),pendingUpdates:n.record(n.string,_privacytypes.PreferenceUpdateItem)});async function Gr({auth:a,sombraAuth:t,receiptFilepath:f,file:u,partition:c,isSilent:d=!0,dryRun:p=!1,skipWorkflowTriggers:o=!1,skipConflictUpdates:i=!1,skipExistingRecordCheck:r=!1,attributes:s=[],transcendUrl:e,forceTriggerWorkflows:l=!1}){let y=_chunkNBXAOUWCcjs.rc.call(void 0, s),g=new (0, _persistedstate.PersistedState)(f,Ve,{fileMetadata:{},failingUpdates:{},pendingUpdates:{}}),h=g.getValue("failingUpdates"),C=g.getValue("pendingUpdates"),w=g.getValue("fileMetadata");_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Restored cache, there are:
5
5
  ${Object.values(h).length} failing requests to be retried
6
6
  ${Object.values(C).length} pending requests to be processed
7
7
  The following files are stored in cache and will be used:
8
8
  ${Object.keys(w).map(M=>M).join(`
9
9
  `)}
10
10
  The following file will be processed: ${u}
11
- `));let P=_chunkKUBXRT3Vcjs.wc.call(void 0, e,a),[b,S,fe]=await Promise.all([_chunkKUBXRT3Vcjs.xc.call(void 0, e,a,t),l?Promise.resolve([]):_chunkKUBXRT3Vcjs.fd.call(void 0, P),l?Promise.resolve([]):_chunkKUBXRT3Vcjs.bd.call(void 0, P)]);await ve({file:u,purposeSlugs:S.map(M=>M.trackingType),preferenceTopics:fe,sombra:b,partitionKey:c,skipExistingRecordCheck:r,forceTriggerWorkflows:l},g);let Q={};w=g.getValue("fileMetadata");let F=w[u];if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(F.pendingSafeUpdates).length} safe updates in ${u}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(F.pendingConflictUpdates).length} conflict updates in ${u}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(F.skippedUpdates).length} skipped updates in ${u}`)),Object.entries({...F.pendingSafeUpdates,...i?{}:_typeutils.apply.call(void 0, F.pendingConflictUpdates,({row:M})=>M)}).forEach(([M,k])=>{let _=F.timestampColum===H?new Date:new Date(k[F.timestampColum]),O=J({row:k,columnToPurposeName:F.columnToPurposeName,preferenceTopics:fe,purposeSlugs:S.map(N=>N.trackingType)});Q[M]={userId:M,partition:c,timestamp:_.toISOString(),purposes:Object.entries(O).map(([N,_e])=>({..._e,purpose:N,workflowSettings:{attributes:y,isSilent:d,skipWorkflowTrigger:o}}))}}),await g.setValue(Q,"pendingUpdates"),await g.setValue({},"failingUpdates"),p){_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Dry run complete, exiting. ${Object.values(Q).length} pending updates. Check file: ${f}`));return}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Uploading ${Object.values(Q).length} preferences to partition: ${c}`));let Ge=new Date().getTime(),ee=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),me=0,te=Object.entries(Q),qe=_chunkEYOQLGDVcjs.b.call(void 0, te,o?100:10);ee.start(te.length,0),await _bluebird.map.call(void 0, qe,async M=>{try{await b.put("v1/preferences",{json:{records:M.map(([,k])=>k),skipWorkflowTriggers:o,forceTriggerWorkflows:l}}).json()}catch(k){try{let O=JSON.parse(_optionalChain([k, 'optionalAccess', _5 => _5.response, 'optionalAccess', _6 => _6.body])||"{}");O.error&&_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error: ${O.error}`))}catch (e2){}_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to upload ${M.length} user preferences to partition ${c}: ${_optionalChain([k, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.body])||_optionalChain([k, 'optionalAccess', _9 => _9.message])}`));let _=g.getValue("failingUpdates");M.forEach(([O,N])=>{_[O]={uploadedAt:new Date().toISOString(),update:N,error:_optionalChain([k, 'optionalAccess', _10 => _10.response, 'optionalAccess', _11 => _11.body])||_optionalChain([k, 'optionalAccess', _12 => _12.message])||"Unknown error"}}),await g.setValue(_,"failingUpdates")}me+=M.length,ee.update(me)},{concurrency:40}),ee.stop();let Le=new Date().getTime()-Ge;_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully uploaded ${te.length} user preferences to partition ${c} in "${Le/1e3}" seconds!`))}function Lr({identifiers:a=[],purposes:t=[],metadata:f=[],consentManagement:u={},system:c={decryptionStatus:"DECRYPTED"},...d}){let p={...d,...c,...u};if(Array.isArray(a)){let o=new Map;for(let{name:i,value:r}of a)o.has(i)||o.set(i,new Set),r&&o.get(i).add(r);for(let[i,r]of o.entries())p[i]=Array.from(r).join(",")}if(Array.isArray(f)&&(p.metadata=JSON.stringify(f.reduce((o,{key:i,value:r})=>(o[i]=r,o),{}))),Array.isArray(t)){for(let{purpose:o,preferences:i,enabled:r}of t)if(p[o]=!!r,Array.isArray(i))for(let{topic:s,choice:e}of i){let l=`${o}_${s}`,y=null;typeof e.booleanValue=="boolean"?y=e.booleanValue:e.selectValue?y=e.selectValue:Array.isArray(e.selectValues)?y=e.selectValues.filter(h=>h.length>0).join(","):y=null,p[l]=y}}return p}async function*X(a,t,f,u){let c;for(;;){let d={limit:u};f&&Object.keys(f).length&&(d.filter=f),c&&(d.cursor=c);let p=await D(()=>a.post(`v1/preferences/${t}/query`,{json:d}).json(),{onRetry:(r,s,e)=>{_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`Retry attempt ${r} for fetchConsentPreferences due to error: ${e}`))}}),{nodes:o,cursor:i}=_typeutils.decodeCodec.call(void 0, V,p);if(!_optionalChain([o, 'optionalAccess', _13 => _13.length])||(yield o,!i))break;c=i}}function Z(a){return!!a.timestampAfter||!!a.timestampBefore?"timestamp":"updated"}function E(a,t){return a==="timestamp"?new Date(t.timestamp):_optionalChain([t, 'access', _14 => _14.system, 'optionalAccess', _15 => _15.updatedAt])?new Date(t.system.updatedAt):new Date}function Ae(a,t){if(a==="timestamp")return{after:t.timestampAfter?new Date(t.timestampAfter):void 0,before:t.timestampBefore?new Date(t.timestampBefore):void 0};let f=_nullishCoalesce(t.system, () => ({}));return{after:f.updatedAfter?new Date(f.updatedAfter):void 0,before:f.updatedBefore?new Date(f.updatedBefore):void 0}}function q(a,t,f){return a==="timestamp"?{...t,timestampBefore:_nullishCoalesce(f, () => (t.timestampBefore))}:{...t,system:{...t.system||{},...f?{updatedBefore:f}:{}},timestampAfter:void 0,timestampBefore:void 0}}async function L(a,t,f){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Single-record probe with filter: ${JSON.stringify(f)}`));let c=await X(a,t,f,1).next();if(c.done||!c.value||c.value.length===0)return _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("Probe result: no record")),null;let d=c.value[0];return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Probe result: found record at ${E(Z(f),d).toISOString()}`)),d}async function Qe(a,t){let{partition:f,mode:u,baseFilter:c,maxLookbackDays:d=3650}=t,p=await L(a,f,q(u,c));if(!p)return _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("No records found; defaulting earliest day to today.")),_chunkKUBXRT3Vcjs.hg.call(void 0, new Date);let o=E(u,p);_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Newest instant: ${o.toISOString()}`));let i=[1,7,30],r=0,s=i[0]*864e5,e=o,l=null;for(;;){let w=r<i.length?new Date(o.getTime()-i[r]*864e5):new Date(o.getTime()-s);if((_chunkKUBXRT3Vcjs.hg.call(void 0, new Date).getTime()-_chunkKUBXRT3Vcjs.hg.call(void 0, w).getTime())/864e5>d){_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`Exponential jump exceeded maxLookbackDays=${d}. Using current bounds.`)),l=w;break}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Probing before=${w.toISOString()} (jump step ${r<i.length?`${i[r]}d`:`${Math.round(s/864e5)}d`})\u2026`));let b=await L(a,f,q(u,c,w.toISOString()));if(b){e=E(u,b),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Found older record at ${e.toISOString()} \u2014 continue jumping back.`)),r<i.length-1?(r+=1,s=i[r]*864e5):r===i.length-1?(r+=1,s=i[i.length-1]*2*864e5):s*=2;continue}l=w,_chunkZUNVPK23cjs.a.info(_colors2.default.green(`No record before ${w.toISOString()} \u2014 established empty lower bound.`));break}l||(l=new Date(e.getTime()-864e5));let y=l,g=e,h=Math.max(864e5,Math.floor((g.getTime()-y.getTime())/64));_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Exponential forward-from-empty start: empty=${y.toISOString()} found=${g.toISOString()} step=${Math.round(h/864e5)}d`));for(let w=0;w<8;w+=1){let P=new Date(y.getTime()+h);if(P.getTime()>=g.getTime())break;_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Forward gallop probe before=${P.toISOString()}\u2026`));let b=await L(a,f,q(u,c,P.toISOString()));if(b?(g=E(u,b),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Gallop hit at ${g.toISOString()} \u2014 tightening found bound. Next step halves.`)),h=Math.max(864e5,Math.floor(h/2))):(y.setTime(P.getTime()),_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Gallop miss \u2014 advancing empty bound to ${y.toISOString()}. Next step doubles.`)),h=Math.min(g.getTime()-y.getTime(),h*2),h<864e5&&(h=864e5)),g.getTime()-y.getTime()<=864e5)break}for(;g.getTime()-y.getTime()>864e5;){let w=new Date(y.getTime()+Math.floor((g.getTime()-y.getTime())/2));_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Binary probe before=${w.toISOString()}\u2026`));let P=await L(a,f,q(u,c,w.toISOString()));if(P){let b=E(u,P);_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Binary probe found record at ${b.toISOString()}.`)),g=b}else _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("Binary probe found no record.")),y=w}let C=_chunkKUBXRT3Vcjs.hg.call(void 0, g);return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Earliest day (UTC) resolved to ${C.toISOString()} (instant \u2248 ${g.toISOString()}).`)),C}async function Ne(a,t){let{partition:f,mode:u,baseFilter:c}=t;_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Latest-day discovery: probing newest record\u2026"));let d=await L(a,f,q(u,c));if(!d)return _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("No records found at all; defaulting latest day to today.")),_chunkKUBXRT3Vcjs.hg.call(void 0, new Date);let p=E(u,d);_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Newest record instant is ${p.toISOString()}.`));let o=_chunkKUBXRT3Vcjs.hg.call(void 0, p);return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Latest day (UTC) resolved to ${o.toISOString()} from instant ${p.toISOString()}.`)),o}function je(a,t,f,u=5e3){let c=Math.max(0,f.getTime()-t.getTime());if(c===0)return[];let d=new Date(Math.floor(t.getTime()/3e5)*3e5),p=Math.ceil(c/Math.max(1,u)),o=Math.max(3e5,p),i=Math.ceil((f.getTime()-d.getTime())/o),r=[];for(let s=0;s<i;s+=1){let e=d.getTime()+s*o,y=Math.min(f.getTime(),e+o)-1,g=Math.max(e,y),h=new Date(e).toISOString(),C=new Date(g).toISOString();a==="timestamp"?r.push({timestampAfter:h,timestampBefore:C}):r.push({system:{updatedAfter:h,updatedBefore:C}})}return r}function pt(a,t,f){return a==="timestamp"?{...t,timestampAfter:_nullishCoalesce(f.timestampAfter, () => (t.timestampAfter)),timestampBefore:_nullishCoalesce(f.timestampBefore, () => (t.timestampBefore)),system:void 0}:{...t,system:{...t.system||{},..._optionalChain([f, 'access', _16 => _16.system, 'optionalAccess', _17 => _17.updatedAfter])?{updatedAfter:f.system.updatedAfter}:{},..._optionalChain([f, 'access', _18 => _18.system, 'optionalAccess', _19 => _19.updatedBefore])?{updatedBefore:f.system.updatedBefore}:{}},timestampAfter:void 0,timestampBefore:void 0}}async function $o(a,{partition:t,filterBy:f={},limit:u=50,windowConcurrency:c=25,maxChunks:d=5e3,maxLookbackDays:p=3650,onItems:o}){let i=Z(f);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Fetching consent preferences in chunks by ${i==="timestamp"?"timestamp":"system.updatedAt"}...`));let{after:r,before:s}=Ae(i,f);if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Initial bounds: after=${_nullishCoalesce(_optionalChain([r, 'optionalAccess', _20 => _20.toISOString, 'call', _21 => _21()]), () => ("undefined"))} before=${_nullishCoalesce(_optionalChain([s, 'optionalAccess', _22 => _22.toISOString, 'call', _23 => _23()]), () => ("undefined"))}`)),(!r||!s)&&(r||(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Discovering earliest day with data for partition ${t}...`)),r=await Qe(a,{partition:t,mode:i,baseFilter:f,maxLookbackDays:p}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Discovered earliest day with data: ${r.toISOString()}`))),!s)){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Discovering latest day with data for partition ${t}...`));let P=await Ne(a,{partition:t,mode:i,baseFilter:f,earliest:r});s=_chunkKUBXRT3Vcjs.kg.call(void 0, P,1),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Discovered latest day with data: ${P.toISOString()}`))}_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Final bounds (UTC): after=${r.toISOString()} before=${s.toISOString()}`));let e=je(i,r,s,d);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Fetching consent preferences from partition ${t} in ${e.length} chunks...`));let l=new _cliprogress2.default.SingleBar({format:"Downloading [{bar}] {percentage}% | chunks {value}/{total} | fetched {fetched}"},_cliprogress2.default.Presets.shades_classic),y=0,g=0;l.start(e.length,0,{fetched:g});let h=Date.now(),C=_chunkKUBXRT3Vcjs.gg.call(void 0, u),w=[];return await _bluebird.map.call(void 0, e.map((P,b)=>({windowFilter:P,idx:b})),async({windowFilter:P})=>{let b=pt(i,f,P);for await(let S of X(a,t,b,C))g+=S.length,l.update(y,{fetched:g}),o?await o(S):w.push(...S);y+=1,l.update(y,{fetched:g})},{concurrency:Math.max(1,c)}),l.update(y,{fetched:g}),l.stop(),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Fetched ${g} consent preference records from partition ${t} in ${(Date.now()-h)/1e3}s.`)),o?[]:w}async function xo(a,{partition:t,filterBy:f={},limit:u=50,onItems:c}){let d=[],p,o=f&&(Object.keys(f).length>0||f.system&&Object.keys(f.system).length>0),i=Math.max(1,Math.min(50,_nullishCoalesce(u, () => (50))));for(;;){let r={limit:i};o&&(r.filter=f),p&&(r.cursor=p);let s=await D(()=>a.post(`v1/preferences/${t}/query`,{json:r}).json(),{onRetry:(y,g,h)=>{_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`Retry attempt ${y} for fetchConsentPreferences due to error: ${h}`))}}),{nodes:e,cursor:l}=_typeutils.decodeCodec.call(void 0, V,s);if(!e||e.length===0||(c?await c(e):d.push(...e),!l))break;p=l}return c?[]:d}exports.a = Gr; exports.b = Lr; exports.c = $o; exports.d = xo;
12
- //# sourceMappingURL=chunk-YKGS253B.cjs.map
11
+ `));let P=_chunkNBXAOUWCcjs.xc.call(void 0, e,a),[b,S,fe]=await Promise.all([_chunkNBXAOUWCcjs.yc.call(void 0, e,a,t),l?Promise.resolve([]):_chunkNBXAOUWCcjs.gd.call(void 0, P),l?Promise.resolve([]):_chunkNBXAOUWCcjs.cd.call(void 0, P)]);await ve({file:u,purposeSlugs:S.map(M=>M.trackingType),preferenceTopics:fe,sombra:b,partitionKey:c,skipExistingRecordCheck:r,forceTriggerWorkflows:l},g);let Q={};w=g.getValue("fileMetadata");let F=w[u];if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(F.pendingSafeUpdates).length} safe updates in ${u}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(F.pendingConflictUpdates).length} conflict updates in ${u}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(F.skippedUpdates).length} skipped updates in ${u}`)),Object.entries({...F.pendingSafeUpdates,...i?{}:_typeutils.apply.call(void 0, F.pendingConflictUpdates,({row:M})=>M)}).forEach(([M,k])=>{let _=F.timestampColum===H?new Date:new Date(k[F.timestampColum]),O=J({row:k,columnToPurposeName:F.columnToPurposeName,preferenceTopics:fe,purposeSlugs:S.map(N=>N.trackingType)});Q[M]={userId:M,partition:c,timestamp:_.toISOString(),purposes:Object.entries(O).map(([N,_e])=>({..._e,purpose:N,workflowSettings:{attributes:y,isSilent:d,skipWorkflowTrigger:o}}))}}),await g.setValue(Q,"pendingUpdates"),await g.setValue({},"failingUpdates"),p){_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Dry run complete, exiting. ${Object.values(Q).length} pending updates. Check file: ${f}`));return}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Uploading ${Object.values(Q).length} preferences to partition: ${c}`));let Ge=new Date().getTime(),ee=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),me=0,te=Object.entries(Q),qe=_chunkF7QE6D3Tcjs.b.call(void 0, te,o?100:10);ee.start(te.length,0),await _bluebird.map.call(void 0, qe,async M=>{try{await b.put("v1/preferences",{json:{records:M.map(([,k])=>k),skipWorkflowTriggers:o,forceTriggerWorkflows:l}}).json()}catch(k){try{let O=JSON.parse(_optionalChain([k, 'optionalAccess', _5 => _5.response, 'optionalAccess', _6 => _6.body])||"{}");O.error&&_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error: ${O.error}`))}catch (e2){}_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to upload ${M.length} user preferences to partition ${c}: ${_optionalChain([k, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.body])||_optionalChain([k, 'optionalAccess', _9 => _9.message])}`));let _=g.getValue("failingUpdates");M.forEach(([O,N])=>{_[O]={uploadedAt:new Date().toISOString(),update:N,error:_optionalChain([k, 'optionalAccess', _10 => _10.response, 'optionalAccess', _11 => _11.body])||_optionalChain([k, 'optionalAccess', _12 => _12.message])||"Unknown error"}}),await g.setValue(_,"failingUpdates")}me+=M.length,ee.update(me)},{concurrency:40}),ee.stop();let Le=new Date().getTime()-Ge;_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully uploaded ${te.length} user preferences to partition ${c} in "${Le/1e3}" seconds!`))}function Lr({identifiers:a=[],purposes:t=[],metadata:f=[],consentManagement:u={},system:c={decryptionStatus:"DECRYPTED"},...d}){let p={...d,...c,...u};if(Array.isArray(a)){let o=new Map;for(let{name:i,value:r}of a)o.has(i)||o.set(i,new Set),r&&o.get(i).add(r);for(let[i,r]of o.entries())p[i]=Array.from(r).join(",")}if(Array.isArray(f)&&(p.metadata=JSON.stringify(f.reduce((o,{key:i,value:r})=>(o[i]=r,o),{}))),Array.isArray(t)){for(let{purpose:o,preferences:i,enabled:r}of t)if(p[o]=!!r,Array.isArray(i))for(let{topic:s,choice:e}of i){let l=`${o}_${s}`,y=null;typeof e.booleanValue=="boolean"?y=e.booleanValue:e.selectValue?y=e.selectValue:Array.isArray(e.selectValues)?y=e.selectValues.filter(h=>h.length>0).join(","):y=null,p[l]=y}}return p}async function*X(a,t,f,u){let c;for(;;){let d={limit:u};f&&Object.keys(f).length&&(d.filter=f),c&&(d.cursor=c);let p=await D(()=>a.post(`v1/preferences/${t}/query`,{json:d}).json(),{onRetry:(r,s,e)=>{_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`Retry attempt ${r} for fetchConsentPreferences due to error: ${e}`))}}),{nodes:o,cursor:i}=_typeutils.decodeCodec.call(void 0, V,p);if(!_optionalChain([o, 'optionalAccess', _13 => _13.length])||(yield o,!i))break;c=i}}function Z(a){return!!a.timestampAfter||!!a.timestampBefore?"timestamp":"updated"}function E(a,t){return a==="timestamp"?new Date(t.timestamp):_optionalChain([t, 'access', _14 => _14.system, 'optionalAccess', _15 => _15.updatedAt])?new Date(t.system.updatedAt):new Date}function Ae(a,t){if(a==="timestamp")return{after:t.timestampAfter?new Date(t.timestampAfter):void 0,before:t.timestampBefore?new Date(t.timestampBefore):void 0};let f=_nullishCoalesce(t.system, () => ({}));return{after:f.updatedAfter?new Date(f.updatedAfter):void 0,before:f.updatedBefore?new Date(f.updatedBefore):void 0}}function q(a,t,f){return a==="timestamp"?{...t,timestampBefore:_nullishCoalesce(f, () => (t.timestampBefore))}:{...t,system:{...t.system||{},...f?{updatedBefore:f}:{}},timestampAfter:void 0,timestampBefore:void 0}}async function L(a,t,f){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Single-record probe with filter: ${JSON.stringify(f)}`));let c=await X(a,t,f,1).next();if(c.done||!c.value||c.value.length===0)return _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("Probe result: no record")),null;let d=c.value[0];return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Probe result: found record at ${E(Z(f),d).toISOString()}`)),d}async function Qe(a,t){let{partition:f,mode:u,baseFilter:c,maxLookbackDays:d=3650}=t,p=await L(a,f,q(u,c));if(!p)return _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("No records found; defaulting earliest day to today.")),_chunkNBXAOUWCcjs.jg.call(void 0, new Date);let o=E(u,p);_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Newest instant: ${o.toISOString()}`));let i=[1,7,30],r=0,s=i[0]*864e5,e=o,l=null;for(;;){let w=r<i.length?new Date(o.getTime()-i[r]*864e5):new Date(o.getTime()-s);if((_chunkNBXAOUWCcjs.jg.call(void 0, new Date).getTime()-_chunkNBXAOUWCcjs.jg.call(void 0, w).getTime())/864e5>d){_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`Exponential jump exceeded maxLookbackDays=${d}. Using current bounds.`)),l=w;break}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Probing before=${w.toISOString()} (jump step ${r<i.length?`${i[r]}d`:`${Math.round(s/864e5)}d`})\u2026`));let b=await L(a,f,q(u,c,w.toISOString()));if(b){e=E(u,b),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Found older record at ${e.toISOString()} \u2014 continue jumping back.`)),r<i.length-1?(r+=1,s=i[r]*864e5):r===i.length-1?(r+=1,s=i[i.length-1]*2*864e5):s*=2;continue}l=w,_chunkZUNVPK23cjs.a.info(_colors2.default.green(`No record before ${w.toISOString()} \u2014 established empty lower bound.`));break}l||(l=new Date(e.getTime()-864e5));let y=l,g=e,h=Math.max(864e5,Math.floor((g.getTime()-y.getTime())/64));_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Exponential forward-from-empty start: empty=${y.toISOString()} found=${g.toISOString()} step=${Math.round(h/864e5)}d`));for(let w=0;w<8;w+=1){let P=new Date(y.getTime()+h);if(P.getTime()>=g.getTime())break;_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Forward gallop probe before=${P.toISOString()}\u2026`));let b=await L(a,f,q(u,c,P.toISOString()));if(b?(g=E(u,b),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Gallop hit at ${g.toISOString()} \u2014 tightening found bound. Next step halves.`)),h=Math.max(864e5,Math.floor(h/2))):(y.setTime(P.getTime()),_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Gallop miss \u2014 advancing empty bound to ${y.toISOString()}. Next step doubles.`)),h=Math.min(g.getTime()-y.getTime(),h*2),h<864e5&&(h=864e5)),g.getTime()-y.getTime()<=864e5)break}for(;g.getTime()-y.getTime()>864e5;){let w=new Date(y.getTime()+Math.floor((g.getTime()-y.getTime())/2));_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Binary probe before=${w.toISOString()}\u2026`));let P=await L(a,f,q(u,c,w.toISOString()));if(P){let b=E(u,P);_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Binary probe found record at ${b.toISOString()}.`)),g=b}else _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("Binary probe found no record.")),y=w}let C=_chunkNBXAOUWCcjs.jg.call(void 0, g);return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Earliest day (UTC) resolved to ${C.toISOString()} (instant \u2248 ${g.toISOString()}).`)),C}async function Ne(a,t){let{partition:f,mode:u,baseFilter:c}=t;_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Latest-day discovery: probing newest record\u2026"));let d=await L(a,f,q(u,c));if(!d)return _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("No records found at all; defaulting latest day to today.")),_chunkNBXAOUWCcjs.jg.call(void 0, new Date);let p=E(u,d);_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Newest record instant is ${p.toISOString()}.`));let o=_chunkNBXAOUWCcjs.jg.call(void 0, p);return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Latest day (UTC) resolved to ${o.toISOString()} from instant ${p.toISOString()}.`)),o}function je(a,t,f,u=5e3){let c=Math.max(0,f.getTime()-t.getTime());if(c===0)return[];let d=new Date(Math.floor(t.getTime()/3e5)*3e5),p=Math.ceil(c/Math.max(1,u)),o=Math.max(3e5,p),i=Math.ceil((f.getTime()-d.getTime())/o),r=[];for(let s=0;s<i;s+=1){let e=d.getTime()+s*o,y=Math.min(f.getTime(),e+o)-1,g=Math.max(e,y),h=new Date(e).toISOString(),C=new Date(g).toISOString();a==="timestamp"?r.push({timestampAfter:h,timestampBefore:C}):r.push({system:{updatedAfter:h,updatedBefore:C}})}return r}function pt(a,t,f){return a==="timestamp"?{...t,timestampAfter:_nullishCoalesce(f.timestampAfter, () => (t.timestampAfter)),timestampBefore:_nullishCoalesce(f.timestampBefore, () => (t.timestampBefore)),system:void 0}:{...t,system:{...t.system||{},..._optionalChain([f, 'access', _16 => _16.system, 'optionalAccess', _17 => _17.updatedAfter])?{updatedAfter:f.system.updatedAfter}:{},..._optionalChain([f, 'access', _18 => _18.system, 'optionalAccess', _19 => _19.updatedBefore])?{updatedBefore:f.system.updatedBefore}:{}},timestampAfter:void 0,timestampBefore:void 0}}async function $o(a,{partition:t,filterBy:f={},limit:u=50,windowConcurrency:c=25,maxChunks:d=5e3,maxLookbackDays:p=3650,onItems:o}){let i=Z(f);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Fetching consent preferences in chunks by ${i==="timestamp"?"timestamp":"system.updatedAt"}...`));let{after:r,before:s}=Ae(i,f);if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Initial bounds: after=${_nullishCoalesce(_optionalChain([r, 'optionalAccess', _20 => _20.toISOString, 'call', _21 => _21()]), () => ("undefined"))} before=${_nullishCoalesce(_optionalChain([s, 'optionalAccess', _22 => _22.toISOString, 'call', _23 => _23()]), () => ("undefined"))}`)),(!r||!s)&&(r||(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Discovering earliest day with data for partition ${t}...`)),r=await Qe(a,{partition:t,mode:i,baseFilter:f,maxLookbackDays:p}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Discovered earliest day with data: ${r.toISOString()}`))),!s)){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Discovering latest day with data for partition ${t}...`));let P=await Ne(a,{partition:t,mode:i,baseFilter:f,earliest:r});s=_chunkNBXAOUWCcjs.mg.call(void 0, P,1),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Discovered latest day with data: ${P.toISOString()}`))}_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Final bounds (UTC): after=${r.toISOString()} before=${s.toISOString()}`));let e=je(i,r,s,d);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Fetching consent preferences from partition ${t} in ${e.length} chunks...`));let l=new _cliprogress2.default.SingleBar({format:"Downloading [{bar}] {percentage}% | chunks {value}/{total} | fetched {fetched}"},_cliprogress2.default.Presets.shades_classic),y=0,g=0;l.start(e.length,0,{fetched:g});let h=Date.now(),C=_chunkNBXAOUWCcjs.ig.call(void 0, u),w=[];return await _bluebird.map.call(void 0, e.map((P,b)=>({windowFilter:P,idx:b})),async({windowFilter:P})=>{let b=pt(i,f,P);for await(let S of X(a,t,b,C))g+=S.length,l.update(y,{fetched:g}),o?await o(S):w.push(...S);y+=1,l.update(y,{fetched:g})},{concurrency:Math.max(1,c)}),l.update(y,{fetched:g}),l.stop(),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Fetched ${g} consent preference records from partition ${t} in ${(Date.now()-h)/1e3}s.`)),o?[]:w}async function xo(a,{partition:t,filterBy:f={},limit:u=50,onItems:c}){let d=[],p,o=f&&(Object.keys(f).length>0||f.system&&Object.keys(f.system).length>0),i=Math.max(1,Math.min(50,_nullishCoalesce(u, () => (50))));for(;;){let r={limit:i};o&&(r.filter=f),p&&(r.cursor=p);let s=await D(()=>a.post(`v1/preferences/${t}/query`,{json:r}).json(),{onRetry:(y,g,h)=>{_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`Retry attempt ${y} for fetchConsentPreferences due to error: ${h}`))}}),{nodes:e,cursor:l}=_typeutils.decodeCodec.call(void 0, V,s);if(!e||e.length===0||(c?await c(e):d.push(...e),!l))break;p=l}return c?[]:d}exports.a = Gr; exports.b = Lr; exports.c = $o; exports.d = xo;
12
+ //# sourceMappingURL=chunk-HCPNMNS3.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-YKGS253B.cjs","../src/lib/preference-management/uploadPreferenceManagementPreferencesInteractive.ts","../src/lib/preference-management/parsePreferenceManagementCsv.ts","../src/lib/preference-management/getPreferencesForIdentifiers.ts","../src/lib/preference-management/withPreferenceQueryRetry.ts","../src/lib/preference-management/parsePreferenceIdentifiersFromCsv.ts","../src/lib/preference-management/parsePreferenceAndPurposeValuesFromCsv.ts","../src/lib/preference-management/codecs.ts"],"names":["RETRY_PREFERENCE_MSGS","s","withPreferenceQueryRetry","fn","maxAttempts","baseDelayMs","isRetryable","_err","msg","m","onRetry","attempt","err"],"mappings":"AAAA,2lCAA2J,wDAAyC,wDAAuE,gFCQxP,oCACC,qGAGI,+DAEO,qJCXZ,qDCES,ICGfA,EAAAA,CAAkC,CAC7C,WAAA,CACA,YAAA,CACA,WAAA,CACA,iBAAA,CACA,sBAAA,CACA,sBAAA,CACA,uBACF,CAAA,CAAE,GAAA,CAAKC,CAAAA,EAAMA,CAAAA,CAAE,WAAA,CAAY,CAAC,CAAA,CAwB5B,MAAA,SAAsBC,CAAAA,CACpBC,CAAAA,CACA,CACE,WAAA,CAAAC,CAAAA,CAAc,CAAA,CACd,WAAA,CAAAC,CAAAA,CAAc,GAAA,CACd,WAAA,CAAAC,CAAAA,CAAc,CAACC,CAAAA,CAAMC,CAAAA,CAAAA,EACnBR,EAAAA,CAAsB,IAAA,CAAMS,CAAAA,EAAMD,CAAAA,CAAI,WAAA,CAAY,CAAA,CAAE,QAAA,CAASC,CAAC,CAAC,CAAA,CACjE,OAAA,CAAAC,CACF,CAAA,CAAkB,CAAC,CAAA,CACP,CACZ,IAAIC,CAAAA,CAAU,CAAA,CAEd,GAAA,CAAA,CAAA,CAAA,CAAa,CACXA,CAAAA,EAAW,CAAA,CACX,GAAI,CACF,OAAO,MAAMR,CAAAA,CAAG,CAElB,CAAA,KAAA,CAASS,CAAAA,CAAU,CACjB,IAAMJ,CAAAA,kBAAAA,CACHI,CAAAA,EAAAA,iBAAQA,CAAAA,qBAAI,QAAA,6BAAU,MAAA,EAAQA,CAAAA,CAAI,OAAA,CAAA,CAAA,SACnC,MAAA,kBAAOA,CAAAA,SAAO,iBAAe,GAAA,CAE/B,EAAA,CAAI,CAAA,CADcD,CAAAA,CAAUP,CAAAA,EAAeE,CAAAA,CAAYM,CAAAA,CAAKJ,CAAG,CAAA,CAAA,CAE7D,MAAM,IAAI,KAAA,CACR,CAAA,8BAAA,EAAiCG,CAAO,CAAA,aAAA,EAAgBH,CAAG,CAAA,CAAA;ACiC/D;ACnBU;ACyBD,oGAAA;ANbP;AAGA;AAAA;AAKQ;AAAK;AACgC,sCAAA;AA+FY","file":"/home/runner/work/cli/cli/dist/chunk-YKGS253B.cjs","sourcesContent":[null,"import {\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllPurposes,\n fetchAllPreferenceTopics,\n PreferenceTopic,\n Purpose,\n} from '../graphql';\nimport colors from 'colors';\nimport { map } from 'bluebird';\nimport { chunk } from 'lodash-es';\nimport { logger } from '../../logger';\nimport cliProgress from 'cli-progress';\nimport { parseAttributesFromString } from '../requests';\nimport { PersistedState } from '@transcend-io/persisted-state';\nimport { parsePreferenceManagementCsvWithCache } from './parsePreferenceManagementCsv';\nimport { PreferenceState } from './codecs';\nimport { PreferenceUpdateItem } from '@transcend-io/privacy-types';\nimport { apply } from '@transcend-io/type-utils';\nimport { NONE_PREFERENCE_MAP } from './parsePreferenceTimestampsFromCsv';\nimport { getPreferenceUpdatesFromRow } from './getPreferenceUpdatesFromRow';\n\n/**\n * Upload a set of consent preferences\n *\n * @param options - Options\n */\nexport async function uploadPreferenceManagementPreferencesInteractive({\n auth,\n sombraAuth,\n receiptFilepath,\n file,\n partition,\n isSilent = true,\n dryRun = false,\n skipWorkflowTriggers = false,\n skipConflictUpdates = false,\n skipExistingRecordCheck = false,\n attributes = [],\n transcendUrl,\n forceTriggerWorkflows = false,\n}: {\n /** The Transcend API key */\n auth: string;\n /** Sombra API key authentication */\n sombraAuth?: string;\n /** Partition key */\n partition: string;\n /** File where to store receipt and continue from where left off */\n receiptFilepath: string;\n /** The file to process */\n file: string;\n /** API URL for Transcend backend */\n transcendUrl: string;\n /** Whether to do a dry run */\n dryRun?: boolean;\n /** Whether to upload as isSilent */\n isSilent?: boolean;\n /** Attributes string pre-parse. In format Key:Value */\n attributes?: string[];\n /** Skip workflow triggers */\n skipWorkflowTriggers?: boolean;\n /**\n * When true, only update preferences that do not conflict with existing\n * preferences. When false, update all preferences in CSV based on timestamp.\n */\n skipConflictUpdates?: boolean;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck?: boolean;\n /** Whether to force trigger workflows */\n forceTriggerWorkflows?: boolean;\n}): Promise<void> {\n // Parse out the extra attributes to apply to all requests uploaded\n const parsedAttributes = parseAttributesFromString(attributes);\n\n // Create a new state file to store the requests from this run\n const preferenceState = new PersistedState(receiptFilepath, PreferenceState, {\n fileMetadata: {},\n failingUpdates: {},\n pendingUpdates: {},\n });\n const failingRequests = preferenceState.getValue('failingUpdates');\n const pendingRequests = preferenceState.getValue('pendingUpdates');\n let fileMetadata = preferenceState.getValue('fileMetadata');\n\n logger.info(\n colors.magenta(\n 'Restored cache, there are: \\n' +\n `${\n Object.values(failingRequests).length\n } failing requests to be retried\\n` +\n `${\n Object.values(pendingRequests).length\n } pending requests to be processed\\n` +\n `The following files are stored in cache and will be used:\\n${Object.keys(\n fileMetadata,\n )\n .map((x) => x)\n .join('\\n')}\\n` +\n `The following file will be processed: ${file}\\n`,\n ),\n );\n\n // Create GraphQL client to connect to Transcend backend\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const [sombra, purposes, preferenceTopics] = await Promise.all([\n // Create sombra instance to communicate with\n createSombraGotInstance(transcendUrl, auth, sombraAuth),\n // get all purposes and topics\n forceTriggerWorkflows\n ? Promise.resolve([] as Purpose[])\n : fetchAllPurposes(client),\n forceTriggerWorkflows\n ? Promise.resolve([] as PreferenceTopic[])\n : fetchAllPreferenceTopics(client),\n ]);\n\n // Process the file\n await parsePreferenceManagementCsvWithCache(\n {\n file,\n purposeSlugs: purposes.map((x) => x.trackingType),\n preferenceTopics,\n sombra,\n partitionKey: partition,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n },\n preferenceState,\n );\n\n // Construct the pending updates\n const pendingUpdates: Record<string, PreferenceUpdateItem> = {};\n fileMetadata = preferenceState.getValue('fileMetadata');\n const metadata = fileMetadata[file];\n\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.pendingSafeUpdates).length\n } safe updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.pendingConflictUpdates).length\n } conflict updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.skippedUpdates).length\n } skipped updates in ${file}`,\n ),\n );\n\n // Update either safe updates only or safe + conflict\n Object.entries({\n ...metadata.pendingSafeUpdates,\n ...(skipConflictUpdates\n ? {}\n : apply(metadata.pendingConflictUpdates, ({ row }) => row)),\n }).forEach(([userId, update]) => {\n // Determine timestamp\n const timestamp =\n metadata.timestampColum === NONE_PREFERENCE_MAP\n ? new Date()\n : new Date(update[metadata.timestampColum!]);\n\n // Determine updates\n const updates = getPreferenceUpdatesFromRow({\n row: update,\n columnToPurposeName: metadata.columnToPurposeName,\n preferenceTopics,\n purposeSlugs: purposes.map((x) => x.trackingType),\n });\n pendingUpdates[userId] = {\n userId,\n partition,\n timestamp: timestamp.toISOString(),\n purposes: Object.entries(updates).map(([purpose, value]) => ({\n ...value,\n purpose,\n workflowSettings: {\n attributes: parsedAttributes,\n isSilent,\n skipWorkflowTrigger: skipWorkflowTriggers,\n },\n })),\n };\n });\n await preferenceState.setValue(pendingUpdates, 'pendingUpdates');\n await preferenceState.setValue({}, 'failingUpdates');\n\n // Exist early if dry run\n if (dryRun) {\n logger.info(\n colors.green(\n `Dry run complete, exiting. ${\n Object.values(pendingUpdates).length\n } pending updates. Check file: ${receiptFilepath}`,\n ),\n );\n return;\n }\n\n logger.info(\n colors.magenta(\n `Uploading ${\n Object.values(pendingUpdates).length\n } preferences to partition: ${partition}`,\n ),\n );\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n\n // Build a GraphQL client\n let total = 0;\n const updatesToRun = Object.entries(pendingUpdates);\n const chunkedUpdates = chunk(updatesToRun, skipWorkflowTriggers ? 100 : 10);\n progressBar.start(updatesToRun.length, 0);\n await map(\n chunkedUpdates,\n async (currentChunk) => {\n // Make the request\n try {\n await sombra\n .put('v1/preferences', {\n json: {\n records: currentChunk.map(([, update]) => update),\n skipWorkflowTriggers,\n forceTriggerWorkflows,\n },\n })\n .json();\n } catch (err) {\n try {\n const parsed = JSON.parse(err?.response?.body || '{}');\n if (parsed.error) {\n logger.error(colors.red(`Error: ${parsed.error}`));\n }\n } catch (e) {\n // continue\n }\n logger.error(\n colors.red(\n `Failed to upload ${\n currentChunk.length\n } user preferences to partition ${partition}: ${\n err?.response?.body || err?.message\n }`,\n ),\n );\n const failingUpdates = preferenceState.getValue('failingUpdates');\n currentChunk.forEach(([userId, update]) => {\n failingUpdates[userId] = {\n uploadedAt: new Date().toISOString(),\n update,\n error: err?.response?.body || err?.message || 'Unknown error',\n };\n });\n await preferenceState.setValue(failingUpdates, 'failingUpdates');\n }\n\n total += currentChunk.length;\n progressBar.update(total);\n },\n {\n concurrency: 40,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n logger.info(\n colors.green(\n `Successfully uploaded ${\n updatesToRun.length\n } user preferences to partition ${partition} in \"${\n totalTime / 1000\n }\" seconds!`,\n ),\n );\n}\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport type { Got } from 'got';\nimport { keyBy } from 'lodash-es';\nimport * as t from 'io-ts';\nimport colors from 'colors';\nimport { FileMetadataState, PreferenceState } from './codecs';\nimport { logger } from '../../logger';\nimport { readCsv } from '../requests';\nimport { getPreferencesForIdentifiers } from './getPreferencesForIdentifiers';\nimport { PreferenceTopic } from '../graphql';\nimport { getPreferenceUpdatesFromRow } from './getPreferenceUpdatesFromRow';\nimport { parsePreferenceTimestampsFromCsv } from './parsePreferenceTimestampsFromCsv';\nimport { parsePreferenceIdentifiersFromCsv } from './parsePreferenceIdentifiersFromCsv';\nimport { parsePreferenceAndPurposeValuesFromCsv } from './parsePreferenceAndPurposeValuesFromCsv';\nimport { checkIfPendingPreferenceUpdatesAreNoOp } from './checkIfPendingPreferenceUpdatesAreNoOp';\nimport { checkIfPendingPreferenceUpdatesCauseConflict } from './checkIfPendingPreferenceUpdatesCauseConflict';\n\n/**\n * Parse a file into the cache\n *\n *\n * @param options - Options\n * @param cache - The cache to store the parsed file in\n * @returns The cache with the parsed file\n */\nexport async function parsePreferenceManagementCsvWithCache(\n {\n file,\n sombra,\n purposeSlugs,\n preferenceTopics,\n partitionKey,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n }: {\n /** File to parse */\n file: string;\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Sombra got instance */\n sombra: Got;\n /** Partition key */\n partitionKey: string;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck: boolean;\n /** Wheather to force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n cache: PersistedState<typeof PreferenceState>,\n): Promise<void> {\n // Start the timer\n const t0 = new Date().getTime();\n\n // Get the current metadata\n const fileMetadata = cache.getValue('fileMetadata');\n\n // Read in the file\n logger.info(colors.magenta(`Reading in file: \"${file}\"`));\n let preferences = readCsv(file, t.record(t.string, t.string));\n\n // start building the cache, can use previous cache as well\n let currentState: FileMetadataState = {\n columnToPurposeName: {},\n pendingSafeUpdates: {},\n pendingConflictUpdates: {},\n skippedUpdates: {},\n // Load in the last fetched time\n ...((fileMetadata[file] || {}) as Partial<FileMetadataState>),\n lastFetchedAt: new Date().toISOString(),\n };\n\n // Validate that all timestamps are present in the file\n currentState = await parsePreferenceTimestampsFromCsv(\n preferences,\n currentState,\n );\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Validate that all identifiers are present and unique\n const result = await parsePreferenceIdentifiersFromCsv(\n preferences,\n currentState,\n );\n currentState = result.currentState;\n preferences = result.preferences;\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Ensure all other columns are mapped to purpose and preference\n // slug values\n currentState = await parsePreferenceAndPurposeValuesFromCsv(\n preferences,\n currentState,\n {\n preferenceTopics,\n purposeSlugs,\n forceTriggerWorkflows,\n },\n );\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Grab existing preference store records\n const identifiers = preferences.map(\n (pref) => pref[currentState.identifierColumn!],\n );\n const existingConsentRecords = skipExistingRecordCheck\n ? []\n : await getPreferencesForIdentifiers(sombra, {\n identifiers: identifiers.map((x) => ({ value: x })),\n partitionKey,\n });\n const consentRecordByIdentifier = keyBy(existingConsentRecords, 'userId');\n\n // Clear out previous updates\n currentState.pendingConflictUpdates = {};\n currentState.pendingSafeUpdates = {};\n currentState.skippedUpdates = {};\n\n // Process each row\n preferences.forEach((pref) => {\n // Grab unique Id for the user\n const userId = pref[currentState.identifierColumn!];\n\n // determine updates for user\n const pendingUpdates = getPreferenceUpdatesFromRow({\n row: pref,\n columnToPurposeName: currentState.columnToPurposeName,\n preferenceTopics,\n purposeSlugs,\n });\n\n // Grab current state of the update\n const currentConsentRecord = consentRecordByIdentifier[userId];\n if (forceTriggerWorkflows && !currentConsentRecord) {\n throw new Error(\n `No existing consent record found for user with id: ${userId}. \n When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`,\n );\n }\n // Check if the update can be skipped\n // this is the case if a record exists, and the purpose\n // and preference values are all in sync\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesAreNoOp({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n }) &&\n !forceTriggerWorkflows\n ) {\n currentState.skippedUpdates[userId] = pref;\n return;\n }\n\n // Determine if there are any conflicts\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesCauseConflict({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n })\n ) {\n currentState.pendingConflictUpdates[userId] = {\n row: pref,\n record: currentConsentRecord,\n };\n return;\n }\n\n // Add to pending updates\n currentState.pendingSafeUpdates[userId] = pref;\n });\n\n // Read in the file\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n const t1 = new Date().getTime();\n logger.info(\n colors.green(\n `Successfully pre-processed file: \"${file}\" in ${(t1 - t0) / 1000}s`,\n ),\n );\n}\n","import { PreferenceQueryResponseItem } from '@transcend-io/privacy-types';\nimport type { Got } from 'got';\nimport colors from 'colors';\nimport cliProgress from 'cli-progress';\nimport { chunk } from 'lodash-es';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { map } from 'bluebird';\nimport { logger } from '../../logger';\nimport { withPreferenceQueryRetry } from './withPreferenceQueryRetry';\nimport { ConsentPreferenceResponse } from './types';\n\n/**\n * Grab the current consent preference values for a list of identifiers\n *\n * @param sombra - Backend to make API call to\n * @param options - Options\n * @returns Plaintext context information\n */\nexport async function getPreferencesForIdentifiers(\n sombra: Got,\n {\n identifiers,\n partitionKey,\n skipLogging = false,\n concurrency = 40,\n }: {\n /** The list of identifiers to look up */\n identifiers: {\n /** The value of the identifier */\n value: string;\n }[];\n /** The partition key to look up */\n partitionKey: string;\n /** Whether to skip logging */\n skipLogging?: boolean;\n /** Concurrency for requests (default 40) */\n concurrency?: number;\n },\n): Promise<PreferenceQueryResponseItem[]> {\n const results: PreferenceQueryResponseItem[] = [];\n const groupedIdentifiers = chunk(identifiers, 100);\n\n // create a new progress bar instance and use shades_classic theme\n const t0 = new Date().getTime();\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n if (!skipLogging) {\n progressBar.start(identifiers.length, 0);\n }\n\n let total = 0;\n await map(\n groupedIdentifiers,\n async (group) => {\n const rawResult = await withPreferenceQueryRetry(\n () =>\n sombra\n .post(`v1/preferences/${partitionKey}/query`, {\n json: {\n filter: { identifiers: group },\n limit: group.length,\n },\n })\n .json(),\n {\n onRetry: (attempt, _err, msg) => {\n logger.warn(\n colors.yellow(\n `[RETRY] group size=${group.length} partition=${partitionKey} attempt=${attempt}: ${msg}`,\n ),\n );\n },\n },\n );\n\n const result = decodeCodec(ConsentPreferenceResponse, rawResult);\n results.push(...result.nodes);\n total += group.length;\n progressBar.update(total);\n },\n {\n concurrency,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n if (!skipLogging) {\n // Log completion time\n logger.info(\n colors.green(`Completed download in \"${totalTime / 1000}\" seconds.`),\n );\n }\n\n return results;\n}\n","import colors from 'colors';\nimport { logger } from '../../logger';\nimport { sleepPromise } from '../helpers';\n\n/**\n * Transient network / platform errors that merit a retry.\n * Keep this list short and specific to avoid masking real failures.\n */\nexport const RETRY_PREFERENCE_MSGS: string[] = [\n 'ENOTFOUND',\n 'ECONNRESET',\n 'ETIMEDOUT',\n '502 Bad Gateway',\n '504 Gateway Time-out',\n 'Task timed out after',\n 'unknown request error',\n].map((s) => s.toLowerCase());\n\n/**\n * Options for retrying preference queries.\n */\nexport type RetryOptions = {\n /** Max attempts including the first try (default 3) */\n maxAttempts?: number;\n /** Initial backoff in ms (default 250) */\n baseDelayMs?: number;\n /** Optional custom predicate to decide if an error is retryable */\n isRetryable?: (err: unknown, message: string) => boolean;\n /** Optional hook to log on each retry */\n onRetry?: (attempt: number, err: unknown, message: string) => void;\n};\n\n/**\n * Run an async function with standardized retry behavior for preference queries.\n * Exponential backoff with jitter; only retries on known-transient messages.\n *\n * @param fn - Function to run\n * @param options - Retry options\n * @returns Result of the function\n */\nexport async function withPreferenceQueryRetry<T>(\n fn: () => Promise<T>,\n {\n maxAttempts = 3,\n baseDelayMs = 250,\n isRetryable = (_err, msg) =>\n RETRY_PREFERENCE_MSGS.some((m) => msg.toLowerCase().includes(m)),\n onRetry,\n }: RetryOptions = {},\n): Promise<T> {\n let attempt = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n attempt += 1;\n try {\n return await fn();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (err: any) {\n const msg: string =\n (err && (err.response?.body || err.message)) ??\n String(err ?? 'Unknown error');\n const willRetry = attempt < maxAttempts && isRetryable(err, msg);\n if (!willRetry) {\n throw new Error(\n `Preference query failed after ${attempt} attempt(s): ${msg}`,\n );\n }\n onRetry?.(attempt, err, msg);\n\n const backoff = baseDelayMs * 2 ** (attempt - 1);\n const jitter = Math.floor(Math.random() * baseDelayMs);\n const delay = backoff + jitter;\n logger.warn(\n colors.yellow(\n `[retry] attempt ${attempt}/${\n maxAttempts - 1\n }; backing off ${delay}ms: ${msg}`,\n ),\n );\n await sleepPromise(delay);\n }\n }\n}\n","import { uniq, groupBy, difference } from 'lodash-es';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { FileMetadataState } from './codecs';\nimport { logger } from '../../logger';\nimport { inquirerConfirmBoolean } from '../helpers';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse identifiers from a CSV list of preferences\n *\n * Ensures that all rows have a valid identifier\n * and that all identifiers are unique.\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceIdentifiersFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<{\n /** The updated state */\n currentState: FileMetadataState;\n /** The updated preferences */\n preferences: Record<string, string>[];\n}> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const remainingColumnsForIdentifier = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the identifier column to work off of\n if (!currentState.identifierColumn) {\n const { identifierName } = await inquirer.prompt<{\n /** Identifier name */\n identifierName: string;\n }>([\n {\n name: 'identifierName',\n message:\n 'Choose the column that will be used as the identifier to upload consent preferences by',\n type: 'list',\n default:\n remainingColumnsForIdentifier.find((col) =>\n col.toLowerCase().includes('email'),\n ) || remainingColumnsForIdentifier[0],\n choices: remainingColumnsForIdentifier,\n },\n ]);\n currentState.identifierColumn = identifierName;\n }\n logger.info(\n colors.magenta(\n `Using identifier column \"${currentState.identifierColumn}\"`,\n ),\n );\n\n // Validate that the identifier column is present for all rows and unique\n const identifierColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.identifierColumn!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (identifierColumnsMissing.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" is missing a value for the following rows: ${identifierColumnsMissing.join(\n ', ',\n )}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to skip rows missing an identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to skip rows missing an identifier?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n\n // Filter out rows missing an identifier\n const previous = preferences.length;\n preferences = preferences.filter(\n (pref) => pref[currentState.identifierColumn!],\n );\n logger.info(\n colors.yellow(\n `Skipped ${previous - preferences.length} rows missing an identifier`,\n ),\n );\n }\n logger.info(\n colors.magenta(\n `The identifier column \"${currentState.identifierColumn}\" is present for all rows`,\n ),\n );\n\n // Validate that all identifiers are unique\n const rowsByUserId = groupBy(preferences, currentState.identifierColumn);\n const duplicateIdentifiers = Object.entries(rowsByUserId).filter(\n ([, rows]) => rows.length > 1,\n );\n if (duplicateIdentifiers.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" has duplicate values for the following rows: ${duplicateIdentifiers\n .slice(0, 10)\n .map(([userId, rows]) => `${userId} (${rows.length})`)\n .join('\\n')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to take the most recent update\n // for each duplicate identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to automatically take the latest update?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n preferences = Object.entries(rowsByUserId)\n .map(([, rows]) => {\n const sorted = rows.sort(\n (a, b) =>\n new Date(b[currentState.timestampColum!]).getTime() -\n new Date(a[currentState.timestampColum!]).getTime(),\n );\n return sorted[0];\n })\n .filter((x) => x);\n }\n\n return { currentState, preferences };\n}\n/* eslint-enable no-param-reassign */\n","import { uniq, difference } from 'lodash-es';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { FileMetadataState } from './codecs';\nimport { logger } from '../../logger';\nimport { mapSeries } from 'bluebird';\nimport { PreferenceTopic } from '../graphql';\nimport { PreferenceTopicType } from '@transcend-io/privacy-types';\nimport { splitCsvToList } from '../requests';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse out the purpose.enabled and preference values from a CSV file\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @param options - Options\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceAndPurposeValuesFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n {\n purposeSlugs,\n preferenceTopics,\n forceTriggerWorkflows,\n }: {\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const otherColumns = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...(currentState.timestampColum ? [currentState.timestampColum] : []),\n ]);\n if (otherColumns.length === 0) {\n if (forceTriggerWorkflows) {\n return currentState;\n }\n throw new Error('No other columns to process');\n }\n\n // The purpose and preferences to map to\n const purposeNames = [\n ...purposeSlugs,\n ...preferenceTopics.map((x) => `${x.purpose.trackingType}->${x.slug}`),\n ];\n\n // Ensure all columns are accounted for\n await mapSeries(otherColumns, async (col) => {\n // Determine the unique values to map in this column\n const uniqueValues = uniq(preferences.map((x) => x[col]));\n\n // Map the column to a purpose\n let purposeMapping = currentState.columnToPurposeName[col];\n if (purposeMapping) {\n logger.info(\n colors.magenta(\n `Column \"${col}\" is associated with purpose \"${purposeMapping.purpose}\"`,\n ),\n );\n } else {\n const { purposeName } = await inquirer.prompt<{\n /** purpose name */\n purposeName: string;\n }>([\n {\n name: 'purposeName',\n message: `Choose the purpose that column ${col} is associated with`,\n type: 'list',\n default: purposeNames.find((x) => x.startsWith(purposeSlugs[0])),\n choices: purposeNames,\n },\n ]);\n const [purposeSlug, preferenceSlug] = purposeName.split('->');\n purposeMapping = {\n purpose: purposeSlug,\n preference: preferenceSlug || null,\n valueMapping: {},\n };\n }\n\n // map each value to the purpose value\n await mapSeries(uniqueValues, async (value) => {\n if (purposeMapping.valueMapping[value] !== undefined) {\n logger.info(\n colors.magenta(\n `Value \"${value}\" is associated with purpose value \"${purposeMapping.valueMapping[value]}\"`,\n ),\n );\n return;\n }\n // if preference is null, this column is just for the purpose\n if (purposeMapping.preference === null) {\n const { purposeValue } = await inquirer.prompt<{\n /** purpose value */\n purposeValue: boolean;\n }>([\n {\n name: 'purposeValue',\n message: `Choose the purpose value for value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = purposeValue;\n }\n\n // if preference is not null, this column is for a specific preference\n if (purposeMapping.preference !== null) {\n const preferenceTopic = preferenceTopics.find(\n (x) => x.slug === purposeMapping.preference,\n );\n if (!preferenceTopic) {\n logger.error(\n colors.red(\n `Preference topic \"${purposeMapping.preference}\" not found`,\n ),\n );\n return;\n }\n const preferenceOptions = preferenceTopic.preferenceOptionValues.map(\n ({ slug }) => slug,\n );\n\n if (preferenceTopic.type === PreferenceTopicType.Boolean) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n message:\n // eslint-disable-next-line max-len\n `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.Select) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === value),\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.MultiSelect) {\n const parsedValues = splitCsvToList(value);\n // need to do this serially\n await mapSeries(parsedValues, async (parsedValue) => {\n // if we already have a value, skip re-processing it again\n if (purposeMapping.valueMapping[parsedValue] !== undefined) {\n return;\n }\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${parsedValue}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === parsedValue),\n },\n ]);\n purposeMapping.valueMapping[parsedValue] = preferenceValue;\n });\n return;\n }\n\n throw new Error(\n `Unknown preference topic type: ${preferenceTopic.type}`,\n );\n }\n });\n\n currentState.columnToPurposeName[col] = purposeMapping;\n });\n\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import {\n PreferenceQueryResponseItem,\n PreferenceUpdateItem,\n} from '@transcend-io/privacy-types';\nimport * as t from 'io-ts';\n\nexport const PurposeRowMapping = t.type({\n /**\n * The slug or trackingType of the purpose to map to\n *\n * e.g. `Marketing`\n */\n purpose: t.string,\n /**\n * If the column maps to a preference instead of a purpose\n * this is the slug of the purpose.\n *\n * null value indicates that this column maps to the true/false\n * value of the purpose\n */\n preference: t.union([t.string, t.null]),\n /**\n * The mapping between each row value and purpose/preference value.\n *\n * e.g. for a boolean preference or purpose\n * {\n * 'true': true,\n * 'false': false,\n * '': true,\n * }\n *\n * or for a single or multi select preference\n * {\n * '': true,\n * 'value1': 'Value1',\n * 'value2': 'Value2',\n * }\n */\n valueMapping: t.record(\n t.string,\n t.union([t.string, t.boolean, t.null, t.undefined]),\n ),\n});\n\n/** Override type */\nexport type PurposeRowMapping = t.TypeOf<typeof PurposeRowMapping>;\n\n/**\n * Mapping of column name to purpose row mapping.\n * This is used to map each column in the CSV to the relevant purpose and preference definitions in\n * transcend.\n */\nexport const ColumnPurposeMap = t.record(t.string, PurposeRowMapping);\n\n/** Override type */\nexport type ColumnPurposeMap = t.TypeOf<typeof ColumnPurposeMap>;\n\nexport const IdentifierMetadataForPreference = t.type({\n /** The identifier name */\n name: t.string,\n /** Is unique on preference store */\n isUniqueOnPreferenceStore: t.boolean,\n});\n\n/** Override type */\nexport type IdentifierMetadataForPreference = t.TypeOf<\n typeof IdentifierMetadataForPreference\n>;\n\n/**\n * Mapping of identifier name to the column name in the CSV file.\n * This is used to map each identifier name to the column in the CSV file.\n */\nexport const ColumnIdentifierMap = t.record(\n t.string,\n IdentifierMetadataForPreference,\n);\n\n/** Override type */\nexport type ColumnIdentifierMap = t.TypeOf<typeof ColumnIdentifierMap>;\n\nexport const FileMetadataState = t.intersection([\n t.type({\n /**\n * Definition of how to map each column in the CSV to\n * the relevant purpose and preference definitions in transcend\n */\n columnToPurposeName: t.record(t.string, PurposeRowMapping),\n /** Last time the file was last parsed at */\n lastFetchedAt: t.string,\n /**\n * Mapping of userId to the rows in the file that need to be uploaded\n * These uploads are overwriting non-existent preferences and are safe\n */\n pendingSafeUpdates: t.record(t.string, t.record(t.string, t.string)),\n /**\n * Mapping of userId to the rows in the file that need to be uploaded\n * these records have conflicts with existing consent preferences\n */\n pendingConflictUpdates: t.record(\n t.string,\n t.type({\n record: PreferenceQueryResponseItem,\n row: t.record(t.string, t.string),\n }),\n ),\n /**\n * Mapping of userId to the rows in the file that can be skipped because\n * their preferences are already in the store\n */\n skippedUpdates: t.record(t.string, t.record(t.string, t.string)),\n }),\n t.partial({\n /** Determine which column name in file maps to consent record identifier to upload on */\n identifierColumn: t.string,\n /** Determine which column name in file maps to the timestamp */\n timestampColum: t.string,\n }),\n]);\n\n/** Override type */\nexport type FileMetadataState = t.TypeOf<typeof FileMetadataState>;\n\n/**\n * This is the type of the receipts that are stored in the file\n * that is used to track the state of the upload process.\n * It is used to resume the upload process from where it left off.\n * It is used to persist the state of the upload process across multiple runs.\n */\nexport const PreferenceUpdateMap = t.record(\n t.string,\n // This can either be true to indicate the record is pending\n // or it can be an object showing the object\n // We only return a fixed number of results to avoid\n // making the JSON file too large\n t.union([t.boolean, PreferenceUpdateItem]),\n);\n\n/** Override type */\nexport type PreferenceUpdateMap = t.TypeOf<typeof PreferenceUpdateMap>;\n\n/**\n * This is the type of the pending updates that are safe to run without\n * conflicts with existing consent preferences.\n *\n * Key is primaryKey of the record in the file.\n * The value is the row in the file that is safe to upload.\n */\nexport const PendingSafePreferenceUpdates = t.record(\n t.string,\n // This can either be true to indicate the record is safe\n // or it can be an object showing the object\n // We only return a fixed number of results to avoid\n // making the JSON file too large\n t.union([t.boolean, t.record(t.string, t.string)]),\n);\n\n/** Override type */\nexport type PendingSafePreferenceUpdates = t.TypeOf<\n typeof PendingSafePreferenceUpdates\n>;\n\n/**\n * These are the updates that failed to be uploaded to the API.\n */\nexport const FailingPreferenceUpdates = t.record(\n t.string,\n t.type({\n /** Time upload ran at */\n uploadedAt: t.string,\n /** Attempts to upload that resulted in an error */\n error: t.string,\n /** The update body */\n update: PreferenceUpdateItem,\n }),\n);\n\n/** Override type */\nexport type FailingPreferenceUpdates = t.TypeOf<\n typeof FailingPreferenceUpdates\n>;\n\n/**\n * This is the type of the pending updates that are in conflict with existing consent preferences.\n *\n * Key is primaryKey of the record in the file.\n * The value is the row in the file that is pending upload.\n */\nexport const PendingWithConflictPreferenceUpdates = t.record(\n t.string,\n // We always return the conflicts for investigation\n t.type({\n /** Record to be inserted to transcend v1/preferences API */\n record: PreferenceQueryResponseItem,\n /** The row in the file that is pending upload */\n row: t.record(t.string, t.string),\n }),\n);\n\n/** Override type */\nexport type PendingWithConflictPreferenceUpdates = t.TypeOf<\n typeof PendingWithConflictPreferenceUpdates\n>;\n\n/**\n * The set of preference updates that are skipped\n * Key is primaryKey and value is the row in the CSV\n * that is skipped.\n *\n * This is usually because the preferences are already in the store\n * or there are duplicate rows in the CSV file that are identical.\n */\nexport const SkippedPreferenceUpdates = t.record(\n t.string,\n t.record(t.string, t.string),\n);\n\n/** Override type */\nexport type SkippedPreferenceUpdates = t.TypeOf<\n typeof SkippedPreferenceUpdates\n>;\n\n/** Persist this data between runs of the script */\nexport const PreferenceState = t.type({\n /**\n * Store a cache of previous files read in\n */\n fileMetadata: t.record(t.string, FileMetadataState),\n /**\n * The set of successful uploads to Transcend\n * Mapping from userId to the upload metadata\n */\n failingUpdates: t.record(\n t.string,\n t.type({\n /** Time upload ran at */\n uploadedAt: t.string,\n /** Attempts to upload that resulted in an error */\n error: t.string,\n /** The update body */\n update: PreferenceUpdateItem,\n }),\n ),\n /**\n * The set of pending uploads to Transcend\n * Mapping from userId to the upload metadata\n */\n pendingUpdates: t.record(t.string, PreferenceUpdateItem),\n});\n\n/** Override type */\nexport type PreferenceState = t.TypeOf<typeof PreferenceState>;\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-HCPNMNS3.cjs","../src/lib/preference-management/uploadPreferenceManagementPreferencesInteractive.ts","../src/lib/preference-management/parsePreferenceManagementCsv.ts","../src/lib/preference-management/getPreferencesForIdentifiers.ts","../src/lib/preference-management/withPreferenceQueryRetry.ts","../src/lib/preference-management/parsePreferenceIdentifiersFromCsv.ts","../src/lib/preference-management/parsePreferenceAndPurposeValuesFromCsv.ts","../src/lib/preference-management/codecs.ts"],"names":["RETRY_PREFERENCE_MSGS","s","withPreferenceQueryRetry","fn","maxAttempts","baseDelayMs","isRetryable","_err","msg","m","onRetry","attempt","err"],"mappings":"AAAA,2lCAA2J,wDAAyC,wDAAuE,gFCQxP,oCACC,qGAGI,+DAEO,qJCXZ,qDCES,ICGfA,EAAAA,CAAkC,CAC7C,WAAA,CACA,YAAA,CACA,WAAA,CACA,iBAAA,CACA,sBAAA,CACA,sBAAA,CACA,uBACF,CAAA,CAAE,GAAA,CAAKC,CAAAA,EAAMA,CAAAA,CAAE,WAAA,CAAY,CAAC,CAAA,CAwB5B,MAAA,SAAsBC,CAAAA,CACpBC,CAAAA,CACA,CACE,WAAA,CAAAC,CAAAA,CAAc,CAAA,CACd,WAAA,CAAAC,CAAAA,CAAc,GAAA,CACd,WAAA,CAAAC,CAAAA,CAAc,CAACC,CAAAA,CAAMC,CAAAA,CAAAA,EACnBR,EAAAA,CAAsB,IAAA,CAAMS,CAAAA,EAAMD,CAAAA,CAAI,WAAA,CAAY,CAAA,CAAE,QAAA,CAASC,CAAC,CAAC,CAAA,CACjE,OAAA,CAAAC,CACF,CAAA,CAAkB,CAAC,CAAA,CACP,CACZ,IAAIC,CAAAA,CAAU,CAAA,CAEd,GAAA,CAAA,CAAA,CAAA,CAAa,CACXA,CAAAA,EAAW,CAAA,CACX,GAAI,CACF,OAAO,MAAMR,CAAAA,CAAG,CAElB,CAAA,KAAA,CAASS,CAAAA,CAAU,CACjB,IAAMJ,CAAAA,kBAAAA,CACHI,CAAAA,EAAAA,iBAAQA,CAAAA,qBAAI,QAAA,6BAAU,MAAA,EAAQA,CAAAA,CAAI,OAAA,CAAA,CAAA,SACnC,MAAA,kBAAOA,CAAAA,SAAO,iBAAe,GAAA,CAE/B,EAAA,CAAI,CAAA,CADcD,CAAAA,CAAUP,CAAAA,EAAeE,CAAAA,CAAYM,CAAAA,CAAKJ,CAAG,CAAA,CAAA,CAE7D,MAAM,IAAI,KAAA,CACR,CAAA,8BAAA,EAAiCG,CAAO,CAAA,aAAA,EAAgBH,CAAG,CAAA,CAAA;ACiC/D;ACnBU;ACyBD,oGAAA;ANbP;AAGA;AAAA;AAKQ;AAAK;AACgC,sCAAA;AA+FY","file":"/home/runner/work/cli/cli/dist/chunk-HCPNMNS3.cjs","sourcesContent":[null,"import {\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllPurposes,\n fetchAllPreferenceTopics,\n PreferenceTopic,\n Purpose,\n} from '../graphql';\nimport colors from 'colors';\nimport { map } from 'bluebird';\nimport { chunk } from 'lodash-es';\nimport { logger } from '../../logger';\nimport cliProgress from 'cli-progress';\nimport { parseAttributesFromString } from '../requests';\nimport { PersistedState } from '@transcend-io/persisted-state';\nimport { parsePreferenceManagementCsvWithCache } from './parsePreferenceManagementCsv';\nimport { PreferenceState } from './codecs';\nimport { PreferenceUpdateItem } from '@transcend-io/privacy-types';\nimport { apply } from '@transcend-io/type-utils';\nimport { NONE_PREFERENCE_MAP } from './parsePreferenceTimestampsFromCsv';\nimport { getPreferenceUpdatesFromRow } from './getPreferenceUpdatesFromRow';\n\n/**\n * Upload a set of consent preferences\n *\n * @param options - Options\n */\nexport async function uploadPreferenceManagementPreferencesInteractive({\n auth,\n sombraAuth,\n receiptFilepath,\n file,\n partition,\n isSilent = true,\n dryRun = false,\n skipWorkflowTriggers = false,\n skipConflictUpdates = false,\n skipExistingRecordCheck = false,\n attributes = [],\n transcendUrl,\n forceTriggerWorkflows = false,\n}: {\n /** The Transcend API key */\n auth: string;\n /** Sombra API key authentication */\n sombraAuth?: string;\n /** Partition key */\n partition: string;\n /** File where to store receipt and continue from where left off */\n receiptFilepath: string;\n /** The file to process */\n file: string;\n /** API URL for Transcend backend */\n transcendUrl: string;\n /** Whether to do a dry run */\n dryRun?: boolean;\n /** Whether to upload as isSilent */\n isSilent?: boolean;\n /** Attributes string pre-parse. In format Key:Value */\n attributes?: string[];\n /** Skip workflow triggers */\n skipWorkflowTriggers?: boolean;\n /**\n * When true, only update preferences that do not conflict with existing\n * preferences. When false, update all preferences in CSV based on timestamp.\n */\n skipConflictUpdates?: boolean;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck?: boolean;\n /** Whether to force trigger workflows */\n forceTriggerWorkflows?: boolean;\n}): Promise<void> {\n // Parse out the extra attributes to apply to all requests uploaded\n const parsedAttributes = parseAttributesFromString(attributes);\n\n // Create a new state file to store the requests from this run\n const preferenceState = new PersistedState(receiptFilepath, PreferenceState, {\n fileMetadata: {},\n failingUpdates: {},\n pendingUpdates: {},\n });\n const failingRequests = preferenceState.getValue('failingUpdates');\n const pendingRequests = preferenceState.getValue('pendingUpdates');\n let fileMetadata = preferenceState.getValue('fileMetadata');\n\n logger.info(\n colors.magenta(\n 'Restored cache, there are: \\n' +\n `${\n Object.values(failingRequests).length\n } failing requests to be retried\\n` +\n `${\n Object.values(pendingRequests).length\n } pending requests to be processed\\n` +\n `The following files are stored in cache and will be used:\\n${Object.keys(\n fileMetadata,\n )\n .map((x) => x)\n .join('\\n')}\\n` +\n `The following file will be processed: ${file}\\n`,\n ),\n );\n\n // Create GraphQL client to connect to Transcend backend\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const [sombra, purposes, preferenceTopics] = await Promise.all([\n // Create sombra instance to communicate with\n createSombraGotInstance(transcendUrl, auth, sombraAuth),\n // get all purposes and topics\n forceTriggerWorkflows\n ? Promise.resolve([] as Purpose[])\n : fetchAllPurposes(client),\n forceTriggerWorkflows\n ? Promise.resolve([] as PreferenceTopic[])\n : fetchAllPreferenceTopics(client),\n ]);\n\n // Process the file\n await parsePreferenceManagementCsvWithCache(\n {\n file,\n purposeSlugs: purposes.map((x) => x.trackingType),\n preferenceTopics,\n sombra,\n partitionKey: partition,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n },\n preferenceState,\n );\n\n // Construct the pending updates\n const pendingUpdates: Record<string, PreferenceUpdateItem> = {};\n fileMetadata = preferenceState.getValue('fileMetadata');\n const metadata = fileMetadata[file];\n\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.pendingSafeUpdates).length\n } safe updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.pendingConflictUpdates).length\n } conflict updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.skippedUpdates).length\n } skipped updates in ${file}`,\n ),\n );\n\n // Update either safe updates only or safe + conflict\n Object.entries({\n ...metadata.pendingSafeUpdates,\n ...(skipConflictUpdates\n ? {}\n : apply(metadata.pendingConflictUpdates, ({ row }) => row)),\n }).forEach(([userId, update]) => {\n // Determine timestamp\n const timestamp =\n metadata.timestampColum === NONE_PREFERENCE_MAP\n ? new Date()\n : new Date(update[metadata.timestampColum!]);\n\n // Determine updates\n const updates = getPreferenceUpdatesFromRow({\n row: update,\n columnToPurposeName: metadata.columnToPurposeName,\n preferenceTopics,\n purposeSlugs: purposes.map((x) => x.trackingType),\n });\n pendingUpdates[userId] = {\n userId,\n partition,\n timestamp: timestamp.toISOString(),\n purposes: Object.entries(updates).map(([purpose, value]) => ({\n ...value,\n purpose,\n workflowSettings: {\n attributes: parsedAttributes,\n isSilent,\n skipWorkflowTrigger: skipWorkflowTriggers,\n },\n })),\n };\n });\n await preferenceState.setValue(pendingUpdates, 'pendingUpdates');\n await preferenceState.setValue({}, 'failingUpdates');\n\n // Exist early if dry run\n if (dryRun) {\n logger.info(\n colors.green(\n `Dry run complete, exiting. ${\n Object.values(pendingUpdates).length\n } pending updates. Check file: ${receiptFilepath}`,\n ),\n );\n return;\n }\n\n logger.info(\n colors.magenta(\n `Uploading ${\n Object.values(pendingUpdates).length\n } preferences to partition: ${partition}`,\n ),\n );\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n\n // Build a GraphQL client\n let total = 0;\n const updatesToRun = Object.entries(pendingUpdates);\n const chunkedUpdates = chunk(updatesToRun, skipWorkflowTriggers ? 100 : 10);\n progressBar.start(updatesToRun.length, 0);\n await map(\n chunkedUpdates,\n async (currentChunk) => {\n // Make the request\n try {\n await sombra\n .put('v1/preferences', {\n json: {\n records: currentChunk.map(([, update]) => update),\n skipWorkflowTriggers,\n forceTriggerWorkflows,\n },\n })\n .json();\n } catch (err) {\n try {\n const parsed = JSON.parse(err?.response?.body || '{}');\n if (parsed.error) {\n logger.error(colors.red(`Error: ${parsed.error}`));\n }\n } catch (e) {\n // continue\n }\n logger.error(\n colors.red(\n `Failed to upload ${\n currentChunk.length\n } user preferences to partition ${partition}: ${\n err?.response?.body || err?.message\n }`,\n ),\n );\n const failingUpdates = preferenceState.getValue('failingUpdates');\n currentChunk.forEach(([userId, update]) => {\n failingUpdates[userId] = {\n uploadedAt: new Date().toISOString(),\n update,\n error: err?.response?.body || err?.message || 'Unknown error',\n };\n });\n await preferenceState.setValue(failingUpdates, 'failingUpdates');\n }\n\n total += currentChunk.length;\n progressBar.update(total);\n },\n {\n concurrency: 40,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n logger.info(\n colors.green(\n `Successfully uploaded ${\n updatesToRun.length\n } user preferences to partition ${partition} in \"${\n totalTime / 1000\n }\" seconds!`,\n ),\n );\n}\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport type { Got } from 'got';\nimport { keyBy } from 'lodash-es';\nimport * as t from 'io-ts';\nimport colors from 'colors';\nimport { FileMetadataState, PreferenceState } from './codecs';\nimport { logger } from '../../logger';\nimport { readCsv } from '../requests';\nimport { getPreferencesForIdentifiers } from './getPreferencesForIdentifiers';\nimport { PreferenceTopic } from '../graphql';\nimport { getPreferenceUpdatesFromRow } from './getPreferenceUpdatesFromRow';\nimport { parsePreferenceTimestampsFromCsv } from './parsePreferenceTimestampsFromCsv';\nimport { parsePreferenceIdentifiersFromCsv } from './parsePreferenceIdentifiersFromCsv';\nimport { parsePreferenceAndPurposeValuesFromCsv } from './parsePreferenceAndPurposeValuesFromCsv';\nimport { checkIfPendingPreferenceUpdatesAreNoOp } from './checkIfPendingPreferenceUpdatesAreNoOp';\nimport { checkIfPendingPreferenceUpdatesCauseConflict } from './checkIfPendingPreferenceUpdatesCauseConflict';\n\n/**\n * Parse a file into the cache\n *\n *\n * @param options - Options\n * @param cache - The cache to store the parsed file in\n * @returns The cache with the parsed file\n */\nexport async function parsePreferenceManagementCsvWithCache(\n {\n file,\n sombra,\n purposeSlugs,\n preferenceTopics,\n partitionKey,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n }: {\n /** File to parse */\n file: string;\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Sombra got instance */\n sombra: Got;\n /** Partition key */\n partitionKey: string;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck: boolean;\n /** Wheather to force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n cache: PersistedState<typeof PreferenceState>,\n): Promise<void> {\n // Start the timer\n const t0 = new Date().getTime();\n\n // Get the current metadata\n const fileMetadata = cache.getValue('fileMetadata');\n\n // Read in the file\n logger.info(colors.magenta(`Reading in file: \"${file}\"`));\n let preferences = readCsv(file, t.record(t.string, t.string));\n\n // start building the cache, can use previous cache as well\n let currentState: FileMetadataState = {\n columnToPurposeName: {},\n pendingSafeUpdates: {},\n pendingConflictUpdates: {},\n skippedUpdates: {},\n // Load in the last fetched time\n ...((fileMetadata[file] || {}) as Partial<FileMetadataState>),\n lastFetchedAt: new Date().toISOString(),\n };\n\n // Validate that all timestamps are present in the file\n currentState = await parsePreferenceTimestampsFromCsv(\n preferences,\n currentState,\n );\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Validate that all identifiers are present and unique\n const result = await parsePreferenceIdentifiersFromCsv(\n preferences,\n currentState,\n );\n currentState = result.currentState;\n preferences = result.preferences;\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Ensure all other columns are mapped to purpose and preference\n // slug values\n currentState = await parsePreferenceAndPurposeValuesFromCsv(\n preferences,\n currentState,\n {\n preferenceTopics,\n purposeSlugs,\n forceTriggerWorkflows,\n },\n );\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Grab existing preference store records\n const identifiers = preferences.map(\n (pref) => pref[currentState.identifierColumn!],\n );\n const existingConsentRecords = skipExistingRecordCheck\n ? []\n : await getPreferencesForIdentifiers(sombra, {\n identifiers: identifiers.map((x) => ({ value: x })),\n partitionKey,\n });\n const consentRecordByIdentifier = keyBy(existingConsentRecords, 'userId');\n\n // Clear out previous updates\n currentState.pendingConflictUpdates = {};\n currentState.pendingSafeUpdates = {};\n currentState.skippedUpdates = {};\n\n // Process each row\n preferences.forEach((pref) => {\n // Grab unique Id for the user\n const userId = pref[currentState.identifierColumn!];\n\n // determine updates for user\n const pendingUpdates = getPreferenceUpdatesFromRow({\n row: pref,\n columnToPurposeName: currentState.columnToPurposeName,\n preferenceTopics,\n purposeSlugs,\n });\n\n // Grab current state of the update\n const currentConsentRecord = consentRecordByIdentifier[userId];\n if (forceTriggerWorkflows && !currentConsentRecord) {\n throw new Error(\n `No existing consent record found for user with id: ${userId}. \n When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`,\n );\n }\n // Check if the update can be skipped\n // this is the case if a record exists, and the purpose\n // and preference values are all in sync\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesAreNoOp({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n }) &&\n !forceTriggerWorkflows\n ) {\n currentState.skippedUpdates[userId] = pref;\n return;\n }\n\n // Determine if there are any conflicts\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesCauseConflict({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n })\n ) {\n currentState.pendingConflictUpdates[userId] = {\n row: pref,\n record: currentConsentRecord,\n };\n return;\n }\n\n // Add to pending updates\n currentState.pendingSafeUpdates[userId] = pref;\n });\n\n // Read in the file\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n const t1 = new Date().getTime();\n logger.info(\n colors.green(\n `Successfully pre-processed file: \"${file}\" in ${(t1 - t0) / 1000}s`,\n ),\n );\n}\n","import { PreferenceQueryResponseItem } from '@transcend-io/privacy-types';\nimport type { Got } from 'got';\nimport colors from 'colors';\nimport cliProgress from 'cli-progress';\nimport { chunk } from 'lodash-es';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { map } from 'bluebird';\nimport { logger } from '../../logger';\nimport { withPreferenceQueryRetry } from './withPreferenceQueryRetry';\nimport { ConsentPreferenceResponse } from './types';\n\n/**\n * Grab the current consent preference values for a list of identifiers\n *\n * @param sombra - Backend to make API call to\n * @param options - Options\n * @returns Plaintext context information\n */\nexport async function getPreferencesForIdentifiers(\n sombra: Got,\n {\n identifiers,\n partitionKey,\n skipLogging = false,\n concurrency = 40,\n }: {\n /** The list of identifiers to look up */\n identifiers: {\n /** The value of the identifier */\n value: string;\n }[];\n /** The partition key to look up */\n partitionKey: string;\n /** Whether to skip logging */\n skipLogging?: boolean;\n /** Concurrency for requests (default 40) */\n concurrency?: number;\n },\n): Promise<PreferenceQueryResponseItem[]> {\n const results: PreferenceQueryResponseItem[] = [];\n const groupedIdentifiers = chunk(identifiers, 100);\n\n // create a new progress bar instance and use shades_classic theme\n const t0 = new Date().getTime();\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n if (!skipLogging) {\n progressBar.start(identifiers.length, 0);\n }\n\n let total = 0;\n await map(\n groupedIdentifiers,\n async (group) => {\n const rawResult = await withPreferenceQueryRetry(\n () =>\n sombra\n .post(`v1/preferences/${partitionKey}/query`, {\n json: {\n filter: { identifiers: group },\n limit: group.length,\n },\n })\n .json(),\n {\n onRetry: (attempt, _err, msg) => {\n logger.warn(\n colors.yellow(\n `[RETRY] group size=${group.length} partition=${partitionKey} attempt=${attempt}: ${msg}`,\n ),\n );\n },\n },\n );\n\n const result = decodeCodec(ConsentPreferenceResponse, rawResult);\n results.push(...result.nodes);\n total += group.length;\n progressBar.update(total);\n },\n {\n concurrency,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n if (!skipLogging) {\n // Log completion time\n logger.info(\n colors.green(`Completed download in \"${totalTime / 1000}\" seconds.`),\n );\n }\n\n return results;\n}\n","import colors from 'colors';\nimport { logger } from '../../logger';\nimport { sleepPromise } from '../helpers';\n\n/**\n * Transient network / platform errors that merit a retry.\n * Keep this list short and specific to avoid masking real failures.\n */\nexport const RETRY_PREFERENCE_MSGS: string[] = [\n 'ENOTFOUND',\n 'ECONNRESET',\n 'ETIMEDOUT',\n '502 Bad Gateway',\n '504 Gateway Time-out',\n 'Task timed out after',\n 'unknown request error',\n].map((s) => s.toLowerCase());\n\n/**\n * Options for retrying preference queries.\n */\nexport type RetryOptions = {\n /** Max attempts including the first try (default 3) */\n maxAttempts?: number;\n /** Initial backoff in ms (default 250) */\n baseDelayMs?: number;\n /** Optional custom predicate to decide if an error is retryable */\n isRetryable?: (err: unknown, message: string) => boolean;\n /** Optional hook to log on each retry */\n onRetry?: (attempt: number, err: unknown, message: string) => void;\n};\n\n/**\n * Run an async function with standardized retry behavior for preference queries.\n * Exponential backoff with jitter; only retries on known-transient messages.\n *\n * @param fn - Function to run\n * @param options - Retry options\n * @returns Result of the function\n */\nexport async function withPreferenceQueryRetry<T>(\n fn: () => Promise<T>,\n {\n maxAttempts = 3,\n baseDelayMs = 250,\n isRetryable = (_err, msg) =>\n RETRY_PREFERENCE_MSGS.some((m) => msg.toLowerCase().includes(m)),\n onRetry,\n }: RetryOptions = {},\n): Promise<T> {\n let attempt = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n attempt += 1;\n try {\n return await fn();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (err: any) {\n const msg: string =\n (err && (err.response?.body || err.message)) ??\n String(err ?? 'Unknown error');\n const willRetry = attempt < maxAttempts && isRetryable(err, msg);\n if (!willRetry) {\n throw new Error(\n `Preference query failed after ${attempt} attempt(s): ${msg}`,\n );\n }\n onRetry?.(attempt, err, msg);\n\n const backoff = baseDelayMs * 2 ** (attempt - 1);\n const jitter = Math.floor(Math.random() * baseDelayMs);\n const delay = backoff + jitter;\n logger.warn(\n colors.yellow(\n `[retry] attempt ${attempt}/${\n maxAttempts - 1\n }; backing off ${delay}ms: ${msg}`,\n ),\n );\n await sleepPromise(delay);\n }\n }\n}\n","import { uniq, groupBy, difference } from 'lodash-es';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { FileMetadataState } from './codecs';\nimport { logger } from '../../logger';\nimport { inquirerConfirmBoolean } from '../helpers';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse identifiers from a CSV list of preferences\n *\n * Ensures that all rows have a valid identifier\n * and that all identifiers are unique.\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceIdentifiersFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<{\n /** The updated state */\n currentState: FileMetadataState;\n /** The updated preferences */\n preferences: Record<string, string>[];\n}> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const remainingColumnsForIdentifier = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the identifier column to work off of\n if (!currentState.identifierColumn) {\n const { identifierName } = await inquirer.prompt<{\n /** Identifier name */\n identifierName: string;\n }>([\n {\n name: 'identifierName',\n message:\n 'Choose the column that will be used as the identifier to upload consent preferences by',\n type: 'list',\n default:\n remainingColumnsForIdentifier.find((col) =>\n col.toLowerCase().includes('email'),\n ) || remainingColumnsForIdentifier[0],\n choices: remainingColumnsForIdentifier,\n },\n ]);\n currentState.identifierColumn = identifierName;\n }\n logger.info(\n colors.magenta(\n `Using identifier column \"${currentState.identifierColumn}\"`,\n ),\n );\n\n // Validate that the identifier column is present for all rows and unique\n const identifierColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.identifierColumn!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (identifierColumnsMissing.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" is missing a value for the following rows: ${identifierColumnsMissing.join(\n ', ',\n )}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to skip rows missing an identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to skip rows missing an identifier?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n\n // Filter out rows missing an identifier\n const previous = preferences.length;\n preferences = preferences.filter(\n (pref) => pref[currentState.identifierColumn!],\n );\n logger.info(\n colors.yellow(\n `Skipped ${previous - preferences.length} rows missing an identifier`,\n ),\n );\n }\n logger.info(\n colors.magenta(\n `The identifier column \"${currentState.identifierColumn}\" is present for all rows`,\n ),\n );\n\n // Validate that all identifiers are unique\n const rowsByUserId = groupBy(preferences, currentState.identifierColumn);\n const duplicateIdentifiers = Object.entries(rowsByUserId).filter(\n ([, rows]) => rows.length > 1,\n );\n if (duplicateIdentifiers.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" has duplicate values for the following rows: ${duplicateIdentifiers\n .slice(0, 10)\n .map(([userId, rows]) => `${userId} (${rows.length})`)\n .join('\\n')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to take the most recent update\n // for each duplicate identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to automatically take the latest update?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n preferences = Object.entries(rowsByUserId)\n .map(([, rows]) => {\n const sorted = rows.sort(\n (a, b) =>\n new Date(b[currentState.timestampColum!]).getTime() -\n new Date(a[currentState.timestampColum!]).getTime(),\n );\n return sorted[0];\n })\n .filter((x) => x);\n }\n\n return { currentState, preferences };\n}\n/* eslint-enable no-param-reassign */\n","import { uniq, difference } from 'lodash-es';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { FileMetadataState } from './codecs';\nimport { logger } from '../../logger';\nimport { mapSeries } from 'bluebird';\nimport { PreferenceTopic } from '../graphql';\nimport { PreferenceTopicType } from '@transcend-io/privacy-types';\nimport { splitCsvToList } from '../requests';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse out the purpose.enabled and preference values from a CSV file\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @param options - Options\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceAndPurposeValuesFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n {\n purposeSlugs,\n preferenceTopics,\n forceTriggerWorkflows,\n }: {\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const otherColumns = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...(currentState.timestampColum ? [currentState.timestampColum] : []),\n ]);\n if (otherColumns.length === 0) {\n if (forceTriggerWorkflows) {\n return currentState;\n }\n throw new Error('No other columns to process');\n }\n\n // The purpose and preferences to map to\n const purposeNames = [\n ...purposeSlugs,\n ...preferenceTopics.map((x) => `${x.purpose.trackingType}->${x.slug}`),\n ];\n\n // Ensure all columns are accounted for\n await mapSeries(otherColumns, async (col) => {\n // Determine the unique values to map in this column\n const uniqueValues = uniq(preferences.map((x) => x[col]));\n\n // Map the column to a purpose\n let purposeMapping = currentState.columnToPurposeName[col];\n if (purposeMapping) {\n logger.info(\n colors.magenta(\n `Column \"${col}\" is associated with purpose \"${purposeMapping.purpose}\"`,\n ),\n );\n } else {\n const { purposeName } = await inquirer.prompt<{\n /** purpose name */\n purposeName: string;\n }>([\n {\n name: 'purposeName',\n message: `Choose the purpose that column ${col} is associated with`,\n type: 'list',\n default: purposeNames.find((x) => x.startsWith(purposeSlugs[0])),\n choices: purposeNames,\n },\n ]);\n const [purposeSlug, preferenceSlug] = purposeName.split('->');\n purposeMapping = {\n purpose: purposeSlug,\n preference: preferenceSlug || null,\n valueMapping: {},\n };\n }\n\n // map each value to the purpose value\n await mapSeries(uniqueValues, async (value) => {\n if (purposeMapping.valueMapping[value] !== undefined) {\n logger.info(\n colors.magenta(\n `Value \"${value}\" is associated with purpose value \"${purposeMapping.valueMapping[value]}\"`,\n ),\n );\n return;\n }\n // if preference is null, this column is just for the purpose\n if (purposeMapping.preference === null) {\n const { purposeValue } = await inquirer.prompt<{\n /** purpose value */\n purposeValue: boolean;\n }>([\n {\n name: 'purposeValue',\n message: `Choose the purpose value for value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = purposeValue;\n }\n\n // if preference is not null, this column is for a specific preference\n if (purposeMapping.preference !== null) {\n const preferenceTopic = preferenceTopics.find(\n (x) => x.slug === purposeMapping.preference,\n );\n if (!preferenceTopic) {\n logger.error(\n colors.red(\n `Preference topic \"${purposeMapping.preference}\" not found`,\n ),\n );\n return;\n }\n const preferenceOptions = preferenceTopic.preferenceOptionValues.map(\n ({ slug }) => slug,\n );\n\n if (preferenceTopic.type === PreferenceTopicType.Boolean) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n message:\n // eslint-disable-next-line max-len\n `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.Select) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === value),\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.MultiSelect) {\n const parsedValues = splitCsvToList(value);\n // need to do this serially\n await mapSeries(parsedValues, async (parsedValue) => {\n // if we already have a value, skip re-processing it again\n if (purposeMapping.valueMapping[parsedValue] !== undefined) {\n return;\n }\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${parsedValue}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === parsedValue),\n },\n ]);\n purposeMapping.valueMapping[parsedValue] = preferenceValue;\n });\n return;\n }\n\n throw new Error(\n `Unknown preference topic type: ${preferenceTopic.type}`,\n );\n }\n });\n\n currentState.columnToPurposeName[col] = purposeMapping;\n });\n\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import {\n PreferenceQueryResponseItem,\n PreferenceUpdateItem,\n} from '@transcend-io/privacy-types';\nimport * as t from 'io-ts';\n\nexport const PurposeRowMapping = t.type({\n /**\n * The slug or trackingType of the purpose to map to\n *\n * e.g. `Marketing`\n */\n purpose: t.string,\n /**\n * If the column maps to a preference instead of a purpose\n * this is the slug of the purpose.\n *\n * null value indicates that this column maps to the true/false\n * value of the purpose\n */\n preference: t.union([t.string, t.null]),\n /**\n * The mapping between each row value and purpose/preference value.\n *\n * e.g. for a boolean preference or purpose\n * {\n * 'true': true,\n * 'false': false,\n * '': true,\n * }\n *\n * or for a single or multi select preference\n * {\n * '': true,\n * 'value1': 'Value1',\n * 'value2': 'Value2',\n * }\n */\n valueMapping: t.record(\n t.string,\n t.union([t.string, t.boolean, t.null, t.undefined]),\n ),\n});\n\n/** Override type */\nexport type PurposeRowMapping = t.TypeOf<typeof PurposeRowMapping>;\n\n/**\n * Mapping of column name to purpose row mapping.\n * This is used to map each column in the CSV to the relevant purpose and preference definitions in\n * transcend.\n */\nexport const ColumnPurposeMap = t.record(t.string, PurposeRowMapping);\n\n/** Override type */\nexport type ColumnPurposeMap = t.TypeOf<typeof ColumnPurposeMap>;\n\nexport const IdentifierMetadataForPreference = t.type({\n /** The identifier name */\n name: t.string,\n /** Is unique on preference store */\n isUniqueOnPreferenceStore: t.boolean,\n});\n\n/** Override type */\nexport type IdentifierMetadataForPreference = t.TypeOf<\n typeof IdentifierMetadataForPreference\n>;\n\n/**\n * Mapping of identifier name to the column name in the CSV file.\n * This is used to map each identifier name to the column in the CSV file.\n */\nexport const ColumnIdentifierMap = t.record(\n t.string,\n IdentifierMetadataForPreference,\n);\n\n/** Override type */\nexport type ColumnIdentifierMap = t.TypeOf<typeof ColumnIdentifierMap>;\n\nexport const FileMetadataState = t.intersection([\n t.type({\n /**\n * Definition of how to map each column in the CSV to\n * the relevant purpose and preference definitions in transcend\n */\n columnToPurposeName: t.record(t.string, PurposeRowMapping),\n /** Last time the file was last parsed at */\n lastFetchedAt: t.string,\n /**\n * Mapping of userId to the rows in the file that need to be uploaded\n * These uploads are overwriting non-existent preferences and are safe\n */\n pendingSafeUpdates: t.record(t.string, t.record(t.string, t.string)),\n /**\n * Mapping of userId to the rows in the file that need to be uploaded\n * these records have conflicts with existing consent preferences\n */\n pendingConflictUpdates: t.record(\n t.string,\n t.type({\n record: PreferenceQueryResponseItem,\n row: t.record(t.string, t.string),\n }),\n ),\n /**\n * Mapping of userId to the rows in the file that can be skipped because\n * their preferences are already in the store\n */\n skippedUpdates: t.record(t.string, t.record(t.string, t.string)),\n }),\n t.partial({\n /** Determine which column name in file maps to consent record identifier to upload on */\n identifierColumn: t.string,\n /** Determine which column name in file maps to the timestamp */\n timestampColum: t.string,\n }),\n]);\n\n/** Override type */\nexport type FileMetadataState = t.TypeOf<typeof FileMetadataState>;\n\n/**\n * This is the type of the receipts that are stored in the file\n * that is used to track the state of the upload process.\n * It is used to resume the upload process from where it left off.\n * It is used to persist the state of the upload process across multiple runs.\n */\nexport const PreferenceUpdateMap = t.record(\n t.string,\n // This can either be true to indicate the record is pending\n // or it can be an object showing the object\n // We only return a fixed number of results to avoid\n // making the JSON file too large\n t.union([t.boolean, PreferenceUpdateItem]),\n);\n\n/** Override type */\nexport type PreferenceUpdateMap = t.TypeOf<typeof PreferenceUpdateMap>;\n\n/**\n * This is the type of the pending updates that are safe to run without\n * conflicts with existing consent preferences.\n *\n * Key is primaryKey of the record in the file.\n * The value is the row in the file that is safe to upload.\n */\nexport const PendingSafePreferenceUpdates = t.record(\n t.string,\n // This can either be true to indicate the record is safe\n // or it can be an object showing the object\n // We only return a fixed number of results to avoid\n // making the JSON file too large\n t.union([t.boolean, t.record(t.string, t.string)]),\n);\n\n/** Override type */\nexport type PendingSafePreferenceUpdates = t.TypeOf<\n typeof PendingSafePreferenceUpdates\n>;\n\n/**\n * These are the updates that failed to be uploaded to the API.\n */\nexport const FailingPreferenceUpdates = t.record(\n t.string,\n t.type({\n /** Time upload ran at */\n uploadedAt: t.string,\n /** Attempts to upload that resulted in an error */\n error: t.string,\n /** The update body */\n update: PreferenceUpdateItem,\n }),\n);\n\n/** Override type */\nexport type FailingPreferenceUpdates = t.TypeOf<\n typeof FailingPreferenceUpdates\n>;\n\n/**\n * This is the type of the pending updates that are in conflict with existing consent preferences.\n *\n * Key is primaryKey of the record in the file.\n * The value is the row in the file that is pending upload.\n */\nexport const PendingWithConflictPreferenceUpdates = t.record(\n t.string,\n // We always return the conflicts for investigation\n t.type({\n /** Record to be inserted to transcend v1/preferences API */\n record: PreferenceQueryResponseItem,\n /** The row in the file that is pending upload */\n row: t.record(t.string, t.string),\n }),\n);\n\n/** Override type */\nexport type PendingWithConflictPreferenceUpdates = t.TypeOf<\n typeof PendingWithConflictPreferenceUpdates\n>;\n\n/**\n * The set of preference updates that are skipped\n * Key is primaryKey and value is the row in the CSV\n * that is skipped.\n *\n * This is usually because the preferences are already in the store\n * or there are duplicate rows in the CSV file that are identical.\n */\nexport const SkippedPreferenceUpdates = t.record(\n t.string,\n t.record(t.string, t.string),\n);\n\n/** Override type */\nexport type SkippedPreferenceUpdates = t.TypeOf<\n typeof SkippedPreferenceUpdates\n>;\n\n/** Persist this data between runs of the script */\nexport const PreferenceState = t.type({\n /**\n * Store a cache of previous files read in\n */\n fileMetadata: t.record(t.string, FileMetadataState),\n /**\n * The set of successful uploads to Transcend\n * Mapping from userId to the upload metadata\n */\n failingUpdates: t.record(\n t.string,\n t.type({\n /** Time upload ran at */\n uploadedAt: t.string,\n /** Attempts to upload that resulted in an error */\n error: t.string,\n /** The update body */\n update: PreferenceUpdateItem,\n }),\n ),\n /**\n * The set of pending uploads to Transcend\n * Mapping from userId to the upload metadata\n */\n pendingUpdates: t.record(t.string, PreferenceUpdateItem),\n});\n\n/** Override type */\nexport type PreferenceState = t.TypeOf<typeof PreferenceState>;\n"]}
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkECGHWDVPcjs = require('./chunk-ECGHWDVP.cjs');var _chunkKUBXRT3Vcjs = require('./chunk-KUBXRT3V.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkEYOQLGDVcjs = require('./chunk-EYOQLGDV.cjs');var _privacytypes = require('@transcend-io/privacy-types');var _bluebird = require('bluebird');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function nt({auth:e,deploy:s=!1,transcendUrl:o=_chunkEYOQLGDVcjs.r,bundleTypes:t=Object.values(_privacytypes.ConsentBundleType)}){let a=_chunkKUBXRT3Vcjs.wc.call(void 0, o,e),n=await _chunkKUBXRT3Vcjs.Qc.call(void 0, a);await _bluebird.mapSeries.call(void 0, t,async i=>{_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Update Consent Manager bundle with ID "${n}" and type "${i}" to latest version...`)),await _chunkKUBXRT3Vcjs.Ac.call(void 0, a,{id:n,bundleType:i}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Updated Consent Manager bundle with ID "${n}" and type "${i}" to latest version!`))}),s&&await _bluebird.mapSeries.call(void 0, t,async i=>{_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Deploying Consent Manager bundle with ID "${n}" and type "${i}"...`)),await _chunkKUBXRT3Vcjs.zc.call(void 0, a,{id:n,bundleType:i}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Deployed Consent Manager bundle with ID "${n}" and type "${i}"!`))})}var F=["ID","Activity","Encounters","Last Seen At","Has Native Do Not Sell/Share Support","IAB USP API Support","Service Description","Website URL","Categories of Recipients"];async function ft({auth:e,trackerStatus:s,file:o,classifyService:t=!1,transcendUrl:a=_chunkEYOQLGDVcjs.r}){let n=_chunkKUBXRT3Vcjs.wc.call(void 0, a,e);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading "${o}" from disk`));let l=_chunkKUBXRT3Vcjs.rc.call(void 0, o,_chunkECGHWDVPcjs.ia).map(({Type:S,Notes:p,Service:m,Purpose:C,Status:f,Owners:E,Teams:T,"Connections Made To":A,...I})=>({value:A,type:S,description:p,trackingPurposes:_chunkKUBXRT3Vcjs.oc.call(void 0, C),status:f||s,owners:E?_chunkKUBXRT3Vcjs.oc.call(void 0, E):void 0,teams:T?_chunkKUBXRT3Vcjs.oc.call(void 0, T):void 0,attributes:Object.entries(I).filter(([y])=>!F.includes(y)).map(([y,$])=>({key:y,values:_chunkKUBXRT3Vcjs.oc.call(void 0, $)}))}));await _chunkKUBXRT3Vcjs.We.call(void 0, n,l,t)||(_chunkZUNVPK23cjs.a.error(_colors2.default.red("Encountered error(s) syncing data flows from CSV, see logs above for more info. ")),process.exit(1))}var H=["ID","Activity","Encounters","Last Seen At","Has Native Do Not Sell/Share Support","IAB USP API Support","Service Description","Website URL","Categories of Recipients"];async function Mt({auth:e,trackerStatus:s,file:o,transcendUrl:t=_chunkEYOQLGDVcjs.r}){let a=_chunkKUBXRT3Vcjs.wc.call(void 0, t,e);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading "${o}" from disk`));let i=_chunkKUBXRT3Vcjs.rc.call(void 0, o,_chunkECGHWDVPcjs.ja).map(({"Is Regex?":c,Notes:S,Service:p,Purpose:m,Status:C,Owners:f,Teams:E,Name:T,...A})=>({...typeof c=="string"?{isRegex:c.toLowerCase()==="true"}:{},name:T,description:S,trackingPurposes:_chunkKUBXRT3Vcjs.oc.call(void 0, m),status:C||s,owners:f?_chunkKUBXRT3Vcjs.oc.call(void 0, f):void 0,teams:E?_chunkKUBXRT3Vcjs.oc.call(void 0, E):void 0,attributes:Object.entries(A).filter(([I])=>!H.includes(I)).map(([I,y])=>({key:I,values:_chunkKUBXRT3Vcjs.oc.call(void 0, y)}))}));await _chunkKUBXRT3Vcjs.Qe.call(void 0, a,i)||(_chunkZUNVPK23cjs.a.error(_colors2.default.red("Encountered error(s) syncing cookies from CSV, see logs above for more info. ")),process.exit(1))}var Y=1e3,j=60*Y,Q=60*j,V=24*Q,X=7*V;async function Rt(e,{bin:s,start:o,end:t=new Date}){let a=await _chunkKUBXRT3Vcjs.Qc.call(void 0, e),n=Math.floor(o.getTime()/1e3),i=Math.floor(t.getTime()/1e3);if(n>i)throw new Error('Received "end" date that happened before "start" date');if(s==="1h"&&t.getTime()-o.getTime()>X*2)throw new Error("When using bin=1h, start and end time can be no more than 2 weeks apart");let l=o.toISOString(),c=t.toISOString(),[S,p,m]=await Promise.all([_chunkKUBXRT3Vcjs.Tc.call(void 0, e,{dataSource:"PRIVACY_SIGNAL_TIMESERIES",startDate:l,endDate:c,forceRefetch:!0,airgapBundleId:a,binInterval:s,smoothTimeseries:!1}),_chunkKUBXRT3Vcjs.Tc.call(void 0, e,{dataSource:"CONSENT_CHANGES_TIMESERIES",startDate:l,endDate:c,forceRefetch:!0,airgapBundleId:a,binInterval:s,smoothTimeseries:!1}),_chunkKUBXRT3Vcjs.Tc.call(void 0, e,{dataSource:"CONSENT_SESSIONS_BY_REGIME",startDate:l,endDate:c,forceRefetch:!0,airgapBundleId:a,binInterval:s,smoothTimeseries:!1})]);return{PRIVACY_SIGNAL_TIMESERIES:S,CONSENT_CHANGES_TIMESERIES:p,CONSENT_SESSIONS_BY_REGIME:m}}var G=e=>new URL(`https://${e}`).hostname.split(".").slice(-2).join(".");var W=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;async function Gt(e,{xdiLocation:s,transcendUrl:o=_chunkEYOQLGDVcjs.r,removeIpAddresses:t=!0,domainBlockList:a=["localhost"],xdiAllowedCommands:n="ConsentManager:Sync"}){let i=Array.isArray(e)?e:[{apiKey:e,organizationId:"",organizationName:""}],l=await _bluebird.map.call(void 0, i,async p=>{_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Pulling consent metadata for organization - ${p.organizationName}`));let m=_chunkKUBXRT3Vcjs.wc.call(void 0, o,p.apiKey);return await _chunkKUBXRT3Vcjs.Pc.call(void 0, m)},{concurrency:5}),c={};return l.forEach(p=>{let m=_optionalChain([p, 'access', _2 => _2.partition, 'optionalAccess', _3 => _3.partition])||p.bundleURL.split("/").reverse()[1];c[m]||(c[m]=[]);let C=_chunkEYOQLGDVcjs.c.call(void 0, p.configuration.domains.filter(f=>!t||!W.test(f)).map(f=>G(f)),a);c[m]=[...new Set([...c[m]||[],...C])]}),{html:`
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkLU3DKRNKcjs = require('./chunk-LU3DKRNK.cjs');var _chunkNBXAOUWCcjs = require('./chunk-NBXAOUWC.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkF7QE6D3Tcjs = require('./chunk-F7QE6D3T.cjs');var _privacytypes = require('@transcend-io/privacy-types');var _bluebird = require('bluebird');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function nt({auth:e,deploy:s=!1,transcendUrl:o=_chunkF7QE6D3Tcjs.r,bundleTypes:t=Object.values(_privacytypes.ConsentBundleType)}){let a=_chunkNBXAOUWCcjs.xc.call(void 0, o,e),n=await _chunkNBXAOUWCcjs.Rc.call(void 0, a);await _bluebird.mapSeries.call(void 0, t,async i=>{_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Update Consent Manager bundle with ID "${n}" and type "${i}" to latest version...`)),await _chunkNBXAOUWCcjs.Bc.call(void 0, a,{id:n,bundleType:i}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Updated Consent Manager bundle with ID "${n}" and type "${i}" to latest version!`))}),s&&await _bluebird.mapSeries.call(void 0, t,async i=>{_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Deploying Consent Manager bundle with ID "${n}" and type "${i}"...`)),await _chunkNBXAOUWCcjs.Ac.call(void 0, a,{id:n,bundleType:i}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Deployed Consent Manager bundle with ID "${n}" and type "${i}"!`))})}var F=["ID","Activity","Encounters","Last Seen At","Has Native Do Not Sell/Share Support","IAB USP API Support","Service Description","Website URL","Categories of Recipients"];async function ft({auth:e,trackerStatus:s,file:o,classifyService:t=!1,transcendUrl:a=_chunkF7QE6D3Tcjs.r}){let n=_chunkNBXAOUWCcjs.xc.call(void 0, a,e);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading "${o}" from disk`));let l=_chunkNBXAOUWCcjs.sc.call(void 0, o,_chunkLU3DKRNKcjs.ja).map(({Type:S,Notes:p,Service:m,Purpose:C,Status:f,Owners:E,Teams:T,"Connections Made To":A,...I})=>({value:A,type:S,description:p,trackingPurposes:_chunkNBXAOUWCcjs.pc.call(void 0, C),status:f||s,owners:E?_chunkNBXAOUWCcjs.pc.call(void 0, E):void 0,teams:T?_chunkNBXAOUWCcjs.pc.call(void 0, T):void 0,attributes:Object.entries(I).filter(([y])=>!F.includes(y)).map(([y,$])=>({key:y,values:_chunkNBXAOUWCcjs.pc.call(void 0, $)}))}));await _chunkNBXAOUWCcjs.Ye.call(void 0, n,l,t)||(_chunkZUNVPK23cjs.a.error(_colors2.default.red("Encountered error(s) syncing data flows from CSV, see logs above for more info. ")),process.exit(1))}var H=["ID","Activity","Encounters","Last Seen At","Has Native Do Not Sell/Share Support","IAB USP API Support","Service Description","Website URL","Categories of Recipients"];async function Mt({auth:e,trackerStatus:s,file:o,transcendUrl:t=_chunkF7QE6D3Tcjs.r}){let a=_chunkNBXAOUWCcjs.xc.call(void 0, t,e);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading "${o}" from disk`));let i=_chunkNBXAOUWCcjs.sc.call(void 0, o,_chunkLU3DKRNKcjs.ka).map(({"Is Regex?":c,Notes:S,Service:p,Purpose:m,Status:C,Owners:f,Teams:E,Name:T,...A})=>({...typeof c=="string"?{isRegex:c.toLowerCase()==="true"}:{},name:T,description:S,trackingPurposes:_chunkNBXAOUWCcjs.pc.call(void 0, m),status:C||s,owners:f?_chunkNBXAOUWCcjs.pc.call(void 0, f):void 0,teams:E?_chunkNBXAOUWCcjs.pc.call(void 0, E):void 0,attributes:Object.entries(A).filter(([I])=>!H.includes(I)).map(([I,y])=>({key:I,values:_chunkNBXAOUWCcjs.pc.call(void 0, y)}))}));await _chunkNBXAOUWCcjs.Se.call(void 0, a,i)||(_chunkZUNVPK23cjs.a.error(_colors2.default.red("Encountered error(s) syncing cookies from CSV, see logs above for more info. ")),process.exit(1))}var Y=1e3,j=60*Y,Q=60*j,V=24*Q,X=7*V;async function Rt(e,{bin:s,start:o,end:t=new Date}){let a=await _chunkNBXAOUWCcjs.Rc.call(void 0, e),n=Math.floor(o.getTime()/1e3),i=Math.floor(t.getTime()/1e3);if(n>i)throw new Error('Received "end" date that happened before "start" date');if(s==="1h"&&t.getTime()-o.getTime()>X*2)throw new Error("When using bin=1h, start and end time can be no more than 2 weeks apart");let l=o.toISOString(),c=t.toISOString(),[S,p,m]=await Promise.all([_chunkNBXAOUWCcjs.Uc.call(void 0, e,{dataSource:"PRIVACY_SIGNAL_TIMESERIES",startDate:l,endDate:c,forceRefetch:!0,airgapBundleId:a,binInterval:s,smoothTimeseries:!1}),_chunkNBXAOUWCcjs.Uc.call(void 0, e,{dataSource:"CONSENT_CHANGES_TIMESERIES",startDate:l,endDate:c,forceRefetch:!0,airgapBundleId:a,binInterval:s,smoothTimeseries:!1}),_chunkNBXAOUWCcjs.Uc.call(void 0, e,{dataSource:"CONSENT_SESSIONS_BY_REGIME",startDate:l,endDate:c,forceRefetch:!0,airgapBundleId:a,binInterval:s,smoothTimeseries:!1})]);return{PRIVACY_SIGNAL_TIMESERIES:S,CONSENT_CHANGES_TIMESERIES:p,CONSENT_SESSIONS_BY_REGIME:m}}var G=e=>new URL(`https://${e}`).hostname.split(".").slice(-2).join(".");var W=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;async function Gt(e,{xdiLocation:s,transcendUrl:o=_chunkF7QE6D3Tcjs.r,removeIpAddresses:t=!0,domainBlockList:a=["localhost"],xdiAllowedCommands:n="ConsentManager:Sync"}){let i=Array.isArray(e)?e:[{apiKey:e,organizationId:"",organizationName:""}],l=await _bluebird.map.call(void 0, i,async p=>{_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Pulling consent metadata for organization - ${p.organizationName}`));let m=_chunkNBXAOUWCcjs.xc.call(void 0, o,p.apiKey);return await _chunkNBXAOUWCcjs.Qc.call(void 0, m)},{concurrency:5}),c={};return l.forEach(p=>{let m=_optionalChain([p, 'access', _2 => _2.partition, 'optionalAccess', _3 => _3.partition])||p.bundleURL.split("/").reverse()[1];c[m]||(c[m]=[]);let C=_chunkF7QE6D3Tcjs.c.call(void 0, p.configuration.domains.filter(f=>!t||!W.test(f)).map(f=>G(f)),a);c[m]=[...new Set([...c[m]||[],...C])]}),{html:`
2
2
  <!DOCTYPE html>
3
3
  <script
4
4
  src="${s}"
@@ -9,4 +9,4 @@ data-xdi-commands="${n}"
9
9
 
10
10
  ~~~~~~~~~~~
11
11
  Airgap scripts to host:`),s.forEach(({attributes:o,title:t},a)=>{_optionalChain([o, 'optionalAccess', _7 => _7.find, 'call', _8 => _8(n=>n.key==="Airgap Production URL"), 'optionalAccess', _9 => _9.values, 'optionalAccess', _10 => _10.forEach, 'call', _11 => _11(n=>{_chunkZUNVPK23cjs.a.info(`${a}) ${t} - ${n}`)})])}),s}exports.a = nt; exports.b = ft; exports.c = Mt; exports.d = Rt; exports.e = G; exports.f = W; exports.g = Gt; exports.h = Ft;
12
- //# sourceMappingURL=chunk-RNZ72QMS.cjs.map
12
+ //# sourceMappingURL=chunk-ID7MP3QD.cjs.map