@freema/drobek-sdk 0.8.0 → 0.9.3

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.
@@ -0,0 +1,37 @@
1
+ /**
2
+ * A server-sent event stream of a module route, read with `fetch` (not
3
+ * `EventSource`): the SDK sees the HTTP status and the `{ error }` body of a
4
+ * refused stream, sends `X-Drobek-SDK: 1`, and resumes with `Last-Event-ID`
5
+ * after every reconnect.
6
+ *
7
+ * A dropped connection, a stream the server ended (its lifetime, a restart,
8
+ * an `event: error`) and a 429 / 5xx answer reconnect after a delay that
9
+ * grows to 30 s; only a 4xx answer to the request stops for good
10
+ * (`onError`). An `event: error` never stops it by itself: the reconnect's
11
+ * answer decides, so a caller the server could not check for a moment (its
12
+ * session store briefly unreachable) comes back, while a caller who really
13
+ * signed out, or a rule that no longer admits them, gets the 4xx.
14
+ * `close()` stops it at once; no callback runs after it.
15
+ */
16
+ import { DrobekError } from './core.js';
17
+ /** One event: `type` is the SSE `event:` field (default `message`). */
18
+ export interface StreamEvent {
19
+ type: string;
20
+ data: string;
21
+ id: string | null;
22
+ }
23
+ export interface EventStreamOptions {
24
+ onEvent(event: StreamEvent): void;
25
+ /** The stream stopped for good: the server refused the request with a 4xx (not 408 / 429). */
26
+ onError?(error: DrobekError): void;
27
+ /** First reconnect delay in ms (default 1000; the server's `retry:` field overrides it). */
28
+ retryMs?: number;
29
+ fetchImpl?: (input: string, init?: RequestInit) => Promise<Response>;
30
+ }
31
+ /** Incremental SSE parser: feed text chunks, get the complete events. */
32
+ export declare function sseParser(): {
33
+ push(chunk: string): StreamEvent[];
34
+ retry(): number | null;
35
+ };
36
+ /** Open `url` (same origin) as an event stream; returns `close()`. */
37
+ export declare function openEventStream(url: string, opts: EventStreamOptions): () => void;
package/dist/events.js ADDED
@@ -0,0 +1,169 @@
1
+ /**
2
+ * A server-sent event stream of a module route, read with `fetch` (not
3
+ * `EventSource`): the SDK sees the HTTP status and the `{ error }` body of a
4
+ * refused stream, sends `X-Drobek-SDK: 1`, and resumes with `Last-Event-ID`
5
+ * after every reconnect.
6
+ *
7
+ * A dropped connection, a stream the server ended (its lifetime, a restart,
8
+ * an `event: error`) and a 429 / 5xx answer reconnect after a delay that
9
+ * grows to 30 s; only a 4xx answer to the request stops for good
10
+ * (`onError`). An `event: error` never stops it by itself: the reconnect's
11
+ * answer decides, so a caller the server could not check for a moment (its
12
+ * session store briefly unreachable) comes back, while a caller who really
13
+ * signed out, or a rule that no longer admits them, gets the 4xx.
14
+ * `close()` stops it at once; no callback runs after it.
15
+ */
16
+ import { DrobekError, SDK_HEADER } from './core.js';
17
+ const MAX_RETRY_MS = 30_000;
18
+ /** Incremental SSE parser: feed text chunks, get the complete events. */
19
+ export function sseParser() {
20
+ let buffer = '';
21
+ let type = '';
22
+ let data = [];
23
+ let id = null;
24
+ let lastId = null;
25
+ let retry = null;
26
+ return {
27
+ push(chunk) {
28
+ buffer += chunk;
29
+ const out = [];
30
+ let nl;
31
+ while ((nl = buffer.search(/\r\n|\r|\n/)) >= 0) {
32
+ const line = buffer.slice(0, nl);
33
+ buffer = buffer.slice(buffer[nl] === '\r' && buffer[nl + 1] === '\n' ? nl + 2 : nl + 1);
34
+ if (line === '') {
35
+ if (id !== null)
36
+ lastId = id;
37
+ if (data.length > 0)
38
+ out.push({ type: type || 'message', data: data.join('\n'), id: lastId });
39
+ type = '';
40
+ data = [];
41
+ id = null;
42
+ continue;
43
+ }
44
+ if (line.startsWith(':'))
45
+ continue;
46
+ const colon = line.indexOf(':');
47
+ const field = colon < 0 ? line : line.slice(0, colon);
48
+ let value = colon < 0 ? '' : line.slice(colon + 1);
49
+ if (value.startsWith(' '))
50
+ value = value.slice(1);
51
+ if (field === 'event')
52
+ type = value;
53
+ else if (field === 'data')
54
+ data.push(value);
55
+ else if (field === 'id' && !value.includes('\0'))
56
+ id = value;
57
+ else if (field === 'retry' && /^\d+$/.test(value))
58
+ retry = Number(value);
59
+ }
60
+ return out;
61
+ },
62
+ retry: () => retry,
63
+ };
64
+ }
65
+ async function refusal(res) {
66
+ let b = {};
67
+ try {
68
+ const parsed = (await res.json());
69
+ if (parsed && typeof parsed === 'object')
70
+ b = parsed;
71
+ }
72
+ catch {
73
+ /* not JSON */
74
+ }
75
+ return new DrobekError(res.status, typeof b.error === 'string' ? b.error : 'http_error', typeof b.message === 'string' ? b.message : `${res.status} ${res.statusText}`.trim(), b.details, typeof b.hint === 'string' ? b.hint : undefined);
76
+ }
77
+ /** Open `url` (same origin) as an event stream; returns `close()`. */
78
+ export function openEventStream(url, opts) {
79
+ const doFetch = opts.fetchImpl ?? ((input, init) => fetch(input, init));
80
+ const base = opts.retryMs ?? 1000;
81
+ let closed = false;
82
+ let lastId = null;
83
+ let delay = base;
84
+ let serverRetry = null;
85
+ let controller = null;
86
+ let timer = null;
87
+ const stop = (err) => {
88
+ if (closed)
89
+ return;
90
+ closed = true;
91
+ controller?.abort();
92
+ opts.onError?.(err);
93
+ };
94
+ const schedule = () => {
95
+ if (closed)
96
+ return;
97
+ const wait = Math.min(serverRetry ?? delay, MAX_RETRY_MS);
98
+ delay = Math.min(delay * 2, MAX_RETRY_MS);
99
+ timer = setTimeout(() => {
100
+ timer = null;
101
+ void connect();
102
+ }, wait);
103
+ };
104
+ async function connect() {
105
+ if (closed)
106
+ return;
107
+ controller = new AbortController();
108
+ const headers = { Accept: 'text/event-stream', [SDK_HEADER]: '1' };
109
+ if (lastId !== null)
110
+ headers['Last-Event-ID'] = lastId;
111
+ let res;
112
+ try {
113
+ res = await doFetch(url, { method: 'GET', headers, credentials: 'same-origin', cache: 'no-store', signal: controller.signal });
114
+ }
115
+ catch {
116
+ schedule();
117
+ return;
118
+ }
119
+ if (closed)
120
+ return;
121
+ if (!res.ok || !res.body) {
122
+ const err = await refusal(res);
123
+ if (res.status >= 400 && res.status < 500 && res.status !== 408 && res.status !== 429)
124
+ stop(err);
125
+ else
126
+ schedule();
127
+ return;
128
+ }
129
+ const parser = sseParser();
130
+ const reader = res.body.getReader();
131
+ const decoder = new TextDecoder();
132
+ try {
133
+ let ended = false;
134
+ while (!ended) {
135
+ const { value, done } = await reader.read();
136
+ if (done || closed)
137
+ break;
138
+ const events = parser.push(decoder.decode(value, { stream: true }));
139
+ serverRetry = parser.retry() ?? serverRetry;
140
+ for (const ev of events) {
141
+ if (closed)
142
+ break;
143
+ if (ev.id !== null)
144
+ lastId = ev.id;
145
+ if (ev.type === 'error') {
146
+ ended = true;
147
+ break;
148
+ }
149
+ delay = base;
150
+ opts.onEvent(ev);
151
+ }
152
+ }
153
+ }
154
+ catch {
155
+ /* the connection dropped: reconnect */
156
+ }
157
+ finally {
158
+ reader.cancel().catch(() => undefined);
159
+ }
160
+ schedule();
161
+ }
162
+ void connect();
163
+ return () => {
164
+ closed = true;
165
+ if (timer)
166
+ clearTimeout(timer);
167
+ controller?.abort();
168
+ };
169
+ }
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * @drobek/sdk — the browser SDK core. `core.ts` is bundled
3
3
  * into `/__drobek/sdk.js` with the SDK entry of every active platform module;
