@caisual/kit 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 (3) hide show
  1. package/dist/kit.d.ts +71 -0
  2. package/dist/kit.js +414 -0
  3. package/package.json +25 -0
package/dist/kit.d.ts ADDED
@@ -0,0 +1,71 @@
1
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
2
+ [key: string]: JsonValue;
3
+ };
4
+ export interface Player {
5
+ id: string;
6
+ name: string;
7
+ guest: boolean;
8
+ }
9
+ export interface SaveInfo {
10
+ key: string;
11
+ bytes: number;
12
+ updatedAt: number;
13
+ }
14
+ export interface BoardEntry {
15
+ rank: number;
16
+ name: string;
17
+ score: number;
18
+ guest: boolean;
19
+ me: boolean;
20
+ }
21
+ export interface BoardTop {
22
+ day: string | null;
23
+ entries: BoardEntry[];
24
+ me: {
25
+ rank: number;
26
+ score: number;
27
+ } | null;
28
+ }
29
+ export type BoardResult = {
30
+ accepted: true;
31
+ best: number;
32
+ rank: number;
33
+ day: string | null;
34
+ };
35
+ export type BoardOffline = {
36
+ accepted: false;
37
+ reason: 'offline';
38
+ };
39
+ export interface CaisualConnection {
40
+ connected: boolean;
41
+ player: Player;
42
+ daily: {
43
+ day: string;
44
+ seed: number;
45
+ random(): number;
46
+ };
47
+ time: {
48
+ now(): number;
49
+ };
50
+ save: {
51
+ set(key: string, value: JsonValue): Promise<SaveInfo>;
52
+ get(key: string): Promise<JsonValue | null>;
53
+ remove(key: string): Promise<void>;
54
+ list(): Promise<SaveInfo[]>;
55
+ };
56
+ board: {
57
+ submit(board: string, score: number, options?: {
58
+ daily?: boolean;
59
+ }): Promise<BoardResult | BoardOffline>;
60
+ top(board: string, options?: {
61
+ daily?: boolean;
62
+ limit?: number;
63
+ guests?: boolean;
64
+ }): Promise<BoardTop>;
65
+ };
66
+ }
67
+ export interface Caisual {
68
+ connect(): Promise<CaisualConnection>;
69
+ }
70
+ export declare const caisual: Caisual;
71
+ export default caisual;
package/dist/kit.js ADDED
@@ -0,0 +1,414 @@
1
+ // Caisual game kit v0.1.0
2
+
3
+ // src/errors.ts
4
+ function creaErrore(code, message) {
5
+ return Object.assign(new Error(message), { name: "CaisualError", code });
6
+ }
7
+ function erroreOffline() {
8
+ return creaErrore("offline", "Caisual services are unavailable.");
9
+ }
10
+ function codiceErrore(valore) {
11
+ return typeof valore === "object" && valore !== null && "code" in valore ? valore.code : null;
12
+ }
13
+
14
+ // src/api.ts
15
+ async function leggiJson(response) {
16
+ try {
17
+ return await response.json();
18
+ } catch {
19
+ throw creaErrore("internal_error", "The service returned an invalid response.");
20
+ }
21
+ }
22
+ async function leggiErrore(response) {
23
+ let corpo = {};
24
+ try {
25
+ corpo = await response.json();
26
+ } catch {
27
+ }
28
+ const code = typeof corpo.error?.code === "string" ? corpo.error.code : response.status === 401 ? "invalid_ticket" : "internal_error";
29
+ const message = typeof corpo.error?.message === "string" ? corpo.error.message : `The request failed with status ${response.status}.`;
30
+ return creaErrore(code, message);
31
+ }
32
+ function creaClienteApi(appOrigin, fetcher, biglietto) {
33
+ async function manda(path, metodo, ticket, corpo) {
34
+ const headers = new Headers({ Authorization: `Bearer ${ticket}` });
35
+ let body;
36
+ if (corpo !== void 0) {
37
+ headers.set("Content-Type", "application/json");
38
+ try {
39
+ body = JSON.stringify(corpo);
40
+ } catch {
41
+ throw creaErrore("invalid_request", "The value must be valid JSON.");
42
+ }
43
+ }
44
+ try {
45
+ return await fetcher(new URL(`/api/kit${path}`, appOrigin), {
46
+ method: metodo,
47
+ headers,
48
+ body,
49
+ credentials: "omit"
50
+ });
51
+ } catch {
52
+ throw erroreOffline();
53
+ }
54
+ }
55
+ async function richiesta(path, metodo, corpo) {
56
+ let ticket;
57
+ try {
58
+ ticket = await biglietto.ottieni();
59
+ } catch {
60
+ throw erroreOffline();
61
+ }
62
+ let response = await manda(path, metodo, ticket, corpo);
63
+ if (response.status === 401) {
64
+ try {
65
+ ticket = await biglietto.rinnova();
66
+ } catch {
67
+ throw erroreOffline();
68
+ }
69
+ response = await manda(path, metodo, ticket, corpo);
70
+ }
71
+ if (!response.ok) throw await leggiErrore(response);
72
+ return leggiJson(response);
73
+ }
74
+ return {
75
+ me: () => richiesta("/me", "GET"),
76
+ saveSet: (key, value) => richiesta(`/saves/${encodeURIComponent(key)}`, "PUT", { value }),
77
+ async saveGet(key) {
78
+ try {
79
+ return (await richiesta(`/saves/${encodeURIComponent(key)}`, "GET")).value;
80
+ } catch (errore) {
81
+ if (codiceErrore(errore) === "not_found") return null;
82
+ throw errore;
83
+ }
84
+ },
85
+ async saveRemove(key) {
86
+ await richiesta(`/saves/${encodeURIComponent(key)}`, "DELETE");
87
+ },
88
+ async saveList() {
89
+ return (await richiesta("/saves", "GET")).saves;
90
+ },
91
+ async boardSubmit(board, score, daily) {
92
+ const risultato = await richiesta("/scores", "POST", { board, score, daily });
93
+ return { accepted: true, best: risultato.best, rank: risultato.rank, day: risultato.day };
94
+ },
95
+ async boardTop(board, opzioni) {
96
+ const query = new URLSearchParams();
97
+ if (opzioni.daily) query.set("daily", "1");
98
+ if (opzioni.limit !== void 0) query.set("limit", String(opzioni.limit));
99
+ if (opzioni.guests) query.set("guests", "1");
100
+ const suffisso = query.size === 0 ? "" : `?${query.toString()}`;
101
+ const { day, entries, me } = await richiesta(
102
+ `/scores/${encodeURIComponent(board)}${suffisso}`,
103
+ "GET"
104
+ );
105
+ return { day, entries, me };
106
+ }
107
+ };
108
+ }
109
+
110
+ // src/daily.ts
111
+ var DIVISORE_UINT32 = 4294967296;
112
+ function giornoUtc(ora) {
113
+ return new Date(ora).toISOString().slice(0, 10);
114
+ }
115
+ async function calcolaSeed(gioco, giorno, subtle) {
116
+ const dati = new TextEncoder().encode(`caisual:${gioco}:${giorno}`);
117
+ const digest = new Uint8Array(await subtle.digest("SHA-256", dati));
118
+ return (digest[0] ?? 0) * 16777216 + ((digest[1] ?? 0) << 16) + ((digest[2] ?? 0) << 8) + (digest[3] ?? 0) >>> 0;
119
+ }
120
+ function creaMulberry32(seed) {
121
+ let stato = seed >>> 0;
122
+ return () => {
123
+ stato = stato + 1831565813 >>> 0;
124
+ let valore = stato;
125
+ valore = Math.imul(valore ^ valore >>> 15, valore | 1);
126
+ valore ^= valore + Math.imul(valore ^ valore >>> 7, valore | 61);
127
+ return ((valore ^ valore >>> 14) >>> 0) / DIVISORE_UINT32;
128
+ };
129
+ }
130
+
131
+ // src/handshake.ts
132
+ function record(valore) {
133
+ return typeof valore === "object" && valore !== null && !Array.isArray(valore) ? valore : null;
134
+ }
135
+ function eTipo(valore, tipo) {
136
+ return record(valore)?.type === tipo;
137
+ }
138
+ function attendiHandshake(finestra, appOrigin, timeoutMs = 3e3) {
139
+ return new Promise((resolve) => {
140
+ let concluso = false;
141
+ const termina = (esito) => {
142
+ if (concluso) return;
143
+ concluso = true;
144
+ finestra.removeEventListener("message", ascolta);
145
+ finestra.clearTimeout(scadenza);
146
+ resolve(esito);
147
+ };
148
+ const segnalaPronto = () => {
149
+ finestra.parent.postMessage({ type: "caisual:ready" }, appOrigin);
150
+ };
151
+ const ascolta = (evento) => {
152
+ if (evento.origin !== appOrigin || evento.source !== finestra.parent) return;
153
+ if (eTipo(evento.data, "caisual:ready?")) {
154
+ segnalaPronto();
155
+ return;
156
+ }
157
+ if (!eTipo(evento.data, "caisual:hello")) return;
158
+ const dati = record(evento.data);
159
+ const porta = evento.ports[0];
160
+ if (typeof dati?.ticket !== "string" || porta === void 0) return;
161
+ porta.start();
162
+ termina({ ticket: dati.ticket, porta });
163
+ };
164
+ finestra.addEventListener("message", ascolta);
165
+ const scadenza = finestra.setTimeout(() => termina(null), timeoutMs);
166
+ segnalaPronto();
167
+ });
168
+ }
169
+ function scadenzaJwt(ticket) {
170
+ const parte = ticket.split(".")[1];
171
+ if (parte === void 0) return null;
172
+ const base64 = parte.replace(/-/g, "+").replace(/_/g, "/").padEnd(
173
+ Math.ceil(parte.length / 4) * 4,
174
+ "="
175
+ );
176
+ try {
177
+ const payload = record(JSON.parse(globalThis.atob(base64)));
178
+ return typeof payload?.exp === "number" && Number.isFinite(payload.exp) ? payload.exp * 1e3 : null;
179
+ } catch {
180
+ return null;
181
+ }
182
+ }
183
+ function chiediBiglietto(porta, finestra, timeoutMs) {
184
+ return new Promise((resolve, reject) => {
185
+ let concluso = false;
186
+ const termina = (ticket) => {
187
+ if (concluso) return;
188
+ concluso = true;
189
+ porta.removeEventListener("message", ascolta);
190
+ finestra.clearTimeout(scadenza);
191
+ if (ticket === null) reject(new Error("Ticket refresh timed out."));
192
+ else resolve(ticket);
193
+ };
194
+ const ascolta = (evento) => {
195
+ const dati = record(evento.data);
196
+ if (dati?.type === "caisual:ticket" && typeof dati.ticket === "string") {
197
+ termina(dati.ticket);
198
+ }
199
+ };
200
+ porta.addEventListener("message", ascolta);
201
+ const scadenza = finestra.setTimeout(() => termina(null), timeoutMs);
202
+ try {
203
+ porta.postMessage({ type: "caisual:ticket" });
204
+ } catch {
205
+ termina(null);
206
+ }
207
+ });
208
+ }
209
+ function creaGestoreBiglietto(ticketIniziale, porta, finestra, ora, timeoutMs = 3e3) {
210
+ let ticket = ticketIniziale;
211
+ let rinnovo = null;
212
+ const rinnova = () => {
213
+ if (rinnovo !== null) return rinnovo;
214
+ const richiesta = chiediBiglietto(porta, finestra, timeoutMs).then((nuovo) => {
215
+ ticket = nuovo;
216
+ return nuovo;
217
+ });
218
+ const completa = richiesta.finally(() => {
219
+ if (rinnovo === completa) rinnovo = null;
220
+ });
221
+ rinnovo = completa;
222
+ return completa;
223
+ };
224
+ return {
225
+ async ottieni() {
226
+ const scadenza = scadenzaJwt(ticket);
227
+ return scadenza !== null && scadenza - ora() < 3e4 ? rinnova() : ticket;
228
+ },
229
+ rinnova
230
+ };
231
+ }
232
+
233
+ // src/standalone.ts
234
+ var PREFISSO = "caisual:save:";
235
+ var CHIAVE_VALIDA = /^[a-z0-9][a-z0-9_-]{0,31}$/;
236
+ function verificaChiave(key) {
237
+ if (!CHIAVE_VALIDA.test(key)) {
238
+ throw creaErrore("invalid_request", "Save keys must use lowercase letters, numbers, underscores, or hyphens.");
239
+ }
240
+ }
241
+ function leggiSalvataggio(testo) {
242
+ if (testo === null) return null;
243
+ try {
244
+ return JSON.parse(testo);
245
+ } catch {
246
+ return null;
247
+ }
248
+ }
249
+ function chiavi(archivio) {
250
+ const risultato = [];
251
+ for (let indice = 0; indice < archivio.length; indice++) {
252
+ const key = archivio.key(indice);
253
+ if (key?.startsWith(PREFISSO)) risultato.push(key.slice(PREFISSO.length));
254
+ }
255
+ return risultato;
256
+ }
257
+ function creaSave(archivio, ora) {
258
+ const disponibile = () => {
259
+ if (archivio === null) throw erroreOffline();
260
+ return archivio;
261
+ };
262
+ return {
263
+ async set(key, value) {
264
+ verificaChiave(key);
265
+ const locale = disponibile();
266
+ const corpo = JSON.stringify({ value });
267
+ const bytes = new TextEncoder().encode(corpo).byteLength;
268
+ if (bytes > 262144) {
269
+ throw creaErrore("payload_too_large", "The save is larger than 262144 bytes.");
270
+ }
271
+ if (locale.getItem(PREFISSO + key) === null && chiavi(locale).length >= 32) {
272
+ throw creaErrore("save_limit", "A game can store at most 32 save keys.");
273
+ }
274
+ const voce = { value, bytes, updatedAt: ora() };
275
+ locale.setItem(PREFISSO + key, JSON.stringify(voce));
276
+ return { key, bytes, updatedAt: voce.updatedAt };
277
+ },
278
+ async get(key) {
279
+ verificaChiave(key);
280
+ return leggiSalvataggio(disponibile().getItem(PREFISSO + key))?.value ?? null;
281
+ },
282
+ async remove(key) {
283
+ verificaChiave(key);
284
+ disponibile().removeItem(PREFISSO + key);
285
+ },
286
+ async list() {
287
+ const locale = disponibile();
288
+ return chiavi(locale).flatMap((key) => {
289
+ const voce = leggiSalvataggio(locale.getItem(PREFISSO + key));
290
+ return voce === null ? [] : [{ key, bytes: voce.bytes, updatedAt: voce.updatedAt }];
291
+ }).sort((a, b) => a.key.localeCompare(b.key));
292
+ }
293
+ };
294
+ }
295
+ async function creaStandalone(input) {
296
+ const day = giornoUtc(input.ora());
297
+ const seed = await calcolaSeed(input.hostname, day, input.subtle);
298
+ return {
299
+ connected: false,
300
+ player: { id: "local", name: "Guest", guest: true },
301
+ daily: { day, seed, random: creaMulberry32(seed) },
302
+ time: { now: input.ora },
303
+ save: creaSave(input.archivio, input.ora),
304
+ board: {
305
+ async submit() {
306
+ return { accepted: false, reason: "offline" };
307
+ },
308
+ async top(_board, opzioni = {}) {
309
+ return { day: opzioni.daily ? day : null, entries: [], me: null };
310
+ }
311
+ }
312
+ };
313
+ }
314
+
315
+ // src/kit.ts
316
+ function leggiAppOrigin(documento) {
317
+ const valore = documento?.querySelector('meta[name="caisual-app"]')?.getAttribute("content");
318
+ if (valore === null || valore === void 0) return null;
319
+ try {
320
+ const url = new URL(valore);
321
+ return url.origin === valore && (url.protocol === "https:" || url.protocol === "http:") ? valore : null;
322
+ } catch {
323
+ return null;
324
+ }
325
+ }
326
+ function archivioReale() {
327
+ try {
328
+ return typeof localStorage === "undefined" ? null : localStorage;
329
+ } catch {
330
+ return null;
331
+ }
332
+ }
333
+ function dipendenzeReali() {
334
+ return {
335
+ finestra: typeof window === "undefined" ? null : window,
336
+ documento: typeof document === "undefined" ? null : document,
337
+ fetcher: (input, init) => globalThis.fetch(input, init),
338
+ archivio: archivioReale(),
339
+ hostname: typeof location === "undefined" ? "" : location.hostname,
340
+ subtle: globalThis.crypto.subtle,
341
+ ora: Date.now
342
+ };
343
+ }
344
+ async function connetti(input) {
345
+ const appOrigin = leggiAppOrigin(input.documento);
346
+ const senzaPadre = input.finestra === null || input.finestra.parent === input.finestra;
347
+ if (appOrigin === null || senzaPadre) {
348
+ return creaStandalone(input);
349
+ }
350
+ const handshake = await attendiHandshake(
351
+ input.finestra,
352
+ appOrigin,
353
+ input.timeoutHandshake
354
+ );
355
+ if (handshake === null) return creaStandalone(input);
356
+ const biglietto = creaGestoreBiglietto(
357
+ handshake.ticket,
358
+ handshake.porta,
359
+ input.finestra,
360
+ input.ora,
361
+ input.timeoutRinnovo
362
+ );
363
+ const api = creaClienteApi(appOrigin, input.fetcher, biglietto);
364
+ const prima = input.ora();
365
+ let me;
366
+ try {
367
+ me = await api.me();
368
+ } catch {
369
+ return creaStandalone(input);
370
+ }
371
+ const dopo = input.ora();
372
+ const scartoOrario = me.serverTime - (prima + dopo) / 2;
373
+ return {
374
+ connected: true,
375
+ player: me.player,
376
+ daily: { day: me.day, seed: me.seed, random: creaMulberry32(me.seed) },
377
+ time: { now: () => input.ora() + scartoOrario },
378
+ save: {
379
+ set: (key, value) => api.saveSet(key, value),
380
+ get: (key) => api.saveGet(key),
381
+ remove: (key) => api.saveRemove(key),
382
+ list: () => api.saveList()
383
+ },
384
+ board: {
385
+ async submit(board, score, opzioni = {}) {
386
+ try {
387
+ return await api.boardSubmit(board, score, opzioni.daily === true);
388
+ } catch (errore) {
389
+ if (typeof errore === "object" && errore !== null && "code" in errore && errore.code === "offline") return { accepted: false, reason: "offline" };
390
+ throw errore;
391
+ }
392
+ },
393
+ top: (board, opzioni = {}) => api.boardTop(board, opzioni)
394
+ }
395
+ };
396
+ }
397
+ function creaKit(input = dipendenzeReali()) {
398
+ let promessa = null;
399
+ return {
400
+ connect() {
401
+ promessa ?? (promessa = connetti(input));
402
+ return promessa;
403
+ }
404
+ };
405
+ }
406
+
407
+ // src/index.ts
408
+ var caisual = creaKit();
409
+ globalThis.caisual = caisual;
410
+ var index_default = caisual;
411
+ export {
412
+ caisual,
413
+ index_default as default
414
+ };
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "@caisual/kit",
3
+ "version": "0.1.0",
4
+ "description": "Browser kit for Caisual games",
5
+ "type": "module",
6
+ "files": [
7
+ "dist/kit.js",
8
+ "dist/kit.d.ts"
9
+ ],
10
+ "exports": {
11
+ ".": "./dist/kit.js"
12
+ },
13
+ "types": "./dist/kit.d.ts",
14
+ "scripts": {
15
+ "build": "node build.mjs",
16
+ "prepack": "pnpm build",
17
+ "typecheck": "tsc --noEmit",
18
+ "test": "vitest run"
19
+ },
20
+ "devDependencies": {
21
+ "esbuild": "^0.28.1",
22
+ "typescript": "^7.0.2",
23
+ "vitest": "^4.1.10"
24
+ }
25
+ }