@crombolo/crombolo 0.36.2 → 0.37.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/crombolo",
3
- "version": "0.36.2",
3
+ "version": "0.37.0",
4
4
  "crombolo": {
5
5
  "migrations": "compatible"
6
6
  },
@@ -35,6 +35,12 @@
35
35
  "./bundle": "./src/bundle.ts",
36
36
  "./host": "./src/host.ts",
37
37
  "./branding": "./src/branding.ts",
38
+ "./navigation": "./src/navigation.ts",
39
+ "./headers": "./src/headers.ts",
40
+ "./server": "./src/server.ts",
41
+ "./middleware": "./src/middleware.ts",
42
+ "./routes": "./src/routes.ts",
43
+ "./islands-react": "./src/islands-react.ts",
38
44
  "./jsx-runtime": "./src/jsx-runtime.ts",
39
45
  "./jsx-dev-runtime": "./src/jsx-runtime.ts",
40
46
  "./loose/jsx-runtime": "./src/loose/jsx-runtime.ts",
@@ -49,19 +55,32 @@
49
55
  "NOTICE"
50
56
  ],
51
57
  "dependencies": {
52
- "@crombolo/api-delivery": "0.36.2",
53
- "@crombolo/api-management": "0.36.2",
54
- "@crombolo/auth": "0.36.2",
58
+ "@crombolo/api-delivery": "0.37.0",
59
+ "@crombolo/api-management": "0.37.0",
60
+ "@crombolo/auth": "0.37.0",
55
61
  "@crombolo/backoffice-dist": "18.2.0",
56
- "@crombolo/backoffice-host": "0.36.2",
57
- "@crombolo/cli": "0.36.2",
58
- "@crombolo/content": "0.36.2",
59
- "@crombolo/contracts": "0.36.2",
60
- "@crombolo/core": "0.36.2",
61
- "@crombolo/data": "0.36.2",
62
- "@crombolo/render": "0.36.2",
63
- "@crombolo/schema": "0.36.2",
64
- "@crombolo/server": "0.36.2",
65
- "@crombolo/transfer": "0.36.2"
62
+ "@crombolo/backoffice-host": "0.37.0",
63
+ "@crombolo/cli": "0.37.0",
64
+ "@crombolo/common": "0.37.0",
65
+ "@crombolo/content": "0.37.0",
66
+ "@crombolo/contracts": "0.37.0",
67
+ "@crombolo/core": "0.37.0",
68
+ "@crombolo/data": "0.37.0",
69
+ "@crombolo/render": "0.37.0",
70
+ "@crombolo/schema": "0.37.0",
71
+ "@crombolo/server": "0.37.0",
72
+ "@crombolo/transfer": "0.37.0"
73
+ },
74
+ "peerDependencies": {
75
+ "react": ">=19",
76
+ "react-dom": ">=19"
77
+ },
78
+ "peerDependenciesMeta": {
79
+ "react": {
80
+ "optional": true
81
+ },
82
+ "react-dom": {
83
+ "optional": true
84
+ }
66
85
  }
67
86
  }
package/src/bundle.ts CHANGED
@@ -6,6 +6,14 @@
6
6
  * A wired bundle is trusted code in the server process; this is a stability
7
7
  * boundary, not a sandbox.
8
8
  */
