@transcend-io/cli 8.26.3 → 8.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +6 -0
  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-IXJG6NAC.cjs → chunk-4PQ4RHUG.cjs} +4 -4
  6. package/dist/{chunk-IXJG6NAC.cjs.map → chunk-4PQ4RHUG.cjs.map} +1 -1
  7. package/dist/{chunk-PZLVJBQM.cjs → chunk-7PF5VVAF.cjs} +2 -2
  8. package/dist/{chunk-PZLVJBQM.cjs.map → chunk-7PF5VVAF.cjs.map} +1 -1
  9. package/dist/{chunk-4LHXA6MV.cjs → chunk-AEL3DOYI.cjs} +2 -2
  10. package/dist/{chunk-4LHXA6MV.cjs.map → chunk-AEL3DOYI.cjs.map} +1 -1
  11. package/dist/{chunk-YPUEGXPW.cjs → chunk-CQT5QQ3U.cjs} +2 -2
  12. package/dist/{chunk-YPUEGXPW.cjs.map → chunk-CQT5QQ3U.cjs.map} +1 -1
  13. package/dist/{chunk-5UBGZNDC.cjs → chunk-ECGHWDVP.cjs} +2 -2
  14. package/dist/chunk-ECGHWDVP.cjs.map +1 -0
  15. package/dist/{chunk-MGIVF74Z.cjs → chunk-EYOQLGDV.cjs} +2 -2
  16. package/dist/{chunk-MGIVF74Z.cjs.map → chunk-EYOQLGDV.cjs.map} +1 -1
  17. package/dist/{chunk-HPU3KPV4.cjs → chunk-FER7XKVN.cjs} +2 -2
  18. package/dist/{chunk-HPU3KPV4.cjs.map → chunk-FER7XKVN.cjs.map} +1 -1
  19. package/dist/{chunk-SBCX6SDE.cjs → chunk-I7PFP5VB.cjs} +2 -2
  20. package/dist/{chunk-SBCX6SDE.cjs.map → chunk-I7PFP5VB.cjs.map} +1 -1
  21. package/dist/{chunk-RE5YALEO.cjs → chunk-JFZPP4VV.cjs} +3 -3
  22. package/dist/{chunk-RE5YALEO.cjs.map → chunk-JFZPP4VV.cjs.map} +1 -1
  23. package/dist/{chunk-UAO3IAO3.cjs → chunk-K4TIJ3VM.cjs} +2 -2
  24. package/dist/{chunk-UAO3IAO3.cjs.map → chunk-K4TIJ3VM.cjs.map} +1 -1
  25. package/dist/{chunk-X6CJEYOA.cjs → chunk-KUBXRT3V.cjs} +5 -4
  26. package/dist/chunk-KUBXRT3V.cjs.map +1 -0
  27. package/dist/{chunk-ZOVKGQJQ.cjs → chunk-L7Z4PFRC.cjs} +2 -2
  28. package/dist/{chunk-ZOVKGQJQ.cjs.map → chunk-L7Z4PFRC.cjs.map} +1 -1
  29. package/dist/{chunk-PP4YLOQE.cjs → chunk-RNZ72QMS.cjs} +2 -2
  30. package/dist/{chunk-PP4YLOQE.cjs.map → chunk-RNZ72QMS.cjs.map} +1 -1
  31. package/dist/{chunk-LMUWS7HI.cjs → chunk-THOOR2KA.cjs} +4 -4
  32. package/dist/{chunk-LMUWS7HI.cjs.map → chunk-THOOR2KA.cjs.map} +1 -1
  33. package/dist/{chunk-S5MX7XJL.cjs → chunk-Y35YHYXP.cjs} +21 -21
  34. package/dist/{chunk-S5MX7XJL.cjs.map → chunk-Y35YHYXP.cjs.map} +1 -1
  35. package/dist/{chunk-EBEILTRR.cjs → chunk-YKGS253B.cjs} +6 -6
  36. package/dist/{chunk-EBEILTRR.cjs.map → chunk-YKGS253B.cjs.map} +1 -1
  37. package/dist/{impl-XW4UTUBW.cjs → impl-3YAJ7ZV3.cjs} +2 -2
  38. package/dist/{impl-XW4UTUBW.cjs.map → impl-3YAJ7ZV3.cjs.map} +1 -1
  39. package/dist/{impl-UHCILICE.cjs → impl-55NL4KOI.cjs} +2 -2
  40. package/dist/{impl-UHCILICE.cjs.map → impl-55NL4KOI.cjs.map} +1 -1
  41. package/dist/{impl-NAITRZS5.cjs → impl-7B7QDZZJ.cjs} +2 -2
  42. package/dist/{impl-NAITRZS5.cjs.map → impl-7B7QDZZJ.cjs.map} +1 -1
  43. package/dist/{impl-ZAKD7OF2.cjs → impl-A6W2KTYL.cjs} +2 -2
  44. package/dist/{impl-ZAKD7OF2.cjs.map → impl-A6W2KTYL.cjs.map} +1 -1
  45. package/dist/{impl-MNMSXIYH.cjs → impl-ALROZNDJ.cjs} +2 -2
  46. package/dist/{impl-MNMSXIYH.cjs.map → impl-ALROZNDJ.cjs.map} +1 -1
  47. package/dist/{impl-65UAYE4Y.cjs → impl-ANXIZT7S.cjs} +2 -2
  48. package/dist/{impl-65UAYE4Y.cjs.map → impl-ANXIZT7S.cjs.map} +1 -1
  49. package/dist/{impl-RIR5ANXH.cjs → impl-AP2ZTYJK.cjs} +2 -2
  50. package/dist/{impl-RIR5ANXH.cjs.map → impl-AP2ZTYJK.cjs.map} +1 -1
  51. package/dist/{impl-HNW6B2DU.cjs → impl-AZYBYV3X.cjs} +2 -2
  52. package/dist/{impl-HNW6B2DU.cjs.map → impl-AZYBYV3X.cjs.map} +1 -1
  53. package/dist/impl-B7ODYIUX.cjs +2 -0
  54. package/dist/{impl-6DHYOTA2.cjs.map → impl-B7ODYIUX.cjs.map} +1 -1
  55. package/dist/{impl-TNSZ6LTO.cjs → impl-BDPD5CCN.cjs} +2 -2
  56. package/dist/{impl-TNSZ6LTO.cjs.map → impl-BDPD5CCN.cjs.map} +1 -1
  57. package/dist/{impl-3BHV7STJ.cjs → impl-BL4XQEFX.cjs} +2 -2
  58. package/dist/{impl-3BHV7STJ.cjs.map → impl-BL4XQEFX.cjs.map} +1 -1
  59. package/dist/{impl-JBFNOZXK.cjs → impl-D7R3HZEC.cjs} +5 -5
  60. package/dist/{impl-JBFNOZXK.cjs.map → impl-D7R3HZEC.cjs.map} +1 -1
  61. package/dist/{impl-WTLPP6WJ.cjs → impl-DDQQGOQ3.cjs} +2 -2
  62. package/dist/{impl-WTLPP6WJ.cjs.map → impl-DDQQGOQ3.cjs.map} +1 -1
  63. package/dist/{impl-5FLGACAD.cjs → impl-DT5KLE2G.cjs} +3 -3
  64. package/dist/{impl-5FLGACAD.cjs.map → impl-DT5KLE2G.cjs.map} +1 -1
  65. package/dist/{impl-PBEQHLIJ.cjs → impl-DVE332P5.cjs} +2 -2
  66. package/dist/{impl-PBEQHLIJ.cjs.map → impl-DVE332P5.cjs.map} +1 -1
  67. package/dist/{impl-Z5MFXC4Y.cjs → impl-DXAKJNLZ.cjs} +2 -2
  68. package/dist/{impl-Z5MFXC4Y.cjs.map → impl-DXAKJNLZ.cjs.map} +1 -1
  69. package/dist/{impl-BFSDPXDV.cjs → impl-H2BRV4GP.cjs} +2 -2
  70. package/dist/{impl-BFSDPXDV.cjs.map → impl-H2BRV4GP.cjs.map} +1 -1
  71. package/dist/{impl-CSTT5HQH.cjs → impl-IFDUZGZM.cjs} +2 -2
  72. package/dist/{impl-CSTT5HQH.cjs.map → impl-IFDUZGZM.cjs.map} +1 -1
  73. package/dist/{impl-KAWZ42M5.cjs → impl-IIIT5MSV.cjs} +2 -2
  74. package/dist/{impl-KAWZ42M5.cjs.map → impl-IIIT5MSV.cjs.map} +1 -1
  75. package/dist/{impl-5K2UCOJJ.cjs → impl-JPVEFSJB.cjs} +2 -2
  76. package/dist/{impl-5K2UCOJJ.cjs.map → impl-JPVEFSJB.cjs.map} +1 -1
  77. package/dist/{impl-LVHX32GS.cjs → impl-LDOILOAQ.cjs} +2 -2
  78. package/dist/{impl-LVHX32GS.cjs.map → impl-LDOILOAQ.cjs.map} +1 -1
  79. package/dist/{impl-6YB36EZH.cjs → impl-LKJFVX7E.cjs} +2 -2
  80. package/dist/{impl-6YB36EZH.cjs.map → impl-LKJFVX7E.cjs.map} +1 -1
  81. package/dist/{impl-3DHFXZRO.cjs → impl-LQEYNOZS.cjs} +2 -2
  82. package/dist/{impl-3DHFXZRO.cjs.map → impl-LQEYNOZS.cjs.map} +1 -1
  83. package/dist/{impl-WP2EKZ6C.cjs → impl-M5QGTDLF.cjs} +2 -2
  84. package/dist/{impl-WP2EKZ6C.cjs.map → impl-M5QGTDLF.cjs.map} +1 -1
  85. package/dist/{impl-BJRSLU3V.cjs → impl-MBEVWSPX.cjs} +2 -2
  86. package/dist/{impl-BJRSLU3V.cjs.map → impl-MBEVWSPX.cjs.map} +1 -1
  87. package/dist/{impl-F4B6PYAE.cjs → impl-NCUMPL6B.cjs} +4 -4
  88. package/dist/{impl-F4B6PYAE.cjs.map → impl-NCUMPL6B.cjs.map} +1 -1
  89. package/dist/{impl-DHAB5PO6.cjs → impl-NISL4HZY.cjs} +2 -2
  90. package/dist/{impl-DHAB5PO6.cjs.map → impl-NISL4HZY.cjs.map} +1 -1
  91. package/dist/{impl-KWAOGILY.cjs → impl-OFRMKTX5.cjs} +2 -2
  92. package/dist/{impl-KWAOGILY.cjs.map → impl-OFRMKTX5.cjs.map} +1 -1
  93. package/dist/impl-PE52QYSI.cjs +2 -0
  94. package/dist/{impl-5G2I4YXV.cjs.map → impl-PE52QYSI.cjs.map} +1 -1
  95. package/dist/{impl-ZJFIQ3WO.cjs → impl-PXT7QNSR.cjs} +2 -2
  96. package/dist/{impl-ZJFIQ3WO.cjs.map → impl-PXT7QNSR.cjs.map} +1 -1
  97. package/dist/{impl-N7KXTUQ5.cjs → impl-SDQ6LUZD.cjs} +2 -2
  98. package/dist/{impl-N7KXTUQ5.cjs.map → impl-SDQ6LUZD.cjs.map} +1 -1
  99. package/dist/{impl-HFNH2244.cjs → impl-SVEK74IU.cjs} +2 -2
  100. package/dist/{impl-HFNH2244.cjs.map → impl-SVEK74IU.cjs.map} +1 -1
  101. package/dist/{impl-3WNATSXH.cjs → impl-SVPD3IHV.cjs} +2 -2
  102. package/dist/{impl-3WNATSXH.cjs.map → impl-SVPD3IHV.cjs.map} +1 -1
  103. package/dist/{impl-AH7B2B24.cjs → impl-UC5CCT6E.cjs} +3 -3
  104. package/dist/{impl-AH7B2B24.cjs.map → impl-UC5CCT6E.cjs.map} +1 -1
  105. package/dist/{impl-ZBPQU55V.cjs → impl-UZPP5VK5.cjs} +2 -2
  106. package/dist/{impl-ZBPQU55V.cjs.map → impl-UZPP5VK5.cjs.map} +1 -1
  107. package/dist/{impl-72IBK3I6.cjs → impl-VZ6NJDAV.cjs} +2 -2
  108. package/dist/{impl-72IBK3I6.cjs.map → impl-VZ6NJDAV.cjs.map} +1 -1
  109. package/dist/{impl-IG2OR2JL.cjs → impl-W35DMTQV.cjs} +2 -2
  110. package/dist/{impl-IG2OR2JL.cjs.map → impl-W35DMTQV.cjs.map} +1 -1
  111. package/dist/{impl-QUYKNAFP.cjs → impl-XHO6WQ2I.cjs} +2 -2
  112. package/dist/{impl-QUYKNAFP.cjs.map → impl-XHO6WQ2I.cjs.map} +1 -1
  113. package/dist/{impl-V2RBWUPL.cjs → impl-YHBNKYSL.cjs} +2 -2
  114. package/dist/{impl-V2RBWUPL.cjs.map → impl-YHBNKYSL.cjs.map} +1 -1
  115. package/dist/{impl-O7I2KRJ7.cjs → impl-YJ6UUT4D.cjs} +2 -2
  116. package/dist/{impl-O7I2KRJ7.cjs.map → impl-YJ6UUT4D.cjs.map} +1 -1
  117. package/dist/{impl-TXK727IK.cjs → impl-YWJCIRTP.cjs} +2 -2
  118. package/dist/{impl-TXK727IK.cjs.map → impl-YWJCIRTP.cjs.map} +1 -1
  119. package/dist/{impl-K6XHDMZZ.cjs → impl-ZTZHVQYY.cjs} +2 -2
  120. package/dist/{impl-K6XHDMZZ.cjs.map → impl-ZTZHVQYY.cjs.map} +1 -1
  121. package/dist/index.cjs +3 -3
  122. package/dist/index.d.cts +18 -1
  123. package/package.json +3 -3
  124. package/dist/chunk-5UBGZNDC.cjs.map +0 -1
  125. package/dist/chunk-X6CJEYOA.cjs.map +0 -1
  126. package/dist/impl-5G2I4YXV.cjs +0 -2
  127. package/dist/impl-6DHYOTA2.cjs +0 -2
