dewctl 0.6.4 → 0.6.6

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.
@@ -81,6 +81,11 @@ The code ([limits](https://alpha.dewdrop.world/docs/limits)):
81
81
  `color-scheme: dark`. Put what the page shows under `public/ui/`, or import it.
82
82
  - `fetch` reads only the game's own files. WebSocket, WebRTC and workers aren't available. Sound plays through
83
83
  Web Audio; `<audio>` and `<video>` make no sound.
84
+ - `localStorage` and `indexedDB` throw. Storage is `saves.storage` and `saves.indexedDB` from `dewdrop-sdk`, open
85
+ once `await saves.load()` is done, and kept only by `await saves.save()` ([saves](https://alpha.dewdrop.world/docs/saves)).
86
+ - `sessionStorage`, `location` navigation, and `alert`, `confirm` and `prompt` throw: keep state in memory, restart in the
87
+ game or call `session.exit()`, and draw dialogs on the page. The console warns once about anything else that isn't
88
+ available; [what works](https://alpha.dewdrop.world/docs/limits) lists it.
84
89
  - Keep `three` at 0.185.1, which Dewdrop provides ([project](https://alpha.dewdrop.world/docs/project)).
85
90
 
86
91
  ## 4. The working loop
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dewctl",
3
- "version": "0.6.4",
3
+ "version": "0.6.6",
4
4
  "description": "Build and publish three.js games on Dewdrop.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/client.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // Requests to Dewdrop, only ever to the address in dewdrop.json, signed in with the session login stored.
2
+ import {createHash} from 'node:crypto';
2
3
  import {RUN} from './command.js';
3
4
  export class ApiError extends Error {
4
5
  constructor(status,message){super(message);this.status=status;}
@@ -15,16 +16,34 @@ export function sleep(ms,signal) {
15
16
  }
16
17
  // An upload is sent in parts of at most this many bytes.
17
18
  export const PART_BYTES=32*1024*1024;
19
+ // How long a poll asks the platform to hold it for news (`Prefer: wait`), under what the edge holds a request open.
20
+ const WAIT_S=25;
21
+ // `chunks` cut into runs of exactly `bytes`, but the last, which is what remains and never empty: an archive given
22
+ // as a run of buffers of any lengths is sent in parts of one size, holding about one part at a time.
23
+ export function* parts(chunks,bytes=PART_BYTES) {
24
+ let part=Buffer.allocUnsafe(bytes),filled=0;
25
+ for(let chunk of chunks) {
26
+ while(chunk.length) {
27
+ const taken=chunk.copy(part,filled,0,Math.min(chunk.length,bytes-filled));
28
+ filled+=taken;chunk=chunk.subarray(taken);
29
+ if(filled===bytes){yield part;part=Buffer.allocUnsafe(bytes);filled=0;}
30
+ }
31
+ }
32
+ if(filled)yield part.subarray(0,filled);
33
+ }
18
34
  export class Client {
19
- constructor(origin,credentials,{fetcher=fetch,pollMs=1000,timeoutMs=180000}={}){this.origin=origin;this.credentials=credentials;this.fetcher=fetcher;this.pollMs=pollMs;this.timeoutMs=timeoutMs;}
35
+ // `partBytes` is for the tests, which cut at a few bytes; an upload is sent in parts of PART_BYTES.
36
+ // `pollMs` is the least a wait on the platform takes a round: a platform that holds the request answers when there
37
+ // is news, within WAIT_S; one that answers at once instead is asked again after that long.
38
+ constructor(origin,credentials,{fetcher=fetch,pollMs=1000,timeoutMs=180000,storeMs=15*60*1000,partBytes=PART_BYTES}={}){this.origin=origin;this.credentials=credentials;this.fetcher=fetcher;this.pollMs=pollMs;this.timeoutMs=timeoutMs;this.storeMs=storeMs;this.partBytes=partBytes;this.holds=true;}
20
39
  // A request signed in with `token`. When Dewdrop can't be reached the failure is marked transient, which a watcher
21
40
  // or a sign-in waits out; a refused token asks for a new sign-in, whatever Dewdrop's words.
22
- async request(path,{method='GET',body,token,signal,type}={}) {
41
+ async request(path,{method='GET',body,token,signal,type,prefer}={}) {
23
42
  if(!path.startsWith('/v1/'))throw new Error('Invalid API path.');
24
43
  const bytes=Buffer.isBuffer(body);
25
44
  let response;
26
45
  try {
27
- response=await this.fetcher(this.origin+path,{method,redirect:'error',signal:signal?AbortSignal.any([signal,AbortSignal.timeout(120000)]):AbortSignal.timeout(120000),headers:{...(token?{authorization:`Bearer ${token}`}:{}),...(body!==undefined?{'content-type':type??(bytes?'application/octet-stream':'application/json')}:{})},body:body===undefined?undefined:bytes||typeof body==='string'?body:JSON.stringify(body)});
46
+ response=await this.fetcher(this.origin+path,{method,redirect:'error',signal:signal?AbortSignal.any([signal,AbortSignal.timeout(120000)]):AbortSignal.timeout(120000),headers:{...(token?{authorization:`Bearer ${token}`}:{}),...(body!==undefined?{'content-type':type??(bytes?'application/octet-stream':'application/json')}:{}),...(prefer?{prefer}:{})},body:body===undefined?undefined:bytes||typeof body==='string'?body:JSON.stringify(body)});
28
47
  } catch(error) {
29
48
  if(signal?.aborted)throw error;
30
49
  const reason=error.name==='TimeoutError'?'no answer in two minutes':error.cause?.code??error.cause?.message??error.message;
@@ -58,14 +77,33 @@ export class Client {
58
77
  throw error;
59
78
  }
60
79
  }
61
- // Uploads a build of a claimed game under its id, in parts of PART_BYTES, then completes it with the number of
62
- // parts; Dewdrop must confirm the same id.
63
- async upload(game,bundle,signal) {
64
- const parts=Math.max(1,Math.ceil(bundle.body.length/PART_BYTES));
65
- for(let index=0;index<parts;index++) {
66
- await this.api(`/v1/games/${game}/releases/${bundle.id}/parts/${index}`,{method:'PUT',body:bundle.body.subarray(index*PART_BYTES,(index+1)*PART_BYTES),signal});
80
+ // Uploads a build of a claimed game under its id — its archive read through again as `bundle.chunks()` gives it,
81
+ // cut into parts of PART_BYTES, so a bundle of gigabytes is never held whole; what is sent is hashed as it goes,
82
+ // and an archive that no longer hashes to the id changed since the id was taken, and is refused — then completes
83
+ // it with the number of parts,
84
+ // asking for the answer at once: Dewdrop takes a large release in over minutes, longer than a request stays
85
+ // open, so an answer at once names the `phase` it is in, and this follows at the release's address, telling
86
+ // `progress` each phase it sees, until Dewdrop records the release — the answer with its `bytes` — or refuses it.
87
+ // A Dewdrop from before the answer at once records the release in the request itself. Dewdrop must confirm the
88
+ // same id.
89
+ async upload(game,bundle,signal,progress) {
90
+ let count=0;
91
+ const hash=createHash('sha256');
92
+ for(const part of parts(bundle.chunks(),this.partBytes)) {
93
+ hash.update(part);
94
+ await this.api(`/v1/games/${game}/releases/${bundle.id}/parts/${count++}`,{method:'PUT',body:part,signal});
95
+ }
96
+ if(hash.digest('hex')!==bundle.id)throw new Error('The build\'s output changed while it was being uploaded. Try again.');
97
+ const path=`/v1/games/${game}/releases/${bundle.id}`,deadline=Date.now()+this.storeMs;
98
+ let result=await this.api(path,{method:'POST',body:{parts:count},signal,prefer:'respond-async'}),phase;
99
+ while(result.bytes===undefined) {
100
+ if(Date.now()>=deadline)throw new Error(`Dewdrop is taking longer than fifteen minutes to store the upload. Run ${RUN} releases to see whether it arrived.`);
101
+ if(result.phase!==undefined&&result.phase!==phase){phase=result.phase;progress?.(phase);}
102
+ // Held by the platform until the completion ends, or answered at once by one that does not hold a poll.
103
+ const asked=Date.now();
104
+ result=await this.api(path,{signal,prefer:`wait=${WAIT_S}`});
105
+ if(result.bytes===undefined)await this.#rest(asked,signal);
67
106
  }
68
- const result=await this.api(`/v1/games/${game}/releases/${bundle.id}`,{method:'POST',body:{parts},signal});
69
107
  if(result.release!==bundle.id)throw new Error('Dewdrop stored a different release than was uploaded, so nothing was changed. Try again.');
70
108
  return result;
71
109
  }
@@ -85,10 +123,30 @@ export class Client {
85
123
  if(current.error)throw new Error(current.error);
86
124
  if(current.ready)return state;
87
125
  if(Date.now()>=deadline)throw new Error(`${doing} is taking longer than three minutes. Run ${RUN} status to follow it.`);
88
- await sleep(this.pollMs,signal);
89
- state=await this.game(game,signal);
126
+ const asked=Date.now();
127
+ state=await this.held(game,version,signal);
128
+ // An answer with news is acted on at once; one without is asked again after the round.
129
+ const seen=state[version];
130
+ if(seen.release===release&&!seen.ready&&!seen.error)await this.#rest(asked,signal);
90
131
  }
91
132
  }
133
+ // The game as the platform answers it once `version` is ready or refused, holding the request for it; a platform from
134
+ // before that route answers the game as it stands, and is asked that way from then on.
135
+ async held(game,version,signal) {
136
+ if(!this.holds)return this.game(game,signal);
137
+ try{return await this.api(`/v1/games/${game}/${version}`,{signal,prefer:`wait=${WAIT_S}`});}
138
+ catch(error){
139
+ if(error.status!==405&&error.status!==404)throw error;
140
+ this.holds=false;
141
+ return this.game(game,signal);
142
+ }
143
+ }
144
+ // The rest of a round that came back at once: a platform holding the request has answered with news, one that
145
+ // answered at once is asked again `pollMs` after it was asked.
146
+ async #rest(asked,signal) {
147
+ const left=this.pollMs-(Date.now()-asked);
148
+ if(left>0)await sleep(left,signal);
149
+ }
92
150
  // Sets the game's thumbnail to the image, sent as itself under its type.
93
151
  thumbnail(game,bytes,type,signal){return this.api(`/v1/games/${game}/thumbnail`,{method:'PUT',body:bytes,type,signal});}
94
152
  async member(game,email,on,signal) {
package/src/project.js CHANGED
@@ -6,12 +6,14 @@ import {spawn} from 'node:child_process';
6
6
  import {fileURLToPath} from 'node:url';
7
7
  import {gunzipSync} from 'node:zlib';
8
8
  import {createInterface} from 'node:readline';
9
- import {packTar,readTar} from './tar.js';
9
+ import {tarChunks,tarLength,readTar} from './tar.js';
10
10
  import {RUN} from './command.js';
11
11
 
12
- const MAX_BYTES = 1024 * 1024 * 1024;
12
+ // The most bytes a bundle holds, Dewdrop's bound: 5 GiB of files.
13
+ const MAX_BYTES = 5 * 1024 ** 3;
14
+ // A file is read from its descriptor this many bytes at a time, so a bundle of gigabytes passes through a few MiB.
15
+ const CHUNK_BYTES = 4 * 1024 * 1024;
13
16
  const ignored = new Set(['node_modules','dist','target']);
14
- const hash = bytes => createHash('sha256').update(bytes).digest('hex');
15
17
  const GAME_NAME = /^[a-z][a-z0-9-]{0,47}$/;
16
18
  export const DEWDROP = 'https://alpha.dewdrop.world';
17
19
  // Dewdrop's address, or the one DEWDROP_PLATFORM names: an https:// origin, or plain http:// to this
@@ -29,6 +31,14 @@ export function projectPath(root, path) {
29
31
  if (!file.startsWith(`${resolve(root)}/`)) throw new Error(`Path leaves the project: ${path}`);
30
32
  return file;
31
33
  }
34
+ // Whether a change at `path`, relative to the project's root, is one `dev --watch` follows: the walk's rule by path —
35
+ // not under the bundle folder, node_modules, dist or target, and no name starting with a dot.
36
+ export function followed(project, path) {
37
+ const names = path.split(/[\\/]/);
38
+ if (names.some(name => name.startsWith('.') || ignored.has(name))) return false;
39
+ const output = relative(project.root, projectPath(project.root, project.bundle)).split('\\').join('/'), joined = names.join('/');
40
+ return joined !== output && !joined.startsWith(`${output}/`);
41
+ }
32
42
  export function readProject(root = process.cwd()) {
33
43
  root = realpathSync(root);
34
44
  const file = join(root,'dewdrop.json');
@@ -44,35 +54,38 @@ export function readProject(root = process.cwd()) {
44
54
  return {...config,root};
45
55
  }
46
56
 
47
- // Opens a file of the project as a regular file under `root` and no symlink, hands `fn` its descriptor, and closes it.
48
- function opened(file, root, fn) {
57
+ // Opens a file of the project as a regular file under `root` and no symlink, gives out the run of buffers `fn` reads
58
+ // from its descriptor and stat, and closes it once the run is taken, or left early.
59
+ function* opened(file, root, fn) {
49
60
  const actual = realpathSync(file);
50
61
  if (!actual.startsWith(`${root}/`) || actual !== file) throw new Error(`Symlinks cannot be uploaded: ${file}`);
51
62
  const fd = openSync(file,constants.O_RDONLY|constants.O_NOFOLLOW);
52
63
  try {
53
64
  const stat=fstatSync(fd);
54
- if (!stat.isFile() || stat.size > MAX_BYTES) throw new Error(`Not a regular file under 1 GiB: ${file}`);
55
- return fn(fd,stat);
65
+ if (!stat.isFile() || stat.size > MAX_BYTES) throw new Error(`Not a regular file of at most 5 GiB: ${file}`);
66
+ yield* fn(fd,stat);
56
67
  } finally { closeSync(fd); }
57
68
  }
58
- const readRegular=(file,root)=>opened(file,root,fd=>readFileSync(fd));
59
- // Copies the file's `size` bytes into `target` at `offset`, straight from the descriptor, and answers how many it
60
- // copied: a file whose size changed since it was walked copies another number, and the archive refuses it.
61
- function readInto(file, root, size, target, offset) {
62
- return opened(file,root,(fd,stat)=>{
63
- if (stat.size!==size) return stat.size;
64
- let copied=0;
65
- while (copied<size) {
66
- const count=readSync(fd,target,offset+copied,size-copied,copied);
67
- if (count===0) break;
68
- copied+=count;
69
- }
70
- return copied;
71
- });
69
+ // The first `size` bytes of the descriptor, a chunk at a time, stopping where the file ends.
70
+ function* readFrom(fd, size) {
71
+ for (let offset=0;offset<size;) {
72
+ const chunk=Buffer.allocUnsafe(Math.min(CHUNK_BYTES,size-offset)),count=readSync(fd,chunk,0,chunk.length,offset);
73
+ if (count===0) return;
74
+ yield count<chunk.length?chunk.subarray(0,count):chunk;
75
+ offset+=count;
76
+ }
77
+ }
78
+ const changed=path=>new Error(`${path} changed while it was being uploaded. Try again.`);
79
+ // The file's `size` bytes as the walk saw them, for the archive's entry at `path`: a file of another size now, or one
80
+ // cut short under the read, has changed since the walk, and the upload is refused rather than sent with it.
81
+ function* entryBytes(path, file, root, size) {
82
+ let count=0;
83
+ for (const chunk of opened(file,root,(fd,stat)=>{if (stat.size!==size) throw changed(path);return readFrom(fd,size);})) { count+=chunk.length;yield chunk; }
84
+ if (count!==size) throw changed(path);
72
85
  }
73
86
  // Every regular file under `start`, by its path under `root`, with its size: what is walked is not read, so a
74
- // bundle over the budget is refused on its sizes alone and the files are read once, into the archive. Names starting
75
- // with a dot are always left out; watching also leaves out the bundle folder, node_modules, dist and target, and
87
+ // bundle over the budget is refused on its sizes alone, before any file is opened. Names starting with a dot are
88
+ // always left out; watching also leaves out the bundle folder, node_modules, dist and target, and
76
89
  // passes over the symlinks an upload refuses.
77
90
  function walk(root, start, files, {watch = false, output, budget = {bytes:0}} = {}) {
78
91
  if (watch && (start === output || start.startsWith(`${output}/`))) return;
@@ -89,7 +102,7 @@ function walk(root, start, files, {watch = false, output, budget = {bytes:0}} =
89
102
  }
90
103
  } else {
91
104
  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.');
92
- if (!watch && (budget.bytes += stat.size) > MAX_BYTES) throw new Error('The build\'s output is over 1 GiB, the most Dewdrop takes.');
105
+ if (!watch && (budget.bytes += stat.size) > MAX_BYTES) throw new Error('The build\'s output is over 5 GiB, the most Dewdrop takes.');
93
106
  files.set(relative(root,start).split('\\').join('/'),{file:start,size:stat.size});
94
107
  }
95
108
  }
@@ -98,7 +111,10 @@ export function fingerprint(project) {
98
111
  const files=new Map();
99
112
  walk(project.root,project.root,files,{watch:true,output:projectPath(project.root,project.bundle)});
100
113
  const digest=createHash('sha256');
101
- for (const [path,{file}] of [...files].sort(([a],[b])=>a<b?-1:1)) { const data=readRegular(file,project.root); digest.update(`${path}\0${data.length}\0`).update(data); }
114
+ for (const [path,{file,size}] of [...files].sort(([a],[b])=>a<b?-1:1)) {
115
+ digest.update(`${path}\0${size}\0`);
116
+ for (const chunk of opened(file,project.root,fd=>readFrom(fd,size))) digest.update(chunk);
117
+ }
102
118
  return digest.digest('hex');
103
119
  }
104
120
  export function snapshot(project) {
@@ -121,11 +137,13 @@ export function snapshot(project) {
121
137
  const entries=[...files].map(([path,{file,size}])=>{
122
138
  if (path.length>240 || !path.split('/').every(p=>/^[A-Za-z0-9_][A-Za-z0-9_. -]*$/.test(p)&&!p.endsWith('.')&&!p.endsWith(' '))) throw new Error(`Can't upload ${path}: a name in it must start with a letter, digit or _ and hold only letters, digits, _, ., - and spaces, and the whole path must be under 240 characters.`);
123
139
  bytes+=size;
124
- return {path,size,read:(target,offset)=>readInto(file,root,size,target,offset)};
140
+ return {path,size,read:()=>entryBytes(path,file,root,size)};
125
141
  });
126
- // The same files always make the same bytes, which give the upload its id.
127
- const body=packTar(entries);
128
- return {body,id:hash(body),bytes,files:files.size};
142
+ // The same files always make the same bytes, which give the upload its id: `chunks` is the archive as a run of
143
+ // buffers, read through here for the id and again by the upload that sends it, `size` bytes in all.
144
+ const chunks=()=>tarChunks(entries),digest=createHash('sha256');
145
+ for (const chunk of chunks()) digest.update(chunk);
146
+ return {id:digest.digest('hex'),size:tarLength(entries),bytes,files:files.size,chunks};
129
147
  }
130
148
  export async function build(project, signal) {
131
149
  if (!project.build) return;
@@ -162,7 +180,7 @@ export async function build(project, signal) {
162
180
  const STARTER_FILES=['package.json','src','index.html','vite.config.js'];
163
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 —
164
182
  // and this CLI, at its own version.
165
- const SDK_RANGE='^0.6.0';
183
+ const SDK_RANGE='^0.8.0';
166
184
  const CLI_RANGE=`^${JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version}`;
167
185
  // The games a new one can start from: Blank, which ships with this CLI, and the starter games in the public
168
186
  // starter-templates repository, a folder each, at the commit this release pins.
package/src/tar.js CHANGED
@@ -29,23 +29,24 @@ function header(path,size) {
29
29
  return block;
30
30
  }
31
31
 
32
- // One archive of `entries` — `{path, size, read}` each, `read(target, offset)` copying the file's `size` bytes into
33
- // `target` at `offset` and answering how many it copied — in path order, with no owner, time or mode but the fixed
34
- // ones. The archive is one buffer the size of the whole, each file read straight into its place, so an upload is
35
- // held in memory once however large it is.
32
+ // One archive of `entries` — `{path, size, read}` each, `read()` giving the file's `size` bytes as a run of buffers —
33
+ // in path order, with no owner, time or mode but the fixed ones, as a run of buffers: each file's header, its bytes
34
+ // as `read` gives them, and its padding, then the two blocks that end the archive. The run is read through once for
35
+ // the archive's id and once more to send it, a few MiB at a time, so an upload of gigabytes is never held whole.
36
36
  const padded=size=>size+(size%BLOCK?BLOCK-size%BLOCK:0);
37
- export function packTar(entries) {
37
+ export function* tarChunks(entries) {
38
38
  const sorted=[...entries].sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);
39
- const out=Buffer.alloc(sorted.reduce((sum,{size})=>sum+BLOCK+padded(size),0)+2*BLOCK);
40
- let offset=0;
41
39
  for(const {path,size,read} of sorted) {
42
- header(path,size).copy(out,offset);
43
- offset+=BLOCK;
44
- if(read(out,offset)!==size)throw new Error(`${path} changed while it was being uploaded. Try again.`);
45
- offset+=padded(size);
40
+ yield header(path,size);
41
+ yield* read();
42
+ if(padded(size)>size)yield Buffer.alloc(padded(size)-size);
46
43
  }
47
- return out;
44
+ yield Buffer.alloc(2*BLOCK);
48
45
  }
46
+ // The archive's length, from its entries' sizes alone.
47
+ export const tarLength=entries=>entries.reduce((sum,{size})=>sum+BLOCK+padded(size),0)+2*BLOCK;
48
+ // The archive as one buffer, for the small ones the tests make.
49
+ export const packTar=entries=>Buffer.concat([...tarChunks(entries)]);
49
50
 
50
51
  // The regular files of a ustar archive, such as a GitHub tarball, as `{path, data}` with the archive's one top-level
51
52
  // folder taken off each path. Folders and pax headers are passed over, but for the path a pax header gives the file
package/src/watch.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Poll the project's files across edits, deletions and atomic saves; only one build and activation runs at a time.
2
+ import {watch as watchDirectory} from 'node:fs';
2
3
  import {PART_BYTES} from './client.js';
3
- import {fingerprint,build,snapshot} from './project.js';
4
+ import {fingerprint,build,snapshot,followed} from './project.js';
4
5
  import {devPlayUrl} from './play.js';
5
6
  import {RUN} from './command.js';
6
7
 
@@ -10,6 +11,8 @@ export function size(bytes) {
10
11
  const [value,unit]=bytes<1024**2?[bytes/1024,'KB']:bytes<1024**3?[bytes/1024**2,'MB']:[bytes/1024**3,'GB'];
11
12
  return `${value<10?value.toFixed(1):Math.round(value)} ${unit}`;
12
13
  }
14
+ // What Dewdrop is doing with an upload that takes a while, by the phase the client sees it in.
15
+ const PHASES={waiting:'Waiting for Dewdrop to take the upload…',assembling:'Dewdrop is assembling the upload…',checking:'Dewdrop is checking the upload…',storing:'Dewdrop is storing the upload…',copying:'Dewdrop is copying the upload to its regions…',recording:'Dewdrop is recording the upload…'};
13
16
  // Claims the game before building, so a name someone else has or an ended sign-in is known at once; then builds,
14
17
  // uploads and plays the build as the dev version.
15
18
  export async function deploy(project,client,{signal,log=console.log}={}) {
@@ -19,25 +22,47 @@ export async function deploy(project,client,{signal,log=console.log}={}) {
19
22
  await build(project,signal);
20
23
  if(fingerprint(project)!==before)return {changed:true};
21
24
  const bundle=snapshot(project);
22
- const parts=Math.max(1,Math.ceil(bundle.body.length/PART_BYTES));
25
+ const parts=Math.max(1,Math.ceil(bundle.size/PART_BYTES));
23
26
  log(`Uploading ${bundle.files} file${bundle.files===1?'':'s'} (${size(bundle.bytes)})${parts>1?` in ${parts} parts`:''}…`);
24
- await client.upload(project.game,bundle,signal);
27
+ await client.upload(project.game,bundle,signal,phase=>log(PHASES[phase]??`Dewdrop is ${phase} the upload…`));
25
28
  await client.activate(project.game,bundle.id,signal,game=>log(`Starting ${bundle.id.slice(0,12)} at ${devPlayUrl(game)}`));
26
29
  log('Ready to play.');
27
30
  return {changed:false};
28
31
  }
29
32
 
30
- // Rebuilds on every save. `reread` gives the project as dewdrop.json says it now, so an edit to it applies to the next
31
- // build; a dewdrop.json that no longer reads waits, like a failed build, for the next save.
32
- export async function watch(project,client,{signal,log=console.log,deployGame=deploy,readFingerprint=fingerprint,reread=()=>project,pollMs=200,debounceMs=500}={}) {
33
- let observed=readFingerprint(project),changedAt=Date.now()-debounceMs,dirty=true;
33
+ // Follows the tree of the project `current` gives by the system's file events, calling `changed` on each event in a
34
+ // file dev follows (`followed`, judged by the project as dewdrop.json says it at the event, so a bundle folder renamed
35
+ // is left out from the next build on), and `lost` should the watch fail later; null where the tree cannot be watched,
36
+ // when dev looks the files over instead.
37
+ export function watchTree(current,changed,lost=()=>{}) {
38
+ try {
39
+ const watcher=watchDirectory(current().root,{recursive:true,persistent:false},(event,filename)=>{
40
+ if(filename===null||followed(current(),filename.toString()))changed();
41
+ });
42
+ watcher.on('error',()=>{watcher.close();lost();});
43
+ return watcher;
44
+ }catch{return null;}
45
+ }
46
+ // Rebuilds on every save: told of each by the system's file events, a save settled EVENT_DEBOUNCE_MS after its last
47
+ // event — an editor writes a file in several steps, and a save-all many files — or, where the tree cannot be watched,
48
+ // by looking the files over every `pollMs`, a save settled `debounceMs` after the last change found. `reread` gives
49
+ // the project as dewdrop.json says it now, so an edit to it applies to the next build; a dewdrop.json that no longer
50
+ // reads waits, like a failed build, for the next save.
51
+ export const EVENT_DEBOUNCE_MS=100;
52
+ export async function watch(project,client,{signal,log=console.log,deployGame=deploy,readFingerprint=fingerprint,reread=()=>project,watchFiles=watchTree,pollMs=200,debounceMs=500}={}) {
53
+ let changedAt=Date.now()-debounceMs,dirty=true;
34
54
  let running=null;
55
+ const noted=()=>{changedAt=Date.now();dirty=true;};
56
+ let watching=watchFiles?.(()=>project,noted,()=>{watching=null;observed=readFingerprint(project);});
57
+ let observed=watching?null:readFingerprint(project);
35
58
  log(`Watching ${project.game} for changes. Ctrl-C stops.`);
36
59
  while(!signal?.aborted) {
37
60
  try {
38
- const next=readFingerprint(project);
39
- if(next!==observed){observed=next;changedAt=Date.now();dirty=true;}
40
- if(dirty&&!running&&Date.now()-changedAt>=debounceMs) {
61
+ if(!watching) {
62
+ const next=readFingerprint(project);
63
+ if(next!==observed){observed=next;noted();}
64
+ }
65
+ if(dirty&&!running&&Date.now()-changedAt>=(watching?EVENT_DEBOUNCE_MS:debounceMs)) {
41
66
  dirty=false;
42
67
  project=reread();
43
68
  running=deployGame(project,client,{signal,log}).then(result=>{
@@ -54,5 +79,6 @@ export async function watch(project,client,{signal,log=console.log,deployGame=de
54
79
  await new Promise(resolve=>setTimeout(resolve,pollMs));
55
80
  }
56
81
  await running;
82
+ watching?.close();
57
83
  log('Stopped watching. The dev version keeps running.');
58
84
  }