@ryusenkei/maezae 0.4.0 → 0.6.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/dist/dev.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './types/sdk/src/dev.js';
package/dist/dev.js ADDED
@@ -0,0 +1,85 @@
1
+ import { i as SIGNED_HEADERS, s as signedHeaders } from "./src-Baj-EC2G.js";
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { createServer } from "node:http";
5
+ import { pathToFileURL } from "node:url";
6
+ // src/dev.ts
7
+ /** 呼び出しの記録のファイル名(メソッド・パス・If-None-Match・本文のハッシュ) */
8
+ const fixtureName = (method, path, ifNoneMatch = "", body = "") => `${createHash("sha256").update(`${method.toUpperCase()} ${path}\n${ifNoneMatch}\n${body}`).digest("hex").slice(0, 16)}.json`;
9
+ /** 記録のディレクトリの URL(末尾はスラッシュ) */
10
+ const dirUrl = (dir) => {
11
+ const url = dir instanceof URL ? dir : pathToFileURL(dir);
12
+ return url.href.endsWith("/") ? url : new URL(`${url.href}/`);
13
+ };
14
+ /** 記録の再生(port Delivery、dir は記録のディレクトリ) */
15
+ function fixtureDelivery(dir) {
16
+ const base = dirUrl(dir);
17
+ return async (path, init = {}) => {
18
+ const method = (init.method ?? "GET").toUpperCase();
19
+ const file = new URL(fixtureName(method, path, new Headers(init.headers).get("if-none-match") ?? "", typeof init.body === "string" ? init.body : ""), base);
20
+ if (!existsSync(file)) throw new Error(`配信 API の記録なし: ${method} ${path}(${file.pathname.split("/").at(-1)})`);
21
+ const { status, headers, body } = JSON.parse(readFileSync(file, "utf8"));
22
+ return new Response(status === 304 ? null : body, {
23
+ status,
24
+ headers
25
+ });
26
+ };
27
+ }
28
+ const READ_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
29
+ /** 公開の配信 API への中継(port Delivery、読み取りだけで書き込みの操作は405) */
30
+ function relayDelivery({ origin, apiKey, previewSecret }) {
31
+ return async (path, init = {}) => {
32
+ const method = (init.method ?? "GET").toUpperCase();
33
+ if (!READ_METHODS.has(method)) return new Response("手元の中継は読み取りだけ", {
34
+ status: 405,
35
+ headers: { allow: "GET, HEAD" }
36
+ });
37
+ const url = `${origin.replace(/\/$/, "")}${path}`;
38
+ const headers = new Headers(init.headers);
39
+ if (previewSecret && headers.has(SIGNED_HEADERS.preview)) headers.set(SIGNED_HEADERS.preview, (await signedHeaders(previewSecret, {
40
+ method,
41
+ url,
42
+ body: null
43
+ }, { header: SIGNED_HEADERS.preview })).get(SIGNED_HEADERS.preview));
44
+ headers.set("authorization", `Bearer ${apiKey}`);
45
+ return fetch(url, {
46
+ ...init,
47
+ method,
48
+ headers
49
+ });
50
+ };
51
+ }
52
+ /** 手元の配信 API のサーバー(/content/v1/… だけ、失敗は502、戻り値は origin と停止の関数) */
53
+ async function serveDelivery(delivery, options = {}) {
54
+ const server = createServer(async (req, res) => {
55
+ const chunks = [];
56
+ for await (const chunk of req) chunks.push(chunk);
57
+ const path = req.url ?? "/";
58
+ if (!path.startsWith("/content/v1")) {
59
+ res.writeHead(404).end();
60
+ return;
61
+ }
62
+ const headers = Object.entries(req.headers).flatMap(([k, v]) => typeof v === "string" && k !== "host" ? [[k, v]] : []);
63
+ try {
64
+ const response = await delivery(path, {
65
+ method: req.method ?? "GET",
66
+ headers,
67
+ ...chunks.length ? { body: Buffer.concat(chunks).toString("utf8") } : {}
68
+ });
69
+ const out = {};
70
+ response.headers.forEach((v, k) => out[k] = v);
71
+ res.writeHead(response.status, out);
72
+ res.end(Buffer.from(await response.arrayBuffer()));
73
+ } catch (e) {
74
+ res.writeHead(502, { "content-type": "text/plain; charset=utf-8" }).end(e instanceof Error ? e.message : String(e));
75
+ }
76
+ });
77
+ const hostname = options.hostname ?? "127.0.0.1";
78
+ await new Promise((resolve) => server.listen(options.port ?? 0, hostname, resolve));
79
+ const address = server.address();
80
+ return {
81
+ origin: `http://${hostname}:${typeof address === "object" && address ? address.port : options.port}`,
82
+ close: () => new Promise((resolve) => server.close(() => resolve()))
83
+ };
84
+ }
85
+ export { fixtureDelivery, fixtureName, relayDelivery, serveDelivery };
@@ -45,6 +45,7 @@ export declare const ERROR_STATUS: {
45
45
  readonly upstream_failed: 502;
46
46
  readonly not_configured: 503;
47
47
  readonly unavailable: 503;
48
+ readonly writes_paused: 503;
48
49
  readonly job_failed: 500;
49
50
  readonly internal_error: 500;
50
51
  readonly network_error: 0;
@@ -0,0 +1,29 @@
1
+ import type { Delivery } from '../../delivery-client/src/index.js';
2
+ /** 記録の1件(記録のファイルの JSON) */
3
+ export type FixtureResponse = Readonly<{
4
+ method: string;
5
+ path: string;
6
+ status: number;
7
+ headers: Record<string, string>;
8
+ body: string;
9
+ }>;
10
+ /** 呼び出しの記録のファイル名(メソッド・パス・If-None-Match・本文のハッシュ) */
11
+ export declare const fixtureName: (method: string, path: string, ifNoneMatch?: string, body?: string) => string;
12
+ /** 記録の再生(port Delivery、dir は記録のディレクトリ) */
13
+ export declare function fixtureDelivery(dir: string | URL): Delivery;
14
+ /** 公開の配信 API の中継先(origin は媒体の識別子までの URL、例: <公開の配信 API のオリジン>/demo) */
15
+ export type Upstream = Readonly<{
16
+ origin: string;
17
+ apiKey: string;
18
+ previewSecret?: string;
19
+ }>;
20
+ /** 公開の配信 API への中継(port Delivery、読み取りだけで書き込みの操作は405) */
21
+ export declare function relayDelivery({ origin, apiKey, previewSecret }: Upstream): Delivery;
22
+ /** 手元の配信 API のサーバー(/content/v1/… だけ、失敗は502、戻り値は origin と停止の関数) */
23
+ export declare function serveDelivery(delivery: Delivery, options?: Readonly<{
24
+ port?: number;
25
+ hostname?: string;
26
+ }>): Promise<Readonly<{
27
+ origin: string;
28
+ close: () => Promise<void>;
29
+ }>>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ryusenkei/maezae",
3
- "version": "0.4.0",
4
- "description": "maezae の導入先のサイト向けの SDK(配信 API の取得・本文の型・プレビューの署名)",
3
+ "version": "0.6.0",
4
+ "description": "maezae の導入先のサイト向けの SDK(配信 API の取得・本文の型・プレビューの署名・手元の開発の配信 API)",
5
5
  "license": "UNLICENSED",
6
6
  "author": "RYUSENKEI",
7
7
  "repository": {
@@ -39,6 +39,10 @@
39
39
  "./trace": {
40
40
  "types": "./dist/trace.d.ts",
41
41
  "default": "./dist/trace.js"
42
+ },
43
+ "./dev": {
44
+ "types": "./dist/dev.d.ts",
45
+ "default": "./dist/dev.js"
42
46
  }
43
47
  },
44
48
  "files": [