@transcend-io/cli 8.0.1 → 8.0.2

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 (143) hide show
  1. package/dist/bin/bash-complete.cjs +1 -1
  2. package/dist/bin/cli.cjs +1 -1
  3. package/dist/bin/deprecated-command.cjs +2 -2
  4. package/dist/{chunk-WRJVOXRS.cjs → chunk-3PX3HVEO.cjs} +2 -2
  5. package/dist/{chunk-WRJVOXRS.cjs.map → chunk-3PX3HVEO.cjs.map} +1 -1
  6. package/dist/{chunk-DBYKJZEA.cjs → chunk-44J2TVZU.cjs} +2 -2
  7. package/dist/{chunk-DBYKJZEA.cjs.map → chunk-44J2TVZU.cjs.map} +1 -1
  8. package/dist/chunk-7UL54E7X.cjs +2 -0
  9. package/dist/{chunk-MBB6OD4E.cjs.map → chunk-7UL54E7X.cjs.map} +1 -1
  10. package/dist/chunk-A4OQQVQT.cjs +3 -0
  11. package/dist/chunk-A4OQQVQT.cjs.map +1 -0
  12. package/dist/chunk-BPX6MSMC.cjs +2 -0
  13. package/dist/chunk-BPX6MSMC.cjs.map +1 -0
  14. package/dist/{chunk-7NYZMFPT.cjs → chunk-FNBADTTI.cjs} +19 -19
  15. package/dist/{chunk-7NYZMFPT.cjs.map → chunk-FNBADTTI.cjs.map} +1 -1
  16. package/dist/{chunk-56TB3NTQ.cjs → chunk-N7QF44VW.cjs} +2 -2
  17. package/dist/{chunk-56TB3NTQ.cjs.map → chunk-N7QF44VW.cjs.map} +1 -1
  18. package/dist/chunk-PQTI6C4Q.cjs +12 -0
  19. package/dist/chunk-PQTI6C4Q.cjs.map +1 -0
  20. package/dist/chunk-UONUI4AB.cjs +2920 -0
  21. package/dist/chunk-UONUI4AB.cjs.map +1 -0
  22. package/dist/chunk-W3S3ULXN.cjs +2 -0
  23. package/dist/chunk-W3S3ULXN.cjs.map +1 -0
  24. package/dist/{chunk-KS2REJYA.cjs → chunk-XARKMCNP.cjs} +4 -4
  25. package/dist/chunk-XARKMCNP.cjs.map +1 -0
  26. package/dist/{chunk-6IHSPKMP.cjs → chunk-XPKFB4IL.cjs} +2 -2
  27. package/dist/{chunk-6IHSPKMP.cjs.map → chunk-XPKFB4IL.cjs.map} +1 -1
  28. package/dist/{chunk-WLUTU3MY.cjs → chunk-YKZKPWDF.cjs} +2 -2
  29. package/dist/{chunk-WLUTU3MY.cjs.map → chunk-YKZKPWDF.cjs.map} +1 -1
  30. package/dist/chunk-YMXQXAUZ.cjs +2 -0
  31. package/dist/{chunk-PSRKLYGK.cjs.map → chunk-YMXQXAUZ.cjs.map} +1 -1
  32. package/dist/{chunk-PNSZQIYV.cjs → chunk-YP2PMUM5.cjs} +2 -2
  33. package/dist/{chunk-PNSZQIYV.cjs.map → chunk-YP2PMUM5.cjs.map} +1 -1
  34. package/dist/{impl-57LDSC2M.cjs → impl-2BXBJZII.cjs} +2 -2
  35. package/dist/{impl-57LDSC2M.cjs.map → impl-2BXBJZII.cjs.map} +1 -1
  36. package/dist/{impl-RGYCC7MP.cjs → impl-2SHN3CZX.cjs} +2 -2
  37. package/dist/{impl-RGYCC7MP.cjs.map → impl-2SHN3CZX.cjs.map} +1 -1
  38. package/dist/{impl-5KEI5AJG.cjs → impl-334G4VTL.cjs} +2 -2
  39. package/dist/{impl-5KEI5AJG.cjs.map → impl-334G4VTL.cjs.map} +1 -1
  40. package/dist/{impl-RXVSZRCO.cjs → impl-37NGCBEQ.cjs} +2 -2
  41. package/dist/{impl-RXVSZRCO.cjs.map → impl-37NGCBEQ.cjs.map} +1 -1
  42. package/dist/{impl-AHLMRZNM.cjs → impl-5IS3UVQQ.cjs} +2 -2
  43. package/dist/{impl-AHLMRZNM.cjs.map → impl-5IS3UVQQ.cjs.map} +1 -1
  44. package/dist/{impl-UMRC5P5T.cjs → impl-5IZQDLG7.cjs} +2 -2
  45. package/dist/{impl-UMRC5P5T.cjs.map → impl-5IZQDLG7.cjs.map} +1 -1
  46. package/dist/impl-7MIPQI3E.cjs +2 -0
  47. package/dist/impl-7MIPQI3E.cjs.map +1 -0
  48. package/dist/impl-AJMAFFJG.cjs +2 -0
  49. package/dist/{impl-FP3D5M5B.cjs.map → impl-AJMAFFJG.cjs.map} +1 -1
  50. package/dist/{impl-XW7JECCZ.cjs → impl-BL64FHKY.cjs} +2 -2
  51. package/dist/{impl-XW7JECCZ.cjs.map → impl-BL64FHKY.cjs.map} +1 -1
  52. package/dist/{impl-QJJNBKJR.cjs → impl-BXNGIHN2.cjs} +2 -2
  53. package/dist/{impl-QJJNBKJR.cjs.map → impl-BXNGIHN2.cjs.map} +1 -1
  54. package/dist/impl-DDHHIRXW.cjs +12 -0
  55. package/dist/impl-DDHHIRXW.cjs.map +1 -0
  56. package/dist/impl-DFDEITPV.cjs +7 -0
  57. package/dist/impl-DFDEITPV.cjs.map +1 -0
  58. package/dist/{impl-TJP4ZLHS.cjs → impl-DZSW2V2J.cjs} +2 -2
  59. package/dist/{impl-TJP4ZLHS.cjs.map → impl-DZSW2V2J.cjs.map} +1 -1
  60. package/dist/impl-FC7ICRDM.cjs +2 -0
  61. package/dist/{impl-YUYWOPRG.cjs.map → impl-FC7ICRDM.cjs.map} +1 -1
  62. package/dist/{impl-T4BXYX2K.cjs → impl-G2MAA4QD.cjs} +2 -2
  63. package/dist/{impl-T4BXYX2K.cjs.map → impl-G2MAA4QD.cjs.map} +1 -1
  64. package/dist/{impl-GP2DMI4O.cjs → impl-GIZXIRD5.cjs} +2 -2
  65. package/dist/{impl-GP2DMI4O.cjs.map → impl-GIZXIRD5.cjs.map} +1 -1
  66. package/dist/{impl-UG3FWG22.cjs → impl-H3RZXUMP.cjs} +2 -2
  67. package/dist/{impl-UG3FWG22.cjs.map → impl-H3RZXUMP.cjs.map} +1 -1
  68. package/dist/impl-HG3PK5DG.cjs +2 -0
  69. package/dist/{impl-HVKSG236.cjs.map → impl-HG3PK5DG.cjs.map} +1 -1
  70. package/dist/impl-IAZCCRHG.cjs +2 -0
  71. package/dist/{impl-GPTJLZHD.cjs.map → impl-IAZCCRHG.cjs.map} +1 -1
  72. package/dist/{impl-LZUXHWDU.cjs → impl-K3VBUCUB.cjs} +2 -2
  73. package/dist/{impl-LZUXHWDU.cjs.map → impl-K3VBUCUB.cjs.map} +1 -1
  74. package/dist/impl-KMLDAWB5.cjs +6 -0
  75. package/dist/impl-KMLDAWB5.cjs.map +1 -0
  76. package/dist/impl-LDJGDZNJ.cjs +2 -0
  77. package/dist/impl-LDJGDZNJ.cjs.map +1 -0
  78. package/dist/impl-LLCE3XUF.cjs +6 -0
  79. package/dist/impl-LLCE3XUF.cjs.map +1 -0
  80. package/dist/{impl-G24XCV65.cjs → impl-MVGWE3OY.cjs} +2 -2
  81. package/dist/{impl-G24XCV65.cjs.map → impl-MVGWE3OY.cjs.map} +1 -1
  82. package/dist/{impl-PAXESZFC.cjs → impl-N56GZUUE.cjs} +2 -2
  83. package/dist/{impl-PAXESZFC.cjs.map → impl-N56GZUUE.cjs.map} +1 -1
  84. package/dist/{impl-HQLA253Z.cjs → impl-NRVKZ6QP.cjs} +2 -2
  85. package/dist/{impl-HQLA253Z.cjs.map → impl-NRVKZ6QP.cjs.map} +1 -1
  86. package/dist/{impl-L2XUXKHL.cjs → impl-O7M62JQO.cjs} +2 -2
  87. package/dist/{impl-L2XUXKHL.cjs.map → impl-O7M62JQO.cjs.map} +1 -1
  88. package/dist/{impl-SW44TCHM.cjs → impl-OXCKKL3L.cjs} +2 -2
  89. package/dist/{impl-SW44TCHM.cjs.map → impl-OXCKKL3L.cjs.map} +1 -1
  90. package/dist/{impl-JUUYZHGL.cjs → impl-OYQLTGBY.cjs} +2 -2
  91. package/dist/{impl-JUUYZHGL.cjs.map → impl-OYQLTGBY.cjs.map} +1 -1
  92. package/dist/{impl-TLDBJN7P.cjs → impl-PNDNQD25.cjs} +2 -2
  93. package/dist/{impl-TLDBJN7P.cjs.map → impl-PNDNQD25.cjs.map} +1 -1
  94. package/dist/{impl-4VCIYJCG.cjs → impl-Q2JAFPV5.cjs} +2 -2
  95. package/dist/{impl-4VCIYJCG.cjs.map → impl-Q2JAFPV5.cjs.map} +1 -1
  96. package/dist/{impl-W6OLYSNF.cjs → impl-Q6LOHZB6.cjs} +2 -2
  97. package/dist/{impl-W6OLYSNF.cjs.map → impl-Q6LOHZB6.cjs.map} +1 -1
  98. package/dist/{impl-AHNQLAH5.cjs → impl-QS77O4PW.cjs} +2 -2
  99. package/dist/{impl-AHNQLAH5.cjs.map → impl-QS77O4PW.cjs.map} +1 -1
  100. package/dist/{impl-MLEPL5MZ.cjs → impl-TC6DE6BU.cjs} +5 -5
  101. package/dist/impl-TC6DE6BU.cjs.map +1 -0
  102. package/dist/{impl-RPRRJOI3.cjs → impl-W6WGF5YD.cjs} +2 -2
  103. package/dist/{impl-RPRRJOI3.cjs.map → impl-W6WGF5YD.cjs.map} +1 -1
  104. package/dist/{impl-C53IQ5HC.cjs → impl-WHZWURMO.cjs} +2 -2
  105. package/dist/{impl-C53IQ5HC.cjs.map → impl-WHZWURMO.cjs.map} +1 -1
  106. package/dist/{impl-WSRMGN2H.cjs → impl-WWQBCKZV.cjs} +2 -2
  107. package/dist/{impl-WSRMGN2H.cjs.map → impl-WWQBCKZV.cjs.map} +1 -1
  108. package/dist/{impl-IKTY3PZ3.cjs → impl-XWRII7ET.cjs} +2 -2
  109. package/dist/{impl-IKTY3PZ3.cjs.map → impl-XWRII7ET.cjs.map} +1 -1
  110. package/dist/index.cjs +3 -3
  111. package/dist/index.cjs.map +1 -1
  112. package/dist/index.d.cts +1 -1
  113. package/package.json +4 -2
  114. package/dist/chunk-7G4SCKPN.cjs +0 -2
  115. package/dist/chunk-7G4SCKPN.cjs.map +0 -1
  116. package/dist/chunk-AMO6I4AO.cjs +0 -2
  117. package/dist/chunk-AMO6I4AO.cjs.map +0 -1
  118. package/dist/chunk-JMBVOY56.cjs +0 -3
  119. package/dist/chunk-JMBVOY56.cjs.map +0 -1
  120. package/dist/chunk-KS2REJYA.cjs.map +0 -1
  121. package/dist/chunk-MBB6OD4E.cjs +0 -2
  122. package/dist/chunk-PSRKLYGK.cjs +0 -2
  123. package/dist/chunk-PTQHBKJU.cjs +0 -12
  124. package/dist/chunk-PTQHBKJU.cjs.map +0 -1
  125. package/dist/chunk-UPUHHIXZ.cjs +0 -2920
  126. package/dist/chunk-UPUHHIXZ.cjs.map +0 -1
  127. package/dist/impl-5BNP4JYG.cjs +0 -2
  128. package/dist/impl-5BNP4JYG.cjs.map +0 -1
  129. package/dist/impl-5MGEJPTO.cjs +0 -12
  130. package/dist/impl-5MGEJPTO.cjs.map +0 -1
  131. package/dist/impl-DSRH7IN2.cjs +0 -2
  132. package/dist/impl-DSRH7IN2.cjs.map +0 -1
  133. package/dist/impl-FP3D5M5B.cjs +0 -2
  134. package/dist/impl-GPTJLZHD.cjs +0 -2
  135. package/dist/impl-HVKSG236.cjs +0 -2
  136. package/dist/impl-IVDJEVS4.cjs +0 -6
  137. package/dist/impl-IVDJEVS4.cjs.map +0 -1
  138. package/dist/impl-MLEPL5MZ.cjs.map +0 -1
  139. package/dist/impl-QW6NAOEK.cjs +0 -7
  140. package/dist/impl-QW6NAOEK.cjs.map +0 -1
  141. package/dist/impl-VF3LT3IJ.cjs +0 -6
  142. package/dist/impl-VF3LT3IJ.cjs.map +0 -1
  143. package/dist/impl-YUYWOPRG.cjs +0 -2
