Skip to content

fix(cloudflare): Import types explicitly from worker-types #16704

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
},
"devDependencies": {
"@cloudflare/vitest-pool-workers": "^0.8.31",
"@cloudflare/workers-types": "^4.20250521.0",
"@cloudflare/workers-types": "^4.20250620.0",
"vitest": "3.1.0",
"wrangler": "^4.16.0"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,19 @@ app.notFound(ctx => {
return ctx.json({ message: 'Not Found' }, 404);
});

class MyDurableObjectBase extends DurableObject<Env> {
// impl
}

// Typecheck that the instrumented durable object is valid
export const MyDurableObject = Sentry.instrumentDurableObjectWithSentry(
(env: Env) => ({
dsn: env?.E2E_TEST_DSN,
tracesSampleRate: 1.0,
}),
MyDurableObjectBase,
);

export default Sentry.withSentry(
(env: Env) => ({
dsn: env?.E2E_TEST_DSN,
Expand Down
5 changes: 2 additions & 3 deletions packages/cloudflare/src/durableobject.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* eslint-disable @typescript-eslint/unbound-method */
import type { DurableObject, DurableObjectState, ExecutionContext } from '@cloudflare/workers-types';
import {
captureException,
flush,
Expand All @@ -9,7 +9,6 @@ import {
withIsolationScope,
withScope,
} from '@sentry/core';
import type { DurableObject } from 'cloudflare:workers';
import { setAsyncLocalStorageAsyncContextStrategy } from './async';
import type { CloudflareOptions } from './client';
import { isInstrumented, markAsInstrumented } from './instrument';
Expand Down Expand Up @@ -135,7 +134,7 @@ function wrapMethodWithSentry<T extends (...args: any[]) => any>(
*/
export function instrumentDurableObjectWithSentry<
E,
T extends DurableObject<E>,
T extends Partial<DurableObject>,
C extends new (state: DurableObjectState, env: E) => T,
>(optionsCallback: (env: E) => CloudflareOptions, DurableObjectClass: C): C {
return new Proxy(DurableObjectClass, {
Expand Down
8 changes: 8 additions & 0 deletions packages/cloudflare/src/handler.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
import type {
EmailExportedHandler,
ExportedHandler,
ExportedHandlerFetchHandler,
ExportedHandlerQueueHandler,
ExportedHandlerScheduledHandler,
ExportedHandlerTailHandler,
} from '@cloudflare/workers-types';
import {
captureException,
flush,
Expand Down
11 changes: 8 additions & 3 deletions packages/cloudflare/src/pages-plugin.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { EventPluginContext, PagesPluginFunction } from '@cloudflare/workers-types';
import { setAsyncLocalStorageAsyncContextStrategy } from './async';
import type { CloudflareOptions } from './client';
import { wrapRequestHandler } from './request';
Expand Down Expand Up @@ -49,8 +50,12 @@ export function sentryPagesPlugin<
setAsyncLocalStorageAsyncContextStrategy();
return context => {
const options = typeof handlerOrOptions === 'function' ? handlerOrOptions(context) : handlerOrOptions;
return wrapRequestHandler({ options, request: context.request, context: { ...context, props: {} } }, () =>
context.next(),
);
return wrapRequestHandler(
{ options, request: context.request, context: { ...context, props: {} } },
() => context.next() as unknown as Promise<Response>,
// Need to use `any` here because the return type does not work with Cloudflare's Response type.
// Returning `PagesPluginFunction` in the wrapper function should take care of type safety.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
) as any;
};
}
8 changes: 6 additions & 2 deletions packages/cloudflare/src/request.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import type { ExecutionContext, IncomingRequestCfProperties } from '@cloudflare/workers-types';
import type {
ExecutionContext,
IncomingRequestCfProperties,
Request as CloudflareRequest,
} from '@cloudflare/workers-types';
import {
captureException,
continueTrace,
Expand All @@ -16,7 +20,7 @@ import { init } from './sdk';

interface RequestHandlerWrapperOptions {
options: CloudflareOptions;
request: Request<unknown, IncomingRequestCfProperties<unknown>>;
request: CloudflareRequest<unknown, IncomingRequestCfProperties<unknown>>;
context: ExecutionContext;
}

Expand Down
4 changes: 2 additions & 2 deletions packages/cloudflare/src/scope-utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { IncomingRequestCfProperties } from '@cloudflare/workers-types';
import type { IncomingRequestCfProperties, Request as CloudflareRequest } from '@cloudflare/workers-types';
import type { Scope } from '@sentry/core';
import { winterCGRequestToRequestData } from '@sentry/core';

Expand All @@ -23,6 +23,6 @@ export function addCultureContext(scope: Scope, cf: IncomingRequestCfProperties)
/**
* Set request data on scope
*/
export function addRequest(scope: Scope, request: Request): void {
export function addRequest(scope: Scope, request: CloudflareRequest): void {
scope.setSDKProcessingMetadata({ normalizedRequest: winterCGRequestToRequestData(request) });
}
87 changes: 87 additions & 0 deletions packages/cloudflare/src/vendor/workflow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable @typescript-eslint/member-ordering */
/* eslint-disable jsdoc/require-jsdoc */
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
// This file vendors in worker types in `cloudflare:workers` because they are not
// exported from `@cloudflare/workers-types` yet.

/* ! *****************************************************************************
Copyright (c) Cloudflare. All rights reserved.
Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */

import type { ExecutionContext, Rpc } from '@cloudflare/workers-types';

const __WORKFLOW_ENTRYPOINT_BRAND = '__WORKFLOW_ENTRYPOINT_BRAND' as const;

export type WorkflowEvent<T> = {
payload: Readonly<T>;
timestamp: Date;
instanceId: string;
};

export type WorkflowStepEvent<T> = {
payload: Readonly<T>;
timestamp: Date;
type: string;
};

export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;
export type WorkflowDelayDuration = WorkflowSleepDuration;
export type WorkflowTimeoutDuration = WorkflowSleepDuration;
export type WorkflowRetentionDuration = WorkflowSleepDuration;

export type WorkflowBackoff = 'constant' | 'linear' | 'exponential';

export type WorkflowStepConfig = {
retries?: {
limit: number;
delay: WorkflowDelayDuration | number;
backoff?: WorkflowBackoff;
};
timeout?: WorkflowTimeoutDuration | number;
};

export abstract class WorkflowStep {
do<T extends Rpc.Serializable<T>>(name: string, callback: () => Promise<T>): Promise<T>;
// @ts-expect-error - This is a vendor file, so we don't need to implement the method.
do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfig, callback: () => Promise<T>): Promise<T>;
// @ts-expect-error - This is a vendor file, so we don't need to implement the method.
sleep: (name: string, duration: WorkflowSleepDuration) => Promise<void>;
// @ts-expect-error - This is a vendor file, so we don't need to implement the method.
sleepUntil: (name: string, timestamp: Date | number) => Promise<void>;
// @ts-expect-error - This is a vendor file, so we don't need to implement the method.
waitForEvent<T extends Rpc.Serializable<T>>(
name: string,
options: {
type: string;
timeout?: WorkflowTimeoutDuration | number;
},
): Promise<WorkflowStepEvent<T>>;
}

export abstract class WorkflowEntrypoint<Env = unknown, T extends Rpc.Serializable<T> | unknown = unknown>
implements Rpc.WorkflowEntrypointBranded
{
// @ts-expect-error - This is a vendor file, so we don't need to implement the property.
[__WORKFLOW_ENTRYPOINT_BRAND]: never;
// @ts-expect-error - This is a vendor file, so we don't need to implement the property.
protected ctx: ExecutionContext;
// @ts-expect-error - This is a vendor file, so we don't need to implement the property.
protected env: Env;
// @ts-expect-error - This is a vendor file, so we don't need to implement the constructor.
constructor(ctx: ExecutionContext, env: Env);
// @ts-expect-error - This is a vendor file, so we don't need to implement the method.
run(event: Readonly<WorkflowEvent<T>>, step: WorkflowStep): Promise<unknown>;
}
11 changes: 6 additions & 5 deletions packages/cloudflare/src/workflows.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { ExecutionContext, Rpc } from '@cloudflare/workers-types';
import type { PropagationContext } from '@sentry/core';
import {
captureException,
Expand All @@ -8,6 +9,10 @@ import {
withIsolationScope,
withScope,
} from '@sentry/core';
import { setAsyncLocalStorageAsyncContextStrategy } from './async';
import type { CloudflareOptions } from './client';
import { addCloudResourceContext } from './scope-utils';
import { init } from './sdk';
import type {
WorkflowEntrypoint,
WorkflowEvent,
Expand All @@ -16,11 +21,7 @@ import type {
WorkflowStepConfig,
WorkflowStepEvent,
WorkflowTimeoutDuration,
} from 'cloudflare:workers';
import { setAsyncLocalStorageAsyncContextStrategy } from './async';
import type { CloudflareOptions } from './client';
import { addCloudResourceContext } from './scope-utils';
import { init } from './sdk';
} from './vendor/workflow';

const UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;

Expand Down
2 changes: 1 addition & 1 deletion packages/cloudflare/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@

"compilerOptions": {
"module": "esnext",
"types": ["node", "@cloudflare/workers-types"]
"types": ["node"]
}
}
3 changes: 2 additions & 1 deletion packages/sveltekit/src/worker/cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ export function initCloudflareSentryHandle(options: CloudflareOptions): Handle {
return wrapRequestHandler(
{
options: opts,
request: event.request as Request<unknown, IncomingRequestCfProperties<unknown>>,
// @ts-expect-error Cloudflare's `request` type is not compatible with `Request` type.
request: event.request,
// @ts-expect-error This will exist in Cloudflare
context: event.platform.context,
},
Expand Down
Loading