Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Ollama text/llm provider #60

Merged
merged 5 commits into from
Aug 6, 2024
Merged

Add Ollama text/llm provider #60

merged 5 commits into from
Aug 6, 2024

Conversation

justyns
Copy link
Owner

@justyns justyns commented Aug 6, 2024

Fixes #57

This is just a wrapper/proxy around the openai provider for now, but should let us add ollama-specific features more easily in the future.

Summary by CodeRabbit

  • New Features

    • Introduced functionality to select embedding, image, and text models from configuration.
    • Added support for the new Ollama provider, enhancing language model options.
    • Enhanced documentation for installation, configuration, and usage of providers.
  • Bug Fixes

    • Improved error handling and logging in publishing processes.
  • Documentation

    • Updated installation instructions and added examples for Ollama provider setup.
    • Revised quick start documentation to reflect updates in model specifications.

Copy link
Contributor

coderabbitai bot commented Aug 6, 2024

Walkthrough

Walkthrough

The recent changes enhance the functionality of the software by introducing new commands for selecting embedding and image models, alongside a new Ollama provider for text and language model usage. Documentation updates include version changes, improved installation instructions, and added functionalities for various providers. The modifications aim to improve user interaction and expand integration options for AI models, ensuring a more flexible and robust platform.

Changes

Files Change Summary
docs/Changelog.md Exposed searchCombinedEmbeddings in AICore; added [[Providers/Ollama]].
docs/Commands/AI: Select Embedding Model from Config.md Introduced command to select embedding model from config.
docs/Commands/AI: Select Image Model from Config.md Introduced command to select image model from config.
docs/Commands/AI: Select Text Model from Config.md Introduced command to select text model from config.
docs/Installation.md Updated version number for silverbullet-ai from 0.3.1 to 0.3.2.
docs/PLUGS.md Added entry for joekrill/silverbullet-treeview.
docs/Providers/Ollama.md Updated textProvider flag to true; added configuration section.
docs/Quick Start.md Updated model specifications from gpt-3-turbo to gpt-4o-mini.
src/_plug/pub.plug.js Enhanced asynchronous handling and error management in publishing workflow.
src/embeddings.ts Removed debugSearchEmbeddings function.
src/init.ts Expanded import for OllamaProvider and updated setup logic.
src/providers/ollama.ts Added OllamaProvider class and chatWithAI method.
src/types.ts Added Ollama to Provider enum.

Assessment against linked issues

