ras-stack 5.2.3 → 5.4.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.
- package/dist/email/index.d.ts +11 -0
- package/dist/email/index.js +6 -1
- package/dist/email/index.js.map +1 -1
- package/dist/posthog/server.js +11 -3
- package/dist/posthog/server.js.map +1 -1
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.js +1 -0
- package/dist/server/index.js.map +1 -1
- package/dist/server/rpc.d.ts +3 -0
- package/dist/server/rpc.js +17 -8
- package/dist/server/rpc.js.map +1 -1
- package/package.json +1 -1
package/dist/email/index.d.ts
CHANGED
|
@@ -1,8 +1,19 @@
|
|
|
1
|
+
/** `cid` lets the HTML body reference the attachment inline as `cid:<value>`. */
|
|
2
|
+
export type EmailAttachment = {
|
|
3
|
+
filename: string;
|
|
4
|
+
content: Buffer;
|
|
5
|
+
contentType: string;
|
|
6
|
+
cid?: string;
|
|
7
|
+
};
|
|
1
8
|
export type EmailMessage = {
|
|
2
9
|
to: string;
|
|
3
10
|
subject: string;
|
|
4
11
|
text: string;
|
|
5
12
|
html?: string;
|
|
13
|
+
attachments?: EmailAttachment[];
|
|
14
|
+
/** Replaces the display name of the configured sender; the address stays the configured one so SPF and DKIM still pass. */
|
|
15
|
+
fromName?: string;
|
|
16
|
+
replyTo?: string;
|
|
6
17
|
};
|
|
7
18
|
export type SmtpConfig = {
|
|
8
19
|
from: string;
|
package/dist/email/index.js
CHANGED
|
@@ -34,10 +34,15 @@ export function createSmtpDelivery(config) {
|
|
|
34
34
|
auth: config.user ? { user: config.user, pass: config.password } : undefined,
|
|
35
35
|
});
|
|
36
36
|
return {
|
|
37
|
-
send: async (
|
|
37
|
+
send: async ({ fromName, ...message }) => transport
|
|
38
|
+
.sendMail({ from: fromName ? { name: fromName, address: senderAddress(config.from) } : config.from, ...message })
|
|
39
|
+
.then(() => undefined),
|
|
38
40
|
verify: async () => transport.verify().then(() => undefined),
|
|
39
41
|
};
|
|
40
42
|
}
|
|
43
|
+
function senderAddress(from) {
|
|
44
|
+
return /<([^<>]+)>\s*$/.exec(from)?.[1] ?? from;
|
|
45
|
+
}
|
|
41
46
|
export function standardAuthEmails(delivery, options) {
|
|
42
47
|
const expiry = 'This link expires in one hour.';
|
|
43
48
|
const send = (subject, label) => async ({ user, url }) => delivery.send({
|
package/dist/email/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/email/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/email/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AA6C5C,MAAM,UAAU,yBAAyB,CACvC,WAAW,GAAsB,OAAO,CAAC,GAAG,EAC5C,IAAI,GAA2B,EAAE;IAEjC,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,IAAI,IAAI,WAAW,CAAC,EAAE,IAAI,EAAE,CAAA;IAC1D,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,IAAI,IAAI,YAAY,CAAC,EAAE,IAAI,EAAE,CAAA;IAC3D,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI;QAAE,OAAO,SAAS,CAAA;IACpC,IAAI,CAAC,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,CAAC,IAAI,IAAI,WAAW,6BAA6B,CAAC,CAAA;IACpF,IAAI,CAAC,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,CAAC,IAAI,IAAI,YAAY,6BAA6B,CAAC,CAAA;IAErF,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,IAAI,WAAW,CAAA;IACxC,MAAM,IAAI,GAAG,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,GAAG,CAAC,CAAA;IAChD,IA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O,CAAC,WAAW,gBAAgB,EAAE,sBAAsB,CAAC;KACxG,CAAA;AACH,CAAC;AAED,SAAS,UAAU,CAAC,KAAa;IAC/B,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;AACjH,CAAC","sourcesContent":["import { createTransport } from 'nodemailer'\n\n/** `cid` lets the HTML body reference the attachment inline as `cid:<value>`. */\nexport type EmailAttachment = { filename: string; content: Buffer; contentType: string; cid?: string }\n\nexport type EmailMessage = {\n to: string\n subject: string\n text: string\n html?: string\n attachments?: EmailAttachment[]\n /** Replaces the display name of the configured sender; the address stays the configured one so SPF and DKIM still pass. */\n fromName?: string\n replyTo?: string\n}\n\nexport type SmtpConfig = {\n from: string\n host: string\n port: number\n secure: boolean\n user?: string\n password?: string\n}\n\nexport type SmtpEnvironmentOptions = {\n host?: string\n port?: string\n secure?: string\n user?: string\n password?: string\n from?: string\n}\n\nexport type EmailDelivery = {\n send(message: EmailMessage): Promise<void>\n verify(): Promise<void>\n}\n\nexport type AuthEmailInput<User extends { email: string } = { email: string }> = {\n user: User\n url: string\n token: string\n}\n\nexport function smtpConfigFromEnvironment(\n environment: NodeJS.ProcessEnv = process.env,\n keys: SmtpEnvironmentOptions = {},\n): SmtpConfig | undefined {\n const host = environment[keys.host ?? 'SMTP_HOST']?.trim()\n const from = environment[keys.from ?? 'EMAIL_FROM']?.trim()\n if (!host && !from) return undefined\n if (!host) throw new Error(`${keys.host ?? 'SMTP_HOST'} is required for SMTP email`)\n if (!from) throw new Error(`${keys.from ?? 'EMAIL_FROM'} is required for SMTP email`)\n\n const portKey = keys.port ?? 'SMTP_PORT'\n const port = Number(environment[portKey] ?? 587)\n if (!Number.isInteger(port) || port < 1 || port > 65_535) throw new Error(`${portKey} must be a valid TCP port`)\n\n const userKey = keys.user ?? 'SMTP_USER'\n const passwordKey = keys.password ?? 'SMTP_PASSWORD'\n const user = environment[userKey]?.trim()\n const password = environment[passwordKey]\n if (Boolean(user) !== Boolean(password)) throw new Error(`${userKey} and ${passwordKey} must be configured together`)\n\n return {\n from,\n host,\n port,\n secure: environment[keys.secure ?? 'SMTP_SECURE']?.trim().toLowerCase() === 'true',\n ...(user && password ? { user, password } : {}),\n }\n}\n\nexport function createSmtpDelivery(config: SmtpConfig): EmailDelivery {\n const transport = createTransport({\n host: config.host,\n port: config.port,\n secure: config.secure,\n auth: config.user ? { user: config.user, pass: config.password } : undefined,\n })\n return {\n send: async ({ fromName, ...message }) =>\n transport\n .sendMail({ from: fromName ? { name: fromName, address: senderAddress(config.from) } : config.from, ...message })\n .then(() => undefined),\n verify: async () => transport.verify().then(() => undefined),\n }\n}\n\nfunction senderAddress(from: string) {\n return /<([^<>]+)>\\s*$/.exec(from)?.[1] ?? from\n}\n\nexport type StandardAuthEmailOptions = { productName: string }\n\nexport function standardAuthEmails<User extends { email: string } = { email: string }>(\n delivery: EmailDelivery,\n options: StandardAuthEmailOptions,\n) {\n const expiry = 'This link expires in one hour.'\n const send =\n (subject: string, label: string) =>\n async ({ user, url }: AuthEmailInput<User>) =>\n delivery.send({\n to: user.email,\n subject,\n text: `${subject} using this link: ${url}\\n\\n${expiry}`,\n html: `<p>${escapeHtml(subject)} using the link below.</p><p><a href=\"${escapeHtml(url)}\">${label}</a></p><p>${expiry}</p>`,\n })\n return {\n sendResetPassword: send(`Reset your ${options.productName} password`, 'Reset password'),\n sendVerificationEmail: send(`Verify your ${options.productName} email address`, 'Verify email address'),\n }\n}\n\nfunction escapeHtml(value: string) {\n return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('\"', '"')\n}\n"]}
|
package/dist/posthog/server.js
CHANGED
|
@@ -125,7 +125,7 @@ export function createManagedPostHogServerTelemetry(options) {
|
|
|
125
125
|
await safely(async () => {
|
|
126
126
|
const value = await getClient();
|
|
127
127
|
const correlation = context.getStore();
|
|
128
|
-
const capturedProperties = mergeProperties(properties, correlation?.properties);
|
|
128
|
+
const capturedProperties = mergeProperties(serverFunctionProperties(), properties, correlation?.properties);
|
|
129
129
|
value?.captureException(error, distinctId ?? correlation?.distinctId ?? 'server', capturedProperties);
|
|
130
130
|
});
|
|
131
131
|
},
|
|
@@ -133,7 +133,7 @@ export function createManagedPostHogServerTelemetry(options) {
|
|
|
133
133
|
await safely(async () => {
|
|
134
134
|
const provider = await getLogProvider();
|
|
135
135
|
const correlation = context.getStore();
|
|
136
|
-
const attributes = boundedAttributes(mergeProperties(record.attributes, {
|
|
136
|
+
const attributes = boundedAttributes(mergeProperties(serverFunctionProperties(), record.attributes, {
|
|
137
137
|
...(correlation?.distinctId ? { posthogDistinctId: correlation.distinctId } : {}),
|
|
138
138
|
...(correlation?.sessionId ? { sessionId: correlation.sessionId } : {}),
|
|
139
139
|
}));
|
|
@@ -211,6 +211,8 @@ export function createPostHogRpcLogger(telemetry, options = {}) {
|
|
|
211
211
|
...correlation.properties,
|
|
212
212
|
...(context.method ? { request_method: context.method } : {}),
|
|
213
213
|
...(context.path ? { request_path: context.path } : {}),
|
|
214
|
+
...(context.function ? { server_function: context.function } : {}),
|
|
215
|
+
...(context.status === undefined ? {} : { response_status: context.status }),
|
|
214
216
|
};
|
|
215
217
|
await Promise.all([
|
|
216
218
|
telemetry.exception(error, distinctId, properties),
|
|
@@ -248,9 +250,10 @@ export function createPostHogRpcObserver(telemetry, options = {}) {
|
|
|
248
250
|
}
|
|
249
251
|
catch (error) {
|
|
250
252
|
const status = responseStatus(error);
|
|
253
|
+
if (status !== undefined)
|
|
254
|
+
span?.setAttribute('http.response.status_code', status);
|
|
251
255
|
if (status === undefined || status >= 500)
|
|
252
256
|
throw error;
|
|
253
|
-
span?.setAttribute('http.response.status_code', status);
|
|
254
257
|
outcome = status >= 400 ? 'refused' : 'success';
|
|
255
258
|
// Returning instead of throwing keeps an intended response from marking the span as failed.
|
|
256
259
|
return { response: error };
|
|
@@ -322,6 +325,11 @@ async function createPostHogLogProvider(environment, options) {
|
|
|
322
325
|
processors: [new BatchLogRecordProcessor({ exporter })],
|
|
323
326
|
});
|
|
324
327
|
}
|
|
328
|
+
/** Names the server function a log or exception was recorded in, so it reads without the request path's opaque id. */
|
|
329
|
+
function serverFunctionProperties() {
|
|
330
|
+
const name = currentServerFunction()?.name;
|
|
331
|
+
return name ? { server_function: name } : undefined;
|
|
332
|
+
}
|
|
325
333
|
function mergeProperties(...values) {
|
|
326
334
|
const merged = Object.assign({}, ...values.filter(Boolean));
|
|
327
335
|
return Object.keys(merged).length ? merged : undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/posthog/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAA;AACpD,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAA;AAG1D,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAA;AAEpE,OAAO,EAAE,qBAAqB,EAAqC,MAAM,cAAc,CAAA;AAoDvF,KAAK,UAAU,yBAAyB,CAAC,WAA+B,EAAE,OAAqC;IAC7G,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,UAAU,mCAAmC,CAAC,OAA6C;IAC/F,IAAI,MAAoC,CAAA;IACxC,IAAI,WAA6C,CAAA;IACjD,IAAI,MAAM,GAAG,KAAK,CAAA;IAClB,MAAM,OAAO,GAAG,IAAI,iBAAiB,EAA2B,CAAA;IAEhE,MAAM,MAAM,GA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S,CAAA;IACzC,IAAI,CAAC;QACH,OAAO,aAAa,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAA;IAC7C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,wBAAwB,CAAA;IACjC,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,KAAa;IAClC,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAA;AAC9B,CAAC;AAED,KAAK,UAAU,0BAA0B,CAAC,QAAqB,EAAE,SAAiB;IAChF,MAAM,KAAK,GAAG,IAAI,eAAe,EAAE,CAAA;IACnC,IAAI,CAAC;QACH,MAAM,OAAO,CAAC,IAAI,CAAC;YACjB,QAAQ,CAAC,QAAQ,EAAE;YACnB,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE;gBAC1E,MAAM,IAAI,KAAK,CAAC,wCAAwC,SAAS,IAAI,CAAC,CAAA;YACxE,CAAC,CAAC;SACH,CAAC,CAAA;IACJ,CAAC;YAAS,CAAC;QACT,KAAK,CAAC,KAAK,EAAE,CAAA;IACf,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 { AsyncLocalStorage } from 'node:async_hooks'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport type { CaptureMetricOptions, PostHog, PostHogOptions, Span, StartSpanOptions } from 'posthog-node'\nimport type { RpcErrorContext, RpcLogger, RpcObserver } from '../server/rpc.js'\nimport { currentServerFunction } from '../server/server-function.js'\nimport type { PostHogEnvironment } from './config.js'\nimport { postHogRequestContext, type PostHogRequestContextOptions } 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 resourceAttributes?: Record<string, string>\n clientOptions?: Omit<PostHogOptions, 'host'>\n onError?: (error: unknown) => void\n}\n\nexport type PostHogServerTelemetry = ReturnType<typeof createManagedPostHogServerTelemetry>\n\nexport type PostHogTelemetryContext = {\n distinctId?: string\n sessionId?: string\n properties?: Record<string, unknown>\n}\n\nexport type PostHogTraceSpan = Span | undefined\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\nexport type PostHogRpcObserverOptions = {\n metricPrefix?: string\n spanName?: 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\nasync function createPostHogServerClient(environment: PostHogEnvironment, options: Omit<PostHogOptions, 'host'>) {\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 function createManagedPostHogServerTelemetry(options: ManagedPostHogServerTelemetryOptions) {\n let client: Promise<PostHog> | undefined\n let logProvider: Promise<LogProvider> | undefined\n let closed = false\n const context = new AsyncLocalStorage<PostHogTelemetryContext>()\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, managedClientOptions(options))\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.environment, 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 const loadClient = async () => {\n try {\n return await getClient()\n } catch (error) {\n report(error)\n return undefined\n }\n }\n\n async function withContext<T>(telemetryContext: PostHogTelemetryContext, work: () => T): Promise<Awaited<T>> {\n const inherited = context.getStore()\n const correlation = {\n ...(inherited?.distinctId ? { distinctId: inherited.distinctId } : {}),\n ...(inherited?.sessionId ? { sessionId: inherited.sessionId } : {}),\n ...telemetryContext,\n }\n const requestContext: PostHogTelemetryContext = {\n ...(correlation.distinctId ? { distinctId: correlation.distinctId } : {}),\n ...(correlation.sessionId ? { sessionId: correlation.sessionId } : {}),\n properties: {\n ...inherited?.properties,\n ...telemetryContext.properties,\n ...(correlation.sessionId ? { $session_id: correlation.sessionId } : {}),\n },\n }\n const run = () => context.run(requestContext, work)\n const value = await loadClient()\n return (value ? value.withContext(telemetryContext, run) : run()) as Awaited<T>\n }\n\n async function withRequestContext<T>(request: Request, requestOptions: PostHogRequestContextOptions, work: () => T): Promise<Awaited<T>> {\n return withContext(postHogRequestContext(request, requestOptions), work)\n }\n\n async function withSpan<T>(name: string, work: (span: PostHogTraceSpan) => T): Promise<Awaited<T>>\n async function withSpan<T>(name: string, spanOptions: StartSpanOptions, work: (span: PostHogTraceSpan) => T): Promise<Awaited<T>>\n async function withSpan<T>(\n name: string,\n optionsOrWork: StartSpanOptions | ((span: PostHogTraceSpan) => T),\n maybeWork?: (span: PostHogTraceSpan) => T,\n ): Promise<Awaited<T>> {\n const spanOptions = typeof optionsOrWork === 'function' ? undefined : optionsOrWork\n const work = typeof optionsOrWork === 'function' ? optionsOrWork : maybeWork!\n const value = await loadClient()\n if (!value) return work(undefined) as Awaited<T>\n return (spanOptions ? value.withSpan(name, spanOptions, work) : value.withSpan(name, work)) as Awaited<T>\n }\n\n const metrics = {\n count(name: string, value = 1, metricOptions?: CaptureMetricOptions) {\n return safely(async () => (await getClient())?.metrics.count(name, value, metricOptions))\n },\n gauge(name: string, value: number, metricOptions?: CaptureMetricOptions) {\n return safely(async () => (await getClient())?.metrics.gauge(name, value, metricOptions))\n },\n histogram(name: string, value: number, metricOptions?: CaptureMetricOptions) {\n return safely(async () => (await getClient())?.metrics.histogram(name, value, metricOptions))\n },\n }\n\n return {\n metrics,\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?: string, properties?: Record<string, unknown>) {\n await safely(async () => {\n const value = await getClient()\n const correlation = context.getStore()\n const capturedProperties = mergeProperties(properties, correlation?.properties)\n value?.captureException(error, distinctId ?? correlation?.distinctId ?? 'server', capturedProperties)\n })\n },\n async log(record: PostHogLogRecord) {\n await safely(async () => {\n const provider = await getLogProvider()\n const correlation = context.getStore()\n const attributes = boundedAttributes(\n mergeProperties(record.attributes, {\n ...(correlation?.distinctId ? { posthogDistinctId: correlation.distinctId } : {}),\n ...(correlation?.sessionId ? { sessionId: correlation.sessionId } : {}),\n }),\n )\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 flush() {\n await safely(async () => {\n const [value, provider] = await Promise.all([getClient(), getLogProvider()])\n await Promise.all([value?.flush(), provider?.forceFlush()])\n })\n },\n async startSpan(name: string, spanOptions?: StartSpanOptions) {\n return (await loadClient())?.startSpan(name, spanOptions)\n },\n withContext,\n withRequestContext,\n withSpan,\n async shutdown(timeoutMs = 10_000) {\n if (closed) return\n assertShutdownTimeout(timeoutMs)\n closed = true\n const results = await Promise.allSettled([\n // oxlint-disable-next-line no-underscore-dangle -- posthog-node's async shutdown API is named `_shutdown`.\n client?.then((value) => value._shutdown(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\nfunction managedClientOptions(options: ManagedPostHogServerTelemetryOptions): Omit<PostHogOptions, 'host'> {\n const { metrics, traces, ...clientOptions } = options.clientOptions ?? {}\n const service = {\n serviceName: options.serviceName,\n ...(options.serviceVersion ? { serviceVersion: options.serviceVersion } : {}),\n ...(options.deploymentEnvironment ? { environment: options.deploymentEnvironment } : {}),\n ...(options.resourceAttributes ? { resourceAttributes: options.resourceAttributes } : {}),\n }\n return {\n ...clientOptions,\n metrics: { ...service, ...metrics },\n traces: { ...service, ...traces },\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 createPostHogRpcObserver(\n telemetry: Pick<PostHogServerTelemetry, 'metrics' | 'withRequestContext' | 'withSpan'>,\n options: PostHogRpcObserverOptions = {},\n): RpcObserver {\n const metricPrefix = options.metricPrefix ?? 'server_function'\n const spanName = options.spanName ?? 'server_function'\n return async function observe<T>(request: Request | undefined, work: () => Promise<T>) {\n if (!request) return work()\n const method = request.method.toUpperCase()\n const identity = currentServerFunction()\n // A function name is bounded by the application's code, unlike its URL or caller.\n const attributes = identity ? { method, function: identity.name } : { method }\n const parent = request.headers.get('traceparent')\n const settled = await telemetry.withRequestContext(request, {}, () =>\n telemetry.withSpan(spanName, { kind: 'server', ...(parent ? { parent } : {}) }, async (span) => {\n const startedAt = performance.now()\n span?.setAttribute('http.request.method', method)\n if (identity) {\n span?.setAttribute('code.function.name', identity.name)\n span?.setAttribute('code.file.path', identity.filename)\n }\n let outcome = 'error'\n try {\n const value = await work()\n outcome = 'success'\n return { value }\n } catch (error) {\n const status = responseStatus(error)\n if (status === undefined || status >= 500) throw error\n span?.setAttribute('http.response.status_code', status)\n outcome = status >= 400 ? 'refused' : 'success'\n // Returning instead of throwing keeps an intended response from marking the span as failed.\n return { response: error }\n } finally {\n span?.setAttribute('server.function.outcome', outcome)\n await Promise.all([\n telemetry.metrics.count(`${metricPrefix}.requests`, 1, { attributes: { ...attributes, outcome } }),\n telemetry.metrics.histogram(`${metricPrefix}.duration`, Math.max(0, performance.now() - startedAt), {\n unit: 'ms',\n attributes,\n }),\n ])\n }\n }),\n )\n if ('response' in settled) throw settled.response\n return settled.value\n }\n}\n\n/** The status of a thrown `Response`, which `createRpc` rethrows as an `Error` whose cause is that response. */\nfunction responseStatus(error: unknown) {\n const response = error instanceof Error ? error.cause : error\n return response instanceof Response ? response.status : undefined\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(environment: PostHogEnvironment, options: ManagedPostHogServerTelemetryOptions) {\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: `${environment.host.replace(/\\/$/, '')}/i/v1/logs`,\n headers: { Authorization: `Bearer ${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 ...options.resourceAttributes,\n }),\n processors: [new BatchLogRecordProcessor({ exporter })],\n })\n}\n\nfunction mergeProperties(...values: Array<Record<string, unknown> | undefined>) {\n const merged = Object.assign({}, ...values.filter(Boolean))\n return Object.keys(merged).length ? merged : undefined\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, timeoutMs: number) {\n const timer = new AbortController()\n try {\n await Promise.race([\n provider.shutdown(),\n delay(timeoutMs, undefined, { ref: false, signal: timer.signal }).then(() => {\n throw new Error(`PostHog log shutdown timed out after ${timeoutMs}ms`)\n }),\n ])\n } finally {\n timer.abort()\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
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/posthog/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAA;AACpD,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAA;AAG1D,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAA;AAEpE,OAAO,EAAE,qBAAqB,EAAqC,MAAM,cAAc,CAAA;AAoDvF,KAAK,UAAU,yBAAyB,CAAC,WAA+B,EAAE,OAAqC;IAC7G,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;KAC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,EAAE;YACnB,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE;gBAC1E,MAAM,IAAI,KAAK,CAAC,wCAAwC,SAAS,IAAI,CAAC,CAAA;YACxE,CAAC,CAAC;SACH,CAAC,CAAA;IACJ,CAAC;YAAS,CAAC;QACT,KAAK,CAAC,KAAK,EAAE,CAAA;IACf,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 { AsyncLocalStorage } from 'node:async_hooks'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport type { CaptureMetricOptions, PostHog, PostHogOptions, Span, StartSpanOptions } from 'posthog-node'\nimport type { RpcErrorContext, RpcLogger, RpcObserver } from '../server/rpc.js'\nimport { currentServerFunction } from '../server/server-function.js'\nimport type { PostHogEnvironment } from './config.js'\nimport { postHogRequestContext, type PostHogRequestContextOptions } 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 resourceAttributes?: Record<string, string>\n clientOptions?: Omit<PostHogOptions, 'host'>\n onError?: (error: unknown) => void\n}\n\nexport type PostHogServerTelemetry = ReturnType<typeof createManagedPostHogServerTelemetry>\n\nexport type PostHogTelemetryContext = {\n distinctId?: string\n sessionId?: string\n properties?: Record<string, unknown>\n}\n\nexport type PostHogTraceSpan = Span | undefined\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\nexport type PostHogRpcObserverOptions = {\n metricPrefix?: string\n spanName?: 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\nasync function createPostHogServerClient(environment: PostHogEnvironment, options: Omit<PostHogOptions, 'host'>) {\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 function createManagedPostHogServerTelemetry(options: ManagedPostHogServerTelemetryOptions) {\n let client: Promise<PostHog> | undefined\n let logProvider: Promise<LogProvider> | undefined\n let closed = false\n const context = new AsyncLocalStorage<PostHogTelemetryContext>()\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, managedClientOptions(options))\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.environment, 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 const loadClient = async () => {\n try {\n return await getClient()\n } catch (error) {\n report(error)\n return undefined\n }\n }\n\n async function withContext<T>(telemetryContext: PostHogTelemetryContext, work: () => T): Promise<Awaited<T>> {\n const inherited = context.getStore()\n const correlation = {\n ...(inherited?.distinctId ? { distinctId: inherited.distinctId } : {}),\n ...(inherited?.sessionId ? { sessionId: inherited.sessionId } : {}),\n ...telemetryContext,\n }\n const requestContext: PostHogTelemetryContext = {\n ...(correlation.distinctId ? { distinctId: correlation.distinctId } : {}),\n ...(correlation.sessionId ? { sessionId: correlation.sessionId } : {}),\n properties: {\n ...inherited?.properties,\n ...telemetryContext.properties,\n ...(correlation.sessionId ? { $session_id: correlation.sessionId } : {}),\n },\n }\n const run = () => context.run(requestContext, work)\n const value = await loadClient()\n return (value ? value.withContext(telemetryContext, run) : run()) as Awaited<T>\n }\n\n async function withRequestContext<T>(request: Request, requestOptions: PostHogRequestContextOptions, work: () => T): Promise<Awaited<T>> {\n return withContext(postHogRequestContext(request, requestOptions), work)\n }\n\n async function withSpan<T>(name: string, work: (span: PostHogTraceSpan) => T): Promise<Awaited<T>>\n async function withSpan<T>(name: string, spanOptions: StartSpanOptions, work: (span: PostHogTraceSpan) => T): Promise<Awaited<T>>\n async function withSpan<T>(\n name: string,\n optionsOrWork: StartSpanOptions | ((span: PostHogTraceSpan) => T),\n maybeWork?: (span: PostHogTraceSpan) => T,\n ): Promise<Awaited<T>> {\n const spanOptions = typeof optionsOrWork === 'function' ? undefined : optionsOrWork\n const work = typeof optionsOrWork === 'function' ? optionsOrWork : maybeWork!\n const value = await loadClient()\n if (!value) return work(undefined) as Awaited<T>\n return (spanOptions ? value.withSpan(name, spanOptions, work) : value.withSpan(name, work)) as Awaited<T>\n }\n\n const metrics = {\n count(name: string, value = 1, metricOptions?: CaptureMetricOptions) {\n return safely(async () => (await getClient())?.metrics.count(name, value, metricOptions))\n },\n gauge(name: string, value: number, metricOptions?: CaptureMetricOptions) {\n return safely(async () => (await getClient())?.metrics.gauge(name, value, metricOptions))\n },\n histogram(name: string, value: number, metricOptions?: CaptureMetricOptions) {\n return safely(async () => (await getClient())?.metrics.histogram(name, value, metricOptions))\n },\n }\n\n return {\n metrics,\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?: string, properties?: Record<string, unknown>) {\n await safely(async () => {\n const value = await getClient()\n const correlation = context.getStore()\n const capturedProperties = mergeProperties(serverFunctionProperties(), properties, correlation?.properties)\n value?.captureException(error, distinctId ?? correlation?.distinctId ?? 'server', capturedProperties)\n })\n },\n async log(record: PostHogLogRecord) {\n await safely(async () => {\n const provider = await getLogProvider()\n const correlation = context.getStore()\n const attributes = boundedAttributes(\n mergeProperties(serverFunctionProperties(), record.attributes, {\n ...(correlation?.distinctId ? { posthogDistinctId: correlation.distinctId } : {}),\n ...(correlation?.sessionId ? { sessionId: correlation.sessionId } : {}),\n }),\n )\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 flush() {\n await safely(async () => {\n const [value, provider] = await Promise.all([getClient(), getLogProvider()])\n await Promise.all([value?.flush(), provider?.forceFlush()])\n })\n },\n async startSpan(name: string, spanOptions?: StartSpanOptions) {\n return (await loadClient())?.startSpan(name, spanOptions)\n },\n withContext,\n withRequestContext,\n withSpan,\n async shutdown(timeoutMs = 10_000) {\n if (closed) return\n assertShutdownTimeout(timeoutMs)\n closed = true\n const results = await Promise.allSettled([\n // oxlint-disable-next-line no-underscore-dangle -- posthog-node's async shutdown API is named `_shutdown`.\n client?.then((value) => value._shutdown(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\nfunction managedClientOptions(options: ManagedPostHogServerTelemetryOptions): Omit<PostHogOptions, 'host'> {\n const { metrics, traces, ...clientOptions } = options.clientOptions ?? {}\n const service = {\n serviceName: options.serviceName,\n ...(options.serviceVersion ? { serviceVersion: options.serviceVersion } : {}),\n ...(options.deploymentEnvironment ? { environment: options.deploymentEnvironment } : {}),\n ...(options.resourceAttributes ? { resourceAttributes: options.resourceAttributes } : {}),\n }\n return {\n ...clientOptions,\n metrics: { ...service, ...metrics },\n traces: { ...service, ...traces },\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 ...(context.function ? { server_function: context.function } : {}),\n ...(context.status === undefined ? {} : { response_status: context.status }),\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 createPostHogRpcObserver(\n telemetry: Pick<PostHogServerTelemetry, 'metrics' | 'withRequestContext' | 'withSpan'>,\n options: PostHogRpcObserverOptions = {},\n): RpcObserver {\n const metricPrefix = options.metricPrefix ?? 'server_function'\n const spanName = options.spanName ?? 'server_function'\n return async function observe<T>(request: Request | undefined, work: () => Promise<T>) {\n if (!request) return work()\n const method = request.method.toUpperCase()\n const identity = currentServerFunction()\n // A function name is bounded by the application's code, unlike its URL or caller.\n const attributes = identity ? { method, function: identity.name } : { method }\n const parent = request.headers.get('traceparent')\n const settled = await telemetry.withRequestContext(request, {}, () =>\n telemetry.withSpan(spanName, { kind: 'server', ...(parent ? { parent } : {}) }, async (span) => {\n const startedAt = performance.now()\n span?.setAttribute('http.request.method', method)\n if (identity) {\n span?.setAttribute('code.function.name', identity.name)\n span?.setAttribute('code.file.path', identity.filename)\n }\n let outcome = 'error'\n try {\n const value = await work()\n outcome = 'success'\n return { value }\n } catch (error) {\n const status = responseStatus(error)\n if (status !== undefined) span?.setAttribute('http.response.status_code', status)\n if (status === undefined || status >= 500) throw error\n outcome = status >= 400 ? 'refused' : 'success'\n // Returning instead of throwing keeps an intended response from marking the span as failed.\n return { response: error }\n } finally {\n span?.setAttribute('server.function.outcome', outcome)\n await Promise.all([\n telemetry.metrics.count(`${metricPrefix}.requests`, 1, { attributes: { ...attributes, outcome } }),\n telemetry.metrics.histogram(`${metricPrefix}.duration`, Math.max(0, performance.now() - startedAt), {\n unit: 'ms',\n attributes,\n }),\n ])\n }\n }),\n )\n if ('response' in settled) throw settled.response\n return settled.value\n }\n}\n\n/** The status of a thrown `Response`, which `createRpc` rethrows as an `Error` whose cause is that response. */\nfunction responseStatus(error: unknown) {\n const response = error instanceof Error ? error.cause : error\n return response instanceof Response ? response.status : undefined\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(environment: PostHogEnvironment, options: ManagedPostHogServerTelemetryOptions) {\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: `${environment.host.replace(/\\/$/, '')}/i/v1/logs`,\n headers: { Authorization: `Bearer ${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 ...options.resourceAttributes,\n }),\n processors: [new BatchLogRecordProcessor({ exporter })],\n })\n}\n\n/** Names the server function a log or exception was recorded in, so it reads without the request path's opaque id. */\nfunction serverFunctionProperties() {\n const name = currentServerFunction()?.name\n return name ? { server_function: name } : undefined\n}\n\nfunction mergeProperties(...values: Array<Record<string, unknown> | undefined>) {\n const merged = Object.assign({}, ...values.filter(Boolean))\n return Object.keys(merged).length ? merged : undefined\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, timeoutMs: number) {\n const timer = new AbortController()\n try {\n await Promise.race([\n provider.shutdown(),\n delay(timeoutMs, undefined, { ref: false, signal: timer.signal }).then(() => {\n throw new Error(`PostHog log shutdown timed out after ${timeoutMs}ms`)\n }),\n ])\n } finally {\n timer.abort()\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"]}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -2,4 +2,6 @@ export { errorHasCode } from './errors.js';
|
|
|
2
2
|
export { databaseHealthFailure, healthResponse } from './health.js';
|
|
3
3
|
export type { HealthFailure, HealthResponseOptions } from './health.js';
|
|
4
4
|
export type { RpcErrorContext, RpcLogger, RpcObserver, RpcOptions } from './rpc.js';
|
|
5
|
+
export { currentServerFunction } from './server-function.js';
|
|
6
|
+
export type { ServerFunctionIdentity } from './server-function.js';
|
|
5
7
|
export { clearGlobalSingleton, globalAsyncSingleton, globalSingleton, peekGlobalSingleton } from './singleton.js';
|
package/dist/server/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { errorHasCode } from './errors.js';
|
|
2
2
|
export { databaseHealthFailure, healthResponse } from './health.js';
|
|
3
|
+
export { currentServerFunction } from './server-function.js';
|
|
3
4
|
export { clearGlobalSingleton, globalAsyncSingleton, globalSingleton, peekGlobalSingleton } from './singleton.js';
|
|
4
5
|
//# sourceMappingURL=index.js.map
|
package/dist/server/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC1C,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAGnE,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAA","sourcesContent":["export { errorHasCode } from './errors.js'\nexport { databaseHealthFailure, healthResponse } from './health.js'\nexport type { HealthFailure, HealthResponseOptions } from './health.js'\nexport type { RpcErrorContext, RpcLogger, RpcObserver, RpcOptions } from './rpc.js'\nexport { clearGlobalSingleton, globalAsyncSingleton, globalSingleton, peekGlobalSingleton } from './singleton.js'\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC1C,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAGnE,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAA;AAE5D,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAA","sourcesContent":["export { errorHasCode } from './errors.js'\nexport { databaseHealthFailure, healthResponse } from './health.js'\nexport type { HealthFailure, HealthResponseOptions } from './health.js'\nexport type { RpcErrorContext, RpcLogger, RpcObserver, RpcOptions } from './rpc.js'\nexport { currentServerFunction } from './server-function.js'\nexport type { ServerFunctionIdentity } from './server-function.js'\nexport { clearGlobalSingleton, globalAsyncSingleton, globalSingleton, peekGlobalSingleton } from './singleton.js'\n"]}
|
package/dist/server/rpc.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
/** Where a failure happened: the request, the server function it ran when the identity middleware names it, and the status of a thrown `Response`. */
|
|
1
2
|
export type RpcErrorContext = {
|
|
2
3
|
method?: string;
|
|
3
4
|
path?: string;
|
|
5
|
+
function?: string;
|
|
6
|
+
status?: number;
|
|
4
7
|
};
|
|
5
8
|
export type RpcLogger = (error: unknown, context: RpcErrorContext, request?: Request) => void | Promise<void>;
|
|
6
9
|
export type RpcObserver = <T>(request: Request | undefined, work: () => Promise<T>) => Promise<T>;
|
package/dist/server/rpc.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { currentServerFunction } from './server-function.js';
|
|
1
2
|
export function createRpc(options = {}) {
|
|
2
3
|
async function rpc(work) {
|
|
3
4
|
return run(work, resolveRequest(options.getRequest));
|
|
@@ -7,13 +8,16 @@ export function createRpc(options = {}) {
|
|
|
7
8
|
try {
|
|
8
9
|
return await work();
|
|
9
10
|
}
|
|
10
|
-
catch (
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
11
|
+
catch (thrown) {
|
|
12
|
+
const status = thrown instanceof Response ? thrown.status : undefined;
|
|
13
|
+
const error = thrown instanceof Response ? new Error((await thrown.text()) || `request failed (${thrown.status})`, { cause: thrown }) : thrown;
|
|
14
|
+
// A 4xx answer is the caller's to fix; a 5xx one, such as an unreachable upstream, is the server's.
|
|
15
|
+
if (status === undefined || status >= 500) {
|
|
16
|
+
try {
|
|
17
|
+
await options.logError?.(error, requestContext(request, status), request);
|
|
18
|
+
}
|
|
19
|
+
catch { }
|
|
15
20
|
}
|
|
16
|
-
catch { }
|
|
17
21
|
throw error;
|
|
18
22
|
}
|
|
19
23
|
};
|
|
@@ -37,7 +41,12 @@ function resolveRequest(getRequest) {
|
|
|
37
41
|
return undefined;
|
|
38
42
|
}
|
|
39
43
|
}
|
|
40
|
-
function requestContext(request) {
|
|
41
|
-
|
|
44
|
+
function requestContext(request, status) {
|
|
45
|
+
const name = currentServerFunction()?.name;
|
|
46
|
+
return {
|
|
47
|
+
...(request ? { method: request.method, path: new URL(request.url).pathname } : {}),
|
|
48
|
+
...(name ? { function: name } : {}),
|
|
49
|
+
...(status === undefined ? {} : { status }),
|
|
50
|
+
};
|
|
42
51
|
}
|
|
43
52
|
//# sourceMappingURL=rpc.js.map
|
package/dist/server/rpc.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rpc.js","sourceRoot":"","sources":["../../src/server/rpc.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"rpc.js","sourceRoot":"","sources":["../../src/server/rpc.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAA;AAc5D,MAAM,UAAU,SAAS,CAAC,OAAO,GAAe,EAAE;IAChD,KAAK,UAAU,GAAG,CAAI,IAA0B;QAC9C,OAAO,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAA;IACtD,CAAC;IAED,KAAK,UAAU,GAAG,CAAI,IAA0B,EAAE,OAA4B;QAC5E,MAAM,OAAO,GAAG,KAAK,IAAI,EAAE;YACzB,IAAI,CAAC;gBACH,OAAO,MAAM,IAAI,EAAE,CAAA;YACrB,CAAC;YAAC,OAAO,MAAM,EAAE,CAAC;gBAChB,MAAM,MAAM,GAAG,MAAM,YAAY,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAA;gBACrE,MAAM,KAAK,GACT,MAAM,YAAY,QAAQ,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC,IAAI,mBAAmB,MAAM,CAAC,MAAM,GAAG,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,CAAA;gBAClI,oGAAoG;gBACpG,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,IAAI,GAAG,EAAE,CAAC;oBAC1C,IAAI,CAAC;wBACH,MAAM,OAAO,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,cAAc,CAAC,OAAO,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,CAAA;oBAC3E,CAAC;oBAAC,MAAM,CAAC,CAAA,CAAC;gBACZ,CAAC;gBACD,MAA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CAAC;KAC5C,CAAA;AACH,CAAC","sourcesContent":["import { currentServerFunction } from './server-function.js'\n\n/** Where a failure happened: the request, the server function it ran when the identity middleware names it, and the status of a thrown `Response`. */\nexport type RpcErrorContext = { method?: string; path?: string; function?: string; status?: number }\nexport type RpcLogger = (error: unknown, context: RpcErrorContext, request?: Request) => void | Promise<void>\nexport type RpcObserver = <T>(request: Request | undefined, work: () => Promise<T>) => Promise<T>\n\nexport type RpcOptions = {\n getRequest?: () => Request\n requireMutation?: (request: Request) => void\n logError?: RpcLogger\n observe?: RpcObserver\n}\n\nexport function createRpc(options: RpcOptions = {}) {\n async function rpc<T>(work: () => Promise<T> | T): Promise<T> {\n return run(work, resolveRequest(options.getRequest))\n }\n\n async function run<T>(work: () => Promise<T> | T, request: Request | undefined): Promise<T> {\n const execute = async () => {\n try {\n return await work()\n } catch (thrown) {\n const status = thrown instanceof Response ? thrown.status : undefined\n const error =\n thrown instanceof Response ? new Error((await thrown.text()) || `request failed (${thrown.status})`, { cause: thrown }) : thrown\n // A 4xx answer is the caller's to fix; a 5xx one, such as an unreachable upstream, is the server's.\n if (status === undefined || status >= 500) {\n try {\n await options.logError?.(error, requestContext(request, status), request)\n } catch {}\n }\n throw error\n }\n }\n return options.observe ? options.observe(request, execute) : execute()\n }\n\n function mutationRpc<T>(work: () => Promise<T> | T, request = resolveRequest(options.getRequest)) {\n return run(() => {\n if (!request) throw new Error('mutation request is unavailable')\n options.requireMutation?.(request)\n return work()\n }, request)\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, status: number | undefined): RpcErrorContext {\n const name = currentServerFunction()?.name\n return {\n ...(request ? { method: request.method, path: new URL(request.url).pathname } : {}),\n ...(name ? { function: name } : {}),\n ...(status === undefined ? {} : { status }),\n }\n}\n"]}
|