dsh-wechat-studio 0.1.0 → 0.1.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-wechat-studio",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "DeepSeek Harness 插件「公众号成稿台」:写稿、按段改稿、朱雀报告质检、公众号排版预览和一键复制。",
5
5
  "type": "module",
6
6
  "main": "src/host.js",
@@ -16,6 +16,11 @@
16
16
  },
17
17
  "engines": { "node": ">=20", "dsh": ">=0.2.1-rc.5 <0.3.0" },
18
18
  "keywords": ["dsh", "deepseek-harness", "dsh-plugin", "wechat"],
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/lqshow/dsh-wechat-studio.git"
22
+ },
23
+ "homepage": "https://github.com/lqshow/dsh-wechat-studio#readme",
19
24
  "license": "MIT",
20
25
  "scripts": {
21
26
  "build": "node scripts/build.mjs",
package/src/article.js CHANGED
@@ -128,6 +128,13 @@ export function undo(article) {
128
128
  article.hook = last.hook ?? null
129
129
  article.titles = last.titles
130
130
  article.blocks = last.blocks
131
+ if (last.reimportBefore) {
132
+ for (const key of ['summary', 'zhuque', 'imageImport']) {
133
+ const value = last.reimportBefore[key]
134
+ if (value === undefined) delete article[key]
135
+ else article[key] = structuredClone(value)
136
+ }
137
+ }
131
138
  touch(article)
132
139
  return last.label
133
140
  }
@@ -142,6 +149,8 @@ export function revisionChanges(article) {
142
149
  }
143
150
  const oldBlocks = new Map(before.blocks.map((block, i) => [block.id, { text: block.text, number: i + 1 }]))
144
151
  const newIds = new Set(after.blocks.map(block => block.id))
152
+ const oldRank = new Map(before.blocks.filter(block => newIds.has(block.id)).map((block, rank) => [block.id, rank]))
153
+ const newRank = new Map(after.blocks.filter(block => oldBlocks.has(block.id)).map((block, rank) => [block.id, rank]))
145
154
  let cursor = 0
146
155
  const deleted = block => rows.push({ kind: 'delete', before: oldBlocks.get(block.id), after: null })
147
156
  after.blocks.forEach((block, i) => {
@@ -155,6 +164,8 @@ export function revisionChanges(article) {
155
164
  }
156
165
  if (!old || old.text !== block.text) {
157
166
  rows.push({ kind: old ? 'rewrite' : 'insert', before: old ?? null, after: { text: block.text, number: i + 1 } })
167
+ } else if (oldRank.get(block.id) !== newRank.get(block.id)) {
168
+ rows.push({ kind: 'move', before: old, after: { text: block.text, number: i + 1 } })
158
169
  }
159
170
  })
160
171
  for (const block of before.blocks.slice(cursor)) {
package/src/host.js CHANGED
@@ -8,6 +8,7 @@ import { BANNER_CHOICES, BANNER_STYLES, DEFAULT_BANNER } from './banner.js'
8
8
  import { blockKind, clearSchedule, correctPublishedAt, createArticle, fixPlan, HOOK_IDS, isCheckable, listMeta, markPublished, newId, revisionChanges, setSchedule, snapshot, splitMarkdown, toMarkdown, touch, undo, unpublish } from './article.js'
9
9
  import { transferFeishuImages, uploadInlineImage } from './cloudinary.js'
10
10
  import { feishuImageUrls, replaceFeishuImages } from './markdown-images.js'
11
+ import { applyMarkdownReimport, planMarkdownReimport } from './markdown-reimport.js'
11
12
  import { generateInlineImage, readInlineAsset, readInlineImage, removeInlineImages, removeOrphanInlineImages, saveInlineImage } from './inline-assets.js'
12
13
  import { analyzeInlineDiagrams, DIAGRAM_KINDS, insertDiagramBlock, sourceHash } from './inline-diagrams.js'
13
14
  import { loadInlineStyle, readInlineStyleCatalog } from './inline-skill.js'
@@ -326,7 +327,10 @@ function startImageImport(deps, article, urls) {
326
327
  const current = state.articles.find(item => item.id === article.id)
327
328
  if (!current) return
328
329
  // Apply URLs to the latest text so edits made during upload are preserved.
329
- for (const blocks of [current.blocks, ...current.history.map(entry => entry.blocks)]) {
330
+ const boundary = current.history.findLastIndex(entry => entry.reimportBefore)
331
+ const recent = current.history.slice(boundary + 1)
332
+ const blockSets = [current.blocks, ...recent.map(entry => entry.blocks)]
333
+ for (const blocks of blockSets) {
330
334
  for (const block of blocks) {
331
335
  block.text = replaceFeishuImages(block.text, replacements)
332
336
  if (block.prev) block.prev = replaceFeishuImages(block.prev, replacements)
@@ -356,6 +360,7 @@ function view(article, pipeline, store, inlineStyles = [], inlineStyleWarnings =
356
360
  }
357
361
  return {
358
362
  id: article.id, topic: article.topic, title: article.title, titles: article.titles, summary: article.summary,
363
+ publishedAt: article.publishedAt ?? null,
359
364
  blocks: article.blocks.map(block => ({
360
365
  id: block.id, text: block.text, kind: blockKind(block.text), checkable: isCheckable(block.text), check: block.check,
361
366
  hasPrev: Boolean(block.prev), previousText: previousText.get(block.id) ?? (block.prev !== block.text ? block.prev ?? null : null),
@@ -423,6 +428,19 @@ function mustActive(article, message) {
423
428
  if (article.archivedAt) throw Object.assign(new Error(message), { status: 409 })
424
429
  }
425
430
 
431
+ function importConflict(message) {
432
+ return Object.assign(new Error(message), { status: 409 })
433
+ }
434
+
435
+ function assertCanReimport(deps, article) {
436
+ mustActive(article, '归档稿件不能重新导入,请先恢复。')
437
+ if (article.publishedAt) throw importConflict('已发布稿件不能覆盖正文。')
438
+ notBusy(deps.pipeline, article.id)
439
+ if (coverJobMap(deps.store).has(article.id) || imageJobMap(deps.store).has(article.id) || diagramJobMap(deps.store).has(article.id)) {
440
+ throw importConflict('请等封面生成、图片转存或插图任务完成后再重新导入。')
441
+ }
442
+ }
443
+
426
444
  function mustPastPublication(at) {
427
445
  if (new Date(at).getTime() > Date.now()) {
428
446
  throw Object.assign(new Error('实际发表时间不能晚于现在。'), { status: 400 })
@@ -663,6 +681,37 @@ export async function route(deps, req, res) {
663
681
  else throw Object.assign(new Error('没有这篇数据趋势文章'), { status: 404 })
664
682
  })
665
683
  return json(res, 200, await insightsView(deps, body.range))
684
+ case 'articles/reimport/preview': {
685
+ const article = mustFind(await store.read(), body.id)
686
+ assertCanReimport(deps, article)
687
+ const plan = planMarkdownReimport(article, body.markdown, { updateTitle: body.updateTitle === true })
688
+ return json(res, 200, {
689
+ token: plan.token, currentTitle: article.title, incomingTitle: plan.incomingTitle, finalTitle: plan.finalTitle,
690
+ changed: plan.changed, bodyChanged: plan.bodyChanged, kept: plan.kept, removed: plan.removed, added: plan.added,
691
+ removedMedia: plan.removedMedia, transfers: plan.bodyChanged ? feishuImageUrls(plan.entries).length : 0,
692
+ bannerReview: Boolean(article.banners?.[article.bannerStyle ?? DEFAULT_BANNER]),
693
+ })
694
+ }
695
+ case 'articles/reimport': {
696
+ const result = await store.update(state => {
697
+ const article = mustFind(state, body.id)
698
+ assertCanReimport(deps, article)
699
+ const plan = planMarkdownReimport(article, body.markdown, { updateTitle: body.updateTitle === true })
700
+ if (plan.token !== body.token) throw importConflict('稿件或导入选项已变化,请重新预检。')
701
+ if (plan.removedMedia.length && body.acknowledgeRemovedMedia !== true) {
702
+ throw importConflict('请先确认将移出的图片和动画卡。')
703
+ }
704
+ if (!plan.changed) throw importConflict('与当前稿件一致,无需覆盖。')
705
+ const applied = applyMarkdownReimport(article, plan)
706
+ if (applied.urls.length) {
707
+ article.imageImport = { error: '图片转存中断,可以重试。', remaining: applied.urls.length }
708
+ }
709
+ article.notice = { text: '已覆盖正文,可在改稿对比查看,或用顶部撤销恢复。', at: new Date().toISOString() }
710
+ return applied
711
+ })
712
+ startImageImport(deps, result.article, result.urls)
713
+ return ok()
714
+ }
666
715
  case 'articles/new': {
667
716
  const hasBody = typeof body.markdown === 'string' && body.markdown.trim()
668
717
  if (!hasBody && !String(body.topic ?? '').trim() && !String(body.material ?? '').trim()) throw Object.assign(new Error('写一句选题,或者贴入已有的文章。'), { status: 400 })
@@ -968,6 +1017,9 @@ export async function route(deps, req, res) {
968
1017
  await store.update(state => {
969
1018
  const article = mustFind(state, body.id)
970
1019
  notBusy(pipeline, article.id)
1020
+ if (article.history.at(-1)?.reimportBefore && imageJobMap(store).has(article.id)) {
1021
+ throw importConflict('图片转存完成后可恢复覆盖前版本。')
1022
+ }
971
1023
  const label = undo(article)
972
1024
  if (label) article.notice = { text: `已撤销:${label}`, at: new Date().toISOString() }
973
1025
  })
@@ -13,10 +13,17 @@ function isFeishuImage(value) {
13
13
 
14
14
  function imageMatches(markdown) {
15
15
  // Keep code examples untouched; only replace inline Markdown image destinations.
16
- const pattern = /^ {0,3}(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^ {0,3}\1[\x60~]*[ \t]*\r?$|(?![\s\S]))|(`+)[^\n]*?\2|\\[^\n]|(!\[[^\]\n]*\]\(<?)([^\s>)]+)(>?(?:[ \t]+"[^"\n]*")?\))/gm
16
+ const pattern = /^ {0,3}(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^ {0,3}\1[\x60~]*[ \t]*\r?$|(?![\s\S]))|(`+)[^\n]*?\2|\\[^\n]|(!\[(?:\\.|[^\]\\])*\]\(<?)([^\s>)]+)(>?(?:[ \t]+"[^"\n]*")?\))/gm
17
17
  return [...markdown.matchAll(pattern)].filter(match => match[4])
18
18
  }
19
19
 
20
+ export function markdownImageDestinations(text) {
21
+ return imageMatches(String(text ?? '')).map(match => ({
22
+ src: match[4],
23
+ caption: match[3].slice(2, match[3].lastIndexOf('](')).replace(/\\([\\\[\]])/g, '$1'),
24
+ }))
25
+ }
26
+
20
27
  export function feishuImageUrls(blocks) {
21
28
  return [...new Set(blocks.flatMap(block => imageMatches(block.text).map(match => match[4]).filter(isFeishuImage)))]
22
29
  }
@@ -0,0 +1,108 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { newId, snapshot, splitMarkdown, touch } from './article.js'
3
+ import { feishuImageUrls, markdownImageDestinations } from './markdown-images.js'
4
+ import { parseSvgCardBlock } from './svg-cards.js'
5
+
6
+ const fail = message => Object.assign(new Error(message), { status: 400 })
7
+ const sha = value => createHash('sha256').update(JSON.stringify(value)).digest('hex')
8
+ const isSvg = text => /^```svg-[a-z]+(?:\s|$)/.test(text.trim())
9
+
10
+ function svgMedia(text, number, blockId) {
11
+ let card
12
+ try {
13
+ card = parseSvgCardBlock(text)
14
+ } catch (error) {
15
+ if (blockId === undefined) throw fail(`第 ${number} 块动画卡无效:${error.message}`)
16
+ const title = text.trim().match(/^```svg-[a-z]+(?:[ \t]+([^\n]+))?/)?.[1] ?? '动画卡'
17
+ return { key: `svg-raw:${text}`, item: { kind: 'svg', blockId, number, title } }
18
+ }
19
+ return {
20
+ key: `svg:${JSON.stringify(card)}`,
21
+ item: { kind: 'svg', blockId, number, title: card.title },
22
+ }
23
+ }
24
+
25
+ function mediaAt(text, number, blockId) {
26
+ if (isSvg(text)) return [svgMedia(text, number, blockId)]
27
+ return markdownImageDestinations(text).map((image, occurrence) => ({
28
+ key: `image:${image.src}`,
29
+ item: { kind: 'image', blockId, number, caption: image.caption, src: image.src, occurrence },
30
+ }))
31
+ }
32
+
33
+ export function planMarkdownReimport(article, markdown, { updateTitle = false } = {}) {
34
+ if (typeof markdown !== 'string') throw fail('Markdown 必须是文本。')
35
+ const parsed = splitMarkdown(markdown.replace(/^\uFEFF/, ''))
36
+ if (!parsed.blocks.length) throw fail('导入文件必须包含正文,只有标题或元信息不能覆盖。')
37
+ if (updateTitle && !parsed.title) throw fail('选择更新标题时,文件必须包含一级标题。')
38
+ if (updateTitle && parsed.title.length > 80) {
39
+ throw fail('一级标题不能超过 80 字;可取消同时更新标题后仅覆盖正文。')
40
+ }
41
+
42
+ const sameBody = parsed.blocks.length === article.blocks.length
43
+ && parsed.blocks.every((text, index) => text === article.blocks[index].text)
44
+ const oldFrequencies = new Map()
45
+ const newFrequencies = new Map()
46
+ const oldByText = new Map()
47
+ for (const block of article.blocks) {
48
+ oldFrequencies.set(block.text, (oldFrequencies.get(block.text) ?? 0) + 1)
49
+ oldByText.set(block.text, block)
50
+ }
51
+ for (const text of parsed.blocks) newFrequencies.set(text, (newFrequencies.get(text) ?? 0) + 1)
52
+ const entries = parsed.blocks.map((text, index) => {
53
+ const unique = oldFrequencies.get(text) === 1 && newFrequencies.get(text) === 1
54
+ return { text, existing: sameBody ? article.blocks[index] : unique ? oldByText.get(text) : null }
55
+ })
56
+
57
+ const incomingMedia = new Map()
58
+ parsed.blocks.forEach((text, index) => {
59
+ for (const media of mediaAt(text, index + 1)) {
60
+ incomingMedia.set(media.key, (incomingMedia.get(media.key) ?? 0) + 1)
61
+ }
62
+ })
63
+ const removedMedia = []
64
+ article.blocks.forEach((block, index) => {
65
+ for (const media of mediaAt(block.text, index + 1, block.id)) {
66
+ const remaining = incomingMedia.get(media.key) ?? 0
67
+ if (remaining > 0) incomingMedia.set(media.key, remaining - 1)
68
+ else removedMedia.push(media.item)
69
+ }
70
+ })
71
+
72
+ const finalTitle = updateTitle ? parsed.title : article.title
73
+ const changed = !sameBody || finalTitle !== article.title
74
+ const kept = entries.filter(entry => entry.existing).length
75
+ const token = sha([
76
+ article.id, article.title, article.summary, article.hook, article.titles,
77
+ article.blocks, article.zhuque, article.archivedAt, article.publishedAt,
78
+ parsed.blocks, parsed.title, updateTitle,
79
+ ])
80
+ return {
81
+ token, title: article.title, finalTitle, incomingTitle: parsed.title,
82
+ changed, bodyChanged: !sameBody, kept, removed: article.blocks.length - kept, added: entries.length - kept,
83
+ entries, removedMedia,
84
+ }
85
+ }
86
+
87
+ export function applyMarkdownReimport(article, plan) {
88
+ const bodyChanged = plan.bodyChanged
89
+ snapshot(article, '重新导入 Markdown')
90
+ article.history.at(-1).reimportBefore = {
91
+ summary: structuredClone(article.summary),
92
+ zhuque: structuredClone(article.zhuque),
93
+ imageImport: structuredClone(article.imageImport),
94
+ }
95
+ if (bodyChanged) {
96
+ article.blocks = plan.entries.map(entry => ({ id: entry.existing?.id ?? newId(), text: entry.text, check: null }))
97
+ article.summary = ''
98
+ article.titles = []
99
+ article.zhuque = { round: 0, lastAt: null }
100
+ article.imageImport = null
101
+ }
102
+ if (plan.finalTitle !== article.title) {
103
+ article.title = plan.finalTitle
104
+ article.hook = null
105
+ }
106
+ touch(article)
107
+ return { article, urls: bodyChanged ? feishuImageUrls(article.blocks) : [] }
108
+ }