@moneykarma/loan-sdk 0.0.0-stage → 0.2.0-next.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/CHANGELOG.md +1 -0
- package/LICENSE +21 -0
- package/README.md +14 -2
- package/dist/chunks/chunk-PY2B3NZC.js +1675 -0
- package/dist/chunks/chunk-PY2B3NZC.js.map +1 -0
- package/dist/chunks/chunk-Z3S35SMX.js +2847 -0
- package/dist/chunks/chunk-Z3S35SMX.js.map +1 -0
- package/dist/core.cjs +1692 -0
- package/dist/core.cjs.map +1 -0
- package/dist/core.d.cts +1286 -0
- package/dist/core.d.ts +1286 -0
- package/dist/core.js +108 -0
- package/dist/core.js.map +1 -0
- package/dist/index.cjs +4499 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +199 -0
- package/dist/index.d.ts +199 -0
- package/dist/index.js +118 -0
- package/dist/index.js.map +1 -0
- package/dist/loan-sdk.css +1 -0
- package/dist/loan-sdk.esm.js +7 -0
- package/dist/loan-sdk.esm.js.map +1 -0
- package/dist/loan-sdk.js +7 -0
- package/dist/loan-sdk.js.map +1 -0
- package/dist/react.cjs +4582 -0
- package/dist/react.cjs.map +1 -0
- package/dist/react.d.cts +17 -0
- package/dist/react.d.ts +17 -0
- package/dist/react.js +202 -0
- package/dist/react.js.map +1 -0
- package/package.json +139 -4
|
@@ -0,0 +1,1675 @@
|
|
|
1
|
+
/*! @moneykarma/loan-sdk v0.1.0 | MIT */
|
|
2
|
+
|
|
3
|
+
// src/core/rules.ts
|
|
4
|
+
var RUPEES_PER_CRORE = 1e7;
|
|
5
|
+
var PRODUCT = "HOME_LOAN";
|
|
6
|
+
var LIMITS = {
|
|
7
|
+
/** Loan amount in rupees, derived by the server: `value - round(value * downPaymentPct / 100)`. */
|
|
8
|
+
loanAmount: { min: 5e5, max: 2e8 },
|
|
9
|
+
/** Property value in rupees. */
|
|
10
|
+
propertyValue: { min: 5e5, max: 1e9 },
|
|
11
|
+
/** Property value as entered in the form, in crores. */
|
|
12
|
+
propertyValueCrores: { min: 0.05, max: 100 },
|
|
13
|
+
/** Down payment, percent of the property value (at most two decimals). */
|
|
14
|
+
downPaymentPct: { min: 0, max: 90 },
|
|
15
|
+
tenureYears: { min: 1, max: 30 },
|
|
16
|
+
fullName: { min: 1, max: 120 },
|
|
17
|
+
location: { min: 1, max: 256 },
|
|
18
|
+
/** Applicant and co-applicant age (whole years on today's IST date). */
|
|
19
|
+
applicantAge: { min: 18, max: 70 },
|
|
20
|
+
partnerReference: { max: 128 },
|
|
21
|
+
metadataKeys: { max: 20 },
|
|
22
|
+
/** Any rupee amount (monthly income or profit, obligations). */
|
|
23
|
+
amount: { max: 1e10 },
|
|
24
|
+
bankSearchQuery: { min: 2, max: 40 },
|
|
25
|
+
/** Applicant age (whole years, IST calendar date) for the credit check. */
|
|
26
|
+
creditCheckAge: { min: 18, max: 100 }
|
|
27
|
+
};
|
|
28
|
+
var REGEX = {
|
|
29
|
+
/** Indian mobile number without country code. */
|
|
30
|
+
mobile: /^[6-9]\d{9}$/,
|
|
31
|
+
/** Indian PIN code; never starts with 0. */
|
|
32
|
+
pincode: /^[1-9]\d{5}$/,
|
|
33
|
+
/** Calendar date, `YYYY-MM-DD`. */
|
|
34
|
+
date: /^\d{4}-\d{2}-\d{2}$/,
|
|
35
|
+
publishableKey: /^mk_(live|test)_pk_[0-9A-Za-z]{43}$/,
|
|
36
|
+
/** Individual (person) PAN, upper case: 5 letters, 4 digits, 1 letter; the 4th letter is `P`. */
|
|
37
|
+
pan: /^[A-Z]{3}P[A-Z]\d{4}[A-Z]$/,
|
|
38
|
+
/** Credit-check OTP: exactly 6 digits. */
|
|
39
|
+
otp: /^\d{6}$/
|
|
40
|
+
};
|
|
41
|
+
var EMPLOYMENT_TYPES = {
|
|
42
|
+
SALARIED: "SALARIED",
|
|
43
|
+
SELF_EMPLOYED: "SELF_EMPLOYED"
|
|
44
|
+
};
|
|
45
|
+
var EMPLOYMENT_TYPE_VALUES = Object.values(EMPLOYMENT_TYPES);
|
|
46
|
+
var PROPERTY_TYPES = {
|
|
47
|
+
APARTMENT: "APARTMENT",
|
|
48
|
+
INDEPENDENT_HOUSE: "INDEPENDENT_HOUSE",
|
|
49
|
+
PLOT: "PLOT",
|
|
50
|
+
UNDER_CONSTRUCTION: "UNDER_CONSTRUCTION",
|
|
51
|
+
TOWNHOUSE: "TOWNHOUSE",
|
|
52
|
+
VILLA: "VILLA",
|
|
53
|
+
DUPLEX: "DUPLEX",
|
|
54
|
+
CHS: "CHS"
|
|
55
|
+
};
|
|
56
|
+
var PROPERTY_TYPE_VALUES = Object.values(PROPERTY_TYPES);
|
|
57
|
+
var ORDER_PRODUCT_STATUSES = ["BEFORE_LOGIN", "LOGGED_IN_WITH_BANK", "ARCHIVE_LOAN"];
|
|
58
|
+
var ORDER_PRODUCT_SUBSTATUSES = [
|
|
59
|
+
"DETAILS_PENDING",
|
|
60
|
+
"PRE_LOGIN_DOCUMENTS_PENDING",
|
|
61
|
+
"PRE_LOGIN_DOCUMENTS_SUBMITTED",
|
|
62
|
+
"DOCUMENTS_VERIFIED",
|
|
63
|
+
"SUBMITTED_TO_BANK",
|
|
64
|
+
"CREDIT_REVIEW_IN_PROGRESS",
|
|
65
|
+
"POST_LOGIN_QUERIES_PENDING",
|
|
66
|
+
"POST_LOGIN_QUERIES_SUBMITTED",
|
|
67
|
+
"LEGAL_AND_TECHNICAL",
|
|
68
|
+
"SANCTIONED_BY_BANK",
|
|
69
|
+
"SM_CONFIRMATION_PENDING",
|
|
70
|
+
"DISBURSED",
|
|
71
|
+
"REJECTED_BY_MMK",
|
|
72
|
+
"DECLINE_BY_CUSTOMER",
|
|
73
|
+
"REJECTED_BY_BANK",
|
|
74
|
+
"DETAILED_DATA_ENTRY",
|
|
75
|
+
"CUSTOMER_PROFILE_VERIFICATION",
|
|
76
|
+
"VEHICLE_VERIFICATION",
|
|
77
|
+
"AGREEMENT_SIGNED",
|
|
78
|
+
"IN_PRINCIPLE_SANCTION",
|
|
79
|
+
"DOCKET_IN",
|
|
80
|
+
"LOGGED_IN_WITH_BANK",
|
|
81
|
+
"PENDING_ZONAL_HEAD_APPROVAL"
|
|
82
|
+
];
|
|
83
|
+
var ERROR_CODES = [
|
|
84
|
+
"UNAUTHENTICATED",
|
|
85
|
+
"CREDENTIAL_TYPE_NOT_ALLOWED",
|
|
86
|
+
"INSUFFICIENT_SCOPE",
|
|
87
|
+
"ORIGIN_REQUIRED",
|
|
88
|
+
"ORIGIN_NOT_ALLOWED",
|
|
89
|
+
"SECRET_KEY_IN_BROWSER",
|
|
90
|
+
"INTEGRATION_DISABLED",
|
|
91
|
+
"LINK_EXPIRED",
|
|
92
|
+
"LINK_INACTIVE",
|
|
93
|
+
"VALIDATION_ERROR",
|
|
94
|
+
"NOT_FOUND",
|
|
95
|
+
"IDEMPOTENCY_KEY_REUSED",
|
|
96
|
+
"REQUEST_IN_PROGRESS",
|
|
97
|
+
"CAPTCHA_FAILED",
|
|
98
|
+
"CUSTOMER_ALREADY_ENGAGED",
|
|
99
|
+
"PARTNER_NOT_ELIGIBLE",
|
|
100
|
+
"CREDIT_CHECK_NOT_ALLOWED",
|
|
101
|
+
"OTP_INVALID",
|
|
102
|
+
"OTP_EXPIRED",
|
|
103
|
+
"OTP_LOCKED",
|
|
104
|
+
"CONSENT_REVOKED",
|
|
105
|
+
"RATE_LIMITED",
|
|
106
|
+
"UPSTREAM_UNAVAILABLE",
|
|
107
|
+
"INTERNAL_ERROR"
|
|
108
|
+
];
|
|
109
|
+
var CLIENT_ERROR_CODES = [
|
|
110
|
+
"NETWORK_ERROR",
|
|
111
|
+
"INVALID_RESPONSE",
|
|
112
|
+
"CONFIG_ERROR",
|
|
113
|
+
"CAPTCHA_UNAVAILABLE",
|
|
114
|
+
"ABORTED",
|
|
115
|
+
"UNKNOWN"
|
|
116
|
+
];
|
|
117
|
+
var API_BASE_URLS = {
|
|
118
|
+
production: "https://api.mymoneykarma.com/v1",
|
|
119
|
+
sandbox: "https://api-testing.mymoneykarma.com/v1"
|
|
120
|
+
};
|
|
121
|
+
var SESSION_REFRESH_LEAD_MS = 6e4;
|
|
122
|
+
var SESSION_MIN_REFRESH_DELAY_MS = 1e4;
|
|
123
|
+
var MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
|
|
124
|
+
var RETRY_DELAYS_MS = [1e3, 3e3];
|
|
125
|
+
var MAX_RETRY_AFTER_MS = 5e3;
|
|
126
|
+
var DEFAULT_TIMEOUT_MS = 2e4;
|
|
127
|
+
var CREDIT_VERIFY_TIMEOUT_MS = 45e3;
|
|
128
|
+
|
|
129
|
+
// src/core/format.ts
|
|
130
|
+
function formatInr(value, options = {}) {
|
|
131
|
+
var _a;
|
|
132
|
+
if (typeof value !== "number" || !isFinite(value)) return "";
|
|
133
|
+
const decimals = (_a = options.decimals) != null ? _a : Number.isInteger(value) ? 0 : 2;
|
|
134
|
+
const negative = value < 0;
|
|
135
|
+
const fixed = Math.abs(value).toFixed(decimals);
|
|
136
|
+
const [intPart = "0", fracPart] = fixed.split(".");
|
|
137
|
+
let grouped;
|
|
138
|
+
if (intPart.length <= 3) {
|
|
139
|
+
grouped = intPart;
|
|
140
|
+
} else {
|
|
141
|
+
const lastThree = intPart.slice(-3);
|
|
142
|
+
const rest = intPart.slice(0, -3).replace(/\B(?=(\d{2})+(?!\d))/g, ",");
|
|
143
|
+
grouped = `${rest},${lastThree}`;
|
|
144
|
+
}
|
|
145
|
+
const body = fracPart !== void 0 && decimals > 0 ? `${grouped}.${fracPart}` : grouped;
|
|
146
|
+
return `${negative ? "-" : ""}${options.symbol ? "\u20B9" : ""}${body}`;
|
|
147
|
+
}
|
|
148
|
+
function parseInr(text2) {
|
|
149
|
+
if (typeof text2 === "number") return text2;
|
|
150
|
+
if (text2 === null || text2 === void 0) return NaN;
|
|
151
|
+
const cleaned = String(text2).replace(/₹|rs\.?|inr/gi, "").replace(/[,\s_]/g, "").trim();
|
|
152
|
+
if (cleaned === "" || !/^-?\d*(\.\d+)?$/.test(cleaned) || cleaned === "-" || cleaned === ".") return NaN;
|
|
153
|
+
return Number(cleaned);
|
|
154
|
+
}
|
|
155
|
+
function decimalPlaces(value) {
|
|
156
|
+
var _a;
|
|
157
|
+
if (!isFinite(value)) return 0;
|
|
158
|
+
const [mantissa = "", exponent] = String(value).toLowerCase().split("e");
|
|
159
|
+
return Math.max(0, ((_a = mantissa.split(".")[1]) != null ? _a : "").length - Number(exponent != null ? exponent : 0));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// src/core/idempotency.ts
|
|
163
|
+
var UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
164
|
+
function bytesToUuid(bytes) {
|
|
165
|
+
var _a, _b, _c;
|
|
166
|
+
bytes[6] = ((_a = bytes[6]) != null ? _a : 0) & 15 | 64;
|
|
167
|
+
bytes[8] = ((_b = bytes[8]) != null ? _b : 0) & 63 | 128;
|
|
168
|
+
let hex = "";
|
|
169
|
+
for (let i = 0; i < 16; i++) hex += ((_c = bytes[i]) != null ? _c : 0).toString(16).padStart(2, "0");
|
|
170
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
171
|
+
}
|
|
172
|
+
function newIdempotencyKey() {
|
|
173
|
+
const c = globalThis.crypto;
|
|
174
|
+
if (c && typeof c.randomUUID === "function") {
|
|
175
|
+
return c.randomUUID();
|
|
176
|
+
}
|
|
177
|
+
const bytes = new Uint8Array(16);
|
|
178
|
+
if (c && typeof c.getRandomValues === "function") {
|
|
179
|
+
c.getRandomValues(bytes);
|
|
180
|
+
} else {
|
|
181
|
+
for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
182
|
+
}
|
|
183
|
+
return bytesToUuid(bytes);
|
|
184
|
+
}
|
|
185
|
+
function isIdempotencyKey(value) {
|
|
186
|
+
return typeof value === "string" && UUID_V4.test(value);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// src/core/mapping.ts
|
|
190
|
+
function croresToRupees(crores) {
|
|
191
|
+
const value = typeof crores === "string" ? parseInr(crores) : crores;
|
|
192
|
+
if (!isFinite(value)) return NaN;
|
|
193
|
+
return Math.round(value * RUPEES_PER_CRORE);
|
|
194
|
+
}
|
|
195
|
+
function rupeesToCrores(rupees) {
|
|
196
|
+
const value = typeof rupees === "string" ? parseInr(rupees) : rupees;
|
|
197
|
+
if (value === void 0 || value === null || !isFinite(value)) return "";
|
|
198
|
+
return String(Number((Math.round(value) / RUPEES_PER_CRORE).toFixed(7)));
|
|
199
|
+
}
|
|
200
|
+
function parseIntInput(text2) {
|
|
201
|
+
if (text2 === void 0 || text2 === null || text2 === "") return void 0;
|
|
202
|
+
const value = parseInr(text2);
|
|
203
|
+
if (!isFinite(value)) return void 0;
|
|
204
|
+
return Math.round(value);
|
|
205
|
+
}
|
|
206
|
+
function deriveLoanAmount(valueCr, downPaymentPct) {
|
|
207
|
+
const value = croresToRupees(valueCr);
|
|
208
|
+
const pct = typeof downPaymentPct === "string" ? parseInr(downPaymentPct) : downPaymentPct;
|
|
209
|
+
if (!isFinite(value) || !isFinite(pct)) return NaN;
|
|
210
|
+
return value - Math.round(value * pct / 100);
|
|
211
|
+
}
|
|
212
|
+
function person(p) {
|
|
213
|
+
const employment = { type: p.employmentType, monthlyIncome: parseInr(p.monthlyIncome) };
|
|
214
|
+
if (p.monthlyObligations.trim() !== "") employment.monthlyObligations = parseInr(p.monthlyObligations);
|
|
215
|
+
return { fullName: p.fullName.trim(), mobile: p.mobile.trim(), dob: p.dob.trim(), employment };
|
|
216
|
+
}
|
|
217
|
+
function toLeadInput(values, options = {}) {
|
|
218
|
+
var _a;
|
|
219
|
+
const property = {
|
|
220
|
+
type: values.propertyType,
|
|
221
|
+
location: values.location.trim(),
|
|
222
|
+
value: croresToRupees(values.propertyValueCr)
|
|
223
|
+
};
|
|
224
|
+
if (values.propertyType === PROPERTY_TYPES.UNDER_CONSTRUCTION) property.possessionDate = values.possessionDate;
|
|
225
|
+
if (values.propertyType === PROPERTY_TYPES.PLOT) property.hasDevelopmentPlan = values.hasDevelopmentPlan === "yes";
|
|
226
|
+
const input = {
|
|
227
|
+
product: PRODUCT,
|
|
228
|
+
applicant: { ...person(values.primary), consent: { given: true } },
|
|
229
|
+
property,
|
|
230
|
+
loan: { downPaymentPct: parseInr(values.downPaymentPct), tenureYears: (_a = parseIntInput(values.tenureYears)) != null ? _a : NaN }
|
|
231
|
+
};
|
|
232
|
+
if (options.consentText) input.applicant.consent.text = options.consentText;
|
|
233
|
+
if (options.consentCapturedAt) input.applicant.consent.capturedAt = options.consentCapturedAt;
|
|
234
|
+
if (values.applicantMode === "joint") input.coApplicant = person(values.co);
|
|
235
|
+
if (options.partnerReference) input.partnerReference = options.partnerReference;
|
|
236
|
+
if (options.metadata && Object.keys(options.metadata).length) input.metadata = options.metadata;
|
|
237
|
+
return input;
|
|
238
|
+
}
|
|
239
|
+
var isStr = (value) => typeof value === "string";
|
|
240
|
+
var isNum = (value) => typeof value === "number" && isFinite(value);
|
|
241
|
+
function personFrom(input) {
|
|
242
|
+
const out = {};
|
|
243
|
+
if (isStr(input.fullName)) out.fullName = input.fullName;
|
|
244
|
+
if (isStr(input.mobile)) out.mobile = input.mobile;
|
|
245
|
+
if (isStr(input.dob)) out.dob = input.dob;
|
|
246
|
+
const e = input.employment;
|
|
247
|
+
if (e) {
|
|
248
|
+
if (e.type && EMPLOYMENT_TYPE_VALUES.includes(e.type)) out.employmentType = e.type;
|
|
249
|
+
if (isNum(e.monthlyIncome)) out.monthlyIncome = String(e.monthlyIncome);
|
|
250
|
+
if (isNum(e.monthlyObligations)) out.monthlyObligations = String(e.monthlyObligations);
|
|
251
|
+
}
|
|
252
|
+
return out;
|
|
253
|
+
}
|
|
254
|
+
function fromLeadInput(input) {
|
|
255
|
+
var _a;
|
|
256
|
+
const out = {};
|
|
257
|
+
if (!input) return out;
|
|
258
|
+
const a = input.applicant;
|
|
259
|
+
if (a) {
|
|
260
|
+
const primary = personFrom(a);
|
|
261
|
+
if (Object.keys(primary).length) out.primary = primary;
|
|
262
|
+
if (typeof ((_a = a.consent) == null ? void 0 : _a.given) === "boolean") out.consentAccepted = a.consent.given;
|
|
263
|
+
}
|
|
264
|
+
const c = input.coApplicant;
|
|
265
|
+
if (c && Object.keys(c).length) {
|
|
266
|
+
out.applicantMode = "joint";
|
|
267
|
+
const co = personFrom(c);
|
|
268
|
+
if (Object.keys(co).length) out.co = co;
|
|
269
|
+
}
|
|
270
|
+
const p = input.property;
|
|
271
|
+
if (p) {
|
|
272
|
+
if (p.type && PROPERTY_TYPE_VALUES.includes(p.type)) out.propertyType = p.type;
|
|
273
|
+
if (isStr(p.location)) out.location = p.location;
|
|
274
|
+
if (isStr(p.possessionDate)) out.possessionDate = p.possessionDate;
|
|
275
|
+
if (typeof p.hasDevelopmentPlan === "boolean") out.hasDevelopmentPlan = p.hasDevelopmentPlan ? "yes" : "no";
|
|
276
|
+
if (isNum(p.value)) out.propertyValueCr = rupeesToCrores(p.value);
|
|
277
|
+
}
|
|
278
|
+
const l = input.loan;
|
|
279
|
+
if (l) {
|
|
280
|
+
if (isNum(l.downPaymentPct)) out.downPaymentPct = String(l.downPaymentPct);
|
|
281
|
+
if (isNum(l.tenureYears)) out.tenureYears = String(Math.round(l.tenureYears));
|
|
282
|
+
}
|
|
283
|
+
return out;
|
|
284
|
+
}
|
|
285
|
+
var PERSON_PATHS = [
|
|
286
|
+
["fullName", "fullName"],
|
|
287
|
+
["mobile", "mobile"],
|
|
288
|
+
["dob", "dob"],
|
|
289
|
+
["employment.type", "employmentType"],
|
|
290
|
+
["employment.monthlyIncome", "monthlyIncome"],
|
|
291
|
+
["employment.monthlyObligations", "monthlyObligations"],
|
|
292
|
+
["employment", "employmentType"]
|
|
293
|
+
];
|
|
294
|
+
var API_TO_FORM = {
|
|
295
|
+
"applicant.consent": "consentAccepted",
|
|
296
|
+
"applicant.consent.given": "consentAccepted",
|
|
297
|
+
"applicant.consent.text": "consentAccepted",
|
|
298
|
+
"applicant.consent.capturedAt": "consentAccepted",
|
|
299
|
+
// The server reports "coApplicant.mobile must differ from applicant.mobile" on `coApplicant`.
|
|
300
|
+
coApplicant: "co.mobile",
|
|
301
|
+
"property.type": "propertyType",
|
|
302
|
+
"property.location": "location",
|
|
303
|
+
"property.possessionDate": "possessionDate",
|
|
304
|
+
"property.hasDevelopmentPlan": "hasDevelopmentPlan",
|
|
305
|
+
"property.value": "propertyValueCr",
|
|
306
|
+
"loan.downPaymentPct": "downPaymentPct",
|
|
307
|
+
// The derived amount has no input: the down payment is what the applicant changes to fix it.
|
|
308
|
+
"loan.amount": "downPaymentPct",
|
|
309
|
+
"loan.tenureYears": "tenureYears"
|
|
310
|
+
};
|
|
311
|
+
var FORM_TO_API = {
|
|
312
|
+
applicantMode: "coApplicant",
|
|
313
|
+
propertyType: "property.type",
|
|
314
|
+
location: "property.location",
|
|
315
|
+
possessionDate: "property.possessionDate",
|
|
316
|
+
hasDevelopmentPlan: "property.hasDevelopmentPlan",
|
|
317
|
+
propertyValueCr: "property.value",
|
|
318
|
+
tenureYears: "loan.tenureYears",
|
|
319
|
+
downPaymentPct: "loan.downPaymentPct",
|
|
320
|
+
consentAccepted: "applicant.consent.given"
|
|
321
|
+
};
|
|
322
|
+
for (const [slot, prefix] of [
|
|
323
|
+
["primary", "applicant"],
|
|
324
|
+
["co", "coApplicant"]
|
|
325
|
+
]) {
|
|
326
|
+
for (const [path, key] of PERSON_PATHS) {
|
|
327
|
+
const formKey = `${slot}.${key}`;
|
|
328
|
+
const apiPath = `${prefix}.${path}`;
|
|
329
|
+
API_TO_FORM[apiPath] = formKey;
|
|
330
|
+
if (path !== "employment") FORM_TO_API[formKey] = apiPath;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
function apiFieldToFormKey(path) {
|
|
334
|
+
if (!path) return void 0;
|
|
335
|
+
const normalised = path.replace(/^\$\./, "").replace(/^\/+/, "").replace(/\//g, ".").replace(/\[(\d+)\]/g, "").replace(/^(body|data|payload)\./, "");
|
|
336
|
+
return API_TO_FORM[normalised];
|
|
337
|
+
}
|
|
338
|
+
function formKeyToApiField(key) {
|
|
339
|
+
return FORM_TO_API[key];
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// src/core/errors.ts
|
|
343
|
+
var SdkError = class extends Error {
|
|
344
|
+
constructor(code, message, options = {}) {
|
|
345
|
+
var _a;
|
|
346
|
+
super(message);
|
|
347
|
+
this.name = "SdkError";
|
|
348
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
349
|
+
this.code = code;
|
|
350
|
+
this.retryable = (_a = options.retryable) != null ? _a : false;
|
|
351
|
+
if (options.status !== void 0) this.status = options.status;
|
|
352
|
+
if (options.details !== void 0) this.details = options.details;
|
|
353
|
+
if (options.requestId !== void 0) this.requestId = options.requestId;
|
|
354
|
+
if (options.retryAfterMs !== void 0) this.retryAfterMs = options.retryAfterMs;
|
|
355
|
+
if (options.serverCode !== void 0) this.serverCode = options.serverCode;
|
|
356
|
+
if (options.cause !== void 0) this.cause = options.cause;
|
|
357
|
+
}
|
|
358
|
+
/** Validation errors keyed by form field, for `details` that map onto the form. */
|
|
359
|
+
get formErrors() {
|
|
360
|
+
return mapDetailsToFormErrors(this.details);
|
|
361
|
+
}
|
|
362
|
+
toJSON() {
|
|
363
|
+
return {
|
|
364
|
+
name: this.name,
|
|
365
|
+
code: this.code,
|
|
366
|
+
message: this.message,
|
|
367
|
+
status: this.status,
|
|
368
|
+
details: this.details,
|
|
369
|
+
retryable: this.retryable,
|
|
370
|
+
requestId: this.requestId,
|
|
371
|
+
retryAfterMs: this.retryAfterMs,
|
|
372
|
+
serverCode: this.serverCode
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
function isSdkError(value) {
|
|
377
|
+
return value instanceof SdkError || typeof value === "object" && value !== null && value.name === "SdkError";
|
|
378
|
+
}
|
|
379
|
+
function toSdkError(error) {
|
|
380
|
+
if (isSdkError(error)) return error;
|
|
381
|
+
return new SdkError("UNKNOWN", error instanceof Error ? error.message : "Unexpected error", { cause: error });
|
|
382
|
+
}
|
|
383
|
+
var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
|
|
384
|
+
var RETRYABLE_CODES = /* @__PURE__ */ new Set([
|
|
385
|
+
"RATE_LIMITED",
|
|
386
|
+
"UPSTREAM_UNAVAILABLE",
|
|
387
|
+
"NETWORK_ERROR",
|
|
388
|
+
"REQUEST_IN_PROGRESS"
|
|
389
|
+
]);
|
|
390
|
+
var RETRY_AFTER_CODES = /* @__PURE__ */ new Set(["RATE_LIMITED", "REQUEST_IN_PROGRESS"]);
|
|
391
|
+
var STATUS_FALLBACK_CODES = {
|
|
392
|
+
400: "VALIDATION_ERROR",
|
|
393
|
+
401: "UNAUTHENTICATED",
|
|
394
|
+
403: "INSUFFICIENT_SCOPE",
|
|
395
|
+
404: "NOT_FOUND",
|
|
396
|
+
422: "VALIDATION_ERROR",
|
|
397
|
+
429: "RATE_LIMITED",
|
|
398
|
+
500: "INTERNAL_ERROR",
|
|
399
|
+
502: "UPSTREAM_UNAVAILABLE",
|
|
400
|
+
503: "UPSTREAM_UNAVAILABLE",
|
|
401
|
+
504: "UPSTREAM_UNAVAILABLE"
|
|
402
|
+
};
|
|
403
|
+
var DEFAULT_MESSAGES = {
|
|
404
|
+
401: "Authentication failed",
|
|
405
|
+
403: "Not allowed",
|
|
406
|
+
404: "Not found",
|
|
407
|
+
429: "Too many requests",
|
|
408
|
+
500: "Server error",
|
|
409
|
+
502: "Service temporarily unavailable",
|
|
410
|
+
503: "Service temporarily unavailable",
|
|
411
|
+
504: "Service timed out"
|
|
412
|
+
};
|
|
413
|
+
function isApiErrorBody(body) {
|
|
414
|
+
if (typeof body !== "object" || body === null) return false;
|
|
415
|
+
const err = body.error;
|
|
416
|
+
return typeof err === "object" && err !== null && typeof err.code === "string";
|
|
417
|
+
}
|
|
418
|
+
function isKnownCode(code) {
|
|
419
|
+
return ERROR_CODES.includes(code);
|
|
420
|
+
}
|
|
421
|
+
function parseRetryAfter(value, now = Date.now()) {
|
|
422
|
+
if (!value) return void 0;
|
|
423
|
+
const trimmed = value.trim();
|
|
424
|
+
if (/^\d+$/.test(trimmed)) return parseInt(trimmed, 10) * 1e3;
|
|
425
|
+
const date2 = Date.parse(trimmed);
|
|
426
|
+
if (isNaN(date2)) return void 0;
|
|
427
|
+
return Math.max(0, date2 - now);
|
|
428
|
+
}
|
|
429
|
+
function fromApiError(status, body, headers) {
|
|
430
|
+
var _a, _b, _c, _d, _e;
|
|
431
|
+
const getHeader = (name) => {
|
|
432
|
+
var _a2;
|
|
433
|
+
if (!headers) return null;
|
|
434
|
+
if (typeof headers.get === "function") return headers.get(name);
|
|
435
|
+
const record = headers;
|
|
436
|
+
const key = Object.keys(record).find((k) => k.toLowerCase() === name.toLowerCase());
|
|
437
|
+
return key ? (_a2 = record[key]) != null ? _a2 : null : null;
|
|
438
|
+
};
|
|
439
|
+
let code;
|
|
440
|
+
let message;
|
|
441
|
+
let details;
|
|
442
|
+
let requestId;
|
|
443
|
+
let serverCode;
|
|
444
|
+
if (isApiErrorBody(body)) {
|
|
445
|
+
const err = body.error;
|
|
446
|
+
if (isKnownCode(err.code)) {
|
|
447
|
+
code = err.code;
|
|
448
|
+
} else {
|
|
449
|
+
code = (_a = STATUS_FALLBACK_CODES[status]) != null ? _a : "UNKNOWN";
|
|
450
|
+
serverCode = err.code;
|
|
451
|
+
}
|
|
452
|
+
message = typeof err.message === "string" && err.message ? err.message : (_b = DEFAULT_MESSAGES[status]) != null ? _b : `Request failed with status ${status}`;
|
|
453
|
+
details = Array.isArray(err.details) ? err.details.filter((d) => typeof (d == null ? void 0 : d.field) === "string" && typeof (d == null ? void 0 : d.message) === "string") : void 0;
|
|
454
|
+
requestId = typeof err.requestId === "string" ? err.requestId : void 0;
|
|
455
|
+
} else {
|
|
456
|
+
code = (_c = STATUS_FALLBACK_CODES[status]) != null ? _c : "UNKNOWN";
|
|
457
|
+
message = (_d = DEFAULT_MESSAGES[status]) != null ? _d : `Request failed with status ${status}`;
|
|
458
|
+
}
|
|
459
|
+
requestId = (_e = requestId != null ? requestId : getHeader("x-request-id")) != null ? _e : void 0;
|
|
460
|
+
const retryAfterMs = status === 429 || RETRY_AFTER_CODES.has(code) ? parseRetryAfter(getHeader("retry-after")) : void 0;
|
|
461
|
+
const retryable = RETRYABLE_STATUSES.has(status) || RETRYABLE_CODES.has(code);
|
|
462
|
+
return new SdkError(code, message, { status, details, retryable, requestId, retryAfterMs, serverCode });
|
|
463
|
+
}
|
|
464
|
+
function fromNetworkError(cause) {
|
|
465
|
+
if (isSdkError(cause)) return cause;
|
|
466
|
+
const name = cause == null ? void 0 : cause.name;
|
|
467
|
+
if (name === "AbortError") {
|
|
468
|
+
return new SdkError("ABORTED", "Request was aborted", { retryable: false, cause });
|
|
469
|
+
}
|
|
470
|
+
const message = cause instanceof Error && cause.message ? cause.message : "Network request failed";
|
|
471
|
+
return new SdkError("NETWORK_ERROR", message, { retryable: true, cause });
|
|
472
|
+
}
|
|
473
|
+
function mapDetailsToFormErrors(details) {
|
|
474
|
+
const errors = {};
|
|
475
|
+
if (!details) return errors;
|
|
476
|
+
for (const detail of details) {
|
|
477
|
+
const key = apiFieldToFormKey(detail.field);
|
|
478
|
+
if (key && errors[key] === void 0) errors[key] = detail.message;
|
|
479
|
+
}
|
|
480
|
+
return errors;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// src/core/schema.form.ts
|
|
484
|
+
import * as yup from "yup";
|
|
485
|
+
|
|
486
|
+
// src/core/dates.ts
|
|
487
|
+
function istToday(now = Date.now()) {
|
|
488
|
+
const ist = new Date(now + 330 * 6e4);
|
|
489
|
+
return [ist.getUTCFullYear(), ist.getUTCMonth() + 1, ist.getUTCDate()];
|
|
490
|
+
}
|
|
491
|
+
function parseYmd(value) {
|
|
492
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value != null ? value : "");
|
|
493
|
+
if (!match) return void 0;
|
|
494
|
+
const [y, m, d] = match.slice(1).map(Number);
|
|
495
|
+
const date2 = new Date(Date.UTC(y, m - 1, d));
|
|
496
|
+
return date2.getUTCFullYear() === y && date2.getUTCMonth() === m - 1 && date2.getUTCDate() === d ? [y, m, d] : void 0;
|
|
497
|
+
}
|
|
498
|
+
function formatYmd(y, m, d) {
|
|
499
|
+
return new Date(Date.UTC(y, m - 1, d)).toISOString().slice(0, 10);
|
|
500
|
+
}
|
|
501
|
+
var daysIn = (y, m) => new Date(Date.UTC(y, m, 0)).getUTCDate();
|
|
502
|
+
function ageOn(dob, now = Date.now()) {
|
|
503
|
+
const born = parseYmd(dob);
|
|
504
|
+
if (!born) return void 0;
|
|
505
|
+
const [y, m] = born;
|
|
506
|
+
const [ty, tm, td] = istToday(now);
|
|
507
|
+
const d = Math.min(born[2], daysIn(ty, m));
|
|
508
|
+
return ty - y - (tm < m || tm === m && td < d ? 1 : 0);
|
|
509
|
+
}
|
|
510
|
+
function istYearsAgo(years, days = 0, now = Date.now()) {
|
|
511
|
+
const [y, m, d] = istToday(now);
|
|
512
|
+
return formatYmd(y - years, m, Math.min(d, daysIn(y - years, m)) + days);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// src/core/i18n/en.ts
|
|
516
|
+
var en = {
|
|
517
|
+
locale: "en-IN",
|
|
518
|
+
steps: {
|
|
519
|
+
details: { title: "Your details" },
|
|
520
|
+
property: { title: "Property & loan" },
|
|
521
|
+
credit: { title: "Credit check" },
|
|
522
|
+
progress: "Application progress",
|
|
523
|
+
completed: "completed"
|
|
524
|
+
},
|
|
525
|
+
sections: {
|
|
526
|
+
applicantMode: {
|
|
527
|
+
title: "Who is applying for this home loan?",
|
|
528
|
+
description: "Adding a co-applicant can raise the eligible loan amount."
|
|
529
|
+
},
|
|
530
|
+
applicant: { title: "Applicant", description: "The applicant's contact, identity and employment details." },
|
|
531
|
+
coApplicant: {
|
|
532
|
+
title: "Co-applicant",
|
|
533
|
+
description: "The co-applicant's contact, identity and employment details."
|
|
534
|
+
},
|
|
535
|
+
property: { title: "Property details", description: "What's being bought, and where?" },
|
|
536
|
+
loan: {
|
|
537
|
+
title: "Loan sizing",
|
|
538
|
+
description: "Property value, down payment and tenure decide the loan amount."
|
|
539
|
+
}
|
|
540
|
+
},
|
|
541
|
+
fields: {
|
|
542
|
+
fullName: { label: "Full name", placeholder: "e.g. Rahul Sharma" },
|
|
543
|
+
mobile: { label: "Mobile number", placeholder: "e.g. 9876543210" },
|
|
544
|
+
dob: { label: "Date of birth", placeholder: "Select the date of birth" },
|
|
545
|
+
employmentType: { label: "Employment type" },
|
|
546
|
+
monthlyIncome: { label: "Monthly in-hand income (\u20B9)", placeholder: "e.g. 85000" },
|
|
547
|
+
monthlyProfit: { label: "Monthly profit (\u20B9)", placeholder: "e.g. 85000" },
|
|
548
|
+
monthlyObligations: { label: "Monthly obligations (\u20B9)", placeholder: "e.g. 15000 (optional)" },
|
|
549
|
+
propertyType: { label: "Property type" },
|
|
550
|
+
location: { label: "Property location", placeholder: "e.g. Whitefield, Bengaluru \u2014 560066" },
|
|
551
|
+
possessionDate: { label: "Expected possession date" },
|
|
552
|
+
hasDevelopmentPlan: { label: "Approved development plan in place?" },
|
|
553
|
+
propertyValueCr: { label: "Property value (\u20B9 Cr)", placeholder: "e.g. 1.0" },
|
|
554
|
+
tenureYears: { label: "Tenure (years)" },
|
|
555
|
+
downPaymentPct: { label: "Down payment (%)" },
|
|
556
|
+
downPaymentSlider: { label: "Down payment percent slider" }
|
|
557
|
+
},
|
|
558
|
+
options: {
|
|
559
|
+
applicantModes: [
|
|
560
|
+
{ value: "single", label: "Just the applicant" },
|
|
561
|
+
{ value: "joint", label: "Applicant + co-applicant" }
|
|
562
|
+
],
|
|
563
|
+
employmentTypes: [
|
|
564
|
+
{ value: "SALARIED", label: "Salaried", description: "Regular monthly salary" },
|
|
565
|
+
{ value: "SELF_EMPLOYED", label: "Self-employed", description: "Business or professional practice" }
|
|
566
|
+
],
|
|
567
|
+
propertyTypes: [
|
|
568
|
+
{ value: "APARTMENT", label: "Apartment" },
|
|
569
|
+
{ value: "INDEPENDENT_HOUSE", label: "Independent house" },
|
|
570
|
+
{ value: "PLOT", label: "Plot" },
|
|
571
|
+
{ value: "UNDER_CONSTRUCTION", label: "Under construction" },
|
|
572
|
+
{ value: "TOWNHOUSE", label: "Townhouse" },
|
|
573
|
+
{ value: "VILLA", label: "Villa" },
|
|
574
|
+
{ value: "DUPLEX", label: "Duplex" },
|
|
575
|
+
{ value: "CHS", label: "CHS" }
|
|
576
|
+
],
|
|
577
|
+
select: "Select\u2026",
|
|
578
|
+
yes: "Yes",
|
|
579
|
+
no: "No"
|
|
580
|
+
},
|
|
581
|
+
errors: {
|
|
582
|
+
fullNameRequired: "Enter the full name",
|
|
583
|
+
fullNameTooLong: "Full name cannot exceed 120 characters",
|
|
584
|
+
mobileRequired: "Enter the mobile number",
|
|
585
|
+
mobileInvalid: "Enter a valid 10-digit mobile number",
|
|
586
|
+
mobileSameAsOther: "Must be different from the other applicant",
|
|
587
|
+
dobRequired: "Enter the date of birth",
|
|
588
|
+
dateInvalid: "Enter a valid date",
|
|
589
|
+
dobAge: "Age must be between 18 and 70",
|
|
590
|
+
employmentTypeRequired: "Select the employment type",
|
|
591
|
+
monthlyIncomeInvalid: "Monthly income must be greater than 0",
|
|
592
|
+
obligationsNegative: "Obligations cannot be negative",
|
|
593
|
+
amountTooLarge: "Amount cannot exceed \u20B91,000 Cr",
|
|
594
|
+
amountDecimals: "Amount can have at most 2 decimal places",
|
|
595
|
+
propertyTypeRequired: "Select the property type",
|
|
596
|
+
locationRequired: "Enter the property location",
|
|
597
|
+
locationTooLong: "Property location cannot exceed 256 characters",
|
|
598
|
+
possessionDateRequired: "Enter the expected possession date",
|
|
599
|
+
developmentPlanRequired: "Select whether a development plan is in place",
|
|
600
|
+
propertyValueRange: "Enter a property value between \u20B90.05 Cr and \u20B9100 Cr",
|
|
601
|
+
tenureRange: "Tenure must be between 1 and 30 years",
|
|
602
|
+
downPaymentRange: "Down payment must be between 0% and 90%",
|
|
603
|
+
downPaymentDecimals: "Down payment can have at most 2 decimal places",
|
|
604
|
+
loanAmountRange: "Loan amount must be between \u20B95,00,000 and \u20B920,00,00,000",
|
|
605
|
+
consentRequired: "Please accept the consent to continue"
|
|
606
|
+
},
|
|
607
|
+
actions: {
|
|
608
|
+
continue: "Continue",
|
|
609
|
+
back: "Back",
|
|
610
|
+
submit: "Submit application",
|
|
611
|
+
submitting: "Submitting\u2026",
|
|
612
|
+
retry: "Try again",
|
|
613
|
+
copied: "Copied"
|
|
614
|
+
},
|
|
615
|
+
loanSummary: {
|
|
616
|
+
title: "Loan amount (auto-calculated)",
|
|
617
|
+
waiting: "Waiting for input",
|
|
618
|
+
crores: "Cr"
|
|
619
|
+
},
|
|
620
|
+
datePicker: {
|
|
621
|
+
months: [
|
|
622
|
+
"January",
|
|
623
|
+
"February",
|
|
624
|
+
"March",
|
|
625
|
+
"April",
|
|
626
|
+
"May",
|
|
627
|
+
"June",
|
|
628
|
+
"July",
|
|
629
|
+
"August",
|
|
630
|
+
"September",
|
|
631
|
+
"October",
|
|
632
|
+
"November",
|
|
633
|
+
"December"
|
|
634
|
+
],
|
|
635
|
+
weekdays: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
|
|
636
|
+
open: "Open calendar",
|
|
637
|
+
dialog: "Choose a date",
|
|
638
|
+
previousMonth: "Previous month",
|
|
639
|
+
nextMonth: "Next month",
|
|
640
|
+
month: "Select month",
|
|
641
|
+
year: "Select year",
|
|
642
|
+
placeholder: "Select date"
|
|
643
|
+
},
|
|
644
|
+
consent: {
|
|
645
|
+
text: "I authorise MoneyKarma and its partner lenders to contact me by phone, SMS, WhatsApp or email regarding my home loan application and to process my details for this purpose.",
|
|
646
|
+
termsLinkText: "Terms of Use",
|
|
647
|
+
privacyLinkText: "Privacy Policy",
|
|
648
|
+
agreePrefix: "I agree to the",
|
|
649
|
+
and: "and"
|
|
650
|
+
},
|
|
651
|
+
success: {
|
|
652
|
+
title: "Application received",
|
|
653
|
+
description: "Our team is reviewing the application and will reach out shortly to take it forward.",
|
|
654
|
+
duplicateTitle: "You already have an application with us",
|
|
655
|
+
duplicateDescription: "We found an existing home-loan application for this mobile number. Our team will contact you on it.",
|
|
656
|
+
referenceLabel: "Application reference",
|
|
657
|
+
copyReference: "Copy reference {reference}",
|
|
658
|
+
nextSteps: "Keep recent salary slips or bank statements ready. Self-employed? Keep ITR and GST returns handy.",
|
|
659
|
+
continue: "Continue",
|
|
660
|
+
redirecting: "Taking you back in {seconds} s\u2026"
|
|
661
|
+
},
|
|
662
|
+
status: {
|
|
663
|
+
poweredBy: "Powered by MoneyKarma"
|
|
664
|
+
},
|
|
665
|
+
ui: {
|
|
666
|
+
errorSummaryTitle: "Please fix the highlighted fields",
|
|
667
|
+
formUnavailable: "This form is unavailable right now."
|
|
668
|
+
},
|
|
669
|
+
credit: {
|
|
670
|
+
title: "Check your credit score",
|
|
671
|
+
description: "Optional. See your credit score band in about a minute; your application is already submitted.",
|
|
672
|
+
dob: { label: "Date of birth" },
|
|
673
|
+
pan: { label: "PAN", placeholder: "e.g. ABCPE1234F", hint: "Your individual PAN (the 4th letter is P)" },
|
|
674
|
+
pincode: { label: "Pincode", placeholder: "Enter 6-digit pincode", hint: "Pincode of your current address" },
|
|
675
|
+
consentLabel: "I agree to this credit check",
|
|
676
|
+
sendOtp: "Send OTP",
|
|
677
|
+
sending: "Sending OTP\u2026",
|
|
678
|
+
skip: "Skip for now",
|
|
679
|
+
otpTitle: "Enter the OTP",
|
|
680
|
+
otpSentTo: "We sent a 6-digit code to {mobile}. Entering it confirms your consent.",
|
|
681
|
+
otp: { label: "OTP" },
|
|
682
|
+
verify: "Verify and check score",
|
|
683
|
+
resendIn: "Resend OTP in {seconds} s",
|
|
684
|
+
resend: "Resend OTP",
|
|
685
|
+
changeDetails: "Change details",
|
|
686
|
+
attemptsLeft: "{count} attempts left",
|
|
687
|
+
verifying: "Checking your credit score\u2026",
|
|
688
|
+
verifyingNote: "This can take up to a minute. Please keep this page open.",
|
|
689
|
+
resultTitle: "Your credit score",
|
|
690
|
+
scoreLabel: "Credit score",
|
|
691
|
+
bandLabel: "Score band",
|
|
692
|
+
bandOnlyNote: "",
|
|
693
|
+
reused: "We used your credit report from the last 30 days, so no new bureau enquiry was made.",
|
|
694
|
+
noHitTitle: "No credit history found",
|
|
695
|
+
noHit: "The bureau has no record for these details. This is common if you have not borrowed before and does not affect your application.",
|
|
696
|
+
failedTitle: "We could not fetch your score",
|
|
697
|
+
mismatch: "The details did not match the credit bureau records. Your application is not affected.",
|
|
698
|
+
bureauUnavailable: "The credit bureau is unavailable right now. Your application is not affected.",
|
|
699
|
+
unavailableTitle: "The credit bureau is not responding",
|
|
700
|
+
stillChecking: "Still checking with the bureau. Try again in a moment.",
|
|
701
|
+
skippedTitle: "Credit check skipped",
|
|
702
|
+
skipped: "No problem. Your application is submitted and our loan expert will guide you from here.",
|
|
703
|
+
consentChanged: "The consent text has been updated. Please read it and agree again.",
|
|
704
|
+
limitReached: "Credit check is unavailable right now. You can skip and continue.",
|
|
705
|
+
inProgress: "A check is already in progress. Try again in a moment.",
|
|
706
|
+
startAgain: "This code request expired. Send a new code.",
|
|
707
|
+
errors: {
|
|
708
|
+
dobRequired: "Date of birth is required",
|
|
709
|
+
dobInvalid: "Enter a valid date",
|
|
710
|
+
dobAge: "You must be between 18 and 100 years old",
|
|
711
|
+
panRequired: "PAN is required",
|
|
712
|
+
panInvalid: "Enter a valid individual PAN, e.g. ABCPE1234F",
|
|
713
|
+
otpInvalid: "Enter the 6-digit OTP",
|
|
714
|
+
consentRequired: "Please agree to the credit check to continue",
|
|
715
|
+
pincodeRequired: "Pincode is required",
|
|
716
|
+
pincodeInvalid: "Pincode must be 6 digits"
|
|
717
|
+
}
|
|
718
|
+
},
|
|
719
|
+
apiErrors: {
|
|
720
|
+
UNAUTHENTICATED: "This form could not be authorised. Please refresh the page.",
|
|
721
|
+
CREDENTIAL_TYPE_NOT_ALLOWED: "This form is not configured correctly. Please contact the site owner.",
|
|
722
|
+
INSUFFICIENT_SCOPE: "This form is not configured correctly. Please contact the site owner.",
|
|
723
|
+
ORIGIN_REQUIRED: "This form cannot be used from this page.",
|
|
724
|
+
ORIGIN_NOT_ALLOWED: "This form cannot be used from this website.",
|
|
725
|
+
SECRET_KEY_IN_BROWSER: "This form is not configured correctly. Please contact the site owner.",
|
|
726
|
+
INTEGRATION_DISABLED: "This form is currently unavailable.",
|
|
727
|
+
LINK_EXPIRED: "This application link has expired.",
|
|
728
|
+
LINK_INACTIVE: "This application link is no longer active.",
|
|
729
|
+
VALIDATION_ERROR: "Please check the highlighted fields and try again.",
|
|
730
|
+
NOT_FOUND: "We could not find what you were looking for.",
|
|
731
|
+
IDEMPOTENCY_KEY_REUSED: "This request was already submitted with different details. Please try again.",
|
|
732
|
+
REQUEST_IN_PROGRESS: "Your application is still being processed. Please wait a moment.",
|
|
733
|
+
CAPTCHA_FAILED: "We could not verify that you are human. Please try again.",
|
|
734
|
+
CUSTOMER_ALREADY_ENGAGED: "You already have an active application with MoneyKarma. Our team will be in touch.",
|
|
735
|
+
PARTNER_NOT_ELIGIBLE: "We are unable to take this application right now.",
|
|
736
|
+
CREDIT_CHECK_NOT_ALLOWED: "A credit check is not available for this application right now.",
|
|
737
|
+
OTP_INVALID: "That OTP is not correct. Please check the SMS and try again.",
|
|
738
|
+
OTP_EXPIRED: "This OTP has expired. Please request a new one.",
|
|
739
|
+
OTP_LOCKED: "Too many incorrect attempts. Please request a new OTP.",
|
|
740
|
+
CONSENT_REVOKED: "You have withdrawn your consent for credit checks with MoneyKarma, so we cannot check your score here.",
|
|
741
|
+
RATE_LIMITED: "Too many attempts. Please wait a moment and try again.",
|
|
742
|
+
UPSTREAM_UNAVAILABLE: "Our service is temporarily unavailable. Please try again shortly.",
|
|
743
|
+
INTERNAL_ERROR: "Something went wrong on our side. Please try again.",
|
|
744
|
+
NETWORK_ERROR: "We could not reach our servers. Check your connection and try again.",
|
|
745
|
+
INVALID_RESPONSE: "We received an unexpected response. Please try again.",
|
|
746
|
+
CONFIG_ERROR: "This form is not configured correctly. Please contact the site owner.",
|
|
747
|
+
CAPTCHA_UNAVAILABLE: "Security check could not be loaded. Please refresh and try again.",
|
|
748
|
+
ABORTED: "The request was cancelled.",
|
|
749
|
+
UNKNOWN: "Something went wrong. Please try again."
|
|
750
|
+
}
|
|
751
|
+
};
|
|
752
|
+
|
|
753
|
+
// src/core/schema.form.ts
|
|
754
|
+
var EMPTY_PERSON = {
|
|
755
|
+
fullName: "",
|
|
756
|
+
mobile: "",
|
|
757
|
+
dob: "",
|
|
758
|
+
employmentType: EMPLOYMENT_TYPES.SALARIED,
|
|
759
|
+
monthlyIncome: "",
|
|
760
|
+
monthlyObligations: ""
|
|
761
|
+
};
|
|
762
|
+
var INITIAL_FORM_VALUES = {
|
|
763
|
+
applicantMode: "single",
|
|
764
|
+
primary: EMPTY_PERSON,
|
|
765
|
+
co: EMPTY_PERSON,
|
|
766
|
+
propertyType: "",
|
|
767
|
+
location: "",
|
|
768
|
+
possessionDate: "",
|
|
769
|
+
hasDevelopmentPlan: "",
|
|
770
|
+
propertyValueCr: "",
|
|
771
|
+
tenureYears: "20",
|
|
772
|
+
downPaymentPct: "20",
|
|
773
|
+
consentAccepted: false
|
|
774
|
+
};
|
|
775
|
+
var isBlank = (value) => !value || value.trim() === "";
|
|
776
|
+
var within = (n, range) => isFinite(n) && n >= range.min && n <= range.max;
|
|
777
|
+
var text = () => yup.string().trim().default("");
|
|
778
|
+
var notTooLarge = (value) => !(parseInr(value) > LIMITS.amount.max);
|
|
779
|
+
var twoDecimals = (value) => decimalPlaces(parseInr(value)) <= 2;
|
|
780
|
+
function personSchema(m, isCo, fullNameMax) {
|
|
781
|
+
let mobile = text().required(m.mobileRequired).matches(REGEX.mobile, m.mobileInvalid);
|
|
782
|
+
if (isCo) {
|
|
783
|
+
mobile = mobile.test("different", m.mobileSameAsOther, function(value) {
|
|
784
|
+
var _a, _b, _c, _d;
|
|
785
|
+
const root = (_b = (_a = this.from) == null ? void 0 : _a[1]) == null ? void 0 : _b.value;
|
|
786
|
+
return !value || value !== ((_d = (_c = root == null ? void 0 : root.primary) == null ? void 0 : _c.mobile) == null ? void 0 : _d.trim());
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
return yup.object({
|
|
790
|
+
fullName: text().required(m.fullNameRequired).max(fullNameMax, m.fullNameTooLong),
|
|
791
|
+
mobile,
|
|
792
|
+
dob: text().required(m.dobRequired).test("date", m.dateInvalid, (value) => isBlank(value) || !!parseYmd(value)).test("age", m.dobAge, (value) => {
|
|
793
|
+
const age = ageOn(value != null ? value : "");
|
|
794
|
+
return age === void 0 || within(age, LIMITS.applicantAge);
|
|
795
|
+
}),
|
|
796
|
+
employmentType: yup.string().oneOf(EMPLOYMENT_TYPE_VALUES, m.employmentTypeRequired).default(EMPLOYMENT_TYPES.SALARIED).required(m.employmentTypeRequired),
|
|
797
|
+
monthlyIncome: text().test("positive", m.monthlyIncomeInvalid, (value) => parseInr(value) > 0).test("max", m.amountTooLarge, notTooLarge).test("decimals", m.amountDecimals, twoDecimals),
|
|
798
|
+
monthlyObligations: text().test("non-negative", m.obligationsNegative, (value) => isBlank(value) || parseInr(value) >= 0).test("max", m.amountTooLarge, notTooLarge).test("decimals", m.amountDecimals, twoDecimals)
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
function createFormSchema(m = en.errors, limits = {}) {
|
|
802
|
+
var _a, _b;
|
|
803
|
+
const { UNDER_CONSTRUCTION, PLOT } = PROPERTY_TYPES;
|
|
804
|
+
const fullNameMax = (_a = limits.fullName) != null ? _a : LIMITS.fullName.max;
|
|
805
|
+
return yup.object({
|
|
806
|
+
applicantMode: yup.string().oneOf(["single", "joint"]).default("single").required(),
|
|
807
|
+
primary: personSchema(m, false, fullNameMax),
|
|
808
|
+
co: yup.object().when("applicantMode", {
|
|
809
|
+
is: "joint",
|
|
810
|
+
then: () => personSchema(m, true, fullNameMax)
|
|
811
|
+
}),
|
|
812
|
+
propertyType: yup.string().default("").required(m.propertyTypeRequired).oneOf(PROPERTY_TYPE_VALUES, m.propertyTypeRequired),
|
|
813
|
+
location: text().required(m.locationRequired).max((_b = limits.location) != null ? _b : LIMITS.location.max, m.locationTooLong),
|
|
814
|
+
possessionDate: text().when("propertyType", {
|
|
815
|
+
is: UNDER_CONSTRUCTION,
|
|
816
|
+
then: (s) => s.required(m.possessionDateRequired).test("date", m.dateInvalid, (value) => isBlank(value) || !!parseYmd(value))
|
|
817
|
+
}),
|
|
818
|
+
hasDevelopmentPlan: yup.string().default("").when("propertyType", {
|
|
819
|
+
is: PLOT,
|
|
820
|
+
then: (s) => s.required(m.developmentPlanRequired).oneOf(["yes", "no"], m.developmentPlanRequired)
|
|
821
|
+
}),
|
|
822
|
+
propertyValueCr: text().test(
|
|
823
|
+
"range",
|
|
824
|
+
m.propertyValueRange,
|
|
825
|
+
(value) => within(croresToRupees(value != null ? value : ""), LIMITS.propertyValue)
|
|
826
|
+
),
|
|
827
|
+
tenureYears: text().test(
|
|
828
|
+
"range",
|
|
829
|
+
m.tenureRange,
|
|
830
|
+
(value) => /^\d+$/.test(value != null ? value : "") && within(Number(value), LIMITS.tenureYears)
|
|
831
|
+
),
|
|
832
|
+
downPaymentPct: text().test("range", m.downPaymentRange, (value) => !isBlank(value) && within(parseInr(value), LIMITS.downPaymentPct)).test("decimals", m.downPaymentDecimals, twoDecimals).test("loan-amount", m.loanAmountRange, function(value) {
|
|
833
|
+
const { propertyValueCr } = this.parent;
|
|
834
|
+
if (!within(croresToRupees(propertyValueCr), LIMITS.propertyValue)) return true;
|
|
835
|
+
if (!within(parseInr(value), LIMITS.downPaymentPct)) return true;
|
|
836
|
+
return within(deriveLoanAmount(propertyValueCr, value != null ? value : ""), LIMITS.loanAmount);
|
|
837
|
+
}),
|
|
838
|
+
consentAccepted: yup.boolean().default(false).oneOf([true], m.consentRequired).required(m.consentRequired)
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
var formSchema = createFormSchema();
|
|
842
|
+
function yupErrorToFormErrors(error) {
|
|
843
|
+
const errors = {};
|
|
844
|
+
if (!(error instanceof yup.ValidationError)) return errors;
|
|
845
|
+
const all = error.inner.length ? error.inner : [error];
|
|
846
|
+
for (const inner of all) {
|
|
847
|
+
const key = inner.path;
|
|
848
|
+
if (key && errors[key] === void 0) errors[key] = inner.message;
|
|
849
|
+
}
|
|
850
|
+
return errors;
|
|
851
|
+
}
|
|
852
|
+
async function validateFormValues(values, schema = formSchema) {
|
|
853
|
+
try {
|
|
854
|
+
await schema.validate(values, { abortEarly: false });
|
|
855
|
+
return {};
|
|
856
|
+
} catch (error) {
|
|
857
|
+
if (error instanceof yup.ValidationError) return yupErrorToFormErrors(error);
|
|
858
|
+
throw error;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
// src/core/schema.lead.ts
|
|
863
|
+
import * as yup2 from "yup";
|
|
864
|
+
var twoDecimals2 = (v) => v === void 0 || decimalPlaces(v) <= 2;
|
|
865
|
+
function withoutNulls(value) {
|
|
866
|
+
if (Array.isArray(value)) return value.map(withoutNulls);
|
|
867
|
+
if (value === null || typeof value !== "object") return value;
|
|
868
|
+
const out = {};
|
|
869
|
+
for (const [key, v] of Object.entries(value)) if (v !== null) out[key] = withoutNulls(v);
|
|
870
|
+
return out;
|
|
871
|
+
}
|
|
872
|
+
var amount = (name) => yup2.number().typeError(`${name} must be a number`).max(LIMITS.amount.max, `${name} must not be greater than ${LIMITS.amount.max}`).test("decimals", `${name} must have at most 2 decimal places`, twoDecimals2);
|
|
873
|
+
var date = (name) => yup2.string().trim().test(
|
|
874
|
+
"date",
|
|
875
|
+
`${name} must be a valid date in YYYY-MM-DD format`,
|
|
876
|
+
(value) => value === void 0 || !!parseYmd(value)
|
|
877
|
+
);
|
|
878
|
+
var employmentSchema = yup2.object({
|
|
879
|
+
type: yup2.string().oneOf(EMPLOYMENT_TYPE_VALUES, "Employment type is invalid").required("Employment type is required"),
|
|
880
|
+
monthlyIncome: amount("monthlyIncome").required("monthlyIncome is required").min(0.01, "monthlyIncome must be at least 0.01"),
|
|
881
|
+
monthlyObligations: amount("monthlyObligations").min(0, "monthlyObligations must not be less than 0").optional()
|
|
882
|
+
});
|
|
883
|
+
var personFields = {
|
|
884
|
+
fullName: yup2.string().trim().required("fullName is required").max(LIMITS.fullName.max, `fullName must be shorter than or equal to ${LIMITS.fullName.max} characters`),
|
|
885
|
+
mobile: yup2.string().trim().required("mobile is required").matches(REGEX.mobile, "mobile must be a 10-digit Indian mobile number"),
|
|
886
|
+
dob: date("dob").required("dob is required").test("age", "age must be between 18 and 70 years on today's date in India", (value) => {
|
|
887
|
+
const age = ageOn(value != null ? value : "");
|
|
888
|
+
return age === void 0 || age >= LIMITS.applicantAge.min && age <= LIMITS.applicantAge.max;
|
|
889
|
+
}),
|
|
890
|
+
employment: employmentSchema.required("Employment is required")
|
|
891
|
+
};
|
|
892
|
+
var consentSchema = yup2.object({
|
|
893
|
+
given: yup2.boolean().required("Consent is required").oneOf([true], "Consent must be given"),
|
|
894
|
+
text: yup2.string().optional(),
|
|
895
|
+
capturedAt: yup2.string().optional()
|
|
896
|
+
}).default(void 0);
|
|
897
|
+
var applicantSchema = yup2.object({
|
|
898
|
+
...personFields,
|
|
899
|
+
consent: consentSchema.required("Consent is required")
|
|
900
|
+
});
|
|
901
|
+
var coApplicantSchema = yup2.object(personFields);
|
|
902
|
+
var absent = (s, message) => s.test("absent", message, (v) => v === void 0);
|
|
903
|
+
var propertySchema = yup2.object({
|
|
904
|
+
type: yup2.string().oneOf(PROPERTY_TYPE_VALUES, "Property type is invalid").required("Property type is required"),
|
|
905
|
+
location: yup2.string().trim().required("Property location is required").max(LIMITS.location.max, `Property location cannot exceed ${LIMITS.location.max} characters`),
|
|
906
|
+
possessionDate: date("possessionDate").when("type", {
|
|
907
|
+
is: PROPERTY_TYPES.UNDER_CONSTRUCTION,
|
|
908
|
+
then: (s) => s.required("possessionDate is required when type is UNDER_CONSTRUCTION"),
|
|
909
|
+
otherwise: (s) => absent(s, "possessionDate is only allowed when type is UNDER_CONSTRUCTION")
|
|
910
|
+
}),
|
|
911
|
+
hasDevelopmentPlan: yup2.boolean().when("type", {
|
|
912
|
+
is: PROPERTY_TYPES.PLOT,
|
|
913
|
+
then: (s) => s.required("hasDevelopmentPlan is required when type is PLOT"),
|
|
914
|
+
otherwise: (s) => absent(s, "hasDevelopmentPlan is only allowed when type is PLOT")
|
|
915
|
+
}),
|
|
916
|
+
value: yup2.number().typeError("value must be a number").required("value is required").min(LIMITS.propertyValue.min, `value must not be less than ${LIMITS.propertyValue.min}`).max(LIMITS.propertyValue.max, `value must not be greater than ${LIMITS.propertyValue.max}`).integer("value must be an integer number")
|
|
917
|
+
});
|
|
918
|
+
var loanSchema = yup2.object({
|
|
919
|
+
downPaymentPct: yup2.number().typeError("downPaymentPct must be a number").required("downPaymentPct is required").min(LIMITS.downPaymentPct.min, `downPaymentPct must not be less than ${LIMITS.downPaymentPct.min}`).max(LIMITS.downPaymentPct.max, `downPaymentPct must not be greater than ${LIMITS.downPaymentPct.max}`).test("decimals", "downPaymentPct must have at most 2 decimal places", twoDecimals2),
|
|
920
|
+
tenureYears: yup2.number().typeError("tenureYears must be a number").required("tenureYears is required").integer("tenureYears must be an integer number").min(LIMITS.tenureYears.min, `tenureYears must not be less than ${LIMITS.tenureYears.min}`).max(LIMITS.tenureYears.max, `tenureYears must not be greater than ${LIMITS.tenureYears.max}`)
|
|
921
|
+
});
|
|
922
|
+
var metadataSchema = yup2.mixed().optional().test(
|
|
923
|
+
"metadata",
|
|
924
|
+
`Metadata must be an object with at most ${LIMITS.metadataKeys.max} string/number/boolean values`,
|
|
925
|
+
(value) => {
|
|
926
|
+
if (value === void 0 || value === null) return true;
|
|
927
|
+
if (typeof value !== "object" || Array.isArray(value)) return false;
|
|
928
|
+
const entries = Object.entries(value);
|
|
929
|
+
if (entries.length > LIMITS.metadataKeys.max) return false;
|
|
930
|
+
return entries.every(([, v]) => ["string", "number", "boolean"].includes(typeof v));
|
|
931
|
+
}
|
|
932
|
+
);
|
|
933
|
+
var attributionSchema = yup2.object({
|
|
934
|
+
utmSource: yup2.string().trim().optional(),
|
|
935
|
+
utmMedium: yup2.string().trim().optional(),
|
|
936
|
+
utmCampaign: yup2.string().trim().optional(),
|
|
937
|
+
utmContent: yup2.string().trim().optional(),
|
|
938
|
+
utmTerm: yup2.string().trim().optional()
|
|
939
|
+
}).default(void 0).optional();
|
|
940
|
+
var leadSchema = yup2.object({
|
|
941
|
+
product: yup2.string().oneOf([PRODUCT], `product must be ${PRODUCT}`).required("product is required"),
|
|
942
|
+
applicant: applicantSchema.default(void 0).required("Applicant is required"),
|
|
943
|
+
coApplicant: coApplicantSchema.default(void 0).optional(),
|
|
944
|
+
property: propertySchema.default(void 0).required("Property is required"),
|
|
945
|
+
loan: loanSchema.default(void 0).required("Loan is required"),
|
|
946
|
+
partnerReference: yup2.string().trim().max(LIMITS.partnerReference.max, `partnerReference cannot exceed ${LIMITS.partnerReference.max} characters`).optional(),
|
|
947
|
+
metadata: metadataSchema,
|
|
948
|
+
attribution: attributionSchema
|
|
949
|
+
}).transform((value) => withoutNulls(value)).test("co-applicant-mobile-differs", "coApplicant.mobile must differ from applicant.mobile", function(value) {
|
|
950
|
+
var _a, _b;
|
|
951
|
+
const primary = (_a = value == null ? void 0 : value.applicant) == null ? void 0 : _a.mobile;
|
|
952
|
+
const secondary = (_b = value == null ? void 0 : value.coApplicant) == null ? void 0 : _b.mobile;
|
|
953
|
+
if (primary && secondary && primary === secondary) {
|
|
954
|
+
return this.createError({ path: "coApplicant", message: "coApplicant.mobile must differ from applicant.mobile" });
|
|
955
|
+
}
|
|
956
|
+
return true;
|
|
957
|
+
}).test("loan-amount", "Loan amount is out of range", function(value) {
|
|
958
|
+
var _a, _b;
|
|
959
|
+
const propertyValue = (_a = value == null ? void 0 : value.property) == null ? void 0 : _a.value;
|
|
960
|
+
const pct = (_b = value == null ? void 0 : value.loan) == null ? void 0 : _b.downPaymentPct;
|
|
961
|
+
if (typeof propertyValue !== "number" || typeof pct !== "number") return true;
|
|
962
|
+
const loanAmount = propertyValue - Math.round(propertyValue * pct / 100);
|
|
963
|
+
if (loanAmount >= LIMITS.loanAmount.min && loanAmount <= LIMITS.loanAmount.max) return true;
|
|
964
|
+
return this.createError({
|
|
965
|
+
path: "loan.downPaymentPct",
|
|
966
|
+
message: "the loan amount (property value minus down payment) must be between \u20B95,00,000 and \u20B920,00,00,000"
|
|
967
|
+
});
|
|
968
|
+
});
|
|
969
|
+
function validateLeadInput(input) {
|
|
970
|
+
return leadSchema.validate(input, { abortEarly: false, stripUnknown: false });
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
// src/core/http.ts
|
|
974
|
+
function resolveFetch(custom) {
|
|
975
|
+
if (custom) return custom;
|
|
976
|
+
const f = globalThis.fetch;
|
|
977
|
+
if (typeof f !== "function") {
|
|
978
|
+
throw new SdkError("CONFIG_ERROR", "No fetch implementation available; pass `fetch` in the client options");
|
|
979
|
+
}
|
|
980
|
+
return (input, init) => f(input, init);
|
|
981
|
+
}
|
|
982
|
+
function abortedError() {
|
|
983
|
+
return new SdkError("ABORTED", "Request was aborted", { retryable: false });
|
|
984
|
+
}
|
|
985
|
+
function timeoutError(timeoutMs, cause) {
|
|
986
|
+
return new SdkError("NETWORK_ERROR", `Request timed out after ${timeoutMs} ms`, { retryable: true, cause });
|
|
987
|
+
}
|
|
988
|
+
function abortableSleep(ms, signal) {
|
|
989
|
+
return new Promise((resolve, reject) => {
|
|
990
|
+
if (signal == null ? void 0 : signal.aborted) {
|
|
991
|
+
reject(abortedError());
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
994
|
+
const onAbort = () => {
|
|
995
|
+
clearTimeout(timer);
|
|
996
|
+
reject(abortedError());
|
|
997
|
+
};
|
|
998
|
+
const timer = setTimeout(() => {
|
|
999
|
+
signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
|
|
1000
|
+
resolve();
|
|
1001
|
+
}, ms);
|
|
1002
|
+
signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
async function sendJson(fetchImpl, url, request) {
|
|
1006
|
+
var _a, _b, _c;
|
|
1007
|
+
const headers = { Accept: "application/json", ...request.headers };
|
|
1008
|
+
if (request.body !== void 0) headers["Content-Type"] = "application/json";
|
|
1009
|
+
const callerSignal = request.signal;
|
|
1010
|
+
if (callerSignal == null ? void 0 : callerSignal.aborted) throw abortedError();
|
|
1011
|
+
const timeoutMs = (_a = request.timeoutMs) != null ? _a : 0;
|
|
1012
|
+
const controller = typeof AbortController === "function" ? new AbortController() : void 0;
|
|
1013
|
+
let timedOut = false;
|
|
1014
|
+
let rejectAborted = () => void 0;
|
|
1015
|
+
const aborted = new Promise((_, reject) => {
|
|
1016
|
+
rejectAborted = reject;
|
|
1017
|
+
});
|
|
1018
|
+
aborted.catch(() => void 0);
|
|
1019
|
+
const abort = () => {
|
|
1020
|
+
rejectAborted(timedOut ? timeoutError(timeoutMs) : abortedError());
|
|
1021
|
+
controller == null ? void 0 : controller.abort();
|
|
1022
|
+
};
|
|
1023
|
+
callerSignal == null ? void 0 : callerSignal.addEventListener("abort", abort, { once: true });
|
|
1024
|
+
const timer = timeoutMs > 0 && isFinite(timeoutMs) ? setTimeout(() => {
|
|
1025
|
+
timedOut = true;
|
|
1026
|
+
abort();
|
|
1027
|
+
}, timeoutMs) : void 0;
|
|
1028
|
+
const classify = (cause) => {
|
|
1029
|
+
if (timedOut) return timeoutError(timeoutMs, cause);
|
|
1030
|
+
if (callerSignal == null ? void 0 : callerSignal.aborted) return abortedError();
|
|
1031
|
+
return void 0;
|
|
1032
|
+
};
|
|
1033
|
+
try {
|
|
1034
|
+
let response;
|
|
1035
|
+
try {
|
|
1036
|
+
response = await Promise.race([
|
|
1037
|
+
fetchImpl(url, {
|
|
1038
|
+
method: request.method,
|
|
1039
|
+
headers,
|
|
1040
|
+
body: request.body === void 0 ? void 0 : JSON.stringify(request.body),
|
|
1041
|
+
signal: (_b = controller == null ? void 0 : controller.signal) != null ? _b : callerSignal,
|
|
1042
|
+
credentials: "omit"
|
|
1043
|
+
}),
|
|
1044
|
+
aborted
|
|
1045
|
+
]);
|
|
1046
|
+
} catch (cause) {
|
|
1047
|
+
throw (_c = classify(cause)) != null ? _c : fromNetworkError(cause);
|
|
1048
|
+
}
|
|
1049
|
+
let body;
|
|
1050
|
+
try {
|
|
1051
|
+
const text2 = await Promise.race([response.text(), aborted]);
|
|
1052
|
+
body = text2 ? JSON.parse(text2) : void 0;
|
|
1053
|
+
} catch (cause) {
|
|
1054
|
+
const error = classify(cause);
|
|
1055
|
+
if (error) throw error;
|
|
1056
|
+
body = void 0;
|
|
1057
|
+
}
|
|
1058
|
+
return { ok: response.ok, status: response.status, headers: response.headers, body };
|
|
1059
|
+
} finally {
|
|
1060
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
1061
|
+
callerSignal == null ? void 0 : callerSignal.removeEventListener("abort", abort);
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
function unwrapData(response) {
|
|
1065
|
+
if (!response.ok) throw fromApiError(response.status, response.body, response.headers);
|
|
1066
|
+
const body = response.body;
|
|
1067
|
+
if (!body || typeof body !== "object" || !("data" in body)) {
|
|
1068
|
+
throw new SdkError("INVALID_RESPONSE", "Malformed response from server", { status: response.status });
|
|
1069
|
+
}
|
|
1070
|
+
return body.data;
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
// src/core/session.ts
|
|
1074
|
+
var noop = () => void 0;
|
|
1075
|
+
function stripHash(url) {
|
|
1076
|
+
const index = url.indexOf("#");
|
|
1077
|
+
return index === -1 ? url : url.slice(0, index);
|
|
1078
|
+
}
|
|
1079
|
+
var MAX_DIAGNOSTIC_URL_LENGTH = 2048;
|
|
1080
|
+
function diagnosticUrl(value) {
|
|
1081
|
+
if (!value) return void 0;
|
|
1082
|
+
const trimmed = stripHash(value.trim());
|
|
1083
|
+
if (!/^https?:\/\//i.test(trimmed)) return void 0;
|
|
1084
|
+
try {
|
|
1085
|
+
new URL(trimmed);
|
|
1086
|
+
} catch {
|
|
1087
|
+
return void 0;
|
|
1088
|
+
}
|
|
1089
|
+
return trimmed.slice(0, MAX_DIAGNOSTIC_URL_LENGTH);
|
|
1090
|
+
}
|
|
1091
|
+
var SessionManager = class {
|
|
1092
|
+
constructor(options) {
|
|
1093
|
+
this.listeners = /* @__PURE__ */ new Set();
|
|
1094
|
+
this.session = null;
|
|
1095
|
+
this.expiresAtMs = 0;
|
|
1096
|
+
this.refreshAtMs = 0;
|
|
1097
|
+
this.inflight = null;
|
|
1098
|
+
this.timer = null;
|
|
1099
|
+
this.wasHidden = false;
|
|
1100
|
+
this.disposed = false;
|
|
1101
|
+
this.paused = false;
|
|
1102
|
+
this.onVisibilityChange = () => {
|
|
1103
|
+
var _a;
|
|
1104
|
+
const state = (_a = this.doc) == null ? void 0 : _a.visibilityState;
|
|
1105
|
+
if (state === "hidden") {
|
|
1106
|
+
this.wasHidden = true;
|
|
1107
|
+
return;
|
|
1108
|
+
}
|
|
1109
|
+
if (state !== "visible" || !this.wasHidden) return;
|
|
1110
|
+
this.wasHidden = false;
|
|
1111
|
+
if (this.paused) return;
|
|
1112
|
+
if (this.session && (this.isExpired() || this.now() >= this.refreshAtMs)) {
|
|
1113
|
+
this.create().catch(noop);
|
|
1114
|
+
}
|
|
1115
|
+
};
|
|
1116
|
+
var _a, _b, _c;
|
|
1117
|
+
if (options.firstParty) {
|
|
1118
|
+
if (options.publishableKey || options.linkCode) {
|
|
1119
|
+
throw new SdkError("CONFIG_ERROR", "firstParty cannot be combined with a publishableKey or a linkCode");
|
|
1120
|
+
}
|
|
1121
|
+
} else if (!options.publishableKey && !options.linkCode) {
|
|
1122
|
+
throw new SdkError("CONFIG_ERROR", "Provide a publishableKey or a linkCode");
|
|
1123
|
+
}
|
|
1124
|
+
this.options = options;
|
|
1125
|
+
this.baseUrl = options.baseUrl.replace(/\/+$/, "");
|
|
1126
|
+
this.fetchImpl = resolveFetch(options.fetch);
|
|
1127
|
+
this.refreshLeadMs = (_a = options.refreshLeadMs) != null ? _a : SESSION_REFRESH_LEAD_MS;
|
|
1128
|
+
this.minRefreshDelayMs = (_b = options.minRefreshDelayMs) != null ? _b : SESSION_MIN_REFRESH_DELAY_MS;
|
|
1129
|
+
this.now = (_c = options.now) != null ? _c : (() => Date.now());
|
|
1130
|
+
this.doc = options.document === void 0 ? typeof document !== "undefined" ? document : null : options.document;
|
|
1131
|
+
if (this.doc) {
|
|
1132
|
+
this.wasHidden = this.doc.visibilityState === "hidden";
|
|
1133
|
+
this.doc.addEventListener("visibilitychange", this.onVisibilityChange);
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
/** The current session, if one has been created (may be expired). */
|
|
1137
|
+
get current() {
|
|
1138
|
+
return this.session;
|
|
1139
|
+
}
|
|
1140
|
+
get integration() {
|
|
1141
|
+
var _a;
|
|
1142
|
+
return (_a = this.session) == null ? void 0 : _a.integration;
|
|
1143
|
+
}
|
|
1144
|
+
/** Time the token will expire, in epoch ms (0 before the first session). */
|
|
1145
|
+
get expiresAt() {
|
|
1146
|
+
return this.expiresAtMs;
|
|
1147
|
+
}
|
|
1148
|
+
isExpired(skewMs = 0) {
|
|
1149
|
+
return !this.session || this.now() + skewMs >= this.expiresAtMs;
|
|
1150
|
+
}
|
|
1151
|
+
/** Creates a new session (`POST /sessions`). Concurrent calls share one request. */
|
|
1152
|
+
create() {
|
|
1153
|
+
if (this.inflight) return this.inflight;
|
|
1154
|
+
const promise = this.doCreate().finally(() => {
|
|
1155
|
+
if (this.inflight === promise) this.inflight = null;
|
|
1156
|
+
});
|
|
1157
|
+
this.inflight = promise;
|
|
1158
|
+
return promise;
|
|
1159
|
+
}
|
|
1160
|
+
/** Forces a new session even if the current one is still valid. */
|
|
1161
|
+
refresh() {
|
|
1162
|
+
return this.create();
|
|
1163
|
+
}
|
|
1164
|
+
/**
|
|
1165
|
+
* Returns a valid token, creating a session when there is none or it has expired.
|
|
1166
|
+
*
|
|
1167
|
+
* This is also the recovery path after a failed background refresh: the
|
|
1168
|
+
* failure is reported to `onChange` listeners, the old token keeps being used
|
|
1169
|
+
* while it is still valid, and the first `getToken()` after it expires mints
|
|
1170
|
+
* a new session (surfacing the error to that caller if it fails again).
|
|
1171
|
+
*/
|
|
1172
|
+
async getToken() {
|
|
1173
|
+
if (this.session && !this.isExpired()) return this.session.sessionToken;
|
|
1174
|
+
const session = await this.create();
|
|
1175
|
+
return session.sessionToken;
|
|
1176
|
+
}
|
|
1177
|
+
/** Subscribe to session changes. Called with `(session)` on success and `(current|null, error)` on failure. */
|
|
1178
|
+
onChange(listener) {
|
|
1179
|
+
this.listeners.add(listener);
|
|
1180
|
+
return () => {
|
|
1181
|
+
this.listeners.delete(listener);
|
|
1182
|
+
};
|
|
1183
|
+
}
|
|
1184
|
+
/** True while background refresh is paused (see `pause()`). */
|
|
1185
|
+
get isPaused() {
|
|
1186
|
+
return this.paused;
|
|
1187
|
+
}
|
|
1188
|
+
/**
|
|
1189
|
+
* Stops the background refresh (timer and foreground catch-up) without
|
|
1190
|
+
* forgetting the token, e.g. while no form is using the session. Explicit
|
|
1191
|
+
* `create()` / `getToken()` calls keep working; `getToken()` still mints a
|
|
1192
|
+
* new session once the current one has expired.
|
|
1193
|
+
*/
|
|
1194
|
+
pause() {
|
|
1195
|
+
this.paused = true;
|
|
1196
|
+
this.clearTimer();
|
|
1197
|
+
}
|
|
1198
|
+
/**
|
|
1199
|
+
* Re-enables the background refresh after `pause()`. Nothing is fetched
|
|
1200
|
+
* here: the timer is re-armed for the current token (at least
|
|
1201
|
+
* `minRefreshDelayMs` from now), and an expired token is replaced lazily by
|
|
1202
|
+
* the next `getToken()`.
|
|
1203
|
+
*/
|
|
1204
|
+
resume() {
|
|
1205
|
+
if (!this.paused) return;
|
|
1206
|
+
this.paused = false;
|
|
1207
|
+
if (this.session && !this.isExpired()) this.schedule();
|
|
1208
|
+
}
|
|
1209
|
+
/** Stops timers and listeners and forgets the token. */
|
|
1210
|
+
dispose() {
|
|
1211
|
+
this.disposed = true;
|
|
1212
|
+
this.clearTimer();
|
|
1213
|
+
if (this.doc) this.doc.removeEventListener("visibilitychange", this.onVisibilityChange);
|
|
1214
|
+
this.listeners.clear();
|
|
1215
|
+
this.session = null;
|
|
1216
|
+
this.expiresAtMs = 0;
|
|
1217
|
+
this.refreshAtMs = 0;
|
|
1218
|
+
}
|
|
1219
|
+
async doCreate() {
|
|
1220
|
+
var _a, _b, _c;
|
|
1221
|
+
if (this.disposed) throw new SdkError("CONFIG_ERROR", "SessionManager has been disposed");
|
|
1222
|
+
const headers = {};
|
|
1223
|
+
const body = {};
|
|
1224
|
+
if (this.options.firstParty) {
|
|
1225
|
+
body.firstParty = true;
|
|
1226
|
+
} else if (this.options.publishableKey) {
|
|
1227
|
+
headers.Authorization = `Bearer ${this.options.publishableKey}`;
|
|
1228
|
+
} else if (this.options.linkCode) {
|
|
1229
|
+
body.linkCode = this.options.linkCode;
|
|
1230
|
+
}
|
|
1231
|
+
const pageUrl = diagnosticUrl(
|
|
1232
|
+
(_a = this.options.pageUrl) != null ? _a : typeof location !== "undefined" ? location.href : void 0
|
|
1233
|
+
);
|
|
1234
|
+
const referrer = diagnosticUrl(
|
|
1235
|
+
(_b = this.options.referrer) != null ? _b : typeof document !== "undefined" ? document.referrer || void 0 : void 0
|
|
1236
|
+
);
|
|
1237
|
+
if (pageUrl) body.pageUrl = pageUrl;
|
|
1238
|
+
if (referrer) body.referrer = referrer;
|
|
1239
|
+
if (this.options.utm && Object.keys(this.options.utm).length) body.utm = this.options.utm;
|
|
1240
|
+
if (this.options.sdkVersion) body.sdkVersion = this.options.sdkVersion;
|
|
1241
|
+
try {
|
|
1242
|
+
const response = await sendJson(this.fetchImpl, `${this.baseUrl}/sessions`, {
|
|
1243
|
+
method: "POST",
|
|
1244
|
+
headers,
|
|
1245
|
+
body,
|
|
1246
|
+
timeoutMs: (_c = this.options.timeoutMs) != null ? _c : DEFAULT_TIMEOUT_MS
|
|
1247
|
+
});
|
|
1248
|
+
const session = unwrapData(response);
|
|
1249
|
+
if (!session || typeof session.sessionToken !== "string" || typeof session.expiresAt !== "string") {
|
|
1250
|
+
throw new SdkError("INVALID_RESPONSE", "Session response is missing sessionToken/expiresAt", {
|
|
1251
|
+
status: response.status
|
|
1252
|
+
});
|
|
1253
|
+
}
|
|
1254
|
+
if (this.disposed) return session;
|
|
1255
|
+
this.session = session;
|
|
1256
|
+
const parsed = Date.parse(session.expiresAt);
|
|
1257
|
+
this.expiresAtMs = isNaN(parsed) ? this.now() + 15 * 6e4 : parsed;
|
|
1258
|
+
this.schedule();
|
|
1259
|
+
this.emit(session);
|
|
1260
|
+
return session;
|
|
1261
|
+
} catch (error) {
|
|
1262
|
+
const sdkError = toSdkError(error);
|
|
1263
|
+
this.emit(this.session && !this.isExpired() ? this.session : null, sdkError);
|
|
1264
|
+
throw sdkError;
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* Schedules the background refresh. A failed refresh is not retried here;
|
|
1269
|
+
* `getToken()` recovers lazily once the current token expires.
|
|
1270
|
+
*/
|
|
1271
|
+
schedule() {
|
|
1272
|
+
this.clearTimer();
|
|
1273
|
+
if (this.disposed) return;
|
|
1274
|
+
const now = this.now();
|
|
1275
|
+
const delay = Math.max(this.minRefreshDelayMs, this.expiresAtMs - now - this.refreshLeadMs);
|
|
1276
|
+
this.refreshAtMs = now + delay;
|
|
1277
|
+
if (!this.paused) this.arm(delay);
|
|
1278
|
+
}
|
|
1279
|
+
arm(delay) {
|
|
1280
|
+
const clamped = delay > MAX_TIMER_DELAY_MS;
|
|
1281
|
+
this.timer = setTimeout(
|
|
1282
|
+
() => {
|
|
1283
|
+
this.timer = null;
|
|
1284
|
+
const remaining = this.refreshAtMs - this.now();
|
|
1285
|
+
if (clamped && remaining > 0) {
|
|
1286
|
+
this.arm(remaining);
|
|
1287
|
+
return;
|
|
1288
|
+
}
|
|
1289
|
+
this.create().catch(noop);
|
|
1290
|
+
},
|
|
1291
|
+
clamped ? MAX_TIMER_DELAY_MS : delay
|
|
1292
|
+
);
|
|
1293
|
+
}
|
|
1294
|
+
clearTimer() {
|
|
1295
|
+
if (this.timer !== null) {
|
|
1296
|
+
clearTimeout(this.timer);
|
|
1297
|
+
this.timer = null;
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
emit(session, error) {
|
|
1301
|
+
for (const listener of Array.from(this.listeners)) {
|
|
1302
|
+
try {
|
|
1303
|
+
listener(session, error);
|
|
1304
|
+
} catch {
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
};
|
|
1309
|
+
|
|
1310
|
+
// src/version.ts
|
|
1311
|
+
var version = true ? "0.1.0" : "0.0.0-dev";
|
|
1312
|
+
|
|
1313
|
+
// src/core/client.ts
|
|
1314
|
+
function resolveEnvironment(options) {
|
|
1315
|
+
var _a;
|
|
1316
|
+
if (options.environment) return options.environment;
|
|
1317
|
+
return ((_a = options.publishableKey) == null ? void 0 : _a.startsWith("mk_test_")) ? "sandbox" : "production";
|
|
1318
|
+
}
|
|
1319
|
+
var SECRET_KEY_PATTERN = /^mk_(live|test)_sk_/;
|
|
1320
|
+
function assertCredentials(options) {
|
|
1321
|
+
const key = options.publishableKey;
|
|
1322
|
+
if (options.firstParty !== void 0 && typeof options.firstParty !== "boolean") {
|
|
1323
|
+
throw new SdkError("CONFIG_ERROR", "firstParty must be a boolean");
|
|
1324
|
+
}
|
|
1325
|
+
if (options.firstParty) {
|
|
1326
|
+
if (key || options.linkCode) {
|
|
1327
|
+
throw new SdkError("CONFIG_ERROR", "firstParty cannot be combined with a publishableKey or a linkCode");
|
|
1328
|
+
}
|
|
1329
|
+
if (!options.environment && !options.apiBaseUrl) {
|
|
1330
|
+
throw new SdkError("CONFIG_ERROR", "firstParty requires an environment or an apiBaseUrl");
|
|
1331
|
+
}
|
|
1332
|
+
} else if (!key && !options.linkCode) {
|
|
1333
|
+
throw new SdkError("CONFIG_ERROR", "createClient requires a publishableKey or a linkCode");
|
|
1334
|
+
}
|
|
1335
|
+
if (key) {
|
|
1336
|
+
if (SECRET_KEY_PATTERN.test(key)) {
|
|
1337
|
+
throw new SdkError(
|
|
1338
|
+
"SECRET_KEY_IN_BROWSER",
|
|
1339
|
+
"A secret key was passed to the browser SDK. Use your publishable key (mk_live_pk_\u2026 / mk_test_pk_\u2026)."
|
|
1340
|
+
);
|
|
1341
|
+
}
|
|
1342
|
+
if (!key.startsWith("mk_live_pk_") && !key.startsWith("mk_test_pk_")) {
|
|
1343
|
+
throw new SdkError("CONFIG_ERROR", "publishableKey must start with mk_live_pk_ or mk_test_pk_");
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
if (options.environment && !(options.environment in API_BASE_URLS)) {
|
|
1347
|
+
throw new SdkError("CONFIG_ERROR", `Unknown environment "${String(options.environment)}"`);
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
function createClient(options) {
|
|
1351
|
+
var _a, _b, _c, _d, _e;
|
|
1352
|
+
assertCredentials(options);
|
|
1353
|
+
const sleep = (_a = options.sleep) != null ? _a : abortableSleep;
|
|
1354
|
+
const timeoutMs = (_b = options.timeoutMs) != null ? _b : DEFAULT_TIMEOUT_MS;
|
|
1355
|
+
const environment = resolveEnvironment(options);
|
|
1356
|
+
const baseUrl = ((_c = options.apiBaseUrl) != null ? _c : API_BASE_URLS[environment]).replace(/\/+$/, "");
|
|
1357
|
+
const fetchImpl = resolveFetch(options.fetch);
|
|
1358
|
+
const retryDelays = (_d = options.retryDelaysMs) != null ? _d : RETRY_DELAYS_MS;
|
|
1359
|
+
const creditTokens = /* @__PURE__ */ new Map();
|
|
1360
|
+
const session = new SessionManager({
|
|
1361
|
+
baseUrl,
|
|
1362
|
+
publishableKey: options.publishableKey,
|
|
1363
|
+
linkCode: options.linkCode,
|
|
1364
|
+
firstParty: options.firstParty,
|
|
1365
|
+
fetch: fetchImpl,
|
|
1366
|
+
sdkVersion: (_e = options.sdkVersion) != null ? _e : version,
|
|
1367
|
+
utm: options.utm,
|
|
1368
|
+
pageUrl: options.pageUrl,
|
|
1369
|
+
referrer: options.referrer,
|
|
1370
|
+
document: options.document,
|
|
1371
|
+
timeoutMs
|
|
1372
|
+
});
|
|
1373
|
+
function shouldRetry(error, only) {
|
|
1374
|
+
if (!error.retryable || only && !only(error)) return false;
|
|
1375
|
+
return error.retryAfterMs === void 0 || error.retryAfterMs <= MAX_RETRY_AFTER_MS;
|
|
1376
|
+
}
|
|
1377
|
+
async function request(method, path, opts = {}) {
|
|
1378
|
+
var _a2, _b2, _c2, _d2, _e2, _f, _g, _h;
|
|
1379
|
+
let authRetried = false;
|
|
1380
|
+
let attempt = 0;
|
|
1381
|
+
const delays = retryDelays.slice(0, (_a2 = opts.retries) != null ? _a2 : retryDelays.length);
|
|
1382
|
+
for (; ; ) {
|
|
1383
|
+
if ((_b2 = opts.signal) == null ? void 0 : _b2.aborted) throw new SdkError("ABORTED", "Request was aborted");
|
|
1384
|
+
const token = await session.getToken();
|
|
1385
|
+
const headers = { ...opts.headers, Authorization: `Bearer ${token}` };
|
|
1386
|
+
if (opts.idempotencyKey) headers["Idempotency-Key"] = opts.idempotencyKey;
|
|
1387
|
+
const captchaToken = typeof opts.captchaToken === "function" ? await opts.captchaToken() : opts.captchaToken;
|
|
1388
|
+
if ((_c2 = opts.signal) == null ? void 0 : _c2.aborted) throw new SdkError("ABORTED", "Request was aborted");
|
|
1389
|
+
if (captchaToken) headers["X-Captcha-Token"] = captchaToken;
|
|
1390
|
+
let response;
|
|
1391
|
+
try {
|
|
1392
|
+
response = await sendJson(fetchImpl, `${baseUrl}${path}`, {
|
|
1393
|
+
method,
|
|
1394
|
+
headers,
|
|
1395
|
+
body: opts.body,
|
|
1396
|
+
signal: opts.signal,
|
|
1397
|
+
timeoutMs: (_d2 = opts.timeoutMs) != null ? _d2 : timeoutMs
|
|
1398
|
+
});
|
|
1399
|
+
} catch (error2) {
|
|
1400
|
+
const sdkError = toSdkError(error2);
|
|
1401
|
+
if (shouldRetry(sdkError, opts.retryIf) && attempt < delays.length) {
|
|
1402
|
+
await sleep((_e2 = delays[attempt++]) != null ? _e2 : 0, opts.signal);
|
|
1403
|
+
continue;
|
|
1404
|
+
}
|
|
1405
|
+
throw sdkError;
|
|
1406
|
+
}
|
|
1407
|
+
if (response.status === 401 && !authRetried) {
|
|
1408
|
+
authRetried = true;
|
|
1409
|
+
if (((_f = session.current) == null ? void 0 : _f.sessionToken) === token) await session.refresh();
|
|
1410
|
+
continue;
|
|
1411
|
+
}
|
|
1412
|
+
if (response.ok) return unwrapData(response);
|
|
1413
|
+
const error = fromApiError(response.status, response.body, response.headers);
|
|
1414
|
+
if (shouldRetry(error, opts.retryIf) && attempt < delays.length) {
|
|
1415
|
+
const backoff = (_g = delays[attempt++]) != null ? _g : 0;
|
|
1416
|
+
await sleep(Math.max(backoff, (_h = error.retryAfterMs) != null ? _h : 0), opts.signal);
|
|
1417
|
+
continue;
|
|
1418
|
+
}
|
|
1419
|
+
throw error;
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
async function creditCall(leadId, suffix, opts) {
|
|
1423
|
+
const token = creditTokens.get(leadId);
|
|
1424
|
+
if (!token) throw new SdkError("CREDIT_CHECK_NOT_ALLOWED", "no credit-check token for this lead");
|
|
1425
|
+
return request("POST", `/leads/${encodeURIComponent(leadId)}/credit-check${suffix}`, {
|
|
1426
|
+
...opts,
|
|
1427
|
+
headers: { "X-Credit-Check-Token": token }
|
|
1428
|
+
});
|
|
1429
|
+
}
|
|
1430
|
+
return {
|
|
1431
|
+
baseUrl,
|
|
1432
|
+
environment,
|
|
1433
|
+
session,
|
|
1434
|
+
createSession: () => session.create(),
|
|
1435
|
+
lookupPincode(pincode, opts) {
|
|
1436
|
+
const trimmed = pincode.trim();
|
|
1437
|
+
if (!REGEX.pincode.test(trimmed)) {
|
|
1438
|
+
return Promise.reject(
|
|
1439
|
+
new SdkError("VALIDATION_ERROR", "Pincode must be 6 digits", {
|
|
1440
|
+
details: [{ field: "pincode", message: "Pincode must be 6 digits" }]
|
|
1441
|
+
})
|
|
1442
|
+
);
|
|
1443
|
+
}
|
|
1444
|
+
return request("GET", `/reference/pincodes/${encodeURIComponent(trimmed)}`, {
|
|
1445
|
+
signal: opts == null ? void 0 : opts.signal
|
|
1446
|
+
});
|
|
1447
|
+
},
|
|
1448
|
+
async searchBanks(query, opts = {}) {
|
|
1449
|
+
const q = query.trim().slice(0, LIMITS.bankSearchQuery.max);
|
|
1450
|
+
if (q.length < LIMITS.bankSearchQuery.min) return [];
|
|
1451
|
+
const params = new URLSearchParams({ q });
|
|
1452
|
+
if (opts.limit !== void 0) params.set("limit", String(opts.limit));
|
|
1453
|
+
return request("GET", `/reference/banks?${params.toString()}`, { signal: opts.signal });
|
|
1454
|
+
},
|
|
1455
|
+
async createLead(input, opts = {}) {
|
|
1456
|
+
var _a2;
|
|
1457
|
+
const idempotencyKey = (_a2 = opts.idempotencyKey) != null ? _a2 : newIdempotencyKey();
|
|
1458
|
+
const { attribution: _attribution, ...body } = input;
|
|
1459
|
+
const { creditCheckToken, ...lead } = await request("POST", "/leads", {
|
|
1460
|
+
body,
|
|
1461
|
+
idempotencyKey,
|
|
1462
|
+
captchaToken: opts.captchaToken,
|
|
1463
|
+
signal: opts.signal
|
|
1464
|
+
});
|
|
1465
|
+
if (typeof creditCheckToken === "string" && creditCheckToken) creditTokens.set(lead.id, creditCheckToken);
|
|
1466
|
+
return lead;
|
|
1467
|
+
},
|
|
1468
|
+
hasCreditCheckToken: (leadId) => creditTokens.has(leadId),
|
|
1469
|
+
async startCreditCheck(leadId, input, opts = {}) {
|
|
1470
|
+
var _a2, _b2;
|
|
1471
|
+
const body = {
|
|
1472
|
+
...input,
|
|
1473
|
+
pan: String((_a2 = input.pan) != null ? _a2 : "").trim().toUpperCase(),
|
|
1474
|
+
pincode: String((_b2 = input.pincode) != null ? _b2 : "").trim()
|
|
1475
|
+
};
|
|
1476
|
+
const field = ["dob", "pan", "pincode"].find(
|
|
1477
|
+
(key) => !(key === "dob" ? /^\d{4}-\d{2}-\d{2}$/ : REGEX[key]).test(String(body[key]))
|
|
1478
|
+
);
|
|
1479
|
+
if (field) {
|
|
1480
|
+
const message = `${field} is invalid`;
|
|
1481
|
+
throw new SdkError("VALIDATION_ERROR", message, { details: [{ field, message }] });
|
|
1482
|
+
}
|
|
1483
|
+
return creditCall(leadId, "", {
|
|
1484
|
+
body,
|
|
1485
|
+
captchaToken: opts.captchaToken,
|
|
1486
|
+
signal: opts.signal,
|
|
1487
|
+
retries: 0
|
|
1488
|
+
});
|
|
1489
|
+
},
|
|
1490
|
+
resendCreditCheckOtp(leadId, opts = {}) {
|
|
1491
|
+
return creditCall(leadId, "/resend", {
|
|
1492
|
+
captchaToken: opts.captchaToken,
|
|
1493
|
+
signal: opts.signal,
|
|
1494
|
+
retries: 0
|
|
1495
|
+
});
|
|
1496
|
+
},
|
|
1497
|
+
async verifyCreditCheck(leadId, otp, opts = {}) {
|
|
1498
|
+
const code = String(otp != null ? otp : "").trim();
|
|
1499
|
+
if (!REGEX.otp.test(code)) {
|
|
1500
|
+
const message = "otp must be 6 digits";
|
|
1501
|
+
throw new SdkError("VALIDATION_ERROR", message, { details: [{ field: "otp", message }] });
|
|
1502
|
+
}
|
|
1503
|
+
const result = await creditCall(leadId, "/verify", {
|
|
1504
|
+
body: { otp: code },
|
|
1505
|
+
captchaToken: opts.captchaToken,
|
|
1506
|
+
signal: opts.signal,
|
|
1507
|
+
timeoutMs: CREDIT_VERIFY_TIMEOUT_MS,
|
|
1508
|
+
// At most one automatic retry, and only for transport failures: a coded 503 means the bureau
|
|
1509
|
+
// pull ran and failed, and every attempt uses up one of the check's three server-side pulls.
|
|
1510
|
+
retries: 1,
|
|
1511
|
+
retryIf: (error) => error.code === "NETWORK_ERROR" || error.status === 502 || error.status === 504
|
|
1512
|
+
});
|
|
1513
|
+
if (result.status === "COMPLETED" || result.status === "NO_HIT") creditTokens.delete(leadId);
|
|
1514
|
+
return result;
|
|
1515
|
+
},
|
|
1516
|
+
skipCreditCheck(leadId, opts = {}) {
|
|
1517
|
+
return creditCall(leadId, "/skip", { signal: opts.signal }).finally(
|
|
1518
|
+
() => creditTokens.delete(leadId)
|
|
1519
|
+
);
|
|
1520
|
+
},
|
|
1521
|
+
forgetCreditCheckToken: (leadId) => void creditTokens.delete(leadId),
|
|
1522
|
+
dispose() {
|
|
1523
|
+
creditTokens.clear();
|
|
1524
|
+
session.dispose();
|
|
1525
|
+
}
|
|
1526
|
+
};
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1529
|
+
// src/core/captcha.ts
|
|
1530
|
+
var RECAPTCHA_SCRIPT_URL = "https://www.google.com/recaptcha/api.js";
|
|
1531
|
+
var DEFAULT_CAPTCHA_ACTION = "lead_submit";
|
|
1532
|
+
var CREDIT_CHECK_CAPTCHA_ACTION = "credit_check_otp";
|
|
1533
|
+
var CREDIT_CHECK_VERIFY_CAPTCHA_ACTION = "credit_check_verify";
|
|
1534
|
+
var loaders = /* @__PURE__ */ new Map();
|
|
1535
|
+
function unavailable(message, cause) {
|
|
1536
|
+
return new SdkError("CAPTCHA_UNAVAILABLE", message, { retryable: false, cause });
|
|
1537
|
+
}
|
|
1538
|
+
function loadRecaptcha(siteKey, host = {}) {
|
|
1539
|
+
var _a, _b;
|
|
1540
|
+
if (!siteKey) return Promise.reject(new SdkError("CONFIG_ERROR", "reCAPTCHA siteKey is required"));
|
|
1541
|
+
const existing = loaders.get(siteKey);
|
|
1542
|
+
if (existing) return existing;
|
|
1543
|
+
const doc = (_a = host.document) != null ? _a : typeof document !== "undefined" ? document : void 0;
|
|
1544
|
+
const win = (_b = host.window) != null ? _b : typeof window !== "undefined" ? window : void 0;
|
|
1545
|
+
if (!doc || !win) return Promise.reject(unavailable("reCAPTCHA requires a browser environment"));
|
|
1546
|
+
const promise = new Promise((resolve, reject) => {
|
|
1547
|
+
var _a2, _b2;
|
|
1548
|
+
let settled = false;
|
|
1549
|
+
const fail = (error) => {
|
|
1550
|
+
if (settled) return;
|
|
1551
|
+
settled = true;
|
|
1552
|
+
clearTimeout(timeout);
|
|
1553
|
+
loaders.delete(siteKey);
|
|
1554
|
+
reject(error);
|
|
1555
|
+
};
|
|
1556
|
+
const succeed = (g) => {
|
|
1557
|
+
if (settled) return;
|
|
1558
|
+
settled = true;
|
|
1559
|
+
clearTimeout(timeout);
|
|
1560
|
+
resolve(g);
|
|
1561
|
+
};
|
|
1562
|
+
const timeout = setTimeout(() => fail(unavailable("Timed out loading reCAPTCHA")), (_a2 = host.timeoutMs) != null ? _a2 : 15e3);
|
|
1563
|
+
const whenReady = () => {
|
|
1564
|
+
const g = win.grecaptcha;
|
|
1565
|
+
if (!g || typeof g.ready !== "function") {
|
|
1566
|
+
fail(unavailable("reCAPTCHA script loaded but grecaptcha is unavailable"));
|
|
1567
|
+
return;
|
|
1568
|
+
}
|
|
1569
|
+
g.ready(() => succeed(g));
|
|
1570
|
+
};
|
|
1571
|
+
if (win.grecaptcha && typeof win.grecaptcha.execute === "function") {
|
|
1572
|
+
whenReady();
|
|
1573
|
+
return;
|
|
1574
|
+
}
|
|
1575
|
+
const src = `${RECAPTCHA_SCRIPT_URL}?render=${encodeURIComponent(siteKey)}`;
|
|
1576
|
+
let script = doc.querySelector(`script[src="${src}"]`);
|
|
1577
|
+
if (!script) {
|
|
1578
|
+
script = doc.createElement("script");
|
|
1579
|
+
script.src = src;
|
|
1580
|
+
script.async = true;
|
|
1581
|
+
script.defer = true;
|
|
1582
|
+
script.setAttribute("data-mk-recaptcha", siteKey);
|
|
1583
|
+
if (host.nonce) {
|
|
1584
|
+
script.nonce = host.nonce;
|
|
1585
|
+
script.setAttribute("nonce", host.nonce);
|
|
1586
|
+
}
|
|
1587
|
+
((_b2 = doc.head) != null ? _b2 : doc.documentElement).appendChild(script);
|
|
1588
|
+
}
|
|
1589
|
+
script.addEventListener("load", whenReady, { once: true });
|
|
1590
|
+
script.addEventListener(
|
|
1591
|
+
"error",
|
|
1592
|
+
() => {
|
|
1593
|
+
var _a3;
|
|
1594
|
+
(_a3 = script == null ? void 0 : script.parentNode) == null ? void 0 : _a3.removeChild(script);
|
|
1595
|
+
fail(unavailable("Failed to load reCAPTCHA"));
|
|
1596
|
+
},
|
|
1597
|
+
{ once: true }
|
|
1598
|
+
);
|
|
1599
|
+
});
|
|
1600
|
+
loaders.set(siteKey, promise);
|
|
1601
|
+
return promise;
|
|
1602
|
+
}
|
|
1603
|
+
async function getCaptchaToken(siteKey, action = DEFAULT_CAPTCHA_ACTION, host = {}) {
|
|
1604
|
+
const grecaptcha = await loadRecaptcha(siteKey, host);
|
|
1605
|
+
let token;
|
|
1606
|
+
try {
|
|
1607
|
+
token = await grecaptcha.execute(siteKey, { action });
|
|
1608
|
+
} catch (cause) {
|
|
1609
|
+
throw unavailable("reCAPTCHA execution failed", cause);
|
|
1610
|
+
}
|
|
1611
|
+
if (!token) throw unavailable("reCAPTCHA returned an empty token");
|
|
1612
|
+
return token;
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
export {
|
|
1616
|
+
version,
|
|
1617
|
+
RUPEES_PER_CRORE,
|
|
1618
|
+
PRODUCT,
|
|
1619
|
+
LIMITS,
|
|
1620
|
+
REGEX,
|
|
1621
|
+
EMPLOYMENT_TYPES,
|
|
1622
|
+
EMPLOYMENT_TYPE_VALUES,
|
|
1623
|
+
PROPERTY_TYPES,
|
|
1624
|
+
PROPERTY_TYPE_VALUES,
|
|
1625
|
+
ORDER_PRODUCT_STATUSES,
|
|
1626
|
+
ORDER_PRODUCT_SUBSTATUSES,
|
|
1627
|
+
ERROR_CODES,
|
|
1628
|
+
CLIENT_ERROR_CODES,
|
|
1629
|
+
API_BASE_URLS,
|
|
1630
|
+
formatInr,
|
|
1631
|
+
parseInr,
|
|
1632
|
+
newIdempotencyKey,
|
|
1633
|
+
isIdempotencyKey,
|
|
1634
|
+
croresToRupees,
|
|
1635
|
+
rupeesToCrores,
|
|
1636
|
+
parseIntInput,
|
|
1637
|
+
deriveLoanAmount,
|
|
1638
|
+
toLeadInput,
|
|
1639
|
+
fromLeadInput,
|
|
1640
|
+
API_TO_FORM,
|
|
1641
|
+
FORM_TO_API,
|
|
1642
|
+
apiFieldToFormKey,
|
|
1643
|
+
formKeyToApiField,
|
|
1644
|
+
SdkError,
|
|
1645
|
+
isSdkError,
|
|
1646
|
+
toSdkError,
|
|
1647
|
+
parseRetryAfter,
|
|
1648
|
+
fromApiError,
|
|
1649
|
+
fromNetworkError,
|
|
1650
|
+
mapDetailsToFormErrors,
|
|
1651
|
+
istToday,
|
|
1652
|
+
parseYmd,
|
|
1653
|
+
formatYmd,
|
|
1654
|
+
ageOn,
|
|
1655
|
+
istYearsAgo,
|
|
1656
|
+
en,
|
|
1657
|
+
EMPTY_PERSON,
|
|
1658
|
+
INITIAL_FORM_VALUES,
|
|
1659
|
+
createFormSchema,
|
|
1660
|
+
formSchema,
|
|
1661
|
+
yupErrorToFormErrors,
|
|
1662
|
+
validateFormValues,
|
|
1663
|
+
leadSchema,
|
|
1664
|
+
validateLeadInput,
|
|
1665
|
+
SessionManager,
|
|
1666
|
+
resolveEnvironment,
|
|
1667
|
+
createClient,
|
|
1668
|
+
RECAPTCHA_SCRIPT_URL,
|
|
1669
|
+
DEFAULT_CAPTCHA_ACTION,
|
|
1670
|
+
CREDIT_CHECK_CAPTCHA_ACTION,
|
|
1671
|
+
CREDIT_CHECK_VERIFY_CAPTCHA_ACTION,
|
|
1672
|
+
loadRecaptcha,
|
|
1673
|
+
getCaptchaToken
|
|
1674
|
+
};
|
|
1675
|
+
//# sourceMappingURL=chunk-PY2B3NZC.js.map
|