diff --git a/README.md b/README.md
index b139a7b..3e76585 100644
--- a/README.md
+++ b/README.md
@@ -26,7 +26,7 @@ Anki Heading Sync 是一个 Obsidian 桌面端插件,用来批量地制作 Ank
### 使用要求
-- Obsidian 桌面端 1.5.0 或更高版本
+- Obsidian 桌面端 1.8.7 或更高版本
- Anki 桌面端
- Anki 中已安装并启用 AnkiConnect
@@ -148,7 +148,7 @@ Currently, the plugin mainly supports four card types:
### Requirements
-- Obsidian desktop 1.5.0 or newer
+- Obsidian desktop 1.8.7 or newer
- Anki desktop
- AnkiConnect enabled in Anki
diff --git a/docs/obsidian-community-release-readiness-report.md b/docs/obsidian-community-release-readiness-report.md
index 83fbef0..36d36f0 100644
--- a/docs/obsidian-community-release-readiness-report.md
+++ b/docs/obsidian-community-release-readiness-report.md
@@ -35,7 +35,7 @@ Repository evidence was verified against these files and modules:
- The GitHub repository currently shows no published releases, so the first submission release still needs to be created.
- No exact `anki-heading-sync` ID match and no exact `Anki Heading Sync` name match were found in the current upstream Obsidian community-plugins.json.
- manifest.json contains the expected release-facing fields: `id`, `name`, `version`, `minAppVersion`, `description`, `author`, `authorUrl`, and `isDesktopOnly`.
-- versions.json currently maps `1.0.0` to `1.5.0`, which matches manifest.json version and minAppVersion.
+- versions.json currently maps `1.0.1` to `1.8.7`, which matches manifest.json version and minAppVersion.
- package.json defines the release-relevant commands: `lint`, `test`, `build`, and `build:obsidian`.
- package-lock.json is present, and no yarn.lock was found.
- LICENSE is present and uses MIT.
@@ -87,7 +87,7 @@ Based on the current Obsidian docs, the repository must satisfy these release co
## 4. What still needs fixing
-- A GitHub release for version `1.0.0` still needs to be created manually, with assets attached.
+- A GitHub release for version `1.0.1` still needs to be created manually, with assets attached.
- Manual QA in real Obsidian and real Anki is still required before submission.
- The actual submission PR to obsidianmd/obsidian-releases still needs to be opened.
@@ -137,7 +137,7 @@ Run these checks in a real desktop Obsidian vault with real Anki running:
- Run `npm test`.
- Run `npm run build`.
- Verify dist/plugin contains `main.js`, `manifest.json`, and `styles.css` when present.
-- Create a GitHub release tag exactly matching `manifest.json.version`, currently `1.0.0`.
+- Create a GitHub release tag exactly matching `manifest.json.version`, currently `1.0.1`.
- Upload these assets to the release:
- main.js
- manifest.json
@@ -180,5 +180,5 @@ Repository-level release preparation is close to complete, but submission should
- local lint, test, and build validation remain green on the release branch
- manual QA is completed in real Obsidian and real Anki
-- the GitHub release for version `1.0.0` exists with the correct assets
+- the GitHub release for version `1.0.1` exists with the correct assets
- the submission PR to obsidianmd/obsidian-releases is opened with the correct metadata
diff --git a/main.js b/main.js
index 0a10e6d..3dcfef7 100644
--- a/main.js
+++ b/main.js
@@ -1,35 +1,35 @@
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
*/
-"use strict";var Tn=Object.defineProperty;var mo=Object.getOwnPropertyDescriptor;var ho=Object.getOwnPropertyNames;var ko=Object.prototype.hasOwnProperty;var Qe=(e,t)=>{for(var n in t)Tn(e,n,{get:t[n],enumerable:!0})},bo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ho(t))!ko.call(e,i)&&i!==n&&Tn(e,i,{get:()=>t[i],enumerable:!(r=mo(t,i))||r.enumerable});return e};var yo=e=>bo(Tn({},"__esModule",{value:!0}),e);var bl={};Qe(bl,{default:()=>kl});module.exports=yo(bl);var fo=require("obsidian");function B(e,t){return`${e}:${t}`}function Dn(e){return e?.cardType==="basic"}function ei(e){return e?.cardType==="cloze"}function H(e){return e?.cardType==="qa-group"}function se(e=xo()){let t=e.toLowerCase();return t==="zh"||t.startsWith("zh-")?"zh":"en"}function ce(e,t){return t.join(e==="zh"?"\u3001":", ")}function xo(){return typeof navigator<"u"&&typeof navigator.language=="string"?navigator.language:"en"}var An={commands:{syncCurrentFileToAnki:"Sync current file to Anki",syncVaultToAnki:"Sync vault to Anki",clearCurrentFileSyncedCards:"Clear synced cards in current file",cleanupEmptyDecks:"Clean up empty decks"},settings:{pluginTitle:"Anki heading sync",ankiConnectUrl:{name:"AnkiConnect URL",desc:"Default: http://127.0.0.1:8765",placeholder:"Example: http://127.0.0.1:8765"},qaHeadingLevel:{name:"Heading level for question-and-answer cards",desc:"Default: H4"},clozeHeadingLevel:{name:"Cloze heading level",desc:"Default: H5"},cardAnswerCutoffMode:{name:"Card answer cutoff mode",desc:"A valid sync marker always wins. Without a valid marker, either keep the whole heading block or stop before the first 2+ consecutive blank lines.",options:{headingBlock:"Heading-block: whole heading block",doubleBlankLines:"Double-blank-lines: stop before the first 2+ blank lines"}},qaGroup:{title:"List notes for question-and-answer groups",marker:{name:"Marker for question-and-answer groups",desc:"When a question-and-answer heading ends with this hashtag marker, the whole heading block syncs as one list note for that group.",placeholder:"Hashtag marker"},managedNoteType:"Current note type: {{modelName}}. This route syncs QA Group list notes using the field mapping shown below.",managedModelContract:"Current note type summary: {{fieldCount}} fields and {{templateCount}} templates are available for this route."},syncOptions:{addObsidianBacklink:{name:"Add Obsidian backlink",desc:"Append a backlink to the source heading into synced cards."},obsidianBacklinkLabel:{name:"Obsidian backlink label",desc:"The text shown for the backlink. Blank input uses the default backlink label.",placeholder:"Open in Obsidian"},obsidianBacklinkPlacement:{name:"Obsidian backlink placement",desc:"Choose whether the backlink is appended to the question field or placed at the start or end of the answer body.",options:{questionLastLine:"Last line of question field",answerFirstLine:"First line of answer body",answerLastLine:"Last line of answer body"}},highlightsToCloze:{name:"Highlights to cloze",desc:"Convert ==highlight== segments into cloze deletions for cloze cards."},syncObsidianTagsToAnki:{name:"Sync Obsidian tags to Anki",desc:"Sync Obsidian-recognized tags from the current note into Anki note tags, including nested tags. On each sync, these tags overwrite the managed tags in Anki based on the current Obsidian content."},keepPureTagLinesInCardBody:{name:"Keep pure tag lines in card body",desc:'When turned off, remove every line in the card body that contains only tags, such as "#example #tag/case". Inline tags like "this is a #tag example" and lines with ordinary text like "tag label: #project" are kept. Extra blank lines created by removal are cleaned up automatically.'}},mapping:{title:"Note type field mappings",refresh:{name:"Refresh note types from Anki",button:"Refresh note types"},status:{idle:"Refresh note types from Anki to load the available note types.",loadedCount:"Loaded {{count}} note types from Anki.",empty:"Anki returned no note types.",failedLoadNoteTypes:"Failed to load note types from Anki.",loadedSavedMapping:"Loaded saved mapping for {{modelName}}.",selectedModel:"Selected {{modelName}}. Read fields from Anki to create or refresh its mapping.",loadedFieldsForModel:"Loaded fields for {{modelName}}. Review the suggested mapping and save it.",failedLoadFields:"Failed to load fields for {{modelName}}.",noLoadedFields:"No loaded fields for {{modelName}}. Read fields from Anki first.",savedMapping:"Saved mapping for {{modelName}}.",failedSaveMapping:"Failed to save mapping for {{modelName}}.",savedMappingReady:"Saved mapping is ready for {{title}}.",noSavedMapping:"No saved mapping for {{title}}. Read fields from Anki first."},section:{basic:{title:"Basic and question-and-answer",description:"Choose the note type for question-and-answer cards, read its fields from Anki, then confirm the title and body mapping."},cloze:{title:"Cloze",description:"Choose the cloze note type, read its fields from Anki, then confirm the main field mapping."}},noteTypeLabel:"{{title}} note type",noteTypeDesc:"Loaded from Anki note types. Refresh if the latest models are not shown.",fieldsLabel:"{{title}} fields",fieldsDesc:"Load the current note type fields from Anki, then review the suggested mapping.",readFieldsButton:"Read fields from Anki",loadedFields:"Loaded fields: {{fields}}",loadedFieldsNone:"Loaded fields: none. Read fields from Anki first.",mappingLabel:"{{title}} mapping",mappingDesc:"Save the current field mapping for this specific note type.",saveMappingButton:"Save mapping",titleFieldLabel:"{{title}} title field",titleFieldDesc:"Which Anki field should receive the heading/title fragment.",bodyFieldLabel:"{{title}} body field",bodyFieldDesc:"Which Anki field should receive the body fragment.",mainField:{name:"Cloze main field",desc:"The selected field receives title +
=p))){a=o===61?1:2;break}}if(e.sCount[u]<0)continue;let f=!1;for(let m=0,p=r.length;m
3||e.sCount[a]<0)continue;let c=!1;for(let d=0,l=r.length;d ${t} ]*>.*?<\/a><\/p>/g,"").replace(/ =p))){a=o===61?1:2;break}}if(e.sCount[u]<0)continue;let f=!1;for(let m=0,p=r.length;m 3||e.sCount[a]<0)continue;let c=!1;for(let d=0,l=r.length;d ${t} ]*>.*?<\/a><\/p>/g,"").replace(/ne((2147483647-i)/c)&&ke("overflow"),i+=(s-r)*c,r=s;for(let d of e)if(d
${t}`:t,body:e.body};let r=`
]*>.*?<\/a>/g,"").trim()}function nl(e){return e.includes("GroupId")&&e.includes("Src")&&e.some(n=>/^S\d+_Id$/i.test(n))&&e.some(n=>/^S\d+_Q$/i.test(n))&&e.some(n=>/^S\d+_A$/i.test(n))?e.filter(n=>n==="GroupId"||n==="Src"||/^S\d+_Id$/i.test(n)):[]}function rl(e){let t=[];return{text:e.replace($d,r=>{let i=`@@QA_GROUP_INLINE_CODE_${t.length}@@`;return t.push(r),i}),restore:r=>t.reduce((i,a,o)=>i.split(`@@QA_GROUP_INLINE_CODE_${o}@@`).join(a),r)}}var il="manual-render-v3",Ae=class{constructor(t=new Oe){this.deckResolutionService=t}resolve(t,n){let r=al(t.cardType,n),i=this.deckResolutionService.resolve(t,n.defaultDeck,n.folderDeckMode),a=i.resolvedDeck.value,o=n.noteFieldMappings[B(t.cardType,r)]??null,u=t.cardType==="cloze"&&t.clozeMode==="all"?"all":void 0,s={version:il,cardType:t.cardType,clozeMode:u,noteModel:r,mapping:o,addObsidianBacklink:n.addObsidianBacklink,obsidianBacklinkLabel:n.obsidianBacklinkLabel,obsidianBacklinkPlacement:n.obsidianBacklinkPlacement,convertHighlightsToCloze:n.convertHighlightsToCloze,keepPureTagLinesInCardBody:n.keepPureTagLinesInCardBody},c=Q(JSON.stringify(s));return{deck:a,noteModel:r,renderConfigHash:c,warnings:i.warnings}}};function al(e,t){if(Ai(e)){if(!t.clozeNoteType.trim())throw new S("errors.noteFieldMapping.noteTypeNotSelected.cloze");return t.clozeNoteType}if(!t.qaNoteType.trim())throw new S("errors.noteFieldMapping.noteTypeNotSelected.basic");return t.qaNoteType}var Zr=/`[^`\n]+`/g,Yr=/```[\s\S]*?```|~~~[\s\S]*?~~~/g,Sn=/==(.+?)==/g,Xr=/(?:(?0&&i.add(u)}for(let o of r.text.matchAll(Xr)){let u=o[1],s=u?Number(u):e.clozeMode==="all"?1:a++;Number.isInteger(s)&&s>0&&i.add(s)}return i}function $e(e,t,n){let r=[];return{text:e.replace(t,a=>{let o=`@@${n}_${r.length}@@`;return r.push(a),o}),restore:(a,o=u=>u)=>r.reduce((u,s,c)=>u.split(`@@${n}_${c}@@`).join(o(s)),a)}}var Fn=class{constructor(t=new Ae){this.renderConfigService=t}plan(t,n,r,i){let a=new Map,o=new Set(n.pendingWriteBack.filter(x=>x.markerKind!=="group-gi").map(x=>Le(x.filePath,x.blockStartLine,x.rawBlockHash))),u=new Set,s=[],c=[],d=[],l=[],f=[],m=[],p=new Map,F=0;for(let x of t){if(a.has(x.syncKey))throw new Error(`Duplicate syncKey detected in current scan: ${x.syncKey}`);if(a.set(x.syncKey,x),x.noteId!==void 0){let R=z(x.noteId);if(u.has(R))throw new Error(`Duplicate noteId detected in current scan: ${x.noteId}`);u.add(R)}let C=x.noteId!==void 0?n.cards[z(x.noteId)]:void 0,h=this.renderConfigService.resolve(x,i);for(let R of h.warnings)p.set(We(R),R);let M=x.noteId,T=Le(x.filePath,x.blockStartLine,x.rawBlockHash),D={card:{...x,noteId:M},noteId:M,deck:h.deck,noteModel:h.noteModel,renderConfigHash:h.renderConfigHash};if(!M){s.push(D);continue}if(ul(C,x,i)){c.push(D);continue}if(l.push(D),(x.idMarkerState!=="present-valid"||x.noteIdSource!=="marker"||o.has(T))&&m.push(D),!C){d.push(D);continue}let L=C.rawBlockHash!==x.rawBlockHash||C.renderConfigHash!==h.renderConfigHash||!Qi(C.tagsHint,x.tagsHint)||C.orphan,A=C.deck!==h.deck;L&&d.push(D),A&&f.push(D),!L&&!A&&(F+=1)}let k=new Set(r),b=Object.values(n.cards).filter(x=>k.has(x.filePath)&&!u.has(z(x.noteId)));return{toCreate:s,toRebuild:c,toUpdate:d,toVerifyDeck:l,toChangeDeck:f,toRewriteMarker:m,toOrphan:b,unchangedCards:F,warnings:Array.from(p.values())}}};function ul(e,t,n){if(!e||e.cardType!=="cloze"||t.cardType!=="cloze")return!1;let r=Se(e.cardType,e.clozeMode);if(r!=="sequential"||t.clozeMode!=="all")return!1;let i=Jr({bodyMarkdown:e.bodyMarkdown,clozeMode:r,convertHighlightsToCloze:n.convertHighlightsToCloze}),a=Jr({bodyMarkdown:t.bodyMarkdown,clozeMode:t.clozeMode,convertHighlightsToCloze:n.convertHighlightsToCloze});return i.size>a.size}var po=new ot({breaks:!0,html:!0,linkify:!0}),sl=/(?`\\[${k.trim()}\\]`),c=c.replace(cl,(F,k)=>`\\(${k.trim()}\\)`),i&&r.convertHighlightsToCloze&&(c=c.replace(Sn,"{$1}")),i&&(c=c.replace(Xr,(F,k,b)=>`{{c${k?Number(k):n.card.clozeMode==="all"?1:l++}::${b}}}`)),c=c.replace(ll,(F,k)=>{let b=r.resourceResolver.resolveEmbed(k,n.card.filePath);return b?(d.push({kind:b.kind,fileName:b.fileName,absolutePath:b.absolutePath,altText:b.altText}),b.kind==="audio"?`[sound:${b.fileName}]`:``):F}),c=c.replace(pl,(F,k)=>{let b=r.resourceResolver.resolveWikiLink(k,n.card.filePath);return b?`${st(b.displayText)}`:F}),c=c.replace(Sn,"$1");let f=$e(c,dl,"MATH");c=f.text,c=s.restore(c),c=u.restore(c);let m=(a?po.renderInline(c):po.render(c)).trim(),p=f.restore(m,st);return{html:a?p:bn(p),media:d}}};function fl(e){let t=new Set;return e.filter(n=>{let r=`${n.kind}:${n.absolutePath}:${n.fileName}`;return t.has(r)?!1:(t.add(r),!0)})}function st(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}var ct=class extends S{constructor(t){super("errors.currentFileOutOfScope",{filePath:t}),this.name="CurrentFileOutOfScopeError"}},Ue=class extends S{constructor(){super("errors.runScopeNotConfigured"),this.name="RunScopeNotConfiguredError"}},wn=class{constructor(t,n,r,i=new Zt(t),a=new Fn,o=new Mn,u=new Ot(r),s=new Yt(t),c=new Ae,d=()=>Date.now()){this.vaultGateway=t;this.pluginStateRepository=n;this.ankiGateway=r;this.fileIndexerService=i;this.diffPlannerService=a;this.renderer=o;this.ankiBatchExecutor=u;this.markdownWriteBackService=s;this.scanScopeService=new Pe;if(this.qaGroupSyncService=new Cn(r,void 0,void 0,void 0,void 0,void 0,void 0,this.vaultGateway.createBacklink.bind(this.vaultGateway)),gl(c)){this.renderConfigService=c,this.now=d;return}this.renderConfigService=new Ae,this.now=c}async syncVault(t){pe(t),this.assertRunScopeConfigured(t);let n=await this.pluginStateRepository.load(),r=await this.fileIndexerService.indexVault(t,n);return this.syncIndexedResult(r,n,t)}async syncFile(t,n){if(pe(n),this.assertRunScopeConfigured(n),!this.scanScopeService.isPathInScope(t,n.scopeMode,n.includeFolders,n.excludeFolders))throw new ct(t);let r=await this.pluginStateRepository.load(),i=await this.fileIndexerService.indexFile(t,n,r);return this.syncIndexedResult(i,r,n)}assertRunScopeConfigured(t){if(!gt(t.scopeMode,t.includeFolders))throw new Ue}async syncIndexedResult(t,n,r){let i=this.diffPlannerService.plan(t.cards,n,t.scopedFilePaths,r),a={addObsidianBacklink:r.addObsidianBacklink,obsidianBacklinkLabel:r.obsidianBacklinkLabel,obsidianBacklinkPlacement:r.obsidianBacklinkPlacement,convertHighlightsToCloze:r.convertHighlightsToCloze,keepPureTagLinesInCardBody:r.keepPureTagLinesInCardBody,resourceResolver:this.vaultGateway},o=new Map;for(let m of[...i.toCreate,...i.toRebuild,...i.toUpdate])o.has(m.card.syncKey)||o.set(m.card.syncKey,this.renderer.render(m,a));let u=await this.ankiBatchExecutor.execute(i,o,m=>Promise.resolve(this.renderer.render(m,a)),r.noteFieldMappings),s=await this.qaGroupSyncService.sync(t.groupBlocks,n,r),c=new Map(t.indexedFiles.map(m=>[m.filePath,m])),d=await this.markdownWriteBackService.write(u.markerWrites,c,s.markerWrites),l=ml(n,t.scopedFilePaths,s.syncedGroupBlocks),f=this.buildNextState(n,t.cards,t.indexedFiles,s.syncedGroupBlocks,r,new Set([...u.touchedSyncKeys,...s.touchedSyncKeys,...d.writtenSyncKeys]),u.resolvedNoteIds,i.toOrphan,l);if(f.pendingWriteBack=[...n.pendingWriteBack.filter(m=>!new Set(t.scopedFilePaths).has(m.filePath)),...d.pendingEntries],this.markFilesDirty(f,[...d.failureFiles.map(m=>m.filePath),...d.conflictFiles]),await this.pluginStateRepository.save(f),d.failureFiles.length>0)throw this.createWriteBackFailureError(d.failureFiles);return{scannedFiles:t.scannedFiles,scannedCards:t.cards.length+t.groupBlocks.length,created:u.created+s.created,rebuilt:u.rebuilt,updated:u.updated+s.updated,migratedNoteTypes:u.migratedNoteTypes+s.migratedNoteTypes,migratedDecks:u.migratedDecks+s.migratedDecks,orphaned:i.toOrphan.length+l.length,uploadedMedia:u.uploadedMedia,skippedUnchangedCards:t.skippedUnchangedCards,rewrittenMarkers:d.writtenSyncKeys.length,markerWriteConflictFiles:d.conflictFiles,warnings:hl(i.warnings,s.warnings)}}buildNextState(t,n,r,i,a,o,u,s,c){let d=this.now(),l=Un(a),f=new Set(r.filter(k=>k.content!==void 0).map(k=>k.filePath)),m=new Map;for(let k of i){let b=m.get(k.filePath);b?b.push(k):m.set(k.filePath,[k])}let p={files:{...t.files},cards:{...t.cards},groupBlocks:{...t.groupBlocks??{}},pendingWriteBack:[...t.pendingWriteBack]};for(let k of f)delete p.files[k];for(let[k,b]of Object.entries(p.cards))f.has(b.filePath)&&delete p.cards[k];for(let[k,b]of Object.entries(p.groupBlocks??{}))f.has(b.filePath)&&delete p.groupBlocks?.[k];let F=new Map;for(let k of n){let b=u.get(k.syncKey)??k.noteId;b!==void 0&&F.set(k.syncKey,b)}for(let k of r){if(k.content===void 0)continue;let b=Array.from(new Set(k.cards.map(x=>F.get(x.syncKey)).filter(x=>x!==void 0)));p.files[k.filePath]={filePath:k.filePath,fileHash:k.fileHash,fileStamp:k.fileStamp,deckRulesFingerprint:l,lastIndexedAt:d,noteIds:b,groupIds:(m.get(k.filePath)??[]).map(x=>x.groupId)}}for(let k of n){let b=F.get(k.syncKey);if(b===void 0)continue;let x=t.cards[z(b)]??(k.noteId!==void 0?t.cards[z(k.noteId)]:void 0),C=this.renderConfigService.resolve(k,a);p.cards[z(b)]={noteId:b,filePath:k.filePath,heading:k.heading,backlinkHeadingText:k.backlinkHeadingText,headingLevel:k.headingLevel,bodyMarkdown:k.bodyMarkdown,cardType:k.cardType,clozeMode:k.clozeMode,blockStartOffset:k.blockStartOffset,blockEndOffset:k.blockEndOffset,blockStartLine:k.blockStartLine,bodyStartLine:k.bodyStartLine,blockEndLine:k.blockEndLine,contentEndLine:k.contentEndLine,markerLine:k.markerLine,rawBlockText:k.rawBlockText,rawBlockHash:k.rawBlockHash,renderConfigHash:C.renderConfigHash,deck:C.deck,deckHint:k.deckHint,deckHintSource:k.deckHintSource,deckWarnings:[...k.deckWarnings],tagsHint:k.tagsHint,lastSyncedAt:o.has(k.syncKey)?d:x?.lastSyncedAt??0,orphan:!1}}for(let k of s)p.cards[z(k.noteId)]={...k,orphan:!0};for(let k of i)p.groupBlocks??(p.groupBlocks={}),p.groupBlocks[k.groupId]=k;for(let k of c)p.groupBlocks??(p.groupBlocks={}),p.groupBlocks[k.groupId]={...k,orphan:!0};return p}markFilesDirty(t,n){for(let r of new Set(n))t.files[r]&&(t.files[r]={...t.files[r],fileHash:"",fileStamp:""})}createWriteBackFailureError(t){return new S("errors.writeBack.summary",{fileCount:t.length},{failures:t})}};function gl(e){return typeof e=="object"&&e!==null&&"resolve"in e}function ml(e,t,n){let r=new Set(t),i=new Set(n.map(a=>a.groupId));return Object.values(e.groupBlocks??{}).filter(a=>r.has(a.filePath)&&!i.has(a.groupId)).map(a=>({...a,orphan:!0}))}function hl(...e){let t=new Map;for(let n of e)for(let r of n)t.set(We(r),r);return[...t.values()]}var dt=class extends fo.Plugin{constructor(){super(...arguments);this.settings=O;this.noticeService=new Nt;this.ankiGateway=new wt(()=>this.settings.ankiConnectUrl);this.deckTemplateInsertionService=new mt}async onload(){let n=new vt(this);this.pluginConfigRepository=new Et(n);let r=new It(n),i=new At(this.app);this.vaultGateway=i;try{this.settings=await this.pluginConfigRepository.load()}catch(o){console.error("Failed to load plugin settings, falling back to defaults.",o),this.settings=O,this.noticeService.error(g("notice.invalidSettingsRestored"))}let a=new wn(i,r,this.ankiGateway);this.syncCurrentFileUseCase=new Ft(a),this.syncVaultUseCase=new Mt(a),this.clearCurrentFileSyncedCardsUseCase=new St(r,this.ankiGateway,i),this.cleanupEmptyDecksUseCase=new ht(this.ankiGateway),Di(this),this.addSettingTab(new Gt(this))}async updateSettings(n){if(!this.pluginConfigRepository)return;let r=Ce({...this.settings,...n});try{await this.pluginConfigRepository.save(r),this.settings=r}catch(i){this.noticeService.error(xe(i,"notice.failedSavePluginSettings"))}}async listNoteModels(){return this.ankiGateway.listNoteModels()}async getModelFieldNamesByModelNames(n){return this.ankiGateway.getModelFieldNamesByModelNames(n)}async getNoteModelDetails(n){return this.ankiGateway.getModelDetails(n)}async listFolderTree(){return this.vaultGateway?this.vaultGateway.listFolderTree():[]}async runSyncCurrentFile(){let n=this.app.workspace.getActiveFile();if(!n||n.extension.toLowerCase()!=="md"){this.noticeService.error(g("notice.noActiveMarkdownForSync"));return}if(!this.syncCurrentFileUseCase){this.noticeService.error(g("notice.syncUseCaseNotInitialized"));return}try{let r=await this.syncCurrentFileUseCase.execute(n.path,this.settings);this.noticeService.showSyncSummary("currentFile",r)}catch(r){if(r instanceof ct||r instanceof Ue){this.noticeService.info(lt(r));return}console.error("Current file sync failed.",r),this.noticeService.error(xe(r,"notice.currentFileSyncFailed"))}}async runSyncVault(){if(!this.syncVaultUseCase){this.noticeService.error(g("notice.syncUseCaseNotInitialized"));return}try{let n=await this.syncVaultUseCase.execute(this.settings);this.noticeService.showSyncSummary("vault",n)}catch(n){if(n instanceof Ue){this.noticeService.info(lt(n));return}console.error("Vault sync failed.",n),this.noticeService.error(xe(n,"notice.vaultSyncFailed"))}}async insertDeckTemplateToCurrentFile(){let n=this.app.workspace.getActiveFile();if(!n||n.extension.toLowerCase()!=="md"){this.noticeService.error(g("notice.noActiveMarkdownForDeckTemplateInsertion"));return}if(!this.vaultGateway){this.noticeService.error(g("notice.vaultGatewayNotInitialized"));return}try{let r=await this.vaultGateway.readMarkdownFile(n.path);if(!r){this.noticeService.error(g("notice.markdownFileNotFound",{filePath:n.path}));return}let i=this.deckTemplateInsertionService.insert(r,this.settings.fileDeckMarker,this.settings.fileDeckTemplate,this.settings.fileDeckInsertLocation);if(i.nextContent===i.expectedContent){this.noticeService.info(g("notice.deckTemplateAlreadyCurrent"));return}await this.vaultGateway.replaceMarkdownFile(n.path,i.expectedContent,i.nextContent),this.noticeService.info(g("notice.deckTemplateInserted",{deck:i.insertedDeck}))}catch(r){console.error("Deck template insertion failed.",r),this.noticeService.error(xe(r,"notice.deckTemplateInsertionFailed"))}}async runClearCurrentFileSyncedCards(){let n=this.app.workspace.getActiveFile();if(!n||n.extension.toLowerCase()!=="md"){this.noticeService.error(g("notice.noActiveMarkdownForReset"));return}if(!this.clearCurrentFileSyncedCardsUseCase){this.noticeService.error(g("notice.clearCurrentFileUseCaseNotInitialized"));return}try{if(!await this.clearCurrentFileSyncedCardsUseCase.hasTrackedCards(n.path)){this.noticeService.info(g("notice.noTrackedCardsInCurrentFile"));return}let i=await this.clearCurrentFileSyncedCardsUseCase.execute(n.path);this.noticeService.showClearCurrentFileSummary(i)}catch(r){console.error("Clear current file synced cards failed.",r),this.noticeService.error(xe(r,"notice.clearCurrentFileFailed"))}}async runCleanupEmptyDecks(){if(!this.cleanupEmptyDecksUseCase){this.noticeService.error(g("notice.cleanupEmptyDecksUseCaseNotInitialized"));return}try{let n=await this.cleanupEmptyDecksUseCase.listCandidates();if(n.length===0){this.noticeService.info(g("notice.noEmptyDeckCandidates"));return}let r=await new Lt(this.app,n).openAndGetSelection();if(r===null){this.noticeService.info(g("notice.cleanupEmptyDecksCancelled"));return}let i=await this.cleanupEmptyDecksUseCase.execute(r,n);this.noticeService.showCleanupEmptyDecksSummary(i)}catch(n){console.error("Cleanup empty decks failed.",n),this.noticeService.error(xe(n,"notice.cleanupEmptyDecksFailed"))}}};var kl=dt;
+`;break;default:}return r};qe.prototype.render=function(e,t,n){let r="",i=this.rules;for(let a=0,o=e.length;a
=4||e.src.charCodeAt(i)!==62)return!1;if(r)return!0;let u=[],s=[],c=[],d=[],l=e.md.block.ruler.getRules("blockquote"),f=e.parentType;e.parentType="blockquote";let m=!1,p;for(p=t;p=4||e.src.charCodeAt(i)!==91)return!1;function u(x){let C=e.lineMax;if(x>=C||e.isEmpty(x))return null;let h=!1;if(e.sCount[x]-e.blkIndent>3&&(h=!0),e.sCount[x]<0&&(h=!0),!h){let D=e.md.block.ruler.getRules("reference"),L=e.parentType;e.parentType="reference";let A=!1;for(let R=0,y=D.length;R
ne((2147483647-i)/c)&&ke("overflow"),i+=(s-r)*c,r=s;for(let d of e)if(d
${t}`:t,body:e.body};let r=`
]*>.*?<\/a>/g,"").trim()}function nl(e){return e.includes("GroupId")&&e.includes("Src")&&e.some(n=>/^S\d+_Id$/i.test(n))&&e.some(n=>/^S\d+_Q$/i.test(n))&&e.some(n=>/^S\d+_A$/i.test(n))?e.filter(n=>n==="GroupId"||n==="Src"||/^S\d+_Id$/i.test(n)):[]}function rl(e){let t=[];return{text:e.replace($d,r=>{let i=`@@QA_GROUP_INLINE_CODE_${t.length}@@`;return t.push(r),i}),restore:r=>t.reduce((i,a,o)=>i.split(`@@QA_GROUP_INLINE_CODE_${o}@@`).join(a),r)}}var il="manual-render-v3",Ae=class{constructor(t=new Oe){this.deckResolutionService=t}resolve(t,n){let r=al(t.cardType,n),i=this.deckResolutionService.resolve(t,n.defaultDeck,n.folderDeckMode),a=i.resolvedDeck.value,o=n.noteFieldMappings[B(t.cardType,r)]??null,u=t.cardType==="cloze"&&t.clozeMode==="all"?"all":void 0,s={version:il,cardType:t.cardType,clozeMode:u,noteModel:r,mapping:o,addObsidianBacklink:n.addObsidianBacklink,obsidianBacklinkLabel:n.obsidianBacklinkLabel,obsidianBacklinkPlacement:n.obsidianBacklinkPlacement,convertHighlightsToCloze:n.convertHighlightsToCloze,keepPureTagLinesInCardBody:n.keepPureTagLinesInCardBody},c=Q(JSON.stringify(s));return{deck:a,noteModel:r,renderConfigHash:c,warnings:i.warnings}}};function al(e,t){if(Ei(e)){if(!t.clozeNoteType.trim())throw new S("errors.noteFieldMapping.noteTypeNotSelected.cloze");return t.clozeNoteType}if(!t.qaNoteType.trim())throw new S("errors.noteFieldMapping.noteTypeNotSelected.basic");return t.qaNoteType}var Zr=/`[^`\n]+`/g,Yr=/```[\s\S]*?```|~~~[\s\S]*?~~~/g,Sn=/==(.+?)==/g,Xr=/(?:(?0&&i.add(u)}for(let o of r.text.matchAll(Xr)){let u=o[1],s=u?Number(u):e.clozeMode==="all"?1:a++;Number.isInteger(s)&&s>0&&i.add(s)}return i}function $e(e,t,n){let r=[];return{text:e.replace(t,a=>{let o=`@@${n}_${r.length}@@`;return r.push(a),o}),restore:(a,o=u=>u)=>r.reduce((u,s,c)=>u.split(`@@${n}_${c}@@`).join(o(s)),a)}}var Fn=class{constructor(t=new Ae){this.renderConfigService=t}plan(t,n,r,i){let a=new Map,o=new Set(n.pendingWriteBack.filter(x=>x.markerKind!=="group-gi").map(x=>Le(x.filePath,x.blockStartLine,x.rawBlockHash))),u=new Set,s=[],c=[],d=[],l=[],f=[],m=[],p=new Map,F=0;for(let x of t){if(a.has(x.syncKey))throw new Error(`Duplicate syncKey detected in current scan: ${x.syncKey}`);if(a.set(x.syncKey,x),x.noteId!==void 0){let R=z(x.noteId);if(u.has(R))throw new Error(`Duplicate noteId detected in current scan: ${x.noteId}`);u.add(R)}let C=x.noteId!==void 0?n.cards[z(x.noteId)]:void 0,h=this.renderConfigService.resolve(x,i);for(let R of h.warnings)p.set(We(R),R);let M=x.noteId,T=Le(x.filePath,x.blockStartLine,x.rawBlockHash),D={card:{...x,noteId:M},noteId:M,deck:h.deck,noteModel:h.noteModel,renderConfigHash:h.renderConfigHash};if(!M){s.push(D);continue}if(ul(C,x,i)){c.push(D);continue}if(l.push(D),(x.idMarkerState!=="present-valid"||x.noteIdSource!=="marker"||o.has(T))&&m.push(D),!C){d.push(D);continue}let L=C.rawBlockHash!==x.rawBlockHash||C.renderConfigHash!==h.renderConfigHash||!Vi(C.tagsHint,x.tagsHint)||C.orphan,A=C.deck!==h.deck;L&&d.push(D),A&&f.push(D),!L&&!A&&(F+=1)}let k=new Set(r),b=Object.values(n.cards).filter(x=>k.has(x.filePath)&&!u.has(z(x.noteId)));return{toCreate:s,toRebuild:c,toUpdate:d,toVerifyDeck:l,toChangeDeck:f,toRewriteMarker:m,toOrphan:b,unchangedCards:F,warnings:Array.from(p.values())}}};function ul(e,t,n){if(!e||e.cardType!=="cloze"||t.cardType!=="cloze")return!1;let r=Se(e.cardType,e.clozeMode);if(r!=="sequential"||t.clozeMode!=="all")return!1;let i=Jr({bodyMarkdown:e.bodyMarkdown,clozeMode:r,convertHighlightsToCloze:n.convertHighlightsToCloze}),a=Jr({bodyMarkdown:t.bodyMarkdown,clozeMode:t.clozeMode,convertHighlightsToCloze:n.convertHighlightsToCloze});return i.size>a.size}var fo=new ot({breaks:!0,html:!0,linkify:!0}),sl=/(?`\\[${k.trim()}\\]`),c=c.replace(cl,(F,k)=>`\\(${k.trim()}\\)`),i&&r.convertHighlightsToCloze&&(c=c.replace(Sn,"{$1}")),i&&(c=c.replace(Xr,(F,k,b)=>`{{c${k?Number(k):n.card.clozeMode==="all"?1:l++}::${b}}}`)),c=c.replace(ll,(F,k)=>{let b=r.resourceResolver.resolveEmbed(k,n.card.filePath);return b?(d.push({kind:b.kind,fileName:b.fileName,absolutePath:b.absolutePath,altText:b.altText}),b.kind==="audio"?`[sound:${b.fileName}]`:``):F}),c=c.replace(pl,(F,k)=>{let b=r.resourceResolver.resolveWikiLink(k,n.card.filePath);return b?`${st(b.displayText)}`:F}),c=c.replace(Sn,"$1");let f=$e(c,dl,"MATH");c=f.text,c=s.restore(c),c=u.restore(c);let m=(a?fo.renderInline(c):fo.render(c)).trim(),p=f.restore(m,st);return{html:a?p:bn(p),media:d}}};function fl(e){let t=new Set;return e.filter(n=>{let r=`${n.kind}:${n.absolutePath}:${n.fileName}`;return t.has(r)?!1:(t.add(r),!0)})}function st(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}var ct=class extends S{constructor(t){super("errors.currentFileOutOfScope",{filePath:t}),this.name="CurrentFileOutOfScopeError"}},Ue=class extends S{constructor(){super("errors.runScopeNotConfigured"),this.name="RunScopeNotConfiguredError"}},wn=class{constructor(t,n,r,i=new Zt(t),a=new Fn,o=new Mn,u=new Ot(r),s=new Yt(t),c=new Ae,d=()=>Date.now()){this.vaultGateway=t;this.pluginStateRepository=n;this.ankiGateway=r;this.fileIndexerService=i;this.diffPlannerService=a;this.renderer=o;this.ankiBatchExecutor=u;this.markdownWriteBackService=s;this.scanScopeService=new Pe;if(this.qaGroupSyncService=new Cn(r,void 0,void 0,void 0,void 0,void 0,void 0,this.vaultGateway.createBacklink.bind(this.vaultGateway)),gl(c)){this.renderConfigService=c,this.now=d;return}this.renderConfigService=new Ae,this.now=c}async syncVault(t){pe(t),this.assertRunScopeConfigured(t);let n=await this.pluginStateRepository.load(),r=await this.fileIndexerService.indexVault(t,n);return this.syncIndexedResult(r,n,t)}async syncFile(t,n){if(pe(n),this.assertRunScopeConfigured(n),!this.scanScopeService.isPathInScope(t,n.scopeMode,n.includeFolders,n.excludeFolders))throw new ct(t);let r=await this.pluginStateRepository.load(),i=await this.fileIndexerService.indexFile(t,n,r);return this.syncIndexedResult(i,r,n)}assertRunScopeConfigured(t){if(!gt(t.scopeMode,t.includeFolders))throw new Ue}async syncIndexedResult(t,n,r){let i=this.diffPlannerService.plan(t.cards,n,t.scopedFilePaths,r),a={addObsidianBacklink:r.addObsidianBacklink,obsidianBacklinkLabel:r.obsidianBacklinkLabel,obsidianBacklinkPlacement:r.obsidianBacklinkPlacement,convertHighlightsToCloze:r.convertHighlightsToCloze,keepPureTagLinesInCardBody:r.keepPureTagLinesInCardBody,resourceResolver:this.vaultGateway},o=new Map;for(let m of[...i.toCreate,...i.toRebuild,...i.toUpdate])o.has(m.card.syncKey)||o.set(m.card.syncKey,this.renderer.render(m,a));let u=await this.ankiBatchExecutor.execute(i,o,m=>Promise.resolve(this.renderer.render(m,a)),r.noteFieldMappings),s=await this.qaGroupSyncService.sync(t.groupBlocks,n,r),c=new Map(t.indexedFiles.map(m=>[m.filePath,m])),d=await this.markdownWriteBackService.write(u.markerWrites,c,s.markerWrites),l=ml(n,t.scopedFilePaths,s.syncedGroupBlocks),f=this.buildNextState(n,t.cards,t.indexedFiles,s.syncedGroupBlocks,r,new Set([...u.touchedSyncKeys,...s.touchedSyncKeys,...d.writtenSyncKeys]),u.resolvedNoteIds,i.toOrphan,l);if(f.pendingWriteBack=[...n.pendingWriteBack.filter(m=>!new Set(t.scopedFilePaths).has(m.filePath)),...d.pendingEntries],this.markFilesDirty(f,[...d.failureFiles.map(m=>m.filePath),...d.conflictFiles]),await this.pluginStateRepository.save(f),d.failureFiles.length>0)throw this.createWriteBackFailureError(d.failureFiles);return{scannedFiles:t.scannedFiles,scannedCards:t.cards.length+t.groupBlocks.length,created:u.created+s.created,rebuilt:u.rebuilt,updated:u.updated+s.updated,migratedNoteTypes:u.migratedNoteTypes+s.migratedNoteTypes,migratedDecks:u.migratedDecks+s.migratedDecks,orphaned:i.toOrphan.length+l.length,uploadedMedia:u.uploadedMedia,skippedUnchangedCards:t.skippedUnchangedCards,rewrittenMarkers:d.writtenSyncKeys.length,markerWriteConflictFiles:d.conflictFiles,warnings:hl(i.warnings,s.warnings)}}buildNextState(t,n,r,i,a,o,u,s,c){let d=this.now(),l=Un(a),f=new Set(r.filter(k=>k.content!==void 0).map(k=>k.filePath)),m=new Map;for(let k of i){let b=m.get(k.filePath);b?b.push(k):m.set(k.filePath,[k])}let p={files:{...t.files},cards:{...t.cards},groupBlocks:{...t.groupBlocks??{}},pendingWriteBack:[...t.pendingWriteBack]};for(let k of f)delete p.files[k];for(let[k,b]of Object.entries(p.cards))f.has(b.filePath)&&delete p.cards[k];for(let[k,b]of Object.entries(p.groupBlocks??{}))f.has(b.filePath)&&delete p.groupBlocks?.[k];let F=new Map;for(let k of n){let b=u.get(k.syncKey)??k.noteId;b!==void 0&&F.set(k.syncKey,b)}for(let k of r){if(k.content===void 0)continue;let b=Array.from(new Set(k.cards.map(x=>F.get(x.syncKey)).filter(x=>x!==void 0)));p.files[k.filePath]={filePath:k.filePath,fileHash:k.fileHash,fileStamp:k.fileStamp,deckRulesFingerprint:l,lastIndexedAt:d,noteIds:b,groupIds:(m.get(k.filePath)??[]).map(x=>x.groupId)}}for(let k of n){let b=F.get(k.syncKey);if(b===void 0)continue;let x=t.cards[z(b)]??(k.noteId!==void 0?t.cards[z(k.noteId)]:void 0),C=this.renderConfigService.resolve(k,a);p.cards[z(b)]={noteId:b,filePath:k.filePath,heading:k.heading,backlinkHeadingText:k.backlinkHeadingText,headingLevel:k.headingLevel,bodyMarkdown:k.bodyMarkdown,cardType:k.cardType,clozeMode:k.clozeMode,blockStartOffset:k.blockStartOffset,blockEndOffset:k.blockEndOffset,blockStartLine:k.blockStartLine,bodyStartLine:k.bodyStartLine,blockEndLine:k.blockEndLine,contentEndLine:k.contentEndLine,markerLine:k.markerLine,rawBlockText:k.rawBlockText,rawBlockHash:k.rawBlockHash,renderConfigHash:C.renderConfigHash,deck:C.deck,deckHint:k.deckHint,deckHintSource:k.deckHintSource,deckWarnings:[...k.deckWarnings],tagsHint:k.tagsHint,lastSyncedAt:o.has(k.syncKey)?d:x?.lastSyncedAt??0,orphan:!1}}for(let k of s)p.cards[z(k.noteId)]={...k,orphan:!0};for(let k of i)p.groupBlocks??(p.groupBlocks={}),p.groupBlocks[k.groupId]=k;for(let k of c)p.groupBlocks??(p.groupBlocks={}),p.groupBlocks[k.groupId]={...k,orphan:!0};return p}markFilesDirty(t,n){for(let r of new Set(n))t.files[r]&&(t.files[r]={...t.files[r],fileHash:"",fileStamp:""})}createWriteBackFailureError(t){return new S("errors.writeBack.summary",{fileCount:t.length},{failures:t})}};function gl(e){return typeof e=="object"&&e!==null&&"resolve"in e}function ml(e,t,n){let r=new Set(t),i=new Set(n.map(a=>a.groupId));return Object.values(e.groupBlocks??{}).filter(a=>r.has(a.filePath)&&!i.has(a.groupId)).map(a=>({...a,orphan:!0}))}function hl(...e){let t=new Map;for(let n of e)for(let r of n)t.set(We(r),r);return[...t.values()]}var dt=class extends go.Plugin{constructor(){super(...arguments);this.settings=O;this.noticeService=new Nt;this.ankiGateway=new wt(()=>this.settings.ankiConnectUrl);this.deckTemplateInsertionService=new mt}async onload(){let n=new vt(this);this.pluginConfigRepository=new Et(n);let r=new It(n),i=new At(this.app);this.vaultGateway=i;try{this.settings=await this.pluginConfigRepository.load()}catch(o){console.error("Failed to load plugin settings, falling back to defaults.",o),this.settings=O,this.noticeService.error(g("notice.invalidSettingsRestored"))}let a=new wn(i,r,this.ankiGateway);this.syncCurrentFileUseCase=new Ft(a),this.syncVaultUseCase=new Mt(a),this.clearCurrentFileSyncedCardsUseCase=new St(r,this.ankiGateway,i),this.cleanupEmptyDecksUseCase=new ht(this.ankiGateway),Ai(this),this.addSettingTab(new Gt(this))}async updateSettings(n){if(!this.pluginConfigRepository)return;let r=Ce({...this.settings,...n});try{await this.pluginConfigRepository.save(r),this.settings=r}catch(i){this.noticeService.error(xe(i,"notice.failedSavePluginSettings"))}}async listNoteModels(){return this.ankiGateway.listNoteModels()}async getModelFieldNamesByModelNames(n){return this.ankiGateway.getModelFieldNamesByModelNames(n)}async getNoteModelDetails(n){return this.ankiGateway.getModelDetails(n)}async listFolderTree(){return this.vaultGateway?this.vaultGateway.listFolderTree():[]}async runSyncCurrentFile(){let n=this.app.workspace.getActiveFile();if(!n||n.extension.toLowerCase()!=="md"){this.noticeService.error(g("notice.noActiveMarkdownForSync"));return}if(!this.syncCurrentFileUseCase){this.noticeService.error(g("notice.syncUseCaseNotInitialized"));return}try{let r=await this.syncCurrentFileUseCase.execute(n.path,this.settings);this.noticeService.showSyncSummary("currentFile",r)}catch(r){if(r instanceof ct||r instanceof Ue){this.noticeService.info(lt(r));return}console.error("Current file sync failed.",r),this.noticeService.error(xe(r,"notice.currentFileSyncFailed"))}}async runSyncVault(){if(!this.syncVaultUseCase){this.noticeService.error(g("notice.syncUseCaseNotInitialized"));return}try{let n=await this.syncVaultUseCase.execute(this.settings);this.noticeService.showSyncSummary("vault",n)}catch(n){if(n instanceof Ue){this.noticeService.info(lt(n));return}console.error("Vault sync failed.",n),this.noticeService.error(xe(n,"notice.vaultSyncFailed"))}}async insertDeckTemplateToCurrentFile(){let n=this.app.workspace.getActiveFile();if(!n||n.extension.toLowerCase()!=="md"){this.noticeService.error(g("notice.noActiveMarkdownForDeckTemplateInsertion"));return}if(!this.vaultGateway){this.noticeService.error(g("notice.vaultGatewayNotInitialized"));return}try{let r=await this.vaultGateway.readMarkdownFile(n.path);if(!r){this.noticeService.error(g("notice.markdownFileNotFound",{filePath:n.path}));return}let i=this.deckTemplateInsertionService.insert(r,this.settings.fileDeckMarker,this.settings.fileDeckTemplate,this.settings.fileDeckInsertLocation);if(i.nextContent===i.expectedContent){this.noticeService.info(g("notice.deckTemplateAlreadyCurrent"));return}await this.vaultGateway.replaceMarkdownFile(n.path,i.expectedContent,i.nextContent),this.noticeService.info(g("notice.deckTemplateInserted",{deck:i.insertedDeck}))}catch(r){console.error("Deck template insertion failed.",r),this.noticeService.error(xe(r,"notice.deckTemplateInsertionFailed"))}}async runClearCurrentFileSyncedCards(){let n=this.app.workspace.getActiveFile();if(!n||n.extension.toLowerCase()!=="md"){this.noticeService.error(g("notice.noActiveMarkdownForReset"));return}if(!this.clearCurrentFileSyncedCardsUseCase){this.noticeService.error(g("notice.clearCurrentFileUseCaseNotInitialized"));return}try{if(!await this.clearCurrentFileSyncedCardsUseCase.hasTrackedCards(n.path)){this.noticeService.info(g("notice.noTrackedCardsInCurrentFile"));return}let i=await this.clearCurrentFileSyncedCardsUseCase.execute(n.path);this.noticeService.showClearCurrentFileSummary(i)}catch(r){console.error("Clear current file synced cards failed.",r),this.noticeService.error(xe(r,"notice.clearCurrentFileFailed"))}}async runCleanupEmptyDecks(){if(!this.cleanupEmptyDecksUseCase){this.noticeService.error(g("notice.cleanupEmptyDecksUseCaseNotInitialized"));return}try{let n=await this.cleanupEmptyDecksUseCase.listCandidates();if(n.length===0){this.noticeService.info(g("notice.noEmptyDeckCandidates"));return}let r=await new Lt(this.app,n).openAndGetSelection();if(r===null){this.noticeService.info(g("notice.cleanupEmptyDecksCancelled"));return}let i=await this.cleanupEmptyDecksUseCase.execute(r,n);this.noticeService.showCleanupEmptyDecksSummary(i)}catch(n){console.error("Cleanup empty decks failed.",n),this.noticeService.error(xe(n,"notice.cleanupEmptyDecksFailed"))}}};var kl=dt;
diff --git a/manifest.json b/manifest.json
index f40111a..1e2dedc 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,8 +1,8 @@
{
"id": "anki-heading-sync",
"name": "Anki Heading Sync",
- "version": "1.0.0",
- "minAppVersion": "1.5.0",
+ "version": "1.0.1",
+ "minAppVersion": "1.8.7",
"description": "Focused heading-based Markdown to Anki sync plugin.",
"author": "Dusk",
"authorUrl": "https://github.com/panAtGitHub",
diff --git a/package-lock.json b/package-lock.json
index 808edb8..e05bd0c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "obsidian-anki-heading-sync",
- "version": "1.0.0",
+ "version": "1.0.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "obsidian-anki-heading-sync",
- "version": "1.0.0",
+ "version": "1.0.1",
"license": "MIT",
"dependencies": {
"markdown-it": "^14.1.0"
diff --git a/package.json b/package.json
index 8721838..28ca643 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "obsidian-anki-heading-sync",
- "version": "1.0.0",
+ "version": "1.0.1",
"description": "Focused heading-based Markdown to Anki sync plugin.",
"author": "Dusk",
"main": "dist/plugin/main.js",
diff --git a/src/application/errors/PluginUserError.test.ts b/src/application/errors/PluginUserError.test.ts
index 1ca4286..f182fcd 100644
--- a/src/application/errors/PluginUserError.test.ts
+++ b/src/application/errors/PluginUserError.test.ts
@@ -1,19 +1,26 @@
import { afterEach, describe, expect, it, vi } from "vitest";
+const { getLanguageMock } = vi.hoisted(() => ({
+ getLanguageMock: vi.fn(() => "en"),
+}));
+
+vi.mock("obsidian", () => ({
+ getLanguage: getLanguageMock,
+}));
+
import { PluginUserError, renderPluginFileFailure, renderPluginFileFailuresInline, renderUnknownUserFacingError, renderUserFacingMessage, renderUserMessage } from "./PluginUserError";
-function setNavigatorLanguage(language: string): void {
- vi.stubGlobal("navigator", { language });
+function setObsidianLanguage(language: string): void {
+ getLanguageMock.mockReturnValue(language);
}
describe("PluginUserError", () => {
afterEach(() => {
- vi.unstubAllGlobals();
vi.restoreAllMocks();
});
it("renders plugin-owned errors in English", () => {
- setNavigatorLanguage("en");
+ setObsidianLanguage("en");
const error = new PluginUserError("errors.currentFileOutOfScope", { filePath: "notes/example.md" });
@@ -21,7 +28,7 @@ describe("PluginUserError", () => {
});
it("renders plugin-owned errors in Simplified Chinese", () => {
- setNavigatorLanguage("zh");
+ setObsidianLanguage("zh");
const error = new PluginUserError("errors.currentFileOutOfScope", { filePath: "notes/example.md" });
@@ -29,19 +36,19 @@ describe("PluginUserError", () => {
});
it("renders scope-not-configured errors in English and Chinese", () => {
- setNavigatorLanguage("en");
+ setObsidianLanguage("en");
expect(renderUserMessage(new PluginUserError("errors.runScopeNotConfigured"))).toBe(
"Run scope is not configured. In include mode, select at least one folder before syncing.",
);
- setNavigatorLanguage("zh");
+ setObsidianLanguage("zh");
expect(renderUserMessage(new PluginUserError("errors.runScopeNotConfigured"))).toBe(
"运行范围尚未配置。当前是 include 模式,请至少选择一个文件夹后再同步。",
);
});
it("renders write-back failure summaries with localized detail lines", () => {
- setNavigatorLanguage("zh");
+ setObsidianLanguage("zh");
const error = new PluginUserError(
"errors.writeBack.summary",
@@ -62,7 +69,7 @@ describe("PluginUserError", () => {
});
it("renders raw and keyed user-facing messages plus inline failure lists", () => {
- setNavigatorLanguage("en");
+ setObsidianLanguage("en");
expect(renderUserFacingMessage({ key: "notice.failedSavePluginSettings" })).toBe("Failed to save plugin settings.");
expect(renderUserFacingMessage({ rawMessage: "raw failure" })).toBe("raw failure");
@@ -74,14 +81,14 @@ describe("PluginUserError", () => {
});
it("falls back to raw error messages for unknown errors", () => {
- setNavigatorLanguage("zh");
+ setObsidianLanguage("zh");
expect(renderUnknownUserFacingError(new Error("socket closed"), "notice.vaultSyncFailed")).toBe("socket closed");
});
it("falls back to a translated default when the value is not an Error", () => {
- setNavigatorLanguage("en");
+ setObsidianLanguage("en");
expect(renderUnknownUserFacingError(null, "notice.vaultSyncFailed")).toBe("Vault sync failed.");
});
-});
\ No newline at end of file
+});
diff --git a/src/presentation/i18n/locale.ts b/src/presentation/i18n/locale.ts
index 776bc8f..329e885 100644
--- a/src/presentation/i18n/locale.ts
+++ b/src/presentation/i18n/locale.ts
@@ -1,6 +1,8 @@
+import { getLanguage } from "obsidian";
+
export type PluginLocale = "en" | "zh";
-export function resolvePluginLocale(languageCode = getPreferredLanguage()): PluginLocale {
+export function resolvePluginLocale(languageCode = getLanguage()): PluginLocale {
const normalizedLanguage = languageCode.toLowerCase();
return normalizedLanguage === "zh" || normalizedLanguage.startsWith("zh-") ? "zh" : "en";
}
@@ -8,11 +10,3 @@ export function resolvePluginLocale(languageCode = getPreferredLanguage()): Plug
export function formatList(locale: PluginLocale, items: string[]): string {
return items.join(locale === "zh" ? "、" : ", ");
}
-
-function getPreferredLanguage(): string {
- if (typeof navigator !== "undefined" && typeof navigator.language === "string") {
- return navigator.language;
- }
-
- return "en";
-}
\ No newline at end of file
diff --git a/src/presentation/modals/EmptyDeckSelectionModal.test.ts b/src/presentation/modals/EmptyDeckSelectionModal.test.ts
index a891269..0bf125f 100644
--- a/src/presentation/modals/EmptyDeckSelectionModal.test.ts
+++ b/src/presentation/modals/EmptyDeckSelectionModal.test.ts
@@ -173,12 +173,11 @@ type FakeButtonComponentInstance = InstanceType