Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
24ef63b
fix(media): preserve original image bytes, format and dimensions
leo72321 Oct 31, 2026
5974f31
fix(media): preserve original image bytes, format and dimensions
leo72321 Oct 31, 2026
f182839
fix(media): preserve original image bytes, format and dimensions
leo72321 Oct 31, 2026
008a98a
feat(media): define isolated CMS media key namespace
leo72321 Oct 31, 2026
8443bd7
feat(media): isolate original assets under per-site CMS prefix
leo72321 Oct 31, 2026
05c642d
feat(media): isolate original assets under per-site CMS prefix
leo72321 Oct 31, 2026
8aa6dde
feat(media): isolate original assets under per-site CMS prefix
leo72321 Oct 31, 2026
8147e85
feat(media): isolate original assets under per-site CMS prefix
leo72321 Oct 31, 2026
db1a445
feat(media): isolate original assets under per-site CMS prefix
leo72321 Oct 31, 2026
1cd3c94
chore(release): bump CMS version to 0.2.6 for original-only media
leo72321 Oct 31, 2026
8f3f646
chore(release): bump CMS version to 0.2.6 for original-only media
leo72321 Oct 31, 2026
02744e3
chore(release): bump CMS version to 0.2.6 for original-only media
leo72321 Oct 31, 2026
b55df03
chore(release): bump CMS version to 0.2.6 for original-only media
leo72321 Oct 31, 2026
7a30166
test(media): align attachment fixtures with isolated CMS directory
leo72321 Oct 31, 2026
b4fd435
fix(media): preserve original CMS per-kind directory layout
leo72321 Oct 31, 2026
f20a45a
fix(media): preserve original CMS per-kind directory layout
leo72321 Oct 31, 2026
2e446d1
fix(media): preserve original CMS per-kind directory layout
leo72321 Oct 31, 2026
4eb66f5
fix(media): preserve original CMS per-kind directory layout
leo72321 Oct 31, 2026
c5f608f
fix(media): preserve original CMS per-kind directory layout
leo72321 Oct 31, 2026
26ae6a3
fix(media): preserve original CMS per-kind directory layout
leo72321 Oct 31, 2026
08d670f
fix(media): preserve original CMS per-kind directory layout
leo72321 Oct 31, 2026
d209f3d
refactor(media): reuse existing documented CMS media folders
leo72321 Oct 31, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

從 v0.2.0 開始,每次更新共通功能、修正公版 BUG 或調整行為,都應提高版本並記錄變更。衍生網站的單純新增文章、SEO 文案或個別設定不代表 CMS 公版升版。

## [0.2.6] - 2026-11-01

- **保留圖片原始檔**:上傳原始位元組、格式與解析度,不再產生 WebP 縮圖或額外的 OG JPEG;封面和社群預覽共用原圖。
- **沿用既有媒體分類目錄**:維持 `網域/site|blog|CPT代碼/永久UID/` 原本的 B2 路徑,與 WordPress `uploads` 分隔;不額外增加 `cms/` 層級,不改動既有 URL。

## [0.2.5] - 2026-10-27

- **高頻 Agent CI 分流**:文章與索引改動只做內容 Schema/URL 快檢;程式與設定改動保留完整驗收,減少重複 Astro 建置。
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# 天公仔CMS

目前公版版本:**v0.2.5**|[查看版本更新紀錄](CHANGELOG.md)
目前公版版本:**v0.2.6**|[查看版本更新紀錄](CHANGELOG.md)

<p align="center">
<img src="assets/php-tiangong-meme.webp" alt="天公仔 PHP 工程師梗圖:寫 PHP 是走投無路的人在做的,老子我天公仔,看起來像走投無路的嗎?" width="680" />
Expand Down
10 changes: 5 additions & 5 deletions docs/圖片操作.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# 圖片操作

給圖片路徑、文章 ID 與替代文字,工具會縮圖、上傳並填回文章。
給圖片原始檔、文章 ID 與替代文字,工具會原檔上傳並填回文章,不會再縮圖或轉成 WebP。

## 第一次設定

