@minecraftbot-com/plugin 0.0.0-stage → 0.1.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.
Files changed (128) hide show
  1. package/AGENTS.md +177 -0
  2. package/README.md +45 -2
  3. package/dist/api.d.ts +351 -0
  4. package/dist/api.js +2 -0
  5. package/dist/cli/api.d.ts +26 -0
  6. package/dist/cli/api.js +61 -0
  7. package/dist/cli/build.d.ts +23 -0
  8. package/dist/cli/build.js +65 -0
  9. package/dist/cli/check.d.ts +10 -0
  10. package/dist/cli/check.js +98 -0
  11. package/dist/cli/config.d.ts +11 -0
  12. package/dist/cli/config.js +38 -0
  13. package/dist/cli/create.d.ts +2 -0
  14. package/dist/cli/create.js +39 -0
  15. package/dist/cli/dev-mcp.d.ts +36 -0
  16. package/dist/cli/dev-mcp.js +101 -0
  17. package/dist/cli/dev.d.ts +15 -0
  18. package/dist/cli/dev.js +261 -0
  19. package/dist/cli/fetch-guard.d.ts +7 -0
  20. package/dist/cli/fetch-guard.js +66 -0
  21. package/dist/cli/main.d.ts +2 -0
  22. package/dist/cli/main.js +112 -0
  23. package/dist/cli/mcp.d.ts +24 -0
  24. package/dist/cli/mcp.js +136 -0
  25. package/dist/cli/output.d.ts +11 -0
  26. package/dist/cli/output.js +25 -0
  27. package/dist/cli/test.d.ts +2 -0
  28. package/dist/cli/test.js +39 -0
  29. package/dist/errors.d.ts +22 -0
  30. package/dist/errors.js +35 -0
  31. package/dist/generated/block-states.d.ts +4087 -0
  32. package/dist/generated/block-states.js +2 -0
  33. package/dist/generated/blocks.d.ts +1289 -0
  34. package/dist/generated/blocks.js +1291 -0
  35. package/dist/generated/contracts.d.ts +304 -0
  36. package/dist/generated/contracts.js +327 -0
  37. package/dist/generated/effects.d.ts +43 -0
  38. package/dist/generated/effects.js +45 -0
  39. package/dist/generated/entities.d.ts +164 -0
  40. package/dist/generated/entities.js +166 -0
  41. package/dist/generated/items.d.ts +1661 -0
  42. package/dist/generated/items.js +1663 -0
  43. package/dist/generated/operations.d.ts +7 -0
  44. package/dist/generated/operations.js +65 -0
  45. package/dist/generated/permission-labels.d.ts +3 -0
  46. package/dist/generated/permission-labels.js +17 -0
  47. package/dist/generated/version.d.ts +2 -0
  48. package/dist/generated/version.js +3 -0
  49. package/dist/host/index.d.ts +7 -0
  50. package/dist/host/index.js +5 -0
  51. package/dist/index.d.ts +19 -0
  52. package/dist/index.js +13 -0
  53. package/dist/permissions.d.ts +11 -0
  54. package/dist/permissions.js +18 -0
  55. package/dist/plugin.d.ts +86 -0
  56. package/dist/plugin.js +26 -0
  57. package/dist/protocol.d.ts +167 -0
  58. package/dist/protocol.js +4 -0
  59. package/dist/runtime/connection.d.ts +52 -0
  60. package/dist/runtime/connection.js +132 -0
  61. package/dist/runtime/handles.d.ts +95 -0
  62. package/dist/runtime/handles.js +289 -0
  63. package/dist/runtime/memory-transport.d.ts +6 -0
  64. package/dist/runtime/memory-transport.js +39 -0
  65. package/dist/runtime/runtime.d.ts +57 -0
  66. package/dist/runtime/runtime.js +265 -0
  67. package/dist/runtime/scope.d.ts +25 -0
  68. package/dist/runtime/scope.js +94 -0
  69. package/dist/runtime/storage-runtime.d.ts +10 -0
  70. package/dist/runtime/storage-runtime.js +131 -0
  71. package/dist/settings.d.ts +111 -0
  72. package/dist/settings.js +78 -0
  73. package/dist/storage.d.ts +78 -0
  74. package/dist/storage.js +24 -0
  75. package/dist/testing/fake-container.d.ts +175 -0
  76. package/dist/testing/fake-container.js +483 -0
  77. package/dist/testing/index.d.ts +37 -0
  78. package/dist/testing/index.js +54 -0
  79. package/dist/types.d.ts +65 -0
  80. package/dist/types.js +54 -0
  81. package/llms.txt +11 -0
  82. package/package.json +55 -4
  83. package/src/api.ts +334 -0
  84. package/src/cli/api.ts +79 -0
  85. package/src/cli/build.ts +76 -0
  86. package/src/cli/check.ts +103 -0
  87. package/src/cli/config.ts +48 -0
  88. package/src/cli/create.ts +38 -0
  89. package/src/cli/dev-mcp.ts +131 -0
  90. package/src/cli/dev.ts +272 -0
  91. package/src/cli/fetch-guard.ts +61 -0
  92. package/src/cli/main.ts +113 -0
  93. package/src/cli/mcp.ts +168 -0
  94. package/src/cli/output.ts +30 -0
  95. package/src/cli/test.ts +38 -0
  96. package/src/errors.ts +34 -0
  97. package/src/generated/block-states.ts +892 -0
  98. package/src/generated/blocks.ts +1291 -0
  99. package/src/generated/contracts.ts +329 -0
  100. package/src/generated/effects.ts +45 -0
  101. package/src/generated/entities.ts +166 -0
  102. package/src/generated/items.ts +1663 -0
  103. package/src/generated/operations.ts +69 -0
  104. package/src/generated/permission-labels.ts +19 -0
  105. package/src/generated/version.ts +3 -0
  106. package/src/host/index.ts +9 -0
  107. package/src/index.ts +34 -0
  108. package/src/permissions.ts +23 -0
  109. package/src/plugin.ts +105 -0
  110. package/src/protocol.ts +107 -0
  111. package/src/runtime/connection.ts +167 -0
  112. package/src/runtime/handles.ts +337 -0
  113. package/src/runtime/memory-transport.ts +41 -0
  114. package/src/runtime/runtime.ts +281 -0
  115. package/src/runtime/scope.ts +101 -0
  116. package/src/runtime/storage-runtime.ts +138 -0
  117. package/src/settings.ts +118 -0
  118. package/src/storage.ts +82 -0
  119. package/src/testing/fake-container.ts +571 -0
  120. package/src/testing/index.ts +70 -0
  121. package/src/types.ts +88 -0
  122. package/templates/basic/AGENTS.md +31 -0
  123. package/templates/basic/README.md +13 -0
  124. package/templates/basic/gitignore +3 -0
  125. package/templates/basic/package.json +18 -0
  126. package/templates/basic/src/index.ts +20 -0
  127. package/templates/basic/test/plugin.test.ts +14 -0
  128. package/templates/basic/tsconfig.json +14 -0
