@pafi-dev/issuer 0.7.9 → 0.9.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.
@@ -0,0 +1,314 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
8
+ var __typeError = (msg) => {
9
+ throw TypeError(msg);
10
+ };
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
26
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
27
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
28
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
29
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
30
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
31
+ var __runInitializers = (array, flags, self, value) => {
32
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
33
+ return value;
34
+ };
35
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
36
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
37
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
38
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
39
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
40
+ return __privateGet(this, extra);
41
+ }, set [name](x) {
42
+ return __privateSet(this, extra, x);
43
+ } }, name));
44
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
45
+ for (var i = decorators.length - 1; i >= 0; i--) {
46
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
47
+ if (k) {
48
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
49
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
50
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
51
+ }
52
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
53
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
54
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
55
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
56
+ }
57
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
58
+ };
59
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
60
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
61
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
62
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
63
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
64
+
65
+ // src/nestjs/index.ts
66
+ var nestjs_exports = {};
67
+ __export(nestjs_exports, {
68
+ PafiHttpExceptionFilter: () => PafiHttpExceptionFilter
69
+ });
70
+ module.exports = __toCommonJS(nestjs_exports);
71
+
72
+ // src/nestjs/httpExceptionFilter.ts
73
+ var import_common = require("@nestjs/common");
74
+ var import_node_crypto = require("crypto");
75
+
76
+ // src/errors.ts
77
+ var import_core = require("@pafi-dev/core");
78
+ var import_core2 = require("@pafi-dev/core");
79
+ var import_core3 = require("@pafi-dev/core");
80
+
81
+ // src/api/errorMapper.ts
82
+ function buildSdkErrorBody(err) {
83
+ const type = err.type ?? (0, import_core.defaultErrorTypeForStatus)(import_core.SDK_ERROR_HTTP_STATUS_CODE[err.httpStatus]);
84
+ const body = {
85
+ type,
86
+ code: err.code,
87
+ message: err.message,
88
+ safeToRetry: err.safeToRetry
89
+ };
90
+ if (err.param) body.param = err.param;
91
+ if (err.metadata) body.metadata = err.metadata;
92
+ if (err.details !== void 0) body.details = err.details;
93
+ return body;
94
+ }
95
+
96
+ // src/http/errorEnvelope.ts
97
+ function isValidationPipeBody(body) {
98
+ return Array.isArray(body["message"]) && typeof body["error"] === "string" && body["error"] === "Bad Request";
99
+ }
100
+ function extractParamFromValidatorMessage(message) {
101
+ const idx = message.indexOf(" ");
102
+ if (idx <= 0) return void 0;
103
+ const candidate = message.slice(0, idx);
104
+ return /^[A-Za-z_][\w.]*$/.test(candidate) ? candidate : void 0;
105
+ }
106
+ function normalizeValidationPipeBody(body) {
107
+ const fields = {};
108
+ for (const msg of body.message) {
109
+ const param2 = extractParamFromValidatorMessage(msg);
110
+ const key = param2 ?? "_";
111
+ (fields[key] ??= []).push(msg);
112
+ }
113
+ const fieldKeys = Object.keys(fields).filter((k) => k !== "_");
114
+ const param = fieldKeys.length === 1 ? fieldKeys[0] : void 0;
115
+ const payload = {
116
+ type: "validation_error",
117
+ code: "VALIDATION_FAILED",
118
+ message: body.message.join("; "),
119
+ safeToRetry: false,
120
+ metadata: { fieldErrors: fields }
121
+ };
122
+ if (param) payload.param = param;
123
+ return payload;
124
+ }
125
+ function normalizeHttpExceptionBody(desc) {
126
+ const { statusCode, responseBody, exceptionName, fallbackMessage } = desc;
127
+ const defaultType = (0, import_core.defaultErrorTypeForStatus)(statusCode);
128
+ if (typeof responseBody === "string") {
129
+ return {
130
+ type: defaultType,
131
+ code: exceptionName,
132
+ message: responseBody,
133
+ safeToRetry: false
134
+ };
135
+ }
136
+ if (responseBody && typeof responseBody === "object") {
137
+ const body = responseBody;
138
+ if (isValidationPipeBody(body)) {
139
+ return normalizeValidationPipeBody(body);
140
+ }
141
+ const code = typeof body["code"] === "string" && body["code"] || typeof body["error"] === "string" && body["error"] || exceptionName;
142
+ const message = typeof body["message"] === "string" && body["message"] || (Array.isArray(body["message"]) ? body["message"].join("; ") : "") || fallbackMessage;
143
+ const type = typeof body["type"] === "string" && body["type"] || defaultType;
144
+ const safeToRetry = typeof body["safeToRetry"] === "boolean" ? body["safeToRetry"] : false;
145
+ const payload = {
146
+ type,
147
+ code,
148
+ message,
149
+ safeToRetry
150
+ };
151
+ if (typeof body["param"] === "string") payload.param = body["param"];
152
+ if (body["metadata"] && typeof body["metadata"] === "object") {
153
+ payload.metadata = body["metadata"];
154
+ }
155
+ if (body["details"] !== void 0) payload.details = body["details"];
156
+ return payload;
157
+ }
158
+ return {
159
+ type: defaultType,
160
+ code: exceptionName || "INTERNAL_SERVER_ERROR",
161
+ message: fallbackMessage || "An unexpected error occurred",
162
+ safeToRetry: false
163
+ };
164
+ }
165
+ function payloadFromPafiSdkError(err) {
166
+ const body = buildSdkErrorBody(err);
167
+ const payload = {
168
+ type: body.type,
169
+ code: body.code,
170
+ message: body.message,
171
+ safeToRetry: body.safeToRetry
172
+ };
173
+ if (body.param) payload.param = body.param;
174
+ if (body.metadata) payload.metadata = body.metadata;
175
+ if (body.details !== void 0) payload.details = body.details;
176
+ return payload;
177
+ }
178
+ function sanitizeDbErrorMessage(message) {
179
+ if (/^[A-Z_]+: /.test(message) && message.length < 256) return message;
180
+ return "Internal database error";
181
+ }
182
+ function buildErrorEnvelope(input) {
183
+ const now = (input.ctx.now ?? (() => /* @__PURE__ */ new Date()))();
184
+ return {
185
+ success: false,
186
+ statusCode: input.status,
187
+ error: input.payload,
188
+ meta: {
189
+ timestamp: now.toISOString(),
190
+ requestId: input.ctx.requestId,
191
+ path: input.ctx.path
192
+ }
193
+ };
194
+ }
195
+ function payloadFromHttpException(desc) {
196
+ return normalizeHttpExceptionBody(desc);
197
+ }
198
+ function payloadFromGenericError(err) {
199
+ const name = err.name || "INTERNAL_SERVER_ERROR";
200
+ const isDbError = name === "QueryFailedError" || name === "EntityNotFoundError";
201
+ return {
202
+ type: "server_error",
203
+ code: name,
204
+ message: isDbError ? sanitizeDbErrorMessage(err.message) : err.message || "An unexpected error occurred",
205
+ safeToRetry: false
206
+ };
207
+ }
208
+
209
+ // src/nestjs/httpExceptionFilter.ts
210
+ var _PafiHttpExceptionFilter_decorators, _init;
211
+ _PafiHttpExceptionFilter_decorators = [(0, import_common.Catch)()];
212
+ var PafiHttpExceptionFilter = class {
213
+ logger = new import_common.Logger("PafiHttpExceptionFilter");
214
+ opts;
215
+ constructor(options = {}) {
216
+ this.opts = {
217
+ requestIdHeader: options.requestIdHeader ?? "x-request-id",
218
+ ...options
219
+ };
220
+ }
221
+ catch(exception, host) {
222
+ const ctx = host.switchToHttp();
223
+ const response = ctx.getResponse();
224
+ const request = ctx.getRequest();
225
+ const headerValue = request?.headers?.[this.opts.requestIdHeader];
226
+ const requestId = (Array.isArray(headerValue) ? headerValue[0] : headerValue) ?? (0, import_node_crypto.randomUUID)();
227
+ const normCtx = {
228
+ path: request?.url ?? "",
229
+ requestId,
230
+ ...this.opts.now ? { now: this.opts.now } : {}
231
+ };
232
+ const { status, payload } = this.normalize(exception);
233
+ const envelope = buildErrorEnvelope({ status, payload, ctx: normCtx });
234
+ if (this.opts.onError) {
235
+ try {
236
+ this.opts.onError(envelope, exception);
237
+ } catch (hookErr) {
238
+ this.logger.warn(
239
+ { err: hookErr instanceof Error ? hookErr.message : String(hookErr) },
240
+ "onError hook threw; continuing"
241
+ );
242
+ }
243
+ }
244
+ if (status >= 500) {
245
+ this.logger.error(
246
+ {
247
+ err: exception instanceof Error ? exception.message : String(exception),
248
+ stack: exception instanceof Error ? exception.stack : void 0,
249
+ name: exception instanceof Error ? exception.name : void 0,
250
+ path: normCtx.path,
251
+ requestId
252
+ },
253
+ "Unhandled error in PafiHttpExceptionFilter"
254
+ );
255
+ }
256
+ response.status(status).json(envelope);
257
+ }
258
+ normalize(exception) {
259
+ if (exception instanceof import_core.PafiSdkError) {
260
+ return {
261
+ status: import_core.SDK_ERROR_HTTP_STATUS_CODE[exception.httpStatus],
262
+ payload: payloadFromPafiSdkError(exception)
263
+ };
264
+ }
265
+ if (exception instanceof import_common.HttpException) {
266
+ return {
267
+ status: exception.getStatus(),
268
+ payload: payloadFromHttpException({
269
+ statusCode: exception.getStatus(),
270
+ responseBody: exception.getResponse(),
271
+ exceptionName: exception.name,
272
+ fallbackMessage: exception.message
273
+ })
274
+ };
275
+ }
276
+ if (exception instanceof Error) {
277
+ const maybeStatus = exception.status;
278
+ const maybeGetResponse = exception.getResponse;
279
+ if (typeof maybeStatus === "number" && typeof maybeGetResponse === "function") {
280
+ return {
281
+ status: maybeStatus,
282
+ payload: payloadFromHttpException({
283
+ statusCode: maybeStatus,
284
+ responseBody: maybeGetResponse.call(exception),
285
+ exceptionName: exception.name,
286
+ fallbackMessage: exception.message
287
+ })
288
+ };
289
+ }
290
+ const maybeStatusOnly = typeof maybeStatus === "number" ? maybeStatus : import_common.HttpStatus.INTERNAL_SERVER_ERROR;
291
+ return {
292
+ status: maybeStatusOnly,
293
+ payload: payloadFromGenericError(exception)
294
+ };
295
+ }
296
+ return {
297
+ status: import_common.HttpStatus.INTERNAL_SERVER_ERROR,
298
+ payload: {
299
+ type: "server_error",
300
+ code: "INTERNAL_SERVER_ERROR",
301
+ message: "An unexpected error occurred",
302
+ safeToRetry: false
303
+ }
304
+ };
305
+ }
306
+ };
307
+ _init = __decoratorStart(null);
308
+ PafiHttpExceptionFilter = __decorateElement(_init, 0, "PafiHttpExceptionFilter", _PafiHttpExceptionFilter_decorators, PafiHttpExceptionFilter);
309
+ __runInitializers(_init, 1, PafiHttpExceptionFilter);
310
+ // Annotate the CommonJS export names for ESM import in node:
311
+ 0 && (module.exports = {
312
+ PafiHttpExceptionFilter
313
+ });
314
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/nestjs/index.ts","../../src/nestjs/httpExceptionFilter.ts","../../src/errors.ts","../../src/api/errorMapper.ts","../../src/http/errorEnvelope.ts"],"sourcesContent":["export {\n PafiHttpExceptionFilter,\n type PafiHttpExceptionFilterOptions,\n} from \"./httpExceptionFilter\";\n","/**\n * NestJS global exception filter that emits the PAFI Stripe-style\n * envelope (see `@pafi-dev/issuer/http`).\n *\n * Wire it once in your bootstrap:\n *\n * ```ts\n * import { PafiHttpExceptionFilter } from \"@pafi-dev/issuer/nestjs\";\n *\n * app.useGlobalFilters(new PafiHttpExceptionFilter());\n * ```\n *\n * Catches every thrown value:\n * - `PafiSdkError` (and subclasses) → typed envelope from `httpStatus`/\n * `code`/`type`/`safeToRetry`/`param`/`metadata`.\n * - `HttpException` (NestJS) → respected status; SDK-shaped body is\n * passed through, plain bodies + ValidationPipe arrays normalized.\n * - any other `Error` → `server_error` 500 with sanitized message.\n *\n * `@nestjs/common` is an optional peer dependency — only required when\n * importing this sub-export.\n */\nimport {\n ArgumentsHost,\n Catch,\n ExceptionFilter,\n HttpException,\n HttpStatus,\n Logger,\n} from \"@nestjs/common\";\nimport { randomUUID } from \"node:crypto\";\n\nimport { PafiSdkError, SDK_ERROR_HTTP_STATUS_CODE } from \"../errors\";\nimport {\n buildErrorEnvelope,\n payloadFromGenericError,\n payloadFromHttpException,\n payloadFromPafiSdkError,\n type NormalizeContext,\n type PafiErrorEnvelope,\n type PafiErrorPayload,\n} from \"../http/errorEnvelope\";\n\ninterface MinimalHttpRequest {\n url?: string;\n headers?: Record<string, string | string[] | undefined>;\n}\ninterface MinimalHttpResponse {\n status(code: number): MinimalHttpResponse;\n json(body: unknown): unknown;\n}\n\n/** Customization knobs. None required — sensible defaults baked in. */\nexport interface PafiHttpExceptionFilterOptions {\n /**\n * Header to read for the request id, lowercase. Default `\"x-request-id\"`.\n * If absent, a UUIDv4 is generated per request.\n */\n requestIdHeader?: string;\n /**\n * Override `Date` for deterministic tests.\n */\n now?: () => Date;\n /**\n * Hook to record/audit normalized errors before sending. Useful for\n * Sentry / Datadog / Pino. Throws are swallowed so a logging bug\n * never masks the real error response.\n */\n onError?: (envelope: PafiErrorEnvelope, raw: unknown) => void;\n}\n\n@Catch()\nexport class PafiHttpExceptionFilter implements ExceptionFilter {\n private readonly logger = new Logger(\"PafiHttpExceptionFilter\");\n private readonly opts: Required<\n Pick<PafiHttpExceptionFilterOptions, \"requestIdHeader\">\n > &\n PafiHttpExceptionFilterOptions;\n\n constructor(options: PafiHttpExceptionFilterOptions = {}) {\n this.opts = {\n requestIdHeader: options.requestIdHeader ?? \"x-request-id\",\n ...options,\n };\n }\n\n catch(exception: unknown, host: ArgumentsHost): void {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse<MinimalHttpResponse>();\n const request = ctx.getRequest<MinimalHttpRequest>();\n\n const headerValue = request?.headers?.[this.opts.requestIdHeader];\n const requestId =\n (Array.isArray(headerValue) ? headerValue[0] : headerValue) ??\n randomUUID();\n\n const normCtx: NormalizeContext = {\n path: request?.url ?? \"\",\n requestId,\n ...(this.opts.now ? { now: this.opts.now } : {}),\n };\n\n const { status, payload } = this.normalize(exception);\n const envelope = buildErrorEnvelope({ status, payload, ctx: normCtx });\n\n if (this.opts.onError) {\n try {\n this.opts.onError(envelope, exception);\n } catch (hookErr) {\n this.logger.warn(\n { err: hookErr instanceof Error ? hookErr.message : String(hookErr) },\n \"onError hook threw; continuing\",\n );\n }\n }\n\n if (status >= 500) {\n this.logger.error(\n {\n err:\n exception instanceof Error\n ? exception.message\n : String(exception),\n stack: exception instanceof Error ? exception.stack : undefined,\n name: exception instanceof Error ? exception.name : undefined,\n path: normCtx.path,\n requestId,\n },\n \"Unhandled error in PafiHttpExceptionFilter\",\n );\n }\n\n response.status(status).json(envelope);\n }\n\n private normalize(exception: unknown): {\n status: number;\n payload: PafiErrorPayload;\n } {\n if (exception instanceof PafiSdkError) {\n return {\n status: SDK_ERROR_HTTP_STATUS_CODE[exception.httpStatus],\n payload: payloadFromPafiSdkError(exception),\n };\n }\n\n if (exception instanceof HttpException) {\n return {\n status: exception.getStatus(),\n payload: payloadFromHttpException({\n statusCode: exception.getStatus(),\n responseBody: exception.getResponse(),\n exceptionName: exception.name,\n fallbackMessage: exception.message,\n }),\n };\n }\n\n if (exception instanceof Error) {\n // Duck-typing for HttpException instances that fail `instanceof`\n // when multiple `@nestjs/common` copies exist in the dep tree.\n const maybeStatus = (exception as { status?: unknown }).status;\n const maybeGetResponse = (\n exception as { getResponse?: () => unknown }\n ).getResponse;\n if (\n typeof maybeStatus === \"number\" &&\n typeof maybeGetResponse === \"function\"\n ) {\n return {\n status: maybeStatus,\n payload: payloadFromHttpException({\n statusCode: maybeStatus,\n responseBody: maybeGetResponse.call(exception),\n exceptionName: exception.name,\n fallbackMessage: exception.message,\n }),\n };\n }\n const maybeStatusOnly =\n typeof maybeStatus === \"number\"\n ? maybeStatus\n : HttpStatus.INTERNAL_SERVER_ERROR;\n return {\n status: maybeStatusOnly,\n payload: payloadFromGenericError(exception),\n };\n }\n\n return {\n status: HttpStatus.INTERNAL_SERVER_ERROR,\n payload: {\n type: \"server_error\",\n code: \"INTERNAL_SERVER_ERROR\",\n message: \"An unexpected error occurred\",\n safeToRetry: false,\n },\n };\n }\n}\n","/**\n * `PafiSdkError` + `SdkErrorHttpStatus` are exported from\n * `@pafi-dev/core/errors` so core-level errors (e.g. `OracleStaleError`)\n * can extend the same base. Issuer re-exports the canonical types here\n * for back-compat — `instanceof PafiSdkError` from EITHER package\n * catches errors thrown from EITHER package.\n */\nexport {\n PafiSdkError,\n SDK_ERROR_HTTP_STATUS_CODE,\n defaultErrorTypeForStatus,\n type SdkErrorHttpStatus,\n type PafiErrorType,\n} from \"@pafi-dev/core\";\nimport { PafiSdkError } from \"@pafi-dev/core\";\n\n/**\n * `ValidationError` lives in `@pafi-dev/core` so core/trading helpers\n * throw the same typed class. Re-exported here for back-compat.\n */\nexport { ValidationError } from \"@pafi-dev/core\";\n\n/**\n * Issuer wired the SDK without a dependency the requested endpoint\n * needs (e.g. `/gas-fee` called but `feeManager` not configured;\n * `/pools` called but `poolsProvider` not configured). 503 because\n * the endpoint genuinely can't serve the request — caller's payload\n * is fine, the issuer's deployment is incomplete.\n */\nexport class ConfigurationError extends PafiSdkError {\n readonly httpStatus = \"service_unavailable\" as const;\n readonly code: string;\n readonly details?: Record<string, unknown>;\n\n constructor(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n ) {\n super(message);\n this.code = code;\n this.details = details;\n }\n}\n","import {\n PafiSdkError,\n SDK_ERROR_HTTP_STATUS_CODE,\n defaultErrorTypeForStatus,\n type PafiErrorType,\n type SdkErrorHttpStatus,\n} from \"../errors\";\n\n/**\n * Normalized HTTP status the issuer controller should surface for a\n * given SDK error. Mirrors `SdkErrorHttpStatus` on `PafiSdkError`.\n */\nexport type SdkErrorStatus = SdkErrorHttpStatus;\n\n/**\n * Structured body the issuer controller passes to its\n * framework-specific exception class. Stripe-style envelope:\n *\n * ```json\n * {\n * \"type\": \"business_logic_error\",\n * \"code\": \"REDEMPTION_POLICY_DENIED\",\n * \"message\": \"...\",\n * \"param\": null,\n * \"metadata\": { \"policyDenialCode\": \"PER_TX_MIN\" },\n * \"safeToRetry\": false\n * }\n * ```\n *\n * Carries enough fields for the global HTTP filter to emit the final\n * envelope without losing any SDK-side context.\n */\nexport interface SdkErrorBody {\n /** Stripe-style taxonomy slot — drives UI branching. */\n type: PafiErrorType;\n /** Machine-readable code, e.g. `\"REDEMPTION_POLICY_DENIED\"`. */\n code: string;\n /** Human-readable message. */\n message: string;\n /** Field name that triggered the error, when applicable. */\n param?: string;\n /** UI-facing structured context. */\n metadata?: Record<string, unknown>;\n /** Raw debug context. */\n details?: unknown;\n /** True when retry is safe (no side effects yet). */\n safeToRetry: boolean;\n}\n\n/**\n * Per-status exception factories. The issuer's controller wires one\n * factory per status to its preferred framework's exception class\n * (NestJS `UnprocessableEntityException`, Fastify `httpErrors.badData`,\n * etc). The factory must return an Error — `createSdkErrorMapper`\n * uses `throw factory(body)`.\n */\nexport interface SdkErrorMapperFactories {\n notFound: (body: SdkErrorBody) => Error;\n forbidden: (body: SdkErrorBody) => Error;\n unprocessable: (body: SdkErrorBody) => Error;\n serviceUnavailable: (body: SdkErrorBody) => Error;\n}\n\n/**\n * Build the Stripe-style body from any `PafiSdkError`. Exposed for\n * frameworks that don't fit the four-factory shape (e.g. a Hono error\n * handler that builds its own response object).\n */\nexport function buildSdkErrorBody(err: PafiSdkError): SdkErrorBody {\n const type =\n err.type ??\n defaultErrorTypeForStatus(SDK_ERROR_HTTP_STATUS_CODE[err.httpStatus]);\n const body: SdkErrorBody = {\n type,\n code: err.code,\n message: err.message,\n safeToRetry: err.safeToRetry,\n };\n if (err.param) body.param = err.param;\n if (err.metadata) body.metadata = err.metadata;\n if (err.details !== undefined) body.details = err.details;\n return body;\n}\n\n/**\n * Build a single error-mapping function that converts any `PafiSdkError`\n * into the issuer's framework-specific HTTP exception. Status, code,\n * `safeToRetry`, and `details` come straight off the error class —\n * the mapper is a dumb funnel, no per-error business logic.\n *\n * Any non-`PafiSdkError` is re-thrown unchanged so unexpected runtime\n * errors propagate to the framework's default 500 handler.\n *\n * Usage (NestJS):\n *\n * ```ts\n * const mapSdkError = createSdkErrorMapper({\n * notFound: (body) => new NotFoundException(body),\n * forbidden: (body) => new ForbiddenException(body),\n * unprocessable: (body) => new UnprocessableEntityException(body),\n * serviceUnavailable: (body) => new ServiceUnavailableException(body),\n * });\n *\n * try { ... } catch (err) { mapSdkError(err); }\n * ```\n *\n * Returns `never` so call sites in `try/catch` propagate the throw\n * without a redundant `throw` keyword.\n */\nexport function createSdkErrorMapper(\n factories: SdkErrorMapperFactories,\n): (err: unknown) => never {\n return (err: unknown): never => {\n if (!(err instanceof PafiSdkError)) {\n throw err;\n }\n const body = buildSdkErrorBody(err);\n switch (err.httpStatus) {\n case \"not_found\":\n throw factories.notFound(body);\n case \"forbidden\":\n throw factories.forbidden(body);\n case \"unprocessable\":\n throw factories.unprocessable(body);\n case \"service_unavailable\":\n throw factories.serviceUnavailable(body);\n }\n };\n}\n","/**\n * Stripe-style HTTP error envelope shared by every PAFI service and\n * issuer backend. The framework-agnostic `normalizeErrorToEnvelope`\n * helper produces this from any thrown value; framework-specific\n * filters (`@pafi-dev/issuer/nestjs`) call into it and write the\n * result to their response object.\n *\n * Wire format:\n *\n * ```json\n * {\n * \"success\": false,\n * \"statusCode\": 422,\n * \"error\": {\n * \"type\": \"business_logic_error\",\n * \"code\": \"REDEMPTION_POLICY_DENIED\",\n * \"message\": \"redemption denied: amount 1 below per-tx minimum\",\n * \"param\": null,\n * \"metadata\": { \"policyDenialCode\": \"PER_TX_MIN\" },\n * \"safeToRetry\": false,\n * \"details\": null\n * },\n * \"meta\": {\n * \"timestamp\": \"2026-05-07T...\",\n * \"requestId\": \"...\",\n * \"path\": \"/pt/redeem\"\n * }\n * }\n * ```\n */\n\nimport {\n PafiSdkError,\n SDK_ERROR_HTTP_STATUS_CODE,\n defaultErrorTypeForStatus,\n type PafiErrorType,\n} from \"../errors\";\nimport { buildSdkErrorBody, type SdkErrorBody } from \"../api/errorMapper\";\n\n/** Inner `error` block of the envelope. */\nexport interface PafiErrorPayload {\n type: PafiErrorType;\n code: string;\n message: string;\n param?: string;\n metadata?: Record<string, unknown>;\n details?: unknown;\n safeToRetry: boolean;\n}\n\n/** Outer envelope returned for any non-2xx response. */\nexport interface PafiErrorEnvelope {\n success: false;\n statusCode: number;\n error: PafiErrorPayload;\n meta: {\n timestamp: string;\n requestId: string;\n path: string;\n };\n}\n\n/** Per-call request context the filter must collect from the host framework. */\nexport interface NormalizeContext {\n /** `req.url` or equivalent. */\n path: string;\n /** Resolved request id (header or generated). */\n requestId: string;\n /** Optional `now()` injection for deterministic tests. */\n now?: () => Date;\n}\n\n/**\n * Generic error duck-type. The filter passes a small descriptor for\n * any framework exception so the normalizer doesn't depend on\n * `@nestjs/common` or any specific HTTP library.\n */\nexport interface GenericHttpExceptionDescriptor {\n /** HTTP status code carried by the exception. */\n statusCode: number;\n /**\n * The body the framework would have serialized. For NestJS this is\n * `exception.getResponse()`. May be a string or a record with\n * `code`/`error`/`message`/`details`/`safeToRetry`/`type`/etc.\n */\n responseBody: unknown;\n /** Exception class name, used as a last-resort `code` fallback. */\n exceptionName: string;\n /** Original `error.message`, used as a last-resort `message` fallback. */\n fallbackMessage: string;\n}\n\n/** True when `value` looks like a NestJS `BadRequestException` from `ValidationPipe`. */\nfunction isValidationPipeBody(\n body: Record<string, unknown>,\n): body is { message: string[]; error?: string; statusCode?: number } {\n return (\n Array.isArray(body[\"message\"]) &&\n typeof body[\"error\"] === \"string\" &&\n body[\"error\"] === \"Bad Request\"\n );\n}\n\n/** Pull `param` out of a `class-validator` message like `\"amount must be a number string\"`. */\nfunction extractParamFromValidatorMessage(message: string): string | undefined {\n const idx = message.indexOf(\" \");\n if (idx <= 0) return undefined;\n const candidate = message.slice(0, idx);\n return /^[A-Za-z_][\\w.]*$/.test(candidate) ? candidate : undefined;\n}\n\nfunction normalizeValidationPipeBody(\n body: { message: string[]; statusCode?: number },\n): PafiErrorPayload {\n const fields: Record<string, string[]> = {};\n for (const msg of body.message) {\n const param = extractParamFromValidatorMessage(msg);\n const key = param ?? \"_\";\n (fields[key] ??= []).push(msg);\n }\n const fieldKeys = Object.keys(fields).filter((k) => k !== \"_\");\n const param = fieldKeys.length === 1 ? fieldKeys[0] : undefined;\n\n const payload: PafiErrorPayload = {\n type: \"validation_error\",\n code: \"VALIDATION_FAILED\",\n message: body.message.join(\"; \"),\n safeToRetry: false,\n metadata: { fieldErrors: fields },\n };\n if (param) payload.param = param;\n return payload;\n}\n\n/**\n * Pull a Stripe-style payload out of a structured exception body. The\n * filter has already determined this is an `HttpException` (or\n * duck-typed equivalent). Order:\n *\n * 1. SDK-shaped body (has `type` + `code`) — pass through verbatim.\n * 2. `ValidationPipe` body (`message: string[]`, `error: \"Bad Request\"`)\n * — collapse into `validation_error` with `metadata.fieldErrors`.\n * 3. Plain object with `code` or `error` — best-effort extract.\n * 4. String body — just a message.\n */\nfunction normalizeHttpExceptionBody(\n desc: GenericHttpExceptionDescriptor,\n): PafiErrorPayload {\n const { statusCode, responseBody, exceptionName, fallbackMessage } = desc;\n const defaultType = defaultErrorTypeForStatus(statusCode);\n\n if (typeof responseBody === \"string\") {\n return {\n type: defaultType,\n code: exceptionName,\n message: responseBody,\n safeToRetry: false,\n };\n }\n\n if (responseBody && typeof responseBody === \"object\") {\n const body = responseBody as Record<string, unknown>;\n\n if (isValidationPipeBody(body)) {\n return normalizeValidationPipeBody(body);\n }\n\n const code =\n (typeof body[\"code\"] === \"string\" && body[\"code\"]) ||\n (typeof body[\"error\"] === \"string\" && body[\"error\"]) ||\n exceptionName;\n const message =\n (typeof body[\"message\"] === \"string\" && body[\"message\"]) ||\n (Array.isArray(body[\"message\"])\n ? (body[\"message\"] as string[]).join(\"; \")\n : \"\") ||\n fallbackMessage;\n const type =\n (typeof body[\"type\"] === \"string\" && (body[\"type\"] as PafiErrorType)) ||\n defaultType;\n const safeToRetry =\n typeof body[\"safeToRetry\"] === \"boolean\" ? body[\"safeToRetry\"] : false;\n\n const payload: PafiErrorPayload = {\n type,\n code,\n message,\n safeToRetry,\n };\n if (typeof body[\"param\"] === \"string\") payload.param = body[\"param\"];\n if (body[\"metadata\"] && typeof body[\"metadata\"] === \"object\") {\n payload.metadata = body[\"metadata\"] as Record<string, unknown>;\n }\n if (body[\"details\"] !== undefined) payload.details = body[\"details\"];\n return payload;\n }\n\n return {\n type: defaultType,\n code: exceptionName || \"INTERNAL_SERVER_ERROR\",\n message: fallbackMessage || \"An unexpected error occurred\",\n safeToRetry: false,\n };\n}\n\n/**\n * Convert a `PafiSdkError` directly to the inner `error` payload —\n * skipping any framework exception wrapper. Used by frameworks that\n * surface SDK errors without going through `createSdkErrorMapper`.\n */\nexport function payloadFromPafiSdkError(err: PafiSdkError): PafiErrorPayload {\n const body: SdkErrorBody = buildSdkErrorBody(err);\n const payload: PafiErrorPayload = {\n type: body.type,\n code: body.code,\n message: body.message,\n safeToRetry: body.safeToRetry,\n };\n if (body.param) payload.param = body.param;\n if (body.metadata) payload.metadata = body.metadata;\n if (body.details !== undefined) payload.details = body.details;\n return payload;\n}\n\n/** Strip SQL fragments from raw DB driver errors before exposing them. */\nfunction sanitizeDbErrorMessage(message: string): string {\n if (/^[A-Z_]+: /.test(message) && message.length < 256) return message;\n return \"Internal database error\";\n}\n\n/**\n * Build the full envelope for any thrown value. The caller resolves\n * `HttpException`-shaped exceptions and passes a descriptor; plain\n * `Error` instances and unknown throws are handled directly.\n */\nexport function buildErrorEnvelope(input: {\n status: number;\n payload: PafiErrorPayload;\n ctx: NormalizeContext;\n}): PafiErrorEnvelope {\n const now = (input.ctx.now ?? (() => new Date()))();\n return {\n success: false,\n statusCode: input.status,\n error: input.payload,\n meta: {\n timestamp: now.toISOString(),\n requestId: input.ctx.requestId,\n path: input.ctx.path,\n },\n };\n}\n\n/**\n * Normalize a known `HttpException`-shaped exception into a payload.\n * Framework filters supply the descriptor; the rest is shape-agnostic.\n */\nexport function payloadFromHttpException(\n desc: GenericHttpExceptionDescriptor,\n): PafiErrorPayload {\n return normalizeHttpExceptionBody(desc);\n}\n\n/**\n * Normalize a generic `Error` (not an HttpException) — TypeORM\n * `QueryFailedError`, viem revert errors, etc. Returns a redacted\n * 500-class payload with no message bleed-through unless the error\n * is recognizably benign.\n */\nexport function payloadFromGenericError(err: Error): PafiErrorPayload {\n const name = err.name || \"INTERNAL_SERVER_ERROR\";\n const isDbError = name === \"QueryFailedError\" || name === \"EntityNotFoundError\";\n return {\n type: \"server_error\",\n code: name,\n message: isDbError\n ? sanitizeDbErrorMessage(err.message)\n : err.message || \"An unexpected error occurred\",\n safeToRetry: false,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsBA,oBAOO;AACP,yBAA2B;;;ACvB3B,kBAMO;AACP,IAAAA,eAA6B;AAM7B,IAAAA,eAAgC;;;ACgDzB,SAAS,kBAAkB,KAAiC;AACjE,QAAM,OACJ,IAAI,YACJ,uCAA0B,uCAA2B,IAAI,UAAU,CAAC;AACtE,QAAM,OAAqB;AAAA,IACzB;AAAA,IACA,MAAM,IAAI;AAAA,IACV,SAAS,IAAI;AAAA,IACb,aAAa,IAAI;AAAA,EACnB;AACA,MAAI,IAAI,MAAO,MAAK,QAAQ,IAAI;AAChC,MAAI,IAAI,SAAU,MAAK,WAAW,IAAI;AACtC,MAAI,IAAI,YAAY,OAAW,MAAK,UAAU,IAAI;AAClD,SAAO;AACT;;;ACWA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J,UACA;AACF,UACE,OAAO,gBAAgB,YACvB,OAAO,qBAAqB,YAC5B;AACA,eAAO;AAAA,UACL,QAAQ;AAAA,UACR,SAAS,yBAAyB;AAAA,YAChC,YAAY;AAAA,YACZ,cAAc,iBAAiB,KAAK,SAAS;AAAA,YAC7C,eAAe,UAAU;AAAA,YACzB,iBAAiB,UAAU;AAAA,UAC7B,CAAC;AAAA,QACH;AAAA,MACF;AACA,YAAM,kBACJ,OAAO,gBAAgB,WACnB,cACA,yBAAW;AACjB,aAAO;AAAA,QACL,QAAQ;AAAA,QACR,SAAS,wBAAwB,SAAS;AAAA,MAC5C;AAAA,IACF;AAEA,WAAO;AAAA,MACL,QAAQ,yBAAW;AAAA,MACnB,SAAS;AAAA,QACP,MAAM;AAAA,QACN,MAAM;AAAA,QACN,SAAS;AAAA,QACT,aAAa;AAAA,MACf;AAAA,IACF;AAAA,EACF;AACF;AA/HO;AAAM,0BAAN,uDADP,qCACa;AAAN,4BAAM;","names":["import_core","param"]}
@@ -0,0 +1,54 @@
1
+ import { ExceptionFilter, ArgumentsHost } from '@nestjs/common';
2
+ import { PafiErrorEnvelope } from '../http/index.cjs';
3
+ import '@pafi-dev/core';
4
+
5
+ /**
6
+ * NestJS global exception filter that emits the PAFI Stripe-style
7
+ * envelope (see `@pafi-dev/issuer/http`).
8
+ *
9
+ * Wire it once in your bootstrap:
10
+ *
11
+ * ```ts
12
+ * import { PafiHttpExceptionFilter } from "@pafi-dev/issuer/nestjs";
13
+ *
14
+ * app.useGlobalFilters(new PafiHttpExceptionFilter());
15
+ * ```
16
+ *
17
+ * Catches every thrown value:
18
+ * - `PafiSdkError` (and subclasses) → typed envelope from `httpStatus`/
19
+ * `code`/`type`/`safeToRetry`/`param`/`metadata`.
20
+ * - `HttpException` (NestJS) → respected status; SDK-shaped body is
21
+ * passed through, plain bodies + ValidationPipe arrays normalized.
22
+ * - any other `Error` → `server_error` 500 with sanitized message.
23
+ *
24
+ * `@nestjs/common` is an optional peer dependency — only required when
25
+ * importing this sub-export.
26
+ */
27
+
28
+ /** Customization knobs. None required — sensible defaults baked in. */
29
+ interface PafiHttpExceptionFilterOptions {
30
+ /**
31
+ * Header to read for the request id, lowercase. Default `"x-request-id"`.
32
+ * If absent, a UUIDv4 is generated per request.
33
+ */
34
+ requestIdHeader?: string;
35
+ /**
36
+ * Override `Date` for deterministic tests.
37
+ */
38
+ now?: () => Date;
39
+ /**
40
+ * Hook to record/audit normalized errors before sending. Useful for
41
+ * Sentry / Datadog / Pino. Throws are swallowed so a logging bug
42
+ * never masks the real error response.
43
+ */
44
+ onError?: (envelope: PafiErrorEnvelope, raw: unknown) => void;
45
+ }
46
+ declare class PafiHttpExceptionFilter implements ExceptionFilter {
47
+ private readonly logger;
48
+ private readonly opts;
49
+ constructor(options?: PafiHttpExceptionFilterOptions);
50
+ catch(exception: unknown, host: ArgumentsHost): void;
51
+ private normalize;
52
+ }
53
+
54
+ export { PafiHttpExceptionFilter, type PafiHttpExceptionFilterOptions };
@@ -0,0 +1,54 @@
1
+ import { ExceptionFilter, ArgumentsHost } from '@nestjs/common';
2
+ import { PafiErrorEnvelope } from '../http/index.js';
3
+ import '@pafi-dev/core';
4
+
5
+ /**
6
+ * NestJS global exception filter that emits the PAFI Stripe-style
7
+ * envelope (see `@pafi-dev/issuer/http`).
8
+ *
9
+ * Wire it once in your bootstrap:
10
+ *
11
+ * ```ts
12
+ * import { PafiHttpExceptionFilter } from "@pafi-dev/issuer/nestjs";
13
+ *
14
+ * app.useGlobalFilters(new PafiHttpExceptionFilter());
15
+ * ```
16
+ *
17
+ * Catches every thrown value:
18
+ * - `PafiSdkError` (and subclasses) → typed envelope from `httpStatus`/
19
+ * `code`/`type`/`safeToRetry`/`param`/`metadata`.
20
+ * - `HttpException` (NestJS) → respected status; SDK-shaped body is
21
+ * passed through, plain bodies + ValidationPipe arrays normalized.
22
+ * - any other `Error` → `server_error` 500 with sanitized message.
23
+ *
24
+ * `@nestjs/common` is an optional peer dependency — only required when
25
+ * importing this sub-export.
26
+ */
27
+
28
+ /** Customization knobs. None required — sensible defaults baked in. */
29
+ interface PafiHttpExceptionFilterOptions {
30
+ /**
31
+ * Header to read for the request id, lowercase. Default `"x-request-id"`.
32
+ * If absent, a UUIDv4 is generated per request.
33
+ */
34
+ requestIdHeader?: string;
35
+ /**
36
+ * Override `Date` for deterministic tests.
37
+ */
38
+ now?: () => Date;
39
+ /**
40
+ * Hook to record/audit normalized errors before sending. Useful for
41
+ * Sentry / Datadog / Pino. Throws are swallowed so a logging bug
42
+ * never masks the real error response.
43
+ */
44
+ onError?: (envelope: PafiErrorEnvelope, raw: unknown) => void;
45
+ }
46
+ declare class PafiHttpExceptionFilter implements ExceptionFilter {
47
+ private readonly logger;
48
+ private readonly opts;
49
+ constructor(options?: PafiHttpExceptionFilterOptions);
50
+ catch(exception: unknown, host: ArgumentsHost): void;
51
+ private normalize;
52
+ }
53
+
54
+ export { PafiHttpExceptionFilter, type PafiHttpExceptionFilterOptions };
@@ -0,0 +1,124 @@
1
+ import {
2
+ PafiSdkError,
3
+ SDK_ERROR_HTTP_STATUS_CODE,
4
+ __decorateElement,
5
+ __decoratorStart,
6
+ __runInitializers,
7
+ buildErrorEnvelope,
8
+ payloadFromGenericError,
9
+ payloadFromHttpException,
10
+ payloadFromPafiSdkError
11
+ } from "../chunk-U3WMORJG.js";
12
+
13
+ // src/nestjs/httpExceptionFilter.ts
14
+ import {
15
+ Catch,
16
+ HttpException,
17
+ HttpStatus,
18
+ Logger
19
+ } from "@nestjs/common";
20
+ import { randomUUID } from "crypto";
21
+ var _PafiHttpExceptionFilter_decorators, _init;
22
+ _PafiHttpExceptionFilter_decorators = [Catch()];
23
+ var PafiHttpExceptionFilter = class {
24
+ logger = new Logger("PafiHttpExceptionFilter");
25
+ opts;
26
+ constructor(options = {}) {
27
+ this.opts = {
28
+ requestIdHeader: options.requestIdHeader ?? "x-request-id",
29
+ ...options
30
+ };
31
+ }
32
+ catch(exception, host) {
33
+ const ctx = host.switchToHttp();
34
+ const response = ctx.getResponse();
35
+ const request = ctx.getRequest();
36
+ const headerValue = request?.headers?.[this.opts.requestIdHeader];
37
+ const requestId = (Array.isArray(headerValue) ? headerValue[0] : headerValue) ?? randomUUID();
38
+ const normCtx = {
39
+ path: request?.url ?? "",
40
+ requestId,
41
+ ...this.opts.now ? { now: this.opts.now } : {}
42
+ };
43
+ const { status, payload } = this.normalize(exception);
44
+ const envelope = buildErrorEnvelope({ status, payload, ctx: normCtx });
45
+ if (this.opts.onError) {
46
+ try {
47
+ this.opts.onError(envelope, exception);
48
+ } catch (hookErr) {
49
+ this.logger.warn(
50
+ { err: hookErr instanceof Error ? hookErr.message : String(hookErr) },
51
+ "onError hook threw; continuing"
52
+ );
53
+ }
54
+ }
55
+ if (status >= 500) {
56
+ this.logger.error(
57
+ {
58
+ err: exception instanceof Error ? exception.message : String(exception),
59
+ stack: exception instanceof Error ? exception.stack : void 0,
60
+ name: exception instanceof Error ? exception.name : void 0,
61
+ path: normCtx.path,
62
+ requestId
63
+ },
64
+ "Unhandled error in PafiHttpExceptionFilter"
65
+ );
66
+ }
67
+ response.status(status).json(envelope);
68
+ }
69
+ normalize(exception) {
70
+ if (exception instanceof PafiSdkError) {
71
+ return {
72
+ status: SDK_ERROR_HTTP_STATUS_CODE[exception.httpStatus],
73
+ payload: payloadFromPafiSdkError(exception)
74
+ };
75
+ }
76
+ if (exception instanceof HttpException) {
77
+ return {
78
+ status: exception.getStatus(),
79
+ payload: payloadFromHttpException({
80
+ statusCode: exception.getStatus(),
81
+ responseBody: exception.getResponse(),
82
+ exceptionName: exception.name,
83
+ fallbackMessage: exception.message
84
+ })
85
+ };
86
+ }
87
+ if (exception instanceof Error) {
88
+ const maybeStatus = exception.status;
89
+ const maybeGetResponse = exception.getResponse;
90
+ if (typeof maybeStatus === "number" && typeof maybeGetResponse === "function") {
91
+ return {
92
+ status: maybeStatus,
93
+ payload: payloadFromHttpException({
94
+ statusCode: maybeStatus,
95
+ responseBody: maybeGetResponse.call(exception),
96
+ exceptionName: exception.name,
97
+ fallbackMessage: exception.message
98
+ })
99
+ };
100
+ }
101
+ const maybeStatusOnly = typeof maybeStatus === "number" ? maybeStatus : HttpStatus.INTERNAL_SERVER_ERROR;
102
+ return {
103
+ status: maybeStatusOnly,
104
+ payload: payloadFromGenericError(exception)
105
+ };
106
+ }
107
+ return {
108
+ status: HttpStatus.INTERNAL_SERVER_ERROR,
109
+ payload: {
110
+ type: "server_error",
111
+ code: "INTERNAL_SERVER_ERROR",
112
+ message: "An unexpected error occurred",
113
+ safeToRetry: false
114
+ }
115
+ };
116
+ }
117
+ };
118
+ _init = __decoratorStart(null);
119
+ PafiHttpExceptionFilter = __decorateElement(_init, 0, "PafiHttpExceptionFilter", _PafiHttpExceptionFilter_decorators, PafiHttpExceptionFilter);
120
+ __runInitializers(_init, 1, PafiHttpExceptionFilter);
121
+ export {
122
+ PafiHttpExceptionFilter
123
+ };
124
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/nestjs/httpExceptionFilter.ts"],"sourcesContent":["/**\n * NestJS global exception filter that emits the PAFI Stripe-style\n * envelope (see `@pafi-dev/issuer/http`).\n *\n * Wire it once in your bootstrap:\n *\n * ```ts\n * import { PafiHttpExceptionFilter } from \"@pafi-dev/issuer/nestjs\";\n *\n * app.useGlobalFilters(new PafiHttpExceptionFilter());\n * ```\n *\n * Catches every thrown value:\n * - `PafiSdkError` (and subclasses) → typed envelope from `httpStatus`/\n * `code`/`type`/`safeToRetry`/`param`/`metadata`.\n * - `HttpException` (NestJS) → respected status; SDK-shaped body is\n * passed through, plain bodies + ValidationPipe arrays normalized.\n * - any other `Error` → `server_error` 500 with sanitized message.\n *\n * `@nestjs/common` is an optional peer dependency — only required when\n * importing this sub-export.\n */\nimport {\n ArgumentsHost,\n Catch,\n ExceptionFilter,\n HttpException,\n HttpStatus,\n Logger,\n} from \"@nestjs/common\";\nimport { randomUUID } from \"node:crypto\";\n\nimport { PafiSdkError, SDK_ERROR_HTTP_STATUS_CODE } from \"../errors\";\nimport {\n buildErrorEnvelope,\n payloadFromGenericError,\n payloadFromHttpException,\n payloadFromPafiSdkError,\n type NormalizeContext,\n type PafiErrorEnvelope,\n type PafiErrorPayload,\n} from \"../http/errorEnvelope\";\n\ninterface MinimalHttpRequest {\n url?: string;\n headers?: Record<string, string | string[] | undefined>;\n}\ninterface MinimalHttpResponse {\n status(code: number): MinimalHttpResponse;\n json(body: unknown): unknown;\n}\n\n/** Customization knobs. None required — sensible defaults baked in. */\nexport interface PafiHttpExceptionFilterOptions {\n /**\n * Header to read for the request id, lowercase. Default `\"x-request-id\"`.\n * If absent, a UUIDv4 is generated per request.\n */\n requestIdHeader?: string;\n /**\n * Override `Date` for deterministic tests.\n */\n now?: () => Date;\n /**\n * Hook to record/audit normalized errors before sending. Useful for\n * Sentry / Datadog / Pino. Throws are swallowed so a logging bug\n * never masks the real error response.\n */\n onError?: (envelope: PafiErrorEnvelope, raw: unknown) => void;\n}\n\n@Catch()\nexport class PafiHttpExceptionFilter implements ExceptionFilter {\n private readonly logger = new Logger(\"PafiHttpExceptionFilter\");\n private readonly opts: Required<\n Pick<PafiHttpExceptionFilterOptions, \"requestIdHeader\">\n > &\n PafiHttpExceptionFilterOptions;\n\n constructor(options: PafiHttpExceptionFilterOptions = {}) {\n this.opts = {\n requestIdHeader: options.requestIdHeader ?? \"x-request-id\",\n ...options,\n };\n }\n\n catch(exception: unknown, host: ArgumentsHost): void {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse<MinimalHttpResponse>();\n const request = ctx.getRequest<MinimalHttpRequest>();\n\n const headerValue = request?.headers?.[this.opts.requestIdHeader];\n const requestId =\n (Array.isArray(headerValue) ? headerValue[0] : headerValue) ??\n randomUUID();\n\n const normCtx: NormalizeContext = {\n path: request?.url ?? \"\",\n requestId,\n ...(this.opts.now ? { now: this.opts.now } : {}),\n };\n\n const { status, payload } = this.normalize(exception);\n const envelope = buildErrorEnvelope({ status, payload, ctx: normCtx });\n\n if (this.opts.onError) {\n try {\n this.opts.onError(envelope, exception);\n } catch (hookErr) {\n this.logger.warn(\n { err: hookErr instanceof Error ? hookErr.message : String(hookErr) },\n \"onError hook threw; continuing\",\n );\n }\n }\n\n if (status >= 500) {\n this.logger.error(\n {\n err:\n exception instanceof Error\n ? exception.message\n : String(exception),\n stack: exception instanceof Error ? exception.stack : undefined,\n name: exception instanceof Error ? exception.name : undefined,\n path: normCtx.path,\n requestId,\n },\n \"Unhandled error in PafiHttpExceptionFilter\",\n );\n }\n\n response.status(status).json(envelope);\n }\n\n private normalize(exception: unknown): {\n status: number;\n payload: PafiErrorPayload;\n } {\n if (exception instanceof PafiSdkError) {\n return {\n status: SDK_ERROR_HTTP_STATUS_CODE[exception.httpStatus],\n payload: payloadFromPafiSdkError(exception),\n };\n }\n\n if (exception instanceof HttpException) {\n return {\n status: exception.getStatus(),\n payload: payloadFromHttpException({\n statusCode: exception.getStatus(),\n responseBody: exception.getResponse(),\n exceptionName: exception.name,\n fallbackMessage: exception.message,\n }),\n };\n }\n\n if (exception instanceof Error) {\n // Duck-typing for HttpException instances that fail `instanceof`\n // when multiple `@nestjs/common` copies exist in the dep tree.\n const maybeStatus = (exception as { status?: unknown }).status;\n const maybeGetResponse = (\n exception as { getResponse?: () => unknown }\n ).getResponse;\n if (\n typeof maybeStatus === \"number\" &&\n typeof maybeGetResponse === \"function\"\n ) {\n return {\n status: maybeStatus,\n payload: payloadFromHttpException({\n statusCode: maybeStatus,\n responseBody: maybeGetResponse.call(exception),\n exceptionName: exception.name,\n fallbackMessage: exception.message,\n }),\n };\n }\n const maybeStatusOnly =\n typeof maybeStatus === \"number\"\n ? maybeStatus\n : HttpStatus.INTERNAL_SERVER_ERROR;\n return {\n status: maybeStatusOnly,\n payload: payloadFromGenericError(exception),\n };\n }\n\n return {\n status: HttpStatus.INTERNAL_SERVER_ERROR,\n payload: {\n type: \"server_error\",\n code: \"INTERNAL_SERVER_ERROR\",\n message: \"An unexp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