@smartcrab/management-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.
- package/LICENSE +202 -0
- package/dist/client.d.ts +176 -0
- package/dist/client.js +230 -0
- package/dist/client.test.d.ts +1 -0
- package/dist/client.test.js +1026 -0
- package/dist/errors.d.ts +44 -0
- package/dist/errors.js +6 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +7 -0
- package/dist/paginate.d.ts +40 -0
- package/dist/paginate.js +54 -0
- package/dist/paginate.test.d.ts +1 -0
- package/dist/paginate.test.js +113 -0
- package/dist/result.d.ts +28 -0
- package/dist/result.js +4 -0
- package/dist/transport.d.ts +81 -0
- package/dist/transport.js +144 -0
- package/package.json +41 -0
- package/src/client.test.ts +1114 -0
- package/src/client.ts +934 -0
- package/src/errors.ts +53 -0
- package/src/index.ts +59 -0
- package/src/paginate.test.ts +123 -0
- package/src/paginate.ts +75 -0
- package/src/result.ts +28 -0
- package/src/transport.ts +294 -0
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typed error union for `@smartcrab/management-client` (IMPL_NOTES §3:
|
|
3
|
+
* discriminated union, snake_case `type`, `retryable?: true` on transient
|
|
4
|
+
* infrastructure failures).
|
|
5
|
+
*/
|
|
6
|
+
/** The server answered with a non-2xx status. RFC 9457 Problem Details fields are mapped when present. */
|
|
7
|
+
export interface ApiError {
|
|
8
|
+
readonly type: "api_error";
|
|
9
|
+
/** HTTP status code returned by the server. */
|
|
10
|
+
readonly status: number;
|
|
11
|
+
/** Problem Details `code` (snake_case) when the server sent one; otherwise `http_<status>`. */
|
|
12
|
+
readonly code: string;
|
|
13
|
+
/** Problem Details `title`, or a generic title derived from the status. */
|
|
14
|
+
readonly title: string;
|
|
15
|
+
/** Problem Details `detail` (safe, server-authored message) when present. */
|
|
16
|
+
readonly detail?: string;
|
|
17
|
+
/** RFC 9457 `type` URI when the body was a Problem Details document. */
|
|
18
|
+
readonly problemType?: string;
|
|
19
|
+
/** Correlating request id (`req_...`) from the body or the `x-request-id` header. */
|
|
20
|
+
readonly requestId?: string;
|
|
21
|
+
/** 429 and 5xx responses: idempotent requests may be retried with backoff. */
|
|
22
|
+
readonly retryable?: true;
|
|
23
|
+
}
|
|
24
|
+
/** The request never received an HTTP response (DNS failure, connection reset, abort, ...). */
|
|
25
|
+
export interface NetworkError {
|
|
26
|
+
readonly type: "network_error";
|
|
27
|
+
readonly message: string;
|
|
28
|
+
readonly retryable: true;
|
|
29
|
+
}
|
|
30
|
+
/** A 2xx response whose body did not conform to the route's contract schema (never trust the wire). */
|
|
31
|
+
export interface InvalidResponseError {
|
|
32
|
+
readonly type: "invalid_response";
|
|
33
|
+
readonly status: number;
|
|
34
|
+
readonly requestId?: string;
|
|
35
|
+
/** Human-readable schema violation summaries (`path: message`). */
|
|
36
|
+
readonly issues: readonly string[];
|
|
37
|
+
}
|
|
38
|
+
/** Client-side request validation failed; nothing was sent over the wire. */
|
|
39
|
+
export interface InvalidRequestError {
|
|
40
|
+
readonly type: "invalid_request";
|
|
41
|
+
/** Human-readable schema violation summaries (`path: message`). */
|
|
42
|
+
readonly issues: readonly string[];
|
|
43
|
+
}
|
|
44
|
+
export type ManagementClientError = ApiError | NetworkError | InvalidResponseError | InvalidRequestError;
|
package/dist/errors.js
ADDED
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@smartcrab/management-client` — typed client for the Management API
|
|
3
|
+
* (design.md §26). See `createManagementClient` for the entry point.
|
|
4
|
+
*/
|
|
5
|
+
export { createManagementClient } from "./client.js";
|
|
6
|
+
export type { AuditEventListParams, BillingCheckoutSessionCreateInput, BillingPortalSessionCreateInput, ClientCreateInput, ClientListParams, ClientUpdateInput, ConnectionCreateInput, ConnectionListParams, ConnectionUpdateInput, DomainCreateInput, DomainListParams, DomainUpdateInput, EnvironmentCreateInput, EnvironmentListParams, EnvironmentUpdateInput, ManagementClient, ManagementClientOptions, MauUsageParams, PaginationParams, ProjectCreateInput, ProjectListParams, ProjectUpdateInput, RpMigration, RpMigrationDisableInput, UserBlockInput, UserCreateInput, UserExportJobCreateInput, UserImportJobCreateInput, UserListParams, UserUpdateInput, WebhookCreateInput, WebhookDeliveryListParams, WebhookListParams, WebhookTestInput, WebhookUpdateInput, WorkspaceCreateInput, WorkspaceMemberListParams, WorkspaceListParams, WorkspaceUpdateInput, WriteOptions, } from "./client.js";
|
|
7
|
+
export type { ApiError, InvalidRequestError, InvalidResponseError, ManagementClientError, NetworkError, } from "./errors.js";
|
|
8
|
+
export { collectAll, DEFAULT_MAX_PAGES, paginate } from "./paginate.js";
|
|
9
|
+
export type { PageFetcher, PaginateOptions } from "./paginate.js";
|
|
10
|
+
export type { Failure, Result, ResultAsync, Success } from "./result.js";
|
|
11
|
+
export { fail, isFailure, isSuccess, succeed } from "./result.js";
|
|
12
|
+
export type { InputOf, ManagementResponse } from "./transport.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@smartcrab/management-client` — typed client for the Management API
|
|
3
|
+
* (design.md §26). See `createManagementClient` for the entry point.
|
|
4
|
+
*/
|
|
5
|
+
export { createManagementClient } from "./client.js";
|
|
6
|
+
export { collectAll, DEFAULT_MAX_PAGES, paginate } from "./paginate.js";
|
|
7
|
+
export { fail, isFailure, isSuccess, succeed } from "./result.js";
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { CursorPage } from "@smartcrab/contracts-management";
|
|
2
|
+
import type { ManagementClientError } from "./errors.js";
|
|
3
|
+
import type { Result, ResultAsync } from "./result.js";
|
|
4
|
+
import type { ManagementResponse } from "./transport.js";
|
|
5
|
+
/**
|
|
6
|
+
* Cursor pagination helpers (design.md §26.3: cursor pagination, max page
|
|
7
|
+
* size 100). `paginate` follows `next_cursor` until the server returns
|
|
8
|
+
* `null`; `collectAll` additionally gathers every item, bounded by
|
|
9
|
+
* `maxPages` so a misbehaving cursor cannot loop forever.
|
|
10
|
+
*/
|
|
11
|
+
/** Hard ceiling on pages fetched per paginated traversal. */
|
|
12
|
+
export declare const DEFAULT_MAX_PAGES = 100;
|
|
13
|
+
export interface PaginateOptions {
|
|
14
|
+
/** Maximum number of pages to fetch before stopping. Defaults to {@link DEFAULT_MAX_PAGES}. */
|
|
15
|
+
readonly maxPages?: number;
|
|
16
|
+
}
|
|
17
|
+
/** Fetches one page; `cursor` is `null` for the first page. */
|
|
18
|
+
export type PageFetcher<Item> = (cursor: string | null) => ResultAsync<ManagementResponse<CursorPage<Item>>, ManagementClientError>;
|
|
19
|
+
/**
|
|
20
|
+
* Async iterator over cursor-paginated list routes. Yields one
|
|
21
|
+
* `Result<ManagementResponse<CursorPage<Item>>>` per fetched page. A failure
|
|
22
|
+
* is yielded exactly once and terminates the iteration; iteration also stops
|
|
23
|
+
* when `next_cursor` is `null` or the `maxPages` bound is reached.
|
|
24
|
+
*
|
|
25
|
+
* ```ts
|
|
26
|
+
* for await (const page of paginate((cursor) =>
|
|
27
|
+
* client.listWorkspaces({ ...(cursor !== null ? { cursor } : {}) }),
|
|
28
|
+
* )) {
|
|
29
|
+
* if (isFailure(page)) { ...; break; }
|
|
30
|
+
* console.log(page.value.data.items.length);
|
|
31
|
+
* }
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export declare function paginate<Item>(fetchPage: PageFetcher<Item>, options?: PaginateOptions): AsyncGenerator<Result<ManagementResponse<CursorPage<Item>>, ManagementClientError>, void>;
|
|
35
|
+
/**
|
|
36
|
+
* Collects every item across all pages into a single array. Stops (keeping
|
|
37
|
+
* what it has) once `maxPages` pages have been fetched; the first page
|
|
38
|
+
* failure is returned as the overall failure.
|
|
39
|
+
*/
|
|
40
|
+
export declare const collectAll: <Item>(fetchPage: PageFetcher<Item>, options?: PaginateOptions) => ResultAsync<readonly Item[], ManagementClientError>;
|
package/dist/paginate.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { isFailure, succeed } from "./result.js";
|
|
2
|
+
/**
|
|
3
|
+
* Cursor pagination helpers (design.md §26.3: cursor pagination, max page
|
|
4
|
+
* size 100). `paginate` follows `next_cursor` until the server returns
|
|
5
|
+
* `null`; `collectAll` additionally gathers every item, bounded by
|
|
6
|
+
* `maxPages` so a misbehaving cursor cannot loop forever.
|
|
7
|
+
*/
|
|
8
|
+
/** Hard ceiling on pages fetched per paginated traversal. */
|
|
9
|
+
export const DEFAULT_MAX_PAGES = 100;
|
|
10
|
+
/**
|
|
11
|
+
* Async iterator over cursor-paginated list routes. Yields one
|
|
12
|
+
* `Result<ManagementResponse<CursorPage<Item>>>` per fetched page. A failure
|
|
13
|
+
* is yielded exactly once and terminates the iteration; iteration also stops
|
|
14
|
+
* when `next_cursor` is `null` or the `maxPages` bound is reached.
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* for await (const page of paginate((cursor) =>
|
|
18
|
+
* client.listWorkspaces({ ...(cursor !== null ? { cursor } : {}) }),
|
|
19
|
+
* )) {
|
|
20
|
+
* if (isFailure(page)) { ...; break; }
|
|
21
|
+
* console.log(page.value.data.items.length);
|
|
22
|
+
* }
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
export async function* paginate(fetchPage, options = {}) {
|
|
26
|
+
const maxPages = options.maxPages ?? DEFAULT_MAX_PAGES;
|
|
27
|
+
let cursor = null;
|
|
28
|
+
let fetched = 0;
|
|
29
|
+
while (fetched < maxPages) {
|
|
30
|
+
const result = await fetchPage(cursor);
|
|
31
|
+
fetched += 1;
|
|
32
|
+
yield result;
|
|
33
|
+
if (isFailure(result))
|
|
34
|
+
return;
|
|
35
|
+
const next = result.value.data.next_cursor;
|
|
36
|
+
if (next === null)
|
|
37
|
+
return;
|
|
38
|
+
cursor = next;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Collects every item across all pages into a single array. Stops (keeping
|
|
43
|
+
* what it has) once `maxPages` pages have been fetched; the first page
|
|
44
|
+
* failure is returned as the overall failure.
|
|
45
|
+
*/
|
|
46
|
+
export const collectAll = async (fetchPage, options = {}) => {
|
|
47
|
+
const items = [];
|
|
48
|
+
for await (const page of paginate(fetchPage, options)) {
|
|
49
|
+
if (isFailure(page))
|
|
50
|
+
return page;
|
|
51
|
+
items.push(...page.value.data.items);
|
|
52
|
+
}
|
|
53
|
+
return succeed(items);
|
|
54
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
import { collectAll, paginate } from "./paginate.js";
|
|
3
|
+
import { fail, isFailure, isSuccess, succeed } from "./result.js";
|
|
4
|
+
const pageOf = (items, nextCursor) => ({
|
|
5
|
+
data: { items, next_cursor: nextCursor },
|
|
6
|
+
requestId: undefined,
|
|
7
|
+
etag: undefined,
|
|
8
|
+
});
|
|
9
|
+
const apiError = (status) => ({
|
|
10
|
+
type: "api_error",
|
|
11
|
+
status,
|
|
12
|
+
code: `http_${status}`,
|
|
13
|
+
title: "Internal Server Error",
|
|
14
|
+
});
|
|
15
|
+
describe("paginate (design.md §26.3 cursor pagination)", () => {
|
|
16
|
+
test("follows next_cursor until null", async () => {
|
|
17
|
+
const cursors = [];
|
|
18
|
+
const pages = [pageOf([1, 2], "c2"), pageOf([3, 4], "c3"), pageOf([5], null)];
|
|
19
|
+
const fetchPage = (cursor) => {
|
|
20
|
+
cursors.push(cursor);
|
|
21
|
+
const page = pages[cursors.length - 1];
|
|
22
|
+
if (page === undefined)
|
|
23
|
+
return Promise.resolve(fail(apiError(500)));
|
|
24
|
+
return Promise.resolve(succeed(page));
|
|
25
|
+
};
|
|
26
|
+
const seen = [];
|
|
27
|
+
for await (const page of paginate(fetchPage)) {
|
|
28
|
+
if (isFailure(page))
|
|
29
|
+
throw new Error("unexpected failure");
|
|
30
|
+
seen.push(...page.value.data.items);
|
|
31
|
+
}
|
|
32
|
+
expect(seen).toEqual([1, 2, 3, 4, 5]);
|
|
33
|
+
expect(cursors).toEqual([null, "c2", "c3"]);
|
|
34
|
+
});
|
|
35
|
+
test("stops at the maxPages bound even when cursors keep coming", async () => {
|
|
36
|
+
let calls = 0;
|
|
37
|
+
const fetchPage = () => {
|
|
38
|
+
calls += 1;
|
|
39
|
+
return Promise.resolve(succeed(pageOf([calls], "again")));
|
|
40
|
+
};
|
|
41
|
+
const seen = [];
|
|
42
|
+
for await (const page of paginate(fetchPage, { maxPages: 3 })) {
|
|
43
|
+
if (isFailure(page))
|
|
44
|
+
throw new Error("unexpected failure");
|
|
45
|
+
seen.push(...page.value.data.items);
|
|
46
|
+
}
|
|
47
|
+
expect(calls).toBe(3);
|
|
48
|
+
expect(seen).toEqual([1, 2, 3]);
|
|
49
|
+
});
|
|
50
|
+
test("yields a failure exactly once, then terminates", async () => {
|
|
51
|
+
const pages = [pageOf([1], "c2")];
|
|
52
|
+
let calls = 0;
|
|
53
|
+
const fetchPage = () => {
|
|
54
|
+
calls += 1;
|
|
55
|
+
const first = pages[calls - 1];
|
|
56
|
+
if (first === undefined)
|
|
57
|
+
return Promise.resolve(fail(apiError(500)));
|
|
58
|
+
return Promise.resolve(succeed(first));
|
|
59
|
+
};
|
|
60
|
+
const yielded = [];
|
|
61
|
+
for await (const page of paginate(fetchPage)) {
|
|
62
|
+
yielded.push(page.type);
|
|
63
|
+
}
|
|
64
|
+
expect(yielded).toEqual(["Success", "Failure"]);
|
|
65
|
+
expect(calls).toBe(2);
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
describe("collectAll", () => {
|
|
69
|
+
test("gathers items across pages", async () => {
|
|
70
|
+
const pages = [pageOf([1, 2], "c2"), pageOf([3], null)];
|
|
71
|
+
let calls = 0;
|
|
72
|
+
const fetchPage = () => {
|
|
73
|
+
const page = pages[calls];
|
|
74
|
+
calls += 1;
|
|
75
|
+
if (page === undefined)
|
|
76
|
+
return Promise.resolve(fail(apiError(500)));
|
|
77
|
+
return Promise.resolve(succeed(page));
|
|
78
|
+
};
|
|
79
|
+
const result = await collectAll(fetchPage);
|
|
80
|
+
expect(isSuccess(result)).toBe(true);
|
|
81
|
+
if (isSuccess(result))
|
|
82
|
+
expect(result.value).toEqual([1, 2, 3]);
|
|
83
|
+
});
|
|
84
|
+
test("stops at the bound and keeps what it has", async () => {
|
|
85
|
+
let calls = 0;
|
|
86
|
+
const fetchPage = () => {
|
|
87
|
+
calls += 1;
|
|
88
|
+
return Promise.resolve(succeed(pageOf([calls], "more")));
|
|
89
|
+
};
|
|
90
|
+
const result = await collectAll(fetchPage, { maxPages: 2 });
|
|
91
|
+
expect(isSuccess(result)).toBe(true);
|
|
92
|
+
if (isSuccess(result))
|
|
93
|
+
expect(result.value).toEqual([1, 2]);
|
|
94
|
+
expect(calls).toBe(2);
|
|
95
|
+
});
|
|
96
|
+
test("returns the first page failure", async () => {
|
|
97
|
+
const fetchPage = () => Promise.resolve(fail(apiError(503)));
|
|
98
|
+
const result = await collectAll(fetchPage);
|
|
99
|
+
expect(isFailure(result)).toBe(true);
|
|
100
|
+
if (isFailure(result)) {
|
|
101
|
+
expect(result.error.type).toBe("api_error");
|
|
102
|
+
if (result.error.type === "api_error")
|
|
103
|
+
expect(result.error.status).toBe(503);
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
test("empty first page yields an empty array", async () => {
|
|
107
|
+
const fetchPage = () => Promise.resolve(succeed(pageOf([], null)));
|
|
108
|
+
const result = await collectAll(fetchPage);
|
|
109
|
+
expect(isSuccess(result)).toBe(true);
|
|
110
|
+
if (isSuccess(result))
|
|
111
|
+
expect(result.value).toEqual([]);
|
|
112
|
+
});
|
|
113
|
+
});
|
package/dist/result.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local Result type for `@smartcrab/management-client`.
|
|
3
|
+
*
|
|
4
|
+
* The shape is deliberately identical to `@praha/byethrow`'s
|
|
5
|
+
* `Result.Result<T, E>` (`{ type: "Success", value } | { type: "Failure",
|
|
6
|
+
* error }`). This package's manifest only declares
|
|
7
|
+
* `@smartcrab/contracts-management`, and pnpm's strict `node_modules`
|
|
8
|
+
* layout makes `@praha/byethrow` unresolvable here, so the type is
|
|
9
|
+
* re-declared locally. Because the shapes match, every Result produced by
|
|
10
|
+
* this client is structurally assignable to byethrow's `Result<T, E>` and
|
|
11
|
+
* can be consumed by `Result.isSuccess` / `Result.isFailure` / combinators
|
|
12
|
+
* from `@smartcrab/result` (that is exactly what `@smartcrab/cli`
|
|
13
|
+
* does).
|
|
14
|
+
*/
|
|
15
|
+
export type Success<T> = {
|
|
16
|
+
readonly type: "Success";
|
|
17
|
+
readonly value: T;
|
|
18
|
+
};
|
|
19
|
+
export type Failure<E> = {
|
|
20
|
+
readonly type: "Failure";
|
|
21
|
+
readonly error: E;
|
|
22
|
+
};
|
|
23
|
+
export type Result<T, E> = Success<T> | Failure<E>;
|
|
24
|
+
export type ResultAsync<T, E> = Promise<Result<T, E>>;
|
|
25
|
+
export declare const succeed: <T>(value: T) => Success<T>;
|
|
26
|
+
export declare const fail: <E>(error: E) => Failure<E>;
|
|
27
|
+
export declare const isSuccess: <T, E>(result: Result<T, E>) => result is Success<T>;
|
|
28
|
+
export declare const isFailure: <T, E>(result: Result<T, E>) => result is Failure<E>;
|
package/dist/result.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { ApiError, InvalidRequestError, InvalidResponseError, ManagementClientError } from "./errors.js";
|
|
2
|
+
import type { ResultAsync } from "./result.js";
|
|
3
|
+
/**
|
|
4
|
+
* Transport layer: builds wire requests, executes them through an injectable
|
|
5
|
+
* `fetch`, and classifies responses. Contains no `try`/`catch` statements
|
|
6
|
+
* (design.md §5.2, enforced by scripts/check-backend-error-style.ts): every
|
|
7
|
+
* exception-prone boundary (`fetch`, body reads, `JSON.parse`) is isolated
|
|
8
|
+
* inside promise callbacks whose rejections are mapped to typed errors.
|
|
9
|
+
*/
|
|
10
|
+
export type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE";
|
|
11
|
+
export interface TransportConfig {
|
|
12
|
+
/** Normalized (no trailing slash) API root, e.g. `https://api.example-auth.com/v1`. */
|
|
13
|
+
readonly baseUrl: string;
|
|
14
|
+
readonly apiKey: string;
|
|
15
|
+
readonly fetchFn: typeof fetch;
|
|
16
|
+
}
|
|
17
|
+
export interface RequestSpec {
|
|
18
|
+
readonly method: HttpMethod;
|
|
19
|
+
/** Absolute path beginning with `/`, e.g. `/workspaces/wsp_...`. */
|
|
20
|
+
readonly path: string;
|
|
21
|
+
readonly query?: Readonly<Record<string, string | number | boolean | undefined>>;
|
|
22
|
+
/** Pre-validated JSON body. */
|
|
23
|
+
readonly body?: unknown;
|
|
24
|
+
readonly idempotencyKey?: string;
|
|
25
|
+
readonly ifMatch?: string;
|
|
26
|
+
}
|
|
27
|
+
export interface RawResponse {
|
|
28
|
+
readonly status: number;
|
|
29
|
+
readonly bodyText: string;
|
|
30
|
+
readonly requestId: string | undefined;
|
|
31
|
+
readonly etag: string | undefined;
|
|
32
|
+
}
|
|
33
|
+
/** Successful, schema-validated response plus the correlation metadata every result must surface. */
|
|
34
|
+
export interface ManagementResponse<T> {
|
|
35
|
+
readonly data: T;
|
|
36
|
+
/** `x-request-id` response header (design.md §26.3: attached to all responses). */
|
|
37
|
+
readonly requestId: string | undefined;
|
|
38
|
+
/** `etag` response header, for subsequent conditional `If-Match` updates (design.md §26.3). */
|
|
39
|
+
readonly etag: string | undefined;
|
|
40
|
+
}
|
|
41
|
+
export interface ParseIssue {
|
|
42
|
+
readonly path: readonly PropertyKey[];
|
|
43
|
+
readonly message: string;
|
|
44
|
+
}
|
|
45
|
+
export interface ParseSuccess<T> {
|
|
46
|
+
readonly success: true;
|
|
47
|
+
readonly data: T;
|
|
48
|
+
}
|
|
49
|
+
export interface ParseFailure {
|
|
50
|
+
readonly success: false;
|
|
51
|
+
readonly error: {
|
|
52
|
+
readonly issues: readonly ParseIssue[];
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export type ParseResult<T> = ParseSuccess<T> | ParseFailure;
|
|
56
|
+
/** Structural minimum of a zod schema: anything with a compatible `safeParse`. */
|
|
57
|
+
export interface Schema<T> {
|
|
58
|
+
safeParse(input: unknown): ParseResult<T>;
|
|
59
|
+
}
|
|
60
|
+
/** Structural equivalent of zod v4's `z.input<S>` (identical to zod's own definition). */
|
|
61
|
+
export type InputOf<S> = S extends {
|
|
62
|
+
readonly _zod: {
|
|
63
|
+
readonly input: infer I;
|
|
64
|
+
};
|
|
65
|
+
} ? I : never;
|
|
66
|
+
export declare const formatIssues: (error: {
|
|
67
|
+
readonly issues: readonly ParseIssue[];
|
|
68
|
+
}) => readonly string[];
|
|
69
|
+
export declare const buildUrl: (baseUrl: string, path: string, query: Readonly<Record<string, string | number | boolean | undefined>> | undefined) => string;
|
|
70
|
+
/** Headers for one request. The API key is only ever placed in `authorization` and never logged. */
|
|
71
|
+
export declare const buildHeaders: (config: TransportConfig, spec: RequestSpec) => Record<string, string>;
|
|
72
|
+
/** Maps a non-2xx response to a typed `api_error`, parsing RFC 9457 Problem Details when present. */
|
|
73
|
+
export declare const apiErrorFromRaw: (raw: RawResponse, bodyJson: unknown) => ApiError;
|
|
74
|
+
export declare const invalidResponse: (status: number, requestId: string | undefined, issues: readonly string[]) => InvalidResponseError;
|
|
75
|
+
export declare const invalidRequest: (issues: readonly string[]) => InvalidRequestError;
|
|
76
|
+
/**
|
|
77
|
+
* Sends one request and validates the success body against `schema`
|
|
78
|
+
* (safeParse — never trust the wire). Non-2xx responses map to `api_error`
|
|
79
|
+
* with Problem Details fields; transport failures map to `network_error`.
|
|
80
|
+
*/
|
|
81
|
+
export declare const send: <T>(config: TransportConfig, spec: RequestSpec, schema: Schema<T>) => ResultAsync<ManagementResponse<T>, ManagementClientError>;
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { problemDetailsSchema } from "@smartcrab/contracts-management";
|
|
2
|
+
import { fail, succeed } from "./result.js";
|
|
3
|
+
const formatIssue = (issue) => {
|
|
4
|
+
const path = issue.path.map((segment) => String(segment)).join(".");
|
|
5
|
+
return path.length > 0 ? `${path}: ${issue.message}` : issue.message;
|
|
6
|
+
};
|
|
7
|
+
export const formatIssues = (error) => error.issues.map(formatIssue);
|
|
8
|
+
// ---------------------------------------------------------------------------
|
|
9
|
+
// URL & header construction (total functions — no throwing operations)
|
|
10
|
+
// ---------------------------------------------------------------------------
|
|
11
|
+
export const buildUrl = (baseUrl, path, query) => {
|
|
12
|
+
const base = `${baseUrl}${path}`;
|
|
13
|
+
if (query === undefined)
|
|
14
|
+
return base;
|
|
15
|
+
const params = new URLSearchParams();
|
|
16
|
+
for (const [key, value] of Object.entries(query)) {
|
|
17
|
+
if (value !== undefined)
|
|
18
|
+
params.set(key, String(value));
|
|
19
|
+
}
|
|
20
|
+
const serialized = params.toString();
|
|
21
|
+
return serialized.length > 0 ? `${base}?${serialized}` : base;
|
|
22
|
+
};
|
|
23
|
+
/** Headers for one request. The API key is only ever placed in `authorization` and never logged. */
|
|
24
|
+
export const buildHeaders = (config, spec) => ({
|
|
25
|
+
authorization: `Bearer ${config.apiKey}`,
|
|
26
|
+
accept: "application/json",
|
|
27
|
+
...(spec.body !== undefined ? { "content-type": "application/json" } : {}),
|
|
28
|
+
...(spec.idempotencyKey !== undefined ? { "idempotency-key": spec.idempotencyKey } : {}),
|
|
29
|
+
...(spec.ifMatch !== undefined ? { "if-match": spec.ifMatch } : {}),
|
|
30
|
+
});
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
// Error constructors
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
const describeCause = (cause) => cause instanceof Error ? cause.message : String(cause);
|
|
35
|
+
const networkError = (context, cause) => ({
|
|
36
|
+
type: "network_error",
|
|
37
|
+
message: `${context}: ${describeCause(cause)}`,
|
|
38
|
+
retryable: true,
|
|
39
|
+
});
|
|
40
|
+
const FALLBACK_TITLES = {
|
|
41
|
+
400: "Bad Request",
|
|
42
|
+
401: "Unauthorized",
|
|
43
|
+
403: "Forbidden",
|
|
44
|
+
404: "Not Found",
|
|
45
|
+
405: "Method Not Allowed",
|
|
46
|
+
409: "Conflict",
|
|
47
|
+
410: "Gone",
|
|
48
|
+
422: "Unprocessable Content",
|
|
49
|
+
429: "Too Many Requests",
|
|
50
|
+
500: "Internal Server Error",
|
|
51
|
+
502: "Bad Gateway",
|
|
52
|
+
503: "Service Unavailable",
|
|
53
|
+
504: "Gateway Timeout",
|
|
54
|
+
};
|
|
55
|
+
const titleForStatus = (status) => FALLBACK_TITLES[status] ?? (status >= 500 ? "Internal Server Error" : "HTTP Error");
|
|
56
|
+
const isRetryableStatus = (status) => status === 429 || status >= 500;
|
|
57
|
+
/** Maps a non-2xx response to a typed `api_error`, parsing RFC 9457 Problem Details when present. */
|
|
58
|
+
export const apiErrorFromRaw = (raw, bodyJson) => {
|
|
59
|
+
const parsed = problemDetailsSchema.safeParse(bodyJson);
|
|
60
|
+
if (parsed.success) {
|
|
61
|
+
const problem = parsed.data;
|
|
62
|
+
return {
|
|
63
|
+
type: "api_error",
|
|
64
|
+
status: problem.status,
|
|
65
|
+
code: problem.code ?? `http_${problem.status}`,
|
|
66
|
+
title: problem.title,
|
|
67
|
+
...(problem.detail !== undefined ? { detail: problem.detail } : {}),
|
|
68
|
+
problemType: problem.type,
|
|
69
|
+
...(problem.request_id !== undefined
|
|
70
|
+
? { requestId: problem.request_id }
|
|
71
|
+
: raw.requestId !== undefined
|
|
72
|
+
? { requestId: raw.requestId }
|
|
73
|
+
: {}),
|
|
74
|
+
...(isRetryableStatus(problem.status) ? { retryable: true } : {}),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
type: "api_error",
|
|
79
|
+
status: raw.status,
|
|
80
|
+
code: `http_${raw.status}`,
|
|
81
|
+
title: titleForStatus(raw.status),
|
|
82
|
+
...(raw.requestId !== undefined ? { requestId: raw.requestId } : {}),
|
|
83
|
+
...(isRetryableStatus(raw.status) ? { retryable: true } : {}),
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
export const invalidResponse = (status, requestId, issues) => ({
|
|
87
|
+
type: "invalid_response",
|
|
88
|
+
status,
|
|
89
|
+
...(requestId !== undefined ? { requestId } : {}),
|
|
90
|
+
issues,
|
|
91
|
+
});
|
|
92
|
+
export const invalidRequest = (issues) => ({
|
|
93
|
+
type: "invalid_request",
|
|
94
|
+
issues,
|
|
95
|
+
});
|
|
96
|
+
// ---------------------------------------------------------------------------
|
|
97
|
+
// Fetch execution (rejection-mapped; no try/catch per design.md §5.2)
|
|
98
|
+
// ---------------------------------------------------------------------------
|
|
99
|
+
const execute = (config, spec) => {
|
|
100
|
+
const init = {
|
|
101
|
+
method: spec.method,
|
|
102
|
+
headers: buildHeaders(config, spec),
|
|
103
|
+
...(spec.body !== undefined ? { body: JSON.stringify(spec.body) } : {}),
|
|
104
|
+
};
|
|
105
|
+
return config.fetchFn(buildUrl(config.baseUrl, spec.path, spec.query), init).then((response) => response.text().then((bodyText) => succeed({
|
|
106
|
+
status: response.status,
|
|
107
|
+
bodyText,
|
|
108
|
+
requestId: response.headers.get("x-request-id") ?? undefined,
|
|
109
|
+
etag: response.headers.get("etag") ?? undefined,
|
|
110
|
+
}), (cause) => fail(networkError("failed to read response body", cause))), (cause) => fail(networkError("request failed", cause)));
|
|
111
|
+
};
|
|
112
|
+
/** `JSON.parse` isolated behind a promise boundary so its throw becomes a typed failure. */
|
|
113
|
+
const parseJson = (text) => Promise.resolve()
|
|
114
|
+
.then(() => JSON.parse(text))
|
|
115
|
+
.then((value) => succeed(value), () => fail("invalid_json"));
|
|
116
|
+
const classifySuccess = (raw, bodyJson, schema) => {
|
|
117
|
+
const parsed = schema.safeParse(bodyJson);
|
|
118
|
+
if (!parsed.success) {
|
|
119
|
+
return fail(invalidResponse(raw.status, raw.requestId, formatIssues(parsed.error)));
|
|
120
|
+
}
|
|
121
|
+
return succeed({ data: parsed.data, requestId: raw.requestId, etag: raw.etag });
|
|
122
|
+
};
|
|
123
|
+
/**
|
|
124
|
+
* Sends one request and validates the success body against `schema`
|
|
125
|
+
* (safeParse — never trust the wire). Non-2xx responses map to `api_error`
|
|
126
|
+
* with Problem Details fields; transport failures map to `network_error`.
|
|
127
|
+
*/
|
|
128
|
+
export const send = (config, spec, schema) => execute(config, spec).then((rawResult) => {
|
|
129
|
+
if (rawResult.type === "Failure")
|
|
130
|
+
return rawResult;
|
|
131
|
+
const raw = rawResult.value;
|
|
132
|
+
return parseJson(raw.bodyText).then((jsonResult) => {
|
|
133
|
+
if (jsonResult.type === "Failure") {
|
|
134
|
+
if (raw.status >= 200 && raw.status < 300) {
|
|
135
|
+
return fail(invalidResponse(raw.status, raw.requestId, ["response body is not valid JSON"]));
|
|
136
|
+
}
|
|
137
|
+
return fail(apiErrorFromRaw(raw, undefined));
|
|
138
|
+
}
|
|
139
|
+
if (raw.status >= 200 && raw.status < 300) {
|
|
140
|
+
return classifySuccess(raw, jsonResult.value, schema);
|
|
141
|
+
}
|
|
142
|
+
return fail(apiErrorFromRaw(raw, jsonResult.value));
|
|
143
|
+
});
|
|
144
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@smartcrab/management-client",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./src/index.ts",
|
|
11
|
+
"development": "./src/index.ts",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./*": {
|
|
16
|
+
"types": "./src/*.ts",
|
|
17
|
+
"development": "./src/*.ts",
|
|
18
|
+
"import": "./dist/*.js",
|
|
19
|
+
"default": "./dist/*.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"src"
|
|
25
|
+
],
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@smartcrab/contracts-management": "0.1.0"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"typescript": "5.9.3",
|
|
34
|
+
"vitest": "4.1.11"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"typecheck": "tsc --noEmit",
|
|
38
|
+
"test": "vitest run --passWithNoTests",
|
|
39
|
+
"build": "tsc -p tsconfig.build.json"
|
|
40
|
+
}
|
|
41
|
+
}
|