@parallelworks/client 7.112.0 → 7.114.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.
package/README.md CHANGED
@@ -106,6 +106,22 @@ export function BucketList() {
106
106
  }
107
107
  ```
108
108
 
109
+ ## Errors
110
+
111
+ The client asks for errors as [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) problem details. Outside a browser it sends `Accept-Language` from the locale environment (`LC_ALL`, `LC_MESSAGES`, `LANG`), or from the `acceptLanguage` option. `toApiError` reads any error, including an older server's error envelope, as an `ApiError` with a stable `code`, `params`, the invalid `fields`, and the server's detail as `message`:
112
+
113
+ ```ts
114
+ import { Client, problemTypeUrl, toApiError } from '@parallelworks/client'
115
+
116
+ const { error } = await client.GET('/api/buckets')
117
+ if (error) {
118
+ const problem = toApiError(error)
119
+ console.error(problem.code, problem.message)
120
+ for (const field of problem.fields) console.error(` ${field.path}: ${field.detail}`)
121
+ console.error(problemTypeUrl(problem, 'https://activate.parallel.works'))
122
+ }
123
+ ```
124
+
109
125
  ## Documentation
110
126
 
111
127
  For full API documentation, visit [https://parallelworks.com/docs](https://parallelworks.com/docs).
package/dist/index.d.ts CHANGED
@@ -1,10 +1,28 @@
1
+ import { type ApiError } from '@parallelworks/problem';
1
2
  import createClient, { type ClientOptions as OpenAPIClientOptions } from 'openapi-fetch';
2
3
  import type { paths } from './types/api';
3
4
  export type { paths };
4
5
  export type { components, operations } from './types/api';
6
+ export { ApiError, codeForStatus, FieldError, fromResponseBody, problemMediaType, toApiError, } from '@parallelworks/problem';
5
7
  type OpenAPIFetchClient = ReturnType<typeof createClient<paths>>;
6
8
  export interface ClientOptions extends Omit<OpenAPIClientOptions, 'baseUrl'> {
9
+ /**
10
+ * The Accept-Language for error details. Outside a browser it defaults to
11
+ * the locale environment (see `acceptLanguageFromEnv`).
12
+ */
13
+ acceptLanguage?: string;
7
14
  }
15
+ /**
16
+ * The language of the POSIX locale environment (LC_ALL, then LC_MESSAGES,
17
+ * then LANG) as a language tag: `ja_JP.UTF-8` is `ja-JP`. Undefined when none
18
+ * is set or the locale is C or POSIX.
19
+ */
20
+ export declare function acceptLanguageFromEnv(env?: Record<string, string | undefined>): string | undefined;
21
+ /**
22
+ * The absolute URL documenting an error's problem type, resolved against the
23
+ * API's base URL. Undefined for `about:blank`, which documents nothing.
24
+ */
25
+ export declare function problemTypeUrl(error: ApiError, baseUrl: string): string | undefined;
8
26
  /** Prefix for Parallel Works API keys */
9
27
  export declare const API_KEY_PREFIX = "pwt_";
10
28
  /** Error thrown when credential parsing fails */
package/dist/index.js CHANGED
@@ -1,4 +1,34 @@
1
+ import { problemMiddleware } from '@parallelworks/problem';
1
2
  import createClient from 'openapi-fetch';
3
+ export { ApiError, codeForStatus, FieldError, fromResponseBody, problemMediaType, toApiError, } from '@parallelworks/problem';
4
+ /**
5
+ * The language of the POSIX locale environment (LC_ALL, then LC_MESSAGES,
6
+ * then LANG) as a language tag: `ja_JP.UTF-8` is `ja-JP`. Undefined when none
7
+ * is set or the locale is C or POSIX.
8
+ */
9
+ export function acceptLanguageFromEnv(env = globalThis.process?.env ?? {}) {
10
+ const locale = env['LC_ALL'] || env['LC_MESSAGES'] || env['LANG'];
11
+ const tag = locale?.split('.')[0]?.split('@')[0];
12
+ if (!tag || tag === 'C' || tag === 'POSIX' || !/^[\w-]+$/.test(tag)) {
13
+ return undefined;
14
+ }
15
+ return tag.replace(/_/g, '-');
16
+ }
17
+ /**
18
+ * The absolute URL documenting an error's problem type, resolved against the
19
+ * API's base URL. Undefined for `about:blank`, which documents nothing.
20
+ */
21
+ export function problemTypeUrl(error, baseUrl) {
22
+ if (error.type === 'about:blank') {
23
+ return undefined;
24
+ }
25
+ try {
26
+ return new URL(error.type, baseUrl).toString();
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ }
2
32
  /** Prefix for Parallel Works API keys */
3
33
  export const API_KEY_PREFIX = 'pwt_';
4
34
  /** Error thrown when credential parsing fails */
@@ -236,22 +266,28 @@ export class Client {
236
266
  * @returns Configured openapi-fetch client instance
237
267
  */
238
268
  build() {
269
+ const { acceptLanguage: language, ...options } = this.options;
270
+ const acceptLanguage = language ??
271
+ (typeof document === 'undefined' ? acceptLanguageFromEnv() : undefined);
239
272
  const client = createClient({
240
273
  baseUrl: this.baseUrl,
241
- ...this.options,
274
+ ...options,
242
275
  headers: {
243
- ...this.options.headers,
276
+ ...(acceptLanguage && { 'Accept-Language': acceptLanguage }),
277
+ ...options.headers,
244
278
  ...(this.authHeader && { Authorization: this.authHeader }),
245
279
  },
246
280
  });
281
+ client.use(problemMiddleware);
247
282
  // Attach HTTP status code to error response bodies so consumers
248
283
  // (e.g. SWR hooks) can distinguish 404s from other errors.
249
284
  // openapi-fetch parses the body after middleware, so we replace the
250
285
  // response with one whose body includes the status field.
251
- // Also guarantee `message` is populated — upstream infrastructure (WAFs,
252
- // proxies) can return non-2xx with an empty body, which would otherwise
253
- // short-circuit openapi-fetch (it returns `error: undefined` when
254
- // Content-Length is 0) and leave consumers with no error to react to.
286
+ // Also guarantee `message` is populated, from a problem's detail when it
287
+ // has one: upstream infrastructure (WAFs, proxies) can return non-2xx with
288
+ // an empty body, which would otherwise short-circuit openapi-fetch (it
289
+ // returns `error: undefined` when Content-Length is 0) and leave consumers
290
+ // with no error to react to.
255
291
  const statusMiddleware = {
256
292
  async onResponse({ response }) {
257
293
  if (!response.ok) {
@@ -262,7 +298,8 @@ export class Client {
262
298
  record['status'] = response.status;
263
299
  if (typeof record['message'] !== 'string' || !record['message']) {
264
300
  record['message'] =
265
- response.statusText ||
301
+ (typeof record['detail'] === 'string' && record['detail']) ||
302
+ response.statusText ||
266
303
  `Request failed with status ${response.status}`;
267
304
  }
268
305
  // Strip Content-Length from the original headers — we're replacing
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,108 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { acceptLanguageFromEnv, Client, problemMediaType, problemTypeUrl, toApiError, } from './index';
3
+ function respond(status, body, contentType) {
4
+ const requests = [];
5
+ const fetch = async (input) => {
6
+ requests.push(input);
7
+ return new Response(body, {
8
+ status,
9
+ statusText: status === 502 ? 'Bad Gateway' : '',
10
+ headers: { 'Content-Type': contentType },
11
+ });
12
+ };
13
+ return { fetch, requests };
14
+ }
15
+ async function failedRequest(status, body, contentType = problemMediaType) {
16
+ const { fetch, requests } = respond(status, body, contentType);
17
+ const client = new Client('https://activate.parallel.works', {
18
+ fetch,
19
+ acceptLanguage: 'ja-JP',
20
+ }).withToken('a.b.c');
21
+ const { error } = await client.GET('/api/workflows');
22
+ return { error: toApiError(error), raw: error, request: requests[0] };
23
+ }
24
+ describe('Client', () => {
25
+ it('asks for problem details in the chosen language', async () => {
26
+ const { request } = await failedRequest(404, '{}');
27
+ expect(request.headers.get('Accept')).toContain(problemMediaType);
28
+ expect(request.headers.get('Accept-Language')).toBe('ja-JP');
29
+ });
30
+ it('reads a problem', async () => {
31
+ const { error, raw } = await failedRequest(404, JSON.stringify({
32
+ type: '/problems/activate/workflow_not_found',
33
+ status: 404,
34
+ detail: 'ワークフローが見つかりません',
35
+ code: 'workflow_not_found',
36
+ params: { name: 'x' },
37
+ }));
38
+ expect(error.code).toBe('workflow_not_found');
39
+ expect(error.status).toBe(404);
40
+ expect(error.message).toBe('ワークフローが見つかりません');
41
+ expect(error.params).toEqual({ name: 'x' });
42
+ expect(raw).toMatchObject({ message: 'ワークフローが見つかりません' });
43
+ expect(problemTypeUrl(error, 'https://activate.parallel.works')).toBe('https://activate.parallel.works/problems/activate/workflow_not_found');
44
+ });
45
+ it('derives the code of an about:blank problem from its status', async () => {
46
+ const { error } = await failedRequest(403, JSON.stringify({ type: 'about:blank', status: 403, title: 'Forbidden' }));
47
+ expect(error.code).toBe('forbidden');
48
+ expect(problemTypeUrl(error, 'https://activate.parallel.works')).toBe(undefined);
49
+ });
50
+ it('reads the invalid fields of a validation problem', async () => {
51
+ const { error } = await failedRequest(422, JSON.stringify({
52
+ type: '/problems/activate/validation',
53
+ status: 422,
54
+ detail: 'validation failed',
55
+ code: 'validation',
56
+ errors: [
57
+ {
58
+ type: '/problems/activate/too_long',
59
+ code: 'too_long',
60
+ detail: 'too long',
61
+ pointer: '#/items/0/name',
62
+ params: { max: 3 },
63
+ },
64
+ {
65
+ type: '/problems/activate/required',
66
+ code: 'required',
67
+ parameter: 'org',
68
+ in: 'query',
69
+ },
70
+ ],
71
+ }));
72
+ expect(error.code).toBe('validation');
73
+ expect(error.fields.map(f => [f.path, f.code, f.params])).toEqual([
74
+ ['items[0].name', 'too_long', { max: 3 }],
75
+ ['org', 'required', {}],
76
+ ]);
77
+ });
78
+ it('reads the older envelope', async () => {
79
+ const { error } = await failedRequest(404, JSON.stringify({
80
+ error: true,
81
+ message: 'Workflow not found',
82
+ code: 'workflow_not_found',
83
+ }), 'application/json');
84
+ expect(error.code).toBe('workflow_not_found');
85
+ expect(error.message).toBe('Workflow not found');
86
+ });
87
+ it("reads a proxy's page", async () => {
88
+ const { error } = await failedRequest(502, '<html><body>Bad Gateway</body></html>', 'text/html');
89
+ expect(error.status).toBe(502);
90
+ expect(error.code).toBe('internal');
91
+ expect(error.message).toBe('Bad Gateway');
92
+ });
93
+ });
94
+ describe('acceptLanguageFromEnv', () => {
95
+ it.each([
96
+ [{ LANG: 'ja_JP.UTF-8' }, 'ja-JP'],
97
+ [{ LANG: 'de_DE.UTF-8@euro' }, 'de-DE'],
98
+ [{ LANG: 'es' }, 'es'],
99
+ [{ LANG: 'C' }, undefined],
100
+ [{ LANG: 'C.UTF-8' }, undefined],
101
+ [{ LANG: 'POSIX' }, undefined],
102
+ [{}, undefined],
103
+ [{ LC_MESSAGES: 'ko_KR.UTF-8', LANG: 'en_US.UTF-8' }, 'ko-KR'],
104
+ [{ LC_ALL: 'fr_FR.UTF-8', LC_MESSAGES: 'ko_KR.UTF-8' }, 'fr-FR'],
105
+ ])('%o is %s', (env, want) => {
106
+ expect(acceptLanguageFromEnv(env)).toBe(want);
107
+ });
108
+ });