@storyblok/management-api-client 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 (73) hide show
  1. package/LICENSE +8 -0
  2. package/README.md +241 -0
  3. package/dist/_virtual/rolldown_runtime.js +25 -0
  4. package/dist/client/client.d.mts +7 -0
  5. package/dist/client/client.d.ts +7 -0
  6. package/dist/client/client.js +160 -0
  7. package/dist/client/client.js.map +1 -0
  8. package/dist/client/client.mjs +159 -0
  9. package/dist/client/client.mjs.map +1 -0
  10. package/dist/client/index.js +4 -0
  11. package/dist/client/index.mjs +4 -0
  12. package/dist/client/types.d.mts +116 -0
  13. package/dist/client/types.d.ts +116 -0
  14. package/dist/client/utils.d.mts +23 -0
  15. package/dist/client/utils.d.ts +23 -0
  16. package/dist/client/utils.js +242 -0
  17. package/dist/client/utils.js.map +1 -0
  18. package/dist/client/utils.mjs +236 -0
  19. package/dist/client/utils.mjs.map +1 -0
  20. package/dist/core/auth.d.mts +21 -0
  21. package/dist/core/auth.d.ts +21 -0
  22. package/dist/core/auth.js +13 -0
  23. package/dist/core/auth.js.map +1 -0
  24. package/dist/core/auth.mjs +12 -0
  25. package/dist/core/auth.mjs.map +1 -0
  26. package/dist/core/bodySerializer.d.mts +13 -0
  27. package/dist/core/bodySerializer.d.ts +13 -0
  28. package/dist/core/bodySerializer.js +7 -0
  29. package/dist/core/bodySerializer.js.map +1 -0
  30. package/dist/core/bodySerializer.mjs +6 -0
  31. package/dist/core/bodySerializer.mjs.map +1 -0
  32. package/dist/core/params.js +12 -0
  33. package/dist/core/params.js.map +1 -0
  34. package/dist/core/params.mjs +11 -0
  35. package/dist/core/params.mjs.map +1 -0
  36. package/dist/core/pathSerializer.d.mts +14 -0
  37. package/dist/core/pathSerializer.d.ts +14 -0
  38. package/dist/core/pathSerializer.js +85 -0
  39. package/dist/core/pathSerializer.js.map +1 -0
  40. package/dist/core/pathSerializer.mjs +82 -0
  41. package/dist/core/pathSerializer.mjs.map +1 -0
  42. package/dist/core/types.d.mts +78 -0
  43. package/dist/core/types.d.ts +78 -0
  44. package/dist/index.d.mts +50 -0
  45. package/dist/index.d.ts +50 -0
  46. package/dist/index.js +84 -0
  47. package/dist/index.js.map +1 -0
  48. package/dist/index.mjs +82 -0
  49. package/dist/index.mjs.map +1 -0
  50. package/dist/sdk-registry.generated.d.mts +28 -0
  51. package/dist/sdk-registry.generated.d.ts +28 -0
  52. package/dist/sdk-registry.generated.js +26 -0
  53. package/dist/sdk-registry.generated.js.map +1 -0
  54. package/dist/sdk-registry.generated.mjs +26 -0
  55. package/dist/sdk-registry.generated.mjs.map +1 -0
  56. package/examples/index.ts +32 -0
  57. package/generate.ts +125 -0
  58. package/package.json +79 -0
  59. package/src/__tests__/integration.test.ts +143 -0
  60. package/src/__tests__/region-resolution.test.ts +89 -0
  61. package/src/client/client.ts +246 -0
  62. package/src/client/index.ts +22 -0
  63. package/src/client/types.ts +222 -0
  64. package/src/client/utils.ts +417 -0
  65. package/src/core/auth.ts +40 -0
  66. package/src/core/bodySerializer.ts +88 -0
  67. package/src/core/params.ts +151 -0
  68. package/src/core/pathSerializer.ts +179 -0
  69. package/src/core/types.ts +118 -0
  70. package/src/index.ts +129 -0
  71. package/src/shared-client.ts +13 -0
  72. package/tsconfig.json +25 -0
  73. package/tsdown.config.ts +21 -0
