scrapbox2anki-bookmarklet
code:single-page.js
(async()=>{
var pe=Object.defineProperty;var mo=Reflect.get,uo=Reflect.set;var ct=e=>pe(e,"__esModule",{value:!0});var me=(e,o)=>()=>(e&&(o=e(e=0)),o);var lt=(e,o)=>{ct(e);for(var t in o)pe(e,t,{get:ot,enumerable:!0})};var le,nt=me(()=>{le=(e,o)=>new Promise((t,r)=>{let{id:n,module:s=!1}=o;document.getElementById(n)?.remove();let i=document.createElement("script");i.addEventListener("load",()=>t()),i.addEventListener("error",c=>r(c)),i.src=e,i.id=n,s&&(i.type="module"),document.head.append(i)})});var it={};lt(it,{sql:()=>po});var st,co,lo,po,at=me(async()=>{nt();st="1.8.0",co="3.10.1",lo="6339056660dae0001f816bc1";await Promise.all([le(https://cdnjs.cloudflare.com/ajax/libs/sql.js/${st}/sql-wasm.min.js,{id:"sqljs-cdn"}),le(https://cdnjs.cloudflare.com/ajax/libs/jszip/${co}/jszip.min.js,{id:"jszip-cdn"})]);po=await initSqlJs({locateFile:e=>e==="sql-wasm.wasm"?https://scrapbox.io/files/${lo}.wasm:https://cdnjs.cloudflare.com/ajax/libs/sql.js/${st}/${e}})});var y=e=>{let{fetch:o=globalThis.fetch,hostName:t="scrapbox.io",...r}=e;return{fetch:o,hostName:t,...r}};var dt=e=>typeof e=="object"&&e!==null,pt=e=>dt(e)?(e.name===void 0||typeof e.name=="string")&&typeof e.message=="string":!1,ue=e=>{try{let o=typeof e=="string"?JSON.parse(e):e;return pt(o)?o:!1}catch(o){if(o instanceof SyntaxError)return!1;throw o}};var q=class extends Error{constructor(o){super(${o.status} ${o.statusText} when fetching ${o.url});this.response=o;this.name="UnexpectedResponseError";Error.captureStackTrace&&Error.captureStackTrace(this,q)}},T=async e=>{let o=e.clone(),t=await o.text(),r=ue(t);if(!r)throw new q(o);return{ok:!1,value:r}};var E=e=>connect.sid=${e};var z=e=>e.replaceAll(" ","_").toLowerCase();var P=e=>...e.map((o,t)=>o===" "?"_":!ut.includes(o)||t===e.length-1&&ft.includes(o)?encodeURIComponent(o):o).join(""),ut='@$&+=:;",',ft=':;",';var fe=(e,o,t)=>{let{sid:r,hostName:n,followRename:s,projects:a}=y(t??{}),i=new URLSearchParams;i.append("followRename",${s??!0});for(let m of a??[])i.append("projects",m);let c=https://${n}/api/pages/${e}/${P(o)}?${i.toString()};return new Request(c,r?{headers:{Cookie:E(r)}}:void 0)},ge=async e=>{if(!e.ok)return e.status===414?{ok:!1,value:{name:"TooLongURIError",message:"project ids may be too much."}}:T(e);let o=await e.json();return{ok:!0,value:o}},R=async(e,o,t)=>{let{fetch:r}=y(t??{}),n=fe(e,o,t),s=await r(n);return await ge(s)};R.toRequest=fe;R.fromResponse=ge;var he=(e,o)=>{let{sid:t,hostName:r,sort:n,limit:s,skip:a}=y(o??{}),i=new URLSearchParams;n!==void 0&&i.append("sort",n),s!==void 0&&i.append("limit",${s}),a!==void 0&&i.append("skip",${a});let c=https://${r}/api/pages/${e}?${i.toString()};return new Request(c,t?{headers:{Cookie:E(t)}}:void 0)},xe=async e=>{if(!e.ok)return T(e);let o=await e.json();return{ok:!0,value:o}},ye=async(e,o)=>{let{fetch:t}=y(o??{}),r=await t(he(e,o));return await xe(r)};ye.toRequest=he;ye.fromResponse=xe;var ke=(e,o,t,r)=>{let{sid:n,hostName:s}=y(r??{}),a=https://${s}/api/table/${e}/${P(o)}/${encodeURIComponent(t)}.csv;return new Request(a,n?{headers:{Cookie:E(n)}}:void 0)},be=async e=>e.ok?{ok:!0,value:await e.text()}:e.status===404?{ok:!1,value:{name:"NotFoundError",message:"Table not found."}}:T(e),we=async(e,o,t,r)=>{let{fetch:n}=y(r??{}),s=ke(e,o,t,r),a=await n(s);return await be(a)};we.toRequest=ke;we.fromResponse=be;var Ee=(e,o)=>{let{sid:t,hostName:r}=y(o??{});return new Request(https://${r}/api/projects/${e},t?{headers:{Cookie:E(t)}}:void 0)},Te=async e=>{if(!e.ok)return T(e);let o=await e.json();return{ok:!0,value:o}},ee=async(e,o)=>{let{fetch:t}=y(o??{}),r=Ee(e,o),n=await t(r);return Te(n)};ee.toRequest=Ee;ee.fromResponse=Te;var ve=(e,o)=>{let{sid:t,hostName:r}=y(o??{}),n=new URLSearchParams;for(let s of e)n.append("ids",s);return new Request(https://${r}/api/projects?${n.toString()},t?{headers:{Cookie:E(t)}}:void 0)},Ie=async e=>{if(!e.ok)return T(e);let o=await e.json();return{ok:!0,value:o}},Le=async(e,o)=>{let{fetch:t}=y(o??{}),r=await t(ve(e,o));return Ie(r)};Le.toRequest=ve;Le.fromResponse=Ie;var es=new Map;var Ne=(e,o,t,r)=>{let{sid:n,hostName:s}=y(r??{}),a=https://${s}/api/code/${e}/${P(o)}/${P(t)};return new Request(a,n?{headers:{Cookie:E(n)}}:void 0)},Ce=async e=>e.ok?{ok:!0,value:await e.text()}:e.status===404&&e.headers.get("Content-Type")?.includes?.("text/plain")?{ok:!1,value:{name:"NotFoundError",message:"Code block is not found"}}:T(e),Pe=async(e,o,t,r)=>{let{fetch:n}=y(r??{}),s=Ne(e,o,t,r),a=await n(s);return await Ce(a)};Pe.toRequest=Ne;Pe.fromResponse=Ce;var Se=new TextEncoder().encode("0123456789abcdef");function Re(e){let o=new Uint8Array(e.length*2);for(let t=0;t<o.length;t++){let r=et;ot*2=Ser>>4,ot*2+1=Ser&15}return o}var Me="md5: data is invalid type",D=64,re=class{#e;#t;#r;#o;#n;#i;#s;#a;constructor(){this.#e=1732584193,this.#t=4023233417,this.#r=2562383102,this.#o=271733878,this.#n=new Uint8Array(D),this.#i=0,this.#s=0,this.#a=0}#l(o){let t=this.#s;t+=o,t>4294967295&&(this.#a+=1),this.#s=t>>>0}#c(o){let t=this.#e,r=this.#t,n=this.#r,s=this.#o,a=O=>oO|oO+1<<8|oO+2<<16|oO+3<<24,i=(O,de)=>O<<de|O>>>32-de,c=a(0),m=a(4),d=a(8),u=a(12),k=a(16),x=a(20),l=a(24),f=a(28),p=a(32),h=a(36),b=a(40),g=a(44),I=a(48),F=a(52),J=a(56),Q=a(60);t=r+i(((n^s)&r^s)+t+c+3614090360,7),s=t+i(((r^n)&t^n)+s+m+3905402710,12),n=s+i(((t^r)&s^r)+n+d+606105819,17),r=n+i(((s^t)&n^t)+r+u+3250441966,22),t=r+i(((n^s)&r^s)+t+k+4118548399,7),s=t+i(((r^n)&t^n)+s+x+1200080426,12),n=s+i(((t^r)&s^r)+n+l+2821735955,17),r=n+i(((s^t)&n^t)+r+f+4249261313,22),t=r+i(((n^s)&r^s)+t+p+1770035416,7),s=t+i(((r^n)&t^n)+s+h+2336552879,12),n=s+i(((t^r)&s^r)+n+b+4294925233,17),r=n+i(((s^t)&n^t)+r+g+2304563134,22),t=r+i(((n^s)&r^s)+t+I+1804603682,7),s=t+i(((r^n)&t^n)+s+F+4254626195,12),n=s+i(((t^r)&s^r)+n+J+2792965006,17),r=n+i(((s^t)&n^t)+r+Q+1236535329,22),t=r+i(((r^n)&s^n)+t+m+4129170786,5),s=t+i(((t^r)&n^r)+s+l+3225465664,9),n=s+i(((s^t)&r^t)+n+g+643717713,14),r=n+i(((n^s)&t^s)+r+c+3921069994,20),t=r+i(((r^n)&s^n)+t+x+3593408605,5),s=t+i(((t^r)&n^r)+s+b+38016083,9),n=s+i(((s^t)&r^t)+n+Q+3634488961,14),r=n+i(((n^s)&t^s)+r+k+3889429448,20),t=r+i(((r^n)&s^n)+t+h+568446438,5),s=t+i(((t^r)&n^r)+s+J+3275163606,9),n=s+i(((s^t)&r^t)+n+u+4107603335,14),r=n+i(((n^s)&t^s)+r+p+1163531501,20),t=r+i(((r^n)&s^n)+t+F+2850285829,5),s=t+i(((t^r)&n^r)+s+d+4243563512,9),n=s+i(((s^t)&r^t)+n+f+1735328473,14),r=n+i(((n^s)&t^s)+r+I+2368359562,20),t=r+i((r^n^s)+t+x+4294588738,4),s=t+i((t^r^n)+s+p+2272392833,11),n=s+i((s^t^r)+n+g+1839030562,16),r=n+i((n^s^t)+r+J+4259657740,23),t=r+i((r^n^s)+t+m+2763975236,4),s=t+i((t^r^n)+s+k+1272893353,11),n=s+i((s^t^r)+n+f+4139469664,16),r=n+i((n^s^t)+r+b+3200236656,23),t=r+i((r^n^s)+t+F+681279174,4),s=t+i((t^r^n)+s+c+3936430074,11),n=s+i((s^t^r)+n+u+3572445317,16),r=n+i((n^s^t)+r+l+76029189,23),t=r+i((r^n^s)+t+h+3654602809,4),s=t+i((t^r^n)+s+I+3873151461,11),n=s+i((s^t^r)+n+Q+530742520,16),r=n+i((n^s^t)+r+d+3299628645,23),t=r+i((n^(r|~s))+t+c+4096336452,6),s=t+i((r^(t|~n))+s+f+1126891415,10),n=s+i((t^(s|~r))+n+J+2878612391,15),r=n+i((s^(n|~t))+r+x+4237533241,21),t=r+i((n^(r|~s))+t+I+1700485571,6),s=t+i((r^(t|~n))+s+u+2399980690,10),n=s+i((t^(s|~r))+n+b+4293915773,15),r=n+i((s^(n|~t))+r+m+2240044497,21),t=r+i((n^(r|~s))+t+p+1873313359,6),s=t+i((r^(t|~n))+s+Q+4264355552,10),n=s+i((t^(s|~r))+n+l+2734768916,15),r=n+i((s^(n|~t))+r+F+1309151649,21),t=r+i((n^(r|~s))+t+k+4149444226,6),s=t+i((r^(t|~n))+s+g+3174756917,10),n=s+i((t^(s|~r))+n+d+718787259,15),r=n+i((s^(n|~t))+r+h+3951481745,21),this.#e=this.#e+t>>>0,this.#t=this.#t+r>>>0,this.#r=this.#r+n>>>0,this.#o=this.#o+s>>>0}update(o){let t;if(typeof o=="string")t=new TextEncoder().encode(o);else if(typeof o=="object")if(o instanceof ArrayBuffer||ArrayBuffer.isView(o))t=new Uint8Array(o);else throw new TypeError(Me);else throw new TypeError(Me);let r=this.#i,n=D-r;if(t.length<n)this.#n.set(t,r),r+=t.length;else{this.#n.set(t.slice(0,n),r),this.#c(this.#n);let s=n;for(;s+D<=t.length;)this.#c(t.slice(s,s+D)),s+=D;this.#n.fill(0).set(t.slice(s),0),r=t.length-s}return this.#i=r,this.#l(t.length),this}digest(){let o=D-this.#i;o<9&&(o+=D);let t=new Uint8Array(o);t0=128;let r=this.#s<<3,n=this.#a<<3|this.#s>>>29;tt.length-8=r&255,tt.length-7=r>>>8&255,tt.length-6=r>>>16&255,tt.length-5=r>>>24&255,tt.length-4=n&255,tt.length-3=n>>>8&255,tt.length-2=n>>>16&255,tt.length-1=n>>>24&255,this.update(t.buffer);let s=new ArrayBuffer(16),a=new DataView(s);return a.setUint32(0,this.#e,!0),a.setUint32(4,this.#t,!0),a.setUint32(8,this.#r,!0),a.setUint32(12,this.#o,!0),s}toString(o="hex"){let t=this.digest();switch(o){case"hex":return new TextDecoder().decode(Re(new Uint8Array(t)));case"base64":{let r=new Uint8Array(t),n="";for(let s=0;s<r.length;++s)n+=String.fromCharCode(rs);return btoa(n)}default:throw new Error("md5: invalid format")}}};var ht=e=>({type:"title",text:e.rows0.text}),xt=e=>{let{rows:o,...t}=e,{indent:r=0,text:n=""}=o??{},s=n.replace(/^\s*code:/,"");return{indent:r,type:"codeBlock",fileName:s,content:t.map(a=>a.text.substring(r+1)).join(` )}},L=(e,{parseOnNested:o,parseOnQuoted:t,patterns:r})=>(n,s,a)=>{var i,c,m,d,u,k;if(!o&&s.nested)return(i=a?.())!==null&&i!==void 0?i:[];if(!t&&s.quoted)return(c=a?.())!==null&&c!==void 0?c:[];for(let x of r){let l=x.exec(n);if(l===null)continue;let f=n.substring(0,l.index),p=n.substring(l.index+((d=(m=l[0])===null||m===void 0?void 0:m.length)!==null&&d!==void 0?d:0)),h=e((u=l[0])!==null&&u!==void 0?u:"",s);return[...M(f,s),...h,...M(p,s)]}return(k=a?.())!==null&&k!==void 0?k:[]},C=e=>[{type:"plain",raw:e,text:e}],yt=L(C,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]}),kt=/^>.*$/,bt=(e,o)=>o.context==="table"?C(e,o):[{type:"quote",raw:e,nodes:M(e.substring(1),{...o,quoted:!0})}],wt=L(bt,{parseOnNested:!1,parseOnQuoted:!1,patterns:[kt]}),Et=/^\? .+$/,Tt=(e,o)=>o.context==="table"?C(e,o):[{type:"helpfeel",raw:e,text:e.substring(2)}],vt=L(Tt,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Et]}),It=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)\]\]/i,Lt=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,Nt=(e,o)=>{if(o.context==="table")return C(e,o);let t=e.substring(2,e.length-2),r=/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(t);return[{type:"strongImage",raw:e,src:r?${t}/thumb/1000:t}]},Ct=L(Nt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[It,Lt]}),Pt=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/;function $e(e){return(o,t)=>{if(e==="strongIcon"&&t.context==="table")return C(o,t);let r=e==="icon"?o.substring(1,o.length-1):o.substring(2,o.length-2),n=r.lastIndexOf(".icon"),s=r.substring(0,n),a=s.startsWith("/")?"root":"relative",i=r.substring(n+5,r.length),c=i.startsWith("*")?parseInt(i.substring(1),10):1;return new Array(c).fill({}).map(()=>({path:s,pathType:a,type:e,raw:o}))}}var St=$e("icon"),Rt=L(St,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Pt]}),Mt=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,$t=$e("strongIcon"),jt=L($t,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Mt]}),Ot=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,Bt=(e,o)=>o.context==="table"?C(e,o):[{type:"strong",raw:e,nodes:M(e.substring(2,e.length-2),{...o,nested:!0})}],Dt=L(Bt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Ot]}),Ut=/\[\$ .+? \]/,Ft=/\[\$ [^\]]+\]/,qt=(e,o)=>o.context==="table"?C(e,o):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],At=L(qt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Ut,Ft]}),_t=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,Ht=(e,o)=>{if(o.context==="table")return C(e,o);let t=e.indexOf(" "),r=e.substring(1,t),n=e.substring(t+1,e.length-1),s=new Set(r);if(s.has("*")){let a=r.split("*").length-1;s.delete("*"),s.add(*-${Math.min(a,10)})}return[{type:"decoration",raw:e,rawDecos:r,decos:Array.from(s),nodes:M(n,{...o,nested:!0})}]},Gt=L(Ht,{parseOnNested:!1,parseOnQuoted:!0,patterns:[_t]}),zt=/.*?/,Kt=(e,o)=>o.context==="table"?C(e,o):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],Wt=L(Kt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[zt]}),Jt=/^[$%] .+$/,Qt=(e,o)=>{var t;if(o.context==="table")return C(e,o);let r=(t=e[0])!==null&&t!==void 0?t:"",n=e.substring(2);return[{type:"commandLine",raw:e,symbol:r,text:n}]},Xt=L(Qt,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Jt]}),Zt=/\[\s+\]/,Yt=(e,o)=>o.context==="table"?C(e,o):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],Vt=L(Yt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Zt]}),er=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,tr=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?\]/i,rr=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,or=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,nr=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg)(\?[^\]\s]+)?$/i.test(e)||sr(e),sr=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),ir=(e,o)=>{if(o.context==="table")return C(e,o);let t=e.search(/\s/),r=t!==-1?e.substring(1,t):e.substring(1,e.length-1),n=t!==-1?e.substring(t,e.length-1).trimLeft():"",[s,a]=nr(n)?[n,r]:[r,n];return[{type:"image",raw:e,src:/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(s)?${s}/thumb/1000:s,link:a}]},ar=L(ir,{parseOnNested:!0,parseOnQuoted:!0,patterns:[er,tr,rr,or]}),cr=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,lr=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,dr=/\[https?:\/\/[^\s\]]+\]/,pr=/https?:\/\/[^\s]+/,mr=(e,o)=>{if(o.context==="table")return C(e,o);let t=e.startsWith("[")&&e.endsWith("]")?e.substring(1,e.length-1):e,r=/^https?:\/\/[^\s\]]/.test(t),n=(r?/^https?:\/\/[^\s\]]+/:/https?:\/\/[^\s\]]+$/).exec(t);if(n?.[0]===void 0)return[];let s=r?t.substring(n[0].length):t.substring(0,n.index-1);return[{type:"link",raw:e,pathType:"absolute",href:n[0],content:s.trim()}]},ur=L(mr,{parseOnNested:!0,parseOnQuoted:!0,patterns:[cr,lr,dr,pr]}),je=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,Oe=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,fr=e=>{let[o="",t="",r=""]=e.split(","),n=parseFloat(o.replace(/^N/,"").replace(/^S/,"-")),s=parseFloat(t.replace(/^E/,"").replace(/^W/,"-")),a=/^Z\d+$/.test(r)?parseInt(r.replace(/^Z/,""),10):14;return{latitude:n,longitude:s,zoom:a}},gr=(e,o)=>{var t;if(o.context==="table")return C(e,o);let r=(t=e.match(je))!==null&&t!==void 0?t:e.match(Oe);if(r===null)return[];let n=e.startsWith("[N")||e.startsWith("[S"),[,s="",a=""]=n?r:[r[0],r[2],r[1]],{latitude:i,longitude:c,zoom:m}=fr(s),d=a!==""?https://www.google.com/maps/place/${encodeURIComponent(a)}/@${i},${c},${m}z:https://www.google.com/maps/@${i},${c},${m}z;return[{type:"googleMap",raw:e,latitude:i,longitude:c,zoom:m,place:a,url:d}]},hr=L(gr,{parseOnNested:!1,parseOnQuoted:!0,patterns:[je,Oe]}),xr=/\[\/?[^[\]]+\]/,yr=e=>{let o=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:o.startsWith("/")?"root":"relative",href:o,content:""}]},kr=L(yr,{parseOnNested:!0,parseOnQuoted:!0,patterns:[xr]}),br=/(?:^|\s)#\S+/,wr=(e,o)=>{if(o.context==="table")return C(e,o);if(e.startsWith("#"))return[{type:"hashTag",raw:e,href:e.substring(1)}];let t=e.substring(0,1),r=e.substring(1);return[...C(t,o),{type:"hashTag",raw:r,href:r.substring(1)}]},Er=L(wr,{parseOnNested:!0,parseOnQuoted:!0,patterns:[br]}),Tr=/^[0-9]+\. .*$/,vr=(e,o)=>{if(o.context==="table")return C(e,o);let t=e.indexOf(" "),r=e.substring(0,t-1),n=parseInt(r,10),s=e.substring(t+1,e.length);return[{type:"numberList",raw:e,rawNumber:r,number:n,nodes:M(s,{...o,nested:!0})}]},Ir=L(vr,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Tr]}),Lr=(e,o,t)=>{var r;return e===""?[]:(r=t?.())!==null&&r!==void 0?r:[]},Nr=(...e)=>(o,t)=>e.reduceRight((r,n)=>()=>n(o,t,r),()=>yt(o,t))(),M=Nr(Lr,wt,vt,Wt,Xt,At,Vt,Gt,Ct,jt,Dt,ar,ur,Rt,hr,kr,Er,Ir),Cr=e=>{let{rows:[o,...t]}=e,{indent:r=0,text:n=""}=o??{},s=n.replace(/^\s*table:/,"");return{indent:r,type:"table",fileName:s,cells:t.map(a=>a.text.substring(r+1)).map(a=>a.split(" ").map(i=>M(i,{nested:!1,quoted:!1,context:"table"})))}},Pr=e=>{let{indent:o,text:t}=e.rows[0];return{indent:o,type:"line",nodes:M(t.substring(o),{nested:!1,quoted:!1,context:"line"})}},S=e=>{switch(e.type){case"title":return ht(e);case"codeBlock":return xt(e);case"table":return Cr(e);case"line":return Pr(e)}},$=e=>e.split( ).map(o=>{var t,r,n;return{indent:(n=(r=(t=/^\s+/.exec(o))===null||t===void 0?void 0:t[0])===null||r===void 0?void 0:r.length)!==null&&n!==void 0?n:0,text:o}}),Sr=(e,o)=>{var t,r;return(e.type==="codeBlock"||e.type==="table")&&o.indent>((r=(t=e.rows[0])===null||t===void 0?void 0:t.indent)!==null&&r!==void 0?r:0)},Be=(e,o)=>{let t=e[e.length-1];return t!==void 0&&Sr(t,o)?(t.rows.push(o),e):(e.push({type:/^\s*code:/.test(o.text)?"codeBlock":/^\s*table:/.test(o.text)?"table":"line",rows:[o]}),e)},j=(e,o)=>{var t;if(!((t=o.hasTitle)!==null&&t!==void 0)||t){let[r,...n]=e;return r===void 0?[]:[{type:"title",rows:[r]},...n.reduce(Be,[])]}return e.reduce(Be,[])},De=(e,o)=>{var t;let r=$(e);return j(r,{hasTitle:(t=o?.hasTitle)!==null&&t!==void 0?t:!0}).map(S)};var Ue=e=>{if(!e.includes(".note"))return;let[,o,t]=e.match(/^(.+)\(([^()]+)\)$/)??[,e],r=o.match(/^(.+?)\.note(?:|\.(.+))$/);if(!r)return;let[,n,s=""]=r;return{guid:n,name:s,isScrapboxSyntax:!t}};var _=(e,o)=>{let[,t,r]=e.match(/^\/([\w\-]+)\/(.+)$/)??[];return t&&r?{project:t,title:r}:{project:o,title:e}};var Rr={"&":"&","<":"<",">":">",'"':""","'":"'"},v=e=>e.replace(/[&<>"']/g,o=>Rr[o]);var w=" ",Fe=(e,o,t)=>{let r=Math.min(...e.map(a=>a.indent)),n=0,s=[];for(let a=0;a<e.length;a++){let i=e[a],c=i.indent-r;for(let d=n;d>c;d--)s.push(${w.repeat(d-1)}</ul>);for(let d=n;d<c;d++)s.push(${w.repeat(d)}<ul class="level-${d+1}">);let m=w.repeat(c);switch(i.type){case"codeBlock":s.push(c===0?qe(i):${m}<li>
${qe(i).split(`
).map(d=>${m}${w}${d}).join(
`)}
${m}</li>);break;case"table":s.push(c===0?Ae(i,o,t):${m}<li>
${Ae(i,o,t).split(`
).map(d=>${m}${w}${d}).join(
`)}
${m}</li>);break;case"line":{let d=i.nodes.map(u=>H(u,o,t)).join("");s.push(c===0?${d}${a+1===e.length?"":"<br/>"}:${m}<li>${d}</li>)}break}n=c}for(let a=n;a>0;a--)s.push(${w.repeat(a-1)}</ul>);return s.join(
)},qe=e=><figure class="codeBlock">
${w}<figcaption><code>${v(e.fileName)}</code></figcaption>
${w}<pre><code>${v(e.content)}</code></pre>
</figure>,Ae=(e,o,t)=>{let[r,...n]=e.cells.map(s=>s.map(a=>a.map(i=>H(i,o,t)).join("")));return<table class="table">
${w}<caption>${v(e.fileName)}</caption>
${w}<thead>
${w}${w}<tr>
${r?.map?.(s=>${w.repeat(3)}<th>${s}</th>)?.join?.(`
`)??""}
${w}${w}</tr>
${w}</thead>
${w}<tbody>
${n?.map?.(s=>`${w}${w}<tr>
${s.map(a=>${w.repeat(3)}<td>${a}</td>).join(`
`)}
${w}${w}</tr>)?.join?.(
`)}
${w}</tbody>
</table>},H=(e,o,t)=>{switch(e.type){case"quote":return<span class="quote">${e.nodes.map(r=>H(r,o,t)).join("")}</span>;case"image":case"strongImage":{let r=<img class="image" src="${v(e.src)}" />;return e.type==="image"?r:<strong>${r}</strong>}case"strongIcon":case"icon":{let r=_(e.path,o),n=https://scrapbox.io/api/pages/${r.project}/${r.title}/icon,s=https://scrapbox.io/${r.project}/${r.title},a=e.path,i=<a class="icon" target="_blank" href="${v(s)}"><img src="${v(n)}" alt="${v(a)}" /></a>;return e.type==="icon"?i:<strong>${i}</strong>}case"formula":return\\( ${v(e.formula)} \\);case"decoration":{let r=e.nodes.map(n=>H(n,o,t)).join("");return e.decos.length===0?r:<span class="${e.decos.map(n=>deco-${v(n)}).join(" ")}">${r}</span>}case"strong":return<strong>${e.nodes.map(r=>H(r,o,t)).join("")}</strong>;case"code":return<code class="code">${v(e.text)}</code>;case"commandLine":return<code class="cli">${e.symbol} ${v(e.text)}</code>;case"helpfeel":return<code class="helpfeel">? ${v(e.text)}</code>;case"googleMap":return<a class="google-map" href="https://www.google.com/maps/search/${e.place}/@${e.latitude},${e.longitude},${e.zoom}z">N${e.latitude},E${e.longitude},Z${e.zoom} ${e.place}</a>;case"link":switch(e.pathType){case"relative":case"root":{let r=_(e.href,o),n=https://scrapbox.io/${r.project}/${v(P(r.title))};return<a class="page-link" target="_blank" href="${v(n)}">${v(e.href)}</a>}default:return<a class="link" target="_blank" href="${v(e.href)}">${v(e.content||e.href)}</a>}case"hashTag":return t(e.href),"";case"numberList":return${e.number}. ${e.nodes.map(r=>H(r,o,t)).join("")};case"blank":return e.text;case"plain":return v(e.text)}};var _e=(e,o,t)=>{if(t.length===0)return[];let r=j($(t.map(c=>c.text).join( )),{hasTitle:!0}),n=new Map,s,a,i=0;for(let c of r)switch(c.type){case"title":i++;break;case"table":case"line":{if(i+=c.rows.length,s&&a)break;let m=S(c),d=Mr(m);for(let u of d)u.toLowerCase().startsWith("deck-")&&(s??=_(u,e)),u.toLowerCase().startsWith("notetype-")&&(a??=_(u,e));break}case"codeBlock":{i+=c.rows.length;let m=S(c);if(m.type!=="codeBlock")throw SyntaxError();let d=Ue(m.fileName);if(!d)break;let{guid:u,name:k,isScrapboxSyntax:x}=d,l=n.get(u)??{guid:u,id:1/0,updated:-1/0,fields:new Map([["SourceURL",[!1,https://scrapbox.io/${e}/${P(o)}#${t[i].id}]]])};l.id=Math.min(...t.slice(i,i+c.rows.length).map(h=>h.created*1e3),l.id),l.updated=Math.max(...t.slice(i,i+c.rows.length).map(h=>h.updated*1e3),l.updated);let[f,p]=l.fields.get(k)??[!0,""];l.fields.set(k,[f&&x,p?${p} ${m.content}:m.content]),n.set(u,l);break}}return[...n.values()].map(({fields:c,...m})=>{let d=[],u=new Set,k=l=>{let f=z(l);u.has(f)||(u.add(f),d.push(l))},x=new Map;k(e),k(o);for(let[l,[f,p]]of c.entries()){if(!f){x.set(l,p);continue}let h=Fe(De(p,{hasTitle:!1}),e,k);x.set(l,h)}return{...m,deck:s,noteType:a,fields:x,tags:d}})},Mr=e=>{switch(e.type){case"line":return e.nodes.flatMap(o=>oe(o));case"table":return e.cells.flatMap(o=>o.flatMap(t=>t.flatMap(r=>oe(r))));default:return[]}},oe=e=>{switch(e.type){case"icon":case"strongIcon":return[e.path];case"decoration":case"quote":return e.nodes.flatMap(o=>oe(o));default:return[]}};var He=e=>{if(e.lines.length===0)return{ok:!1,value:{name:"DeckNotFoundError",message:"This is an empty page so no deck is found."}};let o=j($(e.lines.map(s=>s.text).join(
)),{hasTitle:!0}),t="",r=0,n="deck.json";for(let s of o)switch(s.type){case"title":case"line":r++;break;case"table":r+=s.rows.length;break;case"codeBlock":{r+=s.rows.length;let a=S(s);if(a.type!=="codeBlock")throw Error("Must be a codeblock");if(!a.fileName.endsWith(n))break;t+=
${a.content};break}}if(t.trim()==="")return{ok:!1,value:{name:"DeckNotFoundError",message:"No deck settings found in the page."}};try{let s=JSON.parse(t);return typeof s!="object"||s==null?{ok:!1,value:G("Deck setting must be an object.")}:"name"in s?typeof s.name!="string"?{ok:!1,value:G("Deck name must be string.")}:"id"in s?typeof s.id!="number"?{ok:!1,value:G("Deck id must be number.")}:"description"in s&&typeof s.description!="string"?{ok:!1,value:G("Deck description must be string.")}:{ok:!0,value:{id:s.id,name:s.name,updated:e.updated,..."description"in s?{description:s.description}:{}}}:{ok:!1,value:G("Deck id not found.")}:{ok:!1,value:G("Deck name is not found.")}}catch(s){if(s instanceof SyntaxError)return{ok:!1,value:{name:"DeckSyntaxError",message:s.message}};throw s}},G=e=>({name:"InvalidDeckError",message:e});var ne=[{name:"SourceURL",description:"問題の取得元URL"}],Ge=e=>{if(e.lines.length===0)return{ok:!1,value:{name:"NoteTypeNotFoundError",message:"This is an empty page so no note type is found."}};let o=j($(e.lines.map(l=>l.text).join(
)),{hasTitle:!0}),t=0,r="noteType.json",n="",s="css",a="",i="pre.tex",c="",m="post.tex",d="",u=".question.html",k=".answer.html",x=new Map;for(let l of o)switch(l.type){case"title":case"line":t++;break;case"table":t+=l.rows.length;break;case"codeBlock":{t+=l.rows.length;let f=S(l);if(f.type!=="codeBlock")throw Error("Must be a codeblock");let p=
${f.content};switch(f.fileName){case r:n+=p;break;case s:a+=p;break;case i:c+=p;break;case m:d+=p;break;default:{if(f.fileName.endsWith(u)){let h=[...f.fileName].slice(0,-u.length).join(""),b=x.get(h)??["",""];b[0]+=p,x.set(h,b);break}if(f.fileName.endsWith(k)){let h=[...f.fileName].slice(0,-k.length).join(""),b=x.get(h)??["",""];b[1]+=p,x.set(h,b);break}break}}break}}if(n.trim()==="")return{ok:!1,value:{name:"NoteTypeNotFoundError",message:"No note type settings found in the page."}};try{let l=JSON.parse(n);if(typeof l!="object"||l==null)return{ok:!1,value:N("Note type setting must be an object.")};if(!("name"in l))return{ok:!1,value:N("Note type name is not found.")};if(typeof l.name!="string")return{ok:!1,value:N("Note type name must be string.")};if(!("id"in l))return{ok:!1,value:N("Note type id not found.")};if(typeof l.id!="number")return{ok:!1,value:N("Note type id must be number.")};if(!("fields"in l))return{ok:!1,value:N("Note type must have fields.")};if(!Array.isArray(l.fields))return{ok:!1,value:N("fields must be an array.")};let f=[];for(let b of l.fields){let g=b;switch(typeof g){case"string":if(ne.some(({name:I})=>g===I))break;f.push({name:g});break;case"object":{if(g==null||!("name"in g))return{ok:!1,value:N("Each field object must have name.")};if(typeof g.name!="string")return{ok:!1,value:N("The name of a field must be a string.")};if(ne.some(({name:F})=>g.name===F))break;let I={name:g.name};if("description"in g){if(typeof g.description!="string")return{ok:!1,value:N("The description of a field must be a string.")};I.description=g.description}if("rtl"in g){if(typeof g.rtl!="boolean")return{ok:!1,value:N("The rtl of a field must be a boolean.")};I.rtl=g.rtl}if("font"in g){if(typeof g.font!="string")return{ok:!1,value:N("The font of a field must be a string.")};I.font=g.font}if("fontSize"in g){if(typeof g.fontSize!="number")return{ok:!1,value:N("The fontSize of a field must be a number.")};I.fontSize=g.fontSize}f.push(I);break}default:return{ok:!1,value:N("Members of fields must be a string or an object.")}}}f.push(...ne);let p=[];if(x.size===0)return{ok:!1,value:N("Note type must have one or more template.")};for(let[b,[g,I]]of x.entries()){if(g.trim()==="")return{ok:!1,value:N("${b}${u}" is empty.)};if(I.trim()==="")return{ok:!1,value:N("${b}${k}" is empty.)};p.push({name:b,question:g,answer:I})}let h={name:l.name,id:l.id,updated:e.updated,fields:f,templates:p};if(a.trim()!==""&&(h.css=a),c.trim()!==""&&d.trim()!==""&&(h.latex=[c,d]),"isCloze"in l){if(typeof l.isCloze!="boolean")return{ok:!1,value:N("isCloze must be number.")};h.isCloze=l.isCloze}return{ok:!0,value:h}}catch(l){if(l instanceof SyntaxError)return{ok:!1,value:{name:"NoteTypeSyntaxError",message:l.message}};throw l}},N=e=>({name:"InvalidNoteTypeError",message:e});var ze=new Map,$r=e=>{let o=ze.get(U(e));if(o)return o;let t=(async()=>{let r=await R(e.project,e.title);return r.ok?He(r.value):r})();return ze.set(U(e),t),t},Ke=new Map,jr=e=>{let o=Ke.get(U(e));if(o)return o;let t=(async()=>{let r=await R(e.project,e.title);return r.ok?Ge(r.value):r})();return Ke.set(U(e),t),t},We=async(e,o)=>{let t=new Map,r=new Map,n=[];for(let s of o){let a=U({project:e,title:s.title}),i=t.get(a)??{deckNotSpecified:!1,noteTypeNotSpecified:!1,skipped:0},c=_e(e,s.title,s.lines);for(let m=0;m<c.length;m++){let d=c[m];if(!d.deck||!d.noteType){d.deck||(console.warn(Deck is not specified in ${a}),i.deckNotSpecified=!0),d.noteType||(console.warn(Note type is not specified in ${a}),i.noteTypeNotSpecified=!0),i.skipped=c.length-m;break}let u=await $r(d.deck);if(!u.ok){console.warn(${u.value.name} ${u.value.message}),r.set(U(d.deck),u.value),i.skipped=c.length-m;break}let k=u.value,x=await jr(d.noteType);if(!x.ok){console.warn(${x.value.name} ${x.value.message}),r.set(U(d.noteType),x.value),i.skipped=c.length-m;break}let l=x.value,f=l.fields.map((p,h)=>{let b=typeof p=="string"?p:p.name,g=d.fields.get(b);return h===0?g??d.fields.get("")??"":g??""});n.push({guid:d.guid,id:d.id,updated:d.updated,tags:d.tags,fields:f,deck:k,noteType:l})}(i.deckNotSpecified||i.noteTypeNotSpecified||i.skipped>0)&&t.set(a,i)}return{notes:n,warnings:t,errors:r}},U=e=>/${e.project}/${e.title};var Je=(e,o)=>{let t=new o.Database,r={activeDecks:[1],addToCur:!0,collapseTime:1200,curDeck:1,curModel:"1435645724216",dueCounts:!0,estTimes:!0,newBury:!0,newSpread:0,nextPos:1,sortBackwards:!1,sortType:"noteFld",timeLim:0},n={},s=new Map;{let l=Y();l(1),n[1]={collapsed:!1,conf:1,desc:"",dyn:0,extendNew:10,extendRev:50,id:1,lrnToday:[0,0],mod:0,name:"Default",newToday:[0,0],revToday:[0,0],timeToday:[0,0],usn:0};let f=new Set(e.flatMap(p=>p.noteType.deck?[p.deck,p.noteType.deck]:[p.deck]));for(let p of f){let h=Hr(p,l);n[h.id]=h,s.set(p,h.id)}}let a={},i=new Map;{let l=Y(),f=new Set(e.map(p=>p.noteType));for(let p of f){let h=p.deck?s.get(p.deck):void 0,b=qr(p,h,l);a[b.id]=b,i.set(p,b.id)}}let c={},m={};{let l=Y(),f=Y();for(let p of e){let h=i.get(p.noteType);if(h===void 0)throw Error("Note type id must be already generated");let b=s.get(p.deck);if(b===void 0)throw Error("Deck id must be already generated");let g=Br(p,h,f);c[g.id]=g;for(let I of Dr(p,b,g.id,l))m[I.id]=I}}let d={1:{autoplay:!0,id:1,lapse:{delays:[10],leechAction:0,leechFails:8,minInt:1,mult:0},maxTaken:60,mod:0,name:"Default",new:{bury:!0,delays:[1,10],initialFactor:2500,ints:[1,4,7],order:1,perDay:20,separate:!0},replayq:!0,rev:{bury:!0,ease4:1.3,fuzz:.05,ivlFct:1,maxIvl:36500,minSpace:1,perDay:100},timer:0,usn:0}},u=
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE col (
id integer primary key,
crt integer not null,
mod integer not null,
scm integer not null,
ver integer not null,
dty integer not null,
usn integer not null,
ls integer not null,
conf text not null,
models text not null,
decks text not null,
dconf text not null,
tags text not null
);
INSERT INTO "col" VALUES(
1,
1388548800,
1435645724219,
1435645724215,
11,
0,
0,
0,
'${JSON.stringify(r)}',
'${JSON.stringify(a)}',
'${JSON.stringify(n)}',
'${JSON.stringify(d)}',
'{}'
);
CREATE TABLE notes (
id integer primary key, /* 0 */
guid text not null, /* 1 */
mid integer not null, /* 2 */
mod integer not null, /* 3 */
usn integer not null, /* 4 */
tags text not null, /* 5 */
flds text not null, /* 6 */
sfld integer not null, /* 7 */
csum integer not null, /* 8 */
flags integer not null, /* 9 */
data text not null /* 10 */
);
CREATE TABLE cards (
id integer primary key, /* 0 */
nid integer not null, /* 1 */
did integer not null, /* 2 */
ord integer not null, /* 3 */
mod integer not null, /* 4 */
usn integer not null, /* 5 */
type integer not null, /* 6 */
queue integer not null, /* 7 */
due integer not null, /* 8 */
ivl integer not null, /* 9 */
factor integer not null, /* 10 */
reps integer not null, /* 11 */
lapses integer not null, /* 12 */
left integer not null, /* 13 */
odue integer not null, /* 14 */
odid integer not null, /* 15 */
flags integer not null, /* 16 */
data text not null /* 17 */
);
CREATE TABLE revlog (
id integer primary key,
cid integer not null,
usn integer not null,
ease integer not null,
ivl integer not null,
lastIvl integer not null,
factor integer not null,
time integer not null,
type integer not null
);
CREATE TABLE graves (
usn integer not null,
oid integer not null,
type integer not null
);
ANALYZE sqlite_master;
INSERT INTO "sqlite_stat1" VALUES('col',NULL,'1');
CREATE INDEX ix_notes_usn on notes (usn);
CREATE INDEX ix_cards_usn on cards (usn);
CREATE INDEX ix_revlog_usn on revlog (usn);
CREATE INDEX ix_cards_nid on cards (nid);
CREATE INDEX ix_cards_sched on cards (did, queue, due);
CREATE INDEX ix_revlog_cid on revlog (cid);
CREATE INDEX ix_notes_csum on notes (csum);
COMMIT;
;t.run(u);let k=t.prepare("insert or replace into notes values(:id,:guid,:mid,:mod,:usn,:tags,:flds,:sfld,:csum,:flags,:data)");for(let l of Object.values(c))k.run(Object.fromEntries([...Object.entries(l)].map(([f,p])=>[:${f},p])));let x=t.prepare("insert or replace into cards values(:id,:nid,:did,:ord,:mod,:usn,:type,:queue,:due,:ivl,:factor,:reps,:lapses,:left,:odue,:odid,:flags,:data)");for(let l of Object.values(m))x.run(Object.fromEntries([...Object.entries(l)].map(([f,p])=>[:${f},p])));return t.export()},Qe=(e,o,t,r)=>{let n=new t;n.file("collection.anki2",e);let s=[...o instanceof Map?o.entries():Object.entries(o)],a=Object.fromEntries(s.map(([i],c)=>[c,i]));return n.file("media",JSON.stringify(a)),s.forEach(([,i],c)=>n.file(${c},i)),n.generateAsync({type:"blob",...r})},Or="",Br=(e,o,t)=>{let r=e.fields.join(Or);return{id:t(e.id),guid:e.guid??Gr(),tags:e.tags?.map?.(n=>n.replaceAll(" ","_"))?.join?.(" ")??"",mid:o,mod:e.updated??e.id,flds:r,sfld:r,usn:-1,flags:0,data:"",csum:0}},Dr=(e,o,t,r)=>e.noteType.isCloze?Fr(e,o,t,r):Ur(e,o,t,r),Ur=(e,o,t,r)=>{let n=e.noteType.fields.map(s=>typeof s=="string"?s:s.name);return e.noteType.templates.flatMap((s,a)=>{for(let[,i]of s.question.matchAll(/{{(?:type\:|hint\:|#|\/)?([^}]+)}}/g)){let c=n.indexOf(i);if(!(c<0)&&!e.fields[c])return[]}return[Xe({ord:a,noteId:t,deckId:o,created:t},r)]})},Fr=(e,o,t,r)=>{let n=e.noteType.templates[0].question,s=new Set([...n.matchAll(/{{[^}]*?cloze:(?:[^}]?:)*(.+?)}}/g),...n.matchAll(/<%cloze:(.+?)%>/g)].map(([i,c])=>c)),a=new Set([...s].flatMap(i=>{let c=e.noteType.fields.findIndex(u=>(typeof u=="string"?u:u.name)===i);return[...(c<0?"":e.fields[c]).matchAll(/{{c(\d+)::.+?}}/g)].map(([u,k])=>parseInt(k)).flatMap(u=>u>=1?[u-1]:[])}));return a.size===0&&a.add(0),[...a].map(i=>Xe({ord:i,noteId:t,deckId:o,created:t},r))},Xe=(e,o)=>({ord:e.ord,id:o(e.created),nid:e.noteId,did:e.deckId,mod:e.updated??Math.round(e.created/1e3),usn:-1,type:0,queue:0,due:0,ivl:0,factor:0,reps:0,lapses:0,left:0,odue:0,odid:0,flags:0,data:""}),qr=(e,o,t)=>({vers:[],name:e.name,tags:[],did:o??1,usn:-1,req:[[0,"all",[0]]],flds:e.fields.map((r,n)=>Ar(r,n)),sortf:0,latexPre:e.latex?.[0]??\\documentclass12pt{article} \\special{papersize=3in,5in}
\\usepackageutf8{inputenc} \\usepackage{amssymb,amsmath}
\\pagestyle{empty}
\\setlength{\\parindent}{0in}
\\begin{document}
,tmpls:e.templates.map((r,n)=>_r(r,n)),latexPost:e.latex?.[1]??"\\end{document}",type:e.isCloze?1:0,id:t(e.id),css:e.css??.card {
font-family: arial;
font-size: 20px;
text-align: center;
color: black;
background-color: white;
}
,mod:e.updated??Math.round(e.id/1e3)}),Ar=(e,o)=>typeof e=="string"?{name:e,description:"",media:[],sticky:!1,rtl:!1,ord:o,font:"Arial",size:20}:{name:e.name,description:e.description??"",media:[],sticky:!1,rtl:e.rtl??!1,ord:o,font:e.font??"Arial",size:e.fontSize??20},_r=(e,o)=>({name:e.name,ord:o,did:null,qfmt:e.question,bafmt:e.example?.[0]??"",afmt:e.answer,bqfmt:e.example?.[1]??""}),Hr=(e,o)=>({collapsed:!1,conf:1,desc:e.description??"",dyn:0,extendNew:10,extendRev:50,id:o(e.id),lrnToday:[545,0],mod:e.updated??Math.round(e.id/1e3),name:e.name,newToday:[545,0],revToday:[545,0],timeToday:[545,0],usn:-1}),Y=()=>{let e=-1;return o=>e<o?(e=o,o):++e},se="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&()*+,-./:;<=>?@[]^_{|}~",Gr=()=>{let e=Math.floor(Math.random()*Number.MAX_SAFE_INTEGER),o="";for(;e>0;){let t=Math.floor(e/se.length),r=e%se.length;o+=ser,e=t}return o.split("").reverse().join("")};var Ze=async(e,o,t)=>{let{notes:r,warnings:n,errors:s}=await We(e,o);if(n.size>0||s.size>0){let a=[There are ${n.size} warnings and ${s.size} errors.,"","Warnings:"," (page), (has deck?), (has note type?), (skipped)",......n.entries().map((i,c)=>[ ${i},c.deckNotSpecified?"x":"o",c.noteTypeNotSpecified?"x":"o",c.skipped].join(` )),"","Errors",...[...s.entries()].map(([i,c])=> ${i} ${c.name}: ${c.message}),"","Do you want to create .apkg?"];if(!globalThis.confirm(a.join(
)))return}return Qe(Je(r,t.sql),{},t.JSZip)};var Ye=!1;scrapbox.addListener("lines:changed",()=>Ye=!1);scrapbox.addListener("layout:changed",()=>Ye=!1);var Ve=(e,o)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${o}" must be HTMLDivElememt but actual is "${e}")};var et=()=>zr(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),zr=(e,o)=>{if(!!e)return Ve(e,o),e};var rt=()=>{let e=et();if(!e)throw new Error("div.status-bar can't be found");let o=document.createElement("div");return e.append(o),{render:(...t)=>{o.textContent="";let r=ot(...t);r&&o.append(r)},dispose:()=>o.remove()}},ot=(...e)=>{let o=e.flatMap(r=>{switch(r.type){case"spinner":return[Yr()];case"check-circle":return[Vr()];case"exclamation-triangle":return[eo()];case"text":return[V(r.text)];case"group":{let n=ot(...r.items);return n?[n]:[]}}});if(o.length===0)return;if(o.length===1)return o[0];let t=document.createElement("span");return t.classList.add("item-group"),t.append(...o),t},V=e=>{let o=document.createElement("span");return o.classList.add("item"),o.append(e),o},Yr=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),V(e)},Vr=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),V(e)},eo=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),V(e)};await(async()=>{if(scrapbox?.Layout!=="page")return;let{sql:e}=await at().then(()=>it),o=scrapbox.Project.name,{render:t,dispose:r}=rt();try{t({type:"spinner"},{type:"text",text:loading /${o}/${scrapbox.Page.title}});let n=await R(o,scrapbox.Page.title);if(!n.ok){console.error(n.value),alert(${n.value.name} ${n.value.message});return}t({type:"spinner"},{type:"text",text:creating .apkg from /${o}/${scrapbox.Page.title}});let s=await Ze(o,[n.value],{JSZip,sql:e});if(!s)return;let a=URL.createObjectURL(new Blob([s],{type:"application/octet-stream"}));t({type:"check-circle"},{type:"text",text:"created."});let i=document.createElement("a");i.href=a,i.download="cloze.apkg",i.download=${o}.apkg`,i.style.display="none",i.click(),i.remove(),URL.revokeObjectURL(a)}finally{setTimeout(r,1e3)}})();
})();
global変数と干渉しないよう、iifeでくくっておく必要がある
code:crawl.js
(async()=>{
var be=Object.defineProperty;var Mo=Reflect.get,$o=Reflect.set;var vt=e=>be(e,"__esModule",{value:!0});var we=(e,o)=>()=>(e&&(o=e(e=0)),o);var It=(e,o)=>{vt(e);for(var t in o)be(e,t,{get:ot,enumerable:!0})};var ye,bt=we(()=>{ye=(e,o)=>new Promise((t,r)=>{let{id:n,module:s=!1}=o;document.getElementById(n)?.remove();let i=document.createElement("script");i.addEventListener("load",()=>t()),i.addEventListener("error",c=>r(c)),i.src=e,i.id=n,s&&(i.type="module"),document.head.append(i)})});var Et={};It(Et,{sql:()=>Ro});var wt,Po,So,Ro,Tt=we(async()=>{bt();wt="1.8.0",Po="3.10.1",So="6339056660dae0001f816bc1";await Promise.all([ye(https://cdnjs.cloudflare.com/ajax/libs/sql.js/${wt}/sql-wasm.min.js,{id:"sqljs-cdn"}),ye(https://cdnjs.cloudflare.com/ajax/libs/jszip/${Po}/jszip.min.js,{id:"jszip-cdn"})]);Ro=await initSqlJs({locateFile:e=>e==="sql-wasm.wasm"?https://scrapbox.io/files/${So}.wasm:https://cdnjs.cloudflare.com/ajax/libs/sql.js/${wt}/${e}})});var b=e=>{let{fetch:o=globalThis.fetch,hostName:t="scrapbox.io",...r}=e;return{fetch:o,hostName:t,...r}};var Lt=e=>typeof e=="object"&&e!==null,Nt=e=>Lt(e)?(e.name===void 0||typeof e.name=="string")&&typeof e.message=="string":!1,Ee=e=>{try{let o=typeof e=="string"?JSON.parse(e):e;return Nt(o)?o:!1}catch(o){if(o instanceof SyntaxError)return!1;throw o}};var F=class extends Error{constructor(o){super(${o.status} ${o.statusText} when fetching ${o.url});this.response=o;this.name="UnexpectedResponseError";Error.captureStackTrace&&Error.captureStackTrace(this,F)}},T=async e=>{let o=e.clone(),t=await o.text(),r=Ee(t);if(!r)throw new F(o);return{ok:!1,value:r}};var ce=async e=>{let{sid:o,hostName:t,fetch:r}=b(e??{}),n=new Request(https://${t}/api/users/me,o?{headers:{Cookie:E(o)}}:void 0),s=await r(n);if(!s.ok)throw new F(s);return await s.json()};var E=e=>connect.sid=${e};var S=e=>e.replaceAll(" ","_").toLowerCase();var P=e=>...e.map((o,t)=>o===" "?"_":!Ct.includes(o)||t===e.length-1&&Pt.includes(o)?encodeURIComponent(o):o).join(""),Ct='@$&+=:;",',Pt=':;",';var Te=(e,o,t)=>{let{sid:r,hostName:n,followRename:s,projects:a}=b(t??{}),i=new URLSearchParams;i.append("followRename",${s??!0});for(let d of a??[])i.append("projects",d);let c=https://${n}/api/pages/${e}/${P(o)}?${i.toString()};return new Request(c,r?{headers:{Cookie:E(r)}}:void 0)},ve=async e=>{if(!e.ok)return e.status===414?{ok:!1,value:{name:"TooLongURIError",message:"project ids may be too much."}}:T(e);let o=await e.json();return{ok:!0,value:o}},$=async(e,o,t)=>{let{fetch:r}=b(t??{}),n=Te(e,o,t),s=await r(n);return await ve(s)};$.toRequest=Te;$.fromResponse=ve;var Ie=(e,o)=>{let{sid:t,hostName:r,sort:n,limit:s,skip:a}=b(o??{}),i=new URLSearchParams;n!==void 0&&i.append("sort",n),s!==void 0&&i.append("limit",${s}),a!==void 0&&i.append("skip",${a});let c=https://${r}/api/pages/${e}?${i.toString()};return new Request(c,t?{headers:{Cookie:E(t)}}:void 0)},Le=async e=>{if(!e.ok)return T(e);let o=await e.json();return{ok:!0,value:o}},ee=async(e,o)=>{let{fetch:t}=b(o??{}),r=await t(Ie(e,o));return await Le(r)};ee.toRequest=Ie;ee.fromResponse=Le;var Ne=(e,o,t,r)=>{let{sid:n,hostName:s}=b(r??{}),a=https://${s}/api/table/${e}/${P(o)}/${encodeURIComponent(t)}.csv;return new Request(a,n?{headers:{Cookie:E(n)}}:void 0)},Ce=async e=>e.ok?{ok:!0,value:await e.text()}:e.status===404?{ok:!1,value:{name:"NotFoundError",message:"Table not found."}}:T(e),Pe=async(e,o,t,r)=>{let{fetch:n}=b(r??{}),s=Ne(e,o,t,r),a=await n(s);return await Ce(a)};Pe.toRequest=Ne;Pe.fromResponse=Ce;var Se=(e,o)=>{let{sid:t,hostName:r}=b(o??{});return new Request(https://${r}/api/projects/${e},t?{headers:{Cookie:E(t)}}:void 0)},Re=async e=>{if(!e.ok)return T(e);let o=await e.json();return{ok:!0,value:o}},te=async(e,o)=>{let{fetch:t}=b(o??{}),r=Se(e,o),n=await t(r);return Re(n)};te.toRequest=Se;te.fromResponse=Re;var Me=(e,o)=>{let{sid:t,hostName:r}=b(o??{}),n=new URLSearchParams;for(let s of e)n.append("ids",s);return new Request(https://${r}/api/projects?${n.toString()},t?{headers:{Cookie:E(t)}}:void 0)},$e=async e=>{if(!e.ok)return T(e);let o=await e.json();return{ok:!0,value:o}},Oe=async(e,o)=>{let{fetch:t}=b(o??{}),r=await t(Me(e,o));return $e(r)};Oe.toRequest=Me;Oe.fromResponse=$e;var R=async(e,o)=>{let t=await $(e,o);if(!t.ok)throw new Error(You have no privilege of editing "/${e}/${o}".);let{commitId:r,persistent:n,image:s,links:a,projectLinks:i,lines:c,id:d,pin:l}=t.value;return{commitId:r,pageId:d,persistent:n,image:s,links:a,projectLinks:i,pin:l,lines:c}};var St="4.2.0";async function O(){let o=(await Rt())("https://scrapbox.io",{reconnectionDelay:5e3,transports:["websocket"]});return await new Promise((t,r)=>{let n=s=>r(s);o.once("connect",()=>{o.off("disconnect",n),t()}),o.once("disconnect",n)}),o}function Rt(){let e=https://cdnjs.cloudflare.com/ajax/libs/socket.io/${St}/socket.io.min.js;if(document.querySelector(script[src="${e}"]))return Promise.resolve(window.io);let o=document.createElement("script");return o.src=e,new Promise((t,r)=>{o.onload=()=>t(window.io),o.onerror=n=>r(n),document.head.append(o)})}function q(e,o=9e4){function t(n,s){let a;return new Promise((i,c)=>{let d=l=>{clearTimeout(a),c(new Error(l))};e.emit(n,s,l=>{clearTimeout(a),e.off("disconnect",d),l.error&&c(new Error(JSON.stringify(l.error))),"data"in l?i(l?.data):i(void 0)}),a=setTimeout(()=>{e.off("disconnect",d),c(new Error(Timeout: exceeded ${o}ms))},o),e.once("disconnect",d)})}async function*r(...n){let s,a=()=>new Promise(c=>s=c),i=c=>{s?.(c)};for(let c of n)e.on(c,i);try{for(;;)yield await a()}finally{for(let c of n)e.off(c,i)}}return{request:t,response:r}}var oe,A=async()=>{if(oe!==void 0)return oe;let e=await ce();if(e.isGuest)throw new Error("this script can only be executed by Logged in users");return oe=e.id,oe},je=new Map,z=async e=>{let o=je.get(e);if(o!==void 0)return o;let t=await te(e);if(!t.ok){let{name:n,message:s}=t.value;throw new Error(${n} ${s})}let{id:r}=t.value;return je.set(e,r),r},Be=e=>e.padStart(8,"0"),le=e=>{let o=Math.floor(new Date().getTime()/1e3).toString(16),t=Math.floor(16777214*Math.random()).toString(16);return${Be(o).slice(-8)}${e.slice(-6)}0000${Be(t)}};var ne=async(e,o,t)=>o.length===0?{commitId:t.parentId}:await e("socket.io-request",{method:"commit",data:{kind:"page",...t,changes:o,cursor:null,freeze:!0}}),Q=async(e,o,{project:t,title:r,retry:n=3,parentId:s,...a})=>{try{s=(await ne(e,o,{parentId:s,...a})).commitId}catch{console.log("Faild to push a commit. Retry after pulling new commits");for(let c=0;c<n;c++){let{commitId:d}=await R(t,r);s=d;try{s=(await ne(e,o,{parentId:s,...a})).commitId,console.log("Success in retrying");break}catch{continue}}throw Error("Faild to retry pushing.")}return s};var De=(e,o,t,r)=>{let{sid:n,hostName:s}=b(r??{}),a=https://${s}/api/code/${e}/${P(o)}/${P(t)};return new Request(a,n?{headers:{Cookie:E(n)}}:void 0)},Ue=async e=>e.ok?{ok:!0,value:await e.text()}:e.status===404&&e.headers.get("Content-Type")?.includes?.("text/plain")?{ok:!1,value:{name:"NotFoundError",message:"Code block is not found"}}:T(e),se=async(e,o,t,r)=>{let{fetch:n}=b(r??{}),s=De(e,o,t,r),a=await n(s);return await Ue(a)};se.toRequest=De;se.fromResponse=Ue;var Fe=new TextEncoder().encode("0123456789abcdef");function qe(e){let o=new Uint8Array(e.length*2);for(let t=0;t<o.length;t++){let r=et;ot*2=Fer>>4,ot*2+1=Fer&15}return o}var Ae="md5: data is invalid type",_=64,de=class{#e;#t;#r;#o;#n;#i;#s;#a;constructor(){this.#e=1732584193,this.#t=4023233417,this.#r=2562383102,this.#o=271733878,this.#n=new Uint8Array(_),this.#i=0,this.#s=0,this.#a=0}#l(o){let t=this.#s;t+=o,t>4294967295&&(this.#a+=1),this.#s=t>>>0}#c(o){let t=this.#e,r=this.#t,n=this.#r,s=this.#o,a=U=>oU|oU+1<<8|oU+2<<16|oU+3<<24,i=(U,ke)=>U<<ke|U>>>32-ke,c=a(0),d=a(4),l=a(8),f=a(12),g=a(16),k=a(20),p=a(24),m=a(28),u=a(32),h=a(36),x=a(40),y=a(44),I=a(48),G=a(52),Y=a(56),V=a(60);t=r+i(((n^s)&r^s)+t+c+3614090360,7),s=t+i(((r^n)&t^n)+s+d+3905402710,12),n=s+i(((t^r)&s^r)+n+l+606105819,17),r=n+i(((s^t)&n^t)+r+f+3250441966,22),t=r+i(((n^s)&r^s)+t+g+4118548399,7),s=t+i(((r^n)&t^n)+s+k+1200080426,12),n=s+i(((t^r)&s^r)+n+p+2821735955,17),r=n+i(((s^t)&n^t)+r+m+4249261313,22),t=r+i(((n^s)&r^s)+t+u+1770035416,7),s=t+i(((r^n)&t^n)+s+h+2336552879,12),n=s+i(((t^r)&s^r)+n+x+4294925233,17),r=n+i(((s^t)&n^t)+r+y+2304563134,22),t=r+i(((n^s)&r^s)+t+I+1804603682,7),s=t+i(((r^n)&t^n)+s+G+4254626195,12),n=s+i(((t^r)&s^r)+n+Y+2792965006,17),r=n+i(((s^t)&n^t)+r+V+1236535329,22),t=r+i(((r^n)&s^n)+t+d+4129170786,5),s=t+i(((t^r)&n^r)+s+p+3225465664,9),n=s+i(((s^t)&r^t)+n+y+643717713,14),r=n+i(((n^s)&t^s)+r+c+3921069994,20),t=r+i(((r^n)&s^n)+t+k+3593408605,5),s=t+i(((t^r)&n^r)+s+x+38016083,9),n=s+i(((s^t)&r^t)+n+V+3634488961,14),r=n+i(((n^s)&t^s)+r+g+3889429448,20),t=r+i(((r^n)&s^n)+t+h+568446438,5),s=t+i(((t^r)&n^r)+s+Y+3275163606,9),n=s+i(((s^t)&r^t)+n+f+4107603335,14),r=n+i(((n^s)&t^s)+r+u+1163531501,20),t=r+i(((r^n)&s^n)+t+G+2850285829,5),s=t+i(((t^r)&n^r)+s+l+4243563512,9),n=s+i(((s^t)&r^t)+n+m+1735328473,14),r=n+i(((n^s)&t^s)+r+I+2368359562,20),t=r+i((r^n^s)+t+k+4294588738,4),s=t+i((t^r^n)+s+u+2272392833,11),n=s+i((s^t^r)+n+y+1839030562,16),r=n+i((n^s^t)+r+Y+4259657740,23),t=r+i((r^n^s)+t+d+2763975236,4),s=t+i((t^r^n)+s+g+1272893353,11),n=s+i((s^t^r)+n+m+4139469664,16),r=n+i((n^s^t)+r+x+3200236656,23),t=r+i((r^n^s)+t+G+681279174,4),s=t+i((t^r^n)+s+c+3936430074,11),n=s+i((s^t^r)+n+f+3572445317,16),r=n+i((n^s^t)+r+p+76029189,23),t=r+i((r^n^s)+t+h+3654602809,4),s=t+i((t^r^n)+s+I+3873151461,11),n=s+i((s^t^r)+n+V+530742520,16),r=n+i((n^s^t)+r+l+3299628645,23),t=r+i((n^(r|~s))+t+c+4096336452,6),s=t+i((r^(t|~n))+s+m+1126891415,10),n=s+i((t^(s|~r))+n+Y+2878612391,15),r=n+i((s^(n|~t))+r+k+4237533241,21),t=r+i((n^(r|~s))+t+I+1700485571,6),s=t+i((r^(t|~n))+s+f+2399980690,10),n=s+i((t^(s|~r))+n+x+4293915773,15),r=n+i((s^(n|~t))+r+d+2240044497,21),t=r+i((n^(r|~s))+t+u+1873313359,6),s=t+i((r^(t|~n))+s+V+4264355552,10),n=s+i((t^(s|~r))+n+p+2734768916,15),r=n+i((s^(n|~t))+r+G+1309151649,21),t=r+i((n^(r|~s))+t+g+4149444226,6),s=t+i((r^(t|~n))+s+y+3174756917,10),n=s+i((t^(s|~r))+n+l+718787259,15),r=n+i((s^(n|~t))+r+h+3951481745,21),this.#e=this.#e+t>>>0,this.#t=this.#t+r>>>0,this.#r=this.#r+n>>>0,this.#o=this.#o+s>>>0}update(o){let t;if(typeof o=="string")t=new TextEncoder().encode(o);else if(typeof o=="object")if(o instanceof ArrayBuffer||ArrayBuffer.isView(o))t=new Uint8Array(o);else throw new TypeError(Ae);else throw new TypeError(Ae);let r=this.#i,n=_-r;if(t.length<n)this.#n.set(t,r),r+=t.length;else{this.#n.set(t.slice(0,n),r),this.#c(this.#n);let s=n;for(;s+_<=t.length;)this.#c(t.slice(s,s+_)),s+=_;this.#n.fill(0).set(t.slice(s),0),r=t.length-s}return this.#i=r,this.#l(t.length),this}digest(){let o=_-this.#i;o<9&&(o+=_);let t=new Uint8Array(o);t0=128;let r=this.#s<<3,n=this.#a<<3|this.#s>>>29;tt.length-8=r&255,tt.length-7=r>>>8&255,tt.length-6=r>>>16&255,tt.length-5=r>>>24&255,tt.length-4=n&255,tt.length-3=n>>>8&255,tt.length-2=n>>>16&255,tt.length-1=n>>>24&255,this.update(t.buffer);let s=new ArrayBuffer(16),a=new DataView(s);return a.setUint32(0,this.#e,!0),a.setUint32(4,this.#t,!0),a.setUint32(8,this.#r,!0),a.setUint32(12,this.#o,!0),s}toString(o="hex"){let t=this.digest();switch(o){case"hex":return new TextDecoder().decode(qe(new Uint8Array(t)));case"base64":{let r=new Uint8Array(t),n="";for(let s=0;s<r.length;++s)n+=String.fromCharCode(rs);return btoa(n)}default:throw new Error("md5: invalid format")}}};var _e=e=>{let o=[],t=new Set,r=n=>{t.delete(n);let s=o.pop();if(!s)return;let a=s0().then(i=>s1(i)).catch(i=>s2(i));t.add(a),a.finally(()=>r(a))};return n=>{if(t.size<e){let s=n();return t.add(s),s.finally(()=>r(s)),s}return new Promise((s,a)=>{o.push(n,s,a)})}};async function*He(e,o,t){let r=_e(5),{fetch:n=globalThis.fetch,...s}=t??{},a=c=>r(()=>n(c)),i=0;for(;;){let c=await ee(e,{...t,limit:1e3,skip:i});if(!c.ok){yieldPromise.resolve(c);return}for(let d of c.value.pages)d.updated<=o||(yield$(e,d.title,{...s,fetch:a}));if((c.value.pages.pop()?.updated??0)<=o)break;i+=1e3}}var $t=e=>({type:"title",text:e.rows0.text}),Ot=e=>{let{rows:o,...t}=e,{indent:r=0,text:n=""}=o??{},s=n.replace(/^\s*code:/,"");return{indent:r,type:"codeBlock",fileName:s,content:t.map(a=>a.text.substring(r+1)).join(` )}},L=(e,{parseOnNested:o,parseOnQuoted:t,patterns:r})=>(n,s,a)=>{var i,c,d,l,f,g;if(!o&&s.nested)return(i=a?.())!==null&&i!==void 0?i:[];if(!t&&s.quoted)return(c=a?.())!==null&&c!==void 0?c:[];for(let k of r){let p=k.exec(n);if(p===null)continue;let m=n.substring(0,p.index),u=n.substring(p.index+((l=(d=p[0])===null||d===void 0?void 0:d.length)!==null&&l!==void 0?l:0)),h=e((f=p[0])!==null&&f!==void 0?f:"",s);return[...D(m,s),...h,...D(u,s)]}return(g=a?.())!==null&&g!==void 0?g:[]},C=e=>[{type:"plain",raw:e,text:e}],jt=L(C,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]}),Bt=/^>.*$/,Dt=(e,o)=>o.context==="table"?C(e,o):[{type:"quote",raw:e,nodes:D(e.substring(1),{...o,quoted:!0})}],Ut=L(Dt,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Bt]}),Ft=/^\? .+$/,qt=(e,o)=>o.context==="table"?C(e,o):[{type:"helpfeel",raw:e,text:e.substring(2)}],At=L(qt,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Ft]}),_t=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)\]\]/i,Ht=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,Gt=(e,o)=>{if(o.context==="table")return C(e,o);let t=e.substring(2,e.length-2),r=/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(t);return[{type:"strongImage",raw:e,src:r?${t}/thumb/1000:t}]},zt=L(Gt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[_t,Ht]}),Kt=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/;function Ge(e){return(o,t)=>{if(e==="strongIcon"&&t.context==="table")return C(o,t);let r=e==="icon"?o.substring(1,o.length-1):o.substring(2,o.length-2),n=r.lastIndexOf(".icon"),s=r.substring(0,n),a=s.startsWith("/")?"root":"relative",i=r.substring(n+5,r.length),c=i.startsWith("*")?parseInt(i.substring(1),10):1;return new Array(c).fill({}).map(()=>({path:s,pathType:a,type:e,raw:o}))}}var Wt=Ge("icon"),Jt=L(Wt,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Kt]}),Qt=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,Xt=Ge("strongIcon"),Zt=L(Xt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Qt]}),Yt=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,Vt=(e,o)=>o.context==="table"?C(e,o):[{type:"strong",raw:e,nodes:D(e.substring(2,e.length-2),{...o,nested:!0})}],er=L(Vt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Yt]}),tr=/\[\$ .+? \]/,rr=/\[\$ [^\]]+\]/,or=(e,o)=>o.context==="table"?C(e,o):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],nr=L(or,{parseOnNested:!1,parseOnQuoted:!0,patterns:[tr,rr]}),sr=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,ir=(e,o)=>{if(o.context==="table")return C(e,o);let t=e.indexOf(" "),r=e.substring(1,t),n=e.substring(t+1,e.length-1),s=new Set(r);if(s.has("*")){let a=r.split("*").length-1;s.delete("*"),s.add(*-${Math.min(a,10)})}return[{type:"decoration",raw:e,rawDecos:r,decos:Array.from(s),nodes:D(n,{...o,nested:!0})}]},ar=L(ir,{parseOnNested:!1,parseOnQuoted:!0,patterns:[sr]}),cr=/.*?/,lr=(e,o)=>o.context==="table"?C(e,o):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],dr=L(lr,{parseOnNested:!1,parseOnQuoted:!0,patterns:[cr]}),pr=/^[$%] .+$/,mr=(e,o)=>{var t;if(o.context==="table")return C(e,o);let r=(t=e[0])!==null&&t!==void 0?t:"",n=e.substring(2);return[{type:"commandLine",raw:e,symbol:r,text:n}]},ur=L(mr,{parseOnNested:!1,parseOnQuoted:!1,patterns:[pr]}),fr=/\[\s+\]/,gr=(e,o)=>o.context==="table"?C(e,o):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],hr=L(gr,{parseOnNested:!1,parseOnQuoted:!0,patterns:[fr]}),xr=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,yr=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?\]/i,kr=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,br=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,wr=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg)(\?[^\]\s]+)?$/i.test(e)||Er(e),Er=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),Tr=(e,o)=>{if(o.context==="table")return C(e,o);let t=e.search(/\s/),r=t!==-1?e.substring(1,t):e.substring(1,e.length-1),n=t!==-1?e.substring(t,e.length-1).trimLeft():"",[s,a]=wr(n)?[n,r]:[r,n];return[{type:"image",raw:e,src:/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(s)?${s}/thumb/1000:s,link:a}]},vr=L(Tr,{parseOnNested:!0,parseOnQuoted:!0,patterns:[xr,yr,kr,br]}),Ir=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,Lr=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,Nr=/\[https?:\/\/[^\s\]]+\]/,Cr=/https?:\/\/[^\s]+/,Pr=(e,o)=>{if(o.context==="table")return C(e,o);let t=e.startsWith("[")&&e.endsWith("]")?e.substring(1,e.length-1):e,r=/^https?:\/\/[^\s\]]/.test(t),n=(r?/^https?:\/\/[^\s\]]+/:/https?:\/\/[^\s\]]+$/).exec(t);if(n?.[0]===void 0)return[];let s=r?t.substring(n[0].length):t.substring(0,n.index-1);return[{type:"link",raw:e,pathType:"absolute",href:n[0],content:s.trim()}]},Sr=L(Pr,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Ir,Lr,Nr,Cr]}),ze=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,Ke=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,Rr=e=>{let[o="",t="",r=""]=e.split(","),n=parseFloat(o.replace(/^N/,"").replace(/^S/,"-")),s=parseFloat(t.replace(/^E/,"").replace(/^W/,"-")),a=/^Z\d+$/.test(r)?parseInt(r.replace(/^Z/,""),10):14;return{latitude:n,longitude:s,zoom:a}},Mr=(e,o)=>{var t;if(o.context==="table")return C(e,o);let r=(t=e.match(ze))!==null&&t!==void 0?t:e.match(Ke);if(r===null)return[];let n=e.startsWith("[N")||e.startsWith("[S"),[,s="",a=""]=n?r:[r[0],r[2],r[1]],{latitude:i,longitude:c,zoom:d}=Rr(s),l=a!==""?https://www.google.com/maps/place/${encodeURIComponent(a)}/@${i},${c},${d}z:https://www.google.com/maps/@${i},${c},${d}z;return[{type:"googleMap",raw:e,latitude:i,longitude:c,zoom:d,place:a,url:l}]},$r=L(Mr,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ze,Ke]}),Or=/\[\/?[^[\]]+\]/,jr=e=>{let o=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:o.startsWith("/")?"root":"relative",href:o,content:""}]},Br=L(jr,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Or]}),Dr=/(?:^|\s)#\S+/,Ur=(e,o)=>{if(o.context==="table")return C(e,o);if(e.startsWith("#"))return[{type:"hashTag",raw:e,href:e.substring(1)}];let t=e.substring(0,1),r=e.substring(1);return[...C(t,o),{type:"hashTag",raw:r,href:r.substring(1)}]},Fr=L(Ur,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Dr]}),qr=/^[0-9]+\. .*$/,Ar=(e,o)=>{if(o.context==="table")return C(e,o);let t=e.indexOf(" "),r=e.substring(0,t-1),n=parseInt(r,10),s=e.substring(t+1,e.length);return[{type:"numberList",raw:e,rawNumber:r,number:n,nodes:D(s,{...o,nested:!0})}]},_r=L(Ar,{parseOnNested:!1,parseOnQuoted:!1,patterns:[qr]}),Hr=(e,o,t)=>{var r;return e===""?[]:(r=t?.())!==null&&r!==void 0?r:[]},Gr=(...e)=>(o,t)=>e.reduceRight((r,n)=>()=>n(o,t,r),()=>jt(o,t))(),D=Gr(Hr,Ut,At,dr,ur,nr,hr,ar,zt,Zt,er,vr,Sr,Jt,$r,Br,Fr,_r),zr=e=>{let{rows:[o,...t]}=e,{indent:r=0,text:n=""}=o??{},s=n.replace(/^\s*table:/,"");return{indent:r,type:"table",fileName:s,cells:t.map(a=>a.text.substring(r+1)).map(a=>a.split(" ").map(i=>D(i,{nested:!1,quoted:!1,context:"table"})))}},Kr=e=>{let{indent:o,text:t}=e.rows[0];return{indent:o,type:"line",nodes:D(t.substring(o),{nested:!1,quoted:!1,context:"line"})}},M=e=>{switch(e.type){case"title":return $t(e);case"codeBlock":return Ot(e);case"table":return zr(e);case"line":return Kr(e)}},j=e=>e.split( ).map(o=>{var t,r,n;return{indent:(n=(r=(t=/^\s+/.exec(o))===null||t===void 0?void 0:t[0])===null||r===void 0?void 0:r.length)!==null&&n!==void 0?n:0,text:o}}),Wr=(e,o)=>{var t,r;return(e.type==="codeBlock"||e.type==="table")&&o.indent>((r=(t=e.rows[0])===null||t===void 0?void 0:t.indent)!==null&&r!==void 0?r:0)},We=(e,o)=>{let t=e[e.length-1];return t!==void 0&&Wr(t,o)?(t.rows.push(o),e):(e.push({type:/^\s*code:/.test(o.text)?"codeBlock":/^\s*table:/.test(o.text)?"table":"line",rows:[o]}),e)},B=(e,o)=>{var t;if(!((t=o.hasTitle)!==null&&t!==void 0)||t){let[r,...n]=e;return r===void 0?[]:[{type:"title",rows:[r]},...n.reduce(We,[])]}return e.reduce(We,[])},Je=(e,o)=>{var t;let r=j(e);return B(r,{hasTitle:(t=o?.hasTitle)!==null&&t!==void 0?t:!0}).map(M)};var Qe=e=>{if(!e.includes(".note"))return;let[,o,t]=e.match(/^(.+)\(([^()]+)\)$/)??[,e],r=o.match(/^(.+?)\.note(?:|\.(.+))$/);if(!r)return;let[,n,s=""]=r;return{guid:n,name:s,isScrapboxSyntax:!t}};var K=(e,o)=>{let[,t,r]=e.match(/^\/([\w\-]+)\/(.+)$/)??[];return t&&r?{project:t,title:r}:{project:o,title:e}};var Jr={"&":"&","<":"<",">":">",'"':""","'":"'"},v=e=>e.replace(/[&<>"']/g,o=>Jr[o]);var w=" ",Xe=(e,o,t)=>{let r=Math.min(...e.map(a=>a.indent)),n=0,s=[];for(let a=0;a<e.length;a++){let i=e[a],c=i.indent-r;for(let l=n;l>c;l--)s.push(${w.repeat(l-1)}</ul>);for(let l=n;l<c;l++)s.push(${w.repeat(l)}<ul class="level-${l+1}">);let d=w.repeat(c);switch(i.type){case"codeBlock":s.push(c===0?Ze(i):${d}<li>
${Ze(i).split(`
).map(l=>${d}${w}${l}).join(
`)}
${d}</li>);break;case"table":s.push(c===0?Ye(i,o,t):${d}<li>
${Ye(i,o,t).split(`
).map(l=>${d}${w}${l}).join(
`)}
${d}</li>);break;case"line":{let l=i.nodes.map(f=>W(f,o,t)).join("");s.push(c===0?${l}${a+1===e.length?"":"<br/>"}:${d}<li>${l}</li>)}break}n=c}for(let a=n;a>0;a--)s.push(${w.repeat(a-1)}</ul>);return s.join(
)},Ze=e=><figure class="codeBlock">
${w}<figcaption><code>${v(e.fileName)}</code></figcaption>
${w}<pre><code>${v(e.content)}</code></pre>
</figure>,Ye=(e,o,t)=>{let[r,...n]=e.cells.map(s=>s.map(a=>a.map(i=>W(i,o,t)).join("")));return<table class="table">
${w}<caption>${v(e.fileName)}</caption>
${w}<thead>
${w}${w}<tr>
${r?.map?.(s=>${w.repeat(3)}<th>${s}</th>)?.join?.(`
`)??""}
${w}${w}</tr>
${w}</thead>
${w}<tbody>
${n?.map?.(s=>`${w}${w}<tr>
${s.map(a=>${w.repeat(3)}<td>${a}</td>).join(`
`)}
${w}${w}</tr>)?.join?.(
`)}
${w}</tbody>
</table>},W=(e,o,t)=>{switch(e.type){case"quote":return<span class="quote">${e.nodes.map(r=>W(r,o,t)).join("")}</span>;case"image":case"strongImage":{let r=<img class="image" src="${v(e.src)}" />;return e.type==="image"?r:<strong>${r}</strong>}case"strongIcon":case"icon":{let r=K(e.path,o),n=https://scrapbox.io/api/pages/${r.project}/${r.title}/icon,s=https://scrapbox.io/${r.project}/${r.title},a=e.path,i=<a class="icon" target="_blank" href="${v(s)}"><img src="${v(n)}" alt="${v(a)}" /></a>;return e.type==="icon"?i:<strong>${i}</strong>}case"formula":return\\( ${v(e.formula)} \\);case"decoration":{let r=e.nodes.map(n=>W(n,o,t)).join("");return e.decos.length===0?r:<span class="${e.decos.map(n=>deco-${v(n)}).join(" ")}">${r}</span>}case"strong":return<strong>${e.nodes.map(r=>W(r,o,t)).join("")}</strong>;case"code":return<code class="code">${v(e.text)}</code>;case"commandLine":return<code class="cli">${e.symbol} ${v(e.text)}</code>;case"helpfeel":return<code class="helpfeel">? ${v(e.text)}</code>;case"googleMap":return<a class="google-map" href="https://www.google.com/maps/search/${e.place}/@${e.latitude},${e.longitude},${e.zoom}z">N${e.latitude},E${e.longitude},Z${e.zoom} ${e.place}</a>;case"link":switch(e.pathType){case"relative":case"root":{let r=K(e.href,o),n=https://scrapbox.io/${r.project}/${v(P(r.title))};return<a class="page-link" target="_blank" href="${v(n)}">${v(e.href)}</a>}default:return<a class="link" target="_blank" href="${v(e.href)}">${v(e.content||e.href)}</a>}case"hashTag":return t(e.href),"";case"numberList":return${e.number}. ${e.nodes.map(r=>W(r,o,t)).join("")};case"blank":return e.text;case"plain":return v(e.text)}};var Ve=(e,o,t)=>{if(t.length===0)return[];let r=B(j(t.map(c=>c.text).join( )),{hasTitle:!0}),n=new Map,s,a,i=0;for(let c of r)switch(c.type){case"title":i++;break;case"table":case"line":{if(i+=c.rows.length,s&&a)break;let d=M(c),l=Qr(d);for(let f of l)f.toLowerCase().startsWith("deck-")&&(s??=K(f,e)),f.toLowerCase().startsWith("notetype-")&&(a??=K(f,e));break}case"codeBlock":{i+=c.rows.length;let d=M(c);if(d.type!=="codeBlock")throw SyntaxError();let l=Qe(d.fileName);if(!l)break;let{guid:f,name:g,isScrapboxSyntax:k}=l,p=n.get(f)??{guid:f,id:1/0,updated:-1/0,fields:new Map([["SourceURL",[!1,https://scrapbox.io/${e}/${P(o)}#${t[i].id}]]])};p.id=Math.min(...t.slice(i,i+c.rows.length).map(h=>h.created*1e3),p.id),p.updated=Math.max(...t.slice(i,i+c.rows.length).map(h=>h.updated*1e3),p.updated);let[m,u]=p.fields.get(g)??[!0,""];p.fields.set(g,[m&&k,u?${u} ${d.content}:d.content]),n.set(f,p);break}}return[...n.values()].map(({fields:c,...d})=>{let l=[],f=new Set,g=p=>{let m=S(p);f.has(m)||(f.add(m),l.push(p))},k=new Map;g(e),g(o);for(let[p,[m,u]]of c.entries()){if(!m){k.set(p,u);continue}let h=Xe(Je(u,{hasTitle:!1}),e,g);k.set(p,h)}return{...d,deck:s,noteType:a,fields:k,tags:l}})},Qr=e=>{switch(e.type){case"line":return e.nodes.flatMap(o=>pe(o));case"table":return e.cells.flatMap(o=>o.flatMap(t=>t.flatMap(r=>pe(r))));default:return[]}},pe=e=>{switch(e.type){case"icon":case"strongIcon":return[e.path];case"decoration":case"quote":return e.nodes.flatMap(o=>pe(o));default:return[]}};var et=e=>{if(e.lines.length===0)return{ok:!1,value:{name:"DeckNotFoundError",message:"This is an empty page so no deck is found."}};let o=B(j(e.lines.map(s=>s.text).join(
)),{hasTitle:!0}),t="",r=0,n="deck.json";for(let s of o)switch(s.type){case"title":case"line":r++;break;case"table":r+=s.rows.length;break;case"codeBlock":{r+=s.rows.length;let a=M(s);if(a.type!=="codeBlock")throw Error("Must be a codeblock");if(!a.fileName.endsWith(n))break;t+=
${a.content};break}}if(t.trim()==="")return{ok:!1,value:{name:"DeckNotFoundError",message:"No deck settings found in the page."}};try{let s=JSON.parse(t);return typeof s!="object"||s==null?{ok:!1,value:J("Deck setting must be an object.")}:"name"in s?typeof s.name!="string"?{ok:!1,value:J("Deck name must be string.")}:"id"in s?typeof s.id!="number"?{ok:!1,value:J("Deck id must be number.")}:"description"in s&&typeof s.description!="string"?{ok:!1,value:J("Deck description must be string.")}:{ok:!0,value:{id:s.id,name:s.name,updated:e.updated,..."description"in s?{description:s.description}:{}}}:{ok:!1,value:J("Deck id not found.")}:{ok:!1,value:J("Deck name is not found.")}}catch(s){if(s instanceof SyntaxError)return{ok:!1,value:{name:"DeckSyntaxError",message:s.message}};throw s}},J=e=>({name:"InvalidDeckError",message:e});var me=[{name:"SourceURL",description:"問題の取得元URL"}],tt=e=>{if(e.lines.length===0)return{ok:!1,value:{name:"NoteTypeNotFoundError",message:"This is an empty page so no note type is found."}};let o=B(j(e.lines.map(p=>p.text).join(
)),{hasTitle:!0}),t=0,r="noteType.json",n="",s="css",a="",i="pre.tex",c="",d="post.tex",l="",f=".question.html",g=".answer.html",k=new Map;for(let p of o)switch(p.type){case"title":case"line":t++;break;case"table":t+=p.rows.length;break;case"codeBlock":{t+=p.rows.length;let m=M(p);if(m.type!=="codeBlock")throw Error("Must be a codeblock");let u=
${m.content};switch(m.fileName){case r:n+=u;break;case s:a+=u;break;case i:c+=u;break;case d:l+=u;break;default:{if(m.fileName.endsWith(f)){let h=[...m.fileName].slice(0,-f.length).join(""),x=k.get(h)??["",""];x[0]+=u,k.set(h,x);break}if(m.fileName.endsWith(g)){let h=[...m.fileName].slice(0,-g.length).join(""),x=k.get(h)??["",""];x[1]+=u,k.set(h,x);break}break}}break}}if(n.trim()==="")return{ok:!1,value:{name:"NoteTypeNotFoundError",message:"No note type settings found in the page."}};try{let p=JSON.parse(n);if(typeof p!="object"||p==null)return{ok:!1,value:N("Note type setting must be an object.")};if(!("name"in p))return{ok:!1,value:N("Note type name is not found.")};if(typeof p.name!="string")return{ok:!1,value:N("Note type name must be string.")};if(!("id"in p))return{ok:!1,value:N("Note type id not found.")};if(typeof p.id!="number")return{ok:!1,value:N("Note type id must be number.")};if(!("fields"in p))return{ok:!1,value:N("Note type must have fields.")};if(!Array.isArray(p.fields))return{ok:!1,value:N("fields must be an array.")};let m=[];for(let x of p.fields){let y=x;switch(typeof y){case"string":if(me.some(({name:I})=>y===I))break;m.push({name:y});break;case"object":{if(y==null||!("name"in y))return{ok:!1,value:N("Each field object must have name.")};if(typeof y.name!="string")return{ok:!1,value:N("The name of a field must be a string.")};if(me.some(({name:G})=>y.name===G))break;let I={name:y.name};if("description"in y){if(typeof y.description!="string")return{ok:!1,value:N("The description of a field must be a string.")};I.description=y.description}if("rtl"in y){if(typeof y.rtl!="boolean")return{ok:!1,value:N("The rtl of a field must be a boolean.")};I.rtl=y.rtl}if("font"in y){if(typeof y.font!="string")return{ok:!1,value:N("The font of a field must be a string.")};I.font=y.font}if("fontSize"in y){if(typeof y.fontSize!="number")return{ok:!1,value:N("The fontSize of a field must be a number.")};I.fontSize=y.fontSize}m.push(I);break}default:return{ok:!1,value:N("Members of fields must be a string or an object.")}}}m.push(...me);let u=[];if(k.size===0)return{ok:!1,value:N("Note type must have one or more template.")};for(let[x,[y,I]]of k.entries()){if(y.trim()==="")return{ok:!1,value:N("${x}${f}" is empty.)};if(I.trim()==="")return{ok:!1,value:N("${x}${g}" is empty.)};u.push({name:x,question:y,answer:I})}let h={name:p.name,id:p.id,updated:e.updated,fields:m,templates:u};if(a.trim()!==""&&(h.css=a),c.trim()!==""&&l.trim()!==""&&(h.latex=[c,l]),"isCloze"in p){if(typeof p.isCloze!="boolean")return{ok:!1,value:N("isCloze must be number.")};h.isCloze=p.isCloze}return{ok:!0,value:h}}catch(p){if(p instanceof SyntaxError)return{ok:!1,value:{name:"NoteTypeSyntaxError",message:p.message}};throw p}},N=e=>({name:"InvalidNoteTypeError",message:e});var rt=new Map,Xr=e=>{let o=rt.get(H(e));if(o)return o;let t=(async()=>{let r=await $(e.project,e.title);return r.ok?et(r.value):r})();return rt.set(H(e),t),t},ot=new Map,Zr=e=>{let o=ot.get(H(e));if(o)return o;let t=(async()=>{let r=await $(e.project,e.title);return r.ok?tt(r.value):r})();return ot.set(H(e),t),t},nt=async(e,o)=>{let t=new Map,r=new Map,n=[];for(let s of o){let a=H({project:e,title:s.title}),i=t.get(a)??{deckNotSpecified:!1,noteTypeNotSpecified:!1,skipped:0},c=Ve(e,s.title,s.lines);for(let d=0;d<c.length;d++){let l=c[d];if(!l.deck||!l.noteType){l.deck||(console.warn(Deck is not specified in ${a}),i.deckNotSpecified=!0),l.noteType||(console.warn(Note type is not specified in ${a}),i.noteTypeNotSpecified=!0),i.skipped=c.length-d;break}let f=await Xr(l.deck);if(!f.ok){console.warn(${f.value.name} ${f.value.message}),r.set(H(l.deck),f.value),i.skipped=c.length-d;break}let g=f.value,k=await Zr(l.noteType);if(!k.ok){console.warn(${k.value.name} ${k.value.message}),r.set(H(l.noteType),k.value),i.skipped=c.length-d;break}let p=k.value,m=p.fields.map((u,h)=>{let x=typeof u=="string"?u:u.name,y=l.fields.get(x);return h===0?y??l.fields.get("")??"":y??""});n.push({guid:l.guid,id:l.id,updated:l.updated,tags:l.tags,fields:m,deck:g,noteType:p})}(i.deckNotSpecified||i.noteTypeNotSpecified||i.skipped>0)&&t.set(a,i)}return{notes:n,warnings:t,errors:r}},H=e=>/${e.project}/${e.title};var st=(e,o)=>{let t=new o.Database,r={activeDecks:[1],addToCur:!0,collapseTime:1200,curDeck:1,curModel:"1435645724216",dueCounts:!0,estTimes:!0,newBury:!0,newSpread:0,nextPos:1,sortBackwards:!1,sortType:"noteFld",timeLim:0},n={},s=new Map;{let p=ie();p(1),n[1]={collapsed:!1,conf:1,desc:"",dyn:0,extendNew:10,extendRev:50,id:1,lrnToday:[0,0],mod:0,name:"Default",newToday:[0,0],revToday:[0,0],timeToday:[0,0],usn:0};let m=new Set(e.flatMap(u=>u.noteType.deck?[u.deck,u.noteType.deck]:[u.deck]));for(let u of m){let h=io(u,p);n[h.id]=h,s.set(u,h.id)}}let a={},i=new Map;{let p=ie(),m=new Set(e.map(u=>u.noteType));for(let u of m){let h=u.deck?s.get(u.deck):void 0,x=oo(u,h,p);a[x.id]=x,i.set(u,x.id)}}let c={},d={};{let p=ie(),m=ie();for(let u of e){let h=i.get(u.noteType);if(h===void 0)throw Error("Note type id must be already generated");let x=s.get(u.deck);if(x===void 0)throw Error("Deck id must be already generated");let y=Vr(u,h,m);c[y.id]=y;for(let I of eo(u,x,y.id,p))d[I.id]=I}}let l={1:{autoplay:!0,id:1,lapse:{delays:[10],leechAction:0,leechFails:8,minInt:1,mult:0},maxTaken:60,mod:0,name:"Default",new:{bury:!0,delays:[1,10],initialFactor:2500,ints:[1,4,7],order:1,perDay:20,separate:!0},replayq:!0,rev:{bury:!0,ease4:1.3,fuzz:.05,ivlFct:1,maxIvl:36500,minSpace:1,perDay:100},timer:0,usn:0}},f=
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE col (
id integer primary key,
crt integer not null,
mod integer not null,
scm integer not null,
ver integer not null,
dty integer not null,
usn integer not null,
ls integer not null,
conf text not null,
models text not null,
decks text not null,
dconf text not null,
tags text not null
);
INSERT INTO "col" VALUES(
1,
1388548800,
1435645724219,
1435645724215,
11,
0,
0,
0,
'${JSON.stringify(r)}',
'${JSON.stringify(a)}',
'${JSON.stringify(n)}',
'${JSON.stringify(l)}',
'{}'
);
CREATE TABLE notes (
id integer primary key, /* 0 */
guid text not null, /* 1 */
mid integer not null, /* 2 */
mod integer not null, /* 3 */
usn integer not null, /* 4 */
tags text not null, /* 5 */
flds text not null, /* 6 */
sfld integer not null, /* 7 */
csum integer not null, /* 8 */
flags integer not null, /* 9 */
data text not null /* 10 */
);
CREATE TABLE cards (
id integer primary key, /* 0 */
nid integer not null, /* 1 */
did integer not null, /* 2 */
ord integer not null, /* 3 */
mod integer not null, /* 4 */
usn integer not null, /* 5 */
type integer not null, /* 6 */
queue integer not null, /* 7 */
due integer not null, /* 8 */
ivl integer not null, /* 9 */
factor integer not null, /* 10 */
reps integer not null, /* 11 */
lapses integer not null, /* 12 */
left integer not null, /* 13 */
odue integer not null, /* 14 */
odid integer not null, /* 15 */
flags integer not null, /* 16 */
data text not null /* 17 */
);
CREATE TABLE revlog (
id integer primary key,
cid integer not null,
usn integer not null,
ease integer not null,
ivl integer not null,
lastIvl integer not null,
factor integer not null,
time integer not null,
type integer not null
);
CREATE TABLE graves (
usn integer not null,
oid integer not null,
type integer not null
);
ANALYZE sqlite_master;
INSERT INTO "sqlite_stat1" VALUES('col',NULL,'1');
CREATE INDEX ix_notes_usn on notes (usn);
CREATE INDEX ix_cards_usn on cards (usn);
CREATE INDEX ix_revlog_usn on revlog (usn);
CREATE INDEX ix_cards_nid on cards (nid);
CREATE INDEX ix_cards_sched on cards (did, queue, due);
CREATE INDEX ix_revlog_cid on revlog (cid);
CREATE INDEX ix_notes_csum on notes (csum);
COMMIT;
;t.run(f);let g=t.prepare("insert or replace into notes values(:id,:guid,:mid,:mod,:usn,:tags,:flds,:sfld,:csum,:flags,:data)");for(let p of Object.values(c))g.run(Object.fromEntries([...Object.entries(p)].map(([m,u])=>[:${m},u])));let k=t.prepare("insert or replace into cards values(:id,:nid,:did,:ord,:mod,:usn,:type,:queue,:due,:ivl,:factor,:reps,:lapses,:left,:odue,:odid,:flags,:data)");for(let p of Object.values(d))k.run(Object.fromEntries([...Object.entries(p)].map(([m,u])=>[:${m},u])));return t.export()},it=(e,o,t,r)=>{let n=new t;n.file("collection.anki2",e);let s=[...o instanceof Map?o.entries():Object.entries(o)],a=Object.fromEntries(s.map(([i],c)=>[c,i]));return n.file("media",JSON.stringify(a)),s.forEach(([,i],c)=>n.file(${c},i)),n.generateAsync({type:"blob",...r})},Yr="",Vr=(e,o,t)=>{let r=e.fields.join(Yr);return{id:t(e.id),guid:e.guid??ao(),tags:e.tags?.map?.(n=>n.replaceAll(" ","_"))?.join?.(" ")??"",mid:o,mod:e.updated??e.id,flds:r,sfld:r,usn:-1,flags:0,data:"",csum:0}},eo=(e,o,t,r)=>e.noteType.isCloze?ro(e,o,t,r):to(e,o,t,r),to=(e,o,t,r)=>{let n=e.noteType.fields.map(s=>typeof s=="string"?s:s.name);return e.noteType.templates.flatMap((s,a)=>{for(let[,i]of s.question.matchAll(/{{(?:type\:|hint\:|#|\/)?([^}]+)}}/g)){let c=n.indexOf(i);if(!(c<0)&&!e.fields[c])return[]}return[at({ord:a,noteId:t,deckId:o,created:t},r)]})},ro=(e,o,t,r)=>{let n=e.noteType.templates[0].question,s=new Set([...n.matchAll(/{{[^}]*?cloze:(?:[^}]?:)*(.+?)}}/g),...n.matchAll(/<%cloze:(.+?)%>/g)].map(([i,c])=>c)),a=new Set([...s].flatMap(i=>{let c=e.noteType.fields.findIndex(f=>(typeof f=="string"?f:f.name)===i);return[...(c<0?"":e.fields[c]).matchAll(/{{c(\d+)::.+?}}/g)].map(([f,g])=>parseInt(g)).flatMap(f=>f>=1?[f-1]:[])}));return a.size===0&&a.add(0),[...a].map(i=>at({ord:i,noteId:t,deckId:o,created:t},r))},at=(e,o)=>({ord:e.ord,id:o(e.created),nid:e.noteId,did:e.deckId,mod:e.updated??Math.round(e.created/1e3),usn:-1,type:0,queue:0,due:0,ivl:0,factor:0,reps:0,lapses:0,left:0,odue:0,odid:0,flags:0,data:""}),oo=(e,o,t)=>({vers:[],name:e.name,tags:[],did:o??1,usn:-1,req:[[0,"all",[0]]],flds:e.fields.map((r,n)=>no(r,n)),sortf:0,latexPre:e.latex?.[0]??\\documentclass12pt{article} \\special{papersize=3in,5in}
\\usepackageutf8{inputenc} \\usepackage{amssymb,amsmath}
\\pagestyle{empty}
\\setlength{\\parindent}{0in}
\\begin{document}
,tmpls:e.templates.map((r,n)=>so(r,n)),latexPost:e.latex?.[1]??"\\end{document}",type:e.isCloze?1:0,id:t(e.id),css:e.css??.card {
font-family: arial;
font-size: 20px;
text-align: center;
color: black;
background-color: white;
}
,mod:e.updated??Math.round(e.id/1e3)}),no=(e,o)=>typeof e=="string"?{name:e,description:"",media:[],sticky:!1,rtl:!1,ord:o,font:"Arial",size:20}:{name:e.name,description:e.description??"",media:[],sticky:!1,rtl:e.rtl??!1,ord:o,font:e.font??"Arial",size:e.fontSize??20},so=(e,o)=>({name:e.name,ord:o,did:null,qfmt:e.question,bafmt:e.example?.[0]??"",afmt:e.answer,bqfmt:e.example?.[1]??""}),io=(e,o)=>({collapsed:!1,conf:1,desc:e.description??"",dyn:0,extendNew:10,extendRev:50,id:o(e.id),lrnToday:[545,0],mod:e.updated??Math.round(e.id/1e3),name:e.name,newToday:[545,0],revToday:[545,0],timeToday:[545,0],usn:-1}),ie=()=>{let e=-1;return o=>e<o?(e=o,o):++e},ue="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&()*+,-./:;<=>?@[]^_{|}~",ao=()=>{let e=Math.floor(Math.random()*Number.MAX_SAFE_INTEGER),o="";for(;e>0;){let t=Math.floor(e/ue.length),r=e%ue.length;o+=uer,e=t}return o.split("").reverse().join("")};var ct=async(e,o,t)=>{let{notes:r,warnings:n,errors:s}=await nt(e,o);if(n.size>0||s.size>0){let a=[There are ${n.size} warnings and ${s.size} errors.,"","Warnings:"," (page), (has deck?), (has note type?), (skipped)",......n.entries().map((i,c)=>[ ${i},c.deckNotSpecified?"x":"o",c.noteTypeNotSpecified?"x":"o",c.skipped].join(` )),"","Errors",...[...s.entries()].map(([i,c])=> ${i} ${c.name}: ${c.message}),"","Do you want to create .apkg?"];if(!globalThis.confirm(a.join(
)))return}return it(st(r,t.sql),{},t.JSZip)};var lt=!1;scrapbox.addListener("lines:changed",()=>lt=!1);scrapbox.addListener("layout:changed",()=>lt=!1);var dt=(e,o)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${o}" must be HTMLDivElememt but actual is "${e}")};var pt=()=>co(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),co=(e,o)=>{if(!!e)return dt(e,o),e};var ut=()=>{let e=pt();if(!e)throw new Error("div.status-bar can't be found");let o=document.createElement("div");return e.append(o),{render:(...t)=>{o.textContent="";let r=ft(...t);r&&o.append(r)},dispose:()=>o.remove()}},ft=(...e)=>{let o=e.flatMap(r=>{switch(r.type){case"spinner":return[ho()];case"check-circle":return[xo()];case"exclamation-triangle":return[yo()];case"text":return[ae(r.text)];case"group":{let n=ft(...r.items);return n?[n]:[]}}});if(o.length===0)return;if(o.length===1)return o[0];let t=document.createElement("span");return t.classList.add("item-group"),t.append(...o),t},ae=e=>{let o=document.createElement("span");return o.classList.add("item"),o.append(e),o},ho=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),ae(e)},xo=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),ae(e)},yo=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),ae(e)};var X=async e=>{if(e.connected)return;let o=new Promise(t=>e.once("connect",()=>t()));e.connect(),await o},Z=async e=>{if(e.disconnected)return;let o=new Promise(t=>{let r=n=>{n==="io client disconnect"&&(t(),e.off("disconnect",r))};e.on("disconnect",r)});e.disconnect(),await o};var ge=(e,o)=>{let t=e.length>o.length,r=t?o:e,n=t?e:o,s=r.length+1,a=r.length+n.length+3,i=new Array(a);i.fill(-1);let c=[];function d(m,u,h){let x=Math.max(u,h),y=x-m;for(;y<r.length&&x<n.length&&r[y]===n[x];)++y,++x;return i[m+s]=c.length,c.push([{x:y,y:x},i[m+(u>h?-1:1)+s]]),x}let l=new Array(a);l.fill(-1);let f=-1,g=n.length-r.length;do{++f;for(let m=-f;m<=g-1;++m)l[m+s]=d(m,l[m-1+s]+1,l[m+1+s]);for(let m=g+f;m>=g+1;--m)l[m+s]=d(m,l[m-1+s]+1,l[m+1+s]);l[g+s]=d(g,l[g-1+s]+1,l[g+1+s])}while(l[g+s]!==n.length);let k=[],p=i[g+s];for(;p!==-1;)k.push(c[p][0]),p=c[p][1];return{from:e,to:o,editDistance:g+f*2,buildSES:function*(){let m=0,u=0;for(let{x:h,y:x}of bo(k))for(;m<h||u<x;)x-h>u-m?(yield{value:n[u],type:t?"deleted":"added"},++u):x-h<u-m?(yield{value:r[m],type:t?"added":"deleted"},++m):(yield{value:r[m],type:"common"},++m,++u)}}};function*he(e){let o=[],t=[];function*r(){if(o.length>t.length){for(let n=0;n<t.length;n++)yield gt(o[n],t[n]);for(let n=t.length;n<o.length;n++)yield o[n]}else{for(let n=0;n<o.length;n++)yield gt(o[n],t[n]);for(let n=o.length;n<t.length;n++)yield t[n]}o=[],t=[]}for(let n of e)switch(n.type){case"added":o.push(n);break;case"deleted":t.push(n);break;case"common":yield*r(),yield n;break}yield*r()}var gt=(e,o)=>({value:e.value,oldValue:o.value,type:"replaced"});function*bo(e){for(let o=e.length-1;o>=0;o--)yield e[o]}function*xe(e,o,{userId:t}){let{buildSES:r}=ge(e.map(({text:a})=>a),o),n=0,s=e[0].id;for(let a of he(r())){switch(a.type){case"added":yield{_insert:s,lines:{id:le(t),text:a.value}};continue;case"deleted":yield{_delete:s,lines:-1};break;case"replaced":yield{_update:s,lines:{text:a.value}};break}n++,s=e[n]?.id??"_end"}}var wo=/https?:\/\/(?:www\.|music\.|)youtube\.com\/watch/,Eo=/https?:\/\/youtu\.be\/([a-zA-Z\d_-]+)(?:\?([^\s]{0,100})|)/,To=/https?:\/\/(?:www\.|)youtube\.com\/shorts\/([a-zA-Z\d_-]+)(?:\?([^\s]+)|)/,vo=/https?:\/\/(?:www\.|music\.|)youtube\.com\/playlist\?((?:[^\s]+&|)list=([a-zA-Z\d_-]+)(?:&[^\s]+|))/,ht=e=>{if(wo.test(e)){let o=new URL(e).searchParams,t=o.get("v");if(t)return{pathType:"com",videoId:t,params:o}}{let o=e.match(Eo);if(o){let[,t,r]=o;return{videoId:t,params:new URLSearchParams(r),pathType:"dotbe"}}}{let o=e.match(To);if(o){let[,t,r]=o;return{videoId:t,params:new URLSearchParams(r),pathType:"short"}}}{let o=e.match(vo);if(o){let[,t,r]=o;return{listId:r,params:new URLSearchParams(t),pathType:"list"}}}};function*xt(e,o,{userId:t,head:r}){let n=o.flatMap(l=>l.split(
));for(let l of xe(e,n,{userId:t}))yield l;(e[0].text!==n[0]||!r.persistent)&&(yield{title:n[0]});let s=e.slice(1,6).map(l=>l.text),a=n.slice(1,6);s.join("")!==a.join("")&&(yield{descriptions:a});let[i,c,d]=Io(n.join(
));(r.links.length!==i.length||!r.links.every(l=>i.includes(l)))&&(yield{links:i}),(r.projectLinks.length!==c.length||!r.projectLinks.every(l=>c.includes(l)))&&(yield{projectLinks:c}),r.image!==d&&(yield{image:d})}var Io=e=>{let o=j(e),t=B(o,{hasTitle:!0}).flatMap(d=>{switch(d.type){case"codeBlock":case"title":return[];case"line":case"table":return[M(d)]}}),r=new Map,n=[],s=new Set,a=[],i=null,c=d=>{switch(d.type){case"hashTag":if(r.has(S(d.href)))return;r.set(S(d.href),!1),n.push(d.href);return;case"link":switch(d.pathType){case"relative":{let l=yt(d.href);if(r.get(S(l)))return;r.set(S(l),!0),n.push(l);return}case"root":{let l=yt(d.href);if(/^\/[\w\d-]+\/?$/.test(l)||s.has(S(l)))return;s.add(S(l)),a.push(l);return}case"absolute":{let l=ht(d.href);if(!l||l.pathType==="list")return;i??=https://i.ytimg.com/vi/${l.videoId}/mqdefault.jpg;return}default:return}case"image":case"strongImage":{i??=d.src.endsWith("/thumb/1000")?d.src.replace(/\/thumb\/1000$/,"/raw"):d.src;return}case"strong":case"quote":case"decoration":{for(let l of d.nodes)c(l);return}default:return}};for(let d of Lo(t))c(d);return[n,a,i]};function*Lo(e){for(let o of e)switch(o.type){case"codeBlock":case"title":continue;case"line":for(let t of o.nodes)yield t;continue;case"table":{for(let t of o.cells)for(let r of t)for(let n of r)yield n;continue}}}var yt=e=>e.replace(/#[a-f\d]{24,32}$/,"");var kt=async(e,o,t,r)=>{let[n,s,a]=await Promise.all([R(e,o),z(e),A()]),i=n,c=r?.socket,d=c??await O();await X(d);try{let{request:l}=q(d);for(let f=0;f<3;f++)try{let g=t(i.lines,i),k=g instanceof Promise?await g:g;if(!k)return;k.length===0&&await Q(l,[{deleted:!0}],{projectId:s,pageId:i.pageId,parentId:i.commitId,userId:a,project:e,title:o});let p=[...xt(i.lines,k,{userId:a,head:i})];await ne(l,p,{parentId:i.commitId,projectId:s,pageId:i.pageId,userId:a});break}catch{if(f===2)throw Error("Faild to retry pushing.");console.log("Faild to push a commit. Retry after pulling new commits");try{i=await R(e,o)}catch(k){throw k}}}finally{c||await Z(d)}};await(async()=>{if(!scrapbox)return;let{sql:e}=await Tt().then(()=>Et),o=".ankirc",t=scrapbox.Project.name,r=async()=>{let p=await se(t,o,"json");if(!p.ok)return 0;try{let m=JSON.parse(p.value);return typeof m.checked!="number"?0:m.checked}catch(m){if(!(m instanceof SyntaxError))throw m;return 0}},n=p=>kt(t,o,()=>[o,"This page is automatically generated. DO NOT EDIT ANYTHING, WHITCH WILL BE OVERWRITTEN.","","code:json", ${JSON.stringify({checked:p})}]),s=await r(),a=Math.floor(new Date().getTime()/1e3),i=[],c=[],d=!1,{render:l,dispose:f}=ut(),g,k=()=>{g!==void 0&&cancelAnimationFrame(g),g=requestAnimationFrame(()=>{l({type:"spinner"},{type:"text",text:loading ${i.length} pages updated after ${new Date(s*1e3)}})})};try{for await(let[h]of He(t,s)){if(d)break;c.push(h.then(x=>{if(!x.ok){console.error(x.value),alert(${x.value.name} ${x.value.message}),d=!0;return}i.push(x.value),k()}))}await Promise.all(c);let p=await ct(t,i,{JSZip,sql:e});if(!p)return;l({type:"spinner"},{type:"text",text:creating .apkg from ${i.length} pages...}),l({type:"spinner"},{type:"text",text:"created. updating .ankirc..."}),await n(a),l({type:"check-circle"},{type:"text",text:"successfully finished."});let m=URL.createObjectURL(new Blob([p],{type:"application/octet-stream"})),u=document.createElement("a");u.href=m,u.download=${t}.apkg`,u.style.display="none",u.click(),u.remove(),URL.revokeObjectURL(m)}finally{setTimeout(f,1e3)}})(); })();