@tschk/moonshine-next 0.4.1 → 0.4.49

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/README.md CHANGED
@@ -96,8 +96,15 @@ Behavioural notes where moonshine deliberately differs from Next:
96
96
  moonshine only scrolls when the pathname or hash actually changes, so
97
97
  query-only navigation (filters, pagination, tabs) keeps your scroll position.
98
98
  Pass `scroll` explicitly to force either behaviour.
99
- - **`router.refresh()` and `router.prefetch()` are no-ops.** Moonshine
100
- re-renders from its signal graph; there is no server round trip to invalidate.
99
+ - **`router.refresh()` reloads the browser document.** This requests fresh
100
+ server output and resets local component state. State-preserving RSC refresh
101
+ is unsupported. It is safe to call during SSR, where it does nothing.
102
+ - **`router.prefetch()` is a no-op.** Use `Link` for browser prefetch hints.
103
+ - **Browser navigation stays with the browser.** Links preserve external URLs,
104
+ non-self targets, fragments and downloads without route prefetch. External
105
+ `router.push` uses document assignment; external `replace` replaces the history
106
+ entry. Same-origin absolute URLs retain SPA navigation. The existing safe-href
107
+ policy prevents executable schemes from reaching document navigation.
101
108
  - **`redirect()` / `notFound()`** throw `RedirectError` / `NotFoundError`,
102
109
  exported from `./navigation` so your renderer can catch them.
103
110
  - **`useSearchParams()`** reads the live query string. The moonshine router
@@ -126,8 +133,10 @@ Be aware of these before migrating — none of them are stubbed to silently
126
133
  - **No file-system routing conventions.** `layout.tsx`, `loading.tsx`,
127
134
  `error.tsx`, `template.tsx`, route groups, parallel and intercepting routes
128
135
  are not interpreted. Use the moonshine router.
129
- - **No `next/headers` mutation.** `cookies()` is read-only — no `set()` or
130
- `delete()`. `draftMode()` always reports disabled.
136
+ - **Bounded cookie mutation.** `cookies().set()` and `.delete()` use the opt-in
137
+ request response-header scope on Bun/Node. `headers()` has no response mutation
138
+ API, and `draftMode()` always reports disabled. Streaming Server Actions and
139
+ Next's render-phase restrictions are not implemented.
131
140
  - **Other `next/*` modules are absent**, including `next/server`
132
141
  (`NextRequest` / `NextResponse`), `next/og`, `next/cache`, and
133
142
  `next/navigation`'s `unstable_*` APIs. Route Handlers take and return plain
@@ -137,3 +146,25 @@ Does **not** export `MoonshineRouter` from the client entry — import it from
137
146
  `@tschk/moonshine/router` if you want the moonshine router directly.
138
147
 
139
148
  See [Moonshine README](../../README.md).
149
+
150
+ Request helpers require `requestContext: true` in Moonshine config (enabled by
151
+ Next adoption). Bun/Node deployment and preview inject the runner from the same
152
+ compiled bundle as the route modules; a separately imported context cannot scope
153
+ an already-bundled route. Edge request context is currently unsupported.
154
+
155
+ `cookies()` retains synchronous reads (`await cookies()` also works). With
156
+ `requestContext: true`, loaders, actions and buffered rendering can call
157
+ `set(name, value, options)` or `set({name, value, ...options})`. Values are
158
+ percent-encoded; invalid names and attributes reject before changing headers or
159
+ same-request reads. The default path is `/`. Each write appends a separate
160
+ `Set-Cookie`; later writes to the same name update the shared request-local jar.
161
+ Ordinary incoming cookies still read without a response scope; mutation requires
162
+ one. This does not install a Next runtime.
163
+
164
+ `delete(name)` expires the root-path cookie. Use `delete({name, path, domain})`
165
+ for another scope; the incoming Cookie header cannot reveal a cookie's original
166
+ path or domain. Deletion leaves an empty tombstone in same-request reads; the
167
+ browser applies expiration on receipt. Signed/encrypted sessions, domain ownership
168
+ checks, cookie prefix policies, streaming and Next cache invalidation are outside
169
+ this API. Standard expiry, age, security, SameSite, priority and partitioned
170
+ attributes are serialized; browser acceptance still follows browser policy.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tschk/moonshine-next",
3
- "version": "0.4.1",
3
+ "version": "0.4.49",
4
4
  "description": "Next.js API surface reimplemented on moonshine — drop Next, keep the imports",
5
5
  "license": "ISC",
