arcadible 1.0.37 → 1.0.38

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.
@@ -1,6 +1,7 @@
1
1
  // [import]
2
2
  import cp from "node:child_process";
3
- import { resolve as resolvePath } from "node:path";
3
+ import { readFile } from "node:fs/promises";
4
+ import { join, resolve as resolvePath } from "node:path";
4
5
  // [import]
5
6
  import { pathExists } from "fs-extra";
6
7
  // [import]
@@ -8,6 +9,7 @@ import { BUILT, bundle } from "../../runner/bundle.js";
8
9
  import { BUILD_FAILED } from "../../config/code.js";
9
10
  import { buildCommand } from "../../util/command.js";
10
11
  import { ArcError } from "../../util/error.js";
12
+ import { detect } from "../../util/lockfile.js";
11
13
  import * as phrase from "../../phrase/index.js";
12
14
  // [function]
13
15
  // a build's output has no limit: exec's default maxBuffer, 1 MB, would kill a
@@ -37,7 +39,7 @@ function build(command, { cwdPath, outputPath }) {
37
39
  : Promise.resolve(null);
38
40
  }
39
41
  // [function]
40
- // the game's runner, bundled after the project's own build, which may have
42
+ // the game's function, bundled after the project's own build, which may have
41
43
  // written the code it's made from: resolves with the bundle's path, or null
42
44
  // for a game with none.
