Ship the page-focused follow reply with the news and shop updates.

Replace the subscribe welcome with page-generation examples, add the trial news003 WeChat share card, and let OneShop checkout return to an order or recharge page.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
john
2026-11-25 14:30:20 +08:00
parent 59f85fb5f9
commit 7f06361bd3
13 changed files with 522 additions and 146 deletions
+5 -1
View File
@@ -6,7 +6,8 @@
| 模板 | 版本 | 状态 | 说明 |
|------|------|------|------|
| `news001` | `2026-09-18-refined` | frozen | 2026-09-18 定稿版式,已上生产。**只读,不允许就地修改**;要改版式请新开 `news003`。 |
| `news002` | `2026-09-21-subscriber` | active | 订阅向改版:事件唯一化、每条配图、报头版式、深色模式。 |
| `news002` | `2026-09-21-subscriber` | active | 订阅向改版:事件唯一化、每条配图、报头版式、深色模式。生产默认仍是这一版。 |
| `news003` | `2026-11-21-wechat-forward` | trial | 页面仍是 news002。公众号标题用第一条的具体判断,摘要用新闻标题,其余列表保持紧凑。未切生产。 |
## 切换模板
@@ -146,6 +147,9 @@ news002 的卡片图会先上传到微信正文素材接口,再由 inline 渲
# 渲染一张 news002 静态预览页(样例数据,占位图)
node scripts/preview-news002-template.mjs /tmp/news002-preview.html
# 渲染 news003 公众号对照(分享卡 + 正文,不切换生产模板)
node scripts/preview-news003-template.mjs .tmp/news003-preview.html
# 用当天真实新闻 + 对应文章来源图片生成视觉样图(不推微信、不写生产目录)
node scripts/build-news002-real-design-sample.mjs
+39 -2
View File
@@ -550,6 +550,31 @@ export const NEWS002_FRESH_CONTENT_SPEC = [
'10. 禁止八卦绯闻、未经证实的传闻、标题党;每条都要能说清「为什么重要」,说不清就不要写。',
].join('\n');
/* ------------------------------------------------------------------ *
* news003 · 页面沿用 news002,公众号正文更紧凑
* ------------------------------------------------------------------ */
export const NEWS003_VERSION = '2026-11-21-wechat-forward';
export const NEWS003_MAX_STORY_CARDS = NEWS002_MAX_STORY_CARDS;
export const NEWS003_SECTIONS = NEWS002_SECTIONS;
export const NEWS003_STYLE_BLOCK = NEWS002_STYLE_BLOCK;
export const NEWS003_SEO_SPEC = NEWS002_SEO_SPEC;
export const NEWS003_TEMPLATE_SPEC = [
'生成「每日新闻早报」静态 HTML 页面(daily-news-MMDD.html)。',
'页面继续用 news002,不要改栏目、卡片、配图和色值。news003 只改公众号:分享标题用第一条的判断,其余列表保持紧凑。',
'在 `<html>` 上增加 `data-news-template="news003"`,其余 DOM 与 news002 相同。',
'第一条 `<a class="lead-card">` 的 `.why` 就是公众号标题,不超过 22 字。写出具体变化和读者要付出或得到的东西,有数字或时间就写上。',
'标题禁止「转给」「速看」「先看这条」「你一定要知道」「建议转发」「震惊」。不要写「为什么重要」套话,不要用栏目名。',
'同一条的 h3 仍是新闻标题,公众号摘要用它。其余卡片的 `.why` 仍按 news002。',
'',
NEWS002_TEMPLATE_SPEC,
].join('\n');
export const NEWS003_FRESH_CONTENT_SPEC = NEWS002_FRESH_CONTENT_SPEC;
/* ------------------------------------------------------------------ *
* 注册表
* ------------------------------------------------------------------ */
@@ -579,6 +604,18 @@ export const NEWS_MORNING_TEMPLATES = {
seoSpec: NEWS002_SEO_SPEC,
templateSpec: NEWS002_TEMPLATE_SPEC,
},
news003: {
id: 'news003',
version: NEWS003_VERSION,
label: '每日新闻早报 · 公众号转发版(news003)',
status: 'trial',
referenceUrl: null,
supportsCardImages: true,
maxStoryCards: NEWS003_MAX_STORY_CARDS,
freshContentSpec: NEWS003_FRESH_CONTENT_SPEC,
seoSpec: NEWS003_SEO_SPEC,
templateSpec: NEWS003_TEMPLATE_SPEC,
},
};
export const NEWS_MORNING_TEMPLATE_IDS = Object.keys(NEWS_MORNING_TEMPLATES);
@@ -607,9 +644,9 @@ function envFlag(value, fallback = true) {
export function buildNewsMorningTemplateSpec(templateId, env = process.env) {
const template = getNewsMorningTemplate(templateId, env);
const requireFill = template.id === 'news002'
const requireFill = (template.id === 'news002' || template.id === 'news003')
&& envFlag(env.MEMIND_NEWS_MORNING_NEWS002_REQUIRE_FILL, true);
const subscribeHistorySpec = template.id === 'news002'
const subscribeHistorySpec = template.id === 'news002' || template.id === 'news003'
? [
buildNewsMorningSubscribeBlockSpec(env),
buildNewsMorningHistorySectionSpec(),
+24 -2
View File
@@ -18,14 +18,21 @@ import {
countNews002SectionItems,
getNewsMorningTemplate,
NEWS002_FILL_REQUIREMENT_SPEC,
NEWS003_MAX_STORY_CARDS,
NEWS003_SECTIONS,
NEWS003_STYLE_BLOCK,
NEWS003_TEMPLATE_SPEC,
NEWS003_VERSION,
resolveNewsMorningTemplateId,
} from './news-morning-templates.mjs';
test('registry exposes news001 and news002', () => {
assert.deepEqual(NEWS_MORNING_TEMPLATE_IDS, ['news001', 'news002']);
test('registry exposes news001, news002 and news003', () => {
assert.deepEqual(NEWS_MORNING_TEMPLATE_IDS, ['news001', 'news002', 'news003']);
assert.equal(NEWS_MORNING_TEMPLATES.news001.status, 'frozen');
assert.equal(NEWS_MORNING_TEMPLATES.news001.version, NEWS001_VERSION);
assert.equal(NEWS_MORNING_TEMPLATES.news002.version, NEWS002_VERSION);
assert.equal(NEWS_MORNING_TEMPLATES.news003.version, NEWS003_VERSION);
assert.equal(NEWS_MORNING_TEMPLATES.news003.status, 'trial');
});
test('news001 stays byte-identical to the frozen 0918 spec', () => {
@@ -104,6 +111,21 @@ test('buildNewsMorningTemplateSpec assembles content + seo + layout', () => {
assert.ok(!spec002.includes('版式参照(只读结构)'), 'news002 自带样式,不依赖外部参照页');
});
test('news003 keeps the news002 page and only marks the denser WeChat variant', () => {
assert.equal(NEWS003_STYLE_BLOCK, NEWS002_STYLE_BLOCK);
assert.equal(NEWS003_MAX_STORY_CARDS, NEWS002_MAX_STORY_CARDS);
assert.match(NEWS003_TEMPLATE_SPEC, /data-news-template="news003"/);
assert.match(NEWS003_TEMPLATE_SPEC, /页面继续用 news002/);
assert.match(NEWS003_TEMPLATE_SPEC, /不超过 22 字/);
assert.match(NEWS003_TEMPLATE_SPEC, /禁止「转给」/);
assert.match(NEWS003_TEMPLATE_SPEC, /#FAF7F2/);
const spec = buildNewsMorningTemplateSpec('news003', {});
assert.match(spec, /版式模板:news003/);
assert.ok(spec.includes(NEWS002_FILL_REQUIREMENT_SPEC));
assert.equal(DEFAULT_NEWS_MORNING_TEMPLATE_ID, 'news002');
assert.equal(resolveNewsMorningTemplateId('news003', {}), 'news003');
});
test('auditNews002SectionFill requires core max counts and flex coverage', () => {
const sparse = `<div class="section" id="brief"><ol class="brief"><li><span class="n">1</span><span>一</span></li></ol></div>
<div class="section" id="headlines"><a class="lead-card" data-event-key="a"><div class="body"><h3>头条</h3></div></a></div>`;
+76
View File
@@ -0,0 +1,76 @@
/**
* 对照渲染 news002 / news003 的公众号分享卡和正文。页面结构相同。
*
* node scripts/preview-news003-template.mjs [输出路径]
*/
import fs from 'node:fs';
import path from 'node:path';
import { convertDailyNewsHtmlToWechatInlineArticle } from '../wechat-daily-news-inline.mjs';
const LEAD = ['国际油价一夜上涨', '布伦特原油隔夜上涨约 4%。国内成品油调价窗口就在这两天。', '明天加油,每升多花近两毛'];
const ITEMS = [
['东博会在南宁开幕', '本届参展企业超过三千家。主办方预计到场采购商多于去年。'],
['央行维持政策利率', '公开市场继续净投放,资金面保持平稳。银行间利率围绕政策利率波动。'],
['高铁新线开始试运行', '沿线车站完成联调。正式通车日期还要等监管部门公布。'],
['沪指窄幅整理', '成交额较前一日略有萎缩。权重股分化,题材股成交靠前。'],
['芯片厂上调资本开支', '先进制程订单排到明年二季度。设备交货周期仍在拉长。'],
['冷空气开始南下', '明起华北有明显降温。部分地区风力加大,出行要注意。'],
];
const leadThumb = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360"><rect width="640" height="360" fill="#1b3a6b"/><rect y="210" width="640" height="150" fill="#c8362f"/><circle cx="470" cy="120" r="46" fill="#f4e7c5"/></svg>')}`;
const thumb = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="72" height="54"><rect width="72" height="54" fill="#e4e4e4"/><path d="M0 40 L18 22 L32 34 L50 14 L72 36 V54 H0 Z" fill="#bdbdbd"/></svg>')}`;
function page(templateId) {
const [title, body, why] = LEAD;
const lead = `<a class="lead-card" data-event-key="lead"><div class="media"><img src="${leadThumb}" alt="${title}"></div><div class="body"><span class="tag">能源</span><h3>${title}</h3><p>${body}</p><div class="why"><b>为什么重要</b>:${why}</div></div></a>`;
const cards = ITEMS.map(([itemTitle, itemBody], index) =>
`<div class="card" data-event-key="k${index}"><div class="media"><img src="${thumb}" alt="${itemTitle}"></div><div class="body"><span class="tag">要闻</span><h3>${itemTitle}</h3><p>${itemBody}</p><div class="why"><b>为什么重要</b>:这句只留在页面上。</div></div></div>`,
).join('\n');
return `<html data-news-template="${templateId}"><head>
<title>每日新闻早报 · 2026年11月21日</title>
<meta name="description" content="今日要闻">
</head><body>
<div class="masthead"><h1>每日新闻早报</h1><div class="meta"><b>2026年11月21日</b> · 星期六 · 第 280 期</div></div>
<div class="lede">中美外长再次通话 · 东博会南宁开幕 · 央行维持政策利率</div>
<div class="section" id="headlines"><div class="section-title"><h2>今日头条</h2></div>${lead}${cards}</div>
</body></html>`;
}
function column(label, html, cover) {
const article = convertDailyNewsHtmlToWechatInlineArticle(html, {
includeFixedLayout: false,
imageUrlMap: new Map([[leadThumb, leadThumb], [thumb, thumb]]),
});
return `<section class="phone"><p class="label">${label}</p>
<div class="share"><img src="${cover}" alt=""><div><p class="share-title">${article.title}</p><p class="share-digest">${article.digest}</p></div></div>
<div class="screen">${article.content}</div></section>`;
}
const brandCover = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="120" height="120"><rect width="120" height="120" fill="#1a1a2e"/><text x="60" y="66" fill="#fff" font-size="14" text-anchor="middle">早报</text></svg>')}`;
const out = process.argv[2] || path.join(process.cwd(), '.tmp', 'news003-preview.html');
const html = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>公众号对照 · news002 / news003</title>
<style>
body{margin:0;background:#f3f3f3;font-family:-apple-system,"PingFang SC",sans-serif}
h1{font-size:16px;font-weight:600;margin:0;padding:16px 16px 0}
.note{margin:6px 16px 12px;color:#666;font-size:13px}
.row{display:flex;gap:16px;align-items:flex-start;padding:0 16px 32px;overflow:auto}
.phone{width:390px;flex:0 0 390px;background:#ededed;border:1px solid #e5e5e5;border-radius:16px;overflow:hidden}
.label{margin:0;padding:10px 14px;background:#fafafa;border-bottom:1px solid #eee;font-size:13px;font-weight:650}
.share{display:flex;gap:10px;margin:12px;padding:10px;background:#fff;border-radius:6px}
.share img{width:52px;height:52px;object-fit:cover;border-radius:2px;flex:0 0 52px}
.share-title{margin:0;font-size:15px;font-weight:650;line-height:1.35;color:#111}
.share-digest{margin:4px 0 0;font-size:12px;color:#888;line-height:1.4}
.screen{margin:0 12px 16px;padding:12px 14px 20px;background:#fff;border-radius:6px}
</style></head><body>
<h1>公众号对照</h1>
<p class="note">两边是同一份 news002 页面。上面是分享卡,下面是打开后的正文。左边标题是栏目名,右边标题是这条新闻里跟读者有关的具体变化。其余列表保持紧凑。</p>
<div class="row">
${column('现在 · news002', page('news002'), brandCover)}
${column('转发 · news003', page('news003'), brandCover)}
</div>
</body></html>`;
fs.mkdirSync(path.dirname(out), { recursive: true });
fs.writeFileSync(out, html);
console.log(`news003 wechat preview written to ${out}`);
+17 -1
View File
@@ -3,6 +3,22 @@ import { createHmac, timingSafeEqual } from 'node:crypto';
const lifetimeMs = 5 * 60_000;
const signature = (body, secret) => createHmac('sha256', secret)
.update('one-shop-checkout-v1:' + body).digest('base64url');
const returnPathPattern = /^(\/[a-z0-9-]{1,80})?\/(my\/orders\/[1-9]\d*\/pay|recharge)$/;
export function resolveReturnUrl(shopOrigin, { orderId, returnPath } = {}) {
let path = returnPath;
if (path == null || path === '') {
if (!Number.isSafeInteger(orderId) || orderId <= 0) return null;
path = `/my/orders/${orderId}/pay`;
}
const pattern = Number.isSafeInteger(orderId) && orderId > 0
? new RegExp(`^(?:/[a-z0-9-]{1,80})?/my/orders/${orderId}/pay$`)
: /^(?:\/[a-z0-9-]{1,80})?\/recharge$/;
if (typeof path !== 'string' || path.length > 120 || !pattern.test(path)) return null;
const target = new URL(path, shopOrigin);
if (target.origin !== shopOrigin || target.pathname !== path || target.search || target.hash) return null;
return target.href;
}
export function createCheckoutToken(payload, secret, now = Date.now()) {
const body = Buffer.from(JSON.stringify({ ...payload, expires: now + lifetimeMs })).toString('base64url');
@@ -19,7 +35,7 @@ export function readCheckoutToken(token, secret, shopOrigin, now = Date.now()) {
const payload = JSON.parse(Buffer.from(body, 'base64url').toString());
const target = new URL(payload.return_url);
if (!Number.isSafeInteger(payload.expires) || payload.expires <= now || payload.expires > now + lifetimeMs ||
target.origin !== shopOrigin || !/^\/my\/orders\/[1-9]\d*\/pay$/.test(target.pathname) || target.search || target.hash ||
target.origin !== shopOrigin || !returnPathPattern.test(target.pathname) || target.search || target.hash ||
!Number.isSafeInteger(payload.amount_cents) || payload.amount_cents <= 0 || !payload.jsapi_params?.package) {
throw new Error('Invalid checkout');
}
+16 -8
View File
@@ -1,6 +1,6 @@
import { existsSync } from 'node:fs';
import { randomBytes, timingSafeEqual } from 'node:crypto';
import { checkoutHtml, createCheckoutToken, readCheckoutToken } from './one-shop-checkout.mjs';
import { checkoutHtml, createCheckoutToken, readCheckoutToken, resolveReturnUrl } from './one-shop-checkout.mjs';
import {
createWechatPayClient,
loadWechatPayConfig,
@@ -123,15 +123,19 @@ export function attachPortalOneShopRoutes({
out_trade_no: outTradeNo, amount_cents: amountCents,
memind_user_id: userId, order_id: orderId,
openid: directOpenid, openid_app_id: openidAppId,
return_path: returnPath,
} = req.body || {};
if (typeof outTradeNo !== 'string' || !orderPattern.test(outTradeNo) ||
!Number.isSafeInteger(amountCents) || amountCents <= 0 || amountCents > 100_000_000 ||
(userId != null && (typeof userId !== 'string' || !userId || userId.length > 128)) ||
(directOpenid != null && (typeof directOpenid !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(directOpenid) ||
typeof openidAppId !== 'string' || openidAppId.length > 64)) ||
(orderId != null && (!Number.isSafeInteger(orderId) || orderId <= 0 || !outTradeNo.startsWith('OC')))) {
(orderId != null && (!Number.isSafeInteger(orderId) || orderId <= 0 || !outTradeNo.startsWith('OC'))) ||
(returnPath != null && (typeof returnPath !== 'string' || returnPath.length > 120))) {
return res.sendStatus(400);
}
const returnUrl = resolveReturnUrl(shopOrigin, { orderId, returnPath: returnPath || null });
if (returnPath && !returnUrl) return res.sendStatus(400);
try {
const pay = getPayClient();
if (!pay?.enabled) return res.sendStatus(503);
@@ -140,22 +144,26 @@ export function attachPortalOneShopRoutes({
if (userId) {
await userAuthReady;
openid = await getUserAuth()?.getWechatOpenidForUser(userId, pay.appId);
if (!openid) return res.sendStatus(409);
} else if (directOpenid) {
}
if (!openid && directOpenid) {
if (openidAppId !== pay.appId) return res.sendStatus(409);
openid = directOpenid;
} else if (userId && !openid) {
return res.sendStatus(409);
}
if (openid) {
const { jsapiParams } = await pay.createJsapiOrder({ ...order, openid });
if (orderId) {
if (returnUrl) {
const token = createCheckoutToken({
jsapi_params: jsapiParams, amount_cents: amountCents,
return_url: new URL(`/my/orders/${orderId}/pay`, shopOrigin).href,
jsapi_params: jsapiParams, amount_cents: amountCents, return_url: returnUrl,
}, sharedSecret);
// Use the configured public payment origin, never an untrusted Host header.
const publicOrigin = new URL(paymentPublicUrl).origin;
if (!['https:', 'http:'].includes(new URL(paymentPublicUrl).protocol)) throw new Error('Invalid payment origin');
return res.json({ checkout_url: publicOrigin + '/one-shop-pay#checkout=' + token });
return res.json({
checkout_url: publicOrigin + '/one-shop-pay#checkout=' + token,
jsapi_params: jsapiParams,
});
}
return res.json({ jsapi_params: jsapiParams });
}
+170 -28
View File
@@ -304,25 +304,34 @@ function renderNews002CompactCard({
index = 0,
imageUrl = '',
isLead = false,
dense = false,
}) {
const thumbWidth = dense ? 56 : 72;
const thumbHeight = dense ? 42 : 54;
const thumbBlock = imageUrl
? [
`<span style="${WX.compactThumb}">`,
`<img src="${imageUrl}" alt="${stripInlineText(title)}" style="${WX.compactThumbImg}" />`,
`<span style="${dense ? `display:inline-block;vertical-align:top;width:${thumbWidth}px;margin-right:8px` : WX.compactThumb}">`,
`<img src="${imageUrl}" alt="${stripInlineText(title)}" style="${dense ? `display:block;width:${thumbWidth}px;height:${thumbHeight}px;object-fit:cover;border-radius:6px` : WX.compactThumbImg}" />`,
'</span>',
].join('')
: '';
const titleStyle = isLead ? WX.compactLeadTitle : WX.listTitle;
const titleHtml = isLead
const titleStyle = dense
? `margin:0;font-size:14px;font-weight:700;color:${BRAND.ink};line-height:1.35`
: (isLead ? WX.compactLeadTitle : WX.listTitle);
const titleHtml = isLead || dense
? `<p style="${titleStyle}"><strong>${title}</strong></p>`
: `<p style="${titleStyle}"><span style="color:${BRAND.red}">${formatCardIndex(index)}</span> <strong>${title}</strong></p>`;
const bodyStyle = dense
? `margin:2px 0 0;font-size:12px;color:${BRAND.body};line-height:1.4`
: WX.listBody;
const bodyGap = dense ? 64 : 82;
return [
`<section style="${WX.compactWrap}">`,
`<section style="${dense ? 'margin:0 0 6px' : WX.compactWrap}">`,
thumbBlock,
`<span style="${thumbBlock ? WX.compactBody : 'display:block'}">`,
tag ? `<p style="${WX.compactTag}">${tag}</p>` : '',
`<span style="${thumbBlock ? `display:inline-block;vertical-align:top;width:calc(100% - ${bodyGap}px);max-width:calc(100% - ${bodyGap}px)` : 'display:block'}">`,
!dense && tag ? `<p style="${WX.compactTag}">${tag}</p>` : '',
titleHtml,
body ? `<p style="${WX.listBody}">${body}</p>` : '',
body ? `<p style="${bodyStyle}">${body}</p>` : '',
'</span>',
'</section>',
].filter(Boolean).join('');
@@ -333,6 +342,7 @@ function renderCard(cardHtml, {
index = 0,
imageUrlMap = new Map(),
news002Mode = false,
dense = false,
} = {}) {
const title = extractInnerHtml(cardHtml, /<h3[^>]*>([\s\S]*?)<\/h3>/i);
if (!title) return '';
@@ -349,9 +359,10 @@ function renderCard(cardHtml, {
].join('');
}
const body = maxBodyChars
? truncatePlainText(rawBody.replace(/<[^>]+>/g, ''), maxBodyChars)
: rawBody;
const plainBody = rawBody.replace(/<[^>]+>/g, '');
const body = dense
? truncatePlainText(plainBody.split(/[。!?!?]/u)[0].trim(), Math.min(Number(maxBodyChars) || 36, 36))
: (maxBodyChars ? truncatePlainText(plainBody, maxBodyChars) : rawBody);
const imageUrl = extractMappedCardImage(cardHtml, imageUrlMap);
if (news002Mode) {
@@ -362,6 +373,7 @@ function renderCard(cardHtml, {
index,
imageUrl,
isLead: /\blead-card\b/u.test(cardHtml),
dense,
});
}
@@ -381,14 +393,17 @@ function renderCard(cardHtml, {
});
}
function renderSectionTitle(titleHtml, sectionId = '') {
function renderSectionTitle(titleHtml, sectionId = '', { dense = false } = {}) {
const text = stripInlineText(titleHtml);
if (!text) return '';
const label = SECTION_LABELS[sectionId] ?? '';
const label = dense ? '' : (SECTION_LABELS[sectionId] ?? '');
const suffix = label
? `<span style="font-size:11px;color:${BRAND.faint};font-weight:400"> ${label}</span>`
: '';
return `<p style="${WX.section}"><span style="color:${BRAND.red}">▎</span>${text}${suffix}</p>`;
const style = dense
? `margin:12px 0 4px;padding-bottom:2px;border-bottom:1px solid ${BRAND.line};font-size:15px;font-weight:700;color:${BRAND.ink}`
: WX.section;
return `<p style="${style}"><span style="color:${BRAND.red}">▎</span>${text}${suffix}</p>`;
}
function resolveMappedImageUrl(src, imageUrlMap = new Map()) {
@@ -410,6 +425,7 @@ function extractHeroSubtitle(html) {
const source = String(html);
return stripInlineText(
source.match(/<div class="subtitle"[^>]*>([\s\S]*?)<\/div>/i)?.[1]
?? source.match(/<p class="bannerline"[^>]*>([\s\S]*?)<\/p>/i)?.[1]
?? source.match(/<div class="lede"[^>]*>([\s\S]*?)<\/div>/i)?.[1]
?? '',
);
@@ -420,6 +436,7 @@ function extractHeroDateLine(html) {
const source = String(html);
return stripInlineText(
source.match(/<div class="date-badge"[^>]*>([\s\S]*?)<\/div>/i)?.[1]
?? source.match(/<div class="dateline"[^>]*>([\s\S]*?)<\/div>/i)?.[1]
?? source.match(/<div class="meta"[^>]*>([\s\S]*?)<\/div>/i)?.[1]
?? '',
);
@@ -448,16 +465,93 @@ function renderTodayDigest(html, { maxItems = 6, maxItemChars = 30 } = {}) {
].join('');
}
function renderHero(html, _imageUrlMap = new Map(), { includeSubtitle = true } = {}) {
function isNews003Html(html) {
return /data-news-template=["']news003["']/i.test(String(html ?? ''));
}
function extractFirstLeadCard(html) {
const body = extractBodyInner(html);
const start = body.search(/<a\b[^>]*\blead-card\b/i);
if (start < 0) return '';
const slice = body.slice(start);
const end = slice.search(/<\/a>/i);
if (end < 0) return '';
return slice.slice(0, end + 4);
}
function extractWhySentence(cardHtml) {
const raw = stripInlineText(extractInnerHtml(cardHtml, /<div class="why"[^>]*>([\s\S]*?)<\/div>/i));
return raw.replace(/^为什么重要\s*[::]\s*/u, '').trim();
}
function sliceShareTitle(value, maxChars = 22) {
const text = String(value ?? '').replace(/\s+/g, ' ').trim();
return [...text].slice(0, maxChars).join('');
}
/**
* news003 的分享卡不用「每日新闻早报」当标题。
* 第一条头条的 `.why` 是标题,h3 做摘要。
*/
export function buildNews003ShareMeta(html) {
if (!isNews003Html(html)) return null;
const card = extractFirstLeadCard(html);
if (!card) return null;
const sentence = extractWhySentence(card);
const headline = stripInlineText(extractInnerHtml(card, /<h3[^>]*>([\s\S]*?)<\/h3>/i));
const shareSentence = sentence || headline;
if (!shareSentence) return null;
return {
title: sliceShareTitle(shareSentence, 22),
digest: (headline || shareSentence).slice(0, 120),
sentence: shareSentence,
headline,
};
}
function renderNews003ShareLead(cardHtml, imageUrlMap = new Map()) {
const sentence = extractWhySentence(cardHtml)
|| stripInlineText(extractInnerHtml(cardHtml, /<h3[^>]*>([\s\S]*?)<\/h3>/i));
if (!sentence) return '';
const headline = stripInlineText(extractInnerHtml(cardHtml, /<h3[^>]*>([\s\S]*?)<\/h3>/i));
const rawBody = extractInnerHtml(cardHtml, /<p[^>]*>([\s\S]*?)<\/p>/i).replace(/<[^>]+>/g, '');
const body = truncatePlainText(rawBody.split(/[。!?!?]/u)[0].trim(), 36);
const imageUrl = extractMappedCardImage(cardHtml, imageUrlMap);
const showHeadline = headline && headline !== sentence;
return [
'<section style="margin:0 0 12px">',
imageUrl
? `<img src="${imageUrl}" alt="" style="display:block;width:100%;height:188px;object-fit:cover;border-radius:8px" />`
: '',
`<p style="margin:10px 0 0;font-size:22px;font-weight:700;line-height:1.35;color:${BRAND.ink}"><strong>${sentence}</strong></p>`,
showHeadline ? `<p style="margin:8px 0 0;font-size:14px;color:${BRAND.body}">${headline}</p>` : '',
body ? `<p style="margin:4px 0 0;font-size:12px;line-height:1.4;color:${BRAND.body}">${body}</p>` : '',
'</section>',
].filter(Boolean).join('');
}
function renderHero(html, _imageUrlMap = new Map(), { includeSubtitle = true, dense = false } = {}) {
const title = stripInlineText(String(html).match(/<h1[^>]*>([\s\S]*?)<\/h1>/i)?.[1] ?? '')
|| '每日新闻早报';
const dateBadge = extractHeroDateLine(html);
const subtitle = includeSubtitle ? truncatePlainText(extractHeroSubtitle(html), 150) : '';
const subtitle = includeSubtitle ? truncatePlainText(extractHeroSubtitle(html), dense ? 42 : 150) : '';
const hero = dense
? `background:linear-gradient(135deg,${BRAND.red},${BRAND.navy});border-radius:8px;padding:10px 12px;text-align:center;color:#fff`
: WX.hero;
const heroTitle = dense
? 'margin:0;font-size:18px;font-weight:700;line-height:1.3'
: WX.heroTitle;
const heroMeta = dense
? `margin:4px 0 0;font-size:11px;color:${BRAND.onDark}`
: WX.heroMeta;
const heroSub = dense
? `margin:6px 0 0;font-size:12px;line-height:1.4;color:${BRAND.onDark}`
: WX.heroSub;
return [
`<section style="${WX.hero}">`,
`<p style="${WX.heroTitle}"><strong>${title.replace(/^[📰\s]+/u, '')}</strong></p>`,
dateBadge ? `<p style="${WX.heroMeta}">${dateBadge}</p>` : '',
subtitle ? `<p style="${WX.heroSub}">${subtitle}</p>` : '',
`<section style="${hero}">`,
`<p style="${heroTitle}"><strong>${title.replace(/^[📰\s]+/u, '')}</strong></p>`,
dateBadge ? `<p style="${heroMeta}">${dateBadge}</p>` : '',
subtitle ? `<p style="${heroSub}">${subtitle}</p>` : '',
'</section>',
].filter(Boolean).join('');
}
@@ -726,6 +820,8 @@ function renderGenericSection(
maxBodyChars = null,
imageUrlMap = new Map(),
news002Mode = false,
dense = false,
skipFirstLead = false,
} = {},
) {
const title = extractInnerHtml(sectionHtml, /<div class="section-title"[^>]*>([\s\S]*?)<\/div>/i);
@@ -738,9 +834,10 @@ function renderGenericSection(
const tokens = body
.split(/(?=<figure class="section-figure"|<div class="(?:card|highlight-box)|<a class="lead-card)/i)
.filter(Boolean);
const parts = [renderSectionTitle(title, sectionId)];
const parts = [renderSectionTitle(title, sectionId, { dense })];
let cardCount = 0;
let listIndex = 0;
let skippedLead = false;
for (const token of tokens) {
if (/^<figure class="section-figure"/i.test(token)) {
const rendered = renderSectionFigure(token, imageUrlMap);
@@ -749,6 +846,10 @@ function renderGenericSection(
}
const isLeadCard = /^<a class="lead-card/i.test(token);
if (!isLeadCard && !/^<div class="(?:card|highlight-box)/i.test(token)) continue;
if (skipFirstLead && isLeadCard && !skippedLead) {
skippedLead = true;
continue;
}
if (maxCards != null && cardCount >= maxCards) continue;
const cardChunk = token.replace(/^(?:<div class="(?:card|highlight-box)|<a class="lead-card)(?:\s|")/i, '');
const cardHtml = `<div class="card ${isLeadCard ? 'lead-card ' : ''}${cardChunk}`;
@@ -758,6 +859,7 @@ function renderGenericSection(
index: listIndex,
imageUrlMap,
news002Mode,
dense,
});
if (rendered) {
parts.push(rendered);
@@ -791,6 +893,13 @@ const DEFAULT_SECTION_CARD_LIMITS = {
official_feeds: 3,
finance: 5,
tech: 5,
front: 2,
china: 8,
abroad: 8,
markets: 8,
'desk-tech': 6,
society: 6,
arts: 4,
sports: 3,
technews: 2,
knowledge: 3,
@@ -967,7 +1076,7 @@ function renderFollowMpSection(qrcodeImageUrl = '') {
* 内容卡统一以 `margin:0 0 12px` 开头(见 WX.listWrap / WX.feature / WX.rankWrap),
* 便于按整卡统计与裁剪。调整 margin 时必须同步这里。
*/
const INLINE_CARD_SECTION_RE = /<section style="margin:0 0 12px[^"]*">[\s\S]*?<strong>[\s\S]*?<\/section>/g;
const INLINE_CARD_SECTION_RE = /<section style="margin:0 0 (?:12|6)px[^"]*">[\s\S]*?<strong>[\s\S]*?<\/section>/g;
const INLINE_SECTION_TITLE_PREFIX = '<p style="margin:20px 0 10px;padding-bottom:6px;border-bottom:1px solid';
function countInlineCards(body) {
@@ -1009,6 +1118,20 @@ export function trimWechatInlineBodyByRemovingCards(body, maxLen, {
return result;
}
function renderNews003Scan(html) {
const block = String(html ?? '').match(/<ol class="scan"[^>]*>([\s\S]*?)<\/ol>/i)?.[1] ?? '';
if (!block) return '';
const items = [...block.matchAll(/<li[^>]*>([\s\S]*?)<\/li>/gi)]
.map((match) => stripInlineText(match[1]))
.filter(Boolean)
.slice(0, 8);
if (items.length === 0) return '';
const lines = items.map((item) =>
`<span style="display:block;padding:7px 0;border-bottom:1px solid #eee;font-size:15px;font-weight:650;line-height:1.45;color:#161616">${item}</span>`,
).join('');
return `<section style="margin:14px 0 18px"><p style="margin:0 0 4px;font-size:12px;letter-spacing:.12em;color:#888">先看这 8 条</p>${lines}</section>`;
}
function buildWechatInlineContent(html, {
publicUrl = '',
qrcodeImageUrl = '',
@@ -1018,11 +1141,26 @@ function buildWechatInlineContent(html, {
imageUrlMap = new Map(),
} = {}) {
const sections = splitSections(html);
const news003Mode = isNews003Html(html);
const news002Mode = isNews002Html(html);
const digest = renderTodayDigest(html);
const isNews002 = /class="[^"]*\bmasthead\b/i.test(String(html ?? ''));
const bodyParts = [renderHero(html, imageUrlMap, { includeSubtitle: !digest })];
const shareLead = news003Mode ? extractFirstLeadCard(html) : '';
const digest = news003Mode ? '' : renderTodayDigest(html);
const bodyParts = [];
if (shareLead) {
bodyParts.push(renderHero(html, imageUrlMap, {
includeSubtitle: false,
dense: false,
}));
bodyParts.push(renderNews003ShareLead(shareLead, imageUrlMap));
} else {
bodyParts.push(renderHero(html, imageUrlMap, {
includeSubtitle: news003Mode || !digest,
dense: news003Mode,
}));
}
if (digest) bodyParts.push(digest);
const scan = news003Mode ? '' : renderNews003Scan(html);
if (scan) bodyParts.push(scan);
const contentParts = [];
let renderedSectionCount = 0;
@@ -1065,9 +1203,11 @@ function buildWechatInlineContent(html, {
const rendered = renderGenericSection(section.html, {
sectionId: section.id,
maxCards: resolveSectionCardLimit(section, trimProfile.sectionCardLimits),
maxBodyChars: trimProfile.maxBodyChars,
maxBodyChars: news003Mode ? 36 : trimProfile.maxBodyChars,
imageUrlMap,
news002Mode,
dense: news003Mode,
skipFirstLead: Boolean(shareLead),
});
if (rendered) {
contentParts.push(rendered);
@@ -1201,8 +1341,9 @@ export function convertDailyNewsHtmlToWechatInlineArticle(html, {
includeFixedLayout = true,
fixedLayoutLength = null,
} = {}) {
const title = (extractPageTitle(html) || '每日新闻早报').slice(0, 32);
const digest = (extractMetaDescription(html) || title).slice(0, 120);
const share = buildNews003ShareMeta(html);
const title = share?.title || (extractPageTitle(html) || '每日新闻早报').slice(0, 32);
const digest = share?.digest || (extractMetaDescription(html) || title).slice(0, 120);
const fixedLayoutLengthResolved = Number.isFinite(fixedLayoutLength)
? fixedLayoutLength
@@ -1268,6 +1409,7 @@ export const wechatDailyNewsInlineInternals = {
isNews002Html,
renderCard,
renderNews002CompactCard,
buildNews003ShareMeta,
renderHero,
renderTodayDigest,
renderBriefStats,
+73
View File
@@ -299,3 +299,76 @@ test('section parsing supports attribute order, extra classes and single quotes
assert.match(rendered.content, /国内新闻标题/u);
assert.match(rendered.content, /国际新闻正文/u);
});
test('news003 wechat body tightens news002 cards without changing the page shape', () => {
const sourceImage = 'https://news.example/story.jpg';
const wechatImage = 'https://mmbiz.qpic.cn/wechat-story.jpg';
const longBody = '第一句说明发生了什么。第二句是背景,公众号里不应该占两行。';
const html = `<html data-news-template="news003"><body>
<div class="masthead"><h1>每日新闻早报</h1><div class="meta"><b>2026年11月21日</b></div></div>
<div class="lede">样张导语,只在报头下留一行。</div>
<div class="section" id="domestic"><div class="section-title"><h2>国内</h2></div>
<div class="card" data-event-key="k1"><div class="media"><img src="${sourceImage}" alt="图"></div>
<div class="body"><span class="tag">时政</span><h3>国内标题</h3><p>${longBody}</p></div></div>
</div>
</body></html>`;
const imageUrlMap = new Map([[sourceImage, wechatImage]]);
const dense = convertDailyNewsHtmlToWechatInlineArticle(html, { includeFixedLayout: false, imageUrlMap });
const regular = convertDailyNewsHtmlToWechatInlineArticle(
html.replace('news003', 'news002'),
{ includeFixedLayout: false, imageUrlMap },
);
assert.match(dense.content, /width:56px;height:42px/u);
assert.match(dense.content, /margin:0 0 6px/u);
assert.match(dense.content, /第一句说明发生了什么/u);
assert.doesNotMatch(dense.content, /第二句是背景/u);
assert.doesNotMatch(dense.content, /今日导读/u);
assert.match(regular.content, /width:72px;height:54px/u);
assert.match(regular.content, /第二句是背景/u);
assert.ok(dense.content.length < regular.content.length);
});
test('news003 share card uses the first lead sentence and leaves the rest dense', () => {
const leadImage = 'https://news.example/lead.jpg';
const listImage = 'https://news.example/list.jpg';
const wechatLead = 'https://mmbiz.qpic.cn/lead.jpg';
const wechatList = 'https://mmbiz.qpic.cn/list.jpg';
const sentence = '明天加油,每升多花近两毛';
const html = `<html data-news-template="news003"><head>
<title>每日新闻早报 · 2026年11月21日</title>
<meta name="description" content="今日要闻">
</head><body>
<div class="masthead"><h1>每日新闻早报</h1><div class="meta"><b>2026年11月21日</b> · 星期六</div></div>
<div class="section" id="headlines"><div class="section-title"><h2>今日头条</h2></div>
<a class="lead-card" data-event-key="lead">
<div class="media"><img src="${leadImage}" alt="油价"></div>
<div class="body"><span class="tag">能源</span><h3>国际油价一夜上涨</h3>
<p>布伦特原油隔夜上涨。交易员在等下周的库存数据。</p>
<div class="why"><b>为什么重要</b>:${sentence}</div></div></a>
<div class="card" data-event-key="next"><div class="media"><img src="${listImage}" alt="列表"></div>
<div class="body"><h3>央行维持政策利率</h3><p>第一句说明资金面。第二句不进公众号。</p></div></div>
</div>
</body></html>`;
const imageUrlMap = new Map([[leadImage, wechatLead], [listImage, wechatList]]);
const article = convertDailyNewsHtmlToWechatInlineArticle(html, { includeFixedLayout: false, imageUrlMap });
assert.equal(article.title, sentence);
assert.equal(article.digest, '国际油价一夜上涨');
assert.match(article.content, new RegExp(`<strong>${sentence}</strong>`));
assert.doesNotMatch(article.content, /转给/u);
assert.match(article.content, new RegExp(`src="${wechatLead}"[^>]*height:188px`));
assert.match(article.content, /width:56px;height:42px/u);
assert.match(article.content, /第一句说明资金面/u);
assert.doesNotMatch(article.content, /第二句不进公众号/u);
assert.match(article.content, /linear-gradient\(135deg,#c8102e,#0d2b5c\)/u);
assert.match(article.content, /每日新闻早报/u);
assert.doesNotMatch(article.content, /margin:0 0 8px;font-size:12px;color:#999/u);
assert.equal((article.content.match(/国际油价一夜上涨/g) ?? []).length, 1);
const regular = convertDailyNewsHtmlToWechatInlineArticle(
html.replace('news003', 'news002'),
{ includeFixedLayout: false, imageUrlMap },
);
assert.match(regular.title, /每日新闻早报/u);
assert.equal(regular.digest, '今日要闻');
assert.doesNotMatch(regular.content, /height:188px/u);
});
-6
View File
@@ -3909,12 +3909,6 @@ export function createWechatMpService({
fromUserName: inbound.toUserName,
content: buildSubscribeWelcomeText({
bindUrl: buildBindUrl(),
introUrl: config.subscribeIntroUrl,
plazaHomeUrl: config.subscribePlazaHomeUrl,
pushSubscriptionEnabled: config.pushSubscriptionEnabled !== false,
morningReminderEnabled: config.subscribeMorningReminderEnabled !== false,
morningReminderHour: config.subscribeMorningHour,
morningReminderMinute: config.subscribeMorningMinute,
}),
}),
};
+9
View File
@@ -11,6 +11,7 @@ import {
import { extractMindspaceCoverPath } from './wechat/verify/generated-thumbnail.mjs';
import { extractPageTitle } from './wechat/verify/share-preview-repair.mjs';
import {
buildNews003ShareMeta,
convertDailyNewsHtmlToWechatInlineArticle,
renderCreatePortalCTA,
trimWechatInlineBodyByRemovingCards,
@@ -134,6 +135,12 @@ export function isNewsMorningContentDegraded(html, { minStoryCards = 12 } = {})
if (/class="[^"]*\bmasthead\b/i.test(source)) {
return !auditNews002SectionFill(source).ok;
}
if (
/data-news-template=["']news003["']/i.test(source)
|| /class="[^"]*\bnameplate\b/i.test(source)
) {
return countNewsMorningStoryCards(source) < 16;
}
// 必须按 class token 统计:news002 的头条卡是 a.lead-card,
// 旧写法 `class="card(?:\s|")` 匹配不到,会把正常页误判成降级页。
return countNewsMorningStoryCards(source) < minStoryCards;
@@ -729,6 +736,8 @@ export function applyDailyNewsWechatDraftFooter(
}
export function extractDailyNewsArticleMeta(html) {
const share = buildNews003ShareMeta(html);
if (share) return { title: share.title.slice(0, 64), digest: share.digest.slice(0, 120) };
const title = extractPageTitle(html) || '每日新闻早报';
const digest = (extractMetaDescription(html) || title).slice(0, 120);
return { title: title.slice(0, 64), digest };
+27
View File
@@ -121,6 +121,24 @@ test('buildDailyNewsWechatDraftArticle keeps news002 imageless cards as text-onl
assert.match(article.content, /mmbiz\.qpic\.cn\/a\.jpg/u);
});
test('buildDailyNewsWechatDraftArticle uses the news003 forward sentence as the share card', () => {
const html = `<!DOCTYPE html><html data-news-template="news003"><head>
<title>每日新闻早报 · 2026年11月21日</title>
<meta name="description" content="今日要闻">
</head><body>
<div class="masthead"><h1>每日新闻早报</h1><div class="meta"><b>2026年11月21日</b></div></div>
<div class="section" id="headlines"><div class="section-title"><h2>今日头条</h2></div>
<a class="lead-card" data-event-key="lead"><div class="body"><h3>国际油价一夜上涨</h3><p>布伦特原油隔夜上涨。</p><div class="why">明天加油,每升多花近两毛</div></div></a>
<div class="card" data-event-key="next"><div class="body"><h3>央行维持政策利率</h3><p>资金面保持平稳。</p></div></div>
</div>
</body></html>`;
const article = buildDailyNewsWechatDraftArticle({ html, publicUrl: 'https://m.tkmind.cn/demo' });
assert.equal(article.title, '明天加油,每升多花近两毛');
assert.equal(article.digest, '国际油价一夜上涨');
assert.doesNotMatch(article.content, /转给/u);
assert.match(article.content, /央行维持政策利率/u);
});
test('convertNewsPageHtmlToWechatArticle converts daily-news to inline html with footer', () => {
const article = convertNewsPageHtmlToWechatArticle(SAMPLE_HTML, {
publicUrl: 'https://m.tkmind.cn/MindSpace/demo/public/daily-news-0910.html',
@@ -366,6 +384,15 @@ test('isNewsMorningContentDegraded counts news002 lead cards', async () => {
assert.equal(isNewsMorningContentDegraded(html, { minStoryCards: 9 }), true);
});
test('isNewsMorningContentDegraded uses story count for news003, not news002 fill', async () => {
const { isNewsMorningContentDegraded } = await import('./wechat-news-morning-draft.mjs');
const cards = (count) => Array.from({ length: count }, (_, i) =>
`<div class="card" data-event-key="n${i}"><h3>短讯${i}</h3><p>一句。</p></div>`).join('');
const page = (count) => `<html data-news-template="news003"><body><header class="nameplate"><h1>每日新闻早报</h1></header>${cards(count)}</body></html>`;
assert.equal(isNewsMorningContentDegraded(page(16)), false);
assert.equal(isNewsMorningContentDegraded(page(15)), true);
});
test('news002 push refuses a draft that loses every source news card', () => {
const html = '<html><body><div class="masthead"><h1>每日新闻早报</h1></div><main class="section" id="domestic"><div class="section-title">国内</div><div class="card"><h3>不能丢失的新闻</h3><p>真实新闻正文</p><a href="https://example.com/story">来源</a></div></main></body></html>';
+48 -29
View File
@@ -1,6 +1,4 @@
import { resolveWechatAddressName } from '../user/display-name.mjs';
import { buildPushSubscriptionMenuLines } from '../push-subscription-catalog.mjs';
import { buildSubscribeMorningReminderPromptLines } from '../subscribe-morning-reminder.mjs';
export const DEFAULT_SUBSCRIBE_INTRO_URL =
'https://m.tkmind.cn/MindSpace/a70ff537-8908-486e-9b6c-042e07cc25db/public/tkmind-deep-intro.html';
@@ -11,6 +9,33 @@ export const DEFAULT_PRODUCTION_BIND_URL =
export const DEFAULT_PLAZA_HOME_URL = 'https://plaza.tkmind.cn/plaza';
const SUBSCRIBE_EXAMPLE_ORIGIN =
'https://m.tkmind.cn/MindSpace/a70ff537-8908-486e-9b6c-042e07cc25db/public';
/** 关注欢迎语里的可点开案例。提示句都必须包含「生成页面」。 */
export const DEFAULT_SUBSCRIBE_WELCOME_EXAMPLES = Object.freeze([
{
prompt: '生成页面:某产品调研分析报告,含用户痛点、竞品对比和结论',
label: '产品调研 · 竞品地图',
url: `${SUBSCRIBE_EXAMPLE_ORIGIN}/chenkeming-map.html`,
},
{
prompt: '生成页面:季度数据分析报告,用图表讲清变化',
label: '分析报告 · 数据仪表盘',
url: `${SUBSCRIBE_EXAMPLE_ORIGIN}/zhixing-data-dashboard.html`,
},
{
prompt: '生成页面:苏州一日游攻略,含路线和美食',
label: '旅行攻略 · 新疆亲子游',
url: `${SUBSCRIBE_EXAMPLE_ORIGIN}/xinjiang-travel.html`,
},
{
prompt: '生成页面:周末市集活动页,含时间、地点和报名',
label: '活动页面 · 餐厅招牌',
url: `${SUBSCRIBE_EXAMPLE_ORIGIN}/changsha-restaurant-promo.html`,
},
]);
/** 关注欢迎语里推荐的 M发现精选入口(示例页/广场作品,便于长期维护)。 */
export const DEFAULT_SUBSCRIBE_PLAZA_PICKS = Object.freeze([
{
@@ -59,43 +84,37 @@ export function buildPlazaDiscoveryLines({
export function buildSubscribeWelcomeText({
bindUrl,
introUrl = DEFAULT_SUBSCRIBE_INTRO_URL,
plazaHomeUrl = DEFAULT_PLAZA_HOME_URL,
plazaPicks = DEFAULT_SUBSCRIBE_PLAZA_PICKS,
pushSubscriptionEnabled = true,
morningReminderEnabled = true,
morningReminderHour = 8,
morningReminderMinute = 0,
examples = DEFAULT_SUBSCRIBE_WELCOME_EXAMPLES,
} = {}) {
const normalizedBindUrl = String(bindUrl ?? '').trim();
const normalizedIntroUrl = String(introUrl ?? '').trim();
const lines = [
'欢迎关注 TKMind 智趣 👋',
'',
'在微信里直接发消息即可:',
'· 问答、写作、翻译',
'· 生成精美网页并给链接',
'· 发图解读报告/截图',
'· 设置定时提醒与每日推送',
...buildPlazaDiscoveryLines({ plazaHomeUrl, plazaPicks }),
'你想做的页面,直接说给我。',
'带上「生成页面」,我做好后回你链接,马上就能分享。',
'',
'例如:',
];
if (pushSubscriptionEnabled) {
lines.push(...buildPushSubscriptionMenuLines());
} else if (morningReminderEnabled) {
lines.push(
...buildSubscribeMorningReminderPromptLines({
hour: morningReminderHour,
minute: morningReminderMinute,
}),
);
const picks = Array.isArray(examples) ? examples : DEFAULT_SUBSCRIBE_WELCOME_EXAMPLES;
const visible = [];
for (const example of picks) {
const prompt = String(example?.prompt ?? '').trim();
const url = String(example?.url ?? '').trim();
const label = String(example?.label ?? '').trim();
if (!prompt.includes('生成页面')) continue;
lines.push(`· 「${prompt}」`);
if (url && label) visible.push({ url, label });
}
if (normalizedIntroUrl) {
lines.push('', '📖 了解 TKMind 能做什么:', buildWechatTextLink(normalizedIntroUrl, '看功能介绍'));
if (visible.length) {
lines.push('', '点开看看做好的页面:');
for (const pick of visible) {
lines.push(`· ${buildWechatTextLink(pick.url, pick.label)}`);
}
}
lines.push('', '链接转给朋友,对方点开就能看。');
if (normalizedBindUrl) {
lines.push('', '👉 先完成绑定再开始对话:', buildWechatTextLink(normalizedBindUrl, '点我绑定'));
lines.push('', `👉 先${buildWechatTextLink(normalizedBindUrl, '点我绑定')},再发一句「生成页面:…」`);
}
lines.push('', '绑定后回复「你好」,或试试:', '「帮我做一个苏州游玩攻略页面」');
return lines.join('\n');
}
+18 -69
View File
@@ -5,10 +5,9 @@ import {
buildPlazaDiscoveryLines,
buildSubscribeWelcomeText,
buildWechatTextLink,
DEFAULT_PLAZA_HOME_URL,
DEFAULT_PRODUCTION_BIND_URL,
DEFAULT_SUBSCRIBE_INTRO_URL,
DEFAULT_SUBSCRIBE_PLAZA_PICKS,
DEFAULT_SUBSCRIBE_WELCOME_EXAMPLES,
} from './sync-replies.mjs';
test('buildWechatTextLink renders WeChat anchor without exposing raw url', () => {
@@ -18,35 +17,27 @@ test('buildWechatTextLink renders WeChat anchor without exposing raw url', () =>
);
});
test('buildSubscribeWelcomeText uses clickable anchors instead of raw urls', () => {
test('buildSubscribeWelcomeText asks for a page and a shareable link', () => {
const text = buildSubscribeWelcomeText({ bindUrl: DEFAULT_PRODUCTION_BIND_URL });
assert.match(text, /欢迎关注 TKMind 智趣/);
assert.match(text, /生成精美网页并给链接/);
assert.match(text, /🎯 M发现 · 精选作品广场/);
assert.match(text, /旅行攻略/);
assert.match(text, /深夜食堂/);
assert.match(
text,
new RegExp(`<a href="${DEFAULT_PLAZA_HOME_URL.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}">进入 M发现,逛热门作品</a>`),
);
assert.match(text, /📖 了解 TKMind 能做什么:/);
assert.match(
text,
/<a href="[^"]*tkmind-deep-intro\.html">看功能介绍<\/a>/,
);
assert.match(text, /👉 先完成绑定再开始对话:/);
assert.match(text, /你想做的页面/);
assert.match(text, /马上就能分享/);
assert.match(text, /对方点开就能看/);
assert.match(text, /点开看看做好的页面/);
for (const example of DEFAULT_SUBSCRIBE_WELCOME_EXAMPLES) {
assert.ok(example.prompt.includes('生成页面'));
assert.ok(text.includes(`「${example.prompt}」`));
assert.ok(text.includes(`<a href="${example.url}">${example.label}</a>`));
}
assert.match(
text,
/<a href="[^"]*auth\/wechat\/authorize\?intent=login">点我绑定<\/a>/,
);
assert.doesNotMatch(text, /\nhttps:\/\/m\.tkmind\.cn/);
assert.doesNotMatch(text, /\nhttps:\/\/plaza\.tkmind\.cn/);
assert.match(text, /帮我做一个苏州游玩攻略页面/);
assert.match(text, /📬 每日推送订阅/);
assert.match(text, /1 ☀️ 早安问候/);
assert.match(text, /2 📰 每日新闻早报/);
assert.match(text, /我的订阅/);
assert.doesNotMatch(text, /每日推送订阅/);
assert.doesNotMatch(text, /M发现/);
assert.doesNotMatch(text, /问答、写作、翻译/);
});
test('buildPlazaDiscoveryLines renders curated plaza category links', () => {
@@ -59,51 +50,9 @@ test('buildPlazaDiscoveryLines renders curated plaza category links', () => {
}
});
test('buildSubscribeWelcomeText omits intro section when introUrl is empty', () => {
const text = buildSubscribeWelcomeText({
bindUrl: 'https://m.tkmind.cn/bind',
introUrl: '',
});
test('buildSubscribeWelcomeText omits the bind line when bindUrl is empty', () => {
const text = buildSubscribeWelcomeText({ bindUrl: '' });
assert.doesNotMatch(text, /📖 了解 TKMind 能做什么:/);
assert.doesNotMatch(text, /tkmind-deep-intro\.html/);
});
test('buildSubscribeWelcomeText omits plaza section when plazaHomeUrl is empty', () => {
const text = buildSubscribeWelcomeText({
bindUrl: 'https://m.tkmind.cn/bind',
introUrl: '',
plazaHomeUrl: '',
plazaPicks: [],
});
assert.doesNotMatch(text, /M发现/);
});
test('buildSubscribeWelcomeText omits push subscription menu when disabled', () => {
const text = buildSubscribeWelcomeText({
bindUrl: 'https://m.tkmind.cn/bind',
introUrl: '',
plazaHomeUrl: '',
plazaPicks: [],
pushSubscriptionEnabled: false,
morningReminderEnabled: false,
});
assert.doesNotMatch(text, /每日推送订阅/);
assert.doesNotMatch(text, /回复 1 确认/);
});
test('buildSubscribeWelcomeText falls back to legacy morning prompt when push subscription disabled', () => {
const text = buildSubscribeWelcomeText({
bindUrl: 'https://m.tkmind.cn/bind',
introUrl: '',
plazaHomeUrl: '',
plazaPicks: [],
pushSubscriptionEnabled: false,
morningReminderEnabled: true,
});
assert.match(text, /☀️ 每日早安提醒/);
assert.match(text, /回复 1 确认/);
assert.match(text, /生成页面/);
assert.doesNotMatch(text, /点我绑定/);
});