-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpub.plug.js
1 lines (1 loc) · 13.4 KB
/
pub.plug.js
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:()=>$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};