nomadro/apps/miniprogram/scripts/export-xhs-offline.mjs
eric 1d3e513ae2 Ship Douyin tt/ miniprogram: offline reader, clipboard privacy, README.
Add apps/miniprogram/tt as a standalone Douyin app with official usePrivacyCheck + tt.showModal/setClipboardData flow, single-chapter offline reader, and document console privacy setup for clipboard.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 15:17:52 +08:00

378 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 从微信/Taro 同源数据导出小红书离线种子(纯前端,零网络)。
* SoT: src/data/links.json + public/icons + nomadCodeBook + localCatalog + remoteConfig.defaults
*/
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const mini = path.resolve(__dirname, '..')
const xhsTool = path.join(mini, 'xhs', 'tool')
const iconsSrc = path.join(mini, 'src', 'public', 'icons')
const iconsOut = path.join(xhsTool, 'icons')
function extractJsObject(src, exportName) {
const needle = `export const ${exportName}`
const pos = src.indexOf(needle)
if (pos < 0) throw new Error(`cannot find ${exportName}`)
const eq = src.indexOf('=', pos + needle.length)
if (eq < 0) throw new Error(`no = for ${exportName}`)
let start = eq + 1
while (start < src.length && /\s/.test(src[start])) start++
const open = src[start]
if (open !== '{' && open !== '[') throw new Error(`bad start for ${exportName}: ${open}`)
const close = open === '{' ? '}' : ']'
let depth = 0
for (let i = start; i < src.length; i++) {
const ch = src[i]
if (ch === '"' || ch === "'" || ch === '`') {
// skip strings
const q = ch
i++
while (i < src.length) {
if (src[i] === '\\') {
i += 2
continue
}
if (src[i] === q) break
i++
}
continue
}
if (ch === open) depth++
else if (ch === close) {
depth--
if (depth === 0) {
const lit = src.slice(start, i + 1)
return new Function(`return (${lit})`)()
}
}
}
throw new Error(`unbalanced ${exportName}`)
}
function extractReturnPayload(src, fnName) {
const start = src.indexOf(`export function ${fnName}`)
if (start < 0) throw new Error(`missing ${fnName}`)
const ret = src.indexOf('return', start)
const brace = src.indexOf('{', ret)
let depth = 0
for (let i = brace; i < src.length; i++) {
const ch = src[i]
if (ch === '{') depth++
else if (ch === '}') {
depth--
if (depth === 0) {
const lit = src.slice(brace, i + 1)
return new Function(`return (${lit})`)()
}
}
}
throw new Error(`unbalanced JSON in ${fnName}`)
}
const links = JSON.parse(
fs.readFileSync(path.join(mini, 'src', 'data', 'links.json'), 'utf8'),
)
function readBookSources() {
const candidates = [
path.join(mini, 'tt', 'src', 'data'),
path.join(mini, 'src', 'data'),
]
for (const dir of candidates) {
const bookPath = path.join(dir, 'nomadCodeBook.ts')
const coverPath = path.join(dir, 'coverBook.ts')
if (!fs.existsSync(bookPath) || !fs.existsSync(coverPath)) continue
const payload = extractReturnPayload(fs.readFileSync(bookPath, 'utf8'), 'nomadCodeReadPayload')
const chapters = payload.chapters || []
if (chapters.length >= 10) {
return {
source: bookPath,
coverBook: extractJsObject(fs.readFileSync(coverPath, 'utf8'), 'COVER_BOOK'),
readPayload: payload,
}
}
}
const bookPath = path.join(mini, 'src', 'data', 'nomadCodeBook.ts')
const coverPath = path.join(mini, 'src', 'data', 'coverBook.ts')
return {
source: bookPath,
coverBook: extractJsObject(fs.readFileSync(coverPath, 'utf8'), 'COVER_BOOK'),
readPayload: extractReturnPayload(fs.readFileSync(bookPath, 'utf8'), 'nomadCodeReadPayload'),
}
}
const { source: bookSource, coverBook, readPayload } = readBookSources()
const meetups = extractJsObject(
fs.readFileSync(path.join(mini, 'src', 'data', 'localCatalog.ts'), 'utf8'),
'LOCAL_MEETUPS',
)
const remoteCfg = extractJsObject(
fs.readFileSync(path.join(mini, 'src', 'data', 'remoteConfig.defaults.ts'), 'utf8'),
'DEFAULT_REMOTE_CONFIG',
)
// —— icons:与微信包同源 src/public/icons ——
fs.mkdirSync(iconsOut, { recursive: true })
for (const f of fs.readdirSync(iconsOut)) {
fs.unlinkSync(path.join(iconsOut, f))
}
const needed = new Set(['_brand', 'nomadro'])
// 隐藏分类保留在 links.json,导出门户时不展示(hidden: true)
links.categories = (links.categories || []).filter((c) => !c.hidden)
for (const cat of links.categories) {
for (const g of cat.groups || []) {
for (const link of g.links || []) {
const lid = String(link.id || '').trim()
if (!lid) continue
needed.add(lid)
link.icon = `./icons/${lid}.webp`
}
}
}
const brandSrc = fs.existsSync(path.join(iconsSrc, '_brand.webp'))
? path.join(iconsSrc, '_brand.webp')
: path.join(iconsSrc, 'nomadro.webp')
const missing = []
for (const lid of needed) {
const src = path.join(iconsSrc, `${lid}.webp`)
const dst = path.join(iconsOut, `${lid}.webp`)
if (fs.existsSync(src)) fs.copyFileSync(src, dst)
else if (fs.existsSync(brandSrc)) {
fs.copyFileSync(brandSrc, dst)
missing.push(lid)
} else missing.push(lid)
}
links.brandIcon = fs.existsSync(path.join(iconsOut, 'nomadro.webp'))
? './icons/nomadro.webp'
: './icons/_brand.webp'
const cfg = {
homeBrand: remoteCfg.copy?.homeBrand || 'nomadro',
homeTagline: remoteCfg.copy?.homeTagline || '随处工作 · 自由生活',
homeLead: remoteCfg.copy?.homeLead || '导航 · 小册 · 社群 · VIP · 离线可用',
vipCta: remoteCfg.copy?.vipCta || '立即加入',
vipPriceFen: remoteCfg.copy?.vipPriceFen || 8800,
modules: {
nav: {
enabled: remoteCfg.modules?.nav?.enabled !== false,
title: remoteCfg.modules?.nav?.title || '出海导航',
emoji: '🧭',
desc: '工具与出海资源',
},
book: {
enabled: remoteCfg.modules?.book?.enabled !== false,
title: remoteCfg.modules?.book?.title || '数字游民小册',
emoji: '📖',
desc: '离线阅读',
},
community: {
enabled: remoteCfg.modules?.community?.enabled !== false,
title: remoteCfg.modules?.community?.title || '旅居社群',
emoji: '🌏',
desc: '活动与目的地',
},
vip: {
enabled: remoteCfg.modules?.vip?.enabled !== false,
title: remoteCfg.modules?.vip?.title || 'VIP 会员',
emoji: '👑',
desc: '电子书·视频·社群全解锁',
},
},
}
const bookMeta = readPayload.book || {}
/** 微信/抖音分包图路径 → 小红书离线 ./images/ */
function xhsBookImagePath(body) {
return String(body || '')
.replace(/\/packageBook\/assets\/book-images\//g, './images/')
.replace(/\/assets\/book-images\//g, './images/')
}
const bookChapters = (readPayload.chapters || []).map((ch) => {
const body = xhsBookImagePath(ch.content || ch.body || '')
return {
id: ch.id,
title: ch.title,
order: ch.order,
emoji: ch.emoji || '',
body,
content: body,
}
})
const portalBook = {
title: coverBook.title || bookMeta.title || '数字游民',
subtitle: coverBook.subtitle || bookMeta.subtitle || '',
author: coverBook.author || bookMeta.author || '',
description: coverBook.description || bookMeta.description || '',
tagline: coverBook.tagline || '',
tags: coverBook.viralTags || bookMeta.tags || [],
chapters: bookChapters.map((c) => ({
id: c.id,
title: c.title,
body: c.body,
})),
}
const community = {
titleLine1: '在任意城市',
titleLine2: '过你想要的生活',
typewriter: [
'数字游民不是逃离生活,而是用科技重新定义生活。',
'在巴厘岛写代码,在里斯本开会议,在清迈看日落 ☀️',
'世界那么大,你的办公室可以在任何地方 🌍',
'远程工作 + 全球旅居 = 无限可能 ✨',
],
chips: ['💬 3 条新消息', '🟢 128 人在线', '🤝 同城聚会'],
cta: '👥 加群',
oa: {
eyebrow: '保持连接',
title: '关注',
accent: '异度世界',
lead: '获取出海导航、游民社群与会员更新。',
hint: '搜索公众号「异度世界」',
keyword: '加群',
keywordHint: '关注后私信关键词「加群」',
qr: './icons/wechat-oa-qr.png',
},
meetups: (meetups || []).slice(0, 12).map((m) => ({
id: m.id,
emoji: m.emoji || '📍',
title: m.title,
city: m.city || '',
date: m.date || '',
desc: m.description || m.desc || '',
})),
}
const vip = {
brand: cfg.homeBrand,
eyebrow: 'nomadro',
titleAccent: '全模块解锁',
titleRest: '持续更新 · 抱团出海',
lead: '一次付费,解锁电子书、视频教程、私密社群、即时问答,每周更新',
cta: cfg.vipCta,
priceFen: cfg.vipPriceFen,
priceLabel: `¥${((cfg.vipPriceFen || 8800) / 100).toFixed(0)}`,
portalUrl: 'https://nomadro.cn/vip',
stats: [
{ value: '4', label: '模块' },
{ value: '2', label: '电子书' },
{ value: '40+', label: '视频' },
{ value: '每周', label: '更新' },
],
topics: [
{ id: 'ebook', icon: '📖', title: '电子书', desc: '知识沉淀·随时阅读', locked: false },
{ id: 'cloudphone', icon: '🎬', title: '视频教程', desc: '实战演练·即学即用', locked: false },
{ id: 'community', icon: '👥', title: '私密社群', desc: '抱团出海', locked: true },
{ id: 'tools', icon: '🛒', title: '设备自助下单', desc: '开箱即用', locked: true },
],
videos: [
{ id: 'cloudphone', icon: '☁️', title: '云手机', desc: '低成本自建云手机,TikTok/YouTube 无人直播实战指南' },
{ id: 'livestream', icon: '📺', title: '无人直播', desc: 'TikTok/YouTube 无人直播,24 小时自动化' },
{ id: 'indie', icon: '🛠️', title: '独立开发', desc: '从想法到产品,独立开发者全流程指南' },
{ id: 'aiagent', icon: '🤖', title: 'AI Agent', desc: 'AIGC 与智能体,Vibe Coding 跨界创造' },
],
ebooks: [
{ id: '1', title: '数字游民', desc: '地理套利与自动化杠杆', free: true },
{ id: '2', title: '云手机', desc: '低成本工作室搭建指南', locked: true },
],
compare: [
{ feature: '电子书', single: '按需开通', member: '全解锁' },
{ feature: '视频教程', single: '按需开通', member: '全解锁' },
{ feature: '私密社群', single: '—', member: '✓' },
{ feature: '即时问答', single: '—', member: '✓' },
{ feature: '持续更新', single: '—', member: '✓' },
],
faq: [
{
q: '会员包含哪些内容?',
a: '电子书、视频教程、私密社群、即时问答、设备自助下单等全部解锁,并享受持续更新。',
},
{
q: '如何加入?',
a: '点击「立即加入」完成支付即可,支付成功后自动开通,无需人工审核。',
},
{
q: '为什么越早加入越划算?',
a: '会员采用阶梯定价:越早锁定席位,单价越低;在恢复原价前完成支付,可长期享受全部内容与后续更新,整体投入更省、权益不打折。',
},
],
chips: ['阶梯定价', '数字交付', '持续更新', '不支持退款'],
}
const portal = {
config: cfg,
nav: links,
book: portalBook,
community,
cover: {
title: coverBook.title,
subtitle: coverBook.subtitle,
author: coverBook.author,
description: coverBook.description,
tagline: coverBook.tagline,
viralTags: coverBook.viralTags || [],
hooks: (coverBook.hooks || []).map((h) =>
typeof h === 'string' ? h : `${h.emoji || ''} ${h.text || ''}`.trim(),
),
},
vip,
}
const portalJs =
'/* generated from weapp SoT — offline seed for xhs minitool */\n' +
`var PORTAL_DATA = ${JSON.stringify(portal, null, 2)};\n` +
'var NAV_DATA = PORTAL_DATA.nav;\n'
fs.writeFileSync(path.join(xhsTool, 'portal-data.js'), portalJs, 'utf8')
fs.writeFileSync(path.join(xhsTool, 'nav-data.js'), '/* alias */\nvar NAV_DATA = (typeof PORTAL_DATA!=="undefined"&&PORTAL_DATA.nav)||{};\n', 'utf8')
const bookData = {
id: bookMeta.id || 'default',
title: coverBook.title || bookMeta.title,
subtitle: coverBook.subtitle || bookMeta.subtitle,
author: coverBook.author || bookMeta.author,
cover_emoji: bookMeta.cover_emoji || '📖',
description: coverBook.description || bookMeta.description,
tags: coverBook.viralTags || bookMeta.tags || [],
chapter_count: bookChapters.length,
word_count: bookChapters.reduce((s, c) => s + (c.content || '').length, 0),
is_free: true,
chapters: bookChapters.map((c) => ({
id: c.id,
title: c.title,
order: c.order,
content: c.content,
})),
}
const bookJs =
'// Auto-generated from src/data/nomadCodeBook.ts (weapp SoT) — do not edit by hand.\n' +
`var BOOK_DATA = ${JSON.stringify(bookData, null, 2)};\n`
fs.mkdirSync(path.join(xhsTool, 'book'), { recursive: true })
fs.writeFileSync(path.join(xhsTool, 'book', 'book-data.js'), bookJs, 'utf8')
// 公众号二维码(社群加群弹窗)
const qrCandidates = [
path.join(mini, 'src', 'assets', 'wechat-oa-qr.png'),
path.join(mini, 'assets', 'wechat-oa-qr.png'),
]
for (const qr of qrCandidates) {
if (fs.existsSync(qr)) {
fs.copyFileSync(qr, path.join(iconsOut, 'wechat-oa-qr.png'))
break
}
}
console.log(
`[export-xhs-offline] book=${path.relative(mini, bookSource)} ` +
`portal modules=${Object.keys(cfg.modules).join(',')} ` +
`nav_cats=${(links.categories || []).length} book_ch=${bookChapters.length} ` +
`meetups=${community.meetups.length} vip_topics=${vip.topics.length} ` +
`icons=${fs.readdirSync(iconsOut).length}` +
(missing.length ? ` icon_fallback=${missing.length}` : ''),
)