ras-stack 0.34.1 → 0.35.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.
@@ -1,4 +1,43 @@
1
1
  import type { PostHog, PostHogOptions } from 'posthog-node';
2
+ import type { RpcErrorContext, RpcLogger } from '../server/rpc.js';
2
3
  import type { PostHogEnvironment } from './config.js';
4
+ export type PostHogLogValue = string | number | boolean | null | PostHogLogValue[];
5
+ export type PostHogLogRecord = {
6
+ body: string;
7
+ severityText?: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
8
+ timestamp?: number;
9
+ attributes?: Record<string, unknown>;
10
+ };
11
+ export type ManagedPostHogServerTelemetryOptions = {
12
+ environment: PostHogEnvironment | undefined;
13
+ serviceName: string;
14
+ serviceVersion?: string;
15
+ deploymentEnvironment?: string;
16
+ clientOptions?: Omit<PostHogOptions, 'host'>;
17
+ onError?: (error: unknown) => void;
18
+ };
19
+ export type PostHogServerTelemetry = ReturnType<typeof createManagedPostHogServerTelemetry>;
20
+ export type PostHogRpcLoggerOptions = {
21
+ logError?: (error: unknown, context: RpcErrorContext) => void;
22
+ resolveAuthenticatedDistinctId?: (request: Request) => string | undefined | Promise<string | undefined>;
23
+ allowAnonymousDistinctId?: boolean;
24
+ fallbackDistinctId?: string;
25
+ };
26
+ type PostHogShutdownProcess = {
27
+ pid: number;
28
+ on(signal: 'SIGINT' | 'SIGTERM', listener: () => void): void;
29
+ off(signal: 'SIGINT' | 'SIGTERM', listener: () => void): void;
30
+ kill(pid: number, signal: 'SIGINT' | 'SIGTERM'): void;
31
+ };
3
32
  export declare function createPostHogServerClient(environment: PostHogEnvironment | undefined, options?: Omit<PostHogOptions, 'host'>): Promise<PostHog | undefined>;
4
33
  export declare function shutdownPostHogServerClient(client: PostHog | undefined, timeoutMs?: number): Promise<void>;
34
+ export declare function createManagedPostHogServerTelemetry(options: ManagedPostHogServerTelemetryOptions): {
35
+ start(): Promise<void>;
36
+ capture(distinctId: string, event: string, properties?: Record<string, unknown>): Promise<void>;
37
+ exception(error: unknown, distinctId?: string, properties?: Record<string, unknown>): Promise<void>;
38
+ log(record: PostHogLogRecord): Promise<void>;
39
+ shutdown(timeoutMs?: number): Promise<void>;
40
+ };
41
+ export declare function createPostHogRpcLogger(telemetry: PostHogServerTelemetry, options?: PostHogRpcLoggerOptions): RpcLogger;
42
+ export declare function installPostHogServerTelemetryShutdown(telemetry: Pick<PostHogServerTelemetry, 'shutdown'>, target?: PostHogShutdownProcess): () => void;
43
+ export {};
@@ -1,3 +1,4 @@
1
+ import { postHogRequestContext } from './request.js';
1
2
  export async function createPostHogServerClient(environment, options = {}) {
2
3
  if (!environment)
3
4
  return undefined;
@@ -9,9 +10,236 @@ export async function createPostHogServerClient(environment, options = {}) {
9
10
  });
10
11
  }
11
12
  export async function shutdownPostHogServerClient(client, timeoutMs = 10_000) {
12
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0)
13
- throw new Error('timeoutMs must be a non-negative integer');
13
+ assertShutdownTimeout(timeoutMs);
14
14
  // oxlint-disable-next-line no-underscore-dangle -- posthog-node's async shutdown API is named `_shutdown`.
15
15
  await client?._shutdown(timeoutMs);
16
16
  }