4
- * module SDK entries type their argument with `SdkCore` from here.
4
+ * module SDK entries type their argument with `SdkCore` from here;
5
+ * `events.ts` reads a module route's event stream (`openEventStream`).
5
6
  * `beacon.ts` is bundled into `/__drobek/beacon.js`, which the
6
7
  * compiler imports into every app: the page load, uncaught browser errors,
7
8
  * failed resource loads and CSP blocks → the app's beacon.
@@ -9,4 +10,5 @@
9
10
  export declare const SDK_VERSION = "1.0.0";
10
11
  export { DrobekError, MODULE_API_BASE, SDK_HEADER, createCore, type QueryValue, type RequestOptions, type SdkCore, } from './core.js';
11
12
  export { CORE_SDK_TYPES } from './types.js';
13
+ export { openEventStream, sseParser, type EventStreamOptions, type StreamEvent } from './events.js';
12
14
  export { BEACON_ENDPOINT, BEACON_FLUSH_MS, BEACON_MAX_BATCH, BEACON_MAX_BYTES, BEACON_MAX_PER_PAGE, BEACON_MAX_REPEATS, VERSION_TIMING_METRIC, describeError, describeResource, describeViolation, installBeacon, packBatches, pageVersion, type BeaconEnv, type BeaconEvent, type BeaconEventType, type BeaconHandle, type BeaconMeta, } from './beacon.js';
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * @drobek/sdk — the browser SDK core. `core.ts` is bundled
3
3
  * into `/__drobek/sdk.js` with the SDK entry of every active platform module;
