Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(datasource/yuque): preserve TOC folder hierarchy for synced documents (#3476)

niannian4364e61afa4b
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 681150b9f..edb99262e 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -7018,6 +7018,12 @@ export default {
prereqStep3Brief_lark_drive: 'Configure app permissions',
prereqStep3Desc_lark_drive: 'Enable drive:drive:readonly, drive:export:readonly, docx:document:readonly permissions',
prereqOpenConsole_yuque: 'Open Yuque Token settings',
+ yuqueFolderModeLabel: 'Folder structure',
+ yuqueFolderModeToc: 'Mirror the Yuque TOC',
+ yuqueFolderModeNone: 'Keep everything flat',
+ yuqueFolderModeHint: 'Files documents by their Yuque table-of-contents path. Note: folder moves made in the knowledge base afterwards are overwritten by the Yuque structure the next time that document syncs.',
+ yuqueTOCOnly: 'Sync only documents visible in the Yuque TOC',
+ yuqueTOCOnlyHint: 'Requires the "Mirror the Yuque TOC" layout. Documents already in the knowledge base are untouched — one the Yuque TOC does not list is simply no longer added, never deleted.',
prereqBarText_dingtalk: 'First time? Click to see the DingTalk app setup guide',
prereqStep1Brief_dingtalk: 'Create an internal enterprise app',
prereqStep1Desc_dingtalk: 'Create an internal app in DingTalk Open Platform and copy its Client ID and Client Secret.',
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index 308b3c0f7..19d84e93a 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -7018,6 +7018,12 @@ export default {
prereqStep3Brief_lark_drive: 'アプリの権限を設定',
prereqStep3Desc_lark_drive: 'drive:drive:readonly、drive:export:readonly、docx:document:readonlyの権限を有効にします',
prereqOpenConsole_yuque: 'Yuqueのトークン設定を開く',
+ yuqueFolderModeLabel: 'フォルダ構成',
+ yuqueFolderModeToc: 'Yuqueの目次どおりに階層化',
+ yuqueFolderModeNone: 'ルートに平置き',
+ yuqueFolderModeHint: 'Yuqueの目次階層に従って文書を配置します。なお、その後ナレッジベース上で手動で移動したフォルダは、次回その文書を同期したときにYuqueの構成へ上書きされます。',
+ yuqueTOCOnly: 'Yuqueの目次に表示される文書だけ同期',
+ yuqueTOCOnlyHint: '「Yuqueの目次どおりに階層化」を選ぶと有効になります。すでにナレッジベースにある文書はそのまま残り、Yuqueの目次にない文書は新たに追加されなくなるだけで、削除はされません。',
prereqBarText_dingtalk: '初めての利用ですか?DingTalkアプリの設定ガイドを確認',
prereqStep1Brief_dingtalk: '企業内部アプリを作成',
prereqStep1Desc_dingtalk: 'DingTalk開発者プラットフォームで企業内部アプリを作成し、Client IDとClient Secretを取得します。',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 9bba3b96a..62dde99c3 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -1053,6 +1053,12 @@ export default {
prereqStep3Brief_lark_drive: "앱 권한 구성",
prereqStep3Desc_lark_drive: "drive:drive:readonly, drive:export:readonly, docx:document:readonly 권한 활성화",
prereqOpenConsole_yuque: 'Yuque Token 설정으로 이동',
+ yuqueFolderModeLabel: '폴더 구조',
+ yuqueFolderModeToc: 'Yuque 목차대로 계층 구성',
+ yuqueFolderModeNone: '루트에 평면 배치',
+ yuqueFolderModeHint: 'Yuque 목차 계층에 따라 문서를 배치합니다. 참고: 이후 지식베이스에서 직접 옮긴 폴더는 해당 문서가 다음에 동기화될 때 Yuque 구조로 덮어써집니다.',
+ yuqueTOCOnly: 'Yuque 목차에 표시되는 문서만 동기화',
+ yuqueTOCOnlyHint: '"Yuque 목차대로 계층 구성"을 선택해야 동작합니다. 이미 지식베이스에 있는 문서는 그대로 유지되며, Yuque 목차에 없는 문서는 새로 추가되지 않을 뿐 삭제되지 않습니다.',
prereqBarText_dingtalk: '처음 사용하시나요? 클릭하여 DingTalk 앱 설정 가이드를 확인하세요',
prereqStep1Brief_dingtalk: '기업 내부 앱 생성',
prereqStep1Desc_dingtalk: 'DingTalk Open Platform에서 기업 내부 앱을 생성하고 Client ID와 Client Secret을 복사하세요.',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index d5b8fb166..ebce12dd0 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -1029,6 +1029,12 @@ export default {
prereqStep3Brief_yuque: '(Опционально) Для Enterprise укажите Base URL',
prereqStep3Desc_yuque: 'Пользователям публичного облака указывать не нужно. Для Yuque Enterprise или приватного развёртывания укажите корпоративный домен',
prereqOpenConsole_yuque: 'Перейти к настройкам Yuque Token',
+ yuqueFolderModeLabel: 'Структура папок',
+ yuqueFolderModeToc: 'Как в оглавлении Yuque',
+ yuqueFolderModeNone: 'Всё в корне',
+ yuqueFolderModeHint: 'Раскладывает документы по папкам согласно оглавлению Yuque. Обратите внимание: папки, перемещённые вручную в базе знаний, будут перезаписаны структурой Yuque при следующей синхронизации этого документа.',
+ yuqueTOCOnly: 'Синхронизировать только видимые в оглавлении Yuque документы',
+ yuqueTOCOnlyHint: 'Требуется режим «Как в оглавлении Yuque». Документы, уже добавленные в базу знаний, остаются нетронутыми — документ, которого нет в оглавлении Yuque, просто перестаёт добавляться, но не удаляется.',
prereqBarText_dingtalk: 'Используете впервые? Откройте руководство по настройке приложения DingTalk',
prereqStep1Brief_dingtalk: 'Создайте внутреннее корпоративное приложение',
prereqStep1Desc_dingtalk: 'Создайте внутреннее приложение в DingTalk Open Platform и скопируйте Client ID и Client Secret.',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 5497981a0..f8301a076 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -1031,6 +1031,12 @@ export default {
prereqStep3Brief_yuque: '(可选)企业版填写 Base URL',
prereqStep3Desc_yuque: '公有云用户无需填写;语雀企业版或私有部署请填写企业域名',
prereqOpenConsole_yuque: '前往语雀 Token 设置',
+ yuqueFolderModeLabel: '目录结构',
+ yuqueFolderModeToc: '按语雀目录分层',
+ yuqueFolderModeNone: '平铺在根目录',
+ yuqueFolderModeHint: '按语雀的目录层级放置文档。注意:之后在知识库里手动调整的目录,会在该文档下次同步时被覆盖回语雀的结构。',
+ yuqueTOCOnly: '只同步语雀目录中可见的文档',
+ yuqueTOCOnlyHint: '需要先选择「按语雀目录分层」。已经同步进知识库的文档不受影响——语雀中不在目录里的文档只是不再新增,不会被删除。',
prereqBarText_dingtalk: '首次使用?点击查看钉钉应用配置指引',
prereqStep1Brief_dingtalk: '创建企业内部应用',
prereqStep1Desc_dingtalk: '在钉钉开放平台创建企业内部应用,并获取 Client ID 和 Client Secret',
diff --git a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.ts b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.ts
index f9f2d1267..e6002c92d 100644
--- a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.ts
+++ b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.ts
@@ -18,7 +18,17 @@ const compiled = ts.transpileModule(script, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText
-async function fixture({ configured = true, create = false } = {}) {
+async function fixture({
+ configured = true,
+ create = false,
+ type = 'gitlab',
+ settings = { projects: [{ project_id: '123', paths: [] }] },
+}: {
+ configured?: boolean
+ create?: boolean
+ type?: string
+ settings?: Record<string, unknown>
+} = {}) {
const calls: Array<{ method: string; args: any[] }> = []
let storedToken = configured ? 'expired-token' : ''
const api = {
@@ -42,9 +52,9 @@ async function fixture({ configured = true, create = false } = {}) {
const props = reactive({
visible: false, kbId: 'kb-one',
dataSource: create ? null : {
- id: 'source-one', name: 'GitLab', type: 'gitlab',
+ id: 'source-one', name: 'GitLab', type,
credentials: { credentials: { configured } },
- config: { resource_ids: [], settings: { projects: [{ project_id: '123', paths: [] }] } },
+ config: { resource_ids: [], settings },
sync_schedule: '0 0 */6 * * *', sync_mode: 'incremental',
conflict_strategy: 'overwrite', sync_deletions: true,
},
@@ -158,6 +168,44 @@ test('new GitLab data sources continue to test credentials without persistence',
} finally { f.close() }
})
+test('a new Yuque data source adopts the TOC folder layout, but not the filter', async () => {
+ const f = await fixture({ create: true })
+ try {
+ assert.equal(f.vm.form.config.settings.folder_mode, undefined)
+ f.vm.selectType(f.vm.connectorDefs.find((def: any) => def.type === 'yuque'))
+ assert.equal(f.vm.form.config.settings.folder_mode, 'toc')
+ // The layout is a presentation choice; toc_only decides what may enter the
+ // knowledge base, so a new source is deliberately left without it.
+ assert.equal(f.vm.form.config.settings.toc_only, undefined)
+ assert.equal(f.vm.yuqueTOCOnly, false)
+ } finally { f.close() }
+})
+
+test('an existing Yuque data source reports its admission filter', async () => {
+ const f = await fixture({ type: 'yuque', settings: { folder_mode: 'toc', toc_only: true } })
+ try {
+ assert.equal(f.vm.yuqueTOCOnly, true)
+ } finally { f.close() }
+})
+
+test('an existing Yuque data source is never switched to the TOC layout', async () => {
+ const f = await fixture({ type: 'yuque', settings: {} })
+ try {
+ // Opening a source created before this control existed must not inject
+ // folder_mode: the connector default (flat) has to stand, otherwise editing
+ // an unrelated field would silently re-file the whole knowledge base.
+ assert.equal(f.vm.form.config.settings.folder_mode, undefined)
+ assert.equal(f.vm.yuqueFolderMode, 'none')
+ } finally { f.close() }
+})
+
+test('an existing Yuque data source on the TOC layout reports it', async () => {
+ const f = await fixture({ type: 'yuque', settings: { folder_mode: 'toc' } })
+ try {
+ assert.equal(f.vm.yuqueFolderMode, 'toc')
+ } finally { f.close() }
+})
+
test('Cloud hierarchy limitation stays visible after an empty space expansion', async () => {
const f = await fixture()
try {
diff --git a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue
index cb60d2bb6..27249eaad 100644
--- a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue
+++ b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue
@@ -205,6 +205,28 @@ const form = ref({
sync_deletions: true,
})
+// Yuque folder layout. The key lives in the raw settings bag, and a data source
+// created before this control existed carries no folder_mode at all — the
+// getter therefore reports the connector's own default (flat) rather than
+// rendering the select blank. Writing back is a no-op until the user picks
+// something, so opening an existing source can never change its behaviour.
+const yuqueFolderMode = computed({
+ get: () => (form.value.config.settings?.folder_mode === 'toc' ? 'toc' : 'none'),
+ set: (mode: string) => {
+ form.value.config.settings = { ...form.value.config.settings, folder_mode: mode }
+ },
+})
+
+// toc_only is an admission filter, and the connector only reads the table of
+// contents when folder_mode is 'toc' — under the flat layout the flag has no
+// effect at all, which is why the control is disabled there.
+const yuqueTOCOnly = computed({
+ get: () => form.value.config.settings?.toc_only === true,
+ set: (on: boolean) => {
+ form.value.config.settings = { ...form.value.config.settings, toc_only: on }
+ },
+})
+
// Step 2: Resources
const resources = ref<Resource[]>([])
const loadingResources = ref(false)
@@ -854,6 +876,12 @@ function selectType(def: ConnectorDef) {
if (def.type === 'confluence') {
form.value.config.settings = { ...form.value.config.settings, edition: 'server' }
}
+ // A new Yuque source opts into the book's folder hierarchy. Only on create:
+ // an existing source keeps what it was built with, so the "folder layout is
+ // owned by the connector" caveat never applies to sources that predate it.
+ if (def.type === 'yuque' && !isEdit.value) {
+ form.value.config.settings = { ...form.value.config.settings, folder_mode: 'toc' }
+ }
if (isGitLabConnector(def.type)) addGitLabProject()
rssAuthHeaders.value = []
step.value = 1
@@ -1921,6 +1949,47 @@ const drawerConfirmText = computed(() => {
<t-checkbox v-model="form.sync_deletions">{{ t('datasource.syncDeletions') }}</t-checkbox>
</div>
</section>
+
+ <!-- Yuque only: how synced documents are laid out, and what may be admitted. -->
+ <section v-if="form.type === 'yuque'" class="setting-drawer__section">
+ <h4 class="setting-drawer__section-title">{{ t('datasource.yuqueFolderModeLabel') }}</h4>
+ <div class="form-item form-item--flat">
+ <div
+ class="option-group"
+ role="radiogroup"
+ :aria-label="t('datasource.yuqueFolderModeLabel')"
+ >
+ <button
+ type="button"
+ class="option-pill"
+ :class="{ 'is-active': yuqueFolderMode === 'toc' }"
+ role="radio"
+ :aria-checked="yuqueFolderMode === 'toc'"
+ @click="yuqueFolderMode = 'toc'"
+ >
+ {{ t('datasource.yuqueFolderModeToc') }}
+ </button>
+ <button
+ type="button"
+ class="option-pill"
+ :class="{ 'is-active': yuqueFolderMode === 'none' }"
+ role="radio"
+ :aria-checked="yuqueFolderMode === 'none'"
+ @click="yuqueFolderMode = 'none'"
+ >
+ {{ t('datasource.yuqueFolderModeNone') }}
+ </button>
+ </div>
+ </div>
+ <p class="form-desc">{{ t('datasource.yuqueFolderModeHint') }}</p>
+
+ <div class="form-item form-item--flat">
+ <t-checkbox v-model="yuqueTOCOnly" :disabled="yuqueFolderMode !== 'toc'">
+ {{ t('datasource.yuqueTOCOnly') }}
+ </t-checkbox>
+ </div>
+ <p class="form-desc">{{ t('datasource.yuqueTOCOnlyHint') }}</p>
+ </section>
</template>
</SettingDrawer>
</template>
diff --git a/internal/datasource/connector/yuque/client.go b/internal/datasource/connector/yuque/client.go
index 7de251ef7..e7a9cab79 100644
--- a/internal/datasource/connector/yuque/client.go
+++ b/internal/datasource/connector/yuque/client.go
@@ -294,3 +294,17 @@ func (c *client) GetDocDetail(ctx context.Context, docID int64) (v2DocDetail, er
}
return resp.Data, nil
}
+
+// ListBookTOC fetches the table of contents of a book.
+//
+// The endpoint returns the whole tree in a single flat list (no pagination), so
+// this costs exactly one request per book per sync. Callers fold the result into
+// per-document folder paths with buildTOCPaths.
+func (c *client) ListBookTOC(ctx context.Context, bookID int64) ([]v2TOCNode, error) {
+ path := fmt.Sprintf("/api/v2/repos/%d/toc", bookID)
+ var resp v2TOCResponse
+ if err := c.doRequest(ctx, http.MethodGet, path, &resp); err != nil {
+ return nil, err
+ }
+ return resp.Data, nil
+}
diff --git a/internal/datasource/connector/yuque/connector.go b/internal/datasource/connector/yuque/connector.go
index 485eef13b..b33130d87 100644
--- a/internal/datasource/connector/yuque/connector.go
+++ b/internal/datasource/connector/yuque/connector.go
@@ -6,6 +6,7 @@ import (
"fmt"
"sort"
"strconv"
+ "strings"
"time"
"github.com/Tencent/WeKnora/internal/datasource"
@@ -159,6 +160,11 @@ func (c *Connector) walk(
return nil, nil, err
}
cli := newClient(cfg)
+ settings := parseFolderSettings(ctx, config)
+ if settings.FolderMode != folderModeNone {
+ logger.Infof(ctx, "[Yuque] folder path derivation enabled: folder_mode=%s toc_only=%t",
+ settings.FolderMode, settings.TOCOnly)
+ }
newCursor := &yuqueCursor{LastSyncTime: time.Now(), BookDocTimes: make(map[string]map[string]string)}
var out []types.FetchedItem
@@ -174,11 +180,34 @@ func (c *Connector) walk(
return nil, nil, fmt.Errorf("list docs for book %d: %w", bookID, err)
}
+ // Optionally fetch the book's table of contents and fold it into a
+ // per-document folder path. One request per book per sync.
+ //
+ // tocOK separates "the TOC was fetched and this document is not in it"
+ // from "we could not fetch the TOC at all". Both the path assembly and
+ // the toc_only filter depend on that distinction: with no TOC we must
+ // degrade to the previous flat behaviour rather than silently dropping
+ // every document.
+ var tocSegs map[int64][]string
+ var inTOC map[int64]bool
+ tocOK := false
+ if settings.FolderMode == folderModeTOC {
+ toc, tocErr := cli.ListBookTOC(ctx, bookID)
+ if tocErr != nil {
+ logger.Warnf(ctx, "[Yuque] book %d: fetch TOC failed, falling back to flat file names: %v",
+ bookID, tocErr)
+ } else {
+ tocSegs, inTOC = buildTOCPaths(toc)
+ tocOK = true
+ }
+ }
+ bookName := ""
+
currentDocs := make(map[string]bool)
newCursor.BookDocTimes[bookIDStr] = make(map[string]string)
- var skippedType, skippedDraft, kept int
- var sampleSkipType, sampleSkipDraft string
+ var skippedType, skippedDraft, skippedNotInTOC, kept int
+ var sampleSkipType, sampleSkipDraft, sampleSkipNotInTOC string
for _, d := range docs {
// Empty type/status is treated as acceptable — forward-compat with
// API variations that omit the field.
@@ -196,9 +225,32 @@ func (c *Connector) walk(
}
continue
}
- kept++
+ // Mark the document as seen so the deletion detector does not treat a
+ // filtered document as removed from the source. toc_only is an
+ // admission filter: it decides what enters the knowledge base, not what
+ // leaves it. Reporting these as deleted would remove exactly the
+ // documents the Yuque web UI cannot show (created through the API,
+ // never attached to the TOC), leaving their content unreachable from
+ // both sides.
docIDStr := strconv.FormatInt(d.ID, 10)
currentDocs[docIDStr] = true
+
+ // Filter out documents that do not appear in the TOC. Applies only when
+ // the TOC was actually fetched — see the tocOK comment above. The
+ // predicate is membership in the TOC node list, not "has a path":
+ // a document may sit in the TOC with no enclosing group.
+ if settings.TOCOnly && tocOK && !inTOC[d.ID] {
+ skippedNotInTOC++
+ if sampleSkipNotInTOC == "" {
+ sampleSkipNotInTOC = fmt.Sprintf("id=%d title=%q", d.ID, d.Title)
+ }
+ continue
+ }
+ kept++
+ // Only admitted documents enter the cursor. A filtered document has to
+ // stay unknown to the incremental comparison, so that admitting it
+ // later — by attaching it to the TOC, or by switching toc_only off —
+ // ingests it rather than dismissing it as unchanged.
newCursor.BookDocTimes[bookIDStr][docIDStr] = d.ContentUpdatedAt
// Incremental: skip if content hasn't changed.
@@ -257,12 +309,27 @@ func (c *Connector) walk(
continue
}
+ // Book title for the leading path segment. The detail response
+ // already carries it, so this costs no extra API call. Captured
+ // once per book; falls back to the namespace, then to no prefix.
+ if bookName == "" {
+ bookName = strings.TrimSpace(detail.Book.Name)
+ if bookName == "" {
+ bookName = strings.TrimSpace(detail.Book.Namespace)
+ }
+ }
+
+ // folder_path is derived downstream from FileName alone
+ // (SplitKnowledgeRelativePath → NormalizeKnowledgeFolderPath), so the
+ // hierarchy has to be encoded here as a relative path.
+ fileName := buildFolderFileName(settings, tocOK, bookName, tocSegs[d.ID], d.Title)
+
out = append(out, types.FetchedItem{
ExternalID: docIDStr,
Title: d.Title,
Content: []byte(detail.Body),
ContentType: "text/markdown",
- FileName: datasource.SanitizeFileName(d.Title) + ".md",
+ FileName: fileName,
URL: buildDocURL(cfg.GetBaseURL(), detail.Book.Namespace, d.Slug),
UpdatedAt: parseContentUpdatedAt(d.ContentUpdatedAt),
SourceResourceID: bookIDStr,
@@ -277,8 +344,11 @@ func (c *Connector) walk(
})
}
- logger.Infof(ctx, "[Yuque] book %d: total=%d kept=%d skipped_non_doc=%d skipped_draft=%d non_doc_sample={%s} draft_sample={%s}",
- bookID, len(docs), kept, skippedType, skippedDraft, sampleSkipType, sampleSkipDraft)
+ logger.Infof(ctx, "[Yuque] book %d: total=%d kept=%d skipped_non_doc=%d skipped_draft=%d "+
+ "skipped_not_in_toc=%d toc_loaded=%t non_doc_sample={%s} draft_sample={%s} "+
+ "not_in_toc_sample={%s}",
+ bookID, len(docs), kept, skippedType, skippedDraft, skippedNotInTOC, tocOK,
+ sampleSkipType, sampleSkipDraft, sampleSkipNotInTOC)
// Deletion detection (incremental only): previous doc IDs not in current → IsDeleted=true
if incremental && prev != nil && prev.BookDocTimes != nil {
diff --git a/internal/datasource/connector/yuque/toc_test.go b/internal/datasource/connector/yuque/toc_test.go
new file mode 100644
index 000000000..ab9d8f7c5
--- /dev/null
+++ b/internal/datasource/connector/yuque/toc_test.go
@@ -0,0 +1,676 @@
+package yuque
+
+import (
+ "context"
+ "encoding/json"
+ "strconv"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/datasource"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// --- helpers ---
+
+func makeDSConfigWithSettings(
+ f *fakeYuque, resourceIDs []string, settings map[string]interface{},
+) *types.DataSourceConfig {
+ cfg := makeDSConfig(f, resourceIDs)
+ cfg.Settings = settings
+ return cfg
+}
+
+func tocTitle(uuid, parent, title string) v2TOCNode {
+ return v2TOCNode{UUID: uuid, Type: tocNodeTypeTitle, Title: title, ParentUUID: parent}
+}
+
+func tocDoc(uuid, parent string, docID int64, title string) v2TOCNode {
+ return v2TOCNode{
+ UUID: uuid, Type: tocNodeTypeDoc, Title: title,
+ ParentUUID: parent, DocID: flexibleDocID(docID),
+ }
+}
+
+// --- buildTOCPaths ---
+
+func TestBuildTOCPaths_EmptyAndTitleOnly(t *testing.T) {
+ for name, nodes := range map[string][]v2TOCNode{
+ "nil": nil,
+ "empty": {},
+ "title-only": {tocTitle("t1", "", "Group"), tocTitle("t2", "t1", "Nested")},
+ } {
+ segs, inTOC := buildTOCPaths(nodes)
+ if len(segs) != 0 || len(inTOC) != 0 {
+ t.Errorf("%s: want empty maps, got segs=%v inTOC=%v", name, segs, inTOC)
+ }
+ }
+}
+
+func TestBuildTOCPaths_SingleLevel(t *testing.T) {
+ segs, inTOC := buildTOCPaths([]v2TOCNode{
+ tocTitle("t1", "", "Group"),
+ tocDoc("d1", "t1", 101, "Doc"),
+ })
+ if !inTOC[101] {
+ t.Fatal("inTOC[101] should be true")
+ }
+ if got := segs[101]; len(got) != 1 || got[0] != "Group" {
+ t.Errorf("segs[101] = %v, want [Group]", got)
+ }
+}
+
+func TestBuildTOCPaths_MultiLevel(t *testing.T) {
+ segs, _ := buildTOCPaths([]v2TOCNode{
+ tocTitle("t1", "", "A"),
+ tocTitle("t2", "t1", "B"),
+ tocDoc("d1", "t2", 101, "Doc"),
+ })
+ got := segs[101]
+ if len(got) != 2 || got[0] != "A" || got[1] != "B" {
+ t.Errorf("segs[101] = %v, want [A B] (root first)", got)
+ }
+}
+
+// A DOC nested under another DOC contributes the parent document's title as an
+// extra path segment.
+func TestBuildTOCPaths_DocNestedUnderDoc(t *testing.T) {
+ segs, _ := buildTOCPaths([]v2TOCNode{
+ tocTitle("t1", "", "A"),
+ tocDoc("d1", "t1", 101, "Parent doc"),
+ tocDoc("d2", "d1", 102, "Child doc"),
+ })
+ got := segs[102]
+ if len(got) != 2 || got[0] != "A" || got[1] != "Parent doc" {
+ t.Errorf("segs[102] = %v, want [A Parent doc]", got)
+ }
+}
+
+// A document that appears in the TOC without any enclosing group is still "in
+// the TOC" — the distinction that keeps toc_only from dropping it.
+func TestBuildTOCPaths_InTOCWithoutGroup(t *testing.T) {
+ segs, inTOC := buildTOCPaths([]v2TOCNode{
+ tocDoc("d1", "", 101, "Loose doc"),
+ })
+ if !inTOC[101] {
+ t.Error("inTOC[101] should be true: the doc is in the TOC node list")
+ }
+ if _, ok := segs[101]; ok {
+ t.Errorf("segs[101] should be absent for a group-less doc, got %v", segs[101])
+ }
+}
+
+func TestBuildTOCPaths_DanglingParent(t *testing.T) {
+ segs, inTOC := buildTOCPaths([]v2TOCNode{
+ tocDoc("d1", "does-not-exist", 101, "Doc"),
+ })
+ if !inTOC[101] {
+ t.Error("inTOC[101] should be true")
+ }
+ if _, ok := segs[101]; ok {
+ t.Errorf("segs[101] should be absent, got %v", segs[101])
+ }
+}
+
+// A cyclic parent_uuid chain must terminate rather than loop forever.
+func TestBuildTOCPaths_CycleTerminates(t *testing.T) {
+ segs, inTOC := buildTOCPaths([]v2TOCNode{
+ tocTitle("a", "b", "A"),
+ tocTitle("b", "a", "B"),
+ tocDoc("d", "a", 101, "Doc"),
+ })
+ if !inTOC[101] {
+ t.Error("inTOC[101] should be true")
+ }
+ // Two titles before the cycle is detected; the exact length matters less
+ // than the fact that this returns at all.
+ if got := len(segs[101]); got != 2 {
+ t.Errorf("len(segs[101]) = %d, want 2 (walk must stop at the cycle)", got)
+ }
+}
+
+// A "/" in a group title must not become an extra nesting level: segments are
+// sanitised individually, before they are ever joined.
+func TestBuildTOCPaths_SanitizesEachSegment(t *testing.T) {
+ segs, _ := buildTOCPaths([]v2TOCNode{
+ tocTitle("t1", "", "A/B"),
+ tocDoc("d1", "t1", 101, "Doc"),
+ })
+ got := segs[101]
+ if len(got) != 1 || got[0] != "A_B" {
+ t.Errorf("segs[101] = %v, want [A_B]", got)
+ }
+}
+
+func TestBuildTOCPaths_SkipsNonDocAndEmptyID(t *testing.T) {
+ segs, inTOC := buildTOCPaths([]v2TOCNode{
+ tocTitle("t1", "", "Group"),
+ {UUID: "d0", Type: tocNodeTypeDoc, Title: "No id"}, // doc_id absent → 0
+ {UUID: "d1", Type: "SHEET", Title: "Sheet", ParentUUID: "t1"}, // not a DOC node
+ })
+ if len(segs) != 0 || len(inTOC) != 0 {
+ t.Errorf("want empty maps, got segs=%v inTOC=%v", segs, inTOC)
+ }
+}
+
+func TestBuildTOCPaths_DuplicateDocID(t *testing.T) {
+ segs, inTOC := buildTOCPaths([]v2TOCNode{
+ tocTitle("t1", "", "A"),
+ tocTitle("t2", "", "B"),
+ tocDoc("d1", "t1", 101, "Doc"),
+ tocDoc("d2", "t2", 101, "Doc"),
+ })
+ if !inTOC[101] {
+ t.Error("inTOC[101] should be true")
+ }
+ // Last write wins; what matters is that the map stays well-formed.
+ if len(segs[101]) != 1 {
+ t.Errorf("segs[101] = %v, want a single segment", segs[101])
+ }
+}
+
+// --- flexibleDocID ---
+
+func TestFlexibleDocID_Unmarshal(t *testing.T) {
+ cases := []struct {
+ name string
+ raw string
+ want int64
+ wantErr bool
+ }{
+ {"integer", `{"doc_id":259589930}`, 259589930, false},
+ {"string", `{"doc_id":"259589930"}`, 259589930, false},
+ {"empty string (TITLE node)", `{"doc_id":""}`, 0, false},
+ {"null", `{"doc_id":null}`, 0, false},
+ {"missing", `{}`, 0, false},
+ {"padded string", `{"doc_id":" 42 "}`, 42, false},
+ {"boolean", `{"doc_id":true}`, 0, true},
+ {"non-numeric string", `{"doc_id":"abc"}`, 0, true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ var n v2TOCNode
+ err := json.Unmarshal([]byte(tc.raw), &n)
+ if tc.wantErr {
+ if err == nil {
+ t.Fatalf("expected error for %s", tc.raw)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("unmarshal %s: %v", tc.raw, err)
+ }
+ if int64(n.DocID) != tc.want {
+ t.Errorf("DocID = %d, want %d", int64(n.DocID), tc.want)
+ }
+ })
+ }
+}
+
+// The real API mixes node shapes in one response; the whole list must decode.
+func TestV2TOCResponse_RealisticPayload(t *testing.T) {
+ raw := `{"data":[
+ {"uuid":"t1","type":"TITLE","title":"Group","doc_id":"","parent_uuid":""},
+ {"uuid":"d1","type":"DOC","title":"Doc","doc_id":259589930,"parent_uuid":"t1"},
+ {"uuid":"d2","type":"DOC","title":"Loose","doc_id":"267830135","parent_uuid":""}
+ ]}`
+ var resp v2TOCResponse
+ if err := json.Unmarshal([]byte(raw), &resp); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ segs, inTOC := buildTOCPaths(resp.Data)
+ if !inTOC[259589930] || !inTOC[267830135] {
+ t.Errorf("inTOC = %v, want both docs", inTOC)
+ }
+ if got := segs[259589930]; len(got) != 1 || got[0] != "Group" {
+ t.Errorf("segs[259589930] = %v, want [Group]", got)
+ }
+ if _, ok := segs[267830135]; ok {
+ t.Errorf("segs[267830135] should be absent, got %v", segs[267830135])
+ }
+}
+
+// --- buildFolderFileName ---
+
+// The regression guard: with default settings the emitted FileName must be
+// exactly what previous releases produced, byte for byte.
+func TestBuildFolderFileName_DefaultIsUnchanged(t *testing.T) {
+ got := buildFolderFileName(defaultFolderSettings(), true, "Book", []string{"Group"}, "Title")
+ want := datasource.SanitizeFileName("Title") + ".md"
+ if got != want {
+ t.Errorf("FileName = %q, want %q", got, want)
+ }
+ for _, bookName := range []string{"", "Book"} {
+ for _, segs := range [][]string{nil, {"A"}, {"A", "B"}} {
+ if got := buildFolderFileName(folderSettings{}, true, bookName, segs, "T"); got != "T.md" {
+ t.Errorf("zero-value settings: FileName = %q, want %q", got, "T.md")
+ }
+ }
+ }
+}
+
+func TestBuildFolderFileName_TOCMode(t *testing.T) {
+ tocMode := folderSettings{FolderMode: folderModeTOC}
+
+ cases := []struct {
+ name string
+ settings folderSettings
+ tocOK bool
+ bookName string
+ segs []string
+ want string
+ }{
+ {"book + group", tocMode, true, "My Book", []string{"A", "B"}, "My Book/A/B/Doc.md"},
+ {"book only (doc not in TOC)", tocMode, true, "My Book", nil, "My Book/Doc.md"},
+ {"empty book name", tocMode, true, "", []string{"A"}, "A/Doc.md"},
+ {"book name needs sanitising", tocMode, true, "A/B", nil, "A_B/Doc.md"},
+ {"toc unavailable degrades to flat", tocMode, false, "My Book", []string{"A"}, "Doc.md"},
+ {"default mode stays flat", defaultFolderSettings(), true, "My Book", []string{"A"}, "Doc.md"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := buildFolderFileName(tc.settings, tc.tocOK, tc.bookName, tc.segs, "Doc"); got != tc.want {
+ t.Errorf("FileName = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+// --- parseFolderSettings ---
+
+func TestParseFolderSettings_Defaults(t *testing.T) {
+ got := parseFolderSettings(context.Background(), &types.DataSourceConfig{})
+ want := defaultFolderSettings()
+ if got != want {
+ t.Errorf("got %+v, want %+v", got, want)
+ }
+ if got.FolderMode != folderModeNone {
+ t.Errorf("FolderMode = %q, want %q (upgrades must not change behaviour)", got.FolderMode, folderModeNone)
+ }
+ if got := parseFolderSettings(context.Background(), nil); got != want {
+ t.Errorf("nil config: got %+v, want %+v", got, want)
+ }
+}
+
+func TestParseFolderSettings_ReadsValues(t *testing.T) {
+ got := parseFolderSettings(context.Background(), &types.DataSourceConfig{
+ Settings: map[string]interface{}{
+ "folder_mode": "toc",
+ "toc_only": true,
+ },
+ })
+ if got.FolderMode != folderModeTOC || !got.TOCOnly {
+ t.Errorf("got %+v", got)
+ }
+}
+
+func TestParseFolderSettings_TolerantOfBadInput(t *testing.T) {
+ cases := []struct {
+ name string
+ settings map[string]interface{}
+ want folderSettings
+ }{
+ {"unknown mode", map[string]interface{}{"folder_mode": "bogus"}, defaultFolderSettings()},
+ {"wrong type for mode", map[string]interface{}{"folder_mode": 42}, defaultFolderSettings()},
+ {
+ "string bools",
+ map[string]interface{}{"toc_only": "true"},
+ folderSettings{FolderMode: folderModeNone, TOCOnly: true},
+ },
+ {"unrecognised bool", map[string]interface{}{"toc_only": "maybe"}, defaultFolderSettings()},
+ {
+ "mixed case mode",
+ map[string]interface{}{"folder_mode": " TOC "},
+ folderSettings{FolderMode: folderModeTOC},
+ },
+ {
+ // Unknown keys are ignored rather than failing the sync — settings
+ // arrive from JSON, and a typo must not take a data source down.
+ "unknown key is ignored",
+ map[string]interface{}{"folder_mode": "toc", "no_such_setting": false},
+ folderSettings{FolderMode: folderModeTOC},
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := parseFolderSettings(context.Background(), &types.DataSourceConfig{Settings: tc.settings})
+ if got != tc.want {
+ t.Errorf("got %+v, want %+v", got, tc.want)
+ }
+ })
+ }
+}
+
+// --- FetchAll integration ---
+
+const testTS = "2026-04-20T10:00:00Z"
+
+// fakeBookDocs wires book 7 with three documents: 101 sits under a group, 102
+// appears in the TOC without any group, and 103 is absent from the TOC.
+//
+// FileName is derived from the *list* endpoint's title, so the assertions below
+// use those (Grouped / Loose / Unfiled) rather than the detail titles.
+func fakeBookDocs(f *fakeYuque) {
+ f.handleJSON("/api/v2/repos/7/docs", 200, v2DocListResponse{Data: []v2Doc{
+ {ID: 101, Type: "Doc", Status: "1", Title: "Grouped", Slug: "g", BookID: 7, ContentUpdatedAt: testTS},
+ {ID: 102, Type: "Doc", Status: "1", Title: "Loose", Slug: "l", BookID: 7, ContentUpdatedAt: testTS},
+ {ID: 103, Type: "Doc", Status: "1", Title: "Unfiled", Slug: "u", BookID: 7, ContentUpdatedAt: testTS},
+ }})
+ for _, d := range []struct {
+ id int64
+ title string
+ }{{101, "Grouped"}, {102, "Loose"}, {103, "Unfiled"}} {
+ f.handleJSON(docDetailPath(d.id), 200, v2DocDetailResponse{Data: v2DocDetail{
+ ID: d.id, Title: d.title, Body: "# body", Format: "markdown", Status: "1",
+ ContentUpdatedAt: testTS,
+ Book: v2Repo{ID: 7, Name: "My Book", Namespace: "alice/demo"},
+ }})
+ }
+}
+
+// fakeBookTOC registers the TOC endpoint for book 7. A ServeMux panics on a
+// duplicate pattern, so this is registered exactly once per test.
+func fakeBookTOC(f *fakeYuque, status int) {
+ f.handleJSON("/api/v2/repos/7/toc", status, v2TOCResponse{Data: []v2TOCNode{
+ tocTitle("t1", "", "Group"),
+ tocDoc("d1", "t1", 101, "Grouped"),
+ tocDoc("d2", "", 102, "Loose"),
+ }})
+}
+
+func docDetailPath(id int64) string {
+ return "/api/v2/repos/docs/" + strconv.FormatInt(id, 10)
+}
+
+func itoa(v int64) string { return strconv.FormatInt(v, 10) }
+
+func fileNames(items []types.FetchedItem) map[string]string {
+ out := make(map[string]string, len(items))
+ for _, it := range items {
+ out[it.ExternalID] = it.FileName
+ }
+ return out
+}
+
+func TestConnector_FetchAll_TOCPaths(t *testing.T) {
+ f := newFakeYuque()
+ defer f.Close()
+ fakeBookDocs(f)
+ fakeBookTOC(f, 200)
+
+ items, err := NewConnector().FetchAll(context.Background(),
+ makeDSConfigWithSettings(f, []string{"7"}, map[string]interface{}{"folder_mode": "toc"}),
+ []string{"7"})
+ if err != nil {
+ t.Fatalf("FetchAll: %v", err)
+ }
+ got := fileNames(items)
+ want := map[string]string{
+ "101": "My Book/Group/Grouped.md", // grouped document
+ "102": "My Book/Loose.md", // in the TOC, no group → book segment only
+ "103": "My Book/Unfiled.md", // not in the TOC → book segment only
+ }
+ for id, wantName := range want {
+ if got[id] != wantName {
+ t.Errorf("doc %s: FileName = %q, want %q", id, got[id], wantName)
+ }
+ }
+}
+
+// Without settings the connector must behave exactly as before: flat names.
+func TestConnector_FetchAll_DefaultSettingsFlat(t *testing.T) {
+ f := newFakeYuque()
+ defer f.Close()
+ fakeBookDocs(f)
+ fakeBookTOC(f, 200) // present but must be ignored without folder_mode=toc
+
+ items, err := NewConnector().FetchAll(context.Background(), makeDSConfig(f, []string{"7"}), []string{"7"})
+ if err != nil {
+ t.Fatalf("FetchAll: %v", err)
+ }
+ want := map[string]string{"101": "Grouped.md", "102": "Loose.md", "103": "Unfiled.md"}
+ got := fileNames(items)
+ for id, wantName := range want {
+ if got[id] != wantName {
+ t.Errorf("doc %s: FileName = %q, want %q", id, got[id], wantName)
+ }
+ }
+}
+
+// toc_only must drop documents absent from the TOC but keep a group-less
+// document that is present in it. The latter is the case most likely to
+// regress, since its derived path is empty.
+func TestConnector_FetchAll_TOCOnly(t *testing.T) {
+ f := newFakeYuque()
+ defer f.Close()
+ fakeBookDocs(f)
+ fakeBookTOC(f, 200)
+
+ items, err := NewConnector().FetchAll(context.Background(),
+ makeDSConfigWithSettings(f, []string{"7"}, map[string]interface{}{
+ "folder_mode": "toc", "toc_only": true,
+ }), []string{"7"})
+ if err != nil {
+ t.Fatalf("FetchAll: %v", err)
+ }
+ got := fileNames(items)
+ if len(got) != 2 {
+ t.Fatalf("kept %d docs, want 2 (101 grouped + 102 group-less); got %v", len(got), got)
+ }
+ if _, ok := got["101"]; !ok {
+ t.Error("doc 101 (grouped) should be kept")
+ }
+ if _, ok := got["102"]; !ok {
+ t.Error("doc 102 (in TOC but group-less) must be kept — not filtered by an empty path")
+ }
+ if _, ok := got["103"]; ok {
+ t.Error("doc 103 (absent from TOC) should be filtered out")
+ }
+}
+
+// toc_only is an admission filter, not a reaper. A document that was already
+// ingested and is then filtered out must not be reported as deleted: Yuque's
+// own web UI cannot show documents created through the API that were never
+// attached to the TOC, so removing them here would leave their content
+// reachable from neither side.
+func TestConnector_FetchIncremental_TOCOnlyDoesNotDelete(t *testing.T) {
+ // First sync: folder paths on, no admission filter — all three land.
+ f1 := newFakeYuque()
+ fakeBookDocs(f1)
+ fakeBookTOC(f1, 200)
+ _, cursor1, err := NewConnector().FetchIncremental(context.Background(),
+ makeDSConfigWithSettings(f1, []string{"7"}, map[string]interface{}{"folder_mode": "toc"}), nil)
+ if err != nil {
+ t.Fatalf("first sync: %v", err)
+ }
+ f1.Close()
+
+ // Second sync: same source, now with toc_only. Doc 103 is absent from the
+ // TOC so it is filtered, but it is still present in the book's document list.
+ f2 := newFakeYuque()
+ defer f2.Close()
+ fakeBookDocs(f2)
+ fakeBookTOC(f2, 200)
+
+ items, _, err := NewConnector().FetchIncremental(context.Background(),
+ makeDSConfigWithSettings(f2, []string{"7"}, map[string]interface{}{
+ "folder_mode": "toc", "toc_only": true,
+ }), cursor1)
+ if err != nil {
+ t.Fatalf("second sync: %v", err)
+ }
+ for _, it := range items {
+ if it.ExternalID == "103" {
+ t.Errorf("doc 103 was filtered by toc_only but is still reported "+
+ "(IsDeleted=%t); an admission filter must not turn into a deletion", it.IsDeleted)
+ }
+ }
+}
+
+// Admitting a previously filtered document must ingest it. A filtered document
+// is deliberately kept out of the cursor, so attaching it to the TOC later — or
+// switching toc_only off — has to read as new rather than as unchanged.
+func TestConnector_FetchIncremental_AdmitsPreviouslyFilteredDoc(t *testing.T) {
+ // First sync with toc_only on: doc 103 is absent from the TOC and filtered.
+ f1 := newFakeYuque()
+ fakeBookDocs(f1)
+ fakeBookTOC(f1, 200)
+ items1, cursor1, err := NewConnector().FetchIncremental(context.Background(),
+ makeDSConfigWithSettings(f1, []string{"7"}, map[string]interface{}{
+ "folder_mode": "toc", "toc_only": true,
+ }), nil)
+ if err != nil {
+ t.Fatalf("first sync: %v", err)
+ }
+ for _, it := range items1 {
+ if it.ExternalID == "103" {
+ t.Fatalf("doc 103 should have been filtered on the first sync: %+v", it)
+ }
+ }
+ f1.Close()
+
+ // Second sync: doc 103 has been attached to the TOC. Its content is
+ // unchanged, so only the admission decision can bring it in.
+ f2 := newFakeYuque()
+ defer f2.Close()
+ fakeBookDocs(f2)
+ f2.handleJSON("/api/v2/repos/7/toc", 200, v2TOCResponse{Data: []v2TOCNode{
+ tocTitle("t1", "", "Group"),
+ tocDoc("d1", "t1", 101, "Grouped"),
+ tocDoc("d2", "", 102, "Loose"),
+ tocDoc("d3", "t1", 103, "Unfiled"),
+ }})
+
+ items2, _, err := NewConnector().FetchIncremental(context.Background(),
+ makeDSConfigWithSettings(f2, []string{"7"}, map[string]interface{}{
+ "folder_mode": "toc", "toc_only": true,
+ }), cursor1)
+ if err != nil {
+ t.Fatalf("second sync: %v", err)
+ }
+ var admitted bool
+ for _, it := range items2 {
+ if it.ExternalID != "103" || it.IsDeleted {
+ continue
+ }
+ admitted = true
+ if want := "My Book/Group/Unfiled.md"; it.FileName != want {
+ t.Errorf("doc 103: FileName = %q, want %q", it.FileName, want)
+ }
+ }
+ if !admitted {
+ t.Errorf("doc 103 was attached to the TOC but was not ingested; items=%+v", items2)
+ }
+}
+
+// A document that really is gone from the source must still be reported — the
+// admission filter must not have disabled deletion detection.
+func TestConnector_FetchIncremental_StillDetectsRealDeletion(t *testing.T) {
+ f1 := newFakeYuque()
+ fakeBookDocs(f1)
+ fakeBookTOC(f1, 200)
+ _, cursor1, err := NewConnector().FetchIncremental(context.Background(),
+ makeDSConfigWithSettings(f1, []string{"7"}, map[string]interface{}{
+ "folder_mode": "toc", "toc_only": true,
+ }), nil)
+ if err != nil {
+ t.Fatalf("first sync: %v", err)
+ }
+ f1.Close()
+
+ // Doc 101 disappears from the source entirely.
+ f2 := newFakeYuque()
+ defer f2.Close()
+ f2.handleJSON("/api/v2/repos/7/docs", 200, v2DocListResponse{Data: []v2Doc{
+ {ID: 102, Type: "Doc", Status: "1", Title: "Loose", Slug: "l", BookID: 7, ContentUpdatedAt: testTS},
+ }})
+ fakeBookTOC(f2, 200)
+
+ items, _, err := NewConnector().FetchIncremental(context.Background(),
+ makeDSConfigWithSettings(f2, []string{"7"}, map[string]interface{}{
+ "folder_mode": "toc", "toc_only": true,
+ }), cursor1)
+ if err != nil {
+ t.Fatalf("second sync: %v", err)
+ }
+ deleted := 0
+ for _, it := range items {
+ if it.IsDeleted && it.ExternalID == "101" {
+ deleted++
+ }
+ }
+ if deleted != 1 {
+ t.Errorf("expected doc 101 to be reported as deleted once, got %d; items=%+v", deleted, items)
+ }
+}
+
+// If the TOC endpoint is unavailable, toc_only must not filter anything —
+// otherwise an outage would silently drop the whole book.
+func TestConnector_FetchAll_TOCUnavailableDegrades(t *testing.T) {
+ f := newFakeYuque()
+ defer f.Close()
+ fakeBookDocs(f)
+ // Older Yuque deployments have no TOC endpoint at all → 404.
+ fakeBookTOC(f, 404)
+
+ items, err := NewConnector().FetchAll(context.Background(),
+ makeDSConfigWithSettings(f, []string{"7"}, map[string]interface{}{
+ "folder_mode": "toc", "toc_only": true,
+ }), []string{"7"})
+ if err != nil {
+ t.Fatalf("FetchAll must not fail when the TOC is unavailable: %v", err)
+ }
+ if len(items) != 3 {
+ t.Fatalf("kept %d docs, want 3 (no filtering without a TOC)", len(items))
+ }
+ want := map[string]string{"101": "Grouped.md", "102": "Loose.md", "103": "Unfiled.md"}
+ got := fileNames(items)
+ for id, wantName := range want {
+ if got[id] != wantName {
+ t.Errorf("doc %s: FileName = %q, want flat %q", id, got[id], wantName)
+ }
+ }
+}
+
+// A multi-book sync must not merge identically named top-level groups.
+func TestConnector_FetchAll_SeparatesBooksWithSameGroupName(t *testing.T) {
+ f := newFakeYuque()
+ defer f.Close()
+ for _, book := range []struct {
+ id int64
+ name string
+ }{
+ {7, "Book One"},
+ {8, "Book Two"},
+ } {
+ docID := book.id * 10
+ f.handleJSON("/api/v2/repos/"+itoa(book.id)+"/docs", 200, v2DocListResponse{Data: []v2Doc{
+ {
+ ID: docID, Type: "Doc", Status: "1", Title: "Doc", Slug: "d", BookID: book.id,
+ ContentUpdatedAt: testTS,
+ },
+ }})
+ f.handleJSON("/api/v2/repos/"+itoa(book.id)+"/toc", 200, v2TOCResponse{Data: []v2TOCNode{
+ tocTitle("t1", "", "Shared"),
+ tocDoc("d1", "t1", docID, "Doc"),
+ }})
+ f.handleJSON(docDetailPath(docID), 200, v2DocDetailResponse{Data: v2DocDetail{
+ ID: docID, Title: "Doc", Body: "x", Format: "markdown", Status: "1",
+ ContentUpdatedAt: testTS,
+ Book: v2Repo{ID: book.id, Name: book.name, Namespace: "alice/b"},
+ }})
+ }
+
+ items, err := NewConnector().FetchAll(context.Background(),
+ makeDSConfigWithSettings(f, []string{"7", "8"}, map[string]interface{}{"folder_mode": "toc"}),
+ []string{"7", "8"})
+ if err != nil {
+ t.Fatalf("FetchAll: %v", err)
+ }
+ got := fileNames(items)
+ if got["70"] != "Book One/Shared/Doc.md" {
+ t.Errorf("book 7: FileName = %q, want %q", got["70"], "Book One/Shared/Doc.md")
+ }
+ if got["80"] != "Book Two/Shared/Doc.md" {
+ t.Errorf("book 8: FileName = %q, want %q", got["80"], "Book Two/Shared/Doc.md")
+ }
+}
diff --git a/internal/datasource/connector/yuque/types.go b/internal/datasource/connector/yuque/types.go
index b57b7ad25..abf20e325 100644
--- a/internal/datasource/connector/yuque/types.go
+++ b/internal/datasource/connector/yuque/types.go
@@ -18,6 +18,7 @@
package yuque
import (
+ "context"
"encoding/json"
"fmt"
"strconv"
@@ -25,6 +26,7 @@ import (
"time"
"github.com/Tencent/WeKnora/internal/datasource"
+ "github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
@@ -231,3 +233,234 @@ func redactToken(t string) string {
}
return t[:6] + "..." + t[len(t)-4:]
}
+
+// --- Table of contents (TOC) ---
+
+// v2TOCResponse wraps GET /api/v2/repos/{book_id}/toc.
+type v2TOCResponse struct {
+ Data []v2TOCNode `json:"data"`
+}
+
+// v2TOCNode is one entry in a book's table of contents.
+//
+// The endpoint returns a flat list; the hierarchy is expressed by parent_uuid.
+// TITLE nodes are grouping headers (their doc_id is empty), DOC nodes are the
+// actual documents. Both carry a uuid that other nodes reference as parent_uuid.
+type v2TOCNode struct {
+ UUID string `json:"uuid"`
+ Type string `json:"type"`
+ Title string `json:"title"`
+ ParentUUID string `json:"parent_uuid"`
+ DocID flexibleDocID `json:"doc_id"`
+}
+
+const (
+ tocNodeTypeTitle = "TITLE"
+ tocNodeTypeDoc = "DOC"
+)
+
+// flexibleDocID accepts the TOC `doc_id` field, which the API serializes as a
+// number on DOC nodes but as an empty string on TITLE nodes. Decoding straight
+// into int64 fails on "" ("cannot unmarshal string into Go struct field").
+// Absent or empty IDs normalise to 0, which is never a real Yuque document ID.
+type flexibleDocID int64
+
+func (d *flexibleDocID) UnmarshalJSON(b []byte) error {
+ if len(b) == 0 || string(b) == "null" {
+ *d = 0
+ return nil
+ }
+ if b[0] == '"' {
+ var s string
+ if err := json.Unmarshal(b, &s); err != nil {
+ return err
+ }
+ s = strings.TrimSpace(s)
+ if s == "" {
+ *d = 0
+ return nil
+ }
+ n, err := strconv.ParseInt(s, 10, 64)
+ if err != nil {
+ return fmt.Errorf("flexibleDocID: %q is not a numeric id: %w", s, err)
+ }
+ *d = flexibleDocID(n)
+ return nil
+ }
+ var n int64
+ if err := json.Unmarshal(b, &n); err != nil {
+ return fmt.Errorf("flexibleDocID: expected string or integer, got %s: %w", b, err)
+ }
+ *d = flexibleDocID(n)
+ return nil
+}
+
+// maxTOCDepth bounds the ancestor walk in buildTOCPaths. Real nesting is only a
+// few levels deep; the bound is a backstop against malformed input.
+const maxTOCDepth = 32
+
+// buildTOCPaths folds a flat TOC node list into two per-document lookup maps:
+//
+// segs — doc_id → ancestor titles, root-first, each already passed through
+// sanitizeFileName. Absent when the document sits directly under the
+// book root.
+// inTOC — doc_id → whether the document appears in the TOC node list at all.
+//
+// The two maps are deliberately separate and must stay that way. A document can
+// legitimately appear in the TOC without belonging to any group, in which case
+// inTOC is true and segs is empty. A caller filtering out "documents that are
+// not in the TOC" must test inTOC — testing segs[id] instead would also drop
+// those group-less documents.
+//
+// Sanitising per segment here (rather than on the joined path) is what keeps a
+// "/" inside a group title from silently creating an extra nesting level.
+func buildTOCPaths(nodes []v2TOCNode) (map[int64][]string, map[int64]bool) {
+ byUUID := make(map[string]v2TOCNode, len(nodes))
+ for _, n := range nodes {
+ if n.UUID != "" {
+ byUUID[n.UUID] = n
+ }
+ }
+
+ segs := make(map[int64][]string)
+ inTOC := make(map[int64]bool)
+
+ for _, n := range nodes {
+ if n.Type != tocNodeTypeDoc {
+ continue
+ }
+ id := int64(n.DocID)
+ if id == 0 {
+ continue
+ }
+ inTOC[id] = true
+
+ var reverse []string
+ visited := map[string]bool{n.UUID: true}
+ cur := n
+ for len(reverse) < maxTOCDepth {
+ parent, ok := byUUID[cur.ParentUUID]
+ if !ok || parent.UUID == "" || visited[parent.UUID] {
+ break // reached the root, hit a dangling parent, or a cycle
+ }
+ visited[parent.UUID] = true
+ if title := strings.TrimSpace(parent.Title); title != "" {
+ reverse = append(reverse, datasource.SanitizeFileName(title))
+ }
+ cur = parent
+ }
+ // Walked child → root; flip to root → child for path order.
+ out := make([]string, len(reverse))
+ for i, s := range reverse {
+ out[len(reverse)-1-i] = s
+ }
+ if len(out) > 0 {
+ segs[id] = out
+ }
+ }
+ return segs, inTOC
+}
+
+// --- Folder path settings ---
+
+const (
+ // folderModeNone is the historical behaviour: a bare "<title>.md" file name,
+ // so every synced document lands at the knowledge base root.
+ folderModeNone = "none"
+ // folderModeTOC derives the folder path from the book's table of contents.
+ folderModeTOC = "toc"
+)
+
+// folderSettings controls how folder paths are derived for synced documents.
+// Configured under DataSourceConfig.Settings, never under Credentials.
+type folderSettings struct {
+ // FolderMode is folderModeNone or folderModeTOC.
+ FolderMode string
+ // TOCOnly admits only documents that appear in the book's TOC. It is an
+ // admission filter, not a reaper: a filtered document is simply not
+ // ingested, and one already in the knowledge base is left untouched. Only
+ // meaningful when FolderMode is folderModeTOC.
+ TOCOnly bool
+}
+
+// defaultFolderSettings keeps the emitted FileName byte-for-byte identical to
+// previous releases, so enabling the new behaviour is strictly opt-in and an
+// existing data source keeps working unchanged after an upgrade.
+func defaultFolderSettings() folderSettings {
+ return folderSettings{
+ FolderMode: folderModeNone,
+ TOCOnly: false,
+ }
+}
+
+// parseFolderSettings reads the folder-path settings, falling back to the
+// default for any key that is absent or unrecognised. A typo in the settings
+// map must not fail a sync.
+func parseFolderSettings(ctx context.Context, ds *types.DataSourceConfig) folderSettings {
+ s := defaultFolderSettings()
+ if ds == nil || ds.Settings == nil {
+ return s
+ }
+ if raw, ok := ds.Settings["folder_mode"]; ok {
+ mode := strings.ToLower(strings.TrimSpace(fmt.Sprint(raw)))
+ switch mode {
+ case folderModeNone, folderModeTOC:
+ s.FolderMode = mode
+ default:
+ logger.Warnf(ctx, "[Yuque] unknown folder_mode %q, keeping %q", mode, s.FolderMode)
+ }
+ }
+ s.TOCOnly = settingBool(ds.Settings["toc_only"], s.TOCOnly)
+ return s
+}
+
+// settingBool interprets a settings value as a boolean, returning def when the
+// value is absent or of an unrecognised shape. Settings arrive from JSON, so a
+// hand-edited config may carry either a real bool or its string form.
+func settingBool(v interface{}, def bool) bool {
+ switch t := v.(type) {
+ case bool:
+ return t
+ case string:
+ switch strings.ToLower(strings.TrimSpace(t)) {
+ case "true", "1", "yes", "on":
+ return true
+ case "false", "0", "no", "off":
+ return false
+ }
+ }
+ return def
+}
+
+// buildFolderFileName assembles the FileName for a synced document.
+//
+// folder_path downstream is derived from FileName alone
+// (SplitKnowledgeRelativePath → NormalizeKnowledgeFolderPath), so the folder
+// hierarchy has to be encoded here as a relative path.
+//
+// With the default settings — or whenever the book's TOC could not be loaded —
+// this returns exactly "<title>.md", which is the byte-for-byte behaviour of
+// previous releases.
+//
+// When the TOC is in play the book name is always the first segment. It is the
+// only carrier of the "which book" dimension — the automatic tag granularity is
+// per data source, not per book — and omitting it would silently merge
+// same-named top-level groups from different books into one folder.
+func buildFolderFileName(
+ settings folderSettings, tocOK bool, bookName string, tocSegs []string, title string,
+) string {
+ fileName := datasource.SanitizeFileName(title) + ".md"
+ if settings.FolderMode != folderModeTOC || !tocOK {
+ return fileName
+ }
+ segments := make([]string, 0, len(tocSegs)+1)
+ if bookName != "" {
+ segments = append(segments, datasource.SanitizeFileName(bookName))
+ }
+ // tocSegs are already sanitised by buildTOCPaths.
+ segments = append(segments, tocSegs...)
+ if len(segments) == 0 {
+ return fileName
+ }
+ return strings.Join(segments, "/") + "/" + fileName
+}
diff --git a/website-docs/03-features/10-datasource.md b/website-docs/03-features/10-datasource.md
index 8441c6df9..5734f77ec 100644
--- a/website-docs/03-features/10-datasource.md
+++ b/website-docs/03-features/10-datasource.md
@@ -146,6 +146,14 @@
- **资源列举**:`GET /api/v2/user` 判断 token 身份——`type=="Group"` 为团队 token,直接列团队 repo;否则列个人 repo + 已加入 group 的 repo(用户未加入任何 group 时语雀返回 404,按空处理)。输出扁平的 `book` 资源列表,按 ExternalID 稳定排序。
- **抓取**(`walk`,全量/增量共用):`ListBookDocs` 列文档 → 过滤 `type != "Doc"`(跳过 Sheet/Thread/Board/Table)与 `status != "1"`(跳过草稿)→ 每次 `GetDocDetail` 之间 sleep 300ms 规避限流 → `format` 为 `markdown`/`lake` 时取 `body` Markdown 原文入库(其他格式如 html 防御性跳过并记 `skip_reason`)。
- **增量逻辑**:游标 `yuqueCursor.BookDocTimes`(`bookID → docID → content_updated_at`),一致则跳过。删除检测:游标里有、当前列表没有 → `IsDeleted`。
+- **目录结构(`settings` 配置项)**:默认所有文档平铺在知识库根目录。两个键控制这一点:
+ - **`folder_mode`**(默认 `none`):`none` 输出裸的 `<标题>.md`,与历史行为逐字节一致;`toc` 按书的目录层级拼出 `<书名>/<分组>/…/<标题>.md`。前端在**新建**数据源时写入 `toc`,已有数据源保持 `none`,因此升级不会改变现有来源的行为。
+ - **`toc_only`**(默认 `false`):只让出现在该书目录节点列表中的文档入库。**仅在 `folder_mode=toc` 时生效**——目录只在该模式下才会被拉取,平铺模式下这个键不起作用。判据是"是否出现在目录中",不是"是否有路径"——挂在目录下但未归入任何分组的文档仍会保留。**它是准入过滤器,不是清理器**:被过滤的文档只是不入库,已经同步进知识库的副本原样保留,不会被报成删除。语雀 Web UI 不显示"通过 API 创建、从未挂到目录"的文档,若把这类文档判为已删除,其内容会在源端和知识库两侧都不可达。
+- **目录归属**:`toc` 开启后目录由连接器托管——在知识库里手动调整过的目录,会在该文档下次同步时被覆盖回语雀的结构。
+- **注意 / 限制**:
+ - **切换目录模式后跑一次全量同步**:已有数据源修改 `folder_mode` 后,增量同步只会移动内容有变化的文档;手动触发一次全量同步,已导入的文档才会整体按新模式重新归位。
+ - **仅在语雀目录中移动文档不会立即反映**:增量同步按 `content_updated_at` 判断变化,只调整目录位置、未改内容的文档,会在下次内容变更或全量同步时移到新目录。
+ - **`toc_only` 不会移除已导入的文档**:开启后被过滤掉的文档不再同步,知识库中已有的副本原样保留,之后它在语雀被删除也不会同步删除,需要时请在知识库中手动清理。
#### 钉钉文档(`connector/dingtalk/`)