foldkit-ssr 0.8.2 → 0.9.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/README.md +203 -69
- package/dist/client-F16QT0sc.d.ts +75 -0
- package/dist/client-F16QT0sc.d.ts.map +1 -0
- package/dist/client.d.ts +5 -0
- package/dist/client.js +271 -0
- package/dist/client.js.map +1 -0
- package/dist/context.d.ts +2 -0
- package/dist/context.js +21 -0
- package/dist/context.js.map +1 -0
- package/dist/diagnostics.d.ts +2 -0
- package/dist/diagnostics.js +59 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/{index.d.mts → index.d.ts} +18 -7
- package/dist/index.d.ts.map +1 -0
- package/dist/{index.mjs → index.js} +79 -60
- package/dist/index.js.map +1 -0
- package/dist/listen-zNd0IIAT.d.ts +69 -0
- package/dist/listen-zNd0IIAT.d.ts.map +1 -0
- package/dist/listen.d.ts +2 -0
- package/dist/listen.js +179 -0
- package/dist/listen.js.map +1 -0
- package/dist/requestContext-D9nsbGSJ.d.ts +21 -0
- package/dist/requestContext-D9nsbGSJ.d.ts.map +1 -0
- package/dist/requestContext.d.ts +2 -0
- package/dist/requestContext.js +48 -0
- package/dist/requestContext.js.map +1 -0
- package/dist/resumable-BWItJsxF.d.ts +86 -0
- package/dist/resumable-BWItJsxF.d.ts.map +1 -0
- package/dist/resumable.d.ts +2 -0
- package/dist/resumable.js +358 -0
- package/dist/resumable.js.map +1 -0
- package/dist/{client-DkwAniQQ.d.mts → shared-v1u-OEQI.d.ts} +218 -194
- package/dist/shared-v1u-OEQI.d.ts.map +1 -0
- package/dist/shared.d.ts +2 -0
- package/dist/shared.js +324 -0
- package/dist/shared.js.map +1 -0
- package/dist/{vite.d.mts → vite.d.ts} +3 -5
- package/dist/vite.d.ts.map +1 -0
- package/dist/{vite.mjs → vite.js} +3 -4
- package/dist/vite.js.map +1 -0
- package/package.json +17 -17
- package/dist/client-DVG9_3rL.mjs +0 -1113
- package/dist/client-DVG9_3rL.mjs.map +0 -1
- package/dist/client-DkwAniQQ.d.mts.map +0 -1
- package/dist/client.d.mts +0 -2
- package/dist/client.mjs +0 -1
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/vite.d.mts.map +0 -1
- package/dist/vite.mjs.map +0 -1
package/dist/client.js
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import { withContext } from "./context.js";
|
|
2
|
+
import { bundleUnloaded, noBuildId, otherBuild, pageContained, reportingTo } from "./diagnostics.js";
|
|
3
|
+
import { BINDING_ATTRIBUTE, FALLBACK_FIELD, SLOT_ATTRIBUTE, builder, view } from "./resumable.js";
|
|
4
|
+
import { listen } from "./listen.js";
|
|
5
|
+
import { FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, bindings, bindingsAndEvents, metaEntry, metaMarkup, plan, resume, routeOf, serving, startingFrom, staticRegion } from "./shared.js";
|
|
6
|
+
import { Effect, Option, Result, Schema, Stream } from "effect";
|
|
7
|
+
import { hydrate, makeApplication, run } from "foldkit/runtime";
|
|
8
|
+
import * as Render from "foldkit/render";
|
|
9
|
+
import { Diagnostics, Diagnostics as Diagnostics$1 } from "foldkit-surface";
|
|
10
|
+
// src/client.ts
|
|
11
|
+
/**
|
|
12
|
+
* `foldkit-ssr/client`: what a browser page needs to take a server render
|
|
13
|
+
* over, and nothing that renders one. It never imports
|
|
14
|
+
* `foldkit/experimental/server`, whose renderer and HTML parser a hydrating
|
|
15
|
+
* page would otherwise carry; `foldkit-ssr` is this and the server side.
|
|
16
|
+
*/
|
|
17
|
+
/** Each static region's markup in the page, read before hydration touches it. */
|
|
18
|
+
const snapshotsOf = (root) => new Map(Array.from(root.querySelectorAll(`[${STATIC_ATTRIBUTE}]`), (element) => [element.getAttribute("data-foldkit-plus-static") ?? "", element.innerHTML]));
|
|
19
|
+
/**
|
|
20
|
+
* The build attribute on Foldkit's hydration root. Foldkit does not export it,
|
|
21
|
+
* as it does the app and Flags attributes; a test pins it to what Foldkit's
|
|
22
|
+
* server stamps.
|
|
23
|
+
*/
|
|
24
|
+
const BUILD_ATTRIBUTE = "data-foldkit-build";
|
|
25
|
+
/**
|
|
26
|
+
* Starts the browser from the page's resumed Model, without running `init`.
|
|
27
|
+
*
|
|
28
|
+
* In the order Foldkit checks a page: the build id first, before the payload
|
|
29
|
+
* is read, then the envelope and its route. A page from another build is
|
|
30
|
+
* refused by Foldkit itself. A page that cannot resume is refused and contained
|
|
31
|
+
* by Foldkit's own refusal, and the reason is reported (`options.diagnostics`). A server page is never
|
|
32
|
+
* rendered again on the client. A page with no server render at all, no
|
|
33
|
+
* stamped root, is rendered on the client as usual.
|
|
34
|
+
*/
|
|
35
|
+
const hydrate$1 = (config, plan, options) => {
|
|
36
|
+
const report = (diagnostic) => {
|
|
37
|
+
Effect.runFork(reportingTo(options.diagnostics)(Diagnostics$1.report(diagnostic)));
|
|
38
|
+
};
|
|
39
|
+
const planMeta = plan.meta;
|
|
40
|
+
if (planMeta !== void 0) config = {
|
|
41
|
+
...config,
|
|
42
|
+
subscriptions: {
|
|
43
|
+
...config.subscriptions,
|
|
44
|
+
"foldkit-ssr.meta": metaEntry(planMeta)
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
const root = document.querySelector(`[${FOLDKIT_APP_ATTRIBUTE}]`);
|
|
48
|
+
const declined = options.when !== void 0 && !options.when(document);
|
|
49
|
+
const stale = options.fresh !== void 0 && !options.fresh(plan.version);
|
|
50
|
+
if (root === null) {
|
|
51
|
+
run(makeApplication(config));
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const program = (start) => makeApplication({
|
|
55
|
+
...startingFrom(config, start),
|
|
56
|
+
container: root
|
|
57
|
+
});
|
|
58
|
+
const contain = () => hydrate(program({ model: plan.baseline }), { buildId: "" });
|
|
59
|
+
if (declined || stale) {
|
|
60
|
+
if (options.otherwise !== "render") contain();
|
|
61
|
+
else if (options.until === void 0) run(makeApplication({
|
|
62
|
+
...config,
|
|
63
|
+
container: root
|
|
64
|
+
}));
|
|
65
|
+
else renderBeside(config, root, options.until);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
if (typeof options.buildId !== "string") {
|
|
69
|
+
report(noBuildId);
|
|
70
|
+
contain();
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const served = root.getAttribute(BUILD_ATTRIBUTE);
|
|
74
|
+
if (served !== options.buildId) {
|
|
75
|
+
report(otherBuild(Option.fromNullOr(served), options.buildId));
|
|
76
|
+
hydrate(program({ model: plan.baseline }), { buildId: options.buildId });
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const resumed = resume(plan, document, { route: routeOf(window.location.href) });
|
|
80
|
+
if (Result.isFailure(resumed)) {
|
|
81
|
+
report(pageContained(resumed.failure.reason, resumed.failure.message));
|
|
82
|
+
contain();
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const model = resumed.success;
|
|
86
|
+
const commands = plan.boot?.(model) ?? [];
|
|
87
|
+
const resuming = {
|
|
88
|
+
mode: "resume",
|
|
89
|
+
snapshots: snapshotsOf(root),
|
|
90
|
+
reported: /* @__PURE__ */ new Set(),
|
|
91
|
+
report
|
|
92
|
+
};
|
|
93
|
+
const answered = [];
|
|
94
|
+
const apply = config.update;
|
|
95
|
+
const update = (current, message) => {
|
|
96
|
+
const handingOver = message === HANDOVER;
|
|
97
|
+
if (answered.length === 0) return handingOver ? { model: current } : apply(current, message);
|
|
98
|
+
const returned = [];
|
|
99
|
+
for (const next of [...answered.splice(0), ...handingOver ? [] : [message]]) {
|
|
100
|
+
const step = apply(current, next);
|
|
101
|
+
current = step.model;
|
|
102
|
+
returned.push(...step.commands ?? []);
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
model: current,
|
|
106
|
+
commands: returned
|
|
107
|
+
};
|
|
108
|
+
};
|
|
109
|
+
const boot = (entries = {}) => hydrate(makeApplication({
|
|
110
|
+
...withContext(startingFrom({
|
|
111
|
+
...config,
|
|
112
|
+
update
|
|
113
|
+
}, {
|
|
114
|
+
model,
|
|
115
|
+
commands
|
|
116
|
+
}), resuming),
|
|
117
|
+
container: root,
|
|
118
|
+
subscriptions: {
|
|
119
|
+
...config.subscriptions,
|
|
120
|
+
...entries
|
|
121
|
+
}
|
|
122
|
+
}), { buildId: options.buildId });
|
|
123
|
+
const pending = (config.lazy ?? []).filter((bundle) => !bundle.isLoaded());
|
|
124
|
+
if (plan.start === "now" && pending.length === 0) {
|
|
125
|
+
boot();
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
const decoded = bindingsAndEvents(plan, document, root, model);
|
|
129
|
+
if (Result.isFailure(decoded)) {
|
|
130
|
+
report(pageContained(decoded.failure.reason, decoded.failure.message));
|
|
131
|
+
contain();
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
deferBoot(root, decoded.success, plan.start, {
|
|
135
|
+
boot,
|
|
136
|
+
answered
|
|
137
|
+
}, pending, report);
|
|
138
|
+
};
|
|
139
|
+
/** The longest a served page stays in view while a fresh application waits for `until`. */
|
|
140
|
+
const UNTIL_LIMIT_MS = 3e3;
|
|
141
|
+
/**
|
|
142
|
+
* Runs the application afresh out of view, beside the served page, and puts
|
|
143
|
+
* it in the page's place once a Model it drew satisfies `until`, or after
|
|
144
|
+
* `UNTIL_LIMIT_MS`. It draws in a hidden element, not a detached one, so its
|
|
145
|
+
* Mounts start in the document as they would in place.
|
|
146
|
+
*/
|
|
147
|
+
const renderBeside = (config, served, until) => {
|
|
148
|
+
const holder = document.createElement("div");
|
|
149
|
+
holder.hidden = true;
|
|
150
|
+
const container = document.createElement("div");
|
|
151
|
+
container.id = served.id === "" ? "foldkit-ssr-app" : served.id;
|
|
152
|
+
served.removeAttribute("id");
|
|
153
|
+
served.removeAttribute(FOLDKIT_APP_ATTRIBUTE);
|
|
154
|
+
holder.append(container);
|
|
155
|
+
served.after(holder);
|
|
156
|
+
let shown = false;
|
|
157
|
+
const show = () => {
|
|
158
|
+
if (shown) return;
|
|
159
|
+
shown = true;
|
|
160
|
+
clearTimeout(limit);
|
|
161
|
+
holder.replaceWith(...holder.childNodes);
|
|
162
|
+
served.remove();
|
|
163
|
+
};
|
|
164
|
+
const limit = setTimeout(show, UNTIL_LIMIT_MS);
|
|
165
|
+
const view = (model, h) => {
|
|
166
|
+
const drawn = config.view(model, h);
|
|
167
|
+
if (!shown && until(model)) queueMicrotask(show);
|
|
168
|
+
return drawn;
|
|
169
|
+
};
|
|
170
|
+
run(makeApplication({
|
|
171
|
+
...config,
|
|
172
|
+
view,
|
|
173
|
+
container
|
|
174
|
+
}));
|
|
175
|
+
};
|
|
176
|
+
/**
|
|
177
|
+
* The Message the handover entry sends so the runtime takes the answered
|
|
178
|
+
* Messages when nothing else has asked it to. The wrapped `update` consumes
|
|
179
|
+
* it; the application never sees it.
|
|
180
|
+
*/
|
|
181
|
+
const HANDOVER = Object.freeze({ _tag: "foldkit-ssr/Handover" });
|
|
182
|
+
/**
|
|
183
|
+
* Lets the page answer from its bindings until something asks for the
|
|
184
|
+
* runtime, then boots it and hands over to the live page.
|
|
185
|
+
*
|
|
186
|
+
* Every Message the page answers goes to `answered`, which the runtime takes
|
|
187
|
+
* before its first Message. An event only the live page can answer is kept
|
|
188
|
+
* and sent again to where it first went once the live page listens. The page
|
|
189
|
+
* stops listening as soon as the runtime's first render has committed: when
|
|
190
|
+
* `hydrate` returns, which Foldkit does today, or else when a handover
|
|
191
|
+
* Subscription entry starts, after `Render.afterCommit`. When lazy bundles
|
|
192
|
+
* must load first, the boot waits for them and the page keeps answering.
|
|
193
|
+
*/
|
|
194
|
+
const deferBoot = (root, decoded, start, runtime, pending, report) => {
|
|
195
|
+
const unanswered = [];
|
|
196
|
+
let phase = "waiting";
|
|
197
|
+
const stop = listen(root, {
|
|
198
|
+
bindings: decoded.bindings,
|
|
199
|
+
...decoded.events === void 0 ? {} : { events: decoded.events },
|
|
200
|
+
onAnswer: ({ event, messages, unnamed }) => {
|
|
201
|
+
if (unnamed !== void 0) {
|
|
202
|
+
startNow();
|
|
203
|
+
if (phase !== "live" && event.target instanceof Element) unanswered.push({
|
|
204
|
+
event,
|
|
205
|
+
element: event.target
|
|
206
|
+
});
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
if (messages.length === 0) {
|
|
210
|
+
startNow();
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
runtime.answered.push(...messages);
|
|
214
|
+
event.stopPropagation();
|
|
215
|
+
startNow();
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
const handOver = () => {
|
|
219
|
+
if (phase === "live") return;
|
|
220
|
+
phase = "live";
|
|
221
|
+
stop();
|
|
222
|
+
for (const { event, element } of unanswered.splice(0)) {
|
|
223
|
+
const Ctor = event.constructor;
|
|
224
|
+
element.dispatchEvent(new Ctor(event.type, event));
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
const commit = () => {
|
|
228
|
+
phase = "starting";
|
|
229
|
+
runtime.boot({ "foldkit-ssr.handover": {
|
|
230
|
+
dependenciesSchema: Schema.Null,
|
|
231
|
+
modelToDependencies: () => null,
|
|
232
|
+
dependenciesToStream: () => Stream.fromEffect(Effect.as(Effect.andThen(root.hasAttribute("data-foldkit-app") ? Render.afterCommit : Effect.void, Effect.sync(handOver)), HANDOVER))
|
|
233
|
+
} });
|
|
234
|
+
if (!root.hasAttribute("data-foldkit-app")) handOver();
|
|
235
|
+
};
|
|
236
|
+
const startNow = () => {
|
|
237
|
+
if (phase !== "waiting") return;
|
|
238
|
+
phase = "loading";
|
|
239
|
+
if (pending.length === 0) {
|
|
240
|
+
commit();
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
Promise.all(pending.map((bundle) => bundle.load())).then(commit, (error) => {
|
|
244
|
+
report(bundleUnloaded(error));
|
|
245
|
+
commit();
|
|
246
|
+
});
|
|
247
|
+
};
|
|
248
|
+
if (start === "now") startNow();
|
|
249
|
+
else if (start === "idle") {
|
|
250
|
+
if (typeof window.requestIdleCallback === "function") window.requestIdleCallback(startNow);
|
|
251
|
+
else setTimeout(startNow, 0);
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
/** The resumable track: bindings the server's markup names, so a page can answer before it boots. */
|
|
255
|
+
const Resume = {
|
|
256
|
+
builder,
|
|
257
|
+
view,
|
|
258
|
+
bindings,
|
|
259
|
+
listen
|
|
260
|
+
};
|
|
261
|
+
/** The browser's part of `SSR`: the same functions, without the server's. */
|
|
262
|
+
const SSR = {
|
|
263
|
+
plan,
|
|
264
|
+
resume,
|
|
265
|
+
hydrate: hydrate$1,
|
|
266
|
+
static: staticRegion,
|
|
267
|
+
serving
|
|
268
|
+
};
|
|
269
|
+
export { BINDING_ATTRIBUTE, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, Resume, ResumeRefused, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, UNTIL_LIMIT_MS, metaMarkup };
|
|
270
|
+
|
|
271
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","names":["hydrate","Diagnostics","adopt"],"sources":["../src/client.ts"],"sourcesContent":["/**\n * `foldkit-ssr/client`: what a browser page needs to take a server render\n * over, and nothing that renders one. It never imports\n * `foldkit/experimental/server`, whose renderer and HTML parser a hydrating\n * page would otherwise carry; `foldkit-ssr` is this and the server side.\n */\nimport { Effect, Option, Result, Schema, Stream } from 'effect'\nimport { hydrate as adopt, makeApplication, run } from 'foldkit/runtime'\nimport * as Render from 'foldkit/render'\nimport { Diagnostics, type ReportDiagnostic } from 'foldkit-surface'\nimport { withContext, type RenderContext } from './context.js'\nimport {\n bundleUnloaded,\n noBuildId,\n otherBuild,\n pageContained,\n reportingTo,\n type SsrDiagnostic,\n} from './diagnostics.js'\nimport { listen, type DecodedBinding } from './listen.js'\nimport { builder, view } from './resumable.js'\nimport {\n FOLDKIT_APP_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n bindings,\n bindingsAndEvents,\n metaEntry,\n plan,\n resume,\n routeOf,\n serving,\n startingFrom,\n staticRegion,\n type Loadable,\n type ResumableConfig,\n type ResumePlan,\n type Start,\n} from './shared.js'\n\n/** Foldkit's root stamp, defined beside the envelope that rides on the same root. */\nexport { FOLDKIT_APP_ATTRIBUTE } from './shared.js'\n\n/** Each static region's markup in the page, read before hydration touches it. */\nconst snapshotsOf = (root: Element): ReadonlyMap<string, string> =>\n new Map(\n Array.from(root.querySelectorAll(`[${STATIC_ATTRIBUTE}]`), element => [\n element.getAttribute(STATIC_ATTRIBUTE) ?? '',\n element.innerHTML,\n ]),\n )\n\n/**\n * The build attribute on Foldkit's hydration root. Foldkit does not export it,\n * as it does the app and Flags attributes; a test pins it to what Foldkit's\n * server stamps.\n */\nconst BUILD_ATTRIBUTE = 'data-foldkit-build'\n\n/**\n * Starts the browser from the page's resumed Model, without running `init`.\n *\n * In the order Foldkit checks a page: the build id first, before the payload\n * is read, then the envelope and its route. A page from another build is\n * refused by Foldkit itself. A page that cannot resume is refused and contained\n * by Foldkit's own refusal, and the reason is reported (`options.diagnostics`). A server page is never\n * rendered again on the client. A page with no server render at all, no\n * stamped root, is rendered on the client as usual.\n */\nconst hydrate = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n /**\n * Whether this page is taken over: asked before anything is adopted, so\n * a page showing another reader's data never becomes live facts. Omitted\n * adopts as before. Must not throw: a throwing predicate propagates out\n * of `hydrate` with no runtime booted and nothing contained.\n */\n readonly when?: ((page: Document) => boolean) | undefined\n /**\n * What a declined or stale page does: `render` runs the application\n * afresh where the rendered page is, replacing its markup in place (the\n * config's container with no served page). Omitted contains the page the\n * way a resume failure does.\n */\n readonly otherwise?: 'render' | undefined\n /**\n * With `otherwise: 'render'`, when the fresh application is ready to be\n * seen: until a Model it has drawn satisfies this, it draws out of view\n * and the served page stays, so a page is not swapped for its loading\n * state and back. Omitted, the fresh application replaces the page at\n * once. The served page stays no longer than `UNTIL_LIMIT_MS`.\n */\n readonly until?: ((model: Model) => boolean) | undefined\n /**\n * Whether the plan's data version is still current: asked once, with\n * `plan.version`, before anything is adopted. Omitted never asks. A plan\n * with no version still asks, with `undefined` (a check shaped like\n * `version === expected` then marks every such page stale). Must not\n * throw, as `when`.\n */\n readonly fresh?: ((version: unknown) => boolean) | undefined\n /**\n * Where what the page met goes: a page contained rather than resumed, a\n * static region the server's page lacked, a lazy bundle that did not\n * load. Each is reported before or apart from the runtime, so its\n * resources' reporter is not in effect. Omitted, Effect's log: the\n * browser's console.\n */\n readonly diagnostics?: ReportDiagnostic | undefined\n },\n): void => {\n const report = (diagnostic: SsrDiagnostic): void => {\n Effect.runFork(reportingTo(options.diagnostics)(Diagnostics.report(diagnostic)))\n }\n const planMeta = plan.meta\n if (planMeta !== undefined) {\n config = {\n ...config,\n subscriptions: { ...config.subscriptions, 'foldkit-ssr.meta': metaEntry(planMeta) },\n }\n }\n const root = document.querySelector<HTMLElement>(`[${FOLDKIT_APP_ATTRIBUTE}]`)\n // A page that is declined or stale never adopts. `render` draws afresh at\n // the root's place, replacing it; anything else contains the served page.\n // With no served page the application renders afresh regardless.\n const declined = options.when !== undefined && !options.when(document)\n const stale = options.fresh !== undefined && !options.fresh(plan.version)\n if (root === null) {\n run(makeApplication(config as never))\n return\n }\n const program = (start: { readonly model: Model; readonly commands?: ReadonlyArray<unknown> }) =>\n makeApplication({ ...startingFrom(config, start), container: root } as never)\n // Contain the served page the way Foldkit refuses one: adopt the baseline\n // with an empty build id, with nothing copied here.\n const contain = () => adopt(program({ model: plan.baseline }), { buildId: '' })\n if (declined || stale) {\n if (options.otherwise !== 'render') contain()\n else if (options.until === undefined)\n run(makeApplication({ ...config, container: root } as never))\n else renderBeside(config, root, options.until)\n return\n }\n // The type says a string, but `import.meta.env` is `any`: with the variable\n // unset the id arrives undefined, and Foldkit, given none, takes its own\n // compiled id, which matches the page, so the baseline was adopted in silence.\n if (typeof options.buildId !== 'string') {\n report(noBuildId)\n contain()\n return\n }\n const served = root.getAttribute(BUILD_ATTRIBUTE)\n if (served !== options.buildId) {\n report(otherBuild(Option.fromNullOr(served), options.buildId))\n adopt(program({ model: plan.baseline }), { buildId: options.buildId })\n return\n }\n const resumed = resume(plan, document, { route: routeOf(window.location.href) })\n if (Result.isFailure(resumed)) {\n report(pageContained(resumed.failure.reason, resumed.failure.message))\n contain()\n return\n }\n const model = resumed.success\n const commands = (plan.boot?.(model) as ReadonlyArray<unknown> | undefined) ?? []\n const resuming: RenderContext = {\n mode: 'resume',\n snapshots: snapshotsOf(root),\n reported: new Set(),\n report,\n }\n // The runtime starts from the resumed Model, so its first render is the\n // served markup and Foldkit adopts every node. The Messages the page\n // answered before the live page listened wait in `answered`, and the first\n // Message the runtime processes, whatever it is, runs them through `update`\n // ahead of itself: they reach the Model before anything the live page\n // answers, an event dispatched in the task that boots it included.\n const answered: Array<unknown> = []\n // Each answered Message was decoded through the plan's Message Schema.\n const apply: ResumableConfig<Model>['update'] = config.update\n const update = (current: Model, message: unknown) => {\n const handingOver = message === HANDOVER\n if (answered.length === 0) return handingOver ? { model: current } : apply(current, message)\n const returned: Array<unknown> = []\n for (const next of [...answered.splice(0), ...(handingOver ? [] : [message])]) {\n const step = apply(current, next) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n current = step.model\n returned.push(...(step.commands ?? []))\n }\n return { model: current, commands: returned }\n }\n const boot = (entries: Readonly<Record<string, unknown>> = {}) =>\n adopt(\n makeApplication({\n ...withContext(startingFrom({ ...config, update }, { model, commands }), resuming),\n container: root,\n subscriptions: { ...config.subscriptions, ...entries },\n } as never),\n { buildId: options.buildId },\n )\n const pending = (config.lazy ?? []).filter(bundle => !bundle.isLoaded())\n if (plan.start === 'now' && pending.length === 0) {\n boot()\n return\n }\n const decoded = bindingsAndEvents(plan, document, root, model)\n if (Result.isFailure(decoded)) {\n report(pageContained(decoded.failure.reason, decoded.failure.message))\n contain()\n return\n }\n deferBoot(root, decoded.success, plan.start, { boot, answered }, pending, report)\n}\n\n/** The longest a served page stays in view while a fresh application waits for `until`. */\nexport const UNTIL_LIMIT_MS = 3000\n\n/**\n * Runs the application afresh out of view, beside the served page, and puts\n * it in the page's place once a Model it drew satisfies `until`, or after\n * `UNTIL_LIMIT_MS`. It draws in a hidden element, not a detached one, so its\n * Mounts start in the document as they would in place.\n */\nconst renderBeside = <Model, Message>(\n config: ResumableConfig<Model, Message>,\n served: HTMLElement,\n until: (model: Model) => boolean,\n): void => {\n const holder = document.createElement('div')\n holder.hidden = true\n const container = document.createElement('div')\n // The runtime refuses a container without an id; the served page gives its own up.\n container.id = served.id === '' ? 'foldkit-ssr-app' : served.id\n served.removeAttribute('id')\n // Nor does it boot beside a page stamped as a server render, which this one,\n // never adopted, no longer is.\n served.removeAttribute(FOLDKIT_APP_ATTRIBUTE)\n holder.append(container)\n served.after(holder)\n let shown = false\n const show = () => {\n if (shown) return\n shown = true\n clearTimeout(limit)\n holder.replaceWith(...holder.childNodes)\n served.remove()\n }\n const limit = setTimeout(show, UNTIL_LIMIT_MS)\n const view: ResumableConfig<Model, Message>['view'] = (model, h) => {\n const drawn = config.view(model, h)\n // Shown once the drawing this view returns is patched in, which the\n // runtime does in the same task.\n if (!shown && until(model)) queueMicrotask(show)\n return drawn\n }\n run(makeApplication({ ...config, view, container } as never))\n}\n\n/**\n * The Message the handover entry sends so the runtime takes the answered\n * Messages when nothing else has asked it to. The wrapped `update` consumes\n * it; the application never sees it.\n */\nconst HANDOVER: unknown = Object.freeze({ _tag: 'foldkit-ssr/Handover' })\n\n/**\n * Lets the page answer from its bindings until something asks for the\n * runtime, then boots it and hands over to the live page.\n *\n * Every Message the page answers goes to `answered`, which the runtime takes\n * before its first Message. An event only the live page can answer is kept\n * and sent again to where it first went once the live page listens. The page\n * stops listening as soon as the runtime's first render has committed: when\n * `hydrate` returns, which Foldkit does today, or else when a handover\n * Subscription entry starts, after `Render.afterCommit`. When lazy bundles\n * must load first, the boot waits for them and the page keeps answering.\n */\nconst deferBoot = (\n root: HTMLElement,\n decoded: {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly events: ReadonlyArray<string> | undefined\n },\n start: Start,\n runtime: {\n readonly boot: (entries: Readonly<Record<string, unknown>>) => void\n readonly answered: Array<unknown>\n },\n pending: ReadonlyArray<Loadable>,\n report: (diagnostic: SsrDiagnostic) => void,\n): void => {\n // Events only the live page can answer, met before it listened.\n const unanswered: Array<{ readonly event: Event; readonly element: Element }> = []\n // `waiting` for an interaction or idle, `loading` bodies, `starting` the\n // runtime until its first render commits, then `live`.\n let phase: 'waiting' | 'loading' | 'starting' | 'live' = 'waiting'\n const stop = listen(root, {\n bindings: decoded.bindings,\n ...(decoded.events === undefined ? {} : { events: decoded.events }),\n onAnswer: ({ event, messages, unnamed }) => {\n // An answer the markers could not complete is left to the live page.\n if (unnamed !== undefined) {\n startNow()\n // Once the live page listens, this event reaches it in the rest of\n // its own dispatch; until then it is kept for the handover.\n if (phase !== 'live' && event.target instanceof Element) {\n unanswered.push({ event, element: event.target })\n }\n return\n }\n // Nothing answered it: it goes on to the page, a plain link to the\n // router, as it would have.\n if (messages.length === 0) {\n startNow()\n return\n }\n // Taken by the runtime before anything else. The live page must not\n // answer this one as well.\n runtime.answered.push(...messages)\n event.stopPropagation()\n startNow()\n },\n })\n const handOver = () => {\n if (phase === 'live') return\n phase = 'live'\n stop()\n for (const { event, element } of unanswered.splice(0)) {\n const Ctor = event.constructor as new (type: string, init: Event) => Event\n element.dispatchEvent(new Ctor(event.type, event))\n }\n }\n const commit = () => {\n phase = 'starting'\n runtime.boot({\n 'foldkit-ssr.handover': {\n dependenciesSchema: Schema.Null,\n modelToDependencies: () => null,\n // Foldkit strips the root's stamp just before its first patch, so a\n // stamped root still has a render to wait for.\n dependenciesToStream: () =>\n Stream.fromEffect(\n Effect.as(\n Effect.andThen(\n root.hasAttribute(FOLDKIT_APP_ATTRIBUTE) ? Render.afterCommit : Effect.void,\n Effect.sync(handOver),\n ),\n HANDOVER,\n ),\n ),\n },\n })\n if (!root.hasAttribute(FOLDKIT_APP_ATTRIBUTE)) handOver()\n }\n const startNow = () => {\n if (phase !== 'waiting') return\n phase = 'loading'\n if (pending.length === 0) {\n commit()\n return\n }\n void Promise.all(pending.map(bundle => bundle.load())).then(commit, (error: unknown) => {\n report(bundleUnloaded(error))\n commit()\n })\n }\n if (start === 'now') startNow()\n else if (start === 'idle') {\n if (typeof window.requestIdleCallback === 'function') window.requestIdleCallback(startNow)\n else setTimeout(startNow, 0)\n }\n}\n\n/** The resumable track: bindings the server's markup names, so a page can answer before it boots. */\nexport const Resume = { builder, view, bindings, listen }\n\n/** The browser's part of `SSR`: the same functions, without the server's. */\nexport const SSR = { plan, resume, hydrate, static: staticRegion, serving }\n\nexport {\n META_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n ResumeRefused,\n metaMarkup,\n type Loadable,\n type Meta,\n type PlanSurface,\n type ResumableConfig,\n type ResumePart,\n type ResumePlan,\n type Start,\n} from './shared.js'\nexport {\n BINDING_ATTRIBUTE,\n FALLBACK_FIELD,\n SLOT_ATTRIBUTE,\n type ResumableBuilder,\n} from './resumable.js'\nexport type { DecodedBinding } from './listen.js'\nexport type { UnnamedHandler } from './context.js'\n/** The diagnostics channel `hydrate` reports into, re-exported so a page needs no other import. */\nexport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nexport type {\n BundleUnloaded,\n HandlerUnnamed,\n PageContained,\n PageFailed,\n SsrDiagnostic,\n StaticRegionMissing,\n} from './diagnostics.js'\n"],"mappings":";;;;;;;;;;;;;;;;;AA2CA,MAAM,eAAe,SACnB,IAAI,IACF,MAAM,KAAK,KAAK,iBAAiB,IAAI,iBAAiB,EAAE,IAAG,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AAC,KAAK,SAAS,UAAmB;GACtF,OAAO,eAAe,KAAK,CAAC;GAC5B,OAAO;EACT,CAAC;CACH;CACA,IAAI,UAAU,OAAO,SAAS;MACzB,IAAI,UAAU,QAAQ;EACzB,IAAI,OAAO,OAAO,wBAAwB,YAAY,OAAO,oBAAoB,QAAQ;OACpF,WAAW,UAAU,CAAC;CAC7B;AACF;;AAGA,MAAa,SAAS;CAAE;CAAS;CAAM;CAAU;AAAO;;AAGxD,MAAa,MAAM;CAAE;CAAM;CAAQ,SAAA;CAAS,QAAQ;CAAc;AAAQ"}
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// src/context.ts
|
|
2
|
+
let context;
|
|
3
|
+
/** The context of the view call in progress, if any. */
|
|
4
|
+
const current = () => context;
|
|
5
|
+
const within = (next, run) => {
|
|
6
|
+
const previous = context;
|
|
7
|
+
context = next;
|
|
8
|
+
try {
|
|
9
|
+
return run();
|
|
10
|
+
} finally {
|
|
11
|
+
context = previous;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
/** The config whose view runs inside `next`. */
|
|
15
|
+
const withContext = (config, next) => ({
|
|
16
|
+
...config,
|
|
17
|
+
view: (model, h) => within(next, () => config.view(model, h))
|
|
18
|
+
});
|
|
19
|
+
export { current, withContext, within };
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.js","names":[],"sources":["../src/context.ts"],"sourcesContent":["/**\n * The render context: what the page's server-owned parts do, set around one\n * synchronous call of the view. `SSR.static` reads it to decide whether a\n * region renders, replays, or adopts the server's markup, and the resumable\n * builder reads it to decide whether to mark the bindings it builds. With no\n * context, as in a client-only render, both behave as ordinary view code.\n *\n * - `collect`: the server's render. Each region runs once and is kept, and\n * each binding is recorded in render order.\n * - `replay`: the server's second render, from the browser's Model. Each\n * region is the one already rendered, so it never reads the browser's Model;\n * bindings are recorded again, to be compared with the first render's.\n * - `resume`: the browser. Each region is the markup the server left in the\n * page, and its render never runs; no binding is marked.\n */\nimport type { Html } from 'foldkit/html'\nimport type { StaticRegionMissing } from './diagnostics.js'\n\nexport type Region = ReadonlyArray<Html | string>\n\n/** An element whose handler for `event` is a function, which the page cannot describe. */\nexport interface UnnamedHandler {\n readonly element: string\n readonly event: string\n}\n\n/**\n * An element's binding as the server's render records it, before encoding:\n * the Foldkit attribute and its DOM event, the element for diagnostics, and\n * the Message it causes. For a Message with a hole, `message` is the Message\n * with the hole filled by a placeholder, and `hole` names the fields the event\n * fills.\n */\nexport interface Binding {\n /** Foldkit's attribute, whose tag says what the handler does beside dispatching. */\n readonly attribute: string\n readonly event: string\n readonly element: string\n readonly message: unknown\n readonly hole?: ReadonlyArray<string> | undefined\n /** How many placement wrappers enclose the hole's fields: `message` is entered that many times. */\n readonly depth?: number | undefined\n readonly options?: unknown\n}\n\nexport type RenderContext =\n | {\n readonly mode: 'collect'\n readonly regions: Map<string, Region>\n readonly duplicates: Set<string>\n readonly bindings: Array<Binding>\n /** Encodes a form's Message for its no-script fallback; absent when the plan has none. */\n readonly fallback: ((message: unknown) => string | undefined) | undefined\n /** Lifts a Message of the view in progress to the application's, through each enclosing placement. */\n wrap: (message: unknown) => unknown\n /** How many placements enclose the view in progress. */\n depth: number\n /** The static region whose render is in progress, if any. */\n region: string | undefined\n /** Handlers met inside a static region, which the server alone renders. */\n readonly inStatic: Array<{\n readonly region: string\n readonly element: string\n readonly event: string\n }>\n /** Each element and event marked `*`: a handler the page cannot name. */\n readonly unnamed: Array<UnnamedHandler>\n }\n | {\n readonly mode: 'replay'\n readonly regions: ReadonlyMap<string, Region>\n readonly bindings: Array<Binding>\n readonly fallback: ((message: unknown) => string | undefined) | undefined\n wrap: (message: unknown) => unknown\n depth: number\n }\n | {\n readonly mode: 'resume'\n readonly snapshots: ReadonlyMap<string, string>\n /** The regions already reported missing, so each is reported once. */\n readonly reported: Set<string>\n readonly report: (diagnostic: StaticRegionMissing) => void\n }\n\nlet context: RenderContext | undefined\n\n/** The context of the view call in progress, if any. */\nexport const current = (): RenderContext | undefined => context\n\nexport const within = <A>(next: RenderContext, run: () => A): A => {\n const previous = context\n context = next\n try {\n return run()\n } finally {\n context = previous\n }\n}\n\n/** The config whose view runs inside `next`. */\nexport const withContext = <Config extends { readonly view: (model: any, h: any) => unknown }>(\n config: Config,\n next: RenderContext,\n): Config => ({\n ...config,\n view: (model: unknown, h: unknown) => within(next, () => config.view(model, h)),\n})\n"],"mappings":";AAoFA,IAAI;;AAGJ,MAAa,gBAA2C;AAExD,MAAa,UAAa,MAAqB,QAAoB;CACjE,MAAM,WAAW;CACjB,UAAU;CACV,IAAI;EACF,OAAO,IAAI;CACb,UAAU;EACR,UAAU;CACZ;AACF;;AAGA,MAAa,eACX,QACA,UACY;CACZ,GAAG;CACH,OAAO,OAAgB,MAAe,OAAO,YAAY,OAAO,KAAK,OAAO,CAAC,CAAC;AAChF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { $ as reportingTo, G as SsrDiagnostic, H as HandlerUnnamed, J as handlerUnnamed, K as StaticRegionMissing, Q as pageFailed, U as PageContained, V as BundleUnloaded, W as PageFailed, X as otherBuild, Y as noBuildId, Z as pageContained, et as staticRegionMissing, q as bundleUnloaded } from "./shared-v1u-OEQI.js";
|
|
2
|
+
export { BundleUnloaded, HandlerUnnamed, PageContained, PageFailed, SsrDiagnostic, StaticRegionMissing, bundleUnloaded, handlerUnnamed, noBuildId, otherBuild, pageContained, pageFailed, reportingTo, staticRegionMissing };
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { Cause, Effect, Option } from "effect";
|
|
2
|
+
import { Diagnostics } from "foldkit-surface";
|
|
3
|
+
// src/diagnostics.ts
|
|
4
|
+
/**
|
|
5
|
+
* What SSR meets and keeps going past: a page the browser contains rather
|
|
6
|
+
* than resumes, a static region or lazy bundle it draws without, a request
|
|
7
|
+
* answered 500, and a handler that keeps a page from answering before boot.
|
|
8
|
+
* Each is reported through `Diagnostics.report`, by default to the log.
|
|
9
|
+
*/
|
|
10
|
+
const source = "foldkit-ssr";
|
|
11
|
+
const pageContained = (reason, detail) => ({
|
|
12
|
+
_tag: "PageContained",
|
|
13
|
+
source,
|
|
14
|
+
level: "error",
|
|
15
|
+
message: `the page cannot resume, so it is contained: ${detail}`,
|
|
16
|
+
reason
|
|
17
|
+
});
|
|
18
|
+
const noBuildId = pageContained("NoBuildId", "SSR.hydrate was given no build id, so it cannot tell this page from another deployment's. Pass the id the server stamped: with @foldkit/vite-plugin, set FOLDKIT_BUILD_ID (or `foldkit({ buildId })`) so that `import.meta.env.FOLDKIT_BUILD_ID` is defined in the client too.");
|
|
19
|
+
/** The page's stamped build id, if it has one, is not the client's `client`. */
|
|
20
|
+
const otherBuild = (served, client) => pageContained("OtherBuild", `it was served by ${Option.match(served, {
|
|
21
|
+
onNone: () => "no known deployment",
|
|
22
|
+
onSome: (id) => `deployment "${id}"`
|
|
23
|
+
})}, but this client belongs to deployment "${client}". If both came from one build, they were given different ids: with @foldkit/vite-plugin, set FOLDKIT_BUILD_ID in the build's environment, or once in vite.config.ts before \`foldkit()\` reads it (\`process.env.FOLDKIT_BUILD_ID ??= randomUUID()\`). Otherwise serve the page from the running deployment.`);
|
|
24
|
+
const staticRegionMissing = (region) => ({
|
|
25
|
+
_tag: "StaticRegionMissing",
|
|
26
|
+
source,
|
|
27
|
+
level: "error",
|
|
28
|
+
message: `the static region "${region}" is not in the server's page, so it is rendered in the browser`,
|
|
29
|
+
region
|
|
30
|
+
});
|
|
31
|
+
const bundleUnloaded = (error) => ({
|
|
32
|
+
_tag: "BundleUnloaded",
|
|
33
|
+
source,
|
|
34
|
+
level: "error",
|
|
35
|
+
message: `a bundle's bodies did not load, and the page boots without them: ${String(error)}`,
|
|
36
|
+
error
|
|
37
|
+
});
|
|
38
|
+
const pageFailed = (url, cause) => ({
|
|
39
|
+
_tag: "PageFailed",
|
|
40
|
+
source,
|
|
41
|
+
level: "error",
|
|
42
|
+
message: `${url} was answered 500: ${Cause.pretty(cause)}`,
|
|
43
|
+
url,
|
|
44
|
+
cause
|
|
45
|
+
});
|
|
46
|
+
const handlerUnnamed = (plan, element, event) => ({
|
|
47
|
+
_tag: "HandlerUnnamed",
|
|
48
|
+
source,
|
|
49
|
+
level: "warning",
|
|
50
|
+
message: `plan "${plan}": ${element} handles ${event} with a function, which the page cannot name, so that event waits for the live runtime. Give the handler a Message, or, for OnInput, OnChange, OnKeyDown or OnKeyUp, the Message's constructor with the field the event fills left out.`,
|
|
51
|
+
plan,
|
|
52
|
+
element,
|
|
53
|
+
event
|
|
54
|
+
});
|
|
55
|
+
/** `effect` reporting to `report` when one is given, else to the reporter in its context. */
|
|
56
|
+
const reportingTo = (report) => (effect) => report === void 0 ? effect : Effect.provideService(effect, Diagnostics.Reporter, report);
|
|
57
|
+
export { bundleUnloaded, handlerUnnamed, noBuildId, otherBuild, pageContained, pageFailed, reportingTo, staticRegionMissing };
|
|
58
|
+
|
|
59
|
+
//# sourceMappingURL=diagnostics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"diagnostics.js","names":[],"sources":["../src/diagnostics.ts"],"sourcesContent":["/**\n * What SSR meets and keeps going past: a page the browser contains rather\n * than resumes, a static region or lazy bundle it draws without, a request\n * answered 500, and a handler that keeps a page from answering before boot.\n * Each is reported through `Diagnostics.report`, by default to the log.\n */\nimport { Cause, Effect, Option } from 'effect'\nimport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nimport type { ResumeRefused } from './shared.js'\n\nconst source = 'foldkit-ssr'\n\n/** A served page the browser contained instead of resuming: it stays in view, inert, and no runtime starts. */\nexport interface PageContained extends Diagnostic {\n readonly _tag: 'PageContained'\n /**\n * `NoBuildId` when `SSR.hydrate` was given none, `OtherBuild` when the page\n * names another deployment; otherwise why the envelope was refused.\n */\n readonly reason: 'NoBuildId' | 'OtherBuild' | ResumeRefused['reason']\n}\n\n/** A static region the browser asked for that the server's page did not hold, rendered in the browser. */\nexport interface StaticRegionMissing extends Diagnostic {\n readonly _tag: 'StaticRegionMissing'\n readonly region: string\n}\n\n/** A lazy bundle whose bodies did not load; the runtime boots without them. */\nexport interface BundleUnloaded extends Diagnostic {\n readonly _tag: 'BundleUnloaded'\n readonly error: unknown\n}\n\n/** A request answered 500: its `headers` threw, or its page could not be rendered. */\nexport interface PageFailed extends Diagnostic {\n readonly _tag: 'PageFailed'\n readonly url: string\n readonly cause: Cause.Cause<unknown>\n}\n\n/** A handler the page cannot name, so its event waits for the live runtime. Reported once per process. */\nexport interface HandlerUnnamed extends Diagnostic {\n readonly _tag: 'HandlerUnnamed'\n readonly plan: string\n readonly element: string\n readonly event: string\n}\n\n/** Every diagnostic SSR reports. */\nexport type SsrDiagnostic =\n | PageContained\n | StaticRegionMissing\n | BundleUnloaded\n | PageFailed\n | HandlerUnnamed\n\nexport const pageContained = (reason: PageContained['reason'], detail: string): PageContained => ({\n _tag: 'PageContained',\n source,\n level: 'error',\n message: `the page cannot resume, so it is contained: ${detail}`,\n reason,\n})\n\nexport const noBuildId: PageContained = pageContained(\n 'NoBuildId',\n \"SSR.hydrate was given no build id, so it cannot tell this page from another deployment's. Pass the id the server stamped: with @foldkit/vite-plugin, set FOLDKIT_BUILD_ID (or `foldkit({ buildId })`) so that `import.meta.env.FOLDKIT_BUILD_ID` is defined in the client too.\",\n)\n\n/** The page's stamped build id, if it has one, is not the client's `client`. */\nexport const otherBuild = (served: Option.Option<string>, client: string): PageContained =>\n pageContained(\n 'OtherBuild',\n `it was served by ${Option.match(served, {\n onNone: () => 'no known deployment',\n onSome: id => `deployment \"${id}\"`,\n })}, but this client belongs to deployment \"${client}\". If both came from one build, they were given different ids: with @foldkit/vite-plugin, set FOLDKIT_BUILD_ID in the build's environment, or once in vite.config.ts before \\`foldkit()\\` reads it (\\`process.env.FOLDKIT_BUILD_ID ??= randomUUID()\\`). Otherwise serve the page from the running deployment.`,\n )\n\nexport const staticRegionMissing = (region: string): StaticRegionMissing => ({\n _tag: 'StaticRegionMissing',\n source,\n level: 'error',\n message: `the static region \"${region}\" is not in the server's page, so it is rendered in the browser`,\n region,\n})\n\nexport const bundleUnloaded = (error: unknown): BundleUnloaded => ({\n _tag: 'BundleUnloaded',\n source,\n level: 'error',\n message: `a bundle's bodies did not load, and the page boots without them: ${String(error)}`,\n error,\n})\n\nexport const pageFailed = (url: string, cause: Cause.Cause<unknown>): PageFailed => ({\n _tag: 'PageFailed',\n source,\n level: 'error',\n message: `${url} was answered 500: ${Cause.pretty(cause)}`,\n url,\n cause,\n})\n\nexport const handlerUnnamed = (plan: string, element: string, event: string): HandlerUnnamed => ({\n _tag: 'HandlerUnnamed',\n source,\n level: 'warning',\n message: `plan \"${plan}\": ${element} handles ${event} with a function, which the page cannot name, so that event waits for the live runtime. Give the handler a Message, or, for OnInput, OnChange, OnKeyDown or OnKeyUp, the Message's constructor with the field the event fills left out.`,\n plan,\n element,\n event,\n})\n\n/** `effect` reporting to `report` when one is given, else to the reporter in its context. */\nexport const reportingTo =\n (report: ReportDiagnostic | undefined) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n report === undefined ? effect : Effect.provideService(effect, Diagnostics.Reporter, report)\n"],"mappings":";;;;;;;;;AAUA,MAAM,SAAS;AA+Cf,MAAa,iBAAiB,QAAiC,YAAmC;CAChG,MAAM;CACN;CACA,OAAO;CACP,SAAS,+CAA+C;CACxD;AACF;AAEA,MAAa,YAA2B,cACtC,aACA,gRACF;;AAGA,MAAa,cAAc,QAA+B,WACxD,cACE,cACA,oBAAoB,OAAO,MAAM,QAAQ;CACvC,cAAc;CACd,SAAQ,OAAM,eAAe,GAAG;AAClC,CAAC,EAAE,2CAA2C,OAAO,8SACvD;AAEF,MAAa,uBAAuB,YAAyC;CAC3E,MAAM;CACN;CACA,OAAO;CACP,SAAS,sBAAsB,OAAO;CACtC;AACF;AAEA,MAAa,kBAAkB,WAAoC;CACjE,MAAM;CACN;CACA,OAAO;CACP,SAAS,oEAAoE,OAAO,KAAK;CACzF;AACF;AAEA,MAAa,cAAc,KAAa,WAA6C;CACnF,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,IAAI,qBAAqB,MAAM,OAAO,KAAK;CACvD;CACA;AACF;AAEA,MAAa,kBAAkB,MAAc,SAAiB,WAAmC;CAC/F,MAAM;CACN;CACA,OAAO;CACP,SAAS,SAAS,KAAK,KAAK,QAAQ,WAAW,MAAM;CACrD;CACA;CACA;AACF;;AAGA,MAAa,eACV,YACS,WACR,WAAW,KAAA,IAAY,SAAS,OAAO,eAAe,QAAQ,YAAY,UAAU,MAAM"}
|
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as DecodedBinding, r as EncodedBinding } from "./listen-zNd0IIAT.js";
|
|
2
|
+
import { a as FALLBACK_FIELD, l as ResumableBuilder, n as BINDING_ATTRIBUTE, u as SLOT_ATTRIBUTE } from "./resumable-BWItJsxF.js";
|
|
3
|
+
import { A as serving, D as resume, G as SsrDiagnostic, H as HandlerUnnamed, K as StaticRegionMissing, L as UnnamedHandler, M as staticRegion, U as PageContained, V as BundleUnloaded, W as PageFailed, c as ResumableConfig, d as ResumeRefused, f as RouteMatch, i as Meta, k as serializeJsonScript, l as ResumePart, m as Start, n as Loadable, o as PlanSurface, p as STATIC_ATTRIBUTE, r as META_ATTRIBUTE, s as RESUME_ATTRIBUTE, t as FOLDKIT_APP_ATTRIBUTE, u as ResumePlan, w as plan, x as metaMarkup } from "./shared-v1u-OEQI.js";
|
|
4
|
+
import { i as Resume, n as Diagnostics, o as UNTIL_LIMIT_MS, r as ReportDiagnostic, t as Diagnostic } from "./client-F16QT0sc.js";
|
|
5
|
+
import { n as requestContext, t as RequestContext } from "./requestContext-D9nsbGSJ.js";
|
|
2
6
|
import { Cause, Effect, Layer, Schema } from "effect";
|
|
7
|
+
import { Diagnostic as Diagnostic$1, MetadataSummary } from "foldkit-surface";
|
|
3
8
|
import { EntryModule, RenderError, RenderedApplication } from "foldkit/experimental/server";
|
|
4
|
-
import { MetadataSummary } from "foldkit-surface";
|
|
5
|
-
//#region src/index.d.ts
|
|
6
9
|
interface EnvelopeOptions {
|
|
7
10
|
readonly route?: string | undefined;
|
|
8
11
|
readonly match?: RouteMatch | undefined;
|
|
@@ -203,7 +206,7 @@ declare const generate: <Model, Fields extends Schema.Struct.Fields, const Paths
|
|
|
203
206
|
* the post is unusable. `OPTIONS` is answered `204`, and any other method
|
|
204
207
|
* `405`, each with the methods the entry answers in `allow` (`handleRequest`
|
|
205
208
|
* passes every method through). A render that fails, or a plan the render
|
|
206
|
-
* refuses, is answered `500` with the reason
|
|
209
|
+
* refuses, is answered `500` with the reason reported (`diagnostics`), never with a page the
|
|
207
210
|
* browser cannot resume. `headers(request)` rides on the `Rendered` result, so
|
|
208
211
|
* Foldkit's `toResponse` sets it over its own on the page: a cache policy, or
|
|
209
212
|
* a CORS answer to a preflight.
|
|
@@ -249,6 +252,13 @@ declare const entry: <Model, Fields extends Schema.Struct.Fields, Message = any>
|
|
|
249
252
|
* per-page styles go; anything a head owns stays with `SSR.generate`.
|
|
250
253
|
*/
|
|
251
254
|
readonly styles?: Head | undefined;
|
|
255
|
+
/**
|
|
256
|
+
* Where this request's diagnostics go, with the request: a request
|
|
257
|
+
* answered 500 (`PageFailed`), a handler the page cannot name, and what
|
|
258
|
+
* a posted form's Commands report. The reporter in the Effect context
|
|
259
|
+
* (`Diagnostics.Reporter`) when not given, by default the log.
|
|
260
|
+
*/
|
|
261
|
+
readonly diagnostics?: ((diagnostic: Diagnostic$1, request: Request) => Effect.Effect<void>) | undefined;
|
|
252
262
|
}) => EntryModule;
|
|
253
263
|
declare const FallbackRefused_base: Schema.Class<FallbackRefused, Schema.TaggedStruct<"FallbackRefused", {
|
|
254
264
|
readonly reason: Schema.Literals<readonly ["Missing", "Unreadable", "Invalid", "Unlisted", "NoFallback"]>;
|
|
@@ -288,6 +298,7 @@ export declare const SSR: {
|
|
|
288
298
|
readonly otherwise?: 'render' | undefined;
|
|
289
299
|
readonly until?: ((model: Model) => boolean) | undefined;
|
|
290
300
|
readonly fresh?: ((version: unknown) => boolean) | undefined;
|
|
301
|
+
readonly diagnostics?: import("foldkit-surface").ReportDiagnostic | undefined;
|
|
291
302
|
}) => void;
|
|
292
303
|
inspect: typeof inspect;
|
|
293
304
|
static: typeof staticRegion;
|
|
@@ -298,7 +309,7 @@ export declare const SSR: {
|
|
|
298
309
|
serializeJsonScript: typeof serializeJsonScript;
|
|
299
310
|
sitemap: typeof sitemap;
|
|
300
311
|
robots: typeof robots;
|
|
312
|
+
requestContext: typeof requestContext;
|
|
301
313
|
};
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
//# sourceMappingURL=index.d.mts.map
|
|
314
|
+
export { BINDING_ATTRIBUTE, type BundleUnloaded, type DecodedBinding, type Diagnostic, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, type HandlerUnnamed, type Loadable, META_ATTRIBUTE, type Meta, type PageContained, type PageFailed, type PlanSurface, RESUME_ATTRIBUTE, type ReportDiagnostic, type RequestContext, type ResumableBuilder, type ResumableConfig, Resume, type ResumePart, type ResumePlan, ResumeRefused, SLOT_ATTRIBUTE, STATIC_ATTRIBUTE, type SsrDiagnostic, type Start, type StaticRegionMissing, UNTIL_LIMIT_MS, type UnnamedHandler, metaMarkup };
|
|
315
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["Diagnostic"],"sources":["../src/index.ts"],"mappings":";;;;;;;;UA8FU;WACC;WACA,QAAQ;WACR,WAAW,cAAc;;WAEzB,SAAS;;;;;;;;;cAUd,WAAY,OAAO,eAAe,OAAO,OAAO,QAAM,QAClD,WAAW,OAAO,SAAO,OAC1B,OAAK,UACH;;YAgHC;;iBAGK;WACN;;WAEA;;WAEA;;;;;WAKA;aAEM;aACA;eAAwB;eAAuB,OAAO;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