@nodeloc/apps-cli 0.0.0-stage → 0.3.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nodeloc
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,122 @@
1
- # Temporary Holding Version
1
+ # nodeloc-apps
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 在本地开发社区 app,然后发布到论坛。
4
+
5
+ app 是一个导出若干 handler 的 JS 模块,handler 跑在论坛服务端的沙箱里。这个 CLI 负责本地那一半:登录、打包、在只有你能看见的私有安装上试跑、发布新版本、看日志。
6
+
7
+
8
+ ## 安装
9
+
10
+ 需要 **Node.js 22 或更高**。
11
+
12
+ ```bash
13
+ git clone https://github.com/nodeloc/nodeloc-apps-cli.git
14
+ cd nodeloc-apps-cli
15
+ npm install -g .
16
+ ```
17
+
18
+ ## 登录
19
+
20
+ ```bash
21
+ nodeloc-apps login --site https://www.nodeloc.com
22
+ ```
23
+
24
+ 终端打印一个校验码和一个链接。在浏览器里打开,**核对页面上的码和终端里的一致**(不一致就直接关掉,说明这个批准请求不是你发起的),点「批准」,终端自己就拿到了凭据。
25
+
26
+ 凭据存在 `~/.config/nodeloc-apps/credentials.json`,仅本人可读。这把 key 只能发布你自己的 app,站上别的事一件都干不了。再次 `login` 会让上一把立即失效。
27
+
28
+ 在 CI 或没有浏览器的机器上,改用环境变量(在论坛作者页点「生成 key」拿到),它们优先于存下来的凭据:
29
+
30
+ ```bash
31
+ export NODELOC_APPS_SITE=https://www.nodeloc.com
32
+ export NODELOC_APPS_API_KEY=...
33
+ export NODELOC_APPS_API_USERNAME=你的用户名
34
+ ```
35
+
36
+ ## 用法
37
+
38
+ ```bash
39
+ nodeloc-apps init my-game --template counter # counter | race | bot
40
+ cd my-game
41
+
42
+ nodeloc-apps dev # 打包 + 静态检查,不上传
43
+ nodeloc-apps playtest # 推到只有你能看见的私有安装,改文件自动重推
44
+ nodeloc-apps upload --note "加了排行榜"
45
+ nodeloc-apps logs --limit 50
46
+ ```
47
+
48
+ | 命令 | 作用 |
49
+ |---|---|
50
+ | `login --site <url>` | 通过浏览器登录 |
51
+ | `whoami` | 当前身份 |
52
+ | `logout` | 忘掉本机凭据 |
53
+ | `init <slug> [--template counter\|race\|bot]` | 在 `./<slug>` 建项目 |
54
+ | `dev` | 打包并检查,不上传 |
55
+ | `playtest` | 推到私有安装,监听改动自动重推 |
56
+ | `upload [--note "..."]` | 发布新版本:不审核,提交即生效,所有安装(包括已经放进帖子里的)都换到这一版;打印每个外部主机的审批状态 |
57
+ | `logs [--limit N]` | 看每次调用的 handler、结果、耗时、错误码 |
58
+
59
+ `dev` 会把相对 import 内联成单个模块,并提前拦掉服务端一定会拒的写法:缺 `render` 导出(service app 则要求至少有一个 `onTrigger`/`onSchedule`/`onFetch`)、`eval`、`node:` 内建、浏览器全局、`fetch`。
60
+
61
+ 沙箱没有网络,这一点不会变。要访问外部服务,handler 返回 `http.fetch` effect,由站点代为请求,结果之后作为一次单独的 `onFetch` 调用送回来——只允许 https,只允许管理人员批准过的精确主机名。代码不审核,但 `domains` 里的每个主机都要管理人员逐个批准,批准之前(试玩里也一样)请求会得到 `E_HTTP_DOMAIN_DENIED`;`upload` 和 `playtest` 会打印每个主机的状态(已批准、等批准、没有获批、已撤回)。被拒、撤回的主机再次申请也不会重新排队,请联系管理人员。
62
+
63
+ ## 项目结构
64
+
65
+ ```
66
+ my-game/
67
+ app.json # 平台读的那几个字段
68
+ src/main.js # 入口
69
+ ```
70
+
71
+ ```jsonc
72
+ {
73
+ "slug": "my-game",
74
+ "name": "My game", // 或按语言给:{"en": "My game", "zh_CN": "我的游戏"}
75
+ "entry": "src/main.js",
76
+ "scopes": ["kv"],
77
+ "surface": "blocks", // blocks | webview | service
78
+ "kind": "applet", // game | applet | bot:目录和侧栏把它放在哪一栏
79
+ "placement": "single", // single | many
80
+ "triggers": [], // 唤醒 onTrigger 的站点事件
81
+ "domains": [], // 允许访问的精确主机名,每个都要管理人员批准
82
+ "pin_installs": false // true:已经放进帖子里的不换成这一版
83
+ }
84
+ ```
85
+
86
+ 新版本一发布,这个 app 所有的安装(帖子里的、节点上和全站的机器人)都换到新版本,存的数据和设置原样保留,不重跑 `onInstall`。所以新版本要能读旧版本存下的数据;读不了时在这一版的 `app.json` 里写 `"pin_installs": true`:已经放进帖子里的保持原来的版本(重新放一次才换),新放的和机器人安装用新版本。之后的版本去掉这个字段,帖子里的会一起换过来。
87
+
88
+ `surface: "service"` 是没有界面的 app——机器人。它不渲染,也没有可点的东西:由 `triggers` 里的站点事件唤醒,以自己的账号说话,并且由**管理员**把它装到全站或某个分类上,而不是由成员嵌进帖子里。这类 app 用 `--template bot` 起步。
89
+
90
+ `kind` 决定 app 在目录和侧栏里的归类:`game` 是打开就玩的游戏,`applet` 是嵌在帖子或节点里的小工具,`bot` 是没有界面的机器人。不写的话,service 记为 bot,其余记为 applet;提交后作者也可以在"你的应用"里改。
91
+
92
+ `name` 按语言给时,读者在侧栏和目录里看到自己语言的名称,没有对应翻译的看到 `en` 那个(没有 `en` 就用第一个)。它只在第一次 `push` 创建 app 时读取;已有的 app 在"你的应用"里改。
93
+
94
+ `placement` 值得想清楚:`single` 表示全站只应存在一处(有共享排行榜的都属于此类,因为每个安装的共享区是独立的,放两处等于把榜劈成两半);`many` 适合投票、倒计时、骰子这类每处一份才合理的东西。
95
+
96
+ ## 让 AI 帮你写 app
97
+
98
+ `skills/nodeloc-app/` 是一个 [Claude Code skill](https://docs.claude.com/en/docs/claude-code/skills):把平台的规则(handler 签名、组件表和取值范围、权限对照、什么可信什么不可信)交给 agent,省掉它靠猜和反复试错。
99
+
100
+ 装到个人目录,对所有项目生效:
101
+
102
+ ```bash
103
+ mkdir -p ~/.claude/skills && cp -r skills/nodeloc-app ~/.claude/skills/
104
+ ```
105
+
106
+ 或者只装进某个 app 项目:
107
+
108
+ ```bash
109
+ mkdir -p my-game/.claude/skills && cp -r skills/nodeloc-app my-game/.claude/skills/
110
+ ```
111
+
112
+ 之后在 app 目录里直接说「加个排行榜」就行,agent 会知道分数必须由 handler 决定、共享区只有 handler 写得进去。
113
+
114
+ ## 开发本 CLI
115
+
116
+ ```bash
117
+ npm test
118
+ ```
119
+
120
+ ## License
121
+
122
+ MIT
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { init, dev, upload, playtest, logs } from "../src/commands.js";
4
+ import { login, logout, whoami } from "../src/login.js";
5
+
6
+ const COMMANDS = { login, logout, whoami, init, dev, upload, playtest, logs };
7
+
8
+ const USAGE = `nodeloc-apps <command>
9
+
10
+ login --site <url> Sign in through your browser
11
+ whoami Show who you are signed in as
12
+ logout Forget the stored credential
13
+
14
+ init <slug> Start a new app in ./<slug>
15
+ dev Bundle and check the app without publishing
16
+ playtest Push to a private install and re-push on every change
17
+ upload Submit the current app for review
18
+ logs Show what your app did when it ran
19
+ `;
20
+
21
+ const io = {
22
+ log: (message) => process.stdout.write(`${message}\n`),
23
+ warn: (message) => process.stderr.write(`${message}\n`),
24
+ };
25
+
26
+ const [command, ...args] = process.argv.slice(2);
27
+
28
+ // `upload --help` must not upload.
29
+ const askingForHelp = ["--help", "-h"].some((flag) => flag === command || args.includes(flag));
30
+ if (!command || askingForHelp) {
31
+ io.log(USAGE);
32
+ process.exit(command ? 0 : 1);
33
+ }
34
+
35
+ const handler = COMMANDS[command];
36
+ if (!handler) {
37
+ io.warn(`Unknown command: ${command}\n`);
38
+ io.log(USAGE);
39
+ process.exit(1);
40
+ }
41
+
42
+ try {
43
+ await handler(args, io);
44
+ } catch (error) {
45
+ io.warn(error.message);
46
+ process.exit(1);
47
+ }
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@nodeloc/apps-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "Build and publish sandboxed NodeLoc apps",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "nodeloc-apps": "./bin/nodeloc-apps.js"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "src",
13
+ "templates"
14
+ ],
15
+ "engines": {
16
+ "node": ">=22"
17
+ },
18
+ "scripts": {
19
+ "test": "node --test \"test/*.test.mjs\""
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://github.com/nodeloc/nodeloc-apps-cli.git"
24
+ },
25
+ "homepage": "https://github.com/nodeloc/nodeloc-apps-cli"
26
+ }
package/src/api.js ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Thin wrapper over the authoring endpoints.
3
+ *
4
+ * Every failure is turned into a message an author can act on. A CLI that
5
+ * prints a raw 422 body is a CLI people stop using.
6
+ */
7
+
8
+ export class ApiError extends Error {
9
+ constructor(message, status) {
10
+ super(message);
11
+ this.name = "ApiError";
12
+ this.status = status;
13
+ }
14
+ }
15
+
16
+ export function createClient({ site, key, username }, fetchImpl = fetch) {
17
+ async function request(method, path, body) {
18
+ let response;
19
+ try {
20
+ response = await fetchImpl(`${site}${path}`, {
21
+ method,
22
+ headers: {
23
+ "Api-Key": key,
24
+ "Api-Username": username,
25
+ "Content-Type": "application/json",
26
+ Accept: "application/json",
27
+ },
28
+ body: body === undefined ? undefined : JSON.stringify(body),
29
+ });
30
+ } catch (error) {
31
+ throw new ApiError(`Could not reach ${site}: ${error.message}`);
32
+ }
33
+
34
+ if (response.status === 204) {
35
+ return null;
36
+ }
37
+
38
+ const text = await response.text();
39
+ let payload = null;
40
+ if (text) {
41
+ try {
42
+ payload = JSON.parse(text);
43
+ } catch {
44
+ payload = null;
45
+ }
46
+ }
47
+
48
+ if (!response.ok) {
49
+ throw new ApiError(explain(response.status, payload), response.status);
50
+ }
51
+
52
+ return payload;
53
+ }
54
+
55
+ return {
56
+ listApps: () => request("GET", "/apps/authoring.json"),
57
+ getApp: (id) => request("GET", `/apps/authoring/apps/${id}.json`),
58
+ createApp: (app) => request("POST", "/apps/authoring/apps.json", { ...app }),
59
+ submitVersion: (appId, version) =>
60
+ request("POST", `/apps/authoring/apps/${appId}/versions.json`, version),
61
+ logs: (appId, limit) => request("GET", `/apps/authoring/apps/${appId}/logs.json?limit=${limit}`),
62
+ // One request per save. It writes a draft version and aims the author's
63
+ // playtest at it, which is a different thing from submitting a version —
64
+ // see `playtest` in commands.js.
65
+ pushPlaytest: (appId, version) =>
66
+ request("POST", `/apps/authoring/apps/${appId}/push.json`, version),
67
+ };
68
+ }
69
+
70
+ function explain(status, payload) {
71
+ const errors = payload?.errors;
72
+ if (Array.isArray(errors) && errors.length) {
73
+ return errors.join("\n");
74
+ }
75
+
76
+ switch (status) {
77
+ case 403:
78
+ return "Your account is not allowed to publish apps on this site.";
79
+ case 404:
80
+ return "Not found. Check the app slug and that you own it.";
81
+ case 409:
82
+ return "This app already has a version waiting for review (an older site that still reviews versions).";
83
+ case 429:
84
+ return "Rate limited, or you have hit the app limit for your account.";
85
+ default:
86
+ return `Request failed with status ${status}.`;
87
+ }
88
+ }
package/src/bundle.js ADDED
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Turning a source directory into the single module the platform runs.
3
+ *
4
+ * The platform never runs a build, so bundling happens here, on the author's
5
+ * machine, where a failure is theirs to see and fix immediately.
6
+ */
7
+
8
+ import { readFile } from "node:fs/promises";
9
+ import path from "node:path";
10
+
11
+ // What a module has to export to be runnable at all, per surface. A bot has no
12
+ // interface, so requiring `render` of one would mean shipping a function that
13
+ // is never called; what it must have instead is at least one way in.
14
+ const REQUIRED_EXPORTS = ["render"];
15
+ const SERVICE_ENTRY_POINTS = ["onTrigger", "onSchedule", "onFetch", "onInstall"];
16
+
17
+ // Both forms have to be caught: `import x from "./y.js"` and the side-effect
18
+ // `import "./y.js"`. Missing the second would ship an import statement the
19
+ // sandbox cannot resolve, since nothing outside the bundle exists there.
20
+ //
21
+ // The binding clause is captured too, because inlining a module throws its
22
+ // import statement away and takes any renaming in it along: `import { read as
23
+ // check }` left `check` undefined in a bundle that passed every check here and
24
+ // then failed at runtime, which is the worst way for this to go wrong.
25
+ const IMPORT_PATTERN =
26
+ /^\s*import\s+(?:([^;'"]*?)\s+from\s+)?["'](\.[^"']+)["'];?/gm;
27
+
28
+ /** `{ read as check, other }` -> the aliases that have to survive inlining. */
29
+ function aliasesIn(clause) {
30
+ const braces = /\{([^}]*)\}/.exec(clause ?? "");
31
+ if (!braces) {
32
+ return [];
33
+ }
34
+
35
+ return braces[1]
36
+ .split(",")
37
+ .map((part) => /^\s*([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)\s*$/.exec(part))
38
+ .filter(Boolean)
39
+ .map(([, original, alias]) => `const ${alias} = ${original};`);
40
+ }
41
+
42
+ /** A default import has no name to bind to once the module is inlined. */
43
+ function defaultImportIn(clause) {
44
+ return /^\s*[A-Za-z_$][\w$]*\s*(,|$)/.test(clause ?? "") ? clause.trim().split(/[\s,]/)[0] : null;
45
+ }
46
+
47
+ export class BundleError extends Error {}
48
+
49
+ /**
50
+ * Inlines relative imports depth-first. This is deliberately not a general
51
+ * bundler: apps are small, and a dependency graph an author cannot read in one
52
+ * sitting is a dependency graph a reviewer cannot check.
53
+ */
54
+ export async function bundle(entryPath, { maxBytes = 512 * 1024, seen = new Set() } = {}) {
55
+ const resolved = path.resolve(entryPath);
56
+
57
+ if (seen.has(resolved)) {
58
+ throw new BundleError(`Circular import through ${path.basename(resolved)}`);
59
+ }
60
+ seen.add(resolved);
61
+
62
+ let source;
63
+ try {
64
+ source = await readFile(resolved, "utf8");
65
+ } catch {
66
+ throw new BundleError(`Cannot read ${resolved}`);
67
+ }
68
+
69
+ const dir = path.dirname(resolved);
70
+ const parts = [];
71
+ let lastIndex = 0;
72
+
73
+ for (const match of source.matchAll(IMPORT_PATTERN)) {
74
+ const [statement, clause, specifier] = match;
75
+ const target = path.resolve(dir, specifier);
76
+ const withExtension = target.endsWith(".js") ? target : `${target}.js`;
77
+
78
+ const defaultImport = defaultImportIn(clause);
79
+ if (defaultImport) {
80
+ throw new BundleError(
81
+ `\`import ${defaultImport} from "${specifier}"\` cannot be inlined. ` +
82
+ "Export and import it by name instead."
83
+ );
84
+ }
85
+
86
+ parts.push(source.slice(lastIndex, match.index));
87
+ parts.push(await bundle(withExtension, { maxBytes, seen }));
88
+ // Re-bound after the module it came from, so the alias exists by the time
89
+ // anything uses it.
90
+ parts.push(aliasesIn(clause).join("\n"));
91
+ lastIndex = match.index + statement.length;
92
+ }
93
+
94
+ parts.push(source.slice(lastIndex));
95
+
96
+ const output = parts.join("\n");
97
+
98
+ if (Buffer.byteLength(output, "utf8") > maxBytes) {
99
+ throw new BundleError(
100
+ `Bundle is ${Buffer.byteLength(output, "utf8")} bytes; the limit is ${maxBytes}.`
101
+ );
102
+ }
103
+
104
+ return output;
105
+ }
106
+
107
+ /**
108
+ * Checks the things the server would reject anyway, but here, before an author
109
+ * spends an upload finding out.
110
+ */
111
+ const KINDS = ["game", "applet", "bot"];
112
+
113
+ export function inspect(code, manifest = {}) {
114
+ const problems = [];
115
+ const warnings = [];
116
+
117
+ if (manifest.kind !== undefined && !KINDS.includes(manifest.kind)) {
118
+ problems.push(`"kind" must be one of ${KINDS.join(", ")}, not "${manifest.kind}".`);
119
+ }
120
+ if (manifest.surface === "service" && manifest.kind && manifest.kind !== "bot") {
121
+ warnings.push(`A service app is a bot; the platform will file it as one regardless of kind "${manifest.kind}".`);
122
+ }
123
+ const exported = (name) =>
124
+ new RegExp(`export\\s+(async\\s+)?function\\s+${name}\\b`).test(code);
125
+
126
+ if (manifest.surface === "service") {
127
+ if (!SERVICE_ENTRY_POINTS.some(exported)) {
128
+ problems.push(
129
+ `A service app needs at least one of: ${SERVICE_ENTRY_POINTS.map((name) => `export function ${name}`).join(", ")}.`
130
+ );
131
+ }
132
+ for (const trigger of manifest.triggers ?? []) {
133
+ if (!exported("onTrigger")) {
134
+ problems.push(`Subscribes to "${trigger}" but exports no onTrigger.`);
135
+ break;
136
+ }
137
+ }
138
+ } else {
139
+ for (const name of REQUIRED_EXPORTS) {
140
+ if (!exported(name)) {
141
+ problems.push(`Missing \`export function ${name}\`.`);
142
+ }
143
+ }
144
+ }
145
+
146
+ if (/\bfetch\s*\(/.test(code)) {
147
+ warnings.push(
148
+ "Calls fetch(). The sandbox has no network. To reach an approved host, return an http.fetch effect and read the answer in onFetch."
149
+ );
150
+ }
151
+ // A shop without a delivery handler takes the money and grants nothing until
152
+ // the app happens to reconcile — a bug an author only meets after a real
153
+ // member has paid, which is the most expensive possible place to find it.
154
+ if (/["']points\.spend["']/.test(code) && !exported("onSpend")) {
155
+ warnings.push(
156
+ "Declares points.spend but exports no onSpend. A member's payment lands there; without it, deliver by reconciling api.points.spends() on render."
157
+ );
158
+ }
159
+ if (/\b(eval|new\s+Function)\s*\(/.test(code)) {
160
+ warnings.push("Uses eval or new Function. Staff can suspend an app that loads code at runtime; avoid it.");
161
+ }
162
+ if (/\bimport\s*\(\s*["']node:/.test(code)) {
163
+ warnings.push("Imports a node: builtin. These are blocked in the sandbox.");
164
+ }
165
+ if (/\blocalStorage\b|\bdocument\b|\bwindow\b/.test(code)) {
166
+ warnings.push("References browser globals. Apps run on the server, not in the page.");
167
+ }
168
+
169
+ return { problems, warnings };
170
+ }
@@ -0,0 +1,331 @@
1
+ import { mkdir, writeFile, watch } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { readFile } from "node:fs/promises";
5
+ import { bundle, inspect, BundleError } from "./bundle.js";
6
+ import { createClient } from "./api.js";
7
+ import { readManifest, readCredentials, CONFIG_FILE } from "./config.js";
8
+ import * as store from "./credentials.js";
9
+
10
+ const TEMPLATES = fileURLToPath(new URL("../templates/", import.meta.url));
11
+
12
+ const TEMPLATE_NAMES = { counter: "counter.js", race: "race.js", bot: "bot.js" };
13
+ const TEMPLATE_PLACEMENT = { counter: "many", race: "single", bot: "single" };
14
+ const TEMPLATE_SURFACE = { counter: "blocks", race: "blocks", bot: "service" };
15
+ // What the directory files the app under: a game is played, an applet is a
16
+ // small program in a post or node, a bot works in the background.
17
+ const TEMPLATE_KIND = { counter: "applet", race: "game", bot: "bot" };
18
+ const TEMPLATE_TRIGGERS = { counter: [], race: [], bot: ["topic_created"] };
19
+ const TEMPLATE_SCOPES = {
20
+ counter: ["kv"],
21
+ race: ["kv", "kv.shared", "points", "realtime", "schedule"],
22
+ bot: ["kv", "post.read", "post.write"],
23
+ };
24
+
25
+ export async function init(args, io) {
26
+ const slug = args[0];
27
+ if (!slug) {
28
+ throw new Error("Usage: nodeloc-apps init <slug> [--template counter|race]");
29
+ }
30
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) {
31
+ throw new Error("A slug may only contain lowercase letters, numbers and dashes.");
32
+ }
33
+
34
+ const template = templateFrom(args);
35
+ if (!TEMPLATE_NAMES[template]) {
36
+ throw new Error(`Unknown template "${template}". Available: ${Object.keys(TEMPLATE_NAMES).join(", ")}.`);
37
+ }
38
+
39
+ const dir = path.resolve(process.cwd(), slug);
40
+ await mkdir(path.join(dir, "src"), { recursive: true });
41
+
42
+ const manifest = {
43
+ slug,
44
+ name: slug.replace(/-/g, " ").replace(/^./, (c) => c.toUpperCase()),
45
+ entry: "src/main.js",
46
+ scopes: TEMPLATE_SCOPES[template],
47
+ // "blocks" draws through the site's components; "webview" ships your own
48
+ // HTML and needs an admin to grant it; "service" has no interface at all
49
+ // and is woken by site events instead.
50
+ surface: TEMPLATE_SURFACE[template],
51
+ // "game" | "applet" | "bot": which shelf of the directory and sidebar the
52
+ // app sits on. A service is always a bot; anything else is an applet
53
+ // unless you say game.
54
+ kind: TEMPLATE_KIND[template],
55
+ // "single" means the app lives in one post; "many" lets anyone add it to
56
+ // theirs. Apps with a shared leaderboard want "single".
57
+ placement: TEMPLATE_PLACEMENT[template],
58
+ // Site events that wake onTrigger. Only meaningful for a service app.
59
+ triggers: TEMPLATE_TRIGGERS[template],
60
+ // Exact hostnames the app may reach. The code is not reviewed, but staff
61
+ // approve each of these one at a time; until then requests to it fail. Needs the "http" scope, and requests are made by the site rather
62
+ // than from inside the sandbox.
63
+ domains: [],
64
+ };
65
+
66
+ await writeFile(
67
+ path.join(dir, CONFIG_FILE),
68
+ `${JSON.stringify(manifest, null, 2)}\n`,
69
+ "utf8"
70
+ );
71
+ await writeFile(
72
+ path.join(dir, "src/main.js"),
73
+ await readFile(path.join(TEMPLATES, TEMPLATE_NAMES[template]), "utf8"),
74
+ "utf8"
75
+ );
76
+
77
+ io.log(`Created ${slug}/`);
78
+ io.log("");
79
+ io.log("Next:");
80
+ io.log(` cd ${slug}`);
81
+ io.log(" nodeloc-apps dev # check it builds");
82
+ io.log(" nodeloc-apps playtest # run it on the site, only you can see it");
83
+ }
84
+
85
+ export async function dev(_args, io, cwd = process.cwd()) {
86
+ const manifest = await readManifest(cwd);
87
+ const code = await bundle(path.join(cwd, manifest.entry));
88
+ const { problems, warnings } = inspect(code, manifest);
89
+
90
+ for (const warning of warnings) {
91
+ io.warn(`warning: ${warning}`);
92
+ }
93
+ if (problems.length) {
94
+ throw new BundleError(problems.join("\n"));
95
+ }
96
+
97
+ io.log(`Built ${manifest.slug}: ${Buffer.byteLength(code, "utf8")} bytes, no problems found.`);
98
+ return code;
99
+ }
100
+
101
+ export async function upload(args, io, cwd = process.cwd()) {
102
+ const manifest = await readManifest(cwd);
103
+ const client = createClient(readCredentials(process.env, await store.load()));
104
+ const code = await dev([], io, cwd);
105
+ const note = noteFrom(args);
106
+
107
+ const app = await resolveApp(client, manifest, io);
108
+ const version = await client.submitVersion(app.id, {
109
+ version: {
110
+ bundle: code,
111
+ readme: await readmeFrom(cwd),
112
+ requested_scopes: manifest.scopes ?? [],
113
+ requested_domains: domainsFrom(manifest),
114
+ change_note: note,
115
+ manifest: declaredFrom(manifest),
116
+ },
117
+ });
118
+
119
+ // Versions are not reviewed: a submitted one is live at once, and every
120
+ // install of the app moves to it (posts too, unless pin_installs is set).
121
+ // Older sites still answered "pending" here, so say what the site said.
122
+ const status = version.version.review_status;
123
+ if (status === "pending") {
124
+ io.log(`Submitted v${version.version.version_number}; this site still reviews versions.`);
125
+ } else {
126
+ io.log(
127
+ manifest.pin_installs === true
128
+ ? `Published v${version.version.version_number}. Bots move to it; posts already embedding the app keep their version (pin_installs).`
129
+ : `Published v${version.version.version_number}. Every install of the app moves to it.`
130
+ );
131
+ }
132
+ if (manifest.scopes?.length) {
133
+ io.log(`Requested permissions: ${manifest.scopes.join(", ")}`);
134
+ }
135
+ reportDomains(version.domains, io);
136
+ return version;
137
+ }
138
+
139
+ const DOMAIN_STATES = {
140
+ approved: "approved",
141
+ pending: "waiting for staff approval",
142
+ rejected: "not approved",
143
+ revoked: "approval revoked",
144
+ };
145
+
146
+ /**
147
+ * Outbound hosts are still reviewed one by one, so say where each stands:
148
+ * until a host is approved, http.fetch to it fails with E_HTTP_DOMAIN_DENIED,
149
+ * in a playtest as much as in a live install. Returns the printed summary so
150
+ * a watch session can stay quiet while nothing changes.
151
+ */
152
+ function reportDomains(domains, io, previous = "") {
153
+ if (!Array.isArray(domains) || domains.length === 0) {
154
+ return "";
155
+ }
156
+ const lines = domains.map((d) => {
157
+ const state = DOMAIN_STATES[d.status] ?? d.status;
158
+ return ` ${d.domain}: ${state}${d.note ? ` (${d.note})` : ""}`;
159
+ });
160
+ const summary = lines.join("\n");
161
+ if (summary === previous) {
162
+ return summary;
163
+ }
164
+ io.log(`External hosts:\n${summary}`);
165
+ if (domains.some((d) => d.status !== "approved")) {
166
+ io.log("Requests to hosts that are not approved fail with E_HTTP_DOMAIN_DENIED.");
167
+ }
168
+ return summary;
169
+ }
170
+
171
+ export async function playtest(_args, io, cwd = process.cwd(), { watchFn = watch } = {}) {
172
+ const manifest = await readManifest(cwd);
173
+ const client = createClient(readCredentials(process.env, await store.load()));
174
+ const app = await resolveApp(client, manifest, io);
175
+
176
+ // A push is not a submission: a submission goes live and moves every
177
+ // install to it, a push only changes your own playtest.
178
+ let domainSummary = "";
179
+ const push = async () => {
180
+ const code = await bundle(path.join(cwd, manifest.entry));
181
+ const { problems } = inspect(code, manifest);
182
+ if (problems.length) {
183
+ io.warn(problems.join("\n"));
184
+ return null;
185
+ }
186
+
187
+ const pushed = await client.pushPlaytest(app.id, {
188
+ version: {
189
+ bundle: code,
190
+ readme: await readmeFrom(cwd),
191
+ requested_scopes: manifest.scopes ?? [],
192
+ requested_domains: domainsFrom(manifest),
193
+ change_note: "playtest",
194
+ manifest: declaredFrom(manifest),
195
+ },
196
+ });
197
+ domainSummary = reportDomains(pushed.domains, io, domainSummary);
198
+ return pushed.install;
199
+ };
200
+
201
+ const install = await push();
202
+ if (install) {
203
+ io.log(`Playtest ready: only you can see it. Install #${install.id}`);
204
+ io.log("Watching for changes. Press Ctrl+C to stop.");
205
+ }
206
+
207
+ const watcher = watchFn(path.join(cwd, path.dirname(manifest.entry)), { recursive: true });
208
+ for await (const event of watcher) {
209
+ if (!event.filename?.endsWith(".js")) {
210
+ continue;
211
+ }
212
+ try {
213
+ await push();
214
+ io.log(`Pushed ${event.filename} at ${new Date().toLocaleTimeString()}`);
215
+ } catch (error) {
216
+ io.warn(error.message);
217
+ }
218
+ }
219
+ }
220
+
221
+ async function resolveApp(client, manifest, io) {
222
+ const apps = await client.listApps();
223
+ const existing = apps?.find?.((candidate) => candidate.slug === manifest.slug);
224
+ if (existing) {
225
+ return existing;
226
+ }
227
+
228
+ io.log(`No app named "${manifest.slug}" yet — creating it.`);
229
+ const created = await client.createApp({
230
+ app: { slug: manifest.slug, ...namesFrom(manifest) },
231
+ });
232
+ return created.app;
233
+ }
234
+
235
+ /**
236
+ * `name` is one string, or one per locale. Given per locale, the English one
237
+ * (else the first) is the name shown where no translation fits.
238
+ */
239
+ function namesFrom(manifest) {
240
+ const declared = manifest.name;
241
+ if (declared && typeof declared === "object") {
242
+ return {
243
+ name: declared.en ?? Object.values(declared)[0] ?? manifest.slug,
244
+ localized_names: declared,
245
+ };
246
+ }
247
+
248
+ return { name: declared ?? manifest.slug };
249
+ }
250
+
251
+ function noteFrom(args) {
252
+ const index = args.indexOf("--note");
253
+ return index === -1 ? "" : (args[index + 1] ?? "");
254
+ }
255
+
256
+ /**
257
+ * The parts of app.json the platform reads. Sent explicitly rather than posting
258
+ * the whole file, so a manifest can carry an author's own notes without them
259
+ * ending up stored on the server.
260
+ */
261
+ function declaredFrom(manifest) {
262
+ return {
263
+ surface: manifest.surface ?? "blocks",
264
+ // Left out when the manifest says nothing, so the platform's own default
265
+ // (bot for a service, applet otherwise) applies rather than ours.
266
+ ...(manifest.kind ? { kind: manifest.kind } : {}),
267
+ placement: manifest.placement ?? "single",
268
+ triggers: manifest.triggers ?? [],
269
+ // What the install form will ask for. Without this the only honest thing
270
+ // the platform can offer somebody installing your app is a box to type
271
+ // JSON into, which asks them to already know what it wants.
272
+ settings: manifest.settings ?? [],
273
+ // Set when this version cannot read what the previous one stored: posts
274
+ // that already embed the app keep their version instead of moving to it.
275
+ ...(manifest.pin_installs === true ? { pin_installs: true } : {}),
276
+ };
277
+ }
278
+
279
+ /**
280
+ * The introduction shown on the app's own page. Optional: an app without one
281
+ * simply has no such section. It travels with the version rather than the
282
+ * app, so the code that runs and the description shown cannot drift apart.
283
+ */
284
+ async function readmeFrom(cwd) {
285
+ try {
286
+ return await readFile(path.join(cwd, "readme.md"), "utf8");
287
+ } catch {
288
+ return "";
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Hosts the app wants to reach. Written flat like `scopes`, but the nested form
294
+ * is accepted too, because that is the shape people arrive with from Devvit.
295
+ */
296
+ function domainsFrom(manifest) {
297
+ return manifest.domains ?? manifest.permissions?.http?.domains ?? [];
298
+ }
299
+
300
+ function templateFrom(args) {
301
+ const index = args.indexOf("--template");
302
+ return index === -1 ? "counter" : (args[index + 1] ?? "counter");
303
+ }
304
+
305
+ export async function logs(args, io, cwd = process.cwd()) {
306
+ const manifest = await readManifest(cwd);
307
+ const client = createClient(readCredentials(process.env, await store.load()));
308
+ const app = await resolveApp(client, manifest, io);
309
+
310
+ const { logs: runs } = await client.logs(app.id, limitFrom(args));
311
+
312
+ if (!runs.length) {
313
+ io.log("No runs recorded yet.");
314
+ return runs;
315
+ }
316
+
317
+ for (const run of runs.slice().reverse()) {
318
+ const when = new Date(run.created_at).toLocaleTimeString();
319
+ const detail = run.error_code ? ` ${run.error_code}` : "";
320
+ io.log(
321
+ `${when} ${run.handler.padEnd(9)} ${run.outcome.padEnd(11)} ${String(run.duration_ms).padStart(5)}ms${detail}`
322
+ );
323
+ }
324
+
325
+ return runs;
326
+ }
327
+
328
+ function limitFrom(args) {
329
+ const index = args.indexOf("--limit");
330
+ return index === -1 ? 50 : Number(args[index + 1]) || 50;
331
+ }
package/src/config.js ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Where the CLI gets its credentials and which site it talks to.
3
+ *
4
+ * Credentials come from the environment, never from the project directory: an
5
+ * app's source is meant to be shared and reviewed, and a token committed by
6
+ * accident is the kind of mistake that is hard to take back.
7
+ */
8
+
9
+ import { readFile } from "node:fs/promises";
10
+ import path from "node:path";
11
+
12
+ export const CONFIG_FILE = "app.json";
13
+
14
+ export class ConfigError extends Error {}
15
+
16
+ export async function readManifest(cwd = process.cwd()) {
17
+ const file = path.join(cwd, CONFIG_FILE);
18
+
19
+ let raw;
20
+ try {
21
+ raw = await readFile(file, "utf8");
22
+ } catch {
23
+ throw new ConfigError(
24
+ `No ${CONFIG_FILE} here. Run \`nodeloc-apps init\` first, or change to your app directory.`
25
+ );
26
+ }
27
+
28
+ let manifest;
29
+ try {
30
+ manifest = JSON.parse(raw);
31
+ } catch (error) {
32
+ throw new ConfigError(`${CONFIG_FILE} is not valid JSON: ${error.message}`);
33
+ }
34
+
35
+ if (!manifest.slug) {
36
+ throw new ConfigError(`${CONFIG_FILE} needs a "slug".`);
37
+ }
38
+ if (!manifest.entry) {
39
+ throw new ConfigError(`${CONFIG_FILE} needs an "entry" pointing at your source file.`);
40
+ }
41
+
42
+ return manifest;
43
+ }
44
+
45
+ /**
46
+ * Environment first so CI and scripts keep working, then whatever `login`
47
+ * stored. Nothing is ever read from the project directory: an app's source is
48
+ * meant to be shared, and a token committed by accident is hard to take back.
49
+ */
50
+ export function readCredentials(env = process.env, stored = null) {
51
+ const site = env.NODELOC_APPS_SITE || stored?.site;
52
+ const key = env.NODELOC_APPS_API_KEY || stored?.key;
53
+ const username = env.NODELOC_APPS_API_USERNAME || stored?.username;
54
+
55
+ if (!site || !key || !username) {
56
+ throw new ConfigError("Not signed in. Run `nodeloc-apps login` first.");
57
+ }
58
+
59
+ return { site: site.replace(/\/$/, ""), key, username };
60
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Where the CLI keeps the credential `login` obtained.
3
+ *
4
+ * On disk under the user's config directory rather than in the project, so a
5
+ * token can never be committed by accident. Environment variables still win
6
+ * when set, which keeps CI and scripts working without a login step.
7
+ */
8
+
9
+ import { mkdir, readFile, writeFile, rm, chmod } from "node:fs/promises";
10
+ import { homedir } from "node:os";
11
+ import path from "node:path";
12
+
13
+ export const CONFIG_DIR = path.join(
14
+ process.env.XDG_CONFIG_HOME || path.join(homedir(), ".config"),
15
+ "nodeloc-apps"
16
+ );
17
+ export const CREDENTIALS_FILE = path.join(CONFIG_DIR, "credentials.json");
18
+
19
+ export async function save({ site, key, username }) {
20
+ await mkdir(CONFIG_DIR, { recursive: true });
21
+ await writeFile(
22
+ CREDENTIALS_FILE,
23
+ `${JSON.stringify({ site, key, username }, null, 2)}\n`,
24
+ "utf8"
25
+ );
26
+ // Readable by its owner only; this file is a live credential.
27
+ await chmod(CREDENTIALS_FILE, 0o600);
28
+ }
29
+
30
+ export async function load() {
31
+ try {
32
+ return JSON.parse(await readFile(CREDENTIALS_FILE, "utf8"));
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ export async function forget() {
39
+ await rm(CREDENTIALS_FILE, { force: true });
40
+ }
package/src/login.js ADDED
@@ -0,0 +1,92 @@
1
+ /**
2
+ * `nodeloc-apps login` — the browser does the signing in.
3
+ *
4
+ * A terminal cannot authenticate to a forum, so it asks the site for a short
5
+ * code, the author approves that code in a browser where they are already
6
+ * signed in, and the CLI collects the credential afterwards. Nothing secret is
7
+ * ever typed by hand, and an approval nobody collects simply expires.
8
+ */
9
+
10
+ import { ConfigError } from "./config.js";
11
+ import * as store from "./credentials.js";
12
+
13
+ const POLL_INTERVAL_MS = 2000;
14
+
15
+ export async function login(args, io, { fetchImpl = fetch, sleep = wait } = {}) {
16
+ const site = (siteFrom(args) ?? process.env.NODELOC_APPS_SITE ?? "").replace(/\/$/, "");
17
+ if (!site) {
18
+ throw new ConfigError("Usage: nodeloc-apps login --site https://www.nodeloc.com");
19
+ }
20
+
21
+ const started = await request(fetchImpl, `${site}/apps/cli/start.json`, { method: "POST" });
22
+
23
+ io.log("");
24
+ io.log(` Open: ${started.verify_url}`);
25
+ io.log(` Code: ${started.code}`);
26
+ io.log("");
27
+ io.log("Waiting for approval… (Ctrl+C to cancel)");
28
+
29
+ const deadline = Date.now() + started.expires_in * 1000;
30
+
31
+ while (Date.now() < deadline) {
32
+ await sleep(POLL_INTERVAL_MS);
33
+
34
+ const result = await request(
35
+ fetchImpl,
36
+ `${site}/apps/cli/poll.json?token=${encodeURIComponent(started.poll_token)}`
37
+ );
38
+
39
+ if (result.status === "approved") {
40
+ await store.save({ site, key: result.key, username: result.username });
41
+ io.log(`Signed in as ${result.username}.`);
42
+ return result;
43
+ }
44
+ if (result.status === "expired") {
45
+ break;
46
+ }
47
+ }
48
+
49
+ throw new ConfigError("That code expired before it was approved. Try again.");
50
+ }
51
+
52
+ export async function logout(_args, io) {
53
+ await store.forget();
54
+ io.log("Signed out. The key on the site was left alone — revoke it there if you meant to.");
55
+ }
56
+
57
+ export async function whoami(_args, io) {
58
+ const stored = await store.load();
59
+ if (!stored) {
60
+ io.log("Not signed in.");
61
+ return null;
62
+ }
63
+
64
+ io.log(`${stored.username} at ${stored.site}`);
65
+ return stored;
66
+ }
67
+
68
+ async function request(fetchImpl, url, options = {}) {
69
+ let response;
70
+ try {
71
+ response = await fetchImpl(url, {
72
+ ...options,
73
+ headers: { Accept: "application/json", ...(options.headers ?? {}) },
74
+ });
75
+ } catch (error) {
76
+ throw new ConfigError(`Could not reach the site: ${error.message}`);
77
+ }
78
+
79
+ if (!response.ok) {
80
+ throw new ConfigError(`The site refused the login handshake (${response.status}).`);
81
+ }
82
+ return response.json();
83
+ }
84
+
85
+ function siteFrom(args) {
86
+ const index = args.indexOf("--site");
87
+ return index === -1 ? null : args[index + 1];
88
+ }
89
+
90
+ function wait(ms) {
91
+ return new Promise((resolve) => setTimeout(resolve, ms));
92
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * A bot that welcomes the first topic each member opens.
3
+ *
4
+ * There is no `render` here and nothing to press: a service app has no
5
+ * interface. It is woken by the site events named in app.json, runs under an
6
+ * account of its own, and everything it wants to change comes back as effects
7
+ * for the site to check and commit.
8
+ *
9
+ * Reads are prefetched. `api.post.get` and `api.topic.get` answer for the post
10
+ * and topic this run is about; any other id comes back null, which is what
11
+ * keeps a bot installed in one place from reading its way across the site.
12
+ */
13
+
14
+ const GREETED = "greeted:";
15
+
16
+ export async function onTrigger(ctx, api) {
17
+ if (ctx.event !== "topic_created") {
18
+ return { effects: [] };
19
+ }
20
+
21
+ const topic = await api.topic.get(ctx.data.topic_id);
22
+ const post = await api.post.get(ctx.data.post_id);
23
+ if (!topic || !post) {
24
+ return { effects: [] };
25
+ }
26
+
27
+ // A background run reads and writes the app's own shared area, so this is
28
+ // the bot's memory rather than any one member's.
29
+ const key = `${GREETED}${post.user_id}`;
30
+ if (await api.kv.get(key)) {
31
+ return { effects: [] };
32
+ }
33
+
34
+ return {
35
+ effects: [
36
+ { type: "kv.set", key, value: topic.id },
37
+ {
38
+ type: "post.reply",
39
+ topic_id: topic.id,
40
+ raw: `Welcome, @${post.username}. This is your first topic here — someone will be along shortly.`,
41
+ },
42
+ ],
43
+ };
44
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * A starting point. Both handlers run on the server, in a sandbox with no
3
+ * network and no disk — everything they can reach arrives through `api`.
4
+ */
5
+
6
+ function screen(count) {
7
+ return {
8
+ type: "vstack",
9
+ gap: "small",
10
+ align: "center",
11
+ padding: "medium",
12
+ children: [
13
+ { type: "text", value: `Clicked ${count} times`, size: "large", weight: "bold" },
14
+ { type: "button", label: "Click me", action: "bump", variant: "primary" },
15
+ ],
16
+ };
17
+ }
18
+
19
+ export async function render(ctx, api) {
20
+ const count = (await api.kv.get("count")) ?? 0;
21
+ return { blocks: screen(count), state: { count }, effects: [] };
22
+ }
23
+
24
+ export async function onAction(ctx, api) {
25
+ if (ctx.action_id !== "bump") {
26
+ return { blocks: screen(ctx.state?.count ?? 0), state: ctx.state, effects: [] };
27
+ }
28
+
29
+ const count = (ctx.state?.count ?? 0) + 1;
30
+
31
+ return {
32
+ blocks: screen(count),
33
+ state: { count },
34
+ // Writes are declared, not performed: the site checks each one against the
35
+ // permissions this app was granted before anything is saved.
36
+ effects: [{ type: "kv.set", key: "count", value: count }],
37
+ };
38
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * A multiplayer round: whoever presses first claims it.
3
+ *
4
+ * The thing worth copying here is where the decision is made. The client sends
5
+ * "I pressed", never "I won" and never a score — the handler reads the shared
6
+ * round from storage, decides, and declares what should change. A player who
7
+ * edits anything in their browser is still only sending "I pressed".
8
+ */
9
+
10
+ function screen({ round, holder, you, scores }) {
11
+ const leaderboard = Object.entries(scores ?? {})
12
+ .sort((a, b) => b[1] - a[1])
13
+ .slice(0, 5)
14
+ .map(([name, score]) => ({
15
+ type: "text",
16
+ value: `${name}: ${score}`,
17
+ size: "small",
18
+ }));
19
+
20
+ return {
21
+ type: "vstack",
22
+ gap: "small",
23
+ padding: "medium",
24
+ children: [
25
+ { type: "text", value: `Round ${round}`, weight: "bold", size: "large" },
26
+ {
27
+ type: "text",
28
+ value: holder ? `${holder} took this round` : "Nobody has taken this round yet",
29
+ },
30
+ {
31
+ type: "button",
32
+ label: holder ? "Wait for the next round" : "Take it",
33
+ action: "press",
34
+ variant: "primary",
35
+ disabled: Boolean(holder),
36
+ },
37
+ { type: "divider" },
38
+ { type: "text", value: `Your wins: ${you}`, size: "small" },
39
+ ...leaderboard,
40
+ ],
41
+ };
42
+ }
43
+
44
+ async function load(api) {
45
+ const shared = await api.kv.listPublic();
46
+ const state = shared.find((entry) => entry.key === "round")?.value ?? {
47
+ round: 1,
48
+ holder: null,
49
+ scores: {},
50
+ };
51
+ const you = (await api.kv.get("wins")) ?? 0;
52
+ return { state, you };
53
+ }
54
+
55
+ export async function render(ctx, api) {
56
+ const { state, you } = await load(api);
57
+
58
+ return {
59
+ blocks: screen({ ...state, you }),
60
+ state: { round: state.round },
61
+ effects: [],
62
+ };
63
+ }
64
+
65
+ export async function onAction(ctx, api) {
66
+ const { state, you } = await load(api);
67
+
68
+ if (ctx.action_id !== "press" || state.holder) {
69
+ return { blocks: screen({ ...state, you }), state: { round: state.round }, effects: [] };
70
+ }
71
+
72
+ const name = ctx.user?.username ?? "someone";
73
+ const scores = { ...state.scores, [name]: (state.scores?.[name] ?? 0) + 1 };
74
+ const next = { round: state.round, holder: name, scores };
75
+
76
+ return {
77
+ blocks: screen({ ...next, you: you + 1 }),
78
+ state: { round: state.round },
79
+ effects: [
80
+ { type: "kv.set", key: "wins", value: you + 1 },
81
+ { type: "points.award", amount: 1, reason: "took a round" },
82
+ // Everyone else's screen re-renders through the server; this only says
83
+ // that something changed, never what to display.
84
+ { type: "rt.publish", room: "main", data: { round: state.round } },
85
+ // The next round opens on its own, so a stalled game recovers without
86
+ // anyone having to press anything.
87
+ { type: "schedule.add", job_key: "next-round", in_seconds: 60 },
88
+ ],
89
+ };
90
+ }
91
+
92
+ export async function onSchedule(ctx, api) {
93
+ const shared = await api.kv.listPublic();
94
+ const state = shared.find((entry) => entry.key === "round")?.value ?? { round: 1, scores: {} };
95
+
96
+ return {
97
+ blocks: null,
98
+ state: null,
99
+ effects: [{ type: "rt.publish", room: "main", data: { round: state.round + 1 } }],
100
+ };
101
+ }