43
45
  function buildRunner(root, main) {
@@ -49,13 +51,60 @@ function buildRunner(root, main) {
49
51
  : Promise.resolve(null);
50
52
  }
51
53
  // [function]
54
+ // whether the project's packages were never installed: its package.json names
55
+ // dependencies, and it has neither node_modules nor Yarn's Plug'n'Play file,
56
+ // which stands in for node_modules there.
57
+ export async function uninstalled(root) {
58
+ let conf;
59
+ try {
60
+ conf = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
61
+ }
62
+ catch {
63
+ return false;
64
+ }
65
+ if (typeof conf !== "object" || conf === null) {
66
+ return false;
67
+ }
68
+ const named = ["dependencies", "devDependencies"].some((key) => {
69
+ const table = conf[key];
70
+ return typeof table === "object" && table !== null
71
+ ? Object.keys(table).length > 0
72
+ : false;
73
+ });
74
+ if (!named) {
75
+ return false;
76
+ }
77
+ const [modules, pnp] = await Promise.all([
78
+ pathExists(join(root, "node_modules")),
79
+ pathExists(join(root, ".pnp.cjs")),
80
+ ]);
81
+ return !modules && !pnp;
82
+ }
83
+ // [function]
84
+ // a failed build, said first to be from packages never installed when they
85
+ // weren't: the build's own error (a bundler's, or a tool not found) says
86
+ // nothing of why.
87
+ async function explain(ex, root) {
88
+ if (!(ex instanceof ArcError) ||
89
+ ex.code !== BUILD_FAILED ||
90
+ !(await uninstalled(root))) {
91
+ return ex;
92
+ }
93
+ return new ArcError(BUILD_FAILED, phrase.packagesUninstalled(ex.message, detect(root) || "npm"), { cause: ex });
94
+ }
95
+ // [function]
52
96
  // builds the project: its own build, then its runner, when it has one. The
53
97
  // result is the build's, with `function`, the bundle's path, beside it.
54
98
  export async function buildTool({ project: { function: runner, workflow }, root, }) {
55
- const artifact = await build(buildCommand(workflow.build), {
56
- cwdPath: root,
57
- outputPath: resolvePath(root, workflow.deploy_dir),
58
- });
59
- const bundled = await buildRunner(root, runner?.main);
60
- return bundled ? { ...artifact, function: bundled } : artifact;
99
+ try {
100
+ const artifact = await build(buildCommand(workflow.build), {
101
+ cwdPath: root,
102
+ outputPath: resolvePath(root, workflow.deploy_dir),
103
+ });
104
+ const bundled = await buildRunner(root, runner?.main);
105
+ return bundled ? { ...artifact, function: bundled } : artifact;
106
+ }
107
+ catch (ex) {
108
+ throw await explain(ex, root);
109
+ }
61
110
  }
@@ -29,10 +29,17 @@ function getFlow({ id, secret: token }) {
29
29
  return apiFlow(id, null, auth(token));
30
30
  }
31
31
  // [function]
32
+ // the link page with `code` in its address (`/link/<code>`), which the account
33
+ // site fills in, in capitals, as it's printed. Lowercase, as the API gives
34
+ // it: the site redirects a path with capitals to its lowercase first.
35
+ export function linkTo(code) {
36
+ return `${LINK}/${code.toLowerCase()}`;
37
+ }
38
+ // [function]
32
39
  function createFlow({ expiresAt, secret, type }, onLoginCreated) {
33
40
  return postFlow({ expiresAt, secret, type }).then(({ code, id }) => {
34
41
  if (onLoginCreated) {
35
- onLoginCreated({ code, secret, url: LINK });
42
+ onLoginCreated({ code, link: linkTo(code), url: LINK });
36
43
  }
37
44
  return { id };
38
45
  });
@@ -1,21 +1,19 @@
1
- // a runner's secrets: the values a game's runner needs and its repository
1
+ // a runner's secrets: the values a game's function needs and its repository
2
2
  // mustn't hold, such as another service's key. Each is for one game and one
3
3
  // channel, by the name the manifest declares (function.secrets), set by the
4
4
  // game's owner, and never shown again. Nothing here keeps one.
5
5
  import { deleteGameFunctionSecret, gameFunctionSecrets, putGameFunctionSecret, } from "../../api.js";
6
6
  import { ARGUMENT_INVALID, GAME_UNAVAILABLE, SECRET_LIMIT_REACHED, SECRET_NOT_FOUND, } from "../../config/code.js";
7
+ import { SECRET_NAME } from "../../config/limit.js";
7
8
  import { ArcError } from "../../util/error.js";
8
9
  import { channelOf, gameOf, headersOf, isRefused, isStatus, needOf, } from "../game.js";
9
10
  import { gameNotOwned, secretLimitReached, secretNameInvalid, secretNotFound, secretValueInvalid, } from "../../phrase/index.js";
10
11
  // [declare]
11
- // a secret's name, as an environment variable is named; ARCADIBLE_ is kept
12
- // for Arcadible's own.
13
- const NAME = /^(?!ARCADIBLE_)[A-Z][A-Z0-9_]{0,63}$/u;
14
12
  const VALUE_MAX = 4096;
15
13
  // [function]
16
14
  // a secret's name as it was given, or a refusal before the API is asked.
17
15
  function nameOf(name) {
18
- if (typeof name !== "string" || !NAME.test(name)) {
16
+ if (typeof name !== "string" || !SECRET_NAME.test(name)) {
19
17
  throw new ArcError(ARGUMENT_INVALID, secretNameInvalid());
20
18
  }
21
19
  return name;
@@ -3,7 +3,8 @@
3
3
  // changes.
4
4
  // [import]
5
5
  import { readFile } from "node:fs/promises";
6
- import { dirname, join, relative, resolve as resolvePath } from "node:path";
6
+ import { connect } from "node:net";
7
+ import { join, relative, resolve as resolvePath } from "node:path";
7
8
  import { setTimeout as sleep } from "node:timers/promises";
8
9
  // [import]
9
10
  import { pathExists } from "fs-extra";
@@ -22,7 +23,7 @@ import { configDir } from "../../util/os.js";
22
23
  import { title } from "../../config/product.js";
23
24
  import { watchDir } from "../../serve/reload.js";
24
25
  import { remoteFiles } from "../../serve/remote.js";
25
- import { serve } from "../../serve/server.js";
26
+ import { LOOPBACK, serve, } from "../../serve/server.js";
26
27
  import { playerOf } from "../../serve/ticket.js";
27
28
  import { buildTool } from "../build/tool.js";
28
29
  import { ARCADIBLE_SDK, HOST_HTTP_PLAY } from "../../config/uri.js";
@@ -91,8 +92,31 @@ function storeArt(root) {
91
92
  };
92
93
  }
93
94
  // [function]
94
- // listens, turning a port in use into its code.
95
+ // whether something answers on `port` at `address` already. Listening alone
96
+ // doesn't say: on macOS, a program that holds the port on every IPv6 address
97
+ // (`*:<port>`) still lets 127.0.0.1 and ::1 be listened on, so the page would
98
+ // start beside it, answering some requests and not others.
99
+ function answers(port, address) {
100
+ return new Promise((resolve) => {
101
+ const socket = connect({ host: address, port });
102
+ const done = function (found) {
103
+ socket.destroy();
104
+ resolve(found);
105
+ };
106
+ socket.setTimeout(1000, () => done(false));
107
+ socket.once("connect", () => done(true));
108
+ socket.once("error", () => done(false));
109
+ });
110
+ }
111
+ // [function]
112
+ // listens, turning a port in use into its code: one another program answers
113
+ // on, on either loopback, or one listening fails on.
95
114
  async function listen(options) {
115
+ const found = options.port !== 0 &&
116
+ (await Promise.all(LOOPBACK.map((address) => answers(options.port, address)))).some(Boolean);
117
+ if (found) {
118
+ throw new ArcError(PORT_IN_USE, phrase.portInUse(options.port));
119
+ }
96
120
  try {
97
121
  return await serve(options);
98
122
  }
@@ -149,7 +173,7 @@ export async function serveTool(conf) {
149
173
  // servers of its own, or run for a player
150
174
  const servers = strings(project.client?.server_origins);
151
175
  const forServer = servers.length > 0 || Boolean(player);
152
- // the game's runner, when the project has one: its code, where its runtime
176
+ // the game's function, when the project has one: its code, where its runtime
153
177
  // is kept, and who hears how it's doing
154
178
  const runs = project.function;
155
179
  const main = runs?.main;
@@ -208,28 +232,13 @@ export async function serveTool(conf) {
208
232
  ...(conf.host ? { hostFile: resolvePath(root, conf.host) } : {}),
209
233
  wiresDrop: conf.wiresDrop ?? null,
210
234
  };
211
- // the runner's code, watched: a change runs the new code
212
- const watchRunner = function (served) {
213
- const running = served.runner;
214
- if (!running || !runnerMain) {
215
- return () => null;
216
- }
217
- return watchDir(dirname(runnerMain), () => {
218
- void running.restart();
219
- });
220
- };
221
235
  const version = game.version ?? null;
222
236
  if (url) {
223
237
  const served = await listen({ ...options, src: url });
224
238
  const probed = await probe(url);
225
- const unwatch = watchRunner(served);
226
239
  return {
227
240
  ...served,
228
241
  built: false,
229
- close() {
230
- unwatch();
231
- served.close();
232
- },
233
242
  deployDir: null,
234
243
  forServer,
235
244
  probed,
@@ -270,13 +279,11 @@ export async function serveTool(conf) {
270
279
  served.reload();
271
280
  handler.onReload();
272
281
  });
273
- const unwatch = watchRunner(served);
274
282
  return {
275
283
  ...served,
276
284
  built,
277
285
  close() {
278
286
  stop();
279
- unwatch();
280
287
  served.close();
281
288
  },
282
289
  deployDir,
@@ -9,7 +9,7 @@ import { gameValuesList, gameValuesRead, gameValuesRemove, gameValuesWrite, game
9
9
  import { ARGUMENT_INVALID, GAME_UNAVAILABLE, VALUE_NOT_FOUND, VALUE_STORAGE_FULL, VALUE_TOO_LARGE, } from "../../config/code.js";
10
10
  import { ArcError } from "../../util/error.js";
11
11
  import { gameOf, headersOf, isStatus, needOf } from "../game.js";
12
- import { gameNotOwned, valueDirEmpty, valueFileUnread, valueFull, valueKeyInvalid, valueNotFound, valueNotJson, valueSetWhat, valueTooLarge, } from "../../phrase/index.js";
12
+ import { gameNotOwned, valueDirEmpty, valueFileUnread, valueFull, valueHolds, valueKeyInvalid, valueNotFound, valueNotJson, valueSetWhat, valueTooLarge, } from "../../phrase/index.js";
13
13
  // [declare]
14
14
  // a key, as Arcadible takes one (db/function/game_value.sql, value_keys).
15
15
  export const KEY = /^[A-Za-z0-9_./-]{1,128}$/u;
@@ -96,19 +96,25 @@ function batches(items) {
96
96
  return all;
97
97
  }
98
98
  // [function]
99
+ // what the developer's values on `channel` may hold, as the API states it
100
+ // for the account's plan, or null when it can't be had.
101
+ async function holds(id, channel, headers) {
102
+ const scopes = await gameValueUsages(id, channel, headers).catch(() => null);
103
+ const mine = scopes?.find((each) => each.scope === "developer" && each.channel === channel);
104
+ return mine ? valueHolds(mine) : null;
105
+ }
106
+ // [function]
99
107
  // the API's refusals, said for a developer's values: a game that isn't the
100
- // caller's, and a scope that's full.
101
- function refused(id, channel) {
102
- return (err) => {
108
+ // caller's, and a scope that's full, with what it may hold.
109
+ function refused(id, channel, headers) {
110
+ return async (err) => {
103
111
  if (isStatus(err, 404)) {
104
112
  throw new ArcError(GAME_UNAVAILABLE, gameNotOwned(id), {
105
113
  cause: err,
106
114
  });
107
115
  }
108
116
  if (isStatus(err, 507)) {
109
- throw new ArcError(VALUE_STORAGE_FULL, valueFull(channel), {
110
- cause: err,
111
- });
117
+ throw new ArcError(VALUE_STORAGE_FULL, valueFull(channel, await holds(id, channel, headers)), { cause: err });
112
118
  }
113
119
  throw err;
114
120
  };
@@ -145,7 +151,7 @@ export async function set(current, { channel, dir, file, input, key, ...conf })
145
151
  cause: err,
146
152
  });
147
153
  }
148
- return refused(id, where)(err);
154
+ return refused(id, where, headers)(err);
149
155
  });
150
156
  }
151
157
  return { channel: where, keys: items.map((item) => item.key) };
@@ -158,7 +164,7 @@ export async function get(current, { channel, key, ...conf }) {
158
164
  const where = needOf(channel);
159
165
  const id = await gameOf(conf);
160
166
  const headers = headersOf(current);
161
- const [value] = await gameValuesRead(id, where, [named], headers).catch(refused(id, where));
167
+ const [value] = await gameValuesRead(id, where, [named], headers).catch(refused(id, where, headers));
162
168
  if (!value) {
163
169
  throw new ArcError(VALUE_NOT_FOUND, valueNotFound({ channel: where, key: named }));
164
170
  }
@@ -177,7 +183,7 @@ export async function list(current, { channel, prefix = "", ...conf }) {
177
183
  const all = [];
178
184
  let after = "";
179
185
  for (;;) {
180
- const page = await gameValuesList(id, where, { after, limit: PAGE, prefix }, headers).catch(refused(id, where));
186
+ const page = await gameValuesList(id, where, { after, limit: PAGE, prefix }, headers).catch(refused(id, where, headers));
181
187
  all.push(...page.entries);
182
188
  if (page.next === null) {
183
189
  return all;
@@ -193,7 +199,7 @@ export async function remove(current, { channel, key, ...conf }) {
193
199
  const where = needOf(channel);
194
200
  const id = await gameOf(conf);
195
201
  const headers = headersOf(current);
196
- const { removed } = await gameValuesRemove(id, where, [named], headers).catch(refused(id, where));
202
+ const { removed } = await gameValuesRemove(id, where, [named], headers).catch(refused(id, where, headers));
197
203
  if (removed === 0) {
198
204
  throw new ArcError(VALUE_NOT_FOUND, valueNotFound({ channel: where, key: named }));
199
205
  }
@@ -209,7 +215,7 @@ export async function usage(current, { channel, ...conf }) {
209
215
  const where = needOf(channel);
210
216
  const id = await gameOf(conf);
211
217
  const headers = headersOf(current);
212
- const scopes = (await gameValueUsages(id, where, headers).catch(refused(id, where))) ?? [];
218
+ const scopes = (await gameValueUsages(id, where, headers).catch(refused(id, where, headers))) ?? [];
213
219
  const calls = await gameValueCalls(id, headers).catch(() => null);
214
220
  return {
215
221
  calls: calls?.find((each) => each.channel === where) ?? null,
package/dist/api.js CHANGED
@@ -253,7 +253,7 @@ export function deleteKey(key, params, headers) {
253
253
  return answer(isKeyRevoked, "a key", del(endpoint(pathOf `/keys/${key}`, params), headers));
254
254
  }
255
255
  // [function]
256
- // the secrets of the caller's own game's runner, by channel and name: never
256
+ // the secrets of the caller's own game's function, by channel and name: never
257
257
  // their values.
258
258
  export function gameFunctionSecrets(id, params, headers) {
259
259
  return answer(listed(isSecret), "a function's secrets", get(endpoint(pathOf `/games/${id}/function_secrets`, params), headers));
package/dist/arc.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // the entry: runs the command the first argument names, or with none, or
2
2
  // one that isn't a command, prints the help, the version, or what's wrong.
3
3
  // [import]
4
- import { normalize } from "./cli/argv.js";
4
+ import { fail, normalize } from "./cli/argv.js";
5
5
  import { execute } from "./cli/command.js";
6
6
  import { COMMANDS } from "./commands.js";
7
7
  import { version } from "./config/package.js";
@@ -12,14 +12,18 @@ const TOOL = tool;
12
12
  const VERSION = version;
13
13
  // [function]
14
14
  // `arc` with no command: the help, which lists every command that isn't
15
- // hidden, the version, or an argument that isn't a command, refused.
15
+ // hidden, the version, or an argument that isn't a command, refused as an
16
+ // unknown option on a command is (argument_invalid), as JSON with --json,
17
+ // which is known here, so it's never the refused argument.
16
18
  async function help(args) {
17
19
  const cli = COMMANDS.filter((each) => !each.hidden)
18
20
  .reduce((each, { name, summary }) => each.command(name, summary), yargs(normalize(args)).scriptName(TOOL).usage("$0 <command> [options]"))
21
+ .option("json", { alias: "j", hidden: true, type: "boolean" })
19
22
  .help("help")
20
23
  .alias("help", "h")
21
24
  .version(VERSION)
22
25
  .alias("version", "v")
26
+ .fail(fail(args))
23
27
  .strict();
24
28
  const argv = await cli.parse();
25
29
  if (!argv._.length) {
package/dist/cli/argv.js CHANGED
@@ -49,10 +49,12 @@ export function fail(args) {
49
49
  throw ex;
50
50
  }
51
51
  if (asJson) {
52
- // it exits, once stdout has written the document: not waited for.
52
+ // it exits, once stdout has written the document: not waited for, and
53
+ // nothing else is written meanwhile, so stderr stays empty.
53
54
  void abort("", new ArcError(ARGUMENT_INVALID, String(message)), {
54
55
  json: asJson,
55
56
  });
57
+ return;
56
58
  }
57
59
  cli.showHelp("error");
58
60
  console.error(`\n${message}`);
@@ -17,6 +17,7 @@ import { cpuTime, functionLogsNone } from "../../phrase/index.js";
17
17
  import { p } from "../../util/log.js";
18
18
  import { deepSort } from "../../util/objs.js";
19
19
  import { SpinnerWheel } from "../../util/spinner.js";
20
+ import { interrupted } from "../../util/term.js";
20
21
  import { follow, logs, } from "../../action/function/logs.js";
21
22
  import { whoami } from "../../action/whoami/tool.js";
22
23
  // [function]
@@ -136,6 +137,12 @@ export default defineCommand({
136
137
  version: argv.release,
137
138
  };
138
139
  if (argv.follow) {
140
+ // it runs until stopped: a Ctrl+C ends it as a signal does (130), on
141
+ // a line of its own.
142
+ process.once("SIGINT", () => {
143
+ interrupted();
144
+ process.exit(130);
145
+ });
139
146
  await follow(current, conf, (entry) => {
140
147
  show(entry, json);
141
148
  }).catch(ended(current));
@@ -39,10 +39,9 @@ function onLoginEnter(fn) {
39
39
  // after a blank line.
40
40
  function handler({ browser, qrcode: qr, shown, sw, }) {
41
41
  return {
42
- onLoginCreated({ code: dac, secret, url }) {
42
+ onLoginCreated({ code: dac, link, url }) {
43
43
  sw.stop(true);
44
44
  shown();
45
- const link = `${url}/${secret}`;
46
45
  p(loggingIn());
47
46
  qrcode.generate(link, { small: true }, (code) => {
48
47
  if (qr) {
@@ -11,6 +11,7 @@ import { CWD, QUIET } from "../cli/options.js";
11
11
  import { launched } from "../util/output.js";
12
12
  import { launch } from "../util/shell.js";
13
13
  import { SpinnerWheel } from "../util/spinner.js";
14
+ import { interrupted } from "../util/term.js";
14
15
  import { serveTool } from "../action/serve/tool.js";
15
16
  import { SERVE_URL } from "../config/url.js";
16
17
  // [declare]
@@ -61,7 +62,7 @@ function remoteWarnings({ quiet }) {
61
62
  return function (name, file, ex) {
62
63
  const message = ex
63
64
  ? phrase.remoteUnreachable(name)
64
- : file?.kept && phrase.remoteKept(name, file.fetchedAt);
65
+ : file?.kept && phrase.remoteKept(name, file.fetchedAt, file.refused);
65
66
  if (!message || quiet || warned.has(message)) {
66
67
  return;
67
68
  }
@@ -165,13 +166,18 @@ export default defineCommand({
165
166
  served.close();
166
167
  process.exit(0);
167
168
  };
168
- process.once("SIGINT", stop);
169
+ process.once("SIGINT", () => {
170
+ interrupted();
171
+ stop();
172
+ });
169
173
  process.once("SIGTERM", stop);
170
174
  if (!quiet) {
171
175
  const blocks = [
172
176
  [phrase.playLabel(), `${served.page}/`],
173
177
  [phrase.serveAlone(), served.game],
174
- ...(served.runner ? [[phrase.runnerLabel(), served.runner.url]] : []),
178
+ ...(served.runner
179
+ ? [[phrase.runnerLabel(), `${served.runner.url}/`]]
180
+ : []),
175
181
  // a game with a function or servers of its own can be played by
176
182
  // more than one player: a window each, named by its address
177
183
  ...(served.runner || served.forServer
@@ -4,6 +4,7 @@ import { p } from "../../util/log.js";
4
4
  import { CHANNEL, CWD, JSON_OUTPUT, QUIET } from "../../cli/options.js";
5
5
  import { run } from "../function/secret/run.js";
6
6
  import { table } from "../../util/table.js";
7
+ import { valueHolds, valueSize } from "../../phrase/index.js";
7
8
  import { usage } from "../../action/value/tool.js";
8
9
  // [declare]
9
10
  // each scope as it's said: a player's limits are each player's own.
@@ -14,16 +15,6 @@ const NAMES = {
14
15
  server: "server",
15
16
  };
16
17
  // [function]
17
- // a size in the unit that reads best: "0", "812 B", "14 KB", "2.4 MB".
18
- function size(bytes) {
19
- if (bytes < 1024) {
20
- return bytes === 0 ? "0" : `${bytes} B`;
21
- }
22
- if (bytes < 1024 * 1024) {
23
- return `${Math.round(bytes / 1024)} KB`;
24
- }
25
- return `${(bytes / (1024 * 1024)).toFixed(1).replace(/\.0$/u, "")} MB`;
26
- }
27
18
  // [function]
28
19
  // the scopes as a table. A player's row counts every player's together, and
29
20
  // its limit is what each may hold, so the most any one holds is beside it.
@@ -32,17 +23,15 @@ function rows(scopes) {
32
23
  ["SCOPE", "KEYS", "SIZE", "MAY HOLD"],
33
24
  ...scopes.map((each) => {
34
25
  const players = each.scope === "player";
35
- const limit = each.keys_limit === null && each.bytes_limit === null
36
- ? "no limit"
37
- : `${each.keys_limit === null ? "any number of" : each.keys_limit.toLocaleString("en-US")} keys, ${each.bytes_limit === null ? "any size" : size(each.bytes_limit)}`;
26
+ const limit = valueHolds(each);
38
27
  return [
39
28
  NAMES[each.scope] ?? each.scope,
40
29
  players
41
30
  ? `${each.keys} (${each.owners} ${each.owners === 1 ? "player" : "players"}, ${each.keys_most} at most)`
42
31
  : String(each.keys),
43
32
  players
44
- ? `${size(each.bytes)} (${size(each.bytes_most)} at most)`
45
- : size(each.bytes),
33
+ ? `${valueSize(each.bytes)} (${valueSize(each.bytes_most)} at most)`
34
+ : valueSize(each.bytes),
46
35
  players && limit !== "no limit" ? `${limit} each` : limit,
47
36
  ];
48
37
  }),
@@ -18,3 +18,12 @@ export const TOTAL_SIZE = 256 * MB;
18
18
  export const ZIP_SIZE = 64 * MB;
19
19
  // a function's bundle, as Arcadible runs it (the subscriber's RUNNER_MAX).
20
20
  export const FUNCTION_SIZE = 1 * MB;
21
+ // a secret's name, as the API, the database (chk_runner_secret_name_is_valid),
22
+ // and the subscriber hold it: capitals, digits, and underscores, starting
23
+ // with a letter, 64 at most; ARCADIBLE_ is kept for Arcadible's own. The
24
+ // manifest's [function] secrets and `arc unstable function secret` both take
25
+ // this one.
26
+ export const SECRET_NAME = /^(?!ARCADIBLE_)[A-Z][A-Z0-9_]{0,63}$/u;
27
+ // the most secrets a game's channel holds (api_put_game_function_secret), so
28
+ // the most a function may declare.
29
+ export const SECRETS = 16;
@@ -24,6 +24,14 @@ export function buildFailed({ code, signal, stderr, stdout, }) {
24
24
  : `Build failed with exit code ${code}.`, ...(output ? [output] : []));
25
25
  }
26
26
  // [function]
27
+ // a failed build's `message` (its reason, then what it printed), told first
28
+ // that the project's packages aren't installed, and to install them with
29
+ // `manager`, the one its lockfile names.
30
+ export function packagesUninstalled(message, manager) {
31
+ const [reason = "", ...rest] = message.split("\n\n");
32
+ return blocks(reason, `The project's packages aren't installed. Run \`${manager} install\` first.`, ...rest);
33
+ }
34
+ // [function]
27
35
  export function buildOutputMissing(dir) {
28
36
  return `Build didn't create deploy_dir (${dir}).`;
29
37
  }
@@ -20,9 +20,14 @@ function remoteName(name) {
20
20
  return name === "host" ? "the play page's host" : `/${HANDLE}/${name}`;
21
21
  }
22
22
  // [function]
23
- // arc serve's copy of one of Arcadible's files, kept from `fetchedAt`.
24
- export function remoteKept(name, fetchedAt) {
25
- return `Unable to reach ${TITLE}.\nServing ${remoteName(name)} saved on ${fetchedAt.slice(0, 10)}.`;
23
+ // arc serve's copy of one of Arcadible's files, kept from `fetchedAt`: served
24
+ // because Arcadible couldn't be reached, or with `refused`, because it
25
+ // answered that status for a file that's always there.
26
+ export function remoteKept(name, fetchedAt, refused) {
27
+ const why = refused
28
+ ? `${TITLE} answered ${refused} for ${remoteName(name)}.`
29
+ : `Unable to reach ${TITLE}.`;
30
+ return `${why}\nServing ${remoteName(name)} saved on ${fetchedAt.slice(0, 10)}.`;
26
31
  }
27
32
  // [function]
28
33
  export function remoteUnreachable(name) {
@@ -8,7 +8,7 @@ export function keyCreated({ channel, id, name, }) {
8
8
  }
9
9
  // [function]
10
10
  export function keyRevoked(id) {
11
- return `Revoked ${id}. Servers using it stop working at once.`;
11
+ return blocks(`Revoked ${id}.`, "Servers using it stop working at once.");
12
12
  }
13
13
  // [function]
14
14
  export function keyNone() {
@@ -27,8 +27,33 @@ export function valueTooLarge(key) {
27
27
  return blocks(`Too large: ${key}`, "A value is up to 64 KB of JSON.");
28
28
  }
29
29
  // [function]
30
- export function valueFull(channel) {
31
- return blocks(`The developer's values on ${channel} are full.`, "They hold 10,000 keys and 64 MB. Remove some with `arc unstable value remove <key>`, then try again.");
30
+ // a size in the unit that reads best: "0", "812 B", "14 KB", "2.4 MB".
31
+ export function valueSize(bytes) {
32
+ if (bytes < 1024) {
33
+ return bytes === 0 ? "0" : `${bytes} B`;
34
+ }
35
+ if (bytes < 1024 * 1024) {
36
+ return `${Math.round(bytes / 1024)} KB`;
37
+ }
38
+ return `${(bytes / (1024 * 1024)).toFixed(1).replace(/\.0$/u, "")} MB`;
39
+ }
40
+ // [function]
41
+ // what a scope may hold, as the API states it (null is no limit): "10,000
42
+ // keys, 64 MB", or "no limit".
43
+ export function valueHolds({ bytes_limit: bytes, keys_limit: keys, }) {
44
+ if (keys === null && bytes === null) {
45
+ return "no limit";
46
+ }
47
+ return `${keys === null ? "any number of" : keys.toLocaleString("en-US")} keys, ${bytes === null ? "any size" : valueSize(bytes)}`;
48
+ }
49
+ // [function]
50
+ // the developer's values on `channel` full, with what they may hold, the
51
+ // account's plan's, when the API could say.
52
+ export function valueFull(channel, holds) {
53
+ const remove = "Remove some with `arc unstable value remove <key>`, then try again.";
54
+ return blocks(`The developer's values on ${channel} are full.`, holds === null
55
+ ? `${remove}\n\`arc unstable value usage\` shows what they hold.`
56
+ : `They may hold ${holds}. ${remove}`);
32
57
  }
33
58
  // [function]
34
59
  export function valueSet({ channel, keys, }) {
@@ -1,4 +1,4 @@
1
- // a game's runner, bundled: its server code (plan/SERVERS.md, Runners) with
1
+ // a game's function, bundled: its server code (plan/SERVERS.md, Runners) with
2
2
  // what it imports, as one module whose default export is the developer's
3
3
  // handler. It's the developer's code alone: Arcadible's entry, which is
4
4
  // where a function's script starts, is added beside it where it runs, by
@@ -6,7 +6,7 @@
6
6
  // build carries an entry of the day its `arc` was installed.
7
7
  // [import]
8
8
  import { stat } from "node:fs/promises";
9
- import { join } from "node:path";
9
+ import { join, resolve } from "node:path";
10
10
  // [import]
11
11
  import { build } from "esbuild";
12
12
  import { pathExists } from "fs-extra";
@@ -41,7 +41,11 @@ export const WRONG = {
41
41
  // finds is a warning, a warning has a code, and a code has an entry on the
42
42
  // public Errors page, which says nothing of functions until they ship
43
43
  // (TODO.md, Agreed next).
44
- export async function bundle({ main, onPackages, outfile, }) {
44
+ //
45
+ // `onInputs`, when given, hears every file the bundle was made from, each a
46
+ // full path, so `arc serve` can run the function again when any of them
47
+ // changes, wherever it is (a game's rules its function shares).
48
+ export async function bundle({ main, onInputs, onPackages, outfile, }) {
45
49
  if (!(await pathExists(main))) {
46
50
  throw new ArcError(BUILD_FAILED, phrase.runnerMissing(main));
47
51
  }
@@ -52,7 +56,7 @@ export async function bundle({ main, onPackages, outfile, }) {
52
56
  conditions: ["workerd", "worker", "browser"],
53
57
  format: "esm",
54
58
  logLevel: "silent",
55
- metafile: Boolean(onPackages),
59
+ metafile: Boolean(onPackages ?? onInputs),
56
60
  outfile,
57
61
  platform: "neutral",
58
62
  entryPoints: [main],
@@ -68,6 +72,11 @@ export async function bundle({ main, onPackages, outfile, }) {
68
72
  throw new ArcError(FUNCTION_TOO_LARGE, phrase.functionTooLarge(size));
69
73
  }
70
74
  onPackages?.(packagesOf(inputs));
75
+ // a metafile's inputs are relative to where esbuild ran, and a plugin's
76
+ // own (`ns:name`) aren't files
77
+ onInputs?.(inputs
78
+ .filter((input) => !/^[a-z-]+:/iu.test(input) || /^[a-z]:[\\/]/iu.test(input))
79
+ .map((input) => resolve(input)));
71
80
  return outfile;
72
81
  }
73
82
  // [function]