UNPKG

@dbs-portal/tool-mock

Version:

API mocking toolkit using MSW for DBS Portal development workflows

441 lines (440 loc) 10.7 kB
import { HttpResponse as i, http as S } from "msw"; import { h as E, j as T } from "./delay-C3BTE-53.js"; import { l as k } from "./setup-oE-TArFC.js"; function N(e, r, t) { if (!t) return null; if (t.networkErrorRate && E() < t.networkErrorRate) return A(); if (t.serverErrorRate && E() < t.serverErrorRate) return _(); if (t.timeoutErrorRate && E() < t.timeoutErrorRate) return b(); if (t.customErrors) { for (const a of t.customErrors) if (j(e, a.pattern) && (!a.method || a.method === r) && (!a.probability || E() < a.probability)) { const d = typeof a.error == "function" ? a.error() : a.error; return i.json( { success: !1, error: d, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, { status: d.status || 500 } ); } } return null; } function A() { return i.json( { success: !1, error: { code: "NETWORK_ERROR", message: "Network request failed", status: 0 }, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, { status: 0 } ); } function _() { const e = [ { code: "INTERNAL_SERVER_ERROR", message: "Internal server error", status: 500 }, { code: "BAD_GATEWAY", message: "Bad gateway", status: 502 }, { code: "SERVICE_UNAVAILABLE", message: "Service unavailable", status: 503 }, { code: "GATEWAY_TIMEOUT", message: "Gateway timeout", status: 504 } ], r = e[Math.floor(E() * e.length)]; return i.json( { success: !1, error: r, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, { status: r?.status || 500 } ); } function b() { return i.json( { success: !1, error: { code: "TIMEOUT_ERROR", message: "Request timeout", status: 408 }, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, { status: 408 } ); } function j(e, r) { return typeof r == "string" ? e.includes(r) : r.test(e); } const U = { /** * Create a validation error */ validation: (e, r = "Validation failed") => i.json( { success: !1, error: { code: "VALIDATION_ERROR", message: r, details: e, status: 400 }, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, { status: 400 } ), /** * Create an unauthorized error */ unauthorized: (e = "Unauthorized") => i.json( { success: !1, error: { code: "UNAUTHORIZED", message: e, status: 401 }, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, { status: 401 } ), /** * Create a forbidden error */ forbidden: (e = "Forbidden") => i.json( { success: !1, error: { code: "FORBIDDEN", message: e, status: 403 }, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, { status: 403 } ), /** * Create a not found error */ notFound: (e = "Resource not found") => i.json( { success: !1, error: { code: "NOT_FOUND", message: e, status: 404 }, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, { status: 404 } ), /** * Create a conflict error */ conflict: (e = "Resource conflict") => i.json( { success: !1, error: { code: "CONFLICT", message: e, status: 409 }, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, { status: 409 } ), /** * Create a rate limit error */ rateLimit: (e = "Rate limit exceeded", r = 60) => i.json( { success: !1, error: { code: "RATE_LIMIT_EXCEEDED", message: e, status: 429 }, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, { status: 429, headers: { "Retry-After": r.toString() } } ), /** * Create a server error */ serverError: (e = "Internal server error") => i.json( { success: !1, error: { code: "INTERNAL_SERVER_ERROR", message: e, status: 500 }, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, { status: 500 } ), /** * Create a custom error */ custom: (e, r, t, a) => i.json( { success: !1, error: { code: e, message: r, status: t, details: a }, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, { status: t } ) }; function V(e, r = {}) { let t = e; return r.timeOfDay !== void 0 && r.timeOfDay >= 9 && r.timeOfDay <= 17 && (t *= 1.5), r.dayOfWeek !== void 0 && r.dayOfWeek >= 1 && r.dayOfWeek <= 5 && (t *= 1.2), r.load !== void 0 && (t *= 1 + r.load), Math.min(t, 1); } function G(e) { switch (e) { case "development": return { networkErrorRate: 0.02, serverErrorRate: 0.01, timeoutErrorRate: 5e-3, customErrors: [] }; case "testing": return { networkErrorRate: 0, serverErrorRate: 0, timeoutErrorRate: 0, customErrors: [] }; case "staging": return { networkErrorRate: 0.01, serverErrorRate: 5e-3, timeoutErrorRate: 2e-3, customErrors: [] }; case "production": default: return { networkErrorRate: 0, serverErrorRate: 0, timeoutErrorRate: 0, customErrors: [] }; } } function I(e, r = "1h") { const t = { alg: "HS256", typ: "JWT" }, a = { sub: e.id, email: e.email, roles: e.roles || [], permissions: e.permissions || [], iat: Math.floor(Date.now() / 1e3), exp: Math.floor(Date.now() / 1e3) + g(r) }, d = btoa(JSON.stringify(t)), R = btoa(JSON.stringify(a)), m = btoa(`mock-signature-${e.id}`); return `${d}.${R}.${m}`; } function g(e) { const r = e.match(/^(\d+)([smhd])$/); if (!r) return 3600; const t = parseInt(r[1] || "0", 10); switch (r[2]) { case "s": return t; case "m": return t * 60; case "h": return t * 3600; case "d": return t * 86400; default: return 3600; } } function y(e) { try { const r = e.split("."); if (r.length !== 3) return { valid: !1 }; const t = JSON.parse(atob(r[1] || "")), a = Math.floor(Date.now() / 1e3); return t.exp && t.exp < a ? { valid: !1 } : { valid: !0, payload: t }; } catch { return { valid: !1 }; } } function F(e, r = {}) { const t = k(), a = r.users || [], d = r.tokenExpiry || "1h", R = r.refreshTokenExpiry || "7d", m = async (n, s) => { const o = N(n.url, s, t.errorSimulation); if (o) return o; const u = t.delay; return u && await T(u), null; }, p = (n, s = 200) => i.json( { success: !0, data: n, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, { status: s } ), l = (n, s = 400) => i.json( { success: !1, error: n, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, { status: s } ), v = (n, s) => r.userValidator ? r.userValidator({ email: n, password: s }) : a.find( (o) => o.email === n && o.password === s && o.isActive !== !1 ) || null, h = (n) => { const s = y(n); return !s.valid || !s.payload ? null : a.find((o) => o.id === s.payload.sub) || null; }, f = []; return f.push( S.post(`${e}/login`, async ({ request: n }) => { const s = await m(n, "POST"); if (s) return s; try { const o = await n.json(); if (!o.email || !o.password) return l( { code: "MISSING_CREDENTIALS", message: "Email and password are required" }, 400 ); const u = v(o.email, o.password); if (!u) return l( { code: "INVALID_CREDENTIALS", message: "Invalid email or password" }, 401 ); const c = r.tokenGenerator ? r.tokenGenerator(u) : I(u, d), w = I(u, R), O = { user: { ...u, password: void 0 // Remove password from response }, token: c, refreshToken: w, expiresIn: g(d) }; return p(O); } catch { return l( { code: "INVALID_JSON", message: "Invalid JSON in request body" }, 400 ); } }) ), f.push( S.post(`${e}/logout`, async ({ request: n }) => { const s = await m(n, "POST"); return s || p({ message: "Logged out successfully" }); }) ), f.push( S.post(`${e}/refresh`, async ({ request: n }) => { const s = await m(n, "POST"); if (s) return s; try { const { refreshToken: o } = await n.json(); if (!o) return l( { code: "MISSING_REFRESH_TOKEN", message: "Refresh token is required" }, 400 ); if (!y(o).valid) return l( { code: "INVALID_REFRESH_TOKEN", message: "Invalid or expired refresh token" }, 401 ); const c = h(o); if (!c) return l( { code: "USER_NOT_FOUND", message: "User not found" }, 401 ); const w = r.tokenGenerator ? r.tokenGenerator(c) : I(c, d), O = I(c, R), D = { user: { ...c, password: void 0 }, token: w, refreshToken: O, expiresIn: g(d) }; return p(D); } catch { return l( { code: "INVALID_JSON", message: "Invalid JSON in request body" }, 400 ); } }) ), f.push( S.get(`${e}/me`, async ({ request: n }) => { const s = await m(n, "GET"); if (s) return s; const o = n.headers.get("Authorization"); if (!o || !o.startsWith("Bearer ")) return l( { code: "UNAUTHORIZED", message: "Authorization header is required" }, 401 ); const u = o.substring(7), c = h(u); return c ? p({ ...c, password: void 0 }) : l( { code: "INVALID_TOKEN", message: "Invalid or expired token" }, 401 ); }) ), f; } export { V as a, G as b, F as c, U as e, N as s }; //# sourceMappingURL=auth-DT3h0fWG.js.map