17
+ export function createManagedPostHogServerTelemetry(options) {
18
+ let client;
19
+ let logProvider;
20
+ let closed = false;
21
+ const report = (error) => {
22
+ try {
23
+ options.onError?.(error);
24
+ }
25
+ catch { }
26
+ };
27
+ const getClient = () => {
28
+ if (closed || !options.environment)
29
+ return undefined;
30
+ if (!client) {
31
+ const pending = createPostHogServerClient(options.environment, options.clientOptions);
32
+ client = pending;
33
+ void pending.catch(() => {
34
+ if (client === pending)
35
+ client = undefined;
36
+ });
37
+ }
38
+ return client;
39
+ };
40
+ const getLogProvider = () => {
41
+ if (closed || !options.environment)
42
+ return undefined;
43
+ if (!logProvider) {
44
+ const pending = createPostHogLogProvider(options);
45
+ logProvider = pending;
46
+ void pending.catch(() => {
47
+ if (logProvider === pending)
48
+ logProvider = undefined;
49
+ });
50
+ }
51
+ return logProvider;
52
+ };
53
+ const safely = async (work) => {
54
+ if (closed || !options.environment)
55
+ return;
56
+ try {
57
+ await work();
58
+ }
59
+ catch (error) {
60
+ report(error);
61
+ }
62
+ };
63
+ return {
64
+ async start() {
65
+ await safely(async () => {
66
+ await Promise.all([getClient(), getLogProvider()]);
67
+ });
68
+ },
69
+ async capture(distinctId, event, properties) {
70
+ await safely(async () => {
71
+ const value = await getClient();
72
+ value?.capture({ distinctId, event, ...(properties ? { properties } : {}) });
73
+ });
74
+ },
75
+ async exception(error, distinctId = 'server', properties) {
76
+ await safely(async () => {
77
+ const value = await getClient();
78
+ value?.captureException(error, distinctId, properties);
79
+ });
80
+ },
81
+ async log(record) {
82
+ await safely(async () => {
83
+ const provider = await getLogProvider();
84
+ const attributes = boundedAttributes(record.attributes);
85
+ provider?.getLogger(options.serviceName).emit({
86
+ body: boundedString(record.body),
87
+ ...(record.severityText ? { severityText: record.severityText } : {}),
88
+ ...(record.timestamp === undefined ? {} : { timestamp: record.timestamp }),
89
+ ...(attributes ? { attributes } : {}),
90
+ });
91
+ });
92
+ },
93
+ async shutdown(timeoutMs = 10_000) {
94
+ if (closed)
95
+ return;
96
+ assertShutdownTimeout(timeoutMs);
97
+ closed = true;
98
+ const results = await Promise.allSettled([
99
+ client?.then((value) => shutdownPostHogServerClient(value, timeoutMs)),
100
+ logProvider?.then((value) => shutdownPostHogLogProvider(value, timeoutMs)),
101
+ ]);
102
+ for (const result of results)
103
+ if (result.status === 'rejected')
104
+ report(result.reason);
105
+ },
106
+ };
107
+ }
108
+ export function createPostHogRpcLogger(telemetry, options = {}) {
109
+ return async (error, context, request) => {
110
+ try {
111
+ options.logError?.(error, context);
112
+ }
113
+ catch { }
114
+ let authenticatedDistinctId;
115
+ if (request && options.resolveAuthenticatedDistinctId) {
116
+ try {
117
+ authenticatedDistinctId = await options.resolveAuthenticatedDistinctId(request);
118
+ }
119
+ catch { }
120
+ }
121
+ const correlation = request
122
+ ? postHogRequestContext(request, {
123
+ ...(authenticatedDistinctId ? { authenticatedDistinctId } : {}),
124
+ ...(options.allowAnonymousDistinctId === undefined ? {} : { allowAnonymousDistinctId: options.allowAnonymousDistinctId }),
125
+ })
126
+ : { properties: {} };
127
+ const distinctId = correlation.distinctId ?? options.fallbackDistinctId ?? 'server';
128
+ const properties = {
129
+ ...correlation.properties,
130
+ ...(context.method ? { request_method: context.method } : {}),
131
+ ...(context.path ? { request_path: context.path } : {}),
132
+ };
133
+ await Promise.all([
134
+ telemetry.exception(error, distinctId, properties),
135
+ telemetry.log({
136
+ body: 'server function failed',
137
+ severityText: 'error',
138
+ attributes: { ...properties, posthogDistinctId: distinctId },
139
+ }),
140
+ ]);
141
+ };
142
+ }
143
+ export function installPostHogServerTelemetryShutdown(telemetry, target = process) {
144
+ let shuttingDown = false;
145
+ const listeners = new Map();
146
+ const remove = () => {
147
+ for (const [signal, listener] of listeners)
148
+ target.off(signal, listener);
149
+ listeners.clear();
150
+ };
151
+ for (const signal of ['SIGINT', 'SIGTERM']) {
152
+ const listener = () => {
153
+ if (shuttingDown)
154
+ return;
155
+ shuttingDown = true;
156
+ void telemetry
157
+ .shutdown()
158
+ .catch(() => undefined)
159
+ .finally(() => {
160
+ remove();
161
+ target.kill(target.pid, signal);
162
+ });
163
+ };
164
+ listeners.set(signal, listener);
165
+ target.on(signal, listener);
166
+ }
167
+ return remove;
168
+ }
169
+ async function createPostHogLogProvider(options) {
170
+ if (!options.environment)
171
+ return undefined;
172
+ const [{ OTLPLogExporter }, { resourceFromAttributes }, { BatchLogRecordProcessor, LoggerProvider }] = await Promise.all([
173
+ import('@opentelemetry/exporter-logs-otlp-http'),
174
+ import('@opentelemetry/resources'),
175
+ import('@opentelemetry/sdk-logs'),
176
+ ]);
177
+ const exporter = new OTLPLogExporter({
178
+ url: `${options.environment.host.replace(/\/$/, '')}/i/v1/logs`,
179
+ headers: { Authorization: `Bearer ${options.environment.projectToken}` },
180
+ });
181
+ return new LoggerProvider({
182
+ resource: resourceFromAttributes({
183
+ 'service.name': options.serviceName,
184
+ ...(options.serviceVersion ? { 'service.version': options.serviceVersion } : {}),
185
+ ...(options.deploymentEnvironment ? { 'deployment.environment': options.deploymentEnvironment } : {}),
186
+ }),
187
+ processors: [new BatchLogRecordProcessor({ exporter })],
188
+ });
189
+ }
190
+ function boundedAttributes(attributes) {
191
+ if (!attributes)
192
+ return undefined;
193
+ return Object.fromEntries(Object.entries(attributes)
194
+ .slice(0, 64)
195
+ .map(([key, value]) => [key.slice(0, 128), boundedLogValue(value, 0)])
196
+ .filter((entry) => entry[1] !== undefined));
197
+ }
198
+ function boundedLogValue(value, depth) {
199
+ if (value === null || typeof value === 'number' || typeof value === 'boolean')
200
+ return value;
201
+ if (typeof value === 'string')
202
+ return boundedString(value);
203
+ if (depth >= 3)
204
+ return '[Truncated]';
205
+ if (Array.isArray(value)) {
206
+ return value
207
+ .slice(0, 32)
208
+ .map((entry) => boundedLogValue(entry, depth + 1))
209
+ .filter((entry) => entry !== undefined);
210
+ }
211
+ if (value === undefined)
212
+ return undefined;
213
+ try {
214
+ return boundedString(JSON.stringify(value));
215
+ }
216
+ catch {
217
+ return '[Unserializable value]';
218
+ }
219
+ }
220
+ function boundedString(value) {
221
+ return value.slice(0, 2_048);
222
+ }
223
+ async function shutdownPostHogLogProvider(provider, timeoutMs) {
224
+ if (!provider)
225
+ return;
226
+ let timeout;
227
+ try {
228
+ await Promise.race([
229
+ provider.shutdown(),
230
+ new Promise((_resolve, reject) => {
231
+ timeout = setTimeout(() => reject(new Error(`PostHog log shutdown timed out after ${timeoutMs}ms`)), timeoutMs);
232
+ timeout.unref?.();
233
+ }),
234
+ ]);
235
+ }
236
+ finally {
237
+ if (timeout)
238
+ clearTimeout(timeout);
239
+ }
240
+ }
241
+ function assertShutdownTimeout(timeoutMs) {
242
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0)
243
+ throw new Error('timeoutMs must be a non-negative integer');
244
+ }
17
245
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/posthog/server.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,WAA2C,EAC3C,OAAO,GAAiC,EAAE;IAE1C,IAAI,CAAC,WAAW;QAAE,OAAO,SAAS,CAAA;IAClC,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,MAAM,CAAC,cAAc,CAAC,CAAA;IAChD,OAAO,IAAI,OAAO,CAAC,WAAW,CAAC,YAAY,EAAE;QAC3C,IAAI,EAAE,WAAW,CAAC,IAAI;QACtB,0BAA0B,EAAE,IAAI;QAChC,GAAG,OAAO;KACX,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,MAA2B,EAAE,SAAS,GAAG,MAAM;IAC/F,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,SAAS,CAAC,IAAI,SAAS,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;IAClH,2GAA2G;IAC3G,MAAM,MAAM,EAAE,SAAS,CAAC,SAAS,CAAC,CAAA;AACpC,CAAC","sourcesContent":["import type { PostHog, PostHogOptions } from 'posthog-node'\nimport type { PostHogEnvironment } from './config.js'\n\nexport async function createPostHogServerClient(\n environment: PostHogEnvironment | undefined,\n options: Omit<PostHogOptions, 'host'> = {},\n): Promise<PostHog | undefined> {\n if (!environment) return undefined\n const { PostHog } = await import('posthog-node')\n return new PostHog(environment.projectToken, {\n host: environment.host,\n enableExceptionAutocapture: true,\n ...options,\n })\n}\n\nexport async function shutdownPostHogServerClient(client: PostHog | undefined, timeoutMs = 10_000) {\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0) throw new Error('timeoutMs must be a non-negative integer')\n // oxlint-disable-next-line no-underscore-dangle -- posthog-node's async shutdown API is named `_shutdown`.\n await client?._shutdown(timeoutMs)\n}\n"]}
1
+ {"version":3,"file":"server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I,OAAO;YAAE,YAAY,CAAC,OAAO,CAAC,CAAA;IACpC,CAAC;AACH,CAAC;AAED,SAAS,qBAAqB,CAAC,SAAiB;IAC9C,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,SAAS,CAAC,IAAI,SAAS,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;AACpH,CAAC","sourcesContent":["import type { PostHog, PostHogOptions } from 'posthog-node'\nimport type { RpcErrorContext, RpcLogger } from '../server/rpc.js'\nimport type { PostHogEnvironment } from './config.js'\nimport { postHogRequestContext } from './request.js'\n\ntype LogProvider = InstanceType<(typeof import('@opentelemetry/sdk-logs'))['LoggerProvider']>\n\nexport type PostHogLogValue = string | number | boolean | null | PostHogLogValue[]\n\nexport type PostHogLogRecord = {\n body: string\n severityText?: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'\n timestamp?: number\n attributes?: Record<string, unknown>\n}\n\nexport type ManagedPostHogServerTelemetryOptions = {\n environment: PostHogEnvironment | undefined\n serviceName: string\n serviceVersion?: string\n deploymentEnvironment?: string\n clientOptions?: Omit<PostHogOptions, 'host'>\n onError?: (error: unknown) => void\n}\n\nexport type PostHogServerTelemetry = ReturnType<typeof createManagedPostHogServerTelemetry>\n\nexport type PostHogRpcLoggerOptions = {\n logError?: (error: unknown, context: RpcErrorContext) => void\n resolveAuthenticatedDistinctId?: (request: Request) => string | undefined | Promise<string | undefined>\n allowAnonymousDistinctId?: boolean\n fallbackDistinctId?: string\n}\n\ntype PostHogShutdownProcess = {\n pid: number\n on(signal: 'SIGINT' | 'SIGTERM', listener: () => void): void\n off(signal: 'SIGINT' | 'SIGTERM', listener: () => void): void\n kill(pid: number, signal: 'SIGINT' | 'SIGTERM'): void\n}\n\nexport async function createPostHogServerClient(\n environment: PostHogEnvironment | undefined,\n options: Omit<PostHogOptions, 'host'> = {},\n): Promise<PostHog | undefined> {\n if (!environment) return undefined\n const { PostHog } = await import('posthog-node')\n return new PostHog(environment.projectToken, {\n host: environment.host,\n enableExceptionAutocapture: true,\n ...options,\n })\n}\n\nexport async function shutdownPostHogServerClient(client: PostHog | undefined, timeoutMs = 10_000) {\n assertShutdownTimeout(timeoutMs)\n // oxlint-disable-next-line no-underscore-dangle -- posthog-node's async shutdown API is named `_shutdown`.\n await client?._shutdown(timeoutMs)\n}\n\nexport function createManagedPostHogServerTelemetry(options: ManagedPostHogServerTelemetryOptions) {\n let client: Promise<PostHog | undefined> | undefined\n let logProvider: Promise<LogProvider | undefined> | undefined\n let closed = false\n\n const report = (error: unknown) => {\n try {\n options.onError?.(error)\n } catch {}\n }\n\n const getClient = () => {\n if (closed || !options.environment) return undefined\n if (!client) {\n const pending = createPostHogServerClient(options.environment, options.clientOptions)\n client = pending\n void pending.catch(() => {\n if (client === pending) client = undefined\n })\n }\n return client\n }\n\n const getLogProvider = () => {\n if (closed || !options.environment) return undefined\n if (!logProvider) {\n const pending = createPostHogLogProvider(options)\n logProvider = pending\n void pending.catch(() => {\n if (logProvider === pending) logProvider = undefined\n })\n }\n return logProvider\n }\n\n const safely = async (work: () => void | Promise<void>) => {\n if (closed || !options.environment) return\n try {\n await work()\n } catch (error) {\n report(error)\n }\n }\n\n return {\n async start() {\n await safely(async () => {\n await Promise.all([getClient(), getLogProvider()])\n })\n },\n async capture(distinctId: string, event: string, properties?: Record<string, unknown>) {\n await safely(async () => {\n const value = await getClient()\n value?.capture({ distinctId, event, ...(properties ? { properties } : {}) })\n })\n },\n async exception(error: unknown, distinctId = 'server', properties?: Record<string, unknown>) {\n await safely(async () => {\n const value = await getClient()\n value?.captureException(error, distinctId, properties)\n })\n },\n async log(record: PostHogLogRecord) {\n await safely(async () => {\n const provider = await getLogProvider()\n const attributes = boundedAttributes(record.attributes)\n provider?.getLogger(options.serviceName).emit({\n body: boundedString(record.body),\n ...(record.severityText ? { severityText: record.severityText } : {}),\n ...(record.timestamp === undefined ? {} : { timestamp: record.timestamp }),\n ...(attributes ? { attributes } : {}),\n })\n })\n },\n async shutdown(timeoutMs = 10_000) {\n if (closed) return\n assertShutdownTimeout(timeoutMs)\n closed = true\n const results = await Promise.allSettled([\n client?.then((value) => shutdownPostHogServerClient(value, timeoutMs)),\n logProvider?.then((value) => shutdownPostHogLogProvider(value, timeoutMs)),\n ])\n for (const result of results) if (result.status === 'rejected') report(result.reason)\n },\n }\n}\n\nexport function createPostHogRpcLogger(telemetry: PostHogServerTelemetry, options: PostHogRpcLoggerOptions = {}): RpcLogger {\n return async (error, context, request) => {\n try {\n options.logError?.(error, context)\n } catch {}\n let authenticatedDistinctId: string | undefined\n if (request && options.resolveAuthenticatedDistinctId) {\n try {\n authenticatedDistinctId = await options.resolveAuthenticatedDistinctId(request)\n } catch {}\n }\n const correlation = request\n ? postHogRequestContext(request, {\n ...(authenticatedDistinctId ? { authenticatedDistinctId } : {}),\n ...(options.allowAnonymousDistinctId === undefined ? {} : { allowAnonymousDistinctId: options.allowAnonymousDistinctId }),\n })\n : { properties: {} }\n const distinctId = correlation.distinctId ?? options.fallbackDistinctId ?? 'server'\n const properties = {\n ...correlation.properties,\n ...(context.method ? { request_method: context.method } : {}),\n ...(context.path ? { request_path: context.path } : {}),\n }\n await Promise.all([\n telemetry.exception(error, distinctId, properties),\n telemetry.log({\n body: 'server function failed',\n severityText: 'error',\n attributes: { ...properties, posthogDistinctId: distinctId },\n }),\n ])\n }\n}\n\nexport function installPostHogServerTelemetryShutdown(\n telemetry: Pick<PostHogServerTelemetry, 'shutdown'>,\n target: PostHogShutdownProcess = process,\n) {\n let shuttingDown = false\n const listeners = new Map<'SIGINT' | 'SIGTERM', () => void>()\n const remove = () => {\n for (const [signal, listener] of listeners) target.off(signal, listener)\n listeners.clear()\n }\n for (const signal of ['SIGINT', 'SIGTERM'] as const) {\n const listener = () => {\n if (shuttingDown) return\n shuttingDown = true\n void telemetry\n .shutdown()\n .catch(() => undefined)\n .finally(() => {\n remove()\n target.kill(target.pid, signal)\n })\n }\n listeners.set(signal, listener)\n target.on(signal, listener)\n }\n return remove\n}\n\nasync function createPostHogLogProvider(options: ManagedPostHogServerTelemetryOptions): Promise<LogProvider | undefined> {\n if (!options.environment) return undefined\n const [{ OTLPLogExporter }, { resourceFromAttributes }, { BatchLogRecordProcessor, LoggerProvider }] = await Promise.all([\n import('@opentelemetry/exporter-logs-otlp-http'),\n import('@opentelemetry/resources'),\n import('@opentelemetry/sdk-logs'),\n ])\n const exporter = new OTLPLogExporter({\n url: `${options.environment.host.replace(/\\/$/, '')}/i/v1/logs`,\n headers: { Authorization: `Bearer ${options.environment.projectToken}` },\n })\n return new LoggerProvider({\n resource: resourceFromAttributes({\n 'service.name': options.serviceName,\n ...(options.serviceVersion ? { 'service.version': options.serviceVersion } : {}),\n ...(options.deploymentEnvironment ? { 'deployment.environment': options.deploymentEnvironment } : {}),\n }),\n processors: [new BatchLogRecordProcessor({ exporter })],\n })\n}\n\nfunction boundedAttributes(attributes: Record<string, unknown> | undefined) {\n if (!attributes) return undefined\n return Object.fromEntries(\n Object.entries(attributes)\n .slice(0, 64)\n .map(([key, value]) => [key.slice(0, 128), boundedLogValue(value, 0)])\n .filter((entry): entry is [string, PostHogLogValue] => entry[1] !== undefined),\n )\n}\n\nfunction boundedLogValue(value: unknown, depth: number): PostHogLogValue | undefined {\n if (value === null || typeof value === 'number' || typeof value === 'boolean') return value\n if (typeof value === 'string') return boundedString(value)\n if (depth >= 3) return '[Truncated]'\n if (Array.isArray(value)) {\n return value\n .slice(0, 32)\n .map((entry) => boundedLogValue(entry, depth + 1))\n .filter((entry): entry is PostHogLogValue => entry !== undefined)\n }\n if (value === undefined) return undefined\n try {\n return boundedString(JSON.stringify(value))\n } catch {\n return '[Unserializable value]'\n }\n}\n\nfunction boundedString(value: string) {\n return value.slice(0, 2_048)\n}\n\nasync function shutdownPostHogLogProvider(provider: LogProvider | undefined, timeoutMs: number) {\n if (!provider) return\n let timeout: ReturnType<typeof setTimeout> | undefined\n try {\n await Promise.race([\n provider.shutdown(),\n new Promise<never>((_resolve, reject) => {\n timeout = setTimeout(() => reject(new Error(`PostHog log shutdown timed out after ${timeoutMs}ms`)), timeoutMs)\n timeout.unref?.()\n }),\n ])\n } finally {\n if (timeout) clearTimeout(timeout)\n }\n}\n\nfunction assertShutdownTimeout(timeoutMs: number) {\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0) throw new Error('timeoutMs must be a non-negative integer')\n}\n"]}
@@ -1,7 +1,8 @@
1
- export type RpcLogger = (error: unknown, context: {
1
+ export type RpcErrorContext = {
2
2
  method?: string;
3
3
  path?: string;
4
- }) => void;
4
+ };
5
+ export type RpcLogger = (error: unknown, context: RpcErrorContext, request?: Request) => void | Promise<void>;
5
6
  export type RpcOptions = {
6
7
  getRequest?: () => Request;
7
8
  requireMutation?: (request: Request) => void;
@@ -6,7 +6,11 @@ export function createRpc(options = {}) {
6
6
  catch (error) {
7
7
  if (error instanceof Response)
8
8
  throw new Error((await error.text()) || `request failed (${error.status})`, { cause: error });
9
- options.logError?.(error, requestContext(options.getRequest));
9
+ const request = resolveRequest(options.getRequest);
10
+ try {
11
+ await options.logError?.(error, requestContext(request), request);
12
+ }
13
+ catch { }
10
14
  throw error;
11
15
  }
12
16
  }
@@ -20,13 +24,15 @@ export function createRpc(options = {}) {
20
24
  }
21
25
  return { rpc, mutationRpc };
22
26
  }
