brumate 0.1.1 → 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/dist/{boot-DN1ZU8Hg.d.ts → boot-D-IdPy7B.d.ts} +24 -2
- package/dist/cli.js +2 -2
- package/dist/client-C0UCNL3J.js +1643 -0
- package/dist/client-C0UCNL3J.js.map +1 -0
- package/dist/{client-DwJInP_a.d.ts → client-MD0ZmcFR.d.ts} +101 -26
- package/dist/{client-routes-DakuM32C.js → client-routes-JTbGtukf.js} +28 -15
- package/dist/client-routes-JTbGtukf.js.map +1 -0
- package/dist/context-CTiSzQRc.js +27 -0
- package/dist/context-CTiSzQRc.js.map +1 -0
- package/dist/context-btHuB01Z.d.ts +42 -0
- package/dist/defer-D0bo1Gqx.js +52 -0
- package/dist/defer-D0bo1Gqx.js.map +1 -0
- package/dist/{devtools-BKjnHrnv.js → devtools-C50VH8gZ.js} +2 -2
- package/dist/devtools-C50VH8gZ.js.map +1 -0
- package/dist/{devtools-panel-AWOn0VK2.js → devtools-panel-AYjfwPhj.js} +4 -3
- package/dist/devtools-panel-AYjfwPhj.js.map +1 -0
- package/dist/events-BKWRqtMg.js +52 -0
- package/dist/events-BKWRqtMg.js.map +1 -0
- package/dist/{files-DdT84mPy.js → files-Bnn1JqHx.js} +18 -3
- package/dist/files-Bnn1JqHx.js.map +1 -0
- package/dist/{html-DEeoepg3.js → html-bHZbkK-h.js} +26 -8
- package/dist/html-bHZbkK-h.js.map +1 -0
- package/dist/{html-Du8jY2Cc.d.ts → html-y1q7-t7D.d.ts} +12 -5
- package/dist/index.d.ts +77 -29
- package/dist/index.js +12 -4
- package/dist/index.js.map +1 -1
- package/dist/{inspect-BPchdWbU.js → inspect-BJtACnQp.js} +784 -82
- package/dist/inspect-BJtACnQp.js.map +1 -0
- package/dist/{loader-Dc9OwY5I.js → loader-B18i3_-T.js} +46 -11
- package/dist/loader-B18i3_-T.js.map +1 -0
- package/dist/{navigate-CzLjnoPH.js → navigate-BwuZveDF.js} +71 -12
- package/dist/navigate-BwuZveDF.js.map +1 -0
- package/dist/{produce-BRGHP7e0.js → produce-CWfJ4byV.js} +43 -2
- package/dist/produce-CWfJ4byV.js.map +1 -0
- package/dist/{produce-CtZ32UGG.d.ts → produce-D4K7qpaL.d.ts} +23 -11
- package/dist/routes-BZNt7DSZ.d.ts +38 -0
- package/dist/{rpc-9fSqL_YK.js → rpc-B-Zkn6Ch.js} +24 -18
- package/dist/rpc-B-Zkn6Ch.js.map +1 -0
- package/dist/runtime/batch.d.ts +23 -0
- package/dist/runtime/batch.js +69 -0
- package/dist/runtime/batch.js.map +1 -0
- package/dist/runtime/client.d.ts +5 -5
- package/dist/runtime/client.js +5 -1345
- package/dist/runtime/context.d.ts +2 -2
- package/dist/runtime/context.js +1 -1
- package/dist/runtime/devtools.d.ts +5 -4
- package/dist/runtime/devtools.js +1 -1
- package/dist/runtime/env.d.ts +44 -0
- package/dist/runtime/env.js +61 -0
- package/dist/runtime/env.js.map +1 -0
- package/dist/runtime/events.d.ts +27 -0
- package/dist/runtime/events.js +1 -0
- package/dist/runtime/hot.d.ts +1 -1
- package/dist/runtime/html.d.ts +2 -2
- package/dist/runtime/html.js +1 -1
- package/dist/runtime/loader.d.ts +2 -2
- package/dist/runtime/loader.js +2 -2
- package/dist/runtime/routes.d.ts +2 -21
- package/dist/runtime/routes.js +31 -1
- package/dist/runtime/routes.js.map +1 -1
- package/dist/runtime/server.d.ts +6 -5
- package/dist/runtime/server.js +5 -6
- package/dist/runtime/signals.d.ts +22 -1
- package/dist/runtime/signals.js +29 -1
- package/dist/runtime/signals.js.map +1 -1
- package/dist/runtime/static-loader.d.ts +2 -2
- package/dist/runtime/static-loader.js +1 -1
- package/dist/runtime/testing.d.ts +46 -5
- package/dist/runtime/testing.js +240 -33
- package/dist/runtime/testing.js.map +1 -1
- package/dist/secrets-BxagsJxJ.js +23 -0
- package/dist/secrets-BxagsJxJ.js.map +1 -0
- package/dist/{server-BxqjLUnV.d.ts → server-BA9SJ2Vm.d.ts} +544 -106
- package/dist/server-BqfM95r1.js +2762 -0
- package/dist/server-BqfM95r1.js.map +1 -0
- package/dist/skew-FRmAy9iy.js +49 -0
- package/dist/skew-FRmAy9iy.js.map +1 -0
- package/dist/standard-schema-BNY82yX3.d.ts +63 -0
- package/dist/{static-loader-BcFh4ebX.d.ts → static-loader-BzE9SRaj.d.ts} +2 -2
- package/dist/{static-loader-ClNkHZGn.js → static-loader-DOygOFj5.js} +52 -21
- package/dist/static-loader-DOygOFj5.js.map +1 -0
- package/dist/{stream-bgNCMcaA.js → stream-JaMHMdBD.js} +126 -61
- package/dist/stream-JaMHMdBD.js.map +1 -0
- package/dist/vite.d.ts +42 -1
- package/dist/vite.js +435 -55
- package/dist/vite.js.map +1 -1
- package/package.json +15 -2
- package/types.d.ts +9 -1
- package/dist/client-routes-DakuM32C.js.map +0 -1
- package/dist/context-BG8KCF3v.js +0 -15
- package/dist/context-BG8KCF3v.js.map +0 -1
- package/dist/context-aeo9esY9.d.ts +0 -16
- package/dist/devtools-BKjnHrnv.js.map +0 -1
- package/dist/devtools-panel-AWOn0VK2.js.map +0 -1
- package/dist/files-DdT84mPy.js.map +0 -1
- package/dist/html-DEeoepg3.js.map +0 -1
- package/dist/inspect-BPchdWbU.js.map +0 -1
- package/dist/loader-Dc9OwY5I.js.map +0 -1
- package/dist/navigate-CzLjnoPH.js.map +0 -1
- package/dist/produce-BRGHP7e0.js.map +0 -1
- package/dist/rpc-9fSqL_YK.js.map +0 -1
- package/dist/runtime/client.js.map +0 -1
- package/dist/server-DZsgnPKS.js +0 -1615
- package/dist/server-DZsgnPKS.js.map +0 -1
- package/dist/shared-CWYOd0H3.js +0 -40
- package/dist/shared-CWYOd0H3.js.map +0 -1
- package/dist/static-loader-ClNkHZGn.js.map +0 -1
- package/dist/stream-bgNCMcaA.js.map +0 -1
package/dist/server-DZsgnPKS.js
DELETED
|
@@ -1,1615 +0,0 @@
|
|
|
1
|
-
import { c as escape, d as isRaw, h as styleElement, l as escapeAttribute, m as spread, n as actionAttributes, p as rawHTML, t as VOID_ELEMENTS, u as insertValue } from "./html-DEeoepg3.js";
|
|
2
|
-
import { a as plugins, c as replaceDeep, i as disabledFeatures, o as Upload, r as toChunkStream, s as functionReferences, t as STREAM_TYPE } from "./stream-bgNCMcaA.js";
|
|
3
|
-
import { n as FunctionReference, r as isAsyncIterable, t as ElementReference } from "./shared-CWYOd0H3.js";
|
|
4
|
-
import { n as deleteCookie, o as setCookie, r as getCookies } from "./cookies-Av5WFmcf.js";
|
|
5
|
-
import { crossSerializeStream, fromJSON, toJSON } from "seroval";
|
|
6
|
-
//#region src/runtime/request.ts
|
|
7
|
-
/**
|
|
8
|
-
* A request that the server handles: a server function call, a form post,
|
|
9
|
-
* a page render, or a call of middleware or an endpoint. Its methods read
|
|
10
|
-
* the request and change the response. Get it with `getEvent()`.
|
|
11
|
-
*/
|
|
12
|
-
var RequestEvent = class {
|
|
13
|
-
request;
|
|
14
|
-
/** Headers to add to the response, such as `cache-control`. */
|
|
15
|
-
headers = new Headers();
|
|
16
|
-
/** The status that `setStatus` set. */
|
|
17
|
-
status;
|
|
18
|
-
/** Server functions that `refresh` named, whose memos the client loads again. */
|
|
19
|
-
refreshed;
|
|
20
|
-
/** Cookies that this request set, or deleted with undefined, so later reads see them. */
|
|
21
|
-
cookies;
|
|
22
|
-
constructor(request) {
|
|
23
|
-
this.request = request;
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* Sets the status of the page response, such as 404 for a page that shows
|
|
27
|
-
* that nothing was found. It works while the first render of a page runs.
|
|
28
|
-
* Markup that streams later, such as a `#loading` body, cannot change it,
|
|
29
|
-
* because the response has started by then.
|
|
30
|
-
*/
|
|
31
|
-
setStatus(status) {
|
|
32
|
-
this.status = status;
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Asks the client to load again the memos that call a server function, such
|
|
36
|
-
* as a list after a server function adds to it. The compiler gives those
|
|
37
|
-
* memos client code, so they can load.
|
|
38
|
-
*/
|
|
39
|
-
refresh(fn) {
|
|
40
|
-
this.refreshed ??= /* @__PURE__ */ new Set();
|
|
41
|
-
this.refreshed.add(unwrap(fn));
|
|
42
|
-
}
|
|
43
|
-
/** The cookies of the request, with the ones that this request set or deleted. */
|
|
44
|
-
getCookies() {
|
|
45
|
-
return getCookies(this);
|
|
46
|
-
}
|
|
47
|
-
/** A cookie of the request, or the value that this request set. */
|
|
48
|
-
getCookie(name) {
|
|
49
|
-
return getCookies(this)[name];
|
|
50
|
-
}
|
|
51
|
-
/**
|
|
52
|
-
* Sets a cookie on the response. It is `HttpOnly`, `SameSite=Lax` and on
|
|
53
|
-
* the path `/` unless the options say otherwise, and `Secure` on HTTPS.
|
|
54
|
-
* Markup that streams later, such as a `#loading` body, cannot set cookies,
|
|
55
|
-
* because the response has started.
|
|
56
|
-
*/
|
|
57
|
-
setCookie(name, value, options = {}) {
|
|
58
|
-
setCookie(this, name, value, options);
|
|
59
|
-
}
|
|
60
|
-
/** Deletes a cookie. Pass the `path` and `domain` that it was set with, if they were not the defaults. */
|
|
61
|
-
deleteCookie(name, options = {}) {
|
|
62
|
-
deleteCookie(this, name, options);
|
|
63
|
-
}
|
|
64
|
-
};
|
|
65
|
-
/**
|
|
66
|
-
* The event of the code that runs now. The runtime sets it while it calls a
|
|
67
|
-
* server function, middleware, an endpoint or a memo, and clears it as soon
|
|
68
|
-
* as the call returns, which is at its first `await`. One request at a time
|
|
69
|
-
* runs until an `await`, so it is never the event of another request.
|
|
70
|
-
*/
|
|
71
|
-
let current;
|
|
72
|
-
/** The results of server function calls of the render that runs now, by function and arguments. */
|
|
73
|
-
let currentCalls;
|
|
74
|
-
/**
|
|
75
|
-
* Runs a callback with an event, so `getEvent()` in its code before its first
|
|
76
|
-
* `await` returns it. Returns what the callback returns, such as its promise.
|
|
77
|
-
* `calls`, while a page renders, lets calls with the same arguments share a result.
|
|
78
|
-
*/
|
|
79
|
-
function withEvent(event, callback, calls) {
|
|
80
|
-
const outer = current;
|
|
81
|
-
const outerCalls = currentCalls;
|
|
82
|
-
current = event;
|
|
83
|
-
currentCalls = calls;
|
|
84
|
-
try {
|
|
85
|
-
return callback();
|
|
86
|
-
} finally {
|
|
87
|
-
current = outer;
|
|
88
|
-
currentCalls = outerCalls;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
/**
|
|
92
|
-
* Returns the event of the request that the server handles: in a server
|
|
93
|
-
* function, middleware or an endpoint, or while a component renders.
|
|
94
|
-
*
|
|
95
|
-
* Call it before the first `await` of the function, and keep it in a
|
|
96
|
-
* variable. After an `await`, other requests may have run, so it throws.
|
|
97
|
-
*
|
|
98
|
-
* ```ts
|
|
99
|
-
* async function save(todo: Todo) {
|
|
100
|
-
* 'use server';
|
|
101
|
-
* const event = getEvent();
|
|
102
|
-
* await db.save(todo);
|
|
103
|
-
* event.setCookie('saved', todo.id);
|
|
104
|
-
* }
|
|
105
|
-
* ```
|
|
106
|
-
*/
|
|
107
|
-
function getEvent() {
|
|
108
|
-
if (!current) throw new Error("getEvent() works in server functions, middleware and endpoints before their first await, and while a component renders. Call it at the start of the function, keep the event in a variable, and pass it to helpers");
|
|
109
|
-
return current;
|
|
110
|
-
}
|
|
111
|
-
/**
|
|
112
|
-
* Wraps a server function, so its calls while a page renders share a result
|
|
113
|
-
* when their arguments are the same. Calls from the browser, which are
|
|
114
|
-
* requests of their own, always run, so a function that changes something
|
|
115
|
-
* runs each time.
|
|
116
|
-
*/
|
|
117
|
-
function dedupe(fn, id) {
|
|
118
|
-
const wrapper = ((...args) => {
|
|
119
|
-
const cache = currentCalls;
|
|
120
|
-
if (!cache) return fn(...args);
|
|
121
|
-
let key;
|
|
122
|
-
try {
|
|
123
|
-
key = `${id} ${JSON.stringify(toJSON(args, {
|
|
124
|
-
plugins,
|
|
125
|
-
disabledFeatures
|
|
126
|
-
}))}`;
|
|
127
|
-
} catch {
|
|
128
|
-
return fn(...args);
|
|
129
|
-
}
|
|
130
|
-
if (!cache.has(key)) cache.set(key, fn(...args));
|
|
131
|
-
return cache.get(key);
|
|
132
|
-
});
|
|
133
|
-
Object.defineProperty(wrapper, ORIGINAL, { value: fn });
|
|
134
|
-
return wrapper;
|
|
135
|
-
}
|
|
136
|
-
/**
|
|
137
|
-
* The function that `dedupe` wrapped, on its wrapper. A symbol of the
|
|
138
|
-
* registry, so two copies of the runtime agree on it.
|
|
139
|
-
*/
|
|
140
|
-
const ORIGINAL = Symbol.for("brumate.original");
|
|
141
|
-
/**
|
|
142
|
-
* The server function itself, for a wrapper that `dedupe` made. `refresh`
|
|
143
|
-
* and `$action` compare server functions, and the registry holds them unwrapped.
|
|
144
|
-
*/
|
|
145
|
-
function unwrap(fn) {
|
|
146
|
-
return fn?.[ORIGINAL] ?? fn;
|
|
147
|
-
}
|
|
148
|
-
/**
|
|
149
|
-
* An error whose message reaches the client. A server function call that
|
|
150
|
-
* throws it rejects with the message, and the response has its status.
|
|
151
|
-
* Other errors reach the client as a generic message, so server details stay
|
|
152
|
-
* on the server.
|
|
153
|
-
*/
|
|
154
|
-
var ServerError = class extends Error {
|
|
155
|
-
status;
|
|
156
|
-
constructor(message, options = {}) {
|
|
157
|
-
super(message);
|
|
158
|
-
this.name = "ServerError";
|
|
159
|
-
this.status = options.status ?? 400;
|
|
160
|
-
}
|
|
161
|
-
};
|
|
162
|
-
/** Thrown by `redirect`. */
|
|
163
|
-
var Redirect = class extends Error {
|
|
164
|
-
location;
|
|
165
|
-
status;
|
|
166
|
-
constructor(location, status) {
|
|
167
|
-
super(`Redirect to ${location}`);
|
|
168
|
-
this.name = "Redirect";
|
|
169
|
-
this.location = location;
|
|
170
|
-
this.status = status;
|
|
171
|
-
}
|
|
172
|
-
};
|
|
173
|
-
/**
|
|
174
|
-
* Stops a server function and sends the browser to another page. While a
|
|
175
|
-
* page renders, the error reaches the caller of `render`, which can
|
|
176
|
-
* answer with a redirect.
|
|
177
|
-
*/
|
|
178
|
-
function redirect(location, status = 303) {
|
|
179
|
-
throw new Redirect(location, status);
|
|
180
|
-
}
|
|
181
|
-
function isRedirect(error) {
|
|
182
|
-
return error instanceof Redirect;
|
|
183
|
-
}
|
|
184
|
-
//#endregion
|
|
185
|
-
//#region src/runtime/router.ts
|
|
186
|
-
function key(path, file, params) {
|
|
187
|
-
return `${path}/${file} ${JSON.stringify(params)}`;
|
|
188
|
-
}
|
|
189
|
-
/** Puts a view in the children slot of a layout, with its other slots. */
|
|
190
|
-
function wrap(view, wrapper) {
|
|
191
|
-
return wrapper ? {
|
|
192
|
-
load: wrapper.layout,
|
|
193
|
-
key: wrapper.key,
|
|
194
|
-
slots: {
|
|
195
|
-
...wrapper.slots,
|
|
196
|
-
children: view
|
|
197
|
-
}
|
|
198
|
-
} : view;
|
|
199
|
-
}
|
|
200
|
-
/** The layout of a folder, or undefined when it has none. */
|
|
201
|
-
function wrapperOf(node, segments, index, params, path) {
|
|
202
|
-
return node.layout ? {
|
|
203
|
-
layout: node.layout,
|
|
204
|
-
key: key(path, "_layout", params),
|
|
205
|
-
slots: namedSlots(node, segments, index, params, path)
|
|
206
|
-
} : void 0;
|
|
207
|
-
}
|
|
208
|
-
/** The `_error.brm` of a folder, inside its layout. */
|
|
209
|
-
function errorIn(error, wrapper, params, path) {
|
|
210
|
-
return wrap({
|
|
211
|
-
load: error,
|
|
212
|
-
key: key(path, ERROR_VIEW, params),
|
|
213
|
-
slots: {}
|
|
214
|
-
}, wrapper);
|
|
215
|
-
}
|
|
216
|
-
/** The slots of a layout other than `children`, each matched against the same path. */
|
|
217
|
-
function namedSlots(node, segments, index, params, path) {
|
|
218
|
-
const slots = {};
|
|
219
|
-
for (const [name, slot] of Object.entries(node.slots ?? {})) {
|
|
220
|
-
const match = matchNode(slot, segments, index, params, `${path}/@${name}`);
|
|
221
|
-
if (match) slots[name] = match.view;
|
|
222
|
-
else if (slot.fallback) slots[name] = {
|
|
223
|
-
load: slot.fallback,
|
|
224
|
-
key: key(`${path}/@${name}`, "_default", params),
|
|
225
|
-
slots: {}
|
|
226
|
-
};
|
|
227
|
-
}
|
|
228
|
-
return slots;
|
|
229
|
-
}
|
|
230
|
-
/** The view of an `_error.brm`. Its component gets the error as a prop. */
|
|
231
|
-
const ERROR_VIEW = "_error";
|
|
232
|
-
/**
|
|
233
|
-
* Matches the segments from `index` on. `path` is the folders of `node` in
|
|
234
|
-
* the route files, such as `/todos/[id]`.
|
|
235
|
-
*/
|
|
236
|
-
function matchNode(node, segments, index, params, path = "") {
|
|
237
|
-
let inner;
|
|
238
|
-
if (index === segments.length) {
|
|
239
|
-
if (node.page || node.endpoint) inner = {
|
|
240
|
-
view: {
|
|
241
|
-
load: node.page ?? missingPage,
|
|
242
|
-
key: key(path, "index", params),
|
|
243
|
-
slots: {}
|
|
244
|
-
},
|
|
245
|
-
params,
|
|
246
|
-
endpoint: node.endpoint,
|
|
247
|
-
middleware: [],
|
|
248
|
-
errors: []
|
|
249
|
-
};
|
|
250
|
-
} else {
|
|
251
|
-
const first = segments[index];
|
|
252
|
-
const fixed = node.static?.[first];
|
|
253
|
-
inner = fixed && matchNode(fixed, segments, index + 1, params, `${path}/${first}`);
|
|
254
|
-
if (!inner && node.dynamic) {
|
|
255
|
-
const { name } = node.dynamic;
|
|
256
|
-
inner = matchNode(node.dynamic.node, segments, index + 1, {
|
|
257
|
-
...params,
|
|
258
|
-
[name]: first
|
|
259
|
-
}, `${path}/[${name}]`);
|
|
260
|
-
}
|
|
261
|
-
if (!inner && node.rest) {
|
|
262
|
-
const { name } = node.rest;
|
|
263
|
-
inner = matchNode(node.rest.node, segments, segments.length, {
|
|
264
|
-
...params,
|
|
265
|
-
[name]: segments.slice(index).join("/")
|
|
266
|
-
}, `${path}/[...${name}]`);
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
if (!inner) return;
|
|
270
|
-
const content = node.loading ? {
|
|
271
|
-
...inner.view,
|
|
272
|
-
loading: node.loading
|
|
273
|
-
} : inner.view;
|
|
274
|
-
const wrapper = wrapperOf(node, segments, index, params, path);
|
|
275
|
-
const errors = wrapper ? inner.errors.map((view) => wrap(view, wrapper)) : inner.errors;
|
|
276
|
-
if (node.error) errors.push(errorIn(node.error, wrapper, params, path));
|
|
277
|
-
return {
|
|
278
|
-
view: wrap(content, wrapper),
|
|
279
|
-
params: inner.params,
|
|
280
|
-
endpoint: inner.endpoint,
|
|
281
|
-
middleware: node.middleware ? [node.middleware, ...inner.middleware] : inner.middleware,
|
|
282
|
-
errors
|
|
283
|
-
};
|
|
284
|
-
}
|
|
285
|
-
/** An endpoint without a page: a GET that it does not answer has no page either. */
|
|
286
|
-
const missingPage = () => {
|
|
287
|
-
throw new Error("This path has an endpoint and no page");
|
|
288
|
-
};
|
|
289
|
-
/** Finds the route for a path. A path with a malformed escape, such as `/%E0`, matches none. */
|
|
290
|
-
function matchRoute(tree, pathname) {
|
|
291
|
-
let segments;
|
|
292
|
-
try {
|
|
293
|
-
segments = pathname.split("/").filter(Boolean).map((segment) => decodeURIComponent(segment));
|
|
294
|
-
} catch {
|
|
295
|
-
return;
|
|
296
|
-
}
|
|
297
|
-
return matchNode(tree, segments, 0, {});
|
|
298
|
-
}
|
|
299
|
-
/**
|
|
300
|
-
* The views for a path that no route matches: the `_error.brm` of the
|
|
301
|
-
* root, inside the root layout, and the root middleware.
|
|
302
|
-
*/
|
|
303
|
-
function notFound(tree) {
|
|
304
|
-
return {
|
|
305
|
-
errors: tree.error ? [errorIn(tree.error, wrapperOf(tree, [], 0, {}, ""), {}, "")] : [],
|
|
306
|
-
middleware: tree.middleware ? [tree.middleware] : []
|
|
307
|
-
};
|
|
308
|
-
}
|
|
309
|
-
//#endregion
|
|
310
|
-
//#region src/runtime/validate.ts
|
|
311
|
-
/**
|
|
312
|
-
* The error that `parse` throws when the value does not match. It answers
|
|
313
|
-
* with status 400 and its message, as any `ServerError` does. Its `issues`
|
|
314
|
-
* stay on the server.
|
|
315
|
-
*/
|
|
316
|
-
var ValidationError = class extends ServerError {
|
|
317
|
-
issues;
|
|
318
|
-
constructor(issues) {
|
|
319
|
-
super(summary(issues), { status: 400 });
|
|
320
|
-
this.name = "ValidationError";
|
|
321
|
-
this.issues = issues;
|
|
322
|
-
}
|
|
323
|
-
};
|
|
324
|
-
/** The longest message that `parse` sends, so a long input in a message stays short. */
|
|
325
|
-
const MAX_MESSAGE = 300;
|
|
326
|
-
/** The message of a `ValidationError`: the first issue with its path, and how many others there are. */
|
|
327
|
-
function summary(issues) {
|
|
328
|
-
const first = issues[0];
|
|
329
|
-
if (!first) return "Invalid input";
|
|
330
|
-
const path = first.path?.join(".");
|
|
331
|
-
let message = path ? `${path}: ${first.message}` : first.message;
|
|
332
|
-
if (message.length > MAX_MESSAGE) message = `${message.slice(0, MAX_MESSAGE)}…`;
|
|
333
|
-
const more = issues.length - 1;
|
|
334
|
-
return more > 0 ? `${message} (${more} more ${more === 1 ? "issue" : "issues"})` : message;
|
|
335
|
-
}
|
|
336
|
-
/**
|
|
337
|
-
* Copies an issue as plain data. A `{ key }` segment becomes its key, and a
|
|
338
|
-
* symbol becomes its text, such as `Symbol(id)`. Other fields of the issue,
|
|
339
|
-
* which some libraries add, are left out, so the input is not sent back.
|
|
340
|
-
*/
|
|
341
|
-
function plainIssue(issue) {
|
|
342
|
-
const plain = { message: String(issue.message) };
|
|
343
|
-
if (issue.path && issue.path.length > 0) plain.path = issue.path.map((segment) => {
|
|
344
|
-
const key = typeof segment === "object" && segment !== null ? segment.key : segment;
|
|
345
|
-
return typeof key === "number" ? key : String(key);
|
|
346
|
-
});
|
|
347
|
-
return plain;
|
|
348
|
-
}
|
|
349
|
-
/**
|
|
350
|
-
* Validates a value with a Standard Schema. Returns `{ value }` with the
|
|
351
|
-
* output of the schema, or `{ issues }` as plain data. It does not throw for
|
|
352
|
-
* a value that does not match.
|
|
353
|
-
*/
|
|
354
|
-
async function safeParse(schema, value) {
|
|
355
|
-
const props = schema["~standard"];
|
|
356
|
-
if (props?.version !== 1 || typeof props.validate !== "function") throw new TypeError("The schema is not a Standard Schema of version 1");
|
|
357
|
-
const result = await props.validate(value);
|
|
358
|
-
if (result.issues) return { issues: result.issues.map(plainIssue) };
|
|
359
|
-
return { value: result.value };
|
|
360
|
-
}
|
|
361
|
-
/**
|
|
362
|
-
* Validates a value with a Standard Schema, and returns the output of the
|
|
363
|
-
* schema. A value that does not match throws a `ValidationError`, which
|
|
364
|
-
* answers with status 400 and a message built from the first issue.
|
|
365
|
-
*
|
|
366
|
-
* ```ts
|
|
367
|
-
* async function save(input: unknown) {
|
|
368
|
-
* 'use server';
|
|
369
|
-
* const todo = await parse(Todo, input);
|
|
370
|
-
* await db.todos.save(todo);
|
|
371
|
-
* }
|
|
372
|
-
* ```
|
|
373
|
-
*/
|
|
374
|
-
async function parse(schema, value) {
|
|
375
|
-
const result = await safeParse(schema, value);
|
|
376
|
-
if (result.issues) throw new ValidationError(result.issues);
|
|
377
|
-
return result.value;
|
|
378
|
-
}
|
|
379
|
-
/** Names that would change the prototype of an object, or reach the one of its constructor. */
|
|
380
|
-
const FORBIDDEN = /* @__PURE__ */ new Set([
|
|
381
|
-
"__proto__",
|
|
382
|
-
"constructor",
|
|
383
|
-
"prototype"
|
|
384
|
-
]);
|
|
385
|
-
/**
|
|
386
|
-
* Turns the entries of a form into a plain object:
|
|
387
|
-
*
|
|
388
|
-
* - A name that appears once holds its value.
|
|
389
|
-
* - A name that appears more than once holds an array of its values.
|
|
390
|
-
* - A name that ends with `[]` always holds an array, under the name without `[]`.
|
|
391
|
-
* - Dots nest objects: `address.city` is `{ address: { city } }`.
|
|
392
|
-
* - Values stay strings and files.
|
|
393
|
-
*
|
|
394
|
-
* A name with an empty part, a part such as `__proto__`, or one that needs
|
|
395
|
-
* an object where another field holds a value, is an issue, and the schema
|
|
396
|
-
* does not run.
|
|
397
|
-
*/
|
|
398
|
-
function formValues(form) {
|
|
399
|
-
const root = {};
|
|
400
|
-
const objects = /* @__PURE__ */ new Set([root]);
|
|
401
|
-
const arrays = /* @__PURE__ */ new Set();
|
|
402
|
-
const issues = [];
|
|
403
|
-
for (const [name, value] of form) {
|
|
404
|
-
const list = name.endsWith("[]");
|
|
405
|
-
const parts = (list ? name.slice(0, -2) : name).split(".");
|
|
406
|
-
if (parts.some((part) => part === "" || FORBIDDEN.has(part))) {
|
|
407
|
-
issues.push({ message: "The form has a field name that is not allowed" });
|
|
408
|
-
continue;
|
|
409
|
-
}
|
|
410
|
-
let target = root;
|
|
411
|
-
let conflict = false;
|
|
412
|
-
for (const part of parts.slice(0, -1)) {
|
|
413
|
-
const next = Object.hasOwn(target, part) ? target[part] : void 0;
|
|
414
|
-
if (next === void 0) {
|
|
415
|
-
const child = {};
|
|
416
|
-
objects.add(child);
|
|
417
|
-
target[part] = child;
|
|
418
|
-
target = child;
|
|
419
|
-
} else if (objects.has(next)) target = next;
|
|
420
|
-
else {
|
|
421
|
-
conflict = true;
|
|
422
|
-
break;
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
|
-
const last = parts.at(-1);
|
|
426
|
-
const current = Object.hasOwn(target, last) ? target[last] : void 0;
|
|
427
|
-
if (conflict || objects.has(current)) issues.push({
|
|
428
|
-
message: `Field "${name}" conflicts with another field`,
|
|
429
|
-
path: parts
|
|
430
|
-
});
|
|
431
|
-
else if (arrays.has(current)) current.push(value);
|
|
432
|
-
else if (current !== void 0 || list) {
|
|
433
|
-
const values = current === void 0 ? [value] : [current, value];
|
|
434
|
-
arrays.add(values);
|
|
435
|
-
target[last] = values;
|
|
436
|
-
} else target[last] = value;
|
|
437
|
-
}
|
|
438
|
-
return issues.length > 0 ? { issues } : { value: root };
|
|
439
|
-
}
|
|
440
|
-
/**
|
|
441
|
-
* Validates the data of a form with a Standard Schema. The entries become a
|
|
442
|
-
* plain object first. Returns `{ value }` or `{ issues }`, and does not throw
|
|
443
|
-
* for data that does not match, so a function of `$action` can return the
|
|
444
|
-
* issues for the page to show.
|
|
445
|
-
*
|
|
446
|
-
* ```ts
|
|
447
|
-
* async function signUp(form: FormData) {
|
|
448
|
-
* 'use server';
|
|
449
|
-
* const result = await parseForm(SignUp, form);
|
|
450
|
-
* if (result.issues) {
|
|
451
|
-
* return { errors: fieldErrors(result.issues) };
|
|
452
|
-
* }
|
|
453
|
-
* }
|
|
454
|
-
* ```
|
|
455
|
-
*/
|
|
456
|
-
async function parseForm(schema, form) {
|
|
457
|
-
const values = formValues(form);
|
|
458
|
-
if (values.issues) return { issues: values.issues };
|
|
459
|
-
return safeParse(schema, values.value);
|
|
460
|
-
}
|
|
461
|
-
/**
|
|
462
|
-
* The messages of issues by field, for a page to show next to each field.
|
|
463
|
-
* The key is the path joined with dots, such as `address.city`. Issues
|
|
464
|
-
* without a path, and a path of `__proto__`, are under the key `''`. The
|
|
465
|
-
* result is plain data, so a server function can return it.
|
|
466
|
-
*/
|
|
467
|
-
function fieldErrors(issues) {
|
|
468
|
-
const errors = {};
|
|
469
|
-
for (const issue of issues) {
|
|
470
|
-
let key = plainIssue(issue).path?.join(".") ?? "";
|
|
471
|
-
if (key === "__proto__") key = "";
|
|
472
|
-
(Object.hasOwn(errors, key) ? errors[key] : errors[key] = []).push(String(issue.message));
|
|
473
|
-
}
|
|
474
|
-
return errors;
|
|
475
|
-
}
|
|
476
|
-
//#endregion
|
|
477
|
-
//#region src/runtime/server.ts
|
|
478
|
-
/**
|
|
479
|
-
* Tracks the scopes of one render. A `#loading` body renders in a child
|
|
480
|
-
* context, so its scopes are written with its markup.
|
|
481
|
-
*/
|
|
482
|
-
var Context = class Context {
|
|
483
|
-
state = {};
|
|
484
|
-
root;
|
|
485
|
-
nextScope = 0;
|
|
486
|
-
nextBoundary = 0;
|
|
487
|
-
boundaries = [];
|
|
488
|
-
styles = /* @__PURE__ */ new Set();
|
|
489
|
-
/** Markup of `#portal` blocks, written at the end of the page. */
|
|
490
|
-
portals = [];
|
|
491
|
-
/** Markup of `#head` blocks. */
|
|
492
|
-
heads = [];
|
|
493
|
-
pageTitle;
|
|
494
|
-
onBoundary;
|
|
495
|
-
/** The scope tree of the whole page, for finding contexts across `#loading` bodies. */
|
|
496
|
-
tree = /* @__PURE__ */ new Map();
|
|
497
|
-
/** The scope that renders the next component, which becomes its owner. */
|
|
498
|
-
owner;
|
|
499
|
-
/** Takes back what this context added to the page, from the newest, for `restore`. */
|
|
500
|
-
undo = [];
|
|
501
|
-
/** The URL prefix of server function calls. */
|
|
502
|
-
rpcPrefix = "/_brumate";
|
|
503
|
-
/** The names of the slots of each scope, so an error can name a value that cannot be sent. */
|
|
504
|
-
slotNames = /* @__PURE__ */ new Map();
|
|
505
|
-
/** Results of server functions that a form posted to this page, for `$action`. */
|
|
506
|
-
actions = /* @__PURE__ */ new Map();
|
|
507
|
-
/** The request of the page, when it renders with one. */
|
|
508
|
-
event;
|
|
509
|
-
/** Results of server function calls in this render, so the same call runs once. */
|
|
510
|
-
calls = /* @__PURE__ */ new Map();
|
|
511
|
-
/** The event of the page, for `getEvent()` in a component, which the compiler rewrites to this. */
|
|
512
|
-
getEvent() {
|
|
513
|
-
const event = this.root.event;
|
|
514
|
-
if (!event) throw new Error("getEvent() works while a page renders with a request, such as in a route");
|
|
515
|
-
return event;
|
|
516
|
-
}
|
|
517
|
-
/** Runs code of the render with its event and its call results, such as a memo's compute. */
|
|
518
|
-
run(callback) {
|
|
519
|
-
return withEvent(this.root.event, callback, this.root.calls);
|
|
520
|
-
}
|
|
521
|
-
/** The result of a server function that a form posted to this page. */
|
|
522
|
-
actionResult(fn) {
|
|
523
|
-
return this.root.actions.get(unwrap(fn));
|
|
524
|
-
}
|
|
525
|
-
constructor(root, rpc, base = 0) {
|
|
526
|
-
this.root = root ?? this;
|
|
527
|
-
if (rpc) this.rpcPrefix = rpc;
|
|
528
|
-
this.nextScope = base;
|
|
529
|
-
this.nextBoundary = base;
|
|
530
|
-
}
|
|
531
|
-
/** A number above every scope and boundary ID so far, so a later render can start there. */
|
|
532
|
-
next() {
|
|
533
|
-
return Math.max(this.root.nextScope, this.root.nextBoundary);
|
|
534
|
-
}
|
|
535
|
-
/** Returns the URL prefix of server function calls. */
|
|
536
|
-
rpc() {
|
|
537
|
-
return this.root.rpcPrefix;
|
|
538
|
-
}
|
|
539
|
-
/**
|
|
540
|
-
* Returns a new scope ID. `kind` is the scope's ID in the compiled
|
|
541
|
-
* component, `parent` is the scope that contains it, and `module` is the
|
|
542
|
-
* component ID of a component's root scope.
|
|
543
|
-
*/
|
|
544
|
-
scope(kind, parent, module) {
|
|
545
|
-
const root = this.root;
|
|
546
|
-
const id = root.nextScope++;
|
|
547
|
-
const record = this.record(id);
|
|
548
|
-
record.k = kind;
|
|
549
|
-
if (parent !== void 0) record.p = parent;
|
|
550
|
-
let up = parent;
|
|
551
|
-
if (module !== void 0) {
|
|
552
|
-
record.m = module;
|
|
553
|
-
if (root.owner !== void 0) {
|
|
554
|
-
record.o = root.owner;
|
|
555
|
-
up = root.owner;
|
|
556
|
-
root.owner = void 0;
|
|
557
|
-
}
|
|
558
|
-
}
|
|
559
|
-
root.tree.set(id, { parent: up });
|
|
560
|
-
return id;
|
|
561
|
-
}
|
|
562
|
-
/** The ID that `$id()` makes: the scope's ID and the position of the call. */
|
|
563
|
-
id(scope, index) {
|
|
564
|
-
return `b${scope}-${index}`;
|
|
565
|
-
}
|
|
566
|
-
/** Sets the owner of the next component's root scope. */
|
|
567
|
-
own(scope) {
|
|
568
|
-
this.root.owner = scope;
|
|
569
|
-
}
|
|
570
|
-
/** Provides a value of a context to the scopes inside `scope`. */
|
|
571
|
-
provide(context, value, scope) {
|
|
572
|
-
const node = this.root.tree.get(scope);
|
|
573
|
-
node.values ??= /* @__PURE__ */ new Map();
|
|
574
|
-
node.values.set(context.key, value);
|
|
575
|
-
const record = this.record(scope);
|
|
576
|
-
record.v ??= {};
|
|
577
|
-
record.v[context.key] = value;
|
|
578
|
-
}
|
|
579
|
-
/**
|
|
580
|
-
* Reads a context from the nearest scope that provides it, starting at
|
|
581
|
-
* `scope`. With `slot`, records which slot holds it, so the client can
|
|
582
|
-
* update it when the provided value changes.
|
|
583
|
-
*/
|
|
584
|
-
consume(context, scope, slot) {
|
|
585
|
-
if (slot !== void 0) {
|
|
586
|
-
const record = this.record(scope);
|
|
587
|
-
record.x ??= {};
|
|
588
|
-
record.x[context.key] = slot;
|
|
589
|
-
}
|
|
590
|
-
for (let id = scope; id !== void 0;) {
|
|
591
|
-
const node = this.root.tree.get(id);
|
|
592
|
-
if (node?.values?.has(context.key)) return node.values.get(context.key);
|
|
593
|
-
id = node?.parent;
|
|
594
|
-
}
|
|
595
|
-
return context.defaultValue;
|
|
596
|
-
}
|
|
597
|
-
/** The ID that the next call to `scope()` returns. */
|
|
598
|
-
peek() {
|
|
599
|
-
return this.root.nextScope;
|
|
600
|
-
}
|
|
601
|
-
/** Marks the render so far, such as before a `#try` body, for `restore`. */
|
|
602
|
-
mark() {
|
|
603
|
-
return {
|
|
604
|
-
scope: this.root.nextScope,
|
|
605
|
-
undo: this.undo.length,
|
|
606
|
-
owner: this.root.owner
|
|
607
|
-
};
|
|
608
|
-
}
|
|
609
|
-
/**
|
|
610
|
-
* Takes back what the render added to the page since `mark`, such as a
|
|
611
|
-
* `#try` body that threw, whose markup is not sent: its scopes, the
|
|
612
|
-
* stylesheets it counted as sent, its `#portal` and `#head` markup, its
|
|
613
|
-
* title, its `#loading` bodies, and its links to child components.
|
|
614
|
-
*/
|
|
615
|
-
restore(mark) {
|
|
616
|
-
this.drop(mark.scope);
|
|
617
|
-
for (const undo of this.undo.splice(mark.undo).toReversed()) undo();
|
|
618
|
-
this.root.owner = mark.owner;
|
|
619
|
-
}
|
|
620
|
-
/**
|
|
621
|
-
* Forgets the scopes of this render from `from` on, such as those of a
|
|
622
|
-
* `#try` body that threw, so the client does not resume markup that was
|
|
623
|
-
* never sent. `#loading` bodies render in contexts of their own, so their
|
|
624
|
-
* scopes stay.
|
|
625
|
-
*/
|
|
626
|
-
drop(from) {
|
|
627
|
-
for (const key of Object.keys(this.state)) {
|
|
628
|
-
const id = Number(key);
|
|
629
|
-
if (id >= from) {
|
|
630
|
-
delete this.state[id];
|
|
631
|
-
this.root.slotNames.delete(id);
|
|
632
|
-
this.root.tree.delete(id);
|
|
633
|
-
this.sources.delete(id);
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
}
|
|
637
|
-
record(scope) {
|
|
638
|
-
this.state[scope] ??= {};
|
|
639
|
-
return this.state[scope];
|
|
640
|
-
}
|
|
641
|
-
slots(scope, values, names) {
|
|
642
|
-
this.record(scope).s = values;
|
|
643
|
-
if (names) this.root.slotNames.set(scope, names);
|
|
644
|
-
}
|
|
645
|
-
/**
|
|
646
|
-
* The list of each list item scope whose list is a slot of an enclosing
|
|
647
|
-
* scope, as `[scope, slot]`. The items of a list share one array.
|
|
648
|
-
*/
|
|
649
|
-
sources = /* @__PURE__ */ new Map();
|
|
650
|
-
/**
|
|
651
|
-
* Records the item of a list that can change on the client. `source` is
|
|
652
|
-
* the scope and slot that hold the list, when the compiler found one, so
|
|
653
|
-
* the client can take the item from there.
|
|
654
|
-
*/
|
|
655
|
-
item(scope, value, source) {
|
|
656
|
-
this.record(scope).i = value;
|
|
657
|
-
if (source) this.sources.set(scope, source);
|
|
658
|
-
}
|
|
659
|
-
/** Records the scope of a child component at an anchor of its parent. */
|
|
660
|
-
link(scope, anchor, child) {
|
|
661
|
-
const record = this.record(scope);
|
|
662
|
-
const links = record.c ??= {};
|
|
663
|
-
links[anchor] = child;
|
|
664
|
-
this.undo.push(() => {
|
|
665
|
-
if (links[anchor] === child) delete links[anchor];
|
|
666
|
-
});
|
|
667
|
-
}
|
|
668
|
-
/** Returns the reference that a `ref` signal holds on the server. */
|
|
669
|
-
element(scope, anchor) {
|
|
670
|
-
return new ElementReference(scope, anchor);
|
|
671
|
-
}
|
|
672
|
-
/** Marks a function as a client function, so it serializes as a reference. */
|
|
673
|
-
fn(value, ref, scope) {
|
|
674
|
-
if (typeof value === "function") functionReferences.set(value, new FunctionReference(ref, scope));
|
|
675
|
-
return value;
|
|
676
|
-
}
|
|
677
|
-
/** Returns a component's stylesheet the first time the page renders the component. */
|
|
678
|
-
style(id, css) {
|
|
679
|
-
const styles = this.root.styles;
|
|
680
|
-
if (styles.has(id)) return "";
|
|
681
|
-
styles.add(id);
|
|
682
|
-
this.undo.push(() => styles.delete(id));
|
|
683
|
-
return styleElement(id, css);
|
|
684
|
-
}
|
|
685
|
-
/** Adds the markup of a `#head` block. */
|
|
686
|
-
head(html) {
|
|
687
|
-
const heads = (this.root.sent ? this : this.root).heads;
|
|
688
|
-
heads.push(html);
|
|
689
|
-
this.undo.push(() => removeLast(heads, html));
|
|
690
|
-
}
|
|
691
|
-
/** Sets the title of the page. The last call wins. */
|
|
692
|
-
title(value) {
|
|
693
|
-
const target = this.root.sent ? this : this.root;
|
|
694
|
-
const previous = target.pageTitle;
|
|
695
|
-
const title = value === null || value === void 0 ? "" : String(value);
|
|
696
|
-
target.pageTitle = title;
|
|
697
|
-
this.undo.push(() => {
|
|
698
|
-
if (target.pageTitle === title) target.pageTitle = previous;
|
|
699
|
-
});
|
|
700
|
-
}
|
|
701
|
-
/** True once the first render is done, and its head is about to be sent. */
|
|
702
|
-
sent = false;
|
|
703
|
-
/** Marks the first render as done. Head markup after it streams with its `#loading` body. */
|
|
704
|
-
send() {
|
|
705
|
-
this.root.sent = true;
|
|
706
|
-
}
|
|
707
|
-
/**
|
|
708
|
-
* The head markup and the title that a `#loading` body set, after the
|
|
709
|
-
* head was sent. The title is undefined if the body set none.
|
|
710
|
-
*/
|
|
711
|
-
lateHead() {
|
|
712
|
-
return {
|
|
713
|
-
html: this.heads.join(""),
|
|
714
|
-
title: this.pageTitle
|
|
715
|
-
};
|
|
716
|
-
}
|
|
717
|
-
/** The markup for the document's head: the title and the `#head` blocks. */
|
|
718
|
-
headHTML() {
|
|
719
|
-
return (this.root.pageTitle === void 0 ? "" : `<title>${escape(this.root.pageTitle)}</title>`) + this.root.heads.join("");
|
|
720
|
-
}
|
|
721
|
-
/** Adds the markup of a `#portal` block, which goes after the rest of the page. */
|
|
722
|
-
portal(html) {
|
|
723
|
-
this.portals.push(html);
|
|
724
|
-
this.undo.push(() => removeLast(this.portals, html));
|
|
725
|
-
}
|
|
726
|
-
/** Returns the ID of a new `#loading` boundary. */
|
|
727
|
-
boundary() {
|
|
728
|
-
return this.root.nextBoundary++;
|
|
729
|
-
}
|
|
730
|
-
/** Renders a `#loading` body after the rest of the page, in its own context. */
|
|
731
|
-
defer(id, renderBody) {
|
|
732
|
-
const child = new Context(this.root);
|
|
733
|
-
const boundary = {
|
|
734
|
-
id,
|
|
735
|
-
render: renderBody(child).then((html) => ({
|
|
736
|
-
html,
|
|
737
|
-
ctx: child
|
|
738
|
-
}))
|
|
739
|
-
};
|
|
740
|
-
boundary.render.catch(() => {});
|
|
741
|
-
const root = this.root;
|
|
742
|
-
if (root.onBoundary) root.onBoundary(boundary);
|
|
743
|
-
else root.boundaries.push(boundary);
|
|
744
|
-
this.undo.push(() => {
|
|
745
|
-
boundary.cancelled = true;
|
|
746
|
-
removeLast(root.boundaries, boundary);
|
|
747
|
-
});
|
|
748
|
-
}
|
|
749
|
-
/** Receives every boundary, including those registered before this call. */
|
|
750
|
-
watch(onBoundary) {
|
|
751
|
-
this.onBoundary = onBoundary;
|
|
752
|
-
for (const boundary of this.boundaries.splice(0)) onBoundary(boundary);
|
|
753
|
-
}
|
|
754
|
-
};
|
|
755
|
-
/** Removes the last copy of a value from a list. */
|
|
756
|
-
function removeLast(list, value) {
|
|
757
|
-
const index = list.lastIndexOf(value);
|
|
758
|
-
if (index !== -1) list.splice(index, 1);
|
|
759
|
-
}
|
|
760
|
-
/** Thrown when code reads a memo whose value is still loading. It carries the load. */
|
|
761
|
-
var NotReady = class extends Error {
|
|
762
|
-
source;
|
|
763
|
-
constructor(source) {
|
|
764
|
-
super("The value is still loading");
|
|
765
|
-
this.name = "NotReady";
|
|
766
|
-
this.source = source;
|
|
767
|
-
}
|
|
768
|
-
};
|
|
769
|
-
/** Declares a memo. Its value is computed when it is first read. */
|
|
770
|
-
function memo(compute, ctx) {
|
|
771
|
-
return {
|
|
772
|
-
compute,
|
|
773
|
-
ctx,
|
|
774
|
-
state: "idle"
|
|
775
|
-
};
|
|
776
|
-
}
|
|
777
|
-
/**
|
|
778
|
-
* Reads a memo. A value that is still loading throws `NotReady` with its
|
|
779
|
-
* load, and a memo that read such a value stays unread, so it computes
|
|
780
|
-
* again when it is read after the load settles.
|
|
781
|
-
*/
|
|
782
|
-
function read(node) {
|
|
783
|
-
if (node.state === "done") return node.value;
|
|
784
|
-
if (node.state === "failed") throw node.error;
|
|
785
|
-
if (node.state === "pending") throw new NotReady(node.load);
|
|
786
|
-
let value;
|
|
787
|
-
try {
|
|
788
|
-
value = node.ctx ? node.ctx.run(node.compute) : node.compute();
|
|
789
|
-
} catch (error) {
|
|
790
|
-
if (!(error instanceof NotReady)) {
|
|
791
|
-
node.state = "failed";
|
|
792
|
-
node.error = error;
|
|
793
|
-
}
|
|
794
|
-
throw error;
|
|
795
|
-
}
|
|
796
|
-
if (value !== null && typeof value === "object" && (typeof value.then === "function" || isAsyncIterable(value))) {
|
|
797
|
-
node.state = "pending";
|
|
798
|
-
node.load = Promise.resolve(value).then(firstValue).then((result) => {
|
|
799
|
-
node.state = "done";
|
|
800
|
-
node.value = result;
|
|
801
|
-
}, (error) => {
|
|
802
|
-
node.state = "failed";
|
|
803
|
-
node.error = error;
|
|
804
|
-
});
|
|
805
|
-
throw new NotReady(node.load);
|
|
806
|
-
}
|
|
807
|
-
node.state = "done";
|
|
808
|
-
node.value = value;
|
|
809
|
-
return value;
|
|
810
|
-
}
|
|
811
|
-
/**
|
|
812
|
-
* The first value of an async iterable, such as a server function that
|
|
813
|
-
* streams. A page renders once, so the server stops reading after it. Other
|
|
814
|
-
* values are themselves.
|
|
815
|
-
*/
|
|
816
|
-
async function firstValue(value) {
|
|
817
|
-
if (!isAsyncIterable(value)) return value;
|
|
818
|
-
const iterator = value[Symbol.asyncIterator]();
|
|
819
|
-
const first = await iterator.next();
|
|
820
|
-
await iterator.return?.();
|
|
821
|
-
return first.value;
|
|
822
|
-
}
|
|
823
|
-
/** Waits for the value of a memo, through every load it reads. */
|
|
824
|
-
async function wait(node) {
|
|
825
|
-
for (;;) try {
|
|
826
|
-
return read(node);
|
|
827
|
-
} catch (error) {
|
|
828
|
-
if (!(error instanceof NotReady)) throw error;
|
|
829
|
-
await error.source.catch(() => {});
|
|
830
|
-
}
|
|
831
|
-
}
|
|
832
|
-
/**
|
|
833
|
-
* The value of a memo when it is ready, or a promise of it while it loads.
|
|
834
|
-
* The render then awaits only a memo that is loading.
|
|
835
|
-
*/
|
|
836
|
-
function ready(node) {
|
|
837
|
-
try {
|
|
838
|
-
return read(node);
|
|
839
|
-
} catch (error) {
|
|
840
|
-
if (error instanceof NotReady) return wait(node);
|
|
841
|
-
throw error;
|
|
842
|
-
}
|
|
843
|
-
}
|
|
844
|
-
const LAZY = Symbol.for("brumate.lazy");
|
|
845
|
-
/** Makes markup that renders where it is inserted, such as the children of a layout. */
|
|
846
|
-
function lazy(renderAt) {
|
|
847
|
-
return { [LAZY]: renderAt };
|
|
848
|
-
}
|
|
849
|
-
function isLazy(value) {
|
|
850
|
-
return typeof value === "object" && value !== null && LAZY in value;
|
|
851
|
-
}
|
|
852
|
-
/** Renders the attributes of a form or button that posts to a server function. */
|
|
853
|
-
function action(ctx, name, id, method, result) {
|
|
854
|
-
return actionAttributes(ctx.rpc(), name, id, method, result);
|
|
855
|
-
}
|
|
856
|
-
/**
|
|
857
|
-
* The result of a server function that a form posted to this page, for
|
|
858
|
-
* `$action`, or undefined when the page was not rendered for a post.
|
|
859
|
-
*/
|
|
860
|
-
function actionResult(ctx, fn) {
|
|
861
|
-
return ctx.actionResult(fn);
|
|
862
|
-
}
|
|
863
|
-
/**
|
|
864
|
-
* Renders a value inserted in markup. `ctx` and `scope` are where it is
|
|
865
|
-
* inserted, for markup that renders there.
|
|
866
|
-
*/
|
|
867
|
-
function insert(value, ctx, scope) {
|
|
868
|
-
if (value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function") return Promise.resolve(value).then((resolved) => insert(resolved, ctx, scope));
|
|
869
|
-
if (isLazy(value) && ctx) return value[LAZY](ctx, scope);
|
|
870
|
-
if (Array.isArray(value)) {
|
|
871
|
-
const parts = value.map((item) => insert(item, ctx, scope));
|
|
872
|
-
return parts.every((part) => typeof part === "string") ? parts.join("") : Promise.all(parts).then((all) => all.join(""));
|
|
873
|
-
}
|
|
874
|
-
return insertValue(value);
|
|
875
|
-
}
|
|
876
|
-
/**
|
|
877
|
-
* Renders a child component. With `scope` and `anchor`, records the child's
|
|
878
|
-
* scope so the parent can update its props on the client.
|
|
879
|
-
*/
|
|
880
|
-
function component(Child, props, ctx, scope, anchor) {
|
|
881
|
-
if (scope !== void 0 && anchor !== void 0) ctx.link(scope, anchor, ctx.peek());
|
|
882
|
-
if (scope !== void 0) ctx.own(scope);
|
|
883
|
-
return Child(props, ctx);
|
|
884
|
-
}
|
|
885
|
-
/** Renders a dynamic tag, which can be an element name or a component. */
|
|
886
|
-
function dynamic(tag, attributes, children, ctx, scope) {
|
|
887
|
-
if (typeof tag === "function") return component(tag, children ? {
|
|
888
|
-
...attributes,
|
|
889
|
-
children
|
|
890
|
-
} : attributes, ctx, scope);
|
|
891
|
-
const open = `<${tag}${spread(attributes)}>`;
|
|
892
|
-
if (VOID_ELEMENTS.has(tag)) return open;
|
|
893
|
-
return `${open}${children && isRaw(children) ? rawHTML(children) : ""}</${tag}>`;
|
|
894
|
-
}
|
|
895
|
-
/** True when `value` is `target`, or holds it in plain objects, arrays, maps or sets. */
|
|
896
|
-
function holds(value, target, seen = /* @__PURE__ */ new Set()) {
|
|
897
|
-
if (value === target) return true;
|
|
898
|
-
if (typeof value !== "object" || value === null || seen.has(value)) return false;
|
|
899
|
-
seen.add(value);
|
|
900
|
-
return (value instanceof Map ? [...value.keys(), ...value.values()] : value instanceof Set ? [...value] : Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype ? Object.values(value) : []).some((item) => holds(item, target, seen));
|
|
901
|
-
}
|
|
902
|
-
/**
|
|
903
|
-
* The error of a value in the state of a page that cannot be sent to the
|
|
904
|
-
* browser, which names the value and its component.
|
|
905
|
-
*/
|
|
906
|
-
function unsendable(error, ctx) {
|
|
907
|
-
const target = error.value;
|
|
908
|
-
if (target === void 0) return error instanceof Error ? error : new Error(String(error));
|
|
909
|
-
for (const [id, record] of Object.entries(ctx.state)) {
|
|
910
|
-
const index = (record.s ?? []).findIndex((value) => holds(value, target));
|
|
911
|
-
if (index === -1) continue;
|
|
912
|
-
let owner = record;
|
|
913
|
-
while (owner && owner.m === void 0 && owner.p !== void 0) owner = ctx.state[owner.p];
|
|
914
|
-
const name = ctx.slotNames.get(Number(id))?.[index] ?? `slot ${index}`;
|
|
915
|
-
const kind = target?.constructor?.name ?? typeof target;
|
|
916
|
-
return new Error(`The value of "${name}" in ${owner?.m ?? "a component"} holds a ${kind}, which cannot be sent to the browser, and code that runs in the browser reads it. Use it in a server function, or create it in the browser, such as in $client.`, { cause: error });
|
|
917
|
-
}
|
|
918
|
-
return error instanceof Error ? error : new Error(String(error));
|
|
919
|
-
}
|
|
920
|
-
/** JSON that is safe in a `<script>`, with each `<` escaped. */
|
|
921
|
-
function scriptJSON(value) {
|
|
922
|
-
return JSON.stringify(value).replace(/</g, "\\u003c");
|
|
923
|
-
}
|
|
924
|
-
/** The fields that a record in a group of `PackedState` can have. */
|
|
925
|
-
const PACKED_FIELDS = /* @__PURE__ */ new Set([
|
|
926
|
-
"k",
|
|
927
|
-
"p",
|
|
928
|
-
"o",
|
|
929
|
-
"m",
|
|
930
|
-
"s",
|
|
931
|
-
"i",
|
|
932
|
-
"c"
|
|
933
|
-
]);
|
|
934
|
-
/**
|
|
935
|
-
* The list that the client can take the items of a group from: the items
|
|
936
|
-
* are list items with the same source, the source's record is in `state`,
|
|
937
|
-
* and the item of the scope at each position of the group is the value at
|
|
938
|
-
* that position of the list. The client reads the same list, so it gets the
|
|
939
|
-
* same values. Otherwise the items are written.
|
|
940
|
-
*/
|
|
941
|
-
function groupSource(state, sources, group) {
|
|
942
|
-
const source = sources.get(group.ids[0]);
|
|
943
|
-
if (!source || !(group.flags & 3)) return;
|
|
944
|
-
const value = state[source[0]]?.s?.[source[1]];
|
|
945
|
-
const list = Array.isArray(value) ? value : value instanceof Set ? Array.from(value) : void 0;
|
|
946
|
-
if (!list || list.length < group.ids.length) return;
|
|
947
|
-
for (let n = 0; n < group.ids.length; n++) {
|
|
948
|
-
const id = group.ids[n];
|
|
949
|
-
if (sources.get(id) !== source || !Object.is(list[n], state[id].i)) return;
|
|
950
|
-
}
|
|
951
|
-
return source;
|
|
952
|
-
}
|
|
953
|
-
/**
|
|
954
|
-
* Writes the records of scopes with the same kind, parent and shape, such as
|
|
955
|
-
* the items of a list, in groups. Each one then costs its slots and the gap
|
|
956
|
-
* to the ID before it. The items of a list whose list is in `sources` and in
|
|
957
|
-
* the state are not written. See `PackedState`.
|
|
958
|
-
*/
|
|
959
|
-
function packState(state, sources) {
|
|
960
|
-
const result = {};
|
|
961
|
-
const groups = /* @__PURE__ */ new Map();
|
|
962
|
-
for (const [key, record] of Object.entries(state)) {
|
|
963
|
-
const id = Number(key);
|
|
964
|
-
const base = record.p ?? (record.o === void 0 ? void 0 : id - record.o);
|
|
965
|
-
if (record.k === void 0 || base === void 0 || record.p !== void 0 && record.o !== void 0 || !Object.keys(record).every((field) => PACKED_FIELDS.has(field))) {
|
|
966
|
-
result[id] = record;
|
|
967
|
-
continue;
|
|
968
|
-
}
|
|
969
|
-
const slots = record.s ?? [];
|
|
970
|
-
let flags = record.p === void 0 ? 8 : 0;
|
|
971
|
-
if ("i" in record) flags |= slots.length > 0 && Object.is(record.i, slots[0]) ? 1 : 2;
|
|
972
|
-
if (record.c) flags |= 4;
|
|
973
|
-
if (record.m !== void 0) flags |= 16;
|
|
974
|
-
const name = `${record.k}:${base}:${flags}:${slots.length}:${record.m ?? ""}`;
|
|
975
|
-
const group = groups.get(name);
|
|
976
|
-
if (group) group.ids.push(id);
|
|
977
|
-
else groups.set(name, {
|
|
978
|
-
k: record.k,
|
|
979
|
-
base,
|
|
980
|
-
flags,
|
|
981
|
-
count: slots.length,
|
|
982
|
-
m: record.m,
|
|
983
|
-
ids: [id]
|
|
984
|
-
});
|
|
985
|
-
}
|
|
986
|
-
const packed = [];
|
|
987
|
-
for (const group of groups.values()) {
|
|
988
|
-
const { ids } = group;
|
|
989
|
-
if (ids.length === 1) {
|
|
990
|
-
result[ids[0]] = state[ids[0]];
|
|
991
|
-
continue;
|
|
992
|
-
}
|
|
993
|
-
const source = sources && sources.size > 0 ? groupSource(state, sources, group) : void 0;
|
|
994
|
-
const flags = source ? group.flags | 32 : group.flags;
|
|
995
|
-
const values = [
|
|
996
|
-
group.k,
|
|
997
|
-
group.base,
|
|
998
|
-
flags,
|
|
999
|
-
group.count
|
|
1000
|
-
];
|
|
1001
|
-
if (group.m !== void 0) values.push(group.m);
|
|
1002
|
-
if (source) values.push(source[0], source[1]);
|
|
1003
|
-
const from = source && flags & 1 ? 1 : 0;
|
|
1004
|
-
const item = !source && flags & 2;
|
|
1005
|
-
let last = flags & 8 ? 0 : group.base;
|
|
1006
|
-
for (const id of ids) {
|
|
1007
|
-
const record = state[id];
|
|
1008
|
-
values.push(id - last);
|
|
1009
|
-
const slots = record.s ?? [];
|
|
1010
|
-
for (let n = from; n < slots.length; n++) values.push(slots[n]);
|
|
1011
|
-
if (item) values.push(record.i);
|
|
1012
|
-
if (flags & 4) values.push(record.c);
|
|
1013
|
-
last = id;
|
|
1014
|
-
}
|
|
1015
|
-
packed.push(values);
|
|
1016
|
-
}
|
|
1017
|
-
if (packed.length > 0) result.g = packed;
|
|
1018
|
-
return result;
|
|
1019
|
-
}
|
|
1020
|
-
/**
|
|
1021
|
-
* Serializes the page state as seroval cross-reference code, one record at
|
|
1022
|
-
* a time. The first record holds the state, and each later record settles a
|
|
1023
|
-
* promise in it. Records that share `refs` can refer to each other's values.
|
|
1024
|
-
*/
|
|
1025
|
-
function serializeState(state, refs, onRecord, onError, onDone, sources) {
|
|
1026
|
-
crossSerializeStream(packState(state, sources), {
|
|
1027
|
-
plugins,
|
|
1028
|
-
disabledFeatures,
|
|
1029
|
-
refs,
|
|
1030
|
-
onSerialize: onRecord,
|
|
1031
|
-
onError,
|
|
1032
|
-
onDone
|
|
1033
|
-
});
|
|
1034
|
-
}
|
|
1035
|
-
/**
|
|
1036
|
-
* Serializes the page state as the code of state records. `onRecord`
|
|
1037
|
-
* receives each record as soon as it is ready. The promise resolves when
|
|
1038
|
-
* every promise in the state has settled.
|
|
1039
|
-
*/
|
|
1040
|
-
function streamState(state, onRecord) {
|
|
1041
|
-
return new Promise((resolve, reject) => {
|
|
1042
|
-
serializeState(state, /* @__PURE__ */ new Map(), onRecord, reject, resolve);
|
|
1043
|
-
});
|
|
1044
|
-
}
|
|
1045
|
-
/**
|
|
1046
|
-
* Defines `$bR`, which hands the code of a state record and its script to
|
|
1047
|
-
* the core, through `self.$brm`. The core runs the code when it starts, or
|
|
1048
|
-
* at once when it has started. The first record of each render defines it.
|
|
1049
|
-
*/
|
|
1050
|
-
const RECORD = "function $bR(f){(self.$brm=self.$brm||[]).push([document.currentScript,f])}";
|
|
1051
|
-
/**
|
|
1052
|
-
* Returns the script of a state record. `scopes` marks a record with scopes,
|
|
1053
|
-
* as opposed to one that settles a promise. The record is code that seroval
|
|
1054
|
-
* wrote, as a function of the references of its render, `$R`, and of the
|
|
1055
|
-
* functions that make brumate's values, `$b`. seroval escapes every `<` in
|
|
1056
|
-
* the strings in it.
|
|
1057
|
-
*/
|
|
1058
|
-
function stateScript(code, scopes = false, attributes = {}) {
|
|
1059
|
-
if (code.includes("</") || code.includes("<!")) throw new Error("A state record would end its script");
|
|
1060
|
-
let extra = attributes.nonce === void 0 ? "" : ` nonce="${escapeAttribute(attributes.nonce)}"`;
|
|
1061
|
-
extra += " b-state";
|
|
1062
|
-
if (scopes) extra += " b-scopes";
|
|
1063
|
-
if (attributes.next !== void 0) extra += ` b-next="${attributes.next}"`;
|
|
1064
|
-
if (attributes.root) extra += ` b-root="${attributes.root}"`;
|
|
1065
|
-
if (attributes.route !== void 0) extra += ` b-route="${escapeAttribute(attributes.route)}"`;
|
|
1066
|
-
return `<script${extra}>${attributes.define ? RECORD : ""}$bR(($R,$b)=>(${code}))<\/script>`;
|
|
1067
|
-
}
|
|
1068
|
-
const HEAD = `function $bH(i,t){var e=document.querySelector('template[b-h="'+i+'"]');e&&(document.head.append(e.content),e.remove());t!=null&&(document.title=t)}`;
|
|
1069
|
-
const SWAP = `function $bS(i){var t=document.querySelector('template[b-l="'+i+'"]'),w=document.createTreeWalker(document.body,128),s,n,d=0;while(n=w.nextNode())if(n.data==='l'+i){s=n;break}if(!s||!t)return;var p=s.parentNode;for(n=s.nextSibling;n;){if(n.nodeType===8){if(n.data==='/l'){if(!d)break;d--}else if(/^l\\d/.test(n.data))d++}var x=n.nextSibling;p.removeChild(n);n=x}p.insertBefore(t.content,s);p.removeChild(s);n&&p.removeChild(n);t.remove()}`;
|
|
1070
|
-
/** The `pending` of a render that has nothing left to send. */
|
|
1071
|
-
const NOTHING_PENDING = { [Symbol.asyncIterator]: () => ({ next: () => Promise.resolve({
|
|
1072
|
-
done: true,
|
|
1073
|
-
value: void 0
|
|
1074
|
-
}) }) };
|
|
1075
|
-
/** An async iterable that a producer pushes into. */
|
|
1076
|
-
function createQueue() {
|
|
1077
|
-
const items = [];
|
|
1078
|
-
let wake;
|
|
1079
|
-
let closed = false;
|
|
1080
|
-
let failure;
|
|
1081
|
-
const notify = () => {
|
|
1082
|
-
wake?.();
|
|
1083
|
-
wake = void 0;
|
|
1084
|
-
};
|
|
1085
|
-
return {
|
|
1086
|
-
push(item) {
|
|
1087
|
-
items.push(item);
|
|
1088
|
-
notify();
|
|
1089
|
-
},
|
|
1090
|
-
close() {
|
|
1091
|
-
closed = true;
|
|
1092
|
-
notify();
|
|
1093
|
-
},
|
|
1094
|
-
fail(error) {
|
|
1095
|
-
failure = { error };
|
|
1096
|
-
notify();
|
|
1097
|
-
},
|
|
1098
|
-
iterable: { async *[Symbol.asyncIterator]() {
|
|
1099
|
-
for (;;) if (items.length > 0) yield items.shift();
|
|
1100
|
-
else if (failure) throw failure.error;
|
|
1101
|
-
else if (closed) return;
|
|
1102
|
-
else await new Promise((resolve) => {
|
|
1103
|
-
wake = resolve;
|
|
1104
|
-
});
|
|
1105
|
-
} }
|
|
1106
|
-
};
|
|
1107
|
-
}
|
|
1108
|
-
/**
|
|
1109
|
-
* Renders the parts of a page. It returns as soon as the markup is rendered.
|
|
1110
|
-
* `#loading` bodies and promises in the state do not hold it up: they come
|
|
1111
|
-
* later, from `pending`. `renderToStream` puts the parts together. Use this
|
|
1112
|
-
* directly to send the response headers that server functions set before
|
|
1113
|
-
* the stream starts.
|
|
1114
|
-
*/
|
|
1115
|
-
async function render(Root, props, options = {}) {
|
|
1116
|
-
const scriptTag = options.nonce === void 0 ? "<script>" : `<script nonce="${escapeAttribute(options.nonce)}">`;
|
|
1117
|
-
const ctx = new Context(void 0, options.rpc, options.base);
|
|
1118
|
-
if (options.actions) ctx.actions = options.actions;
|
|
1119
|
-
const event = options.event ?? (options.request ? new RequestEvent(options.request) : void 0);
|
|
1120
|
-
ctx.event = event;
|
|
1121
|
-
const rendered = await ctx.run(() => Root(props, ctx));
|
|
1122
|
-
ctx.send();
|
|
1123
|
-
const html = beforeBodyEnd(rendered, ctx.portals.join(""));
|
|
1124
|
-
let queue;
|
|
1125
|
-
const pending = () => queue ??= createQueue();
|
|
1126
|
-
const refs = /* @__PURE__ */ new Map();
|
|
1127
|
-
const { nonce, base: root } = options;
|
|
1128
|
-
let first = true;
|
|
1129
|
-
let open = 0;
|
|
1130
|
-
let swap = false;
|
|
1131
|
-
let headSwap = false;
|
|
1132
|
-
const finish = () => {
|
|
1133
|
-
open--;
|
|
1134
|
-
if (open === 0) queue?.close();
|
|
1135
|
-
};
|
|
1136
|
-
const serialize = ({ state, sources }, onScopes, route, onError = (error) => pending().fail(error)) => {
|
|
1137
|
-
open++;
|
|
1138
|
-
serializeState(state, refs, (code, initial) => {
|
|
1139
|
-
if (initial) {
|
|
1140
|
-
onScopes(stateScript(code, true, {
|
|
1141
|
-
next: ctx.next(),
|
|
1142
|
-
route,
|
|
1143
|
-
root,
|
|
1144
|
-
nonce,
|
|
1145
|
-
define: first
|
|
1146
|
-
}));
|
|
1147
|
-
first = false;
|
|
1148
|
-
} else pending().push(stateScript(code, false, {
|
|
1149
|
-
root,
|
|
1150
|
-
nonce
|
|
1151
|
-
}));
|
|
1152
|
-
}, onError, finish, sources);
|
|
1153
|
-
};
|
|
1154
|
-
ctx.watch((boundary) => {
|
|
1155
|
-
open++;
|
|
1156
|
-
boundary.render.then((result) => {
|
|
1157
|
-
if (boundary.cancelled) {
|
|
1158
|
-
finish();
|
|
1159
|
-
return;
|
|
1160
|
-
}
|
|
1161
|
-
serialize(result.ctx, (script) => {
|
|
1162
|
-
let call = `${swap ? "" : SWAP}$bS(${boundary.id})`;
|
|
1163
|
-
swap = true;
|
|
1164
|
-
const late = result.ctx.lateHead();
|
|
1165
|
-
let head = "";
|
|
1166
|
-
if (late.html || late.title !== void 0) {
|
|
1167
|
-
head = `<template b-h="${boundary.id}">${late.html}</template>`;
|
|
1168
|
-
const title = late.title === void 0 ? "" : `,${scriptJSON(late.title)}`;
|
|
1169
|
-
call += `;${headSwap ? "" : HEAD}$bH(${boundary.id}${title})`;
|
|
1170
|
-
headSwap = true;
|
|
1171
|
-
}
|
|
1172
|
-
pending().push(`<template b-l="${boundary.id}">${result.html}</template>${head}${result.ctx.portals.join("")}${scriptTag}${call}<\/script>${script}`);
|
|
1173
|
-
});
|
|
1174
|
-
finish();
|
|
1175
|
-
}, (error) => {
|
|
1176
|
-
console.error(error);
|
|
1177
|
-
finish();
|
|
1178
|
-
});
|
|
1179
|
-
});
|
|
1180
|
-
let state = "";
|
|
1181
|
-
let failure;
|
|
1182
|
-
serialize(ctx, (script) => {
|
|
1183
|
-
state = script;
|
|
1184
|
-
}, options.route, (error) => {
|
|
1185
|
-
failure = error;
|
|
1186
|
-
});
|
|
1187
|
-
if (failure !== void 0) throw unsendable(failure, ctx);
|
|
1188
|
-
return {
|
|
1189
|
-
html,
|
|
1190
|
-
state,
|
|
1191
|
-
pending: queue === void 0 && open === 0 ? NOTHING_PENDING : pending().iterable,
|
|
1192
|
-
headers: event?.headers ?? new Headers(),
|
|
1193
|
-
status: event?.status ?? 200,
|
|
1194
|
-
next: () => ctx.next(),
|
|
1195
|
-
head: ctx.headHTML()
|
|
1196
|
-
};
|
|
1197
|
-
}
|
|
1198
|
-
const HTML = /<html[\s>]/i;
|
|
1199
|
-
/**
|
|
1200
|
-
* Inserts markup before `</body>`, or at the end if there is none. `index`
|
|
1201
|
-
* is where `</body>` is, when the caller found it already.
|
|
1202
|
-
*/
|
|
1203
|
-
function beforeBodyEnd(html, content, index = content ? html.toLowerCase().lastIndexOf("</body>") : -1) {
|
|
1204
|
-
if (!content) return html;
|
|
1205
|
-
return index === -1 ? html + content : html.slice(0, index) + content + html.slice(index);
|
|
1206
|
-
}
|
|
1207
|
-
/**
|
|
1208
|
-
* Builds the first chunk of a page: the whole rendered document, with the
|
|
1209
|
-
* page state and the scripts. A component that renders `<html>` gets the
|
|
1210
|
-
* doctype, its head before `</head>`, and the state and scripts before
|
|
1211
|
-
* `</body>`. Markup that resolves later is written after it.
|
|
1212
|
-
*/
|
|
1213
|
-
function firstRender(html, componentHead, state, options) {
|
|
1214
|
-
const head = (options.head ?? "") + componentHead;
|
|
1215
|
-
const tail = state + (options.scripts ?? "");
|
|
1216
|
-
const match = HTML.exec(html);
|
|
1217
|
-
if (!match) return (typeof options.start === "function" ? options.start(head) : options.start ?? "") + html + tail + (options.end ?? "");
|
|
1218
|
-
const headContent = html.slice(0, match.index) + head;
|
|
1219
|
-
let page = html.slice(match.index);
|
|
1220
|
-
const lower = page.toLowerCase();
|
|
1221
|
-
const headEnd = lower.indexOf("</head>");
|
|
1222
|
-
let bodyEnd = lower.lastIndexOf("</body>");
|
|
1223
|
-
let at = headEnd;
|
|
1224
|
-
let inserted = headContent;
|
|
1225
|
-
if (headEnd === -1 && headContent) {
|
|
1226
|
-
const bodyStart = lower.search(/<body[\s>]/);
|
|
1227
|
-
at = bodyStart === -1 ? page.indexOf(">") + 1 : bodyStart;
|
|
1228
|
-
inserted = `<head>${headContent}</head>`;
|
|
1229
|
-
}
|
|
1230
|
-
if (at !== -1 && inserted) {
|
|
1231
|
-
page = page.slice(0, at) + inserted + page.slice(at);
|
|
1232
|
-
const own = inserted.toLowerCase();
|
|
1233
|
-
if (bodyEnd >= at) bodyEnd += own.length;
|
|
1234
|
-
else if (own.includes("</body>")) bodyEnd = at + own.lastIndexOf("</body>");
|
|
1235
|
-
}
|
|
1236
|
-
return `<!doctype html>${beforeBodyEnd(page, tail, bodyEnd)}`;
|
|
1237
|
-
}
|
|
1238
|
-
/**
|
|
1239
|
-
* Renders a component as a stream. The first chunk is the whole first
|
|
1240
|
-
* render, sent as soon as it is ready. Each `#loading` body and each state
|
|
1241
|
-
* record that settles a promise follows it as it resolves. A component that
|
|
1242
|
-
* renders `<html>` gets the doctype and its head.
|
|
1243
|
-
*/
|
|
1244
|
-
function renderToStream(Root, props, options = {}) {
|
|
1245
|
-
return partsStream(() => render(Root, props, options), options);
|
|
1246
|
-
}
|
|
1247
|
-
/** Streams the parts of a page from `render`: the first render whole, then what resolves later. */
|
|
1248
|
-
function streamParts(parts, options = {}) {
|
|
1249
|
-
return partsStream(() => parts, options);
|
|
1250
|
-
}
|
|
1251
|
-
/** A stream of the parts of a page. An error while it gets or writes them fails the stream. */
|
|
1252
|
-
function partsStream(getParts, options) {
|
|
1253
|
-
return new ReadableStream({ async start(controller) {
|
|
1254
|
-
try {
|
|
1255
|
-
await writeParts(await getParts(), options, controller);
|
|
1256
|
-
} catch (error) {
|
|
1257
|
-
controller.error(error);
|
|
1258
|
-
}
|
|
1259
|
-
} });
|
|
1260
|
-
}
|
|
1261
|
-
async function writeParts(parts, options, controller) {
|
|
1262
|
-
controller.enqueue(firstRender(parts.html, parts.head, parts.state, options));
|
|
1263
|
-
if (parts.pending !== NOTHING_PENDING) for await (const chunk of parts.pending) controller.enqueue(chunk);
|
|
1264
|
-
controller.close();
|
|
1265
|
-
}
|
|
1266
|
-
/**
|
|
1267
|
-
* The message and status that answer an error. A `ServerError` sends its
|
|
1268
|
-
* own. Any other error is logged, and sends `fallback` with status 500.
|
|
1269
|
-
*/
|
|
1270
|
-
function errorAnswer(error, fallback) {
|
|
1271
|
-
if (error instanceof ServerError) return {
|
|
1272
|
-
message: error.message,
|
|
1273
|
-
status: error.status
|
|
1274
|
-
};
|
|
1275
|
-
console.error(error);
|
|
1276
|
-
return {
|
|
1277
|
-
message: fallback,
|
|
1278
|
-
status: 500
|
|
1279
|
-
};
|
|
1280
|
-
}
|
|
1281
|
-
/** True for a request that a `<form>` sent, without client code. */
|
|
1282
|
-
function isFormPost(request) {
|
|
1283
|
-
const type = request.headers.get("content-type") ?? "";
|
|
1284
|
-
return type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data");
|
|
1285
|
-
}
|
|
1286
|
-
/** The answer to a call or a form post from a page of another site. See `isCrossSite`. */
|
|
1287
|
-
function crossSiteAnswer() {
|
|
1288
|
-
return new Response("Calls from other sites are not allowed", { status: 403 });
|
|
1289
|
-
}
|
|
1290
|
-
/** The answer to a call or a form post to a server function that does not exist. */
|
|
1291
|
-
function unknownAnswer(id) {
|
|
1292
|
-
return new Response(`Unknown server function "${id}"`, { status: 404 });
|
|
1293
|
-
}
|
|
1294
|
-
/**
|
|
1295
|
-
* Calls a server function with the data of a form that the browser sent.
|
|
1296
|
-
* Returns its result, or the response that answers the post instead: a
|
|
1297
|
-
* `redirect` in the function sends the browser there, and an error answers
|
|
1298
|
-
* with a short text page, because there is no page to report it in. The
|
|
1299
|
-
* response has `headers`. With `base`, the location of a redirect is
|
|
1300
|
-
* resolved against it.
|
|
1301
|
-
*/
|
|
1302
|
-
async function callWithForm(fn, request, event, headers, base) {
|
|
1303
|
-
try {
|
|
1304
|
-
const form = await request.formData();
|
|
1305
|
-
return { result: await withEvent(event, () => fn(form)) };
|
|
1306
|
-
} catch (error) {
|
|
1307
|
-
if (error instanceof Redirect) {
|
|
1308
|
-
headers.set("location", base ? new URL(error.location, base).href : error.location);
|
|
1309
|
-
return { answer: new Response(null, {
|
|
1310
|
-
status: error.status,
|
|
1311
|
-
headers
|
|
1312
|
-
}) };
|
|
1313
|
-
}
|
|
1314
|
-
const { message, status } = errorAnswer(error, "The server function failed");
|
|
1315
|
-
headers.set("content-type", "text/plain; charset=utf-8");
|
|
1316
|
-
return { answer: new Response(message, {
|
|
1317
|
-
status,
|
|
1318
|
-
headers
|
|
1319
|
-
}) };
|
|
1320
|
-
}
|
|
1321
|
-
}
|
|
1322
|
-
/**
|
|
1323
|
-
* Calls a server function with the data of a form that the browser sent, and
|
|
1324
|
-
* sends the browser back to the page with a redirect. The response has the
|
|
1325
|
-
* headers of the event, such as cookies that the function set.
|
|
1326
|
-
*/
|
|
1327
|
-
async function handleForm(fn, request, event) {
|
|
1328
|
-
const { headers } = event;
|
|
1329
|
-
const outcome = await callWithForm(fn, request, event, headers);
|
|
1330
|
-
if ("answer" in outcome) return outcome.answer;
|
|
1331
|
-
headers.set("location", request.headers.get("referer") ?? "/");
|
|
1332
|
-
return new Response(null, {
|
|
1333
|
-
status: 303,
|
|
1334
|
-
headers
|
|
1335
|
-
});
|
|
1336
|
-
}
|
|
1337
|
-
/**
|
|
1338
|
-
* The arguments of a call. They come as seroval JSON, or as multipart form
|
|
1339
|
-
* data when they hold files: the JSON in `args`, and each file in
|
|
1340
|
-
* `file<index>`, where an `Upload` stands in the JSON.
|
|
1341
|
-
*/
|
|
1342
|
-
async function readArgs(request) {
|
|
1343
|
-
if (!request.headers.has("x-brumate-args")) return fromJSON(await request.json(), {
|
|
1344
|
-
plugins,
|
|
1345
|
-
disabledFeatures
|
|
1346
|
-
});
|
|
1347
|
-
const form = await request.formData();
|
|
1348
|
-
const args = fromJSON(JSON.parse(String(form.get("args"))), {
|
|
1349
|
-
plugins,
|
|
1350
|
-
disabledFeatures
|
|
1351
|
-
});
|
|
1352
|
-
return replaceDeep(args, (value) => value instanceof Upload ? form.get(`file${value.index}`) ?? void 0 : void 0);
|
|
1353
|
-
}
|
|
1354
|
-
/**
|
|
1355
|
-
* True when a request comes from a page of another site. Server function
|
|
1356
|
-
* calls and form posts send the cookies of the user, so another site must
|
|
1357
|
-
* not be able to make them.
|
|
1358
|
-
*
|
|
1359
|
-
* The browser sends `Origin` with every call and post. Without it, an older
|
|
1360
|
-
* browser's `Sec-Fetch-Site` decides. A request with neither does not come
|
|
1361
|
-
* from a page in a browser, so it is allowed.
|
|
1362
|
-
*/
|
|
1363
|
-
function isCrossSite(request, options = {}) {
|
|
1364
|
-
const origin = request.headers.get("origin");
|
|
1365
|
-
if (origin === null) {
|
|
1366
|
-
const site = request.headers.get("sec-fetch-site");
|
|
1367
|
-
return site === "cross-site" || site === "same-site";
|
|
1368
|
-
}
|
|
1369
|
-
if (origin === "null") return true;
|
|
1370
|
-
if (options.origins?.includes(origin)) return false;
|
|
1371
|
-
let host;
|
|
1372
|
-
try {
|
|
1373
|
-
host = new URL(origin).host;
|
|
1374
|
-
} catch {
|
|
1375
|
-
return true;
|
|
1376
|
-
}
|
|
1377
|
-
return ![
|
|
1378
|
-
new URL(request.url).host,
|
|
1379
|
-
request.headers.get("host"),
|
|
1380
|
-
request.headers.get("x-forwarded-host")
|
|
1381
|
-
].includes(host);
|
|
1382
|
-
}
|
|
1383
|
-
/**
|
|
1384
|
-
* Answers a server function call from `brumate/client`. Returns undefined
|
|
1385
|
-
* when the request is not a call, so other handlers can answer it. Server
|
|
1386
|
-
* functions read the request with `getEvent()`. A call from a page of
|
|
1387
|
-
* another site answers 403. See `isCrossSite`.
|
|
1388
|
-
*/
|
|
1389
|
-
async function handleRequest(functions, request, prefix = "/_brumate", options = {}) {
|
|
1390
|
-
const url = new URL(request.url);
|
|
1391
|
-
if (request.method !== "POST" || !url.pathname.startsWith(`${prefix}/`)) return;
|
|
1392
|
-
if (isCrossSite(request, options)) return crossSiteAnswer();
|
|
1393
|
-
const id = decodeURIComponent(url.pathname.slice(prefix.length + 1));
|
|
1394
|
-
const fn = functions[id];
|
|
1395
|
-
if (!fn) return unknownAnswer(id);
|
|
1396
|
-
const event = new RequestEvent(request);
|
|
1397
|
-
const invoke = (args) => withEvent(event, () => fn(...args));
|
|
1398
|
-
if (isFormPost(request) && !request.headers.has("x-brumate-args")) {
|
|
1399
|
-
if (!request.headers.has("x-brumate-result")) return handleForm(fn, request, event);
|
|
1400
|
-
const form = await request.formData();
|
|
1401
|
-
return answerCall(functions, event, async () => invoke([form]));
|
|
1402
|
-
}
|
|
1403
|
-
return answerCall(functions, event, async () => invoke(await readArgs(request)));
|
|
1404
|
-
}
|
|
1405
|
-
/**
|
|
1406
|
-
* Answers a server function call with its result as a stream of seroval
|
|
1407
|
-
* chunks, so promises and async iterables in it stream as they settle. A
|
|
1408
|
-
* redirect is sent as a header, so the client can follow it. An error
|
|
1409
|
-
* answers with a message that the client throws.
|
|
1410
|
-
*/
|
|
1411
|
-
async function answerCall(functions, event, run) {
|
|
1412
|
-
const { headers } = event;
|
|
1413
|
-
try {
|
|
1414
|
-
const result = await run();
|
|
1415
|
-
const { refreshed } = event;
|
|
1416
|
-
if (refreshed?.size) {
|
|
1417
|
-
const ids = Object.keys(functions).filter((key) => refreshed.has(unwrap(functions[key])));
|
|
1418
|
-
if (ids.length > 0) headers.set("x-brumate-refresh", ids.join(","));
|
|
1419
|
-
}
|
|
1420
|
-
headers.set("content-type", STREAM_TYPE);
|
|
1421
|
-
return new Response(toChunkStream(result), { headers });
|
|
1422
|
-
} catch (error) {
|
|
1423
|
-
if (error instanceof Redirect) {
|
|
1424
|
-
headers.set("x-brumate-redirect", error.location);
|
|
1425
|
-
return new Response(null, {
|
|
1426
|
-
status: 204,
|
|
1427
|
-
headers
|
|
1428
|
-
});
|
|
1429
|
-
}
|
|
1430
|
-
const { message, status } = errorAnswer(error, "The server function failed");
|
|
1431
|
-
headers.set("content-type", "application/json");
|
|
1432
|
-
return new Response(JSON.stringify({ error: message }), {
|
|
1433
|
-
status,
|
|
1434
|
-
headers
|
|
1435
|
-
});
|
|
1436
|
-
}
|
|
1437
|
-
}
|
|
1438
|
-
/** Imports every module of a matched route before it renders. */
|
|
1439
|
-
async function resolveView(view) {
|
|
1440
|
-
const [module, loading, ...slots] = await Promise.all([
|
|
1441
|
-
view.load(),
|
|
1442
|
-
view.loading?.(),
|
|
1443
|
-
...Object.values(view.slots).map(resolveView)
|
|
1444
|
-
]);
|
|
1445
|
-
const names = Object.keys(view.slots);
|
|
1446
|
-
return {
|
|
1447
|
-
key: view.key,
|
|
1448
|
-
component: module.default,
|
|
1449
|
-
loading: loading?.default,
|
|
1450
|
-
slots: Object.fromEntries(names.map((name, index) => [name, slots[index]]))
|
|
1451
|
-
};
|
|
1452
|
-
}
|
|
1453
|
-
/**
|
|
1454
|
-
* Renders a view where its layout inserts it. A view with a loading file
|
|
1455
|
-
* streams in after the rest of the page, as a `#loading` body does.
|
|
1456
|
-
*/
|
|
1457
|
-
async function renderView(view, props, ctx, scope) {
|
|
1458
|
-
if (!view.loading) return component(viewComponent(view, props), {}, ctx, scope);
|
|
1459
|
-
const id = ctx.boundary();
|
|
1460
|
-
const fallback = await component(view.loading, props, ctx, scope);
|
|
1461
|
-
ctx.defer(id, (child) => component(viewComponent(view, props), {}, child, scope));
|
|
1462
|
-
return `<!--l${id}-->${fallback}<!--/l-->`;
|
|
1463
|
-
}
|
|
1464
|
-
/**
|
|
1465
|
-
* A component that renders a route, with its slots rendering where the
|
|
1466
|
-
* layout inserts them. `props` go to every view, such as `params`.
|
|
1467
|
-
*/
|
|
1468
|
-
function viewComponent(view, props) {
|
|
1469
|
-
return (_props, ctx) => {
|
|
1470
|
-
const own = { ...props };
|
|
1471
|
-
for (const [name, slot] of Object.entries(view.slots)) own[name] = lazy(async (at, scope) => {
|
|
1472
|
-
const root = at.peek();
|
|
1473
|
-
const html = await renderView(slot, props, at, scope);
|
|
1474
|
-
return `<!--R${scope ?? -1}:${name}:${root}:${encodeURIComponent(slot.key)}-->${html}<!--/R-->`;
|
|
1475
|
-
});
|
|
1476
|
-
return view.component(own, ctx);
|
|
1477
|
-
};
|
|
1478
|
-
}
|
|
1479
|
-
/**
|
|
1480
|
-
* Runs the server function that a form without scripts posted to a page, as
|
|
1481
|
-
* `?__action=<id>`. Returns its result for `$action`, or the response that
|
|
1482
|
-
* answers the post instead of the page: a redirect, or an error.
|
|
1483
|
-
* `handleRoute` adds the cookies of the event to that response, and no other
|
|
1484
|
-
* headers of the event.
|
|
1485
|
-
*/
|
|
1486
|
-
async function runAction(request, id, options, event) {
|
|
1487
|
-
if (isCrossSite(request, options)) return { answer: crossSiteAnswer() };
|
|
1488
|
-
const fn = options.functions?.[id];
|
|
1489
|
-
if (!fn) return { answer: unknownAnswer(id) };
|
|
1490
|
-
const outcome = await callWithForm(fn, request, event, new Headers(), request.url);
|
|
1491
|
-
return "answer" in outcome ? outcome : { actions: /* @__PURE__ */ new Map([[fn, outcome.result]]) };
|
|
1492
|
-
}
|
|
1493
|
-
/** Renders the page of a route tree, streamed, with the results of a form for `$action`. */
|
|
1494
|
-
async function renderPage(view, props, request, options, extra) {
|
|
1495
|
-
const base = Number(request.headers.get("x-brumate-base"));
|
|
1496
|
-
const parts = await render(viewComponent(view, props), {}, {
|
|
1497
|
-
...options,
|
|
1498
|
-
request,
|
|
1499
|
-
actions: extra.actions,
|
|
1500
|
-
route: view.key,
|
|
1501
|
-
base: Number.isSafeInteger(base) && base > 0 ? base : void 0
|
|
1502
|
-
});
|
|
1503
|
-
const headers = new Headers(parts.headers);
|
|
1504
|
-
headers.set("content-type", "text/html; charset=utf-8");
|
|
1505
|
-
const body = streamParts(parts, options).pipeThrough(new TextEncoderStream());
|
|
1506
|
-
return new Response(body, {
|
|
1507
|
-
status: extra.status ?? parts.status,
|
|
1508
|
-
headers
|
|
1509
|
-
});
|
|
1510
|
-
}
|
|
1511
|
-
/**
|
|
1512
|
-
* Renders the first `_error.brm` that renders, from the innermost. Its
|
|
1513
|
-
* component gets `error`, with the message and the status.
|
|
1514
|
-
*/
|
|
1515
|
-
async function renderError(views, error, params, request, options) {
|
|
1516
|
-
for (const view of views) try {
|
|
1517
|
-
return await renderPage(await resolveView(view), {
|
|
1518
|
-
params,
|
|
1519
|
-
error
|
|
1520
|
-
}, request, options, { status: error.status });
|
|
1521
|
-
} catch (failure) {
|
|
1522
|
-
console.error(failure);
|
|
1523
|
-
}
|
|
1524
|
-
}
|
|
1525
|
-
/** Runs the middleware of the folders on the path, from the outside in, around the answer. */
|
|
1526
|
-
async function runMiddleware(loaders, request, event, answer) {
|
|
1527
|
-
const [first, ...rest] = loaders;
|
|
1528
|
-
if (!first) return answer();
|
|
1529
|
-
const { middleware } = await first();
|
|
1530
|
-
return withEvent(event, () => middleware(request, () => runMiddleware(rest, request, event, answer)));
|
|
1531
|
-
}
|
|
1532
|
-
/**
|
|
1533
|
-
* Answers a request with the route that matches its path, streamed:
|
|
1534
|
-
*
|
|
1535
|
-
* - The `_middleware.ts` of each folder on the path runs first, from the outside in.
|
|
1536
|
-
* - An endpoint at the path answers the methods that it exports.
|
|
1537
|
-
* - A form without scripts that posts to the page with `?__action=<id>`
|
|
1538
|
-
* runs that server function first, and the page renders with its result
|
|
1539
|
-
* for `$action`.
|
|
1540
|
-
* - A route that throws renders the nearest `_error.brm`, and a path that
|
|
1541
|
-
* no route matches renders the `_error.brm` of the root with status 404.
|
|
1542
|
-
*
|
|
1543
|
-
* Returns undefined when no route matches and the root has no error file or
|
|
1544
|
-
* middleware. A `redirect` while the page renders answers with a redirect.
|
|
1545
|
-
*/
|
|
1546
|
-
async function handleRoute(tree, request, options = {}) {
|
|
1547
|
-
const event = options.event ?? new RequestEvent(request);
|
|
1548
|
-
const answer = await routeAnswer(tree, request, {
|
|
1549
|
-
...options,
|
|
1550
|
-
event
|
|
1551
|
-
});
|
|
1552
|
-
return answer && withHeaders(answer, event.headers);
|
|
1553
|
-
}
|
|
1554
|
-
/** A response with more headers, such as cookies that middleware set. */
|
|
1555
|
-
function withHeaders(answer, headers) {
|
|
1556
|
-
const sent = new Set(answer.headers.getSetCookie());
|
|
1557
|
-
const cookies = headers.getSetCookie().filter((cookie) => !sent.has(cookie));
|
|
1558
|
-
if (cookies.length === 0) return answer;
|
|
1559
|
-
const result = new Response(answer.body, answer);
|
|
1560
|
-
for (const cookie of cookies) result.headers.append("set-cookie", cookie);
|
|
1561
|
-
return result;
|
|
1562
|
-
}
|
|
1563
|
-
async function routeAnswer(tree, request, options) {
|
|
1564
|
-
const url = new URL(request.url);
|
|
1565
|
-
const match = matchRoute(tree, url.pathname);
|
|
1566
|
-
if (!match) {
|
|
1567
|
-
const missing = notFound(tree);
|
|
1568
|
-
if (missing.errors.length === 0 && missing.middleware.length === 0) return;
|
|
1569
|
-
return runMiddleware(missing.middleware, request, options.event, async () => {
|
|
1570
|
-
return await renderError(missing.errors, {
|
|
1571
|
-
message: "Not found",
|
|
1572
|
-
status: 404
|
|
1573
|
-
}, {}, request, options) ?? new Response("Not found", { status: 404 });
|
|
1574
|
-
});
|
|
1575
|
-
}
|
|
1576
|
-
return runMiddleware(match.middleware, request, options.event, () => answerRoute(match, request, url, options));
|
|
1577
|
-
}
|
|
1578
|
-
/** Answers a request that a route matches, after its middleware. `url` is the URL of the request. */
|
|
1579
|
-
async function answerRoute(match, request, url, options) {
|
|
1580
|
-
if (match.endpoint) {
|
|
1581
|
-
const endpoint = await match.endpoint();
|
|
1582
|
-
const handler = endpoint[request.method] ?? (request.method === "HEAD" ? endpoint.GET : void 0);
|
|
1583
|
-
if (handler) return withEvent(options.event, () => handler(request, match.params));
|
|
1584
|
-
if (match.view.load === missingPage || request.method !== "GET") {
|
|
1585
|
-
const allow = Object.keys(endpoint).filter((name) => /^[A-Z]+$/.test(name));
|
|
1586
|
-
return new Response("Method not allowed", {
|
|
1587
|
-
status: 405,
|
|
1588
|
-
headers: { allow: allow.join(", ") }
|
|
1589
|
-
});
|
|
1590
|
-
}
|
|
1591
|
-
}
|
|
1592
|
-
let actions;
|
|
1593
|
-
const posted = url.searchParams.get("__action");
|
|
1594
|
-
if (request.method === "POST" && posted !== null) {
|
|
1595
|
-
const outcome = await runAction(request, posted, options, options.event);
|
|
1596
|
-
if ("answer" in outcome) return outcome.answer;
|
|
1597
|
-
actions = outcome.actions;
|
|
1598
|
-
}
|
|
1599
|
-
try {
|
|
1600
|
-
return await renderPage(await resolveView(match.view), { params: match.params }, request, options, { actions });
|
|
1601
|
-
} catch (error) {
|
|
1602
|
-
if (isRedirect(error)) return new Response(null, {
|
|
1603
|
-
status: error.status,
|
|
1604
|
-
headers: { location: new URL(error.location, url).href }
|
|
1605
|
-
});
|
|
1606
|
-
if (options.dev && !(error instanceof ServerError)) throw error;
|
|
1607
|
-
const page = await renderError(match.errors, errorAnswer(error, "Something went wrong"), match.params, request, options);
|
|
1608
|
-
if (page) return page;
|
|
1609
|
-
throw error;
|
|
1610
|
-
}
|
|
1611
|
-
}
|
|
1612
|
-
//#endregion
|
|
1613
|
-
export { dedupe as A, fieldErrors as C, matchRoute as D, safeParse as E, isRedirect as M, redirect as N, RequestEvent as O, withEvent as P, ValidationError as S, parseForm as T, renderToStream as _, component as a, streamState as b, handleRoute as c, lazy as d, memo as f, render as g, ready as h, actionResult as i, getEvent as j, ServerError as k, insert as l, read as m, NotReady as n, dynamic as o, packState as p, action as r, handleRequest as s, Context as t, isCrossSite as u, stateScript as v, parse as w, wait as x, streamParts as y };
|
|
1614
|
-
|
|
1615
|
-
//# sourceMappingURL=server-DZsgnPKS.js.map
|