cfw-graphql-bootstrap 1.0.9 → 1.0.10

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/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import { BaseContext as BaseContext$1, ApolloServerOptions, ApolloServerPlugin } from '@apollo/server';
2
2
  import { ExecutionContext } from '@cloudflare/workers-types';
3
3
  import { CloudflareContextFunctionArgument } from '@as-integrations/cloudflare-workers';
4
- import { GraphQLSchema, GraphQLError, DocumentNode } from 'graphql';
4
+ import { GraphQLSchema, GraphQLError, DocumentNode, GraphQLFormattedError } from 'graphql';
5
5
  import { Hono, MiddlewareHandler } from 'hono';
6
6
  import { ApolloServerErrorCode } from '@apollo/server/errors';
7
+ import { Logger } from 'pino';
7
8
  import DataLoader, { BatchLoadFn, Options } from 'dataloader';
8
9
  import { KeyValueCache, KeyValueCacheSetOptions } from '@apollo/utils.keyvaluecache';
9
10
  export { gql } from 'graphql-tag';
@@ -320,18 +321,119 @@ declare class EnvironmentLoader {
320
321
  }
321
322
  declare const envLoader: EnvironmentLoader;
322
323
 
323
- interface JaegerContext {
324
- rootSpan?: {
325
- getBaggageItem: (key: string) => string | undefined;
324
+ /**
325
+ * Cloudflare Workers Tracing Wrapper
326
+ *
327
+ * Cloudflare Workers now provides automatic tracing with zero configuration.
328
+ * This wrapper provides additional context and manual span creation when needed.
329
+ *
330
+ * Key features:
331
+ * - Automatic instrumentation of all I/O operations (KV, R2, D1, etc.)
332
+ * - OpenTelemetry-compliant spans
333
+ * - Zero-config setup when enabled in wrangler.toml
334
+ */
335
+ interface TraceContext {
336
+ traceId: string;
337
+ spanId: string;
338
+ parentSpanId?: string;
339
+ baggage?: Record<string, string>;
340
+ }
341
+ /**
342
+ * Extract W3C Trace Context from headers
343
+ * Format: traceparent: 00-{traceId}-{spanId}-{flags}
344
+ */
345
+ declare function extractTraceContext(headers: Headers): TraceContext | null;
346
+ /**
347
+ * Generate W3C Trace Context header
348
+ */
349
+ declare function generateTraceHeader(context: TraceContext): string;
350
+ /**
351
+ * Generate trace ID (32 hex chars / 128 bits)
352
+ */
353
+ declare function generateTraceId(): string;
354
+ /**
355
+ * Generate span ID (16 hex chars / 64 bits)
356
+ */
357
+ declare function generateSpanId(): string;
358
+ /**
359
+ * Custom span for manual instrumentation
360
+ * This is useful when you want to track specific operations
361
+ * that aren't automatically instrumented
362
+ */
363
+ declare class WorkerSpan {
364
+ readonly name: string;
365
+ readonly spanId: string;
366
+ readonly traceId: string;
367
+ readonly parentSpanId?: string;
368
+ private startTime;
369
+ private endTime?;
370
+ private attributes;
371
+ private events;
372
+ constructor(name: string, spanId: string, traceId: string, parentSpanId?: string);
373
+ setAttribute(key: string, value: any): this;
374
+ setAttributes(attributes: Record<string, any>): this;
375
+ addEvent(name: string, attributes?: Record<string, any>): this;
376
+ end(): void;
377
+ toJSON(): {
378
+ name: string;
379
+ spanId: string;
380
+ traceId: string;
381
+ parentSpanId: string;
382
+ startTime: number;
383
+ endTime: number;
384
+ duration: number;
385
+ attributes: Record<string, any>;
386
+ events: {
387
+ name: string;
388
+ timestamp: number;
389
+ attributes?: Record<string, any>;
390
+ }[];
326
391
  };
327
392
  }
328
- interface BaseContext extends JaegerContext, BaseContext$1 {
393
+ /**
394
+ * Tracer for Cloudflare Workers
395
+ * Provides manual span creation for custom instrumentation
396
+ */
397
+ declare class WorkerTracer {
398
+ private readonly traceContext;
399
+ private readonly executionContext?;
400
+ private spans;
401
+ constructor(traceContext: TraceContext, executionContext?: ExecutionContext);
402
+ createSpan(name: string, parentSpanId?: string): WorkerSpan;
403
+ /**
404
+ * Run a function within a span
405
+ */
406
+ trace<T>(name: string, fn: (span: WorkerSpan) => Promise<T>): Promise<T>;
407
+ /**
408
+ * Export spans (for custom logging or external systems)
409
+ */
410
+ exportSpans(): Array<ReturnType<WorkerSpan['toJSON']>>;
411
+ /**
412
+ * Log spans to console (useful for development)
413
+ */
414
+ logSpans(): void;
415
+ /**
416
+ * Send spans to external observability platform via fetch
417
+ * This can be used with waitUntil to avoid blocking the response
418
+ */
419
+ sendToObservabilityPlatform(endpoint: string, headers?: Record<string, string>): Promise<void>;
420
+ }
421
+ /**
422
+ * Create a tracer instance for the current request
423
+ */
424
+ declare function createTracer(headers: Headers, executionContext?: ExecutionContext): WorkerTracer;
425
+
426
+ interface BaseContext extends BaseContext$1 {
329
427
  user?: ContextUser;
330
428
  logger: typeof logger;
331
429
  executionCtx: ExecutionContext;
332
430
  cache?: KVCache;
333
431
  db?: D1Database;
334
432
  env: EnvConfig;
433
+ traceContext?: TraceContext;
434
+ tracer?: WorkerTracer;
435
+ traceId?: string;
436
+ spanId?: string;
335
437
  /** @deprecated should not be used directly */
336
438
  authorization: string;
337
439
  clientId: string;
@@ -411,6 +513,18 @@ interface ValidationOptions {
411
513
  }
412
514
  declare function createValidationMiddleware(options?: ValidationOptions): MiddlewareHandler;
413
515
 
516
+ /**
517
+ * Cloudflare Workers Native Tracing Middleware
518
+ *
519
+ * This middleware integrates with Cloudflare's automatic tracing feature.
520
+ * When enabled in wrangler.toml, CF automatically traces all I/O operations.
521
+ *
522
+ * This middleware:
523
+ * 1. Extracts or creates W3C Trace Context (traceparent header)
524
+ * 2. Propagates trace context through the request
525
+ * 3. Provides manual tracing capabilities for custom spans
526
+ * 4. Logs trace information for correlation
527
+ */
414
528
  declare function createTracingMiddleware(): MiddlewareHandler;
415
529
 
416
530
  interface HealthCheckOptions {
@@ -424,6 +538,12 @@ declare function configureHealthChecks(app: Hono<{
424
538
  };
425
539
  }>, options?: HealthCheckOptions): void;
426
540
 
541
+ /**
542
+ * Apollo Server plugin for GraphQL operation tracing
543
+ * Integrates with Cloudflare Workers native tracing
544
+ */
545
+ declare function createTracingPlugin<TContext extends BaseContext>(): ApolloServerPlugin<TContext>;
546
+
427
547
  declare enum ErrorCode {
428
548
  UNAUTHENTICATED = "UNAUTHENTICATED",
429
549
  FORBIDDEN = "FORBIDDEN",
@@ -445,6 +565,22 @@ type SchemaModule = ReturnType<typeof createSchemaModule>;
445
565
 
446
566
  declare const getNonUserInputErrors: (errors: readonly GraphQLError[]) => GraphQLError[];
447
567
 
568
+ /**
569
+ * Sanitizes Prisma errors before sending to client
570
+ * Removes implementation details like "prisma.speaker.create()"
571
+ */
572
+ declare function sanitizePrismaError(error: any, logger?: Logger): GraphQLError;
573
+ /**
574
+ * Wraps async resolver functions to catch and sanitize Prisma errors
575
+ */
576
+ declare function withPrismaErrorHandling<T extends (...args: any[]) => Promise<any>>(fn: T, logger?: Logger): T;
577
+
578
+ /**
579
+ * Format error function that sanitizes Prisma errors
580
+ * This is used in Apollo Server configuration
581
+ */
582
+ declare function formatError(formattedError: GraphQLFormattedError, error: unknown): GraphQLFormattedError;
583
+
448
584
  type DataSources = Record<string, any>;
449
585
  type DataSourcesFn = <TContext extends BaseContext = BaseContext>(cache: KVCache, contextValue: TContext) => DataSources;
450
586
  type ComputedContext<TDatasource, TContext extends BaseContext> = TContext & {
@@ -574,8 +710,22 @@ declare global {
574
710
  * }
575
711
  *
576
712
  * async getUser(id: string) {
713
+ * // Just use Prisma normally - errors are sanitized by Apollo plugin
577
714
  * return this.client.user.findUnique({ where: { id } });
578
715
  * }
716
+ *
717
+ * async createUser(data: CreateUserInput) {
718
+ * // Prisma errors like "Unique constraint" are automatically sanitized
719
+ * return this.client.user.create({ data });
720
+ * }
721
+ *
722
+ * async updateUser(id: string, data: UpdateUserInput) {
723
+ * // Clean, simple code - error handling is in the GraphQL layer
724
+ * return this.client.user.update({
725
+ * where: { id },
726
+ * data
727
+ * });
728
+ * }
579
729
  * }
580
730
  *
581
731
  * // Multiple instances share the same client efficiently:
@@ -626,4 +776,4 @@ declare abstract class PrismaD1Datasource<TContext extends BaseContext = BaseCon
626
776
  }): Promise<number>;
627
777
  }
628
778
 
629
- export { AbstractDatasource, ApolloDataSources, ApolloKVAdapter, AppError, type BaseContext, type BaseDatasource, type BaseServerOptions, BatchingDataSource, type CacheOptions, CachedDataLoader, type ComputedContext, type ContextExtendFunction, type ContextUser, type EnvConfig, ErrorCode, InMemoryCache, KVCache, type PrismaClientLike, type PrismaD1, PrismaD1Datasource, type RestClientOptions, RestDatasource, type Runner, type SchemaModule, ServerBuilder, type ServerConfig, type ServerOptions, cached, configureHealthChecks, createApolloCache, createApolloLoggingPlugin, createBatchingDataSource, createCache, createContextFunction, createGraphQLServer, createRateLimitMiddleware, createSchemaModule, createTracingMiddleware, createValidationMiddleware, ensureBatchOrder, ensureBatchOrderNullable, envLoader, getNonUserInputErrors, logger };
779
+ export { AbstractDatasource, ApolloDataSources, ApolloKVAdapter, AppError, type BaseContext, type BaseDatasource, type BaseServerOptions, BatchingDataSource, type CacheOptions, CachedDataLoader, type ComputedContext, type ContextExtendFunction, type ContextUser, type EnvConfig, ErrorCode, InMemoryCache, KVCache, type PrismaClientLike, type PrismaD1, PrismaD1Datasource, type RestClientOptions, RestDatasource, type Runner, type SchemaModule, ServerBuilder, type ServerConfig, type ServerOptions, type TraceContext, WorkerSpan, WorkerTracer, cached, configureHealthChecks, createApolloCache, createApolloLoggingPlugin, createBatchingDataSource, createCache, createContextFunction, createGraphQLServer, createRateLimitMiddleware, createSchemaModule, createTracer, createTracingMiddleware, createTracingPlugin, createValidationMiddleware, ensureBatchOrder, ensureBatchOrderNullable, envLoader, extractTraceContext, formatError, generateSpanId, generateTraceHeader, generateTraceId, getNonUserInputErrors, logger, sanitizePrismaError, withPrismaErrorHandling };