note-blog-kit 0.1.0 → 0.2.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.
@@ -1,5 +1,7 @@
1
- import { NoteArticlePage, NoteArticleSummary } from '../index.js';
2
- export { NoteArticle, NoteAuthor, NoteEmbed, NoteEyecatch, NoteSource, NoteTocItem } from '../index.js';
1
+ import { NoteArticle } from '../index.js';
2
+ export { NoteArticlePage, NoteArticleSummary, NoteAuthor, NoteEmbed, NoteEyecatch, NoteSource, NoteTocItem } from '../index.js';
3
+ import { N as NoteRequestOptions } from '../iterate-articles-9dzDflSn.js';
4
+ export { I as IterateArticlesOptions, a as IterateArticlesResult, b as ListAllArticlesResult, L as ListArticlesOptions, i as iterateArticles, l as listAllArticles, c as listArticles } from '../iterate-articles-9dzDflSn.js';
3
5
 
4
6
  /** エラーの種類を表す安定した識別子 */
5
7
  type NoteErrorCode = 'NOTE_NOT_FOUND' | 'NOTE_HTTP_ERROR' | 'NOTE_NETWORK_ERROR' | 'NOTE_TIMEOUT' | 'NOTE_SCHEMA_ERROR';
@@ -81,80 +83,27 @@ type AnyNoteError = NoteNotFoundError | NoteHttpError | NoteNetworkError | NoteT
81
83
  */
82
84
  declare function isNoteError(value: unknown): value is AnyNoteError;
83
85
 
