@dim24/servin 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1655 -3
- package/example/index.js +43 -0
- package/example/router.js +11 -0
- package/index.js +3 -0
- package/package.json +38 -4
- package/src/server.js +793 -0
- package/src/servin.test.js +292 -0
- package/src/session.js +311 -0
- package/src/tree.js +504 -0
- package/src/utils.js +436 -0
- package/src/websocket.js +311 -0
- package/src/wire.js +254 -0
- package/test.js +45 -0
package/src/tree.js
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
const GUARD_META = Symbol('servin.guard');
|
|
2
|
+
const PARAM_META = Symbol('servin.param');
|
|
3
|
+
|
|
4
|
+
const HTTP_VERBS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
|
|
5
|
+
const META_KEYS = new Set([
|
|
6
|
+
'expect',
|
|
7
|
+
'cache',
|
|
8
|
+
'coalesce',
|
|
9
|
+
'idempotent',
|
|
10
|
+
'limit',
|
|
11
|
+
'webhook',
|
|
12
|
+
'wsConfig',
|
|
13
|
+
'priority',
|
|
14
|
+
'sunset',
|
|
15
|
+
'rawBody'
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
const AsyncGeneratorFunction = (async function* () { }).constructor;
|
|
19
|
+
|
|
20
|
+
const BUILTIN_PARAM_TYPES = {
|
|
21
|
+
int(raw) {
|
|
22
|
+
if (!/^\d+$/.test(raw)) return { ok: false };
|
|
23
|
+
const val = Number(raw);
|
|
24
|
+
if (!Number.isSafeInteger(val)) return { ok: false };
|
|
25
|
+
return { ok: true, value: val };
|
|
26
|
+
},
|
|
27
|
+
number(raw) {
|
|
28
|
+
if (!/^-?\d+(?:\.\d+)?$/.test(raw)) return { ok: false };
|
|
29
|
+
const val = Number(raw);
|
|
30
|
+
if (!Number.isFinite(val)) return { ok: false };
|
|
31
|
+
return { ok: true, value: val };
|
|
32
|
+
},
|
|
33
|
+
float(raw) {
|
|
34
|
+
return BUILTIN_PARAM_TYPES.number(raw);
|
|
35
|
+
},
|
|
36
|
+
bigint(raw) {
|
|
37
|
+
if (!/^-?\d+$/.test(raw)) return { ok: false };
|
|
38
|
+
try {
|
|
39
|
+
return { ok: true, value: BigInt(raw) };
|
|
40
|
+
} catch {
|
|
41
|
+
return { ok: false };
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
uuid(raw) {
|
|
45
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(raw)) {
|
|
46
|
+
return { ok: false };
|
|
47
|
+
}
|
|
48
|
+
return { ok: true, value: raw.toLowerCase() };
|
|
49
|
+
},
|
|
50
|
+
alpha(raw) {
|
|
51
|
+
if (!/^[a-zA-Z]+$/.test(raw)) return { ok: false };
|
|
52
|
+
return { ok: true, value: raw };
|
|
53
|
+
},
|
|
54
|
+
alnum(raw) {
|
|
55
|
+
if (!/^[a-zA-Z0-9]+$/.test(raw)) return { ok: false };
|
|
56
|
+
return { ok: true, value: raw };
|
|
57
|
+
},
|
|
58
|
+
slug(raw) {
|
|
59
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(raw)) return { ok: false };
|
|
60
|
+
return { ok: true, value: raw };
|
|
61
|
+
},
|
|
62
|
+
bool(raw) {
|
|
63
|
+
const lower = raw.toLowerCase();
|
|
64
|
+
if (lower === 'true' || lower === '1') return { ok: true, value: true };
|
|
65
|
+
if (lower === 'false' || lower === '0') return { ok: true, value: false };
|
|
66
|
+
return { ok: false };
|
|
67
|
+
},
|
|
68
|
+
boolean(raw) {
|
|
69
|
+
return BUILTIN_PARAM_TYPES.bool(raw);
|
|
70
|
+
},
|
|
71
|
+
string(raw) {
|
|
72
|
+
return { ok: true, value: raw };
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
function resolveParamParser(rule, customTypes = {}, rawSegment = '') {
|
|
77
|
+
if (rule === Number) return BUILTIN_PARAM_TYPES.number;
|
|
78
|
+
if (rule === Boolean) return BUILTIN_PARAM_TYPES.bool;
|
|
79
|
+
if (rule === BigInt) return BUILTIN_PARAM_TYPES.bigint;
|
|
80
|
+
if (rule === String) return BUILTIN_PARAM_TYPES.string;
|
|
81
|
+
|
|
82
|
+
if (rule instanceof RegExp) {
|
|
83
|
+
const rx = new RegExp(rule.source, rule.flags.replace(/[gy]/g, ''));
|
|
84
|
+
return (raw) => (rx.test(raw) ? { ok: true, value: raw } : { ok: false });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (typeof rule === 'function') {
|
|
88
|
+
return (raw) => {
|
|
89
|
+
try {
|
|
90
|
+
const parsed = rule(raw);
|
|
91
|
+
if (parsed === undefined || parsed === null || parsed === false) {
|
|
92
|
+
return { ok: false };
|
|
93
|
+
}
|
|
94
|
+
return { ok: true, value: parsed };
|
|
95
|
+
} catch {
|
|
96
|
+
return { ok: false };
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (typeof rule === 'string') {
|
|
102
|
+
if (customTypes && Object.prototype.hasOwnProperty.call(customTypes, rule)) {
|
|
103
|
+
return resolveParamParser(customTypes[rule], {}, rawSegment);
|
|
104
|
+
}
|
|
105
|
+
if (Object.prototype.hasOwnProperty.call(BUILTIN_PARAM_TYPES, rule)) {
|
|
106
|
+
return BUILTIN_PARAM_TYPES[rule];
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
throw new Error(`[servin] Invalid parameter rule "${String(rule)}" on segment "${rawSegment}"`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function attachMeta(branch, { addGuard, setParam }) {
|
|
114
|
+
const existingGuards = branch?.[GUARD_META] || [];
|
|
115
|
+
const existingParam = branch?.[PARAM_META] || null;
|
|
116
|
+
const nextGuards = addGuard ? [addGuard, ...existingGuards] : existingGuards;
|
|
117
|
+
const nextParam = setParam !== undefined ? setParam : existingParam;
|
|
118
|
+
|
|
119
|
+
let target;
|
|
120
|
+
if (typeof branch === 'function') {
|
|
121
|
+
if (branch instanceof AsyncGeneratorFunction) {
|
|
122
|
+
target = async function* (...args) {
|
|
123
|
+
return yield* branch(...args);
|
|
124
|
+
};
|
|
125
|
+
} else {
|
|
126
|
+
target = function (...args) {
|
|
127
|
+
return branch.apply(this, args);
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
} else if (branch && typeof branch === 'object') {
|
|
131
|
+
target = { ...branch };
|
|
132
|
+
} else {
|
|
133
|
+
throw new TypeError('Branch must be a route object or handler function');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (nextGuards.length > 0) {
|
|
137
|
+
Object.defineProperty(target, GUARD_META, {
|
|
138
|
+
value: nextGuards,
|
|
139
|
+
enumerable: false,
|
|
140
|
+
configurable: true
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
if (nextParam) {
|
|
144
|
+
Object.defineProperty(target, PARAM_META, {
|
|
145
|
+
value: nextParam,
|
|
146
|
+
enumerable: false,
|
|
147
|
+
configurable: true
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
return target;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function guard(policyFn, branch) {
|
|
154
|
+
if (typeof policyFn !== 'function') {
|
|
155
|
+
throw new TypeError('guard(policyFn, branch) requires a policy function');
|
|
156
|
+
}
|
|
157
|
+
return attachMeta(branch, { addGuard: policyFn });
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function param(rule, branch) {
|
|
161
|
+
if (rule === undefined || rule === null) {
|
|
162
|
+
throw new TypeError('param(rule, branch) requires a type name, constructor, RegExp, or validator function');
|
|
163
|
+
}
|
|
164
|
+
return attachMeta(branch, { setParam: rule });
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function parseVerbKey(key) {
|
|
168
|
+
if (key === 'ws') return ['WS'];
|
|
169
|
+
const parts = key.split('|').map((s) => s.trim().toUpperCase());
|
|
170
|
+
if (parts.length > 0 && parts.every((p) => HTTP_VERBS.has(p))) {
|
|
171
|
+
return parts;
|
|
172
|
+
}
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function classifySegment(seg, customTypes = {}, paramRule = null) {
|
|
177
|
+
if (seg === '$path') {
|
|
178
|
+
return { type: 'wild', priority: 3, param: 'path', parse: null, raw: seg };
|
|
179
|
+
}
|
|
180
|
+
if (seg.startsWith('$') && seg.length > 1) {
|
|
181
|
+
const paramName = seg.slice(1);
|
|
182
|
+
if (paramRule !== null && paramRule !== undefined) {
|
|
183
|
+
const parse = resolveParamParser(paramRule, customTypes, seg);
|
|
184
|
+
return { type: 'param', priority: 1, param: paramName, parse, raw: seg };
|
|
185
|
+
}
|
|
186
|
+
return { type: 'param', priority: 2, param: paramName, parse: null, raw: seg };
|
|
187
|
+
}
|
|
188
|
+
if (paramRule !== null && paramRule !== undefined) {
|
|
189
|
+
throw new Error(`[servin] param() can only be applied to dynamic "$" segments, got "${seg}"`);
|
|
190
|
+
}
|
|
191
|
+
return { type: 'static', priority: 0, value: seg, parse: null, raw: seg };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function compileDomainTree(apiRoot = {}, customTypes = {}) {
|
|
195
|
+
const routes = [];
|
|
196
|
+
let nodeCounter = 0;
|
|
197
|
+
|
|
198
|
+
function walk(node, segments, dotPath, inheritedGuards, inheritedMeta, ancestorCaches) {
|
|
199
|
+
if (!node || typeof node !== 'object') return;
|
|
200
|
+
|
|
201
|
+
const nodeId = `node_${++nodeCounter}`;
|
|
202
|
+
const guards = [...inheritedGuards, ...(node[GUARD_META] || [])];
|
|
203
|
+
const meta = { ...inheritedMeta };
|
|
204
|
+
|
|
205
|
+
for (const mk of META_KEYS) {
|
|
206
|
+
if (mk in node) meta[mk] = node[mk];
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const nodeCache = node.cache ? new Map() : null;
|
|
210
|
+
const nextAncestorCaches = nodeCache ? [...ancestorCaches, nodeCache] : ancestorCaches;
|
|
211
|
+
const nodeInFlight = meta.coalesce ? new Map() : null;
|
|
212
|
+
const nodeIdempotency = meta.idempotent ? new Map() : null;
|
|
213
|
+
|
|
214
|
+
for (const [key, value] of Object.entries(node)) {
|
|
215
|
+
if (META_KEYS.has(key)) continue;
|
|
216
|
+
|
|
217
|
+
const verbs = parseVerbKey(key);
|
|
218
|
+
if (verbs && typeof value === 'function') {
|
|
219
|
+
const paramNames = segments.filter((s) => s.type !== 'static').map((s) => s.param);
|
|
220
|
+
routes.push({
|
|
221
|
+
nodeId,
|
|
222
|
+
dotPath: [...dotPath, key].join('.'),
|
|
223
|
+
segments,
|
|
224
|
+
paramNames,
|
|
225
|
+
verbs,
|
|
226
|
+
handler: value,
|
|
227
|
+
isAsyncGen: value instanceof AsyncGeneratorFunction,
|
|
228
|
+
guards,
|
|
229
|
+
meta,
|
|
230
|
+
nodeCache,
|
|
231
|
+
ancestorCaches,
|
|
232
|
+
nodeInFlight,
|
|
233
|
+
nodeIdempotency
|
|
234
|
+
});
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const paramRule = value?.[PARAM_META] ?? null;
|
|
239
|
+
|
|
240
|
+
if (typeof value === 'function') {
|
|
241
|
+
const seg = classifySegment(key, customTypes, paramRule);
|
|
242
|
+
const childSegments = [...segments, seg];
|
|
243
|
+
const paramNames = childSegments.filter((s) => s.type !== 'static').map((s) => s.param);
|
|
244
|
+
const isAsyncGen = value instanceof AsyncGeneratorFunction;
|
|
245
|
+
const fnGuards = [...guards, ...(value[GUARD_META] || [])];
|
|
246
|
+
routes.push({
|
|
247
|
+
nodeId: `${nodeId}_${key}`,
|
|
248
|
+
dotPath: [...dotPath, key].join('.'),
|
|
249
|
+
segments: childSegments,
|
|
250
|
+
paramNames,
|
|
251
|
+
verbs: [isAsyncGen ? 'GET' : 'POST'],
|
|
252
|
+
handler: value,
|
|
253
|
+
isAsyncGen,
|
|
254
|
+
guards: fnGuards,
|
|
255
|
+
meta,
|
|
256
|
+
nodeCache: null,
|
|
257
|
+
ancestorCaches: nextAncestorCaches,
|
|
258
|
+
nodeInFlight: meta.coalesce ? new Map() : null,
|
|
259
|
+
nodeIdempotency: meta.idempotent ? new Map() : null
|
|
260
|
+
});
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
if (value && typeof value === 'object') {
|
|
265
|
+
const seg = classifySegment(key, customTypes, paramRule);
|
|
266
|
+
walk(value, [...segments, seg], [...dotPath, key], guards, meta, nextAncestorCaches);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
walk(apiRoot, [], [], [], {}, []);
|
|
272
|
+
|
|
273
|
+
routes.sort((a, b) => {
|
|
274
|
+
const minLen = Math.min(a.segments.length, b.segments.length);
|
|
275
|
+
for (let i = 0; i < minLen; i++) {
|
|
276
|
+
if (a.segments[i].priority !== b.segments[i].priority) {
|
|
277
|
+
return a.segments[i].priority - b.segments[i].priority;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return a.segments.length - b.segments.length;
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
return routes;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export function matchDomainRoute(routes, method, pathname) {
|
|
287
|
+
const clean = pathname.replace(/^\/+|\/+$/g, '');
|
|
288
|
+
const parts = clean ? clean.split('/') : [];
|
|
289
|
+
const allowedVerbs = new Set();
|
|
290
|
+
|
|
291
|
+
for (const route of routes) {
|
|
292
|
+
const params = {};
|
|
293
|
+
let matched = true;
|
|
294
|
+
|
|
295
|
+
for (let i = 0; i < route.segments.length; i++) {
|
|
296
|
+
const seg = route.segments[i];
|
|
297
|
+
if (seg.type === 'wild') {
|
|
298
|
+
params[seg.param] = parts.slice(i).map(decodeURIComponent).join('/');
|
|
299
|
+
break;
|
|
300
|
+
}
|
|
301
|
+
if (i >= parts.length) {
|
|
302
|
+
matched = false;
|
|
303
|
+
break;
|
|
304
|
+
}
|
|
305
|
+
if (seg.type === 'param') {
|
|
306
|
+
let decoded;
|
|
307
|
+
try {
|
|
308
|
+
decoded = decodeURIComponent(parts[i]);
|
|
309
|
+
} catch {
|
|
310
|
+
matched = false;
|
|
311
|
+
break;
|
|
312
|
+
}
|
|
313
|
+
if (seg.parse) {
|
|
314
|
+
const res = seg.parse(decoded);
|
|
315
|
+
if (!res.ok) {
|
|
316
|
+
matched = false;
|
|
317
|
+
break;
|
|
318
|
+
}
|
|
319
|
+
params[seg.param] = res.value;
|
|
320
|
+
} else {
|
|
321
|
+
params[seg.param] = decoded;
|
|
322
|
+
}
|
|
323
|
+
} else if (seg.value !== parts[i]) {
|
|
324
|
+
matched = false;
|
|
325
|
+
break;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const lastSeg = route.segments[route.segments.length - 1];
|
|
330
|
+
if (matched && lastSeg?.type !== 'wild' && parts.length !== route.segments.length) {
|
|
331
|
+
matched = false;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
if (matched) {
|
|
335
|
+
for (const v of route.verbs) {
|
|
336
|
+
if (v !== 'WS') allowedVerbs.add(v);
|
|
337
|
+
}
|
|
338
|
+
if (route.verbs.includes(method)) {
|
|
339
|
+
return { status: 200, route, params };
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
if (allowedVerbs.size > 0) {
|
|
345
|
+
return { status: 405, allow: [...allowedVerbs].join(', ') };
|
|
346
|
+
}
|
|
347
|
+
return { status: 404 };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
export function generateVirtualClientModule(routes) {
|
|
351
|
+
const manifest = routes.map((r) => ({
|
|
352
|
+
dotPath: r.dotPath,
|
|
353
|
+
verbs: r.verbs,
|
|
354
|
+
isAsyncGen: r.isAsyncGen
|
|
355
|
+
}));
|
|
356
|
+
|
|
357
|
+
return `// Auto-generated Zero-Build Virtual ESM Client by servin
|
|
358
|
+
const MANIFEST = ${JSON.stringify(manifest, null, 2)};
|
|
359
|
+
const ORIGIN = new URL(import.meta.url).origin;
|
|
360
|
+
|
|
361
|
+
function parseMethod(key) {
|
|
362
|
+
if (key === 'ws') return 'WS';
|
|
363
|
+
const upper = key.split('|')[0].toUpperCase();
|
|
364
|
+
const verbs = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
|
|
365
|
+
return verbs.has(upper) ? upper : null;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function createNode(chain) {
|
|
369
|
+
return new Proxy(function () {}, {
|
|
370
|
+
get(_, prop) {
|
|
371
|
+
if (typeof prop === 'symbol') return undefined;
|
|
372
|
+
return createNode([...chain, prop]);
|
|
373
|
+
},
|
|
374
|
+
apply(_, __, args) {
|
|
375
|
+
const argQueue = [...args];
|
|
376
|
+
const dotKey = chain.join('.');
|
|
377
|
+
const entry = MANIFEST.find((m) => m.dotPath === dotKey);
|
|
378
|
+
const lastKey = chain[chain.length - 1];
|
|
379
|
+
let method = parseMethod(lastKey);
|
|
380
|
+
const pathSegments = method ? chain.slice(0, -1) : [...chain];
|
|
381
|
+
|
|
382
|
+
if (!method) {
|
|
383
|
+
method = entry?.verbs?.[0] || 'POST';
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const resolvedParts = [];
|
|
387
|
+
for (const seg of pathSegments) {
|
|
388
|
+
if (seg.startsWith('$')) {
|
|
389
|
+
const val = argQueue.shift();
|
|
390
|
+
resolvedParts.push(encodeURIComponent(String(val ?? '')));
|
|
391
|
+
} else {
|
|
392
|
+
resolvedParts.push(encodeURIComponent(seg));
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const pathname = '/' + resolvedParts.join('/');
|
|
397
|
+
|
|
398
|
+
if (method === 'WS') {
|
|
399
|
+
const wsOrigin = ORIGIN.replace(/^http/, 'ws');
|
|
400
|
+
const ws = new WebSocket(wsOrigin + pathname);
|
|
401
|
+
const queue = [];
|
|
402
|
+
let notify = null;
|
|
403
|
+
let closed = false;
|
|
404
|
+
|
|
405
|
+
ws.onmessage = (ev) => {
|
|
406
|
+
let data = ev.data;
|
|
407
|
+
if (typeof data === 'string') {
|
|
408
|
+
try { data = JSON.parse(data); } catch {}
|
|
409
|
+
}
|
|
410
|
+
queue.push(data);
|
|
411
|
+
if (notify) { notify(); notify = null; }
|
|
412
|
+
};
|
|
413
|
+
ws.onclose = () => {
|
|
414
|
+
closed = true;
|
|
415
|
+
if (notify) { notify(); notify = null; }
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
return {
|
|
419
|
+
send(data) {
|
|
420
|
+
const payload = (data instanceof Uint8Array || typeof data === 'string')
|
|
421
|
+
? data
|
|
422
|
+
: JSON.stringify(data);
|
|
423
|
+
if (ws.readyState === WebSocket.OPEN) ws.send(payload);
|
|
424
|
+
else ws.addEventListener('open', () => ws.send(payload), { once: true });
|
|
425
|
+
},
|
|
426
|
+
close(code, reason) {
|
|
427
|
+
ws.close(code, reason);
|
|
428
|
+
},
|
|
429
|
+
async *[Symbol.asyncIterator]() {
|
|
430
|
+
while (!closed || queue.length > 0) {
|
|
431
|
+
if (queue.length > 0) {
|
|
432
|
+
yield queue.shift();
|
|
433
|
+
} else {
|
|
434
|
+
await new Promise((r) => { notify = r; });
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const hasBody = method === 'POST' || method === 'PUT' || method === 'PATCH';
|
|
442
|
+
const payload = hasBody ? argQueue.shift() : undefined;
|
|
443
|
+
const queryObj = argQueue.shift();
|
|
444
|
+
const url = new URL(ORIGIN + pathname);
|
|
445
|
+
|
|
446
|
+
if (queryObj && typeof queryObj === 'object') {
|
|
447
|
+
for (const [k, v] of Object.entries(queryObj)) {
|
|
448
|
+
if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
if (entry?.isAsyncGen) {
|
|
453
|
+
return (async function* () {
|
|
454
|
+
const res = await fetch(url, {
|
|
455
|
+
method,
|
|
456
|
+
headers: { Accept: 'text/event-stream' },
|
|
457
|
+
credentials: 'include'
|
|
458
|
+
});
|
|
459
|
+
if (!res.ok) throw Object.assign(new Error(await res.text()), { status: res.status });
|
|
460
|
+
const reader = res.body.getReader();
|
|
461
|
+
const decoder = new TextDecoder();
|
|
462
|
+
let buffer = '';
|
|
463
|
+
while (true) {
|
|
464
|
+
const { done, value } = await reader.read();
|
|
465
|
+
if (done) break;
|
|
466
|
+
buffer += decoder.decode(value, { stream: true });
|
|
467
|
+
const blocks = buffer.split('\\n\\n');
|
|
468
|
+
buffer = blocks.pop() || '';
|
|
469
|
+
for (const block of blocks) {
|
|
470
|
+
const line = block.split('\\n').find((l) => l.startsWith('data:'));
|
|
471
|
+
if (line) yield JSON.parse(line.slice(5).trim());
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
})();
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
return (async () => {
|
|
478
|
+
const headers = {};
|
|
479
|
+
let body;
|
|
480
|
+
if (hasBody && payload !== undefined) {
|
|
481
|
+
headers['Content-Type'] = 'application/json';
|
|
482
|
+
body = JSON.stringify(payload);
|
|
483
|
+
}
|
|
484
|
+
const res = await fetch(url, { method, headers, body, credentials: 'include' });
|
|
485
|
+
if (res.status === 204) return null;
|
|
486
|
+
const text = await res.text();
|
|
487
|
+
let data = text;
|
|
488
|
+
try { data = JSON.parse(text); } catch {}
|
|
489
|
+
if (!res.ok) {
|
|
490
|
+
throw Object.assign(new Error(data?.error || text || 'Request failed'), {
|
|
491
|
+
status: res.status,
|
|
492
|
+
data
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
return data;
|
|
496
|
+
})();
|
|
497
|
+
}
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
export const api = createNode([]);
|
|
502
|
+
export default api;
|
|
503
|
+
`;
|
|
504
|
+
}
|