@orpc/pino 2.0.0-beta.47 → 2.0.0-beta.49

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/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  <img alt="codecov" src="https://codecov.io/gh/middleapi/orpc/branch/main/graph/badge.svg">
6
6
  </a>
7
7
  <a href="https://www.npmjs.com/package/@orpc/pino">
8
- <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fpino?logo=npm" />
8
+ <img alt="monthly downloads" src="https://img.shields.io/npm/dm/%40orpc%2Fpino?logo=npm" />
9
9
  </a>
10
10
  <a href="https://app.codspeed.io/middleapi/orpc?utm_source=badge">
11
11
  <img alt="CodSpeed" src="https://img.shields.io/endpoint?url=https://codspeed.io/badge.json" />
@@ -41,10 +41,11 @@ export const router = {
41
41
  Then call them from a client that knows every input and output, without generating anything:
42
42
 
43
43
  ```ts
44
- import type { RouterClient } from '@orpc/server'
45
- import type { router } from './router'
46
44
  import { createORPCClient } from '@orpc/client'
47
45
  import { RPCLink } from '@orpc/client/fetch'
46
+ import type { RouterClient } from '@orpc/server'
47
+
48
+ import type { router } from './router'
48
49
 
49
50
  const link = new RPCLink({ origin: 'http://localhost:3000', url: '/rpc' })
50
51
  const client: RouterClient<typeof router> = createORPCClient(link)
@@ -191,15 +192,14 @@ Like what we build over at [middleapi](https://github.com/middleapi)? You can he
191
192
  <td align="center"><a href="https://kellychan.im/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Kelly Peilin Chan"><img src="https://avatars.githubusercontent.com/u/520852?u=6b0f7105f694e7b5cacf410a3f04c7044b469dc8&amp;v=4" width="139" alt="Kelly Peilin Chan"/><br />Kelly Peilin Chan</a></td>
192
193
  <td align="center"><a href="https://guyariely.com/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Guy Ariely"><img src="https://avatars.githubusercontent.com/u/42813496?u=edb6b7f563bf28e160a290832e7da57c0506f8ca&amp;v=4" width="139" alt="Guy Ariely"/><br />Guy Ariely</a></td>
193
194
  <td align="center"><a href="https://paulsenon.com/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="PaulSenon"><img src="https://avatars.githubusercontent.com/u/19531087?u=6385741eb91d200b8c513ec6045482e301767ca6&amp;v=4" width="139" alt="PaulSenon"/><br />PaulSenon</a></td>
194
- <td align="center"><a href="https://nakasyou.how/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Shotaro Nakamura"><img src="https://avatars.githubusercontent.com/u/79000684?u=f644df3f29f0e8677a90967115774564f1d9d6ab&amp;v=4" width="139" alt="Shotaro Nakamura"/><br />Shotaro Nakamura</a></td>
195
+ <td align="center"><a href="https://piscis.dev/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Alex"><img src="https://avatars.githubusercontent.com/u/326163?u=b245f368bd940cf51d08c0b6bf55f8257f359437&amp;v=4" width="139" alt="Alex"/><br />Alex</a></td>
195
196
  </tr>
196
197
  <tr>
197
- <td align="center"><a href="https://piscis.dev/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Alex"><img src="https://avatars.githubusercontent.com/u/326163?u=b245f368bd940cf51d08c0b6bf55f8257f359437&amp;v=4" width="139" alt="Alex"/><br />Alex</a></td>
198
198
  <td align="center"><a href="https://opensource.gubanov.eu/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Andrey Gubanov"><img src="https://avatars.githubusercontent.com/u/1082083?u=c5f2daf7ebece498e85c83367bb37b4e10e2649d&amp;v=4" width="139" alt="Andrey Gubanov"/><br />Andrey Gubanov</a></td>
199
199
  </tr>
200
200
  </table>
201
201
 
202
- With thanks to [39 past sponsors](https://orpc.dev/sponsors#past-sponsors) who helped get oRPC here.
202
+ With thanks to [40 past sponsors](https://orpc.dev/sponsors#past-sponsors) who helped get oRPC here.
203
203
 
204
204
  ## Open Source Programs
205
205
 
@@ -209,7 +209,6 @@ With thanks to [39 past sponsors](https://orpc.dev/sponsors#past-sponsors) who h
209
209
  <tr>
210
210
  <td align="center"><a href="https://claude.com/contact-sales/claude-for-oss" target="_blank" rel="noopener" title="Claude for Open Source"><img src="https://cdn.simpleicons.org/claude" width="64" alt="Claude"/><br />Claude</a></td>
211
211
  <td align="center"><a href="https://pullfrog.com/for-oss" target="_blank" rel="noopener" title="Pullfrog for OSS"><img src="https://avatars.githubusercontent.com/in/1768019?s=128&amp;v=4" width="64" alt="Pullfrog"/><br />Pullfrog</a></td>
212
- <td align="center"><a href="https://macroscope.com/open-source" target="_blank" rel="noopener" title="Macroscope for Open Source"><img src="https://avatars.githubusercontent.com/in/900172?s=128&amp;v=4" width="64" alt="Macroscope"/><br />Macroscope</a></td>
213
212
  </tr>
214
213
  </table>
215
214
 
@@ -0,0 +1,22 @@
1
+ import type { Logger } from 'pino';
2
+ /**
3
+ * Context symbol under which the Pino logger is stored. Use it to provide a
4
+ * custom logger instance per request, e.g. when integrating with pino-http.
5
+ *
6
+ * @see {@link https://orpc.dev/docs/integrations/pino#providing-custom-logger-per-request | Pino Integration - Providing Custom Logger per Request}
7
+ */
8
+ export declare const LOGGER_CONTEXT_SYMBOL: unique symbol;
9
+ /**
10
+ * Context shape that carries the Pino logger injected by `PinoHandlerPlugin`.
11
+ *
12
+ * @see {@link https://orpc.dev/docs/integrations/pino#using-the-logger-in-your-code | Pino Integration - Using the Logger in Your Code}
13
+ */
14
+ export interface LoggerContext {
15
+ [LOGGER_CONTEXT_SYMBOL]?: Logger | undefined;
16
+ }
17
+ /**
18
+ * Retrieves the Pino logger from the oRPC context, if available.
19
+ *
20
+ * @see {@link https://orpc.dev/docs/integrations/pino#using-the-logger-in-your-code | Pino Integration - Using the Logger in Your Code}
21
+ */
22
+ export declare function getLogger(context: LoggerContext): Logger | undefined;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Context symbol under which the Pino logger is stored. Use it to provide a
3
+ * custom logger instance per request, e.g. when integrating with pino-http.
4
+ *
5
+ * @see {@link https://orpc.dev/docs/integrations/pino#providing-custom-logger-per-request | Pino Integration - Providing Custom Logger per Request}
6
+ */
7
+ export const LOGGER_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for('ORPC_PINO_LOGGER_CONTEXT');
8
+ /**
9
+ * Retrieves the Pino logger from the oRPC context, if available.
10
+ *
11
+ * @see {@link https://orpc.dev/docs/integrations/pino#using-the-logger-in-your-code | Pino Integration - Using the Logger in Your Code}
12
+ */
13
+ export function getLogger(context) {
14
+ return context[LOGGER_CONTEXT_SYMBOL];
15
+ }
@@ -1,30 +1,8 @@
1
- import pino, { Logger } from 'pino';
2
- import { Context } from '@orpc/server';
3
- import { StandardHandlerPlugin, StandardHandlerRoutingInterceptorOptions, StandardHandlerOptions } from '@orpc/server/standard';
4
-
5
- /**
6
- * Context symbol under which the Pino logger is stored. Use it to provide a
7
- * custom logger instance per request, e.g. when integrating with pino-http.
8
- *
9
- * @see {@link https://orpc.dev/docs/integrations/pino#providing-custom-logger-per-request | Pino Integration - Providing Custom Logger per Request}
10
- */
11
- declare const LOGGER_CONTEXT_SYMBOL: unique symbol;
12
- /**
13
- * Context shape that carries the Pino logger injected by `PinoHandlerPlugin`.
14
- *
15
- * @see {@link https://orpc.dev/docs/integrations/pino#using-the-logger-in-your-code | Pino Integration - Using the Logger in Your Code}
16
- */
17
- interface LoggerContext {
18
- [LOGGER_CONTEXT_SYMBOL]?: Logger | undefined;
19
- }
20
- /**
21
- * Retrieves the Pino logger from the oRPC context, if available.
22
- *
23
- * @see {@link https://orpc.dev/docs/integrations/pino#using-the-logger-in-your-code | Pino Integration - Using the Logger in Your Code}
24
- */
25
- declare function getLogger(context: LoggerContext): Logger | undefined;
26
-
27
- interface PinoHandlerPluginOptions<T extends Context> {
1
+ import type { Context } from '@orpc/server';
2
+ import type { StandardHandlerOptions, StandardHandlerPlugin, StandardHandlerRoutingInterceptorOptions } from '@orpc/server/standard';
3
+ import type { Logger } from 'pino';
4
+ import pino from 'pino';
5
+ export interface PinoHandlerPluginOptions<T extends Context> {
28
6
  /**
29
7
  * Logger instance to use for logging.
30
8
  *
@@ -66,7 +44,7 @@ interface PinoHandlerPluginOptions<T extends Context> {
66
44
  *
67
45
  * @see {@link https://orpc.dev/docs/integrations/pino | Pino Integration}
68
46
  */
69
- declare class PinoHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
47
+ export declare class PinoHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
70
48
  name: string;
71
49
  /**
72
50
  * - Logging interceptors should run after tracing interceptors
@@ -83,6 +61,3 @@ declare class PinoHandlerPlugin<T extends Context> implements StandardHandlerPlu
83
61
  constructor(options?: PinoHandlerPluginOptions<T>);
84
62
  init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
85
63
  }
86
-
87
- export { LOGGER_CONTEXT_SYMBOL, PinoHandlerPlugin, getLogger };
88
- export type { LoggerContext, PinoHandlerPluginOptions };
@@ -0,0 +1,167 @@
1
+ import { ORPCError, wrapAsyncIteratorPreservingEventMeta } from '@orpc/client';
2
+ import { isAbortError, isAsyncIteratorObject, ORPC_NAME, override, toArray, wrapReadableStream, } from '@orpc/shared';
3
+ import { flattenStandardHeader } from '@standard-server/core';
4
+ import pino from 'pino';
5
+ import { getLogger, LOGGER_CONTEXT_SYMBOL } from './context.js';
6
+ /**
7
+ * Instruments an oRPC handler with Pino structured logging, request tracking,
8
+ * and error monitoring.
9
+ *
10
+ * @see {@link https://orpc.dev/docs/integrations/pino | Pino Integration}
11
+ */
12
+ export class PinoHandlerPlugin {
13
+ name = '~pino';
14
+ /**
15
+ * - Logging interceptors should run after tracing interceptors
16
+ * so they execute within the active request span.
17
+ * - Logging interceptors should run after batch interceptors
18
+ * so they log each individual request instead of the batch request.
19
+ */
20
+ before = ['~tracing', '~batch', '~hibernation'];
21
+ logger;
22
+ generateRequestId;
23
+ logLifecycle;
24
+ logAbort;
25
+ procedureErrorLevel;
26
+ constructor(options = {}) {
27
+ this.logger = options.logger ?? pino();
28
+ this.generateRequestId =
29
+ options.generateRequestId ??
30
+ (({ request }) => flattenStandardHeader(request.headers['x-request-id']) ?? crypto.randomUUID());
31
+ this.logLifecycle = options.logLifecycle ?? false;
32
+ this.logAbort = options.logAbort ?? false;
33
+ this.procedureErrorLevel = options.procedureErrorLevel ?? ((_, level) => level);
34
+ }
35
+ init(options) {
36
+ const routingInterceptor = async ({ next, ...interceptorOptions }) => {
37
+ const startMs = Date.now();
38
+ const logger = (interceptorOptions.context[LOGGER_CONTEXT_SYMBOL] ?? this.logger).child({});
39
+ /**
40
+ * pino-http might have already set req info in bindings
41
+ */
42
+ if (!logger.bindings().req) {
43
+ logger.setBindings({
44
+ req: {
45
+ id: this.generateRequestId(interceptorOptions),
46
+ url: interceptorOptions.request.url,
47
+ method: interceptorOptions.request.method,
48
+ headers: {
49
+ 'content-type': interceptorOptions.request.headers['content-type'],
50
+ 'content-length': interceptorOptions.request.headers['content-length'],
51
+ 'content-disposition': interceptorOptions.request.headers['content-disposition'],
52
+ 'standard-server': interceptorOptions.request.headers['standard-server'],
53
+ },
54
+ },
55
+ });
56
+ }
57
+ try {
58
+ if (this.logLifecycle) {
59
+ logger?.info('request received');
60
+ }
61
+ const result = await next({
62
+ ...interceptorOptions,
63
+ context: {
64
+ ...interceptorOptions.context,
65
+ [LOGGER_CONTEXT_SYMBOL]: logger,
66
+ },
67
+ });
68
+ if (this.logLifecycle) {
69
+ if (result.matched) {
70
+ logger?.info({
71
+ msg: 'request handled',
72
+ res: {
73
+ status: result.response.status,
74
+ },
75
+ responseTime: Date.now() - startMs,
76
+ });
77
+ }
78
+ else {
79
+ logger?.info('no matching procedure found');
80
+ }
81
+ }
82
+ return result;
83
+ }
84
+ catch (error) {
85
+ /**
86
+ * Any error here is internal (interceptor/framework), not business logic.
87
+ * Indicates unexpected handler failure.
88
+ */
89
+ logger.error(error);
90
+ throw error;
91
+ }
92
+ };
93
+ const interceptor = async ({ next, context, path, request }) => {
94
+ const logger = getLogger(context);
95
+ logger?.setBindings({ rpc: { system: ORPC_NAME, method: path.join('.') } });
96
+ if (this.logAbort) {
97
+ const signal = request.signal;
98
+ if (signal?.aborted) {
99
+ logger?.info(`request was aborted before handling (${String(signal.reason)})`);
100
+ }
101
+ else {
102
+ signal?.addEventListener('abort', () => {
103
+ logger?.info(`request is aborted (${String(signal.reason)})`);
104
+ }, { once: true });
105
+ }
106
+ }
107
+ try {
108
+ return await next();
109
+ }
110
+ catch (error) {
111
+ logProcedureError(logger, error, this.procedureErrorLevel);
112
+ throw error;
113
+ }
114
+ };
115
+ const clientInterceptor = async ({ next, context, }) => {
116
+ const output = await next();
117
+ if (isAsyncIteratorObject(output)) {
118
+ /**
119
+ * @remarks
120
+ * **Warning**: Remember use `override` for AsyncIteratorObject to remain other special properties
121
+ */
122
+ return override(output, wrapAsyncIteratorPreservingEventMeta(output, {
123
+ onError: (error) => {
124
+ logProcedureError(getLogger(context), error, this.procedureErrorLevel);
125
+ },
126
+ }));
127
+ }
128
+ if (output instanceof ReadableStream) {
129
+ /**
130
+ * @remarks
131
+ * **Warning**: Remember use `override` for ReadableStream to remain other special properties
132
+ */
133
+ return override(output, wrapReadableStream(output, {
134
+ onError: (error) => {
135
+ logProcedureError(getLogger(context), error, this.procedureErrorLevel);
136
+ },
137
+ }));
138
+ }
139
+ return output;
140
+ };
141
+ return {
142
+ ...options,
143
+ routingInterceptors: [routingInterceptor, ...toArray(options.routingInterceptors)],
144
+ interceptors: [interceptor, ...toArray(options.interceptors)],
145
+ clientInterceptors: [clientInterceptor, ...toArray(options.clientInterceptors)],
146
+ };
147
+ }
148
+ }
149
+ function logProcedureError(logger, error, procedureErrorLevel) {
150
+ logger?.[procedureErrorLevel(error, defaultProcedureErrorLevel(error))](error);
151
+ }
152
+ function defaultProcedureErrorLevel(error) {
153
+ // An abort means the client withdrew the request, not that something failed,
154
+ // so record it as normal operation.
155
+ if (isAbortError(error)) {
156
+ return 'info';
157
+ }
158
+ // A thrown ORPCError is a deliberate business rejection delivered to the client,
159
+ // so keep it reviewable without treating it as a failure. INTERNAL_SERVER_ERROR
160
+ // is the exception: it signals a server-side failure (oRPC itself throws it for
161
+ // failures like output validation), so it stays at error level along with
162
+ // anything unexpected.
163
+ if (error instanceof ORPCError && error.code !== 'INTERNAL_SERVER_ERROR') {
164
+ return 'warn';
165
+ }
166
+ return 'error';
167
+ }
package/dist/index.d.ts CHANGED
@@ -1,88 +1,2 @@
1
- import pino, { Logger } from 'pino';
2
- import { Context } from '@orpc/server';
3
- import { StandardHandlerPlugin, StandardHandlerRoutingInterceptorOptions, StandardHandlerOptions } from '@orpc/server/standard';
4
-
5
- /**
6
- * Context symbol under which the Pino logger is stored. Use it to provide a
7
- * custom logger instance per request, e.g. when integrating with pino-http.
8
- *
9
- * @see {@link https://orpc.dev/docs/integrations/pino#providing-custom-logger-per-request | Pino Integration - Providing Custom Logger per Request}
10
- */
11
- declare const LOGGER_CONTEXT_SYMBOL: unique symbol;
12
- /**
13
- * Context shape that carries the Pino logger injected by `PinoHandlerPlugin`.
14
- *
15
- * @see {@link https://orpc.dev/docs/integrations/pino#using-the-logger-in-your-code | Pino Integration - Using the Logger in Your Code}
16
- */
17
- interface LoggerContext {
18
- [LOGGER_CONTEXT_SYMBOL]?: Logger | undefined;
19
- }
20
- /**
21
- * Retrieves the Pino logger from the oRPC context, if available.
22
- *
23
- * @see {@link https://orpc.dev/docs/integrations/pino#using-the-logger-in-your-code | Pino Integration - Using the Logger in Your Code}
24
- */
25
- declare function getLogger(context: LoggerContext): Logger | undefined;
26
-
27
- interface PinoHandlerPluginOptions<T extends Context> {
28
- /**
29
- * Logger instance to use for logging.
30
- *
31
- * @default pino()
32
- */
33
- logger?: Logger | undefined;
34
- /**
35
- * Function to generate a unique ID for each request.
36
- *
37
- * @default ({ request }) => flattenStandardHeader(request.headers['x-request-id']) ?? crypto.randomUUID()
38
- */
39
- generateRequestId?: ((options: StandardHandlerRoutingInterceptorOptions<T>) => string) | undefined;
40
- /**
41
- * If true, this plugin will log information about request lifecycle,
42
- * including when a request is received, handled, or no matching procedure is found.
43
- *
44
- * @default false
45
- */
46
- logLifecycle?: boolean | undefined;
47
- /**
48
- * If true, this plugin will log when a request signal is aborted.
49
- *
50
- * @default false
51
- */
52
- logAbort?: boolean | undefined;
53
- /**
54
- * Customizes the log level for errors thrown from procedures;
55
- * internal handler failures are always logged at error level.
56
- * Receives the level applied by default; return it to keep the default behavior:
57
- * 'info' for abort errors, 'warn' for ORPCError except INTERNAL_SERVER_ERROR, 'error' otherwise.
58
- *
59
- * @default (error, level) => level
60
- */
61
- procedureErrorLevel?: ((error: unknown, level: pino.Level) => pino.Level) | undefined;
62
- }
63
- /**
64
- * Instruments an oRPC handler with Pino structured logging, request tracking,
65
- * and error monitoring.
66
- *
67
- * @see {@link https://orpc.dev/docs/integrations/pino | Pino Integration}
68
- */
69
- declare class PinoHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
70
- name: string;
71
- /**
72
- * - Logging interceptors should run after tracing interceptors
73
- * so they execute within the active request span.
74
- * - Logging interceptors should run after batch interceptors
75
- * so they log each individual request instead of the batch request.
76
- */
77
- before: string[];
78
- private readonly logger;
79
- private readonly generateRequestId;
80
- private readonly logLifecycle;
81
- private readonly logAbort;
82
- private readonly procedureErrorLevel;
83
- constructor(options?: PinoHandlerPluginOptions<T>);
84
- init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
85
- }
86
-
87
- export { LOGGER_CONTEXT_SYMBOL, PinoHandlerPlugin, getLogger };
88
- export type { LoggerContext, PinoHandlerPluginOptions };
1
+ export * from './context.ts';
2
+ export * from './handler-plugin.ts';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './context.js';
2
+ export * from './handler-plugin.js';
package/package.json CHANGED
@@ -1,52 +1,50 @@
1
1
  {
2
2
  "name": "@orpc/pino",
3
- "type": "module",
4
- "version": "2.0.0-beta.47",
3
+ "version": "2.0.0-beta.49",
5
4
  "description": "Pino integration for oRPC: structured logging for typesafe APIs",
6
- "license": "MIT",
7
- "funding": [
8
- "https://github.com/sponsors/dinwwwh",
9
- "https://opencollective.com/middleapi"
5
+ "keywords": [
6
+ "logger",
7
+ "logging",
8
+ "observability",
9
+ "orpc",
10
+ "pino",
11
+ "typescript"
10
12
  ],
11
13
  "homepage": "https://orpc.dev",
14
+ "license": "MIT",
12
15
  "repository": {
13
16
  "type": "git",
14
17
  "url": "git+https://github.com/middleapi/orpc.git",
15
18
  "directory": "packages/pino"
16
19
  },
17
- "keywords": [
18
- "orpc",
19
- "pino",
20
- "logging",
21
- "logger",
22
- "observability",
23
- "typescript"
20
+ "funding": [
21
+ "https://github.com/sponsors/dinwwwh",
22
+ "https://opencollective.com/middleapi"
24
23
  ],
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "type": "module",
25
28
  "sideEffects": false,
26
29
  "exports": {
27
30
  "./package.json": "./package.json",
28
31
  ".": {
29
- "types": "./dist/index.d.mts",
30
- "import": "./dist/index.mjs",
31
- "default": "./dist/index.mjs"
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js",
34
+ "default": "./dist/index.js"
32
35
  }
33
36
  },
34
- "files": [
35
- "dist"
36
- ],
37
- "peerDependencies": {
38
- "pino": ">=10.1.0"
39
- },
40
37
  "dependencies": {
41
- "@orpc/client": "2.0.0-beta.47",
42
- "@orpc/server": "2.0.0-beta.47",
43
- "@orpc/shared": "2.0.0-beta.47",
44
- "@standard-server/core": "~0.13.0"
38
+ "@orpc/client": "2.0.0-beta.49",
39
+ "@orpc/server": "2.0.0-beta.49",
40
+ "@orpc/shared": "2.0.0-beta.49",
41
+ "@standard-server/core": "~0.15.0"
45
42
  },
46
43
  "devDependencies": {
47
44
  "pino": "^10.4.0"
48
45
  },
49
- "scripts": {
50
- "type:check": "tsc -b"
51
- }
46
+ "peerDependencies": {
47
+ "pino": ">=10.1.0"
48
+ },
49
+ "scripts": {}
52
50
  }
package/dist/index.mjs DELETED
@@ -1,149 +0,0 @@
1
- import { wrapAsyncIteratorPreservingEventMeta, ORPCError } from '@orpc/client';
2
- import { toArray, ORPC_NAME, isAsyncIteratorObject, override, wrapReadableStream, isAbortError } from '@orpc/shared';
3
- import { flattenStandardHeader } from '@standard-server/core';
4
- import pino from 'pino';
5
-
6
- const LOGGER_CONTEXT_SYMBOL = Symbol.for("ORPC_PINO_LOGGER_CONTEXT");
7
- function getLogger(context) {
8
- return context[LOGGER_CONTEXT_SYMBOL];
9
- }
10
-
11
- class PinoHandlerPlugin {
12
- name = "~pino";
13
- /**
14
- * - Logging interceptors should run after tracing interceptors
15
- * so they execute within the active request span.
16
- * - Logging interceptors should run after batch interceptors
17
- * so they log each individual request instead of the batch request.
18
- */
19
- before = ["~tracing", "~batch", "~hibernation"];
20
- logger;
21
- generateRequestId;
22
- logLifecycle;
23
- logAbort;
24
- procedureErrorLevel;
25
- constructor(options = {}) {
26
- this.logger = options.logger ?? pino();
27
- this.generateRequestId = options.generateRequestId ?? (({ request }) => flattenStandardHeader(request.headers["x-request-id"]) ?? crypto.randomUUID());
28
- this.logLifecycle = options.logLifecycle ?? false;
29
- this.logAbort = options.logAbort ?? false;
30
- this.procedureErrorLevel = options.procedureErrorLevel ?? ((_, level) => level);
31
- }
32
- init(options) {
33
- const routingInterceptor = async ({ next, ...interceptorOptions }) => {
34
- const startMs = Date.now();
35
- const logger = (interceptorOptions.context[LOGGER_CONTEXT_SYMBOL] ?? this.logger).child({});
36
- if (!logger.bindings().req) {
37
- logger.setBindings({
38
- req: {
39
- id: this.generateRequestId(interceptorOptions),
40
- url: interceptorOptions.request.url,
41
- method: interceptorOptions.request.method,
42
- headers: {
43
- "content-type": interceptorOptions.request.headers["content-type"],
44
- "content-length": interceptorOptions.request.headers["content-length"],
45
- "content-disposition": interceptorOptions.request.headers["content-disposition"],
46
- "standard-server": interceptorOptions.request.headers["standard-server"]
47
- }
48
- }
49
- });
50
- }
51
- try {
52
- if (this.logLifecycle) {
53
- logger?.info("request received");
54
- }
55
- const result = await next({
56
- ...interceptorOptions,
57
- context: {
58
- ...interceptorOptions.context,
59
- [LOGGER_CONTEXT_SYMBOL]: logger
60
- }
61
- });
62
- if (this.logLifecycle) {
63
- if (result.matched) {
64
- logger?.info({
65
- msg: "request handled",
66
- res: {
67
- status: result.response.status
68
- },
69
- responseTime: Date.now() - startMs
70
- });
71
- } else {
72
- logger?.info("no matching procedure found");
73
- }
74
- }
75
- return result;
76
- } catch (error) {
77
- logger.error(error);
78
- throw error;
79
- }
80
- };
81
- const interceptor = async ({ next, context, path, request }) => {
82
- const logger = getLogger(context);
83
- logger?.setBindings({ rpc: { system: ORPC_NAME, method: path.join(".") } });
84
- if (this.logAbort) {
85
- const signal = request.signal;
86
- if (signal?.aborted) {
87
- logger?.info(`request was aborted before handling (${String(signal.reason)})`);
88
- } else {
89
- signal?.addEventListener("abort", () => {
90
- logger?.info(`request is aborted (${String(signal.reason)})`);
91
- }, { once: true });
92
- }
93
- }
94
- try {
95
- return await next();
96
- } catch (error) {
97
- logProcedureError(logger, error, this.procedureErrorLevel);
98
- throw error;
99
- }
100
- };
101
- const clientInterceptor = async ({ next, context }) => {
102
- const output = await next();
103
- if (isAsyncIteratorObject(output)) {
104
- return override(output, wrapAsyncIteratorPreservingEventMeta(output, {
105
- onError: (error) => {
106
- logProcedureError(getLogger(context), error, this.procedureErrorLevel);
107
- }
108
- }));
109
- }
110
- if (output instanceof ReadableStream) {
111
- return override(output, wrapReadableStream(output, {
112
- onError: (error) => {
113
- logProcedureError(getLogger(context), error, this.procedureErrorLevel);
114
- }
115
- }));
116
- }
117
- return output;
118
- };
119
- return {
120
- ...options,
121
- routingInterceptors: [
122
- routingInterceptor,
123
- ...toArray(options.routingInterceptors)
124
- ],
125
- interceptors: [
126
- interceptor,
127
- ...toArray(options.interceptors)
128
- ],
129
- clientInterceptors: [
130
- clientInterceptor,
131
- ...toArray(options.clientInterceptors)
132
- ]
133
- };
134
- }
135
- }
136
- function logProcedureError(logger, error, procedureErrorLevel) {
137
- logger?.[procedureErrorLevel(error, defaultProcedureErrorLevel(error))](error);
138
- }
139
- function defaultProcedureErrorLevel(error) {
140
- if (isAbortError(error)) {
141
- return "info";
142
- }
143
- if (error instanceof ORPCError && error.code !== "INTERNAL_SERVER_ERROR") {
144
- return "warn";
145
- }
146
- return "error";
147
- }
148
-
149
- export { LOGGER_CONTEXT_SYMBOL, PinoHandlerPlugin, getLogger };