@arcadible/function-sdk 0.0.0-stage → 0.4.0-next.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,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/README.md CHANGED
@@ -1,3 +1,89 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://arcadible.com">
3
+ <img src="https://adn-arcadible.imgix.net/images/i18n/core/www/appicon-512.png?w=256" alt="Arcadible" height="96">
4
+ </a>
5
+ </p>
2
6
 
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.
7
+ <h1 align="center">Arcadible Function SDK</h1>
8
+
9
+ <p align="center">
10
+ How your game's function works with Arcadible.
11
+ </p>
12
+
13
+ <br>
14
+
15
+ A game on [Arcadible](https://arcadible.com) can have a function: server code that Arcadible runs beside the game, named in `arcadible.toml`'s `[function]`. The Arcadible Function SDK is for that code: it says who sent a request, asks Arcadible about your players, and keeps your game's data, with nothing to set up. Arcadible checks each request's ticket before your code runs, and your function calls Arcadible with no key.
16
+
17
+ **A prerelease.** It may change before it's released.
18
+
19
+ ## Install
20
+
21
+ ```sh
22
+ npm install @arcadible/function-sdk@next
23
+ ```
24
+
25
+ `arc build` bundles it with your function. It runs in your function alone, on Arcadible or under `arc serve`: a server of your own uses [`@arcadible/server-sdk`](https://www.npmjs.com/package/@arcadible/server-sdk), and a game [`@arcadible/sdk`](https://www.npmjs.com/package/@arcadible/sdk).
26
+
27
+ ## A function
28
+
29
+ ```ts
30
+ import { players, values } from "@arcadible/function-sdk";
31
+
32
+ export default {
33
+ async fetch(request: Request): Promise<Response> {
34
+ const me = players.primary(request);
35
+ if (me === null) return Response.json({ code: "guest" }, { status: 403 });
36
+ const [best] = await values.read([{ scope: me, key: "best" }]);
37
+ return Response.json({ best: best?.value ?? 0 });
38
+ },
39
+ };
40
+ ```
41
+
42
+ ## Players
43
+
44
+ ```ts
45
+ const me = players.primary(request);
46
+ // { id }, or null for a guest
47
+
48
+ const [sam] = await players.read([me.id]);
49
+ // { id, name }, or null for a player who's gone, or a guest
50
+ ```
51
+
52
+ - **`players.primary(request)`** is who sent the request, by their id in your game, the same one your game's `players.primary` has. Arcadible set it after checking the request's ticket, so there's nothing to check.
53
+ - **`players.read`** takes up to 50 ids. A name is the player's own, as they've set it on Arcadible; show it as text.
54
+
55
+ ## Values
56
+
57
+ Your game's data, kept on Arcadible: JSON under a key, in a scope. Your function reads the developer's values, and reads and writes the game's (which every player reads), its own (`"server"`, which no player reads), and any player's.
58
+
59
+ ```ts
60
+ // one call across scopes, one snapshot
61
+ const [match, seats] = await values.read([
62
+ { scope: "game", key: `match/${code}` },
63
+ { scope: "server", key: `seats/${code}` },
64
+ ]);
65
+ // each { scope, key, value, revision, updatedAt }, or null
66
+
67
+ // written all or none, each only if it's still the one read
68
+ await values.write([
69
+ { scope: "game", key: `match/${code}`, value: next, revision: match?.revision ?? 0 },
70
+ { scope: "server", key: `seats/${code}`, value: taken, revision: seats?.revision ?? 0 },
71
+ ]);
72
+ await values.remove([{ scope: "server", key: `seats/${code}` }]);
73
+ const { entries, next: after } = await values.list("game", { prefix: "match/" });
74
+ ```
75
+
76
+ - **`read`, `write`, and `remove`** take items, each naming its scope and key, up to 32, as one request across scopes: a read is one snapshot, and a write or a remove is all made or none.
77
+ - **A `revision`** makes a write, or a remove, only if the value is still that one (`0`: only if there's none); otherwise the whole call rejects with `conflict`, and your function reads again.
78
+ - **`since`** on a read item, a revision you have: if the value is still at it, it comes back `{ scope, key, revision, unchanged: true }`, without its value.
79
+ - **`list`** gives a scope's keys, with their sizes and times and no values, 50 at a time.
80
+
81
+ Every call rejects with an `ArcadibleError`, whose `code` says what to do: `invalid`, `denied` (not allowed to a function), `conflict`, `too_large`, `too_many`, `full` (the scope's storage is used up), `busy`, or `unavailable`.
82
+
83
+ ## Development
84
+
85
+ `arc serve` runs your function beside your game, as Arcadible would, and the Function SDK's calls go to `arc serve`'s own values and players: nothing reaches Arcadible.
86
+
87
+ ## License
88
+
89
+ Apache-2.0
@@ -0,0 +1,19 @@
1
+ import { type Api } from "../shared/api.js";
2
+ import { ArcadibleError } from "../shared/error.js";
3
+ /** Where Arcadible's entry puts its transport. */
4
+ export declare const TRANSPORT: unique symbol;
5
+ /**
6
+ * What the entry gives: `version`, raised whenever the entry adds to it, and
7
+ * `fetch`, which sends a request to the server API (`path` after
8
+ * `/v1/server`, `init` fetch's own) and resolves with its answer, never
9
+ * throwing: Arcadible unreached is a `503`.
10
+ */
11
+ export type Transport = {
12
+ version: number;
13
+ fetch(path: string, init: RequestInit): Promise<Response>;
14
+ };
15
+ /** The entry's transport, or `null` outside a function. */
16
+ export declare function transportOf(): Transport | null;
17
+ export declare function notInFunction(call: string): ArcadibleError;
18
+ /** The server API, through the entry's transport, read at each request. */
19
+ export declare function createApi(): Api;
@@ -0,0 +1,54 @@
1
+ // Arcadible's server API, for a game's function: every call goes through
2
+ // the transport Arcadible's entry around the function's code sets (the
3
+ // CLI's runner/entry.ts, and the pipeline's, plan/SERVER-SDK-SPLIT.md, 5),
4
+ // which adds the address and the newest claim, on Arcadible, or points at
5
+ // `arc serve`'s API under it. The Function SDK reads nothing else: no
6
+ // environment, no key.
7
+ // [import]
8
+ import { dataOf, initOf, TIMEOUT, unreachable, } from "../shared/api.js";
9
+ import { ArcadibleError, Codes } from "../shared/error.js";
10
+ // [declare]
11
+ /** Where Arcadible's entry puts its transport. */
12
+ export const TRANSPORT = Symbol.for("arcadible.function.api");
13
+ // The least version of the transport this SDK needs.
14
+ const VERSION = 1;
15
+ // [function]
16
+ /** The entry's transport, or `null` outside a function. */
17
+ export function transportOf() {
18
+ const given = globalThis[TRANSPORT];
19
+ if (typeof given !== "object" || given === null)
20
+ return null;
21
+ const { fetch, version } = given;
22
+ return typeof fetch === "function" &&
23
+ typeof version === "number" &&
24
+ version >= VERSION
25
+ ? given
26
+ : null;
27
+ }
28
+ // [function]
29
+ // the error for a call made where there's no function.
30
+ export function notInFunction(call) {
31
+ return new ArcadibleError(Codes.Invalid, `${call} works only in a game's function, on Arcadible or under arc serve. On a server of your own, use @arcadible/server-sdk.`);
32
+ }
33
+ // [function]
34
+ /** The server API, through the entry's transport, read at each request. */
35
+ export function createApi() {
36
+ return {
37
+ async request(path, body) {
38
+ const transport = transportOf();
39
+ if (!transport)
40
+ throw notInFunction("The Function SDK");
41
+ let res;
42
+ try {
43
+ res = await transport.fetch(path, {
44
+ ...initOf(body),
45
+ signal: AbortSignal.timeout(TIMEOUT),
46
+ });
47
+ }
48
+ catch {
49
+ throw unreachable();
50
+ }
51
+ return dataOf(res, "Arcadible didn't take the function's claim. Try again.");
52
+ },
53
+ };
54
+ }
@@ -0,0 +1,36 @@
1
+ import { type Values } from "../shared/values.js";
2
+ import { type Players } from "./players.js";
3
+ /** What a function's calls fail with: every code but `expired`, a ticket's. */
4
+ export declare const Codes: {
5
+ readonly Busy: "busy";
6
+ readonly Conflict: "conflict";
7
+ readonly Denied: "denied";
8
+ readonly Full: "full";
9
+ readonly Invalid: "invalid";
10
+ readonly TooLarge: "too_large";
11
+ readonly TooMany: "too_many";
12
+ readonly Unavailable: "unavailable";
13
+ };
14
+ export type Code = (typeof Codes)[keyof typeof Codes];
15
+ /** A failure with a code: `err.code` says what to do about it. */
16
+ export interface ArcadibleError extends Error {
17
+ readonly code: Code;
18
+ }
19
+ export declare const ArcadibleError: {
20
+ new (code: Code, message: string): ArcadibleError;
21
+ readonly prototype: ArcadibleError;
22
+ };
23
+ /**
24
+ * The game's players: who sent a request, which Arcadible checked before
25
+ * the code ran, and their names.
26
+ */
27
+ export declare const players: Players;
28
+ /**
29
+ * The game's values, kept on Arcadible: JSON under a key, in a scope. A
30
+ * function reads the developer's, and reads and writes the game's, its own
31
+ * (`server`), and any player's of the game.
32
+ */
33
+ export declare const values: Values;
34
+ export type { Player } from "../shared/players.js";
35
+ export type { Entry, Listed, ListOptions, ReadItem, RemoveItem, Scope, Unchanged, Value, WritableScope, WriteItem, Written, } from "../shared/values.js";
36
+ export type { PrimaryPlayer } from "./players.js";
@@ -0,0 +1,36 @@
1
+ // `@arcadible/function-sdk`: what a game's function uses with Arcadible, on
2
+ // Arcadible or under `arc serve`. It runs in a function alone, where
3
+ // Arcadible's entry gives it its way to Arcadible (./api.ts); a server of the
4
+ // developer's own uses `@arcadible/server-sdk`.
5
+ // [import]
6
+ import { ArcadibleError as Shared, Codes as Every } from "../shared/error.js";
7
+ import { createValues } from "../shared/values.js";
8
+ import { createApi } from "./api.js";
9
+ import { createPlayers } from "./players.js";
10
+ // [declare]
11
+ const api = createApi();
12
+ // [export]
13
+ /** What a function's calls fail with: every code but `expired`, a ticket's. */
14
+ export const Codes = {
15
+ Busy: Every.Busy,
16
+ Conflict: Every.Conflict,
17
+ Denied: Every.Denied,
18
+ Full: Every.Full,
19
+ Invalid: Every.Invalid,
20
+ TooLarge: Every.TooLarge,
21
+ TooMany: Every.TooMany,
22
+ Unavailable: Every.Unavailable,
23
+ };
24
+ // the one class both packages throw, typed with this package's codes.
25
+ export const ArcadibleError = Shared;
26
+ /**
27
+ * The game's players: who sent a request, which Arcadible checked before
28
+ * the code ran, and their names.
29
+ */
30
+ export const players = createPlayers(() => api);
31
+ /**
32
+ * The game's values, kept on Arcadible: JSON under a key, in a scope. A
33
+ * function reads the developer's, and reads and writes the game's, its own
34
+ * (`server`), and any player's of the game.
35
+ */
36
+ export const values = createValues(() => api);
@@ -0,0 +1,25 @@
1
+ import type { Api } from "../shared/api.js";
2
+ import { type Player } from "../shared/players.js";
3
+ /** Who sent a request to a function. */
4
+ export type PrimaryPlayer = {
5
+ /** Their id in this game, the same every time. */
6
+ id: string;
7
+ };
8
+ export interface Players {
9
+ /**
10
+ * Who sent a request: the player, by their id in this game, the one the
11
+ * game's `players.primary` has, or `null` for a guest. It's Arcadible's
12
+ * word, set after the request's ticket was checked: a request with none
13
+ * never reaches a function. Only in a function: anywhere else nobody has
14
+ * checked the request, so it throws there.
15
+ */
16
+ primary(request: Request): PrimaryPlayer | null;
17
+ /**
18
+ * Each player, in the order given: their id and name, or `null` for one
19
+ * who's gone, never was, or is a guest. Up to 50 ids.
20
+ */
21
+ read(ids: readonly string[]): Promise<(Player | null)[]>;
22
+ }
23
+ /** The header Arcadible sets on a request to a function: the player's id, or empty for a guest. */
24
+ export declare const PLAYER = "x-arcadible-player";
25
+ export declare function createPlayers(api: () => Api): Players;
@@ -0,0 +1,20 @@
1
+ // Players, for a game's function: who sent a request, which Arcadible has
2
+ // checked already, and their names.
3
+ import { readPlayers, UUID } from "../shared/players.js";
4
+ import { notInFunction, transportOf } from "./api.js";
5
+ /** The header Arcadible sets on a request to a function: the player's id, or empty for a guest. */
6
+ export const PLAYER = "x-arcadible-player";
7
+ // [function]
8
+ export function createPlayers(api) {
9
+ return {
10
+ primary(request) {
11
+ // the entry's transport says the code runs as a function, where
12
+ // Arcadible checked the request and set this header itself.
13
+ if (!transportOf())
14
+ throw notInFunction("players.primary(request)");
15
+ const id = request.headers.get(PLAYER);
16
+ return id !== null && UUID.test(id) ? { id } : null;
17
+ },
18
+ read: readPlayers(api),
19
+ };
20
+ }
@@ -0,0 +1,16 @@
1
+ import { ArcadibleError } from "./error.js";
2
+ export type Api = {
3
+ request(path: string, body?: unknown): Promise<unknown>;
4
+ };
5
+ export declare const TIMEOUT: number;
6
+ export declare function initOf(body: unknown): {
7
+ body?: string;
8
+ headers: Record<string, string>;
9
+ method: "GET" | "POST";
10
+ };
11
+ export declare function unreachable(): ArcadibleError;
12
+ /**
13
+ * An answer's `data`, or the error its status says. `unauthorized` is what
14
+ * a `401` means to the caller: its key, or its claim, wasn't taken.
15
+ */
16
+ export declare function dataOf(res: Response, unauthorized: string): Promise<unknown>;
@@ -0,0 +1,75 @@
1
+ // Arcadible's server API, as both packages read it: what a call sends, and
2
+ // what an answer means. How a request gets there is each package's own: a
3
+ // server's with its key (../server/api.ts), a function's through Arcadible's
4
+ // entry, with its claim (../function/api.ts).
5
+ // [import]
6
+ import { ArcadibleError, Codes } from "./error.js";
7
+ // How long a call waits for Arcadible.
8
+ export const TIMEOUT = 15 * 1000;
9
+ // what Arcadible says of a game's values (values.ts), by status.
10
+ const REFUSED = {
11
+ 403: ["Denied", "Arcadible doesn't allow that to a game's server."],
12
+ 409: [
13
+ "Conflict",
14
+ "The value was written since the revision named. Read it again.",
15
+ ],
16
+ 413: ["TooLarge", "A value, or the call's values together, is too large."],
17
+ 507: ["Full", "The scope's storage is used up."],
18
+ };
19
+ // [function]
20
+ function isObject(value) {
21
+ return typeof value === "object" && value !== null && !Array.isArray(value);
22
+ }
23
+ // [function]
24
+ // what a call sends: the method, lowercase headers, and its body as JSON.
25
+ export function initOf(body) {
26
+ return body === undefined
27
+ ? { headers: { accept: "application/json" }, method: "GET" }
28
+ : {
29
+ body: JSON.stringify(body),
30
+ headers: {
31
+ "accept": "application/json",
32
+ "content-type": "application/json",
33
+ },
34
+ method: "POST",
35
+ };
36
+ }
37
+ // [function]
38
+ // Arcadible couldn't be reached.
39
+ export function unreachable() {
40
+ return new ArcadibleError(Codes.Unavailable, "Arcadible couldn't be reached. Try again.");
41
+ }
42
+ // [function]
43
+ /**
44
+ * An answer's `data`, or the error its status says. `unauthorized` is what
45
+ * a `401` means to the caller: its key, or its claim, wasn't taken.
46
+ */
47
+ export async function dataOf(res, unauthorized) {
48
+ if (res.status === 429) {
49
+ throw new ArcadibleError(Codes.Busy, "Too many requests. Slow down, and try again.");
50
+ }
51
+ if (res.status === 401) {
52
+ throw new ArcadibleError(Codes.Invalid, unauthorized);
53
+ }
54
+ const refusal = REFUSED[res.status];
55
+ if (refusal) {
56
+ throw new ArcadibleError(Codes[refusal[0]], refusal[1]);
57
+ }
58
+ if (res.status >= 500) {
59
+ throw new ArcadibleError(Codes.Unavailable, "Arcadible couldn't answer. Try again.");
60
+ }
61
+ if (!res.ok) {
62
+ throw new ArcadibleError(Codes.Invalid, "Arcadible didn't take the request.");
63
+ }
64
+ let answer;
65
+ try {
66
+ answer = await res.json();
67
+ }
68
+ catch {
69
+ answer = null;
70
+ }
71
+ if (!isObject(answer) || !("data" in answer)) {
72
+ throw new ArcadibleError(Codes.Unavailable, "Arcadible's answer couldn't be read. Try again.");
73
+ }
74
+ return answer["data"];
75
+ }
@@ -0,0 +1,17 @@
1
+ export declare const Codes: {
2
+ readonly Busy: "busy";
3
+ readonly Conflict: "conflict";
4
+ readonly Denied: "denied";
5
+ readonly Expired: "expired";
6
+ readonly Full: "full";
7
+ readonly Invalid: "invalid";
8
+ readonly TooLarge: "too_large";
9
+ readonly TooMany: "too_many";
10
+ readonly Unavailable: "unavailable";
11
+ };
12
+ export type Code = (typeof Codes)[keyof typeof Codes];
13
+ /** A failure with a code: `err.code` says what to do about it. */
14
+ export declare class ArcadibleError extends Error {
15
+ readonly code: Code;
16
+ constructor(code: Code, message: string);
17
+ }
@@ -0,0 +1,38 @@
1
+ // Why a call failed: a code a server branches on, and a message for its
2
+ // logs. The codes are the Arcadible SDK's, where the two share one. One
3
+ // class for both packages; each exports the codes it makes (the Function
4
+ // SDK's have no `expired`, since it checks no tickets).
5
+ // [declare]
6
+ export const Codes = {
7
+ // too many requests: slow down, and try again.
8
+ Busy: "busy",
9
+ // a value was written since the revision a write named: read it again.
10
+ Conflict: "conflict",
11
+ // Arcadible won't do this for a server: writing the developer's values,
12
+ // or a player who isn't the game's.
13
+ Denied: "denied",
14
+ // a ticket that was good, and isn't any more: ask the game for another.
15
+ // The Server SDK's alone.
16
+ Expired: "expired",
17
+ // the scope's storage is used up: remove something first.
18
+ Full: "full",
19
+ // not a ticket, or not one for this server and game: refuse it. Or a
20
+ // request Arcadible won't take: no key, a revoked one, or a bad argument.
21
+ Invalid: "invalid",
22
+ // a value, or a call's values together, past what one may be.
23
+ TooLarge: "too_large",
24
+ // more items in a call than one takes.
25
+ TooMany: "too_many",
26
+ // Arcadible couldn't be reached: worth trying again.
27
+ Unavailable: "unavailable",
28
+ };
29
+ // [class]
30
+ /** A failure with a code: `err.code` says what to do about it. */
31
+ export class ArcadibleError extends Error {
32
+ code;
33
+ constructor(code, message) {
34
+ super(message);
35
+ this.name = "ArcadibleError";
36
+ this.code = code;
37
+ }
38
+ }
@@ -0,0 +1,18 @@
1
+ import type { Api } from "./api.js";
2
+ import { ArcadibleError } from "./error.js";
3
+ /** A player, as a game's server sees one. */
4
+ export type Player = {
5
+ /** Their id in this game, the one a ticket names. */
6
+ id: string;
7
+ /** Their profile's name, as players see it; `null` with none. */
8
+ name: string | null;
9
+ };
10
+ export declare const MAX_PLAYERS = 50;
11
+ export declare const UUID: RegExp;
12
+ export declare function isObject(value: unknown): value is Record<string, unknown>;
13
+ export declare function unreadable(): ArcadibleError;
14
+ /**
15
+ * `players.read`: each player, in the order given, their id and name, or
16
+ * `null` for one who's gone, never was, or is a guest. Up to 50 ids.
17
+ */
18
+ export declare function readPlayers(api: () => Api): (ids: readonly string[]) => Promise<(Player | null)[]>;
@@ -0,0 +1,52 @@
1
+ // Players: what a game's server, or its function, may ask Arcadible about
2
+ // the players it knows by their ids: their names. Each package adds its own
3
+ // (the server's `deleted`, the function's `primary`).
4
+ import { ArcadibleError, Codes } from "./error.js";
5
+ // The most ids one read takes.
6
+ export const MAX_PLAYERS = 50;
7
+ export const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
8
+ // [function]
9
+ export function isObject(value) {
10
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11
+ }
12
+ // [function]
13
+ // an answer that isn't the shape a server relies on.
14
+ export function unreadable() {
15
+ return new ArcadibleError(Codes.Unavailable, "Arcadible's answer couldn't be read. Try again.");
16
+ }
17
+ // [function]
18
+ /**
19
+ * `players.read`: each player, in the order given, their id and name, or
20
+ * `null` for one who's gone, never was, or is a guest. Up to 50 ids.
21
+ */
22
+ export function readPlayers(api) {
23
+ return async (ids) => {
24
+ if (!Array.isArray(ids) ||
25
+ ids.length > MAX_PLAYERS ||
26
+ !ids.every((id) => typeof id === "string" && UUID.test(id))) {
27
+ throw new TypeError(`players.read takes up to ${MAX_PLAYERS} ids, each a player's id in the game.`);
28
+ }
29
+ if (ids.length === 0)
30
+ return [];
31
+ // each id once, then every place it was asked for
32
+ const asked = [...new Set(ids)];
33
+ const data = await api().request(`/players/${asked.join(",")}`);
34
+ if (!Array.isArray(data) || data.length !== asked.length) {
35
+ throw unreadable();
36
+ }
37
+ const found = new Map();
38
+ for (const entry of data) {
39
+ if (entry === null)
40
+ continue;
41
+ if (!isObject(entry) || typeof entry["id"] !== "string") {
42
+ throw unreadable();
43
+ }
44
+ const name = entry["name"];
45
+ found.set(entry["id"], {
46
+ id: entry["id"],
47
+ name: typeof name === "string" && name !== "" ? name : null,
48
+ });
49
+ }
50
+ return ids.map((id) => found.get(id) ?? null);
51
+ };
52
+ }
@@ -0,0 +1,99 @@
1
+ import type { Api } from "./api.js";
2
+ /**
3
+ * Whose the values are: `"developer"`, what the developer publishes, to
4
+ * read; `"game"`, what every player reads and only the game's server writes;
5
+ * `"server"`, the server's alone; or a player, by their id in the game:
6
+ * `{ id }`, as `players.primary(request)` or a ticket gives it.
7
+ */
8
+ export type Scope = "developer" | WritableScope;
9
+ /** A scope a server writes: every one but the developer's. */
10
+ export type WritableScope = "game" | "server" | {
11
+ id: string;
12
+ };
13
+ /** A value, with the revision a write may name to replace it. */
14
+ export type Value = {
15
+ scope: Scope;
16
+ key: string;
17
+ value: unknown;
18
+ revision: number;
19
+ /** When it was written, as an ISO time. */
20
+ updatedAt: string;
21
+ };
22
+ /** A value a read named with `since`, still at that revision: nothing more to read. */
23
+ export type Unchanged = {
24
+ scope: Scope;
25
+ key: string;
26
+ revision: number;
27
+ unchanged: true;
28
+ };
29
+ /** What a write left: the value's new revision. */
30
+ export type Written = {
31
+ scope: Scope;
32
+ key: string;
33
+ revision: number;
34
+ updatedAt: string;
35
+ };
36
+ /** A key in a list, without its value: its size is the value's, in bytes. */
37
+ export type Entry = {
38
+ key: string;
39
+ revision: number;
40
+ updatedAt: string;
41
+ size: number;
42
+ };
43
+ /** A value to read: its scope and key, and, with `since`, the revision the caller has. */
44
+ export type ReadItem = {
45
+ scope: Scope;
46
+ key: string;
47
+ since?: number;
48
+ };
49
+ /** A value to write: with `revision`, only if it's the value's now (`0`: only if there's none). */
50
+ export type WriteItem = {
51
+ scope: WritableScope;
52
+ key: string;
53
+ value: unknown;
54
+ revision?: number;
55
+ };
56
+ /** A value to remove: with `revision`, only if it's the value's now. */
57
+ export type RemoveItem = {
58
+ scope: WritableScope;
59
+ key: string;
60
+ revision?: number;
61
+ };
62
+ /** What a list takes: a prefix, the key to go on after, and how many. */
63
+ export type ListOptions = {
64
+ prefix?: string;
65
+ after?: string;
66
+ limit?: number;
67
+ };
68
+ /** A list's page: `next` is the key to pass as `after`, or `null` at the end. */
69
+ export type Listed = {
70
+ entries: Entry[];
71
+ next: string | null;
72
+ };
73
+ export interface Values {
74
+ /**
75
+ * The values of the items, in their order, in one call and one snapshot,
76
+ * across scopes: each with its revision, `Unchanged` for an item whose
77
+ * `since` is still its revision, or `null` for a key with none. Up to 32.
78
+ */
79
+ read(items: readonly ReadItem[]): Promise<(Value | Unchanged | null)[]>;
80
+ /**
81
+ * Replaces each item's value, whole, all of them or none, across scopes.
82
+ * With `revision`, only if it's the value's now (`0`: only if there's
83
+ * none); otherwise the call rejects with `conflict`, and nothing is
84
+ * written.
85
+ */
86
+ write(items: readonly WriteItem[]): Promise<Written[]>;
87
+ /** Removes what each item holds, all of them or none: with `revision`, only if it's the value's now. */
88
+ remove(items: readonly RemoveItem[]): Promise<void>;
89
+ /**
90
+ * A scope's keys in order, by byte, each with its revision, time, and
91
+ * size: those that start with `prefix`, after the key `after`, 50 by
92
+ * default and 100 at most. `next` is the key to pass as `after` for the
93
+ * following page, or `null` at the end.
94
+ */
95
+ list(scope: Scope, options?: ListOptions): Promise<Listed>;
96
+ }
97
+ export declare const MAX_KEYS = 32;
98
+ export declare const MAX_LIST = 100;
99
+ export declare function createValues(api: () => Api): Values;
@@ -0,0 +1,203 @@
1
+ // Values: a game's data kept on Arcadible, JSON under a key, in a scope. A
2
+ // game's server, its own or its function, reads all four scopes, and writes
3
+ // all but the developer's: its own (`server`, which no client reads, and
4
+ // which a function and a server with the channel's key share), the game's
5
+ // (`game`, which every client reads), and any player's of the game.
6
+ import { ArcadibleError, Codes } from "./error.js";
7
+ // A key: 1 to 128 letters, digits, `-`, `_`, `.`, and `/`.
8
+ const KEY = /^[A-Za-z0-9_./-]{1,128}$/u;
9
+ const PREFIX = /^[A-Za-z0-9_./-]{0,128}$/u;
10
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
11
+ // The most keys one call names, and one list gives.
12
+ export const MAX_KEYS = 32;
13
+ export const MAX_LIST = 100;
14
+ // [function]
15
+ function isObject(value) {
16
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17
+ }
18
+ // [function]
19
+ function invalid(message) {
20
+ return new ArcadibleError(Codes.Invalid, message);
21
+ }
22
+ // [function]
23
+ // an answer that isn't the shape a server relies on.
24
+ function unreadable() {
25
+ return new ArcadibleError(Codes.Unavailable, "Arcadible's answer couldn't be read. Try again.");
26
+ }
27
+ // [function]
28
+ // what a request says of its scope: its name, and the player for a player's.
29
+ function scopeOf(scope) {
30
+ if (scope === "developer" || scope === "game" || scope === "server") {
31
+ return { scope };
32
+ }
33
+ if (isObject(scope) && typeof scope.id === "string" && UUID.test(scope.id)) {
34
+ return { player: scope.id, scope: "player" };
35
+ }
36
+ throw invalid('A scope is "developer", "game", "server", or a player, as { id }.');
37
+ }
38
+ // [function]
39
+ // a call's items: at least one, no more than a call takes, each an object
40
+ // with a scope and a key, none named twice in a scope.
41
+ function itemsOf(items) {
42
+ if (!Array.isArray(items) || !items.every(isObject)) {
43
+ throw invalid("A call takes a list of items, each { scope, key }.");
44
+ }
45
+ if (items.length === 0)
46
+ throw invalid("A call names at least one item.");
47
+ if (items.length > MAX_KEYS) {
48
+ throw new ArcadibleError(Codes.TooMany, `A call names up to ${MAX_KEYS} items.`);
49
+ }
50
+ const seen = new Set();
51
+ for (const item of items) {
52
+ const key = item["key"];
53
+ if (typeof key !== "string" || !KEY.test(key)) {
54
+ throw invalid("A key is 1 to 128 letters, digits, -, _, ., and /: " +
55
+ JSON.stringify(key));
56
+ }
57
+ const where = `${JSON.stringify(scopeOf(item["scope"]))} ${key}`;
58
+ if (seen.has(where))
59
+ throw invalid("A call names each key once in a scope.");
60
+ seen.add(where);
61
+ }
62
+ return items;
63
+ }
64
+ // [function]
65
+ // a value as JSON keeps it: `undefined`, a function, or a number that isn't
66
+ // one would be dropped or changed on the way, so each is refused here.
67
+ function jsonOf(key, value) {
68
+ let text;
69
+ try {
70
+ text = JSON.stringify(value, (_, each) => {
71
+ if (typeof each === "number" && !Number.isFinite(each)) {
72
+ throw new TypeError("not finite");
73
+ }
74
+ return each;
75
+ });
76
+ }
77
+ catch {
78
+ text = undefined;
79
+ }
80
+ if (text === undefined) {
81
+ throw invalid(`The value for ${JSON.stringify(key)} isn't JSON.`);
82
+ }
83
+ return JSON.parse(text);
84
+ }
85
+ // [function]
86
+ function revisionOf(revision) {
87
+ if (!Number.isSafeInteger(revision) || revision < 0) {
88
+ throw invalid("A revision is a value's own, from a read or a write, or 0.");
89
+ }
90
+ return revision;
91
+ }
92
+ // [function]
93
+ // a row of a read, a write, or a list, in the SDK's words.
94
+ function rowOf(entry) {
95
+ if (!isObject(entry) ||
96
+ typeof entry["key"] !== "string" ||
97
+ typeof entry["revision"] !== "number" ||
98
+ typeof entry["updated_at"] !== "string") {
99
+ throw unreadable();
100
+ }
101
+ return {
102
+ key: entry["key"],
103
+ revision: entry["revision"],
104
+ size: typeof entry["size"] === "number" ? entry["size"] : 0,
105
+ updatedAt: entry["updated_at"],
106
+ value: entry["value"],
107
+ };
108
+ }
109
+ // [function]
110
+ export function createValues(api) {
111
+ const read = async function (given) {
112
+ const items = itemsOf(given).map((item) => ({
113
+ ...scopeOf(item.scope),
114
+ key: item.key,
115
+ ...(item.since === undefined ? {} : { since: revisionOf(item.since) }),
116
+ }));
117
+ const data = await api().request("/values/read", { items });
118
+ if (!Array.isArray(data) || data.length !== items.length) {
119
+ throw unreadable();
120
+ }
121
+ return data.map((entry, at) => {
122
+ const scope = given[at].scope;
123
+ if (entry === null)
124
+ return null;
125
+ if (isObject(entry) &&
126
+ entry["unchanged"] === true &&
127
+ typeof entry["key"] === "string" &&
128
+ typeof entry["revision"] === "number") {
129
+ return {
130
+ key: entry["key"],
131
+ revision: entry["revision"],
132
+ scope,
133
+ unchanged: true,
134
+ };
135
+ }
136
+ const { key, revision, updatedAt, value } = rowOf(entry);
137
+ return { key, revision, scope, updatedAt, value };
138
+ });
139
+ };
140
+ const write = async function (given) {
141
+ const items = itemsOf(given).map((item) => ({
142
+ ...scopeOf(item.scope),
143
+ key: item.key,
144
+ value: jsonOf(item.key, item.value),
145
+ ...(item.revision === undefined
146
+ ? {}
147
+ : { revision: revisionOf(item.revision) }),
148
+ }));
149
+ const data = await api().request("/values/write", { items });
150
+ if (!Array.isArray(data) || data.length !== items.length) {
151
+ throw unreadable();
152
+ }
153
+ return data.map((entry, at) => {
154
+ const { key, revision, updatedAt } = rowOf(entry);
155
+ return {
156
+ key,
157
+ revision,
158
+ scope: given[at].scope,
159
+ updatedAt,
160
+ };
161
+ });
162
+ };
163
+ const remove = async function (given) {
164
+ const items = itemsOf(given).map((item) => ({
165
+ ...scopeOf(item.scope),
166
+ key: item.key,
167
+ ...(item.revision === undefined
168
+ ? {}
169
+ : { revision: revisionOf(item.revision) }),
170
+ }));
171
+ await api().request("/values/remove", { items });
172
+ };
173
+ const list = async function (scope, options = {}) {
174
+ const { after = "", limit = 50, prefix = "" } = options;
175
+ if (typeof prefix !== "string" || !PREFIX.test(prefix)) {
176
+ throw invalid("A prefix is what a key starts with: a key's letters.");
177
+ }
178
+ if (typeof after !== "string" || !PREFIX.test(after)) {
179
+ throw invalid("`after` is a key: a list's `next`.");
180
+ }
181
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIST) {
182
+ throw invalid(`A list gives 1 to ${MAX_LIST} keys.`);
183
+ }
184
+ const data = await api().request("/values/list", {
185
+ ...scopeOf(scope),
186
+ after,
187
+ limit,
188
+ prefix,
189
+ });
190
+ if (!isObject(data) || !Array.isArray(data["entries"])) {
191
+ throw unreadable();
192
+ }
193
+ const next = data["next"];
194
+ return {
195
+ entries: data["entries"].map((entry) => {
196
+ const { key, revision, size, updatedAt } = rowOf(entry);
197
+ return { key, revision, size, updatedAt };
198
+ }),
199
+ next: typeof next === "string" ? next : null,
200
+ };
201
+ };
202
+ return { list, read, remove, write };
203
+ }
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
+ "author": "Offst, Inc.",
3
+ "description": "The Arcadible Function SDK: how your game's function works with Arcadible.",
4
+ "exports": {
5
+ ".": {
6
+ "import": "./dist/function/index.js",
7
+ "types": "./dist/function/index.d.ts"
8
+ }
9
+ },
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "homepage": "https://developer.arcadible.com/references/arcadible-function-sdk",
14
+ "keywords": [
15
+ "arcadible",
16
+ "function",
17
+ "games",
18
+ "sdk",
19
+ "server"
20
+ ],
21
+ "license": "Apache-2.0",
2
22
  "name": "@arcadible/function-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
23
+ "scripts": {
24
+ "prepack": "rm -rf dist && tsc -p ../tsconfig.function.json"
25
+ },
26
+ "type": "module",
27
+ "types": "./dist/function/index.d.ts",
28
+ "version": "0.4.0-next.0"
29
+ }