http-json-contract 0.0.0-stage → 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/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
1
+ # http-json-contract
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Rust API처럼 별도 프로세스에서 실행되는 서버의 HTTP JSON 응답을 기존 TypeScript 파서로 검사하는 패키지입니다. Node.js 22.18 이상에서 사용하는 ESM 패키지이며, 런타임 의존성이 없습니다.
4
+
5
+ ## 설치와 사용
6
+
7
+ 프로젝트 루트에서 설치용 파일을 만듭니다.
8
+
9
+ ```bash
10
+ pnpm install --frozen-lockfile
11
+ pnpm build
12
+ pnpm pack
13
+ ```
14
+
15
+ 다른 프로젝트에서는 생성한 `.tgz`의 실제 경로를 넘겨 개발 의존성으로 설치합니다.
16
+
17
+ ```bash
18
+ pnpm add -D /path/to/http-json-contract-0.1.0.tgz
19
+ ```
20
+
21
+ 아래 테스트는 애플리케이션의 기존 파서인 `parsePreferences`와 테스트 러너를 사용합니다.
22
+
23
+ ```ts
24
+ import assert from "node:assert/strict";
25
+ import { test } from "node:test";
26
+ import { createJsonContractClient } from "http-json-contract";
27
+ import { parsePreferences } from "../src/preferences.ts";
28
+
29
+ const api = createJsonContractClient({
30
+ baseUrl: process.env.API_BASE_URL ?? "http://127.0.0.1:8080",
31
+ timeoutMs: 5_000,
32
+ });
33
+
34
+ test("이메일 알림 수신 거부를 유지한다", async () => {
35
+ const preferences = await api.get("/preferences", parsePreferences);
36
+ assert.equal(preferences.emailNotifications, false);
37
+ });
38
+ ```
39
+
40
+ ## 공개 API
41
+
42
+ - `createJsonContractClient({ baseUrl, timeoutMs })`에 경로나 인증 정보가 없는 HTTP(S) origin을 넘깁니다. 선택 사항인 타임아웃의 기본값은 5초입니다.
43
+ - `client.get(path, parse)`에는 `/documents`처럼 같은 origin의 경로와 동기 또는 비동기 파서를 넘깁니다. 쿼리 문자열을 함께 보낼 수 있습니다.
44
+ - HTTP 200과 `application/json` 또는 `application/*+json`을 확인한 뒤, 응답 본문 원문을 파서에 넘깁니다. 반환 타입은 파서에서 추론하며, 요청·파싱 오류는 경로와 원래 오류를 함께 제공합니다.
45
+
46
+ ## Rust와 GitHub Actions 예제
47
+
48
+ 저장소 루트에서 아래 명령을 실행합니다. Node.js 외에 Bash, pnpm, Rust와 Cargo가 필요합니다.
49
+
50
+ ```bash
51
+ pnpm test:example
52
+ ```
53
+
54
+ 예제는 tarball을 임시 소비자 프로젝트에 설치하고, Axum 서버를 루프백 임시 포트에서 시작합니다. 준비된 주소를 `API_BASE_URL`로 건네 `/documents`와 `/preferences`를 테스트한 뒤 서버를 정리합니다. 필드명 변경 사례는 기대값 `false`와 실제값 `true`가 담긴 단언 오류가 발생하는지 확인합니다.
55
+
56
+ 저장소의 `.github/workflows/rust-http-json-contract.yml`은 같은 명령을 실행합니다. 한 저장소에서 실행할 때는 Rust 실행 파일 준비, 실제 포트 전달, 패키지 설치본 테스트와 서버 정리 순서를 재사용하면 됩니다.
57
+
58
+ ## 브라우저 데모
59
+
60
+ `pnpm demo`를 실행하고 터미널에 출력된 로컬 주소를 엽니다. 정상 응답과 필드명 변경을 두 카드로 비교하며 브라우저에서 같은 파서와 검사 조건을 사용합니다.
@@ -0,0 +1,8 @@
1
+ export interface JsonContractOptions {
2
+ baseUrl: string | URL;
3
+ timeoutMs?: number;
4
+ }
5
+ export interface JsonContractClient {
6
+ get<T>(path: string, parse: (body: string) => T | Promise<T>): Promise<T>;
7
+ }
8
+ export declare function createJsonContractClient({ baseUrl, timeoutMs, }: JsonContractOptions): JsonContractClient;
package/dist/index.js ADDED
@@ -0,0 +1,64 @@
1
+ export function createJsonContractClient({ baseUrl, timeoutMs = 5_000, }) {
2
+ const base = new URL(baseUrl);
3
+ if (!["http:", "https:"].includes(base.protocol) ||
4
+ base.href !== base.origin + "/") {
5
+ throw new TypeError("baseUrl must be an HTTP(S) origin");
6
+ }
7
+ if (!Number.isInteger(timeoutMs) ||
8
+ timeoutMs < 1 ||
9
+ timeoutMs > 2_147_483_647) {
10
+ throw new RangeError("timeoutMs must be an integer between 1 and 2147483647");
11
+ }
12
+ return {
13
+ async get(path, parse) {
14
+ const url = new URL(path, base);
15
+ if (!path.startsWith("/") ||
16
+ url.origin !== base.origin ||
17
+ url.href.includes("#")) {
18
+ throw new TypeError("path must be a same-origin URL path without a fragment");
19
+ }
20
+ const endpoint = "GET " + url.pathname;
21
+ let response;
22
+ try {
23
+ response = await fetch(url, {
24
+ headers: { accept: "application/json" },
25
+ redirect: "manual",
26
+ signal: AbortSignal.timeout(timeoutMs),
27
+ });
28
+ }
29
+ catch (cause) {
30
+ throw new Error(endpoint + ": request failed", { cause });
31
+ }
32
+ if (response.status !== 200) {
33
+ await response.body?.cancel().catch(() => { });
34
+ throw new Error(endpoint + ": expected HTTP 200, received " + response.status);
35
+ }
36
+ const contentType = response.headers.get("content-type");
37
+ const mediaType = contentType?.split(";", 1)[0]?.trim().toLowerCase();
38
+ if (mediaType !== "application/json" &&
39
+ !/^application\/[\w.+-]+\+json$/.test(mediaType ?? "")) {
40
+ await response.body?.cancel().catch(() => { });
41
+ throw new Error(endpoint +
42
+ ": expected JSON, received " +
43
+ (contentType ?? "no content type"));
44
+ }
45
+ let raw;
46
+ try {
47
+ raw = await response.text();
48
+ }
49
+ catch (cause) {
50
+ throw new Error(endpoint + ": could not read the response body", {
51
+ cause,
52
+ });
53
+ }
54
+ try {
55
+ return await parse(raw);
56
+ }
57
+ catch (cause) {
58
+ throw new Error(endpoint + ": consumer parser rejected the response", {
59
+ cause,
60
+ });
61
+ }
62
+ },
63
+ };
64
+ }
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "http-json-contract",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Verify HTTP JSON responses with the application's existing TypeScript parser.",
5
+ "type": "module",
6
+ "files": [
7
+ "dist",
8
+ "README.md"
9
+ ],
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ }
15
+ },
16
+ "scripts": {
17
+ "build": "tsc -p tsconfig.build.json",
18
+ "test:example": "pnpm build && bash examples/rust/run.sh",
19
+ "demo": "tsc -p examples/rust/web/tsconfig.json && cargo run --locked --manifest-path examples/rust/Cargo.toml --features browser-demo"
20
+ },
21
+ "devDependencies": {
22
+ "typescript": "6.0.3"
23
+ },
24
+ "engines": {
25
+ "node": ">=22.18.0"
26
+ },
27
+ "packageManager": "pnpm@12.14.0"
28
+ }