fancive_obsidian-parallel-r.../main.js
wujunchen 1fff3cb343 fix: address CR findings — test runner, CI dedup, error cause
- Create scripts/run-tests.mjs to auto-discover test files, replacing
  the 900-char inline test command in package.json (P3-1)
- Add test:only script for CI to avoid duplicate build+typecheck (P2-1)
- Preserve original SyntaxError as cause in responseJson (P2-3)

Change-Id: I51d0c8c51d3b0b648ed5ff4ea282bda070b0d457
2026-04-27 16:04:03 +08:00

111 lines
96 KiB
JavaScript

'use strict';
"use strict";var $t=Object.create;var pe=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var zt=Object.getOwnPropertyNames;var Wt=Object.getPrototypeOf,Yt=Object.prototype.hasOwnProperty;var ft=(n,t)=>{for(var e in t)pe(n,e,{get:t[e],enumerable:!0})},yt=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of zt(t))!Yt.call(n,i)&&i!==e&&pe(n,i,{get:()=>t[i],enumerable:!(r=qt(t,i))||r.enumerable});return n};var he=(n,t,e)=>(e=n!=null?$t(Wt(n)):{},yt(t||!n||!n.__esModule?pe(e,"default",{value:n,enumerable:!0}):e,n)),Xt=n=>yt(pe({},"__esModule",{value:!0}),n);var Sr={};ft(Sr,{__test:()=>Ar,default:()=>xr});module.exports=Xt(Sr);var p=require("obsidian");var At=require("obsidian");var wt=he(require("crypto"));var H={zh:{appTitle:"\u5BF9\u7167\u9605\u8BFB\u7B14\u8BB0",settingsTitle:"Parallel Reader \u8BBE\u7F6E",emptyOpenNote:"\u6253\u5F00\u4E00\u7BC7\u7B14\u8BB0\uFF0C\u7136\u540E\u8FD0\u884C\u547D\u4EE4\uFF1A",emptyNoCache:"\u8BE5\u7B14\u8BB0\u5C1A\u65E0\u5BF9\u7167\u7B14\u8BB0\u7F13\u5B58\u3002\u8FD0\u884C\u547D\u4EE4\uFF1A",commandGenerate:"Parallel Reader: \u4E3A\u5F53\u524D\u7B14\u8BB0\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",displayName:"\u5BF9\u7167\u9605\u8BFB\u7B14\u8BB0",ribbonOpen:"\u6253\u5F00\u5BF9\u7167\u7B14\u8BB0\u9762\u677F",cmdRun:"\u4E3A\u5F53\u524D\u7B14\u8BB0\u751F\u6210\u5BF9\u7167\u7B14\u8BB0\uFF08\u7F13\u5B58\u4F18\u5148\uFF09",cmdRegen:"\u5F3A\u5236\u91CD\u65B0\u751F\u6210\uFF08\u7ED5\u8FC7\u7F13\u5B58\uFF09",cmdOpenView:"\u6253\u5F00\u5BF9\u7167\u7B14\u8BB0\u9762\u677F",cmdExport:"\u5BFC\u51FA\u5F53\u524D\u5BF9\u7167\u7B14\u8BB0\u5230 Vault",cmdCopyMarkdown:"\u590D\u5236\u5F53\u524D\u5BF9\u7167\u7B14\u8BB0 Markdown",cmdCancel:"\u53D6\u6D88\u5F53\u524D\u5BF9\u7167\u7B14\u8BB0\u751F\u6210",cmdClearCurrent:"\u6E05\u9664\u5F53\u524D\u7B14\u8BB0\u7684\u7F13\u5B58",cmdClearAll:"\u6E05\u9664\u6240\u6709\u7F13\u5B58",cmdCardPrev:"\u805A\u7126\u4E0A\u4E00\u5F20\u6458\u8981\u5361\u7247",cmdCardNext:"\u805A\u7126\u4E0B\u4E00\u5F20\u6458\u8981\u5361\u7247",cmdCardJump:"\u8DF3\u8F6C\u5230\u5F53\u524D\u6458\u8981\u5361\u7247\u539F\u6587",actionCancel:"\u53D6\u6D88\u751F\u6210",actionRegenerate:"\u91CD\u65B0\u751F\u6210",actionCopyAll:"\u590D\u5236\u5168\u90E8 Markdown",actionExport:"\u5BFC\u51FA\u5230 Vault",staleBanner:"\u6E90\u7B14\u8BB0\u6216\u751F\u6210\u914D\u7F6E\u5DF2\u4FEE\u6539\uFF0C\u5F53\u524D\u662F\u65E7\u7F13\u5B58\u3002",loadingDefault:"\u6B63\u5728\u751F\u6210\u5BF9\u7167\u7B14\u8BB0...",loadingGenerating:"\u5BF9\u7167\u9605\u8BFB\uFF1A\u8BA9 LLM \u8BFB\u5168\u6587\u5E76\u81EA\u9002\u5E94\u5207\u6BB5...",loadingSubtitle:"\u53EF\u4EE5\u7EE7\u7EED\u9605\u8BFB\u539F\u6587\uFF0C\u751F\u6210\u5B8C\u6210\u540E\u4F1A\u81EA\u52A8\u5237\u65B0\u53F3\u4FA7\u5361\u7247\u3002",errorTitle:"\u751F\u6210\u5931\u8D25",actionCopyError:"\u590D\u5236\u9519\u8BEF\u4FE1\u606F",emptyCard:"\uFF08\u672A\u751F\u6210\uFF09",anchorMismatch:"anchor \u5339\u914D\u5931\u8D25\uFF0C\u65E0\u6CD5\u6EDA\u52A8\u8054\u52A8",menuCopyMarkdown:"\u590D\u5236 Markdown",menuCopyPlain:"\u590D\u5236\u7EAF\u6587\u672C",menuCopyAnchor:"\u590D\u5236 anchor \u5F15\u7528",menuJumpSource:"\u8DF3\u8F6C\u5230\u539F\u6587",menuEditCard:"\u7F16\u8F91\u6B64\u5361\u7247",menuDeleteCard:"\u5220\u9664\u6B64\u5361\u7247",copiedMarkdown:"\u5DF2\u590D\u5236 Markdown",copiedPlain:"\u5DF2\u590D\u5236\u7EAF\u6587\u672C",copiedAnchor:"\u5DF2\u590D\u5236\u5F15\u7528\u539F\u6587",copiedAllMarkdown:"\u5DF2\u590D\u5236\u5168\u90E8 Markdown",copyFailed:"\u590D\u5236\u5931\u8D25\uFF1A{error}",actionFailed:"{label}\u5931\u8D25\uFF1A{error}",exported:"\u5DF2\u5BFC\u51FA \u2192 {path}",noCurrentNote:"\u6CA1\u6709\u5F53\u524D\u7B14\u8BB0",cacheClearedFile:"\u5DF2\u6E05\u9664\u7F13\u5B58\uFF1A{name}",cacheClearedAll:"\u5DF2\u6E05\u9664 {count} \u6761\u7F13\u5B58",noCancelableJob:"\u5F53\u524D\u6CA1\u6709\u53EF\u53D6\u6D88\u7684\u751F\u6210\u4EFB\u52A1",cancelRequested:"\u5DF2\u8BF7\u6C42\u53D6\u6D88\u751F\u6210",cancelRequestedApiInFlight:"\u5DF2\u8BF7\u6C42\u53D6\u6D88\u751F\u6210\uFF1B\u5F53\u524D API \u8BF7\u6C42\u65E0\u6CD5\u7ACB\u5373\u4E2D\u65AD\uFF0C\u8FD4\u56DE\u540E\u4F1A\u4E22\u5F03\u7ED3\u679C\u3002",actionGenerate:"\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",fileMenuGenerate:"\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",fileMenuRegen:"\u5F3A\u5236\u91CD\u65B0\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",fileMenuClear:"\u6E05\u9664\u5BF9\u7167\u7B14\u8BB0\u7F13\u5B58",noExportContent:"\u5F53\u524D\u6CA1\u6709\u53EF\u5BFC\u51FA\u7684\u5BF9\u7167\u7B14\u8BB0",noCopyContent:"\u5F53\u524D\u6CA1\u6709\u53EF\u590D\u5236\u7684\u5BF9\u7167\u7B14\u8BB0",noActiveCard:"\u5F53\u524D\u6CA1\u6709\u53EF\u8DF3\u8F6C\u7684\u6458\u8981\u5361\u7247",viewOpenFailed:"\u65E0\u6CD5\u6253\u5F00\u5BF9\u7167\u7B14\u8BB0\u9762\u677F",confirmRegenerateEditedCards:"\u8FD9\u7BC7\u7B14\u8BB0\u7684\u5BF9\u7167\u5361\u7247\u5DF2\u88AB\u624B\u52A8\u7F16\u8F91\u3002\u91CD\u65B0\u751F\u6210\u4F1A\u8986\u76D6\u8FD9\u4E9B\u4FEE\u6539\uFF0C\u662F\u5426\u7EE7\u7EED\uFF1F",regenerateCancelled:"\u5DF2\u53D6\u6D88\u91CD\u65B0\u751F\u6210",cardDeleted:"\u5DF2\u5220\u9664\u6B64\u5361\u7247",cardSaved:"\u5DF2\u4FDD\u5B58\u6B64\u5361\u7247",editCardTitle:"\u7F16\u8F91\u6458\u8981\u5361\u7247",editCardTitleField:"\u6807\u9898",editCardGistField:"\u9886\u8BFB",editCardBulletsField:"\u8981\u70B9\uFF08\u6BCF\u884C\u4E00\u6761\uFF09",editCardCancel:"\u53D6\u6D88",editCardSave:"\u4FDD\u5B58",openNoteFirst:"\u5148\u6253\u5F00\u4E00\u7BC7\u7B14\u8BB0",alreadyGenerating:"\u8BE5\u7B14\u8BB0\u6B63\u5728\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",emptyNote:"\u7B14\u8BB0\u4E3A\u7A7A",longNoteTruncated:"\u7B14\u8BB0\u8F83\u957F\uFF1A\u4EC5\u53D1\u9001\u524D {count} \u4E2A\u5B57\u7B26\u7ED9\u6A21\u578B",generatingNotice:"\u5BF9\u7167\u9605\u8BFB\uFF1A\u8BA9 LLM \u8BFB\u5168\u6587\u5E76\u81EA\u9002\u5E94\u5207\u6BB5\u2026",noCardsReturned:"LLM \u672A\u8FD4\u56DE\u4EFB\u4F55 card",generationDone:"\u5BF9\u7167\u7B14\u8BB0\u751F\u6210\u5B8C\u6210\uFF1A{count} \u6BB5{suffix}",unanchoredSuffix:"\uFF08\u26A0 {count} \u6BB5 anchor \u672A\u5339\u914D\uFF09",cancelled:"\u5DF2\u53D6\u6D88\u751F\u6210",cancelledError:"\u751F\u6210\u5DF2\u53D6\u6D88",generationFailed:"\u751F\u6210\u5931\u8D25{kind}\uFF1A{error}",errorCustomProviderBaseUrlRequired:"\u81EA\u5B9A\u4E49 provider \u9700\u8981\u586B\u5199 API Base URL\u3002",errorApiBaseUrlMissing:"API Base URL \u672A\u8BBE\u7F6E\u3002\u8BF7\u5728\u8BBE\u7F6E\u91CC\u9009\u62E9 provider \u6216\u586B\u5199\u81EA\u5B9A\u4E49 base URL\u3002",errorModelMissing:"Model \u672A\u8BBE\u7F6E\u3002\u8BF7\u5728\u8BBE\u7F6E\u91CC\u586B\u5199\u6A21\u578B ID\u3002",errorApiKeyMissing:"API key \u672A\u8BBE\u7F6E\u3002\u8BF7\u5728\u8BBE\u7F6E\u91CC\u586B\u5199 API Key{hint}\u3002",errorApiKeyEnvHint:" \u6216\u73AF\u5883\u53D8\u91CF {envVar}",errorLlmNonJson:`LLM \u8FD4\u56DE\u975E JSON\uFF1A
{excerpt}`,errorCustomHeadersJsonParse:"\u81EA\u5B9A\u4E49 headers JSON \u89E3\u6790\u5931\u8D25\uFF1A{error}",errorCustomHeadersJsonObject:"\u81EA\u5B9A\u4E49 headers JSON \u5FC5\u987B\u662F\u5BF9\u8C61",errorCustomHeadersLineFormat:"\u81EA\u5B9A\u4E49 headers \u6BCF\u884C\u683C\u5F0F\u5E94\u4E3A `Header-Name: value`",errorProviderNonJson:`{label} \u8FD4\u56DE\u975E JSON\uFF1A
{excerpt}`,errorProviderRequestFailed:"{label} \u8BF7\u6C42\u5931\u8D25\uFF1A{error}",errorProviderApiStatus:"{label} API \u8FD4\u56DE HTTP {status}\uFF1A{excerpt}",noEditor:"\u627E\u4E0D\u5230\u6E90\u7B14\u8BB0\u5BF9\u5E94\u7684\u7F16\u8F91\u5668\u7A97\u53E3",settingUiLanguageName:"\u754C\u9762\u8BED\u8A00",settingUiLanguageDesc:"\u63A7\u5236\u63D2\u4EF6\u754C\u9762\u3001\u547D\u4EE4\u548C\u63D0\u793A\u6587\u6848\uFF1BAuto \u8DDF\u968F Obsidian/\u7CFB\u7EDF\u8BED\u8A00",settingBackendName:"Backend",settingBackendDesc:"\u751F\u6210 bullet \u7684\u540E\u7AEF\uFF1ACLI \u590D\u7528\u672C\u673A\u767B\u5F55\uFF1BAPI \u652F\u6301 OpenAI/Anthropic/Gemini \u53CA\u517C\u5BB9\u4EE3\u7406",settingCliPathName:"CLI \u8DEF\u5F84\uFF08\u53EF\u9009\uFF09",settingCliPathDesc:"\u7559\u7A7A\u5219\u81EA\u52A8\u63A2\u6D4B\u5E38\u89C1\u4F4D\u7F6E\uFF1BObsidian GUI \u542F\u52A8\u65F6\u4E0D\u7EE7\u627F shell PATH\uFF0C\u5FC5\u8981\u65F6\u586B\u7EDD\u5BF9\u8DEF\u5F84",settingCliPathPlaceholder:"\u4F8B\uFF1A/Users/you/bin/codex",settingCliTimeoutName:"CLI \u8D85\u65F6 (ms)",apiProviderHeader:"API Provider",settingProviderPresetName:"Provider preset",settingProviderPresetDesc:"\u53C2\u8003 OpenClaw \u7684 provider/model \u601D\u8DEF\uFF1Apreset \u53EA\u8D1F\u8D23\u534F\u8BAE\u3001base URL \u548C\u8BA4\u8BC1\u9ED8\u8BA4\u503C",settingApiFormatName:"API format",settingApiFormatDesc:"\u4E0D\u540C provider \u7684 wire protocol\uFF1BOpenAI-compatible \u4EE3\u7406\u901A\u5E38\u9009 Chat Completions",settingBaseUrlName:"Base URL",settingBaseUrlDesc:"\u586B provider \u6839\u5730\u5740\uFF0C\u4E0D\u8981\u9644\u52A0 /chat/completions\uFF1B\u7559\u7A7A\u65F6\u4F7F\u7528 preset \u9ED8\u8BA4\u503C",settingApiKeyName:"API Key",settingApiKeyDesc:"\u672C\u5730 Ollama/LM Studio \u53EF\u7559\u7A7A\uFF1B\u5176\u4ED6 provider \u901A\u5E38\u9700\u8981 key",settingApiKeyEnvName:"API Key \u73AF\u5883\u53D8\u91CF",settingApiKeyEnvDesc:"\u53EF\u9009\uFF1BObsidian GUI \u4E0D\u4E00\u5B9A\u7EE7\u627F shell \u73AF\u5883\uFF0C\u76F4\u63A5\u586B API Key \u66F4\u7A33\u5B9A",settingAuthTypeName:"\u8BA4\u8BC1\u65B9\u5F0F",settingAuthTypeDesc:"Auto \u4F7F\u7528 provider preset\uFF1B\u81EA\u5B9A\u4E49\u4EE3\u7406\u53EF\u6309\u9700\u8981\u6539\u6210 Bearer\u3001x-api-key \u6216 none",settingHeadersName:"\u989D\u5916 headers",settingHeadersDesc:"\u53EF\u9009\u3002\u652F\u6301 JSON \u5BF9\u8C61\u6216\u6BCF\u884C `Header: value`\uFF0C\u7528\u4E8E Cloudflare AI Gateway \u7B49\u4EE3\u7406",settingMaxTokensName:"\u6700\u5927\u8F93\u51FA tokens",settingModelName:"Model",settingModelDescApi:"API \u8C03\u7528\u7684\u6A21\u578B ID\uFF1B\u652F\u6301 OpenClaw \u98CE\u683C provider/model\uFF0C\u82E5 provider \u524D\u7F00\u5339\u914D\u5F53\u524D preset \u4F1A\u81EA\u52A8\u5265\u79BB",settingModelDescCli:"Claude Code \u4E0B\u4F1A\u4F20 --model\uFF1BCodex \u4E0B\u901A\u5E38\u5FFD\u7565\uFF08\u7528 Codex \u9ED8\u8BA4\u914D\u7F6E\uFF09",settingMaxInputName:"\u6700\u5927\u8F93\u5165\u5B57\u7B26\u6570",settingMaxInputDesc:"\u8D85\u8FC7\u8BE5\u957F\u5EA6\u4F1A\u622A\u65AD\u540E\u518D\u53D1\u9001\u7ED9\u6A21\u578B\uFF1B\u957F\u4E0A\u4E0B\u6587\u6A21\u578B\u53EF\u9002\u5F53\u8C03\u5927",promptHeader:"Prompt",settingPromptLanguageName:"\u8F93\u51FA\u8BED\u8A00",settingPromptLanguageDesc:"\u63A7\u5236 title/gist/bullets \u7684\u8BED\u8A00\uFF1Banchor \u59CB\u7EC8\u9010\u5B57\u590D\u5236\u539F\u6587",settingCardRangeName:"\u5361\u7247\u6570\u91CF\u8303\u56F4",settingCardRangeDesc:"\u6A21\u578B\u4F1A\u5728\u8FD9\u4E2A\u8303\u56F4\u5185\u81EA\u9002\u5E94\u5207\u6BB5",settingCustomPromptName:"\u81EA\u5B9A\u4E49 system prompt",settingCustomPromptDesc:"\u53EF\u9009\u3002\u652F\u6301\u53D8\u91CF\uFF1A{minCards}\u3001{maxCards}\u3001{languageInstruction}\u3001{schema}\u3001{example}",settingCustomPromptPlaceholder:"\u7559\u7A7A\u4F7F\u7528\u5185\u7F6E prompt",settingTestBackendName:"\u6D4B\u8BD5\u5F53\u524D\u540E\u7AEF",settingTestBackendDescApi:"\u4F1A\u53D1\u8D77\u4E00\u6B21\u6700\u5C0F LLM \u8BF7\u6C42\u9A8C\u8BC1 API \u8BBE\u7F6E",settingTestBackendDescCli:"\u8C03\u7528 `<cli> --version` \u9A8C\u8BC1 spawn \u80FD\u627E\u5230\u4E8C\u8FDB\u5236",backendTestFailed:"\u2717 \u540E\u7AEF\u6D4B\u8BD5\u5931\u8D25\uFF1A{error}",settingExportFolderName:"\u5BFC\u51FA\u6587\u4EF6\u5939",settingExportFolderDesc:"\u5BF9\u7167\u7B14\u8BB0\u751F\u6210\u4F4D\u7F6E\uFF08\u76F8\u5BF9 Vault \u6839\uFF09",cacheHeader:"\u7F13\u5B58",settingMaxCacheName:"\u6700\u5927\u7F13\u5B58\u7BC7\u6570",settingMaxCacheDesc:"\u8D85\u8FC7\u4E0A\u9650\u540E\u6309\u6700\u8FD1\u8BBF\u95EE\u65F6\u95F4\u6DD8\u6C70\u6700\u65E7\u7684\u7B14\u8BB0\u7F13\u5B58\uFF1B\u7F13\u5B58\u4FDD\u5B58\u5728\u63D2\u4EF6\u76EE\u5F55\u7684 cache.json",cachePruned:"\u5DF2\u6DD8\u6C70 {count} \u6761\u65E7\u7F13\u5B58",cachedNotesName:"\u5DF2\u7F13\u5B58\u7B14\u8BB0\uFF1A{count} \u7BC7",cachedNotesDesc:"\u7F13\u5B58\u4EE5\u6E90\u7B14\u8BB0 SHA1 + \u751F\u6210\u914D\u7F6E\u6307\u7EB9\u4F5C\u4E3A\u5931\u6548\u952E\uFF0C\u6E90\u7B14\u8BB0\u6216\u6A21\u578B\u914D\u7F6E\u4FEE\u6539\u540E\u4F1A\u663E\u793A stale \u63D0\u793A",clearAllCacheButton:"\u6E05\u9664\u6240\u6709\u7F13\u5B58",settingStreamingName:"\u6D41\u5F0F\u8F93\u51FA",settingStreamingDesc:"\u542F\u7528\u540E\u751F\u6210\u65F6\u5B9E\u65F6\u663E\u793A LLM \u8F93\u51FA\u8FDB\u5EA6\uFF08\u4EC5 OpenAI Chat \u548C Anthropic \u683C\u5F0F\u652F\u6301\uFF09",settingStreamingTimeoutName:"\u6D41\u5F0F\u8D85\u65F6 (ms)",settingStreamingTimeoutDesc:"\u5355\u6B21\u6D41\u5F0F\u8BF7\u6C42\u7684\u8D85\u65F6\u65F6\u95F4\uFF1B\u4F4E\u4E8E 1000ms \u6216\u975E\u6CD5\u503C\u4F1A\u6062\u590D\u9ED8\u8BA4\u503C",cmdBatchGenerate:"\u6279\u91CF\u751F\u6210\u5BF9\u7167\u7B14\u8BB0\uFF08\u5F53\u524D\u6587\u4EF6\u5939\uFF09",batchSelectFolder:"\u8BF7\u8F93\u5165\u8981\u6279\u91CF\u5904\u7406\u7684\u6587\u4EF6\u5939\u8DEF\u5F84\uFF08\u7559\u7A7A\u4E3A Vault \u6839\u76EE\u5F55\uFF09",batchFolderPrompt:"\u6587\u4EF6\u5939\u8DEF\u5F84",batchAlreadyRunning:"\u6279\u91CF\u751F\u6210\u6B63\u5728\u8FD0\u884C",batchCancelRequested:"\u5DF2\u8BF7\u6C42\u53D6\u6D88\u6279\u91CF\u751F\u6210\uFF1B\u5F53\u524D\u6587\u4EF6\u7ED3\u675F\u540E\u505C\u6B62",batchInvalidFolderInput:"\u6587\u4EF6\u5939\u8DEF\u5F84\u65E0\u6548\uFF1A{path}",batchFolderNotFound:"\u6587\u4EF6\u5939\u4E0D\u5B58\u5728\uFF1A{path}",batchNoMarkdown:"\u8BE5\u6587\u4EF6\u5939\u4E0B\u6CA1\u6709 Markdown \u6587\u4EF6",batchProgress:"\u6279\u91CF\u751F\u6210\uFF1A{current}/{total}",batchDone:"\u6279\u91CF\u751F\u6210\u5B8C\u6210\uFF1A\u5171\u5904\u7406 {processed}/{total} \u7BC7\uFF0C\u8DF3\u8FC7\u7F13\u5B58 {skipped} \u7BC7\uFF0C\u5931\u8D25 {errors} \u7BC7",batchCancelled:"\u6279\u91CF\u751F\u6210\u5DF2\u53D6\u6D88\uFF1A\u5DF2\u5904\u7406 {processed}/{total} \u7BC7\uFF0C\u8DF3\u8FC7\u7F13\u5B58 {skipped} \u7BC7\uFF0C\u5931\u8D25 {errors} \u7BC7"},en:{appTitle:"Parallel Reader",settingsTitle:"Parallel Reader Settings",emptyOpenNote:"Open a note, then run:",emptyNoCache:"This note has no cached parallel notes. Run:",commandGenerate:"Parallel Reader: Generate notes for current note",displayName:"Parallel Reader",ribbonOpen:"Open Parallel Reader pane",cmdRun:"Generate parallel notes for current note (cache first)",cmdRegen:"Regenerate parallel notes (bypass cache)",cmdOpenView:"Open Parallel Reader pane",cmdExport:"Export current parallel notes to Vault",cmdCopyMarkdown:"Copy current parallel notes as Markdown",cmdCancel:"Cancel current parallel-note generation",cmdClearCurrent:"Clear cache for current note",cmdClearAll:"Clear all caches",cmdCardPrev:"Focus previous summary card",cmdCardNext:"Focus next summary card",cmdCardJump:"Jump current summary card to source",actionCancel:"Cancel generation",actionRegenerate:"Regenerate",actionCopyAll:"Copy all Markdown",actionExport:"Export to Vault",staleBanner:"The source note or generation settings changed. This is stale cache.",loadingDefault:"Generating parallel notes...",loadingGenerating:"Parallel Reader: asking the LLM to read and segment the full note...",loadingSubtitle:"You can keep reading. Cards will refresh when generation finishes.",errorTitle:"Generation failed",actionCopyError:"Copy error",emptyCard:"(not generated)",anchorMismatch:"Anchor did not match; scroll sync is unavailable",menuCopyMarkdown:"Copy Markdown",menuCopyPlain:"Copy plain text",menuCopyAnchor:"Copy anchor quote",menuJumpSource:"Jump to source",menuEditCard:"Edit this card",menuDeleteCard:"Delete this card",copiedMarkdown:"Copied Markdown",copiedPlain:"Copied plain text",copiedAnchor:"Copied anchor quote",copiedAllMarkdown:"Copied all Markdown",copyFailed:"Copy failed: {error}",actionFailed:"{label} failed: {error}",exported:"Exported \u2192 {path}",noCurrentNote:"No current note",cacheClearedFile:"Cleared cache: {name}",cacheClearedAll:"Cleared {count} cache entries",noCancelableJob:"No cancellable generation job",cancelRequested:"Cancel requested",cancelRequestedApiInFlight:"Cancel requested. The in-flight API request cannot be aborted immediately; its result will be ignored.",actionGenerate:"Generate parallel notes",fileMenuGenerate:"Generate parallel notes",fileMenuRegen:"Regenerate parallel notes",fileMenuClear:"Clear parallel-note cache",noExportContent:"No parallel notes to export",noCopyContent:"No parallel notes to copy",noActiveCard:"No active summary card to jump",viewOpenFailed:"Could not open the Parallel Reader pane",confirmRegenerateEditedCards:"These parallel-reader cards were edited manually. Regenerating will overwrite those edits. Continue?",regenerateCancelled:"Regeneration cancelled",cardDeleted:"Deleted this card",cardSaved:"Saved this card",editCardTitle:"Edit summary card",editCardTitleField:"Title",editCardGistField:"Gist",editCardBulletsField:"Bullets (one per line)",editCardCancel:"Cancel",editCardSave:"Save",openNoteFirst:"Open a note first",alreadyGenerating:"This note is already being generated",emptyNote:"The note is empty",longNoteTruncated:"Long note: only the first {count} characters will be sent to the model",generatingNotice:"Parallel Reader: asking the LLM to read and segment the full note...",noCardsReturned:"LLM returned no cards",generationDone:"Generated {count} sections{suffix}",unanchoredSuffix:" (\u26A0 {count} anchors unmatched)",cancelled:"Generation cancelled",cancelledError:"Generation cancelled",generationFailed:"Generation failed{kind}: {error}",errorCustomProviderBaseUrlRequired:"Custom provider requires an API Base URL.",errorApiBaseUrlMissing:"API Base URL is not set. Choose a provider or enter a custom base URL in settings.",errorModelMissing:"Model is not set. Enter a model ID in settings.",errorApiKeyMissing:"API key is not set. Enter an API Key in settings{hint}.",errorApiKeyEnvHint:" or set environment variable {envVar}",errorLlmNonJson:`LLM returned non-JSON:
{excerpt}`,errorCustomHeadersJsonParse:"Custom headers JSON parse failed: {error}",errorCustomHeadersJsonObject:"Custom headers JSON must be an object",errorCustomHeadersLineFormat:"Custom headers lines must use `Header-Name: value`",errorProviderNonJson:`{label} returned non-JSON:
{excerpt}`,errorProviderRequestFailed:"{label} request failed: {error}",errorProviderApiStatus:"{label} API returned HTTP {status}: {excerpt}",noEditor:"Could not find the source note editor",settingUiLanguageName:"UI language",settingUiLanguageDesc:"Controls plugin UI, commands, and notices. Auto follows Obsidian/system language.",settingBackendName:"Backend",settingBackendDesc:"Backend for generating bullets: CLI reuses local login; API supports OpenAI, Anthropic, Gemini, and compatible proxies.",settingCliPathName:"CLI path (optional)",settingCliPathDesc:"Leave blank to auto-detect common paths. Obsidian launched from the GUI may not inherit shell PATH.",settingCliPathPlaceholder:"Example: /Users/you/bin/codex",settingCliTimeoutName:"CLI timeout (ms)",apiProviderHeader:"API Provider",settingProviderPresetName:"Provider preset",settingProviderPresetDesc:"OpenClaw-style provider/model setup: presets define protocol, base URL, and auth defaults.",settingApiFormatName:"API format",settingApiFormatDesc:"Wire protocol for the provider. OpenAI-compatible proxies usually use Chat Completions.",settingBaseUrlName:"Base URL",settingBaseUrlDesc:"Provider root URL, without /chat/completions. Blank uses the preset default.",settingApiKeyName:"API Key",settingApiKeyDesc:"Can be blank for local Ollama/LM Studio; most hosted providers require a key.",settingApiKeyEnvName:"API key env var",settingApiKeyEnvDesc:"Optional. Obsidian GUI may not inherit shell env; direct API Key is usually more reliable.",settingAuthTypeName:"Auth type",settingAuthTypeDesc:"Auto uses provider preset. Custom proxies can use Bearer, x-api-key, or none.",settingHeadersName:"Extra headers",settingHeadersDesc:"Optional. JSON object or one `Header: value` per line, useful for Cloudflare AI Gateway.",settingMaxTokensName:"Max output tokens",settingModelName:"Model",settingModelDescApi:"Model ID for API calls. Supports OpenClaw-style provider/model; matching provider prefixes are stripped.",settingModelDescCli:"Passed as --model for Claude Code. Usually ignored by Codex, which uses its default config.",settingMaxInputName:"Max input characters",settingMaxInputDesc:"Longer notes are truncated before sending to the model. Raise this for long-context models.",promptHeader:"Prompt",settingPromptLanguageName:"Output language",settingPromptLanguageDesc:"Controls title/gist/bullets language. Anchor is always copied verbatim from source.",settingCardRangeName:"Card count range",settingCardRangeDesc:"The model adapts segmentation within this range.",settingCustomPromptName:"Custom system prompt",settingCustomPromptDesc:"Optional. Variables: {minCards}, {maxCards}, {languageInstruction}, {schema}, {example}",settingCustomPromptPlaceholder:"Leave blank to use built-in prompt",settingTestBackendName:"Test current backend",settingTestBackendDescApi:"Sends a minimal LLM request to validate API settings.",settingTestBackendDescCli:"Runs `<cli> --version` to verify the binary can be spawned.",backendTestFailed:"\u2717 Backend test failed: {error}",settingExportFolderName:"Export folder",settingExportFolderDesc:"Parallel-note output location, relative to the Vault root.",cacheHeader:"Cache",settingMaxCacheName:"Max cached notes",settingMaxCacheDesc:"Prunes least-recently accessed note caches above this limit. Cache is stored in plugin cache.json.",cachePruned:"Pruned {count} old cache entries",cachedNotesName:"Cached notes: {count}",cachedNotesDesc:"Cache is invalidated by source SHA1 and generation settings fingerprint.",clearAllCacheButton:"Clear all caches",settingStreamingName:"Streaming output",settingStreamingDesc:"Show real-time LLM output progress during generation (OpenAI Chat and Anthropic formats only)",settingStreamingTimeoutName:"Streaming timeout (ms)",settingStreamingTimeoutDesc:"Timeout for one streaming request; invalid values or values below 1000ms use the default",cmdBatchGenerate:"Batch generate parallel notes (current folder)",batchSelectFolder:"Enter the folder path to batch-process (leave blank for Vault root)",batchFolderPrompt:"Folder path",batchAlreadyRunning:"Batch generation is already running",batchCancelRequested:"Batch cancellation requested; it will stop after the current note",batchInvalidFolderInput:"Invalid folder path: {path}",batchFolderNotFound:"Folder not found: {path}",batchNoMarkdown:"No Markdown files found in that folder",batchProgress:"Batch generating: {current}/{total}",batchDone:"Batch complete: processed {processed}/{total}, skipped {skipped} (cached), errors {errors}",batchCancelled:"Batch cancelled: processed {processed}/{total}, skipped {skipped} (cached), errors {errors}"}};function Zt(n){let t=n?.uiLanguage;return t==="zh"||t==="en"?t:String((typeof navigator<"u"?navigator:null)?.language||"").toLowerCase().startsWith("zh")?"zh":"en"}function y(n,t,e){let r=Zt(n),i=H[r]||H.en,a=H.en[t]||H.zh[t]||t,s=i[t]||a;return String(s).replace(/\{([a-zA-Z0-9_]+)\}/g,(o,l)=>e&&Object.hasOwn(e,l)?String(e[l]):o)}var E={anthropic:{label:"Anthropic",format:"anthropic-messages",baseUrl:"https://api.anthropic.com/v1",authType:"x-api-key",envVar:"ANTHROPIC_API_KEY",model:"claude-sonnet-4-6"},openai:{label:"OpenAI",format:"openai-chat",baseUrl:"https://api.openai.com/v1",authType:"bearer",envVar:"OPENAI_API_KEY",tokenLimitField:"max_completion_tokens",model:"gpt-5.1"},"openai-responses":{label:"OpenAI Responses",format:"openai-responses",baseUrl:"https://api.openai.com/v1",authType:"bearer",envVar:"OPENAI_API_KEY",modelPrefix:"openai",model:"gpt-5.1"},google:{label:"Google Gemini",format:"google-generative-ai",baseUrl:"https://generativelanguage.googleapis.com/v1beta",authType:"x-goog-api-key",envVar:"GEMINI_API_KEY",model:"gemini-3-pro-preview"},openrouter:{label:"OpenRouter",format:"openai-chat",baseUrl:"https://openrouter.ai/api/v1",authType:"bearer",envVar:"OPENROUTER_API_KEY",model:""},groq:{label:"Groq",format:"openai-chat",baseUrl:"https://api.groq.com/openai/v1",authType:"bearer",envVar:"GROQ_API_KEY",model:""},deepseek:{label:"DeepSeek",format:"openai-chat",baseUrl:"https://api.deepseek.com",authType:"bearer",envVar:"DEEPSEEK_API_KEY",model:"deepseek-chat"},moonshot:{label:"Moonshot / Kimi",format:"openai-chat",baseUrl:"https://api.moonshot.ai/v1",authType:"bearer",envVar:"MOONSHOT_API_KEY",model:"kimi-k2.5"},qianfan:{label:"Baidu Qianfan",format:"openai-chat",baseUrl:"https://qianfan.baidubce.com/v2",authType:"bearer",envVar:"QIANFAN_API_KEY",model:"deepseek-v3.2"},minimax:{label:"MiniMax (Anthropic-compatible)",format:"anthropic-messages",baseUrl:"https://api.minimax.io/anthropic",authType:"bearer",envVar:"MINIMAX_API_KEY",model:"MiniMax-M2.1"},xai:{label:"xAI",format:"openai-chat",baseUrl:"https://api.x.ai/v1",authType:"bearer",envVar:"XAI_API_KEY",model:""},mistral:{label:"Mistral",format:"openai-chat",baseUrl:"https://api.mistral.ai/v1",authType:"bearer",envVar:"MISTRAL_API_KEY",model:""},cerebras:{label:"Cerebras",format:"openai-chat",baseUrl:"https://api.cerebras.ai/v1",authType:"bearer",envVar:"CEREBRAS_API_KEY",model:""},zai:{label:"Z.AI / GLM",format:"openai-chat",baseUrl:"https://api.z.ai/api/paas/v4",authType:"bearer",envVar:"ZAI_API_KEY",model:""},ollama:{label:"Ollama (local)",format:"openai-chat",baseUrl:"http://127.0.0.1:11434/v1",authType:"none",envVar:"",model:""},lmstudio:{label:"LM Studio (local)",format:"openai-chat",baseUrl:"http://127.0.0.1:1234/v1",authType:"none",envVar:"",model:""},"custom-openai":{label:"Custom OpenAI-compatible",format:"openai-chat",baseUrl:"",authType:"bearer",envVar:"",model:""},"custom-anthropic":{label:"Custom Anthropic-compatible",format:"anthropic-messages",baseUrl:"",authType:"x-api-key",envVar:"",model:""}};var We=1e5,Qt=2,J=2,K=100,er=1e3,te={zh:"\u4E2D\u6587",en:"English",auto:"Auto-detect"},Ye={auto:"Auto",zh:"\u4E2D\u6587",en:"English"},m={uiLanguage:"auto",backend:"api",cliPath:"",apiProvider:"anthropic",apiFormat:"anthropic-messages",apiBaseUrl:"",apiKey:"",apiKeyEnvVar:"",apiAuthType:"auto",apiHeaders:"",apiMaxTokens:4096,maxDocChars:We,maxCacheEntries:K,promptLanguage:"zh",minCards:5,maxCards:15,customSystemPrompt:"",model:"claude-sonnet-4-6",exportFolder:"Reading/Articles",cliTimeoutMs:12e4,streaming:!0,streamingTimeoutMs:12e4},S={"anthropic-messages":{label:"Anthropic Messages",defaultBaseUrl:"https://api.anthropic.com/v1",defaultAuthType:"x-api-key"},"openai-chat":{label:"OpenAI Chat Completions",defaultBaseUrl:"https://api.openai.com/v1",defaultAuthType:"bearer",tokenLimitField:"max_tokens"},"openai-responses":{label:"OpenAI Responses",defaultBaseUrl:"https://api.openai.com/v1",defaultAuthType:"bearer"},"google-generative-ai":{label:"Google Gemini generateContent",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta",defaultAuthType:"x-goog-api-key"}},Xe={auto:"Auto",bearer:"Authorization: Bearer","x-api-key":"x-api-key","x-goog-api-key":"x-goog-api-key","api-key":"api-key",none:"None"};function j(n){return wt.default.createHash("sha1").update(n,"utf8").digest("hex")}function ze(n){return Array.isArray(n)?"["+n.map(ze).join(",")+"]":n&&typeof n=="object"?"{"+Object.keys(n).sort().map(t=>JSON.stringify(t)+":"+ze(n[t])).join(",")+"}":JSON.stringify(n)}function Ze(n){return n==="api"||n==="anthropic-api"}function v(n){return E[n.apiProvider]||E.anthropic}function x(n){let t=v(n),e=(n.apiFormat||t.format||"").trim();return S[e]?e:t.format}function M(n){let t=x(n),e=v(n),r=(n.apiBaseUrl||"").trim();if(r)return r.replace(/\/+$/,"");if((n.apiProvider||"").startsWith("custom-"))throw new Error(y(n,"errorCustomProviderBaseUrlRequired"));let i=(e.baseUrl||S[t].defaultBaseUrl||"").trim();if(!i)throw new Error(y(n,"errorApiBaseUrlMissing"));return i.replace(/\/+$/,"")}function Qe(n){let t=(n.apiAuthType||"auto").trim();if(t&&t!=="auto")return t;let e=v(n),r=x(n);return e.authType||S[r].defaultAuthType||"bearer"}function vt(n){let t=(n.apiKey||"").trim();if(t)return t;let e=(n.apiKeyEnvVar||v(n).envVar||"").trim();return e&&process.env?.[e]?String(process.env[e]).trim():""}function I(n){let t=(n.model||"").trim();if(!t)throw new Error(y(n,"errorModelMissing"));let e=v(n),r=[n.apiProvider,e.modelPrefix].map(a=>(a||"").trim()).filter(Boolean),i=t.toLowerCase();for(let a of r){let s=a.toLowerCase();if(i.startsWith(s+"/"))return t.slice(a.length+1).trim()}return t}function et(n,t){let e=v(n),r=E[t]||E.anthropic,i=(n.model||"").trim(),a=!i||i===m.model||!!e.model&&i===e.model;return{...n,apiProvider:t,apiFormat:r.format,apiBaseUrl:r.baseUrl,apiAuthType:r.authType||"auto",apiKeyEnvVar:r.envVar||"",...a?{model:r.model||""}:{}}}function re(n){let t={...n};Ye[t.uiLanguage]||(t.uiLanguage=m.uiLanguage),(!t.apiProvider||!E[t.apiProvider])&&(t.apiProvider="anthropic");let e=v(t);(!t.apiFormat||!S[t.apiFormat])&&(t.apiFormat=e.format),(!t.apiAuthType||!Xe[t.apiAuthType])&&(t.apiAuthType="auto"),t.backend==="anthropic-api"&&(t.apiProvider=t.apiProvider||"anthropic",t.apiFormat=t.apiFormat||"anthropic-messages",t.apiBaseUrl=t.apiBaseUrl||E.anthropic.baseUrl,t.apiAuthType=t.apiAuthType||"x-api-key",t.apiKeyEnvVar=t.apiKeyEnvVar||"ANTHROPIC_API_KEY");let r=Number(t.apiMaxTokens);(!Number.isFinite(r)||r<=0)&&(t.apiMaxTokens=m.apiMaxTokens);let i=Number(t.maxDocChars);return(!Number.isFinite(i)||i<1e3)&&(t.maxDocChars=m.maxDocChars),t.maxCacheEntries=xt(t.maxCacheEntries),te[t.promptLanguage]||(t.promptLanguage=m.promptLanguage),t.minCards=bt(t.minCards,m.minCards),t.maxCards=bt(t.maxCards,m.maxCards),t.maxCards<t.minCards&&(t.maxCards=t.minCards),t.streamingTimeoutMs=ne(t.streamingTimeoutMs),typeof t.customSystemPrompt!="string"&&(t.customSystemPrompt=""),t}function bt(n,t){let e=Math.floor(Number(n));return Number.isFinite(e)?Math.min(30,Math.max(1,e)):t}function xt(n){let t=Math.floor(Number(n));return!Number.isFinite(t)||t<=0?K:t}function ne(n){let t=Math.floor(Number(n));return!Number.isFinite(t)||t<er?m.streamingTimeoutMs:t}function Ct(n){let t=n&&(n.lastAccessedAt||n.generatedAt||n.updatedAt),e=Date.parse(t||"");return Number.isFinite(e)?e:0}function me(n,t){if(!n||typeof n!="object")return[];let e=xt(t),r=Object.entries(n);if(r.length<=e)return[];let i=r.sort(([a,s],[o,l])=>Ct(s)-Ct(l)||a.localeCompare(o)).slice(0,r.length-e).map(([a])=>a);for(let a of i)delete n[a];return i}function ie(n){let t=re(Object.assign({},m,n||{})),e=Ze(t.backend),r=v(t),i=x(t),a=e?(t.apiBaseUrl||r.baseUrl||S[i]?.defaultBaseUrl||"").trim().replace(/\/+$/,""):"";return j(ze({cacheSchemaVersion:J,promptVersion:Qt,maxDocChars:Number(t.maxDocChars)||m.maxDocChars,promptLanguage:t.promptLanguage,minCards:t.minCards,maxCards:t.maxCards,customSystemPromptHash:j(t.customSystemPrompt||""),backend:t.backend,model:t.model,apiProvider:e?t.apiProvider:"",apiFormat:e?i:"",apiBaseUrl:a,apiAuthType:e?Qe(t):"",apiHeadersHash:e?j(t.apiHeaders||""):"",apiMaxTokens:e?Number(t.apiMaxTokens)||m.apiMaxTokens:0,structuredOutputVersion:1}))}function D(n,t,e){return!!n&&n.schemaVersion===J&&n.contentHash===j(t)&&n.settingsHash===ie(e)}function ge(n){return(n||"").trim().split("/").map(t=>t.trim()).filter(t=>t&&t!=="."&&t!=="..").join("/")}function tt(n){return(n||"").split("/").map(t=>t.trim()).some(t=>t==="."||t==="..")}function fe(n,t){let e=ge(n);return tt(n)?{valid:!1,reason:"unsafe",folderPath:e}:e&&!t(e)?{valid:!1,reason:"missing",folderPath:e}:{valid:!0,reason:"ok",folderPath:e}}function tr(n,t){return t?n.parent?.path===t:!n.path.includes("/")}function ye(n,t){let e=ge(t);return n.filter(r=>tr(r,e))}function be(n,t){return{current:n+1,total:t}}function Ce(n){return{total:n,processed:0,skipped:0,errors:0}}function we(n){return{...n,processed:n.processed+1}}function ve(n){return{...n,processed:n.processed+1,skipped:n.skipped+1}}function xe(n){return{...n,processed:n.processed+1,errors:n.errors+1}}function Ae(n,t,e){return!!n&&D(n,t,e)}function Se(){return{cancelled:!1,currentPath:""}}function Pe(n,t){return n.currentPath=t,n}function ae(n){return!n||n.cancelled?!1:(n.cancelled=!0,!0)}function St(n,t,e){return new Promise(r=>{let i=new At.Modal(n);i.onOpen=()=>{i.contentEl.createEl("p",{text:t});let s=i.contentEl.createDiv({cls:"parallel-reader-modal-field"}).createEl("input",{type:"text"});s.placeholder=e,s.addEventListener("keydown",o=>{o.key==="Enter"&&(r(s.value.trim()),i.close())}),i.contentEl.createEl("button",{text:"OK"}).addEventListener("click",()=>{r(s.value.trim()),i.close()})},i.onClose=()=>r(null),i.open()})}function Te(n,t){return n?{...n,lastAccessedAt:t||new Date().toISOString()}:null}function ke(n){return JSON.stringify({version:1,entries:n||{}})}function Ee(n,t){return!!t&&!!n&&typeof n.updatedAt=="string"&&n.updatedAt.trim().length>0}var $=class{constructor(t,e,r,i){this.adapter=t;this.configDir=e;this.pluginId=r;this.getSettings=i;this.cache={};this._timer=null;this._dirty=!1}filePath(){return`${this.configDir}/plugins/${this.pluginId}/cache.json`}async ensureDir(){let t=`${this.configDir}/plugins/${this.pluginId}`;try{if(typeof this.adapter.exists=="function"&&await this.adapter.exists(t))return;await this.adapter.mkdir(t)}catch{}}async readFile(){try{let t=await this.adapter.read(this.filePath()),e=JSON.parse(t);if(e&&typeof e=="object"&&e.entries&&typeof e.entries=="object")return e.entries}catch(t){let e=t instanceof Error?t.message:String(t);/not found|does not exist|ENOENT/i.test(e)||console.warn("[parallel-reader] failed to read cache.json",t)}return{}}async writeFile(){await this.ensureDir(),await this.adapter.write(this.filePath(),ke(this.cache))}async load(){this.cache=await this.readFile(),this.prune().length>0&&await this.writeFile()}prune(){let t=this.getSettings();return me(this.cache,t?.maxCacheEntries||K)}async pruneIfNeeded(){let t=this.prune();return t.length>0&&await this.save(),t}async save(){this._timer&&(clearTimeout(this._timer),this._timer=null),this.prune(),await this.writeFile(),this._dirty=!1}scheduleSave(t=5e3){this._dirty=!0,!this._timer&&(this._timer=setTimeout(()=>{this._timer=null,this._dirty&&this.save().catch(e=>console.error("[parallel-reader] failed to save cache",e))},t))}async flush(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._dirty&&await this.save()}get(t){return this.cache[t]||null}touch(t){let e=Te(this.cache[t]||null);return e?(this.cache[t]=e,this.scheduleSave(),e):null}async move(t,e){if(typeof t!="string"||typeof e!="string"||!t.trim()||!e.trim())return!1;if(t===e)return Object.hasOwn(this.cache,t);let r=this.cache[t];if(!r||Object.hasOwn(this.cache,e))return!1;let i={...this.cache,[e]:r};return delete i[t],this.cache=i,await this.save(),!0}async put(t,e,r,i){let a=new Date().toISOString();this.cache[t]={schemaVersion:J,contentHash:j(e),settingsHash:ie(i||this.getSettings()),cards:r,generatedAt:a,lastAccessedAt:a},await this.save()}async replaceCards(t,e){let r=this.cache[t];if(!r)return!1;let i=new Date().toISOString();return this.cache[t]={...r,cards:(e||[]).map(a=>({title:a.title,anchor:a.anchor,gist:a.gist,bullets:a.bullets||[]})),updatedAt:i,lastAccessedAt:i},await this.save(),!0}async delete(t){this.cache[t]&&(delete this.cache[t],await this.save())}async clear(){this.cache={},await this.save()}};function q(n,t){if(!t)return-1;let e=u=>u.replace(/\s+/g," ").trim(),r=u=>{let g=[],b=[],w=!1;for(let k=0;k<u.length;k++){let de=u[k];if(/\s/.test(de)){w=g.length>0;continue}w&&(g.push(" "),b.push(k),w=!1),g.push(de),b.push(k)}return{text:g.join(""),map:b}},i=u=>{if(!u)return-1;let g=n.indexOf(u);if(g===-1)return-1;let b=0;for(let w=0;w<g;w++)n[w]===`
`&&b++;return b},a=i(t);if(a>=0||(a=i(t.trim()),a>=0))return a;for(let u of[60,40,25,15]){let g=t.trim().slice(0,u);if(a=i(g),a>=0)return a}let s=r(n),o=e(t).slice(0,30);if(!o)return-1;let l=s.text.indexOf(o);if(l===-1)return-1;let c=s.map[l];if(c==null)return-1;let d=0;for(let u=0;u<c;u++)n[u]===`
`&&d++;return d}function Fe(n,t){let e=Array.isArray(n)?n.slice():[];return!Number.isInteger(t)||t<0||t>=e.length||e.splice(t,1),e}function Re(n,t,e){if(!Number.isInteger(n)||!Number.isInteger(t)||t<=0||!Number.isInteger(e)||e<0||n<0||n>=t)return e;let r=t-1;return r<=0?-1:n<e?Math.max(0,e-1):n===e?Math.min(e,r-1):e}function Me(n,t,e){let r=Array.isArray(n)?n.slice():[];return!Number.isInteger(t)||t<0||t>=r.length||(r[t]=Object.assign({},r[t],e||{})),r}function rt(n,t){let e=(t||[]).map(r=>({title:r.title,level:2,anchor:r.anchor,gist:r.gist,startLine:q(n,r.anchor),bullets:r.bullets||[]}));return e.sort((r,i)=>r.startLine<0&&i.startLine<0?0:r.startLine<0?1:i.startLine<0?-1:r.startLine-i.startLine),e}var Ut=require("obsidian");var Et=require("child_process"),Ft=he(require("fs")),Le=he(require("os")),C=he(require("path"));var O=class extends Error{constructor(t){super("\u8BE5\u7B14\u8BB0\u6B63\u5728\u751F\u6210\u5BF9\u7167\u7B14\u8BB0"),this.name="GenerationJobAlreadyRunningError",this.code="already-running",this.key=t}},P=class extends Error{constructor(t){super("\u751F\u6210\u5DF2\u53D6\u6D88"),this.name="GenerationJobCancelledError",this.code="cancelled",this.key=t}},nt=class{constructor(t){this.key=t,this.phase="queued",this.cancelled=!1,this.startedAt=new Date().toISOString(),this.updatedAt=this.startedAt,this._cancelHandlers=[]}setPhase(t){this.phase=t,this.updatedAt=new Date().toISOString()}onCancel(t){if(typeof t=="function"){if(this.cancelled){t();return}this._cancelHandlers.push(t)}}cancel(){if(this.cancelled)return!1;this.cancelled=!0,this.setPhase("cancelled");for(let t of this._cancelHandlers.splice(0))try{t()}catch(e){console.warn("[parallel-reader] cancel handler error",e)}return!0}throwIfCancelled(){if(this.cancelled)throw new P(this.key)}},z=class{constructor(){this.jobs=new Map}get(t){return this.jobs.get(t)||null}isRunning(t){return this.jobs.has(t)}async start(t,e){if(this.jobs.has(t))throw new O(t);let r=new nt(t);this.jobs.set(t,r);try{r.setPhase("running");let i=await e(r);return r.throwIfCancelled(),i}catch(i){throw r.cancelled&&!(i instanceof P)?new P(t):i}finally{this.jobs.delete(t)}}cancel(t){let e=this.jobs.get(t);return e?e.cancel():!1}};function Ne(n){if(n instanceof P)return"cancelled";let t=n;if(t?.code==="cancelled")return"cancelled";let e=String(t?.message||n);return/api key|unauthorized|401|403|认证|权限/i.test(e)?"auth":/timeout|超时|timed out/i.test(e)?"timeout":/429|rate limit|too many requests/i.test(e)?"rate-limit":/非 JSON|json_schema|schema|structured/i.test(e)?"schema":/model 未设置|base url|配置|config/i.test(e)?"config":"unknown"}var se="record_parallel_reader_cards";function Ie(n){let t=[],e=-1,r=0,i=!1,a=!1;for(let s=0;s<n.length;s++){let o=n[s];if(i){a?a=!1:o==="\\"?a=!0:o==='"'&&(i=!1);continue}o==='"'?i=!0:o==="{"?(r===0&&(e=s),r++):o==="}"&&(r>0&&r--,r===0&&e>=0&&(t.push(n.slice(e,s+1)),e=-1))}return t}function it(n){let t=(n||"").trim();if(!t)return t;try{return JSON.parse(t),t}catch{}let e=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(e){let i=e[1].trim();try{return JSON.parse(i),i}catch{}}let r=Ie(t);r.sort((i,a)=>a.length-i.length);for(let i of r)try{return JSON.parse(i),i}catch{}return t}function at(n){let t=n.match(/\{\s*"cards"\s*:\s*\[/);if(!t||t.index===void 0)return null;let e=t.index+t[0].length,r=Ie(n.slice(e)),i=[];for(let a of r)try{JSON.parse(a),i.push(a)}catch{}return i.length===0?null:'{"cards":['+i.join(",")+"]}"}function T(n,t){let e=it(n),r;try{r=JSON.parse(e)}catch{let a=at(n);if(a)try{return r=JSON.parse(a),console.warn("[parallel-reader] LLM output was truncated; salvaged",r.cards?.length??0,"complete cards. Consider increasing max tokens."),W(r)}catch{}throw console.warn("[parallel-reader] LLM returned non-JSON. Raw response:",n),new Error(y(t||null,"errorLlmNonJson",{excerpt:(n||"").slice(0,500)}))}return W(r)}function W(n){let t=n;return(t&&Array.isArray(t.cards)?t.cards:[]).filter(r=>!!r&&typeof r=="object").map(r=>({title:typeof r.title=="string"?r.title:"(\u65E0\u6807\u9898)",anchor:typeof r.anchor=="string"?r.anchor:"",gist:typeof r.gist=="string"?r.gist:"",bullets:Array.isArray(r.bullets)?r.bullets.filter(i=>typeof i=="string"):[]}))}function oe(n){let t={type:"object",properties:{title:{type:"string"},anchor:{type:"string"},gist:{type:"string"},bullets:{type:"array",items:{type:"string"}}},required:["title","anchor","gist","bullets"]},e={type:"object",properties:{cards:{type:"array",items:t}},required:["cards"]};return n&&(t.additionalProperties=!1,e.additionalProperties=!1),e}function Pt(){return{type:"json_schema",json_schema:{name:"parallel_reader_cards",strict:!0,schema:oe(!0)}}}function Tt(){return{format:{type:"json_schema",name:"parallel_reader_cards",strict:!0,schema:oe(!0)}}}function kt(){return{name:se,description:"Return the generated Parallel Reader summary cards.",input_schema:oe(!0)}}function B(n,t){if(t?.trim())return t.trim();let e=Le.default.homedir(),r=process.platform==="win32",i=r?[".cmd",".exe",""]:[""],a=r?[C.default.join(e,"AppData","Roaming","npm"),C.default.join(e,"AppData","Local","Programs","claude-code"),C.default.join(e,"AppData","Local","Programs","codex"),C.default.join(e,".claude","local"),C.default.join(e,".codex","bin"),C.default.join(e,".bun","bin"),C.default.join(e,"scoop","shims"),"C:\\Program Files\\nodejs"]:[C.default.join(e,"bin"),C.default.join(e,".local","bin"),C.default.join(e,".claude","local"),C.default.join(e,".codex","bin"),C.default.join(e,".bun","bin"),C.default.join(e,".npm-global","bin"),C.default.join(e,".cargo","bin"),"/opt/homebrew/bin","/usr/local/bin"];for(let s of a)for(let o of i){let l=C.default.join(s,n+o);try{if(Ft.default.existsSync(l))return l}catch{}}return n}function _(n,t,e,r,i,a=Et.spawn){return new Promise((s,o)=>{let l,c=!1,d=null,u=f=>{c||(c=!0,d&&clearTimeout(d),o(f))},g=f=>{c||(c=!0,d&&clearTimeout(d),s(f))};try{l=a(n,t,{stdio:["pipe","pipe","pipe"],env:{...process.env,PATH:[process.env.PATH||"","/usr/local/bin","/opt/homebrew/bin",C.default.join(Le.default.homedir(),".local/bin"),C.default.join(Le.default.homedir(),".claude/local")].filter(Boolean).join(":")}})}catch(f){return o(new Error(`Failed to start ${n}: ${f instanceof Error?f.message:String(f)}`))}let b="",w="";if(d=setTimeout(()=>{try{l.kill("SIGKILL")}catch(f){console.warn("[parallel-reader] failed to kill timed-out CLI process",f)}u(new Error(`CLI timed out (${r}ms)`))},r),i&&i.onCancel(()=>{try{l.kill("SIGKILL")}catch(f){console.warn("[parallel-reader] failed to kill cancelled CLI process",f)}u(new P(i.key))}),!l.stdout||!l.stderr||!l.stdin){u(new Error("CLI process streams are unavailable"));return}let k=l.stdout,de=l.stderr,qe=l.stdin;if(k.on("data",f=>{b+=f.toString("utf8")}),de.on("data",f=>{w+=f.toString("utf8")}),l.on("error",f=>{u(new Error(`CLI startup error: ${f.message}. Try setting an absolute CLI path.`))}),l.on("close",f=>{if(!c){if(f!==0)return u(new Error(`CLI exited with code ${f}
stderr:
${w.slice(0,1e3)}`));g({stdout:b,stderr:w})}}),e)try{qe.write(e),qe.end()}catch{}else try{qe.end()}catch(f){console.warn("[parallel-reader] failed to close CLI stdin",f)}})}async function Rt(n,t,e,r){let i=B("claude",e.cliPath),a=Number(e.apiMaxTokens)||4096,s=["-p","--output-format","json","--max-tokens",String(a),"--append-system-prompt",n,"--disallowed-tools","Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch,TodoWrite,Task"],{stdout:o}=await _(i,s,t,e.cliTimeoutMs,r),l="";try{let c=JSON.parse(o);if(Array.isArray(c)){let d=c.find(u=>u.type==="result");d&&typeof d.result=="string"&&(l=d.result)}else c&&typeof c=="object"&&(l=c.result||c.content||"")}catch{throw new Error(`claude CLI returned unexpected output:
`+o.slice(0,500))}if(!l)throw console.warn("[parallel-reader] claude CLI returned no result. Full stdout:",o),new Error(`claude CLI returned no result. Output:
`+o.slice(0,500));return T(l,e)}async function Mt(n,t,e,r){let i=B("codex",e.cliPath),a=`<<SYSTEM>>
${n}
<<USER>>
${t}
Output JSON directly with no explanation.`,s=["exec","--skip-git-repo-check","-"],{stdout:o}=await _(i,s,a,e.cliTimeoutMs,r);return T(o,e)}function rr(n){return n==="en"?"Write title, gist, and bullets in English.":n==="auto"?"Write title, gist, and bullets in the main language of the source document.":"\u7528\u4E2D\u6587\u8F93\u51FA title\u3001gist \u548C bullets\u3002"}function nr(n){return n==="en"?`{"cards":[
{"title":"U-shaped gains","anchor":"Who benefits from AI? Overall, it shifts the score from one to seven","gist":"AI productivity gains form a U shape, with both ends benefiting most","bullets":["Top-paid software managers benefit by accelerating existing work","Low-paid workers use AI to create new side income","Middle-layer specialists gain less because prompt precision is hard to trust","Average reported benefit is 5.1/7, with 42% describing gains as unclear"]}
]}`:`{"cards":[
{"title":"U \u578B\u6536\u76CA\u66F2\u7EBF","anchor":"\u90A3\u8C01\u53C8\u4F1A\u88AB AI \u6240\u53D7\u76CA\uFF1F\u6574\u4F53\u6765\u770B\uFF0C\u5B83\u628A\u6574\u4E2A\u5206\u6570\u53D8\u6210\u4E86\u4E00\u5206\u5230\u4E03\u5206","gist":"AI \u751F\u4EA7\u529B\u6536\u76CA\u5448 U \u578B\uFF0C\u4E24\u7AEF\u53D7\u76CA\u6700\u5927\u3001\u4E2D\u95F4\u5C42\u584C\u9677","bullets":["\u6700\u9AD8\u85AA\u5C97\u4F4D\uFF08\u8F6F\u4EF6\u7BA1\u7406\uFF09\u901A\u8FC7\u52A0\u901F\u65E2\u6709\u5DE5\u4F5C\u53D7\u76CA\u6700\u5927","\u6700\u4F4E\u85AA\u5C97\u4F4D\uFF08\u5916\u5356\u5458\u3001\u56ED\u827A\u5DE5\uFF09\u7528 AI \u5F00\u526F\u4E1A\u521B\u9020\u65B0\u6536\u5165","\u4E2D\u95F4\u5C42\u79D1\u5B66\u5BB6\u3001\u5F8B\u5E08\u6536\u76CA\u6700\u5C11\uFF0C\u90E8\u5206\u56E0\u5BF9 prompt \u7CBE\u5EA6\u4FE1\u4EFB\u4E0D\u8DB3","\u5168\u4F53\u5747\u5206 5.1/7\uFF0C42% \u62A5\u544A\u6536\u76CA\u6A21\u7CCA"]}
]}`}function ir(n,t){return String(n||"").replace(/\{([a-zA-Z0-9_]+)\}/g,(e,r)=>Object.hasOwn(t,r)?String(t[r]):e)}function ar(n,t,e,r,i,a){return n==="en"?`You are a long-form reading summary assistant. After reading the full document, split it into ${t}-${e} natural topic units. They do not need to match markdown headings; use a complete argument or topic as the unit, merging short sections and splitting long ones when needed.
Each card has one guiding sentence plus several bullets. Bullets carry details; gist is the lead-in.
Language:
- ${r}
For each unit, output:
- title: a concise 3-10 word heading that clearly states what the section is about; avoid vague labels like "Background" or "Introduction"
- anchor: a verbatim quote from the start of this unit, copied 1:1 from the source, 40-80 characters where possible, preserving punctuation, spaces, and line breaks; it is only used internally for positioning
- gist: one guiding sentence, 20-40 words, stating the core claim or conclusion
- bullets: 3-6 supporting bullets, each 20-50 words, carrying data, comparisons, mechanisms, examples, or counterintuitive observations. Gist and bullets must not repeat each other.
Rules:
- anchor must exact-substring-match the source. Never paraphrase, translate, summarize, or alter it.
- Choose the earliest sufficiently distinctive quote for each unit; avoid generic phrases.
- Every card must include both gist and bullets.
- Each bullet must be a standalone assertion; avoid sequencing phrases such as "first" or "then".
- Output strict JSON only: no markdown fence, no explanation, no tool call.
Output shape:
${i}
Example:
${a}`:`\u4F60\u662F\u4E00\u4E2A\u957F\u6587\u9605\u8BFB\u6458\u8981\u52A9\u624B\u3002\u9605\u8BFB\u5168\u6587\u540E\uFF0C\u628A\u6587\u7AE0\u5207\u6210 ${t}-${e} \u4E2A"\u81EA\u7136\u4E3B\u9898\u5355\u5143"\u2014\u2014\u4E0D\u5FC5\u5BF9\u5E94 markdown heading\uFF0C\u4EE5"\u4E00\u4E2A\u5B8C\u6574\u8BBA\u70B9\u6216\u8BDD\u9898"\u4E3A\u5355\u4F4D\u81EA\u884C\u5224\u65AD\u7C92\u5EA6\uFF1A\u77ED\u7AE0\u8282\u5408\u5E76\u3001\u957F\u7AE0\u8282\u62C6\u5206\u3002
**\u6BCF\u5F20\u5361\u7247\u7684\u7ED3\u6784\uFF1A\u4E00\u53E5\u8BDD\u9886\u8BFB + \u82E5\u5E72\u6761 bullet\u3002bullet \u627F\u8F7D\u7EC6\u8282\uFF0Cgist \u662F\u4E00\u53E5\u8BDD\u5BFC\u8BFB\u3002**
\u8BED\u8A00\uFF1A
- ${r}
\u5BF9\u6BCF\u4E2A\u5355\u5143\u8F93\u51FA\uFF1A
- title: 3-10 \u5B57\u7684\u77ED\u6807\u9898\uFF0C\u8981\u80FD\u72EC\u7ACB\u8BF4\u660E\u8FD9\u6BB5\u8BB2\u4EC0\u4E48\uFF0C\u907F\u514D"\u80CC\u666F""\u4ECB\u7ECD"\u8FD9\u7C7B\u7A7A\u6CDB\u8BCD
- anchor: \u8BE5\u5355\u5143\u5F00\u5934\u7684**\u9010\u5B57\u5F15\u7528**\uFF0C\u4ECE\u539F\u6587 1:1 \u590D\u5236 40-80 \u5B57\uFF0C\u4FDD\u7559\u539F\u59CB\u6807\u70B9/\u7A7A\u683C/\u6362\u884C\uFF1B\u4EC5\u4F9B\u63D2\u4EF6\u5185\u90E8\u5B9A\u4F4D\uFF0C\u7528\u6237\u4E0D\u53EF\u89C1
- gist: **\u4E00\u53E5\u8BDD\u9886\u8BFB**\uFF0820-40 \u5B57\uFF09\uFF0C\u70B9\u51FA\u8BE5\u5355\u5143\u7684\u6838\u5FC3\u7ACB\u573A\u6216\u7ED3\u8BBA\uFF0C\u4F5C\u4E3A bullets \u7684\u5BFC\u8BFB
- bullets: **3-6 \u6761**\u652F\u6491 bullet\uFF0C\u6BCF\u6761 20-50 \u5B57\u3002\u627F\u8F7D\u6570\u636E\u3001\u5BF9\u6BD4\u3001\u673A\u5236\u3001\u4F8B\u5B50\u3001\u53CD\u76F4\u89C9\u89C2\u5BDF\u3002gist \u662F\u7ACB\u573A\uFF0Cbullets \u662F\u5177\u4F53\u5185\u5BB9\uFF0C\u4E24\u8005\u4E0D\u5141\u8BB8\u91CD\u590D\u3002
\u89C4\u5219\uFF1A
- anchor \u5FC5\u987B\u80FD\u5728\u539F\u6587\u91CC exact substring match \u627E\u5230\u3002\u7EDD\u5BF9\u4E0D\u8981\u6539\u52A8\u3001\u603B\u7ED3\u3001\u7FFB\u8BD1\uFF0C\u5FC5\u987B\u539F\u6837\u590D\u5236
- anchor \u9009\u7528\u8BE5\u5355\u5143\u6700\u9760\u524D\u4E14\u8DB3\u591F\u72EC\u7279\u7684\u4E00\u6BB5\uFF08\u907F\u514D\u901A\u7528\u5957\u8BDD\u5982"\u7EFC\u4E0A\u6240\u8FF0"\uFF09
- \u6BCF\u5F20\u5361\u90FD\u5FC5\u987B\u540C\u65F6\u6709 gist \u548C bullets\u2014\u2014\u4E0D\u8981\u53EA\u6709 gist\uFF0C\u4E5F\u4E0D\u8981\u53EA\u6709 bullets
- bullet \u6BCF\u6761\u662F\u4E00\u4E2A\u5B8C\u6574\u72EC\u7ACB\u7684\u65AD\u8A00\uFF0C\u4E0D\u8981\u7528"\u9996\u5148""\u5176\u6B21"\u8FD9\u79CD\u987A\u5E8F\u8BCD
- \u4E25\u683C\u53EA\u8F93\u51FA JSON\uFF0C\u65E0 markdown fence\u3001\u65E0\u89E3\u91CA\u3001\u65E0 tool call
\u8F93\u51FA\u683C\u5F0F\uFF1A
${i}
\u793A\u4F8B\uFF1A
${a}`}function sr(n,t,e,r,i){return n==="en"?`Non-overridable output contract:
- Must output ${t}-${e} cards.
- ${r}
- anchor must be copied verbatim from the source and exact-substring-match the source.
- Output strict JSON only: no markdown fence, no explanation, no tool call.
- JSON shape: ${i}`:`\u4E0D\u53EF\u8986\u76D6\u7684\u8F93\u51FA\u5951\u7EA6\uFF1A
- \u5FC5\u987B\u8F93\u51FA ${t}-${e} \u5F20 cards\u3002
- ${r}
- anchor \u5FC5\u987B\u4ECE\u539F\u6587\u9010\u5B57\u590D\u5236\uFF0C\u5FC5\u987B\u80FD\u5728\u539F\u6587 exact substring match \u627E\u5230\u3002
- \u4E25\u683C\u53EA\u8F93\u51FA JSON\uFF0C\u65E0 markdown fence\u3001\u65E0\u89E3\u91CA\u3001\u65E0 tool call\u3002
- JSON shape: ${i}`}function De(n,t){let e=Number(t.maxDocChars)||We,r=te[t.promptLanguage]?t.promptLanguage:m.promptLanguage,i=Math.max(1,Number(t.minCards)||m.minCards),a=Math.max(i,Number(t.maxCards)||m.maxCards),s=rr(r),o=n.length>e?n.slice(0,e)+(r==="en"?`
[Document truncated]`:`
[\u6587\u6863\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD]`):n,l='{"cards":[{"title":"...","anchor":"...","gist":"...","bullets":["...","..."]}]}',c=nr(r),d={minCards:i,maxCards:a,languageInstruction:s,schema:l,example:c},u=ir(t.customSystemPrompt,d).trim(),g=sr(r,i,a,s,l),b=ar(r,i,a,s,l,c),w=u?`${u}
${g}`:b,k=r==="en"?`Source document:
${o}`:`\u4EE5\u4E0B\u662F\u9700\u8981\u5904\u7406\u7684\u6587\u6863\u5168\u6587\uFF1A
${o}`;return{system:w,user:k}}function Oe(n){let t=v(n),e=S[x(n)];return t.tokenLimitField||e?.tokenLimitField||"max_tokens"}function V(n,t,e,r){let i=!r||r.structured!==!1,a={model:I(e),max_tokens:Number(e.apiMaxTokens)||4096,system:n,messages:[{role:"user",content:t}]};return i&&(a.tools=[kt()],a.tool_choice={type:"tool",name:se}),a}function G(n,t,e,r){let i=!r||r.structured!==!1,a={model:I(e),messages:[{role:"system",content:n},{role:"user",content:t}]};return a[Oe(e)]=Number(e.apiMaxTokens)||4096,i&&(a.response_format=Pt()),a}function Y(n,t,e,r){let i=!r||r.structured!==!1,a={model:I(e),instructions:n,input:t,max_output_tokens:Number(e.apiMaxTokens)||4096};return i&&(a.text=Tt()),a}function X(n,t,e,r){let i=!r||r.structured!==!1,a={temperature:0,maxOutputTokens:Number(e.apiMaxTokens)||4096};return i&&(a.responseMimeType="application/json",a.responseJsonSchema=oe(!1)),{systemInstruction:{parts:[{text:n}]},contents:[{role:"user",parts:[{text:t}]}],generationConfig:a}}function st(n){if(typeof n=="string")return n;if(Array.isArray(n))return n.map(t=>{if(typeof t=="string")return t;if(t&&typeof t=="object"){let e=t;return typeof e.text=="string"?e.text:typeof e.output_text=="string"?e.output_text:""}return""}).join("");if(n&&typeof n=="object"){let t=n;return typeof t.text=="string"?t.text:typeof t.output_text=="string"?t.output_text:""}return""}function Nt(n){if(typeof n.output_text=="string")return n.output_text;let t=[],e=r=>{if(r&&typeof r!="string"){if(Array.isArray(r)){r.forEach(e);return}if(typeof r=="object"){let i=r;typeof i.text=="string"&&t.push(i.text),typeof i.output_text=="string"&&t.push(i.output_text),i.type==="output_text"&&typeof i.content=="string"&&t.push(i.content),i.content&&e(i.content),i.output&&e(i.output)}}};return e(n.output),t.join("")}function It(n,t){let r=(Array.isArray(n?.content)?n.content:[]).find(i=>i&&i.type==="tool_use"&&i.name===se);return r?typeof r.input=="string"?T(r.input,t):r.input&&typeof r.input=="object"?W(r.input):[]:null}function Lt(n){return(Array.isArray(n.content)?n.content:[]).map(e=>st(e)).join("").trim()}function Dt(n){let e=(Array.isArray(n.choices)?n.choices:[])[0]||{},r=e.message;return st(r?.content??e.text??"").trim()}function Ot(n){let r=((Array.isArray(n.candidates)?n.candidates:[])[0]||{}).content;return(Array.isArray(r?.parts)?r.parts:[]).map(a=>st(a)).join("").trim()}function Z(n,t){let e=n.replace(/\/+$/,"");for(let r of t)if(e.endsWith(r))return e;return e+t[0]}function or(n,t,e){if(n.json&&typeof n.json=="object")return n.json;try{return JSON.parse(n.text||"{}")}catch(r){throw new Error(y(e||null,"errorProviderNonJson",{label:t,excerpt:(n.text||"").slice(0,500)}),{cause:r})}}async function Bt(n,t,e,r,i,a){let s;try{s=await n({url:e,method:"POST",headers:r,body:JSON.stringify(i),throw:!1})}catch(o){throw new Error(y(a||null,"errorProviderRequestFailed",{label:t,error:o instanceof Error?o.message:String(o)}))}if(s.status>=400)throw new Error(y(a||null,"errorProviderApiStatus",{label:t,status:s.status,excerpt:(s.text||"").slice(0,500)}));return or(s,t,a)}function lr(n){let t=n instanceof Error?n.message:String(n);return/(?:API (?:400|404|422):|API returned HTTP (?:400|404|422)|API 返回 HTTP (?:400|404|422))/.test(t)?/response_format|json_schema|responseJsonSchema|responseMimeType|tools?|tool_choice|unsupported|unrecognized|unknown|schema/i.test(t):!1}async function le(n,t,e,r,i,a,s){try{return await Bt(n,t,e,r,i,s)}catch(o){if(!a||!lr(o))throw o;return console.warn(`[parallel-reader] ${t} structured output rejected; retrying without structured output`,o),Bt(n,t+" fallback",e,r,a,s)}}function cr(n){return n.choices?.[0]?.delta?.content||""}function ur(n){return n.type==="content_block_delta"&&n.delta?.text||""}function ce(n){switch(n){case"openai-chat":return cr;case"anthropic-messages":return ur;default:return null}}function ot(n,t){let e=[],r=n.replace(/\r\n/g,`
`),i=r.split(`
`),a=r.endsWith(`
`)?"":i.pop()??"",s=r.endsWith(`
`)?i.slice(0,-1):i;for(let o of s){let l=[];for(let d of o.split(`
`)){if(!d.startsWith("data:"))continue;let u=d.slice(d.startsWith("data: ")?6:5);l.push(u)}if(l.length===0)continue;let c=l.join(`
`);if(c.trim()!=="[DONE]")try{let d=JSON.parse(c),u=t(d);u&&e.push(u)}catch{}}return{deltas:e,rest:a}}async function dr(n,t,e,r,i,a,s){let o=await globalThis.fetch(n,{method:"POST",headers:t,body:JSON.stringify(e),signal:a});if(!o.ok){let g=await o.text();throw new Error(y(s||null,"errorProviderApiStatus",{label:"Streaming",status:o.status,excerpt:g.slice(0,500)}))}if(!o.body)throw new Error("Response has no body for streaming");let l=o.body.getReader(),c=new TextDecoder,d="",u="";try{for(;;){let{done:g,value:b}=await l.read();if(g)break;u+=c.decode(b,{stream:!0});let w=ot(u,r);u=w.rest;for(let k of w.deltas)d+=k;w.deltas.length>0&&i?.({accumulated:d,done:!1})}}finally{l.releaseLock()}return i?.({accumulated:d,done:!0}),d}async function lt(n,t,e,r,i,a,s){if(typeof globalThis.fetch!="function")throw new Error("Streaming requires fetch API");let o=s?.streamingTimeoutMs??12e4,l=new AbortController,c=null;a&&(c=()=>l.abort(),a.addEventListener("abort",c,{once:!0}),a.aborted&&l.abort());let d=null,u=new Promise((g,b)=>{d=setTimeout(()=>{l.abort(),b(new Error(`Streaming timed out after ${o}ms`))},o)});try{return await Promise.race([dr(n,t,e,r,i,l.signal,s),u])}finally{d!==null&&clearTimeout(d),a&&c&&a.removeEventListener("abort",c)}}function _t(n){let t=ce(n);if(!t)throw new Error(`Streaming not supported for format: ${n}`);return t}function ct(n,t){let e=(n||"").trim();if(!e)return{};if(e.startsWith("{")){let i;try{i=JSON.parse(e)}catch(s){throw new Error(y(t||null,"errorCustomHeadersJsonParse",{error:s instanceof Error?s.message:String(s)}))}if(!i||typeof i!="object"||Array.isArray(i))throw new Error(y(t||null,"errorCustomHeadersJsonObject"));let a={};for(let[s,o]of Object.entries(i))typeof o=="string"&&s.trim()&&(a[s.trim()]=o);return a}let r={};for(let i of e.split(/\r?\n/)){let a=i.trim();if(!a||a.startsWith("#"))continue;let s=a.indexOf(":");if(s<=0)throw new Error(y(t||null,"errorCustomHeadersLineFormat"));let o=a.slice(0,s).trim(),l=a.slice(s+1).trim();o&&(r[o]=l)}return r}function pr(n){let t=Qe(n);if(t==="none")return{};let e=vt(n);if(!e){let r=(n.apiKeyEnvVar||v(n).envVar||"").trim(),i=r?y(n,"errorApiKeyEnvHint",{envVar:r}):"";throw new Error(y(n,"errorApiKeyMissing",{hint:i}))}return t==="bearer"?{authorization:`Bearer ${e}`}:t==="x-api-key"?{"x-api-key":e}:t==="x-goog-api-key"?{"x-goog-api-key":e}:t==="api-key"?{"api-key":e}:{authorization:`Bearer ${e}`}}function Q(n,t){return{"content-type":"application/json",...pr(n),...t||{},...ct(n.apiHeaders,n)}}async function hr(n,t,e,r){let i=Z(M(r),["/messages"]),a=await le(n,"Anthropic-compatible",i,Q(r,{"anthropic-version":"2023-06-01"}),V(t,e,r),V(t,e,r,{structured:!1}),r),s=It(a,r);return s||T(Lt(a),r)}async function mr(n,t,e,r){let i=Z(M(r),["/chat/completions"]),a=await le(n,"OpenAI-compatible Chat",i,Q(r),G(t,e,r),G(t,e,r,{structured:!1}),r);return T(Dt(a),r)}async function gr(n,t,e,r){let i=Z(M(r),["/responses"]),a=await le(n,"OpenAI Responses",i,Q(r),Y(t,e,r),Y(t,e,r,{structured:!1}),r);return T(Nt(a).trim(),r)}async function fr(n,t,e,r){let i=encodeURIComponent(I(r)),a=M(r);/:generateContent(?:\?|$)/.test(a)||(a=`${a.replace(/\/+$/,"")}/models/${i}:generateContent`);let s=Q(r),o=await le(n,"Google Gemini",a,s,X(t,e,r),X(t,e,r,{structured:!1}),r);return T(Ot(o),r)}async function ue(n,t,e,r){switch(x(r)){case"openai-chat":return mr(n,t,e,r);case"openai-responses":return gr(n,t,e,r);case"google-generative-ai":return fr(n,t,e,r);default:return hr(n,t,e,r)}}function Be(n){if(!n.streaming)return!1;let t=x(n);return!!ce(t)}async function yr(n,t,e,r,i){let a=Z(M(e),["/chat/completions"]),s=Q(e),o=G(n,t,e,{structured:!1});o.stream=!0;let l=_t("openai-chat"),c=await lt(a,s,o,l,r,i,e);return T(c.trim(),e)}async function br(n,t,e,r,i){let a=Z(M(e),["/messages"]),s=Q(e,{"anthropic-version":"2023-06-01"}),o=V(n,t,e,{structured:!1});o.stream=!0;let l=_t("anthropic-messages"),c=await lt(a,s,o,l,r,i,e);return T(c.trim(),e)}async function Vt(n,t,e,r,i){let a=x(e);switch(a){case"openai-chat":return yr(n,t,e,r,i);case"anthropic-messages":return br(n,t,e,r,i);default:throw new Error(`Streaming not supported for format: ${a}`)}}async function Gt(n,t){await ue(n,'\u53EA\u8F93\u51FA JSON\uFF1A{"cards":[]}','\u8FDE\u901A\u6027\u6D4B\u8BD5\uFF1A\u8BF7\u539F\u6837\u8F93\u51FA {"cards":[]}',t);let e=x(t);return`${v(t).label} / ${S[e].label}`}async function _e(n,t,e,r){let{system:i,user:a}=De(n,t),s;switch(t.backend){case"claude-code":s=await Rt(i,a,t,e);break;case"codex":s=await Mt(i,a,t,e);break;default:{if(Be(t)){let c=new AbortController;e.onCancel(()=>c.abort()),s=await Vt(i,a,t,r,c.signal)}else s=await ue(Ut.requestUrl,i,a,t);break}}let o=s.map(l=>({title:l.title,level:2,anchor:l.anchor,gist:l.gist,startLine:q(n,l.anchor),bullets:l.bullets}));return o.sort((l,c)=>l.startLine<0&&c.startLine<0?0:l.startLine<0?1:c.startLine<0?-1:l.startLine-c.startLine),o}function Ve(n,t){return t?.phase==="generating"&&n&&Ze(n.backend)?"cancelRequestedApiInFlight":"cancelRequested"}function ut(n){let t=[`## ${n.title}`];if(n.anchor){let e=n.anchor.replace(/\s+/g," ").trim();t.push(`> ${e}`)}return n.gist&&t.push(n.gist),n.bullets&&n.bullets.length>0&&t.push(n.bullets.map(e=>`- ${e}`).join(`
`)),t.join(`
`)}function Ht(n){return[n.title,n.gist||"",...(n.bullets||[]).map(t=>"\u2022 "+t)].filter(Boolean).join(`
`)}function ee(n,t){let e=[`# ${n||"\u5BF9\u7167\u7B14\u8BB0"}`];for(let r of t||[])e.push(ut(r));return e.join(`
`)}var dt=require("obsidian");var F=require("obsidian");function L(n,t,e,r){let i=n.createEl("button",{cls:"parallel-reader-icon-button",attr:{type:"button","aria-label":e}});return i.title=e,typeof F.setIcon=="function"?(0,F.setIcon)(i,t):i.textContent=e,i.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),Promise.resolve(r()).catch(s=>{console.error(s),new F.Notice(`${e} failed: ${s instanceof Error?s.message:String(s)}`)})}),i}function R(n,t,e,r,i){let a=n.createEl("button",{cls:i||"parallel-reader-text-button",attr:{type:"button"}});return t&&typeof F.setIcon=="function"&&(0,F.setIcon)(a,t),a.createSpan({text:e}),a.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),Promise.resolve(r()).catch(o=>{console.error(o),new F.Notice(`${e} failed: ${o instanceof Error?o.message:String(o)}`)})}),a}async function N(n,t){try{await navigator.clipboard.writeText(n),new F.Notice(t)}catch(e){new F.Notice(`Copy failed: ${e instanceof Error?e.message:String(e)}`)}}function jt(n,t,e){return new Promise(r=>{let i=!1,a=l=>{i||(i=!0,r(l))},s=new dt.Modal(n);s.titleEl.setText(t),s.contentEl.createEl("p",{text:e});let o=s.contentEl.createDiv({cls:"modal-button-container"});o.createEl("button",{text:"Cancel"}).addEventListener("click",()=>{s.close(),a(!1)}),o.createEl("button",{text:"OK",cls:"mod-cta"}).addEventListener("click",()=>{s.close(),a(!0)}),s.onClose=()=>a(!1),s.open()})}var Ge=class extends dt.Modal{constructor(t,e,r,i){super(t),this.plugin=e,this.card=r,this.onSave=i}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:this.plugin.t("editCardTitle")});let e=this.createLabeledInput(t,this.plugin.t("editCardTitleField"),this.card.title||""),r=this.createLabeledTextarea(t,this.plugin.t("editCardGistField"),this.card.gist||"",3),i=this.createLabeledTextarea(t,this.plugin.t("editCardBulletsField"),(this.card.bullets||[]).join(`
`),8),a=t.createDiv({cls:"parallel-reader-modal-actions"});R(a,null,this.plugin.t("editCardCancel"),()=>this.close(),"parallel-reader-text-button"),R(a,null,this.plugin.t("editCardSave"),async()=>{await this.onSave({title:e.value.trim()||this.card.title||"",gist:r.value.trim(),bullets:i.value.split(/\r?\n/).map(s=>s.trim()).filter(Boolean)}),this.close()},"parallel-reader-text-button")}createLabeledInput(t,e,r){let i=t.createDiv({cls:"parallel-reader-modal-field"});i.createEl("label",{text:e});let a=i.createEl("input",{attr:{type:"text"}});return a.value=r,a}createLabeledTextarea(t,e,r,i){let a=t.createDiv({cls:"parallel-reader-modal-field"});a.createEl("label",{text:e});let s=a.createEl("textarea");return s.rows=i,s.value=r,s}};function Ue(n,t=80,e=.1){let r=Number(n?.top)||0,i=Math.max(0,Number(n?.height)||0),a=Math.min(Number(t)||0,i*e);return r+Math.max(0,a)}function Jt(n){return{__brand:"ScheduleId",raw:n}}function Cr(n){return Jt(typeof requestAnimationFrame=="function"?requestAnimationFrame(n):setTimeout(()=>n(Date.now()),16))}function wr(n){if(typeof cancelAnimationFrame=="function"){cancelAnimationFrame(n.raw);return}clearTimeout(n.raw)}function He(n,t=Cr,e=wr){let r=null,i=()=>{r===null&&(r=t(()=>{r=null,n()}))};return i.cancel=()=>{r!==null&&(e(r),r=null)},i}var h=require("obsidian");async function vr(n){if(n.backend==="claude-code"){let t=B("claude",n.cliPath),{stdout:e}=await _(t,["--version"],"",1e4);return`claude @ ${t}
${e.trim()}`}if(n.backend==="codex"){let t=B("codex",n.cliPath),{stdout:e}=await _(t,["--version"],"",1e4);return`codex @ ${t}
${e.trim()}`}return Gt(h.requestUrl,n)}var je=class extends h.PluginSettingTab{constructor(t,e){super(t,e),this.plugin=e}tr(t,e){return this.plugin.t(t,e)}display(){let{containerEl:t}=this;t.empty(),new h.Setting(t).setName(this.tr("settingsTitle")).setHeading(),this.renderGeneralSection(t);let e=this.plugin.settings.backend==="claude-code"||this.plugin.settings.backend==="codex";this.renderBackendSection(t,e),this.renderPromptSection(t,e),this.renderActionsSection(t,e),this.renderCacheSection(t)}renderGeneralSection(t){new h.Setting(t).setName(this.tr("settingUiLanguageName")).setDesc(this.tr("settingUiLanguageDesc")).addDropdown(e=>{for(let[r,i]of Object.entries(Ye))e.addOption(r,i);return e.setValue(this.plugin.settings.uiLanguage||m.uiLanguage).onChange(async r=>{this.plugin.settings.uiLanguage=r,await this.plugin.saveSettings(),this.display()})}),new h.Setting(t).setName(this.tr("settingBackendName")).setDesc(this.tr("settingBackendDesc")).addDropdown(e=>e.addOption("api","API / provider").addOption("claude-code","Claude code CLI").addOption("codex","Codex CLI").setValue(this.plugin.settings.backend).onChange(async r=>{this.plugin.settings.backend=r,r==="api"&&!this.plugin.settings.apiBaseUrl&&(this.plugin.settings=et(this.plugin.settings,this.plugin.settings.apiProvider||"anthropic")),await this.plugin.saveSettings(),this.display()}))}renderBackendSection(t,e){e?this.renderCliBackendSettings(t):this.renderApiBackendSettings(t)}renderCliBackendSettings(t){new h.Setting(t).setName(this.tr("settingCliPathName")).setDesc(this.tr("settingCliPathDesc")).addText(e=>e.setPlaceholder(this.tr("settingCliPathPlaceholder")).setValue(this.plugin.settings.cliPath).onChange(r=>{this.plugin.settings.cliPath=r.trim(),this.plugin.saveSettingsDebounced()}))}renderApiBackendSettings(t){let e=v(this.plugin.settings);new h.Setting(t).setName(this.tr("apiProviderHeader")).setHeading(),new h.Setting(t).setName(this.tr("settingProviderPresetName")).setDesc(this.tr("settingProviderPresetDesc")).addDropdown(r=>{for(let[i,a]of Object.entries(E))r.addOption(i,a.label);return r.setValue(this.plugin.settings.apiProvider).onChange(async i=>{this.plugin.settings=et(this.plugin.settings,i),await this.plugin.saveSettings(),this.display()})}),new h.Setting(t).setName(this.tr("settingApiFormatName")).setDesc(this.tr("settingApiFormatDesc")).addDropdown(r=>{for(let[i,a]of Object.entries(S))r.addOption(i,a.label);return r.setValue(x(this.plugin.settings)).onChange(async i=>{this.plugin.settings.apiFormat=i,await this.plugin.saveSettings(),this.display()})}),new h.Setting(t).setName(this.tr("settingBaseUrlName")).setDesc(this.tr("settingBaseUrlDesc")).addText(r=>r.setPlaceholder((this.plugin.settings.apiProvider||"").startsWith("custom-")?"https://your-provider.example/v1":e.baseUrl||S[x(this.plugin.settings)].defaultBaseUrl).setValue(this.plugin.settings.apiBaseUrl).onChange(i=>{this.plugin.settings.apiBaseUrl=i.trim(),this.plugin.saveSettingsDebounced()})),new h.Setting(t).setName(this.tr("settingApiKeyName")).setDesc(this.tr("settingApiKeyDesc")).addText(r=>(r.inputEl.type="password",r.setValue(this.plugin.settings.apiKey).onChange(i=>{this.plugin.settings.apiKey=i.trim(),this.plugin.saveSettingsDebounced()}))),new h.Setting(t).setName(this.tr("settingApiKeyEnvName")).setDesc(this.tr("settingApiKeyEnvDesc")).addText(r=>r.setPlaceholder(e.envVar||"OPENAI_API_KEY").setValue(this.plugin.settings.apiKeyEnvVar).onChange(i=>{this.plugin.settings.apiKeyEnvVar=i.trim(),this.plugin.saveSettingsDebounced()})),new h.Setting(t).setName(this.tr("settingAuthTypeName")).setDesc(this.tr("settingAuthTypeDesc")).addDropdown(r=>{for(let[i,a]of Object.entries(Xe))r.addOption(i,a);return r.setValue(this.plugin.settings.apiAuthType||"auto").onChange(async i=>{this.plugin.settings.apiAuthType=i,await this.plugin.saveSettings()})}),new h.Setting(t).setName(this.tr("settingHeadersName")).setDesc(this.tr("settingHeadersDesc")).addTextArea(r=>r.setValue(this.plugin.settings.apiHeaders).onChange(i=>{this.plugin.settings.apiHeaders=i,this.plugin.saveSettingsDebounced()})),new h.Setting(t).setName(this.tr("settingMaxTokensName")).addText(r=>r.setValue(String(this.plugin.settings.apiMaxTokens)).onChange(i=>{let a=parseInt(i,10);!Number.isNaN(a)&&a>0&&(this.plugin.settings.apiMaxTokens=a,this.plugin.saveSettingsDebounced())})),new h.Setting(t).setName(this.tr("settingStreamingName")).setDesc(this.tr("settingStreamingDesc")).addToggle(r=>r.setValue(this.plugin.settings.streaming??!0).onChange(async i=>{this.plugin.settings.streaming=i,await this.plugin.saveSettings()})),new h.Setting(t).setName(this.tr("settingStreamingTimeoutName")).setDesc(this.tr("settingStreamingTimeoutDesc")).addText(r=>r.setPlaceholder(String(m.streamingTimeoutMs)).setValue(String(this.plugin.settings.streamingTimeoutMs||m.streamingTimeoutMs)).onChange(i=>{this.plugin.settings.streamingTimeoutMs=ne(i),this.plugin.saveSettingsDebounced()}))}renderPromptSection(t,e){new h.Setting(t).setName(this.tr("settingModelName")).setDesc(e?this.tr("settingModelDescCli"):this.tr("settingModelDescApi")).addText(r=>r.setPlaceholder(e?m.model:v(this.plugin.settings).model||"Model-id").setValue(this.plugin.settings.model).onChange(i=>{this.plugin.settings.model=i.trim()||(e?m.model:""),this.plugin.saveSettingsDebounced()})),new h.Setting(t).setName(this.tr("settingMaxInputName")).setDesc(this.tr("settingMaxInputDesc")).addText(r=>r.setValue(String(this.plugin.settings.maxDocChars||m.maxDocChars)).onChange(i=>{let a=parseInt(i,10);!Number.isNaN(a)&&a>=1e3&&(this.plugin.settings.maxDocChars=a,this.plugin.saveSettingsDebounced())})),new h.Setting(t).setName(this.tr("promptHeader")).setHeading(),new h.Setting(t).setName(this.tr("settingPromptLanguageName")).setDesc(this.tr("settingPromptLanguageDesc")).addDropdown(r=>{for(let[i,a]of Object.entries(te))r.addOption(i,a);return r.setValue(this.plugin.settings.promptLanguage||m.promptLanguage).onChange(async i=>{this.plugin.settings.promptLanguage=i,await this.plugin.saveSettings()})}),new h.Setting(t).setName(this.tr("settingCardRangeName")).setDesc(this.tr("settingCardRangeDesc")).addText(r=>r.setPlaceholder("Min").setValue(String(this.plugin.settings.minCards||m.minCards)).onChange(i=>{let a=parseInt(i,10);!Number.isNaN(a)&&a>0&&(this.plugin.settings.minCards=a,this.plugin.settings.maxCards<a&&(this.plugin.settings.maxCards=a),this.plugin.saveSettingsDebounced())})).addText(r=>r.setPlaceholder("Max").setValue(String(this.plugin.settings.maxCards||m.maxCards)).onChange(i=>{let a=parseInt(i,10);!Number.isNaN(a)&&a>0&&(this.plugin.settings.maxCards=Math.max(a,this.plugin.settings.minCards||m.minCards),this.plugin.saveSettingsDebounced())})),new h.Setting(t).setName(this.tr("settingCustomPromptName")).setDesc(this.tr("settingCustomPromptDesc")).addTextArea(r=>(r.inputEl.rows=8,r.setPlaceholder(this.tr("settingCustomPromptPlaceholder")).setValue(this.plugin.settings.customSystemPrompt||"").onChange(i=>{this.plugin.settings.customSystemPrompt=i,this.plugin.saveSettingsDebounced()})))}renderActionsSection(t,e){new h.Setting(t).setName(this.tr("settingTestBackendName")).setDesc(e?this.tr("settingTestBackendDescCli"):this.tr("settingTestBackendDescApi")).addButton(r=>r.setButtonText("Test").onClick(async()=>{try{let i=await vr(this.plugin.settings);new h.Notice(`\u2713 ${i.slice(0,180)}`,8e3)}catch(i){new h.Notice(this.tr("backendTestFailed",{error:i instanceof Error?i.message:String(i)}),1e4)}})),new h.Setting(t).setName(this.tr("settingExportFolderName")).setDesc(this.tr("settingExportFolderDesc")).addText(r=>r.setValue(this.plugin.settings.exportFolder).onChange(i=>{this.plugin.settings.exportFolder=i.trim()||m.exportFolder,this.plugin.saveSettingsDebounced()}))}renderCacheSection(t){new h.Setting(t).setName(this.tr("cacheHeader")).setHeading(),new h.Setting(t).setName(this.tr("settingMaxCacheName")).setDesc(this.tr("settingMaxCacheDesc")).addText(r=>{r.setValue(String(this.plugin.settings.maxCacheEntries||K));let i=async()=>{let a=parseInt(r.getValue(),10);if(Number.isFinite(a)&&a>0){this.plugin.settings.maxCacheEntries=a,await this.plugin.saveSettings();let s=await this.plugin.pruneCacheIfNeeded();s.length>0&&new h.Notice(this.tr("cachePruned",{count:s.length})),this.display()}};return r.inputEl.addEventListener("change",()=>{i().catch(a=>console.error("[parallel-reader] failed to save cache settings",a))}),r.inputEl.addEventListener("keydown",a=>{a.key==="Enter"&&r.inputEl.blur()}),r});let e=Object.keys(this.plugin.cache).length;new h.Setting(t).setName(this.tr("cachedNotesName",{count:e})).setDesc(this.tr("cachedNotesDesc")).addButton(r=>r.setButtonText(this.tr("clearAllCacheButton")).setWarning().onClick(async()=>{let i=Object.keys(this.plugin.cache).length;await this.plugin.cacheClear(),new h.Notice(this.tr("cacheClearedAll",{count:i})),this.display()}))}};var mt={};ft(mt,{CACHE_SCHEMA_VERSION:()=>J,CacheManager:()=>$,GenerationJobAlreadyRunningError:()=>O,GenerationJobCancelledError:()=>P,GenerationJobManager:()=>z,activeIndexAfterCardDelete:()=>Re,activeSectionLine:()=>Ke,addIconButton:()=>L,addTextButton:()=>R,batchProgressVars:()=>be,buildAnthropicMessagesBody:()=>V,buildGeminiBody:()=>X,buildOpenAiChatBody:()=>G,buildOpenAiResponsesBody:()=>Y,buildPrompts:()=>De,cacheEntryMatches:()=>D,cancellationNoticeKey:()=>Ve,cardsToMarkdown:()=>ee,classifyGenerationError:()=>Ne,collectJsonObjectCandidates:()=>Ie,copyToClipboard:()=>N,createBatchRunState:()=>Se,createBatchStats:()=>Ce,createRafThrottledHandler:()=>He,deltaExtractorForFormat:()=>ce,extractJson:()=>it,findLineForAnchor:()=>q,folderPathsForTarget:()=>ht,generationFingerprint:()=>ie,getApiBaseUrl:()=>M,hasUnsafeBatchFolderSegments:()=>tt,markBatchFileRunning:()=>Pe,modelForApi:()=>I,nextCardIndex:()=>Je,normalizeBatchFolderInput:()=>ge,normalizeCardsPayload:()=>W,normalizeSettings:()=>re,normalizeStreamingTimeoutMs:()=>ne,parseApiHeaders:()=>ct,parseSseBuffer:()=>ot,pruneCacheEntries:()=>me,recordBatchError:()=>xe,recordBatchProcessed:()=>we,recordBatchSkip:()=>ve,removeCardAt:()=>Fe,repairTruncatedCardsJson:()=>at,requestBatchCancel:()=>ae,resolveCliPath:()=>B,runCli:()=>_,selectBatchFiles:()=>ye,serializeCacheFile:()=>ke,shouldConfirmRegenerate:()=>Ee,shouldSkipBatchFile:()=>Ae,summarizeDocument:()=>_e,summarizeViaApi:()=>ue,supportsStreaming:()=>Be,tokenLimitFieldForOpenAiChat:()=>Oe,touchCacheEntry:()=>Te,translate:()=>y,updateCardAt:()=>Me,validateBatchFolderInput:()=>fe,visibleTopProbeY:()=>Ue});function Je(n,t,e){if(!Number.isFinite(t)||t<=0)return-1;let r=Math.floor(t),i=e<0?-1:1;return n<0||n>=r?i<0?r-1:0:Math.min(r-1,Math.max(0,n+i))}function Ke(n,t){if(!Array.isArray(n)||t<0||t>=n.length)return-1;let e=Number(n[t]?.startLine);return Number.isFinite(e)&&e>=0?e:-1}function pt(n){return String(n||"").split("/").map(t=>t.trim()).filter(t=>!!t&&t!==".."&&t!==".").join("/")}function ht(n){let t=pt(n);if(!t)return[];let e=t.split("/");return e.map((r,i)=>e.slice(0,i+1).join("/"))}async function Kt(n,t){for(let e of ht(t))if(!n.vault.getAbstractFileByPath(e))try{await n.vault.createFolder(e)}catch(r){if(!n.vault.getAbstractFileByPath(e))throw r}}var A=require("obsidian");var U="parallel-reader-view",$e=class extends A.ItemView{constructor(e,r){super(e);this.stale=!1;this.loadingMessage="";this.errorMessage="";this.plugin=r,this.sections=[],this.sourceFile=null,this.cards=[],this.activeIdx=-1}getViewType(){return U}getDisplayText(){return this.plugin.t("displayName")}getIcon(){return"book-open"}onOpen(){let e=this.containerEl.children[1];return e.empty(),e.addClass("parallel-reader-container"),e.setAttr("tabindex","0"),e.addEventListener("keydown",r=>this.handleKeydown(r)),this.renderEmpty(),this.focusSummaryPane(),Promise.resolve()}onClose(){return Promise.resolve()}renderEmpty(){this.sourceFile=null,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage="";let e=this.containerEl.children[1];e.empty();let r=e.createDiv({cls:"parallel-reader-empty"});r.createEl("h3",{text:this.plugin.t("appTitle")}),r.createEl("p",{text:this.plugin.t("emptyOpenNote")}),r.createEl("code",{text:this.plugin.t("commandGenerate")})}focusSummaryPane(){let e=this.containerEl.children[1];return!e||typeof e.focus!="function"?!1:(e.focus({preventScroll:!0}),!0)}loadFor(e,r,i){this.sourceFile=e,this.sections=r,this.stale=!!i,this.loadingMessage="",this.errorMessage="",this.render()}renderLoading(e,r){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage=r||this.plugin.t("loadingDefault"),this.errorMessage="",this.render()}renderStreamingPreview(e,r){this.sourceFile?.path!==e.path&&(this.sourceFile=e);let i=this.containerEl.children[1],a=i.querySelector(".parallel-reader-streaming-preview");if(a){let g=a.querySelector("pre");g&&(g.textContent=r.slice(-2e3));let b=a.querySelector(".parallel-reader-stream-counter");b&&(b.textContent=`${r.length} chars`);return}i.empty();let o=i.createDiv({cls:"parallel-reader-header"}).createDiv({cls:"parallel-reader-header-row"});o.createEl("div",{text:e.basename,cls:"parallel-reader-title"});let l=o.createDiv({cls:"parallel-reader-actions"});L(l,"square",this.plugin.t("actionCancel"),()=>{this.plugin.cancelGenerationForFile(e)});let c=i.createDiv({cls:"parallel-reader-state parallel-reader-loading parallel-reader-streaming-preview"});c.createDiv({cls:"parallel-reader-spinner"});let d=c.createEl("div",{cls:"parallel-reader-state-title"});d.createSpan({text:this.plugin.t("loadingGenerating")+" "}),d.createSpan({cls:"parallel-reader-stream-counter",text:`${r.length} chars`});let u=c.createEl("pre",{cls:"parallel-reader-stream-text"});u.textContent=r.slice(-2e3)}renderError(e,r){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage=r||this.plugin.t("errorTitle"),this.render()}renderEmptyWithHint(e){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage="";let r=this.containerEl.children[1];r.empty();let i=r.createDiv({cls:"parallel-reader-empty"});i.createEl("h3",{text:e.basename}),i.createEl("p",{text:this.plugin.t("emptyNoCache")}),i.createEl("code",{text:this.plugin.t("commandGenerate")}),R(i,null,this.plugin.t("actionGenerate"),()=>{this.plugin.isGeneratingFile(e)||this.plugin.runForFile(e,!1)})}render(){let e=this.containerEl.children[1];if(e.empty(),this.renderHeader(e),this.stale&&this.renderStaleBanner(e),this.loadingMessage){this.renderLoadingState(e);return}if(this.errorMessage){this.renderErrorState(e);return}this.renderCardList(e)}renderHeader(e){let i=e.createDiv({cls:"parallel-reader-header"}).createDiv({cls:"parallel-reader-header-row"});i.createEl("div",{text:this.sourceFile?.basename||"",cls:"parallel-reader-title"});let a=i.createDiv({cls:"parallel-reader-actions"});this.sourceFile&&(this.plugin.isGeneratingFile(this.sourceFile)?L(a,"square",this.plugin.t("actionCancel"),()=>{this.plugin.cancelGenerationForFile(this.sourceFile)}):L(a,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0)),L(a,"copy",this.plugin.t("actionCopyAll"),()=>this.plugin.copyCurrentViewMarkdown()),L(a,"download",this.plugin.t("actionExport"),()=>this.exportToVault()))}renderStaleBanner(e){let r=e.createDiv({cls:"parallel-reader-stale-banner"});r.createSpan({text:this.plugin.t("staleBanner")}),R(r,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0),"parallel-reader-stale-button")}renderLoadingState(e){let r=e.createDiv({cls:"parallel-reader-state parallel-reader-loading"});r.createDiv({cls:"parallel-reader-spinner"}),r.createEl("div",{text:this.loadingMessage,cls:"parallel-reader-state-title"}),r.createEl("div",{text:this.plugin.t("loadingSubtitle"),cls:"parallel-reader-state-subtitle"})}renderErrorState(e){let r=e.createDiv({cls:"parallel-reader-state parallel-reader-error"});r.createEl("div",{text:this.plugin.t("errorTitle"),cls:"parallel-reader-state-title"}),r.createEl("div",{text:this.errorMessage,cls:"parallel-reader-state-subtitle parallel-reader-selectable"});let i=r.createDiv({cls:"parallel-reader-error-actions"});R(i,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0),"parallel-reader-text-button"),R(i,"copy",this.plugin.t("actionCopyError"),()=>N(this.errorMessage,this.plugin.t("actionCopyError")),"parallel-reader-text-button")}renderCardList(e){let r=e.createDiv({cls:"parallel-reader-cards"});this.cards=[];let i=this.sourceFile?.path||"";this.sections.forEach((a,s)=>{this.cards.push(this.renderCard(r,a,s,i))}),this.activeIdx>=0&&this.cards[this.activeIdx]&&this.cards[this.activeIdx].addClass("is-active")}renderCard(e,r,i,a){let s=e.createDiv({cls:"parallel-reader-card"});s.dataset.idx=String(i),r.startLine<0&&s.addClass("parallel-reader-card-unanchored");let o=s.createEl("div",{cls:"parallel-reader-card-title"});if(o.createSpan({text:r.title}),r.startLine<0&&o.createEl("span",{text:" \u26A0",cls:"parallel-reader-warn",title:this.plugin.t("anchorMismatch")}),r.gist){let c=s.createEl("div",{cls:"parallel-reader-gist"});A.MarkdownRenderer.render(this.app,r.gist,c,a,this).catch(()=>{c.setText(r.gist)})}let l=r.bullets||[];if(l.length>0){let c=s.createEl("div",{cls:"parallel-reader-bullets-md"}),d=l.map(u=>`- ${u}`).join(`
`);A.MarkdownRenderer.render(this.app,d,c,a,this).catch(()=>{c.setText(d)})}else r.gist||s.createEl("div",{cls:"parallel-reader-empty-li",text:this.plugin.t("emptyCard")});return s.addEventListener("click",c=>{let d=window.getSelection();if(d&&d.toString().length>0)return;let u=c.target;u&&u.tagName==="A"||r.startLine>=0&&this.plugin.scrollEditorToLine(r.startLine,this.sourceFile)}),s.addEventListener("contextmenu",c=>{c.preventDefault(),this.showCardContextMenu(c,r,i)}),s}showCardContextMenu(e,r,i){let a=new A.Menu;a.addItem(s=>s.setTitle(this.plugin.t("menuCopyMarkdown")).setIcon("copy").onClick(()=>N(ut(r),this.plugin.t("copiedMarkdown")))),a.addItem(s=>s.setTitle(this.plugin.t("menuCopyPlain")).setIcon("clipboard-copy").onClick(()=>N(Ht(r),this.plugin.t("copiedPlain")))),r.anchor&&a.addItem(s=>s.setTitle(this.plugin.t("menuCopyAnchor")).setIcon("quote-glyph").onClick(()=>N(r.anchor,this.plugin.t("copiedAnchor")))),a.addSeparator(),r.startLine>=0&&a.addItem(s=>s.setTitle(this.plugin.t("menuJumpSource")).setIcon("arrow-right").onClick(()=>this.plugin.scrollEditorToLine(r.startLine,this.sourceFile))),a.addSeparator(),a.addItem(s=>s.setTitle(this.plugin.t("menuEditCard")).setIcon("pencil").onClick(()=>this.openEditCardModal(i))),a.addItem(s=>s.setTitle(this.plugin.t("menuDeleteCard")).setIcon("trash").onClick(()=>this.deleteCard(i))),a.showAtMouseEvent(e)}setActiveSection(e){e!==this.activeIdx&&(this.activeIdx>=0&&this.cards[this.activeIdx]&&this.cards[this.activeIdx].removeClass("is-active"),this.activeIdx=e,e>=0&&this.cards[e]&&(this.cards[e].addClass("is-active"),this.cards[e].scrollIntoView({block:"nearest",behavior:"smooth"})))}moveActiveSection(e){let r=Je(this.activeIdx,this.sections.length,e);return this.setActiveSection(r),this.focusSummaryPane(),r}jumpToActiveSection(){let e=Ke(this.sections,this.activeIdx);return e<0||!this.sourceFile?-1:(this.plugin.scrollEditorToLine(e,this.sourceFile),e)}handleKeydown(e){if(e.altKey&&e.key==="ArrowUp"){e.preventDefault(),this.moveActiveSection(-1);return}if(e.altKey&&e.key==="ArrowDown"){e.preventDefault(),this.moveActiveSection(1);return}!e.altKey&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&e.key==="Enter"&&this.jumpToActiveSection()>=0&&e.preventDefault()}async deleteCard(e){if(!this.sourceFile)return!1;let r=Fe(this.sections,e);if(r.length===this.sections.length)return!1;let i=this.sections.length;return this.sections=r,this.activeIdx=Re(e,i,this.activeIdx),await this.plugin.cacheReplaceCards(this.sourceFile.path,r),this.render(),new A.Notice(this.plugin.t("cardDeleted")),!0}openEditCardModal(e){return!this.sourceFile||!this.sections[e]?!1:(new Ge(this.app,this.plugin,this.sections[e],async r=>{await this.updateCard(e,r)}).open(),!0)}async updateCard(e,r){if(!this.sourceFile)return!1;let i=Me(this.sections,e,r);return i.length!==this.sections.length?!1:(this.sections=i,await this.plugin.cacheReplaceCards(this.sourceFile.path,i),this.render(),new A.Notice(this.plugin.t("cardSaved")),!0)}async exportToVault(){if(!this.sourceFile)return;let e=pt(this.plugin.settings.exportFolder),r=`${this.sourceFile.basename} - ${this.plugin.t("displayName")}.md`,i=`${e}/${r}`,a=["---",`source: [[${this.sourceFile.basename}]]`,`generated: ${new Date().toISOString().slice(0,10)}`,"tool: parallel-reader","---","",ee(`${this.sourceFile.basename} \xB7 ${this.plugin.t("displayName")}`,this.sections),""].join(`
`),s=this.plugin.app;await Kt(s,e);let o=s.vault.getAbstractFileByPath(i);o instanceof A.TFile?await s.vault.modify(o,a):await s.vault.create(i,a),new A.Notice(this.plugin.t("exported",{path:i}))}};var gt=class extends p.Plugin{constructor(){super(...arguments);this.activeBatch=null;this._scrollDispose=null;this._settingsSaveTimer=null}get cache(){return this.cacheManager.cache}t(e,r){return y(this.settings||m,e,r)}async onload(){await this.loadSettings(),this.jobs=new z,this.addRibbonIcon("book-open",this.t("ribbonOpen"),async()=>{let e=this.getActiveView();await this.ensureView()&&e?.file&&await this.syncViewToFile(e.file)}),this.registerView(U,e=>new $e(e,this)),this.addCommand({id:"run",name:this.t("cmdRun"),callback:()=>this.runForActiveFile(!1)}),this.addCommand({id:"regen",name:this.t("cmdRegen"),callback:()=>this.runForActiveFile(!0)}),this.addCommand({id:"open-view",name:this.t("cmdOpenView"),callback:async()=>{let e=this.getActiveView();await this.ensureView()&&e?.file&&await this.syncViewToFile(e.file)}}),this.addCommand({id:"export-current",name:this.t("cmdExport"),callback:()=>this.exportCurrentView()}),this.addCommand({id:"copy-current-markdown",name:this.t("cmdCopyMarkdown"),callback:()=>this.copyCurrentViewMarkdown()}),this.addCommand({id:"cancel-current",name:this.t("cmdCancel"),callback:()=>this.cancelActiveGeneration()}),this.addCommand({id:"clear-current",name:this.t("cmdClearCurrent"),callback:async()=>{let e=this.getActiveView();if(!e?.file){new p.Notice(this.t("noCurrentNote"));return}await this.cacheManager.delete(e.file.path),new p.Notice(this.t("cacheClearedFile",{name:e.file.basename}))}}),this.addCommand({id:"clear-all",name:this.t("cmdClearAll"),callback:async()=>{let e=Object.keys(this.cacheManager.cache).length;await this.cacheManager.clear(),new p.Notice(this.t("cacheClearedAll",{count:e}))}}),this.addCommand({id:"card-prev",name:this.t("cmdCardPrev"),callback:()=>this.moveActiveCard(-1)}),this.addCommand({id:"card-next",name:this.t("cmdCardNext"),callback:()=>this.moveActiveCard(1)}),this.addCommand({id:"card-jump",name:this.t("cmdCardJump"),callback:()=>this.jumpActiveCard()}),this.addCommand({id:"batch-generate",name:this.t("cmdBatchGenerate"),callback:()=>this.runBatchForFolder()}),this.addSettingTab(new je(this.app,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>this.bindScrollSync())),this.registerEvent(this.app.workspace.on("file-open",e=>{e&&this.syncViewToFile(e).catch(r=>console.error("[parallel-reader] sync view",r))})),this.registerEvent(this.app.workspace.on("file-menu",(e,r)=>this.addFileMenuItems(e,r))),this.registerEvent(this.app.vault.on("rename",(e,r)=>{e instanceof p.TFile&&this.handleFileRename(e,r).catch(i=>console.error("[parallel-reader] file rename",i))})),this.registerEvent(this.app.vault.on("delete",e=>{e instanceof p.TFile&&this.handleFileDelete(e).catch(r=>console.error("[parallel-reader] file delete",r))})),this.bindScrollSync()}onunload(){this.flushSettingsSave().catch(e=>console.error("[parallel-reader] flush settings on unload",e)),this.flushCacheSave().catch(e=>console.error("[parallel-reader] flush cache on unload",e))}async loadSettings(){let r=(await this.loadData()||{}).settings||{};this.settings=re(Object.assign({},m,r)),this.cacheManager=new $(this.app.vault.adapter,this.app.vault.configDir,this.manifest?.id||"parallel-reader",()=>this.settings),await this.cacheManager.load()}async saveSettings(){this._settingsSaveTimer&&(clearTimeout(this._settingsSaveTimer),this._settingsSaveTimer=null),await this.saveData({settings:this.settings})}saveSettingsDebounced(e=400){this._settingsSaveTimer&&clearTimeout(this._settingsSaveTimer),this._settingsSaveTimer=setTimeout(()=>{this._settingsSaveTimer=null,this.saveSettings().catch(r=>console.error("[parallel-reader] failed to save settings",r))},e)}async flushSettingsSave(){this._settingsSaveTimer&&(clearTimeout(this._settingsSaveTimer),this._settingsSaveTimer=null,await this.saveSettings())}cacheTouch(e){return this.cacheManager.touch(e)}scheduleCacheSave(e=5e3){this.cacheManager.scheduleSave(e)}async flushCacheSave(){await this.cacheManager.flush()}async cacheReplaceCards(e,r){return this.cacheManager.replaceCards(e,r)}async cacheClear(){return this.cacheManager.clear()}async pruneCacheIfNeeded(){return this.cacheManager.pruneIfNeeded()}async ensureView(){let{workspace:e}=this.app,r=e.getLeavesOfType(U)[0];if(!r){let i=e.getRightLeaf(!1);if(!i)return new p.Notice(this.t("viewOpenFailed")),null;r=i,await r.setViewState({type:U,active:!0})}return await e.revealLeaf(r),r.view}getActiveView(){return this.app.workspace.getActiveViewOfType(p.MarkdownView)}getParallelView(){return this.app.workspace.getLeavesOfType(U)[0]?.view}moveActiveCard(e){let r=this.getParallelView();return r?.sections.length?r.moveActiveSection(e):(new p.Notice(this.t("noActiveCard")),-1)}jumpActiveCard(){let e=this.getParallelView();return!e||e.jumpToActiveSection()<0?(new p.Notice(this.t("noActiveCard")),!1):!0}isGeneratingFile(e){return!!e&&!!e.path&&this.jobs.isRunning(e.path)}cancelGenerationForFile(e){if(!e?.path)return new p.Notice(this.t("noCancelableJob")),!1;let r=this.jobs.get(e.path),i=Ve(this.settings,r),a=this.jobs.cancel(e.path);return a&&this.activeBatch?.currentPath===e.path&&ae(this.activeBatch),new p.Notice(a?this.t(i):this.t("noCancelableJob")),a}requestBatchCancellation(){return ae(this.activeBatch)}viewIsShowingFile(e,r){return!!e&&!!r&&e.sourceFile?.path===r.path}activeFileStillMatches(e){let r=this.getActiveView();return!r?.file||r.file.path===e.path}cancelActiveGeneration(){if(this.requestBatchCancellation()){let i=this.activeBatch?.currentPath;i&&this.jobs.cancel(i),new p.Notice(this.t("batchCancelRequested"));return}let e=this.getActiveView();if(e?.file&&this.cancelGenerationForFile(e.file))return;let r=this.getParallelView();r?.sourceFile?this.cancelGenerationForFile(r.sourceFile):new p.Notice(this.t("noCancelableJob"))}confirmRegenerateEditedCards(){return jt(this.app,this.t("displayName"),this.t("confirmRegenerateEditedCards"))}addFileMenuItems(e,r){!(r instanceof p.TFile)||!r.path.endsWith(".md")||(e.addSeparator(),e.addItem(i=>i.setTitle(this.t("fileMenuGenerate")).setIcon("book-open").onClick(()=>this.runForFile(r,!1))),e.addItem(i=>i.setTitle(this.t("fileMenuRegen")).setIcon("refresh-cw").onClick(()=>this.runForFile(r,!0))),this.cacheManager.get(r.path)&&e.addItem(i=>i.setTitle(this.t("fileMenuClear")).setIcon("trash").onClick(async()=>{await this.cacheManager.delete(r.path),new p.Notice(this.t("cacheClearedFile",{name:r.basename}))})))}async handleFileRename(e,r){if(!(e instanceof p.TFile)||!r)return;let i=r.endsWith(".md"),a=e.path.endsWith(".md");if(!i&&!a)return;if(i&&!a){await this.cacheManager.delete(r);let o=this.getParallelView();o&&o.sourceFile?.path===r&&o.renderEmpty();return}if(!i)return;await this.cacheManager.move(r,e.path);let s=this.getParallelView();s?.sourceFile&&(s.sourceFile.path===r||s.sourceFile.path===e.path)&&(s.sourceFile=e,await this.syncViewToFile(e))}async handleFileDelete(e){if(!(e instanceof p.TFile))return;await this.cacheManager.delete(e.path);let r=this.getParallelView();r?.sourceFile?.path===e.path&&r.renderEmpty()}async exportCurrentView(){let e=this.getActiveView(),r=await this.ensureView();if(r){if((!r.sourceFile||!r.sections.length)&&e?.file&&await this.syncViewToFile(e.file),!r.sourceFile||!r.sections.length){new p.Notice(this.t("noExportContent"));return}await r.exportToVault()}}async copyCurrentViewMarkdown(){let e=this.getActiveView(),r=await this.ensureView();if(r){if((!r.sourceFile||!r.sections.length)&&e?.file&&await this.syncViewToFile(e.file),!r.sourceFile||!r.sections.length){new p.Notice(this.t("noCopyContent"));return}await N(ee(`${r.sourceFile.basename} \xB7 ${this.t("displayName")}`,r.sections),this.t("copiedAllMarkdown"))}}async runForActiveFile(e){let r=this.getActiveView();if(!r?.file){new p.Notice(this.t("openNoteFirst"));return}return this.runForFile(r.file,e)}async runForFile(e,r){if(!e){new p.Notice(this.t("openNoteFirst"));return}if(this.jobs.isRunning(e.path)){new p.Notice(this.t("alreadyGenerating"));return}if(Ee(this.cacheManager.get(e.path),r)&&!await this.confirmRegenerateEditedCards()){new p.Notice(this.t("regenerateCancelled"));return}let i=null;return this.jobs.start(e.path,async a=>{a.setPhase("reading");let s=await this.app.vault.read(e);if(a.throwIfCancelled(),!s.trim()){new p.Notice(this.t("emptyNote"));return}if(i=await this.ensureView(),!i)return;if(a.throwIfCancelled(),a.setPhase("cache-check"),!r){let u=this.cacheManager.get(e.path);if(u&&D(u,s,this.settings)){this.cacheTouch(e.path),this.activeFileStillMatches(e)&&i.loadFor(e,rt(s,u.cards),!1);return}}i.renderLoading(e,this.t("loadingGenerating"));let o=Number(this.settings.maxDocChars)||m.maxDocChars;s.length>o&&new p.Notice(this.t("longNoteTruncated",{count:o})),new p.Notice(this.t("generatingNotice")),a.setPhase("generating");let l=await _e(s,this.settings,a,this.streamProgressFor(i,e));if(a.throwIfCancelled(),l.length===0){new p.Notice(this.t("noCardsReturned"));return}let c=l.map(u=>({title:u.title,anchor:u.anchor,gist:u.gist,bullets:u.bullets}));a.setPhase("saving"),await this.cacheManager.put(e.path,s,c,this.settings),a.throwIfCancelled(),this.viewIsShowingFile(i,e)&&i.loadFor(e,l,!1);let d=l.filter(u=>u.startLine<0).length;new p.Notice(this.t("generationDone",{count:l.length,suffix:d?this.t("unanchoredSuffix",{count:d}):""}))}).catch(a=>this.handleGenerationError(a,e,i))}streamProgressFor(e,r){if(e)return i=>{!i.done&&this.viewIsShowingFile(e,r)&&e.renderStreamingPreview(r,i.accumulated)}}handleGenerationError(e,r,i){if(e instanceof O){new p.Notice(e.message);return}if(e instanceof P){i&&this.viewIsShowingFile(i,r)&&i.renderError(r,this.t("cancelledError")),new p.Notice(this.t("cancelled"));return}let a=Ne(e),s=e instanceof Error?e.message:String(e);console.error(e),i&&this.viewIsShowingFile(i,r)&&i.renderError(r,s),new p.Notice(this.t("generationFailed",{kind:a==="unknown"?"":` (${a})`,error:s}))}async runBatchForFolder(){if(this.activeBatch){new p.Notice(this.t("batchAlreadyRunning"));return}let e=await St(this.app,this.t("batchSelectFolder"),this.t("batchFolderPrompt"));if(e===null)return;let r=fe(e,l=>{let c=this.app.vault.getAbstractFileByPath(l);return!!c&&!(c instanceof p.TFile)});if(!r.valid){let l=r.reason==="unsafe"?"batchInvalidFolderInput":"batchFolderNotFound";new p.Notice(this.t(l,{path:r.folderPath||e}));return}let i=ye(this.app.vault.getMarkdownFiles(),r.folderPath);if(i.length===0){new p.Notice(this.t("batchNoMarkdown"));return}let a=Se();this.activeBatch=a;let s=Ce(i.length);try{for(let l=0;l<i.length&&!a.cancelled;l++){let c=i[l];Pe(a,c.path),new p.Notice(this.t("batchProgress",be(l,i.length)));let d=await this.app.vault.read(c);if(a.cancelled)break;let u=this.cacheManager.get(c.path);if(Ae(u,d,this.settings)){s=ve(s);continue}try{await this.runForFile(c,!1),s=we(s)}catch(g){s=xe(s),console.error("[parallel-reader] batch error for",c.path,g)}}}finally{this.activeBatch===a&&(this.activeBatch=null)}let o={processed:s.processed,skipped:s.skipped,errors:s.errors,total:s.total};a.cancelled?new p.Notice(this.t("batchCancelled",o)):new p.Notice(this.t("batchDone",o))}async syncViewToFile(e){if(!e?.path?.endsWith(".md"))return;let r=this.app.workspace.getLeavesOfType(U);if(r.length===0)return;let i=r[0].view;if(!i||!this.activeFileStillMatches(e))return;let a=this.cacheManager.get(e.path);if(!a){i.loadFor(e,[],!1),i.renderEmptyWithHint(e);return}let s=await this.app.vault.read(e);if(!this.activeFileStillMatches(e))return;let o=!D(a,s,this.settings);this.cacheTouch(e.path),i.loadFor(e,rt(s,a.cards),o)}bindScrollSync(){this._scrollDispose&&(this._scrollDispose(),this._scrollDispose=null);let e=this.getActiveView();if(!e)return;let r=e.editor,i=r&&r.cm,a=i?.scrollDOM?i.scrollDOM:e.contentEl.querySelector(".cm-scroller");if(!a)return;let s=He(()=>this.handleEditorScroll(e));a.addEventListener("scroll",s,{passive:!0}),this._scrollDispose=()=>{s.cancel(),a.removeEventListener("scroll",s)}}handleEditorScroll(e){let r=this.getParallelView();if(!r||!e.file||r.sourceFile?.path!==e.file.path)return;let i=e.editor,a=i&&i.cm;if(!a?.scrollDOM)return;let s=a.scrollDOM.getBoundingClientRect(),o=Ue(s),l=0;try{let d=a.posAtCoords({x:s.left+20,y:o});d!=null&&(l=a.state.doc.lineAt(d).number-1)}catch{return}let c=-1;for(let d=0;d<r.sections.length;d++){let u=r.sections[d];if(!(u.startLine<0))if(u.startLine<=l)c=d;else break}r.setActiveSection(c)}findLeafForFile(e){if(!e)return null;for(let r of this.app.workspace.getLeavesOfType("markdown")){let i=r.view;if(i?.file&&i.file.path===e.path)return r}return null}async scrollEditorToLine(e,r){let i=r?this.findLeafForFile(r):null;if(!i&&r&&(i=this.app.workspace.getLeaf("tab"),await i.openFile(r,{active:!1})),!i){let s=this.getActiveView();s&&(i=s.leaf)}if(!i){new p.Notice(this.t("noEditor"));return}this.app.workspace.setActiveLeaf(i,{focus:!0});let a=i.view;if(a instanceof p.MarkdownView&&(a.setEphemeralState({line:e}),a.editor))try{a.editor.setCursor({line:e,ch:0}),a.editor.scrollIntoView({from:{line:e,ch:0},to:{line:e,ch:0}},!0)}catch{}}},xr=gt,Ar=mt;0&&(module.exports={__test});