@@ -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 _chunkX6CJEYOAcjs = require('./chunk-X6CJEYOA.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkMGIVF74Zcjs = require('./chunk-MGIVF74Z.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 _chunkX6CJEYOAcjs.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=_chunkMGIVF74Zcjs.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=_chunkX6CJEYOAcjs.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=_chunkMGIVF74Zcjs.j.call(void 0, a.map(c=>Object.keys(c)).flat()),u=_chunkMGIVF74Zcjs.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=_chunkMGIVF74Zcjs.j.call(void 0, a.map(o=>Object.keys(o)).flat()),u=_chunkMGIVF74Zcjs.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 _chunkX6CJEYOAcjs.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=_chunkMGIVF74Zcjs.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 _chunkX6CJEYOAcjs.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=_chunkMGIVF74Zcjs.j.call(void 0, a.map(i=>Object.keys(i)).flat()),p=_chunkMGIVF74Zcjs.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=_chunkMGIVF74Zcjs.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=_chunkX6CJEYOAcjs.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=_chunkX6CJEYOAcjs.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=_chunkMGIVF74Zcjs.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=_chunkX6CJEYOAcjs.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 _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:
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=_chunkX6CJEYOAcjs.wc.call(void 0, e,a),[b,S,fe]=await Promise.all([_chunkX6CJEYOAcjs.xc.call(void 0, e,a,t),l?Promise.resolve([]):_chunkX6CJEYOAcjs.fd.call(void 0, P),l?Promise.resolve([]):_chunkX6CJEYOAcjs.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=_chunkMGIVF74Zcjs.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.")),_chunkX6CJEYOAcjs.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((_chunkX6CJEYOAcjs.hg.call(void 0, new Date).getTime()-_chunkX6CJEYOAcjs.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=_chunkX6CJEYOAcjs.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.")),_chunkX6CJEYOAcjs.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=_chunkX6CJEYOAcjs.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=_chunkX6CJEYOAcjs.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=_chunkX6CJEYOAcjs.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-EBEILTRR.cjs.map
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
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-EBEILTRR.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-EBEILTRR.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-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,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 _chunkRE5YALEOcjs = require('./chunk-RE5YALEO.cjs');var _chunk5UBGZNDCcjs = require('./chunk-5UBGZNDC.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');require('./chunk-LCDYXJN6.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');require('./chunk-Q7I37FJV.cjs');var _iots = require('io-ts'); var f = _interopRequireWildcard(_iots);var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _fs = require('fs');var _typeutils = require('@transcend-io/type-utils');var _privacytypes = require('@transcend-io/privacy-types');function T({file:t,output:n}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),_fs.existsSync.call(void 0, t)||(_chunkZUNVPK23cjs.a.error(_colors2.default.red(`File does not exist: --file="${t}"`)),this.process.exit(1));let u=_typeutils.decodeCodec.call(void 0, f.array(_chunk5UBGZNDCcjs.ka),_fs.readFileSync.call(void 0, t,"utf-8")),e=[],r=[];u.forEach(a=>{a.dataFlows.filter(({type:o})=>o!==_privacytypes.DataFlowScope.CSP).forEach(o=>{e.push({value:o.value,type:o.type,status:_privacytypes.ConsentTrackerStatus.Live,trackingPurposes:o.trackingPurposes})}),a.cookies.forEach(o=>{r.push({name:o.name,status:_privacytypes.ConsentTrackerStatus.Live,trackingPurposes:o.trackingPurposes})})}),_chunkRE5YALEOcjs.e.call(void 0, n,{"data-flows":e,cookies:r}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully wrote ${e.length} data flows and ${r.length} cookies to file "${n}"`))}exports.consentManagerServiceJsonToYml = T;
2
- //# sourceMappingURL=impl-XW4UTUBW.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 _chunkJFZPP4VVcjs = require('./chunk-JFZPP4VV.cjs');var _chunkECGHWDVPcjs = require('./chunk-ECGHWDVP.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');require('./chunk-LCDYXJN6.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');require('./chunk-Q7I37FJV.cjs');var _iots = require('io-ts'); var f = _interopRequireWildcard(_iots);var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _fs = require('fs');var _typeutils = require('@transcend-io/type-utils');var _privacytypes = require('@transcend-io/privacy-types');function T({file:t,output:n}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),_fs.existsSync.call(void 0, t)||(_chunkZUNVPK23cjs.a.error(_colors2.default.red(`File does not exist: --file="${t}"`)),this.process.exit(1));let u=_typeutils.decodeCodec.call(void 0, f.array(_chunkECGHWDVPcjs.ka),_fs.readFileSync.call(void 0, t,"utf-8")),e=[],r=[];u.forEach(a=>{a.dataFlows.filter(({type:o})=>o!==_privacytypes.DataFlowScope.CSP).forEach(o=>{e.push({value:o.value,type:o.type,status:_privacytypes.ConsentTrackerStatus.Live,trackingPurposes:o.trackingPurposes})}),a.cookies.forEach(o=>{r.push({name:o.name,status:_privacytypes.ConsentTrackerStatus.Live,trackingPurposes:o.trackingPurposes})})}),_chunkJFZPP4VVcjs.e.call(void 0, n,{"data-flows":e,cookies:r}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully wrote ${e.length} data flows and ${r.length} cookies to file "${n}"`))}exports.consentManagerServiceJsonToYml = T;
2
+ //# sourceMappingURL=impl-3YAJ7ZV3.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-XW4UTUBW.cjs","../src/commands/inventory/consent-manager-service-json-to-yml/impl.ts"],"names":["consentManagerServiceJsonToYml","file","output","doneInputValidation","existsSync","logger","colors","services","decodeCodec","ConsentManagerServiceMetadata","readFileSync","dataFlows","cookies","service","type","DataFlowScope","dataFlow","ConsentTrackerStatus","cookie","writeTranscendYaml"],"mappings":"AAAA,mfAAwC,wDAA0C,wDAAyC,gCAA6B,wDAAyC,gCAA6B,qECC3M,gFAEA,wBAEsB,qDACb,2DASrB,SAQSA,CAAAA,CAEd,CAAE,IAAA,CAAAC,CAAAA,CAAM,MAAA,CAAAC,CAAO,CAAA,CACT,CACNC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAGhCC,4BAAAA,CAAe,CAAA,EAAA,CAClBC,mBAAAA,CAAO,KAAA,CAAMC,gBAAAA,CAAO,GAAA,CAAI,CAAA,6BAAA,EAAgCL,CAAI,CAAA,CAAA,CAAG,CAAC,CAAA,CAChE,IAAA,CAAK,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,CAAA,CAIrB,IAAMM,CAAAA,CAAWC,oCAAAA,CACb,CAAA,KAAA,CAAMC,oBAA6B,CAAA,CACrCC,8BAAAA,CAAaT,CAAM,OAAO,CAC5B,CAAA,CAGMU,CAAAA,CAA6B,CAAC,CAAA,CAC9BC,CAAAA,CAAyB,CAAC,CAAA,CAChCL,CAAAA,CAAS,OAAA,CAASM,CAAAA,EAAY,CAC5BA,CAAAA,CAAQ,SAAA,CACL,MAAA,CAAO,CAAC,CAAE,IAAA,CAAAC,CAAK,CAAA,CAAA,EAAMA,CAAAA,GAASC,2BAAAA,CAAc,GAAG,CAAA,CAC/C,OAAA,CAASC,CAAAA,EAAa,CACrBL,CAAAA,CAAU,IAAA,CAAK,CACb,KAAA,CAAOK,CAAAA,CAAS,KAAA,CAChB,IAAA,CAAMA,CAAAA,CAAS,IAAA,CACf,MAAA,CAAQC,kCAAAA,CAAqB,IAAA,CAC7B,gBAAA,CAAkBD,CAAAA,CAAS,gBAC7B,CAAC,CACH,CAAC,CAAA,CAEHH,CAAAA,CAAQ,OAAA,CAAQ,OAAA,CAASK,CAAAA,EAAW,CAClCN,CAAAA,CAAQ,IAAA,CAAK,CACX,IAAA,CAAMM,CAAAA,CAAO,IAAA,CACb,MAAA,CAAQD,kCAAAA,CAAqB,IAAA,CAC7B,gBAAA,CAAkBC,CAAAA,CAAO,gBAC3B,CAAC,CACH,CAAC,CACH,CAAC,CAAA,CAGDC,iCAAAA,CAAmBjB,CAAQ,CACzB,YAAA,CAAcS,CAAAA,CACd,OAAA,CAAAC,CACF,CAAC,CAAA,CAEDP,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,KAAA,CACL,CAAA,mBAAA,EAAsBK,CAAAA,CAAU,MAAM,CAAA,gBAAA,EAAmBC,CAAAA,CAAQ,MAAM,CAAA,kBAAA,EAAqBV,CAAM,CAAA,CAAA,CACpG,CACF,CACF,CAAA,2CAAA","file":"/home/runner/work/cli/cli/dist/impl-XW4UTUBW.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport * as t from 'io-ts';\nimport { writeTranscendYaml } from '../../../lib/readTranscendYaml';\nimport colors from 'colors';\nimport { logger } from '../../../logger';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport {\n ConsentManagerServiceMetadata,\n CookieInput,\n DataFlowInput,\n} from '../../../codecs';\nimport {\n ConsentTrackerStatus,\n DataFlowScope,\n} from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface ConsentManagerServiceJsonToYmlCommandFlags {\n file: string;\n output: string;\n}\n\nexport function consentManagerServiceJsonToYml(\n this: LocalContext,\n { file, output }: ConsentManagerServiceJsonToYmlCommandFlags,\n): void {\n doneInputValidation(this.process.exit);\n\n // Ensure files exist\n if (!existsSync(file)) {\n logger.error(colors.red(`File does not exist: --file=\"${file}\"`));\n this.process.exit(1);\n }\n\n // Read in each consent manager configuration\n const services = decodeCodec(\n t.array(ConsentManagerServiceMetadata),\n readFileSync(file, 'utf-8'),\n );\n\n // Create data flows and cookie configurations\n const dataFlows: DataFlowInput[] = [];\n const cookies: CookieInput[] = [];\n services.forEach((service) => {\n service.dataFlows\n .filter(({ type }) => type !== DataFlowScope.CSP)\n .forEach((dataFlow) => {\n dataFlows.push({\n value: dataFlow.value,\n type: dataFlow.type,\n status: ConsentTrackerStatus.Live,\n trackingPurposes: dataFlow.trackingPurposes,\n });\n });\n\n service.cookies.forEach((cookie) => {\n cookies.push({\n name: cookie.name,\n status: ConsentTrackerStatus.Live,\n trackingPurposes: cookie.trackingPurposes,\n });\n });\n });\n\n // write to disk\n writeTranscendYaml(output, {\n 'data-flows': dataFlows,\n cookies,\n });\n\n logger.info(\n colors.green(\n `Successfully wrote ${dataFlows.length} data flows and ${cookies.length} cookies to file \"${output}\"`,\n ),\n );\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-3YAJ7ZV3.cjs","../src/commands/inventory/consent-manager-service-json-to-yml/impl.ts"],"names":["consentManagerServiceJsonToYml","file","output","doneInputValidation","existsSync","logger","colors","services","decodeCodec","ConsentManagerServiceMetadata","readFileSync","dataFlows","cookies","service","type","DataFlowScope","dataFlow","ConsentTrackerStatus","cookie","writeTranscendYaml"],"mappings":"AAAA,mfAAwC,wDAA0C,wDAAyC,gCAA6B,wDAAyC,gCAA6B,qECC3M,gFAEA,wBAEsB,qDACb,2DASrB,SAQSA,CAAAA,CAEd,CAAE,IAAA,CAAAC,CAAAA,CAAM,MAAA,CAAAC,CAAO,CAAA,CACT,CACNC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAGhCC,4BAAAA,CAAe,CAAA,EAAA,CAClBC,mBAAAA,CAAO,KAAA,CAAMC,gBAAAA,CAAO,GAAA,CAAI,CAAA,6BAAA,EAAgCL,CAAI,CAAA,CAAA,CAAG,CAAC,CAAA,CAChE,IAAA,CAAK,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,CAAA,CAIrB,IAAMM,CAAAA,CAAWC,oCAAAA,CACb,CAAA,KAAA,CAAMC,oBAA6B,CAAA,CACrCC,8BAAAA,CAAaT,CAAM,OAAO,CAC5B,CAAA,CAGMU,CAAAA,CAA6B,CAAC,CAAA,CAC9BC,CAAAA,CAAyB,CAAC,CAAA,CAChCL,CAAAA,CAAS,OAAA,CAASM,CAAAA,EAAY,CAC5BA,CAAAA,CAAQ,SAAA,CACL,MAAA,CAAO,CAAC,CAAE,IAAA,CAAAC,CAAK,CAAA,CAAA,EAAMA,CAAAA,GAASC,2BAAAA,CAAc,GAAG,CAAA,CAC/C,OAAA,CAASC,CAAAA,EAAa,CACrBL,CAAAA,CAAU,IAAA,CAAK,CACb,KAAA,CAAOK,CAAAA,CAAS,KAAA,CAChB,IAAA,CAAMA,CAAAA,CAAS,IAAA,CACf,MAAA,CAAQC,kCAAAA,CAAqB,IAAA,CAC7B,gBAAA,CAAkBD,CAAAA,CAAS,gBAC7B,CAAC,CACH,CAAC,CAAA,CAEHH,CAAAA,CAAQ,OAAA,CAAQ,OAAA,CAASK,CAAAA,EAAW,CAClCN,CAAAA,CAAQ,IAAA,CAAK,CACX,IAAA,CAAMM,CAAAA,CAAO,IAAA,CACb,MAAA,CAAQD,kCAAAA,CAAqB,IAAA,CAC7B,gBAAA,CAAkBC,CAAAA,CAAO,gBAC3B,CAAC,CACH,CAAC,CACH,CAAC,CAAA,CAGDC,iCAAAA,CAAmBjB,CAAQ,CACzB,YAAA,CAAcS,CAAAA,CACd,OAAA,CAAAC,CACF,CAAC,CAAA,CAEDP,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,KAAA,CACL,CAAA,mBAAA,EAAsBK,CAAAA,CAAU,MAAM,CAAA,gBAAA,EAAmBC,CAAAA,CAAQ,MAAM,CAAA,kBAAA,EAAqBV,CAAM,CAAA,CAAA,CACpG,CACF,CACF,CAAA,2CAAA","file":"/home/runner/work/cli/cli/dist/impl-3YAJ7ZV3.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport * as t from 'io-ts';\nimport { writeTranscendYaml } from '../../../lib/readTranscendYaml';\nimport colors from 'colors';\nimport { logger } from '../../../logger';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport {\n ConsentManagerServiceMetadata,\n CookieInput,\n DataFlowInput,\n} from '../../../codecs';\nimport {\n ConsentTrackerStatus,\n DataFlowScope,\n} from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface ConsentManagerServiceJsonToYmlCommandFlags {\n file: string;\n output: string;\n}\n\nexport function consentManagerServiceJsonToYml(\n this: LocalContext,\n { file, output }: ConsentManagerServiceJsonToYmlCommandFlags,\n): void {\n doneInputValidation(this.process.exit);\n\n // Ensure files exist\n if (!existsSync(file)) {\n logger.error(colors.red(`File does not exist: --file=\"${file}\"`));\n this.process.exit(1);\n }\n\n // Read in each consent manager configuration\n const services = decodeCodec(\n t.array(ConsentManagerServiceMetadata),\n readFileSync(file, 'utf-8'),\n );\n\n // Create data flows and cookie configurations\n const dataFlows: DataFlowInput[] = [];\n const cookies: CookieInput[] = [];\n services.forEach((service) => {\n service.dataFlows\n .filter(({ type }) => type !== DataFlowScope.CSP)\n .forEach((dataFlow) => {\n dataFlows.push({\n value: dataFlow.value,\n type: dataFlow.type,\n status: ConsentTrackerStatus.Live,\n trackingPurposes: dataFlow.trackingPurposes,\n });\n });\n\n service.cookies.forEach((cookie) => {\n cookies.push({\n name: cookie.name,\n status: ConsentTrackerStatus.Live,\n trackingPurposes: cookie.trackingPurposes,\n });\n });\n });\n\n // write to disk\n writeTranscendYaml(output, {\n 'data-flows': dataFlows,\n cookies,\n });\n\n logger.info(\n colors.green(\n `Successfully wrote ${dataFlows.length} data flows and ${cookies.length} cookies to file \"${output}\"`,\n ),\n );\n}\n"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkX6CJEYOAcjs = require('./chunk-X6CJEYOA.cjs');require('./chunk-LCDYXJN6.cjs');require('./chunk-ZUNVPK23.cjs');require('./chunk-MGIVF74Z.cjs');require('./chunk-Q7I37FJV.cjs');var _privacytypes = require('@transcend-io/privacy-types');async function g({auth:r,transcendUrl:a,folderPath:n,requestIds:s,statuses:i=[_privacytypes.RequestStatus.Approving,_privacytypes.RequestStatus.Downloadable],concurrency:l,createdAtBefore:d,createdAtAfter:m,approveAfterDownload:c}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),await _chunkX6CJEYOAcjs.zf.call(void 0, {transcendUrl:a,auth:r,folderPath:n,requestIds:s,statuses:i,concurrency:l,createdAtBefore:d,createdAtAfter:m,approveAfterDownload:c})}exports.downloadFiles = g;
2
- //# sourceMappingURL=impl-UHCILICE.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkKUBXRT3Vcjs = require('./chunk-KUBXRT3V.cjs');require('./chunk-LCDYXJN6.cjs');require('./chunk-ZUNVPK23.cjs');require('./chunk-EYOQLGDV.cjs');require('./chunk-Q7I37FJV.cjs');var _privacytypes = require('@transcend-io/privacy-types');async function g({auth:r,transcendUrl:a,folderPath:n,requestIds:s,statuses:i=[_privacytypes.RequestStatus.Approving,_privacytypes.RequestStatus.Downloadable],concurrency:l,createdAtBefore:d,createdAtAfter:m,approveAfterDownload:c}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),await _chunkKUBXRT3Vcjs.zf.call(void 0, {transcendUrl:a,auth:r,folderPath:n,requestIds:s,statuses:i,concurrency:l,createdAtBefore:d,createdAtAfter:m,approveAfterDownload:c})}exports.downloadFiles = g;
2
+ //# sourceMappingURL=impl-55NL4KOI.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-UHCILICE.cjs","../src/commands/request/download-files/impl.ts"],"names":["downloadFiles","auth","transcendUrl","folderPath","requestIds","statuses","RequestStatus","concurrency","createdAtBefore","createdAtAfter","approveAfterDownload","doneInputValidation","downloadPrivacyRequestFiles"],"mappings":"AAAA,iIAAwC,wDAA0C,gCAA6B,gCAA6B,gCAA6B,gCAA6B,2DCExK,MAgB9B,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CAAW,CAACC,2BAAAA,CAAc,SAAA,CAAWA,2BAAAA,CAAc,YAAY,CAAA,CAC/D,WAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,cAAA,CAAAC,CAAAA,CACA,oBAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,MAAMC,kCAAAA,CACJ,YAAA,CAAAV,CAAAA,CACA,IAAA,CAAAD,CAAAA,CACA,UAAA,CAAAE,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,WAAA,CAAAE,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,cAAA,CAAAC,CAAAA,CACA,oBAAA,CAAAC,CACF,CAAC,CACH,CAAA,0BAAA","file":"/home/runner/work/cli/cli/dist/impl-UHCILICE.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport { downloadPrivacyRequestFiles } from '../../../lib/requests';\nimport { RequestStatus } from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface DownloadFilesCommandFlags {\n auth: string;\n sombraAuth?: string;\n concurrency: number;\n requestIds?: string[];\n statuses?: RequestStatus[];\n folderPath: string;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n approveAfterDownload: boolean;\n transcendUrl: string;\n}\n\nexport async function downloadFiles(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n folderPath,\n requestIds,\n statuses = [RequestStatus.Approving, RequestStatus.Downloadable],\n concurrency,\n createdAtBefore,\n createdAtAfter,\n approveAfterDownload,\n }: DownloadFilesCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await downloadPrivacyRequestFiles({\n transcendUrl,\n auth,\n folderPath,\n requestIds,\n statuses,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n approveAfterDownload,\n });\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-55NL4KOI.cjs","../src/commands/request/download-files/impl.ts"],"names":["downloadFiles","auth","transcendUrl","folderPath","requestIds","statuses","RequestStatus","concurrency","createdAtBefore","createdAtAfter","approveAfterDownload","doneInputValidation","downloadPrivacyRequestFiles"],"mappings":"AAAA,iIAAwC,wDAA0C,gCAA6B,gCAA6B,gCAA6B,gCAA6B,2DCExK,MAgB9B,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CAAW,CAACC,2BAAAA,CAAc,SAAA,CAAWA,2BAAAA,CAAc,YAAY,CAAA,CAC/D,WAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,cAAA,CAAAC,CAAAA,CACA,oBAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,MAAMC,kCAAAA,CACJ,YAAA,CAAAV,CAAAA,CACA,IAAA,CAAAD,CAAAA,CACA,UAAA,CAAAE,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,WAAA,CAAAE,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,cAAA,CAAAC,CAAAA,CACA,oBAAA,CAAAC,CACF,CAAC,CACH,CAAA,0BAAA","file":"/home/runner/work/cli/cli/dist/impl-55NL4KOI.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport { downloadPrivacyRequestFiles } from '../../../lib/requests';\nimport { RequestStatus } from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface DownloadFilesCommandFlags {\n auth: string;\n sombraAuth?: string;\n concurrency: number;\n requestIds?: string[];\n statuses?: RequestStatus[];\n folderPath: string;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n approveAfterDownload: boolean;\n transcendUrl: string;\n}\n\nexport async function downloadFiles(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n folderPath,\n requestIds,\n statuses = [RequestStatus.Approving, RequestStatus.Downloadable],\n concurrency,\n createdAtBefore,\n createdAtAfter,\n approveAfterDownload,\n }: DownloadFilesCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await downloadPrivacyRequestFiles({\n transcendUrl,\n auth,\n folderPath,\n requestIds,\n statuses,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n approveAfterDownload,\n });\n}\n"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkX6CJEYOAcjs = require('./chunk-X6CJEYOA.cjs');require('./chunk-LCDYXJN6.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkMGIVF74Zcjs = require('./chunk-MGIVF74Z.cjs');require('./chunk-Q7I37FJV.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function F({auth:n,transcendUrl:m,file:e,pageLimit:c,actions:p,sombraAuth:u,skipRequestIdentifiers:f,statuses:l,createdAtBefore:d,createdAtAfter:g,showTests:q}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);let{requestsFormattedForCsv:t}=await _chunkX6CJEYOAcjs.Of.call(void 0, {transcendUrl:m,pageLimit:c,actions:p,skipRequestIdentifiers:f,statuses:l,auth:n,sombraAuth:u,createdAtBefore:d,createdAtAfter:g,isTest:q}),x=_chunkMGIVF74Zcjs.j.call(void 0, t.map(y=>Object.keys(y)).flat());await _chunkX6CJEYOAcjs.rg.call(void 0, e,t,x),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully wrote ${t.length} requests to file "${e}"`))}exports._export = F;
2
- //# sourceMappingURL=impl-NAITRZS5.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkKUBXRT3Vcjs = require('./chunk-KUBXRT3V.cjs');require('./chunk-LCDYXJN6.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkEYOQLGDVcjs = require('./chunk-EYOQLGDV.cjs');require('./chunk-Q7I37FJV.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function F({auth:n,transcendUrl:m,file:e,pageLimit:c,actions:p,sombraAuth:u,skipRequestIdentifiers:f,statuses:l,createdAtBefore:d,createdAtAfter:g,showTests:q}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);let{requestsFormattedForCsv:t}=await _chunkKUBXRT3Vcjs.Of.call(void 0, {transcendUrl:m,pageLimit:c,actions:p,skipRequestIdentifiers:f,statuses:l,auth:n,sombraAuth:u,createdAtBefore:d,createdAtAfter:g,isTest:q}),x=_chunkEYOQLGDVcjs.j.call(void 0, t.map(y=>Object.keys(y)).flat());await _chunkKUBXRT3Vcjs.rg.call(void 0, e,t,x),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully wrote ${t.length} requests to file "${e}"`))}exports._export = F;
2
+ //# sourceMappingURL=impl-7B7QDZZJ.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-NAITRZS5.cjs","../src/commands/request/export/impl.ts"],"names":["_export","auth","transcendUrl","file","pageLimit","actions","sombraAuth","skipRequestIdentifiers","statuses","createdAtBefore","createdAtAfter","showTests","doneInputValidation","requestsFormattedForCsv","pullPrivacyRequests","headers","uniq_default","d","writeLargeCsv","logger","colors"],"mappings":"AAAA,iOAAmC,wDAAkD,gCAA6B,wDAAyC,wDAAyC,gCAA6B,gFCC9M,MA0BnB,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,sBAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,cAAA,CAAAC,CAAAA,CACA,SAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,GAAM,CAAE,uBAAA,CAAAC,CAAwB,CAAA,CAAI,MAAMC,kCAAAA,CACxC,YAAA,CAAAZ,CAAAA,CACA,SAAA,CAAAE,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,sBAAA,CAAAE,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,IAAA,CAAAP,CAAAA,CACA,UAAA,CAAAK,CAAAA,CACA,eAAA,CAAAG,CAAAA,CACA,cAAA,CAAAC,CAAAA,CACA,MAAA,CAAQC,CACV,CAAC,CAAA,CAGKI,CAAAA,CAAUC,iCAAAA,CACdH,CAAwB,GAAA,CAAKI,CAAAA,EAAM,MAAA,CAAO,IAAA,CAAKA,CAAC,CAAC,CAAA,CAAE,IAAA,CAAK,CAC1D,CAAA,CACA,MAAMC,kCAAAA,CAAcf,CAAMU,CAAAA,CAAyBE,CAAO,CAAA,CAC1DI,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,KAAA,CACL,CAAA,mBAAA,EAAsBP,CAAAA,CAAwB,MAAM,CAAA,mBAAA,EAAsBV,CAAI,CAAA,CAAA,CAChF,CACF,CACF,CAAA,oBAAA","file":"/home/runner/work/cli/cli/dist/impl-NAITRZS5.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport colors from 'colors';\n\nimport { logger } from '../../../logger';\nimport { uniq } from 'lodash-es';\nimport { pullPrivacyRequests } from '../../../lib/requests';\nimport { writeLargeCsv } from '../../../lib/helpers';\nimport type { RequestAction, RequestStatus } from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface ExportCommandFlags {\n auth: string;\n sombraAuth?: string;\n actions?: RequestAction[];\n statuses?: RequestStatus[];\n transcendUrl: string;\n file: string;\n concurrency: number;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n showTests?: boolean;\n skipRequestIdentifiers?: boolean;\n pageLimit: number;\n}\n\n// `export` is a reserved keyword, so we need to prefix it with an underscore\n// eslint-disable-next-line no-underscore-dangle\nexport async function _export(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n file,\n pageLimit,\n actions,\n sombraAuth,\n skipRequestIdentifiers,\n statuses,\n createdAtBefore,\n createdAtAfter,\n showTests,\n }: ExportCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n const { requestsFormattedForCsv } = await pullPrivacyRequests({\n transcendUrl,\n pageLimit,\n actions,\n skipRequestIdentifiers,\n statuses,\n auth,\n sombraAuth,\n createdAtBefore,\n createdAtAfter,\n isTest: showTests,\n });\n\n // Write to CSV\n const headers = uniq(\n requestsFormattedForCsv.map((d) => Object.keys(d)).flat(),\n );\n await writeLargeCsv(file, requestsFormattedForCsv, headers);\n logger.info(\n colors.green(\n `Successfully wrote ${requestsFormattedForCsv.length} requests to file \"${file}\"`,\n ),\n );\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-7B7QDZZJ.cjs","../src/commands/request/export/impl.ts"],"names":["_export","auth","transcendUrl","file","pageLimit","actions","sombraAuth","skipRequestIdentifiers","statuses","createdAtBefore","createdAtAfter","showTests","doneInputValidation","requestsFormattedForCsv","pullPrivacyRequests","headers","uniq_default","d","writeLargeCsv","logger","colors"],"mappings":"AAAA,iOAAmC,wDAAkD,gCAA6B,wDAAyC,wDAAyC,gCAA6B,gFCC9M,MA0BnB,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,sBAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,cAAA,CAAAC,CAAAA,CACA,SAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,GAAM,CAAE,uBAAA,CAAAC,CAAwB,CAAA,CAAI,MAAMC,kCAAAA,CACxC,YAAA,CAAAZ,CAAAA,CACA,SAAA,CAAAE,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,sBAAA,CAAAE,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,IAAA,CAAAP,CAAAA,CACA,UAAA,CAAAK,CAAAA,CACA,eAAA,CAAAG,CAAAA,CACA,cAAA,CAAAC,CAAAA,CACA,MAAA,CAAQC,CACV,CAAC,CAAA,CAGKI,CAAAA,CAAUC,iCAAAA,CACdH,CAAwB,GAAA,CAAKI,CAAAA,EAAM,MAAA,CAAO,IAAA,CAAKA,CAAC,CAAC,CAAA,CAAE,IAAA,CAAK,CAC1D,CAAA,CACA,MAAMC,kCAAAA,CAAcf,CAAMU,CAAAA,CAAyBE,CAAO,CAAA,CAC1DI,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,KAAA,CACL,CAAA,mBAAA,EAAsBP,CAAAA,CAAwB,MAAM,CAAA,mBAAA,EAAsBV,CAAI,CAAA,CAAA,CAChF,CACF,CACF,CAAA,oBAAA","file":"/home/runner/work/cli/cli/dist/impl-7B7QDZZJ.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport colors from 'colors';\n\nimport { logger } from '../../../logger';\nimport { uniq } from 'lodash-es';\nimport { pullPrivacyRequests } from '../../../lib/requests';\nimport { writeLargeCsv } from '../../../lib/helpers';\nimport type { RequestAction, RequestStatus } from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface ExportCommandFlags {\n auth: string;\n sombraAuth?: string;\n actions?: RequestAction[];\n statuses?: RequestStatus[];\n transcendUrl: string;\n file: string;\n concurrency: number;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n showTests?: boolean;\n skipRequestIdentifiers?: boolean;\n pageLimit: number;\n}\n\n// `export` is a reserved keyword, so we need to prefix it with an underscore\n// eslint-disable-next-line no-underscore-dangle\nexport async function _export(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n file,\n pageLimit,\n actions,\n sombraAuth,\n skipRequestIdentifiers,\n statuses,\n createdAtBefore,\n createdAtAfter,\n showTests,\n }: ExportCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n const { requestsFormattedForCsv } = await pullPrivacyRequests({\n transcendUrl,\n pageLimit,\n actions,\n skipRequestIdentifiers,\n statuses,\n auth,\n sombraAuth,\n createdAtBefore,\n createdAtAfter,\n isTest: showTests,\n });\n\n // Write to CSV\n const headers = uniq(\n requestsFormattedForCsv.map((d) => Object.keys(d)).flat(),\n );\n await writeLargeCsv(file, requestsFormattedForCsv, headers);\n logger.info(\n colors.green(\n `Successfully wrote ${requestsFormattedForCsv.length} requests to file \"${file}\"`,\n ),\n );\n}\n"]}
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunkPZLVJBQMcjs = require('./chunk-PZLVJBQM.cjs');require('./chunk-UAO3IAO3.cjs');require('./chunk-5UBGZNDC.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkX6CJEYOAcjs = require('./chunk-X6CJEYOA.cjs');require('./chunk-LCDYXJN6.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkMGIVF74Zcjs = require('./chunk-MGIVF74Z.cjs');require('./chunk-Q7I37FJV.cjs');var _querystring = require('query-string');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _fastglob = require('fast-glob'); var _fastglob2 = _interopRequireDefault(_fastglob);async function m({scanPath:t,fileGlobs:e,ignoreDirs:g,config:p}){let{ignoreDirs:f,supportedFiles:s,scanFunction:a}=p,n=e===""?s:s.concat(e.split(",")),l=[...g.split(","),...f].filter(o=>o.length>0);try{let o=await _fastglob2.default.call(void 0, `${t}/**/${n.join("|")}`,{ignore:l.map(i=>`${t}/**/${i}`),unique:!0,onlyFiles:!0});_chunkZUNVPK23cjs.a.info(`Scanning: ${o.length} files`);let I=o.map(i=>a(i)).flat().map(i=>i.softwareDevelopmentKits||[]).flat(),d=[...new Set(I.map(i=>i.name))];return _chunkZUNVPK23cjs.a.info(`Found: ${d.length} unique dependencies`),d.map(i=>({name:i,resourceId:`${t}/**/${i}`,useStrictClassifier:!0}))}catch(o){throw new Error(`Error scanning globs ${m} with error: ${o}`)}}async function P({scanPath:t,dataSiloId:e,auth:g,fileGlobs:p,ignoreDirs:f,transcendUrl:s}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);let a=_chunkX6CJEYOAcjs.wc.call(void 0, s,g),n=await _chunkX6CJEYOAcjs.Bc.call(void 0, a,e),l=_chunkPZLVJBQMcjs.a[n.dataSilo.type];l||(_chunkZUNVPK23cjs.a.error(_colors2.default.red(`This plugin "${n.dataSilo.type}" is not supported for offline silo discovery.`)),this.process.exit(1));let o=await m({scanPath:t,fileGlobs:p,ignoreDirs:f,config:l});await _chunkX6CJEYOAcjs.mf.call(void 0, a,n.id,o);let c=new URL(_chunkMGIVF74Zcjs.o);c.pathname="/data-map/data-inventory/silo-discovery/triage",c.search=_querystring.stringify.call(void 0, {filters:JSON.stringify({pluginIds:[n.id]})}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Scan found ${o.length} potential data silos at ${t}! View at '${c.href}'
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunk7PF5VVAFcjs = require('./chunk-7PF5VVAF.cjs');require('./chunk-K4TIJ3VM.cjs');require('./chunk-ECGHWDVP.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkKUBXRT3Vcjs = require('./chunk-KUBXRT3V.cjs');require('./chunk-LCDYXJN6.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkEYOQLGDVcjs = require('./chunk-EYOQLGDV.cjs');require('./chunk-Q7I37FJV.cjs');var _querystring = require('query-string');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _fastglob = require('fast-glob'); var _fastglob2 = _interopRequireDefault(_fastglob);async function m({scanPath:t,fileGlobs:e,ignoreDirs:g,config:p}){let{ignoreDirs:f,supportedFiles:s,scanFunction:a}=p,n=e===""?s:s.concat(e.split(",")),l=[...g.split(","),...f].filter(o=>o.length>0);try{let o=await _fastglob2.default.call(void 0, `${t}/**/${n.join("|")}`,{ignore:l.map(i=>`${t}/**/${i}`),unique:!0,onlyFiles:!0});_chunkZUNVPK23cjs.a.info(`Scanning: ${o.length} files`);let I=o.map(i=>a(i)).flat().map(i=>i.softwareDevelopmentKits||[]).flat(),d=[...new Set(I.map(i=>i.name))];return _chunkZUNVPK23cjs.a.info(`Found: ${d.length} unique dependencies`),d.map(i=>({name:i,resourceId:`${t}/**/${i}`,useStrictClassifier:!0}))}catch(o){throw new Error(`Error scanning globs ${m} with error: ${o}`)}}async function P({scanPath:t,dataSiloId:e,auth:g,fileGlobs:p,ignoreDirs:f,transcendUrl:s}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);let a=_chunkKUBXRT3Vcjs.wc.call(void 0, s,g),n=await _chunkKUBXRT3Vcjs.Bc.call(void 0, a,e),l=_chunk7PF5VVAFcjs.a[n.dataSilo.type];l||(_chunkZUNVPK23cjs.a.error(_colors2.default.red(`This plugin "${n.dataSilo.type}" is not supported for offline silo discovery.`)),this.process.exit(1));let o=await m({scanPath:t,fileGlobs:p,ignoreDirs:f,config:l});await _chunkKUBXRT3Vcjs.mf.call(void 0, a,n.id,o);let c=new URL(_chunkEYOQLGDVcjs.o);c.pathname="/data-map/data-inventory/silo-discovery/triage",c.search=_querystring.stringify.call(void 0, {filters:JSON.stringify({pluginIds:[n.id]})}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Scan found ${o.length} potential data silos at ${t}! View at '${c.href}'
2
2
 
3
3
  NOTE: it may take 2-3 minutes for scan results to appear in the UI.`))}exports.discoverSilos = P;
4
- //# sourceMappingURL=impl-ZAKD7OF2.cjs.map
4
+ //# sourceMappingURL=impl-A6W2KTYL.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-ZAKD7OF2.cjs","../src/commands/inventory/discover-silos/impl.ts","../src/lib/code-scanning/findFilesToScan.ts"],"names":["findFilesToScan","scanPath","fileGlobs","ignoreDirs","config","IGNORE_DIRS","supportedFiles","scanFunction","globsToSupport","dirsToIgnore","dir","filesToScan","fastGlob"],"mappings":"AAAA,iOAAwC,gCAA6B,gCAA6B,wDAAyC,wDAA0D,gCAA6B,wDAAyC,wDAAyC,gCAA6B,2CCCvT,gFAEP,yFCHE,MAsBrB,SAAsBA,CAAAA,CAAgB,CACpC,QAAA,CAAAC,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,MAAA,CAAAC,CACF,CAAA,CASuC,CACrC,GAAM,CAAE,UAAA,CAAYC,CAAAA,CAAa,cAAA,CAAAC,CAAAA,CAAgB,YAAA,CAAAC,CAAa,CAAA,CAAIH,CAAAA,CAC5DI,CAAAA,CACJN,CAAAA,GAAc,EAAA,CACVI,CAAAA,CACAA,CAAAA,CAAe,MAAA,CAAOJ,CAAAA,CAAU,KAAA,CAAM,GAAG,CAAC,CAAA,CAC1CO,CAAAA,CAAe,CAAC,GAAGN,CAAAA,CAAW,KAAA,CAAM,GAAG,CAAA,CAAG,GAAGE,CAAW,CAAA,CAAE,MAAA,CAC7DK,CAAAA,EAAQA,CAAAA,CAAI,MAAA,CAAS,CACxB,CAAA,CACA,GAAI,CACF,IAAMC,CAAAA,CAAwB,MAAMC,gCAAAA,CAClC,EAAA;ADuByB;AAI/B,oEAAA","file":"/home/runner/work/cli/cli/dist/impl-ZAKD7OF2.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport { stringify } from 'query-string';\nimport { logger } from '../../../logger';\nimport colors from 'colors';\nimport { ADMIN_DASH } from '../../../constants';\nimport {\n fetchActiveSiloDiscoPlugin,\n buildTranscendGraphQLClient,\n uploadSiloDiscoveryResults,\n} from '../../../lib/graphql';\nimport { findFilesToScan } from '../../../lib/code-scanning/findFilesToScan';\nimport { SILO_DISCOVERY_CONFIGS } from '../../../lib/code-scanning';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface DiscoverSilosCommandFlags {\n scanPath: string;\n dataSiloId: string;\n auth: string;\n fileGlobs: string;\n ignoreDirs: string;\n transcendUrl: string;\n}\n\nexport async function discoverSilos(\n this: LocalContext,\n {\n scanPath,\n dataSiloId,\n auth,\n fileGlobs,\n ignoreDirs,\n transcendUrl,\n }: DiscoverSilosCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const plugin = await fetchActiveSiloDiscoPlugin(client, dataSiloId);\n\n const config = SILO_DISCOVERY_CONFIGS[plugin.dataSilo.type];\n if (!config) {\n logger.error(\n colors.red(\n `This plugin \"${plugin.dataSilo.type}\" is not supported for offline silo discovery.`,\n ),\n );\n this.process.exit(1);\n }\n\n const results = await findFilesToScan({\n scanPath,\n fileGlobs,\n ignoreDirs,\n config,\n });\n\n await uploadSiloDiscoveryResults(client, plugin.id, results);\n\n const newUrl = new URL(ADMIN_DASH);\n newUrl.pathname = '/data-map/data-inventory/silo-discovery/triage';\n newUrl.search = stringify({\n filters: JSON.stringify({ pluginIds: [plugin.id] }),\n });\n\n // Indicate success\n logger.info(\n colors.green(\n `Scan found ${results.length} potential data silos at ${scanPath}! ` +\n `View at '${newUrl.href}' ` +\n '\\n\\n NOTE: it may take 2-3 minutes for scan results to appear in the UI.',\n ),\n );\n}\n","import fastGlob from 'fast-glob';\nimport { logger } from '../../logger';\nimport { CodeScanningConfig } from './types';\n\nexport interface SiloDiscoveryRawResults {\n /** The name of the potential data silo entry */\n name: string;\n /** A unique UUID (represents the same resource across different silo discovery runs) */\n resourceId: string;\n /** Any hosts associated with the entry */\n host?: string;\n /** Type of data silo */\n type?: string | undefined;\n}\n\n/**\n * Helper to scan for data silos in all package.json files that it can find in a directory\n *\n * @deprecated TODO: https://transcend.height.app/T-32325 - use code scanning instead\n * @param options - Options\n * @returns the list of integrations\n */\nexport async function findFilesToScan({\n scanPath,\n fileGlobs,\n ignoreDirs,\n config,\n}: {\n /** Where to look for package.json files */\n scanPath: string;\n /** Globs to look for */\n fileGlobs: string;\n /** The directories to ignore (excludes node_modules and serverless-build) */\n ignoreDirs: string;\n /** Silo Discovery configuration */\n config: CodeScanningConfig;\n}): Promise<SiloDiscoveryRawResults[]> {\n const { ignoreDirs: IGNORE_DIRS, supportedFiles, scanFunction } = config;\n const globsToSupport =\n fileGlobs === ''\n ? supportedFiles\n : supportedFiles.concat(fileGlobs.split(','));\n const dirsToIgnore = [...ignoreDirs.split(','), ...IGNORE_DIRS].filter(\n (dir) => dir.length > 0,\n );\n try {\n const filesToScan: string[] = await fastGlob(\n `${scanPath}/**/${globsToSupport.join('|')}`,\n {\n ignore: dirsToIgnore.map((dir: string) => `${scanPath}/**/${dir}`),\n unique: true,\n onlyFiles: true,\n },\n );\n logger.info(`Scanning: ${filesToScan.length} files`);\n const allPackages = filesToScan\n .map((filePath: string) => scanFunction(filePath))\n .flat();\n const allSdks = allPackages\n .map((appPackage) => appPackage.softwareDevelopmentKits || [])\n .flat();\n const uniqueDeps = new Set(allSdks.map((sdk) => sdk.name));\n const deps = [...uniqueDeps];\n logger.info(`Found: ${deps.length} unique dependencies`);\n return deps.map((dep) => ({\n name: dep,\n resourceId: `${scanPath}/**/${dep}`,\n useStrictClassifier: true,\n }));\n } catch (error) {\n throw new Error(\n `Error scanning globs ${findFilesToScan} with error: ${error}`,\n );\n }\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-A6W2KTYL.cjs","../src/commands/inventory/discover-silos/impl.ts","../src/lib/code-scanning/findFilesToScan.ts"],"names":["findFilesToScan","scanPath","fileGlobs","ignoreDirs","config","IGNORE_DIRS","supportedFiles","scanFunction","globsToSupport","dirsToIgnore","dir","filesToScan","fastGlob"],"mappings":"AAAA,iOAAwC,gCAA6B,gCAA6B,wDAAyC,wDAA0D,gCAA6B,wDAAyC,wDAAyC,gCAA6B,2CCCvT,gFAEP,yFCHE,MAsBrB,SAAsBA,CAAAA,CAAgB,CACpC,QAAA,CAAAC,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,MAAA,CAAAC,CACF,CAAA,CASuC,CACrC,GAAM,CAAE,UAAA,CAAYC,CAAAA,CAAa,cAAA,CAAAC,CAAAA,CAAgB,YAAA,CAAAC,CAAa,CAAA,CAAIH,CAAAA,CAC5DI,CAAAA,CACJN,CAAAA,GAAc,EAAA,CACVI,CAAAA,CACAA,CAAAA,CAAe,MAAA,CAAOJ,CAAAA,CAAU,KAAA,CAAM,GAAG,CAAC,CAAA,CAC1CO,CAAAA,CAAe,CAAC,GAAGN,CAAAA,CAAW,KAAA,CAAM,GAAG,CAAA,CAAG,GAAGE,CAAW,CAAA,CAAE,MAAA,CAC7DK,CAAAA,EAAQA,CAAAA,CAAI,MAAA,CAAS,CACxB,CAAA,CACA,GAAI,CACF,IAAMC,CAAAA,CAAwB,MAAMC,gCAAAA,CAClC,EAAA;ADuByB;AAI/B,oEAAA","file":"/home/runner/work/cli/cli/dist/impl-A6W2KTYL.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport { stringify } from 'query-string';\nimport { logger } from '../../../logger';\nimport colors from 'colors';\nimport { ADMIN_DASH } from '../../../constants';\nimport {\n fetchActiveSiloDiscoPlugin,\n buildTranscendGraphQLClient,\n uploadSiloDiscoveryResults,\n} from '../../../lib/graphql';\nimport { findFilesToScan } from '../../../lib/code-scanning/findFilesToScan';\nimport { SILO_DISCOVERY_CONFIGS } from '../../../lib/code-scanning';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface DiscoverSilosCommandFlags {\n scanPath: string;\n dataSiloId: string;\n auth: string;\n fileGlobs: string;\n ignoreDirs: string;\n transcendUrl: string;\n}\n\nexport async function discoverSilos(\n this: LocalContext,\n {\n scanPath,\n dataSiloId,\n auth,\n fileGlobs,\n ignoreDirs,\n transcendUrl,\n }: DiscoverSilosCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const plugin = await fetchActiveSiloDiscoPlugin(client, dataSiloId);\n\n const config = SILO_DISCOVERY_CONFIGS[plugin.dataSilo.type];\n if (!config) {\n logger.error(\n colors.red(\n `This plugin \"${plugin.dataSilo.type}\" is not supported for offline silo discovery.`,\n ),\n );\n this.process.exit(1);\n }\n\n const results = await findFilesToScan({\n scanPath,\n fileGlobs,\n ignoreDirs,\n config,\n });\n\n await uploadSiloDiscoveryResults(client, plugin.id, results);\n\n const newUrl = new URL(ADMIN_DASH);\n newUrl.pathname = '/data-map/data-inventory/silo-discovery/triage';\n newUrl.search = stringify({\n filters: JSON.stringify({ pluginIds: [plugin.id] }),\n });\n\n // Indicate success\n logger.info(\n colors.green(\n `Scan found ${results.length} potential data silos at ${scanPath}! ` +\n `View at '${newUrl.href}' ` +\n '\\n\\n NOTE: it may take 2-3 minutes for scan results to appear in the UI.',\n ),\n );\n}\n","import fastGlob from 'fast-glob';\nimport { logger } from '../../logger';\nimport { CodeScanningConfig } from './types';\n\nexport interface SiloDiscoveryRawResults {\n /** The name of the potential data silo entry */\n name: string;\n /** A unique UUID (represents the same resource across different silo discovery runs) */\n resourceId: string;\n /** Any hosts associated with the entry */\n host?: string;\n /** Type of data silo */\n type?: string | undefined;\n}\n\n/**\n * Helper to scan for data silos in all package.json files that it can find in a directory\n *\n * @deprecated TODO: https://transcend.height.app/T-32325 - use code scanning instead\n * @param options - Options\n * @returns the list of integrations\n */\nexport async function findFilesToScan({\n scanPath,\n fileGlobs,\n ignoreDirs,\n config,\n}: {\n /** Where to look for package.json files */\n scanPath: string;\n /** Globs to look for */\n fileGlobs: string;\n /** The directories to ignore (excludes node_modules and serverless-build) */\n ignoreDirs: string;\n /** Silo Discovery configuration */\n config: CodeScanningConfig;\n}): Promise<SiloDiscoveryRawResults[]> {\n const { ignoreDirs: IGNORE_DIRS, supportedFiles, scanFunction } = config;\n const globsToSupport =\n fileGlobs === ''\n ? supportedFiles\n : supportedFiles.concat(fileGlobs.split(','));\n const dirsToIgnore = [...ignoreDirs.split(','), ...IGNORE_DIRS].filter(\n (dir) => dir.length > 0,\n );\n try {\n const filesToScan: string[] = await fastGlob(\n `${scanPath}/**/${globsToSupport.join('|')}`,\n {\n ignore: dirsToIgnore.map((dir: string) => `${scanPath}/**/${dir}`),\n unique: true,\n onlyFiles: true,\n },\n );\n logger.info(`Scanning: ${filesToScan.length} files`);\n const allPackages = filesToScan\n .map((filePath: string) => scanFunction(filePath))\n .flat();\n const allSdks = allPackages\n .map((appPackage) => appPackage.softwareDevelopmentKits || [])\n .flat();\n const uniqueDeps = new Set(allSdks.map((sdk) => sdk.name));\n const deps = [...uniqueDeps];\n logger.info(`Found: ${deps.length} unique dependencies`);\n return deps.map((dep) => ({\n name: dep,\n resourceId: `${scanPath}/**/${dep}`,\n useStrictClassifier: true,\n }));\n } catch (error) {\n throw new Error(\n `Error scanning globs ${findFilesToScan} with error: ${error}`,\n );\n }\n}\n"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkX6CJEYOAcjs = require('./chunk-X6CJEYOA.cjs');require('./chunk-LCDYXJN6.cjs');require('./chunk-ZUNVPK23.cjs');require('./chunk-MGIVF74Z.cjs');require('./chunk-Q7I37FJV.cjs');async function a({auth:o,transcendUrl:r,enricherIds:e}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),await _chunkX6CJEYOAcjs.Lf.call(void 0, {transcendUrl:r,auth:o,enricherIds:e})}exports.skipPreflightJobs = a;
2
- //# sourceMappingURL=impl-MNMSXIYH.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkKUBXRT3Vcjs = require('./chunk-KUBXRT3V.cjs');require('./chunk-LCDYXJN6.cjs');require('./chunk-ZUNVPK23.cjs');require('./chunk-EYOQLGDV.cjs');require('./chunk-Q7I37FJV.cjs');async function a({auth:o,transcendUrl:r,enricherIds:e}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),await _chunkKUBXRT3Vcjs.Lf.call(void 0, {transcendUrl:r,auth:o,enricherIds:e})}exports.skipPreflightJobs = a;
2
+ //# sourceMappingURL=impl-ALROZNDJ.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-MNMSXIYH.cjs","../src/commands/request/skip-preflight-jobs/impl.ts"],"names":["skipPreflightJobs","auth","transcendUrl","enricherIds","doneInputValidation"],"mappings":"AAAA,iIAAwC,wDAA0C,gCAA6B,gCAA6B,gCAA6B,gCAA6B,MCUtM,SAAsBA,CAAAA,CAEpB,CAAE,IAAA,CAAAC,CAAAA,CAAM,YAAA,CAAAC,CAAAA,CAAc,WAAA,CAAAC,CAAY,CAAA,CACnB,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,MAAMJ,kCAAAA,CACJ,YAAA,CAAAE,CAAAA,CACA,IAAA,CAAAD,CAAAA,CACA,WAAA,CAAAE,CACF,CAAC,CACH,CAAA,8BAAA","file":"/home/runner/work/cli/cli/dist/impl-MNMSXIYH.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport { skipPreflightJobs as skipPreflightJobsHelper } from '../../../lib/requests';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface SkipPreflightJobsCommandFlags {\n auth: string;\n enricherIds: string[];\n transcendUrl: string;\n}\n\nexport async function skipPreflightJobs(\n this: LocalContext,\n { auth, transcendUrl, enricherIds }: SkipPreflightJobsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await skipPreflightJobsHelper({\n transcendUrl,\n auth,\n enricherIds,\n });\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-ALROZNDJ.cjs","../src/commands/request/skip-preflight-jobs/impl.ts"],"names":["skipPreflightJobs","auth","transcendUrl","enricherIds","doneInputValidation"],"mappings":"AAAA,iIAAwC,wDAA0C,gCAA6B,gCAA6B,gCAA6B,gCAA6B,MCUtM,SAAsBA,CAAAA,CAEpB,CAAE,IAAA,CAAAC,CAAAA,CAAM,YAAA,CAAAC,CAAAA,CAAc,WAAA,CAAAC,CAAY,CAAA,CACnB,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,MAAMJ,kCAAAA,CACJ,YAAA,CAAAE,CAAAA,CACA,IAAA,CAAAD,CAAAA,CACA,WAAA,CAAAE,CACF,CAAC,CACH,CAAA,8BAAA","file":"/home/runner/work/cli/cli/dist/impl-ALROZNDJ.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport { skipPreflightJobs as skipPreflightJobsHelper } from '../../../lib/requests';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface SkipPreflightJobsCommandFlags {\n auth: string;\n enricherIds: string[];\n transcendUrl: string;\n}\n\nexport async function skipPreflightJobs(\n this: LocalContext,\n { auth, transcendUrl, enricherIds }: SkipPreflightJobsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await skipPreflightJobsHelper({\n transcendUrl,\n auth,\n enricherIds,\n });\n}\n"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunkLMUWS7HIcjs = require('./chunk-LMUWS7HI.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkX6CJEYOAcjs = require('./chunk-X6CJEYOA.cjs');require('./chunk-LCDYXJN6.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkMGIVF74Zcjs = require('./chunk-MGIVF74Z.cjs');require('./chunk-Q7I37FJV.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function j({auth:p,file:o,transcendUrl:f,dataSiloIds:g,subCategories:C,status:S,includeEncryptedSnippets:a}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);try{let i=_chunkX6CJEYOAcjs.wc.call(void 0, f,p),b=await _chunkLMUWS7HIcjs.b.call(void 0, i,{dataSiloIds:g,subCategories:C,status:S,includeEncryptedSnippets:a});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Writing unstructured discovery files to file "${o}"...`));let s=[],h=b.map(t=>{let n={"Entry ID":t.id,"Data Silo ID":t.dataSiloId,"Object Path ID":t.scannedObjectPathId,"Object ID":t.scannedObjectId,...a?{Entry:t.name,"Context Snippet":t.contextSnippet}:{},"Data Category":`${t.dataSubCategory.category}:${t.dataSubCategory.name}`,"Classification Status":t.status,"Confidence Score":t.confidence,"Classification Method":t.classificationMethod,"Classifier Version":t.classifierVersion};return s=_chunkMGIVF74Zcjs.j.call(void 0, [...s,...Object.keys(n)]),n});await _chunkX6CJEYOAcjs.rg.call(void 0, o,h,s)}catch(i){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`An error occurred syncing the unstructured discovery files: ${i.message}`)),this.process.exit(1)}_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully synced unstructured discovery files to disk at ${o}!`))}exports.pullUnstructuredDiscoveryFiles = j;
2
- //# sourceMappingURL=impl-65UAYE4Y.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunkTHOOR2KAcjs = require('./chunk-THOOR2KA.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkKUBXRT3Vcjs = require('./chunk-KUBXRT3V.cjs');require('./chunk-LCDYXJN6.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkEYOQLGDVcjs = require('./chunk-EYOQLGDV.cjs');require('./chunk-Q7I37FJV.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function j({auth:p,file:o,transcendUrl:f,dataSiloIds:g,subCategories:C,status:S,includeEncryptedSnippets:a}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);try{let i=_chunkKUBXRT3Vcjs.wc.call(void 0, f,p),b=await _chunkTHOOR2KAcjs.b.call(void 0, i,{dataSiloIds:g,subCategories:C,status:S,includeEncryptedSnippets:a});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Writing unstructured discovery files to file "${o}"...`));let s=[],h=b.map(t=>{let n={"Entry ID":t.id,"Data Silo ID":t.dataSiloId,"Object Path ID":t.scannedObjectPathId,"Object ID":t.scannedObjectId,...a?{Entry:t.name,"Context Snippet":t.contextSnippet}:{},"Data Category":`${t.dataSubCategory.category}:${t.dataSubCategory.name}`,"Classification Status":t.status,"Confidence Score":t.confidence,"Classification Method":t.classificationMethod,"Classifier Version":t.classifierVersion};return s=_chunkEYOQLGDVcjs.j.call(void 0, [...s,...Object.keys(n)]),n});await _chunkKUBXRT3Vcjs.rg.call(void 0, o,h,s)}catch(i){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`An error occurred syncing the unstructured discovery files: ${i.message}`)),this.process.exit(1)}_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully synced unstructured discovery files to disk at ${o}!`))}exports.pullUnstructuredDiscoveryFiles = j;
2
+ //# sourceMappingURL=impl-ANXIZT7S.cjs.map