diff --git a/app/api/platform-content/[platform]/[runtime]/[framework]/[...includePath]/route.ts b/app/api/platform-content/[platform]/[runtime]/[framework]/[...includePath]/route.ts new file mode 100644 index 0000000000000..acfaca67ac4f3 --- /dev/null +++ b/app/api/platform-content/[platform]/[runtime]/[framework]/[...includePath]/route.ts @@ -0,0 +1,161 @@ +import { + PlatformContentPayload, + RUNTIMES, +} from 'sentry-docs/components/frameworkSelector/frameworks'; +import {resolvePlatformContent} from 'sentry-docs/components/platformContent'; +import {getFileBySlugWithCache} from 'sentry-docs/mdx'; + +/** + * Serves the compiled MDX of a `` include as it applies to a framework running + * on a runtime, so a runtime's page can swap in framework snippets client-side + * (see ``). + * + * Only the combinations from `generateStaticParams` are built; there is no runtime rendering. + */ + +export const dynamic = 'force-static'; +export const dynamicParams = false; + +export function generateStaticParams() { + return Object.entries(RUNTIMES).flatMap(([runtime, {frameworks, includePaths}]) => + frameworks.flatMap(({key: framework}) => + includePaths.map(includePath => ({ + platform: 'javascript', + runtime, + framework, + includePath: includePath.split('/'), + })) + ) + ); +} + +type SlugFile = Awaited>; + +async function tryGetFile(slug: string): Promise { + try { + return await getFileBySlugWithCache(slug); + } catch { + return undefined; + } +} + +/** + * Resolves an include for a framework on a runtime: + * 1. `..`, for snippets specific to both + * 2. On Node.js, the framework guide's content, which falls back to Node.js + * Elsewhere, only a `.` snippet, to not pull in Node.js content + * 3. The runtime guide's own content + */ +async function resolveForFramework( + includePath: string, + platform: string, + runtime: string, + framework: string +): Promise { + const base = `platform-includes/${includePath}/${platform}`; + + const doc = await tryGetFile(`${base}.${runtime}.${framework}`); + if (doc) { + return doc; + } + + if (runtime === 'node') { + return resolvePlatformContent({ + includePath, + path: ['platforms', platform, 'guides', framework], + }); + } + + return ( + (await tryGetFile(`${base}.${framework}`)) ?? + resolvePlatformContent({ + includePath, + path: ['platforms', platform, 'guides', runtime], + }) + ); +} + +const INCLUDE_RE = / Promise, + payload: PlatformContentPayload +) { + for (const [, rawName] of source.matchAll(INCLUDE_RE)) { + const name = rawName.replace(/\.mdx$/, ''); + if (name in payload.includes) { + continue; + } + // Missing includes render nothing, same as . + const doc = await tryGetFile(`includes/${name}`); + if (doc) { + payload.includes[name] = doc.mdxSource; + await collectNested(doc.matter.content, resolve, payload); + } + } + + for (const [, includePath] of source.matchAll(PLATFORM_CONTENT_RE)) { + if (includePath in payload.platformContents) { + continue; + } + const doc = await resolve(includePath); + payload.platformContents[includePath] = doc?.mdxSource ?? null; + if (doc) { + await collectNested(doc.matter.content, resolve, payload); + } + } +} + +async function buildPayload( + includePath: string, + resolve: (includePath: string) => Promise +): Promise { + const doc = await resolve(includePath); + const payload: PlatformContentPayload = { + changed: false, + code: doc?.mdxSource ?? null, + includes: {}, + platformContents: {}, + }; + if (doc) { + await collectNested(doc.matter.content, resolve, payload); + } + return payload; +} + +export async function GET( + _request: Request, + { + params, + }: { + params: Promise<{ + framework: string; + includePath: string[]; + platform: string; + runtime: string; + }>; + } +) { + const {platform, runtime, framework, includePath} = await params; + const resolve = (path: string) => + resolveForFramework(path, platform, runtime, framework); + + const resolveForRuntime = (path: string) => + resolvePlatformContent({ + includePath: path, + path: ['platforms', platform, 'guides', runtime], + }); + + const [payload, runtimePayload] = await Promise.all([ + buildPayload(includePath.join('/'), resolve), + buildPayload(includePath.join('/'), resolveForRuntime), + ]); + payload.changed = + payload.code !== runtimePayload.code || + JSON.stringify(payload.platformContents) !== + JSON.stringify(runtimePayload.platformContents); + + return Response.json(payload); +} diff --git a/app/platform-redirect/page.tsx b/app/platform-redirect/page.tsx index 8ae7d7f0d7a64..858edc12f0828 100644 --- a/app/platform-redirect/page.tsx +++ b/app/platform-redirect/page.tsx @@ -7,7 +7,7 @@ import {SmartLink} from 'sentry-docs/components/smartLink'; import {extractPlatforms, getDocsRootNode, nodeForPath} from 'sentry-docs/docTree'; import {setServerContext} from 'sentry-docs/serverContext'; -import {platformUrlFor, sanitizeNext} from './utils'; +import {landingPageFallbackGuide, platformUrlFor, sanitizeNext} from './utils'; export const metadata: Metadata = { robots: 'noindex', @@ -142,9 +142,11 @@ export default async function Page(props: { const requestedPlatform = Array.isArray(platform) ? platform[0] : platform; if (requestedPlatform) { - const validPlatform = platformOrGuideList.find( - p => p.key === requestedPlatform?.toLowerCase() - ); + const requestedKey = requestedPlatform.toLowerCase(); + const fallbackKey = landingPageFallbackGuide(rootNode, requestedKey); + const validPlatform = + platformOrGuideList.find(p => p.key === requestedKey) ?? + platformOrGuideList.find(p => p.key === fallbackKey); if (validPlatform) { return redirect(platformUrlFor(validPlatform.url, sanitized)); } diff --git a/app/platform-redirect/utils.spec.ts b/app/platform-redirect/utils.spec.ts index 3b14c5b7f79df..a55e6f20f5e43 100644 --- a/app/platform-redirect/utils.spec.ts +++ b/app/platform-redirect/utils.spec.ts @@ -1,11 +1,54 @@ +import type {DocNode} from 'sentry-docs/docTree'; import {describe, expect, it} from 'vitest'; -import {platformUrlFor, sanitizeNext} from './utils'; +import {landingPageFallbackGuide, platformUrlFor, sanitizeNext} from './utils'; const path = (next: string) => sanitizeNext(next).pathname; const hash = (next: string) => sanitizeNext(next).hash; const REJECTED = {pathname: '', hash: ''}; +describe('landingPageFallbackGuide', () => { + const node = ( + slug: string, + frontmatter: Record = {}, + children: DocNode[] = [] + ) => ({slug, frontmatter, children, missing: false, path: slug}) as unknown as DocNode; + + const rootNode = node('', {}, [ + node('platforms', {}, [ + node('javascript', {}, [ + node('guides', {}, [ + node('express', { + inheritCommonContent: false, + fallbackGuide: 'javascript.node', + }), + node('nestjs', {fallbackGuide: 'javascript.node'}), + node('cordova', {inheritCommonContent: false}), + ]), + ]), + ]), + ]); + + it('returns the fallback guide of a landing page guide', () => { + expect(landingPageFallbackGuide(rootNode, 'javascript.express')).toBe( + 'javascript.node' + ); + }); + + it('returns nothing for a guide that inherits the common content', () => { + expect(landingPageFallbackGuide(rootNode, 'javascript.nestjs')).toBeUndefined(); + }); + + it('returns nothing for a landing page guide without a fallback guide', () => { + expect(landingPageFallbackGuide(rootNode, 'javascript.cordova')).toBeUndefined(); + }); + + it('returns nothing for a platform or an unknown guide', () => { + expect(landingPageFallbackGuide(rootNode, 'javascript')).toBeUndefined(); + expect(landingPageFallbackGuide(rootNode, 'javascript.unknown')).toBeUndefined(); + }); +}); + describe('sanitizeNext', () => { it('should return an empty string for external URLs', () => { expect(sanitizeNext('http://example.com')).toEqual(REJECTED); diff --git a/app/platform-redirect/utils.ts b/app/platform-redirect/utils.ts index e646c519afcab..816318c19a356 100644 --- a/app/platform-redirect/utils.ts +++ b/app/platform-redirect/utils.ts @@ -1,3 +1,25 @@ +import {DocNode, nodeForPath} from 'sentry-docs/docTree'; + +/** + * Returns the `fallbackGuide` key (e.g. `javascript.node`) of a guide that is a single + * landing page (`inheritCommonContent: false`), such as `javascript.express`. The pages + * that such a guide does not have are in its fallback guide. + */ +export function landingPageFallbackGuide( + rootNode: DocNode, + key: string +): string | undefined { + const [platform, guide] = key.split('.'); + if (!guide) { + return undefined; + } + const guideNode = nodeForPath(rootNode, ['platforms', platform, 'guides', guide]); + if (guideNode?.frontmatter.inheritCommonContent !== false) { + return undefined; + } + return guideNode.frontmatter.fallbackGuide; +} + // Parse base only — never part of the return value, and only compared against itself const PARSE_BASE = 'https://sanitize.invalid'; diff --git a/docs/contributing/pages/components.mdx b/docs/contributing/pages/components.mdx index 130549944885f..06fe0522ac58f 100644 --- a/docs/contributing/pages/components.mdx +++ b/docs/contributing/pages/components.mdx @@ -360,6 +360,7 @@ Attributes: - `includePath` (string) - the subfolder within `/includes` to map to - `platform` (string) - defaults to the `platform` value from the page context +- `switchable` (boolean) - lets a surrounding [`FrameworkSelector`](#frameworkselector) swap the include for the selected framework's version Some notes: @@ -371,6 +372,28 @@ Some notes: Note: This currently causes issues with tableOfContents generation, so its recommended to disable the TOC when using it. +## FrameworkSelector + +Adds a framework dropdown to a runtime's quick start, such as the Node.js, Bun, and Deno guides. Selecting a framework that doesn't have its own SDK (Express, Fastify, Koa, Hapi) swaps every `` inside the selector for that framework's version. Selecting a framework that has its own guide (Next.js, Nuxt, and others) opens that guide. The selection is kept in the `?framework=` query parameter. + +```markdown {tabTitle:Example} + + + + + +``` + +The runtimes, their frameworks, and their switchable include paths are configured in `src/components/frameworkSelector/frameworks.ts`. + +The framework snippets are only shown after a reader selects the framework, so they're easy to miss when you change content: + +- `platform-includes//javascript..mdx` (for example, `javascript.express.mdx`) shows up on the Node.js, Bun, **and** Deno quick starts. Put snippets that only apply to one runtime in `javascript...mdx`, for example `javascript.node.express.mdx`. +- On Node.js, a framework without its own file uses the Node.js content. On Bun and Deno, it uses the runtime's own content. +- Every `switchable` include path has to be listed in the runtime's `includePaths` in `frameworks.ts`. If it isn't, the framework version isn't built and the page quietly keeps showing the runtime's content. `frameworks.spec.ts` fails when the two get out of sync. +- The framework snippets aren't part of the runtime page's [Markdown export](/contributing/pages/llm-support/). Keep framework-specific guidance that agents need, such as error handling options, on the framework's own guide page too, for example `docs/platforms/javascript/guides/express/index.mdx`. +- To review a change, open the quick start with the framework selected, for example `/platforms/javascript/guides/node/?framework=express`, for each runtime the file applies to. + ## PlatformIdentifier Render terms in the correct case within the body text of a page (not in code samples) based on the platform case_style setting: diff --git a/docs/platforms/javascript/common/configuration/integrations/fastify.mdx b/docs/platforms/javascript/common/configuration/integrations/fastify.mdx index f4ba56683c2d8..cf140e80b1134 100644 --- a/docs/platforms/javascript/common/configuration/integrations/fastify.mdx +++ b/docs/platforms/javascript/common/configuration/integrations/fastify.mdx @@ -19,6 +19,47 @@ Sentry.init({ }); ``` +## Options + +### `shouldHandleError` + +A function that decides whether an error is captured. By default, errors with a 5xx status code (and errors with a 2xx status code or lower) are captured, and errors with a 3xx or 4xx status code aren't. + +```typescript +declare function shouldHandleError( + error: Error, + request: FastifyRequest, + reply: FastifyReply +): boolean; +``` + +```javascript +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [ + Sentry.fastifyIntegration({ + shouldHandleError(error, request, reply) { + return reply.statusCode >= 500; + }, + }), + ], +}); +``` + +If you use TypeScript, cast the request and reply to get full type safety: + +```typescript +import type { FastifyRequest, FastifyReply } from "fastify"; + +Sentry.fastifyIntegration({ + shouldHandleError(error, minimalRequest, minimalReply) { + const request = minimalRequest as FastifyRequest; + const reply = minimalReply as FastifyReply; + return reply.statusCode >= 500; + }, +}); +``` + ## Supported Versions - `fastify`: `^3.21.0 || ^4.0.0` diff --git a/docs/platforms/javascript/common/data-management/sensitive-data/index.mdx b/docs/platforms/javascript/common/data-management/sensitive-data/index.mdx index b5c70dd09409f..dae753d55eacb 100644 --- a/docs/platforms/javascript/common/data-management/sensitive-data/index.mdx +++ b/docs/platforms/javascript/common/data-management/sensitive-data/index.mdx @@ -1,7 +1,7 @@ --- title: "Scrubbing Sensitive Data" description: "Learn about filtering or scrubbing sensitive data within the Sentry JavaScript SDK, so that data is not sent with the event. You can also configure server-side scrubbing to ensure the data is not stored." -customCanonicalTag: "/platforms/javascript/guides/koa/data-management/sensitive-data/" +customCanonicalTag: "/platforms/javascript/guides/node/data-management/sensitive-data/" sidebar_order: 100 keywords: - pii diff --git a/docs/platforms/javascript/common/sourcemaps/uploading/rollup.mdx b/docs/platforms/javascript/common/sourcemaps/uploading/rollup.mdx index 1595ac6fcb59a..06aa5f958ffef 100644 --- a/docs/platforms/javascript/common/sourcemaps/uploading/rollup.mdx +++ b/docs/platforms/javascript/common/sourcemaps/uploading/rollup.mdx @@ -2,7 +2,7 @@ title: Rollup description: "Upload your source maps with the Sentry Rollup Plugin." sidebar_order: 5 -customCanonicalTag: "/platforms/javascript/guides/koa/sourcemaps/uploading/rollup/" +customCanonicalTag: "/platforms/javascript/guides/node/sourcemaps/uploading/rollup/" --- diff --git a/docs/platforms/javascript/guides/bun/index.mdx b/docs/platforms/javascript/guides/bun/index.mdx index 953542c895b9e..4f18bafd063a0 100644 --- a/docs/platforms/javascript/guides/bun/index.mdx +++ b/docs/platforms/javascript/guides/bun/index.mdx @@ -7,6 +7,8 @@ categories: - server-only --- + + @@ -108,13 +110,7 @@ For Bun, `bunR Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. -Add an intentional error to your main application file: - -```javascript -setTimeout(() => { - throw new Error("Sentry Test Error"); -}, 0); -``` + ### View Captured Data in Sentry @@ -137,3 +133,5 @@ At this point, you should have integrated Sentry into your Bun application. Here + + diff --git a/docs/platforms/javascript/guides/cloudflare/index.mdx b/docs/platforms/javascript/guides/cloudflare/index.mdx index 51632e610ec6b..cd9bfc16f52ed 100644 --- a/docs/platforms/javascript/guides/cloudflare/index.mdx +++ b/docs/platforms/javascript/guides/cloudflare/index.mdx @@ -12,16 +12,9 @@ categories: This guide covers Cloudflare Workers. If you're deploying a Cloudflare Pages application, see Cloudflare Pages instead, which is set up with middleware rather than a wrapper. -If you're using any of the listed frameworks, follow their specific setup instructions: +If you're using a framework, select it to open its setup instructions: -- **[Astro](/platforms/javascript/guides/astro/cloudflare/)** -- **[Hono](/platforms/javascript/guides/hono/cloudflare/)** (with @sentry/hono) -- **[Hydrogen](/platforms/javascript/guides/react-router/hydrogen/)** -- **[Next.js](/platforms/javascript/guides/nextjs/cloudflare/)** -- **[Nuxt](/platforms/javascript/guides/nuxt/cloudflare/)** -- **[Remix](/platforms/javascript/guides/remix/cloudflare/)** -- **[SvelteKit](/platforms/javascript/guides/sveltekit/cloudflare/)** -- **[TanStack Start](/platforms/javascript/guides/tanstackstart-react/cloudflare/)** + The Cloudflare Workers runtime has some platform-specific limitations that @@ -178,7 +171,7 @@ At this point, you should have integrated Sentry into your Cloudflare Worker. He -- Using a framework? Follow its setup instructions, linked at the top of this page +- Using a framework? Select it in the [framework selector](#framework-selector) at the top of this page - Find various support topics in troubleshooting - [Get support](https://www.sentry.help/en/) diff --git a/docs/platforms/javascript/guides/cordova/data-management/sensitive-data/index.mdx b/docs/platforms/javascript/guides/cordova/data-management/sensitive-data/index.mdx index 5045b48f990e1..5a280d3a5710c 100644 --- a/docs/platforms/javascript/guides/cordova/data-management/sensitive-data/index.mdx +++ b/docs/platforms/javascript/guides/cordova/data-management/sensitive-data/index.mdx @@ -1,7 +1,7 @@ --- title: "Scrubbing Sensitive Data" description: "Learn about filtering or scrubbing sensitive data within the Sentry JavaScript SDK, so that data is not sent with the event. You can also configure server-side scrubbing to ensure the data is not stored." -customCanonicalTag: "/platforms/javascript/guides/koa/data-management/sensitive-data/" +customCanonicalTag: "/platforms/javascript/guides/node/data-management/sensitive-data/" sidebar_order: 100 keywords: - pii diff --git a/docs/platforms/javascript/guides/cordova/sourcemaps/uploading/rollup.mdx b/docs/platforms/javascript/guides/cordova/sourcemaps/uploading/rollup.mdx index 066d1b6ba87f4..c2f8ffb6e6b6d 100644 --- a/docs/platforms/javascript/guides/cordova/sourcemaps/uploading/rollup.mdx +++ b/docs/platforms/javascript/guides/cordova/sourcemaps/uploading/rollup.mdx @@ -2,7 +2,7 @@ title: Rollup description: "Upload your source maps with the Sentry Rollup Plugin." sidebar_order: 5 -customCanonicalTag: "/platforms/javascript/guides/koa/sourcemaps/uploading/rollup/" +customCanonicalTag: "/platforms/javascript/guides/node/sourcemaps/uploading/rollup/" --- diff --git a/docs/platforms/javascript/guides/deno/index.mdx b/docs/platforms/javascript/guides/deno/index.mdx index 41329f9bb689a..87e356d892b3f 100644 --- a/docs/platforms/javascript/guides/deno/index.mdx +++ b/docs/platforms/javascript/guides/deno/index.mdx @@ -7,6 +7,8 @@ categories: - server-only --- + + This SDK is currently in **beta**. Beta features are still in progress and may have bugs. Please reach out on [GitHub](https://github.com/getsentry/sentry-javascript/issues/new/choose) if you have any feedback or concerns @@ -122,13 +124,7 @@ For Deno, `de Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. -Add an intentional error to your application: - -```javascript -setTimeout(() => { - throw new Error("Sentry Test Error"); -}, 0); -``` + ### View Captured Data in Sentry @@ -151,3 +147,5 @@ At this point, you should have integrated Sentry into your Deno application. Her + + diff --git a/docs/platforms/javascript/guides/express/configuration/integrations/contextlines.mdx b/docs/platforms/javascript/guides/express/configuration/integrations/contextlines.mdx deleted file mode 100644 index 7b3af58727490..0000000000000 --- a/docs/platforms/javascript/guides/express/configuration/integrations/contextlines.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: ContextLines -description: "Adds source code to your stack frames. (default)" ---- - -_Import name: `Sentry.contextLinesIntegration`_ - -This integration is enabled by default. If you'd like to modify your default integrations, read [this](./../#modifying-default-integrations). - -This integration adds source code to your stack frames. It ensures that you can see the code that caused the error directly in the Sentry UI. - - - -## Options - -### `frameContextLines` - -_Type: `number`_ - -The number of lines to collect around each stack frame's line number. Defaults to 7. diff --git a/docs/platforms/javascript/guides/express/index.mdx b/docs/platforms/javascript/guides/express/index.mdx index 059dcbfb2b745..222756abf18f0 100644 --- a/docs/platforms/javascript/guides/express/index.mdx +++ b/docs/platforms/javascript/guides/express/index.mdx @@ -1,11 +1,51 @@ --- title: Express -description: "Learn how to manually set up Sentry in your Express app and capture your first events." +description: "Learn how to set up Sentry in your Express app on Node.js, Bun, or Deno." sdk: sentry.javascript.node fallbackGuide: javascript.node +inheritCommonContent: false categories: - server - server-only --- - +[Express](https://expressjs.com/) doesn't need its own Sentry SDK. Set up Sentry for the runtime your app runs on, and the SDK instruments Express automatically: `expressIntegration` captures errors from your routes and middleware, and creates spans for incoming requests when tracing is enabled. + +## Set Up Sentry for Your Runtime + +- +- +- + +## Customize Error Capturing + +Errors with a 3xx or 4xx status code are skipped, since they're usually expected redirects or client errors. To change which errors are captured, pass a `shouldHandleError` callback to `expressIntegration()`: + +```javascript +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [ + Sentry.expressIntegration({ + shouldHandleError(error) { + const status = Number(error.status ?? error.statusCode ?? 500); + // Capture 401/403 in addition to the default 5xx errors + return status === 401 || status === 403 || status >= 500; + }, + }), + ], +}); +``` + +If you capture errors yourself in your own error-handling middleware, set `shouldHandleError: false` to avoid duplicate events. diff --git a/docs/platforms/javascript/guides/express/index__v7.x.mdx b/docs/platforms/javascript/guides/express/index__v7.x.mdx deleted file mode 100644 index 76ef56f70dc76..0000000000000 --- a/docs/platforms/javascript/guides/express/index__v7.x.mdx +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Express -description: "Learn how to instrument the Sentry Express SDK." -sdk: sentry.javascript.node -fallbackGuide: javascript.node -categories: - - server ---- - - - -This guide explains how to set up Sentry in your Express application. - - diff --git a/docs/platforms/javascript/guides/express/tracing/instrumentation/automatic-instrumentation.mdx b/docs/platforms/javascript/guides/express/tracing/instrumentation/automatic-instrumentation.mdx deleted file mode 100644 index c7b42fb602ab9..0000000000000 --- a/docs/platforms/javascript/guides/express/tracing/instrumentation/automatic-instrumentation.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Automatic Instrumentation -description: "Learn what transactions are captured after tracing is enabled in the Sentry Express SDK." ---- - - diff --git a/docs/platforms/javascript/guides/fastify/features/error-handler.mdx b/docs/platforms/javascript/guides/fastify/features/error-handler.mdx deleted file mode 100644 index 43e3c0f8cf935..0000000000000 --- a/docs/platforms/javascript/guides/fastify/features/error-handler.mdx +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Fastify Error Handler -description: "Learn how Sentry's Fastify integration captures errors and how to configure it." ---- - -The `fastifyIntegration` captures errors in your Fastify application and sends them to Sentry. It's enabled by default, so you only need to add it to your `Sentry.init` call to configure it. - -By default, errors with status codes 5xx and above, as well as errors with status codes 2xx and below, are captured. Errors with 3xx and 4xx status codes aren't sent to Sentry. - -## Configuration - -To control which errors are captured, pass `shouldHandleError` to `Sentry.fastifyIntegration`: - -```javascript -import * as Sentry from "@sentry/node"; - -Sentry.init({ - dsn: "your-dsn", - integrations: [ - Sentry.fastifyIntegration({ - shouldHandleError(error, request, reply) { - return reply.statusCode >= 500; - }, - }), - ], -}); -``` - -## Options - -`Sentry.fastifyIntegration` accepts the following options: - -- `shouldHandleError` - -A function that determines whether an error should be captured. - -```typescript -declare function shouldHandleError( - error: Error, - request: FastifyRequest, - reply: FastifyReply -): boolean; -``` - -If using TypeScript, you can cast the request and reply to get full type safety. - -```typescript -import type { FastifyRequest, FastifyReply } from "fastify"; - -Sentry.fastifyIntegration({ - shouldHandleError(error, minimalRequest, minimalReply) { - const request = minimalRequest as FastifyRequest; - const reply = minimalReply as FastifyReply; - return reply.statusCode >= 500; - }, -}); -``` diff --git a/docs/platforms/javascript/guides/fastify/features/index.mdx b/docs/platforms/javascript/guides/fastify/features/index.mdx deleted file mode 100644 index b7fcfb338bb49..0000000000000 --- a/docs/platforms/javascript/guides/fastify/features/index.mdx +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: Fastify Features -description: "Learn how Sentry's Node SDK exposes features for first class integration with Fastify." -excerpt: "" ---- - -The Sentry Node SDK offers Fastify-specific features for first class integration with the framework. - - diff --git a/docs/platforms/javascript/guides/fastify/index.mdx b/docs/platforms/javascript/guides/fastify/index.mdx index 8635ad6a08605..2e8735557adb6 100644 --- a/docs/platforms/javascript/guides/fastify/index.mdx +++ b/docs/platforms/javascript/guides/fastify/index.mdx @@ -1,13 +1,34 @@ --- title: Fastify -description: "Learn how to manually set up Sentry in your Fastify app and capture your first events." +description: "Learn how to set up Sentry in your Fastify app on Node.js, Bun, or Deno." sdk: sentry.javascript.node fallbackGuide: javascript.node +inheritCommonContent: false categories: - server - server-only --- - +[Fastify](https://fastify.dev/) doesn't need its own Sentry SDK. Set up Sentry for the runtime your app runs on, and the SDK instruments Fastify automatically: `fastifyIntegration` captures errors from your routes and hooks, and creates spans for incoming requests when tracing is enabled. - +## Set Up Sentry for Your Runtime + +- +- +- + +## Customize Error Capturing + +Errors with a 3xx or 4xx status code are skipped. To change which errors are captured, pass a `shouldHandleError` callback to `fastifyIntegration()`. See the [Fastify integration](/platforms/javascript/guides/node/configuration/integrations/fastify/#shouldhandleerror) for all options. diff --git a/docs/platforms/javascript/guides/fastify/tracing/instrumentation/automatic-instrumentation.mdx b/docs/platforms/javascript/guides/fastify/tracing/instrumentation/automatic-instrumentation.mdx deleted file mode 100644 index abc98b5bca4fd..0000000000000 --- a/docs/platforms/javascript/guides/fastify/tracing/instrumentation/automatic-instrumentation.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Automatic Instrumentation -description: "Learn what transactions are captured after tracing is enabled in the Sentry Fastify SDK." ---- - - diff --git a/docs/platforms/javascript/guides/hapi/configuration/integrations/contextlines.mdx b/docs/platforms/javascript/guides/hapi/configuration/integrations/contextlines.mdx deleted file mode 100644 index 7b3af58727490..0000000000000 --- a/docs/platforms/javascript/guides/hapi/configuration/integrations/contextlines.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: ContextLines -description: "Adds source code to your stack frames. (default)" ---- - -_Import name: `Sentry.contextLinesIntegration`_ - -This integration is enabled by default. If you'd like to modify your default integrations, read [this](./../#modifying-default-integrations). - -This integration adds source code to your stack frames. It ensures that you can see the code that caused the error directly in the Sentry UI. - - - -## Options - -### `frameContextLines` - -_Type: `number`_ - -The number of lines to collect around each stack frame's line number. Defaults to 7. diff --git a/docs/platforms/javascript/guides/hapi/index.mdx b/docs/platforms/javascript/guides/hapi/index.mdx index 9c3a092676880..147b858df193c 100644 --- a/docs/platforms/javascript/guides/hapi/index.mdx +++ b/docs/platforms/javascript/guides/hapi/index.mdx @@ -1,11 +1,32 @@ --- title: Hapi -description: "Learn how to manually set up Sentry in your Hapi app and capture your first events." +description: "Learn how to set up Sentry in your Hapi app on Node.js, Bun, or Deno." sdk: sentry.javascript.node fallbackGuide: javascript.node +inheritCommonContent: false categories: - server - server-only --- - +[Hapi](https://hapi.dev/) doesn't need its own Sentry SDK. Set up Sentry for the runtime your app runs on, and the SDK instruments Hapi automatically: `hapiIntegration` registers an error handler when your server starts, and creates spans for incoming requests when tracing is enabled. + +## Set Up Sentry for Your Runtime + +- +- +- + +To configure the integration, see the [Hapi integration](/platforms/javascript/guides/node/configuration/integrations/hapi/). diff --git a/docs/platforms/javascript/guides/hapi/tracing/instrumentation/automatic-instrumentation.mdx b/docs/platforms/javascript/guides/hapi/tracing/instrumentation/automatic-instrumentation.mdx deleted file mode 100644 index e749b53b702b1..0000000000000 --- a/docs/platforms/javascript/guides/hapi/tracing/instrumentation/automatic-instrumentation.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Automatic Instrumentation -description: "Learn what transactions are captured after tracing is enabled in the Sentry Hapi SDK." ---- - - diff --git a/docs/platforms/javascript/guides/koa/configuration/integrations/contextlines.mdx b/docs/platforms/javascript/guides/koa/configuration/integrations/contextlines.mdx deleted file mode 100644 index 7b3af58727490..0000000000000 --- a/docs/platforms/javascript/guides/koa/configuration/integrations/contextlines.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: ContextLines -description: "Adds source code to your stack frames. (default)" ---- - -_Import name: `Sentry.contextLinesIntegration`_ - -This integration is enabled by default. If you'd like to modify your default integrations, read [this](./../#modifying-default-integrations). - -This integration adds source code to your stack frames. It ensures that you can see the code that caused the error directly in the Sentry UI. - - - -## Options - -### `frameContextLines` - -_Type: `number`_ - -The number of lines to collect around each stack frame's line number. Defaults to 7. diff --git a/docs/platforms/javascript/guides/koa/index.mdx b/docs/platforms/javascript/guides/koa/index.mdx index 61f9b6d2450cb..33d7cff36ebad 100644 --- a/docs/platforms/javascript/guides/koa/index.mdx +++ b/docs/platforms/javascript/guides/koa/index.mdx @@ -1,11 +1,32 @@ --- title: Koa -description: "Learn how to manually set up Sentry in your Koa app and capture your first events." +description: "Learn how to set up Sentry in your Koa app on Node.js, Bun, or Deno." sdk: sentry.javascript.node fallbackGuide: javascript.node +inheritCommonContent: false categories: - server - server-only --- - +[Koa](https://koajs.com/) doesn't need its own Sentry SDK. Set up Sentry for the runtime your app runs on, and the SDK instruments Koa automatically: `koaIntegration` registers an error handler when your app starts, and creates spans for incoming requests and middleware when tracing is enabled. + +## Set Up Sentry for Your Runtime + +- +- +- + +To configure the integration, see the [Koa integration](/platforms/javascript/guides/node/configuration/integrations/koa/). diff --git a/docs/platforms/javascript/guides/koa/tracing/instrumentation/automatic-instrumentation.mdx b/docs/platforms/javascript/guides/koa/tracing/instrumentation/automatic-instrumentation.mdx deleted file mode 100644 index 4ad82b17e57af..0000000000000 --- a/docs/platforms/javascript/guides/koa/tracing/instrumentation/automatic-instrumentation.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Automatic Instrumentation -description: "Learn what transactions are captured after tracing is enabled in the Sentry Koa SDK." ---- - - diff --git a/docs/platforms/javascript/guides/node/index.mdx b/docs/platforms/javascript/guides/node/index.mdx index 989e9c7935797..0955371bf4511 100644 --- a/docs/platforms/javascript/guides/node/index.mdx +++ b/docs/platforms/javascript/guides/node/index.mdx @@ -7,8 +7,12 @@ categories: - server-only --- + + + + diff --git a/docs/product/logs/getting-started/index.mdx b/docs/product/logs/getting-started/index.mdx index abe253815930a..22a2b112a8ae4 100644 --- a/docs/product/logs/getting-started/index.mdx +++ b/docs/product/logs/getting-started/index.mdx @@ -68,13 +68,13 @@ To set up Sentry Logs, use the links below for supported SDKs. After it's been s - - - - - - - - - `shouldHandleError` option. +`fastifyIntegration` captures errors from your routes and hooks automatically, so you don't need to register a Sentry error handler. Errors with a 3xx or 4xx status code are skipped. To change which errors are captured, use the `shouldHandleError` option. diff --git a/platform-includes/getting-started-install/javascript.koa.mdx b/platform-includes/getting-started-install/javascript.koa.mdx deleted file mode 100644 index d0c4e2e161466..0000000000000 --- a/platform-includes/getting-started-install/javascript.koa.mdx +++ /dev/null @@ -1,31 +0,0 @@ - - -```bash {tabTitle:npm} -npm install @sentry/node -``` - -```bash {tabTitle:yarn} -yarn add @sentry/node -``` - -```bash {tabTitle:pnpm} -pnpm add @sentry/node -``` - - - - - -```bash {tabTitle:npm} -npm install @sentry/node @sentry/profiling-node --save -``` - -```bash {tabTitle:yarn} -yarn add @sentry/node @sentry/profiling-node -``` - -```bash {tabTitle:pnpm} -pnpm add @sentry/node @sentry/profiling-node -``` - - diff --git a/platform-includes/getting-started-node/javascript.mdx b/platform-includes/getting-started-node/javascript.mdx index 6494a33f2dd07..339f211dd3356 100644 --- a/platform-includes/getting-started-node/javascript.mdx +++ b/platform-includes/getting-started-node/javascript.mdx @@ -1,4 +1,4 @@ - + @@ -6,7 +6,7 @@ Run the command for your preferred package manager to add the Sentry SDK to your application: - + ## Configure @@ -23,7 +23,7 @@ The snippet also turns on: - Tracing: via `tracesSampleRate` - Profiling: via `profileSessionSampleRate` and `nodeProfilingIntegration()` - + Then, use the [--import](https://nodejs.org/api/cli.html#--importmodule) command line option and point it to your `instrument.(js|mjs)` file to load the module before the application starts: @@ -37,15 +37,15 @@ node --import ./instrument.mjs app.mjs If you are using a bundler like vite, you can also follow the bundler setup docs instead. - + ### Add Readable Stack Traces With Source Maps - + ### Control the Data You Send to Sentry - + ## Send Logs @@ -66,7 +66,7 @@ On Node.js, ` Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. - + ### View Captured Data in Sentry diff --git a/platform-includes/getting-started-verify-issues-tracing/javascript.bun.mdx b/platform-includes/getting-started-verify-issues-tracing/javascript.bun.mdx new file mode 100644 index 0000000000000..3f64ed54344fb --- /dev/null +++ b/platform-includes/getting-started-verify-issues-tracing/javascript.bun.mdx @@ -0,0 +1,7 @@ +Add an intentional error to your main application file: + +```javascript +setTimeout(() => { + throw new Error("Sentry Test Error"); +}, 0); +``` diff --git a/platform-includes/getting-started-verify-issues-tracing/javascript.deno.mdx b/platform-includes/getting-started-verify-issues-tracing/javascript.deno.mdx new file mode 100644 index 0000000000000..d65d054a8eb1d --- /dev/null +++ b/platform-includes/getting-started-verify-issues-tracing/javascript.deno.mdx @@ -0,0 +1,7 @@ +Add an intentional error to your application: + +```javascript +setTimeout(() => { + throw new Error("Sentry Test Error"); +}, 0); +``` diff --git a/platform-includes/getting-started-verify/javascript.express.mdx b/platform-includes/getting-started-verify-issues-tracing/javascript.express.mdx similarity index 100% rename from platform-includes/getting-started-verify/javascript.express.mdx rename to platform-includes/getting-started-verify-issues-tracing/javascript.express.mdx diff --git a/platform-includes/getting-started-verify/javascript.fastify.mdx b/platform-includes/getting-started-verify-issues-tracing/javascript.fastify.mdx similarity index 100% rename from platform-includes/getting-started-verify/javascript.fastify.mdx rename to platform-includes/getting-started-verify-issues-tracing/javascript.fastify.mdx diff --git a/platform-includes/getting-started-verify/javascript.hapi.mdx b/platform-includes/getting-started-verify-issues-tracing/javascript.hapi.mdx similarity index 100% rename from platform-includes/getting-started-verify/javascript.hapi.mdx rename to platform-includes/getting-started-verify-issues-tracing/javascript.hapi.mdx diff --git a/platform-includes/getting-started-verify/javascript.koa.mdx b/platform-includes/getting-started-verify-issues-tracing/javascript.koa.mdx similarity index 100% rename from platform-includes/getting-started-verify/javascript.koa.mdx rename to platform-includes/getting-started-verify-issues-tracing/javascript.koa.mdx diff --git a/platform-includes/getting-started-verify-issues-tracing/javascript.mdx b/platform-includes/getting-started-verify-issues-tracing/javascript.mdx new file mode 100644 index 0000000000000..736f01a457988 --- /dev/null +++ b/platform-includes/getting-started-verify-issues-tracing/javascript.mdx @@ -0,0 +1,11 @@ +Add an intentional error to your main application file that Sentry will capture: + +```javascript +setTimeout(() => { + try { + foo(); + } catch (e) { + Sentry.captureException(e); + } +}, 99); +``` diff --git a/platform-includes/getting-started-verify/javascript.node.mdx b/platform-includes/getting-started-verify/javascript.node.mdx index 736f01a457988..11d461b54dfc7 100644 --- a/platform-includes/getting-started-verify/javascript.node.mdx +++ b/platform-includes/getting-started-verify/javascript.node.mdx @@ -1,11 +1 @@ -Add an intentional error to your main application file that Sentry will capture: - -```javascript -setTimeout(() => { - try { - foo(); - } catch (e) { - Sentry.captureException(e); - } -}, 99); -``` + diff --git a/redirects.js b/redirects.js index d79bbd296af08..597821d1a0681 100644 --- a/redirects.js +++ b/redirects.js @@ -1095,17 +1095,17 @@ const userDocsRedirects = [ { source: '/platforms/javascript/guides/express/install/lightweight/', destination: - '/platforms/javascript/guides/express/configuration/integrations/opentelemetry/', + '/platforms/javascript/guides/node/configuration/integrations/opentelemetry/', }, { source: '/platforms/javascript/guides/fastify/install/lightweight/', destination: - '/platforms/javascript/guides/fastify/configuration/integrations/opentelemetry/', + '/platforms/javascript/guides/node/configuration/integrations/opentelemetry/', }, { source: '/platforms/javascript/guides/hapi/install/lightweight/', destination: - '/platforms/javascript/guides/hapi/configuration/integrations/opentelemetry/', + '/platforms/javascript/guides/node/configuration/integrations/opentelemetry/', }, { source: '/platforms/javascript/guides/hono/install/lightweight/', @@ -1115,7 +1115,7 @@ const userDocsRedirects = [ { source: '/platforms/javascript/guides/koa/install/lightweight/', destination: - '/platforms/javascript/guides/koa/configuration/integrations/opentelemetry/', + '/platforms/javascript/guides/node/configuration/integrations/opentelemetry/', }, { source: @@ -1127,6 +1127,20 @@ const userDocsRedirects = [ '/platforms/javascript/guides/:guide(node|express|fastify|hapi|hono|koa|nestjs)/install/commonjs/', destination: '/platforms/javascript/guides/:guide/', }, + // Express, Fastify, Hapi and Koa are single landing pages, their subpages moved to Node.js. + { + source: '/platforms/javascript/guides/fastify/features/:path*', + destination: '/platforms/javascript/guides/node/configuration/integrations/fastify/', + }, + { + source: + '/platforms/javascript/guides/:guide(express|fastify|hapi|koa)__v:version/:path*', + destination: '/platforms/javascript/guides/node/', + }, + { + source: '/platforms/javascript/guides/:guide(express|fastify|hapi|koa)/:path+', + destination: '/platforms/javascript/guides/node/:path+/', + }, { source: '/platforms/javascript/guides/nestjs/install/esm-without-import/', destination: '/platforms/javascript/guides/nestjs/', diff --git a/src/components/frameworkSelector/frameworks.spec.ts b/src/components/frameworkSelector/frameworks.spec.ts new file mode 100644 index 0000000000000..41c74fea53736 --- /dev/null +++ b/src/components/frameworkSelector/frameworks.spec.ts @@ -0,0 +1,88 @@ +import {existsSync, readdirSync, readFileSync} from 'node:fs'; +import {join} from 'node:path'; + +import matter from 'gray-matter'; +import {describe, expect, it} from 'vitest'; + +import {getRuntimeLinks} from '../runtimeLinks'; +import {RUNTIMES} from './frameworks'; + +const GUIDES_DIR = 'docs/platforms/javascript/guides'; + +const pageExists = (url: string) => { + const file = join('docs', url.replace(/\/$/, '')); + return existsSync(`${file}.mdx`) || existsSync(join(file, 'index.mdx')); +}; + +/** The index page of a guide and its child pages, with their frontmatter. */ +const guidePages = (guide: string) => { + const dir = join(GUIDES_DIR, guide); + const path = `platforms/javascript/guides/${guide}`; + const frontmatter = (file: string) => + matter(readFileSync(join(dir, file), 'utf8')).data; + const children = readdirSync(dir, {withFileTypes: true}).flatMap(entry => { + const file = entry.isDirectory() ? join(entry.name, 'index.mdx') : entry.name; + if (!file.endsWith('.mdx') || file === 'index.mdx' || !existsSync(join(dir, file))) { + return []; + } + const name = entry.isDirectory() ? entry.name : entry.name.replace(/\.mdx$/, ''); + return [{path: `${path}/${name}`, frontmatter: frontmatter(file)}]; + }); + return {path, frontmatter: frontmatter('index.mdx'), children}; +}; + +const PLATFORM_CONTENT_RE = /]*)\/>/g; + +/** + * The `switchable` include paths of a runtime's quick start: the ones on its page and in the + * `platform-includes` files the page includes directly. + */ +const switchableIncludePaths = (runtime: string) => { + const found = new Set(); + const scan = (source: string, nested: boolean) => { + for (const [, includePath, attributes] of source.matchAll(PLATFORM_CONTENT_RE)) { + if (/\bswitchable\b/.test(attributes)) { + found.add(includePath); + } else if (nested) { + const file = [`javascript.${runtime}.mdx`, 'javascript.mdx'] + .map(name => join('platform-includes', includePath, name)) + .find(existsSync); + if (file) { + scan(readFileSync(file, 'utf8'), false); + } + } + } + }; + scan(readFileSync(join(GUIDES_DIR, runtime, 'index.mdx'), 'utf8'), true); + return [...found].sort(); +}; + +describe('RUNTIMES', () => { + it.each(Object.entries(RUNTIMES))('%s links only to existing pages', (_, runtime) => { + const urls = (runtime.frameworkGuides ?? []).map(g => g.url); + expect(urls.filter(url => !pageExists(url))).toEqual([]); + }); + + it.each(Object.entries(RUNTIMES))( + '%s lists every switchable include path of its quick start', + (runtime, {includePaths}) => { + expect(switchableIncludePaths(runtime)).toEqual([...includePaths].sort()); + } + ); + + it('links every quick start of a guide with quick starts for more than one runtime', () => { + const guides = readdirSync(GUIDES_DIR).filter(guide => + existsSync(join(GUIDES_DIR, guide, 'index.mdx')) + ); + const missing = guides.flatMap(guide => + (getRuntimeLinks(guidePages(guide), []) ?? []) + .filter( + link => + link.runtime in RUNTIMES && + !RUNTIMES[link.runtime].frameworkGuides?.some(g => g.url === link.url) + ) + .map(link => link.url) + ); + expect(missing).toEqual([]); + }); +}); diff --git a/src/components/frameworkSelector/frameworks.ts b/src/components/frameworkSelector/frameworks.ts new file mode 100644 index 0000000000000..4922ff5ffd359 --- /dev/null +++ b/src/components/frameworkSelector/frameworks.ts @@ -0,0 +1,125 @@ +export type Framework = { + /** Guide slug, e.g. `express` for `/platforms/javascript/guides/express/`. */ + key: string; + title: string; +}; + +const EXPRESS: Framework = {key: 'express', title: 'Express'}; +const FASTIFY: Framework = {key: 'fastify', title: 'Fastify'}; +const KOA: Framework = {key: 'koa', title: 'Koa'}; +const HAPI: Framework = {key: 'hapi', title: 'Hapi'}; + +/** A framework with its own Sentry SDK. The selector opens its guide instead of swapping snippets. */ +export type FrameworkGuide = { + /** Platform icon key, e.g. `javascript-astro`. */ + icon: string; + title: string; + url: string; +}; + +/** + * `slug` is the page path below `/platforms/javascript/guides/`. The icon defaults to the + * one of the guide in the first segment of `slug`. + */ +const guide = ( + title: string, + slug: string, + icon = `javascript-${slug.split('/')[0]}` +): FrameworkGuide => ({ + icon, + title, + url: `/platforms/javascript/guides/${slug}/`, +}); + +export type Runtime = { + /** Frameworks selectable on the runtime's getting started page. */ + frameworks: Framework[]; + /** Frameworks with their own Sentry SDK that the selector links to. */ + frameworkGuides?: FrameworkGuide[]; + /** + * `` include paths on the runtime's getting started page. + * Each one is pre-built per framework as a static JSON file that the page loads on demand. + */ + includePaths: string[]; + title: string; +}; + +/** Runtime guides (keyed by guide slug) that have a framework selector on their getting started page. */ +export const RUNTIMES: Record = { + node: { + title: 'Node.js', + frameworks: [EXPRESS, FASTIFY, KOA, HAPI], + frameworkGuides: [ + guide('Astro', 'astro'), + guide('Hono', 'hono'), + guide('NestJS', 'nestjs'), + guide('Next.js', 'nextjs'), + guide('Nitro', 'nitro'), + guide('Nuxt', 'nuxt'), + guide('React Router', 'react-router'), + guide('Remix', 'remix'), + guide('SolidStart', 'solidstart'), + guide('SvelteKit', 'sveltekit'), + guide('TanStack Start', 'tanstackstart-react'), + ], + includePaths: [ + 'getting-started-prerequisites', + 'getting-started-install', + 'getting-started-config', + 'getting-started-capture-errors', + 'getting-started-sourcemaps-short-version', + 'getting-started-data-collection', + 'getting-started-verify', + ], + }, + bun: { + title: 'Bun', + frameworks: [EXPRESS, FASTIFY, KOA, HAPI], + frameworkGuides: [guide('Elysia', 'elysia'), guide('Hono', 'hono')], + includePaths: ['getting-started-verify-issues-tracing'], + }, + deno: { + title: 'Deno', + frameworks: [EXPRESS, FASTIFY, KOA, HAPI], + frameworkGuides: [guide('Hono', 'hono')], + includePaths: ['getting-started-verify-issues-tracing'], + }, + cloudflare: { + title: 'Cloudflare Workers', + frameworks: [], + frameworkGuides: [ + guide('Astro', 'astro/cloudflare'), + guide('Hono', 'hono/cloudflare'), + guide('Hydrogen', 'react-router/hydrogen', 'javascript-hydrogen'), + guide('Next.js', 'nextjs/cloudflare'), + guide('Nuxt', 'nuxt/cloudflare'), + guide('Remix', 'remix/cloudflare'), + guide('SvelteKit', 'sveltekit/cloudflare'), + guide('TanStack Start', 'tanstackstart-react/cloudflare'), + ], + includePaths: [], + }, +}; + +export const FRAMEWORK_QUERY_PARAM = 'framework'; + +/** The serialized form of a `` include, served by the platform-content API route. */ +export type PlatformContentPayload = { + /** Whether the content differs from what the runtime's page shows without a framework. */ + changed: boolean; + /** Compiled MDX of the resolved include, or `null` if there is no content for it. */ + code: string | null; + /** Compiled MDX of nested `` files, keyed by name. */ + includes: Record; + /** Compiled MDX of nested `` files, keyed by include path. */ + platformContents: Record; +}; + +export function platformContentUrl( + platform: string, + runtime: string, + framework: string, + includePath: string +) { + return `/api/platform-content/${platform}/${runtime}/${framework}/${includePath}/`; +} diff --git a/src/components/frameworkSelector/index.tsx b/src/components/frameworkSelector/index.tsx new file mode 100644 index 0000000000000..4284ff50108b9 --- /dev/null +++ b/src/components/frameworkSelector/index.tsx @@ -0,0 +1,557 @@ +'use client'; + +import {ArrowRightIcon, CaretSortIcon} from '@radix-ui/react-icons'; +import * as RadixSelect from '@radix-ui/react-select'; +import {useRouter} from 'next/navigation'; +import { + createContext, + ReactNode, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from 'react'; +import {getMDXComponent} from 'sentry-docs/getMDXComponent'; + +import {Alert} from '../alert'; +import {CodeBlock} from '../codeBlock'; +import {CodeContext} from '../codeContext'; +import {CodeTabs} from '../codeTabs'; +import {Expandable} from '../expandable'; +import {FeatureBadge} from '../featureBadge'; +import { + OnboardingOption, + OnboardingOptionButtons, + OnboardingSteps, + updateElementsVisibilityForOptions, +} from '../onboarding'; +import {PlatformIcon} from '../platformIcon'; +import {SmartLink} from '../smartLink'; +import styles from '../versionSelector/style.module.scss'; +import { + Framework, + FRAMEWORK_QUERY_PARAM, + FrameworkGuide, + PlatformContentPayload, + platformContentUrl, + RUNTIMES, +} from './frameworks'; +import frameworkStyles from './style.module.scss'; + +const DEFAULT_VALUE = 'none'; +const GUIDE_VALUE_PREFIX = 'guide:'; +const groupLabelClassName = 'px-2 pt-2 pb-1 text-xs font-medium text-[var(--gray-11)]'; +const itemClassName = `${styles.item} ${frameworkStyles.option}`; + +/** The state of a switchable block while a framework is selected. */ +type ContentStatus = + | {state: 'loading' | 'unchanged'} + /** `step` is the title of the `h2` step that contains the block, `targetId` the block's id. */ + | {state: 'changed'; targetId: string; step?: string}; + +type FrameworkContextValue = { + framework: Framework | null; + platform: string; + /** Records the status of the block with `includePath`, or removes it with `null`. */ + reportContent: (includePath: string, status: ContentStatus | null) => void; + /** The runtime guide the page belongs to, e.g. `node`. */ + runtime: string; +}; + +const FrameworkContext = createContext(null); + +function ItemLabel({icon, title}: {icon: string; title: string}) { + return ( + + + {title} + + ); +} + +/** + * The guides of a dropdown group as plain links. The dropdown renders its options only while + * it's open, so without these the page's HTML, and its Markdown export for AI agents, would + * not link the guides. People use the dropdown, so the links are hidden from them. + */ +function GuideLinks({guides, label}: {guides: FrameworkGuide[]; label: string}) { + if (guides.length === 0) { + return null; + } + return ( + + ); +} + +function stepTitle(el: HTMLElement): string | undefined { + const step = Array.from(document.querySelectorAll('main h2[id]')) + .filter(h => h.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING) + .pop(); + return (step?.querySelector('a') ?? step)?.textContent?.trim(); +} + +function FrameworkSummary({ + contents, + framework, + platform, +}: { + contents: Record; + framework: Framework; + platform: string; +}) { + const statuses = Object.values(contents); + if (statuses.some(c => c.state === 'loading')) { + return ( +

Loading the steps for {framework.title}…

+ ); + } + + const changed = statuses + .filter(c => c.state === 'changed') + .map(c => ({...c, el: document.getElementById(c.targetId)})) + .filter(c => c.el) + .sort((a, b) => + a.el!.compareDocumentPosition(b.el!) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1 + ); + const steps = changed.filter( + (c, i) => changed.findIndex(other => other.step === c.step) === i + ); + + return ( +

+ + {steps.length > 0 ? ( + + Updated for {framework.title}:{' '} + {steps.map((c, i) => ( + + {i > 0 && ', '} + {c.step ?? 'Show the change'} + + ))} + + ) : ( + The steps for {framework.title} are the same as without a framework. + )} +

+ ); +} + +function readFrameworkFromUrl(frameworks: Framework[]): Framework | null { + const key = new URLSearchParams(window.location.search).get(FRAMEWORK_QUERY_PARAM); + return frameworks.find(f => f.key === key) ?? null; +} + +function writeFrameworkToUrl(framework: Framework | null) { + const url = new URL(window.location.href); + if (framework) { + url.searchParams.set(FRAMEWORK_QUERY_PARAM, framework.key); + } else { + url.searchParams.delete(FRAMEWORK_QUERY_PARAM); + } + window.history.replaceState(window.history.state, '', url); +} + +/** + * Renders a framework dropdown and lets `` blocks among its + * children swap to the selected framework's snippets for `runtime`, loaded on demand. + * The selection is kept in the `?framework=` query param. + */ +export function FrameworkSelector({ + children, + runtime, + platform = 'javascript', +}: { + runtime: string; + children?: ReactNode; + platform?: string; +}) { + const router = useRouter(); + const runtimeConfig = RUNTIMES[runtime]; + const frameworks = useMemo(() => runtimeConfig?.frameworks ?? [], [runtimeConfig]); + const frameworkGuides = runtimeConfig?.frameworkGuides ?? []; + const [framework, setFramework] = useState(null); + const [contents, setContents] = useState>({}); + + const reportContent = useCallback( + (includePath: string, status: ContentStatus | null) => + setContents(prev => { + const next = {...prev}; + if (status) { + next[includePath] = status; + } else { + delete next[includePath]; + } + return next; + }), + [] + ); + + // The page is statically rendered, so the query param can only be read after mount. + useEffect(() => { + setFramework(readFrameworkFromUrl(frameworks)); + }, [frameworks]); + + const handleChange = (value: string) => { + if (value.startsWith(GUIDE_VALUE_PREFIX)) { + router.push(value.slice(GUIDE_VALUE_PREFIX.length)); + return; + } + const selected = frameworks.find(f => f.key === value) ?? null; + setFramework(selected); + writeFrameworkToUrl(selected); + }; + + const contextValue = useMemo( + () => ({framework, platform, reportContent, runtime}), + [framework, platform, reportContent, runtime] + ); + + return ( + + {/* Left out of the Markdown export, which gets the guides from `GuideLinks` */} +
+ +
+ + + + + + + + + {/* Radix finds the items for keyboard navigation only inside the viewport. + It hides the viewport's scrollbar, so the content scrolls instead. */} + + + + + + + {frameworks.length > 0 && ( + + + Set up with this guide + + {frameworks.map(f => ( + + + + + + ))} + + )} + {frameworkGuides.length > 0 && ( + + + Set up with its own guide + + {frameworkGuides.map(g => ( + + + + + + + ))} + + )} + + + +
+
+ +
+ {framework && ( + + )} +
+ {children} +
+ ); +} + +const payloadCache = new Map>(); + +function fetchPayload(url: string): Promise { + let promise = payloadCache.get(url); + if (!promise) { + promise = fetch(url).then(res => { + if (!res.ok) { + throw new Error(`Failed to load ${url}: ${res.status}`); + } + return res.json(); + }); + // Allow retrying after a failed request + promise.catch(() => payloadCache.delete(url)); + payloadCache.set(url, promise); + } + return promise; +} + +/** + * Client-side stand-ins for the server-only MDX components, scoped to the selected + * framework on the page's runtime. + */ +function clientMdxComponents( + payload: PlatformContentPayload, + platform: string, + runtime: string, + framework: string +) { + // Checked in order, like the server's fallback chain + const platformKeys = [`${platform}.${framework}`, `${platform}.${runtime}`]; + + function MDX({code}: {code: string | null | undefined}) { + const Component = useMemo(() => (code ? getMDXComponent(code) : null), [code]); + return Component ? : null; + } + + function Include({name}: {name: string}) { + return ; + } + + function PlatformContent({includePath}: {includePath: string}) { + return ; + } + + function PlatformLink({children, to}: {children: ReactNode; to?: string}) { + if (!to) { + return children; + } + return ( + + {children} + + ); + } + + function PlatformSection({ + children, + supported = [], + notSupported = [], + noGuides, + }: { + children: ReactNode; + noGuides?: boolean; + notSupported?: string[]; + supported?: string[]; + }) { + if (noGuides) { + return null; + } + for (const key of platformKeys) { + if (supported.includes(key)) { + return
{children}
; + } + if (notSupported.includes(key)) { + return null; + } + } + return supported.length ? null :
{children}
; + } + + const components = { + Alert, + CodeBlock, + CodeTabs, + Expandable, + FeatureBadge, + Include, + Link: SmartLink, + OnboardingOption, + OnboardingOptionButtons, + OnboardingSteps, + PlatformContent, + PlatformLink, + PlatformSection, + a: SmartLink, + }; + + return {MDX, components}; +} + +function RemoteFrameworkContent({ + fallback, + framework, + includePath, + platform, + reportContent, + runtime, +}: { + fallback: ReactNode; + framework: Framework; + includePath: string; + platform: string; + reportContent: FrameworkContextValue['reportContent']; + runtime: string; +}) { + const url = platformContentUrl(platform, runtime, framework.key, includePath); + const [payload, setPayload] = useState(null); + const [error, setError] = useState(false); + const codeContext = useContext(CodeContext); + const changedRef = useRef(null); + const targetId = `framework-content-${includePath.replace(/\//g, '-')}`; + + useEffect(() => { + if (error) { + reportContent(includePath, {state: 'unchanged'}); + } else if (!payload) { + reportContent(includePath, {state: 'loading'}); + } else if (!payload.changed || !changedRef.current) { + reportContent(includePath, {state: 'unchanged'}); + } else { + reportContent(includePath, { + state: 'changed', + step: stepTitle(changedRef.current), + targetId, + }); + } + }, [error, includePath, payload, reportContent, targetId]); + + useEffect(() => () => reportContent(includePath, null), [includePath, reportContent]); + + useEffect(() => { + let cancelled = false; + setPayload(null); + setError(false); + fetchPayload(url).then( + result => !cancelled && setPayload(result), + () => !cancelled && setError(true) + ); + return () => { + cancelled = true; + }; + }, [url]); + + const mdx = useMemo( + () => + payload ? clientMdxComponents(payload, platform, runtime, framework.key) : null, + [payload, platform, runtime, framework.key] + ); + + // Apply the current feature selection (tracing, profiling, ...) to the new content + useEffect(() => { + if (payload && codeContext?.onboardingOptions) { + updateElementsVisibilityForOptions(codeContext.onboardingOptions, false); + } + }, [payload, codeContext?.onboardingOptions]); + + if (error || payload?.changed === false) { + return fallback; + } + + if (!payload || !mdx) { + return ( +
+ {fallback} +
+ ); + } + + return ( +
+

+ + For {framework.title} +

+ +
+ ); +} + +/** + * Renders the server-rendered `children` by default, or the selected framework's + * version of `includePath` when inside a `` with a framework selected. + */ +export function FrameworkContent({ + children, + includePath, +}: { + children: ReactNode; + includePath: string; +}) { + const context = useContext(FrameworkContext); + + if (!context?.framework) { + return children; + } + + return ( + + ); +} diff --git a/src/components/frameworkSelector/style.module.scss b/src/components/frameworkSelector/style.module.scss new file mode 100644 index 0000000000000..5ba4afe092218 --- /dev/null +++ b/src/components/frameworkSelector/style.module.scss @@ -0,0 +1,69 @@ +.summary { + display: flex; + align-items: center; + gap: 0.5rem; + margin-top: -0.5rem; + font-size: 0.875rem; + color: var(--gray-11); +} + +.changed { + margin-block: 1rem; + padding: 0.25rem 0 0.25rem 1rem; + border-left: 3px solid var(--accent-purple); + border-radius: 0 0.25rem 0.25rem 0; + // Clears the sticky header and the sticky feature buttons of the quick start + scroll-margin-top: calc(var(--header-height) + 5rem); + animation: highlight 1.6s ease-out; +} + +.label { + display: flex; + align-items: center; + gap: 0.5rem; + margin: 0 0 0.5rem; + font-size: 0.75rem; + font-weight: 500; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--accent-purple); +} + +// The option that has the keyboard focus. The selected option keeps its own color. +.option[data-highlighted]:not([data-state='checked']) { + background-color: var(--accent-purple-light); +} + +@keyframes highlight { + from { + background-color: var(--accent-purple-light); + } + + to { + background-color: transparent; + } +} + +:global(.dark) { + .label { + color: var(--accent-purple-light); + } + + .changed { + animation-name: highlight-dark; + } + + .option[data-highlighted]:not([data-state='checked']) { + background-color: var(--gray-a4); + } +} + +@keyframes highlight-dark { + from { + background-color: color-mix(in srgb, var(--accent-purple), transparent 85%); + } + + to { + background-color: transparent; + } +} diff --git a/src/components/migrationGuide/index.tsx b/src/components/migrationGuide/index.tsx index 1f46b98d4ed71..f4c9f1ba1083e 100644 --- a/src/components/migrationGuide/index.tsx +++ b/src/components/migrationGuide/index.tsx @@ -16,8 +16,10 @@ const MIGRATIONS = { 'dotnet-v7': {storagePrefix: 'sentry-dotnet-v7-migration', platform: 'dotnet'}, } as const; -// Share the MDX component map across item bodies and platform pages. -const components = mdxComponents(); +// Share the MDX component map across item bodies and platform pages. Built on first +// use rather than at import time: `mdxComponents` imports this module, so calling it +// while that import cycle is still resolving can read components that aren't loaded yet. +let components: ReturnType | undefined; // `getMDXComponent` compiles its source with `new Function`, so the same item // body is compiled once instead of once per page it appears on. Keyed by source, @@ -30,6 +32,7 @@ function ItemBody({mdxSource}: {mdxSource: string}) { MDXLayout = getMDXComponent(mdxSource); componentBySource.set(mdxSource, MDXLayout); } + components ??= mdxComponents(); return ; } diff --git a/src/components/platformContent.tsx b/src/components/platformContent.tsx index a4fa773303f60..4a6402165f00d 100644 --- a/src/components/platformContent.tsx +++ b/src/components/platformContent.tsx @@ -12,6 +12,7 @@ import { VERSION_INDICATOR, } from 'sentry-docs/versioning'; +import {FrameworkContent} from './frameworkSelector'; import {Include} from './include'; type Props = { @@ -20,6 +21,11 @@ type Props = { fallbackPlatform?: string; noGuides?: boolean; platform?: string; + /** + * Allow this content to be swapped client-side for another guide's version + * when rendered inside a ``. + */ + switchable?: boolean; }; const updatePathIfVersionedFileDoesNotExist = (path: string): string => { @@ -52,9 +58,33 @@ function MDXLayoutRenderer({mdxSource: source, ...rest}) { return ; } -export async function PlatformContent({includePath, platform, noGuides}: Props) { +export async function PlatformContent({ + includePath, + platform, + noGuides, + switchable, +}: Props) { const {path} = serverContext(); + const doc = await resolvePlatformContent({includePath, path, platform, noGuides}); + const content = doc ? : null; + if (switchable) { + return {content}; + } + + return content; +} + +/** + * Returns the `platform-includes//` file for the page at `path`: the file of the + * guide, its `fallbackGuide`, the platform, its `fallbackPlatform`, or `_default`, in this order. + */ +export async function resolvePlatformContent({ + includePath, + path, + platform, + noGuides, +}: Pick & {path: string[]}) { if (!platform) { if (path.length < 2 || path[0] !== 'platforms') { return null; @@ -136,8 +166,7 @@ export async function PlatformContent({includePath, platform, noGuides}: Props) } } - const {mdxSource} = doc; - return ; + return doc; } const mdxComponentsWithWrapper = mdxComponents({Include, PlatformContent}); diff --git a/src/components/platformIcon.tsx b/src/components/platformIcon.tsx index 132b094e3b550..d7ddb88331ced 100644 --- a/src/components/platformIcon.tsx +++ b/src/components/platformIcon.tsx @@ -76,6 +76,7 @@ import Html5SVG from 'platformicons/svg/HTML5.svg'; import HttpxSVG from 'platformicons/svg/httpx.svg'; import HueySVG from 'platformicons/svg/huey.svg'; import HuggingfaceSVG from 'platformicons/svg/huggingface.svg'; +import HydrogenSVG from 'platformicons/svg/hydrogen.svg'; import IonicSVG from 'platformicons/svg/ionic.svg'; import IrisSVG from 'platformicons/svg/iris.svg'; import JavaSVG from 'platformicons/svg/java.svg'; @@ -235,6 +236,7 @@ import Html5SVGLarge from 'platformicons/svg_80x80/HTML5.svg'; import HttpxSVGLarge from 'platformicons/svg_80x80/httpx.svg'; import HueySVGLarge from 'platformicons/svg_80x80/huey.svg'; import HuggingfaceSVGLarge from 'platformicons/svg_80x80/huggingface.svg'; +import HydrogenSVGLarge from 'platformicons/svg_80x80/hydrogen.svg'; import IonicSVGLarge from 'platformicons/svg_80x80/ionic.svg'; import IrisSVGLarge from 'platformicons/svg_80x80/iris.svg'; import JavaSVGLarge from 'platformicons/svg_80x80/java.svg'; @@ -672,6 +674,10 @@ const formatToSVG = { sm: HonoSVG, lg: HonoSVGLarge, }, + hydrogen: { + sm: HydrogenSVG, + lg: HydrogenSVGLarge, + }, kotlin: { sm: KotlinSVG, lg: KotlinSVGLarge, @@ -1076,6 +1082,7 @@ export const PLATFORM_TO_ICON = { 'javascript-ionic': 'ionic', 'javascript-hapi': 'hapi', 'javascript-hono': 'hono', + 'javascript-hydrogen': 'hydrogen', 'javascript-eve': 'eve', 'javascript-firebase': 'firebase', 'javascript-flue': 'flue', diff --git a/src/mdxComponents.ts b/src/mdxComponents.ts index 13d823b180d63..20bd731cd3f31 100644 --- a/src/mdxComponents.ts +++ b/src/mdxComponents.ts @@ -19,6 +19,7 @@ import {DevDocsCardGrid} from './components/devDocsCardGrid'; import DocImage from './components/docImage'; import {Expandable} from './components/expandable'; import {FeatureBadge} from './components/featureBadge'; +import {FrameworkSelector} from './components/frameworkSelector'; import {GitHubCodePreview} from './components/githubCodePreview'; import {GitHubDomainChecker} from './components/githubDomainChecker'; import {GradleFeatureConfig} from './components/gradleFeatureConfig'; @@ -99,6 +100,7 @@ export function mdxComponents( DefinitionList, Expandable, FeatureBadge, + FrameworkSelector, GuideGrid, IntegrationGrid, IntegrationListItem,