6
6
  "type": "module",
@@ -21,9 +21,10 @@
21
21
  "./shaders": "./src/shaders.ts"
22
22
  },
23
23
  "dependencies": {
24
- "@tschk/moonshine": "^0.4.1",
25
- "@tschk/moonshine-router": "^0.4.1",
26
- "@tschk/moonshine-shaders": "^0.4.1"
24
+ "@tschk/moonshine": "^0.4.48",
25
+ "@tschk/moonshine-router": "^0.4.48",
26
+ "@tschk/moonshine-shaders": "^0.4.48",
27
+ "@tschk/moonshine-framework": "^0.4.48"
27
28
  },
28
29
  "peerDependencies": {
29
30
  "react": ">=18",
@@ -43,5 +44,13 @@
43
44
  "lint": "bunx oxlint .",
44
45
  "typecheck": "bunx tsc --noEmit",
45
46
  "test": "bun test"
47
+ },
48
+ "peerDependenciesMeta": {
49
+ "react": {
50
+ "optional": true
51
+ },
52
+ "react-dom": {
53
+ "optional": true
54
+ }
46
55
  }
47
56
  }
package/src/headers.ts CHANGED
@@ -8,17 +8,14 @@
8
8
  * import { headers, cookies } from "@tschk/moonshine-next/headers";
