dewctl 0.8.1 → 0.9.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 +69 -0
- package/examples/AGENTS.md +3 -1
- package/package.json +1 -1
- package/src/client.js +35 -0
- package/src/logs.js +58 -0
- package/src/main.js +144 -17
- package/src/project.js +28 -6
- package/src/session.js +137 -0
- package/src/sourcemap.js +124 -0
- package/src/watch.js +28 -8
package/README.md
CHANGED
|
@@ -6,6 +6,75 @@ and publishes it for players.
|
|
|
6
6
|
Getting started, every command, `dewdrop.json` and troubleshooting are in the
|
|
7
7
|
docs: https://alpha.dewdrop.world/docs
|
|
8
8
|
|
|
9
|
+
## Logs and seat passes
|
|
10
|
+
|
|
11
|
+
`dewctl logs` prints the dev version's recent console (the game's page and
|
|
12
|
+
backend lines, and how each seat's session ended), with positions in the built
|
|
13
|
+
code shown in your source by the last build's source maps; `--follow` keeps
|
|
14
|
+
printing. `dewctl dev` prints the same at a terminal and with `--watch`. Source
|
|
15
|
+
maps (`.map` files) are never uploaded: they stay on your computer.
|
|
16
|
+
|
|
17
|
+
`dewctl seat --out .dewdrop-seat.json` gets a seat pass, which opens the dev
|
|
18
|
+
version in a browser your own tools drive, and writes it to a file only you can
|
|
19
|
+
read. Keep the file outside the bundle folder — dewctl refuses a path inside
|
|
20
|
+
it, as the pass would be uploaded with the game — and out of version control;
|
|
21
|
+
a dot-file in the game's folder, as here, is also one `dewctl dev --watch`
|
|
22
|
+
doesn't rebuild for. Get a new pass at the start of each test run, right after
|
|
23
|
+
an upload: it works once, within 10 minutes. Set its `cookie` with your browser
|
|
24
|
+
tool for its `url` — the cookie names no domain, so it goes to Dewdrop's host
|
|
25
|
+
alone — then open the `url`. Without `--out` the pass is printed, to pipe into
|
|
26
|
+
your tool — where a terminal log or a CI log can keep it. For example, in a
|
|
27
|
+
script that drives Chrome with Puppeteer:
|
|
28
|
+
|
|
29
|
+
```js
|
|
30
|
+
const pass = JSON.parse(readFileSync('.dewdrop-seat.json', 'utf8'));
|
|
31
|
+
await page.setCookie({...pass.cookie, url: pass.url});
|
|
32
|
+
await page.goto(pass.url);
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Playwright takes a cookie's `url` or its `path`, not both:
|
|
36
|
+
|
|
37
|
+
```js
|
|
38
|
+
const {path, ...cookie} = pass.cookie;
|
|
39
|
+
await context.addCookies([{...cookie, url: pass.url}]);
|
|
40
|
+
await page.goto(pass.url);
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Your live seats
|
|
44
|
+
|
|
45
|
+
With a seat of yours playing the dev version — a tab you opened, or a browser
|
|
46
|
+
your tools drive with a seat pass — dewctl reaches it from the terminal, as the
|
|
47
|
+
page's own console does. It reaches only your own seats, in the dev version,
|
|
48
|
+
and never starts one.
|
|
49
|
+
|
|
50
|
+
- `dewctl sessions` lists your seats playing, newest first. The newest is the
|
|
51
|
+
one the commands below use unless `--seat` names another.
|
|
52
|
+
- `dewctl eval '<code>'` evaluates code in the seat's page (`--backend`: its
|
|
53
|
+
room's backend) and prints its value as JSON; `-` reads the code from
|
|
54
|
+
standard input and `@file.js` from a file, and after `--` code may start
|
|
55
|
+
with `-` (`dewctl eval -- -1`). An error prints its message and
|
|
56
|
+
stack in your source, by the last build's source maps, and exits 1.
|
|
57
|
+
`--json` prints `{"value":…}`, `{"error":"…"}` or `{}` (undefined).
|
|
58
|
+
- `dewctl pause` and `dewctl resume` stop and start the seat's room — its
|
|
59
|
+
backend and every seat in it; `dewctl step 60` advances the paused room 60
|
|
60
|
+
frames and returns once they are drawn; `dewctl speed 0.25` runs it at a
|
|
61
|
+
quarter speed (at most 1).
|
|
62
|
+
- `dewctl repl` evaluates each line you type; `.pause`, `.resume`, `.step N`,
|
|
63
|
+
`.speed K`, `.seat S`, `.backend`, `.page`, `.help` and `.exit` do what they
|
|
64
|
+
say.
|
|
65
|
+
|
|
66
|
+
A loop an agent might run — upload, seat, pause, look, step, look, resume:
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
dewctl dev
|
|
70
|
+
dewctl seat --out .dewdrop-seat.json # the agent's browser tool sets the cookie and opens the url
|
|
71
|
+
dewctl pause
|
|
72
|
+
dewctl eval 'player.position'
|
|
73
|
+
dewctl step 60
|
|
74
|
+
dewctl eval 'player.position'
|
|
75
|
+
dewctl resume
|
|
76
|
+
```
|
|
77
|
+
|
|
9
78
|
## License
|
|
10
79
|
|
|
11
80
|
MIT
|
package/examples/AGENTS.md
CHANGED
|
@@ -114,7 +114,9 @@ at a time, so you know what each change did.
|
|
|
114
114
|
- `dewdrop.json` connects the folder to the game: its name, the build command, the folder the build writes, and
|
|
115
115
|
the thumbnail ([dewdrop.json](https://alpha.dewdrop.world/docs/dewdrop-json)).
|
|
116
116
|
- `npm run dev` uploads the game to its dev version on Dewdrop once; `npx dewctl dev --watch` uploads it again on
|
|
117
|
-
every save. `npx dewctl
|
|
117
|
+
every save. `npx dewctl logs` prints the dev version's recent console, page and backend, with positions in the
|
|
118
|
+
game's source. `npx dewctl seat --out <file>` gets a pass for a browser a script drives: one use, within 10 minutes
|
|
119
|
+
of getting it, so get a new one for each run. `npx dewctl status` shows both versions. Run `npx dewctl publish` only when the user asks: it puts the game
|
|
118
120
|
in front of players ([commands](https://alpha.dewdrop.world/docs/cli)).
|
|
119
121
|
- `LOOK.md` is the agreed look. In a starter game, README.md says how the game works and why its look works.
|
|
120
122
|
Read both first.
|
package/package.json
CHANGED
package/src/client.js
CHANGED
|
@@ -202,6 +202,41 @@ export class Client {
|
|
|
202
202
|
}
|
|
203
203
|
// Sets the game's thumbnail to the image, sent as itself under its type.
|
|
204
204
|
thumbnail(game,bytes,type,signal){return this.api(`/v1/games/${game}/thumbnail`,{method:'PUT',body:bytes,type,signal});}
|
|
205
|
+
// The dev version's console lines after `after`, held up to `wait` ms for new ones. A refusal says why in the
|
|
206
|
+
// developer's terms.
|
|
207
|
+
devLogs(game,after,wait,signal){return this.#dev(game,`logs?after=${after}&wait=${wait}`,{signal});}
|
|
208
|
+
// A seat pass for the dev version: one use, within minutes, by whatever the developer's own tools are.
|
|
209
|
+
seat(game,signal){return this.#dev(game,'seat',{method:'POST',body:{},signal});}
|
|
210
|
+
async #dev(game,path,options) {
|
|
211
|
+
try { return await this.api(`/v1/games/${game}/dev/${path}`,options); }
|
|
212
|
+
catch(error) {
|
|
213
|
+
const said={
|
|
214
|
+
403:`Only ${game}'s owner and the developers it's shared with can use its dev version.`,
|
|
215
|
+
404:`${game} isn't on Dewdrop yet. Run ${RUN} dev to create it.`,
|
|
216
|
+
429:path==='seat'?'You\'ve reached your account\'s limit on seat passes and the seats they open. Try again later.':'Dewdrop is asked for the console too often. Try again in a moment.',
|
|
217
|
+
503:`${game} has no dev version running. Run ${RUN} dev to start it.`,
|
|
218
|
+
}[error.status];
|
|
219
|
+
if(said===undefined||error.status===401)throw error;
|
|
220
|
+
throw new ApiError(error.status,said,error.body);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
// The developer's own seats playing the dev version, newest first: `{sessions:[{seat, room}]}`.
|
|
224
|
+
sessions(game,signal){return this.#control(game,'sessions',{signal});}
|
|
225
|
+
// Code for seat `seat` of the dev version to evaluate, or with `backend` its room's backend: `{value}`, `{error}`, or
|
|
226
|
+
// `{}` for undefined.
|
|
227
|
+
evaluate(game,seat,code,backend,signal){return this.#control(game,`sessions/${encodeURIComponent(seat)}/evaluate`,{method:'POST',body:{code,backend},signal});}
|
|
228
|
+
// Pauses, resumes, steps (`{frames}`) or slows (`{k}`) room `room`: `{frame, paused}`.
|
|
229
|
+
room(game,room,action,fields,signal){return this.#control(game,`rooms/${encodeURIComponent(room)}/${action}`,{method:'POST',body:fields,signal});}
|
|
230
|
+
// A control of the developer's own seats. Dewdrop's own words say what was wrong — which seat or room, what to run —
|
|
231
|
+
// but for a Dewdrop from before these routes, and a refusal to someone not on the game.
|
|
232
|
+
async #control(game,path,options) {
|
|
233
|
+
try { return await this.api(`/v1/games/${game}/dev/${path}`,options); }
|
|
234
|
+
catch(error) {
|
|
235
|
+
if(error.status===405||(error.status===404&&error.message==='Route not found'))throw new ApiError(error.status,'This Dewdrop can\'t control dev sessions from the CLI yet. Try again later.',error.body);
|
|
236
|
+
if(error.status===403)throw new ApiError(403,`Only ${game}'s owner and the developers it's shared with can use its dev version.`,error.body);
|
|
237
|
+
throw error;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
205
240
|
async member(game,email,on,signal) {
|
|
206
241
|
if(!EMAIL.test(email??''))throw new Error("Pass the developer's email address, for example dev@example.com.");
|
|
207
242
|
return this.api(`/v1/games/${game}/members/${email}`,on?{method:'PUT',body:{},signal}:{method:'DELETE',signal});
|
package/src/logs.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// The dev version's console as Dewdrop keeps it — the game's page and backend lines and how each seat's session ended —
|
|
2
|
+
// printed a line each, with every position in the built code read back to the game's source.
|
|
3
|
+
import {sleep} from './client.js';
|
|
4
|
+
|
|
5
|
+
// How long a request asks Dewdrop to hold it for new lines, and the longest rest after failures in a row.
|
|
6
|
+
const WAIT_MS=25000,MOST_REST_MS=30000;
|
|
7
|
+
// The characters but tab and line breaks that a terminal takes as commands rather than text, shown as `?`.
|
|
8
|
+
export const CONTROL=/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g;
|
|
9
|
+
const two=n=>String(n).padStart(2,'0');
|
|
10
|
+
// A line as printed: this computer's time of it, where it came from — the page of a seat, named by its player, the
|
|
11
|
+
// backend, or a seat's session — its level, and its text, positions mapped by `maps` for the release that wrote it.
|
|
12
|
+
export function format(line,maps) {
|
|
13
|
+
const at=new Date(line.at),time=Number.isNaN(at.getTime())?'':`${two(at.getHours())}:${two(at.getMinutes())}:${two(at.getSeconds())} `;
|
|
14
|
+
const text=maps?maps.text(line.release,String(line.text)):String(line.text);
|
|
15
|
+
return `${time}[${line.source}${line.seat?` ${line.seat}`:''}] ${line.level}: ${text}`.replace(CONTROL,'?');
|
|
16
|
+
}
|
|
17
|
+
// Prints `game`'s dev console from the start of what Dewdrop keeps: those lines alone, or with `follow` each new line
|
|
18
|
+
// as it comes until `signal` ends it, starting again from the start when the dev version restarts. Following, a
|
|
19
|
+
// Dewdrop that can't be reached, a dev version not running and a limit reached are waited out, resting longer after
|
|
20
|
+
// each failure in a row; any other refusal, or any refusal at all without `follow`, is thrown. `note` says what
|
|
21
|
+
// happened to the lines rather than printing one.
|
|
22
|
+
export async function printLogs(client,game,{signal,follow=false,maps,log=console.log,note=log,restMs=1000,waitMs=WAIT_MS}={}) {
|
|
23
|
+
let after=0,failures=0,printed=0,restarts=0;
|
|
24
|
+
while(!signal?.aborted) {
|
|
25
|
+
const asked=Date.now();
|
|
26
|
+
let answer;
|
|
27
|
+
try { answer=await client.devLogs(game,after,follow?waitMs:0,signal); }
|
|
28
|
+
catch(error) {
|
|
29
|
+
if(signal?.aborted)break;
|
|
30
|
+
if(!follow||!(error.transient||[429,503].includes(error.status)||error.status>=500))throw error;
|
|
31
|
+
if(!failures++)note(error.status===503?`Waiting for ${game}'s dev version to run…`:`${error.message} Following again once Dewdrop answers.`);
|
|
32
|
+
try { await sleep(Math.min(restMs*2**(failures-1),MOST_REST_MS),signal); } catch { break; }
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
failures=0;
|
|
36
|
+
const lines=Array.isArray(answer.lines)?answer.lines:[];
|
|
37
|
+
if(answer.restarted) {
|
|
38
|
+
// Without `follow`, a dev version that keeps restarting under the read gives what it had.
|
|
39
|
+
if(!follow&&++restarts>2)break;
|
|
40
|
+
if(follow&&after>0)note(`(${game}'s dev version restarted.)`);
|
|
41
|
+
after=0;
|
|
42
|
+
} else {
|
|
43
|
+
if(answer.lost>0)note(`(${answer.lost} line${answer.lost===1?' was':'s were'} dropped here, written faster than Dewdrop keeps them)`);
|
|
44
|
+
for(const line of lines)log(format(line,maps));
|
|
45
|
+
printed+=lines.length;
|
|
46
|
+
const next=Number.isSafeInteger(answer.next)?answer.next:after;
|
|
47
|
+
if(!follow&&(!lines.length||next<=after))break;
|
|
48
|
+
after=next;
|
|
49
|
+
}
|
|
50
|
+
// An answer with nothing new that came at once is asked again after a rest, so a Dewdrop that doesn't hold the
|
|
51
|
+
// request isn't asked in a loop.
|
|
52
|
+
if(follow&&!lines.length) {
|
|
53
|
+
const left=restMs-(Date.now()-asked);
|
|
54
|
+
if(left>0)try { await sleep(left,signal); } catch { break; }
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if(!follow&&!printed&&!signal?.aborted)note(`${game}'s dev version has no console lines yet.`);
|
|
58
|
+
}
|
package/src/main.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Dewdrop's developer commands: sign in, connect a directory to a game, then run, publish, share and inspect it.
|
|
3
3
|
import {spawn} from 'node:child_process';
|
|
4
|
-
import {readFileSync} from 'node:fs';
|
|
5
|
-
import {
|
|
4
|
+
import {readFileSync,writeFileSync,renameSync,rmSync} from 'node:fs';
|
|
5
|
+
import {randomBytes} from 'node:crypto';
|
|
6
|
+
import {readProject,platformOrigin,initProject,chooseTemplate,projectPath,insideBundle,DEWDROP,GAME_NAME} from './project.js';
|
|
6
7
|
import {Credentials} from './credentials.js';
|
|
7
8
|
import {Client} from './client.js';
|
|
8
9
|
import {deploy,watch,size} from './watch.js';
|
|
@@ -10,6 +11,9 @@ import {devPlayUrl} from './play.js';
|
|
|
10
11
|
import {signInLink,waitForApproval} from './login.js';
|
|
11
12
|
import {RUN} from './command.js';
|
|
12
13
|
import {syncThumbnail} from './thumbnail.js';
|
|
14
|
+
import {SourceMaps} from './sourcemap.js';
|
|
15
|
+
import {printLogs} from './logs.js';
|
|
16
|
+
import {findSeat,seatTable,codeOf,shown,machine,roomLine,frames,factor,repl} from './session.js';
|
|
13
17
|
|
|
14
18
|
const HELP=`${RUN} — make three.js games on Dewdrop
|
|
15
19
|
|
|
@@ -21,7 +25,37 @@ const HELP=`${RUN} — make three.js games on Dewdrop
|
|
|
21
25
|
login Sign in: prints a link to open in your browser and approve
|
|
22
26
|
logout Sign this computer out
|
|
23
27
|
dev [--watch] [--release ID] Build, upload and play the dev version; --watch repeats this on every
|
|
24
|
-
save, --release plays a kept upload without building
|
|
28
|
+
save, --release plays a kept upload without building. At a terminal, and
|
|
29
|
+
with --watch, dev then prints the dev version's console as logs --follow
|
|
30
|
+
does, until Ctrl-C. The build's source maps (.map files) are never
|
|
31
|
+
uploaded: they stay on this computer
|
|
32
|
+
logs [GAME] [--follow] Print the dev version's recent console: the game's page and backend lines,
|
|
33
|
+
and how each seat's session ended. Positions in the built code are shown
|
|
34
|
+
in your source, by the last build's source maps. --follow keeps printing
|
|
35
|
+
new lines until Ctrl-C
|
|
36
|
+
seat [GAME] [--out FILE] Get a seat pass, which opens the dev version in a browser your own tools
|
|
37
|
+
drive. Get a new one at the start of each test run, right after an
|
|
38
|
+
upload: it works once, within 10 minutes. Set its cookie in your browser
|
|
39
|
+
tool for its url — it names no domain — then open the url. --out writes
|
|
40
|
+
it to FILE, readable by you alone, and prints the path and when it
|
|
41
|
+
expires. Use a dot-file in the game's folder, such as .dewdrop-seat.json,
|
|
42
|
+
and keep it out of version control: a FILE in the bundle folder is
|
|
43
|
+
refused, as it would be uploaded. Without --out the pass is printed to
|
|
44
|
+
standard output, where logs can keep it
|
|
45
|
+
sessions [GAME] [--json] List your own seats playing the dev version, newest first: the newest is
|
|
46
|
+
the one eval, pause, resume, step, speed and repl use without --seat
|
|
47
|
+
eval [GAME] [--seat S] [--backend] [--json] CODE
|
|
48
|
+
Evaluate CODE in your seat's page, or with --backend its room's backend,
|
|
49
|
+
and print its value as JSON. CODE is the code itself, - for standard
|
|
50
|
+
input, or @FILE; after --, code starting with - (eval -- -1). An error
|
|
51
|
+
prints its message and stack in your source,
|
|
52
|
+
and exits 1. --json prints {"value":…}, {"error":"…"} or {} (undefined)
|
|
53
|
+
pause [GAME] [--seat S] [--json] Pause your seat's room: its backend and every seat in it
|
|
54
|
+
resume [GAME] [--seat S] [--json] Resume it
|
|
55
|
+
step [GAME] [--seat S] [--json] N Advance the paused room N frames (1 to 600), once they are drawn
|
|
56
|
+
speed [GAME] [--seat S] [--json] K Run the room at K times its speed: above 0, at most 1
|
|
57
|
+
repl [GAME] [--seat S] [--backend] Evaluate each line you type in your seat. .pause, .resume, .step N,
|
|
58
|
+
.speed K, .seat S, .backend, .page, .help and .exit do what they say
|
|
25
59
|
stop Stop the dev version and disconnect its players
|
|
26
60
|
publish [--release ID] Publish the dev version, or an earlier upload, for players; uploads
|
|
27
61
|
the thumbnail dewdrop.json names when it has changed
|
|
@@ -37,30 +71,63 @@ const HELP=`${RUN} — make three.js games on Dewdrop
|
|
|
37
71
|
can't be undone (owner only)
|
|
38
72
|
--version Show this CLI's version
|
|
39
73
|
|
|
40
|
-
Run the commands in your game's folder: they read the game from its dewdrop.json.
|
|
74
|
+
Run the commands in your game's folder: they read the game from its dewdrop.json. logs, seat, sessions,
|
|
75
|
+
eval, pause, resume, step, speed and repl also take the name of a game you develop. Those that reach your
|
|
76
|
+
seats reach only your own, in the dev version, and none starts one: open one in a browser first.
|
|
77
|
+
|
|
78
|
+
A coding agent driving the game, for example:
|
|
79
|
+
${RUN} dev && ${RUN} seat --out .dewdrop-seat.json upload, and get a pass for its browser tool
|
|
80
|
+
${RUN} pause && ${RUN} eval 'player.position' && ${RUN} step 60 && ${RUN} eval 'player.position'
|
|
81
|
+
dewctl resume
|
|
41
82
|
Docs: ${DEWDROP}/docs
|
|
42
83
|
`;
|
|
43
|
-
// Each command's flags; share and unshare also take one address, delete one release
|
|
44
|
-
//
|
|
45
|
-
|
|
46
|
-
const
|
|
84
|
+
// Each command's flags; share and unshare also take one address, delete one release, delete-game the game's name,
|
|
85
|
+
// logs, seat and the seat commands (SEATED) a game's name, eval its code, step its frames and speed its factor. Anything
|
|
86
|
+
// else on the line is refused.
|
|
87
|
+
const COMMANDS={init:['--game','--template'],login:[],logout:[],dev:['--watch','--release'],stop:[],publish:['--release'],unpublish:[],share:[],unshare:[],status:[],releases:[],delete:[],'delete-game':[],logs:['--follow'],seat:['--out'],sessions:['--json'],eval:['--seat','--backend','--json'],pause:['--seat','--json'],resume:['--seat','--json'],step:['--seat','--json'],speed:['--seat','--json'],repl:['--seat','--backend']};
|
|
88
|
+
const VALUED=['--game','--template','--release','--out','--seat'];
|
|
89
|
+
// The commands that reach the developer's own seats, and the one value each takes after the game's name.
|
|
90
|
+
const SEATED={sessions:null,eval:'code',pause:null,resume:null,step:'frames',speed:'k',repl:null};
|
|
47
91
|
function options(command,args) {
|
|
48
92
|
const out={};
|
|
93
|
+
// After `--`, a seat command's words are words whatever they start with: code such as -1 is evaluated, not read as a flag.
|
|
94
|
+
let words=false;
|
|
49
95
|
for(let i=0;i<args.length;i++) {
|
|
50
96
|
const key=args[i];
|
|
51
|
-
if(
|
|
97
|
+
if(key==='--'&&Object.hasOwn(SEATED,command)&&!words){words=true;continue;}
|
|
98
|
+
if(words&&(out.words??=[]).length<(SEATED[command]?2:1))out.words.push(key);
|
|
99
|
+
else if(words)throw new Error(`${command} doesn't take ${key}. Run ${RUN} --help to see what it takes.`);
|
|
100
|
+
else if(COMMANDS[command].includes(key)) {
|
|
52
101
|
if(!VALUED.includes(key))out[key.slice(2)]=true;
|
|
53
102
|
else if(!args[i+1]||args[i+1].startsWith('--'))throw new Error(`${key} needs a value.`);
|
|
54
103
|
else out[key.slice(2)]=args[++i];
|
|
55
104
|
} else if(['share','unshare'].includes(command)&&!key.startsWith('-')&&out.email===undefined)out.email=key;
|
|
56
105
|
else if(command==='delete'&&!key.startsWith('-')&&out.release===undefined)out.release=key;
|
|
57
106
|
else if(command==='delete-game'&&!key.startsWith('-')&&out.name===undefined)out.name=key;
|
|
107
|
+
else if(['logs','seat'].includes(command)&&!key.startsWith('-')&&out.game===undefined)out.game=key;
|
|
108
|
+
// A seat command's words: its game's name, then its value — a lone word is the value for a command that takes one.
|
|
109
|
+
else if(Object.hasOwn(SEATED,command)&&(!key.startsWith('-')||key==='-')&&(out.words??=[]).length<(SEATED[command]?2:1))out.words.push(key);
|
|
58
110
|
else throw new Error(`${command} doesn't take ${key}. Run ${RUN} --help to see what it takes.`);
|
|
59
111
|
}
|
|
60
112
|
if(out.release!==undefined&&!/^[a-f0-9]{8,64}$/.test(out.release))throw new Error(`${command==='delete'?'delete':'--release'} takes a release id, or its first 8 or more characters, from ${RUN} releases.`);
|
|
61
113
|
if(out.watch&&out.release)throw new Error('Choose --watch or --release, not both.');
|
|
114
|
+
if(Object.hasOwn(SEATED,command)) {
|
|
115
|
+
const words=out.words??[],value=SEATED[command];
|
|
116
|
+
delete out.words;
|
|
117
|
+
if(value&&!words.length)throw new Error(`${command} needs ${{code:'the code to evaluate, - for standard input, or @FILE',frames:'a number of frames',k:'a speed factor'}[value]}.`);
|
|
118
|
+
if(words.length>(value?1:0))out.game=words[0];
|
|
119
|
+
if(value)out[value]=words.at(-1);
|
|
120
|
+
}
|
|
121
|
+
if((['logs','seat'].includes(command)||Object.hasOwn(SEATED,command))&&out.game!==undefined&&!GAME_NAME.test(out.game))throw new Error(`${out.game} isn't a game's name: a name is 1–48 lowercase letters, digits or dashes, starting with a letter.`);
|
|
62
122
|
return out;
|
|
63
123
|
}
|
|
124
|
+
// Writes `text` to `file` readable and writable by this user alone, whatever was there: a new file beside it, then
|
|
125
|
+
// moved into its place, so a file or link already at the path is replaced rather than written through.
|
|
126
|
+
function writePrivate(file,text) {
|
|
127
|
+
const temporary=`${file}.${randomBytes(6).toString('hex')}.tmp`;
|
|
128
|
+
try { writeFileSync(temporary,text,{mode:0o600,flag:'wx'}); renameSync(temporary,file); }
|
|
129
|
+
catch(error) { rmSync(temporary,{force:true}); throw new Error(`Couldn't write ${file} (${error.code??error.message}).`); }
|
|
130
|
+
}
|
|
64
131
|
// Opens the link in this computer's browser. login prints the link too, so a browser that won't start is no failure.
|
|
65
132
|
function open(url) {
|
|
66
133
|
const command=process.platform==='darwin'?'open':'xdg-open';
|
|
@@ -89,7 +156,9 @@ async function main() {
|
|
|
89
156
|
// The paths, permissions and processes the CLI relies on are POSIX ones.
|
|
90
157
|
if(process.platform==='win32')throw new Error('The Dewdrop CLI runs on macOS and Linux. On Windows, run it inside WSL (Windows Subsystem for Linux).');
|
|
91
158
|
const [command,...args]=process.argv.slice(2);
|
|
92
|
-
|
|
159
|
+
// Help is asked before `--` alone: after it, -h is code.
|
|
160
|
+
const flagged=args.includes('--')?args.slice(0,args.indexOf('--')):args;
|
|
161
|
+
if(!command||['--help','help','-h'].includes(command)||flagged.some(arg=>arg==='--help'||arg==='-h')){console.log(HELP);return;}
|
|
93
162
|
if(['--version','-v','version'].includes(command)){console.log(JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version);return;}
|
|
94
163
|
if(!Object.hasOwn(COMMANDS,command))throw new Error(`There's no ${command} command. Run ${RUN} --help to see them.`);
|
|
95
164
|
const flags=options(command,args);
|
|
@@ -102,15 +171,18 @@ async function main() {
|
|
|
102
171
|
if(!config.starter&&!config.buildScript)console.log('No build script is in package.json, so dewdrop.json builds with npm run build. Add one that runs vite build with the Dewdrop plugin in vite.config.js, or set "build" in dewdrop.json to your own command.');
|
|
103
172
|
return;
|
|
104
173
|
}
|
|
105
|
-
// Every command but init reads the game from the project's dewdrop.json
|
|
106
|
-
|
|
174
|
+
// Every command but init reads the game from the project's dewdrop.json; logs, seat and the seat commands may name
|
|
175
|
+
// the game instead, and then work in any folder.
|
|
176
|
+
let project=null;
|
|
177
|
+
try { project=readProject(process.cwd()); }
|
|
178
|
+
catch(error) { if(flags.game===undefined)throw error; }
|
|
107
179
|
const origin=platformOrigin();
|
|
108
180
|
const credentials=new Credentials(origin),client=new Client(origin,credentials);
|
|
109
181
|
// The commands that wait on Dewdrop stop waiting at Ctrl-C; the rest end the ordinary way. Every signal is taken,
|
|
110
182
|
// not the first alone: under `npm run dev`, npm passes the terminal's Ctrl-C on to the CLI, which has had it already,
|
|
111
183
|
// and a second signal must not end the CLI before it has said what it stopped.
|
|
112
184
|
const controller=new AbortController(),{signal}=controller;
|
|
113
|
-
if(['login','stop','unpublish','publish','dev'].includes(command)) {
|
|
185
|
+
if(['login','stop','unpublish','publish','dev','logs','seat','sessions','eval','pause','resume','step','speed'].includes(command)) {
|
|
114
186
|
process.on('SIGINT',()=>controller.abort(new Error('Stopped.')));
|
|
115
187
|
process.on('SIGTERM',()=>controller.abort(new Error('Stopped.')));
|
|
116
188
|
}
|
|
@@ -138,7 +210,54 @@ async function main() {
|
|
|
138
210
|
console.log(session?'Signed out.':'You weren\'t signed in.');
|
|
139
211
|
return;
|
|
140
212
|
}
|
|
141
|
-
const game=project.game;
|
|
213
|
+
const game=flags.game??project.game;
|
|
214
|
+
// The source maps of what this run builds, and for logs and a kept upload the last build's in the bundle folder,
|
|
215
|
+
// for the game's positions in its console and in a load Dewdrop refuses.
|
|
216
|
+
const maps=new SourceMaps(project?.root??process.cwd());
|
|
217
|
+
if(project?.game===game&&(['logs','eval','repl'].includes(command)||flags.release))maps.load(projectPath(project.root,project.bundle));
|
|
218
|
+
if(command==='logs') {
|
|
219
|
+
await printLogs(client,game,{signal,follow:Boolean(flags.follow),maps,note:line=>console.error(line)});
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if(command==='seat') {
|
|
223
|
+
// A pass written into the bundle folder would go up with the next upload. A path climbing with `..` is refused: the
|
|
224
|
+
// system takes it after the links before it, which no check read in the path's words can be sure of.
|
|
225
|
+
if(flags.out?.split(/[\\/]/).includes('..'))throw new Error(`Name the --out file without .., such as .dewdrop-seat.json in the game's folder.`);
|
|
226
|
+
if(flags.out&&project&&insideBundle(project,flags.out))throw new Error(`${flags.out} is in ${project.bundle}, which ${RUN} dev uploads, so the pass would be uploaded with the game. Write it outside that folder: --out .dewdrop-seat.json writes it in the game's folder, which uploads skip.`);
|
|
227
|
+
const pass=await client.seat(game,signal);
|
|
228
|
+
if(!flags.out){process.stdout.write(`${JSON.stringify(pass,null,2)}\n`);return;}
|
|
229
|
+
writePrivate(flags.out,`${JSON.stringify(pass,null,2)}\n`);
|
|
230
|
+
console.log(`Wrote a seat pass for ${game} to ${flags.out}. It expires at ${pass.expires}.`);
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
if(command==='sessions') {
|
|
234
|
+
const answer=await client.sessions(game,signal);
|
|
235
|
+
console.log(flags.json?JSON.stringify(answer):seatTable(answer.sessions,game));
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
if(command==='eval') {
|
|
239
|
+
const code=await codeOf(flags.code,process.stdin,signal);
|
|
240
|
+
const seat=flags.seat??(await findSeat(client,game,undefined,signal)).seat;
|
|
241
|
+
const answer=await client.evaluate(game,seat,code,Boolean(flags.backend),signal);
|
|
242
|
+
if(flags.json)console.log(JSON.stringify(await machine(client,game,answer,maps,signal)));
|
|
243
|
+
else {
|
|
244
|
+
const printed=await shown(client,game,answer,maps,signal);
|
|
245
|
+
(printed.error?console.error:console.log)(printed.text);
|
|
246
|
+
}
|
|
247
|
+
if(typeof answer.error==='string')process.exitCode=1;
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if(['pause','resume','step','speed'].includes(command)) {
|
|
251
|
+
const fields=command==='step'?{frames:frames(flags.frames)}:command==='speed'?{k:factor(flags.k)}:{};
|
|
252
|
+
const {room}=await findSeat(client,game,flags.seat,signal);
|
|
253
|
+
const answer=await client.room(game,room,command,fields,signal);
|
|
254
|
+
console.log(flags.json?JSON.stringify(answer):roomLine(room,answer)+(command==='speed'?` It runs at ${fields.k}× speed.`:''));
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
if(command==='repl') {
|
|
258
|
+
await repl(client,game,{seat:flags.seat,backend:Boolean(flags.backend),maps});
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
142
261
|
if(command==='status') {
|
|
143
262
|
let state;
|
|
144
263
|
try { state=await client.game(game); }
|
|
@@ -188,14 +307,22 @@ async function main() {
|
|
|
188
307
|
}
|
|
189
308
|
if(flags.release){
|
|
190
309
|
const release=await releaseId(client,game,flags.release);
|
|
191
|
-
await client.activate(game,release,signal,state=>console.log(`Starting ${release.slice(0,12)} at ${devPlayUrl(state)}`));
|
|
310
|
+
try { await client.activate(game,release,signal,state=>console.log(`Starting ${release.slice(0,12)} at ${devPlayUrl(state)}`)); }
|
|
311
|
+
catch(error) { error.message=maps.text(release,error.message); throw error; }
|
|
192
312
|
console.log('Ready to play.');return;
|
|
193
313
|
}
|
|
194
|
-
|
|
314
|
+
const follow=(name,until)=>printLogs(client,name,{signal:until,follow:true,maps});
|
|
315
|
+
if(flags.watch)await watch(project,client,{signal,reread:()=>readProject(project.root),maps,follow});
|
|
195
316
|
else {
|
|
196
317
|
// Claimed before the build, so a name someone else has or an ended sign-in is known at once.
|
|
197
318
|
await client.claim(game,signal);
|
|
198
|
-
if((await deploy(project,client,{signal})).changed)throw new Error(`Files changed during the build, so nothing was uploaded. Run ${RUN} dev again, or ${RUN} dev --watch to rebuild on every save.`);
|
|
319
|
+
if((await deploy(project,client,{signal,maps})).changed)throw new Error(`Files changed during the build, so nothing was uploaded. Run ${RUN} dev again, or ${RUN} dev --watch to rebuild on every save.`);
|
|
320
|
+
// At a terminal the console follows, for the developer to watch; a script or an agent gets the upload alone, and
|
|
321
|
+
// reads the console with logs.
|
|
322
|
+
if(process.stdout.isTTY) {
|
|
323
|
+
console.log(`Printing ${game}'s console. Ctrl-C stops; the dev version keeps running.`);
|
|
324
|
+
await follow(game,signal);
|
|
325
|
+
}
|
|
199
326
|
}
|
|
200
327
|
}
|
|
201
328
|
main().catch(error=>{console.error(`dewctl: ${error.message}`);process.exitCode=1;});
|
package/src/project.js
CHANGED
|
@@ -9,9 +9,10 @@ import {createInterface} from 'node:readline';
|
|
|
9
9
|
import {readTar} from './tar.js';
|
|
10
10
|
import {MAX_BYTES,entryBytes,hashFiles} from './hash.js';
|
|
11
11
|
import {RUN} from './command.js';
|
|
12
|
+
import {readMaps,recordMaps} from './sourcemap.js';
|
|
12
13
|
|
|
13
14
|
const ignored = new Set(['node_modules','dist','target']);
|
|
14
|
-
const GAME_NAME = /^[a-z][a-z0-9-]{0,47}$/;
|
|
15
|
+
export const GAME_NAME = /^[a-z][a-z0-9-]{0,47}$/;
|
|
15
16
|
export const DEWDROP = 'https://alpha.dewdrop.world';
|
|
16
17
|
// Dewdrop's address, or the one DEWDROP_PLATFORM names: an https:// origin, or plain http:// to this
|
|
17
18
|
// computer's own loopback address, which a credential never leaves. The slash an address bar adds is the same origin.
|
|
@@ -28,6 +29,21 @@ export function projectPath(root, path) {
|
|
|
28
29
|
if (!file.startsWith(`${resolve(root)}/`)) throw new Error(`Path leaves the project: ${path}`);
|
|
29
30
|
return file;
|
|
30
31
|
}
|
|
32
|
+
// Whether `file`, a path from the working directory, is in the project's bundle folder — which an upload sends whole
|
|
33
|
+
// but for names starting with a dot — or is the folder. The folders are read through their links, so a link to the
|
|
34
|
+
// bundle folder is no way around it, but the file's own name is not: a file is written in place of a link at its
|
|
35
|
+
// path, never through it, so a link in the folder to a file elsewhere is still a file in the folder. `file` names no
|
|
36
|
+
// `..`, which the system would take after the links before it rather than as `resolve` does.
|
|
37
|
+
export function insideBundle(project, file) {
|
|
38
|
+
const real = path => {
|
|
39
|
+
let at = resolve(path), rest = '';
|
|
40
|
+
while (!existsSync(at) && dirname(at) !== at) { rest = rest ? join(basename(at), rest) : basename(at); at = dirname(at); }
|
|
41
|
+
return rest ? join(realpathSync(at), rest) : realpathSync(at);
|
|
42
|
+
};
|
|
43
|
+
const named = resolve(file), bundle = real(projectPath(project.root, project.bundle));
|
|
44
|
+
const target = dirname(named) === named ? named : join(real(dirname(named)), basename(named));
|
|
45
|
+
return target === bundle || target.startsWith(`${bundle}/`);
|
|
46
|
+
}
|
|
31
47
|
// Whether a change at `path`, relative to the project's root, is one `dev --watch` follows: the walk's rule by path —
|
|
32
48
|
// not under the bundle folder, node_modules, dist or target, and no name starting with a dot.
|
|
33
49
|
export function followed(project, path) {
|
|
@@ -53,8 +69,9 @@ export function readProject(root = process.cwd()) {
|
|
|
53
69
|
|
|
54
70
|
// Every regular file under `start`, by its path under `root`, with its size and its stamp — size, times and inode, which
|
|
55
71
|
// tell the file as it stands from any other write of it: what is walked is not read, so a bundle over the budget is
|
|
56
|
-
// refused on its sizes alone, before any file is opened. Names starting with a dot are always left out;
|
|
57
|
-
// leaves out
|
|
72
|
+
// refused on its sizes alone, before any file is opened. Names starting with a dot are always left out; an upload also
|
|
73
|
+
// leaves out every name ending .map, so the build's source maps stay on this computer; watching leaves out the bundle
|
|
74
|
+
// folder, node_modules, dist and target, and passes over the symlinks an upload refuses.
|
|
58
75
|
function walk(root, start, files, {watch = false, output, budget = {bytes:0}} = {}) {
|
|
59
76
|
if (watch && (start === output || start.startsWith(`${output}/`))) return;
|
|
60
77
|
if (!existsSync(start)) return;
|
|
@@ -69,6 +86,7 @@ function walk(root, start, files, {watch = false, output, budget = {bytes:0}} =
|
|
|
69
86
|
walk(root,join(start,name),files,{watch,output,budget});
|
|
70
87
|
}
|
|
71
88
|
} else {
|
|
89
|
+
if (!watch && start.endsWith('.map')) return;
|
|
72
90
|
if (files.size >= 4096) throw new Error(watch ? 'More than 4096 files are in the project folder, too many for dev to follow. Move what the game doesn\'t need out of it (node_modules, dist, target, the bundle folder and names starting with a dot don\'t count).' : 'The build\'s output has more than 4096 files, the most Dewdrop takes.');
|
|
73
91
|
const size=Number(stat.size);
|
|
74
92
|
if (!watch && (budget.bytes += size) > MAX_BYTES) throw new Error('The build\'s output is over 5 GiB, the most Dewdrop takes.');
|
|
@@ -89,7 +107,9 @@ export function fingerprint(project) {
|
|
|
89
107
|
let hashes=new Map();
|
|
90
108
|
export function forgetHashes() { hashes=new Map(); }
|
|
91
109
|
// The bundle as a release: the manifest of its files — a line each of hash, size and path, in the order of the
|
|
92
|
-
// paths' bytes — which names the release by its own hash, with each file's bytes to read for the upload
|
|
110
|
+
// paths' bytes — which names the release by its own hash, with each file's bytes to read for the upload, and the
|
|
111
|
+
// source maps beside its chunks, read now, before another build can replace them, and noted in the folder as the
|
|
112
|
+
// release's.
|
|
93
113
|
export async function snapshot(project) {
|
|
94
114
|
const directory=projectPath(project.root,project.bundle);
|
|
95
115
|
if (!existsSync(directory)) throw new Error(project.build
|
|
@@ -121,7 +141,9 @@ export async function snapshot(project) {
|
|
|
121
141
|
return {path,size,sha256,read:()=>entryBytes(path,file,root,size,sha256)};
|
|
122
142
|
});
|
|
123
143
|
const manifest=Buffer.from(entries.map(({sha256,size,path})=>`${sha256} ${size} ${path}\n`).join(''));
|
|
124
|
-
|
|
144
|
+
const id=createHash('sha256').update(manifest).digest('hex'),maps=readMaps(root);
|
|
145
|
+
recordMaps(root,id,maps);
|
|
146
|
+
return {id,bytes,files:entries.length,manifest,entries,directory:root,maps};
|
|
125
147
|
}
|
|
126
148
|
export async function build(project, signal) {
|
|
127
149
|
if (!project.build) return;
|
|
@@ -158,7 +180,7 @@ export async function build(project, signal) {
|
|
|
158
180
|
const STARTER_FILES=['package.json','src','index.html','vite.config.js'];
|
|
159
181
|
// The SDK a new game depends on — the range moves with the SDK's minor, since a caret on 0.x stays within one —
|
|
160
182
|
// and this CLI, at its own version.
|
|
161
|
-
const SDK_RANGE='^0.
|
|
183
|
+
const SDK_RANGE='^0.9.0';
|
|
162
184
|
const CLI_RANGE=`^${JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version}`;
|
|
163
185
|
// The games a new one can start from: Blank, which ships with this CLI, and the starter games in the public
|
|
164
186
|
// starter-templates repository, a folder each, at the commit this release pins.
|
package/src/session.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// The developer's own live seats of a dev version, from the terminal: listed, code evaluated in one or its room's
|
|
2
|
+
// backend, its room paused, resumed, stepped and slowed, and a console that evaluates each line typed. Dewdrop reaches
|
|
3
|
+
// only the seats it admitted for this account, and never starts one: a browser — the developer's own, or one their
|
|
4
|
+
// tools drive with a seat pass — plays it.
|
|
5
|
+
import {createInterface} from 'node:readline';
|
|
6
|
+
import {readFileSync} from 'node:fs';
|
|
7
|
+
import {RUN} from './command.js';
|
|
8
|
+
import {CONTROL} from './logs.js';
|
|
9
|
+
|
|
10
|
+
// No seat of the developer's playing, in their words: how to get one.
|
|
11
|
+
const noSeat=game=>`No dev seat of yours is playing ${game}: open one in a browser (${RUN} seat) first.`;
|
|
12
|
+
// The seat named `seat`, or the developer's newest when it names none, as `{seat, room}`.
|
|
13
|
+
export async function findSeat(client,game,seat,signal) {
|
|
14
|
+
const {sessions}=await client.sessions(game,signal);
|
|
15
|
+
if(!sessions.length)throw new Error(noSeat(game));
|
|
16
|
+
if(seat===undefined)return sessions[0];
|
|
17
|
+
const found=sessions.find(each=>each.seat===seat);
|
|
18
|
+
if(!found)throw new Error(`No dev seat of yours named ${seat} is playing ${game}. Run ${RUN} sessions to list yours.`);
|
|
19
|
+
return found;
|
|
20
|
+
}
|
|
21
|
+
// The seats as `sessions` prints them: a column each for the seat and its room, the newest — the one the other commands
|
|
22
|
+
// use when no --seat is given — first.
|
|
23
|
+
export function seatTable(sessions,game) {
|
|
24
|
+
if(!sessions.length)return noSeat(game);
|
|
25
|
+
const width=Math.max(4,...sessions.map(each=>each.seat.length));
|
|
26
|
+
return [`${'SEAT'.padEnd(width)} ROOM`,...sessions.map((each,i)=>`${each.seat.padEnd(width)} ${each.room}${i===0?' (default)':''}`)].join('\n').replace(CONTROL,'?');
|
|
27
|
+
}
|
|
28
|
+
// The code `eval` is given: the argument itself, everything on standard input for `-`, or a file's text for `@FILE`.
|
|
29
|
+
// Reading standard input ends at `signal`, the input let go so the CLI can end.
|
|
30
|
+
export async function codeOf(argument,stdin=process.stdin,signal) {
|
|
31
|
+
if(argument==='-') {
|
|
32
|
+
try { return Buffer.concat((await stdin.toArray({signal})).map(chunk=>Buffer.from(chunk))).toString('utf8'); }
|
|
33
|
+
catch(error) {
|
|
34
|
+
if(!signal?.aborted)throw error;
|
|
35
|
+
stdin.destroy();
|
|
36
|
+
throw signal.reason;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if(argument.startsWith('@')) {
|
|
40
|
+
try { return readFileSync(argument.slice(1),'utf8'); }
|
|
41
|
+
catch(error) { throw new Error(`Couldn't read ${argument.slice(1)} (${error.code??error.message}).`); }
|
|
42
|
+
}
|
|
43
|
+
return argument;
|
|
44
|
+
}
|
|
45
|
+
// What an evaluate answered as printed: its value as indented JSON, `undefined` for none, or what the code threw with
|
|
46
|
+
// each position in the built code shown in the game's source by `maps`, for the dev version's release, which is asked
|
|
47
|
+
// of Dewdrop only when there is an error to map.
|
|
48
|
+
export async function shown(client,game,answer,maps,signal) {
|
|
49
|
+
if(typeof answer.error==='string') {
|
|
50
|
+
let text=answer.error;
|
|
51
|
+
if(maps)try { text=maps.text((await client.game(game,signal)).dev.release,text); } catch {}
|
|
52
|
+
return {error:true,text:text.replace(CONTROL,'?')};
|
|
53
|
+
}
|
|
54
|
+
return {error:false,text:'value' in answer?JSON.stringify(answer.value,null,2):'undefined'};
|
|
55
|
+
}
|
|
56
|
+
// The answer to an evaluate, `--json`: as Dewdrop gave it, with the error's positions mapped as printed.
|
|
57
|
+
export async function machine(client,game,answer,maps,signal) {
|
|
58
|
+
if(typeof answer.error!=='string')return answer;
|
|
59
|
+
return {error:(await shown(client,game,answer,maps,signal)).text};
|
|
60
|
+
}
|
|
61
|
+
// A room's state after an action, in words.
|
|
62
|
+
export const roomLine=(room,{frame,paused})=>`Room ${room}: frame ${frame}, ${paused?'paused':'running'}.`;
|
|
63
|
+
// Checks a step's frame count and a speed's factor before anything is asked of Dewdrop.
|
|
64
|
+
export function frames(value) {
|
|
65
|
+
if(!/^[1-9][0-9]{0,2}$/.test(value??'')||Number(value)>600)throw new Error('step takes a number of frames from 1 to 600.');
|
|
66
|
+
return Number(value);
|
|
67
|
+
}
|
|
68
|
+
export function factor(value) {
|
|
69
|
+
const k=Number(value);
|
|
70
|
+
if(!/^(0|1)?(\.[0-9]+)?$/.test(value??'')||!(k>0&&k<=1))throw new Error('speed takes a factor above 0 and at most 1, such as 0.25.');
|
|
71
|
+
return k;
|
|
72
|
+
}
|
|
73
|
+
const HELP=`Each line is evaluated in the seat (or, after .backend, in its room's backend) and its value printed.
|
|
74
|
+
.pause Pause the seat's room
|
|
75
|
+
.resume Resume it
|
|
76
|
+
.step N Advance the paused room N frames (1 to 600)
|
|
77
|
+
.speed K Run the room at K times its speed (above 0, at most 1)
|
|
78
|
+
.seat S Evaluate in your seat S from now on (${RUN} sessions lists them)
|
|
79
|
+
.backend Evaluate in the room's backend from now on
|
|
80
|
+
.page Evaluate in the seat's page again
|
|
81
|
+
.help Show this
|
|
82
|
+
.exit Leave (or Ctrl-D)`;
|
|
83
|
+
// A console of the dev version: each line from `input` evaluated in seat `seat` — the developer's newest when none is
|
|
84
|
+
// named — or its room's backend, and printed to `output`, until the input ends, `.exit`, or Ctrl-C, which also gives up
|
|
85
|
+
// on a request under way. A refusal is printed and the console goes on.
|
|
86
|
+
export async function repl(client,game,{seat,backend=false,maps,input=process.stdin,output=process.stdout}={}) {
|
|
87
|
+
const terminal=Boolean(input.isTTY&&output.isTTY);
|
|
88
|
+
const stop=new AbortController(),{signal}=stop;
|
|
89
|
+
let current=(await findSeat(client,game,seat)).seat;
|
|
90
|
+
const say=text=>output.write(`${text}\n`);
|
|
91
|
+
const prompt=()=>`${game} ${current}${backend?' backend':''}> `;
|
|
92
|
+
say(`Evaluating in ${current}${backend?'\'s backend':''} of ${game}. .help lists the commands.`);
|
|
93
|
+
const lines=createInterface({input,output:terminal?output:undefined,terminal,prompt:prompt()});
|
|
94
|
+
// Ctrl-C at a terminal; a console reading a pipe ends at its end, once every line read is answered.
|
|
95
|
+
lines.on('SIGINT',()=>{stop.abort(new Error('Stopped.'));lines.close();});
|
|
96
|
+
if(terminal)lines.prompt();
|
|
97
|
+
// The seat's room, asked each time: a seat may have joined another since.
|
|
98
|
+
const act=async(action,fields={})=>{
|
|
99
|
+
const {room}=await findSeat(client,game,current,signal);
|
|
100
|
+
say(roomLine(room,await client.room(game,room,action,fields,signal)));
|
|
101
|
+
};
|
|
102
|
+
const commands={
|
|
103
|
+
'.pause':()=>act('pause'),
|
|
104
|
+
'.resume':()=>act('resume'),
|
|
105
|
+
'.step':value=>act('step',{frames:frames(value)}),
|
|
106
|
+
'.speed':value=>act('speed',{k:factor(value)}),
|
|
107
|
+
'.seat':async value=>{
|
|
108
|
+
if(!value)throw new Error('.seat takes one of your seats, such as alice#5.');
|
|
109
|
+
current=(await findSeat(client,game,value,signal)).seat;
|
|
110
|
+
say(`Evaluating in ${current}${backend?'\'s backend':''}.`);
|
|
111
|
+
},
|
|
112
|
+
'.backend':()=>{backend=true;say(`Evaluating in ${current}'s room's backend.`);},
|
|
113
|
+
'.page':()=>{backend=false;say(`Evaluating in ${current}'s page.`);},
|
|
114
|
+
'.help':()=>say(HELP),
|
|
115
|
+
};
|
|
116
|
+
for await(const line of lines) {
|
|
117
|
+
const text=line.trim();
|
|
118
|
+
if(text==='.exit'||signal.aborted)break;
|
|
119
|
+
if(text) {
|
|
120
|
+
try {
|
|
121
|
+
if(text.startsWith('.')) {
|
|
122
|
+
const [name,value,...rest]=text.split(/\s+/);
|
|
123
|
+
if(!Object.hasOwn(commands,name)||rest.length)throw new Error(`${text} isn't a command here. .help lists them.`);
|
|
124
|
+
await commands[name](value);
|
|
125
|
+
} else {
|
|
126
|
+
const answer=await shown(client,game,await client.evaluate(game,current,line,backend,signal),maps,signal);
|
|
127
|
+
say(answer.text);
|
|
128
|
+
}
|
|
129
|
+
} catch(error) {
|
|
130
|
+
if(signal.aborted)break;
|
|
131
|
+
say(error.message);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if(terminal&&!signal.aborted){lines.setPrompt(prompt());lines.prompt();}
|
|
135
|
+
}
|
|
136
|
+
lines.close();
|
|
137
|
+
}
|
package/src/sourcemap.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// Positions in the built main.js and backend.js read back to the game's source with the build's source maps, which
|
|
2
|
+
// stay on this computer: the upload leaves every .map out, and these are read from the bundle folder as each build
|
|
3
|
+
// is snapshotted, kept by the release that build became.
|
|
4
|
+
import {createHash,randomBytes} from 'node:crypto';
|
|
5
|
+
import {existsSync, lstatSync, readFileSync, writeFileSync, renameSync, rmSync} from 'node:fs';
|
|
6
|
+
import {join, relative, resolve} from 'node:path';
|
|
7
|
+
|
|
8
|
+
// The chunks whose positions Dewdrop's logs and errors name, each mapped by the file beside it with `.map` added.
|
|
9
|
+
export const CHUNKS=['main.js','backend.js'];
|
|
10
|
+
// What a snapshot leaves in the bundle folder about its maps — the release they belong to and each map's hash — so a
|
|
11
|
+
// later dewctl, run without building, uses them only while they are still the ones that release was built with. The
|
|
12
|
+
// name starts with a dot, so the upload leaves it out like the maps.
|
|
13
|
+
export const RECORD='.dewctl-maps.json';
|
|
14
|
+
const BASE64='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
15
|
+
// A source, or the root sources are under, given as an address with a scheme rather than a path.
|
|
16
|
+
const URL_LIKE=/^[a-z][a-z0-9+.-]*:/i;
|
|
17
|
+
const sha256=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
18
|
+
|
|
19
|
+
// A source map's mappings as each generated line's segments, `[column]` where the code is mapped to no source and
|
|
20
|
+
// `[column, source, line, column]` where it is, every field counted from 0: base64 VLQ fields, each relative to the
|
|
21
|
+
// field before it of the same kind, the generated column starting again on each line.
|
|
22
|
+
export function decodeMappings(mappings) {
|
|
23
|
+
const state=[0,0,0,0,0];
|
|
24
|
+
return mappings.split(';').map(line=>{
|
|
25
|
+
state[0]=0;
|
|
26
|
+
if(!line)return [];
|
|
27
|
+
return line.split(',').filter(Boolean).map(segment=>{
|
|
28
|
+
const fields=[];
|
|
29
|
+
let value=0,shift=0;
|
|
30
|
+
for(const char of segment) {
|
|
31
|
+
const digit=BASE64.indexOf(char);
|
|
32
|
+
if(digit<0)throw new Error('not a source map');
|
|
33
|
+
value+=(digit&31)*2**shift;
|
|
34
|
+
if(digit&32){shift+=5;continue;}
|
|
35
|
+
fields.push(value%2?-Math.floor(value/2):value/2);
|
|
36
|
+
value=0;shift=0;
|
|
37
|
+
}
|
|
38
|
+
return fields.map((delta,i)=>state[i]+=delta).slice(0,4);
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
// One chunk's source map, decoded on the first look-up. `directory` is the bundle folder the map sat in and `root`
|
|
43
|
+
// the project's, so a source is named by its path in the project.
|
|
44
|
+
class SourceMap {
|
|
45
|
+
constructor(bytes,directory,root){this.bytes=bytes;this.directory=directory;this.root=root;this.lines=null;}
|
|
46
|
+
// Where the code at `line` and `column`, both counted from 1 as a stack names them, came from, as
|
|
47
|
+
// `{source, line, column}` counted the same way; null where the map says nothing of it or doesn't read.
|
|
48
|
+
original(line,column) {
|
|
49
|
+
if(this.lines===null) {
|
|
50
|
+
try {
|
|
51
|
+
const map=JSON.parse(this.bytes.toString('utf8'));
|
|
52
|
+
if(map.version!==3||typeof map.mappings!=='string'||!Array.isArray(map.sources))throw new Error('not a source map');
|
|
53
|
+
this.map=map;this.lines=decodeMappings(map.mappings);
|
|
54
|
+
} catch {this.lines=[];}
|
|
55
|
+
}
|
|
56
|
+
let found;
|
|
57
|
+
for(const segment of this.lines[line-1]??[]){if(segment[0]>column-1)break;found=segment;}
|
|
58
|
+
if(!found||found.length<4||typeof this.map.sources[found[1]]!=='string')return null;
|
|
59
|
+
return {source:this.name(this.map.sources[found[1]]),line:found[2]+1,column:found[3]+1};
|
|
60
|
+
}
|
|
61
|
+
// A source as the developer finds it: its path from the project's folder, or as the map gives it when that is
|
|
62
|
+
// an address rather than a path.
|
|
63
|
+
name(source) {
|
|
64
|
+
const root=typeof this.map.sourceRoot==='string'?this.map.sourceRoot:'';
|
|
65
|
+
if(URL_LIKE.test(source))return source;
|
|
66
|
+
if(URL_LIKE.test(root))return URL.parse(source,root.endsWith('/')?root:`${root}/`)?.href??`${root}${source}`;
|
|
67
|
+
return relative(this.root,resolve(this.directory,root,source)).split('\\').join('/');
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
// The maps beside the chunks in the bundle folder `directory`, as bytes by chunk: regular files only, never a link
|
|
71
|
+
// that could reach some other file.
|
|
72
|
+
export function readMaps(directory) {
|
|
73
|
+
const maps={};
|
|
74
|
+
for(const chunk of CHUNKS) {
|
|
75
|
+
const file=join(directory,`${chunk}.map`);
|
|
76
|
+
if(existsSync(file)&&lstatSync(file).isFile())maps[chunk]=readFileSync(file);
|
|
77
|
+
}
|
|
78
|
+
return maps;
|
|
79
|
+
}
|
|
80
|
+
// Notes in the bundle folder which release its maps belong to: a new file moved into the note's place, so a link
|
|
81
|
+
// already there is replaced, never written through. A folder that can't be written to only loses the note.
|
|
82
|
+
export function recordMaps(directory,release,maps) {
|
|
83
|
+
const record={release,maps:Object.fromEntries(Object.entries(maps).map(([chunk,bytes])=>[chunk,sha256(bytes)]))};
|
|
84
|
+
const file=join(directory,RECORD),temporary=`${file}.${randomBytes(6).toString('hex')}`;
|
|
85
|
+
try { writeFileSync(temporary,`${JSON.stringify(record)}\n`,{flag:'wx'}); renameSync(temporary,file); }
|
|
86
|
+
catch { rmSync(temporary,{force:true}); }
|
|
87
|
+
}
|
|
88
|
+
// The maps the bundle folder's note names, while the files are still the ones it hashed: `{release, maps}`, or null.
|
|
89
|
+
export function recordedMaps(directory) {
|
|
90
|
+
try {
|
|
91
|
+
const record=JSON.parse(readFileSync(join(directory,RECORD),'utf8')),maps=readMaps(directory);
|
|
92
|
+
if(typeof record.release!=='string')return null;
|
|
93
|
+
const named=Object.entries(record.maps??{});
|
|
94
|
+
if(named.length!==Object.keys(maps).length||named.some(([chunk,hash])=>!maps[chunk]||sha256(maps[chunk])!==hash))return null;
|
|
95
|
+
return {release:record.release,maps};
|
|
96
|
+
} catch {return null;}
|
|
97
|
+
}
|
|
98
|
+
// A `main.js:L:C` or `backend.js:L:C` in text Dewdrop sent, not part of a longer name or path.
|
|
99
|
+
const POSITION=/(?<![\w$./\\-])(main\.js|backend\.js):(\d+):(\d+)/g;
|
|
100
|
+
// The source maps of the releases this run built, the latest few, for the positions their logs and errors name.
|
|
101
|
+
export class SourceMaps {
|
|
102
|
+
constructor(root){this.root=root;this.releases=new Map();}
|
|
103
|
+
// Keeps the maps `readMaps` read from `directory` as `release`'s, forgetting the oldest beyond four releases.
|
|
104
|
+
remember(release,directory,maps) {
|
|
105
|
+
this.releases.delete(release);
|
|
106
|
+
this.releases.set(release,Object.fromEntries(Object.entries(maps).map(([chunk,bytes])=>[chunk,new SourceMap(bytes,directory,this.root)])));
|
|
107
|
+
while(this.releases.size>4)this.releases.delete(this.releases.keys().next().value);
|
|
108
|
+
}
|
|
109
|
+
// Takes on the maps the bundle folder notes, for a run that built nothing.
|
|
110
|
+
load(directory) {
|
|
111
|
+
const recorded=recordedMaps(directory);
|
|
112
|
+
if(recorded&&!this.releases.has(recorded.release))this.remember(recorded.release,directory,recorded.maps);
|
|
113
|
+
}
|
|
114
|
+
// `text` with each position in a chunk of `release` that its map knows written as the source's instead; a
|
|
115
|
+
// position with no map, or one its map says nothing of, is left as it is.
|
|
116
|
+
text(release,text) {
|
|
117
|
+
const maps=this.releases.get(release);
|
|
118
|
+
if(!maps)return text;
|
|
119
|
+
return text.replace(POSITION,(position,chunk,line,column)=>{
|
|
120
|
+
const found=maps[chunk]?.original(Number(line),Number(column));
|
|
121
|
+
return found?`${found.source}:${found.line}:${found.column}`:position;
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
}
|
package/src/watch.js
CHANGED
|
@@ -22,14 +22,19 @@ const telling=log=>event=>{
|
|
|
22
22
|
else if(event.files===0)log('Dewdrop has every file of the build; recording the release…');
|
|
23
23
|
else log(`Uploading ${count(event.files,'file')} (${size(event.bytes)})…`);
|
|
24
24
|
};
|
|
25
|
-
// Builds, pushes and plays the build of a claimed game as the dev version, under the id Dewdrop recorded it by.
|
|
26
|
-
|
|
25
|
+
// Builds, pushes and plays the build of a claimed game as the dev version, under the id Dewdrop recorded it by. The
|
|
26
|
+
// build's source maps are kept in `maps` as that release's, and a load Dewdrop refuses names its positions in the
|
|
27
|
+
// game's source.
|
|
28
|
+
export async function deploy(project,client,{signal,log=console.log,maps}={}) {
|
|
27
29
|
const before=fingerprint(project);
|
|
28
30
|
log('Building…');
|
|
29
31
|
await build(project,signal);
|
|
30
32
|
if(fingerprint(project)!==before)return {changed:true};
|
|
31
|
-
const
|
|
32
|
-
await client.
|
|
33
|
+
const bundle=await snapshot(project);
|
|
34
|
+
const {release}=await client.push(project.game,bundle,signal,telling(log));
|
|
35
|
+
maps?.remember(release,bundle.directory,bundle.maps);
|
|
36
|
+
try { await client.activate(project.game,release,signal,game=>log(`Starting ${release.slice(0,12)} at ${devPlayUrl(game)}`)); }
|
|
37
|
+
catch(error) { if(maps)error.message=maps.text(release,error.message); throw error; }
|
|
33
38
|
log('Ready to play.');
|
|
34
39
|
return {changed:false};
|
|
35
40
|
}
|
|
@@ -53,10 +58,21 @@ export function watchTree(current,changed,lost=()=>{}) {
|
|
|
53
58
|
// the project as dewdrop.json says it now, so an edit to it applies to the next build; a dewdrop.json that no longer
|
|
54
59
|
// reads waits, like a failed build, for the next save. The game is claimed once for the session, before its first
|
|
55
60
|
// build, so a name someone else has or an ended sign-in is known at once, and again only for a game dewdrop.json renames.
|
|
61
|
+
// Once a build is ready to play, `follow` follows the game's dev console until the watch stops: started again by the
|
|
62
|
+
// next build ready should it stop, and for a renamed game in place of the old one's.
|
|
56
63
|
export const EVENT_DEBOUNCE_MS=100;
|
|
57
|
-
export async function watch(project,client,{signal,log=console.log,deployGame=deploy,readFingerprint=fingerprint,reread=()=>project,watchFiles=watchTree,pollMs=200,debounceMs=500}={}) {
|
|
64
|
+
export async function watch(project,client,{signal,log=console.log,deployGame=deploy,readFingerprint=fingerprint,reread=()=>project,watchFiles=watchTree,pollMs=200,debounceMs=500,maps,follow}={}) {
|
|
58
65
|
let changedAt=Date.now()-debounceMs,dirty=true;
|
|
59
|
-
let running=null,claimed=null;
|
|
66
|
+
let running=null,claimed=null,following=null;
|
|
67
|
+
const startFollowing=game=>{
|
|
68
|
+
if(!follow||following?.game===game)return;
|
|
69
|
+
following?.controller.abort();
|
|
70
|
+
const controller=new AbortController(),current={game,controller};
|
|
71
|
+
current.done=follow(game,signal?AbortSignal.any([signal,controller.signal]):controller.signal).catch(error=>{
|
|
72
|
+
if(!controller.signal.aborted&&!signal?.aborted)log(`dewctl: ${error.message}`);
|
|
73
|
+
}).finally(()=>{if(following===current)following=null;});
|
|
74
|
+
following=current;
|
|
75
|
+
};
|
|
60
76
|
const noted=()=>{changedAt=Date.now();dirty=true;};
|
|
61
77
|
let watching=watchFiles?.(()=>project,noted,()=>{watching=null;observed=readFingerprint(project);});
|
|
62
78
|
let observed=watching?null:readFingerprint(project);
|
|
@@ -70,11 +86,13 @@ export async function watch(project,client,{signal,log=console.log,deployGame=de
|
|
|
70
86
|
if(dirty&&!running&&Date.now()-changedAt>=(watching?EVENT_DEBOUNCE_MS:debounceMs)) {
|
|
71
87
|
dirty=false;
|
|
72
88
|
project=reread();
|
|
89
|
+
const game=project.game;
|
|
73
90
|
running=(async()=>{
|
|
74
|
-
if(
|
|
75
|
-
return deployGame(project,client,{signal,log});
|
|
91
|
+
if(game!==claimed){await client.claim(game,signal);claimed=game;}
|
|
92
|
+
return deployGame(project,client,{signal,log,maps});
|
|
76
93
|
})().then(result=>{
|
|
77
94
|
if(result.changed)dirty=true;
|
|
95
|
+
else startFollowing(game);
|
|
78
96
|
}).catch(error=>{
|
|
79
97
|
if(signal?.aborted)return;
|
|
80
98
|
log(`dewctl: ${error.message}`);
|
|
@@ -87,6 +105,8 @@ export async function watch(project,client,{signal,log=console.log,deployGame=de
|
|
|
87
105
|
await new Promise(resolve=>setTimeout(resolve,pollMs));
|
|
88
106
|
}
|
|
89
107
|
await running;
|
|
108
|
+
following?.controller.abort();
|
|
109
|
+
await following?.done;
|
|
90
110
|
watching?.close();
|
|
91
111
|
log('Stopped watching. The dev version keeps running.');
|
|
92
112
|
}
|