All files / src/lib/content posts.ts

97.67% Statements 126/129
86.58% Branches 71/82
100% Functions 43/43
100% Lines 114/114

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354                        1x                             1x 1x 1x 1x     2x 2x 2x 2x       20x   106x   19x         19x           10x               40x 40x   40x 1x     39x 4x     35x               13x     22x     1x               6x 3x       2x   2x 7x   7x 1x     6x         17x 30x         51x                     3x 6x                 2x 2x 2x   2x   8x 8x 5x 5x   5x                   3x           5x             2x 3x   2x   1x             2x 2x     1x     6x                                         6x 6x   3x 3x   1x       3x 3x           1x   1x 2x 2x 2x     2x                   3x   3x 6x 7x 7x 7x       3x 7x 7x               9x   9x 8x   5x           5x 4x     1x           1x   1x 4x 4x 4x 4x     1x 2x   3x   3x     4x                 3x   3x 8x 8x 8x 8x 8x 8x 8x 8x     3x 2x 5x     1x 6x                       1x 2x 1x    
import { pinyin } from "pinyin-pro";
 
import type { ArchiveYear, PostLike, TagDirectoryGroup, TaxonomyGroup } from "./types";
 
export type {
  ArchiveMonth,
  ArchiveYear,
  PostLike,
  TagDirectoryGroup,
  TaxonomyGroup,
} from "./types";
 
const monthLabels = [
  "一月",
  "二月",
  "三月",
  "四月",
  "五月",
  "六月",
  "七月",
  "八月",
  "九月",
  "十月",
  "十一月",
  "十二月",
];
 
