@dim24/servin 0.2.2 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +805 -77
- package/index.js +1 -1
- package/package.json +1 -1
- package/src/server.js +229 -24
- package/src/servin.test.js +118 -1
- package/src/tree.js +641 -20
- package/src/utils.js +10 -0
- package/src/websocket.js +332 -6
package/src/tree.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { StaticRouteDescriptor, RedirectDescriptor } from './utils.js';
|
|
1
|
+
import { StaticRouteDescriptor, RedirectDescriptor, AliasDescriptor } from './utils.js';
|
|
2
2
|
|
|
3
3
|
const GUARD_META = Symbol('servin.guard');
|
|
4
4
|
const PARAM_META = Symbol('servin.param');
|
|
5
5
|
|
|
6
6
|
const HTTP_VERBS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
|
|
7
|
+
const ALL_ALIAS_VERBS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'WS'];
|
|
7
8
|
const META_KEYS = new Set([
|
|
8
9
|
'expect',
|
|
9
10
|
'cache',
|
|
@@ -129,7 +130,11 @@ function attachMeta(branch, { addGuard, setParam }) {
|
|
|
129
130
|
return branch.apply(this, args);
|
|
130
131
|
};
|
|
131
132
|
}
|
|
132
|
-
} else if (
|
|
133
|
+
} else if (
|
|
134
|
+
branch instanceof StaticRouteDescriptor ||
|
|
135
|
+
branch instanceof RedirectDescriptor ||
|
|
136
|
+
branch instanceof AliasDescriptor
|
|
137
|
+
) {
|
|
133
138
|
target = Object.assign(Object.create(Object.getPrototypeOf(branch)), branch);
|
|
134
139
|
} else if (branch && typeof branch === 'object') {
|
|
135
140
|
target = { ...branch };
|
|
@@ -176,6 +181,10 @@ export function redirect(target, status = 301) {
|
|
|
176
181
|
return new RedirectDescriptor(target, status);
|
|
177
182
|
}
|
|
178
183
|
|
|
184
|
+
export function alias(target, options = {}) {
|
|
185
|
+
return new AliasDescriptor(target, options);
|
|
186
|
+
}
|
|
187
|
+
|
|
179
188
|
function parseVerbKey(key) {
|
|
180
189
|
if (key === 'ws') return ['WS'];
|
|
181
190
|
const parts = key.split('|').map((s) => s.trim().toUpperCase());
|
|
@@ -202,8 +211,7 @@ function classifySegment(seg, customTypes = {}, paramRule = null) {
|
|
|
202
211
|
}
|
|
203
212
|
return { type: 'static', priority: 0, value: seg, parse: null, raw: seg };
|
|
204
213
|
}
|
|
205
|
-
|
|
206
|
-
export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig = null) {
|
|
214
|
+
export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig = null, aliasConfig = null) {
|
|
207
215
|
const routes = [];
|
|
208
216
|
let nodeCounter = 0;
|
|
209
217
|
|
|
@@ -260,6 +268,28 @@ export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig =
|
|
|
260
268
|
});
|
|
261
269
|
}
|
|
262
270
|
|
|
271
|
+
function registerAliasDescriptor(descriptor, fullSegments, dotPath, inheritedGuards, inheritedMeta, verbs = ALL_ALIAS_VERBS) {
|
|
272
|
+
const paramNames = fullSegments.filter((s) => s.type !== 'static').map((s) => s.param);
|
|
273
|
+
const descGuards = [...inheritedGuards, ...(descriptor[GUARD_META] || [])];
|
|
274
|
+
|
|
275
|
+
routes.push({
|
|
276
|
+
nodeId: `alias_${++nodeCounter}`,
|
|
277
|
+
dotPath: dotPath.join('.'),
|
|
278
|
+
segments: fullSegments,
|
|
279
|
+
paramNames,
|
|
280
|
+
verbs,
|
|
281
|
+
aliasDescriptor: descriptor,
|
|
282
|
+
handler: null,
|
|
283
|
+
isAsyncGen: false,
|
|
284
|
+
guards: descGuards,
|
|
285
|
+
meta: inheritedMeta,
|
|
286
|
+
nodeCache: null,
|
|
287
|
+
ancestorCaches: [],
|
|
288
|
+
nodeInFlight: null,
|
|
289
|
+
nodeIdempotency: null
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
|
|
263
293
|
function walk(node, segments, dotPath, inheritedGuards, inheritedMeta, ancestorCaches) {
|
|
264
294
|
if (!node || typeof node !== 'object') return;
|
|
265
295
|
|
|
@@ -283,12 +313,38 @@ export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig =
|
|
|
283
313
|
for (const [key, value] of Object.entries(node)) {
|
|
284
314
|
if (META_KEYS.has(key)) continue;
|
|
285
315
|
|
|
316
|
+
if (key === 'ws' && value && typeof value === 'object') {
|
|
317
|
+
const paramNames = segments.filter((s) => s.type !== 'static').map((s) => s.param);
|
|
318
|
+
const wsMeta = { ...meta, wsConfig: value };
|
|
319
|
+
routes.push({
|
|
320
|
+
nodeId: `${nodeId}_ws`,
|
|
321
|
+
dotPath: [...dotPath, key].join('.'),
|
|
322
|
+
segments,
|
|
323
|
+
paramNames,
|
|
324
|
+
verbs: ['WS'],
|
|
325
|
+
handler: typeof value.handler === 'function' ? value.handler : null,
|
|
326
|
+
isAsyncGen: false,
|
|
327
|
+
guards,
|
|
328
|
+
meta: wsMeta,
|
|
329
|
+
nodeCache: null,
|
|
330
|
+
ancestorCaches,
|
|
331
|
+
nodeInFlight: null,
|
|
332
|
+
nodeIdempotency: null
|
|
333
|
+
});
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
|
|
286
337
|
const verbs = parseVerbKey(key);
|
|
287
338
|
if (verbs && value instanceof RedirectDescriptor) {
|
|
288
339
|
registerRedirectDescriptor(value, segments, [...dotPath, key], guards, meta, verbs);
|
|
289
340
|
continue;
|
|
290
341
|
}
|
|
291
342
|
|
|
343
|
+
if (verbs && value instanceof AliasDescriptor) {
|
|
344
|
+
registerAliasDescriptor(value, segments, [...dotPath, key], guards, meta, verbs);
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
|
|
292
348
|
if (verbs && typeof value === 'function') {
|
|
293
349
|
const paramNames = segments.filter((s) => s.type !== 'static').map((s) => s.param);
|
|
294
350
|
routes.push({
|
|
@@ -350,6 +406,12 @@ export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig =
|
|
|
350
406
|
continue;
|
|
351
407
|
}
|
|
352
408
|
|
|
409
|
+
if (value instanceof AliasDescriptor) {
|
|
410
|
+
const seg = classifySegment(key, customTypes, paramRule);
|
|
411
|
+
registerAliasDescriptor(value, [...segments, seg], [...dotPath, key], guards, meta);
|
|
412
|
+
continue;
|
|
413
|
+
}
|
|
414
|
+
|
|
353
415
|
if (typeof value === 'function') {
|
|
354
416
|
const seg = classifySegment(key, customTypes, paramRule);
|
|
355
417
|
const childSegments = [...segments, seg];
|
|
@@ -403,6 +465,25 @@ export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig =
|
|
|
403
465
|
}
|
|
404
466
|
}
|
|
405
467
|
|
|
468
|
+
if (aliasConfig && typeof aliasConfig === 'object') {
|
|
469
|
+
for (const [sourcePath, target] of Object.entries(aliasConfig)) {
|
|
470
|
+
const desc = target instanceof AliasDescriptor
|
|
471
|
+
? target
|
|
472
|
+
: new AliasDescriptor(target);
|
|
473
|
+
const cleanPrefix = sourcePath.replace(/^\/+|\/+$/g, '');
|
|
474
|
+
const prefixSegs = cleanPrefix
|
|
475
|
+
? cleanPrefix.split('/').map((s) => classifySegment(s, customTypes))
|
|
476
|
+
: [];
|
|
477
|
+
registerAliasDescriptor(
|
|
478
|
+
desc,
|
|
479
|
+
prefixSegs,
|
|
480
|
+
['alias', ...prefixSegs.map((s) => s.raw)],
|
|
481
|
+
[],
|
|
482
|
+
{}
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
406
487
|
routes.sort((a, b) => {
|
|
407
488
|
const minLen = Math.min(a.segments.length, b.segments.length);
|
|
408
489
|
for (let i = 0; i < minLen; i++) {
|
|
@@ -498,9 +579,366 @@ export function matchDomainRoute(routes, method, pathname) {
|
|
|
498
579
|
return { status: 404 };
|
|
499
580
|
}
|
|
500
581
|
|
|
582
|
+
// export function generateVirtualClientModule(routes) {
|
|
583
|
+
// const manifest = routes
|
|
584
|
+
// .filter((r) => !r.staticDescriptor && !r.redirectDescriptor)
|
|
585
|
+
// .map((r) => ({
|
|
586
|
+
// dotPath: r.dotPath,
|
|
587
|
+
// verbs: r.verbs,
|
|
588
|
+
// isAsyncGen: r.isAsyncGen
|
|
589
|
+
// }));
|
|
590
|
+
|
|
591
|
+
// return `// Auto-generated Zero-Build Virtual ESM Client by servin
|
|
592
|
+
// const MANIFEST = ${JSON.stringify(manifest, null, 2)};
|
|
593
|
+
// const ORIGIN = new URL(import.meta.url).origin;
|
|
594
|
+
// const HTTP_VERBS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
|
|
595
|
+
|
|
596
|
+
// function parseMethod(key) {
|
|
597
|
+
// if (key === 'ws') return 'WS';
|
|
598
|
+
// const upper = key.split('|')[0].toUpperCase();
|
|
599
|
+
// return HTTP_VERBS.has(upper) ? upper : null;
|
|
600
|
+
// }
|
|
601
|
+
|
|
602
|
+
// function isOptionsBag(arg) {
|
|
603
|
+
// return Boolean(
|
|
604
|
+
// arg &&
|
|
605
|
+
// typeof arg === 'object' &&
|
|
606
|
+
// !Array.isArray(arg) &&
|
|
607
|
+
// !(arg instanceof FormData) &&
|
|
608
|
+
// !(arg instanceof URLSearchParams) &&
|
|
609
|
+
// !(arg instanceof Blob) &&
|
|
610
|
+
// Object.prototype.hasOwnProperty.call(arg, 'headers')
|
|
611
|
+
// );
|
|
612
|
+
// }
|
|
613
|
+
|
|
614
|
+
// function createNode(chain) {
|
|
615
|
+
// return new Proxy(function () {}, {
|
|
616
|
+
// get(_, prop) {
|
|
617
|
+
// if (typeof prop === 'symbol') return undefined;
|
|
618
|
+
// return createNode([...chain, prop]);
|
|
619
|
+
// },
|
|
620
|
+
// apply(_, __, args) {
|
|
621
|
+
// const argQueue = [...args];
|
|
622
|
+
// const dotKey = chain.join('.');
|
|
623
|
+
// const entry = MANIFEST.find((m) => m.dotPath === dotKey);
|
|
624
|
+
// const lastKey = chain[chain.length - 1];
|
|
625
|
+
// let method = parseMethod(lastKey);
|
|
626
|
+
// const pathSegments = method ? chain.slice(0, -1) : [...chain];
|
|
627
|
+
|
|
628
|
+
// if (!method) {
|
|
629
|
+
// method = entry?.verbs?.[0] || 'POST';
|
|
630
|
+
// }
|
|
631
|
+
|
|
632
|
+
// const resolvedParts = [];
|
|
633
|
+
// for (const seg of pathSegments) {
|
|
634
|
+
// if (seg.startsWith('$')) {
|
|
635
|
+
// const val = argQueue.shift();
|
|
636
|
+
// resolvedParts.push(encodeURIComponent(String(val ?? '')));
|
|
637
|
+
// } else {
|
|
638
|
+
// resolvedParts.push(encodeURIComponent(seg));
|
|
639
|
+
// }
|
|
640
|
+
// }
|
|
641
|
+
|
|
642
|
+
// const pathname = '/' + resolvedParts.join('/');
|
|
643
|
+
|
|
644
|
+
// if (method === 'WS') {
|
|
645
|
+
// const wsOrigin = ORIGIN.replace(/^http/, 'ws');
|
|
646
|
+
// const firstArg = argQueue.shift();
|
|
647
|
+
// let connData = (firstArg && typeof firstArg === 'object' && !Array.isArray(firstArg))
|
|
648
|
+
// ? { ...firstArg }
|
|
649
|
+
// : {};
|
|
650
|
+
|
|
651
|
+
// let socket = null;
|
|
652
|
+
// let manualClose = false;
|
|
653
|
+
// let hasConnectedOnce = false;
|
|
654
|
+
// let lastSeq = 0;
|
|
655
|
+
// let currentState = null;
|
|
656
|
+
|
|
657
|
+
// const queue = [];
|
|
658
|
+
// let notify = null;
|
|
659
|
+
// let closed = false;
|
|
660
|
+
|
|
661
|
+
// const listeners = {
|
|
662
|
+
// open: new Set(),
|
|
663
|
+
// close: new Set(),
|
|
664
|
+
// error: new Set(),
|
|
665
|
+
// event: new Set(),
|
|
666
|
+
// broadcast: new Set()
|
|
667
|
+
// };
|
|
668
|
+
// const syncCallbacks = new Set();
|
|
669
|
+
|
|
670
|
+
// const emitLocal = (type, detail) => {
|
|
671
|
+
// const set = listeners[type];
|
|
672
|
+
// if (!set) return;
|
|
673
|
+
// for (const fn of set) fn(detail);
|
|
674
|
+
// };
|
|
675
|
+
|
|
676
|
+
// const notifySync = (meta) => {
|
|
677
|
+
// for (const fn of syncCallbacks) {
|
|
678
|
+
// fn(currentState, meta);
|
|
679
|
+
// }
|
|
680
|
+
// };
|
|
681
|
+
|
|
682
|
+
// const buildWsUrl = () => {
|
|
683
|
+
// const u = new URL(wsOrigin + pathname);
|
|
684
|
+
// for (const [k, v] of Object.entries(connData)) {
|
|
685
|
+
// if (v !== undefined && v !== null) {
|
|
686
|
+
// u.searchParams.set(k, String(v));
|
|
687
|
+
// }
|
|
688
|
+
// }
|
|
689
|
+
// if (lastSeq > 0) {
|
|
690
|
+
// u.searchParams.set('__lastSeq', String(lastSeq));
|
|
691
|
+
// }
|
|
692
|
+
// return u.toString();
|
|
693
|
+
// };
|
|
694
|
+
|
|
695
|
+
// const connect = () => {
|
|
696
|
+
// if (socket && socket.readyState <= WebSocket.OPEN) {
|
|
697
|
+
// socket.close(1000, 'refresh');
|
|
698
|
+
// }
|
|
699
|
+
// manualClose = false;
|
|
700
|
+
// closed = false;
|
|
701
|
+
|
|
702
|
+
// const ws = new WebSocket(buildWsUrl());
|
|
703
|
+
// socket = ws;
|
|
704
|
+
|
|
705
|
+
// ws.addEventListener('open', () => {
|
|
706
|
+
// const reconnected = hasConnectedOnce;
|
|
707
|
+
// hasConnectedOnce = true;
|
|
708
|
+
// emitLocal('open', { reconnected });
|
|
709
|
+
// });
|
|
710
|
+
|
|
711
|
+
// ws.addEventListener('message', (ev) => {
|
|
712
|
+
// let data = ev.data;
|
|
713
|
+
// if (typeof data === 'string') {
|
|
714
|
+
// try { data = JSON.parse(data); } catch {}
|
|
715
|
+
// }
|
|
716
|
+
|
|
717
|
+
// if (data && typeof data === 'object') {
|
|
718
|
+
// if (data.type === 'sync_snapshot') {
|
|
719
|
+
// currentState = data.state;
|
|
720
|
+
// if (typeof data.seq === 'number') lastSeq = data.seq;
|
|
721
|
+
// notifySync({
|
|
722
|
+
// seq: data.seq,
|
|
723
|
+
// room: data.room,
|
|
724
|
+
// fullSnapshot: true,
|
|
725
|
+
// replayed: false
|
|
726
|
+
// });
|
|
727
|
+
// return;
|
|
728
|
+
// }
|
|
729
|
+
// if (data.type === 'sync_patch') {
|
|
730
|
+
// currentState = data.state;
|
|
731
|
+
// if (typeof data.seq === 'number') lastSeq = data.seq;
|
|
732
|
+
// notifySync({
|
|
733
|
+
// seq: data.seq,
|
|
734
|
+
// room: data.room,
|
|
735
|
+
// meta: data.meta,
|
|
736
|
+
// fullSnapshot: false,
|
|
737
|
+
// replayed: Boolean(data.replayed)
|
|
738
|
+
// });
|
|
739
|
+
// return;
|
|
740
|
+
// }
|
|
741
|
+
// if (data.type === 'error') {
|
|
742
|
+
// emitLocal('error', data);
|
|
743
|
+
// return;
|
|
744
|
+
// }
|
|
745
|
+
// if (data.type === 'broadcast') {
|
|
746
|
+
// emitLocal('broadcast', data);
|
|
747
|
+
// return;
|
|
748
|
+
// }
|
|
749
|
+
// if (data.type === 'event') {
|
|
750
|
+
// emitLocal('event', data.payload);
|
|
751
|
+
// return;
|
|
752
|
+
// }
|
|
753
|
+
// }
|
|
754
|
+
|
|
755
|
+
// queue.push(data);
|
|
756
|
+
// if (notify) { notify(); notify = null; }
|
|
757
|
+
// });
|
|
758
|
+
|
|
759
|
+
// ws.addEventListener('close', (ev) => {
|
|
760
|
+
// closed = true;
|
|
761
|
+
// emitLocal('close', { code: ev.code, reason: ev.reason, manual: manualClose });
|
|
762
|
+
// if (notify) { notify(); notify = null; }
|
|
763
|
+
// if (!manualClose) {
|
|
764
|
+
// setTimeout(() => connect(), 1000);
|
|
765
|
+
// }
|
|
766
|
+
// });
|
|
767
|
+
|
|
768
|
+
// ws.addEventListener('error', () => {
|
|
769
|
+
// emitLocal('error', { message: 'WEBSOCKET_ERROR' });
|
|
770
|
+
// });
|
|
771
|
+
// };
|
|
772
|
+
|
|
773
|
+
// connect();
|
|
774
|
+
|
|
775
|
+
// const clientWs = {
|
|
776
|
+
// on(event, cb) {
|
|
777
|
+
// if (listeners[event]) listeners[event].add(cb);
|
|
778
|
+
// return clientWs;
|
|
779
|
+
// },
|
|
780
|
+
// off(event, cb) {
|
|
781
|
+
// if (listeners[event]) listeners[event].delete(cb);
|
|
782
|
+
// return clientWs;
|
|
783
|
+
// },
|
|
784
|
+
// sync(cb) {
|
|
785
|
+
// syncCallbacks.add(cb);
|
|
786
|
+
// if (currentState !== null) {
|
|
787
|
+
// cb(currentState, { seq: lastSeq, fullSnapshot: true, replayed: false });
|
|
788
|
+
// }
|
|
789
|
+
// return clientWs;
|
|
790
|
+
// },
|
|
791
|
+
// emit(name, payload = {}) {
|
|
792
|
+
// if (socket && socket.readyState === WebSocket.OPEN) {
|
|
793
|
+
// socket.send(JSON.stringify({ type: 'action', name, payload }));
|
|
794
|
+
// }
|
|
795
|
+
// return clientWs;
|
|
796
|
+
// },
|
|
797
|
+
// refresh(nextData = null) {
|
|
798
|
+
// if (nextData && typeof nextData === 'object') {
|
|
799
|
+
// connData = { ...connData, ...nextData };
|
|
800
|
+
// }
|
|
801
|
+
// lastSeq = 0;
|
|
802
|
+
// manualClose = true;
|
|
803
|
+
// connect();
|
|
804
|
+
// return clientWs;
|
|
805
|
+
// },
|
|
806
|
+
// resync(room = null) {
|
|
807
|
+
// if (socket && socket.readyState === WebSocket.OPEN) {
|
|
808
|
+
// socket.send(JSON.stringify({ type: 'resync', room }));
|
|
809
|
+
// }
|
|
810
|
+
// return clientWs;
|
|
811
|
+
// },
|
|
812
|
+
// send(data) {
|
|
813
|
+
// const payload = (data instanceof Uint8Array || typeof data === 'string')
|
|
814
|
+
// ? data
|
|
815
|
+
// : JSON.stringify(data);
|
|
816
|
+
// if (socket && socket.readyState === WebSocket.OPEN) {
|
|
817
|
+
// socket.send(payload);
|
|
818
|
+
// } else if (socket) {
|
|
819
|
+
// socket.addEventListener('open', () => socket.send(payload), { once: true });
|
|
820
|
+
// }
|
|
821
|
+
// },
|
|
822
|
+
// close(code = 1000, reason = '') {
|
|
823
|
+
// console.log({code,reason})
|
|
824
|
+
// manualClose = true;
|
|
825
|
+
// if (socket) socket.close(code, reason);
|
|
826
|
+
// },
|
|
827
|
+
// async *[Symbol.asyncIterator]() {
|
|
828
|
+
// while (!closed || queue.length > 0) {
|
|
829
|
+
// if (queue.length > 0) {
|
|
830
|
+
// yield queue.shift();
|
|
831
|
+
// } else {
|
|
832
|
+
// await new Promise((r) => { notify = r; });
|
|
833
|
+
// }
|
|
834
|
+
// }
|
|
835
|
+
// }
|
|
836
|
+
// };
|
|
837
|
+
|
|
838
|
+
// return clientWs;
|
|
839
|
+
// }
|
|
840
|
+
|
|
841
|
+
// let customHeaders = {};
|
|
842
|
+
// let payload;
|
|
843
|
+
// let queryObj;
|
|
844
|
+
|
|
845
|
+
// const hasBody = method === 'POST' || method === 'PUT' || method === 'PATCH';
|
|
846
|
+
|
|
847
|
+
// if (hasBody) {
|
|
848
|
+
// const first = argQueue.shift();
|
|
849
|
+
// if (isOptionsBag(first)) {
|
|
850
|
+
// customHeaders = { ...first.headers };
|
|
851
|
+
// payload = first.body !== undefined ? first.body : argQueue.shift();
|
|
852
|
+
// queryObj = first.query !== undefined ? first.query : argQueue.shift();
|
|
853
|
+
// } else {
|
|
854
|
+
// payload = first;
|
|
855
|
+
// const second = argQueue.shift();
|
|
856
|
+
// if (isOptionsBag(second)) {
|
|
857
|
+
// customHeaders = { ...second.headers };
|
|
858
|
+
// queryObj = second.query !== undefined ? second.query : argQueue.shift();
|
|
859
|
+
// } else {
|
|
860
|
+
// queryObj = second;
|
|
861
|
+
// }
|
|
862
|
+
// }
|
|
863
|
+
// } else {
|
|
864
|
+
// const first = argQueue.shift();
|
|
865
|
+
// if (isOptionsBag(first)) {
|
|
866
|
+
// customHeaders = { ...first.headers };
|
|
867
|
+
// queryObj = first.query !== undefined ? first.query : argQueue.shift();
|
|
868
|
+
// } else {
|
|
869
|
+
// queryObj = first;
|
|
870
|
+
// const second = argQueue.shift();
|
|
871
|
+
// if (isOptionsBag(second)) {
|
|
872
|
+
// customHeaders = { ...second.headers };
|
|
873
|
+
// }
|
|
874
|
+
// }
|
|
875
|
+
// }
|
|
876
|
+
|
|
877
|
+
// const url = new URL(ORIGIN + pathname);
|
|
878
|
+
// if (queryObj && typeof queryObj === 'object') {
|
|
879
|
+
// for (const [k, v] of Object.entries(queryObj)) {
|
|
880
|
+
// if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
|
|
881
|
+
// }
|
|
882
|
+
// }
|
|
883
|
+
|
|
884
|
+
// if (entry?.isAsyncGen) {
|
|
885
|
+
// return (async function* () {
|
|
886
|
+
// const res = await fetch(url, {
|
|
887
|
+
// method,
|
|
888
|
+
// headers: { Accept: 'text/event-stream', ...customHeaders },
|
|
889
|
+
// credentials: 'include'
|
|
890
|
+
// });
|
|
891
|
+
// if (!res.ok) throw Object.assign(new Error(await res.text()), { status: res.status });
|
|
892
|
+
// const reader = res.body.getReader();
|
|
893
|
+
// const decoder = new TextDecoder();
|
|
894
|
+
// let buffer = '';
|
|
895
|
+
// while (true) {
|
|
896
|
+
// const { done, value } = await reader.read();
|
|
897
|
+
// if (done) break;
|
|
898
|
+
// buffer += decoder.decode(value, { stream: true });
|
|
899
|
+
// const blocks = buffer.split('\\n\\n');
|
|
900
|
+
// buffer = blocks.pop() || '';
|
|
901
|
+
// for (const block of blocks) {
|
|
902
|
+
// const line = block.split('\\n').find((l) => l.startsWith('data:'));
|
|
903
|
+
// if (line) yield JSON.parse(line.slice(5).trim());
|
|
904
|
+
// }
|
|
905
|
+
// }
|
|
906
|
+
// })();
|
|
907
|
+
// }
|
|
908
|
+
|
|
909
|
+
// return (async () => {
|
|
910
|
+
// const headers = { ...customHeaders };
|
|
911
|
+
// let body;
|
|
912
|
+
// if (hasBody && payload !== undefined) {
|
|
913
|
+
// if (!Object.keys(headers).some((k) => k.toLowerCase() === 'content-type')) {
|
|
914
|
+
// headers['Content-Type'] = 'application/json';
|
|
915
|
+
// }
|
|
916
|
+
// body = typeof payload === 'string' ? payload : JSON.stringify(payload);
|
|
917
|
+
// }
|
|
918
|
+
// const res = await fetch(url, { method, headers, body, credentials: 'include' });
|
|
919
|
+
// if (res.status === 204) return null;
|
|
920
|
+
// const text = await res.text();
|
|
921
|
+
// let data = text;
|
|
922
|
+
// try { data = JSON.parse(text); } catch {}
|
|
923
|
+
// if (!res.ok) {
|
|
924
|
+
// throw Object.assign(new Error(data?.error || text || 'Request failed'), {
|
|
925
|
+
// status: res.status,
|
|
926
|
+
// data
|
|
927
|
+
// });
|
|
928
|
+
// }
|
|
929
|
+
// return data;
|
|
930
|
+
// })();
|
|
931
|
+
// }
|
|
932
|
+
// });
|
|
933
|
+
// }
|
|
934
|
+
|
|
935
|
+
// export const api = createNode([]);
|
|
936
|
+
// export default api;`;
|
|
937
|
+
// }
|
|
938
|
+
|
|
501
939
|
export function generateVirtualClientModule(routes) {
|
|
502
940
|
const manifest = routes
|
|
503
|
-
.filter((r) => !r.staticDescriptor && !r.redirectDescriptor)
|
|
941
|
+
.filter((r) => !r.staticDescriptor && !r.redirectDescriptor && !r.aliasDescriptor)
|
|
504
942
|
.map((r) => ({
|
|
505
943
|
dotPath: r.dotPath,
|
|
506
944
|
verbs: r.verbs,
|
|
@@ -562,34 +1000,215 @@ function createNode(chain) {
|
|
|
562
1000
|
|
|
563
1001
|
if (method === 'WS') {
|
|
564
1002
|
const wsOrigin = ORIGIN.replace(/^http/, 'ws');
|
|
565
|
-
const
|
|
1003
|
+
const firstArg = argQueue.shift();
|
|
1004
|
+
let connData = (firstArg && typeof firstArg === 'object' && !Array.isArray(firstArg))
|
|
1005
|
+
? { ...firstArg }
|
|
1006
|
+
: {};
|
|
1007
|
+
|
|
1008
|
+
let activeRoom = connData.room ? String(connData.room) : null;
|
|
1009
|
+
let socket = null;
|
|
1010
|
+
let manualClose = false;
|
|
1011
|
+
let hasConnectedOnce = false;
|
|
1012
|
+
let lastSeq = 0;
|
|
1013
|
+
let currentState = null;
|
|
1014
|
+
|
|
566
1015
|
const queue = [];
|
|
567
1016
|
let notify = null;
|
|
568
1017
|
let closed = false;
|
|
569
1018
|
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
1019
|
+
const listeners = {
|
|
1020
|
+
open: new Set(),
|
|
1021
|
+
close: new Set(),
|
|
1022
|
+
error: new Set(),
|
|
1023
|
+
event: new Set(),
|
|
1024
|
+
broadcast: new Set()
|
|
1025
|
+
};
|
|
1026
|
+
const syncCallbacks = new Set();
|
|
1027
|
+
|
|
1028
|
+
const emitLocal = (type, detail) => {
|
|
1029
|
+
const set = listeners[type];
|
|
1030
|
+
if (!set) return;
|
|
1031
|
+
for (const fn of set) fn(detail);
|
|
1032
|
+
};
|
|
1033
|
+
|
|
1034
|
+
const notifySync = (meta) => {
|
|
1035
|
+
for (const fn of syncCallbacks) {
|
|
1036
|
+
fn(currentState, meta);
|
|
1037
|
+
}
|
|
1038
|
+
};
|
|
1039
|
+
|
|
1040
|
+
const buildWsUrl = () => {
|
|
1041
|
+
const u = new URL(wsOrigin + pathname);
|
|
1042
|
+
for (const [k, v] of Object.entries(connData)) {
|
|
1043
|
+
if (v !== undefined && v !== null) {
|
|
1044
|
+
u.searchParams.set(k, String(v));
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
if (lastSeq > 0) {
|
|
1048
|
+
u.searchParams.set('__lastSeq', String(lastSeq));
|
|
574
1049
|
}
|
|
575
|
-
|
|
576
|
-
if (notify) { notify(); notify = null; }
|
|
1050
|
+
return u.toString();
|
|
577
1051
|
};
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
if (
|
|
1052
|
+
|
|
1053
|
+
const isAllowedRoom = (msgRoom) => {
|
|
1054
|
+
if (!activeRoom) return true;
|
|
1055
|
+
return Boolean(msgRoom) && String(msgRoom) === activeRoom;
|
|
581
1056
|
};
|
|
582
1057
|
|
|
583
|
-
|
|
1058
|
+
const connect = () => {
|
|
1059
|
+
if (socket && socket.readyState <= WebSocket.OPEN) {
|
|
1060
|
+
socket.close(1000, 'refresh');
|
|
1061
|
+
}
|
|
1062
|
+
manualClose = false;
|
|
1063
|
+
closed = false;
|
|
1064
|
+
|
|
1065
|
+
const ws = new WebSocket(buildWsUrl());
|
|
1066
|
+
socket = ws;
|
|
1067
|
+
|
|
1068
|
+
ws.addEventListener('open', () => {
|
|
1069
|
+
const reconnected = hasConnectedOnce;
|
|
1070
|
+
hasConnectedOnce = true;
|
|
1071
|
+
emitLocal('open', { reconnected });
|
|
1072
|
+
});
|
|
1073
|
+
|
|
1074
|
+
ws.addEventListener('message', (ev) => {
|
|
1075
|
+
let data = ev.data;
|
|
1076
|
+
if (typeof data === 'string') {
|
|
1077
|
+
try { data = JSON.parse(data); } catch {}
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
if (data && typeof data === 'object') {
|
|
1081
|
+
if (data.type === 'sync_snapshot') {
|
|
1082
|
+
if (!isAllowedRoom(data.room)) return;
|
|
1083
|
+
currentState = data.state;
|
|
1084
|
+
if (typeof data.seq === 'number') lastSeq = data.seq;
|
|
1085
|
+
notifySync({
|
|
1086
|
+
seq: data.seq,
|
|
1087
|
+
room: data.room,
|
|
1088
|
+
fullSnapshot: true,
|
|
1089
|
+
replayed: false
|
|
1090
|
+
});
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
if (data.type === 'sync_patch') {
|
|
1094
|
+
if (!isAllowedRoom(data.room)) return;
|
|
1095
|
+
currentState = data.state;
|
|
1096
|
+
if (typeof data.seq === 'number') lastSeq = data.seq;
|
|
1097
|
+
notifySync({
|
|
1098
|
+
seq: data.seq,
|
|
1099
|
+
room: data.room,
|
|
1100
|
+
meta: data.meta,
|
|
1101
|
+
fullSnapshot: false,
|
|
1102
|
+
replayed: Boolean(data.replayed)
|
|
1103
|
+
});
|
|
1104
|
+
return;
|
|
1105
|
+
}
|
|
1106
|
+
if (data.type === 'error') {
|
|
1107
|
+
emitLocal('error', data);
|
|
1108
|
+
return;
|
|
1109
|
+
}
|
|
1110
|
+
if (data.type === 'broadcast') {
|
|
1111
|
+
if (!data.global && !isAllowedRoom(data.room)) return;
|
|
1112
|
+
emitLocal('broadcast', data);
|
|
1113
|
+
return;
|
|
1114
|
+
}
|
|
1115
|
+
if (data.type === 'event') {
|
|
1116
|
+
emitLocal('event', data.payload);
|
|
1117
|
+
return;
|
|
1118
|
+
}
|
|
1119
|
+
if (typeof data.event === 'string' && listeners[data.event]) {
|
|
1120
|
+
emitLocal(data.event, data.data !== undefined ? data.data : data);
|
|
1121
|
+
return;
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
queue.push(data);
|
|
1126
|
+
if (notify) { notify(); notify = null; }
|
|
1127
|
+
});
|
|
1128
|
+
|
|
1129
|
+
ws.addEventListener('close', (ev) => {
|
|
1130
|
+
closed = true;
|
|
1131
|
+
emitLocal('close', { code: ev.code, reason: ev.reason, manual: manualClose });
|
|
1132
|
+
if (notify) { notify(); notify = null; }
|
|
1133
|
+
if (!manualClose) {
|
|
1134
|
+
setTimeout(() => connect(), 1000);
|
|
1135
|
+
}
|
|
1136
|
+
});
|
|
1137
|
+
|
|
1138
|
+
ws.addEventListener('error', () => {
|
|
1139
|
+
emitLocal('error', { message: 'WEBSOCKET_ERROR' });
|
|
1140
|
+
});
|
|
1141
|
+
};
|
|
1142
|
+
|
|
1143
|
+
connect();
|
|
1144
|
+
|
|
1145
|
+
const clientWs = {
|
|
1146
|
+
on(event, cb) {
|
|
1147
|
+
if (!listeners[event]) listeners[event] = new Set();
|
|
1148
|
+
listeners[event].add(cb);
|
|
1149
|
+
return clientWs;
|
|
1150
|
+
},
|
|
1151
|
+
off(event, cb) {
|
|
1152
|
+
if (listeners[event]) listeners[event].delete(cb);
|
|
1153
|
+
return clientWs;
|
|
1154
|
+
},
|
|
1155
|
+
sync(cb) {
|
|
1156
|
+
syncCallbacks.add(cb);
|
|
1157
|
+
if (currentState !== null) {
|
|
1158
|
+
cb(currentState, {
|
|
1159
|
+
seq: lastSeq,
|
|
1160
|
+
room: activeRoom,
|
|
1161
|
+
fullSnapshot: true,
|
|
1162
|
+
replayed: false
|
|
1163
|
+
});
|
|
1164
|
+
}
|
|
1165
|
+
return clientWs;
|
|
1166
|
+
},
|
|
1167
|
+
emit(name, payload = {}) {
|
|
1168
|
+
if (socket && socket.readyState === WebSocket.OPEN) {
|
|
1169
|
+
socket.send(JSON.stringify({ type: 'action', name, payload }));
|
|
1170
|
+
}
|
|
1171
|
+
return clientWs;
|
|
1172
|
+
},
|
|
1173
|
+
refresh(nextData = null) {
|
|
1174
|
+
if (nextData && typeof nextData === 'object') {
|
|
1175
|
+
connData = { ...connData, ...nextData };
|
|
1176
|
+
if (nextData.room !== undefined) {
|
|
1177
|
+
activeRoom = nextData.room ? String(nextData.room) : null;
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
currentState = null;
|
|
1181
|
+
lastSeq = 0;
|
|
1182
|
+
manualClose = true;
|
|
1183
|
+
connect();
|
|
1184
|
+
return clientWs;
|
|
1185
|
+
},
|
|
1186
|
+
resync(room = null) {
|
|
1187
|
+
if (room !== null && room !== undefined) {
|
|
1188
|
+
activeRoom = String(room);
|
|
1189
|
+
connData.room = activeRoom;
|
|
1190
|
+
currentState = null;
|
|
1191
|
+
lastSeq = 0;
|
|
1192
|
+
}
|
|
1193
|
+
if (socket && socket.readyState === WebSocket.OPEN) {
|
|
1194
|
+
socket.send(JSON.stringify({ type: 'resync', room: room ?? activeRoom }));
|
|
1195
|
+
}
|
|
1196
|
+
return clientWs;
|
|
1197
|
+
},
|
|
584
1198
|
send(data) {
|
|
585
1199
|
const payload = (data instanceof Uint8Array || typeof data === 'string')
|
|
586
1200
|
? data
|
|
587
1201
|
: JSON.stringify(data);
|
|
588
|
-
if (
|
|
589
|
-
|
|
1202
|
+
if (socket && socket.readyState === WebSocket.OPEN) {
|
|
1203
|
+
socket.send(payload);
|
|
1204
|
+
} else if (socket) {
|
|
1205
|
+
socket.addEventListener('open', () => socket.send(payload), { once: true });
|
|
1206
|
+
}
|
|
590
1207
|
},
|
|
591
|
-
close(code, reason) {
|
|
592
|
-
|
|
1208
|
+
close(code=1000, reason = '') {
|
|
1209
|
+
console.log({code,reason})
|
|
1210
|
+
manualClose = true;
|
|
1211
|
+
if (socket) socket.close(code, reason);
|
|
593
1212
|
},
|
|
594
1213
|
async *[Symbol.asyncIterator]() {
|
|
595
1214
|
while (!closed || queue.length > 0) {
|
|
@@ -601,6 +1220,8 @@ function createNode(chain) {
|
|
|
601
1220
|
}
|
|
602
1221
|
}
|
|
603
1222
|
};
|
|
1223
|
+
|
|
1224
|
+
return clientWs;
|
|
604
1225
|
}
|
|
605
1226
|
|
|
606
1227
|
let customHeaders = {};
|