pin-diary-6-weekly
blu3mo-publicの方を読み込んでbundleするので、更新反映時は注意blu3mo.icon*2
code:script.ts
import { launch } from "./mod.ts";
import {
makeWeeklyDiary, isOldWeeklyDiary,
} from "../pin-diary-6%2Ftemplate/mod.ts";
launch(
"blu3mo",
{
makeDiary: makeWeeklyDiary,
isOldDiary: isOldWeeklyDiary,
},
);
code:mod.ts
/// <reference no-default-lib="true"/>
/// <reference lib="esnext"/>
/// <reference lib="dom"/>
import {
pin,
unpin,
patch,
useStatusBar,
sleep,
makeSocket,
disconnect,
format,
} from "./deps.ts";
import { listPinnedPages } from "./list.ts";
import type { Scrapbox, Socket } from "./deps.ts";
declare const scrapbox: Scrapbox;
export interface WeeklyDiaryInit {
/** 与えられた週の日記ページのテンプレートを作る */
makeDiary: (date: Date) => {
title: string;
header: string[];
footer: string[];
},
/** 今週以外の日記ページかどうかを判断する函数
*
* @param title 判断対象のページタイトル
* @param thisWeek 今週の日付
* @return 今週以外の日記ページならtrue, それ以外のページは false
*/
isOldDiary: (title: string, thisWeek: Date) => boolean;
}
// initialize
export function launch(
project: string,
init: WeeklyDiaryInit & { interval?: number },
) {
const interval = init.interval ?? 24 * 3600 * 1000;
const handleChange = () =>
scrapbox.Project.name === project ?
startObserve(project, interval, init) :
endObserve();
handleChange();
scrapbox.addListener("project:changed", handleChange);
}
let updateTimer: number | undefined;
async function startObserve(
project: string,
interval: number,
init: DiaryInit,
) {
endObserve();
await pinDiary(project, new Date(), init);
updateTimer = setInterval(
() => pinDiary(project, new Date(), init),
interval,
);
}
function endObserve() {
clearInterval(updateTimer);
}
code:mod.ts
export async function pinDiary(
project: string,
date: Date,
{ makeDiary, isOldDiary, }: DiaryInit,
): Promise<void> {
const { render, dispose } = useStatusBar();
let socket: Socket | undefined;
try {
// 今日以外の日付ページを外す
render(
{ type: "spinner" },
{ type: "text", text: unpin other diary pages...},
);
socket = await makeSocket();
for await (const { title } of listPinnedPages(project)) {
if (!isOldDiary(title, date)) continue;
await unpin(project, title, { socket });
}
// 今日の日付ページをピン留めする
const { title, header, footer } = makeDiary(date);
render(
{ type: "spinner" },
{ type: "text", text: pin "/${project}/${title}"...},
);
await pin(project, title, { socket, create: true });
// 今日の日付ページにtemplateを挿入する
render(
{ type: "spinner" },
{ type: "text", text: format "/${project}/${title}"...},
);
await patch(project, title, (lines) => [
...format(
lines.slice(1).map(line => line.text),
header,
footer,
),
], { socket });
render(
{ type: "check-circle" },
{ type: "text", text: Pinned "/${project}/${title}".},
);
} catch(e: unknown) {
render(
{ type: "exclamation-triangle" },
{ type: "text", text: e instanceof Error ?
${e.name} ${e.message} :
Unknown error! (see developper console),
},
);
console.error(e);
} finally {
if (socket) await disconnect(socket);
await sleep(1000);
dispose();
}
}
code:list.ts
import { listPages, BasePage } from "./deps.ts";
/** 全てのピン留めされたページを取得する */
export async function* listPinnedPages(project: string, skip = 0): AsyncGenerator<BasePage> {
const { count, pages } = await ensureList(project, skip);
for (const page of pages) {
if (page.pin === 0) continue;
yield page;
}
// pinしたページこれ以上ないときは終了
if ((pages.at(-1)?.pin ?? 0) === 0) return;
yield* listPinnedPages(project, skip + 1000);
}
async function ensureList(project: string, skip: number) {
const result = await listPages(project, {
limit: 1000,
skip,
});
// login errorなどは全部例外として扱う
if (!result.ok) {
const error = new Error();
error.name = result.value.name;
error.message = result.value.message;
throw error;
}
return result.value;
}
code:deps.ts
export { patchTemplate as format } from "./format.ts";
export {
pin,
unpin,
patch,
useStatusBar,
makeSocket,
disconnect,
listPages,
export type {
Socket,
export {
sleep,
export type {
Scrapbox,
export type {
BasePage,
code:format.ts
import { patchLines, findSplitIndex } from "./util.ts";
// linesにタイトルを入れないように
export function patchTemplate(lines: string[], headers: string[], footers: string[]): string[] {
// headerとfooterに相当する行を補う
const bodies = patchLines(
patchLines(lines, headers).reverse(),
).reverse();
// headerとfooterの間に余裕をもたせる
const headerStart = findSplitIndex(bodies, headers);
const footerStart = bodies.length - 1 - findSplitIndex(
);
return [
...bodies.slice(0, headerStart + 1),
"",
...bodies.slice(headerStart + 1, footerStart).join("\n").trim().split("\n"),
"",
...bodies.slice(footerStart),
];
}
code:util.ts
export function patchLines(lines: string[], appends: string[]): string[] {
let index = 0;
const result = [] as string[];
for (let i = 0; i < appends.length; i++) {
const pos = lines.findIndex((line, j) => j >= index && line.trim() === appendsi.trim()); if (pos < 0) {
continue;
}
result.push(...lines.slice(index, pos + 1));
index = pos + 1;
}
result.push(...lines.slice(index));
return result;
}
export function findSplitIndex(lines: string[], query: string[]) {
let index = -1;
for (const text of query) {
const pos = lines.findIndex((line, j) => j > index && line.trim() === text.trim());
if (pos < 0) return -1;
index = pos;
}
return index;
}
code:script.js
function le(e,t){let r=0,o=[];for(let n=0;n<t.length;n++){let s=e.findIndex((a,i)=>i>=r&&a.trim()===tn.trim());if(s<0){o.push(tn);continue}o.push(...e.slice(r,s+1)),r=s+1}return o.push(...e.slice(r)),o}function fe(e,t){let r=-1;for(let o of t){let n=e.findIndex((s,a)=>a>r&&s.trim()===o.trim());if(n<0)return-1;r=n}return r}function ge(e,t,r){let o=le(le(e,t).reverse(),...r.reverse()).reverse(),n=fe(o,t),s=o.length-1-fe(...o.reverse(),...r.reverse());return[...o.slice(0,n+1),"",...o.slice(n+1,s).join(` ).trim().split(
),"",...o.slice(s)]}var h=e=>{let{fetch:t=globalThis.fetch,hostName:r="scrapbox.io",...o}=e;return{fetch:t,hostName:r,...o}};var Ot=e=>typeof e=="object"&&e!==null,St=e=>Ot(e)?(e.name===void 0||typeof e.name=="string")&&typeof e.message=="string":!1,Ke=e=>{try{let t=typeof e=="string"?JSON.parse(e):e;return St(t)?t:!1}catch(t){if(t instanceof SyntaxError)return!1;throw t}};var B=class extends Error{constructor(t){super(${t.status} ${t.statusText} when fetching ${t.url});this.response=t;this.name="UnexpectedResponseError";Error.captureStackTrace&&Error.captureStackTrace(this,B)}},k=async e=>{let t=e.clone(),r=await t.text(),o=Ke(r);if(!o)throw new B(t);return{ok:!1,value:o}};var he=async e=>{let{sid:t,hostName:r,fetch:o}=h(e??{}),n=new Request(https://${r}/api/users/me,t?{headers:{Cookie:w(t)}}:void 0),s=await o(n);if(!s.ok)throw new B(s);return await s.json()};var w=e=>connect.sid=${e};var Q=e=>e.replaceAll(" ","_").toLowerCase();var xe=e=>[...e].map((t,r)=>t===" "?"_":!Pt.includes(t)||r===e.length-1&&Rt.includes(t)?encodeURIComponent(t):t).join(""),Pt='@$&+=:;",',Rt=':;",';var ze=(e,t,r)=>{let{sid:o,hostName:n,followRename:s,projects:a}=h(r??{}),i=new URLSearchParams;i.append("followRename",${s??!0});for(let u of a??[])i.append("projects",u);let c=https://${n}/api/pages/${e}/${xe(t)}?${i.toString()};return new Request(c,o?{headers:{Cookie:w(o)}}:void 0)},Ge=async e=>{if(!e.ok)return e.status===414?{ok:!1,value:{name:"TooLongURIError",message:"project ids may be too much."}}:k(e);let t=await e.json();return{ok:!0,value:t}},te=async(e,t,r)=>{let{fetch:o}=h(r??{}),n=ze(e,t,r),s=await o(n);return await Ge(s)};te.toRequest=ze;te.fromResponse=Ge;var Qe=(e,t)=>{let{sid:r,hostName:o,sort:n,limit:s,skip:a}=h(t??{}),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://${o}/api/pages/${e}?${i.toString()};return new Request(c,r?{headers:{Cookie:w(r)}}:void 0)},Ve=async e=>{if(!e.ok)return k(e);let t=await e.json();return{ok:!0,value:t}},V=async(e,t)=>{let{fetch:r}=h(t??{}),o=await r(Qe(e,t));return await Ve(o)};V.toRequest=Qe;V.fromResponse=Ve;var Xe=(e,t)=>{let{sid:r,hostName:o}=h(t??{});return new Request(https://${o}/api/projects/${e},r?{headers:{Cookie:w(r)}}:void 0)},Ze=async e=>{if(!e.ok)return k(e);let t=await e.json();return{ok:!0,value:t}},re=async(e,t)=>{let{fetch:r}=h(t??{}),o=Xe(e,t),n=await r(o);return Ze(n)};re.toRequest=Xe;re.fromResponse=Ze;var Je=(e,t)=>{let{sid:r,hostName:o}=h(t??{}),n=new URLSearchParams;for(let s of e)n.append("ids",s);return new Request(https://${o}/api/projects?${n.toString()},r?{headers:{Cookie:w(r)}}:void 0)},et=async e=>{if(!e.ok)return k(e);let t=await e.json();return{ok:!0,value:t}},tt=async(e,t)=>{let{fetch:r}=h(t??{}),o=await r(Je(e,t));return et(o)};tt.toRequest=Je;tt.fromResponse=et;var rt=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${t}" must be HTMLDivElememt but actual is "${e}")};var ot=()=>Ct(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),Ct=(e,t)=>{if(!!e)return rt(e,t),e};var X=e=>new Promise(t=>setTimeout(()=>t(),e));var we=()=>{let e=ot();if(!e)throw new Error("div.status-bar can't be found");let t=document.createElement("div");return e.append(t),{render:(...r)=>{t.textContent="";let o=st(...r);o&&t.append(o)},dispose:()=>t.remove()}},st=(...e)=>{let t=e.flatMap(o=>{switch(o.type){case"spinner":return[Ft()];case"check-circle":return[$t()];case"exclamation-triangle":return[Ht()];case"text":return[oe(o.text)];case"group":{let n=st(...o.items);return n?[n]:[]}}});if(t.length===0)return;if(t.length===1)return t[0];let r=document.createElement("span");return r.classList.add("item-group"),r.append(...t),r},oe=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},Ft=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),oe(e)},$t=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),oe(e)},Ht=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),oe(e)};var Bt="4.2.0";async function M(){let t=(await Wt())("https://scrapbox.io",{reconnectionDelay:5e3,transports:["websocket"]});return await new Promise((r,o)=>{let n=s=>o(s);t.once("connect",()=>{t.off("disconnect",n),r()}),t.once("disconnect",n)}),t}function Wt(){let e=https://cdnjs.cloudflare.com/ajax/libs/socket.io/${Bt}/socket.io.min.js;if(document.querySelector(scriptsrc="${e}"))return Promise.resolve(window.io);let t=document.createElement("script");return t.src=e,new Promise((r,o)=>{t.onload=()=>r(window.io),t.onerror=n=>o(n),document.head.append(t)})}function A(e,t=9e4){function r(n,s){let a;return new Promise((i,c)=>{let u=m=>{clearTimeout(a),c(new Error(m))};e.emit(n,s,m=>{clearTimeout(a),e.off("disconnect",u),m.error&&c(new Error(JSON.stringify(m.error))),"data"in m?i(m?.data):i(void 0)}),a=setTimeout(()=>{e.off("disconnect",u),c(new Error(Timeout: exceeded ${t}ms))},t),e.once("disconnect",u)})}async function*o(...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:r,response:o}}var ke=()=>M(),_=async e=>{if(e.connected)return;let t=new Promise(r=>e.once("connect",()=>r()));e.connect(),await t},N=async e=>{if(e.disconnected)return;let t=new Promise(r=>{let o=n=>{n==="io client disconnect"&&(r(),e.off("disconnect",o))};e.on("disconnect",o)});e.disconnect(),await t};var ne,W=async()=>{if(ne!==void 0)return ne;let e=await he();if(e.isGuest)throw new Error("this script can only be executed by Logged in users");return ne=e.id,ne},it=new Map,j=async e=>{let t=it.get(e);if(t!==void 0)return t;let r=await re(e);if(!r.ok){let{name:n,message:s}=r.value;throw new Error(${n} ${s})}let{id:o}=r.value;return it.set(e,o),o},at=e=>e.padStart(8,"0"),ct=e=>{let t=Math.floor(new Date().getTime()/1e3).toString(16),r=Math.floor(16777214*Math.random()).toString(16);return${at(t).slice(-8)}${e.slice(-6)}0000${at(r)}};var dt=(e,t)=>{let r=e.length>t.length,o=r?t:e,n=r?e:t,s=o.length+1,a=o.length+n.length+3,i=new Array(a);i.fill(-1);let c=[];function u(f,L,C){let T=Math.max(L,C),ee=T-f;for(;ee<o.length&&T<n.length&&o[ee]===n[T];)++ee,++T;return i[f+s]=c.length,c.push([{x:ee,y:T},i[f+(L>C?-1:1)+s]]),T}let m=new Array(a);m.fill(-1);let b=-1,g=n.length-o.length;do{++b;for(let f=-b;f<=g-1;++f)m[f+s]=u(f,m[f-1+s]+1,m[f+1+s]);for(let f=g+b;f>=g+1;--f)m[f+s]=u(f,m[f-1+s]+1,m[f+1+s]);m[g+s]=u(g,m[g-1+s]+1,m[g+1+s])}while(m[g+s]!==n.length);let I=[],v=i[g+s];for(;v!==-1;)I.push(c[v][0]),v=c[v][1];return{from:e,to:t,editDistance:g+b*2,buildSES:function*(){let f=0,L=0;for(let{x:C,y:T}of Yt(I))for(;f<C||L<T;)T-C>L-f?(yield{value:n[L],type:r?"deleted":"added"},++L):T-C<L-f?(yield{value:o[f],type:r?"added":"deleted"},++f):(yield{value:o[f],type:"common"},++f,++L)}}};function*pt(e){let t=[],r=[];function*o(){if(t.length>r.length){for(let n=0;n<r.length;n++)yield ut(t[n],r[n]);for(let n=r.length;n<t.length;n++)yield t[n]}else{for(let n=0;n<t.length;n++)yield ut(t[n],r[n]);for(let n=t.length;n<r.length;n++)yield r[n]}t=[],r=[]}for(let n of e)switch(n.type){case"added":t.push(n);break;case"deleted":r.push(n);break;case"common":yield*o(),yield n;break}yield*o()}var ut=(e,t)=>({value:e.value,oldValue:t.value,type:"replaced"});function*Yt(e){for(let t=e.length-1;t>=0;t--)yield e[t]}function*mt(e,t,{userId:r}){let{buildSES:o}=dt(e.map(({text:a})=>a),t),n=0,s=e[0].id;for(let a of pt(o())){switch(a.type){case"added":yield{_insert:s,lines:{id:ct(r),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 Kt=e=>({type:"title",text:e.rows[0].text}),zt=e=>{let{rows:[t,...r]}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*code:/,"");return{indent:o,type:"codeBlock",fileName:s,content:r.map(a=>a.text.substring(o+1)).join( )}},x=(e,{parseOnNested:t,parseOnQuoted:r,patterns:o})=>(n,s,a)=>{var i,c,u,m,b,g;if(!t&&s.nested)return(i=a?.())!==null&&i!==void 0?i:[];if(!r&&s.quoted)return(c=a?.())!==null&&c!==void 0?c:[];for(let I of o){let v=I.exec(n);if(v===null)continue;let f=n.substring(0,v.index),L=n.substring(v.index+((m=(u=v[0])===null||u===void 0?void 0:u.length)!==null&&m!==void 0?m:0)),C=e((b=v[0])!==null&&b!==void 0?b:"",s);return[...q(f,s),...C,...q(L,s)]}return(g=a?.())!==null&&g!==void 0?g:[]},y=e=>[{type:"plain",raw:e,text:e}],Gt=x(y,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]}),Qt=/^>.*$/,Vt=(e,t)=>t.context==="table"?y(e,t):[{type:"quote",raw:e,nodes:q(e.substring(1),{...t,quoted:!0})}],Xt=x(Vt,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Qt]}),Zt=/^\? .+$/,Jt=(e,t)=>t.context==="table"?y(e,t):[{type:"helpfeel",raw:e,text:e.substring(2)}],er=x(Jt,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Zt]}),tr=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)\]\]/i,rr=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,or=(e,t)=>{if(t.context==="table")return y(e,t);let r=e.substring(2,e.length-2),o=/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(r);return[{type:"strongImage",raw:e,src:o?${r}/thumb/1000:r}]},nr=x(or,{parseOnNested:!1,parseOnQuoted:!0,patterns:[tr,rr]}),sr=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/;function lt(e){return(t,r)=>{if(e==="strongIcon"&&r.context==="table")return y(t,r);let o=e==="icon"?t.substring(1,t.length-1):t.substring(2,t.length-2),n=o.lastIndexOf(".icon"),s=o.substring(0,n),a=s.startsWith("/")?"root":"relative",i=o.substring(n+5,o.length),c=i.startsWith("*")?parseInt(i.substring(1),10):1;return new Array(c).fill({}).map(()=>({path:s,pathType:a,type:e,raw:t}))}}var ir=lt("icon"),ar=x(ir,{parseOnNested:!0,parseOnQuoted:!0,patterns:[sr]}),cr=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,dr=lt("strongIcon"),pr=x(dr,{parseOnNested:!1,parseOnQuoted:!0,patterns:[cr]}),ur=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,mr=(e,t)=>t.context==="table"?y(e,t):[{type:"strong",raw:e,nodes:q(e.substring(2,e.length-2),{...t,nested:!0})}],lr=x(mr,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ur]}),fr=/\[\$ .+? \]/,gr=/\[\$ [^\]]+\]/,hr=(e,t)=>t.context==="table"?y(e,t):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],xr=x(hr,{parseOnNested:!1,parseOnQuoted:!0,patterns:[fr,gr]}),yr=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,br=(e,t)=>{if(t.context==="table")return y(e,t);let r=e.indexOf(" "),o=e.substring(1,r),n=e.substring(r+1,e.length-1),s=new Set(o);if(s.has("*")){let a=o.split("*").length-1;s.delete("*"),s.add(*-${Math.min(a,10)})}return[{type:"decoration",raw:e,rawDecos:o,decos:Array.from(s),nodes:q(n,{...t,nested:!0})}]},wr=x(br,{parseOnNested:!1,parseOnQuoted:!0,patterns:[yr]}),kr=/.*?/,Er=(e,t)=>t.context==="table"?y(e,t):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],vr=x(Er,{parseOnNested:!1,parseOnQuoted:!0,patterns:[kr]}),Dr=/^[$%] .+$/,Ir=(e,t)=>{var r;if(t.context==="table")return y(e,t);let o=(r=e[0])!==null&&r!==void 0?r:"",n=e.substring(2);return[{type:"commandLine",raw:e,symbol:o,text:n}]},Lr=x(Ir,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Dr]}),Tr=/\[\s+\]/,Mr=(e,t)=>t.context==="table"?y(e,t):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],Nr=x(Mr,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Tr]}),Or=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,Sr=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?\]/i,Pr=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,Rr=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,Cr=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg)(\?[^\]\s]+)?$/i.test(e)||Ar(e),Ar=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),qr=(e,t)=>{if(t.context==="table")return y(e,t);let r=e.search(/\s/),o=r!==-1?e.substring(1,r):e.substring(1,e.length-1),n=r!==-1?e.substring(r,e.length-1).trimLeft():"",[s,a]=Cr(n)?[n,o]:[o,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}]},_r=x(qr,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Or,Sr,Pr,Rr]}),jr=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,Fr=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,$r=/\[https?:\/\/[^\s\]]+\]/,Hr=/https?:\/\/[^\s]+/,Ur=(e,t)=>{if(t.context==="table")return y(e,t);let r=e.startsWith("[")&&e.endsWith("]")?e.substring(1,e.length-1):e,o=/^https?:\/\/[^\s\]]/.test(r),n=(o?/^https?:\/\/[^\s\]]+/:/https?:\/\/[^\s\]]+$/).exec(r);if(n?.[0]===void 0)return[];let s=o?r.substring(n[0].length):r.substring(0,n.index-1);return[{type:"link",raw:e,pathType:"absolute",href:n[0],content:s.trim()}]},Br=x(Ur,{parseOnNested:!0,parseOnQuoted:!0,patterns:[jr,Fr,$r,Hr]}),ft=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,gt=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,Wr=e=>{let[t="",r="",o=""]=e.split(","),n=parseFloat(t.replace(/^N/,"").replace(/^S/,"-")),s=parseFloat(r.replace(/^E/,"").replace(/^W/,"-")),a=/^Z\d+$/.test(o)?parseInt(o.replace(/^Z/,""),10):14;return{latitude:n,longitude:s,zoom:a}},Yr=(e,t)=>{var r;if(t.context==="table")return y(e,t);let o=(r=e.match(ft))!==null&&r!==void 0?r:e.match(gt);if(o===null)return[];let n=e.startsWith("[N")||e.startsWith("[S"),[,s="",a=""]=n?o:[o[0],o[2],o[1]],{latitude:i,longitude:c,zoom:u}=Wr(s),m=a!==""?https://www.google.com/maps/place/${encodeURIComponent(a)}/@${i},${c},${u}z:https://www.google.com/maps/@${i},${c},${u}z;return[{type:"googleMap",raw:e,latitude:i,longitude:c,zoom:u,place:a,url:m}]},Kr=x(Yr,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ft,gt]}),zr=/\[\/?[^[\]]+\]/,Gr=e=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},Qr=x(Gr,{parseOnNested:!0,parseOnQuoted:!0,patterns:[zr]}),Vr=/(?:^|\s)#\S+/,Xr=(e,t)=>{if(t.context==="table")return y(e,t);if(e.startsWith("#"))return[{type:"hashTag",raw:e,href:e.substring(1)}];let r=e.substring(0,1),o=e.substring(1);return[...y(r,t),{type:"hashTag",raw:o,href:o.substring(1)}]},Zr=x(Xr,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Vr]}),Jr=/^[0-9]+\. .*$/,eo=(e,t)=>{if(t.context==="table")return y(e,t);let r=e.indexOf(" "),o=e.substring(0,r-1),n=parseInt(o,10),s=e.substring(r+1,e.length);return[{type:"numberList",raw:e,rawNumber:o,number:n,nodes:q(s,{...t,nested:!0})}]},to=x(eo,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Jr]}),ro=(e,t,r)=>{var o;return e===""?[]:(o=r?.())!==null&&o!==void 0?o:[]},oo=(...e)=>(t,r)=>e.reduceRight((o,n)=>()=>n(t,r,o),()=>Gt(t,r))(),q=oo(ro,Xt,er,vr,Lr,xr,Nr,wr,nr,pr,lr,_r,Br,ar,Kr,Qr,Zr,to),no=e=>{let{rows:[t,...r]}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*table:/,"");return{indent:o,type:"table",fileName:s,cells:r.map(a=>a.text.substring(o+1)).map(a=>a.split(" ").map(i=>q(i,{nested:!1,quoted:!1,context:"table"})))}},so=e=>{let{indent:t,text:r}=e.rows[0];return{indent:t,type:"line",nodes:q(r.substring(t),{nested:!1,quoted:!1,context:"line"})}},ht=e=>{switch(e.type){case"title":return Kt(e);case"codeBlock":return zt(e);case"table":return no(e);case"line":return so(e)}},xt=e=>e.split( ).map(t=>{var r,o,n;return{indent:(n=(o=(r=/^\s+/.exec(t))===null||r===void 0?void 0:r[0])===null||o===void 0?void 0:o.length)!==null&&n!==void 0?n:0,text:t}}),io=(e,t)=>{var r,o;return(e.type==="codeBlock"||e.type==="table")&&t.indent>((o=(r=e.rows[0])===null||r===void 0?void 0:r.indent)!==null&&o!==void 0?o:0)},yt=(e,t)=>{let r=e[e.length-1];return r!==void 0&&io(r,t)?(r.rows.push(t),e):(e.push({type:/^\s*code:/.test(t.text)?"codeBlock":/^\s*table:/.test(t.text)?"table":"line",rows:[t]}),e)},bt=(e,t)=>{var r;if(!((r=t.hasTitle)!==null&&r!==void 0)||r){let[o,...n]=e;return o===void 0?[]:[{type:"title",rows:[o]},...n.reduce(yt,[])]}return e.reduce(yt,[])};var ao=/https?:\/\/(?:www\.|music\.|)youtube\.com\/watch/,co=/https?:\/\/youtu\.be\/([a-zA-Z\d_-]+)(?:\?([^\s]{0,100})|)/,po=/https?:\/\/(?:www\.|)youtube\.com\/shorts\/([a-zA-Z\d_-]+)(?:\?([^\s]+)|)/,uo=/https?:\/\/(?:www\.|music\.|)youtube\.com\/playlist\?((?:[^\s]+&|)list=([a-zA-Z\d_-]+)(?:&[^\s]+|))/,Ee=e=>{if(ao.test(e)){let t=new URL(e).searchParams,r=t.get("v");if(r)return{pathType:"com",videoId:r,params:t}}{let t=e.match(co);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"dotbe"}}}{let t=e.match(po);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"short"}}}{let t=e.match(uo);if(t){let[,r,o]=t;return{listId:o,params:new URLSearchParams(r),pathType:"list"}}}};function*wt(e,t,{userId:r,head:o}){let n=t.flatMap(u=>u.split(
));for(let u of mt(e,n,{userId:r}))yield u;(e[0].text!==n[0]||!o.persistent)&&(yield{title:n[0]});let s=e.slice(1,6).map(u=>u.text),a=n.slice(1,6);s.join("")!==a.join("")&&(yield{descriptions:a});let[i,c]=mo(n.join(
));(o.links.length!==i.length||!o.links.every(u=>i.includes(u)))&&(yield{links:i}),o.image!==c&&(yield{image:c})}var mo=e=>{let t=xt(e),r=bt(t,{hasTitle:!0}).flatMap(i=>{switch(i.type){case"codeBlock":case"title":return[];case"line":case"table":return[ht(i)]}}),o=new Map,n=[],s=null,a=i=>{switch(i.type){case"hashTag":if(o.has(Q(i.href)))return;o.set(Q(i.href),!1),n.push(i.href);return;case"link":switch(i.pathType){case"relative":if(o.get(Q(i.href)))return;o.set(Q(i.href),!0),n.push(i.href);return;case"absolute":{let c=Ee(i.href);if(!c||c.pathType==="list")return;s??=https://i.ytimg.com/vi/${c.videoId}/mqdefault.jpg;return}default:return}case"image":case"strongImage":{s??=i.src.endsWith("/thumb/1000")?i.src.replace(/\/thumb\/1000$/,"/raw"):i.src;return}case"strong":case"quote":case"decoration":{for(let c of i.nodes)a(c);return}default:return}};for(let i of lo(r))a(i);return[n,s]};function*lo(e){for(let t of e)switch(t.type){case"codeBlock":case"title":continue;case"line":for(let r of t.nodes)yield r;continue;case"table":{for(let r of t.cells)for(let o of r)for(let n of o)yield n;continue}}}var P=async(e,t)=>{let r=await te(e,t);if(!r.ok)throw new Error(You have no privilege of editing "/${e}/${t}".);let{commitId:o,persistent:n,image:s,links:a,lines:i,id:c,pin:u}=r.value;return{commitId:o,pageId:c,persistent:n,image:s,links:a,pin:u,lines:i}};var se=async(e,t,r)=>t.length===0?{commitId:r.parentId}:await e("socket.io-request",{method:"commit",data:{kind:"page",...r,changes:t,cursor:null,freeze:!0}}),F=async(e,t,{project:r,title:o,retry:n=3,parentId:s,...a})=>{try{s=(await se(e,t,{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:u}=await P(r,o);s=u;try{s=(await se(e,t,{parentId:s,...a})).commitId,console.log("Success in retrying");break}catch{continue}}throw Error("Faild to retry pushing.")}return s};var ve=async(e,t,r,o)=>{let[n,s,a]=await Promise.all([P(e,t),j(e),W()]),i=n,c=o?.socket,u=c??await M();await _(u);try{let{request:m}=A(u);for(let b=0;b<3;b++)try{let g=r(i.lines,i),I=g instanceof Promise?await g:g;if(!I)return;I.length===0&&await F(m,[{deleted:!0}],{projectId:s,pageId:i.pageId,parentId:i.commitId,userId:a,project:e,title:t});let v=[...wt(i.lines,I,{userId:a,head:i})];await se(m,v,{parentId:i.commitId,projectId:s,pageId:i.pageId,userId:a});break}catch{if(b===2)throw Error("Faild to retry pushing.");console.log("Faild to push a commit. Retry after pulling new commits");try{i=await P(e,t)}catch(I){throw I}}}finally{c||await N(u)}};var De=async(e,t,r)=>{let[o,n,s]=await Promise.all([P(e,t),j(e),W()]);if(o.pin>0||!o.persistent&&!(r?.create??!1))return;let a={parentId:o.commitId,projectId:n,pageId:o.pageId,userId:s,project:e,title:t},i=r?.socket,c=i??await M();await _(c);let{request:u}=A(c);if(!o.persistent){let m=await F(u,[{title:t}],a);a.parentId=m}try{await F(u,[{pin:fo()}],a)}finally{i||await N(c)}},Ie=async(e,t,r)=>{let[o,n,s]=await Promise.all([P(e,t),j(e),W()]);if(o.pin==0||!o.persistent)return;let a={parentId:o.commitId,projectId:n,pageId:o.pageId,userId:s,project:e,title:t},i=r?.socket,c=i??await M();await _(c);let{request:u}=A(c);try{await F(u,[{pin:0}],a)}finally{i||await N(c)}},fo=()=>Number.MAX_SAFE_INTEGER-Math.floor(Date.now()/1e3);async function*Le(e,t=0){let{count:r,pages:o}=await go(e,t);for(let n of o)n.pin!==0&&(yield n);(o.at(-1)?.pin??0)!==0&&(yield*Le(e,t+1e3))}async function go(e,t){let r=await V(e,{limit:1e3,skip:t});if(!r.ok){let o=new Error;throw o.name=r.value.name,o.message=r.value.message,o}return r.value}function kt(e,t){let r=t.interval??24*3600*1e3,o=()=>scrapbox.Project.name===e?ho(e,r,t):vt();o(),scrapbox.addListener("project:changed",o)}var Et;async function ho(e,t,r){vt(),await Dt(e,new Date,r),Et=setInterval(()=>Dt(e,new Date,r),t)}function vt(){clearInterval(Et)}async function Dt(e,t,{makeDiary:r,isOldDiary:o}){let{render:n,dispose:s}=we(),a;try{n({type:"spinner"},{type:"text",text:"unpin other diary pages..."}),a=await ke();for await(let{title:m}of Le(e))!o(m,t)||await Ie(e,m,{socket:a});let{title:i,header:c,footer:u}=r(t);n({type:"spinner"},{type:"text",text:pin "/${e}/${i}"...}),await De(e,i,{socket:a,create:!0}),n({type:"spinner"},{type:"text",text:format "/${e}/${i}"...}),await ve(e,i,m=>[m[0].text,...ge(m.slice(1).map(b=>b.text),c,u)],{socket:a}),n({type:"check-circle"},{type:"text",text:Pinned "/${e}/${i}".})}catch(i){n({type:"exclamation-triangle"},{type:"text",text:i instanceof Error?${i.name} ${i.message}:"Unknown error! (see developper console)"}),console.error(i)}finally{a&&await N(a),await X(1e3),s()}}function d(e,t){if(t.length<e)throw new TypeError(e+" argument"+(e>1?"s":"")+" required, but only "+t.length+" present")}function p(e){d(1,arguments);let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new Date(e.getTime()):typeof e=="number"||t==="[object Number]"?new Date(e):((typeof e=="string"||t==="[object String]")&&typeof console!="undefined"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use parseISO to parse strings. See: https://git.io/fjule"),console.warn(new Error().stack)),new Date(NaN))}function Te(e){d(1,arguments);let r=p(e).getFullYear();return r%400==0||r%4==0&&r%100!=0}function ie(e){d(1,arguments);let t=p(e);return String(new Date(t))==="Invalid Date"?NaN:Te(t)?366:365}function Me(e){d(1,arguments);let t=p(e),r=new Date(0);return r.setFullYear(t.getFullYear(),0,1),r.setHours(0,0,0,0),r}function Y(e){let t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}function ae(e){d(1,arguments);let t=p(e);return t.setHours(0,0,0,0),t}var xo=864e5;function Z(e,t){d(2,arguments);let r=ae(e),o=ae(t),n=r.getTime()-Y(r),s=o.getTime()-Y(o);return Math.round((n-s)/xo)}function ce(e){d(1,arguments);let t=p(e);return Z(t,Me(t))+1}function l(e){if(e===null||e===!0||e===!1)return NaN;let t=Number(e);return isNaN(t)?t:t<0?Math.ceil(t):Math.floor(t)}function K(e,t){d(2,arguments);let r=p(e),o=l(t);return isNaN(o)?new Date(NaN):(o&&r.setDate(r.getDate()+o),r)}function z(e,t){d(2,arguments);let r=l(t);return K(e,-r)}function E(e,t){d(1,arguments);let r=t||{},o=r.locale,n=o&&o.options&&o.options.weekStartsOn,s=n==null?0:l(n),a=r.weekStartsOn==null?s:l(r.weekStartsOn);if(!(a>=0&&a<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");let i=p(e),c=i.getDay(),u=(c<a?7:0)+c-a;return i.setDate(i.getDate()-u),i.setHours(0,0,0,0),i}function Ne(e,t){d(1,arguments);let r=p(e),o=r.getFullYear(),n=t?.locale?.options?.firstWeekContainsDate,s=n==null?1:l(n),a=t?.firstWeekContainsDate==null?s:l(t.firstWeekContainsDate);if(!(a>=1&&a<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");let i=new Date(0);i.setFullYear(o+1,0,a),i.setHours(0,0,0,0);let c=E(i,t),u=new Date(0);u.setFullYear(o,0,a),u.setHours(0,0,0,0);let m=E(u,t);return r.getTime()>=c.getTime()?o+1:r.getTime()>=m.getTime()?o:o-1}function Oe(e,t){d(1,arguments);var r=t||{},o=r.locale,n=o&&o.options&&o.options.firstWeekContainsDate,s=n==null?1:l(n),a=r.firstWeekContainsDate==null?s:l(r.firstWeekContainsDate),i=Ne(e,t),c=new Date(0);c.setFullYear(i,0,a),c.setHours(0,0,0,0);var u=E(c,t);return u}var yo=6048e5;function de(e,t){d(1,arguments);let r=p(e),o=E(r,t).getTime()-Oe(r,t).getTime();return Math.round(o/yo)+1}function J(e,t){d(2,arguments);let r=p(e),o=l(t);if(isNaN(o))return new Date(NaN);if(!o)return r;let n=r.getDate(),s=new Date(r.getTime());s.setMonth(r.getMonth()+o+1,0);let a=s.getDate();return n>=a?s:(r.setFullYear(s.getFullYear(),s.getMonth(),n),r)}function Se(e,t){d(2,arguments);let r=l(t);return J(e,r*12)}function pe(e,t){d(2,arguments);let r=l(t);return Se(e,-r)}function ue(e){return d(1,arguments),p(e).getFullYear()}function O(e,t){for(var r=e<0?"-":"",o=Math.abs(e).toString();o.length<t;)o="0"+o;return r+o}var bo={y(e,t){let r=e.getUTCFullYear(),o=r>0?r:1-r;return O(t==="yy"?o%100:o,t.length)},M(e,t){let r=e.getUTCMonth();return t==="M"?String(r+1):O(r+1,2)},d(e,t){return O(e.getUTCDate(),t.length)},a(e,t){let r=e.getUTCHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];case"aaaa":default:return r==="am"?"a.m.":"p.m."}},h(e,t){return O(e.getUTCHours()%12||12,t.length)},H(e,t){return O(e.getUTCHours(),t.length)},m(e,t){return O(e.getUTCMinutes(),t.length)},s(e,t){return O(e.getUTCSeconds(),t.length)},S(e,t){let r=t.length,o=e.getUTCMilliseconds(),n=Math.floor(o*Math.pow(10,r-3));return O(n,t.length)}},It=bo;function G(e){d(1,arguments);var t=p(e);return!isNaN(t)}function Pe(e,t){d(2,arguments);let r=p(e).getTime(),o=l(t);return new Date(r+o)}function Re(e,t){d(2,arguments);let r=l(t);return Pe(e,-r)}var wo=/(\w)\1*|''|'(''|[^'])+('|$)|./g,ko=/^'([^]*?)'?$/,Eo=/''/g,vo=/[a-zA-Z]/;function D(e,t){d(2,arguments);let r=p(e);if(!G(r))throw new RangeError("Invalid time value");let o=Y(r),n=Re(r,o),s=t.match(wo);return s?s.map(i=>{if(i==="''")return"'";let c=i[0];if(c==="'")return Do(i);let u=It[c];if(u)return u(n,i);if(c.match(vo))throw new RangeError("Format string contains an unescaped latin alphabet character "+c+"");return i}).join(""):""}function Do(e){let t=e.match(ko);return t?t[1].replace(Eo,"'"):e}function S(e,t){d(2,arguments);let r=p(e),o=p(t),n=r.getTime()-o.getTime();return n<0?-1:n>0?1:n}function Ce(e,t){d(2,arguments);let r=p(e),o=p(t);return r.getFullYear()-o.getFullYear()}function Ae(e,t){d(2,arguments);let r=p(e),o=p(t),n=S(r,o),s=Math.abs(Ce(r,o));r.setFullYear(1584),o.setFullYear(1584);let a=S(r,o)===-n,i=n*(s-Number(a));return i===0?0:i}function qe(e,t){d(2,arguments);let r=p(e),o=p(t),n=r.getFullYear()-o.getFullYear(),s=r.getMonth()-o.getMonth();return n*12+s}function _e(e){d(1,arguments);let t=p(e);return t.setHours(23,59,59,999),t}function je(e){d(1,arguments);let t=p(e),r=t.getMonth();return t.setFullYear(t.getFullYear(),r+1,0),t.setHours(23,59,59,999),t}function Fe(e){d(1,arguments);let t=p(e);return _e(t).getTime()===je(t).getTime()}function $e(e,t){d(2,arguments);let r=p(e),o=p(t),n=S(r,o),s=Math.abs(qe(r,o)),a;if(s<1)a=0;else{r.getMonth()===1&&r.getDate()>27&&r.setDate(30),r.setMonth(r.getMonth()-n*s);let i=S(r,o)===-n;Fe(p(e))&&s===1&&S(e,o)===1&&(i=!1),a=n*(s-Number(i))}return a===0?0:a}function Lt(e,t){let r=e.getFullYear()-t.getFullYear()||e.getMonth()-t.getMonth()||e.getDate()-t.getDate()||e.getHours()-t.getHours()||e.getMinutes()-t.getMinutes()||e.getSeconds()-t.getSeconds()||e.getMilliseconds()-t.getMilliseconds();return r<0?-1:r>0?1:r}function He(e,t){d(2,arguments);let r=p(e),o=p(t),n=Lt(r,o),s=Math.abs(Z(r,o));r.setDate(r.getDate()-n*s);let a=Number(Lt(r,o)===-n),i=n*(s-a);return i===0?0:i}function $(e,t){d(2,arguments);let r=p(e),o=p(t);return r.getTime()-o.getTime()}var Io=36e5;function Ue(e,t){d(2,arguments);let r=$(e,t)/Io;return r>0?Math.floor(r):Math.ceil(r)}var Lo=6e4;function Be(e,t){d(2,arguments);var r=$(e,t)/Lo;return r>0?Math.floor(r):Math.ceil(r)}function We(e,t){d(2,arguments);let r=$(e,t)/1e3;return r>0?Math.floor(r):Math.ceil(r)}function Ye(e,t){d(2,arguments);let r=l(t);return J(e,-r)}function H(e,t){if(d(2,arguments),!t||typeof t!="object")return new Date(NaN);let r="years"in t?l(t.years):0,o="months"in t?l(t.months):0,n="weeks"in t?l(t.weeks):0,s="days"in t?l(t.days):0,a="hours"in t?l(t.hours):0,i="minutes"in t?l(t.minutes):0,c="seconds"in t?l(t.seconds):0,u=Ye(p(e),o+r*12),m=z(u,s+n*7),b=i+a*60,I=(c+b*60)*1e3;return new Date(m.getTime()-I)}function me({start:e,end:t}){d(1,arguments);let r=p(e),o=p(t);if(!G(r))throw new RangeError("Start Date is invalid");if(!G(o))throw new RangeError("End Date is invalid");let n={years:0,months:0,days:0,hours:0,minutes:0,seconds:0},s=S(r,o);n.years=Math.abs(Ae(r,o));let a=H(r,{years:s*n.years});n.months=Math.abs($e(a,o));let i=H(a,{months:s*n.months});n.days=Math.abs(He(i,o));let c=H(i,{days:s*n.days});n.hours=Math.abs(Ue(c,o));let u=H(c,{hours:s*n.hours});n.minutes=Math.abs(Be(u,o));let m=H(u,{minutes:s*n.minutes});return n.seconds=Math.abs(We(m,o)),n}function U(e,t){d(1,arguments);let r=t||{},o=r.locale,n=o&&o.options&&o.options.weekStartsOn,s=n==null?0:l(n),a=r.weekStartsOn==null?s:l(r.weekStartsOn);if(!(a>=0&&a<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");let i=p(e),c=i.getDay(),u=(c<a?-7:0)+6-(c-a);return i.setDate(i.getDate()+u),i.setHours(23,59,59,999),i}var R="yyyy/MM/dd";function Tt(e){let t=me({start:new Date(2020,9,9),end:e}).years;return{title:Nt(e),header:[第${de(e)}週: ${To(e)},${ue(e)}年 ${(ce(e)*100/ie(e)).toFixed(2)}%経過,"","今週のn年前",...[...Array(t).keys()].map(r=> ${D(pe(e,r+1),R)})],footer:[${D(z(E(e),1),R)}←${D(E(e),R)} - ${D(U(e),R)}→${D(K(U(e),1),R)},${D(e,"yyyy/MM")}.icon]}}function To(e){returnFrom ${D(E(e),R)} to ${D(U(e),R)}`}var Mo=/^\d{4}\/\d{2}\/\d{2} - \d{4}\/\d{2}\/\d{2}$/;function Mt(e,t){return Mo.test(e)?Nt(t)!==e:!1}function Nt(e){return D(E(e),R)+" - "+D(U(e),R)}kt("blu3mo",{makeDiary:Tt,isOldDiary:Mt});