@rsc-kit/core 0.38.0 → 0.40.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.
package/dist/vite.js CHANGED
@@ -304,6 +304,12 @@ let hostFunctions = null;
304
304
  /** The backend's typed signatures, by function name, and the named types they refer to. */
305
305
  let hostTypes = {};
306
306
  let hostDefs = {};
307
+ /**
308
+ * The functions the backend can check without running: given `validate`, it
309
+ * runs the guards and the validation and stops there. Only these are ever
310
+ * sent a check - a backend that has never heard of one would run the call.
311
+ */
312
+ let hostValidates = [];
307
313
  /**
308
314
  * The manifest commands run in this process, by project and command.
309
315
  *
@@ -391,7 +397,7 @@ function fileHostManifest(root) {
391
397
  throw new Error("[rsc-kit] rsc-host-actions.json is the old manifest. The backend now writes " +
392
398
  HOST_FILE + " - { actions, functions } - so update the adapter and run its manifest command.");
393
399
  }
394
- return { actions: {}, functions: null, types: {}, defs: {} };
400
+ return { actions: {}, functions: null, types: {}, defs: {}, validates: [] };
395
401
  }
396
402
  let parsed;
397
403
  try {
@@ -411,12 +417,17 @@ function fileHostManifest(root) {
411
417
  throw new Error(`[rsc-kit] ${HOST_FILE}: "functions" must be an array of names.`);
412
418
  }
413
419
  const isMap = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
420
+ const validates = parsed?.validates;
421
+ if (validates !== undefined && (!Array.isArray(validates) || validates.some((n) => typeof n !== "string"))) {
422
+ throw new Error(`[rsc-kit] ${HOST_FILE}: "validates" must be an array of function names.`);
423
+ }
414
424
  return {
415
425
  types: isMap(parsed?.types) ? parsed.types : {},
416
426
  defs: isMap(parsed?.defs) ? parsed.defs : {},
417
427
  actions: actions,
418
428
  // The reserved guard call is the engine's to make, not the app's.
419
429
  functions: functions ? functions.filter((n) => !n.startsWith("__rsc.")).sort() : null,
430
+ validates: validates ?? [],
420
431
  };
421
432
  }
422
433
  /**
@@ -609,10 +620,29 @@ export function subdomainProblem(routes, labels, hasSiteHost) {
609
620
  }
610
621
  return null;
611
622
  }
623
+ /**
624
+ * A backend path under a folder served on its own subdomain: a proxy forwards
625
+ * by the path visitors send, and on merchant.example.com that is /auth, never
626
+ * /merchant/auth - the prefix would match nothing.
627
+ */
628
+ export function backendPathOnSubdomain(paths, labels) {
629
+ for (const path of paths) {
630
+ const first = path.slice(1).split("/")[0];
631
+ if (labels.includes(first)) {
632
+ return (`[rsc-kit] backendPaths: ${JSON.stringify(path)} is under app/${first}/, which subdomains serves on ${first}.<site>, ` +
633
+ `where its visitors send ${JSON.stringify(path.slice(first.length + 1) || "/")}. Name the backend's urls as visitors send them.`);
634
+ }
635
+ }
636
+ return null;
637
+ }
638
+ /**
639
+ * A page a backend path would take - a plain prefix or one with a bracketed
640
+ * segment. The path goes to the backend before any page is asked, so that
641
+ * page would never render. A dynamic page the prefix only shares urls with,
642
+ * [team]/[app] under /auth, is not taken: that is what backendPaths is for.
643
+ */
612
644
  export function pageUnderBackendPath(routes, paths) {
613
645
  for (const path of paths) {
614
- if (!path.includes("["))
615
- continue;
616
646
  const parts = path.slice(1).split("/");
617
647
  for (const route of routes) {
618
648
  const segments = route.segments.filter((segment) => segment.type !== "host");
@@ -765,6 +795,7 @@ function loadHostManifest(options) {
765
795
  hostFunctions = manifest.functions;
766
796
  hostTypes = manifest.types;
767
797
  hostDefs = manifest.defs;
798
+ hostValidates = manifest.validates;
768
799
  }
769
800
  /** Run the backend's manifest command, once per process; see the option. */
770
801
  function runHostManifest(options, isBuild, again = false) {
@@ -1034,7 +1065,7 @@ function routeManifest() {
1034
1065
  ...revalidateOf([...layouts, name].map((n) => components.get(n).absPath)),
1035
1066
  });
1036
1067
  }
1037
- const clash = samePageUrl(routes) ?? pageUnderBackendPath(routes, backendPaths) ?? subdomainProblem(routes, subdomains, siteHosts.length > 0);
1068
+ const clash = samePageUrl(routes) ?? pageUnderBackendPath(routes, backendPaths) ?? subdomainProblem(routes, subdomains, siteHosts.length > 0) ?? backendPathOnSubdomain(backendPaths, subdomains);
1038
1069
  if (clash)
1039
1070
  throw new Error(clash);
1040
1071
  // What the build decided, for a host that has to act on it afterwards —
@@ -1057,7 +1088,7 @@ function routeManifest() {
1057
1088
  },
1058
1089
  routes,
1059
1090
  intercepts,
1060
- apis: [...apiRoutes.values()].map(({ name, methods, generated, absPath }) => ({
1091
+ apis: [...apiRoutes.values()].map(({ name, methods, generated, absPath, crossOrigin }) => ({
1061
1092
  name,
1062
1093
  segments: urlSegments(name),
1063
1094
  methods,
@@ -1074,6 +1105,7 @@ function routeManifest() {
1074
1105
  // ['auth']` on a directory guards the route.ts files in it, or adding
1075
1106
  // an endpoint under a guarded path opened a hole in it.
1076
1107
  hostMiddleware: generated ? [] : hostMiddleware(dirOf(name)),
1108
+ ...(crossOrigin ? { crossOrigin } : {}),
1077
1109
  })),
1078
1110
  };
1079
1111
  }
@@ -2282,7 +2314,7 @@ ${legend(counted)}
2282
2314
  .filter((r) => existsSync(join(staticDir, pathKeyOf(r.url) + ".html")))
2283
2315
  .map((r) => r.url),
2284
2316
  results,
2285
- shells: edgeShells(results, manifest.routes),
2317
+ shells: edgeShells(results, manifest.routes, manifest.build?.subdomains ?? []),
2286
2318
  routes: manifest.routes,
2287
2319
  pathKey: pathKeyOf,
2288
2320
  build,
@@ -3085,7 +3117,23 @@ function registerApiRoute(absPath) {
3085
3117
  ` Export one named for the method it answers — export function GET(request: Request) — ` +
3086
3118
  `or delete the file. One of: ${API_METHODS.join(", ")}.`);
3087
3119
  }
3088
- apiRoutes.set(name, { name, absPath, methods });
3120
+ apiRoutes.set(name, { name, absPath, methods, ...crossOriginOf(absPath) });
3121
+ }
3122
+ /**
3123
+ * `export const crossOrigin = true` on a route.ts, read from the source as
3124
+ * revalidate is. `true` only: anything the build cannot read is refused,
3125
+ * since reading it as false would 403 every other site and reading it as true
3126
+ * would open a route nobody meant to.
3127
+ */
3128
+ export function crossOriginOf(file) {
3129
+ const declared = exportedConst(file, "crossOrigin");
3130
+ if (!declared)
3131
+ return {};
3132
+ const value = unwrapTypes(declared.init);
3133
+ if (value?.type !== "Literal" || typeof value.value !== "boolean") {
3134
+ throw new Error(`${file}: export const crossOrigin must be true or false. Found: ${declared.source}`);
3135
+ }
3136
+ return value.value ? { crossOrigin: true } : {};
3089
3137
  }
3090
3138
  /**
3091
3139
  * Whether a middleware.ts is a guard the engine runs, or only names guards
@@ -3775,6 +3823,7 @@ import { observeServed } from ${JSON.stringify(join(packageDir, "served"))}
3775
3823
  import { renderToReadableStream, decodeReply, decodeAction, decodeFormState, loadServerAction } from '@vitejs/plugin-rsc/rsc'
3776
3824
  import { isQuery, queryCacheControl, isQueryValidationError, queryRefusal } from ${JSON.stringify(join(packageDir, "query"))}
3777
3825
  import { isActionValidationError, isActionRefusal, isClientBuilt, turnedAwayStatus } from ${JSON.stringify(join(packageDir, "action"))}
3826
+ import { checkOf, checkOnly } from ${JSON.stringify(join(packageDir, "precognition"))}
3778
3827
  import { forgetCached } from ${JSON.stringify(join(packageDir, "cache"))}
3779
3828
  import { noteFallback as noteCaughtRead } from ${JSON.stringify(join(packageDir, "request"))}
3780
3829
  import { isOutdatedOptimizedDep, outdatedDepResponse } from ${JSON.stringify(join(packageDir, "devReload"))}
@@ -4160,6 +4209,8 @@ const HOST_GLOBAL = ${JSON.stringify(hostGlobal)}
4160
4209
  ? `Object.entries(${JSON.stringify(hostActions)}).map(([name, target]) => [(__rsc_host_actions as Record<string, unknown>)[name], target])`
4161
4210
  : ""}),
4162
4211
  inputs: ${JSON.stringify(formInputs(hostTypes, hostDefs))},
4212
+ // Which of them the backend can check without running - see checkOnly().
4213
+ validates: new Set<string>(${JSON.stringify(hostValidates)}),
4163
4214
  }
4164
4215
 
4165
4216
  /**
@@ -5819,6 +5870,20 @@ export async function handleAction(
5819
5870
  const args = (await decodeReply(decodable)) as unknown[]
5820
5871
  const action = await loadServerAction(actionId)
5821
5872
 
5873
+ // A check, not a submit: <Form> asking whether the fields it names would
5874
+ // pass, before anyone presses the button. The action's guards and validation run; its body never does,
5875
+ // and nothing is revalidated, because nothing was written.
5876
+ //
5877
+ // The mark rides in the form's own data rather than a header beside it, so
5878
+ // nothing can deliver the call without it. A header set for the next call
5879
+ // is missed by a call React sends a tick later, and a check that arrived
5880
+ // unmarked would be a submit.
5881
+ const checking = checkOf(args)
5882
+
5883
+ if (checking) {
5884
+ return { stream: renderToReadableStream({ __rscChecked: await checkOnly(action, args, checking) }, { onError: flightOnError }) }
5885
+ }
5886
+
5822
5887
  // A query reached the ACTION endpoint, which means it was called directly
5823
5888
  // rather than through fetchQuery — so it went out as a POST and none of the
5824
5889
  // reasons it was marked a read apply to it. It still works, which is the
@@ -7990,6 +8055,26 @@ export const SHUTDOWN_PLUGIN = `export default function rscKitShutdown() {
7990
8055
  process.once('SIGINT', stop)
7991
8056
  }
7992
8057
  `;
8058
+ /**
8059
+ * The Nitro rsc-kit is built against, and the oldest it runs on. Nitro 3
8060
+ * numbers its prereleases by date (3.0.YYMMDD-tag), and a semver peer range
8061
+ * cannot hold that: `>=3.0.261103-rc` refuses every later rc as a mismatch.
8062
+ */
8063
+ export const NITRO_VERSION = "3.0.261103-rc";
8064
+ /** What to say when an app's Nitro is older than NITRO_VERSION, or null. */
8065
+ export function nitroVersionProblem(version) {
8066
+ const day = (v) => /^3\.0\.(\d{6})(?:-|$)/.exec(v)?.[1];
8067
+ const found = version && day(version);
8068
+ // Plain 3.0.0 is not newer: it is an older release that npm sorts below the
8069
+ // dated ones, builds without complaint and answers 404 to every route (see
8070
+ // "Why nitro is pinned"). Only a 3.1 or a 4 would be past the dated ones.
8071
+ const later = /^(\d+)\.(\d+)\./.exec(version ?? "");
8072
+ const past = later !== null && (Number(later[1]) > 3 || (Number(later[1]) === 3 && Number(later[2]) >= 1));
8073
+ if (!version || past || (found && Number(found) >= Number(day(NITRO_VERSION))))
8074
+ return null;
8075
+ return (`[rsc-kit] nitro ${version} is older than ${NITRO_VERSION}, the version rsc-kit builds with. ` +
8076
+ `Set "nitro": "${NITRO_VERSION}" in package.json and install again.`);
8077
+ }
7993
8078
  /**
7994
8079
  * One dev-server restart at a time, and none lost.
7995
8080
  *
@@ -8184,6 +8269,9 @@ export function rscKit(options = {}) {
8184
8269
  nitro: {
8185
8270
  name: "rsc-kit",
8186
8271
  setup(nitro) {
8272
+ const outdated = nitroVersionProblem(nitro.meta?.version);
8273
+ if (outdated)
8274
+ throw new Error(outdated);
8187
8275
  if (nitro.options.dev)
8188
8276
  return;
8189
8277
  nitroPreset = nitro.options.preset ?? null;
@@ -8199,8 +8287,9 @@ export function rscKit(options = {}) {
8199
8287
  // entry of the server bundle, it is written beside the server's
8200
8288
  // `_ssr/rsc.mjs` and shares its chunks - without importing the entry
8201
8289
  // that imports instrumentation.ts.
8202
- nitro.hooks.hook("rollup:before", (_nitro, config) => {
8203
- if (!buildCommands().some((command) => !command.instrumented))
8290
+ nitro.hooks.hook("build:config", (_nitro, built) => {
8291
+ const config = built.rollup ?? built.rolldown;
8292
+ if (!config || !buildCommands().some((command) => !command.instrumented))
8204
8293
  return;
8205
8294
  const file = join(nitro.options.buildDir, "vite", "services", "rsc", BARE_COMMANDS_ENVIRONMENT + ".js");
8206
8295
  const input = config.input;
@@ -9078,7 +9167,7 @@ export function rscKit(options = {}) {
9078
9167
  // without the app - before the build id, which hashes the documents
9079
9168
  // this changes, and before the pages are packed into a module or the
9080
9169
  // assets. A server build only: an export has no edge in front of an app.
9081
- const listed = output !== "export" && clientOut ? edgeStatic(results, routes, shells.shells) : { static: [], left: [] };
9170
+ const listed = output !== "export" && clientOut ? edgeStatic(results, routes, shells.shells, subdomains) : { static: [], left: [] };
9082
9171
  const keyOf = new Map(results.map((r) => [contractPath(r.url), pathKeyOf(r.url)]));
9083
9172
  const statics = clientOut
9084
9173
  ? storedPayloadAssets(staticDir, clientOut, listed.static.map((path) => ({ path, key: keyOf.get(path) })).filter((page) => page.key))