const asciiLetterPattern = /^[A-Za-z]$/;
const reservedPostSlugPattern = /[/?#%]/u;
const unsafePostFilenamePattern = /[\\:*"<>|]/u;
const windowsReservedPostNamePattern = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/iu;
 
function compareTagInitials(a: string, b: string): number {
  Iif (a === b) return 0;
  Iif (a === "#") return 1;
  Iif (b === "#") return -1;
  return a.localeCompare(b, "en", { sensitivity: "base" });
}
 
function getTagSortKey(name: string): string {
  return Array.from(name.trim())
    .map((char) => {
      if (asciiLetterPattern.test(char)) return char.toLowerCase();
 
      const [charPinyin] = pinyin(char, {
        toneType: "none",
        type: "array",
      });
 
      return (charPinyin ?? char).toLowerCase();
    })
    .join("");
}
 
export function compareTagNames(a: string, b: string): number {
  return (
    getTagSortKey(a).localeCompare(getTagSortKey(b), "en", {
      sensitivity: "base",
    }) || a.localeCompare(b, "zh-CN")
  );
}
 
export function getPostSlug(post: Pick<PostLike, "id" | "data">): string {
  const rawTitle = post.data.title;
  const slug = rawTitle.trim();
 
  if (!slug) {
    throw new Error(`Article title cannot be empty: ${post.id}`);
  }
 
  if (reservedPostSlugPattern.test(slug)) {
    throw new Error(`Article title cannot contain URL-reserved characters: ${post.id}`);
  }
 
  if (
    rawTitle !== slug ||
    unsafePostFilenamePattern.test(slug) ||
    slug === "." ||
    slug === ".." ||
    /[. ]$/u.test(slug) ||
    windowsReservedPostNamePattern.test(slug)
  ) {
    throw new Error(`Article title is not filesystem-safe: ${post.id}`);
  }
 
  return slug;
}
 
const rasterCoverPattern = /\.(webp|png|jpe?g|avif)$/i;
 
/**
 * Cover thumbnails are generated next to the original as `<name>-thumb.webp`
 * (build time for production, on-demand by the dev middleware). Non-raster
 * covers (SVG/GIF/MP4) have no thumb and keep the original URL.
 */
export function getCoverThumb(cover: string): string {
  if (!rasterCoverPattern.test(cover)) return cover;
  return cover.replace(rasterCoverPattern, "-thumb.webp");
}
 
export function validateUniquePostSlugs<TPost extends PostLike>(posts: TPost[]): void {
  const seen = new Set<string>();
 
  for (const post of posts) {
    const slug = getPostSlug(post);
 
    if (seen.has(slug)) {
      throw new Error(`Duplicate article slug: ${slug}`);
    }
 
    seen.add(slug);
  }
}
 
export function sortPostsByDate<TPost extends PostLike>(posts: TPost[]): TPost[] {
  return [...posts].sort(
    (a, b) => b.data.publishedAt.getTime() - a.data.publishedAt.getTime(),
  );
}
 
export function getPublicPosts<TPost extends PostLike>(posts: TPost[]): TPost[] {
  return sortPostsByDate(posts.filter((post) => !post.data.draft));
}
 
/**
 * 精选文章:只返回显式标记 `featured: true` 的文章(按发布时间降序)。
 * 不做"最新文章自动补齐"——新文章默认 featured: false,不会自动进入精选列表。
 */
export function getFeaturedPosts<TPost extends PostLike>(
  posts: TPost[],
  limit = 3,
): TPost[] {
  return getPublicPosts(posts)
    .filter((post) => post.data.featured)
    .slice(0, limit);
}
 
export function getRelatedPosts<TPost extends PostLike>(
  posts: TPost[],
  currentPost: TPost,
  limit = 4,
): TPost[] {
  const currentSlug = getPostSlug(currentPost);
  const currentTags = new Set(currentPost.data.tags ?? []);
  const seenSlugs = new Set<string>();
 
  return getPublicPosts(posts)
    .filter((post) => {
      const slug = getPostSlug(post);
      if (slug === currentSlug || seenSlugs.has(slug)) return false;
      seenSlugs.add(slug);
      return true;
    })
    .map((post) => ({
      post,
      sameSeries: Boolean(
        currentPost.data.series && post.data.series === currentPost.data.series,
      ),
      sharedTags: new Set(post.data.tags ?? []).intersection(currentTags).size,
      sameCategory: post.data.category === currentPost.data.category,
    }))
    .sort(
      (a, b) =>
        Number(b.sameSeries) - Number(a.sameSeries) ||
        b.sharedTags - a.sharedTags ||
        Number(b.sameCategory) - Number(a.sameCategory) ||
        b.post.data.publishedAt.getTime() - a.post.data.publishedAt.getTime(),
    )
    .slice(0, Math.max(0, limit))
    .map(({ post }) => post);
}
 
export function getAdjacentPosts<TPost extends PostLike>(
  posts: TPost[],
  currentSlug: string,
): { previous?: TPost; next?: TPost } {
  const publicPosts = getPublicPosts(posts);
  const currentIndex = publicPosts.findIndex((post) => getPostSlug(post) === currentSlug);
 
  if (currentIndex === -1) return {};
 
  return {
    previous: publicPosts[currentIndex + 1],
    next: publicPosts[currentIndex - 1],
  };
}
 
export function calculateReadingTime(body = ""): number {
  const words = body.trim().split(/\s+/).filter(Boolean).length;
  return Math.max(1, Math.ceil(words / 200));
}
 
const MAX_POST_DESCRIPTION_LENGTH = 150;
 
function stripMarkdownForDescription(markdown: string): string {
  return markdown
    .replace(/<!--[\s\S]*?-->/g, " ")
    .replace(/```[\s\S]*?```/g, " ")
    .replace(/~~~[\s\S]*?~~~/g, " ")
    .replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
    .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
    .replace(/<[^>]+>/g, " ")
    .replace(/^\s{0,3}#{1,6}\s+/gm, " ")
    .replace(/^\s{0,3}>\s?/gm, " ")
    .replace(/^[-*_]{3,}\s*$/gm, " ")
    .replace(/~~([^~]+)~~/g, "$1")
    .replace(/\*\*([^*]+)\*\*/g, "$1")
    .replace(/\*([^*]+)\*/g, "$1")
    .replace(/__([^_]+)__/g, "$1")
    .replace(/`([^`]+)`/g, "$1")
    .replace(/[#>*_|`]/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}
 
export function derivePostDescription(body = ""): string {
  const text = stripMarkdownForDescription(body);
  if (!text) return "";
 
  const chars = Array.from(text);
  if (chars.length <= MAX_POST_DESCRIPTION_LENGTH) return text;
 
  return `${chars.slice(0, MAX_POST_DESCRIPTION_LENGTH).join("").trimEnd()}…`;
}
 
export function getPostDescription<TPost extends PostLike>(post: TPost): string {
  const manual = post.data.description?.trim();
  return manual || derivePostDescription(post.body ?? "");
}
 
export function groupPostsByCategory<TPost extends PostLike>(
  posts: TPost[],
): TaxonomyGroup<TPost>[] {
  const groups = new Map<string, TPost[]>();
 
  for (const post of getPublicPosts(posts)) {
    const list = groups.get(post.data.category) ?? [];
    list.push(post);
    groups.set(post.data.category, list);
  }
 
  return [...groups.entries()].map(([name, groupedPosts]) => ({
    name,
    count: groupedPosts.length,
    posts: groupedPosts,
  }));
}
 
export function groupPostsByTag<TPost extends PostLike>(
  posts: TPost[],
): TaxonomyGroup<TPost>[] {
  const groups = new Map<string, TPost[]>();
 
  for (const post of getPublicPosts(posts)) {
    for (const tag of post.data.tags ?? []) {
      const list = groups.get(tag) ?? [];
      list.push(post);
      groups.set(tag, list);
    }
  }
 
  return [...groups.entries()]
    .sort(([a], [b]) => compareTagNames(a, b))
    .map(([name, groupedPosts]) => ({
      name,
      count: groupedPosts.length,
      posts: groupedPosts,
    }));
}
 
export function getTagInitial(name: string): string {
  const firstChar = Array.from(name.trim())[0];
 
  if (!firstChar) return "#";
  if (asciiLetterPattern.test(firstChar)) return firstChar.toUpperCase();
 
  const [firstPinyin] = pinyin(firstChar, {
    pattern: "first",
    toneType: "none",
    type: "array",
  });
 
  if (firstPinyin && asciiLetterPattern.test(firstPinyin)) {
    return firstPinyin.toUpperCase();
  }
 
  return "#";
}
 
export function groupTagsByInitial<TPost extends PostLike>(
  posts: TPost[],
): TagDirectoryGroup<TPost>[] {
  const groups = new Map<string, TaxonomyGroup<TPost>[]>();
 
  for (const tag of groupPostsByTag(posts)) {
    const initial = getTagInitial(tag.name);
    const list = groups.get(initial) ?? [];
    list.push(tag);
    groups.set(initial, list);
  }
 
  return [...groups.entries()]
    .sort(([a], [b]) => compareTagInitials(a, b))
    .map(([initial, tags]) => {
      const sortedTags = [...tags].sort((a, b) => compareTagNames(a.name, b.name));
 
      return {
        initial,
        count: sortedTags.length,
        postsCount: sortedTags.reduce((sum, tag) => sum + tag.count, 0),
        tags: sortedTags,
      };
    });
}
 
export function groupPostsByArchive<TPost extends PostLike>(
  posts: TPost[],
): ArchiveYear<TPost>[] {
  const years = new Map<number, Map<number, TPost[]>>();
 
  for (const post of getPublicPosts(posts)) {
    const date = post.data.publishedAt;
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const months = years.get(year) ?? new Map<number, TPost[]>();
    const monthPosts = months.get(month) ?? [];
    monthPosts.push(post);
    months.set(month, monthPosts);
    years.set(year, months);
  }
 
  return [...years.entries()]
    .sort(([a], [b]) => b - a)
    .map(([year, months]) => ({
      year,
      months: [...months.entries()]
        .sort(([a], [b]) => b - a)
        .map(([month, monthPosts]) => ({
          month,
          label: monthLabels[month - 1] ?? `${month}月`,
          posts: monthPosts,
        })),
    }));
}
 
export function getSeriesPosts<TPost extends PostLike>(
  posts: TPost[],
  seriesSlug: string,
): TPost[] {
  return getPublicPosts(posts)
    .filter((post) => post.data.series === seriesSlug)
    .sort((a, b) => (a.data.seriesOrder ?? 999) - (b.data.seriesOrder ?? 999));
}