@rsc-kit/core 0.18.1 → 0.19.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.
Files changed (60) hide show
  1. package/dist/action.d.ts +16 -2
  2. package/dist/action.js +21 -12
  3. package/dist/action.js.map +1 -1
  4. package/dist/apiPrerender.js +24 -6
  5. package/dist/apiPrerender.js.map +1 -1
  6. package/dist/clientPackages.d.ts +30 -0
  7. package/dist/clientPackages.js +234 -0
  8. package/dist/clientPackages.js.map +1 -0
  9. package/dist/compress.d.ts +12 -0
  10. package/dist/compress.js +134 -0
  11. package/dist/compress.js.map +1 -0
  12. package/dist/compressRuntime.d.ts +8 -0
  13. package/dist/compressRuntime.js +62 -0
  14. package/dist/compressRuntime.js.map +1 -0
  15. package/dist/files.d.ts +20 -0
  16. package/dist/files.js +38 -0
  17. package/dist/files.js.map +1 -1
  18. package/dist/formSubmit.d.ts +1 -0
  19. package/dist/formSubmit.js +14 -0
  20. package/dist/formSubmit.js.map +1 -0
  21. package/dist/host.d.ts +23 -0
  22. package/dist/host.js +175 -31
  23. package/dist/host.js.map +1 -1
  24. package/dist/hostCalls.d.ts +15 -0
  25. package/dist/hostCalls.js +75 -8
  26. package/dist/hostCalls.js.map +1 -1
  27. package/dist/js/Form.d.ts +19 -2
  28. package/dist/js/Form.js +110 -83
  29. package/dist/js/Form.js.map +1 -1
  30. package/dist/js/createViteRscApp.d.ts +1 -0
  31. package/dist/js/createViteRscApp.js +34 -5
  32. package/dist/js/createViteRscApp.js.map +1 -1
  33. package/dist/js/errors.d.ts +3 -1
  34. package/dist/js/errors.js +26 -3
  35. package/dist/js/errors.js.map +1 -1
  36. package/dist/js/formEncoding.d.ts +72 -3
  37. package/dist/js/formEncoding.js +284 -20
  38. package/dist/js/formEncoding.js.map +1 -1
  39. package/dist/js/navigate.d.ts +3 -0
  40. package/dist/js/navigate.js +56 -6
  41. package/dist/js/navigate.js.map +1 -1
  42. package/dist/js/updateStore.js +8 -2
  43. package/dist/js/updateStore.js.map +1 -1
  44. package/dist/openapi.d.ts +74 -0
  45. package/dist/openapi.js +172 -0
  46. package/dist/openapi.js.map +1 -0
  47. package/dist/redirect.d.ts +2 -2
  48. package/dist/redirect.js.map +1 -1
  49. package/dist/request.d.ts +56 -2
  50. package/dist/request.js +68 -4
  51. package/dist/request.js.map +1 -1
  52. package/dist/routes.d.ts +15 -1
  53. package/dist/routes.js.map +1 -1
  54. package/dist/testing.d.ts +14 -0
  55. package/dist/testing.js +56 -2
  56. package/dist/testing.js.map +1 -1
  57. package/dist/vite.d.ts +69 -1
  58. package/dist/vite.js +451 -45
  59. package/dist/vite.js.map +1 -1
  60. package/package.json +5 -1
package/dist/action.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type StandardSchemaV1 } from './js/standardSchema.js';
2
2
  import { type QueryOptions } from './query.js';
