typescript-pos 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -22,7 +22,9 @@ var SENSITIVE_KEYS = /* @__PURE__ */ new Set([
22
22
  "secret_key",
23
23
  "store_key",
24
24
  "cvv2val",
25
- "expires"
25
+ "expires",
26
+ "expiremonth",
27
+ "expireyear"
26
28
  ]);
27
29
  var PAN_PATTERN = /(?<!\d)\d{13,19}(?!\d)/g;
28
30
  var MASK = "***";
@@ -34,42 +36,45 @@ var SENSITIVE_TAGS = [
34
36
  "Expiry",
35
37
  "ExpiryDate",
36
38
  "Expires",
39
+ "ExpireMonth",
40
+ "ExpireYear",
37
41
  "Password",
38
42
  "MerchantPassword",
39
43
  "Pan"
40
44
  ];
41
45
  var XML_PATTERN = new RegExp(`(<(${SENSITIVE_TAGS.join("|")})(?:\\s[^>]*)?>)[^<]*(</\\2\\s*>)`, "gi");
42
46
  var QUERY_PATTERN = new RegExp(`(?<![A-Za-z0-9_])(${SENSITIVE_TAGS.join("|")})=[^&\\s"']*`, "gi");
43
- function maskString(value) {
44
- return value.replace(XML_PATTERN, `$1${MASK}$3`).replace(QUERY_PATTERN, `$1=${MASK}`).replace(PAN_PATTERN, (m) => `${m.slice(0, 6)}****${m.slice(-4)}`);
45
- }
46
- function mask(value, seen, depth) {
47
- if (typeof value === "string") return maskString(value);
48
- if (typeof value === "number" || typeof value === "bigint") {
49
- const str = String(value);
50
- return /^\d{13,19}$/.test(str) ? maskString(str) : value;
51
- }
52
- if (typeof value === "function") return "[Function]";
53
- if (value === null || typeof value !== "object") return value;
54
- if (seen.has(value)) return seen.get(value);
47
+ var JSON_PATTERN = new RegExp(`"(${SENSITIVE_TAGS.join("|")})"\\s*:\\s*"(?:[^"\\\\]|\\\\.)*"`, "gi");
48
+ function maskString(value2) {
49
+ return value2.replace(XML_PATTERN, `$1${MASK}$3`).replace(QUERY_PATTERN, `$1=${MASK}`).replace(JSON_PATTERN, `"$1":"${MASK}"`).replace(PAN_PATTERN, (m) => `${m.slice(0, 6)}****${m.slice(-4)}`);
50
+ }
51
+ function mask(value2, seen, depth) {
52
+ if (typeof value2 === "string") return maskString(value2);
53
+ if (typeof value2 === "number" || typeof value2 === "bigint") {
54
+ const str = String(value2);
55
+ return /^\d{13,19}$/.test(str) ? maskString(str) : value2;
56
+ }
57
+ if (typeof value2 === "function") return "[Function]";
58
+ if (value2 === null || typeof value2 !== "object") return value2;
59
+ if (seen.has(value2)) return seen.get(value2);
55
60
  if (depth >= MAX_DEPTH) return "[MaxDepth]";
56
- if (value instanceof Error) {
57
- const out2 = { name: value.name, message: maskString(value.message) };
58
- seen.set(value, out2);
61
+ if (value2 instanceof Error) {
62
+ const out2 = { name: value2.name, message: maskString(value2.message) };
63
+ seen.set(value2, out2);
59
64
  return out2;
60
65
  }
61
- if (Array.isArray(value)) {
66
+ if (Array.isArray(value2)) {
62
67
  const out2 = [];
63
- seen.set(value, out2);
64
- for (const item of value) out2.push(mask(item, seen, depth + 1));
68
+ seen.set(value2, out2);
69
+ for (const item of value2) out2.push(mask(item, seen, depth + 1));
65
70
  return out2;
66
71
  }
67
- const tag = Object.prototype.toString.call(value).slice(8, -1);
68
- if (tag === "Date") return value;
72
+ const tag = Object.prototype.toString.call(value2).slice(8, -1);
73
+ if (tag === "Date") return value2;
69
74
  if (tag !== "Object") return `[${tag}]`;
70
75
  const out = {};
71
- seen.set(value, out);
72
- for (const [key, item] of Object.entries(value)) {
76
+ seen.set(value2, out);
77
+ for (const [key, item] of Object.entries(value2)) {
73
78
  if (SENSITIVE_KEYS.has(key.toLowerCase()) && item !== null && item !== void 0) {
74
79
  out[key] = MASK;
75
80
  } else {
@@ -126,9 +131,9 @@ var OrderMismatchError = class extends PosError {
126
131
  * Always `false` when no response is attached.
127
132
  */
128
133
  paymentMayHaveCompleted;
129
- constructor(field3, expected, actual, response) {
130
- super(`Callback ${field3} mismatch: expected "${expected}", got "${actual}"`);
131
- this.field = field3;
134
+ constructor(field4, expected, actual, response) {
135
+ super(`Callback ${field4} mismatch: expected "${expected}", got "${actual}"`);
136
+ this.field = field4;
132
137
  this.expected = expected;
133
138
  this.actual = actual;
134
139
  this.paymentMayHaveCompleted = response !== void 0 && (response.status === "approved" || response.proc_return_code === "00");
@@ -172,7 +177,7 @@ var HttpTransport = class {
172
177
  const exchange = async () => {
173
178
  let res;
174
179
  let bytes;
175
- let text5;
180
+ let text6;
176
181
  try {
177
182
  res = await this.fetchImpl(url, {
178
183
  method: "POST",
@@ -182,7 +187,7 @@ var HttpTransport = class {
182
187
  redirect: "error"
183
188
  });
184
189
  bytes = new Uint8Array(await res.arrayBuffer());
185
- text5 = new TextDecoder().decode(bytes);
190
+ text6 = new TextDecoder().decode(bytes);
186
191
  } catch (e) {
187
192
  if (e instanceof PosHttpError) throw e;
188
193
  throw new PosHttpError(
@@ -192,9 +197,9 @@ var HttpTransport = class {
192
197
  );
193
198
  }
194
199
  if (res.status < 200 || res.status >= 300) {
195
- throw new PosHttpError(`Bank returned HTTP ${res.status}`, { url, status: res.status, body: text5 });
200
+ throw new PosHttpError(`Bank returned HTTP ${res.status}`, { url, status: res.status, body: text6 });
196
201
  }
197
- return { status: res.status, body: text5, bytes, headers: res.headers };
202
+ return { status: res.status, body: text6, bytes, headers: res.headers };
198
203
  };
199
204
  const pending = exchange();
200
205
  pending.catch(() => {
@@ -212,13 +217,13 @@ function freezeConfig(config) {
212
217
  deepFreeze(config);
213
218
  return config;
214
219
  }
215
- function deepFreeze(value) {
216
- for (const child of Object.values(value)) {
220
+ function deepFreeze(value2) {
221
+ for (const child of Object.values(value2)) {
217
222
  if (child !== null && typeof child === "object") {
218
223
  deepFreeze(child);
219
224
  }
220
225
  }
221
- Object.freeze(value);
226
+ Object.freeze(value2);
222
227
  }
223
228
 
224
229
  // src/config/posProductionConfig.ts
@@ -282,6 +287,13 @@ var posProductionConfig = freezeConfig({
282
287
  query_api: "https://apigw.vakifbank.com.tr:8443/virtualPos/Search"
283
288
  }
284
289
  },
290
+ "vakifbank-cp": {
291
+ name: "VakifBank-PayFlex-Common-Payment",
292
+ class: "PayFlexCPV4Pos",
293
+ gateway_endpoints: {
294
+ payment_api: "https://inbound.apigateway.vakifbank.com.tr:8443/commonPayment"
295
+ }
296
+ },
285
297
  "ziraat-vpos": {
286
298
  name: "Ziraat Bankas\u0131 PayFlex",
287
299
  class: "PayFlexV4Pos",
@@ -322,6 +334,13 @@ var posTestConfig = freezeConfig({
322
334
  query_api: "https://inbound.apigatewaytest.vakifbank.com.tr:8443/virtualPos/Search"
323
335
  }
324
336
  },
337
+ "vakifbank-cp": {
338
+ name: "VakifBank-PayFlex-Common-Payment",
339
+ class: "PayFlexCPV4Pos",
340
+ gateway_endpoints: {
341
+ payment_api: "https://inbound.apigatewaytest.vakifbank.com.tr:8443/commonPayment"
342
+ }
343
+ },
325
344
  "ziraat-vpos": {
326
345
  name: "Ziraat Bankas\u0131",
327
346
  class: "PayFlexV4Pos",
@@ -619,36 +638,36 @@ var XmlDecoder = {
619
638
 
620
639
  // src/serializer/XmlEncoder.ts
621
640
  var ILLEGAL_XML_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g;
622
- function escapeText(value) {
623
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
641
+ function escapeText(value2) {
642
+ return value2.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
624
643
  }
625
- function escapeAttr(value) {
626
- return escapeText(value).replace(/"/g, "&quot;");
644
+ function escapeAttr(value2) {
645
+ return escapeText(value2).replace(/"/g, "&quot;");
627
646
  }
628
- function scalar(value) {
629
- if (value === true) return "1";
630
- if (value === false) return "0";
631
- if (value === null || value === void 0) return "";
632
- return String(value).replace(ILLEGAL_XML_CHARS, "");
647
+ function scalar(value2) {
648
+ if (value2 === true) return "1";
649
+ if (value2 === false) return "0";
650
+ if (value2 === null || value2 === void 0) return "";
651
+ return String(value2).replace(ILLEGAL_XML_CHARS, "");
633
652
  }
634
- function text(value) {
635
- const str = scalar(value);
653
+ function text(value2) {
654
+ const str = scalar(value2);
636
655
  if (/[<>&]/.test(str)) return `<![CDATA[${str.replace(/]]>/g, "]]]]><![CDATA[>")}]]>`;
637
656
  return str;
638
657
  }
639
- function element(name, value) {
640
- if (Array.isArray(value)) return value.map((item) => element(name, item)).join("");
641
- if (value !== null && typeof value === "object") {
658
+ function element(name, value2) {
659
+ if (Array.isArray(value2)) return value2.map((item) => element(name, item)).join("");
660
+ if (value2 !== null && typeof value2 === "object") {
642
661
  let attrs = "";
643
662
  let inner = "";
644
- for (const [key, v] of Object.entries(value)) {
663
+ for (const [key, v] of Object.entries(value2)) {
645
664
  if (key.startsWith("@")) attrs += ` ${key.slice(1)}="${escapeAttr(scalar(v))}"`;
646
665
  else if (key === "#") inner += text(v);
647
666
  else inner += element(key, v);
648
667
  }
649
668
  return inner === "" ? `<${name}${attrs}/>` : `<${name}${attrs}>${inner}</${name}>`;
650
669
  }
651
- const str = text(value);
670
+ const str = text(value2);
652
671
  return str === "" ? `<${name}/>` : `<${name}>${str}</${name}>`;
653
672
  }
654
673
  var XmlEncoder = {
@@ -775,9 +794,9 @@ var REPLACED_LATIN1_LETTERS = /* @__PURE__ */ new Set([208, 221, 222, 240, 253,
775
794
  function inIso88599(codePoint) {
776
795
  return codePoint <= 255 ? !REPLACED_LATIN1_LETTERS.has(codePoint) : TURKISH_LETTERS.has(codePoint);
777
796
  }
778
- function replaceUnrepresentable(value, replace) {
797
+ function replaceUnrepresentable(value2, replace) {
779
798
  let out = "";
780
- for (const char of value) {
799
+ for (const char of value2) {
781
800
  out += inIso88599(char.codePointAt(0)) ? char : replace(char);
782
801
  }
783
802
  return out;
@@ -899,30 +918,30 @@ var CARD_TYPE = {
899
918
  };
900
919
 
901
920
  // src/serializer/FormEncoder.ts
902
- function phpUrlEncode(value) {
903
- return encodeURIComponent(value).replace(/[!'()*~]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, "+");
921
+ function phpUrlEncode(value2) {
922
+ return encodeURIComponent(value2).replace(/[!'()*~]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, "+");
904
923
  }
905
- function scalarToString(value) {
906
- if (typeof value === "boolean") return value ? "1" : "0";
907
- return String(value);
924
+ function scalarToString(value2) {
925
+ if (typeof value2 === "boolean") return value2 ? "1" : "0";
926
+ return String(value2);
908
927
  }
909
928
  function sub(prefix, key) {
910
929
  return prefix === null ? phpUrlEncode(key) : `${prefix}%5B${phpUrlEncode(key)}%5D`;
911
930
  }
912
- function build(prefix, value, out) {
913
- if (value === null || value === void 0) return;
914
- if (Array.isArray(value)) {
915
- value.forEach((item, i) => {
931
+ function build(prefix, value2, out) {
932
+ if (value2 === null || value2 === void 0) return;
933
+ if (Array.isArray(value2)) {
934
+ value2.forEach((item, i) => {
916
935
  build(sub(prefix, String(i)), item, out);
917
936
  });
918
937
  return;
919
938
  }
920
- if (typeof value === "object") {
921
- for (const [k, v] of Object.entries(value)) build(sub(prefix, k), v, out);
939
+ if (typeof value2 === "object") {
940
+ for (const [k, v] of Object.entries(value2)) build(sub(prefix, k), v, out);
922
941
  return;
923
942
  }
924
943
  if (prefix === null) return;
925
- out.push(`${prefix}=${phpUrlEncode(scalarToString(value))}`);
944
+ out.push(`${prefix}=${phpUrlEncode(scalarToString(value2))}`);
926
945
  }
927
946
  var FormEncoder = {
928
947
  encode(data) {
@@ -932,6 +951,44 @@ var FormEncoder = {
932
951
  }
933
952
  };
934
953
 
954
+ // src/client/PayFlexCPV4PosHttpClient.ts
955
+ var PayFlexCPV4PosHttpClient = class _PayFlexCPV4PosHttpClient extends AbstractHttpClient {
956
+ static API_NAME_PAYMENT_API = "payment_api";
957
+ /** Accepted for configs that name the endpoint `gateway_3d`. */
958
+ static API_NAME_GATEWAY_3D = "gateway_3d";
959
+ constructor(endpoint, transport, logger = noopLogger) {
960
+ super(endpoint, transport, logger);
961
+ }
962
+ static supports(gatewayClass, apiName) {
963
+ return gatewayClass === "PayFlexCPV4Pos" && (apiName === _PayFlexCPV4PosHttpClient.API_NAME_PAYMENT_API || apiName === _PayFlexCPV4PosHttpClient.API_NAME_GATEWAY_3D);
964
+ }
965
+ supportsTx(_txType, _paymentModel) {
966
+ return true;
967
+ }
968
+ getApiUrl(txType, _paymentModel) {
969
+ const base = this.endpoint.endsWith("/") ? this.endpoint.slice(0, -1) : this.endpoint;
970
+ if (txType === TX_TYPE.INTERNAL_3D_FORM_BUILD) {
971
+ return `${base}/CreateToken`;
972
+ }
973
+ return `${base}/GetVposTransaction`;
974
+ }
975
+ encode(txType, _paymentModel, requestData, _order) {
976
+ if (txType === TX_TYPE.INTERNAL_3D_FORM_BUILD) {
977
+ return { data: FormEncoder.encode(requestData), format: "form" };
978
+ }
979
+ return { data: JSON.stringify(requestData), format: "json" };
980
+ }
981
+ headers(txType, paymentModel, encoded) {
982
+ return { ...super.headers(txType, paymentModel, encoded), Accept: "application/json" };
983
+ }
984
+ decode(body) {
985
+ if (body.trimStart().startsWith("<")) {
986
+ return Promise.resolve(XmlDecoder.decode(body));
987
+ }
988
+ return Promise.resolve(JsonDecoder.decode(body));
989
+ }
990
+ };
991
+
935
992
  // src/client/PayFlexV4Pos3DFormHttpClient.ts
936
993
  var PayFlexV4Pos3DFormHttpClient = class _PayFlexV4Pos3DFormHttpClient extends AbstractHttpClient {
937
994
  static API_NAME_GATEWAY_3D_API = "gateway_3d";
@@ -1104,17 +1161,17 @@ function randomHexString(length = 24) {
1104
1161
  }
1105
1162
 
1106
1163
  // src/crypt/AbstractCrypt.ts
1107
- function isContainer(value) {
1108
- if (Array.isArray(value)) return true;
1109
- if (value === null || typeof value !== "object") return false;
1110
- const proto = Object.getPrototypeOf(value);
1164
+ function isContainer(value2) {
1165
+ if (Array.isArray(value2)) return true;
1166
+ if (value2 === null || typeof value2 !== "object") return false;
1167
+ const proto = Object.getPrototypeOf(value2);
1111
1168
  return proto === Object.prototype || proto === null;
1112
1169
  }
1113
- function phpString(value) {
1114
- if (value === null || value === void 0 || value === false) return "";
1115
- if (value === true) return "1";
1116
- if (isContainer(value)) return "Array";
1117
- return String(value);
1170
+ function phpString(value2) {
1171
+ if (value2 === null || value2 === void 0 || value2 === false) return "";
1172
+ if (value2 === true) return "1";
1173
+ if (isContainer(value2)) return "Array";
1174
+ return String(value2);
1118
1175
  }
1119
1176
  var AbstractCrypt = class {
1120
1177
  /** Node `crypto.createHash` algorithm. */
@@ -1168,10 +1225,10 @@ var AbstractCrypt = class {
1168
1225
  }
1169
1226
  findIn(haystack, needle) {
1170
1227
  const isList = Array.isArray(haystack);
1171
- for (const [key, value] of Object.entries(haystack)) {
1172
- if (!isList && key === needle) return phpString(value);
1173
- if (isContainer(value)) {
1174
- const found = this.findIn(value, needle);
1228
+ for (const [key, value2] of Object.entries(haystack)) {
1229
+ if (!isList && key === needle) return phpString(value2);
1230
+ if (isContainer(value2)) {
1231
+ const found = this.findIn(value2, needle);
1175
1232
  if (found !== void 0) return found;
1176
1233
  }
1177
1234
  }
@@ -1181,10 +1238,10 @@ var AbstractCrypt = class {
1181
1238
 
1182
1239
  // src/crypt/AssecoPosCrypt.ts
1183
1240
  var EXCLUDED_KEYS = /* @__PURE__ */ new Set(["hash", "encoding", "nationalidno"]);
1184
- function phpString2(value) {
1185
- if (value === null || value === void 0 || value === false) return "";
1186
- if (value === true) return "1";
1187
- return String(value);
1241
+ function phpString2(value2) {
1242
+ if (value2 === null || value2 === void 0 || value2 === false) return "";
1243
+ if (value2 === true) return "1";
1244
+ return String(value2);
1188
1245
  }
1189
1246
  var AssecoPosCrypt = class extends AbstractCrypt {
1190
1247
  hashAlgorithm = "sha512";
@@ -1199,10 +1256,10 @@ var AssecoPosCrypt = class extends AbstractCrypt {
1199
1256
  * `nationalidno` (seen in Ziraat callbacks) must not be part of the hash string; confirmed by Asseco.
1200
1257
  */
1201
1258
  create3DHash(account, formInputs) {
1202
- const values = Object.entries(formInputs).sort(([a], [b]) => strnatcasecmp(a, b)).filter(([key]) => !EXCLUDED_KEYS.has(key.toLowerCase())).map(([, value]) => phpString2(value));
1259
+ const values = Object.entries(formInputs).sort(([a], [b]) => strnatcasecmp(a, b)).filter(([key]) => !EXCLUDED_KEYS.has(key.toLowerCase())).map(([, value2]) => phpString2(value2));
1203
1260
  values.push(account.getSecretKey());
1204
1261
  const escaped = values.map(
1205
- (value) => value.replaceAll("\\", "\\\\").replaceAll(this.hashSeparator, `\\${this.hashSeparator}`)
1262
+ (value2) => value2.replaceAll("\\", "\\\\").replaceAll(this.hashSeparator, `\\${this.hashSeparator}`)
1206
1263
  );
1207
1264
  return this.hashString(escaped.join(this.hashSeparator));
1208
1265
  }
@@ -1221,6 +1278,22 @@ var AssecoPosCrypt = class extends AbstractCrypt {
1221
1278
  }
1222
1279
  };
1223
1280
 
1281
+ // src/crypt/PayFlexCPV4PosCrypt.ts
1282
+ var PayFlexCPV4PosCrypt = class extends AbstractCrypt {
1283
+ static supports(gatewayClass) {
1284
+ return gatewayClass === "PayFlexCPV4Pos";
1285
+ }
1286
+ create3DHash(_account, _formInputs) {
1287
+ throw new NotImplementedError("Common payment has no 3D form hash.");
1288
+ }
1289
+ check3DHash(_account, _data) {
1290
+ throw new NotImplementedError("The common payment callback is confirmed by the query API.");
1291
+ }
1292
+ createHash(_account, _requestData) {
1293
+ throw new NotImplementedError("The common payment registration is sent without HashedData.");
1294
+ }
1295
+ };
1296
+
1224
1297
  // src/crypt/PayFlexV4PosCrypt.ts
1225
1298
  import { createHash as createHash2 } from "crypto";
1226
1299
  import iconv2 from "iconv-lite";
@@ -1259,11 +1332,11 @@ var PayFlexV4PosCrypt = class extends NullCrypt {
1259
1332
  if (hashKey === void 0) {
1260
1333
  return true;
1261
1334
  }
1262
- const field3 = (name) => {
1263
- const value = Object.hasOwn(data, name) ? data[name] : void 0;
1264
- return typeof value === "string" ? value : "";
1335
+ const field4 = (name) => {
1336
+ const value2 = Object.hasOwn(data, name) ? data[name] : void 0;
1337
+ return typeof value2 === "string" ? value2 : "";
1265
1338
  };
1266
- const hashString = field3("VerifyEnrollmentRequestId") + field3("MerchantId") + field3("PurchCurrency") + field3("PurchAmount").replaceAll(".", "") + field3("Eci").padStart(2, "0") + field3("Cavv") + field3("MdStatus") + field3("Status") + account.getPassword();
1339
+ const hashString = field4("VerifyEnrollmentRequestId") + field4("MerchantId") + field4("PurchCurrency") + field4("PurchAmount").replaceAll(".", "") + field4("Eci").padStart(2, "0") + field4("Cavv") + field4("MdStatus") + field4("Status") + account.getPassword();
1267
1340
  const expected = this.hashBytes(iconv2.encode(hashString, "ISO-8859-9"));
1268
1341
  if (timingSafeEqualStr(data[hashKey], expected)) {
1269
1342
  this.logger.debug("hash check is successful");
@@ -1278,22 +1351,22 @@ var PayFlexV4PosCrypt = class extends NullCrypt {
1278
1351
  };
1279
1352
 
1280
1353
  // src/util/required.ts
1281
- function isSet(value) {
1282
- return value !== void 0 && value !== null;
1354
+ function isSet(value2) {
1355
+ return value2 !== void 0 && value2 !== null;
1283
1356
  }
1284
1357
  function required(order, key) {
1285
- const value = order[key];
1286
- if (!isSet(value) || value === "") {
1358
+ const value2 = order[key];
1359
+ if (!isSet(value2) || value2 === "") {
1287
1360
  throw new PosError(`Order field "${String(key)}" is required`);
1288
1361
  }
1289
- return value;
1362
+ return value2;
1290
1363
  }
1291
1364
  function requiredString(data, key, what) {
1292
- const value = data[key];
1293
- if (!isSet(value) || value === "") {
1365
+ const value2 = data[key];
1366
+ if (!isSet(value2) || value2 === "") {
1294
1367
  throw new PosError(`${what} field "${key}" is required`);
1295
1368
  }
1296
- return String(value);
1369
+ return String(value2);
1297
1370
  }
1298
1371
 
1299
1372
  // src/hooks.ts
@@ -1530,6 +1603,130 @@ var AssecoPosRequestDataMapper = class extends AbstractRequestDataMapper {
1530
1603
  }
1531
1604
  };
1532
1605
 
1606
+ // src/data-mapper/request/mapper/PayFlexCPV4PosRequestDataMapper.ts
1607
+ var ORDER_ID_PATTERN = /^[0-9a-zA-Z-]+$/;
1608
+ var TRANSACTION_ID_PATTERN = /^[0-9A-Za-z-]{1,40}$/;
1609
+ var PayFlexCPV4PosRequestDataMapper = class extends AbstractRequestDataMapper {
1610
+ static supports(gatewayClass) {
1611
+ return gatewayClass === "PayFlexCPV4Pos";
1612
+ }
1613
+ create3DPaymentRequestData(_account, _order, _txType, _responseData, _creditCard = null) {
1614
+ throw new NotImplementedError("Common payment completes the payment on the bank page");
1615
+ }
1616
+ /**
1617
+ * Query (GetVposTransaction) body built from the callback data. At least one of `TransactionId` / `PaymentToken`
1618
+ * is needed (VakifBank Common Payment guide v2.1 §6.5).
1619
+ */
1620
+ create3DPaymentStatusRequestData(account, responseData) {
1621
+ return this.createQueryData(account, responseData.TransactionId, responseData.PaymentToken, "3D response");
1622
+ }
1623
+ /**
1624
+ * Registration (CreateToken) body. Field set and the `MerchantId` rule follow VakifBank Common Payment guide
1625
+ * v2.1 §4/§5: `MerchantId` is `1`, or the sub merchant id for sub-dealer accounts.
1626
+ */
1627
+ create3DFormInitializeRequestData(account, order, _paymentModel, txType, creditCard = null) {
1628
+ const orderId = String(required(order, "id"));
1629
+ if (!ORDER_ID_PATTERN.test(orderId)) {
1630
+ throw new PosError('Order field "id" may only contain digits, letters and hyphens');
1631
+ }
1632
+ let transactionId;
1633
+ if (isSet(order.transaction_id) && order.transaction_id !== "") {
1634
+ transactionId = order.transaction_id;
1635
+ if (!TRANSACTION_ID_PATTERN.test(transactionId)) {
1636
+ throw new PosError('Order field "transaction_id" must be 1-40 characters of digits, letters and hyphens');
1637
+ }
1638
+ } else {
1639
+ transactionId = this.crypt.generateRandomString(32);
1640
+ }
1641
+ const requestData = {
1642
+ HostMerchantId: account.getMerchantId(),
1643
+ MerchantId: this.getMerchantId(account),
1644
+ MerchantPassword: account.getPassword(),
1645
+ HostTerminalId: account.getTerminalId(),
1646
+ TransactionType: this.valueMapper.mapTxType(txType),
1647
+ TransactionId: transactionId,
1648
+ AmountCode: String(this.valueMapper.mapCurrency(order.currency ?? CURRENCY.TRY)),
1649
+ Amount: String(this.valueFormatter.formatAmount(required(order, "amount"))),
1650
+ OrderId: orderId,
1651
+ // 3D is always applied; "Half Secure" (AllowNotEnrolledCard true) can be opted into with a request hook.
1652
+ IsSecure: "true",
1653
+ AllowNotEnrolledCard: "false",
1654
+ SuccessUrl: required(order, "success_url"),
1655
+ FailUrl: required(order, "fail_url"),
1656
+ RequestLanguage: this.getLang(order),
1657
+ // printed on the card holder statement
1658
+ Extract: "",
1659
+ // merchant defined extra items
1660
+ CustomItems: ""
1661
+ };
1662
+ if (creditCard !== null) {
1663
+ const cardType = creditCard.getType();
1664
+ requestData.BrandNumber = cardType !== null ? this.valueMapper.mapCardType(cardType) : "";
1665
+ requestData.CVV = creditCard.getCvv();
1666
+ requestData.PAN = creditCard.getNumber();
1667
+ requestData.ExpireMonth = this.valueFormatter.formatCardExpDate(creditCard, "ExpireMonth");
1668
+ requestData.ExpireYear = this.valueFormatter.formatCardExpDate(creditCard, "ExpireYear");
1669
+ requestData.CardHoldersName = creditCard.getHolderName() ?? "";
1670
+ }
1671
+ if (order.installment) {
1672
+ requestData.InstallmentCount = String(this.valueFormatter.formatInstallment(order.installment));
1673
+ }
1674
+ return requestData;
1675
+ }
1676
+ createNonSecurePaymentRequestData(_account, _order, _txType, _creditCard) {
1677
+ throw new NotImplementedError("Common payment has no non-secure payment");
1678
+ }
1679
+ createNonSecurePostAuthPaymentRequestData(_account, _order) {
1680
+ throw new NotImplementedError("Common payment has no post authorization");
1681
+ }
1682
+ /** Query (GetVposTransaction) body from the order's `transaction_id` / `payment_token`. */
1683
+ createStatusRequestData(account, order) {
1684
+ return this.createQueryData(account, order.transaction_id, order.payment_token, "Order");
1685
+ }
1686
+ createCancelRequestData(_account, _order) {
1687
+ throw new NotImplementedError("Common payment has no cancel");
1688
+ }
1689
+ createRefundRequestData(_account, _order, _refundTxType) {
1690
+ throw new NotImplementedError("Common payment has no refund");
1691
+ }
1692
+ createOrderHistoryRequestData(_account, _order) {
1693
+ throw new NotImplementedError("Common payment has no order history");
1694
+ }
1695
+ /** The browser is sent to the bank page with a GET carrying the payment token; no hash is calculated. */
1696
+ async create3DFormData(_account, _order, _paymentModel, _txType, _gatewayURL, _creditCard = null, extraData = null) {
1697
+ if (extraData === null) {
1698
+ throw new PosError("extraData can not be null");
1699
+ }
1700
+ return {
1701
+ gateway: requiredString(extraData, "CommonPaymentUrl", "3D response"),
1702
+ method: "GET",
1703
+ inputs: { Ptkn: requiredString(extraData, "PaymentToken", "3D response") }
1704
+ };
1705
+ }
1706
+ getMerchantId(account) {
1707
+ const sub2 = account.getSubMerchantId();
1708
+ return account.isSubBranch() && sub2 ? sub2 : "1";
1709
+ }
1710
+ createQueryData(account, transactionId, paymentToken, what) {
1711
+ const data = {
1712
+ HostMerchantId: account.getMerchantId(),
1713
+ MerchantId: this.getMerchantId(account),
1714
+ Password: account.getPassword()
1715
+ };
1716
+ if (typeof transactionId === "string" && transactionId !== "") {
1717
+ data.TransactionId = transactionId;
1718
+ }
1719
+ if (typeof paymentToken === "string" && paymentToken !== "") {
1720
+ data.PaymentToken = paymentToken;
1721
+ }
1722
+ if (data.TransactionId === void 0 && data.PaymentToken === void 0) {
1723
+ const [a, b] = what === "Order" ? ["transaction_id", "payment_token"] : ["TransactionId", "PaymentToken"];
1724
+ throw new PosError(`${what} field "${a}" or "${b}" is required`);
1725
+ }
1726
+ return data;
1727
+ }
1728
+ };
1729
+
1533
1730
  // src/data-mapper/request/mapper/PayFlexV4PosRequestDataMapper.ts
1534
1731
  var PayFlexV4PosRequestDataMapper = class extends AbstractRequestDataMapper {
1535
1732
  static supports(gatewayClass) {
@@ -1750,7 +1947,7 @@ var AssecoPosRequestValueFormatter = class {
1750
1947
  }
1751
1948
  };
1752
1949
 
1753
- // src/data-mapper/request/value-formatter/PayFlexV4PosRequestValueFormatter.ts
1950
+ // src/util/numberFormat2.ts
1754
1951
  var MAX_AMOUNT = 1e13;
1755
1952
  function numberFormat2(amount) {
1756
1953
  if (!Number.isFinite(amount) || Math.abs(amount) >= MAX_AMOUNT) {
@@ -1759,9 +1956,42 @@ function numberFormat2(amount) {
1759
1956
  const magnitude = Math.abs(amount);
1760
1957
  const floor = Math.floor(magnitude * 100);
1761
1958
  const cents = magnitude >= (floor + 0.5) / 100 ? floor + 1 : floor;
1762
- const text5 = (cents / 100).toFixed(2);
1763
- return amount < 0 && cents !== 0 ? `-${text5}` : text5;
1959
+ const text6 = (cents / 100).toFixed(2);
1960
+ return amount < 0 && cents !== 0 ? `-${text6}` : text6;
1764
1961
  }
1962
+
1963
+ // src/data-mapper/request/value-formatter/PayFlexCPV4PosRequestValueFormatter.ts
1964
+ var PayFlexCPV4PosRequestValueFormatter = class {
1965
+ static supports(gatewayClass) {
1966
+ return gatewayClass === "PayFlexCPV4Pos";
1967
+ }
1968
+ /** 0 => '0', 1 => '0', 2 => '2' */
1969
+ formatInstallment(installment) {
1970
+ return installment > 1 ? String(installment) : "0";
1971
+ }
1972
+ /** ex: 10.1 => '10.10' */
1973
+ formatAmount(amount, _txType = null) {
1974
+ return numberFormat2(amount);
1975
+ }
1976
+ /** 'ExpireMonth' => 'm' (04), 'ExpireYear' => 'Y' (2024, four digits per guide section 4), 'Expiry' => 'Ym' (202404) */
1977
+ formatCardExpDate(card, fieldName) {
1978
+ if (fieldName === "ExpireMonth") {
1979
+ return card.getExpirationDate("m");
1980
+ }
1981
+ if (fieldName === "ExpireYear") {
1982
+ return card.getExpirationDate("Y");
1983
+ }
1984
+ if (fieldName === "Expiry") {
1985
+ return card.getExpirationDate("Ym");
1986
+ }
1987
+ throw new PosError("Unsupported field name");
1988
+ }
1989
+ formatDateTime(_dateTime, _fieldName = null) {
1990
+ throw new NotImplementedError("Date formatting is not supported.");
1991
+ }
1992
+ };
1993
+
1994
+ // src/data-mapper/request/value-formatter/PayFlexV4PosRequestValueFormatter.ts
1765
1995
  function istanbulParts(dateTime) {
1766
1996
  const parts = new Intl.DateTimeFormat("en-US", {
1767
1997
  timeZone: "Europe/Istanbul",
@@ -1811,11 +2041,11 @@ function ownValue(obj, key) {
1811
2041
 
1812
2042
  // src/data-mapper/request/value-mapper/AbstractRequestValueMapper.ts
1813
2043
  function requireMapped(table, key, what) {
1814
- const value = ownValue(table, key);
1815
- if (value === void 0) {
2044
+ const value2 = ownValue(table, key);
2045
+ if (value2 === void 0) {
1816
2046
  throw new PosError(`${what} "${key}" is not mapped.`);
1817
2047
  }
1818
- return value;
2048
+ return value2;
1819
2049
  }
1820
2050
  var AbstractRequestValueMapper = class {
1821
2051
  cardTypeMappings = {};
@@ -1942,6 +2172,35 @@ var AssecoPosRequestValueMapper = class extends AbstractRequestValueMapper {
1942
2172
  }
1943
2173
  };
1944
2174
 
2175
+ // src/data-mapper/request/value-mapper/PayFlexCPV4PosRequestValueMapper.ts
2176
+ var PayFlexCPV4PosRequestValueMapper = class extends AbstractRequestValueMapper {
2177
+ cardTypeMappings = {
2178
+ [CARD_TYPE.VISA]: "100",
2179
+ [CARD_TYPE.MASTERCARD]: "200",
2180
+ [CARD_TYPE.TROY]: "300",
2181
+ [CARD_TYPE.AMEX]: "400"
2182
+ };
2183
+ txTypeMappings = {
2184
+ [TX_TYPE.PAY_AUTH]: "Sale",
2185
+ [TX_TYPE.PAY_PRE_AUTH]: "Auth",
2186
+ [TX_TYPE.PAY_POST_AUTH]: "Capture",
2187
+ [TX_TYPE.CANCEL]: "Cancel",
2188
+ [TX_TYPE.REFUND]: "Refund",
2189
+ [TX_TYPE.REFUND_PARTIAL]: "Refund",
2190
+ [TX_TYPE.STATUS]: "OrderInquiry"
2191
+ };
2192
+ langMappings = {
2193
+ [LANG.TR]: "tr-TR",
2194
+ [LANG.EN]: "en-US"
2195
+ };
2196
+ static supports(gatewayClass) {
2197
+ return gatewayClass === "PayFlexCPV4Pos";
2198
+ }
2199
+ mapCurrency(currency) {
2200
+ return String(super.mapCurrency(currency));
2201
+ }
2202
+ };
2203
+
1945
2204
  // src/data-mapper/request/value-mapper/PayFlexV4PosRequestValueMapper.ts
1946
2205
  var PayFlexV4PosRequestValueMapper = class extends AbstractRequestValueMapper {
1947
2206
  cardTypeMappings = {
@@ -1978,16 +2237,16 @@ var TX_DECLINED = "declined";
1978
2237
 
1979
2238
  // src/data-mapper/response/mapper/AbstractResponseDataMapper.ts
1980
2239
  var PHP_TRIM_CHARS = /* @__PURE__ */ new Set([" ", " ", "\n", "\r", "\0", "\v"]);
1981
- function phpTrim(value) {
2240
+ function phpTrim(value2) {
1982
2241
  let start = 0;
1983
- let end = value.length;
1984
- while (start < end && PHP_TRIM_CHARS.has(value.charAt(start))) start++;
1985
- while (end > start && PHP_TRIM_CHARS.has(value.charAt(end - 1))) end--;
1986
- return value.slice(start, end);
1987
- }
1988
- function isPlainObject(value) {
1989
- if (value === null || typeof value !== "object") return false;
1990
- const proto = Object.getPrototypeOf(value);
2242
+ let end = value2.length;
2243
+ while (start < end && PHP_TRIM_CHARS.has(value2.charAt(start))) start++;
2244
+ while (end > start && PHP_TRIM_CHARS.has(value2.charAt(end - 1))) end--;
2245
+ return value2.slice(start, end);
2246
+ }
2247
+ function isPlainObject(value2) {
2248
+ if (value2 === null || typeof value2 !== "object") return false;
2249
+ const proto = Object.getPrototypeOf(value2);
1991
2250
  return proto === Object.prototype || proto === null;
1992
2251
  }
1993
2252
  var AbstractResponseDataMapper = class {
@@ -2099,8 +2358,8 @@ var AbstractResponseDataMapper = class {
2099
2358
  }
2100
2359
  if (isPlainObject(data)) {
2101
2360
  const result = {};
2102
- for (const [key, value] of Object.entries(data)) {
2103
- result[key] = this.emptyStringsToNull(value);
2361
+ for (const [key, value2] of Object.entries(data)) {
2362
+ result[key] = this.emptyStringsToNull(value2);
2104
2363
  }
2105
2364
  return result;
2106
2365
  }
@@ -2116,21 +2375,21 @@ function field(data, key) {
2116
2375
  return null;
2117
2376
  }
2118
2377
  function text2(data, key) {
2119
- const value = field(data, key);
2120
- if (value === null) return null;
2121
- return typeof value === "string" ? value : String(value);
2378
+ const value2 = field(data, key);
2379
+ if (value2 === null) return null;
2380
+ return typeof value2 === "string" ? value2 : String(value2);
2122
2381
  }
2123
- function phpInt(value) {
2124
- if (value === null) return 0;
2125
- const n = Number.parseInt(value.trim(), 10);
2382
+ function phpInt(value2) {
2383
+ if (value2 === null) return 0;
2384
+ const n = Number.parseInt(value2.trim(), 10);
2126
2385
  return Number.isNaN(n) ? 0 : n;
2127
2386
  }
2128
- function greaterThanZero(value) {
2129
- const trimmed = value.trim();
2387
+ function greaterThanZero(value2) {
2388
+ const trimmed = value2.trim();
2130
2389
  if (trimmed !== "" && Number.isFinite(Number(trimmed))) {
2131
2390
  return Number(trimmed) > 0;
2132
2391
  }
2133
- return value > "0";
2392
+ return value2 > "0";
2134
2393
  }
2135
2394
  var AssecoPosResponseDataMapper = class extends AbstractResponseDataMapper {
2136
2395
  static supports(gatewayClass) {
@@ -2468,8 +2727,8 @@ var AssecoPosResponseDataMapper = class extends AbstractResponseDataMapper {
2468
2727
  mapCurrency(raw, txType) {
2469
2728
  return this.valueMapper.mapCurrency(text2(raw, "currency") ?? "", txType);
2470
2729
  }
2471
- formatOptionalDateTime(value, txType) {
2472
- return value === null ? null : this.valueFormatter.formatDateTime(value, txType);
2730
+ formatOptionalDateTime(value2, txType) {
2731
+ return value2 === null ? null : this.valueFormatter.formatDateTime(value2, txType);
2473
2732
  }
2474
2733
  mapSingleOrderHistoryTransaction(rawTxData) {
2475
2734
  const txType = TX_TYPE.ORDER_HISTORY;
@@ -2529,23 +2788,180 @@ var AssecoPosResponseDataMapper = class extends AbstractResponseDataMapper {
2529
2788
  }
2530
2789
  };
2531
2790
 
2791
+ // src/data-mapper/response/mapper/PayFlexCPV4PosResponseDataMapper.ts
2792
+ function field2(data, key) {
2793
+ if (data !== null && typeof data === "object" && !Array.isArray(data) && Object.hasOwn(data, key)) {
2794
+ return data[key] ?? null;
2795
+ }
2796
+ return null;
2797
+ }
2798
+ function text3(data, key) {
2799
+ const value2 = field2(data, key);
2800
+ if (value2 === null) return null;
2801
+ return typeof value2 === "string" ? value2 : String(value2);
2802
+ }
2803
+ function firstText(data, ...keys) {
2804
+ for (const key of keys) {
2805
+ const value2 = text3(data, key);
2806
+ if (value2 !== null) return value2;
2807
+ }
2808
+ return null;
2809
+ }
2810
+ function normalizeAmount(value2) {
2811
+ if (typeof value2 === "string" && /^\d+,\d{1,2}$/.test(value2)) {
2812
+ return value2.replace(",", ".");
2813
+ }
2814
+ return value2;
2815
+ }
2816
+ var PayFlexCPV4PosResponseDataMapper = class _PayFlexCPV4PosResponseDataMapper extends AbstractResponseDataMapper {
2817
+ static PROCEDURE_SUCCESS_CODE = "0000";
2818
+ static supports(gatewayClass) {
2819
+ return gatewayClass === "PayFlexCPV4Pos";
2820
+ }
2821
+ map3DPaymentData(_raw3DAuthResponseData, _rawPaymentResponseData, _txType, _order) {
2822
+ throw new NotImplementedError("Common Payment has no separate 3D payment step");
2823
+ }
2824
+ map3DPayResponseData(raw3DAuthResponseData, txType, _order) {
2825
+ const raw = this.emptyStringsToNull(raw3DAuthResponseData);
2826
+ const response = this.getCommonPaymentResponse(raw, txType, MODEL.THREE_D_PAY);
2827
+ response.md_status = null;
2828
+ response.md_error_message = null;
2829
+ response.transaction_security = null;
2830
+ response.transaction_id = field2(raw, "TransactionId");
2831
+ response.masked_number = field2(raw, "MaskedPan");
2832
+ if (response.status === TX_APPROVED) {
2833
+ const amount = normalizeAmount(field2(raw, "Amount"));
2834
+ const bankTxType = text3(raw, "TransactionType");
2835
+ const amountCode = text3(raw, "AmountCode");
2836
+ const hostDate = text3(raw, "HostDate");
2837
+ response.auth_code = firstText(raw, "AuthCode", "AuthorizeId");
2838
+ response.ref_ret_num = field2(raw, "TransactionId");
2839
+ response.order_id = firstText(raw, "OrderID", "OrderId");
2840
+ response.currency = amountCode !== null ? this.valueMapper.mapCurrency(amountCode, txType) : null;
2841
+ response.amount = this.formatAmount(amount, txType);
2842
+ response.transaction_type = bankTxType !== null ? this.valueMapper.mapTxType(bankTxType) : null;
2843
+ response.installment_count = this.valueFormatter.formatInstallment(text3(raw, "InstallmentCount"), txType);
2844
+ response.transaction_time = this.formatHostDate(hostDate, txType);
2845
+ }
2846
+ return response;
2847
+ }
2848
+ map3DHostResponseData(raw3DAuthResponseData, txType, order) {
2849
+ const response = this.map3DPayResponseData(raw3DAuthResponseData, txType, order);
2850
+ response.payment_model = MODEL.THREE_D_HOST;
2851
+ return response;
2852
+ }
2853
+ mapRefundResponse(_rawResponseData) {
2854
+ throw new NotImplementedError("Refund is not supported by Common Payment");
2855
+ }
2856
+ mapCancelResponse(_rawResponseData) {
2857
+ throw new NotImplementedError("Cancel is not supported by Common Payment");
2858
+ }
2859
+ /** Maps the transaction query answer (VakifBank Common Payment guide v2.1 §6.5). */
2860
+ mapStatusResponse(rawResponseData) {
2861
+ const txType = TX_TYPE.STATUS;
2862
+ const raw = this.emptyStringsToNull(rawResponseData);
2863
+ const response = this.getDefaultStatusResponse(raw);
2864
+ const { status, procCode, errorMessage } = this.resolveOutcome(raw);
2865
+ response.status = status;
2866
+ response.proc_return_code = procCode;
2867
+ response.error_code = status === TX_DECLINED ? procCode : null;
2868
+ response.error_message = errorMessage;
2869
+ if (status === TX_APPROVED) {
2870
+ const amount = normalizeAmount(field2(raw, "Amount"));
2871
+ const bankTxType = text3(raw, "TransactionType");
2872
+ const amountCode = text3(raw, "AmountCode");
2873
+ const hostDate = text3(raw, "HostDate");
2874
+ response.order_id = firstText(raw, "OrderID", "OrderId");
2875
+ response.auth_code = firstText(raw, "AuthCode", "AuthorizeId");
2876
+ response.transaction_id = field2(raw, "TransactionId");
2877
+ response.ref_ret_num = field2(raw, "Rrn");
2878
+ response.transaction_time = this.formatHostDate(hostDate, txType);
2879
+ response.transaction_type = bankTxType !== null ? this.valueMapper.mapTxType(bankTxType) : null;
2880
+ response.first_amount = this.formatAmount(amount, txType);
2881
+ response.currency = amountCode !== null ? this.valueMapper.mapCurrency(amountCode, txType) : null;
2882
+ response.masked_number = field2(raw, "MaskedPan");
2883
+ response.installment_count = this.valueFormatter.formatInstallment(text3(raw, "InstallmentCount"), txType);
2884
+ }
2885
+ return response;
2886
+ }
2887
+ mapPaymentResponse(_rawPaymentResponseData, _txType, _order) {
2888
+ throw new NotImplementedError("Common Payment has no direct payment API");
2889
+ }
2890
+ mapOrderHistoryResponse(_rawResponseData) {
2891
+ throw new NotImplementedError("Order history is not supported by Common Payment");
2892
+ }
2893
+ is3dAuthSuccess(_mdStatus) {
2894
+ return true;
2895
+ }
2896
+ extractMdStatus(_raw3DAuthResponseData) {
2897
+ return null;
2898
+ }
2899
+ getProcReturnCode(response) {
2900
+ return firstText(response, "Rc", "ResultCode");
2901
+ }
2902
+ /**
2903
+ * Only a string or number amount is formatted; anything else maps to null. The gateway binds the raw answer
2904
+ * amount, so a malformed value fails the binding instead of throwing here.
2905
+ */
2906
+ formatAmount(amount, txType) {
2907
+ return typeof amount === "string" || typeof amount === "number" ? this.valueFormatter.formatAmount(amount, txType) : null;
2908
+ }
2909
+ /** `HostDate` is informational: an unknown format gives null and a warning instead of failing the mapping. */
2910
+ formatHostDate(hostDate, txType) {
2911
+ if (hostDate === null) return null;
2912
+ try {
2913
+ return this.valueFormatter.formatDateTime(hostDate, txType);
2914
+ } catch (e) {
2915
+ if (!(e instanceof PosError)) throw e;
2916
+ this.logger.warn("unrecognized HostDate format in the transaction query answer", { HostDate: hostDate });
2917
+ return null;
2918
+ }
2919
+ }
2920
+ /** Status, procedure code and message shared by the callback and query mappings. */
2921
+ resolveOutcome(raw) {
2922
+ const errorCode = text3(raw, "ErrorCode");
2923
+ if (errorCode !== null) {
2924
+ return {
2925
+ status: TX_DECLINED,
2926
+ procCode: errorCode,
2927
+ errorMessage: firstText(raw, "Message", "ResultDescription", "ResponseMessage")
2928
+ };
2929
+ }
2930
+ const procCode = this.getProcReturnCode(raw);
2931
+ if (procCode === _PayFlexCPV4PosResponseDataMapper.PROCEDURE_SUCCESS_CODE) {
2932
+ return { status: TX_APPROVED, procCode, errorMessage: null };
2933
+ }
2934
+ return { status: TX_DECLINED, procCode, errorMessage: firstText(raw, "Message", "ResultDescription") };
2935
+ }
2936
+ getCommonPaymentResponse(raw, txType, paymentModel) {
2937
+ const { status, procCode, errorMessage } = this.resolveOutcome(raw);
2938
+ const response = this.getDefaultPaymentResponse(txType, paymentModel);
2939
+ response.proc_return_code = procCode;
2940
+ response.status = status;
2941
+ response.error_code = status === TX_DECLINED ? procCode : null;
2942
+ response.error_message = errorMessage;
2943
+ response.all = raw;
2944
+ return response;
2945
+ }
2946
+ };
2947
+
2532
2948
  // src/data-mapper/response/mapper/PayFlexV4PosResponseDataMapper.ts
2533
2949
  var FULL_3D_ECI = /* @__PURE__ */ new Set(["02", "05"]);
2534
2950
  var BANK_TIME_OFFSET_MS = 3 * 60 * 60 * 1e3;
2535
- function field2(data, key) {
2951
+ function field3(data, key) {
2536
2952
  if (data !== null && typeof data === "object" && !Array.isArray(data) && Object.hasOwn(data, key)) {
2537
2953
  return data[key] ?? null;
2538
2954
  }
2539
2955
  return null;
2540
2956
  }
2541
- function text3(data, key) {
2542
- const value = field2(data, key);
2543
- if (value === null) return null;
2544
- return typeof value === "string" ? value : String(value);
2957
+ function text4(data, key) {
2958
+ const value2 = field3(data, key);
2959
+ if (value2 === null) return null;
2960
+ return typeof value2 === "string" ? value2 : String(value2);
2545
2961
  }
2546
2962
  function record(data, key) {
2547
- const value = field2(data, key);
2548
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
2963
+ const value2 = field3(data, key);
2964
+ return value2 !== null && typeof value2 === "object" && !Array.isArray(value2) ? value2 : {};
2549
2965
  }
2550
2966
  var PayFlexV4PosResponseDataMapper = class _PayFlexV4PosResponseDataMapper extends AbstractResponseDataMapper {
2551
2967
  static PROCEDURE_SUCCESS_CODE = "0000";
@@ -2563,19 +2979,19 @@ var PayFlexV4PosResponseDataMapper = class _PayFlexV4PosResponseDataMapper exten
2563
2979
  const threeDAuthStatus = authSuccess ? TX_APPROVED : TX_DECLINED;
2564
2980
  const declined = threeDAuthStatus === TX_DECLINED;
2565
2981
  const paymentResponseData = authSuccess && rawPaymentResponseData !== null ? this.mapPaymentResponse(rawPaymentResponseData, txType, order) : this.getDefaultPaymentResponse(txType, null);
2566
- const purchCurrency = text3(raw, "PurchCurrency");
2982
+ const purchCurrency = text4(raw, "PurchCurrency");
2567
2983
  const threeDResponse = {
2568
- eci: field2(raw, "Eci"),
2569
- cavv: field2(raw, "Cavv"),
2984
+ eci: field3(raw, "Eci"),
2985
+ cavv: field3(raw, "Cavv"),
2570
2986
  auth_code: null,
2571
- order_id: field2(raw, "VerifyEnrollmentRequestId"),
2987
+ order_id: field3(raw, "VerifyEnrollmentRequestId"),
2572
2988
  status: threeDAuthStatus,
2573
2989
  currency: paymentResponseData.currency ?? (purchCurrency !== null ? this.valueMapper.mapCurrency(purchCurrency, txType) : null),
2574
- installment_count: paymentResponseData.installment_count ?? this.valueFormatter.formatInstallment(text3(raw, "InstallmentCount"), txType),
2575
- error_code: declined ? field2(raw, "ErrorCode") : null,
2576
- error_message: declined ? field2(raw, "ErrorMessage") : null,
2990
+ installment_count: paymentResponseData.installment_count ?? this.valueFormatter.formatInstallment(text4(raw, "InstallmentCount"), txType),
2991
+ error_code: declined ? field3(raw, "ErrorCode") : null,
2992
+ error_message: declined ? field3(raw, "ErrorMessage") : null,
2577
2993
  md_status: mdStatus,
2578
- md_error_message: declined ? field2(raw, "ErrorMessage") : null,
2994
+ md_error_message: declined ? field3(raw, "ErrorMessage") : null,
2579
2995
  transaction_security: null,
2580
2996
  all: rawPaymentResponseData,
2581
2997
  "3d_all": raw
@@ -2597,13 +3013,13 @@ var PayFlexV4PosResponseDataMapper = class _PayFlexV4PosResponseDataMapper exten
2597
3013
  const status = resultCode === _PayFlexV4PosResponseDataMapper.PROCEDURE_SUCCESS_CODE ? TX_APPROVED : TX_DECLINED;
2598
3014
  const declined = status === TX_DECLINED;
2599
3015
  return {
2600
- order_id: field2(raw, "TransactionId"),
2601
- auth_code: declined ? null : field2(raw, "AuthCode"),
2602
- ref_ret_num: field2(raw, "Rrn"),
3016
+ order_id: field3(raw, "TransactionId"),
3017
+ auth_code: declined ? null : field3(raw, "AuthCode"),
3018
+ ref_ret_num: field3(raw, "Rrn"),
2603
3019
  proc_return_code: resultCode,
2604
- transaction_id: field2(raw, "TransactionId"),
3020
+ transaction_id: field3(raw, "TransactionId"),
2605
3021
  error_code: declined ? resultCode : null,
2606
- error_message: declined ? field2(raw, "ResultDetail") : null,
3022
+ error_message: declined ? field3(raw, "ResultDetail") : null,
2607
3023
  status,
2608
3024
  all: raw
2609
3025
  };
@@ -2612,65 +3028,65 @@ var PayFlexV4PosResponseDataMapper = class _PayFlexV4PosResponseDataMapper exten
2612
3028
  const txType = TX_TYPE.STATUS;
2613
3029
  const raw = this.emptyStringsToNull(rawResponseData);
2614
3030
  const responseInfo = record(raw, "ResponseInfo");
2615
- const procReturnCode = text3(responseInfo, "ResponseCode");
3031
+ const procReturnCode = text4(responseInfo, "ResponseCode");
2616
3032
  const defaultResponse = this.getDefaultStatusResponse(raw);
2617
3033
  defaultResponse.proc_return_code = procReturnCode;
2618
3034
  const status = procReturnCode === _PayFlexV4PosResponseDataMapper.PROCEDURE_SUCCESS_CODE ? TX_APPROVED : TX_DECLINED;
2619
3035
  defaultResponse.status = status;
2620
3036
  if (status === TX_DECLINED) {
2621
3037
  defaultResponse.error_code = procReturnCode;
2622
- defaultResponse.error_message = text3(responseInfo, "ResponseMessage");
3038
+ defaultResponse.error_message = text4(responseInfo, "ResponseMessage");
2623
3039
  return defaultResponse;
2624
3040
  }
2625
3041
  const txResultInfo = record(record(raw, "TransactionSearchResultInfo"), "TransactionSearchResultInfo");
2626
3042
  const orderProcCode = this.getProcReturnCode(txResultInfo);
2627
3043
  let orderStatus = PAYMENT_STATUS.PAYMENT_COMPLETED;
2628
- if (field2(txResultInfo, "IsCanceled") === "true") {
3044
+ if (field3(txResultInfo, "IsCanceled") === "true") {
2629
3045
  orderStatus = PAYMENT_STATUS.CANCELED;
2630
- } else if (field2(txResultInfo, "IsReversed") === "true") {
3046
+ } else if (field3(txResultInfo, "IsReversed") === "true") {
2631
3047
  orderStatus = "REVERSED";
2632
- } else if (field2(txResultInfo, "IsRefunded") === "true") {
3048
+ } else if (field3(txResultInfo, "IsRefunded") === "true") {
2633
3049
  orderStatus = PAYMENT_STATUS.FULLY_REFUNDED;
2634
3050
  }
2635
3051
  const orderApproved = orderProcCode === _PayFlexV4PosResponseDataMapper.PROCEDURE_SUCCESS_CODE;
2636
- const bankTxType = text3(txResultInfo, "TransactionType");
2637
- const amountCode = text3(txResultInfo, "AmountCode");
2638
- const amount = text3(txResultInfo, "CurrencyAmount") ?? text3(txResultInfo, "Amount");
2639
- defaultResponse.order_id = text3(txResultInfo, "OrderId");
2640
- defaultResponse.auth_code = field2(txResultInfo, "AuthCode");
2641
- defaultResponse.transaction_id = field2(txResultInfo, "TransactionId");
2642
- defaultResponse.ref_ret_num = field2(txResultInfo, "Rrn");
3052
+ const bankTxType = text4(txResultInfo, "TransactionType");
3053
+ const amountCode = text4(txResultInfo, "AmountCode");
3054
+ const amount = text4(txResultInfo, "CurrencyAmount") ?? text4(txResultInfo, "Amount");
3055
+ defaultResponse.order_id = text4(txResultInfo, "OrderId");
3056
+ defaultResponse.auth_code = field3(txResultInfo, "AuthCode");
3057
+ defaultResponse.transaction_id = field3(txResultInfo, "TransactionId");
3058
+ defaultResponse.ref_ret_num = field3(txResultInfo, "Rrn");
2643
3059
  defaultResponse.order_status = orderStatus;
2644
3060
  defaultResponse.transaction_type = bankTxType !== null ? this.valueMapper.mapTxType(bankTxType) : null;
2645
3061
  defaultResponse.currency = amountCode !== null ? this.valueMapper.mapCurrency(amountCode, txType) : null;
2646
3062
  defaultResponse.first_amount = amount !== null ? this.valueFormatter.formatAmount(amount, txType) : null;
2647
3063
  defaultResponse.capture_amount = null;
2648
3064
  defaultResponse.status = orderApproved ? TX_APPROVED : TX_DECLINED;
2649
- defaultResponse.error_code = orderApproved ? null : text3(txResultInfo, "HostResultCode");
2650
- defaultResponse.error_message = orderApproved ? null : text3(txResultInfo, "ResponseMessage");
3065
+ defaultResponse.error_code = orderApproved ? null : text4(txResultInfo, "HostResultCode");
3066
+ defaultResponse.error_message = orderApproved ? null : text4(txResultInfo, "ResponseMessage");
2651
3067
  return defaultResponse;
2652
3068
  }
2653
3069
  mapPaymentResponse(rawPaymentResponseData, txType, _order) {
2654
3070
  this.logger.debug("mapping payment response", [rawPaymentResponseData]);
2655
3071
  const raw = this.emptyStringsToNull(rawPaymentResponseData);
2656
3072
  const commonResponse = this.getCommonPaymentResponse(raw, txType);
2657
- const currencyCode = text3(raw, "CurrencyCode");
2658
- const tlAmount = field2(raw, "TLAmount");
2659
- const bankTxType = text3(raw, "TransactionType");
2660
- commonResponse.order_id = text3(raw, "OrderId");
3073
+ const currencyCode = text4(raw, "CurrencyCode");
3074
+ const tlAmount = field3(raw, "TLAmount");
3075
+ const bankTxType = text4(raw, "TransactionType");
3076
+ commonResponse.order_id = text4(raw, "OrderId");
2661
3077
  commonResponse.currency = currencyCode !== null ? this.valueMapper.mapCurrency(currencyCode, txType) : null;
2662
3078
  commonResponse.amount = tlAmount !== null ? this.valueFormatter.formatAmount(tlAmount, txType) : null;
2663
3079
  commonResponse.transaction_type = bankTxType !== null ? this.valueMapper.mapTxType(bankTxType) : null;
2664
3080
  if (commonResponse.status === TX_APPROVED) {
2665
- let txTime = text3(raw, "HostDate");
3081
+ let txTime = text4(raw, "HostDate");
2666
3082
  if (txTime !== null && txTime.length === 10) {
2667
3083
  txTime = `${new Date(Date.now() + BANK_TIME_OFFSET_MS).getUTCFullYear()}${txTime}`;
2668
3084
  }
2669
- commonResponse.transaction_id = field2(raw, "TransactionId");
3085
+ commonResponse.transaction_id = field3(raw, "TransactionId");
2670
3086
  commonResponse.transaction_time = txTime !== null ? this.valueFormatter.formatDateTime(txTime, txType) : null;
2671
- commonResponse.auth_code = field2(raw, "AuthCode");
2672
- commonResponse.ref_ret_num = field2(raw, "TransactionId");
2673
- commonResponse.batch_num = field2(raw, "BatchNo");
3087
+ commonResponse.auth_code = field3(raw, "AuthCode");
3088
+ commonResponse.ref_ret_num = field3(raw, "TransactionId");
3089
+ commonResponse.batch_num = field3(raw, "BatchNo");
2674
3090
  }
2675
3091
  this.logger.debug("mapped payment response", commonResponse);
2676
3092
  return commonResponse;
@@ -2688,30 +3104,30 @@ var PayFlexV4PosResponseDataMapper = class _PayFlexV4PosResponseDataMapper exten
2688
3104
  if (mdStatus !== "Y" || raw3DAuthResponseData === null || typeof raw3DAuthResponseData !== "object") {
2689
3105
  return false;
2690
3106
  }
2691
- const own = (key) => Object.hasOwn(raw3DAuthResponseData, key) ? raw3DAuthResponseData[key] : void 0;
2692
- const status = own("Status");
2693
- const eci = own("Eci");
2694
- const cavv = own("Cavv");
2695
- const md = own("MdStatus");
3107
+ const own2 = (key) => Object.hasOwn(raw3DAuthResponseData, key) ? raw3DAuthResponseData[key] : void 0;
3108
+ const status = own2("Status");
3109
+ const eci = own2("Eci");
3110
+ const cavv = own2("Cavv");
3111
+ const md = own2("MdStatus");
2696
3112
  return status === "Y" && typeof eci === "string" && FULL_3D_ECI.has(eci) && typeof cavv === "string" && cavv.trim() !== "" && (md === void 0 || md === null || md === "" || md === "1");
2697
3113
  }
2698
3114
  /** The enrollment / authentication `Status` (Y, A, N, U, E). */
2699
3115
  extractMdStatus(raw3DAuthResponseData) {
2700
- return text3(raw3DAuthResponseData, "Status");
3116
+ return text4(raw3DAuthResponseData, "Status");
2701
3117
  }
2702
3118
  getProcReturnCode(response) {
2703
- return text3(response, "ResultCode");
3119
+ return text4(response, "ResultCode");
2704
3120
  }
2705
3121
  getCommonPaymentResponse(responseData, txType) {
2706
3122
  const resultCode = this.getProcReturnCode(responseData);
2707
3123
  const status = resultCode === _PayFlexV4PosResponseDataMapper.PROCEDURE_SUCCESS_CODE ? TX_APPROVED : TX_DECLINED;
2708
- const secureType = text3(responseData, "ThreeDSecureType");
3124
+ const secureType = text4(responseData, "ThreeDSecureType");
2709
3125
  const paymentModel = secureType !== null ? this.valueMapper.mapSecureType(secureType, txType) : null;
2710
3126
  const response = this.getDefaultPaymentResponse(txType, paymentModel);
2711
3127
  response.proc_return_code = resultCode;
2712
3128
  response.status = status;
2713
3129
  response.error_code = status === TX_DECLINED ? resultCode : null;
2714
- response.error_message = status === TX_DECLINED ? text3(responseData, "ResultDetail") : null;
3130
+ response.error_message = status === TX_DECLINED ? text4(responseData, "ResultDetail") : null;
2715
3131
  response.all = responseData;
2716
3132
  return response;
2717
3133
  }
@@ -2719,18 +3135,18 @@ var PayFlexV4PosResponseDataMapper = class _PayFlexV4PosResponseDataMapper exten
2719
3135
 
2720
3136
  // src/data-mapper/response/value-formatter/AbstractResponseValueFormatter.ts
2721
3137
  var PHP_NUMERIC = /^[ \t\n\r\v\f]*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?[ \t\n\r\v\f]*$/;
2722
- function phpInt2(value) {
2723
- if (value === null || value === void 0) return 0;
2724
- if (PHP_NUMERIC.test(value)) {
2725
- const n2 = Math.trunc(Number(value));
3138
+ function phpInt2(value2) {
3139
+ if (value2 === null || value2 === void 0) return 0;
3140
+ if (PHP_NUMERIC.test(value2)) {
3141
+ const n2 = Math.trunc(Number(value2));
2726
3142
  return Number.isFinite(n2) ? n2 : 0;
2727
3143
  }
2728
- const n = Number.parseInt(value.replace(/^[ \t\n\r\v\f]+/, ""), 10);
3144
+ const n = Number.parseInt(value2.replace(/^[ \t\n\r\v\f]+/, ""), 10);
2729
3145
  return Number.isNaN(n) ? 0 : n;
2730
3146
  }
2731
- function phpFloat(value) {
2732
- if (typeof value === "number") return value;
2733
- const n = Number.parseFloat(value.replace(/^[ \t\n\r\v\f]+/, ""));
3147
+ function phpFloat(value2) {
3148
+ if (typeof value2 === "number") return value2;
3149
+ const n = Number.parseFloat(value2.replace(/^[ \t\n\r\v\f]+/, ""));
2734
3150
  return Number.isFinite(n) ? n : 0;
2735
3151
  }
2736
3152
  var BANK_TIMEZONE_OFFSET_MINUTES = 180;
@@ -2746,16 +3162,16 @@ function parseOffset(offset) {
2746
3162
  return sign * (Number(digits.slice(0, 2)) * 60 + Number(digits.slice(2)));
2747
3163
  }
2748
3164
  function parseDateTime(input) {
2749
- const value = input.trim();
2750
- if (value.toLowerCase() === "now") {
3165
+ const value2 = input.trim();
3166
+ if (value2.toLowerCase() === "now") {
2751
3167
  return /* @__PURE__ */ new Date();
2752
3168
  }
2753
3169
  let parts = null;
2754
- const iso = ISO_LIKE.exec(value);
3170
+ const iso = ISO_LIKE.exec(value2);
2755
3171
  if (iso) {
2756
3172
  parts = [iso[1], iso[2], iso[3], iso[4], iso[5], iso[6], iso[7], iso[8]];
2757
3173
  } else {
2758
- const dotted = DOTTED.exec(value);
3174
+ const dotted = DOTTED.exec(value2);
2759
3175
  if (dotted) {
2760
3176
  parts = [dotted[3], dotted[2], dotted[1], dotted[4], dotted[5], dotted[6]];
2761
3177
  }
@@ -2793,11 +3209,11 @@ var AssecoPosResponseValueFormatter = class extends AbstractResponseValueFormatt
2793
3209
  }
2794
3210
  /** Status and order history responses return amounts in minor units (`1001` -> 10.01). */
2795
3211
  formatAmount(amount, txType) {
2796
- const value = super.formatAmount(amount, txType);
3212
+ const value2 = super.formatAmount(amount, txType);
2797
3213
  if (txType === TX_TYPE.STATUS || txType === TX_TYPE.ORDER_HISTORY) {
2798
- return value / 100;
3214
+ return value2 / 100;
2799
3215
  }
2800
- return value;
3216
+ return value2;
2801
3217
  }
2802
3218
  };
2803
3219
 
@@ -2810,9 +3226,9 @@ var BasicResponseValueFormatter = class extends AbstractResponseValueFormatter {
2810
3226
  };
2811
3227
 
2812
3228
  // src/data-mapper/response/value-mapper/AbstractResponseValueMapper.ts
2813
- function phpKey(value) {
2814
- if (typeof value === "boolean") return value ? "1" : "0";
2815
- return String(value);
3229
+ function phpKey(value2) {
3230
+ if (typeof value2 === "boolean") return value2 ? "1" : "0";
3231
+ return String(value2);
2816
3232
  }
2817
3233
  var AbstractResponseValueMapper = class {
2818
3234
  /** Bank currency code -> CURRENCY value. */
@@ -2909,6 +3325,30 @@ var AssecoPosResponseValueMapper = class extends AbstractResponseValueMapper {
2909
3325
  }
2910
3326
  };
2911
3327
 
3328
+ // src/data-mapper/response/value-mapper/PayFlexCPV4PosResponseValueMapper.ts
3329
+ var PayFlexCPV4PosResponseValueMapper = class extends AbstractResponseValueMapper {
3330
+ currencyMappings = {
3331
+ "949": CURRENCY.TRY,
3332
+ "840": CURRENCY.USD,
3333
+ "978": CURRENCY.EUR,
3334
+ "826": CURRENCY.GBP,
3335
+ "392": CURRENCY.JPY,
3336
+ "643": CURRENCY.RUB
3337
+ };
3338
+ txTypeMappings = {
3339
+ [TX_TYPE.PAY_AUTH]: "Sale",
3340
+ [TX_TYPE.PAY_PRE_AUTH]: "Auth",
3341
+ [TX_TYPE.PAY_POST_AUTH]: "Capture",
3342
+ [TX_TYPE.CANCEL]: "Cancel",
3343
+ [TX_TYPE.REFUND]: "Refund",
3344
+ [TX_TYPE.REFUND_PARTIAL]: "Refund",
3345
+ [TX_TYPE.STATUS]: "OrderInquiry"
3346
+ };
3347
+ static supports(gatewayClass) {
3348
+ return gatewayClass === "PayFlexCPV4Pos";
3349
+ }
3350
+ };
3351
+
2912
3352
  // src/data-mapper/response/value-mapper/PayFlexV4PosResponseValueMapper.ts
2913
3353
  var PayFlexV4PosResponseValueMapper = class extends AbstractResponseValueMapper {
2914
3354
  currencyMappings = {
@@ -3415,43 +3855,331 @@ var AssecoPos = class extends AbstractGateway {
3415
3855
  }
3416
3856
  }
3417
3857
  };
3418
- function parseAmount(value) {
3419
- if (typeof value === "number") {
3420
- return Number.isFinite(value) ? value : Number.NaN;
3858
+ function parseAmount(value2) {
3859
+ if (typeof value2 === "number") {
3860
+ return Number.isFinite(value2) ? value2 : Number.NaN;
3421
3861
  }
3422
- return typeof value === "string" && DECIMAL.test(value) ? Number(value) : Number.NaN;
3862
+ return typeof value2 === "string" && DECIMAL.test(value2) ? Number(value2) : Number.NaN;
3423
3863
  }
3424
- function asText(value) {
3425
- return value === null || value === void 0 ? "" : String(value);
3864
+ function asText(value2) {
3865
+ return value2 === null || value2 === void 0 ? "" : String(value2);
3426
3866
  }
3427
3867
 
3868
+ // src/gateway/PayFlexCPV4Pos.ts
3869
+ var SUCCESS_CODE = "0000";
3870
+ var ANSWER_AMOUNT = /^(\d+)(?:[.,](\d{1,2}))?$/;
3871
+ var NO_IDS_MESSAGE = "Callback carries no TransactionId or PaymentToken; the result cannot be confirmed with the bank.";
3872
+ var DECIMAL2 = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)\s*$/;
3873
+ var ALTERNATIVE = 'use a PayFlexV4Pos gateway (bank "vakifbank") with transaction_id = the common payment TransactionId';
3874
+ function own(data, key) {
3875
+ return Object.hasOwn(data, key) ? data[key] : void 0;
3876
+ }
3877
+ function value(data, key) {
3878
+ return own(data, key) ?? void 0;
3879
+ }
3880
+ function asText2(v) {
3881
+ return v === null || v === void 0 ? "" : String(v);
3882
+ }
3883
+ function nonEmpty(data, key) {
3884
+ const v = value(data, key);
3885
+ if (v === void 0) return null;
3886
+ const s = String(v);
3887
+ return s === "" ? null : s;
3888
+ }
3889
+ function firstNonEmptyString(data, ...keys) {
3890
+ for (const key of keys) {
3891
+ const v = value(data, key);
3892
+ if (typeof v === "string" && v !== "") return v;
3893
+ }
3894
+ return null;
3895
+ }
3896
+ function nonEmptyString(v) {
3897
+ return typeof v === "string" && v !== "" ? v : null;
3898
+ }
3899
+ function answerCents(v) {
3900
+ if (typeof v !== "string" && !(typeof v === "number" && Number.isFinite(v))) return null;
3901
+ const match = ANSWER_AMOUNT.exec(String(v));
3902
+ if (match === null) return null;
3903
+ return BigInt(match[1]) * 100n + BigInt((match[2] ?? "").padEnd(2, "0"));
3904
+ }
3905
+ function orderCents(v) {
3906
+ let amount;
3907
+ if (typeof v === "number") {
3908
+ amount = v;
3909
+ } else if (typeof v === "string" && DECIMAL2.test(v)) {
3910
+ amount = Number(v);
3911
+ } else {
3912
+ return null;
3913
+ }
3914
+ try {
3915
+ return BigInt(numberFormat2(amount).replace(".", ""));
3916
+ } catch (e) {
3917
+ if (e instanceof PosError) return null;
3918
+ throw e;
3919
+ }
3920
+ }
3921
+ var PayFlexCPV4Pos = class extends AbstractGateway {
3922
+ static NAME = "PayFlex-Common-Payment-V4";
3923
+ static GATEWAY_CLASS = "PayFlexCPV4Pos";
3924
+ static supportedTransactions = {
3925
+ [TX_TYPE.PAY_AUTH]: [MODEL.THREE_D_PAY, MODEL.THREE_D_HOST],
3926
+ [TX_TYPE.PAY_PRE_AUTH]: [MODEL.THREE_D_PAY, MODEL.THREE_D_HOST],
3927
+ [TX_TYPE.PAY_POST_AUTH]: false,
3928
+ [TX_TYPE.STATUS]: true,
3929
+ [TX_TYPE.CANCEL]: false,
3930
+ [TX_TYPE.REFUND]: false,
3931
+ [TX_TYPE.REFUND_PARTIAL]: false,
3932
+ [TX_TYPE.ORDER_HISTORY]: false
3933
+ };
3934
+ cpRequestDataMapper;
3935
+ constructor(config, account, deps) {
3936
+ super(config, account, deps);
3937
+ const mapper = deps.requestDataMapper;
3938
+ if (typeof mapper.create3DPaymentStatusRequestData !== "function") {
3939
+ throw new PosError("PayFlexCPV4Pos needs a request data mapper with create3DPaymentStatusRequestData");
3940
+ }
3941
+ this.cpRequestDataMapper = deps.requestDataMapper;
3942
+ }
3943
+ /**
3944
+ * Registers the payment and returns the redirect (GET `CommonPaymentUrl?Ptkn=…`) to the bank card page.
3945
+ *
3946
+ * @throws UnsupportedFormFormatError for `formFormat: 'html'`
3947
+ * @throws PosError when the registration is not accepted
3948
+ */
3949
+ async get3DFormData(order, paymentModel, txType, card = null, createWithoutCard = false, formFormat = null) {
3950
+ this.check3DFormInputs(paymentModel, txType, card, createWithoutCard);
3951
+ if (formFormat === FORM_FORMAT.HTML) {
3952
+ throw new UnsupportedFormFormatError("Unsupported 3D form format!");
3953
+ }
3954
+ const requestTxType = TX_TYPE.INTERNAL_3D_FORM_BUILD;
3955
+ const requestData = await this.dispatchRequestDataPrepared(
3956
+ this.requestDataMapper.create3DFormInitializeRequestData(this.account, order, paymentModel, txType, card),
3957
+ requestTxType,
3958
+ order,
3959
+ paymentModel
3960
+ );
3961
+ const answer = await this.sendRequest(requestTxType, paymentModel, requestData, order);
3962
+ this.assertRegistered(answer);
3963
+ this.logger.debug("preparing 3D form data");
3964
+ return await this.requestDataMapper.create3DFormData(
3965
+ this.account,
3966
+ null,
3967
+ paymentModel,
3968
+ txType,
3969
+ "",
3970
+ null,
3971
+ answer
3972
+ );
3973
+ }
3974
+ async make3DPayment(_gatewayResponseData, _order, _txType, _card = null) {
3975
+ throw new UnsupportedPaymentModelError("Common payment supports the 3D Pay and 3D Host models only");
3976
+ }
3977
+ /**
3978
+ * @throws OrderMismatchError when the approved query answer belongs to another payment
3979
+ * @throws PosHttpError when the query fails or answers something that is not JSON/XML (e.g. an HTML page)
3980
+ */
3981
+ make3DPayPayment(gatewayResponseData, order, txType) {
3982
+ return this.completeHostedPayment(gatewayResponseData, order, txType, MODEL.THREE_D_PAY);
3983
+ }
3984
+ /**
3985
+ * @throws OrderMismatchError when the approved query answer belongs to another payment
3986
+ * @throws PosHttpError when the query fails or answers something that is not JSON/XML (e.g. an HTML page)
3987
+ */
3988
+ make3DHostPayment(gatewayResponseData, order, txType) {
3989
+ return this.completeHostedPayment(gatewayResponseData, order, txType, MODEL.THREE_D_HOST);
3990
+ }
3991
+ async makeRegularPayment(_order, _card, _txType) {
3992
+ throw new UnsupportedPaymentModelError("Common payment has no non-secure payment");
3993
+ }
3994
+ async makeRegularPostPayment(_order) {
3995
+ throw new UnsupportedTransactionTypeError(`Common payment has no post authorization; ${ALTERNATIVE}`);
3996
+ }
3997
+ async cancel(_order) {
3998
+ throw new UnsupportedTransactionTypeError(`Common payment has no cancel; ${ALTERNATIVE}`);
3999
+ }
4000
+ async refund(_order) {
4001
+ throw new UnsupportedTransactionTypeError(`Common payment has no refund; ${ALTERNATIVE}`);
4002
+ }
4003
+ async orderHistory(_order) {
4004
+ throw new UnsupportedTransactionTypeError("Common payment has no order history");
4005
+ }
4006
+ /**
4007
+ * Registration succeeds only with a payment token, an `https:` payment URL and no error code
4008
+ * (VakifBank Common Payment guide v2.1 §4: `ErrorCode` is set only on failure).
4009
+ */
4010
+ assertRegistered(answer) {
4011
+ const errorCode = nonEmpty(answer, "ErrorCode");
4012
+ const statusCode = nonEmpty(answer, "StatusCode");
4013
+ const token = nonEmpty(answer, "PaymentToken");
4014
+ const url = nonEmpty(answer, "CommonPaymentUrl");
4015
+ const failed = token === null || url === null || errorCode !== null && errorCode !== SUCCESS_CODE || statusCode !== null && statusCode !== "0";
4016
+ if (failed) {
4017
+ this.logger.error("payment register fail response", answer);
4018
+ const message = nonEmpty(answer, "ResponseMessage") ?? nonEmpty(answer, "ErrorMessage") ?? nonEmpty(answer, "StatusDescription") ?? "Common payment registration failed";
4019
+ throw new PosError(message, {
4020
+ cause: { code: value(answer, "ErrorCode") ?? value(answer, "StatusCode") ?? null }
4021
+ });
4022
+ }
4023
+ let protocol;
4024
+ try {
4025
+ protocol = new URL(url).protocol;
4026
+ } catch {
4027
+ protocol = "";
4028
+ }
4029
+ if (protocol !== "https:") {
4030
+ this.logger.error("payment register response has no https payment URL", { url });
4031
+ throw new PosError("Common payment URL must be an https: URL");
4032
+ }
4033
+ }
4034
+ /**
4035
+ * Confirms the browser callback with the transaction query (VakifBank Common Payment guide v2.1 §6.4, §6.5) and
4036
+ * binds an approved answer to the order. The callback result code never decides the status.
4037
+ *
4038
+ * @throws OrderMismatchError (`paymentMayHaveCompleted: false`, no HTTP call) when the callback ids contradict
4039
+ * the order's `transaction_id` / `payment_token`
4040
+ */
4041
+ async completeHostedPayment(callback, order, txType, paymentModel) {
4042
+ if (txType !== TX_TYPE.PAY_AUTH && txType !== TX_TYPE.PAY_PRE_AUTH) {
4043
+ throw new UnsupportedTransactionTypeError(`Invalid transaction type "${txType}" provided`);
4044
+ }
4045
+ const cb = callback;
4046
+ const callbackSaysApproved = firstNonEmptyString(cb, "Rc", "RC", "ResultCode") === SUCCESS_CODE;
4047
+ const map = (data) => paymentModel === MODEL.THREE_D_PAY ? this.responseDataMapper.map3DPayResponseData(data, txType, order) : this.responseDataMapper.map3DHostResponseData(data, txType, order);
4048
+ const orderTransactionId = nonEmptyString(order.transaction_id);
4049
+ const orderPaymentToken = nonEmptyString(order.payment_token);
4050
+ const callbackTransactionId = nonEmpty(cb, "TransactionId");
4051
+ const callbackPaymentToken = nonEmpty(cb, "PaymentToken");
4052
+ if (orderTransactionId !== null && callbackTransactionId !== null && callbackTransactionId !== orderTransactionId) {
4053
+ this.rejectCallbackId(orderTransactionId, callbackTransactionId);
4054
+ }
4055
+ if (orderPaymentToken !== null && callbackPaymentToken !== null && callbackPaymentToken !== orderPaymentToken) {
4056
+ this.rejectCallbackId(orderPaymentToken, callbackPaymentToken);
4057
+ }
4058
+ const queryByOrder = orderTransactionId !== null || orderPaymentToken !== null;
4059
+ if (!queryByOrder && callbackTransactionId === null && callbackPaymentToken === null) {
4060
+ this.logger.error("3D callback has no TransactionId or PaymentToken to confirm", {
4061
+ callback_says_approved: callbackSaysApproved
4062
+ });
4063
+ const response2 = {
4064
+ ...map({}),
4065
+ status: "declined",
4066
+ proc_return_code: null,
4067
+ error_code: null,
4068
+ error_message: NO_IDS_MESSAGE,
4069
+ all: cb
4070
+ };
4071
+ if (callbackSaysApproved) response2.requires_manual_review = true;
4072
+ return response2;
4073
+ }
4074
+ const queryTxType = TX_TYPE.INTERNAL_3D_PAYMENT_STATUS;
4075
+ const queryModel = MODEL.NON_SECURE;
4076
+ const query = await this.dispatchRequestDataPrepared(
4077
+ queryByOrder ? this.requestDataMapper.createStatusRequestData(this.account, order) : this.cpRequestDataMapper.create3DPaymentStatusRequestData(this.account, cb),
4078
+ queryTxType,
4079
+ order,
4080
+ queryModel
4081
+ );
4082
+ const answer = await this.sendRequest(queryTxType, queryModel, query, order);
4083
+ const response = map(answer);
4084
+ if (response.status === "approved") {
4085
+ this.assertAnswerMatchesOrder(
4086
+ answer,
4087
+ orderTransactionId ?? callbackTransactionId,
4088
+ orderPaymentToken,
4089
+ order,
4090
+ txType,
4091
+ response
4092
+ );
4093
+ this.logger.debug("finished 3D payment", { mapped_response: response });
4094
+ return response;
4095
+ }
4096
+ if (callbackSaysApproved) {
4097
+ this.logger.error("3D callback says approved but the transaction query does not confirm it", {
4098
+ proc_return_code: response.proc_return_code,
4099
+ error_code: response.error_code
4100
+ });
4101
+ return { ...response, requires_manual_review: true };
4102
+ }
4103
+ this.logger.debug("finished 3D payment", { mapped_response: response });
4104
+ return response;
4105
+ }
4106
+ /** A callback id that contradicts the order's own id: rejected before any HTTP call. */
4107
+ rejectCallbackId(expected, actual) {
4108
+ this.logger.error("3D callback id does not match the order", { expected, actual });
4109
+ throw new OrderMismatchError("transaction_id", expected, actual);
4110
+ }
4111
+ /** Binds an approved query answer to the order (fail closed: a missing required value never matches). */
4112
+ assertAnswerMatchesOrder(answer, expectedTransactionId, expectedPaymentToken, order, txType, response) {
4113
+ const fail2 = (field4, expected, actual) => {
4114
+ this.logger.error(`transaction query ${field4} does not match the payment`, { expected, actual });
4115
+ throw new OrderMismatchError(field4, expected, actual, response);
4116
+ };
4117
+ const expectedOrderId = asText2(order.id);
4118
+ const answerOrderId = value(answer, "OrderID") ?? value(answer, "OrderId");
4119
+ if (expectedOrderId === "" || typeof answerOrderId !== "string" || answerOrderId !== expectedOrderId) {
4120
+ fail2("order_id", expectedOrderId, asText2(answerOrderId));
4121
+ }
4122
+ const answerAmount = answerCents(value(answer, "Amount"));
4123
+ const orderAmount = orderCents(order.amount);
4124
+ if (answerAmount === null || orderAmount === null || answerAmount !== orderAmount) {
4125
+ fail2("amount", asText2(order.amount), asText2(value(answer, "Amount")));
4126
+ }
4127
+ const expectedCurrency = String(this.requestValueMapper.mapCurrency(order.currency ?? CURRENCY.TRY));
4128
+ const answerCurrency = value(answer, "AmountCode") ?? value(answer, "CurrencyCode");
4129
+ if (answerCurrency === void 0) {
4130
+ if (expectedCurrency !== "949") fail2("currency", expectedCurrency, "");
4131
+ } else if (String(answerCurrency) !== expectedCurrency) {
4132
+ fail2("currency", expectedCurrency, asText2(answerCurrency));
4133
+ }
4134
+ const answerMerchantId = value(answer, "HostMerchantId");
4135
+ if (answerMerchantId !== void 0 && String(answerMerchantId) !== this.account.getMerchantId()) {
4136
+ fail2("merchant_id", this.account.getMerchantId(), asText2(answerMerchantId));
4137
+ }
4138
+ const answerTxType = value(answer, "TransactionType");
4139
+ if (answerTxType !== void 0) {
4140
+ const expectedTxType = this.requestValueMapper.mapTxType(txType);
4141
+ if (String(answerTxType) !== expectedTxType) {
4142
+ fail2("transaction_type", expectedTxType, asText2(answerTxType));
4143
+ }
4144
+ }
4145
+ const answerTransactionId = value(answer, "TransactionId");
4146
+ if (expectedTransactionId !== null && answerTransactionId !== void 0 && String(answerTransactionId) !== expectedTransactionId) {
4147
+ fail2("transaction_id", expectedTransactionId, asText2(answerTransactionId));
4148
+ }
4149
+ const answerPaymentToken = value(answer, "PaymentToken");
4150
+ if (expectedPaymentToken !== null && answerPaymentToken !== void 0 && String(answerPaymentToken) !== expectedPaymentToken) {
4151
+ fail2("transaction_id", expectedPaymentToken, asText2(answerPaymentToken));
4152
+ }
4153
+ }
4154
+ };
4155
+
3428
4156
  // src/gateway/PayFlexV4Pos.ts
3429
4157
  var AMOUNT_TOLERANCE2 = 5e-3;
3430
4158
  var CALLBACK_AMOUNT = /^\d+(\.\d{2})?$/;
3431
- var DECIMAL2 = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)\s*$/;
4159
+ var DECIMAL3 = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)\s*$/;
3432
4160
  function record2(data, key) {
3433
4161
  if (data !== null && typeof data === "object" && !Array.isArray(data) && Object.hasOwn(data, key)) {
3434
- const value = data[key];
3435
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
3436
- return value;
4162
+ const value2 = data[key];
4163
+ if (value2 !== null && typeof value2 === "object" && !Array.isArray(value2)) {
4164
+ return value2;
3437
4165
  }
3438
4166
  }
3439
4167
  return {};
3440
4168
  }
3441
- function parseCallbackAmount(value) {
3442
- if (typeof value !== "string" || !CALLBACK_AMOUNT.test(value)) return Number.NaN;
3443
- return Number(value.replace(".", "")) / 100;
4169
+ function parseCallbackAmount(value2) {
4170
+ if (typeof value2 !== "string" || !CALLBACK_AMOUNT.test(value2)) return Number.NaN;
4171
+ return Number(value2.replace(".", "")) / 100;
3444
4172
  }
3445
- function parseOrderAmount(value) {
3446
- if (typeof value === "number") return Number.isFinite(value) ? value : Number.NaN;
3447
- return typeof value === "string" && DECIMAL2.test(value) ? Number(value) : Number.NaN;
4173
+ function parseOrderAmount(value2) {
4174
+ if (typeof value2 === "number") return Number.isFinite(value2) ? value2 : Number.NaN;
4175
+ return typeof value2 === "string" && DECIMAL3.test(value2) ? Number(value2) : Number.NaN;
3448
4176
  }
3449
- function asText2(value) {
3450
- return value === null || value === void 0 ? "" : String(value);
4177
+ function asText3(value2) {
4178
+ return value2 === null || value2 === void 0 ? "" : String(value2);
3451
4179
  }
3452
- function text4(data, key) {
3453
- const value = Object.hasOwn(data, key) ? data[key] : void 0;
3454
- return value === void 0 || value === null ? "" : String(value);
4180
+ function text5(data, key) {
4181
+ const value2 = Object.hasOwn(data, key) ? data[key] : void 0;
4182
+ return value2 === void 0 || value2 === null ? "" : String(value2);
3455
4183
  }
3456
4184
  var PayFlexV4Pos = class extends AbstractGateway {
3457
4185
  static NAME = "PayFlexV4";
@@ -3517,12 +4245,12 @@ var PayFlexV4Pos = class extends AbstractGateway {
3517
4245
  }
3518
4246
  const data = await this.sendEnrollmentRequest(order, card, txType, paymentModel);
3519
4247
  const veRes = record2(record2(data, "Message"), "VERes");
3520
- const status = text4(veRes, "Status");
4248
+ const status = text5(veRes, "Status");
3521
4249
  if (status !== "Y") {
3522
4250
  this.logger.error("enrollment fail response", data);
3523
4251
  if (status === "E") {
3524
- throw new PosError(text4(data, "ErrorMessage") || "Enrollment failed", {
3525
- cause: { code: text4(data, "MessageErrorCode") }
4252
+ throw new PosError(text5(data, "ErrorMessage") || "Enrollment failed", {
4253
+ cause: { code: text5(data, "MessageErrorCode") }
3526
4254
  });
3527
4255
  }
3528
4256
  if (status === "N") {
@@ -3563,29 +4291,29 @@ var PayFlexV4Pos = class extends AbstractGateway {
3563
4291
  * guard only stops naive replays.
3564
4292
  */
3565
4293
  assertCallbackMatchesOrder(callback, order) {
3566
- const own = (key) => Object.hasOwn(callback, key) ? callback[key] : void 0;
3567
- const callbackAmount = parseCallbackAmount(own("PurchAmount"));
4294
+ const own2 = (key) => Object.hasOwn(callback, key) ? callback[key] : void 0;
4295
+ const callbackAmount = parseCallbackAmount(own2("PurchAmount"));
3568
4296
  const orderAmount = parseOrderAmount(order.amount);
3569
4297
  if (!(Math.abs(callbackAmount - orderAmount) < AMOUNT_TOLERANCE2)) {
3570
- this.fail("amount", asText2(order.amount), asText2(own("PurchAmount")));
4298
+ this.fail("amount", asText3(order.amount), asText3(own2("PurchAmount")));
3571
4299
  }
3572
4300
  const expectedCurrency = String(this.requestValueMapper.mapCurrency(order.currency ?? CURRENCY.TRY));
3573
- if (own("PurchCurrency") !== expectedCurrency) {
3574
- this.fail("currency", expectedCurrency, asText2(own("PurchCurrency")));
4301
+ if (own2("PurchCurrency") !== expectedCurrency) {
4302
+ this.fail("currency", expectedCurrency, asText3(own2("PurchCurrency")));
3575
4303
  }
3576
4304
  const merchantIds = [this.account.getMerchantId()];
3577
4305
  const subMerchantId = this.account.getSubMerchantId();
3578
4306
  if (this.account.isSubBranch() && subMerchantId !== null && subMerchantId !== "") {
3579
4307
  merchantIds.push(subMerchantId);
3580
4308
  }
3581
- const merchantId = own("MerchantId");
4309
+ const merchantId = own2("MerchantId");
3582
4310
  if (typeof merchantId !== "string" || !merchantIds.includes(merchantId)) {
3583
- this.fail("merchant_id", merchantIds.join(" | "), asText2(merchantId));
4311
+ this.fail("merchant_id", merchantIds.join(" | "), asText3(merchantId));
3584
4312
  }
3585
4313
  }
3586
- fail(field3, expected, actual) {
3587
- this.logger.error(`3D callback ${field3} does not match the payment`, { expected, actual });
3588
- throw new OrderMismatchError(field3, expected, actual);
4314
+ fail(field4, expected, actual) {
4315
+ this.logger.error(`3D callback ${field4} does not match the payment`, { expected, actual });
4316
+ throw new OrderMismatchError(field4, expected, actual);
3589
4317
  }
3590
4318
  /** Enrollment status query (VerifyEnrollmentRequest) sent to `gateway_3d`. */
3591
4319
  async sendEnrollmentRequest(order, card, orderTxType, paymentModel) {
@@ -3626,6 +4354,8 @@ var PosFactory = {
3626
4354
  return createAssecoPos(account, gatewayConfig, transport, logger, hooks);
3627
4355
  case PayFlexV4Pos.GATEWAY_CLASS:
3628
4356
  return createPayFlexV4Pos(account, gatewayConfig, transport, logger, hooks);
4357
+ case PayFlexCPV4Pos.GATEWAY_CLASS:
4358
+ return createPayFlexCPV4Pos(account, gatewayConfig, transport, logger, hooks);
3629
4359
  default:
3630
4360
  throw new GatewayClassNotConfiguredError(
3631
4361
  `Gateway class [${bankConfig.class}] of bank [${bankName}] is not supported.`
@@ -3695,6 +4425,38 @@ function createPayFlexV4Pos(account, config, transport, logger, hooks) {
3695
4425
  hooks
3696
4426
  });
3697
4427
  }
4428
+ function createPayFlexCPV4Pos(account, config, transport, logger, hooks) {
4429
+ if (!(account instanceof PayFlexPosAccount)) {
4430
+ throw new PosError(
4431
+ `Bank [${account.getBankName()}] is configured for PayFlexCPV4Pos and needs a PayFlexPosAccount.`
4432
+ );
4433
+ }
4434
+ const crypt = new PayFlexCPV4PosCrypt(logger);
4435
+ const requestValueMapper = new PayFlexCPV4PosRequestValueMapper();
4436
+ const requestValueFormatter = new PayFlexCPV4PosRequestValueFormatter();
4437
+ return new PayFlexCPV4Pos(config, account, {
4438
+ requestValueMapper,
4439
+ requestValueFormatter,
4440
+ requestDataMapper: new PayFlexCPV4PosRequestDataMapper(
4441
+ requestValueMapper,
4442
+ requestValueFormatter,
4443
+ hooks,
4444
+ crypt,
4445
+ config.lang ?? LANG.TR
4446
+ ),
4447
+ responseDataMapper: new PayFlexCPV4PosResponseDataMapper(
4448
+ new BasicResponseValueFormatter(),
4449
+ new PayFlexCPV4PosResponseValueMapper(),
4450
+ logger
4451
+ ),
4452
+ crypt,
4453
+ clientStrategy: new HttpClientStrategy([
4454
+ new PayFlexCPV4PosHttpClient(requiredEndpoint(config, "payment_api"), transport, logger)
4455
+ ]),
4456
+ logger,
4457
+ hooks
4458
+ });
4459
+ }
3698
4460
  function assertHttpsEndpoints(config) {
3699
4461
  const endpoints = config.gateway_endpoints ?? {};
3700
4462
  for (const [key, url] of Object.entries(endpoints)) {
@@ -3721,7 +4483,7 @@ function requiredEndpoint(config, key) {
3721
4483
  }
3722
4484
 
3723
4485
  // src/index.ts
3724
- var VERSION = "0.1.0";
4486
+ var VERSION = "0.2.0";
3725
4487
  export {
3726
4488
  AbstractGateway,
3727
4489
  AbstractPosAccount,
@@ -3745,6 +4507,7 @@ export {
3745
4507
  NotImplementedError,
3746
4508
  OrderMismatchError,
3747
4509
  PAYMENT_STATUS,
4510
+ PayFlexCPV4Pos,
3748
4511
  PayFlexPosAccount,
3749
4512
  PayFlexV4Pos,
3750
4513
  PosError,