fix(datasource/dingtalk): 块级渲染不再静默丢内容(列表按线上真实形状渲染 + 未建模块类型可见) (#3822)
* fix(datasource/dingtalk): 块级渲染不再静默丢内容(列表按契约渲染 + 未建模块类型可见)
渲染器有三处会无声地丢正文:
- 列表块只在 inline 子节点渲染结果为空时才递归子块,于是 children 里既有
inline 又有块级元素时,块级子节点的文本永远不渲染 —— 而且连 unknown 标记
都不设,完全无痕;块级列表项还会被 strings.Fields 折叠进同一个 bullet 行;
- 未建模的块类型(code / attachment / slot / sheet / unknown …)payload 解析
不出来,正文整块丢失,只剩类型名写进文档 metadata,全仓没有一行日志;
- 未建模的 inline 元素类型(slot 等,官方文档里文本放在 children)在默认分支
只写 text 字段,children 里的正文直接消失。
改动:
- 列表按官方契约渲染:一个列表块 = 一个列表项,缩进用 list.level(0-based),
同一列表的多项是共享 listId 的兄弟块(扁平模型),不假设结构嵌套;契约外的
块级子节点仍然逐个渲染,作为防御,不再二选一、不再塌行;
- 未建模的 inline 元素在自身没有文本时渲染 children,避免整段消失;
- 未建模块类型在 Fetch 路径上显式暴露(这一层同时拿得到 ctx 与节点身份):
collectUnknownBlockTypes 产出可测值,同时喂给 logger.Warnf 与
common.PipelineWarn;文档 metadata 保持不变。
code / attachment / sheet / slot 的正文渲染不在本次范围:它们的块级 JSON 形状
仍无可靠证据(官方与公开 CLI 参考的键名互相冲突),先靠告警把真实 payload
找出来再按形状补,免得用猜测的字段把"可见的丢失"变回"静默的丢失"。
* fix(datasource/dingtalk): 按实测形状补 code / attachment / unknown 三类块的渲染
只读探针在真实 adoc 文档上取到的形状(不再依赖公开参考里互相冲突的键名):
- code: {"syntax":"bash","text":"...","title":"..."},title 有时缺;语言键是
syntax 而不是 language;
- attachment: {"name":..,"size":..,"type":..,"viewType":..,"resourceId":..},
resourceId 有时缺,payload 里没有任何下载 URL;
- unknown: {"rawType":"..."},只有真实类型名,没有正文;
- table.cells 的读取路径与实测一致,未改动。
改动:
- code 渲染成围栏代码块:语言取 syntax(含反引号或换行这类无法作为 info string
的值时省略),围栏长度取 max(3, 正文最长反引号串+1),避免正文自带的围栏把代码块
提前截断;title 非空时在围栏前输出一行加粗标题;text 为空不输出空围栏,仍按未建模
类型记录并告警;
- attachment 渲染成一行纯文本 Attachment: <name> (<size>):名称做 Markdown 转义,
size 按 1024 进制保留一位小数(B/KB/MB/GB),size<=0 时省略括号;payload 没有可
解析的下载地址,因此不拿 resourceId 拼任何链接;名称为空不输出,仍按未建模类型
记录并告警;
- unknown:default 分支在 rawType 非空时把标记写成 "unknown:"+rawType,使
unknown_block_types metadata 与 warnUnknownBlockTypes 的日志/pipeline 事件直接
带真实类型名,而不是无信息量的 "unknown"(字段名、签名与调用位置均未动),
children 仍逐层递归。
既有普通块(段落/标题/引用/表格/列表)的输出逐字节不变,回归用例
TestRenderDocumentKeepsOrdinaryBlocksStable 未修改即通过。原先拿 code/attachment
当“未建模”夹具的两个用例改用空载荷的同类块与带 rawType 的 unknown 块,覆盖新的
“渲染不出内容仍要告警”语义。
* fix(datasource/dingtalk): 列表按线上真实形状渲染(块自带 text)
线上 Blocks API 返回的是一个列表项一个块,正文在块自带的 text 字段里,
没有 children、没有 list.level、也没有 listId。列表是唯一一类没有回退到
「块自带 text」的正文块 —— paragraph / heading / blockquote 都有
renderInlines(children) 取不到就取自身 text 的回退,列表直接进
renderListBlock,而那个函数只遍历 children,于是列表正文被整条丢弃;
又因为 blockType 是已知类型,switch 命中了它,连 unknown_block_types
都不会记一笔。
同一形状问题还影响 unknown:sdt 块(文档目录)的正文就在 unknown.text 里,
此前只写标记不渲染正文。
夹具取自线上 payload(markdown_live_shape_test.go),不按转述的契约自造。
---------
Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
main
parent
08f7e702cf
commit
7d1d71e50d
|
|
@ -12,6 +12,7 @@ import (
|
|||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/common"
|
||||
"github.com/Tencent/WeKnora/internal/datasource"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
|
|
@ -559,6 +560,9 @@ func (c *Connector) sync(
|
|||
continue
|
||||
}
|
||||
rendered := renderDocument(document.title(), blocks)
|
||||
// The renderer stays context-free; the warning is emitted here,
|
||||
// where both the request context and the node identity are known.
|
||||
warnUnknownBlockTypes(ctx, document, rendered)
|
||||
items = append(items, fetchedDocument(
|
||||
scope.ResourceID, scope.Reference.WorkspaceID, document, rendered,
|
||||
))
|
||||
|
|
@ -851,6 +855,59 @@ type renderResult struct {
|
|||
UnknownTypes []string
|
||||
}
|
||||
|
||||
// unknownBlockTypes identifies a document whose Blocks payload contains types
|
||||
// the renderer does not model. The log line and the pipeline event are both
|
||||
// built from this value, so the collection logic is testable on its own
|
||||
// instead of through log text.
|
||||
type unknownBlockTypes struct {
|
||||
NodeID string
|
||||
Title string
|
||||
URL string
|
||||
BlockTypes []string
|
||||
}
|
||||
|
||||
// collectUnknownBlockTypes reports the unknown block types of a rendered
|
||||
// document, or false when the document rendered without loss.
|
||||
func collectUnknownBlockTypes(document node, rendered renderResult) (unknownBlockTypes, bool) {
|
||||
if len(rendered.UnknownTypes) == 0 {
|
||||
return unknownBlockTypes{}, false
|
||||
}
|
||||
types := make([]string, len(rendered.UnknownTypes))
|
||||
copy(types, rendered.UnknownTypes)
|
||||
return unknownBlockTypes{
|
||||
NodeID: document.ID,
|
||||
Title: document.title(),
|
||||
URL: strings.TrimSpace(document.URL),
|
||||
BlockTypes: types,
|
||||
}, true
|
||||
}
|
||||
|
||||
func (u unknownBlockTypes) fields() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"node_id": u.NodeID,
|
||||
"title": u.Title,
|
||||
"url": u.URL,
|
||||
"block_types": strings.Join(u.BlockTypes, ","),
|
||||
"count": len(u.BlockTypes),
|
||||
}
|
||||
}
|
||||
|
||||
// warnUnknownBlockTypes surfaces blocks the renderer could not model. The type
|
||||
// names also land in document metadata, but metadata is invisible to operators
|
||||
// watching sync logs, so the loss is reported as a warning and as a structured
|
||||
// pipeline event as well. Content of those blocks is still missing from the
|
||||
// rendered Markdown until their payloads are modelled.
|
||||
func warnUnknownBlockTypes(ctx context.Context, document node, rendered renderResult) {
|
||||
unknown, ok := collectUnknownBlockTypes(document, rendered)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
logger.Warnf(ctx,
|
||||
"[DingTalk] document %s (%s) contains unmodelled block types %s; their text is not rendered",
|
||||
unknown.NodeID, unknown.Title, strings.Join(unknown.BlockTypes, ", "))
|
||||
common.PipelineWarn(ctx, "DingTalkConnector", "unknown_block_types", unknown.fields())
|
||||
}
|
||||
|
||||
func fetchedDocument(
|
||||
sourceResourceID string,
|
||||
workspaceID string,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,142 @@
|
|||
package dingtalk
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// The unknown-type collection is a value on its own so the reporting path is
|
||||
// testable without asserting on free-form log text: whatever this returns is
|
||||
// exactly what the warning and the pipeline event carry.
|
||||
func TestCollectUnknownBlockTypesReportsDocumentIdentity(t *testing.T) {
|
||||
document := node{
|
||||
ID: "node-1",
|
||||
Name: "季度规划",
|
||||
URL: "https://example.com/i/nodes/node-1",
|
||||
}
|
||||
rendered := renderResult{Markdown: "# 季度规划\n", UnknownTypes: []string{"attachment", "code"}}
|
||||
|
||||
unknown, ok := collectUnknownBlockTypes(document, rendered)
|
||||
if !ok {
|
||||
t.Fatal("collectUnknownBlockTypes() reported a complete document")
|
||||
}
|
||||
if unknown.NodeID != "node-1" || unknown.Title != "季度规划" ||
|
||||
unknown.URL != "https://example.com/i/nodes/node-1" ||
|
||||
!reflect.DeepEqual(unknown.BlockTypes, []string{"attachment", "code"}) {
|
||||
t.Fatalf("unknownBlockTypes = %#v", unknown)
|
||||
}
|
||||
|
||||
fields := unknown.fields()
|
||||
if fields["node_id"] != "node-1" || fields["title"] != "季度规划" ||
|
||||
fields["block_types"] != "attachment,code" || fields["count"] != 2 {
|
||||
t.Fatalf("fields() = %#v", fields)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollectUnknownBlockTypesIsSilentWhenComplete(t *testing.T) {
|
||||
if _, ok := collectUnknownBlockTypes(node{ID: "node-1"}, renderResult{Markdown: "# ok\n"}); ok {
|
||||
t.Fatal("collectUnknownBlockTypes() reported loss for a fully rendered document")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownBlockTypesTitleFallsBackToNodeID(t *testing.T) {
|
||||
unknown, ok := collectUnknownBlockTypes(
|
||||
node{ID: "node-2"},
|
||||
renderResult{UnknownTypes: []string{"code"}},
|
||||
)
|
||||
if !ok || unknown.Title != "node-2" {
|
||||
t.Fatalf("unknownBlockTypes = %#v, ok = %v", unknown, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// An unmodelled block type must stay visible on the fetch path: it keeps the
|
||||
// metadata entry and additionally reaches the structured pipeline event that
|
||||
// monitoring keys on. A block the API could not map carries only the real type
|
||||
// name, and that name is what the metadata and the event must show. Only the
|
||||
// stage/action pair and the document identity are asserted here, never the
|
||||
// free-form message.
|
||||
func TestFetchAllReportsUnknownBlockTypes(t *testing.T) {
|
||||
api := &fakeAPI{
|
||||
workspaces: []workspace{{ID: "space", RootNodeID: "root", Name: "Space"}},
|
||||
nodes: map[string][]node{
|
||||
"root": {{
|
||||
ID: "doc-unmapped", Type: "FILE", Category: "ALIDOC", Extension: "adoc",
|
||||
Name: "Release notes",
|
||||
}},
|
||||
},
|
||||
blocks: map[string][]json.RawMessage{
|
||||
"doc-unmapped": {rawJSON(`{"blockType":"unknown","unknown":{"rawType":"card"}}`)},
|
||||
},
|
||||
nodeErrors: make(map[string]error),
|
||||
blockErrors: make(map[string]error),
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
logger.SetOutput(&buf)
|
||||
defer logger.SetOutput(os.Stdout)
|
||||
|
||||
items, err := testConnector(api).FetchAll(context.Background(), testConfig("space"), []string{"space"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll() error = %v", err)
|
||||
}
|
||||
if len(items) != 1 {
|
||||
t.Fatalf("FetchAll() returned %d items, want 1", len(items))
|
||||
}
|
||||
if got := items[0].Metadata["unknown_block_types"]; got != "unknown:card" {
|
||||
t.Fatalf("metadata unknown_block_types = %q, want %q", got, "unknown:card")
|
||||
}
|
||||
for _, want := range []string{
|
||||
"stage=DingTalkConnector",
|
||||
"action=unknown_block_types",
|
||||
`node_id="doc-unmapped"`,
|
||||
`block_types="unknown:card"`,
|
||||
} {
|
||||
if !strings.Contains(buf.String(), want) {
|
||||
t.Fatalf("pipeline event missing %q:\n%s", want, buf.String())
|
||||
}
|
||||
}
|
||||
t.Logf("emitted warnings:\n%s", strings.TrimSpace(buf.String()))
|
||||
}
|
||||
|
||||
// A document whose blocks are all modelled must not emit the warning.
|
||||
func TestFetchAllStaysQuietForModelledBlocks(t *testing.T) {
|
||||
api := &fakeAPI{
|
||||
workspaces: []workspace{{ID: "space", RootNodeID: "root", Name: "Space"}},
|
||||
nodes: map[string][]node{
|
||||
"root": {{
|
||||
ID: "doc-plain", Type: "FILE", Category: "ALIDOC", Extension: "adoc",
|
||||
Name: "Release notes",
|
||||
}},
|
||||
},
|
||||
blocks: map[string][]json.RawMessage{
|
||||
"doc-plain": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"all good"}}`)},
|
||||
},
|
||||
nodeErrors: make(map[string]error),
|
||||
blockErrors: make(map[string]error),
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
logger.SetOutput(&buf)
|
||||
defer logger.SetOutput(os.Stdout)
|
||||
|
||||
items, err := testConnector(api).FetchAll(context.Background(), testConfig("space"), []string{"space"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll() error = %v", err)
|
||||
}
|
||||
if len(items) != 1 {
|
||||
t.Fatalf("FetchAll() returned %d items, want 1", len(items))
|
||||
}
|
||||
if _, exists := items[0].Metadata["unknown_block_types"]; exists {
|
||||
t.Fatalf("metadata = %#v, want no unknown_block_types", items[0].Metadata)
|
||||
}
|
||||
if strings.Contains(buf.String(), "action=unknown_block_types") {
|
||||
t.Fatalf("unexpected warning for a fully rendered document:\n%s", buf.String())
|
||||
}
|
||||
}
|
||||
|
|
@ -19,6 +19,9 @@ type block struct {
|
|||
OrderedList listBlock `json:"orderedList"`
|
||||
UnorderedList listBlock `json:"unorderedList"`
|
||||
Table tableBlock `json:"table"`
|
||||
Code codeBlock `json:"code"`
|
||||
Attachment attachmentBlock `json:"attachment"`
|
||||
Unknown unknownBlock `json:"unknown"`
|
||||
Children []json.RawMessage `json:"children"`
|
||||
}
|
||||
|
||||
|
|
@ -32,6 +35,7 @@ type headingBlock struct {
|
|||
}
|
||||
|
||||
type listBlock struct {
|
||||
Text string `json:"text"`
|
||||
List struct {
|
||||
Level flexibleInt `json:"level"`
|
||||
} `json:"list"`
|
||||
|
|
@ -41,6 +45,32 @@ type tableBlock struct {
|
|||
Cells json.RawMessage `json:"cells"`
|
||||
}
|
||||
|
||||
// codeBlock is the payload the Blocks API returns for a code block:
|
||||
// {"syntax":"bash","text":"...","title":"..."}. The language key is syntax
|
||||
// (not "language", as some public references assume) and title is optional.
|
||||
type codeBlock struct {
|
||||
Text string `json:"text"`
|
||||
Syntax string `json:"syntax"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
|
||||
// attachmentBlock identifies a file stored in the document. The payload has no
|
||||
// download URL: resourceId is an opaque identifier, not a resolvable address.
|
||||
type attachmentBlock struct {
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
Type string `json:"type"`
|
||||
ViewType string `json:"viewType"`
|
||||
ResourceID string `json:"resourceId"`
|
||||
}
|
||||
|
||||
// unknownBlock is the payload of a block whose real type the API did not map:
|
||||
// {"rawType":"..."}. It carries no body text, only the original type name.
|
||||
type unknownBlock struct {
|
||||
RawType string `json:"rawType"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type inline struct {
|
||||
ElementType string `json:"elementType"`
|
||||
Text string `json:"text"`
|
||||
|
|
@ -138,25 +168,7 @@ func renderBlock(
|
|||
}
|
||||
builder.WriteByte('\n')
|
||||
case "orderedlist", "unorderedlist":
|
||||
text := renderInlines(value.Children, depth+1, unknown)
|
||||
if text == "" {
|
||||
var nested strings.Builder
|
||||
renderChildBlocks(&nested, value.Children, depth, unknown)
|
||||
text = strings.Join(strings.Fields(strings.TrimSpace(nested.String())), " ")
|
||||
}
|
||||
if text == "" {
|
||||
return
|
||||
}
|
||||
level, marker := int(value.UnorderedList.List.Level), "- "
|
||||
if blockType == "orderedlist" {
|
||||
level, marker = int(value.OrderedList.List.Level), "1. "
|
||||
}
|
||||
if level < 0 {
|
||||
level = 0
|
||||
} else if level > maxRenderDepth {
|
||||
level = maxRenderDepth
|
||||
}
|
||||
fmt.Fprintf(builder, "%s%s%s\n", strings.Repeat(" ", level), marker, text)
|
||||
renderListBlock(builder, value, blockType, depth, 0, unknown)
|
||||
case "callout", "columns":
|
||||
if len(value.Children) == 0 {
|
||||
// The Blocks API only returns first-level blocks. A container with
|
||||
|
|
@ -168,16 +180,180 @@ func renderBlock(
|
|||
renderChildBlocks(builder, value.Children, depth, unknown)
|
||||
case "table":
|
||||
renderTable(builder, parseTableCells(value.Table.Cells))
|
||||
case "code":
|
||||
renderCodeBlock(builder, value, depth, unknown)
|
||||
case "attachment":
|
||||
renderAttachmentBlock(builder, value, depth, unknown)
|
||||
case "":
|
||||
unknown["missing_block_type"] = struct{}{}
|
||||
default:
|
||||
unknown[blockType] = struct{}{}
|
||||
marker := blockType
|
||||
if rawType := strings.TrimSpace(value.Unknown.RawType); rawType != "" {
|
||||
// The payload of this block carries no body text, only the real
|
||||
// type name, so keep that name in the marker instead of the
|
||||
// uninformative "unknown": it is what the metadata and the sync
|
||||
// warning report.
|
||||
marker = "unknown:" + rawType
|
||||
}
|
||||
unknown[marker] = struct{}{}
|
||||
// Some unmodelled blocks still carry their body text: the live `sdt`
|
||||
// block is a table of contents and holds the whole thing. The type stays
|
||||
// unknown — the marker above still reports it — but the text must not be
|
||||
// dropped just because the presentation semantics are not modelled.
|
||||
if text := strings.TrimSpace(value.Unknown.Text); text != "" {
|
||||
writeParagraph(builder, escapeText(text))
|
||||
}
|
||||
// Preserve useful content when DingTalk introduces a container block
|
||||
// before the connector learns its presentation semantics.
|
||||
renderChildBlocks(builder, value.Children, depth, unknown)
|
||||
}
|
||||
}
|
||||
|
||||
// renderListBlock renders one list block.
|
||||
//
|
||||
// Documented shape: children are inline elements and one block is one item —
|
||||
// nesting comes from list.level (0-based) and the items of one list are linked
|
||||
// by a shared listId across sibling blocks, not by structural nesting. The
|
||||
// child walk below also accepts block children, which the contract does not
|
||||
// produce: the previous implementation rendered inline children *or* block
|
||||
// children (never both), so a payload outside the contract lost whichever kind
|
||||
// it did not pick, sometimes without even an unknown-type marker.
|
||||
//
|
||||
// minLevel is the smallest indent level this list may use; pass 0 for a
|
||||
// top-level list.
|
||||
func renderListBlock(
|
||||
builder *strings.Builder,
|
||||
value block,
|
||||
blockType string,
|
||||
depth int,
|
||||
minLevel int,
|
||||
unknown map[string]struct{},
|
||||
) {
|
||||
if depth > maxRenderDepth {
|
||||
unknown["max_depth"] = struct{}{}
|
||||
return
|
||||
}
|
||||
|
||||
level, marker := int(value.UnorderedList.List.Level), "- "
|
||||
if blockType == "orderedlist" {
|
||||
level, marker = int(value.OrderedList.List.Level), "1. "
|
||||
}
|
||||
if level < minLevel {
|
||||
level = minLevel
|
||||
}
|
||||
if level < 0 {
|
||||
level = 0
|
||||
} else if level > maxRenderDepth {
|
||||
level = maxRenderDepth
|
||||
}
|
||||
indent := strings.Repeat(" ", level)
|
||||
|
||||
// Inline children are the current item's own text and block children are
|
||||
// further items, so walk the children in payload order: consecutive inline
|
||||
// elements form one item, and every block child becomes its own item.
|
||||
// The live Blocks API delivers one block per list item, with the item text
|
||||
// in the block's own text field and no children at all: across every list
|
||||
// block of nine production documents there is no children, no list.level
|
||||
// and no listId. Every other text-bearing block type already falls back to
|
||||
// its own text field; lists were the one that did not, so their content was
|
||||
// dropped without even an unknown-type marker — the type is known, it just
|
||||
// carried nothing the renderer read.
|
||||
ownText := strings.TrimSpace(listOwnText(value, blockType))
|
||||
if ownText != "" {
|
||||
writeListItem(builder, indent, marker, escapeText(ownText))
|
||||
}
|
||||
|
||||
var pending strings.Builder
|
||||
flush := func() {
|
||||
if text := pending.String(); text != "" {
|
||||
writeListItem(builder, indent, marker, text)
|
||||
}
|
||||
pending.Reset()
|
||||
}
|
||||
for _, child := range value.Children {
|
||||
childType := blockChildType(child)
|
||||
if childType == "" {
|
||||
if ownText != "" {
|
||||
// A shape the API does not produce. The item text is already in
|
||||
// the block's own field, so a second bullet would duplicate it;
|
||||
// surface the shape instead of guessing which one is the item.
|
||||
unknown["list_text_and_inline_children"] = struct{}{}
|
||||
continue
|
||||
}
|
||||
pending.WriteString(renderInlines([]json.RawMessage{child}, depth+1, unknown))
|
||||
continue
|
||||
}
|
||||
flush()
|
||||
if childType == "orderedlist" || childType == "unorderedlist" {
|
||||
var nested block
|
||||
if err := json.Unmarshal(child, &nested); err != nil {
|
||||
unknown["invalid_json"] = struct{}{}
|
||||
continue
|
||||
}
|
||||
// Outside the documented contract: the Blocks API returns lists
|
||||
// flat (one block per item, siblings linked by listId, nesting
|
||||
// carried by list.level), so a list child that is itself a list
|
||||
// should not appear. If one does, keep it below its parent rather
|
||||
// than at the same indent, and never drop it.
|
||||
renderListBlock(builder, nested, childType, depth+1, level+1, unknown)
|
||||
continue
|
||||
}
|
||||
var item strings.Builder
|
||||
renderBlock(&item, child, depth+1, unknown)
|
||||
if text := strings.TrimSpace(item.String()); text != "" {
|
||||
writeListItem(builder, indent, marker, text)
|
||||
}
|
||||
}
|
||||
flush()
|
||||
}
|
||||
|
||||
// listOwnText returns the item text a list block carries in its own payload.
|
||||
// The live Blocks API puts one item per block and its text here.
|
||||
func listOwnText(value block, blockType string) string {
|
||||
if blockType == "orderedlist" {
|
||||
return value.OrderedList.Text
|
||||
}
|
||||
return value.UnorderedList.Text
|
||||
}
|
||||
|
||||
// blockChildType reports the block type of a list child, or "" when the child
|
||||
// is an inline element (including an untyped text run) rather than a block.
|
||||
func blockChildType(raw json.RawMessage) string {
|
||||
var probe struct {
|
||||
BlockType string `json:"blockType"`
|
||||
ElementType string `json:"elementType"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &probe); err != nil {
|
||||
return ""
|
||||
}
|
||||
if strings.TrimSpace(probe.ElementType) != "" {
|
||||
return ""
|
||||
}
|
||||
return strings.ToLower(strings.TrimSpace(probe.BlockType))
|
||||
}
|
||||
|
||||
// writeListItem writes one list item. Continuation lines of a multi-line item
|
||||
// are aligned under the first line so the value cannot escape its bullet.
|
||||
func writeListItem(builder *strings.Builder, indent string, marker string, text string) {
|
||||
lines := strings.Split(text, "\n")
|
||||
builder.WriteString(indent)
|
||||
builder.WriteString(marker)
|
||||
builder.WriteString(lines[0])
|
||||
builder.WriteByte('\n')
|
||||
if len(lines) == 1 {
|
||||
return
|
||||
}
|
||||
continuation := strings.Repeat(" ", len(indent)+len(marker))
|
||||
for _, line := range lines[1:] {
|
||||
if line = strings.TrimRight(line, " \t"); line == "" {
|
||||
continue
|
||||
}
|
||||
builder.WriteString(continuation)
|
||||
builder.WriteString(line)
|
||||
builder.WriteByte('\n')
|
||||
}
|
||||
}
|
||||
|
||||
func renderChildBlocks(
|
||||
builder *strings.Builder,
|
||||
children []json.RawMessage,
|
||||
|
|
@ -229,7 +405,14 @@ func renderInlines(
|
|||
}
|
||||
default:
|
||||
unknown["inline_"+elementType] = struct{}{}
|
||||
builder.WriteString(escapeText(value.Text))
|
||||
// Inline types this renderer does not model can carry their text in
|
||||
// children instead of in a text field (slot is documented that way),
|
||||
// so falling back to children keeps the run from vanishing.
|
||||
if text := escapeText(value.Text); text != "" {
|
||||
builder.WriteString(text)
|
||||
} else {
|
||||
builder.WriteString(renderInlines(value.Children, depth+1, unknown))
|
||||
}
|
||||
}
|
||||
}
|
||||
return builder.String()
|
||||
|
|
@ -285,6 +468,113 @@ func writeParagraph(builder *strings.Builder, text string) {
|
|||
}
|
||||
}
|
||||
|
||||
// renderCodeBlock renders a code block as a fenced code block. The language
|
||||
// comes from syntax, and a non-empty title becomes a bold line above the fence.
|
||||
// A block without text stays unmodelled: an empty fence would only be noise, so
|
||||
// the loss is still reported instead.
|
||||
func renderCodeBlock(
|
||||
builder *strings.Builder,
|
||||
value block,
|
||||
depth int,
|
||||
unknown map[string]struct{},
|
||||
) {
|
||||
if strings.TrimSpace(value.Code.Text) == "" {
|
||||
unknown["code"] = struct{}{}
|
||||
// The documented shape carries no children, but a payload outside the
|
||||
// contract must not lose them.
|
||||
renderChildBlocks(builder, value.Children, depth, unknown)
|
||||
return
|
||||
}
|
||||
if title := oneLine(value.Code.Title); title != "" {
|
||||
fmt.Fprintf(builder, "**%s**\n\n", escapeText(title))
|
||||
}
|
||||
fence := strings.Repeat("`", codeFenceLength(value.Code.Text))
|
||||
builder.WriteString(fence)
|
||||
builder.WriteString(codeInfo(value.Code.Syntax))
|
||||
builder.WriteByte('\n')
|
||||
builder.WriteString(value.Code.Text)
|
||||
if !strings.HasSuffix(value.Code.Text, "\n") {
|
||||
builder.WriteByte('\n')
|
||||
}
|
||||
builder.WriteString(fence)
|
||||
builder.WriteString("\n\n")
|
||||
}
|
||||
|
||||
// codeFenceLength returns a fence longer than the longest backtick run inside
|
||||
// text, so code that itself contains a fence cannot end the block early.
|
||||
func codeFenceLength(text string) int {
|
||||
longest := 0
|
||||
for _, run := range strings.FieldsFunc(text, func(r rune) bool { return r != '`' }) {
|
||||
if len(run) > longest {
|
||||
longest = len(run)
|
||||
}
|
||||
}
|
||||
if longest < 2 {
|
||||
return 3
|
||||
}
|
||||
return longest + 1
|
||||
}
|
||||
|
||||
// codeInfo returns the info string of the fence, or "" when the syntax value
|
||||
// cannot be one: a backtick or a line break would break the fence line, and
|
||||
// dropping it loses nothing because the code text is written verbatim.
|
||||
func codeInfo(syntax string) string {
|
||||
syntax = strings.TrimSpace(syntax)
|
||||
if syntax == "" || strings.ContainsAny(syntax, "`\r\n") {
|
||||
return ""
|
||||
}
|
||||
return syntax
|
||||
}
|
||||
|
||||
// renderAttachmentBlock renders an attachment as one plain line: the payload
|
||||
// holds no download URL, so the renderer names the file instead of fabricating
|
||||
// a link that cannot be resolved. An attachment without a name stays
|
||||
// unmodelled and is reported.
|
||||
func renderAttachmentBlock(
|
||||
builder *strings.Builder,
|
||||
value block,
|
||||
depth int,
|
||||
unknown map[string]struct{},
|
||||
) {
|
||||
name := oneLine(value.Attachment.Name)
|
||||
if name == "" {
|
||||
unknown["attachment"] = struct{}{}
|
||||
renderChildBlocks(builder, value.Children, depth, unknown)
|
||||
return
|
||||
}
|
||||
line := "Attachment: " + escapeText(name)
|
||||
if size := humanSize(value.Attachment.Size); size != "" {
|
||||
line += " (" + size + ")"
|
||||
}
|
||||
writeParagraph(builder, line)
|
||||
}
|
||||
|
||||
// humanSize formats a byte count with one decimal place. A size of zero or
|
||||
// below means the API did not report one, so it is omitted rather than shown
|
||||
// as "0.0 B".
|
||||
func humanSize(size int64) string {
|
||||
if size <= 0 {
|
||||
return ""
|
||||
}
|
||||
const unit = 1024
|
||||
switch {
|
||||
case size < unit:
|
||||
return fmt.Sprintf("%.1f B", float64(size))
|
||||
case size < unit*unit:
|
||||
return fmt.Sprintf("%.1f KB", float64(size)/unit)
|
||||
case size < unit*unit*unit:
|
||||
return fmt.Sprintf("%.1f MB", float64(size)/(unit*unit))
|
||||
default:
|
||||
return fmt.Sprintf("%.1f GB", float64(size)/(unit*unit*unit))
|
||||
}
|
||||
}
|
||||
|
||||
// oneLine collapses a value that is rendered inline so an embedded line break
|
||||
// cannot split the surrounding Markdown construct.
|
||||
func oneLine(value string) string {
|
||||
return strings.TrimSpace(strings.NewReplacer("\r", " ", "\n", " ").Replace(value))
|
||||
}
|
||||
|
||||
func renderTable(builder *strings.Builder, rows [][]string) {
|
||||
columns := 0
|
||||
for _, row := range rows {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,247 @@
|
|||
package dingtalk
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The shapes pinned in this file come from read-only probes of real documents:
|
||||
// a code block carries {"syntax","text","title"} with an optional title, an
|
||||
// attachment carries file metadata but no download URL, and a block the API
|
||||
// could not map carries only {"rawType"}. All fixtures below are synthetic.
|
||||
|
||||
func TestRenderCodeBlockUsesSyntaxAsLanguage(t *testing.T) {
|
||||
result := renderDocument("测试文档", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"code","code":{"syntax":"bash","text":"echo hello"}}`),
|
||||
})
|
||||
|
||||
want := "# 测试文档\n\n```bash\necho hello\n```\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
if len(result.UnknownTypes) != 0 {
|
||||
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderCodeBlockWithoutSyntaxOrTitle(t *testing.T) {
|
||||
result := renderDocument("", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"code","code":{"text":"plain code"}}`),
|
||||
})
|
||||
|
||||
want := "```\nplain code\n```\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
if len(result.UnknownTypes) != 0 {
|
||||
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderCodeBlockWritesTitleAboveTheFence(t *testing.T) {
|
||||
result := renderDocument("", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"code","code":{"syntax":"bash","title":"Example *script*","text":"ls"}}`),
|
||||
})
|
||||
|
||||
want := "**Example \\*script\\***\n\n```bash\nls\n```\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
if len(result.UnknownTypes) != 0 {
|
||||
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
|
||||
}
|
||||
}
|
||||
|
||||
// Code that itself contains a fence must not terminate the block early, so the
|
||||
// fence grows past the longest backtick run in the text. The payload is written
|
||||
// as an interpreted string because a raw one cannot hold the backticks.
|
||||
func TestRenderCodeBlockLengthensFenceAroundEmbeddedFence(t *testing.T) {
|
||||
result := renderDocument("", []json.RawMessage{
|
||||
rawJSON("{\"blockType\":\"code\",\"code\":{\"syntax\":\"markdown\"," +
|
||||
"\"text\":\"before\\n```\\ninner\\n```\\nafter\"}}"),
|
||||
})
|
||||
|
||||
want := "````markdown\nbefore\n```\ninner\n```\nafter\n````\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
if len(result.UnknownTypes) != 0 {
|
||||
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodeFenceLengthOutgrowsEmbeddedBacktickRuns(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
text string
|
||||
want int
|
||||
}{
|
||||
{name: "no backtick", text: "plain", want: 3},
|
||||
{name: "single backtick", text: "a `b` c", want: 3},
|
||||
{name: "two backticks", text: "a ``b`` c", want: 3},
|
||||
{name: "fence inside", text: "a ```b``` c", want: 4},
|
||||
{name: "long run", text: "a `````b````` c", want: 6},
|
||||
{name: "fence only", text: "```", want: 4},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if got := codeFenceLength(test.text); got != test.want {
|
||||
t.Fatalf("codeFenceLength(%q) = %d, want %d", test.text, got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A code block without text has nothing to fence. An empty fence would only be
|
||||
// noise, so the block stays reported as an unmodelled payload; children outside
|
||||
// the documented shape are rendered rather than dropped.
|
||||
func TestRenderCodeBlockWithoutTextIsReportedNotRendered(t *testing.T) {
|
||||
result := renderDocument("", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"code","code":{"syntax":"bash","title":"Example"},` +
|
||||
`"children":[{"blockType":"paragraph","paragraph":{"text":"kept body"}}]}`),
|
||||
})
|
||||
|
||||
if strings.Contains(result.Markdown, "```") || strings.Contains(result.Markdown, "**Example**") {
|
||||
t.Fatalf("empty code block rendered a fragment:\n%s", result.Markdown)
|
||||
}
|
||||
if !strings.Contains(result.Markdown, "kept body") {
|
||||
t.Fatalf("child content lost:\n%s", result.Markdown)
|
||||
}
|
||||
if want := []string{"code"}; !reflect.DeepEqual(result.UnknownTypes, want) {
|
||||
t.Fatalf("UnknownTypes = %#v, want %#v", result.UnknownTypes, want)
|
||||
}
|
||||
}
|
||||
|
||||
// The attachment payload has no download URL, so the renderer only names the
|
||||
// file. Sizes are byte counts with binary units and one decimal place; a size
|
||||
// the API did not report is omitted instead of rendered as "0.0 B".
|
||||
func TestRenderAttachmentFormatsNameAndSize(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
payload string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "half a kilobyte stays in bytes",
|
||||
payload: `{"name":"example.pdf","size":512}`,
|
||||
want: "Attachment: example.pdf (512.0 B)\n",
|
||||
},
|
||||
{
|
||||
name: "just below a kilobyte",
|
||||
payload: `{"name":"example.pdf","size":1023}`,
|
||||
want: "Attachment: example.pdf (1023.0 B)\n",
|
||||
},
|
||||
{
|
||||
name: "kilobyte boundary",
|
||||
payload: `{"name":"example.pdf","size":1024}`,
|
||||
want: "Attachment: example.pdf (1.0 KB)\n",
|
||||
},
|
||||
{
|
||||
name: "kilobytes",
|
||||
payload: `{"name":"example.pdf","size":1229}`,
|
||||
want: "Attachment: example.pdf (1.2 KB)\n",
|
||||
},
|
||||
{
|
||||
name: "megabytes",
|
||||
payload: `{"name":"example.pdf","size":1258291}`,
|
||||
want: "Attachment: example.pdf (1.2 MB)\n",
|
||||
},
|
||||
{
|
||||
name: "gigabytes",
|
||||
payload: `{"name":"example.pdf","size":2147483648}`,
|
||||
want: "Attachment: example.pdf (2.0 GB)\n",
|
||||
},
|
||||
{
|
||||
name: "size omitted",
|
||||
payload: `{"name":"example.pdf"}`,
|
||||
want: "Attachment: example.pdf\n",
|
||||
},
|
||||
{
|
||||
name: "zero size omitted",
|
||||
payload: `{"name":"example.pdf","size":0}`,
|
||||
want: "Attachment: example.pdf\n",
|
||||
},
|
||||
{
|
||||
name: "negative size omitted",
|
||||
payload: `{"name":"example.pdf","size":-1}`,
|
||||
want: "Attachment: example.pdf\n",
|
||||
},
|
||||
{
|
||||
name: "without resource id",
|
||||
payload: `{"name":"example.pdf","size":1024,"type":"pdf","viewType":"preview"}`,
|
||||
want: "Attachment: example.pdf (1.0 KB)\n",
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
result := renderDocument("", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"attachment","attachment":` + test.payload + `}`),
|
||||
})
|
||||
if result.Markdown != test.want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, test.want)
|
||||
}
|
||||
if len(result.UnknownTypes) != 0 {
|
||||
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The name is document content, not a link target, and the opaque resourceId is
|
||||
// never turned into a download URL because the payload has no resolvable one.
|
||||
func TestRenderAttachmentEscapesNameAndBuildsNoLink(t *testing.T) {
|
||||
result := renderDocument("", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"attachment","attachment":{"name":"example_[draft]*.pdf","size":1024,` +
|
||||
`"resourceId":"res-synthetic-1"}}`),
|
||||
})
|
||||
|
||||
want := "Attachment: example\\_\\[draft\\]\\*.pdf (1.0 KB)\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
for _, forbidden := range []string{"](", "http", "res-synthetic-1"} {
|
||||
if strings.Contains(result.Markdown, forbidden) {
|
||||
t.Fatalf("attachment rendered %q:\n%s", forbidden, result.Markdown)
|
||||
}
|
||||
}
|
||||
if len(result.UnknownTypes) != 0 {
|
||||
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderAttachmentWithoutNameIsReportedNotRendered(t *testing.T) {
|
||||
result := renderDocument("", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"attachment","attachment":{"size":1024,"resourceId":"res-synthetic-1"},` +
|
||||
`"children":[{"blockType":"paragraph","paragraph":{"text":"kept body"}}]}`),
|
||||
})
|
||||
|
||||
if strings.Contains(result.Markdown, "Attachment:") {
|
||||
t.Fatalf("nameless attachment rendered a line:\n%s", result.Markdown)
|
||||
}
|
||||
if !strings.Contains(result.Markdown, "kept body") {
|
||||
t.Fatalf("child content lost:\n%s", result.Markdown)
|
||||
}
|
||||
if want := []string{"attachment"}; !reflect.DeepEqual(result.UnknownTypes, want) {
|
||||
t.Fatalf("UnknownTypes = %#v, want %#v", result.UnknownTypes, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A block the API could not map carries no body text, only the real type name.
|
||||
// Keeping that name in the marker is what makes the document metadata and the
|
||||
// sync warning actionable, and children outside the documented shape are still
|
||||
// rendered instead of dropped.
|
||||
func TestRenderUnknownBlockKeepsRawTypeVisible(t *testing.T) {
|
||||
result := renderDocument("", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"unknown","unknown":{"rawType":"card"},` +
|
||||
`"children":[{"blockType":"paragraph","paragraph":{"text":"card body"}}]}`),
|
||||
rawJSON(`{"blockType":"unknown","unknown":{}}`),
|
||||
rawJSON(`{"blockType":"unknown","unknown":{"rawType":" "}}`),
|
||||
})
|
||||
|
||||
if !strings.Contains(result.Markdown, "card body") {
|
||||
t.Fatalf("child content lost:\n%s", result.Markdown)
|
||||
}
|
||||
if want := []string{"unknown", "unknown:card"}; !reflect.DeepEqual(result.UnknownTypes, want) {
|
||||
t.Fatalf("UnknownTypes = %#v, want %#v", result.UnknownTypes, want)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,114 @@
|
|||
package dingtalk
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A list block can carry inline children (the item text) and block children
|
||||
// (one per item) at the same time. Both kinds must survive rendering: an inline
|
||||
// item used to shadow every block item that followed it.
|
||||
func TestRenderListKeepsInlineAndBlockItems(t *testing.T) {
|
||||
result := renderDocument("测试文档", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"unorderedList","unorderedList":{"list":{"level":0}},"children":[` +
|
||||
`{"elementType":"text","text":"第一项"},` +
|
||||
`{"blockType":"paragraph","paragraph":{"text":"第二项整段内容"}}]}`),
|
||||
})
|
||||
|
||||
want := "# 测试文档\n\n- 第一项\n- 第二项整段内容\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
if len(result.UnknownTypes) != 0 {
|
||||
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
|
||||
}
|
||||
}
|
||||
|
||||
// Items delivered as block children must keep one bullet line each instead of
|
||||
// being flattened onto a single line.
|
||||
func TestRenderListEmitsOneBulletPerBlockItem(t *testing.T) {
|
||||
result := renderDocument("测试文档", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"unorderedList","unorderedList":{"list":{"level":0}},"children":[` +
|
||||
`{"blockType":"paragraph","paragraph":{"text":"甲项"}},` +
|
||||
`{"blockType":"paragraph","paragraph":{"text":"乙项"}},` +
|
||||
`{"blockType":"paragraph","paragraph":{"text":"丙项"}}]}`),
|
||||
})
|
||||
|
||||
want := "# 测试文档\n\n- 甲项\n- 乙项\n- 丙项\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Inline and block children keep their payload order, so an inline run that
|
||||
// follows a block item is not hoisted above it or merged into another item.
|
||||
func TestRenderListKeepsItemOrder(t *testing.T) {
|
||||
result := renderDocument("", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"orderedList","orderedList":{"list":{"level":0}},"children":[` +
|
||||
`{"blockType":"paragraph","paragraph":{"text":"块项"}},` +
|
||||
`{"elementType":"text","text":"内联项一"},` +
|
||||
`{"elementType":"text","text":"内联项二"}]}`),
|
||||
})
|
||||
|
||||
want := "1. 块项\n1. 内联项一内联项二\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Nested lists are indented by their own level, and never sit at or above the
|
||||
// parent list even when the payload repeats the parent level.
|
||||
func TestRenderListIndentsNestedLists(t *testing.T) {
|
||||
result := renderDocument("", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"unorderedList","unorderedList":{"list":{"level":0}},"children":[` +
|
||||
`{"elementType":"text","text":"父项"},` +
|
||||
`{"blockType":"unorderedList","unorderedList":{"list":{"level":1}},"children":[` +
|
||||
`{"elementType":"text","text":"子项"}]},` +
|
||||
`{"blockType":"unorderedList","unorderedList":{"list":{"level":0}},"children":[` +
|
||||
`{"elementType":"text","text":"孙项同层级"}]}]}`),
|
||||
})
|
||||
|
||||
want := "- 父项\n - 子项\n - 孙项同层级\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A multi-line item stays inside its bullet: continuation lines are aligned
|
||||
// under the first line rather than escaping to the document root.
|
||||
func TestRenderListIndentsContinuationLines(t *testing.T) {
|
||||
// A document title keeps the leading indentation of the first list from
|
||||
// being trimmed away, matching how these lists appear in real documents.
|
||||
result := renderDocument("测试文档", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"unorderedList","unorderedList":{"list":{"level":1}},"children":[` +
|
||||
`{"blockType":"paragraph","paragraph":{"text":"第一行\n第二行"}}]}`),
|
||||
})
|
||||
|
||||
want := "# 测试文档\n\n - 第一行\n 第二行\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
}
|
||||
|
||||
// The documented list shape is flat: one block per item, nesting carried by
|
||||
// list.level, the items of one list linked by a shared listId across sibling
|
||||
// blocks. This pins that main path — two sibling items at different levels —
|
||||
// so the defensive block-child handling above cannot become the assumed model.
|
||||
func TestRenderListFollowsTheFlatDocumentedShape(t *testing.T) {
|
||||
result := renderDocument("", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"unorderedList","unorderedList":{"list":{"listId":"list-1","level":0}},` +
|
||||
`"children":[{"text":"父项"}]}`),
|
||||
rawJSON(`{"blockType":"unorderedList","unorderedList":{"list":{"listId":"list-1","level":1}},` +
|
||||
`"children":[{"text":"子项"}]}`),
|
||||
rawJSON(`{"blockType":"unorderedList","unorderedList":{"list":{"listId":"list-2","level":0}},` +
|
||||
`"children":[{"text":"另一组的项"}]}`),
|
||||
})
|
||||
|
||||
want := "- 父项\n - 子项\n- 另一组的项\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
if len(result.UnknownTypes) != 0 {
|
||||
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,130 @@
|
|||
package dingtalk
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Fixtures in this file are **live payloads**, copied from
|
||||
// `GET /v1.0/doc/suites/documents/{id}/blocks` against a production tenant and
|
||||
// only shortened where marked. They exist because the list renderer was once
|
||||
// written against a shape the API never returns — `children` — while the real
|
||||
// response carries one item per block with the text in the block's own field.
|
||||
// Nine production documents, every list block: no `children`, no `list.level`,
|
||||
// no `listId`. A fixture invented from the docs cannot catch that; these can.
|
||||
|
||||
// The live shape of an unordered list item: the whole item is `text`, nothing else.
|
||||
func TestRenderListReadsTheLiveFlatShape(t *testing.T) {
|
||||
result := renderDocument("测试文档", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"unorderedList","index":87,"id":"m050v0j3o1iic0pr7xg",` +
|
||||
`"unorderedList":{"text":"确认是否自定义全端口,默认是常见端口"}}`),
|
||||
rawJSON(`{"blockType":"orderedList","index":88,"id":"m050w04e41a0sfbcy1",` +
|
||||
`"orderedList":{"text":"第一步:确认资产范围"}}`),
|
||||
})
|
||||
|
||||
want := "# 测试文档\n\n- 确认是否自定义全端口,默认是常见端口\n1. 第一步:确认资产范围\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
if len(result.UnknownTypes) != 0 {
|
||||
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
|
||||
}
|
||||
}
|
||||
|
||||
// Consecutive live list blocks are consecutive items of one list, and every one
|
||||
// of them must survive. This is the regression that shipped: 190 of 190 list
|
||||
// items were dropped, silently, because the type was "known" and so never
|
||||
// showed up in the unknown-type report either.
|
||||
func TestRenderListKeepsEveryItemOfALiveDocument(t *testing.T) {
|
||||
result := renderDocument("测试文档", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"unorderedList","index":1,"id":"a","unorderedList":{"text":"项目分享(团队版中)"}}`),
|
||||
rawJSON(`{"blockType":"unorderedList","index":2,"id":"b","unorderedList":{"text":"项目报告导出"}}`),
|
||||
rawJSON(`{"blockType":"unorderedList","index":3,"id":"c","unorderedList":{"text":"任务下发"}}`),
|
||||
})
|
||||
|
||||
want := "# 测试文档\n\n- 项目分享(团队版中)\n- 项目报告导出\n- 任务下发\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Multi-line items keep their continuation lines aligned under the first line,
|
||||
// so the value cannot escape its bullet.
|
||||
func TestRenderListKeepsLiveMultiLineItem(t *testing.T) {
|
||||
result := renderDocument("测试文档", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"orderedList","index":4,"id":"d",` +
|
||||
`"orderedList":{"text":"连接到内网探测模块:\n执行所下载的探测Agent"}}`),
|
||||
})
|
||||
|
||||
want := "# 测试文档\n\n1. 连接到内网探测模块:\n 执行所下载的探测Agent\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
}
|
||||
|
||||
// The live `sdt` block is a table of contents and carries the whole thing in
|
||||
// `text`. The type is still unmodelled, so the marker must stay — but dropping
|
||||
// the text because the presentation is unknown loses the document's contents
|
||||
// page. Verified live: 1,212 characters in one block.
|
||||
func TestRenderUnknownBlockRendersItsLiveText(t *testing.T) {
|
||||
result := renderDocument("测试文档", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"unknown","index":19,"id":"lqaap37i2lv2yn7i5w7",` +
|
||||
`"unknown":{"rawType":"sdt","text":"目录目录1前言11. 产品介绍1"}}`),
|
||||
})
|
||||
|
||||
want := "# 测试文档\n\n目录目录1前言11. 产品介绍1\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
if len(result.UnknownTypes) != 1 || result.UnknownTypes[0] != "unknown:sdt" {
|
||||
t.Fatalf("UnknownTypes = %#v, want [unknown:sdt]", result.UnknownTypes)
|
||||
}
|
||||
}
|
||||
|
||||
// Not every unmodelled block has text: the live `card` and `sectionBr` blocks
|
||||
// carry only `rawType`, so they stay a marker and render nothing.
|
||||
func TestRenderUnknownBlockWithoutTextStaysAMarker(t *testing.T) {
|
||||
result := renderDocument("测试文档", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"unknown","index":21,"id":"mulaiyzgurq2s6o7b2f",` +
|
||||
`"unknown":{"rawType":"sectionBr"}}`),
|
||||
})
|
||||
|
||||
want := "# 测试文档\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
if len(result.UnknownTypes) != 1 || result.UnknownTypes[0] != "unknown:sectionBr" {
|
||||
t.Fatalf("UnknownTypes = %#v, want [unknown:sectionBr]", result.UnknownTypes)
|
||||
}
|
||||
}
|
||||
|
||||
// A block carrying both its own text and inline children is a shape the API does
|
||||
// not produce. Emitting both would duplicate the item, so the shape is reported
|
||||
// instead of guessed at.
|
||||
func TestRenderListFlagsOwnTextAndInlineChildrenTogether(t *testing.T) {
|
||||
result := renderDocument("测试文档", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"unorderedList","unorderedList":{"text":"甲"},` +
|
||||
`"children":[{"elementType":"text","text":"甲"}]}`),
|
||||
})
|
||||
|
||||
want := "# 测试文档\n\n- 甲\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
if len(result.UnknownTypes) != 1 || result.UnknownTypes[0] != "list_text_and_inline_children" {
|
||||
t.Fatalf("UnknownTypes = %#v, want [list_text_and_inline_children]", result.UnknownTypes)
|
||||
}
|
||||
}
|
||||
|
||||
// Escaping still applies to the block's own text, so an item that starts with a
|
||||
// marker character cannot turn into a nested list or a heading.
|
||||
func TestRenderListEscapesLiveOwnText(t *testing.T) {
|
||||
result := renderDocument("测试文档", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"unorderedList","unorderedList":{"text":"- 不是子列表"}}`),
|
||||
})
|
||||
|
||||
want := "# 测试文档\n\n- \\- 不是子列表\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
}
|
||||
|
|
@ -128,3 +128,75 @@ func TestRenderDocumentAcceptsOfficialBlockVariants(t *testing.T) {
|
|||
t.Fatalf("UnknownTypes = %#v", result.UnknownTypes)
|
||||
}
|
||||
}
|
||||
|
||||
// A block whose type is modelled but whose payload carries nothing renderable
|
||||
// (a code block without text, an attachment without a name) must still be
|
||||
// collected, so the loss stays visible instead of turning into an empty
|
||||
// fragment of Markdown.
|
||||
func TestRenderDocumentCollectsUnknownBlockTypes(t *testing.T) {
|
||||
result := renderDocument("测试文档", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"code","code":{"syntax":"bash"}}`),
|
||||
rawJSON(`{"blockType":"attachment","attachment":{"resourceId":"res-synthetic-1"}}`),
|
||||
rawJSON(`{"blockType":"paragraph","paragraph":{"text":"正文仍然保留"}}`),
|
||||
})
|
||||
|
||||
if !strings.Contains(result.Markdown, "正文仍然保留") {
|
||||
t.Fatalf("known content lost:\n%s", result.Markdown)
|
||||
}
|
||||
if strings.Contains(result.Markdown, "```") || strings.Contains(result.Markdown, "Attachment:") {
|
||||
t.Fatalf("empty payload rendered a fragment:\n%s", result.Markdown)
|
||||
}
|
||||
if want := []string{"attachment", "code"}; !reflect.DeepEqual(result.UnknownTypes, want) {
|
||||
t.Fatalf("UnknownTypes = %#v, want %#v", result.UnknownTypes, want)
|
||||
}
|
||||
}
|
||||
|
||||
// The list fix must not change how ordinary documents render: paragraphs,
|
||||
// headings, styles, blockquotes, tables and inline-only lists keep their exact
|
||||
// Markdown output.
|
||||
func TestRenderDocumentKeepsOrdinaryBlocksStable(t *testing.T) {
|
||||
result := renderDocument("标题 Doc", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"heading","heading":{"level":2,"text":"Overview"}}`),
|
||||
rawJSON(`{"blockType":"paragraph","children":[` +
|
||||
`{"elementType":"text","text":"bold","bold":true},` +
|
||||
`{"elementType":"text","text":" and plain"}]}`),
|
||||
rawJSON(`{"blockType":"blockquote","blockquote":{"text":"first\nsecond"}}`),
|
||||
rawJSON(`{"blockType":"table","table":{"cells":[["A","B"],["1","x|y"]]}}`),
|
||||
rawJSON(`{"blockType":"orderedList","orderedList":{"list":{"level":1}},` +
|
||||
`"children":[{"elementType":"text","text":"nested"}]}`),
|
||||
rawJSON(`{"blockType":"paragraph","paragraph":{"text":"tail"}}`),
|
||||
})
|
||||
|
||||
want := "# 标题 Doc\n\n" +
|
||||
"## Overview\n\n" +
|
||||
"**bold** and plain\n\n" +
|
||||
"> first\n> second\n\n" +
|
||||
"| A | B |\n| --- | --- |\n| 1 | x\\|y |\n\n" +
|
||||
" 1. nested\n" +
|
||||
"tail\n"
|
||||
if result.Markdown != want {
|
||||
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
|
||||
}
|
||||
if len(result.UnknownTypes) != 0 {
|
||||
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
|
||||
}
|
||||
}
|
||||
|
||||
// Inline element types the renderer does not model may carry their text in
|
||||
// children rather than in a text field (slot is documented that way), and those
|
||||
// runs used to disappear: the default branch wrote an empty text and stopped.
|
||||
func TestRenderDocumentKeepsTextOfUnmodelledInlineElements(t *testing.T) {
|
||||
result := renderDocument("测试文档", []json.RawMessage{
|
||||
rawJSON(`{"blockType":"paragraph","children":[` +
|
||||
`{"elementType":"text","text":"由 "},` +
|
||||
`{"elementType":"slot","children":[{"elementType":"text","text":"张三"}]},` +
|
||||
`{"elementType":"text","text":" 负责"}]}`),
|
||||
})
|
||||
|
||||
if !strings.Contains(result.Markdown, "由 张三 负责") {
|
||||
t.Fatalf("inline run lost its unmodelled element:\n%s", result.Markdown)
|
||||
}
|
||||
if want := []string{"inline_slot"}; !reflect.DeepEqual(result.UnknownTypes, want) {
|
||||
t.Fatalf("UnknownTypes = %#v, want %#v", result.UnknownTypes, want)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue