@solidjs/start 2.0.0-rc.4 → 2.0.0-rc.5

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/CHANGELOG.md CHANGED
@@ -1,5 +1,45 @@
1
1
  # @solidjs/start
2
2
 
3
+ ## 2.0.0-rc.5
4
+
5
+ ### Minor Changes
6
+
7
+ - 4c803e5: Add `serialization.plugins` to configure custom Seroval plugins for server functions.
8
+
9
+ Values Seroval has no built-in support for (Mongo's `ObjectId`, Prisma's `Decimal`, `Temporal`, and other custom classes) previously threw when returned from or passed to a server function. Point the new option at a module whose default export is an array of plugins:
10
+
11
+ ```ts
12
+ // vite.config.ts
13
+ solidStart({
14
+ serialization: {
15
+ plugins: "src/seroval-plugins.ts",
16
+ },
17
+ });
18
+ ```
19
+
20
+ ```ts
21
+ // src/seroval-plugins.ts
22
+ import { createPlugin } from "@solidjs/start/serialization";
23
+ ```
24
+
25
+ The module is bundled into both the client and the server so both ends of a server function agree on the format, so it must not import server-only code. SolidStart's built-in plugins keep precedence. Only server-function and action payloads are affected; the SSR hydration payload is serialized by `solid-js/web`.
26
+
27
+ Also adds a `@solidjs/start/serialization` entrypoint re-exporting Seroval's `createPlugin`, `OpaqueReference`, and plugin types, so plugin authors stay on the same Seroval version SolidStart serializes with.
28
+
29
+ ### Patch Changes
30
+
31
+ - e117d91: Route module ids now end in the source extension, so ecosystem plugins apply inside `src/routes`.
32
+
33
+ Route files are imported through an id carrying the picked exports in the query (`routes/api.ts?pick=GET`), which left the id ending in the export name. Plugins whose filter is anchored on the file extension (`/\.[cm]?[jt]sx?$/`, the default for `unplugin-auto-import`, `unplugin-macros` and others) silently skipped every route file. The id now ends with a `lang.<ext>` marker, the same convention Vue SFCs use for `?vue&type=script&lang.ts`. Chunk filenames are unchanged.
34
+
35
+ - d8f1ea8: Apply the configured `nonce` to the two script tags that were still missing it, so a strict `script-src` CSP no longer needs `unsafe-inline`:
36
+
37
+ - The client-side redirect that streaming mode emits after the shell has already flushed (`<script>window.location=...</script>`) now carries the nonce.
38
+ - The SPA entry script tag now carries the nonce, matching the SSR entry script.
39
+
40
+ - 27fca88: Fix actions returning `json()` or `reload()` leaving no-JS form submissions stranded on the `/_server` endpoint. These responses carry a value rather than a destination, so the redirect issued for progressive-enhancement submissions had no `Location` header. It now falls back to the submitting page, and the response value is unwrapped into the flash cookie so `useSubmission().result` matches the JS path.
41
+ - 75debc3: Scope the built-in `~` alias to the app package, so files in other workspace packages can map `~` to their own root through an importer-aware plugin such as `vite-tsconfig-paths`. In stylesheets and asset URLs (CSS `@import`, `url()`, `new URL(..., import.meta.url)`) `~` still always means the app root, since Vite resolves those without running plugins.
42
+
3
43
  ## 2.0.0-rc.4
4
44
 
5
45
  ### Patch Changes