@@ -0,0 +1,246 @@
1
+ import { getManagementBaseUrl, getRegion } from '@storyblok/region-helper';
2
+ import type { Client, Config, RequestOptions } from './types';
3
+ import {
4
+ buildUrl,
5
+ createConfig,
6
+ createInterceptors,
7
+ getParseAs,
8
+ mergeConfigs,
9
+ mergeHeaders,
10
+ setAuthParams,
11
+ } from './utils';
12
+
13
+ type ReqInit = Omit<RequestInit, 'body' | 'headers'> & {
14
+ body?: any;
15
+ headers: ReturnType<typeof mergeHeaders>;
16
+ };
17
+
18
+ export const createClient = (config: Config = {}): Client => {
19
+ let _config = mergeConfigs(createConfig(), config);
20
+
21
+ const getConfig = (): Config => ({ ..._config });
22
+
23
+ const setConfig = (config: Config): Config => {
24
+ _config = mergeConfigs(_config, config);
25
+ return getConfig();
26
+ };
27
+
28
+ const interceptors = createInterceptors<
29
+ Request,
30
+ Response,
31
+ unknown,
32
+ RequestOptions
33
+ >();
34
+
35
+ const request: Client['request'] = async (options) => {
36
+ const opts = {
37
+ ..._config,
38
+ ...options,
39
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
40
+ headers: mergeHeaders(_config.headers, options.headers),
41
+ };
42
+
43
+ // If the baseUrl is not set and we have a space_id, we can attempt toinfer the region
44
+ if (!_config.baseUrl && options.path?.space_id) {
45
+ const region = getRegion(options.path.space_id as number);
46
+ if (region) {
47
+ opts.baseUrl = getManagementBaseUrl(region, 'https');
48
+ }
49
+ }
50
+
51
+ if (opts.security) {
52
+ await setAuthParams({
53
+ ...opts,
54
+ security: opts.security,
55
+ });
56
+ }
57
+
58
+ if (opts.requestValidator) {
59
+ await opts.requestValidator(opts);
60
+ }
61
+
62
+ if (opts.body && opts.bodySerializer) {
63
+ opts.body = opts.bodySerializer(opts.body);
64
+ }
65
+
66
+ // remove Content-Type header if body is empty to avoid sending invalid requests
67
+ if (opts.body === undefined || opts.body === '') {
68
+ opts.headers.delete('Content-Type');
69
+ }
70
+
71
+ const url = buildUrl(opts);
72
+ const requestInit: ReqInit = {
73
+ redirect: 'follow',
74
+ ...opts,
75
+ };
76
+
77
+ let request = new Request(url, requestInit);
78
+
79
+ for (const fn of interceptors.request._fns) {
80
+ if (fn) {
81
+ request = await fn(request, opts);
82
+ }
83
+ }
84
+
85
+ // fetch must be assigned here, otherwise it would throw the error:
86
+ // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
87
+ const _fetch = opts.fetch!;
88
+
89
+ // Execute with retry logic by recreating the request for each attempt
90
+ let response = await executeWithRetry(_fetch, url, requestInit, {
91
+ maxRetries: 3,
92
+ retryDelay: 1000
93
+ });
94
+
95
+ for (const fn of interceptors.response._fns) {
96
+ if (fn) {
97
+ response = await fn(response, request, opts);
98
+ }
99
+ }
100
+
101
+ const result = {
102
+ request,
103
+ response,
104
+ };
105
+
106
+ if (response.ok) {
107
+ if (
108
+ response.status === 204 ||
109
+ response.headers.get('Content-Length') === '0'
110
+ ) {
111
+ return opts.responseStyle === 'data'
112
+ ? {}
113
+ : {
114
+ data: {},
115
+ ...result,
116
+ };
117
+ }
118
+
119
+ const parseAs =
120
+ (opts.parseAs === 'auto'
121
+ ? getParseAs(response.headers.get('Content-Type'))
122
+ : opts.parseAs) ?? 'json';
123
+
124
+ let data: any;
125
+ switch (parseAs) {
126
+ case 'arrayBuffer':
127
+ case 'blob':
128
+ case 'formData':
129
+ case 'json':
130
+ case 'text':
131
+ data = await response[parseAs]();
132
+ break;
133
+ case 'stream':
134
+ return opts.responseStyle === 'data'
135
+ ? response.body
136
+ : {
137
+ data: response.body,
138
+ ...result,
139
+ };
140
+ }
141
+
142
+ if (parseAs === 'json') {
143
+ if (opts.responseValidator) {
144
+ await opts.responseValidator(data);
145
+ }
146
+
147
+ if (opts.responseTransformer) {
148
+ data = await opts.responseTransformer(data);
149
+ }
150
+ }
151
+
152
+ return opts.responseStyle === 'data'
153
+ ? data
154
+ : {
155
+ data,
156
+ ...result,
157
+ };
158
+ }
159
+
160
+ const textError = await response.text();
161
+ let jsonError: unknown;
162
+
163
+ try {
164
+ jsonError = JSON.parse(textError);
165
+ } catch {
166
+ // noop
167
+ }
168
+
169
+ const error = jsonError ?? textError;
170
+ let finalError = error;
171
+
172
+ for (const fn of interceptors.error._fns) {
173
+ if (fn) {
174
+ finalError = (await fn(error, response, request, opts)) as string;
175
+ }
176
+ }
177
+
178
+ finalError = finalError || ({} as string);
179
+
180
+ if (opts.throwOnError) {
181
+ throw finalError;
182
+ }
183
+
184
+ // TODO: we probably want to return error and improve types
185
+ return opts.responseStyle === 'data'
186
+ ? undefined
187
+ : {
188
+ error: finalError,
189
+ ...result,
190
+ };
191
+ };
192
+
193
+ // Helper function to execute fetch with retry logic
194
+ async function executeWithRetry(
195
+ fetchFn: any,
196
+ url: string,
197
+ requestInit: ReqInit,
198
+ retryConfig: { maxRetries: number; retryDelay: number },
199
+ attempt: number = 0
200
+ ): Promise<Response> {
201
+ try {
202
+ const request = new Request(url, requestInit);
203
+ const response = await fetchFn(request);
204
+
205
+ if (response.status === 429 && attempt < retryConfig.maxRetries) {
206
+ const retryAfter = response.headers.get('retry-after');
207
+ const delay = retryAfter ? parseInt(retryAfter) * 1000 : retryConfig.retryDelay;
208
+
209
+ await new Promise(resolve => setTimeout(resolve, delay));
210
+
211
+ // Use the original unconsumed request for retry
212
+ return executeWithRetry(fetchFn, url, requestInit, retryConfig, attempt + 1);
213
+ }
214
+
215
+ return response;
216
+ } catch (error) {
217
+ // If it's a network error and we haven't exceeded retries, try again
218
+ if (attempt < retryConfig.maxRetries) {
219
+ const delay = retryConfig.retryDelay;
220
+ await new Promise(resolve => setTimeout(resolve, delay));
221
+
222
+ // Use the original unconsumed request for retry
223
+ return executeWithRetry(fetchFn, url, requestInit, retryConfig, attempt + 1);
224
+ }
225
+
226
+ throw error;
227
+ }
228
+ }
229
+
230
+ return {
231
+ buildUrl,
232
+ connect: (options) => request({ ...options, method: 'CONNECT' }),
233
+ delete: (options) => request({ ...options, method: 'DELETE' }),
234
+ get: (options) => request({ ...options, method: 'GET' }),
235
+ getConfig,
236
+ head: (options) => request({ ...options, method: 'HEAD' }),
237
+ interceptors,
238
+ options: (options) => request({ ...options, method: 'OPTIONS' }),
239
+ patch: (options) => request({ ...options, method: 'PATCH' }),
240
+ post: (options) => request({ ...options, method: 'POST' }),
241
+ put: (options) => request({ ...options, method: 'PUT' }),
242
+ request,
243
+ setConfig,
244
+ trace: (options) => request({ ...options, method: 'TRACE' }),
245
+ };
246
+ };
@@ -0,0 +1,22 @@
1
+ export type { Auth } from '../core/auth';
2
+ export type { QuerySerializerOptions } from '../core/bodySerializer';
3
+ export {
4
+ formDataBodySerializer,
5
+ jsonBodySerializer,
6
+ urlSearchParamsBodySerializer,
7
+ } from '../core/bodySerializer';
8
+ export { buildClientParams } from '../core/params';
9
+ export { createClient } from './client';
10
+ export type {
11
+ Client,
12
+ ClientOptions,
13
+ Config,
14
+ CreateClientConfig,
15
+ Options,
16
+ OptionsLegacyParser,
17
+ RequestOptions,
18
+ RequestResult,
19
+ ResponseStyle,
20
+ TDataShape,
21
+ } from './types';
22
+ export { createConfig, mergeHeaders } from './utils';
@@ -0,0 +1,222 @@
1
+ import type { Auth } from '../core/auth';
2
+ import type {
3
+ Client as CoreClient,
4
+ Config as CoreConfig,
5
+ } from '../core/types';
6
+ import type { Middleware } from './utils';
7
+
8
+ export type ResponseStyle = 'data' | 'fields';
9
+
10
+ export interface Config<T extends ClientOptions = ClientOptions>
11
+ extends Omit<RequestInit, 'body' | 'headers' | 'method'>,
12
+ CoreConfig {
13
+ /**
14
+ * Base URL for all requests made by this client.
15
+ */
16
+ baseUrl?: T['baseUrl'];
17
+ /**
18
+ * Fetch API implementation. You can use this option to provide a custom
19
+ * fetch instance.
20
+ *
21
+ * @default globalThis.fetch
22
+ */
23
+ fetch?: (request: Request) => ReturnType<typeof fetch>;
24
+ /**
25
+ * Please don't use the Fetch client for Next.js applications. The `next`
26
+ * options won't have any effect.
27
+ *
28
+ * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
29
+ */
30
+ next?: never;
31
+ /**
32
+ * Return the response data parsed in a specified format. By default, `auto`
33
+ * will infer the appropriate method from the `Content-Type` response header.
34
+ * You can override this behavior with any of the {@link Body} methods.
35
+ * Select `stream` if you don't want to parse response data at all.
36
+ *
37
+ * @default 'auto'
38
+ */
39
+ parseAs?:
40
+ | 'arrayBuffer'
41
+ | 'auto'
42
+ | 'blob'
43
+ | 'formData'
44
+ | 'json'
45
+ | 'stream'
46
+ | 'text';
47
+ /**
48
+ * Should we return only data or multiple fields (data, error, response, etc.)?
49
+ *
50
+ * @default 'fields'
51
+ */
52
+ responseStyle?: ResponseStyle;
53
+ /**
54
+ * Throw an error instead of returning it in the response?
55
+ *
56
+ * @default false
57
+ */
58
+ throwOnError?: T['throwOnError'];
59
+ }
60
+
61
+ export interface RequestOptions<
62
+ TResponseStyle extends ResponseStyle = 'fields',
63
+ ThrowOnError extends boolean = boolean,
64
+ Url extends string = string,
65
+ > extends Config<{
66
+ responseStyle: TResponseStyle;
67
+ throwOnError: ThrowOnError;
68
+ }> {
69
+ /**
70
+ * Any body that you want to add to your request.
71
+ *
72
+ * {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
73
+ */
74
+ body?: unknown;
75
+ path?: Record<string, unknown>;
76
+ query?: Record<string, unknown>;
77
+ /**
78
+ * Security mechanism(s) to use for the request.
79
+ */
80
+ security?: ReadonlyArray<Auth>;
81
+ url: Url;
82
+ }
83
+
84
+ export type RequestResult<
85
+ TData = unknown,
86
+ TError = unknown,
87
+ ThrowOnError extends boolean = boolean,
88
+ TResponseStyle extends ResponseStyle = 'fields',
89
+ > = ThrowOnError extends true
90
+ ? Promise<
91
+ TResponseStyle extends 'data'
92
+ ? TData extends Record<string, unknown>
93
+ ? TData[keyof TData]
94
+ : TData
95
+ : {
96
+ data: TData extends Record<string, unknown>
97
+ ? TData[keyof TData]
98
+ : TData;
99
+ request: Request;
100
+ response: Response;
101
+ }
102
+ >
103
+ : Promise<
104
+ TResponseStyle extends 'data'
105
+ ?
106
+ | (TData extends Record<string, unknown>
107
+ ? TData[keyof TData]
108
+ : TData)
109
+ | undefined
110
+ : (
111
+ | {
112
+ data: TData extends Record<string, unknown>
113
+ ? TData[keyof TData]
114
+ : TData;
115
+ error: undefined;
116
+ }
117
+ | {
118
+ data: undefined;
119
+ error: TError extends Record<string, unknown>
120
+ ? TError[keyof TError]
121
+ : TError;
122
+ }
123
+ ) & {
124
+ request: Request;
125
+ response: Response;
126
+ }
127
+ >;
128
+
129
+ export interface ClientOptions {
130
+ baseUrl?: string;
131
+ responseStyle?: ResponseStyle;
132
+ throwOnError?: boolean;
133
+ }
134
+
135
+ type MethodFn = <
136
+ TData = unknown,
137
+ TError = unknown,
138
+ ThrowOnError extends boolean = false,
139
+ TResponseStyle extends ResponseStyle = 'fields',
140
+ >(
141
+ options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, 'method'>,
142
+ ) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
143
+
144
+ type RequestFn = <
145
+ TData = unknown,
146
+ TError = unknown,
147
+ ThrowOnError extends boolean = false,
148
+ TResponseStyle extends ResponseStyle = 'fields',
149
+ >(
150
+ options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, 'method'> &
151
+ Pick<Required<RequestOptions<TResponseStyle, ThrowOnError>>, 'method'>,
152
+ ) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
153
+
154
+ type BuildUrlFn = <
155
+ TData extends {
156
+ body?: unknown;
157
+ path?: Record<string, unknown>;
158
+ query?: Record<string, unknown>;
159
+ url: string;
160
+ },
161
+ >(
162
+ options: Pick<TData, 'url'> & Options<TData>,
163
+ ) => string;
164
+
165
+ export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn> & {
166
+ interceptors: Middleware<Request, Response, unknown, RequestOptions>;
167
+ };
168
+
169
+ /**
170
+ * The `createClientConfig()` function will be called on client initialization
171
+ * and the returned object will become the client's initial configuration.
172
+ *
173
+ * You may want to initialize your client this way instead of calling
174
+ * `setConfig()`. This is useful for example if you're using Next.js
175
+ * to ensure your client always has the correct values.
176
+ */
177
+ export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
178
+ override?: Config<ClientOptions & T>,
179
+ ) => Config<Required<ClientOptions> & T>;
180
+
181
+ export interface TDataShape {
182
+ body?: unknown;
183
+ headers?: unknown;
184
+ path?: unknown;
185
+ query?: unknown;
186
+ url: string;
187
+ }
188
+
189
+ type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
190
+
191
+ export type Options<
192
+ TData extends TDataShape = TDataShape,
193
+ ThrowOnError extends boolean = boolean,
194
+ TResponseStyle extends ResponseStyle = 'fields',
195
+ > = OmitKeys<
196
+ RequestOptions<TResponseStyle, ThrowOnError>,
197
+ 'body' | 'path' | 'query' | 'url'
198
+ > &
199
+ Omit<TData, 'url'>;
200
+
201
+ export type OptionsLegacyParser<
202
+ TData = unknown,
203
+ ThrowOnError extends boolean = boolean,
204
+ TResponseStyle extends ResponseStyle = 'fields',
205
+ > = TData extends { body?: any }
206
+ ? TData extends { headers?: any }
207
+ ? OmitKeys<
208
+ RequestOptions<TResponseStyle, ThrowOnError>,
209
+ 'body' | 'headers' | 'url'
210
+ > &
211
+ TData
212
+ : OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, 'body' | 'url'> &
213
+ TData &
214
+ Pick<RequestOptions<TResponseStyle, ThrowOnError>, 'headers'>
215
+ : TData extends { headers?: any }
216
+ ? OmitKeys<
217
+ RequestOptions<TResponseStyle, ThrowOnError>,
218
+ 'headers' | 'url'
219
+ > &
220
+ TData &
221
+ Pick<RequestOptions<TResponseStyle, ThrowOnError>, 'body'>
222
+ : OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, 'url'> & TData;