@kagayoi/hatena-blog-mcp 0.0.2

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.
@@ -0,0 +1,326 @@
1
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { z } from "zod";
3
+ import type { ContentType, Page, PageWritePayload } from "../../atompub/types.js";
4
+ import { MAX_CONTENT_CHARS, MAX_IDENTIFIER_CHARS, MAX_TITLE_CHARS } from "../../utils/limits.js";
5
+ import { makeClient, type ToolContext } from "../context.js";
6
+ import { ok, type ToolTextResult, toolError } from "../response.js";
7
+
8
+ // ---------------------------------------------------------------------------
9
+ // Page view
10
+ // ---------------------------------------------------------------------------
11
+
12
+ export function pageView(page: Page, includeHtml: boolean): Record<string, unknown> {
13
+ const view: Record<string, unknown> = {
14
+ id: page.id,
15
+ title: page.title,
16
+ author: page.authorName,
17
+ content: page.content,
18
+ content_type: page.contentType,
19
+ draft: page.control.draft,
20
+ preview: page.control.preview,
21
+ updated: page.updated,
22
+ };
23
+ if (page.published !== undefined) view.published = page.published;
24
+ if (page.edited !== undefined) view.edited = page.edited;
25
+ if (page.url !== undefined) view.url = page.url;
26
+ if (page.customUrl !== undefined) view.custom_url = page.customUrl;
27
+ if (includeHtml && page.formattedContent !== undefined) {
28
+ view.formatted_content = page.formattedContent;
29
+ }
30
+ return view;
31
+ }
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // mergePage — same shape as mergeEntry but without categories/scheduled
35
+ // ---------------------------------------------------------------------------
36
+
37
+ export interface PagePatch {
38
+ title?: string;
39
+ content?: string;
40
+ draft?: boolean;
41
+ preview?: boolean;
42
+ customUrl?: string;
43
+ touchUpdated?: boolean;
44
+ }
45
+
46
+ export function mergePage(existing: Page, patch: PagePatch): PageWritePayload {
47
+ const payload: PageWritePayload = {
48
+ title: patch.title ?? existing.title,
49
+ content: patch.content ?? existing.content,
50
+ control: {
51
+ draft: patch.draft ?? existing.control.draft,
52
+ preview: patch.preview ?? existing.control.preview,
53
+ },
54
+ };
55
+ if (existing.contentType !== undefined) payload.contentType = existing.contentType;
56
+ if (existing.authorName) payload.authorName = existing.authorName;
57
+ if (patch.customUrl !== undefined) {
58
+ payload.customUrl = patch.customUrl;
59
+ }
60
+ if (patch.touchUpdated === true) {
61
+ payload.updated = new Date().toISOString();
62
+ }
63
+ return payload;
64
+ }
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // Zod shapes
68
+ // ---------------------------------------------------------------------------
69
+
70
+ const identifier = z.string().min(1).max(MAX_IDENTIFIER_CHARS);
71
+ const blogId = identifier.describe("Blog ID, e.g. example.hatenablog.com");
72
+ const hatenaIdOverride = z
73
+ .string()
74
+ .min(1)
75
+ .max(MAX_IDENTIFIER_CHARS)
76
+ .optional()
77
+ .describe("Override the Hatena ID derived from the Authorization header");
78
+ const contentTypeSchema = z
79
+ .enum(["text/x-markdown", "text/x-hatena-syntax", "text/html"])
80
+ .describe("Body syntax. Omit on create to use the blog's default.");
81
+
82
+ // ---------------------------------------------------------------------------
83
+ // Handlers
84
+ // ---------------------------------------------------------------------------
85
+
86
+ interface ListPagesArgs {
87
+ blog_id: string;
88
+ hatena_id?: string | undefined;
89
+ page?: string | undefined;
90
+ include_html?: boolean | undefined;
91
+ }
92
+
93
+ export async function listPagesHandler(
94
+ args: ListPagesArgs,
95
+ ctx: ToolContext,
96
+ ): Promise<ToolTextResult> {
97
+ try {
98
+ const client = makeClient(ctx, args.blog_id, args.hatena_id);
99
+ const listOpts: { page?: string } = {};
100
+ if (args.page !== undefined) listOpts.page = args.page;
101
+ const feed = await client.listPages(listOpts);
102
+ return ok({
103
+ pages: feed.pages.map((p) => pageView(p, args.include_html ?? false)),
104
+ next_page: feed.nextPage,
105
+ });
106
+ } catch (err) {
107
+ return toolError(err, { operation: "list_pages", requestId: ctx.requestId });
108
+ }
109
+ }
110
+
111
+ interface GetPageArgs {
112
+ blog_id: string;
113
+ page_id: string;
114
+ hatena_id?: string | undefined;
115
+ include_html?: boolean | undefined;
116
+ }
117
+
118
+ export async function getPageHandler(args: GetPageArgs, ctx: ToolContext): Promise<ToolTextResult> {
119
+ try {
120
+ const client = makeClient(ctx, args.blog_id, args.hatena_id);
121
+ const page = await client.getPage(args.page_id);
122
+ return ok(pageView(page, args.include_html ?? false));
123
+ } catch (err) {
124
+ return toolError(err, { operation: "get_page", requestId: ctx.requestId });
125
+ }
126
+ }
127
+
128
+ interface CreatePageArgs {
129
+ blog_id: string;
130
+ hatena_id?: string | undefined;
131
+ title: string;
132
+ content: string;
133
+ content_type?: ContentType | undefined;
134
+ draft?: boolean | undefined;
135
+ preview?: boolean | undefined;
136
+ custom_url: string;
137
+ }
138
+
139
+ export async function createPageHandler(
140
+ args: CreatePageArgs,
141
+ ctx: ToolContext,
142
+ ): Promise<ToolTextResult> {
143
+ try {
144
+ const client = makeClient(ctx, args.blog_id, args.hatena_id);
145
+ const payload: PageWritePayload = {
146
+ title: args.title,
147
+ content: args.content,
148
+ customUrl: args.custom_url,
149
+ control: {
150
+ draft: args.draft ?? false,
151
+ preview: args.preview ?? false,
152
+ },
153
+ };
154
+ if (args.content_type !== undefined) payload.contentType = args.content_type;
155
+ const page = await client.createPage(payload);
156
+ return ok(pageView(page, false));
157
+ } catch (err) {
158
+ return toolError(err, { operation: "create_page", requestId: ctx.requestId });
159
+ }
160
+ }
161
+
162
+ interface UpdatePageArgs {
163
+ blog_id: string;
164
+ hatena_id?: string | undefined;
165
+ page_id: string;
166
+ title?: string | undefined;
167
+ content?: string | undefined;
168
+ draft?: boolean | undefined;
169
+ preview?: boolean | undefined;
170
+ custom_url?: string | undefined;
171
+ touch_updated?: boolean | undefined;
172
+ expected_edited?: string | undefined;
173
+ }
174
+
175
+ export async function updatePageHandler(
176
+ args: UpdatePageArgs,
177
+ ctx: ToolContext,
178
+ ): Promise<ToolTextResult> {
179
+ try {
180
+ const client = makeClient(ctx, args.blog_id, args.hatena_id);
181
+ const existing = await client.getPage(args.page_id);
182
+ if (args.expected_edited !== undefined && existing.edited !== args.expected_edited) {
183
+ return toolError(
184
+ new Error("更新競合を検出しました。get_page で最新状態を取得してから再試行してください。"),
185
+ { operation: "update_page", requestId: ctx.requestId },
186
+ );
187
+ }
188
+ const patch: PagePatch = {};
189
+ if (args.title !== undefined) patch.title = args.title;
190
+ if (args.content !== undefined) patch.content = args.content;
191
+ if (args.draft !== undefined) patch.draft = args.draft;
192
+ if (args.preview !== undefined) patch.preview = args.preview;
193
+ if (args.custom_url !== undefined) patch.customUrl = args.custom_url;
194
+ if (args.touch_updated !== undefined) patch.touchUpdated = args.touch_updated;
195
+ const payload = mergePage(existing, patch);
196
+ const updated = await client.updatePage(args.page_id, payload);
197
+ return ok(pageView(updated, false));
198
+ } catch (err) {
199
+ return toolError(err, { operation: "update_page", requestId: ctx.requestId });
200
+ }
201
+ }
202
+
203
+ interface DeletePageArgs {
204
+ blog_id: string;
205
+ hatena_id?: string | undefined;
206
+ page_id: string;
207
+ }
208
+
209
+ export async function deletePageHandler(
210
+ args: DeletePageArgs,
211
+ ctx: ToolContext,
212
+ ): Promise<ToolTextResult> {
213
+ try {
214
+ const client = makeClient(ctx, args.blog_id, args.hatena_id);
215
+ await client.deletePage(args.page_id);
216
+ return ok({ ok: true });
217
+ } catch (err) {
218
+ return toolError(err, { operation: "delete_page", requestId: ctx.requestId });
219
+ }
220
+ }
221
+
222
+ // ---------------------------------------------------------------------------
223
+ // Registration
224
+ // ---------------------------------------------------------------------------
225
+
226
+ export function registerPageTools(server: McpServer, ctx: ToolContext): void {
227
+ server.registerTool(
228
+ "list_pages",
229
+ {
230
+ description:
231
+ "固定ページの一覧を取得します。続きは返り値の next_page を page に渡して再取得してください。",
232
+ inputSchema: {
233
+ blog_id: blogId,
234
+ hatena_id: hatenaIdOverride,
235
+ page: z
236
+ .string()
237
+ .max(MAX_IDENTIFIER_CHARS)
238
+ .optional()
239
+ .describe("next_page token from a previous response"),
240
+ include_html: z.boolean().optional(),
241
+ },
242
+ annotations: { readOnlyHint: true },
243
+ },
244
+ (args) => listPagesHandler(args, ctx),
245
+ );
246
+
247
+ server.registerTool(
248
+ "get_page",
249
+ {
250
+ description: "固定ページを1件取得します。",
251
+ inputSchema: {
252
+ blog_id: blogId,
253
+ hatena_id: hatenaIdOverride,
254
+ page_id: identifier,
255
+ include_html: z.boolean().optional(),
256
+ },
257
+ annotations: { readOnlyHint: true },
258
+ },
259
+ (args) => getPageHandler(args, ctx),
260
+ );
261
+
262
+ server.registerTool(
263
+ "create_page",
264
+ {
265
+ description: "新規の固定ページを作成します。custom_url はページのスラッグで必須です。",
266
+ inputSchema: {
267
+ blog_id: blogId,
268
+ hatena_id: hatenaIdOverride,
269
+ title: z.string().min(1).max(MAX_TITLE_CHARS),
270
+ content: z.string().max(MAX_CONTENT_CHARS),
271
+ content_type: contentTypeSchema.optional(),
272
+ draft: z.boolean().optional(),
273
+ preview: z.boolean().optional(),
274
+ custom_url: z
275
+ .string()
276
+ .min(1)
277
+ .max(MAX_IDENTIFIER_CHARS)
278
+ .describe("ページのスラッグ (例: about)"),
279
+ },
280
+ },
281
+ (args) => createPageHandler(args, ctx),
282
+ );
283
+
284
+ server.registerTool(
285
+ "update_page",
286
+ {
287
+ description:
288
+ "固定ページを部分更新します。指定したフィールドのみ書き換え、未指定のフィールドは既存値を維持します (投稿日時・URL・本文の記法を含む)。",
289
+ inputSchema: {
290
+ blog_id: blogId,
291
+ hatena_id: hatenaIdOverride,
292
+ page_id: identifier,
293
+ title: z.string().max(MAX_TITLE_CHARS).optional(),
294
+ content: z.string().max(MAX_CONTENT_CHARS).optional(),
295
+ draft: z.boolean().optional(),
296
+ preview: z.boolean().optional(),
297
+ custom_url: z.string().max(MAX_IDENTIFIER_CHARS).optional(),
298
+ touch_updated: z
299
+ .boolean()
300
+ .optional()
301
+ .describe("true を指定した場合のみ現在時刻で updated を送信します (デフォルト false)"),
302
+ expected_edited: z
303
+ .string()
304
+ .max(MAX_IDENTIFIER_CHARS)
305
+ .optional()
306
+ .describe("get_page が返した edited。現在値と異なる場合は更新せず競合エラーにします"),
307
+ },
308
+ annotations: { destructiveHint: true },
309
+ },
310
+ (args) => updatePageHandler(args, ctx),
311
+ );
312
+
313
+ server.registerTool(
314
+ "delete_page",
315
+ {
316
+ description: "固定ページを削除します。",
317
+ inputSchema: {
318
+ blog_id: blogId,
319
+ hatena_id: hatenaIdOverride,
320
+ page_id: identifier,
321
+ },
322
+ annotations: { destructiveHint: true, idempotentHint: true },
323
+ },
324
+ (args) => deletePageHandler(args, ctx),
325
+ );
326
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Credentials extracted from a BYOK `Authorization: Basic ...` header.
3
+ *
4
+ * We keep the raw header around so the AtomPub client can relay it verbatim
5
+ * to Hatena without re-encoding — decoding once, re-encoding once is almost
6
+ * always fine, but "once" is already one round-trip more than is necessary.
7
+ */
8
+ export interface BasicCredentials {
9
+ /** `Basic base64(user:pass)` — ready to paste into an outbound Authorization header. */
10
+ authHeader: string;
11
+ /** Hatena ID (the username portion of the Basic header). */
12
+ hatenaId: string;
13
+ }
14
+
15
+ export class MissingCredentialsError extends Error {
16
+ constructor(message = "Authorization header is missing or not Basic") {
17
+ super(message);
18
+ this.name = "MissingCredentialsError";
19
+ }
20
+ }
21
+
22
+ /**
23
+ * Parse a raw `Authorization` header value. Returns the credentials or throws
24
+ * MissingCredentialsError. The password/API key is never returned — callers
25
+ * that need to forward it use `authHeader` instead.
26
+ *
27
+ * Implementation note: we use Web-standard `atob` which is available in both
28
+ * Cloudflare Workers and Node 16+. No `Buffer` — this code runs on Workers.
29
+ */
30
+ export function parseBasicAuth(headerValue: string | null | undefined): BasicCredentials {
31
+ if (!headerValue) throw new MissingCredentialsError();
32
+ const trimmed = headerValue.trim();
33
+ const match = /^Basic\s+(.+)$/i.exec(trimmed);
34
+ if (!match?.[1]) throw new MissingCredentialsError();
35
+ const b64 = match[1].trim();
36
+ let decoded: string;
37
+ try {
38
+ decoded = atob(b64);
39
+ } catch {
40
+ throw new MissingCredentialsError("Authorization header has invalid base64");
41
+ }
42
+ const colonIndex = decoded.indexOf(":");
43
+ if (colonIndex <= 0) {
44
+ throw new MissingCredentialsError("Authorization payload must be 'user:password'");
45
+ }
46
+ const hatenaId = decoded.slice(0, colonIndex);
47
+ return { authHeader: trimmed, hatenaId };
48
+ }
@@ -0,0 +1,71 @@
1
+ export const MAX_XML_RESPONSE_BYTES = 8 * 1024 * 1024;
2
+ export const MAX_ERROR_RESPONSE_BYTES = 16 * 1024;
3
+
4
+ export class ResponseBodyTooLargeError extends Error {
5
+ constructor(
6
+ readonly maxBytes: number,
7
+ readonly actualBytes?: number,
8
+ ) {
9
+ super(
10
+ actualBytes === undefined
11
+ ? `Response body exceeded ${maxBytes} bytes`
12
+ : `Response body is ${actualBytes} bytes (limit: ${maxBytes})`,
13
+ );
14
+ this.name = "ResponseBodyTooLargeError";
15
+ }
16
+ }
17
+
18
+ export async function readBytesWithLimit(
19
+ body: ReadableStream<Uint8Array> | null,
20
+ maxBytes: number,
21
+ ): Promise<Uint8Array<ArrayBuffer>> {
22
+ if (!body) return new Uint8Array();
23
+
24
+ const reader = body.getReader();
25
+ const chunks: Uint8Array[] = [];
26
+ let totalBytes = 0;
27
+ try {
28
+ while (true) {
29
+ const { done, value } = await reader.read();
30
+ if (done) break;
31
+ totalBytes += value.byteLength;
32
+ if (totalBytes > maxBytes) {
33
+ await reader.cancel();
34
+ throw new ResponseBodyTooLargeError(maxBytes, totalBytes);
35
+ }
36
+ chunks.push(value);
37
+ }
38
+ } finally {
39
+ reader.releaseLock();
40
+ }
41
+
42
+ const bytes = new Uint8Array(totalBytes);
43
+ let offset = 0;
44
+ for (const chunk of chunks) {
45
+ bytes.set(chunk, offset);
46
+ offset += chunk.byteLength;
47
+ }
48
+ return bytes;
49
+ }
50
+
51
+ export async function readTextWithLimit(response: Response, maxBytes: number): Promise<string> {
52
+ const contentLength = response.headers.get("content-length");
53
+ if (contentLength !== null) {
54
+ const parsed = Number.parseInt(contentLength, 10);
55
+ if (Number.isFinite(parsed) && parsed > maxBytes) {
56
+ await response.body?.cancel();
57
+ throw new ResponseBodyTooLargeError(maxBytes, parsed);
58
+ }
59
+ }
60
+
61
+ const bytes = await readBytesWithLimit(response.body, maxBytes);
62
+ return new TextDecoder().decode(bytes);
63
+ }
64
+
65
+ export async function readErrorText(response: Response): Promise<string> {
66
+ try {
67
+ return await readTextWithLimit(response, MAX_ERROR_RESPONSE_BYTES);
68
+ } catch {
69
+ return "";
70
+ }
71
+ }
@@ -0,0 +1,8 @@
1
+ export const MAX_MCP_REQUEST_BYTES = 16 * 1024 * 1024;
2
+ export const MAX_TITLE_CHARS = 1024;
3
+ export const MAX_CONTENT_CHARS = 4 * 1024 * 1024;
4
+ export const MAX_IDENTIFIER_CHARS = 2048;
5
+ export const MAX_CATEGORY_COUNT = 100;
6
+ export const MAX_CATEGORY_CHARS = 256;
7
+ export const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
8
+ export const MAX_IMAGE_BASE64_CHARS = Math.ceil(MAX_IMAGE_BYTES / 3) * 4;
@@ -0,0 +1,166 @@
1
+ /**
2
+ * `fetch` wrapper that retries transient failures from the Hatena AtomPub API.
3
+ *
4
+ * Retries:
5
+ * - HTTP 429, 502, 503, and 504
6
+ * - Network-level rejections (DNS, TLS, fetch threw)
7
+ *
8
+ * Does NOT retry:
9
+ * - Non-idempotent methods such as POST
10
+ * - 4xx other than 429 (caller bug / auth issue — retrying won't help)
11
+ * - AbortError from the caller's signal (user gave up deliberately)
12
+ *
13
+ * `Retry-After` is honoured both as a whole-number seconds value and as an
14
+ * HTTP-date. When present, it replaces the computed backoff.
15
+ */
16
+ export interface RetryOptions {
17
+ maxRetries?: number;
18
+ baseDelayMs?: number;
19
+ /** Multiplier per attempt; 2 means 1s, 2s, 4s ... */
20
+ factor?: number;
21
+ /** Upper bound on a single wait — useful for very polite retries. */
22
+ maxDelayMs?: number;
23
+ /** Deterministic backoff source (0..1). Default: Math.random. Tests pass a stub. */
24
+ random?: () => number;
25
+ /** Deterministic sleep. Default: setTimeout. Tests pass a no-op collector. */
26
+ sleep?: (ms: number, signal?: AbortSignal | null) => Promise<void>;
27
+ /** Override `fetch` — useful for Workers, Node tests, etc. */
28
+ fetchImpl?: typeof fetch;
29
+ /** Wall-clock source used to parse Retry-After HTTP-dates. */
30
+ now?: () => number;
31
+ }
32
+
33
+ const DEFAULTS = {
34
+ maxRetries: 3,
35
+ baseDelayMs: 1000,
36
+ factor: 2,
37
+ maxDelayMs: 30_000,
38
+ };
39
+
40
+ const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
41
+ const RETRYABLE_METHODS = new Set(["DELETE", "GET", "HEAD", "OPTIONS", "PUT", "TRACE"]);
42
+
43
+ const defaultSleep = (ms: number, signal?: AbortSignal | null): Promise<void> =>
44
+ new Promise((resolve, reject) => {
45
+ if (signal?.aborted) {
46
+ reject(signal.reason ?? new DOMException("The operation was aborted", "AbortError"));
47
+ return;
48
+ }
49
+ const timeout = setTimeout(() => {
50
+ signal?.removeEventListener("abort", onAbort);
51
+ resolve();
52
+ }, ms);
53
+ const onAbort = () => {
54
+ clearTimeout(timeout);
55
+ reject(signal?.reason ?? new DOMException("The operation was aborted", "AbortError"));
56
+ };
57
+ signal?.addEventListener("abort", onAbort, { once: true });
58
+ });
59
+
60
+ export async function fetchWithRetry(
61
+ input: string | URL | Request,
62
+ init: RequestInit = {},
63
+ opts: RetryOptions = {},
64
+ ): Promise<Response> {
65
+ const method = resolveMethod(input, init);
66
+ const maxRetries = RETRYABLE_METHODS.has(method) ? (opts.maxRetries ?? DEFAULTS.maxRetries) : 0;
67
+ const baseDelayMs = opts.baseDelayMs ?? DEFAULTS.baseDelayMs;
68
+ const factor = opts.factor ?? DEFAULTS.factor;
69
+ const maxDelayMs = opts.maxDelayMs ?? DEFAULTS.maxDelayMs;
70
+ const random = opts.random ?? Math.random;
71
+ const sleep = opts.sleep ?? defaultSleep;
72
+ const fetchImpl = opts.fetchImpl ?? fetch;
73
+ const now = opts.now ?? Date.now;
74
+ const signal = init.signal ?? (input instanceof Request ? input.signal : undefined);
75
+
76
+ let attempt = 0;
77
+ let lastError: unknown;
78
+
79
+ while (attempt <= maxRetries) {
80
+ try {
81
+ const response = await fetchImpl(input, init);
82
+ if (!RETRYABLE_STATUSES.has(response.status)) {
83
+ return response;
84
+ }
85
+ if (attempt === maxRetries) {
86
+ return response;
87
+ }
88
+ const waitMs = computeWaitMs({
89
+ attempt,
90
+ baseDelayMs,
91
+ factor,
92
+ maxDelayMs,
93
+ random,
94
+ retryAfter: response.headers.get("retry-after"),
95
+ now,
96
+ });
97
+ // Consume the body so the connection can be reused.
98
+ await response.body?.cancel?.();
99
+ await sleep(waitMs, signal);
100
+ } catch (err) {
101
+ lastError = err;
102
+ if (signal?.aborted || isAbortError(err) || attempt === maxRetries) {
103
+ throw err;
104
+ }
105
+ const waitMs = computeWaitMs({
106
+ attempt,
107
+ baseDelayMs,
108
+ factor,
109
+ maxDelayMs,
110
+ random,
111
+ retryAfter: null,
112
+ now,
113
+ });
114
+ await sleep(waitMs, signal);
115
+ }
116
+ attempt += 1;
117
+ }
118
+
119
+ // Loop only exits via return/throw above; this satisfies the type checker.
120
+ throw lastError ?? new Error("fetchWithRetry exhausted retries");
121
+ }
122
+
123
+ function resolveMethod(input: string | URL | Request, init: RequestInit): string {
124
+ if (init.method) return init.method.toUpperCase();
125
+ if (input instanceof Request) return input.method.toUpperCase();
126
+ return "GET";
127
+ }
128
+
129
+ function computeWaitMs(args: {
130
+ attempt: number;
131
+ baseDelayMs: number;
132
+ factor: number;
133
+ maxDelayMs: number;
134
+ random: () => number;
135
+ retryAfter: string | null;
136
+ now: () => number;
137
+ }): number {
138
+ const retryAfterMs = parseRetryAfter(args.retryAfter, args.now);
139
+ if (retryAfterMs !== null) {
140
+ return Math.min(retryAfterMs, args.maxDelayMs);
141
+ }
142
+ const exp = args.baseDelayMs * args.factor ** args.attempt;
143
+ const jitter = 1 + (args.random() - 0.5) * 0.5; // ±25%
144
+ return Math.min(Math.max(0, exp * jitter), args.maxDelayMs);
145
+ }
146
+
147
+ function parseRetryAfter(value: string | null, now: () => number): number | null {
148
+ if (value === null) return null;
149
+ const trimmed = value.trim();
150
+ if (trimmed.length === 0) return null;
151
+ // Pure-digit form: seconds.
152
+ if (/^\d+$/.test(trimmed)) {
153
+ return Number.parseInt(trimmed, 10) * 1000;
154
+ }
155
+ // HTTP-date form.
156
+ const asDate = Date.parse(trimmed);
157
+ if (Number.isNaN(asDate)) return null;
158
+ return Math.max(0, asDate - now());
159
+ }
160
+
161
+ function isAbortError(err: unknown): boolean {
162
+ return (
163
+ err instanceof Error &&
164
+ (err.name === "AbortError" || (err as { code?: string }).code === "ABORT_ERR")
165
+ );
166
+ }
@@ -0,0 +1,20 @@
1
+ export function assertValidXmlChars(value: string): string {
2
+ for (const char of value) {
3
+ const codePoint = char.codePointAt(0);
4
+ if (
5
+ codePoint === undefined ||
6
+ codePoint === 0x09 ||
7
+ codePoint === 0x0a ||
8
+ codePoint === 0x0d ||
9
+ (codePoint >= 0x20 && codePoint <= 0xd7ff) ||
10
+ (codePoint >= 0xe000 && codePoint <= 0xfffd) ||
11
+ (codePoint >= 0x10000 && codePoint <= 0x10ffff)
12
+ ) {
13
+ continue;
14
+ }
15
+ throw new Error(
16
+ `XML 1.0 で使用できない文字 U+${codePoint.toString(16).toUpperCase()} が含まれています。`,
17
+ );
18
+ }
19
+ return value;
20
+ }