@dbs-portal/tool-mock
Version:
API mocking toolkit using MSW for DBS Portal development workflows
909 lines (908 loc) • 20.3 kB
JavaScript
import { HttpResponse as C } from "msw";
import { h as m, j as L } from "./delay-C3BTE-53.js";
const l = [];
for (let e = 0; e < 256; ++e)
l.push((e + 256).toString(16).slice(1));
function T(e, t = 0) {
return (l[e[t + 0]] + l[e[t + 1]] + l[e[t + 2]] + l[e[t + 3]] + "-" + l[e[t + 4]] + l[e[t + 5]] + "-" + l[e[t + 6]] + l[e[t + 7]] + "-" + l[e[t + 8]] + l[e[t + 9]] + "-" + l[e[t + 10]] + l[e[t + 11]] + l[e[t + 12]] + l[e[t + 13]] + l[e[t + 14]] + l[e[t + 15]]).toLowerCase();
}
let w;
const k = new Uint8Array(16);
function x() {
if (!w) {
if (typeof crypto > "u" || !crypto.getRandomValues)
throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
w = crypto.getRandomValues.bind(crypto);
}
return w(k);
}
const O = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), M = { randomUUID: O };
function U(e, t, a) {
if (M.randomUUID && !e)
return M.randomUUID();
e = e || {};
const n = e.random ?? e.rng?.() ?? x();
if (n.length < 16)
throw new Error("Random bytes length must be >= 16");
return n[6] = n[6] & 15 | 64, n[8] = n[8] & 63 | 128, T(n);
}
function v() {
return U();
}
function c(e = 0, t = 100, a = 0) {
const n = m() * (t - e) + e;
return a > 0 ? Number(n.toFixed(a)) : Math.floor(n);
}
function J(e) {
return c(e.min, e.max, e.decimals);
}
function j(e = 0.5) {
return m() < e;
}
function A(e = 5, t = 20, a = "alphanumeric") {
const n = c(e, t);
let r = "";
switch (a) {
case "alpha":
r = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
break;
case "numeric":
r = "0123456789";
break;
case "alphanumeric":
r = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
break;
case "ascii":
r = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=[]{}|;:,.<>?";
break;
}
let i = "";
for (let s = 0; s < n; s++)
i += r.charAt(Math.floor(m() * r.length));
return i;
}
function P(e) {
const t = c(e.minLength, e.maxLength);
let a = "";
switch (e.charset) {
case "alpha":
a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
break;
case "numeric":
a = "0123456789";
break;
case "alphanumeric":
a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
break;
case "ascii":
a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=[]{}|;:,.<>?";
break;
case "custom":
a = e.customChars || "abcdefghijklmnopqrstuvwxyz";
break;
default:
a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
}
e.includeSpaces && (a += " ");
let n = "";
for (let r = 0; r < t; r++)
n += a.charAt(Math.floor(m() * a.length));
return n;
}
function $(e = new Date(2020, 0, 1), t = /* @__PURE__ */ new Date(), a = "iso") {
const n = typeof e == "string" ? new Date(e) : e, r = typeof t == "string" ? new Date(t) : t, i = n.getTime() + m() * (r.getTime() - n.getTime()), s = new Date(i);
switch (a) {
case "iso":
return s.toISOString();
case "timestamp":
return s.getTime();
case "date":
return s;
default:
return s.toISOString();
}
}
function q(e) {
return $(e.start, e.end, e.format);
}
function N(e = "example.com") {
return `${A(5, 12, "alpha").toLowerCase()}@${e}`;
}
function E(e = "full") {
const t = [
"John",
"Jane",
"Michael",
"Sarah",
"David",
"Emily",
"Robert",
"Jessica",
"William",
"Ashley",
"James",
"Amanda",
"Christopher",
"Stephanie",
"Daniel",
"Melissa",
"Matthew",
"Nicole",
"Anthony",
"Elizabeth",
"Mark",
"Helen",
"Donald",
"Deborah",
"Steven",
"Rachel",
"Paul",
"Carolyn",
"Andrew",
"Janet"
], a = [
"Smith",
"Johnson",
"Williams",
"Brown",
"Jones",
"Garcia",
"Miller",
"Davis",
"Rodriguez",
"Martinez",
"Hernandez",
"Lopez",
"Gonzalez",
"Wilson",
"Anderson",
"Thomas",
"Taylor",
"Moore",
"Jackson",
"Martin",
"Lee",
"Perez",
"Thompson",
"White",
"Harris",
"Sanchez",
"Clark",
"Ramirez",
"Lewis",
"Robinson"
], n = t[Math.floor(m() * t.length)] || "John", r = a[Math.floor(m() * a.length)] || "Doe";
switch (e) {
case "first":
return n;
case "last":
return r;
case "full":
default:
return `${n} ${r}`;
}
}
function I(e = "+1-XXX-XXX-XXXX") {
return e.replace(/X/g, () => c(0, 9).toString());
}
function z(e = "https") {
const t = ["example.com", "test.org", "demo.net", "sample.io", "mock.dev"], a = ["", "/api", "/docs", "/admin", "/dashboard", "/profile", "/settings"], n = t[Math.floor(m() * t.length)], r = a[Math.floor(m() * a.length)];
return `${e}://${n}${r}`;
}
function F(e = "hex") {
switch (e) {
case "hex":
return `#${Math.floor(m() * 16777215).toString(16).padStart(6, "0")}`;
case "rgb":
const t = c(0, 255), a = c(0, 255), n = c(0, 255);
return `rgb(${t}, ${a}, ${n})`;
case "hsl":
const r = c(0, 360), i = c(0, 100), s = c(0, 100);
return `hsl(${r}, ${i}%, ${s}%)`;
default:
return F("hex");
}
}
function B(e) {
const t = c(e.minLength, e.maxLength), a = [], n = e.unique ? /* @__PURE__ */ new Set() : null;
for (let r = 0; r < t; r++) {
let i = e.itemGenerator();
if (e.unique && n) {
const s = JSON.stringify(i);
let d = 0;
for (; n.has(s) && d < 100; )
i = e.itemGenerator(), d++;
n.add(JSON.stringify(i));
}
a.push(i);
}
return a;
}
function g(e) {
if (e.length === 0)
throw new Error("Cannot pick from empty array");
const t = e[Math.floor(m() * e.length)];
if (t === void 0)
throw new Error("Failed to pick item from array");
return t;
}
function G(e, t, a = !0) {
if (t >= e.length)
return [...e];
const n = [], r = a ? /* @__PURE__ */ new Set() : null;
for (let i = 0; i < t; i++) {
let s = Math.floor(m() * e.length);
if (a && r) {
let h = 0;
for (; r.has(s) && h < 100; )
s = Math.floor(m() * e.length), h++;
r.add(s);
}
const d = e[s];
d !== void 0 && n.push(d);
}
return n;
}
function W(e = {}) {
const t = e.gender || g(["male", "female", "other"]), a = E("first"), n = E("last"), r = e.ageRange ? c(e.ageRange[0], e.ageRange[1]) : c(18, 80);
return {
id: v(),
firstName: a,
lastName: n,
fullName: `${a} ${n}`,
email: N(),
phone: I(),
gender: t,
age: r,
dateOfBirth: $(
new Date((/* @__PURE__ */ new Date()).getFullYear() - r - 1, 0, 1),
new Date((/* @__PURE__ */ new Date()).getFullYear() - r, 11, 31)
),
nationality: e.nationality || "US",
avatar: e.includeAvatar ? `https://api.dicebear.com/7.x/avataaars/svg?seed=${a}${n}` : void 0
};
}
function Y(e = {}) {
const t = [
"Tech Solutions",
"Digital Innovations",
"Global Systems",
"Smart Technologies",
"Future Enterprises",
"Advanced Solutions",
"Dynamic Systems",
"Innovative Labs",
"Next Generation",
"Modern Solutions",
"Elite Technologies",
"Premier Systems"
], a = ["Inc", "LLC", "Corp", "Ltd", "Co"], n = [
"Technology",
"Healthcare",
"Finance",
"Education",
"Manufacturing",
"Retail",
"Consulting",
"Media",
"Transportation",
"Energy"
], r = g(t), i = g(a), s = e.industry || g(n);
return {
id: v(),
name: `${r} ${i}`,
industry: s,
size: e.size || g(["startup", "small", "medium", "large", "enterprise"]),
founded: c(1950, (/* @__PURE__ */ new Date()).getFullYear()),
website: z(),
email: N(`${r.toLowerCase().replace(" ", "")}.com`),
phone: I(),
logo: e.includeLogo ? `https://api.dicebear.com/7.x/initials/svg?seed=${r}` : void 0
};
}
function K(e = {}) {
const t = [
"Main St",
"Oak Ave",
"Park Rd",
"First St",
"Second St",
"Third St",
"Elm St",
"Washington Ave",
"Lincoln Blvd",
"Madison Dr",
"Jefferson Way"
], a = [
"Springfield",
"Franklin",
"Georgetown",
"Madison",
"Washington",
"Arlington",
"Richmond",
"Fairview",
"Salem",
"Bristol"
], n = [
"CA",
"NY",
"TX",
"FL",
"IL",
"PA",
"OH",
"GA",
"NC",
"MI"
], r = ["US", "CA", "UK", "DE", "FR", "AU", "JP"], i = c(1, 9999), s = g(t), d = e.city || g(a), h = e.state || g(n), p = e.country || g(r), b = A(5, 5, "numeric"), S = {
id: v(),
street: `${i} ${s}`,
city: d,
state: h,
country: p,
zipCode: b,
full: `${i} ${s}, ${d}, ${h} ${b}, ${p}`
};
return e.includeCoordinates ? {
...S,
coordinates: {
latitude: c(-90, 90, 6),
longitude: c(-180, 180, 6)
}
} : S;
}
class V {
responseData = null;
statusCode = 200;
responseHeaders = {};
responseDelay;
responseError;
metadata = {};
constructor(t = {}) {
t.data !== void 0 && (this.responseData = t.data), t.status !== void 0 && (this.statusCode = t.status), t.headers && (this.responseHeaders = { ...t.headers }), t.delay !== void 0 && (this.responseDelay = t.delay), t.error && (this.responseError = t.error), t.meta && (this.metadata = { ...t.meta });
}
/**
* Set response data
*/
data(t) {
return this.responseData = t, this;
}
/**
* Set status code
*/
status(t) {
return this.statusCode = t, this;
}
/**
* Set headers
*/
headers(t) {
return this.responseHeaders = { ...this.responseHeaders, ...t }, this;
}
/**
* Set delay
*/
delay(t) {
return this.responseDelay = t, this;
}
/**
* Add error
*/
error(t) {
return this.responseError = t, this;
}
/**
* Set metadata
*/
meta(t) {
return this.metadata = { ...this.metadata, ...t }, this;
}
/**
* Build the response
*/
build() {
const t = performance.now();
let a;
this.responseError ? a = {
success: !1,
errors: [this.responseError],
meta: {
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
requestId: v(),
version: "1.0.0",
...this.metadata
}
} : a = {
success: !0,
data: this.responseData,
meta: {
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
requestId: v(),
version: "1.0.0",
...this.metadata
}
};
const n = {
"Content-Type": "application/json",
"X-Mock-Response": "true",
...this.responseHeaders
};
if (this.metadata.generatedAt) {
const r = performance.now();
n["X-Generation-Time"] = `${(r - t).toFixed(2)}ms`;
}
return C.json(a, {
status: this.statusCode,
headers: n
});
}
/**
* Build with async delay
*/
async buildAsync() {
return this.responseDelay && await L(this.responseDelay), this.build();
}
}
function f(e = {}) {
return new V(e);
}
function Z(e, t = {}) {
return f({
...t,
data: e,
success: !0
}).build();
}
function R(e, t = {}) {
const a = e.status || 400;
return f({
...t,
error: e,
success: !1,
status: a
}).build();
}
function _(e, t = [1e3, 3e3], a = {}) {
return f({
...a,
data: e,
delay: t
});
}
function Q(e = "Resource not found", t = {}) {
return R(
{
code: "NOT_FOUND",
message: e
},
{ ...t, status: 404 }
);
}
function ee(e = "Unauthorized", t = {}) {
return R(
{
code: "UNAUTHORIZED",
message: e
},
{ ...t, status: 401 }
);
}
function te(e = "Forbidden", t = {}) {
return R(
{
code: "FORBIDDEN",
message: e
},
{ ...t, status: 403 }
);
}
function ae(e, t = "Validation failed", a = {}) {
return R(
{
code: "VALIDATION_ERROR",
message: t,
details: e
},
{ ...a, status: 400 }
);
}
function ne(e = "Internal server error", t = {}) {
return R(
{
code: "INTERNAL_SERVER_ERROR",
message: e
},
{ ...t, status: 500 }
);
}
function re(e = "Rate limit exceeded", t = 60, a = {}) {
return f({
...a,
error: {
code: "RATE_LIMIT_EXCEEDED",
message: e
},
headers: {
"Retry-After": t.toString(),
...a.headers
},
status: 429
}).build();
}
function se(e = "Service temporarily unavailable", t = 3600, a = {}) {
return f({
...a,
error: {
code: "SERVICE_UNAVAILABLE",
message: e
},
headers: {
"Retry-After": t.toString(),
...a.headers
},
status: 503
}).build();
}
function ie(e, t, a, n = {}) {
const r = f({
...n,
status: e
});
return a ? r.error(a) : t !== void 0 && r.data(t), r.build();
}
function oe(e, t = "fast", a = {}) {
let n;
switch (t) {
case "fast":
n = [10, 50];
break;
case "slow":
n = [2e3, 5e3];
break;
case "unstable":
n = [100, 3e3];
break;
default:
n = [100, 300];
}
return f({
...a,
data: e,
delay: n
});
}
function ue(e, t = "public, max-age=3600", a = {}) {
return f({
...a,
data: e,
headers: {
"Cache-Control": t,
ETag: `"${Date.now()}"`,
...a.headers
}
}).build();
}
function le(e, t = "*", a = {}) {
return f({
...a,
data: e,
headers: {
"Access-Control-Allow-Origin": t,
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
...a.headers
}
}).build();
}
function y(e, t) {
const a = [], n = {};
for (const r of t.fields) {
const i = String(r.field), s = e[r.field], d = [];
if (r.required && (s == null || s === "")) {
const h = r.requiredMessage || `${i} is required`;
d.push(h), a.push(h);
} else if (s != null)
for (const h of r.rules) {
const p = h.validate(s, e);
if (p === !1) {
const b = h.message || `${i} failed ${h.name} validation`;
d.push(b), a.push(b);
} else typeof p == "string" && (d.push(p), a.push(p));
}
d.length > 0 && (n[i] = d);
}
if (t.customValidation) {
const r = t.customValidation(e);
r && a.push(...r);
}
return {
valid: a.length === 0,
errors: a,
fieldErrors: Object.keys(n).length > 0 ? n : {}
};
}
const o = {
/**
* Email validation rule
*/
email: () => ({
name: "email",
validate: (e) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e),
message: "Must be a valid email address"
}),
/**
* Minimum length validation rule
*/
minLength: (e) => ({
name: "minLength",
validate: (t) => t.length >= e,
message: `Must be at least ${e} characters long`
}),
/**
* Maximum length validation rule
*/
maxLength: (e) => ({
name: "maxLength",
validate: (t) => t.length <= e,
message: `Must be no more than ${e} characters long`
}),
/**
* Minimum value validation rule
*/
min: (e) => ({
name: "min",
validate: (t) => t >= e,
message: `Must be at least ${e}`
}),
/**
* Maximum value validation rule
*/
max: (e) => ({
name: "max",
validate: (t) => t <= e,
message: `Must be no more than ${e}`
}),
/**
* Pattern validation rule
*/
pattern: (e, t) => ({
name: "pattern",
validate: (a) => e.test(a),
message: t || "Invalid format"
}),
/**
* URL validation rule
*/
url: () => ({
name: "url",
validate: (e) => {
try {
return new URL(e), !0;
} catch {
return !1;
}
},
message: "Must be a valid URL"
}),
/**
* Phone number validation rule
*/
phone: () => ({
name: "phone",
validate: (e) => /^[\+]?[1-9][\d]{0,15}$/.test(e.replace(/[\s\-\(\)]/g, "")),
message: "Must be a valid phone number"
}),
/**
* Date validation rule
*/
date: () => ({
name: "date",
validate: (e) => {
const t = new Date(e);
return !isNaN(t.getTime());
},
message: "Must be a valid date"
}),
/**
* Future date validation rule
*/
futureDate: () => ({
name: "futureDate",
validate: (e) => new Date(e) > /* @__PURE__ */ new Date(),
message: "Must be a future date"
}),
/**
* Past date validation rule
*/
pastDate: () => ({
name: "pastDate",
validate: (e) => new Date(e) < /* @__PURE__ */ new Date(),
message: "Must be a past date"
}),
/**
* One of validation rule
*/
oneOf: (e) => ({
name: "oneOf",
validate: (t) => e.includes(t),
message: `Must be one of: ${e.join(", ")}`
}),
/**
* Array validation rule
*/
array: (e, t) => ({
name: "array",
validate: (a) => !(!Array.isArray(a) || e !== void 0 && a.length < e || t !== void 0 && a.length > t),
message: `Must be an array${e !== void 0 ? ` with at least ${e} items` : ""}${t !== void 0 ? ` and no more than ${t} items` : ""}`
}),
/**
* Object validation rule
*/
object: () => ({
name: "object",
validate: (e) => typeof e == "object" && e !== null && !Array.isArray(e),
message: "Must be an object"
}),
/**
* Number validation rule
*/
number: () => ({
name: "number",
validate: (e) => typeof e == "number" && !isNaN(e),
message: "Must be a number"
}),
/**
* Integer validation rule
*/
integer: () => ({
name: "integer",
validate: (e) => Number.isInteger(e),
message: "Must be an integer"
}),
/**
* Boolean validation rule
*/
boolean: () => ({
name: "boolean",
validate: (e) => typeof e == "boolean",
message: "Must be a boolean"
}),
/**
* String validation rule
*/
string: () => ({
name: "string",
validate: (e) => typeof e == "string",
message: "Must be a string"
}),
/**
* Custom validation rule
*/
custom: (e, t = "Custom validation failed") => ({
name: "custom",
validate: e,
message: t
})
};
function u(e, t, a = !1, n) {
return {
field: e,
rules: t,
required: a,
requiredMessage: n || `${String(e)} is required`
};
}
function D(e, t) {
return {
fields: e,
customValidation: t || (() => null)
};
}
const ce = {
/**
* Validate user data
*/
user: (e) => {
const t = D([
u("email", [o.email()], !0),
u("firstName", [o.minLength(1)], !0),
u("lastName", [o.minLength(1)], !0),
u("phone", [o.phone()], !1)
]);
return y(e, t);
},
/**
* Validate product data
*/
product: (e) => {
const t = D([
u("name", [o.minLength(1)], !0),
u("price", [o.number(), o.min(0)], !0),
u("description", [o.maxLength(1e3)], !1),
u("category", [o.minLength(1)], !0)
]);
return y(e, t);
},
/**
* Validate order data
*/
order: (e) => {
const t = D([
u("customerId", [o.minLength(1)], !0),
u("items", [o.array(1)], !0),
u("total", [o.number(), o.min(0)], !0),
u("status", [o.oneOf(["pending", "processing", "shipped", "delivered", "cancelled"])], !0)
]);
return y(e, t);
},
/**
* Validate address data
*/
address: (e) => {
const t = D([
u("street", [o.minLength(1)], !0),
u("city", [o.minLength(1)], !0),
u("state", [o.minLength(1)], !0),
u("zipCode", [o.pattern(/^\d{5}(-\d{4})?$/, "Invalid ZIP code format")], !0),
u("country", [o.minLength(2)], !0)
]);
return y(e, t);
}
};
function de(e, t, a) {
let n = { ...e };
if (a)
for (const [i, s] of Object.entries(a))
n[i] !== void 0 && (n[i] = s(n[i]));
const r = y(n, t);
return {
valid: r.valid,
data: n,
errors: r.errors
};
}
export {
ae as A,
ne as B,
re as C,
se as D,
ie as E,
oe as F,
ue as G,
le as H,
y as I,
o as J,
u as K,
D as L,
V as M,
ce as N,
de as O,
c as a,
J as b,
j as c,
A as d,
P as e,
$ as f,
v as g,
q as h,
N as i,
E as j,
I as k,
z as l,
F as m,
B as n,
G as o,
g as p,
W as q,
Y as r,
K as s,
f as t,
Z as u,
R as v,
_ as w,
Q as x,
ee as y,
te as z
};
//# sourceMappingURL=validation-Arr3Zrwv.js.map