diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 206560136b5..5620f4b1137 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -41,6 +41,7 @@ body: Which website or app were you using when the bug happened? Note: - Please provide a link via our pre-configured Stackblitz project ([file-based routes](https://stackblitz.com/github/tanstack/router/tree/main/examples/react/quickstart-file-based?file=src%2Fmain.tsx)|[code-based routes](https://stackblitz.com/github/tanstack/router/tree/main/examples/react/quickstart?file=src%2Fmain.tsx)) or a link to a repo that can reproduce the issue. + - For Start bugs, use the baseline starters where possible: [React start-basic](https://github.com/tanstack/router/tree/main/examples/react/start-basic) | [Solid start-basic](https://github.com/tanstack/router/tree/main/examples/solid/start-basic). - Your bug will may get fixed much faster if we can run your code and it doesn't have dependencies other than the `router` npm package / dependency. - To create a shareable code example you can use Stackblitz. Please no localhost URLs. - Please read these tips for providing a minimal example: https://stackoverflow.com/help/mcve. diff --git a/docs/router/guide/authenticated-routes.md b/docs/router/guide/authenticated-routes.md index 706e89955c7..e4885e983a5 100644 --- a/docs/router/guide/authenticated-routes.md +++ b/docs/router/guide/authenticated-routes.md @@ -157,7 +157,7 @@ If your authentication flow relies on interactions with React context and/or hoo We'll cover the `router.context` options in-detail in the [Router Context](./router-context.md) section. -Here's an example that uses React context and hooks for protecting authenticated routes in TanStack Router. See the entire working setup in the [Authenticated Routes example](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes). +Here's an example that uses React context and hooks for protecting authenticated routes in TanStack Router. See a reference implementation in the [Authenticated Routes example](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes). @@ -335,4 +335,4 @@ Working authentication examples are available in the repository: - [Basic Authentication Example](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes) - Simple authentication with context - [Firebase Authentication](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes-firebase) - Firebase Auth integration -- [TanStack Start Auth Examples](https://github.com/TanStack/router/tree/main/examples/react) - Various auth implementations with TanStack Start +- [TanStack Start Authentication Overview](/router/latest/docs/framework/react/start/guide/authentication-overview) - Compare hosted, OSS, and DIY auth approaches for Start diff --git a/docs/router/guide/custom-link.md b/docs/router/guide/custom-link.md index dd7038cecd8..24c2c2b5e3f 100644 --- a/docs/router/guide/custom-link.md +++ b/docs/router/guide/custom-link.md @@ -174,7 +174,7 @@ export const CustomLink: LinkComponent = ( ### MUI example -There is an [example](https://github.com/TanStack/router/tree/main/examples/react/start-material-ui) available which uses these patterns. +These patterns are designed to work directly with MUI's `Link`/`Button` components in your app. #### `Link` diff --git a/docs/router/guide/internationalization-i18n.md b/docs/router/guide/internationalization-i18n.md index f6fd04087e7..94155e0c944 100644 --- a/docs/router/guide/internationalization-i18n.md +++ b/docs/router/guide/internationalization-i18n.md @@ -122,7 +122,7 @@ This pattern combines TanStack Router with a client-side i18n library. It is sui Paraglide provides type-safe translations, locale detection, and URL localization that pair naturally with TanStack Router. -**GitHub example:** +**Reference implementation:** [https://github.com/TanStack/router/tree/main/examples/react/i18n-paraglide](https://github.com/TanStack/router/tree/main/examples/react/i18n-paraglide) ### Project Setup @@ -168,8 +168,10 @@ This pattern integrates i18n at the routing and server layers. It is suitable wh ### TanStack Start + Paraglide -**GitHub example:** -[https://github.com/TanStack/router/tree/main/examples/react/start-i18n-paraglide](https://github.com/TanStack/router/tree/main/examples/react/start-i18n-paraglide) +**Start guides:** + +- [React Start Middleware](https://tanstack.com/router/latest/docs/framework/react/start/guide/middleware) +- [Solid Start Middleware](https://tanstack.com/router/latest/docs/framework/solid/start/guide/middleware) ### Server Middleware (SSR) diff --git a/docs/router/guide/url-rewrites.md b/docs/router/guide/url-rewrites.md index 7bc3df85452..32aef6bdf42 100644 --- a/docs/router/guide/url-rewrites.md +++ b/docs/router/guide/url-rewrites.md @@ -488,9 +488,9 @@ const composedRewrite = composeRewrites([ ## Examples -Complete working examples are available in the TanStack Router repository: +Reference implementations and guides: - [React + Paraglide (Client-side i18n)](https://github.com/TanStack/router/tree/main/examples/react/i18n-paraglide) -- [React + TanStack Start + Paraglide (SSR i18n)](https://github.com/TanStack/router/tree/main/examples/react/start-i18n-paraglide) +- [React + TanStack Start + Paraglide (SSR i18n)](https://tanstack.com/router/latest/docs/framework/react/start/guide/middleware) - [Solid + Paraglide (Client-side i18n)](https://github.com/TanStack/router/tree/main/examples/solid/i18n-paraglide) -- [Solid + TanStack Start + Paraglide (SSR i18n)](https://github.com/TanStack/router/tree/main/examples/solid/start-i18n-paraglide) +- [Solid + TanStack Start + Paraglide (SSR i18n)](https://tanstack.com/router/latest/docs/framework/solid/start/guide/middleware) diff --git a/docs/router/how-to/setup-authentication.md b/docs/router/how-to/setup-authentication.md index 2ef819c676c..f3f8d08df4d 100644 --- a/docs/router/how-to/setup-authentication.md +++ b/docs/router/how-to/setup-authentication.md @@ -482,4 +482,4 @@ After setting up basic authentication, you might want to: - [Authenticated Routes Guide](../guide/authenticated-routes.md) - Detailed conceptual guide - [Router Context Guide](../guide/router-context.md) - Understanding context in TanStack Router -- [Authentication Examples](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes) - Complete working examples +- [Authenticated Routes Guide](../guide/authenticated-routes.md) - End-to-end route protection patterns diff --git a/docs/start/config.json b/docs/start/config.json index 180d38ed44d..f54ea4c78dd 100644 --- a/docs/start/config.json +++ b/docs/start/config.json @@ -302,110 +302,6 @@ } ] }, - { - "label": "Examples", - "children": [], - "frameworks": [ - { - "label": "react", - "children": [ - { - "label": "Basic", - "to": "framework/react/examples/start-basic" - }, - { - "label": "Basic + React Query", - "to": "framework/react/examples/start-basic-react-query" - }, - { - "label": "Basic + Clerk Auth", - "to": "framework/react/examples/start-clerk-basic" - }, - { - "label": "Basic + DIY Auth", - "to": "framework/react/examples/start-basic-auth" - }, - { - "label": "Basic + Supabase Auth", - "to": "framework/react/examples/start-supabase-basic" - }, - { - "label": "Trellaux + Convex", - "to": "framework/react/examples/start-convex-trellaux" - }, - { - "label": "Trellaux", - "to": "framework/react/examples/start-trellaux" - }, - { - "label": "WorkOS", - "to": "framework/react/examples/start-workos" - }, - { - "label": "Material UI", - "to": "framework/react/examples/start-material-ui" - }, - { - "label": "Basic + Auth.js", - "to": "framework/react/examples/start-basic-authjs" - }, - { - "label": "Basic + Static rendering", - "to": "framework/react/examples/start-basic-static" - }, - { - "label": "Cloudflare Vite Plugin", - "to": "framework/react/examples/start-basic-cloudflare" - } - ] - }, - { - "label": "solid", - "children": [ - { - "label": "Basic", - "to": "framework/solid/examples/start-basic" - }, - { - "label": "Basic + Solid Query", - "to": "framework/solid/examples/start-basic-solid-query" - }, - { - "label": "Basic + DIY Auth", - "to": "framework/solid/examples/start-basic-auth" - }, - { - "label": "Basic + Supabase Auth", - "to": "framework/solid/examples/start-supabase-basic" - }, - { - "label": "Basic + Convex + Better Auth", - "to": "framework/solid/examples/start-convex-better-auth" - }, - { - "label": "Basic + Auth.js", - "to": "framework/solid/examples/start-basic-authjs" - }, - { - "label": "Basic + Static rendering", - "to": "framework/solid/examples/start-basic-static" - }, - { - "label": "Cloudflare Vite Plugin", - "to": "framework/solid/examples/start-basic-cloudflare" - }, - { - "label": "Netlify Vite Plugin", - "to": "framework/solid/examples/start-basic-netlify" - }, - { - "label": "Nitro Vite Plugin", - "to": "framework/solid/examples/start-basic-nitro" - } - ] - } - ] - }, { "label": "Tutorials", "children": [], diff --git a/docs/start/framework/react/build-from-scratch.md b/docs/start/framework/react/build-from-scratch.md index 59579c1be36..00f5e4ddfe8 100644 --- a/docs/start/framework/react/build-from-scratch.md +++ b/docs/start/framework/react/build-from-scratch.md @@ -14,7 +14,7 @@ This guide will help you build a **very** basic TanStack Start web application. - Display a counter - Increment the counter on the server and client -[Here is what that will look like](https://stackblitz.com/github/tanstack/router/tree/main/examples/react/start-counter) +[If you want a generated starting point instead, use TanStack Builder](https://tanstack.com/builder) Let's create a new project directory and initialize it. diff --git a/docs/start/framework/react/comparison.md b/docs/start/framework/react/comparison.md index b68a1cc08e7..953224d3a46 100644 --- a/docs/start/framework/react/comparison.md +++ b/docs/start/framework/react/comparison.md @@ -264,10 +264,10 @@ const authMiddleware = createMiddleware({ type: 'function' }) **Current Status**: - **Next.js**: Full production support with extensive ecosystem -- **TanStack Start**: In active development, expected soon +- **TanStack Start**: Supported - **React Router**: Experimental support available -RSC is still evolving, and TanStack Start is taking time to ensure the best possible implementation that aligns with its type-safety-first philosophy. +RSC is still evolving across the ecosystem. TanStack Start treats RSC as a composable primitive alongside Router and server functions. ## Performance Considerations diff --git a/docs/start/framework/react/getting-started.md b/docs/start/framework/react/getting-started.md index 7f3c1223d82..4c6f928cdff 100644 --- a/docs/start/framework/react/getting-started.md +++ b/docs/start/framework/react/getting-started.md @@ -14,9 +14,9 @@ title: Getting Started Choose one of the following options to start building a _new_ TanStack Start project: -- [TanStack Start CLI](./quick-start) - Just run `npm create @tanstack/start@latest`. Local, fast, and optionally customizable +- [TanStack Start CLI](./quick-start) - Just run `npx @tanstack/cli create`. Local, fast, and optionally customizable - [TanStack Builder](https://tanstack.com/builder) - A visual interface to configure new TanStack projects with a few clicks -- [Quick Start Examples](./quick-start) Download or clone one of our official examples +- [Issue repro baseline](https://github.com/TanStack/router/tree/main/examples/react/start-basic) - A minimal starter we keep stable for bug reports and reproductions - [Build a project from scratch](./build-from-scratch) - A guide to building a TanStack Start project line-by-line, file-by-file. ## Next Steps diff --git a/docs/start/framework/react/guide/authentication-overview.md b/docs/start/framework/react/guide/authentication-overview.md index 16fc63090ce..bce3337b3be 100644 --- a/docs/start/framework/react/guide/authentication-overview.md +++ b/docs/start/framework/react/guide/authentication-overview.md @@ -146,7 +146,7 @@ Build your own authentication system using TanStack Start's server functions and - **Multi-factor Authentication** - Enterprise-grade security options - **Compliance Ready** - SOC 2, GDPR, and CCPA compliant -[Visit WorkOS →](https://workos.com/) | [View example →](https://github.com/TanStack/router/tree/main/examples/react/start-workos) +[Visit WorkOS →](https://workos.com/) | [Get started in Builder →](https://tanstack.com/builder) ### Clerk - Complete Authentication Platform @@ -163,21 +163,21 @@ Build your own authentication system using TanStack Start's server functions and - **Multi-factor Authentication** - SMS, TOTP, and backup codes - **Organizations & Teams** - Built-in support for team-based applications -[Visit Clerk →](https://go.clerk.com/wOwHtuJ) | [Sign up free →](https://go.clerk.com/PrSDXti) | [View example →](https://github.com/TanStack/router/tree/main/examples/react/start-clerk-basic) +[Visit Clerk →](https://go.clerk.com/wOwHtuJ) | [Sign up free →](https://go.clerk.com/PrSDXti) | [Get started in Builder →](https://tanstack.com/builder) -## Examples +## Starter Paths **Partner Solutions:** -- [Clerk Integration](https://github.com/TanStack/router/tree/main/examples/react/start-clerk-basic) -- [WorkOS Integration](https://github.com/TanStack/router/tree/main/examples/react/start-workos) +- [Clerk Integration](https://tanstack.com/builder) +- [WorkOS Integration](https://tanstack.com/builder) **DIY Implementations:** -- [Basic Auth with Prisma](https://github.com/TanStack/router/tree/main/examples/react/start-basic-auth) -- [Supabase Auth](https://github.com/TanStack/router/tree/main/examples/react/start-supabase-basic) +- [Build with server sessions and middleware](./authentication) +- [Database setup patterns](./databases) -**Client-Side Examples:** +**Client-Side Patterns:** - [Basic Authentication](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes) - [Firebase Auth](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes-firebase) @@ -220,7 +220,7 @@ Build your own authentication system using TanStack Start's server functions and - **Partner solutions** → [Clerk](https://go.clerk.com/wOwHtuJ) or [WorkOS](https://workos.com/) - **DIY implementation** → [Authentication Guide](./authentication.md) -- **Examples** → [Working implementations](https://github.com/TanStack/router/tree/main/examples/react) +- **Templates & integrations** → [TanStack Builder](https://tanstack.com/builder) ## Resources diff --git a/docs/start/framework/react/guide/authentication.md b/docs/start/framework/react/guide/authentication.md index f42fbc220fe..50982206a7d 100644 --- a/docs/start/framework/react/guide/authentication.md +++ b/docs/start/framework/react/guide/authentication.md @@ -540,13 +540,13 @@ export const loginFn = createServerFn({ method: 'POST' }) }) ``` -## Working Examples +## Starter Paths -Study these implementations to understand different authentication patterns: +Use these paths depending on what you need: -- **[Basic Auth with Prisma](https://github.com/TanStack/router/tree/main/examples/react/start-basic-auth)** - Complete DIY implementation with database and sessions -- **[Supabase Integration](https://github.com/TanStack/router/tree/main/examples/react/start-supabase-basic)** - Third-party service integration example -- **[Client-side Context Auth](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes)** - Client-only authentication patterns +- **[TanStack Builder](https://tanstack.com/builder)** - Generate projects with hosted auth providers and deployment options +- **[Authentication Overview](./authentication-overview)** - Compare hosted, OSS, and DIY approaches +- **[Client-side Context Auth](/router/latest/docs/framework/react/guide/authenticated-routes)** - Client-only authentication patterns ## Migration from Other Solutions @@ -607,4 +607,4 @@ When implementing authentication, consider: - **Monitoring**: Add logging and monitoring for authentication events - **Compliance**: Ensure compliance with relevant regulations if storing personal data -For other authentication approaches, check the [Authentication Overview](./authentication-overview.md). For specific integration help, explore our [working examples](https://github.com/TanStack/router/tree/main/examples/react). +For other authentication approaches, check the [Authentication Overview](./authentication-overview.md). For specific integration help, use [TanStack Builder](https://tanstack.com/builder) and the auth guides linked above. diff --git a/docs/start/framework/react/guide/hosting.md b/docs/start/framework/react/guide/hosting.md index 14b5f77e079..6e7eb0702bd 100644 --- a/docs/start/framework/react/guide/hosting.md +++ b/docs/start/framework/react/guide/hosting.md @@ -112,7 +112,7 @@ pnpm run deploy Deploy your application to Cloudflare Workers using their one-click deployment process, and you're ready to go! -A full TanStack Start example for Cloudflare Workers is available [here](https://github.com/TanStack/router/tree/main/examples/react/start-basic-cloudflare). +You can generate a Cloudflare-ready project with [TanStack Builder](https://tanstack.com/builder) by selecting the Cloudflare deployment option. ### Netlify ⭐ _Official Partner_ @@ -326,7 +326,7 @@ We provide a reference implementation that demonstrates one approach to building **Quick Setup:** -1. Copy the [`server.ts`](https://github.com/tanstack/router/blob/main/examples/react/start-bun/server.ts) file from the example repository to your project root (or use it as inspiration for your own implementation) +1. Create a `server.ts` file in your project root and adapt the Bun server strategy shown in this section. 2. Build your application: @@ -409,7 +409,7 @@ bun run server.ts 🚀 Server running at http://localhost:3000 ``` -For a complete working example, check out the [TanStack Start + Bun example](https://github.com/TanStack/router/tree/main/examples/react/start-bun) in this repository. +To start from a Bun-ready base quickly, generate a new project in [TanStack Builder](https://tanstack.com/builder) and select Bun-compatible deployment settings. ### Appwrite Sites @@ -418,7 +418,7 @@ When deploying to [Appwrite Sites](https://appwrite.io/products/sites), you'll n 1. **Create a TanStack Start app** (or use an existing one) ```bash -npm create @tanstack/start@latest +npx @tanstack/cli create ``` 2. **Push your project to a GitHub repository** diff --git a/docs/start/framework/react/guide/observability.md b/docs/start/framework/react/guide/observability.md index 71d39d16ce8..c87bbecd0ca 100644 --- a/docs/start/framework/react/guide/observability.md +++ b/docs/start/framework/react/guide/observability.md @@ -774,4 +774,4 @@ Direct OpenTelemetry support is coming to TanStack Start, which will provide aut - **[Sentry Documentation](https://docs.sentry.io/)** - **[OpenTelemetry Documentation](https://opentelemetry.io/docs/)** - Industry standard observability -- **[Working Example](https://github.com/TanStack/router/tree/main/examples/react/start-basic)** - See observability patterns in action +- **[TanStack Builder](https://tanstack.com/builder)** - Generate projects with Sentry and deployment options preconfigured diff --git a/docs/start/framework/react/guide/streaming-data-from-server-functions.md b/docs/start/framework/react/guide/streaming-data-from-server-functions.md index 474452e8856..ad39caa26d9 100644 --- a/docs/start/framework/react/guide/streaming-data-from-server-functions.md +++ b/docs/start/framework/react/guide/streaming-data-from-server-functions.md @@ -6,7 +6,7 @@ Streaming data from the server has become very popular thanks to the rise of AI The two most popular ways of streaming data from server functions are using `ReadableStream`-s or async generators. -You can see how to implement both in the [Streaming Data From Server Functions example](https://github.com/TanStack/router/tree/main/examples/react/start-streaming-data-from-server-functions). +The examples below show both patterns directly, so you can copy them into any Start project generated from [TanStack Builder](https://tanstack.com/builder) or the CLI. ## Typed Readable Streams diff --git a/docs/start/framework/react/overview.md b/docs/start/framework/react/overview.md index 7fe29f64f9d..4da388c0f47 100644 --- a/docs/start/framework/react/overview.md +++ b/docs/start/framework/react/overview.md @@ -34,7 +34,7 @@ That said, if you **know with certainty** that you will not need any of the abov ## Are there limitations? -The only relevant limitation is that TanStack Start does not currently support React Server Components, **but we are actively working on integration and expect to support them in the near future.** +TanStack Start supports React Server Components. Otherwise, TanStack Start provides the same capability as other full-stack frameworks like Next.js, Remix, etc, with even more features and a more powerful developer experience. diff --git a/docs/start/framework/react/quick-start.md b/docs/start/framework/react/quick-start.md index d16f6683dbf..c8198e835f7 100644 --- a/docs/start/framework/react/quick-start.md +++ b/docs/start/framework/react/quick-start.md @@ -5,82 +5,37 @@ title: Quick Start ## Impatient? -The fastest way to get a Start project up and running is with the CLI. Just run +The fastest way to get a Start project up and running is with [TanStack Builder](https://tanstack.com/builder) or the CLI. -``` -pnpm create @tanstack/start@latest -``` - -or +### Builder (recommended) -``` -npm create @tanstack/start@latest -``` +Open [TanStack Builder](https://tanstack.com/builder), choose your framework/toolchain/deployment/add-ons, and generate a project. -depending on your package manager of choice. You'll be prompted to add things like Tailwind, eslint, and a ton of other options. +### CLI -You can also clone and run the [Basic](https://github.com/TanStack/router/tree/main/examples/react/start-basic) example right away with the following commands: +Run: -```bash -npx gitpick TanStack/router/tree/main/examples/react/start-basic start-basic -cd start-basic -npm install -npm run dev +``` +npx @tanstack/cli create ``` -If you'd like to use a different example, you can replace `start-basic` above with the slug of the example you'd like to use from the list below. - -Once you've cloned the example you want, head back to the [Routing](./guide/routing) guide to learn how to use TanStack Start! - -## Examples - -TanStack Start has a load of examples to get you started. Pick one of the examples below to get started! - -- [Basic](https://github.com/TanStack/router/tree/main/examples/react/start-basic) (start-basic) -- [Basic + Auth](https://github.com/TanStack/router/tree/main/examples/react/start-basic-auth) (start-basic-auth) -- [Counter](https://github.com/TanStack/router/tree/main/examples/react/start-counter) (start-counter) -- [Basic + React Query](https://github.com/TanStack/router/tree/main/examples/react/start-basic-react-query) (start-basic-react-query) -- [Clerk Auth](https://github.com/TanStack/router/tree/main/examples/react/start-clerk-basic) (start-clerk-basic) -- [Convex + Trellaux](https://github.com/TanStack/router/tree/main/examples/react/start-convex-trellaux) (start-convex-trellaux) -- [Supabase](https://github.com/TanStack/router/tree/main/examples/react/start-supabase-basic) (start-supabase-basic) -- [Trellaux](https://github.com/TanStack/router/tree/main/examples/react/start-trellaux) (start-trellaux) -- [WorkOS](https://github.com/TanStack/router/tree/main/examples/react/start-workos) (start-workos) -- [Material UI](https://github.com/TanStack/router/tree/main/examples/react/start-material-ui) (start-material-ui) - -### Stackblitz - -Each example above has an embedded stackblitz preview to find the one that feels like a good starting point +You'll be prompted to add things like Tailwind, eslint, and a ton of other options. -### Quick Deploy +### Canonical issue repro baseline -To quickly deploy an example, click the **Deploy to Netlify** button on an example's page to both clone and deploy the example to Netlify. +We keep exactly one lightweight React Start baseline for reproductions and bug reports: -### Manual Deploy +- [start-basic](https://github.com/TanStack/router/tree/main/examples/react/start-basic) -To manually clone and deploy the example to anywhere else you'd like, use the following commands replacing `EXAMPLE_SLUG` with the slug of the example you'd like to use from above: +Clone it with: ```bash -npx gitpick TanStack/router/tree/main/examples/react/EXAMPLE_SLUG my-new-project -cd my-new-project +npx gitpick TanStack/router/tree/main/examples/react/start-basic start-basic +cd start-basic npm install npm run dev ``` -Once you've cloned or deployed an example, head back to the [Routing](./guide/routing) guide to learn how to use TanStack Start! - -## Other Router Examples - -While not Start-specific examples, these may help you understand more about how TanStack Router works: +If you're looking for full templates (blog, resume, and more), use [TanStack Builder](https://tanstack.com/builder). -- [Quickstart (file-based)](https://github.com/TanStack/router/tree/main/examples/react/quickstart-file-based) -- [Basic (file-based)](https://github.com/TanStack/router/tree/main/examples/react/basic-file-based) -- [Kitchen Sink (file-based)](https://github.com/TanStack/router/tree/main/examples/react/kitchen-sink-file-based) -- [Kitchen Sink + React Query (file-based)](https://github.com/TanStack/router/tree/main/examples/react/kitchen-sink-react-query-file-based) -- [Location Masking](https://github.com/TanStack/router/tree/main/examples/react/location-masking) -- [Authenticated Routes](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes) -- [Scroll Restoration](https://github.com/TanStack/router/tree/main/examples/react/scroll-restoration) -- [Deferred Data](https://github.com/TanStack/router/tree/main/examples/react/deferred-data) -- [Navigation Blocking](https://github.com/TanStack/router/tree/main/examples/react/navigation-blocking) -- [View Transitions](https://github.com/TanStack/router/tree/main/examples/react/view-transitions) -- [With tRPC](https://github.com/TanStack/router/tree/main/examples/react/with-trpc) -- [With tRPC + React Query](https://github.com/TanStack/router/tree/main/examples/react/with-trpc-react-query) +Once you've created your project, head to the [Routing](./guide/routing) guide. diff --git a/docs/start/framework/react/tutorial/reading-writing-file.md b/docs/start/framework/react/tutorial/reading-writing-file.md index 93b9cff0b02..704864c2513 100644 --- a/docs/start/framework/react/tutorial/reading-writing-file.md +++ b/docs/start/framework/react/tutorial/reading-writing-file.md @@ -35,7 +35,7 @@ The complete code for this tutorial is available on [GitHub](https://github.com/ First, let's create a new TanStack Start project: ```bash -pnpm create @tanstack/start@latest devjokes +npx @tanstack/cli create devjokes cd devjokes ``` diff --git a/docs/start/framework/solid/getting-started.md b/docs/start/framework/solid/getting-started.md index 18ef51f5353..eea67680c9c 100644 --- a/docs/start/framework/solid/getting-started.md +++ b/docs/start/framework/solid/getting-started.md @@ -7,9 +7,9 @@ title: Getting Started Choose one of the following options to start building a _new_ TanStack Start project: -- [TanStack Start CLI] - Just run `npm create @tanstack/start@latest --framework solid`. Local, fast, and optionally customizable -- [TanStack Builder](#) (coming soon!) - A visual interface to configure new TanStack projects with a few clicks -- [Quick Start Examples](./quick-start) Download or clone one of our official examples +- [TanStack Start CLI](./quick-start) - Just run `npx @tanstack/cli create --framework solid`. Local, fast, and optionally customizable +- [TanStack Builder](https://tanstack.com/builder) - A visual interface to configure new TanStack projects with a few clicks +- [Issue repro baseline](https://github.com/TanStack/router/tree/main/examples/solid/start-basic) - A minimal starter we keep stable for bug reports and reproductions - [Build a project from scratch](./build-from-scratch) - A guide to building a TanStack Start project line-by-line, file-by-file. ## Next Steps diff --git a/docs/start/framework/solid/guide/authentication.md b/docs/start/framework/solid/guide/authentication.md index 289aa23e75a..45f79ffe684 100644 --- a/docs/start/framework/solid/guide/authentication.md +++ b/docs/start/framework/solid/guide/authentication.md @@ -599,4 +599,4 @@ When implementing authentication, consider: - **Monitoring**: Add logging and monitoring for authentication events - **Compliance**: Ensure compliance with relevant regulations if storing personal data -For other authentication approaches, check the [Authentication Overview](./authentication-overview.md). For specific integration help, see the [How-to Guides](/router/latest/docs/framework/solid/how-to/README.md#authentication) or explore our [working examples](https://github.com/TanStack/router/tree/main/examples/solid). +For other authentication approaches, check the [Authentication Overview](./authentication-overview.md). For specific integration help, see the [How-to Guides](/router/latest/docs/framework/solid/how-to/README.md#authentication) and use [TanStack Builder](https://tanstack.com/builder). diff --git a/docs/start/framework/solid/guide/hosting.md b/docs/start/framework/solid/guide/hosting.md index 5c374e8fd19..7a623456b71 100644 --- a/docs/start/framework/solid/guide/hosting.md +++ b/docs/start/framework/solid/guide/hosting.md @@ -310,7 +310,7 @@ We provide a reference implementation that demonstrates one approach to building **Quick Setup:** -1. Copy the [`server.ts`](https://github.com/tanstack/router/blob/main/examples/react/start-bun/server.ts) file from the example repository to your project root (or use it as inspiration for your own implementation) +1. Create a `server.ts` file in your project root and adapt the Bun server strategy shown in this section. 2. Build your application: @@ -393,7 +393,7 @@ bun run server.ts 🚀 Server running at http://localhost:3000 ``` -For a complete working example, check out the [TanStack Start + Bun example](https://github.com/TanStack/router/tree/main/examples/react/start-bun) in this repository. +To start from a Bun-ready base quickly, generate a new project in [TanStack Builder](https://tanstack.com/builder) and select Bun-compatible deployment settings. ### Appwrite Sites @@ -402,7 +402,7 @@ When deploying to [Appwrite Sites](https://appwrite.io/products/sites), you'll n 1. **Create a TanStack Start app** (or use an existing one) ```bash -npm create @tanstack/start@latest +npx @tanstack/cli create --framework solid ``` 2. **Push your project to a GitHub repository** diff --git a/docs/start/framework/solid/guide/observability.md b/docs/start/framework/solid/guide/observability.md index 20b5827c3af..80351895045 100644 --- a/docs/start/framework/solid/guide/observability.md +++ b/docs/start/framework/solid/guide/observability.md @@ -657,4 +657,4 @@ Direct OpenTelemetry support is coming to TanStack Start, which will provide aut - **[Sentry Documentation](https://docs.sentry.io/)** - **[OpenTelemetry Documentation](https://opentelemetry.io/docs/)** - Industry standard observability -- **[Working Example](https://github.com/TanStack/router/tree/main/examples/solid/start-basic)** - See observability patterns in action +- **[TanStack Builder](https://tanstack.com/builder)** - Generate projects with Sentry and deployment options preconfigured diff --git a/docs/start/framework/solid/quick-start.md b/docs/start/framework/solid/quick-start.md index b311e8850a8..54e4a341c9c 100644 --- a/docs/start/framework/solid/quick-start.md +++ b/docs/start/framework/solid/quick-start.md @@ -5,59 +5,37 @@ title: Quick Start ## Impatient? -The fastest way to get a Start project up and running is with the cli. Just run +The fastest way to get a Start project up and running is with [TanStack Builder](https://tanstack.com/builder) or the CLI. -``` -pnpm create @tanstack/start@latest --framework solid -``` - -or +### Builder (recommended) -``` -npm create @tanstack/start@latest -- --framework solid -``` +Open [TanStack Builder](https://tanstack.com/builder), choose your framework/toolchain/deployment/add-ons, and generate a project. -depending on your package manager of choice. You'll be prompted to add things like Tailwind, eslint, and a ton of other options. +### CLI -You can also clone and run the [Basic](https://github.com/TanStack/router/tree/main/examples/solid/start-basic) example right away with the following commands: +Run: -```bash -npx gitpick TanStack/router/tree/main/examples/solid/start-basic start-basic -cd start-basic -npm install -npm run dev +``` +npx @tanstack/cli create --framework solid ``` -If you'd like to use a different example, you can replace `start-basic` above with the slug of the example you'd like to use from the list below. - -Once you've cloned the example you want, head back to the [Routing](./guide/routing) guide to learn how to use TanStack Start! - -## Examples - -TanStack Start has loads of examples to get you started. Pick one of the examples below to get started! - -- [Bare](https://github.com/TanStack/router/tree/main/examples/solid/start-bare) (start-bare) -- [Basic](https://github.com/TanStack/router/tree/main/examples/solid/start-basic) (start-basic) -- [Basic Static](https://github.com/TanStack/router/tree/main/examples/solid/start-basic-stats) (start-basic-static) -- [Counter](https://github.com/TanStack/router/tree/main/examples/solid/start-counter) (start-counter) - -### Stackblitz - -Each example above has an embedded stackblitz preview to find the one that feels like a good starting point +You'll be prompted to add things like Tailwind, eslint, and a ton of other options. -### Quick Deploy +### Canonical issue repro baseline -To quickly deploy an example, click the **Deploy to Netlify** button on an example's page to both clone and deploy the example to Netlify. +We keep exactly one lightweight Solid Start baseline for reproductions and bug reports: -### Manual Deploy +- [start-basic](https://github.com/TanStack/router/tree/main/examples/solid/start-basic) -To manually clone and deploy the example to anywhere else you'd like, use the following commands replacing `EXAMPLE_SLUG` with the slug of the example you'd like to use from above: +Clone it with: ```bash -npx gitpick TanStack/router/tree/main/examples/solid/EXAMPLE_SLUG my-new-project -cd my-new-project +npx gitpick TanStack/router/tree/main/examples/solid/start-basic start-basic +cd start-basic npm install npm run dev ``` -Once you've cloned or deployed an example, head back to the [Routing](./guide/routing) guide to learn how to use TanStack Start! +If you're looking for full templates, use [TanStack Builder](https://tanstack.com/builder). + +Once you've created your project, head to the [Routing](./guide/routing) guide. diff --git a/docs/start/start-examples-migration.md b/docs/start/start-examples-migration.md new file mode 100644 index 00000000000..47f41d5f525 --- /dev/null +++ b/docs/start/start-examples-migration.md @@ -0,0 +1,79 @@ +--- +title: Start Examples Migration Plan +--- + +This document tracks the Start-first migration from hand-maintained `examples/*/start-*` apps to Builder/CLI kits, guide-first education, and e2e fixtures for QA. + +## Goals + +- Make [TanStack Builder](https://tanstack.com/builder) the default source of truth for starters and templates. +- Keep exactly one issue-repro baseline per framework: + - React: `examples/react/start-basic` + - Solid: `examples/solid/start-basic` +- Reduce long-term maintenance burden for showcase-style examples. +- Preserve link equity while migrating docs and entry points. + +## Classification Rules + +- **Template**: polished end result (blog/cv/kanban) -> move to Builder kit. +- **Guide**: topical implementation pattern (auth/deploy/i18n/streaming) -> distill into guides. +- **Baseline**: minimal repro app -> keep as a stable reference example. + +## Phase 1 Scope (Start examples only) + +- In: `examples/react/start-*`, `examples/solid/start-*` +- Out: non-Start Router examples (handled in a later phase) + +## Migration Matrix (Phase 1) + +### Keep (baseline) + +- React: `start-basic` +- Solid: `start-basic` + +### Move to Builder Kits + +- `start-blog-starter` (new) +- `start-cv-template` (new) +- `start-trellaux` / `start-convex-trellaux` -> future kanban-style kit + +### Move to Guides (and/or Builder integration paths) + +- Auth: `start-basic-auth`, `start-basic-authjs`, `start-clerk-basic`, `start-workos`, `start-supabase-basic`, `solid/start-basic-auth`, `solid/start-convex-better-auth` +- Deployment: `start-basic-cloudflare`, `start-bun`, `solid/start-basic-cloudflare`, `solid/start-basic-netlify`, `solid/start-basic-nitro` +- Data/rendering/features: `start-basic-react-query`, `solid/start-basic-solid-query`, `start-streaming-data-from-server-functions`, `start-basic-static`, `start-basic-rsc`, `start-i18n-paraglide`, `solid/start-i18n-paraglide`, `start-tailwind-v4`, `start-material-ui` + +### Deprecate (tombstone path) + +- `start-counter` +- `start-large` +- `start-bare` (React) + +## SEO and Link Preservation + +- Do not hard-delete legacy example paths until docs and links are fully migrated. +- Keep migration/tombstone READMEs in deprecated example folders when they are retired. +- Point all new documentation entry points to Builder first, then to guides. + +## Current Progress + +- Start docs now use `npx @tanstack/cli create` for CLI setup. +- Builder is the primary entry point in Start quick start/getting started docs. +- The temporary "Starter Baselines" docs nav section has been removed. +- Non-baseline Start example READMEs now point to Builder/CLI and relevant guides. +- Non-baseline `examples/*/start-*` directories have been reduced to README tombstones only. + +## Pattern Assimilation Audit (completed) + +The following example pattern families are now covered by docs/guides: + +- Auth examples (`start-basic-auth`, `start-basic-authjs`, `start-clerk-basic`, `start-workos`, `start-supabase-basic`, `solid/start-basic-auth`, `solid/start-convex-better-auth`) -> `guide/authentication-overview`, `guide/authentication`, `guide/databases` +- Hosting/deploy examples (`start-basic-cloudflare`, `start-bun`, `solid/start-basic-cloudflare`, `solid/start-basic-netlify`, `solid/start-basic-nitro`) -> `guide/hosting` +- Streaming example (`start-streaming-data-from-server-functions`) -> `guide/streaming-data-from-server-functions` +- Styling examples (`start-tailwind-v4`, `start-material-ui`) -> `guide/tailwind-integration`, router `guide/custom-link` +- i18n Start examples (`start-i18n-paraglide`, `solid/start-i18n-paraglide`) -> router guides `guide/internationalization-i18n` and `guide/url-rewrites` +- Static/rendering examples (`start-basic-static`, `start-basic-rsc`) -> `guide/static-prerendering` and Start framework docs that cover rendering model/capabilities + +Notes: + +- Product-template style examples (eg trellaux variants) are intentionally not being moved into guides; they are being moved to Builder/CLI ownership. diff --git a/examples/react/i18n-paraglide/README.md b/examples/react/i18n-paraglide/README.md index 98b25f6d0fe..0f6b46536d8 100644 --- a/examples/react/i18n-paraglide/README.md +++ b/examples/react/i18n-paraglide/README.md @@ -183,7 +183,7 @@ And import into the Paraglide Vite plugin. ## Server-side rendering -For server-side rendering, check out the [TanStack Start guide](https://github.com/TanStack/router/tree/main/examples/react/start-i18n-paraglide). +For server-side rendering with TanStack Start, check out the [Start Middleware guide](https://tanstack.com/router/latest/docs/framework/react/start/guide/middleware). ## Prerender routes diff --git a/examples/react/start-bare/README.md b/examples/react/start-bare/README.md index 8f218785c55..9904fb54406 100644 --- a/examples/react/start-bare/README.md +++ b/examples/react/start-bare/README.md @@ -1,32 +1,16 @@ -# TanStack Start - Bare Example +# Deprecated: TanStack Start React Example (`start-bare`) -A minimal TanStack Start example demonstrating the bare essentials. +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-bare start-bare -``` +- [Start React Quick Start](https://tanstack.com/router/latest/docs/framework/react/start/quick-start) -## Getting Started +Canonical issue reproduction baseline: -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -This starts your app in development mode, rebuilding assets on file changes. - -## Build - -To build the app for production: - -```sh -pnpm build -``` +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-bare/package.json b/examples/react/start-bare/package.json deleted file mode 100644 index cf581a239cc..00000000000 --- a/examples/react/start-bare/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "tanstack-start-example-bare", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" - }, - "dependencies": { - "@tanstack/react-router": "^1.161.1", - "@tanstack/react-router-devtools": "^1.161.1", - "@tanstack/react-start": "^1.161.1", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "zod": "^3.24.2" - }, - "devDependencies": { - "@types/node": "^22.5.4", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.3.1", - "vite-tsconfig-paths": "^5.1.4" - } -} diff --git a/examples/react/start-bare/public/favicon.ico b/examples/react/start-bare/public/favicon.ico deleted file mode 100644 index 1a1751676f7..00000000000 Binary files a/examples/react/start-bare/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-bare/src/components/Counter.css b/examples/react/start-bare/src/components/Counter.css deleted file mode 100644 index 308965720fc..00000000000 --- a/examples/react/start-bare/src/components/Counter.css +++ /dev/null @@ -1,21 +0,0 @@ -.increment { - font-family: inherit; - font-size: inherit; - padding: 1em 2em; - color: #335d92; - background-color: rgba(68, 107, 158, 0.1); - border-radius: 2em; - border: 2px solid rgba(68, 107, 158, 0); - outline: none; - width: 200px; - font-variant-numeric: tabular-nums; - cursor: pointer; -} - -.increment:focus { - border: 2px solid #335d92; -} - -.increment:active { - background-color: rgba(68, 107, 158, 0.2); -} diff --git a/examples/react/start-bare/src/components/Counter.tsx b/examples/react/start-bare/src/components/Counter.tsx deleted file mode 100644 index 47347c38306..00000000000 --- a/examples/react/start-bare/src/components/Counter.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { useState } from 'react' -import './Counter.css' - -export default function Counter() { - const [count, setCount] = useState(0) - return ( - - ) -} diff --git a/examples/react/start-bare/src/routeTree.gen.ts b/examples/react/start-bare/src/routeTree.gen.ts deleted file mode 100644 index 421daf2790a..00000000000 --- a/examples/react/start-bare/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' -import { Route as IndexRouteImport } from './routes/index' - -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/about': typeof AboutRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/about': typeof AboutRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/about': typeof AboutRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/about' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/about' - id: '__root__' | '/' | '/about' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AboutRoute: typeof AboutRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AboutRoute: AboutRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' -declare module '@tanstack/react-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/examples/react/start-bare/src/router.tsx b/examples/react/start-bare/src/router.tsx deleted file mode 100644 index a464233af90..00000000000 --- a/examples/react/start-bare/src/router.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - const router = createRouter({ - routeTree, - defaultPreload: 'intent', - defaultErrorComponent: (err) =>

{err.error.stack}

, - defaultNotFoundComponent: () =>

not found

, - scrollRestoration: true, - }) - - return router -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/examples/react/start-bare/src/routes/__root.tsx b/examples/react/start-bare/src/routes/__root.tsx deleted file mode 100644 index 4b83d392e9b..00000000000 --- a/examples/react/start-bare/src/routes/__root.tsx +++ /dev/null @@ -1,46 +0,0 @@ -/// -import * as React from 'react' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import appCss from '~/styles/app.css?url' - -export const Route = createRootRoute({ - head: () => ({ - links: [{ rel: 'stylesheet', href: appCss }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - ) -} - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- Index - About -
- - {children} - - - - - ) -} diff --git a/examples/react/start-bare/src/routes/about.tsx b/examples/react/start-bare/src/routes/about.tsx deleted file mode 100644 index 95a5fe4b869..00000000000 --- a/examples/react/start-bare/src/routes/about.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import Counter from '~/components/Counter' - -export const Route = createFileRoute('/about')({ - component: RouteComponent, -}) - -function RouteComponent() { - return ( -
-

About

- -
- ) -} diff --git a/examples/react/start-bare/src/routes/index.tsx b/examples/react/start-bare/src/routes/index.tsx deleted file mode 100644 index 03832940ce2..00000000000 --- a/examples/react/start-bare/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: RouteComponent, -}) - -function RouteComponent() { - return ( -
-

Hello world!

-
- ) -} diff --git a/examples/react/start-bare/src/styles/app.css b/examples/react/start-bare/src/styles/app.css deleted file mode 100644 index a6f35642e42..00000000000 --- a/examples/react/start-bare/src/styles/app.css +++ /dev/null @@ -1,15 +0,0 @@ -body { - font-family: - Gordita, Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', - sans-serif; -} - -a { - margin-right: 1rem; -} - -main { - text-align: center; - padding: 1em; - margin: 0 auto; -} diff --git a/examples/react/start-bare/tsconfig.json b/examples/react/start-bare/tsconfig.json deleted file mode 100644 index b3a2d67dfa6..00000000000 --- a/examples/react/start-bare/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx", "public/script*.js"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "baseUrl": ".", - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/examples/react/start-bare/vite.config.ts b/examples/react/start-bare/vite.config.ts deleted file mode 100644 index f10c86e79fc..00000000000 --- a/examples/react/start-bare/vite.config.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' -import viteReact from '@vitejs/plugin-react' - -export default defineConfig({ - server: { - port: 3000, - }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], -}) diff --git a/examples/react/start-basic-auth/.env b/examples/react/start-basic-auth/.env deleted file mode 100644 index c498ab59bf1..00000000000 --- a/examples/react/start-basic-auth/.env +++ /dev/null @@ -1,7 +0,0 @@ -# Environment variables declared in this file are automatically made available to Prisma. -# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema - -# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB. -# See the documentation for all the connection string options: https://pris.ly/d/connection-strings - -DATABASE_URL="file:./dev.db" \ No newline at end of file diff --git a/examples/react/start-basic-auth/.gitignore b/examples/react/start-basic-auth/.gitignore deleted file mode 100644 index 28185491585..00000000000 --- a/examples/react/start-basic-auth/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -!.env -.DS_Store -.cache -.vercel -.output -/build/ -/api/ -/server/build -/public/build# Sentry Config File -.env.sentry-build-plugin -/test-results/ -/playwright-report/ -/blob-report/ -/playwright/.cache/ diff --git a/examples/react/start-basic-auth/.prettierignore b/examples/react/start-basic-auth/.prettierignore deleted file mode 100644 index 2be5eaa6ece..00000000000 --- a/examples/react/start-basic-auth/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/build -**/public -pnpm-lock.yaml -routeTree.gen.ts \ No newline at end of file diff --git a/examples/react/start-basic-auth/.vscode/settings.json b/examples/react/start-basic-auth/.vscode/settings.json deleted file mode 100644 index 00b5278e580..00000000000 --- a/examples/react/start-basic-auth/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "files.watcherExclude": { - "**/routeTree.gen.ts": true - }, - "search.exclude": { - "**/routeTree.gen.ts": true - }, - "files.readonlyInclude": { - "**/routeTree.gen.ts": true - } -} diff --git a/examples/react/start-basic-auth/README.md b/examples/react/start-basic-auth/README.md index 4e5ee29b400..bf2cea30c0d 100644 --- a/examples/react/start-basic-auth/README.md +++ b/examples/react/start-basic-auth/README.md @@ -1,41 +1,17 @@ -# TanStack Start - Basic Auth Example +# Deprecated: TanStack Start React Example (`start-basic-auth`) -A TanStack Start example demonstrating authentication patterns and protected routes. +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-basic-auth start-basic-auth -``` +- [Start React Quick Start](https://tanstack.com/router/latest/docs/framework/react/start/quick-start) +- [Start React Guides](https://tanstack.com/router/latest/docs/framework/react/start/guide/routing) -## Getting Started +Canonical issue reproduction baseline: -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -This starts your app in development mode, rebuilding assets on file changes. - -## Build - -To build the app for production: - -```sh -pnpm build -``` - -## Authentication Features - -This example demonstrates: - -- User authentication flow -- Protected routes -- Login/logout functionality -- Redirect after authentication +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-basic-auth/dev.db b/examples/react/start-basic-auth/dev.db deleted file mode 100644 index 5f4ab51a029..00000000000 Binary files a/examples/react/start-basic-auth/dev.db and /dev/null differ diff --git a/examples/react/start-basic-auth/package.json b/examples/react/start-basic-auth/package.json deleted file mode 100644 index 3703054b1f6..00000000000 --- a/examples/react/start-basic-auth/package.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "tanstack-start-example-basic-auth", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build", - "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "prisma-generate": "prisma generate" - }, - "dependencies": { - "@libsql/client": "^0.15.15", - "@prisma/adapter-libsql": "^7.0.0", - "@prisma/client": "^7.0.0", - "@tanstack/react-router": "^1.161.1", - "@tanstack/react-router-devtools": "^1.161.1", - "@tanstack/react-start": "^1.161.1", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0" - }, - "devDependencies": { - "@tailwindcss/vite": "^4.1.18", - "@types/node": "^22.5.4", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "dotenv": "^17.2.3", - "prisma": "^7.0.0", - "tailwindcss": "^4.1.18", - "typescript": "^5.7.2", - "vite": "^7.3.1", - "vite-tsconfig-paths": "^5.1.4" - } -} diff --git a/examples/react/start-basic-auth/prisma.config.ts b/examples/react/start-basic-auth/prisma.config.ts deleted file mode 100644 index 9e548f8b1ae..00000000000 --- a/examples/react/start-basic-auth/prisma.config.ts +++ /dev/null @@ -1,12 +0,0 @@ -import 'dotenv/config' -import { defineConfig, env } from 'prisma/config' - -export default defineConfig({ - schema: './prisma/schema.prisma', - migrations: { - path: './prisma/migrations', - }, - datasource: { - url: env('DATABASE_URL'), - }, -}) diff --git a/examples/react/start-basic-auth/prisma/migrations/20240811183753_init/migration.sql b/examples/react/start-basic-auth/prisma/migrations/20240811183753_init/migration.sql deleted file mode 100644 index 4512a8f7823..00000000000 --- a/examples/react/start-basic-auth/prisma/migrations/20240811183753_init/migration.sql +++ /dev/null @@ -1,8 +0,0 @@ --- CreateTable -CREATE TABLE "User" ( - "email" TEXT NOT NULL PRIMARY KEY, - "password" TEXT NOT NULL -); - --- CreateIndex -CREATE UNIQUE INDEX "User_email_key" ON "User"("email"); diff --git a/examples/react/start-basic-auth/prisma/migrations/migration_lock.toml b/examples/react/start-basic-auth/prisma/migrations/migration_lock.toml deleted file mode 100644 index e5e5c4705ab..00000000000 --- a/examples/react/start-basic-auth/prisma/migrations/migration_lock.toml +++ /dev/null @@ -1,3 +0,0 @@ -# Please do not edit this file manually -# It should be added in your version-control system (i.e. Git) -provider = "sqlite" \ No newline at end of file diff --git a/examples/react/start-basic-auth/prisma/schema.prisma b/examples/react/start-basic-auth/prisma/schema.prisma deleted file mode 100644 index a4ff8688915..00000000000 --- a/examples/react/start-basic-auth/prisma/schema.prisma +++ /dev/null @@ -1,16 +0,0 @@ -// This is your Prisma schema file, -// learn more about it in the docs: https://pris.ly/d/prisma-schema - -generator client { - provider = "prisma-client" - output = "../src/prisma-generated" -} - -datasource db { - provider = "sqlite" -} - -model User { - email String @id @unique - password String -} \ No newline at end of file diff --git a/examples/react/start-basic-auth/public/android-chrome-192x192.png b/examples/react/start-basic-auth/public/android-chrome-192x192.png deleted file mode 100644 index 09c8324f8c6..00000000000 Binary files a/examples/react/start-basic-auth/public/android-chrome-192x192.png and /dev/null differ diff --git a/examples/react/start-basic-auth/public/android-chrome-512x512.png b/examples/react/start-basic-auth/public/android-chrome-512x512.png deleted file mode 100644 index 11d626ea3d0..00000000000 Binary files a/examples/react/start-basic-auth/public/android-chrome-512x512.png and /dev/null differ diff --git a/examples/react/start-basic-auth/public/apple-touch-icon.png b/examples/react/start-basic-auth/public/apple-touch-icon.png deleted file mode 100644 index 5a9423cc02c..00000000000 Binary files a/examples/react/start-basic-auth/public/apple-touch-icon.png and /dev/null differ diff --git a/examples/react/start-basic-auth/public/favicon-16x16.png b/examples/react/start-basic-auth/public/favicon-16x16.png deleted file mode 100644 index e3389b00443..00000000000 Binary files a/examples/react/start-basic-auth/public/favicon-16x16.png and /dev/null differ diff --git a/examples/react/start-basic-auth/public/favicon-32x32.png b/examples/react/start-basic-auth/public/favicon-32x32.png deleted file mode 100644 index 900c77d444c..00000000000 Binary files a/examples/react/start-basic-auth/public/favicon-32x32.png and /dev/null differ diff --git a/examples/react/start-basic-auth/public/favicon.ico b/examples/react/start-basic-auth/public/favicon.ico deleted file mode 100644 index 1a1751676f7..00000000000 Binary files a/examples/react/start-basic-auth/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-basic-auth/public/favicon.png b/examples/react/start-basic-auth/public/favicon.png deleted file mode 100644 index 1e77bc06091..00000000000 Binary files a/examples/react/start-basic-auth/public/favicon.png and /dev/null differ diff --git a/examples/react/start-basic-auth/public/site.webmanifest b/examples/react/start-basic-auth/public/site.webmanifest deleted file mode 100644 index fa99de77db6..00000000000 --- a/examples/react/start-basic-auth/public/site.webmanifest +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "", - "short_name": "", - "icons": [ - { - "src": "/android-chrome-192x192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "/android-chrome-512x512.png", - "sizes": "512x512", - "type": "image/png" - } - ], - "theme_color": "#ffffff", - "background_color": "#ffffff", - "display": "standalone" -} diff --git a/examples/react/start-basic-auth/src/components/Auth.tsx b/examples/react/start-basic-auth/src/components/Auth.tsx deleted file mode 100644 index 39a4997346c..00000000000 --- a/examples/react/start-basic-auth/src/components/Auth.tsx +++ /dev/null @@ -1,57 +0,0 @@ -export function Auth({ - actionText, - onSubmit, - status, - afterSubmit, -}: { - actionText: string - onSubmit: (e: React.FormEvent) => void - status: 'pending' | 'idle' | 'success' | 'error' - afterSubmit?: React.ReactNode -}) { - return ( -
-
-

{actionText}

-
{ - e.preventDefault() - onSubmit(e) - }} - className="space-y-4" - > -
- - -
-
- - -
- - {afterSubmit ? afterSubmit : null} -
-
-
- ) -} diff --git a/examples/react/start-basic-auth/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-auth/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index ef2daa1ea1d..00000000000 --- a/examples/react/start-basic-auth/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { - ErrorComponent, - Link, - rootRouteId, - useMatch, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error(error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/examples/react/start-basic-auth/src/components/Login.tsx b/examples/react/start-basic-auth/src/components/Login.tsx deleted file mode 100644 index b6b6da0c37f..00000000000 --- a/examples/react/start-basic-auth/src/components/Login.tsx +++ /dev/null @@ -1,71 +0,0 @@ -import { useRouter } from '@tanstack/react-router' -import { useServerFn } from '@tanstack/react-start' -import { useMutation } from '../hooks/useMutation' -import { loginFn } from '../routes/_authed' -import { Auth } from './Auth' -import { signupFn } from '~/routes/signup' - -export function Login() { - const router = useRouter() - - const loginMutation = useMutation({ - fn: loginFn, - onSuccess: async (ctx) => { - if (!ctx.data?.error) { - await router.invalidate() - router.navigate({ to: '/' }) - return - } - }, - }) - - const signupMutation = useMutation({ - fn: useServerFn(signupFn), - }) - - return ( - { - const formData = new FormData(e.target as HTMLFormElement) - - loginMutation.mutate({ - data: { - email: formData.get('email') as string, - password: formData.get('password') as string, - }, - }) - }} - afterSubmit={ - loginMutation.data ? ( - <> -
{loginMutation.data.message}
- {loginMutation.data.userNotFound ? ( -
- -
- ) : null} - - ) : null - } - /> - ) -} diff --git a/examples/react/start-basic-auth/src/components/NotFound.tsx b/examples/react/start-basic-auth/src/components/NotFound.tsx deleted file mode 100644 index fd4e75befe3..00000000000 --- a/examples/react/start-basic-auth/src/components/NotFound.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: any }) { - return ( -
-
- {children ||

The page you are looking for does not exist.

} -
-

- - - Start Over - -

-
- ) -} diff --git a/examples/react/start-basic-auth/src/hooks/useMutation.ts b/examples/react/start-basic-auth/src/hooks/useMutation.ts deleted file mode 100644 index 1ff7a4653bd..00000000000 --- a/examples/react/start-basic-auth/src/hooks/useMutation.ts +++ /dev/null @@ -1,44 +0,0 @@ -import * as React from 'react' - -export function useMutation(opts: { - fn: (variables: TVariables) => Promise - onSuccess?: (ctx: { data: TData }) => void | Promise -}) { - const [submittedAt, setSubmittedAt] = React.useState() - const [variables, setVariables] = React.useState() - const [error, setError] = React.useState() - const [data, setData] = React.useState() - const [status, setStatus] = React.useState< - 'idle' | 'pending' | 'success' | 'error' - >('idle') - - const mutate = React.useCallback( - async (variables: TVariables): Promise => { - setStatus('pending') - setSubmittedAt(Date.now()) - setVariables(variables) - // - try { - const data = await opts.fn(variables) - await opts.onSuccess?.({ data }) - setStatus('success') - setError(undefined) - setData(data) - return data - } catch (err: any) { - setStatus('error') - setError(err) - } - }, - [opts.fn], - ) - - return { - status, - variables, - submittedAt, - mutate, - error, - data, - } -} diff --git a/examples/react/start-basic-auth/src/prisma-generated/browser.ts b/examples/react/start-basic-auth/src/prisma-generated/browser.ts deleted file mode 100644 index 7ca76c93683..00000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/browser.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * This file should be your main import to use Prisma-related types and utilities in a browser. - * Use it to get access to models, enums, and input types. - * - * This file does not contain a `PrismaClient` class, nor several other helpers that are intended as server-side only. - * See `client.ts` for the standard, server-side entry point. - * - * 🟢 You can import this file directly. - */ - -import * as Prisma from './internal/prismaNamespaceBrowser' -export { Prisma } -export * as $Enums from './enums' -export * from './enums' -/** - * Model User - * - */ -export type User = Prisma.UserModel diff --git a/examples/react/start-basic-auth/src/prisma-generated/client.ts b/examples/react/start-basic-auth/src/prisma-generated/client.ts deleted file mode 100644 index 2be7866ae30..00000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/client.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * This file should be your main import to use Prisma. Through it you get access to all the models, enums, and input types. - * If you're looking for something you can import in the client-side of your application, please refer to the `browser.ts` file instead. - * - * 🟢 You can import this file directly. - */ - -import * as process from 'node:process' -import * as path from 'node:path' -import { fileURLToPath } from 'node:url' -globalThis['__dirname'] = path.dirname(fileURLToPath(import.meta.url)) - -import * as runtime from '@prisma/client/runtime/client' -import * as $Enums from './enums' -import * as $Class from './internal/class' -import * as Prisma from './internal/prismaNamespace' - -export * as $Enums from './enums' -export * from './enums' -/** - * ## Prisma Client - * - * Type-safe database client for TypeScript - * @example - * ``` - * const prisma = new PrismaClient() - * // Fetch zero or more Users - * const users = await prisma.user.findMany() - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client). - */ -export const PrismaClient = $Class.getPrismaClientClass() -export type PrismaClient< - LogOpts extends Prisma.LogLevel = never, - OmitOpts extends Prisma.PrismaClientOptions['omit'] = - Prisma.PrismaClientOptions['omit'], - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = $Class.PrismaClient -export { Prisma } - -/** - * Model User - * - */ -export type User = Prisma.UserModel diff --git a/examples/react/start-basic-auth/src/prisma-generated/commonInputTypes.ts b/examples/react/start-basic-auth/src/prisma-generated/commonInputTypes.ts deleted file mode 100644 index 72c68f142ed..00000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/commonInputTypes.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * This file exports various common sort, input & filter types that are not directly linked to a particular model. - * - * 🟢 You can import this file directly. - */ - -import type * as runtime from '@prisma/client/runtime/client' -import * as $Enums from './enums' -import type * as Prisma from './internal/prismaNamespace' - -export type StringFilter<$PrismaModel = never> = { - equals?: string | Prisma.StringFieldRefInput<$PrismaModel> - in?: string[] - notIn?: string[] - lt?: string | Prisma.StringFieldRefInput<$PrismaModel> - lte?: string | Prisma.StringFieldRefInput<$PrismaModel> - gt?: string | Prisma.StringFieldRefInput<$PrismaModel> - gte?: string | Prisma.StringFieldRefInput<$PrismaModel> - contains?: string | Prisma.StringFieldRefInput<$PrismaModel> - startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - not?: Prisma.NestedStringFilter<$PrismaModel> | string -} - -export type StringWithAggregatesFilter<$PrismaModel = never> = { - equals?: string | Prisma.StringFieldRefInput<$PrismaModel> - in?: string[] - notIn?: string[] - lt?: string | Prisma.StringFieldRefInput<$PrismaModel> - lte?: string | Prisma.StringFieldRefInput<$PrismaModel> - gt?: string | Prisma.StringFieldRefInput<$PrismaModel> - gte?: string | Prisma.StringFieldRefInput<$PrismaModel> - contains?: string | Prisma.StringFieldRefInput<$PrismaModel> - startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - not?: Prisma.NestedStringWithAggregatesFilter<$PrismaModel> | string - _count?: Prisma.NestedIntFilter<$PrismaModel> - _min?: Prisma.NestedStringFilter<$PrismaModel> - _max?: Prisma.NestedStringFilter<$PrismaModel> -} - -export type NestedStringFilter<$PrismaModel = never> = { - equals?: string | Prisma.StringFieldRefInput<$PrismaModel> - in?: string[] - notIn?: string[] - lt?: string | Prisma.StringFieldRefInput<$PrismaModel> - lte?: string | Prisma.StringFieldRefInput<$PrismaModel> - gt?: string | Prisma.StringFieldRefInput<$PrismaModel> - gte?: string | Prisma.StringFieldRefInput<$PrismaModel> - contains?: string | Prisma.StringFieldRefInput<$PrismaModel> - startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - not?: Prisma.NestedStringFilter<$PrismaModel> | string -} - -export type NestedStringWithAggregatesFilter<$PrismaModel = never> = { - equals?: string | Prisma.StringFieldRefInput<$PrismaModel> - in?: string[] - notIn?: string[] - lt?: string | Prisma.StringFieldRefInput<$PrismaModel> - lte?: string | Prisma.StringFieldRefInput<$PrismaModel> - gt?: string | Prisma.StringFieldRefInput<$PrismaModel> - gte?: string | Prisma.StringFieldRefInput<$PrismaModel> - contains?: string | Prisma.StringFieldRefInput<$PrismaModel> - startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - not?: Prisma.NestedStringWithAggregatesFilter<$PrismaModel> | string - _count?: Prisma.NestedIntFilter<$PrismaModel> - _min?: Prisma.NestedStringFilter<$PrismaModel> - _max?: Prisma.NestedStringFilter<$PrismaModel> -} - -export type NestedIntFilter<$PrismaModel = never> = { - equals?: number | Prisma.IntFieldRefInput<$PrismaModel> - in?: number[] - notIn?: number[] - lt?: number | Prisma.IntFieldRefInput<$PrismaModel> - lte?: number | Prisma.IntFieldRefInput<$PrismaModel> - gt?: number | Prisma.IntFieldRefInput<$PrismaModel> - gte?: number | Prisma.IntFieldRefInput<$PrismaModel> - not?: Prisma.NestedIntFilter<$PrismaModel> | number -} diff --git a/examples/react/start-basic-auth/src/prisma-generated/enums.ts b/examples/react/start-basic-auth/src/prisma-generated/enums.ts deleted file mode 100644 index 84979fb8d26..00000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/enums.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * This file exports all enum related types from the schema. - * - * 🟢 You can import this file directly. - */ - -// This file is empty because there are no enums in the schema. -export {} diff --git a/examples/react/start-basic-auth/src/prisma-generated/internal/class.ts b/examples/react/start-basic-auth/src/prisma-generated/internal/class.ts deleted file mode 100644 index 594896a020a..00000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/internal/class.ts +++ /dev/null @@ -1,241 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * WARNING: This is an internal file that is subject to change! - * - * 🛑 Under no circumstances should you import this file directly! 🛑 - * - * Please import the `PrismaClient` class from the `client.ts` file instead. - */ - -import * as runtime from '@prisma/client/runtime/client' -import type * as Prisma from './prismaNamespace' - -const config: runtime.GetPrismaClientConfig = { - previewFeatures: [], - clientVersion: '7.0.0', - engineVersion: '0c19ccc313cf9911a90d99d2ac2eb0280c76c513', - activeProvider: 'sqlite', - inlineSchema: - '// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator client {\n provider = "prisma-client"\n output = "../src/prisma-generated"\n}\n\ndatasource db {\n provider = "sqlite"\n}\n\nmodel User {\n email String @id @unique\n password String\n}\n', - runtimeDataModel: { - models: {}, - enums: {}, - types: {}, - }, -} - -config.runtimeDataModel = JSON.parse( - '{"models":{"User":{"fields":[{"name":"email","kind":"scalar","type":"String"},{"name":"password","kind":"scalar","type":"String"}],"dbName":null}},"enums":{},"types":{}}', -) - -async function decodeBase64AsWasm( - wasmBase64: string, -): Promise { - const { Buffer } = await import('node:buffer') - const wasmArray = Buffer.from(wasmBase64, 'base64') - return new WebAssembly.Module(wasmArray) -} - -config.compilerWasm = { - getRuntime: async () => - await import('@prisma/client/runtime/query_compiler_bg.sqlite.mjs'), - - getQueryCompilerWasmModule: async () => { - const { wasm } = - await import('@prisma/client/runtime/query_compiler_bg.sqlite.wasm-base64.mjs') - return await decodeBase64AsWasm(wasm) - }, -} - -export type LogOptions = - 'log' extends keyof ClientOptions - ? ClientOptions['log'] extends Array - ? Prisma.GetEvents - : never - : never - -export interface PrismaClientConstructor { - /** - * ## Prisma Client - * - * Type-safe database client for TypeScript - * @example - * ``` - * const prisma = new PrismaClient() - * // Fetch zero or more Users - * const users = await prisma.user.findMany() - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client). - */ - - new < - Options extends Prisma.PrismaClientOptions = Prisma.PrismaClientOptions, - LogOpts extends LogOptions = LogOptions, - OmitOpts extends Prisma.PrismaClientOptions['omit'] = Options extends { - omit: infer U - } - ? U - : Prisma.PrismaClientOptions['omit'], - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, - >( - options: Prisma.Subset, - ): PrismaClient -} - -/** - * ## Prisma Client - * - * Type-safe database client for TypeScript - * @example - * ``` - * const prisma = new PrismaClient() - * // Fetch zero or more Users - * const users = await prisma.user.findMany() - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client). - */ - -export interface PrismaClient< - in LogOpts extends Prisma.LogLevel = never, - in out OmitOpts extends Prisma.PrismaClientOptions['omit'] = undefined, - in out ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> { - [K: symbol]: { types: Prisma.TypeMap['other'] } - - $on( - eventType: V, - callback: ( - event: V extends 'query' ? Prisma.QueryEvent : Prisma.LogEvent, - ) => void, - ): PrismaClient - - /** - * Connect with the database - */ - $connect(): runtime.Types.Utils.JsPromise - - /** - * Disconnect from the database - */ - $disconnect(): runtime.Types.Utils.JsPromise - - /** - * Executes a prepared raw query and returns the number of affected rows. - * @example - * ``` - * const result = await prisma.$executeRaw`UPDATE User SET cool = ${true} WHERE email = ${'user@email.com'};` - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/raw-database-access). - */ - $executeRaw( - query: TemplateStringsArray | Prisma.Sql, - ...values: any[] - ): Prisma.PrismaPromise - - /** - * Executes a raw query and returns the number of affected rows. - * Susceptible to SQL injections, see documentation. - * @example - * ``` - * const result = await prisma.$executeRawUnsafe('UPDATE User SET cool = $1 WHERE email = $2 ;', true, 'user@email.com') - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/raw-database-access). - */ - $executeRawUnsafe( - query: string, - ...values: any[] - ): Prisma.PrismaPromise - - /** - * Performs a prepared raw query and returns the `SELECT` data. - * @example - * ``` - * const result = await prisma.$queryRaw`SELECT * FROM User WHERE id = ${1} OR email = ${'user@email.com'};` - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/raw-database-access). - */ - $queryRaw( - query: TemplateStringsArray | Prisma.Sql, - ...values: any[] - ): Prisma.PrismaPromise - - /** - * Performs a raw query and returns the `SELECT` data. - * Susceptible to SQL injections, see documentation. - * @example - * ``` - * const result = await prisma.$queryRawUnsafe('SELECT * FROM User WHERE id = $1 OR email = $2;', 1, 'user@email.com') - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/raw-database-access). - */ - $queryRawUnsafe( - query: string, - ...values: any[] - ): Prisma.PrismaPromise - - /** - * Allows the running of a sequence of read/write operations that are guaranteed to either succeed or fail as a whole. - * @example - * ``` - * const [george, bob, alice] = await prisma.$transaction([ - * prisma.user.create({ data: { name: 'George' } }), - * prisma.user.create({ data: { name: 'Bob' } }), - * prisma.user.create({ data: { name: 'Alice' } }), - * ]) - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/concepts/components/prisma-client/transactions). - */ - $transaction

[]>( - arg: [...P], - options?: { isolationLevel?: Prisma.TransactionIsolationLevel }, - ): runtime.Types.Utils.JsPromise> - - $transaction( - fn: ( - prisma: Omit, - ) => runtime.Types.Utils.JsPromise, - options?: { - maxWait?: number - timeout?: number - isolationLevel?: Prisma.TransactionIsolationLevel - }, - ): runtime.Types.Utils.JsPromise - - $extends: runtime.Types.Extensions.ExtendsHook< - 'extends', - Prisma.TypeMapCb, - ExtArgs, - runtime.Types.Utils.Call< - Prisma.TypeMapCb, - { - extArgs: ExtArgs - } - > - > - - /** - * `prisma.user`: Exposes CRUD operations for the **User** model. - * Example usage: - * ```ts - * // Fetch zero or more Users - * const users = await prisma.user.findMany() - * ``` - */ - get user(): Prisma.UserDelegate -} - -export function getPrismaClientClass(): PrismaClientConstructor { - return runtime.getPrismaClient(config) as unknown as PrismaClientConstructor -} diff --git a/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespace.ts b/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespace.ts deleted file mode 100644 index f420c553297..00000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespace.ts +++ /dev/null @@ -1,738 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * WARNING: This is an internal file that is subject to change! - * - * 🛑 Under no circumstances should you import this file directly! 🛑 - * - * All exports from this file are wrapped under a `Prisma` namespace object in the client.ts file. - * While this enables partial backward compatibility, it is not part of the stable public API. - * - * If you are looking for your Models, Enums, and Input Types, please import them from the respective - * model files in the `model` directory! - */ - -import * as runtime from '@prisma/client/runtime/client' -import type * as Prisma from '../models' -import { type PrismaClient } from './class' - -export type * from '../models' - -export type DMMF = typeof runtime.DMMF - -export type PrismaPromise = runtime.Types.Public.PrismaPromise - -/** - * Prisma Errors - */ - -export const PrismaClientKnownRequestError = - runtime.PrismaClientKnownRequestError -export type PrismaClientKnownRequestError = - runtime.PrismaClientKnownRequestError - -export const PrismaClientUnknownRequestError = - runtime.PrismaClientUnknownRequestError -export type PrismaClientUnknownRequestError = - runtime.PrismaClientUnknownRequestError - -export const PrismaClientRustPanicError = runtime.PrismaClientRustPanicError -export type PrismaClientRustPanicError = runtime.PrismaClientRustPanicError - -export const PrismaClientInitializationError = - runtime.PrismaClientInitializationError -export type PrismaClientInitializationError = - runtime.PrismaClientInitializationError - -export const PrismaClientValidationError = runtime.PrismaClientValidationError -export type PrismaClientValidationError = runtime.PrismaClientValidationError - -/** - * Re-export of sql-template-tag - */ -export const sql = runtime.sqltag -export const empty = runtime.empty -export const join = runtime.join -export const raw = runtime.raw -export const Sql = runtime.Sql -export type Sql = runtime.Sql - -/** - * Decimal.js - */ -export const Decimal = runtime.Decimal -export type Decimal = runtime.Decimal - -export type DecimalJsLike = runtime.DecimalJsLike - -/** - * Extensions - */ -export type Extension = runtime.Types.Extensions.UserArgs -export const getExtensionContext = runtime.Extensions.getExtensionContext -export type Args = runtime.Types.Public.Args< - T, - F -> -export type Payload< - T, - F extends runtime.Operation = never, -> = runtime.Types.Public.Payload -export type Result< - T, - A, - F extends runtime.Operation, -> = runtime.Types.Public.Result -export type Exact = runtime.Types.Public.Exact - -export type PrismaVersion = { - client: string - engine: string -} - -/** - * Prisma Client JS version: 7.0.0 - * Query Engine version: 0c19ccc313cf9911a90d99d2ac2eb0280c76c513 - */ -export const prismaVersion: PrismaVersion = { - client: '7.0.0', - engine: '0c19ccc313cf9911a90d99d2ac2eb0280c76c513', -} - -/** - * Utility Types - */ - -export type Bytes = runtime.Bytes -export type JsonObject = runtime.JsonObject -export type JsonArray = runtime.JsonArray -export type JsonValue = runtime.JsonValue -export type InputJsonObject = runtime.InputJsonObject -export type InputJsonArray = runtime.InputJsonArray -export type InputJsonValue = runtime.InputJsonValue - -export const NullTypes = { - DbNull: runtime.NullTypes.DbNull as new ( - secret: never, - ) => typeof runtime.DbNull, - JsonNull: runtime.NullTypes.JsonNull as new ( - secret: never, - ) => typeof runtime.JsonNull, - AnyNull: runtime.NullTypes.AnyNull as new ( - secret: never, - ) => typeof runtime.AnyNull, -} -/** - * Helper for filtering JSON entries that have `null` on the database (empty on the db) - * - * @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field - */ -export const DbNull = runtime.DbNull - -/** - * Helper for filtering JSON entries that have JSON `null` values (not empty on the db) - * - * @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field - */ -export const JsonNull = runtime.JsonNull - -/** - * Helper for filtering JSON entries that are `Prisma.DbNull` or `Prisma.JsonNull` - * - * @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field - */ -export const AnyNull = runtime.AnyNull - -type SelectAndInclude = { - select: any - include: any -} - -type SelectAndOmit = { - select: any - omit: any -} - -/** - * From T, pick a set of properties whose keys are in the union K - */ -type Prisma__Pick = { - [P in K]: T[P] -} - -export type Enumerable = T | Array - -/** - * Subset - * @desc From `T` pick properties that exist in `U`. Simple version of Intersection - */ -export type Subset = { - [key in keyof T]: key extends keyof U ? T[key] : never -} - -/** - * SelectSubset - * @desc From `T` pick properties that exist in `U`. Simple version of Intersection. - * Additionally, it validates, if both select and include are present. If the case, it errors. - */ -export type SelectSubset = { - [key in keyof T]: key extends keyof U ? T[key] : never -} & (T extends SelectAndInclude - ? 'Please either choose `select` or `include`.' - : T extends SelectAndOmit - ? 'Please either choose `select` or `omit`.' - : {}) - -/** - * Subset + Intersection - * @desc From `T` pick properties that exist in `U` and intersect `K` - */ -export type SubsetIntersection = { - [key in keyof T]: key extends keyof U ? T[key] : never -} & K - -type Without = { [P in Exclude]?: never } - -/** - * XOR is needed to have a real mutually exclusive union type - * https://stackoverflow.com/questions/42123407/does-typescript-support-mutually-exclusive-types - */ -export type XOR = T extends object - ? U extends object - ? (Without & U) | (Without & T) - : U - : T - -/** - * Is T a Record? - */ -type IsObject = - T extends Array - ? False - : T extends Date - ? False - : T extends Uint8Array - ? False - : T extends BigInt - ? False - : T extends object - ? True - : False - -/** - * If it's T[], return T - */ -export type UnEnumerate = T extends Array ? U : T - -/** - * From ts-toolbelt - */ - -type __Either = Omit & - { - // Merge all but K - [P in K]: Prisma__Pick // With K possibilities - }[K] - -type EitherStrict = Strict<__Either> - -type EitherLoose = ComputeRaw<__Either> - -type _Either = { - 1: EitherStrict - 0: EitherLoose -}[strict] - -export type Either< - O extends object, - K extends Key, - strict extends Boolean = 1, -> = O extends unknown ? _Either : never - -export type Union = any - -export type PatchUndefined = { - [K in keyof O]: O[K] extends undefined ? At : O[K] -} & {} - -/** Helper Types for "Merge" **/ -export type IntersectOf = ( - U extends unknown ? (k: U) => void : never -) extends (k: infer I) => void - ? I - : never - -export type Overwrite = { - [K in keyof O]: K extends keyof O1 ? O1[K] : O[K] -} & {} - -type _Merge = IntersectOf< - Overwrite< - U, - { - [K in keyof U]-?: At - } - > -> - -type Key = string | number | symbol -type AtStrict = O[K & keyof O] -type AtLoose = O extends unknown - ? AtStrict - : never -export type At = { - 1: AtStrict - 0: AtLoose -}[strict] - -export type ComputeRaw = A extends Function - ? A - : { - [K in keyof A]: A[K] - } & {} - -export type OptionalFlat = { - [K in keyof O]?: O[K] -} & {} - -type _Record = { - [P in K]: T -} - -// cause typescript not to expand types and preserve names -type NoExpand = T extends unknown ? T : never - -// this type assumes the passed object is entirely optional -export type AtLeast = NoExpand< - O extends unknown - ? - | (K extends keyof O ? { [P in K]: O[P] } & O : O) - | ({ [P in keyof O as P extends K ? P : never]-?: O[P] } & O) - : never -> - -type _Strict = U extends unknown - ? U & OptionalFlat<_Record, keyof U>, never>> - : never - -export type Strict = ComputeRaw<_Strict> -/** End Helper Types for "Merge" **/ - -export type Merge = ComputeRaw<_Merge>> - -export type Boolean = True | False - -export type True = 1 - -export type False = 0 - -export type Not = { - 0: 1 - 1: 0 -}[B] - -export type Extends = [A1] extends [never] - ? 0 // anything `never` is false - : A1 extends A2 - ? 1 - : 0 - -export type Has = Not< - Extends, U1> -> - -export type Or = { - 0: { - 0: 0 - 1: 1 - } - 1: { - 0: 1 - 1: 1 - } -}[B1][B2] - -export type Keys = U extends unknown ? keyof U : never - -export type GetScalarType = O extends object - ? { - [P in keyof T]: P extends keyof O ? O[P] : never - } - : never - -type FieldPaths> = - IsObject extends True ? U : T - -export type GetHavingFields = { - [K in keyof T]: Or< - Or, Extends<'AND', K>>, - Extends<'NOT', K> - > extends True - ? // infer is only needed to not hit TS limit - // based on the brilliant idea of Pierre-Antoine Mills - // https://github.com/microsoft/TypeScript/issues/30188#issuecomment-478938437 - T[K] extends infer TK - ? GetHavingFields< - UnEnumerate extends object ? Merge> : never - > - : never - : {} extends FieldPaths - ? never - : K -}[keyof T] - -/** - * Convert tuple to union - */ -type _TupleToUnion = T extends (infer E)[] ? E : never -type TupleToUnion = _TupleToUnion -export type MaybeTupleToUnion = T extends any[] ? TupleToUnion : T - -/** - * Like `Pick`, but additionally can also accept an array of keys - */ -export type PickEnumerable< - T, - K extends Enumerable | keyof T, -> = Prisma__Pick> - -/** - * Exclude all keys with underscores - */ -export type ExcludeUnderscoreKeys = T extends `_${string}` - ? never - : T - -export type FieldRef = runtime.FieldRef - -type FieldRefInputType = Model extends never - ? never - : FieldRef - -export const ModelName = { - User: 'User', -} as const - -export type ModelName = (typeof ModelName)[keyof typeof ModelName] - -export interface TypeMapCb extends runtime.Types.Utils - .Fn< - { extArgs: runtime.Types.Extensions.InternalArgs }, - runtime.Types.Utils.Record -> { - returns: TypeMap -} - -export type TypeMap< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, - GlobalOmitOptions = {}, -> = { - globalOmitOptions: { - omit: GlobalOmitOptions - } - meta: { - modelProps: 'user' - txIsolationLevel: TransactionIsolationLevel - } - model: { - User: { - payload: Prisma.$UserPayload - fields: Prisma.UserFieldRefs - operations: { - findUnique: { - args: Prisma.UserFindUniqueArgs - result: runtime.Types.Utils.PayloadToResult | null - } - findUniqueOrThrow: { - args: Prisma.UserFindUniqueOrThrowArgs - result: runtime.Types.Utils.PayloadToResult - } - findFirst: { - args: Prisma.UserFindFirstArgs - result: runtime.Types.Utils.PayloadToResult | null - } - findFirstOrThrow: { - args: Prisma.UserFindFirstOrThrowArgs - result: runtime.Types.Utils.PayloadToResult - } - findMany: { - args: Prisma.UserFindManyArgs - result: runtime.Types.Utils.PayloadToResult[] - } - create: { - args: Prisma.UserCreateArgs - result: runtime.Types.Utils.PayloadToResult - } - createMany: { - args: Prisma.UserCreateManyArgs - result: BatchPayload - } - createManyAndReturn: { - args: Prisma.UserCreateManyAndReturnArgs - result: runtime.Types.Utils.PayloadToResult[] - } - delete: { - args: Prisma.UserDeleteArgs - result: runtime.Types.Utils.PayloadToResult - } - update: { - args: Prisma.UserUpdateArgs - result: runtime.Types.Utils.PayloadToResult - } - deleteMany: { - args: Prisma.UserDeleteManyArgs - result: BatchPayload - } - updateMany: { - args: Prisma.UserUpdateManyArgs - result: BatchPayload - } - updateManyAndReturn: { - args: Prisma.UserUpdateManyAndReturnArgs - result: runtime.Types.Utils.PayloadToResult[] - } - upsert: { - args: Prisma.UserUpsertArgs - result: runtime.Types.Utils.PayloadToResult - } - aggregate: { - args: Prisma.UserAggregateArgs - result: runtime.Types.Utils.Optional - } - groupBy: { - args: Prisma.UserGroupByArgs - result: runtime.Types.Utils.Optional[] - } - count: { - args: Prisma.UserCountArgs - result: - | runtime.Types.Utils.Optional - | number - } - } - } - } -} & { - other: { - payload: any - operations: { - $executeRaw: { - args: [query: TemplateStringsArray | Sql, ...values: any[]] - result: any - } - $executeRawUnsafe: { - args: [query: string, ...values: any[]] - result: any - } - $queryRaw: { - args: [query: TemplateStringsArray | Sql, ...values: any[]] - result: any - } - $queryRawUnsafe: { - args: [query: string, ...values: any[]] - result: any - } - } - } -} - -/** - * Enums - */ - -export const TransactionIsolationLevel = runtime.makeStrictEnum({ - Serializable: 'Serializable', -} as const) - -export type TransactionIsolationLevel = - (typeof TransactionIsolationLevel)[keyof typeof TransactionIsolationLevel] - -export const UserScalarFieldEnum = { - email: 'email', - password: 'password', -} as const - -export type UserScalarFieldEnum = - (typeof UserScalarFieldEnum)[keyof typeof UserScalarFieldEnum] - -export const SortOrder = { - asc: 'asc', - desc: 'desc', -} as const - -export type SortOrder = (typeof SortOrder)[keyof typeof SortOrder] - -/** - * Field references - */ - -/** - * Reference to a field of type 'String' - */ -export type StringFieldRefInput<$PrismaModel> = FieldRefInputType< - $PrismaModel, - 'String' -> - -/** - * Reference to a field of type 'Int' - */ -export type IntFieldRefInput<$PrismaModel> = FieldRefInputType< - $PrismaModel, - 'Int' -> - -/** - * Batch Payload for updateMany & deleteMany & createMany - */ -export type BatchPayload = { - count: number -} - -export const defineExtension = runtime.Extensions - .defineExtension as unknown as runtime.Types.Extensions.ExtendsHook< - 'define', - TypeMapCb, - runtime.Types.Extensions.DefaultArgs -> -export type DefaultPrismaClient = PrismaClient -export type ErrorFormat = 'pretty' | 'colorless' | 'minimal' -export type PrismaClientOptions = ( - | { - /** - * Instance of a Driver Adapter, e.g., like one provided by `@prisma/adapter-pg`. - */ - adapter: runtime.SqlDriverAdapterFactory - accelerateUrl?: never - } - | { - /** - * Prisma Accelerate URL allowing the client to connect through Accelerate instead of a direct database. - */ - accelerateUrl: string - adapter?: never - } -) & { - /** - * @default "colorless" - */ - errorFormat?: ErrorFormat - /** - * @example - * ``` - * // Shorthand for `emit: 'stdout'` - * log: ['query', 'info', 'warn', 'error'] - * - * // Emit as events only - * log: [ - * { emit: 'event', level: 'query' }, - * { emit: 'event', level: 'info' }, - * { emit: 'event', level: 'warn' } - * { emit: 'event', level: 'error' } - * ] - * - * / Emit as events and log to stdout - * og: [ - * { emit: 'stdout', level: 'query' }, - * { emit: 'stdout', level: 'info' }, - * { emit: 'stdout', level: 'warn' } - * { emit: 'stdout', level: 'error' } - * - * ``` - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/logging#the-log-option). - */ - log?: (LogLevel | LogDefinition)[] - /** - * The default values for transactionOptions - * maxWait ?= 2000 - * timeout ?= 5000 - */ - transactionOptions?: { - maxWait?: number - timeout?: number - isolationLevel?: TransactionIsolationLevel - } - /** - * Global configuration for omitting model fields by default. - * - * @example - * ``` - * const prisma = new PrismaClient({ - * omit: { - * user: { - * password: true - * } - * } - * }) - * ``` - */ - omit?: GlobalOmitConfig -} -export type GlobalOmitConfig = { - user?: Prisma.UserOmit -} - -/* Types for Logging */ -export type LogLevel = 'info' | 'query' | 'warn' | 'error' -export type LogDefinition = { - level: LogLevel - emit: 'stdout' | 'event' -} - -export type CheckIsLogLevel = T extends LogLevel ? T : never - -export type GetLogType = CheckIsLogLevel< - T extends LogDefinition ? T['level'] : T -> - -export type GetEvents = - T extends Array ? GetLogType : never - -export type QueryEvent = { - timestamp: Date - query: string - params: string - duration: number - target: string -} - -export type LogEvent = { - timestamp: Date - message: string - target: string -} -/* End Types for Logging */ - -export type PrismaAction = - | 'findUnique' - | 'findUniqueOrThrow' - | 'findMany' - | 'findFirst' - | 'findFirstOrThrow' - | 'create' - | 'createMany' - | 'createManyAndReturn' - | 'update' - | 'updateMany' - | 'updateManyAndReturn' - | 'upsert' - | 'delete' - | 'deleteMany' - | 'executeRaw' - | 'queryRaw' - | 'aggregate' - | 'count' - | 'runCommandRaw' - | 'findRaw' - | 'groupBy' - -/** - * `PrismaClient` proxy available in interactive transactions. - */ -export type TransactionClient = Omit< - DefaultPrismaClient, - runtime.ITXClientDenyList -> diff --git a/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespaceBrowser.ts b/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespaceBrowser.ts deleted file mode 100644 index d730c0a5bb5..00000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespaceBrowser.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * WARNING: This is an internal file that is subject to change! - * - * 🛑 Under no circumstances should you import this file directly! 🛑 - * - * All exports from this file are wrapped under a `Prisma` namespace object in the browser.ts file. - * While this enables partial backward compatibility, it is not part of the stable public API. - * - * If you are looking for your Models, Enums, and Input Types, please import them from the respective - * model files in the `model` directory! - */ - -import * as runtime from '@prisma/client/runtime/index-browser' - -export type * from '../models' -export type * from './prismaNamespace' - -export const Decimal = runtime.Decimal - -export const NullTypes = { - DbNull: runtime.NullTypes.DbNull as new ( - secret: never, - ) => typeof runtime.DbNull, - JsonNull: runtime.NullTypes.JsonNull as new ( - secret: never, - ) => typeof runtime.JsonNull, - AnyNull: runtime.NullTypes.AnyNull as new ( - secret: never, - ) => typeof runtime.AnyNull, -} -/** - * Helper for filtering JSON entries that have `null` on the database (empty on the db) - * - * @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field - */ -export const DbNull = runtime.DbNull - -/** - * Helper for filtering JSON entries that have JSON `null` values (not empty on the db) - * - * @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field - */ -export const JsonNull = runtime.JsonNull - -/** - * Helper for filtering JSON entries that are `Prisma.DbNull` or `Prisma.JsonNull` - * - * @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field - */ -export const AnyNull = runtime.AnyNull - -export const ModelName = { - User: 'User', -} as const - -export type ModelName = (typeof ModelName)[keyof typeof ModelName] - -/* - * Enums - */ - -export const TransactionIsolationLevel = { - Serializable: 'Serializable', -} as const - -export type TransactionIsolationLevel = - (typeof TransactionIsolationLevel)[keyof typeof TransactionIsolationLevel] - -export const UserScalarFieldEnum = { - email: 'email', - password: 'password', -} as const - -export type UserScalarFieldEnum = - (typeof UserScalarFieldEnum)[keyof typeof UserScalarFieldEnum] - -export const SortOrder = { - asc: 'asc', - desc: 'desc', -} as const - -export type SortOrder = (typeof SortOrder)[keyof typeof SortOrder] diff --git a/examples/react/start-basic-auth/src/prisma-generated/models.ts b/examples/react/start-basic-auth/src/prisma-generated/models.ts deleted file mode 100644 index 0222c392e33..00000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/models.ts +++ /dev/null @@ -1,11 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * This is a barrel export file for all models and their related types. - * - * 🟢 You can import this file directly. - */ -export type * from './models/User' -export type * from './commonInputTypes' diff --git a/examples/react/start-basic-auth/src/prisma-generated/models/User.ts b/examples/react/start-basic-auth/src/prisma-generated/models/User.ts deleted file mode 100644 index 4312db9bd9f..00000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/models/User.ts +++ /dev/null @@ -1,1323 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * This file exports the `User` model and its related types. - * - * 🟢 You can import this file directly. - */ -import type * as runtime from '@prisma/client/runtime/client' -import type * as $Enums from '../enums' -import type * as Prisma from '../internal/prismaNamespace' - -/** - * Model User - * - */ -export type UserModel = - runtime.Types.Result.DefaultSelection - -export type AggregateUser = { - _count: UserCountAggregateOutputType | null - _min: UserMinAggregateOutputType | null - _max: UserMaxAggregateOutputType | null -} - -export type UserMinAggregateOutputType = { - email: string | null - password: string | null -} - -export type UserMaxAggregateOutputType = { - email: string | null - password: string | null -} - -export type UserCountAggregateOutputType = { - email: number - password: number - _all: number -} - -export type UserMinAggregateInputType = { - email?: true - password?: true -} - -export type UserMaxAggregateInputType = { - email?: true - password?: true -} - -export type UserCountAggregateInputType = { - email?: true - password?: true - _all?: true -} - -export type UserAggregateArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Filter which User to aggregate. - */ - where?: Prisma.UserWhereInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} - * - * Determine the order of Users to fetch. - */ - orderBy?: - | Prisma.UserOrderByWithRelationInput - | Prisma.UserOrderByWithRelationInput[] - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} - * - * Sets the start position - */ - cursor?: Prisma.UserWhereUniqueInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Take `±n` Users from the position of the cursor. - */ - take?: number - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Skip the first `n` Users. - */ - skip?: number - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} - * - * Count returned Users - **/ - _count?: true | UserCountAggregateInputType - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} - * - * Select which fields to find the minimum value - **/ - _min?: UserMinAggregateInputType - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} - * - * Select which fields to find the maximum value - **/ - _max?: UserMaxAggregateInputType -} - -export type GetUserAggregateType = { - [P in keyof T & keyof AggregateUser]: P extends '_count' | 'count' - ? T[P] extends true - ? number - : Prisma.GetScalarType - : Prisma.GetScalarType -} - -export type UserGroupByArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - where?: Prisma.UserWhereInput - orderBy?: - | Prisma.UserOrderByWithAggregationInput - | Prisma.UserOrderByWithAggregationInput[] - by: Prisma.UserScalarFieldEnum[] | Prisma.UserScalarFieldEnum - having?: Prisma.UserScalarWhereWithAggregatesInput - take?: number - skip?: number - _count?: UserCountAggregateInputType | true - _min?: UserMinAggregateInputType - _max?: UserMaxAggregateInputType -} - -export type UserGroupByOutputType = { - email: string - password: string - _count: UserCountAggregateOutputType | null - _min: UserMinAggregateOutputType | null - _max: UserMaxAggregateOutputType | null -} - -type GetUserGroupByPayload = Prisma.PrismaPromise< - Array< - Prisma.PickEnumerable & { - [P in keyof T & keyof UserGroupByOutputType]: P extends '_count' - ? T[P] extends boolean - ? number - : Prisma.GetScalarType - : Prisma.GetScalarType - } - > -> - -export type UserWhereInput = { - AND?: Prisma.UserWhereInput | Prisma.UserWhereInput[] - OR?: Prisma.UserWhereInput[] - NOT?: Prisma.UserWhereInput | Prisma.UserWhereInput[] - email?: Prisma.StringFilter<'User'> | string - password?: Prisma.StringFilter<'User'> | string -} - -export type UserOrderByWithRelationInput = { - email?: Prisma.SortOrder - password?: Prisma.SortOrder -} - -export type UserWhereUniqueInput = Prisma.AtLeast< - { - email?: string - AND?: Prisma.UserWhereInput | Prisma.UserWhereInput[] - OR?: Prisma.UserWhereInput[] - NOT?: Prisma.UserWhereInput | Prisma.UserWhereInput[] - password?: Prisma.StringFilter<'User'> | string - }, - 'email' | 'email' -> - -export type UserOrderByWithAggregationInput = { - email?: Prisma.SortOrder - password?: Prisma.SortOrder - _count?: Prisma.UserCountOrderByAggregateInput - _max?: Prisma.UserMaxOrderByAggregateInput - _min?: Prisma.UserMinOrderByAggregateInput -} - -export type UserScalarWhereWithAggregatesInput = { - AND?: - | Prisma.UserScalarWhereWithAggregatesInput - | Prisma.UserScalarWhereWithAggregatesInput[] - OR?: Prisma.UserScalarWhereWithAggregatesInput[] - NOT?: - | Prisma.UserScalarWhereWithAggregatesInput - | Prisma.UserScalarWhereWithAggregatesInput[] - email?: Prisma.StringWithAggregatesFilter<'User'> | string - password?: Prisma.StringWithAggregatesFilter<'User'> | string -} - -export type UserCreateInput = { - email: string - password: string -} - -export type UserUncheckedCreateInput = { - email: string - password: string -} - -export type UserUpdateInput = { - email?: Prisma.StringFieldUpdateOperationsInput | string - password?: Prisma.StringFieldUpdateOperationsInput | string -} - -export type UserUncheckedUpdateInput = { - email?: Prisma.StringFieldUpdateOperationsInput | string - password?: Prisma.StringFieldUpdateOperationsInput | string -} - -export type UserCreateManyInput = { - email: string - password: string -} - -export type UserUpdateManyMutationInput = { - email?: Prisma.StringFieldUpdateOperationsInput | string - password?: Prisma.StringFieldUpdateOperationsInput | string -} - -export type UserUncheckedUpdateManyInput = { - email?: Prisma.StringFieldUpdateOperationsInput | string - password?: Prisma.StringFieldUpdateOperationsInput | string -} - -export type UserCountOrderByAggregateInput = { - email?: Prisma.SortOrder - password?: Prisma.SortOrder -} - -export type UserMaxOrderByAggregateInput = { - email?: Prisma.SortOrder - password?: Prisma.SortOrder -} - -export type UserMinOrderByAggregateInput = { - email?: Prisma.SortOrder - password?: Prisma.SortOrder -} - -export type StringFieldUpdateOperationsInput = { - set?: string -} - -export type UserSelect< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = runtime.Types.Extensions.GetSelect< - { - email?: boolean - password?: boolean - }, - ExtArgs['result']['user'] -> - -export type UserSelectCreateManyAndReturn< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = runtime.Types.Extensions.GetSelect< - { - email?: boolean - password?: boolean - }, - ExtArgs['result']['user'] -> - -export type UserSelectUpdateManyAndReturn< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = runtime.Types.Extensions.GetSelect< - { - email?: boolean - password?: boolean - }, - ExtArgs['result']['user'] -> - -export type UserSelectScalar = { - email?: boolean - password?: boolean -} - -export type UserOmit< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = runtime.Types.Extensions.GetOmit< - 'email' | 'password', - ExtArgs['result']['user'] -> - -export type $UserPayload< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - name: 'User' - objects: {} - scalars: runtime.Types.Extensions.GetPayloadResult< - { - email: string - password: string - }, - ExtArgs['result']['user'] - > - composites: {} -} - -export type UserGetPayload< - S extends boolean | null | undefined | UserDefaultArgs, -> = runtime.Types.Result.GetResult - -export type UserCountArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = Omit & { - select?: UserCountAggregateInputType | true -} - -export interface UserDelegate< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, - GlobalOmitOptions = {}, -> { - [K: symbol]: { - types: Prisma.TypeMap['model']['User'] - meta: { name: 'User' } - } - /** - * Find zero or one User that matches the filter. - * @param {UserFindUniqueArgs} args - Arguments to find a User - * @example - * // Get one User - * const user = await prisma.user.findUnique({ - * where: { - * // ... provide filter here - * } - * }) - */ - findUnique( - args: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'findUnique', - GlobalOmitOptions - > | null, - null, - ExtArgs, - GlobalOmitOptions - > - - /** - * Find one User that matches the filter or throw an error with `error.code='P2025'` - * if no matches were found. - * @param {UserFindUniqueOrThrowArgs} args - Arguments to find a User - * @example - * // Get one User - * const user = await prisma.user.findUniqueOrThrow({ - * where: { - * // ... provide filter here - * } - * }) - */ - findUniqueOrThrow( - args: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'findUniqueOrThrow', - GlobalOmitOptions - >, - never, - ExtArgs, - GlobalOmitOptions - > - - /** - * Find the first User that matches the filter. - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * @param {UserFindFirstArgs} args - Arguments to find a User - * @example - * // Get one User - * const user = await prisma.user.findFirst({ - * where: { - * // ... provide filter here - * } - * }) - */ - findFirst( - args?: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'findFirst', - GlobalOmitOptions - > | null, - null, - ExtArgs, - GlobalOmitOptions - > - - /** - * Find the first User that matches the filter or - * throw `PrismaKnownClientError` with `P2025` code if no matches were found. - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * @param {UserFindFirstOrThrowArgs} args - Arguments to find a User - * @example - * // Get one User - * const user = await prisma.user.findFirstOrThrow({ - * where: { - * // ... provide filter here - * } - * }) - */ - findFirstOrThrow( - args?: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'findFirstOrThrow', - GlobalOmitOptions - >, - never, - ExtArgs, - GlobalOmitOptions - > - - /** - * Find zero or more Users that matches the filter. - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * @param {UserFindManyArgs} args - Arguments to filter and select certain fields only. - * @example - * // Get all Users - * const users = await prisma.user.findMany() - * - * // Get first 10 Users - * const users = await prisma.user.findMany({ take: 10 }) - * - * // Only select the `email` - * const userWithEmailOnly = await prisma.user.findMany({ select: { email: true } }) - * - */ - findMany( - args?: Prisma.SelectSubset>, - ): Prisma.PrismaPromise< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'findMany', - GlobalOmitOptions - > - > - - /** - * Create a User. - * @param {UserCreateArgs} args - Arguments to create a User. - * @example - * // Create one User - * const User = await prisma.user.create({ - * data: { - * // ... data to create a User - * } - * }) - * - */ - create( - args: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'create', - GlobalOmitOptions - >, - never, - ExtArgs, - GlobalOmitOptions - > - - /** - * Create many Users. - * @param {UserCreateManyArgs} args - Arguments to create many Users. - * @example - * // Create many Users - * const user = await prisma.user.createMany({ - * data: [ - * // ... provide data here - * ] - * }) - * - */ - createMany( - args?: Prisma.SelectSubset>, - ): Prisma.PrismaPromise - - /** - * Create many Users and returns the data saved in the database. - * @param {UserCreateManyAndReturnArgs} args - Arguments to create many Users. - * @example - * // Create many Users - * const user = await prisma.user.createManyAndReturn({ - * data: [ - * // ... provide data here - * ] - * }) - * - * // Create many Users and only return the `email` - * const userWithEmailOnly = await prisma.user.createManyAndReturn({ - * select: { email: true }, - * data: [ - * // ... provide data here - * ] - * }) - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * - */ - createManyAndReturn( - args?: Prisma.SelectSubset>, - ): Prisma.PrismaPromise< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'createManyAndReturn', - GlobalOmitOptions - > - > - - /** - * Delete a User. - * @param {UserDeleteArgs} args - Arguments to delete one User. - * @example - * // Delete one User - * const User = await prisma.user.delete({ - * where: { - * // ... filter to delete one User - * } - * }) - * - */ - delete( - args: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'delete', - GlobalOmitOptions - >, - never, - ExtArgs, - GlobalOmitOptions - > - - /** - * Update one User. - * @param {UserUpdateArgs} args - Arguments to update one User. - * @example - * // Update one User - * const user = await prisma.user.update({ - * where: { - * // ... provide filter here - * }, - * data: { - * // ... provide data here - * } - * }) - * - */ - update( - args: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'update', - GlobalOmitOptions - >, - never, - ExtArgs, - GlobalOmitOptions - > - - /** - * Delete zero or more Users. - * @param {UserDeleteManyArgs} args - Arguments to filter Users to delete. - * @example - * // Delete a few Users - * const { count } = await prisma.user.deleteMany({ - * where: { - * // ... provide filter here - * } - * }) - * - */ - deleteMany( - args?: Prisma.SelectSubset>, - ): Prisma.PrismaPromise - - /** - * Update zero or more Users. - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * @param {UserUpdateManyArgs} args - Arguments to update one or more rows. - * @example - * // Update many Users - * const user = await prisma.user.updateMany({ - * where: { - * // ... provide filter here - * }, - * data: { - * // ... provide data here - * } - * }) - * - */ - updateMany( - args: Prisma.SelectSubset>, - ): Prisma.PrismaPromise - - /** - * Update zero or more Users and returns the data updated in the database. - * @param {UserUpdateManyAndReturnArgs} args - Arguments to update many Users. - * @example - * // Update many Users - * const user = await prisma.user.updateManyAndReturn({ - * where: { - * // ... provide filter here - * }, - * data: [ - * // ... provide data here - * ] - * }) - * - * // Update zero or more Users and only return the `email` - * const userWithEmailOnly = await prisma.user.updateManyAndReturn({ - * select: { email: true }, - * where: { - * // ... provide filter here - * }, - * data: [ - * // ... provide data here - * ] - * }) - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * - */ - updateManyAndReturn( - args: Prisma.SelectSubset>, - ): Prisma.PrismaPromise< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'updateManyAndReturn', - GlobalOmitOptions - > - > - - /** - * Create or update one User. - * @param {UserUpsertArgs} args - Arguments to update or create a User. - * @example - * // Update or create a User - * const user = await prisma.user.upsert({ - * create: { - * // ... data to create a User - * }, - * update: { - * // ... in case it already exists, update - * }, - * where: { - * // ... the filter for the User we want to update - * } - * }) - */ - upsert( - args: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'upsert', - GlobalOmitOptions - >, - never, - ExtArgs, - GlobalOmitOptions - > - - /** - * Count the number of Users. - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * @param {UserCountArgs} args - Arguments to filter Users to count. - * @example - * // Count the number of Users - * const count = await prisma.user.count({ - * where: { - * // ... the filter for the Users we want to count - * } - * }) - **/ - count( - args?: Prisma.Subset, - ): Prisma.PrismaPromise< - T extends runtime.Types.Utils.Record<'select', any> - ? T['select'] extends true - ? number - : Prisma.GetScalarType - : number - > - - /** - * Allows you to perform aggregations operations on a User. - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * @param {UserAggregateArgs} args - Select which aggregations you would like to apply and on what fields. - * @example - * // Ordered by age ascending - * // Where email contains prisma.io - * // Limited to the 10 users - * const aggregations = await prisma.user.aggregate({ - * _avg: { - * age: true, - * }, - * where: { - * email: { - * contains: "prisma.io", - * }, - * }, - * orderBy: { - * age: "asc", - * }, - * take: 10, - * }) - **/ - aggregate( - args: Prisma.Subset, - ): Prisma.PrismaPromise> - - /** - * Group by User. - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * @param {UserGroupByArgs} args - Group by arguments. - * @example - * // Group by city, order by createdAt, get count - * const result = await prisma.user.groupBy({ - * by: ['city', 'createdAt'], - * orderBy: { - * createdAt: true - * }, - * _count: { - * _all: true - * }, - * }) - * - **/ - groupBy< - T extends UserGroupByArgs, - HasSelectOrTake extends Prisma.Or< - Prisma.Extends<'skip', Prisma.Keys>, - Prisma.Extends<'take', Prisma.Keys> - >, - OrderByArg extends Prisma.True extends HasSelectOrTake - ? { orderBy: UserGroupByArgs['orderBy'] } - : { orderBy?: UserGroupByArgs['orderBy'] }, - OrderFields extends Prisma.ExcludeUnderscoreKeys< - Prisma.Keys> - >, - ByFields extends Prisma.MaybeTupleToUnion, - ByValid extends Prisma.Has, - HavingFields extends Prisma.GetHavingFields, - HavingValid extends Prisma.Has, - ByEmpty extends T['by'] extends never[] ? Prisma.True : Prisma.False, - InputErrors extends ByEmpty extends Prisma.True - ? `Error: "by" must not be empty.` - : HavingValid extends Prisma.False - ? { - [P in HavingFields]: P extends ByFields - ? never - : P extends string - ? `Error: Field "${P}" used in "having" needs to be provided in "by".` - : [ - Error, - 'Field ', - P, - ` in "having" needs to be provided in "by"`, - ] - }[HavingFields] - : 'take' extends Prisma.Keys - ? 'orderBy' extends Prisma.Keys - ? ByValid extends Prisma.True - ? {} - : { - [P in OrderFields]: P extends ByFields - ? never - : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` - }[OrderFields] - : 'Error: If you provide "take", you also need to provide "orderBy"' - : 'skip' extends Prisma.Keys - ? 'orderBy' extends Prisma.Keys - ? ByValid extends Prisma.True - ? {} - : { - [P in OrderFields]: P extends ByFields - ? never - : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` - }[OrderFields] - : 'Error: If you provide "skip", you also need to provide "orderBy"' - : ByValid extends Prisma.True - ? {} - : { - [P in OrderFields]: P extends ByFields - ? never - : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` - }[OrderFields], - >( - args: Prisma.SubsetIntersection & - InputErrors, - ): {} extends InputErrors - ? GetUserGroupByPayload - : Prisma.PrismaPromise - /** - * Fields of the User model - */ - readonly fields: UserFieldRefs -} - -/** - * The delegate class that acts as a "Promise-like" for User. - * Why is this prefixed with `Prisma__`? - * Because we want to prevent naming conflicts as mentioned in - * https://github.com/prisma/prisma-client-js/issues/707 - */ -export interface Prisma__UserClient< - T, - Null = never, - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, - GlobalOmitOptions = {}, -> extends Prisma.PrismaPromise { - readonly [Symbol.toStringTag]: 'PrismaPromise' - /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then( - onfulfilled?: - | ((value: T) => TResult1 | PromiseLike) - | undefined - | null, - onrejected?: - | ((reason: any) => TResult2 | PromiseLike) - | undefined - | null, - ): runtime.Types.Utils.JsPromise - /** - * Attaches a callback for only the rejection of the Promise. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of the callback. - */ - catch( - onrejected?: - | ((reason: any) => TResult | PromiseLike) - | undefined - | null, - ): runtime.Types.Utils.JsPromise - /** - * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The - * resolved value cannot be modified from the callback. - * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). - * @returns A Promise for the completion of the callback. - */ - finally( - onfinally?: (() => void) | undefined | null, - ): runtime.Types.Utils.JsPromise -} - -/** - * Fields of the User model - */ -export interface UserFieldRefs { - readonly email: Prisma.FieldRef<'User', 'String'> - readonly password: Prisma.FieldRef<'User', 'String'> -} - -// Custom InputTypes -/** - * User findUnique - */ -export type UserFindUniqueArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * Filter, which User to fetch. - */ - where: Prisma.UserWhereUniqueInput -} - -/** - * User findUniqueOrThrow - */ -export type UserFindUniqueOrThrowArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * Filter, which User to fetch. - */ - where: Prisma.UserWhereUniqueInput -} - -/** - * User findFirst - */ -export type UserFindFirstArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * Filter, which User to fetch. - */ - where?: Prisma.UserWhereInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} - * - * Determine the order of Users to fetch. - */ - orderBy?: - | Prisma.UserOrderByWithRelationInput - | Prisma.UserOrderByWithRelationInput[] - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} - * - * Sets the position for searching for Users. - */ - cursor?: Prisma.UserWhereUniqueInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Take `±n` Users from the position of the cursor. - */ - take?: number - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Skip the first `n` Users. - */ - skip?: number - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} - * - * Filter by unique combinations of Users. - */ - distinct?: Prisma.UserScalarFieldEnum | Prisma.UserScalarFieldEnum[] -} - -/** - * User findFirstOrThrow - */ -export type UserFindFirstOrThrowArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * Filter, which User to fetch. - */ - where?: Prisma.UserWhereInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} - * - * Determine the order of Users to fetch. - */ - orderBy?: - | Prisma.UserOrderByWithRelationInput - | Prisma.UserOrderByWithRelationInput[] - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} - * - * Sets the position for searching for Users. - */ - cursor?: Prisma.UserWhereUniqueInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Take `±n` Users from the position of the cursor. - */ - take?: number - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Skip the first `n` Users. - */ - skip?: number - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} - * - * Filter by unique combinations of Users. - */ - distinct?: Prisma.UserScalarFieldEnum | Prisma.UserScalarFieldEnum[] -} - -/** - * User findMany - */ -export type UserFindManyArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * Filter, which Users to fetch. - */ - where?: Prisma.UserWhereInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} - * - * Determine the order of Users to fetch. - */ - orderBy?: - | Prisma.UserOrderByWithRelationInput - | Prisma.UserOrderByWithRelationInput[] - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} - * - * Sets the position for listing Users. - */ - cursor?: Prisma.UserWhereUniqueInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Take `±n` Users from the position of the cursor. - */ - take?: number - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Skip the first `n` Users. - */ - skip?: number - distinct?: Prisma.UserScalarFieldEnum | Prisma.UserScalarFieldEnum[] -} - -/** - * User create - */ -export type UserCreateArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * The data needed to create a User. - */ - data: Prisma.XOR -} - -/** - * User createMany - */ -export type UserCreateManyArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * The data used to create many Users. - */ - data: Prisma.UserCreateManyInput | Prisma.UserCreateManyInput[] -} - -/** - * User createManyAndReturn - */ -export type UserCreateManyAndReturnArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelectCreateManyAndReturn | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * The data used to create many Users. - */ - data: Prisma.UserCreateManyInput | Prisma.UserCreateManyInput[] -} - -/** - * User update - */ -export type UserUpdateArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * The data needed to update a User. - */ - data: Prisma.XOR - /** - * Choose, which User to update. - */ - where: Prisma.UserWhereUniqueInput -} - -/** - * User updateMany - */ -export type UserUpdateManyArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * The data used to update Users. - */ - data: Prisma.XOR< - Prisma.UserUpdateManyMutationInput, - Prisma.UserUncheckedUpdateManyInput - > - /** - * Filter which Users to update - */ - where?: Prisma.UserWhereInput - /** - * Limit how many Users to update. - */ - limit?: number -} - -/** - * User updateManyAndReturn - */ -export type UserUpdateManyAndReturnArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelectUpdateManyAndReturn | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * The data used to update Users. - */ - data: Prisma.XOR< - Prisma.UserUpdateManyMutationInput, - Prisma.UserUncheckedUpdateManyInput - > - /** - * Filter which Users to update - */ - where?: Prisma.UserWhereInput - /** - * Limit how many Users to update. - */ - limit?: number -} - -/** - * User upsert - */ -export type UserUpsertArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * The filter to search for the User to update in case it exists. - */ - where: Prisma.UserWhereUniqueInput - /** - * In case the User found by the `where` argument doesn't exist, create a new User with this data. - */ - create: Prisma.XOR - /** - * In case the User was found with the provided `where` argument, update it with this data. - */ - update: Prisma.XOR -} - -/** - * User delete - */ -export type UserDeleteArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * Filter which User to delete. - */ - where: Prisma.UserWhereUniqueInput -} - -/** - * User deleteMany - */ -export type UserDeleteManyArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Filter which Users to delete - */ - where?: Prisma.UserWhereInput - /** - * Limit how many Users to delete. - */ - limit?: number -} - -/** - * User without action - */ -export type UserDefaultArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null -} diff --git a/examples/react/start-basic-auth/src/routeTree.gen.ts b/examples/react/start-basic-auth/src/routeTree.gen.ts deleted file mode 100644 index 6691c8a12f3..00000000000 --- a/examples/react/start-basic-auth/src/routeTree.gen.ts +++ /dev/null @@ -1,224 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as SignupRouteImport } from './routes/signup' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthedRouteImport } from './routes/_authed' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AuthedPostsRouteRouteImport } from './routes/_authed/posts.route' -import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' -import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' - -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', - getParentRoute: () => rootRouteImport, -} as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', - getParentRoute: () => rootRouteImport, -} as any) -const LoginRoute = LoginRouteImport.update({ - id: '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/login', - path: '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/login', - getParentRoute: () => rootRouteImport, -} as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthedPostsRouteRoute = AuthedPostsRouteRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => AuthedRoute, -} as any) -const AuthedPostsIndexRoute = AuthedPostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => AuthedPostsRouteRoute, -} as any) -const AuthedPostsPostIdRoute = AuthedPostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => AuthedPostsRouteRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '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/login': typeof LoginRoute - '/logout': typeof LogoutRoute - '/signup': typeof SignupRoute - '/posts': typeof AuthedPostsRouteRouteWithChildren - '/posts/$postId': typeof AuthedPostsPostIdRoute - '/posts/': typeof AuthedPostsIndexRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '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/login': typeof LoginRoute - '/logout': typeof LogoutRoute - '/signup': typeof SignupRoute - '/posts/$postId': typeof AuthedPostsPostIdRoute - '/posts': typeof AuthedPostsIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/_authed': typeof AuthedRouteWithChildren - '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/login': typeof LoginRoute - '/logout': typeof LogoutRoute - '/signup': typeof SignupRoute - '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/_authed/posts': typeof AuthedPostsRouteRouteWithChildren - '/_authed/posts/$postId': typeof AuthedPostsPostIdRoute - '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/_authed/posts/': typeof AuthedPostsIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '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/login' - | '/logout' - | '/signup' - | '/posts' - | '/posts/$postId' - | '/posts/' - fileRoutesByTo: FileRoutesByTo - to: '/' | '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/login' | '/logout' | '/signup' | '/posts/$postId' | '/posts' - id: - | '__root__' - | '/' - | '/_authed' - | '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/login' - | '/logout' - | '/signup' - | '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/_authed/posts' - | '/_authed/posts/$postId' - | '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/_authed/posts/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AuthedRoute: typeof AuthedRouteWithChildren - LoginRoute: typeof LoginRoute - LogoutRoute: typeof LogoutRoute - SignupRoute: typeof SignupRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport - parentRoute: typeof rootRouteImport - } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport - parentRoute: typeof rootRouteImport - } - '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/login': { - id: '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/login' - path: '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/login' - fullPath: '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/login' - preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '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/_authed/posts': { - id: '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/_authed/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof AuthedPostsRouteRouteImport - parentRoute: typeof AuthedRoute - } - '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/_authed/posts/': { - id: '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/_authed/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof AuthedPostsIndexRouteImport - parentRoute: typeof AuthedPostsRouteRoute - } - '/_authed/posts/$postId': { - id: '/_authed/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof AuthedPostsPostIdRouteImport - parentRoute: typeof AuthedPostsRouteRoute - } - } -} - -interface AuthedPostsRouteRouteChildren { - AuthedPostsPostIdRoute: typeof AuthedPostsPostIdRoute - AuthedPostsIndexRoute: typeof AuthedPostsIndexRoute -} - -const AuthedPostsRouteRouteChildren: AuthedPostsRouteRouteChildren = { - AuthedPostsPostIdRoute: AuthedPostsPostIdRoute, - AuthedPostsIndexRoute: AuthedPostsIndexRoute, -} - -const AuthedPostsRouteRouteWithChildren = - AuthedPostsRouteRoute._addFileChildren(AuthedPostsRouteRouteChildren) - -interface AuthedRouteChildren { - AuthedPostsRouteRoute: typeof AuthedPostsRouteRouteWithChildren -} - -const AuthedRouteChildren: AuthedRouteChildren = { - AuthedPostsRouteRoute: AuthedPostsRouteRouteWithChildren, -} - -const AuthedRouteWithChildren = - AuthedRoute._addFileChildren(AuthedRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AuthedRoute: AuthedRouteWithChildren, - LoginRoute: LoginRoute, - LogoutRoute: LogoutRoute, - SignupRoute: SignupRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' -declare module '@tanstack/react-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/examples/react/start-basic-auth/src/router.tsx b/examples/react/start-basic-auth/src/router.tsx deleted file mode 100644 index f648dfcf8c4..00000000000 --- a/examples/react/start-basic-auth/src/router.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - const router = createRouter({ - routeTree, - defaultPreload: 'intent', - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - scrollRestoration: true, - }) - - return router -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/examples/react/start-basic-auth/src/routes/__root.tsx b/examples/react/start-basic-auth/src/routes/__root.tsx deleted file mode 100644 index 5728345fcff..00000000000 --- a/examples/react/start-basic-auth/src/routes/__root.tsx +++ /dev/null @@ -1,141 +0,0 @@ -/// -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import { createServerFn } from '@tanstack/react-start' -import * as React from 'react' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' -import { NotFound } from '~/components/NotFound.js' -import appCss from '~/styles/app.css?url' -import { seo } from '~/utils/seo.js' -import { useAppSession } from '~/utils/session.js' - -const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { - // We need to auth on the server so we have access to secure cookies - const session = await useAppSession() - - if (!session.data.userEmail) { - return null - } - - return { - email: session.data.userEmail, - } -}) - -export const Route = createRootRoute({ - beforeLoad: async () => { - const user = await fetchUser() - - return { - user, - } - }, - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - ...seo({ - title: - 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', - description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, - }), - ], - links: [ - { rel: 'stylesheet', href: appCss }, - { - rel: 'apple-touch-icon', - sizes: '180x180', - href: '/apple-touch-icon.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '32x32', - href: '/favicon-32x32.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '16x16', - href: '/favicon-16x16.png', - }, - { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, - { rel: 'icon', href: '/favicon.ico' }, - ], - }), - errorComponent: (props) => { - return ( - - - - ) - }, - notFoundComponent: () => , - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - ) -} - -function RootDocument({ children }: { children: React.ReactNode }) { - const { user } = Route.useRouteContext() - - return ( - - - - - -

-
- {children} - - - - - ) -} diff --git a/examples/react/start-basic-auth/src/routes/_authed.tsx b/examples/react/start-basic-auth/src/routes/_authed.tsx deleted file mode 100644 index 230be64c625..00000000000 --- a/examples/react/start-basic-auth/src/routes/_authed.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { hashPassword, prismaClient } from '~/utils/prisma' -import { Login } from '~/components/Login' -import { useAppSession } from '~/utils/session' - -export const loginFn = createServerFn({ method: 'POST' }) - .inputValidator((d: { email: string; password: string }) => d) - .handler(async ({ data }) => { - // Find the user - const user = await prismaClient.user.findUnique({ - where: { - email: data.email, - }, - }) - - // Check if the user exists - if (!user) { - return { - error: true, - userNotFound: true, - message: 'User not found', - } - } - - // Check if the password is correct - const hashedPassword = await hashPassword(data.password) - - if (user.password !== hashedPassword) { - return { - error: true, - message: 'Incorrect password', - } - } - - // Create a session - const session = await useAppSession() - - // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) - }) - -export const Route = createFileRoute('/_authed')({ - beforeLoad: ({ context }) => { - if (!context.user) { - throw new Error('Not authenticated') - } - }, - errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { - return - } - - throw error - }, -}) diff --git a/examples/react/start-basic-auth/src/routes/_authed/posts.$postId.tsx b/examples/react/start-basic-auth/src/routes/_authed/posts.$postId.tsx deleted file mode 100644 index 039271bb896..00000000000 --- a/examples/react/start-basic-auth/src/routes/_authed/posts.$postId.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { ErrorComponent, createFileRoute } from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' -import { NotFound } from '~/components/NotFound.js' -import { fetchPost } from '~/utils/posts.js' - -export const Route = createFileRoute('/_authed/posts/$postId')({ - loader: ({ params: { postId } }) => fetchPost({ data: postId }), - errorComponent: PostErrorComponent, - component: PostComponent, - notFoundComponent: () => { - return Post not found - }, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return -} - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.title}

-
{post.body}
-
- ) -} diff --git a/examples/react/start-basic-auth/src/routes/_authed/posts.index.tsx b/examples/react/start-basic-auth/src/routes/_authed/posts.index.tsx deleted file mode 100644 index de01fe5ddef..00000000000 --- a/examples/react/start-basic-auth/src/routes/_authed/posts.index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('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/_authed/posts/')({ - component: PostsIndexComponent, -}) - -function PostsIndexComponent() { - return
Select a post.
-} diff --git a/examples/react/start-basic-auth/src/routes/_authed/posts.route.tsx b/examples/react/start-basic-auth/src/routes/_authed/posts.route.tsx deleted file mode 100644 index 86c8ef41389..00000000000 --- a/examples/react/start-basic-auth/src/routes/_authed/posts.route.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '~/utils/posts.js' - -export const Route = createFileRoute('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/_authed/posts')({ - loader: () => fetchPosts(), - component: PostsComponent, -}) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( - (post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - }, - )} -
-
- -
- ) -} diff --git a/examples/react/start-basic-auth/src/routes/index.tsx b/examples/react/start-basic-auth/src/routes/index.tsx deleted file mode 100644 index 37c8d237bd4..00000000000 --- a/examples/react/start-basic-auth/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Welcome Home!!!

-
- ) -} diff --git a/examples/react/start-basic-auth/src/routes/login.tsx b/examples/react/start-basic-auth/src/routes/login.tsx deleted file mode 100644 index 03ced208326..00000000000 --- a/examples/react/start-basic-auth/src/routes/login.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { Login } from '~/components/Login' - -export const Route = createFileRoute('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/login')({ - component: LoginComp, -}) - -function LoginComp() { - return -} diff --git a/examples/react/start-basic-auth/src/routes/logout.tsx b/examples/react/start-basic-auth/src/routes/logout.tsx deleted file mode 100644 index 28f3c9f8feb..00000000000 --- a/examples/react/start-basic-auth/src/routes/logout.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { redirect, createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { useAppSession } from '~/utils/session' - -const logoutFn = createServerFn().handler(async () => { - const session = await useAppSession() - - session.clear() - - throw redirect({ - href: '/', - }) -}) - -export const Route = createFileRoute('/logout')({ - preload: false, - loader: () => logoutFn(), -}) diff --git a/examples/react/start-basic-auth/src/routes/signup.tsx b/examples/react/start-basic-auth/src/routes/signup.tsx deleted file mode 100644 index 7b64265840b..00000000000 --- a/examples/react/start-basic-auth/src/routes/signup.tsx +++ /dev/null @@ -1,97 +0,0 @@ -import { redirect, createFileRoute } from '@tanstack/react-router' -import { createServerFn, useServerFn } from '@tanstack/react-start' -import { hashPassword, prismaClient } from '~/utils/prisma' -import { useMutation } from '~/hooks/useMutation' -import { Auth } from '~/components/Auth' -import { useAppSession } from '~/utils/session' - -export const signupFn = createServerFn({ method: 'POST' }) - .inputValidator( - (d: { email: string; password: string; redirectUrl?: string }) => d, - ) - .handler(async ({ data }) => { - // Check if the user already exists - const found = await prismaClient.user.findUnique({ - where: { - email: data.email, - }, - }) - - // Encrypt the password using Sha256 into plaintext - const password = await hashPassword(data.password) - - // Create a session - const session = await useAppSession() - - if (found) { - if (found.password !== password) { - return { - error: true, - userExists: true, - message: 'User already exists', - } - } - - // Store the user's email in the session - await session.update({ - userEmail: found.email, - }) - - // Redirect to the prev page stored in the "redirect" search param - throw redirect({ - href: data.redirectUrl || '/', - }) - } - - // Create the user - const user = await prismaClient.user.create({ - data: { - email: data.email, - password, - }, - }) - - // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) - - // Redirect to the prev page stored in the "redirect" search param - throw redirect({ - href: data.redirectUrl || '/', - }) - }) - -export const Route = createFileRoute('/signup')({ - component: SignupComp, -}) - -function SignupComp() { - const signupMutation = useMutation({ - fn: useServerFn(signupFn), - }) - - return ( - { - const formData = new FormData(e.target as HTMLFormElement) - - signupMutation.mutate({ - data: { - email: formData.get('email') as string, - password: formData.get('password') as string, - }, - }) - }} - afterSubmit={ - signupMutation.data?.error ? ( - <> -
{signupMutation.data.message}
- - ) : null - } - /> - ) -} diff --git a/examples/react/start-basic-auth/src/styles/app.css b/examples/react/start-basic-auth/src/styles/app.css deleted file mode 100644 index 37c1f5a6e2d..00000000000 --- a/examples/react/start-basic-auth/src/styles/app.css +++ /dev/null @@ -1,30 +0,0 @@ -@import 'tailwindcss' source('../'); - -@layer base { - *, - ::after, - ::before, - ::backdrop, - ::file-selector-button { - border-color: var(--color-gray-200, currentcolor); - } -} - -@layer base { - html { - color-scheme: light dark; - } - - * { - @apply border-gray-200 dark:border-gray-800; - } - - html, - body { - @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; - } - - .using-mouse * { - outline: none !important; - } -} diff --git a/examples/react/start-basic-auth/src/utils/posts.ts b/examples/react/start-basic-auth/src/utils/posts.ts deleted file mode 100644 index fbcc43c34b0..00000000000 --- a/examples/react/start-basic-auth/src/utils/posts.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { notFound } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import axios from 'redaxios' - -export type PostType = { - id: string - title: string - body: string -} - -export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((postId: string) => postId) - .handler(async ({ data }) => { - console.info(`Fetching post with id ${data}...`) - const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${data}`) - .then((r) => r.data) - .catch((err) => { - console.error(err) - if (err.status === 404) { - throw notFound() - } - throw err - }) - - return post - }) - -export const fetchPosts = createServerFn({ method: 'GET' }).handler( - async () => { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 1000)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) - }, -) diff --git a/examples/react/start-basic-auth/src/utils/prisma.ts b/examples/react/start-basic-auth/src/utils/prisma.ts deleted file mode 100644 index d08622b30b7..00000000000 --- a/examples/react/start-basic-auth/src/utils/prisma.ts +++ /dev/null @@ -1,20 +0,0 @@ -import crypto from 'node:crypto' -import { PrismaLibSql } from '@prisma/adapter-libsql' -import { PrismaClient } from '../prisma-generated/client' - -const adapter = new PrismaLibSql({ - url: process.env.DATABASE_URL || 'file:./prisma/dev.db', -}) -export const prismaClient = new PrismaClient({ adapter }) - -export function hashPassword(password: string) { - return new Promise((resolve, reject) => { - crypto.pbkdf2(password, 'salt', 100000, 64, 'sha256', (err, derivedKey) => { - if (err) { - reject(err) - } else { - resolve(derivedKey.toString('hex')) - } - }) - }) -} diff --git a/examples/react/start-basic-auth/src/utils/seo.ts b/examples/react/start-basic-auth/src/utils/seo.ts deleted file mode 100644 index d18ad84b74e..00000000000 --- a/examples/react/start-basic-auth/src/utils/seo.ts +++ /dev/null @@ -1,33 +0,0 @@ -export const seo = ({ - title, - description, - keywords, - image, -}: { - title: string - description?: string - image?: string - keywords?: string -}) => { - const tags = [ - { title }, - { name: 'description', content: description }, - { name: 'keywords', content: keywords }, - { name: 'twitter:title', content: title }, - { name: 'twitter:description', content: description }, - { name: 'twitter:creator', content: '@tannerlinsley' }, - { name: 'twitter:site', content: '@tannerlinsley' }, - { name: 'og:type', content: 'website' }, - { name: 'og:title', content: title }, - { name: 'og:description', content: description }, - ...(image - ? [ - { name: 'twitter:image', content: image }, - { name: 'twitter:card', content: 'summary_large_image' }, - { name: 'og:image', content: image }, - ] - : []), - ] - - return tags -} diff --git a/examples/react/start-basic-auth/src/utils/session.ts b/examples/react/start-basic-auth/src/utils/session.ts deleted file mode 100644 index c38bac1e48e..00000000000 --- a/examples/react/start-basic-auth/src/utils/session.ts +++ /dev/null @@ -1,13 +0,0 @@ -// src/services/session.server.ts -import { useSession } from '@tanstack/react-start/server' -import type { User } from '@prisma/client' - -type SessionUser = { - userEmail: User['email'] -} - -export function useAppSession() { - return useSession({ - password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', - }) -} diff --git a/examples/react/start-basic-auth/tsconfig.json b/examples/react/start-basic-auth/tsconfig.json deleted file mode 100644 index 3a9fb7cd716..00000000000 --- a/examples/react/start-basic-auth/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "baseUrl": ".", - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/examples/react/start-basic-auth/vite.config.ts b/examples/react/start-basic-auth/vite.config.ts deleted file mode 100644 index 843599315ef..00000000000 --- a/examples/react/start-basic-auth/vite.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' -import viteReact from '@vitejs/plugin-react' -import tailwindcss from '@tailwindcss/vite' - -export default defineConfig({ - server: { - port: 3000, - }, - plugins: [ - tailwindcss(), - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], -}) diff --git a/examples/react/start-basic-authjs/.env.example b/examples/react/start-basic-authjs/.env.example deleted file mode 100644 index 062e707907f..00000000000 --- a/examples/react/start-basic-authjs/.env.example +++ /dev/null @@ -1,11 +0,0 @@ -# Auth.js Configuration -AUTH_SECRET=your-secret-key-here-min-32-chars-long - -# Auth.js URL (must include the auth path) -AUTH_URL=http://localhost:10000/api/auth - -# Auth0 Configuration (https://manage.auth0.com) -# Auth.js auto-reads these env vars for the Auth0 provider -AUTH_AUTH0_ID=your-auth0-client-id -AUTH_AUTH0_SECRET=your-auth0-client-secret -AUTH_AUTH0_ISSUER=https://your-tenant.auth0.com diff --git a/examples/react/start-basic-authjs/.gitignore b/examples/react/start-basic-authjs/.gitignore deleted file mode 100644 index dc87421f7dc..00000000000 --- a/examples/react/start-basic-authjs/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -node_modules -dist -.env -*.local -.DS_Store -.tanstack \ No newline at end of file diff --git a/examples/react/start-basic-authjs/README.md b/examples/react/start-basic-authjs/README.md index 4a908d80695..4560cf8bd52 100644 --- a/examples/react/start-basic-authjs/README.md +++ b/examples/react/start-basic-authjs/README.md @@ -1,51 +1,17 @@ -# TanStack Start - Auth.js Example +# Deprecated: TanStack Start React Example (`start-basic-authjs`) -A TanStack Start example demonstrating authentication with Auth.js (NextAuth.js). +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) -- [Auth.js Documentation](https://authjs.dev/) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-basic-authjs start-basic-authjs -``` +- [Start React Quick Start](https://tanstack.com/router/latest/docs/framework/react/start/quick-start) +- [Start React Guides](https://tanstack.com/router/latest/docs/framework/react/start/guide/routing) -## Setup +Canonical issue reproduction baseline: -This example requires environment variables for Auth.js configuration. Copy the `.env.example` file to `.env` and fill in your authentication provider credentials: - -```sh -cp .env.example .env -``` - -Edit `.env` and add your authentication provider credentials. - -## Getting Started - -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -This starts your app in development mode, rebuilding assets on file changes. - -## Build - -To build the app for production: - -```sh -pnpm build -``` - -## Authentication Configuration - -This example demonstrates how to integrate Auth.js with TanStack Start. Check the source code for examples of: - -- Configuring authentication providers -- Protecting routes with authentication -- Accessing session data in server functions +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-basic-authjs/package.json b/examples/react/start-basic-authjs/package.json deleted file mode 100644 index 289de8ffd0f..00000000000 --- a/examples/react/start-basic-authjs/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "tanstack-router-react-example-basic-authjs", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build", - "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" - }, - "dependencies": { - "@auth/core": "^0.41.1", - "@tanstack/react-router": "^1.161.1", - "@tanstack/react-router-devtools": "^1.161.1", - "@tanstack/react-start": "^1.161.1", - "start-authjs": "^1.0.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "tailwind-merge": "^2.6.0" - }, - "devDependencies": { - "@tailwindcss/vite": "^4.1.18", - "@types/node": "^22.5.4", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "tailwindcss": "^4.1.18", - "typescript": "^5.7.2", - "vite": "^7.3.1", - "@vitejs/plugin-react": "^4.6.0", - "vite-tsconfig-paths": "^5.1.4" - } -} diff --git a/examples/react/start-basic-authjs/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-authjs/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index 260c2ea41f7..00000000000 --- a/examples/react/start-basic-authjs/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { - ErrorComponent, - Link, - rootRouteId, - useMatch, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error('DefaultCatchBoundary Error:', error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/examples/react/start-basic-authjs/src/components/NotFound.tsx b/examples/react/start-basic-authjs/src/components/NotFound.tsx deleted file mode 100644 index fd4e75befe3..00000000000 --- a/examples/react/start-basic-authjs/src/components/NotFound.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: any }) { - return ( -
-
- {children ||

The page you are looking for does not exist.

} -
-

- - - Start Over - -

-
- ) -} diff --git a/examples/react/start-basic-authjs/src/routeTree.gen.ts b/examples/react/start-basic-authjs/src/routeTree.gen.ts deleted file mode 100644 index 2f59e4ba338..00000000000 --- a/examples/react/start-basic-authjs/src/routeTree.gen.ts +++ /dev/null @@ -1,122 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ProtectedRouteImport } from './routes/protected' -import { Route as LoginRouteImport } from './routes/login' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$' - -const ProtectedRoute = ProtectedRouteImport.update({ - id: '/protected', - path: '/protected', - getParentRoute: () => rootRouteImport, -} as any) -const LoginRoute = LoginRouteImport.update({ - id: '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/login', - path: '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/login', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiAuthSplatRoute = ApiAuthSplatRouteImport.update({ - id: '/api/auth/$', - path: '/api/auth/$', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '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/login': typeof LoginRoute - '/protected': typeof ProtectedRoute - '/api/auth/$': typeof ApiAuthSplatRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '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/login': typeof LoginRoute - '/protected': typeof ProtectedRoute - '/api/auth/$': typeof ApiAuthSplatRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '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/login': typeof LoginRoute - '/protected': typeof ProtectedRoute - '/api/auth/$': typeof ApiAuthSplatRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '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/login' | '/protected' | '/api/auth/$' - fileRoutesByTo: FileRoutesByTo - to: '/' | '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/login' | '/protected' | '/api/auth/$' - id: '__root__' | '/' | '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/login' | '/protected' | '/api/auth/$' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - LoginRoute: typeof LoginRoute - ProtectedRoute: typeof ProtectedRoute - ApiAuthSplatRoute: typeof ApiAuthSplatRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/protected': { - id: '/protected' - path: '/protected' - fullPath: '/protected' - preLoaderRoute: typeof ProtectedRouteImport - parentRoute: typeof rootRouteImport - } - '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/login': { - id: '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/login' - path: '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/login' - fullPath: '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/login' - preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/auth/$': { - id: '/api/auth/$' - path: '/api/auth/$' - fullPath: '/api/auth/$' - preLoaderRoute: typeof ApiAuthSplatRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - LoginRoute: LoginRoute, - ProtectedRoute: ProtectedRoute, - ApiAuthSplatRoute: ApiAuthSplatRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' -declare module '@tanstack/react-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/examples/react/start-basic-authjs/src/router.tsx b/examples/react/start-basic-authjs/src/router.tsx deleted file mode 100644 index f380f73be74..00000000000 --- a/examples/react/start-basic-authjs/src/router.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - const router = createRouter({ - routeTree, - defaultPreload: 'intent', - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - scrollRestoration: true, - }) - return router -} diff --git a/examples/react/start-basic-authjs/src/routes/__root.tsx b/examples/react/start-basic-authjs/src/routes/__root.tsx deleted file mode 100644 index af2c24ab57b..00000000000 --- a/examples/react/start-basic-authjs/src/routes/__root.tsx +++ /dev/null @@ -1,117 +0,0 @@ -/// -import type { ReactNode } from 'react' -import type { AuthSession } from 'start-authjs' -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRouteWithContext, -} from '@tanstack/react-router' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import { createServerFn } from '@tanstack/react-start' -import { getRequest } from '@tanstack/react-start/server' -import { getSession } from 'start-authjs' -import { authConfig } from '~/utils/auth' -import appCss from '~/styles/app.css?url' - -interface RouterContext { - session: AuthSession | null -} - -const fetchSession = createServerFn({ method: 'GET' }).handler(async () => { - const request = getRequest() - const session = await getSession(request, authConfig) - return session -}) - -export const Route = createRootRouteWithContext()({ - beforeLoad: async () => { - const session = await fetchSession() - return { - session, - } - }, - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - { - title: 'TanStack Start Auth Example', - }, - ], - links: [{ rel: 'stylesheet', href: appCss }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - ) -} - -function RootDocument({ children }: { children: ReactNode }) { - return ( - - - - - - -
{children}
- - - - - ) -} - -function NavBar() { - const routeContext = Route.useRouteContext() - - return ( -
- ) -} diff --git a/examples/react/start-basic-authjs/src/routes/api/auth/$.ts b/examples/react/start-basic-authjs/src/routes/api/auth/$.ts deleted file mode 100644 index 3e59239db5c..00000000000 --- a/examples/react/start-basic-authjs/src/routes/api/auth/$.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { StartAuthJS } from 'start-authjs' -import { authConfig } from '~/utils/auth' - -/** - * Auth.js API route handler - * Handles all auth routes: /api/auth/* - */ -const { GET, POST } = StartAuthJS(authConfig) - -export const Route = createFileRoute('/api/auth/$')({ - server: { - handlers: { - GET: ({ request }) => GET({ request, response: new Response() }), - POST: ({ request }) => POST({ request, response: new Response() }), - }, - }, -}) diff --git a/examples/react/start-basic-authjs/src/routes/index.tsx b/examples/react/start-basic-authjs/src/routes/index.tsx deleted file mode 100644 index 5723b0f030a..00000000000 --- a/examples/react/start-basic-authjs/src/routes/index.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - const { session } = Route.useRouteContext() - const user = session?.user - - return ( -
-

- TanStack Start Auth.js Example -

-

- This example demonstrates auth.js integration with TanStack Start using - Auth0 OAuth. -

- -
-

Auth Status

- - {session ? ( -
-

Authenticated

- {user?.image && ( - Avatar - )} -

- Name: {user?.name ?? 'N/A'} -

-

- Email: {user?.email ?? 'N/A'} -

-
- ) : ( -

- You are not signed in. Click "Sign In" in the navigation bar to - authenticate with Auth0. -

- )} -
-
- ) -} diff --git a/examples/react/start-basic-authjs/src/routes/login.tsx b/examples/react/start-basic-authjs/src/routes/login.tsx deleted file mode 100644 index 008f62d5112..00000000000 --- a/examples/react/start-basic-authjs/src/routes/login.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import { useState, useEffect, Suspense } from 'react' -import { createFileRoute, redirect } from '@tanstack/react-router' - -export const Route = createFileRoute('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/login')({ - beforeLoad: ({ context }) => { - // Redirect if already authenticated - if (context.session) { - throw redirect({ to: '/' }) - } - }, - component: Login, -}) - -function Login() { - const [csrfToken, setCsrfToken] = useState('') - - useEffect(() => { - fetch('/api/auth/csrf') - .then((res) => res.json()) - .then((data) => setCsrfToken(data.csrfToken)) - }, []) - - return ( -
-

Sign In

- -
-
- - - -
- -

- You'll be redirected to Auth0 to complete the sign-in process. -

-
-
- ) -} diff --git a/examples/react/start-basic-authjs/src/routes/protected.tsx b/examples/react/start-basic-authjs/src/routes/protected.tsx deleted file mode 100644 index a5b960582ad..00000000000 --- a/examples/react/start-basic-authjs/src/routes/protected.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' - -export const Route = createFileRoute('/protected')({ - beforeLoad: ({ context }) => { - if (!context.session) { - throw redirect({ to: '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/login' }) - } - }, - component: Protected, -}) - -function Protected() { - const { session } = Route.useRouteContext() - const user = session?.user - - return ( -
-

Protected Page

-

- This page is only accessible to authenticated users. -

- -
-

- Welcome, {user?.name ?? 'User'}! -

- - {user && ( -
-

- Email: {user?.email ?? 'N/A'} -

- {user?.image && ( -
- Avatar: - User avatar -
- )} -
- )} -
- -
-

Session Data (Debug)

-
-          {JSON.stringify(session, null, 2)}
-        
-
-
- ) -} diff --git a/examples/react/start-basic-authjs/src/styles/app.css b/examples/react/start-basic-authjs/src/styles/app.css deleted file mode 100644 index 23fa2415ca2..00000000000 --- a/examples/react/start-basic-authjs/src/styles/app.css +++ /dev/null @@ -1 +0,0 @@ -@import 'tailwindcss' source('../'); diff --git a/examples/react/start-basic-authjs/src/utils/auth.ts b/examples/react/start-basic-authjs/src/utils/auth.ts deleted file mode 100644 index 8d5c0b1baff..00000000000 --- a/examples/react/start-basic-authjs/src/utils/auth.ts +++ /dev/null @@ -1,50 +0,0 @@ -import Auth0 from '@auth/core/providers/auth0' -import { setCookie } from '@tanstack/react-start/server' -import type { Profile } from '@auth/core/types' -import type { StartAuthJSConfig } from 'start-authjs' - -declare module '@auth/core/types' { - export interface Session { - user: { - name: string - email: string - sub: string - email_verified: boolean - } & Profile - account: { - access_token: string - } - expires: Date - } -} - -/** - * Auth.js configuration for TanStack Start with Auth0 - */ -export const authConfig: StartAuthJSConfig = { - // basePath is derived from AUTH_URL env var - secret: process.env.AUTH_SECRET, - providers: [ - Auth0({ - // Auth.js auto-reads AUTH_AUTH0_ID, AUTH_AUTH0_SECRET, AUTH_AUTH0_ISSUER from env - authorization: { - params: { - scope: 'email email_verified openid profile', - prompt: 'login', - }, - }, - async profile(profile, tokens) { - await setCookie( - 'auth0Token', - encodeURIComponent(tokens.access_token ?? ''), - ) - await setCookie( - 'auth0User', - encodeURIComponent(JSON.stringify(profile)), - ) - - return profile - }, - }), - ], -} diff --git a/examples/react/start-basic-authjs/tsconfig.json b/examples/react/start-basic-authjs/tsconfig.json deleted file mode 100644 index 70cbbc5ce37..00000000000 --- a/examples/react/start-basic-authjs/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "lib": ["ES2022", "DOM", "DOM.Iterable"], - "module": "ESNext", - "skipLibCheck": true, - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true, - "jsx": "react-jsx", - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noFallthroughCasesInSwitch": true, - "allowSyntheticDefaultImports": true, - "baseUrl": ".", - "paths": { - "~/*": ["./src/*"] - } - }, - "include": ["src", "env.d.ts", "vite.config.ts"] -} diff --git a/examples/react/start-basic-authjs/vite.config.ts b/examples/react/start-basic-authjs/vite.config.ts deleted file mode 100644 index e6d05205653..00000000000 --- a/examples/react/start-basic-authjs/vite.config.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' -import viteReact from '@vitejs/plugin-react' -import tailwindcss from '@tailwindcss/vite' - -export default defineConfig({ - server: { - port: 10000, - strictPort: true, - }, - plugins: [ - tailwindcss(), - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], -}) diff --git a/examples/react/start-basic-cloudflare/.gitignore b/examples/react/start-basic-cloudflare/.gitignore deleted file mode 100644 index 32f79ff6cd2..00000000000 --- a/examples/react/start-basic-cloudflare/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -node_modules -.DS_Store -.cache -.env -dist -.wrangler diff --git a/examples/react/start-basic-cloudflare/.prettierignore b/examples/react/start-basic-cloudflare/.prettierignore deleted file mode 100644 index f36f42b7c8b..00000000000 --- a/examples/react/start-basic-cloudflare/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/public -pnpm-lock.yaml -routeTree.gen.ts -worker-configuration.d.ts diff --git a/examples/react/start-basic-cloudflare/.vscode/settings.json b/examples/react/start-basic-cloudflare/.vscode/settings.json deleted file mode 100644 index 00b5278e580..00000000000 --- a/examples/react/start-basic-cloudflare/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "files.watcherExclude": { - "**/routeTree.gen.ts": true - }, - "search.exclude": { - "**/routeTree.gen.ts": true - }, - "files.readonlyInclude": { - "**/routeTree.gen.ts": true - } -} diff --git a/examples/react/start-basic-cloudflare/README.md b/examples/react/start-basic-cloudflare/README.md index 711b60f2d4f..ad91c8de50a 100644 --- a/examples/react/start-basic-cloudflare/README.md +++ b/examples/react/start-basic-cloudflare/README.md @@ -1,68 +1,17 @@ -# TanStack Start - Cloudflare Example +# Deprecated: TanStack Start React Example (`start-basic-cloudflare`) -A TanStack Start example demonstrating deployment to Cloudflare Workers. +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) -- [Cloudflare Workers Documentation](https://developers.cloudflare.com/workers/) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-basic-cloudflare start-basic-cloudflare -``` +- [Start React Quick Start](https://tanstack.com/router/latest/docs/framework/react/start/quick-start) +- [Start React Hosting Guide](https://tanstack.com/router/latest/docs/framework/react/start/guide/hosting) -## Getting Started +Canonical issue reproduction baseline: -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -This starts your app in development mode, rebuilding assets on file changes. - -## Build - -To build the app for production: - -```sh -pnpm build -``` - -## Preview - -To preview the production build locally: - -```sh -pnpm preview -``` - -## Deploy to Cloudflare - -To deploy your app to Cloudflare Workers: - -```sh -pnpm run deploy -``` - -## Accessing Cloudflare Bindings - -You can access Cloudflare bindings in server functions by using importable `env`: - -```ts -import { env } from 'cloudflare:workers' -``` - -See `src/routes/index.tsx` for an example. - -## Cloudflare Configuration - -This example includes: - -- Wrangler configuration for Cloudflare Workers -- Type generation for Cloudflare bindings -- Server-side rendering on the edge -- Access to Cloudflare platform features (KV, D1, R2, etc.) +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-basic-cloudflare/package.json b/examples/react/start-basic-cloudflare/package.json deleted file mode 100644 index 8aa37cdffc7..00000000000 --- a/examples/react/start-basic-cloudflare/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "tanstack-start-example-basic-cloudflare", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "deploy": "npm run build && wrangler deploy", - "cf-typegen": "wrangler types", - "postinstall": "npm run cf-typegen" - }, - "dependencies": { - "@tanstack/react-router": "^1.161.1", - "@tanstack/react-router-devtools": "^1.161.1", - "@tanstack/react-start": "^1.161.1", - "react": "^19.0.0", - "react-dom": "^19.0.0" - }, - "devDependencies": { - "@cloudflare/vite-plugin": "^1.13.7", - "@tailwindcss/vite": "^4.1.18", - "@types/node": "^22.5.4", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.6.0", - "tailwindcss": "^4.1.18", - "typescript": "^5.7.2", - "vite": "^7.3.1", - "vite-tsconfig-paths": "^5.1.4", - "wrangler": "^4.49.1" - } -} diff --git a/examples/react/start-basic-cloudflare/public/android-chrome-192x192.png b/examples/react/start-basic-cloudflare/public/android-chrome-192x192.png deleted file mode 100644 index 09c8324f8c6..00000000000 Binary files a/examples/react/start-basic-cloudflare/public/android-chrome-192x192.png and /dev/null differ diff --git a/examples/react/start-basic-cloudflare/public/android-chrome-512x512.png b/examples/react/start-basic-cloudflare/public/android-chrome-512x512.png deleted file mode 100644 index 11d626ea3d0..00000000000 Binary files a/examples/react/start-basic-cloudflare/public/android-chrome-512x512.png and /dev/null differ diff --git a/examples/react/start-basic-cloudflare/public/apple-touch-icon.png b/examples/react/start-basic-cloudflare/public/apple-touch-icon.png deleted file mode 100644 index 5a9423cc02c..00000000000 Binary files a/examples/react/start-basic-cloudflare/public/apple-touch-icon.png and /dev/null differ diff --git a/examples/react/start-basic-cloudflare/public/favicon-16x16.png b/examples/react/start-basic-cloudflare/public/favicon-16x16.png deleted file mode 100644 index e3389b00443..00000000000 Binary files a/examples/react/start-basic-cloudflare/public/favicon-16x16.png and /dev/null differ diff --git a/examples/react/start-basic-cloudflare/public/favicon-32x32.png b/examples/react/start-basic-cloudflare/public/favicon-32x32.png deleted file mode 100644 index 900c77d444c..00000000000 Binary files a/examples/react/start-basic-cloudflare/public/favicon-32x32.png and /dev/null differ diff --git a/examples/react/start-basic-cloudflare/public/favicon.ico b/examples/react/start-basic-cloudflare/public/favicon.ico deleted file mode 100644 index 1a1751676f7..00000000000 Binary files a/examples/react/start-basic-cloudflare/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-basic-cloudflare/public/favicon.png b/examples/react/start-basic-cloudflare/public/favicon.png deleted file mode 100644 index 1e77bc06091..00000000000 Binary files a/examples/react/start-basic-cloudflare/public/favicon.png and /dev/null differ diff --git a/examples/react/start-basic-cloudflare/public/site.webmanifest b/examples/react/start-basic-cloudflare/public/site.webmanifest deleted file mode 100644 index fa99de77db6..00000000000 --- a/examples/react/start-basic-cloudflare/public/site.webmanifest +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "", - "short_name": "", - "icons": [ - { - "src": "/android-chrome-192x192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "/android-chrome-512x512.png", - "sizes": "512x512", - "type": "image/png" - } - ], - "theme_color": "#ffffff", - "background_color": "#ffffff", - "display": "standalone" -} diff --git a/examples/react/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index 260c2ea41f7..00000000000 --- a/examples/react/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { - ErrorComponent, - Link, - rootRouteId, - useMatch, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error('DefaultCatchBoundary Error:', error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/components/NotFound.tsx b/examples/react/start-basic-cloudflare/src/components/NotFound.tsx deleted file mode 100644 index fd4e75befe3..00000000000 --- a/examples/react/start-basic-cloudflare/src/components/NotFound.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: any }) { - return ( -
-
- {children ||

The page you are looking for does not exist.

} -
-

- - - Start Over - -

-
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/components/PostError.tsx b/examples/react/start-basic-cloudflare/src/components/PostError.tsx deleted file mode 100644 index 271f2d1de1f..00000000000 --- a/examples/react/start-basic-cloudflare/src/components/PostError.tsx +++ /dev/null @@ -1,6 +0,0 @@ -import { ErrorComponent } from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return -} diff --git a/examples/react/start-basic-cloudflare/src/components/UserError.tsx b/examples/react/start-basic-cloudflare/src/components/UserError.tsx deleted file mode 100644 index af5d0c6f160..00000000000 --- a/examples/react/start-basic-cloudflare/src/components/UserError.tsx +++ /dev/null @@ -1,6 +0,0 @@ -import { ErrorComponent } from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function UserErrorComponent({ error }: ErrorComponentProps) { - return -} diff --git a/examples/react/start-basic-cloudflare/src/routeTree.gen.ts b/examples/react/start-basic-cloudflare/src/routeTree.gen.ts deleted file mode 100644 index 06a64190d7f..00000000000 --- a/examples/react/start-basic-cloudflare/src/routeTree.gen.ts +++ /dev/null @@ -1,447 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' - -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ - id: '/customScript.js', - path: '/customScript.js', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '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/api/users', - path: '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/api/users', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, -} as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => ApiUsersRoute, -} as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/customScript.js': typeof CustomScriptDotjsRoute - '/deferred': typeof DeferredRoute - '/posts': typeof PostsRouteWithChildren - '/redirect': typeof RedirectRoute - '/users': typeof UsersRouteWithChildren - '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/api/users': typeof ApiUsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts/': typeof PostsIndexRoute - '/users/': typeof UsersIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/api/users/$userId': typeof ApiUsersUserIdRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/customScript.js': typeof CustomScriptDotjsRoute - '/deferred': typeof DeferredRoute - '/redirect': typeof RedirectRoute - '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/api/users': typeof ApiUsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts': typeof PostsIndexRoute - '/users': typeof UsersIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/api/users/$userId': typeof ApiUsersUserIdRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren - '/customScript.js': typeof CustomScriptDotjsRoute - '/deferred': typeof DeferredRoute - '/posts': typeof PostsRouteWithChildren - '/redirect': typeof RedirectRoute - '/users': typeof UsersRouteWithChildren - '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/_pathlessLayout/_nested-layout': typeof PathlessLayoutNestedLayoutRouteWithChildren - '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/api/users': typeof ApiUsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts/': typeof PostsIndexRoute - '/users/': typeof UsersIndexRoute - '/_pathlessLayout/_nested-layout/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/_pathlessLayout/_nested-layout/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/api/users/$userId': typeof ApiUsersUserIdRoute - '/posts_/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/customScript.js' - | '/deferred' - | '/posts' - | '/redirect' - | '/users' - | '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/api/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts/' - | '/users/' - | '/route-a' - | '/route-b' - | '/api/users/$userId' - | '/posts/$postId/deep' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/customScript.js' - | '/deferred' - | '/redirect' - | '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/api/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts' - | '/users' - | '/route-a' - | '/route-b' - | '/api/users/$userId' - | '/posts/$postId/deep' - id: - | '__root__' - | '/' - | '/_pathlessLayout' - | '/customScript.js' - | '/deferred' - | '/posts' - | '/redirect' - | '/users' - | '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/_pathlessLayout/_nested-layout' - | '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/api/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts/' - | '/users/' - | '/_pathlessLayout/_nested-layout/route-a' - | '/_pathlessLayout/_nested-layout/route-b' - | '/api/users/$userId' - | '/posts_/$postId/deep' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren - CustomScriptDotjsRoute: typeof CustomScriptDotjsRoute - DeferredRoute: typeof DeferredRoute - PostsRoute: typeof PostsRouteWithChildren - RedirectRoute: typeof RedirectRoute - UsersRoute: typeof UsersRouteWithChildren - ApiUsersRoute: typeof ApiUsersRouteWithChildren - PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/customScript.js': { - id: '/customScript.js' - path: '/customScript.js' - fullPath: '/customScript.js' - preLoaderRoute: typeof CustomScriptDotjsRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '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/api/users': { - id: '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/api/users' - path: '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/api/users' - fullPath: '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/api/users' - preLoaderRoute: typeof ApiUsersRouteImport - parentRoute: typeof rootRouteImport - } - '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/_pathlessLayout/_nested-layout': { - id: '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/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport - } - '/api/users/$userId': { - id: '/api/users/$userId' - path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute - } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - } -} - -interface PathlessLayoutNestedLayoutRouteChildren { - PathlessLayoutNestedLayoutRouteARoute: typeof PathlessLayoutNestedLayoutRouteARoute - PathlessLayoutNestedLayoutRouteBRoute: typeof PathlessLayoutNestedLayoutRouteBRoute -} - -const PathlessLayoutNestedLayoutRouteChildren: PathlessLayoutNestedLayoutRouteChildren = - { - PathlessLayoutNestedLayoutRouteARoute: - PathlessLayoutNestedLayoutRouteARoute, - PathlessLayoutNestedLayoutRouteBRoute: - PathlessLayoutNestedLayoutRouteBRoute, - } - -const PathlessLayoutNestedLayoutRouteWithChildren = - PathlessLayoutNestedLayoutRoute._addFileChildren( - PathlessLayoutNestedLayoutRouteChildren, - ) - -interface PathlessLayoutRouteChildren { - PathlessLayoutNestedLayoutRoute: typeof PathlessLayoutNestedLayoutRouteWithChildren -} - -const PathlessLayoutRouteChildren: PathlessLayoutRouteChildren = { - PathlessLayoutNestedLayoutRoute: PathlessLayoutNestedLayoutRouteWithChildren, -} - -const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( - PathlessLayoutRouteChildren, -) - -interface PostsRouteChildren { - PostsPostIdRoute: typeof PostsPostIdRoute - PostsIndexRoute: typeof PostsIndexRoute -} - -const PostsRouteChildren: PostsRouteChildren = { - PostsPostIdRoute: PostsPostIdRoute, - PostsIndexRoute: PostsIndexRoute, -} - -const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) - -interface UsersRouteChildren { - UsersUserIdRoute: typeof UsersUserIdRoute - UsersIndexRoute: typeof UsersIndexRoute -} - -const UsersRouteChildren: UsersRouteChildren = { - UsersUserIdRoute: UsersUserIdRoute, - UsersIndexRoute: UsersIndexRoute, -} - -const UsersRouteWithChildren = UsersRoute._addFileChildren(UsersRouteChildren) - -interface ApiUsersRouteChildren { - ApiUsersUserIdRoute: typeof ApiUsersUserIdRoute -} - -const ApiUsersRouteChildren: ApiUsersRouteChildren = { - ApiUsersUserIdRoute: ApiUsersUserIdRoute, -} - -const ApiUsersRouteWithChildren = ApiUsersRoute._addFileChildren( - ApiUsersRouteChildren, -) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - PathlessLayoutRoute: PathlessLayoutRouteWithChildren, - CustomScriptDotjsRoute: CustomScriptDotjsRoute, - DeferredRoute: DeferredRoute, - PostsRoute: PostsRouteWithChildren, - RedirectRoute: RedirectRoute, - UsersRoute: UsersRouteWithChildren, - ApiUsersRoute: ApiUsersRouteWithChildren, - PostsPostIdDeepRoute: PostsPostIdDeepRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' -declare module '@tanstack/react-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/examples/react/start-basic-cloudflare/src/router.tsx b/examples/react/start-basic-cloudflare/src/router.tsx deleted file mode 100644 index 1a1d8822d20..00000000000 --- a/examples/react/start-basic-cloudflare/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - const router = createRouter({ - routeTree, - defaultPreload: 'intent', - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - scrollRestoration: true, - }) - - return router -} diff --git a/examples/react/start-basic-cloudflare/src/routes/__root.tsx b/examples/react/start-basic-cloudflare/src/routes/__root.tsx deleted file mode 100644 index 346409e9d91..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/__root.tsx +++ /dev/null @@ -1,131 +0,0 @@ -/// -import { - HeadContent, - Link, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import * as React from 'react' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' -import { NotFound } from '~/components/NotFound' -import appCss from '~/styles/app.css?url' -import { seo } from '~/utils/seo' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - ...seo({ - title: - 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', - description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, - }), - ], - links: [ - { rel: 'stylesheet', href: appCss }, - { - rel: 'apple-touch-icon', - sizes: '180x180', - href: '/apple-touch-icon.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '32x32', - href: '/favicon-32x32.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '16x16', - href: '/favicon-16x16.png', - }, - { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, - { rel: 'icon', href: '/favicon.ico' }, - ], - scripts: [ - { - src: '/customScript.js', - type: 'text/javascript', - }, - ], - }), - errorComponent: DefaultCatchBoundary, - notFoundComponent: () => , - shellComponent: RootDocument, -}) - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- - Home - {' '} - - Posts - {' '} - - Users - {' '} - - Pathless Layout - {' '} - - Deferred - {' '} - - This Route Does Not Exist - -
-
- {children} - - - - - ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout.tsx b/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout.tsx deleted file mode 100644 index c3b12442b82..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout')({ - component: LayoutComponent, -}) - -function LayoutComponent() { - return ( -
-
I'm a layout
-
- -
-
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout.tsx b/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout.tsx deleted file mode 100644 index 9a48b73a468..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('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/_pathlessLayout/_nested-layout')({ - component: LayoutComponent, -}) - -function LayoutComponent() { - return ( -
-
I'm a nested layout
-
- - Go to route A - - - Go to route B - -
-
- -
-
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout/route-a.tsx b/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout/route-a.tsx deleted file mode 100644 index 426a8fe486d..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout/route-a.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-a')( - { - component: LayoutAComponent, - }, -) - -function LayoutAComponent() { - return
I'm A!
-} diff --git a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout/route-b.tsx b/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout/route-b.tsx deleted file mode 100644 index 20facf2daf6..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout/route-b.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-b')( - { - component: LayoutBComponent, - }, -) - -function LayoutBComponent() { - return
I'm B!
-} diff --git a/examples/react/start-basic-cloudflare/src/routes/api/users.$userId.ts b/examples/react/start-basic-cloudflare/src/routes/api/users.$userId.ts deleted file mode 100644 index ee34d7a1898..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/api/users.$userId.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import type { User } from '~/utils/users' - -export const Route = createFileRoute('/api/users/$userId')({ - server: { - handlers: { - GET: async ({ params, request }) => { - console.info(`Fetching users by id=${params.userId}... @`, request.url) - try { - const res = await fetch( - 'https://jsonplaceholder.typicode.com/users/' + params.userId, - ) - if (!res.ok) { - throw new Error('Failed to fetch user') - } - - const user = (await res.json()) as User - - return Response.json({ - id: user.id, - name: user.name, - email: user.email, - }) - } catch (e) { - console.error(e) - return Response.json({ error: 'User not found' }, { status: 404 }) - } - }, - }, - }, -}) diff --git a/examples/react/start-basic-cloudflare/src/routes/api/users.ts b/examples/react/start-basic-cloudflare/src/routes/api/users.ts deleted file mode 100644 index 4cecd018525..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/api/users.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { getRequestHeaders } from '@tanstack/react-start/server' -import { createMiddleware } from '@tanstack/react-start' -import type { User } from '~/utils/users' - -const userLoggerMiddleware = createMiddleware().server(async ({ next }) => { - console.info('In: /users') - console.info('Request Headers:', getRequestHeaders()) - const result = await next() - result.response.headers.set('x-users', 'true') - console.info('Out: /users') - return result -}) - -const testParentMiddleware = createMiddleware().server(async ({ next }) => { - console.info('In: testParentMiddleware') - const result = await next() - result.response.headers.set('x-test-parent', 'true') - console.info('Out: testParentMiddleware') - return result -}) - -const testMiddleware = createMiddleware() - .middleware([testParentMiddleware]) - .server(async ({ next }) => { - console.info('In: testMiddleware') - const result = await next() - result.response.headers.set('x-test', 'true') - - // if (Math.random() > 0.5) { - // throw new Response(null, { - // status: 302, - // headers: { Location: 'https://www.google.com' }, - // }) - // } - - console.info('Out: testMiddleware') - return result - }) - -export const Route = createFileRoute('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/api/users')({ - server: { - middleware: [testMiddleware, userLoggerMiddleware], - handlers: { - GET: async ({ request }) => { - console.info('GET /api/users @', request.url) - console.info('Fetching users... @', request.url) - const res = await fetch('https://jsonplaceholder.typicode.com/users') - if (!res.ok) { - throw new Error('Failed to fetch users') - } - - const data = (await res.json()) as Array - - const list = data.slice(0, 10) - - return Response.json( - list.map((u) => ({ id: u.id, name: u.name, email: u.email })), - ) - }, - }, - }, -}) diff --git a/examples/react/start-basic-cloudflare/src/routes/customScript[.]js.ts b/examples/react/start-basic-cloudflare/src/routes/customScript[.]js.ts deleted file mode 100644 index 811471ac153..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/customScript[.]js.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/customScript.js')({ - server: { - handlers: { - GET: () => { - return new Response('console.log("Hello from customScript.js!")', { - headers: { - 'Content-Type': 'application/javascript', - }, - }) - }, - }, - }, -}) diff --git a/examples/react/start-basic-cloudflare/src/routes/deferred.tsx b/examples/react/start-basic-cloudflare/src/routes/deferred.tsx deleted file mode 100644 index c38808243e1..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/deferred.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { Suspense, useState } from 'react' - -const personServerFn = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) - .handler(({ data: name }) => { - return { name, randomNumber: Math.floor(Math.random() * 100) } - }) - -const slowServerFn = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) - .handler(async ({ data: name }) => { - await new Promise((r) => setTimeout(r, 1000)) - return { name, randomNumber: Math.floor(Math.random() * 100) } - }) - -export const Route = createFileRoute('/deferred')({ - loader: async () => { - return { - deferredStuff: new Promise((r) => - setTimeout(() => r('Hello deferred!'), 2000), - ), - deferredPerson: slowServerFn({ data: 'Tanner Linsley' }), - person: await personServerFn({ data: 'John Doe' }), - } - }, - component: Deferred, -}) - -function Deferred() { - const [count, setCount] = useState(0) - const { deferredStuff, deferredPerson, person } = Route.useLoaderData() - - return ( -
-
- {person.name} - {person.randomNumber} -
- Loading person...
}> - ( -
- {data.name} - {data.randomNumber} -
- )} - /> - - Loading stuff...}> -

{data}

} - /> -
-
Count: {count}
-
- -
- - ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/index.tsx b/examples/react/start-basic-cloudflare/src/routes/index.tsx deleted file mode 100644 index 44c66fe6682..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/index.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { env } from 'cloudflare:workers' - -export const Route = createFileRoute('/')({ - loader: () => getData(), - component: Home, -}) - -const getData = createServerFn().handler(() => { - return { - message: `Running in ${navigator.userAgent}`, - myVar: env.MY_VAR, - } -}) - -function Home() { - const data = Route.useLoaderData() - - return ( -
-

Welcome Home!!!

-

{data.message}

-

{data.myVar}

-
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/posts.$postId.tsx b/examples/react/start-basic-cloudflare/src/routes/posts.$postId.tsx deleted file mode 100644 index 7e111fa20d6..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/posts.$postId.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { fetchPost } from '~/utils/posts' -import { NotFound } from '~/components/NotFound' -import { PostErrorComponent } from '~/components/PostError' - -export const Route = createFileRoute('/posts/$postId')({ - loader: ({ params: { postId } }) => fetchPost({ data: postId }), - errorComponent: PostErrorComponent, - component: PostComponent, - notFoundComponent: () => { - return Post not found - }, -}) - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.title}

-
{post.body}
- - Deep View - -
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/posts.index.tsx b/examples/react/start-basic-cloudflare/src/routes/posts.index.tsx deleted file mode 100644 index 5b5f08f95bf..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/posts.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/posts/')({ - component: PostsIndexComponent, -}) - -function PostsIndexComponent() { - return
Select a post.
-} diff --git a/examples/react/start-basic-cloudflare/src/routes/posts.tsx b/examples/react/start-basic-cloudflare/src/routes/posts.tsx deleted file mode 100644 index 095b2e248fe..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/posts.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '~/utils/posts' - -export const Route = createFileRoute('/posts')({ - loader: async () => fetchPosts(), - component: PostsComponent, -}) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( - (post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - }, - )} -
-
- -
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/posts_.$postId.deep.tsx b/examples/react/start-basic-cloudflare/src/routes/posts_.$postId.deep.tsx deleted file mode 100644 index 48d317ec30e..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/posts_.$postId.deep.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { fetchPost } from '~/utils/posts' -import { PostErrorComponent } from '~/components/PostError' - -export const Route = createFileRoute('/posts_/$postId/deep')({ - loader: async ({ params: { postId } }) => - fetchPost({ - data: postId, - }), - errorComponent: PostErrorComponent, - component: PostDeepComponent, -}) - -function PostDeepComponent() { - const post = Route.useLoaderData() - - return ( -
- - ← All Posts - -

{post.title}

-
{post.body}
-
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/redirect.tsx b/examples/react/start-basic-cloudflare/src/routes/redirect.tsx deleted file mode 100644 index ea34b6e4205..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/redirect.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' - -export const Route = createFileRoute('/redirect')({ - beforeLoad: () => { - throw redirect({ - to: '/posts', - }) - }, -}) diff --git a/examples/react/start-basic-cloudflare/src/routes/users.$userId.tsx b/examples/react/start-basic-cloudflare/src/routes/users.$userId.tsx deleted file mode 100644 index 212e83d8fe8..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/users.$userId.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { NotFound } from 'src/components/NotFound' -import { UserErrorComponent } from 'src/components/UserError' -import type { User } from '~/utils/users' - -export const Route = createFileRoute('/users/$userId')({ - loader: async ({ params: { userId } }) => { - try { - const res = await fetch('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/api/users/' + userId) - if (!res.ok) { - throw new Error('Unexpected status code') - } - - const data = await res.json() - - return data as User - } catch { - throw new Error('Failed to fetch user') - } - }, - errorComponent: UserErrorComponent, - component: UserComponent, - notFoundComponent: () => { - return User not found - }, -}) - -function UserComponent() { - const user = Route.useLoaderData() - - return ( -
-

{user.name}

-
{user.email}
- -
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/users.index.tsx b/examples/react/start-basic-cloudflare/src/routes/users.index.tsx deleted file mode 100644 index 27d136987ee..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/users.index.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/users/')({ - component: UsersIndexComponent, -}) - -function UsersIndexComponent() { - return ( -
- Select a user or{' '} - - view as JSON - -
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/users.tsx b/examples/react/start-basic-cloudflare/src/routes/users.tsx deleted file mode 100644 index 55b22b6e408..00000000000 --- a/examples/react/start-basic-cloudflare/src/routes/users.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import type { User } from '~/utils/users' - -export const Route = createFileRoute('/users')({ - loader: async () => { - const res = await fetch('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/api/users') - - if (!res.ok) { - throw new Error('Unexpected status code') - } - - const data = await res.json() - - return data as Array - }, - component: UsersComponent, -}) - -function UsersComponent() { - const users = Route.useLoaderData() - - return ( -
-
    - {[ - ...users, - { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, - ].map((user) => { - return ( -
  • - -
    {user.name}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/styles/app.css b/examples/react/start-basic-cloudflare/src/styles/app.css deleted file mode 100644 index 37c1f5a6e2d..00000000000 --- a/examples/react/start-basic-cloudflare/src/styles/app.css +++ /dev/null @@ -1,30 +0,0 @@ -@import 'tailwindcss' source('../'); - -@layer base { - *, - ::after, - ::before, - ::backdrop, - ::file-selector-button { - border-color: var(--color-gray-200, currentcolor); - } -} - -@layer base { - html { - color-scheme: light dark; - } - - * { - @apply border-gray-200 dark:border-gray-800; - } - - html, - body { - @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; - } - - .using-mouse * { - outline: none !important; - } -} diff --git a/examples/react/start-basic-cloudflare/src/utils/loggingMiddleware.tsx b/examples/react/start-basic-cloudflare/src/utils/loggingMiddleware.tsx deleted file mode 100644 index 3ea9a06439f..00000000000 --- a/examples/react/start-basic-cloudflare/src/utils/loggingMiddleware.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start' - -const preLogMiddleware = createMiddleware({ type: 'function' }) - .client(async (ctx) => { - const clientTime = new Date() - - return ctx.next({ - context: { - clientTime, - }, - sendContext: { - clientTime, - }, - }) - }) - .server(async (ctx) => { - const serverTime = new Date() - - return ctx.next({ - sendContext: { - serverTime, - durationToServer: - serverTime.getTime() - ctx.context.clientTime.getTime(), - }, - }) - }) - -export const logMiddleware = createMiddleware({ type: 'function' }) - .middleware([preLogMiddleware]) - .client(async (ctx) => { - const res = await ctx.next() - - const now = new Date() - console.log('Client Req/Res:', { - duration: now.getTime() - res.context.clientTime.getTime(), - durationToServer: res.context.durationToServer, - durationFromServer: now.getTime() - res.context.serverTime.getTime(), - }) - - return res - }) diff --git a/examples/react/start-basic-cloudflare/src/utils/posts.tsx b/examples/react/start-basic-cloudflare/src/utils/posts.tsx deleted file mode 100644 index 098542fd745..00000000000 --- a/examples/react/start-basic-cloudflare/src/utils/posts.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { notFound } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' - -export type PostType = { - id: number - title: string - body: string -} - -export const fetchPost = createServerFn({ method: 'POST' }) - .inputValidator((d: string) => d) - .handler(async ({ data }) => { - console.info(`Fetching post with id ${data}...`) - const res = await fetch( - `https://jsonplaceholder.typicode.com/posts/${data}`, - ) - if (!res.ok) { - if (res.status === 404) { - throw notFound() - } - - throw new Error('Failed to fetch post') - } - - const post = await res.json() - - return post as PostType - }) - -export const fetchPosts = createServerFn().handler(async () => { - console.info('Fetching posts...') - const res = await fetch('https://jsonplaceholder.typicode.com/posts') - if (!res.ok) { - throw new Error('Failed to fetch posts') - } - - const posts = await res.json() - - return (posts as Array).slice(0, 10) -}) diff --git a/examples/react/start-basic-cloudflare/src/utils/seo.ts b/examples/react/start-basic-cloudflare/src/utils/seo.ts deleted file mode 100644 index d18ad84b74e..00000000000 --- a/examples/react/start-basic-cloudflare/src/utils/seo.ts +++ /dev/null @@ -1,33 +0,0 @@ -export const seo = ({ - title, - description, - keywords, - image, -}: { - title: string - description?: string - image?: string - keywords?: string -}) => { - const tags = [ - { title }, - { name: 'description', content: description }, - { name: 'keywords', content: keywords }, - { name: 'twitter:title', content: title }, - { name: 'twitter:description', content: description }, - { name: 'twitter:creator', content: '@tannerlinsley' }, - { name: 'twitter:site', content: '@tannerlinsley' }, - { name: 'og:type', content: 'website' }, - { name: 'og:title', content: title }, - { name: 'og:description', content: description }, - ...(image - ? [ - { name: 'twitter:image', content: image }, - { name: 'twitter:card', content: 'summary_large_image' }, - { name: 'og:image', content: image }, - ] - : []), - ] - - return tags -} diff --git a/examples/react/start-basic-cloudflare/src/utils/users.tsx b/examples/react/start-basic-cloudflare/src/utils/users.tsx deleted file mode 100644 index 7ba645b3831..00000000000 --- a/examples/react/start-basic-cloudflare/src/utils/users.tsx +++ /dev/null @@ -1,5 +0,0 @@ -export type User = { - id: number - name: string - email: string -} diff --git a/examples/react/start-basic-cloudflare/tsconfig.json b/examples/react/start-basic-cloudflare/tsconfig.json deleted file mode 100644 index 3a9fb7cd716..00000000000 --- a/examples/react/start-basic-cloudflare/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "baseUrl": ".", - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/examples/react/start-basic-cloudflare/vite.config.ts b/examples/react/start-basic-cloudflare/vite.config.ts deleted file mode 100644 index 93f3950880b..00000000000 --- a/examples/react/start-basic-cloudflare/vite.config.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' -import { cloudflare } from '@cloudflare/vite-plugin' -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import viteReact from '@vitejs/plugin-react' -import tailwindcss from '@tailwindcss/vite' - -export default defineConfig({ - server: { - port: 3000, - }, - plugins: [ - tailwindcss(), - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - cloudflare({ viteEnvironment: { name: 'ssr' } }), - tanstackStart(), - viteReact(), - ], -}) diff --git a/examples/react/start-basic-cloudflare/worker-configuration.d.ts b/examples/react/start-basic-cloudflare/worker-configuration.d.ts deleted file mode 100644 index bdfccc2017f..00000000000 --- a/examples/react/start-basic-cloudflare/worker-configuration.d.ts +++ /dev/null @@ -1,9101 +0,0 @@ -/* eslint-disable */ -// Generated by Wrangler by running `wrangler types` (hash: b11df627d8b3c51b1bf3230a546b0f20) -// Runtime types generated with workerd@1.20251118.0 2025-09-24 nodejs_compat -declare namespace Cloudflare { - interface Env { - MY_VAR: "Hello from Cloudflare"; - } -} -interface Env extends Cloudflare.Env {} -type StringifyValues> = { - [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; -}; -declare namespace NodeJS { - interface ProcessEnv extends StringifyValues> {} -} - -// Begin runtime types -/*! ***************************************************************************** -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. -***************************************************************************** */ -/* eslint-disable */ -// noinspection JSUnusedGlobalSymbols -declare var onmessage: never; -/** - * The **`DOMException`** interface represents an abnormal event (called an **exception**) that occurs as a result of calling a method or accessing a property of a web API. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) - */ -declare class DOMException extends Error { - constructor(message?: string, name?: string); - /** - * The **`message`** read-only property of the a message or description associated with the given error name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) - */ - readonly message: string; - /** - * The **`name`** read-only property of the one of the strings associated with an error name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) - */ - readonly name: string; - /** - * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) - */ - readonly code: number; - static readonly INDEX_SIZE_ERR: number; - static readonly DOMSTRING_SIZE_ERR: number; - static readonly HIERARCHY_REQUEST_ERR: number; - static readonly WRONG_DOCUMENT_ERR: number; - static readonly INVALID_CHARACTER_ERR: number; - static readonly NO_DATA_ALLOWED_ERR: number; - static readonly NO_MODIFICATION_ALLOWED_ERR: number; - static readonly NOT_FOUND_ERR: number; - static readonly NOT_SUPPORTED_ERR: number; - static readonly INUSE_ATTRIBUTE_ERR: number; - static readonly INVALID_STATE_ERR: number; - static readonly SYNTAX_ERR: number; - static readonly INVALID_MODIFICATION_ERR: number; - static readonly NAMESPACE_ERR: number; - static readonly INVALID_ACCESS_ERR: number; - static readonly VALIDATION_ERR: number; - static readonly TYPE_MISMATCH_ERR: number; - static readonly SECURITY_ERR: number; - static readonly NETWORK_ERR: number; - static readonly ABORT_ERR: number; - static readonly URL_MISMATCH_ERR: number; - static readonly QUOTA_EXCEEDED_ERR: number; - static readonly TIMEOUT_ERR: number; - static readonly INVALID_NODE_TYPE_ERR: number; - static readonly DATA_CLONE_ERR: number; - get stack(): any; - set stack(value: any); -} -type WorkerGlobalScopeEventMap = { - fetch: FetchEvent; - scheduled: ScheduledEvent; - queue: QueueEvent; - unhandledrejection: PromiseRejectionEvent; - rejectionhandled: PromiseRejectionEvent; -}; -declare abstract class WorkerGlobalScope extends EventTarget { - EventTarget: typeof EventTarget; -} -/* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). * - * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) - */ -interface Console { - "assert"(condition?: boolean, ...data: any[]): void; - /** - * The **`console.clear()`** static method clears the console if possible. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) - */ - clear(): void; - /** - * The **`console.count()`** static method logs the number of times that this particular call to `count()` has been called. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) - */ - count(label?: string): void; - /** - * The **`console.countReset()`** static method resets counter used with console/count_static. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) - */ - countReset(label?: string): void; - /** - * The **`console.debug()`** static method outputs a message to the console at the 'debug' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) - */ - debug(...data: any[]): void; - /** - * The **`console.dir()`** static method displays a list of the properties of the specified JavaScript object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) - */ - dir(item?: any, options?: any): void; - /** - * The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) - */ - dirxml(...data: any[]): void; - /** - * The **`console.error()`** static method outputs a message to the console at the 'error' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) - */ - error(...data: any[]): void; - /** - * The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console/groupEnd_static is called. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) - */ - group(...data: any[]): void; - /** - * The **`console.groupCollapsed()`** static method creates a new inline group in the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) - */ - groupCollapsed(...data: any[]): void; - /** - * The **`console.groupEnd()`** static method exits the current inline group in the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) - */ - groupEnd(): void; - /** - * The **`console.info()`** static method outputs a message to the console at the 'info' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) - */ - info(...data: any[]): void; - /** - * The **`console.log()`** static method outputs a message to the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) - */ - log(...data: any[]): void; - /** - * The **`console.table()`** static method displays tabular data as a table. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) - */ - table(tabularData?: any, properties?: string[]): void; - /** - * The **`console.time()`** static method starts a timer you can use to track how long an operation takes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) - */ - time(label?: string): void; - /** - * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console/time_static. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) - */ - timeEnd(label?: string): void; - /** - * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console/time_static. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) - */ - timeLog(label?: string, ...data: any[]): void; - timeStamp(label?: string): void; - /** - * The **`console.trace()`** static method outputs a stack trace to the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) - */ - trace(...data: any[]): void; - /** - * The **`console.warn()`** static method outputs a warning message to the console at the 'warning' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) - */ - warn(...data: any[]): void; -} -declare const console: Console; -type BufferSource = ArrayBufferView | ArrayBuffer; -type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; -declare namespace WebAssembly { - class CompileError extends Error { - constructor(message?: string); - } - class RuntimeError extends Error { - constructor(message?: string); - } - type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128"; - interface GlobalDescriptor { - value: ValueType; - mutable?: boolean; - } - class Global { - constructor(descriptor: GlobalDescriptor, value?: any); - value: any; - valueOf(): any; - } - type ImportValue = ExportValue | number; - type ModuleImports = Record; - type Imports = Record; - type ExportValue = Function | Global | Memory | Table; - type Exports = Record; - class Instance { - constructor(module: Module, imports?: Imports); - readonly exports: Exports; - } - interface MemoryDescriptor { - initial: number; - maximum?: number; - shared?: boolean; - } - class Memory { - constructor(descriptor: MemoryDescriptor); - readonly buffer: ArrayBuffer; - grow(delta: number): number; - } - type ImportExportKind = "function" | "global" | "memory" | "table"; - interface ModuleExportDescriptor { - kind: ImportExportKind; - name: string; - } - interface ModuleImportDescriptor { - kind: ImportExportKind; - module: string; - name: string; - } - abstract class Module { - static customSections(module: Module, sectionName: string): ArrayBuffer[]; - static exports(module: Module): ModuleExportDescriptor[]; - static imports(module: Module): ModuleImportDescriptor[]; - } - type TableKind = "anyfunc" | "externref"; - interface TableDescriptor { - element: TableKind; - initial: number; - maximum?: number; - } - class Table { - constructor(descriptor: TableDescriptor, value?: any); - readonly length: number; - get(index: number): any; - grow(delta: number, value?: any): number; - set(index: number, value?: any): void; - } - function instantiate(module: Module, imports?: Imports): Promise; - function validate(bytes: BufferSource): boolean; -} -/** - * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) - */ -interface ServiceWorkerGlobalScope extends WorkerGlobalScope { - DOMException: typeof DOMException; - WorkerGlobalScope: typeof WorkerGlobalScope; - btoa(data: string): string; - atob(data: string): string; - setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; - setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearTimeout(timeoutId: number | null): void; - setInterval(callback: (...args: any[]) => void, msDelay?: number): number; - setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearInterval(timeoutId: number | null): void; - queueMicrotask(task: Function): void; - structuredClone(value: T, options?: StructuredSerializeOptions): T; - reportError(error: any): void; - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - self: ServiceWorkerGlobalScope; - crypto: Crypto; - caches: CacheStorage; - scheduler: Scheduler; - performance: Performance; - Cloudflare: Cloudflare; - readonly origin: string; - Event: typeof Event; - ExtendableEvent: typeof ExtendableEvent; - CustomEvent: typeof CustomEvent; - PromiseRejectionEvent: typeof PromiseRejectionEvent; - FetchEvent: typeof FetchEvent; - TailEvent: typeof TailEvent; - TraceEvent: typeof TailEvent; - ScheduledEvent: typeof ScheduledEvent; - MessageEvent: typeof MessageEvent; - CloseEvent: typeof CloseEvent; - ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; - ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; - ReadableStream: typeof ReadableStream; - WritableStream: typeof WritableStream; - WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; - TransformStream: typeof TransformStream; - ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; - CountQueuingStrategy: typeof CountQueuingStrategy; - ErrorEvent: typeof ErrorEvent; - MessageChannel: typeof MessageChannel; - MessagePort: typeof MessagePort; - EventSource: typeof EventSource; - ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; - ReadableStreamDefaultController: typeof ReadableStreamDefaultController; - ReadableByteStreamController: typeof ReadableByteStreamController; - WritableStreamDefaultController: typeof WritableStreamDefaultController; - TransformStreamDefaultController: typeof TransformStreamDefaultController; - CompressionStream: typeof CompressionStream; - DecompressionStream: typeof DecompressionStream; - TextEncoderStream: typeof TextEncoderStream; - TextDecoderStream: typeof TextDecoderStream; - Headers: typeof Headers; - Body: typeof Body; - Request: typeof Request; - Response: typeof Response; - WebSocket: typeof WebSocket; - WebSocketPair: typeof WebSocketPair; - WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; - AbortController: typeof AbortController; - AbortSignal: typeof AbortSignal; - TextDecoder: typeof TextDecoder; - TextEncoder: typeof TextEncoder; - navigator: Navigator; - Navigator: typeof Navigator; - URL: typeof URL; - URLSearchParams: typeof URLSearchParams; - URLPattern: typeof URLPattern; - Blob: typeof Blob; - File: typeof File; - FormData: typeof FormData; - Crypto: typeof Crypto; - SubtleCrypto: typeof SubtleCrypto; - CryptoKey: typeof CryptoKey; - CacheStorage: typeof CacheStorage; - Cache: typeof Cache; - FixedLengthStream: typeof FixedLengthStream; - IdentityTransformStream: typeof IdentityTransformStream; - HTMLRewriter: typeof HTMLRewriter; -} -declare function addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; -declare function removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; -/** - * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) - */ -declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */ -declare function btoa(data: string): string; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */ -declare function atob(data: string): string; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ -declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ -declare function setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */ -declare function clearTimeout(timeoutId: number | null): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ -declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ -declare function setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */ -declare function clearInterval(timeoutId: number | null): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ -declare function queueMicrotask(task: Function): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ -declare function structuredClone(value: T, options?: StructuredSerializeOptions): T; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ -declare function reportError(error: any): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ -declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; -declare const self: ServiceWorkerGlobalScope; -/** -* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. -* The Workers runtime implements the full surface of this API, but with some differences in -* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) -* compared to those implemented in most browsers. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) -*/ -declare const crypto: Crypto; -/** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ -declare const caches: CacheStorage; -declare const scheduler: Scheduler; -/** -* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, -* as well as timing of subrequests and other operations. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) -*/ -declare const performance: Performance; -declare const Cloudflare: Cloudflare; -declare const origin: string; -declare const navigator: Navigator; -interface TestController { -} -interface ExecutionContext { - waitUntil(promise: Promise): void; - passThroughOnException(): void; - readonly props: Props; -} -type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; -type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; -type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; -interface ExportedHandler { - fetch?: ExportedHandlerFetchHandler; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; -} -interface StructuredSerializeOptions { - transfer?: any[]; -} -declare abstract class Navigator { - sendBeacon(url: string, body?: BodyInit): boolean; - readonly userAgent: string; - readonly hardwareConcurrency: number; - readonly language: string; - readonly languages: string[]; -} -interface AlarmInvocationInfo { - readonly isRetry: boolean; - readonly retryCount: number; -} -interface Cloudflare { - readonly compatibilityFlags: Record; -} -interface DurableObject { - fetch(request: Request): Response | Promise; - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; -} -type DurableObjectStub = Fetcher & { - readonly id: DurableObjectId; - readonly name?: string; -}; -interface DurableObjectId { - toString(): string; - equals(other: DurableObjectId): boolean; - readonly name?: string; -} -declare abstract class DurableObjectNamespace { - newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; - idFromName(name: string): DurableObjectId; - idFromString(id: string): DurableObjectId; - get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; -} -type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high"; -interface DurableObjectNamespaceNewUniqueIdOptions { - jurisdiction?: DurableObjectJurisdiction; -} -type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; -interface DurableObjectNamespaceGetDurableObjectOptions { - locationHint?: DurableObjectLocationHint; -} -interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { -} -interface DurableObjectState { - waitUntil(promise: Promise): void; - readonly props: Props; - readonly id: DurableObjectId; - readonly storage: DurableObjectStorage; - container?: Container; - blockConcurrencyWhile(callback: () => Promise): Promise; - acceptWebSocket(ws: WebSocket, tags?: string[]): void; - getWebSockets(tag?: string): WebSocket[]; - setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; - getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; - getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; - setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; - getHibernatableWebSocketEventTimeout(): number | null; - getTags(ws: WebSocket): string[]; - abort(reason?: string): void; -} -interface DurableObjectTransaction { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - rollback(): void; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; -} -interface DurableObjectStorage { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - deleteAll(options?: DurableObjectPutOptions): Promise; - transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; - sync(): Promise; - sql: SqlStorage; - kv: SyncKvStorage; - transactionSync(closure: () => T): T; - getCurrentBookmark(): Promise; - getBookmarkForTime(timestamp: number | Date): Promise; - onNextSessionRestoreBookmark(bookmark: string): Promise; -} -interface DurableObjectListOptions { - start?: string; - startAfter?: string; - end?: string; - prefix?: string; - reverse?: boolean; - limit?: number; - allowConcurrency?: boolean; - noCache?: boolean; -} -interface DurableObjectGetOptions { - allowConcurrency?: boolean; - noCache?: boolean; -} -interface DurableObjectGetAlarmOptions { - allowConcurrency?: boolean; -} -interface DurableObjectPutOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; - noCache?: boolean; -} -interface DurableObjectSetAlarmOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; -} -declare class WebSocketRequestResponsePair { - constructor(request: string, response: string); - get request(): string; - get response(): string; -} -interface AnalyticsEngineDataset { - writeDataPoint(event?: AnalyticsEngineDataPoint): void; -} -interface AnalyticsEngineDataPoint { - indexes?: ((ArrayBuffer | string) | null)[]; - doubles?: number[]; - blobs?: ((ArrayBuffer | string) | null)[]; -} -/** - * The **`Event`** interface represents an event which takes place on an `EventTarget`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) - */ -declare class Event { - constructor(type: string, init?: EventInit); - /** - * The **`type`** read-only property of the Event interface returns a string containing the event's type. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) - */ - get type(): string; - /** - * The **`eventPhase`** read-only property of the being evaluated. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) - */ - get eventPhase(): number; - /** - * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) - */ - get composed(): boolean; - /** - * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) - */ - get bubbles(): boolean; - /** - * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) - */ - get cancelable(): boolean; - /** - * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) - */ - get defaultPrevented(): boolean; - /** - * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) - */ - get returnValue(): boolean; - /** - * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) - */ - get currentTarget(): EventTarget | undefined; - /** - * The read-only **`target`** property of the dispatched. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) - */ - get target(): EventTarget | undefined; - /** - * The deprecated **`Event.srcElement`** is an alias for the Event.target property. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) - */ - get srcElement(): EventTarget | undefined; - /** - * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) - */ - get timeStamp(): number; - /** - * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) - */ - get isTrusted(): boolean; - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - get cancelBubble(): boolean; - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - set cancelBubble(value: boolean); - /** - * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) - */ - stopImmediatePropagation(): void; - /** - * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) - */ - preventDefault(): void; - /** - * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) - */ - stopPropagation(): void; - /** - * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) - */ - composedPath(): EventTarget[]; - static readonly NONE: number; - static readonly CAPTURING_PHASE: number; - static readonly AT_TARGET: number; - static readonly BUBBLING_PHASE: number; -} -interface EventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; -} -type EventListener = (event: EventType) => void; -interface EventListenerObject { - handleEvent(event: EventType): void; -} -type EventListenerOrEventListenerObject = EventListener | EventListenerObject; -/** - * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) - */ -declare class EventTarget = Record> { - constructor(); - /** - * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) - */ - addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; - /** - * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) - */ - removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; - /** - * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) - */ - dispatchEvent(event: EventMap[keyof EventMap]): boolean; -} -interface EventTargetEventListenerOptions { - capture?: boolean; -} -interface EventTargetAddEventListenerOptions { - capture?: boolean; - passive?: boolean; - once?: boolean; - signal?: AbortSignal; -} -interface EventTargetHandlerObject { - handleEvent: (event: Event) => any | undefined; -} -/** - * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) - */ -declare class AbortController { - constructor(); - /** - * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) - */ - get signal(): AbortSignal; - /** - * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) - */ - abort(reason?: any): void; -} -/** - * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) - */ -declare abstract class AbortSignal extends EventTarget { - /** - * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) - */ - static abort(reason?: any): AbortSignal; - /** - * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) - */ - static timeout(delay: number): AbortSignal; - /** - * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) - */ - static any(signals: AbortSignal[]): AbortSignal; - /** - * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) - */ - get aborted(): boolean; - /** - * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) - */ - get reason(): any; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ - get onabort(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ - set onabort(value: any | null); - /** - * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) - */ - throwIfAborted(): void; -} -interface Scheduler { - wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; -} -interface SchedulerWaitOptions { - signal?: AbortSignal; -} -/** - * The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) - */ -declare abstract class ExtendableEvent extends Event { - /** - * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) - */ - waitUntil(promise: Promise): void; -} -/** - * The **`CustomEvent`** interface represents events initialized by an application for any purpose. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) - */ -declare class CustomEvent extends Event { - constructor(type: string, init?: CustomEventCustomEventInit); - /** - * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) - */ - get detail(): T; -} -interface CustomEventCustomEventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; - detail?: any; -} -/** - * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) - */ -declare class Blob { - constructor(type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions); - /** - * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) - */ - get size(): number; - /** - * The **`type`** read-only property of the Blob interface returns the MIME type of the file. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) - */ - get type(): string; - /** - * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) - */ - slice(start?: number, end?: number, type?: string): Blob; - /** - * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) - */ - arrayBuffer(): Promise; - /** - * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) - */ - bytes(): Promise; - /** - * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) - */ - text(): Promise; - /** - * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) - */ - stream(): ReadableStream; -} -interface BlobOptions { - type?: string; -} -/** - * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) - */ -declare class File extends Blob { - constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions); - /** - * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) - */ - get name(): string; - /** - * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) - */ - get lastModified(): number; -} -interface FileOptions { - type?: string; - lastModified?: number; -} -/** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ -declare abstract class CacheStorage { - /** - * The **`open()`** method of the the Cache object matching the `cacheName`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) - */ - open(cacheName: string): Promise; - readonly default: Cache; -} -/** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ -declare abstract class Cache { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ - delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ - match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ - put(request: RequestInfo | URL, response: Response): Promise; -} -interface CacheQueryOptions { - ignoreMethod?: boolean; -} -/** -* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. -* The Workers runtime implements the full surface of this API, but with some differences in -* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) -* compared to those implemented in most browsers. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) -*/ -declare abstract class Crypto { - /** - * The **`Crypto.subtle`** read-only property returns a cryptographic operations. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) - */ - get subtle(): SubtleCrypto; - /** - * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) - */ - getRandomValues(buffer: T): T; - /** - * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) - */ - randomUUID(): string; - DigestStream: typeof DigestStream; -} -/** - * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) - */ -declare abstract class SubtleCrypto { - /** - * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) - */ - encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) - */ - decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) - */ - sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) - */ - verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) - */ - digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) - */ - generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) - */ - deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * The **`deriveBits()`** method of the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) - */ - deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise; - /** - * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) - */ - importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) - */ - exportKey(format: string, key: CryptoKey): Promise; - /** - * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) - */ - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise; - /** - * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) - */ - unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; -} -/** - * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.unwrapKey. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) - */ -declare abstract class CryptoKey { - /** - * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) - */ - readonly type: string; - /** - * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) - */ - readonly extractable: boolean; - /** - * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) - */ - readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm; - /** - * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) - */ - readonly usages: string[]; -} -interface CryptoKeyPair { - publicKey: CryptoKey; - privateKey: CryptoKey; -} -interface JsonWebKey { - kty: string; - use?: string; - key_ops?: string[]; - alg?: string; - ext?: boolean; - crv?: string; - x?: string; - y?: string; - d?: string; - n?: string; - e?: string; - p?: string; - q?: string; - dp?: string; - dq?: string; - qi?: string; - oth?: RsaOtherPrimesInfo[]; - k?: string; -} -interface RsaOtherPrimesInfo { - r?: string; - d?: string; - t?: string; -} -interface SubtleCryptoDeriveKeyAlgorithm { - name: string; - salt?: (ArrayBuffer | ArrayBufferView); - iterations?: number; - hash?: (string | SubtleCryptoHashAlgorithm); - $public?: CryptoKey; - info?: (ArrayBuffer | ArrayBufferView); -} -interface SubtleCryptoEncryptAlgorithm { - name: string; - iv?: (ArrayBuffer | ArrayBufferView); - additionalData?: (ArrayBuffer | ArrayBufferView); - tagLength?: number; - counter?: (ArrayBuffer | ArrayBufferView); - length?: number; - label?: (ArrayBuffer | ArrayBufferView); -} -interface SubtleCryptoGenerateKeyAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - modulusLength?: number; - publicExponent?: (ArrayBuffer | ArrayBufferView); - length?: number; - namedCurve?: string; -} -interface SubtleCryptoHashAlgorithm { - name: string; -} -interface SubtleCryptoImportKeyAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - length?: number; - namedCurve?: string; - compressed?: boolean; -} -interface SubtleCryptoSignAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - dataLength?: number; - saltLength?: number; -} -interface CryptoKeyKeyAlgorithm { - name: string; -} -interface CryptoKeyAesKeyAlgorithm { - name: string; - length: number; -} -interface CryptoKeyHmacKeyAlgorithm { - name: string; - hash: CryptoKeyKeyAlgorithm; - length: number; -} -interface CryptoKeyRsaKeyAlgorithm { - name: string; - modulusLength: number; - publicExponent: ArrayBuffer | ArrayBufferView; - hash?: CryptoKeyKeyAlgorithm; -} -interface CryptoKeyEllipticKeyAlgorithm { - name: string; - namedCurve: string; -} -interface CryptoKeyArbitraryKeyAlgorithm { - name: string; - hash?: CryptoKeyKeyAlgorithm; - namedCurve?: string; - length?: number; -} -declare class DigestStream extends WritableStream { - constructor(algorithm: string | SubtleCryptoHashAlgorithm); - readonly digest: Promise; - get bytesWritten(): number | bigint; -} -/** - * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) - */ -declare class TextDecoder { - constructor(label?: string, options?: TextDecoderConstructorOptions); - /** - * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) - */ - decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string; - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; -} -/** - * The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) - */ -declare class TextEncoder { - constructor(); - /** - * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) - */ - encode(input?: string): Uint8Array; - /** - * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) - */ - encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult; - get encoding(): string; -} -interface TextDecoderConstructorOptions { - fatal: boolean; - ignoreBOM: boolean; -} -interface TextDecoderDecodeOptions { - stream: boolean; -} -interface TextEncoderEncodeIntoResult { - read: number; - written: number; -} -/** - * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) - */ -declare class ErrorEvent extends Event { - constructor(type: string, init?: ErrorEventErrorEventInit); - /** - * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) - */ - get filename(): string; - /** - * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) - */ - get message(): string; - /** - * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) - */ - get lineno(): number; - /** - * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) - */ - get colno(): number; - /** - * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) - */ - get error(): any; -} -interface ErrorEventErrorEventInit { - message?: string; - filename?: string; - lineno?: number; - colno?: number; - error?: any; -} -/** - * The **`MessageEvent`** interface represents a message received by a target object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) - */ -declare class MessageEvent extends Event { - constructor(type: string, initializer: MessageEventInit); - /** - * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) - */ - readonly data: any; - /** - * The **`origin`** read-only property of the origin of the message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) - */ - readonly origin: string | null; - /** - * The **`lastEventId`** read-only property of the unique ID for the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) - */ - readonly lastEventId: string; - /** - * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) - */ - readonly source: MessagePort | null; - /** - * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) - */ - readonly ports: MessagePort[]; -} -interface MessageEventInit { - data: ArrayBuffer | string; -} -/** - * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) - */ -declare abstract class PromiseRejectionEvent extends Event { - /** - * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) - */ - readonly promise: Promise; - /** - * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) - */ - readonly reason: any; -} -/** - * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the Window/fetch, XMLHttpRequest.send() or navigator.sendBeacon() methods. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) - */ -declare class FormData { - constructor(); - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: string): void; - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: Blob, filename?: string): void; - /** - * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) - */ - delete(name: string): void; - /** - * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) - */ - get(name: string): (File | string) | null; - /** - * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) - */ - getAll(name: string): (File | string)[]; - /** - * The **`has()`** method of the FormData interface returns whether a `FormData` object contains a certain key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) - */ - has(name: string): boolean; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: string): void; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: Blob, filename?: string): void; - /* Returns an array of key, value pairs for every entry in the list. */ - entries(): IterableIterator<[ - key: string, - value: File | string - ]>; - /* Returns a list of keys in the list. */ - keys(): IterableIterator; - /* Returns a list of values in the list. */ - values(): IterableIterator<(File | string)>; - forEach(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: File | string - ]>; -} -interface ContentOptions { - html?: boolean; -} -declare class HTMLRewriter { - constructor(); - on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; - onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; - transform(response: Response): Response; -} -interface HTMLRewriterElementContentHandlers { - element?(element: Element): void | Promise; - comments?(comment: Comment): void | Promise; - text?(element: Text): void | Promise; -} -interface HTMLRewriterDocumentContentHandlers { - doctype?(doctype: Doctype): void | Promise; - comments?(comment: Comment): void | Promise; - text?(text: Text): void | Promise; - end?(end: DocumentEnd): void | Promise; -} -interface Doctype { - readonly name: string | null; - readonly publicId: string | null; - readonly systemId: string | null; -} -interface Element { - tagName: string; - readonly attributes: IterableIterator; - readonly removed: boolean; - readonly namespaceURI: string; - getAttribute(name: string): string | null; - hasAttribute(name: string): boolean; - setAttribute(name: string, value: string): Element; - removeAttribute(name: string): Element; - before(content: string | ReadableStream | Response, options?: ContentOptions): Element; - after(content: string | ReadableStream | Response, options?: ContentOptions): Element; - prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; - append(content: string | ReadableStream | Response, options?: ContentOptions): Element; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; - remove(): Element; - removeAndKeepContent(): Element; - setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; - onEndTag(handler: (tag: EndTag) => void | Promise): void; -} -interface EndTag { - name: string; - before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - remove(): EndTag; -} -interface Comment { - text: string; - readonly removed: boolean; - before(content: string, options?: ContentOptions): Comment; - after(content: string, options?: ContentOptions): Comment; - replace(content: string, options?: ContentOptions): Comment; - remove(): Comment; -} -interface Text { - readonly text: string; - readonly lastInTextNode: boolean; - readonly removed: boolean; - before(content: string | ReadableStream | Response, options?: ContentOptions): Text; - after(content: string | ReadableStream | Response, options?: ContentOptions): Text; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; - remove(): Text; -} -interface DocumentEnd { - append(content: string, options?: ContentOptions): DocumentEnd; -} -/** - * This is the event type for `fetch` events dispatched on the ServiceWorkerGlobalScope. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) - */ -declare abstract class FetchEvent extends ExtendableEvent { - /** - * The **`request`** read-only property of the the event handler. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) - */ - readonly request: Request; - /** - * The **`respondWith()`** method of allows you to provide a promise for a Response yourself. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) - */ - respondWith(promise: Response | Promise): void; - passThroughOnException(): void; -} -type HeadersInit = Headers | Iterable> | Record; -/** - * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) - */ -declare class Headers { - constructor(init?: HeadersInit); - /** - * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) - */ - get(name: string): string | null; - getAll(name: string): string[]; - /** - * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) - */ - getSetCookie(): string[]; - /** - * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) - */ - has(name: string): boolean; - /** - * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) - */ - set(name: string, value: string): void; - /** - * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) - */ - append(name: string, value: string): void; - /** - * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) - */ - delete(name: string): void; - forEach(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void; - /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ - entries(): IterableIterator<[ - key: string, - value: string - ]>; - /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ - keys(): IterableIterator; - /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: string - ]>; -} -type BodyInit = ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData; -declare abstract class Body { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ - get body(): ReadableStream | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ - get bodyUsed(): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ - arrayBuffer(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ - bytes(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ - text(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ - json(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ - formData(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ - blob(): Promise; -} -/** - * The **`Response`** interface of the Fetch API represents the response to a request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) - */ -declare var Response: { - prototype: Response; - new (body?: BodyInit | null, init?: ResponseInit): Response; - error(): Response; - redirect(url: string, status?: number): Response; - json(any: any, maybeInit?: (ResponseInit | Response)): Response; -}; -/** - * The **`Response`** interface of the Fetch API represents the response to a request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) - */ -interface Response extends Body { - /** - * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) - */ - clone(): Response; - /** - * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) - */ - status: number; - /** - * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) - */ - statusText: string; - /** - * The **`headers`** read-only property of the with the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) - */ - headers: Headers; - /** - * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) - */ - ok: boolean; - /** - * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) - */ - redirected: boolean; - /** - * The **`url`** read-only property of the Response interface contains the URL of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) - */ - url: string; - webSocket: WebSocket | null; - cf: any | undefined; - /** - * The **`type`** read-only property of the Response interface contains the type of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) - */ - type: "default" | "error"; -} -interface ResponseInit { - status?: number; - statusText?: string; - headers?: HeadersInit; - cf?: any; - webSocket?: (WebSocket | null); - encodeBody?: "automatic" | "manual"; -} -type RequestInfo> = Request | string; -/** - * The **`Request`** interface of the Fetch API represents a resource request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) - */ -declare var Request: { - prototype: Request; - new >(input: RequestInfo | URL, init?: RequestInit): Request; -}; -/** - * The **`Request`** interface of the Fetch API represents a resource request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) - */ -interface Request> extends Body { - /** - * The **`clone()`** method of the Request interface creates a copy of the current `Request` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) - */ - clone(): Request; - /** - * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) - */ - method: string; - /** - * The **`url`** read-only property of the Request interface contains the URL of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) - */ - url: string; - /** - * The **`headers`** read-only property of the with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) - */ - headers: Headers; - /** - * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) - */ - redirect: string; - fetcher: Fetcher | null; - /** - * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) - */ - signal: AbortSignal; - cf: Cf | undefined; - /** - * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) - */ - integrity: string; - /** - * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) - */ - keepalive: boolean; - /** - * The **`cache`** read-only property of the Request interface contains the cache mode of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) - */ - cache?: "no-store" | "no-cache"; -} -interface RequestInit { - /* A string to set request's method. */ - method?: string; - /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ - headers?: HeadersInit; - /* A BodyInit object or null to set request's body. */ - body?: BodyInit | null; - /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ - redirect?: string; - fetcher?: (Fetcher | null); - cf?: Cf; - /* A string indicating how the request will interact with the browser's cache to set request's cache. */ - cache?: "no-store" | "no-cache"; - /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ - integrity?: string; - /* An AbortSignal to set request's signal. */ - signal?: (AbortSignal | null); - encodeResponseBody?: "automatic" | "manual"; -} -type Service Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; -type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - connect(address: SocketAddress | string, options?: SocketOptions): Socket; -}; -interface KVNamespaceListKey { - name: Key; - expiration?: number; - metadata?: Metadata; -} -type KVNamespaceListResult = { - list_complete: false; - keys: KVNamespaceListKey[]; - cursor: string; - cacheStatus: string | null; -} | { - list_complete: true; - keys: KVNamespaceListKey[]; - cacheStatus: string | null; -}; -interface KVNamespace { - get(key: Key, options?: Partial>): Promise; - get(key: Key, type: "text"): Promise; - get(key: Key, type: "json"): Promise; - get(key: Key, type: "arrayBuffer"): Promise; - get(key: Key, type: "stream"): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"json">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise; - get(key: Array, type: "text"): Promise>; - get(key: Array, type: "json"): Promise>; - get(key: Array, options?: Partial>): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>; - list(options?: KVNamespaceListOptions): Promise>; - put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise; - getWithMetadata(key: Key, options?: Partial>): Promise>; - getWithMetadata(key: Key, type: "text"): Promise>; - getWithMetadata(key: Key, type: "json"): Promise>; - getWithMetadata(key: Key, type: "arrayBuffer"): Promise>; - getWithMetadata(key: Key, type: "stream"): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"text">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"json">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"stream">): Promise>; - getWithMetadata(key: Array, type: "text"): Promise>>; - getWithMetadata(key: Array, type: "json"): Promise>>; - getWithMetadata(key: Array, options?: Partial>): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>>; - delete(key: Key): Promise; -} -interface KVNamespaceListOptions { - limit?: number; - prefix?: (string | null); - cursor?: (string | null); -} -interface KVNamespaceGetOptions { - type: Type; - cacheTtl?: number; -} -interface KVNamespacePutOptions { - expiration?: number; - expirationTtl?: number; - metadata?: (any | null); -} -interface KVNamespaceGetWithMetadataResult { - value: Value | null; - metadata: Metadata | null; - cacheStatus: string | null; -} -type QueueContentType = "text" | "bytes" | "json" | "v8"; -interface Queue { - send(message: Body, options?: QueueSendOptions): Promise; - sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; -} -interface QueueSendOptions { - contentType?: QueueContentType; - delaySeconds?: number; -} -interface QueueSendBatchOptions { - delaySeconds?: number; -} -interface MessageSendRequest { - body: Body; - contentType?: QueueContentType; - delaySeconds?: number; -} -interface QueueRetryOptions { - delaySeconds?: number; -} -interface Message { - readonly id: string; - readonly timestamp: Date; - readonly body: Body; - readonly attempts: number; - retry(options?: QueueRetryOptions): void; - ack(): void; -} -interface QueueEvent extends ExtendableEvent { - readonly messages: readonly Message[]; - readonly queue: string; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; -} -interface MessageBatch { - readonly messages: readonly Message[]; - readonly queue: string; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; -} -interface R2Error extends Error { - readonly name: string; - readonly code: number; - readonly message: string; - readonly action: string; - readonly stack: any; -} -interface R2ListOptions { - limit?: number; - prefix?: string; - cursor?: string; - delimiter?: string; - startAfter?: string; - include?: ("httpMetadata" | "customMetadata")[]; -} -declare abstract class R2Bucket { - head(key: string): Promise; - get(key: string, options: R2GetOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - get(key: string, options?: R2GetOptions): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise; - createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; - resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; - delete(keys: string | string[]): Promise; - list(options?: R2ListOptions): Promise; -} -interface R2MultipartUpload { - readonly key: string; - readonly uploadId: string; - uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise; - abort(): Promise; - complete(uploadedParts: R2UploadedPart[]): Promise; -} -interface R2UploadedPart { - partNumber: number; - etag: string; -} -declare abstract class R2Object { - readonly key: string; - readonly version: string; - readonly size: number; - readonly etag: string; - readonly httpEtag: string; - readonly checksums: R2Checksums; - readonly uploaded: Date; - readonly httpMetadata?: R2HTTPMetadata; - readonly customMetadata?: Record; - readonly range?: R2Range; - readonly storageClass: string; - readonly ssecKeyMd5?: string; - writeHttpMetadata(headers: Headers): void; -} -interface R2ObjectBody extends R2Object { - get body(): ReadableStream; - get bodyUsed(): boolean; - arrayBuffer(): Promise; - bytes(): Promise; - text(): Promise; - json(): Promise; - blob(): Promise; -} -type R2Range = { - offset: number; - length?: number; -} | { - offset?: number; - length: number; -} | { - suffix: number; -}; -interface R2Conditional { - etagMatches?: string; - etagDoesNotMatch?: string; - uploadedBefore?: Date; - uploadedAfter?: Date; - secondsGranularity?: boolean; -} -interface R2GetOptions { - onlyIf?: (R2Conditional | Headers); - range?: (R2Range | Headers); - ssecKey?: (ArrayBuffer | string); -} -interface R2PutOptions { - onlyIf?: (R2Conditional | Headers); - httpMetadata?: (R2HTTPMetadata | Headers); - customMetadata?: Record; - md5?: ((ArrayBuffer | ArrayBufferView) | string); - sha1?: ((ArrayBuffer | ArrayBufferView) | string); - sha256?: ((ArrayBuffer | ArrayBufferView) | string); - sha384?: ((ArrayBuffer | ArrayBufferView) | string); - sha512?: ((ArrayBuffer | ArrayBufferView) | string); - storageClass?: string; - ssecKey?: (ArrayBuffer | string); -} -interface R2MultipartOptions { - httpMetadata?: (R2HTTPMetadata | Headers); - customMetadata?: Record; - storageClass?: string; - ssecKey?: (ArrayBuffer | string); -} -interface R2Checksums { - readonly md5?: ArrayBuffer; - readonly sha1?: ArrayBuffer; - readonly sha256?: ArrayBuffer; - readonly sha384?: ArrayBuffer; - readonly sha512?: ArrayBuffer; - toJSON(): R2StringChecksums; -} -interface R2StringChecksums { - md5?: string; - sha1?: string; - sha256?: string; - sha384?: string; - sha512?: string; -} -interface R2HTTPMetadata { - contentType?: string; - contentLanguage?: string; - contentDisposition?: string; - contentEncoding?: string; - cacheControl?: string; - cacheExpiry?: Date; -} -type R2Objects = { - objects: R2Object[]; - delimitedPrefixes: string[]; -} & ({ - truncated: true; - cursor: string; -} | { - truncated: false; -}); -interface R2UploadPartOptions { - ssecKey?: (ArrayBuffer | string); -} -declare abstract class ScheduledEvent extends ExtendableEvent { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; -} -interface ScheduledController { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; -} -interface QueuingStrategy { - highWaterMark?: (number | bigint); - size?: (chunk: T) => number | bigint; -} -interface UnderlyingSink { - type?: string; - start?: (controller: WritableStreamDefaultController) => void | Promise; - write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; - abort?: (reason: any) => void | Promise; - close?: () => void | Promise; -} -interface UnderlyingByteSource { - type: "bytes"; - autoAllocateChunkSize?: number; - start?: (controller: ReadableByteStreamController) => void | Promise; - pull?: (controller: ReadableByteStreamController) => void | Promise; - cancel?: (reason: any) => void | Promise; -} -interface UnderlyingSource { - type?: "" | undefined; - start?: (controller: ReadableStreamDefaultController) => void | Promise; - pull?: (controller: ReadableStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: (number | bigint); -} -interface Transformer { - readableType?: string; - writableType?: string; - start?: (controller: TransformStreamDefaultController) => void | Promise; - transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; - flush?: (controller: TransformStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: number; -} -interface StreamPipeOptions { - /** - * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - * - * Errors and closures of the source and destination streams propagate as follows: - * - * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. - * - * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. - * - * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - * - * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. - * - * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. - */ - preventClose?: boolean; - preventAbort?: boolean; - preventCancel?: boolean; - signal?: AbortSignal; -} -type ReadableStreamReadResult = { - done: false; - value: R; -} | { - done: true; - value?: undefined; -}; -/** - * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) - */ -interface ReadableStream { - /** - * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) - */ - get locked(): boolean; - /** - * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) - */ - cancel(reason?: any): Promise; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(): ReadableStreamDefaultReader; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; - /** - * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) - */ - pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; - /** - * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) - */ - pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; - /** - * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) - */ - tee(): [ - ReadableStream, - ReadableStream - ]; - values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; - [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; -} -/** - * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) - */ -declare const ReadableStream: { - prototype: ReadableStream; - new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; - new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; -}; -/** - * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) - */ -declare class ReadableStreamDefaultReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) - */ - read(): Promise>; - /** - * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) - */ - releaseLock(): void; -} -/** - * The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) - */ -declare class ReadableStreamBYOBReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) - */ - read(view: T): Promise>; - /** - * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) - */ - releaseLock(): void; - readAtLeast(minElements: number, view: T): Promise>; -} -interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { - min?: number; -} -interface ReadableStreamGetReaderOptions { - /** - * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. - * - * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. - */ - mode: "byob"; -} -/** - * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a 'pull request' for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) - */ -declare abstract class ReadableStreamBYOBRequest { - /** - * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) - */ - get view(): Uint8Array | null; - /** - * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) - */ - respond(bytesWritten: number): void; - /** - * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) - */ - respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; - get atLeast(): number | null; -} -/** - * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) - */ -declare abstract class ReadableStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the required to fill the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) - */ - close(): void; - /** - * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) - */ - enqueue(chunk?: R): void; - /** - * The **`error()`** method of the with the associated stream to error. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) - */ - error(reason: any): void; -} -/** - * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) - */ -declare abstract class ReadableByteStreamController { - /** - * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) - */ - get byobRequest(): ReadableStreamBYOBRequest | null; - /** - * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) - */ - close(): void; - /** - * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) - */ - enqueue(chunk: ArrayBuffer | ArrayBufferView): void; - /** - * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) - */ - error(reason: any): void; -} -/** - * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) - */ -declare abstract class WritableStreamDefaultController { - /** - * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) - */ - get signal(): AbortSignal; - /** - * The **`error()`** method of the with the associated stream to error. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) - */ - error(reason?: any): void; -} -/** - * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) - */ -declare abstract class TransformStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) - */ - enqueue(chunk?: O): void; - /** - * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) - */ - error(reason: any): void; - /** - * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) - */ - terminate(): void; -} -interface ReadableWritablePair { - /** - * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - */ - writable: WritableStream; - readable: ReadableStream; -} -/** - * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) - */ -declare class WritableStream { - constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); - /** - * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) - */ - get locked(): boolean; - /** - * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) - */ - abort(reason?: any): Promise; - /** - * The **`close()`** method of the WritableStream interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) - */ - close(): Promise; - /** - * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) - */ - getWriter(): WritableStreamDefaultWriter; -} -/** - * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the `WritableStream` ensuring that no other streams can write to the underlying sink. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) - */ -declare class WritableStreamDefaultWriter { - constructor(stream: WritableStream); - /** - * The **`closed`** read-only property of the the stream errors or the writer's lock is released. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) - */ - get closed(): Promise; - /** - * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) - */ - get ready(): Promise; - /** - * The **`desiredSize`** read-only property of the to fill the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) - */ - abort(reason?: any): Promise; - /** - * The **`close()`** method of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) - */ - close(): Promise; - /** - * The **`write()`** method of the operation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) - */ - write(chunk?: W): Promise; - /** - * The **`releaseLock()`** method of the corresponding stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) - */ - releaseLock(): void; -} -/** - * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain _transform stream_ concept. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) - */ -declare class TransformStream { - constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); - /** - * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) - */ - get readable(): ReadableStream; - /** - * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) - */ - get writable(): WritableStream; -} -declare class FixedLengthStream extends IdentityTransformStream { - constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); -} -declare class IdentityTransformStream extends TransformStream { - constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); -} -interface IdentityTransformStreamQueuingStrategy { - highWaterMark?: (number | bigint); -} -interface ReadableStreamValuesOptions { - preventCancel?: boolean; -} -/** - * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) - */ -declare class CompressionStream extends TransformStream { - constructor(format: "gzip" | "deflate" | "deflate-raw"); -} -/** - * The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) - */ -declare class DecompressionStream extends TransformStream { - constructor(format: "gzip" | "deflate" | "deflate-raw"); -} -/** - * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) - */ -declare class TextEncoderStream extends TransformStream { - constructor(); - get encoding(): string; -} -/** - * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) - */ -declare class TextDecoderStream extends TransformStream { - constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; -} -interface TextDecoderStreamTextDecoderStreamInit { - fatal?: boolean; - ignoreBOM?: boolean; -} -/** - * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) - */ -declare class ByteLengthQueuingStrategy implements QueuingStrategy { - constructor(init: QueuingStrategyInit); - /** - * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) - */ - get highWaterMark(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ - get size(): (chunk?: any) => number; -} -/** - * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy) - */ -declare class CountQueuingStrategy implements QueuingStrategy { - constructor(init: QueuingStrategyInit); - /** - * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) - */ - get highWaterMark(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ - get size(): (chunk?: any) => number; -} -interface QueuingStrategyInit { - /** - * Creates a new ByteLengthQueuingStrategy with the provided high water mark. - * - * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. - */ - highWaterMark: number; -} -interface ScriptVersion { - id?: string; - tag?: string; - message?: string; -} -declare abstract class TailEvent extends ExtendableEvent { - readonly events: TraceItem[]; - readonly traces: TraceItem[]; -} -interface TraceItem { - readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null; - readonly eventTimestamp: number | null; - readonly logs: TraceLog[]; - readonly exceptions: TraceException[]; - readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; - readonly scriptName: string | null; - readonly entrypoint?: string; - readonly scriptVersion?: ScriptVersion; - readonly dispatchNamespace?: string; - readonly scriptTags?: string[]; - readonly durableObjectId?: string; - readonly outcome: string; - readonly executionModel: string; - readonly truncated: boolean; - readonly cpuTime: number; - readonly wallTime: number; -} -interface TraceItemAlarmEventInfo { - readonly scheduledTime: Date; -} -interface TraceItemCustomEventInfo { -} -interface TraceItemScheduledEventInfo { - readonly scheduledTime: number; - readonly cron: string; -} -interface TraceItemQueueEventInfo { - readonly queue: string; - readonly batchSize: number; -} -interface TraceItemEmailEventInfo { - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; -} -interface TraceItemTailEventInfo { - readonly consumedEvents: TraceItemTailEventInfoTailItem[]; -} -interface TraceItemTailEventInfoTailItem { - readonly scriptName: string | null; -} -interface TraceItemFetchEventInfo { - readonly response?: TraceItemFetchEventInfoResponse; - readonly request: TraceItemFetchEventInfoRequest; -} -interface TraceItemFetchEventInfoRequest { - readonly cf?: any; - readonly headers: Record; - readonly method: string; - readonly url: string; - getUnredacted(): TraceItemFetchEventInfoRequest; -} -interface TraceItemFetchEventInfoResponse { - readonly status: number; -} -interface TraceItemJsRpcEventInfo { - readonly rpcMethod: string; -} -interface TraceItemHibernatableWebSocketEventInfo { - readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError; -} -interface TraceItemHibernatableWebSocketEventInfoMessage { - readonly webSocketEventType: string; -} -interface TraceItemHibernatableWebSocketEventInfoClose { - readonly webSocketEventType: string; - readonly code: number; - readonly wasClean: boolean; -} -interface TraceItemHibernatableWebSocketEventInfoError { - readonly webSocketEventType: string; -} -interface TraceLog { - readonly timestamp: number; - readonly level: string; - readonly message: any; -} -interface TraceException { - readonly timestamp: number; - readonly message: string; - readonly name: string; - readonly stack?: string; -} -interface TraceDiagnosticChannelEvent { - readonly timestamp: number; - readonly channel: string; - readonly message: any; -} -interface TraceMetrics { - readonly cpuTime: number; - readonly wallTime: number; -} -interface UnsafeTraceMetrics { - fromTrace(item: TraceItem): TraceMetrics; -} -/** - * The **`URL`** interface is used to parse, construct, normalize, and encode URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) - */ -declare class URL { - constructor(url: string | URL, base?: string | URL); - /** - * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) - */ - get origin(): string; - /** - * The **`href`** property of the URL interface is a string containing the whole URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) - */ - get href(): string; - /** - * The **`href`** property of the URL interface is a string containing the whole URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) - */ - set href(value: string); - /** - * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) - */ - get protocol(): string; - /** - * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) - */ - set protocol(value: string); - /** - * The **`username`** property of the URL interface is a string containing the username component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) - */ - get username(): string; - /** - * The **`username`** property of the URL interface is a string containing the username component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) - */ - set username(value: string); - /** - * The **`password`** property of the URL interface is a string containing the password component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) - */ - get password(): string; - /** - * The **`password`** property of the URL interface is a string containing the password component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) - */ - set password(value: string); - /** - * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) - */ - get host(): string; - /** - * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) - */ - set host(value: string); - /** - * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) - */ - get hostname(): string; - /** - * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) - */ - set hostname(value: string); - /** - * The **`port`** property of the URL interface is a string containing the port number of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) - */ - get port(): string; - /** - * The **`port`** property of the URL interface is a string containing the port number of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) - */ - set port(value: string); - /** - * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) - */ - get pathname(): string; - /** - * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) - */ - set pathname(value: string); - /** - * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) - */ - get search(): string; - /** - * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) - */ - set search(value: string); - /** - * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - get hash(): string; - /** - * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - set hash(value: string); - /** - * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) - */ - get searchParams(): URLSearchParams; - /** - * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) - */ - toJSON(): string; - /*function toString() { [native code] }*/ - toString(): string; - /** - * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) - */ - static canParse(url: string, base?: string): boolean; - /** - * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) - */ - static parse(url: string, base?: string): URL | null; - /** - * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) - */ - static createObjectURL(object: File | Blob): string; - /** - * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) - */ - static revokeObjectURL(object_url: string): void; -} -/** - * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) - */ -declare class URLSearchParams { - constructor(init?: (Iterable> | Record | string)); - /** - * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) - */ - get size(): number; - /** - * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) - */ - append(name: string, value: string): void; - /** - * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) - */ - delete(name: string, value?: string): void; - /** - * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) - */ - get(name: string): string | null; - /** - * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) - */ - getAll(name: string): string[]; - /** - * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) - */ - has(name: string, value?: string): boolean; - /** - * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) - */ - set(name: string, value: string): void; - /** - * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) - */ - sort(): void; - /* Returns an array of key, value pairs for every entry in the search params. */ - entries(): IterableIterator<[ - key: string, - value: string - ]>; - /* Returns a list of keys in the search params. */ - keys(): IterableIterator; - /* Returns a list of values in the search params. */ - values(): IterableIterator; - forEach(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void; - /*function toString() { [native code] }*/ - toString(): string; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: string - ]>; -} -declare class URLPattern { - constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions); - get protocol(): string; - get username(): string; - get password(): string; - get hostname(): string; - get port(): string; - get pathname(): string; - get search(): string; - get hash(): string; - get hasRegExpGroups(): boolean; - test(input?: (string | URLPatternInit), baseURL?: string): boolean; - exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null; -} -interface URLPatternInit { - protocol?: string; - username?: string; - password?: string; - hostname?: string; - port?: string; - pathname?: string; - search?: string; - hash?: string; - baseURL?: string; -} -interface URLPatternComponentResult { - input: string; - groups: Record; -} -interface URLPatternResult { - inputs: (string | URLPatternInit)[]; - protocol: URLPatternComponentResult; - username: URLPatternComponentResult; - password: URLPatternComponentResult; - hostname: URLPatternComponentResult; - port: URLPatternComponentResult; - pathname: URLPatternComponentResult; - search: URLPatternComponentResult; - hash: URLPatternComponentResult; -} -interface URLPatternOptions { - ignoreCase?: boolean; -} -/** - * A `CloseEvent` is sent to clients using WebSockets when the connection is closed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) - */ -declare class CloseEvent extends Event { - constructor(type: string, initializer?: CloseEventInit); - /** - * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) - */ - readonly code: number; - /** - * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) - */ - readonly reason: string; - /** - * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) - */ - readonly wasClean: boolean; -} -interface CloseEventInit { - code?: number; - reason?: string; - wasClean?: boolean; -} -type WebSocketEventMap = { - close: CloseEvent; - message: MessageEvent; - open: Event; - error: ErrorEvent; -}; -/** - * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) - */ -declare var WebSocket: { - prototype: WebSocket; - new (url: string, protocols?: (string[] | string)): WebSocket; - readonly READY_STATE_CONNECTING: number; - readonly CONNECTING: number; - readonly READY_STATE_OPEN: number; - readonly OPEN: number; - readonly READY_STATE_CLOSING: number; - readonly CLOSING: number; - readonly READY_STATE_CLOSED: number; - readonly CLOSED: number; -}; -/** - * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) - */ -interface WebSocket extends EventTarget { - accept(): void; - /** - * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) - */ - send(message: (ArrayBuffer | ArrayBufferView) | string): void; - /** - * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) - */ - close(code?: number, reason?: string): void; - serializeAttachment(attachment: any): void; - deserializeAttachment(): any | null; - /** - * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) - */ - readyState: number; - /** - * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) - */ - url: string | null; - /** - * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) - */ - protocol: string | null; - /** - * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) - */ - extensions: string | null; -} -declare const WebSocketPair: { - new (): { - 0: WebSocket; - 1: WebSocket; - }; -}; -interface SqlStorage { - exec>(query: string, ...bindings: any[]): SqlStorageCursor; - get databaseSize(): number; - Cursor: typeof SqlStorageCursor; - Statement: typeof SqlStorageStatement; -} -declare abstract class SqlStorageStatement { -} -type SqlStorageValue = ArrayBuffer | string | number | null; -declare abstract class SqlStorageCursor> { - next(): { - done?: false; - value: T; - } | { - done: true; - value?: never; - }; - toArray(): T[]; - one(): T; - raw(): IterableIterator; - columnNames: string[]; - get rowsRead(): number; - get rowsWritten(): number; - [Symbol.iterator](): IterableIterator; -} -interface Socket { - get readable(): ReadableStream; - get writable(): WritableStream; - get closed(): Promise; - get opened(): Promise; - get upgraded(): boolean; - get secureTransport(): "on" | "off" | "starttls"; - close(): Promise; - startTls(options?: TlsOptions): Socket; -} -interface SocketOptions { - secureTransport?: string; - allowHalfOpen: boolean; - highWaterMark?: (number | bigint); -} -interface SocketAddress { - hostname: string; - port: number; -} -interface TlsOptions { - expectedServerHostname?: string; -} -interface SocketInfo { - remoteAddress?: string; - localAddress?: string; -} -/** - * The **`EventSource`** interface is web content's interface to server-sent events. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) - */ -declare class EventSource extends EventTarget { - constructor(url: string, init?: EventSourceEventSourceInit); - /** - * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) - */ - close(): void; - /** - * The **`url`** read-only property of the URL of the source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) - */ - get url(): string; - /** - * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) - */ - get withCredentials(): boolean; - /** - * The **`readyState`** read-only property of the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) - */ - get readyState(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - get onopen(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - set onopen(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - get onmessage(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - set onmessage(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - get onerror(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - set onerror(value: any | null); - static readonly CONNECTING: number; - static readonly OPEN: number; - static readonly CLOSED: number; - static from(stream: ReadableStream): EventSource; -} -interface EventSourceEventSourceInit { - withCredentials?: boolean; - fetcher?: Fetcher; -} -interface Container { - get running(): boolean; - start(options?: ContainerStartupOptions): void; - monitor(): Promise; - destroy(error?: any): Promise; - signal(signo: number): void; - getTcpPort(port: number): Fetcher; - setInactivityTimeout(durationMs: number | bigint): Promise; -} -interface ContainerStartupOptions { - entrypoint?: string[]; - enableInternet: boolean; - env?: Record; - hardTimeout?: (number | bigint); -} -/** - * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) - */ -declare abstract class MessagePort extends EventTarget { - /** - * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) - */ - postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void; - /** - * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) - */ - close(): void; - /** - * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) - */ - start(): void; - get onmessage(): any | null; - set onmessage(value: any | null); -} -/** - * The **`MessageChannel`** interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel) - */ -declare class MessageChannel { - constructor(); - /** - * The **`port1`** read-only property of the the port attached to the context that originated the channel. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1) - */ - readonly port1: MessagePort; - /** - * The **`port2`** read-only property of the the port attached to the context at the other end of the channel, which the message is initially sent to. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2) - */ - readonly port2: MessagePort; -} -interface MessagePortPostMessageOptions { - transfer?: any[]; -} -type LoopbackForExport Rpc.EntrypointBranded) | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass> : T extends ExportedHandler ? LoopbackServiceStub : undefined; -type LoopbackServiceStub = Fetcher & (T extends CloudflareWorkersModule.WorkerEntrypoint ? (opts: { - props?: Props; -}) => Fetcher : (opts: { - props?: any; -}) => Fetcher); -type LoopbackDurableObjectClass = DurableObjectClass & (T extends CloudflareWorkersModule.DurableObject ? (opts: { - props?: Props; -}) => DurableObjectClass : (opts: { - props?: any; -}) => DurableObjectClass); -interface SyncKvStorage { - get(key: string): T | undefined; - list(options?: SyncKvListOptions): Iterable<[ - string, - T - ]>; - put(key: string, value: T): void; - delete(key: string): boolean; -} -interface SyncKvListOptions { - start?: string; - startAfter?: string; - end?: string; - prefix?: string; - reverse?: boolean; - limit?: number; -} -interface WorkerStub { - getEntrypoint(name?: string, options?: WorkerStubEntrypointOptions): Fetcher; -} -interface WorkerStubEntrypointOptions { - props?: any; -} -interface WorkerLoader { - get(name: string, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; -} -interface WorkerLoaderModule { - js?: string; - cjs?: string; - text?: string; - data?: ArrayBuffer; - json?: any; - py?: string; - wasm?: ArrayBuffer; -} -interface WorkerLoaderWorkerCode { - compatibilityDate: string; - compatibilityFlags?: string[]; - allowExperimental?: boolean; - mainModule: string; - modules: Record; - env?: any; - globalOutbound?: (Fetcher | null); - tails?: Fetcher[]; - streamingTails?: Fetcher[]; -} -/** -* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, -* as well as timing of subrequests and other operations. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) -*/ -declare abstract class Performance { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ - get timeOrigin(): number; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ - now(): number; -} -type AiImageClassificationInput = { - image: number[]; -}; -type AiImageClassificationOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiImageClassification { - inputs: AiImageClassificationInput; - postProcessedOutputs: AiImageClassificationOutput; -} -type AiImageToTextInput = { - image: number[]; - prompt?: string; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - raw?: boolean; - messages?: RoleScopedChatInput[]; -}; -type AiImageToTextOutput = { - description: string; -}; -declare abstract class BaseAiImageToText { - inputs: AiImageToTextInput; - postProcessedOutputs: AiImageToTextOutput; -} -type AiImageTextToTextInput = { - image: string; - prompt?: string; - max_tokens?: number; - temperature?: number; - ignore_eos?: boolean; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - raw?: boolean; - messages?: RoleScopedChatInput[]; -}; -type AiImageTextToTextOutput = { - description: string; -}; -declare abstract class BaseAiImageTextToText { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; -} -type AiMultimodalEmbeddingsInput = { - image: string; - text: string[]; -}; -type AiIMultimodalEmbeddingsOutput = { - data: number[][]; - shape: number[]; -}; -declare abstract class BaseAiMultimodalEmbeddings { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; -} -type AiObjectDetectionInput = { - image: number[]; -}; -type AiObjectDetectionOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiObjectDetection { - inputs: AiObjectDetectionInput; - postProcessedOutputs: AiObjectDetectionOutput; -} -type AiSentenceSimilarityInput = { - source: string; - sentences: string[]; -}; -type AiSentenceSimilarityOutput = number[]; -declare abstract class BaseAiSentenceSimilarity { - inputs: AiSentenceSimilarityInput; - postProcessedOutputs: AiSentenceSimilarityOutput; -} -type AiAutomaticSpeechRecognitionInput = { - audio: number[]; -}; -type AiAutomaticSpeechRecognitionOutput = { - text?: string; - words?: { - word: string; - start: number; - end: number; - }[]; - vtt?: string; -}; -declare abstract class BaseAiAutomaticSpeechRecognition { - inputs: AiAutomaticSpeechRecognitionInput; - postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; -} -type AiSummarizationInput = { - input_text: string; - max_length?: number; -}; -type AiSummarizationOutput = { - summary: string; -}; -declare abstract class BaseAiSummarization { - inputs: AiSummarizationInput; - postProcessedOutputs: AiSummarizationOutput; -} -type AiTextClassificationInput = { - text: string; -}; -type AiTextClassificationOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiTextClassification { - inputs: AiTextClassificationInput; - postProcessedOutputs: AiTextClassificationOutput; -} -type AiTextEmbeddingsInput = { - text: string | string[]; -}; -type AiTextEmbeddingsOutput = { - shape: number[]; - data: number[][]; -}; -declare abstract class BaseAiTextEmbeddings { - inputs: AiTextEmbeddingsInput; - postProcessedOutputs: AiTextEmbeddingsOutput; -} -type RoleScopedChatInput = { - role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); - content: string; - name?: string; -}; -type AiTextGenerationToolLegacyInput = { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; - }; - required: string[]; - }; -}; -type AiTextGenerationToolInput = { - type: "function" | (string & NonNullable); - function: { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; - }; - required: string[]; - }; - }; -}; -type AiTextGenerationFunctionsInput = { - name: string; - code: string; -}; -type AiTextGenerationResponseFormat = { - type: string; - json_schema?: any; -}; -type AiTextGenerationInput = { - prompt?: string; - raw?: boolean; - stream?: boolean; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - messages?: RoleScopedChatInput[]; - response_format?: AiTextGenerationResponseFormat; - tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable); - functions?: AiTextGenerationFunctionsInput[]; -}; -type AiTextGenerationToolLegacyOutput = { - name: string; - arguments: unknown; -}; -type AiTextGenerationToolOutput = { - id: string; - type: "function"; - function: { - name: string; - arguments: string; - }; -}; -type UsageTags = { - prompt_tokens: number; - completion_tokens: number; - total_tokens: number; -}; -type AiTextGenerationOutput = { - response?: string; - tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; - usage?: UsageTags; -}; -declare abstract class BaseAiTextGeneration { - inputs: AiTextGenerationInput; - postProcessedOutputs: AiTextGenerationOutput; -} -type AiTextToSpeechInput = { - prompt: string; - lang?: string; -}; -type AiTextToSpeechOutput = Uint8Array | { - audio: string; -}; -declare abstract class BaseAiTextToSpeech { - inputs: AiTextToSpeechInput; - postProcessedOutputs: AiTextToSpeechOutput; -} -type AiTextToImageInput = { - prompt: string; - negative_prompt?: string; - height?: number; - width?: number; - image?: number[]; - image_b64?: string; - mask?: number[]; - num_steps?: number; - strength?: number; - guidance?: number; - seed?: number; -}; -type AiTextToImageOutput = ReadableStream; -declare abstract class BaseAiTextToImage { - inputs: AiTextToImageInput; - postProcessedOutputs: AiTextToImageOutput; -} -type AiTranslationInput = { - text: string; - target_lang: string; - source_lang?: string; -}; -type AiTranslationOutput = { - translated_text?: string; -}; -declare abstract class BaseAiTranslation { - inputs: AiTranslationInput; - postProcessedOutputs: AiTranslationOutput; -} -type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; - }[]; -}; -type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} | AsyncResponse; -interface AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output; -} -type Ai_Cf_Openai_Whisper_Input = string | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[]; -}; -interface Ai_Cf_Openai_Whisper_Output { - /** - * The transcription - */ - text: string; - word_count?: number; - words?: { - word?: string; - /** - * The second this word begins in the recording - */ - start?: number; - /** - * The ending second when the word completes - */ - end?: number; - }[]; - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper { - inputs: Ai_Cf_Openai_Whisper_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; -} -type Ai_Cf_Meta_M2M100_1_2B_Input = { - /** - * The text to be translated - */ - text: string; - /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified - */ - source_lang?: string; - /** - * The language code to translate the text into (e.g., 'es' for Spanish) - */ - target_lang: string; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - /** - * The text to be translated - */ - text: string; - /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified - */ - source_lang?: string; - /** - * The language code to translate the text into (e.g., 'es' for Spanish) - */ - target_lang: string; - }[]; -}; -type Ai_Cf_Meta_M2M100_1_2B_Output = { - /** - * The translated text in the target language - */ - translated_text?: string; -} | AsyncResponse; -declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { - inputs: Ai_Cf_Meta_M2M100_1_2B_Input; - postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; -} -type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; - }[]; -}; -type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} | AsyncResponse; -declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; -} -type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; - }[]; -}; -type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} | AsyncResponse; -declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; -} -type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | { - /** - * The input text prompt for the model to generate a response. - */ - prompt?: string; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - image: number[] | (string & NonNullable); - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; -}; -interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { - description?: string; -} -declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { - inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input; - postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output; -} -type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[]; -}; -interface Ai_Cf_Openai_Whisper_Tiny_En_Output { - /** - * The transcription - */ - text: string; - word_count?: number; - words?: { - word?: string; - /** - * The second this word begins in the recording - */ - start?: number; - /** - * The ending second when the word completes - */ - end?: number; - }[]; - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { - inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; -} -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { - /** - * Base64 encoded value of the audio data. - */ - audio: string; - /** - * Supported tasks are 'translate' or 'transcribe'. - */ - task?: string; - /** - * The language of the audio being transcribed or translated. - */ - language?: string; - /** - * Preprocess the audio with a voice activity detection model. - */ - vad_filter?: boolean; - /** - * A text prompt to help provide context to the model on the contents of the audio. - */ - initial_prompt?: string; - /** - * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result. - */ - prefix?: string; -} -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { - transcription_info?: { - /** - * The language of the audio being transcribed or translated. - */ - language?: string; - /** - * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. - */ - language_probability?: number; - /** - * The total duration of the original audio file, in seconds. - */ - duration?: number; - /** - * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. - */ - duration_after_vad?: number; - }; - /** - * The complete transcription of the audio. - */ - text: string; - /** - * The total number of words in the transcription. - */ - word_count?: number; - segments?: { - /** - * The starting time of the segment within the audio, in seconds. - */ - start?: number; - /** - * The ending time of the segment within the audio, in seconds. - */ - end?: number; - /** - * The transcription of the segment. - */ - text?: string; - /** - * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. - */ - temperature?: number; - /** - * The average log probability of the predictions for the words in this segment, indicating overall confidence. - */ - avg_logprob?: number; - /** - * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. - */ - compression_ratio?: number; - /** - * The probability that the segment contains no speech, represented as a decimal between 0 and 1. - */ - no_speech_prob?: number; - words?: { - /** - * The individual word transcribed from the audio. - */ - word?: string; - /** - * The starting time of the word within the audio, in seconds. - */ - start?: number; - /** - * The ending time of the word within the audio, in seconds. - */ - end?: number; - }[]; - }[]; - /** - * The transcription in WebVTT format, which includes timing and text information for use in subtitles. - */ - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { - inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; -} -type Ai_Cf_Baai_Bge_M3_Input = BGEM3InputQueryAndContexts | BGEM3InputEmbedding | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: (BGEM3InputQueryAndContexts1 | BGEM3InputEmbedding1)[]; -}; -interface BGEM3InputQueryAndContexts { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -interface BGEM3InputEmbedding { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -interface BGEM3InputQueryAndContexts1 { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -interface BGEM3InputEmbedding1 { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -type Ai_Cf_Baai_Bge_M3_Output = BGEM3OuputQuery | BGEM3OutputEmbeddingForContexts | BGEM3OuputEmbedding | AsyncResponse; -interface BGEM3OuputQuery { - response?: { - /** - * Index of the context in the request - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; -} -interface BGEM3OutputEmbeddingForContexts { - response?: number[][]; - shape?: number[]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} -interface BGEM3OuputEmbedding { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} -declare abstract class Base_Ai_Cf_Baai_Bge_M3 { - inputs: Ai_Cf_Baai_Bge_M3_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; -} -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * The number of diffusion steps; higher values can improve quality but take longer. - */ - steps?: number; -} -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { - /** - * The generated image in Base64 format. - */ - image?: string; -} -declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { - inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; - postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; -} -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Prompt | Messages; -interface Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - image?: number[] | (string & NonNullable); - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; -} -interface Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - image?: number[] | (string & NonNullable); - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * If true, the response will be streamed back incrementally. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { - /** - * The generated text response from the model - */ - response?: string; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { - inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; -} -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | AsyncBatch; -interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: JSONMode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface JSONMode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: JSONMode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface AsyncBatch { - requests?: { - /** - * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. - */ - external_reference?: string; - /** - * Prompt for the text generation model - */ - prompt?: string; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - response_format?: JSONMode; - }[]; -} -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -} | string | AsyncResponse; -declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { - inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; -} -interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender must alternate between 'user' and 'assistant'. - */ - role: "user" | "assistant"; - /** - * The content of the message as a string. - */ - content: string; - }[]; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Dictate the output format of the generated response. - */ - response_format?: { - /** - * Set to json_object to process and output generated text as JSON. - */ - type?: string; - }; -} -interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { - response?: string | { - /** - * Whether the conversation is safe or not. - */ - safe?: boolean; - /** - * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. - */ - categories?: string[]; - }; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; -} -declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { - inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; -} -interface Ai_Cf_Baai_Bge_Reranker_Base_Input { - /** - * A query you wish to perform against the provided contexts. - */ - /** - * Number of returned results starting with the best score. - */ - top_k?: number; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; -} -interface Ai_Cf_Baai_Bge_Reranker_Base_Output { - response?: { - /** - * Index of the context in the request - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { - inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; -} -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Qwen2_5_Coder_32B_Instruct_Prompt | Qwen2_5_Coder_32B_Instruct_Messages; -interface Qwen2_5_Coder_32B_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: JSONMode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Qwen2_5_Coder_32B_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: JSONMode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { - inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; -} -type Ai_Cf_Qwen_Qwq_32B_Input = Qwen_Qwq_32B_Prompt | Qwen_Qwq_32B_Messages; -interface Qwen_Qwq_32B_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Qwen_Qwq_32B_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Qwen_Qwq_32B_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { - inputs: Ai_Cf_Qwen_Qwq_32B_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; -} -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Mistral_Small_3_1_24B_Instruct_Prompt | Mistral_Small_3_1_24B_Instruct_Messages; -interface Mistral_Small_3_1_24B_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Mistral_Small_3_1_24B_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { - inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; -} -type Ai_Cf_Google_Gemma_3_12B_It_Input = Google_Gemma_3_12B_It_Prompt | Google_Gemma_3_12B_It_Messages; -interface Google_Gemma_3_12B_It_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Google_Gemma_3_12B_It_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Google_Gemma_3_12B_It_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { - inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; - postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; -} -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Prompt | Ai_Cf_Meta_Llama_4_Messages | Ai_Cf_Meta_Llama_4_Async_Batch; -interface Ai_Cf_Meta_Llama_4_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: JSONMode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_4_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: JSONMode; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_4_Async_Batch { - requests: (Ai_Cf_Meta_Llama_4_Prompt_Inner | Ai_Cf_Meta_Llama_4_Messages_Inner)[]; -} -interface Ai_Cf_Meta_Llama_4_Prompt_Inner { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: JSONMode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_4_Messages_Inner { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: JSONMode; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The tool call id. - */ - id?: string; - /** - * Specifies the type of tool (e.g., 'function'). - */ - type?: string; - /** - * Details of the function tool. - */ - function?: { - /** - * The name of the tool to be called - */ - name?: string; - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - }; - }[]; -}; -declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { - inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; -} -interface Ai_Cf_Deepgram_Nova_3_Input { - audio: { - body: object; - contentType: string; - }; - /** - * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. - */ - custom_topic_mode?: "extended" | "strict"; - /** - * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 - */ - custom_topic?: string; - /** - * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param - */ - custom_intent_mode?: "extended" | "strict"; - /** - * Custom intents you want the model to detect within your input audio if present - */ - custom_intent?: string; - /** - * Identifies and extracts key entities from content in submitted audio - */ - detect_entities?: boolean; - /** - * Identifies the dominant language spoken in submitted audio - */ - detect_language?: boolean; - /** - * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 - */ - diarize?: boolean; - /** - * Identify and extract key entities from content in submitted audio - */ - dictation?: boolean; - /** - * Specify the expected encoding of your submitted audio - */ - encoding?: "linear16" | "flac" | "mulaw" | "amr-nb" | "amr-wb" | "opus" | "speex" | "g729"; - /** - * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing - */ - extra?: string; - /** - * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' - */ - filler_words?: boolean; - /** - * Key term prompting can boost or suppress specialized terminology and brands. - */ - keyterm?: string; - /** - * Keywords can boost or suppress specialized terminology and brands. - */ - keywords?: string; - /** - * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. - */ - language?: string; - /** - * Spoken measurements will be converted to their corresponding abbreviations. - */ - measurements?: boolean; - /** - * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. - */ - mip_opt_out?: boolean; - /** - * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio - */ - mode?: "general" | "medical" | "finance"; - /** - * Transcribe each audio channel independently. - */ - multichannel?: boolean; - /** - * Numerals converts numbers from written format to numerical format. - */ - numerals?: boolean; - /** - * Splits audio into paragraphs to improve transcript readability. - */ - paragraphs?: boolean; - /** - * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. - */ - profanity_filter?: boolean; - /** - * Add punctuation and capitalization to the transcript. - */ - punctuate?: boolean; - /** - * Redaction removes sensitive information from your transcripts. - */ - redact?: string; - /** - * Search for terms or phrases in submitted audio and replaces them. - */ - replace?: string; - /** - * Search for terms or phrases in submitted audio. - */ - search?: string; - /** - * Recognizes the sentiment throughout a transcript or text. - */ - sentiment?: boolean; - /** - * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. - */ - smart_format?: boolean; - /** - * Detect topics throughout a transcript or text. - */ - topics?: boolean; - /** - * Segments speech into meaningful semantic units. - */ - utterances?: boolean; - /** - * Seconds to wait before detecting a pause between words in submitted audio. - */ - utt_split?: number; - /** - * The number of channels in the submitted audio - */ - channels?: number; - /** - * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. - */ - interim_results?: boolean; - /** - * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing - */ - endpointing?: string; - /** - * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. - */ - vad_events?: boolean; - /** - * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. - */ - utterance_end_ms?: boolean; -} -interface Ai_Cf_Deepgram_Nova_3_Output { - results?: { - channels?: { - alternatives?: { - confidence?: number; - transcript?: string; - words?: { - confidence?: number; - end?: number; - start?: number; - word?: string; - }[]; - }[]; - }[]; - summary?: { - result?: string; - short?: string; - }; - sentiments?: { - segments?: { - text?: string; - start_word?: number; - end_word?: number; - sentiment?: string; - sentiment_score?: number; - }[]; - average?: { - sentiment?: string; - sentiment_score?: number; - }; - }; - }; -} -declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { - inputs: Ai_Cf_Deepgram_Nova_3_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; -} -type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = { - /** - * readable stream with audio data and content-type specified for that data - */ - audio: { - body: object; - contentType: string; - }; - /** - * type of data PCM data that's sent to the inference server as raw array - */ - dtype?: "uint8" | "float32" | "float64"; -} | { - /** - * base64 encoded audio data - */ - audio: string; - /** - * type of data PCM data that's sent to the inference server as raw array - */ - dtype?: "uint8" | "float32" | "float64"; -}; -interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output { - /** - * if true, end-of-turn was detected - */ - is_complete?: boolean; - /** - * probability of the end-of-turn detection - */ - probability?: number; -} -declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { - inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; - postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; -} -type Ai_Cf_Openai_Gpt_Oss_120B_Input = GPT_OSS_120B_Responses | GPT_OSS_120B_Responses_Async; -interface GPT_OSS_120B_Responses { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; -} -interface GPT_OSS_120B_Responses_Async { - requests: { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; - }[]; -} -type Ai_Cf_Openai_Gpt_Oss_120B_Output = {} | (string & NonNullable); -declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { - inputs: Ai_Cf_Openai_Gpt_Oss_120B_Input; - postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_120B_Output; -} -type Ai_Cf_Openai_Gpt_Oss_20B_Input = GPT_OSS_20B_Responses | GPT_OSS_20B_Responses_Async; -interface GPT_OSS_20B_Responses { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; -} -interface GPT_OSS_20B_Responses_Async { - requests: { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; - }[]; -} -type Ai_Cf_Openai_Gpt_Oss_20B_Output = {} | (string & NonNullable); -declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { - inputs: Ai_Cf_Openai_Gpt_Oss_20B_Input; - postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_20B_Output; -} -interface Ai_Cf_Leonardo_Phoenix_1_0_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt - */ - guidance?: number; - /** - * Random seed for reproducibility of the image generation - */ - seed?: number; - /** - * The height of the generated image in pixels - */ - height?: number; - /** - * The width of the generated image in pixels - */ - width?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - num_steps?: number; - /** - * Specify what to exclude from the generated images - */ - negative_prompt?: string; -} -/** - * The generated image in JPEG format - */ -type Ai_Cf_Leonardo_Phoenix_1_0_Output = string; -declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 { - inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input; - postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output; -} -interface Ai_Cf_Leonardo_Lucid_Origin_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt - */ - guidance?: number; - /** - * Random seed for reproducibility of the image generation - */ - seed?: number; - /** - * The height of the generated image in pixels - */ - height?: number; - /** - * The width of the generated image in pixels - */ - width?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - num_steps?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - steps?: number; -} -interface Ai_Cf_Leonardo_Lucid_Origin_Output { - /** - * The generated image in Base64 format. - */ - image?: string; -} -declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin { - inputs: Ai_Cf_Leonardo_Lucid_Origin_Input; - postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output; -} -interface Ai_Cf_Deepgram_Aura_1_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: "angus" | "asteria" | "arcas" | "orion" | "orpheus" | "athena" | "luna" | "zeus" | "perseus" | "helios" | "hera" | "stella"; - /** - * Encoding of the output audio. - */ - encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: "none" | "wav" | "ogg"; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; -} -/** - * The generated audio in MP3 format - */ -type Ai_Cf_Deepgram_Aura_1_Output = string; -declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { - inputs: Ai_Cf_Deepgram_Aura_1_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; -} -interface AiModels { - "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; - "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; - "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage; - "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage; - "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage; - "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage; - "@cf/myshell-ai/melotts": BaseAiTextToSpeech; - "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings; - "@cf/microsoft/resnet-50": BaseAiImageClassification; - "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration; - "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration; - "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration; - "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration; - "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration; - "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration; - "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration; - "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration; - "@hf/thebloke/llamaguard-7b-awq": BaseAiTextGeneration; - "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration; - "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration; - "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration; - "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration; - "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration; - "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration; - "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration; - "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration; - "@cf/microsoft/phi-2": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration; - "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration; - "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration; - "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration; - "@hf/google/gemma-7b-it": BaseAiTextGeneration; - "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration; - "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration; - "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration; - "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration; - "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; - "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; - "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; - "@hf/meta-llama/meta-llama-3-8b-instruct": BaseAiTextGeneration; - "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; - "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; - "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; - "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; - "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; - "@cf/facebook/bart-large-cnn": BaseAiSummarization; - "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; - "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; - "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper; - "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B; - "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5; - "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5; - "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; - "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En; - "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; - "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3; - "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; - "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; - "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; - "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B; - "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base; - "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; - "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B; - "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; - "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; - "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; - "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3; - "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; - "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B; - "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B; - "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0; - "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin; - "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1; -} -type AiOptions = { - /** - * Send requests as an asynchronous batch job, only works for supported models - * https://developers.cloudflare.com/workers-ai/features/batch-api - */ - queueRequest?: boolean; - /** - * Establish websocket connections, only works for supported models - */ - websocket?: boolean; - gateway?: GatewayOptions; - returnRawResponse?: boolean; - prefix?: string; - extraHeaders?: object; -}; -type AiModelsSearchParams = { - author?: string; - hide_experimental?: boolean; - page?: number; - per_page?: number; - search?: string; - source?: number; - task?: string; -}; -type AiModelsSearchObject = { - id: string; - source: number; - name: string; - description: string; - task: { - id: string; - name: string; - description: string; - }; - tags: string[]; - properties: { - property_id: string; - value: string; - }[]; -}; -interface InferenceUpstreamError extends Error { -} -interface AiInternalError extends Error { -} -type AiModelListType = Record; -declare abstract class Ai { - aiGatewayLogId: string | null; - gateway(gatewayId: string): AiGateway; - autorag(autoragId: string): AutoRAG; - run(model: Name, inputs: InputOptions, options?: Options): Promise; - models(params?: AiModelsSearchParams): Promise; - toMarkdown(): ToMarkdownService; - toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; - toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; -} -type GatewayRetries = { - maxAttempts?: 1 | 2 | 3 | 4 | 5; - retryDelayMs?: number; - backoff?: 'constant' | 'linear' | 'exponential'; -}; -type GatewayOptions = { - id: string; - cacheKey?: string; - cacheTtl?: number; - skipCache?: boolean; - metadata?: Record; - collectLog?: boolean; - eventId?: string; - requestTimeoutMs?: number; - retries?: GatewayRetries; -}; -type UniversalGatewayOptions = Exclude & { - /** - ** @deprecated - */ - id?: string; -}; -type AiGatewayPatchLog = { - score?: number | null; - feedback?: -1 | 1 | null; - metadata?: Record | null; -}; -type AiGatewayLog = { - id: string; - provider: string; - model: string; - model_type?: string; - path: string; - duration: number; - request_type?: string; - request_content_type?: string; - status_code: number; - response_content_type?: string; - success: boolean; - cached: boolean; - tokens_in?: number; - tokens_out?: number; - metadata?: Record; - step?: number; - cost?: number; - custom_cost?: boolean; - request_size: number; - request_head?: string; - request_head_complete: boolean; - response_size: number; - response_head?: string; - response_head_complete: boolean; - created_at: Date; -}; -type AIGatewayProviders = 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly'; -type AIGatewayHeaders = { - 'cf-aig-metadata': Record | string; - 'cf-aig-custom-cost': { - per_token_in?: number; - per_token_out?: number; - } | { - total_cost?: number; - } | string; - 'cf-aig-cache-ttl': number | string; - 'cf-aig-skip-cache': boolean | string; - 'cf-aig-cache-key': string; - 'cf-aig-event-id': string; - 'cf-aig-request-timeout': number | string; - 'cf-aig-max-attempts': number | string; - 'cf-aig-retry-delay': number | string; - 'cf-aig-backoff': string; - 'cf-aig-collect-log': boolean | string; - Authorization: string; - 'Content-Type': string; - [key: string]: string | number | boolean | object; -}; -type AIGatewayUniversalRequest = { - provider: AIGatewayProviders | string; // eslint-disable-line - endpoint: string; - headers: Partial; - query: unknown; -}; -interface AiGatewayInternalError extends Error { -} -interface AiGatewayLogNotFound extends Error { -} -declare abstract class AiGateway { - patchLog(logId: string, data: AiGatewayPatchLog): Promise; - getLog(logId: string): Promise; - run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: { - gateway?: UniversalGatewayOptions; - extraHeaders?: object; - }): Promise; - getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line -} -interface AutoRAGInternalError extends Error { -} -interface AutoRAGNotFoundError extends Error { -} -interface AutoRAGUnauthorizedError extends Error { -} -interface AutoRAGNameNotSetError extends Error { -} -type ComparisonFilter = { - key: string; - type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; - value: string | number | boolean; -}; -type CompoundFilter = { - type: 'and' | 'or'; - filters: ComparisonFilter[]; -}; -type AutoRagSearchRequest = { - query: string; - filters?: CompoundFilter | ComparisonFilter; - max_num_results?: number; - ranking_options?: { - ranker?: string; - score_threshold?: number; - }; - reranking?: { - enabled?: boolean; - model?: string; - }; - rewrite_query?: boolean; -}; -type AutoRagAiSearchRequest = AutoRagSearchRequest & { - stream?: boolean; - system_prompt?: string; -}; -type AutoRagAiSearchRequestStreaming = Omit & { - stream: true; -}; -type AutoRagSearchResponse = { - object: 'vector_store.search_results.page'; - search_query: string; - data: { - file_id: string; - filename: string; - score: number; - attributes: Record; - content: { - type: 'text'; - text: string; - }[]; - }[]; - has_more: boolean; - next_page: string | null; -}; -type AutoRagListResponse = { - id: string; - enable: boolean; - type: string; - source: string; - vectorize_name: string; - paused: boolean; - status: string; -}[]; -type AutoRagAiSearchResponse = AutoRagSearchResponse & { - response: string; -}; -declare abstract class AutoRAG { - list(): Promise; - search(params: AutoRagSearchRequest): Promise; - aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; - aiSearch(params: AutoRagAiSearchRequest): Promise; - aiSearch(params: AutoRagAiSearchRequest): Promise; -} -interface BasicImageTransformations { - /** - * Maximum width in image pixels. The value must be an integer. - */ - width?: number; - /** - * Maximum height in image pixels. The value must be an integer. - */ - height?: number; - /** - * Resizing mode as a string. It affects interpretation of width and height - * options: - * - scale-down: Similar to contain, but the image is never enlarged. If - * the image is larger than given width or height, it will be resized. - * Otherwise its original size will be kept. - * - contain: Resizes to maximum size that fits within the given width and - * height. If only a single dimension is given (e.g. only width), the - * image will be shrunk or enlarged to exactly match that dimension. - * Aspect ratio is always preserved. - * - cover: Resizes (shrinks or enlarges) to fill the entire area of width - * and height. If the image has an aspect ratio different from the ratio - * of width and height, it will be cropped to fit. - * - crop: The image will be shrunk and cropped to fit within the area - * specified by width and height. The image will not be enlarged. For images - * smaller than the given dimensions it's the same as scale-down. For - * images larger than the given dimensions, it's the same as cover. - * See also trim. - * - pad: Resizes to the maximum size that fits within the given width and - * height, and then fills the remaining area with a background color - * (white by default). Use of this mode is not recommended, as the same - * effect can be more efficiently achieved with the contain mode and the - * CSS object-fit: contain property. - * - squeeze: Stretches and deforms to the width and height given, even if it - * breaks aspect ratio - */ - fit?: "scale-down" | "contain" | "cover" | "crop" | "pad" | "squeeze"; - /** - * Image segmentation using artificial intelligence models. Sets pixels not - * within selected segment area to transparent e.g "foreground" sets every - * background pixel as transparent. - */ - segment?: "foreground"; - /** - * When cropping with fit: "cover", this defines the side or point that should - * be left uncropped. The value is either a string - * "left", "right", "top", "bottom", "auto", or "center" (the default), - * or an object {x, y} containing focal point coordinates in the original - * image expressed as fractions ranging from 0.0 (top or left) to 1.0 - * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will - * crop bottom or left and right sides as necessary, but won’t crop anything - * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to - * preserve as much as possible around a point at 20% of the height of the - * source image. - */ - gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates; - /** - * Background color to add underneath the image. Applies only to images with - * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), - * hsl(…), etc.) - */ - background?: string; - /** - * Number of degrees (90, 180, 270) to rotate the image by. width and height - * options refer to axes after rotation. - */ - rotate?: 0 | 90 | 180 | 270 | 360; -} -interface BasicImageTransformationsGravityCoordinates { - x?: number; - y?: number; - mode?: 'remainder' | 'box-center'; -} -/** - * In addition to the properties you can set in the RequestInit dict - * that you pass as an argument to the Request constructor, you can - * set certain properties of a `cf` object to control how Cloudflare - * features are applied to that new Request. - * - * Note: Currently, these properties cannot be tested in the - * playground. - */ -interface RequestInitCfProperties extends Record { - cacheEverything?: boolean; - /** - * A request's cache key is what determines if two requests are - * "the same" for caching purposes. If a request has the same cache key - * as some previous request, then we can serve the same cached response for - * both. (e.g. 'some-key') - * - * Only available for Enterprise customers. - */ - cacheKey?: string; - /** - * This allows you to append additional Cache-Tag response headers - * to the origin response without modifications to the origin server. - * This will allow for greater control over the Purge by Cache Tag feature - * utilizing changes only in the Workers process. - * - * Only available for Enterprise customers. - */ - cacheTags?: string[]; - /** - * Force response to be cached for a given number of seconds. (e.g. 300) - */ - cacheTtl?: number; - /** - * Force response to be cached for a given number of seconds based on the Origin status code. - * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) - */ - cacheTtlByStatus?: Record; - scrapeShield?: boolean; - apps?: boolean; - image?: RequestInitCfPropertiesImage; - minify?: RequestInitCfPropertiesImageMinify; - mirage?: boolean; - polish?: "lossy" | "lossless" | "off"; - r2?: RequestInitCfPropertiesR2; - /** - * Redirects the request to an alternate origin server. You can use this, - * for example, to implement load balancing across several origins. - * (e.g.us-east.example.com) - * - * Note - For security reasons, the hostname set in resolveOverride must - * be proxied on the same Cloudflare zone of the incoming request. - * Otherwise, the setting is ignored. CNAME hosts are allowed, so to - * resolve to a host under a different domain or a DNS only domain first - * declare a CNAME record within your own zone’s DNS mapping to the - * external hostname, set proxy on Cloudflare, then set resolveOverride - * to point to that CNAME record. - */ - resolveOverride?: string; -} -interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations { - /** - * Absolute URL of the image file to use for the drawing. It can be any of - * the supported file formats. For drawing of watermarks or non-rectangular - * overlays we recommend using PNG or WebP images. - */ - url: string; - /** - * Floating-point number between 0 (transparent) and 1 (opaque). - * For example, opacity: 0.5 makes overlay semitransparent. - */ - opacity?: number; - /** - * - If set to true, the overlay image will be tiled to cover the entire - * area. This is useful for stock-photo-like watermarks. - * - If set to "x", the overlay image will be tiled horizontally only - * (form a line). - * - If set to "y", the overlay image will be tiled vertically only - * (form a line). - */ - repeat?: true | "x" | "y"; - /** - * Position of the overlay image relative to a given edge. Each property is - * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 - * positions left side of the overlay 10 pixels from the left edge of the - * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom - * of the background image. - * - * Setting both left & right, or both top & bottom is an error. - * - * If no position is specified, the image will be centered. - */ - top?: number; - left?: number; - bottom?: number; - right?: number; -} -interface RequestInitCfPropertiesImage extends BasicImageTransformations { - /** - * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it - * easier to specify higher-DPI sizes in . - */ - dpr?: number; - /** - * Allows you to trim your image. Takes dpr into account and is performed before - * resizing or rotation. - * - * It can be used as: - * - left, top, right, bottom - it will specify the number of pixels to cut - * off each side - * - width, height - the width/height you'd like to end up with - can be used - * in combination with the properties above - * - border - this will automatically trim the surroundings of an image based on - * it's color. It consists of three properties: - * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit) - * - tolerance: difference from color to treat as color - * - keep: the number of pixels of border to keep - */ - trim?: "border" | { - top?: number; - bottom?: number; - left?: number; - right?: number; - width?: number; - height?: number; - border?: boolean | { - color?: string; - tolerance?: number; - keep?: number; - }; - }; - /** - * Quality setting from 1-100 (useful values are in 60-90 range). Lower values - * make images look worse, but load faster. The default is 85. It applies only - * to JPEG and WebP images. It doesn’t have any effect on PNG. - */ - quality?: number | "low" | "medium-low" | "medium-high" | "high"; - /** - * Output format to generate. It can be: - * - avif: generate images in AVIF format. - * - webp: generate images in Google WebP format. Set quality to 100 to get - * the WebP-lossless format. - * - json: instead of generating an image, outputs information about the - * image, in JSON format. The JSON object will contain image size - * (before and after resizing), source image’s MIME type, file size, etc. - * - jpeg: generate images in JPEG format. - * - png: generate images in PNG format. - */ - format?: "avif" | "webp" | "json" | "jpeg" | "png" | "baseline-jpeg" | "png-force" | "svg"; - /** - * Whether to preserve animation frames from input files. Default is true. - * Setting it to false reduces animations to still images. This setting is - * recommended when enlarging images or processing arbitrary user content, - * because large GIF animations can weigh tens or even hundreds of megabytes. - * It is also useful to set anim:false when using format:"json" to get the - * response quicker without the number of frames. - */ - anim?: boolean; - /** - * What EXIF data should be preserved in the output image. Note that EXIF - * rotation and embedded color profiles are always applied ("baked in" into - * the image), and aren't affected by this option. Note that if the Polish - * feature is enabled, all metadata may have been removed already and this - * option may have no effect. - * - keep: Preserve most of EXIF metadata, including GPS location if there's - * any. - * - copyright: Only keep the copyright tag, and discard everything else. - * This is the default behavior for JPEG files. - * - none: Discard all invisible EXIF metadata. Currently WebP and PNG - * output formats always discard metadata. - */ - metadata?: "keep" | "copyright" | "none"; - /** - * Strength of sharpening filter to apply to the image. Floating-point - * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a - * recommended value for downscaled images. - */ - sharpen?: number; - /** - * Radius of a blur filter (approximate gaussian). Maximum supported radius - * is 250. - */ - blur?: number; - /** - * Overlays are drawn in the order they appear in the array (last array - * entry is the topmost layer). - */ - draw?: RequestInitCfPropertiesImageDraw[]; - /** - * Fetching image from authenticated origin. Setting this property will - * pass authentication headers (Authorization, Cookie, etc.) through to - * the origin. - */ - "origin-auth"?: "share-publicly"; - /** - * Adds a border around the image. The border is added after resizing. Border - * width takes dpr into account, and can be specified either using a single - * width property, or individually for each side. - */ - border?: { - color: string; - width: number; - } | { - color: string; - top: number; - right: number; - bottom: number; - left: number; - }; - /** - * Increase brightness by a factor. A value of 1.0 equals no change, a value - * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. - * 0 is ignored. - */ - brightness?: number; - /** - * Increase contrast by a factor. A value of 1.0 equals no change, a value of - * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is - * ignored. - */ - contrast?: number; - /** - * Increase exposure by a factor. A value of 1.0 equals no change, a value of - * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. - */ - gamma?: number; - /** - * Increase contrast by a factor. A value of 1.0 equals no change, a value of - * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is - * ignored. - */ - saturation?: number; - /** - * Flips the images horizontally, vertically, or both. Flipping is applied before - * rotation, so if you apply flip=h,rotate=90 then the image will be flipped - * horizontally, then rotated by 90 degrees. - */ - flip?: 'h' | 'v' | 'hv'; - /** - * Slightly reduces latency on a cache miss by selecting a - * quickest-to-compress file format, at a cost of increased file size and - * lower image quality. It will usually override the format option and choose - * JPEG over WebP or AVIF. We do not recommend using this option, except in - * unusual circumstances like resizing uncacheable dynamically-generated - * images. - */ - compression?: "fast"; -} -interface RequestInitCfPropertiesImageMinify { - javascript?: boolean; - css?: boolean; - html?: boolean; -} -interface RequestInitCfPropertiesR2 { - /** - * Colo id of bucket that an object is stored in - */ - bucketColoId?: number; -} -/** - * Request metadata provided by Cloudflare's edge. - */ -type IncomingRequestCfProperties = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield; -interface IncomingRequestCfPropertiesBase extends Record { - /** - * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. - * - * @example 395747 - */ - asn?: number; - /** - * The organization which owns the ASN of the incoming request. - * - * @example "Google Cloud" - */ - asOrganization?: string; - /** - * The original value of the `Accept-Encoding` header if Cloudflare modified it. - * - * @example "gzip, deflate, br" - */ - clientAcceptEncoding?: string; - /** - * The number of milliseconds it took for the request to reach your worker. - * - * @example 22 - */ - clientTcpRtt?: number; - /** - * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) - * airport code of the data center that the request hit. - * - * @example "DFW" - */ - colo: string; - /** - * Represents the upstream's response to a - * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) - * from cloudflare. - * - * For workers with no upstream, this will always be `1`. - * - * @example 3 - */ - edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; - /** - * The HTTP Protocol the request used. - * - * @example "HTTP/2" - */ - httpProtocol: string; - /** - * The browser-requested prioritization information in the request object. - * - * If no information was set, defaults to the empty string `""` - * - * @example "weight=192;exclusive=0;group=3;group-weight=127" - * @default "" - */ - requestPriority: string; - /** - * The TLS version of the connection to Cloudflare. - * In requests served over plaintext (without TLS), this property is the empty string `""`. - * - * @example "TLSv1.3" - */ - tlsVersion: string; - /** - * The cipher for the connection to Cloudflare. - * In requests served over plaintext (without TLS), this property is the empty string `""`. - * - * @example "AEAD-AES128-GCM-SHA256" - */ - tlsCipher: string; - /** - * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. - * - * If the incoming request was served over plaintext (without TLS) this field is undefined. - */ - tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; -} -interface IncomingRequestCfPropertiesBotManagementBase { - /** - * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, - * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). - * - * @example 54 - */ - score: number; - /** - * A boolean value that is true if the request comes from a good bot, like Google or Bing. - * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). - */ - verifiedBot: boolean; - /** - * A boolean value that is true if the request originates from a - * Cloudflare-verified proxy service. - */ - corporateProxy: boolean; - /** - * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. - */ - staticResource: boolean; - /** - * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). - */ - detectionIds: number[]; -} -interface IncomingRequestCfPropertiesBotManagement { - /** - * Results of Cloudflare's Bot Management analysis - */ - botManagement: IncomingRequestCfPropertiesBotManagementBase; - /** - * Duplicate of `botManagement.score`. - * - * @deprecated - */ - clientTrustScore: number; -} -interface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement { - /** - * Results of Cloudflare's Bot Management analysis - */ - botManagement: IncomingRequestCfPropertiesBotManagementBase & { - /** - * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients - * across different destination IPs, Ports, and X509 certificates. - */ - ja3Hash: string; - }; -} -interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise { - /** - * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). - * - * This field is only present if you have Cloudflare for SaaS enabled on your account - * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). - */ - hostMetadata?: HostMetadata; -} -interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { - /** - * Information about the client certificate presented to Cloudflare. - * - * This is populated when the incoming request is served over TLS using - * either Cloudflare Access or API Shield (mTLS) - * and the presented SSL certificate has a valid - * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) - * (i.e., not `null` or `""`). - * - * Otherwise, a set of placeholder values are used. - * - * The property `certPresented` will be set to `"1"` when - * the object is populated (i.e. the above conditions were met). - */ - tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; -} -/** - * Metadata about the request's TLS handshake - */ -interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { - /** - * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" - */ - clientHandshake: string; - /** - * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" - */ - serverHandshake: string; - /** - * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" - */ - clientFinished: string; - /** - * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" - */ - serverFinished: string; -} -/** - * Geographic data about the request's origin. - */ -interface IncomingRequestCfPropertiesGeographicInformation { - /** - * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. - * - * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. - * - * If Cloudflare is unable to determine where the request originated this property is omitted. - * - * The country code `"T1"` is used for requests originating on TOR. - * - * @example "GB" - */ - country?: Iso3166Alpha2Code | "T1"; - /** - * If present, this property indicates that the request originated in the EU - * - * @example "1" - */ - isEUCountry?: "1"; - /** - * A two-letter code indicating the continent the request originated from. - * - * @example "AN" - */ - continent?: ContinentCode; - /** - * The city the request originated from - * - * @example "Austin" - */ - city?: string; - /** - * Postal code of the incoming request - * - * @example "78701" - */ - postalCode?: string; - /** - * Latitude of the incoming request - * - * @example "30.27130" - */ - latitude?: string; - /** - * Longitude of the incoming request - * - * @example "-97.74260" - */ - longitude?: string; - /** - * Timezone of the incoming request - * - * @example "America/Chicago" - */ - timezone?: string; - /** - * If known, the ISO 3166-2 name for the first level region associated with - * the IP address of the incoming request - * - * @example "Texas" - */ - region?: string; - /** - * If known, the ISO 3166-2 code for the first-level region associated with - * the IP address of the incoming request - * - * @example "TX" - */ - regionCode?: string; - /** - * Metro code (DMA) of the incoming request - * - * @example "635" - */ - metroCode?: string; -} -/** Data about the incoming request's TLS certificate */ -interface IncomingRequestCfPropertiesTLSClientAuth { - /** Always `"1"`, indicating that the certificate was presented */ - certPresented: "1"; - /** - * Result of certificate verification. - * - * @example "FAILED:self signed certificate" - */ - certVerified: Exclude; - /** The presented certificate's revokation status. - * - * - A value of `"1"` indicates the certificate has been revoked - * - A value of `"0"` indicates the certificate has not been revoked - */ - certRevoked: "1" | "0"; - /** - * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) - * - * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certIssuerDN: string; - /** - * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) - * - * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certSubjectDN: string; - /** - * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) - * - * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certIssuerDNRFC2253: string; - /** - * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) - * - * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certSubjectDNRFC2253: string; - /** The certificate issuer's distinguished name (legacy policies) */ - certIssuerDNLegacy: string; - /** The certificate subject's distinguished name (legacy policies) */ - certSubjectDNLegacy: string; - /** - * The certificate's serial number - * - * @example "00936EACBE07F201DF" - */ - certSerial: string; - /** - * The certificate issuer's serial number - * - * @example "2489002934BDFEA34" - */ - certIssuerSerial: string; - /** - * The certificate's Subject Key Identifier - * - * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" - */ - certSKI: string; - /** - * The certificate issuer's Subject Key Identifier - * - * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" - */ - certIssuerSKI: string; - /** - * The certificate's SHA-1 fingerprint - * - * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" - */ - certFingerprintSHA1: string; - /** - * The certificate's SHA-256 fingerprint - * - * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" - */ - certFingerprintSHA256: string; - /** - * The effective starting date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" - */ - certNotBefore: string; - /** - * The effective expiration date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" - */ - certNotAfter: string; -} -/** Placeholder values for TLS Client Authorization */ -interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { - certPresented: "0"; - certVerified: "NONE"; - certRevoked: "0"; - certIssuerDN: ""; - certSubjectDN: ""; - certIssuerDNRFC2253: ""; - certSubjectDNRFC2253: ""; - certIssuerDNLegacy: ""; - certSubjectDNLegacy: ""; - certSerial: ""; - certIssuerSerial: ""; - certSKI: ""; - certIssuerSKI: ""; - certFingerprintSHA1: ""; - certFingerprintSHA256: ""; - certNotBefore: ""; - certNotAfter: ""; -} -/** Possible outcomes of TLS verification */ -declare type CertVerificationStatus = -/** Authentication succeeded */ -"SUCCESS" -/** No certificate was presented */ - | "NONE" -/** Failed because the certificate was self-signed */ - | "FAILED:self signed certificate" -/** Failed because the certificate failed a trust chain check */ - | "FAILED:unable to verify the first certificate" -/** Failed because the certificate not yet valid */ - | "FAILED:certificate is not yet valid" -/** Failed because the certificate is expired */ - | "FAILED:certificate has expired" -/** Failed for another unspecified reason */ - | "FAILED"; -/** - * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. - */ -declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = 0 /** Unknown */ | 1 /** no keepalives (not found) */ | 2 /** no connection re-use, opening keepalive connection failed */ | 3 /** no connection re-use, keepalive accepted and saved */ | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ | 5; /** connection re-use, accepted by the origin server */ -/** ISO 3166-1 Alpha-2 codes */ -declare type Iso3166Alpha2Code = "AD" | "AE" | "AF" | "AG" | "AI" | "AL" | "AM" | "AO" | "AQ" | "AR" | "AS" | "AT" | "AU" | "AW" | "AX" | "AZ" | "BA" | "BB" | "BD" | "BE" | "BF" | "BG" | "BH" | "BI" | "BJ" | "BL" | "BM" | "BN" | "BO" | "BQ" | "BR" | "BS" | "BT" | "BV" | "BW" | "BY" | "BZ" | "CA" | "CC" | "CD" | "CF" | "CG" | "CH" | "CI" | "CK" | "CL" | "CM" | "CN" | "CO" | "CR" | "CU" | "CV" | "CW" | "CX" | "CY" | "CZ" | "DE" | "DJ" | "DK" | "DM" | "DO" | "DZ" | "EC" | "EE" | "EG" | "EH" | "ER" | "ES" | "ET" | "FI" | "FJ" | "FK" | "FM" | "FO" | "FR" | "GA" | "GB" | "GD" | "GE" | "GF" | "GG" | "GH" | "GI" | "GL" | "GM" | "GN" | "GP" | "GQ" | "GR" | "GS" | "GT" | "GU" | "GW" | "GY" | "HK" | "HM" | "HN" | "HR" | "HT" | "HU" | "ID" | "IE" | "IL" | "IM" | "IN" | "IO" | "IQ" | "IR" | "IS" | "IT" | "JE" | "JM" | "JO" | "JP" | "KE" | "KG" | "KH" | "KI" | "KM" | "KN" | "KP" | "KR" | "KW" | "KY" | "KZ" | "LA" | "LB" | "LC" | "LI" | "LK" | "LR" | "LS" | "LT" | "LU" | "LV" | "LY" | "MA" | "MC" | "MD" | "ME" | "MF" | "MG" | "MH" | "MK" | "ML" | "MM" | "MN" | "MO" | "MP" | "MQ" | "MR" | "MS" | "MT" | "MU" | "MV" | "MW" | "MX" | "MY" | "MZ" | "NA" | "NC" | "NE" | "NF" | "NG" | "NI" | "NL" | "NO" | "NP" | "NR" | "NU" | "NZ" | "OM" | "PA" | "PE" | "PF" | "PG" | "PH" | "PK" | "PL" | "PM" | "PN" | "PR" | "PS" | "PT" | "PW" | "PY" | "QA" | "RE" | "RO" | "RS" | "RU" | "RW" | "SA" | "SB" | "SC" | "SD" | "SE" | "SG" | "SH" | "SI" | "SJ" | "SK" | "SL" | "SM" | "SN" | "SO" | "SR" | "SS" | "ST" | "SV" | "SX" | "SY" | "SZ" | "TC" | "TD" | "TF" | "TG" | "TH" | "TJ" | "TK" | "TL" | "TM" | "TN" | "TO" | "TR" | "TT" | "TV" | "TW" | "TZ" | "UA" | "UG" | "UM" | "US" | "UY" | "UZ" | "VA" | "VC" | "VE" | "VG" | "VI" | "VN" | "VU" | "WF" | "WS" | "YE" | "YT" | "ZA" | "ZM" | "ZW"; -/** The 2-letter continent codes Cloudflare uses */ -declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; -type CfProperties = IncomingRequestCfProperties | RequestInitCfProperties; -interface D1Meta { - duration: number; - size_after: number; - rows_read: number; - rows_written: number; - last_row_id: number; - changed_db: boolean; - changes: number; - /** - * The region of the database instance that executed the query. - */ - served_by_region?: string; - /** - * True if-and-only-if the database instance that executed the query was the primary. - */ - served_by_primary?: boolean; - timings?: { - /** - * The duration of the SQL query execution by the database instance. It doesn't include any network time. - */ - sql_duration_ms: number; - }; - /** - * Number of total attempts to execute the query, due to automatic retries. - * Note: All other fields in the response like `timings` only apply to the last attempt. - */ - total_attempts?: number; -} -interface D1Response { - success: true; - meta: D1Meta & Record; - error?: never; -} -type D1Result = D1Response & { - results: T[]; -}; -interface D1ExecResult { - count: number; - duration: number; -} -type D1SessionConstraint = -// Indicates that the first query should go to the primary, and the rest queries -// using the same D1DatabaseSession will go to any replica that is consistent with -// the bookmark maintained by the session (returned by the first query). -'first-primary' -// Indicates that the first query can go anywhere (primary or replica), and the rest queries -// using the same D1DatabaseSession will go to any replica that is consistent with -// the bookmark maintained by the session (returned by the first query). - | 'first-unconstrained'; -type D1SessionBookmark = string; -declare abstract class D1Database { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; - exec(query: string): Promise; - /** - * Creates a new D1 Session anchored at the given constraint or the bookmark. - * All queries executed using the created session will have sequential consistency, - * meaning that all writes done through the session will be visible in subsequent reads. - * - * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session. - */ - withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession; - /** - * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases. - */ - dump(): Promise; -} -declare abstract class D1DatabaseSession { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; - /** - * @returns The latest session bookmark across all executed queries on the session. - * If no query has been executed yet, `null` is returned. - */ - getBookmark(): D1SessionBookmark | null; -} -declare abstract class D1PreparedStatement { - bind(...values: unknown[]): D1PreparedStatement; - first(colName: string): Promise; - first>(): Promise; - run>(): Promise>; - all>(): Promise>; - raw(options: { - columnNames: true; - }): Promise<[ - string[], - ...T[] - ]>; - raw(options?: { - columnNames?: false; - }): Promise; -} -// `Disposable` was added to TypeScript's standard lib types in version 5.2. -// To support older TypeScript versions, define an empty `Disposable` interface. -// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, -// but this will ensure type checking on older versions still passes. -// TypeScript's interface merging will ensure our empty interface is effectively -// ignored when `Disposable` is included in the standard lib. -interface Disposable { -} -/** - * An email message that can be sent from a Worker. - */ -interface EmailMessage { - /** - * Envelope From attribute of the email message. - */ - readonly from: string; - /** - * Envelope To attribute of the email message. - */ - readonly to: string; -} -/** - * An email message that is sent to a consumer Worker and can be rejected/forwarded. - */ -interface ForwardableEmailMessage extends EmailMessage { - /** - * Stream of the email message content. - */ - readonly raw: ReadableStream; - /** - * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). - */ - readonly headers: Headers; - /** - * Size of the email message content. - */ - readonly rawSize: number; - /** - * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. - * @param reason The reject reason. - * @returns void - */ - setReject(reason: string): void; - /** - * Forward this email message to a verified destination address of the account. - * @param rcptTo Verified destination address. - * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). - * @returns A promise that resolves when the email message is forwarded. - */ - forward(rcptTo: string, headers?: Headers): Promise; - /** - * Reply to the sender of this email message with a new EmailMessage object. - * @param message The reply message. - * @returns A promise that resolves when the email message is replied. - */ - reply(message: EmailMessage): Promise; -} -/** - * A binding that allows a Worker to send email messages. - */ -interface SendEmail { - send(message: EmailMessage): Promise; -} -declare abstract class EmailEvent extends ExtendableEvent { - readonly message: ForwardableEmailMessage; -} -declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; -declare module "cloudflare:email" { - let _EmailMessage: { - prototype: EmailMessage; - new (from: string, to: string, raw: ReadableStream | string): EmailMessage; - }; - export { _EmailMessage as EmailMessage }; -} -/** - * Hello World binding to serve as an explanatory example. DO NOT USE - */ -interface HelloWorldBinding { - /** - * Retrieve the current stored value - */ - get(): Promise<{ - value: string; - ms?: number; - }>; - /** - * Set a new stored value - */ - set(value: string): Promise; -} -interface Hyperdrive { - /** - * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. - * - * Calling this method returns an idential socket to if you call - * `connect("host:port")` using the `host` and `port` fields from this object. - * Pick whichever approach works better with your preferred DB client library. - * - * Note that this socket is not yet authenticated -- it's expected that your - * code (or preferably, the client library of your choice) will authenticate - * using the information in this class's readonly fields. - */ - connect(): Socket; - /** - * A valid DB connection string that can be passed straight into the typical - * client library/driver/ORM. This will typically be the easiest way to use - * Hyperdrive. - */ - readonly connectionString: string; - /* - * A randomly generated hostname that is only valid within the context of the - * currently running Worker which, when passed into `connect()` function from - * the "cloudflare:sockets" module, will connect to the Hyperdrive instance - * for your database. - */ - readonly host: string; - /* - * The port that must be paired the the host field when connecting. - */ - readonly port: number; - /* - * The username to use when authenticating to your database via Hyperdrive. - * Unlike the host and password, this will be the same every time - */ - readonly user: string; - /* - * The randomly generated password to use when authenticating to your - * database via Hyperdrive. Like the host field, this password is only valid - * within the context of the currently running Worker instance from which - * it's read. - */ - readonly password: string; - /* - * The name of the database to connect to. - */ - readonly database: string; -} -// Copyright (c) 2024 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 -type ImageInfoResponse = { - format: 'image/svg+xml'; -} | { - format: string; - fileSize: number; - width: number; - height: number; -}; -type ImageTransform = { - width?: number; - height?: number; - background?: string; - blur?: number; - border?: { - color?: string; - width?: number; - } | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - brightness?: number; - contrast?: number; - fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop'; - flip?: 'h' | 'v' | 'hv'; - gamma?: number; - segment?: 'foreground'; - gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | { - x?: number; - y?: number; - mode: 'remainder' | 'box-center'; - }; - rotate?: 0 | 90 | 180 | 270; - saturation?: number; - sharpen?: number; - trim?: 'border' | { - top?: number; - bottom?: number; - left?: number; - right?: number; - width?: number; - height?: number; - border?: boolean | { - color?: string; - tolerance?: number; - keep?: number; - }; - }; -}; -type ImageDrawOptions = { - opacity?: number; - repeat?: boolean | string; - top?: number; - left?: number; - bottom?: number; - right?: number; -}; -type ImageInputOptions = { - encoding?: 'base64'; -}; -type ImageOutputOptions = { - format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba'; - quality?: number; - background?: string; - anim?: boolean; -}; -interface ImagesBinding { - /** - * Get image metadata (type, width and height) - * @throws {@link ImagesError} with code 9412 if input is not an image - * @param stream The image bytes - */ - info(stream: ReadableStream, options?: ImageInputOptions): Promise; - /** - * Begin applying a series of transformations to an image - * @param stream The image bytes - * @returns A transform handle - */ - input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; -} -interface ImageTransformer { - /** - * Apply transform next, returning a transform handle. - * You can then apply more transformations, draw, or retrieve the output. - * @param transform - */ - transform(transform: ImageTransform): ImageTransformer; - /** - * Draw an image on this transformer, returning a transform handle. - * You can then apply more transformations, draw, or retrieve the output. - * @param image The image (or transformer that will give the image) to draw - * @param options The options configuring how to draw the image - */ - draw(image: ReadableStream | ImageTransformer, options?: ImageDrawOptions): ImageTransformer; - /** - * Retrieve the image that results from applying the transforms to the - * provided input - * @param options Options that apply to the output e.g. output format - */ - output(options: ImageOutputOptions): Promise; -} -type ImageTransformationOutputOptions = { - encoding?: 'base64'; -}; -interface ImageTransformationResult { - /** - * The image as a response, ready to store in cache or return to users - */ - response(): Response; - /** - * The content type of the returned image - */ - contentType(): string; - /** - * The bytes of the response - */ - image(options?: ImageTransformationOutputOptions): ReadableStream; -} -interface ImagesError extends Error { - readonly code: number; - readonly message: string; - readonly stack?: string; -} -/** - * Media binding for transforming media streams. - * Provides the entry point for media transformation operations. - */ -interface MediaBinding { - /** - * Creates a media transformer from an input stream. - * @param media - The input media bytes - * @returns A MediaTransformer instance for applying transformations - */ - input(media: ReadableStream): MediaTransformer; -} -/** - * Media transformer for applying transformation operations to media content. - * Handles sizing, fitting, and other input transformation parameters. - */ -interface MediaTransformer { - /** - * Applies transformation options to the media content. - * @param transform - Configuration for how the media should be transformed - * @returns A generator for producing the transformed media output - */ - transform(transform: MediaTransformationInputOptions): MediaTransformationGenerator; -} -/** - * Generator for producing media transformation results. - * Configures the output format and parameters for the transformed media. - */ -interface MediaTransformationGenerator { - /** - * Generates the final media output with specified options. - * @param output - Configuration for the output format and parameters - * @returns The final transformation result containing the transformed media - */ - output(output: MediaTransformationOutputOptions): MediaTransformationResult; -} -/** - * Result of a media transformation operation. - * Provides multiple ways to access the transformed media content. - */ -interface MediaTransformationResult { - /** - * Returns the transformed media as a readable stream of bytes. - * @returns A stream containing the transformed media data - */ - media(): ReadableStream; - /** - * Returns the transformed media as an HTTP response object. - * @returns The transformed media as a Response, ready to store in cache or return to users - */ - response(): Response; - /** - * Returns the MIME type of the transformed media. - * @returns The content type string (e.g., 'image/jpeg', 'video/mp4') - */ - contentType(): string; -} -/** - * Configuration options for transforming media input. - * Controls how the media should be resized and fitted. - */ -type MediaTransformationInputOptions = { - /** How the media should be resized to fit the specified dimensions */ - fit?: 'contain' | 'cover' | 'scale-down'; - /** Target width in pixels */ - width?: number; - /** Target height in pixels */ - height?: number; -}; -/** - * Configuration options for Media Transformations output. - * Controls the format, timing, and type of the generated output. - */ -type MediaTransformationOutputOptions = { - /** - * Output mode determining the type of media to generate - */ - mode?: 'video' | 'spritesheet' | 'frame' | 'audio'; - /** Whether to include audio in the output */ - audio?: boolean; - /** - * Starting timestamp for frame extraction or start time for clips. (e.g. '2s'). - */ - time?: string; - /** - * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s'). - */ - duration?: string; - /** - * Number of frames in the spritesheet. - */ - imageCount?: number; - /** - * Output format for the generated media. - */ - format?: 'jpg' | 'png' | 'm4a'; -}; -/** - * Error object for media transformation operations. - * Extends the standard Error interface with additional media-specific information. - */ -interface MediaError extends Error { - readonly code: number; - readonly message: string; - readonly stack?: string; -} -declare module 'cloudflare:node' { - interface NodeStyleServer { - listen(...args: unknown[]): this; - address(): { - port?: number | null | undefined; - }; - } - export function httpServerHandler(port: number): ExportedHandler; - export function httpServerHandler(options: { - port: number; - }): ExportedHandler; - export function httpServerHandler(server: NodeStyleServer): ExportedHandler; -} -type Params

= Record; -type EventContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; - }; - }; - params: Params

; - data: Data; -}; -type PagesFunction = Record> = (context: EventContext) => Response | Promise; -type EventPluginContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; - }; - }; - params: Params

; - data: Data; - pluginArgs: PluginArgs; -}; -type PagesPluginFunction = Record, PluginArgs = unknown> = (context: EventPluginContext) => Response | Promise; -declare module "assets:*" { - export const onRequest: PagesFunction; -} -// Copyright (c) 2022-2023 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 -declare module "cloudflare:pipelines" { - export abstract class PipelineTransformationEntrypoint { - protected env: Env; - protected ctx: ExecutionContext; - constructor(ctx: ExecutionContext, env: Env); - /** - * run recieves an array of PipelineRecord which can be - * transformed and returned to the pipeline - * @param records Incoming records from the pipeline to be transformed - * @param metadata Information about the specific pipeline calling the transformation entrypoint - * @returns A promise containing the transformed PipelineRecord array - */ - public run(records: I[], metadata: PipelineBatchMetadata): Promise; - } - export type PipelineRecord = Record; - export type PipelineBatchMetadata = { - pipelineId: string; - pipelineName: string; - }; - export interface Pipeline { - /** - * The Pipeline interface represents the type of a binding to a Pipeline - * - * @param records The records to send to the pipeline - */ - send(records: T[]): Promise; - } -} -// PubSubMessage represents an incoming PubSub message. -// The message includes metadata about the broker, the client, and the payload -// itself. -// https://developers.cloudflare.com/pub-sub/ -interface PubSubMessage { - // Message ID - readonly mid: number; - // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT - readonly broker: string; - // The MQTT topic the message was sent on. - readonly topic: string; - // The client ID of the client that published this message. - readonly clientId: string; - // The unique identifier (JWT ID) used by the client to authenticate, if token - // auth was used. - readonly jti?: string; - // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker - // received the message from the client. - readonly receivedAt: number; - // An (optional) string with the MIME type of the payload, if set by the - // client. - readonly contentType: string; - // Set to 1 when the payload is a UTF-8 string - // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 - readonly payloadFormatIndicator: number; - // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. - // You can use payloadFormatIndicator to inspect this before decoding. - payload: string | Uint8Array; -} -// JsonWebKey extended by kid parameter -interface JsonWebKeyWithKid extends JsonWebKey { - // Key Identifier of the JWK - readonly kid: string; -} -interface RateLimitOptions { - key: string; -} -interface RateLimitOutcome { - success: boolean; -} -interface RateLimit { - /** - * Rate limit a request based on the provided options. - * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/ - * @returns A promise that resolves with the outcome of the rate limit. - */ - limit(options: RateLimitOptions): Promise; -} -// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need -// to referenced by `Fetcher`. This is included in the "importable" version of the types which -// strips all `module` blocks. -declare namespace Rpc { - // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. - // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. - // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to - // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) - export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND'; - export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND'; - export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND'; - export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND'; - export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND'; - export interface RpcTargetBranded { - [__RPC_TARGET_BRAND]: never; - } - export interface WorkerEntrypointBranded { - [__WORKER_ENTRYPOINT_BRAND]: never; - } - export interface DurableObjectBranded { - [__DURABLE_OBJECT_BRAND]: never; - } - export interface WorkflowEntrypointBranded { - [__WORKFLOW_ENTRYPOINT_BRAND]: never; - } - export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded; - // Types that can be used through `Stub`s - export type Stubable = RpcTargetBranded | ((...args: any[]) => any); - // Types that can be passed over RPC - // The reason for using a generic type here is to build a serializable subset of structured - // cloneable composite types. This allows types defined with the "interface" keyword to pass the - // serializable check as well. Otherwise, only types defined with the "type" keyword would pass. - type Serializable = - // Structured cloneables - BaseType - // Structured cloneable composites - | Map ? Serializable : never, T extends Map ? Serializable : never> | Set ? Serializable : never> | ReadonlyArray ? Serializable : never> | { - [K in keyof T]: K extends number | string ? Serializable : never; - } - // Special types - | Stub - // Serialized as stubs, see `Stubify` - | Stubable; - // Base type for all RPC stubs, including common memory management methods. - // `T` is used as a marker type for unwrapping `Stub`s later. - interface StubBase extends Disposable { - [__RPC_STUB_BRAND]: T; - dup(): this; - } - export type Stub = Provider & StubBase; - // This represents all the types that can be sent as-is over an RPC boundary - type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream | WritableStream | Request | Response | Headers; - // Recursively rewrite all `Stubable` types with `Stub`s - // prettier-ignore - type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { - [key: string | number]: any; - } ? { - [K in keyof T]: Stubify; - } : T; - // Recursively rewrite all `Stub`s with the corresponding `T`s. - // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: - // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. - // prettier-ignore - type Unstubify = T extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { - [key: string | number]: unknown; - } ? { - [K in keyof T]: Unstubify; - } : T; - type UnstubifyAll = { - [I in keyof A]: Unstubify; - }; - // Utility type for adding `Provider`/`Disposable`s to `object` types only. - // Note `unknown & T` is equivalent to `T`. - type MaybeProvider = T extends object ? Provider : unknown; - type MaybeDisposable = T extends object ? Disposable : unknown; - // Type for method return or property on an RPC interface. - // - Stubable types are replaced by stubs. - // - Serializable types are passed by value, with stubable types replaced by stubs - // and a top-level `Disposer`. - // Everything else can't be passed over PRC. - // Technically, we use custom thenables here, but they quack like `Promise`s. - // Intersecting with `(Maybe)Provider` allows pipelining. - // prettier-ignore - type Result = R extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : never; - // Type for method or property on an RPC interface. - // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. - // Unwrapping `Stub`s allows calling with `Stubable` arguments. - // For properties, rewrite types to be `Result`s. - // In each case, unwrap `Promise`s. - type MethodOrProperty = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll

) => Result> : Result>; - // Type for the callable part of an `Provider` if `T` is callable. - // This is intersected with methods/properties. - type MaybeCallableProvider = T extends (...args: any[]) => any ? MethodOrProperty : unknown; - // Base type for all other types providing RPC-like interfaces. - // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. - // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. - export type Provider = MaybeCallableProvider & { - [K in Exclude>]: MethodOrProperty; - }; -} -declare namespace Cloudflare { - // Type of `env`. - // - // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript - // will merge all declarations. - // - // You can use `wrangler types` to generate the `Env` type automatically. - interface Env { - } - // Project-specific parameters used to inform types. - // - // This interface is, again, intended to be declared in project-specific files, and then that - // declaration will be merged with this one. - // - // A project should have a declaration like this: - // - // interface GlobalProps { - // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type - // // of `ctx.exports`. - // mainModule: typeof import("my-main-module"); - // - // // Declares which of the main module's exports are configured with durable storage, and - // // thus should behave as Durable Object namsepace bindings. - // durableNamespaces: "MyDurableObject" | "AnotherDurableObject"; - // } - // - // You can use `wrangler types` to generate `GlobalProps` automatically. - interface GlobalProps { - } - // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not - // present. - type GlobalProp = K extends keyof GlobalProps ? GlobalProps[K] : Default; - // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the - // `mainModule` property. - type MainModule = GlobalProp<"mainModule", {}>; - // The type of ctx.exports, which contains loopback bindings for all top-level exports. - type Exports = { - [K in keyof MainModule]: LoopbackForExport - // If the export is listed in `durableNamespaces`, then it is also a - // DurableObjectNamespace. - & (K extends GlobalProp<"durableNamespaces", never> ? MainModule[K] extends new (...args: any[]) => infer DoInstance ? DoInstance extends Rpc.DurableObjectBranded ? DurableObjectNamespace : DurableObjectNamespace : DurableObjectNamespace : {}); - }; -} -declare namespace CloudflareWorkersModule { - export type RpcStub = Rpc.Stub; - export const RpcStub: { - new (value: T): Rpc.Stub; - }; - export abstract class RpcTarget implements Rpc.RpcTargetBranded { - [Rpc.__RPC_TARGET_BRAND]: never; - } - // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC - export abstract class WorkerEntrypoint implements Rpc.WorkerEntrypointBranded { - [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - email?(message: ForwardableEmailMessage): void | Promise; - fetch?(request: Request): Response | Promise; - queue?(batch: MessageBatch): void | Promise; - scheduled?(controller: ScheduledController): void | Promise; - tail?(events: TraceItem[]): void | Promise; - tailStream?(event: TailStream.TailEvent): TailStream.TailEventHandlerType | Promise; - test?(controller: TestController): void | Promise; - trace?(traces: TraceItem[]): void | Promise; - } - export abstract class DurableObject implements Rpc.DurableObjectBranded { - [Rpc.__DURABLE_OBJECT_BRAND]: never; - protected ctx: DurableObjectState; - protected env: Env; - constructor(ctx: DurableObjectState, env: Env); - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - fetch?(request: Request): Response | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; - } - 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 type WorkflowEvent = { - payload: Readonly; - timestamp: Date; - instanceId: string; - }; - export type WorkflowStepEvent = { - payload: Readonly; - timestamp: Date; - type: string; - }; - export abstract class WorkflowStep { - do>(name: string, callback: () => Promise): Promise; - do>(name: string, config: WorkflowStepConfig, callback: () => Promise): Promise; - sleep: (name: string, duration: WorkflowSleepDuration) => Promise; - sleepUntil: (name: string, timestamp: Date | number) => Promise; - waitForEvent>(name: string, options: { - type: string; - timeout?: WorkflowTimeoutDuration | number; - }): Promise>; - } - export abstract class WorkflowEntrypoint | unknown = unknown> implements Rpc.WorkflowEntrypointBranded { - [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - run(event: Readonly>, step: WorkflowStep): Promise; - } - export function waitUntil(promise: Promise): void; - export const env: Cloudflare.Env; -} -declare module 'cloudflare:workers' { - export = CloudflareWorkersModule; -} -interface SecretsStoreSecret { - /** - * Get a secret from the Secrets Store, returning a string of the secret value - * if it exists, or throws an error if it does not exist - */ - get(): Promise; -} -declare module "cloudflare:sockets" { - function _connect(address: string | SocketAddress, options?: SocketOptions): Socket; - export { _connect as connect }; -} -type MarkdownDocument = { - name: string; - blob: Blob; -}; -type ConversionResponse = { - name: string; - mimeType: string; - format: 'markdown'; - tokens: number; - data: string; -} | { - name: string; - mimeType: string; - format: 'error'; - error: string; -}; -type ImageConversionOptions = { - descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de'; -}; -type EmbeddedImageConversionOptions = ImageConversionOptions & { - convert?: boolean; - maxConvertedImages?: number; -}; -type ConversionOptions = { - html?: { - images?: EmbeddedImageConversionOptions & { - convertOGImage?: boolean; - }; - }; - docx?: { - images?: EmbeddedImageConversionOptions; - }; - image?: ImageConversionOptions; - pdf?: { - images?: EmbeddedImageConversionOptions; - metadata?: boolean; - }; -}; -type ConversionRequestOptions = { - gateway?: GatewayOptions; - extraHeaders?: object; - conversionOptions?: ConversionOptions; -}; -type SupportedFileFormat = { - mimeType: string; - extension: string; -}; -declare abstract class ToMarkdownService { - transform(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; - transform(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; - supported(): Promise; -} -declare namespace TailStream { - interface Header { - readonly name: string; - readonly value: string; - } - interface FetchEventInfo { - readonly type: "fetch"; - readonly method: string; - readonly url: string; - readonly cfJson?: object; - readonly headers: Header[]; - } - interface JsRpcEventInfo { - readonly type: "jsrpc"; - } - interface ScheduledEventInfo { - readonly type: "scheduled"; - readonly scheduledTime: Date; - readonly cron: string; - } - interface AlarmEventInfo { - readonly type: "alarm"; - readonly scheduledTime: Date; - } - interface QueueEventInfo { - readonly type: "queue"; - readonly queueName: string; - readonly batchSize: number; - } - interface EmailEventInfo { - readonly type: "email"; - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; - } - interface TraceEventInfo { - readonly type: "trace"; - readonly traces: (string | null)[]; - } - interface HibernatableWebSocketEventInfoMessage { - readonly type: "message"; - } - interface HibernatableWebSocketEventInfoError { - readonly type: "error"; - } - interface HibernatableWebSocketEventInfoClose { - readonly type: "close"; - readonly code: number; - readonly wasClean: boolean; - } - interface HibernatableWebSocketEventInfo { - readonly type: "hibernatableWebSocket"; - readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage; - } - interface CustomEventInfo { - readonly type: "custom"; - } - interface FetchResponseInfo { - readonly type: "fetch"; - readonly statusCode: number; - } - type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound"; - interface ScriptVersion { - readonly id: string; - readonly tag?: string; - readonly message?: string; - } - interface Onset { - readonly type: "onset"; - readonly attributes: Attribute[]; - // id for the span being opened by this Onset event. - readonly spanId: string; - readonly dispatchNamespace?: string; - readonly entrypoint?: string; - readonly executionModel: string; - readonly scriptName?: string; - readonly scriptTags?: string[]; - readonly scriptVersion?: ScriptVersion; - readonly info: FetchEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo; - } - interface Outcome { - readonly type: "outcome"; - readonly outcome: EventOutcome; - readonly cpuTime: number; - readonly wallTime: number; - } - interface SpanOpen { - readonly type: "spanOpen"; - readonly name: string; - // id for the span being opened by this SpanOpen event. - readonly spanId: string; - readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes; - } - interface SpanClose { - readonly type: "spanClose"; - readonly outcome: EventOutcome; - } - interface DiagnosticChannelEvent { - readonly type: "diagnosticChannel"; - readonly channel: string; - readonly message: any; - } - interface Exception { - readonly type: "exception"; - readonly name: string; - readonly message: string; - readonly stack?: string; - } - interface Log { - readonly type: "log"; - readonly level: "debug" | "error" | "info" | "log" | "warn"; - readonly message: object; - } - // This marks the worker handler return information. - // This is separate from Outcome because the worker invocation can live for a long time after - // returning. For example - Websockets that return an http upgrade response but then continue - // streaming information or SSE http connections. - interface Return { - readonly type: "return"; - readonly info?: FetchResponseInfo; - } - interface Attribute { - readonly name: string; - readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[]; - } - interface Attributes { - readonly type: "attributes"; - readonly info: Attribute[]; - } - type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | Return | Attributes; - // Context in which this trace event lives. - interface SpanContext { - // Single id for the entire top-level invocation - // This should be a new traceId for the first worker stage invoked in the eyeball request and then - // same-account service-bindings should reuse the same traceId but cross-account service-bindings - // should use a new traceId. - readonly traceId: string; - // spanId in which this event is handled - // for Onset and SpanOpen events this would be the parent span id - // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events - // For Hibernate and Mark this would be the span under which they were emitted. - // spanId is not set ONLY if: - // 1. This is an Onset event - // 2. We are not inherting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) - readonly spanId?: string; - } - interface TailEvent { - // invocation id of the currently invoked worker stage. - // invocation id will always be unique to every Onset event and will be the same until the Outcome event. - readonly invocationId: string; - // Inherited spanContext for this event. - readonly spanContext: SpanContext; - readonly timestamp: Date; - readonly sequence: number; - readonly event: Event; - } - type TailEventHandler = (event: TailEvent) => void | Promise; - type TailEventHandlerObject = { - outcome?: TailEventHandler; - spanOpen?: TailEventHandler; - spanClose?: TailEventHandler; - diagnosticChannel?: TailEventHandler; - exception?: TailEventHandler; - log?: TailEventHandler; - return?: TailEventHandler; - attributes?: TailEventHandler; - }; - type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; -} -// Copyright (c) 2022-2023 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 -/** - * Data types supported for holding vector metadata. - */ -type VectorizeVectorMetadataValue = string | number | boolean | string[]; -/** - * Additional information to associate with a vector. - */ -type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record; -type VectorFloatArray = Float32Array | Float64Array; -interface VectorizeError { - code?: number; - error: string; -} -/** - * Comparison logic/operation to use for metadata filtering. - * - * This list is expected to grow as support for more operations are released. - */ -type VectorizeVectorMetadataFilterOp = '$eq' | '$ne' | '$lt' | '$lte' | '$gt' | '$gte'; -type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin'; -/** - * Filter criteria for vector metadata used to limit the retrieved query result set. - */ -type VectorizeVectorMetadataFilter = { - [field: string]: Exclude | null | { - [Op in VectorizeVectorMetadataFilterOp]?: Exclude | null; - } | { - [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude[]; - }; -}; -/** - * Supported distance metrics for an index. - * Distance metrics determine how other "similar" vectors are determined. - */ -type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; -/** - * Metadata return levels for a Vectorize query. - * - * Default to "none". - * - * @property all Full metadata for the vector return set, including all fields (including those un-indexed) without truncation. This is a more expensive retrieval, as it requires additional fetching & reading of un-indexed data. - * @property indexed Return all metadata fields configured for indexing in the vector return set. This level of retrieval is "free" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings). - * @property none No indexed metadata will be returned. - */ -type VectorizeMetadataRetrievalLevel = "all" | "indexed" | "none"; -interface VectorizeQueryOptions { - topK?: number; - namespace?: string; - returnValues?: boolean; - returnMetadata?: boolean | VectorizeMetadataRetrievalLevel; - filter?: VectorizeVectorMetadataFilter; -} -/** - * Information about the configuration of an index. - */ -type VectorizeIndexConfig = { - dimensions: number; - metric: VectorizeDistanceMetric; -} | { - preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity -}; -/** - * Metadata about an existing index. - * - * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. - * See {@link VectorizeIndexInfo} for its post-beta equivalent. - */ -interface VectorizeIndexDetails { - /** The unique ID of the index */ - readonly id: string; - /** The name of the index. */ - name: string; - /** (optional) A human readable description for the index. */ - description?: string; - /** The index configuration, including the dimension size and distance metric. */ - config: VectorizeIndexConfig; - /** The number of records containing vectors within the index. */ - vectorsCount: number; -} -/** - * Metadata about an existing index. - */ -interface VectorizeIndexInfo { - /** The number of records containing vectors within the index. */ - vectorCount: number; - /** Number of dimensions the index has been configured for. */ - dimensions: number; - /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */ - processedUpToDatetime: number; - /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */ - processedUpToMutation: number; -} -/** - * Represents a single vector value set along with its associated metadata. - */ -interface VectorizeVector { - /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ - id: string; - /** The vector values */ - values: VectorFloatArray | number[]; - /** The namespace this vector belongs to. */ - namespace?: string; - /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */ - metadata?: Record; -} -/** - * Represents a matched vector for a query along with its score and (if specified) the matching vector information. - */ -type VectorizeMatch = Pick, "values"> & Omit & { - /** The score or rank for similarity, when returned as a result */ - score: number; -}; -/** - * A set of matching {@link VectorizeMatch} for a particular query. - */ -interface VectorizeMatches { - matches: VectorizeMatch[]; - count: number; -} -/** - * Results of an operation that performed a mutation on a set of vectors. - * Here, `ids` is a list of vectors that were successfully processed. - * - * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. - * See {@link VectorizeAsyncMutation} for its post-beta equivalent. - */ -interface VectorizeVectorMutation { - /* List of ids of vectors that were successfully processed. */ - ids: string[]; - /* Total count of the number of processed vectors. */ - count: number; -} -/** - * Result type indicating a mutation on the Vectorize Index. - * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation. - */ -interface VectorizeAsyncMutation { - /** The unique identifier for the async mutation operation containing the changeset. */ - mutationId: string; -} -/** - * A Vectorize Vector Search Index for querying vectors/embeddings. - * - * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. - * See {@link Vectorize} for its new implementation. - */ -declare abstract class VectorizeIndex { - /** - * Get information about the currently bound index. - * @returns A promise that resolves with information about the current index. - */ - public describe(): Promise; - /** - * Use the provided vector to perform a similarity search across the index. - * @param vector Input vector that will be used to drive the similarity search. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; - /** - * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. - * @param vectors List of vectors that will be inserted. - * @returns A promise that resolves with the ids & count of records that were successfully processed. - */ - public insert(vectors: VectorizeVector[]): Promise; - /** - * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. - * @param vectors List of vectors that will be upserted. - * @returns A promise that resolves with the ids & count of records that were successfully processed. - */ - public upsert(vectors: VectorizeVector[]): Promise; - /** - * Delete a list of vectors with a matching id. - * @param ids List of vector ids that should be deleted. - * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). - */ - public deleteByIds(ids: string[]): Promise; - /** - * Get a list of vectors with a matching id. - * @param ids List of vector ids that should be returned. - * @returns A promise that resolves with the raw unscored vectors matching the id set. - */ - public getByIds(ids: string[]): Promise; -} -/** - * A Vectorize Vector Search Index for querying vectors/embeddings. - * - * Mutations in this version are async, returning a mutation id. - */ -declare abstract class Vectorize { - /** - * Get information about the currently bound index. - * @returns A promise that resolves with information about the current index. - */ - public describe(): Promise; - /** - * Use the provided vector to perform a similarity search across the index. - * @param vector Input vector that will be used to drive the similarity search. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; - /** - * Use the provided vector-id to perform a similarity search across the index. - * @param vectorId Id for a vector in the index against which the index should be queried. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise; - /** - * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. - * @param vectors List of vectors that will be inserted. - * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset. - */ - public insert(vectors: VectorizeVector[]): Promise; - /** - * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. - * @param vectors List of vectors that will be upserted. - * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset. - */ - public upsert(vectors: VectorizeVector[]): Promise; - /** - * Delete a list of vectors with a matching id. - * @param ids List of vector ids that should be deleted. - * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset. - */ - public deleteByIds(ids: string[]): Promise; - /** - * Get a list of vectors with a matching id. - * @param ids List of vector ids that should be returned. - * @returns A promise that resolves with the raw unscored vectors matching the id set. - */ - public getByIds(ids: string[]): Promise; -} -/** - * The interface for "version_metadata" binding - * providing metadata about the Worker Version using this binding. - */ -type WorkerVersionMetadata = { - /** The ID of the Worker Version using this binding */ - id: string; - /** The tag of the Worker Version using this binding */ - tag: string; - /** The timestamp of when the Worker Version was uploaded */ - timestamp: string; -}; -interface DynamicDispatchLimits { - /** - * Limit CPU time in milliseconds. - */ - cpuMs?: number; - /** - * Limit number of subrequests. - */ - subRequests?: number; -} -interface DynamicDispatchOptions { - /** - * Limit resources of invoked Worker script. - */ - limits?: DynamicDispatchLimits; - /** - * Arguments for outbound Worker script, if configured. - */ - outbound?: { - [key: string]: any; - }; -} -interface DispatchNamespace { - /** - * @param name Name of the Worker script. - * @param args Arguments to Worker script. - * @param options Options for Dynamic Dispatch invocation. - * @returns A Fetcher object that allows you to send requests to the Worker script. - * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. - */ - get(name: string, args?: { - [key: string]: any; - }, options?: DynamicDispatchOptions): Fetcher; -} -declare module 'cloudflare:workflows' { - /** - * NonRetryableError allows for a user to throw a fatal error - * that makes a Workflow instance fail immediately without triggering a retry - */ - export class NonRetryableError extends Error { - public constructor(message: string, name?: string); - } -} -declare abstract class Workflow { - /** - * Get a handle to an existing instance of the Workflow. - * @param id Id for the instance of this Workflow - * @returns A promise that resolves with a handle for the Instance - */ - public get(id: string): Promise; - /** - * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown. - * @param options Options when creating an instance including id and params - * @returns A promise that resolves with a handle for the Instance - */ - public create(options?: WorkflowInstanceCreateOptions): Promise; - /** - * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown. - * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached. - * @param batch List of Options when creating an instance including name and params - * @returns A promise that resolves with a list of handles for the created instances. - */ - public createBatch(batch: WorkflowInstanceCreateOptions[]): Promise; -} -type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; -type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; -type WorkflowRetentionDuration = WorkflowSleepDuration; -interface WorkflowInstanceCreateOptions { - /** - * An id for your Workflow instance. Must be unique within the Workflow. - */ - id?: string; - /** - * The event payload the Workflow instance is triggered with - */ - params?: PARAMS; - /** - * The retention policy for Workflow instance. - * Defaults to the maximum retention period available for the owner's account. - */ - retention?: { - successRetention?: WorkflowRetentionDuration; - errorRetention?: WorkflowRetentionDuration; - }; -} -type InstanceStatus = { - status: 'queued' // means that instance is waiting to be started (see concurrency limits) - | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running - | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish - | 'waitingForPause' // instance is finishing the current work to pause - | 'unknown'; - error?: string; - output?: object; -}; -interface WorkflowError { - code?: number; - message: string; -} -declare abstract class WorkflowInstance { - public id: string; - /** - * Pause the instance. - */ - public pause(): Promise; - /** - * Resume the instance. If it is already running, an error will be thrown. - */ - public resume(): Promise; - /** - * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. - */ - public terminate(): Promise; - /** - * Restart the instance. - */ - public restart(): Promise; - /** - * Returns the current status of the instance. - */ - public status(): Promise; - /** - * Send an event to this instance. - */ - public sendEvent({ type, payload, }: { - type: string; - payload: unknown; - }): Promise; -} diff --git a/examples/react/start-basic-cloudflare/wrangler.jsonc b/examples/react/start-basic-cloudflare/wrangler.jsonc deleted file mode 100644 index 05aca667af9..00000000000 --- a/examples/react/start-basic-cloudflare/wrangler.jsonc +++ /dev/null @@ -1,10 +0,0 @@ -{ - "$schema": "node_modules/wrangler/config-schema.json", - "name": "tanstack-start-app", - "compatibility_date": "2025-09-24", - "compatibility_flags": ["nodejs_compat"], - "main": "@tanstack/react-start/server-entry", - "vars": { - "MY_VAR": "Hello from Cloudflare", - }, -} diff --git a/examples/react/start-basic-react-query/.gitignore b/examples/react/start-basic-react-query/.gitignore deleted file mode 100644 index ca63f498851..00000000000 --- a/examples/react/start-basic-react-query/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -.DS_Store -.cache -.env -.vercel -.output -/build/ -/api/ -/server/build -/public/build# Sentry Config File -.env.sentry-build-plugin -/test-results/ -/playwright-report/ -/blob-report/ -/playwright/.cache/ diff --git a/examples/react/start-basic-react-query/.prettierignore b/examples/react/start-basic-react-query/.prettierignore deleted file mode 100644 index 2be5eaa6ece..00000000000 --- a/examples/react/start-basic-react-query/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/build -**/public -pnpm-lock.yaml -routeTree.gen.ts \ No newline at end of file diff --git a/examples/react/start-basic-react-query/.vscode/settings.json b/examples/react/start-basic-react-query/.vscode/settings.json deleted file mode 100644 index 00b5278e580..00000000000 --- a/examples/react/start-basic-react-query/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "files.watcherExclude": { - "**/routeTree.gen.ts": true - }, - "search.exclude": { - "**/routeTree.gen.ts": true - }, - "files.readonlyInclude": { - "**/routeTree.gen.ts": true - } -} diff --git a/examples/react/start-basic-react-query/README.md b/examples/react/start-basic-react-query/README.md index 77c61c2504d..95a31b0ddab 100644 --- a/examples/react/start-basic-react-query/README.md +++ b/examples/react/start-basic-react-query/README.md @@ -1,42 +1,17 @@ -# TanStack Start - Basic React Query Example +# Deprecated: TanStack Start React Example (`start-basic-react-query`) -A TanStack Start example demonstrating integration with TanStack Query (React Query). +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) -- [TanStack Query Docs](https://tanstack.com/query) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-basic-react-query start-basic-react-query -``` +- [Start React Quick Start](https://tanstack.com/router/latest/docs/framework/react/start/quick-start) +- [TanStack Query Docs](https://tanstack.com/query/latest) -## Getting Started +Canonical issue reproduction baseline: -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -This starts your app in development mode, rebuilding assets on file changes. - -## Build - -To build the app for production: - -```sh -pnpm build -``` - -## TanStack Query Integration - -This example demonstrates how to use TanStack Query with TanStack Start for: - -- Server-side data fetching -- Client-side caching and synchronization -- Optimistic updates -- Automatic refetching +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-basic-react-query/package.json b/examples/react/start-basic-react-query/package.json deleted file mode 100644 index a8e3c5e54f9..00000000000 --- a/examples/react/start-basic-react-query/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "tanstack-start-example-basic-react-query", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" - }, - "dependencies": { - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.161.1", - "@tanstack/react-router-devtools": "^1.161.1", - "@tanstack/react-router-ssr-query": "^1.161.1", - "@tanstack/react-start": "^1.161.1", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0" - }, - "devDependencies": { - "@tailwindcss/vite": "^4.1.18", - "@types/node": "^22.5.4", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "tailwindcss": "^4.1.18", - "typescript": "^5.7.2", - "vite": "^7.3.1", - "vite-tsconfig-paths": "^5.1.4" - } -} diff --git a/examples/react/start-basic-react-query/public/android-chrome-192x192.png b/examples/react/start-basic-react-query/public/android-chrome-192x192.png deleted file mode 100644 index 09c8324f8c6..00000000000 Binary files a/examples/react/start-basic-react-query/public/android-chrome-192x192.png and /dev/null differ diff --git a/examples/react/start-basic-react-query/public/android-chrome-512x512.png b/examples/react/start-basic-react-query/public/android-chrome-512x512.png deleted file mode 100644 index 11d626ea3d0..00000000000 Binary files a/examples/react/start-basic-react-query/public/android-chrome-512x512.png and /dev/null differ diff --git a/examples/react/start-basic-react-query/public/apple-touch-icon.png b/examples/react/start-basic-react-query/public/apple-touch-icon.png deleted file mode 100644 index 5a9423cc02c..00000000000 Binary files a/examples/react/start-basic-react-query/public/apple-touch-icon.png and /dev/null differ diff --git a/examples/react/start-basic-react-query/public/favicon-16x16.png b/examples/react/start-basic-react-query/public/favicon-16x16.png deleted file mode 100644 index e3389b00443..00000000000 Binary files a/examples/react/start-basic-react-query/public/favicon-16x16.png and /dev/null differ diff --git a/examples/react/start-basic-react-query/public/favicon-32x32.png b/examples/react/start-basic-react-query/public/favicon-32x32.png deleted file mode 100644 index 900c77d444c..00000000000 Binary files a/examples/react/start-basic-react-query/public/favicon-32x32.png and /dev/null differ diff --git a/examples/react/start-basic-react-query/public/favicon.ico b/examples/react/start-basic-react-query/public/favicon.ico deleted file mode 100644 index 1a1751676f7..00000000000 Binary files a/examples/react/start-basic-react-query/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-basic-react-query/public/favicon.png b/examples/react/start-basic-react-query/public/favicon.png deleted file mode 100644 index 1e77bc06091..00000000000 Binary files a/examples/react/start-basic-react-query/public/favicon.png and /dev/null differ diff --git a/examples/react/start-basic-react-query/public/site.webmanifest b/examples/react/start-basic-react-query/public/site.webmanifest deleted file mode 100644 index fa99de77db6..00000000000 --- a/examples/react/start-basic-react-query/public/site.webmanifest +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "", - "short_name": "", - "icons": [ - { - "src": "/android-chrome-192x192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "/android-chrome-512x512.png", - "sizes": "512x512", - "type": "image/png" - } - ], - "theme_color": "#ffffff", - "background_color": "#ffffff", - "display": "standalone" -} diff --git a/examples/react/start-basic-react-query/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-react-query/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index ef2daa1ea1d..00000000000 --- a/examples/react/start-basic-react-query/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { - ErrorComponent, - Link, - rootRouteId, - useMatch, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error(error) - - return ( -

- ) -} diff --git a/examples/react/start-basic-react-query/src/components/NotFound.tsx b/examples/react/start-basic-react-query/src/components/NotFound.tsx deleted file mode 100644 index fd4e75befe3..00000000000 --- a/examples/react/start-basic-react-query/src/components/NotFound.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: any }) { - return ( -
-
- {children ||

The page you are looking for does not exist.

} -
-

- - - Start Over - -

-
- ) -} diff --git a/examples/react/start-basic-react-query/src/routeTree.gen.ts b/examples/react/start-basic-react-query/src/routeTree.gen.ts deleted file mode 100644 index e713afe557e..00000000000 --- a/examples/react/start-basic-react-query/src/routeTree.gen.ts +++ /dev/null @@ -1,430 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as UsersRouteRouteImport } from './routes/users.route' -import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' - -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const UsersRouteRoute = UsersRouteRouteImport.update({ - id: '/users', - path: '/users', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRouteRoute = PostsRouteRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRouteRoute, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRouteRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRouteRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRouteRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '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/api/users', - path: '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/api/users', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, -} as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, -} as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/posts': typeof PostsRouteRouteWithChildren - '/users': typeof UsersRouteRouteWithChildren - '/deferred': typeof DeferredRoute - '/redirect': typeof RedirectRoute - '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/api/users': typeof ApiUsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts/': typeof PostsIndexRoute - '/users/': typeof UsersIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/api/users/$id': typeof ApiUsersIdRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/deferred': typeof DeferredRoute - '/redirect': typeof RedirectRoute - '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/api/users': typeof ApiUsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts': typeof PostsIndexRoute - '/users': typeof UsersIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/api/users/$id': typeof ApiUsersIdRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/posts': typeof PostsRouteRouteWithChildren - '/users': typeof UsersRouteRouteWithChildren - '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren - '/deferred': typeof DeferredRoute - '/redirect': typeof RedirectRoute - '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/_pathlessLayout/_nested-layout': typeof PathlessLayoutNestedLayoutRouteWithChildren - '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/api/users': typeof ApiUsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts/': typeof PostsIndexRoute - '/users/': typeof UsersIndexRoute - '/_pathlessLayout/_nested-layout/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/_pathlessLayout/_nested-layout/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/api/users/$id': typeof ApiUsersIdRoute - '/posts_/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/posts' - | '/users' - | '/deferred' - | '/redirect' - | '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/api/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts/' - | '/users/' - | '/route-a' - | '/route-b' - | '/api/users/$id' - | '/posts/$postId/deep' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/deferred' - | '/redirect' - | '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/api/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts' - | '/users' - | '/route-a' - | '/route-b' - | '/api/users/$id' - | '/posts/$postId/deep' - id: - | '__root__' - | '/' - | '/posts' - | '/users' - | '/_pathlessLayout' - | '/deferred' - | '/redirect' - | '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/_pathlessLayout/_nested-layout' - | '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/api/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts/' - | '/users/' - | '/_pathlessLayout/_nested-layout/route-a' - | '/_pathlessLayout/_nested-layout/route-b' - | '/api/users/$id' - | '/posts_/$postId/deep' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - PostsRouteRoute: typeof PostsRouteRouteWithChildren - UsersRouteRoute: typeof UsersRouteRouteWithChildren - PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren - DeferredRoute: typeof DeferredRoute - RedirectRoute: typeof RedirectRoute - ApiUsersRoute: typeof ApiUsersRouteWithChildren - PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRouteRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRouteRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRouteRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRouteRoute - } - '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/api/users': { - id: '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/api/users' - path: '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/api/users' - fullPath: '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/api/users' - preLoaderRoute: typeof ApiUsersRouteImport - parentRoute: typeof rootRouteImport - } - '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/_pathlessLayout/_nested-layout': { - id: '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/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport - } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute - } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - } -} - -interface PostsRouteRouteChildren { - PostsPostIdRoute: typeof PostsPostIdRoute - PostsIndexRoute: typeof PostsIndexRoute -} - -const PostsRouteRouteChildren: PostsRouteRouteChildren = { - PostsPostIdRoute: PostsPostIdRoute, - PostsIndexRoute: PostsIndexRoute, -} - -const PostsRouteRouteWithChildren = PostsRouteRoute._addFileChildren( - PostsRouteRouteChildren, -) - -interface UsersRouteRouteChildren { - UsersUserIdRoute: typeof UsersUserIdRoute - UsersIndexRoute: typeof UsersIndexRoute -} - -const UsersRouteRouteChildren: UsersRouteRouteChildren = { - UsersUserIdRoute: UsersUserIdRoute, - UsersIndexRoute: UsersIndexRoute, -} - -const UsersRouteRouteWithChildren = UsersRouteRoute._addFileChildren( - UsersRouteRouteChildren, -) - -interface PathlessLayoutNestedLayoutRouteChildren { - PathlessLayoutNestedLayoutRouteARoute: typeof PathlessLayoutNestedLayoutRouteARoute - PathlessLayoutNestedLayoutRouteBRoute: typeof PathlessLayoutNestedLayoutRouteBRoute -} - -const PathlessLayoutNestedLayoutRouteChildren: PathlessLayoutNestedLayoutRouteChildren = - { - PathlessLayoutNestedLayoutRouteARoute: - PathlessLayoutNestedLayoutRouteARoute, - PathlessLayoutNestedLayoutRouteBRoute: - PathlessLayoutNestedLayoutRouteBRoute, - } - -const PathlessLayoutNestedLayoutRouteWithChildren = - PathlessLayoutNestedLayoutRoute._addFileChildren( - PathlessLayoutNestedLayoutRouteChildren, - ) - -interface PathlessLayoutRouteChildren { - PathlessLayoutNestedLayoutRoute: typeof PathlessLayoutNestedLayoutRouteWithChildren -} - -const PathlessLayoutRouteChildren: PathlessLayoutRouteChildren = { - PathlessLayoutNestedLayoutRoute: PathlessLayoutNestedLayoutRouteWithChildren, -} - -const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( - PathlessLayoutRouteChildren, -) - -interface ApiUsersRouteChildren { - ApiUsersIdRoute: typeof ApiUsersIdRoute -} - -const ApiUsersRouteChildren: ApiUsersRouteChildren = { - ApiUsersIdRoute: ApiUsersIdRoute, -} - -const ApiUsersRouteWithChildren = ApiUsersRoute._addFileChildren( - ApiUsersRouteChildren, -) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - PostsRouteRoute: PostsRouteRouteWithChildren, - UsersRouteRoute: UsersRouteRouteWithChildren, - PathlessLayoutRoute: PathlessLayoutRouteWithChildren, - DeferredRoute: DeferredRoute, - RedirectRoute: RedirectRoute, - ApiUsersRoute: ApiUsersRouteWithChildren, - PostsPostIdDeepRoute: PostsPostIdDeepRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' -declare module '@tanstack/react-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/examples/react/start-basic-react-query/src/router.tsx b/examples/react/start-basic-react-query/src/router.tsx deleted file mode 100644 index 314b29edd01..00000000000 --- a/examples/react/start-basic-react-query/src/router.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import { QueryClient } from '@tanstack/react-query' -import { createRouter } from '@tanstack/react-router' -import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query' -import { routeTree } from './routeTree.gen' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - const queryClient = new QueryClient() - - const router = createRouter({ - routeTree, - context: { queryClient }, - defaultPreload: 'intent', - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - }) - setupRouterSsrQueryIntegration({ - router, - queryClient, - }) - - return router -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/examples/react/start-basic-react-query/src/routes/__root.tsx b/examples/react/start-basic-react-query/src/routes/__root.tsx deleted file mode 100644 index bc278f8036b..00000000000 --- a/examples/react/start-basic-react-query/src/routes/__root.tsx +++ /dev/null @@ -1,145 +0,0 @@ -/// -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRouteWithContext, -} from '@tanstack/react-router' -import { ReactQueryDevtools } from '@tanstack/react-query-devtools' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import * as React from 'react' -import type { QueryClient } from '@tanstack/react-query' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' -import { NotFound } from '~/components/NotFound' -import appCss from '~/styles/app.css?url' -import { seo } from '~/utils/seo' - -export const Route = createRootRouteWithContext<{ - queryClient: QueryClient -}>()({ - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - ...seo({ - title: - 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', - description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, - }), - ], - links: [ - { rel: 'stylesheet', href: appCss }, - { - rel: 'apple-touch-icon', - sizes: '180x180', - href: '/apple-touch-icon.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '32x32', - href: '/favicon-32x32.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '16x16', - href: '/favicon-16x16.png', - }, - { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, - { rel: 'icon', href: '/favicon.ico' }, - ], - }), - errorComponent: (props) => { - return ( - - - - ) - }, - notFoundComponent: () => , - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - ) -} - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- - Home - {' '} - - Posts - {' '} - - Users - {' '} - - Pathless Layout - {' '} - - Deferred - {' '} - - This Route Does Not Exist - -
-
- {children} - - - - - - ) -} diff --git a/examples/react/start-basic-react-query/src/routes/_pathlessLayout.tsx b/examples/react/start-basic-react-query/src/routes/_pathlessLayout.tsx deleted file mode 100644 index 3353841595a..00000000000 --- a/examples/react/start-basic-react-query/src/routes/_pathlessLayout.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout')({ - component: PathlessLayoutComponent, -}) - -function PathlessLayoutComponent() { - return ( -
-
I'm a pathless layout
-
- -
-
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout.tsx b/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout.tsx deleted file mode 100644 index 0dcb1270ad7..00000000000 --- a/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('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/_pathlessLayout/_nested-layout')({ - component: PathlessLayoutComponent, -}) - -function PathlessLayoutComponent() { - return ( -
-
I'm a nested pathless layout
-
- - Go to route A - - - Go to route B - -
-
- -
-
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout/route-a.tsx b/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout/route-a.tsx deleted file mode 100644 index 0213f1516f4..00000000000 --- a/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout/route-a.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-a')( - { - component: LayoutAComponent, - }, -) - -function LayoutAComponent() { - return
I'm A!
-} diff --git a/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout/route-b.tsx b/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout/route-b.tsx deleted file mode 100644 index 3d909523fb9..00000000000 --- a/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout/route-b.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-b')( - { - component: LayoutBComponent, - }, -) - -function LayoutBComponent() { - return
I'm B!
-} diff --git a/examples/react/start-basic-react-query/src/routes/api/users.$id.ts b/examples/react/start-basic-react-query/src/routes/api/users.$id.ts deleted file mode 100644 index fd2becb76c9..00000000000 --- a/examples/react/start-basic-react-query/src/routes/api/users.$id.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import axios from 'redaxios' -import type { User } from '../../utils/users' - -export const Route = createFileRoute('/api/users/$id')({ - server: { - handlers: { - GET: async ({ request, params }) => { - console.info(`Fetching users by id=${params.id}... @`, request.url) - try { - const res = await axios.get( - 'https://jsonplaceholder.typicode.com/users/' + params.id, - ) - return Response.json({ - id: res.data.id, - name: res.data.name, - email: res.data.email, - }) - } catch (e) { - console.error(e) - return Response.json({ error: 'User not found' }, { status: 404 }) - } - }, - }, - }, -}) diff --git a/examples/react/start-basic-react-query/src/routes/api/users.ts b/examples/react/start-basic-react-query/src/routes/api/users.ts deleted file mode 100644 index 68fbdfcff0d..00000000000 --- a/examples/react/start-basic-react-query/src/routes/api/users.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import axios from 'redaxios' -import type { User } from '../../utils/users' - -export const Route = createFileRoute('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/api/users')({ - server: { - handlers: { - GET: async ({ request }) => { - console.info('Fetching users... @', request.url) - const res = await axios.get>( - 'https://jsonplaceholder.typicode.com/users', - ) - const list = res.data.slice(0, 10) - return Response.json( - list.map((u) => ({ id: u.id, name: u.name, email: u.email })), - ) - }, - }, - }, -}) diff --git a/examples/react/start-basic-react-query/src/routes/deferred.tsx b/examples/react/start-basic-react-query/src/routes/deferred.tsx deleted file mode 100644 index 0380f79acac..00000000000 --- a/examples/react/start-basic-react-query/src/routes/deferred.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { queryOptions, useSuspenseQuery } from '@tanstack/react-query' -import {} from '@tanstack/react-router' -import { Suspense, useState } from 'react' - -const deferredQueryOptions = () => - queryOptions({ - queryKey: ['deferred'], - queryFn: async () => { - await new Promise((r) => setTimeout(r, 3000)) - return { - message: `Hello deferred from the server!`, - status: 'success', - time: new Date(), - } - }, - }) - -export const Route = createFileRoute('/deferred')({ - loader: ({ context }) => { - // Kick off loading as early as possible! - context.queryClient.prefetchQuery(deferredQueryOptions()) - }, - component: Deferred, -}) - -function Deferred() { - const [count, setCount] = useState(0) - - return ( -
- - - -
Count: {count}
-
- -
-
- ) -} - -function DeferredQuery() { - const deferredQuery = useSuspenseQuery(deferredQueryOptions()) - - return ( -
-

Deferred Query

-
Status: {deferredQuery.data.status}
-
Message: {deferredQuery.data.message}
-
Time: {deferredQuery.data.time.toISOString()}
-
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/index.tsx b/examples/react/start-basic-react-query/src/routes/index.tsx deleted file mode 100644 index 37c8d237bd4..00000000000 --- a/examples/react/start-basic-react-query/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Welcome Home!!!

-
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/posts.$postId.tsx b/examples/react/start-basic-react-query/src/routes/posts.$postId.tsx deleted file mode 100644 index e9e58e55411..00000000000 --- a/examples/react/start-basic-react-query/src/routes/posts.$postId.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { ErrorComponent, Link, createFileRoute } from '@tanstack/react-router' -import { useSuspenseQuery } from '@tanstack/react-query' -import { postQueryOptions } from '../utils/posts' -import type { ErrorComponentProps } from '@tanstack/react-router' -import { NotFound } from '~/components/NotFound' - -export const Route = createFileRoute('/posts/$postId')({ - loader: async ({ params: { postId }, context }) => { - const data = await context.queryClient.ensureQueryData( - postQueryOptions(postId), - ) - - return { - title: data.title, - } - }, - head: ({ loaderData }) => ({ - meta: loaderData ? [{ title: loaderData.title }] : undefined, - }), - errorComponent: PostErrorComponent, - notFoundComponent: () => { - return Post not found - }, - component: PostComponent, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return -} - -function PostComponent() { - const { postId } = Route.useParams() - const postQuery = useSuspenseQuery(postQueryOptions(postId)) - - return ( -
-

{postQuery.data.title}

-
{postQuery.data.body}
- - Deep View - -
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/posts.index.tsx b/examples/react/start-basic-react-query/src/routes/posts.index.tsx deleted file mode 100644 index c6592745679..00000000000 --- a/examples/react/start-basic-react-query/src/routes/posts.index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/posts/')({ - component: PostsIndexComponent, -}) - -function PostsIndexComponent() { - return
Select a post.
-} diff --git a/examples/react/start-basic-react-query/src/routes/posts.route.tsx b/examples/react/start-basic-react-query/src/routes/posts.route.tsx deleted file mode 100644 index b545663be20..00000000000 --- a/examples/react/start-basic-react-query/src/routes/posts.route.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { useSuspenseQuery } from '@tanstack/react-query' -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { postsQueryOptions } from '../utils/posts' - -export const Route = createFileRoute('/posts')({ - loader: async ({ context }) => { - await context.queryClient.ensureQueryData(postsQueryOptions()) - }, - head: () => ({ - meta: [{ title: 'Posts' }], - }), - component: PostsComponent, -}) - -function PostsComponent() { - const postsQuery = useSuspenseQuery(postsQueryOptions()) - - return ( -
-
    - {[ - ...postsQuery.data, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/posts_.$postId.deep.tsx b/examples/react/start-basic-react-query/src/routes/posts_.$postId.deep.tsx deleted file mode 100644 index 33f6475a55a..00000000000 --- a/examples/react/start-basic-react-query/src/routes/posts_.$postId.deep.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { useSuspenseQuery } from '@tanstack/react-query' -import { postQueryOptions } from '../utils/posts' -import { PostErrorComponent } from './posts.$postId' - -export const Route = createFileRoute('/posts_/$postId/deep')({ - loader: async ({ params: { postId }, context }) => { - const data = await context.queryClient.ensureQueryData( - postQueryOptions(postId), - ) - - return { - title: data.title, - } - }, - head: ({ loaderData }) => ({ - meta: loaderData ? [{ title: loaderData.title }] : undefined, - }), - errorComponent: PostErrorComponent, - component: PostDeepComponent, -}) - -function PostDeepComponent() { - const { postId } = Route.useParams() - const postQuery = useSuspenseQuery(postQueryOptions(postId)) - - return ( -
- - ← All Posts - -

{postQuery.data.title}

-
{postQuery.data.body}
-
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/redirect.tsx b/examples/react/start-basic-react-query/src/routes/redirect.tsx deleted file mode 100644 index fa220b50975..00000000000 --- a/examples/react/start-basic-react-query/src/routes/redirect.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { redirect, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/redirect')({ - beforeLoad: async () => { - throw redirect({ - to: '/posts', - }) - }, -}) diff --git a/examples/react/start-basic-react-query/src/routes/users.$userId.tsx b/examples/react/start-basic-react-query/src/routes/users.$userId.tsx deleted file mode 100644 index 0750a01568b..00000000000 --- a/examples/react/start-basic-react-query/src/routes/users.$userId.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { useSuspenseQuery } from '@tanstack/react-query' -import { ErrorComponent, createFileRoute } from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' -import { NotFound } from '~/components/NotFound' -import { userQueryOptions } from '~/utils/users' - -export const Route = createFileRoute('/users/$userId')({ - loader: async ({ context, params: { userId } }) => { - await context.queryClient.ensureQueryData(userQueryOptions(userId)) - }, - errorComponent: UserErrorComponent, - component: UserComponent, - notFoundComponent: () => { - return User not found - }, -}) - -export function UserErrorComponent({ error }: ErrorComponentProps) { - return -} - -function UserComponent() { - const params = Route.useParams() - const userQuery = useSuspenseQuery(userQueryOptions(params.userId)) - const user = userQuery.data - - return ( -
-

{user.name}

-
{user.email}
-
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/users.index.tsx b/examples/react/start-basic-react-query/src/routes/users.index.tsx deleted file mode 100644 index ea814e2cbf8..00000000000 --- a/examples/react/start-basic-react-query/src/routes/users.index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/users/')({ - component: UsersIndexComponent, -}) - -function UsersIndexComponent() { - return
Select a user.
-} diff --git a/examples/react/start-basic-react-query/src/routes/users.route.tsx b/examples/react/start-basic-react-query/src/routes/users.route.tsx deleted file mode 100644 index 2f3c72cb7b3..00000000000 --- a/examples/react/start-basic-react-query/src/routes/users.route.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { useSuspenseQuery } from '@tanstack/react-query' -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { usersQueryOptions } from '../utils/users' - -export const Route = createFileRoute('/users')({ - loader: async ({ context }) => { - await context.queryClient.ensureQueryData(usersQueryOptions()) - }, - component: UsersComponent, -}) - -function UsersComponent() { - const usersQuery = useSuspenseQuery(usersQueryOptions()) - - return ( -
-
    - {[ - ...usersQuery.data, - { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, - ].map((user) => { - return ( -
  • - -
    {user.name}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/examples/react/start-basic-react-query/src/styles/app.css b/examples/react/start-basic-react-query/src/styles/app.css deleted file mode 100644 index 37c1f5a6e2d..00000000000 --- a/examples/react/start-basic-react-query/src/styles/app.css +++ /dev/null @@ -1,30 +0,0 @@ -@import 'tailwindcss' source('../'); - -@layer base { - *, - ::after, - ::before, - ::backdrop, - ::file-selector-button { - border-color: var(--color-gray-200, currentcolor); - } -} - -@layer base { - html { - color-scheme: light dark; - } - - * { - @apply border-gray-200 dark:border-gray-800; - } - - html, - body { - @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; - } - - .using-mouse * { - outline: none !important; - } -} diff --git a/examples/react/start-basic-react-query/src/utils/posts.tsx b/examples/react/start-basic-react-query/src/utils/posts.tsx deleted file mode 100644 index a95e9dce271..00000000000 --- a/examples/react/start-basic-react-query/src/utils/posts.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import { queryOptions } from '@tanstack/react-query' -import { notFound } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import axios from 'redaxios' - -export type PostType = { - id: string - title: string - body: string -} - -export const fetchPosts = createServerFn({ method: 'GET' }).handler( - async () => { - console.info('Fetching posts...') - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) - }, -) - -export const postsQueryOptions = () => - queryOptions({ - queryKey: ['posts'], - queryFn: () => fetchPosts(), - }) - -export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) - .handler(async ({ data }) => { - console.info(`Fetching post with id ${data}...`) - const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${data}`) - .then((r) => r.data) - .catch((err) => { - console.error(err) - if (err.status === 404) { - throw notFound() - } - throw err - }) - - return post - }) - -export const postQueryOptions = (postId: string) => - queryOptions({ - queryKey: ['post', postId], - queryFn: () => fetchPost({ data: postId }), - }) diff --git a/examples/react/start-basic-react-query/src/utils/seo.ts b/examples/react/start-basic-react-query/src/utils/seo.ts deleted file mode 100644 index d18ad84b74e..00000000000 --- a/examples/react/start-basic-react-query/src/utils/seo.ts +++ /dev/null @@ -1,33 +0,0 @@ -export const seo = ({ - title, - description, - keywords, - image, -}: { - title: string - description?: string - image?: string - keywords?: string -}) => { - const tags = [ - { title }, - { name: 'description', content: description }, - { name: 'keywords', content: keywords }, - { name: 'twitter:title', content: title }, - { name: 'twitter:description', content: description }, - { name: 'twitter:creator', content: '@tannerlinsley' }, - { name: 'twitter:site', content: '@tannerlinsley' }, - { name: 'og:type', content: 'website' }, - { name: 'og:title', content: title }, - { name: 'og:description', content: description }, - ...(image - ? [ - { name: 'twitter:image', content: image }, - { name: 'twitter:card', content: 'summary_large_image' }, - { name: 'og:image', content: image }, - ] - : []), - ] - - return tags -} diff --git a/examples/react/start-basic-react-query/src/utils/users.tsx b/examples/react/start-basic-react-query/src/utils/users.tsx deleted file mode 100644 index 9b6760bfa7e..00000000000 --- a/examples/react/start-basic-react-query/src/utils/users.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { queryOptions } from '@tanstack/react-query' -import axios from 'redaxios' - -export type User = { - id: number - name: string - email: string -} - -export const DEPLOY_URL = 'http://localhost:3000' - -export const usersQueryOptions = () => - queryOptions({ - queryKey: ['users'], - queryFn: () => - axios - .get>(DEPLOY_URL + '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/api/users') - .then((r) => r.data) - .catch(() => { - throw new Error('Failed to fetch users') - }), - }) - -export const userQueryOptions = (id: string) => - queryOptions({ - queryKey: ['users', id], - queryFn: () => - axios - .get(DEPLOY_URL + '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/api/users/' + id) - .then((r) => r.data) - .catch(() => { - throw new Error('Failed to fetch user') - }), - }) diff --git a/examples/react/start-basic-react-query/tsconfig.json b/examples/react/start-basic-react-query/tsconfig.json deleted file mode 100644 index 3a9fb7cd716..00000000000 --- a/examples/react/start-basic-react-query/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "baseUrl": ".", - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/examples/react/start-basic-react-query/vite.config.ts b/examples/react/start-basic-react-query/vite.config.ts deleted file mode 100644 index 843599315ef..00000000000 --- a/examples/react/start-basic-react-query/vite.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' -import viteReact from '@vitejs/plugin-react' -import tailwindcss from '@tailwindcss/vite' - -export default defineConfig({ - server: { - port: 3000, - }, - plugins: [ - tailwindcss(), - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], -}) diff --git a/examples/react/start-basic-rsc/.gitignore b/examples/react/start-basic-rsc/.gitignore deleted file mode 100644 index 3c8e6870b30..00000000000 --- a/examples/react/start-basic-rsc/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -.DS_Store -.cache -.env -.vercel -.output -/build/ -/api/ -/server/build -/public/build# Sentry Config File -.env.sentry-build-plugin diff --git a/examples/react/start-basic-rsc/.prettierignore b/examples/react/start-basic-rsc/.prettierignore deleted file mode 100644 index 2be5eaa6ece..00000000000 --- a/examples/react/start-basic-rsc/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/build -**/public -pnpm-lock.yaml -routeTree.gen.ts \ No newline at end of file diff --git a/examples/react/start-basic-rsc/.vscode/settings.json b/examples/react/start-basic-rsc/.vscode/settings.json deleted file mode 100644 index 00b5278e580..00000000000 --- a/examples/react/start-basic-rsc/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "files.watcherExclude": { - "**/routeTree.gen.ts": true - }, - "search.exclude": { - "**/routeTree.gen.ts": true - }, - "files.readonlyInclude": { - "**/routeTree.gen.ts": true - } -} diff --git a/examples/react/start-basic-rsc/README.md b/examples/react/start-basic-rsc/README.md index 494e34f03f0..a08a08413d8 100644 --- a/examples/react/start-basic-rsc/README.md +++ b/examples/react/start-basic-rsc/README.md @@ -1,43 +1,17 @@ -# TanStack Start - RSC Example +# Deprecated: TanStack Start React Example (`start-basic-rsc`) -This site is built with TanStack Router and React Server Components! +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-basic-rsc start-basic-rsc -``` +- [Start React Quick Start](https://tanstack.com/router/latest/docs/framework/react/start/quick-start) +- [Start React Guides](https://tanstack.com/router/latest/docs/framework/react/start/guide/routing) -## Deployment +Canonical issue reproduction baseline: -It's deployed automagically with Netlify! - -- [Netlify](https://netlify.com/) - -## Getting Started - -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -## Build - -Build for production: - -```sh -pnpm build -``` - -## About This Example - -This example demonstrates: - -- React Server Components (RSC) with TanStack Start -- Server-side rendering +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-basic-rsc/package.json b/examples/react/start-basic-rsc/package.json deleted file mode 100644 index 3c58147bd88..00000000000 --- a/examples/react/start-basic-rsc/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "tanstack-start-example-basic-rsc", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "exit 0; vite build", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" - }, - "dependencies": { - "@babel/plugin-syntax-typescript": "^7.25.9", - "@tanstack/react-router": "^1.161.1", - "@tanstack/react-router-devtools": "^1.161.1", - "@tanstack/react-start": "^1.161.1", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0" - }, - "devDependencies": { - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "tailwindcss": "4.1.18", - "typescript": "^5.7.2", - "vite": "^7.3.1", - "vite-tsconfig-paths": "^5.1.4", - "@tailwindcss/vite": "4.1.18" - }, - "overrides": { - "react": "0.0.0-experimental-035a41c4e-20230704", - "react-dom": "0.0.0-experimental-035a41c4e-20230704" - } -} diff --git a/examples/react/start-basic-rsc/public/android-chrome-192x192.png b/examples/react/start-basic-rsc/public/android-chrome-192x192.png deleted file mode 100644 index 09c8324f8c6..00000000000 Binary files a/examples/react/start-basic-rsc/public/android-chrome-192x192.png and /dev/null differ diff --git a/examples/react/start-basic-rsc/public/android-chrome-512x512.png b/examples/react/start-basic-rsc/public/android-chrome-512x512.png deleted file mode 100644 index 11d626ea3d0..00000000000 Binary files a/examples/react/start-basic-rsc/public/android-chrome-512x512.png and /dev/null differ diff --git a/examples/react/start-basic-rsc/public/apple-touch-icon.png b/examples/react/start-basic-rsc/public/apple-touch-icon.png deleted file mode 100644 index 5a9423cc02c..00000000000 Binary files a/examples/react/start-basic-rsc/public/apple-touch-icon.png and /dev/null differ diff --git a/examples/react/start-basic-rsc/public/favicon-16x16.png b/examples/react/start-basic-rsc/public/favicon-16x16.png deleted file mode 100644 index e3389b00443..00000000000 Binary files a/examples/react/start-basic-rsc/public/favicon-16x16.png and /dev/null differ diff --git a/examples/react/start-basic-rsc/public/favicon-32x32.png b/examples/react/start-basic-rsc/public/favicon-32x32.png deleted file mode 100644 index 900c77d444c..00000000000 Binary files a/examples/react/start-basic-rsc/public/favicon-32x32.png and /dev/null differ diff --git a/examples/react/start-basic-rsc/public/favicon.ico b/examples/react/start-basic-rsc/public/favicon.ico deleted file mode 100644 index 1a1751676f7..00000000000 Binary files a/examples/react/start-basic-rsc/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-basic-rsc/public/favicon.png b/examples/react/start-basic-rsc/public/favicon.png deleted file mode 100644 index 1e77bc06091..00000000000 Binary files a/examples/react/start-basic-rsc/public/favicon.png and /dev/null differ diff --git a/examples/react/start-basic-rsc/public/site.webmanifest b/examples/react/start-basic-rsc/public/site.webmanifest deleted file mode 100644 index fa99de77db6..00000000000 --- a/examples/react/start-basic-rsc/public/site.webmanifest +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "", - "short_name": "", - "icons": [ - { - "src": "/android-chrome-192x192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "/android-chrome-512x512.png", - "sizes": "512x512", - "type": "image/png" - } - ], - "theme_color": "#ffffff", - "background_color": "#ffffff", - "display": "standalone" -} diff --git a/examples/react/start-basic-rsc/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-rsc/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index ef2daa1ea1d..00000000000 --- a/examples/react/start-basic-rsc/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { - ErrorComponent, - Link, - rootRouteId, - useMatch, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error(error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/examples/react/start-basic-rsc/src/components/NotFound.tsx b/examples/react/start-basic-rsc/src/components/NotFound.tsx deleted file mode 100644 index fd4e75befe3..00000000000 --- a/examples/react/start-basic-rsc/src/components/NotFound.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: any }) { - return ( -
-
- {children ||

The page you are looking for does not exist.

} -
-

- - - Start Over - -

-
- ) -} diff --git a/examples/react/start-basic-rsc/src/routeTree.gen.ts b/examples/react/start-basic-rsc/src/routeTree.gen.ts deleted file mode 100644 index cf37bb35c56..00000000000 --- a/examples/react/start-basic-rsc/src/routeTree.gen.ts +++ /dev/null @@ -1,263 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as IndexRouteImport } from './routes/index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' - -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/posts': typeof PostsRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/posts/': typeof PostsIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/posts/$postId': typeof PostsPostIdRoute - '/posts': typeof PostsIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren - '/posts': typeof PostsRouteWithChildren - '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/_pathlessLayout/_nested-layout': typeof PathlessLayoutNestedLayoutRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/posts/': typeof PostsIndexRoute - '/_pathlessLayout/_nested-layout/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/_pathlessLayout/_nested-layout/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/posts_/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/posts' - | '/posts/$postId' - | '/posts/' - | '/route-a' - | '/route-b' - | '/posts/$postId/deep' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/posts/$postId' - | '/posts' - | '/route-a' - | '/route-b' - | '/posts/$postId/deep' - id: - | '__root__' - | '/' - | '/_pathlessLayout' - | '/posts' - | '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/_pathlessLayout/_nested-layout' - | '/posts/$postId' - | '/posts/' - | '/_pathlessLayout/_nested-layout/route-a' - | '/_pathlessLayout/_nested-layout/route-b' - | '/posts_/$postId/deep' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren - PostsRoute: typeof PostsRouteWithChildren - PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '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/_pathlessLayout/_nested-layout': { - id: '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/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - } -} - -interface PathlessLayoutNestedLayoutRouteChildren { - PathlessLayoutNestedLayoutRouteARoute: typeof PathlessLayoutNestedLayoutRouteARoute - PathlessLayoutNestedLayoutRouteBRoute: typeof PathlessLayoutNestedLayoutRouteBRoute -} - -const PathlessLayoutNestedLayoutRouteChildren: PathlessLayoutNestedLayoutRouteChildren = - { - PathlessLayoutNestedLayoutRouteARoute: - PathlessLayoutNestedLayoutRouteARoute, - PathlessLayoutNestedLayoutRouteBRoute: - PathlessLayoutNestedLayoutRouteBRoute, - } - -const PathlessLayoutNestedLayoutRouteWithChildren = - PathlessLayoutNestedLayoutRoute._addFileChildren( - PathlessLayoutNestedLayoutRouteChildren, - ) - -interface PathlessLayoutRouteChildren { - PathlessLayoutNestedLayoutRoute: typeof PathlessLayoutNestedLayoutRouteWithChildren -} - -const PathlessLayoutRouteChildren: PathlessLayoutRouteChildren = { - PathlessLayoutNestedLayoutRoute: PathlessLayoutNestedLayoutRouteWithChildren, -} - -const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( - PathlessLayoutRouteChildren, -) - -interface PostsRouteChildren { - PostsPostIdRoute: typeof PostsPostIdRoute - PostsIndexRoute: typeof PostsIndexRoute -} - -const PostsRouteChildren: PostsRouteChildren = { - PostsPostIdRoute: PostsPostIdRoute, - PostsIndexRoute: PostsIndexRoute, -} - -const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - PathlessLayoutRoute: PathlessLayoutRouteWithChildren, - PostsRoute: PostsRouteWithChildren, - PostsPostIdDeepRoute: PostsPostIdDeepRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' -declare module '@tanstack/react-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/examples/react/start-basic-rsc/src/router.tsx b/examples/react/start-basic-rsc/src/router.tsx deleted file mode 100644 index f648dfcf8c4..00000000000 --- a/examples/react/start-basic-rsc/src/router.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - const router = createRouter({ - routeTree, - defaultPreload: 'intent', - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - scrollRestoration: true, - }) - - return router -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/examples/react/start-basic-rsc/src/routes/__root.tsx b/examples/react/start-basic-rsc/src/routes/__root.tsx deleted file mode 100644 index 0a5e0bf3704..00000000000 --- a/examples/react/start-basic-rsc/src/routes/__root.tsx +++ /dev/null @@ -1,125 +0,0 @@ -/// -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import * as React from 'react' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' -import { NotFound } from '~/components/NotFound' -import appCss from '~/styles/app.css?url' -import { seo } from '~/utils/seo' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - ...seo({ - title: - 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', - description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, - }), - ], - links: [ - { rel: 'stylesheet', href: appCss }, - { - rel: 'apple-touch-icon', - sizes: '180x180', - href: '/apple-touch-icon.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '32x32', - href: '/favicon-32x32.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '16x16', - href: '/favicon-16x16.png', - }, - { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, - { rel: 'icon', href: '/favicon.ico' }, - ], - }), - errorComponent: (props) => { - return ( - - - - ) - }, - notFoundComponent: () => , - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - ) -} - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- - Home - {' '} - - Posts - - - Pathless Layout - - - This Route Does Not Exist - -
-
- {/* {children} */} - {children} - - - - - ) -} diff --git a/examples/react/start-basic-rsc/src/routes/_pathlessLayout.tsx b/examples/react/start-basic-rsc/src/routes/_pathlessLayout.tsx deleted file mode 100644 index c3b12442b82..00000000000 --- a/examples/react/start-basic-rsc/src/routes/_pathlessLayout.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout')({ - component: LayoutComponent, -}) - -function LayoutComponent() { - return ( -
-
I'm a layout
-
- -
-
- ) -} diff --git a/examples/react/start-basic-rsc/src/routes/_pathlessLayout/_nested-layout.tsx b/examples/react/start-basic-rsc/src/routes/_pathlessLayout/_nested-layout.tsx deleted file mode 100644 index c5bcffd5a42..00000000000 --- a/examples/react/start-basic-rsc/src/routes/_pathlessLayout/_nested-layout.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('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/_pathlessLayout/_nested-layout')({ - component: LayoutComponent, -}) - -function LayoutComponent() { - return ( -
-
I'm a nested pathless layout
-
- - Go to route A - - - Go to route B - -
-
- -
-
- ) -} diff --git a/examples/react/start-basic-rsc/src/routes/_pathlessLayout/_nested-layout/route-a.tsx b/examples/react/start-basic-rsc/src/routes/_pathlessLayout/_nested-layout/route-a.tsx deleted file mode 100644 index 0213f1516f4..00000000000 --- a/examples/react/start-basic-rsc/src/routes/_pathlessLayout/_nested-layout/route-a.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-a')( - { - component: LayoutAComponent, - }, -) - -function LayoutAComponent() { - return
I'm A!
-} diff --git a/examples/react/start-basic-rsc/src/routes/_pathlessLayout/_nested-layout/route-b.tsx b/examples/react/start-basic-rsc/src/routes/_pathlessLayout/_nested-layout/route-b.tsx deleted file mode 100644 index 3d909523fb9..00000000000 --- a/examples/react/start-basic-rsc/src/routes/_pathlessLayout/_nested-layout/route-b.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-b')( - { - component: LayoutBComponent, - }, -) - -function LayoutBComponent() { - return
I'm B!
-} diff --git a/examples/react/start-basic-rsc/src/routes/index.tsx b/examples/react/start-basic-rsc/src/routes/index.tsx deleted file mode 100644 index d531858f8ce..00000000000 --- a/examples/react/start-basic-rsc/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Welcome Home!

-
- ) -} diff --git a/examples/react/start-basic-rsc/src/routes/posts.$postId.tsx b/examples/react/start-basic-rsc/src/routes/posts.$postId.tsx deleted file mode 100644 index f3dba9bfd3c..00000000000 --- a/examples/react/start-basic-rsc/src/routes/posts.$postId.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { ErrorComponent, Link, createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { fetchPost } from '../utils/posts' -import type { ErrorComponentProps } from '@tanstack/react-router' -import { NotFound } from '~/components/NotFound' - -const renderPost = createServerFn({ method: 'GET' }) - .inputValidator((postId: string) => postId) - .handler(async ({ data }) => { - const post = await fetchPost(data) - - return ( -
-

{post.title}

-
{post.body}
- - Deep View - -
- ) - }) - -export const Route = createFileRoute('/posts/$postId')({ - loader: async ({ params: { postId } }) => renderPost({ data: postId }), - errorComponent: PostErrorComponent, - component: PostComponent, - notFoundComponent: () => { - return Post not found - }, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return -} - -function PostComponent() { - return Route.useLoaderData() -} diff --git a/examples/react/start-basic-rsc/src/routes/posts.index.tsx b/examples/react/start-basic-rsc/src/routes/posts.index.tsx deleted file mode 100644 index c6592745679..00000000000 --- a/examples/react/start-basic-rsc/src/routes/posts.index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/posts/')({ - component: PostsIndexComponent, -}) - -function PostsIndexComponent() { - return
Select a post.
-} diff --git a/examples/react/start-basic-rsc/src/routes/posts.tsx b/examples/react/start-basic-rsc/src/routes/posts.tsx deleted file mode 100644 index a3ef2a2e200..00000000000 --- a/examples/react/start-basic-rsc/src/routes/posts.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { createServerFn, renderRsc } from '@tanstack/react-start' -import { renderPosts } from '~/utils/renderPosts' - -export const serverRenderPosts = createServerFn({ method: 'GET' }).handler( - renderPosts, -) - -export const Route = createFileRoute('/posts')({ - loader: async () => serverRenderPosts(), - component: PostsComponent, -}) - -function PostsComponent() { - return renderRsc(Route.useLoaderData()) -} diff --git a/examples/react/start-basic-rsc/src/routes/posts_.$postId.deep.tsx b/examples/react/start-basic-rsc/src/routes/posts_.$postId.deep.tsx deleted file mode 100644 index 13d368cf9c7..00000000000 --- a/examples/react/start-basic-rsc/src/routes/posts_.$postId.deep.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { fetchPost } from '../utils/posts' -import { PostErrorComponent } from './posts.$postId' - -export const Route = createFileRoute('/posts_/$postId/deep')({ - loader: async ({ params: { postId } }) => fetchPost(postId), - errorComponent: PostErrorComponent, - component: PostDeepComponent, -}) - -function PostDeepComponent() { - const post = Route.useLoaderData() - - return ( -
- - ← All Posts - -

{post.title}

-
{post.body}
-
- ) -} diff --git a/examples/react/start-basic-rsc/src/styles/app.css b/examples/react/start-basic-rsc/src/styles/app.css deleted file mode 100644 index 0ef1bc98daf..00000000000 --- a/examples/react/start-basic-rsc/src/styles/app.css +++ /dev/null @@ -1,40 +0,0 @@ -@import 'tailwindcss' source('../'); - -@source '../**/*.{js,jsx,ts,tsx}'; - -/* - The default border color has changed to `currentcolor` in Tailwind CSS v4, - so we've added these compatibility styles to make sure everything still - looks the same as it did with Tailwind CSS v3. - - If we ever want to remove these styles, we need to add an explicit border - color utility to any element that depends on these defaults. -*/ -@layer base { - *, - ::after, - ::before, - ::backdrop, - ::file-selector-button { - border-color: var(--color-gray-200, currentcolor); - } -} - -@layer base { - html { - color-scheme: light dark; - } - - * { - @apply border-gray-200 dark:border-gray-800; - } - - html, - body { - @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; - } - - .using-mouse * { - outline: none !important; - } -} diff --git a/examples/react/start-basic-rsc/src/utils/posts.tsx b/examples/react/start-basic-rsc/src/utils/posts.tsx deleted file mode 100644 index 16fc1744e6e..00000000000 --- a/examples/react/start-basic-rsc/src/utils/posts.tsx +++ /dev/null @@ -1,35 +0,0 @@ -// import { notFound } from '@tanstack/react-router' -// import { createServerFn } from '@tanstack/react-start' -import axios from 'redaxios' - -export type PostType = { - id: string - title: string - body: string -} - -export const fetchPost = async (postId: string) => { - 'use server' - console.info(`Fetching post with id ${postId}...`) - await new Promise((r) => setTimeout(r, 500)) - const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) - .then((r) => r.data) - .catch((err) => { - if (err.status === 404) { - // throw notFound() - } - throw err - }) - - return post -} - -export const fetchPosts = async () => { - 'use server' - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -} diff --git a/examples/react/start-basic-rsc/src/utils/renderPosts.tsx b/examples/react/start-basic-rsc/src/utils/renderPosts.tsx deleted file mode 100644 index 37c06612176..00000000000 --- a/examples/react/start-basic-rsc/src/utils/renderPosts.tsx +++ /dev/null @@ -1,63 +0,0 @@ -'use server' - -import React from 'react' -import { fetchPosts } from './posts' - -export async function renderPosts() { - const posts = await fetchPosts() - - posts.state = posts.state || { - status: 'pending', - promise: Promise.resolve(), - } - - return ( -
-
    - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }]?.map( - (post) => { - return ( -
  • - {post.title.substring(0, 20)} - {/* -
    {post.title.substring(0, 20)}
    - */} -
  • - ) - }, - )} -
-
- Loading...
}> - - - - ) -} - -function DelayedDateViaSuspense({ state }) { - // a component that will suspend for 1 second and then show the current date - if (state.status === 'pending') { - state.promise = new Promise((resolve) => { - setTimeout(() => { - state.status = 'success' - resolve() - }, 5000) - }) - throw state.promise - } - - return
{new Date().toISOString().replace('T', ' ').split('.')[0]}
-} - -// ...fetchPosts -// posts -// ...5000 -// timestamp diff --git a/examples/react/start-basic-rsc/src/utils/seo.ts b/examples/react/start-basic-rsc/src/utils/seo.ts deleted file mode 100644 index d18ad84b74e..00000000000 --- a/examples/react/start-basic-rsc/src/utils/seo.ts +++ /dev/null @@ -1,33 +0,0 @@ -export const seo = ({ - title, - description, - keywords, - image, -}: { - title: string - description?: string - image?: string - keywords?: string -}) => { - const tags = [ - { title }, - { name: 'description', content: description }, - { name: 'keywords', content: keywords }, - { name: 'twitter:title', content: title }, - { name: 'twitter:description', content: description }, - { name: 'twitter:creator', content: '@tannerlinsley' }, - { name: 'twitter:site', content: '@tannerlinsley' }, - { name: 'og:type', content: 'website' }, - { name: 'og:title', content: title }, - { name: 'og:description', content: description }, - ...(image - ? [ - { name: 'twitter:image', content: image }, - { name: 'twitter:card', content: 'summary_large_image' }, - { name: 'og:image', content: image }, - ] - : []), - ] - - return tags -} diff --git a/examples/react/start-basic-rsc/tsconfig.json b/examples/react/start-basic-rsc/tsconfig.json deleted file mode 100644 index 3a9fb7cd716..00000000000 --- a/examples/react/start-basic-rsc/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "baseUrl": ".", - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/examples/react/start-basic-rsc/vite.config.ts b/examples/react/start-basic-rsc/vite.config.ts deleted file mode 100644 index 843599315ef..00000000000 --- a/examples/react/start-basic-rsc/vite.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' -import viteReact from '@vitejs/plugin-react' -import tailwindcss from '@tailwindcss/vite' - -export default defineConfig({ - server: { - port: 3000, - }, - plugins: [ - tailwindcss(), - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], -}) diff --git a/examples/react/start-basic-static/.gitignore b/examples/react/start-basic-static/.gitignore deleted file mode 100644 index ca63f498851..00000000000 --- a/examples/react/start-basic-static/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -.DS_Store -.cache -.env -.vercel -.output -/build/ -/api/ -/server/build -/public/build# Sentry Config File -.env.sentry-build-plugin -/test-results/ -/playwright-report/ -/blob-report/ -/playwright/.cache/ diff --git a/examples/react/start-basic-static/.prettierignore b/examples/react/start-basic-static/.prettierignore deleted file mode 100644 index 2be5eaa6ece..00000000000 --- a/examples/react/start-basic-static/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/build -**/public -pnpm-lock.yaml -routeTree.gen.ts \ No newline at end of file diff --git a/examples/react/start-basic-static/README.md b/examples/react/start-basic-static/README.md index 9f05a926954..3dc335dfaec 100644 --- a/examples/react/start-basic-static/README.md +++ b/examples/react/start-basic-static/README.md @@ -1,44 +1,17 @@ -# TanStack Start - Static Example +# Deprecated: TanStack Start React Example (`start-basic-static`) -This site is built with TanStack Router! +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-basic-static start-basic-static -``` +- [Start React Quick Start](https://tanstack.com/router/latest/docs/framework/react/start/quick-start) +- [Static Prerendering](https://tanstack.com/router/latest/docs/framework/react/start/guide/static-prerendering) -## Deployment +Canonical issue reproduction baseline: -It's deployed automagically with Vercel! - -- [Vercel](https://vercel.com/) - -## Getting Started - -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -## Build - -Build for production: - -```sh -pnpm build -``` - -## About This Example - -This example demonstrates: - -- Static Site Generation (SSG) with TanStack Start -- Prerendering routes -- Static export +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-basic-static/package.json b/examples/react/start-basic-static/package.json deleted file mode 100644 index 934dad52c4a..00000000000 --- a/examples/react/start-basic-static/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "tanstack-start-example-basic-static", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" - }, - "dependencies": { - "@tanstack/react-router": "^1.161.1", - "@tanstack/react-router-devtools": "^1.161.1", - "@tanstack/react-start": "^1.161.1", - "@tanstack/start-static-server-functions": "^1.161.1", - "@vitejs/plugin-react": "^5.1.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0" - }, - "devDependencies": { - "@types/node": "^22.5.4", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "tailwindcss": "4.1.18", - "typescript": "^5.6.2", - "vite": "^7.3.1", - "vite-tsconfig-paths": "^5.1.3", - "@tailwindcss/vite": "4.1.18" - } -} diff --git a/examples/react/start-basic-static/public/android-chrome-192x192.png b/examples/react/start-basic-static/public/android-chrome-192x192.png deleted file mode 100644 index 09c8324f8c6..00000000000 Binary files a/examples/react/start-basic-static/public/android-chrome-192x192.png and /dev/null differ diff --git a/examples/react/start-basic-static/public/android-chrome-512x512.png b/examples/react/start-basic-static/public/android-chrome-512x512.png deleted file mode 100644 index 11d626ea3d0..00000000000 Binary files a/examples/react/start-basic-static/public/android-chrome-512x512.png and /dev/null differ diff --git a/examples/react/start-basic-static/public/apple-touch-icon.png b/examples/react/start-basic-static/public/apple-touch-icon.png deleted file mode 100644 index 5a9423cc02c..00000000000 Binary files a/examples/react/start-basic-static/public/apple-touch-icon.png and /dev/null differ diff --git a/examples/react/start-basic-static/public/favicon-16x16.png b/examples/react/start-basic-static/public/favicon-16x16.png deleted file mode 100644 index e3389b00443..00000000000 Binary files a/examples/react/start-basic-static/public/favicon-16x16.png and /dev/null differ diff --git a/examples/react/start-basic-static/public/favicon-32x32.png b/examples/react/start-basic-static/public/favicon-32x32.png deleted file mode 100644 index 900c77d444c..00000000000 Binary files a/examples/react/start-basic-static/public/favicon-32x32.png and /dev/null differ diff --git a/examples/react/start-basic-static/public/favicon.ico b/examples/react/start-basic-static/public/favicon.ico deleted file mode 100644 index 1a1751676f7..00000000000 Binary files a/examples/react/start-basic-static/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-basic-static/public/favicon.png b/examples/react/start-basic-static/public/favicon.png deleted file mode 100644 index 1e77bc06091..00000000000 Binary files a/examples/react/start-basic-static/public/favicon.png and /dev/null differ diff --git a/examples/react/start-basic-static/public/site.webmanifest b/examples/react/start-basic-static/public/site.webmanifest deleted file mode 100644 index fa99de77db6..00000000000 --- a/examples/react/start-basic-static/public/site.webmanifest +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "", - "short_name": "", - "icons": [ - { - "src": "/android-chrome-192x192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "/android-chrome-512x512.png", - "sizes": "512x512", - "type": "image/png" - } - ], - "theme_color": "#ffffff", - "background_color": "#ffffff", - "display": "standalone" -} diff --git a/examples/react/start-basic-static/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-static/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index 260c2ea41f7..00000000000 --- a/examples/react/start-basic-static/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { - ErrorComponent, - Link, - rootRouteId, - useMatch, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error('DefaultCatchBoundary Error:', error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/examples/react/start-basic-static/src/components/NotFound.tsx b/examples/react/start-basic-static/src/components/NotFound.tsx deleted file mode 100644 index fd4e75befe3..00000000000 --- a/examples/react/start-basic-static/src/components/NotFound.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: any }) { - return ( -
-
- {children ||

The page you are looking for does not exist.

} -
-

- - - Start Over - -

-
- ) -} diff --git a/examples/react/start-basic-static/src/routeTree.gen.ts b/examples/react/start-basic-static/src/routeTree.gen.ts deleted file mode 100644 index bb27e7cefc6..00000000000 --- a/examples/react/start-basic-static/src/routeTree.gen.ts +++ /dev/null @@ -1,374 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' - -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/deferred': typeof DeferredRoute - '/posts': typeof PostsRouteWithChildren - '/redirect': typeof RedirectRoute - '/users': typeof UsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts/': typeof PostsIndexRoute - '/users/': typeof UsersIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/deferred': typeof DeferredRoute - '/redirect': typeof RedirectRoute - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts': typeof PostsIndexRoute - '/users': typeof UsersIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren - '/deferred': typeof DeferredRoute - '/posts': typeof PostsRouteWithChildren - '/redirect': typeof RedirectRoute - '/users': typeof UsersRouteWithChildren - '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/_pathlessLayout/_nested-layout': typeof PathlessLayoutNestedLayoutRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts/': typeof PostsIndexRoute - '/users/': typeof UsersIndexRoute - '/_pathlessLayout/_nested-layout/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/_pathlessLayout/_nested-layout/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/posts_/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/deferred' - | '/posts' - | '/redirect' - | '/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts/' - | '/users/' - | '/route-a' - | '/route-b' - | '/posts/$postId/deep' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/deferred' - | '/redirect' - | '/posts/$postId' - | '/users/$userId' - | '/posts' - | '/users' - | '/route-a' - | '/route-b' - | '/posts/$postId/deep' - id: - | '__root__' - | '/' - | '/_pathlessLayout' - | '/deferred' - | '/posts' - | '/redirect' - | '/users' - | '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/_pathlessLayout/_nested-layout' - | '/posts/$postId' - | '/users/$userId' - | '/posts/' - | '/users/' - | '/_pathlessLayout/_nested-layout/route-a' - | '/_pathlessLayout/_nested-layout/route-b' - | '/posts_/$postId/deep' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren - DeferredRoute: typeof DeferredRoute - PostsRoute: typeof PostsRouteWithChildren - RedirectRoute: typeof RedirectRoute - UsersRoute: typeof UsersRouteWithChildren - PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '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/_pathlessLayout/_nested-layout': { - id: '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/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - } -} - -interface PathlessLayoutNestedLayoutRouteChildren { - PathlessLayoutNestedLayoutRouteARoute: typeof PathlessLayoutNestedLayoutRouteARoute - PathlessLayoutNestedLayoutRouteBRoute: typeof PathlessLayoutNestedLayoutRouteBRoute -} - -const PathlessLayoutNestedLayoutRouteChildren: PathlessLayoutNestedLayoutRouteChildren = - { - PathlessLayoutNestedLayoutRouteARoute: - PathlessLayoutNestedLayoutRouteARoute, - PathlessLayoutNestedLayoutRouteBRoute: - PathlessLayoutNestedLayoutRouteBRoute, - } - -const PathlessLayoutNestedLayoutRouteWithChildren = - PathlessLayoutNestedLayoutRoute._addFileChildren( - PathlessLayoutNestedLayoutRouteChildren, - ) - -interface PathlessLayoutRouteChildren { - PathlessLayoutNestedLayoutRoute: typeof PathlessLayoutNestedLayoutRouteWithChildren -} - -const PathlessLayoutRouteChildren: PathlessLayoutRouteChildren = { - PathlessLayoutNestedLayoutRoute: PathlessLayoutNestedLayoutRouteWithChildren, -} - -const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( - PathlessLayoutRouteChildren, -) - -interface PostsRouteChildren { - PostsPostIdRoute: typeof PostsPostIdRoute - PostsIndexRoute: typeof PostsIndexRoute -} - -const PostsRouteChildren: PostsRouteChildren = { - PostsPostIdRoute: PostsPostIdRoute, - PostsIndexRoute: PostsIndexRoute, -} - -const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) - -interface UsersRouteChildren { - UsersUserIdRoute: typeof UsersUserIdRoute - UsersIndexRoute: typeof UsersIndexRoute -} - -const UsersRouteChildren: UsersRouteChildren = { - UsersUserIdRoute: UsersUserIdRoute, - UsersIndexRoute: UsersIndexRoute, -} - -const UsersRouteWithChildren = UsersRoute._addFileChildren(UsersRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - PathlessLayoutRoute: PathlessLayoutRouteWithChildren, - DeferredRoute: DeferredRoute, - PostsRoute: PostsRouteWithChildren, - RedirectRoute: RedirectRoute, - UsersRoute: UsersRouteWithChildren, - PostsPostIdDeepRoute: PostsPostIdDeepRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' -declare module '@tanstack/react-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/examples/react/start-basic-static/src/router.tsx b/examples/react/start-basic-static/src/router.tsx deleted file mode 100644 index 5b15fa10597..00000000000 --- a/examples/react/start-basic-static/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - const router = createRouter({ - routeTree, - basepath: '/test/', - defaultPreload: 'intent', - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - scrollRestoration: true, - }) - - return router -} diff --git a/examples/react/start-basic-static/src/routes/__root.tsx b/examples/react/start-basic-static/src/routes/__root.tsx deleted file mode 100644 index 5a5c051bbe4..00000000000 --- a/examples/react/start-basic-static/src/routes/__root.tsx +++ /dev/null @@ -1,140 +0,0 @@ -/// -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import * as React from 'react' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' -import { NotFound } from '~/components/NotFound' -import appCss from '~/styles/app.css?url' -import { seo } from '~/utils/seo' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - ...seo({ - title: - 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', - description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, - }), - ], - links: [ - { rel: 'stylesheet', href: appCss }, - { - rel: 'apple-touch-icon', - sizes: '180x180', - href: '/apple-touch-icon.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '32x32', - href: '/favicon-32x32.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '16x16', - href: '/favicon-16x16.png', - }, - { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, - { rel: 'icon', href: '/favicon.ico' }, - ], - }), - errorComponent: (props) => { - return ( - - - - ) - }, - notFoundComponent: () => , - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - ) -} - -function RootLayout({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- - Home - {' '} - - Posts - {' '} - - Users - {' '} - - Pathless Layout - {' '} - - Deferred - {' '} - - This Route Does Not Exist - -
-
- {children} - - - - - ) -} diff --git a/examples/react/start-basic-static/src/routes/_pathlessLayout.tsx b/examples/react/start-basic-static/src/routes/_pathlessLayout.tsx deleted file mode 100644 index 29d3477145c..00000000000 --- a/examples/react/start-basic-static/src/routes/_pathlessLayout.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout')({ - component: PathlessLayoutComponent, -}) - -function PathlessLayoutComponent() { - return ( -
-
I'm a pathless layout
-
- -
-
- ) -} diff --git a/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout.tsx b/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout.tsx deleted file mode 100644 index 9a48b73a468..00000000000 --- a/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('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/_pathlessLayout/_nested-layout')({ - component: LayoutComponent, -}) - -function LayoutComponent() { - return ( -
-
I'm a nested layout
-
- - Go to route A - - - Go to route B - -
-
- -
-
- ) -} diff --git a/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout/route-a.tsx b/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout/route-a.tsx deleted file mode 100644 index 0213f1516f4..00000000000 --- a/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout/route-a.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-a')( - { - component: LayoutAComponent, - }, -) - -function LayoutAComponent() { - return
I'm A!
-} diff --git a/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout/route-b.tsx b/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout/route-b.tsx deleted file mode 100644 index 3d909523fb9..00000000000 --- a/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout/route-b.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-b')( - { - component: LayoutBComponent, - }, -) - -function LayoutBComponent() { - return
I'm B!
-} diff --git a/examples/react/start-basic-static/src/routes/deferred.tsx b/examples/react/start-basic-static/src/routes/deferred.tsx deleted file mode 100644 index f0d832b8055..00000000000 --- a/examples/react/start-basic-static/src/routes/deferred.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { Suspense, useState } from 'react' -import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' - -const personServerFn = createServerFn({ method: 'GET' }) - .middleware([staticFunctionMiddleware]) - .inputValidator((d: string) => d) - .handler(({ data: name }) => { - return { name, randomNumber: Math.floor(Math.random() * 100) } - }) - -const slowServerFn = createServerFn({ method: 'GET' }) - .middleware([staticFunctionMiddleware]) - .inputValidator((d: string) => d) - .handler(async ({ data: name }) => { - await new Promise((r) => setTimeout(r, 1000)) - return { name, randomNumber: Math.floor(Math.random() * 100) } - }) - -export const Route = createFileRoute('/deferred')({ - loader: async () => { - return { - deferredStuff: new Promise((r) => - setTimeout(() => r('Hello deferred!'), 2000), - ), - deferredPerson: slowServerFn({ data: 'Tanner Linsley' }), - person: await personServerFn({ data: 'John Doe' }), - } - }, - component: Deferred, -}) - -function Deferred() { - const [count, setCount] = useState(0) - const { deferredStuff, deferredPerson, person } = Route.useLoaderData() - - return ( -
-
- {person.name} - {person.randomNumber} -
- Loading person...
}> - ( -
- {data.name} - {data.randomNumber} -
- )} - /> - - Loading stuff...}> -

{data}

} - /> -
-
Count: {count}
-
- -
- - ) -} diff --git a/examples/react/start-basic-static/src/routes/index.tsx b/examples/react/start-basic-static/src/routes/index.tsx deleted file mode 100644 index 37c8d237bd4..00000000000 --- a/examples/react/start-basic-static/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Welcome Home!!!

-
- ) -} diff --git a/examples/react/start-basic-static/src/routes/posts.$postId.tsx b/examples/react/start-basic-static/src/routes/posts.$postId.tsx deleted file mode 100644 index 301f675142e..00000000000 --- a/examples/react/start-basic-static/src/routes/posts.$postId.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { ErrorComponent, Link, createFileRoute } from '@tanstack/react-router' -import { fetchPost } from '../utils/posts' -import type { ErrorComponentProps } from '@tanstack/react-router' -import { NotFound } from '~/components/NotFound' - -export const Route = createFileRoute('/posts/$postId')({ - loader: ({ params: { postId } }) => fetchPost({ data: postId }), - errorComponent: PostErrorComponent, - component: PostComponent, - notFoundComponent: () => { - return Post not found - }, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return -} - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.title}

-
{post.body}
- - Deep View - -
- ) -} diff --git a/examples/react/start-basic-static/src/routes/posts.index.tsx b/examples/react/start-basic-static/src/routes/posts.index.tsx deleted file mode 100644 index c6592745679..00000000000 --- a/examples/react/start-basic-static/src/routes/posts.index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/posts/')({ - component: PostsIndexComponent, -}) - -function PostsIndexComponent() { - return
Select a post.
-} diff --git a/examples/react/start-basic-static/src/routes/posts.tsx b/examples/react/start-basic-static/src/routes/posts.tsx deleted file mode 100644 index ae49032459f..00000000000 --- a/examples/react/start-basic-static/src/routes/posts.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../utils/posts' - -export const Route = createFileRoute('/posts')({ - loader: async () => fetchPosts(), - component: PostsComponent, -}) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( - (post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - }, - )} -
-
- -
- ) -} diff --git a/examples/react/start-basic-static/src/routes/posts_.$postId.deep.tsx b/examples/react/start-basic-static/src/routes/posts_.$postId.deep.tsx deleted file mode 100644 index a82d2e32117..00000000000 --- a/examples/react/start-basic-static/src/routes/posts_.$postId.deep.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { fetchPost } from '../utils/posts' -import { PostErrorComponent } from './posts.$postId' - -export const Route = createFileRoute('/posts_/$postId/deep')({ - loader: ({ params: { postId } }) => - fetchPost({ - data: postId, - }), - errorComponent: PostErrorComponent, - component: PostDeepComponent, -}) - -function PostDeepComponent() { - const post = Route.useLoaderData() - - return ( -
- - ← All Posts - -

{post.title}

-
{post.body}
-
- ) -} diff --git a/examples/react/start-basic-static/src/routes/redirect.tsx b/examples/react/start-basic-static/src/routes/redirect.tsx deleted file mode 100644 index fa220b50975..00000000000 --- a/examples/react/start-basic-static/src/routes/redirect.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { redirect, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/redirect')({ - beforeLoad: async () => { - throw redirect({ - to: '/posts', - }) - }, -}) diff --git a/examples/react/start-basic-static/src/routes/users.$userId.tsx b/examples/react/start-basic-static/src/routes/users.$userId.tsx deleted file mode 100644 index 2e163f86ef4..00000000000 --- a/examples/react/start-basic-static/src/routes/users.$userId.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { ErrorComponent, createFileRoute } from '@tanstack/react-router' -import axios from 'redaxios' -import { createServerFn } from '@tanstack/react-start' -import type { ErrorComponentProps } from '@tanstack/react-router' -import type { User } from '~/utils/users' -import { NotFound } from '~/components/NotFound' -import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' - -const fetchUser = createServerFn({ method: 'GET' }) - .middleware([staticFunctionMiddleware]) - .inputValidator((d: string) => d) - .handler(async ({ data: userId }) => { - return axios - .get('https://jsonplaceholder.typicode.com/users/' + userId) - .then((d) => ({ - id: d.data.id, - name: d.data.name, - email: d.data.email, - })) - .catch((e) => { - throw new Error('Failed to fetch user') - }) - }) - -export const Route = createFileRoute('/users/$userId')({ - loader: ({ params: { userId } }) => fetchUser({ data: userId }), - errorComponent: UserErrorComponent, - component: UserComponent, - notFoundComponent: () => { - return User not found - }, -}) - -export function UserErrorComponent({ error }: ErrorComponentProps) { - return -} - -function UserComponent() { - const user = Route.useLoaderData() - - if ('error' in user) { - return User not found - } - - return ( -
-

{user.name}

-
{user.email}
-
- ) -} diff --git a/examples/react/start-basic-static/src/routes/users.index.tsx b/examples/react/start-basic-static/src/routes/users.index.tsx deleted file mode 100644 index ea814e2cbf8..00000000000 --- a/examples/react/start-basic-static/src/routes/users.index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/users/')({ - component: UsersIndexComponent, -}) - -function UsersIndexComponent() { - return
Select a user.
-} diff --git a/examples/react/start-basic-static/src/routes/users.tsx b/examples/react/start-basic-static/src/routes/users.tsx deleted file mode 100644 index 98fb79518b3..00000000000 --- a/examples/react/start-basic-static/src/routes/users.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import axios from 'redaxios' -import { createServerFn } from '@tanstack/react-start' -import type { User } from '../utils/users' -import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' - -const fetchUsers = createServerFn({ method: 'GET' }) - .middleware([staticFunctionMiddleware]) - .handler(async () => { - console.info('Fetching users...') - const res = await axios.get>( - 'https://jsonplaceholder.typicode.com/users', - ) - - return res.data - .slice(0, 10) - .map((u) => ({ id: u.id, name: u.name, email: u.email })) - }) - -export const Route = createFileRoute('/users')({ - loader: async () => fetchUsers(), - component: UsersComponent, -}) - -function UsersComponent() { - const users = Route.useLoaderData() - - return ( -
-
    - {[ - ...users, - { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, - ].map((user) => { - return ( -
  • - -
    {user.name}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/examples/react/start-basic-static/src/styles/app.css b/examples/react/start-basic-static/src/styles/app.css deleted file mode 100644 index fa969827060..00000000000 --- a/examples/react/start-basic-static/src/styles/app.css +++ /dev/null @@ -1,32 +0,0 @@ -@import 'tailwindcss' source('../'); - -@source '../**/*.{js,jsx,ts,tsx}'; - -/* - The default border color has changed to `currentcolor` in Tailwind CSS v4, - so we've added these compatibility styles to make sure everything still - looks the same as it did with Tailwind CSS v3. - - If we ever want to remove these styles, we need to add an explicit border - color utility to any element that depends on these defaults. -*/ -@layer base { - *, - ::after, - ::before, - ::backdrop, - ::file-selector-button { - border-color: var(--color-gray-200, currentcolor); - } -} - -@layer base { - html, - body { - @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; - } - - .using-mouse * { - outline: none !important; - } -} diff --git a/examples/react/start-basic-static/src/utils/loggingMiddleware.tsx b/examples/react/start-basic-static/src/utils/loggingMiddleware.tsx deleted file mode 100644 index 80ef49b306f..00000000000 --- a/examples/react/start-basic-static/src/utils/loggingMiddleware.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start' - -export const logMiddleware = createMiddleware({ type: 'function' }) - .middleware([ - createMiddleware({ type: 'function' }) - .client(async (ctx) => { - const clientTime = new Date() - - return await ctx.next({ - context: { - clientTime, - }, - sendContext: { - clientTime, - }, - }) - }) - .server(async (ctx) => { - const serverTime = new Date() - - return await ctx.next({ - sendContext: { - serverTime, - durationToServer: - serverTime.getTime() - ctx.context.clientTime.getTime(), - }, - }) - }), - ]) - .client(async (options) => { - const result = await options.next() - - const now = new Date() - - console.log('Client Req/Res:', { - duration: result.context.clientTime.getTime() - now.getTime(), - durationToServer: result.context.durationToServer, - durationFromServer: now.getTime() - result.context.serverTime.getTime(), - }) - - return result - }) diff --git a/examples/react/start-basic-static/src/utils/posts.tsx b/examples/react/start-basic-static/src/utils/posts.tsx deleted file mode 100644 index 5f01de769ae..00000000000 --- a/examples/react/start-basic-static/src/utils/posts.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { createServerFn } from '@tanstack/react-start' -import axios from 'redaxios' -import { notFound } from '@tanstack/react-router' -import { logMiddleware } from './loggingMiddleware' -import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' - -export type PostType = { - id: string - title: string - body: string -} - -export const fetchPost = createServerFn({ method: 'GET' }) - .middleware([logMiddleware, staticFunctionMiddleware]) - .inputValidator((d: string) => d) - .handler(async ({ data }) => { - console.info(`Fetching post with id ${data}...`) - const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${data}`) - .catch((err) => { - if (err.status === 404) { - throw notFound() - } - throw err - }) - .then((r) => r.data) - - return post - }) - -export const fetchPosts = createServerFn({ method: 'GET' }) - .middleware([logMiddleware, staticFunctionMiddleware]) - .handler(async () => { - console.info('Fetching posts...') - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) - }) diff --git a/examples/react/start-basic-static/src/utils/seo.ts b/examples/react/start-basic-static/src/utils/seo.ts deleted file mode 100644 index d18ad84b74e..00000000000 --- a/examples/react/start-basic-static/src/utils/seo.ts +++ /dev/null @@ -1,33 +0,0 @@ -export const seo = ({ - title, - description, - keywords, - image, -}: { - title: string - description?: string - image?: string - keywords?: string -}) => { - const tags = [ - { title }, - { name: 'description', content: description }, - { name: 'keywords', content: keywords }, - { name: 'twitter:title', content: title }, - { name: 'twitter:description', content: description }, - { name: 'twitter:creator', content: '@tannerlinsley' }, - { name: 'twitter:site', content: '@tannerlinsley' }, - { name: 'og:type', content: 'website' }, - { name: 'og:title', content: title }, - { name: 'og:description', content: description }, - ...(image - ? [ - { name: 'twitter:image', content: image }, - { name: 'twitter:card', content: 'summary_large_image' }, - { name: 'og:image', content: image }, - ] - : []), - ] - - return tags -} diff --git a/examples/react/start-basic-static/src/utils/users.tsx b/examples/react/start-basic-static/src/utils/users.tsx deleted file mode 100644 index b810f455fe5..00000000000 --- a/examples/react/start-basic-static/src/utils/users.tsx +++ /dev/null @@ -1,7 +0,0 @@ -export type User = { - id: number - name: string - email: string -} - -export const DEPLOY_URL = 'http://localhost:3000' diff --git a/examples/react/start-basic-static/tsconfig.json b/examples/react/start-basic-static/tsconfig.json deleted file mode 100644 index 3a9fb7cd716..00000000000 --- a/examples/react/start-basic-static/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "baseUrl": ".", - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/examples/react/start-basic-static/vite.config.ts b/examples/react/start-basic-static/vite.config.ts deleted file mode 100644 index 0de9a0db198..00000000000 --- a/examples/react/start-basic-static/vite.config.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' -import viteReact from '@vitejs/plugin-react' -import tailwindcss from '@tailwindcss/vite' - -export default defineConfig({ - base: '/test/', - server: { - port: 3000, - }, - plugins: [ - tailwindcss(), - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart({ - spa: { - enabled: true, - prerender: { - crawlLinks: true, - }, - }, - sitemap: { - host: 'https://localhost:3000', - }, - prerender: { - failOnError: false, - }, - }), - viteReact(), - ], -}) diff --git a/examples/react/start-bun/.gitignore b/examples/react/start-bun/.gitignore deleted file mode 100644 index 029f7fba9a9..00000000000 --- a/examples/react/start-bun/.gitignore +++ /dev/null @@ -1,12 +0,0 @@ -node_modules -.DS_Store -dist -dist-ssr -*.local -count.txt -.env -.nitro -.tanstack -.output -.vinxi -todos.json diff --git a/examples/react/start-bun/.prettierignore b/examples/react/start-bun/.prettierignore deleted file mode 100644 index 5322d7feeae..00000000000 --- a/examples/react/start-bun/.prettierignore +++ /dev/null @@ -1,3 +0,0 @@ -package-lock.json -pnpm-lock.yaml -yarn.lock \ No newline at end of file diff --git a/examples/react/start-bun/.vscode/settings.json b/examples/react/start-bun/.vscode/settings.json deleted file mode 100644 index 00b5278e580..00000000000 --- a/examples/react/start-bun/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "files.watcherExclude": { - "**/routeTree.gen.ts": true - }, - "search.exclude": { - "**/routeTree.gen.ts": true - }, - "files.readonlyInclude": { - "**/routeTree.gen.ts": true - } -} diff --git a/examples/react/start-bun/README.md b/examples/react/start-bun/README.md index 04920e8796c..73c4f8ca110 100644 --- a/examples/react/start-bun/README.md +++ b/examples/react/start-bun/README.md @@ -1,209 +1,16 @@ -# TanStack Start + Bun Production Server +# Deprecated: TanStack Start React Example (`start-bun`) -An optimized production server for TanStack Start applications using Bun, implementing intelligent static asset loading with configurable memory management. +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) -- [Bun Documentation](https://bun.sh/docs) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-bun start-bun -``` +- [Start React Hosting Guide](https://tanstack.com/router/latest/docs/framework/react/start/guide/hosting) -## 🚀 Features +Canonical issue reproduction baseline: -- **Hybrid Loading Strategy**: Small files are preloaded into memory, large files are served on-demand -- **Configurable File Filtering**: Include/Exclude patterns for precise control -- **Memory-efficient Response Generation**: Optimized for high performance -- **Production-ready Caching Headers**: Automatic Cache-Control headers for optimal performance -- **Detailed Logging**: Vite-like output for better overview - -## 📦 Installation - -This project was created with TanStack Start: - -```bash -bunx create-start-app@latest -``` - -Install dependencies: - -```bash -bun install -``` - -## 🏃‍♂️ Development - -For development: - -```bash -bun run dev -``` - -## 🔨 Production Build - -Build the application for production: - -```bash -bun run build -``` - -## 🚀 Production Server with server.ts - -### Quick Start - Use in Your Project - -You can easily use this production server in your own TanStack Start project: - -1. **Copy the `server.ts` file** into your project root -2. **Build your project** with `bun run build` -3. **Start the server** directly with: - ```bash - bun run server.ts - ``` - -Or add it to your `package.json` scripts: - -```json -{ - "scripts": { - "start": "bun run server.ts" - } -} -``` - -Then run with: - -```bash -bun run start -``` - -### Server Features - -The `server.ts` implements a high-performance production server with the following features: - -#### 1. Intelligent Asset Loading - -The server automatically decides which files to preload into memory and which to serve on-demand: - -- **In-Memory Loading**: Small files (default < 5MB) are loaded into memory at startup -- **On-Demand Loading**: Large files are loaded from disk only when requested -- **Optimized Performance**: Frequently used assets are served from memory - -#### 2. Configuration via Environment Variables - -```bash -# Server Port (default: 3000) -PORT=3000 - -# Maximum file size for in-memory loading (in bytes, default: 5MB) -STATIC_PRELOAD_MAX_BYTES=5242880 - -# Include patterns (comma-separated, only these files will be preloaded) -STATIC_PRELOAD_INCLUDE="*.js,*.css,*.woff2" - -# Exclude patterns (comma-separated, these files will be excluded) -STATIC_PRELOAD_EXCLUDE="*.map,*.txt" - -# Enable detailed logging -STATIC_PRELOAD_VERBOSE=true -``` - -### Example Configurations - -#### Minimal Memory Footprint - -```bash -# Preload only critical assets -STATIC_PRELOAD_MAX_BYTES=1048576 \ -STATIC_PRELOAD_INCLUDE="*.js,*.css" \ -STATIC_PRELOAD_EXCLUDE="*.map,vendor-*" \ -bun run start -``` - -#### Maximum Performance - -```bash -# Preload all small assets -STATIC_PRELOAD_MAX_BYTES=10485760 \ -bun run start -``` - -#### Debug Mode - -```bash -# With detailed logging -STATIC_PRELOAD_VERBOSE=true \ -bun run start -``` - -### Server Output - -The server displays a clear overview of all loaded assets at startup: - -```txt -📦 Loading static assets from ./dist/client... - Max preload size: 5.00 MB - Include patterns: *.js,*.css,*.woff2 - -📁 Preloaded into memory: - /assets/index-a1b2c3d4.js 45.23 kB │ gzip: 15.83 kB - /assets/index-e5f6g7h8.css 12.45 kB │ gzip: 4.36 kB - -💾 Served on-demand: - /assets/vendor-i9j0k1l2.js 245.67 kB │ gzip: 86.98 kB - -✅ Preloaded 2 files (57.68 KB) into memory -ℹ️ 1 files will be served on-demand (1 too large, 0 filtered) - -🚀 Server running at http://localhost:3000 -``` - -## Getting Started - -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -## Build - -Build for production: - -```sh -pnpm build -``` - -## Production - -Start the production server: - -```sh -pnpm start -``` - -## Testing - -This project uses [Vitest](https://vitest.dev/) for testing. You can run the tests with: - -```bash -bun run test -``` - -## Styling - -This project uses [Tailwind CSS](https://tailwindcss.com/) for styling. - -## Linting & Formatting - -This project uses [eslint](https://eslint.org/) and [prettier](https://prettier.io/) for linting and formatting. Eslint is configured using [tanstack/eslint-config](https://tanstack.com/config/latest/docs/eslint). The following scripts are available: - -```bash -bun run lint -bun run format -bun run check -``` +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-bun/eslint.config.js b/examples/react/start-bun/eslint.config.js deleted file mode 100644 index 676b32a87ff..00000000000 --- a/examples/react/start-bun/eslint.config.js +++ /dev/null @@ -1,5 +0,0 @@ -// @ts-check - -import { tanstackConfig } from '@tanstack/eslint-config' - -export default [...tanstackConfig] diff --git a/examples/react/start-bun/package.json b/examples/react/start-bun/package.json deleted file mode 100644 index b0d60ae6bb9..00000000000 --- a/examples/react/start-bun/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "tanstack-start-bun-hosting", - "private": true, - "type": "module", - "scripts": { - "dev": "vite dev --port 3000", - "start": "bun run server.ts", - "build": "vite build", - "preview": "vite preview", - "test": "vitest run", - "lint": "eslint", - "format": "prettier", - "check": "prettier --write . && eslint --fix" - }, - "dependencies": { - "@tailwindcss/vite": "^4.1.18", - "@tanstack/react-devtools": "^0.7.0", - "@tanstack/react-router": "^1.161.1", - "@tanstack/react-router-devtools": "^1.161.1", - "@tanstack/react-router-ssr-query": "^1.161.1", - "@tanstack/react-start": "^1.161.1", - "@tanstack/router-plugin": "^1.161.1", - "react": "^19.1.1", - "react-dom": "^19.1.1", - "tailwindcss": "^4.1.18", - "vite-tsconfig-paths": "^5.1.4" - }, - "devDependencies": { - "@tanstack/eslint-config": "^0.3.2", - "@testing-library/dom": "^10.4.1", - "@testing-library/react": "^16.3.0", - "@types/bun": "^1.2.22", - "@types/node": "22.10.2", - "@types/react": "^19.1.13", - "@types/react-dom": "^19.1.9", - "@vitejs/plugin-react": "^5.0.3", - "jsdom": "^27.0.0", - "prettier": "^3.6.2", - "typescript": "^5.9.2", - "vite": "^7.3.1", - "vitest": "^3.2.4", - "web-vitals": "^5.1.0" - } -} diff --git a/examples/react/start-bun/prettier.config.js b/examples/react/start-bun/prettier.config.js deleted file mode 100644 index f7279f7ba51..00000000000 --- a/examples/react/start-bun/prettier.config.js +++ /dev/null @@ -1,10 +0,0 @@ -// @ts-check - -/** @type {import('prettier').Config} */ -const config = { - semi: false, - singleQuote: true, - trailingComma: 'all', -} - -export default config diff --git a/examples/react/start-bun/public/favicon.ico b/examples/react/start-bun/public/favicon.ico deleted file mode 100644 index a11777cc471..00000000000 Binary files a/examples/react/start-bun/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-bun/public/logo192.png b/examples/react/start-bun/public/logo192.png deleted file mode 100644 index fc44b0a3796..00000000000 Binary files a/examples/react/start-bun/public/logo192.png and /dev/null differ diff --git a/examples/react/start-bun/public/logo512.png b/examples/react/start-bun/public/logo512.png deleted file mode 100644 index a4e47a6545b..00000000000 Binary files a/examples/react/start-bun/public/logo512.png and /dev/null differ diff --git a/examples/react/start-bun/public/manifest.json b/examples/react/start-bun/public/manifest.json deleted file mode 100644 index 078ef501162..00000000000 --- a/examples/react/start-bun/public/manifest.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "short_name": "TanStack App", - "name": "Create TanStack App Sample", - "icons": [ - { - "src": "favicon.ico", - "sizes": "64x64 32x32 24x24 16x16", - "type": "image/x-icon" - }, - { - "src": "logo192.png", - "type": "image/png", - "sizes": "192x192" - }, - { - "src": "logo512.png", - "type": "image/png", - "sizes": "512x512" - } - ], - "start_url": ".", - "display": "standalone", - "theme_color": "#000000", - "background_color": "#ffffff" -} diff --git a/examples/react/start-bun/public/robots.txt b/examples/react/start-bun/public/robots.txt deleted file mode 100644 index e9e57dc4d41..00000000000 --- a/examples/react/start-bun/public/robots.txt +++ /dev/null @@ -1,3 +0,0 @@ -# https://www.robotstxt.org/robotstxt.html -User-agent: * -Disallow: diff --git a/examples/react/start-bun/server.ts b/examples/react/start-bun/server.ts deleted file mode 100644 index be8d3b1ed5a..00000000000 --- a/examples/react/start-bun/server.ts +++ /dev/null @@ -1,556 +0,0 @@ -/** - * TanStack Start Production Server with Bun - * - * A high-performance production server for TanStack Start applications that - * implements intelligent static asset loading with configurable memory management. - * - * Features: - * - Hybrid loading strategy (preload small files, serve large files on-demand) - * - Configurable file filtering with include/exclude patterns - * - Memory-efficient response generation - * - Production-ready caching headers - * - * Environment Variables: - * - * PORT (number) - * - Server port number - * - Default: 3000 - * - * ASSET_PRELOAD_MAX_SIZE (number) - * - Maximum file size in bytes to preload into memory - * - Files larger than this will be served on-demand from disk - * - Default: 5242880 (5MB) - * - Example: ASSET_PRELOAD_MAX_SIZE=5242880 (5MB) - * - * ASSET_PRELOAD_INCLUDE_PATTERNS (string) - * - Comma-separated list of glob patterns for files to include - * - If specified, only matching files are eligible for preloading - * - Patterns are matched against filenames only, not full paths - * - Example: ASSET_PRELOAD_INCLUDE_PATTERNS="*.js,*.css,*.woff2" - * - * ASSET_PRELOAD_EXCLUDE_PATTERNS (string) - * - Comma-separated list of glob patterns for files to exclude - * - Applied after include patterns - * - Patterns are matched against filenames only, not full paths - * - Example: ASSET_PRELOAD_EXCLUDE_PATTERNS="*.map,*.txt" - * - * ASSET_PRELOAD_VERBOSE_LOGGING (boolean) - * - Enable detailed logging of loaded and skipped files - * - Default: false - * - Set to "true" to enable verbose output - * - * ASSET_PRELOAD_ENABLE_ETAG (boolean) - * - Enable ETag generation for preloaded assets - * - Default: true - * - Set to "false" to disable ETag support - * - * ASSET_PRELOAD_ENABLE_GZIP (boolean) - * - Enable Gzip compression for eligible assets - * - Default: true - * - Set to "false" to disable Gzip compression - * - * ASSET_PRELOAD_GZIP_MIN_SIZE (number) - * - Minimum file size in bytes required for Gzip compression - * - Files smaller than this will not be compressed - * - Default: 1024 (1KB) - * - * ASSET_PRELOAD_GZIP_MIME_TYPES (string) - * - Comma-separated list of MIME types eligible for Gzip compression - * - Supports partial matching for types ending with "/" - * - Default: text/,application/javascript,application/json,application/xml,image/svg+xml - * - * Usage: - * bun run server.ts - */ - -import path from 'node:path' - -// Configuration -const SERVER_PORT = Number(process.env.PORT ?? 3000) -const CLIENT_DIRECTORY = './dist/client' -const SERVER_ENTRY_POINT = './dist/server/server.js' - -// Logging utilities for professional output -const log = { - info: (message: string) => { - console.log(`[INFO] ${message}`) - }, - success: (message: string) => { - console.log(`[SUCCESS] ${message}`) - }, - warning: (message: string) => { - console.log(`[WARNING] ${message}`) - }, - error: (message: string) => { - console.log(`[ERROR] ${message}`) - }, - header: (message: string) => { - console.log(`\n${message}\n`) - }, -} - -// Preloading configuration from environment variables -const MAX_PRELOAD_BYTES = Number( - process.env.ASSET_PRELOAD_MAX_SIZE ?? 5 * 1024 * 1024, // 5MB default -) - -// Parse comma-separated include patterns (no defaults) -const INCLUDE_PATTERNS = (process.env.ASSET_PRELOAD_INCLUDE_PATTERNS ?? '') - .split(',') - .map((s) => s.trim()) - .filter(Boolean) - .map((pattern: string) => convertGlobToRegExp(pattern)) - -// Parse comma-separated exclude patterns (no defaults) -const EXCLUDE_PATTERNS = (process.env.ASSET_PRELOAD_EXCLUDE_PATTERNS ?? '') - .split(',') - .map((s) => s.trim()) - .filter(Boolean) - .map((pattern: string) => convertGlobToRegExp(pattern)) - -// Verbose logging flag -const VERBOSE = process.env.ASSET_PRELOAD_VERBOSE_LOGGING === 'true' - -// Optional ETag feature -const ENABLE_ETAG = (process.env.ASSET_PRELOAD_ENABLE_ETAG ?? 'true') === 'true' - -// Optional Gzip feature -const ENABLE_GZIP = (process.env.ASSET_PRELOAD_ENABLE_GZIP ?? 'true') === 'true' -const GZIP_MIN_BYTES = Number(process.env.ASSET_PRELOAD_GZIP_MIN_SIZE ?? 1024) // 1KB -const GZIP_TYPES = ( - process.env.ASSET_PRELOAD_GZIP_MIME_TYPES ?? - 'text/,application/javascript,application/json,application/xml,image/svg+xml' -) - .split(',') - .map((v) => v.trim()) - .filter(Boolean) - -/** - * Convert a simple glob pattern to a regular expression - * Supports * wildcard for matching any characters - */ -function convertGlobToRegExp(globPattern: string): RegExp { - // Escape regex special chars except *, then replace * with .* - const escapedPattern = globPattern - .replace(/[-/\\^$+?.()|[\]{}]/g, '\\$&') - .replace(/\*/g, '.*') - return new RegExp(`^${escapedPattern}$`, 'i') -} - -/** - * Compute ETag for a given data buffer - */ -function computeEtag(data: Uint8Array): string { - const hash = Bun.hash(data) - return `W/"${hash.toString(16)}-${data.byteLength.toString()}"` -} - -/** - * Metadata for preloaded static assets - */ -interface AssetMetadata { - route: string - size: number - type: string -} - -/** - * In-memory asset with ETag and Gzip support - */ -interface InMemoryAsset { - raw: Uint8Array - gz?: Uint8Array - etag?: string - type: string - immutable: boolean - size: number -} - -/** - * Result of static asset preloading process - */ -interface PreloadResult { - routes: Record Response | Promise> - loaded: AssetMetadata[] - skipped: AssetMetadata[] -} - -/** - * Check if a file is eligible for preloading based on configured patterns - */ -function isFileEligibleForPreloading(relativePath: string): boolean { - const fileName = relativePath.split(/[/\\]/).pop() ?? relativePath - - // If include patterns are specified, file must match at least one - if (INCLUDE_PATTERNS.length > 0) { - if (!INCLUDE_PATTERNS.some((pattern) => pattern.test(fileName))) { - return false - } - } - - // If exclude patterns are specified, file must not match any - if (EXCLUDE_PATTERNS.some((pattern) => pattern.test(fileName))) { - return false - } - - return true -} - -/** - * Check if a MIME type is compressible - */ -function isMimeTypeCompressible(mimeType: string): boolean { - return GZIP_TYPES.some((type) => - type.endsWith('/') ? mimeType.startsWith(type) : mimeType === type, - ) -} - -/** - * Conditionally compress data based on size and MIME type - */ -function compressDataIfAppropriate( - data: Uint8Array, - mimeType: string, -): Uint8Array | undefined { - if (!ENABLE_GZIP) return undefined - if (data.byteLength < GZIP_MIN_BYTES) return undefined - if (!isMimeTypeCompressible(mimeType)) return undefined - try { - return Bun.gzipSync(data.buffer as ArrayBuffer) - } catch { - return undefined - } -} - -/** - * Create response handler function with ETag and Gzip support - */ -function createResponseHandler( - asset: InMemoryAsset, -): (req: Request) => Response { - return (req: Request) => { - const headers: Record = { - 'Content-Type': asset.type, - 'Cache-Control': asset.immutable - ? 'public, max-age=31536000, immutable' - : 'public, max-age=3600', - } - - if (ENABLE_ETAG && asset.etag) { - const ifNone = req.headers.get('if-none-match') - if (ifNone && ifNone === asset.etag) { - return new Response(null, { - status: 304, - headers: { ETag: asset.etag }, - }) - } - headers.ETag = asset.etag - } - - if ( - ENABLE_GZIP && - asset.gz && - req.headers.get('accept-encoding')?.includes('gzip') - ) { - headers['Content-Encoding'] = 'gzip' - headers['Content-Length'] = String(asset.gz.byteLength) - const gzCopy = new Uint8Array(asset.gz) - return new Response(gzCopy, { status: 200, headers }) - } - - headers['Content-Length'] = String(asset.raw.byteLength) - const rawCopy = new Uint8Array(asset.raw) - return new Response(rawCopy, { status: 200, headers }) - } -} - -/** - * Create composite glob pattern from include patterns - */ -function createCompositeGlobPattern(): Bun.Glob { - const raw = (process.env.ASSET_PRELOAD_INCLUDE_PATTERNS ?? '') - .split(',') - .map((s) => s.trim()) - .filter(Boolean) - if (raw.length === 0) return new Bun.Glob('**/*') - if (raw.length === 1) return new Bun.Glob(raw[0]) - return new Bun.Glob(`{${raw.join(',')}}`) -} - -/** - * Initialize static routes with intelligent preloading strategy - * Small files are loaded into memory, large files are served on-demand - */ -async function initializeStaticRoutes( - clientDirectory: string, -): Promise { - const routes: Record Response | Promise> = - {} - const loaded: AssetMetadata[] = [] - const skipped: AssetMetadata[] = [] - - log.info(`Loading static assets from ${clientDirectory}...`) - if (VERBOSE) { - console.log( - `Max preload size: ${(MAX_PRELOAD_BYTES / 1024 / 1024).toFixed(2)} MB`, - ) - if (INCLUDE_PATTERNS.length > 0) { - console.log( - `Include patterns: ${process.env.ASSET_PRELOAD_INCLUDE_PATTERNS ?? ''}`, - ) - } - if (EXCLUDE_PATTERNS.length > 0) { - console.log( - `Exclude patterns: ${process.env.ASSET_PRELOAD_EXCLUDE_PATTERNS ?? ''}`, - ) - } - } - - let totalPreloadedBytes = 0 - - try { - const glob = createCompositeGlobPattern() - for await (const relativePath of glob.scan({ cwd: clientDirectory })) { - const filepath = path.join(clientDirectory, relativePath) - const route = `/${relativePath.split(path.sep).join(path.posix.sep)}` - - try { - // Get file metadata - const file = Bun.file(filepath) - - // Skip if file doesn't exist or is empty - if (!(await file.exists()) || file.size === 0) { - continue - } - - const metadata: AssetMetadata = { - route, - size: file.size, - type: file.type || 'application/octet-stream', - } - - // Determine if file should be preloaded - const matchesPattern = isFileEligibleForPreloading(relativePath) - const withinSizeLimit = file.size <= MAX_PRELOAD_BYTES - - if (matchesPattern && withinSizeLimit) { - // Preload small files into memory with ETag and Gzip support - const bytes = new Uint8Array(await file.arrayBuffer()) - const gz = compressDataIfAppropriate(bytes, metadata.type) - const etag = ENABLE_ETAG ? computeEtag(bytes) : undefined - const asset: InMemoryAsset = { - raw: bytes, - gz, - etag, - type: metadata.type, - immutable: true, - size: bytes.byteLength, - } - routes[route] = createResponseHandler(asset) - - loaded.push({ ...metadata, size: bytes.byteLength }) - totalPreloadedBytes += bytes.byteLength - } else { - // Serve large or filtered files on-demand - routes[route] = () => { - const fileOnDemand = Bun.file(filepath) - return new Response(fileOnDemand, { - headers: { - 'Content-Type': metadata.type, - 'Cache-Control': 'public, max-age=3600', - }, - }) - } - - skipped.push(metadata) - } - } catch (error: unknown) { - if (error instanceof Error && error.name !== 'EISDIR') { - log.error(`Failed to load ${filepath}: ${error.message}`) - } - } - } - - // Show detailed file overview only when verbose mode is enabled - if (VERBOSE && (loaded.length > 0 || skipped.length > 0)) { - const allFiles = [...loaded, ...skipped].sort((a, b) => - a.route.localeCompare(b.route), - ) - - // Calculate max path length for alignment - const maxPathLength = Math.min( - Math.max(...allFiles.map((f) => f.route.length)), - 60, - ) - - // Format file size with KB and actual gzip size - const formatFileSize = (bytes: number, gzBytes?: number) => { - const kb = bytes / 1024 - const sizeStr = kb < 100 ? kb.toFixed(2) : kb.toFixed(1) - - if (gzBytes !== undefined) { - const gzKb = gzBytes / 1024 - const gzStr = gzKb < 100 ? gzKb.toFixed(2) : gzKb.toFixed(1) - return { - size: sizeStr, - gzip: gzStr, - } - } - - // Rough gzip estimation (typically 30-70% compression) if no actual gzip data - const gzipKb = kb * 0.35 - return { - size: sizeStr, - gzip: gzipKb < 100 ? gzipKb.toFixed(2) : gzipKb.toFixed(1), - } - } - - if (loaded.length > 0) { - console.log('\n📁 Preloaded into memory:') - console.log( - 'Path │ Size │ Gzip Size', - ) - loaded - .sort((a, b) => a.route.localeCompare(b.route)) - .forEach((file) => { - const { size, gzip } = formatFileSize(file.size) - const paddedPath = file.route.padEnd(maxPathLength) - const sizeStr = `${size.padStart(7)} kB` - const gzipStr = `${gzip.padStart(7)} kB` - console.log(`${paddedPath} │ ${sizeStr} │ ${gzipStr}`) - }) - } - - if (skipped.length > 0) { - console.log('\n💾 Served on-demand:') - console.log( - 'Path │ Size │ Gzip Size', - ) - skipped - .sort((a, b) => a.route.localeCompare(b.route)) - .forEach((file) => { - const { size, gzip } = formatFileSize(file.size) - const paddedPath = file.route.padEnd(maxPathLength) - const sizeStr = `${size.padStart(7)} kB` - const gzipStr = `${gzip.padStart(7)} kB` - console.log(`${paddedPath} │ ${sizeStr} │ ${gzipStr}`) - }) - } - } - - // Show detailed verbose info if enabled - if (VERBOSE) { - if (loaded.length > 0 || skipped.length > 0) { - const allFiles = [...loaded, ...skipped].sort((a, b) => - a.route.localeCompare(b.route), - ) - console.log('\n📊 Detailed file information:') - console.log( - 'Status │ Path │ MIME Type │ Reason', - ) - allFiles.forEach((file) => { - const isPreloaded = loaded.includes(file) - const status = isPreloaded ? 'MEMORY' : 'ON-DEMAND' - const reason = - !isPreloaded && file.size > MAX_PRELOAD_BYTES - ? 'too large' - : !isPreloaded - ? 'filtered' - : 'preloaded' - const route = - file.route.length > 30 - ? file.route.substring(0, 27) + '...' - : file.route - console.log( - `${status.padEnd(12)} │ ${route.padEnd(30)} │ ${file.type.padEnd(28)} │ ${reason.padEnd(10)}`, - ) - }) - } else { - console.log('\n📊 No files found to display') - } - } - - // Log summary after the file list - console.log() // Empty line for separation - if (loaded.length > 0) { - log.success( - `Preloaded ${String(loaded.length)} files (${(totalPreloadedBytes / 1024 / 1024).toFixed(2)} MB) into memory`, - ) - } else { - log.info('No files preloaded into memory') - } - - if (skipped.length > 0) { - const tooLarge = skipped.filter((f) => f.size > MAX_PRELOAD_BYTES).length - const filtered = skipped.length - tooLarge - log.info( - `${String(skipped.length)} files will be served on-demand (${String(tooLarge)} too large, ${String(filtered)} filtered)`, - ) - } - } catch (error) { - log.error( - `Failed to load static files from ${clientDirectory}: ${String(error)}`, - ) - } - - return { routes, loaded, skipped } -} - -/** - * Initialize the server - */ -async function initializeServer() { - log.header('Starting Production Server') - - // Load TanStack Start server handler - let handler: { fetch: (request: Request) => Response | Promise } - try { - const serverModule = (await import(SERVER_ENTRY_POINT)) as { - default: { fetch: (request: Request) => Response | Promise } - } - handler = serverModule.default - log.success('TanStack Start application handler initialized') - } catch (error) { - log.error(`Failed to load server handler: ${String(error)}`) - process.exit(1) - } - - // Build static routes with intelligent preloading - const { routes } = await initializeStaticRoutes(CLIENT_DIRECTORY) - - // Create Bun server - const server = Bun.serve({ - port: SERVER_PORT, - - routes: { - // Serve static assets (preloaded or on-demand) - ...routes, - - // Fallback to TanStack Start handler for all other routes - '/*': (req: Request) => { - try { - return handler.fetch(req) - } catch (error) { - log.error(`Server handler error: ${String(error)}`) - return new Response('Internal Server Error', { status: 500 }) - } - }, - }, - - // Global error handler - error(error) { - log.error( - `Uncaught server error: ${error instanceof Error ? error.message : String(error)}`, - ) - return new Response('Internal Server Error', { status: 500 }) - }, - }) - - log.success(`Server listening on http://localhost:${String(server.port)}`) -} - -// Initialize the server -initializeServer().catch((error: unknown) => { - log.error(`Failed to start server: ${String(error)}`) - process.exit(1) -}) diff --git a/examples/react/start-bun/src/components/Header.tsx b/examples/react/start-bun/src/components/Header.tsx deleted file mode 100644 index 8a138a0a422..00000000000 --- a/examples/react/start-bun/src/components/Header.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export default function Header() { - return ( -
- -
- ) -} diff --git a/examples/react/start-bun/src/logo.svg b/examples/react/start-bun/src/logo.svg deleted file mode 100644 index fe53fe8d0d2..00000000000 --- a/examples/react/start-bun/src/logo.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - logo - - \ No newline at end of file diff --git a/examples/react/start-bun/src/routeTree.gen.ts b/examples/react/start-bun/src/routeTree.gen.ts deleted file mode 100644 index 18fbc9b60e0..00000000000 --- a/examples/react/start-bun/src/routeTree.gen.ts +++ /dev/null @@ -1,135 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiDemoNamesRouteImport } from './routes/api.demo-names' -import { Route as DemoStartServerFuncsRouteImport } from './routes/demo.start.server-funcs' -import { Route as DemoStartApiRequestRouteImport } from './routes/demo.start.api-request' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiDemoNamesRoute = ApiDemoNamesRouteImport.update({ - id: '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/api/demo-names', - path: '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/api/demo-names', - getParentRoute: () => rootRouteImport, -} as any) -const DemoStartServerFuncsRoute = DemoStartServerFuncsRouteImport.update({ - id: '/demo/start/server-funcs', - path: '/demo/start/server-funcs', - getParentRoute: () => rootRouteImport, -} as any) -const DemoStartApiRequestRoute = DemoStartApiRequestRouteImport.update({ - id: '/demo/start/api-request', - path: '/demo/start/api-request', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '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/api/demo-names': typeof ApiDemoNamesRoute - '/demo/start/api-request': typeof DemoStartApiRequestRoute - '/demo/start/server-funcs': typeof DemoStartServerFuncsRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '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/api/demo-names': typeof ApiDemoNamesRoute - '/demo/start/api-request': typeof DemoStartApiRequestRoute - '/demo/start/server-funcs': typeof DemoStartServerFuncsRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '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/api/demo-names': typeof ApiDemoNamesRoute - '/demo/start/api-request': typeof DemoStartApiRequestRoute - '/demo/start/server-funcs': typeof DemoStartServerFuncsRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '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/api/demo-names' - | '/demo/start/api-request' - | '/demo/start/server-funcs' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '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/api/demo-names' - | '/demo/start/api-request' - | '/demo/start/server-funcs' - id: - | '__root__' - | '/' - | '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/api/demo-names' - | '/demo/start/api-request' - | '/demo/start/server-funcs' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiDemoNamesRoute: typeof ApiDemoNamesRoute - DemoStartApiRequestRoute: typeof DemoStartApiRequestRoute - DemoStartServerFuncsRoute: typeof DemoStartServerFuncsRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '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/api/demo-names': { - id: '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/api/demo-names' - path: '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/api/demo-names' - fullPath: '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/api/demo-names' - preLoaderRoute: typeof ApiDemoNamesRouteImport - parentRoute: typeof rootRouteImport - } - '/demo/start/server-funcs': { - id: '/demo/start/server-funcs' - path: '/demo/start/server-funcs' - fullPath: '/demo/start/server-funcs' - preLoaderRoute: typeof DemoStartServerFuncsRouteImport - parentRoute: typeof rootRouteImport - } - '/demo/start/api-request': { - id: '/demo/start/api-request' - path: '/demo/start/api-request' - fullPath: '/demo/start/api-request' - preLoaderRoute: typeof DemoStartApiRequestRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiDemoNamesRoute: ApiDemoNamesRoute, - DemoStartApiRequestRoute: DemoStartApiRequestRoute, - DemoStartServerFuncsRoute: DemoStartServerFuncsRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' -declare module '@tanstack/react-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/examples/react/start-bun/src/router.tsx b/examples/react/start-bun/src/router.tsx deleted file mode 100644 index ee1edab88c9..00000000000 --- a/examples/react/start-bun/src/router.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createRouter } from '@tanstack/react-router' - -// Import the generated route tree -import { routeTree } from './routeTree.gen' - -// Create a new router instance -export const getRouter = () => { - return createRouter({ - routeTree, - scrollRestoration: true, - defaultPreloadStaleTime: 0, - }) -} diff --git a/examples/react/start-bun/src/routes/__root.tsx b/examples/react/start-bun/src/routes/__root.tsx deleted file mode 100644 index cf53f185c5f..00000000000 --- a/examples/react/start-bun/src/routes/__root.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import { TanStackDevtools } from '@tanstack/react-devtools' -import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' -import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools' - -import Header from '../components/Header' - -import appCss from '../styles.css?url' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - { - title: 'TanStack Start Starter', - }, - ], - links: [ - { - rel: 'stylesheet', - href: appCss, - }, - ], - }), - - shellComponent: RootDocument, -}) - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- {children} - , - }, - ]} - /> - - - - ) -} diff --git a/examples/react/start-bun/src/routes/api.demo-names.ts b/examples/react/start-bun/src/routes/api.demo-names.ts deleted file mode 100644 index ecf045c0182..00000000000 --- a/examples/react/start-bun/src/routes/api.demo-names.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('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/api/demo-names')({ - server: { - handlers: { - GET: () => { - return new Response(JSON.stringify(['Alice', 'Bob', 'Charlie']), { - headers: { - 'Content-Type': 'application/json', - }, - }) - }, - }, - }, -}) diff --git a/examples/react/start-bun/src/routes/demo.start.api-request.tsx b/examples/react/start-bun/src/routes/demo.start.api-request.tsx deleted file mode 100644 index b3fadbaa2d2..00000000000 --- a/examples/react/start-bun/src/routes/demo.start.api-request.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import { useEffect, useState } from 'react' - -import { createFileRoute } from '@tanstack/react-router' - -function getNames() { - return fetch('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/api/demo-names').then((res) => res.json()) -} - -export const Route = createFileRoute('/demo/start/api-request')({ - component: Home, -}) - -function Home() { - const [names, setNames] = useState>([]) - - useEffect(() => { - getNames().then(setNames) - }, []) - - return ( -
-
-

Start API Request Demo - Names List

-
    - {names.map((name) => ( -
  • - {name} -
  • - ))} -
-
-
- ) -} diff --git a/examples/react/start-bun/src/routes/demo.start.server-funcs.tsx b/examples/react/start-bun/src/routes/demo.start.server-funcs.tsx deleted file mode 100644 index e1a132aa1d2..00000000000 --- a/examples/react/start-bun/src/routes/demo.start.server-funcs.tsx +++ /dev/null @@ -1,97 +0,0 @@ -import fs from 'node:fs' -import { useCallback, useState } from 'react' -import { createFileRoute, useRouter } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' - -const filePath = 'todos.json' - -async function readTodos() { - return JSON.parse( - await fs.promises.readFile(filePath, 'utf-8').catch(() => - JSON.stringify( - [ - { id: 1, name: 'Get groceries' }, - { id: 2, name: 'Buy a new phone' }, - ], - null, - 2, - ), - ), - ) -} - -const getTodos = createServerFn({ - method: 'GET', -}).handler(async () => await readTodos()) - -const addTodo = createServerFn({ method: 'POST' }) - .inputValidator((d: string) => d) - .handler(async ({ data }) => { - const todos = await readTodos() - todos.push({ id: todos.length + 1, name: data }) - await fs.promises.writeFile(filePath, JSON.stringify(todos, null, 2)) - return todos - }) - -export const Route = createFileRoute('/demo/start/server-funcs')({ - component: Home, - loader: async () => await getTodos(), -}) - -function Home() { - const router = useRouter() - let todos = Route.useLoaderData() - - const [todo, setTodo] = useState('') - - const submitTodo = useCallback(async () => { - todos = await addTodo({ data: todo }) - setTodo('') - router.invalidate() - }, [addTodo, todo]) - - return ( -
-
-

Start Server Functions - Todo Example

-
    - {todos?.map((t) => ( -
  • - {t.name} -
  • - ))} -
-
- setTodo(e.target.value)} - onKeyDown={(e) => { - if (e.key === 'Enter') { - submitTodo() - } - }} - placeholder="Enter a new todo..." - className="w-full px-4 py-3 rounded-lg border border-white/20 bg-white/10 backdrop-blur-sm text-white placeholder-white/60 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent" - /> - -
-
-
- ) -} diff --git a/examples/react/start-bun/src/routes/index.tsx b/examples/react/start-bun/src/routes/index.tsx deleted file mode 100644 index b285335dfbc..00000000000 --- a/examples/react/start-bun/src/routes/index.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import logo from '../logo.svg' - -export const Route = createFileRoute('/')({ - component: App, -}) - -function App() { - return ( -
- ) -} diff --git a/examples/react/start-bun/src/styles.css b/examples/react/start-bun/src/styles.css deleted file mode 100644 index f59c071ef60..00000000000 --- a/examples/react/start-bun/src/styles.css +++ /dev/null @@ -1,15 +0,0 @@ -@import 'tailwindcss' source('../'); - -body { - @apply m-0; - font-family: - -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', - 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -code { - font-family: - source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; -} diff --git a/examples/react/start-bun/tsconfig.json b/examples/react/start-bun/tsconfig.json deleted file mode 100644 index 2cc3abd5d4d..00000000000 --- a/examples/react/start-bun/tsconfig.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "include": [ - "**/*.ts", - "**/*.tsx", - "eslint.config.js", - "prettier.config.js", - "vite.config.js" - ], - - "compilerOptions": { - "target": "ES2022", - "jsx": "react-jsx", - "module": "ESNext", - "lib": ["ES2022", "DOM", "DOM.Iterable"], - "types": ["vite/client", "bun"], - - /* Bundler mode */ - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "verbatimModuleSyntax": false, - "noEmit": true, - - /* Linting */ - "skipLibCheck": true, - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noFallthroughCasesInSwitch": true, - "noUncheckedSideEffectImports": true, - "baseUrl": ".", - "paths": { - "@/*": ["./src/*"] - } - } -} diff --git a/examples/react/start-bun/vite.config.ts b/examples/react/start-bun/vite.config.ts deleted file mode 100644 index 206769f5023..00000000000 --- a/examples/react/start-bun/vite.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import viteReact from '@vitejs/plugin-react' -import viteTsConfigPaths from 'vite-tsconfig-paths' -import tailwindcss from '@tailwindcss/vite' - -const config = defineConfig({ - plugins: [ - // this is the plugin that enables path aliases - viteTsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tailwindcss(), - tanstackStart(), - viteReact(), - ], -}) - -export default config diff --git a/examples/react/start-clerk-basic/.env b/examples/react/start-clerk-basic/.env deleted file mode 100644 index 5e3b005f2de..00000000000 --- a/examples/react/start-clerk-basic/.env +++ /dev/null @@ -1,2 +0,0 @@ -VITE_CLERK_PUBLISHABLE_KEY=[YOUR_CLERK_PUBLISHABLE_KEY] -CLERK_SECRET_KEY=[YOUR_CLERK_SECRET_KEY] \ No newline at end of file diff --git a/examples/react/start-clerk-basic/.gitignore b/examples/react/start-clerk-basic/.gitignore deleted file mode 100644 index bc14f2cea63..00000000000 --- a/examples/react/start-clerk-basic/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -!.env -.DS_Store -.cache -.vercel -.output -.nitro -/build/ -/api/ -/server/build -/public/build# Sentry Config File -.env.sentry-build-plugin -/test-results/ -/playwright-report/ -/blob-report/ -/playwright/.cache/ -.tanstack diff --git a/examples/react/start-clerk-basic/.prettierignore b/examples/react/start-clerk-basic/.prettierignore deleted file mode 100644 index 2be5eaa6ece..00000000000 --- a/examples/react/start-clerk-basic/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/build -**/public -pnpm-lock.yaml -routeTree.gen.ts \ No newline at end of file diff --git a/examples/react/start-clerk-basic/.vscode/settings.json b/examples/react/start-clerk-basic/.vscode/settings.json deleted file mode 100644 index 00b5278e580..00000000000 --- a/examples/react/start-clerk-basic/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "files.watcherExclude": { - "**/routeTree.gen.ts": true - }, - "search.exclude": { - "**/routeTree.gen.ts": true - }, - "files.readonlyInclude": { - "**/routeTree.gen.ts": true - } -} diff --git a/examples/react/start-clerk-basic/README.md b/examples/react/start-clerk-basic/README.md index 896ce58300f..23b70ea31a2 100644 --- a/examples/react/start-clerk-basic/README.md +++ b/examples/react/start-clerk-basic/README.md @@ -1,46 +1,16 @@ -# TanStack Start - Clerk Authentication Example +# Deprecated: TanStack Start React Example (`start-clerk-basic`) -This site is built with TanStack Router and Clerk Authentication! +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) -- [Clerk Documentation](https://clerk.com/docs) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-clerk-basic start-clerk-basic -``` +- [Authentication Overview](https://tanstack.com/router/latest/docs/framework/react/start/guide/authentication-overview) -## Deployment +Canonical issue reproduction baseline: -It's deployed automagically with Netlify! - -- [Netlify](https://netlify.com/) - -## Getting Started - -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -## Build - -Build for production: - -```sh -pnpm build -``` - -## About This Example - -This example demonstrates: - -- Clerk authentication integration -- Protected routes -- User management -- Authentication UI components +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-clerk-basic/package.json b/examples/react/start-clerk-basic/package.json deleted file mode 100644 index 7cf3866023b..00000000000 --- a/examples/react/start-clerk-basic/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "tanstack-start-example-clerk-basic", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" - }, - "dependencies": { - "@clerk/tanstack-react-start": "^0.27.14", - "@tanstack/react-router": "^1.161.1", - "@tanstack/react-router-devtools": "^1.161.1", - "@tanstack/react-start": "^1.161.1", - "@vitejs/plugin-react": "^4.3.4", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "srvx": "^0.11.2", - "tailwind-merge": "^2.6.0" - }, - "devDependencies": { - "@tailwindcss/vite": "^4.1.18", - "@types/node": "^22.5.4", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "tailwindcss": "^4.1.18", - "typescript": "^5.7.2", - "vite": "^7.3.1", - "vite-tsconfig-paths": "^5.1.4" - } -} diff --git a/examples/react/start-clerk-basic/public/android-chrome-192x192.png b/examples/react/start-clerk-basic/public/android-chrome-192x192.png deleted file mode 100644 index 09c8324f8c6..00000000000 Binary files a/examples/react/start-clerk-basic/public/android-chrome-192x192.png and /dev/null differ diff --git a/examples/react/start-clerk-basic/public/android-chrome-512x512.png b/examples/react/start-clerk-basic/public/android-chrome-512x512.png deleted file mode 100644 index 11d626ea3d0..00000000000 Binary files a/examples/react/start-clerk-basic/public/android-chrome-512x512.png and /dev/null differ diff --git a/examples/react/start-clerk-basic/public/apple-touch-icon.png b/examples/react/start-clerk-basic/public/apple-touch-icon.png deleted file mode 100644 index 5a9423cc02c..00000000000 Binary files a/examples/react/start-clerk-basic/public/apple-touch-icon.png and /dev/null differ diff --git a/examples/react/start-clerk-basic/public/favicon-16x16.png b/examples/react/start-clerk-basic/public/favicon-16x16.png deleted file mode 100644 index e3389b00443..00000000000 Binary files a/examples/react/start-clerk-basic/public/favicon-16x16.png and /dev/null differ diff --git a/examples/react/start-clerk-basic/public/favicon-32x32.png b/examples/react/start-clerk-basic/public/favicon-32x32.png deleted file mode 100644 index 900c77d444c..00000000000 Binary files a/examples/react/start-clerk-basic/public/favicon-32x32.png and /dev/null differ diff --git a/examples/react/start-clerk-basic/public/favicon.ico b/examples/react/start-clerk-basic/public/favicon.ico deleted file mode 100644 index 1a1751676f7..00000000000 Binary files a/examples/react/start-clerk-basic/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-clerk-basic/public/favicon.png b/examples/react/start-clerk-basic/public/favicon.png deleted file mode 100644 index 1e77bc06091..00000000000 Binary files a/examples/react/start-clerk-basic/public/favicon.png and /dev/null differ diff --git a/examples/react/start-clerk-basic/public/site.webmanifest b/examples/react/start-clerk-basic/public/site.webmanifest deleted file mode 100644 index fa99de77db6..00000000000 --- a/examples/react/start-clerk-basic/public/site.webmanifest +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "", - "short_name": "", - "icons": [ - { - "src": "/android-chrome-192x192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "/android-chrome-512x512.png", - "sizes": "512x512", - "type": "image/png" - } - ], - "theme_color": "#ffffff", - "background_color": "#ffffff", - "display": "standalone" -} diff --git a/examples/react/start-clerk-basic/src/components/DefaultCatchBoundary.tsx b/examples/react/start-clerk-basic/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index ef2daa1ea1d..00000000000 --- a/examples/react/start-clerk-basic/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { - ErrorComponent, - Link, - rootRouteId, - useMatch, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error(error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/examples/react/start-clerk-basic/src/components/NotFound.tsx b/examples/react/start-clerk-basic/src/components/NotFound.tsx deleted file mode 100644 index fd4e75befe3..00000000000 --- a/examples/react/start-clerk-basic/src/components/NotFound.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: any }) { - return ( -
-
- {children ||

The page you are looking for does not exist.

} -
-

- - - Start Over - -

-
- ) -} diff --git a/examples/react/start-clerk-basic/src/routeTree.gen.ts b/examples/react/start-clerk-basic/src/routeTree.gen.ts deleted file mode 100644 index baaabbc2c03..00000000000 --- a/examples/react/start-clerk-basic/src/routeTree.gen.ts +++ /dev/null @@ -1,181 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as AuthedRouteImport } from './routes/_authed' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' -import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' -import { Route as AuthedProfileSplatRouteImport } from './routes/_authed/profile.$' -import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' - -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthedPostsRoute = AuthedPostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => AuthedRoute, -} as any) -const AuthedPostsIndexRoute = AuthedPostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => AuthedPostsRoute, -} as any) -const AuthedProfileSplatRoute = AuthedProfileSplatRouteImport.update({ - id: '/profile/$', - path: '/profile/$', - getParentRoute: () => AuthedRoute, -} as any) -const AuthedPostsPostIdRoute = AuthedPostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => AuthedPostsRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/posts': typeof AuthedPostsRouteWithChildren - '/posts/$postId': typeof AuthedPostsPostIdRoute - '/profile/$': typeof AuthedProfileSplatRoute - '/posts/': typeof AuthedPostsIndexRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/posts/$postId': typeof AuthedPostsPostIdRoute - '/profile/$': typeof AuthedProfileSplatRoute - '/posts': typeof AuthedPostsIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/_authed': typeof AuthedRouteWithChildren - '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/_authed/posts': typeof AuthedPostsRouteWithChildren - '/_authed/posts/$postId': typeof AuthedPostsPostIdRoute - '/_authed/profile/$': typeof AuthedProfileSplatRoute - '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/_authed/posts/': typeof AuthedPostsIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/posts' | '/posts/$postId' | '/profile/$' | '/posts/' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/posts/$postId' | '/profile/$' | '/posts' - id: - | '__root__' - | '/' - | '/_authed' - | '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/_authed/posts' - | '/_authed/posts/$postId' - | '/_authed/profile/$' - | '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/_authed/posts/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AuthedRoute: typeof AuthedRouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/_authed': { - id: '/_authed' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '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/_authed/posts': { - id: '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/_authed/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof AuthedPostsRouteImport - parentRoute: typeof AuthedRoute - } - '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/_authed/posts/': { - id: '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/_authed/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof AuthedPostsIndexRouteImport - parentRoute: typeof AuthedPostsRoute - } - '/_authed/profile/$': { - id: '/_authed/profile/$' - path: '/profile/$' - fullPath: '/profile/$' - preLoaderRoute: typeof AuthedProfileSplatRouteImport - parentRoute: typeof AuthedRoute - } - '/_authed/posts/$postId': { - id: '/_authed/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof AuthedPostsPostIdRouteImport - parentRoute: typeof AuthedPostsRoute - } - } -} - -interface AuthedPostsRouteChildren { - AuthedPostsPostIdRoute: typeof AuthedPostsPostIdRoute - AuthedPostsIndexRoute: typeof AuthedPostsIndexRoute -} - -const AuthedPostsRouteChildren: AuthedPostsRouteChildren = { - AuthedPostsPostIdRoute: AuthedPostsPostIdRoute, - AuthedPostsIndexRoute: AuthedPostsIndexRoute, -} - -const AuthedPostsRouteWithChildren = AuthedPostsRoute._addFileChildren( - AuthedPostsRouteChildren, -) - -interface AuthedRouteChildren { - AuthedPostsRoute: typeof AuthedPostsRouteWithChildren - AuthedProfileSplatRoute: typeof AuthedProfileSplatRoute -} - -const AuthedRouteChildren: AuthedRouteChildren = { - AuthedPostsRoute: AuthedPostsRouteWithChildren, - AuthedProfileSplatRoute: AuthedProfileSplatRoute, -} - -const AuthedRouteWithChildren = - AuthedRoute._addFileChildren(AuthedRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AuthedRoute: AuthedRouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { startInstance } from './start.ts' -declare module '@tanstack/react-start' { - interface Register { - ssr: true - router: Awaited> - config: Awaited> - } -} diff --git a/examples/react/start-clerk-basic/src/router.tsx b/examples/react/start-clerk-basic/src/router.tsx deleted file mode 100644 index 1a1d8822d20..00000000000 --- a/examples/react/start-clerk-basic/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - const router = createRouter({ - routeTree, - defaultPreload: 'intent', - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - scrollRestoration: true, - }) - - return router -} diff --git a/examples/react/start-clerk-basic/src/routes/__root.tsx b/examples/react/start-clerk-basic/src/routes/__root.tsx deleted file mode 100644 index 8cf05a38350..00000000000 --- a/examples/react/start-clerk-basic/src/routes/__root.tsx +++ /dev/null @@ -1,135 +0,0 @@ -/// -import { - ClerkProvider, - SignInButton, - SignedIn, - SignedOut, - UserButton, -} from '@clerk/tanstack-react-start' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import { createServerFn } from '@tanstack/react-start' -import { auth } from '@clerk/tanstack-react-start/server' -import * as React from 'react' -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' -import { NotFound } from '~/components/NotFound.js' -import appCss from '~/styles/app.css?url' - -const fetchClerkAuth = createServerFn({ method: 'GET' }).handler(async () => { - const { userId } = await auth() - - return { - userId, - } -}) - -export const Route = createRootRoute({ - beforeLoad: async () => { - const { userId } = await fetchClerkAuth() - - return { - userId, - } - }, - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - ], - links: [ - { rel: 'stylesheet', href: appCss }, - { - rel: 'apple-touch-icon', - sizes: '180x180', - href: '/apple-touch-icon.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '32x32', - href: '/favicon-32x32.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '16x16', - href: '/favicon-16x16.png', - }, - { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, - { rel: 'icon', href: '/favicon.ico' }, - ], - }), - errorComponent: (props) => { - return ( - - - - ) - }, - notFoundComponent: () => , - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - ) -} - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- - Home - {' '} - - Posts - -
- - - - - - -
-
-
- {children} - - - - - ) -} diff --git a/examples/react/start-clerk-basic/src/routes/_authed.tsx b/examples/react/start-clerk-basic/src/routes/_authed.tsx deleted file mode 100644 index 1a97917c124..00000000000 --- a/examples/react/start-clerk-basic/src/routes/_authed.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { SignIn } from '@clerk/tanstack-react-start' -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_authed')({ - beforeLoad: ({ context }) => { - if (!context.userId) { - throw new Error('Not authenticated') - } - }, - errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { - return ( -
- -
- ) - } - - throw error - }, -}) diff --git a/examples/react/start-clerk-basic/src/routes/_authed/posts.$postId.tsx b/examples/react/start-clerk-basic/src/routes/_authed/posts.$postId.tsx deleted file mode 100644 index 039271bb896..00000000000 --- a/examples/react/start-clerk-basic/src/routes/_authed/posts.$postId.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { ErrorComponent, createFileRoute } from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' -import { NotFound } from '~/components/NotFound.js' -import { fetchPost } from '~/utils/posts.js' - -export const Route = createFileRoute('/_authed/posts/$postId')({ - loader: ({ params: { postId } }) => fetchPost({ data: postId }), - errorComponent: PostErrorComponent, - component: PostComponent, - notFoundComponent: () => { - return Post not found - }, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return -} - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.title}

-
{post.body}
-
- ) -} diff --git a/examples/react/start-clerk-basic/src/routes/_authed/posts.index.tsx b/examples/react/start-clerk-basic/src/routes/_authed/posts.index.tsx deleted file mode 100644 index de01fe5ddef..00000000000 --- a/examples/react/start-clerk-basic/src/routes/_authed/posts.index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('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/_authed/posts/')({ - component: PostsIndexComponent, -}) - -function PostsIndexComponent() { - return
Select a post.
-} diff --git a/examples/react/start-clerk-basic/src/routes/_authed/posts.tsx b/examples/react/start-clerk-basic/src/routes/_authed/posts.tsx deleted file mode 100644 index 86c8ef41389..00000000000 --- a/examples/react/start-clerk-basic/src/routes/_authed/posts.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '~/utils/posts.js' - -export const Route = createFileRoute('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/_authed/posts')({ - loader: () => fetchPosts(), - component: PostsComponent, -}) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( - (post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - }, - )} -
-
- -
- ) -} diff --git a/examples/react/start-clerk-basic/src/routes/_authed/profile.$.tsx b/examples/react/start-clerk-basic/src/routes/_authed/profile.$.tsx deleted file mode 100644 index 208a38e2300..00000000000 --- a/examples/react/start-clerk-basic/src/routes/_authed/profile.$.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '~/utils/posts.js' - -export const Route = createFileRoute('/_authed/profile/$')({ - loader: () => fetchPosts(), - component: PostsComponent, -}) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( - (post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - }, - )} -
-
- -
- ) -} diff --git a/examples/react/start-clerk-basic/src/routes/index.tsx b/examples/react/start-clerk-basic/src/routes/index.tsx deleted file mode 100644 index 00ce18725b4..00000000000 --- a/examples/react/start-clerk-basic/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Hello Clerk!

-
- ) -} diff --git a/examples/react/start-clerk-basic/src/start.ts b/examples/react/start-clerk-basic/src/start.ts deleted file mode 100644 index 7447718f41c..00000000000 --- a/examples/react/start-clerk-basic/src/start.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { clerkMiddleware } from '@clerk/tanstack-react-start/server' -import { createStart } from '@tanstack/react-start' - -export const startInstance = createStart(() => { - return { - requestMiddleware: [clerkMiddleware()], - } -}) diff --git a/examples/react/start-clerk-basic/src/styles/app.css b/examples/react/start-clerk-basic/src/styles/app.css deleted file mode 100644 index 37c1f5a6e2d..00000000000 --- a/examples/react/start-clerk-basic/src/styles/app.css +++ /dev/null @@ -1,30 +0,0 @@ -@import 'tailwindcss' source('../'); - -@layer base { - *, - ::after, - ::before, - ::backdrop, - ::file-selector-button { - border-color: var(--color-gray-200, currentcolor); - } -} - -@layer base { - html { - color-scheme: light dark; - } - - * { - @apply border-gray-200 dark:border-gray-800; - } - - html, - body { - @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; - } - - .using-mouse * { - outline: none !important; - } -} diff --git a/examples/react/start-clerk-basic/src/utils/posts.ts b/examples/react/start-clerk-basic/src/utils/posts.ts deleted file mode 100644 index fbcc43c34b0..00000000000 --- a/examples/react/start-clerk-basic/src/utils/posts.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { notFound } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import axios from 'redaxios' - -export type PostType = { - id: string - title: string - body: string -} - -export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((postId: string) => postId) - .handler(async ({ data }) => { - console.info(`Fetching post with id ${data}...`) - const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${data}`) - .then((r) => r.data) - .catch((err) => { - console.error(err) - if (err.status === 404) { - throw notFound() - } - throw err - }) - - return post - }) - -export const fetchPosts = createServerFn({ method: 'GET' }).handler( - async () => { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 1000)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) - }, -) diff --git a/examples/react/start-clerk-basic/src/utils/seo.ts b/examples/react/start-clerk-basic/src/utils/seo.ts deleted file mode 100644 index d18ad84b74e..00000000000 --- a/examples/react/start-clerk-basic/src/utils/seo.ts +++ /dev/null @@ -1,33 +0,0 @@ -export const seo = ({ - title, - description, - keywords, - image, -}: { - title: string - description?: string - image?: string - keywords?: string -}) => { - const tags = [ - { title }, - { name: 'description', content: description }, - { name: 'keywords', content: keywords }, - { name: 'twitter:title', content: title }, - { name: 'twitter:description', content: description }, - { name: 'twitter:creator', content: '@tannerlinsley' }, - { name: 'twitter:site', content: '@tannerlinsley' }, - { name: 'og:type', content: 'website' }, - { name: 'og:title', content: title }, - { name: 'og:description', content: description }, - ...(image - ? [ - { name: 'twitter:image', content: image }, - { name: 'twitter:card', content: 'summary_large_image' }, - { name: 'og:image', content: image }, - ] - : []), - ] - - return tags -} diff --git a/examples/react/start-clerk-basic/tsconfig.json b/examples/react/start-clerk-basic/tsconfig.json deleted file mode 100644 index 3a9fb7cd716..00000000000 --- a/examples/react/start-clerk-basic/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "baseUrl": ".", - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/examples/react/start-clerk-basic/vite.config.ts b/examples/react/start-clerk-basic/vite.config.ts deleted file mode 100644 index 21ac5d775ca..00000000000 --- a/examples/react/start-clerk-basic/vite.config.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' -import viteReact from '@vitejs/plugin-react' -import tailwindcss from '@tailwindcss/vite' - -export default defineConfig({ - server: { - port: 3000, - }, - plugins: [ - tailwindcss(), - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], - // See https://github.com/TanStack/router/issues/5738 - resolve: { - alias: [ - { find: 'use-sync-external-store/shim/index.js', replacement: 'react' }, - ], - }, -}) diff --git a/examples/react/start-convex-trellaux/.env.local.example b/examples/react/start-convex-trellaux/.env.local.example deleted file mode 100644 index 315dd107e0e..00000000000 --- a/examples/react/start-convex-trellaux/.env.local.example +++ /dev/null @@ -1,3 +0,0 @@ -# This is a shared default backend you can't modify the code for. -# In order to create your own backend, run `npx convex dev`. -VITE_CONVEX_URL=https://laudable-anaconda-558.convex.cloud diff --git a/examples/react/start-convex-trellaux/.gitignore b/examples/react/start-convex-trellaux/.gitignore deleted file mode 100644 index ba7dbddfbe0..00000000000 --- a/examples/react/start-convex-trellaux/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -.DS_Store -.cache -.env -.vercel -.output -/build/ -/api/ -/server/build -/public/build# Sentry Config File -.env.sentry-build-plugin - -.env.local diff --git a/examples/react/start-convex-trellaux/.prettierignore b/examples/react/start-convex-trellaux/.prettierignore deleted file mode 100644 index 2be5eaa6ece..00000000000 --- a/examples/react/start-convex-trellaux/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/build -**/public -pnpm-lock.yaml -routeTree.gen.ts \ No newline at end of file diff --git a/examples/react/start-convex-trellaux/.stackblitzrc b/examples/react/start-convex-trellaux/.stackblitzrc deleted file mode 100644 index e616ee3a78c..00000000000 --- a/examples/react/start-convex-trellaux/.stackblitzrc +++ /dev/null @@ -1,3 +0,0 @@ -{ - "startCommand": "cp .env.local.example .env.local && npx vite dev" -} diff --git a/examples/react/start-convex-trellaux/.vscode/settings.json b/examples/react/start-convex-trellaux/.vscode/settings.json deleted file mode 100644 index 00b5278e580..00000000000 --- a/examples/react/start-convex-trellaux/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "files.watcherExclude": { - "**/routeTree.gen.ts": true - }, - "search.exclude": { - "**/routeTree.gen.ts": true - }, - "files.readonlyInclude": { - "**/routeTree.gen.ts": true - } -} diff --git a/examples/react/start-convex-trellaux/README.md b/examples/react/start-convex-trellaux/README.md index 1eeee3d50a1..8c249370a3a 100644 --- a/examples/react/start-convex-trellaux/README.md +++ b/examples/react/start-convex-trellaux/README.md @@ -1,52 +1,12 @@ -# Trello-like example using Convex DB +# Deprecated: TanStack Start React Example (`start-convex-trellaux`) -This is a TanStack Start demo using Convex as the database. -It is similar to the [start-trellaux](https://github.com/TanStack/router/tree/main/examples/react/start-trellaux) example but uses a cloud Convex deployment instead of an in-memory database. +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) -- [Convex Documentation](https://docs.convex.dev) +For new projects and templates, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +Canonical issue reproduction baseline: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-convex-trellaux start-convex-trellaux -``` - -## Convex - -Convex is an open-source, reactive backend made by [convex.dev](https://convex.dev/?utm_source=tanstack), a sponsor of TanStack Start. - -This example uses Convex with TanStack Query and TanStack Start to provide: - -- Typesafe TanStack Query options factories like `convexQuery` for use with `useQuery`, `useSuspenseQuery` etc. -- Live-updating queries: updates come in over a WebSocket instead of requiring polling -- Automatic query invalidation: when a mutation succeeds all queries it affects update automatically -- Selective optimistic update rollback: when a mutation succeeds only its update will be rolled back, with other optimistic updates reapplied -- Consistent snapshot reads of database state: /messages will never return a foreign key for a /user that doesn't exist until the next fetch - -## Getting Started - -To run this example: - -```sh -pnpm install -pnpm dev -``` - -## Build - -Build for production: - -```sh -pnpm build -``` - -## About This Example - -This example demonstrates: - -- Convex database integration -- Real-time updates -- Complex UI state management +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-convex-trellaux/convex/README.md b/examples/react/start-convex-trellaux/convex/README.md deleted file mode 100644 index 896489de6ad..00000000000 --- a/examples/react/start-convex-trellaux/convex/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# Welcome to your Convex functions directory! - -Write your Convex functions here. -See https://docs.convex.dev/functions for more. - -A query function that takes two arguments looks like: - -```ts -// functions.js -import { query } from './_generated/server' -import { v } from 'convex/values' - -export const myQueryFunction = query({ - // Validators for arguments. - args: { - first: v.number(), - second: v.string(), - }, - - // Function implementation. - handler: async (ctx, args) => { - // Read the database as many times as you need here. - // See https://docs.convex.dev/database/reading-data. - const documents = await ctx.db.query('tablename').collect() - - // Arguments passed from the client are properties of the args object. - console.log(args.first, args.second) - - // Write arbitrary JavaScript here: filter, aggregate, build derived data, - // remove non-public properties, or create new objects. - return documents - }, -}) -``` - -Using this query function in a React component looks like: - -```ts -const data = useQuery(api.functions.myQueryFunction, { - first: 10, - second: 'hello', -}) -``` - -A mutation function looks like: - -```ts -// functions.js -import { mutation } from './_generated/server' -import { v } from 'convex/values' - -export const myMutationFunction = mutation({ - // Validators for arguments. - args: { - first: v.string(), - second: v.string(), - }, - - // Function implementation. - handler: async (ctx, args) => { - // Insert or modify documents in the database here. - // Mutations can also read from the database like queries. - // See https://docs.convex.dev/database/writing-data. - const message = { body: args.first, author: args.second } - const id = await ctx.db.insert('messages', message) - - // Optionally, return a value from your mutation. - return await ctx.db.get(id) - }, -}) -``` - -Using this mutation function in a React component looks like: - -```ts -const mutation = useMutation(api.functions.myMutationFunction) -function handleButtonPress() { - // fire and forget, the most common way to use mutations - mutation({ first: 'Hello!', second: 'me' }) - // OR - // use the result once the mutation has completed - mutation({ first: 'Hello!', second: 'me' }).then((result) => - console.log(result), - ) -} -``` - -Use the Convex CLI to push your functions to a deployment. See everything -the Convex CLI can do by running `npx convex -h` in your project root -directory. To learn more, launch the docs with `npx convex docs`. diff --git a/examples/react/start-convex-trellaux/convex/_generated/api.d.ts b/examples/react/start-convex-trellaux/convex/_generated/api.d.ts deleted file mode 100644 index a65ecbcce43..00000000000 --- a/examples/react/start-convex-trellaux/convex/_generated/api.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -/* eslint-disable */ -/** - * Generated `api` utility. - * - * THIS CODE IS AUTOMATICALLY GENERATED. - * - * To regenerate, run `npx convex dev`. - * @module - */ - -import type { - ApiFromModules, - FilterApi, - FunctionReference, -} from 'convex/server' -import type * as board from '../board.js' -import type * as crons from '../crons.js' - -/** - * A utility for referencing Convex functions in your app's API. - * - * Usage: - * ```js - * const myFunctionReference = api.myModule.myFunction; - * ``` - */ -declare const fullApi: ApiFromModules<{ - board: typeof board - crons: typeof crons -}> -export declare const api: FilterApi< - typeof fullApi, - FunctionReference -> -export declare const internal: FilterApi< - typeof fullApi, - FunctionReference -> diff --git a/examples/react/start-convex-trellaux/convex/_generated/api.js b/examples/react/start-convex-trellaux/convex/_generated/api.js deleted file mode 100644 index 2b62e6b82fc..00000000000 --- a/examples/react/start-convex-trellaux/convex/_generated/api.js +++ /dev/null @@ -1,22 +0,0 @@ -/* eslint-disable */ -/** - * Generated `api` utility. - * - * THIS CODE IS AUTOMATICALLY GENERATED. - * - * To regenerate, run `npx convex dev`. - * @module - */ - -import { anyApi } from 'convex/server' - -/** - * A utility for referencing Convex functions in your app's API. - * - * Usage: - * ```js - * const myFunctionReference = api.myModule.myFunction; - * ``` - */ -export const api = anyApi -export const internal = anyApi diff --git a/examples/react/start-convex-trellaux/convex/_generated/dataModel.d.ts b/examples/react/start-convex-trellaux/convex/_generated/dataModel.d.ts deleted file mode 100644 index 5b936a43a01..00000000000 --- a/examples/react/start-convex-trellaux/convex/_generated/dataModel.d.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* eslint-disable */ -/** - * Generated data model types. - * - * THIS CODE IS AUTOMATICALLY GENERATED. - * - * To regenerate, run `npx convex dev`. - * @module - */ - -import type { - DataModelFromSchemaDefinition, - DocumentByName, - TableNamesInDataModel, - SystemTableNames, -} from 'convex/server' -import type { GenericId } from 'convex/values' -import schema from '../schema.js' - -/** - * The names of all of your Convex tables. - */ -export type TableNames = TableNamesInDataModel - -/** - * The type of a document stored in Convex. - * - * @typeParam TableName - A string literal type of the table name (like "users"). - */ -export type Doc = DocumentByName< - DataModel, - TableName -> - -/** - * An identifier for a document in Convex. - * - * Convex documents are uniquely identified by their `Id`, which is accessible - * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids). - * - * Documents can be loaded using `db.get(id)` in query and mutation functions. - * - * IDs are just strings at runtime, but this type can be used to distinguish them from other - * strings when type checking. - * - * @typeParam TableName - A string literal type of the table name (like "users"). - */ -export type Id = - GenericId - -/** - * A type describing your Convex data model. - * - * This type includes information about what tables you have, the type of - * documents stored in those tables, and the indexes defined on them. - * - * This type is used to parameterize methods like `queryGeneric` and - * `mutationGeneric` to make them type-safe. - */ -export type DataModel = DataModelFromSchemaDefinition diff --git a/examples/react/start-convex-trellaux/convex/_generated/server.d.ts b/examples/react/start-convex-trellaux/convex/_generated/server.d.ts deleted file mode 100644 index 869a677bc4b..00000000000 --- a/examples/react/start-convex-trellaux/convex/_generated/server.d.ts +++ /dev/null @@ -1,142 +0,0 @@ -/* eslint-disable */ -/** - * Generated utilities for implementing server-side Convex query and mutation functions. - * - * THIS CODE IS AUTOMATICALLY GENERATED. - * - * To regenerate, run `npx convex dev`. - * @module - */ - -import { - ActionBuilder, - HttpActionBuilder, - MutationBuilder, - QueryBuilder, - GenericActionCtx, - GenericMutationCtx, - GenericQueryCtx, - GenericDatabaseReader, - GenericDatabaseWriter, -} from 'convex/server' -import type { DataModel } from './dataModel.js' - -/** - * Define a query in this Convex app's public API. - * - * This function will be allowed to read your Convex database and will be accessible from the client. - * - * @param func - The query function. It receives a {@link QueryCtx} as its first argument. - * @returns The wrapped query. Include this as an `export` to name it and make it accessible. - */ -export declare const query: QueryBuilder - -/** - * Define a query that is only accessible from other Convex functions (but not from the client). - * - * This function will be allowed to read from your Convex database. It will not be accessible from the client. - * - * @param func - The query function. It receives a {@link QueryCtx} as its first argument. - * @returns The wrapped query. Include this as an `export` to name it and make it accessible. - */ -export declare const internalQuery: QueryBuilder - -/** - * Define a mutation in this Convex app's public API. - * - * This function will be allowed to modify your Convex database and will be accessible from the client. - * - * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. - * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. - */ -export declare const mutation: MutationBuilder - -/** - * Define a mutation that is only accessible from other Convex functions (but not from the client). - * - * This function will be allowed to modify your Convex database. It will not be accessible from the client. - * - * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. - * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. - */ -export declare const internalMutation: MutationBuilder - -/** - * Define an action in this Convex app's public API. - * - * An action is a function which can execute any JavaScript code, including non-deterministic - * code and code with side-effects, like calling third-party services. - * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive. - * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}. - * - * @param func - The action. It receives an {@link ActionCtx} as its first argument. - * @returns The wrapped action. Include this as an `export` to name it and make it accessible. - */ -export declare const action: ActionBuilder - -/** - * Define an action that is only accessible from other Convex functions (but not from the client). - * - * @param func - The function. It receives an {@link ActionCtx} as its first argument. - * @returns The wrapped function. Include this as an `export` to name it and make it accessible. - */ -export declare const internalAction: ActionBuilder - -/** - * Define an HTTP action. - * - * This function will be used to respond to HTTP requests received by a Convex - * deployment if the requests matches the path and method where this action - * is routed. Be sure to route your action in `convex/http.js`. - * - * @param func - The function. It receives an {@link ActionCtx} as its first argument. - * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up. - */ -export declare const httpAction: HttpActionBuilder - -/** - * A set of services for use within Convex query functions. - * - * The query context is passed as the first argument to any Convex query - * function run on the server. - * - * This differs from the {@link MutationCtx} because all of the services are - * read-only. - */ -export type QueryCtx = GenericQueryCtx - -/** - * A set of services for use within Convex mutation functions. - * - * The mutation context is passed as the first argument to any Convex mutation - * function run on the server. - */ -export type MutationCtx = GenericMutationCtx - -/** - * A set of services for use within Convex action functions. - * - * The action context is passed as the first argument to any Convex action - * function run on the server. - */ -export type ActionCtx = GenericActionCtx - -/** - * An interface to read from the database within Convex query functions. - * - * The two entry points are {@link DatabaseReader.get}, which fetches a single - * document by its {@link Id}, or {@link DatabaseReader.query}, which starts - * building a query. - */ -export type DatabaseReader = GenericDatabaseReader - -/** - * An interface to read from and write to the database within Convex mutation - * functions. - * - * Convex guarantees that all writes within a single mutation are - * executed atomically, so you never have to worry about partial writes leaving - * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control) - * for the guarantees Convex provides your functions. - */ -export type DatabaseWriter = GenericDatabaseWriter diff --git a/examples/react/start-convex-trellaux/convex/_generated/server.js b/examples/react/start-convex-trellaux/convex/_generated/server.js deleted file mode 100644 index d16f9527d34..00000000000 --- a/examples/react/start-convex-trellaux/convex/_generated/server.js +++ /dev/null @@ -1,89 +0,0 @@ -/* eslint-disable */ -/** - * Generated utilities for implementing server-side Convex query and mutation functions. - * - * THIS CODE IS AUTOMATICALLY GENERATED. - * - * To regenerate, run `npx convex dev`. - * @module - */ - -import { - actionGeneric, - httpActionGeneric, - queryGeneric, - mutationGeneric, - internalActionGeneric, - internalMutationGeneric, - internalQueryGeneric, -} from 'convex/server' - -/** - * Define a query in this Convex app's public API. - * - * This function will be allowed to read your Convex database and will be accessible from the client. - * - * @param func - The query function. It receives a {@link QueryCtx} as its first argument. - * @returns The wrapped query. Include this as an `export` to name it and make it accessible. - */ -export const query = queryGeneric - -/** - * Define a query that is only accessible from other Convex functions (but not from the client). - * - * This function will be allowed to read from your Convex database. It will not be accessible from the client. - * - * @param func - The query function. It receives a {@link QueryCtx} as its first argument. - * @returns The wrapped query. Include this as an `export` to name it and make it accessible. - */ -export const internalQuery = internalQueryGeneric - -/** - * Define a mutation in this Convex app's public API. - * - * This function will be allowed to modify your Convex database and will be accessible from the client. - * - * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. - * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. - */ -export const mutation = mutationGeneric - -/** - * Define a mutation that is only accessible from other Convex functions (but not from the client). - * - * This function will be allowed to modify your Convex database. It will not be accessible from the client. - * - * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. - * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. - */ -export const internalMutation = internalMutationGeneric - -/** - * Define an action in this Convex app's public API. - * - * An action is a function which can execute any JavaScript code, including non-deterministic - * code and code with side-effects, like calling third-party services. - * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive. - * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}. - * - * @param func - The action. It receives an {@link ActionCtx} as its first argument. - * @returns The wrapped action. Include this as an `export` to name it and make it accessible. - */ -export const action = actionGeneric - -/** - * Define an action that is only accessible from other Convex functions (but not from the client). - * - * @param func - The function. It receives an {@link ActionCtx} as its first argument. - * @returns The wrapped function. Include this as an `export` to name it and make it accessible. - */ -export const internalAction = internalActionGeneric - -/** - * Define a Convex HTTP action. - * - * @param func - The function. It receives an {@link ActionCtx} as its first argument, and a `Request` object - * as its second. - * @returns The wrapped endpoint function. Route a URL path to this function in `convex/http.js`. - */ -export const httpAction = httpActionGeneric diff --git a/examples/react/start-convex-trellaux/convex/board.ts b/examples/react/start-convex-trellaux/convex/board.ts deleted file mode 100644 index bae241a7734..00000000000 --- a/examples/react/start-convex-trellaux/convex/board.ts +++ /dev/null @@ -1,196 +0,0 @@ -import invariant from 'tiny-invariant' -import { v } from 'convex/values' -import { - type QueryCtx, - internalMutation, - mutation, - query, -} from './_generated/server' -import schema, { - deleteColumnSchema, - deleteItemSchema, - newColumnsSchema, - updateBoardSchema, - updateColumnSchema, -} from './schema' -import type { Doc, Id } from './_generated/dataModel' - -export const seed = internalMutation(async (ctx) => { - const allBoards = await ctx.db.query('boards').collect() - if (allBoards.length > 0) { - return - } - await ctx.db.insert('boards', { - id: '1', - name: 'First board', - color: '#e0e0e0', - }) -}) - -// Clear all boards (do this on a regular cadence for public examples) -export const clear = internalMutation(async (ctx) => { - const allBoards = await ctx.db.query('boards').collect() - for (const board of allBoards) { - await ctx.db.delete(board._id) - } - await ctx.db.insert('boards', { - id: '1', - name: 'First board', - color: '#e0e0e0', - }) -}) - -function withoutSystemFields }>( - doc: T, -) { - const { _id, _creationTime, ...rest } = doc - return rest -} - -async function getFullBoard(ctx: QueryCtx, id: string) { - const board = withoutSystemFields(await ensureBoardExists(ctx, id)) - - const [columns, items] = await Promise.all([ - ctx.db - .query('columns') - .withIndex('board', (q) => q.eq('boardId', board.id)) - .collect(), - ctx.db - .query('items') - .withIndex('board', (q) => q.eq('boardId', board.id)) - .collect(), - ]) - - return { - ...board, - columns: columns.map(withoutSystemFields), - items: items.map(withoutSystemFields), - } -} - -export const getBoards = query(async (ctx) => { - const boards = await ctx.db.query('boards').collect() - return await Promise.all(boards.map((b) => getFullBoard(ctx, b.id))) -}) - -export const getBoard = query({ - args: { id: v.string() }, - handler: async (ctx, { id }) => { - return await getFullBoard(ctx, id) - }, -}) - -async function ensureBoardExists( - ctx: QueryCtx, - boardId: string, -): Promise> { - const board = await ctx.db - .query('boards') - .withIndex('id', (q) => q.eq('id', boardId)) - .unique() - - invariant(board, `missing board ${boardId}`) - return board -} -async function ensureColumnExists( - ctx: QueryCtx, - columnId: string, -): Promise> { - const column = await ctx.db - .query('columns') - .withIndex('id', (q) => q.eq('id', columnId)) - .unique() - - invariant(column, `missing column: ${columnId}`) - return column -} -async function ensureItemExists( - ctx: QueryCtx, - itemId: string, -): Promise> { - const item = await ctx.db - .query('items') - .withIndex('id', (q) => q.eq('id', itemId)) - .unique() - - invariant(item, `missing item: ${itemId}`) - return item -} - -export const createColumn = mutation({ - args: newColumnsSchema, - handler: async (ctx, { boardId, name }) => { - ensureBoardExists(ctx, boardId) - - const existingColumns = await ctx.db - .query('columns') - .withIndex('board', (q) => q.eq('boardId', boardId)) - .collect() - - ctx.db.insert('columns', { - boardId, - name, - order: existingColumns.length + 1, - id: crypto.randomUUID(), - }) - }, -}) - -export const createItem = mutation({ - args: schema.tables.items.validator, - handler: async (ctx, item) => { - await ensureBoardExists(ctx, item.boardId) - await ctx.db.insert('items', item) - }, -}) - -export const deleteItem = mutation({ - args: deleteItemSchema, - handler: async (ctx, { id, boardId }) => { - await ensureBoardExists(ctx, boardId) - const item = await ensureItemExists(ctx, id) - await ctx.db.delete(item._id) - }, -}) - -export const updateItem = mutation({ - args: schema.tables.items.validator, - handler: async (ctx, newItem) => { - const { id, boardId } = newItem - await ensureBoardExists(ctx, boardId) - const item = await ensureItemExists(ctx, id) - await ctx.db.patch(item._id, newItem) - }, -}) - -export const updateColumn = mutation({ - args: updateColumnSchema, - handler: async (ctx, newColumn) => { - const { id, boardId } = newColumn - await ensureBoardExists(ctx, boardId) - const item = await ensureColumnExists(ctx, id) - await ctx.db.patch(item._id, newColumn) - }, -}) - -export const updateBoard = mutation({ - args: updateBoardSchema, - handler: async (ctx, boardUpdate) => { - const board = await ensureBoardExists(ctx, boardUpdate.id) - await ctx.db.patch(board._id, boardUpdate) - }, -}) - -export const deleteColumn = mutation({ - args: deleteColumnSchema, - handler: async (ctx, { boardId, id }) => { - await ensureBoardExists(ctx, boardId) - const column = await ensureColumnExists(ctx, id) - const items = await ctx.db - .query('items') - .withIndex('column', (q) => q.eq('columnId', id)) - .collect() - await Promise.all(items.map((item) => ctx.db.delete(item._id))) - await ctx.db.delete(column._id) - }, -}) diff --git a/examples/react/start-convex-trellaux/convex/crons.ts b/examples/react/start-convex-trellaux/convex/crons.ts deleted file mode 100644 index a11889d5b1d..00000000000 --- a/examples/react/start-convex-trellaux/convex/crons.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { cronJobs } from 'convex/server' -import { internal } from './_generated/api' - -const crons = cronJobs() - -crons.cron('clear messages table', '0,20,40 * * * *', internal.board.clear) - -export default crons diff --git a/examples/react/start-convex-trellaux/convex/schema.ts b/examples/react/start-convex-trellaux/convex/schema.ts deleted file mode 100644 index 18dca7862af..00000000000 --- a/examples/react/start-convex-trellaux/convex/schema.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { defineSchema, defineTable } from 'convex/server' -import { type Infer, v } from 'convex/values' - -const schema = defineSchema({ - boards: defineTable({ - id: v.string(), - name: v.string(), - color: v.string(), - }).index('id', ['id']), - - columns: defineTable({ - id: v.string(), - boardId: v.string(), - name: v.string(), - order: v.number(), - }) - .index('id', ['id']) - .index('board', ['boardId']), - - items: defineTable({ - id: v.string(), - title: v.string(), - content: v.optional(v.string()), - order: v.number(), - columnId: v.string(), - boardId: v.string(), - }) - .index('id', ['id']) - .index('column', ['columnId']) - .index('board', ['boardId']), -}) -export default schema - -const board = schema.tables.boards.validator -const column = schema.tables.columns.validator -const item = schema.tables.items.validator - -export const updateBoardSchema = v.object({ - id: board.fields.id, - name: v.optional(board.fields.name), - color: v.optional(v.string()), -}) - -export const updateColumnSchema = v.object({ - id: column.fields.id, - boardId: column.fields.boardId, - name: v.optional(column.fields.name), - order: v.optional(column.fields.order), -}) - -export const deleteItemSchema = v.object({ - id: item.fields.id, - boardId: item.fields.boardId, -}) -const { order, id, ...rest } = column.fields -export const newColumnsSchema = v.object(rest) -export const deleteColumnSchema = v.object({ - boardId: column.fields.boardId, - id: column.fields.id, -}) - -export type Board = Infer -export type Column = Infer -export type Item = Infer diff --git a/examples/react/start-convex-trellaux/convex/tsconfig.json b/examples/react/start-convex-trellaux/convex/tsconfig.json deleted file mode 100644 index 6fa874e8164..00000000000 --- a/examples/react/start-convex-trellaux/convex/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - /* This TypeScript project config describes the environment that - * Convex functions run in and is used to typecheck them. - * You can modify it, but some settings required to use Convex. - */ - "compilerOptions": { - /* These settings are not required by Convex and can be modified. */ - "allowJs": true, - "strict": true, - "moduleResolution": "Bundler", - "jsx": "react-jsx", - "skipLibCheck": true, - "allowSyntheticDefaultImports": true, - - /* These compiler options are required by Convex */ - "target": "ESNext", - "lib": ["ES2021", "dom"], - "forceConsistentCasingInFileNames": true, - "module": "ESNext", - "isolatedModules": true, - "noEmit": true - }, - "include": ["./**/*"], - "exclude": ["./_generated"] -} diff --git a/examples/react/start-convex-trellaux/package.json b/examples/react/start-convex-trellaux/package.json deleted file mode 100644 index adc2107f8df..00000000000 --- a/examples/react/start-convex-trellaux/package.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "tanstack-start-example-convex-trellaux", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "npx convex dev --once && concurrently -r npm:dev:web npm:dev:db", - "dev:web": "vite dev", - "dev:db": "convex dev --run board:seed", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" - }, - "dependencies": { - "@convex-dev/react-query": "0.0.0-alpha.8", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.161.1", - "@tanstack/react-router-devtools": "^1.161.1", - "@tanstack/react-router-ssr-query": "^1.161.1", - "@tanstack/react-start": "^1.161.1", - "concurrently": "^8.2.2", - "convex": "^1.19.0", - "ky": "^1.7.4", - "msw": "^2.7.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "react-hot-toast": "^2.5.1", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", - "tiny-invariant": "^1.3.3", - "zod": "^3.24.2" - }, - "devDependencies": { - "@tailwindcss/vite": "^4.1.18", - "@types/node": "22.10.2", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "tailwindcss": "^4.1.18", - "typescript": "^5.7.2", - "vite": "^7.3.1", - "vite-tsconfig-paths": "^5.1.4" - } -} diff --git a/examples/react/start-convex-trellaux/public/android-chrome-192x192.png b/examples/react/start-convex-trellaux/public/android-chrome-192x192.png deleted file mode 100644 index 09c8324f8c6..00000000000 Binary files a/examples/react/start-convex-trellaux/public/android-chrome-192x192.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/android-chrome-512x512.png b/examples/react/start-convex-trellaux/public/android-chrome-512x512.png deleted file mode 100644 index 11d626ea3d0..00000000000 Binary files a/examples/react/start-convex-trellaux/public/android-chrome-512x512.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/apple-touch-icon.png b/examples/react/start-convex-trellaux/public/apple-touch-icon.png deleted file mode 100644 index 5a9423cc02c..00000000000 Binary files a/examples/react/start-convex-trellaux/public/apple-touch-icon.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/favicon-16x16.png b/examples/react/start-convex-trellaux/public/favicon-16x16.png deleted file mode 100644 index e3389b00443..00000000000 Binary files a/examples/react/start-convex-trellaux/public/favicon-16x16.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/favicon-32x32.png b/examples/react/start-convex-trellaux/public/favicon-32x32.png deleted file mode 100644 index 900c77d444c..00000000000 Binary files a/examples/react/start-convex-trellaux/public/favicon-32x32.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/favicon.ico b/examples/react/start-convex-trellaux/public/favicon.ico deleted file mode 100644 index 1a1751676f7..00000000000 Binary files a/examples/react/start-convex-trellaux/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/favicon.png b/examples/react/start-convex-trellaux/public/favicon.png deleted file mode 100644 index 1e77bc06091..00000000000 Binary files a/examples/react/start-convex-trellaux/public/favicon.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/github-mark-white.png b/examples/react/start-convex-trellaux/public/github-mark-white.png deleted file mode 100644 index 50b81752278..00000000000 Binary files a/examples/react/start-convex-trellaux/public/github-mark-white.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/site.webmanifest b/examples/react/start-convex-trellaux/public/site.webmanifest deleted file mode 100644 index fa99de77db6..00000000000 --- a/examples/react/start-convex-trellaux/public/site.webmanifest +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "", - "short_name": "", - "icons": [ - { - "src": "/android-chrome-192x192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "/android-chrome-512x512.png", - "sizes": "512x512", - "type": "image/png" - } - ], - "theme_color": "#ffffff", - "background_color": "#ffffff", - "display": "standalone" -} diff --git a/examples/react/start-convex-trellaux/public/tanstack.png b/examples/react/start-convex-trellaux/public/tanstack.png deleted file mode 100644 index e0b8e2802bf..00000000000 Binary files a/examples/react/start-convex-trellaux/public/tanstack.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/src/components/Board.tsx b/examples/react/start-convex-trellaux/src/components/Board.tsx deleted file mode 100644 index 327603e2046..00000000000 --- a/examples/react/start-convex-trellaux/src/components/Board.tsx +++ /dev/null @@ -1,116 +0,0 @@ -import { useCallback, useMemo, useRef } from 'react' -import invariant from 'tiny-invariant' -import { useSuspenseQuery } from '@tanstack/react-query' -import { convexQuery } from '@convex-dev/react-query' -import { api } from '../../convex/_generated/api.js' -import { useUpdateBoardMutation } from '../queries.js' -import { NewColumn } from './NewColumn.js' -import { Column as ColumnComponent } from './Column.js' -import type { Column } from 'convex/schema.js' -import { EditableText } from '~/components/EditableText.js' - -export function Board({ boardId }: { boardId: string }) { - const newColumnAddedRef = useRef(false) - const updateBoardMutation = useUpdateBoardMutation() - const { data: board } = useSuspenseQuery( - convexQuery(api.board.getBoard, { id: boardId }), - ) - - // scroll right when new columns are added - const scrollContainerRef = useRef(null) - const columnRef = useCallback((_node: HTMLElement | null) => { - if (scrollContainerRef.current && newColumnAddedRef.current) { - newColumnAddedRef.current = false - scrollContainerRef.current.scrollLeft = - scrollContainerRef.current.scrollWidth - } - }, []) - - const itemsById = useMemo( - () => new Map(board.items.map((item) => [item.id, item])), - [board.items], - ) - - type ColumnWithItems = Column & { items: typeof board.items } - - const columns = useMemo(() => { - const columnsMap = new Map() - - for (const column of [...board.columns]) { - columnsMap.set(column.id, { ...column, items: [] }) - } - - // add items to their columns - for (const item of itemsById.values()) { - const columnId = item.columnId - const column = columnsMap.get(columnId) - invariant( - column, - `missing column: ${columnId} from ${[...columnsMap.keys()]}`, - ) - column.items.push(item) - } - - return [...columnsMap.values()].sort((a, b) => a.order - b.order) - }, [board.columns, itemsById]) - - return ( -
-

- { - updateBoardMutation.mutate({ - id: board.id, - name: value, - }) - }} - /> -

- -
- {columns.map((col, index) => { - return ( - - ) - })} - { - newColumnAddedRef.current = true - }} - /> -
- - {/* trolling you to add some extra margin to the right of the container with a whole dang div */} -
-
- ) -} diff --git a/examples/react/start-convex-trellaux/src/components/CancelButton.tsx b/examples/react/start-convex-trellaux/src/components/CancelButton.tsx deleted file mode 100644 index 09b92ec15ff..00000000000 --- a/examples/react/start-convex-trellaux/src/components/CancelButton.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { forwardRef } from 'react' - -export const CancelButton = forwardRef< - HTMLButtonElement, - React.ButtonHTMLAttributes ->((props, ref) => { - return ( - - -
- - ) - }, -) diff --git a/examples/react/start-convex-trellaux/src/components/Column.tsx b/examples/react/start-convex-trellaux/src/components/Column.tsx deleted file mode 100644 index dd90e02ee71..00000000000 --- a/examples/react/start-convex-trellaux/src/components/Column.tsx +++ /dev/null @@ -1,250 +0,0 @@ -import { forwardRef, useCallback, useMemo, useRef, useState } from 'react' -import invariant from 'tiny-invariant' -import { twMerge } from 'tailwind-merge' - -import { flushSync } from 'react-dom' -import { CONTENT_TYPES } from '../types' -import { Icon } from '../icons/icons' -import { - useDeleteColumnMutation, - useUpdateCardMutation, - useUpdateColumnMutation, -} from '../queries' -import { EditableText } from './EditableText' -import { NewCard } from './NewCard' -import { Card } from './Card' -import type { RenderedItem } from '../types' - -interface ColumnProps { - name: string - boardId: string - columnId: string - items: Array - nextOrder: number - previousOrder: number - order: number -} - -export const Column = forwardRef( - ( - { name, columnId, boardId, items, nextOrder, previousOrder, order }, - ref, - ) => { - const [acceptCardDrop, setAcceptCardDrop] = useState(false) - const editState = useState(false) - - const [acceptColumnDrop, setAcceptColumnDrop] = useState< - 'none' | 'left' | 'right' - >('none') - - const [edit, setEdit] = useState(false) - - const itemRef = useCallback((node: HTMLElement | null) => { - node?.scrollIntoView({ - block: 'nearest', - }) - }, []) - - const listRef = useRef(null!) - - function scrollList() { - invariant(listRef.current) - listRef.current.scrollTop = listRef.current.scrollHeight - } - - const updateColumnMutation = useUpdateColumnMutation() - const deleteColumnMutation = useDeleteColumnMutation() - const updateCardMutation = useUpdateCardMutation() - - const sortedItems = useMemo( - () => [...items].sort((a, b) => a.order - b.order), - [items], - ) - - const cardDndProps = { - onDragOver: (event: React.DragEvent) => { - if (event.dataTransfer.types.includes(CONTENT_TYPES.card)) { - event.preventDefault() - setAcceptCardDrop(true) - } - }, - onDragLeave: () => { - setAcceptCardDrop(false) - }, - onDrop: (event: React.DragEvent) => { - const transfer = JSON.parse( - event.dataTransfer.getData(CONTENT_TYPES.card) || 'null', - ) - - if (!transfer) { - return - } - - invariant(transfer.id, 'missing transfer.id') - invariant(transfer.title, 'missing transfer.title') - - updateCardMutation.mutate({ - order: (sortedItems[sortedItems.length - 1]?.order ?? 0) + 1, - columnId: columnId, - boardId, - id: transfer.id, - title: transfer.title, - }) - - setAcceptCardDrop(false) - }, - } - - return ( -
{ - if (event.dataTransfer.types.includes(CONTENT_TYPES.column)) { - event.preventDefault() - event.stopPropagation() - const rect = event.currentTarget.getBoundingClientRect() - const midpoint = (rect.left + rect.right) / 2 - setAcceptColumnDrop(event.clientX <= midpoint ? 'left' : 'right') - } - }} - onDragLeave={() => { - setAcceptColumnDrop('none') - }} - onDrop={(event: React.DragEvent) => { - const transfer = JSON.parse( - event.dataTransfer.getData(CONTENT_TYPES.column) || 'null', - ) - - if (!transfer) { - return - } - - invariant(transfer.id, 'missing transfer.id') - - const droppedOrder = - acceptColumnDrop === 'left' ? previousOrder : nextOrder - const moveOrder = (droppedOrder + order) / 2 - - updateColumnMutation.mutate({ - boardId, - id: transfer.id, - order: moveOrder, - }) - - setAcceptColumnDrop('none') - }} - className={twMerge( - 'border-l-transparent border-r-transparent border-l-2 border-r-2 -mr-[2px] last:mr-0 cursor-grab active:cursor-grabbing px-2 shrink-0 flex flex-col max-h-full', - acceptColumnDrop === 'left' - ? 'border-l-red-500 border-r-transparent' - : acceptColumnDrop === 'right' - ? 'border-r-red-500 border-l-transparent' - : '', - )} - > -
{ - event.dataTransfer.effectAllowed = 'move' - event.dataTransfer.setData( - CONTENT_TYPES.column, - JSON.stringify({ id: columnId, name }), - ) - }} - {...(!items.length ? cardDndProps : {})} - className={twMerge( - 'shrink-0 flex flex-col max-h-full w-80 border-slate-400 rounded-xl shadow-xs shadow-slate-400 bg-slate-100 relative', - acceptCardDrop && `outline-solid outline-2 outline-red-500`, - )} - > -
- { - updateColumnMutation.mutate({ - boardId, - id: columnId, - name: value, - }) - }} - /> -
- -
    - {sortedItems.map((item, index, items) => ( - - ))} -
- {edit ? ( - setEdit(false)} - /> - ) : ( -
- -
- )} -
{ - event.preventDefault() - - deleteColumnMutation.mutate({ - id: columnId, - boardId, - }) - }} - > - -
-
-
- ) - }, -) diff --git a/examples/react/start-convex-trellaux/src/components/DefaultCatchBoundary.tsx b/examples/react/start-convex-trellaux/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index ef2daa1ea1d..00000000000 --- a/examples/react/start-convex-trellaux/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { - ErrorComponent, - Link, - rootRouteId, - useMatch, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error(error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/examples/react/start-convex-trellaux/src/components/EditableText.tsx b/examples/react/start-convex-trellaux/src/components/EditableText.tsx deleted file mode 100644 index aa74b282667..00000000000 --- a/examples/react/start-convex-trellaux/src/components/EditableText.tsx +++ /dev/null @@ -1,85 +0,0 @@ -import { useRef, useState } from 'react' -import { flushSync } from 'react-dom' - -export function EditableText({ - fieldName, - value, - inputClassName, - inputLabel, - buttonClassName, - buttonLabel, - onChange, - editState, -}: { - fieldName: string - value: string - inputClassName: string - inputLabel: string - buttonClassName: string - buttonLabel: string - onChange: (value: string) => void - editState?: [boolean, (value: boolean) => void] -}) { - const localEditState = useState(false) - const [edit, setEdit] = editState || localEditState - const inputRef = useRef(null) - const buttonRef = useRef(null) - - return edit ? ( -
{ - event.preventDefault() - - onChange(inputRef.current!.value) - - flushSync(() => { - setEdit(false) - }) - - buttonRef.current?.focus() - }} - > - { - if (event.key === 'Escape') { - flushSync(() => { - setEdit(false) - }) - buttonRef.current?.focus() - } - }} - onBlur={(event) => { - if ( - inputRef.current?.value !== value && - inputRef.current?.value.trim() !== '' - ) { - onChange(inputRef.current!.value) - } - setEdit(false) - }} - /> -
- ) : ( - - ) -} diff --git a/examples/react/start-convex-trellaux/src/components/IconLink.tsx b/examples/react/start-convex-trellaux/src/components/IconLink.tsx deleted file mode 100644 index 6ab5be2053b..00000000000 --- a/examples/react/start-convex-trellaux/src/components/IconLink.tsx +++ /dev/null @@ -1,19 +0,0 @@ -export function IconLink({ - icon, - href, - label, -}: { - icon: string - href: string - label: string -}) { - return ( - - - {label} - - ) -} diff --git a/examples/react/start-convex-trellaux/src/components/Loader.tsx b/examples/react/start-convex-trellaux/src/components/Loader.tsx deleted file mode 100644 index 1058eabde39..00000000000 --- a/examples/react/start-convex-trellaux/src/components/Loader.tsx +++ /dev/null @@ -1,7 +0,0 @@ -export function Loader() { - return ( -
-
-
- ) -} diff --git a/examples/react/start-convex-trellaux/src/components/NewCard.tsx b/examples/react/start-convex-trellaux/src/components/NewCard.tsx deleted file mode 100644 index 47cadcf5aee..00000000000 --- a/examples/react/start-convex-trellaux/src/components/NewCard.tsx +++ /dev/null @@ -1,87 +0,0 @@ -import { useRef } from 'react' -import invariant from 'tiny-invariant' - -import { ItemMutationFields } from '../types' -import { useCreateItemMutation } from '../queries' -import { itemSchema } from '../db/schema' -import { SaveButton } from '~/components/SaveButton' -import { CancelButton } from '~/components/CancelButton' - -export function NewCard({ - columnId, - boardId, - nextOrder, - onComplete, -}: { - columnId: string - boardId: string - nextOrder: number - onComplete: () => void -}) { - const textAreaRef = useRef(null) - const buttonRef = useRef(null) - const { mutate } = useCreateItemMutation() - - return ( -
{ - event.preventDefault() - - const formData = new FormData(event.currentTarget) - const id = crypto.randomUUID() - formData.set(ItemMutationFields.id.name, id) - - invariant(textAreaRef.current) - textAreaRef.current.value = '' - - mutate(itemSchema.parse(Object.fromEntries(formData.entries()))) - }} - onBlur={(event) => { - if (!event.currentTarget.contains(event.relatedTarget)) { - onComplete() - } - }} - > - - - - -