23
- function requestContext(getRequest) {
27
+ function resolveRequest(getRequest) {
24
28
  try {
25
- const request = getRequest?.();
26
- return request ? { method: request.method, path: new URL(request.url).pathname } : {};
29
+ return getRequest?.();
27
30
  }
28
31
  catch {
29
- return {};
32
+ return undefined;
30
33
  }
31
34
  }
35
+ function requestContext(request) {
36
+ return request ? { method: request.method, path: new URL(request.url).pathname } : {};
37
+ }
32
38
  //# sourceMappingURL=rpc.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"rpc.js","sourceRoot":"","sources":["../../src/server/rpc.ts"],"names":[],"mappings":"AAQA,MAAM,UAAU,SAAS,CAAC,OAAO,GAAe,EAAE;IAChD,KAAK,UAA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RpcOptions = {\n getRequest?: () => Request\n requireMutation?: (request: Request) => void\n logError?: RpcLogger\n}\n\nexport function createRpc(options: RpcOptions = {}) {\n async function rpc<T>(work: () => Promise<T> | T): Promise<T> {\n try {\n return await work()\n } catch (error) {\n if (error instanceof Response) throw new Error((await error.text()) || `request failed (${error.status})`, { cause: error })\n options.logError?.(error, requestContext(options.getRequest))\n throw error\n }\n }\n\n function mutationRpc<T>(work: () => Promise<T> | T, request = options.getRequest?.()) {\n return rpc(() => {\n if (!request) throw new Error('mutation request is unavailable')\n options.requireMutation?.(request)\n return work()\n })\n }\n\n return { rpc, mutationRpc }\n}\n\nfunction requestContext(getRequest: (() => Request) | undefined) {\n try {\n const request = getRequest?.()\n return request ? { method: request.method, path: new URL(request.url).pathname } : {}\n } catch {\n return {}\n }\n}\n"]}
1
+ {"version":3,"file":"rpc.js","sourceRoot":"","sources":["../../src/server/rpc.ts"],"names":[],"mappings":"AASA,MAAM,UAAU,SAAS,CAAC,OAAO,GAAe,EAAE;IAChD,KAAK,UAAU,GAAG,CAAI,IAA0B;QAC9C,IAAI,CAAC;YACH,OAAO,MAAM,IAAI,EAAE,CAAA;QACrB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,YAAY,QAAQ;gBAAE,MAAM,IAAI,KAAK,CAAC,CAAC,MAAM,KAAK,CAAC,IAAI,EAAE,CAAC,IAAI,mBAAmB,KAAK,CAAC,MAAM,GAAG,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAA;YAC5H,MAAM,OAAO,GAAG,cAAc,CAAC,OAAO,CAAC,UAAU,CAAC,CAAA;YAClD,IAAI,CAAC;gBACH,MAAM,OAAO,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,cAAc,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,CAAA;YACnE,CAAC;YAAC,MAAM,CAAC,CAAA,CAAC;YACV,MAAM,KAAK,CAAA;QACb,CAAC;IACH,CAAC;IAED,SAAS,WAAW,CAAI,IAA0B,EAAE,OAAO,GAAG,OAAO,CAAC,UAAU,EAAE,EAAE;QAClF,OAAO,GAAG,CAAC,GAAG,EAAE;YACd,IAAI,CAAC,OAAO;gBAAE,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAA;YAChE,OAAO,CAAC,eAAe,EAAE,CAAC,OAAO,CAAC,CAAA;YAClC,OAAO,IAAI,EAAE,CAAA;QACf,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,OAAO,EAAE,GAAG,EAAE,WAAW,EAAE,CAAA;AAC7B,CAAC;AAED,SAAS,cAAc,CAAC,UAAuC;IAC7D,IAAI,CAAC;QACH,OAAO,UAAU,EAAE,EAAE,CAAA;IACvB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAA;IAClB,CAAC;AACH,CAAC;AAED,SAAS,cAAc,CAAC,OAA4B;IAClD,OAAO,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;AACvF,CAAC","sourcesContent":["export type RpcErrorContext = { method?: string; path?: string }\nexport type RpcLogger = (error: unknown, context: RpcErrorContext, request?: Request) => void | Promise<void>\n\nexport type RpcOptions = {\n getRequest?: () => Request\n requireMutation?: (request: Request) => void\n logError?: RpcLogger\n}\n\nexport function createRpc(options: RpcOptions = {}) {\n async function rpc<T>(work: () => Promise<T> | T): Promise<T> {\n try {\n return await work()\n } catch (error) {\n if (error instanceof Response) throw new Error((await error.text()) || `request failed (${error.status})`, { cause: error })\n const request = resolveRequest(options.getRequest)\n try {\n await options.logError?.(error, requestContext(request), request)\n } catch {}\n throw error\n }\n }\n\n function mutationRpc<T>(work: () => Promise<T> | T, request = options.getRequest?.()) {\n return rpc(() => {\n if (!request) throw new Error('mutation request is unavailable')\n options.requireMutation?.(request)\n return work()\n })\n }\n\n return { rpc, mutationRpc }\n}\n\nfunction resolveRequest(getRequest: (() => Request) | undefined) {\n try {\n return getRequest?.()\n } catch {\n return undefined\n }\n}\n\nfunction requestContext(request: Request | undefined): RpcErrorContext {\n return request ? { method: request.method, path: new URL(request.url).pathname } : {}\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ras-stack",
3
- "version": "0.34.1",
3
+ "version": "0.35.0",
4
4
  "description": "Composable full-stack primitives shared across Richard Solomou's applications.",
5
5
  "keywords": [
6
6
  "authentication",
@@ -156,6 +156,10 @@
156
156
  },
157
157
  "devDependencies": {
158
158
  "@changesets/cli": "^2.31.1",
159
+ "@opentelemetry/api-logs": "^0.221.0",
160
+ "@opentelemetry/exporter-logs-otlp-http": "^0.221.0",
161
+ "@opentelemetry/resources": "^2.10.0",
162
+ "@opentelemetry/sdk-logs": "^0.221.0",
159
163
  "@playwright/test": "1.62.1",
160
164
  "@posthog/react": "^1.10.3",
161
165
  "@tanstack/react-query": "^5.101.4",
@@ -183,6 +187,10 @@
183
187
  "vitest": "^4.1.10"
184
188
  },
185
189
  "peerDependencies": {
190
+ "@opentelemetry/api-logs": "^0.221.0",
191
+ "@opentelemetry/exporter-logs-otlp-http": "^0.221.0",
192
+ "@opentelemetry/resources": "^2.10.0",
193
+ "@opentelemetry/sdk-logs": "^0.221.0",
186
194
  "@posthog/react": ">=1 <2",
187
195
  "@tanstack/react-query": ">=5 <6",
188
196
  "@tanstack/react-start": ">=1 <2",
@@ -197,6 +205,18 @@
197
205
  "tus-js-client": ">=4 <5"
198
206
  },
199
207
  "peerDependenciesMeta": {
208
+ "@opentelemetry/api-logs": {
209
+ "optional": true
210
+ },
211
+ "@opentelemetry/exporter-logs-otlp-http": {
212
+ "optional": true
213
+ },
214
+ "@opentelemetry/resources": {
215
+ "optional": true
216
+ },
217
+ "@opentelemetry/sdk-logs": {
218
+ "optional": true
219
+ },
200
220
  "@posthog/react": {
201
221
  "optional": true
202
222
  },