@sagl/query 0.0.0-stage → 0.1.0-next.53

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 Thomas Burnett-Taylor
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,41 @@
1
- # Temporary Holding Version
1
+ # @sagl/query
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
+ Ask [SAGL](https://docs.sagl.mp) servers (GTA: San Andreas multiplayer) about themselves without joining them: their name, who's on, their branding and logo, and whatever the gamemode adds (a description, links, tags, its own values). For server lists, websites and bots. Plain Node.js, no dependencies.
4
+
5
+ ```sh
6
+ npm install @sagl/query
7
+ ```
8
+
9
+ ```js
10
+ import { queryServer } from "@sagl/query";
11
+
12
+ const { info, ping } = await queryServer("play.example.com", 7777);
13
+ console.log(`${info.name}: ${info.players?.online}/${info.players?.max} players, ${ping} ms`);
14
+ for (const p of info.players?.list ?? []) console.log(` ${p.name} (score ${p.score}, ${p.ping} ms)`);
15
+ console.log(info.links?.discord);
16
+ ```
17
+
18
+ `queryServer(host, port = 7777, options)` resolves to:
19
+
20
+ - `info`: what the server says. Its fields are listed below.
21
+ - `ping`: the round trip, in milliseconds.
22
+ - `logo`: the logo's bytes (PNG or JPEG), when `logo: true` is passed and the server has one. They're checked against its SHA-256.
23
+
24
+ It rejects if the server doesn't answer. The options are:
25
+
26
+ - `timeout`: how long to wait for each reply, in ms. Default 1500.
27
+ - `logo`: fetch the logo too. Default false.
28
+
29
+ `info` has these fields:
30
+
31
+ | Field | |
32
+ |---|---|
33
+ | `name`, `version`, `protocol` | The server's name, its SAGL version, and the protocol a game client needs to join it |
34
+ | `players` | `{ online, max, list?: [{ id, name, score, ping }], truncated? }`. Left out, or without `list`, if the server hides it |
35
+ | `branding` | `{ logo: { sha256, size } \| null, primary, secondary, showName }`. The colours are `"#rrggbb"` or `null` |
36
+ | `description`, `gamemode`, `language`, `tags`, `links` | The gamemode's, if set. `links` is by name: `website`, `discord`, ... |
37
+ | `values` | The gamemode's own key/values, which can change at any time |
38
+
39
+ The query uses UDP on the server's game port. Servers can also serve the same JSON over HTTP (`GET /` and `GET /logo`) if their owner turns it on. The format is documented at [docs.sagl.mp](https://docs.sagl.mp/server-api/query/).
40
+
41
+ MIT licence.
@@ -0,0 +1,66 @@
1
+ /** A query value: the gamemode's own, changed whenever it likes. */
2
+ export type QueryValue = string | number | boolean | null;
3
+ /** What a query says (`queryServer`, or the HTTP endpoint). */
4
+ export interface QueryResult {
5
+ /** The query format's version (1). */
6
+ query: number;
7
+ name: string;
8
+ /** The server's SAGL version. */
9
+ version: string;
10
+ /** Its protocol: a client needs the same to join. */
11
+ protocol: number;
12
+ /** Left out if the server hides them. */
13
+ players?: {
14
+ online: number;
15
+ max: number;
16
+ /** Left out if the server shows only the count. */
17
+ list?: {
18
+ id: number;
19
+ name: string;
20
+ score: number;
21
+ ping: number;
22
+ }[];
23
+ /** The list was too long to send whole. */
24
+ truncated?: boolean;
25
+ };
26
+ branding: {
27
+ /** Its logo (a square PNG or JPEG), to fetch by hash, or null. */
28
+ logo: {
29
+ sha256: string;
30
+ size: number;
31
+ } | null;
32
+ /** `"#rrggbb"`, or null for SAGL's own. */
33
+ primary: string | null;
34
+ secondary: string | null;
35
+ showName: boolean;
36
+ };
37
+ description?: string;
38
+ gamemode?: string;
39
+ language?: string;
40
+ tags?: string[];
41
+ links?: Record<string, string>;
42
+ values?: Record<string, QueryValue>;
43
+ }
44
+ export interface QueryServerOptions {
45
+ /** How long to wait for each reply, in ms. Default 1500. */
46
+ timeout?: number;
47
+ /** Fetches the logo too (checked against its hash). Default false. */
48
+ logo?: boolean;
49
+ }
50
+ export interface QueryServerResult {
51
+ info: QueryResult;
52
+ /** The round trip, in ms. */
53
+ ping: number;
54
+ /** With `logo: true`, if it has one. */
55
+ logo?: Buffer;
56
+ }
57
+ /**
58
+ * Asks a SAGL server about itself over UDP, as server lists do: its name,
59
+ * players, branding and the gamemode's fields. Rejects if it doesn't answer.
60
+ *
61
+ * ```ts
62
+ * const { info, ping } = await queryServer("play.example.com", 7777);
63
+ * console.log(`${info.name}: ${info.players?.online}/${info.players?.max}, ${ping} ms`);
64
+ * ```
65
+ */
66
+ export declare function queryServer(host: string, port?: number, options?: QueryServerOptions): Promise<QueryServerResult>;
@@ -0,0 +1,127 @@
1
+ // Asking a SAGL server about itself without joining it (the query: see
2
+ // docs/server-api/query.md). Plain Node, no addon: it's also published on
3
+ // its own as @sagl/query, for websites, bots and server lists.
4
+ import * as dgram from "node:dgram";
5
+ import { createHash } from "node:crypto";
6
+ // ---- Asking a server -----------------------------------------------------------------
7
+ const REQUEST = 64;
8
+ const HEADER = 8;
9
+ const KIND_CHALLENGE = 0, KIND_INFO = 1, KIND_LOGO = 2;
10
+ function request(kind, token, arg = 0) {
11
+ const b = Buffer.alloc(REQUEST);
12
+ b.write("SAGQ", 0, "latin1");
13
+ b[4] = 1;
14
+ b[5] = kind;
15
+ b.writeUInt32LE(token >>> 0, 8);
16
+ b.writeUInt32LE(arg >>> 0, 12);
17
+ return b;
18
+ }
19
+ /**
20
+ * Asks a SAGL server about itself over UDP, as server lists do: its name,
21
+ * players, branding and the gamemode's fields. Rejects if it doesn't answer.
22
+ *
23
+ * ```ts
24
+ * const { info, ping } = await queryServer("play.example.com", 7777);
25
+ * console.log(`${info.name}: ${info.players?.online}/${info.players?.max}, ${ping} ms`);
26
+ * ```
27
+ */
28
+ export function queryServer(host, port = 7777, options = {}) {
29
+ const timeout = options.timeout ?? 1500;
30
+ const socket = dgram.createSocket("udp4");
31
+ let token = 0;
32
+ let listener = null;
33
+ socket.on("message", (msg) => {
34
+ if (msg.length < HEADER || msg.toString("latin1", 0, 4) !== "SAGR" || msg[4] !== 1)
35
+ return;
36
+ if (msg[5] === KIND_CHALLENGE && msg.length >= HEADER + 4)
37
+ token = msg.readUInt32LE(HEADER);
38
+ listener?.(msg);
39
+ });
40
+ const send = (b) => new Promise((resolve, reject) => socket.send(b, port, host, (e) => (e ? reject(e) : resolve())));
41
+ // Sends until `done` takes a reply (resolving), answering challenges.
42
+ const exchange = (make, take) => new Promise((resolve, reject) => {
43
+ let tries = 0;
44
+ let timer;
45
+ const attempt = () => {
46
+ if (++tries > 4) {
47
+ listener = null;
48
+ reject(new Error(`${host}:${port} didn't answer`));
49
+ return;
50
+ }
51
+ clearTimeout(timer);
52
+ timer = setTimeout(attempt, timeout);
53
+ send(make()).catch((e) => {
54
+ clearTimeout(timer);
55
+ listener = null;
56
+ reject(e);
57
+ });
58
+ };
59
+ listener = (msg) => {
60
+ if (msg[5] === KIND_CHALLENGE) {
61
+ tries = Math.max(0, tries - 1); // a challenge isn't a lost try
62
+ attempt();
63
+ return;
64
+ }
65
+ const got = take(msg);
66
+ if (got === undefined) {
67
+ clearTimeout(timer);
68
+ timer = setTimeout(attempt, timeout);
69
+ return;
70
+ }
71
+ clearTimeout(timer);
72
+ listener = null;
73
+ resolve(got);
74
+ };
75
+ attempt();
76
+ });
77
+ const run = async () => {
78
+ let parts = [];
79
+ let serial = -1, total = 0, have = 0, sent = 0, ping = 0;
80
+ const json = await exchange(() => {
81
+ sent = performance.now();
82
+ return request(KIND_INFO, token);
83
+ }, (msg) => {
84
+ if (msg[5] !== KIND_INFO || msg.length < HEADER + 12)
85
+ return undefined;
86
+ const s = msg.readUInt32LE(HEADER), part = msg.readUInt16LE(HEADER + 8), count = msg.readUInt16LE(HEADER + 10);
87
+ if (s !== serial) {
88
+ serial = s;
89
+ total = msg.readUInt32LE(HEADER + 4);
90
+ parts = new Array(count);
91
+ have = 0;
92
+ ping = Math.round(performance.now() - sent);
93
+ }
94
+ if (part >= parts.length || parts[part])
95
+ return undefined;
96
+ parts[part] = msg.subarray(HEADER + 12);
97
+ if (++have < parts.length)
98
+ return undefined;
99
+ const all = Buffer.concat(parts);
100
+ return all.length === total ? all.toString("utf8") : undefined;
101
+ });
102
+ const info = JSON.parse(json);
103
+ const result = { info, ping };
104
+ if (options.logo && info.branding?.logo) {
105
+ const want = info.branding.logo;
106
+ const chunks = [];
107
+ let got = 0;
108
+ while (got < want.size) {
109
+ const chunk = await exchange(() => request(KIND_LOGO, token, got), (msg) => (msg[5] === KIND_LOGO && msg.length >= HEADER + 40 && msg.readUInt32LE(HEADER + 4) === got ? msg : undefined));
110
+ const size = chunk.readUInt32LE(HEADER);
111
+ if (size !== want.size)
112
+ throw new Error("the logo changed while it was fetched");
113
+ const data = chunk.subarray(HEADER + 40);
114
+ if (!data.length)
115
+ throw new Error("the logo stopped short");
116
+ chunks.push(data);
117
+ got += data.length;
118
+ }
119
+ const logo = Buffer.concat(chunks);
120
+ if (createHash("sha256").update(logo).digest("hex") !== want.sha256)
121
+ throw new Error("the logo didn't match its hash");
122
+ result.logo = logo;
123
+ }
124
+ return result;
125
+ };
126
+ return run().finally(() => socket.close());
127
+ }
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@sagl/query",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-next.53",
4
+ "description": "Ask SAGL (GTA: San Andreas multiplayer) servers about themselves: name, players, branding, links",
5
+ "type": "module",
6
+ "main": "dist/query-client.js",
7
+ "types": "dist/query-client.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/query-client.d.ts",
11
+ "default": "./dist/query-client.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "engines": {
20
+ "node": ">=18"
21
+ },
22
+ "license": "MIT",
23
+ "homepage": "https://docs.sagl.mp/server-api/query/",
24
+ "keywords": [
25
+ "gta",
26
+ "san-andreas",
27
+ "multiplayer",
28
+ "server-query",
29
+ "server-list",
30
+ "sagl"
31
+ ]
32
+ }