Expand All @@ -27,7 +27,7 @@
npm run media:add -- --uid 範例新增文章 --file "D:/圖片/cover.png" --alt "文章與分類的關係" --cover
```

產生單尺寸 WebP(最大寬 1440,小圖不放大);封面額外產生 1200 × 630 的分享圖片。成功後自動寫入 `cover` 的網址、替代文字、寬高與各尺寸。
保留來源圖片的原始位元組、格式、完整尺寸;不再生成其他尺寸的 WebP 或 1200 × 630 OG 副本。封面與 OG 皆引用同一張原圖,`variants` 為空。

## 內文

Expand All @@ -43,13 +43,13 @@ npm run media:add -- --uid 範例新增文章 --file "D:/圖片/cover.png" --alt
npm run media:add -- --uid 範例新增文章 --file "D:/圖片/流程.png" --alt "從寫作到發布的流程" --name 流程圖
```

成功後換成 Markdown 圖片,建置時補上寬高、自適應尺寸與延遲載入。封面可重跑覆換;內文重插時,先將原圖片換回占位符。
成功後換成 Markdown 圖片,建置時補上寬高與延遲載入。封面可重跑覆換;內文重插時,先將原圖片換回占位符。

加 `--dry-run`(預覽模式)只列出處理結果與目標網址,不上傳、不改文章、不需金鑰。

## 上傳成功與連結檢查

圖片轉檔後交給 B2 Native 或 S3 上傳 API。**API 明確成功後,只對這次上傳的圖片網址發出一次 HTTP HEAD**,確認連結是 2xx,且回應標頭沒有顯示 HTML 假圖片或空檔案。不使用 GET 下載媒體內容,不計算下載後雜湊,也不對同一張圖連續重試。若 HEAD 回 404/403/405 或不正確的類型,就顯示錯誤並暫停更新文章,請檢查 CDN 設定。
圖片原檔交給 B2 Native 或 S3 上傳 API。**API 明確成功後,只對這次上傳的圖片網址發出一次 HTTP HEAD**,確認連結是 2xx,且回應標頭沒有顯示 HTML 假圖片或空檔案。不使用 GET 下載媒體內容,不計算下載後雜湊,也不對同一張圖連續重試。若 HEAD 回 404/403/405 或不正確的類型,就顯示錯誤並暫停更新文章,請檢查 CDN 設定。

B2 Native API 的 SHA-1 是該 API 上傳所需的原生校驗欄位,與重新下載檔案無關;媒體 manifest 仍保留現有 SHA-1、尺寸、時間等欄位,確保既有資料相容。S3 API 接收上傳成功回應後不額外 GET 檔案。內容雜湊仍可用於避免圖片同名與快取衝突。

Expand All @@ -74,7 +74,7 @@ npm run media:verify -- --batch-size 1000 # 手動分批 HEAD

## CPT 圖片路徑

新上傳圖片依 `網域/site|blog|CPT代碼/永久UID/檔案` 儲存,不與會改變的文章分類及 Slug 綁定。已存在的圖片路徑保持不動,操作詳見 [CPT 自訂內容](CPT自訂內容.md)。
沿用既有媒體目錄:`網域/site|blog|CPT代碼/永久UID/原檔`。同一 Bucket 內每個網站依網域隔離;WordPress 舊圖保留在 `網域/wp-content/uploads/`,不會混用。這次只調整新圖片保留原檔的行為,既有 URL 不自動改寫;現有 WebP 衍生圖另經來源核對、B2 原圖複製及 CDN 驗證後再切換。操作詳見 [CPT 自訂內容](CPT自訂內容.md)。

## 附件上傳:PDF/ZIP/Office 及其他檔案

Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "cms-template",
"version": "0.2.5",
"version": "0.2.6",
"private": true,
"type": "module",
"description": "少爺的輕量靜態網站公版:繁體中文操作、Post / Page、SEO 自動化與 B2 圖床",
Expand Down
42 changes: 28 additions & 14 deletions scripts/lib/media.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,36 @@
import { readFileSync } from 'node:fs';
import sharp from 'sharp';
import { createHash } from 'node:crypto';
import type { Site } from '../../src/lib/schema';
import type { ImageUpload } from './b2';
import { mediaBase } from '../../src/lib/settings';