@@ -0,0 +1,7 @@
1
+ import { type Plugin } from "vite";
2
+ /**
3
+ * Provides SolidStart's `~` app-root alias without claiming module imports made
4
+ * by other workspace packages. Those packages may map `~` to their own root
5
+ * through an importer-aware resolver such as vite-tsconfig-paths.
6
+ */
7
+ export declare function appRootAlias(projectRoot: string, appRoot: string): Plugin;
@@ -0,0 +1,58 @@
1
+ import { existsSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, resolve } from "node:path";
3
+ import { normalizePath } from "vite";
4
+ /**
5
+ * `~/app.css`, `~/logo.svg`, ... but not `~/lib/api.ts` or `~/components/Counter`.
6
+ *
7
+ * CSS `@import`, `url()`, preprocessor imports and `new URL(..., import.meta.url)`
8
+ * are resolved by internal Vite resolvers that only run the alias plugin, never
9
+ * user plugins, so those ids can never reach `resolveId` below. Keeping non-module
10
+ * ids on a plain alias preserves `~` in stylesheets and asset URLs, where it always
11
+ * means the app root.
12
+ */
13
+ const NON_MODULE_ID = /^~\/([^?#]*\.(?![cm]?[jt]sx?(?:[?#]|$))[^./?#]+(?:[?#].*)?)$/;
14
+ /**
15
+ * Provides SolidStart's `~` app-root alias without claiming module imports made
16
+ * by other workspace packages. Those packages may map `~` to their own root
17
+ * through an importer-aware resolver such as vite-tsconfig-paths.
18
+ */
19
+ export function appRootAlias(projectRoot, appRoot) {
20
+ const appDir = normalizePath(resolve(projectRoot, appRoot));
21
+ const packageRoots = new Map();
22
+ /** Nearest directory at or above `directory` that holds a `package.json`. */
23
+ function packageRoot(directory) {
24
+ if (!packageRoots.has(directory)) {
25
+ const parent = dirname(directory);
26
+ packageRoots.set(directory, existsSync(join(directory, "package.json"))
27
+ ? directory
28
+ : parent === directory
29
+ ? undefined
30
+ : packageRoot(parent));
31
+ }
32
+ return packageRoots.get(directory);
33
+ }
34
+ const appPackage = packageRoot(appDir);
35
+ /** True only when the importer demonstrably belongs to another package. */
36
+ function isForeignImporter(importer) {
37
+ const file = normalizePath(importer.replace(/[?#].*$/s, ""));
38
+ if (!isAbsolute(file))
39
+ return false;
40
+ const owner = packageRoot(dirname(file));
41
+ return owner !== undefined && owner !== appPackage;
42
+ }
43
+ return {
44
+ name: "solid-start:app-root-alias",
45
+ enforce: "pre",
46
+ config() {
47
+ return { resolve: { alias: [{ find: NON_MODULE_ID, replacement: `${appDir}/$1` }] } };
48
+ },
49
+ async resolveId(id, importer, options) {
50
+ if (id !== "~" && !id.startsWith("~/"))
51
+ return null;
52
+ if (importer && isForeignImporter(importer))
53
+ return null;
54
+ const target = join(appDir, id.slice(1));
55
+ return (await this.resolve(target, importer, { ...options, skipSelf: true })) ?? target;
56
+ },
57
+ };
58
+ }
@@ -5,6 +5,7 @@ export declare const VIRTUAL_MODULES: {
5
5
  readonly getClientManifest: "solid-start:get-client-manifest";
6
6
  readonly getManifest: "solid-start:get-manifest";
7
7
  readonly middleware: "solid-start:middleware";
8
+ readonly serovalPlugins: "solid-start:seroval-plugins";
8
9
  readonly serverFnManifest: "solid-start:server-fn-manifest";
9
10
  readonly clientEntry: "solid-start:client-entry";
10
11
  readonly serverEntry: "solid-start:server-entry";
@@ -5,6 +5,7 @@ export const VIRTUAL_MODULES = {
5
5
  getClientManifest: "solid-start:get-client-manifest",
6
6
  getManifest: "solid-start:get-manifest",
7
7
  middleware: "solid-start:middleware",
8
+ serovalPlugins: "solid-start:seroval-plugins",
8
9
  serverFnManifest: "solid-start:server-fn-manifest",
9
10
  clientEntry: "solid-start:client-entry",
10
11
  serverEntry: "solid-start:server-entry",
@@ -1,6 +1,6 @@
1
1
  import { relative } from "node:path";
2
2
  import { fileSystemWatcher } from "./fs-watcher.js";
3
- import { treeShake } from "./tree-shake.js";
3
+ import { toPickId, treeShake } from "./tree-shake.js";
4
4
  export const moduleId = "solid-start:routes";
5
5
  export function fsRoutes({ routers }) {
6
6
  globalThis.ROUTERS = routers;
@@ -24,7 +24,7 @@ export function fsRoutes({ routers }) {
24
24
  if (v === undefined)
25
25
  return undefined;
26
26
  if (k.startsWith("$$")) {
27
- const buildId = `${v.src}?${v.pick.map((p) => `pick=${p}`).join("&")}`;
27
+ const buildId = toPickId(v.src, v.pick);
28
28
  /**
29
29
  * @type {{ [key: string]: string }}
30
30
  */
@@ -40,7 +40,7 @@ export function fsRoutes({ routers }) {
40
40
  };
41
41
  }
42
42
  else if (k.startsWith("$")) {
43
- const buildId = `${v.src}?${v.pick.map((p) => `pick=${p}`).join("&")}`;
43
+ const buildId = toPickId(v.src, v.pick);
44
44
  return {
45
45
  src: relative(root, buildId),
46
46
  build: isBuild ? `_$() => import('${buildId}')$_` : undefined,
@@ -1,2 +1,29 @@
1
1
  import type { Plugin } from "vite";
2
+ /**
3
+ * Builds the module id used to import a subset of a route file's exports.
4
+ *
5
+ * The `pick` list has to live in the query so that the same file can be
6
+ * instantiated once per export subset (the client picks `default`/`$css`,
7
+ * the server picks its HTTP handlers). That query would otherwise leave the
8
+ * id ending in `?pick=GET`, which silently excludes route files from any
9
+ * plugin whose filter is anchored on the file extension -- a very common
10
+ * default, e.g. unplugin-macros' `/\.[cm]?[jt]sx?$/`.
11
+ *
12
+ * The trailing `lang.<ext>` marker is the same convention Vue SFCs use
13
+ * (`?vue&type=script&lang.ts`) and puts a real extension back at the end of
14
+ * the id, so those filters match again.
15
+ *
16
+ * @see https://github.com/solidjs/solid-start/issues/1918
17
+ */
18
+ export declare function toPickId(src: string, pick: string[]): string;
19
+ /**
20
+ * Rolldown's default chunk name sanitizer, plus a pass that drops the
21
+ * `?pick=...&lang` tail so route chunks keep the short, stable filenames they
22
+ * had before the `lang` marker was introduced (`index-<hash>.js`, not
23
+ * `index.tsx_pick_default_pick__css_lang-<hash>.js`). Client chunk filenames
24
+ * are public URLs, so this is not purely cosmetic.
25
+ *
26
+ * @see https://github.com/rollup/rollup/blob/master/src/utils/sanitizeFileName.ts
27
+ */
28
+ export declare function sanitizeChunkFileName(name: string): string;
2
29
  export declare function treeShake(): Plugin;
@@ -1,7 +1,52 @@
1
1
  // All credit for this work goes to the amazing Next.js team.
2
2
  // https://github.com/vercel/next.js/blob/canary/packages/next/build/babel/plugins/next-ssg-transform.ts
3
3
  // This is adapted to work with routeData functions. It can be run in two modes, one which preserves the routeData and the Component in the same file, and one which creates a
4
- import { basename } from "pathe";
4
+ import { basename, extname } from "pathe";
5
+ const PICKABLE_EXTENSIONS = ["js", "jsx", "ts", "tsx"];
6
+ /**
7
+ * Builds the module id used to import a subset of a route file's exports.
8
+ *
9
+ * The `pick` list has to live in the query so that the same file can be
10
+ * instantiated once per export subset (the client picks `default`/`$css`,
11
+ * the server picks its HTTP handlers). That query would otherwise leave the
12
+ * id ending in `?pick=GET`, which silently excludes route files from any
13
+ * plugin whose filter is anchored on the file extension -- a very common
14
+ * default, e.g. unplugin-macros' `/\.[cm]?[jt]sx?$/`.
15
+ *
16
+ * The trailing `lang.<ext>` marker is the same convention Vue SFCs use
17
+ * (`?vue&type=script&lang.ts`) and puts a real extension back at the end of
18
+ * the id, so those filters match again.
19
+ *
20
+ * @see https://github.com/solidjs/solid-start/issues/1918
21
+ */
22
+ export function toPickId(src, pick) {
23
+ const query = pick.map(p => `pick=${p}`).join("&");
24
+ const ext = extname(src).slice(1);
25
+ return PICKABLE_EXTENSIONS.includes(ext) ? `${src}?${query}&lang.${ext}` : `${src}?${query}`;
26
+ }
27
+ /**
28
+ * Matches the tail that {@link toPickId} appends, as it appears in a chunk
29
+ * name. Rolldown derives a chunk name from the module id by taking the
30
+ * basename minus its extension, so `index.tsx?pick=default&pick=$css&lang.tsx`
31
+ * arrives here as `index.tsx?pick=default&pick=$css&lang`.
32
+ */
33
+ const PICK_CHUNK_NAME_RE = /\.[cm]?[jt]sx?\?pick=[^?]*&lang$/;
34
+ const INVALID_CHAR_RE = /[\u0000-\u001F"#$&*+,:;<=>?[\]^`{|}\u007F]/g;
35
+ const DRIVE_LETTER_RE = /^[a-z]:/i;
36
+ /**
37
+ * Rolldown's default chunk name sanitizer, plus a pass that drops the
38
+ * `?pick=...&lang` tail so route chunks keep the short, stable filenames they
39
+ * had before the `lang` marker was introduced (`index-<hash>.js`, not
40
+ * `index.tsx_pick_default_pick__css_lang-<hash>.js`). Client chunk filenames
41
+ * are public URLs, so this is not purely cosmetic.
42
+ *
43
+ * @see https://github.com/rollup/rollup/blob/master/src/utils/sanitizeFileName.ts
44
+ */
45
+ export function sanitizeChunkFileName(name) {
46
+ const stripped = name.replace(PICK_CHUNK_NAME_RE, "");
47
+ const driveLetter = DRIVE_LETTER_RE.exec(stripped)?.[0] ?? "";
48
+ return driveLetter + stripped.slice(driveLetter.length).replace(INVALID_CHAR_RE, "_");
49
+ }
5
50
  function treeShakeTransform({ types: t }) {
6
51
  function getIdentifier(path) {
7
52
  const parentPath = path.parentPath;
@@ -86,6 +86,29 @@ export interface SolidStartOptions {
86
86
  * @default "json"
87
87
  */
88
88
  mode?: "js" | "json";
89
+ /**
90
+ * Path to a module whose default export is an array of custom Seroval
91
+ * plugins, used to serialize values Seroval doesn't understand natively
92
+ * (ORM id types, decimals, `Temporal`, and other custom classes).
93
+ *
94
+ * Build plugins with `createPlugin` from `seroval`. The module is bundled
95
+ * into both the client and the server so that both ends of a server
96
+ * function agree on the format, so it must not import server-only code.
97
+ *
98
+ * SolidStart's built-in plugins take precedence: Seroval uses the first
99
+ * plugin whose `test()` passes, and these are appended after the built-ins.
100
+ *
101
+ * A plugin's `deserialize` rebuilds the value under {@link mode} `"json"`.
102
+ * `serialize` is only used by `mode: "js"`, where the payload is evaluated
103
+ * on the client and may therefore reference globals only, not the plugin
104
+ * module's own imports.
105
+ *
106
+ * Only applies to server-function and action payloads. The SSR hydration
107
+ * payload is serialized by `solid-js/web` and is unaffected.
108
+ *
109
+ * @example "src/seroval-plugins.ts"
110
+ */
111
+ plugins?: string;
89
112
  };
90
113
  /**
91
114
  * Configures plugin behavior per build environment
@@ -3,12 +3,14 @@ import { globSync } from "node:fs";
3
3
  import { basename, extname, isAbsolute, join } from "node:path";
4
4
  import solid from "vite-plugin-solid";
5
5
  import { serverFunctionsPlugin } from "../directives/index.js";
6
+ import { appRootAlias } from "./app-root-alias.js";
6
7
  import { boundaryModules } from "./boundary-modules.js";
7
8
  import { DEFAULT_EXTENSIONS, VIRTUAL_MODULES, VITE_ENVIRONMENTS } from "./constants.js";
8
9
  import { devServer } from "./dev-server.js";
9
10
  import { envPlugin } from "./env.js";
10
11
  import { SolidStartClientFileRouter, SolidStartServerFileRouter } from "./fs-router.js";
11
12
  import { fsRoutes } from "./fs-routes/index.js";
13
+ import { sanitizeChunkFileName, toPickId } from "./fs-routes/tree-shake.js";
12
14
  import lazy from "./lazy.js";
13
15
  import { manifest } from "./manifest.js";
14
16
  import { parseIdQuery } from "./utils.js";
@@ -71,17 +73,23 @@ export function solidStart(options) {
71
73
  for (const route of await clientRouter.getRoutes()) {
72
74
  for (const [key, value] of Object.entries(route)) {
73
75
  if (value && key.startsWith("$") && !key.startsWith("$$")) {
74
- function toRouteId(route) {
75
- return `${route.src}?${route.pick.map((p) => `pick=${p}`).join("&")}`;
76
- }
77
- clientInput.push(toRouteId(value));
76
+ clientInput.push(toPickId(value.src, value.pick));
78
77
  }
79
78
  }
80
79
  }
81
80
  }
82
81
  return {
83
82
  appType: "custom",
84
- build: { assetsDir: "_build/assets" },
83
+ build: {
84
+ assetsDir: "_build/assets",
85
+ rollupOptions: {
86
+ output: {
87
+ // Keeps route chunks named after their file rather than after
88
+ // the `?pick=...` id that addresses them. See toPickId.
89
+ sanitizeFileName: sanitizeChunkFileName,
90
+ },
91
+ },
92
+ },
85
93
  optimizeDeps: {
86
94
  // Suppress TS errors from Vite 7 types when configuring Vite 8's Rolldown
87
95
  ...{
@@ -126,7 +134,6 @@ export function solidStart(options) {
126
134
  resolve: {
127
135
  alias: {
128
136
  "@solidjs/start/server/entry": handlers.server,
129
- "~": join(process.cwd(), start.appRoot),
130
137
  ...(!start.ssr
131
138
  ? {
132
139
  "@solidjs/start/server": "@solidjs/start/server/spa",
@@ -175,6 +182,7 @@ export function solidStart(options) {
175
182
  };
176
183
  },
177
184
  },
185
+ appRootAlias(root, start.appRoot),
178
186
  manifest(start),
179
187
  fsRoutes({
180
188
  routers: {
@@ -28,6 +28,12 @@ export function manifest(start) {
28
28
  return await this.resolve(start.middleware);
29
29
  return `\0${VIRTUAL_MODULES.middleware}`;
30
30
  }
31
+ if (id === VIRTUAL_MODULES.serovalPlugins) {
32
+ const plugins = start.serialization?.plugins;
33
+ if (plugins)
34
+ return await this.resolve(plugins);
35
+ return `\0${VIRTUAL_MODULES.serovalPlugins}`;
36
+ }
31
37
  },
32
38
  async load(id) {
33
39
  if (id === `\0${VIRTUAL_MODULES.clientViteManifest}`) {
@@ -76,6 +82,8 @@ export function manifest(start) {
76
82
  }
77
83
  else if (id === `\0${VIRTUAL_MODULES.middleware}`)
78
84
  return "export default {};";
85
+ else if (id === `\0${VIRTUAL_MODULES.serovalPlugins}`)
86
+ return "export default [];";
79
87
  else if (id.startsWith("/@manifest")) {
80
88
  if (this.environment.mode !== "dev")
81
89
  throw new Error("@manifest queries are only allowed in dev");
@@ -109,7 +109,7 @@ export async function handleServerFunction(h3Event) {
109
109
  }
110
110
  // handle no JS success case
111
111
  if (!instance)
112
- return handleNoJS(result, request, parsed);
112
+ return await handleNoJS(result, request, parsed);
113
113
  const body = getHeadersAndBody(result);
114
114
  if (body) {
115
115
  return new Response(body.body, {
@@ -146,7 +146,7 @@ export async function handleServerFunction(h3Event) {
146
146
  h3Event.res.headers.set("X-Error", toHeaderValue(error));
147
147
  }
148
148
  else {
149
- x = handleNoJS(x, request, parsed, true);
149
+ x = await handleNoJS(x, request, parsed, true);
150
150
  }
151
151
  if (instance) {
152
152
  const body = getHeadersAndBody(x);
@@ -181,7 +181,20 @@ function toHeaderValue(value) {
181
181
  return "true";
182
182
  }
183
183
  }
184
- function handleNoJS(result, request, parsed, thrown) {
184
+ function getRefererLocation(request, url) {
185
+ const referer = request.headers.get("referer");
186
+ try {
187
+ if (referer)
188
+ return new URL(referer).toString();
189
+ }
190
+ catch {
191
+ // fall through to the app root below
192
+ }
193
+ // no usable referer (e.g. a no-referrer policy): the app root still beats
194
+ // leaving the browser sitting on the server function endpoint
195
+ return new URL(import.meta.env.BASE_URL, url.origin).toString();
196
+ }
197
+ async function handleNoJS(result, request, parsed, thrown) {
185
198
  const url = new URL(request.url);
186
199
  const isError = result instanceof Error;
187
200
  let statusCode = 302;
@@ -192,10 +205,19 @@ function handleNoJS(result, request, parsed, thrown) {
192
205
  headers.set(`Location`, new URL(result.headers.get("Location"), url.origin + import.meta.env.BASE_URL).toString());
193
206
  statusCode = getExpectedRedirectStatus(result);
194
207
  }
208
+ else {
209
+ // responses that carry a value rather than a destination (json(), reload())
210
+ // still have to send the browser back to the page the form came from
211
+ headers.set("Location", getRefererLocation(request, url));
212
+ }
213
+ // the body is dropped from the redirect, so don't advertise its type
214
+ headers.delete("Content-Type");
215
+ // mirror the JS path: the flash cookie carries the value, not the Response
216
+ result = result.customBody ? await result.customBody() : null;
195
217
  }
196
218
  else
197
219
  headers = new Headers({
198
- Location: new URL(request.headers.get("referer")).toString(),
220
+ Location: getRefererLocation(request, url),
199
221
  });
200
222
  if (result) {
201
223
  headers.append("Set-Cookie", `flash=${encodeURIComponent(JSON.stringify({
@@ -203,7 +225,9 @@ function handleNoJS(result, request, parsed, thrown) {
203
225
  result: isError ? result.message : result,
204
226
  thrown: thrown,
205
227
  error: isError,
206
- input: [...parsed.slice(0, -1), [...parsed[parsed.length - 1].entries()]],
228
+ input: parsed.length
229
+ ? [...parsed.slice(0, -1), [...parsed[parsed.length - 1].entries()]]
230
+ : [],
207
231
  }))}; Secure; HttpOnly;`);
208
232
  }
209
233
  return new Response(null, {
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Re-exports Seroval's plugin authoring API for use with the
3
+ * `serialization.plugins` option in `vite.config.ts`.
4
+ *
5
+ * Importing from here rather than depending on `seroval` directly keeps plugin
6
+ * authors on the exact Seroval version SolidStart serializes with. A mismatched
7
+ * version would not fail the build: it would produce plugin nodes the other end
8
+ * of the wire can't interpret.
9
+ *
10
+ * @see https://github.com/solidjs/solid-start/issues/1474
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * // src/seroval-plugins.ts
15
+ * import { createPlugin } from "@solidjs/start/serialization";
16
+ * import { ObjectId } from "mongodb";
17
+ *
18
+ * const ObjectIdPlugin = createPlugin<ObjectId, { hex: any }>({
19
+ * tag: "app/ObjectId",
20
+ * test: value => value instanceof ObjectId,
21
+ * parse: {
22
+ * sync: (value, ctx) => ({ hex: ctx.parse(value.toHexString()) }),
23
+ * async: async (value, ctx) => ({ hex: await ctx.parse(value.toHexString()) }),
24
+ * stream: (value, ctx) => ({ hex: ctx.parse(value.toHexString()) }),
25
+ * },
26
+ * serialize: (node, ctx) => `globalThis.ObjectId(${ctx.serialize(node.hex)})`,
27
+ * deserialize: (node, ctx) => new ObjectId(ctx.deserialize(node.hex) as string),
28
+ * });
29
+ *
30
+ * export default [ObjectIdPlugin];
31
+ * ```
32
+ */
33
+ export { createPlugin, OpaqueReference } from "seroval";
34
+ export type { AsyncParsePluginContext, DeserializePluginContext, Plugin, PluginData, PluginInfo, SerializePluginContext, SerovalNode, StreamParsePluginContext, SyncParsePluginContext, } from "seroval";
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Re-exports Seroval's plugin authoring API for use with the
3
+ * `serialization.plugins` option in `vite.config.ts`.
4
+ *
5
+ * Importing from here rather than depending on `seroval` directly keeps plugin
6
+ * authors on the exact Seroval version SolidStart serializes with. A mismatched
7
+ * version would not fail the build: it would produce plugin nodes the other end
8
+ * of the wire can't interpret.
9
+ *
10
+ * @see https://github.com/solidjs/solid-start/issues/1474
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * // src/seroval-plugins.ts
15
+ * import { createPlugin } from "@solidjs/start/serialization";
16
+ * import { ObjectId } from "mongodb";
17
+ *
18
+ * const ObjectIdPlugin = createPlugin<ObjectId, { hex: any }>({
19
+ * tag: "app/ObjectId",
20
+ * test: value => value instanceof ObjectId,
21
+ * parse: {
22
+ * sync: (value, ctx) => ({ hex: ctx.parse(value.toHexString()) }),
23
+ * async: async (value, ctx) => ({ hex: await ctx.parse(value.toHexString()) }),
24
+ * stream: (value, ctx) => ({ hex: ctx.parse(value.toHexString()) }),
25
+ * },
26
+ * serialize: (node, ctx) => `globalThis.ObjectId(${ctx.serialize(node.hex)})`,
27
+ * deserialize: (node, ctx) => new ObjectId(ctx.deserialize(node.hex) as string),
28
+ * });
29
+ *
30
+ * export default [ObjectIdPlugin];
31
+ * ```
32
+ */
33
+ export { createPlugin, OpaqueReference } from "seroval";
@@ -1,6 +1,6 @@
1
1
  import { crossSerializeStream, deserialize, Feature, fromCrossJSON, getCrossReferenceHeader, toCrossJSONStream, } from "seroval";
2
2
  import { AbortSignalPlugin, CustomEventPlugin, DOMExceptionPlugin, EventPlugin, FormDataPlugin, HeadersPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLPlugin, URLSearchParamsPlugin, } from "seroval-plugins/web";
3
- // TODO(Alexis): if we can, allow providing an option to extend these.
3
+ import userPlugins from "solid-start:seroval-plugins";
4
4
  const DEFAULT_PLUGINS = [
5
5
  AbortSignalPlugin,
6
6
  CustomEventPlugin,
@@ -14,6 +14,16 @@ const DEFAULT_PLUGINS = [
14
14
  URLSearchParamsPlugin,
15
15
  URLPlugin,
16
16
  ];
17
+ /**
18
+ * Plugins from `serialization.plugins` are appended rather than prepended:
19
+ * seroval picks the first plugin whose `test()` passes, so the built-ins win
20
+ * and a loose user `test()` can't take over `Request`/`FormData`/`URL`.
21
+ *
22
+ * The same list has to be used on both ends of a server function, which is why
23
+ * this comes from a virtual module bundled into the client and the server
24
+ * rather than a runtime option.
25
+ */
26
+ const PLUGINS = [...DEFAULT_PLUGINS, ...userPlugins];
17
27
  const MAX_SERIALIZATION_DEPTH_LIMIT = 64;
18
28
  const DISABLED_FEATURES = Feature.RegExp;
19
29
  /**
@@ -67,7 +77,7 @@ export function serializeToJSStream(id, value) {
67
77
  crossSerializeStream(value, {
68
78
  scopeId: id,
69
79
  disabledFeatures: JS_SERIALIZE_DISABLED_FEATURES,
70
- plugins: DEFAULT_PLUGINS,
80
+ plugins: PLUGINS,
71
81
  onSerialize(data, initial) {
72
82
  controller.enqueue(createChunk(initial ? `(${getCrossReferenceHeader(id)},${data})` : data));
73
83
  },
@@ -87,7 +97,7 @@ export function serializeToJSONStream(value) {
87
97
  toCrossJSONStream(value, {
88
98
  disabledFeatures: SERIALIZE_DISABLED_FEATURES,
89
99
  depthLimit: MAX_SERIALIZATION_DEPTH_LIMIT,
90
- plugins: DEFAULT_PLUGINS,
100
+ plugins: PLUGINS,
91
101
  onParse(node) {
92
102
  controller.enqueue(createChunk(JSON.stringify(node)));
93
103
  },
@@ -200,7 +210,7 @@ export async function deserializeJSONStream(response) {
200
210
  refs,
201
211
  disabledFeatures: DISABLED_FEATURES,
202
212
  depthLimit: MAX_SERIALIZATION_DEPTH_LIMIT,
203
- plugins: DEFAULT_PLUGINS,
213
+ plugins: PLUGINS,
204
214
  });
205
215
  return value;
206
216
  }
@@ -171,9 +171,17 @@ function handleStreamCompleteRedirect(context) {
171
171
  return ({ write }) => {
172
172
  context.complete = true;
173
173
  const to = context.response && context.response.headers.get("Location");
174
- to && write(`<script>window.location=${JSON.stringify(to).replace(/</g, "\\u003c")}</script>`);
174
+ if (!to)
175
+ return;
176
+ // The shell has already flushed, so the redirect has to happen client side.
177
+ // Carry the nonce so a strict `script-src` CSP doesn't block it.
178
+ const nonce = context.nonce ? ` nonce="${escapeAttribute(context.nonce)}"` : "";
179
+ write(`<script${nonce}>window.location=${JSON.stringify(to).replace(/</g, "\\u003c")}</script>`);
175
180
  };
176
181
  }
182
+ function escapeAttribute(value) {
183
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
184
+ }
177
185
  function stripBaseUrl(path) {
178
186
  const base = import.meta.env.SERVER_BASE_URL || import.meta.env.BASE_URL || "/";
179
187
  return stripPathBase(path, base);
@@ -18,7 +18,7 @@ export function StartServer(props) {
18
18
  <TopErrorBoundary>
19
19
  <props.document scripts={<>
20
20
  <PatchVirtualDevStyles nonce={nonce}/>
21
- <script type="module" src={getSsrManifest("client").path(import.meta.env.START_CLIENT_ENTRY_URL)}/>
21
+ <script type="module" nonce={nonce} src={getSsrManifest("client").path(import.meta.env.START_CLIENT_ENTRY_URL)}/>
22
22
  </>}/>
23
23
  </TopErrorBoundary>
24
24
  </NoHydration>);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solidjs/start",
3
- "version": "2.0.0-rc.4",
3
+ "version": "2.0.0-rc.5",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/solidjs/solid-start.git",
@@ -24,7 +24,8 @@
24
24
  "./http": "./dist/http/index.js",
25
25
  "./env": "./env.d.ts",
26
26
  "./fns/server": "./dist/fns/server.js",
27
- "./fns/client": "./dist/fns/client.js"
27
+ "./fns/client": "./dist/fns/client.js",
28
+ "./serialization": "./dist/fns/plugins.js"
28
29
  },
29
30
  "publishConfig": {
30
31
  "access": "public"