@rsc-kit/core 0.34.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,kEAAkE;AAClE,8EAA8E;AAC9E,4EAA4E;AAC5E,6EAA6E;AAC7E,mCAAmC;AACnC,EAAE;AACF,wEAAwE;AACxE,kEAAkE;AAClE,6EAA6E;AAC7E,8EAA8E;AAC9E,8CAA8C;AAC9C,EAAE;AACF,8EAA8E;AAC9E,sCAAsC;AACtC,EAAE;AACF,4CAA4C;AAC5C,2DAA2D;AAC3D,MAAM;AACN,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,8EAA8E;AAC9E,4EAA4E;AAC5E,kBAAkB;AAsJlB;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,MAAM,CAAC,IAAc;IACnC,OAAO,IAAI,CAAC;AACd,CAAC;AAwLD,uGAAuG;AACvG,MAAM,UAAU,YAAY,CAAC,MAAc;IACzC,MAAM,MAAM,GAAG,IAAI,eAAe,EAAE,CAAC;IAErC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAClD,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;YAAE,SAAS;QAEpD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACzB,KAAK,MAAM,IAAI,IAAI,KAAK;gBAAE,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;QAC7D,CAAC;aAAM,CAAC;YACN,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;IAED,OA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AAO,EACP,GAAG,IAEuB;IAE1B,OAAO,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAuB,CAAU,CAAC;AAClE,CAAC;AAyED,MAAM,UAAU,OAAO,CAAC,IAAY,EAAE,IAAa;IACjD,MAAM,IAAI,GAAG,OAAO,iBAAiB,KAAK,QAAQ,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,IAAI,CAAC;IAE9E,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAU,CAAC;IAC3E,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,KAAK,IAAI,GAAG,IAAI,EAAW,CAAC;IAC3D,IAAI,IAAI;QAAE,OAAO,KAAK,IAAI,IAAI,IAAI,GAAG,IAAI,EAAW,CAAC;IAErD,OAAO,IAAI,IAAI,GAAG,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAW,CAAC;AACzH,CAAC","sourcesContent":["// Typed routes: the urls this app can actually answer, as a type.\n//\n// Laravel needs route() because the url lives in PHP and can move\n// independently of the name it is called by. Here the url *is* the file path,\n// so a name would be indirection that buys nothing. What is worth having is\n// the other half — a link to a page that does not exist should fail at build\n// time rather than in the browser.\n//\n// There is no route() builder to go with this, deliberately. A template\n// literal is checked the same way — `/posts/${slug}` compiles and\n// `/postz/${slug}` does not — so a builder would only wrap what the language\n// already does. Encoding a value that is not url-safe is `encodeURIComponent`\n// in the template, the same as anywhere else.\n//\n// The build already walks app/ and knows every route's segments, so it writes\n// one line into the app's source dir:\n//\n// declare module '@rsc-kit/core/routes' {\n// interface Register { routes: '/' | '/posts/[slug]' }\n// }\n//\n// Everything below is derived from that union. An app that never runs the\n// generator — a generic host, a Laravel app that has not rebuilt — registers\n// nothing, `RoutePattern` stays `string`, and every url-taking API is exactly\n// as permissive as it was before. That fallback is the reason this can ship\n// without a flag.\n\n/**\n * Augmented by the generated `rsc-routes.d.ts`. Empty here on purpose.\n *\n * Declaration merging rather than a generic parameter, because the routes are\n * a property of the project, not of each call site — threading them through\n * every component that renders a Link is not a thing anyone would do twice.\n */\nexport interface Register {}\n\n/** The route patterns this app declared: `'/posts/[slug]'`. */\nexport type RoutePattern = Register extends { routes: infer R extends string }\n ? R\n : string;\n\n/** Whether anything was registered. `string` means the generator never ran. */\ntype Unregistered = string extends RoutePattern ? true : false;\n\n/**\n * A pattern with its dynamic segments opened up: `/posts/[slug]` accepts\n * `/posts/anything`.\n *\n * Catch-all and single params both become `${string}`, which for a catch-all\n * also swallows the slashes — `/docs/[...path]` accepts `/docs/a/b/c`.\n */\ntype Filled<P extends string> = P extends `${infer A}[...${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P extends `${infer A}[${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P;\n\n/**\n * Not a route, but a legitimate href: another site, a mail client, a phone\n * number, an anchor on this page, a bare query string.\n */\ntype OffRoute =\n | `${string}://${string}`\n | `mailto:${string}`\n | `tel:${string}`\n | `#${string}`\n | `?${string}`;\n\n/**\n * A url this app can answer, or one that deliberately leaves it.\n *\n * Cast when the destination is computed rather than written:\n * `href={path as Route}`.\n */\n/**\n * A url this app answers - a page or a route.ts - or one that deliberately\n * leaves it. One type, as Next's `Route` is one type: what `<Link href>`,\n * `visit()` and `redirect()` take. A route.ts is a full navigation rather\n * than a payload fetch, and never prefetched - the client knows which urls\n * are routes and treats a link to one as the anchor it is - so the type\n * does not have to keep them apart to keep a hover from running one.\n *\n * `Route` is the same type under the name Next uses, so a port keeps the\n * word it already has.\n */\nexport type Route = Unregistered extends true\n ? string\n : | Filled<RoutePattern>\n | `${Filled<RoutePattern>}?${string}`\n | `${Filled<RoutePattern>}#${string}`\n | Filled<ApiPattern>\n | `${Filled<ApiPattern>}?${string}`\n | BackendUrl\n | OffRoute;\n\n// ── The backend's urls ───────────────────────────────────────────────────────\n//\n// `rscKit({ backendPaths: ['/gitlab'] })` names the prefixes the backend owns.\n// They are not in the route tree, so a link or a redirect to `/gitlab/connect`\n// needed a cast to compile, for a url the app itself had declared. They are a\n// place to go and, like a route.ts, a full page load.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterBackend {}\n\n/** The prefixes `backendPaths` named: `'/gitlab'`. */\ntype BackendPrefix = RegisterBackend extends { paths: infer P extends string }\n ? P\n : never;\n\n/**\n * A prefix and everything under it, at a segment boundary: `/gitlab`,\n * `/gitlab/connect?next=/`, never `/gitlabs`. `never` when nothing was named.\n */\ntype BackendUrl =\n | BackendPrefix\n | `${BackendPrefix}/${string}`\n | `${BackendPrefix}?${string}`\n | `${BackendPrefix}#${string}`;\n\n// ── Api routes ───────────────────────────────────────────────────────────────\n//\n// Their own union rather than part of Route, because they are not pages and a\n// link to one is almost always a mistake — an <a href=\"/api/orders\"> navigates\n// the browser away to a json document. Keeping them apart means `Link` refuses\n// an api url and `apiUrl()` refuses a page, which is the pair of mistakes worth\n// catching.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterApi {}\n\n// ── Regions a page can re-render on its own ──────────────────────────────────\n//\n// Every `section('name', …)` the build found, and every `@slot` directory.\n// `revalidate('orders')` is checked against them, so a name that matches no\n// section - a typo, or a section renamed since - stops compiling instead of\n// being refused by the renderer at runtime.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterRegions {}\n\n/** The region names the build found: section names and slot names. */\nexport type RegionName = RegisterRegions extends {\n regions: infer R extends string;\n}\n ? R\n : string;\n\ntype NoRegions = string extends RegionName ? true : false;\n\n/**\n * What `revalidate()` takes: the page, the whole document, or a region by\n * name. `string` until the build has written the types.\n */\nexport type RevalidateTarget = NoRegions extends true\n ? string\n : \"page\" | \"all\" | RegionName;\n\n/** The api route patterns this app declared: `'/api/orders/[id]'`. */\nexport type ApiPattern = RegisterApi extends { apis: infer R extends string }\n ? R\n : string;\n\ntype NoApis = string extends ApiPattern ? true : false;\n\n/**\n * A url an api route in this app answers.\n *\n * `/api/orders/[id]` accepts `/api/orders/42`, and a query string is allowed\n * because that is how a GET is parameterised.\n */\nexport type ApiRoute = NoApis extends true\n ? string\n : Filled<ApiPattern> | `${Filled<ApiPattern>}?${string}`;\n\n/**\n * An api url, checked against the routes the build found.\n *\n * await fetch(apiUrl(`/api/orders/${id}`))\n *\n * A function rather than a bare type so it can be used inline at a call site\n * that is typed `string` — `fetch` takes any string, so nothing would check the\n * argument without somewhere to put the type. It returns what it was given.\n *\n * Wrong path, and it stops compiling. Renamed the directory, and every call\n * site says so rather than one of them 404ing in production.\n */\nexport function apiUrl(href: ApiRoute): string {\n return href;\n}\n\n// ── What an events route sends ───────────────────────────────────────────────\n//\n// A route.ts whose GET is `events(...)` says, as a type, what its generator\n// yields. The generated file records that per api pattern:\n//\n// interface RegisterApi {\n// events: { '/api/orders/[id]/events': EventsExportOf<typeof import('../src/app/api/orders/[id]/events/route')> }\n// }\n//\n// and `useEvents` reads a url's messages from it, so the hook and the route\n// cannot disagree about a message's shape.\n\n/** What a route module's GET yields, when it is `events(...)`; `unknown` for any other stream. */\nexport type EventsExportOf<M> = M extends {\n GET: { readonly \"~events\"?: infer S };\n}\n ? NonNullable<S> extends { yields: infer Y }\n ? Y\n : unknown\n : unknown;\n\ntype EventsMap = RegisterApi extends { events: infer M } ? M : {};\n\ntype Split<S extends string> = S extends `${infer A}/${infer B}`\n ? [A, ...Split<B>]\n : [S];\n\n/**\n * Whether a url's segments fit a pattern's, one segment at a time. Unlike\n * `Filled`, a `[id]` takes exactly one segment, so `/api/orders/42/events`\n * is `/api/orders/[id]/events` and not also `/api/orders/[id]`.\n */\ntype Fits<H extends string[], P extends string[]> = P extends [\n infer P0 extends string,\n ...infer PR extends string[],\n]\n ? P0 extends `[...${string}]`\n ? H extends [string, ...string[]]\n ? true\n : false\n : H extends [infer H0 extends string, ...infer HR extends string[]]\n ? P0 extends `[${string}]`\n ? Fits<HR, PR>\n : H0 extends P0\n ? Fits<HR, PR>\n : false\n : false\n : H extends []\n ? true\n : false;\n\n/** The api pattern a written url belongs to: `/api/orders/42/events` is `/api/orders/[id]/events`. */\ntype ApiPatternOf<H extends string> = ApiPattern extends infer P\n ? P extends string\n ? Fits<Split<StripQuery<H>>, Split<P>> extends true\n ? P\n : never\n : never\n : never;\n\n/**\n * Everything the stream at `H` yields, named events included. `unknown` when\n * `H` is not one api route the build found - a url computed at runtime, or\n * another site's - since there is nothing to read it from.\n */\nexport type EventsAt<H extends string> = NoApis extends true\n ? unknown\n : IsUnion<H> extends true\n ? unknown\n : [ApiPatternOf<H>] extends [never]\n ? unknown\n : ApiPatternOf<H> extends keyof EventsMap\n ? EventsMap[ApiPatternOf<H>]\n : unknown;\n\n/** A url `useEvents` may open: an api route this app answers, or another site's stream. */\nexport type EventsUrl = ApiRoute | `${string}://${string}`;\n\n// ── Search params, typed per route ───────────────────────────────────────────\n//\n// A page that exports a `searchParams` schema has said what its query string\n// means. The generated file records that schema per pattern:\n//\n// interface Register {\n// search: { '/search': SearchExportOf<typeof import('../src/app/search/page')> }\n// }\n//\n// and from there a link to `/search` is checked against the same schema the\n// page parses with — a `page` that must be a number is a number on the link,\n// a `q` the page requires is required to write the link, and a key the page\n// never reads does not compile. One schema, both ends. A route that exports\n// none takes anything; an href that is not a single route (computed, cast, or\n// off-site) takes anything too, because there is nothing to check it against.\n\n/** What a page module contributes: its `searchParams` export, or nothing. For the generated file. */\nexport type SearchExportOf<M> = M extends { searchParams: infer S }\n ? S\n : undefined;\n\ntype SearchMap = Register extends { search: infer M } ? M : {};\n\ntype StripQuery<H extends string> = H extends `${infer P}?${string}`\n ? P\n : H extends `${infer P}#${string}`\n ? P\n : H;\n\n/** The pattern a written href belongs to: `/posts/hello` is `/posts/[slug]`. */\ntype PatternOf<H extends string> = RoutePattern extends infer P\n ? P extends string\n ? StripQuery<H> extends Filled<P>\n ? P\n : never\n : never\n : never;\n\ntype IsUnion<T, U = T> = T extends unknown\n ? [U] extends [T]\n ? false\n : true\n : never;\n\ntype SchemaFor<P> = P extends keyof SearchMap ? SearchMap[P] : undefined;\n\ntype InputOf<S> = S extends { \"~standard\": { types?: { input: infer I } } }\n ? I\n : never;\ntype OutputOf<S> = S extends { \"~standard\": { types?: { output: infer O } } }\n ? O\n : never;\n\ntype OptionalKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? K : never;\n}[keyof T];\ntype RequiredKeys<T> = Exclude<keyof T, OptionalKeys<T>>;\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/**\n * What a link may write for a schema: the keys the schema's input requires\n * are required, the rest optional, and every value is the schema's OUTPUT\n * type. Output rather than input because `z.coerce.number()` takes `unknown`\n * in - that is what coercion means - and a link typed by it would accept\n * `page: 'two'`. The output is the number the page will actually see.\n */\ntype LinkInputOf<S> = Simplify<\n { [K in RequiredKeys<InputOf<S>> & keyof OutputOf<S>]: OutputOf<S>[K] } & {\n [K in OptionalKeys<InputOf<S>> & keyof OutputOf<S>]?: OutputOf<S>[K];\n }\n>;\n\ntype Scalar = string | number | boolean | null | undefined;\n\n/** What a link may carry when nothing declares otherwise. */\nexport type LooseSearch = Record<string, Scalar | readonly (string | number)[]>;\n\n/**\n * The search params a link to `H` may carry.\n *\n * The page's schema input when `H` is one declared route with a schema;\n * otherwise anything. \"One route\" matters: `path as Route` is every route at\n * once, and a link that could go anywhere cannot be held to one page's schema.\n */\nexport type SearchFor<H extends string> = Unregistered extends true\n ? LooseSearch\n : IsUnion<H> extends true\n ? LooseSearch\n : [PatternOf<H>] extends [never]\n ? LooseSearch\n : SchemaFor<PatternOf<H>> extends undefined\n ? LooseSearch\n : LinkInputOf<SchemaFor<PatternOf<H>>>;\n\n/**\n * The `search` prop, required exactly when the page's schema has a required\n * key. A page that needs `q` is not reachable without one, so the link that\n * omits it is the bug — caught here rather than on the page's error boundary.\n */\nexport type SearchProp<H extends string> =\n {} extends SearchFor<H>\n ? { search?: SearchFor<H> }\n : { search: SearchFor<H> };\n\n/** A query string from an object: scalars stringified, arrays repeated, null and undefined dropped. */\nexport function searchString(search: object): string {\n const params = new URLSearchParams();\n\n for (const [key, value] of Object.entries(search)) {\n if (value === null || value === undefined) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) params.append(key, String(item));\n } else {\n params.set(key, String(value));\n }\n }\n\n return params.toString();\n}\n\n/** `path` with `search` appended, keeping any query and hash already on it. */\nexport function withSearch(path: string, search: object | undefined): string {\n if (!search) return path;\n\n const hashAt = path.indexOf(\"#\");\n const hash = hashAt === -1 ? \"\" : path.slice(hashAt);\n const before = hashAt === -1 ? path : path.slice(0, hashAt);\n const queryAt = before.indexOf(\"?\");\n const base = queryAt === -1 ? before : before.slice(0, queryAt);\n const existing = queryAt === -1 ? \"\" : before.slice(queryAt + 1);\n const added = searchString(search);\n const query = [existing, added].filter(Boolean).join(\"&\");\n\n return query ? `${base}?${query}${hash}` : `${base}${hash}`;\n}\n\n/**\n * A typed url with its search params, for the places that take a string.\n *\n * visit(href('/search', { q: 'shoes', page: 2 }))\n *\n * `Link` has the same check on its own `search` prop. This is for `visit`,\n * `prefetch`, `redirect` and anything else that wants the finished string.\n */\nexport function href<H extends Route>(\n path: H,\n ...rest: {} extends SearchFor<H>\n ? [search?: SearchFor<H>]\n : [search: SearchFor<H>]\n): Route {\n return withSearch(path, rest[0] as object | undefined) as Route;\n}\n\n// ── Another host ─────────────────────────────────────────────────────────────\n//\n// A page under app/merchant is reached as merchant.example.com/orders as well\n// as example.com/merchant/orders, and a page under app/[domain] only from the\n// tenant's own host. A typed `href` names the folder path, which is the second\n// of those - and the first is a host Link cannot know you meant. So the host is\n// said where it is meant, and the path is typed for it.\n\n/** The site's host, from rscKit({ hosts }) or a literal metadataBase, baked in by the build. */\ndeclare const __RSC_SITE_HOST__: string | null | undefined;\n\n/** A top-level folder a url can begin with: `merchant` for app/merchant. */\ntype TopFolder<P> = P extends `/${infer F}/${string}`\n ? F extends `[${string}` ? never : F\n : P extends `/${infer F}`\n ? F extends `[${string}` | \"\" ? never : F\n : never;\n\n/** The patterns under `/${F}`, with the folder taken off: `/merchant/orders` → `/orders`. */\ntype Under<P, F extends string> = P extends `/${F}`\n ? \"/\"\n : P extends `/${F}/${infer R}`\n ? `/${R}`\n : never;\n\n/** A tenant tree's patterns, with the tenant taken off: `/[domain]/settings` → `/settings`. */\ntype TenantPaths<P> = P extends `/[domain]${infer R}` | `/[host]${infer R}`\n ? R extends \"\" ? \"/\" : R\n : never;\n\ntype WithQuery<P extends string> = P | `${P}?${string}` | `${P}#${string}`;\n\n/**\n * What `hostUrl`'s first argument autocompletes to: every top-level folder.\n * Any other string is taken too - a tenant's subdomain, a custom domain.\n */\nexport type HostName = Unregistered extends true ? string : HostFolder | (string & {});\n\n/** The top-level folders of the route tree: `merchant` for app/merchant. */\nexport type HostFolder = TopFolder<RoutePattern>;\n\n/**\n * The paths a host answers: for a folder's subdomain the pages under that\n * folder; for anything else the tenant tree's, or any path when there is none.\n */\nexport type HostPath<H extends string> = Unregistered extends true\n ? string\n : H extends HostFolder\n ? WithQuery<Filled<Under<RoutePattern, H>>>\n : [TenantPaths<RoutePattern>] extends [never]\n ? `/${string}`\n : WithQuery<Filled<TenantPaths<RoutePattern>>>;\n\n/**\n * A url on another host of the site, for `<Link href>`, `visit()` and\n * `redirect()`:\n *\n * hostUrl('merchant', '/orders') // //merchant.example.com/orders\n * hostUrl('testbrand', '/settings') // //testbrand.example.com/settings - a tenant\n * hostUrl('acme.com', '/settings') // //acme.com/settings - a name with a dot is a whole domain\n * hostUrl('/pricing') // //example.com/pricing - the site itself\n *\n * The site's host is the one rscKit({ hosts }) names first. Where none is\n * named, a folder's url is its path - `/merchant/orders` - as every page is\n * then reached by path; a tenant or a domain still names its host.\n *\n * The same string on the server and in the browser, so a link hydrates as\n * it rendered. On the host it names already, Link navigates without a reload.\n */\nexport function hostUrl(path: Route): Route;\nexport function hostUrl<H extends HostName>(host: H, path: HostPath<H>): Route;\nexport function hostUrl(host: string, path?: string): Route {\n const site = typeof __RSC_SITE_HOST__ === \"string\" ? __RSC_SITE_HOST__ : null;\n\n if (path === undefined) return (site ? `//${site}${host}` : host) as Route;\n if (host.includes(\".\")) return `//${host}${path}` as Route;\n if (site) return `//${host}.${site}${path}` as Route;\n\n return `/${host}${path === \"/\" ? \"\" : path.startsWith(\"/?\") || path.startsWith(\"/#\") ? path.slice(1) : path}` as Route;\n}\n"]}
1
+ {"version":3,"file":"routes.js","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,kEAAkE;AAClE,8EAA8E;AAC9E,4EAA4E;AAC5E,6EAA6E;AAC7E,mCAAmC;AACnC,EAAE;AACF,wEAAwE;AACxE,kEAAkE;AAClE,6EAA6E;AAC7E,8EAA8E;AAC9E,8CAA8C;AAC9C,EAAE;AACF,8EAA8E;AAC9E,sCAAsC;AACtC,EAAE;AACF,4CAA4C;AAC5C,2DAA2D;AAC3D,MAAM;AACN,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,8EAA8E;AAC9E,4EAA4E;AAC5E,kBAAkB;AAsJlB;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,MAAM,CAAC,IAAc;IACnC,OAAO,IAAI,CAAC;AACd,CAAC;AAwLD,uGAAuG;AACvG,MAAM,UAAU,YAAY,CAAC,MAAc;IACzC,MAAM,MAAM,GAAG,IAAI,eAAe,EAAE,CAAC;IAErC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAClD,IAAI,KAAK,KAAK,IAAI,I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IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAW,CAAC;AACzH,CAAC","sourcesContent":["// Typed routes: the urls this app can actually answer, as a type.\n//\n// Laravel needs route() because the url lives in PHP and can move\n// independently of the name it is called by. Here the url *is* the file path,\n// so a name would be indirection that buys nothing. What is worth having is\n// the other half — a link to a page that does not exist should fail at build\n// time rather than in the browser.\n//\n// There is no route() builder to go with this, deliberately. A template\n// literal is checked the same way — `/posts/${slug}` compiles and\n// `/postz/${slug}` does not — so a builder would only wrap what the language\n// already does. Encoding a value that is not url-safe is `encodeURIComponent`\n// in the template, the same as anywhere else.\n//\n// The build already walks app/ and knows every route's segments, so it writes\n// one line into the app's source dir:\n//\n// declare module '@rsc-kit/core/routes' {\n// interface Register { routes: '/' | '/posts/[slug]' }\n// }\n//\n// Everything below is derived from that union. An app that never runs the\n// generator — a generic host, a Laravel app that has not rebuilt — registers\n// nothing, `RoutePattern` stays `string`, and every url-taking API is exactly\n// as permissive as it was before. That fallback is the reason this can ship\n// without a flag.\n\n/**\n * Augmented by the generated `rsc-routes.d.ts`. Empty here on purpose.\n *\n * Declaration merging rather than a generic parameter, because the routes are\n * a property of the project, not of each call site — threading them through\n * every component that renders a Link is not a thing anyone would do twice.\n */\nexport interface Register {}\n\n/** The route patterns this app declared: `'/posts/[slug]'`. */\nexport type RoutePattern = Register extends { routes: infer R extends string }\n ? R\n : string;\n\n/** Whether anything was registered. `string` means the generator never ran. */\ntype Unregistered = string extends RoutePattern ? true : false;\n\n/**\n * A pattern with its dynamic segments opened up: `/posts/[slug]` accepts\n * `/posts/anything`.\n *\n * Catch-all and single params both become `${string}`, which for a catch-all\n * also swallows the slashes — `/docs/[...path]` accepts `/docs/a/b/c`.\n */\ntype Filled<P extends string> = P extends `${infer A}[...${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P extends `${infer A}[${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P;\n\n/**\n * Not a route, but a legitimate href: another site, a mail client, a phone\n * number, an anchor on this page, a bare query string.\n */\ntype OffRoute =\n | `${string}://${string}`\n | `mailto:${string}`\n | `tel:${string}`\n | `#${string}`\n | `?${string}`;\n\n/**\n * A url this app can answer, or one that deliberately leaves it.\n *\n * Cast when the destination is computed rather than written:\n * `href={path as Route}`.\n */\n/**\n * A url this app answers - a page or a route.ts - or one that deliberately\n * leaves it. One type, as Next's `Route` is one type: what `<Link href>`,\n * `visit()` and `redirect()` take. A route.ts is a full navigation rather\n * than a payload fetch, and never prefetched - the client knows which urls\n * are routes and treats a link to one as the anchor it is - so the type\n * does not have to keep them apart to keep a hover from running one.\n *\n * `Route` is the same type under the name Next uses, so a port keeps the\n * word it already has.\n */\nexport type Route = Unregistered extends true\n ? string\n : | Filled<RoutePattern>\n | `${Filled<RoutePattern>}?${string}`\n | `${Filled<RoutePattern>}#${string}`\n | Filled<ApiPattern>\n | `${Filled<ApiPattern>}?${string}`\n | BackendUrl\n | OffRoute;\n\n// ── The backend's urls ───────────────────────────────────────────────────────\n//\n// `rscKit({ backendPaths: ['/gitlab'] })` names the prefixes the backend owns.\n// They are not in the route tree, so a link or a redirect to `/gitlab/connect`\n// needed a cast to compile, for a url the app itself had declared. They are a\n// place to go and, like a route.ts, a full page load.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterBackend {}\n\n/** The prefixes `backendPaths` named: `'/gitlab'`. */\ntype BackendPrefix = RegisterBackend extends { paths: infer P extends string }\n ? P\n : never;\n\n/**\n * A prefix and everything under it, at a segment boundary: `/gitlab`,\n * `/gitlab/connect?next=/`, never `/gitlabs`. `never` when nothing was named.\n */\ntype BackendUrl =\n | BackendPrefix\n | `${BackendPrefix}/${string}`\n | `${BackendPrefix}?${string}`\n | `${BackendPrefix}#${string}`;\n\n// ── Api routes ───────────────────────────────────────────────────────────────\n//\n// Their own union rather than part of Route, because they are not pages and a\n// link to one is almost always a mistake — an <a href=\"/api/orders\"> navigates\n// the browser away to a json document. Keeping them apart means `Link` refuses\n// an api url and `apiUrl()` refuses a page, which is the pair of mistakes worth\n// catching.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterApi {}\n\n// ── Regions a page can re-render on its own ──────────────────────────────────\n//\n// Every `section('name', …)` the build found, and every `@slot` directory.\n// `revalidate('orders')` is checked against them, so a name that matches no\n// section - a typo, or a section renamed since - stops compiling instead of\n// being refused by the renderer at runtime.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterRegions {}\n\n/** The region names the build found: section names and slot names. */\nexport type RegionName = RegisterRegions extends {\n regions: infer R extends string;\n}\n ? R\n : string;\n\ntype NoRegions = string extends RegionName ? true : false;\n\n/**\n * What `revalidate()` takes: the page, the whole document, or a region by\n * name. `string` until the build has written the types.\n */\nexport type RevalidateTarget = NoRegions extends true\n ? string\n : \"page\" | \"all\" | RegionName;\n\n/** The api route patterns this app declared: `'/api/orders/[id]'`. */\nexport type ApiPattern = RegisterApi extends { apis: infer R extends string }\n ? R\n : string;\n\ntype NoApis = string extends ApiPattern ? true : false;\n\n/**\n * A url an api route in this app answers.\n *\n * `/api/orders/[id]` accepts `/api/orders/42`, and a query string is allowed\n * because that is how a GET is parameterised.\n */\nexport type ApiRoute = NoApis extends true\n ? string\n : Filled<ApiPattern> | `${Filled<ApiPattern>}?${string}`;\n\n/**\n * An api url, checked against the routes the build found.\n *\n * await fetch(apiUrl(`/api/orders/${id}`))\n *\n * A function rather than a bare type so it can be used inline at a call site\n * that is typed `string` — `fetch` takes any string, so nothing would check the\n * argument without somewhere to put the type. It returns what it was given.\n *\n * Wrong path, and it stops compiling. Renamed the directory, and every call\n * site says so rather than one of them 404ing in production.\n */\nexport function apiUrl(href: ApiRoute): string {\n return href;\n}\n\n// ── What an events route sends ───────────────────────────────────────────────\n//\n// A route.ts whose GET is `events(...)` says, as a type, what its generator\n// yields. The generated file records that per api pattern:\n//\n// interface RegisterApi {\n// events: { '/api/orders/[id]/events': EventsExportOf<typeof import('../src/app/api/orders/[id]/events/route')> }\n// }\n//\n// and `useEvents` reads a url's messages from it, so the hook and the route\n// cannot disagree about a message's shape.\n\n/** What a route module's GET yields, when it is `events(...)`; `unknown` for any other stream. */\nexport type EventsExportOf<M> = M extends {\n GET: { readonly \"~events\"?: infer S };\n}\n ? NonNullable<S> extends { yields: infer Y }\n ? Y\n : unknown\n : unknown;\n\ntype EventsMap = RegisterApi extends { events: infer M } ? M : {};\n\ntype Split<S extends string> = S extends `${infer A}/${infer B}`\n ? [A, ...Split<B>]\n : [S];\n\n/**\n * Whether a url's segments fit a pattern's, one segment at a time. Unlike\n * `Filled`, a `[id]` takes exactly one segment, so `/api/orders/42/events`\n * is `/api/orders/[id]/events` and not also `/api/orders/[id]`.\n */\ntype Fits<H extends string[], P extends string[]> = P extends [\n infer P0 extends string,\n ...infer PR extends string[],\n]\n ? P0 extends `[...${string}]`\n ? H extends [string, ...string[]]\n ? true\n : false\n : H extends [infer H0 extends string, ...infer HR extends string[]]\n ? P0 extends `[${string}]`\n ? Fits<HR, PR>\n : H0 extends P0\n ? Fits<HR, PR>\n : false\n : false\n : H extends []\n ? true\n : false;\n\n/** The api pattern a written url belongs to: `/api/orders/42/events` is `/api/orders/[id]/events`. */\ntype ApiPatternOf<H extends string> = ApiPattern extends infer P\n ? P extends string\n ? Fits<Split<StripQuery<H>>, Split<P>> extends true\n ? P\n : never\n : never\n : never;\n\n/**\n * Everything the stream at `H` yields, named events included. `unknown` when\n * `H` is not one api route the build found - a url computed at runtime, or\n * another site's - since there is nothing to read it from.\n */\nexport type EventsAt<H extends string> = NoApis extends true\n ? unknown\n : IsUnion<H> extends true\n ? unknown\n : [ApiPatternOf<H>] extends [never]\n ? unknown\n : ApiPatternOf<H> extends keyof EventsMap\n ? EventsMap[ApiPatternOf<H>]\n : unknown;\n\n/** A url `useEvents` may open: an api route this app answers, or another site's stream. */\nexport type EventsUrl = ApiRoute | `${string}://${string}`;\n\n// ── Search params, typed per route ───────────────────────────────────────────\n//\n// A page that exports a `searchParams` schema has said what its query string\n// means. The generated file records that schema per pattern:\n//\n// interface Register {\n// search: { '/search': SearchExportOf<typeof import('../src/app/search/page')> }\n// }\n//\n// and from there a link to `/search` is checked against the same schema the\n// page parses with — a `page` that must be a number is a number on the link,\n// a `q` the page requires is required to write the link, and a key the page\n// never reads does not compile. One schema, both ends. A route that exports\n// none takes anything; an href that is not a single route (computed, cast, or\n// off-site) takes anything too, because there is nothing to check it against.\n\n/** What a page module contributes: its `searchParams` export, or nothing. For the generated file. */\nexport type SearchExportOf<M> = M extends { searchParams: infer S }\n ? S\n : undefined;\n\ntype SearchMap = Register extends { search: infer M } ? M : {};\n\ntype StripQuery<H extends string> = H extends `${infer P}?${string}`\n ? P\n : H extends `${infer P}#${string}`\n ? P\n : H;\n\n/** The pattern a written href belongs to: `/posts/hello` is `/posts/[slug]`. */\ntype PatternOf<H extends string> = RoutePattern extends infer P\n ? P extends string\n ? StripQuery<H> extends Filled<P>\n ? P\n : never\n : never\n : never;\n\ntype IsUnion<T, U = T> = T extends unknown\n ? [U] extends [T]\n ? false\n : true\n : never;\n\ntype SchemaFor<P> = P extends keyof SearchMap ? SearchMap[P] : undefined;\n\ntype InputOf<S> = S extends { \"~standard\": { types?: { input: infer I } } }\n ? I\n : never;\ntype OutputOf<S> = S extends { \"~standard\": { types?: { output: infer O } } }\n ? O\n : never;\n\ntype OptionalKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? K : never;\n}[keyof T];\ntype RequiredKeys<T> = Exclude<keyof T, OptionalKeys<T>>;\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/**\n * What a link may write for a schema: the keys the schema's input requires\n * are required, the rest optional, and every value is the schema's OUTPUT\n * type. Output rather than input because `z.coerce.number()` takes `unknown`\n * in - that is what coercion means - and a link typed by it would accept\n * `page: 'two'`. The output is the number the page will actually see.\n */\ntype LinkInputOf<S> = Simplify<\n { [K in RequiredKeys<InputOf<S>> & keyof OutputOf<S>]: OutputOf<S>[K] } & {\n [K in OptionalKeys<InputOf<S>> & keyof OutputOf<S>]?: OutputOf<S>[K];\n }\n>;\n\ntype Scalar = string | number | boolean | null | undefined;\n\n/** What a link may carry when nothing declares otherwise. */\nexport type LooseSearch = Record<string, Scalar | readonly (string | number)[]>;\n\n/**\n * The search params a link to `H` may carry.\n *\n * The page's schema input when `H` is one declared route with a schema;\n * otherwise anything. \"One route\" matters: `path as Route` is every route at\n * once, and a link that could go anywhere cannot be held to one page's schema.\n */\nexport type SearchFor<H extends string> = Unregistered extends true\n ? LooseSearch\n : IsUnion<H> extends true\n ? LooseSearch\n : [PatternOf<H>] extends [never]\n ? LooseSearch\n : SchemaFor<PatternOf<H>> extends undefined\n ? LooseSearch\n : LinkInputOf<SchemaFor<PatternOf<H>>>;\n\n/**\n * The `search` prop, required exactly when the page's schema has a required\n * key. A page that needs `q` is not reachable without one, so the link that\n * omits it is the bug — caught here rather than on the page's error boundary.\n */\nexport type SearchProp<H extends string> =\n {} extends SearchFor<H>\n ? { search?: SearchFor<H> }\n : { search: SearchFor<H> };\n\n/** A query string from an object: scalars stringified, arrays repeated, null and undefined dropped. */\nexport function searchString(search: object): string {\n const params = new URLSearchParams();\n\n for (const [key, value] of Object.entries(search)) {\n if (value === null || value === undefined) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) params.append(key, String(item));\n } else {\n params.set(key, String(value));\n }\n }\n\n return params.toString();\n}\n\n/** `path` with `search` appended, keeping any query and hash already on it. */\nexport function withSearch(path: string, search: object | undefined): string {\n if (!search) return path;\n\n const hashAt = path.indexOf(\"#\");\n const hash = hashAt === -1 ? \"\" : path.slice(hashAt);\n const before = hashAt === -1 ? path : path.slice(0, hashAt);\n const queryAt = before.indexOf(\"?\");\n const base = queryAt === -1 ? before : before.slice(0, queryAt);\n const existing = queryAt === -1 ? \"\" : before.slice(queryAt + 1);\n const added = searchString(search);\n const query = [existing, added].filter(Boolean).join(\"&\");\n\n return query ? `${base}?${query}${hash}` : `${base}${hash}`;\n}\n\n/**\n * A typed url with its search params, for the places that take a string.\n *\n * visit(href('/search', { q: 'shoes', page: 2 }))\n *\n * `Link` has the same check on its own `search` prop. This is for `visit`,\n * `prefetch`, `redirect` and anything else that wants the finished string.\n */\nexport function href<H extends Route>(\n path: H,\n ...rest: {} extends SearchFor<H>\n ? [search?: SearchFor<H>]\n : [search: SearchFor<H>]\n): Route {\n return withSearch(path, rest[0] as object | undefined) as Route;\n}\n\n// ── Another host ─────────────────────────────────────────────────────────────\n//\n// A page under app/merchant is reached as merchant.example.com/orders as well\n// as example.com/merchant/orders, and a page under app/[domain] only from the\n// tenant's own host. A typed `href` names the folder path, which is the second\n// of those - and the first is a host Link cannot know you meant. So the host is\n// said where it is meant, and the path is typed for it.\n\n/** The site's host, from rscKit({ hosts }) or a literal metadataBase, baked in by the build. */\ndeclare const __RSC_SITE_HOST__: string | null | undefined;\n\n/** A top-level folder a url can begin with: `merchant` for app/merchant. */\ntype TopFolder<P> = P extends `/${infer F}/${string}`\n ? F extends `[${string}` ? never : F\n : P extends `/${infer F}`\n ? F extends `[${string}` | \"\" ? never : F\n : never;\n\n/** The patterns under `/${F}`, with the folder taken off: `/merchant/orders` → `/orders`. */\ntype Under<P, F extends string> = P extends `/${F}`\n ? \"/\"\n : P extends `/${F}/${infer R}`\n ? `/${R}`\n : never;\n\n/** A tenant tree's patterns, with the tenant taken off: `/[domain]/settings` → `/settings`. */\ntype TenantPaths<P> = P extends `/[domain]${infer R}` | `/[host]${infer R}`\n ? R extends \"\" ? \"/\" : R\n : never;\n\ntype WithQuery<P extends string> = P | `${P}?${string}` | `${P}#${string}`;\n\n/**\n * What `hostUrl`'s first argument autocompletes to: every top-level folder.\n * Any other string is taken too - a tenant's subdomain, a custom domain.\n */\nexport type HostName = Unregistered extends true ? string : HostFolder | `/${HostFolder}` | (string & {});\n\n/** The top-level folders of the route tree: `merchant` for app/merchant. */\nexport type HostFolder = TopFolder<RoutePattern>;\n\n/**\n * The paths a host answers: for a folder's subdomain the pages under that\n * folder; for anything else the tenant tree's, or any path when there is none.\n */\nexport type HostPath<H extends string> = Unregistered extends true\n ? string\n : H extends HostFolder | `/${HostFolder}`\n ? WithQuery<Filled<Under<RoutePattern, H extends `/${infer F}` ? F : H>>>\n : [TenantPaths<RoutePattern>] extends [never]\n ? `/${string}`\n : WithQuery<Filled<TenantPaths<RoutePattern>>>;\n\n/**\n * A url on another host of the site, for `<Link href>`, `visit()` and\n * `redirect()`:\n *\n * hostUrl('merchant', '/orders') // //merchant.example.com/orders\n * hostUrl('testbrand', '/settings') // //testbrand.example.com/settings - a tenant\n * hostUrl('acme.com', '/settings') // //acme.com/settings - a name with a dot is a whole domain\n * hostUrl('/pricing') // //example.com/pricing - the site itself\n *\n * The folder may be written as its path too: `hostUrl('/merchant', '/orders')`.\n *\n * The site's host is the one rscKit({ hosts }) names first. Where none is\n * named, a folder's url is its path - `/merchant/orders` - as every page is\n * then reached by path; a tenant or a domain still names its host.\n *\n * The same string on the server and in the browser, so a link hydrates as\n * it rendered. On the host it names already, Link navigates without a reload.\n */\nexport function hostUrl(path: Route): Route;\nexport function hostUrl<H extends HostName>(host: H, path: HostPath<H>): Route;\nexport function hostUrl(name: string, path?: string): Route {\n const site = typeof __RSC_SITE_HOST__ === \"string\" ? __RSC_SITE_HOST__ : null;\n\n if (path === undefined) return (site ? `//${site}${name}` : name) as Route;\n\n // '/merchant' is the folder too: the first argument's suggestions include\n // the site's paths, for the one-argument form, and that is the one picked.\n const host = name.startsWith(\"/\") ? name.slice(1) : name;\n\n if (host.includes(\".\")) return `//${host}${path}` as Route;\n if (site) return `//${host}.${site}${path}` as Route;\n\n return `/${host}${path === \"/\" ? \"\" : path.startsWith(\"/?\") || path.startsWith(\"/#\") ? path.slice(1) : path}` as Route;\n}\n"]}
package/dist/vite.js CHANGED
@@ -56,6 +56,25 @@ let clientLibraryImports = [];
56
56
  let nitroPreset = null;
