@surfaces-ui/next 0.0.0-stage → 0.5.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Surfaces UI
2
+ Copyright 2026 Josh Schoen
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
package/README.md CHANGED
@@ -1,3 +1,27 @@
1
- # Temporary Holding Version
1
+ <!-- Generated by scripts/package-readmes.mjs from package.json. Edit the script, not this file. -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @surfaces-ui/next
4
+
5
+ Serve Surfaces UI pages from a Next.js app: routes, metadata and server-rendered pages, with Next.js doing the routing, building and hosting.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @surfaces-ui/next next react react-dom
11
+ ```
12
+
13
+ `next` and `react` and `react-dom` are peer dependencies: your app provides them.
14
+
15
+ ## Part of Surfaces UI
16
+
17
+ Surfaces UI is a UI library for data and analytics: exploring schemas, querying, charting, tables at scale, chat, and pages an agent can build.
18
+
19
+ Every Surfaces UI package is released at the same version; install them all at that one version, since mixing releases is not supported.
20
+
21
+ - [The guides on surfaces-ui.com](https://surfaces-ui.com/#docs)
22
+ - [Getting started](https://github.com/teradata-labs/surfaces-ui/blob/main/docs/getting-started.md)
23
+ - [Building with an agent](https://github.com/teradata-labs/surfaces-ui/blob/main/docs/agent-integration.md)
24
+ - [Styling](https://github.com/teradata-labs/surfaces-ui/blob/main/docs/styling.md)
25
+ - [Source for this package](https://github.com/teradata-labs/surfaces-ui/tree/main/packages/next)
26
+
27
+ Licensed under Apache-2.0. See LICENSE and NOTICE.
@@ -0,0 +1,23 @@
1
+ import { type RouteParams } from "./params.js";
2
+ import { type ImageResolver, type PageData } from "./prepare.js";
3
+ import { type SiteRoutes } from "./routes.js";
4
+ export interface SitePageProps {
5
+ site: SiteRoutes;
6
+ /** The `params` Next.js gives the page. */
7
+ params: RouteParams;
8
+ /** The name of the catch-all segment, as for `siteParams`. Default "route". */
9
+ param?: string;
10
+ /** Data for the page, worked out on the server and merged over its own. */
11
+ data?: PageData;
12
+ /** Turns an image name a page uses into an address on the site. */
13
+ resolveImage?: ImageResolver;
14
+ /** Origins an image may also come from as written. */
15
+ imageOrigins?: string[];
16
+ }
17
+ /**
18
+ * The page of a site for an address, as a server component: `export default function Page({ params }) { return
19
+ * <SitePage site={site} params={params} /> }` in `app/[[...route]]/page.tsx`. An address the site does not have is
20
+ * Next.js's 404 (`notFound`). A page the catalog refuses stops the build, or the request, with what is wrong, so a
21
+ * static export never ships a broken page.
22
+ */
23
+ export declare function SitePage({ site, params, param, data, resolveImage, imageOrigins }: SitePageProps): Promise<import("react").JSX.Element>;
@@ -0,0 +1,22 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { notFound } from "next/navigation";
3
+ import { assertPage } from "./check.js";
4
+ import { SiteSurface } from "./client.js";
5
+ import { segmentsOf } from "./params.js";
6
+ import { preparePage } from "./prepare.js";
7
+ import { matchRoute } from "./routes.js";
8
+ /**
9
+ * The page of a site for an address, as a server component: `export default function Page({ params }) { return
10
+ * <SitePage site={site} params={params} /> }` in `app/[[...route]]/page.tsx`. An address the site does not have is
11
+ * Next.js's 404 (`notFound`). A page the catalog refuses stops the build, or the request, with what is wrong, so a
12
+ * static export never ships a broken page.
13
+ */
14
+ export async function SitePage({ site, params, param, data, resolveImage, imageOrigins }) {
15
+ const match = matchRoute(site, await segmentsOf(params, param));
16
+ if (!match)
17
+ notFound();
18
+ const prepared = await preparePage(site, match, { data, resolveImage });
19
+ assertPage(prepared.page, `on "${match.entry.route}"`);
20
+ return _jsx(SiteSurface, { page: prepared.page, images: prepared.images, imageOrigins: imageOrigins });
21
+ }
22
+ //# sourceMappingURL=SitePage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SitePage.js","sourceRoot":"","sources":["../src/SitePage.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAoB,UAAU,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EAAqC,WAAW,EAAE,MAAM,cAAc,CAAC;AAC9E,OAAO,EAAmB,UAAU,EAAE,MAAM,aAAa,CAAC;AAgB1D;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,YAAY,EAAiB;IACrG,MAAM,KAAK,GAAG,UAAU,CAAC,IAAI,EAAE,MAAM,UAAU,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;IAChE,IAAI,CAAC,KAAK;QAAE,QAAQ,EAAE,CAAC;IACvB,MAAM,QAAQ,GAAG,MAAM,WAAW,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;IACxE,UAAU,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,KAAK,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC;IACvD,OAAO,KAAC,WAAW,IAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,YAAY,EAAE,YAAY,GAAI,CAAC;AACnG,CAAC","sourcesContent":["import { notFound } from \"next/navigation\";\nimport { assertPage } from \"./check.js\";\nimport { SiteSurface } from \"./client.js\";\nimport { type RouteParams, segmentsOf } from \"./params.js\";\nimport { type ImageResolver, type PageData, preparePage } from \"./prepare.js\";\nimport { type SiteRoutes, matchRoute } from \"./routes.js\";\n\nexport interface SitePageProps {\n site: SiteRoutes;\n /** The `params` Next.js gives the page. */\n params: RouteParams;\n /** The name of the catch-all segment, as for `siteParams`. Default \"route\". */\n param?: string;\n /** Data for the page, worked out on the server and merged over its own. */\n data?: PageData;\n /** Turns an image name a page uses into an address on the site. */\n resolveImage?: ImageResolver;\n /** Origins an image may also come from as written. */\n imageOrigins?: string[];\n}\n\n/**\n * The page of a site for an address, as a server component: `export default function Page({ params }) { return\n * <SitePage site={site} params={params} /> }` in `app/[[...route]]/page.tsx`. An address the site does not have is\n * Next.js's 404 (`notFound`). A page the catalog refuses stops the build, or the request, with what is wrong, so a\n * static export never ships a broken page.\n */\nexport async function SitePage({ site, params, param, data, resolveImage, imageOrigins }: SitePageProps) {\n const match = matchRoute(site, await segmentsOf(params, param));\n if (!match) notFound();\n const prepared = await preparePage(site, match, { data, resolveImage });\n assertPage(prepared.page, `on \"${match.entry.route}\"`);\n return <SiteSurface page={prepared.page} images={prepared.images} imageOrigins={imageOrigins} />;\n}\n"]}
@@ -0,0 +1,22 @@
1
+ import type { PageDocument } from "@surfaces-ui/spec";
2
+ import type { ThemeRequest } from "@surfaces-ui/tokens";
3
+ import { type ImageResolver } from "./prepare.js";
4
+ export interface SurfaceSectionProps {
5
+ /** The components to draw, as a page document: written by hand, by an agent, or kept in a store. */
6
+ page: PageDocument;
7
+ /** Data for the page's bindings, worked out on the server and merged over its own. Plain JSON. */
8
+ data?: Record<string, unknown>;
9
+ /** A theme the page's own is laid over. Without either, the section is drawn in the default theme, or in the app's
10
+ * own `ThemeProvider` when one is above it. */
11
+ theme?: ThemeRequest;
12
+ /** Turns an image name the page uses into an address on the site. */
13
+ resolveImage?: ImageResolver;
14
+ /** Origins an image may also come from as written. */
15
+ imageOrigins?: string[];
16
+ }
17
+ /**
18
+ * Surfaces components as one part of a Next.js page the app writes itself, as a server component: the app's own
19
+ * markup around it, any number on one page. It is rendered to HTML on the server and themed only in its own region,
20
+ * so the rest of the page keeps the app's look. A page the catalog refuses stops the build with what is wrong.
21
+ */
22
+ export declare function SurfaceSection({ page, data, theme, resolveImage, imageOrigins }: SurfaceSectionProps): import("react").JSX.Element;
@@ -0,0 +1,15 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { assertPage } from "./check.js";
3
+ import { SiteSurface } from "./client.js";
4
+ import { prepareDocument } from "./prepare.js";
5
+ /**
6
+ * Surfaces components as one part of a Next.js page the app writes itself, as a server component: the app's own
7
+ * markup around it, any number on one page. It is rendered to HTML on the server and themed only in its own region,
8
+ * so the rest of the page keeps the app's look. A page the catalog refuses stops the build with what is wrong.
9
+ */
10
+ export function SurfaceSection({ page, data, theme, resolveImage, imageOrigins }) {
11
+ const prepared = prepareDocument(page, { data, theme, resolveImage });
12
+ assertPage(prepared.page, `"${page.id}"`);
13
+ return _jsx(SiteSurface, { page: prepared.page, images: prepared.images, imageOrigins: imageOrigins });
14
+ }
15
+ //# sourceMappingURL=SurfaceSection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SurfaceSection.js","sourceRoot":"","sources":["../src/SurfaceSection.tsx"],"names":[],"mappings":";AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAsB,eAAe,EAAE,MAAM,cAAc,CAAC;AAgBnE;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,YAAY,EAAE,YAAY,EAAuB;IACnG,MAAM,QAAQ,GAAG,eAAe,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC;IACtE,UAAU,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,IAAI,CAAC,EAAE,GAAG,CAAC,CAAC;IAC1C,OAAO,KAAC,WAAW,IAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,YAAY,EAAE,YAAY,GAAI,CAAC;AACnG,CAAC","sourcesContent":["import type { PageDocument } from \"@surfaces-ui/spec\";\nimport type { ThemeRequest } from \"@surfaces-ui/tokens\";\nimport { assertPage } from \"./check.js\";\nimport { SiteSurface } from \"./client.js\";\nimport { type ImageResolver, prepareDocument } from \"./prepare.js\";\n\nexport interface SurfaceSectionProps {\n /** The components to draw, as a page document: written by hand, by an agent, or kept in a store. */\n page: PageDocument;\n /** Data for the page's bindings, worked out on the server and merged over its own. Plain JSON. */\n data?: Record<string, unknown>;\n /** A theme the page's own is laid over. Without either, the section is drawn in the default theme, or in the app's\n * own `ThemeProvider` when one is above it. */\n theme?: ThemeRequest;\n /** Turns an image name the page uses into an address on the site. */\n resolveImage?: ImageResolver;\n /** Origins an image may also come from as written. */\n imageOrigins?: string[];\n}\n\n/**\n * Surfaces components as one part of a Next.js page the app writes itself, as a server component: the app's own\n * markup around it, any number on one page. It is rendered to HTML on the server and themed only in its own region,\n * so the rest of the page keeps the app's look. A page the catalog refuses stops the build with what is wrong.\n */\nexport function SurfaceSection({ page, data, theme, resolveImage, imageOrigins }: SurfaceSectionProps) {\n const prepared = prepareDocument(page, { data, theme, resolveImage });\n assertPage(prepared.page, `\"${page.id}\"`);\n return <SiteSurface page={prepared.page} images={prepared.images} imageOrigins={imageOrigins} />;\n}\n"]}
@@ -0,0 +1,6 @@
1
+ import { type PageDocument } from "@surfaces-ui/spec";
2
+ /**
3
+ * Stops on a page its catalog refuses, saying what is wrong and where (`where`: a route, or the page's id), so a
4
+ * build never ships a broken page. A page of an app's own catalog is checked in the browser, by `SurfaceView`.
5
+ */
6
+ export declare function assertPage(page: PageDocument, where: string): void;
package/dist/check.js ADDED
@@ -0,0 +1,15 @@
1
+ import { analyticsCatalog, basicsCatalog, siteCatalog, validatePage } from "@surfaces-ui/spec";
2
+ const CHECKED = [siteCatalog, basicsCatalog, analyticsCatalog];
3
+ /**
4
+ * Stops on a page its catalog refuses, saying what is wrong and where (`where`: a route, or the page's id), so a
5
+ * build never ships a broken page. A page of an app's own catalog is checked in the browser, by `SurfaceView`.
6
+ */
7
+ export function assertPage(page, where) {
8
+ const catalog = CHECKED.find((c) => c.id === page.catalogId);
9
+ if (!catalog)
10
+ return;
11
+ const issues = validatePage(page, catalog);
12
+ if (issues.length)
13
+ throw new Error(`The page ${where} does not fit the ${catalog.id} catalog: ${issues.map((i) => `${i.path} ${i.message}`).join("; ")}`);
14
+ }
15
+ //# sourceMappingURL=check.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"check.js","sourceRoot":"","sources":["../src/check.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,gBAAgB,EAAE,aAAa,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAElH,MAAM,OAAO,GAAG,CAAC,WAAW,EAAE,aAAa,EAAE,gBAAgB,CAAC,CAAC;AAE/D;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,IAAkB,EAAE,KAAa;IAC1D,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC,SAAS,CAAC,CAAC;IAC7D,IAAI,CAAC,OAAO;QAAE,OAAO;IACrB,MAAM,MAAM,GAAG,YAAY,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAC3C,IAAI,MAAM,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,YAAY,KAAK,qBAAqB,OAAO,CAAC,EAAE,aAAa,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAC5J,CAAC","sourcesContent":["import { type PageDocument, analyticsCatalog, basicsCatalog, siteCatalog, validatePage } from \"@surfaces-ui/spec\";\n\nconst CHECKED = [siteCatalog, basicsCatalog, analyticsCatalog];\n\n/**\n * Stops on a page its catalog refuses, saying what is wrong and where (`where`: a route, or the page's id), so a\n * build never ships a broken page. A page of an app's own catalog is checked in the browser, by `SurfaceView`.\n */\nexport function assertPage(page: PageDocument, where: string): void {\n const catalog = CHECKED.find((c) => c.id === page.catalogId);\n if (!catalog) return;\n const issues = validatePage(page, catalog);\n if (issues.length) throw new Error(`The page ${where} does not fit the ${catalog.id} catalog: ${issues.map((i) => `${i.path} ${i.message}`).join(\"; \")}`);\n}\n"]}
@@ -0,0 +1,28 @@
1
+ import { type Catalog, type PageDocument, type SurfaceAction } from "@surfaces-ui/spec";
2
+ import { type ComponentRenderer } from "@surfaces-ui/spec/react";
3
+ import { type MouseEvent } from "react";
4
+ export interface SiteSurfaceProps {
5
+ /** The page, prepared on the server (`preparePage`): plain JSON. */
6
+ page: PageDocument;
7
+ /** The address of each image name the page uses. */
8
+ images?: Record<string, string>;
9
+ /** Origins an image may also come from as written ("https://images.example.com"). */
10
+ imageOrigins?: string[];
11
+ /** For an app's own catalog (from a client file of the app's): the catalog and its renderers. */
12
+ catalog?: Catalog;
13
+ renderers?: Record<string, ComponentRenderer>;
14
+ /** Told of an event a control sends. A site has no agent, so with none an event goes nowhere. */
15
+ onAction?(action: SurfaceAction): void;
16
+ }
17
+ /**
18
+ * Draws one page of a site in a Next.js app. It is a client component, and is rendered to HTML on the server
19
+ * like any other: the site's components render with no browser, and a data component draws once the page has
20
+ * loaded. A link to a path on the site moves through Next.js's router, so the page is not loaded again; any other
21
+ * link, a link opened in a new tab and a download behave as links do.
22
+ */
23
+ export declare function SiteSurface({ page, images, imageOrigins, catalog, renderers, onAction }: SiteSurfaceProps): import("react").JSX.Element;
24
+ /**
25
+ * The path a click should go to through the router, or nothing when the browser should handle it: a press that
26
+ * is not a plain left click, a link that opens elsewhere, downloads, or leaves the site.
27
+ */
28
+ export declare function sitePathOf(event: Pick<MouseEvent, "defaultPrevented" | "button" | "metaKey" | "ctrlKey" | "shiftKey" | "altKey" | "target">): string | undefined;
package/dist/client.js ADDED
@@ -0,0 +1,69 @@
1
+ "use client";
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { ThemeProvider, useOptionalTheme } from "@surfaces-ui/components";
4
+ import { analyticsCatalog, basicsCatalog, pageSurface, siteCatalog } from "@surfaces-ui/spec";
5
+ import { MediaPolicyProvider, SurfaceView, basicsRenderers, lazyAnalyticsRenderers, siteRenderers, } from "@surfaces-ui/spec/react";
6
+ import { useRouter } from "next/navigation";
7
+ import { useCallback, useMemo } from "react";
8
+ /** The catalogs a page may name, with what draws each. */
9
+ const CATALOGS = {
10
+ [siteCatalog.id]: { catalog: siteCatalog, renderers: siteRenderers },
11
+ [basicsCatalog.id]: { catalog: basicsCatalog, renderers: basicsRenderers },
12
+ [analyticsCatalog.id]: { catalog: analyticsCatalog, renderers: lazyAnalyticsRenderers },
13
+ };
14
+ /**
15
+ * Draws one page of a site in a Next.js app. It is a client component, and is rendered to HTML on the server
16
+ * like any other: the site's components render with no browser, and a data component draws once the page has
17
+ * loaded. A link to a path on the site moves through Next.js's router, so the page is not loaded again; any other
18
+ * link, a link opened in a new tab and a download behave as links do.
19
+ */
20
+ export function SiteSurface({ page, images, imageOrigins, catalog, renderers, onAction }) {
21
+ const router = useRouter();
22
+ const known = CATALOGS[page.catalogId];
23
+ const drawWith = catalog && renderers ? { catalog, renderers } : known;
24
+ const surface = useMemo(() => pageSurface(page), [page]);
25
+ const policy = useMemo(() => ({ resolve: (name) => images?.[name], origins: imageOrigins }), [images, imageOrigins]);
26
+ const follow = useCallback((event) => {
27
+ const to = sitePathOf(event);
28
+ if (!to)
29
+ return;
30
+ event.preventDefault();
31
+ router.push(to);
32
+ }, [router]);
33
+ if (!drawWith) {
34
+ return _jsxs("p", { role: "alert", children: ["This page names the catalog \"", page.catalogId, "\", which this site does not draw."] });
35
+ }
36
+ return (_jsx(WithTheme, { children: _jsx(MediaPolicyProvider, { policy: policy, children: _jsx("div", { onClick: follow, style: { display: "contents" }, children: _jsx(SurfaceView, { surface: surface, catalog: drawWith.catalog, renderers: drawWith.renderers, onAction: onAction }) }) }) }));
37
+ }
38
+ /** The app's own theme when it has a `ThemeProvider`, else one kept to the page's region and in memory. */
39
+ function WithTheme({ children }) {
40
+ const outer = useOptionalTheme();
41
+ if (outer)
42
+ return _jsx(_Fragment, { children: children });
43
+ return (_jsx(ThemeProvider, { scope: "scoped", storage: null, children: children }));
44
+ }
45
+ /**
46
+ * The path a click should go to through the router, or nothing when the browser should handle it: a press that
47
+ * is not a plain left click, a link that opens elsewhere, downloads, or leaves the site.
48
+ */
49
+ export function sitePathOf(event) {
50
+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
51
+ return undefined;
52
+ const target = event.target;
53
+ const link = target?.closest?.("a[href]");
54
+ if (!link)
55
+ return undefined;
56
+ if ((link.target && link.target !== "_self") || link.hasAttribute("download"))
57
+ return undefined;
58
+ const href = link.getAttribute("href") ?? "";
59
+ if (href.startsWith("#"))
60
+ return undefined;
61
+ const here = globalThis.location;
62
+ if (!here)
63
+ return undefined;
64
+ const url = new URL(href, here.href);
65
+ if (url.origin !== here.origin)
66
+ return undefined;
67
+ return `${url.pathname}${url.search}${url.hash}`;
68
+ }
69
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC1E,OAAO,EAAuD,gBAAgB,EAAE,aAAa,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACnJ,OAAO,EAEL,mBAAmB,EACnB,WAAW,EACX,eAAe,EACf,sBAAsB,EACtB,aAAa,GACd,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,SAA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9C,MAAM,IAAI,GAAG,MAAM,EAAE,OAAO,EAAE,CAAC,SAAS,CAA6B,CAAC;IACtE,IAAI,CAAC,IAAI;QAAE,OAAO,SAAS,CAAC;IAC5B,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,KAAK,OAAO,CAAC,IAAI,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC;QAAE,OAAO,SAAS,CAAC;IAChG,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;IAC7C,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO,SAAS,CAAC;IAC3C,MAAM,IAAI,GAAG,UAAU,CAAC,QAAQ,CAAC;IACjC,IAAI,CAAC,IAAI;QAAE,OAAO,SAAS,CAAC;IAC5B,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;IACrC,IAAI,GAAG,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,CAAC;IACjD,OAAO,GAAG,GAAG,CAAC,QAAQ,GAAG,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC;AACnD,CAAC","sourcesContent":["\"use client\";\n\nimport { ThemeProvider, useOptionalTheme } from \"@surfaces-ui/components\";\nimport { type Catalog, type PageDocument, type SurfaceAction, analyticsCatalog, basicsCatalog, pageSurface, siteCatalog } from \"@surfaces-ui/spec\";\nimport {\n type ComponentRenderer,\n MediaPolicyProvider,\n SurfaceView,\n basicsRenderers,\n lazyAnalyticsRenderers,\n siteRenderers,\n} from \"@surfaces-ui/spec/react\";\nimport { useRouter } from \"next/navigation\";\nimport { type MouseEvent, type ReactNode, useCallback, useMemo } from \"react\";\n\n/** The catalogs a page may name, with what draws each. */\nconst CATALOGS: Record<string, { catalog: Catalog; renderers: Record<string, ComponentRenderer> }> = {\n [siteCatalog.id]: { catalog: siteCatalog, renderers: siteRenderers },\n [basicsCatalog.id]: { catalog: basicsCatalog, renderers: basicsRenderers },\n [analyticsCatalog.id]: { catalog: analyticsCatalog, renderers: lazyAnalyticsRenderers },\n};\n\nexport interface SiteSurfaceProps {\n /** The page, prepared on the server (`preparePage`): plain JSON. */\n page: PageDocument;\n /** The address of each image name the page uses. */\n images?: Record<string, string>;\n /** Origins an image may also come from as written (\"https://images.example.com\"). */\n imageOrigins?: string[];\n /** For an app's own catalog (from a client file of the app's): the catalog and its renderers. */\n catalog?: Catalog;\n renderers?: Record<string, ComponentRenderer>;\n /** Told of an event a control sends. A site has no agent, so with none an event goes nowhere. */\n onAction?(action: SurfaceAction): void;\n}\n\n/**\n * Draws one page of a site in a Next.js app. It is a client component, and is rendered to HTML on the server\n * like any other: the site's components render with no browser, and a data component draws once the page has\n * loaded. A link to a path on the site moves through Next.js's router, so the page is not loaded again; any other\n * link, a link opened in a new tab and a download behave as links do.\n */\nexport function SiteSurface({ page, images, imageOrigins, catalog, renderers, onAction }: SiteSurfaceProps) {\n const router = useRouter();\n const known = CATALOGS[page.catalogId];\n const drawWith = catalog && renderers ? { catalog, renderers } : known;\n const surface = useMemo(() => pageSurface(page), [page]);\n const policy = useMemo(() => ({ resolve: (name: string) => images?.[name], origins: imageOrigins }), [images, imageOrigins]);\n const follow = useCallback(\n (event: MouseEvent<HTMLDivElement>) => {\n const to = sitePathOf(event);\n if (!to) return;\n event.preventDefault();\n router.push(to);\n },\n [router],\n );\n if (!drawWith) {\n return <p role=\"alert\">This page names the catalog \"{page.catalogId}\", which this site does not draw.</p>;\n }\n return (\n <WithTheme>\n <MediaPolicyProvider policy={policy}>\n {/* A wrapper that takes no room: it only hears clicks on the page's links. */}\n <div onClick={follow} style={{ display: \"contents\" }}>\n <SurfaceView surface={surface} catalog={drawWith.catalog} renderers={drawWith.renderers} onAction={onAction} />\n </div>\n </MediaPolicyProvider>\n </WithTheme>\n );\n}\n\n/** The app's own theme when it has a `ThemeProvider`, else one kept to the page's region and in memory. */\nfunction WithTheme({ children }: { children: ReactNode }) {\n const outer = useOptionalTheme();\n if (outer) return <>{children}</>;\n return (\n <ThemeProvider scope=\"scoped\" storage={null}>\n {children}\n </ThemeProvider>\n );\n}\n\n/**\n * The path a click should go to through the router, or nothing when the browser should handle it: a press that\n * is not a plain left click, a link that opens elsewhere, downloads, or leaves the site.\n */\nexport function sitePathOf(event: Pick<MouseEvent, \"defaultPrevented\" | \"button\" | \"metaKey\" | \"ctrlKey\" | \"shiftKey\" | \"altKey\" | \"target\">): string | undefined {\n if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return undefined;\n const target = event.target as Element | null;\n const link = target?.closest?.(\"a[href]\") as HTMLAnchorElement | null;\n if (!link) return undefined;\n if ((link.target && link.target !== \"_self\") || link.hasAttribute(\"download\")) return undefined;\n const href = link.getAttribute(\"href\") ?? \"\";\n if (href.startsWith(\"#\")) return undefined;\n const here = globalThis.location;\n if (!here) return undefined;\n const url = new URL(href, here.href);\n if (url.origin !== here.origin) return undefined;\n return `${url.pathname}${url.search}${url.hash}`;\n}\n"]}
@@ -0,0 +1,8 @@
1
+ export * from "./routes.js";
2
+ export * from "./params.js";
3
+ export * from "./prepare.js";
4
+ export * from "./metadata.js";
5
+ export * from "./SitePage.js";
6
+ export * from "./SurfaceSection.js";
7
+ export { assertPage } from "./check.js";
8
+ export { SiteSurface, type SiteSurfaceProps } from "./client.js";
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export * from "./routes.js";
2
+ export * from "./params.js";
3
+ export * from "./prepare.js";
4
+ export * from "./metadata.js";
5
+ export * from "./SitePage.js";
6
+ export * from "./SurfaceSection.js";
7
+ export { assertPage } from "./check.js";
8
+ export { SiteSurface } from "./client.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC;AAC9B,cAAc,qBAAqB,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,WAAW,EAAyB,MAAM,aAAa,CAAC","sourcesContent":["export * from \"./routes.js\";\nexport * from \"./params.js\";\nexport * from \"./prepare.js\";\nexport * from \"./metadata.js\";\nexport * from \"./SitePage.js\";\nexport * from \"./SurfaceSection.js\";\nexport { assertPage } from \"./check.js\";\nexport { SiteSurface, type SiteSurfaceProps } from \"./client.js\";\n"]}
@@ -0,0 +1,22 @@
1
+ import type { Metadata } from "next";
2
+ import type { ImageResolver } from "./prepare.js";
3
+ import { type SiteMeta, type SiteRoutes } from "./routes.js";
4
+ import { type RouteParams } from "./params.js";
5
+ export interface SiteMetadataOptions {
6
+ /** The name of the catch-all segment, as for `siteParams`. Default "route". */
7
+ param?: string;
8
+ /** Turns an image name in `meta.image` into an address. An http(s) address is used as written. */
9
+ resolveImage?: ImageResolver;
10
+ /**
11
+ * The meta of a route that takes values, worked out from them: an essay's own title and summary. Merged over
12
+ * the route's `meta`.
13
+ */
14
+ describe?: (route: string, values: Record<string, string>) => SiteMeta | undefined | Promise<SiteMeta | undefined>;
15
+ }
16
+ /**
17
+ * Next.js metadata for an address of the site, for `generateMetadata`: the title (with the site's title after
18
+ * it, through Next.js's title template), the description, the canonical path and a link preview. The page's own
19
+ * title and description are used where the route's `meta` says nothing. An address the site does not have gets
20
+ * no metadata; the page itself answers it with a 404.
21
+ */
22
+ export declare function siteMetadata(site: SiteRoutes, params: RouteParams, options?: SiteMetadataOptions): Promise<Metadata>;
@@ -0,0 +1,35 @@
1
+ import { siteLink } from "@surfaces-ui/spec";
2
+ import { matchRoute, routePath } from "./routes.js";
3
+ import { segmentsOf } from "./params.js";
4
+ /**
5
+ * Next.js metadata for an address of the site, for `generateMetadata`: the title (with the site's title after
6
+ * it, through Next.js's title template), the description, the canonical path and a link preview. The page's own
7
+ * title and description are used where the route's `meta` says nothing. An address the site does not have gets
8
+ * no metadata; the page itself answers it with a 404.
9
+ */
10
+ export async function siteMetadata(site, params, options = {}) {
11
+ const match = matchRoute(site, await segmentsOf(params, options.param));
12
+ if (!match)
13
+ return {};
14
+ const described = options.describe ? await options.describe(match.entry.route, match.values) : undefined;
15
+ const meta = { ...match.entry.meta, ...described };
16
+ const title = meta.title ?? match.entry.page.title;
17
+ const description = meta.description ?? match.entry.page.description;
18
+ const image = meta.image ? (options.resolveImage?.(meta.image) ?? meta.image) : undefined;
19
+ const imageAddress = image ? siteLink(image) : undefined;
20
+ const path = routePath(match.entry.route, match.values);
21
+ const isHome = match.entry.route === "/";
22
+ return {
23
+ ...(title ? { title: isHome || !site.title ? { absolute: title } : `${title} · ${site.title}` } : {}),
24
+ ...(description ? { description } : {}),
25
+ alternates: { canonical: path },
26
+ openGraph: {
27
+ ...(title ? { title } : {}),
28
+ ...(description ? { description } : {}),
29
+ ...(site.title ? { siteName: site.title } : {}),
30
+ url: path,
31
+ ...(imageAddress ? { images: [imageAddress] } : {}),
32
+ },
33
+ };
34
+ }
35
+ //# sourceMappingURL=metadata.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metadata.js","sourceRoot":"","sources":["../src/metadata.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAG7C,OAAO,EAAkC,UAAU,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACpF,OAAO,EAAoB,UAAU,EAAE,MAAM,aAAa,CAAC;AAc3D;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,IAAgB,EAAE,MAAmB,EAAE,OAAO,GAAwB,EAAE;IACzG,MAAM,KAAK,GAAG,UAAU,CAAC,IAAI,EAAE,MAAM,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC,C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CAAC;QACrG,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACvC,UAAU,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE;QAC/B,SAAS,EAAE;YACT,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC3B,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACvC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC/C,GAAG,EAAE,IAAI;YACT,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACpD;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { siteLink } from \"@surfaces-ui/spec\";\nimport type { Metadata } from \"next\";\nimport type { ImageResolver } from \"./prepare.js\";\nimport { type SiteMeta, type SiteRoutes, matchRoute, routePath } from \"./routes.js\";\nimport { type RouteParams, segmentsOf } from \"./params.js\";\n\nexport interface SiteMetadataOptions {\n /** The name of the catch-all segment, as for `siteParams`. Default \"route\". */\n param?: string;\n /** Turns an image name in `meta.image` into an address. An http(s) address is used as written. */\n resolveImage?: ImageResolver;\n /**\n * The meta of a route that takes values, worked out from them: an essay's own title and summary. Merged over\n * the route's `meta`.\n */\n describe?: (route: string, values: Record<string, string>) => SiteMeta | undefined | Promise<SiteMeta | undefined>;\n}\n\n/**\n * Next.js metadata for an address of the site, for `generateMetadata`: the title (with the site's title after\n * it, through Next.js's title template), the description, the canonical path and a link preview. The page's own\n * title and description are used where the route's `meta` says nothing. An address the site does not have gets\n * no metadata; the page itself answers it with a 404.\n */\nexport async function siteMetadata(site: SiteRoutes, params: RouteParams, options: SiteMetadataOptions = {}): Promise<Metadata> {\n const match = matchRoute(site, await segmentsOf(params, options.param));\n if (!match) return {};\n const described = options.describe ? await options.describe(match.entry.route, match.values) : undefined;\n const meta: SiteMeta = { ...match.entry.meta, ...described };\n const title = meta.title ?? match.entry.page.title;\n const description = meta.description ?? match.entry.page.description;\n const image = meta.image ? (options.resolveImage?.(meta.image) ?? meta.image) : undefined;\n const imageAddress = image ? siteLink(image) : undefined;\n const path = routePath(match.entry.route, match.values);\n const isHome = match.entry.route === \"/\";\n return {\n ...(title ? { title: isHome || !site.title ? { absolute: title } : `${title} · ${site.title}` } : {}),\n ...(description ? { description } : {}),\n alternates: { canonical: path },\n openGraph: {\n ...(title ? { title } : {}),\n ...(description ? { description } : {}),\n ...(site.title ? { siteName: site.title } : {}),\n url: path,\n ...(imageAddress ? { images: [imageAddress] } : {}),\n },\n };\n}\n"]}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * What Next.js passes a page as `params`: a promise since Next.js 15, the object itself before. Either is
3
+ * accepted, so the same route file works on both.
4
+ */
5
+ export type RouteParams = Promise<Record<string, string | string[] | undefined>> | Record<string, string | string[] | undefined>;
6
+ /** The catch-all segments out of `params`: `["essays", "first-post"]`, or none for the home page. */
7
+ export declare function segmentsOf(params: RouteParams | undefined, param?: string): Promise<string[]>;
package/dist/params.js ADDED
@@ -0,0 +1,6 @@
1
+ /** The catch-all segments out of `params`: `["essays", "first-post"]`, or none for the home page. */
2
+ export async function segmentsOf(params, param = "route") {
3
+ const value = (await params)?.[param];
4
+ return value === undefined ? [] : typeof value === "string" ? [value] : value;
5
+ }
6
+ //# sourceMappingURL=params.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"params.js","sourceRoot":"","sources":["../src/params.ts"],"names":[],"mappings":"AAMA,qGAAqG;AACrG,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,MAA+B,EAAE,KAAK,GAAG,OAAO;IAC/E,MAAM,KAAK,GAAG,CAAC,MAAM,MAAM,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;IACtC,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;AAChF,CAAC","sourcesContent":["/**\n * What Next.js passes a page as `params`: a promise since Next.js 15, the object itself before. Either is\n * accepted, so the same route file works on both.\n */\nexport type RouteParams = Promise<Record<string, string | string[] | undefined>> | Record<string, string | string[] | undefined>;\n\n/** The catch-all segments out of `params`: `[\"essays\", \"first-post\"]`, or none for the home page. */\nexport async function segmentsOf(params: RouteParams | undefined, param = \"route\"): Promise<string[]> {\n const value = (await params)?.[param];\n return value === undefined ? [] : typeof value === \"string\" ? [value] : value;\n}\n"]}
@@ -0,0 +1,36 @@
1
+ import { type PageDocument } from "@surfaces-ui/spec";
2
+ import type { ThemeRequest } from "@surfaces-ui/tokens";
3
+ import type { MatchedRoute, SiteRoutes } from "./routes.js";
4
+ /** Turns an image name a page uses ("dashboard") into an address the site serves it from. */
5
+ export type ImageResolver = (name: string) => string | undefined;
6
+ /**
7
+ * Where a page's data comes from on the server: anything a page binds to (an essay's title and text, a list of
8
+ * posts), as plain JSON. It is merged over the page's own `data`.
9
+ */
10
+ export type PageData = (route: string, values: Record<string, string>) => unknown | Promise<unknown>;
11
+ /** A page ready to send to the browser: plain JSON, with nothing in it the browser has to ask the server for. */
12
+ export interface PreparedPage {
13
+ page: PageDocument;
14
+ /** The address for each image name the page uses, worked out on the server. */
15
+ images: Record<string, string>;
16
+ }
17
+ /** Where the route's values are put in the page's data, so a page can write `${/@route/slug}`. */
18
+ export declare const ROUTE_DATA_KEY = "@route";
19
+ /**
20
+ * Prepares the page an address matched: the site's theme under the page's own, the route's values and the app's
21
+ * data in its data model, and the address of every image it names. Functions stay on the server, since none can
22
+ * cross to the browser.
23
+ */
24
+ export declare function preparePage(site: SiteRoutes, match: MatchedRoute, options?: {
25
+ data?: PageData;
26
+ resolveImage?: ImageResolver;
27
+ }): Promise<PreparedPage>;
28
+ export interface PrepareOptions {
29
+ /** Merged over the page's own data. */
30
+ data?: Record<string, unknown>;
31
+ /** A theme the page's own `theme` is laid over (the site's). */
32
+ theme?: ThemeRequest;
33
+ resolveImage?: ImageResolver;
34
+ }
35
+ /** Prepares any page to send to the browser: data merged in, themes merged, image names resolved. */
36
+ export declare function prepareDocument(given: PageDocument, options?: PrepareOptions): PreparedPage;
@@ -0,0 +1,42 @@
1
+ import { siteLink, upgradePage } from "@surfaces-ui/spec";
2
+ /** Where the route's values are put in the page's data, so a page can write `${/@route/slug}`. */
3
+ export const ROUTE_DATA_KEY = "@route";
4
+ /**
5
+ * Prepares the page an address matched: the site's theme under the page's own, the route's values and the app's
6
+ * data in its data model, and the address of every image it names. Functions stay on the server, since none can
7
+ * cross to the browser.
8
+ */
9
+ export async function preparePage(site, match, options = {}) {
10
+ const given = options.data ? await options.data(match.entry.route, match.values) : undefined;
11
+ return prepareDocument(match.entry.page, {
12
+ data: { ...(isRecord(given) ? given : {}), [ROUTE_DATA_KEY]: match.values },
13
+ theme: site.theme,
14
+ resolveImage: options.resolveImage,
15
+ });
16
+ }
17
+ /** Prepares any page to send to the browser: data merged in, themes merged, image names resolved. */
18
+ export function prepareDocument(given, options = {}) {
19
+ const page = upgradePage(given);
20
+ const data = { ...(isRecord(page.data) ? page.data : {}), ...options.data };
21
+ const theme = mergeTheme(options.theme, page.theme);
22
+ const images = {};
23
+ if (options.resolveImage) {
24
+ for (const name of mediaNames(page.components)) {
25
+ const address = siteLink(options.resolveImage(name));
26
+ if (address)
27
+ images[name] = address;
28
+ }
29
+ }
30
+ return { page: { ...page, data, ...(theme ? { theme } : {}) }, images };
31
+ }
32
+ function mergeTheme(site, page) {
33
+ if (!site && !page)
34
+ return undefined;
35
+ return { ...site, ...page };
36
+ }
37
+ const isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
38
+ /** The image names a page's Media components use, written as text (a bound one is resolved in the browser). */
39
+ function mediaNames(components) {
40
+ return [...new Set(components.flatMap((c) => (c.component === "Media" && typeof c.src === "string" && c.src ? [c.src] : [])))];
41
+ }
42
+ //# sourceMappingURL=prepare.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prepare.js","sourceRoot":"","sources":["../src/prepare.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4C,QAAQ,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAoBpG,kGAAkG;AAClG,MAAM,CAAC,MAAM,cAAc,GAAG,QAAQ,CAAC;AAEvC;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,IAAgB,EAAE,KAAmB,EAAE,OAAO,GAAsD,EAAE;IACtI,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC7F,OAAO,eAAe,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE;QACvC,IAAI,EAAE,EAAE,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,cAAc,CAAC,EAAE,KAAK,CAAC,MAAM,EAAE;QAC3E,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,YAAY,EAAE,OAAO,CAAC,YAAY;KACnC,CAAC,CAAC;AACL,CAAC;AAUD,qGAAqG;AACrG,MAAM,UAAU,eAAe,CAAC,KAAmB,EAAE,OAAO,GAAmB,EAAE;IAC/E,MAAM,IAAI,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC;IAChC,MAAM,IAAI,GAAG,EAAE,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAA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,IAAI,OAAO,CAAC,CAAC,GAAG,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;AACjI,CAAC","sourcesContent":["import { type PageDocument, type SurfaceComponent, siteLink, upgradePage } from \"@surfaces-ui/spec\";\nimport type { ThemeRequest } from \"@surfaces-ui/tokens\";\nimport type { MatchedRoute, SiteRoutes } from \"./routes.js\";\n\n/** Turns an image name a page uses (\"dashboard\") into an address the site serves it from. */\nexport type ImageResolver = (name: string) => string | undefined;\n\n/**\n * Where a page's data comes from on the server: anything a page binds to (an essay's title and text, a list of\n * posts), as plain JSON. It is merged over the page's own `data`.\n */\nexport type PageData = (route: string, values: Record<string, string>) => unknown | Promise<unknown>;\n\n/** A page ready to send to the browser: plain JSON, with nothing in it the browser has to ask the server for. */\nexport interface PreparedPage {\n page: PageDocument;\n /** The address for each image name the page uses, worked out on the server. */\n images: Record<string, string>;\n}\n\n/** Where the route's values are put in the page's data, so a page can write `${/@route/slug}`. */\nexport const ROUTE_DATA_KEY = \"@route\";\n\n/**\n * Prepares the page an address matched: the site's theme under the page's own, the route's values and the app's\n * data in its data model, and the address of every image it names. Functions stay on the server, since none can\n * cross to the browser.\n */\nexport async function preparePage(site: SiteRoutes, match: MatchedRoute, options: { data?: PageData; resolveImage?: ImageResolver } = {}): Promise<PreparedPage> {\n const given = options.data ? await options.data(match.entry.route, match.values) : undefined;\n return prepareDocument(match.entry.page, {\n data: { ...(isRecord(given) ? given : {}), [ROUTE_DATA_KEY]: match.values },\n theme: site.theme,\n resolveImage: options.resolveImage,\n });\n}\n\nexport interface PrepareOptions {\n /** Merged over the page's own data. */\n data?: Record<string, unknown>;\n /** A theme the page's own `theme` is laid over (the site's). */\n theme?: ThemeRequest;\n resolveImage?: ImageResolver;\n}\n\n/** Prepares any page to send to the browser: data merged in, themes merged, image names resolved. */\nexport function prepareDocument(given: PageDocument, options: PrepareOptions = {}): PreparedPage {\n const page = upgradePage(given);\n const data = { ...(isRecord(page.data) ? page.data : {}), ...options.data };\n const theme = mergeTheme(options.theme, page.theme);\n const images: Record<string, string> = {};\n if (options.resolveImage) {\n for (const name of mediaNames(page.components)) {\n const address = siteLink(options.resolveImage(name));\n if (address) images[name] = address;\n }\n }\n return { page: { ...page, data, ...(theme ? { theme } : {}) }, images };\n}\n\nfunction mergeTheme(site: ThemeRequest | undefined, page: ThemeRequest | undefined): ThemeRequest | undefined {\n if (!site && !page) return undefined;\n return { ...site, ...page };\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => !!value && typeof value === \"object\" && !Array.isArray(value);\n\n/** The image names a page's Media components use, written as text (a bound one is resolved in the browser). */\nfunction mediaNames(components: SurfaceComponent[]): string[] {\n return [...new Set(components.flatMap((c) => (c.component === \"Media\" && typeof c.src === \"string\" && c.src ? [c.src] : [])))];\n}\n"]}
@@ -0,0 +1,81 @@
1
+ import type { PageDocument } from "@surfaces-ui/spec";
2
+ import type { ThemeRequest } from "@surfaces-ui/tokens";
3
+ /** What a route says about itself to search engines and link previews. */
4
+ export interface SiteMeta {
5
+ title?: string;
6
+ description?: string;
7
+ /** An image for link previews: a name the app's `resolveImage` turns into an address, or an http(s) address. */
8
+ image?: string;
9
+ }
10
+ /** One page of a site and the route it is served on. */
11
+ export interface SiteRoute {
12
+ /** A path: "/", "/pricing", "/essays/[slug]". A segment in brackets takes a value from the app. */
13
+ route: string;
14
+ page: PageDocument;
15
+ meta?: SiteMeta;
16
+ }
17
+ /**
18
+ * The pages of a site, each on its route. This is the part of the planned site document (`docs/plans/sites.md`,
19
+ * step 4) that a Next.js app needs to serve pages, so that document will be accepted here as it is.
20
+ */
21
+ export interface SiteRoutes {
22
+ title?: string;
23
+ /** The look of every page, unless a page asks for its own. */
24
+ theme?: ThemeRequest;
25
+ pages: SiteRoute[];
26
+ }
27
+ /** One part of a route: a fixed name, or a value named in brackets. */
28
+ export type RouteSegment = {
29
+ kind: "fixed";
30
+ name: string;
31
+ } | {
32
+ kind: "value";
33
+ name: string;
34
+ };
35
+ /** The segments of a route, or what is wrong with it. */
36
+ export declare function parseRoute(route: string): {
37
+ segments: RouteSegment[];
38
+ } | {
39
+ problem: string;
40
+ };
41
+ /** The names a route takes values for, in order: ["slug"] for "/essays/[slug]". */
42
+ export declare function routeValueNames(route: string): string[];
43
+ export interface SiteProblem {
44
+ route: string;
45
+ message: string;
46
+ }
47
+ /**
48
+ * What is wrong with a site's routes: a route that is not a path, two pages on one route, or two routes that
49
+ * would answer the same address ("/[a]" and "/[b]"). A fixed route always wins over one with a value, so
50
+ * "/essays/new" beside "/essays/[slug]" is fine.
51
+ */
52
+ export declare function siteProblems(site: SiteRoutes): SiteProblem[];
53
+ /** A page found for an address, with the values its route took from it. */
54
+ export interface MatchedRoute {
55
+ entry: SiteRoute;
56
+ values: Record<string, string>;
57
+ }
58
+ /**
59
+ * The page for an address, given as Next.js gives a catch-all route's segments (`["essays", "first-post"]`; none
60
+ * for the home page). A route whose segments are all fixed wins over one that takes values, segment by segment
61
+ * from the left, as in Next.js.
62
+ */
63
+ export declare function matchRoute(site: SiteRoutes, segments: readonly string[] | string | undefined): MatchedRoute | undefined;
64
+ /** The address of a route with its values filled in: "/essays/first-post". Values are encoded. */
65
+ export declare function routePath(route: string, values?: Record<string, string>): string;
66
+ /**
67
+ * Where a route's values come from, by route: a list of values when it takes one ("/essays/[slug]" →
68
+ * `["first-post", "second-post"]`), or of objects when it takes several. From files, a CMS or a database; the app
69
+ * decides, and Surfaces only asks.
70
+ */
71
+ export type RouteValues = Record<string, () => Iterable<string | Record<string, string>> | Promise<Iterable<string | Record<string, string>>>>;
72
+ export interface SiteParamsOptions {
73
+ /** The name of the catch-all segment in the app's folder, `app/[[...route]]`. Default "route". */
74
+ param?: string;
75
+ }
76
+ /**
77
+ * Every address of a site as Next.js's `generateStaticParams` wants it for an optional catch-all route,
78
+ * `app/[[...route]]/page.tsx`: `[{ route: [] }, { route: ["pricing"] }, { route: ["essays", "first-post"] }]`.
79
+ * A route that takes values with none given is an error, so a static export never leaves a page out quietly.
80
+ */
81
+ export declare function siteParams(site: SiteRoutes, values?: RouteValues, options?: SiteParamsOptions): Promise<Record<string, string[]>[]>;
package/dist/routes.js ADDED
@@ -0,0 +1,157 @@
1
+ const FIXED = /^[A-Za-z0-9._~!$&'()*+,;=:@%-]+$/;
2
+ const VALUE = /^\[([A-Za-z_][A-Za-z0-9_]*)\]$/;
3
+ /** The segments of a route, or what is wrong with it. */
4
+ export function parseRoute(route) {
5
+ if (typeof route !== "string" || !route.startsWith("/"))
6
+ return { problem: `A route is a path that starts with "/", not "${String(route)}".` };
7
+ if (route !== "/" && route.endsWith("/"))
8
+ return { problem: `Write "${route}" without the "/" at the end.` };
9
+ const parts = route === "/" ? [] : route.slice(1).split("/");
10
+ const segments = [];
11
+ const names = new Set();
12
+ for (const part of parts) {
13
+ const value = VALUE.exec(part);
14
+ if (value) {
15
+ const name = value[1];
16
+ if (names.has(name))
17
+ return { problem: `"${route}" names [${name}] twice.` };
18
+ names.add(name);
19
+ segments.push({ kind: "value", name });
20
+ }
21
+ else if (part.startsWith("[")) {
22
+ return { problem: `"${part}" in "${route}" is not a value Surfaces can fill: write one name in brackets, such as [slug]. Catch-all segments ([...path]) are not supported.` };
23
+ }
24
+ else if (!part || part === "." || part === ".." || !FIXED.test(part)) {
25
+ return { problem: `"${part}" in "${route}" is not a path segment.` };
26
+ }
27
+ else {
28
+ segments.push({ kind: "fixed", name: part });
29
+ }
30
+ }
31
+ return { segments };
32
+ }
33
+ /** The names a route takes values for, in order: ["slug"] for "/essays/[slug]". */
34
+ export function routeValueNames(route) {
35
+ const parsed = parseRoute(route);
36
+ return "segments" in parsed ? parsed.segments.filter((s) => s.kind === "value").map((s) => s.name) : [];
37
+ }
38
+ /**
39
+ * What is wrong with a site's routes: a route that is not a path, two pages on one route, or two routes that
40
+ * would answer the same address ("/[a]" and "/[b]"). A fixed route always wins over one with a value, so
41
+ * "/essays/new" beside "/essays/[slug]" is fine.
42
+ */
43
+ export function siteProblems(site) {
44
+ const problems = [];
45
+ const shapes = new Map();
46
+ for (const { route, page } of site.pages ?? []) {
47
+ const parsed = parseRoute(route);
48
+ if ("problem" in parsed) {
49
+ problems.push({ route, message: parsed.problem });
50
+ continue;
51
+ }
52
+ if (!page || !Array.isArray(page.components))
53
+ problems.push({ route, message: `"${route}" has no page.` });
54
+ const shape = parsed.segments.map((s) => (s.kind === "fixed" ? s.name : "[]")).join("/");
55
+ const before = shapes.get(shape);
56
+ if (before === route)
57
+ problems.push({ route, message: `Two pages are on "${route}".` });
58
+ else if (before)
59
+ problems.push({ route, message: `"${route}" and "${before}" answer the same addresses. Give one of them a fixed segment.` });
60
+ else
61
+ shapes.set(shape, route);
62
+ }
63
+ return problems;
64
+ }
65
+ /**
66
+ * The page for an address, given as Next.js gives a catch-all route's segments (`["essays", "first-post"]`; none
67
+ * for the home page). A route whose segments are all fixed wins over one that takes values, segment by segment
68
+ * from the left, as in Next.js.
69
+ */
70
+ export function matchRoute(site, segments) {
71
+ const parts = (segments === undefined ? [] : typeof segments === "string" ? [segments] : [...segments]).map(decodeSegment);
72
+ if (parts.some((part) => part === undefined))
73
+ return undefined;
74
+ let best;
75
+ for (const entry of site.pages ?? []) {
76
+ const parsed = parseRoute(entry.route);
77
+ if ("problem" in parsed || parsed.segments.length !== parts.length)
78
+ continue;
79
+ const values = {};
80
+ let fits = true;
81
+ for (const [i, segment] of parsed.segments.entries()) {
82
+ const part = parts[i];
83
+ if (segment.kind === "fixed")
84
+ fits = segment.name === part;
85
+ else if (part)
86
+ values[segment.name] = part;
87
+ else
88
+ fits = false;
89
+ if (!fits)
90
+ break;
91
+ }
92
+ if (!fits)
93
+ continue;
94
+ // "0" for a fixed segment sorts before "1" for a value: the more fixed segments to the left, the better.
95
+ const rank = parsed.segments.map((s) => (s.kind === "fixed" ? "0" : "1")).join("");
96
+ if (!best || rank < best.rank)
97
+ best = { match: { entry, values }, rank };
98
+ }
99
+ return best?.match;
100
+ }
101
+ function decodeSegment(part) {
102
+ try {
103
+ return decodeURIComponent(part);
104
+ }
105
+ catch {
106
+ return undefined;
107
+ }
108
+ }
109
+ /** The address of a route with its values filled in: "/essays/first-post". Values are encoded. */
110
+ export function routePath(route, values = {}) {
111
+ const parsed = parseRoute(route);
112
+ if ("problem" in parsed)
113
+ throw new Error(parsed.problem);
114
+ const parts = parsed.segments.map((segment) => {
115
+ if (segment.kind === "fixed")
116
+ return segment.name;
117
+ const value = values[segment.name];
118
+ if (!value)
119
+ throw new Error(`"${route}" needs a value for [${segment.name}].`);
120
+ return encodeURIComponent(value);
121
+ });
122
+ return `/${parts.join("/")}`;
123
+ }
124
+ /**
125
+ * Every address of a site as Next.js's `generateStaticParams` wants it for an optional catch-all route,
126
+ * `app/[[...route]]/page.tsx`: `[{ route: [] }, { route: ["pricing"] }, { route: ["essays", "first-post"] }]`.
127
+ * A route that takes values with none given is an error, so a static export never leaves a page out quietly.
128
+ */
129
+ export async function siteParams(site, values = {}, options = {}) {
130
+ const param = options.param ?? "route";
131
+ const problems = siteProblems(site);
132
+ if (problems.length)
133
+ throw new Error(`The site's routes have problems: ${problems.map((p) => p.message).join(" ")}`);
134
+ const unknown = Object.keys(values).filter((route) => !site.pages.some((p) => p.route === route));
135
+ if (unknown.length)
136
+ throw new Error(`Values are given for routes the site does not have: ${unknown.join(", ")}.`);
137
+ const params = [];
138
+ for (const { route } of site.pages) {
139
+ const names = routeValueNames(route);
140
+ if (!names.length) {
141
+ params.push({ [param]: route === "/" ? [] : route.slice(1).split("/") });
142
+ continue;
143
+ }
144
+ const source = values[route];
145
+ if (!source)
146
+ throw new Error(`"${route}" takes ${names.map((n) => `[${n}]`).join(" and ")}: pass its values to siteParams, as { "${route}": () => [...] }.`);
147
+ for (const given of await source()) {
148
+ const filled = typeof given === "string" ? (names.length === 1 ? { [names[0]]: given } : undefined) : given;
149
+ if (!filled)
150
+ throw new Error(`"${route}" takes ${names.length} values, so give each as an object, such as { ${names.map((n) => `${n}: "…"`).join(", ")} }.`);
151
+ // Next.js hands the segments back decoded, so they are given decoded.
152
+ params.push({ [param]: routePath(route, filled).slice(1).split("/").map(decodeURIComponent) });
153
+ }
154
+ }
155
+ return params;
156
+ }
157
+ //# sourceMappingURL=routes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.js","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAiCA,MAAM,KAAK,GAAG,kCAAkC,CAAC;AACjD,MAAM,KAAK,GAAG,gCAAgC,CAAC;AAE/C,yDAAyD;AACzD,MAAM,UAAU,UAAU,CAAC,KAAa;IACtC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO,EAAE,OAAO,EAAE,gDAAgD,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;IAC/I,IAAI,KAAK,KAAK,GAAG,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,EAAE,OAAO,EAAE,UAAU,KAAK,+BAA+B,EAAE,CAAC;IAC7G,MAAM,KAAK,GAAG,KAAK,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC7D,MAAM,QAAQ,GAAmB,EAAE,CAAC;IACpC,MAAM,KAAK,GAAG,IAAI,GAAG,EAAU,CAAC;IAChC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC/B,IAAI,KAAK,EAAE,CAAC;YACV,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAE,CAAC;YACvB,IAAI,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC;gBAAE,OAAO,E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AE,CAAC,CAAC;YACzE,SAAS;QACX,CAAC;QACD,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;QAC7B,IAAI,CAAC,MAAM;YAAE,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,WAAW,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,0CAA0C,KAAK,mBAAmB,CAAC,CAAC;QAC7J,KAAK,MAAM,KAAK,IAAI,MAAM,MAAM,EAAE,EAAE,CAAC;YACnC,MAAM,MAAM,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,CAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;YAC7G,IAAI,CAAC,MAAM;gBAAE,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,WAAW,KAAK,CAAC,MAAM,iDAAiD,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YAC7J,sEAAsE;YACtE,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,kBAAkB,CAAC,EAAE,CAAC,CAAC;QACjG,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { PageDocument } from \"@surfaces-ui/spec\";\nimport type { ThemeRequest } from \"@surfaces-ui/tokens\";\n\n/** What a route says about itself to search engines and link previews. */\nexport interface SiteMeta {\n title?: string;\n description?: string;\n /** An image for link previews: a name the app's `resolveImage` turns into an address, or an http(s) address. */\n image?: string;\n}\n\n/** One page of a site and the route it is served on. */\nexport interface SiteRoute {\n /** A path: \"/\", \"/pricing\", \"/essays/[slug]\". A segment in brackets takes a value from the app. */\n route: string;\n page: PageDocument;\n meta?: SiteMeta;\n}\n\n/**\n * The pages of a site, each on its route. This is the part of the planned site document (`docs/plans/sites.md`,\n * step 4) that a Next.js app needs to serve pages, so that document will be accepted here as it is.\n */\nexport interface SiteRoutes {\n title?: string;\n /** The look of every page, unless a page asks for its own. */\n theme?: ThemeRequest;\n pages: SiteRoute[];\n}\n\n/** One part of a route: a fixed name, or a value named in brackets. */\nexport type RouteSegment = { kind: \"fixed\"; name: string } | { kind: \"value\"; name: string };\n\nconst FIXED = /^[A-Za-z0-9._~!$&'()*+,;=:@%-]+$/;\nconst VALUE = /^\\[([A-Za-z_][A-Za-z0-9_]*)\\]$/;\n\n/** The segments of a route, or what is wrong with it. */\nexport function parseRoute(route: string): { segments: RouteSegment[] } | { problem: string } {\n if (typeof route !== \"string\" || !route.startsWith(\"/\")) return { problem: `A route is a path that starts with \"/\", not \"${String(route)}\".` };\n if (route !== \"/\" && route.endsWith(\"/\")) return { problem: `Write \"${route}\" without the \"/\" at the end.` };\n const parts = route === \"/\" ? [] : route.slice(1).split(\"/\");\n const segments: RouteSegment[] = [];\n const names = new Set<string>();\n for (const part of parts) {\n const value = VALUE.exec(part);\n if (value) {\n const name = value[1]!;\n if (names.has(name)) return { problem: `\"${route}\" names [${name}] twice.` };\n names.add(name);\n segments.push({ kind: \"value\", name });\n } else if (part.startsWith(\"[\")) {\n return { problem: `\"${part}\" in \"${route}\" is not a value Surfaces can fill: write one name in brackets, such as [slug]. Catch-all segments ([...path]) are not supported.` };\n } else if (!part || part === \".\" || part === \"..\" || !FIXED.test(part)) {\n return { problem: `\"${part}\" in \"${route}\" is not a path segment.` };\n } else {\n segments.push({ kind: \"fixed\", name: part });\n }\n }\n return { segments };\n}\n\n/** The names a route takes values for, in order: [\"slug\"] for \"/essays/[slug]\". */\nexport function routeValueNames(route: string): string[] {\n const parsed = parseRoute(route);\n return \"segments\" in parsed ? parsed.segments.filter((s) => s.kind === \"value\").map((s) => s.name) : [];\n}\n\nexport interface SiteProblem {\n route: string;\n message: string;\n}\n\n/**\n * What is wrong with a site's routes: a route that is not a path, two pages on one route, or two routes that\n * would answer the same address (\"/[a]\" and \"/[b]\"). A fixed route always wins over one with a value, so\n * \"/essays/new\" beside \"/essays/[slug]\" is fine.\n */\nexport function siteProblems(site: SiteRoutes): SiteProblem[] {\n const problems: SiteProblem[] = [];\n const shapes = new Map<string, string>();\n for (const { route, page } of site.pages ?? []) {\n const parsed = parseRoute(route);\n if (\"problem\" in parsed) {\n problems.push({ route, message: parsed.problem });\n continue;\n }\n if (!page || !Array.isArray(page.components)) problems.push({ route, message: `\"${route}\" has no page.` });\n const shape = parsed.segments.map((s) => (s.kind === \"fixed\" ? s.name : \"[]\")).join(\"/\");\n const before = shapes.get(shape);\n if (before === route) problems.push({ route, message: `Two pages are on \"${route}\".` });\n else if (before) problems.push({ route, message: `\"${route}\" and \"${before}\" answer the same addresses. Give one of them a fixed segment.` });\n else shapes.set(shape, route);\n }\n return problems;\n}\n\n/** A page found for an address, with the values its route took from it. */\nexport interface MatchedRoute {\n entry: SiteRoute;\n values: Record<string, string>;\n}\n\n/**\n * The page for an address, given as Next.js gives a catch-all route's segments (`[\"essays\", \"first-post\"]`; none\n * for the home page). A route whose segments are all fixed wins over one that takes values, segment by segment\n * from the left, as in Next.js.\n */\nexport function matchRoute(site: SiteRoutes, segments: readonly string[] | string | undefined): MatchedRoute | undefined {\n const parts = (segments === undefined ? [] : typeof segments === \"string\" ? [segments] : [...segments]).map(decodeSegment);\n if (parts.some((part) => part === undefined)) return undefined;\n let best: { match: MatchedRoute; rank: string } | undefined;\n for (const entry of site.pages ?? []) {\n const parsed = parseRoute(entry.route);\n if (\"problem\" in parsed || parsed.segments.length !== parts.length) continue;\n const values: Record<string, string> = {};\n let fits = true;\n for (const [i, segment] of parsed.segments.entries()) {\n const part = parts[i]!;\n if (segment.kind === \"fixed\") fits = segment.name === part;\n else if (part) values[segment.name] = part;\n else fits = false;\n if (!fits) break;\n }\n if (!fits) continue;\n // \"0\" for a fixed segment sorts before \"1\" for a value: the more fixed segments to the left, the better.\n const rank = parsed.segments.map((s) => (s.kind === \"fixed\" ? \"0\" : \"1\")).join(\"\");\n if (!best || rank < best.rank) best = { match: { entry, values }, rank };\n }\n return best?.match;\n}\n\nfunction decodeSegment(part: string): string | undefined {\n try {\n return decodeURIComponent(part);\n } catch {\n return undefined;\n }\n}\n\n/** The address of a route with its values filled in: \"/essays/first-post\". Values are encoded. */\nexport function routePath(route: string, values: Record<string, string> = {}): string {\n const parsed = parseRoute(route);\n if (\"problem\" in parsed) throw new Error(parsed.problem);\n const parts = parsed.segments.map((segment) => {\n if (segment.kind === \"fixed\") return segment.name;\n const value = values[segment.name];\n if (!value) throw new Error(`\"${route}\" needs a value for [${segment.name}].`);\n return encodeURIComponent(value);\n });\n return `/${parts.join(\"/\")}`;\n}\n\n/**\n * Where a route's values come from, by route: a list of values when it takes one (\"/essays/[slug]\" →\n * `[\"first-post\", \"second-post\"]`), or of objects when it takes several. From files, a CMS or a database; the app\n * decides, and Surfaces only asks.\n */\nexport type RouteValues = Record<string, () => Iterable<string | Record<string, string>> | Promise<Iterable<string | Record<string, string>>>>;\n\nexport interface SiteParamsOptions {\n /** The name of the catch-all segment in the app's folder, `app/[[...route]]`. Default \"route\". */\n param?: string;\n}\n\n/**\n * Every address of a site as Next.js's `generateStaticParams` wants it for an optional catch-all route,\n * `app/[[...route]]/page.tsx`: `[{ route: [] }, { route: [\"pricing\"] }, { route: [\"essays\", \"first-post\"] }]`.\n * A route that takes values with none given is an error, so a static export never leaves a page out quietly.\n */\nexport async function siteParams(site: SiteRoutes, values: RouteValues = {}, options: SiteParamsOptions = {}): Promise<Record<string, string[]>[]> {\n const param = options.param ?? \"route\";\n const problems = siteProblems(site);\n if (problems.length) throw new Error(`The site's routes have problems: ${problems.map((p) => p.message).join(\" \")}`);\n const unknown = Object.keys(values).filter((route) => !site.pages.some((p) => p.route === route));\n if (unknown.length) throw new Error(`Values are given for routes the site does not have: ${unknown.join(\", \")}.`);\n const params: Record<string, string[]>[] = [];\n for (const { route } of site.pages) {\n const names = routeValueNames(route);\n if (!names.length) {\n params.push({ [param]: route === \"/\" ? [] : route.slice(1).split(\"/\") });\n continue;\n }\n const source = values[route];\n if (!source) throw new Error(`\"${route}\" takes ${names.map((n) => `[${n}]`).join(\" and \")}: pass its values to siteParams, as { \"${route}\": () => [...] }.`);\n for (const given of await source()) {\n const filled = typeof given === \"string\" ? (names.length === 1 ? { [names[0]!]: given } : undefined) : given;\n if (!filled) throw new Error(`\"${route}\" takes ${names.length} values, so give each as an object, such as { ${names.map((n) => `${n}: \"…\"`).join(\", \")} }.`);\n // Next.js hands the segments back decoded, so they are given decoded.\n params.push({ [param]: routePath(route, filled).slice(1).split(\"/\").map(decodeURIComponent) });\n }\n }\n return params;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
2
  "name": "@surfaces-ui/next",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.5.0",
4
+ "description": "Serve Surfaces UI pages from a Next.js app: routes, metadata and server-rendered pages, with Next.js doing the routing, building and hosting",
5
+ "keywords": [
6
+ "surfaces-ui",
7
+ "nextjs",
8
+ "next",
9
+ "site",
10
+ "ssr",
11
+ "static-export"
12
+ ],
13
+ "license": "Apache-2.0",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/teradata-labs/surfaces-ui.git",
17
+ "directory": "packages/next"
18
+ },
19
+ "homepage": "https://github.com/teradata-labs/surfaces-ui#readme",
20
+ "bugs": {
21
+ "url": "https://github.com/teradata-labs/surfaces-ui/issues"
22
+ },
23
+ "type": "module",
24
+ "sideEffects": false,
25
+ "main": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "default": "./dist/index.js"
31
+ },
32
+ "./client": {
33
+ "types": "./dist/client.d.ts",
34
+ "default": "./dist/client.js"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "NOTICE"
40
+ ],
41
+ "peerDependencies": {
42
+ "next": ">=15",
43
+ "react": ">=19",
44
+ "react-dom": ">=19"
45
+ },
46
+ "dependencies": {
47
+ "@surfaces-ui/components": "0.5.0",
48
+ "@surfaces-ui/spec": "0.5.0",
49
+ "@surfaces-ui/tokens": "0.5.0"
50
+ },
51
+ "devDependencies": {
52
+ "@testing-library/react": "^16.3.3",
53
+ "@types/react": "^19.3.0",
54
+ "@types/react-dom": "^19.3.0",
55
+ "jsdom": "^31.0.0",
56
+ "next": "16.4.6",
57
+ "react": "^19.3.1",
58
+ "react-dom": "^19.3.1",
59
+ "@surfaces-ui/data": "0.5.0"
60
+ },
61
+ "publishConfig": {
62
+ "access": "public",
63
+ "provenance": true
64
+ },
65
+ "scripts": {
66
+ "build": "tsc -p tsconfig.build.json",
67
+ "typecheck": "tsc -p tsconfig.json --noEmit",
68
+ "test": "vitest run --passWithNoTests"
69
+ }
6
70
  }