@altenginenet/sdk 0.0.0-stage → 0.1.2
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 +21 -0
- package/README.md +429 -2
- package/dist/auth.cjs +312 -0
- package/dist/auth.cjs.map +1 -0
- package/dist/auth.d.cts +1 -0
- package/dist/auth.d.ts +1 -0
- package/dist/auth.js +11 -0
- package/dist/auth.js.map +1 -0
- package/dist/channel.cjs +249 -0
- package/dist/channel.cjs.map +1 -0
- package/dist/channel.d.cts +1 -0
- package/dist/channel.d.ts +1 -0
- package/dist/channel.js +7 -0
- package/dist/channel.js.map +1 -0
- package/dist/chunk-6Q4X4E7X.js +291 -0
- package/dist/chunk-6Q4X4E7X.js.map +1 -0
- package/dist/chunk-NAQQAMY7.js +225 -0
- package/dist/chunk-NAQQAMY7.js.map +1 -0
- package/dist/client-rCIrl668.d.cts +201 -0
- package/dist/client-rCIrl668.d.ts +201 -0
- package/dist/index.cjs +1974 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1951 -0
- package/dist/index.d.ts +1951 -0
- package/dist/index.js +1431 -0
- package/dist/index.js.map +1 -0
- package/dist/socket-DqIm8vll.d.cts +144 -0
- package/dist/socket-DqIm8vll.d.ts +144 -0
- package/examples/first-write.mjs +14 -0
- package/package.json +85 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/channel/socket.ts"],"sourcesContent":["/** ChannelSocket — the browser/edge WebSocket subscriber for altengine channels.\n *\n * Standalone and browser-safe: no API keys, no other SDK imports. Your backend\n * mints a subscriber token (`ChannelClient.createToken`) and hands the response\n * (`{token, ws_endpoint, protocols}`) to the page; the socket does the rest — connect, auto-reconnect with backoff,\n * token re-mint on reconnect, resubscribe, and keepalive pings.\n */\n\nimport type { ChannelMessage } from \"./types.js\";\n\nexport type SocketState = \"idle\" | \"connecting\" | \"open\" | \"reconnecting\" | \"closed\";\n\nexport interface SocketToken {\n token: string;\n /** Subscribe URL without the token, from the token response. */\n ws_endpoint?: string;\n /** Subprotocols that carry the token, from the token response. */\n protocols?: string[];\n /** @deprecated The subscribe URL with the token in its query string. Used only when the\n * response has no `ws_endpoint` (an older server). */\n ws_url?: string;\n}\n\n/** The subprotocol offered alongside the token, and the one the server answers with. */\nconst WS_PROTOCOL = \"altengine.v1\";\nconst WS_TOKEN_PROTOCOL_PREFIX = \"altengine.token.\";\n\nexport interface ChannelSocketOptions {\n /** Called before every connection attempt (including reconnects) so tokens are\n * always fresh. Return the token-mint response (or `{token}` with `url` set). */\n getToken: () => Promise<SocketToken> | SocketToken;\n /** Explicit subscribe URL (`wss://…/v1/channel/<instance>/subscribe`) when the token\n * response has no `ws_endpoint`. The token is sent as a subprotocol, not in the URL. */\n url?: string;\n /** Subset of the token's channels to subscribe on connect (default: all). */\n channels?: string[];\n /** WebSocket constructor for runtimes without a global one. */\n webSocket?: new (url: string, protocols?: string | string[]) => WebSocket;\n /** Keepalive ping interval in ms (default 30000, at most 60000). A silent\n * connection past ~1.5 intervals is treated as dead and reconnected. */\n pingIntervalMs?: number;\n /** Reconnect backoff base/cap in ms (defaults 250 / 30000). */\n backoffBaseMs?: number;\n backoffMaxMs?: number;\n}\n\nexport interface SocketEvents {\n message: ChannelMessage;\n state: SocketState;\n error: Error;\n /** Channels the server would not subscribe this socket to — on open or on a subscribe() —\n * because a channel or user limit was reached. They stay requested and are tried again on\n * the next reconnect. */\n refused: string[];\n}\n\ntype Listener<T> = (payload: T) => void;\n\n// readyState values, spelled out rather than read off the global `WebSocket`: Node 20 has no\n// global one (that is what the `webSocket` option is for), and `WebSocket.OPEN` there is a\n// ReferenceError the first time a connected socket is checked.\nconst CONNECTING = 0;\nconst OPEN = 1;\n\nexport class ChannelSocket {\n private readonly opts: ChannelSocketOptions;\n private readonly listeners: { [K in keyof SocketEvents]: Set<Listener<SocketEvents[K]>> } = {\n message: new Set(),\n state: new Set(),\n error: new Set(),\n refused: new Set(),\n };\n\n private ws?: WebSocket;\n private stateValue: SocketState = \"idle\";\n private desired = new Set<string>();\n private explicitChannels: boolean;\n private closedByUser = false;\n private attempts = 0;\n private pingTimer?: ReturnType<typeof setInterval>;\n private lastActivity = 0;\n private reconnectTimer?: ReturnType<typeof setTimeout>;\n private pendingSubscribes: { channels: string[]; resolve: (channels: string[]) => void; reject: (e: Error) => void }[] = [];\n private pendingPublishes: { resolve: (delivered: number) => void; reject: (e: Error) => void }[] = [];\n\n constructor(opts: ChannelSocketOptions) {\n this.opts = opts;\n this.explicitChannels = opts.channels !== undefined;\n for (const c of opts.channels ?? []) this.desired.add(c);\n }\n\n get state(): SocketState {\n return this.stateValue;\n }\n\n on<K extends keyof SocketEvents>(event: K, fn: Listener<SocketEvents[K]>): () => void {\n this.listeners[event].add(fn);\n return () => this.listeners[event].delete(fn);\n }\n\n private emit<K extends keyof SocketEvents>(event: K, payload: SocketEvents[K]): void {\n for (const fn of this.listeners[event]) fn(payload);\n }\n\n private setState(s: SocketState): void {\n if (this.stateValue === s) return;\n this.stateValue = s;\n this.emit(\"state\", s);\n }\n\n /** Connect (resolves once the socket is open). Reconnects automatically until\n * `close()` is called. */\n async connect(): Promise<void> {\n this.closedByUser = false;\n if (this.ws && (this.ws.readyState === OPEN || this.ws.readyState === CONNECTING)) return;\n await this.dial();\n }\n\n /** Stop reconnecting and close the connection. */\n close(): void {\n this.closedByUser = true;\n if (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n this.stopPing();\n this.failPending(new Error(\"socket closed\"));\n this.ws?.close(1000, \"client close\");\n this.ws = undefined;\n this.setState(\"closed\");\n }\n\n /** Subscribe to more channels (tracked and re-applied after reconnects).\n * Resolves with the server's ack. */\n async subscribe(channels: string[]): Promise<string[]> {\n for (const c of channels) this.desired.add(c);\n this.explicitChannels = true;\n if (!this.isOpen()) return [...this.desired];\n return new Promise<string[]>((resolve, reject) => {\n this.pendingSubscribes.push({ channels, resolve, reject });\n this.send({ type: \"subscribe\", channels });\n });\n }\n\n /** Unsubscribe from channels. */\n unsubscribe(channels: string[]): void {\n for (const c of channels) this.desired.delete(c);\n this.explicitChannels = true;\n if (this.isOpen()) this.send({ type: \"unsubscribe\", channels });\n }\n\n /** Publish over the socket (requires a ws-capable `publish` token). Resolves\n * with the delivered count from the server's ack. */\n async publish(channel: string, data: unknown): Promise<number> {\n if (!this.isOpen()) throw new Error(\"socket is not open\");\n return new Promise<number>((resolve, reject) => {\n this.pendingPublishes.push({ resolve, reject });\n this.send({ type: \"publish\", channel, data });\n });\n }\n\n // --- internals ---\n\n private isOpen(): boolean {\n return !!this.ws && this.ws.readyState === OPEN;\n }\n\n private send(frame: unknown): void {\n this.ws?.send(typeof frame === \"string\" ? frame : JSON.stringify(frame));\n }\n\n /** Where to dial, and with which subprotocols. The token travels as a subprotocol\n * (`altengine.token.<token>`, beside `altengine.v1`), never in the URL — except against an\n * older server whose response has only `ws_url`, which is opened as it is. */\n private target(tok: SocketToken): { url: string; protocols?: string[] } {\n const endpoint = tok.ws_endpoint ?? (tok.ws_url ? undefined : this.opts.url);\n let url: URL;\n let protocols: string[] | undefined;\n if (endpoint) {\n url = new URL(endpoint);\n protocols = tok.protocols?.length ? tok.protocols : [WS_PROTOCOL, WS_TOKEN_PROTOCOL_PREFIX + tok.token];\n } else if (tok.ws_url) {\n url = new URL(tok.ws_url);\n if (!url.searchParams.has(\"token\")) url.searchParams.set(\"token\", tok.token);\n } else {\n throw new Error(\"no WebSocket URL: token response had no ws_endpoint and no url option was set\");\n }\n // Narrow the initial subscription to the explicitly requested subset.\n if (this.explicitChannels && this.desired.size) {\n url.searchParams.set(\"channels\", [...this.desired].join(\",\"));\n }\n return { url: url.toString(), protocols };\n }\n\n private async dial(): Promise<void> {\n this.setState(this.attempts === 0 ? \"connecting\" : \"reconnecting\");\n let tok: SocketToken;\n try {\n tok = await this.opts.getToken();\n } catch (err) {\n this.emit(\"error\", err instanceof Error ? err : new Error(String(err)));\n this.scheduleReconnect();\n return;\n }\n\n const WS = this.opts.webSocket ?? (globalThis.WebSocket as typeof WebSocket | undefined);\n if (!WS) throw new Error(\"no WebSocket implementation; pass { webSocket } (e.g. `ws` on Node < 22)\");\n\n await new Promise<void>((resolve) => {\n let settled = false;\n const { url, protocols } = this.target(tok);\n const ws = protocols ? new WS(url, protocols) : new WS(url);\n this.ws = ws;\n\n ws.onopen = () => {\n settled = true;\n this.attempts = 0;\n this.lastActivity = Date.now();\n this.setState(\"open\");\n this.startPing();\n resolve();\n };\n ws.onmessage = (ev: MessageEvent) => this.handleMessage(ev);\n ws.onerror = () => {\n // onclose always follows; error details aren't portable across runtimes.\n };\n ws.onclose = (ev: CloseEvent) => {\n this.stopPing();\n this.failPending(new Error(`socket closed (${ev.code})`));\n if (!settled) {\n settled = true;\n resolve();\n }\n if (!this.closedByUser) this.scheduleReconnect();\n };\n });\n }\n\n private handleMessage(ev: MessageEvent): void {\n this.lastActivity = Date.now();\n const raw = typeof ev.data === \"string\" ? ev.data : \"\";\n if (raw === \"pong\" || raw === \"ping\") return;\n let frame: any;\n try {\n frame = JSON.parse(raw);\n } catch {\n return;\n }\n switch (frame?.type) {\n case \"subscribed\": {\n // Only settle the oldest pending subscribe if this ack covers its channels —\n // an unsolicited ack (e.g. for the connect-time ?channels= subscription)\n // arriving late must not steal a runtime subscribe()'s resolution.\n // A refused channel is answered too, so it counts as covered; the promise resolves with\n // the channels actually admitted.\n const refused: string[] = Array.isArray(frame.refused) ? frame.refused : [];\n const head = this.pendingSubscribes[0];\n const acked = new Set<string>([...(frame.channels ?? []), ...refused]);\n if (head && head.channels.every((c) => acked.has(c))) {\n this.pendingSubscribes.shift()!.resolve(frame.channels ?? []);\n }\n if (refused.length) this.emit(\"refused\", refused);\n return;\n }\n case \"published\":\n this.pendingPublishes.shift()?.resolve(frame.delivered ?? 0);\n return;\n case \"error\": {\n const err = new Error(typeof frame.error === \"string\" ? frame.error : JSON.stringify(frame.error));\n // An error ack settles the oldest pending request, if any.\n (this.pendingPublishes.shift() ?? this.pendingSubscribes.shift())?.reject(err);\n this.emit(\"error\", err);\n return;\n }\n default:\n if (frame && typeof frame.channel === \"string\" && frame.type === undefined) {\n this.emit(\"message\", frame as ChannelMessage);\n }\n }\n }\n\n private startPing(): void {\n // The server closes (4408) a connection that pinged and then stops for 15 minutes.\n const interval = Math.min(this.opts.pingIntervalMs ?? 30_000, 60_000);\n this.stopPing();\n this.pingTimer = setInterval(() => {\n if (!this.isOpen()) return;\n if (Date.now() - this.lastActivity > interval * 1.5) {\n // Dead connection: no traffic (not even pongs). Force a reconnect.\n this.ws?.close(4000, \"keepalive timeout\");\n return;\n }\n this.send(\"ping\");\n }, interval);\n }\n\n private stopPing(): void {\n if (this.pingTimer) clearInterval(this.pingTimer);\n this.pingTimer = undefined;\n }\n\n private scheduleReconnect(): void {\n if (this.closedByUser) return;\n const base = this.opts.backoffBaseMs ?? 250;\n const cap = this.opts.backoffMaxMs ?? 30_000;\n const delay = Math.min(base * 2 ** this.attempts, cap) * (0.5 + Math.random() * 0.5);\n this.attempts++;\n this.setState(\"reconnecting\");\n this.reconnectTimer = setTimeout(() => void this.dial(), delay);\n }\n\n private failPending(err: Error): void {\n for (const p of this.pendingSubscribes.splice(0)) p.reject(err);\n for (const p of this.pendingPublishes.splice(0)) p.reject(err);\n }\n}\n\nexport type { ChannelMessage } from \"./types.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAwBA,IAAM,cAAc;AACpB,IAAM,2BAA2B;AAoCjC,IAAM,aAAa;AACnB,IAAM,OAAO;AAEN,IAAM,gBAAN,MAAoB;AAAA,EACR;AAAA,EACA,YAA2E;AAAA,IAC1F,SAAS,oBAAI,IAAI;AAAA,IACjB,OAAO,oBAAI,IAAI;AAAA,IACf,OAAO,oBAAI,IAAI;AAAA,IACf,SAAS,oBAAI,IAAI;AAAA,EACnB;AAAA,EAEQ;AAAA,EACA,aAA0B;AAAA,EAC1B,UAAU,oBAAI,IAAY;AAAA,EAC1B;AAA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I,SAAS,OAAO,MAAM,YAAY,YAAY,MAAM,SAAS,QAAW;AAC1E,eAAK,KAAK,WAAW,KAAuB;AAAA,QAC9C;AAAA,IACJ;AAAA,EACF;AAAA,EAEQ,YAAkB;AAExB,UAAM,WAAW,KAAK,IAAI,KAAK,KAAK,kBAAkB,KAAQ,GAAM;AACpE,SAAK,SAAS;AACd,SAAK,YAAY,YAAY,MAAM;AACjC,UAAI,CAAC,KAAK,OAAO,EAAG;AACpB,UAAI,KAAK,IAAI,IAAI,KAAK,eAAe,WAAW,KAAK;AAEnD,aAAK,IAAI,MAAM,KAAM,mBAAmB;AACxC;AAAA,MACF;AACA,WAAK,KAAK,MAAM;AAAA,IAClB,GAAG,QAAQ;AAAA,EACb;AAAA,EAEQ,WAAiB;AACvB,QAAI,KAAK,UAAW,eAAc,KAAK,SAAS;AAChD,SAAK,YAAY;AAAA,EACnB;AAAA,EAEQ,oBAA0B;AAChC,QAAI,KAAK,aAAc;AACvB,UAAM,OAAO,KAAK,KAAK,iBAAiB;AACxC,UAAM,MAAM,KAAK,KAAK,gBAAgB;AACtC,UAAM,QAAQ,KAAK,IAAI,OAAO,KAAK,KAAK,UAAU,GAAG,KAAK,MAAM,KAAK,OAAO,IAAI;AAChF,SAAK;AACL,SAAK,SAAS,cAAc;AAC5B,SAAK,iBAAiB,WAAW,MAAM,KAAK,KAAK,KAAK,GAAG,KAAK;AAAA,EAChE;AAAA,EAEQ,YAAY,KAAkB;AACpC,eAAW,KAAK,KAAK,kBAAkB,OAAO,CAAC,EAAG,GAAE,OAAO,GAAG;AAC9D,eAAW,KAAK,KAAK,iBAAiB,OAAO,CAAC,EAAG,GAAE,OAAO,GAAG;AAAA,EAC/D;AACF;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { C as ChannelMessage, b as ChannelSocket, c as ChannelSocketOptions, g as SocketEvents, S as SocketState, f as SocketToken } from './socket-DqIm8vll.cjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { C as ChannelMessage, b as ChannelSocket, c as ChannelSocketOptions, g as SocketEvents, S as SocketState, f as SocketToken } from './socket-DqIm8vll.js';
|
package/dist/channel.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var AltEngineError = class extends Error {
|
|
3
|
+
code;
|
|
4
|
+
status;
|
|
5
|
+
details;
|
|
6
|
+
/** Seconds to wait before retrying, from the `Retry-After` header (429s). */
|
|
7
|
+
retryAfter;
|
|
8
|
+
constructor(opts) {
|
|
9
|
+
super(opts.message);
|
|
10
|
+
this.name = "AltEngineError";
|
|
11
|
+
this.code = opts.code;
|
|
12
|
+
this.status = opts.status;
|
|
13
|
+
this.details = opts.details;
|
|
14
|
+
this.retryAfter = opts.retryAfter;
|
|
15
|
+
}
|
|
16
|
+
/** Whether the request can be safely retried after a backoff. 429 always carries
|
|
17
|
+
* Retry-After; 502/503/504 are transient. 507 INDEX_FULL is NOT retryable. */
|
|
18
|
+
get retryable() {
|
|
19
|
+
if (this.status === 429) return true;
|
|
20
|
+
return this.status === 502 || this.status === 503 || this.status === 504;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
var AltEngineNetworkError = class extends Error {
|
|
24
|
+
cause;
|
|
25
|
+
constructor(message, cause) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = "AltEngineNetworkError";
|
|
28
|
+
this.cause = cause;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// src/constants.ts
|
|
33
|
+
var DEFAULT_BASE_URL = "https://api.altengine.net";
|
|
34
|
+
var DEV_BASE_URL = "http://127.0.0.1:9191";
|
|
35
|
+
var seg = (s) => encodeURIComponent(String(s));
|
|
36
|
+
var nsSeg = (namespace) => seg(namespace === "" ? "_default" : namespace);
|
|
37
|
+
|
|
38
|
+
// src/auth/storage.ts
|
|
39
|
+
function memoryStorage() {
|
|
40
|
+
const map = /* @__PURE__ */ new Map();
|
|
41
|
+
return {
|
|
42
|
+
get: (k) => map.get(k) ?? null,
|
|
43
|
+
set: (k, v) => void map.set(k, v),
|
|
44
|
+
remove: (k) => void map.delete(k)
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function defaultStorage() {
|
|
48
|
+
try {
|
|
49
|
+
const ls = globalThis.localStorage;
|
|
50
|
+
if (!ls) return memoryStorage();
|
|
51
|
+
const probe = "__altengine_probe__";
|
|
52
|
+
ls.setItem(probe, "1");
|
|
53
|
+
ls.removeItem(probe);
|
|
54
|
+
return {
|
|
55
|
+
get: (k) => ls.getItem(k),
|
|
56
|
+
set: (k, v) => ls.setItem(k, v),
|
|
57
|
+
remove: (k) => ls.removeItem(k)
|
|
58
|
+
};
|
|
59
|
+
} catch {
|
|
60
|
+
return memoryStorage();
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// src/auth/client.ts
|
|
65
|
+
var nowSec = () => Math.floor(Date.now() / 1e3);
|
|
66
|
+
var AuthClient = class {
|
|
67
|
+
instance;
|
|
68
|
+
baseUrl;
|
|
69
|
+
base;
|
|
70
|
+
storage;
|
|
71
|
+
key;
|
|
72
|
+
fetchImpl;
|
|
73
|
+
skew;
|
|
74
|
+
listeners = /* @__PURE__ */ new Set();
|
|
75
|
+
session;
|
|
76
|
+
/** In-flight refresh, so concurrent requests share one round trip. */
|
|
77
|
+
refreshing = null;
|
|
78
|
+
constructor(opts) {
|
|
79
|
+
if (!opts.instance) throw new Error("AuthClient requires an `instance`");
|
|
80
|
+
this.instance = opts.instance;
|
|
81
|
+
this.baseUrl = (opts.baseUrl ?? (opts.dev ? DEV_BASE_URL : DEFAULT_BASE_URL)).replace(/\/+$/, "");
|
|
82
|
+
this.base = `${this.baseUrl}/v1/auth/${seg(opts.instance)}`;
|
|
83
|
+
this.storage = opts.storage ?? defaultStorage();
|
|
84
|
+
this.key = opts.storageKey ?? `altengine.auth.${opts.instance}`;
|
|
85
|
+
const f = opts.fetch ?? globalThis.fetch;
|
|
86
|
+
if (!f) throw new Error("no fetch implementation available; pass { fetch }");
|
|
87
|
+
this.fetchImpl = f;
|
|
88
|
+
this.skew = opts.refreshSkewSeconds ?? 30;
|
|
89
|
+
this.session = this.load();
|
|
90
|
+
}
|
|
91
|
+
// --- session state ------------------------------------------------------
|
|
92
|
+
/** The signed-in user, or null. Reads persisted state, so it survives reloads. */
|
|
93
|
+
get user() {
|
|
94
|
+
return this.session?.user ?? null;
|
|
95
|
+
}
|
|
96
|
+
get isSignedIn() {
|
|
97
|
+
return !!this.session?.id_token;
|
|
98
|
+
}
|
|
99
|
+
/** Subscribe to sign-in/sign-out. Returns an unsubscribe function. */
|
|
100
|
+
onChange(fn) {
|
|
101
|
+
this.listeners.add(fn);
|
|
102
|
+
return () => void this.listeners.delete(fn);
|
|
103
|
+
}
|
|
104
|
+
emit() {
|
|
105
|
+
for (const fn of this.listeners) {
|
|
106
|
+
try {
|
|
107
|
+
fn(this.user);
|
|
108
|
+
} catch {
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
load() {
|
|
113
|
+
try {
|
|
114
|
+
const raw = this.storage.get(this.key);
|
|
115
|
+
return raw ? JSON.parse(raw) : null;
|
|
116
|
+
} catch {
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
save(s) {
|
|
121
|
+
this.session = s;
|
|
122
|
+
try {
|
|
123
|
+
if (s) this.storage.set(this.key, JSON.stringify(s));
|
|
124
|
+
else this.storage.remove(this.key);
|
|
125
|
+
} catch {
|
|
126
|
+
}
|
|
127
|
+
this.emit();
|
|
128
|
+
}
|
|
129
|
+
adopt(t) {
|
|
130
|
+
const user = t.user ?? this.session?.user ?? null;
|
|
131
|
+
this.save({ id_token: t.id_token, refresh_token: t.refresh_token, expires_at: t.expires_at, user });
|
|
132
|
+
return { ...t, user };
|
|
133
|
+
}
|
|
134
|
+
// --- transport ----------------------------------------------------------
|
|
135
|
+
async call(method, path, body, bearer) {
|
|
136
|
+
const headers = {};
|
|
137
|
+
if (bearer) headers["authorization"] = `Bearer ${bearer}`;
|
|
138
|
+
if (body !== void 0) headers["content-type"] = "application/json";
|
|
139
|
+
let res;
|
|
140
|
+
try {
|
|
141
|
+
res = await this.fetchImpl(this.base + path, {
|
|
142
|
+
method,
|
|
143
|
+
headers,
|
|
144
|
+
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
145
|
+
});
|
|
146
|
+
} catch (err) {
|
|
147
|
+
throw new AltEngineNetworkError(`request failed: ${method} ${path}`, err);
|
|
148
|
+
}
|
|
149
|
+
if (!res.ok) throw await toError(res);
|
|
150
|
+
if (res.status === 204) return void 0;
|
|
151
|
+
return await res.json();
|
|
152
|
+
}
|
|
153
|
+
// --- config -------------------------------------------------------------
|
|
154
|
+
/** The instance's public sign-in configuration — which fields the sign-up form
|
|
155
|
+
* collects, which one is the login identity, and which methods are enabled.
|
|
156
|
+
* Fetch this to render a sign-in UI that matches the instance's settings. */
|
|
157
|
+
async config() {
|
|
158
|
+
return this.call("GET", "/config");
|
|
159
|
+
}
|
|
160
|
+
// --- sign up / in / out -------------------------------------------------
|
|
161
|
+
/** Create an account. Pass the configured sign-up fields plus `password`,
|
|
162
|
+
* e.g. `{ email, name, password }`. Signs the new user in. */
|
|
163
|
+
async signUp(fields) {
|
|
164
|
+
const t = await this.call("POST", "/signup", fields);
|
|
165
|
+
return this.adopt(t);
|
|
166
|
+
}
|
|
167
|
+
/** Sign in with the identity field + password. When the account has two-factor
|
|
168
|
+
* enabled this resolves to `{ status: "mfa_required" }` and you must call
|
|
169
|
+
* {@link verifyMfa} with the code — no tokens are issued until then. */
|
|
170
|
+
async signIn(identifier, password) {
|
|
171
|
+
const t = await this.call("POST", "/signin", {
|
|
172
|
+
identifier,
|
|
173
|
+
password
|
|
174
|
+
});
|
|
175
|
+
if ("mfa_required" in t) return { status: "mfa_required", mfaToken: t.mfa_token };
|
|
176
|
+
return { status: "signed_in", session: this.adopt(t) };
|
|
177
|
+
}
|
|
178
|
+
/** Complete a two-factor challenge from {@link signIn} or {@link passwordlessVerify}. */
|
|
179
|
+
async verifyMfa(mfaToken, code) {
|
|
180
|
+
const t = await this.call("POST", "/2fa/verify", { mfa_token: mfaToken, code });
|
|
181
|
+
return this.adopt(t);
|
|
182
|
+
}
|
|
183
|
+
/** Start passwordless sign-in: emails a one-time code. Always resolves — the
|
|
184
|
+
* server never reveals whether the account exists. */
|
|
185
|
+
async passwordlessStart(identifier) {
|
|
186
|
+
await this.call("POST", "/passwordless/start", { identifier });
|
|
187
|
+
}
|
|
188
|
+
/** Finish passwordless sign-in with the emailed code. */
|
|
189
|
+
async passwordlessVerify(identifier, code) {
|
|
190
|
+
const t = await this.call("POST", "/passwordless/verify", {
|
|
191
|
+
identifier,
|
|
192
|
+
code
|
|
193
|
+
});
|
|
194
|
+
if ("mfa_required" in t) return { status: "mfa_required", mfaToken: t.mfa_token };
|
|
195
|
+
return { status: "signed_in", session: this.adopt(t) };
|
|
196
|
+
}
|
|
197
|
+
/** Start a password reset: emails a one-time code. Always resolves. */
|
|
198
|
+
async passwordResetStart(identifier) {
|
|
199
|
+
await this.call("POST", "/password/reset/start", { identifier });
|
|
200
|
+
}
|
|
201
|
+
/** Finish a password reset with the emailed code and a new password. */
|
|
202
|
+
async passwordResetVerify(identifier, code, password) {
|
|
203
|
+
await this.call("POST", "/password/reset/verify", { identifier, code, password });
|
|
204
|
+
}
|
|
205
|
+
/** The signed-in user, re-read from the server (picks up claim changes). */
|
|
206
|
+
async me() {
|
|
207
|
+
const tok = await this.getToken();
|
|
208
|
+
if (!tok) throw new AltEngineError({ code: "UNAUTHENTICATED", message: "not signed in", status: 401 });
|
|
209
|
+
const { user } = await this.call("GET", "/me", void 0, tok);
|
|
210
|
+
if (user && this.session) this.save({ ...this.session, user });
|
|
211
|
+
return user;
|
|
212
|
+
}
|
|
213
|
+
/** Revoke the refresh token server-side and clear local state. Always clears
|
|
214
|
+
* locally, even if the network call fails. */
|
|
215
|
+
async signOut() {
|
|
216
|
+
const rt = this.session?.refresh_token;
|
|
217
|
+
this.save(null);
|
|
218
|
+
if (rt) {
|
|
219
|
+
try {
|
|
220
|
+
await this.call("POST", "/signout", { refresh_token: rt });
|
|
221
|
+
} catch {
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
// --- tokens -------------------------------------------------------------
|
|
226
|
+
/** Force a refresh-token rotation and return the new id_token. */
|
|
227
|
+
async refresh() {
|
|
228
|
+
const rt = this.session?.refresh_token;
|
|
229
|
+
if (!rt) throw new AltEngineError({ code: "UNAUTHENTICATED", message: "not signed in", status: 401 });
|
|
230
|
+
const t = await this.call("POST", "/token/refresh", { refresh_token: rt });
|
|
231
|
+
this.adopt(t);
|
|
232
|
+
return t.id_token;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* The current id_token, refreshed first if it is expired or about to be.
|
|
236
|
+
* Returns `undefined` when nobody is signed in. This is the `TokenProvider`
|
|
237
|
+
* the SDK calls before every Datastore/Search/Channel request — pass the
|
|
238
|
+
* client as `new AltEngine({ auth })` and tokens stay fresh automatically.
|
|
239
|
+
*
|
|
240
|
+
* Concurrent callers share a single refresh. If the refresh fails because the
|
|
241
|
+
* session is truly gone (401/403), local state is cleared so the app can react
|
|
242
|
+
* via {@link onChange} instead of retrying forever.
|
|
243
|
+
*/
|
|
244
|
+
async getToken() {
|
|
245
|
+
const s = this.session;
|
|
246
|
+
if (!s?.id_token) return void 0;
|
|
247
|
+
if (s.expires_at - this.skew > nowSec()) return s.id_token;
|
|
248
|
+
if (!this.refreshing) {
|
|
249
|
+
this.refreshing = this.refresh().catch((err) => {
|
|
250
|
+
if (err instanceof AltEngineError && (err.status === 401 || err.status === 403)) {
|
|
251
|
+
this.save(null);
|
|
252
|
+
return void 0;
|
|
253
|
+
}
|
|
254
|
+
throw err;
|
|
255
|
+
}).finally(() => {
|
|
256
|
+
this.refreshing = null;
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
return this.refreshing;
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
async function toError(res) {
|
|
263
|
+
let code = "INTERNAL";
|
|
264
|
+
let message = `HTTP ${res.status}`;
|
|
265
|
+
let details;
|
|
266
|
+
try {
|
|
267
|
+
const parsed = await res.json();
|
|
268
|
+
if (parsed?.error) {
|
|
269
|
+
code = parsed.error.code ?? code;
|
|
270
|
+
message = parsed.error.message ?? message;
|
|
271
|
+
details = parsed.error.details;
|
|
272
|
+
}
|
|
273
|
+
} catch {
|
|
274
|
+
}
|
|
275
|
+
const ra = res.headers.get("retry-after");
|
|
276
|
+
const retryAfter = ra !== null && !Number.isNaN(Number(ra)) ? Number(ra) : void 0;
|
|
277
|
+
return new AltEngineError({ code, message, status: res.status, details, retryAfter });
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export {
|
|
281
|
+
AltEngineError,
|
|
282
|
+
AltEngineNetworkError,
|
|
283
|
+
DEFAULT_BASE_URL,
|
|
284
|
+
DEV_BASE_URL,
|
|
285
|
+
seg,
|
|
286
|
+
nsSeg,
|
|
287
|
+
memoryStorage,
|
|
288
|
+
defaultStorage,
|
|
289
|
+
AuthClient
|
|
290
|
+
};
|
|
291
|
+
//# sourceMappingURL=chunk-6Q4X4E7X.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/constants.ts","../src/auth/storage.ts","../src/auth/client.ts"],"sourcesContent":["/** Error codes emitted by the altengine API. The union is open (`string`) so new\n * server codes never break compilation. */\nexport type ErrorCode =\n | \"NOT_FOUND\"\n | \"INVALID_ARGUMENT\"\n | \"UNAUTHENTICATED\"\n | \"PERMISSION_DENIED\"\n | \"RATE_LIMITED\"\n | \"QUERY_TOO_COMPLEX\"\n | \"INDEX_REQUIRED\"\n | \"DOCUMENT_TOO_LARGE\"\n | \"INDEX_FULL\"\n | \"ALREADY_EXISTS\"\n | \"PRECONDITION_FAILED\"\n | \"INTERNAL\"\n | (string & {});\n\n/** A structured altengine API error: the `{error:{code,message,details?}}` envelope\n * plus transport context (HTTP status, Retry-After). */\nexport class AltEngineError extends Error {\n readonly code: ErrorCode;\n readonly status: number;\n readonly details?: unknown;\n /** Seconds to wait before retrying, from the `Retry-After` header (429s). */\n readonly retryAfter?: number;\n\n constructor(opts: { code: ErrorCode; message: string; status: number; details?: unknown; retryAfter?: number }) {\n super(opts.message);\n this.name = \"AltEngineError\";\n this.code = opts.code;\n this.status = opts.status;\n this.details = opts.details;\n this.retryAfter = opts.retryAfter;\n }\n\n /** Whether the request can be safely retried after a backoff. 429 always carries\n * Retry-After; 502/503/504 are transient. 507 INDEX_FULL is NOT retryable. */\n get retryable(): boolean {\n if (this.status === 429) return true;\n return this.status === 502 || this.status === 503 || this.status === 504;\n }\n}\n\n/** Thrown when the network/fetch layer fails before an HTTP response exists. */\nexport class AltEngineNetworkError extends Error {\n readonly cause?: unknown;\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = \"AltEngineNetworkError\";\n this.cause = cause;\n }\n}\n","/** Side-effect-free constants and path helpers shared by every client.\n *\n * These live apart from `http.ts` on purpose: the browser-safe entry points\n * (`@altenginenet/sdk/auth`, `@altenginenet/sdk/channel`) need the base URLs and path\n * encoders but must NOT pull in the API-key transport, which is a backend\n * credential path that has no business in a browser bundle. */\n\n/** Production API origin used when no override is given. */\nexport const DEFAULT_BASE_URL = \"https://api.altengine.net\";\n/** Where `altengine dev` (the local emulator) listens by default. */\nexport const DEV_BASE_URL = \"http://127.0.0.1:9191\";\n\n/** Encode one path segment (instance/index/collection/key names). */\nexport const seg = (s: string | number): string => encodeURIComponent(String(s));\n\n/** Encode a namespace path segment. The empty (default) namespace can't ride a\n * URL path — routers collapse the resulting \"//\", so it travels as the reserved\n * sentinel `_default` (the server maps it back to \"\"). */\nexport const nsSeg = (namespace: string): string => seg(namespace === \"\" ? \"_default\" : namespace);\n","/** Where the signed-in session is kept between page loads. Implement this to use\n * cookies, IndexedDB, React Native's AsyncStorage (via a sync cache), or nothing\n * at all. The default picks `localStorage` in the browser and falls back to an\n * in-memory store everywhere else (Node, SSR, private-mode failures). */\nexport interface TokenStorage {\n get(key: string): string | null;\n set(key: string, value: string): void;\n remove(key: string): void;\n}\n\n/** A `TokenStorage` that forgets everything when the process/tab goes away. */\nexport function memoryStorage(): TokenStorage {\n const map = new Map<string, string>();\n return {\n get: (k) => map.get(k) ?? null,\n set: (k, v) => void map.set(k, v),\n remove: (k) => void map.delete(k),\n };\n}\n\n/** `localStorage` when it's present AND writable, else an in-memory store.\n * Safari private mode throws on `setItem`, so this probes with a real write. */\nexport function defaultStorage(): TokenStorage {\n try {\n const ls = globalThis.localStorage;\n if (!ls) return memoryStorage();\n const probe = \"__altengine_probe__\";\n ls.setItem(probe, \"1\");\n ls.removeItem(probe);\n return {\n get: (k) => ls.getItem(k),\n set: (k, v) => ls.setItem(k, v),\n remove: (k) => ls.removeItem(k),\n };\n } catch {\n return memoryStorage();\n }\n}\n","/** AuthClient — the browser-side identity client for `/v1/auth/{instance}`.\n *\n * This is the piece that lets a client-side app talk to altengine with **no\n * backend of its own**: the end user signs in here, and the resulting `id_token`\n * is what Datastore/Channel requests carry. Access rules on the auth instance\n * decide what that user may read and write.\n *\n * Deliberately self-contained and API-key-free (like `ChannelSocket`) so it is\n * safe to ship to a browser — see the `@altenginenet/sdk/auth` subpath export.\n *\n * ```ts\n * import { AuthClient } from \"@altenginenet/sdk/auth\";\n * import { AltEngine } from \"@altenginenet/sdk\";\n *\n * const auth = new AuthClient({ instance: \"myapp-auth\" });\n * await auth.signIn(\"alice@example.com\", \"hunter2\");\n *\n * // Hand the client to the SDK: every request now carries the user's token.\n * const ae = new AltEngine({ auth });\n * const { documents } = await ae.datastore(\"myapp\").query(\"posts\", { limit: 20 });\n * ```\n */\n\nimport { AltEngineError, AltEngineNetworkError } from \"../errors.js\";\nimport { DEFAULT_BASE_URL, DEV_BASE_URL, seg } from \"../constants.js\";\nimport { defaultStorage, memoryStorage, type TokenStorage } from \"./storage.js\";\nimport type { AuthConfig, AuthSession, AuthUser, SignInResult, StoredSession, AuthTokens } from \"./types.js\";\n\nexport interface AuthClientOptions {\n /** The auth instance name, e.g. \"myapp-auth\". */\n instance: string;\n /** API origin override. Resolution order: this → `dev: true` → production. */\n baseUrl?: string;\n /** Target the local emulator (`altengine dev`) at `http://127.0.0.1:9191`. */\n dev?: boolean;\n /** Where to persist the session (default: `localStorage`, else in-memory).\n * Pass `memoryStorage()` to keep the session out of storage entirely. */\n storage?: TokenStorage;\n /** Storage key prefix, so several apps/instances can share one origin.\n * Defaults to `altengine.auth.<instance>`. */\n storageKey?: string;\n /** Custom fetch (tests, polyfills). Defaults to `globalThis.fetch`. */\n fetch?: typeof globalThis.fetch;\n /** Refresh the id_token this many seconds before it expires (default 30). */\n refreshSkewSeconds?: number;\n}\n\ntype Listener = (user: AuthUser | null) => void;\n\nconst nowSec = () => Math.floor(Date.now() / 1000);\n\nexport class AuthClient {\n readonly instance: string;\n readonly baseUrl: string;\n\n private readonly base: string;\n private readonly storage: TokenStorage;\n private readonly key: string;\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly skew: number;\n private readonly listeners = new Set<Listener>();\n\n private session: StoredSession | null;\n /** In-flight refresh, so concurrent requests share one round trip. */\n private refreshing: Promise<string | undefined> | null = null;\n\n constructor(opts: AuthClientOptions) {\n if (!opts.instance) throw new Error(\"AuthClient requires an `instance`\");\n this.instance = opts.instance;\n this.baseUrl = (opts.baseUrl ?? (opts.dev ? DEV_BASE_URL : DEFAULT_BASE_URL)).replace(/\\/+$/, \"\");\n this.base = `${this.baseUrl}/v1/auth/${seg(opts.instance)}`;\n this.storage = opts.storage ?? defaultStorage();\n this.key = opts.storageKey ?? `altengine.auth.${opts.instance}`;\n const f = opts.fetch ?? globalThis.fetch;\n if (!f) throw new Error(\"no fetch implementation available; pass { fetch }\");\n this.fetchImpl = f;\n this.skew = opts.refreshSkewSeconds ?? 30;\n this.session = this.load();\n }\n\n // --- session state ------------------------------------------------------\n\n /** The signed-in user, or null. Reads persisted state, so it survives reloads. */\n get user(): AuthUser | null {\n return this.session?.user ?? null;\n }\n\n get isSignedIn(): boolean {\n return !!this.session?.id_token;\n }\n\n /** Subscribe to sign-in/sign-out. Returns an unsubscribe function. */\n onChange(fn: Listener): () => void {\n this.listeners.add(fn);\n return () => void this.listeners.delete(fn);\n }\n\n private emit(): void {\n for (const fn of this.listeners) {\n try {\n fn(this.user);\n } catch {\n /* a listener must never break the auth flow */\n }\n }\n }\n\n private load(): StoredSession | null {\n try {\n const raw = this.storage.get(this.key);\n return raw ? (JSON.parse(raw) as StoredSession) : null;\n } catch {\n return null;\n }\n }\n\n private save(s: StoredSession | null): void {\n this.session = s;\n try {\n if (s) this.storage.set(this.key, JSON.stringify(s));\n else this.storage.remove(this.key);\n } catch {\n /* storage full / blocked — the session still works for this page */\n }\n this.emit();\n }\n\n private adopt(t: AuthTokens & { user?: AuthUser }): AuthSession {\n const user = t.user ?? this.session?.user ?? null;\n this.save({ id_token: t.id_token, refresh_token: t.refresh_token, expires_at: t.expires_at, user });\n return { ...t, user: user as AuthUser };\n }\n\n // --- transport ----------------------------------------------------------\n\n private async call<T>(method: string, path: string, body?: unknown, bearer?: string): Promise<T> {\n const headers: Record<string, string> = {};\n if (bearer) headers[\"authorization\"] = `Bearer ${bearer}`;\n if (body !== undefined) headers[\"content-type\"] = \"application/json\";\n let res: Response;\n try {\n res = await this.fetchImpl(this.base + path, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch (err) {\n throw new AltEngineNetworkError(`request failed: ${method} ${path}`, err);\n }\n if (!res.ok) throw await toError(res);\n if (res.status === 204) return undefined as T;\n return (await res.json()) as T;\n }\n\n // --- config -------------------------------------------------------------\n\n /** The instance's public sign-in configuration — which fields the sign-up form\n * collects, which one is the login identity, and which methods are enabled.\n * Fetch this to render a sign-in UI that matches the instance's settings. */\n async config(): Promise<AuthConfig> {\n return this.call<AuthConfig>(\"GET\", \"/config\");\n }\n\n // --- sign up / in / out -------------------------------------------------\n\n /** Create an account. Pass the configured sign-up fields plus `password`,\n * e.g. `{ email, name, password }`. Signs the new user in. */\n async signUp(fields: Record<string, unknown>): Promise<AuthSession> {\n const t = await this.call<AuthSession>(\"POST\", \"/signup\", fields);\n return this.adopt(t);\n }\n\n /** Sign in with the identity field + password. When the account has two-factor\n * enabled this resolves to `{ status: \"mfa_required\" }` and you must call\n * {@link verifyMfa} with the code — no tokens are issued until then. */\n async signIn(identifier: string, password: string): Promise<SignInResult> {\n const t = await this.call<AuthSession | { mfa_required: true; mfa_token: string }>(\"POST\", \"/signin\", {\n identifier,\n password,\n });\n if (\"mfa_required\" in t) return { status: \"mfa_required\", mfaToken: t.mfa_token };\n return { status: \"signed_in\", session: this.adopt(t) };\n }\n\n /** Complete a two-factor challenge from {@link signIn} or {@link passwordlessVerify}. */\n async verifyMfa(mfaToken: string, code: string): Promise<AuthSession> {\n const t = await this.call<AuthSession>(\"POST\", \"/2fa/verify\", { mfa_token: mfaToken, code });\n return this.adopt(t);\n }\n\n /** Start passwordless sign-in: emails a one-time code. Always resolves — the\n * server never reveals whether the account exists. */\n async passwordlessStart(identifier: string): Promise<void> {\n await this.call(\"POST\", \"/passwordless/start\", { identifier });\n }\n\n /** Finish passwordless sign-in with the emailed code. */\n async passwordlessVerify(identifier: string, code: string): Promise<SignInResult> {\n const t = await this.call<AuthSession | { mfa_required: true; mfa_token: string }>(\"POST\", \"/passwordless/verify\", {\n identifier,\n code,\n });\n if (\"mfa_required\" in t) return { status: \"mfa_required\", mfaToken: t.mfa_token };\n return { status: \"signed_in\", session: this.adopt(t) };\n }\n\n /** Start a password reset: emails a one-time code. Always resolves. */\n async passwordResetStart(identifier: string): Promise<void> {\n await this.call(\"POST\", \"/password/reset/start\", { identifier });\n }\n\n /** Finish a password reset with the emailed code and a new password. */\n async passwordResetVerify(identifier: string, code: string, password: string): Promise<void> {\n await this.call(\"POST\", \"/password/reset/verify\", { identifier, code, password });\n }\n\n /** The signed-in user, re-read from the server (picks up claim changes). */\n async me(): Promise<AuthUser> {\n const tok = await this.getToken();\n if (!tok) throw new AltEngineError({ code: \"UNAUTHENTICATED\", message: \"not signed in\", status: 401 });\n // The wire wraps the user in a `{ user }` envelope.\n const { user } = await this.call<{ user: AuthUser }>(\"GET\", \"/me\", undefined, tok);\n // Keep the cached user in step, so claim changes made elsewhere land locally too.\n if (user && this.session) this.save({ ...this.session, user });\n return user;\n }\n\n /** Revoke the refresh token server-side and clear local state. Always clears\n * locally, even if the network call fails. */\n async signOut(): Promise<void> {\n const rt = this.session?.refresh_token;\n this.save(null);\n if (rt) {\n try {\n await this.call(\"POST\", \"/signout\", { refresh_token: rt });\n } catch {\n /* best-effort: local state is already gone */\n }\n }\n }\n\n // --- tokens -------------------------------------------------------------\n\n /** Force a refresh-token rotation and return the new id_token. */\n async refresh(): Promise<string> {\n const rt = this.session?.refresh_token;\n if (!rt) throw new AltEngineError({ code: \"UNAUTHENTICATED\", message: \"not signed in\", status: 401 });\n const t = await this.call<AuthTokens>(\"POST\", \"/token/refresh\", { refresh_token: rt });\n this.adopt(t);\n return t.id_token;\n }\n\n /**\n * The current id_token, refreshed first if it is expired or about to be.\n * Returns `undefined` when nobody is signed in. This is the `TokenProvider`\n * the SDK calls before every Datastore/Search/Channel request — pass the\n * client as `new AltEngine({ auth })` and tokens stay fresh automatically.\n *\n * Concurrent callers share a single refresh. If the refresh fails because the\n * session is truly gone (401/403), local state is cleared so the app can react\n * via {@link onChange} instead of retrying forever.\n */\n async getToken(): Promise<string | undefined> {\n const s = this.session;\n if (!s?.id_token) return undefined;\n if (s.expires_at - this.skew > nowSec()) return s.id_token;\n if (!this.refreshing) {\n this.refreshing = this.refresh()\n .catch((err) => {\n if (err instanceof AltEngineError && (err.status === 401 || err.status === 403)) {\n this.save(null); // refresh token revoked/expired — session is over\n return undefined;\n }\n throw err; // transient (network/5xx): let the caller see it and retry\n })\n .finally(() => {\n this.refreshing = null;\n });\n }\n return this.refreshing;\n }\n}\n\nasync function toError(res: Response): Promise<AltEngineError> {\n let code = \"INTERNAL\";\n let message = `HTTP ${res.status}`;\n let details: unknown;\n try {\n const parsed = (await res.json()) as { error?: { code?: string; message?: string; details?: unknown } };\n if (parsed?.error) {\n code = parsed.error.code ?? code;\n message = parsed.error.message ?? message;\n details = parsed.error.details;\n }\n } catch {\n /* non-JSON error body */\n }\n const ra = res.headers.get(\"retry-after\");\n const retryAfter = ra !== null && !Number.isNaN(Number(ra)) ? Number(ra) : undefined;\n return new AltEngineError({ code, message, status: res.status, details, retryAfter });\n}\n\nexport { memoryStorage, defaultStorage, type TokenStorage };\n"],"mappings":";AAmBO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,MAAoG;AAC9G,UAAM,KAAK,OAAO;AAClB,SAAK,OAAO;AACZ,SAAK,OAAO,KAAK;AACjB,SAAK,SAAS,KAAK;AACnB,SAAK,UAAU,KAAK;AACpB,SAAK,aAAa,KAAK;AAAA,EACzB;AAAA;AAAA;AAAA,EAIA,IAAI,YAAqB;AACvB,QAAI,KAAK,WAAW,IAAK,QAAO;AAChC,WAAO,KAAK,WAAW,OAAO,KAAK,WAAW,OAAO,KAAK,WAAW;AAAA,EACvE;AACF;AAGO,IAAM,wBAAN,cAAoC,MAAM;AAAA,EACtC;AAAA,EACT,YAAY,SAAiB,OAAiB;AAC5C,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,QAAQ;AAAA,EACf;AACF;;;AC3CO,IAAM,mBAAmB;AAEzB,IAAM,eAAe;AAGrB,IAAM,MAAM,CAAC,MAA+B,mBAAmB,OAAO,CAAC,CAAC;AAKxE,IAAM,QAAQ,CAAC,cAA8B,IAAI,cAAc,KAAK,aAAa,SAAS;;;ACP1F,SAAS,gBAA8B;AAC5C,QAAM,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AAE,CAAC,IAAI,OAAO,EAAE,IAAI;AAC3E,SAAO,IAAI,eAAe,EAAE,MAAM,SAAS,QAAQ,IAAI,QAAQ,SAAS,WAAW,CAAC;AACtF;","names":[]}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// src/channel/socket.ts
|
|
2
|
+
var WS_PROTOCOL = "altengine.v1";
|
|
3
|
+
var WS_TOKEN_PROTOCOL_PREFIX = "altengine.token.";
|
|
4
|
+
var CONNECTING = 0;
|
|
5
|
+
var OPEN = 1;
|
|
6
|
+
var ChannelSocket = class {
|
|
7
|
+
opts;
|
|
8
|
+
listeners = {
|
|
9
|
+
message: /* @__PURE__ */ new Set(),
|
|
10
|
+
state: /* @__PURE__ */ new Set(),
|
|
11
|
+
error: /* @__PURE__ */ new Set(),
|
|
12
|
+
refused: /* @__PURE__ */ new Set()
|
|
13
|
+
};
|
|
14
|
+
ws;
|
|
15
|
+
stateValue = "idle";
|
|
16
|
+
desired = /* @__PURE__ */ new Set();
|
|
17
|
+
explicitChannels;
|
|
18
|
+
closedByUser = false;
|
|
19
|
+
attempts = 0;
|
|
20
|
+
pingTimer;
|
|
21
|
+
lastActivity = 0;
|
|
22
|
+
reconnectTimer;
|
|
23
|
+
pendingSubscribes = [];
|
|
24
|
+
pendingPublishes = [];
|
|
25
|
+
constructor(opts) {
|
|
26
|
+
this.opts = opts;
|
|
27
|
+
this.explicitChannels = opts.channels !== void 0;
|
|
28
|
+
for (const c of opts.channels ?? []) this.desired.add(c);
|
|
29
|
+
}
|
|
30
|
+
get state() {
|
|
31
|
+
return this.stateValue;
|
|
32
|
+
}
|
|
33
|
+
on(event, fn) {
|
|
34
|
+
this.listeners[event].add(fn);
|
|
35
|
+
return () => this.listeners[event].delete(fn);
|
|
36
|
+
}
|
|
37
|
+
emit(event, payload) {
|
|
38
|
+
for (const fn of this.listeners[event]) fn(payload);
|
|
39
|
+
}
|
|
40
|
+
setState(s) {
|
|
41
|
+
if (this.stateValue === s) return;
|
|
42
|
+
this.stateValue = s;
|
|
43
|
+
this.emit("state", s);
|
|
44
|
+
}
|
|
45
|
+
/** Connect (resolves once the socket is open). Reconnects automatically until
|
|
46
|
+
* `close()` is called. */
|
|
47
|
+
async connect() {
|
|
48
|
+
this.closedByUser = false;
|
|
49
|
+
if (this.ws && (this.ws.readyState === OPEN || this.ws.readyState === CONNECTING)) return;
|
|
50
|
+
await this.dial();
|
|
51
|
+
}
|
|
52
|
+
/** Stop reconnecting and close the connection. */
|
|
53
|
+
close() {
|
|
54
|
+
this.closedByUser = true;
|
|
55
|
+
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
56
|
+
this.stopPing();
|
|
57
|
+
this.failPending(new Error("socket closed"));
|
|
58
|
+
this.ws?.close(1e3, "client close");
|
|
59
|
+
this.ws = void 0;
|
|
60
|
+
this.setState("closed");
|
|
61
|
+
}
|
|
62
|
+
/** Subscribe to more channels (tracked and re-applied after reconnects).
|
|
63
|
+
* Resolves with the server's ack. */
|
|
64
|
+
async subscribe(channels) {
|
|
65
|
+
for (const c of channels) this.desired.add(c);
|
|
66
|
+
this.explicitChannels = true;
|
|
67
|
+
if (!this.isOpen()) return [...this.desired];
|
|
68
|
+
return new Promise((resolve, reject) => {
|
|
69
|
+
this.pendingSubscribes.push({ channels, resolve, reject });
|
|
70
|
+
this.send({ type: "subscribe", channels });
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/** Unsubscribe from channels. */
|
|
74
|
+
unsubscribe(channels) {
|
|
75
|
+
for (const c of channels) this.desired.delete(c);
|
|
76
|
+
this.explicitChannels = true;
|
|
77
|
+
if (this.isOpen()) this.send({ type: "unsubscribe", channels });
|
|
78
|
+
}
|
|
79
|
+
/** Publish over the socket (requires a ws-capable `publish` token). Resolves
|
|
80
|
+
* with the delivered count from the server's ack. */
|
|
81
|
+
async publish(channel, data) {
|
|
82
|
+
if (!this.isOpen()) throw new Error("socket is not open");
|
|
83
|
+
return new Promise((resolve, reject) => {
|
|
84
|
+
this.pendingPublishes.push({ resolve, reject });
|
|
85
|
+
this.send({ type: "publish", channel, data });
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
// --- internals ---
|
|
89
|
+
isOpen() {
|
|
90
|
+
return !!this.ws && this.ws.readyState === OPEN;
|
|
91
|
+
}
|
|
92
|
+
send(frame) {
|
|
93
|
+
this.ws?.send(typeof frame === "string" ? frame : JSON.stringify(frame));
|
|
94
|
+
}
|
|
95
|
+
/** Where to dial, and with which subprotocols. The token travels as a subprotocol
|
|
96
|
+
* (`altengine.token.<token>`, beside `altengine.v1`), never in the URL — except against an
|
|
97
|
+
* older server whose response has only `ws_url`, which is opened as it is. */
|
|
98
|
+
target(tok) {
|
|
99
|
+
const endpoint = tok.ws_endpoint ?? (tok.ws_url ? void 0 : this.opts.url);
|
|
100
|
+
let url;
|
|
101
|
+
let protocols;
|
|
102
|
+
if (endpoint) {
|
|
103
|
+
url = new URL(endpoint);
|
|
104
|
+
protocols = tok.protocols?.length ? tok.protocols : [WS_PROTOCOL, WS_TOKEN_PROTOCOL_PREFIX + tok.token];
|
|
105
|
+
} else if (tok.ws_url) {
|
|
106
|
+
url = new URL(tok.ws_url);
|
|
107
|
+
if (!url.searchParams.has("token")) url.searchParams.set("token", tok.token);
|
|
108
|
+
} else {
|
|
109
|
+
throw new Error("no WebSocket URL: token response had no ws_endpoint and no url option was set");
|
|
110
|
+
}
|
|
111
|
+
if (this.explicitChannels && this.desired.size) {
|
|
112
|
+
url.searchParams.set("channels", [...this.desired].join(","));
|
|
113
|
+
}
|
|
114
|
+
return { url: url.toString(), protocols };
|
|
115
|
+
}
|
|
116
|
+
async dial() {
|
|
117
|
+
this.setState(this.attempts === 0 ? "connecting" : "reconnecting");
|
|
118
|
+
let tok;
|
|
119
|
+
try {
|
|
120
|
+
tok = await this.opts.getToken();
|
|
121
|
+
} catch (err) {
|
|
122
|
+
this.emit("error", err instanceof Error ? err : new Error(String(err)));
|
|
123
|
+
this.scheduleReconnect();
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const WS = this.opts.webSocket ?? globalThis.WebSocket;
|
|
127
|
+
if (!WS) throw new Error("no WebSocket implementation; pass { webSocket } (e.g. `ws` on Node < 22)");
|
|
128
|
+
await new Promise((resolve) => {
|
|
129
|
+
let settled = false;
|
|
130
|
+
const { url, protocols } = this.target(tok);
|
|
131
|
+
const ws = protocols ? new WS(url, protocols) : new WS(url);
|
|
132
|
+
this.ws = ws;
|
|
133
|
+
ws.onopen = () => {
|
|
134
|
+
settled = true;
|
|
135
|
+
this.attempts = 0;
|
|
136
|
+
this.lastActivity = Date.now();
|
|
137
|
+
this.setState("open");
|
|
138
|
+
this.startPing();
|
|
139
|
+
resolve();
|
|
140
|
+
};
|
|
141
|
+
ws.onmessage = (ev) => this.handleMessage(ev);
|
|
142
|
+
ws.onerror = () => {
|
|
143
|
+
};
|
|
144
|
+
ws.onclose = (ev) => {
|
|
145
|
+
this.stopPing();
|
|
146
|
+
this.failPending(new Error(`socket closed (${ev.code})`));
|
|
147
|
+
if (!settled) {
|
|
148
|
+
settled = true;
|
|
149
|
+
resolve();
|
|
150
|
+
}
|
|
151
|
+
if (!this.closedByUser) this.scheduleReconnect();
|
|
152
|
+
};
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
handleMessage(ev) {
|
|
156
|
+
this.lastActivity = Date.now();
|
|
157
|
+
const raw = typeof ev.data === "string" ? ev.data : "";
|
|
158
|
+
if (raw === "pong" || raw === "ping") return;
|
|
159
|
+
let frame;
|
|
160
|
+
try {
|
|
161
|
+
frame = JSON.parse(raw);
|
|
162
|
+
} catch {
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
switch (frame?.type) {
|
|
166
|
+
case "subscribed": {
|
|
167
|
+
const refused = Array.isArray(frame.refused) ? frame.refused : [];
|
|
168
|
+
const head = this.pendingSubscribes[0];
|
|
169
|
+
const acked = /* @__PURE__ */ new Set([...frame.channels ?? [], ...refused]);
|
|
170
|
+
if (head && head.channels.every((c) => acked.has(c))) {
|
|
171
|
+
this.pendingSubscribes.shift().resolve(frame.channels ?? []);
|
|
172
|
+
}
|
|
173
|
+
if (refused.length) this.emit("refused", refused);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
case "published":
|
|
177
|
+
this.pendingPublishes.shift()?.resolve(frame.delivered ?? 0);
|
|
178
|
+
return;
|
|
179
|
+
case "error": {
|
|
180
|
+
const err = new Error(typeof frame.error === "string" ? frame.error : JSON.stringify(frame.error));
|
|
181
|
+
(this.pendingPublishes.shift() ?? this.pendingSubscribes.shift())?.reject(err);
|
|
182
|
+
this.emit("error", err);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
default:
|
|
186
|
+
if (frame && typeof frame.channel === "string" && frame.type === void 0) {
|
|
187
|
+
this.emit("message", frame);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
startPing() {
|
|
192
|
+
const interval = Math.min(this.opts.pingIntervalMs ?? 3e4, 6e4);
|
|
193
|
+
this.stopPing();
|
|
194
|
+
this.pingTimer = setInterval(() => {
|
|
195
|
+
if (!this.isOpen()) return;
|
|
196
|
+
if (Date.now() - this.lastActivity > interval * 1.5) {
|
|
197
|
+
this.ws?.close(4e3, "keepalive timeout");
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
this.send("ping");
|
|
201
|
+
}, interval);
|
|
202
|
+
}
|
|
203
|
+
stopPing() {
|
|
204
|
+
if (this.pingTimer) clearInterval(this.pingTimer);
|
|
205
|
+
this.pingTimer = void 0;
|
|
206
|
+
}
|
|
207
|
+
scheduleReconnect() {
|
|
208
|
+
if (this.closedByUser) return;
|
|
209
|
+
const base = this.opts.backoffBaseMs ?? 250;
|
|
210
|
+
const cap = this.opts.backoffMaxMs ?? 3e4;
|
|
211
|
+
const delay = Math.min(base * 2 ** this.attempts, cap) * (0.5 + Math.random() * 0.5);
|
|
212
|
+
this.attempts++;
|
|
213
|
+
this.setState("reconnecting");
|
|
214
|
+
this.reconnectTimer = setTimeout(() => void this.dial(), delay);
|
|
215
|
+
}
|
|
216
|
+
failPending(err) {
|
|
217
|
+
for (const p of this.pendingSubscribes.splice(0)) p.reject(err);
|
|
218
|
+
for (const p of this.pendingPublishes.splice(0)) p.reject(err);
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
export {
|
|
223
|
+
ChannelSocket
|
|
224
|
+
};
|
|
225
|
+
//# sourceMappingURL=chunk-NAQQAMY7.js.map
|