Objective Addressed Explanation
Is it expected to pass openai as provider for ollama models? (#57) Documentation indicates using openai as provider, but lacks clarity on ollama support as a provider. Further clarification is needed on intended behavior.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Outside diff range, codebase verification and nitpick comments (1)
docs/Providers/Ollama.md (1)

31-31: Expanded description of requireAuth.

The expanded description is clear and informative. However, a comma is missing after "Otherwise".

- Otherwise you will get a CORS error.
+ Otherwise, you will get a CORS error.
Tools
LanguageTool

[uncategorized] ~31-~31: A comma may be missing after the conjunctive/linking adverb ‘Otherwise’.
Context: ...at the Authorization header isn't set. Otherwise you will get a CORS error. It can also ...

(SENT_START_CONJUNCTIVE_LINKING_ADVERB_COMMA)

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d869bf7 and 83b4625.

Files ignored due to path filters (4)
  • README.md is excluded by none and included by none
  • sbai.ts is excluded by none and included by none
  • scripts/create-test-space.sh is excluded by none and included by none
  • silverbullet-ai.plug.yaml is excluded by none and included by none
Files selected for processing (13)
  • docs/Changelog.md (1 hunks)
  • docs/Commands/AI: Select Embedding Model from Config.md (1 hunks)
  • docs/Commands/AI: Select Image Model from Config.md (1 hunks)
  • docs/Commands/AI: Select Text Model from Config.md (1 hunks)
  • docs/Installation.md (1 hunks)
  • docs/PLUGS.md (1 hunks)
  • docs/Providers/Ollama.md (2 hunks)
  • docs/Quick Start.md (1 hunks)
  • docs/_plug/pub.plug.js (1 hunks)
  • src/embeddings.ts (1 hunks)
  • src/init.ts (2 hunks)
  • src/providers/ollama.ts (1 hunks)
  • src/types.ts (1 hunks)
Files skipped from review due to trivial changes (4)
  • docs/Commands/AI: Select Embedding Model from Config.md
  • docs/Commands/AI: Select Image Model from Config.md
  • docs/Commands/AI: Select Text Model from Config.md
  • docs/Installation.md
Additional context used
Path-based instructions (8)
docs/PLUGS.md (1)

Pattern **/*.md: Review these markdown files. They are written for a markdown note taking tool called Silverbullet, and may contain extra syntax not typically found in markdown.

Ensure any documentation makes sense and is good.

docs/Providers/Ollama.md (1)

Pattern **/*.md: Review these markdown files. They are written for a markdown note taking tool called Silverbullet, and may contain extra syntax not typically found in markdown.

Ensure any documentation makes sense and is good.

docs/Quick Start.md (1)

Pattern **/*.md: Review these markdown files. They are written for a markdown note taking tool called Silverbullet, and may contain extra syntax not typically found in markdown.

Ensure any documentation makes sense and is good.

src/providers/ollama.ts (1)

Pattern **/*.ts: Review these typescript files for best practices, readability, and DRY.

src/types.ts (1)

Pattern **/*.ts: Review these typescript files for best practices, readability, and DRY.

docs/Changelog.md (1)

Pattern **/*.md: Review these markdown files. They are written for a markdown note taking tool called Silverbullet, and may contain extra syntax not typically found in markdown.

Ensure any documentation makes sense and is good.

src/init.ts (1)

Pattern **/*.ts: Review these typescript files for best practices, readability, and DRY.

src/embeddings.ts (1)

Pattern **/*.ts: Review these typescript files for best practices, readability, and DRY.

LanguageTool
docs/Providers/Ollama.md

[uncategorized] ~31-~31: A comma may be missing after the conjunctive/linking adverb ‘Otherwise’.
Context: ...at the Authorization header isn't set. Otherwise you will get a CORS error. It can also ...

(SENT_START_CONJUNCTIVE_LINKING_ADVERB_COMMA)

Biome
docs/_plug/pub.plug.js

[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

Additional comments not posted (15)
docs/PLUGS.md (1)

5-5: New plug entry added.

The entry for github:joekrill/silverbullet-treeview/treeview.plug.js is correctly formatted and logically placed within the list.

docs/Providers/Ollama.md (2)

3-3: Updated textProvider flag.

The textProvider flag is correctly updated to true.


15-22: New configuration section for using Ollama locally.

The configuration examples for using Ollama locally are accurate and clearly documented.

docs/Quick Start.md (1)

34-36: Updated model specifications.

The model specifications are correctly updated to gpt-4o-mini.

src/providers/ollama.ts (4)

12-31: Constructor initializes OllamaProvider correctly.

The constructor initializes the OllamaProvider with the necessary parameters and creates an instance of OpenAIProvider. This setup ensures that the OllamaProvider can leverage the capabilities of the OpenAIProvider while maintaining its own identity.


33-41: chatWithAI method correctly forwards parameters.

The chatWithAI method correctly forwards the parameters to the chatWithAI method of the OpenAIProvider instance. This ensures that the OllamaProvider can utilize the chat functionalities of the OpenAIProvider.


Line range hint 43-47:
Constructor initializes OllamaEmbeddingProvider correctly.

The constructor initializes the OllamaEmbeddingProvider with the necessary parameters, ensuring that the provider can generate embeddings using the Ollama API.


Line range hint 49-78:
_generateEmbeddings method correctly handles embedding generation.

The _generateEmbeddings method sends a POST request to the Ollama API to generate embeddings. It includes proper error handling for HTTP responses and validates the response data.

src/types.ts (1)

65-65: Added Ollama to Provider enum.

The addition of Ollama to the Provider enum expands the functionality to support the new provider, enhancing the system's extensibility and adaptability.

docs/Changelog.md (1)

10-12: Documented new functionality in version 0.3.2.

The changelog correctly documents the new functionality introduced in version 0.3.2, including the searchCombinedEmbeddings function and the [[Providers/Ollama]] text/LLM provider. This ensures that users are informed about the latest features and improvements.

src/init.ts (2)

10-10: Import statement looks good.

The import statement for OllamaProvider is correct and necessary for the new functionality.


179-186: LGTM! Ensure proper configuration parameters for OllamaProvider.

The logic for setting up the Ollama provider appears correct. Verify that the configuration parameters (apiKey, modelName, baseUrl, requireAuth) are properly set.

docs/_plug/pub.plug.js (2)

1-1: Variable renaming looks good.

The variable vr has been renamed to Tr, likely for consistency or clarity.

Tools
Biome

[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


1-1: Export statement looks good.

The export statement now exports Tr instead of vr, likely for consistency or clarity.

Tools
Biome

[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

src/embeddings.ts (1)

Line range hint 1-1:
Verify the impact of removing debugSearchEmbeddings.

The removal of the debugSearchEmbeddings function eliminates a debugging tool. Ensure that this does not impact other parts of the codebase and that proper testing and troubleshooting mechanisms are in place.

Verification successful

The removal of debugSearchEmbeddings does not impact other parts of the codebase.

The debugSearchEmbeddings function was not found in any TypeScript or non-TypeScript files, indicating that it was not being used elsewhere. Therefore, its removal does not affect other parts of the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the impact of removing `debugSearchEmbeddings`.

# Test: Search for the function usage. Expect: No occurrences of `debugSearchEmbeddings`.
rg --type ts -A 5 $'debugSearchEmbeddings'

Length of output: 41


Script:

#!/bin/bash
# Description: Verify the impact of removing `debugSearchEmbeddings`.

# Test 1: Search for the function usage in all files. Expect: No occurrences of `debugSearchEmbeddings`.
rg --type ts -A 5 $'debugSearchEmbeddings'

# Test 2: Search for any references to `debugSearchEmbeddings` in non-TypeScript files. Expect: No occurrences of `debugSearchEmbeddings`.
rg -A 5 $'debugSearchEmbeddings'

Length of output: 73

@@ -1 +1 @@
var Y=Object.defineProperty;var p=(e,t)=>{for(var n in t)Y(e,n,{get:t[n],enumerable:!0})};var E=typeof window>"u"&&typeof globalThis.WebSocketPair>"u";typeof Deno>"u"&&(self.Deno={args:[],build:{arch:"x86_64"},env:{get(){}}});var C=new Map,M=0;function x(e){self.postMessage(e)}E&&(globalThis.syscall=async(e,...t)=>await new Promise((n,o)=>{M++,C.set(M,{resolve:n,reject:o}),x({type:"sys",id:M,name:e,args:t})}));function R(e,t){E&&(self.addEventListener("message",n=>{(async()=>{let o=n.data;switch(o.type){case"inv":{let a=e[o.name];if(!a)throw new Error(`Function not loaded: ${o.name}`);try{let s=await Promise.resolve(a(...o.args||[]));x({type:"invr",id:o.id,result:s})}catch(s){console.error("An exception was thrown as a result of invoking function",o.name,"error:",s.message),x({type:"invr",id:o.id,error:s.message})}}break;case"sysr":{let a=o.id,s=C.get(a);if(!s)throw Error("Invalid request id");C.delete(a),o.error?s.reject(new Error(o.error)):s.resolve(o.result)}break}})().catch(console.error)}),x({type:"manifest",manifest:t}))}function Q(e){let t=atob(e),n=t.length,o=new Uint8Array(n);for(let a=0;a<n;a++)o[a]=t.charCodeAt(a);return o}function B(e){typeof e=="string"&&(e=new TextEncoder().encode(e));let t="",n=e.byteLength;for(let o=0;o<n;o++)t+=String.fromCharCode(e[o]);return btoa(t)}async function V(e,t){if(typeof e!="string"){let n=new Uint8Array(await e.arrayBuffer()),o=n.length>0?B(n):void 0;t={method:e.method,headers:Object.fromEntries(e.headers.entries()),base64Body:o},e=e.url}return syscall("sandboxFetch.fetch",e,t)}globalThis.nativeFetch=globalThis.fetch;function X(){globalThis.fetch=async function(e,t){let n=t&&t.body?B(new Uint8Array(await new Response(t.body).arrayBuffer())):void 0,o=await V(e,t&&{method:t.method,headers:t.headers,base64Body:n});return new Response(o.base64Body?Q(o.base64Body):null,{status:o.status,headers:o.headers})}}E&&X();var m={};p(m,{confirm:()=>ve,copyToClipboard:()=>Be,dispatch:()=>Te,downloadFile:()=>pe,filterBox:()=>ge,flashNotification:()=>me,fold:()=>Ce,foldAll:()=>ke,getCurrentPage:()=>_,getCursor:()=>ee,getSelection:()=>te,getText:()=>J,getUiOption:()=>Fe,goHistory:()=>de,hidePanel:()=>he,insertAtCursor:()=>be,insertAtPos:()=>Pe,moveCursor:()=>we,navigate:()=>oe,openCommandPalette:()=>se,openPageNavigator:()=>ie,openSearchPanel:()=>Re,openUrl:()=>ue,prompt:()=>Ae,redo:()=>$e,reloadPage:()=>ae,reloadSettingsAndCommands:()=>le,reloadUI:()=>ce,replaceRange:()=>xe,save:()=>ne,setPage:()=>z,setSelection:()=>re,setText:()=>Z,setUiOption:()=>Se,showPanel:()=>ye,toggleFold:()=>Ue,undo:()=>Ne,unfold:()=>Ee,unfoldAll:()=>Ke,uploadFile:()=>fe,vimEx:()=>Me});typeof self>"u"&&(self={syscall:()=>{throw new Error("Not implemented here")}});var r=globalThis.syscall;function _(){return r("editor.getCurrentPage")}function z(e){return r("editor.setPage",e)}function J(){return r("editor.getText")}function Z(e){return r("editor.setText",e)}function ee(){return r("editor.getCursor")}function te(){return r("editor.getSelection")}function re(e,t){return r("editor.setSelection",e,t)}function ne(){return r("editor.save")}function oe(e,t=!1,n=!1){return r("editor.navigate",e,t,n)}function ie(e="page"){return r("editor.openPageNavigator",e)}function se(){return r("editor.openCommandPalette")}function ae(){return r("editor.reloadPage")}function ce(){return r("editor.reloadUI")}function le(){return r("editor.reloadSettingsAndCommands")}function ue(e,t=!1){return r("editor.openUrl",e,t)}function de(e){return r("editor.goHistory",e)}function pe(e,t){return r("editor.downloadFile",e,t)}function fe(e,t){return r("editor.uploadFile",e,t)}function me(e,t="info"){return r("editor.flashNotification",e,t)}function ge(e,t,n="",o=""){return r("editor.filterBox",e,t,n,o)}function ye(e,t,n,o=""){return r("editor.showPanel",e,t,n,o)}function he(e){return r("editor.hidePanel",e)}function Pe(e,t){return r("editor.insertAtPos",e,t)}function xe(e,t,n){return r("editor.replaceRange",e,t,n)}function we(e,t=!1){return r("editor.moveCursor",e,t)}function be(e){return r("editor.insertAtCursor",e)}function Te(e){return r("editor.dispatch",e)}function Ae(e,t=""){return r("editor.prompt",e,t)}function ve(e){return r("editor.confirm",e)}function Fe(e){return r("editor.getUiOption",e)}function Se(e,t){return r("editor.setUiOption",e,t)}function Me(e){return r("editor.vimEx",e)}function Ce(){return r("editor.fold")}function Ee(){return r("editor.unfold")}function Ue(){return r("editor.toggleFold")}function ke(){return r("editor.foldAll")}function Ke(){return r("editor.unfoldAll")}function Ne(){return r("editor.undo")}function $e(){return r("editor.redo")}function Re(){return r("editor.openSearchPanel")}function Be(e){return r("editor.copyToClipboard",e)}var g={};p(g,{parseMarkdown:()=>De});function De(e){return r("markdown.parseMarkdown",e)}var c={};p(c,{deleteAttachment:()=>Ve,deleteFile:()=>Ze,deletePage:()=>qe,getAttachmentMeta:()=>je,getFileMeta:()=>ze,getPageMeta:()=>We,listAttachments:()=>He,listFiles:()=>Xe,listPages:()=>Le,listPlugs:()=>Ie,readAttachment:()=>Ye,readFile:()=>_e,readPage:()=>Oe,writeAttachment:()=>Qe,writeFile:()=>Je,writePage:()=>Ge});function Le(e=!1){return r("space.listPages",e)}function We(e){return r("space.getPageMeta",e)}function Oe(e){return r("space.readPage",e)}function Ge(e,t){return r("space.writePage",e,t)}function qe(e){return r("space.deletePage",e)}function Ie(){return r("space.listPlugs")}function He(){return r("space.listAttachments")}function je(e){return r("space.getAttachmentMeta",e)}function Ye(e){return r("space.readAttachment",e)}function Qe(e,t){return r("space.writeAttachment",e,t)}function Ve(e){return r("space.deleteAttachment",e)}function Xe(){return r("space.listFiles")}function _e(e){return r("space.readFile",e)}function ze(e){return r("space.getFileMeta",e)}function Je(e,t){return r("space.writeFile",e,t)}function Ze(e){return r("space.deleteFile",e)}var y={};p(y,{applyAttributeExtractors:()=>it,getEnv:()=>at,getMode:()=>ct,getVersion:()=>lt,invokeCommand:()=>tt,invokeFunction:()=>et,invokeSpaceFunction:()=>ot,listCommands:()=>rt,listSyscalls:()=>nt,reloadPlugs:()=>st});function et(e,...t){return r("system.invokeFunction",e,...t)}function tt(e,t){return r("system.invokeCommand",e,t)}function rt(){return r("system.listCommands")}function nt(){return r("system.listSyscalls")}function ot(e,...t){return r("system.invokeSpaceFunction",e,...t)}function it(e,t,n){return r("system.applyAttributeExtractors",e,t,n)}function st(){return r("system.reloadPlugs")}function at(){return r("system.getEnv")}function ct(){return r("system.getMode")}function lt(){return r("system.getVersion")}var w={};p(w,{hasInitialSyncCompleted:()=>pt,isSyncing:()=>dt,scheduleFileSync:()=>ft,scheduleSpaceSync:()=>mt});function dt(){return r("sync.isSyncing")}function pt(){return r("sync.hasInitialSyncCompleted")}function ft(e){return r("sync.scheduleFileSync",e)}function mt(){return r("sync.scheduleSpaceSync")}var b={};p(b,{parseTemplate:()=>Pt,renderTemplate:()=>ht});function ht(e,t,n={}){return r("template.renderTemplate",e,t,n)}function Pt(e){return r("template.parseTemplate",e)}var P={};p(P,{parse:()=>At,stringify:()=>vt});function At(e){return r("yaml.parse",e)}function vt(e){return r("yaml.stringify",e)}function D(e,t){return T(e,n=>n.type===t)}function T(e,t){if(t(e))return[e];let n=[];if(e.children)for(let o of e.children)n=[...n,...T(o,t)];return n}function U(e,t){if(e.children){let n=e.children.slice();for(let o of n){let a=t(o);if(a!==void 0){let s=e.children.indexOf(o);a?e.children.splice(s,1,a):e.children.splice(s,1)}else U(o,t)}}}function k(e,t){return T(e,n=>n.type===t)[0]}function L(e,t){T(e,t)}function K(e){if(!e)return"";let t=[];if(e.text!==void 0)return e.text;for(let n of e.children)t.push(K(n));return t.join("")}async function N(e,t){let n=await c.readPage(e),o=await g.parseMarkdown(n),a;return L(o,s=>{if(s.type!=="FencedCode")return!1;let l=k(s,"CodeInfo");if(t&&!l||t&&!t.includes(l.children[0].text))return!1;let d=k(s,"CodeText");return d?(a=d.children[0].text,!0):!1}),a}async function A(e,t=["yaml"]){let n=await N(e,t);if(n!==void 0)try{return P.parse(n)}catch(o){throw console.error("YAML Page parser error",o),new Error(`YAML Error: ${o.message}`)}}async function W(e){try{let n=(await A("SECRETS",["yaml","secrets"]))[e];if(n===void 0)throw new Error(`No such secret: ${e}`);return n}catch(t){throw t.message==="Not found"?new Error(`No such secret: ${e}`):t}}var Mt="SETTINGS";async function O(e,t){try{let o=(await A(Mt,["yaml"])||{})[e];return o===void 0?t:o}catch(n){if(n.message==="Not found")return t;throw n}}var v=class{constructor(t){this.prefix=t}async listFiles(){return(await c.listFiles()).filter(t=>t.name.startsWith(this.prefix)).map(t=>({...t,name:t.name.slice(this.prefix.length)}))}readFile(t){return c.readFile(this.prefix+t)}getFileMeta(t){return c.getFileMeta(this.prefix+t)}writeFile(t,n){return c.writeFile(this.prefix+t,n)}deleteFile(t){return c.deleteFile(this.prefix+t)}};var F=class{constructor(t,n){this.url=t;this.token=n}authenticatedFetch(t,n){return nativeFetch(t,{...n,headers:{...n?.headers,"X-Sync-Mode":"true",Authorization:`Bearer ${this.token}`}})}async listFiles(){let t=await this.authenticatedFetch(`${this.url}/index.json`,{method:"GET"});if(t.status===404)throw new Error("Not found");return t.json()}async readFile(t){let n=await this.authenticatedFetch(`${this.url}/${t}`,{method:"GET"});return new Uint8Array(await n.arrayBuffer())}async getFileMeta(t){let n=await this.authenticatedFetch(`${this.url}/${t}`,{method:"GET",headers:{"X-Get-Meta":"true"}});return this.headersToFileMeta(t,n.headers)}async writeFile(t,n){let o=await this.authenticatedFetch(`${this.url}/${t}`,{method:"PUT",body:n});if(o.ok)return this.headersToFileMeta(t,o.headers);throw new Error(`Failed to write file: ${await o.text()}`)}async deleteFile(t){let n=await this.authenticatedFetch(`${this.url}/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`Failed to delete file: ${t}: ${await n.text()}`)}headersToFileMeta(t,n){return{name:t,contentType:n.get("Content-Type")||"application/octet-stream",perm:n.get("X-Perm"),created:+(n.get("X-Created")||"0"),lastModified:+(n.get("X-Last-Modified")||"0"),size:n.has("X-Content-Length")?+n.get("X-Content-Length"):+n.get("Content-Length")}}};var G={removeHashtags:!0,template:"!pub.silverbullet.md/template/page",destPrefix:"_public/"};async function q(e,t,n,o,a,s,l){console.log("Writing",t);let d=await c.readPage(t),f=await g.parseMarkdown(d),h=await Et(f,s,a,t),i=Ct(f);for(let u of i)try{let S=await c.readAttachment(u);console.log("Writing",u),await e.writeFile(u,S)}catch(S){console.error("Error reading attachment",u,S.message)}await e.writeFile(o,new TextEncoder().encode(h)),await e.writeFile(n,new TextEncoder().encode(await b.renderTemplate(l,{pageName:t,config:s,isIndex:t===s.indexPage,body:await y.invokeFunction("markdown.markdownToHtml",h,{smartHardBreak:!0,attachmentUrlPrefix:""})},{})))}async function $(){let e=G;try{let i=await O("publish",{});if(e={...G,...i},e.publishServer)try{let u=await W("publish");e.publishToken=u.token}catch(u){console.error("No publish secret found",u)}}catch(i){console.warn("No SETTINGS page found, using defaults",i.message)}let t=e.destPrefix;if(e.publishServer&&!e.publishToken)throw new Error("publishServer specified, but no matching 'token' under 'publish' found in SECRETS");let n=e.publishServer?new F(e.publishServer,e.publishToken):new v(t);console.log("Publishing to",n);let o=await y.invokeFunction("index.queryObjects","page",{});console.log("All pages",o);let a=new Map(o.map(i=>[i.name,i]));a.delete("SECRETS"),console.log("Cleaning up destination directory");let s=[];try{s=await n.listFiles()}catch(i){i.message==="Not found"&&console.log("Could not fetch file list from remote, assume it has not been initialized yet")}for(let i of s)await n.deleteFile(i.name);o=[...a.values()];let l=new Set;if(e.publishAll)l=new Set(o.map(i=>i.name));else for(let i of o){if(e.tags&&i.tags)for(let u of i.tags)e.tags.includes(u)&&l.add(i.name);if(typeof i.name=="string"){if(e.prefixes)for(let u of e.prefixes)i.name.startsWith(u)&&l.add(i.name);i.$share&&(Array.isArray(i.$share)||(i.$share=[i.$share]),i.$share.includes("pub")&&l.add(i.name))}}console.log("Publishing",[...l]);let d=await N(e.template),f=[...l];for(let i of f)await q(n,i,`${i}/index.html`,`${i}.md`,f,e,d);console.log("Done writing published paegs"),e.indexPage&&(console.log("Writing index page",e.indexPage),await q(n,e.indexPage,"index.html","index.md",f,e,d)),console.log("Publishing index.json");let h=[];for(let i of await n.listFiles())i.contentType!=="text/html"&&h.push({...i,perm:"ro"});await n.writeFile("index.json",new TextEncoder().encode(JSON.stringify(h,null,2)))}async function I(){await m.flashNotification("Publishing..."),await $(),await w.scheduleSpaceSync(),await m.flashNotification("Done!")}function Ct(e){let t=[];return D(e,"URL").forEach(n=>{let o=n.children[0].text;console.log("attachment url: ",o),o.indexOf("://")===-1&&t.push(o)}),t}async function Et(e,t,n,o){try{e=await y.invokeFunction("markdown.expandCodeWidgets",e,o)}catch(a){console.error("Error expanding code widgets in page",o,a.message)}return U(e,a=>{if(a.type==="WikiLink"){let s=a.children[1].children[0].text;if(s.includes("@")&&(s=s.split("@")[0]),s.startsWith("!"))return{text:`[${s.split("/").pop()}](https://${s.slice(1)})`};if(!n.includes(s)&&!s.startsWith("!"))return{text:`_${s}_`}}if(a.type==="CommentBlock"||a.type==="Comment"||a.type==="Hashtag"&&t.removeHashtags)return null}),K(e).trim()}var H={publishAll:$,publishAllCommand:I},j={name:"pub",functions:{publishAll:{path:"./publish.ts:publishAll"},publishAllCommand:{path:"./publish.ts:publishAllCommand",command:{name:"Pub: Publish All"}}},assets:{}},vr={manifest:j,functionMapping:H};R(H,j);export{vr as plug};
var Y=Object.defineProperty;var p=(e,t)=>{for(var n in t)Y(e,n,{get:t[n],enumerable:!0})};var E=typeof window>"u"&&typeof globalThis.WebSocketPair>"u";typeof Deno>"u"&&(self.Deno={args:[],build:{arch:"x86_64"},env:{get(){}}});var C=new Map,M=0;function x(e){self.postMessage(e)}E&&(globalThis.syscall=async(e,...t)=>await new Promise((n,o)=>{M++,C.set(M,{resolve:n,reject:o}),x({type:"sys",id:M,name:e,args:t})}));function R(e,t){E&&(self.addEventListener("message",n=>{(async()=>{let o=n.data;switch(o.type){case"inv":{let a=e[o.name];if(!a)throw new Error(`Function not loaded: ${o.name}`);try{let s=await Promise.resolve(a(...o.args||[]));x({type:"invr",id:o.id,result:s})}catch(s){console.error("An exception was thrown as a result of invoking function",o.name,"error:",s.message),x({type:"invr",id:o.id,error:s.message})}}break;case"sysr":{let a=o.id,s=C.get(a);if(!s)throw Error("Invalid request id");C.delete(a),o.error?s.reject(new Error(o.error)):s.resolve(o.result)}break}})().catch(console.error)}),x({type:"manifest",manifest:t}))}function Q(e){let t=atob(e),n=t.length,o=new Uint8Array(n);for(let a=0;a<n;a++)o[a]=t.charCodeAt(a);return o}function B(e){typeof e=="string"&&(e=new TextEncoder().encode(e));let t="",n=e.byteLength;for(let o=0;o<n;o++)t+=String.fromCharCode(e[o]);return btoa(t)}async function V(e,t){if(typeof e!="string"){let n=new Uint8Array(await e.arrayBuffer()),o=n.length>0?B(n):void 0;t={method:e.method,headers:Object.fromEntries(e.headers.entries()),base64Body:o},e=e.url}return syscall("sandboxFetch.fetch",e,t)}globalThis.nativeFetch=globalThis.fetch;function X(){globalThis.fetch=async function(e,t){let n=t&&t.body?B(new Uint8Array(await new Response(t.body).arrayBuffer())):void 0,o=await V(e,t&&{method:t.method,headers:t.headers,base64Body:n});return new Response(o.base64Body?Q(o.base64Body):null,{status:o.status,headers:o.headers})}}E&&X();var m={};p(m,{confirm:()=>ve,copyToClipboard:()=>$e,dispatch:()=>Te,downloadFile:()=>pe,filterBox:()=>ge,flashNotification:()=>me,fold:()=>Ce,foldAll:()=>ke,getCurrentPage:()=>_,getCursor:()=>ee,getSelection:()=>te,getText:()=>J,getUiOption:()=>Fe,goHistory:()=>de,hidePanel:()=>he,insertAtCursor:()=>be,insertAtPos:()=>Pe,moveCursor:()=>we,navigate:()=>oe,openCommandPalette:()=>se,openPageNavigator:()=>ie,openSearchPanel:()=>Ne,openUrl:()=>ue,prompt:()=>Ae,reloadPage:()=>ae,reloadSettingsAndCommands:()=>le,reloadUI:()=>ce,replaceRange:()=>xe,save:()=>ne,setPage:()=>z,setSelection:()=>re,setText:()=>Z,setUiOption:()=>Se,showPanel:()=>ye,toggleFold:()=>Ue,unfold:()=>Ee,unfoldAll:()=>Ke,uploadFile:()=>fe,vimEx:()=>Me});typeof self>"u"&&(self={syscall:()=>{throw new Error("Not implemented here")}});var r=globalThis.syscall;function _(){return r("editor.getCurrentPage")}function z(e){return r("editor.setPage",e)}function J(){return r("editor.getText")}function Z(e){return r("editor.setText",e)}function ee(){return r("editor.getCursor")}function te(){return r("editor.getSelection")}function re(e,t){return r("editor.setSelection",e,t)}function ne(){return r("editor.save")}function oe(e,t=!1,n=!1){return r("editor.navigate",e,t,n)}function ie(e="page"){return r("editor.openPageNavigator",e)}function se(){return r("editor.openCommandPalette")}function ae(){return r("editor.reloadPage")}function ce(){return r("editor.reloadUI")}function le(){return r("editor.reloadSettingsAndCommands")}function ue(e,t=!1){return r("editor.openUrl",e,t)}function de(e){return r("editor.goHistory",e)}function pe(e,t){return r("editor.downloadFile",e,t)}function fe(e,t){return r("editor.uploadFile",e,t)}function me(e,t="info"){return r("editor.flashNotification",e,t)}function ge(e,t,n="",o=""){return r("editor.filterBox",e,t,n,o)}function ye(e,t,n,o=""){return r("editor.showPanel",e,t,n,o)}function he(e){return r("editor.hidePanel",e)}function Pe(e,t){return r("editor.insertAtPos",e,t)}function xe(e,t,n){return r("editor.replaceRange",e,t,n)}function we(e,t=!1){return r("editor.moveCursor",e,t)}function be(e){return r("editor.insertAtCursor",e)}function Te(e){return r("editor.dispatch",e)}function Ae(e,t=""){return r("editor.prompt",e,t)}function ve(e){return r("editor.confirm",e)}function Fe(e){return r("editor.getUiOption",e)}function Se(e,t){return r("editor.setUiOption",e,t)}function Me(e){return r("editor.vimEx",e)}function Ce(){return r("editor.fold")}function Ee(){return r("editor.unfold")}function Ue(){return r("editor.toggleFold")}function ke(){return r("editor.foldAll")}function Ke(){return r("editor.unfoldAll")}function Ne(){return r("editor.openSearchPanel")}function $e(e){return r("editor.copyToClipboard",e)}var g={};p(g,{parseMarkdown:()=>Re});function Re(e){return r("markdown.parseMarkdown",e)}var c={};p(c,{deleteAttachment:()=>Ye,deleteFile:()=>ze,deletePage:()=>Oe,getAttachmentMeta:()=>Ie,getFileMeta:()=>Xe,getPageMeta:()=>De,listAttachments:()=>qe,listFiles:()=>Qe,listPages:()=>Be,listPlugs:()=>Ge,readAttachment:()=>He,readFile:()=>Ve,readPage:()=>Le,writeAttachment:()=>je,writeFile:()=>_e,writePage:()=>We});function Be(e=!1){return r("space.listPages",e)}function De(e){return r("space.getPageMeta",e)}function Le(e){return r("space.readPage",e)}function We(e,t){return r("space.writePage",e,t)}function Oe(e){return r("space.deletePage",e)}function Ge(){return r("space.listPlugs")}function qe(){return r("space.listAttachments")}function Ie(e){return r("space.getAttachmentMeta",e)}function He(e){return r("space.readAttachment",e)}function je(e,t){return r("space.writeAttachment",e,t)}function Ye(e){return r("space.deleteAttachment",e)}function Qe(){return r("space.listFiles")}function Ve(e){return r("space.readFile",e)}function Xe(e){return r("space.getFileMeta",e)}function _e(e,t){return r("space.writeFile",e,t)}function ze(e){return r("space.deleteFile",e)}var y={};p(y,{applyAttributeExtractors:()=>nt,getEnv:()=>it,getMode:()=>st,getVersion:()=>at,invokeCommand:()=>Ze,invokeFunction:()=>Je,invokeSpaceFunction:()=>rt,listCommands:()=>et,listSyscalls:()=>tt,reloadPlugs:()=>ot});function Je(e,...t){return r("system.invokeFunction",e,...t)}function Ze(e,t){return r("system.invokeCommand",e,t)}function et(){return r("system.listCommands")}function tt(){return r("system.listSyscalls")}function rt(e,...t){return r("system.invokeSpaceFunction",e,...t)}function nt(e,t,n){return r("system.applyAttributeExtractors",e,t,n)}function ot(){return r("system.reloadPlugs")}function it(){return r("system.getEnv")}function st(){return r("system.getMode")}function at(){return r("system.getVersion")}var w={};p(w,{hasInitialSyncCompleted:()=>ut,isSyncing:()=>lt,scheduleFileSync:()=>dt,scheduleSpaceSync:()=>pt});function lt(){return r("sync.isSyncing")}function ut(){return r("sync.hasInitialSyncCompleted")}function dt(e){return r("sync.scheduleFileSync",e)}function pt(){return r("sync.scheduleSpaceSync")}var b={};p(b,{parseTemplate:()=>yt,renderTemplate:()=>gt});function gt(e,t,n={}){return r("template.renderTemplate",e,t,n)}function yt(e){return r("template.parseTemplate",e)}var P={};p(P,{parse:()=>bt,stringify:()=>Tt});function bt(e){return r("yaml.parse",e)}function Tt(e){return r("yaml.stringify",e)}function D(e,t){return T(e,n=>n.type===t)}function T(e,t){if(t(e))return[e];let n=[];if(e.children)for(let o of e.children)n=[...n,...T(o,t)];return n}function U(e,t){if(e.children){let n=e.children.slice();for(let o of n){let a=t(o);if(a!==void 0){let s=e.children.indexOf(o);a?e.children.splice(s,1,a):e.children.splice(s,1)}else U(o,t)}}}function k(e,t){return T(e,n=>n.type===t)[0]}function L(e,t){T(e,t)}function K(e){if(!e)return"";let t=[];if(e.text!==void 0)return e.text;for(let n of e.children)t.push(K(n));return t.join("")}async function N(e,t){let n=await c.readPage(e),o=await g.parseMarkdown(n),a;return L(o,s=>{if(s.type!=="FencedCode")return!1;let l=k(s,"CodeInfo");if(t&&!l||t&&!t.includes(l.children[0].text))return!1;let d=k(s,"CodeText");return d?(a=d.children[0].text,!0):!1}),a}async function A(e,t=["yaml"]){let n=await N(e,t);if(n!==void 0)try{return P.parse(n)}catch(o){throw console.error("YAML Page parser error",o),new Error(`YAML Error: ${o.message}`)}}async function W(e){try{let n=(await A("SECRETS",["yaml","secrets"]))[e];if(n===void 0)throw new Error(`No such secret: ${e}`);return n}catch(t){throw t.message==="Not found"?new Error(`No such secret: ${e}`):t}}var Ft="SETTINGS";async function O(e,t){try{let o=(await A(Ft,["yaml"])||{})[e];return o===void 0?t:o}catch(n){if(n.message==="Not found")return t;throw n}}var v=class{constructor(t){this.prefix=t}async listFiles(){return(await c.listFiles()).filter(t=>t.name.startsWith(this.prefix)).map(t=>({...t,name:t.name.slice(this.prefix.length)}))}readFile(t){return c.readFile(this.prefix+t)}getFileMeta(t){return c.getFileMeta(this.prefix+t)}writeFile(t,n){return c.writeFile(this.prefix+t,n)}deleteFile(t){return c.deleteFile(this.prefix+t)}};var F=class{constructor(t,n){this.url=t;this.token=n}authenticatedFetch(t,n){return nativeFetch(t,{...n,headers:{...n?.headers,"X-Sync-Mode":"true",Authorization:`Bearer ${this.token}`}})}async listFiles(){let t=await this.authenticatedFetch(`${this.url}/index.json`,{method:"GET"});if(t.status===404)throw new Error("Not found");return t.json()}async readFile(t){let n=await this.authenticatedFetch(`${this.url}/${t}`,{method:"GET"});return new Uint8Array(await n.arrayBuffer())}async getFileMeta(t){let n=await this.authenticatedFetch(`${this.url}/${t}`,{method:"GET",headers:{"X-Get-Meta":"true"}});return this.headersToFileMeta(t,n.headers)}async writeFile(t,n){let o=await this.authenticatedFetch(`${this.url}/${t}`,{method:"PUT",body:n});if(o.ok)return this.headersToFileMeta(t,o.headers);throw new Error(`Failed to write file: ${await o.text()}`)}async deleteFile(t){let n=await this.authenticatedFetch(`${this.url}/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`Failed to delete file: ${t}: ${await n.text()}`)}headersToFileMeta(t,n){return{name:t,contentType:n.get("Content-Type")||"application/octet-stream",perm:n.get("X-Perm"),created:+(n.get("X-Created")||"0"),lastModified:+(n.get("X-Last-Modified")||"0"),size:n.has("X-Content-Length")?+n.get("X-Content-Length"):+n.get("Content-Length")}}};var G={removeHashtags:!0,template:"!pub.silverbullet.md/template/page",destPrefix:"_public/"};async function q(e,t,n,o,a,s,l){console.log("Writing",t);let d=await c.readPage(t),f=await g.parseMarkdown(d),h=await Mt(f,s,a,t),i=St(f);for(let u of i)try{let S=await c.readAttachment(u);console.log("Writing",u),await e.writeFile(u,S)}catch(S){console.error("Error reading attachment",u,S.message)}await e.writeFile(o,new TextEncoder().encode(h)),await e.writeFile(n,new TextEncoder().encode(await b.renderTemplate(l,{pageName:t,config:s,isIndex:t===s.indexPage,body:await y.invokeFunction("markdown.markdownToHtml",h,{smartHardBreak:!0,attachmentUrlPrefix:"/"})},{})))}async function $(){let e=G;try{let i=await O("publish",{});if(e={...G,...i},e.publishServer)try{let u=await W("publish");e.publishToken=u.token}catch(u){console.error("No publish secret found",u)}}catch(i){console.warn("No SETTINGS page found, using defaults",i.message)}let t=e.destPrefix;if(e.publishServer&&!e.publishToken)throw new Error("publishServer specified, but no matching 'token' under 'publish' found in SECRETS");let n=e.publishServer?new F(e.publishServer,e.publishToken):new v(t);console.log("Publishing to",n);let o=await y.invokeFunction("index.queryObjects","page",{});console.log("All pages",o);let a=new Map(o.map(i=>[i.name,i]));a.delete("SECRETS"),console.log("Cleaning up destination directory");let s=[];try{s=await n.listFiles()}catch(i){i.message==="Not found"&&console.log("Could not fetch file list from remote, assume it has not been initialized yet")}for(let i of s)await n.deleteFile(i.name);o=[...a.values()];let l=new Set;if(e.publishAll)l=new Set(o.map(i=>i.name));else for(let i of o){if(e.tags&&i.tags)for(let u of i.tags)e.tags.includes(u)&&l.add(i.name);if(typeof i.name=="string"){if(e.prefixes)for(let u of e.prefixes)i.name.startsWith(u)&&l.add(i.name);i.$share&&(Array.isArray(i.$share)||(i.$share=[i.$share]),i.$share.includes("pub")&&l.add(i.name))}}console.log("Publishing",[...l]);let d=await N(e.template),f=[...l];for(let i of f)await q(n,i,`${i}/index.html`,`${i}.md`,f,e,d);console.log("Done writing published paegs"),e.indexPage&&(console.log("Writing index page",e.indexPage),await q(n,e.indexPage,"index.html","index.md",f,e,d)),console.log("Publishing index.json");let h=[];for(let i of await n.listFiles())i.contentType!=="text/html"&&h.push({...i,perm:"ro"});await n.writeFile("index.json",new TextEncoder().encode(JSON.stringify(h,null,2)))}async function I(){await m.flashNotification("Publishing..."),await $(),await w.scheduleSpaceSync(),await m.flashNotification("Done!")}function St(e){let t=[];return D(e,"URL").forEach(n=>{let o=n.children[0].text;o.indexOf("://")===-1&&t.push(o)}),t}async function Mt(e,t,n,o){try{e=await y.invokeFunction("markdown.expandCodeWidgets",e,o)}catch(a){console.error("Error expanding code widgets in page",o,a.message)}return U(e,a=>{if(a.type==="WikiLink"){let s=a.children[1].children[0].text;if(s.includes("@")&&(s=s.split("@")[0]),s.startsWith("!"))return{text:`[${s.split("/").pop()}](https://${s.slice(1)})`};if(!n.includes(s)&&!s.startsWith("!"))return{text:`_${s}_`}}if(a.type==="CommentBlock"||a.type==="Comment"||a.type==="Hashtag"&&t.removeHashtags)return null}),K(e).trim()}var H={publishAll:$,publishAllCommand:I},j={name:"pub",functions:{publishAll:{path:"./publish.ts:publishAll"},publishAllCommand:{path:"./publish.ts:publishAllCommand",command:{name:"Pub: Publish All"}}},assets:{}},Tr={manifest:j,functionMapping:H};R(H,j);export{Tr as plug};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid assignments in expressions.

The use of assignments in expressions is confusing and can lead to errors. Consider refactoring to avoid this pattern.

- var Y=Object.defineProperty;var p=(e,t)=>{for(var n in t)Y(e,n,{get:t[n],enumerable:!0})};
+ var Y=Object.defineProperty;
+ var p=(e,t)=>{
+   for(var n in t) Y(e,n,{get:t[n],enumerable:!0});
+ };
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var Y=Object.defineProperty;var p=(e,t)=>{for(var n in t)Y(e,n,{get:t[n],enumerable:!0})};var E=typeof window>"u"&&typeof globalThis.WebSocketPair>"u";typeof Deno>"u"&&(self.Deno={args:[],build:{arch:"x86_64"},env:{get(){}}});var C=new Map,M=0;function x(e){self.postMessage(e)}E&&(globalThis.syscall=async(e,...t)=>await new Promise((n,o)=>{M++,C.set(M,{resolve:n,reject:o}),x({type:"sys",id:M,name:e,args:t})}));function R(e,t){E&&(self.addEventListener("message",n=>{(async()=>{let o=n.data;switch(o.type){case"inv":{let a=e[o.name];if(!a)throw new Error(`Function not loaded: ${o.name}`);try{let s=await Promise.resolve(a(...o.args||[]));x({type:"invr",id:o.id,result:s})}catch(s){console.error("An exception was thrown as a result of invoking function",o.name,"error:",s.message),x({type:"invr",id:o.id,error:s.message})}}break;case"sysr":{let a=o.id,s=C.get(a);if(!s)throw Error("Invalid request id");C.delete(a),o.error?s.reject(new Error(o.error)):s.resolve(o.result)}break}})().catch(console.error)}),x({type:"manifest",manifest:t}))}function Q(e){let t=atob(e),n=t.length,o=new Uint8Array(n);for(let a=0;a<n;a++)o[a]=t.charCodeAt(a);return o}function B(e){typeof e=="string"&&(e=new TextEncoder().encode(e));let t="",n=e.byteLength;for(let o=0;o<n;o++)t+=String.fromCharCode(e[o]);return btoa(t)}async function V(e,t){if(typeof e!="string"){let n=new Uint8Array(await e.arrayBuffer()),o=n.length>0?B(n):void 0;t={method:e.method,headers:Object.fromEntries(e.headers.entries()),base64Body:o},e=e.url}return syscall("sandboxFetch.fetch",e,t)}globalThis.nativeFetch=globalThis.fetch;function X(){globalThis.fetch=async function(e,t){let n=t&&t.body?B(new Uint8Array(await new Response(t.body).arrayBuffer())):void 0,o=await V(e,t&&{method:t.method,headers:t.headers,base64Body:n});return new Response(o.base64Body?Q(o.base64Body):null,{status:o.status,headers:o.headers})}}E&&X();var m={};p(m,{confirm:()=>ve,copyToClipboard:()=>$e,dispatch:()=>Te,downloadFile:()=>pe,filterBox:()=>ge,flashNotification:()=>me,fold:()=>Ce,foldAll:()=>ke,getCurrentPage:()=>_,getCursor:()=>ee,getSelection:()=>te,getText:()=>J,getUiOption:()=>Fe,goHistory:()=>de,hidePanel:()=>he,insertAtCursor:()=>be,insertAtPos:()=>Pe,moveCursor:()=>we,navigate:()=>oe,openCommandPalette:()=>se,openPageNavigator:()=>ie,openSearchPanel:()=>Ne,openUrl:()=>ue,prompt:()=>Ae,reloadPage:()=>ae,reloadSettingsAndCommands:()=>le,reloadUI:()=>ce,replaceRange:()=>xe,save:()=>ne,setPage:()=>z,setSelection:()=>re,setText:()=>Z,setUiOption:()=>Se,showPanel:()=>ye,toggleFold:()=>Ue,unfold:()=>Ee,unfoldAll:()=>Ke,uploadFile:()=>fe,vimEx:()=>Me});typeof self>"u"&&(self={syscall:()=>{throw new Error("Not implemented here")}});var r=globalThis.syscall;function _(){return r("editor.getCurrentPage")}function z(e){return r("editor.setPage",e)}function J(){return r("editor.getText")}function Z(e){return r("editor.setText",e)}function ee(){return r("editor.getCursor")}function te(){return r("editor.getSelection")}function re(e,t){return r("editor.setSelection",e,t)}function ne(){return r("editor.save")}function oe(e,t=!1,n=!1){return r("editor.navigate",e,t,n)}function ie(e="page"){return r("editor.openPageNavigator",e)}function se(){return r("editor.openCommandPalette")}function ae(){return r("editor.reloadPage")}function ce(){return r("editor.reloadUI")}function le(){return r("editor.reloadSettingsAndCommands")}function ue(e,t=!1){return r("editor.openUrl",e,t)}function de(e){return r("editor.goHistory",e)}function pe(e,t){return r("editor.downloadFile",e,t)}function fe(e,t){return r("editor.uploadFile",e,t)}function me(e,t="info"){return r("editor.flashNotification",e,t)}function ge(e,t,n="",o=""){return r("editor.filterBox",e,t,n,o)}function ye(e,t,n,o=""){return r("editor.showPanel",e,t,n,o)}function he(e){return r("editor.hidePanel",e)}function Pe(e,t){return r("editor.insertAtPos",e,t)}function xe(e,t,n){return r("editor.replaceRange",e,t,n)}function we(e,t=!1){return r("editor.moveCursor",e,t)}function be(e){return r("editor.insertAtCursor",e)}function Te(e){return r("editor.dispatch",e)}function Ae(e,t=""){return r("editor.prompt",e,t)}function ve(e){return r("editor.confirm",e)}function Fe(e){return r("editor.getUiOption",e)}function Se(e,t){return r("editor.setUiOption",e,t)}function Me(e){return r("editor.vimEx",e)}function Ce(){return r("editor.fold")}function Ee(){return r("editor.unfold")}function Ue(){return r("editor.toggleFold")}function ke(){return r("editor.foldAll")}function Ke(){return r("editor.unfoldAll")}function Ne(){return r("editor.openSearchPanel")}function $e(e){return r("editor.copyToClipboard",e)}var g={};p(g,{parseMarkdown:()=>Re});function Re(e){return r("markdown.parseMarkdown",e)}var c={};p(c,{deleteAttachment:()=>Ye,deleteFile:()=>ze,deletePage:()=>Oe,getAttachmentMeta:()=>Ie,getFileMeta:()=>Xe,getPageMeta:()=>De,listAttachments:()=>qe,listFiles:()=>Qe,listPages:()=>Be,listPlugs:()=>Ge,readAttachment:()=>He,readFile:()=>Ve,readPage:()=>Le,writeAttachment:()=>je,writeFile:()=>_e,writePage:()=>We});function Be(e=!1){return r("space.listPages",e)}function De(e){return r("space.getPageMeta",e)}function Le(e){return r("space.readPage",e)}function We(e,t){return r("space.writePage",e,t)}function Oe(e){return r("space.deletePage",e)}function Ge(){return r("space.listPlugs")}function qe(){return r("space.listAttachments")}function Ie(e){return r("space.getAttachmentMeta",e)}function He(e){return r("space.readAttachment",e)}function je(e,t){return r("space.writeAttachment",e,t)}function Ye(e){return r("space.deleteAttachment",e)}function Qe(){return r("space.listFiles")}function Ve(e){return r("space.readFile",e)}function Xe(e){return r("space.getFileMeta",e)}function _e(e,t){return r("space.writeFile",e,t)}function ze(e){return r("space.deleteFile",e)}var y={};p(y,{applyAttributeExtractors:()=>nt,getEnv:()=>it,getMode:()=>st,getVersion:()=>at,invokeCommand:()=>Ze,invokeFunction:()=>Je,invokeSpaceFunction:()=>rt,listCommands:()=>et,listSyscalls:()=>tt,reloadPlugs:()=>ot});function Je(e,...t){return r("system.invokeFunction",e,...t)}function Ze(e,t){return r("system.invokeCommand",e,t)}function et(){return r("system.listCommands")}function tt(){return r("system.listSyscalls")}function rt(e,...t){return r("system.invokeSpaceFunction",e,...t)}function nt(e,t,n){return r("system.applyAttributeExtractors",e,t,n)}function ot(){return r("system.reloadPlugs")}function it(){return r("system.getEnv")}function st(){return r("system.getMode")}function at(){return r("system.getVersion")}var w={};p(w,{hasInitialSyncCompleted:()=>ut,isSyncing:()=>lt,scheduleFileSync:()=>dt,scheduleSpaceSync:()=>pt});function lt(){return r("sync.isSyncing")}function ut(){return r("sync.hasInitialSyncCompleted")}function dt(e){return r("sync.scheduleFileSync",e)}function pt(){return r("sync.scheduleSpaceSync")}var b={};p(b,{parseTemplate:()=>yt,renderTemplate:()=>gt});function gt(e,t,n={}){return r("template.renderTemplate",e,t,n)}function yt(e){return r("template.parseTemplate",e)}var P={};p(P,{parse:()=>bt,stringify:()=>Tt});function bt(e){return r("yaml.parse",e)}function Tt(e){return r("yaml.stringify",e)}function D(e,t){return T(e,n=>n.type===t)}function T(e,t){if(t(e))return[e];let n=[];if(e.children)for(let o of e.children)n=[...n,...T(o,t)];return n}function U(e,t){if(e.children){let n=e.children.slice();for(let o of n){let a=t(o);if(a!==void 0){let s=e.children.indexOf(o);a?e.children.splice(s,1,a):e.children.splice(s,1)}else U(o,t)}}}function k(e,t){return T(e,n=>n.type===t)[0]}function L(e,t){T(e,t)}function K(e){if(!e)return"";let t=[];if(e.text!==void 0)return e.text;for(let n of e.children)t.push(K(n));return t.join("")}async function N(e,t){let n=await c.readPage(e),o=await g.parseMarkdown(n),a;return L(o,s=>{if(s.type!=="FencedCode")return!1;let l=k(s,"CodeInfo");if(t&&!l||t&&!t.includes(l.children[0].text))return!1;let d=k(s,"CodeText");return d?(a=d.children[0].text,!0):!1}),a}async function A(e,t=["yaml"]){let n=await N(e,t);if(n!==void 0)try{return P.parse(n)}catch(o){throw console.error("YAML Page parser error",o),new Error(`YAML Error: ${o.message}`)}}async function W(e){try{let n=(await A("SECRETS",["yaml","secrets"]))[e];if(n===void 0)throw new Error(`No such secret: ${e}`);return n}catch(t){throw t.message==="Not found"?new Error(`No such secret: ${e}`):t}}var Ft="SETTINGS";async function O(e,t){try{let o=(await A(Ft,["yaml"])||{})[e];return o===void 0?t:o}catch(n){if(n.message==="Not found")return t;throw n}}var v=class{constructor(t){this.prefix=t}async listFiles(){return(await c.listFiles()).filter(t=>t.name.startsWith(this.prefix)).map(t=>({...t,name:t.name.slice(this.prefix.length)}))}readFile(t){return c.readFile(this.prefix+t)}getFileMeta(t){return c.getFileMeta(this.prefix+t)}writeFile(t,n){return c.writeFile(this.prefix+t,n)}deleteFile(t){return c.deleteFile(this.prefix+t)}};var F=class{constructor(t,n){this.url=t;this.token=n}authenticatedFetch(t,n){return nativeFetch(t,{...n,headers:{...n?.headers,"X-Sync-Mode":"true",Authorization:`Bearer ${this.token}`}})}async listFiles(){let t=await this.authenticatedFetch(`${this.url}/index.json`,{method:"GET"});if(t.status===404)throw new Error("Not found");return t.json()}async readFile(t){let n=await this.authenticatedFetch(`${this.url}/${t}`,{method:"GET"});return new Uint8Array(await n.arrayBuffer())}async getFileMeta(t){let n=await this.authenticatedFetch(`${this.url}/${t}`,{method:"GET",headers:{"X-Get-Meta":"true"}});return this.headersToFileMeta(t,n.headers)}async writeFile(t,n){let o=await this.authenticatedFetch(`${this.url}/${t}`,{method:"PUT",body:n});if(o.ok)return this.headersToFileMeta(t,o.headers);throw new Error(`Failed to write file: ${await o.text()}`)}async deleteFile(t){let n=await this.authenticatedFetch(`${this.url}/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`Failed to delete file: ${t}: ${await n.text()}`)}headersToFileMeta(t,n){return{name:t,contentType:n.get("Content-Type")||"application/octet-stream",perm:n.get("X-Perm"),created:+(n.get("X-Created")||"0"),lastModified:+(n.get("X-Last-Modified")||"0"),size:n.has("X-Content-Length")?+n.get("X-Content-Length"):+n.get("Content-Length")}}};var G={removeHashtags:!0,template:"!pub.silverbullet.md/template/page",destPrefix:"_public/"};async function q(e,t,n,o,a,s,l){console.log("Writing",t);let d=await c.readPage(t),f=await g.parseMarkdown(d),h=await Mt(f,s,a,t),i=St(f);for(let u of i)try{let S=await c.readAttachment(u);console.log("Writing",u),await e.writeFile(u,S)}catch(S){console.error("Error reading attachment",u,S.message)}await e.writeFile(o,new TextEncoder().encode(h)),await e.writeFile(n,new TextEncoder().encode(await b.renderTemplate(l,{pageName:t,config:s,isIndex:t===s.indexPage,body:await y.invokeFunction("markdown.markdownToHtml",h,{smartHardBreak:!0,attachmentUrlPrefix:"/"})},{})))}async function $(){let e=G;try{let i=await O("publish",{});if(e={...G,...i},e.publishServer)try{let u=await W("publish");e.publishToken=u.token}catch(u){console.error("No publish secret found",u)}}catch(i){console.warn("No SETTINGS page found, using defaults",i.message)}let t=e.destPrefix;if(e.publishServer&&!e.publishToken)throw new Error("publishServer specified, but no matching 'token' under 'publish' found in SECRETS");let n=e.publishServer?new F(e.publishServer,e.publishToken):new v(t);console.log("Publishing to",n);let o=await y.invokeFunction("index.queryObjects","page",{});console.log("All pages",o);let a=new Map(o.map(i=>[i.name,i]));a.delete("SECRETS"),console.log("Cleaning up destination directory");let s=[];try{s=await n.listFiles()}catch(i){i.message==="Not found"&&console.log("Could not fetch file list from remote, assume it has not been initialized yet")}for(let i of s)await n.deleteFile(i.name);o=[...a.values()];let l=new Set;if(e.publishAll)l=new Set(o.map(i=>i.name));else for(let i of o){if(e.tags&&i.tags)for(let u of i.tags)e.tags.includes(u)&&l.add(i.name);if(typeof i.name=="string"){if(e.prefixes)for(let u of e.prefixes)i.name.startsWith(u)&&l.add(i.name);i.$share&&(Array.isArray(i.$share)||(i.$share=[i.$share]),i.$share.includes("pub")&&l.add(i.name))}}console.log("Publishing",[...l]);let d=await N(e.template),f=[...l];for(let i of f)await q(n,i,`${i}/index.html`,`${i}.md`,f,e,d);console.log("Done writing published paegs"),e.indexPage&&(console.log("Writing index page",e.indexPage),await q(n,e.indexPage,"index.html","index.md",f,e,d)),console.log("Publishing index.json");let h=[];for(let i of await n.listFiles())i.contentType!=="text/html"&&h.push({...i,perm:"ro"});await n.writeFile("index.json",new TextEncoder().encode(JSON.stringify(h,null,2)))}async function I(){await m.flashNotification("Publishing..."),await $(),await w.scheduleSpaceSync(),await m.flashNotification("Done!")}function St(e){let t=[];return D(e,"URL").forEach(n=>{let o=n.children[0].text;o.indexOf("://")===-1&&t.push(o)}),t}async function Mt(e,t,n,o){try{e=await y.invokeFunction("markdown.expandCodeWidgets",e,o)}catch(a){console.error("Error expanding code widgets in page",o,a.message)}return U(e,a=>{if(a.type==="WikiLink"){let s=a.children[1].children[0].text;if(s.includes("@")&&(s=s.split("@")[0]),s.startsWith("!"))return{text:`[${s.split("/").pop()}](https://${s.slice(1)})`};if(!n.includes(s)&&!s.startsWith("!"))return{text:`_${s}_`}}if(a.type==="CommentBlock"||a.type==="Comment"||a.type==="Hashtag"&&t.removeHashtags)return null}),K(e).trim()}var H={publishAll:$,publishAllCommand:I},j={name:"pub",functions:{publishAll:{path:"./publish.ts:publishAll"},publishAllCommand:{path:"./publish.ts:publishAllCommand",command:{name:"Pub: Publish All"}}},assets:{}},Tr={manifest:j,functionMapping:H};R(H,j);export{Tr as plug};
var Y=Object.defineProperty;
var p=(e,t)=>{
for(var n in t) Y(e,n,{get:t[n],enumerable:!0});
};
Tools
Biome

[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1-1: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 1-1: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Is it expected we need to pass openai as provider of ollama models?
1 participant