57
57
  /** Set by Nitro's setup of a built server, which asks for the commands before Vite has resolved. */
58
58
  let nitroBuilding = false;
59
+ /**
60
+ * Where Nitro writes this build, from the module's setup. The preset decides
61
+ * it: `.output/server` on node, bun and Workers, a function directory on
62
+ * Vercel (`.vercel/output/functions/__server.func`) and Netlify, `_worker.js`
63
+ * on Cloudflare Pages. What the server reads at runtime goes in `serverDir`,
64
+ * because that is what the platform deploys as the server; what a deploy
65
+ * reads goes in `dir`. Neither is derivable from Vite's client outDir.
66
+ */
67
+ let nitroOutput = null;
68
+ /**
69
+ * Where the build's manifests for a deploy go - rsc-kit.json, edge.json,
70
+ * files.json: Nitro's output directory, unless that is the public one
71
+ * (Cloudflare Pages serves all of `dist`), when they would be published;
72
+ * then `.output/` at the app root, where the docs say they are.
73
+ */
74
+ function deployManifestDir(projectRoot, output) {
75
+ const inside = relative(output.publicDir, output.dir);
76
+ return inside === "" || (!inside.startsWith("..") && !isAbsolute(inside)) ? join(projectRoot, ".output") : output.dir;
77
+ }
59
78
  /** The mode this build bakes in, for the process that runs it. See nodeEnvPlugin. */
