@dbs-portal/tool-mock
Version:
API mocking toolkit using MSW for DBS Portal development workflows
712 lines (711 loc) • 16.1 kB
JavaScript
import { http as y, HttpResponse as S } from "msw";
import { j as O } from "./delay-C3BTE-53.js";
import { s as R } from "./auth-DT3h0fWG.js";
import { l as b, g as D } from "./setup-oE-TArFC.js";
import { c as v } from "./pagination-DLG5J9NY.js";
class A {
handlers = /* @__PURE__ */ new Set();
taggedHandlers = /* @__PURE__ */ new Map();
handlerMetadata = /* @__PURE__ */ new WeakMap();
/**
* Register handlers
*/
register(...e) {
for (const t of e)
this.handlers.add(t);
}
/**
* Unregister handlers
*/
unregister(...e) {
for (const t of e) {
this.handlers.delete(t);
for (const a of this.taggedHandlers.values())
a.delete(t);
this.handlerMetadata.delete(t);
}
}
/**
* Get all registered handlers
*/
getHandlers() {
return Array.from(this.handlers);
}
/**
* Clear all handlers
*/
clear() {
this.handlers.clear(), this.taggedHandlers.clear();
}
/**
* Get handlers by tag
*/
getByTag(e) {
const t = this.taggedHandlers.get(e);
return t ? Array.from(t) : [];
}
/**
* Tag handlers
*/
tag(e, ...t) {
this.taggedHandlers.has(e) || this.taggedHandlers.set(e, /* @__PURE__ */ new Set());
const a = this.taggedHandlers.get(e);
for (const r of t) {
a.add(r);
const i = this.handlerMetadata.get(r) || {}, d = i.tags || [];
d.includes(e) || d.push(e), this.handlerMetadata.set(r, {
...i,
tags: d
});
}
}
/**
* Set metadata for a handler
*/
setMetadata(e, t) {
if (this.handlerMetadata.set(e, t), t.tags)
for (const a of t.tags)
this.tag(a, e);
}
/**
* Get metadata for a handler
*/
getMetadata(e) {
return this.handlerMetadata.get(e);
}
/**
* Get all tags
*/
getTags() {
return Array.from(this.taggedHandlers.keys());
}
/**
* Remove tag
*/
removeTag(e) {
const t = this.taggedHandlers.get(e);
if (t) {
for (const a of t) {
const r = this.handlerMetadata.get(a);
r?.tags && (r.tags = r.tags.filter((i) => i !== e), r.tags.length === 0 && delete r.tags);
}
this.taggedHandlers.delete(e);
}
}
/**
* Get handlers with metadata
*/
getTaggedHandlers() {
return this.getHandlers().map((e) => ({
handler: e,
metadata: this.getMetadata(e) || {}
}));
}
/**
* Find handlers by criteria
*/
find(e) {
return this.getHandlers().filter((a) => {
const r = this.getMetadata(a);
if (e.name && r?.name !== e.name || e.author && r?.author !== e.author)
return !1;
if (e.tags && e.tags.length > 0) {
const i = r?.tags || [];
if (!e.tags.every((c) => i.includes(c)))
return !1;
}
return !0;
});
}
/**
* Get registry statistics
*/
getStats() {
const e = this.getHandlers(), t = this.getTags(), a = t.map((r) => ({
tag: r,
count: this.getByTag(r).length
}));
return {
totalHandlers: e.length,
totalTags: t.length,
tagStats: a
};
}
}
const I = new A();
function V(...s) {
I.register(...s);
}
function x(...s) {
I.unregister(...s);
}
function B() {
return I.getHandlers();
}
function z() {
I.clear();
}
function $(s, ...e) {
I.tag(s, ...e);
}
function J(s) {
return I.getByTag(s);
}
function G() {
return new A();
}
function m(s, e, t) {
const a = y[s.toLowerCase()];
return a(e, async ({ request: r, params: i }) => {
const d = b(), c = R(r.url, s, d.errorSimulation);
if (c)
return c;
if (t.auth) {
const g = F(r, t.auth);
if (!g.success)
return S.json(
{
success: !1,
error: {
code: g.code,
message: g.message
}
},
{ status: g.status || 401 }
);
}
const o = new URL(r.url), u = {
url: o,
method: r.method,
headers: r.headers,
body: r.body ? await r.json().catch(() => null) : null,
params: i || {},
query: Object.fromEntries(o.searchParams.entries())
}, n = await t.response(u), l = t.delay || d.delay;
l && await O(l);
const h = t.status || 200, f = {
"Content-Type": "application/json",
...t.headers
};
return S.json(n, { status: h, headers: f });
});
}
function q(s) {
return Object.entries(s).map(([e, t]) => {
const a = m(
t.method,
t.path,
t
);
return a.__handlerName = e, a;
});
}
function K(s, e, t, a = {}) {
return m(s, e, {
...a,
response: t
});
}
function W(s, e, t = {}) {
return m("GET", s, { ...t, response: e });
}
function Q(s, e, t = {}) {
return m("POST", s, { ...t, response: e });
}
function Z(s, e, t = {}) {
return m("PUT", s, { ...t, response: e });
}
function X(s, e, t = {}) {
return m("PATCH", s, { ...t, response: e });
}
function Y(s, e, t = {}) {
return m("DELETE", s, { ...t, response: e });
}
function ee(s, e) {
return s;
}
function te(s, e, t) {
return m(s, e, {
response: () => ({
success: !1,
error: {
code: t.code,
message: t.message,
details: t.details
}
}),
status: t.status
});
}
function se(s, e, t, a = [1e3, 3e3]) {
return m(s, e, {
response: t,
delay: a
});
}
function F(s, e) {
if (!e.requireAuth)
return { success: !0 };
const t = s.headers.get("Authorization");
if (!t)
return {
success: !1,
code: "UNAUTHORIZED",
message: "Authorization header is required",
status: 401
};
if (!t.startsWith("Bearer "))
return {
success: !1,
code: "INVALID_TOKEN",
message: "Invalid authorization format",
status: 401
};
const a = t.substring(7);
if (!a)
return {
success: !1,
code: "MISSING_TOKEN",
message: "Token is required",
status: 401
};
try {
const r = JSON.parse(atob(a.split(".")[1] || ""));
if (e.requiredRoles && e.requiredRoles.length > 0) {
const i = r.roles || [];
if (!e.requiredRoles.some(
(c) => i.includes(c)
))
return {
success: !1,
code: "INSUFFICIENT_PERMISSIONS",
message: "Insufficient role permissions",
status: 403
};
}
if (e.requiredPermissions && e.requiredPermissions.length > 0) {
const i = r.permissions || [];
if (!e.requiredPermissions.every(
(c) => i.includes(c)
))
return {
success: !1,
code: "INSUFFICIENT_PERMISSIONS",
message: "Insufficient permissions",
status: 403
};
}
if (e.validator) {
const i = {
url: new URL(s.url),
method: s.method,
headers: s.headers,
body: null,
params: {},
query: {}
};
if (!e.validator(i))
return {
success: !1,
code: "CUSTOM_AUTH_FAILED",
message: "Custom authentication failed",
status: 403
};
}
return { success: !0 };
} catch {
return {
success: !1,
code: "INVALID_TOKEN",
message: "Invalid token format",
status: 401
};
}
}
class _ {
constructor(e, t = []) {
this.options = e;
for (const a of t) {
const r = this.getId(a);
this.data.set(r, a), typeof r == "string" && /^\d+$/.test(r) && (this.nextId = Math.max(this.nextId, parseInt(r, 10) + 1));
}
}
data = /* @__PURE__ */ new Map();
nextId = 1;
getId(e) {
const t = this.options.idField || "id", a = e[t];
return String(a || this.nextId++);
}
setId(e, t) {
const a = this.options.idField || "id";
return { ...e, [a]: t };
}
getAll() {
const e = Array.from(this.data.values());
if (this.options.softDelete) {
const t = this.options.deletedField || "deleted";
return e.filter((a) => !a[t]);
}
return e;
}
getById(e) {
const t = this.data.get(e);
if (t && this.options.softDelete) {
const a = this.options.deletedField || "deleted";
if (t[a])
return;
}
return t;
}
create(e) {
const t = String(this.nextId++), a = this.setId(this.options.dataFactory(e), t);
return this.data.set(t, a), a;
}
update(e, t) {
const a = this.getById(e);
if (!a)
return;
const r = { ...a, ...t };
return this.data.set(e, r), r;
}
delete(e) {
if (this.options.softDelete) {
const t = this.getById(e);
if (!t)
return !1;
const a = this.options.deletedField || "deleted", r = { ...t, [a]: !0 };
return this.data.set(e, r), !0;
} else
return this.data.delete(e);
}
search(e, t) {
const a = this.getAll(), r = e.toLowerCase();
return a.filter((i) => t.some((d) => {
const c = i[d];
return c && String(c).toLowerCase().includes(r);
}));
}
filter(e) {
return this.getAll().filter((a) => Object.entries(e).every(([r, i]) => {
const d = a[r];
return Array.isArray(i) ? i.includes(d) : d === i;
}));
}
sort(e, t, a = "asc") {
return [...e].sort((r, i) => {
const d = r[t], c = i[t];
return d < c ? a === "asc" ? -1 : 1 : d > c ? a === "asc" ? 1 : -1 : 0;
});
}
}
function ae(s) {
const e = new _(s, s.initialData), t = b(), a = async (o, u) => {
const n = R(o.url, u, t.errorSimulation);
if (n)
return n;
const l = s.delay || t.delay;
return l && await O(l), null;
}, r = (o) => s.validate ? s.validate(o) : null, i = (o, u = 200) => {
const n = {
"Content-Type": "application/json",
...s.headers
};
return S.json(
{
success: !0,
data: o,
timestamp: (/* @__PURE__ */ new Date()).toISOString()
},
{ status: u, headers: n }
);
}, d = (o, u = 400) => S.json(
{
success: !1,
error: o,
timestamp: (/* @__PURE__ */ new Date()).toISOString()
},
{ status: u }
), c = [];
return c.push(
y.get(s.basePath, async ({ request: o }) => {
const u = await a(o, "GET");
if (u) return u;
const n = new URL(o.url), l = parseInt(n.searchParams.get("page") || "1", 10), h = Math.min(
parseInt(n.searchParams.get("pageSize") || String(s.pagination?.defaultPageSize || 10), 10),
s.pagination?.maxPageSize || 100
), f = n.searchParams.get("search") || n.searchParams.get("q"), g = n.searchParams.get("sortBy"), E = n.searchParams.get("sortOrder") || "asc";
let p = e.getAll();
if (f) {
const w = Object.keys(p[0] || {});
p = e.search(f, w);
}
const T = {};
for (const [w, M] of n.searchParams.entries())
["page", "pageSize", "search", "q", "sortBy", "sortOrder"].includes(w) || (T[w] = M);
Object.keys(T).length > 0 && (p = e.filter(T)), g && (p = e.sort(p, g, E));
const P = v({
items: p,
page: l,
pageSize: h,
total: p.length
});
return i(P.data, 200);
})
), c.push(
y.get(`${s.basePath}/:id`, async ({ request: o, params: u }) => {
const n = await a(o, "GET");
if (n) return n;
const l = u.id, h = e.getById(l);
return h ? i(h) : d(
{
code: "NOT_FOUND",
message: `Item with id ${l} not found`
},
404
);
})
), c.push(
y.post(s.basePath, async ({ request: o }) => {
const u = await a(o, "POST");
if (u) return u;
try {
const n = await o.json(), l = r(n);
if (l)
return d(
{
code: "VALIDATION_ERROR",
message: "Validation failed",
details: l
},
400
);
const h = e.create(n);
return i(h, 201);
} catch {
return d(
{
code: "INVALID_JSON",
message: "Invalid JSON in request body"
},
400
);
}
})
), c.push(
y.put(`${s.basePath}/:id`, async ({ request: o, params: u }) => {
const n = await a(o, "PUT");
if (n) return n;
const l = u.id;
try {
const h = await o.json(), f = r(h);
if (f)
return d(
{
code: "VALIDATION_ERROR",
message: "Validation failed",
details: f
},
400
);
const g = e.update(l, h);
return g ? i(g) : d(
{
code: "NOT_FOUND",
message: `Item with id ${l} not found`
},
404
);
} catch {
return d(
{
code: "INVALID_JSON",
message: "Invalid JSON in request body"
},
400
);
}
})
), c.push(
y.patch(`${s.basePath}/:id`, async ({ request: o, params: u }) => {
const n = await a(o, "PATCH");
if (n) return n;
const l = u.id;
try {
const h = await o.json(), f = r(h);
if (f)
return d(
{
code: "VALIDATION_ERROR",
message: "Validation failed",
details: f
},
400
);
const g = e.update(l, h);
return g ? i(g) : d(
{
code: "NOT_FOUND",
message: `Item with id ${l} not found`
},
404
);
} catch {
return d(
{
code: "INVALID_JSON",
message: "Invalid JSON in request body"
},
400
);
}
})
), c.push(
y.delete(`${s.basePath}/:id`, async ({ request: o, params: u }) => {
const n = await a(o, "DELETE");
if (n) return n;
const l = u.id;
return e.delete(l) ? i({ id: l, deleted: !0 }, 200) : d(
{
code: "NOT_FOUND",
message: `Item with id ${l} not found`
},
404
);
})
), c;
}
class N {
handlers = /* @__PURE__ */ new Set();
enabled = !0;
/**
* Add handlers
*/
add(...e) {
for (const t of e)
this.handlers.add(t);
this.enabled && this.applyHandlers();
}
/**
* Remove handlers
*/
remove(...e) {
for (const t of e)
this.handlers.delete(t);
this.enabled && this.applyHandlers();
}
/**
* Replace all handlers
*/
replace(e) {
this.handlers.clear();
for (const t of e)
this.handlers.add(t);
this.enabled && this.applyHandlers();
}
/**
* Get current handlers
*/
getHandlers() {
return Array.from(this.handlers);
}
/**
* Enable/disable handlers
*/
setEnabled(e) {
this.enabled = e, this.applyHandlers();
}
/**
* Check if enabled
*/
isEnabled() {
return this.enabled;
}
/**
* Apply handlers to MSW instance
*/
applyHandlers() {
const e = D();
if (!e) {
console.warn("MSW instance not available, cannot apply handlers");
return;
}
this.enabled ? e.resetHandlers(...this.getHandlers()) : e.resetHandlers();
}
/**
* Clear all handlers
*/
clear() {
this.handlers.clear(), this.enabled && this.applyHandlers();
}
/**
* Get handler count
*/
getHandlerCount() {
return this.handlers.size;
}
/**
* Check if handler exists
*/
hasHandler(e) {
return this.handlers.has(e);
}
}
const H = new N();
function re(...s) {
H.add(...s);
}
function ne(...s) {
H.remove(...s);
}
function ie(s) {
H.replace(s);
}
function de() {
return H.getHandlers();
}
function oe(s) {
H.setEnabled(s);
}
function le() {
return H.isEnabled();
}
function ce() {
H.clear();
}
function ue() {
return new N();
}
export {
oe as A,
le as B,
ce as C,
ue as D,
A as M,
B as a,
J as b,
z as c,
G as d,
m as e,
q as f,
I as g,
K as h,
W as i,
Q as j,
Z as k,
X as l,
Y as m,
te as n,
se as o,
ae as p,
N as q,
V as r,
H as s,
$ as t,
x as u,
re as v,
ee as w,
ne as x,
ie as y,
de as z
};
//# sourceMappingURL=manager-BJaZBgsI.js.map