4
- * module SDK entries type their argument with `SdkCore` from here.
4
+ * module SDK entries type their argument with `SdkCore` from here;
5
+ * `events.ts` reads a module route's event stream (`openEventStream`).
5
6
  * `beacon.ts` is bundled into `/__drobek/beacon.js`, which the
6
7
  * compiler imports into every app: the page load, uncaught browser errors,
7
8
  * failed resource loads and CSP blocks → the app's beacon.
@@ -9,4 +10,5 @@
9
10
  export const SDK_VERSION = '1.0.0';
10
11
  export { DrobekError, MODULE_API_BASE, SDK_HEADER, createCore, } from './core.js';
11
12
  export { CORE_SDK_TYPES } from './types.js';
13
+ export { openEventStream, sseParser } from './events.js';
12
14
  export { BEACON_ENDPOINT, BEACON_FLUSH_MS, BEACON_MAX_BATCH, BEACON_MAX_BYTES, BEACON_MAX_PER_PAGE, BEACON_MAX_REPEATS, VERSION_TIMING_METRIC, describeError, describeResource, describeViolation, installBeacon, packBatches, pageVersion, } from './beacon.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@freema/drobek-sdk",
3
- "version": "0.8.0",
3
+ "version": "0.9.3",
4
4
  "description": "The drobek browser SDK core: the SdkCore a platform module's SDK entry receives, DrobekError, the error beacon.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
@@ -34,6 +34,10 @@
34
34
  "types": "./dist/core.d.ts",
35
35
  "default": "./dist/core.js"
36
36
  },
37
+ "./events": {
38
+ "types": "./dist/events.d.ts",
39
+ "default": "./dist/events.js"
40
+ },
37
41
  "./beacon": {
38
42
  "types": "./dist/beacon.d.ts",
39
43
  "default": "./dist/beacon.js"