@@ -0,0 +1,265 @@
1
+ import { isStopped, PluginError } from "../errors.js";
2
+ import { toPosition } from "../types.js";
3
+ import { Connection } from "./connection.js";
4
+ import { BotHandle, ProfileBotHandle, ProfileHandle } from "./handles.js";
5
+ import { Scope } from "./scope.js";
6
+ import { createStorage } from "./storage-runtime.js";
7
+ export const SDK_VERSION = "0.1.0";
8
+ /** Builds the manifest the container checks, from the plugin's definition. */
9
+ export function buildManifest(plugin, version) {
10
+ const d = plugin.definition;
11
+ const settings = {};
12
+ for (const [key, setting] of Object.entries(d.settings ?? {}))
13
+ settings[key] = setting.schema;
14
+ const storage = {};
15
+ for (const [key, entry] of Object.entries(d.storage ?? {}))
16
+ storage[key] = entry.schema;
17
+ return {
18
+ name: d.name,
19
+ version,
20
+ permissions: [...new Set(d.permissions)],
21
+ exclusive: [...new Set((d.exclusive ?? []))],
22
+ settings,
23
+ storage,
24
+ profile: typeof d.runProfile === "function",
25
+ };
26
+ }
27
+ function applyDefaults(manifest, values) {
28
+ const out = {};
29
+ for (const [key, schema] of Object.entries(manifest.settings)) {
30
+ const v = values[key];
31
+ out[key] = v === undefined || v === null ? schema.default : v;
32
+ if (schema.type === "position" && out[key])
33
+ out[key] = toPosition(out[key]);
34
+ }
35
+ return Object.freeze(out);
36
+ }
37
+ function describe(error) {
38
+ if (error instanceof Error)
39
+ return error.stack && !(error instanceof PluginError) ? error.stack : error.message;
40
+ return String(error);
41
+ }
42
+ /**
43
+ * Runs one plugin instance over a connection: starts `runProfile` and `run(bot)` when the container says so,
44
+ * stops them when it says so, and routes events to listeners.
45
+ */
46
+ export class PluginRuntime {
47
+ plugin;
48
+ manifest;
49
+ connection;
50
+ welcome;
51
+ options;
52
+ root = new Scope();
53
+ botScopes = new Map();
54
+ profileScope = null;
55
+ bots = new Map();
56
+ listeners = new Map();
57
+ profileBots = new Map();
58
+ stats = new Map();
59
+ constructor(plugin, manifest, connection, welcome, options = {}) {
60
+ this.plugin = plugin;
61
+ this.manifest = manifest;
62
+ this.connection = connection;
63
+ this.welcome = welcome;
64
+ this.options = options;
65
+ for (const bot of welcome.bots)
66
+ this.bots.set(bot.id, bot);
67
+ connection.attach({
68
+ start: (bot, settings, version) => this.start(bot, settings, version),
69
+ stop: (bot, reason) => this.stop(bot, reason),
70
+ event: (bot, event, data) => this.dispatch(bot, event, data),
71
+ bots: frame => {
72
+ this.bots.clear();
73
+ for (const bot of frame.bots)
74
+ this.bots.set(bot.id, bot);
75
+ },
76
+ dropped: count => this.emitLog("warn", `${count} events were dropped because the plugin didn't keep up`, null),
77
+ closed: (code, reason) => {
78
+ this.root.stop("Disconnected");
79
+ this.options.onClosed?.(code, reason);
80
+ },
81
+ });
82
+ }
83
+ /** Connects, sends hello and starts running once welcomed. Rejects if the container refuses. */
84
+ static async connect(plugin, transport, token, version, options = {}, dev) {
85
+ const manifest = buildManifest(plugin, version);
86
+ const connection = new Connection(transport);
87
+ const welcome = await connection.open(token, manifest, SDK_VERSION, dev);
88
+ return new PluginRuntime(plugin, manifest, connection, welcome, options);
89
+ }
90
+ /** The profile's bots as the container last reported them. */
91
+ get currentBots() {
92
+ return [...this.bots.values()];
93
+ }
94
+ /** The bots `run(bot)` is currently running on. */
95
+ get runningBots() {
96
+ return [...this.botScopes.keys()];
97
+ }
98
+ /** Stops everything and closes the connection. */
99
+ close() {
100
+ this.root.stop("Disconnected");
101
+ this.connection.close();
102
+ }
103
+ // ---- HandleHost ----
104
+ call(scope, bot, op, args = {}) {
105
+ return this.connection.call(scope, bot, op, args);
106
+ }
107
+ subscribe(scope, bot, event, listener) {
108
+ scope.check();
109
+ const key = `${bot ?? ""}|${event}`;
110
+ let set = this.listeners.get(key);
111
+ if (!set) {
112
+ set = new Set();
113
+ this.listeners.set(key, set);
114
+ this.connection.send({ type: "subscribe", bot, event });
115
+ }
116
+ set.add(listener);
117
+ return scope.onStop(() => {
118
+ const current = this.listeners.get(key);
119
+ if (!current)
120
+ return;
121
+ current.delete(listener);
122
+ if (current.size === 0) {
123
+ this.listeners.delete(key);
124
+ if (!this.root.stopped)
125
+ this.connection.send({ type: "unsubscribe", bot, event });
126
+ }
127
+ });
128
+ }
129
+ botInfo(id) {
130
+ return this.bots.get(id);
131
+ }
132
+ profileBot(id) {
133
+ let handle = this.profileBots.get(id);
134
+ if (!handle) {
135
+ handle = new ProfileBotHandle(this.profileScope ?? this.root, this, id);
136
+ this.profileBots.set(id, handle);
137
+ }
138
+ return handle;
139
+ }
140
+ logError(bot, error) {
141
+ this.emitLog("error", describe(error), bot);
142
+ }
143
+ // ---- lifecycle ----
144
+ start(bot, settingsFrame, version) {
145
+ const settings = applyDefaults(this.manifest, settingsFrame);
146
+ const d = this.plugin.definition;
147
+ if (bot === null) {
148
+ if (!d.runProfile || this.profileScope)
149
+ return;
150
+ const scope = this.root.child();
151
+ this.profileScope = scope;
152
+ this.profileBots.clear();
153
+ const profile = new ProfileHandle(scope, this, this.welcome.profile.id, this.welcome.profile.name, () => [...this.bots.values()]);
154
+ const context = this.context(scope, null, settings);
155
+ this.supervise(null, () => d.runProfile(profile, context), scope);
156
+ return;
157
+ }
158
+ if (!d.run)
159
+ return;
160
+ this.botScopes.get(bot)?.stop("Replaced");
161
+ const scope = this.root.child();
162
+ this.botScopes.set(bot, scope);
163
+ const handle = new BotHandle(scope, this, bot, version);
164
+ const context = this.context(scope, bot, settings);
165
+ this.supervise(bot, () => d.run(handle, context), scope);
166
+ }
167
+ stop(bot, reason) {
168
+ if (bot === null) {
169
+ this.profileScope?.stop(reason);
170
+ this.profileScope = null;
171
+ this.profileBots.clear();
172
+ return;
173
+ }
174
+ this.botScopes.get(bot)?.stop(reason);
175
+ this.botScopes.delete(bot);
176
+ }
177
+ /** Runs `run`/`runProfile`. Returning keeps listeners alive until stopped; throwing ends the run and is reported. */
178
+ supervise(bot, body, scope) {
179
+ Promise.resolve()
180
+ .then(body)
181
+ .catch(error => {
182
+ if (isStopped(error) || scope.stopped)
183
+ return;
184
+ this.emitLog("error", describe(error), bot);
185
+ this.connection.send({ type: "done", bot, error: error instanceof Error ? error.message : String(error) });
186
+ scope.stop("Failed");
187
+ if (bot === null)
188
+ this.profileScope = null;
189
+ else if (this.botScopes.get(bot) === scope)
190
+ this.botScopes.delete(bot);
191
+ });
192
+ }
193
+ context(scope, bot, settings) {
194
+ const log = {
195
+ debug: m => this.emitLog("debug", String(m), bot),
196
+ info: m => this.emitLog("info", String(m), bot),
197
+ warn: m => this.emitLog("warn", String(m), bot),
198
+ error: m => this.emitLog("error", m instanceof Error ? describe(m) : String(m), bot),
199
+ };
200
+ const statKey = (name) => `${bot ?? ""}|${name}`;
201
+ const stats = {
202
+ set: (name, value) => {
203
+ this.stats.set(statKey(name), value);
204
+ this.connection.send({ type: "stat", bot, key: name, value });
205
+ },
206
+ add: (name, amount = 1) => {
207
+ const value = (this.stats.get(statKey(name)) ?? 0) + amount;
208
+ this.stats.set(statKey(name), value);
209
+ this.connection.send({ type: "stat", bot, key: name, value });
210
+ },
211
+ };
212
+ const warnings = {
213
+ set: (key, message) => this.connection.send({ type: "warning", bot, key, message }),
214
+ clear: key => this.connection.send({ type: "warning", bot, key, message: null }),
215
+ };
216
+ const botUuid = bot === null ? null : this.bots.get(bot)?.uuid ?? null;
217
+ const storage = createStorage(this.manifest.storage, (s, op, args) => this.connection.call(s, bot, op, args), scope, bot === null ? null : botUuid ?? bot);
218
+ return { settings, storage, log, stats, warnings };
219
+ }
220
+ emitLog(level, message, bot) {
221
+ const trimmed = message.length > 4000 ? `${message.slice(0, 4000)}…` : message;
222
+ this.connection.send({ type: "log", bot, level, message: trimmed });
223
+ this.options.onLog?.(level, trimmed, bot === null ? null : this.bots.get(bot) ?? null);
224
+ }
225
+ // ---- events ----
226
+ dispatch(bot, event, data) {
227
+ if (event === "__error") {
228
+ const e = data;
229
+ this.emitLog("error", `${e.code}: ${e.message}`, null);
230
+ return;
231
+ }
232
+ const set = this.listeners.get(`${bot ?? ""}|${event}`);
233
+ if (!set)
234
+ return;
235
+ const payload = this.decorate(data);
236
+ for (const listener of [...set]) {
237
+ try {
238
+ const r = listener(payload);
239
+ if (r && typeof r.then === "function") {
240
+ r.catch(error => {
241
+ if (!isStopped(error))
242
+ this.emitLog("error", describe(error), bot);
243
+ });
244
+ }
245
+ }
246
+ catch (error) {
247
+ if (!isStopped(error))
248
+ this.emitLog("error", describe(error), bot);
249
+ }
250
+ }
251
+ }
252
+ /** Turns bot ids in event data into ProfileBot handles, and positions into Positions. */
253
+ decorate(data) {
254
+ if (!data || typeof data !== "object")
255
+ return data;
256
+ const out = { ...data };
257
+ if (typeof out.botId === "string") {
258
+ out.bot = this.profileBot(out.botId);
259
+ delete out.botId;
260
+ }
261
+ if (out.position && typeof out.position === "object")
262
+ out.position = toPosition(out.position);
263
+ return Object.freeze(out);
264
+ }
265
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * A lifetime: one run(bot), one runProfile, or the whole plugin. Everything started inside it (calls,
3
+ * listeners, timers, child scopes) ends when it stops, so plugin code never needs cancellation plumbing.
4
+ */
5
+ export declare class Scope {
6
+ private readonly parent;
7
+ private readonly cleanups;
8
+ private readonly children;
9
+ private stoppedReason;
10
+ constructor(parent?: Scope | null);
11
+ get stopped(): boolean;
12
+ get reason(): string | null;
13
+ /** Throws StoppedError if this scope has stopped. */
14
+ check(): void;
15
+ child(): Scope;
16
+ /** Runs `cleanup` when the scope stops. Returns a function that runs it early and forgets it. */
17
+ onStop(cleanup: () => void): () => void;
18
+ /** Forgets a cleanup without running it. */
19
+ forget(cleanup: () => void): void;
20
+ stop(reason: string): void;
21
+ /** A promise that settles like `promise` but rejects with StoppedError as soon as the scope stops. */
22
+ guard<T>(promise: Promise<T>): Promise<T>;
23
+ /** Waits `ms`, or rejects with StoppedError when the scope stops first. */
24
+ sleep(ms: number): Promise<void>;
25
+ }
@@ -0,0 +1,94 @@
1
+ import { StoppedError } from "../errors.js";
2
+ /**
3
+ * A lifetime: one run(bot), one runProfile, or the whole plugin. Everything started inside it (calls,
4
+ * listeners, timers, child scopes) ends when it stops, so plugin code never needs cancellation plumbing.
5
+ */
6
+ export class Scope {
7
+ parent;
8
+ cleanups = new Set();
9
+ children = new Set();
10
+ stoppedReason = null;
11
+ constructor(parent = null) {
12
+ this.parent = parent;
13
+ parent?.children.add(this);
14
+ }
15
+ get stopped() {
16
+ return this.stoppedReason !== null;
17
+ }
18
+ get reason() {
19
+ return this.stoppedReason;
20
+ }
21
+ /** Throws StoppedError if this scope has stopped. */
22
+ check() {
23
+ if (this.stoppedReason !== null)
24
+ throw new StoppedError(this.stoppedReason);
25
+ }
26
+ child() {
27
+ this.check();
28
+ return new Scope(this);
29
+ }
30
+ /** Runs `cleanup` when the scope stops. Returns a function that runs it early and forgets it. */
31
+ onStop(cleanup) {
32
+ if (this.stoppedReason !== null) {
33
+ cleanup();
34
+ return () => { };
35
+ }
36
+ this.cleanups.add(cleanup);
37
+ return () => {
38
+ if (this.cleanups.delete(cleanup))
39
+ cleanup();
40
+ };
41
+ }
42
+ /** Forgets a cleanup without running it. */
43
+ forget(cleanup) {
44
+ this.cleanups.delete(cleanup);
45
+ }
46
+ stop(reason) {
47
+ if (this.stoppedReason !== null)
48
+ return;
49
+ this.stoppedReason = reason;
50
+ for (const child of [...this.children])
51
+ child.stop(reason);
52
+ this.children.clear();
53
+ for (const cleanup of [...this.cleanups]) {
54
+ try {
55
+ cleanup();
56
+ }
57
+ catch {
58
+ // A cleanup must not keep the others from running.
59
+ }
60
+ }
61
+ this.cleanups.clear();
62
+ this.parent?.children.delete(this);
63
+ }
64
+ /** A promise that settles like `promise` but rejects with StoppedError as soon as the scope stops. */
65
+ guard(promise) {
66
+ this.check();
67
+ return new Promise((resolve, reject) => {
68
+ const cancel = () => reject(new StoppedError(this.stoppedReason ?? "Stopped"));
69
+ this.cleanups.add(cancel);
70
+ promise.then(value => {
71
+ this.cleanups.delete(cancel);
72
+ resolve(value);
73
+ }, error => {
74
+ this.cleanups.delete(cancel);
75
+ reject(error);
76
+ });
77
+ });
78
+ }
79
+ /** Waits `ms`, or rejects with StoppedError when the scope stops first. */
80
+ sleep(ms) {
81
+ this.check();
82
+ return new Promise((resolve, reject) => {
83
+ const timer = setTimeout(() => {
84
+ this.cleanups.delete(cancel);
85
+ resolve();
86
+ }, ms);
87
+ const cancel = () => {
88
+ clearTimeout(timer);
89
+ reject(new StoppedError(this.stoppedReason ?? "Stopped"));
90
+ };
91
+ this.cleanups.add(cancel);
92
+ });
93
+ }
94
+ }
@@ -0,0 +1,10 @@
1
+ import type { StorageSchema } from "../protocol.js";
2
+ import type { CallOutcome } from "./connection.js";
3
+ import type { Scope } from "./scope.js";
4
+ type Call = (scope: Scope, op: string, args: Record<string, unknown>) => Promise<CallOutcome>;
5
+ /**
6
+ * Builds the `storage` object for a scope from the manifest's declarations. In run(bot) `bot` is that bot's
7
+ * uuid and bot-scoped entries bind to it; in runProfile `bot` is null and bot-scoped entries need `.for(bot)`.
8
+ */
9
+ export declare function createStorage(declared: Record<string, StorageSchema>, call: Call, scope: Scope, bot: string | null): Record<string, unknown>;
10
+ export {};
@@ -0,0 +1,131 @@
1
+ import { PluginError } from "../errors.js";
2
+ import { StorageScope } from "../generated/contracts.js";
3
+ const MAX_UPDATE_ATTEMPTS = 16;
4
+ function ok(outcome) {
5
+ if (!outcome.ok)
6
+ throw new PluginError(outcome.failure, outcome.message);
7
+ return outcome.value;
8
+ }
9
+ function clone(value) {
10
+ return value === undefined ? value : JSON.parse(JSON.stringify(value));
11
+ }
12
+ class Value {
13
+ call;
14
+ scope;
15
+ at;
16
+ fallback;
17
+ constructor(call, scope, at, fallback) {
18
+ this.call = call;
19
+ this.scope = scope;
20
+ this.at = at;
21
+ this.fallback = fallback;
22
+ }
23
+ async read() {
24
+ const r = ok(await this.call(this.scope, "storage.get", { ...this.at, key: null }));
25
+ return { value: r.value === null || r.value === undefined ? clone(this.fallback) : r.value, version: r.version };
26
+ }
27
+ async get() {
28
+ return (await this.read()).value;
29
+ }
30
+ async set(value) {
31
+ ok(await this.call(this.scope, "storage.set", { ...this.at, key: null, value, ifVersion: null }));
32
+ }
33
+ async delete() {
34
+ ok(await this.call(this.scope, "storage.delete", { ...this.at, key: null, ifVersion: null }));
35
+ }
36
+ async update(fn) {
37
+ for (let attempt = 0; attempt < MAX_UPDATE_ATTEMPTS; attempt++) {
38
+ const { value, version } = await this.read();
39
+ const next = fn(value);
40
+ const outcome = await this.call(this.scope, "storage.set", { ...this.at, key: null, value: next, ifVersion: version });
41
+ if (outcome.ok)
42
+ return next;
43
+ if (outcome.failure !== "Conflict")
44
+ throw new PluginError(outcome.failure, outcome.message);
45
+ }
46
+ throw new PluginError("Conflict", `storage.${this.at.name}.update: gave up after ${MAX_UPDATE_ATTEMPTS} conflicting writes`);
47
+ }
48
+ }
49
+ class Map_ {
50
+ call;
51
+ scope;
52
+ at;
53
+ constructor(call, scope, at) {
54
+ this.call = call;
55
+ this.scope = scope;
56
+ this.at = at;
57
+ }
58
+ checkKey(key) {
59
+ if (typeof key !== "string" || key.length === 0 || key.length > 128)
60
+ throw new TypeError(`storage.${this.at.name}: keys are strings of 1 to 128 characters`);
61
+ }
62
+ async read(key) {
63
+ this.checkKey(key);
64
+ const r = ok(await this.call(this.scope, "storage.get", { ...this.at, key }));
65
+ return { value: r.value === null ? undefined : r.value, version: r.version };
66
+ }
67
+ async get(key) {
68
+ return (await this.read(key)).value;
69
+ }
70
+ async set(key, value) {
71
+ this.checkKey(key);
72
+ ok(await this.call(this.scope, "storage.set", { ...this.at, key, value, ifVersion: null }));
73
+ }
74
+ async delete(key) {
75
+ this.checkKey(key);
76
+ ok(await this.call(this.scope, "storage.delete", { ...this.at, key, ifVersion: null }));
77
+ }
78
+ async update(key, fn) {
79
+ for (let attempt = 0; attempt < MAX_UPDATE_ATTEMPTS; attempt++) {
80
+ const { value, version } = await this.read(key);
81
+ const next = fn(value);
82
+ const outcome = await this.call(this.scope, "storage.set", { ...this.at, key, value: next, ifVersion: version });
83
+ if (outcome.ok)
84
+ return next;
85
+ if (outcome.failure !== "Conflict")
86
+ throw new PluginError(outcome.failure, outcome.message);
87
+ }
88
+ throw new PluginError("Conflict", `storage.${this.at.name}.update: gave up after ${MAX_UPDATE_ATTEMPTS} conflicting writes`);
89
+ }
90
+ async keys() {
91
+ return (await this.entries()).map(([k]) => k);
92
+ }
93
+ async entries() {
94
+ const all = [];
95
+ let after = null;
96
+ for (;;) {
97
+ const page = ok(await this.call(this.scope, "storage.entries", { ...this.at, after, limit: 100 }));
98
+ all.push(...page.entries);
99
+ if (!page.next)
100
+ return all;
101
+ after = page.next;
102
+ }
103
+ }
104
+ }
105
+ /**
106
+ * Builds the `storage` object for a scope from the manifest's declarations. In run(bot) `bot` is that bot's
107
+ * uuid and bot-scoped entries bind to it; in runProfile `bot` is null and bot-scoped entries need `.for(bot)`.
108
+ */
109
+ export function createStorage(declared, call, scope, bot) {
110
+ const storage = {};
111
+ for (const [name, schema] of Object.entries(declared)) {
112
+ const make = (botUuid) => {
113
+ const at = { name, scope: schema.scope, bot: schema.scope === StorageScope.Bot ? botUuid : null };
114
+ return schema.kind === "map" ? new Map_(call, scope, at) : new Value(call, scope, at, schema.default);
115
+ };
116
+ if (schema.scope === StorageScope.Bot && bot === null) {
117
+ const perBot = {
118
+ for: target => {
119
+ if (!target?.uuid)
120
+ throw new TypeError(`storage.${name}.for(bot): pass a bot from profile.bots()`);
121
+ return make(target.uuid);
122
+ },
123
+ };
124
+ storage[name] = perBot;
125
+ }
126
+ else {
127
+ storage[name] = make(bot);
128
+ }
129
+ }
130
+ return storage;
131
+ }
@@ -0,0 +1,111 @@
1
+ import type { SettingSchema } from "./protocol.js";
2
+ import type { Block } from "./generated/blocks.js";
3
+ import type { Item } from "./generated/items.js";
4
+ import type { Entity } from "./generated/entities.js";
5
+ import type { Vec3 } from "./types.js";
6
+ /**
7
+ * One setting the user fills in on the dashboard. Build it with `Setting.*`; the type parameter is the
8
+ * value your plugin receives in `settings`.
9
+ */
10
+ export interface SettingDefinition<T> {
11
+ readonly schema: SettingSchema;
12
+ /** Type only, never set: carries the value type to `settings`. */
13
+ readonly __value?: T;
14
+ }
15
+ interface Common<T> {
16
+ /** Shown next to the field. */
17
+ label: string;
18
+ /** Shown under the field. */
19
+ description?: string;
20
+ default?: T;
21
+ }
22
+ type Optional<T, O> = O extends {
23
+ optional: true;
24
+ } ? T | undefined : T;
25
+ /**
26
+ * Settings the user configures on the dashboard, per bot.
27
+ *
28
+ * @example
29
+ * settings: {
30
+ * crop: Setting.block({ label: "Crop", options: [Block.Wheat, Block.Carrots], default: Block.Wheat }),
31
+ * radius: Setting.radius({ label: "Search radius", default: 16, max: 48 }),
32
+ * greeting: Setting.text({ label: "Greeting", default: "Hello!" }),
33
+ * }
34
+ */
35
+ export declare const Setting: {
36
+ /** Free text. `max` limits the length (default 256). */
37
+ text<O extends Common<string> & {
38
+ optional?: boolean;
39
+ max?: number;
40
+ }>(o: O): SettingDefinition<Optional<string, O>>;
41
+ /** A number between `min` and `max`. */
42
+ number<O extends Common<number> & {
43
+ optional?: boolean;
44
+ min?: number;
45
+ max?: number;
46
+ }>(o: O): SettingDefinition<Optional<number, O>>;
47
+ /** A distance in blocks, 1 to `max` (at most 64). */
48
+ radius(o: Common<number> & {
49
+ max?: number;
50
+ }): SettingDefinition<number>;
51
+ /** On or off. */
52
+ boolean(o: Common<boolean>): SettingDefinition<boolean>;
53
+ /** One of a fixed list of values, e.g. an enum's members. */
54
+ select<const V extends string | number, O extends Common<V> & {
55
+ options: readonly V[];
56
+ optional?: boolean;
57
+ }>(o: O): SettingDefinition<Optional<V, O>>;
58
+ /** A block type. `options` limits the choice; without it any block can be picked. */
59
+ block<O extends Common<Block> & {
60
+ options?: readonly Block[];
61
+ optional?: boolean;
62
+ }>(o: O): SettingDefinition<Optional<Block, O>>;
63
+ /** An item type. */
64
+ item<O extends Common<Item> & {
65
+ options?: readonly Item[];
66
+ optional?: boolean;
67
+ }>(o: O): SettingDefinition<Optional<Item, O>>;
68
+ /** An entity type (mob, animal, player...). */
69
+ entity<O extends Common<Entity> & {
70
+ options?: readonly Entity[];
71
+ optional?: boolean;
72
+ }>(o: O): SettingDefinition<Optional<Entity, O>>;
73
+ /** A position in the world (x, y, z). */
74
+ position<O extends Common<Vec3> & {
75
+ optional?: boolean;
76
+ }>(o: O): SettingDefinition<Optional<Vec3, O>>;
77
+ /**
78
+ * An HTTPS address the user enters, such as a webhook. Your plugin may `fetch` exactly this origin
79
+ * without declaring a network permission. `hosts` limits which hosts are accepted.
80
+ *
81
+ * @example
82
+ * webhook: Setting.url({ label: "Discord webhook", hosts: ["discord.com"], secret: true, optional: true })
83
+ */
84
+ url<O extends Common<string> & {
85
+ hosts?: readonly string[];
86
+ secret?: boolean;
87
+ optional?: boolean;
88
+ }>(o: O): SettingDefinition<Optional<string, O>>;
89
+ /**
90
+ * A secret such as an API key: stored encrypted, never shown again on the dashboard, sent only to the
91
+ * running plugin and never to its author.
92
+ */
93
+ secret<O extends {
94
+ label: string;
95
+ description?: string;
96
+ optional?: boolean;
97
+ }>(o: O): SettingDefinition<Optional<string, O>>;
98
+ /** A list of values of one kind, e.g. `Setting.list({ label: "Owners", of: Setting.text({ label: "Name" }) })`. */
99
+ list<T>(o: {
100
+ label: string;
101
+ description?: string;
102
+ of: SettingDefinition<T>;
103
+ max?: number;
104
+ default?: T[];
105
+ }): SettingDefinition<T[]>;
106
+ };
107
+ /** The values your plugin receives for a settings declaration. */
108
+ export type SettingValues<S> = {
109
+ readonly [K in keyof S]: S[K] extends SettingDefinition<infer T> ? T : never;
110
+ };
111
+ export {};