@@ -0,0 +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 }; } 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 _chunkUONUI4ABcjs = require('./chunk-UONUI4AB.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkXPKFB4ILcjs = require('./chunk-XPKFB4IL.cjs');var _chunk44J2TVZUcjs = require('./chunk-44J2TVZU.cjs');var _typeutils = require('@transcend-io/type-utils');var _internationalization = require('@transcend-io/internationalization');var _privacytypes = require('@transcend-io/privacy-types');var _iots = require('io-ts'); var R = _interopRequireWildcard(_iots); var te = _interopRequireWildcard(_iots); var at = _interopRequireWildcard(_iots); var P = _interopRequireWildcard(_iots); var q = _interopRequireWildcard(_iots); var C = _interopRequireWildcard(_iots); var fe = _interopRequireWildcard(_iots); var Ot = _interopRequireWildcard(_iots); var V = _interopRequireWildcard(_iots);var T="[NONE]",me= exports.b ="[APPLY VALUE TO ALL ROWS]",Pe= exports.c ="<blank>",Se= exports.d =["email","coreIdentifier"],ie= exports.e =(c=>(c.Email="email",c.CoreIdentifier="coreIdentifier",c.RequestType="requestType",c.SubjectType="subjectType",c.Locale="locale",c.Country="country",c.CountrySubDivision="countrySubDivision",c.RequestStatus="requestStatus",c.CreatedAt="createdAt",c.DataSiloIds="dataSiloIds",c))(ie||{}),He= exports.f ={email:!1,coreIdentifier:!0,requestType:!0,subjectType:!0,requestStatus:!1,createdAt:!1,dataSiloIds:!1,locale:!1,country:!1,countrySubDivision:!1},Xe= exports.g ={requestType:!0,subjectType:!0},et= exports.h =R.type({columnNames:R.partial(_typeutils.applyEnum.call(void 0, ie,()=>R.string)),identifierNames:R.record(R.string,R.string),attributeNames:R.record(R.string,R.string),requestTypeToRequestAction:R.record(R.string,_typeutils.valuesOf.call(void 0, _privacytypes.RequestAction)),subjectTypeToSubjectName:R.record(R.string,R.string),languageToLocale:R.record(R.string,_typeutils.valuesOf.call(void 0, _internationalization.LanguageKey)),regionToCountry:R.record(R.string,_typeutils.valuesOf.call(void 0, {..._privacytypes.IsoCountryCode,[T]:T})),regionToCountrySubDivision:R.record(R.string,_typeutils.valuesOf.call(void 0, {..._privacytypes.IsoCountrySubdivisionCode,[T]:T})),statusToRequestStatus:R.record(R.string,_typeutils.valuesOf.call(void 0, {..._privacytypes.CompletedRequestStatus,[T]:T}))}),be= exports.i =R.type({id:R.string,link:R.string,rowIndex:R.number,coreIdentifier:R.string,attemptedAt:R.string}),tt= exports.j =R.type({failingRequests:R.array(R.record(R.string,R.any)),successfulRequests:R.array(be),duplicateRequests:R.array(R.type({rowIndex:R.number,coreIdentifier:R.string,attemptedAt:R.string}))});var _inquirer = require('inquirer'); var _inquirer2 = _interopRequireDefault(_inquirer);var _fuzzysearch = require('fuzzysearch'); var _fuzzysearch2 = _interopRequireDefault(_fuzzysearch);function Te(n,e){return _fuzzysearch2.default.call(void 0, n.toLowerCase(),e.toLowerCase())||_fuzzysearch2.default.call(void 0, e.toLowerCase(),n.toLowerCase())}function ne(n,e,s,l){let a=n.filter(o=>Te(e.toLowerCase(),o.toLowerCase()));return[...a,new _inquirer2.default.Separator,...s?[]:[T],...l?[me]:[],...n.filter(o=>!a.includes(o))]}var _inquirerautocompleteprompt = require('inquirer-autocomplete-prompt'); var _inquirerautocompleteprompt2 = _interopRequireDefault(_inquirerautocompleteprompt);async function ee(n,e,s){_inquirer2.default.registerPrompt("autocomplete",_inquirerautocompleteprompt2.default);let l=n.map(o=>o||"<blank>").filter(o=>!s[o]);if(l.length===0)return s;let a=await _inquirer2.default.prompt(l.map(o=>({name:o,message:`Map value of: ${o}`,type:"autocomplete",default:e.find(i=>Te(o,i)),source:(i,r)=>r?e.filter(t=>typeof t=="string"&&Te(r,t)):e})));return{...s,..._typeutils.apply.call(void 0, a,o=>typeof o=="string"?o:Object.values(o)[0])}}function De(n){return n.split(",").map(e=>e.trim()).filter(e=>e)}var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var it=te.type({key:te.string,values:te.array(te.string)});function nt(n){let e=n.map(s=>{let[l,a]=s.trim().split(":");if(!a)throw new Error("Expected attributes in key:value1;value2,key2:value3;value4");let o=a.split(";");return{key:l,values:o}});return _chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Attributes to apply to all requests:")),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(JSON.stringify(e,null,2))),e}var _sync = require('csv-parse/sync');var _fs = require('fs');function ut(n,e,s={columns:!0}){let l=_sync.parse.call(void 0, _fs.readFileSync.call(void 0, n,"utf-8"),s);return _typeutils.decodeCodec.call(void 0, at.array(e),l).map(i=>Object.entries(i).reduce((r,[t,y])=>Object.assign(r,{[t.replace(/[^a-z_.+\-A-Z -~]/g,"")]:y}),{}))}function Q(n,e){return _chunk44J2TVZUcjs.j.call(void 0, n.map(s=>s[e]||"").flat())}async function ct(n){let e=_chunk44J2TVZUcjs.j.call(void 0, n.map(a=>Object.keys(a)).flat()),s=n,l=!0;for(;l;){let{filterColumnName:a}=await _inquirer2.default.prompt([{name:"filterColumnName",message:`If you need to filter the list of requests to import, choose the column to filter on. Currently ${s.length} rows.`,type:"list",default:e,choices:[T,...e]}]);if(l=T!==a,l){let o=Q(s,a),{valuesToKeep:i}=await _inquirer2.default.prompt([{name:"valuesToKeep",message:"Keep rows matching this value",type:"checkbox",default:e,choices:o}]);s=s.filter(r=>i.includes(r[a]))}}return _chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Importing ${s.length} requests`)),s}var _bluebird = require('bluebird');var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);async function so({requestActions:n,auth:e,requestIds:s,statuses:l=[_privacytypes.RequestStatus.Compiling,_privacytypes.RequestStatus.RequestMade,_privacytypes.RequestStatus.Delayed,_privacytypes.RequestStatus.Approving,_privacytypes.RequestStatus.Secondary,_privacytypes.RequestStatus.Enriching,_privacytypes.RequestStatus.Waiting,_privacytypes.RequestStatus.SecondaryApproving],createdAtAfter:a,createdAtBefore:o,concurrency:i=100,transcendUrl:r=_chunkXPKFB4ILcjs.e}){let t=_chunkUONUI4ABcjs.Ud.call(void 0, r,e),y=new Date().getTime(),c=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),g=await _chunkUONUI4ABcjs.le.call(void 0, t,{actions:n,statuses:l,createdAtBefore:o,createdAtAfter:a,isSilent:!1,requestIds:s});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Marking "${g.length}" as silent mode.`));let m=0;c.start(g.length,0),await _bluebird.map.call(void 0, g,async f=>{await _chunkUONUI4ABcjs.ac.call(void 0, t,_chunkUONUI4ABcjs.Y,{input:{id:f.id,isSilent:!0}}),m+=1,c.update(m)},{concurrency:i}),c.stop();let p=new Date().getTime()-y;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully marked ${m} requests as silent mode in "${p/1e3}" seconds!`)),g.length}async function ft(n,e){let s=_typeutils.getValues.call(void 0, ie).filter(a=>!e.getValue("columnNames",a)),l=s.length===0?{}:await _inquirer2.default.prompt(s.map(a=>{let o=_chunk44J2TVZUcjs.h.call(void 0, a.replace("ColumnName","")),i=ne(n,o,He[a],!!Xe[a]);return{name:a,message:`Choose the column that will be used to map in the field: ${o}`,type:"list",default:i[0],choices:i}}));return await Promise.all(_typeutils.getEntries.call(void 0, l).map(([a,o])=>e.setValue(o,"columnNames",a))),l}async function dt(n,e,{state:s,columnNameMap:l}){let a=f=>s.getValue("columnNames",f)||l[f],{internalSubjects:o}=await _chunkUONUI4ABcjs.ac.call(void 0, n,_chunkUONUI4ABcjs.w);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Determining mapping of columns for request action"));let i=await ee(Q(e,a("requestType")),Object.values(_privacytypes.RequestAction),s.getValue("requestTypeToRequestAction"));await s.setValue(i,"requestTypeToRequestAction"),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Determining mapping of columns for subject"));let r=await ee(Q(e,a("subjectType")),o.map(({type:f})=>f),s.getValue("subjectTypeToSubjectName"));await s.setValue(r,"subjectTypeToSubjectName"),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Determining mapping of columns for locale"));let t=await ee(Q(e,a("locale")),Object.values(_internationalization.LanguageKey),s.getValue("languageToLocale"));await s.setValue(t,"languageToLocale"),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Determining mapping of columns for request status")),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Determining mapping of columns for request status"));let y=a("requestStatus"),c=y===T?{}:await ee(Q(e,y),[...Object.values(_privacytypes.CompletedRequestStatus),T],s.getValue("statusToRequestStatus"));await s.setValue(c,"statusToRequestStatus"),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Determining mapping of columns for country"));let g=a("country"),m=g===T?{}:await ee(Q(e,g),[...Object.values(_privacytypes.IsoCountryCode),T],s.getValue("regionToCountry"));await s.setValue(m,"regionToCountry"),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Determining mapping of columns for country sub division"));let d=a("countrySubDivision"),p=d===T?{}:await ee(Q(e,d),[...Object.values(_privacytypes.IsoCountrySubdivisionCode),T],s.getValue("regionToCountrySubDivision"));await s.setValue(p,"regionToCountrySubDivision")}var _iotstypes = require('io-ts-types');var Pr=P.record(P.string,P.array(P.intersection([P.type({value:P.string}),P.partial({name:P.string})]))),Lo= exports.x =P.intersection([P.type({email:P.string,attestedExtraIdentifiers:Pr,coreIdentifier:P.string,requestType:_typeutils.valuesOf.call(void 0, _privacytypes.RequestAction),subjectType:P.string}),P.partial({country:_typeutils.valuesOf.call(void 0, _privacytypes.IsoCountryCode),countrySubDivision:_typeutils.valuesOf.call(void 0, _privacytypes.IsoCountrySubdivisionCode),attributes:P.array(it),status:_typeutils.valuesOf.call(void 0, _privacytypes.CompletedRequestStatus),createdAt:_iotstypes.DateFromISOString,dataSiloIds:P.array(P.string),locale:_typeutils.valuesOf.call(void 0, _internationalization.LanguageKey)})]);function Dr(n,e,s){if(e===_privacytypes.IdentifierType.Email)return n.toLowerCase();if(e===_privacytypes.IdentifierType.Phone){let l=n.replace(_privacytypes.NORMALIZE_PHONE_NUMBER,"").replace(/[()]/g,"").replace(/[–]/g,"").replace(/[:]/g,"").replace(/[‭‬]/g,"").replace(/[A-Za-z]/g,"");return l?l.startsWith("+")?l:`+${s}${l}`:""}return n}function gt(n,e,{columnNameMap:s,identifierNameMap:l,attributeNameMap:a,requestAttributeKeys:o,defaultPhoneCountryCode:i="1"}){let r=t=>e.getValue("columnNames",t)||s[t];return n.map(t=>{let y={};Object.entries(l).filter(([,d])=>d!==T).forEach(([d,p])=>{let f=Object.values(_privacytypes.IdentifierType).includes(d)?d:_privacytypes.IdentifierType.Custom,h=t[p];if(h){let S=Dr(h,f,i);S&&(y[f]||(y[f]=[]),y[f].push({value:S,name:d}))}});let c=[];Object.entries(a).filter(([,d])=>d!==T).forEach(([d,p])=>{let f=t[p];if(f){let h=_optionalChain([o, 'access', _2 => _2.find, 'call', _3 => _3(S=>S.name===d), 'optionalAccess', _4 => _4.type])==="MULTI_SELECT";c.push({values:h?De(f):f,key:d})}});let g=r("requestType"),m=r("subjectType");return[t,{email:t[r("email")],attestedExtraIdentifiers:y,attributes:c,coreIdentifier:t[r("coreIdentifier")],requestType:g===me?e.getValue("requestTypeToRequestAction",Pe):e.getValue("requestTypeToRequestAction",t[g]),subjectType:m===me?e.getValue("subjectTypeToSubjectName",Pe):e.getValue("subjectTypeToSubjectName",t[m]),...r("locale")!==T&&t[r("locale")]?{locale:e.getValue("languageToLocale",t[r("locale")])}:{},...r("country")!==T&&t[r("country")]?{country:e.getValue("regionToCountry",t[r("country")])}:{},...r("countrySubDivision")!==T&&t[r("countrySubDivision")]?{countrySubDivision:e.getValue("regionToCountrySubDivision",t[r("countrySubDivision")])}:{},...r("requestStatus")!==T&&e.getValue("statusToRequestStatus",t[r("requestStatus")])!==T&&t[r("requestStatus")]?{status:e.getValue("statusToRequestStatus",t[r("requestStatus")])}:{},...r("createdAt")!==T&&t[r("createdAt")]?{createdAt:new Date(t[r("createdAt")])}:{},...r("dataSiloIds")!==T&&t[r("dataSiloIds")]?{dataSiloIds:De(t[r("dataSiloIds")])}:{}}]})}var Rt=q.type({defaultMessage:q.string,id:q.string}),Lr= exports.B =q.type({downloadKey:q.string,error:q.union([q.null,q.string]),mimetype:q.string,size:q.string,fileName:q.string,dataPoint:q.type({id:q.string,title:q.union([Rt,q.null]),description:q.union([Rt,q.null]),name:q.string,slug:q.string,encryption:q.union([_typeutils.valuesOf.call(void 0, _privacytypes.TableEncryptionType),q.null]),dataSilo:q.type({id:q.string,title:q.string,description:q.string,type:q.string,outerType:q.union([q.string,q.null])}),path:q.array(q.string)})}),$r= exports.C =q.type({nodes:q.array(Lr),totalCount:q.number,_links:q.partial({next:q.union([q.string,q.null]),previous:q.union([q.string,q.null])})});async function ht(n,{sombra:e,concurrency:s=5,limit:l=100}){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Pulling file metadata for ${n.length} requests`));let a=new Date().getTime(),o=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),i=0;o.start(n.length,0);let r=await _bluebird.map.call(void 0, n,async c=>{let g=[],m=!0,d=0;for(;m;){let p;try{let f=await e.get(`v1/data-subject-request/${c.id}/download-keys`,{searchParams:{limit:l,offset:d}}).json();p=_typeutils.decodeCodec.call(void 0, $r,f),g.push(...p.nodes),d+=l,m=!!p._links.next&&p.nodes.length===l}catch(f){throw new Error(`Received an error from server: ${_optionalChain([f, 'optionalAccess', _5 => _5.response, 'optionalAccess', _6 => _6.body])||_optionalChain([f, 'optionalAccess', _7 => _7.message])}`)}}return i+=1,o.update(i),[c,g]},{concurrency:s});o.stop();let y=new Date().getTime()-a;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully downloaded file metadata ${n.length} requests in "${y/1e3}" seconds!`)),r}async function St(n,{requestId:e,sombra:s,onFileDownloaded:l,concurrency:a=20}){await _bluebird.map.call(void 0, n,async o=>{try{await s.get("v1/files",{searchParams:{downloadKey:o.downloadKey}}).buffer().then(i=>l(o,i))}catch(i){if(_optionalChain([i, 'optionalAccess', _8 => _8.response, 'optionalAccess', _9 => _9.body, 'optionalAccess', _10 => _10.includes, 'call', _11 => _11("fileMetadata#verify")])){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to pull file for: ${o.fileName} (request:${e}) - JWT expired. This likely means that the file is no longer available. Try restarting the request from scratch in Transcend Admin Dashboard. Skipping the download of this file.`));return}throw new Error(`Received an error from server: ${_optionalChain([i, 'optionalAccess', _12 => _12.response, 'optionalAccess', _13 => _13.body])||_optionalChain([i, 'optionalAccess', _14 => _14.message])}`)}},{concurrency:a})}var _path = require('path');async function si({auth:n,folderPath:e,requestIds:s,createdAtBefore:l,sombraAuth:a,createdAtAfter:o,statuses:i=[_privacytypes.RequestStatus.Approving,_privacytypes.RequestStatus.Downloadable],concurrency:r=5,transcendUrl:t=_chunkXPKFB4ILcjs.e,approveAfterDownload:y=!1}){let c=_chunkUONUI4ABcjs.Ud.call(void 0, t,n),g=await _chunkUONUI4ABcjs.Vd.call(void 0, t,n,a);_fs.existsSync.call(void 0, e)||_fs.mkdirSync.call(void 0, e);let m=await _chunkUONUI4ABcjs.le.call(void 0, c,{actions:[_privacytypes.RequestAction.Access],createdAtBefore:l,createdAtAfter:o,statuses:i,requestIds:s}),d=await ht(m,{sombra:g,concurrency:r}),p=new Date().getTime(),f=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),h=0,S=0;f.start(m.length,0),await _bluebird.map.call(void 0, d,async([E,N])=>{let G=_path.join.call(void 0, e,E.id);_fs.existsSync.call(void 0, G)||_fs.mkdirSync.call(void 0, G),await St(N,{sombra:g,requestId:E.id,onFileDownloaded:(L,F)=>{let K=_path.join.call(void 0, G,L.fileName),O=_path.dirname.call(void 0, K);_fs.existsSync.call(void 0, O)||_fs.mkdirSync.call(void 0, O,{recursive:!0}),_fs.writeFileSync.call(void 0, K,F)}}),y&&E.status===_privacytypes.RequestStatus.Approving&&(await _chunkUONUI4ABcjs.ac.call(void 0, c,_chunkUONUI4ABcjs.W,{input:{requestId:E.id}}),S+=1),h+=1,f.update(h)},{concurrency:r}),f.stop();let b=new Date().getTime()-p;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully downloaded ${h} requests in "${b/1e3}" seconds!`)),S>0&&_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Approved ${S} requests in Transcend.`)),m.length}var xe=C.type({id:C.string,link:C.string,status:_typeutils.valuesOf.call(void 0, _privacytypes.RequestStatus),type:_typeutils.valuesOf.call(void 0, _privacytypes.RequestAction),subjectType:C.string,email:C.union([C.null,C.string]),coreIdentifier:C.string,isSilent:C.boolean,isTest:C.boolean,country:C.union([C.null,_typeutils.valuesOf.call(void 0, _privacytypes.IsoCountryCode)]),countrySubDivision:C.union([C.null,_typeutils.valuesOf.call(void 0, _privacytypes.IsoCountrySubdivisionCode)]),attributeValues:C.array(C.type({attributeKey:C.type({name:C.string}),name:C.string}))});async function wt(n,e,{details:s="",isTest:l=!1,emailIsVerified:a=!0,skipSendingReceipt:o=!1,isSilent:i=!0,additionalAttributes:r=[]}={}){let t=[...r];(e.attributes||[]).forEach(g=>{let m=t.find(d=>d.key===g.key);m?(m.values.push(...g.values),m.values=_chunk44J2TVZUcjs.j.call(void 0, m.values)):t.push(g)});let y;try{y=await n.post("v1/data-subject-request",{json:{type:e.requestType,subject:{coreIdentifier:e.coreIdentifier,email:e.email,emailIsVerified:a,attestedExtraIdentifiers:e.attestedExtraIdentifiers},subjectType:e.subjectType,isSilent:i,isTest:l,skipSendingReceipt:o,...e.locale?{locale:e.locale}:{},details:s,attributes:t,...e.country||e.countrySubDivision?{region:{...e.country?{country:e.country}:e.countrySubDivision?{country:e.countrySubDivision.split("-")[0]}:{},...e.countrySubDivision?{countrySubDivision:e.countrySubDivision}:{}}}:{},...e.createdAt?{createdAt:e.createdAt}:{},...e.dataSiloIds?{dataSiloIds:e.dataSiloIds}:{},...e.status?{completedRequestStatus:e.status}:{}}}).json()}catch(g){throw new Error(`Received an error from server: ${_optionalChain([g, 'optionalAccess', _15 => _15.response, 'optionalAccess', _16 => _16.body])||_optionalChain([g, 'optionalAccess', _17 => _17.message])}`)}let{request:c}=_typeutils.decodeCodec.call(void 0, C.type({request:xe}),y);return c}async function Ri({requestActions:n,requestOrigins:e,auth:s,silentModeBefore:l,createdAtAfter:a,createdAtBefore:o,concurrency:i=50,transcendUrl:r=_chunkXPKFB4ILcjs.e}){let t=_chunkUONUI4ABcjs.Ud.call(void 0, r,s),y=new Date().getTime(),c=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),g=await _chunkUONUI4ABcjs.le.call(void 0, t,{actions:n,statuses:[_privacytypes.RequestStatus.Approving],createdAtAfter:a,origins:e,createdAtBefore:o});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Approving "${g.length}" requests.`));let m=0,d=0;c.start(g.length,0),await _bluebird.map.call(void 0, g,async h=>{l&&new Date(l)>new Date(h.createdAt)&&await _chunkUONUI4ABcjs.ac.call(void 0, t,_chunkUONUI4ABcjs.Y,{input:{id:h.id,isSilent:!0}});try{await _chunkUONUI4ABcjs.ac.call(void 0, t,_chunkUONUI4ABcjs.W,{input:{requestId:h.id}})}catch(S){S.message.includes("Request must be in an approving state,")&&(d+=1)}m+=1,c.update(m)},{concurrency:i}),c.stop();let f=new Date().getTime()-y;return d>0&&_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`${d} requests were skipped.`)),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully approved ${m} requests in "${f/1e3}" seconds!`)),g.length}async function Pi({requestActions:n=Object.values(_privacytypes.RequestAction),auth:e,requestIds:s,createdAtBefore:l,days:a=45,daysLeft:o=10,createdAtAfter:i,emailTemplate:r="Additional Time Needed",concurrency:t=100,transcendUrl:y=_chunkXPKFB4ILcjs.e}){let c=_chunkUONUI4ABcjs.Ud.call(void 0, y,e),g=new Date().getTime(),m=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),p=(await _chunkUONUI4ABcjs.fd.call(void 0, c,r)).find(b=>b.title===r);if(!p)throw new Error(`Failed to find a template with title: "${r}"`);let f=await _chunkUONUI4ABcjs.le.call(void 0, c,{actions:n,createdAtBefore:l,createdAtAfter:i,isSilent:!1,isClosed:!1,requestIds:s});f=f.filter(b=>typeof b.daysRemaining=="number"&&b.daysRemaining<o),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Notifying "${f.length}" that more time is needed.`));let h=0;m.start(f.length,0),await _bluebird.map.call(void 0, f,async b=>{await _chunkUONUI4ABcjs.ac.call(void 0, c,_chunkUONUI4ABcjs.Z,{input:{requestId:b.id,template:p.template.defaultMessage,subject:p.subject.defaultMessage,additionalTime:a}}),h+=1,m.update(h)},{concurrency:t}),m.stop();let v=new Date().getTime()-g;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully marked ${h} requests as silent mode in "${v/1e3}" seconds!`)),f.length}async function Dt(n,e,s){let{initializer:l}=await _chunkUONUI4ABcjs.ac.call(void 0, n,_chunkUONUI4ABcjs.o),a=l.identifiers.filter(({name:i})=>!s.getValue("identifierNames",i)&&!Se.includes(i)),o=a.length===0?{}:await _inquirer2.default.prompt(a.map(({name:i})=>{let r=ne(e,i,!1);return{name:i,message:`Choose the column that will be used to map in the identifier: ${i}`,type:"list",default:r[0],choices:r}}));return await Promise.all(Object.entries(o).map(([i,r])=>s.setValue(r,"identifierNames",i))),{...s.getValue("identifierNames"),...o}}async function Gi({requestActions:n,cancellationTitle:e,auth:s,requestIds:l,silentModeBefore:a,createdAtBefore:o,createdAtAfter:i,statuses:r=[_privacytypes.RequestStatus.Compiling,_privacytypes.RequestStatus.RequestMade,_privacytypes.RequestStatus.Delayed,_privacytypes.RequestStatus.Approving,_privacytypes.RequestStatus.Secondary,_privacytypes.RequestStatus.Enriching,_privacytypes.RequestStatus.Waiting,_privacytypes.RequestStatus.SecondaryApproving],concurrency:t=50,transcendUrl:y=_chunkXPKFB4ILcjs.e}){let c=_chunkUONUI4ABcjs.Ud.call(void 0, y,s),g=new Date().getTime(),m=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),d;if(e){let b=(await _chunkUONUI4ABcjs.fd.call(void 0, c,e)).find(E=>E.title===e);if(!b)throw new Error(`Failed to find a template with title: "${e}"`);d=b}let p=await _chunkUONUI4ABcjs.le.call(void 0, c,{actions:n,createdAtBefore:o,createdAtAfter:i,statuses:r,requestIds:l});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Canceling "${p.length}" requests${d?` Using template: ${d.title}`:""}.`));let f=0;m.start(p.length,0),await _bluebird.map.call(void 0, p,async v=>{a&&new Date(a)>new Date(v.createdAt)&&await _chunkUONUI4ABcjs.ac.call(void 0, c,_chunkUONUI4ABcjs.Y,{input:{id:v.id,isSilent:!0}}),await _chunkUONUI4ABcjs.ac.call(void 0, c,_chunkUONUI4ABcjs.X,{input:{requestId:v.id,...d?{subject:`Re: ${d.subject.defaultMessage}`,template:d.template.defaultMessage}:{}}}),f+=1,m.update(f)},{concurrency:t}),m.stop();let S=new Date().getTime()-g;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully canceled ${f} requests in "${S/1e3}" seconds!`)),p.length}async function Nt(n,e,s,l){let a=l.filter(({name:i})=>!s.getValue("attributeNames",i)),o=a.length===0?{}:await _inquirer2.default.prompt(a.map(({name:i})=>{let r=ne(e,i,!1);return{name:i,message:`Choose the column that will be used to map in the attribute: ${i}`,type:"list",default:r[0],choices:r}}));return await Promise.all(Object.entries(o).map(([i,r])=>s.setValue(r,"attributeNames",i))),{...s.getValue("attributeNames"),...o}}var xt=/{\\"message\\":\\"(.+?)\\",/;function Ce(n){return xt.test(n)?xt.exec(n)[1]:null}var _persistedstate = require('@transcend-io/persisted-state');async function Rn({cacheFilepath:n,requestReceiptFolder:e,file:s,auth:l,sombraAuth:a,concurrency:o=100,defaultPhoneCountryCode:i="1",transcendUrl:r=_chunkXPKFB4ILcjs.e,attributes:t=[],emailIsVerified:y=!0,skipFilterStep:c=!1,skipSendingReceipt:g=!0,isTest:m=!1,isSilent:d=!0,debug:p=!1,dryRun:f=!1}){let h=new Date().getTime(),S=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),v=nt(t),b=new (0, _persistedstate.PersistedState)(n,et,{columnNames:{},requestTypeToRequestAction:{},subjectTypeToSubjectName:{},languageToLocale:{},statusToRequestStatus:{},identifierNames:{},attributeNames:{},regionToCountrySubDivision:{},regionToCountry:{}}),E=_path.join.call(void 0, e,`tr-request-upload-${new Date().toISOString()}-${s.split("/").pop()}`.replace(".csv",".json")),N=new (0, _persistedstate.PersistedState)(E,tt,{successfulRequests:[],duplicateRequests:[],failingRequests:[]}),G=await _chunkUONUI4ABcjs.Vd.call(void 0, r,l,a),L=ut(s,fe.record(fe.string,fe.string)),F=_chunk44J2TVZUcjs.j.call(void 0, L.map(B=>Object.keys(B)).flat());if(L.length===0)throw new Error("No Requests found in list! Ensure the first row of the CSV is a header and the rest are requests.");if(p){let B=L[0];_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`First request: ${JSON.stringify(B,null,2)}`))}let K=c?L:await ct(L),O=_chunkUONUI4ABcjs.Ud.call(void 0, r,l),x=await _chunkUONUI4ABcjs.ae.call(void 0, O),M=await ft(F,b),z=await Dt(O,F,b),_=await Nt(O,F,b,x);await dt(O,K,{state:b,columnNameMap:M});let $=gt(K,b,{defaultPhoneCountryCode:i,columnNameMap:M,identifierNameMap:z,attributeNameMap:_,requestAttributeKeys:x});p||S.start($.length,0);let H=0;await _bluebird.map.call(void 0, $,async([B,k],U)=>{let Fe=p?`email:${k.email} | coreIdentifier:${k.coreIdentifier}`:`row:${U.toString()}`;if(p&&_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`[${U+1}/${$.length}] Importing: ${JSON.stringify(k,null,2)}`)),f){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Bailing out on dry run because dryRun is set"));return}try{let X=await wt(G,k,{details:`Uploaded by Transcend Cli: "tr-request-upload" : ${JSON.stringify(B,null,2)}`,isTest:m,emailIsVerified:y,skipSendingReceipt:g,isSilent:d,additionalAttributes:v});p&&(_chunkZUNVPK23cjs.a.info(_colors2.default.green(`[${U+1}/${$.length}] Successfully submitted the test data subject request: "${Fe}"`)),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`[${U+1}/${$.length}] View it at: "${X.link}"`)));let se=N.getValue("successfulRequests");se.push({id:X.id,link:X.link,rowIndex:U,coreIdentifier:X.coreIdentifier,attemptedAt:new Date().toISOString()}),await N.setValue(se,"successfulRequests")}catch(X){let se=`${X.message} - ${JSON.stringify(_optionalChain([X, 'access', _18 => _18.response, 'optionalAccess', _19 => _19.body]),null,2)}`,Ie=Ce(se);if(Ie==="Client error: You have already made this request."){p&&_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`[${U+1}/${$.length}] Skipping request as it is a duplicate`));let ue=N.getValue("duplicateRequests");ue.push({coreIdentifier:k.coreIdentifier,rowIndex:U,attemptedAt:new Date().toISOString()}),await N.setValue(ue,"duplicateRequests")}else{let ue=N.getValue("failingRequests");ue.push({...k,rowIndex:U,error:Ie||se,attemptedAt:new Date().toISOString()}),await N.setValue(ue,"failingRequests"),p&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red(Ie||se)),_chunkZUNVPK23cjs.a.error(_colors2.default.red(`[${U+1}/${$.length}] Failed to submit request for: "${Fe}"`)))}}H+=1,p||S.update(H)},{concurrency:o}),S.stop();let ae=new Date().getTime()-h;_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Completed upload in "${ae/1e3}" seconds.`)),N.getValue("duplicateRequests").length>0&&_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Encountered "${N.getValue("duplicateRequests").length}" duplicate requests. See "${E}" to review the core identifiers for these requests.`)),N.getValue("failingRequests").length>0&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Encountered "${N.getValue("failingRequests").length}" errors. See "${E}" to review the error messages and inputs.`)),process.exit(1))}async function jt(n,e,{sendEmailReceipt:s=!1,skipWaitingPeriod:l=!1,emailIsVerified:a=!0,requestIdentifiers:o=[]}={}){let i=await n.post("v1/data-subject-request",{json:{type:e.type,subject:{coreIdentifier:e.coreIdentifier,email:e.email,emailIsVerified:a,...o.length>0?{attestedExtraIdentifiers:_typeutils.apply.call(void 0, _chunk44J2TVZUcjs.d.call(void 0, o.filter(t=>!(t.name==="email"&&t.value===e.email)&&!Se.includes(t.name)).map(t=>({...t,type:Object.values(_privacytypes.IdentifierType).includes(t.name)?t.name:_privacytypes.IdentifierType.Custom})),"type"),(t,y)=>t.map(({name:c,value:g})=>({...y===_privacytypes.IdentifierType.Custom?{name:c}:{},value:g})))}:{}},requestId:e.id,subjectType:e.subjectType,isSilent:e.isSilent,isTest:e.isTest,locale:e.locale,skipWaitingPeriod:l,createdAt:e.createdAt,details:`Restarted by Transcend cli: "tr-request-restart" - ${e.details}`,skipSendingReceipt:!s}}).json(),{request:r}=_typeutils.decodeCodec.call(void 0, Ot.type({request:xe}),i);return r}var ns=V.intersection([be,V.type({error:V.string})]),as=V.type({restartedRequests:V.array(be),failingRequests:V.array(ns)});async function _n({requestReceiptFolder:n,auth:e,sombraAuth:s,requestActions:l,requestStatuses:a,createdAtBefore:o,createdAtAfter:i,transcendUrl:r=_chunkXPKFB4ILcjs.e,requestIds:t=[],createdAt:y=new Date,silentModeBefore:c,sendEmailReceipt:g=!1,emailIsVerified:m=!0,copyIdentifiers:d=!1,skipWaitingPeriod:p=!1,concurrency:f=20}){let h=new Date().getTime(),S=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),v=_path.join.call(void 0, n,`tr-request-restart-${new Date().toISOString()}`),b=new (0, _persistedstate.PersistedState)(v,as,{restartedRequests:[],failingRequests:[]}),E=await _chunkUONUI4ABcjs.Vd.call(void 0, r,e,s),N=_chunkUONUI4ABcjs.Ud.call(void 0, r,e),L=(await _chunkUONUI4ABcjs.le.call(void 0, N,{actions:l,statuses:a,createdAtBefore:o,createdAtAfter:i})).filter(x=>new Date(x.createdAt)<y);if(_chunkZUNVPK23cjs.a.info(`Found ${L.length} requests to process`),d&&_chunkZUNVPK23cjs.a.info("copyIdentifiers detected - All Identifiers will be copied."),g&&_chunkZUNVPK23cjs.a.info("sendEmailReceipt detected - Email receipts will be sent."),p&&_chunkZUNVPK23cjs.a.info("skipWaitingPeriod detected - Waiting period will be skipped."),t.length>0&&t.length!==L.length){let x=_chunk44J2TVZUcjs.c.call(void 0, t,L.map(({id:M})=>M));x.length>0&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to find the following requests by ID: ${x.join(",")}.`)),process.exit(1))}let F=0;S.start(L.length,0),await _bluebird.map.call(void 0, L,async(x,M)=>{try{let z=d?await _chunkUONUI4ABcjs.je.call(void 0, N,E,{requestId:x.id}):[],_=await jt(E,{...x,isSilent:c&&new Date(x.createdAt)<c?!0:x.isSilent},{requestIdentifiers:z,skipWaitingPeriod:p,sendEmailReceipt:g,emailIsVerified:m}),$=b.getValue("restartedRequests");$.push({id:_.id,link:_.link,rowIndex:M,coreIdentifier:_.coreIdentifier,attemptedAt:new Date().toISOString()}),await b.setValue($,"restartedRequests")}catch(z){let _=`${z.message} - ${JSON.stringify(_optionalChain([z, 'access', _20 => _20.response, 'optionalAccess', _21 => _21.body]),null,2)}`,$=Ce(_),H=b.getValue("failingRequests");H.push({id:x.id,link:x.link,rowIndex:M,coreIdentifier:x.coreIdentifier,attemptedAt:new Date().toISOString(),error:$||_}),await b.setValue(H,"failingRequests")}F+=1,S.update(F)},{concurrency:f}),S.stop();let O=new Date().getTime()-h;_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Completed restarting of requests in "${O/1e3}" seconds.`)),b.getValue("failingRequests").length>0&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Encountered "${b.getValue("failingRequests").length}" errors. See "${v}" to review the error messages and inputs.`)),process.exit(1))}async function zn({enricherIds:n,auth:e,concurrency:s=100,transcendUrl:l=_chunkXPKFB4ILcjs.e}){let a=_chunkUONUI4ABcjs.Ud.call(void 0, l,e),o=new Date().getTime(),i=await _chunkUONUI4ABcjs.le.call(void 0, a,{statuses:[_privacytypes.RequestStatus.Enriching]});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Processing enricher: "${n.join(",")}" fetched "${i.length}" in enriching status.`));let r=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),t=0;r.start(i.length,0);let y=0;await _bluebird.map.call(void 0, i,async m=>{let p=(await _chunkUONUI4ABcjs.ge.call(void 0, a,{requestId:m.id})).filter(f=>n.includes(f.enricher.id)&&![_privacytypes.RequestEnricherStatus.Resolved,_privacytypes.RequestEnricherStatus.Skipped].includes(f.status));p.length>0&&await _bluebird.mapSeries.call(void 0, p,async f=>{try{await _chunkUONUI4ABcjs.ac.call(void 0, a,_chunkUONUI4ABcjs.ca,{requestEnricherId:f.id}),y+=1}catch(h){if(!h.message.includes("Client error: Cannot skip Request enricher because it has already completed"))throw h}}),t+=1,r.update(t)},{concurrency:s}),r.stop();let g=new Date().getTime()-o;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully skipped "${y}" for "${i.length}" requests in "${g/1e3}" seconds!`)),i.length}async function oa({auth:n,requestActions:e=[],createdAtBefore:s,createdAtAfter:l,transcendUrl:a=_chunkXPKFB4ILcjs.e,requestEnricherStatuses:o=Object.values(_privacytypes.RequestEnricherStatus),requestIds:i=[],enricherId:r,concurrency:t=20}){let y=new Date().getTime(),c=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),g=_chunkUONUI4ABcjs.Ud.call(void 0, a,n);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Fetching requests to restart..."));let m=await _chunkUONUI4ABcjs.le.call(void 0, g,{actions:e,statuses:[_privacytypes.RequestStatus.Enriching],createdAtBefore:s,createdAtAfter:l,requestIds:i}),d=0;if(i.length>0&&i.length!==m.length){let S=_chunk44J2TVZUcjs.c.call(void 0, i,m.map(({id:v})=>v));S.length>0&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to find the following requests by ID: ${S.join(",")}.`)),process.exit(1))}let p=0;c.start(m.length,0),await _bluebird.map.call(void 0, m,async S=>{let b=(await _chunkUONUI4ABcjs.ge.call(void 0, g,{requestId:S.id})).filter(E=>E.enricher.id===r&&o.includes(E.status));await _bluebird.map.call(void 0, b,async E=>{await _chunkUONUI4ABcjs.He.call(void 0, g,E.id),d+=1}),p+=1,c.update(p)},{concurrency:t}),c.stop();let h=new Date().getTime()-y;_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Completed restarting of ${m.length} requests and ${d} enrichers in "${h/1e3}" seconds.`))}async function da({requestActions:n,dataSiloId:e,auth:s,concurrency:l=20,transcendUrl:a=_chunkXPKFB4ILcjs.e}){let o=_chunkUONUI4ABcjs.Ud.call(void 0, a,s),i=new Date().getTime(),r=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),t=await _chunkUONUI4ABcjs.le.call(void 0, o,{actions:n,statuses:[_privacytypes.RequestStatus.Compiling,_privacytypes.RequestStatus.Approving]});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Retrying requests for Data Silo: "${e}", restarting "${t.length}" requests.`));let y=0,c=0;r.start(t.length,0),await _bluebird.map.call(void 0, t,async d=>{try{let p=await _chunkUONUI4ABcjs.re.call(void 0, o,{requestId:d.id,dataSiloId:e});await _chunkUONUI4ABcjs.ac.call(void 0, o,_chunkUONUI4ABcjs.va,{requestDataSiloId:p.id})}catch(p){if(!p.message.includes("Failed to find RequestDataSilo"))throw p;c+=1}y+=1,r.update(y)},{concurrency:l}),r.stop();let m=new Date().getTime()-i;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully notified Transcend in "${m/1e3}" seconds for ${y} requests, ${c} requests were skipped because data silo was not attached to the request!`)),t.length}async function wa({auth:n,sombraAuth:e,actions:s=[],statuses:l=[],identifierSearch:a,pageLimit:o=100,transcendUrl:i=_chunkXPKFB4ILcjs.e,createdAtBefore:r,createdAtAfter:t,isTest:y}){let c=_chunkUONUI4ABcjs.Ud.call(void 0, i,n),g=await _chunkUONUI4ABcjs.Vd.call(void 0, i,n,e),m="";r&&(m+=` before ${r.toISOString()}`),t&&(m+=`${m?", and":""} after ${t.toISOString()}`),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`${s.length>0?`Pulling requests of type "${s.join('" , "')}"`:"Pulling all requests"}${m}`));let d=await _chunkUONUI4ABcjs.le.call(void 0, c,{actions:s,text:a,statuses:l,createdAtBefore:r,createdAtAfter:t,isTest:y}),p=await _bluebird.map.call(void 0, d,async h=>{let S=await _chunkUONUI4ABcjs.je.call(void 0, c,g,{requestId:h.id});return{...h,requestIdentifiers:S}},{concurrency:o});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Pulled ${p.length} requests`));let f=p.map(({attributeValues:h,requestIdentifiers:S,id:v,email:b,type:E,status:N,subjectType:G,details:L,createdAt:F,country:K,locale:O,origin:x,countrySubDivision:M,isSilent:z,isTest:_,coreIdentifier:$,...H})=>({"Request ID":v,"Created At":F,Email:b,"Core Identifier":$,"Request Type":E,"Data Subject Type":G,Status:N,Country:K,"Country Sub Division":M,Details:L,Origin:x,"Silent Mode":z,"Is Test Request":_,Language:O,...H,...Object.entries(_chunk44J2TVZUcjs.d.call(void 0, h,"attributeKey.name")).reduce((de,[ae,B])=>Object.assign(de,{[ae]:B.map(({name:k})=>k).join(",")}),{}),...Object.entries(_chunk44J2TVZUcjs.d.call(void 0, S,"name")).reduce((de,[ae,B])=>Object.assign(de,{[ae]:B.map(({value:k})=>k).join(",")}),{})}));return{requestsWithRequestIdentifiers:p,requestsFormattedForCsv:f}}async function La({dataSiloId:n,auth:e,concurrency:s=100,status:l="SKIPPED",transcendUrl:a=_chunkXPKFB4ILcjs.e,requestStatuses:o=[_privacytypes.RequestStatus.Compiling,_privacytypes.RequestStatus.Secondary]}){let i=_chunkUONUI4ABcjs.Ud.call(void 0, a,e),r=new Date().getTime(),t=await _chunkUONUI4ABcjs.qe.call(void 0, i,{dataSiloId:n,requestStatuses:o});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Processing data silo: "${n}" marking "${t.length}" requests as skipped.`));let y=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),c=0;y.start(t.length,0),await _bluebird.map.call(void 0, t,async d=>{try{await _chunkUONUI4ABcjs.ac.call(void 0, i,_chunkUONUI4ABcjs.ua,{requestDataSiloId:d.id,status:l})}catch(p){if(!p.message.includes("Client error: Request must be active:"))throw p}c+=1,y.update(c)},{concurrency:s}),y.stop();let m=new Date().getTime()-r;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully skipped "${t.length}" requests in "${m/1e3}" seconds!`)),t.length}async function Ua({requestActions:n,identifierNames:e,auth:s,concurrency:l=20,transcendUrl:a=_chunkXPKFB4ILcjs.e}){let o=_chunkUONUI4ABcjs.Ud.call(void 0, a,s),i=new Date().getTime(),r=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),t=await _chunkUONUI4ABcjs.le.call(void 0, o,{actions:n,statuses:[_privacytypes.RequestStatus.Enriching]});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Fetched requests in preflight/enriching state."));let y=0,c=0;r.start(t.length,0),await _bluebird.map.call(void 0, t,async d=>{let f=(await _chunkUONUI4ABcjs.he.call(void 0, o,{requestId:d.id})).filter(({isVerifiedAtLeastOnce:h,name:S})=>h===!1&&e.includes(S)).map(({id:h})=>h);f.length>0&&(await _chunkUONUI4ABcjs.ac.call(void 0, o,_chunkUONUI4ABcjs.Aa,{input:{requestId:d.id,requestIdentifierIds:f}}),c+=f.length),y+=1,r.update(y)},{concurrency:l}),r.stop();let m=new Date().getTime()-i;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully cleared out unverified identifiers "${m/1e3}" seconds for ${y} requests, ${c} identifiers were cleared out!`)),t.length}exports.a = T; exports.b = me; exports.c = Pe; exports.d = Se; exports.e = ie; exports.f = He; exports.g = Xe; exports.h = et; exports.i = be; exports.j = tt; exports.k = Te; exports.l = ne; exports.m = ee; exports.n = De; exports.o = it; exports.p = nt; exports.q = ut; exports.r = Q; exports.s = ct; exports.t = so; exports.u = ft; exports.v = dt; exports.w = Pr; exports.x = Lo; exports.y = Dr; exports.z = gt; exports.A = Rt; exports.B = Lr; exports.C = $r; exports.D = ht; exports.E = St; exports.F = si; exports.G = xe; exports.H = wt; exports.I = Ri; exports.J = Pi; exports.K = Dt; exports.L = Gi; exports.M = Nt; exports.N = Ce; exports.O = Rn; exports.P = jt; exports.Q = _n; exports.R = zn; exports.S = oa; exports.T = da; exports.U = wa; exports.V = La; exports.W = Ua;
2
+ //# sourceMappingURL=chunk-7UL54E7X.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-MBB6OD4E.cjs","../src/lib/requests/constants.ts","../src/lib/requests/fuzzyMatchColumns.ts","../src/lib/requests/mapEnumValues.ts"],"names":["NONE","BULK_APPLY","BLANK","IDENTIFIER_BLOCK_LIST","ColumnName","IS_REQUIRED","CAN_APPLY_IN_BULK","CachedFileState","applyEnum","valuesOf","IsoCountryCode","IsoCountrySubdivisionCode","CompletedRequestStatus","SuccessfulRequest","CachedRequestState","fuzzySearch","word1","word2","fuzzysearch","fuzzyMatchColumns","allColumnNames","fuzzyMapName","isRequired","canApplyAll","matchingColumnNames","x","inquirer","mapEnumValues","csvInputs","expectedOutputs","cache","autoCompletePrompt","inputs","item","value","result"],"mappings":"AAAA,u/BAAuO,wDAAyC,wDAAyC,wDAAiE,qDCAtV,0EACR,2DAMrB,yYACY,IAENA,CAAAA,CAAO,QAAA,CACPC,EAAAA,aAAa,2BAAA,CACbC,EAAAA,aAAQ,SAAA,CAGRC,EAAAA,aAAwB,CAAC,OAAA,CAAS,gBAAgB,CAAA,CAKnDC,EAAAA,aAAAA,CAAAA,CAAAA,EA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AA,CAAKK,CAAAA,EAASA,CAAAA,EAAQ,SAAS,CAAA,CAC/B,MAAA,CAAQC,CAAAA,EAAU,CAACJ,CAAAA,CAAMI,CAAK,CAAC,CAAA,CAClC,EAAA,CAAIF,CAAAA,CAAO,MAAA,GAAW,CAAA,CACpB,OAAOF,CAAAA,CAET,IAAMK,CAAAA,CAAS,MAAMT,kBAAAA,CAAS,MAAA,CAC5BM,CAAAA,CAAO,GAAA,CAAKE,CAAAA,EAAAA,CAAW,CACrB,IAAA,CAAMA,CAAAA,CACN,OAAA,CAAS,CAAA,cAAA,EAAiBA,CAAK,CAAA,CAAA","file":"/home/runner/work/cli/cli/dist/chunk-MBB6OD4E.cjs","sourcesContent":[null,"import { applyEnum, valuesOf } from '@transcend-io/type-utils';\nimport { LanguageKey } from '@transcend-io/internationalization';\nimport {\n CompletedRequestStatus,\n RequestAction,\n IsoCountryCode,\n IsoCountrySubdivisionCode,\n} from '@transcend-io/privacy-types';\nimport * as t from 'io-ts';\n\nexport const NONE = '[NONE]' as const;\nexport const BULK_APPLY = '[APPLY VALUE TO ALL ROWS]' as const;\nexport const BLANK = '<blank>' as const;\n\n/** These are uploaded at the top level of the request */\nexport const IDENTIFIER_BLOCK_LIST = ['email', 'coreIdentifier'];\n\n/**\n * Column names to map\n */\nexport enum ColumnName {\n /** The title of the email column */\n Email = 'email',\n /** The title of the core identifier column */\n CoreIdentifier = 'coreIdentifier',\n /** The title of the requestType column */\n RequestType = 'requestType',\n /** The title of the subjectType column */\n SubjectType = 'subjectType',\n /** The title of the locale column */\n Locale = 'locale',\n /** The country */\n Country = 'country',\n /** The country sub division */\n CountrySubDivision = 'countrySubDivision',\n /** The title of the requestStatus column */\n RequestStatus = 'requestStatus',\n /** The title of the createdAt column */\n CreatedAt = 'createdAt',\n /** The title of the dataSiloIds column */\n DataSiloIds = 'dataSiloIds',\n}\n\n/** These parameters are required in the Transcend DSR API */\nexport const IS_REQUIRED: { [k in ColumnName]: boolean } = {\n [ColumnName.Email]: false,\n [ColumnName.CoreIdentifier]: true,\n [ColumnName.RequestType]: true,\n [ColumnName.SubjectType]: true,\n [ColumnName.RequestStatus]: false,\n [ColumnName.CreatedAt]: false,\n [ColumnName.DataSiloIds]: false,\n [ColumnName.Locale]: false,\n [ColumnName.Country]: false,\n [ColumnName.CountrySubDivision]: false,\n};\n\n/** These parameters can be specified for the entire CSV set if needed */\nexport const CAN_APPLY_IN_BULK: { [k in ColumnName]?: boolean } = {\n [ColumnName.RequestType]: true,\n [ColumnName.SubjectType]: true,\n};\n\n// Cache state\nexport const CachedFileState = t.type({\n /** Mapping between the default request input column names and the CSV column name for that input */\n columnNames: t.partial(applyEnum(ColumnName, () => t.string)),\n /** Mapping between the identifier names and the CSV column name for that input */\n identifierNames: t.record(t.string, t.string),\n /** Mapping between the request attribute inputs and the CSV column name for that input */\n attributeNames: t.record(t.string, t.string),\n /** Mapping between CSV request type and Transcend Request Action */\n requestTypeToRequestAction: t.record(t.string, valuesOf(RequestAction)),\n /** Mapping between CSV data subject type and the name of the data subject in Transcend */\n subjectTypeToSubjectName: t.record(t.string, t.string),\n /** Mapping between language imported and Transcend locale code */\n languageToLocale: t.record(t.string, valuesOf(LanguageKey)),\n /** Mapping between region and country code */\n regionToCountry: t.record(\n t.string,\n valuesOf({ ...IsoCountryCode, [NONE]: NONE }),\n ),\n /** Mapping between region and country sub division code */\n regionToCountrySubDivision: t.record(\n t.string,\n valuesOf({ ...IsoCountrySubdivisionCode, [NONE]: NONE }),\n ),\n /** Mapping between request status in import to Transcend request status */\n statusToRequestStatus: t.record(\n t.string,\n valuesOf({ ...CompletedRequestStatus, [NONE]: NONE }),\n ),\n});\n\n/** Type override */\nexport type CachedFileState = t.TypeOf<typeof CachedFileState>;\n\n/**\n * Successfully processed request\n */\nexport const SuccessfulRequest = t.type({\n id: t.string,\n link: t.string,\n rowIndex: t.number,\n coreIdentifier: t.string,\n attemptedAt: t.string,\n});\n\n/** Type override */\nexport type SuccessfulRequest = t.TypeOf<typeof SuccessfulRequest>;\n\n// Cache state\nexport const CachedRequestState = t.type({\n /** Set of privacy requests that failed to upload */\n failingRequests: t.array(t.record(t.string, t.any)),\n /** Successfully uploaded requests */\n successfulRequests: t.array(SuccessfulRequest),\n /** Duplicate requests */\n duplicateRequests: t.array(\n t.type({\n rowIndex: t.number,\n coreIdentifier: t.string,\n attemptedAt: t.string,\n }),\n ),\n});\n\n/** Type override */\nexport type CachedRequestState = t.TypeOf<typeof CachedRequestState>;\n","import inquirer from 'inquirer';\nimport { NONE, BULK_APPLY } from './constants';\n\nimport fuzzysearch from 'fuzzysearch';\n\n/**\n * Check if word1 and word2 are a fuzzy match of each other.\n * Returns true if word1 is fuzzy match of word2 or vice versa.\n *\n * @param word1 - First word\n * @param word2 - Second word\n * @returns True if words are fuzzy match\n */\nexport function fuzzySearch(word1: string, word2: string): boolean {\n return (\n fuzzysearch(word1.toLowerCase(), word2.toLowerCase()) ||\n fuzzysearch(word2.toLowerCase(), word1.toLowerCase())\n );\n}\n\n/**\n * Fuzzy match column names for a particular field\n *\n * @param allColumnNames - List of all column names\n * @param fuzzyMapName - The name of field being mapped to\n * @param isRequired - When true, don't include \"NONE\" as an option\n * @param canApplyAll - When true, include an option to specify the value in bulk\n * @returns The list of suggestions for inquirer\n */\nexport function fuzzyMatchColumns(\n allColumnNames: string[],\n fuzzyMapName: string,\n isRequired: boolean,\n canApplyAll?: boolean,\n): (string | InstanceType<typeof inquirer.Separator>)[] {\n const matchingColumnNames = allColumnNames.filter((x) =>\n fuzzySearch(fuzzyMapName.toLowerCase(), x.toLowerCase()),\n );\n return [\n ...matchingColumnNames,\n new inquirer.Separator(),\n ...(isRequired ? [] : [NONE]),\n ...(canApplyAll ? [BULK_APPLY] : []),\n ...allColumnNames.filter((x) => !matchingColumnNames.includes(x)),\n ];\n}\n","import inquirer from 'inquirer';\nimport autoCompletePrompt from 'inquirer-autocomplete-prompt';\nimport { apply, ObjByString } from '@transcend-io/type-utils';\nimport { fuzzySearch } from './fuzzyMatchColumns';\n\n/**\n * Map a set of inputs to a set of outputs\n *\n * @param csvInputs - Input list\n * @param expectedOutputs - Output list\n * @param cache - Cache\n * @returns Mapping from row to enum value\n */\nexport async function mapEnumValues<TValue extends string>(\n csvInputs: string[],\n expectedOutputs: TValue[],\n cache: { [k in string]: TValue },\n): Promise<{ [k in string]: TValue }> {\n inquirer.registerPrompt('autocomplete', autoCompletePrompt);\n\n const inputs = csvInputs\n .map((item) => item || '<blank>')\n .filter((value) => !cache[value]);\n if (inputs.length === 0) {\n return cache;\n }\n const result = await inquirer.prompt<{ [k in string]: TValue }>(\n inputs.map((value) => ({\n name: value,\n message: `Map value of: ${value}`,\n type: 'autocomplete',\n default: expectedOutputs.find((x) => fuzzySearch(value, x)),\n source: (answersSoFar: ObjByString, input: string) =>\n !input\n ? expectedOutputs\n : expectedOutputs.filter(\n (x) => typeof x === 'string' && fuzzySearch(input, x),\n ),\n })),\n );\n return {\n ...cache,\n ...apply(result, (r) =>\n typeof r === 'string' ? (r as TValue) : (Object.values(r)[0] as TValue),\n ),\n };\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-7UL54E7X.cjs","../src/lib/requests/constants.ts","../src/lib/requests/fuzzyMatchColumns.ts","../src/lib/requests/mapEnumValues.ts"],"names":["NONE","BULK_APPLY","BLANK","IDENTIFIER_BLOCK_LIST","ColumnName","IS_REQUIRED","CAN_APPLY_IN_BULK","CachedFileState","applyEnum","valuesOf","IsoCountryCode","IsoCountrySubdivisionCode","CompletedRequestStatus","SuccessfulRequest","CachedRequestState","fuzzySearch","word1","word2","fuzzysearch","fuzzyMatchColumns","allColumnNames","fuzzyMapName","isRequired","canApplyAll","matchingColumnNames","x","inquirer","mapEnumValues","csvInputs","expectedOutputs","cache","autoCompletePrompt","inputs","item","value","result"],"mappings":"AAAA,u/BAA6N,wDAAyC,wDAAyC,wDAAiE,qDCA5U,0EACR,2DAMrB,yYACY,IAENA,CAAAA,CAAO,QAAA,CACPC,EA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AC,CAAAA,CACAC,CAAAA,CACoC,CACpCJ,kBAAAA,CAAS,cAAA,CAAe,cAAA,CAAgBK,oCAAkB,CAAA,CAE1D,IAAMC,CAAAA,CAASJ,CAAAA,CACZ,GAAA,CAAKK,CAAAA,EAASA,CAAAA,EAAQ,SAAS,CAAA,CAC/B,MAAA,CAAQC,CAAAA,EAAU,CAACJ,CAAAA,CAAMI,CAAK,CAAC,CAAA,CAClC,EAAA,CAAIF,CAAAA,CAAO,MAAA,GAAW,CAAA,CACpB,OAAOF,CAAAA,CAET,IAAMK,CAAAA,CAAS,MAAMT,kBAAAA,CAAS,MAAA,CAC5BM,CAAAA,CAAO,GAAA,CAAKE,CAAAA,EAAAA,CAAW,CACrB,IAAA,CAAMA,CAAAA,CACN,OAAA,CAAS,CAAA,cAAA,EAAiBA,CAAK,CAAA,CAAA","file":"/home/runner/work/cli/cli/dist/chunk-7UL54E7X.cjs","sourcesContent":[null,"import { applyEnum, valuesOf } from '@transcend-io/type-utils';\nimport { LanguageKey } from '@transcend-io/internationalization';\nimport {\n CompletedRequestStatus,\n RequestAction,\n IsoCountryCode,\n IsoCountrySubdivisionCode,\n} from '@transcend-io/privacy-types';\nimport * as t from 'io-ts';\n\nexport const NONE = '[NONE]' as const;\nexport const BULK_APPLY = '[APPLY VALUE TO ALL ROWS]' as const;\nexport const BLANK = '<blank>' as const;\n\n/** These are uploaded at the top level of the request */\nexport const IDENTIFIER_BLOCK_LIST = ['email', 'coreIdentifier'];\n\n/**\n * Column names to map\n */\nexport enum ColumnName {\n /** The title of the email column */\n Email = 'email',\n /** The title of the core identifier column */\n CoreIdentifier = 'coreIdentifier',\n /** The title of the requestType column */\n RequestType = 'requestType',\n /** The title of the subjectType column */\n SubjectType = 'subjectType',\n /** The title of the locale column */\n Locale = 'locale',\n /** The country */\n Country = 'country',\n /** The country sub division */\n CountrySubDivision = 'countrySubDivision',\n /** The title of the requestStatus column */\n RequestStatus = 'requestStatus',\n /** The title of the createdAt column */\n CreatedAt = 'createdAt',\n /** The title of the dataSiloIds column */\n DataSiloIds = 'dataSiloIds',\n}\n\n/** These parameters are required in the Transcend DSR API */\nexport const IS_REQUIRED: { [k in ColumnName]: boolean } = {\n [ColumnName.Email]: false,\n [ColumnName.CoreIdentifier]: true,\n [ColumnName.RequestType]: true,\n [ColumnName.SubjectType]: true,\n [ColumnName.RequestStatus]: false,\n [ColumnName.CreatedAt]: false,\n [ColumnName.DataSiloIds]: false,\n [ColumnName.Locale]: false,\n [ColumnName.Country]: false,\n [ColumnName.CountrySubDivision]: false,\n};\n\n/** These parameters can be specified for the entire CSV set if needed */\nexport const CAN_APPLY_IN_BULK: { [k in ColumnName]?: boolean } = {\n [ColumnName.RequestType]: true,\n [ColumnName.SubjectType]: true,\n};\n\n// Cache state\nexport const CachedFileState = t.type({\n /** Mapping between the default request input column names and the CSV column name for that input */\n columnNames: t.partial(applyEnum(ColumnName, () => t.string)),\n /** Mapping between the identifier names and the CSV column name for that input */\n identifierNames: t.record(t.string, t.string),\n /** Mapping between the request attribute inputs and the CSV column name for that input */\n attributeNames: t.record(t.string, t.string),\n /** Mapping between CSV request type and Transcend Request Action */\n requestTypeToRequestAction: t.record(t.string, valuesOf(RequestAction)),\n /** Mapping between CSV data subject type and the name of the data subject in Transcend */\n subjectTypeToSubjectName: t.record(t.string, t.string),\n /** Mapping between language imported and Transcend locale code */\n languageToLocale: t.record(t.string, valuesOf(LanguageKey)),\n /** Mapping between region and country code */\n regionToCountry: t.record(\n t.string,\n valuesOf({ ...IsoCountryCode, [NONE]: NONE }),\n ),\n /** Mapping between region and country sub division code */\n regionToCountrySubDivision: t.record(\n t.string,\n valuesOf({ ...IsoCountrySubdivisionCode, [NONE]: NONE }),\n ),\n /** Mapping between request status in import to Transcend request status */\n statusToRequestStatus: t.record(\n t.string,\n valuesOf({ ...CompletedRequestStatus, [NONE]: NONE }),\n ),\n});\n\n/** Type override */\nexport type CachedFileState = t.TypeOf<typeof CachedFileState>;\n\n/**\n * Successfully processed request\n */\nexport const SuccessfulRequest = t.type({\n id: t.string,\n link: t.string,\n rowIndex: t.number,\n coreIdentifier: t.string,\n attemptedAt: t.string,\n});\n\n/** Type override */\nexport type SuccessfulRequest = t.TypeOf<typeof SuccessfulRequest>;\n\n// Cache state\nexport const CachedRequestState = t.type({\n /** Set of privacy requests that failed to upload */\n failingRequests: t.array(t.record(t.string, t.any)),\n /** Successfully uploaded requests */\n successfulRequests: t.array(SuccessfulRequest),\n /** Duplicate requests */\n duplicateRequests: t.array(\n t.type({\n rowIndex: t.number,\n coreIdentifier: t.string,\n attemptedAt: t.string,\n }),\n ),\n});\n\n/** Type override */\nexport type CachedRequestState = t.TypeOf<typeof CachedRequestState>;\n","import inquirer from 'inquirer';\nimport { NONE, BULK_APPLY } from './constants';\n\nimport fuzzysearch from 'fuzzysearch';\n\n/**\n * Check if word1 and word2 are a fuzzy match of each other.\n * Returns true if word1 is fuzzy match of word2 or vice versa.\n *\n * @param word1 - First word\n * @param word2 - Second word\n * @returns True if words are fuzzy match\n */\nexport function fuzzySearch(word1: string, word2: string): boolean {\n return (\n fuzzysearch(word1.toLowerCase(), word2.toLowerCase()) ||\n fuzzysearch(word2.toLowerCase(), word1.toLowerCase())\n );\n}\n\n/**\n * Fuzzy match column names for a particular field\n *\n * @param allColumnNames - List of all column names\n * @param fuzzyMapName - The name of field being mapped to\n * @param isRequired - When true, don't include \"NONE\" as an option\n * @param canApplyAll - When true, include an option to specify the value in bulk\n * @returns The list of suggestions for inquirer\n */\nexport function fuzzyMatchColumns(\n allColumnNames: string[],\n fuzzyMapName: string,\n isRequired: boolean,\n canApplyAll?: boolean,\n): (string | InstanceType<typeof inquirer.Separator>)[] {\n const matchingColumnNames = allColumnNames.filter((x) =>\n fuzzySearch(fuzzyMapName.toLowerCase(), x.toLowerCase()),\n );\n return [\n ...matchingColumnNames,\n new inquirer.Separator(),\n ...(isRequired ? [] : [NONE]),\n ...(canApplyAll ? [BULK_APPLY] : []),\n ...allColumnNames.filter((x) => !matchingColumnNames.includes(x)),\n ];\n}\n","import inquirer from 'inquirer';\nimport autoCompletePrompt from 'inquirer-autocomplete-prompt';\nimport { apply, ObjByString } from '@transcend-io/type-utils';\nimport { fuzzySearch } from './fuzzyMatchColumns';\n\n/**\n * Map a set of inputs to a set of outputs\n *\n * @param csvInputs - Input list\n * @param expectedOutputs - Output list\n * @param cache - Cache\n * @returns Mapping from row to enum value\n */\nexport async function mapEnumValues<TValue extends string>(\n csvInputs: string[],\n expectedOutputs: TValue[],\n cache: { [k in string]: TValue },\n): Promise<{ [k in string]: TValue }> {\n inquirer.registerPrompt('autocomplete', autoCompletePrompt);\n\n const inputs = csvInputs\n .map((item) => item || '<blank>')\n .filter((value) => !cache[value]);\n if (inputs.length === 0) {\n return cache;\n }\n const result = await inquirer.prompt<{ [k in string]: TValue }>(\n inputs.map((value) => ({\n name: value,\n message: `Map value of: ${value}`,\n type: 'autocomplete',\n default: expectedOutputs.find((x) => fuzzySearch(value, x)),\n source: (answersSoFar: ObjByString, input: string) =>\n !input\n ? expectedOutputs\n : expectedOutputs.filter(\n (x) => typeof x === 'string' && fuzzySearch(input, x),\n ),\n })),\n );\n return {\n ...cache,\n ...apply(result, (r) =>\n typeof r === 'string' ? (r as TValue) : (Object.values(r)[0] as TValue),\n ),\n };\n}\n"]}
@@ -0,0 +1,3 @@
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 _chunkLR3CPNDMcjs = require('./chunk-LR3CPNDM.cjs');var _chunk7UL54E7Xcjs = require('./chunk-7UL54E7X.cjs');var _chunkUONUI4ABcjs = require('./chunk-UONUI4AB.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkXPKFB4ILcjs = require('./chunk-XPKFB4IL.cjs');var _chunk44J2TVZUcjs = require('./chunk-44J2TVZU.cjs');var _privacytypes = require('@transcend-io/privacy-types');var _bluebird = require('bluebird');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function te({file:u,auth:s,sombraAuth:g,requestActions:f=[],concurrency:p=100,transcendUrl:n=_chunkXPKFB4ILcjs.e}){let o=_chunkUONUI4ABcjs.Ud.call(void 0, n,s),e=await _chunkUONUI4ABcjs.Vd.call(void 0, n,s,g);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Pulling manual enrichment requests, filtered for actions: ${f.join(",")}`));let d=await _chunkUONUI4ABcjs.le.call(void 0, o,{actions:f,statuses:[_privacytypes.RequestStatus.Enriching]}),i=[];await _bluebird.map.call(void 0, d,async t=>{let c=await _chunkUONUI4ABcjs.ge.call(void 0, o,{requestId:t.id});if(c.filter(({status:m})=>m==="ACTION_REQUIRED")){let m=await _chunkUONUI4ABcjs.je.call(void 0, o,e,{requestId:t.id});i.push({...t,requestIdentifiers:m,requestEnrichers:c})}},{concurrency:p});let l=i.map(({attributeValues:t,requestIdentifiers:c,requestEnrichers:I,...m})=>({...m,...Object.entries(_chunk44J2TVZUcjs.d.call(void 0, c,"name")).reduce((w,[P,$])=>Object.assign(w,{[P]:$.map(({value:C})=>C).join(",")}),{}),...Object.entries(_chunk44J2TVZUcjs.d.call(void 0, t,"attributeKey.name")).reduce((w,[P,$])=>Object.assign(w,{[P]:$.map(({name:C})=>C).join(",")}),{})})),a=_chunk44J2TVZUcjs.j.call(void 0, l.map(t=>Object.keys(t)).flat());return _chunkLR3CPNDMcjs.c.call(void 0, u,l,a),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully wrote ${i.length} requests to file "${u}"`)),i}var _iots = require('io-ts'); var R = _interopRequireWildcard(_iots);var T="https://app.transcend.io/privacy-requests/incoming-requests/",F= exports.b =R.record(R.string,R.string);async function M(u,{id:s,...g},f,p){if(!s){let e=`Request ID must be provided to enricher request.${p?` Found error in row: ${p}`:""}`;throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(e)),new Error(e)}let n=s.toLowerCase(),o=Object.entries(g).reduce((e,[d,i])=>_chunk44J2TVZUcjs.j.call(void 0, _chunk7UL54E7Xcjs.n.call(void 0, i)).length===0?e:Object.assign(e,{[d]:_chunk44J2TVZUcjs.j.call(void 0, _chunk7UL54E7Xcjs.n.call(void 0, i)).map(a=>({value:d==="email"?a.toLowerCase():a}))}),{});try{return await u.post("v1/enrich-identifiers",{headers:{"x-transcend-request-id":n,"x-transcend-enricher-id":f},json:{enrichedIdentifiers:o}}).json(),_chunkZUNVPK23cjs.a.error(_colors2.default.green(`Successfully enriched request: ${T}${n}`)),!0}catch(e){if(typeof e.response.body=="string"&&e.response.body.includes("Cannot update a resolved RequestEnricher"))return _chunkZUNVPK23cjs.a.warn(_colors2.default.magenta(`Skipped enrichment for request: ${T}${n}, request is no longer in the enriching phase.`)),!1;throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to enricher identifiers for request with id: ${T}${n} - ${e.message} - ${e.response.body}`)),e}}async function ge({file:u,auth:s,sombraAuth:g,enricherId:f,markSilent:p,concurrency:n=100,transcendUrl:o=_chunkXPKFB4ILcjs.e}){let e=await _chunkUONUI4ABcjs.Vd.call(void 0, o,s,g),d=_chunkUONUI4ABcjs.Ud.call(void 0, o,s);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading "${u}" from disk`));let i=_chunk7UL54E7Xcjs.q.call(void 0, u,F);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Enriching "${i.length}" privacy requests.`));let l=0,a=0,t=0;if(await _bluebird.map.call(void 0, i,async(c,I)=>{try{p&&(await _chunkUONUI4ABcjs.ac.call(void 0, d,_chunkUONUI4ABcjs.Y,{input:{id:c.id,isSilent:!0}}),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Mark request as silent mode - ${c.id}`))),await M(e,c,f,I)?l+=1:a+=1}catch (e2){t+=1}},{concurrency:n}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully notified Transcend!
2
+ Success count: ${l}.`)),a>0&&_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Skipped count: ${a}.`)),t>0)throw _chunkZUNVPK23cjs.a.info(_colors2.default.red(`Error Count: ${t}.`)),new Error(`Failed to enrich: ${t} requests.`);return i.length}exports.a = te; exports.b = F; exports.c = M; exports.d = ge;
3
+ //# sourceMappingURL=chunk-A4OQQVQT.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-A4OQQVQT.cjs","../src/lib/manual-enrichment/pullManualEnrichmentIdentifiersToCsv.ts","../src/lib/manual-enrichment/pushManualEnrichmentIdentifiersFromCsv.ts"],"names":["pullManualEnrichmentIdentifiersToCsv","file","auth","sombraAuth","requestActions","concurrency","transcendUrl","DEFAULT_TRANSCEND_API","client","buildTranscendGraphQLClient","sombra","createSombraGotInstance","logger","colors"],"mappings":"AAAA,mfAAwC,wDAAgD,wDAAyF,wDAAyC,wDAAyC,wDAAgD,2DCAtQ,oCACzB,gFACD,MA6BnB,SAAsBA,EAAAA,CAAqC,CACzD,IAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,cAAA,CAAAC,CAAAA,CAAiB,CAAC,CAAA,CAClB,WAAA,CAAAC,CAAAA,CAAc,GAAA,CACd,YAAA,CAAAC,CAAAA,CAAeC,mBACjB,CAAA,CAa6C,CAE3C,IAAMC,CAAAA,CAASC,kCAAAA,CAA4BH,CAAcJ,CAAI,CAAA,CACvDQ,CAAAA,CAAS,MAAMC,kCAAAA,CAAwBL,CAAcJ,CAAAA,CAAMC,CAAU,CAAA,CAE3ES,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,OAAA,CACL,CAAA,0DAAA,EAA6DT,CAAAA,CAAe,IAAA,CAC1E,GACF,CAAC,CAAA,CAAA;ACuDP,gBAAA","file":"/home/runner/work/cli/cli/dist/chunk-A4OQQVQT.cjs","sourcesContent":[null,"import { RequestAction, RequestStatus } from '@transcend-io/privacy-types';\nimport { map } from 'bluebird';\nimport colors from 'colors';\nimport { groupBy, uniq } from 'lodash-es';\nimport { DEFAULT_TRANSCEND_API } from '../../constants';\nimport { writeCsv } from '../cron/writeCsv';\nimport {\n PrivacyRequest,\n RequestEnricher,\n RequestIdentifier,\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllRequestEnrichers,\n fetchAllRequestIdentifiers,\n fetchAllRequests,\n} from '../graphql';\nimport { logger } from '../../logger';\n\nexport interface PrivacyRequestWithIdentifiers extends PrivacyRequest {\n /** Request Enrichers */\n requestEnrichers: RequestEnricher[];\n /** Request Identifiers */\n requestIdentifiers: RequestIdentifier[];\n}\n\n/**\n * Pull the set of manual enrichment jobs to CSV\n *\n * @param options - Options\n * @returns List of requests with identifiers\n */\nexport async function pullManualEnrichmentIdentifiersToCsv({\n file,\n auth,\n sombraAuth,\n requestActions = [],\n concurrency = 100,\n transcendUrl = DEFAULT_TRANSCEND_API,\n}: {\n /** CSV file path */\n file: string;\n /** Transcend API key authentication */\n auth: string;\n /** Sombra API key */\n sombraAuth?: string;\n /** Concurrency */\n concurrency?: number;\n /** The request actions to fetch */\n requestActions?: RequestAction[];\n /** API URL for Transcend backend */\n transcendUrl?: string;\n}): Promise<PrivacyRequestWithIdentifiers[]> {\n // Find all requests made before createdAt that are in a removing data state\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n const sombra = await createSombraGotInstance(transcendUrl, auth, sombraAuth);\n\n logger.info(\n colors.magenta(\n `Pulling manual enrichment requests, filtered for actions: ${requestActions.join(\n ',',\n )}`,\n ),\n );\n\n // Pull all privacy requests\n const allRequests = await fetchAllRequests(client, {\n actions: requestActions,\n statuses: [RequestStatus.Enriching],\n });\n\n // Requests to save\n const savedRequests: PrivacyRequestWithIdentifiers[] = [];\n\n // Filter down requests to what is needed\n await map(\n allRequests,\n async (request) => {\n // Fetch enrichers\n const requestEnrichers = await fetchAllRequestEnrichers(client, {\n requestId: request.id,\n });\n\n // Check if manual enrichment exists for that request\n const hasManualEnrichment = requestEnrichers.filter(\n ({ status }) => status === 'ACTION_REQUIRED',\n );\n\n // Save request to queue\n if (hasManualEnrichment) {\n const requestIdentifiers = await fetchAllRequestIdentifiers(\n client,\n sombra,\n {\n requestId: request.id,\n },\n );\n savedRequests.push({\n ...request,\n requestIdentifiers,\n requestEnrichers,\n });\n }\n },\n {\n concurrency,\n },\n );\n\n const data = savedRequests.map(\n ({\n attributeValues,\n requestIdentifiers,\n requestEnrichers, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...request\n }) => ({\n ...request,\n // flatten identifiers\n ...Object.entries(groupBy(requestIdentifiers, 'name')).reduce(\n (acc, [key, values]) =>\n Object.assign(acc, {\n [key]: values.map(({ value }) => value).join(','),\n }),\n {},\n ),\n // flatten attributes\n ...Object.entries(groupBy(attributeValues, 'attributeKey.name')).reduce(\n (acc, [key, values]) =>\n Object.assign(acc, {\n [key]: values.map(({ name }) => name).join(','),\n }),\n {},\n ),\n }),\n );\n\n // Write out to CSV\n const headers = uniq(data.map((d) => Object.keys(d)).flat());\n writeCsv(file, data, headers);\n\n logger.info(\n colors.green(\n `Successfully wrote ${savedRequests.length} requests to file \"${file}\"`,\n ),\n );\n\n return savedRequests;\n}\n","import colors from 'colors';\nimport { map } from 'bluebird';\nimport { logger } from '../../logger';\nimport {\n UPDATE_PRIVACY_REQUEST,\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n makeGraphQLRequest,\n} from '../graphql';\nimport {\n enrichPrivacyRequest,\n EnrichPrivacyRequest,\n} from './enrichPrivacyRequest';\nimport { readCsv } from '../requests';\nimport { DEFAULT_TRANSCEND_API } from '../../constants';\n\n/**\n * Push a CSV of enriched requests back into Transcend\n *\n * @param options - Options\n * @returns Number of items processed\n */\nexport async function pushManualEnrichmentIdentifiersFromCsv({\n file,\n auth,\n sombraAuth,\n enricherId,\n markSilent,\n concurrency = 100,\n transcendUrl = DEFAULT_TRANSCEND_API,\n}: {\n /** CSV file path */\n file: string;\n /** Transcend API key authentication */\n auth: string;\n /** ID of enricher being uploaded to */\n enricherId: string;\n /** Sombra API key authentication */\n sombraAuth?: string;\n /** Concurrency */\n concurrency?: number;\n /** API URL for Transcend backend */\n transcendUrl?: string;\n /** Mark requests in silent mode before enriching */\n markSilent?: boolean;\n}): Promise<number> {\n // Create sombra instance to communicate with\n const sombra = await createSombraGotInstance(transcendUrl, auth, sombraAuth);\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Read from CSV\n logger.info(colors.magenta(`Reading \"${file}\" from disk`));\n const activeResults = readCsv(file, EnrichPrivacyRequest);\n\n // Notify Transcend\n logger.info(\n colors.magenta(`Enriching \"${activeResults.length}\" privacy requests.`),\n );\n\n let successCount = 0;\n let skippedCount = 0;\n let errorCount = 0;\n\n await map(\n activeResults,\n async (request, index) => {\n try {\n // Mark requests in silent mode before a certain date\n if (markSilent) {\n await makeGraphQLRequest(client, UPDATE_PRIVACY_REQUEST, {\n input: {\n id: request.id,\n isSilent: true,\n },\n });\n\n logger.info(\n colors.magenta(`Mark request as silent mode - ${request.id}`),\n );\n }\n\n const result = await enrichPrivacyRequest(\n sombra,\n request,\n enricherId,\n index,\n );\n if (result) {\n successCount += 1;\n } else {\n skippedCount += 1;\n }\n } catch (err) {\n errorCount += 1;\n }\n },\n { concurrency },\n );\n\n logger.info(\n colors.green(\n `Successfully notified Transcend! \\n Success count: ${successCount}.`,\n ),\n );\n\n if (skippedCount > 0) {\n logger.info(colors.magenta(`Skipped count: ${skippedCount}.`));\n }\n\n if (errorCount > 0) {\n logger.info(colors.red(`Error Count: ${errorCount}.`));\n throw new Error(`Failed to enrich: ${errorCount} requests.`);\n }\n\n return activeResults.length;\n}\n"]}
@@ -0,0 +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 }; } 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 _chunkUONUI4ABcjs = require('./chunk-UONUI4AB.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkXPKFB4ILcjs = require('./chunk-XPKFB4IL.cjs');var _crypto = require('crypto'); var U = _interopRequireWildcard(_crypto);var _jsonwebtoken = require('jsonwebtoken'); var E = _interopRequireWildcard(_jsonwebtoken);function $(c,l,n){let o=Buffer.from(n,"base64"),f=Buffer.from(l,"base64"),u="id-aes256-wrap-pad",d=Buffer.from("A65959A6","hex"),s=U.createCipheriv(u,f,d),i={encryptedIdentifier:Buffer.concat([s.update(c),s.final()]).toString("base64")};return E.sign(i,o,{algorithm:"HS384"})}var _iots = require('io-ts'); var e = _interopRequireWildcard(_iots); var r = _interopRequireWildcard(_iots);var B=e.intersection([e.type({userId:e.string,timestamp:e.string}),e.partial({confirmed:e.union([e.literal("true"),e.literal("false")]),updated:e.union([e.literal("true"),e.literal("false")]),prompted:e.union([e.literal("true"),e.literal("false")]),metadata:e.string,usp:e.union([e.string,e.null]),gpp:e.union([e.string,e.null])})]),Y= exports.b =e.intersection([B,e.partial({purposes:e.string})]),G= exports.c =e.intersection([B,e.type({partition:e.string}),e.partial({tcf:e.union([e.string,e.null]),purposes:e.record(e.string,e.union([e.boolean,e.string]))})]);var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _bluebird = require('bluebird');var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);var _typeutils = require('@transcend-io/type-utils');var I=/^[0-9][Y|N]([Y|N])[Y|N]$/,R= exports.e =r.record(r.string,r.union([r.boolean,r.literal("Auto")]));async function Z({base64EncryptionKey:c,base64SigningKey:l,preferences:n,partition:o,concurrency:f=100,transcendUrl:u=_chunkXPKFB4ILcjs.f}){let d=_chunkUONUI4ABcjs.Wd.call(void 0, u),s=n.filter(t=>t.usp&&!I.test(t.usp));if(s.length>0)throw new Error(`Received invalid usp strings: ${JSON.stringify(s,null,2)}`);let m=n.map((t,y)=>[t,y]).filter(([t])=>{if(!t.purposes)return!1;try{return _typeutils.decodeCodec.call(void 0, R,t.purposes),!1}catch (e2){return!0}});if(m.length>0)throw new Error(`Received invalid purpose maps: ${JSON.stringify(m,null,2)}`);let i=n.filter(t=>!t.usp&&!t.purposes);if(i.length>0)throw new Error(`Received invalid inputs, expected either purposes or usp to be defined: ${JSON.stringify(i,null,2)}`);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Uploading ${n.length} user preferences to partition ${o}`));let w=new Date().getTime(),g=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),S=0;g.start(n.length,0),await _bluebird.map.call(void 0, n,async({userId:t,confirmed:y="true",updated:T,prompted:v,purposes:x,...p})=>{let j=$(t,c,l),[,k]=p.usp?I.exec(p.usp)||[]:[],D={token:j,partition:o,consent:{confirmed:y==="true",purposes:x?_typeutils.decodeCodec.call(void 0, R,x):p.usp?{SaleOfInfo:k==="Y"}:{},...T?{updated:T==="true"}:{},...v?{prompted:v==="true"}:{},...p}};try{await d.post("sync",{json:D}).json()}catch(h){try{let C=JSON.parse(_optionalChain([h, 'optionalAccess', _2 => _2.response, 'optionalAccess', _3 => _3.body])||"{}");C.error&&_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error: ${C.error}`))}catch (e3){}throw new Error(`Received an error from server: ${_optionalChain([h, 'optionalAccess', _4 => _4.response, 'optionalAccess', _5 => _5.body])||_optionalChain([h, 'optionalAccess', _6 => _6.message])}`)}S+=1,g.update(S)},{concurrency:f}),g.stop();let _=new Date().getTime()-w;_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully uploaded ${n.length} user preferences to partition ${o} in "${_/1e3}" seconds!`))}exports.a = $; exports.b = Y; exports.c = G; exports.d = I; exports.e = R; exports.f = Z;
2
+ //# sourceMappingURL=chunk-BPX6MSMC.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-BPX6MSMC.cjs","../src/lib/consent-manager/createConsentToken.ts","../src/lib/consent-manager/types.ts","../src/lib/consent-manager/uploadConsents.ts"],"names":["createConsentToken","userId","base64EncryptionKey","base64SigningKey","signingKey","encryptionKey","encryptionAlgorithm","iv","cipher","jwtPayload","ConsentPreferenceBase","ConsentPreferenceUpload","ConsentPreferenceFetch","USP_STRING_REGEX","PurposeMap","uploadConsents","preferences","partition","concurrency","transcendUrl","DEFAULT_TRANSCEND_CONSENT_API","transcendConsentApi","createTranscendConsentGotInstance","invalidUspStrings","pref"],"mappings":"AAAA,u/BAAyC,wDAAoC,wDAAyC,0ECA9F,4FACH,SAWLA,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACQ,CAER,IAAMC,CAAAA,CAAa,MAAA,CAAO,IAAA,CAAKD,CAAAA,CAAkB,QAAQ,CAAA,CACnDE,CAAAA,CAAgB,MAAA,CAAO,IAAA,CAAKH,CAAAA,CAAqB,QAAQ,CAAA,CAGzDI,CAAAA,CAAsB,oBAAA,CAEtBC,CAAAA,CAAK,MAAA,CAAO,IAAA,CAAK,UAAA,CAAY,KAAK,CAAA,CAElCC,CAAAA,CAAgB,CAAA,CAAA,cAAA,CAAeF,CAAAA,CAAqBD,CAAAA,CAAeE,CAAE,CAAA,CAYrEE,CAAAA,CAAa,C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AAA,CAAkB,MAAA,CAAS,CAAA,CAC7B,MAAM,IAAI,KAAA,CACR,CAAA,8BAAA,EAAiC,IAAA,CAAK,SAAA,CACpCA,CAAAA,CACA,IAAA,CACA,CACF,CAAC,CAAA,CAAA","file":"/home/runner/work/cli/cli/dist/chunk-BPX6MSMC.cjs","sourcesContent":[null,"import * as crypto from 'crypto';\nimport * as jwt from 'jsonwebtoken';\n\n/**\n * Function to create a consent manager token\n *\n * @see https://docs.transcend.io/docs/consent/reference/managed-consent-database\n * @param userId - User ID\n * @param base64EncryptionKey - Encryption key\n * @param base64SigningKey - Signing key\n * @returns Token\n */\nexport function createConsentToken(\n userId: string,\n base64EncryptionKey: string,\n base64SigningKey: string,\n): string {\n // Read on for where to find these keys\n const signingKey = Buffer.from(base64SigningKey, 'base64');\n const encryptionKey = Buffer.from(base64EncryptionKey, 'base64');\n\n // NIST's AES-KWP implementation { aes 48 } - see https://tools.ietf.org/html/rfc5649\n const encryptionAlgorithm = 'id-aes256-wrap-pad';\n // Initial Value for AES-KWP integrity check - see https://tools.ietf.org/html/rfc5649#section-3\n const iv = Buffer.from('A65959A6', 'hex');\n // Set up encryption algorithm\n const cipher = crypto.createCipheriv(encryptionAlgorithm, encryptionKey, iv);\n\n // Encrypt the userId and base64-encode the result\n const encryptedIdentifier = Buffer.concat([\n cipher.update(userId),\n cipher.final(),\n ]).toString('base64');\n\n // Create the JWT content - jwt.sign will add a 'iat' (issued at) field to the payload\n // If you wanted to add something manually, consider\n // const issued: Date = new Date();\n // const isoDate = issued.toISOString();\n const jwtPayload = {\n encryptedIdentifier,\n };\n\n // Create a JSON web token and HMAC it with SHA-384\n const consentToken = jwt.sign(jwtPayload, signingKey, {\n algorithm: 'HS384',\n });\n\n return consentToken;\n}\n","import * as t from 'io-ts';\n\nexport const ConsentPreferenceBase = t.intersection([\n t.type({\n /** User ID */\n userId: t.string,\n /** Has the consent been updated (including no-change confirmation) since default resolution */\n timestamp: t.string,\n }),\n t.partial({\n /** Was tracking consent confirmed by the user? If this is false, the consent was resolved from defaults & is not yet confirmed */\n confirmed: t.union([t.literal('true'), t.literal('false')]),\n /**\n * Has the consent been updated (including no-change confirmation) since default resolution\n */\n updated: t.union([t.literal('true'), t.literal('false')]),\n /**\n * Whether or not the UI has been shown to the end-user (undefined in older versions of airgap.js)\n */\n prompted: t.union([t.literal('true'), t.literal('false')]),\n /** Consent metadata */\n metadata: t.string,\n /** US Privacy (USP) String */\n usp: t.union([t.string, t.null]),\n /** IAB GPP String */\n gpp: t.union([t.string, t.null]),\n }),\n]);\n\n/** Type override */\nexport type ConsentPreferenceBase = t.TypeOf<typeof ConsentPreferenceUpload>;\n\nexport const ConsentPreferenceUpload = t.intersection([\n ConsentPreferenceBase,\n t.partial({\n /**\n * Purpose map\n * This is a stringified JSON object with keys as purpose names and values as booleans or 'Auto'\n */\n purposes: t.string,\n }),\n]);\n\n/** Type override */\nexport type ConsentPreferenceUpload = t.TypeOf<typeof ConsentPreferenceUpload>;\n\nexport const ConsentPreferenceFetch = t.intersection([\n ConsentPreferenceBase,\n t.type({\n /** This is the partition key used for the dynamo entry */\n partition: t.string,\n }),\n t.partial({\n /** IAB TCF String */\n tcf: t.union([t.string, t.null]),\n /**\n * Purpose map\n * This is a JSON object with keys as purpose names and values as booleans or 'Auto'\n */\n purposes: t.record(t.string, t.union([t.boolean, t.string])),\n }),\n]);\n\n/** Type override */\nexport type ConsentPreferenceFetch = t.TypeOf<typeof ConsentPreferenceFetch>;\n","import { createTranscendConsentGotInstance } from '../graphql';\nimport colors from 'colors';\nimport * as t from 'io-ts';\nimport { DEFAULT_TRANSCEND_CONSENT_API } from '../../constants';\nimport { map } from 'bluebird';\nimport { createConsentToken } from './createConsentToken';\nimport { logger } from '../../logger';\nimport cliProgress from 'cli-progress';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport type { ConsentPreferenceUpload } from './types';\nimport { ConsentPreferencesBody } from '@transcend-io/airgap.js-types';\n\nexport const USP_STRING_REGEX = /^[0-9][Y|N]([Y|N])[Y|N]$/;\n\nexport const PurposeMap = t.record(\n t.string,\n t.union([t.boolean, t.literal('Auto')]),\n);\n\n/**\n * Upload a set of consent preferences\n *\n * @param options - Options\n */\nexport async function uploadConsents({\n base64EncryptionKey,\n base64SigningKey,\n preferences,\n partition,\n concurrency = 100,\n transcendUrl = DEFAULT_TRANSCEND_CONSENT_API,\n}: {\n /** base64 encryption key */\n base64EncryptionKey: string;\n /** base64 signing key */\n base64SigningKey: string;\n /** Partition key */\n partition: string;\n /** Sombra API key authentication */\n preferences: ConsentPreferenceUpload[];\n /** API URL for Transcend backend */\n transcendUrl?: string;\n /** Concurrency limit for approving */\n concurrency?: number;\n}): Promise<void> {\n // Create connection to API\n const transcendConsentApi = createTranscendConsentGotInstance(transcendUrl);\n\n // Ensure usp strings are valid\n const invalidUspStrings = preferences.filter(\n (pref) => pref.usp && !USP_STRING_REGEX.test(pref.usp),\n );\n if (invalidUspStrings.length > 0) {\n throw new Error(\n `Received invalid usp strings: ${JSON.stringify(\n invalidUspStrings,\n null,\n 2,\n )}`,\n );\n }\n\n // Ensure purpose maps are valid\n const invalidPurposeMaps = preferences\n .map((pref, ind) => [pref, ind] as [ConsentPreferenceUpload, number])\n .filter(([pref]) => {\n if (!pref.purposes) {\n return false;\n }\n try {\n decodeCodec(PurposeMap, pref.purposes);\n return false;\n } catch {\n return true;\n }\n });\n if (invalidPurposeMaps.length > 0) {\n throw new Error(\n `Received invalid purpose maps: ${JSON.stringify(\n invalidPurposeMaps,\n null,\n 2,\n )}`,\n );\n }\n\n // Ensure usp or preferences are provided\n const invalidInputs = preferences.filter(\n (pref) => !pref.usp && !pref.purposes,\n );\n if (invalidInputs.length > 0) {\n throw new Error(\n `Received invalid inputs, expected either purposes or usp to be defined: ${JSON.stringify(\n invalidInputs,\n null,\n 2,\n )}`,\n );\n }\n\n logger.info(\n colors.magenta(\n `Uploading ${preferences.length} user preferences to partition ${partition}`,\n ),\n );\n\n // Time duration\n const t0 = new Date().getTime();\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 progressBar.start(preferences.length, 0);\n await map(\n preferences,\n async ({\n userId,\n confirmed = 'true',\n updated,\n prompted,\n purposes,\n ...consent\n }) => {\n const token = createConsentToken(\n userId,\n base64EncryptionKey,\n base64SigningKey,\n );\n\n // parse usp string\n const [, saleStatus] = consent.usp\n ? USP_STRING_REGEX.exec(consent.usp) || []\n : [];\n\n const input = {\n token,\n partition,\n consent: {\n confirmed: confirmed === 'true',\n purposes: purposes\n ? decodeCodec(PurposeMap, purposes)\n : consent.usp\n ? { SaleOfInfo: saleStatus === 'Y' }\n : {},\n ...(updated ? { updated: updated === 'true' } : {}),\n ...(prompted ? { prompted: prompted === 'true' } : {}),\n ...consent,\n },\n } as ConsentPreferencesBody;\n\n // Make the request\n try {\n await transcendConsentApi\n .post('sync', {\n json: input,\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 throw new Error(\n `Received an error from server: ${\n err?.response?.body || err?.message\n }`,\n );\n }\n\n total += 1;\n progressBar.update(total);\n },\n { concurrency },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n logger.info(\n colors.green(\n `Successfully uploaded ${\n preferences.length\n } user preferences to partition ${partition} in \"${\n totalTime / 1000\n }\" seconds!`,\n ),\n );\n}\n"]}