9
9
  * ```
10
10
  */
11
- import { AsyncLocalStorage } from "node:async_hooks";
12
-
13
- const store = new AsyncLocalStorage<Request>();
14
-
15
- /** Runs `fn` with `request` visible to `headers()` and `cookies()`. */
16
- export function runWithRequest<T>(request: Request, fn: () => T): T {
17
- return store.run(request, fn);
18
- }
11
+ import {
12
+ getRequest,
13
+ getResponseHeaders,
14
+ } from "@tschk/moonshine-framework/request";
15
+ export { runWithRequest } from "@tschk/moonshine-framework/request";
19
16
 
20
17
  function current(): Request {
21
- const request = store.getStore();
18
+ const request = getRequest();
22
19
  if (!request) {
23
20
  throw new Error(
24
21
  "headers() was called outside a request. Wrap the render in runWithRequest().",
@@ -40,24 +37,162 @@ function parseCookies(header: string | null): Map<string, string> {
40
37
  const index = part.indexOf("=");
41
38
  if (index === -1) continue;
42
39
  const name = part.slice(0, index).trim();
43
- if (name) jar.set(name, decodeURIComponent(part.slice(index + 1).trim()));
40
+ if (!name) continue;
41
+ const raw = part.slice(index + 1).trim();
42
+ let value = raw;
43
+ try {
44
+ value = decodeURIComponent(raw);
45
+ } catch {
46
+ // Cookie values may contain literal percent signs or invalid URI sequences.
47
+ }
48
+ jar.set(name, value);
44
49
  }
45
50
  return jar;
46
51
  }
47
52
 
48
- export function cookies(): {
53
+ export type CookieOptions = {
54
+ domain?: string;
55
+ path?: string;
56
+ expires?: Date;
57
+ maxAge?: number;
58
+ secure?: boolean;
59
+ httpOnly?: boolean;
60
+ sameSite?: boolean | "lax" | "strict" | "none";
61
+ priority?: "low" | "medium" | "high";
62
+ partitioned?: boolean;
63
+ };
64
+ export type CookieStore = {
49
65
  get(name: string): CookieEntry | undefined;
50
- getAll(): CookieEntry[];
66
+ getAll(name?: string): CookieEntry[];
51
67
  has(name: string): boolean;
52
- } {
53
- const jar = parseCookies(current().headers.get("cookie"));
68
+ set(name: string, value: string, options?: CookieOptions): void;
69
+ set(cookie: CookieEntry & CookieOptions): void;
70
+ delete(
71
+ cookie:
72
+ string | ({ name: string } & Pick<CookieOptions, "path" | "domain">),
73
+ ): void;
74
+ };
75
+
76
+ const responseJars = new WeakMap<Headers, Map<string, string>>();
77
+ function serializeCookie(
78
+ name: string,
79
+ value: string,
80
+ options: CookieOptions,
81
+ ): string {
82
+ if (typeof name !== "string" || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name))
83
+ throw new TypeError("Invalid cookie name");
84
+ if (typeof value !== "string")
85
+ throw new TypeError("Cookie value must be a string");
86
+ const allowed = [
87
+ "domain",
88
+ "path",
89
+ "expires",
90
+ "maxAge",
91
+ "secure",
92
+ "httpOnly",
93
+ "sameSite",
94
+ "priority",
95
+ "partitioned",
96
+ ];
97
+ if (
98
+ !options ||
99
+ typeof options !== "object" ||
100
+ Object.keys(options).some((key) => !allowed.includes(key))
101
+ )
102
+ throw new TypeError("Unsupported cookie options");
103
+ for (const key of ["secure", "httpOnly", "partitioned"] as const)
104
+ if (options[key] !== undefined && typeof options[key] !== "boolean")
105
+ throw new TypeError("Cookie flags must be boolean");
106
+ const parts = [name + "=" + encodeURIComponent(value)];
107
+ if (options.domain !== undefined) {
108
+ if (
109
+ typeof options.domain !== "string" ||
110
+ !/^\.?(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*$/.test(
111
+ options.domain,
112
+ )
113
+ )
114
+ throw new TypeError("Invalid cookie domain");
115
+ parts.push("Domain=" + options.domain);
116
+ }
117
+ const path = options.path ?? "/";
118
+ if (typeof path !== "string" || !/^[\x20-\x3a\x3c-\x7e]*$/.test(path))
119
+ throw new TypeError("Invalid cookie path");
120
+ if (path) parts.push("Path=" + path);
121
+ if (options.expires !== undefined) {
122
+ if (
123
+ !(options.expires instanceof Date) ||
124
+ !Number.isFinite(options.expires.getTime())
125
+ )
126
+ throw new TypeError("Invalid cookie expiry");
127
+ parts.push("Expires=" + options.expires.toUTCString());
128
+ }
129
+ if (options.maxAge !== undefined) {
130
+ if (!Number.isSafeInteger(options.maxAge))
131
+ throw new TypeError("Invalid cookie maxAge");
132
+ parts.push("Max-Age=" + options.maxAge);
133
+ }
134
+ if (options.secure) parts.push("Secure");
135
+ if (options.httpOnly) parts.push("HttpOnly");
136
+ if (options.sameSite !== undefined && options.sameSite !== false) {
137
+ const policy = options.sameSite === true ? "strict" : options.sameSite;
138
+ if (!["lax", "strict", "none"].includes(policy))
139
+ throw new TypeError("Invalid cookie sameSite");
140
+ parts.push("SameSite=" + policy[0]!.toUpperCase() + policy.slice(1));
141
+ }
142
+ if (options.priority !== undefined) {
143
+ if (!["low", "medium", "high"].includes(options.priority))
144
+ throw new TypeError("Invalid cookie priority");
145
+ parts.push(
146
+ "Priority=" +
147
+ options.priority[0]!.toUpperCase() +
148
+ options.priority.slice(1),
149
+ );
150
+ }
151
+ if (options.partitioned) parts.push("Partitioned");
152
+ return parts.join("; ");
153
+ }
154
+
155
+ export function cookies(): CookieStore {
156
+ const request = current();
157
+ const sink = getResponseHeaders();
158
+ let jar = sink && responseJars.get(sink);
159
+ if (!jar) {
160
+ jar = parseCookies(request.headers.get("cookie"));
161
+ if (sink) responseJars.set(sink, jar);
162
+ }
163
+ const values = jar;
164
+ function set(
165
+ name: string | (CookieEntry & CookieOptions),
166
+ value?: string,
167
+ options: CookieOptions = {},
168
+ ): void {
169
+ if (!sink)
170
+ throw new Error("Cookie mutation requires a response request scope");
171
+ if (typeof name !== "string") {
172
+ const { name: key, value: next, ...rest } = name;
173
+ set(key, next, rest);
174
+ return;
175
+ }
176
+ const serialized = serializeCookie(name, value!, options);
177
+ sink.append("set-cookie", serialized);
178
+ values.set(name, value!);
179
+ }
54
180
  return {
55
181
  get: (name) => {
56
- const value = jar.get(name);
182
+ const value = values.get(name);
57
183
  return value === undefined ? undefined : { name, value };
58
184
  },
59
- getAll: () => [...jar].map(([name, value]) => ({ name, value })),
60
- has: (name) => jar.has(name),
185
+ getAll: (filter) =>
186
+ [...values]
187
+ .filter(([key]) => filter === undefined || key === filter)
188
+ .map(([name, value]) => ({ name, value })),
189
+ has: (name) => values.has(name),
190
+ set,
191
+ delete: (cookie) => {
192
+ const { name, ...options } =
193
+ typeof cookie === "string" ? { name: cookie } : cookie;
194
+ set(name, "", { ...options, expires: new Date(0), maxAge: 0 });
195
+ },
61
196
  };
62
197
  }
63
198
 
package/src/link.ts CHANGED
@@ -17,7 +17,7 @@ import {
17
17
  type MouseEvent,
18
18
  type ReactNode,
19
19
  } from "react";
20
- import { isExternal, navigate } from "@tschk/moonshine/router";
20
+ import { isExternal, useNavigate } from "@tschk/moonshine/router";
21
21
 
22
22
  export type LinkProps = Omit<
23
23
  AnchorHTMLAttributes<HTMLAnchorElement>,
@@ -85,8 +85,9 @@ export default function Link({
85
85
  onMouseEnter,
86
86
  ...rest
87
87
  }: LinkProps): ReactNode {
88
+ const navigate = useNavigate();
88
89
  const url = hrefToString(href);
89
- const external = isExternal(url, rest.target);
90
+ const external = isExternal(url, rest.target, rest.download);
90
91
  const ref = useRef<HTMLAnchorElement>(null);
91
92
  // Navigation runs in a transition so a slow subtree cannot block the click.
92
93
  const [, startTransition] = useTransition();
package/src/navigation.ts CHANGED
@@ -8,8 +8,9 @@
8
8
  * ```
