foldkit-site 0.0.0-stage → 0.2.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Patrick Glenn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,356 @@
1
- # Temporary Holding Version
1
+ # `foldkit-site`
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
+ The deployed route topology of a Foldkit application: which locations exist,
4
+ how they nest, what each is called, and what it activates — as data that
5
+ compiles down to the primitives the runtime already runs.
6
+
7
+ ## What this package is
8
+
9
+ Every application with more than one screen answers the same questions: what
10
+ places exist, which place are we on, how do places link to each other, and
11
+ what does each place show. Foldkit's Router already answers the URL half with
12
+ bidirectional parsers. `foldkit-site` answers the structural half: a tree of
13
+ stable route nodes over those parsers, with one annotated place for the
14
+ metadata (titles, sections, history intent) that applications otherwise
15
+ recompute in four parallel tables.
16
+
17
+ ## When it owns the problem
18
+
19
+ `foldkit-site` owns **where the application is**, and nothing else:
20
+
21
+ ```text
22
+ Site "What location are we at, and what is around it?"
23
+ Surface "What may this location observe, and which Messages may it cause?"
24
+ Remote "What server facts do those observations require?"
25
+ ```
26
+
27
+ It owns no Model, runs no Effects, dispatches no Messages, and fetches
28
+ nothing. A node lowers to an ordinary Foldkit Router (which it is built
29
+ from), an ordinary `Surface.when` (through `Site.sources`), and — in a later
30
+ cut — an ordinary Bundle placement. If a feature would need the Site to
31
+ become another store, async runtime, or cache, it does not belong here.
32
+
33
+ ## The mental model
34
+
35
+ ```text
36
+ Foldkit Router (per node) URL <-> typed route value
37
+ +
38
+ Site tree route value -> chain, metadata, Surfaces
39
+ +
40
+ Surface / Remote / SSR the existing consumers of those answers
41
+ ```
42
+
43
+ A node is a stable first-class value: mounting it in a tree never mutates
44
+ it, so the same node builds targets, hrefs, and inspection wherever it is
45
+ mounted. A target is one typed destination — node, route value, and URL from
46
+ one declaration — so a link can never point where the parser would not go.
47
+
48
+ ## Install
49
+
50
+ ```sh
51
+ pnpm add foldkit-site
52
+ ```
53
+
54
+ Peers: `effect`, `foldkit`. `foldkit-surface` is a dependency (for
55
+ `Site.sources`), and `foldkit-ssr` for the `Meta` a node's head returns.
56
+
57
+ ## 60-second example
58
+
59
+ ```ts
60
+ import { Site } from 'foldkit-site'
61
+
62
+ const Home = Site.route(homeRouter, AppRoute.Home, { title: () => 'Routing' })
63
+ const Person = Site.route(personRouter, AppRoute.Person, {
64
+ title: ({ personId }) => `Person ${personId} | Routing`,
65
+ section: 'People',
66
+ })
67
+
68
+ const AppSite = Site.make(Home, Site.mount(People, [Person]))
69
+
70
+ // One declaration builds the value and the address together.
71
+ const target = Site.target(Person, { personId: 3 })
72
+ target.route // AppRoute.Person({ personId: 3 })
73
+ target.url // '/people/3'
74
+
75
+ // And the tree answers structural questions off route values.
76
+ Site.chainOf(AppSite, target.route) // [People, Person]
77
+ Site.titleOf(AppSite, target.route) // 'Person 3 | Routing'
78
+ Site.sectionOf(AppSite, target.route) // 'People'
79
+ ```
80
+
81
+ `Site.route` takes an existing full Foldkit Router — `literal`, `slash`,
82
+ `query`, `mapTo`, all of it — and the route case it builds. The router stays
83
+ the whole URL story; the Site adds hierarchy, metadata, and inspection
84
+ without re-parsing anything.
85
+
86
+ ## Core concepts
87
+
88
+ **Nodes.** `Site.route(router, case, options?)` declares one location. Options
89
+ are `title` (a function of the route value), `section`, `landing` (the
90
+ section's nav address as this node's params), `shortcut` (the keys that go to
91
+ its landing, as Foldkit's key bindings name them: `'/'`, `['G', 'H']`), `history`, and `surface` (below). The node is frozen; keep the
92
+ exported value and use it for targets and hrefs. To annotate in steps, or to
93
+ share an annotation bundle across nodes, build incrementally instead — the
94
+ options are sugar over this builder:
95
+
96
+ ```ts
97
+ const Person = Site.node(personRouter, AppRoute.Person)
98
+ .title(({ personId }) => `Person ${personId} | Routing`)
99
+ .section('People')
100
+ .node
101
+ ```
102
+
103
+ Methods — not pipeable fragments — because each stage of a pipe is a
104
+ separate generic call and could not infer the route. Read `.node` at any
105
+ stage: every step freezes, so intermediates are usable nodes too, never
106
+ drafts. Named bundles also compose through `.pipe` (Effect-style, one
107
+ bundle; chain for more) or free `pipe(builder, bundle)` — the bundle stays
108
+ generic over the builder it meets, so it instantiates with no annotation.
109
+
110
+ **Trees.** `Site.mount(node, children?)` mounts a node under children without
111
+ mutating it — children may be bare nodes or mounts. `Site.make(...roots)`
112
+ freezes the topology. Two nodes sharing a tag, or one node mounted twice,
113
+ throw at `make`: both would make chain inspection ambiguous.
114
+
115
+ **Targets.** `Site.target(node, params)` is `{ node, route, url }`.
116
+ `Site.href(target)` — or `Site.href(node, params)` — is its URL. Because the
117
+ URL is built by the node's own router, a round trip holds by construction: a
118
+ built URL parses back to the target's route (there is a test proving it).
119
+
120
+ **Both directions.** A tree's type carries its routes, so the tree is the
121
+ one declaration of address to route and back. `Site.parse(site, NotFound)`
122
+ is the application's parser: the first node, in tree order (depth-first,
123
+ parents first), whose router takes the whole address, or the fallback; put a
124
+ node that takes any segment (`/:slug`) after the nodes whose literal it would
125
+ take too. `Site.hrefOf(site, route)` builds a route's address with its node's
126
+ router, and refuses at compile time a route no node holds.
127
+
128
+ **One tree, one document.** A tree holds the routes one application draws.
129
+ `Site.routeAt(site, url)` is the route a node reads at an address, as
130
+ `Site.parse` reads it, or `None` when no node takes it: an address the tree
131
+ does not hold is another document's, reached with a full load, not a
132
+ Navigate Command that could only draw NotFound.
133
+
134
+ **Every address.** `Site.targets(site, paths)` lists the site in tree order:
135
+ a node whose route has no params once, and a node with params by its
136
+ `Site.paths(node, list)`, where `list` is an Effect giving each address's
137
+ params and, for a sitemap, when it last changed:
138
+
139
+ ```ts
140
+ const list = Site.paths(People, Effect.succeed([{ params: { searchText: Option.none() } }]))
141
+ const people = Site.paths(
142
+ Person,
143
+ Effect.succeed([{ params: { personId: 3 }, modified: '2026-10-01' }]),
144
+ )
145
+ const listed = Site.targets(AppSite, [list, people])
146
+ // an Effect of [..., { node: Person, route, url: '/people/3', modified: '2026-10-01' }]
147
+ ```
148
+
149
+ A build renders what it lists, a sitemap keeps what `Site.indexedOf` keeps,
150
+ and prefetch can warm it. A node with params and no `paths`, `paths` for a
151
+ node the tree does not hold, and `paths` given twice are refused, so no page
152
+ is left out unsaid; `Site.paths(node, Effect.succeed([]))` lists none. Its
153
+ failures and services are those of the lists, typed.
154
+
155
+ **Inspection.** `Site.nodeOf(site, route)` and `Site.chainOf(site, route)`
156
+ resolve a route value to its node and its root-first chain (`[]` for a tag
157
+ the tree does not hold, as an inactive Surface resolves to nothing).
158
+ `Site.parentOf`, `Site.ancestorsOf`, `Site.depthOf`, and `Site.nodesOf`
159
+ (depth-first, parents before children) cover the rest.
160
+
161
+ **History.** `Site.historyOf(prev, next)` declares push-vs-replace once: to
162
+ another node — or from an unknown location, so Back can still return to it — a
163
+ step; within a node, its `history` rule (a string, or a function for nodes
164
+ where some param changes are entries of their own, such as another person,
165
+ and others are views of one entry, such as another search). This unifies the
166
+ mirror's per-key spelling with the routed code that used to spell the same
167
+ rule by hand.
168
+
169
+ **Navigation metadata.** Titles and sections read with `Site.titleOf` and
170
+ `Site.sectionOf`. `Site.landing(site, section)` is where the section's nav
171
+ item points: the first node of the section that declares a landing, as a
172
+ target. `Site.shortcuts(site, toMessage)` is the tree's shortcuts as key
173
+ bindings for `Subscription.keyBindings`, each sending the Message
174
+ `toMessage` makes of its node's landing target; a shortcut with no landing,
175
+ or one used twice, is refused. Annotate once; derive nav, titles, shortcuts,
176
+ and breadcrumbs from it.
177
+
178
+ **Head metadata.** `meta` is what a node says of itself to a search result
179
+ and a link preview: a function of its route and the Model, since a post's
180
+ excerpt is data, not an address. It returns `foldkit-ssr`'s `Meta`
181
+ (description, image, type, article dates, JSON-LD, ...). `indexed: false`
182
+ keeps a node, and every node below it that does not say otherwise, out of
183
+ search engines. `Site.metaOf(site, route, model)` reads the route's chain
184
+ root first, a deeper node's field replacing its ancestor's, the preview
185
+ title falling back to the node's `title`, and `noindex` for an unindexed
186
+ route whatever its `meta` says. It is an SSR plan's `meta` as it stands:
187
+
188
+ ```ts
189
+ const Person = Site.node(personRouter, AppRoute.Person)
190
+ .title(({ personId }) => `Person ${personId} | Routing`)
191
+ .meta<Model>(({ route, model }) => ({ description: model.bios[route.personId] }))
192
+ .node
193
+ const Nested = Site.route(nestedRouter, AppRoute.Nested, { indexed: false })
194
+
195
+ const plan = SSR.plan(App, {
196
+ id: 'site',
197
+ state: Projection.pick(App.model.route, App.model.bios),
198
+ meta: model => Site.metaOf(AppSite, model.route, model),
199
+ })
200
+ ```
201
+
202
+ The plan writes it into the generated page and keeps the head in step as the
203
+ reader moves; the Site only says what it is. `meta` must read what crosses
204
+ to the browser (the route, a resumed read), as any plan's `meta` must.
205
+ `Site.indexedOf(site, route)` is the same flag for a sitemap.
206
+
207
+ ## Nested rendering
208
+
209
+ `Site.view(site, route, model, h)` draws the route: the deepest node's view,
210
+ wrapped by every ancestor's layout root-first. Declare them on nodes:
211
+
212
+ ```ts
213
+ const Section = Site.route(sectionRouter, AppRoute.Section, {
214
+ layout: {
215
+ render: (child, model, h) => h.div([], [sidebar(model, h), child]),
216
+ },
217
+ view: {
218
+ render: (model, h) => h.ul([], [...]),
219
+ },
220
+ })
221
+ ```
222
+
223
+ Ancestors contribute layouts only — never their views. A layout receives its
224
+ composed child explicitly: no Outlet, no context provider, no hidden route
225
+ state, no child router. Unknown tags and viewless leaves fail loudly instead
226
+ of guessing.
227
+
228
+ **Attached Surfaces.** A node may name the Surface its route activates:
229
+
230
+ ```ts
231
+ const People = Site.route(peopleRouter, AppRoute.People, {
232
+ surface: {
233
+ surface: PeoplePage,
234
+ params: route => ({ searchText: route.searchText }),
235
+ },
236
+ })
237
+ ```
238
+
239
+ `Site.sources(site, App.owner, App.model.route)` is each surfaced node as its
240
+ `Surface.when`, keyed by tag, for `Data.wiring`, `Data.subscriptions`,
241
+ `Data.satisfy`, or an SSR plan's `surfaces`. A surface from another
242
+ application is refused here. Each entry answers its own tag only: on a
243
+ person page the person surface is active and the people surface is not.
244
+ `Site.sourcesFor(site, owner, place, target.route)` is the same entries for
245
+ the target's chain only — the route-level Sources prefetch and SSR read. A
246
+ layout surface active for several tags is not yet expressible — that is a
247
+ `Surface.whenAny`-shaped extension, deliberately deferred until a real layout
248
+ needs it.
249
+
250
+ ## Routed pages
251
+
252
+ `Site.placement` states one routed page once — its link, what starts it, and
253
+ what its route arrival tells it — so the fold and the drawing never restate
254
+ the field, the wrapper, or the slot:
255
+
256
+ ```ts
257
+ const PeoplePage = Site.placement(People, PeopleBundle, {
258
+ link: Link.field<Model>()('peoplePage', Link.wrapper(Message.GotPeopleMessage)),
259
+ args: parent => ({
260
+ searchText: parent.route._tag === 'People' ? parent.route.searchText : Option.none(),
261
+ }),
262
+ changed: route => People.Message.ChangedRoute({ route }),
263
+ })
264
+
265
+ const assembly = Bundle.assemble([PeoplePage.placed, Routing])
266
+ const update = assembly.update((model, message) =>
267
+ Routing.reduces(message) || message._tag === 'GotPeopleMessage' ? { model } : updateOwn(model, message),
268
+ )
269
+ ```
270
+
271
+ `placed.update` folds the child's Messages (route it in `update` through the
272
+ assembly; the wrapper tag never reaches your own branches) and `placed.view`
273
+ draws it. `changed` receives the node's own case value when its route
274
+ arrives and returns the child's Message — or nothing when the arrival needs
275
+ no answer. Pass the pages to `Site.routing` (`pages: [PeoplePage]`) and the
276
+ wiring informs each page whose route arrives, after setting the route field.
277
+
278
+ Without `changed` a page is never informed. Bundles with OutMessages, and
279
+ children that are not Bundles, stay on `Bundle.at` and `Link.child` directly.
280
+ With service-needing pages, name the services on both calls:
281
+ `Site.routing<Model, Message, AppRoute, RemoteClient>`.
282
+
283
+ ## The lifecycle wiring
284
+
285
+ `Site.routing` is the application's link-click and URL-change lifecycle as
286
+ one wiring, so `update` stops hand-writing those two branches:
287
+
288
+ ```ts
289
+ import { modifyFields } from 'foldkit/struct'
290
+
291
+ const Routing = Site.routing<Model, Message, AppRoute>({
292
+ site: AppSite,
293
+ owner: App.owner,
294
+ route: {
295
+ dependency: App.model.route.dependency,
296
+ get: (model) => model.route,
297
+ set: (model, route) => modifyFields(model, { route: () => route }),
298
+ },
299
+ parse: urlToAppRoute,
300
+ tags: { clicked: 'ClickedLink', changed: 'ChangedUrl' },
301
+ completed: Message.CompletedNavigation,
302
+ })
303
+
304
+ const assembly = Bundle.assemble([Routing, ...pages])
305
+ const update = assembly.update((model, message) =>
306
+ Routing.reduces(message) ? { model } : updateOwn(model, message),
307
+ )
308
+ ```
309
+
310
+ A click on a link the tree holds navigates — pushing or replacing per
311
+ `Site.historyOf`, computed from the current route, so entries stay entries.
312
+ Any other link loads, on this origin or not (`Site.routeAt`): another
313
+ application serves it. A URL change sets the route field, or returns the
314
+ same Model when the address parses to the route already shown, so an echo of
315
+ our own write never re-renders or clears pending state. The application's own
316
+ update answers nothing for either message; `reduces` names them for its
317
+ guard, the way `Remote.reduces` does. What a new route does beyond setting
318
+ the field is `arrived: (model, route) => ({ model, commands })`, run after the
319
+ routed pages are told and never for an echo: the CMS site moves focus to what
320
+ it drew there (`examples/cms/src/apps/siteApp.ts`).
321
+
322
+ The wiring claims the click tag and shares the change tag with URL mirrors,
323
+ which read their slices first. `CompletedNavigation` is one completion for
324
+ the navigation commands — declare the variant, pass the constructor. Route
325
+ changes reach child pages through their own Messages only once routed
326
+ placements land; until then informing them stays hand-written.
327
+
328
+ ## Common workflows
329
+
330
+ **Navigation rendering.** Derive the nav from the tree instead of keeping
331
+ parallel tables: sections in tree order, hrefs from `Site.landing`, titles
332
+ from `Site.titleOf`, key bindings from `Site.shortcuts`, and the current
333
+ section by comparing tags.
334
+
335
+ **Route changes.** On a URL change, resolve the route value once, then
336
+ `Site.chainOf` for the active chain and `Site.historyOf` for the history
337
+ step — or hand both branches to `Site.routing` (with `pages` for the routed
338
+ placements) and keep only the guard in `update`. What each route *does* with
339
+ the change beyond informing its page is still the application's `update`.
340
+
341
+ **Prefetch and SSR.** `Site.target` plus `Site.chainOf` say which Surfaces a
342
+ destination will activate; `Site.sourcesFor(site, owner, place, target.route)`
343
+ is those as Sources — `Data.satisfy` over them, with the route set to the
344
+ target's, prepares the Model before a synchronous render. Preparation stays
345
+ caller-composed — there is no `prepare` in any plan.
346
+
347
+ ## Limits / when not to use it
348
+
349
+ - A single-screen application has one node; the tree buys nothing.
350
+ - Bundles with OutMessages, and children that are not Bundles, stay on
351
+ `Bundle.at` and `Link.child`: `Site.placement` takes neither `onOut` nor a
352
+ non-Bundle child.
353
+ - A node's `history` function sees only its own route values; cross-node
354
+ rules more subtle than "another node is a step" do not exist yet.
355
+ - Locales are route params like any other when they arrive; themes are
356
+ preferences, not routes.