84
- /** {@link listArticles} のオプション */
85
- interface ListArticlesOptions {
86
- /** note のユーザー名(note.com/{user} の部分)。英数字・_・- のみ */
87
- user: string;
88
- /** ページ番号(1 始まり)。既定は 1。1ページは6件 */
89
- page?: number;
90
- /**
91
- * fetch の差し替え(テストやキャッシュ層のため)。既定は globalThis.fetch。
92
- * 差し替えた fetch でも Cookie・認証ヘッダーを付けないこと(note の公開情報だけを取得する前提)
93
- */
94
- fetch?: typeof globalThis.fetch;
95
- /** 中断用のシグナル。間隔の制限で待っている間も含め、中断したらすぐにその理由をそのまま投げる */
96
- signal?: AbortSignal;
97
- /** タイムアウト(ミリ秒)。1〜2147483647。既定は 10000 */
98
- timeoutMs?: number;
99
- /**
100
- * 連続リクエストの最小間隔(ミリ秒)。0〜2147483647。既定は 1000。
101
- * 送信順はプロセス全体(ESM・CJS の併用やパッケージの重複を含む)で1本の列にまとめられ、
102
- * この呼び出しは「直前の送信から minIntervalMs 経つまで」待ってから送られる。
103
- */
104
- minIntervalMs?: number;
86
+ /** {@link getArticle} のオプション */
87
+ interface GetArticleOptions extends NoteRequestOptions {
88
+ /** 記事キー(例: n55256baa5425。記事 URL の /n/ の後ろ)。n と英小文字・数字のみ */
89
+ key: string;
105
90
  }
106
91
  /**
107
- * 記事一覧の1ページを取得する(サーバー専用。note は CORS に対応していない)。
92
+ * 記事1件を取得する(サーバー専用。note は CORS に対応していない)。
93
+ * 本文(`bodyHtml`)はサニタイズ済み。有料記事は無料部分だけで、`isPartial` が true になる。
94
+ * 有料記事の `toc` は有料部分の見出しも含むため、一部の `id` は `bodyHtml` の中にない。
108
95
  *
109
- * @throws {TypeError} user・page が不正なとき
110
- * @throws {NoteNotFoundError} ユーザーが見つからないとき
96
+ * note の API は記事キーだけで誰の記事でも返す。ページの URL から受け取ったキーをそのまま渡す場合は、
97
+ * 他人の記事を表示しないよう、`article.author.urlname` が自分のユーザー名か確かめること。
98
+ *
99
+ * @throws {TypeError} key やオプションが不正なとき
100
+ * @throws {NoteNotFoundError} 記事が見つからないとき
111
101
  * @throws {NoteHttpError} その他の 2xx でないステータス
112
102
  * @throws {NoteNetworkError} 通信に失敗したとき
113
103
  * @throws {NoteTimeoutError} タイムアウトしたとき
114
104
  * @throws {NoteSchemaError} レスポンスの形が想定と違うとき
115
105
  */
116
- declare function listArticles(options: ListArticlesOptions): Promise<NoteArticlePage>;
117
-
118
- /** {@link iterateArticles}・{@link listAllArticles} のオプション。`listArticles` のオプションから `page` を除いたもの */
119
- interface IterateArticlesOptions extends Omit<ListArticlesOptions, 'page'> {
120
- /** 取得する最大ページ数(1 以上の整数)。既定は 20(1ページ6件なので120件) */
121
- maxPages?: number;
122
- }
123
- /** 全件取得の結果のうち、記事以外の情報 */
124
- interface IterateArticlesResult {
125
- /** maxPages に達して打ち切ったとき true(続きのページがある可能性がある) */
126
- truncated: boolean;
127
- /** 最後に取得したページの totalCount */
128
- totalCount: number | null;
129
- /** 実際に取得したページ数 */
130
- pages: number;
131
- }
132
- /** {@link listAllArticles} の結果 */
133
- interface ListAllArticlesResult extends IterateArticlesResult {
134
- /** 取得した記事(新しい順、key で重複を除いたもの) */
135
- articles: NoteArticleSummary[];
136
- }
137
- /**
138
- * 記事を新しい順に1件ずつ返す(サーバー専用)。最終ページか maxPages に達したら終わる。
139
- * ページの取得には `listArticles` を使うため、取得間隔の制限・タイムアウト・中断もそのまま効く。
140
- * 取得中にページがずれて同じ記事が再び出た場合は、`key` で重複を除く。
141
- *
142
- * 打ち切りの有無などはジェネレーターの戻り値(`IterateArticlesResult`)で返す。
143
- * `for await` ではこの戻り値を受け取れないため、必要なら {@link listAllArticles} を使うか `next()` を手で回す。
144
- *
145
- * @throws {TypeError} maxPages などが不正なとき(呼び出した時点ではなく、最初の `next()` で投げる)
146
- * @throws 途中のページの取得で起きたエラー(それまでに返した記事はそのまま)
147
- */
148
- declare function iterateArticles(options: IterateArticlesOptions): AsyncGenerator<NoteArticleSummary, IterateArticlesResult, undefined>;
149
- /**
150
- * 全件(maxPages まで。既定は 20 ページ)を配列で返す(サーバー専用)。
151
- * `truncated` が true なら maxPages で打ち切っており、続きのページがある可能性がある。
152
- *
153
- * @throws {TypeError} maxPages などが不正なとき
154
- * @throws 途中のページの取得で起きたエラー。それまでに集めた記事は返らない
155
- * (途中までの記事も使いたい場合は {@link iterateArticles} を使う)
156
- */
157
- declare function listAllArticles(options: IterateArticlesOptions): Promise<ListAllArticlesResult>;
106
+ declare function getArticle(options: GetArticleOptions): Promise<NoteArticle>;
158
107
 
159
- export { NoteArticlePage, NoteArticleSummary, NoteError, NoteHttpError, NoteNetworkError, NoteNotFoundError, NoteSchemaError, NoteTimeoutError, isNoteError, iterateArticles, listAllArticles, listArticles };
160
- export type { AnyNoteError, IterateArticlesOptions, IterateArticlesResult, ListAllArticlesResult, ListArticlesOptions, NoteErrorCode, NoteErrorOptions, NoteSchemaIssue };
108
+ export { NoteArticle, NoteError, NoteHttpError, NoteNetworkError, NoteNotFoundError, NoteRequestOptions, NoteSchemaError, NoteTimeoutError, getArticle, isNoteError };
109
+ export type { AnyNoteError, GetArticleOptions, NoteErrorCode, NoteErrorOptions, NoteSchemaIssue };
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ import sanitizeHtml from 'sanitize-html';
2
3
 
3
4
  // src/server/errors.ts
4
5
  var NOTE_ERROR_CODES = /* @__PURE__ */ new Set([
@@ -126,6 +127,182 @@ async function fetchNoteJson(url, options) {
126
127
  });
127
128
  }
128
129
  }