60
79
  let builtNodeEnv = "production";
61
80
  /** `src/commands`, read once per build; null until asked. See buildCommands(). */
@@ -7726,6 +7745,11 @@ function clientImportsAudit() {
7726
7745
  },
7727
7746
  };
7728
7747
  }
7748
+ /** `inner` as a path under `outer` - `["/x"]` - or nothing when it is not inside it. */
7749
+ function insideOf(outer, inner) {
7750
+ const path = relative(outer, inner).replace(/\\/g, "/");
7751
+ return path && !path.startsWith("..") && !isAbsolute(path) ? [`/${path}`] : [];
7752
+ }
7729
7753
  /** Whether the app's Nitro exports `nitro/services`: the release candidate on. */
7730
7754
  function nitroHasPublicServices(root) {
7731
7755
  try {
@@ -7992,6 +8016,11 @@ export function rscKit(options = {}) {
7992
8016
  return;
7993
8017
  nitroPreset = nitro.options.preset ?? null;
7994
8018
  nitroBuilding = true;
8019
+ nitroOutput = {
8020
+ dir: nitro.options.output.dir ?? dirname(nitro.options.output.serverDir),
8021
+ serverDir: nitro.options.output.serverDir,
8022
+ publicDir: nitro.options.output.publicDir ?? join(dirname(nitro.options.output.serverDir), "public"),
8023
+ };
7995
8024
  // The commands that did not ask for register() are an entry of the
7996
8025
  // rsc environment that Nitro would leave behind: it bundles the
7997
8026
  // server from the environment's main entry only. Given to it as an
@@ -8069,6 +8098,60 @@ export function rscKit(options = {}) {
8069
8098
  log(`native packages: ${tree.packages.join(", ")} (${tree.files} files) travel inside the binary, written to disk on its first start`);
8070
8099
  });
8071
8100
  }
8101
+ // .output/files.json: what a server in front may answer from disk
8102
+ // before the app runs - see filesManifest.ts. The stored pages a
8103
+ // Workers build copies into the public directory (the hook below)
8104
+ // are read through a binding, never served: left out by name, not
8105
+ // by running first.
8106
+ //
8107
+ // Written to Nitro's output directory - `.output` on node, bun and
8108
+ // Workers, `.vercel/output` on Vercel, `.output` at the app root when
8109
+ // the output directory is the public one (Cloudflare Pages) - never
8110
+ // beside the server bundle, which on some presets is a function
8111
+ // directory. A file's
8112
+ // path is its url: Nitro serves `<publicDir>/x` at `<baseURL>/x`, and
8113
+ // most presets nest the public directory under the base url, so
8114
+ // `root` is that directory with the base taken back off.
8115
+ nitro.hooks.hook("compiled", async () => {
8116
+ const { filesManifest, nitroRouteRules } = await import("./filesManifest.js");
8117
+ const { ASSETS_PREFIX } = await import("./files.js");
8118
+ const publicDir = nitro.options.output.publicDir ?? join(nitro.options.output.dir ?? dirname(nitro.options.output.serverDir), "public");
8119
+ const outputDir = deployManifestDir(projectRoot, { dir: nitro.options.output.dir ?? dirname(nitro.options.output.serverDir), publicDir });
8120
+ const baseURL = (nitro.options.baseURL ?? "/").replace(/\/+$/, "");
8121
+ const publicRoot = baseURL && publicDir.replace(/[\\/]+$/, "").replace(/\\/g, "/").endsWith(baseURL)
8122
+ ? publicDir.replace(/[\\/]+$/, "").slice(0, -baseURL.length)
8123
+ : baseURL ? null : publicDir;
8124
+ const leftOut = [];
8125
+ const manifest = filesManifest(publicRoot === null ? join(outputDir, "-no-files-") : publicDir, nitro.options.routeRules, {
8126
+ root: relative(outputDir, publicRoot ?? publicDir).replace(/\\/g, "/") || ".",
8127
+ exclude: [
8128
+ `/${ASSETS_PREFIX(NITRO_STATIC_DIR)}`,
8129
+ // A platform's own configuration, which it reads and never
8130
+ // serves: Workers and Netlify take `_headers` and `_redirects`
8131
+ // from the public directory, Pages `_routes.json`.
8132
+ "/_headers",
8133
+ "/_redirects",
8134
+ "/_routes.json",
8135
+ "/.assetsignore",
8136
+ // The server itself, where a preset builds it inside the public
8137
+ // directory - Cloudflare Pages' `_worker.js`.
8138
+ ...insideOf(publicDir, nitro.options.output.serverDir),
8139
+ ],
8140
+ baseURL,
8141
+ resolve: await nitroRouteRules(projectRoot, nitro.options.routeRules, baseURL),
8142
+ onLeftOut: (path, why) => leftOut.push(`${path} (${why})`),
8143
+ });
8144
+ // A public directory not under its base url cannot be served by
8145
+ // joining a root and a url path: nothing is listed, and every
8146
+ // request goes to the app.
8147
+ if (publicRoot === null)
8148
+ log(`files.json lists no files: the public directory ${publicDir} is not under the base url ${baseURL}`);
8149
+ if (leftOut.length) {
8150
+ log(`files.json leaves ${leftOut.length} file${leftOut.length === 1 ? "" : "s"} to the app, under route rules a server in front cannot follow: ${leftOut.slice(0, 5).join(", ")}${leftOut.length > 5 ? ", ..." : ""}`);
8151
+ }
8152
+ mkdirSync(outputDir, { recursive: true });
8153
+ writeFileSync(join(outputDir, "files.json"), JSON.stringify(manifest, null, 2) + "\n");
8154
+ });
8072
8155
  // On Workers the stored pages ride the static assets, not the bundle.
8073
8156
  // Copied once Nitro has listed its public files, so the copies are
8074
8157
  // not in that list: a path in it is served as an asset before the
@@ -8121,14 +8204,25 @@ export function rscKit(options = {}) {
8121
8204
  // deploy's list against the new server, every file 404s, and the
8122
8205
  // install fails - leaving the old worker in charge, serving the old
8123
8206
  // documents, for as long as the browser holds the script.
8124
- nitro.options.routeRules = {
8125
- ...(nitro.options.routeRules ?? {}),
8207
+ //
8208
+ // And the other files the build writes under a fixed name: the app's
8209
+ // own worker code the worker imports (src/app/sw.js, served as
8210
+ // /sw-app.js - kept by a heuristic it is the old code inside the new
8211
+ // worker), the web app manifest, and the icons, splash screens and
8212
+ // share images under /_app/, which hold nothing fingerprinted. Each
8213
+ // revalidates; its ETag makes that a 304. The app's own public/ files
8214
+ // are its own to decide. A rule the app set for one of these paths
8215
+ // keeps its headers over these.
8216
+ const revalidate = { "cache-control": "public, max-age=0, must-revalidate" };
8217
+ const rules = (nitro.options.routeRules ?? {});
8218
+ nitro.options.routeRules = { ...rules };
8219
+ for (const path of ["/sw.js", "/sw-app.js", "/manifest.webmanifest", `${ASSET_BASE}/**`]) {
8126
8220
  // Spelled with max-age=0 rather than no-cache: a CDN's browser
8127
8221
  // cache TTL - Cloudflare's, four hours - applies where the origin
8128
8222
  // names no max-age, and rewrote no-cache to max-age=14400; a
8129
8223
  // max-age of zero it leaves alone, as it leaves the documents'.
8130
- "/sw.js": { ...(nitro.options.routeRules?.["/sw.js"] ?? {}), headers: { "cache-control": "public, max-age=0, must-revalidate", ...(nitro.options.routeRules?.["/sw.js"]?.headers ?? {}) } },
8131
- };
8224
+ nitro.options.routeRules[path] = { ...(rules[path] ?? {}), headers: { ...revalidate, ...(rules[path]?.headers ?? {}) } };
8225
+ }
8132
8226
  // The names of functions survive Nitro's bundle. The pages were
8133
8227
  // prerendered against Vite's own server bundles, where a dependency
8134
8228
  // is loaded from node_modules under the names it was written with;
@@ -8787,10 +8881,20 @@ export function rscKit(options = {}) {
8787
8881
  // else exist on the build machine and nowhere after that. They go beside
8788
8882
  // the server bundle instead, and buildApp runs before Nitro assembles, so
8789
8883
  // they are in place by the time it does.
8884
+ //
8885
+ // Beside the server Nitro writes, wherever the preset puts it: a
8886
+ // function directory on Vercel and Netlify is what the platform
8887
+ // deploys, and a path next to it is left on the build machine - every
8888
+ // page then rendered live, with nothing to say so.
8790
8889
  const clientOut = builder?.environments?.client?.config?.build?.outDir;
8791
- const staticDir = clientOut
8792
- ? join(dirname(clientOut), "server", NITRO_STATIC_DIR)
8793
- : join(outDir, NITRO_STATIC_DIR);
8890
+ const staticDir = nitroOutput
8891
+ ? join(nitroOutput.serverDir, NITRO_STATIC_DIR)
8892
+ : clientOut
8893
+ ? join(dirname(clientOut), "server", NITRO_STATIC_DIR)
8894
+ : join(outDir, NITRO_STATIC_DIR);
8895
+ // Where a deploy reads what the build produced: Nitro's output
8896
+ // directory, as for files.json.
8897
+ const manifestDir = nitroOutput ? deployManifestDir(projectRoot, nitroOutput) : clientOut ? dirname(clientOut) : outDir;
8794
8898
  const { frozen, results, shells, routes, pathKey: pathKeyOf, build: clientBuild } = await prerenderAfterBundles(bundle, staticDir, clientOut ?? publicAssetsDir, builder ? knownActionsOf(builder.config, projectRoot) : []);
8795
8899
  // The edge contract's static pages, each given a payload it boots from
8796
8900
  // without the app - before the build id, which hashes the documents
@@ -8864,7 +8968,8 @@ export function rscKit(options = {}) {
8864
8968
  // compute it - or knowing where rsc-kit keeps things inside .output.
8865
8969
  // Written by the code that decided, so it cannot disagree with it.
8866
8970
  if (clientOut) {
8867
- writeFileSync(join(dirname(clientOut), "rsc-kit.json"), JSON.stringify(output === "export"
8971
+ mkdirSync(manifestDir, { recursive: true });
8972
+ writeFileSync(join(manifestDir, "rsc-kit.json"), JSON.stringify(output === "export"
8868
8973
  ? { version: PACKAGE_VERSION, output: "export", dir: relative(projectRoot, exportPath) }
8869
8974
  : {
8870
8975
  version: PACKAGE_VERSION,
@@ -8880,10 +8985,10 @@ export function rscKit(options = {}) {
8880
8985
  // belong to. Written by every server build, with empty lists when
8881
8986
  // there are none, so a platform can tell "none" from "an rsc-kit too
8882
8987
  // old to say". Not by an export, which has no origin to answer for it.
8883
- const markerFile = join(dirname(clientOut), "edge.json");
8988
+ const markerFile = join(manifestDir, "edge.json");
8884
8989
  // v1's marker, from a build before this one: an edge reading it
8885
8990
  // would ask for endpoints that are no longer here.
8886
- rmSync(join(dirname(clientOut), "ppr.json"), { force: true });
8991
+ rmSync(join(manifestDir, "ppr.json"), { force: true });
8887
8992
  if (output !== "export" && marker) {
8888
8993
  writeFileSync(markerFile, JSON.stringify(marker, null, 2) + "\n");
8889
8994
  }