diff --git a/internal/datasource/connector/dingtalk/connector.go b/internal/datasource/connector/dingtalk/connector.go index 798f5fd5..bd0fed8e 100644 --- a/internal/datasource/connector/dingtalk/connector.go +++ b/internal/datasource/connector/dingtalk/connector.go @@ -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, diff --git a/internal/datasource/connector/dingtalk/connector_unknown_blocks_test.go b/internal/datasource/connector/dingtalk/connector_unknown_blocks_test.go new file mode 100644 index 00000000..7345ea53 --- /dev/null +++ b/internal/datasource/connector/dingtalk/connector_unknown_blocks_test.go @@ -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()) + } +} diff --git a/internal/datasource/connector/dingtalk/markdown.go b/internal/datasource/connector/dingtalk/markdown.go index 5eabe61c..cdf36dae 100644 --- a/internal/datasource/connector/dingtalk/markdown.go +++ b/internal/datasource/connector/dingtalk/markdown.go @@ -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 { diff --git a/internal/datasource/connector/dingtalk/markdown_blocks_test.go b/internal/datasource/connector/dingtalk/markdown_blocks_test.go new file mode 100644 index 00000000..416f68c2 --- /dev/null +++ b/internal/datasource/connector/dingtalk/markdown_blocks_test.go @@ -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) + } +} diff --git a/internal/datasource/connector/dingtalk/markdown_lists_test.go b/internal/datasource/connector/dingtalk/markdown_lists_test.go new file mode 100644 index 00000000..2186d2ad --- /dev/null +++ b/internal/datasource/connector/dingtalk/markdown_lists_test.go @@ -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) + } +} diff --git a/internal/datasource/connector/dingtalk/markdown_live_shape_test.go b/internal/datasource/connector/dingtalk/markdown_live_shape_test.go new file mode 100644 index 00000000..493ca085 --- /dev/null +++ b/internal/datasource/connector/dingtalk/markdown_live_shape_test.go @@ -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) + } +} diff --git a/internal/datasource/connector/dingtalk/markdown_test.go b/internal/datasource/connector/dingtalk/markdown_test.go index d90a7521..628160d7 100644 --- a/internal/datasource/connector/dingtalk/markdown_test.go +++ b/internal/datasource/connector/dingtalk/markdown_test.go @@ -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) + } +}