9
9
  */
10
10
  import { useMemo } from "react";
11
+ import { safeHref } from "@tschk/moonshine-router";
11
12
  import {
12
- navigate,
13
+ useNavigate as useMoonshineNavigate,
13
14
  useLocation,
14
15
  useParams as useMoonshineParams,
15
16
  } from "@tschk/moonshine/router";
@@ -32,17 +33,9 @@ export function splitLocation(location: string): [string, string] {
32
33
  : [location.slice(0, index), location.slice(index + 1)];
33
34
  }
34
35
 
35
- /**
36
- * The location signal carries the query, so the signal is the source of truth
37
- * and a query-only navigation re-renders. The browser fallback remains for the
38
- * one case the signal cannot cover: a controlled `path` prop given without a
39
- * query while the address bar has one.
40
- */
36
+ /** The scoped location signal is the source of truth for query state. */
41
37
  function readSearch(location: string): string {
42
- const [, fromSignal] = splitLocation(location);
43
- if (fromSignal) return fromSignal;
44
- if (typeof window === "undefined") return "";
45
- return window.location.search.replace(/^\?/, "");
38
+ return splitLocation(location)[1];
46
39
  }
47
40
 
48
41
  function shouldScrollByDefault(href: string): boolean {
@@ -54,27 +47,39 @@ function shouldScrollByDefault(href: string): boolean {
54
47
  );
55
48
  }
56
49
 
50
+ function navigateExternal(href: string, replace: boolean): boolean {
51
+ if (typeof window === "undefined") return false;
52
+ const url = new URL(safeHref(href), window.location.href);
53
+ if (url.origin === window.location.origin) return false;
54
+ if (replace) window.location.replace(url.href);
55
+ else window.location.assign(url.href);
56
+ return true;
57
+ }
58
+
57
59
  export function useRouter(): AppRouterInstance {
60
+ const navigate = useMoonshineNavigate();
58
61
  return useMemo(
59
62
  () => ({
60
63
  push: (href, options) => {
64
+ if (navigateExternal(href, false)) return;
61
65
  const jump = options?.scroll ?? shouldScrollByDefault(href);
62
66
  navigate(href);
63
67
  if (jump) globalThis.scrollTo?.(0, 0);
64
68
  },
65
69
  replace: (href, options) => {
70
+ if (navigateExternal(href, true)) return;
66
71
  const jump = options?.scroll ?? shouldScrollByDefault(href);
67
72
  navigate(href, { replace: true });
68
73
  if (jump) globalThis.scrollTo?.(0, 0);
69
74
  },
70
75
  back: () => globalThis.history?.back(),
71
76
  forward: () => globalThis.history?.forward(),
72
- // Moonshine re-renders from its signal graph, so there is no server
73
- // round trip to invalidate.
74
- refresh: () => {},
77
+ // Reload server data through a document request; local component state resets.
78
+ // State-preserving RSC refresh is not supported.
79
+ refresh: () => globalThis.location?.reload(),
75
80
  prefetch: () => {},
76
81
  }),
77
- [],
82
+ [navigate],
78
83
  );
79
84
  }
80
85