dewdrop-sdk 0.5.5 → 0.6.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 +4 -3
- package/package.json +2 -2
- package/src/index.js +9 -40
- package/src/message.js +4 -0
- package/src/vite.js +13 -98
- package/src/backend-host.js +0 -17
- package/src/backend.js +0 -103
- package/src/clients.js +0 -104
- package/src/dev.js +0 -122
- package/src/env.js +0 -40
- package/src/evaluate.js +0 -57
- package/src/fresh.js +0 -103
- package/src/llm.js +0 -96
- package/src/net.js +0 -165
- package/src/providers.js +0 -20
- package/src/route.js +0 -36
- package/src/saves.js +0 -254
- package/src/serve.js +0 -203
- package/src/session.js +0 -47
- package/src/voice.js +0 -135
package/README.md
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
# dewdrop-sdk
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
calls, multiplayer, saves and voice.
|
|
3
|
+
The Vite plugin that builds a three.js game for Dewdrop, and the name a game
|
|
4
|
+
imports model calls, multiplayer, saves, sessions and voice from. Dewdrop
|
|
5
|
+
supplies those where the game runs; this package carries only the build.
|
|
5
6
|
|
|
6
|
-
How to set up a project and everything
|
|
7
|
+
How to set up a project and everything a game can do is in the docs:
|
|
7
8
|
https://alpha.dewdrop.world/docs
|
|
8
9
|
|
|
9
10
|
## License
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dewdrop-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "The Vite plugin that builds a three.js game for Dewdrop.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"exports": {
|
package/src/index.js
CHANGED
|
@@ -1,41 +1,10 @@
|
|
|
1
|
-
// `dewdrop-sdk`
|
|
2
|
-
// `
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
|
|
8
|
-
// none does, lets a game end its player's session, which here ends
|
|
9
|
-
// nothing, and lets a game allow portrait views, which here the browser's
|
|
10
|
-
// window already gives; and `voice` reads the microphone through the browser's own
|
|
11
|
-
// audio worklet, into the chunks a game gets on Dewdrop.
|
|
12
|
-
export { llm } from './llm.js';
|
|
13
|
-
export { backend } from './backend.js';
|
|
14
|
-
export { clients } from './clients.js';
|
|
15
|
-
export { session } from './session.js';
|
|
16
|
-
export { voice } from './voice.js';
|
|
17
|
-
import { attachBackend, joining } from './backend.js';
|
|
18
|
-
import { load, save } from './saves.js';
|
|
1
|
+
// `dewdrop-sdk` as a game imports it: `llm`, `backend`, `clients`, `player`,
|
|
2
|
+
// `saves`, `session` and `voice`, which Dewdrop supplies where the game
|
|
3
|
+
// runs. A build with the plugin from `./vite` leaves the import to
|
|
4
|
+
// Dewdrop, so this file is reached only by a page built without the plugin
|
|
5
|
+
// or served by something else, which has none of them and is told so. The names are declared so the page's
|
|
6
|
+
// imports link and the error is what it sees.
|
|
7
|
+
import { ON_DEWDROP } from './message.js';
|
|
19
8
|
|
|
20
|
-
export
|
|
21
|
-
|
|
22
|
-
// Where the page's URL joins this tab: `player` is the label it names —
|
|
23
|
-
// on Dewdrop, the player's username — the empty string when it names none
|
|
24
|
-
// and always in a backend's thread, where there is no location.
|
|
25
|
-
const joined = joining(typeof location === 'undefined' ? '' : location.search);
|
|
26
|
-
export const player = joined.player;
|
|
27
|
-
|
|
28
|
-
// A page served by the dev server joins its room's backend as it loads,
|
|
29
|
-
// told by the plugin whether the game has one; a built game, or one
|
|
30
|
-
// served by something else, has no channel and says so when it sends.
|
|
31
|
-
if (typeof document !== 'undefined' && import.meta.hot) {
|
|
32
|
-
const meta = document.querySelector('meta[name="dew-backend"]');
|
|
33
|
-
attachBackend(import.meta.hot, {
|
|
34
|
-
channel: meta !== null,
|
|
35
|
-
hasBackend: meta?.content === 'yes',
|
|
36
|
-
frame: (fn) => requestAnimationFrame(fn),
|
|
37
|
-
room: joined.room,
|
|
38
|
-
player: joined.player,
|
|
39
|
-
players: joined.players,
|
|
40
|
-
});
|
|
41
|
-
}
|
|
9
|
+
export let llm, backend, clients, player, saves, session, voice;
|
|
10
|
+
throw new Error(ON_DEWDROP);
|
package/src/message.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// What a page served outside Dewdrop is told, by the stub `.` entry when it
|
|
2
|
+
// is evaluated and by the plugin when Vite's dev server starts: the game
|
|
3
|
+
// plays on Dewdrop, where `npm run dev` uploads it.
|
|
4
|
+
export const ON_DEWDROP = 'dewdrop-sdk runs on Dewdrop: play the game with npm run dev, which uploads it to Dewdrop';
|
package/src/vite.js
CHANGED
|
@@ -1,25 +1,16 @@
|
|
|
1
|
-
// The Vite plugin
|
|
2
|
-
//
|
|
3
|
-
//
|
|
1
|
+
// The Vite plugin: every `vite build` is a Dewdrop build — three and the
|
|
2
|
+
// SDK left as imports for Dewdrop to supply, one chunk of ES modules with
|
|
3
|
+
// dynamic imports folded in, written as `main.js` at the top of the
|
|
4
4
|
// output, no module preload, a root base, the files Vite emits under
|
|
5
5
|
// `ui/`, and the built page opened in the document by the entry; a game
|
|
6
|
-
// with a backend gets a second chunk beside it, `backend.js`.
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
|
|
11
|
-
// untouched. The plugin
|
|
12
|
-
// imports nothing from Vite itself, so it works linked from a checkout as
|
|
13
|
-
// well as installed, on Vite 3 through 8.
|
|
14
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
6
|
+
// with a backend gets a second chunk beside it, `backend.js`. Vite's dev
|
|
7
|
+
// server is refused, since a game plays on Dewdrop alone: the refusal
|
|
8
|
+
// says where. The plugin imports nothing from Vite itself, so it works
|
|
9
|
+
// linked from a checkout as well as installed, on Vite 3 through 8.
|
|
10
|
+
import { existsSync } from 'node:fs';
|
|
15
11
|
import { resolve } from 'node:path';
|
|
16
12
|
import { ASSETS_DIR, BACKEND_FILE, ENTRY_FILE, PAGE_FILE, detectViteMajor, openPage, outputOptions } from './build.js';
|
|
17
|
-
import {
|
|
18
|
-
import { loadKeys } from './env.js';
|
|
19
|
-
import { evaluateScript } from './evaluate.js';
|
|
20
|
-
import { freshScript } from './fresh.js';
|
|
21
|
-
import { DEV_ROUTE } from './route.js';
|
|
22
|
-
import { createBackendHost } from './serve.js';
|
|
13
|
+
import { ON_DEWDROP } from './message.js';
|
|
23
14
|
|
|
24
15
|
// The imports Dewdrop supplies, left in the output: three and the paths
|
|
25
16
|
// into it, and the SDK by its name. Dewdrop supplies nothing else, a path
|
|
@@ -28,8 +19,6 @@ export function isRuntimeModule(id) {
|
|
|
28
19
|
return id === 'three' || id.startsWith('three/') || id === 'dewdrop-sdk';
|
|
29
20
|
}
|
|
30
21
|
|
|
31
|
-
export const DEW_MODE = 'dew';
|
|
32
|
-
|
|
33
22
|
// Where a project's backend is: `backend.js` at the root, else
|
|
34
23
|
// `src/backend.js`, else none.
|
|
35
24
|
export function backendEntry(root) {
|
|
@@ -40,53 +29,15 @@ export function backendEntry(root) {
|
|
|
40
29
|
return null;
|
|
41
30
|
}
|
|
42
31
|
|
|
43
|
-
// `html` with `script` run before anything of the page's own: first in
|
|
44
|
-
// the page, right after its prologue, which comes before every element
|
|
45
|
-
// and runs nothing, so never in a template, a comment or a script of the
|
|
46
|
-
// page's. A prologue is read as a browser reads it: a byte order mark,
|
|
47
|
-
// whitespace, comments — ended by `-->` or `--!>`, or at once as `<!-->`
|
|
48
|
-
// or `<!--->` — and the doctype and any other `<!` or `<?`, ended by the
|
|
49
|
-
// first `>`. A `<meta charset>` of UTF-8, the encoding Vite serves every
|
|
50
|
-
// page in, leads the script: a browser looks for one in a page's first
|
|
51
|
-
// bytes, which the script fills.
|
|
52
|
-
const PROLOGUE = /^\uFEFF?(?:[\t\n\f\r ]+|<!--(?:-?>|[\s\S]*?(?:--!?>|$))|<[!?][^>]*(?:>|$))*/;
|
|
53
|
-
export function withFirstScript(html, script) {
|
|
54
|
-
const at = PROLOGUE.exec(html)[0].length;
|
|
55
|
-
return `${html.slice(0, at)}<meta charset="utf-8"><script>${script}</script>${html.slice(at)}`;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// The game a project's dewdrop.json names, which the dev server keeps its
|
|
59
|
-
// saves under: a name as Dewdrop takes one, else none.
|
|
60
|
-
const GAME_NAME = /^[a-z][a-z0-9-]{0,47}$/;
|
|
61
|
-
export function projectGame(root) {
|
|
62
|
-
try {
|
|
63
|
-
const { game } = JSON.parse(readFileSync(resolve(root, 'dewdrop.json'), 'utf8'));
|
|
64
|
-
return typeof game === 'string' && GAME_NAME.test(game) ? game : '';
|
|
65
|
-
} catch {
|
|
66
|
-
return '';
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
32
|
export default function dew() {
|
|
71
|
-
let dewBuild = false;
|
|
72
|
-
let serving = false;
|
|
73
|
-
let entry = null;
|
|
74
|
-
let game = '';
|
|
75
|
-
// The dev server's backend host, from the server's start to its close.
|
|
76
|
-
let host = null;
|
|
77
33
|
return {
|
|
78
34
|
name: 'dew',
|
|
79
35
|
config(userConfig, env) {
|
|
36
|
+
// Said in the terminal, where the developer typed `vite`, rather than
|
|
37
|
+
// left to the page's console.
|
|
38
|
+
if (env.command === 'serve') throw new Error(ON_DEWDROP);
|
|
80
39
|
const root = userConfig.root ?? process.cwd();
|
|
81
|
-
entry = backendEntry(root);
|
|
82
|
-
dewBuild = env.mode === DEW_MODE;
|
|
83
|
-
serving = env.command === 'serve';
|
|
84
|
-
game = serving ? projectGame(root) : '';
|
|
85
|
-
if (!dewBuild) {
|
|
86
|
-
// Served as source, so the hot context the client's `backend`
|
|
87
|
-
// joins over is injected as in the game's own modules.
|
|
88
|
-
return env.command === 'serve' ? { optimizeDeps: { exclude: ['dewdrop-sdk'] } } : undefined;
|
|
89
|
-
}
|
|
40
|
+
const entry = backendEntry(root);
|
|
90
41
|
const major = detectViteMajor(root);
|
|
91
42
|
const config = {
|
|
92
43
|
base: '/',
|
|
@@ -132,7 +83,6 @@ export default function dew() {
|
|
|
132
83
|
generateBundle: {
|
|
133
84
|
order: 'post',
|
|
134
85
|
handler(_options, bundle) {
|
|
135
|
-
if (!dewBuild) return;
|
|
136
86
|
const chunk = bundle[ENTRY_FILE];
|
|
137
87
|
if (chunk === undefined || chunk.type !== 'chunk') return;
|
|
138
88
|
const page = bundle[PAGE_FILE];
|
|
@@ -141,40 +91,5 @@ export default function dew() {
|
|
|
141
91
|
chunk.code = openPage(html) + chunk.code;
|
|
142
92
|
},
|
|
143
93
|
},
|
|
144
|
-
// The page the dev server serves is told whether the game has a
|
|
145
|
-
// backend, which the client's `backend` reads before it joins, starts
|
|
146
|
-
// with its storage empty, as on Dewdrop, and offers `dewdrop.evaluate`,
|
|
147
|
-
// as a dev version's page does, from a script first in the page,
|
|
148
|
-
// before anything of its own.
|
|
149
|
-
// A build's page, which no dev server serves, is left alone.
|
|
150
|
-
transformIndexHtml(html) {
|
|
151
|
-
if (!serving) return undefined;
|
|
152
|
-
return {
|
|
153
|
-
html: withFirstScript(html, freshScript(game) + evaluateScript()),
|
|
154
|
-
tags: [{ tag: 'meta', attrs: { name: 'dew-backend', content: entry === null ? 'no' : 'yes' }, injectTo: 'head' }],
|
|
155
|
-
};
|
|
156
|
-
},
|
|
157
|
-
configureServer(server) {
|
|
158
|
-
// The keys come from the project's own .env files and the
|
|
159
|
-
// environment, every variable rather than the VITE_-prefixed ones a
|
|
160
|
-
// page may see.
|
|
161
|
-
const env = loadKeys(server.config.envDir ?? server.config.root, server.config.mode);
|
|
162
|
-
server.middlewares.use(DEV_ROUTE, createLlmMiddleware({ env }));
|
|
163
|
-
if (entry === null) return;
|
|
164
|
-
host = createBackendHost({
|
|
165
|
-
entry,
|
|
166
|
-
ws: server.ws,
|
|
167
|
-
watcher: server.watcher,
|
|
168
|
-
origin: () => server.resolvedUrls?.local?.[0]?.replace(/\/$/, '') ?? server.config.server?.origin ?? '',
|
|
169
|
-
});
|
|
170
|
-
},
|
|
171
|
-
// The dev server closing — in middleware mode too, which has no HTTP
|
|
172
|
-
// server of its own — ends every room: a backend left running for an
|
|
173
|
-
// empty room would hold the process open past the server it served.
|
|
174
|
-
// A build's close has no host to end.
|
|
175
|
-
closeBundle() {
|
|
176
|
-
host?.close();
|
|
177
|
-
host = null;
|
|
178
|
-
},
|
|
179
94
|
};
|
|
180
95
|
}
|
package/src/backend-host.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
// The thread the plugin runs a project's backend.js in: it serves the
|
|
2
|
-
// clients over the port to the plugin, tells the model call where the dev
|
|
3
|
-
// server is, loads the game's backend, whose `dewdrop-sdk` resolves to this
|
|
4
|
-
// package as the plugin's own does, and only then starts delivering what
|
|
5
|
-
// the clients sent, so the first join reaches the handlers the module
|
|
6
|
-
// registered. A throw while the backend evaluates ends the thread, which
|
|
7
|
-
// the host reports and stops; a throw in a handler or a timer after that
|
|
8
|
-
// is logged and the backend goes on.
|
|
9
|
-
import { parentPort, workerData } from 'node:worker_threads';
|
|
10
|
-
import { pathToFileURL } from 'node:url';
|
|
11
|
-
import { attachClients } from './clients.js';
|
|
12
|
-
|
|
13
|
-
process.env.DEW_DEV_ORIGIN = workerData.origin;
|
|
14
|
-
const start = attachClients(parentPort, { capacity: workerData.capacity });
|
|
15
|
-
await import(pathToFileURL(workerData.entry).href);
|
|
16
|
-
process.on('uncaughtException', (error) => console.error(`uncaught ${error?.stack ?? error}`));
|
|
17
|
-
start();
|
package/src/backend.js
DELETED
|
@@ -1,103 +0,0 @@
|
|
|
1
|
-
// `backend` on a developer's machine: the client's side of the messages a
|
|
2
|
-
// game exchanges with its backend, carried here over the Vite dev server's
|
|
3
|
-
// socket to the backend.js the plugin runs beside it, so a game's code is
|
|
4
|
-
// the same here and on Dewdrop. A frame's sends leave together at the next
|
|
5
|
-
// animation frame; what the backend sends arrives at the next animation
|
|
6
|
-
// frame as `message` events, or one `gap` where the inbox dropped messages
|
|
7
|
-
// past its cap. The page's URL says which room the tab joins and under
|
|
8
|
-
// what name; on Dewdrop the game's page says which room, and the name is
|
|
9
|
-
// the player's username.
|
|
10
|
-
import { DEFAULT_ROOM_PLAYERS, MAX_NET_CLIENTS, MAX_NET_CLIENT_FRAME_BYTES, createInbox, createOutbox, defineHandlers, label, side, unpack } from './net.js';
|
|
11
|
-
import { NO_CHANNEL } from './route.js';
|
|
12
|
-
|
|
13
|
-
let channel = null;
|
|
14
|
-
let hasBackend = false;
|
|
15
|
-
let frame = null;
|
|
16
|
-
const outbox = createOutbox(MAX_NET_CLIENT_FRAME_BYTES);
|
|
17
|
-
const inbox = createInbox();
|
|
18
|
-
let flushing = false;
|
|
19
|
-
let draining = false;
|
|
20
|
-
|
|
21
|
-
class Backend extends EventTarget {
|
|
22
|
-
send(data) {
|
|
23
|
-
if (side.backend) throw new DOMException('backend is unavailable in a backend', 'NotSupportedError');
|
|
24
|
-
if (channel === null) throw new TypeError(`backend.send: ${NO_CHANNEL}`);
|
|
25
|
-
if (!hasBackend) throw new DOMException('backend is unavailable: this game has no backend.js', 'NotSupportedError');
|
|
26
|
-
outbox.push('backend.send', 0, data);
|
|
27
|
-
if (flushing) return;
|
|
28
|
-
flushing = true;
|
|
29
|
-
frame(() => {
|
|
30
|
-
flushing = false;
|
|
31
|
-
channel.send('dew:send', { items: outbox.flush() });
|
|
32
|
-
});
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
defineHandlers(Backend.prototype, ['message', 'gap']);
|
|
36
|
-
|
|
37
|
-
export const backend = new Backend();
|
|
38
|
-
|
|
39
|
-
function deliver() {
|
|
40
|
-
draining = false;
|
|
41
|
-
for (const record of inbox.drain()) {
|
|
42
|
-
backend.dispatchEvent(record.kind === 'gap' ? new Event('gap') : new MessageEvent('message', { data: unpack(record) }));
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// A room as Dewdrop names one: lowercase letters, digits, and dashes, up
|
|
47
|
-
// to 32, a name typed in capitals or with space around it being the same
|
|
48
|
-
// room; anything else names no room.
|
|
49
|
-
const ROOM_KEY = /^[a-z0-9-]{1,32}$/;
|
|
50
|
-
function room(text) {
|
|
51
|
-
const key = text.trim().toLowerCase();
|
|
52
|
-
return ROOM_KEY.test(key) ? key : '';
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
// A name as Dewdrop takes one: control characters removed, trimmed, then
|
|
56
|
-
// cut to the label's cap.
|
|
57
|
-
function name(text) {
|
|
58
|
-
return label(text.replace(/\p{Cc}/gu, '').trim());
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// The players a room seats as `?players=` names them: a whole number from
|
|
62
|
-
// 1 to MAX_NET_CLIENTS, or DEFAULT_ROOM_PLAYERS without one or with any other.
|
|
63
|
-
function players(text) {
|
|
64
|
-
return /^[0-9]{1,3}$/.test(text) && Number(text) >= 1 && Number(text) <= MAX_NET_CLIENTS ? Number(text) : DEFAULT_ROOM_PLAYERS;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
// Where a page's URL joins its tab: the room `?room=` names, the name
|
|
68
|
-
// `?player=` names, and the players `?players=` says the room seats should
|
|
69
|
-
// the tab make it, each held to Dewdrop's rule — the empty room without
|
|
70
|
-
// one, or with one that names no room; unnamed without a name, or with one
|
|
71
|
-
// that is nothing but space and control characters.
|
|
72
|
-
export function joining(search) {
|
|
73
|
-
const params = new URLSearchParams(search);
|
|
74
|
-
return { room: room(params.get('room') ?? ''), player: name(params.get('player') ?? ''), players: players(params.get('players') ?? '') };
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
// Whether the page's game has a backend, as the plugin said; false until
|
|
78
|
-
// it has.
|
|
79
|
-
export function gameHasBackend() {
|
|
80
|
-
return hasBackend;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
// Joins the backend of `room` under `player`'s name over `hot`, the page's
|
|
84
|
-
// hot context, once the plugin has said whether the game has one, a room
|
|
85
|
-
// it makes seating `players`: `present` is that, `schedule` runs a
|
|
86
|
-
// function at the next animation frame. Without a plugin there is no
|
|
87
|
-
// channel, and `send` says so. A room that seats no more says so in the
|
|
88
|
-
// console, as Dewdrop refuses the connect, and the tab's sends reach no one.
|
|
89
|
-
export function attachBackend(hot, { channel: routed, hasBackend: present, frame: schedule, room = '', player = '', players = DEFAULT_ROOM_PLAYERS }) {
|
|
90
|
-
if (!routed) return;
|
|
91
|
-
channel = hot;
|
|
92
|
-
hasBackend = present;
|
|
93
|
-
frame = schedule;
|
|
94
|
-
if (!present) return;
|
|
95
|
-
hot.on('dew:recv', ({ items }) => {
|
|
96
|
-
inbox.receive(items.map((item) => ({ kind: 'message', ...item })));
|
|
97
|
-
if (draining) return;
|
|
98
|
-
draining = true;
|
|
99
|
-
frame(deliver);
|
|
100
|
-
});
|
|
101
|
-
hot.on('dew:full', ({ capacity }) => console.error(`[dewdrop] this room is full: it seats ${capacity === 1 ? '1 player' : `${capacity} players`}`));
|
|
102
|
-
hot.send('dew:join', { room, player, players });
|
|
103
|
-
}
|
package/src/clients.js
DELETED
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
// `clients` on a developer's machine: the backend's side of the messages a
|
|
2
|
-
// game exchanges with its clients, and the most players its room seats,
|
|
3
|
-
// run by the plugin in a thread of the dev server with a port to the
|
|
4
|
-
// plugin, which carries each message over the socket to the tab it names. The thread ticks sixty times a second:
|
|
5
|
-
// each tick delivers what the clients sent as `join`, `leave`, `message`,
|
|
6
|
-
// and `gap` events — a join naming the player's label — runs the
|
|
7
|
-
// animation-frame callbacks, and sends the frame's messages.
|
|
8
|
-
import { MAX_NET_BACKEND_FRAME_BYTES, MAX_NET_CLIENTS, NET_TICK_MS, ClientEvent, createInbox, createOutbox, defineHandlers, side, unpack } from './net.js';
|
|
9
|
-
|
|
10
|
-
const outbox = createOutbox(MAX_NET_BACKEND_FRAME_BYTES);
|
|
11
|
-
const inbox = createInbox();
|
|
12
|
-
let port = null;
|
|
13
|
-
let seats = 0;
|
|
14
|
-
|
|
15
|
-
// A client number as the backend was told it: a whole number from one.
|
|
16
|
-
function number(op, value) {
|
|
17
|
-
if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > 0xffffffff) {
|
|
18
|
-
throw new TypeError(`${op}: client is not a client number`);
|
|
19
|
-
}
|
|
20
|
-
return value;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
class Clients extends EventTarget {
|
|
24
|
-
send(to, data) {
|
|
25
|
-
if (port === null) throw new DOMException('clients is unavailable in a client', 'NotSupportedError');
|
|
26
|
-
outbox.push('clients.send', number('clients.send', to), data);
|
|
27
|
-
}
|
|
28
|
-
broadcast(data) {
|
|
29
|
-
if (port === null) throw new DOMException('clients is unavailable in a client', 'NotSupportedError');
|
|
30
|
-
outbox.push('clients.broadcast', 0, data);
|
|
31
|
-
}
|
|
32
|
-
// The most players the room seats, as it was made: 1 for a room of one,
|
|
33
|
-
// a player counted once however many clients they play from.
|
|
34
|
-
get capacity() {
|
|
35
|
-
if (port === null) throw new DOMException('clients is unavailable in a client', 'NotSupportedError');
|
|
36
|
-
return seats;
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
defineHandlers(Clients.prototype, ['join', 'leave', 'message', 'gap']);
|
|
40
|
-
|
|
41
|
-
export const clients = new Clients();
|
|
42
|
-
|
|
43
|
-
// The animation-frame callbacks, run once each tick; installed when the
|
|
44
|
-
// thread has none of its own.
|
|
45
|
-
const callbacks = new Map();
|
|
46
|
-
let nextCallback = 1;
|
|
47
|
-
function requestAnimationFrame(fn) {
|
|
48
|
-
if (typeof fn !== 'function') throw new TypeError("Failed to execute 'requestAnimationFrame': parameter 1 is not of type 'Function'");
|
|
49
|
-
const id = nextCallback++;
|
|
50
|
-
callbacks.set(id, fn);
|
|
51
|
-
return id;
|
|
52
|
-
}
|
|
53
|
-
function cancelAnimationFrame(id) {
|
|
54
|
-
callbacks.delete(id);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
function frame() {
|
|
58
|
-
for (const record of inbox.drain()) {
|
|
59
|
-
switch (record.kind) {
|
|
60
|
-
case 'join': clients.dispatchEvent(new ClientEvent('join', { client: record.client, player: record.player ?? '' })); break;
|
|
61
|
-
case 'leave': clients.dispatchEvent(new ClientEvent('leave', { client: record.client })); break;
|
|
62
|
-
case 'message': clients.dispatchEvent(new ClientEvent('message', { client: record.client, data: unpack(record) })); break;
|
|
63
|
-
default: clients.dispatchEvent(new Event('gap'));
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
const due = [...callbacks.values()];
|
|
67
|
-
callbacks.clear();
|
|
68
|
-
const now = performance.now();
|
|
69
|
-
for (const fn of due) {
|
|
70
|
-
// A callback that throws is logged and the rest run, as in a browser.
|
|
71
|
-
try {
|
|
72
|
-
fn(now);
|
|
73
|
-
} catch (error) {
|
|
74
|
-
console.error(`uncaught ${error?.stack ?? error}`);
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
const sends = outbox.flush();
|
|
78
|
-
if (sends.length !== 0) port.postMessage({ kind: 'send', sends });
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
// Serves the clients over `channel`, the port to the plugin's host, from
|
|
82
|
-
// now on: what comes in is a record per message — `{kind, client, ...}` —
|
|
83
|
-
// held until the returned function starts the ticks, which the host calls
|
|
84
|
-
// once the backend has evaluated, so the first tick delivers what arrived
|
|
85
|
-
// meanwhile, the first join included, to the handlers the module
|
|
86
|
-
// registered. `tick` runs the frame once per tick from then on, and
|
|
87
|
-
// `capacity` is the most players the room seats.
|
|
88
|
-
export function attachClients(channel, { tick = (fn) => setInterval(fn, NET_TICK_MS), capacity = MAX_NET_CLIENTS } = {}) {
|
|
89
|
-
port = channel;
|
|
90
|
-
seats = capacity;
|
|
91
|
-
side.backend = true;
|
|
92
|
-
if (typeof globalThis.requestAnimationFrame !== 'function') {
|
|
93
|
-
globalThis.requestAnimationFrame = requestAnimationFrame;
|
|
94
|
-
globalThis.cancelAnimationFrame = cancelAnimationFrame;
|
|
95
|
-
}
|
|
96
|
-
// A backend has no view: its viewport reads zero.
|
|
97
|
-
globalThis.innerWidth ??= 0;
|
|
98
|
-
globalThis.innerHeight ??= 0;
|
|
99
|
-
port.on('message', (records) => inbox.receive(records));
|
|
100
|
-
return function start() {
|
|
101
|
-
frame();
|
|
102
|
-
tick(frame);
|
|
103
|
-
};
|
|
104
|
-
}
|
package/src/dev.js
DELETED
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
// The dev server's model-call route, its stand-in for Dewdrop. It takes
|
|
2
|
-
// the envelope `llm.fetch` posts — the provider URL, method, headers, and
|
|
3
|
-
// body — adds the key from the developer's environment, sends the call,
|
|
4
|
-
// and answers with the provider's status, content type, and body, or a
|
|
5
|
-
// reason in the `x-dew-error` header for a call that got no response, as
|
|
6
|
-
// Dewdrop refuses one. Asked with GET, it names the providers it holds
|
|
7
|
-
// keys for.
|
|
8
|
-
import { LLM_TIMEOUT_MS, MAX_LLM_REQUEST_BYTES, MAX_LLM_RESPONSE_BYTES, PROVIDERS } from './providers.js';
|
|
9
|
-
import { ROUTE_HEADER } from './route.js';
|
|
10
|
-
|
|
11
|
-
// Headers the transport sets for itself, dropped from the game's request.
|
|
12
|
-
const HOP_HEADERS = ['host', 'content-length', 'transfer-encoding', 'connection', 'expect'];
|
|
13
|
-
|
|
14
|
-
function readBody(req, limit) {
|
|
15
|
-
return new Promise((resolve, reject) => {
|
|
16
|
-
const chunks = [];
|
|
17
|
-
let length = 0;
|
|
18
|
-
req.on('data', (chunk) => {
|
|
19
|
-
length += chunk.length;
|
|
20
|
-
if (length > limit) {
|
|
21
|
-
reject(new Error(`a call is at most ${MAX_LLM_REQUEST_BYTES} bytes with its headers and body`));
|
|
22
|
-
req.destroy();
|
|
23
|
-
return;
|
|
24
|
-
}
|
|
25
|
-
chunks.push(chunk);
|
|
26
|
-
});
|
|
27
|
-
req.on('end', () => resolve(Buffer.concat(chunks)));
|
|
28
|
-
req.on('error', reject);
|
|
29
|
-
});
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function refuse(res, status, reason) {
|
|
33
|
-
res.statusCode = status;
|
|
34
|
-
res.setHeader('x-dew-error', reason);
|
|
35
|
-
res.setHeader('content-type', 'text/plain');
|
|
36
|
-
res.end(reason);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
// Where a host's calls go: the provider's own origin, or a test's listener.
|
|
40
|
-
function originFor(origins, host) {
|
|
41
|
-
return origins[host] ?? `https://${host}`;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
// `env` holds the keys by variable name; `fetch` sends the call; `origins`
|
|
45
|
-
// maps a provider host to a stand-in for tests. The returned function is
|
|
46
|
-
// connect middleware, as Vite's server takes it.
|
|
47
|
-
export function createLlmMiddleware({ env = process.env, fetch = globalThis.fetch, origins = {} } = {}) {
|
|
48
|
-
return async (req, res) => {
|
|
49
|
-
// Every answer says it came from this route, refusals included.
|
|
50
|
-
res.setHeader(ROUTE_HEADER, 'llm');
|
|
51
|
-
// GET names the providers with a key; POST carries a call.
|
|
52
|
-
if (req.method === 'GET') {
|
|
53
|
-
const hosts = PROVIDERS.filter((provider) => env[provider.keyVar]).map((provider) => provider.host);
|
|
54
|
-
res.statusCode = 200;
|
|
55
|
-
res.setHeader('content-type', 'application/json');
|
|
56
|
-
res.end(JSON.stringify({ hosts }));
|
|
57
|
-
return;
|
|
58
|
-
}
|
|
59
|
-
if (req.method !== 'POST') {
|
|
60
|
-
refuse(res, 405, 'the model-call route takes GET or POST');
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
let envelope;
|
|
64
|
-
try {
|
|
65
|
-
// The envelope carries the body as base64, so the byte budget leaves
|
|
66
|
-
// room for its expansion and the JSON around it.
|
|
67
|
-
envelope = JSON.parse((await readBody(req, MAX_LLM_REQUEST_BYTES * 2)).toString('utf8'));
|
|
68
|
-
} catch (error) {
|
|
69
|
-
refuse(res, 400, error.message);
|
|
70
|
-
return;
|
|
71
|
-
}
|
|
72
|
-
let url;
|
|
73
|
-
try {
|
|
74
|
-
url = new URL(envelope.url);
|
|
75
|
-
} catch {
|
|
76
|
-
refuse(res, 400, `${envelope.url} is not a URL`);
|
|
77
|
-
return;
|
|
78
|
-
}
|
|
79
|
-
const provider = url.protocol === 'https:' && !url.port && !url.username && !url.password
|
|
80
|
-
? PROVIDERS.find((each) => each.host === url.hostname)
|
|
81
|
-
: undefined;
|
|
82
|
-
if (provider === undefined) {
|
|
83
|
-
refuse(res, 502, `${url.origin} is not a model provider Dewdrop carries calls to`);
|
|
84
|
-
return;
|
|
85
|
-
}
|
|
86
|
-
const key = env[provider.keyVar];
|
|
87
|
-
if (!key) {
|
|
88
|
-
refuse(res, 502, `no key for ${provider.host}: set ${provider.keyVar}`);
|
|
89
|
-
return;
|
|
90
|
-
}
|
|
91
|
-
const headers = new Headers();
|
|
92
|
-
for (const [name, value] of envelope.headers ?? []) {
|
|
93
|
-
const lower = String(name).toLowerCase();
|
|
94
|
-
if (HOP_HEADERS.includes(lower) || lower === provider.header) continue;
|
|
95
|
-
headers.set(lower, String(value));
|
|
96
|
-
}
|
|
97
|
-
headers.set(provider.header, provider.prefix + key);
|
|
98
|
-
const body = Buffer.from(String(envelope.body ?? ''), 'base64');
|
|
99
|
-
let upstream;
|
|
100
|
-
try {
|
|
101
|
-
upstream = await fetch(originFor(origins, provider.host) + url.pathname + url.search, {
|
|
102
|
-
method: envelope.method,
|
|
103
|
-
headers,
|
|
104
|
-
body: body.length > 0 ? body : undefined,
|
|
105
|
-
redirect: 'manual',
|
|
106
|
-
signal: AbortSignal.timeout(LLM_TIMEOUT_MS),
|
|
107
|
-
});
|
|
108
|
-
} catch (error) {
|
|
109
|
-
refuse(res, 502, `${provider.host}: ${error.message}`);
|
|
110
|
-
return;
|
|
111
|
-
}
|
|
112
|
-
const answer = Buffer.from(await upstream.arrayBuffer());
|
|
113
|
-
if (answer.length > MAX_LLM_RESPONSE_BYTES) {
|
|
114
|
-
refuse(res, 502, `${provider.host}: the response is past ${MAX_LLM_RESPONSE_BYTES} bytes`);
|
|
115
|
-
return;
|
|
116
|
-
}
|
|
117
|
-
res.statusCode = upstream.status;
|
|
118
|
-
const type = upstream.headers.get('content-type');
|
|
119
|
-
if (type !== null) res.setHeader('content-type', type);
|
|
120
|
-
res.end(answer);
|
|
121
|
-
};
|
|
122
|
-
}
|
package/src/env.js
DELETED
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
// The keys the dev route reads: the project's .env files in Vite's order,
|
|
2
|
-
// then the environment, parsed here so the plugin imports nothing from
|
|
3
|
-
// Vite and works linked from a checkout as well as installed.
|
|
4
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
5
|
-
import { join } from 'node:path';
|
|
6
|
-
|
|
7
|
-
// The variables in one `.env` file: `KEY=VALUE` lines, `#` comments,
|
|
8
|
-
// optional quotes; nothing expanded.
|
|
9
|
-
export function parseDotenv(text) {
|
|
10
|
-
const out = {};
|
|
11
|
-
for (const raw of text.split(/\r?\n/)) {
|
|
12
|
-
const line = raw.trim();
|
|
13
|
-
if (line === '' || line.startsWith('#')) continue;
|
|
14
|
-
const at = line.indexOf('=');
|
|
15
|
-
if (at <= 0) continue;
|
|
16
|
-
const key = line.slice(0, at).trim().replace(/^export\s+/, '');
|
|
17
|
-
let value = line.slice(at + 1).trim();
|
|
18
|
-
// A quoted value runs to its closing quote, whatever follows; a bare
|
|
19
|
-
// one runs to a comment.
|
|
20
|
-
const quoted = value.match(/^(["'])(.*?)\1/);
|
|
21
|
-
if (quoted) value = quoted[2];
|
|
22
|
-
else {
|
|
23
|
-
const comment = value.indexOf(' #');
|
|
24
|
-
if (comment >= 0) value = value.slice(0, comment).trim();
|
|
25
|
-
}
|
|
26
|
-
out[key] = value;
|
|
27
|
-
}
|
|
28
|
-
return out;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
// The environment the route reads keys from: the project's `.env` files
|
|
32
|
-
// in Vite's order, then the process's own, which wins.
|
|
33
|
-
export function loadKeys(root, mode) {
|
|
34
|
-
const env = {};
|
|
35
|
-
for (const name of ['.env', '.env.local', `.env.${mode}`, `.env.${mode}.local`]) {
|
|
36
|
-
const path = join(root, name);
|
|
37
|
-
if (existsSync(path)) Object.assign(env, parseDotenv(readFileSync(path, 'utf8')));
|
|
38
|
-
}
|
|
39
|
-
return { ...env, ...process.env };
|
|
40
|
-
}
|