@alecsibilia/ui-kit 0.0.0-stage → 0.1.0-alpha.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/CHANGELOG.md +7 -0
- package/LICENSE +201 -0
- package/README.md +233 -2
- package/bin/ui-kit.js +12 -0
- package/dist/alchemy/app.d.ts +34 -0
- package/dist/alchemy/app.js +88 -0
- package/dist/alchemy/index.d.ts +11 -0
- package/dist/alchemy/index.js +11 -0
- package/dist/alchemy/live-rooms.d.ts +21 -0
- package/dist/alchemy/live-rooms.js +31 -0
- package/dist/alchemy/migrations.d.ts +28 -0
- package/dist/alchemy/migrations.js +56 -0
- package/dist/alchemy/stage.d.ts +20 -0
- package/dist/alchemy/stage.js +20 -0
- package/dist/alchemy/wrangler-config.d.ts +76 -0
- package/dist/alchemy/wrangler-config.js +82 -0
- package/dist/build/app-modules.d.ts +11 -0
- package/dist/build/app-modules.js +40 -0
- package/dist/build/check.d.ts +4 -0
- package/dist/build/check.js +170 -0
- package/dist/build/cli.d.ts +1 -0
- package/dist/build/cli.js +79 -0
- package/dist/build/feature.d.ts +8 -0
- package/dist/build/feature.js +24 -0
- package/dist/build/index.d.ts +13 -0
- package/dist/build/index.js +13 -0
- package/dist/build/measure-cpu.d.ts +2 -0
- package/dist/build/measure-cpu.js +196 -0
- package/dist/build/prerender.d.ts +5 -0
- package/dist/build/prerender.js +109 -0
- package/dist/build/preview.d.ts +7 -0
- package/dist/build/preview.js +41 -0
- package/dist/build/seo-files.d.ts +27 -0
- package/dist/build/seo-files.js +24 -0
- package/dist/client/head-swap.d.ts +45 -0
- package/dist/client/head-swap.js +183 -0
- package/dist/client/hydration-pass.d.ts +56 -0
- package/dist/client/hydration-pass.js +186 -0
- package/dist/client/hydration-reset.d.ts +82 -0
- package/dist/client/hydration-reset.js +154 -0
- package/dist/client/index.d.ts +37 -0
- package/dist/client/index.js +65 -0
- package/dist/client/nav-client.d.ts +35 -0
- package/dist/client/nav-client.js +371 -0
- package/dist/live/collab/doc-provider.d.ts +74 -0
- package/dist/live/collab/doc-provider.js +412 -0
- package/dist/live/collab/index.d.ts +51 -0
- package/dist/live/collab/index.jsx +142 -0
- package/dist/live/collab-status.d.ts +25 -0
- package/dist/live/collab-status.js +17 -0
- package/dist/live/cursors/cursor-engine.d.ts +57 -0
- package/dist/live/cursors/cursor-engine.js +243 -0
- package/dist/live/cursors/index.d.ts +46 -0
- package/dist/live/cursors/index.jsx +110 -0
- package/dist/live/declaration.d.ts +113 -0
- package/dist/live/declaration.js +94 -0
- package/dist/live/index.d.ts +8 -0
- package/dist/live/index.js +8 -0
- package/dist/live/protocol.d.ts +224 -0
- package/dist/live/protocol.js +272 -0
- package/dist/live/server/doc-store.d.ts +68 -0
- package/dist/live/server/doc-store.js +187 -0
- package/dist/live/server/index.d.ts +60 -0
- package/dist/live/server/index.js +77 -0
- package/dist/live/server/room-presence.d.ts +24 -0
- package/dist/live/server/room-presence.js +123 -0
- package/dist/live/server/room-sockets.d.ts +65 -0
- package/dist/live/server/room-sockets.js +97 -0
- package/dist/live/server/room.d.ts +20 -0
- package/dist/live/server/room.js +348 -0
- package/dist/live/server/route.d.ts +56 -0
- package/dist/live/server/route.js +159 -0
- package/dist/live/server/types.d.ts +163 -0
- package/dist/live/server/types.js +2 -0
- package/dist/logic/agent-actions.d.ts +133 -0
- package/dist/logic/agent-actions.js +150 -0
- package/dist/logic/command-types.d.ts +53 -0
- package/dist/logic/command-types.js +0 -0
- package/dist/logic/dev.d.ts +9 -0
- package/dist/logic/dev.js +10 -0
- package/dist/logic/draft-rebase.d.ts +59 -0
- package/dist/logic/draft-rebase.js +71 -0
- package/dist/logic/form-state.d.ts +105 -0
- package/dist/logic/form-state.js +93 -0
- package/dist/logic/head.d.ts +145 -0
- package/dist/logic/head.js +140 -0
- package/dist/logic/index.d.ts +27 -0
- package/dist/logic/index.js +25 -0
- package/dist/logic/island-def.d.ts +89 -0
- package/dist/logic/island-def.js +59 -0
- package/dist/logic/kit-commands.d.ts +104 -0
- package/dist/logic/kit-commands.js +72 -0
- package/dist/logic/kit-errors.d.ts +25 -0
- package/dist/logic/kit-errors.js +6 -0
- package/dist/logic/listen.d.ts +99 -0
- package/dist/logic/listen.js +92 -0
- package/dist/logic/mutation-def.d.ts +65 -0
- package/dist/logic/mutation-def.js +43 -0
- package/dist/logic/navigation-data.d.ts +50 -0
- package/dist/logic/navigation-data.js +55 -0
- package/dist/logic/navigation-policy.d.ts +74 -0
- package/dist/logic/navigation-policy.js +127 -0
- package/dist/logic/page-model-def.d.ts +108 -0
- package/dist/logic/page-model-def.js +31 -0
- package/dist/logic/path.d.ts +31 -0
- package/dist/logic/path.js +48 -0
- package/dist/logic/query-def.d.ts +56 -0
- package/dist/logic/query-def.js +37 -0
- package/dist/logic/query-key.d.ts +24 -0
- package/dist/logic/query-key.js +35 -0
- package/dist/logic/query-types.d.ts +28 -0
- package/dist/logic/query-types.js +2 -0
- package/dist/logic/resources.d.ts +163 -0
- package/dist/logic/resources.js +62 -0
- package/dist/logic/result.d.ts +30 -0
- package/dist/logic/result.js +23 -0
- package/dist/logic/route-model.d.ts +139 -0
- package/dist/logic/route-model.js +207 -0
- package/dist/logic/route-params.d.ts +80 -0
- package/dist/logic/route-params.js +114 -0
- package/dist/logic/route-table.d.ts +308 -0
- package/dist/logic/route-table.js +206 -0
- package/dist/logic/seo.d.ts +61 -0
- package/dist/logic/seo.js +101 -0
- package/dist/logic/site.d.ts +12 -0
- package/dist/logic/site.js +0 -0
- package/dist/logic/subscriptions.d.ts +177 -0
- package/dist/logic/subscriptions.js +152 -0
- package/dist/render/index.d.ts +32 -0
- package/dist/render/index.js +52 -0
- package/dist/runtime/island-wake.d.ts +38 -0
- package/dist/runtime/island-wake.js +147 -0
- package/dist/runtime/query-scope.d.ts +224 -0
- package/dist/runtime/query-scope.js +222 -0
- package/dist/runtime/room-hub.d.ts +107 -0
- package/dist/runtime/room-hub.js +307 -0
- package/dist/runtime/subscription-runner.d.ts +71 -0
- package/dist/runtime/subscription-runner.js +240 -0
- package/dist/server/bindings.d.ts +41 -0
- package/dist/server/bindings.js +74 -0
- package/dist/server/browser.d.ts +9 -0
- package/dist/server/browser.js +9 -0
- package/dist/server/edge-cache.d.ts +28 -0
- package/dist/server/edge-cache.js +35 -0
- package/dist/server/errors.d.ts +45 -0
- package/dist/server/errors.js +36 -0
- package/dist/server/form-actions-setup.d.ts +1 -0
- package/dist/server/form-actions-setup.js +15 -0
- package/dist/server/form-actions.d.ts +121 -0
- package/dist/server/form-actions.js +211 -0
- package/dist/server/index.d.ts +36 -0
- package/dist/server/index.js +35 -0
- package/dist/server/inputs.d.ts +45 -0
- package/dist/server/inputs.js +77 -0
- package/dist/server/rate-limit.d.ts +29 -0
- package/dist/server/rate-limit.js +32 -0
- package/dist/server/read-cache.d.ts +74 -0
- package/dist/server/read-cache.js +58 -0
- package/dist/server/request-info.d.ts +17 -0
- package/dist/server/request-info.js +11 -0
- package/dist/server/request.d.ts +52 -0
- package/dist/server/request.js +73 -0
- package/dist/server/response-cookies.d.ts +23 -0
- package/dist/server/response-cookies.js +24 -0
- package/dist/server/run-effect.d.ts +42 -0
- package/dist/server/run-effect.js +92 -0
- package/dist/server/run.d.ts +63 -0
- package/dist/server/run.js +66 -0
- package/dist/server/session.d.ts +125 -0
- package/dist/server/session.js +247 -0
- package/dist/test/fake-bindings.d.ts +32 -0
- package/dist/test/fake-bindings.js +108 -0
- package/dist/test/fake-room.d.ts +66 -0
- package/dist/test/fake-room.js +216 -0
- package/dist/test/index.d.ts +19 -0
- package/dist/test/index.js +44 -0
- package/dist/test/probe.d.ts +11 -0
- package/dist/test/probe.js +11 -0
- package/dist/test/solid-jsx.d.ts +23 -0
- package/dist/test/solid-jsx.js +28 -0
- package/dist/test/solid-preload.d.ts +1 -0
- package/dist/test/solid-preload.js +29 -0
- package/dist/ui/code-editor/index.d.ts +21 -0
- package/dist/ui/code-editor/index.jsx +286 -0
- package/dist/ui/collab-text/index.d.ts +29 -0
- package/dist/ui/collab-text/index.jsx +96 -0
- package/dist/ui/components/controls.d.ts +69 -0
- package/dist/ui/components/controls.jsx +81 -0
- package/dist/ui/components/feedback.d.ts +26 -0
- package/dist/ui/components/feedback.jsx +80 -0
- package/dist/ui/components/layout.d.ts +74 -0
- package/dist/ui/components/layout.jsx +146 -0
- package/dist/ui/components/lists.d.ts +69 -0
- package/dist/ui/components/lists.jsx +133 -0
- package/dist/ui/components/navigation.d.ts +73 -0
- package/dist/ui/components/navigation.jsx +112 -0
- package/dist/ui/components/text.d.ts +34 -0
- package/dist/ui/components/text.jsx +163 -0
- package/dist/ui/index.d.ts +7 -0
- package/dist/ui/index.js +7 -0
- package/dist/ui/jsx-runtime.d.ts +19 -0
- package/dist/ui/jsx-runtime.js +0 -0
- package/dist/ui/list-keys.d.ts +31 -0
- package/dist/ui/list-keys.js +45 -0
- package/dist/ui/styles/base.css +38 -0
- package/dist/ui/styles/components.css +608 -0
- package/dist/ui/styles/tokens.css +27 -0
- package/dist/ui/styles/transitions.css +23 -0
- package/dist/ui/styles/workbench.css +428 -0
- package/dist/ui/styles.css +9 -0
- package/dist/view/agent-actions-view.d.ts +30 -0
- package/dist/view/agent-actions-view.js +27 -0
- package/dist/view/agent-surface.d.ts +42 -0
- package/dist/view/agent-surface.js +123 -0
- package/dist/view/app-scope.d.ts +51 -0
- package/dist/view/app-scope.js +75 -0
- package/dist/view/boundary.d.ts +18 -0
- package/dist/view/boundary.jsx +26 -0
- package/dist/view/command-runner.d.ts +16 -0
- package/dist/view/command-runner.js +245 -0
- package/dist/view/form.d.ts +82 -0
- package/dist/view/form.jsx +109 -0
- package/dist/view/head-view.d.ts +31 -0
- package/dist/view/head-view.js +46 -0
- package/dist/view/index.d.ts +41 -0
- package/dist/view/index.js +40 -0
- package/dist/view/island-root.d.ts +30 -0
- package/dist/view/island-root.js +36 -0
- package/dist/view/island.d.ts +102 -0
- package/dist/view/island.jsx +154 -0
- package/dist/view/match.d.ts +41 -0
- package/dist/view/match.js +111 -0
- package/dist/view/model.d.ts +92 -0
- package/dist/view/model.js +162 -0
- package/dist/view/navigation-head.d.ts +29 -0
- package/dist/view/navigation-head.jsx +38 -0
- package/dist/view/page-model.d.ts +46 -0
- package/dist/view/page-model.js +146 -0
- package/dist/view/query-effects.d.ts +87 -0
- package/dist/view/query-effects.js +147 -0
- package/dist/view/query-ok.d.ts +45 -0
- package/dist/view/query-ok.js +96 -0
- package/dist/view/query.d.ts +115 -0
- package/dist/view/query.jsx +179 -0
- package/dist/view/result-view.d.ts +14 -0
- package/dist/view/result-view.jsx +15 -0
- package/dist/view/route-pages.d.ts +43 -0
- package/dist/view/route-pages.js +59 -0
- package/dist/view/router.d.ts +44 -0
- package/dist/view/router.js +123 -0
- package/dist/vite/dev-middleware.d.ts +12 -0
- package/dist/vite/dev-middleware.js +39 -0
- package/dist/vite/dev-objects.d.ts +25 -0
- package/dist/vite/dev-objects.js +127 -0
- package/dist/vite/dev-platform.d.ts +19 -0
- package/dist/vite/dev-platform.js +77 -0
- package/dist/vite/dev-seo-files.d.ts +11 -0
- package/dist/vite/dev-seo-files.js +40 -0
- package/dist/vite/index.d.ts +53 -0
- package/dist/vite/index.js +148 -0
- package/dist/vite/local-config.d.ts +34 -0
- package/dist/vite/local-config.js +72 -0
- package/dist/vite/worker-build.d.ts +24 -0
- package/dist/vite/worker-build.js +84 -0
- package/dist/worker/create-worker.d.ts +52 -0
- package/dist/worker/create-worker.js +90 -0
- package/dist/worker/index.d.ts +12 -0
- package/dist/worker/index.js +12 -0
- package/dist/worker/page-routes.d.ts +88 -0
- package/dist/worker/page-routes.js +100 -0
- package/dist/worker/page-status.d.ts +41 -0
- package/dist/worker/page-status.js +23 -0
- package/dist/worker/request-prelude.d.ts +69 -0
- package/dist/worker/request-prelude.js +107 -0
- package/dist/worker/security.d.ts +76 -0
- package/dist/worker/security.js +137 -0
- package/dist/worker/server-app.d.ts +54 -0
- package/dist/worker/server-app.js +76 -0
- package/guards/browser-only.js +5 -0
- package/guards/node-only.js +6 -0
- package/guards/server-only.js +5 -0
- package/migrations/0001-sessions.sql +22 -0
- package/package.json +233 -5
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { Clock, Context, Effect, Layer } from 'effect';
|
|
2
|
+
import { Bindings } from './bindings.js';
|
|
3
|
+
import { Unauthorized } from './errors.js';
|
|
4
|
+
import { parseCookieHeader, serializeCookie } from './request.js';
|
|
5
|
+
import { ResponseCookies } from './response-cookies.js';
|
|
6
|
+
/*
|
|
7
|
+
* Sessions: an opaque session cookie backed by the kit's own D1 table
|
|
8
|
+
* (`sessions`, `migrations/0001-sessions.sql`, applied by `uiKitApp` and the
|
|
9
|
+
* local tooling next to the app's migrations). The kit owns only that
|
|
10
|
+
* table: users are the app's, and the app hands the kit a user lookup.
|
|
11
|
+
*
|
|
12
|
+
* - The cookie holds a random 256-bit token (base64url). D1 stores only its
|
|
13
|
+
* SHA-256, so the table can't be replayed as cookies.
|
|
14
|
+
* - `HttpOnly`, `SameSite=Lax`, `Path=/`, `Secure` (named `__Host-sid`).
|
|
15
|
+
* Only a plain-http request to localhost gets an insecure cookie, `sid`.
|
|
16
|
+
* - Expiry is server-side (`sessions.expires_at`); the cookie's Max-Age
|
|
17
|
+
* mirrors it. Reads never write, so a session isn't extended on use.
|
|
18
|
+
* - The Worker puts a lazy lookup on `locals.session`: D1 is read only when
|
|
19
|
+
* something needs the session (a program reading `Session`, or an
|
|
20
|
+
* `auth: "required"` page). Reading it marks the call as personal, so a
|
|
21
|
+
* shared cache never keeps the answer.
|
|
22
|
+
*/
|
|
23
|
+
/** How long a session lasts by default (server-side expiry; the cookie mirrors it). */
|
|
24
|
+
export const SESSION_TTL_SECONDS = 7 * 24 * 60 * 60;
|
|
25
|
+
export const SIGNED_OUT = Object.freeze({
|
|
26
|
+
_tag: 'SignedOut',
|
|
27
|
+
});
|
|
28
|
+
/** Hosts that may get an insecure (`http:`) session cookie: local dev only. */
|
|
29
|
+
const LOCAL_HOSTS = new Set([
|
|
30
|
+
'localhost',
|
|
31
|
+
'127.0.0.1',
|
|
32
|
+
'[::1]',
|
|
33
|
+
]);
|
|
34
|
+
/** The cookie name and `Secure` flag for a request URL. */
|
|
35
|
+
export function sessionCookieSpec(url) {
|
|
36
|
+
const insecure = url.protocol === 'http:' && LOCAL_HOSTS.has(url.hostname);
|
|
37
|
+
return insecure
|
|
38
|
+
? { name: 'sid', secure: false }
|
|
39
|
+
: { name: '__Host-sid', secure: true };
|
|
40
|
+
}
|
|
41
|
+
/** A token is 32 random bytes as base64url: 43 characters. */
|
|
42
|
+
const TOKEN_SHAPE = /^[A-Za-z0-9_-]{43}$/;
|
|
43
|
+
/** Bytes as base64url (no padding). */
|
|
44
|
+
export function base64url(bytes) {
|
|
45
|
+
let binary = '';
|
|
46
|
+
for (const byte of bytes)
|
|
47
|
+
binary += String.fromCharCode(byte);
|
|
48
|
+
return btoa(binary)
|
|
49
|
+
.replace(/\+/g, '-')
|
|
50
|
+
.replace(/\//g, '_')
|
|
51
|
+
.replace(/=+$/, '');
|
|
52
|
+
}
|
|
53
|
+
/** A fresh opaque session token (256 bits). */
|
|
54
|
+
export function newSessionToken() {
|
|
55
|
+
return base64url(crypto.getRandomValues(new Uint8Array(32)));
|
|
56
|
+
}
|
|
57
|
+
/** The `sessions.session_id` for a token: SHA-256, hex. */
|
|
58
|
+
export async function sessionIdOf(token) {
|
|
59
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(token));
|
|
60
|
+
return [...new Uint8Array(digest)]
|
|
61
|
+
.map((byte) => byte.toString(16).padStart(2, '0'))
|
|
62
|
+
.join('');
|
|
63
|
+
}
|
|
64
|
+
/** The session token in the request's cookie, if it has a well-formed one. */
|
|
65
|
+
export function sessionTokenOf(request) {
|
|
66
|
+
const { name } = sessionCookieSpec(new URL(request.url));
|
|
67
|
+
const token = parseCookieHeader(request.headers.get('cookie'))[name];
|
|
68
|
+
return token !== undefined && TOKEN_SHAPE.test(token) ? token : undefined;
|
|
69
|
+
}
|
|
70
|
+
/** `Set-Cookie` for a new session. */
|
|
71
|
+
export function sessionCookie(url, token, maxAge = SESSION_TTL_SECONDS) {
|
|
72
|
+
const { name, secure } = sessionCookieSpec(url);
|
|
73
|
+
return serializeCookie(name, token, {
|
|
74
|
+
path: '/',
|
|
75
|
+
httpOnly: true,
|
|
76
|
+
secure,
|
|
77
|
+
sameSite: 'Lax',
|
|
78
|
+
maxAge,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
/** `Set-Cookie` that removes the session cookie. */
|
|
82
|
+
export function clearSessionCookie(url) {
|
|
83
|
+
const { name, secure } = sessionCookieSpec(url);
|
|
84
|
+
return serializeCookie(name, '', {
|
|
85
|
+
path: '/',
|
|
86
|
+
httpOnly: true,
|
|
87
|
+
secure,
|
|
88
|
+
sameSite: 'Lax',
|
|
89
|
+
maxAge: 0,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
/** A resolved session for a slot (runs the lookup if it is lazy). */
|
|
93
|
+
export async function resolveSlot(slot) {
|
|
94
|
+
return slot._tag === 'Lazy' ? slot.resolve() : slot;
|
|
95
|
+
}
|
|
96
|
+
/** `locals.session` as a slot (`SignedOut` when absent or malformed). */
|
|
97
|
+
export function sessionSlotFromLocals(locals) {
|
|
98
|
+
const value = locals.session;
|
|
99
|
+
if (typeof value !== 'object' || value === null)
|
|
100
|
+
return SIGNED_OUT;
|
|
101
|
+
const tag = Reflect.get(value, '_tag');
|
|
102
|
+
if (tag === 'SignedIn' || tag === 'Lazy') {
|
|
103
|
+
// Put there by the Worker's prelude (`createSessions().lazy`) or a test.
|
|
104
|
+
return value;
|
|
105
|
+
}
|
|
106
|
+
return SIGNED_OUT;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* This request's session as an Effect service, provided per call from
|
|
110
|
+
* `locals.session` (like `Bindings`). `onRead` runs when a program reads
|
|
111
|
+
* it: `runRead` uses that to force `Cache-Control: private, no-store`.
|
|
112
|
+
* Apps read it through their `createSessions` helpers, which type the user.
|
|
113
|
+
*/
|
|
114
|
+
export class Session extends Context.Service()('@alecsibilia/ui-kit/server/Session') {
|
|
115
|
+
/** The service value for one call. */
|
|
116
|
+
static forCall(slot, onRead = () => { }) {
|
|
117
|
+
return {
|
|
118
|
+
current: Effect.suspend(() => {
|
|
119
|
+
onRead();
|
|
120
|
+
return Effect.promise(() => resolveSlot(slot));
|
|
121
|
+
}),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
static layer(slot, onRead) {
|
|
125
|
+
return Layer.succeed(Session, Session.forCall(slot, onRead));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* The app's sessions over the kit's `sessions` table.
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* ```ts
|
|
133
|
+
* export const sessions = createSessions<DemoUser>({
|
|
134
|
+
* resources,
|
|
135
|
+
* lookupUser: ({ db, user_id }) => findUser(db, user_id),
|
|
136
|
+
* })
|
|
137
|
+
* const session = yield* sessions.require
|
|
138
|
+
* ```
|
|
139
|
+
*/
|
|
140
|
+
export function createSessions(config) {
|
|
141
|
+
const database = config.resources.sessions?.database;
|
|
142
|
+
if (database === undefined) {
|
|
143
|
+
throw new Error('createSessions: the resource declaration has no `sessions: { database }`');
|
|
144
|
+
}
|
|
145
|
+
const ttl = config.ttlSeconds ?? SESSION_TTL_SECONDS;
|
|
146
|
+
const dbOf = (env) =>
|
|
147
|
+
// `Bindings` holds the checked lazy env: reading it validates the binding.
|
|
148
|
+
env[database];
|
|
149
|
+
const resolve = async (request, db, nowMs) => {
|
|
150
|
+
const token = sessionTokenOf(request);
|
|
151
|
+
if (token === undefined)
|
|
152
|
+
return SIGNED_OUT;
|
|
153
|
+
const row = await db
|
|
154
|
+
.prepare('SELECT session_id, user_id, expires_at FROM sessions ' +
|
|
155
|
+
'WHERE session_id = ?1 AND expires_at > ?2')
|
|
156
|
+
.bind(await sessionIdOf(token), new Date(nowMs).toISOString())
|
|
157
|
+
.first();
|
|
158
|
+
if (!row)
|
|
159
|
+
return SIGNED_OUT;
|
|
160
|
+
const user = await config.lookupUser({ db, user_id: row.user_id });
|
|
161
|
+
if (user === undefined)
|
|
162
|
+
return SIGNED_OUT;
|
|
163
|
+
return {
|
|
164
|
+
_tag: 'SignedIn',
|
|
165
|
+
session_id: row.session_id,
|
|
166
|
+
user_id: row.user_id,
|
|
167
|
+
expires_at: Date.parse(row.expires_at),
|
|
168
|
+
user,
|
|
169
|
+
};
|
|
170
|
+
};
|
|
171
|
+
const current = Effect.gen(function* () {
|
|
172
|
+
const state = yield* (yield* Session).current;
|
|
173
|
+
// The slot was made by `lazy` above, so its user is a `U`.
|
|
174
|
+
return state;
|
|
175
|
+
});
|
|
176
|
+
const onEnded = config.onEnded;
|
|
177
|
+
const ended = (db, user_ids) => onEnded === undefined || user_ids.length === 0
|
|
178
|
+
? Effect.void
|
|
179
|
+
: Effect.promise(() => onEnded({ db, user_ids }));
|
|
180
|
+
return {
|
|
181
|
+
config,
|
|
182
|
+
database,
|
|
183
|
+
resolve,
|
|
184
|
+
lazy: (request, db, nowMs) => {
|
|
185
|
+
if (sessionTokenOf(request) === undefined)
|
|
186
|
+
return SIGNED_OUT;
|
|
187
|
+
let pending;
|
|
188
|
+
return {
|
|
189
|
+
_tag: 'Lazy',
|
|
190
|
+
resolve: () => {
|
|
191
|
+
pending ??= resolve(request, db(), nowMs);
|
|
192
|
+
return pending;
|
|
193
|
+
},
|
|
194
|
+
};
|
|
195
|
+
},
|
|
196
|
+
current,
|
|
197
|
+
require: Effect.gen(function* () {
|
|
198
|
+
const state = yield* current;
|
|
199
|
+
if (state._tag === 'SignedOut') {
|
|
200
|
+
return yield* new Unauthorized({
|
|
201
|
+
message: 'Sign in to continue.',
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
return state;
|
|
205
|
+
}),
|
|
206
|
+
signIn: ({ user_id, before = [] }) => Effect.gen(function* () {
|
|
207
|
+
const db = dbOf(yield* Bindings);
|
|
208
|
+
const now = yield* Clock.currentTimeMillis;
|
|
209
|
+
const expires_at = now + ttl * 1000;
|
|
210
|
+
const token = newSessionToken();
|
|
211
|
+
const session_id = yield* Effect.promise(() => sessionIdOf(token));
|
|
212
|
+
const insert = db
|
|
213
|
+
.prepare('INSERT INTO sessions (session_id, user_id, created_at, expires_at) VALUES (?1, ?2, ?3, ?4)')
|
|
214
|
+
.bind(session_id, user_id, new Date(now).toISOString(), new Date(expires_at).toISOString());
|
|
215
|
+
yield* Effect.promise(() => db.batch([...before, insert]));
|
|
216
|
+
const cookies = yield* ResponseCookies;
|
|
217
|
+
yield* cookies.set(sessionCookie(cookies.requestUrl, token, ttl));
|
|
218
|
+
return { expires_at };
|
|
219
|
+
}),
|
|
220
|
+
signOut: Effect.gen(function* () {
|
|
221
|
+
const state = yield* (yield* Session).current;
|
|
222
|
+
if (state._tag === 'SignedIn') {
|
|
223
|
+
const db = dbOf(yield* Bindings);
|
|
224
|
+
yield* Effect.promise(() => db
|
|
225
|
+
.prepare('DELETE FROM sessions WHERE session_id = ?1')
|
|
226
|
+
.bind(state.session_id)
|
|
227
|
+
.run());
|
|
228
|
+
yield* ended(db, [state.user_id]);
|
|
229
|
+
}
|
|
230
|
+
const cookies = yield* ResponseCookies;
|
|
231
|
+
yield* cookies.set(clearSessionCookie(cookies.requestUrl));
|
|
232
|
+
}),
|
|
233
|
+
purgeExpired: (limit) => Effect.gen(function* () {
|
|
234
|
+
const db = dbOf(yield* Bindings);
|
|
235
|
+
const nowIso = new Date(yield* Clock.currentTimeMillis).toISOString();
|
|
236
|
+
const removed = yield* Effect.promise(() => db
|
|
237
|
+
.prepare('DELETE FROM sessions WHERE session_id IN ' +
|
|
238
|
+
'(SELECT session_id FROM sessions WHERE expires_at <= ?1 ORDER BY expires_at LIMIT ?2) ' +
|
|
239
|
+
'RETURNING user_id')
|
|
240
|
+
.bind(nowIso, limit)
|
|
241
|
+
.all());
|
|
242
|
+
const user_ids = removed.results.map((row) => row.user_id);
|
|
243
|
+
yield* ended(db, user_ids);
|
|
244
|
+
return user_ids.length;
|
|
245
|
+
}),
|
|
246
|
+
};
|
|
247
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite';
|
|
2
|
+
import type { D1Binding, R2Binding, RateLimitBinding } from '../logic/resources.ts';
|
|
3
|
+
/**
|
|
4
|
+
* Fake Worker bindings for server tests (D1 over in-memory SQLite, R2 over
|
|
5
|
+
* a Map, the rate limiter over a counter per key).
|
|
6
|
+
*/
|
|
7
|
+
/** The kit's own migrations (the `sessions` table), applied before an app's. */
|
|
8
|
+
export declare const KIT_MIGRATIONS_DIR: string;
|
|
9
|
+
/**
|
|
10
|
+
* A D1 binding over in-memory SQLite with the kit's migrations and then the
|
|
11
|
+
* app's (`migrations`: folders, each applied in name order). `writes`
|
|
12
|
+
* counts statements that change rows; `statements` counts every statement
|
|
13
|
+
* run (reads too), and `sessionLookups` the kit's session lookups.
|
|
14
|
+
*/
|
|
15
|
+
export declare function fakeD1(options?: {
|
|
16
|
+
readonly migrations?: readonly string[];
|
|
17
|
+
}): D1Binding & {
|
|
18
|
+
readonly writes: () => number;
|
|
19
|
+
readonly statements: () => number;
|
|
20
|
+
readonly sessionLookups: () => number;
|
|
21
|
+
readonly db: Database;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* A rate limiter allowing `limit` calls per key (no period: a test's run is
|
|
25
|
+
* well inside one). `calls` lists the keys it was asked about.
|
|
26
|
+
*/
|
|
27
|
+
export declare function fakeRateLimit(limit?: number): RateLimitBinding & {
|
|
28
|
+
readonly calls: string[];
|
|
29
|
+
};
|
|
30
|
+
export declare function fakeR2(): R2Binding & {
|
|
31
|
+
readonly objects: Map<string, string>;
|
|
32
|
+
};
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { join, resolve } from 'node:path';
|
|
3
|
+
import { Database } from 'bun:sqlite';
|
|
4
|
+
/**
|
|
5
|
+
* Fake Worker bindings for server tests (D1 over in-memory SQLite, R2 over
|
|
6
|
+
* a Map, the rate limiter over a counter per key).
|
|
7
|
+
*/
|
|
8
|
+
/** The kit's own migrations (the `sessions` table), applied before an app's. */
|
|
9
|
+
export const KIT_MIGRATIONS_DIR = resolve(import.meta.dir, '../../migrations');
|
|
10
|
+
/** The `.sql` files of each folder, in name order, folder by folder. */
|
|
11
|
+
function migrationFiles(dirs) {
|
|
12
|
+
return dirs.flatMap((dir) => readdirSync(dir)
|
|
13
|
+
.filter((file) => file.endsWith('.sql'))
|
|
14
|
+
.sort()
|
|
15
|
+
.map((file) => join(dir, file)));
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A D1 binding over in-memory SQLite with the kit's migrations and then the
|
|
19
|
+
* app's (`migrations`: folders, each applied in name order). `writes`
|
|
20
|
+
* counts statements that change rows; `statements` counts every statement
|
|
21
|
+
* run (reads too), and `sessionLookups` the kit's session lookups.
|
|
22
|
+
*/
|
|
23
|
+
export function fakeD1(options = {}) {
|
|
24
|
+
const db = new Database(':memory:');
|
|
25
|
+
for (const file of migrationFiles([
|
|
26
|
+
KIT_MIGRATIONS_DIR,
|
|
27
|
+
...(options.migrations ?? []),
|
|
28
|
+
])) {
|
|
29
|
+
db.exec(readFileSync(file, 'utf8'));
|
|
30
|
+
}
|
|
31
|
+
let writes = 0;
|
|
32
|
+
let statements = 0;
|
|
33
|
+
let sessionLookups = 0;
|
|
34
|
+
const count = (sql) => {
|
|
35
|
+
statements += 1;
|
|
36
|
+
if (sql.includes('FROM sessions WHERE session_id'))
|
|
37
|
+
sessionLookups += 1;
|
|
38
|
+
};
|
|
39
|
+
const changes = () => db.query('SELECT total_changes() AS n').get().n;
|
|
40
|
+
const statement = (sql, values) => ({
|
|
41
|
+
bind: (...next) => statement(sql, next),
|
|
42
|
+
first: async () => {
|
|
43
|
+
count(sql);
|
|
44
|
+
const before = changes();
|
|
45
|
+
const row = db.query(sql).get(...values) ?? null;
|
|
46
|
+
writes += changes() - before;
|
|
47
|
+
return row;
|
|
48
|
+
},
|
|
49
|
+
run: async () => {
|
|
50
|
+
count(sql);
|
|
51
|
+
const before = changes();
|
|
52
|
+
db.query(sql).run(...values);
|
|
53
|
+
writes += changes() - before;
|
|
54
|
+
return {};
|
|
55
|
+
},
|
|
56
|
+
all: async () => {
|
|
57
|
+
count(sql);
|
|
58
|
+
const before = changes();
|
|
59
|
+
const results = db.query(sql).all(...values);
|
|
60
|
+
writes += changes() - before;
|
|
61
|
+
return { results };
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
return {
|
|
65
|
+
db,
|
|
66
|
+
prepare: (sql) => statement(sql, []),
|
|
67
|
+
// Sequential, not a transaction: enough for these tests.
|
|
68
|
+
batch: async (statements) => {
|
|
69
|
+
const results = [];
|
|
70
|
+
for (const each of statements)
|
|
71
|
+
results.push(await each.run());
|
|
72
|
+
return results;
|
|
73
|
+
},
|
|
74
|
+
writes: () => writes,
|
|
75
|
+
statements: () => statements,
|
|
76
|
+
sessionLookups: () => sessionLookups,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* A rate limiter allowing `limit` calls per key (no period: a test's run is
|
|
81
|
+
* well inside one). `calls` lists the keys it was asked about.
|
|
82
|
+
*/
|
|
83
|
+
export function fakeRateLimit(limit = 5) {
|
|
84
|
+
const counts = new Map();
|
|
85
|
+
const calls = [];
|
|
86
|
+
return {
|
|
87
|
+
calls,
|
|
88
|
+
limit: async ({ key }) => {
|
|
89
|
+
calls.push(key);
|
|
90
|
+
const used = counts.get(key) ?? 0;
|
|
91
|
+
if (used >= limit)
|
|
92
|
+
return { success: false };
|
|
93
|
+
counts.set(key, used + 1);
|
|
94
|
+
return { success: true };
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
export function fakeR2() {
|
|
99
|
+
const objects = new Map();
|
|
100
|
+
return {
|
|
101
|
+
objects,
|
|
102
|
+
put: async (key, value) => {
|
|
103
|
+
objects.set(key, value);
|
|
104
|
+
return {};
|
|
105
|
+
},
|
|
106
|
+
head: async (key) => (objects.has(key) ? {} : null),
|
|
107
|
+
};
|
|
108
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite';
|
|
2
|
+
import * as awarenessProtocol from 'y-protocols/awareness';
|
|
3
|
+
import * as Y from 'yjs';
|
|
4
|
+
import { type LiveUser, type RoomCore, type RoomRuntime, type RoomSocket, type RoomState } from '../live/server/index.ts';
|
|
5
|
+
/**
|
|
6
|
+
* Fakes for the live room Durable Object: a `RoomState` whose SQLite is
|
|
7
|
+
* real (bun:sqlite, so "reload after hibernation" is a new core over the
|
|
8
|
+
* same database), hibernation-style sockets with attachments and tags, a
|
|
9
|
+
* runtime with a manual clock and timers, and a tiny Yjs client speaking
|
|
10
|
+
* the y-websocket message format.
|
|
11
|
+
*/
|
|
12
|
+
export interface FakeSocket extends RoomSocket {
|
|
13
|
+
readonly sent: (string | Uint8Array)[];
|
|
14
|
+
readonly tags: string[];
|
|
15
|
+
closed: {
|
|
16
|
+
code?: number;
|
|
17
|
+
reason?: string;
|
|
18
|
+
} | undefined;
|
|
19
|
+
/** Text frames received, parsed as JSON. */
|
|
20
|
+
readonly json: () => Record<string, unknown>[];
|
|
21
|
+
}
|
|
22
|
+
export declare function fakeSocket(): FakeSocket;
|
|
23
|
+
export interface FakeRoom {
|
|
24
|
+
readonly state: RoomState;
|
|
25
|
+
readonly runtime: RoomRuntime;
|
|
26
|
+
readonly db: Database;
|
|
27
|
+
readonly sockets: FakeSocket[];
|
|
28
|
+
alarm: number | null;
|
|
29
|
+
advance(ms: number): void;
|
|
30
|
+
/** Runs timers that are due. */
|
|
31
|
+
tick(ms?: number): void;
|
|
32
|
+
/** Open sockets (closed ones are dropped, as workerd does). */
|
|
33
|
+
live(): FakeSocket[];
|
|
34
|
+
/** Rows written to storage tables so far (by name). */
|
|
35
|
+
tables(): string[];
|
|
36
|
+
}
|
|
37
|
+
export declare function fakeRoom(db?: Database): FakeRoom;
|
|
38
|
+
/** A request as the Worker route forwards it to the room. */
|
|
39
|
+
export declare function roomRequest(room: {
|
|
40
|
+
readonly type: string;
|
|
41
|
+
readonly key: string;
|
|
42
|
+
}, user: LiveUser, options?: {
|
|
43
|
+
readonly doc?: string;
|
|
44
|
+
readonly access?: 'Editor' | 'Reader';
|
|
45
|
+
}): Request;
|
|
46
|
+
/** Connects through the core; returns the server-side socket (what the room holds). */
|
|
47
|
+
export declare function connect(core: RoomCore, fake: FakeRoom, request: Request): Promise<FakeSocket>;
|
|
48
|
+
export declare const member: (userId: string, name: string, session?: string) => LiveUser;
|
|
49
|
+
export declare const GUEST: LiveUser;
|
|
50
|
+
/**
|
|
51
|
+
* A Yjs client over a fake doc socket, speaking y-websocket's format: it
|
|
52
|
+
* answers the server's sync step 1, sends its own, forwards local updates,
|
|
53
|
+
* and applies what the server sends. `pump()` delivers the server's frames.
|
|
54
|
+
*/
|
|
55
|
+
export declare function yClient(core: RoomCore, socket: FakeSocket, field: string): {
|
|
56
|
+
doc: Y.Doc;
|
|
57
|
+
awareness: awarenessProtocol.Awareness;
|
|
58
|
+
text: () => string;
|
|
59
|
+
type: (at: number, value: string) => void;
|
|
60
|
+
denied: string[];
|
|
61
|
+
/** Sends sync step 1 (what a provider does on open). */
|
|
62
|
+
start: () => void;
|
|
63
|
+
announce: (state: Record<string, unknown>) => void;
|
|
64
|
+
/** Waits for in-flight sends, then applies every new server frame (repeat until quiet). */
|
|
65
|
+
pump: () => Promise<void>;
|
|
66
|
+
};
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite';
|
|
2
|
+
import * as decoding from 'lib0/decoding';
|
|
3
|
+
import * as encoding from 'lib0/encoding';
|
|
4
|
+
import * as awarenessProtocol from 'y-protocols/awareness';
|
|
5
|
+
import * as syncProtocol from 'y-protocols/sync';
|
|
6
|
+
import * as Y from 'yjs';
|
|
7
|
+
import { IDENTITY_HEADER, } from '../live/server/index.js';
|
|
8
|
+
export function fakeSocket() {
|
|
9
|
+
let attachment = null;
|
|
10
|
+
const sent = [];
|
|
11
|
+
const socket = {
|
|
12
|
+
sent,
|
|
13
|
+
tags: [],
|
|
14
|
+
closed: undefined,
|
|
15
|
+
send: (message) => {
|
|
16
|
+
if (socket.closed)
|
|
17
|
+
throw new Error('closed');
|
|
18
|
+
sent.push(typeof message === 'string'
|
|
19
|
+
? message
|
|
20
|
+
: new Uint8Array(message));
|
|
21
|
+
},
|
|
22
|
+
close: (code, reason) => {
|
|
23
|
+
socket.closed = { code, reason };
|
|
24
|
+
},
|
|
25
|
+
serializeAttachment: (value) => {
|
|
26
|
+
const text = JSON.stringify(value);
|
|
27
|
+
if (text.length > 2048)
|
|
28
|
+
throw new Error(`attachment over 2 KB: ${text.length}`);
|
|
29
|
+
attachment = JSON.parse(text);
|
|
30
|
+
},
|
|
31
|
+
deserializeAttachment: () => attachment,
|
|
32
|
+
json: () => sent
|
|
33
|
+
.filter((m) => typeof m === 'string' && m.startsWith('{'))
|
|
34
|
+
.map((m) => JSON.parse(m)),
|
|
35
|
+
};
|
|
36
|
+
return socket;
|
|
37
|
+
}
|
|
38
|
+
export function fakeRoom(db = new Database(':memory:')) {
|
|
39
|
+
const sockets = [];
|
|
40
|
+
let now = Date.UTC(2026, 11, 5, 12, 0, 0);
|
|
41
|
+
const timers = [];
|
|
42
|
+
const room = {
|
|
43
|
+
db,
|
|
44
|
+
sockets,
|
|
45
|
+
alarm: null,
|
|
46
|
+
state: {
|
|
47
|
+
acceptWebSocket: (socket, tags) => {
|
|
48
|
+
;
|
|
49
|
+
socket.tags.push(...(tags ?? []));
|
|
50
|
+
sockets.push(socket);
|
|
51
|
+
},
|
|
52
|
+
getWebSockets: (tag) => sockets.filter((s) => !s.closed && (tag === undefined || s.tags.includes(tag))),
|
|
53
|
+
setWebSocketAutoResponse: () => { },
|
|
54
|
+
storage: {
|
|
55
|
+
sql: {
|
|
56
|
+
exec: (query, ...bindings) => {
|
|
57
|
+
const statement = db.query(query);
|
|
58
|
+
const rows = /^\s*(SELECT|INSERT[\s\S]*RETURNING)/i.test(query)
|
|
59
|
+
? statement.all(...bindings)
|
|
60
|
+
: (statement.run(...bindings), []);
|
|
61
|
+
return { toArray: () => rows };
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
transactionSync: (fn) => db.transaction(fn)(),
|
|
65
|
+
getAlarm: async () => room.alarm,
|
|
66
|
+
setAlarm: async (at) => {
|
|
67
|
+
room.alarm = at;
|
|
68
|
+
},
|
|
69
|
+
deleteAlarm: async () => {
|
|
70
|
+
room.alarm = null;
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
runtime: {
|
|
75
|
+
newPair: () => {
|
|
76
|
+
const client = fakeSocket();
|
|
77
|
+
const server = fakeSocket();
|
|
78
|
+
return { client, server };
|
|
79
|
+
},
|
|
80
|
+
switchingProtocols: (client) => Object.assign(new Response(null, { status: 200 }), {
|
|
81
|
+
socket: client,
|
|
82
|
+
}),
|
|
83
|
+
autoResponse: () => ({}),
|
|
84
|
+
now: () => now,
|
|
85
|
+
setTimeout: (fn, ms) => {
|
|
86
|
+
timers.push({ at: now + ms, fn });
|
|
87
|
+
return timers.length;
|
|
88
|
+
},
|
|
89
|
+
randomId: () => crypto.randomUUID(),
|
|
90
|
+
},
|
|
91
|
+
advance: (ms) => {
|
|
92
|
+
now += ms;
|
|
93
|
+
},
|
|
94
|
+
tick: (ms = 0) => {
|
|
95
|
+
now += ms;
|
|
96
|
+
const due = timers.filter((t) => t.at <= now);
|
|
97
|
+
for (const t of due)
|
|
98
|
+
timers.splice(timers.indexOf(t), 1);
|
|
99
|
+
for (const t of due)
|
|
100
|
+
t.fn();
|
|
101
|
+
},
|
|
102
|
+
live: () => sockets.filter((s) => !s.closed),
|
|
103
|
+
tables: () => db
|
|
104
|
+
.query("SELECT name FROM sqlite_master WHERE type = 'table'")
|
|
105
|
+
.all().map((r) => r.name),
|
|
106
|
+
};
|
|
107
|
+
return room;
|
|
108
|
+
}
|
|
109
|
+
let peerCounter = 0;
|
|
110
|
+
/** A request as the Worker route forwards it to the room. */
|
|
111
|
+
export function roomRequest(room, user, options = {}) {
|
|
112
|
+
peerCounter += 1;
|
|
113
|
+
const identity = {
|
|
114
|
+
peer: `peer-${peerCounter}`,
|
|
115
|
+
user,
|
|
116
|
+
access: options.access ?? 'Reader',
|
|
117
|
+
socket: options.doc === undefined
|
|
118
|
+
? { _tag: 'Room' }
|
|
119
|
+
: { _tag: 'Doc', doc: options.doc },
|
|
120
|
+
room,
|
|
121
|
+
};
|
|
122
|
+
return new Request(`https://x/live/room/${room.type}/${room.key}`, {
|
|
123
|
+
headers: { [IDENTITY_HEADER]: JSON.stringify(identity) },
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
/** Connects through the core; returns the server-side socket (what the room holds). */
|
|
127
|
+
export async function connect(core, fake, request) {
|
|
128
|
+
const before = fake.sockets.length;
|
|
129
|
+
const response = await core.fetch(request);
|
|
130
|
+
if (fake.sockets.length === before)
|
|
131
|
+
throw new Error(`refused: ${response.status}`);
|
|
132
|
+
return fake.sockets[fake.sockets.length - 1];
|
|
133
|
+
}
|
|
134
|
+
export const member = (userId, name, session = `sess-${userId}`) => ({
|
|
135
|
+
_tag: 'Member',
|
|
136
|
+
userId,
|
|
137
|
+
name,
|
|
138
|
+
session,
|
|
139
|
+
});
|
|
140
|
+
export const GUEST = { _tag: 'Guest' };
|
|
141
|
+
/**
|
|
142
|
+
* A Yjs client over a fake doc socket, speaking y-websocket's format: it
|
|
143
|
+
* answers the server's sync step 1, sends its own, forwards local updates,
|
|
144
|
+
* and applies what the server sends. `pump()` delivers the server's frames.
|
|
145
|
+
*/
|
|
146
|
+
export function yClient(core, socket, field) {
|
|
147
|
+
const doc = new Y.Doc();
|
|
148
|
+
const awareness = new awarenessProtocol.Awareness(doc);
|
|
149
|
+
let read = 0;
|
|
150
|
+
const pending = [];
|
|
151
|
+
const send = (frame) => {
|
|
152
|
+
pending.push(core.message(socket, frame.buffer.slice(frame.byteOffset, frame.byteOffset + frame.byteLength)));
|
|
153
|
+
};
|
|
154
|
+
doc.on('update', (update, origin) => {
|
|
155
|
+
if (origin === 'server')
|
|
156
|
+
return;
|
|
157
|
+
const encoder = encoding.createEncoder();
|
|
158
|
+
encoding.writeVarUint(encoder, 0);
|
|
159
|
+
syncProtocol.writeUpdate(encoder, update);
|
|
160
|
+
send(encoding.toUint8Array(encoder));
|
|
161
|
+
});
|
|
162
|
+
const client = {
|
|
163
|
+
doc,
|
|
164
|
+
awareness,
|
|
165
|
+
text: () => doc.getText(field).toString(),
|
|
166
|
+
type: (at, value) => doc.getText(field).insert(at, value),
|
|
167
|
+
denied: [],
|
|
168
|
+
/** Sends sync step 1 (what a provider does on open). */
|
|
169
|
+
start: () => {
|
|
170
|
+
const encoder = encoding.createEncoder();
|
|
171
|
+
encoding.writeVarUint(encoder, 0);
|
|
172
|
+
syncProtocol.writeSyncStep1(encoder, doc);
|
|
173
|
+
send(encoding.toUint8Array(encoder));
|
|
174
|
+
},
|
|
175
|
+
announce: (state) => {
|
|
176
|
+
awareness.setLocalState(state);
|
|
177
|
+
const encoder = encoding.createEncoder();
|
|
178
|
+
encoding.writeVarUint(encoder, 1);
|
|
179
|
+
encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(awareness, [
|
|
180
|
+
doc.clientID,
|
|
181
|
+
]));
|
|
182
|
+
send(encoding.toUint8Array(encoder));
|
|
183
|
+
},
|
|
184
|
+
/** Waits for in-flight sends, then applies every new server frame (repeat until quiet). */
|
|
185
|
+
pump: async () => {
|
|
186
|
+
for (let round = 0; round < 5; round += 1) {
|
|
187
|
+
await Promise.all(pending.splice(0));
|
|
188
|
+
const frames = socket.sent
|
|
189
|
+
.slice(read)
|
|
190
|
+
.filter((m) => typeof m !== 'string');
|
|
191
|
+
read = socket.sent.length;
|
|
192
|
+
if (frames.length === 0 && pending.length === 0)
|
|
193
|
+
return;
|
|
194
|
+
for (const frame of frames) {
|
|
195
|
+
const decoder = decoding.createDecoder(frame);
|
|
196
|
+
const type = decoding.readVarUint(decoder);
|
|
197
|
+
if (type === 0) {
|
|
198
|
+
const encoder = encoding.createEncoder();
|
|
199
|
+
encoding.writeVarUint(encoder, 0);
|
|
200
|
+
syncProtocol.readSyncMessage(decoder, encoder, doc, 'server');
|
|
201
|
+
if (encoding.length(encoder) > 1)
|
|
202
|
+
send(encoding.toUint8Array(encoder));
|
|
203
|
+
}
|
|
204
|
+
else if (type === 1) {
|
|
205
|
+
awarenessProtocol.applyAwarenessUpdate(awareness, decoding.readVarUint8Array(decoder), 'server');
|
|
206
|
+
}
|
|
207
|
+
else if (type === 2) {
|
|
208
|
+
decoding.readVarUint(decoder);
|
|
209
|
+
client.denied.push(decoding.readVarString(decoder));
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
},
|
|
214
|
+
};
|
|
215
|
+
return client;
|
|
216
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Tagged } from '../logic/result.ts';
|
|
2
|
+
export interface Story<Model, Msg, Cmd> {
|
|
3
|
+
send(msg: Msg): Story<Model, Msg, Cmd>;
|
|
4
|
+
expectModel(check: (model: Model) => void): Story<Model, Msg, Cmd>;
|
|
5
|
+
expectCommands(expected: readonly Cmd[]): Story<Model, Msg, Cmd>;
|
|
6
|
+
model(): Model;
|
|
7
|
+
lastCommands(): readonly Cmd[];
|
|
8
|
+
allCommands(): readonly Cmd[];
|
|
9
|
+
}
|
|
10
|
+
type UpdateWithCommands<Model, Msg, Cmd> = (model: Model, msg: Msg) => readonly [Model, readonly Cmd[]];
|
|
11
|
+
type UpdatePlain<Model, Msg> = (model: Model, msg: Msg) => Model;
|
|
12
|
+
/**
|
|
13
|
+
* Foldkit-style 0ms test runner for pure `update` state machines.
|
|
14
|
+
* Zero DOM, zero JSX, zero timers.
|
|
15
|
+
*/
|
|
16
|
+
export declare function story<Model, Msg, Cmd extends Tagged>(update: UpdateWithCommands<Model, Msg, Cmd>, init: Model): Story<Model, Msg, Cmd>;
|
|
17
|
+
export declare function story<Model, Msg>(update: UpdatePlain<Model, Msg>, init: Model): Story<Model, Msg, never>;
|
|
18
|
+
export * from './fake-bindings.ts';
|
|
19
|
+
export * from './fake-room.ts';
|