130
+
131
+ // src/server/patterns.ts
132
+ var NOTE_KEY_RE = /^n[0-9a-z]{1,32}$/;
133
+ var NOTE_USER_RE = /^[A-Za-z0-9_-]{1,64}$/;
134
+ var ALLOWED_TAGS = [
135
+ "p",
136
+ "br",
137
+ "h2",
138
+ "h3",
139
+ "h4",
140
+ "strong",
141
+ "em",
142
+ "s",
143
+ "a",
144
+ "ul",
145
+ "ol",
146
+ "li",
147
+ "blockquote",
148
+ "figure",
149
+ "figcaption",
150
+ "img",
151
+ "pre",
152
+ "code",
153
+ "hr",
154
+ "table",
155
+ "thead",
156
+ "tbody",
157
+ "tr",
158
+ "th",
159
+ "td",
160
+ "div"
161
+ ];
162
+ var DISCARD_WITH_CONTENT = [
163
+ "script",
164
+ "style",
165
+ "iframe",
166
+ "frame",
167
+ "frameset",
168
+ "object",
169
+ "embed",
170
+ "applet",
171
+ "form",
172
+ "input",
173
+ "button",
174
+ "textarea",
175
+ "select",
176
+ "option",
177
+ "svg",
178
+ "math",
179
+ "template",
180
+ "noscript",
181
+ "meta",
182
+ "link",
183
+ "base",
184
+ "title",
185
+ "xmp",
186
+ "plaintext"
187
+ ];
188
+ var ALLOWED_ATTRIBUTES = {
189
+ "*": ["id"],
190
+ a: ["href", "target", "rel"],
191
+ img: ["src", "alt", "width", "height", "loading", "decoding"],
192
+ th: ["colspan", "rowspan"],
193
+ td: ["colspan", "rowspan"],
194
+ figure: ["data-nbk-embed-service", "data-nbk-embed-key", "data-nbk-embed-url"],
195
+ div: ["data-nbk-toc"]
196
+ };
197
+ var LINK_SCHEMES = /* @__PURE__ */ new Set(["http:", "https:", "mailto:"]);
198
+ var IMAGE_PREFIX = "https://assets.st-note.com/";
199
+ var IMAGE_HOST = "assets.st-note.com";
200
+ var SAFE_VALUE = /^[A-Za-z0-9\-_.:/]+$/;
201
+ var DIGITS = /^\d+$/;
202
+ var AMAZON_HOSTS = /* @__PURE__ */ new Set(["amazon.co.jp", "www.amazon.co.jp", "amazon.com", "www.amazon.com"]);
203
+ var AFFILIATE_HOSTS = /* @__PURE__ */ new Set([
204
+ "amzn.to",
205
+ "amzn.asia",
206
+ "hb.afl.rakuten.co.jp",
207
+ "af.moshimo.com",
208
+ "px.a8.net",
209
+ "ck.jp.ap.valuecommerce.com"
210
+ ]);
211
+ function parseAbsoluteUrl(raw) {
212
+ const value = raw.replace(/[\t\n\r]/g, "").replace(/^[\u0000- ]+|[\u0000- ]+$/g, "");
213
+ if (!URL.canParse(value)) return void 0;
214
+ return { value, url: new URL(value) };
215
+ }
216
+ function isAffiliate(url) {
217
+ const host = url.hostname.toLowerCase();
218
+ if (AFFILIATE_HOSTS.has(host)) return true;
219
+ return AMAZON_HOSTS.has(host) && url.searchParams.has("tag");
220
+ }
221
+ function transformLink(attribs) {
222
+ const out = {};
223
+ const parsed = attribs.href === void 0 ? void 0 : parseAbsoluteUrl(attribs.href);
224
+ const href = parsed && LINK_SCHEMES.has(parsed.url.protocol) ? parsed : void 0;
225
+ if (href) out.href = href.value;
226
+ const blank = attribs.target?.trim().toLowerCase() === "_blank";
227
+ if (blank) out.target = "_blank";
228
+ const rel = [];
229
+ if (blank) rel.push("nofollow", "noopener", "noreferrer");
230
+ if (href && isAffiliate(href.url)) rel.push("sponsored");
231
+ if (rel.length > 0) out.rel = rel.join(" ");
232
+ return out;
233
+ }
234
+ function transformImage(attribs) {
235
+ const parsed = attribs.src === void 0 ? void 0 : parseAbsoluteUrl(attribs.src);
236
+ if (!parsed || parsed.url.protocol !== "https:" || parsed.url.host !== IMAGE_HOST || parsed.url.username !== "" || parsed.url.password !== "" || !parsed.value.toLowerCase().startsWith(IMAGE_PREFIX)) {
237
+ return void 0;
238
+ }
239
+ const out = { src: parsed.value };
240
+ if (attribs.alt !== void 0) out.alt = attribs.alt;
241
+ if (attribs.width !== void 0 && DIGITS.test(attribs.width)) out.width = attribs.width;
242
+ if (attribs.height !== void 0 && DIGITS.test(attribs.height)) out.height = attribs.height;
243
+ out.loading = "lazy";
244
+ out.decoding = "async";
245
+ return out;
246
+ }
247
+ function transformEmbed(attribs, out) {
248
+ const service = attribs["embedded-service"];
249
+ if (service !== void 0 && SAFE_VALUE.test(service)) out["data-nbk-embed-service"] = service;
250
+ const key = attribs["embedded-content-key"];
251
+ if (key !== void 0 && SAFE_VALUE.test(key)) out["data-nbk-embed-key"] = key;
252
+ const parsed = attribs["data-src"] === void 0 ? void 0 : parseAbsoluteUrl(attribs["data-src"]);
253
+ if (parsed && parsed.url.protocol === "https:") out["data-nbk-embed-url"] = parsed.value;
254
+ }
255
+ function transform(tagName, attribs) {
256
+ if (tagName === "table-of-contents") return { tagName: "div", attribs: { "data-nbk-toc": "" } };
257
+ if (tagName === "div") return { tagName, attribs: {} };
258
+ let out = {};
259
+ if (tagName === "a") {
260
+ out = transformLink(attribs);
261
+ } else if (tagName === "img") {
262
+ const image = transformImage(attribs);
263
+ if (!image) return { tagName, attribs: {} };
264
+ out = image;
265
+ } else if (tagName === "th" || tagName === "td") {
266
+ for (const name of ["colspan", "rowspan"]) {
267
+ const value = attribs[name];
268
+ if (value !== void 0 && DIGITS.test(value)) out[name] = value;
269
+ }
270
+ } else if (tagName === "figure") {
271
+ transformEmbed(attribs, out);
272
+ }
273
+ if (attribs.id !== void 0 && SAFE_VALUE.test(attribs.id)) out.id = `nbk-${attribs.id}`;
274
+ return { tagName, attribs: out };
275
+ }
276
+ function sanitizeNoteBody(html) {
277
+ let tocDepth = 0;
278
+ return sanitizeHtml(html, {
279
+ allowedTags: ALLOWED_TAGS,
280
+ allowedAttributes: ALLOWED_ATTRIBUTES,
281
+ allowedSchemes: ["http", "https", "mailto"],
282
+ allowedSchemesByTag: { img: ["https"] },
283
+ allowProtocolRelative: false,
284
+ disallowedTagsMode: "discard",
285
+ nonTextTags: DISCARD_WITH_CONTENT,
286
+ selfClosing: ["img", "br", "hr"],
287
+ enforceHtmlBoundary: false,
288
+ // 属性値の実体参照を解いた値で URL を判定し、出力時にエスケープする前提(既定値だが明示する)
289
+ parser: { decodeEntities: true },
290
+ onOpenTag: (name) => {
291
+ if (tocDepth > 0 || name === "table-of-contents") tocDepth++;
292
+ },
293
+ onCloseTag: () => {
294
+ if (tocDepth > 0) tocDepth--;
295
+ },
296
+ transformTags: { "*": transform },
297
+ exclusiveFilter: (frame) => {
298
+ if (tocDepth > 0) return true;
299
+ if (frame.tag === "div") return "excludeTag";
300
+ if (frame.tag === "img" && frame.attribs.src === void 0) return true;
301
+ return false;
302
+ },
303
+ textFilter: (text) => tocDepth > 0 ? "" : text
304
+ });
305
+ }
129
306
  function hasControlOrSpace(value) {
130
307
  for (let i = 0; i < value.length; i += 1) {
131
308
  const code = value.charCodeAt(i);
@@ -143,67 +320,116 @@ function isHttpsUrl(value) {
143
320
  }
144
321
  var httpsUrl = z.string().refine(isHttpsUrl, "https \u306E URL \u3067\u306F\u3042\u308A\u307E\u305B\u3093");
145
322
  var optionalHttpsUrl = z.string().refine((value) => value.trim() === "" || isHttpsUrl(value), "https \u306E URL \u3067\u306F\u3042\u308A\u307E\u305B\u3093");
146
- var contentSchema = z.object({
147
- key: z.string().min(1),
323
+ function emptyToNull(value) {
324
+ return value.trim() === "" ? null : value;
325
+ }
326
+
327
+ // src/server/normalize/note.ts
328
+ var EXCERPT_LENGTH = 240;
329
+ var noteSchema = z.object({
330
+ key: z.string().regex(NOTE_KEY_RE),
148
331
  name: z.string(),
149
- noteUrl: httpsUrl,
150
- publishAt: z.string().refine((value) => !Number.isNaN(Date.parse(value)), "\u65E5\u6642\u3068\u3057\u3066\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093"),
151
332
  body: z.string(),
152
- eyecatch: optionalHttpsUrl,
153
- hashtags: z.array(z.object({ hashtag: z.object({ name: z.string() }) })),
154
- likeCount: z.number(),
333
+ note_url: httpsUrl,
334
+ publish_at: z.string().refine((value) => !Number.isNaN(Date.parse(value)), "\u65E5\u6642\u3068\u3057\u3066\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093"),
335
+ // 見出し画像のない記事の例は fixture にないため、null も「画像なし」として受け付ける
336
+ eyecatch: optionalHttpsUrl.nullable(),
337
+ eyecatch_alt: z.string().nullable(),
338
+ eyecatch_width: z.number().nullable(),
339
+ eyecatch_height: z.number().nullable(),
340
+ hashtag_notes: z.array(z.object({ hashtag: z.object({ name: z.string() }) })),
341
+ like_count: z.number(),
155
342
  price: z.number(),
343
+ can_read: z.boolean(),
344
+ // 目次と埋め込みは、1件の形が違うだけで記事全体を失敗させないよう、項目ごとに検証して除く
345
+ index: z.array(z.unknown()),
346
+ embedded_contents: z.array(z.unknown()),
156
347
  user: z.object({
157
348
  nickname: z.string(),
158
- urlname: z.string(),
159
- userProfileImagePath: optionalHttpsUrl
349
+ // 著者の確認やリンクの組み立てに使われるため、note のユーザー名の形式に限る
350
+ urlname: z.string().regex(NOTE_USER_RE),
351
+ user_profile_image_path: optionalHttpsUrl
160
352
  })
161
353
  });
162
- var contentsResponseSchema = z.object({
163
- data: z.object({
164
- contents: z.array(contentSchema),
165
- isLastPage: z.boolean(),
166
- totalCount: z.number()
167
- })
354
+ var responseSchema = z.object({ data: noteSchema });
355
+ var tocItemSchema = z.object({
356
+ body: z.string(),
357
+ name: z.string().regex(SAFE_VALUE),
358
+ level: z.enum(["h2", "h3"])
168
359
  });
169
- function emptyToNull(value) {
170
- return value.trim() === "" ? null : value;
360
+ var embedSchema = z.object({
361
+ key: z.string().regex(SAFE_VALUE),
362
+ service: z.string().regex(SAFE_VALUE),
363
+ url: z.string().refine(isHttpsUrl)
364
+ });
365
+ function toToc(index) {
366
+ return index.flatMap((item) => {
367
+ const result = tocItemSchema.safeParse(item);
368
+ if (!result.success) return [];
369
+ const { body, name, level } = result.data;
370
+ return [{ id: `nbk-${name}`, text: body, level: level === "h2" ? 2 : 3 }];
371
+ });
171
372
  }
172
- function toSummary(content) {
173
- return {
174
- key: content.key,
175
- title: content.name,
176
- url: content.noteUrl,
177
- publishedAt: new Date(content.publishAt).toISOString(),
178
- excerpt: content.body.trim(),
179
- eyecatchUrl: emptyToNull(content.eyecatch),
180
- hashtags: content.hashtags.map(({ hashtag }) => hashtag.name.replace(/^#/, "")),
181
- likeCount: content.likeCount,
182
- price: content.price,
183
- author: {
184
- name: content.user.nickname,
185
- urlname: content.user.urlname,
186
- imageUrl: emptyToNull(content.user.userProfileImagePath)
187
- },
188
- source: "api"
189
- };
373
+ function toEmbeds(contents) {
374
+ return contents.flatMap((item) => {
375
+ const result = embedSchema.safeParse(item);
376
+ return result.success ? [{ key: result.data.key, service: result.data.service, url: result.data.url }] : [];
377
+ });
190
378
  }
191
- function normalizeContentsPage(json, page) {
192
- const result = contentsResponseSchema.safeParse(json);
379
+ function toEyecatch(note) {
380
+ const url = note.eyecatch === null ? null : emptyToNull(note.eyecatch);
381
+ if (url === null) return null;
382
+ return { url, width: note.eyecatch_width, height: note.eyecatch_height, alt: note.eyecatch_alt ?? "" };
383
+ }
384
+ var BLOCK_END = /<br \/>|<\/(?:p|h2|h3|h4|li|blockquote|figcaption|pre|td|th|tr)>/g;
385
+ function toExcerpt(bodyHtml) {
386
+ const text = bodyHtml.replace(BLOCK_END, " ").replace(/<[^>]*>/g, "").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&").replace(/\s+/g, " ").trim();
387
+ return Array.from(text).slice(0, EXCERPT_LENGTH).join("");
388
+ }
389
+ function normalizeNote(json) {
390
+ const result = responseSchema.safeParse(json);
193
391
  if (!result.success) {
194
- throw new NoteSchemaError("Unexpected shape of the note article list response", {
392
+ throw new NoteSchemaError("Unexpected shape of the note article response", {
195
393
  issues: result.error.issues.map((issue) => ({ path: issue.path.map(String).join("."), message: issue.message }))
196
394
  });
197
395
  }
198
- const { data } = result.data;
396
+ const note = result.data.data;
397
+ const bodyHtml = sanitizeNoteBody(note.body);
398
+ const eyecatch = toEyecatch(note);
199
399
  return {
200
- articles: data.contents.map(toSummary),
201
- page,
202
- totalCount: data.totalCount,
203
- isLastPage: data.isLastPage
400
+ key: note.key,
401
+ title: note.name,
402
+ url: note.note_url,
403
+ publishedAt: new Date(note.publish_at).toISOString(),
404
+ excerpt: toExcerpt(bodyHtml),
405
+ eyecatchUrl: eyecatch?.url ?? null,
406
+ hashtags: note.hashtag_notes.map(({ hashtag }) => hashtag.name.replace(/^#/, "")),
407
+ likeCount: note.like_count,
408
+ price: note.price,
409
+ author: {
410
+ name: note.user.nickname,
411
+ urlname: note.user.urlname,
412
+ imageUrl: emptyToNull(note.user.user_profile_image_path)
413
+ },
414
+ source: "api",
415
+ bodyHtml,
416
+ isPartial: !note.can_read,
417
+ eyecatch,
418
+ toc: toToc(note.index),
419
+ embeds: toEmbeds(note.embedded_contents)
204
420
  };
205
421
  }
206
422
 
423
+ // src/server/request-options.ts
424
+ var DEFAULT_TIMEOUT_MS = 1e4;
425
+ var DEFAULT_MIN_INTERVAL_MS = 1e3;
426
+ var MAX_TIMER_MS = 2 ** 31 - 1;
427
+ function assertMilliseconds(name, value, min) {
428
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > MAX_TIMER_MS) {
429
+ throw new TypeError(`${name} must be a finite number between ${min} and ${MAX_TIMER_MS}: ${String(value)}`);
430
+ }
431
+ }
432
+
207
433
  // src/server/throttle.ts
208
434
  function sleep(ms, signal) {
209
435
  return new Promise((resolve, reject) => {
@@ -246,19 +472,90 @@ function getDefaultThrottle() {
246
472
  return store[GLOBAL_KEY];
247
473
  }
248
474
 
249
- // src/server/list-articles.ts
250
- var USER_RE = /^[A-Za-z0-9_-]{1,64}$/;
251
- var DEFAULT_TIMEOUT_MS = 1e4;
252
- var DEFAULT_MIN_INTERVAL_MS = 1e3;
253
- var MAX_TIMER_MS = 2 ** 31 - 1;
254
- function assertMilliseconds(name, value, min) {
255
- if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > MAX_TIMER_MS) {
256
- throw new TypeError(`${name} must be a finite number between ${min} and ${MAX_TIMER_MS}: ${String(value)}`);
475
+ // src/server/get-article.ts
476
+ async function getArticle(options) {
477
+ const { key, timeoutMs = DEFAULT_TIMEOUT_MS, minIntervalMs = DEFAULT_MIN_INTERVAL_MS, signal } = options;
478
+ if (typeof key !== "string" || !NOTE_KEY_RE.test(key)) {
479
+ throw new TypeError(`Invalid note article key: ${typeof key === "string" ? JSON.stringify(key) : typeof key}`);
480
+ }
481
+ assertMilliseconds("timeoutMs", timeoutMs, 1);
482
+ assertMilliseconds("minIntervalMs", minIntervalMs, 0);
483
+ const url = `${NOTE_ORIGIN}/api/v3/notes/${key}`;
484
+ await getDefaultThrottle()(minIntervalMs, signal);
485
+ const json = await fetchNoteJson(url, { fetch: options.fetch ?? globalThis.fetch, timeoutMs, signal });
486
+ const article = normalizeNote(json);
487
+ if (article.key !== key) {
488
+ throw new NoteSchemaError("note returned a different article than requested", {
489
+ issues: [{ path: "data.key", message: `Expected ${key}` }]
490
+ });
491
+ }
492
+ return article;
493
+ }
494
+ var contentSchema = z.object({
495
+ // リンク・キャッシュキーに使われるため、記事キーの形式に限る
496
+ key: z.string().regex(NOTE_KEY_RE),
497
+ name: z.string(),
498
+ noteUrl: httpsUrl,
499
+ publishAt: z.string().refine((value) => !Number.isNaN(Date.parse(value)), "\u65E5\u6642\u3068\u3057\u3066\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093"),
500
+ body: z.string(),
501
+ // 見出し画像のない記事は null になる(実データで確認。fixture には例がない)
502
+ eyecatch: optionalHttpsUrl.nullable(),
503
+ hashtags: z.array(z.object({ hashtag: z.object({ name: z.string() }) })),
504
+ likeCount: z.number(),
505
+ price: z.number(),
506
+ user: z.object({
507
+ nickname: z.string(),
508
+ // 著者の確認やリンクの組み立てに使われるため、note のユーザー名の形式に限る
509
+ urlname: z.string().regex(NOTE_USER_RE),
510
+ userProfileImagePath: optionalHttpsUrl
511
+ })
512
+ });
513
+ var contentsResponseSchema = z.object({
514
+ data: z.object({
515
+ contents: z.array(contentSchema),
516
+ isLastPage: z.boolean(),
517
+ totalCount: z.number()
518
+ })
519
+ });
520
+ function toSummary(content) {
521
+ return {
522
+ key: content.key,
523
+ title: content.name,
524
+ url: content.noteUrl,
525
+ publishedAt: new Date(content.publishAt).toISOString(),
526
+ excerpt: content.body.trim(),
527
+ eyecatchUrl: content.eyecatch === null ? null : emptyToNull(content.eyecatch),
528
+ hashtags: content.hashtags.map(({ hashtag }) => hashtag.name.replace(/^#/, "")),
529
+ likeCount: content.likeCount,
530
+ price: content.price,
531
+ author: {
532
+ name: content.user.nickname,
533
+ urlname: content.user.urlname,
534
+ imageUrl: emptyToNull(content.user.userProfileImagePath)
535
+ },
536
+ source: "api"
537
+ };
538
+ }
539
+ function normalizeContentsPage(json, page) {
540
+ const result = contentsResponseSchema.safeParse(json);
541
+ if (!result.success) {
542
+ throw new NoteSchemaError("Unexpected shape of the note article list response", {
543
+ issues: result.error.issues.map((issue) => ({ path: issue.path.map(String).join("."), message: issue.message }))
544
+ });
257
545
  }
546
+ const { data } = result.data;
547
+ return {
548
+ articles: data.contents.map(toSummary),
549
+ page,
550
+ totalCount: data.totalCount,
551
+ isLastPage: data.isLastPage
552
+ };
258
553
  }
554
+
555
+ // src/server/list-articles.ts
259
556
  async function listArticles(options) {
260
557
  const { user, page = 1, timeoutMs = DEFAULT_TIMEOUT_MS, minIntervalMs = DEFAULT_MIN_INTERVAL_MS, signal } = options;
261
- if (typeof user !== "string" || !USER_RE.test(user)) {
558
+ if (typeof user !== "string" || !NOTE_USER_RE.test(user)) {
262
559
  throw new TypeError(`Invalid note user name: ${typeof user === "string" ? JSON.stringify(user) : typeof user}`);
263
560
  }
264
561
  if (typeof page !== "number" || !Number.isInteger(page) || page < 1) {
@@ -310,4 +607,4 @@ async function listAllArticles(options) {
310
607
  return { articles, ...step.value };
311
608
  }
312
609
 
313
- export { NoteError, NoteHttpError, NoteNetworkError, NoteNotFoundError, NoteSchemaError, NoteTimeoutError, isNoteError, iterateArticles, listAllArticles, listArticles };
610
+ export { NoteError, NoteHttpError, NoteNetworkError, NoteNotFoundError, NoteSchemaError, NoteTimeoutError, getArticle, isNoteError, iterateArticles, listAllArticles, listArticles };