@osrsclans/api 0.0.0 → 1.15.1

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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +166 -0
  3. package/dist/answered.d.ts +17 -0
  4. package/dist/answered.js +52 -0
  5. package/dist/api-error.d.ts +13 -0
  6. package/dist/api-error.js +18 -0
  7. package/dist/chains.d.ts +37 -0
  8. package/dist/chains.js +30 -0
  9. package/dist/client.d.ts +24 -0
  10. package/dist/client.js +25 -0
  11. package/dist/data-request-error.d.ts +9 -0
  12. package/dist/data-request-error.js +12 -0
  13. package/dist/data-requests.d.ts +6 -0
  14. package/dist/data-requests.js +16 -0
  15. package/dist/destinations.d.ts +23 -0
  16. package/dist/destinations.js +74 -0
  17. package/dist/errors.generated.d.ts +775 -0
  18. package/dist/errors.generated.js +1034 -0
  19. package/dist/index.generated.d.ts +7 -0
  20. package/dist/index.generated.js +4 -0
  21. package/dist/models.generated.d.ts +351 -0
  22. package/dist/models.generated.js +1 -0
  23. package/dist/operation-types.d.ts +23 -0
  24. package/dist/operation-types.js +1 -0
  25. package/dist/operations.generated.d.ts +5693 -0
  26. package/dist/operations.generated.js +362 -0
  27. package/dist/outcomes.generated.d.ts +21 -0
  28. package/dist/outcomes.generated.js +26 -0
  29. package/dist/public.d.ts +7 -0
  30. package/dist/public.js +7 -0
  31. package/dist/schema.generated.d.ts +32193 -0
  32. package/dist/schema.generated.js +1136 -0
  33. package/dist/streams.d.ts +29 -0
  34. package/dist/streams.js +95 -0
  35. package/dist/unexpected-status.d.ts +5 -0
  36. package/dist/unexpected-status.js +9 -0
  37. package/dist/walk.d.ts +13 -0
  38. package/dist/walk.js +24 -0
  39. package/dist/walkers.generated.d.ts +702 -0
  40. package/dist/walkers.generated.js +106 -0
  41. package/package.json +52 -6
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The OSRS Clans authors
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 ADDED
@@ -0,0 +1,166 @@
1
+ # @osrsclans/api
2
+
3
+ A typed client for the [OSRS Clans](https://osrsclans.cc) API. It covers the Public API, which needs no sign-in, and the Clan Owner API, which takes a clan token.
4
+
5
+ The types are generated from the API's own OpenAPI document, so every path, parameter and answer is checked by TypeScript. Requests go through [openapi-fetch](https://openapi-ts.dev/openapi-fetch/).
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @osrsclans/api
11
+ ```
12
+
13
+ ## Read the public API
14
+
15
+ ```ts EXAMPLE: read the public API
16
+ import { createClient, LootSort, Recruitment, SortDirection } from "@osrsclans/api";
17
+
18
+ const osrsclans = createClient();
19
+
20
+ const tags = await osrsclans.listTags();
21
+ const clan = await osrsclans.getClan("iron-foundry");
22
+ const clans = await osrsclans.listClans({ recruitment: [Recruitment.Open], limit: 20 });
23
+ const rates = await osrsclans.listLootRates({ sort: LootSort.GpPerHour, direction: SortDirection.Desc });
24
+ const whip = await osrsclans.getItem(4151);
25
+ ```
26
+
27
+ Each route has one function, a verb and an object: `getClan`, `listClans`, `searchItems`, `updateDinkConfig`. The verbs are `get`, `list`, `search`, `create`, `update`, `delete` and a few more for one kind of action each, such as `rotate` and `preview`.
28
+
29
+ A function takes the path parameters first, in the order of the path. The query parameters and the request `body` come last, in one object. A function returns the answer alone. An image or a model file comes back as a `Blob`.
30
+
31
+ Each set of named values is an exported enum, such as `Recruitment`, `LootSort` or `ItemScale`. A member is its value on the wire: `Recruitment.Open` is `"open"`. Each answer and body has a named type, such as `ClanDetailOut` or `DataRequestAsk`.
32
+
33
+ ## Errors
34
+
35
+ A refusal throws the class of its problem code, such as `ClanNotFoundError` for `clan_not_found`. Each one is an `ApiError`, with the HTTP `status` and the parsed `problem`.
36
+
37
+ ```ts EXAMPLE: catch a refusal by its code
38
+ import { ApiError, ClanNotFoundError } from "@osrsclans/api";
39
+
40
+ try {
41
+ await osrsclans.getClan("no-such-clan");
42
+ } catch (error) {
43
+ if (error instanceof ClanNotFoundError) console.log("No clan has this address.");
44
+ else if (error instanceof ApiError) console.log(error.status, error.problem?.detail);
45
+ else throw error;
46
+ }
47
+ ```
48
+
49
+ ## Read every page
50
+
51
+ A list route that answers in pages has a walker, named `iter` and the route's name less a leading `list`: `iterClans`, `iterItems`, `iterSearchItems`. A walker takes the route's path parameters and its query less `offset`, and yields every row. It reads the next page only when the rows before it are taken, so a loop that stops early reads no more pages.
52
+
53
+ ```ts EXAMPLE: read every clan that recruits
54
+ for await (const clan of osrsclans.iterClans({ recruitment: [Recruitment.Open], limit: 200 })) {
55
+ console.log(clan.slug);
56
+ }
57
+ ```
58
+
59
+ `limit` is the size of each page. The directory shuffles its clans, so `iterClans` sends the first page's `seed` with each later page and reads every clan once.
60
+
61
+ ## Use a clan token
62
+
63
+ A clan owner makes a clan token in the 3rd party tab of the clan page. The client sends it as a bearer token.
64
+
65
+ ```ts EXAMPLE: call the Clan Owner API with a clan token
66
+ import { ClanSocketEvent, DataRequestMode, DestinationFormat, StreamSwitch } from "@osrsclans/api";
67
+
68
+ const owner = createClient({ clanToken: process.env.OSRSCLANS_CLAN_TOKEN });
69
+
70
+ const destinations = await owner.listClansocketDestinations("my-clan");
71
+
72
+ const made = await owner.createClansocketDestination("my-clan", {
73
+ body: {
74
+ label: "Drops channel",
75
+ address: "https://example.org/osrsclans-hook",
76
+ format: DestinationFormat.Json,
77
+ events: [ClanSocketEvent.LevelUp, ClanSocketEvent.Loot],
78
+ },
79
+ });
80
+
81
+ const asked = await owner.createClansocketDataRequest("my-clan", {
82
+ body: { accountHash: "4519273648123", switches: [StreamSwitch.StreamBank], mode: DataRequestMode.Snapshot, seconds: 60 },
83
+ });
84
+ ```
85
+
86
+ Keep the token secret. Do not put it in code that runs in a browser.
87
+
88
+ ## Calls that go together
89
+
90
+ | Function | Does |
91
+ | --- | --- |
92
+ | `requestClanData(slug, ask)` | Starts a ClanSocket data request, reads it until it has an outcome, and returns the member's data. It needs the clan token |
93
+ | `lookupItemsByName(names, query?)` | Looks up any number of names, 50 to a request, and returns a `Map` from each name to its matches. `lookupNpcsByName` and `lookupSpritesByName` do the same for NPCs and sprites |
94
+ | `getClanProfile(slug, { roster })` | Reads a clan, its first page of posts and of reviews, and, with `roster: true`, its roster, all at once. The roster needs the clan token |
95
+
96
+ A data request that ends without data throws the class of its outcome. Each one is a `DataRequestError`, and its `request` holds the request with its status.
97
+
98
+ ```ts EXAMPLE: ask a member's plugin for its bank
99
+ import { DataRequestDeclined } from "@osrsclans/api";
100
+
101
+ try {
102
+ const answer = await owner.requestClanData("my-clan", {
103
+ accountHash: "4519273648123",
104
+ mode: DataRequestMode.Snapshot,
105
+ seconds: 60,
106
+ switches: [StreamSwitch.StreamBank],
107
+ });
108
+ console.log(answer.items.map((item) => item.event));
109
+ } catch (error) {
110
+ if (error instanceof DataRequestDeclined) console.log("The member declined the request in the game.");
111
+ else throw error;
112
+ }
113
+ ```
114
+
115
+ The other outcomes are `DataRequestNotConnected`, `DataRequestPluginOutdated`, `DataRequestBusy` and `DataRequestFailed`.
116
+
117
+ ## ClanSocket events
118
+
119
+ Each ClanSocket event has a typed data model, such as `LevelUpEvent` or `LootEvent`. The `type` of the data names its model, so a check of `frame.data.type` narrows it.
120
+
121
+ The clan's live stream needs the clan token. It ends when the service closes it, and a close other than a normal one throws `StreamClosed`.
122
+
123
+ ```ts EXAMPLE: read the clan's live stream
124
+ for await (const frame of owner.streamEvents("my-clan", { events: [ClanSocketEvent.Loot] })) {
125
+ if (frame.data.type === ClanSocketEvent.Loot) console.log(frame.data.source, frame.data.items);
126
+ }
127
+ ```
128
+
129
+ The stream opens a `WebSocket` with an `Authorization` header, which Bun supports. Give `webSocket` to `createClient` to open the socket another way.
130
+
131
+ A JSON destination receives each batch of events as a signed webhook. `readDestinationBatch` checks the signature and the age of a batch with the destination's secret, then returns its events. A wrong signature throws `SignatureMismatch`.
132
+
133
+ ```ts EXAMPLE: read a signed destination batch
134
+ import { readDestinationBatch } from "@osrsclans/api";
135
+
136
+ const body = await request.text();
137
+ const batch = await readDestinationBatch(body, request.headers, process.env.OSRSCLANS_DESTINATION_SECRET ?? "");
138
+ for (const frame of batch.events) console.log(frame.event, frame.data);
139
+ ```
140
+
141
+ The types check each event at compile time only. The client does not check a value that a newer plugin sends.
142
+
143
+ ## Options
144
+
145
+ Make one client and use it for every call. Each option has a default, so give only the options you change:
146
+
147
+ | Option | Default | Use |
148
+ | --- | --- | --- |
149
+ | `baseUrl` | `https://osrsclans.cc` | Another address of the API |
150
+ | `clanToken` | none | A clan token for the Clan Owner API |
151
+ | `headers` | none | More headers for every request |
152
+ | `fetch` | the global `fetch` | Your own fetch, for a proxy or for tests |
153
+ | `webSocket` | the global `WebSocket` | Your own socket for the clan stream |
154
+
155
+ `createClient` also takes every other option of openapi-fetch's `createClient`, such as `querySerializer`.
156
+
157
+ ## Reference
158
+
159
+ - Public API: https://osrsclans.cc/docs/public
160
+ - Clan Owner API: https://osrsclans.cc/docs/clan-owner
161
+
162
+ The site limits how many requests one address can send. Spread a large read over time, and keep an answer you already have.
163
+
164
+ ## Licence
165
+
166
+ MIT. The API's data includes material from Old School RuneScape, which belongs to Jagex Ltd.
@@ -0,0 +1,17 @@
1
+ import { ApiError } from "./api-error.js";
2
+ import { UnexpectedStatus } from "./unexpected-status.js";
3
+ /** What openapi-fetch hands back: the parsed answer on a success, the parsed error body otherwise. */
4
+ interface Outcome<T> {
5
+ data?: T;
6
+ error?: unknown;
7
+ response: Response;
8
+ }
9
+ /** The error of an answer that is not a success: the class of its problem code, or `ApiError`. */
10
+ export declare const refusal: (response: Response, body: unknown) => ApiError | UnexpectedStatus;
11
+ /** The answer of a call, or its refusal thrown. A success with no body throws `UnexpectedStatus`. */
12
+ export declare const answered: <T>(pending: Promise<Outcome<T>>) => Promise<T>;
13
+ /** Nothing for a call that answers with no body, or its refusal thrown. */
14
+ export declare const finished: (pending: Promise<Outcome<unknown>>) => Promise<void>;
15
+ /** A multipart body as form data: a `Blob` as a file part, and every other value as text. */
16
+ export declare const formData: (body: unknown) => FormData;
17
+ export {};
@@ -0,0 +1,52 @@
1
+ import { ApiError } from "./api-error.js";
2
+ import { PROBLEM_ERRORS } from "./errors.generated.js";
3
+ import { UnexpectedStatus } from "./unexpected-status.js";
4
+ const KNOWN_REFUSALS = PROBLEM_ERRORS;
5
+ const isProblem = function isProblem(body) {
6
+ return typeof body === "object" && body !== null && typeof Reflect.get(body, "code") === "string";
7
+ };
8
+ /** The error of an answer that is not a success: the class of its problem code, or `ApiError`. */
9
+ export const refusal = function refusal(response, body) {
10
+ if (response.status < 400) {
11
+ return new UnexpectedStatus(response.status);
12
+ }
13
+ if (!isProblem(body)) {
14
+ return new ApiError(response.status, undefined, body);
15
+ }
16
+ return new (KNOWN_REFUSALS[body.code] ?? ApiError)(response.status, body, body);
17
+ };
18
+ /** The answer of a call, or its refusal thrown. A success with no body throws `UnexpectedStatus`. */
19
+ export const answered = async function answered(pending) {
20
+ const { data, error, response } = await pending;
21
+ if (!response.ok) {
22
+ throw refusal(response, error);
23
+ }
24
+ if (data === undefined) {
25
+ throw new UnexpectedStatus(response.status);
26
+ }
27
+ return data;
28
+ };
29
+ /** Nothing for a call that answers with no body, or its refusal thrown. */
30
+ export const finished = async function finished(pending) {
31
+ const { error, response } = await pending;
32
+ if (!response.ok) {
33
+ throw refusal(response, error);
34
+ }
35
+ };
36
+ const formText = function formText(value) {
37
+ return typeof value === "string" ? value : JSON.stringify(value);
38
+ };
39
+ /** A multipart body as form data: a `Blob` as a file part, and every other value as text. */
40
+ export const formData = function formData(body) {
41
+ const form = new FormData();
42
+ if (typeof body !== "object" || body === null) {
43
+ return form;
44
+ }
45
+ for (const name of Object.keys(body)) {
46
+ const value = Reflect.get(body, name);
47
+ if (value !== undefined && value !== null) {
48
+ form.append(name, value instanceof Blob ? value : formText(value));
49
+ }
50
+ }
51
+ return form;
52
+ };
@@ -0,0 +1,13 @@
1
+ import type { Problem } from "./models.generated.js";
2
+ /**
3
+ * The API refused the request. `status` is the HTTP status, `problem` the parsed problem body, or
4
+ * `undefined` when the API answers with another body, and `body` the body as the API sent it.
5
+ * A refusal throws the class of its problem code, such as `ClanNotFoundError`, and each one is an
6
+ * `ApiError`.
7
+ */
8
+ export declare class ApiError extends Error {
9
+ readonly status: number;
10
+ readonly problem: Problem | undefined;
11
+ readonly body: unknown;
12
+ constructor(status: number, problem: Problem | undefined, body: unknown);
13
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The API refused the request. `status` is the HTTP status, `problem` the parsed problem body, or
3
+ * `undefined` when the API answers with another body, and `body` the body as the API sent it.
4
+ * A refusal throws the class of its problem code, such as `ClanNotFoundError`, and each one is an
5
+ * `ApiError`.
6
+ */
7
+ export class ApiError extends Error {
8
+ status;
9
+ problem;
10
+ body;
11
+ constructor(status, problem, body) {
12
+ super(problem === undefined ? `${status} ${String(body)}` : `${status} ${problem.code}: ${problem.detail}`);
13
+ this.name = new.target.name;
14
+ this.status = status;
15
+ this.problem = problem;
16
+ this.body = body;
17
+ }
18
+ }
@@ -0,0 +1,37 @@
1
+ import type { ClanDetailOut, ClanReviewsOut, DataAnswerOut, DataRequestAsk, RosterMemberOut } from "./models.generated.js";
2
+ import type { NamedOperations } from "./operations.generated.js";
3
+ import type { QueryParams } from "./operation-types.js";
4
+ import type { components } from "./schema.generated.js";
5
+ type Schemas = components["schemas"];
6
+ type ItemMatches = Schemas["NameMatches_ItemOut_"];
7
+ type NpcMatches = Schemas["NameMatches_NpcOut_"];
8
+ type SpriteMatches = Schemas["NameMatches_SpriteOut_"];
9
+ type ClanPostPage = Schemas["Paginated_ClanPostOut_"];
10
+ type LookupQuery<P extends "/api/v1/osrs/items/lookup" | "/api/v1/osrs/npcs/lookup" | "/api/v1/osrs/sprites/lookup"> = Omit<QueryParams<P, "get">, "name">;
11
+ /** The API takes at most this many names in one by-name lookup. */
12
+ export declare const LOOKUP_NAMES_MOST = 50;
13
+ /** A clan, its first page of posts and of reviews, and its roster where asked for. */
14
+ export interface ClanProfile {
15
+ clan: ClanDetailOut;
16
+ posts: ClanPostPage;
17
+ reviews: ClanReviewsOut;
18
+ roster: RosterMemberOut[] | null;
19
+ }
20
+ /** The functions that chain routes callers often call together. */
21
+ export interface NamedChains {
22
+ /** A clan, its first page of posts and of reviews, and its roster with `roster: true`, read at once. The roster needs the clan's token. */
23
+ getClanProfile: (slug: string, options?: {
24
+ roster?: boolean;
25
+ }) => Promise<ClanProfile>;
26
+ /** Any number of items by exact name, in batches the API takes, keyed by the name as given. */
27
+ lookupItemsByName: (names: readonly string[], query?: LookupQuery<"/api/v1/osrs/items/lookup">) => Promise<Map<string, ItemMatches>>;
28
+ /** Any number of NPCs by exact name, in batches the API takes, keyed by the name as given. */
29
+ lookupNpcsByName: (names: readonly string[], query?: LookupQuery<"/api/v1/osrs/npcs/lookup">) => Promise<Map<string, NpcMatches>>;
30
+ /** Any number of sprites by exact name, in batches the API takes, keyed by the name as given. */
31
+ lookupSpritesByName: (names: readonly string[], query?: LookupQuery<"/api/v1/osrs/sprites/lookup">) => Promise<Map<string, SpriteMatches>>;
32
+ /** Ask one member's plugin for data and wait for the outcome. It returns the data, and any other outcome throws its `DataRequestError` class. It needs the clan's token. */
33
+ requestClanData: (slug: string, ask: DataRequestAsk) => Promise<DataAnswerOut>;
34
+ }
35
+ /** The chained functions over one client's named operations. */
36
+ export declare const namedChains: (operations: NamedOperations) => NamedChains;
37
+ export {};
package/dist/chains.js ADDED
@@ -0,0 +1,30 @@
1
+ import { settledAnswer } from "./data-requests.js";
2
+ /** The API takes at most this many names in one by-name lookup. */
3
+ export const LOOKUP_NAMES_MOST = 50;
4
+ const nameBatches = function nameBatches(names) {
5
+ const unique = [...new Set(names)];
6
+ return Array.from({ length: Math.ceil(unique.length / LOOKUP_NAMES_MOST) }, (_, index) => unique.slice(index * LOOKUP_NAMES_MOST, (index + 1) * LOOKUP_NAMES_MOST));
7
+ };
8
+ const byName = async function byName(names, lookup) {
9
+ const answers = await Promise.all(nameBatches(names).map(lookup));
10
+ return new Map(answers.flat().map((named) => [named.name, named]));
11
+ };
12
+ /** The chained functions over one client's named operations. */
13
+ export const namedChains = function namedChains(operations) {
14
+ const settle = async (slug, request) => settledAnswer(request) ?? settle(slug, await operations.getClansocketDataRequest(slug, request.id));
15
+ return {
16
+ getClanProfile: async (slug, { roster = false } = {}) => {
17
+ const [clan, posts, reviews, members] = await Promise.all([
18
+ operations.getClan(slug),
19
+ operations.listClanPosts(slug),
20
+ operations.listClanReviews(slug),
21
+ roster ? operations.getRoster(slug) : null,
22
+ ]);
23
+ return { clan, posts, reviews, roster: members };
24
+ },
25
+ lookupItemsByName: async (names, query = {}) => byName(names, async (name) => operations.lookupItems({ ...query, name })),
26
+ lookupNpcsByName: async (names, query = {}) => byName(names, async (name) => operations.lookupNpcs({ ...query, name })),
27
+ lookupSpritesByName: async (names, query = {}) => byName(names, async (name) => operations.lookupSprites({ ...query, name })),
28
+ requestClanData: async (slug, ask) => settle(slug, await operations.createClansocketDataRequest(slug, { body: ask })),
29
+ };
30
+ };
@@ -0,0 +1,24 @@
1
+ import { type NamedChains } from "./chains.js";
2
+ import { type NamedOperations } from "./operations.generated.js";
3
+ import { type NamedWalkers } from "./walkers.generated.js";
4
+ import { type StreamOptions, type WebSocketFactory } from "./streams.js";
5
+ import { type ClientOptions as FetchClientOptions } from "openapi-fetch";
6
+ import type { ClanSocketEventFrame } from "./models.generated.js";
7
+ /** The production API. */
8
+ export declare const DEFAULT_BASE_URL = "https://osrsclans.cc";
9
+ export type ClientOptions = FetchClientOptions & {
10
+ /** A clan token for the Clan Owner API, sent as a bearer token. */
11
+ clanToken?: string;
12
+ /** Opens the clan stream's WebSocket. The global `WebSocket` with a `headers` option when left out. */
13
+ webSocket?: WebSocketFactory;
14
+ };
15
+ /**
16
+ * One function per route, one walker per paged route (`iterClans` and the rest), the methods that
17
+ * chain routes often called together, and the clan's live stream.
18
+ */
19
+ export type OsrsClansClient = NamedChains & NamedOperations & NamedWalkers & {
20
+ /** The clan's live stream of ClanSocket events. It needs the clan's token. */
21
+ streamEvents: (slug: string, options?: StreamOptions) => AsyncIterableIterator<ClanSocketEventFrame, null>;
22
+ };
23
+ /** One client to make once and reuse. Each option has a default, so pass only the options you change. */
24
+ export declare const createClient: ({ clanToken, headers, webSocket, ...options }?: ClientOptions) => OsrsClansClient;
package/dist/client.js ADDED
@@ -0,0 +1,25 @@
1
+ import { namedChains } from "./chains.js";
2
+ import { namedOperations } from "./operations.generated.js";
3
+ import { namedWalkers } from "./walkers.generated.js";
4
+ import { headeredWebSocket, streamEvents, streamUrl } from "./streams.js";
5
+ import createFetchClient, { mergeHeaders } from "openapi-fetch";
6
+ /** The production API. */
7
+ export const DEFAULT_BASE_URL = "https://osrsclans.cc";
8
+ const AUTHORIZATION = "Authorization";
9
+ const bearerOf = function bearerOf(clanToken) {
10
+ return clanToken === undefined || clanToken === "" ? {} : Object.fromEntries([[AUTHORIZATION, `Bearer ${clanToken}`]]);
11
+ };
12
+ /** One client to make once and reuse. Each option has a default, so pass only the options you change. */
13
+ export const createClient = function createClient({ clanToken, headers, webSocket, ...options } = {}) {
14
+ const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
15
+ const bearer = bearerOf(clanToken);
16
+ const core = createFetchClient({ ...options, baseUrl, headers: mergeHeaders(headers, bearer) });
17
+ const open = webSocket ?? headeredWebSocket;
18
+ const operations = namedOperations(core);
19
+ return {
20
+ ...operations,
21
+ ...namedWalkers(operations),
22
+ ...namedChains(operations),
23
+ streamEvents: (slug, stream) => streamEvents(() => open(streamUrl(baseUrl, slug), { ...bearer }), stream),
24
+ };
25
+ };
@@ -0,0 +1,9 @@
1
+ import type { DataRequestOut } from "./models.generated.js";
2
+ /**
3
+ * A data request ended without the member's data. `request` is the request, with its status. Each
4
+ * outcome other than data throws its own subclass, such as `DataRequestDeclined`.
5
+ */
6
+ export declare class DataRequestError extends Error {
7
+ readonly request: DataRequestOut;
8
+ constructor(request: DataRequestOut);
9
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * A data request ended without the member's data. `request` is the request, with its status. Each
3
+ * outcome other than data throws its own subclass, such as `DataRequestDeclined`.
4
+ */
5
+ export class DataRequestError extends Error {
6
+ request;
7
+ constructor(request) {
8
+ super(request.detail === null ? request.status : `${request.status}: ${request.detail}`);
9
+ this.name = new.target.name;
10
+ this.request = request;
11
+ }
12
+ }
@@ -0,0 +1,6 @@
1
+ import type { DataAnswerOut, DataRequestOut } from "./models.generated.js";
2
+ /**
3
+ * The member's data, or `null` while the request is pending. Any other outcome throws its class, and
4
+ * a `data` outcome that carries no data throws `DataRequestFailed`.
5
+ */
6
+ export declare const settledAnswer: (request: DataRequestOut) => DataAnswerOut | null;
@@ -0,0 +1,16 @@
1
+ import { DataRequestStatus } from "./schema.generated.js";
2
+ import { OUTCOME_ERRORS } from "./outcomes.generated.js";
3
+ /**
4
+ * The member's data, or `null` while the request is pending. Any other outcome throws its class, and
5
+ * a `data` outcome that carries no data throws `DataRequestFailed`.
6
+ */
7
+ export const settledAnswer = function settledAnswer(request) {
8
+ if (request.status === DataRequestStatus.Pending) {
9
+ return null;
10
+ }
11
+ if (request.status === DataRequestStatus.Data && request.data !== null) {
12
+ return request.data;
13
+ }
14
+ const outcome = request.status === DataRequestStatus.Data ? DataRequestStatus.Failed : request.status;
15
+ throw new OUTCOME_ERRORS[outcome](request);
16
+ };
@@ -0,0 +1,23 @@
1
+ import type { DestinationBatch } from "./models.generated.js";
2
+ export declare const DELIVERY_HEADER = "X-OSRSClans-Delivery";
3
+ export declare const TIMESTAMP_HEADER = "X-OSRSClans-Timestamp";
4
+ export declare const SIGNATURE_HEADER = "X-OSRSClans-Signature";
5
+ export declare const TOLERANCE_SECONDS = 300;
6
+ /** The batch is not signed with the destination's secret, or it was signed too long ago. */
7
+ export declare class SignatureMismatch extends Error {
8
+ constructor(message: string);
9
+ }
10
+ export interface BatchCheck {
11
+ /** The most seconds between the signature and `now`. 300 when left out. */
12
+ toleranceSeconds?: number;
13
+ /** The time to check against, in unix seconds. The clock when left out. */
14
+ now?: number;
15
+ }
16
+ /** The signature header value of one body sent at one unix second. */
17
+ export declare const batchSignature: (secret: string, timestamp: number, body: Uint8Array | string) => Promise<string>;
18
+ /**
19
+ * The events of one batch a JSON destination receives, after its signature and its age are checked.
20
+ * `body` is the raw request body, before any parse, and `secret` the destination's secret. A wrong
21
+ * signature, or one older than the tolerance, throws `SignatureMismatch`.
22
+ */
23
+ export declare const readDestinationBatch: (body: Uint8Array | string, headers: Headers | Record<string, string>, secret: string, { toleranceSeconds, now }?: BatchCheck) => Promise<DestinationBatch>;
@@ -0,0 +1,74 @@
1
+ export const DELIVERY_HEADER = "X-OSRSClans-Delivery";
2
+ export const TIMESTAMP_HEADER = "X-OSRSClans-Timestamp";
3
+ export const SIGNATURE_HEADER = "X-OSRSClans-Signature";
4
+ export const TOLERANCE_SECONDS = 300;
5
+ const SCHEME = "sha256=";
6
+ /** The batch is not signed with the destination's secret, or it was signed too long ago. */
7
+ export class SignatureMismatch extends Error {
8
+ constructor(message) {
9
+ super(message);
10
+ this.name = "SignatureMismatch";
11
+ }
12
+ }
13
+ const bytesOf = function bytesOf(body) {
14
+ return typeof body === "string" ? new TextEncoder().encode(body) : body;
15
+ };
16
+ const hex = function hex(bytes) {
17
+ return [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
18
+ };
19
+ /** The signature header value of one body sent at one unix second. */
20
+ export const batchSignature = async function batchSignature(secret, timestamp, body) {
21
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { hash: "SHA-256", name: "HMAC" }, false, ["sign"]);
22
+ const stamp = new TextEncoder().encode(`${timestamp}.`);
23
+ const signed = new Uint8Array([...stamp, ...bytesOf(body)]);
24
+ return SCHEME + hex(await crypto.subtle.sign("HMAC", key, signed));
25
+ };
26
+ const sameText = function sameText(left, right) {
27
+ let differs = left.length ^ right.length;
28
+ for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
29
+ differs |= left.charCodeAt(index) ^ right.charCodeAt(index);
30
+ }
31
+ return differs === 0;
32
+ };
33
+ const headerOf = function headerOf(headers, name) {
34
+ const found = headers instanceof Headers
35
+ ? headers.get(name)
36
+ : Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
37
+ if (found === null || found === undefined) {
38
+ throw new SignatureMismatch(`the batch carries no ${name} header`);
39
+ }
40
+ return found;
41
+ };
42
+ const isUnixSecond = function isUnixSecond(stamp) {
43
+ const zero = "0".charCodeAt(0);
44
+ const nine = "9".charCodeAt(0);
45
+ return stamp.length > 0 && Array.from({ length: stamp.length }, (_, index) => stamp.charCodeAt(index)).every((code) => code >= zero && code <= nine);
46
+ };
47
+ const isBatch = function isBatch(value) {
48
+ return typeof value === "object" && value !== null && Array.isArray(Reflect.get(value, "events"));
49
+ };
50
+ /**
51
+ * The events of one batch a JSON destination receives, after its signature and its age are checked.
52
+ * `body` is the raw request body, before any parse, and `secret` the destination's secret. A wrong
53
+ * signature, or one older than the tolerance, throws `SignatureMismatch`.
54
+ */
55
+ export const readDestinationBatch = async function readDestinationBatch(body, headers, secret, { toleranceSeconds = TOLERANCE_SECONDS, now = Date.now() / 1000 } = {}) {
56
+ const stamp = headerOf(headers, TIMESTAMP_HEADER);
57
+ if (!isUnixSecond(stamp)) {
58
+ throw new SignatureMismatch(`${TIMESTAMP_HEADER} is not a unix second`);
59
+ }
60
+ const timestamp = Number(stamp);
61
+ if (Math.abs(now - timestamp) > toleranceSeconds) {
62
+ throw new SignatureMismatch("the batch was signed too long ago");
63
+ }
64
+ const expected = await batchSignature(secret, timestamp, body);
65
+ if (!sameText(headerOf(headers, SIGNATURE_HEADER), expected)) {
66
+ throw new SignatureMismatch("the signature does not match the destination's secret");
67
+ }
68
+ const text = typeof body === "string" ? body : new TextDecoder().decode(body);
69
+ const parsed = JSON.parse(text);
70
+ if (!isBatch(parsed)) {
71
+ throw new TypeError("the signed batch has no events list");
72
+ }
73
+ return parsed;
74
+ };