3
- /** What an action answers with. Exactly one of the three is set. */
3
+ /** What an action answers with. Exactly one of the four is set. */
4
4
  export interface ActionResult<Data> {
5
5
  /** What the handler returned. */
6
6
  data?: Data;
@@ -8,6 +8,12 @@ export interface ActionResult<Data> {
8
8
  validationErrors?: Record<string, string[]>;
9
9
  /** Something else went wrong, reduced to a message the browser may see. */
10
10
  serverError?: string;
11
+ /**
12
+ * Where the action sent the visitor. Set by the client, which has already
13
+ * started the navigation: the page is on its way there, and there is
14
+ * nothing for the caller to do. Never set on the server side of the call.
15
+ */
16
+ redirected?: string;
11
17
  }
12
18
  /**
13
19
  * A middleware that neither continued nor refused.
@@ -105,7 +111,15 @@ export interface ActionBuilder<Ctx extends Record<string, unknown>, Input> {
105
111
  }) => Promise<MiddlewareResult<Extra>>): ActionBuilder<Ctx & Extra, Input>;
106
112
  /** Parse and check what the caller sent. The handler's `input` follows. */
107
113
  input<S extends StandardSchemaV1>(schema: S): ActionBuilder<Ctx, Output<S>>;
108
- /** The body. */
114
+ /**
115
+ * The body.
116
+ *
117
+ * What the caller gets is always the result object: `data`, or a
118
+ * refusal, or - when the action redirected - `redirected`, set by the
119
+ * client once the navigation is under way. Always an object, so a caller
120
+ * reading `result.validationErrors` after a redirect reads undefined and
121
+ * not a TypeError inside a transition, which unmounts the root.
122
+ */
109
123
  handler<Data>(fn: (args: HandlerArgs<Input, Ctx>) => Promise<Data> | Data): (input?: unknown) => Promise<ActionResult<Data>>;
110
124
  /**
111
125
  * The body of a READ, sharing this client's middleware and schema.
package/dist/action.js CHANGED
@@ -20,7 +20,9 @@
20
20
  // page may render. This wraps one action. They are different questions: an
21
21
  // action is reachable without any page, which is why it defends itself.
22
22
  import { validateWith } from './js/standardSchema.js';
23
+ import { decodeFormData } from './js/formEncoding.js';
23
24
  import { markQuery, QueryValidationError } from './query.js';
25
+ import { isRedirectSignal } from './redirectDigest.js';
24
26
  /**
25
27
  * A middleware that neither continued nor refused.
26
28
  *
@@ -98,17 +100,16 @@ export function fieldErrors(errors) {
98
100
  throw new ActionValidationError(normalised);
99
101
  }
100
102
  const GENERIC = 'Something went wrong.';
101
- /** FormData in, a plain object out — what a schema expects to be handed. */
102
- function fromFormData(body) {
103
- const out = {};
104
- for (const key of new Set(body.keys())) {
105
- const values = body.getAll(key);
106
- // One value stays a value. Several stay several — a multi-select that
107
- // collapsed to its last entry would be a silent data loss.
108
- out[key] = values.length > 1 ? values : values[0];
109
- }
110
- return out;
111
- }
103
+ /**
104
+ * FormData in, a plain object out — what a schema expects to be handed.
105
+ *
106
+ * The form's own decoder, so the object validated here is the object the
107
+ * browser validated. This had a flat decoder of its own: `items[0].name`
108
+ * stayed a key spelled exactly that, `<Form>` had already parsed it into an
109
+ * array, and a nested form passed in the browser and failed on the server
110
+ * with the fields it named gone.
111
+ */
112
+ const fromFormData = (body, schema) => decodeFormData(body, schema);
112
113
  export function createActionClient(options = {}) {
113
114
  const report = options.onError ?? (() => GENERIC);
114
115
  function build(middlewares, schema) {
@@ -121,7 +122,7 @@ export function createActionClient(options = {}) {
121
122
  * that should look like from the outside.
122
123
  */
123
124
  const pipeline = async (raw, fn) => {
124
- const value = raw instanceof FormData ? fromFormData(raw) : raw;
125
+ const value = raw instanceof FormData ? fromFormData(raw, schema) : raw;
125
126
  if (schema) {
126
127
  const invalid = await validateWith(schema, value);
127
128
  if (invalid)
@@ -181,6 +182,12 @@ export function createActionClient(options = {}) {
181
182
  // Past onError deliberately — see ActionMisuse.
182
183
  if (error instanceof ActionMisuse)
183
184
  throw error;
185
+ // A redirect is an instruction, not a failure: it has to reach
186
+ // the host, which answers the action with the destination. Caught
187
+ // here it became { serverError: 'Something went wrong.' } - a
188
+ // login that succeeded and then showed an error.
189
+ if (isRedirectSignal(error))
190
+ throw error;
184
191
  if (isActionValidationError(error)) {
185
192
  return { validationErrors: error.errors };
186
193
  }
@@ -196,6 +203,8 @@ export function createActionClient(options = {}) {
196
203
  catch (error) {
197
204
  if (error instanceof ActionMisuse)
198
205
  throw error;
206
+ if (isRedirectSignal(error))
207
+ throw error;
199
208
  // Thrown, not returned. A cache library reports failure by
200
209
  // rejection, so a query that answered with an error-shaped object
201
210
  // would look like a successful read of something odd.
@@ -1 +1 @@
1
- {"version":3,"file":"action.js","sourceRoot":"","sources":["../src/action.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,EAAE;AACF,oEAAoE;AACpE,EAAE;AACF,uCAAuC;AACvC,+EAA+E;AAC/E,uDAAuD;AACvD,+EAA+E;AAC/E,EAAE;AACF,gFAAgF;AAChF,+EAA+E;AAC/E,EAAE;AACF,+EAA+E;AAC/E,2EAA2E;AAC3E,6EAA6E;AAC7E,+EAA+E;AAC/E,uDAAuD;AACvD,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,wEAAwE;AAExE,OAAO,EAAE,YAAY,EAAyB,MAAM,wBAAwB,CAAA;AAC5E,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAqB,MAAM,YAAY,CAAA;AAY/E;;;;;;;GAOG;AACH,MAAM,OAAO,YAAa,SAAQ,KAAK;IACrC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO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4BACnC,MAAM,IAAI,oBAAoB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;wBAC9C,CAAC;wBAED,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAA;oBAChC,CAAC;gBACH,CAAC,CAAA;gBAED,OAAO,eAAe,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,CAAwC,CAAA;YACzF,CAAC;SACF,CAAA;IACH,CAAC;IAED,OAAO,KAAK,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;AACxB,CAAC","sourcesContent":["// Server actions with a schema, middleware, and types that follow from both.\n//\n// export const action = createActionClient({ onError: report })\n//\n// export const createPost = action\n// .use(async ({ next }) => next({ ctx: { user: await currentUser() } }))\n// .input(z.object({ title: z.string().min(3) }))\n// .handler(async ({ input, ctx }) => savePost(ctx.user.id, input.title))\n//\n// `input` is typed from the schema and `ctx` from every middleware that ran, so\n// the handler is checked against both without either being written down twice.\n//\n// The built action RETURNS its failures rather than throwing them, and that is\n// not a style choice. React serialises a rejected server action opaquely —\n// production strips the message and leaves a digest — so a thrown validation\n// error reaches the browser as \"an error occurred\" and the fields it named are\n// gone. A returned object crosses the boundary intact.\n//\n// Distinct from `middleware.ts` in a route directory, which decides whether a\n// page may render. This wraps one action. They are different questions: an\n// action is reachable without any page, which is why it defends itself.\n\nimport { validateWith, type StandardSchemaV1 } from './js/standardSchema.js'\nimport { markQuery, QueryValidationError, type QueryOptions } from './query.js'\n\n/** What an action answers with. Exactly one of the three is set. */\nexport interface ActionResult<Data> {\n /** What the handler returned. */\n data?: Data\n /** Field name to messages, in the shape a form already renders. */\n validationErrors?: Record<string, string[]>\n /** Something else went wrong, reduced to a message the browser may see. */\n serverError?: string\n}\n\n/**\n * A middleware that neither continued nor refused.\n *\n * Never reported through `onError`: that reduces an error to a message for the\n * browser, and this one is for whoever wrote the middleware. A check that\n * forgot to call `next()` would otherwise look exactly like a check that\n * passed.\n */\nexport class ActionMisuse extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ActionMisuse'\n }\n}\n\n/** Refuse from inside a handler, naming the fields. */\n/**\n * Marks a refusal so it survives a bundle seam.\n *\n * A property rather than `instanceof`, for the reason this project keeps\n * running into: an app's actions are bundled separately from the engine, so\n * each gets its own copy of this module and its own copy of the class.\n * `instanceof` compares identity across that seam and is simply false — and\n * the refusal is then reported as a server error, so the form shows \"Something\n * went wrong\" instead of naming the fields. Everything works; nothing logs.\n *\n * Symbol.for, so the two copies agree on the key as well as the value.\n */\nconst VALIDATION_MARK = Symbol.for('@rsc-kit/core.action-validation')\n\n/**\n * Set on every function a client builds, so the build can tell them from a\n * bare \"use server\" export. The difference is the middleware: a bare export\n * runs with nothing checking who called it, and nothing else in the app\n * would ever say so. Symbol.for, because the build reads the mark from the\n * bundled copy of this module and the app's actions were built by another.\n */\nconst CLIENT_MARK = Symbol.for('@rsc-kit/core.action-client')\n\n/** Whether a server action was built by createActionClient, and so ran its chain. */\nexport function isClientBuilt(fn: unknown): boolean {\n return typeof fn === 'function' && (fn as unknown as Record<symbol, unknown>)[CLIENT_MARK] === true\n}\n\nfunction markClientBuilt<F extends Function>(fn: F): F {\n Object.defineProperty(fn, CLIENT_MARK, { value: true })\n\n return fn\n}\n\nexport class ActionValidationError extends Error {\n public readonly errors: Record<string, string[]>\n\n constructor(errors: Record<string, string[]>) {\n super('Validation failed')\n this.name = 'ActionValidationError'\n this.errors = errors\n ;(this as unknown as Record<symbol, boolean>)[VALIDATION_MARK] = true\n }\n}\n\n/** Whether this is a refusal, whichever copy of the class built it. */\nexport function isActionValidationError(error: unknown): error is ActionValidationError {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as Record<symbol, unknown>)[VALIDATION_MARK] === true\n )\n}\n\n/**\n * The field errors a handler may report, keyed by its own input's fields.\n *\n * `''` is the whole submission — for a refusal that is about no field in\n * particular, which is where the form already looks for one.\n */\nexport type FieldErrorsFor<Input> = Partial<\n Record<(Input extends object ? keyof Input & string : string) | '', string | string[]>\n>\n\n/**\n * What a handler is given.\n *\n * `fieldErrors` is here as well as exported on its own, and the one here is\n * the one to use: it is typed to this handler's input, so a field the schema\n * does not have is a type error rather than an error the form never shows.\n * The bare export takes any string, for the rare check that runs outside a\n * handler.\n */\nexport interface HandlerArgs<Input, Ctx> {\n input: Input\n ctx: Ctx\n /**\n * Fail with errors on this input's fields. Throws; nothing after it runs.\n *\n * Write `return fieldErrors(...)`. It throws either way, but TypeScript does\n * not treat a never-return as terminating when the callee is a destructured\n * binding — only a declaration or an explicitly annotated variable — so\n * without the return, a value checked on the line above is still possibly\n * undefined on the line below. The return is what lets the type narrow.\n */\n fieldErrors: (errors: FieldErrorsFor<Input>) => never\n}\n\n/**\n * Fail with field errors the form can show.\n *\n * For what a schema cannot know — a name already taken, a balance too low.\n * Throws, so the handler stops where it is; the action turns it into a\n * returned result on the way out.\n *\n * Untyped by field, because it has no handler to take the input from. Inside\n * one, use the `fieldErrors` the handler is given instead.\n */\nexport function fieldErrors(errors: Record<string, string[] | string>): never {\n const normalised: Record<string, string[]> = {}\n\n for (const [field, message] of Object.entries(errors)) {\n normalised[field] = Array.isArray(message) ? message : [message]\n }\n\n throw new ActionValidationError(normalised)\n}\n\n/**\n * What `next()` hands back, carrying what the step added.\n *\n * The context a middleware contributes cannot be inferred from the arguments\n * it passes to `next` — TypeScript infers from a function's return, not from a\n * call inside it. So `next` returns this, the middleware returns it, and the\n * addition is read off the middleware's own return type.\n */\nexport interface MiddlewareResult<Extra> {\n readonly ctx: Extra\n readonly value: unknown\n}\n\n/**\n * A step that runs before the handler.\n *\n * It calls `next` to continue, optionally adding to the context, and what it\n * adds shows up in the handler's types. Returning without calling `next` — or\n * throwing — stops the action, which is how a check refuses.\n */\nexport type ActionMiddleware<Ctx, Extra extends Record<string, unknown>> = (args: {\n ctx: Ctx\n next: <E extends Record<string, unknown> = Record<string, never>>(\n opts?: { ctx?: E },\n ) => Promise<MiddlewareResult<E>>\n}) => Promise<MiddlewareResult<Extra>>\n\ntype Output<S> = S extends StandardSchemaV1<unknown, infer O> ? O : never\n\nexport interface ActionBuilder<Ctx extends Record<string, unknown>, Input> {\n /** Add a step, and whatever context it contributes. */\n use<Extra extends Record<string, unknown> = Record<string, never>>(\n middleware: (args: {\n ctx: Ctx\n next: <E extends Record<string, unknown> = Record<string, never>>(\n opts?: { ctx?: E },\n ) => Promise<MiddlewareResult<E>>\n }) => Promise<MiddlewareResult<Extra>>,\n ): ActionBuilder<Ctx & Extra, Input>\n /** Parse and check what the caller sent. The handler's `input` follows. */\n input<S extends StandardSchemaV1>(schema: S): ActionBuilder<Ctx, Output<S>>\n /** The body. */\n handler<Data>(\n fn: (args: HandlerArgs<Input, Ctx>) => Promise<Data> | Data,\n ): (input?: unknown) => Promise<ActionResult<Data>>\n /**\n * The body of a READ, sharing this client's middleware and schema.\n *\n * export const getPosts = client.input(filter).query(async ({ input, ctx }) =>\n * db.posts(ctx.user.id, input))\n *\n * The same builder as `handler`, and deliberately so: an app configures its\n * auth check and its error reporting once, and both a mutation and a read go\n * through them.\n *\n * It fails differently, though, and that is not an oversight. An action\n * RETURNS its failures because React serialises a rejection opaquely. A query\n * is handed to a cache library as a fetcher, and every one of them reports\n * failure by rejection — so this returns the data directly and throws, and\n * the endpoint carries the message across for it.\n */\n query<Data>(\n fn: (args: { input: Input; ctx: Ctx }) => Promise<Data> | Data,\n options?: QueryOptions,\n ): (input?: unknown) => Promise<Data>\n}\n\nexport interface ActionClientOptions {\n /**\n * What the browser is told when something unexpected throws.\n *\n * Everything reaching here is a bug or an outage, and its message may say\n * more than a stranger should see — a query, a path, a host. Returning a\n * fixed string is the safe default; return the message only for errors you\n * raised deliberately.\n */\n onError?: (error: unknown) => string\n}\n\nconst GENERIC = 'Something went wrong.'\n\n/** FormData in, a plain object out — what a schema expects to be handed. */\nfunction fromFormData(body: FormData): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n\n for (const key of new Set(body.keys())) {\n const values = body.getAll(key)\n\n // One value stays a value. Several stay several — a multi-select that\n // collapsed to its last entry would be a silent data loss.\n out[key] = values.length > 1 ? values : values[0]\n }\n\n return out\n}\n\nexport function createActionClient(\n options: ActionClientOptions = {},\n): ActionBuilder<Record<never, never>, undefined> {\n const report = options.onError ?? (() => GENERIC)\n\n function build<Ctx extends Record<string, unknown>, Input>(\n middlewares: ActionMiddleware<never, never>[],\n schema: StandardSchemaV1 | null,\n ): ActionBuilder<Ctx, Input> {\n /**\n * Validate, run the chain, call the body.\n *\n * Shared by both terminals, which is the point of putting a read on this\n * builder at all: one set of middleware, one schema, one place the auth\n * check lives. Refusals leave by throwing, and each terminal decides what\n * that should look like from the outside.\n */\n const pipeline = async (\n raw: unknown,\n fn: (args: HandlerArgs<never, never>) => unknown,\n ): Promise<unknown> => {\n const value = raw instanceof FormData ? fromFormData(raw) : raw\n\n if (schema) {\n const invalid = await validateWith(schema, value)\n\n if (invalid) throw new ActionValidationError(invalid)\n }\n\n const parsed = schema\n ? ((await schema['~standard'].validate(value)).value as Input)\n : (value as Input)\n\n // Composed inside-out so the first `use` is the outermost — it sees the\n // others run, which is what makes timing and cleanup possible rather\n // than only checks.\n let ctx = {} as Ctx\n let index = 0\n\n const run = async (): Promise<unknown> => {\n const middleware = middlewares[index++]\n\n if (!middleware) {\n return await fn({\n input: parsed as never,\n ctx: ctx as never,\n // The same function as the export; the type on the way in is what\n // is different, and the type is the handler's input.\n fieldErrors: fieldErrors as never,\n })\n }\n\n let continued = false\n\n const result = await (middleware as unknown as ActionMiddleware<Ctx, Record<string, unknown>>)({\n ctx,\n next: (async (opts?: { ctx?: Record<string, unknown> }) => {\n continued = true\n ctx = { ...ctx, ...(opts?.ctx ?? {}) } as Ctx\n\n return { ctx, value: await run() }\n }) as never,\n })\n\n // Silence is not refusal. A middleware that neither called next() nor\n // threw has done nothing, and guessing which it meant turns a\n // forgotten `return` into a check that quietly passes.\n if (!continued) {\n throw new ActionMisuse(\n 'A middleware returned without calling next(). Call it to continue, or throw to refuse.',\n )\n }\n\n return (result as { value?: unknown })?.value\n }\n\n return await run()\n }\n\n return {\n use(middleware) {\n return build([...middlewares, middleware as never], schema) as never\n },\n input(next) {\n return build(middlewares, next) as never\n },\n handler(fn) {\n return markClientBuilt(async (raw?: unknown) => {\n try {\n return { data: (await pipeline(raw, fn)) as Awaited<ReturnType<typeof fn>> }\n } catch (error) {\n // Past onError deliberately — see ActionMisuse.\n if (error instanceof ActionMisuse) throw error\n\n if (isActionValidationError(error)) {\n return { validationErrors: error.errors }\n }\n\n return { serverError: report(error) }\n }\n })\n },\n query(fn, options) {\n const read = async (raw?: unknown) => {\n try {\n return await pipeline(raw, fn)\n } catch (error) {\n if (error instanceof ActionMisuse) throw error\n\n // Thrown, not returned. A cache library reports failure by\n // rejection, so a query that answered with an error-shaped object\n // would look like a successful read of something odd.\n if (isActionValidationError(error)) {\n throw new QueryValidationError(error.errors)\n }\n\n throw new Error(report(error))\n }\n }\n\n return markClientBuilt(markQuery(read, options)) as (input?: unknown) => Promise<never>\n },\n }\n }\n\n return build([], null)\n}\n"]}
1
+ {"version":3,"file":"action.js","sourceRoot":"","sources":["../src/action.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,EAAE;AACF,oEAAoE;AACpE,EAAE;AACF,uCAAuC;AACvC,+EAA+E;AAC/E,uDAAuD;AACvD,+EAA+E;AAC/E,EAAE;AACF,gFAAgF;AAChF,+EAA+E;AAC/E,EAAE;AACF,+EAA+E;AAC/E,2EAA2E;AAC3E,6EAA6E;AAC7E,+EAA+E;AAC/E,uDAAuD;AACvD,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,wEAAwE;AAExE,OAAO,EAAE,YAAY,EAAyB,MAAM,wBAAwB,CAAA;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AACrD,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAqB,MAAM,YAAY,CAAA;AAC/E,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAA;AAkBtD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CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;wBAC9C,CAAC;wBAED,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAA;oBAChC,CAAC;gBACH,CAAC,CAAA;gBAED,OAAO,eAAe,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,CAAwC,CAAA;YACzF,CAAC;SACF,CAAA;IACH,CAAC;IAED,OAAO,KAAK,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;AACxB,CAAC","sourcesContent":["// Server actions with a schema, middleware, and types that follow from both.\n//\n// export const action = createActionClient({ onError: report })\n//\n// export const createPost = action\n// .use(async ({ next }) => next({ ctx: { user: await currentUser() } }))\n// .input(z.object({ title: z.string().min(3) }))\n// .handler(async ({ input, ctx }) => savePost(ctx.user.id, input.title))\n//\n// `input` is typed from the schema and `ctx` from every middleware that ran, so\n// the handler is checked against both without either being written down twice.\n//\n// The built action RETURNS its failures rather than throwing them, and that is\n// not a style choice. React serialises a rejected server action opaquely —\n// production strips the message and leaves a digest — so a thrown validation\n// error reaches the browser as \"an error occurred\" and the fields it named are\n// gone. A returned object crosses the boundary intact.\n//\n// Distinct from `middleware.ts` in a route directory, which decides whether a\n// page may render. This wraps one action. They are different questions: an\n// action is reachable without any page, which is why it defends itself.\n\nimport { validateWith, type StandardSchemaV1 } from './js/standardSchema.js'\nimport { decodeFormData } from './js/formEncoding.js'\nimport { markQuery, QueryValidationError, type QueryOptions } from './query.js'\nimport { isRedirectSignal } from './redirectDigest.js'\n\n/** What an action answers with. Exactly one of the four is set. */\nexport interface ActionResult<Data> {\n /** What the handler returned. */\n data?: Data\n /** Field name to messages, in the shape a form already renders. */\n validationErrors?: Record<string, string[]>\n /** Something else went wrong, reduced to a message the browser may see. */\n serverError?: string\n /**\n * Where the action sent the visitor. Set by the client, which has already\n * started the navigation: the page is on its way there, and there is\n * nothing for the caller to do. Never set on the server side of the call.\n */\n redirected?: string\n}\n\n/**\n * A middleware that neither continued nor refused.\n *\n * Never reported through `onError`: that reduces an error to a message for the\n * browser, and this one is for whoever wrote the middleware. A check that\n * forgot to call `next()` would otherwise look exactly like a check that\n * passed.\n */\nexport class ActionMisuse extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ActionMisuse'\n }\n}\n\n/** Refuse from inside a handler, naming the fields. */\n/**\n * Marks a refusal so it survives a bundle seam.\n *\n * A property rather than `instanceof`, for the reason this project keeps\n * running into: an app's actions are bundled separately from the engine, so\n * each gets its own copy of this module and its own copy of the class.\n * `instanceof` compares identity across that seam and is simply false — and\n * the refusal is then reported as a server error, so the form shows \"Something\n * went wrong\" instead of naming the fields. Everything works; nothing logs.\n *\n * Symbol.for, so the two copies agree on the key as well as the value.\n */\nconst VALIDATION_MARK = Symbol.for('@rsc-kit/core.action-validation')\n\n/**\n * Set on every function a client builds, so the build can tell them from a\n * bare \"use server\" export. The difference is the middleware: a bare export\n * runs with nothing checking who called it, and nothing else in the app\n * would ever say so. Symbol.for, because the build reads the mark from the\n * bundled copy of this module and the app's actions were built by another.\n */\nconst CLIENT_MARK = Symbol.for('@rsc-kit/core.action-client')\n\n/** Whether a server action was built by createActionClient, and so ran its chain. */\nexport function isClientBuilt(fn: unknown): boolean {\n return typeof fn === 'function' && (fn as unknown as Record<symbol, unknown>)[CLIENT_MARK] === true\n}\n\nfunction markClientBuilt<F extends Function>(fn: F): F {\n Object.defineProperty(fn, CLIENT_MARK, { value: true })\n\n return fn\n}\n\nexport class ActionValidationError extends Error {\n public readonly errors: Record<string, string[]>\n\n constructor(errors: Record<string, string[]>) {\n super('Validation failed')\n this.name = 'ActionValidationError'\n this.errors = errors\n ;(this as unknown as Record<symbol, boolean>)[VALIDATION_MARK] = true\n }\n}\n\n/** Whether this is a refusal, whichever copy of the class built it. */\nexport function isActionValidationError(error: unknown): error is ActionValidationError {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as Record<symbol, unknown>)[VALIDATION_MARK] === true\n )\n}\n\n/**\n * The field errors a handler may report, keyed by its own input's fields.\n *\n * `''` is the whole submission — for a refusal that is about no field in\n * particular, which is where the form already looks for one.\n */\nexport type FieldErrorsFor<Input> = Partial<\n Record<(Input extends object ? keyof Input & string : string) | '', string | string[]>\n>\n\n/**\n * What a handler is given.\n *\n * `fieldErrors` is here as well as exported on its own, and the one here is\n * the one to use: it is typed to this handler's input, so a field the schema\n * does not have is a type error rather than an error the form never shows.\n * The bare export takes any string, for the rare check that runs outside a\n * handler.\n */\nexport interface HandlerArgs<Input, Ctx> {\n input: Input\n ctx: Ctx\n /**\n * Fail with errors on this input's fields. Throws; nothing after it runs.\n *\n * Write `return fieldErrors(...)`. It throws either way, but TypeScript does\n * not treat a never-return as terminating when the callee is a destructured\n * binding — only a declaration or an explicitly annotated variable — so\n * without the return, a value checked on the line above is still possibly\n * undefined on the line below. The return is what lets the type narrow.\n */\n fieldErrors: (errors: FieldErrorsFor<Input>) => never\n}\n\n/**\n * Fail with field errors the form can show.\n *\n * For what a schema cannot know — a name already taken, a balance too low.\n * Throws, so the handler stops where it is; the action turns it into a\n * returned result on the way out.\n *\n * Untyped by field, because it has no handler to take the input from. Inside\n * one, use the `fieldErrors` the handler is given instead.\n */\nexport function fieldErrors(errors: Record<string, string[] | string>): never {\n const normalised: Record<string, string[]> = {}\n\n for (const [field, message] of Object.entries(errors)) {\n normalised[field] = Array.isArray(message) ? message : [message]\n }\n\n throw new ActionValidationError(normalised)\n}\n\n/**\n * What `next()` hands back, carrying what the step added.\n *\n * The context a middleware contributes cannot be inferred from the arguments\n * it passes to `next` — TypeScript infers from a function's return, not from a\n * call inside it. So `next` returns this, the middleware returns it, and the\n * addition is read off the middleware's own return type.\n */\nexport interface MiddlewareResult<Extra> {\n readonly ctx: Extra\n readonly value: unknown\n}\n\n/**\n * A step that runs before the handler.\n *\n * It calls `next` to continue, optionally adding to the context, and what it\n * adds shows up in the handler's types. Returning without calling `next` — or\n * throwing — stops the action, which is how a check refuses.\n */\nexport type ActionMiddleware<Ctx, Extra extends Record<string, unknown>> = (args: {\n ctx: Ctx\n next: <E extends Record<string, unknown> = Record<string, never>>(\n opts?: { ctx?: E },\n ) => Promise<MiddlewareResult<E>>\n}) => Promise<MiddlewareResult<Extra>>\n\ntype Output<S> = S extends StandardSchemaV1<unknown, infer O> ? O : never\n\nexport interface ActionBuilder<Ctx extends Record<string, unknown>, Input> {\n /** Add a step, and whatever context it contributes. */\n use<Extra extends Record<string, unknown> = Record<string, never>>(\n middleware: (args: {\n ctx: Ctx\n next: <E extends Record<string, unknown> = Record<string, never>>(\n opts?: { ctx?: E },\n ) => Promise<MiddlewareResult<E>>\n }) => Promise<MiddlewareResult<Extra>>,\n ): ActionBuilder<Ctx & Extra, Input>\n /** Parse and check what the caller sent. The handler's `input` follows. */\n input<S extends StandardSchemaV1>(schema: S): ActionBuilder<Ctx, Output<S>>\n /**\n * The body.\n *\n * What the caller gets is always the result object: `data`, or a\n * refusal, or - when the action redirected - `redirected`, set by the\n * client once the navigation is under way. Always an object, so a caller\n * reading `result.validationErrors` after a redirect reads undefined and\n * not a TypeError inside a transition, which unmounts the root.\n */\n handler<Data>(\n fn: (args: HandlerArgs<Input, Ctx>) => Promise<Data> | Data,\n ): (input?: unknown) => Promise<ActionResult<Data>>\n /**\n * The body of a READ, sharing this client's middleware and schema.\n *\n * export const getPosts = client.input(filter).query(async ({ input, ctx }) =>\n * db.posts(ctx.user.id, input))\n *\n * The same builder as `handler`, and deliberately so: an app configures its\n * auth check and its error reporting once, and both a mutation and a read go\n * through them.\n *\n * It fails differently, though, and that is not an oversight. An action\n * RETURNS its failures because React serialises a rejection opaquely. A query\n * is handed to a cache library as a fetcher, and every one of them reports\n * failure by rejection — so this returns the data directly and throws, and\n * the endpoint carries the message across for it.\n */\n query<Data>(\n fn: (args: { input: Input; ctx: Ctx }) => Promise<Data> | Data,\n options?: QueryOptions,\n ): (input?: unknown) => Promise<Data>\n}\n\nexport interface ActionClientOptions {\n /**\n * What the browser is told when something unexpected throws.\n *\n * Everything reaching here is a bug or an outage, and its message may say\n * more than a stranger should see — a query, a path, a host. Returning a\n * fixed string is the safe default; return the message only for errors you\n * raised deliberately.\n */\n onError?: (error: unknown) => string\n}\n\nconst GENERIC = 'Something went wrong.'\n\n/**\n * FormData in, a plain object out — what a schema expects to be handed.\n *\n * The form's own decoder, so the object validated here is the object the\n * browser validated. This had a flat decoder of its own: `items[0].name`\n * stayed a key spelled exactly that, `<Form>` had already parsed it into an\n * array, and a nested form passed in the browser and failed on the server\n * with the fields it named gone.\n */\nconst fromFormData = (body: FormData, schema: unknown): Record<string, unknown> => decodeFormData(body, schema)\n\nexport function createActionClient(\n options: ActionClientOptions = {},\n): ActionBuilder<Record<never, never>, undefined> {\n const report = options.onError ?? (() => GENERIC)\n\n function build<Ctx extends Record<string, unknown>, Input>(\n middlewares: ActionMiddleware<never, never>[],\n schema: StandardSchemaV1 | null,\n ): ActionBuilder<Ctx, Input> {\n /**\n * Validate, run the chain, call the body.\n *\n * Shared by both terminals, which is the point of putting a read on this\n * builder at all: one set of middleware, one schema, one place the auth\n * check lives. Refusals leave by throwing, and each terminal decides what\n * that should look like from the outside.\n */\n const pipeline = async (\n raw: unknown,\n fn: (args: HandlerArgs<never, never>) => unknown,\n ): Promise<unknown> => {\n const value = raw instanceof FormData ? fromFormData(raw, schema) : raw\n\n if (schema) {\n const invalid = await validateWith(schema, value)\n\n if (invalid) throw new ActionValidationError(invalid)\n }\n\n const parsed = schema\n ? ((await schema['~standard'].validate(value)).value as Input)\n : (value as Input)\n\n // Composed inside-out so the first `use` is the outermost — it sees the\n // others run, which is what makes timing and cleanup possible rather\n // than only checks.\n let ctx = {} as Ctx\n let index = 0\n\n const run = async (): Promise<unknown> => {\n const middleware = middlewares[index++]\n\n if (!middleware) {\n return await fn({\n input: parsed as never,\n ctx: ctx as never,\n // The same function as the export; the type on the way in is what\n // is different, and the type is the handler's input.\n fieldErrors: fieldErrors as never,\n })\n }\n\n let continued = false\n\n const result = await (middleware as unknown as ActionMiddleware<Ctx, Record<string, unknown>>)({\n ctx,\n next: (async (opts?: { ctx?: Record<string, unknown> }) => {\n continued = true\n ctx = { ...ctx, ...(opts?.ctx ?? {}) } as Ctx\n\n return { ctx, value: await run() }\n }) as never,\n })\n\n // Silence is not refusal. A middleware that neither called next() nor\n // threw has done nothing, and guessing which it meant turns a\n // forgotten `return` into a check that quietly passes.\n if (!continued) {\n throw new ActionMisuse(\n 'A middleware returned without calling next(). Call it to continue, or throw to refuse.',\n )\n }\n\n return (result as { value?: unknown })?.value\n }\n\n return await run()\n }\n\n return {\n use(middleware) {\n return build([...middlewares, middleware as never], schema) as never\n },\n input(next) {\n return build(middlewares, next) as never\n },\n handler(fn) {\n return markClientBuilt(async (raw?: unknown) => {\n try {\n return { data: (await pipeline(raw, fn)) as Awaited<ReturnType<typeof fn>> }\n } catch (error) {\n // Past onError deliberately — see ActionMisuse.\n if (error instanceof ActionMisuse) throw error\n\n // A redirect is an instruction, not a failure: it has to reach\n // the host, which answers the action with the destination. Caught\n // here it became { serverError: 'Something went wrong.' } - a\n // login that succeeded and then showed an error.\n if (isRedirectSignal(error)) throw error\n\n if (isActionValidationError(error)) {\n return { validationErrors: error.errors }\n }\n\n return { serverError: report(error) }\n }\n })\n },\n query(fn, options) {\n const read = async (raw?: unknown) => {\n try {\n return await pipeline(raw, fn)\n } catch (error) {\n if (error instanceof ActionMisuse) throw error\n if (isRedirectSignal(error)) throw error\n\n // Thrown, not returned. A cache library reports failure by\n // rejection, so a query that answered with an error-shaped object\n // would look like a successful read of something odd.\n if (isActionValidationError(error)) {\n throw new QueryValidationError(error.errors)\n }\n\n throw new Error(report(error))\n }\n }\n\n return markClientBuilt(markQuery(read, options)) as (input?: unknown) => Promise<never>\n },\n }\n }\n\n return build([], null)\n}\n"]}
@@ -11,7 +11,7 @@
11
11
  // answer to a POST is a stored answer to something that was supposed to happen
12
12
  // once.
13
13
  import { pathKey } from './prerender.js';
14
- import { requestReadBy, withRequest, withResponseDraft } from './request.js';
14
+ import { UNPROBED, requestReadBy, withRequest, withResponseDraft } from './request.js';
15
15
  import { watchNondeterminism, whileRendering } from './nondeterminism.js';
16
16
  import { allowFor } from './routing.js';
17
17
  /**
@@ -30,12 +30,17 @@ export function apiKey(url) {
30
30
  /**
31
31
  * Reading anything here means the answer depends on the caller.
32
32
  *
33
- * Deliberately not `url`: the url is the key the answer is stored under, so
34
- * reading it tells you the same thing on every request that would hit the
35
- * stored file. The query string is handled by refusing to serve a stored
36
- * answer to a request that has one, which needs no detection at all.
33
+ * `url` is on the list although the path is the key the answer is stored
34
+ * under, because nobody reads it for the path: a handler written the Next way
35
+ * reads `new URL(request.url).searchParams`, which the probe cannot see the
36
+ * way it sees the awaited `searchParams` — and a stored answer marked as
37
+ * varying with nothing would then be served to every query, a webhook's
38
+ * verification handshake included. Reading the url also puts the build
39
+ * machine's origin within reach of the answer. A route that wants the bare
40
+ * url stored awaits `searchParams` instead; the table says so.
37
41
  */
38
42
  const PER_CALLER = new Set([
43
+ 'url',
39
44
  'headers',
40
45
  'body',
41
46
  'bodyUsed',
@@ -60,6 +65,10 @@ function probeRequest(url, touched) {
60
65
  const real = new Request(url, { method: 'GET' });
61
66
  return new Proxy(real, {
62
67
  get(target, property) {
68
+ // The engine's own way past the probe, for the url read that resolves
69
+ // the awaited searchParams - booked to searchParams, not to url.
70
+ if (property === UNPROBED)
71
+ return target;
63
72
  if (typeof property === 'string' && PER_CALLER.has(property))
64
73
  touched.add(property);
65
74
  const value = Reflect.get(target, property, target);
@@ -178,7 +187,8 @@ export async function prerenderApiRoutes(engine, manifest, write) {
178
187
  continue;
179
188
  }
180
189
  if (touched.size > 0) {
181
- said('dynamic', 'reads the request — ' + [...touched].sort().join(', '));
190
+ const hint = touched.has('url') ? ' (await searchParams to read the query and keep the bare url stored)' : '';
191
+ said('dynamic', 'reads the request — ' + [...touched].sort().join(', ') + hint);
182
192
  continue;
183
193
  }
184
194
  // Awaiting the query string is not a reason to give up on the route — the
@@ -186,6 +196,14 @@ export async function prerenderApiRoutes(engine, manifest, write) {
186
196
  // stored answer is good for.
187
197
  const varies = answered.readBy.includes('searchParams');
188
198
  const response = answered.response.value;
199
+ // A refusal is an answer to the request the build sent - none - not to
200
+ // the ones visitors will. A route that answers 403 with nothing read is
201
+ // usually checking something the probe cannot see, and a stored 403 was
202
+ // once every webhook handshake's answer. Left to run, and said so.
203
+ if (response.status >= 400) {
204
+ said('dynamic', `answered ${response.status} to the build — a refusal is not an answer to store`);
205
+ continue;
206
+ }
189
207
  // A cookie is an answer for one visitor, whatever the route read to
190
208
  // decide on it. Stored, the build's cookie would be handed to everyone.
191
209
  if (response.headers.has('set-cookie') || answered.drafted.has('set-cookie')) {
@@ -1 +1 @@
1
- {"version":3,"file":"apiPrerender.js","sourceRoot":"","sources":["../src/apiPrerender.ts"],"names":[],"mappings":"AAAA,kDAAkD;AAClD,EAAE;AACF,4EAA4E;AAC5E,+EAA+E;AAC/E,8EAA8E;AAC9E,8EAA8E;AAC9E,+EAA+E;AAC/E,qCAAqC;AACrC,EAAE;AACF,8EAA8E;AAC9E,+EAA+E;AAC/E,QAAQ;AAER,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAA;AACxC,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAC5E,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA;AAEzE,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AAEvC;;;;;;;GAOG;AACH,MAAM,SAAS,GAAG,KAAK,CAAA;AAiBvB,4CAA4C;AAC5C,MAAM,UAAU,MAAM,CAAC,GAAW;IAChC,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAA;AACnC,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACzB,SAAS;IACT,MAAM;IACN,UAAU;IACV,MAAM;IACN,MAAM;IACN,UAAU;IACV,aAAa;IACb,MA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Q,EAAE,MAAM,CAAC,CAAC,CAAC,qDAAqD,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;YAErF,0EAA0E;YAC1E,0EAA0E;YAC1E,iBAAiB;YACjB,MAAM,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAA;YAEzC,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACvB,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC,OAAO;oBAClC,SAAS,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,iEAAiE;wBAC/F,kGAAkG,CAAA;YACtG,CAAC;QACH,CAAC;IACD,CAAC;YAAS,CAAC;QACT,OAAO,EAAE,CAAA;IACX,CAAC;IAED,OAAO,OAAO,CAAA;AAChB,CAAC","sourcesContent":["// Freezing an api route the way a page is frozen.\n//\n// Not as an opt-in flag, deliberately. A page is stored by default and opts\n// OUT by touching the request — connection(), cookies(), headers() all suspend\n// at build time because there is no request there, and that is what marks the\n// page dynamic. A route works the same way and for the same reason: one model\n// to learn rather than two, and the honest default in both cases is \"the build\n// tried, and here is what it found\".\n//\n// GET only. Everything else is a method a caller may not repeat, and a stored\n// answer to a POST is a stored answer to something that was supposed to happen\n// once.\n\nimport { pathKey } from './prerender.js'\nimport { requestReadBy, withRequest, withResponseDraft } from './request.js'\nimport { watchNondeterminism, whileRendering } from './nondeterminism.js'\nimport type { ManifestApiRoute, RouteManifest } from './manifest.js'\nimport { allowFor } from './routing.js'\n\n/**\n * How long a route gets to answer before it is called dynamic.\n *\n * A route that reads the request does not fail here — it never settles, because\n * the accessors suspend forever with no request to read. So the budget is what\n * turns \"waiting\" into an answer, and it only has to be long enough for a route\n * that was going to finish.\n */\nconst BUDGET_MS = 2_000\n\n/** What a stored answer holds. Enough to rebuild the Response exactly. */\nexport interface FrozenApiResponse {\n status: number\n headers: [string, string][]\n body: string\n /**\n * Whether the answer depends on the query string.\n *\n * False when the handler never awaited `searchParams` and declared no schema\n * for it, which means the same answer is right for `?utm_source=anything`.\n * True and the stored answer is only good for the bare url.\n */\n varies: boolean\n}\n\n/** The file a frozen route is stored as. */\nexport function apiKey(url: string): string {\n return `${pathKey(url)}.api.json`\n}\n\n/**\n * Reading anything here means the answer depends on the caller.\n *\n * Deliberately not `url`: the url is the key the answer is stored under, so\n * reading it tells you the same thing on every request that would hit the\n * stored file. The query string is handled by refusing to serve a stored\n * answer to a request that has one, which needs no detection at all.\n */\nconst PER_CALLER = new Set([\n 'headers',\n 'body',\n 'bodyUsed',\n 'text',\n 'json',\n 'formData',\n 'arrayBuffer',\n 'blob',\n 'bytes',\n 'signal',\n 'referrer',\n 'credentials',\n])\n\n/**\n * A Request that records what was read out of it.\n *\n * A proxy rather than a subclass because the interesting properties are\n * getters on Request.prototype, and `this` has to stay the real Request or\n * every one of them throws about an illegal invocation.\n */\nfunction probeRequest(url: string, touched: Set<string>): Request {\n const real = new Request(url, { method: 'GET' })\n\n return new Proxy(real, {\n get(target, property) {\n if (typeof property === 'string' && PER_CALLER.has(property)) touched.add(property)\n\n const value = Reflect.get(target, property, target)\n\n return typeof value === 'function' ? value.bind(target) : value\n },\n })\n}\n\n/** The url a route with no parameters answers. */\nfunction urlFor(route: ManifestApiRoute): string | null {\n // A parameterised route has as many urls as there are values, and nothing\n // here knows them. Pages solve this with generateStaticParams; until a route\n // can say the same, one is answered per request.\n if (route.segments.some((segment) => segment.type !== 'static')) return null\n\n return '/' + route.segments.map((segment) => segment.value).join('/')\n}\n\n/**\n * What the build calls a route in its output.\n *\n * The pattern for a parameterised one, spelled the way pages already spell\n * theirs, rather than the module name — a line reading\n * \"/app/api/greet/[name]/route\" names a file on disk and the rest of the table\n * names urls.\n */\nfunction labelFor(route: ManifestApiRoute): string {\n return (\n '/' +\n route.segments\n .map((segment) => (segment.type === 'static' ? segment.value : `_${segment.value}_`))\n .join('/')\n )\n}\n\n/** Whether a body is text this can store and hand back unchanged. */\nfunction asText(bytes: Uint8Array): string | null {\n try {\n const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n\n return text\n } catch {\n // Binary. Storable in principle, as base64, at the cost of a third of its\n // size on disk and a decode per request — for a route that is far more\n // likely to be streaming a file it should be serving as a file.\n return null\n }\n}\n\nexport interface ApiPrerenderResult {\n url: string\n name: string\n type: 'frozen' | 'dynamic'\n reason: string | null\n /** Stored, and worth a second look - it froze a value that will not be the same tomorrow. */\n warning?: string\n}\n\n/**\n * Try to answer every api route once, at build time, and store what can be.\n *\n * Sequential rather than parallel: there are usually few of them, each is a\n * function call rather than a React render, and the ones that are going to be\n * dynamic spend the whole budget waiting — which is time, not work.\n */\nexport async function prerenderApiRoutes(\n engine: { handleApiRoute?: (n: string, r: Request, p: Record<string, string>, a: string) => Promise<Response> },\n manifest: RouteManifest,\n write: (name: string, contents: string) => Promise<void>,\n): Promise<ApiPrerenderResult[]> {\n if (!engine.handleApiRoute || !manifest.apis?.length) return []\n\n const results: ApiPrerenderResult[] = []\n\n // Date.now() and friends are watched for the length of the loop, the way\n // the page prerender watches them; whileRendering records what each route\n // reached for while it answered.\n const unwatch = watchNondeterminism()\n\n try {\n for (const route of manifest.apis) {\n const said = (type: 'frozen' | 'dynamic', reason: string | null) => {\n results.push({ url: labelFor(route), name: route.name, type, reason })\n }\n\n if (!route.methods.includes('GET')) {\n said('dynamic', 'no GET to store')\n continue\n }\n\n // A guarded route answers differently depending on who is asking, which is\n // the whole purpose of the guard. Storing one answer and serving it to\n // everyone is how a guard is silently removed.\n if (route.middleware.length > 0) {\n said('dynamic', 'guarded by middleware')\n continue\n }\n\n const url = urlFor(route)\n\n if (!url) {\n said('dynamic', 'one url per param value, and none are listed')\n continue\n }\n\n const touched = new Set<string>()\n const request = probeRequest('https://prerender.invalid' + url, touched)\n\n // No request in scope, so headers(), cookies() and connection() suspend\n // forever rather than resolving to whatever the build machine had. The\n // budget below is what turns that into an answer.\n // Inside a response draft, because that is where the engine puts a cookie\n // a route sets - a literal Set-Cookie on its Response is moved there too\n // whenever a draft is open - and a probe with no draft reads a Response\n // the cookie may already have left. Whether it went to the draft or stayed\n // on the Response depends on what else is running in the process; the\n // question here is only whether there was one.\n const answered = await withResponseDraft(({ taken }) =>\n withRequest(null as never, async () => {\n let readBy: string[] = []\n\n const response = await Promise.race([\n whileRendering(() => engine.handleApiRoute!(route.name, request, {}, allowFor(route)))\n .then(([value, reached]) => ({ value, reached }))\n .catch((error) => ({ error })),\n new Promise<null>((resolve) =>\n setTimeout(() => {\n readBy = requestReadBy()\n resolve(null)\n }, BUDGET_MS),\n ),\n ])\n\n return { response, readBy: readBy.length ? readBy : requestReadBy(), drafted: taken() }\n }),\n )\n\n if (answered.response === null) {\n const why = answered.readBy.length\n ? 'dynamic — called ' + answered.readBy.join(', ')\n : 'did not answer within the build budget'\n\n said('dynamic', why)\n continue\n }\n\n if ('error' in answered.response) {\n // Not a build failure. A route that throws with no request may be doing\n // exactly the right thing — refusing a caller it cannot identify — and\n // refusing the build over it would make that route unbuildable.\n said('dynamic', 'threw without a request')\n continue\n }\n\n if (touched.size > 0) {\n said('dynamic', 'reads the request — ' + [...touched].sort().join(', '))\n continue\n }\n\n // Awaiting the query string is not a reason to give up on the route — the\n // bare url still has one right answer. It only narrows which requests the\n // stored answer is good for.\n const varies = answered.readBy.includes('searchParams')\n\n const response = answered.response.value\n\n // A cookie is an answer for one visitor, whatever the route read to\n // decide on it. Stored, the build's cookie would be handed to everyone.\n if (response.headers.has('set-cookie') || answered.drafted.has('set-cookie')) {\n said('dynamic', 'sets a cookie — an answer for one visitor, not one to store')\n continue\n }\n\n const body = asText(new Uint8Array(await response.arrayBuffer()))\n\n if (body === null) {\n said('dynamic', 'answers with bytes rather than text')\n continue\n }\n\n await write(\n apiKey(url),\n JSON.stringify({\n status: response.status,\n // Lower-cased and sorted, so two builds of the same route produce the\n // same bytes. Headers iteration does not promise a case or an order,\n // and a file that differs between builds for no reason defeats\n // content-addressed caching and makes a diff unreadable. Names are\n // case-insensitive, so nothing is lost by picking one.\n headers: [...response.headers]\n .map(([name, value]) => [name.toLowerCase(), value] as [string, string])\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n body,\n varies,\n } satisfies FrozenApiResponse),\n )\n\n said('frozen', varies ? 'stored for the bare url — it reads the query string' : null)\n\n // The same warning a page gets: a stored answer keeps whatever Date.now()\n // or Math.random() returned at build time, and a json body has no browser\n // to move it to.\n const reached = answered.response.reached\n\n if (reached.length > 0) {\n results[results.length - 1]!.warning =\n `froze ${reached.join(' and ')} — a stored answer keeps whatever that returned at build time. ` +\n 'If it should differ per call, read the request (await connection()) so the route runs on demand.'\n }\n }\n } finally {\n unwatch()\n }\n\n return results\n}\n"]}
1
+ {"version":3,"file":"apiPrerender.js","sourceRoot":"","sources":["../src/apiPrerender.ts"],"names":[],"mappings":"AAAA,kDAAkD;AAClD,EAAE;AACF,4EAA4E;AAC5E,+EAA+E;AAC/E,8EAA8E;AAC9E,8EAA8E;AAC9E,+EAA+E;AAC/E,qCAAqC;AACrC,EAAE;AACF,8EAA8E;AAC9E,+EAA+E;AAC/E,QAAQ;AAER,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAA;AACxC,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AACtF,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA;AAEzE,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AAEvC;;;;;;;GAOG;AACH,MAAM,SAAS,GAAG,KAAK,CAAA;AAiBvB,4CAA4C;AAC5C,MAAM,UAAU,MAAM,CAAC,GAAW;IAChC,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAA;AACnC,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACzB,KAAK;IACL,SAAS;IACT,MAAM;IACN,UAAU;IACV,MAAM;IACN,MAAM;I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AAQ,CAAC,OAAO,CAAC;qBAC3B,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,KAAK,CAAqB,CAAC;qBACvE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;gBACnD,IAAI;gBACJ,MAAM;aACqB,CAAC,CAC/B,CAAA;YAED,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,qDAAqD,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;YAErF,0EAA0E;YAC1E,0EAA0E;YAC1E,iBAAiB;YACjB,MAAM,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAA;YAEzC,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACvB,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC,OAAO;oBAClC,SAAS,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,iEAAiE;wBAC/F,kGAAkG,CAAA;YACtG,CAAC;QACH,CAAC;IACD,CAAC;YAAS,CAAC;QACT,OAAO,EAAE,CAAA;IACX,CAAC;IAED,OAAO,OAAO,CAAA;AAChB,CAAC","sourcesContent":["// Freezing an api route the way a page is frozen.\n//\n// Not as an opt-in flag, deliberately. A page is stored by default and opts\n// OUT by touching the request — connection(), cookies(), headers() all suspend\n// at build time because there is no request there, and that is what marks the\n// page dynamic. A route works the same way and for the same reason: one model\n// to learn rather than two, and the honest default in both cases is \"the build\n// tried, and here is what it found\".\n//\n// GET only. Everything else is a method a caller may not repeat, and a stored\n// answer to a POST is a stored answer to something that was supposed to happen\n// once.\n\nimport { pathKey } from './prerender.js'\nimport { UNPROBED, requestReadBy, withRequest, withResponseDraft } from './request.js'\nimport { watchNondeterminism, whileRendering } from './nondeterminism.js'\nimport type { ManifestApiRoute, RouteManifest } from './manifest.js'\nimport { allowFor } from './routing.js'\n\n/**\n * How long a route gets to answer before it is called dynamic.\n *\n * A route that reads the request does not fail here — it never settles, because\n * the accessors suspend forever with no request to read. So the budget is what\n * turns \"waiting\" into an answer, and it only has to be long enough for a route\n * that was going to finish.\n */\nconst BUDGET_MS = 2_000\n\n/** What a stored answer holds. Enough to rebuild the Response exactly. */\nexport interface FrozenApiResponse {\n status: number\n headers: [string, string][]\n body: string\n /**\n * Whether the answer depends on the query string.\n *\n * False when the handler never awaited `searchParams` and declared no schema\n * for it, which means the same answer is right for `?utm_source=anything`.\n * True and the stored answer is only good for the bare url.\n */\n varies: boolean\n}\n\n/** The file a frozen route is stored as. */\nexport function apiKey(url: string): string {\n return `${pathKey(url)}.api.json`\n}\n\n/**\n * Reading anything here means the answer depends on the caller.\n *\n * `url` is on the list although the path is the key the answer is stored\n * under, because nobody reads it for the path: a handler written the Next way\n * reads `new URL(request.url).searchParams`, which the probe cannot see the\n * way it sees the awaited `searchParams` — and a stored answer marked as\n * varying with nothing would then be served to every query, a webhook's\n * verification handshake included. Reading the url also puts the build\n * machine's origin within reach of the answer. A route that wants the bare\n * url stored awaits `searchParams` instead; the table says so.\n */\nconst PER_CALLER = new Set([\n 'url',\n 'headers',\n 'body',\n 'bodyUsed',\n 'text',\n 'json',\n 'formData',\n 'arrayBuffer',\n 'blob',\n 'bytes',\n 'signal',\n 'referrer',\n 'credentials',\n])\n\n/**\n * A Request that records what was read out of it.\n *\n * A proxy rather than a subclass because the interesting properties are\n * getters on Request.prototype, and `this` has to stay the real Request or\n * every one of them throws about an illegal invocation.\n */\nfunction probeRequest(url: string, touched: Set<string>): Request {\n const real = new Request(url, { method: 'GET' })\n\n return new Proxy(real, {\n get(target, property) {\n // The engine's own way past the probe, for the url read that resolves\n // the awaited searchParams - booked to searchParams, not to url.\n if (property === UNPROBED) return target\n if (typeof property === 'string' && PER_CALLER.has(property)) touched.add(property)\n\n const value = Reflect.get(target, property, target)\n\n return typeof value === 'function' ? value.bind(target) : value\n },\n })\n}\n\n/** The url a route with no parameters answers. */\nfunction urlFor(route: ManifestApiRoute): string | null {\n // A parameterised route has as many urls as there are values, and nothing\n // here knows them. Pages solve this with generateStaticParams; until a route\n // can say the same, one is answered per request.\n if (route.segments.some((segment) => segment.type !== 'static')) return null\n\n return '/' + route.segments.map((segment) => segment.value).join('/')\n}\n\n/**\n * What the build calls a route in its output.\n *\n * The pattern for a parameterised one, spelled the way pages already spell\n * theirs, rather than the module name — a line reading\n * \"/app/api/greet/[name]/route\" names a file on disk and the rest of the table\n * names urls.\n */\nfunction labelFor(route: ManifestApiRoute): string {\n return (\n '/' +\n route.segments\n .map((segment) => (segment.type === 'static' ? segment.value : `_${segment.value}_`))\n .join('/')\n )\n}\n\n/** Whether a body is text this can store and hand back unchanged. */\nfunction asText(bytes: Uint8Array): string | null {\n try {\n const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n\n return text\n } catch {\n // Binary. Storable in principle, as base64, at the cost of a third of its\n // size on disk and a decode per request — for a route that is far more\n // likely to be streaming a file it should be serving as a file.\n return null\n }\n}\n\nexport interface ApiPrerenderResult {\n url: string\n name: string\n type: 'frozen' | 'dynamic'\n reason: string | null\n /** Stored, and worth a second look - it froze a value that will not be the same tomorrow. */\n warning?: string\n}\n\n/**\n * Try to answer every api route once, at build time, and store what can be.\n *\n * Sequential rather than parallel: there are usually few of them, each is a\n * function call rather than a React render, and the ones that are going to be\n * dynamic spend the whole budget waiting — which is time, not work.\n */\nexport async function prerenderApiRoutes(\n engine: { handleApiRoute?: (n: string, r: Request, p: Record<string, string>, a: string) => Promise<Response> },\n manifest: RouteManifest,\n write: (name: string, contents: string) => Promise<void>,\n): Promise<ApiPrerenderResult[]> {\n if (!engine.handleApiRoute || !manifest.apis?.length) return []\n\n const results: ApiPrerenderResult[] = []\n\n // Date.now() and friends are watched for the length of the loop, the way\n // the page prerender watches them; whileRendering records what each route\n // reached for while it answered.\n const unwatch = watchNondeterminism()\n\n try {\n for (const route of manifest.apis) {\n const said = (type: 'frozen' | 'dynamic', reason: string | null) => {\n results.push({ url: labelFor(route), name: route.name, type, reason })\n }\n\n if (!route.methods.includes('GET')) {\n said('dynamic', 'no GET to store')\n continue\n }\n\n // A guarded route answers differently depending on who is asking, which is\n // the whole purpose of the guard. Storing one answer and serving it to\n // everyone is how a guard is silently removed.\n if (route.middleware.length > 0) {\n said('dynamic', 'guarded by middleware')\n continue\n }\n\n const url = urlFor(route)\n\n if (!url) {\n said('dynamic', 'one url per param value, and none are listed')\n continue\n }\n\n const touched = new Set<string>()\n const request = probeRequest('https://prerender.invalid' + url, touched)\n\n // No request in scope, so headers(), cookies() and connection() suspend\n // forever rather than resolving to whatever the build machine had. The\n // budget below is what turns that into an answer.\n // Inside a response draft, because that is where the engine puts a cookie\n // a route sets - a literal Set-Cookie on its Response is moved there too\n // whenever a draft is open - and a probe with no draft reads a Response\n // the cookie may already have left. Whether it went to the draft or stayed\n // on the Response depends on what else is running in the process; the\n // question here is only whether there was one.\n const answered = await withResponseDraft(({ taken }) =>\n withRequest(null as never, async () => {\n let readBy: string[] = []\n\n const response = await Promise.race([\n whileRendering(() => engine.handleApiRoute!(route.name, request, {}, allowFor(route)))\n .then(([value, reached]) => ({ value, reached }))\n .catch((error) => ({ error })),\n new Promise<null>((resolve) =>\n setTimeout(() => {\n readBy = requestReadBy()\n resolve(null)\n }, BUDGET_MS),\n ),\n ])\n\n return { response, readBy: readBy.length ? readBy : requestReadBy(), drafted: taken() }\n }),\n )\n\n if (answered.response === null) {\n const why = answered.readBy.length\n ? 'dynamic — called ' + answered.readBy.join(', ')\n : 'did not answer within the build budget'\n\n said('dynamic', why)\n continue\n }\n\n if ('error' in answered.response) {\n // Not a build failure. A route that throws with no request may be doing\n // exactly the right thing — refusing a caller it cannot identify — and\n // refusing the build over it would make that route unbuildable.\n said('dynamic', 'threw without a request')\n continue\n }\n\n if (touched.size > 0) {\n const hint = touched.has('url') ? ' (await searchParams to read the query and keep the bare url stored)' : ''\n\n said('dynamic', 'reads the request — ' + [...touched].sort().join(', ') + hint)\n continue\n }\n\n // Awaiting the query string is not a reason to give up on the route — the\n // bare url still has one right answer. It only narrows which requests the\n // stored answer is good for.\n const varies = answered.readBy.includes('searchParams')\n\n const response = answered.response.value\n\n // A refusal is an answer to the request the build sent - none - not to\n // the ones visitors will. A route that answers 403 with nothing read is\n // usually checking something the probe cannot see, and a stored 403 was\n // once every webhook handshake's answer. Left to run, and said so.\n if (response.status >= 400) {\n said('dynamic', `answered ${response.status} to the build — a refusal is not an answer to store`)\n continue\n }\n\n // A cookie is an answer for one visitor, whatever the route read to\n // decide on it. Stored, the build's cookie would be handed to everyone.\n if (response.headers.has('set-cookie') || answered.drafted.has('set-cookie')) {\n said('dynamic', 'sets a cookie — an answer for one visitor, not one to store')\n continue\n }\n\n const body = asText(new Uint8Array(await response.arrayBuffer()))\n\n if (body === null) {\n said('dynamic', 'answers with bytes rather than text')\n continue\n }\n\n await write(\n apiKey(url),\n JSON.stringify({\n status: response.status,\n // Lower-cased and sorted, so two builds of the same route produce the\n // same bytes. Headers iteration does not promise a case or an order,\n // and a file that differs between builds for no reason defeats\n // content-addressed caching and makes a diff unreadable. Names are\n // case-insensitive, so nothing is lost by picking one.\n headers: [...response.headers]\n .map(([name, value]) => [name.toLowerCase(), value] as [string, string])\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n body,\n varies,\n } satisfies FrozenApiResponse),\n )\n\n said('frozen', varies ? 'stored for the bare url — it reads the query string' : null)\n\n // The same warning a page gets: a stored answer keeps whatever Date.now()\n // or Math.random() returned at build time, and a json body has no browser\n // to move it to.\n const reached = answered.response.reached\n\n if (reached.length > 0) {\n results[results.length - 1]!.warning =\n `froze ${reached.join(' and ')} — a stored answer keeps whatever that returned at build time. ` +\n 'If it should differ per call, read the request (await connection()) so the route runs on demand.'\n }\n }\n } finally {\n unwatch()\n }\n\n return results\n}\n"]}
@@ -0,0 +1,30 @@
1
+ /** Where `name` is installed, walking up from `from` the way resolution does. */
2
+ export declare function packageDir(name: string, from: string): string | null;
3
+ /** Whether any source file under `dir` opens with "use client". */
4
+ export declare function hasClientDirective(dir: string): boolean;
5
+ /**
6
+ * Whether any source file under `dir` imports react-dom/server.
7
+ *
8
+ * For a dependency left external where server components render: its
9
+ * imports are never resolved by the build, so the renderer stub that names
10
+ * the app file for a direct import never sees this one. @react-email/render
11
+ * is the usual case - an action imports it, the build says nothing, and the
12
+ * first call throws React's refusal at a visitor.
13
+ */
14
+ export declare function importsServerRenderer(dir: string): boolean;
15
+ /**
16
+ * Where a package is, anywhere in the project's dependency graph.
17
+ *
18
+ * For a polyfill a dependency of a dependency needs: not hoisted to the
19
+ * project under a strict store, so not resolvable from the project by
20
+ * name, and still what has to be evaluated first. A breadth-first walk of
21
+ * the manifests, from each package's real path, bounded in depth. The
22
+ * entry file is what `main` names, or index.js.
23
+ */
24
+ export declare function packageEntryInGraph(root: string, name: string, depth?: number): string | null;
25
+ /**
26
+ * The direct dependencies of the project at `root` that plugin-rsc would
27
+ * leave external and that carry a "use client" file - and the React-using
28
+ * dependencies under each, which have to be bundled with it.
29
+ */
30
+ export declare function clientPackages(root: string): string[];
@@ -0,0 +1,234 @@
1
+ // Dependencies with "use client" files that plugin-rsc would leave external.
2
+ //
3
+ // plugin-rsc bundles a dependency into the server graphs - and so sees its
4
+ // directives - only when the dependency declares react as a peer. That is
5
+ // the right signal for a library written for React. It misses the package
6
+ // that imports react and never says so: a component wrapper generated by a
7
+ // tool, a workspace package with react under dependencies, a published
8
+ // package whose author forgot. Left external, its "use client" is a string
9
+ // nobody reads, the rsc environment loads it under the react-server
10
+ // condition, and the first useState inside it fails at render with an error
11
+ // that names React and not the package.
12
+ //
13
+ // So the direct dependencies are read once at config time: any that plugin-rsc
14
+ // would not bundle, and that carries a "use client" directive in one of its
15
+ // files, is bundled here. Direct dependencies only - a directive two levels
16
+ // down is the concern of the package between, which declared it.
17
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync, openSync, readSync, closeSync } from "node:fs";
18
+ import { dirname, join } from "node:path";
19
+ /** A directive at the top of a file: comments may precede it, code may not. */
20
+ const DIRECTIVE = /^(?:\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)*(?:'use client'|"use client")\s*;?/;
21
+ const SOURCE = /\.(?:m?js|cjs|jsx)$/;
22
+ /** The most files read per package before giving up: a bound, not a budget. */
23
+ const FILE_CAP = 3000;
24
+ /** Enough of a file to hold a licence header and the directive after it. */
25
+ const HEAD_BYTES = 2048;
26
+ /** The packages plugin-rsc handles itself, and this one. */
27
+ const OWN = new Set(["react", "react-dom", "react-server-dom-webpack", "@vitejs/plugin-rsc"]);
28
+ function readJson(path) {
29
+ try {
30
+ return JSON.parse(readFileSync(path, "utf8"));
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ /** Where `name` is installed, walking up from `from` the way resolution does. */
37
+ export function packageDir(name, from) {
38
+ let dir = from;
39
+ for (;;) {
40
+ const candidate = join(dir, "node_modules", name);
41
+ if (existsSync(join(candidate, "package.json")))
42
+ return candidate;
43
+ const parent = dirname(dir);
44
+ if (parent === dir)
45
+ return null;
46
+ dir = parent;
47
+ }
48
+ }
49
+ function realpathOf(path) {
50
+ try {
51
+ return realpathSync(path);
52
+ }
53
+ catch {
54
+ return path;
55
+ }
56
+ }
57
+ function headOf(path) {
58
+ const fd = openSync(path, "r");
59
+ try {
60
+ const buffer = Buffer.alloc(HEAD_BYTES);
61
+ const read = readSync(fd, buffer, 0, HEAD_BYTES, 0);
62
+ return buffer.toString("utf8", 0, read);
63
+ }
64
+ finally {
65
+ closeSync(fd);
66
+ }
67
+ }
68
+ /** Whether any source file under `dir` opens with "use client". */
69
+ export function hasClientDirective(dir) {
70
+ return someSourceFile(dir, (path) => DIRECTIVE.test(headOf(path)));
71
+ }
72
+ /** An import of react-dom's server renderer, static or dynamic, ESM or CJS. */
73
+ const SERVER_RENDERER_IMPORT = /["']react-dom\/server(?:\.[a-z]+)?["']/;
74
+ /** The largest file worth reading whole for an import: a bundled dist, not a data table. */
75
+ const WHOLE_FILE_CAP = 512 * 1024;
76
+ /**
77
+ * Whether any source file under `dir` imports react-dom/server.
78
+ *
79
+ * For a dependency left external where server components render: its
80
+ * imports are never resolved by the build, so the renderer stub that names
81
+ * the app file for a direct import never sees this one. @react-email/render
82
+ * is the usual case - an action imports it, the build says nothing, and the
83
+ * first call throws React's refusal at a visitor.
84
+ */
85
+ export function importsServerRenderer(dir) {
86
+ return someSourceFile(dir, (path) => {
87
+ try {
88
+ if (statSync(path).size > WHOLE_FILE_CAP)
89
+ return false;
90
+ return SERVER_RENDERER_IMPORT.test(readFileSync(path, "utf8"));
91
+ }
92
+ catch {
93
+ return false;
94
+ }
95
+ });
96
+ }
97
+ /** Whether `test` holds for some source file under `dir`, within the cap. */
98
+ function someSourceFile(dir, test) {
99
+ const pending = [dir];
100
+ let seen = 0;
101
+ while (pending.length) {
102
+ const current = pending.pop();
103
+ let entries;
104
+ try {
105
+ entries = readdirSync(current);
106
+ }
107
+ catch {
108
+ continue;
109
+ }
110
+ for (const entry of entries) {
111
+ if (entry === "node_modules" || entry.startsWith("."))
112
+ continue;
113
+ const path = join(current, entry);
114
+ let stat;
115
+ try {
116
+ stat = statSync(path);
117
+ }
118
+ catch {
119
+ continue;
120
+ }
121
+ if (stat.isDirectory()) {
122
+ pending.push(path);
123
+ continue;
124
+ }
125
+ if (!SOURCE.test(entry))
126
+ continue;
127
+ if (++seen > FILE_CAP)
128
+ return false;
129
+ try {
130
+ if (test(path))
131
+ return true;
132
+ }
133
+ catch {
134
+ // Unreadable is neither.
135
+ }
136
+ }
137
+ }
138
+ return false;
139
+ }
140
+ /** Whether a package says it uses React, as a peer or as a dependency. */
141
+ function usesReact(manifest) {
142
+ return !!manifest && ("react" in (manifest.peerDependencies ?? {}) || "react" in (manifest.dependencies ?? {}));
143
+ }
144
+ /**
145
+ * The dependencies of a bundled package that use React, and theirs.
146
+ *
147
+ * Bundling the package that carries the directive is not enough: the
148
+ * runtime it calls into - @stencil/react-output-target under a generated
149
+ * wrapper - is its own package, with react as a peer, and plugin-rsc's
150
+ * crawl never reached it because it only descends through packages that
151
+ * declared React. Left external, that runtime loads React through Node
152
+ * while everything else gets it through Vite: two copies, and the hooks
153
+ * dispatcher is null in one of them. Every React-using dependency under
154
+ * a bundled package is bundled with it.
155
+ */
156
+ function reactDependenciesOf(dir, into, seen) {
157
+ const manifest = readJson(join(dir, "package.json"));
158
+ for (const name of Object.keys(manifest?.dependencies ?? {})) {
159
+ if (OWN.has(name) || seen.has(name))
160
+ continue;
161
+ seen.add(name);
162
+ // From where the package really is: under Bun's store a symlink in the
163
+ // app's node_modules points into .bun/<pkg>@<v>/node_modules/<pkg>, and
164
+ // the dependency sits beside it there, not beside the symlink.
165
+ const depDir = packageDir(name, realpathOf(dir));
166
+ if (!depDir || !usesReact(readJson(join(depDir, "package.json"))))
167
+ continue;
168
+ into.add(name);
169
+ reactDependenciesOf(depDir, into, seen);
170
+ }
171
+ }
172
+ /**
173
+ * Where a package is, anywhere in the project's dependency graph.
174
+ *
175
+ * For a polyfill a dependency of a dependency needs: not hoisted to the
176
+ * project under a strict store, so not resolvable from the project by
177
+ * name, and still what has to be evaluated first. A breadth-first walk of
178
+ * the manifests, from each package's real path, bounded in depth. The
179
+ * entry file is what `main` names, or index.js.
180
+ */
181
+ export function packageEntryInGraph(root, name, depth = 5) {
182
+ const seen = new Set();
183
+ let frontier = [root];
184
+ for (let level = 0; level <= depth && frontier.length; level++) {
185
+ const next = [];
186
+ for (const dir of frontier) {
187
+ const found = packageDir(name, realpathOf(dir));
188
+ if (found) {
189
+ const manifest = readJson(join(found, "package.json"));
190
+ const entry = join(found, manifest?.main ?? "index.js");
191
+ return existsSync(entry) ? entry : existsSync(entry + ".js") ? entry + ".js" : null;
192
+ }
193
+ const manifest = readJson(join(dir, "package.json"));
194
+ for (const dep of Object.keys(manifest?.dependencies ?? {})) {
195
+ if (seen.has(dep))
196
+ continue;
197
+ seen.add(dep);
198
+ const depDir = packageDir(dep, realpathOf(dir));
199
+ if (depDir)
200
+ next.push(depDir);
201
+ }
202
+ }
203
+ frontier = next;
204
+ }
205
+ return null;
206
+ }
207
+ /**
208
+ * The direct dependencies of the project at `root` that plugin-rsc would
209
+ * leave external and that carry a "use client" file - and the React-using
210
+ * dependencies under each, which have to be bundled with it.
211
+ */
212
+ export function clientPackages(root) {
213
+ const own = readJson(join(root, "package.json"));
214
+ if (!own?.dependencies)
215
+ return [];
216
+ const found = new Set();
217
+ for (const name of Object.keys(own.dependencies)) {
218
+ if (OWN.has(name) || name.startsWith("@rsc-kit/"))
219
+ continue;
220
+ const dir = packageDir(name, root);
221
+ if (!dir)
222
+ continue;
223
+ const manifest = readJson(join(dir, "package.json"));
224
+ // plugin-rsc's own rule: react as a peer, and the package is bundled already.
225
+ if (manifest?.peerDependencies && "react" in manifest.peerDependencies)
226
+ continue;
227
+ if (!hasClientDirective(dir))
228
+ continue;
229
+ found.add(name);
230
+ reactDependenciesOf(dir, found, new Set([name]));
231
+ }
232
+ return [...found].sort();
233
+ }
234
+ //# sourceMappingURL=clientPackages.js.map