9
+
10
+ export {
11
+ type RouteContext,
12
+ type RouteHandler,
13
+ type RouteMethod,
14
+ type RouteOptions,
15
+ route,
16
+ } from '@crombolo/common'
9
17
  export {
10
18
  assertBundleTables,
11
19
  type BundleStep,
@@ -18,8 +26,6 @@ export {
18
26
  } from '@crombolo/data'
19
27
  export type {
20
28
  AppAlias,
21
- BackofficeBundleRoute,
22
- BundleAudience,
23
29
  BundleCaller,
24
30
  BundleCapability,
25
31
  BundleDocuments,
@@ -37,21 +43,16 @@ export type {
37
43
  BundleMediaRefusal,
38
44
  BundleMediaUpdate,
39
45
  BundleMember,
40
- BundleMemberRequest,
41
46
  BundleMethod,
42
- BundlePublicRequest,
43
- BundleRateLimit,
44
47
  BundleRedirectInput,
45
48
  BundleRedirectRule,
46
49
  BundleRedirects,
47
- BundleRequest,
50
+ BundleRoute,
51
+ BundleRouteContext,
48
52
  BundleSection,
49
53
  ExtensionSectionAlias,
50
54
  ImageLocation,
51
- MemberBundleRoute,
52
55
  Principal,
53
56
  ProviderOverrideInput,
54
- PublicBundleRoute,
55
57
  ServerBundle,
56
- ServerBundleRoute,
57
58
  } from '@crombolo/server'
package/src/headers.ts ADDED
@@ -0,0 +1,14 @@
1
+ /** The request a page renders for, mirroring `next/headers` (story 206). */
2
+ export {
3
+ cookies,
4
+ headers,
5
+ type ReadonlyHeaders,
6
+ type ReadonlyRequestCookies,
7
+ type RequestCookie,
8
+ } from '@crombolo/render/headers'
9
+
10
+ // Decision 8 of story 209: a browser that loads this has been handed server code.
11
+ if (typeof document !== 'undefined')
12
+ throw new Error(
13
+ "@crombolo/crombolo/headers only runs on the server; a 'use client' component cannot import it.",
14
+ )
package/src/index.ts CHANGED
@@ -51,7 +51,9 @@ export type {
51
51
  MediaWithCrops,
52
52
  Menu,
53
53
  MenuItem,
54
+ Metadata,
54
55
  Navigation,
56
+ PageOutcome,
55
57
  PageProps,
56
58
  PublishedContent,
57
59
  PublishedElement,
@@ -61,6 +63,7 @@ export type {
61
63
  RedirectTo,
62
64
  RequestMember,
63
65
  SearchOptions,
66
+ SearchParams,
64
67
  SearchResult,
65
68
  SearchResults,
66
69
  SeoHeadProps,
@@ -76,6 +79,9 @@ export {
76
79
  externalSignInUrl,
77
80
  Form,
78
81
  formAction,
82
+ Island,
83
+ type IslandLoad,
84
+ type IslandProps,
79
85
  type ProviderProps,
80
86
  redirect,
81
87
  SeoHead,
@@ -212,12 +218,10 @@ export type {
212
218
  BundleRedirectRule,
213
219
  BundleRedirects,
214
220
  BundleReload,
215
- BundleRequest,
216
221
  BundleSection,
217
222
  Principal,
218
223
  ReloadedBundle,
219
224
  ServerBundle,
220
- ServerBundleRoute,
221
225
  } from '@crombolo/server'
222
226
  /** @deprecated Import it from `@crombolo/crombolo/host`. */
223
227
  /** @deprecated Import it from `@crombolo/crombolo/host`. */
@@ -0,0 +1,28 @@
1
+ /**
2
+ * What the browser runs to mount a `'use client'` island with React (story
3
+ * 209): the one part of `@crombolo/crombolo` that is bundled for the browser.
4
+ * Crombolo's island build includes it; a site building islands with Vite lists
5
+ * it among its inputs. React is the site's own.
6
+ */
7
+ import { type ComponentType, createElement } from 'react'
8
+ import { createRoot } from 'react-dom/client'
9
+
10
+ /** Renders the component into the island, with the server-rendered children as its `children`. */
11
+ export function mount(
12
+ component: ComponentType<Record<string, unknown>>,
13
+ element: Element,
14
+ props: Record<string, unknown>,
15
+ childrenHtml: string | null,
16
+ ): void {
17
+ const children =
18
+ childrenHtml === null
19
+ ? undefined
20
+ : createElement('div', {
21
+ style: { display: 'contents' },
22
+ dangerouslySetInnerHTML: { __html: childrenHtml },
23
+ })
24
+ element.replaceChildren()
25
+ createRoot(element).render(
26
+ createElement(component, children === undefined ? props : { ...props, children }),
27
+ )
28
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * A site's middleware (story 210): the contract from `@crombolo/common`, bound
3
+ * to crombolo's own types, and `fromNextMiddleware`, which brings a Next.js
4
+ * middleware into the chain as one link.
5
+ */
6
+ import {
7
+ type Middleware as CommonMiddleware,
8
+ type MiddlewareContext as CommonMiddlewareContext,
9
+ type MiddlewareHandler as CommonMiddlewareHandler,
10
+ type CookieOptions,
11
+ type Matcher,
12
+ rewrite,
13
+ } from '@crombolo/common'
14
+ import type { PublishedContent, RequestMember, SiteServices } from '@crombolo/render'
15
+
16
+ export {
17
+ type CookieOptions,
18
+ type Matcher,
19
+ type MatcherCondition,
20
+ type MiddlewareStage,
21
+ type ReadonlyRequestCookies,
22
+ type RequestCookie,
23
+ rewrite,
24
+ withCookie,
25
+ } from '@crombolo/common'
26
+
27
+ /** A middleware for this site: `site()` gives its services, `page` and `member` crombolo's own. */
28
+ export type Middleware = CommonMiddleware<SiteServices, PublishedContent, RequestMember>
29
+ export type MiddlewareHandler = CommonMiddlewareHandler<
30
+ SiteServices,
31
+ PublishedContent,
32
+ RequestMember
33
+ >
34
+ export type MiddlewareContext = CommonMiddlewareContext<
35
+ SiteServices,
36
+ PublishedContent,
37
+ RequestMember
38
+ >
39
+
40
+ /** What a Next.js-style middleware is handed: the request, with `nextUrl` and `cookies`. */
41
+ export type NextRequest = Request & {
42
+ nextUrl: URL
43
+ cookies: {
44
+ get(name: string): { name: string; value: string } | undefined
45
+ getAll(): Array<{ name: string; value: string }>
46
+ has(name: string): boolean
47
+ }
48
+ }
49
+
50
+ interface Marks {
51
+ next?: true
52
+ rewrite?: string | URL
53
+ requestHeaders?: Headers
54
+ }
55
+
56
+ const marks = new WeakMap<Response, Marks>()
57
+
58
+ /** A Next.js-style answer: `next()`, `redirect()`, `rewrite()` and `json()`, with cookies to set. */
59
+ export class NextResponse extends Response {
60
+ readonly cookies = {
61
+ set: (name: string, value: string, options: CookieOptions = {}) => {
62
+ const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${options.path ?? '/'}`]
63
+ if (options.maxAge !== undefined) parts.push(`Max-Age=${Math.floor(options.maxAge)}`)
64
+ if (options.expires) parts.push(`Expires=${options.expires.toUTCString()}`)
65
+ if (options.domain) parts.push(`Domain=${options.domain}`)
66
+ if (options.secure ?? true) parts.push('Secure')
67
+ if (options.httpOnly ?? true) parts.push('HttpOnly')
68
+ parts.push(`SameSite=${options.sameSite ?? 'Lax'}`)
69
+ this.headers.append('set-cookie', parts.join('; '))
70
+ return this.cookies
71
+ },
72
+ delete: (name: string) => this.cookies.set(name, '', { maxAge: 0 }),
73
+ }
74
+
75
+ /** Carry on, optionally with the request's headers replaced for what follows. */
76
+ static next(init: { request?: { headers?: Headers }; headers?: HeadersInit } = {}): NextResponse {
77
+ const response = new NextResponse(null, { headers: init.headers })
78
+ marks.set(response, {
79
+ next: true,
80
+ ...(init.request?.headers ? { requestHeaders: new Headers(init.request.headers) } : {}),
81
+ })
82
+ return response
83
+ }
84
+
85
+ /** Render another path of this site at the address asked for. */
86
+ static rewrite(
87
+ url: string | URL,
88
+ init: { request?: { headers?: Headers }; headers?: HeadersInit } = {},
89
+ ): NextResponse {
90
+ const response = new NextResponse(null, { headers: init.headers })
91
+ marks.set(response, {
92
+ rewrite: url,
93
+ ...(init.request?.headers ? { requestHeaders: new Headers(init.request.headers) } : {}),
94
+ })
95
+ return response
96
+ }
97
+
98
+ static override redirect(url: string | URL, status = 307): NextResponse {
99
+ return new NextResponse(null, { status, headers: { location: String(url) } })
100
+ }
101
+
102
+ static override json(body: unknown, init?: ResponseInit): NextResponse {
103
+ const headers = new Headers(init?.headers)
104
+ if (!headers.has('content-type')) headers.set('content-type', 'application/json')
105
+ return new NextResponse(JSON.stringify(body), { ...init, headers })
106
+ }
107
+ }
108
+
109
+ /** A Next.js-style middleware: the request in, a response (or nothing, to carry on) out. */
110
+ export type NextMiddleware = (
111
+ request: NextRequest,
112
+ ) => Response | undefined | Promise<Response | undefined>
113
+
114
+ function nextRequestOf(request: Request, context: MiddlewareContext): NextRequest {
115
+ const copy = new Request(request)
116
+ const read = () => context.cookies
117
+ return Object.assign(copy, {
118
+ nextUrl: new URL(request.url),
119
+ cookies: {
120
+ get: (name: string) => read().get(name),
121
+ getAll: () => read().getAll(),
122
+ has: (name: string) => read().has(name),
123
+ },
124
+ })
125
+ }
126
+
127
+ /**
128
+ * A Next.js middleware as one link in the chain: `NextResponse.next()` carries
129
+ * on, `rewrite()` renders another path of this site, `redirect()` and any
130
+ * other response answer outright, and headers and cookies set on a
131
+ * `NextResponse` reach the final answer.
132
+ */
133
+ export function fromNextMiddleware(
134
+ middleware: NextMiddleware,
135
+ options: { name?: string; matcher?: Matcher | Matcher[] } = {},
136
+ ): Middleware {
137
+ return {
138
+ name: options.name ?? (middleware.name || 'next middleware'),
139
+ ...(options.matcher ? { matcher: options.matcher } : {}),
140
+ async handle(request, next, context) {
141
+ const answer = await middleware(nextRequestOf(request, context))
142
+ if (!answer) return next()
143
+ const marked = marks.get(answer)
144
+ if (!marked) return answer
145
+ let forward = marked.requestHeaders
146
+ ? new Request(request, { headers: marked.requestHeaders })
147
+ : request
148
+ if (marked.rewrite !== undefined) {
149
+ const target = new URL(String(marked.rewrite), request.url)
150
+ if (target.origin !== new URL(request.url).origin)
151
+ throw new Error(`A rewrite goes to a path on this site, not to ${target.origin}.`)
152
+ forward = rewrite(forward, `${target.pathname}${target.search}`)
153
+ }
154
+ const inner = await next(forward)
155
+ const headers = new Headers(inner.headers)
156
+ for (const [name, value] of answer.headers)
157
+ if (name !== 'set-cookie') headers.set(name, value)
158
+ for (const cookie of answer.headers.getSetCookie()) headers.append('set-cookie', cookie)
159
+ return new Response(inner.body, {
160
+ status: inner.status,
161
+ statusText: inner.statusText,
162
+ headers,
163
+ })
164
+ },
165
+ }
166
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Ending a page early, mirroring `next/navigation` (story 206): each function
3
+ * throws, from any component, layout or block, and the page answers its status.
4
+ */
5
+ export {
6
+ badRequest,
7
+ forbidden,
8
+ foundAt,
9
+ gone,
10
+ movedPermanentlyTo,
11
+ notFound,
12
+ permanentRedirect,
13
+ redirect,
14
+ rethrow,
15
+ seeOther,
16
+ unauthorized,
17
+ unprocessableContent,
18
+ } from '@crombolo/render/navigation'
19
+
20
+ // Decision 8 of story 209: a browser that loads this has been handed server code.
21
+ if (typeof document !== 'undefined')
22
+ throw new Error(
23
+ "@crombolo/crombolo/navigation only runs on the server; a 'use client' component cannot import it.",
24
+ )
package/src/routes.ts ADDED
@@ -0,0 +1,72 @@
1
+ /**
2
+ * A site's route handlers (story 211): the contract from `@crombolo/common`,
3
+ * bound to crombolo's types, and `fromRouteModule`, which takes a Next.js-style
4
+ * route module (exports `GET`, `POST`, …) as one route.
5
+ */
6
+ import {
7
+ type RouteContext as CommonRouteContext,
8
+ type RouteHandler as CommonRouteHandler,
9
+ type SiteRoute as CommonSiteRoute,
10
+ route as commonRoute,
11
+ ROUTE_METHODS,
12
+ type RouteMethod,
13
+ type RouteOptions,
14
+ } from '@crombolo/common'
15
+ import type { RequestMember, SiteServices } from '@crombolo/render'
16
+
17
+ export {
18
+ type CookieOptions,
19
+ type FieldError,
20
+ Outcome,
21
+ ok,
22
+ ROUTE_METHODS,
23
+ type RouteMethod,
24
+ type RouteOptions,
25
+ } from '@crombolo/common'
26
+
27
+ /** What a site's handler is given: `site()` gives its services, `member()` the signed-in member. */
28
+ export type RouteContext = CommonRouteContext<SiteServices, RequestMember>
29
+ export type RouteHandler = CommonRouteHandler<SiteServices, RequestMember>
30
+ export type SiteRoute = CommonSiteRoute<SiteServices, RequestMember>
31
+
32
+ /** A route on this site: `route('/api/records/:species', { GET: list, POST: add })`. */
33
+ export function route(
34
+ path: string,
35
+ handlers: Partial<Record<RouteMethod, RouteHandler>>,
36
+ options: RouteOptions = {},
37
+ ): SiteRoute {
38
+ return commonRoute<SiteServices, RequestMember>(path, handlers, options)
39
+ }
40
+
41
+ /** A Next.js route module's handler: the request, and `{ params }` as a promise. */
42
+ type NextRouteHandler = (
43
+ request: Request,
44
+ context: { params: Promise<Record<string, string>> },
45
+ ) => Response | Promise<Response>
46
+
47
+ /**
48
+ * A Next.js-style route module as a route: each exported method becomes its
49
+ * handler, given `{ params }` as Next.js does. `export const csrf = false` and
50
+ * the other options may be exported beside them, or passed here.
51
+ */
52
+ export function fromRouteModule(
53
+ path: string,
54
+ module: Partial<Record<RouteMethod, NextRouteHandler>> & Record<string, unknown>,
55
+ options: RouteOptions = {},
56
+ ): SiteRoute {
57
+ const handlers: Partial<Record<RouteMethod, RouteHandler>> = {}
58
+ for (const method of ROUTE_METHODS) {
59
+ const handler = module[method]
60
+ if (typeof handler === 'function')
61
+ handlers[method] = (request, context) =>
62
+ (handler as NextRouteHandler)(request, { params: Promise.resolve(context.params) })
63
+ }
64
+ const exported: RouteOptions = {
65
+ ...(typeof module.csrf === 'boolean' ? { csrf: module.csrf } : {}),
66
+ ...(module.rateLimit !== undefined
67
+ ? { rateLimit: module.rateLimit as RouteOptions['rateLimit'] }
68
+ : {}),
69
+ ...(module.members !== undefined ? { members: module.members as RouteOptions['members'] } : {}),
70
+ }
71
+ return commonRoute<SiteServices, RequestMember>(path, handlers, { ...exported, ...options })
72
+ }
package/src/server.ts ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The site's own services for page code (story 206): `site()`, acting as the
3
+ * visitor, and the `Result` its services return.
4
+ */
5
+ export {
6
+ assertSafeLocation,
7
+ type FieldError,
8
+ isOk,
9
+ isOutcome,
10
+ type MatchHandlers,
11
+ Ok,
12
+ Outcome,
13
+ type OutcomeStatus,
14
+ ok,
15
+ type RedirectStatus,
16
+ type RefusalStatus,
17
+ Result,
18
+ } from '@crombolo/core'
19
+ export {
20
+ type SiteMedia,
21
+ type SiteMembers,
22
+ type SiteServices,
23
+ type SiteSql,
24
+ site,
25
+ } from '@crombolo/render'
26
+
27
+ // Decision 8 of story 209: a browser that loads this has been handed server code.
28
+ if (typeof document !== 'undefined')
29
+ throw new Error(
30
+ "@crombolo/crombolo/server only runs on the server; a 'use client' component cannot import it.",
31
+ )