@safeurl/sdk 1.0.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.
@@ -0,0 +1,169 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+
3
+ type Slot = 'body' | 'headers' | 'path' | 'query';
4
+
5
+ export type Field =
6
+ | {
7
+ in: Exclude<Slot, 'body'>;
8
+ /**
9
+ * Field name. This is the name we want the user to see and use.
10
+ */
11
+ key: string;
12
+ /**
13
+ * Field mapped name. This is the name we want to use in the request.
14
+ * If omitted, we use the same value as `key`.
15
+ */
16
+ map?: string;
17
+ }
18
+ | {
19
+ in: Extract<Slot, 'body'>;
20
+ /**
21
+ * Key isn't required for bodies.
22
+ */
23
+ key?: string;
24
+ map?: string;
25
+ }
26
+ | {
27
+ /**
28
+ * Field name. This is the name we want the user to see and use.
29
+ */
30
+ key: string;
31
+ /**
32
+ * Field mapped name. This is the name we want to use in the request.
33
+ * If `in` is omitted, `map` aliases `key` to the transport layer.
34
+ */
35
+ map: Slot;
36
+ };
37
+
38
+ export interface Fields {
39
+ allowExtra?: Partial<Record<Slot, boolean>>;
40
+ args?: ReadonlyArray<Field>;
41
+ }
42
+
43
+ export type FieldsConfig = ReadonlyArray<Field | Fields>;
44
+
45
+ const extraPrefixesMap: Record<string, Slot> = {
46
+ $body_: 'body',
47
+ $headers_: 'headers',
48
+ $path_: 'path',
49
+ $query_: 'query',
50
+ };
51
+ const extraPrefixes = Object.entries(extraPrefixesMap);
52
+
53
+ type KeyMap = Map<
54
+ string,
55
+ | {
56
+ in: Slot;
57
+ map?: string;
58
+ }
59
+ | {
60
+ in?: never;
61
+ map: Slot;
62
+ }
63
+ >;
64
+
65
+ const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {
66
+ if (!map) {
67
+ map = new Map();
68
+ }
69
+
70
+ for (const config of fields) {
71
+ if ('in' in config) {
72
+ if (config.key) {
73
+ map.set(config.key, {
74
+ in: config.in,
75
+ map: config.map,
76
+ });
77
+ }
78
+ } else if ('key' in config) {
79
+ map.set(config.key, {
80
+ map: config.map,
81
+ });
82
+ } else if (config.args) {
83
+ buildKeyMap(config.args, map);
84
+ }
85
+ }
86
+
87
+ return map;
88
+ };
89
+
90
+ interface Params {
91
+ body: unknown;
92
+ headers: Record<string, unknown>;
93
+ path: Record<string, unknown>;
94
+ query: Record<string, unknown>;
95
+ }
96
+
97
+ const stripEmptySlots = (params: Params) => {
98
+ for (const [slot, value] of Object.entries(params)) {
99
+ if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) {
100
+ delete params[slot as Slot];
101
+ }
102
+ }
103
+ };
104
+
105
+ export const buildClientParams = (args: ReadonlyArray<unknown>, fields: FieldsConfig) => {
106
+ const params: Params = {
107
+ body: {},
108
+ headers: {},
109
+ path: {},
110
+ query: {},
111
+ };
112
+
113
+ const map = buildKeyMap(fields);
114
+
115
+ let config: FieldsConfig[number] | undefined;
116
+
117
+ for (const [index, arg] of args.entries()) {
118
+ if (fields[index]) {
119
+ config = fields[index];
120
+ }
121
+
122
+ if (!config) {
123
+ continue;
124
+ }
125
+
126
+ if ('in' in config) {
127
+ if (config.key) {
128
+ const field = map.get(config.key)!;
129
+ const name = field.map || config.key;
130
+ if (field.in) {
131
+ (params[field.in] as Record<string, unknown>)[name] = arg;
132
+ }
133
+ } else {
134
+ params.body = arg;
135
+ }
136
+ } else {
137
+ for (const [key, value] of Object.entries(arg ?? {})) {
138
+ const field = map.get(key);
139
+
140
+ if (field) {
141
+ if (field.in) {
142
+ const name = field.map || key;
143
+ (params[field.in] as Record<string, unknown>)[name] = value;
144
+ } else {
145
+ params[field.map] = value;
146
+ }
147
+ } else {
148
+ const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix));
149
+
150
+ if (extra) {
151
+ const [prefix, slot] = extra;
152
+ (params[slot] as Record<string, unknown>)[key.slice(prefix.length)] = value;
153
+ } else if ('allowExtra' in config && config.allowExtra) {
154
+ for (const [slot, allowed] of Object.entries(config.allowExtra)) {
155
+ if (allowed) {
156
+ (params[slot as Slot] as Record<string, unknown>)[key] = value;
157
+ break;
158
+ }
159
+ }
160
+ }
161
+ }
162
+ }
163
+ }
164
+ }
165
+
166
+ stripEmptySlots(params);
167
+
168
+ return params;
169
+ };
@@ -0,0 +1,171 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+
3
+ interface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {}
4
+
5
+ interface SerializePrimitiveOptions {
6
+ allowReserved?: boolean;
7
+ name: string;
8
+ }
9
+
10
+ export interface SerializerOptions<T> {
11
+ /**
12
+ * @default true
13
+ */
14
+ explode: boolean;
15
+ style: T;
16
+ }
17
+
18
+ export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
19
+ export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
20
+ type MatrixStyle = 'label' | 'matrix' | 'simple';
21
+ export type ObjectStyle = 'form' | 'deepObject';
22
+ type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
23
+
24
+ interface SerializePrimitiveParam extends SerializePrimitiveOptions {
25
+ value: string;
26
+ }
27
+
28
+ export const separatorArrayExplode = (style: ArraySeparatorStyle) => {
29
+ switch (style) {
30
+ case 'label':
31
+ return '.';
32
+ case 'matrix':
33
+ return ';';
34
+ case 'simple':
35
+ return ',';
36
+ default:
37
+ return '&';
38
+ }
39
+ };
40
+
41
+ export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => {
42
+ switch (style) {
43
+ case 'form':
44
+ return ',';
45
+ case 'pipeDelimited':
46
+ return '|';
47
+ case 'spaceDelimited':
48
+ return '%20';
49
+ default:
50
+ return ',';
51
+ }
52
+ };
53
+
54
+ export const separatorObjectExplode = (style: ObjectSeparatorStyle) => {
55
+ switch (style) {
56
+ case 'label':
57
+ return '.';
58
+ case 'matrix':
59
+ return ';';
60
+ case 'simple':
61
+ return ',';
62
+ default:
63
+ return '&';
64
+ }
65
+ };
66
+
67
+ export const serializeArrayParam = ({
68
+ allowReserved,
69
+ explode,
70
+ name,
71
+ style,
72
+ value,
73
+ }: SerializeOptions<ArraySeparatorStyle> & {
74
+ value: unknown[];
75
+ }) => {
76
+ if (!explode) {
77
+ const joinedValues = (
78
+ allowReserved ? value : value.map((v) => encodeURIComponent(v as string))
79
+ ).join(separatorArrayNoExplode(style));
80
+ switch (style) {
81
+ case 'label':
82
+ return `.${joinedValues}`;
83
+ case 'matrix':
84
+ return `;${name}=${joinedValues}`;
85
+ case 'simple':
86
+ return joinedValues;
87
+ default:
88
+ return `${name}=${joinedValues}`;
89
+ }
90
+ }
91
+
92
+ const separator = separatorArrayExplode(style);
93
+ const joinedValues = value
94
+ .map((v) => {
95
+ if (style === 'label' || style === 'simple') {
96
+ return allowReserved ? v : encodeURIComponent(v as string);
97
+ }
98
+
99
+ return serializePrimitiveParam({
100
+ allowReserved,
101
+ name,
102
+ value: v as string,
103
+ });
104
+ })
105
+ .join(separator);
106
+ return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;
107
+ };
108
+
109
+ export const serializePrimitiveParam = ({
110
+ allowReserved,
111
+ name,
112
+ value,
113
+ }: SerializePrimitiveParam) => {
114
+ if (value === undefined || value === null) {
115
+ return '';
116
+ }
117
+
118
+ if (typeof value === 'object') {
119
+ throw new Error(
120
+ 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.',
121
+ );
122
+ }
123
+
124
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
125
+ };
126
+
127
+ export const serializeObjectParam = ({
128
+ allowReserved,
129
+ explode,
130
+ name,
131
+ style,
132
+ value,
133
+ valueOnly,
134
+ }: SerializeOptions<ObjectSeparatorStyle> & {
135
+ value: Record<string, unknown> | Date;
136
+ valueOnly?: boolean;
137
+ }) => {
138
+ if (value instanceof Date) {
139
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
140
+ }
141
+
142
+ if (style !== 'deepObject' && !explode) {
143
+ let values: string[] = [];
144
+ Object.entries(value).forEach(([key, v]) => {
145
+ values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)];
146
+ });
147
+ const joinedValues = values.join(',');
148
+ switch (style) {
149
+ case 'form':
150
+ return `${name}=${joinedValues}`;
151
+ case 'label':
152
+ return `.${joinedValues}`;
153
+ case 'matrix':
154
+ return `;${name}=${joinedValues}`;
155
+ default:
156
+ return joinedValues;
157
+ }
158
+ }
159
+
160
+ const separator = separatorObjectExplode(style);
161
+ const joinedValues = Object.entries(value)
162
+ .map(([key, v]) =>
163
+ serializePrimitiveParam({
164
+ allowReserved,
165
+ name: style === 'deepObject' ? `${name}[${key}]` : key,
166
+ value: v as string,
167
+ }),
168
+ )
169
+ .join(separator);
170
+ return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;
171
+ };
@@ -0,0 +1,117 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+
3
+ /**
4
+ * JSON-friendly union that mirrors what Pinia Colada can hash.
5
+ */
6
+ export type JsonValue =
7
+ | null
8
+ | string
9
+ | number
10
+ | boolean
11
+ | JsonValue[]
12
+ | { [key: string]: JsonValue };
13
+
14
+ /**
15
+ * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.
16
+ */
17
+ export const queryKeyJsonReplacer = (_key: string, value: unknown) => {
18
+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol') {
19
+ return undefined;
20
+ }
21
+ if (typeof value === 'bigint') {
22
+ return value.toString();
23
+ }
24
+ if (value instanceof Date) {
25
+ return value.toISOString();
26
+ }
27
+ return value;
28
+ };
29
+
30
+ /**
31
+ * Safely stringifies a value and parses it back into a JsonValue.
32
+ */
33
+ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => {
34
+ try {
35
+ const json = JSON.stringify(input, queryKeyJsonReplacer);
36
+ if (json === undefined) {
37
+ return undefined;
38
+ }
39
+ return JSON.parse(json) as JsonValue;
40
+ } catch {
41
+ return undefined;
42
+ }
43
+ };
44
+
45
+ /**
46
+ * Detects plain objects (including objects with a null prototype).
47
+ */
48
+ const isPlainObject = (value: unknown): value is Record<string, unknown> => {
49
+ if (value === null || typeof value !== 'object') {
50
+ return false;
51
+ }
52
+ const prototype = Object.getPrototypeOf(value as object);
53
+ return prototype === Object.prototype || prototype === null;
54
+ };
55
+
56
+ /**
57
+ * Turns URLSearchParams into a sorted JSON object for deterministic keys.
58
+ */
59
+ const serializeSearchParams = (params: URLSearchParams): JsonValue => {
60
+ const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b));
61
+ const result: Record<string, JsonValue> = {};
62
+
63
+ for (const [key, value] of entries) {
64
+ const existing = result[key];
65
+ if (existing === undefined) {
66
+ result[key] = value;
67
+ continue;
68
+ }
69
+
70
+ if (Array.isArray(existing)) {
71
+ (existing as string[]).push(value);
72
+ } else {
73
+ result[key] = [existing, value];
74
+ }
75
+ }
76
+
77
+ return result;
78
+ };
79
+
80
+ /**
81
+ * Normalizes any accepted value into a JSON-friendly shape for query keys.
82
+ */
83
+ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => {
84
+ if (value === null) {
85
+ return null;
86
+ }
87
+
88
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
89
+ return value;
90
+ }
91
+
92
+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol') {
93
+ return undefined;
94
+ }
95
+
96
+ if (typeof value === 'bigint') {
97
+ return value.toString();
98
+ }
99
+
100
+ if (value instanceof Date) {
101
+ return value.toISOString();
102
+ }
103
+
104
+ if (Array.isArray(value)) {
105
+ return stringifyToJsonValue(value);
106
+ }
107
+
108
+ if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) {
109
+ return serializeSearchParams(value);
110
+ }
111
+
112
+ if (isPlainObject(value)) {
113
+ return stringifyToJsonValue(value);
114
+ }
115
+
116
+ return undefined;
117
+ };
@@ -0,0 +1,243 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+
3
+ import type { Config } from './types.gen';
4
+
5
+ export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, 'method'> &
6
+ Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {
7
+ /**
8
+ * Fetch API implementation. You can use this option to provide a custom
9
+ * fetch instance.
10
+ *
11
+ * @default globalThis.fetch
12
+ */
13
+ fetch?: typeof fetch;
14
+ /**
15
+ * Implementing clients can call request interceptors inside this hook.
16
+ */
17
+ onRequest?: (url: string, init: RequestInit) => Promise<Request>;
18
+ /**
19
+ * Callback invoked when a network or parsing error occurs during streaming.
20
+ *
21
+ * This option applies only if the endpoint returns a stream of events.
22
+ *
23
+ * @param error The error that occurred.
24
+ */
25
+ onSseError?: (error: unknown) => void;
26
+ /**
27
+ * Callback invoked when an event is streamed from the server.
28
+ *
29
+ * This option applies only if the endpoint returns a stream of events.
30
+ *
31
+ * @param event Event streamed from the server.
32
+ * @returns Nothing (void).
33
+ */
34
+ onSseEvent?: (event: StreamEvent<TData>) => void;
35
+ serializedBody?: RequestInit['body'];
36
+ /**
37
+ * Default retry delay in milliseconds.
38
+ *
39
+ * This option applies only if the endpoint returns a stream of events.
40
+ *
41
+ * @default 3000
42
+ */
43
+ sseDefaultRetryDelay?: number;
44
+ /**
45
+ * Maximum number of retry attempts before giving up.
46
+ */
47
+ sseMaxRetryAttempts?: number;
48
+ /**
49
+ * Maximum retry delay in milliseconds.
50
+ *
51
+ * Applies only when exponential backoff is used.
52
+ *
53
+ * This option applies only if the endpoint returns a stream of events.
54
+ *
55
+ * @default 30000
56
+ */
57
+ sseMaxRetryDelay?: number;
58
+ /**
59
+ * Optional sleep function for retry backoff.
60
+ *
61
+ * Defaults to using `setTimeout`.
62
+ */
63
+ sseSleepFn?: (ms: number) => Promise<void>;
64
+ url: string;
65
+ };
66
+
67
+ export interface StreamEvent<TData = unknown> {
68
+ data: TData;
69
+ event?: string;
70
+ id?: string;
71
+ retry?: number;
72
+ }
73
+
74
+ export type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {
75
+ stream: AsyncGenerator<
76
+ TData extends Record<string, unknown> ? TData[keyof TData] : TData,
77
+ TReturn,
78
+ TNext
79
+ >;
80
+ };
81
+
82
+ export const createSseClient = <TData = unknown>({
83
+ onRequest,
84
+ onSseError,
85
+ onSseEvent,
86
+ responseTransformer,
87
+ responseValidator,
88
+ sseDefaultRetryDelay,
89
+ sseMaxRetryAttempts,
90
+ sseMaxRetryDelay,
91
+ sseSleepFn,
92
+ url,
93
+ ...options
94
+ }: ServerSentEventsOptions): ServerSentEventsResult<TData> => {
95
+ let lastEventId: string | undefined;
96
+
97
+ const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));
98
+
99
+ const createStream = async function* () {
100
+ let retryDelay: number = sseDefaultRetryDelay ?? 3000;
101
+ let attempt = 0;
102
+ const signal = options.signal ?? new AbortController().signal;
103
+
104
+ while (true) {
105
+ if (signal.aborted) break;
106
+
107
+ attempt++;
108
+
109
+ const headers =
110
+ options.headers instanceof Headers
111
+ ? options.headers
112
+ : new Headers(options.headers as Record<string, string> | undefined);
113
+
114
+ if (lastEventId !== undefined) {
115
+ headers.set('Last-Event-ID', lastEventId);
116
+ }
117
+
118
+ try {
119
+ const requestInit: RequestInit = {
120
+ redirect: 'follow',
121
+ ...options,
122
+ body: options.serializedBody,
123
+ headers,
124
+ signal,
125
+ };
126
+ let request = new Request(url, requestInit);
127
+ if (onRequest) {
128
+ request = await onRequest(url, requestInit);
129
+ }
130
+ // fetch must be assigned here, otherwise it would throw the error:
131
+ // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
132
+ const _fetch = options.fetch ?? globalThis.fetch;
133
+ const response = await _fetch(request);
134
+
135
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
136
+
137
+ if (!response.body) throw new Error('No body in SSE response');
138
+
139
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
140
+
141
+ let buffer = '';
142
+
143
+ const abortHandler = () => {
144
+ try {
145
+ reader.cancel();
146
+ } catch {
147
+ // noop
148
+ }
149
+ };
150
+
151
+ signal.addEventListener('abort', abortHandler);
152
+
153
+ try {
154
+ while (true) {
155
+ const { done, value } = await reader.read();
156
+ if (done) break;
157
+ buffer += value;
158
+ // Normalize line endings: CRLF -> LF, then CR -> LF
159
+ buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
160
+
161
+ const chunks = buffer.split('\n\n');
162
+ buffer = chunks.pop() ?? '';
163
+
164
+ for (const chunk of chunks) {
165
+ const lines = chunk.split('\n');
166
+ const dataLines: Array<string> = [];
167
+ let eventName: string | undefined;
168
+
169
+ for (const line of lines) {
170
+ if (line.startsWith('data:')) {
171
+ dataLines.push(line.replace(/^data:\s*/, ''));
172
+ } else if (line.startsWith('event:')) {
173
+ eventName = line.replace(/^event:\s*/, '');
174
+ } else if (line.startsWith('id:')) {
175
+ lastEventId = line.replace(/^id:\s*/, '');
176
+ } else if (line.startsWith('retry:')) {
177
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10);
178
+ if (!Number.isNaN(parsed)) {
179
+ retryDelay = parsed;
180
+ }
181
+ }
182
+ }
183
+
184
+ let data: unknown;
185
+ let parsedJson = false;
186
+
187
+ if (dataLines.length) {
188
+ const rawData = dataLines.join('\n');
189
+ try {
190
+ data = JSON.parse(rawData);
191
+ parsedJson = true;
192
+ } catch {
193
+ data = rawData;
194
+ }
195
+ }
196
+
197
+ if (parsedJson) {
198
+ if (responseValidator) {
199
+ await responseValidator(data);
200
+ }
201
+
202
+ if (responseTransformer) {
203
+ data = await responseTransformer(data);
204
+ }
205
+ }
206
+
207
+ onSseEvent?.({
208
+ data,
209
+ event: eventName,
210
+ id: lastEventId,
211
+ retry: retryDelay,
212
+ });
213
+
214
+ if (dataLines.length) {
215
+ yield data as any;
216
+ }
217
+ }
218
+ }
219
+ } finally {
220
+ signal.removeEventListener('abort', abortHandler);
221
+ reader.releaseLock();
222
+ }
223
+
224
+ break; // exit loop on normal completion
225
+ } catch (error) {
226
+ // connection failed or aborted; retry after delay
227
+ onSseError?.(error);
228
+
229
+ if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {
230
+ break; // stop after firing error
231
+ }
232
+
233
+ // exponential backoff: double retry each attempt, cap at 30s
234
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);
235
+ await sleep(backoff);
236
+ }
237
+ }
238
+ };
239
+
240
+ const stream = createStream();
241
+
242
+ return { stream };
243
+ };