// Preserve the exact source bytes and dimensions. Never generate WebP, resized
// copies or a second OG asset; the original also serves as the share image.
export async function prepareMedia(file: string | Buffer, site: Site, path: string, name: string, cover: boolean): Promise<ImageUpload[]> {
const source = await sharp(file, { animated: false }).rotate().toBuffer();
const metadata = await sharp(source).metadata();
if (!['jpeg', 'png', 'webp', 'avif', 'tiff', 'gif'].includes(metadata.format ?? '') || !metadata.width || !metadata.height) throw new Error('請提供 JPG、PNG、WebP、AVIF、TIFF 或 GIF 圖片。GIF 只保留第一格。');
// 單尺寸 WebP(最大 1440,絕不放大小圖);封面另外產生一張 OG JPEG。
const widths = [Math.min(1440, metadata.width!)];
const items: ImageUpload[] = [];
const add = async (bytes: Buffer, suffix: string, contentType: string) => {
const meta = await sharp(bytes).metadata();
const hash = createHash('sha256').update(bytes).digest('hex').slice(0, 16);
const relative = `${path.replace(/^\/+|\/+$/g, '')}/${name}-${suffix}-${hash}.${contentType === 'image/jpeg' ? 'jpg' : 'webp'}`;
items.push({ bytes, objectName: `${site.domain}/${relative}`, contentType, width: meta.width!, height: meta.height!, url: mediaBase(site) + relative.split('/').map(encodeURIComponent).join('/') });
void cover;
const bytes = typeof file === 'string' ? readFileSync(file) : file;
if (!bytes.length) throw new Error('圖片不能是空檔案。');
const metadata = await sharp(bytes, { animated: false }).metadata();
const formats: Record<string, { extension: string; contentType: string }> = {
jpeg: { extension: 'jpg', contentType: 'image/jpeg' },
png: { extension: 'png', contentType: 'image/png' },
webp: { extension: 'webp', contentType: 'image/webp' },
avif: { extension: 'avif', contentType: 'image/avif' },
gif: { extension: 'gif', contentType: 'image/gif' },
};
for (const width of widths) await add(await sharp(source).resize({ width, withoutEnlargement: true }).webp({ quality: 80, effort: 5 }).toBuffer(), `${width}w`, 'image/webp');
if (cover) await add(await sharp(source).resize(1200, 630, { fit: 'cover', position: 'attention' }).jpeg({ quality: 82, mozjpeg: true }).toBuffer(), 'og', 'image/jpeg');
return items;
const format = formats[metadata.format ?? ''];
if (!format || !metadata.width || !metadata.height) {
throw new Error('原檔格式不適合直接在網頁顯示;請使用 JPG、PNG、WebP、AVIF 或 GIF。TIFF/HEIF 不會暗中轉檔。');
}
const hash = createHash('sha256').update(bytes).digest('hex').slice(0, 16);
const relative = `${path.replace(/^\/+|\/+$/g, '')}/${name}-${hash}.${format.extension}`;
return [{
bytes,
objectName: `${site.domain}/${relative}`,
contentType: format.contentType,
width: metadata.width,
height: metadata.height,
url: mediaBase(site) + relative.split('/').map(encodeURIComponent).join('/'),
}];
}
10 changes: 5 additions & 5 deletions scripts/media.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ run(async () => {
'CPT 相簿:npm run media:add -- --uid UID --file ./car.jpg --alt 車輛照片 --field photos(自動追加到 gallery)',
'CPT 附件:npm run media:add -- --uid UID --file ./report.pdf --field report(自動填入 file 欄位)',
'一般文章附件:npm run media:add -- --uid UID --file ./report.pdf --name report --label 車況報告(內文先放 <!-- 檔案:report -->)',
'支援 PDF、ZIP、Office、CSV、TXT、7Z、RAR、音訊及影片等附件(單檔 <=100 MiB);圖片單尺寸 WebP。',
'支援 PDF、ZIP、Office、CSV、TXT、7Z、RAR、音訊及影片等附件(單檔 <=100 MiB);圖片只保留原始檔,無轉檔及縮圖。',
'附加 --dry-run 只列出目標網址,不上傳、不修改任何內容。',
].join('\n'));
return;
Expand Down Expand Up @@ -56,7 +56,7 @@ run(async () => {
const items = isImage
? await prepareMedia(values.file, site, path, name, !!values.cover)
: [prepareAttachment(values.file, site, path, name)];
const imageVariants = isImage ? items.filter((i): i is ImageUpload => i.contentType === 'image/webp' && i.width !== undefined && i.height !== undefined) : [];
const imageVariants = isImage ? items.filter((i): i is ImageUpload => i.width !== undefined && i.height !== undefined) : [];
const main = isImage ? imageVariants.at(-1)! : items[0];
if (!main) throw new Error('沒有產生可上傳的媒體。');
const url = main.url;
Expand Down Expand Up @@ -98,8 +98,8 @@ run(async () => {
const cover = imageVariants.at(-1)!;
parsed.data.cover = {
url: cover.url, alt: values.alt, width: cover.width, height: cover.height,
variants: imageVariants.map(i => ({ url: i.url, width: i.width })),
ogUrl: items.find(i => i.contentType === 'image/jpeg')!.url,
variants: [],
ogUrl: cover.url,
};
} else if (fieldType && values.field) {
parsed.data.fields = nextFields;
Expand All @@ -117,7 +117,7 @@ run(async () => {
records.set(receipt.url, {
...receipt,
...(imageVariants.some(i => i.url === receipt.url)
? { variants: imageVariants.map(i => ({ url: i.url, width: i.width })) }
? { variants: [] }
: {}),
});
}
Expand Down
13 changes: 9 additions & 4 deletions tests/media.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,25 @@ import { prepareMedia } from '../scripts/lib/media';
import { uploadB2, type Upload } from '../scripts/lib/b2';
import { siteSchema } from '../src/lib/schema';
const site = siteSchema.parse({ domain: 'site.example.org', title: '測試', description: '說明', author: '作者', media: { bucket: 'wordpress-cdn' } });
test('圖片只產生單尺寸 WebP 與分享圖片,中文路徑只編碼一次', async () => {
test('圖片及 OG 只引用原始檔,不重新編碼、不產生尺寸版本,中文路徑只編碼一次', async () => {
const image = await sharp({ create: { width: 1600, height: 900, channels: 4, background: '#287655' } }).png().toBuffer();
const output = await prepareMedia(image, site, '/分類/文章/', 'cover', true);
assert.deepEqual(output.filter(o => o.contentType === 'image/webp').map(o => o.width), [1440]);
assert.equal(output.at(-1)!.width, 1200); assert.equal(output.at(-1)!.height, 630);
assert.equal(output.length, 1);
assert.equal(output[0].contentType, 'image/png');
assert.equal(output[0].width, 1600);
assert.equal(output[0].height, 900);
assert.ok(output[0].objectName.endsWith('.png'));
assert.deepEqual(output[0].bytes, image);
assert.ok(output[0].objectName.startsWith('site.example.org/分類/文章/'));
assert.ok(output[0].url.startsWith('https://cdn.site.example.org/file/wordpress-cdn/site.example.org/%E5%88%86%E9%A1%9E/'));
assert.deepEqual((await prepareMedia(image, site, '/分類/文章/', 'cover', true)).map(o => o.url), output.map(o => o.url));
});
test('小圖不放大,內容雜湊會隨圖片內容變更', async () => {
test('原始 GIF 不會被截為首格;內容雜湊隨圖片變更', async () => {
const image = (background: string) => sharp({ create: { width: 300, height: 200, channels: 3, background } }).png().toBuffer();
const a = await prepareMedia(await image('#ffffff'), site, '/分類/文章/', '圖', false);
const b = await prepareMedia(await image('#000000'), site, '/分類/文章/', '圖', false);
assert.equal(a.length, 1); assert.equal(a[0].width, 300); assert.notEqual(a[0].url, b[0].url);
assert.equal(a[0].contentType, 'image/png');
});
const bytes = Buffer.from('image-test-data');
const digest = createHash('sha1').update(bytes).digest('hex');
Expand Down
Loading