@heycys/gallery 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/THIRD-PARTY-NOTICES.md +1 -1
  2. package/browser/editor/components/icon/page.mjs +6 -4
  3. package/browser/editor/components/icons.mjs +2 -2
  4. package/browser/editor/page/annotate/index.mjs +3 -2
  5. package/browser/editor/page/board/index.mjs +2 -1
  6. package/browser/editor/page/board/settings.mjs +2 -1
  7. package/browser/editor/page/clipboard/import/read.mjs +20 -2
  8. package/browser/editor/page/core.mjs +3 -2
  9. package/browser/editor/page/custom-page.mjs +4 -3
  10. package/browser/editor/page/editor.mjs +9 -5
  11. package/browser/editor/page/emoji-picker/support.mjs +3 -2
  12. package/browser/editor/page/links/index.mjs +1 -12
  13. package/browser/editor/page/links/pages.mjs +3 -2
  14. package/browser/editor/page/outline/folds.mjs +3 -0
  15. package/browser/editor/page/post.mjs +2 -1
  16. package/browser/editor/page/present-links.mjs +4 -3
  17. package/browser/editor/page/present-shell.mjs +3 -58
  18. package/browser/editor/page/session.mjs +3 -37
  19. package/browser/editor/page/storage.mjs +5 -5
  20. package/browser/shared/component-catalog.mjs +2 -2
  21. package/browser/shared/document-copy.mjs +43 -0
  22. package/browser/shared/drafts.mjs +32 -50
  23. package/browser/shared/emoji/icon-value.mjs +4 -3
  24. package/browser/shared/extension-manifest.mjs +90 -0
  25. package/browser/shared/extensions.mjs +93 -7
  26. package/browser/shared/http.mjs +1 -1
  27. package/browser/shared/i18n/en.mjs +55 -14
  28. package/browser/shared/media.mjs +2 -1
  29. package/browser/shared/outline-shape.mjs +6 -0
  30. package/browser/shared/outline.mjs +95 -10
  31. package/browser/shared/page-address.mjs +8 -15
  32. package/browser/shared/paths.mjs +2 -1
  33. package/browser/shared/preferences.mjs +3 -1
  34. package/browser/shared/preview-server.mjs +51 -63
  35. package/browser/shared/service-location.mjs +18 -0
  36. package/browser/shared/session.mjs +3 -6
  37. package/browser/shared/workspace-address.mjs +19 -0
  38. package/browser/shared/workspace-columns.mjs +12 -9
  39. package/browser/shared/workspace-registry.mjs +6 -40
  40. package/browser/shared/workspace.mjs +3 -6
  41. package/browser/shared/writing-preferences.mjs +6 -4
  42. package/dist/{chunk-W7665ZEC.mjs → chunk-236JJXWY.mjs} +2 -2
  43. package/dist/{chunk-EAIFITAV.mjs → chunk-2KAVXMKG.mjs} +1 -1
  44. package/dist/chunk-2T4PZQEP.mjs +2 -0
  45. package/dist/{chunk-HXG7EOPJ.mjs → chunk-3SKOU6OZ.mjs} +1 -1
  46. package/dist/{chunk-AR5D57ZD.mjs → chunk-3XZOA7AH.mjs} +2 -2
  47. package/dist/{chunk-UYVCQK3H.mjs → chunk-4B2TB5K2.mjs} +1 -1
  48. package/dist/{chunk-3MBRL2PM.mjs → chunk-4KUO7R2M.mjs} +8 -8
  49. package/dist/chunk-4SNV4HA5.mjs +2 -0
  50. package/dist/chunk-53XDTHTG.mjs +4 -0
  51. package/dist/chunk-5XV3YYLG.mjs +2 -0
  52. package/dist/{chunk-ZDLPUOAG.mjs → chunk-65NTKF4N.mjs} +1 -1
  53. package/dist/chunk-6GV3CBB2.mjs +2 -0
  54. package/dist/{chunk-WQDQWCX5.mjs → chunk-6L6V7YR2.mjs} +1 -1
  55. package/dist/{chunk-ITOH5EGO.mjs → chunk-6NLXUKAY.mjs} +1 -1
  56. package/dist/chunk-6Q7ASAXJ.mjs +3 -0
  57. package/dist/{chunk-7OG26PGF.mjs → chunk-6QWQXHAV.mjs} +1 -1
  58. package/dist/chunk-6XD6U3QA.mjs +5 -0
  59. package/dist/{chunk-YNAWBAYN.mjs → chunk-7EFHNQ5B.mjs} +1 -1
  60. package/dist/{chunk-OFHXGWOX.mjs → chunk-7ISBBDJR.mjs} +1 -1
  61. package/dist/{chunk-QE5RG76S.mjs → chunk-7UZUQQ7Q.mjs} +29 -24
  62. package/dist/chunk-BLNQUR5R.mjs +168 -0
  63. package/dist/chunk-BMX3VUHY.mjs +2 -0
  64. package/dist/chunk-BN7M3IN7.mjs +8 -0
  65. package/dist/{chunk-K5XATEOO.mjs → chunk-BQNTTFPL.mjs} +1 -1
  66. package/dist/chunk-C257H6IA.mjs +2 -0
  67. package/dist/chunk-CHQU37CA.mjs +2 -0
  68. package/dist/{chunk-CMA72MAG.mjs → chunk-E4IHAIJ7.mjs} +1 -1
  69. package/dist/{chunk-VS7JIGJW.mjs → chunk-E7656LR7.mjs} +1 -1
  70. package/dist/{chunk-VFX2KNHP.mjs → chunk-ECZBLQKK.mjs} +1 -1
  71. package/dist/{chunk-MN7BZL4R.mjs → chunk-ERE2BXYV.mjs} +1 -1
  72. package/dist/chunk-FFV733MA.mjs +2 -0
  73. package/dist/{chunk-AHN3NFKJ.mjs → chunk-GJJRBGMY.mjs} +1 -1
  74. package/dist/{chunk-BZ5RAF7L.mjs → chunk-GKOBB6DH.mjs} +1 -1
  75. package/dist/chunk-GMJD7ID3.mjs +2 -0
  76. package/dist/{chunk-OEXWRJME.mjs → chunk-IA2SIEJQ.mjs} +1 -1
  77. package/dist/chunk-JPG2LBQM.mjs +11 -0
  78. package/dist/{chunk-POTA2FV4.mjs → chunk-JXXHAXYH.mjs} +1 -1
  79. package/dist/{chunk-FDMAXMQA.mjs → chunk-K3JKPFL5.mjs} +1 -1
  80. package/dist/{chunk-J5PUIV3Y.mjs → chunk-KLQP46Y3.mjs} +1 -1
  81. package/dist/chunk-LMUZQK5O.mjs +2 -0
  82. package/dist/{chunk-JLTZF4LA.mjs → chunk-M4NRDYI5.mjs} +1 -1
  83. package/dist/{chunk-HPOI4ZX7.mjs → chunk-MKIBJTJZ.mjs} +1 -1
  84. package/dist/{chunk-5K44HLTZ.mjs → chunk-MNWJ4EZY.mjs} +1 -1
  85. package/dist/{chunk-FETSREUN.mjs → chunk-NHP66IWR.mjs} +1 -1
  86. package/dist/{chunk-PGDE24N5.mjs → chunk-OEIJLMPI.mjs} +1 -1
  87. package/dist/{chunk-YROX2O22.mjs → chunk-PDZR3L3C.mjs} +1 -1
  88. package/dist/{chunk-6N3PX4XX.mjs → chunk-PLB7L22J.mjs} +1 -1
  89. package/dist/{chunk-LM4XFQHZ.mjs → chunk-Q4MS6OFC.mjs} +1 -1
  90. package/dist/{chunk-7JDX4E65.mjs → chunk-Q7P3Q5YX.mjs} +1 -1
  91. package/dist/{chunk-ZHEHPMBK.mjs → chunk-QNECWMGR.mjs} +1 -1
  92. package/dist/{chunk-YI43RG4P.mjs → chunk-QP7BOHE4.mjs} +1 -1
  93. package/dist/chunk-QVGOPHOF.mjs +2 -0
  94. package/dist/{chunk-DAZL73VK.mjs → chunk-RRKJMHNX.mjs} +2 -2
  95. package/dist/chunk-S3SX3COT.mjs +20 -0
  96. package/dist/{chunk-HDWTZ763.mjs → chunk-TKWEX4FD.mjs} +2 -2
  97. package/dist/{chunk-YLPSMDIS.mjs → chunk-ULXSPX5H.mjs} +2 -2
  98. package/dist/chunk-USIHBCSW.mjs +15 -0
  99. package/dist/{chunk-TR7TWGHB.mjs → chunk-VPMRP2TL.mjs} +1 -1
  100. package/dist/{chunk-ZQS6H473.mjs → chunk-VRPVVMRB.mjs} +1 -1
  101. package/dist/{chunk-F6HVDZR4.mjs → chunk-VZ2RQ3AM.mjs} +1 -1
  102. package/dist/{chunk-R2ZDLJYT.mjs → chunk-W5NPH5UA.mjs} +1 -1
  103. package/dist/chunk-WFGPMCTZ.mjs +4 -0
  104. package/dist/chunk-XZCFPKGO.mjs +2 -0
  105. package/dist/{chunk-4OKWZY5E.mjs → chunk-YN37ZDLW.mjs} +1 -1
  106. package/dist/chunk-ZFGMJVJC.mjs +2 -0
  107. package/dist/cli.mjs +1 -1
  108. package/dist/server.mjs +1 -1
  109. package/dist/worker.mjs +1 -1
  110. package/kit/report.css +3 -3
  111. package/kit/runtime.js +12 -2
  112. package/kit/state.js +2 -0
  113. package/kit/ui.js +5 -1
  114. package/package.json +1 -1
  115. package/release.json +7 -7
  116. package/skill/SKILL.md +13 -12
  117. package/skill/references/building-blocks.md +1 -1
  118. package/skill/references/extensions.md +48 -8
  119. package/web/assets/index-FLb9jCfl.css +1 -0
  120. package/web/assets/index-czjrXVjf.js +15 -0
  121. package/web/index.html +2 -2
  122. package/dist/chunk-5XA2ZBAE.mjs +0 -8
  123. package/dist/chunk-67N2QJYT.mjs +0 -2
  124. package/dist/chunk-6KBYRA2C.mjs +0 -2
  125. package/dist/chunk-DJISHPUL.mjs +0 -3
  126. package/dist/chunk-EKNHM3P4.mjs +0 -2
  127. package/dist/chunk-EP25HDAJ.mjs +0 -2
  128. package/dist/chunk-GHOYKMQ3.mjs +0 -4
  129. package/dist/chunk-IV64FFI4.mjs +0 -2
  130. package/dist/chunk-J43Z6LSS.mjs +0 -2
  131. package/dist/chunk-JA7G53PC.mjs +0 -2
  132. package/dist/chunk-JZT7I2OJ.mjs +0 -2
  133. package/dist/chunk-L2SUIS5S.mjs +0 -2
  134. package/dist/chunk-L7UP52JO.mjs +0 -2
  135. package/dist/chunk-MTYYHM2G.mjs +0 -15
  136. package/dist/chunk-MXUBKDRO.mjs +0 -15
  137. package/dist/chunk-NAMN3RAF.mjs +0 -2
  138. package/dist/chunk-ORID3AE7.mjs +0 -166
  139. package/dist/chunk-SWUTTZCN.mjs +0 -2
  140. package/dist/chunk-U7NZI6N4.mjs +0 -4
  141. package/dist/chunk-UJQJKNGK.mjs +0 -2
  142. package/dist/chunk-ZWWC4KLF.mjs +0 -20
  143. package/web/assets/index-BM_K-Auu.css +0 -1
  144. package/web/assets/index-DRslOBiv.js +0 -15
package/web/index.html CHANGED
@@ -5,8 +5,8 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1" />
6
6
  <title>Gallery</title>
7
7
  <link rel="icon" href="data:," />
8
- <script type="module" crossorigin src="/assets/index-DRslOBiv.js"></script>
9
- <link rel="stylesheet" crossorigin href="/assets/index-BM_K-Auu.css">
8
+ <script type="module" crossorigin src="/assets/index-czjrXVjf.js"></script>
9
+ <link rel="stylesheet" crossorigin href="/assets/index-FLb9jCfl.css">
10
10
  </head>
11
11
  <body class="preload">
12
12
  <div id="root"></div>
@@ -1,8 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{spawn as J}from"node:child_process";import P from"node:fs";import m from"node:fs/promises";import Q from"node:os";import k from"node:path";import{escapeMarkup as X}from"../browser/shared/escape.mjs";import{spawn as C}from"node:child_process";import{existsSync as H,readFileSync as M}from"node:fs";import w from"node:path";var V=e=>!["","0",void 0].includes(e),z=(e,r)=>(r.PATH??"").split(w.delimiter).some(t=>t&&H(w.join(t,e))),U=()=>{try{return process.platform==="linux"&&/microsoft/i.test(M("/proc/version","utf8"))}catch{return!1}};function K(e,{platform:r=process.platform,env:t=process.env,wsl:s=U()}={}){let n=encodeURI(e);return V(t.GALLERY_NO_BROWSER)?{skip:"GALLERY_NO_BROWSER is set"}:r==="win32"?{command:w.join(t.SystemRoot||t.windir||"C:\\Windows","System32","rundll32.exe"),args:["url.dll,FileProtocolHandler",n]}:r==="darwin"?{command:"open",args:[n]}:s?{command:"cmd.exe",args:["/c","start",'""',n.replace(/[&^]/g,"^$&")]}:!t.DISPLAY&&!t.WAYLAND_DISPLAY?{skip:"no display here (neither DISPLAY nor WAYLAND_DISPLAY is set)"}:z("xdg-open",t)?{command:"xdg-open",args:[n]}:{skip:"xdg-open is not installed"}}var q="Opened it in the default browser (if that is not Chrome or Edge, open the address there to edit).",T=e=>e.opened?q:`Not opened in a browser: ${e.why}.`;async function O(e,r){let t=K(e,r);return t.skip?{opened:!1,why:t.skip}:new Promise(s=>{let n;try{n=C(t.command,t.args,{detached:!0,stdio:"ignore",windowsHide:!0})}catch(o){return s({opened:!1,why:`${w.basename(t.command)} did not start (${o.code??o.message})`})}n.once("error",o=>s({opened:!1,why:`${w.basename(t.command)} did not start (${o.code??o.message})`})),n.once("spawn",()=>{n.unref(),s({opened:!0})})})}import{packageRoot as Z,previewLogFile as f,projectRoot as G,release as I,reportsDirectory as h}from"../browser/shared/paths.mjs";import{fullAddress as ee}from"../browser/shared/page-address.mjs";import{findPreviewServer as te,galleryVersion as F,portIsFree as re,previewServerFor as ne,readAnnouncement as oe}from"../browser/shared/preview-server.mjs";import{documentLinks as se}from"../browser/shared/reports.mjs";import{documentDirectory as ie,documentFiles as ae,layoutOf as ce}from"../browser/shared/workspace.mjs";var $="\u4EA4\u7ED9\u7528\u6237\uFF08\u73B0\u5728\u5C31\u628A\u8FD9\u4E2A\u5730\u5740\u7ED9\u7528\u6237\uFF1B\u7528 Chrome \u6216 Edge \u6253\u5F00\uFF09\uFF1A",le="Agent \u81EA\u7528\uFF08\u53EA\u6709\u6587\u6863\u9875\uFF0C\u4E0D\u4EA4\u7ED9\u7528\u6237\uFF09\uFF1A",de=e=>`send the user ${e} now, in a message of its own, before any other step; then `;function Ve(e,r){let t=e.at(-1)??"";return`Next: ${t.startsWith($)?de(t.slice($.length)):""}${r}`}async function ze(e,r){let t=e.at(-1)??"";return t.startsWith($)?r.has("--no-browser")?"Not opened in a browser (--no-browser).":T(await O(t.slice($.length))):null}var D="GALLERY_NO_PREVIEW",pe=e=>!["","0",void 0].includes(e),Ue=e=>e.has("--no-preview")||pe(process.env[D]),ue=4317,fe=20,me=(e=process.env)=>{let r=Number(e.GALLERY_PORT);return Number.isInteger(r)&&r>0&&r<65536?r:ue},we=6e4,he=5*1024*1024,$e=k.join(G,"node_modules","vite","bin","vite.js"),ye=k.join(Z,"dist","server.mjs"),ge=e=>new Promise(r=>setTimeout(r,e)),A={reportsDirectory:h},Y=ce(h),R=(e,r)=>`http://127.0.0.1:${e}/generated/${r}.html`,ve=(e,r)=>`${R(e,r)}?agent`,j=e=>`http://127.0.0.1:${e}/`,xe=(e,r)=>se().then(({links:t})=>t,()=>null).then(t=>ee(`http://127.0.0.1:${e}`,r,t));async function ke({first:e=me(),count:r=fe}={}){let t=Number((await m.readFile(Y.lastPortFile,"utf8").catch(()=>"")).trim()),s=Array.from({length:Math.max(0,r)},(n,o)=>e+o);return Number.isInteger(t)&&t>0&&t<65536?[t,...s.filter(n=>n!==t)]:s}async function Le(){return await m.mkdir(k.dirname(f),{recursive:!0}),await m.stat(f).then(r=>r.size,()=>0)>he&&await m.rename(f,`${f}.1`).catch(()=>{}),P.openSync(f,"a")}async function Se(e,r){if(!I){let{writeSharedAssets:p}=await import("./chunk-WQDQWCX5.mjs");await p()}let t=await Le();P.writeSync(t,`
3
- [${new Date().toISOString()}] ${r}: Gallery ${F} on 127.0.0.1:${e} for ${h}
4
- `);let[s,n]=I?[[ye,"--port",String(e)],Q.homedir()]:[[$e,"--host","127.0.0.1","--port",String(e),"--strictPort"],G],o=J(process.execPath,s,{cwd:n,env:{...process.env,GALLERY_WORKSPACE:k.resolve(h),GALLERY_SERVER_KIND:"cli"},detached:!0,stdio:["ignore",t,t],windowsHide:!0});return P.closeSync(t),o.unref(),o}async function be({slug:e=null,command:r=`gallery open${e?` ${e}`:""}`,ports:t=null,starting:s=we,baseline:n=!1}={}){let o=()=>!0;if(e){let a=ae(ie(e,h)),c=await m.readFile(a.html,"utf8").catch(()=>null);if(c===null)return{ok:!1,reason:"missing",message:`No document "${e}": ${a.html} does not exist (gallery new ${e} "<\u6807\u9898>" makes one; gallery list lists those there are).`};n&&await import("./chunk-FDMAXMQA.mjs").then(({previewBaseline:x})=>x(e,c));let i=await m.readFile(a.json,"utf8").then(JSON.parse).catch(()=>({})),v=[/<title>([^<]*)<\/title>/i.exec(c)?.[1]?.trim(),typeof i.title=="string"?i.title.trim():""].filter(Boolean);o=x=>v.length===0||v.some(_=>x.includes(_)||x.includes(X(_)))}let p=t??await ke(),L=p.length?`${Math.min(...p)} to ${Math.max(...p)}`:"none",S=`gallery open${e?` ${e}`:""}`,E=async(a,c=[])=>{let i=await ne({...A,ports:p.slice(a),start:v=>Se(v,r)});return i.busy?.newer?{failed:{ok:!1,reason:"newer",message:`A newer Gallery (${i.busy.version}) serves this workspace (port ${i.busy.port}, pid ${i.busy.pid}) and gave no answer in 10s; this is Gallery ${F}. Update this one (npm i -g @heycys/gallery@latest), or run ${S} again in a while.`}}:i.busy?{failed:{ok:!1,reason:"busy",message:`This workspace's Gallery server (port ${i.busy.port}, pid ${i.busy.pid}) took the request and gave no answer in 10s: it is busy or stuck. Run ${S} again in a while, or stop that process first (gallery stop): a second server of this workspace is not started beside it.`}}:i.stuck?{failed:{ok:!1,reason:"stuck",message:`An older Gallery's server serves this workspace and did not stop: ${i.stuck.message}`}}:i.port===null?{failed:{ok:!1,reason:"ports",message:`No server of this workspace runs, and no port from ${L} is free to start one on: stop a server on one of them (or name another first port: GALLERY_PORT=<n>), then run ${S}.`}}:{...i,passed:[...c,...i.passed]}},u=await E(0);if(u.failed)return u.failed;let{port:l,started:d,passed:b,replaced:W}=u,y=u.running??null,N=Date.now()+s,g="",B=async()=>{if(e){let c=await fetch(`${R(l,e)}?present`,{signal:AbortSignal.timeout(5e3)}).catch(()=>null),i=c?.ok?await c.text():"";return g=c?i?`HTTP ${c.status} without the title`:`HTTP ${c.status}`:"no answer",!!(i&&o(i))}let a=await fetch(`http://127.0.0.1:${l}/__gallery/workspace/info`,{signal:AbortSignal.timeout(5e3)}).catch(()=>null);return g=a?`HTTP ${a.status}`:"no answer",!!a?.ok};for(;;await ge(300)){if(Date.now()>N)return{ok:!1,reason:"timeout",message:`${e?R(l,e):j(l)} did not answer${e?" with the document's title":""} in ${s/1e3}s (${g})${d?`; the server's output is in ${f}`:""}.`};if(d){let a=await te({...A,answering:!0});if(a&&a.pid!==d.pid){if(d.exitCode===null)try{process.kill(d.pid)}catch{}({port:l}=a),y={pid:a.pid,kind:(await oe(A))?.kind??"cli",version:null},d=null;continue}if(!a&&d.exitCode===null){g="the server started has not announced itself yet";continue}if(!a){if(!await re(l)){if(u=await E(p.indexOf(l)+1,[...b,`${l} (taken by another program while the server started)`]),u.failed)return u.failed;({port:l,started:d,passed:b}=u),y=u.running??null,N=Date.now()+s;continue}let c=await m.readFile(f,"utf8").catch(()=>"");return{ok:!1,reason:"stopped",message:`The Gallery server on port ${l} stopped (exit ${d.exitCode}). Its last words (${f}):
5
- ${c.split(`
6
- `).slice(-15).join(`
7
- `)}`}}}if(await B())break}return await m.writeFile(Y.lastPortFile,`${l}
8
- `).catch(()=>{}),{ok:!0,port:l,pid:d?.pid??y?.pid??null,kind:y?.kind??"cli",started:!!d,replaced:W??null,passed:b}}var Ae=e=>e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`;function Pe({port:e,pid:r,kind:t,started:s,replaced:n,passed:o=[]}){let p=[`pid ${r}`,...t==="dev"?["npm run dev's"]:[],...s?[`started now${o.length?`, after passing over ${Ae(o)}`:""}`]:[],...n?[`it replaced Gallery ${n.version??"an older version"}'s server, pid ${n.pid}`]:[]],L=s?`; its log: ${f}`:"";return`This workspace's Gallery server runs on port ${e} (${p.join(", ")}${L}). This command is done; the server runs on after it (nothing to wait for or keep running).`}async function Re(e,r,t=null){return[Pe(r),...e?[`${le}${ve(r.port,e)}`]:[],`${$}${e?await xe(r.port,{slug:e,block:t}):j(r.port)}`]}async function Ke(e,{skipped:r,command:t,ports:s=null}){let n=`gallery open ${e} starts it and prints the address to give the user`;if(r)return[`Preview: not started (--no-preview or ${D}): ${n}.`];let o=await be({slug:e,command:t,ports:s});return o.ok?Re(e,o):[`Preview: not started: ${o.message}`,`When that is fixed, ${n}.`]}export{$ as a,le as b,Ve as c,ze as d,Ue as e,ve as f,j as g,ke as h,be as i,Pe as j,Re as k,Ke as l};
@@ -1,2 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{h as p}from"./chunk-ZWWC4KLF.mjs";import{g as k}from"./chunk-ZQS6H473.mjs";import{g as b}from"./chunk-MXUBKDRO.mjs";import{k as d}from"./chunk-6N3PX4XX.mjs";import v from"node:fs/promises";import h from"node:path";import{editStateDirectory as m,reportsDirectory as f}from"../browser/shared/paths.mjs";import{findPreviewServer as $}from"../browser/shared/preview-server.mjs";import{documentDirectory as S,documentFiles as g,isDocumentSource as j}from"../browser/shared/workspace.mjs";var u=e=>h.resolve(e),D=e=>h.basename(g(h.dirname(e)).json),N={busy:"it kept changing while it was being written (an Agent writing it?); nothing written. Run the export again.",timeout:"the workspace's Gallery server did not answer in 30s; nothing written. Run the export again."};async function w(e,n,o="hand-in",l=3e4){let t=`127.0.0.1:${e.port}`,s;try{s=await fetch(`http://${t}/__gallery/edit/${o}`,{method:"POST",headers:{"Content-Type":"application/json",Origin:`http://${t}`,"X-Gallery-Token":e.token},body:JSON.stringify({slug:n,workspace:f}),signal:AbortSignal.timeout(l)})}catch(a){return a.name==="TimeoutError"?{ok:!1,reason:"timeout"}:null}let i=await s.json().catch(()=>null);return typeof i?.ok!="boolean"||["elsewhere","token","host","origin"].includes(i.reason)?null:i}async function P(e){let n=await $({reportsDirectory:f}),o=null,l=[],t=new Map,s=[];for(let i of e){let{html:a,json:c}=g(S(i,f)),r=n?await w(n,i):null;if(r===null&&(o??=p({reportsDirectory:f,stateDirectory:m,finish:d}),r=await o.handIn(i),r.ok&&await o.settleNotes(i)),!r.ok){r.reason!=="missing"&&t.set(i,[`${u(a)} was not handed in: ${N[r.reason]??r.message??r.reason}`]);continue}if(r.repeated?.length){t.set(i,b(r.repeated));continue}s.push(...L(a,r)),r.written&&(r.changes.length&&s.push(...k(a,r.changes,{reread:!1})),r.added&&s.push(...T(a,r.given,r.added)),l.push(u(a))),O(r)&&l.push(u(c))}return{written:l,failures:t,lines:s}}async function _(e){let n=await $({reportsDirectory:f});if(n){for(let o of e)if(await w(n,o,"settle")===null)return}}async function C(e,{wait:n=3e4}={}){try{let o=await $({reportsDirectory:f}),l=o?await w(o,e,"round",n):null;return l!==null?l.ok?l.ended===!0:null:await p({reportsDirectory:f,stateDirectory:m,finish:d}).beginRound(e)}catch{return null}}async function H(e){try{let n=p({reportsDirectory:f,stateDirectory:m,finish:d}),{html:o}=g(S(e,f));await n.noteTaken(e,await v.readFile(o,"utf8"))}catch{}}var O=({title:e=null,icon:n=null})=>!!(e&&typeof e.from=="string"&&e.from!==e.to||n&&!n.missing),x=10;function T(e,n,o=n?.length??0,{pending:l=!1}={}){let t=`${o} block${o===1?"":"s"}`;if(l){let i=[`ids ${u(e)}: ${t} without an id yet: the export gives ${o===1?"it":"each"} one`];return o>x?i:[...i,...n.map(({line:a,tag:c})=>` line ${a} ${c}`)]}let s=[`ids ${u(e)}: ${t} given an id`];return!n||o>x?s:[...s,...n.map(({line:i,tag:a,id:c})=>` line ${i} ${a} \u2192 ${c}`)]}function L(e,{title:n=null,icon:o=null}={},{pending:l=!1}={}){let t=u(h.dirname(e)),s=D(e),i=(c,r,y)=>l?`${c} not ${r} yet (${y}): the export writes ${c.includes(" and ")?"them":"it"}`:`${c} written ${r}: ${y}`,a=[];if(n){let c=[...n.page?["<title>"]:[],...typeof n.from=="string"&&n.from!==n.to?[`${s}'s title`]:[]];c.length&&a.push(`title ${t}: ${i(c.join(" and "),"as its h1 says it",JSON.stringify(n.to))}`)}return o?.missing?a.push(`icon ${t}: ${s} has the icon ${JSON.stringify(o.from)} and the page's header none: write it there (<div class="doc-icon">\u2026</div> before the h1) or take "icon" out of ${s} (the export leaves ${s}'s as it is)`):o&&a.push(`icon ${t}: ${i(`${s}'s icon`,"as its header has it",o.to===null?"none":JSON.stringify(o.to))}`),a}function K(e,{by:n="this export"}={}){let o=e.length===1,l=[...e.filter(t=>j(h.basename(t))).map(t=>h.basename(t)).filter((t,s,i)=>i.indexOf(t)===s).map(t=>`${t}: the kit's markup, block ids`),...e.filter(t=>/^(doc|report)\.json$/.test(h.basename(t))).map(t=>h.basename(t)).filter((t,s,i)=>i.indexOf(t)===s).map(t=>`${t}: the title or icon said above`)];return`Re-read ${e.join(", ")} before editing ${o?"it":"them"}: ${n} wrote ${o?"it":"them"} (${l.join("; ")}).`}export{P as a,_ as b,C as c,H as d,T as e,L as f,K as g};
@@ -1,2 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{a,b}from"./chunk-OEXWRJME.mjs";import"./chunk-EAIFITAV.mjs";import"./chunk-67N2QJYT.mjs";import"./chunk-ZWWC4KLF.mjs";import"./chunk-IA4PSIMD.mjs";import"./chunk-F4ZA6JRZ.mjs";import"./chunk-7M2BQQGZ.mjs";import"./chunk-ITOH5EGO.mjs";import"./chunk-ZQS6H473.mjs";import"./chunk-4OZWXZE5.mjs";import"./chunk-MXUBKDRO.mjs";import"./chunk-HXG7EOPJ.mjs";import"./chunk-ZTHICSSF.mjs";import"./chunk-6N3PX4XX.mjs";import"./chunk-PAREWQGB.mjs";import"./chunk-BFJGHSQN.mjs";import"./chunk-U5XL7D6A.mjs";import"./chunk-HYMEEXKN.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-R2ZDLJYT.mjs";import"./chunk-VFX2KNHP.mjs";import"./chunk-VS7JIGJW.mjs";import"./chunk-HDWTZ763.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";export{a as noDocuments,b as run};
@@ -1,3 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{b as E}from"./chunk-ZQS6H473.mjs";import{g as M}from"./chunk-HXG7EOPJ.mjs";import{a as O}from"./chunk-HYMEEXKN.mjs";import{e as I,j as S}from"./chunk-VFX2KNHP.mjs";import d from"node:fs/promises";import b from"node:path";import{isInstance as T}from"../browser/shared/components/index.mjs";import{ATTRIBUTE as _}from"../browser/shared/components/installed.mjs";import{exportSourceOf as q}from"../browser/shared/export-wrap.mjs";import{sha256 as w}from"../browser/shared/files.mjs";import{attr as g,hasClass as y}from"../browser/shared/html-tree.mjs";import{editStateDirectory as F,exportsDirectory as z,qaDirectory as G,reportsDirectory as H}from"../browser/shared/paths.mjs";import{documentDirectory as K,documentFiles as Q}from"../browser/shared/workspace.mjs";function V(t,e=null){return t.tagName==="figure"&&y(t,"doc-figure")||t.tagName==="div"&&(y(t,"doc-code")||y(t,"doc-diff"))||e===D||T(t)||y(t,"doc-flow")||y(t,"doc-sheet-shell")||g(t,"data-doc-sheets")!==void 0?0:t.tagName==="figure"||y(t,"doc-columns")?1:y(t,"doc-table-wrap")?2:3}function X(t){let e=new Map,n=new Map;for(let i of I(t).units)i.blockId&&!n.has(i.blockId)&&n.set(i.blockId,i.kind);let a=new Map,r=new Map,o=new Map,f=i=>!!i.tagName&&g(i,"data-block-id")!==void 0,u=(i,c)=>{if(i.nodeName==="#text")return i.value;if(!i.tagName||i.tagName==="template")return"";let s=g(i,"data-doc-chart-data")?.trim();s&&a.get(c).push(s);let l=g(i,"data-doc-chart-source")?.trim();l&&!r.has(l)&&r.set(l,c);let h=i.attrs.map(({name:k,value:N})=>`${k}="${N}"`).sort().join(" ");return`<${i.tagName} ${h}>${(i.childNodes??[]).map(k=>f(k)?"":u(k,c)).join("")}</${i.tagName}>`},m=(i,c)=>{for(let s of i.childNodes??[]){if(!s.tagName||s.tagName==="template")continue;let l=g(s,"data-block-id"),h=c;if(l!==void 0&&!e.has(l)){let k=[s.tagName,...(g(s,"class")??"").split(/\s+/).filter(Boolean).slice(0,1)].join("."),N=o.get(c)??0;o.set(c,N+1),a.set(l,[]);let v=V(s,n.get(l)),x=s.sourceCodeLocation,U=x?(x.endOffset??x.startTag?.endOffset??x.startOffset)-x.startOffset:0,B=u(s,l).replace(R," ");e.set(l,{hash:w(B).slice(0,16),bare:w(B.replace(`data-block-id="${l}"`,"")).slice(0,16),rank:v,card:v<3,whole:n.get(l)===D,figure:n.get(l)===tt,tag:k,parent:c,at:N,size:U,package:T(s)?g(s,_)??null:null}),h=l}m(s,h)}};m(O(t),null);let p=new Map([...e].map(([i,{hash:c,bare:s}])=>[i,{hash:c,bare:s}]));for(let[i,c]of a){let s=c.map(l=>p.get(r.get(l))).filter(Boolean);s.length&&(e.get(i).hash=w([p.get(i).hash,...s.map(({hash:l})=>l)].join("|")).slice(0,16),e.get(i).bare=w([p.get(i).bare,...s.map(({bare:l})=>l)].join("|")).slice(0,16))}return e}function Y(t){let e=[],n=a=>{for(let r of a.childNodes??[])if(!(!r.tagName||r.tagName==="template"||g(r,"data-block-id")!==void 0))if(r.tagName==="script"||r.tagName==="style"){let o=r.attrs.map(({name:f,value:u})=>`${f}="${u}"`).sort().join(" ");e.push(`<${r.tagName} ${o}>${(r.childNodes??[]).map(f=>f.value??"").join("")}`.replace(R," "))}else n(r)};return n(O(t)),e.length?w(e.join("|")).slice(0,16):""}var Z=t=>Object.fromEntries(M(t).map(({id:e,stamp:n})=>[e,n])),D="block",tt="figure",R=/[ \t\n\f\r]+/g,et=["export","preview"];function st(t){if(t==null)return null;try{let{blocks:e,places:n,moved:a,unseen:r,from:o,time:f,idless:u,page:m,packages:p}=JSON.parse(t)??{};if(!e||typeof e!="object"||Array.isArray(e))return null;let i=n&&typeof n=="object"&&!Array.isArray(n)?n:{},c=s=>Array.isArray(s)?s.filter(l=>typeof l=="string"):[];return{blocks:Object.fromEntries(Object.entries(e).filter(([,s])=>typeof s=="string")),places:Object.fromEntries(Object.entries(i).filter(([,s])=>Array.isArray(s)&&s.length===2&&(s[0]===null||typeof s[0]=="string")&&Number.isInteger(s[1]))),moved:c(a),unseen:c(r),...et.includes(o)?{from:o,time:Number.isFinite(f)?f:null}:{},...c(u).length?{idless:c(u)}:{},...typeof m=="string"?{page:m}:{},...p&&typeof p=="object"&&!Array.isArray(p)?{packages:Object.fromEntries(Object.entries(p).filter(([,s])=>typeof s=="string"))}:{}}}catch{return null}}var $="ge-idless-";function nt(t,{from:e,time:n}){let a=0,{text:r}=S(E(t).text,()=>`${$}${a++}`),o=Z(r),f={blocks:{},places:{},moved:[],unseen:[],from:e,time:n,page:Y(r),...Object.keys(o).length?{packages:o}:{}},u=[];for(let[m,{hash:p,bare:i,card:c,parent:s,at:l}]of X(r)){if(m.startsWith($)){u.push(i);continue}f.blocks[m]=p,s?.startsWith($)||(f.places[m]=[s,l]),c&&f.unseen.push(m)}return u.length?{...f,idless:u}:f}function yt(t,e){if(!e?.idless?.length)return e;let n=new Map;for(let o of e.idless)n.set(o,(n.get(o)??0)+1);let a={...e,blocks:{...e.blocks},unseen:[...e.unseen]};for(let[o,{hash:f,bare:u,card:m}]of t)Object.hasOwn(e.blocks,o)||!n.get(u)||(n.set(u,n.get(u)-1),a.blocks[o]=f,m&&a.unseen.push(o));let r=[...n].flatMap(([o,f])=>Array(f).fill(o));return r.length?a.idless=r:delete a.idless,a}var at=/<[^>]*\sdata-doc-placeholder\b/,j=t=>b.join(G,t),L=t=>b.join(j(t),"blocks.json"),P=t=>b.join(j(t),"exported.html");async function W(t){return st(await d.readFile(L(t),"utf8").catch(()=>null))!==null}async function C(t,e,n){let a=async c=>d.readFile(c).then(s=>({bytes:s,file:c}),()=>null),r=await a(P(t)),o=[r];if(e){let c=e.slice(0,16),s=b.join(F,"history",t),l=await d.readdir(s).catch(()=>[]);o.push(...await Promise.all(l.filter(h=>h.endsWith(`-${c}.html`)).map(h=>a(b.join(s,h))))),o.push(await a(b.join(F,"snapshots",`${c}.html`)))}let f=r?(await d.stat(r.file).catch(()=>null))?.mtimeMs??null:null,m=!(r&&e&&n!==null&&f!==null&&f>n&&w(r.bytes)!==e)&&e&&o.find(c=>c&&w(c.bytes)===e),p=m||r;if(!p)return null;let i=m&&n!==null?n:p===r?f??n:(await d.stat(p.file).catch(()=>null))?.mtimeMs??n;return{text:p.bytes.toString("utf8"),time:i??null}}async function A(t){let e=b.join(z,`${t}.html`),[n,a]=await Promise.all([d.readFile(e,"utf8").catch(()=>null),d.stat(e).catch(()=>null)]);return n===null||!a?null:{said:q(n),time:a.mtimeMs}}async function J(t,e,n){if(at.test(e))return!1;let a=nt(e,n);return!Object.keys(a.blocks).length&&!a.idless?!1:(await d.mkdir(j(t),{recursive:!0}),await d.writeFile(L(t),`${JSON.stringify(a)}
3
- `),!0)}async function bt(t){let e=new Map(await Promise.all(t.map(async a=>[a,await A(a).catch(()=>null)])));return{keep:async(a,r=null)=>{for(let o of a)try{if(!await W(o)){let m=e.get(o),p=await C(o,m?.said??null,m?.time??null);p&&await J(o,p.text,{from:"export",time:p.time})}let[f,u]=await Promise.all([d.readFile(Q(K(o,H)).html),r?{said:r.get(o)??null}:A(o)]);u?.said&&w(f)===u.said&&(await d.mkdir(j(o),{recursive:!0}),await d.writeFile(P(o),f))}catch{}}}}async function kt(t,e){try{if(await W(t))return!1;let n=await A(t),a=await C(t,n?.said??null,n?.time??null);return await J(t,a?.text??e,a?{from:"export",time:a.time}:{from:"preview",time:Date.now()})}catch{return!1}}export{V as a,X as b,Y as c,Z as d,et as e,st as f,nt as g,yt as h,W as i,C as j,bt as k,kt as l};
@@ -1,2 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{b as n,f as i}from"./chunk-4OZWXZE5.mjs";import"./chunk-5L7RYZCL.mjs";import{reportsDirectory as r}from"../browser/shared/paths.mjs";import{answerOf as a,readAnnouncement as d,stopServer as l}from"../browser/shared/preview-server.mjs";async function m(p){let{positional:s}=i({argv:p});if(s.length>0)throw new n(`gallery stop takes no arguments: ${s[0]}`);let o=await d({reportsDirectory:r}),t=o?await a(o,r,1e4):"no";if(t==="no")return void console.log(`No Gallery server runs for ${r}.`);t==="busy"&&(console.error(`The Gallery server on port ${o.port} (pid ${o.pid}) took the request and gave no answer in 10s: it is busy or stuck. Run gallery stop again in a while, or end process ${o.pid} yourself.`),process.exit(1)),o.kind==="dev"&&(console.error(`This workspace's server is npm run dev's (port ${o.port}, pid ${o.pid}): stop it where it runs.`),process.exit(1));let e=await l(o);e.ok||(console.error(e.message),process.exit(1)),console.log(`Stopped the server on port ${o.port} (pid ${o.pid})${e.killed?": it did not stop by itself in 10s, so its process was ended":""}.`)}export{m as run};
@@ -1,2 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{g as v,h as X}from"./chunk-AR5D57ZD.mjs";import{a as C,b as B,d as z,g as W,i as J,j as K}from"./chunk-5XA2ZBAE.mjs";import{a as w}from"./chunk-JEUK3ZO7.mjs";import{f as G}from"./chunk-QE5RG76S.mjs";import{h as F,i as H}from"./chunk-UYVCQK3H.mjs";import{a as R,e as P,f as Y}from"./chunk-J5PUIV3Y.mjs";import{a as U,b as d,f as q}from"./chunk-4OZWXZE5.mjs";import{f as L}from"./chunk-HDWTZ763.mjs";import{editStateDirectory as re,reportsDirectory as Z}from"../browser/shared/paths.mjs";import{FIRST_BOARD as le,HOME as D,createPage as ce,listPages as de,pageExists as ee,pageFiles as O,pageSlugRefused as te,pagesSettings as he,readPageMeta as ge}from"../browser/shared/pages.mjs";import{findPreviewServer as se}from"../browser/shared/preview-server.mjs";var M=(e,t)=>`${W(e)}#@${t}`,pe=(e,t)=>`http://127.0.0.1:${e}/pages/${t}`,fe="The default home page (\u9996\u9875, slug home) is not made yet: Gallery makes it, with its own cards, when its server first starts in this workspace. gallery open --no-browser starts it: run that once, then gallery page list again.";async function oe(e){return H()||ee(D,e)||he(e).homeMade||await te(D,e)?null:fe}async function ne(e,t){return(e===D?await oe(t):null)??`No custom page "${e}": ${w(O(e,t).html)} does not exist (gallery page list lists those there are).`}async function ae(e){return(await se({reportsDirectory:e,answering:!0,timeout:2e3}))?.port??null}async function we(e,[t,o,...i]){if(!t||!o?.trim()||i.length)throw new d("Name the slug and the title, the title quoted when it has spaces.");let n=await te(t,e);n&&(console.error(n),process.exit(1));let s=await ce(t,o,{root:e});console.log(`Created ${w(s.html)} and page.json`),console.log(`It is listed in the workbench's sidebar, last among the rows under \u65B0\u5EFA and \u641C\u7D22 (the user may drag it elsewhere), and shows one empty board (data-board-id="main"): use it, or write the page as you like.`);let a=await ae(e),r=`write page.html: a board of cards (each <section class="gallery-card" data-card-id="\u2026" data-x data-y data-w data-h> around one custom block's instance; gallery page add places one), or any HTML, CSS and script of your own (references/pages-and-data.md)`,c="at the end tell them where it is in the sidebar (under \u65B0\u5EFA and \u641C\u7D22, its title)";a?(console.log(`Next: send the user the address on the last line now, in a message of its own (the page is theirs to watch as its cards arrive); ${r}; ${c}.`),console.log(`${C}${M(a,t)}`)):console.log(`Next: run gallery page open ${t} --no-browser now (it starts the server) and send the user the address on its \u4EA4\u7ED9\u7528\u6237 line, in a message of its own, before you write any card (the page is theirs to watch as its cards arrive); then ${r}; ${c}.`)}async function me(e,t){if(t.length)throw new d("gallery page list takes nothing else.");let o=await de(e);console.log(`\u5DE5\u4F5C\u533A\uFF1A${w(e)}`);let i=await oe(e);o.length===0&&!i?console.log('No custom pages yet: gallery page new <slug> "<\u6807\u9898>" makes one.'):o.length>0&&console.log(`Custom pages, in the sidebar's order (${o.length}):`);let n=o.length?await ae(e):null;for(let{slug:s,title:a,icon:r}of o)console.log(`- ${s} ${r?`${r} `:""}${a}`),console.log(` \u5730\u5740\uFF1A${n?M(n,s):`/#@${s}`} ${w(O(s,e).html)}`);i&&console.log(i)}async function ue(e,[t,...o],i){if(!t||o.length)throw new d("gallery page open takes one page's slug.");await ge(t,e)||(console.error(await ne(t,e)),process.exit(1)),console.log(`\u5DE5\u4F5C\u533A\uFF1A${w(e)}`);let s=await J({command:`gallery page open ${t}`});s.ok||(console.error(s.message),process.exit(1));let a=[K(s),`${B}${pe(s.port,t)}`,`${C}${M(s.port,t)}`];for(let r of a)console.log(r);console.log(await z(a,i))}async function Q(e,t,o){let i=`127.0.0.1:${e.port}`;try{let n=await fetch(`http://${i}/__gallery/pages/${t}/cards`,{method:"POST",headers:{"Content-Type":"application/json",Origin:`http://${i}`,"X-Gallery-Token":e.token},body:JSON.stringify({...o,workspace:Z}),signal:AbortSignal.timeout(3e4)}),s=await n.json().catch(()=>null);return!s||["elsewhere","token","host","origin","unknown","method"].includes(s.reason)?null:[n.status,s]}catch{return null}}var $e=8e3,b={places:e=>`${e} is a block of documents (its manifest's places has no "page"): it does not go on a custom page.`,disabled:e=>`${e} is turned off (\u8BBE\u7F6E \u203A \u7EC4\u4EF6\u5217\u8868 \u505C\u7528): nothing of it loads, on a page or in a document.`,missing:e=>`No custom block ${e} in this workspace: gallery block list lists them.`,template:e=>`${e} has no template.html a new card can be made of (gallery block check ${e} says why).`,board:(e,t)=>`No board "${t}" on this page: its <div class="gallery-board" data-board-id="\u2026">s are the ones there are.`,cells:()=>"--x, --y, --w and --h are whole numbers (x and y from 0, w and h from 1).",busy:()=>"page.html was written again and again meanwhile: run this again.",size:()=>"page.html would grow past 1,000,000 bytes.",values:(e,t,o)=>`${e}'s setting ${o?`"${o}" `:""}does not take that value (a text of 10,000 characters at most, a number, a date, one of a select's options, a switch's true or false).`,settings:e=>`${e} has no settings, or a card of it no settings part: --set goes with a block whose manifest has some.`};function ye(e){let t=e.indexOf("--"),o=[],i=[];for(let n=0;n<e.length;n++){let s=e[n];if(t!==-1&&n>=t)i.push(s);else if(s==="--set"||s.startsWith("--set=")){let a=s==="--set"?e[n+1]:s.slice(6);s==="--set"&&(n+=1);let r=a?.indexOf("=")??-1;if(a===void 0||r<1)throw new d("--set takes a setting's key and its value: --set <key>=<value> (--set city=\u4E0A\u6D77).");o.push([a.slice(0,r),a.slice(r+1)])}else i.push(s)}return{argv:i,given:o}}var V=new Map([["true",!0],["yes",!0],["on",!0],["1",!0],["false",!1],["no",!1],["off",!1],["0",!1]]);function be(e,t){let o=t.settings??[],i=()=>o.length?`its settings are ${o.map(({key:s,label:a})=>`${s} (${a?.en??a?.zh??s})`).join(", ")}`:"it has no settings",n={};for(let[s,a]of e){let r=o.find(c=>c.key===s);if(!r)throw new d(`${t.id} has no setting "${s}": ${i()}.`);if(Object.hasOwn(n,s))throw new d(`--set ${s} is given twice.`);if(r.type==="number"){if(a.trim()!==""&&!Number.isFinite(Number(a)))throw new d(`The setting ${s} of ${t.id} is a number: --set ${s}=<number>, or --set ${s}= for none.`);n[s]=a.trim()===""?null:Number(a)}else if(r.type==="switch"){if(!V.has(a.trim().toLowerCase()))throw new d(`The setting ${s} of ${t.id} is a switch: --set ${s}=true or --set ${s}=false.`);n[s]=V.get(a.trim().toLowerCase())}else if(r.type==="select"){if(!r.options.includes(a))throw new d(`The setting ${s} of ${t.id} is one of ${r.options.join(", ")}: --set ${s}=<one of them>.`);n[s]=a}else if(r.type==="date"){if(a!==""&&!/^\d{4}-\d{2}-\d{2}$/.test(a))throw new d(`The setting ${s} of ${t.id} is a date, written YYYY-MM-DD: --set ${s}=2027-02-06.`);n[s]=a}else n[s]=a}return n}function ke(e,t){let o=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return(e.settings??[]).filter(i=>i.required&&i.type!=="switch").filter(({key:i,default:n})=>{let s=Object.hasOwn(o,i)?o[i]:n;return s==null||typeof s=="string"&&s.trim()===""}).map(({key:i,label:n})=>({key:i,label:n?.en??n?.zh??i,zh:n?.zh??null}))}async function xe(e,[t,o,...i],n,s,a,r=[]){if(!t||!o||i.length)throw new d("gallery page add takes a page's slug and a block's id (gallery block list lists them).");let c={};for(let l of["x","y","w","h"]){let g=s.get(`--${l}`);if(g!==void 0){if(!/^\d+$/.test(g)||(l==="w"||l==="h")&&Number(g)<1)throw new d(b.cells());c[l]=Number(g)}}if(c.x===void 0!=(c.y===void 0))throw new d("--x and --y go together: a place is both.");ee(t,e)||(console.error(await ne(t,e)),process.exit(1));let k=o.includes("/")?null:P(o),h=o.includes("/")?o:k?k.id:o,m=L(e),u=m.packages.get(h);if(!u){let l=Y(h)?P(h):null;m.settings.disabled.includes(h)?console.error(b.disabled(h)):console.error(l?`${h} is one of Gallery's own blocks, not yet in this workspace: gallery block add ${l.pack===R?l.name:l.id} puts it in; then run this again.`:m.problems.has(h)?`${h} does not load (gallery block check ${h} says why).`:b.missing(h)),process.exit(1)}u.places.includes("page")||(console.error(b.places(h)),process.exit(1));let p=s.get("--board"),y=r.length?be(r,u):null,N={op:"add",block:h,...p?{board:p}:{},...c,...y?{settings:y}:{},agent:!0},j=await se({reportsDirectory:e}),x=j?await Q(j,t,N):null;for(let l=0;x?.[1]?.reason==="missing"&&l<$e/250;l++)await new Promise(g=>setTimeout(g,250)),x=await Q(j,t,N);let[ie,f]=x??await F({root:e,stateDirectory:re,catalog:()=>m}).apply(t,N);if(!f?.ok){let l=f?.reason;console.error(b[l]?.(h,p??le,f?.message)??`Not added (${ie}: ${l??"no answer"}${f?.message?`: ${f.message}`:""}).`),process.exit(1)}let $=f.cards.find(l=>l.id===f.card),I=(f.pushed??[]).map(l=>f.cards.find(g=>g.id===l)).filter(Boolean);console.log(`Added a card of ${h} to ${w(O(t,e).html)}${x?" (through the workspace's running server: an open page shows it at once)":""}:`),console.log(` data-card-id="${$.id}" on board ${$.board}: x ${$.x}, y ${$.y}, w ${$.w}, h ${$.h}${f.measure?" (its block gives no height: 2 cells, --h sets another)":""}`),I.length&&console.log(` Pushed down under it, as it met them: ${I.map(l=>`${l.id} (y ${l.y})`).join(", ")}; no card moved up.`),y&&console.log(` Settings written with it: ${Object.entries(y).map(([l,g])=>`${l}=${JSON.stringify(g)}`).join(", ")}`),console.log(y?"The rest of its data is as the block's template writes it, in the card's instance: write it there if it is to hold something else, leaving every other card as it is.":"Its data is as the block's template writes it, in the card's instance: write it there if it is to hold something else, leaving every other card as it is.");let S=ke(u,{...y??{}});if(S.length){let l=S.map(({key:g,label:T,zh:E})=>`${g} (${E&&E!==T?`${T}, ${E}`:T})`).join(", ");console.log(`${h} needs its setting ${l} before the card shows anything, and this card has none: ask the user for it, or take it from what the workspace says (\u5199\u4F5C\u504F\u597D, the documents) and tell them in the handoff which you did. Give it with the add (${S.map(({key:g})=>`--set ${g}=<value>`).join(" ")}); for this card, write it in its settings part of ${w(O(t,e).html)} (the <script type="application/json"> of data-card-id="${$.id}": {"${S[0].key}":"\u2026"}), re-reading the page right before, or the user fills it in on the card (the grip at its top right \u203A \u8BBE\u7F6E\u2026).`)}}var _={new:we,list:me,open:ue,add:xe,try:async(e,t,o,i,n)=>(await import("./chunk-J43Z6LSS.mjs")).pageTryCommand(e,{named:t,values:i,seconds:n,keep:o.has("--keep"),replace:o.has("--replace")}),check:async(e,t)=>(await import("./chunk-YLPSMDIS.mjs")).pageCheckCommand(e,t)},A=["--board","--x","--y","--w","--h"];async function Ie(e){try{return await Se(e)}catch(t){throw t instanceof d&&e.find(o=>!U(o))==="try"&&(t.synopsis=G),t}}async function Se(e){let{argv:t,seconds:o}=X(e),{argv:i,given:n}=ye(t),{positional:s,options:a,values:r}=q({options:["--no-browser","--keep","--replace"],values:[...A,...v],argv:i}),[c,...k]=s,h=Object.keys(_).join(", ");if(!c)throw new d(`Say what to do: ${h}.`);if(!Object.hasOwn(_,c))throw new d(`No such page command: ${c} (${h}).`);if(a.has("--no-browser")&&c!=="open")throw new d(`--no-browser goes with open, not ${c}.`);let m=[...v.filter(p=>r.has(p)),...Object.keys(o).filter(p=>!r.has(p)),...a.has("--keep")?["--keep"]:[],...a.has("--replace")?["--replace"]:[]];if(m.length&&c!=="try")throw new d(`${m[0]} goes with try, not ${c}.`);let u=A.filter(p=>r.has(p));if(u.length&&c!=="add")throw new d(`${u.join(", ")} go with add, not ${c}.`);if(n.length&&c!=="add")throw new d(`--set goes with add, not ${c}.`);return _[c](Z,k,a,new Map([...r].filter(([p])=>c==="try"?v.includes(p):A.includes(p))),o,n)}export{M as a,pe as b,fe as c,ne as d,ye as e,be as f,ke as g,Ie as h};
@@ -1,4 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{a as w,b as k,c as f,g as u}from"./chunk-QE5RG76S.mjs";import{readFileSync as x,realpathSync as E}from"node:fs";import p from"node:path";import{fileURLToPath as $}from"node:url";var S=p.dirname($(import.meta.url));function v(t=S){for(let e=t;;e=p.dirname(e)){try{let a=JSON.parse(x(p.join(e,"package.json"),"utf8"));if(a.name==="@heycys/gallery")return a.version}catch{}if(p.dirname(e)===e)return"0.0.0"}}var O={init:()=>import("./chunk-F6HVDZR4.mjs"),new:()=>import("./chunk-LM4XFQHZ.mjs"),import:()=>import("./chunk-ZDLPUOAG.mjs"),open:()=>import("./chunk-5K44HLTZ.mjs"),serve:()=>import("./chunk-U7NZI6N4.mjs"),stop:()=>import("./chunk-EKNHM3P4.mjs"),check:()=>import("./chunk-6KBYRA2C.mjs"),export:()=>import("./chunk-CMA72MAG.mjs"),qa:()=>import("./chunk-TR7TWGHB.mjs"),list:()=>import("./chunk-ZHEHPMBK.mjs"),workspaces:()=>import("./chunk-MN7BZL4R.mjs"),move:()=>import("./chunk-BZ5RAF7L.mjs"),set:()=>import("./chunk-YNAWBAYN.mjs"),link:()=>import("./chunk-JZT7I2OJ.mjs"),extension:()=>import("./chunk-L7UP52JO.mjs"),block:()=>import("./chunk-PGDE24N5.mjs"),page:()=>import("./chunk-UJQJKNGK.mjs"),skill:()=>import("./chunk-POTA2FV4.mjs")},j=new Set(["stop","init","skill","workspaces"]),N=(t,e)=>`${t.split(`
3
- `)[0]} (gallery ${e?`${e} --help`:"help"} says more)`,g=t=>/^--.|^-[A-Za-z]/.test(t);function A(t){let e=t.indexOf("--"),a=e===-1?t:t.slice(0,e),h=e===-1?[]:t.slice(e),n=[],s=null;for(let r=0;r<a.length;r++){let o=a[r];if(o==="--workspace"||o.startsWith("--workspace=")){let c=o.includes("=")?o.slice(o.indexOf("=")+1):r+1<a.length&&!g(a[r+1])?a[++r]:"";if(!c)return{error:"--workspace takes a folder: --workspace <dir>",usage:u};if(s!==null&&p.resolve(s)!==p.resolve(c))return{error:`Two workspaces named: ${s} and ${c}.`,usage:u};s=c;continue}n.push(o)}if(n[0]==="--version"||n[0]==="-v"||n[0]==="-V")return n.length===1&&h.length===0?{version:!0}:{error:"--version takes nothing else.",usage:u};if(n.length===0||n[0]==="help"||n[0]==="--help"||n[0]==="-h"){let r=n[0]==="help"?n[1]:void 0;return r===void 0?{help:u}:Object.hasOwn(f,r)?{help:f[r]}:{error:`No such command: ${r} (${w.join(", ")}).`,usage:u}}let[d,...m]=n,l=k[d]??d;if(!Object.hasOwn(O,l))return{error:g(l)?`Unknown option: ${l} (the command comes first: gallery <command> [options]).`:`No such command: ${l} (${w.join(", ")}).`,usage:u};let i=[...m,...h];if(m.some(r=>r==="--help"||r==="-h"))return{help:f[l]};if(l==="init"){let r=new Set(["--from","--name"]),o=[];for(let c=0;c<m.length;c++)r.has(m[c])?c++:g(m[c])||o.push(m[c]);if(o.push(...h.slice(1)),o.length>1)return{error:"Name one folder at most.",usage:f.init,command:l};if(o.length===1){if(s!==null&&p.resolve(s)!==p.resolve(o[0]))return{error:`Two workspaces named: ${o[0]} and --workspace ${s}.`,usage:f.init,command:l};s=o[0]}}return{command:l,argv:i,flag:s}}var L=(t,e)=>`Cannot write the workspace ${t} (${e}): allow Gallery to write there, or pass --workspace <a folder you may write>.`,G=(t,e=!0)=>e?`${p.join(t,"gallery.json")} is not Gallery's (another program's file of that name): pass --workspace <another folder> for Gallery's documents.`:`${p.join(t,"gallery.json")} does not read as JSON: mend the file, or pass --workspace <another folder> for Gallery's documents.`;async function b(t=process.argv.slice(2)){process.stdout.on("error",i=>{throw i.code==="EPIPE"&&process.exit(process.exitCode??0),i});let e=A(t);if(e.version){let i=v();console.log(i);try{let{versionNotes:r}=await import("./chunk-TANZRINB.mjs");for(let o of r(i))console.log(o)}catch{}return}if(e.help)return void console.log(e.help);e.error&&(console.error(`${e.error}
4
- ${N(e.usage,e.command)}`),process.exit(2));let{command:a,flag:h}=e,{findWorkspace:n}=await import("../browser/shared/workspace.mjs"),s=n({flag:h});if(process.env.GALLERY_WORKSPACE=s.root,!j.has(a)){let{ensureWorkspace:i}=await import("../browser/shared/workspace.mjs");try{let{ours:o,reads:c}=await i(s.root);o||(console.error(G(s.root,c)),process.exit(1))}catch(o){if(!o.code)throw o;console.error(L(s.root,o.code)),process.exit(1)}let{registerQuietly:r}=await import("../browser/shared/workspace-registry.mjs");await r(s.root)}let{UsageError:d,usageFailureText:m}=await import("./chunk-GPIWQ4X4.mjs"),l=await O[a]();try{await l.run(e.argv,{command:a,workspace:s.root,how:s.how,version:v()})}catch(i){if(!(i instanceof d))throw i;console.error(m(f[a],i.message,i.synopsis)),process.exit(2)}}var y=t=>{try{return E.native(t)}catch{return null}};process.argv[1]&&y(process.argv[1])===y($(import.meta.url))&&b();export{v as a,A as b,L as c,G as d,b as e};
@@ -1,2 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{c as i,d as u}from"./chunk-GHOYKMQ3.mjs";import{j as f,k as p}from"./chunk-UYVCQK3H.mjs";import{u as c}from"./chunk-J5PUIV3Y.mjs";import{b as d,f as h}from"./chunk-4OZWXZE5.mjs";import w from"node:fs/promises";import y from"node:path";import{reportsDirectory as b}from"../browser/shared/paths.mjs";import{sameDirectory as x}from"../browser/shared/preview-server.mjs";import{copyOldDocuments as j,ensureWorkspace as v,layoutOf as D}from"../browser/shared/workspace.mjs";import{nameProblem as G,writeWorkspaceName as N}from"../browser/shared/workspace-name.mjs";import{registerQuietly as O}from"../browser/shared/workspace-registry.mjs";var g=(o,t)=>`${o} ${t}${o===1?"":"s"}`;function C(o,t,r){let{preferences:s}=D(r);return[o.copied.length?`Copied ${g(o.copied.length,"document")} from ${t}: ${o.copied.join(", ")}`:`Copied no documents from ${t}.`,...o.skipped.length?[`Skipped (the slug is taken here, or the folder's name is no slug): ${o.skipped.join(", ")}`]:[],...o.kept.length?[`Left behind (a name a workspace keeps for itself, for its custom blocks here, which no new document takes): ${o.kept.join(", ")}`]:[],...o.preferences==="copied"?[`\u5199\u4F5C\u504F\u597D\uFF1Acopied (${s})`]:o.preferences==="kept"?[`\u5199\u4F5C\u504F\u597D\uFF1Akept the workspace's (${s}); the old one was not copied`]:[],...o.outline?[`Sidebar order: ${o.outline}`]:[],...o.page?[`\u5199\u4F5C\u504F\u597D's page: ${o.page==="copied"?"copied":"kept the workspace's"}`]:[],...o.emoji?[`Emoji library: ${o.emoji} added`]:[],...o.history?[`Recent versions: ${g(o.history,"document")}`]:[],...o.packages.length?[`Custom blocks: ${o.packages.join(", ")}`]:[]]}async function U(o){let{values:t}=h({values:["--from","--name"],argv:o}),r=b,s=t.get("--name"),l=s===void 0?null:G(s);if(l)throw new d(l);let m;try{let{made:e,ours:n,reads:k}=await v(r);n||(console.error(u(r,k)),process.exit(1)),m=e}catch(e){if(!e.code)throw e;console.error(i(r,e.code)),process.exit(1)}if(console.log(`\u5DE5\u4F5C\u533A\uFF1A${r}\uFF08${m?"\u65B0\u5EFA":"\u5DF2\u6709"}\uFF09`),s!==void 0)try{let e=await N(r,s);console.log(`\u540D\u5B57\uFF1A${e.name}${e.before&&e.before!==e.name?` (it was "${e.before}")`:""}`)}catch(e){console.error(e.code?i(r,e.code):e.message),process.exit(1)}if(await O(r),t.has("--from")){let e=y.resolve(t.get("--from"));await w.stat(e).then(n=>n.isDirectory(),()=>!1)||(console.error(`No such folder: ${e} (--from names an older Gallery's reports/ folder).`),process.exit(1)),x(e,r)&&(console.error(`${e} is this workspace: --from names another folder (an older Gallery's reports/).`),process.exit(1));for(let n of C(await j({from:e,to:r}),e,r))console.log(n)}let $=await c(r);for(let e of $.packs)e.failed?console.warn(`\u5757\u5305\uFF1AGallery's pack ${e.id} was not installed (${e.failed}); a later start tries again.`):e.first&&console.log(`\u5757\u5305\uFF1A${e.name.zh} (${e.id} ${e.version}, ${e.added.length+e.same.length+e.updated.length} blocks)${e.id==="gallery-soft"?", switched off: \u8BBE\u7F6E \u203A \u7EC4\u4EF6\u5217\u8868 turns it on":""}`);let a=await f(r);a.did==="made"?console.log(`\u9996\u9875\uFF1A${a.file} (the home page, its cards Gallery's today and note; the workbench opens it first)`):a.did==="failed"&&console.warn(`\u9996\u9875\uFF1A${p(a)}`),console.log('Next: gallery new <slug> "<title>" makes a document; gallery open opens the workbench.')}export{C as a,U as b};
@@ -1,2 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{a,b,c,d,e,f,g,h}from"./chunk-W7665ZEC.mjs";import"./chunk-7JDX4E65.mjs";import"./chunk-3MBRL2PM.mjs";import"./chunk-HPOI4ZX7.mjs";import"./chunk-342HXE3Q.mjs";import"./chunk-EAIFITAV.mjs";import"./chunk-EP25HDAJ.mjs";import"./chunk-AR5D57ZD.mjs";import"./chunk-67N2QJYT.mjs";import"./chunk-5XA2ZBAE.mjs";import"./chunk-JEUK3ZO7.mjs";import"./chunk-JLTZF4LA.mjs";import"./chunk-PUOQ65NC.mjs";import"./chunk-7OG26PGF.mjs";import"./chunk-DJISHPUL.mjs";import"./chunk-ZWWC4KLF.mjs";import"./chunk-IA4PSIMD.mjs";import"./chunk-2OHANJ6Q.mjs";import"./chunk-F4ZA6JRZ.mjs";import"./chunk-7M2BQQGZ.mjs";import"./chunk-ITOH5EGO.mjs";import"./chunk-ZQS6H473.mjs";import"./chunk-QE5RG76S.mjs";import"./chunk-UYVCQK3H.mjs";import"./chunk-J5PUIV3Y.mjs";import"./chunk-4OZWXZE5.mjs";import"./chunk-MXUBKDRO.mjs";import"./chunk-HXG7EOPJ.mjs";import"./chunk-ZTHICSSF.mjs";import"./chunk-6N3PX4XX.mjs";import"./chunk-PAREWQGB.mjs";import"./chunk-BFJGHSQN.mjs";import"./chunk-U5XL7D6A.mjs";import"./chunk-HYMEEXKN.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-R2ZDLJYT.mjs";import"./chunk-VFX2KNHP.mjs";import"./chunk-VS7JIGJW.mjs";import"./chunk-HDWTZ763.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";export{a as PAGE_ASIDE,b as PAGE_INSIDE_ALONE,e as cardChangesOf,c as firstInstance,d as outsideWhat,g as pageHost,f as pageSaves,h as pageTryCommand};
@@ -1,2 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{a as D,b as M}from"./chunk-YI43RG4P.mjs";import{c as v,d as j}from"./chunk-GHOYKMQ3.mjs";import{b as k,f as A}from"./chunk-4OZWXZE5.mjs";import L from"node:fs/promises";import y from"node:path";import{readAnnouncement as _}from"../browser/shared/preview-server.mjs";import{nameProblem as B,nameStops as b,ownName as K,workspaceLabels as Q,workspaceName as x,writeWorkspaceName as R}from"../browser/shared/workspace-name.mjs";import{forgetWorkspace as U,isTemporary as q,isWorkspace as C,isWorkspaceId as z,readRegistry as F,registerQuietly as W,registerWorkspace as G,SCAN_DEPTH as P,SCAN_LIMIT as J,scanForWorkspaces as V,workspaceId as X,workspaceKey as l}from"../browser/shared/workspace-registry.mjs";import{defaultWorkspace as Y,documentsFolder as T,ensureWorkspace as Z,layoutOf as ee}from"../browser/shared/workspace.mjs";import{clashingIds as oe}from"../browser/shared/drafts.mjs";var $=(o,r)=>`${o} ${r}${o===1?"":"s"}`,I=(o,r)=>l(o)===l(r);function se(o){if(K(o)||I(o,Y()))return null;let{name:r}=x(o,{stops:b()});return`\u5DE5\u4F5C\u533A\u540D\u5B57\uFF1A\u6CA1\u6709\uFF08\u522B\u5904\u6309\u6587\u4EF6\u5939\u53EB\u5B83"${r}"\uFF09\uFF1B\u8FD9\u4E2A\u5DE5\u4F5C\u533A\u662F\u4E3A\u4E00\u4E2A\u9879\u76EE\u5EFA\u7684\uFF0C\u5C31\u7528 gallery workspaces --name "<\u9879\u76EE\u540D>" \u5199\u4E0A\u9879\u76EE\u540D`}async function re(o,r){let c=B(r);if(c)throw new k(c);try{let{ours:t,reads:i}=await Z(o);t||(console.error(j(o,i)),process.exit(1))}catch(t){if(!t.code)throw t;console.error(v(o,t.code)),process.exit(1)}let s;try{s=await R(o,r)}catch(t){console.error(t.code?v(o,t.code):t.message),process.exit(1)}await W(o),console.log(`\u5DE5\u4F5C\u533A\uFF1A${o}`),console.log(`\u540D\u5B57\uFF1A${s.name} (in ${ee(o).marker}${s.before&&s.before!==s.name?`; it was "${s.before}"`:""}): the sidebar and gallery workspaces call it so.`)}async function te(o,r){let c=await U(o);c.length||(console.error(`No registered workspace is ${z(o)?o:y.resolve(o)}: gallery workspaces lists them, with their paths and ws- ids.`),process.exit(1));for(let s of c)console.log(`Forgot ${s} (only the registry changed: nothing on disk).${I(s,r)?" It is the current workspace: the next command run in it registers it again.":""}`)}async function ne(o){let r=y.resolve(o??T());await L.stat(r).then(n=>n.isDirectory(),()=>!1)||(console.error(`No such folder: ${r} (--scan names a folder to look in).`),process.exit(1));let c=new Set(F().workspaces.map(({root:n})=>l(n))),{found:s,read:t,cut:i}=await V(r);console.log(`Scanned ${r}, ${P} levels down (${$(t,"folder")}): ${s.length?`${$(s.length,"workspace")}.`:"no workspace."}`);let f=b();for(let n of s){let{name:h}=x(n,{stops:f});if(c.has(l(n))){await W(n),console.log(` \u5DF2\u767B\u8BB0\uFF1A${n}\uFF08${h}\uFF09`);continue}let g;try{g=await G(n)}catch(m){console.log(` \u6CA1\u80FD\u767B\u8BB0\uFF08${m.code??m.message}\uFF09\uFF1A${n}`);continue}console.log(g==="temporary"?` \u4E0D\u767B\u8BB0\uFF08\u5728\u7CFB\u7EDF\u7684\u4E34\u65F6\u6587\u4EF6\u5939\u91CC\uFF09\uFF1A${n}`:` \u65B0\u767B\u8BB0\uFF1A${n}\uFF08${h}\uFF09`)}i&&console.log(`Stopped after ${$(J,"folder")}: gallery workspaces --scan <a folder further down> looks at the rest.`),s.length&&console.log("gallery workspaces lists them; gallery list <words> --all searches their documents.")}async function ae(o){let r=C(o),c=q(o);r&&await W(o);let s=F().workspaces,t=[o,...s.map(({root:e})=>e).filter(e=>!I(e,o))],i=new Map(s.map(({root:e,seen:a})=>[l(e),Date.parse(a)])),f=T(),n=b({documents:f}),h=await Promise.all(t.map(async e=>{let a=C(e),w=a?await D(e):[],p=a?await _({reportsDirectory:e}):null;return{root:e,there:a,count:w.length,edited:w.reduce((d,{edited:u})=>Math.max(d,u),0),port:p?.port??null,named:{root:e,...x(e,{stops:n})}}})),[g,...m]=h;m.sort((e,a)=>a.there-e.there||a.edited-e.edited||(i.get(l(a.root))??0)-(i.get(l(e.root))??0));let N=[g,...m],E=new Map(Q(N.map(({named:e})=>e)).map(e=>[l(e.root),e])),O=s.length;console.log(`${$(O,"workspace")} on this machine's registry; the current one first (*):`);for(let e of N){let{name:a,own:w,above:p}=E.get(l(e.root)),d=e===g,u=[...w||!e.there?[]:["\u6CA1\u6709\u8D77\u540D\uFF1A\u7528\u7684\u662F\u6587\u4EF6\u5939\u7684\u540D\u5B57"],...e.there?[]:[d?"\u8FD8\u6CA1\u6709\u5EFA":"\u4E0D\u5728\u4E86\uFF1A\u6587\u4EF6\u5939\u6216\u5B83\u7684 gallery.json \u627E\u4E0D\u5230\u4E86"],...d&&e.there&&c?["\u5728\u7CFB\u7EDF\u7684\u4E34\u65F6\u6587\u4EF6\u5939\u91CC\uFF1A\u4E0D\u767B\u8BB0"]:[]],H=p?y.isAbsolute(p)?`\uFF08${p}\uFF09`:`\uFF08\u4E0A\u4E00\u7EA7\uFF1A${p}\uFF09`:"";console.log(`${d?"*":" "} ${a}${H} ${X(e.root)}${u.length?` \uFF08${u.join("\uFF1B")}\uFF09`:""}`),console.log(` \u8DEF\u5F84\uFF1A${e.root}`),e.there&&console.log(` \u6587\u6863\uFF1A${e.count?`${e.count} \u7BC7\uFF1B\u4E0A\u6B21\u7F16\u8F91\uFF1A${M(e.edited)}`:"\u6CA1\u6709"}`),e.port&&console.log(` \u670D\u52A1\uFF1Ahttp://127.0.0.1:${e.port}/`)}for(let{id:e,roots:a}of oe())console.log(`${e} \u662F ${a.length} \u4E2A\u767B\u8BB0\u7684\u5DE5\u4F5C\u533A\u5171\u7528\u7684\u7F16\u53F7\uFF08${a.join("\u3001")}\uFF09\uFF1A\u4FA7\u8FB9\u680F\u91CC\u5B83\u4EEC\u7684\u5E95\u7A3F\u90FD\u627E\u4E0D\u5230\uFF1Bgallery workspaces --forget <\u8DEF\u5F84> \u53BB\u6389\u5176\u4E2D\u4E00\u4E2A`);let S=r?se(o):null;S&&console.log(S),m.some(({there:e})=>!e)&&console.log("One no longer there stays registered (a drive may come back): gallery workspaces --forget <\u8DEF\u5F84> takes it off, nothing on disk changed."),O<=1&&console.log(`gallery workspaces --scan registers the workspaces already on this machine (in the Documents folder, ${P} levels down; or --scan <folder>).`),console.log("gallery list <words> --all searches the documents of them all; every command takes --workspace <\u8DEF\u5F84> to work in one.")}async function ue(o,r){let{positional:c,options:s,values:t}=A({options:["--scan"],values:["--name","--forget"],argv:o});if([s.has("--scan"),t.has("--name"),t.has("--forget")].filter(Boolean).length>1)throw new k("One of --scan, --name and --forget at a time.");if(c.length>(s.has("--scan")?1:0))throw new k(s.has("--scan")?"--scan takes one folder at most.":"gallery workspaces names no folder: --scan <folder> looks in one, --workspace <dir> names the current workspace.");let f=y.resolve(r.workspace);return t.has("--name")?re(f,t.get("--name")):t.has("--forget")?te(t.get("--forget"),f):s.has("--scan")?ne(c[0]):ae(f)}export{se as a,ue as b};
@@ -1,2 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{a as h,b as v,d as p,e as j,h as I,j as A}from"./chunk-NAMN3RAF.mjs";import{a as O}from"./chunk-JEUK3ZO7.mjs";import{a as E}from"./chunk-MTYYHM2G.mjs";import"./chunk-ALZ6ZENZ.mjs";import"./chunk-IA4PSIMD.mjs";import{g as C}from"./chunk-7M2BQQGZ.mjs";import{b as i,f as g,i as y}from"./chunk-4OZWXZE5.mjs";import"./chunk-ZTHICSSF.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";import D from"node:path";import{pageLinks as F,pageOfLink as J}from"../browser/shared/page-links.mjs";import{reportsDirectory as x}from"../browser/shared/paths.mjs";import{findPreviewServer as K}from"../browser/shared/preview-server.mjs";import{topOf as M}from"../browser/shared/outline-shape.mjs";import{LINK_FILE as U,linkAddress as P,linkIcon as T}from"../browser/shared/web-links.mjs";var $=t=>t.replace(/\s+/g," ").trim(),k=t=>t==null?"none":JSON.stringify(t);async function L(t,e){let n=await K({reportsDirectory:x}),o=n?await I(n,e,t):null;if(o)return o;let[,s]=await E({edits:{},reports:{},reportsDirectory:x,web:{icon:a=>C(a)}}).run(t,e);return s}function _(t,e){let n=[...t.documents.values()].filter(({url:a})=>a!==void 0),o=J(F(n),e.replace(/^.*#/,""));return o?{slug:o,link:t.documents.get(o)}:{refused:t.documents.get(e)?`${p(t,e)} is a document, not a web link: gallery set changes a document.`:`No web link "${e}": gallery list --tree shows the sidebar's entries.`}}var W=(t,e)=>t.groups.find(n=>[v(n),n.id].some(o=>o.toLowerCase()===$(e).toLowerCase()))??null;async function B(t,e,n){if(t.length!==2)throw new i('Name the address and the name: gallery link add <url> "<name>".');let[o,s]=t,a=P(o);if(a.refused)throw new i(`Not an address a web link takes: ${o} (${{url:"no address",scheme:"http or https only",long:"2048 characters at most"}[a.refused]}).`);if(!$(s))throw new i("The name is never empty.");let d=n.get("--column"),u=n.get("--under"),l=n.get("--after"),c=n.get("--icon");if(d!==void 0&&u!==void 0)throw new i("--column and --under are two places: give one.");if(l!==void 0&&e.has("--first"))throw new i("--after and --first are two places: give one.");if(c!==void 0&&!T(c))throw new i(`Not an icon a web link takes: ${c} (an emoji, or an icon of the \u56FE\u6807 tab as /icons/<name>_<color>.svg).`);let f=await h(),w;if(d!==void 0){let S=W(f,d);S||(console.error(`No column "${d}" in the sidebar (${f.groups.map(v).join(", ")}): nothing added.`),process.exit(1)),w=M(S.id)}u!==void 0&&(w=(await y(u)).slug);let r=l===void 0?null:(await y(l)).slug,q=e.has("--first")||u===void 0&&r===null,m=await L("link",{url:a.url,title:$(s),...c?{icon:c}:{},...w!==void 0?{parent:w}:{},after:r,first:q});m?.ok||(console.error(`Not added: ${m?.message??m?.reason??"no answer"}.`),process.exit(1));let b=await h(),{slug:N,url:z}=m.link;console.log(`Added the web link ${p(b,N)}: ${z}`),console.log(`Placed it ${A(b,{parent:m.parent,index:m.index})}.`),console.log(j(b,N)),console.log(`It is ${O(D.join(x,N,U))}; the workbench shows the page beside the sidebar (a site that refuses frames: \u5728\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00).`)}async function G(t,e){if(t.length!==1)throw new i("Name one web link, then what to set: --url, --title, --icon.");if(!["--url","--title","--icon"].some(r=>e.has(r)))throw new i('Say what to set: --url <address>, --title "<name>", --icon <emoji|none>.');let n=e.has("--title")?$(e.get("--title")):void 0;if(n==="")throw new i("--title takes the words of the name: a web link's name is never empty.");let o;if(e.has("--url")){let r=P(e.get("--url"));if(r.refused)throw new i(`Not an address a web link takes: ${e.get("--url")}.`);o=r.url}let s;if(e.has("--icon")){let r=e.get("--icon").trim();if(r!=="none"&&!T(r))throw new i(`Not an icon a web link takes: ${r} (an emoji, none, or an icon of the \u56FE\u6807 tab).`);s=r==="none"?null:r}let a=await h(),d=_(a,t[0]);d.refused&&(console.error(d.refused),process.exit(1));let{slug:u,link:l}=d,c=await L("link-set",{slug:u,...o!==void 0?{url:o}:{},...n!==void 0?{title:n}:{},...s!==void 0?{icon:s}:{}});c?.ok||(console.error(`Not set: ${c?.message??c?.reason??"no answer"}.`),process.exit(1));let f=c.link,w=[...n!==void 0&&n!==l.title?[` title: ${k(l.title)} \u2192 ${k(f.title)}`]:[],...o!==void 0&&f.url!==l.url?[` url: ${l.url} \u2192 ${f.url}`]:[],...s!==void 0&&(f.icon??null)!==(l.icon??null)?[` icon: ${k(l.icon)} \u2192 ${k(f.icon??null)}`]:[]];if(!w.length)return void console.log(`Nothing to change: ${u} has ${e.size===1?"that already":"those already"}.`);console.log(`Set the web link ${u}:`);for(let r of w)console.log(r)}async function H(t){if(t.length!==1)throw new i("Name one web link to move to the trash.");let e=await h(),n=_(e,t[0]);n.refused&&(console.error(n.refused),process.exit(1));let o=await L("trash",{slug:n.slug,kind:"link"});o?.ok||(console.error(`Not moved to the trash: ${o?.message??o?.reason??"no answer"}.`),process.exit(1)),console.log(`Moved the web link ${p(e,n.slug)} to the trash: the workbench's \u8BBE\u7F6E \u203A \u56DE\u6536\u533A restores it where it was.`)}async function se(t){let[e,...n]=t;if(e==="add"){let{positional:o,options:s,values:a}=g({options:["--first"],values:["--column","--under","--after","--icon"],argv:n});return B(o,s,a)}if(e==="set"){let{positional:o,values:s}=g({values:["--url","--title","--icon"],argv:n});return G(o,s)}if(e==="remove"){let{positional:o}=g({argv:n});return H(o)}throw new i(e?`No such action: link ${e} (add, set, remove).`:"Say what to do: gallery link add, set or remove.")}export{se as run};
@@ -1,2 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{a}from"./chunk-ORID3AE7.mjs";import"./chunk-DR73Y2UJ.mjs";import"./chunk-JLTZF4LA.mjs";import"./chunk-PUOQ65NC.mjs";import"./chunk-7OG26PGF.mjs";import"./chunk-DJISHPUL.mjs";import"./chunk-ZWWC4KLF.mjs";import"./chunk-AHN3NFKJ.mjs";import"./chunk-MTYYHM2G.mjs";import"./chunk-ALZ6ZENZ.mjs";import"./chunk-IA4PSIMD.mjs";import"./chunk-2OHANJ6Q.mjs";import"./chunk-F4ZA6JRZ.mjs";import"./chunk-7M2BQQGZ.mjs";import"./chunk-ITOH5EGO.mjs";import"./chunk-ZQS6H473.mjs";import"./chunk-UYVCQK3H.mjs";import"./chunk-J5PUIV3Y.mjs";import"./chunk-MXUBKDRO.mjs";import"./chunk-HXG7EOPJ.mjs";import"./chunk-ZTHICSSF.mjs";import"./chunk-6N3PX4XX.mjs";import"./chunk-PAREWQGB.mjs";import"./chunk-BFJGHSQN.mjs";import"./chunk-U5XL7D6A.mjs";import"./chunk-HYMEEXKN.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-R2ZDLJYT.mjs";import"./chunk-VFX2KNHP.mjs";import"./chunk-VS7JIGJW.mjs";import"./chunk-HDWTZ763.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";export{a as startProductionServer};
@@ -1,2 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{b as c,f as h}from"./chunk-4OZWXZE5.mjs";import"./chunk-5L7RYZCL.mjs";import g from"node:path";import{SIDEBAR_FILE as l}from"../browser/shared/extension-sidebar.mjs";import{extensionFolders as f,listExtensions as m,readExtension as w}from"../browser/shared/extensions.mjs";import{isExtensionId as x}from"../browser/shared/outline-shape.mjs";import{reportsDirectory as s}from"../browser/shared/paths.mjs";import{layoutOf as a}from"../browser/shared/workspace.mjs";var d=t=>`${t} ${t===1?"entry":"entries"}`,u=t=>g.join(a(s).extensions,t,l);function p(t){if(t.length>0)throw new c("list takes nothing: gallery extension check <id> reads one.");return m(s,{all:!0}).then(o=>{if(o.length===0){console.log(`No extensions in ${a(s).extensions}: an extension that gives the sidebar a column is a folder there, <id>/${l} (references/extensions.md says how it is written).`);return}console.log(`${o.length} extension${o.length===1?"":"s"} in ${a(s).extensions}:`);for(let n of o){let e=n.missing?`no ${l}: it gives the sidebar no column`:n.error?`\u6761\u76EE\u8BFB\u4E0D\u51FA\u6765\uFF1A${n.error.message}`:`${n.title}, ${d(n.count)}${n.notes.length?`, ${n.notes.length} note${n.notes.length===1?"":"s"}`:""}`;console.log(` ${n.id} ${e}`)}console.log("gallery extension check <id> prints what the sidebar shows of one.")})}function $(t,o,n=[]){for(let e of t){let i=e.url?e.url:"(no address: a click opens and closes what is under it)";n.push(`${" ".repeat(o)}${e.id} ${e.icon?`${e.icon} `:""}${e.title} ${i}`),$(e.children??[],o+1,n)}return n}async function y(t){if(t.length!==1)throw new c("Name one extension: gallery extension check <id>.");let[o]=t;if(!x(o))throw new c(`Not an extension's id: ${o} (its folder's name under extensions/: lowercase letters, digits and dashes, 48 at most).`);(await f(s)).some(r=>r.id===o)||(console.error(`No extension "${o}" in ${a(s).extensions}: gallery extension list shows them.`),process.exit(1));let e=await w(s,o),i=u(o);e.missing&&(console.error(`FAIL ${i}: there is no ${l}; the folder gives the sidebar no column until it has one (references/extensions.md says how it is written).`),process.exit(1)),e.error&&(console.error(`FAIL ${i}: ${e.error.message}`),console.error(`The sidebar shows the column "${e.title}" with one row: \u6761\u76EE\u8BFB\u4E0D\u51FA\u6765\uFF1A${e.error.message}`),process.exit(1)),console.log(`The sidebar shows the column ${e.title}${e.icon?` (${e.icon})`:""}, ${d(e.count)}, in the order the file gives (an entry with an address opens it beside the sidebar, one without opens and closes what is under it):`),console.log(e.title);for(let r of $(e.entries,1))console.log(r);for(let r of e.notes)console.log(`note: ${r.message}`);console.log(`OK ${o}: ${d(e.count)} (${i})`)}async function F(t){let[o,...n]=t;if(o==="list"){let{positional:e}=h({argv:n});return p(e)}if(o==="check"){let{positional:e}=h({argv:n});return y(e)}throw new c(o?`No such action: extension ${o} (list, check).`:"Say what to do: gallery extension list or check <id>.")}export{F as run};
@@ -1,15 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{a as Dt,b as qt}from"./chunk-ALZ6ZENZ.mjs";import{a as Zt}from"./chunk-UMHUSOPJ.mjs";import{randomBytes as _t}from"node:crypto";import b from"node:fs/promises";import g from"node:path";import{writeAtomic as G}from"../browser/shared/files.mjs";import{sendJson as H}from"../browser/shared/http.mjs";import{said as tt,saying as Tt}from"../browser/shared/i18n/index.mjs";import{reportsDirectory as Ge}from"../browser/shared/paths.mjs";import{moveDocument as Ye,outlineAndFile as We,placeIn as vt,readOutline as He,validOutline as ae,withOutlineLock as Me,writeHead as Be,writeOutline as Ve,writtenAs as Ue}from"../browser/shared/outline.mjs";import{storedHead as Ke}from"../browser/shared/sidebar-head.mjs";import{DOCS as xt,isForeign as ie,isTop as Et,topOf as At}from"../browser/shared/outline-shape.mjs";import{addDraft as se,addWorkspace as ze,draftEntry as ut,draftFacts as ce,draftOf as Ct,findDraft as Xe,foreignMarker as Qe,projectChoices as Ze,registeredIds as le,workspaceNames as De,workspaceOf as M}from"../browser/shared/drafts.mjs";import{forgetSnapshot as nt,shownWorkspaces as qe}from"../browser/shared/workspace-columns.mjs";import{nameStops as tn}from"../browser/shared/workspace-name.mjs";import{registerWorkspace as en,workspaceId as Pt,workspaceKey as ue}from"../browser/shared/workspace-registry.mjs";import{spawn as ne}from"node:child_process";import xe from"node:http";import Ee from"node:os";import Rt from"node:path";import{NO_DEFAULT_TREE as Ae}from"../browser/shared/drafts.mjs";import{said as te}from"../browser/shared/i18n/index.mjs";import{packageRoot as Pe}from"../browser/shared/paths.mjs";import{answerOf as ee,compareVersions as Le,galleryVersion as Ne,readAnnouncement as $t}from"../browser/shared/preview-server.mjs";import{isWorkspace as Ie,readRegistry as $e,workspaceId as Re,workspaceKey as St}from"../browser/shared/workspace-registry.mjs";var bt={rename:{to:"workspace",fields:["slug","title"]},create:{to:"workspace",fields:["title","description","language"]},trash:{to:"workspace",fields:["slug"]},restore:{to:"workspace",fields:["id"]},duplicate:{to:"workspace",fields:["slug","suffix","untitled"]},look:{to:"workspace",fields:["slug","look"]},looks:{to:"workspace",fields:["slug"]},markdown:{to:"transfer",fields:["slug"]},import:{to:"transfer",fields:["uploads","parent","from","language"]},annotations:{to:"edit",fields:["slug","restore"]},export:{to:"transfer",fields:["slug","options"],file:"out",timeout:6e5},upload:{to:"transfer",fields:[],query:["name"],file:"in",timeout:36e5}},_e=["content-type","content-length","content-disposition","x-file-name","cache-control"],Te=9e4,Ce=m=>!["","0",void 0].includes(m);function Fe(m,{platform:x=process.platform,env:l=process.env}={}){return Ce(l.GALLERY_NO_BROWSER)?{skip:"GALLERY_NO_BROWSER is set"}:x==="win32"?{command:Rt.join(l.SystemRoot||l.windir||"C:\\Windows","explorer.exe"),args:[`/select,"${m}"`],verbatim:!0}:x==="darwin"?{command:"open",args:["-R",m]}:!l.DISPLAY&&!l.WAYLAND_DISPLAY?{skip:"no display here (neither DISPLAY nor WAYLAND_DISPLAY is set)"}:{command:"xdg-open",args:[Rt.dirname(m)]}}function re(m,x){let l=Fe(m,x);return l.skip?Promise.resolve({opened:!1,why:l.skip}):new Promise($=>{let _;try{_=ne(l.command,l.args,{detached:!0,stdio:"ignore",windowsHide:!1,windowsVerbatimArguments:!!l.verbatim})}catch(N){return $({opened:!1,why:N.code??N.message})}_.once("error",N=>$({opened:!1,why:N.code??N.message})),_.once("spawn",()=>{_.unref(),$({opened:!0})})})}function Je(m){let x=/^http:\/\/127\.0\.0\.1:(\d{1,5})$/.exec(String(m??"")),l=x?Number(x[1]):0;return l>0&&l<65536?l:null}function oe({root:m,changed:x=()=>{},log:l=()=>{},gallery:$=Rt.join(Pe,"bin","gallery.mjs")}){let _=St(m),N=new Map;function Nt(p){let d={...process.env,[Ae]:"1",GALLERY_NO_UPDATE_CHECK:"1"};return delete d.GALLERY_WORKSPACE,delete d.GALLERY_SERVER_KIND,d.GALLERY_VITE_CACHE_DIR&&(d.GALLERY_VITE_CACHE_DIR=`${d.GALLERY_VITE_CACHE_DIR}-${Re(p)}`),new Promise(S=>{let h=[],j;try{j=ne(process.execPath,[$,"--workspace",p,"open","--no-browser"],{cwd:Ee.homedir(),env:d,stdio:["ignore","pipe","pipe"],windowsHide:!0})}catch(P){return S({ok:!1,message:P.message})}j.stdout.on("data",P=>h.push(String(P))),j.stderr.on("data",P=>h.push(String(P)));let v=setTimeout(()=>j.kill(),Te);j.once("error",P=>{clearTimeout(v),S({ok:!1,message:P.message})}),j.once("exit",P=>{clearTimeout(v);let w=h.join("").trim().split(/\r?\n/).filter(Boolean);S(P===0?{ok:!0}:{ok:!1,message:w.slice(-3).join(" ")||`gallery open ended with ${P}`})})})}async function mt(p){let d=await $t({reportsDirectory:p});return!d||await ee(d,p,5e3)!=="yes"||d.kind!=="dev"&&Le(d.version,Ne)<0?null:{port:d.port,token:d.token,pid:d.pid}}async function Y(p,{start:d=!0}={}){if(St(p)===_)return{refused:"self",message:"\u8FD9\u662F\u5F53\u524D\u7684\u5DE5\u4F5C\u533A"};if(!Ie(p))return{refused:"workspace",message:te("\u627E\u4E0D\u5230\u5B83\u6240\u5728\u7684\u5DE5\u4F5C\u533A\uFF1A{0} \u4E0D\u5728\u4E86",p)};let S=await mt(p);if(S||!d)return S??{refused:"start",message:"\u5B83\u6240\u5728\u5DE5\u4F5C\u533A\u7684\u670D\u52A1\u6CA1\u6709\u5728\u8FD0\u884C"};let h=St(p);N.has(h)||(l(`starting the server of ${p}`),N.set(h,Nt(p).finally(()=>N.delete(h))));let j=await N.get(h);return await mt(p)??{refused:"start",message:j.ok?"\u5B83\u6240\u5728\u5DE5\u4F5C\u533A\u7684\u670D\u52A1\u6CA1\u6709\u56DE\u7B54":te("\u6CA1\u80FD\u542F\u52A8\u5B83\u6240\u5728\u5DE5\u4F5C\u533A\u7684\u670D\u52A1\uFF1A{0}",j.message)}}let pt=(p,d,S,h)=>{let j=bt[d],v=Object.fromEntries(j.fields.filter(w=>S?.[w]!==void 0).map(w=>[w,S[w]])),P=new URLSearchParams((j.query??[]).filter(w=>h?.[w]!==void 0).map(w=>[w,String(h[w])]));return{fields:v,host:`127.0.0.1:${p.port}`,path:`/__gallery/${j.to}/${d}${P.size?`?${P}`:""}`}};async function E(p,d,S){if(!Object.hasOwn(bt,d)||bt[d].file)return[404,{ok:!1,reason:"unknown",message:"\u8FD9\u4E2A\u547D\u4EE4\u4E0D\u80FD\u8F6C\u7ED9\u522B\u7684\u5DE5\u4F5C\u533A"}];let h=await Y(p);if(h.refused)return[409,{ok:!1,reason:h.refused,message:h.message}];let{fields:j,host:v,path:P}=pt(h,d,S);try{let w=await fetch(`http://${v}${P}`,{method:"POST",headers:{"Content-Type":"application/json",Origin:`http://${v}`,"X-Gallery-Token":h.token},body:JSON.stringify(j),signal:AbortSignal.timeout(3e4)}),V=await w.json().catch(()=>null);return V&&typeof V.ok=="boolean"?[w.status,V]:[502,{ok:!1,reason:"answer",message:"\u5B83\u6240\u5728\u5DE5\u4F5C\u533A\u7684\u670D\u52A1\u6CA1\u6709\u7ED9\u51FA\u7ED3\u679C"}]}catch{return[502,{ok:!1,reason:"answer",message:"\u5B83\u6240\u5728\u5DE5\u4F5C\u533A\u7684\u670D\u52A1\u6CA1\u6709\u56DE\u7B54"}]}}async function F(p,d,{body:S={},query:h={},request:j=null,response:v}){let P=bt[d];if(!P?.file)return[404,{ok:!1,reason:"unknown",message:"\u8FD9\u4E2A\u547D\u4EE4\u4E0D\u80FD\u8F6C\u7ED9\u522B\u7684\u5DE5\u4F5C\u533A"}];let w=await Y(p);if(w.refused)return[409,{ok:!1,reason:w.refused,message:w.message}];let{fields:V,host:Z,path:J}=pt(w,d,S,h);return new Promise(it=>{let W={Origin:`http://${Z}`,"X-Gallery-Token":w.token},U=P.file==="out"?Buffer.from(JSON.stringify(V)):null;U?Object.assign(W,{"Content-Type":"application/json","Content-Length":U.length}):Object.assign(W,{"Content-Type":"application/octet-stream",...j.headers["content-length"]?{"Content-Length":j.headers["content-length"]}:{}});let st=[502,{ok:!1,reason:"answer",message:"\u5B83\u6240\u5728\u5DE5\u4F5C\u533A\u7684\u670D\u52A1\u6CA1\u6709\u56DE\u7B54"}],K=xe.request({host:"127.0.0.1",port:w.port,path:J,method:"POST",headers:W,timeout:P.timeout},L=>{v.writeHead(L.statusCode??502,Object.fromEntries(_e.filter(C=>L.headers[C]!==void 0).map(C=>[C,L.headers[C]]))),L.pipe(v),L.once("end",()=>it(null)),L.once("error",()=>{v.destroy(),it(null)})});K.once("timeout",()=>K.destroy()),K.once("error",()=>{v.headersSent?(v.destroy(),it(null)):it(st)}),v.once("close",()=>{v.writableEnded||K.destroy()}),U?K.end(U):j.pipe(K)})}let kt=new Map;async function ht(p){let d=Je(p);if(d===null)return!1;let S=kt.get(d);if(S&&Date.now()-S.at<6e4)return S.answer;let h=(async()=>{for(let{root:j}of $e().workspaces){let v=await $t({reportsDirectory:j});if(v?.port===d&&await ee(v,j,3e3)==="yes")return!0}return!1})();return kt.set(d,{at:Date.now(),answer:h}),h}let B=new Map,c=new Map,ot=new Set,X=!1;async function Q(p,d,S){let h=new AbortController,j={controller:h,port:S.port};c.set(p,j);try{let v=await fetch(`http://127.0.0.1:${S.port}/__gallery/events?workspace=own`,{signal:h.signal});if(!v.ok||!v.body)return;ot.has(p)&&x(d),ot.add(p);let P=new TextDecoder,w="";for await(let V of v.body){w+=P.decode(V,{stream:!0});for(let Z=w.indexOf(`
3
-
4
- `);Z>=0;Z=w.indexOf(`
5
-
6
- `)){let J=w.slice(0,Z);w=w.slice(Z+2),/^data: workspace /m.test(J)&&x(d)}}}catch{}finally{c.get(p)===j&&c.delete(p)}}async function A(){for(let[p,d]of c)B.has(p)||d.controller.abort();for(let[p,d]of B){if(X||c.has(p)||St(d)===_)continue;let S=await $t({reportsDirectory:d});S&&!c.has(p)&&!X&&Q(p,d,S)}}let T=Promise.resolve(),at=setInterval(()=>{T=T.then(A).catch(()=>{})},3e3);at.unref();function gt(p){B.clear();for(let[d,S]of p)S&&B.set(d,S);T=T.then(A).catch(()=>{})}function yt(){X=!0,clearInterval(at);for(let{controller:p}of c.values())p.abort();c.clear()}return{serverOf:Y,forward:E,relay:F,shellVouched:ht,follow:gt,close:yt,get following(){return[...c.keys()]}}}import{LINK_FILE as Ft,linkStem as nn,linkValue as ft,ownAddress as Jt,readLinkText as rn}from"../browser/shared/web-links.mjs";import{sameDirectory as rt}from"../browser/shared/preview-server.mjs";import{listReportSlugs as on,slugPattern as I}from"../browser/shared/reports.mjs";import{COMPONENTS_FOLDER as an,DOCUMENT_FOLDERS as sn,PAGE_SLUG as cn,SHARED_FOLDERS as Gt,defaultWorkspace as ln,documentDirectory as un,documentFiles as dt,ensureWorkspace as fn,idHolder as dn,isDocSlug as wn,layoutOf as fe,listTrash as mn,newDocSlug as Yt,packageFolders as pn,pageSlug as kn,readLink as Wt,slugTaken as hn,trashIdPattern as de}from"../browser/shared/workspace.mjs";import{createPage as gn,headOf as we,listPages as yn,newPageSlug as On,pageFiles as wt,readPageMeta as Ht,renamePage as jn}from"../browser/shared/pages.mjs";import{listExtensions as Sn}from"../browser/shared/extensions.mjs";import{effectiveLook as Mt,ownLookFor as bn,ownLookOf as vn,sameLook as xn,withLookField as me}from"../browser/shared/document-look.mjs";import{workspaceLook as Bt,writeWorkspaceLook as En}from"../browser/shared/workspace-look.mjs";import{findIn as An,tidyQuery as Pn}from"../browser/shared/search.mjs";var Ln=([m,x,l,...$])=>$.length?tt("\u68C0\u67E5\u6CA1\u6709\u901A\u8FC7\uFF1A{0}\uFF1B{1}\uFF1B{2} \u7B49 {3} \u6761",m,x,l,$.length+3):l!==void 0?tt("\u68C0\u67E5\u6CA1\u6709\u901A\u8FC7\uFF1A{0}\uFF1B{1}\uFF1B{2}",m,x,l):x!==void 0?tt("\u68C0\u67E5\u6CA1\u6709\u901A\u8FC7\uFF1A{0}\uFF1B{1}",m,x):tt("\u68C0\u67E5\u6CA1\u6709\u901A\u8FC7\uFF1A{0}",m),Lt=m=>m==="en"?"en":null,Nn=32*1024*1024;async function q(m,x){for(let l=0;;l++)try{return await b.rename(m,x)}catch($){if(!["EPERM","EBUSY","EACCES"].includes($.code))throw $;if(l>=5)break;await new Promise(_=>setTimeout(_,60*(l+1)))}await b.cp(m,x,{recursive:!0,errorOnExist:!0,force:!1}),await b.rm(m,{recursive:!0,force:!0,maxRetries:5})}var In=m=>g.resolve(m);function pr({edits:m,reports:x,reportsDirectory:l=Ge,server:$={kind:"dev",version:null,stop:null},components:_=null,changed:N=()=>{},relayed:Nt=N,index:mt=null,web:Y=null,elsewhere:pt=null}){let{trash:E}=fe(l),F=pt??oe({root:l,changed:t=>{t&&nt(t),Nt()}}),kt=null,ht=()=>kt??=tn(),B=mt??qt({root:l,read:Dt(m),draw:(t,e)=>x.words(t,e)}),c=(t,e,n)=>[t,{ok:!1,reason:e,...Tt(n)}],ot=t=>b.readFile(t,"utf8").then(JSON.parse).catch(()=>null),X=t=>un(t,l),Q=t=>dt(X(t)),A=t=>g.join(l,t),T=t=>W(dt(A(t)).html),at=t=>Promise.resolve(m.forgetChanges?.(t)).catch(()=>{}),gt=async t=>{let e=await b.readdir(A(t),{withFileTypes:!0});if(!Gt.includes(t))return e.map(({name:r})=>r);let n=t===an?new Set(pn(l).map(({id:r})=>r.split("/")[0])):new Set;return e.filter(r=>r.isFile()||sn.includes(r.name)&&!n.has(r.name)).map(({name:r})=>r)},yt=async(t,e,n)=>{await b.mkdir(n,{recursive:!0});let r=[];try{for(let o of t)await q(g.join(e,o),g.join(n,o)),r.push(o)}catch(o){for(let a of r)await q(g.join(n,a),g.join(e,a));throw o}},p=async(t,e)=>{if(!Gt.includes(t))return q(A(t),e);await yt(await gt(t),A(t),e),await b.rmdir(A(t)).catch(()=>{})},d=async(t,e)=>Gt.includes(t)&&!await T(t)&&(await Promise.all((await b.readdir(e)).map(n=>W(g.join(A(t),n))))).every(n=>!n),S=async t=>await ot(dt(t).json)??{},h=async t=>{let{title:e=t,description:n="",type:r,instructions:o,icon:a,look:i}=await S(X(t)),s=o===!0?{}:Mt(i,Bt(l));return{slug:t,title:e,description:n,...r?{type:r}:{},...typeof a=="string"&&a?{icon:a}:{},...o===!0?{instructions:!0}:{},...Object.keys(s).length?{look:s}:{}}},j=async t=>{let e=await Wt(A(t));return e&&{slug:t,title:e.title,description:"",kind:"link",url:e.url,...e.icon?{icon:e.icon}:{},...e.siteIcon?{siteIcon:e.siteIcon}:{}}},v=async(t,e,n=[])=>{let r=Ct(t),o=r&&n.find(({id:z})=>z===r.ws),a=o?.facts.get(r.slug);if(a){let z=g.join(o.root,r.slug);return{slug:t,title:a.title,description:a.description,kind:"draft",workspace:r.ws,...a.icon?{icon:a.icon}:{},path:a.path,folder:z,root:o.root}}let{ws:i,title:s,description:u,icon:f,path:k,folder:O,root:y,missing:R}=await ce(t,e);return{slug:t,title:s,description:u,kind:"draft",workspace:i,...f?{icon:f}:{},...k?{path:k,folder:O,root:y}:{},...R?{missing:R}:{}}},P=async(t,e,n,r)=>ie(t)?v(t,n,r):e.includes(t)?await j(t)??{slug:t,title:t,description:"",kind:"link",url:""}:h(t),w=Pt(l),V=()=>ue(ln())===ue(l),Z=(t,e)=>{let n=t.shown.find(({isDefault:s})=>s)?.id??(V()?w:null),r=new Set([...t.drafts.map(s=>Ct(s)?.ws),...t.groups.map(({workspace:s})=>s),...t.shown.map(({id:s})=>s)].filter(Boolean)),o=new Set(t.groups.filter(({workspace:s,title:u})=>s&&!u).map(({workspace:s})=>s));t.groups.find(({id:s})=>s===xt)?.title||o.add(w),o.delete(n);let a=De(new Set([...r,w]),{ids:new Map([...e,[w,[l]]]),stops:ht(),among:o});F.follow(new Map([...a].filter(([s])=>s!==w).map(([s,{root:u}])=>[s,u])));let i=Object.fromEntries([...r].map(s=>[s,{...a.get(s)??{missing:M(s,e).refused??"unknown"},...s===n?{default:!0}:{}}]));return i[w]={...a.get(w),there:!0,self:!0,...w===n?{default:!0}:{}},i},J=()=>kn(l),it=async(t,e)=>{let n=await S(X(t));await G(Q(t).json,`${JSON.stringify({...n,[e]:!0},null,2)}
7
- `)},W=t=>b.access(t).then(()=>!0,()=>!1),U=async(t,{own:e=null}={})=>{let n=new Set((await ct()).map(({slug:r})=>r));n.delete(e);for(let r=1;;r++){let o=r===1?t:`${t}-${r}`;if(!hn(o,l)&&!n.has(o))return o}},st=async t=>{let e=await U(t.slug,{own:t.slug});return wn(t.slug)?e===t.slug&&!await dn(t.slug,l)?e:Yt(l):e},K=async(t,e)=>{let n=Q(t).html,r=await b.readFile(n,"utf8"),o=Zt(r).replace(`data-doc-id="${e}"`,`data-doc-id="${t}"`);o!==r&&await G(n,o)},L=()=>He(l),C=async t=>{await Ve(l,t),N()},D=t=>Me(l,t);async function Ot(t,e="",n=1/0){await D(async()=>{let r=await L();vt(r,t,e,n),await C(r)})}async function jt(t,{parent:e="",after:n=null,first:r=!1}={}){await D(async()=>{let o=await L();for(let i of Object.values(o.children))i.includes(t)&&i.splice(i.indexOf(t),1);let a=typeof n=="string"?Object.keys(o.children).find(i=>o.children[i].includes(n)):void 0;a!==void 0?vt(o,t,a,o.children[a].indexOf(n)+1):vt(o,t,typeof e=="string"?e:"",r===!0?0:1/0),await C(o)})}function pe(t,e){let n=new Set(Object.values(t.children).flat()),r={...t.children};for(let{id:o}of e.groups){if(o===xt)continue;let a=i=>{let s=(e.children[i]??[]).filter(u=>!n.has(u));(Et(i)||s.length)&&(r[i]=s),s.forEach(a)};a(At(o))}return{groups:e.groups,children:r}}function Vt(t){return D(async()=>{let e=await L();for(let[n,r]of Object.entries(e.children)){let o=r.indexOf(t);if(!(o<0))return r.splice(o,1,...e.children[t]??[]),delete e.children[t],await C(e),{parent:n,index:o}}return{parent:"",index:1/0}})}let ke=(t,e)=>B.lines(t,e),Ut=t=>ot(g.join(E,t,"entry.json")),ct=()=>mn(l);async function he(t){let e=await Ht(t,l);if(!e)return c(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4E2A\u9875\u9762");let n=`${Date.now().toString(36)}-${_t(3).toString("hex")}`;try{await b.mkdir(g.join(E,n),{recursive:!0}),await q(wt(t,l).folder,g.join(E,n,"page"))}catch(o){throw await b.rm(g.join(E,n),{recursive:!0,force:!0}).catch(()=>{}),o}let r={id:n,kind:"page",slug:t,title:e.title,at:Date.now(),parent:"",index:-1};return await G(g.join(E,n,"entry.json"),`${JSON.stringify(r,null,2)}
8
- `),[200,{ok:!0,entry:r}]}async function ge(t){let e=g.join(E,t.id,"page"),n=await st(t);if(await b.mkdir(fe(l).customPages,{recursive:!0}),await q(e,wt(n,l).folder),n!==t.slug){let{html:r}=wt(n,l),o=await b.readFile(r,"utf8").catch(()=>null),a=o?.replace(`data-page-id="${t.slug}"`,`data-page-id="${n}"`);o!==null&&a!==o&&await G(r,a)}return await b.rm(g.join(E,t.id),{recursive:!0,force:!0}),[200,{ok:!0,page:await Ht(n,l),entry:{...t,slug:n}}]}async function ye(t){let e=await Wt(A(t));if(!e)return c(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4E2A\u94FE\u63A5");let n=`${Date.now().toString(36)}-${_t(3).toString("hex")}`,r=await L(),{parent:o,index:a}=await Vt(t);try{await b.mkdir(g.join(E,n),{recursive:!0}),await q(A(t),g.join(E,n,"link"))}catch(s){throw await D(()=>C(r)),await b.rm(g.join(E,n),{recursive:!0,force:!0}).catch(()=>{}),s}let i={id:n,kind:"link",slug:t,title:e.title,at:Date.now(),parent:o,index:Number.isFinite(a)?a:-1};return await G(g.join(E,n,"entry.json"),`${JSON.stringify(i,null,2)}
9
- `),[200,{ok:!0,entry:i}]}async function Oe(t){let e=g.join(E,t.id,"link"),n=await st(t);return await q(e,A(n)),await b.rm(g.join(E,t.id),{recursive:!0,force:!0}),await Ot(n,t.parent,t.index<0?1/0:t.index),[200,{ok:!0,report:await j(n),entry:{...t,slug:n}}]}function je(t,{parent:e,after:n,first:r}){let o=i=>Et(i)?Object.hasOwn(t.children,i):Object.values(t.children).some(s=>s.includes(i));if(n!=null){let i=Object.keys(t.children).find(s=>t.children[s].includes(n));return i===void 0?{refused:[404,"after","\u627E\u4E0D\u5230\u8981\u653E\u5728\u5B83\u540E\u9762\u7684\u6761\u76EE"]}:e!=null&&e!==i?{refused:[409,"level","\u8981\u653E\u5728\u5B83\u540E\u9762\u7684\u6761\u76EE\u4E0D\u5728\u8FD9\u4E00\u5C42"]}:{parent:i,index:t.children[i].indexOf(n)+1}}let a=e??At(xt);return Et(a)&&t.groups.some(i=>i.extension&&At(i.id)===a)?{refused:[409,"extension","\u6269\u5C55\u7684\u680F\u91CC\u653E\u4E0D\u4E86\u522B\u7684\u6761\u76EE"]}:o(a)?{parent:a,index:r?0:(t.children[a]??[]).length}:{refused:[404,"parent",Et(a)?"\u627E\u4E0D\u5230\u8FD9\u4E00\u680F":"\u627E\u4E0D\u5230\u8981\u653E\u5230\u5B83\u4E0B\u9762\u7684\u6761\u76EE"]}}let et=new Map;function Se(t){let e=et.get(t);if(e&&Date.now()-e.at<36e5)return e.answer;let n=Y?Y.frameable(t).catch(()=>({frameable:!0,reason:"unknown"})):Promise.resolve({frameable:!0,reason:"unknown"});return et.size>=500&&et.delete(et.keys().next().value),et.set(t,{at:Date.now(),answer:n}),n.then(r=>{["auth","unknown"].includes(r.reason)&&et.get(t)?.answer===n&&et.delete(t)}),n}function Kt(t,e){return Y?.icon?(async()=>{let n=await Y.icon(e).catch(()=>null);if(!n)return null;let r=g.join(A(t),Ft),o=await b.readFile(r,"utf8").catch(()=>null),a=o===null?null:rn(o);if(!a||a.url!==e||a.siteIcon===n)return null;let i=ft({...a,siteIcon:n});return i.refused||!i.value.siteIcon||!await G(r,`${JSON.stringify(i.value,null,2)}
10
- `,{expect:o})?null:(N(),n)})().catch(()=>null):Promise.resolve(null)}let zt={info:async()=>[200,{ok:!0,version:1,gallery:$.version,token:m.token,commands:[...Object.keys(lt)],server:{pid:process.pid,workspace:g.resolve(l),kind:$.kind}}],async outline(){let{outline:t,others:e}=await We(l),n=await J(),r=[...Object.values(t.children).flat(),...n?[n]:[]],o=le(),a=async y=>[y,await P(y,t.links,o,e)],[i,s,u,f]=await Promise.all([Promise.all(r.map(a)),yn(l),ct(),Sn(l)]),k=f.map(({id:y,title:R,icon:z,entries:It,count:ve,error:Qt})=>({id:y,title:R,...z?{icon:z}:{},entries:It,count:ve,...Qt?{error:Tt(Qt)}:{}})),O=await we(l,s);return[200,{ok:!0,outline:t,instructions:n,reports:Object.fromEntries(i),pages:s,head:O,trash:u,workspaces:Z(t,o),self:w,extensions:k}]},trash:async()=>[200,{ok:!0,entries:await ct()}],async stats(t){let e=t.get("slug")??"",n=I.test(e)?await B.facts(e).catch(()=>null):null;return n?[200,{ok:!0,edited:n.edited,words:n.words}]:c(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863")},async query(t){let e;try{e=JSON.parse(t.get("options")??"{}")}catch{return[400,{ok:!1,reason:"options",message:"options is JSON"}]}return B.query(t.get("kind")??"",e,{doc:t.get("doc")})},components:async()=>[200,{ok:!0,..._.read()}],async source(t){let e=t.get("slug")??"",n=t.get("kind")==="page";if(!I.test(e))return c(404,"missing",n?"\u627E\u4E0D\u5230\u8FD9\u4E2A\u9875\u9762":"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863");let r=g.resolve(n?wt(e,l).html:Q(e).html);return await W(r)?[200,{ok:!0,path:r}]:c(404,"missing",n?"\u627E\u4E0D\u5230\u8FD9\u4E2A\u9875\u9762":"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863")},projects:async()=>[200,{ok:!0,workspaces:await Ze(l,{stops:ht()})}],shell:async t=>[200,{ok:!0,shell:await F.shellVouched(t.get("origin"))}],async search(t){let e=Pn(t.get("q")??"");if(!e)return[200,{ok:!0,results:[]}];let{children:n,groups:r,links:o}=await L(),a=[],i=O=>(n[O]??[]).forEach(y=>{!o.includes(y)&&!ie(y)&&a.push(y),i(y)});for(let{id:O}of r)i(At(O));let s=e.toLowerCase(),u=new Map(await Promise.all(a.map(async O=>[O,await h(O)]))),f=JSON.stringify([...u].map(([O,{title:y}])=>[O,y])),k=(await Promise.all(a.map(async O=>{let y=await ke(O,f);if(!y)return null;let R=String(u.get(O).title).toLowerCase().includes(s),{count:z,hits:It}=An(y,e);return R||z?{slug:O,title:R,count:z,hits:It}:null}))).filter(Boolean);return k.sort((O,y)=>Number(y.title)-Number(O.title)||y.count-O.count),[200,{ok:!0,results:k.slice(0,50)}]}},lt={async outline({outline:t,base:e}){return!ae(t)||e!==void 0&&!ae(e)?c(400,"outline","\u6587\u6863\u76EE\u5F55\u7684\u7ED3\u6784\u4E0D\u5BF9\uFF1A\u6BCF\u4EFD\u6587\u6863\u53EA\u80FD\u51FA\u73B0\u4E00\u6B21"):await D(async()=>{let r=await L();return e!==void 0&&!Ue(e,r)?!1:(await C(t.groups?t:pe(t,r)),!0)})?[200,{ok:!0,outline:await L()}]:c(409,"stale","\u6587\u6863\u76EE\u5F55\u521A\u5728\u522B\u5904\u6539\u8FC7")},async move({slug:t,parent:e,after:n=null,first:r=!1,workspace:o}){if(typeof o=="string"&&!rt(o,l))return c(409,"elsewhere","\u8FD9\u4E2A\u9884\u89C8\u670D\u52A1\u5668\u7BA1\u7684\u662F\u53E6\u4E00\u4E2A\u76EE\u5F55\u7684\u6587\u6863");let a=u=>typeof u=="string"&&I.test(u);if(!a(t)||e!==void 0&&e!==""&&!a(e)||n!==null&&!a(n)||typeof r!="boolean")return c(400,"body","\u8BF7\u6C42\u683C\u5F0F\u4E0D\u5BF9");let i=await J();if(i!==null&&[t,e,n].includes(i))return c(409,"instructions","\u5199\u4F5C\u504F\u597D\u4E0D\u5728\u6587\u6863\u76EE\u5F55\u91CC\uFF0C\u4E0D\u80FD\u79FB\u52A8\uFF0C\u4E0B\u9762\u4E5F\u4E0D\u80FD\u653E\u6587\u6863");let s=await Ye(l,t,{parent:e,after:n,first:r});if(s.written&&N(),!s.ok){let[u,f]={missing:[404,"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"],parent:[404,"\u627E\u4E0D\u5230\u8981\u653E\u5230\u5B83\u4E0B\u9762\u7684\u6587\u6863"],after:[404,"\u627E\u4E0D\u5230\u8981\u653E\u5728\u5B83\u540E\u9762\u7684\u6587\u6863"],level:[409,"\u8981\u653E\u5728\u5B83\u540E\u9762\u7684\u6587\u6863\u4E0D\u5728\u8FD9\u4E00\u5C42"],itself:[409,"\u6587\u6863\u4E0D\u80FD\u653E\u5728\u5B83\u81EA\u5DF1\u540E\u9762"],inside:[409,"\u6587\u6863\u4E0D\u80FD\u79FB\u5230\u5B83\u81EA\u5DF1\u6216\u5B83\u4E0B\u9762\u7684\u6587\u6863\u4E0B\u9762"]}[s.reason];return c(u,s.reason,f)}return[200,{ok:!0,...s,outline:await L()}]},async create({title:t,description:e,parent:n="",after:r=null,first:o=!1,language:a}){let i=typeof t=="string"?t.replace(/\s+/g," ").trim().slice(0,200):"",s=await Yt(l);return await at(s),await x.create(s,i,typeof e=="string"&&e.trim()?e.trim():"\u65B0\u6587\u6863",{lang:Lt(a)}),await jt(s,{parent:n,after:r,first:o}),[200,{ok:!0,report:await h(s)}]},async instructions({title:t,description:e,language:n}){let r=await J();if(r)return[200,{ok:!0,report:await h(r)}];let o=await U(cn),a=(i,s)=>typeof i=="string"&&i.trim()?i.trim().slice(0,200):s;return await x.create(o,a(t,"\u5199\u4F5C\u504F\u597D"),a(e,"Agent \u6BCF\u6B21\u5199\u62A5\u544A\u524D\u90FD\u4F1A\u5148\u8BFB\u7684\u5199\u4F5C\u504F\u597D"),{lang:Lt(n),page:!0}),await it(o,"instructions"),[200,{ok:!0,report:await h(o)}]},async components({id:t,hidden:e,shown:n,disabled:r,unlisted:o,net:a,pack:i,enabled:s}){try{return[200,{ok:!0,...await _.write(i!==void 0?{pack:i,enabled:s}:{id:t,hidden:e,shown:n,disabled:r,unlisted:o,net:a})}]}catch(u){return c(409,"components",u)}},async duplicate({slug:t,suffix:e,untitled:n}){if(typeof t!="string"||!I.test(t)||!await T(t))return c(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863");let r=await Yt(l);await at(r);let o=new Set(["",...await gt(t)]);await b.cp(A(t),A(r),{recursive:!0,errorOnExist:!0,filter:O=>o.has(g.relative(A(t),O).split(g.sep)[0])}),await K(r,t);let{title:a}=await h(t),i=a||(typeof n=="string"&&n.trim()?n.trim().slice(0,50):"\u672A\u547D\u540D\u6587\u6863"),s=await m.renameReport(r,`${i}${typeof e=="string"&&e.length>0&&e.length<=20?e:"\uFF08\u526F\u672C\uFF09"}`),u=await L(),[f,k]=Object.entries(u.children).find(([,O])=>O.includes(t))??["",null];return await Ot(r,f,k?k.indexOf(t)+1:1/0),[200,{ok:!0,report:await h(r),notes:s.notes??[]}]},async look({slug:t,look:e}){if(typeof t!="string"||!I.test(t)||!await T(t))return c(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863");if(t===await J())return c(409,"instructions","\u5199\u4F5C\u504F\u597D\u6CA1\u6709\u5B57\u4F53\u4E0E\u5E03\u5C40");if(e!==null&&(typeof e!="object"||Array.isArray(e)))return c(400,"look","\u5B57\u4F53\u4E0E\u5E03\u5C40\u4E0D\u5BF9");let n=Q(t).json,r=null;try{r=JSON.parse(await b.readFile(n,"utf8"))}catch{}if(!r||typeof r!="object"||Array.isArray(r))return c(409,"metadata","\u8FD9\u4EFD\u6587\u6863\u7684\u6807\u9898\u548C\u8BF4\u660E\u8BFB\u4E0D\u51FA\u6765");let o=me(r,bn(e,Bt(l)));return JSON.stringify(o)!==JSON.stringify(r)&&await G(n,`${JSON.stringify(o,null,2)}
11
- `),[200,{ok:!0,report:await h(t)}]},async looks({slug:t}){if(typeof t!="string"||!I.test(t)||!await T(t))return c(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863");let e=await J();if(t===e)return c(409,"instructions","\u5199\u4F5C\u504F\u597D\u6CA1\u6709\u5B57\u4F53\u4E0E\u5E03\u5C40");let n=await ot(Q(t).json);if(!n||typeof n!="object"||Array.isArray(n))return c(409,"metadata","\u8FD9\u4EFD\u6587\u6863\u7684\u6807\u9898\u548C\u8BF4\u660E\u8BFB\u4E0D\u51FA\u6765");let r=Bt(l),o=Mt(n.look,r);try{await En(l,o)}catch(u){return c(409,"workspace",u)}let a=0,i=(await on(l)).filter(u=>u!==e).map(u=>({json:Q(u).json,self:u===t})),s=(await ct()).filter(({kind:u})=>u==="document").map(({id:u})=>({json:dt(g.join(E,u,"report")).json,self:!1}));for(let{json:u,self:f}of[...i,...s])for(let k=0;k<3;k++){let O=await b.readFile(u,"utf8").catch(()=>null),y=null;try{y=JSON.parse(O??"")}catch{}if(!y||typeof y!="object"||Array.isArray(y)||!Object.hasOwn(y,"look")||y.instructions===!0)break;let R=await G(u,`${JSON.stringify(me(y,{}),null,2)}
12
- `,{expect:O}).catch(()=>null);if(R===null)break;if(R){!f&&Object.keys(vn(y.look)).length>0&&!xn(Mt(y.look,r),o)&&a++;break}}return[200,{ok:!0,look:o,replaced:a,report:await h(t)}]},async head({order:t}){let e=Ke(t);return e?(await D(()=>Be(l,e)),N(),[200,{ok:!0,head:await we(l)}]):c(400,"head","\u4FA7\u680F\u5934\u90E8\u7684\u987A\u5E8F\u4E0D\u5BF9")},async"new-page"({title:t,after:e=null,language:n}){let r=typeof t=="string"?t.replace(/\s+/g," ").trim():"";if(!r||r.length>200)return c(400,"title","\u6807\u9898\u4E0D\u80FD\u662F\u7A7A\u7684\uFF0C\u4E5F\u4E0D\u80FD\u8D85\u8FC7 200 \u4E2A\u5B57");if(e!==null&&(typeof e!="string"||!I.test(e)))return c(400,"body","\u8BF7\u6C42\u683C\u5F0F\u4E0D\u5BF9");let o=await On(l);return await gn(o,r,{root:l,blank:!0,after:e,...Lt(n)?{lang:Lt(n)}:{}}),N(),[200,{ok:!0,page:await Ht(o,l)}]},async rename({slug:t,title:e,kind:n="document"}){if(typeof t!="string"||!I.test(t))return c(400,"slug","\u6587\u6863\u540D\u4E0D\u5BF9");if(n==="page"){let o;try{o=await jn(t,e,l)}catch{return c(400,"title","\u6807\u9898\u4E0D\u80FD\u662F\u7A7A\u7684\uFF0C\u4E5F\u4E0D\u80FD\u8D85\u8FC7 200 \u4E2A\u5B57")}return o?[200,{ok:!0,page:o}]:c(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4E2A\u9875\u9762")}let r=await m.renameReport(t,e);return r.ok?[200,{ok:!0,report:await h(t),notes:r.notes}]:c({title:400,missing:404}[r.reason]??409,r.reason,r.message??"\u6539\u540D\u6CA1\u6709\u6210\u529F")},async trash({slug:t,kind:e="document"}){if(typeof t!="string"||!I.test(t))return c(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863");if(e==="page")return he(t);if(e==="link")return ye(t);if(t===await J())return c(409,"instructions","\u5199\u4F5C\u504F\u597D\u4E0D\u80FD\u79FB\u5230\u56DE\u6536\u533A");if(!await T(t))return c(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863");let{title:n}=await h(t),r=`${Date.now().toString(36)}-${_t(3).toString("hex")}`,o=await L(),{parent:a,index:i}=await Vt(t);try{await b.mkdir(g.join(E,r),{recursive:!0}),await p(t,g.join(E,r,"report"))}catch(u){throw await D(()=>C(o)),await b.rm(g.join(E,r),{recursive:!0,force:!0}).catch(()=>{}),u}let s={id:r,kind:"document",slug:t,title:n,at:Date.now(),parent:a,index:Number.isFinite(i)?i:-1};return await G(g.join(E,r,"entry.json"),`${JSON.stringify(s,null,2)}
13
- `),[200,{ok:!0,entry:s}]},async restore({id:t}){let e=typeof t=="string"&&de.test(t)?await Ut(t):null;if(!e)return c(404,"missing","\u56DE\u6536\u533A\u91CC\u6CA1\u6709\u8FD9\u4E00\u9879");if(e.kind==="page")return ge(e);if(e.kind==="link")return Oe(e);let n=g.join(E,t,"report"),r=await d(e.slug,n),o=r?e.slug:await st(e);return r?await yt(await b.readdir(n),n,A(o)):await q(n,A(o)),o!==e.slug&&await K(o,e.slug),await b.rm(g.join(E,t),{recursive:!0,force:!0}),await Ot(o,e.parent,e.index<0?1/0:e.index),[200,{ok:!0,report:await h(o),entry:{...e,kind:"document",slug:o}}]},async destroy({id:t}){let e=typeof t=="string"&&de.test(t)?await Ut(t):null;return e?((e.kind??"document")==="document"&&!await T(e.slug)&&await at(e.slug),await b.rm(g.join(E,t),{recursive:!0,force:!0}),[200,{ok:!0}]):c(404,"missing","\u56DE\u6536\u533A\u91CC\u6CA1\u6709\u8FD9\u4E00\u9879")},async link({url:t,title:e,icon:n=null,parent:r,after:o=null,first:a=!1},{port:i,wait:s=!1}={}){let u=ft({url:t,title:e,icon:n});if(u.refused)return c(400,u.refused,u.message);if(Jt(u.value.url,i))return c(409,"own","\u8FD9\u662F Gallery \u81EA\u5DF1\u7684\u5730\u5740\uFF0C\u8BF7\u76F4\u63A5\u94FE\u63A5\u6587\u6863");if(r!=null&&typeof r!="string"||o!==null&&typeof o!="string"||typeof a!="boolean")return c(400,"body","\u8BF7\u6C42\u683C\u5F0F\u4E0D\u5BF9");let f=await D(async()=>{let O=await L(),y=je(O,{parent:r,after:o,first:a||r==null&&o===null});if(y.refused)return y;let R=await U(nn(u.value.title,u.value.url));return await b.mkdir(A(R),{recursive:!0}),await G(g.join(A(R),Ft),`${JSON.stringify(u.value,null,2)}
14
- `),vt(O,R,y.parent,y.index),await C(O),{slug:R,parent:y.parent,index:y.index}});if(f.refused)return c(...f.refused);let k=Kt(f.slug,u.value.url);return s&&await k,[200,{ok:!0,link:await j(f.slug),parent:f.parent,index:f.index,outline:await L()}]},async"link-set"({slug:t,url:e,title:n,icon:r},{port:o,wait:a=!1}={}){let i=typeof t=="string"&&I.test(t)?await Wt(A(t)):null;if(!i)return c(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4E2A\u94FE\u63A5");let s=e??i.url,u=ft({url:s,title:n??i.title,icon:r===void 0?i.icon??null:r,siteIcon:i.siteIcon??null});if(u.refused)return c(400,u.refused,u.message);let f=u.value.url!==i.url;if(f&&Jt(u.value.url,o))return c(409,"own","\u8FD9\u662F Gallery \u81EA\u5DF1\u7684\u5730\u5740\uFF0C\u8BF7\u76F4\u63A5\u94FE\u63A5\u6587\u6863");if(f&&delete u.value.siteIcon,JSON.stringify(u.value)!==JSON.stringify(i)&&await G(g.join(A(t),Ft),`${JSON.stringify(u.value,null,2)}
15
- `),f){let k=Kt(t,u.value.url);a&&await k}return[200,{ok:!0,link:await j(t)}]},async"draft-add"({path:t,confirm:e=!1,after:n=null}){let r=await Xe(t),o=typeof n=="string"?n:null;if(r.kind==="missing")return c(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4E2A\u6587\u4EF6\u6216\u6587\u4EF6\u5939");if(r.kind==="plain")return c(409,"plain","\u8FD9\u4E0D\u662F Gallery \u7684\u5E95\u7A3F\u6216\u5DE5\u4F5C\u533A\uFF0C\u53EF\u4EE5\u7528\u300C\u5BFC\u5165\u300D\u628A\u6587\u4EF6\u590D\u5236\u8FDB\u6765");if(r.kind==="nested")return c(409,"nested","\u8FD9\u4EFD\u5E95\u7A3F\u4E0D\u5728\u5B83\u5DE5\u4F5C\u533A\u7684\u7B2C\u4E00\u5C42\uFF08\u5728\u56DE\u6536\u533A\u91CC\uFF0C\u6216\u662F\u5199\u4F5C\u504F\u597D\uFF09\uFF0C\u4E0D\u80FD\u6DFB\u52A0");if(r.kind==="name")return c(409,"name","\u8FD9\u4E2A\u6587\u4EF6\u5939\u7684\u540D\u5B57\u4E0D\u662F Gallery \u6587\u6863\u7684\u5199\u6CD5\uFF08\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u8FDE\u5B57\u7B26\uFF09\uFF0C\u4E0D\u80FD\u6DFB\u52A0");let a=r.kind==="workspace"?r.root:r.kind==="folder"?null:r.root,i=!a||!qe(l).some(k=>rt(k.root,a));if(!a){let k=r.kind==="folder"?r.folder:r.parent;if(Qe(k))return c(409,"marker",tt("{0} \u91CC\u7684 gallery.json \u662F\u522B\u7684\u7A0B\u5E8F\u7684\uFF0C\u4E0D\u80FD\u628A\u5B83\u767B\u8BB0\u6210\u5DE5\u4F5C\u533A",k));if(e!==!0)return[409,{ok:!1,reason:"unregistered",folder:k,...Tt(tt("\u4F1A\u628A {0} \u767B\u8BB0\u6210\u4E00\u4E2A\u5DE5\u4F5C\u533A\uFF08\u5728\u91CC\u9762\u653E gallery.json \u548C .gallery/\uFF09",k))}];if(!(await fn(k)).ours)return c(409,"marker",tt("{0} \u91CC\u7684 gallery.json \u662F\u522B\u7684\u7A0B\u5E8F\u7684\uFF0C\u4E0D\u80FD\u628A\u5B83\u767B\u8BB0\u6210\u5DE5\u4F5C\u533A",k));a=k}let s=r.kind==="workspace"||r.kind==="folder";if(rt(a,l))return[200,{ok:!0,kind:s?"workspace":"draft",own:!0,existing:!0,...s?{column:xt}:{entry:r.slug}}];let u=await en(a,{force:!0}).catch(()=>"failed"),f=M(Pt(a));return f.refused==="ambiguous"?c(409,"ambiguous",tt("\u672C\u673A\u767B\u8BB0\u7684 {0} \u4E2A\u5DE5\u4F5C\u533A\u7F16\u53F7\u76F8\u540C\uFF08{1}\uFF09\uFF0C\u5148\u7528 gallery workspaces --forget \u53BB\u6389\u5176\u4E2D\u4E00\u4E2A",f.roots.length,Pt(a))):!f.root||!rt(f.root,a)?u==="temporary"?c(409,"temporary","\u8FD9\u4E2A\u5DE5\u4F5C\u533A\u5728\u7CFB\u7EDF\u7684\u4E34\u65F6\u6587\u4EF6\u5939\u91CC\uFF0C\u4E0D\u80FD\u6DFB\u52A0"):c(409,"registry","\u6CA1\u80FD\u628A\u5B83\u7684\u5DE5\u4F5C\u533A\u8BB0\u8FDB\u672C\u673A\u7684\u767B\u8BB0\u8868"):(nt(a),s?[200,{ok:!0,kind:"workspace",...await ze(l,a,{changed:N,after:o})}]:[200,{ok:!0,kind:"draft",...await se(l,a,r.slug,{changed:N,pick:!0,after:o,fresh:i})}])},async"draft-join"({root:t,slug:e}){if(typeof t!="string"||typeof e!="string"||!I.test(e))return c(400,"body","\u8BF7\u6C42\u683C\u5F0F\u4E0D\u5BF9");if(rt(t,l))return c(409,"own","\u8FD9\u662F\u5F53\u524D\u7684\u5DE5\u4F5C\u533A");let n=M(Pt(t));return!n.root||!rt(n.root,t)?c(409,"registry","\u8FD9\u4E2A\u5DE5\u4F5C\u533A\u4E0D\u5728\u672C\u673A\u7684\u767B\u8BB0\u8868\u91CC"):await W(dt(g.join(t,e)).html)?(nt(t),[200,{ok:!0,...await se(l,t,e,{changed:N})}]):c(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863")},async export({slug:t}){if(typeof t!="string"||!I.test(t)||!await W(X(t)))return c(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863");let{problems:e=[],file:n,refused:r}=await x.export(t);return r?c(r.reason==="missing"?404:409,r.reason,r.message):e.length?c(422,"check",Ln(e)):[200,{ok:!0,path:In(n)}]}},Xt={async frameable({url:t},{port:e}){let n=typeof t=="string"?ft({url:t,title:"-"}):{refused:"url"};return n.refused?c(400,"url","\u8FD9\u4E0D\u662F\u4E00\u4E2A\u7F51\u5740"):Jt(n.value.url,e)?[200,{ok:!0,frameable:!1,reason:"own"}]:[200,{ok:!0,...await Se(n.value.url)}]},async elsewhere({ws:t}){let e=typeof t=="string"?M(t):{refused:"unknown"};if(e.refused)return c(409,e.refused,e.refused==="ambiguous"?"\u672C\u673A\u767B\u8BB0\u7684\u5DE5\u4F5C\u533A\u91CC\u6709\u4E24\u4E2A\u7528\u7684\u662F\u540C\u4E00\u4E2A\u7F16\u53F7\uFF0C\u5148\u7528 gallery workspaces --forget \u53BB\u6389\u5176\u4E2D\u4E00\u4E2A":"\u627E\u4E0D\u5230\u5B83\u6240\u5728\u7684\u5DE5\u4F5C\u533A\uFF1A\u5B83\u4E0D\u5728\u672C\u673A\u7684\u767B\u8BB0\u8868\u91CC");let n=await F.serverOf(e.root);return n.refused?c(409,n.refused,n.message):[200,{ok:!0,origin:`http://127.0.0.1:${n.port}`}]},async"draft-command"({ws:t,name:e,...n}){let r=typeof t=="string"?M(t):{refused:"unknown"};if(r.refused)return c(409,r.refused,"\u627E\u4E0D\u5230\u5B83\u6240\u5728\u7684\u5DE5\u4F5C\u533A\uFF1A\u5B83\u4E0D\u5728\u672C\u673A\u7684\u767B\u8BB0\u8868\u91CC");let o=await F.forward(r.root,e,n);return o[1]?.ok&&nt(r.root),o},async"draft-duplicate"({ws:t,slug:e,suffix:n,untitled:r}){if(t===w)return c(409,"self","\u8FD9\u662F\u5F53\u524D\u7684\u5DE5\u4F5C\u533A");let o=typeof t=="string"?M(t):{refused:"unknown"};if(o.refused)return c(409,o.refused,"\u627E\u4E0D\u5230\u5B83\u6240\u5728\u7684\u5DE5\u4F5C\u533A\uFF1A\u5B83\u4E0D\u5728\u672C\u673A\u7684\u767B\u8BB0\u8868\u91CC");let[a,i]=await F.forward(o.root,"duplicate",{slug:e,suffix:n,untitled:r});if(!i?.ok)return[a,i];let s=i.report?.slug;if(typeof s!="string"||!I.test(s))return c(502,"answer","\u5B83\u6240\u5728\u5DE5\u4F5C\u533A\u7684\u670D\u52A1\u6CA1\u6709\u7ED9\u51FA\u7ED3\u679C");let u=ut(t,s);return nt(o.root),await jt(u,{after:ut(t,e)}),[200,{ok:!0,entry:u,report:{...i.report,slug:u,kind:"draft",workspace:t}}]},async"draft-import"({ws:t,uploads:e,parent:n="",from:r,language:o}){if(t===w)return c(409,"self","\u8FD9\u662F\u5F53\u524D\u7684\u5DE5\u4F5C\u533A");let a=typeof t=="string"?M(t):{refused:"unknown"};if(a.refused)return c(409,a.refused,"\u627E\u4E0D\u5230\u5B83\u6240\u5728\u7684\u5DE5\u4F5C\u533A\uFF1A\u5B83\u4E0D\u5728\u672C\u673A\u7684\u767B\u8BB0\u8868\u91CC");let[i,s]=await F.forward(a.root,"import",{uploads:e,parent:n,from:r,language:o});if(!s?.ok)return[i,s];nt(a.root);let u=(Array.isArray(s.reports)?s.reports:[]).filter(k=>typeof k=="string"&&I.test(k)).map(k=>ut(t,k)),f=typeof n=="string"&&I.test(n)?ut(t,n):null;if(f&&u.length&&Object.values((await L()).children).some(k=>k.includes(f)))for(let k of u)await jt(k,{parent:f});return[200,{...s,reports:u}]},async"draft-create"({ws:t,title:e,description:n,language:r,parent:o="",after:a=null,first:i=!1}){if(t===w)return c(409,"self","\u8FD9\u662F\u5F53\u524D\u7684\u5DE5\u4F5C\u533A");let s=typeof t=="string"?M(t):{refused:"unknown"};if(s.refused)return c(409,s.refused,"\u627E\u4E0D\u5230\u5B83\u6240\u5728\u7684\u5DE5\u4F5C\u533A\uFF1A\u5B83\u4E0D\u5728\u672C\u673A\u7684\u767B\u8BB0\u8868\u91CC");let[u,f]=await F.forward(s.root,"create",{title:e,description:n,language:r});if(!f?.ok)return[u,f];let k=f.report?.slug;if(typeof k!="string"||!I.test(k))return c(502,"answer","\u5B83\u6240\u5728\u5DE5\u4F5C\u533A\u7684\u670D\u52A1\u6CA1\u6709\u7ED9\u51FA\u7ED3\u679C");let O=ut(t,k);return nt(s.root),await jt(O,{parent:o,after:a,first:i}),[200,{ok:!0,entry:O,report:{...f.report,slug:O,kind:"draft",workspace:t}}]},async reveal({entry:t,ws:e,page:n}){let r=le(),o=null;return typeof n=="string"?o=I.test(n)?wt(n,l).folder:null:typeof t=="string"&&Ct(t)?o=(await ce(t,r)).folder:e===w?o=g.resolve(l):typeof e=="string"&&(o=M(e,r).root??null),!o||!await W(o)?c(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4E2A\u6587\u4EF6\u5939"):[200,{ok:!0,path:o,...await re(o)}]},async title({url:t}){let e=typeof t=="string"?ft({url:t,title:"-"}):{refused:"url"};if(e.refused)return c(400,"url","\u8FD9\u4E0D\u662F\u4E00\u4E2A\u7F51\u5740");let n=Y?await Y.title(e.value.url).catch(()=>""):"",r=typeof n=="string"?n:n?.title,o=["auth","unknown"].includes(n?.reason)?n.reason:void 0;return[200,{ok:!0,title:typeof r=="string"?r.slice(0,200):"",...o?{reason:o}:{}}]}};function be(t,e,n){if(t.method==="GET"&&Object.hasOwn(zt,n)){let o=t.headers.host??"",a=t.socket.localPort;return o!==`127.0.0.1:${a}`&&o!==`localhost:${a}`?H(e,403,{ok:!1,reason:"host"}):zt[n](new URL(t.url??"/","http://localhost").searchParams).then(([i,s])=>H(e,i,s),i=>H(e,...c(500,"read",i)))}if(t.method==="POST"&&n==="stop")return m.respond(async o=>{let a=await m.check(o);return a.error?a.error:$.kind!=="cli"||typeof $.stop!="function"?c(409,"dev","\u8FD9\u662F npm run dev \u7684\u670D\u52A1\u5668\uFF1A\u5728\u8FD0\u884C\u5B83\u7684\u5730\u65B9\u505C\u6B62\u5B83"):(e.once("finish",()=>$.stop()),[200,{ok:!0,pid:process.pid}])})(t,e);if(t.method==="POST"&&n==="pack-install")return m.respond(async o=>{let a=await m.check(o,Nn);if(a.error)return a.error;if(!_?.install)return c(404,"unknown");try{return[200,{ok:!0,..._.install(a.body??{})}]}catch(i){if(!i.code)throw i;return c(409,i.code,i)}})(t,e);if(t.method==="POST"&&n==="todo")return(async()=>{let o=await m.check(t);if(o.error)return o.error;let{slug:a,items:i}=o.body??{};return typeof a!="string"||!I.test(a)||!Array.isArray(i)?[400,{ok:!1,reason:"body"}]:!await T(a)||a===await J()?c(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"):m.setTodos(a,i)})().then(([o,a])=>H(e,o,a),o=>H(e,...c(500,"write",o.message)));if(t.method==="POST"&&(n==="draft-export"||n==="draft-upload"))return(async()=>{let o=n==="draft-upload",a=new URL(t.url??"/","http://localhost").searchParams,i={};if(o){let f=m.checkHeaders(t);if(f)return f;if(!/^application\/octet-stream\b/i.test(t.headers["content-type"]??""))return[415,{ok:!1,reason:"type"}]}else{let f=await m.check(t);if(f.error)return f.error;i=f.body&&typeof f.body=="object"?f.body:{}}let s=o?a.get("ws"):i.ws,u=typeof s=="string"?M(s):{refused:"unknown"};return u.refused?c(409,u.refused,"\u627E\u4E0D\u5230\u5B83\u6240\u5728\u7684\u5DE5\u4F5C\u533A\uFF1A\u5B83\u4E0D\u5728\u672C\u673A\u7684\u767B\u8BB0\u8868\u91CC"):s===w?c(409,"self","\u8FD9\u662F\u5F53\u524D\u7684\u5DE5\u4F5C\u533A"):F.relay(u.root,o?"upload":"export",{body:i,query:{name:a.get("name")??void 0},request:t,response:e})})().then(o=>{o&&(t.resume(),H(e,...o))},o=>{t.resume(),e.headersSent?e.destroy():H(e,...c(500,"read",o))});let r={port:t.socket.localPort};return t.method==="POST"&&Object.hasOwn(lt,n)?m.respond(async o=>{let a=await m.check(o);if(a.error)return a.error;let i=a.body&&typeof a.body=="object"?a.body:{};return typeof i.workspace=="string"&&!rt(i.workspace,l)?c(409,"elsewhere","\u8FD9\u4E2A\u9884\u89C8\u670D\u52A1\u5668\u7BA1\u7684\u662F\u53E6\u4E00\u4E2A\u76EE\u5F55\u7684\u6587\u6863"):lt[n](i,r)})(t,e):t.method==="POST"&&Object.hasOwn(Xt,n)?(async()=>{let o=await m.check(t);return o.error?o.error:Xt[n](o.body&&typeof o.body=="object"?o.body:{},r)})().then(([o,a])=>H(e,o,a),o=>H(e,...c(500,"read",o))):H(e,404,{ok:!1,reason:"unknown"})}return{handle:be,outline:L,trashEntries:ct,place:Ot,freeSlug:U,index:B,run:(t,e,n={})=>Object.hasOwn(lt,t)?lt[t](e??{},{wait:!0,...n}):Promise.resolve(c(404,"unknown","\u6CA1\u6709\u8FD9\u4E2A\u547D\u4EE4")),close:()=>F.close()}}export{pr as a};
@@ -1,15 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{a as ke,b as X,c as Q,f as ye,g as L,h as xe,i as tt,l as Se,m as Ne}from"./chunk-HXG7EOPJ.mjs";import{a as $t}from"./chunk-ZTHICSSF.mjs";import{b as fe,c as wt,e as K,f as he,i as ue,j as pe,m as me,n as ge,o as $e,p as we,q as be,r as bt}from"./chunk-6N3PX4XX.mjs";import{a as mt}from"./chunk-PAREWQGB.mjs";import{a as oe,b as se,c as ne,d as ie,e as ae,f as re,g as ce,h as le,l as de}from"./chunk-BFJGHSQN.mjs";import{b as gt,c as Xt,d as Qt,e as te,g as ee}from"./chunk-U5XL7D6A.mjs";import{a as w,b as Yt,c as qt}from"./chunk-HYMEEXKN.mjs";import{g as E,j as Jt,l as Vt,m as Zt}from"./chunk-HDWTZ763.mjs";import{existsSync as yo,readFileSync as yi,readdirSync as xi}from"node:fs";import S from"node:fs/promises";import N from"node:path";function ve(t){if(!t||!Array.isArray(t.lines))throw new Error("diff: lines must be an array.");t.lines.forEach(e=>{if(!e||!["added","removed","unchanged"].includes(e.type)||typeof e.content!="string"||/[\r\n]/.test(e.content))throw new Error("diff: each line needs a valid type and single-line content.");if(e.lineNumber!=null&&(!Number.isInteger(e.lineNumber)||e.lineNumber<1))throw new Error("diff: lineNumber must be a positive integer.")})}import{BODY as yt,isInstance as Bo}from"../browser/shared/components/index.mjs";import{ATTRIBUTE as Ho}from"../browser/shared/components/installed.mjs";import{attr as F,elementsOf as Oe,hasClass as Ko,walk as xt}from"../browser/shared/html-tree.mjs";import{CHART_DATA as Go,CHART_KEY as Jo,CHART_SOURCE as C,VIEW_FROM as et,cellWords as Vo,rowsReading as Ee,tableRows as Zo}from"../browser/shared/table-chart.mjs";var Yo=t=>t.tagName==="script"&&(F(t,"type")??"").trim().toLowerCase()==="application/json",Te=t=>t.nodeName==="#text"?t.value:(t.childNodes??[]).map(Te).join("");function qo(t){let e=t;for(;e&&e.tagName!=="figure";)e=e.parentNode;let s=e?Oe(e).find(o=>/^h[2-4]$/.test(o.tagName)):null;return s?Vo(Te(s)):""}function Le(t,e,s=w(t)){let o=[];return xt(s,n=>{let i=e(n);if(i===void 0||!n.sourceCodeLocation)return;let r=n.childNodes.find(Yo);o.push({type:i,line:n.sourceCodeLocation.startLine,text:r?r.childNodes.map(c=>c.value??"").join(""):null,source:F(n,Go),tag:n.tagName,holder:n.parentNode?.tagName,title:qo(n)})},yt),o}var Xo=t=>t.tagName==="ol"&&F(t,"data-doc-chart")==="flow",ot=(t,e)=>Le(t,s=>Xo(s)?void 0:F(s,"data-doc-chart"),e),Qo=t=>Le(t,e=>Ko(e,"doc-diff")?"diff":void 0);function G(t){let e=new Map;return xt(t,s=>{let o=F(s,C);if(o===void 0||!s.sourceCodeLocation)return;(e.get(o)??e.set(o,[]).get(o)).push({line:s.sourceCodeLocation.startLine,offset:s.sourceCodeLocation.startOffset,table:Oe(s).find(i=>i.tagName==="table")??null})},{...yt,inTemplates:!1}),e}function St(t,e){let s=e.get(t)??[];if(s.length===0)return{error:`no table's frame carries ${C}="${t}", so the chart has nothing to draw: put the table back, or delete the card`};if(s.length>1)return{error:`${s.length} tables carry ${C}="${t}" (lines ${s.map(({line:c})=>c).join(", ")}): a key names one table (the chart draws the first); take it off the copies`};let[{line:o,table:n}]=s;if(!n)return{error:`the frame carrying ${C}="${t}" (line ${o}) holds no table`};let i=$t(n),r=Zo(i);return r.error?{error:`its table (line ${o}) ${r.error}`}:{...r,line:o,cells:i}}function Nt(t){let e=[t,...L(t).filter(({files:n})=>n.includes("kit.js")).map(n=>tt(n,"kit.js")??"")].join(`
3
- `),s=new Set([...e.matchAll(/DocCharts\.define\(\s*(["'`])([a-z][a-z0-9-]*)\1/g)].map(n=>n[2])),o=new Set([...e.matchAll(/DocCharts\.define\(\s*(["'`])([^"'`\n]*)\1/g)].map(n=>n[2]).filter(n=>!s.has(n)));return{defined:s,misnamed:o}}function vt(t){let e=w(t),s=[],{defined:o,misnamed:n}=Nt(t),i=null;for(let{type:r,line:c,text:l,source:a,tag:d,holder:f}of ot(t,e)){let u=`data-doc-chart="${r}" (line ${c})`;if(d==="table"){s.push(f==="figure"?`${u} is on a table inside a <figure>: the chart's card is a figure of its own, so write the table outside it, its <caption> the chart's title`:`${u} is on a table the tools leave as written (inside a whole block, an element with a class of the document's own, a cell): a chart is drawn from a table outside one`);continue}if(n.has(r)){s.push(`${u}: the document's script defines "${r}" with DocCharts.define, which refuses that name: a chart type's name is lowercase letters, digits and hyphens, a letter first ("interval", "ci-plot"); rename it in both places`);continue}if(!o.has(r)){s.push(`${u}: the document's script does not define "${r}": define it once in the document's <script> with DocCharts.define("${r}", ({ host, data, tokens, width, height }) => { \u2026 }) (references/writing-html.md, "Figures and charts")`);continue}if(a!==void 0){if(l!==null){s.push(`${u}: a chart drawn from a table takes its data from the table: take its <script type="application/json"> out`);continue}let h=St(a,i??=G(e));h.error&&s.push(`${u}: ${h.error}`);continue}if(l===null){s.push(`${u} needs its data in a <script type="application/json"> child`);continue}try{JSON.parse(l)}catch(h){s.push(`${u}: its data is not valid JSON (${h.message})`)}}s.push(...Ce(e,i??=G(e)).failures);for(let{line:r,text:c}of Qo(t)){if(c===null)continue;let l=`.doc-diff (line ${r})`;try{ve(JSON.parse(c))}catch(a){s.push(`${l}: ${a instanceof SyntaxError?`its options are not valid JSON (${a.message})`:a.message}`)}}return s}function Ae(t,{written:e=t}={}){let s=w(t),o=[],{defined:n}=Nt(t),i=null,r=null;for(let{type:c,line:l,text:a,source:d,title:f,tag:u}of ot(t,s)){if(d===void 0||u==="table"||a!==null||!n.has(c))continue;let h=`data-doc-chart="${c}" (line ${l})`;if(!f){r??=new Set(e===t?[]:ot(e).map(k=>k.source).filter(k=>k!==void 0));let b=e!==t&&!r.has(d);o.push(`${h}: this chart card has no title: ${b?"write a <caption> on its table (the one with data-doc-chart), which becomes the card's h3":"write an h3 in the card's figure, before the chart"}`)}let m=St(d,i??=G(s));if(m.error)continue;let{blank:p,twice:g}=Ee(m.cells,m.data);p&&o.push(`${h}: its table's header (line ${m.line}) has a cell with no words, so that column's values are keyed "" in data: write the column's name there`),g.length>0&&o.push(`${h}: its table's header (line ${m.line}) names ${g.map(b=>`"${b}"`).join(", ")} twice, so data keeps the later column's value under it: give each column a name of its own`)}return o.push(...Ce(s,i??=G(s)).notes),o}var kt=500;function Ce(t,e){let s=[],o=[],n=E().packages;return xt(t,i=>{let r=F(i,et);if(r===void 0||!i.sourceCodeLocation)return;let c=F(i,Ho),l=`${c??i.tagName} (line ${i.sourceCodeLocation.startLine})`;if(!Bo(i))return void s.push(`<${i.tagName}> (line ${i.sourceCodeLocation.startLine}) carries ${et}="${r}", which only a view of a table carries: an instance of a custom block (<div data-doc-component="<scope>/<name>">) whose block's needs hold "tables"; take it off`);if(!Jo.test(r))return void s.push(`${l}: ${et}="${r}" is no key: a letter, then letters, digits, "_" or "-", 32 at most, as the table's frame writes it in ${C}`);let a=e.get(r)??[];if(a.length===0)return void s.push(`${l}: no table's frame carries ${C}="${r}", so the view has no table to read: put the table back, or delete the view`);if(a.length>1)return void s.push(`${l}: ${a.length} tables carry ${C}="${r}" (lines ${a.map(({line:g})=>g).join(", ")}): a key names one table (the view reads the first); take it off the copies`);let[{line:d,offset:f,table:u}]=a;if(!u)return void s.push(`${l}: the frame carrying ${C}="${r}" (line ${d}) holds no table`);i.sourceCodeLocation.startOffset<f&&o.push(`${l} stands before the table it reads (${C}="${r}", line ${d}): it works there, but each block's writing.md writes the table first and the view after it, as its example does: move the view below the table, unless the document is meant to open on it`);let h=n.get(c)?.needs;h&&!h.includes("tables")&&o.push(`${l} carries ${et}="${r}", but its block's needs hold no "tables", so it reads no table: add "tables" to needs in its component.json, or take the key off`);let m=$t(u);m.merged&&o.push(`${l}: its table (line ${d}) has merged cells, which no view reads, so the view shows nothing of it: write each value in its own cell`);let p=m.names?m.rows.length:Math.max(0,m.rows.length-1);p>kt&&o.push(`${l}: its table (line ${d}) has ${p} rows: every view of a table reads it again as it is typed in, and past ${kt} rows that slows typing in it; split it, or keep what a view shows to ${kt} rows`)},yt),{failures:s,notes:o}}function ze(t){let e=w(t),s=[],o=[],{defined:n}=Nt(t),i=null,r=(c,l)=>`${c} ${l}${c===1?"":"s"}`;for(let{type:c,line:l,text:a,source:d,tag:f}of ot(t,e)){if(d===void 0||f==="table"||a!==null||!n.has(c))continue;let u=St(d,i??=G(e));if(u.error)continue;let{rows:h,columns:m,foot:p,extra:g}=Ee(u.cells,u.data),b=`data-doc-chart="${c}" (line ${l})`,k=[r(h,"row")];for(let{name:x,numbers:v,words:T,empty:H}of m){let R=v+T+H,q=v===R&&R>0?"numbers":T===R&&R>0?"words":[v&&r(v,"number"),T&&`${T} as words`,H&&`${H} empty (null)`].filter(Boolean).join(", ")||"no rows";k.push(`"${x}": ${q}`),v>0&&T>0&&o.push(`${b}: its table's column "${x}" (line ${u.line}) reads as numbers in ${r(v,"row")} and as words in ${T}: write each of its cells as one number (an empty cell, "\u2014" or "n/a" for none: null in data), or, for a column of words, data-sort-type="text" on its header cell`)}p>0&&o.push(`${b}: its table's <tfoot> (line ${u.line}) holds ${r(p,"row")} the chart leaves out, and a table with a <tfoot> has no table tools in the preview: keep a total out of a table you chart and say it in the text`),g>0&&o.push(`${b}: ${r(g,"row")} of its table (line ${u.line}) ${g===1?"has":"have"} cells past the header, which the chart does not read: give each column a header cell`),s.push(`${c} (line ${l}) reads its table (line ${u.line}): ${k.join("; ")}`)}return{readings:s,notes:o}}import{BODY as Si,componentOf as Ni,matchesNode as xo}from"../browser/shared/components/index.mjs";import{FLOW as vi}from"../browser/shared/components/list.mjs";import{attr as O,elementsOf as So,walk as M}from"../browser/shared/html-tree.mjs";import{GLYPH_SETS as Oi,ICON_COLORS as No,glyphOf as Ei,glyphValue as Ti,iconKind as Ut,iconMarkup as Li,iconValueOf as Ai}from"../browser/shared/emoji/icon-value.mjs";import ts from"node:vm";import{LINE_START as it,lineStart as es}from"../browser/shared/code-lines.mjs";import{BODY as Me,COMPONENTS as os,FLOWS as ss,instanceSlots as ns,instancesOf as is,isInstance as _,isSlot as Pe,matchesNode as P,ownSlots as as,partOf as Lt,vocabulary as rs}from"../browser/shared/components/index.mjs";import{ATTRIBUTE as A,INSTANCE as cs,PACKAGE_ID as at,SCHEMA as Ot,SLOT as z,schemaAhead as ls}from"../browser/shared/components/installed.mjs";import{packageScript as ds}from"../browser/shared/export-wrap.mjs";import{asDocName as fs,kitNamespace as hs}from"../browser/shared/old-names.mjs";import{shortSheets as us}from"../browser/shared/components/sheets.mjs";import{attr as y,curlyQuoted as ps,hasClass as ms,walk as J}from"../browser/shared/html-tree.mjs";var{authoring:nt,runtime:Ie}=rs(),gs="input, select, textarea, button, details, table",rt=t=>t.sourceCodeLocation?.startLine,$=t=>rt(t)?` (line ${rt(t)})`:"";function je(t){let e=(o,n)=>{let i=Array.from({length:n.length+1},(r,c)=>c);for(let r=1;r<=o.length;r++){let c=i[0];i[0]=r;for(let l=1;l<=n.length;l++){let a=i[l];i[l]=Math.min(i[l]+1,i[l-1]+1,c+(o[r-1]===n[l-1]?0:1)),c=a}}return i[n.length]},[s]=[...nt.keys()].filter(o=>o.startsWith(t.slice(0,7))).map(o=>[o,e(t,o)]).sort((o,n)=>o[1]-n[1]);return s&&s[1]<=3?` (${s[0]}?)`:""}function $s(t,e,s){let{part:o,property:n,min:i}=t.shares,r=new RegExp(`(?:^|;)\\s*${n}\\s*:\\s*([^;]*)`),c=s.map(f=>r.exec(y(f,"style")??"")?.[1].trim()??null),l=c.filter(f=>f!==null);if(l.length===0)return[];let a=`${t.id}${$(e)}`;return l.length<c.length?[`${a}: ${n} on ${l.length} of its ${c.length} ${o}: write it on every one of them, or on none (equal widths)`]:l.map(Number).some(f=>!Number.isFinite(f)||f<i-1e-9||f>1)?[`${a}: ${n} is a share of the row, a number from ${Math.round(i*1e3)/1e3} to 1 (${l.join(", ")})`]:[]}var st={"doc-dialog-header":'a detail card has no header: its content region (<div class="doc-dialog-content">) stands alone in its panel',"doc-dialog-title":"a detail card's title is an ordinary heading (<h3>), first in its content region","doc-dialog-close":"a detail card has no close button: Esc and a press outside it close it","data-doc-dialog-close":"a detail card has no close button: Esc and a press outside it close it","doc-section-header":"a section's title is a plain heading (<h2>) with an ordinary paragraph below it for the line that says what the section is: no <div> goes around them","doc-grid":'a card row is now columns: <div class="doc-columns"> holding one <div class="doc-column"> per card',"doc-grid-3":'a card row is now columns: <div class="doc-columns"> holding three <div class="doc-column">',"doc-lede":`write the line under the title as a paragraph of the header (an ordinary <p>), or as small text, <p class="doc-note"): the header's lines read as the body's paragraphs`,"doc-source":`write the line under the title as a plain paragraph of the header (an ordinary <p>), or as small text (<p class="doc-note">): the header's lines read as the body's paragraphs`,"doc-prose":"write the text straight in its flow (the page, a Sheet panel, a section, a panel, a column\u2026): it reads the same there","doc-prose-h1":"write an h1","doc-prose-h2":"write an h2","doc-prose-h3":"write an h3","doc-prose-h4":"write an h4","doc-state-grid":'put the groups side by side in columns (<div class="doc-columns">)',"doc-state-group":"write the group's title as a heading and its controls as blocks of their own in a column","doc-state-status":'write the line as small text, <p class="doc-note">',"doc-code-block":'a code block is <div class="doc-code"> holding its title (<div class="doc-code-title">) and the <pre><code>',"doc-code-card":'a code block is <div class="doc-code"> holding its title and its <pre>; a diff is <div class="doc-diff">',"doc-code-header":'write the title as <div class="doc-code-title">: the kit draws the rest of the header',"data-doc-diff":'a diff is <div class="doc-diff"> holding its title and its options as JSON (sdk/doc-code.d.ts)',"data-doc-diff-stats":"the kit shows a diff's counts in its header: remove it","doc-code--wrap":"a code block wraps its long lines by itself: remove it (doc-code--nowrap scrolls them instead)"},ws={[it]:'write it on its <div class="doc-code">',"data-start":`write ${it} on its <div class="doc-code">`,"data-line-numbers":'write it on its <div class="doc-code">',"data-folded-lines":'write it on its <div class="doc-code">',"data-title":'write the title in its <div class="doc-code-title">',"data-wrap":'for long lines that scroll, write class="doc-code doc-code--nowrap" on its <div class="doc-code">'};function bs(t){let e=[],s=t.tagName==="pre"?t.parentNode:t.tagName==="code"&&t.parentNode?.tagName==="pre"?t.parentNode.parentNode:null;if(s?.tagName&&P(s,".doc-code"))for(let[n,i]of Object.entries(ws))y(t,n)!==void 0&&e.push(`${n}${$(t)} on the <${t.tagName}> of a code block does nothing: ${i}`);let o=t.tagName==="div"&&P(t,".doc-code")?y(t,it):void 0;return o!==void 0&&es(o)===null&&e.push(`${it}="${o}"${$(t)}: the number of a code block's first line is a whole number from 1`),e}var Re=ss.join(", "),ks=t=>P(t.parentNode,Re)||t.parentNode?.tagName==="div"&&!y(t.parentNode,"class")&&P(t.parentNode.parentNode,Re);function ys(t,e){let s=[];J(e,n=>s.push(...ps(t,n)));let o=n=>n.replace(/=(\s*)[“”]/,'=$1"').replace(/[“”]$/,'"');return s.map(({written:n,line:i},r)=>r===0?`line ${i}: attribute ${n} uses curly quotes (U+201C/U+201D), which HTML reads as part of the value: write straight quotes, ${o(n)}; an editor keeping a file's \u201C\u2026\u201D style may change them`:`line ${i}: attribute ${n} uses curly quotes too: write ${o(n)}`)}var Fe={details:"write a plain <details> without the class (its <summary>, then what it holds): the export makes it the kit's"},xs="write a <section> of no attribute straight in it for each tab, starting with its heading (<h2>\u2013<h4>), the tab's name, the rest its blocks, and nothing else: the export makes the kit's tabs",Ss='a bookmark written the short way is a paragraph in a flow holding only <a class="doc-bookmark" href="https://\u2026">its title</a> (a title attribute its description, nothing else on it, words alone in it): the export makes the card';function Ue(t){let e=[];return J(t,s=>{y(s,A)!==void 0&&e.push(s)},Me),e}var Ns=t=>{let e=t.parentNode;for(;e&&!(_(e)||Pe(e));)e=e.parentNode;return e??null};function vs(t,e){let s=[];return J(t,o=>{let n=y(o,z);if(n===void 0)return;if(_(o))return void s.push(`${z}="${n}"${$(o)} on the instance itself: a slot is an element inside it`);if(!Pe(o))return void s.push(`${z}${$(o)} on a <${o.tagName}>: a slot is a block-level <div> or <section>`);let i=Ns(o),r=i&&_(i)?e?.get(y(i,A)):null;if(!i||!_(i)||r&&We(i,r,o))return void s.push(`${z}="${n}"${$(o)} stands outside any instance's own markup: a slot is a part of a component package's instance, written in its template`);y(o,"data-block-id")!==void 0&&s.push(`${z}="${n}"${$(o)}: a slot is no block: it carries no data-block-id`)}),s}var Os=(t,e)=>{for(let s=e.parentNode;s;s=s.parentNode)if(s===t)return!0;return!1},We=(t,e,s)=>Object.values(e.parts??{}).filter(({edit:o})=>o==="text"||o==="data").some(({at:o})=>Lt(t,o).some(n=>Os(n,s))),_e=(t,e)=>as(t).filter(s=>!We(t,e,s)),Es=t=>t.flatMap(e=>_(e)?at.test(y(e,A))?[]:[`${A}="${y(e,A)}"${$(e)} names no custom block: write <scope>/<name>, the id of a custom block of the workspace's components/ folder`]:[`${A}${$(e)} on a <${e.tagName}>: an instance of a component is a block-level <div> or <section>`]);function Be(t){let e=Ue(t).filter(o=>_(o)&&at.test(y(o,A))),s=e.length>0?E():null;return e.flatMap(o=>{let n=y(o,A),i=s.packages.get(n);if(i&&!ls(y(o,Ot),i.schema))return[];if(i)return[`line ${rt(o)}: <${o.tagName} ${A}="${n}">: ${Ot}="${y(o,Ot)}" is past the ${i.schema??1} its package's manifest reads (schema): nothing can write it back, and the block shows read-only until the package reads it`];let r=s.problems.get(n)?.problem,c=r?`package ${n} does not load (${Jt("en",r)})`:`no package ${n} in this workspace (components/${n}/component.json)`;return[`line ${rt(o)}: <${o.tagName} ${A}="${n}">: ${c}: the block shows what it holds, read-only, and moves, copies and deletes whole`]})}function Et(t,e){let s=[];for(let{name:o,value:n}of t.attrs){if(st[o]&&!nt.has(o)){s.push(`${o}${$(t)} is gone: ${st[o]}`);continue}if(o.startsWith("data-doc-")&&!nt.has(o)&&s.push(Ie.has(o)?`${o}${$(t)} is the kit's to set: remove it`:`${o}${$(t)} is no attribute of the kit's${je(o)}`),o==="class"){for(let i of n.split(/\s+/).filter(e))if(!nt.has(i)){if(st[i]){s.push(`class ${i}${$(t)} is gone: ${st[i]}`);continue}s.push(Ie.has(i)?`class ${i}${$(t)} is the kit's to set: remove it`:`class ${i}${$(t)} is no class of the kit's${je(fs(i))}: give a class of the document's own a name of its own (not doc-\u2026)`)}}}return s}var De=t=>t.startsWith("doc-");function Ts(t){try{return new ts.Script(ds(t),{filename:"kit.js"}),null}catch(e){let s=/^kit\.js:(\d+)/.exec(e.stack??"")?.[1];return{message:e.message,line:s?Number(s):null}}}var Tt=new Map;function Ls(t){if(!t.files.includes("kit.js"))return null;if(Tt.get(t.folder)?.stamp!==t.stamp){let e=tt(t,"kit.js"),s=e===null?null:Ts(e),o=e===null?`${t.id}: its kit.js cannot be read`:s&&`${t.id}: its kit.js does not run: ${s.message}${s.line?` (line ${s.line})`:""}`;Tt.set(t.folder,{stamp:t.stamp,failure:o})}return Tt.get(t.folder).failure}function At(t,e=w(t),s=null){let o=ys(t,e),n=Ue(e);o.push(...Es(n));let i=n.length>0?s??E():null,r=i?[...i.packages.values()]:[];i&&o.push(...L(t,i,e).map(Ls).filter(Boolean));for(let a of[...os,...r].filter(d=>d.match&&(d.parts||d.pairs)))for(let d of is(e,a)){if(a.empty&&!(d.childNodes??[]).some(h=>h.tagName||h.nodeName==="#text"&&h.value.trim()))continue;let f=a.id==="sheets"?us(d):null;if(f){o.push(`${a.id}${$(d)} has no tabs and is no short form: ${f.why??"it stands where no block does (in a whole block or a figure)"}; ${xs}`);continue}if(Fe[a.id]&&Object.values(a.parts??{}).some(h=>Lt(d,h.at).length<(h.optional?0:h.min??1))){o.push(`${a.id}${$(d)} carries the kit's class without the kit's parts: ${Fe[a.id]}`);continue}let u={};for(let[h,m]of Object.entries(a.parts??{})){if(m.edit==="flow"&&at.test(a.id)){let b=_e(d,a).filter(k=>y(k,z)===h);b.length===0&&!m.optional&&o.push(`${a.id}${$(d)} has no ${h} (${z}="${h}")`);for(let k of b.slice(1))o.push(`${a.id}${$(k)}: slot "${h}" twice`);u[h]=b.slice(0,1);continue}u[h]=Lt(d,m.at);let p=m.optional?0:m.min??1,g=m.max??1/0;u[h].length<p?o.push(`${a.id}${$(d)} has ${u[h].length===0?"no":`${u[h].length} of`} ${h} (${m.at.replace(":scope > ","")})${u[h].length>0?`, at least ${p}`:""}`):u[h].length>g&&o.push(`${a.id}${$(d)} has ${u[h].length} of ${h}, at most ${g}`)}if(a.only){let h=new Set(a.only.flatMap(m=>u[m]));for(let m of(d.childNodes??[]).filter(p=>p.tagName&&!h.has(p)))o.push(`${a.id}${$(d)} holds a <${m.tagName}>${$(m)}: only its ${a.only.join(", ")} (${a.only.map(p=>a.parts[p].at.replace(":scope > ","")).join(", ")}) go in it`)}if(a.shares&&o.push(...$s(a,d,u[a.shares.part])),at.test(a.id)){let h=Object.entries(a.parts??{}).filter(([,m])=>m.edit==="flow").map(([m])=>m);for(let m of _e(d,a).filter(p=>!h.includes(y(p,z))))o.push(`${a.id}${$(m)}: slot "${y(m,z)}" is no part of its manifest edited as flow`)}for(let{a:h,attrA:m,b:p,attrB:g}of a.pairs??[]){let b=u[h].map(x=>y(x,m)),k=u[p].map(x=>y(x,g));for(let x of new Set(b.filter((v,T)=>b.indexOf(v)!==T)))o.push(`${a.id}${$(d)}: ${h} "${x}" twice`);for(let x of b.filter(v=>!k.includes(v)))o.push(`${a.id}${$(d)}: ${h.replace(/s$/,"")} "${x}" has no ${p.replace(/s$/,"")} (${g}="${x}")`);for(let x of k.filter(v=>!b.includes(v)))o.push(`${a.id}${$(d)}: ${p.replace(/s$/,"")} "${x}" has no ${h.replace(/s$/,"")} (${m}="${x}")`)}}o.push(...vs(e,i?.packages));let c=new Set,l=[];J(e,a=>{if(_(a)){let u=new Set(ns(a));o.push(...Et(a,De)),J(a,h=>o.push(...Et(h,De)),{stop:h=>u.has(h)});return}a.tagName==="pre"&&ks(a)&&o.push(`<pre>${$(a)} straight in the text: a code block is <div class="doc-code"> holding its title (<div class="doc-code-title">) and the <pre>`),o.push(...bs(a)),a.tagName==="a"&&ms(a,"doc-bookmark")&&o.push(`<a class="doc-bookmark">${$(a)} is no bookmark: ${Ss}`),o.push(...Et(a,hs));let d=y(a,"data-doc-bind");d!==void 0&&(d.trim()?P(a,gs)?a.tagName==="button"&&y(a,"value")===void 0?o.push(`data-doc-bind${$(a)} on a button without a value: give it the value a click chooses`):c.add(d.trim()):o.push(`data-doc-bind${$(a)} on a ${a.tagName}: only inputs, selects, textareas, buttons with a value, details and tables hold a key`):o.push(`data-doc-bind${$(a)} names no key`));let f=y(a,"data-doc-show");f!==void 0&&l.push([a,f])},Me);for(let[a,d]of l){let f=d.split(":")[0].trim();!f||!d.includes(":")?o.push(`data-doc-show="${d}"${$(a)}: write key:value`):c.has(f)||o.push(`data-doc-show="${d}"${$(a)}: nothing binds "${f}" (data-doc-bind="${f}")`)}return o.push(...Rs(t,e)),o}var As=/(?<![\\$])\$(?=[^\s$])([^$]*?[^\s$\\])\$(?![$\d])/g,Cs=/(?:(?<![A-Za-z0-9_])[A-Za-z]|[)\]}])_[A-Za-z0-9{]/,zs=t=>/[\\^]/.test(t)||!t.startsWith("{")&&Cs.test(t),Is=new Set(["head","code","pre","kbd","samp","script","style","template","textarea","noscript","svg","math","title","iframe","object"]),js=`.doc-math-inline, .doc-math-block, .doc-code, .doc-diff, [data-doc-math-dollar], [data-doc-chart], ${cs}`;function Rs(t,e){let s=[],o=n=>{for(let i of n.childNodes??[])if(i.nodeName==="#text"&&i.sourceCodeLocation&&i.value.includes("$")){let{startOffset:r,endOffset:c}=i.sourceCodeLocation;for(let l of t.slice(r,c).matchAll(As)){if(!zs(l[1]))continue;let a=l[1].replace(/\s+/g," "),d=a.length>60?`${a.slice(0,59)}\u2026`:a;s.push(`line ${qt(t,r+l.index)}: $${d}$ is not drawn as a formula (single dollars are off: they are money): write \\(${d}\\)`)}}else i.tagName&&!Is.has(i.tagName)&&!P(i,js)&&o(i)};return o(e),s}import V from"node:fs";import W from"node:path";import{COLOR_NAMES as Ks}from"../browser/shared/colors.mjs";import{FOLD_DOTS as Gs}from"../browser/shared/code-folds.mjs";import{kitPublicDirectory as Js,kitSourceDirectory as Vs,release as Zs}from"../browser/shared/paths.mjs";import{FLOW_LABEL as Ua}from"../browser/shared/components/list.mjs";var Fs={"code-title":{zh:"\u4EE3\u7801\u5757",en:"Code"},"plain-text":{zh:"\u7EAF\u6587\u672C",en:"Plain text"},"fold-code":{zh:"\u6298\u53E0\u6216\u5C55\u5F00\u4EE3\u7801\u5757",en:"Collapse or expand the code block"},"copy-code":{zh:"\u590D\u5236\u4EE3\u7801",en:"Copy code"},copied:{zh:"\u5DF2\u590D\u5236",en:"Copied"},wrap:{zh:"\u81EA\u52A8\u6362\u884C",en:"Wrap lines"},"no-wrap":{zh:"\u53D6\u6D88\u81EA\u52A8\u6362\u884C",en:"Stop wrapping lines"},fold:{zh:"\u6298\u53E0",en:"Collapse"},unfold:{zh:"\u5C55\u5F00",en:"Expand"},line:{zh:"\u7B2C {0} \u884C",en:"Line {0}"},lines:{zh:"\u7B2C {0}\u2013{1} \u884C",en:"Lines {0}\u2013{1}"},"diff-counts":{zh:"\u65B0\u589E {0} \u884C\uFF0C\u5220\u9664 {1} \u884C",en:"Lines added: {0}, removed: {1}"}};var He="data-ge-language",_s={"code-title":"--doc-word-code-title"};function Ds(t,e,s,...o){let n=t[s];if(!n)throw new Error(`The kit has no word "${s}" here (src/render/kit/words.js).`);let i=n[e]??n.zh;return o.length===0?i:i.replace(/\{(\d+)\}/g,(r,c)=>c<o.length?String(o[c]):r)}var Ms=`:root[${He}="en"], :root:not([${He}])[lang|="en" i]`;function Ke(){let t=e=>Object.entries(_s).map(([s,o])=>`${o}: ${JSON.stringify(Ds(Fs,e,s))};`).join(" ");return`:root { ${t("zh")} }
4
- ${Ms} { ${t("en")} }`}import{LOOK as Ct,LOOK_ATTRIBUTES as Ps,SERIF_FONT as Ge,SIZE_FACTOR as Us,SPACING as Ws,WIDTH as zt}from"../browser/shared/document-look.mjs";var Je=[["--doc-body-font-size","--doc-body-line-height"],["--doc-small-font-size","--doc-small-line-height"],["--doc-note-font-size","--doc-note-line-height"],["--doc-title-font-size","--doc-title-line-height"],["--doc-h1-font-size","--doc-h1-line-height"],["--doc-h2-font-size","--doc-h2-line-height"],["--doc-h3-font-size","--doc-h3-line-height"],["--doc-h4-font-size","--doc-h4-line-height"],["--doc-card-title-font-size","--doc-card-title-line-height"],["--doc-table-font-size","--doc-table-line-height"]],Bs=["--doc-component-gap","--doc-block-gap","--doc-media-gap","--doc-paragraph-gap","--doc-group-gap","--doc-list-gap"],It="--doc-content-max-width";function Hs(t){let e=new Map;for(let[,s,o]of String(t).matchAll(/^\s*(--doc-[a-z0-9-]+):\s*([^;]+);/gm))e.has(s)||e.set(s,o.trim());return e}var ct=t=>`${Math.round(t)}px`;function lt(t,{size:e="default",spacing:s="default",width:o="default"}={}){let n=a=>{let d=/^(-?[0-9.]+)px$/.exec(t.get(a)??"");if(!d)throw new Error(`src/render/kit/styles/tokens.css: ${a} is no length in px (src/render/look-css.mjs reads it)`);return Number(d[1])},i=Us[e],{leading:r,gaps:c}=Ws[s],l={};if(e!=="default"||s!=="default")for(let[a,d]of Je){let f=n(a)*i;e!=="default"&&(l[a]=ct(f)),l[d]=ct(Math.round(f)+(n(d)-n(a))*i*r)}if(s!=="default"){for(let a of Bs)l[a]=ct(n(a)*c);l["--doc-space"]=String(c)}if(o!=="default"){if(n(It)!==zt.default)throw new Error(`src/render/kit/styles/tokens.css: ${It} is not \u9ED8\u8BA4 \u6B63\u6587\u5BBD\u5EA6's ${zt.default}px (src/shared/document-look.mjs WIDTH)`);l[It]=ct(zt[o])}return l}var U=(t,e)=>`${t} { ${Object.entries(e).map(([s,o])=>`${s}: ${o};`).join(" ")} }`,D=(t,e)=>`[${Ps[t]}="${e}"]`;function Ve(t){let e=Hs(t),s=e.get("--doc-font");if(!s)throw new Error("src/render/kit/styles/tokens.css: no --doc-font (src/render/look-css.mjs keeps it as --doc-sans-font)");let o=[U(`:root${D("font","serif")}`,{"--doc-sans-font":s,"--doc-font":Ge}),U(`:root${D("font","mixed")}`,{"--doc-heading-font":Ge})],[,...n]=Ct.size,[,...i]=Ct.spacing,[,...r]=Ct.width;for(let c of n)o.push(U(`:root${D("size",c)}`,lt(e,{size:c})));for(let c of i)o.push(U(`:root${D("spacing",c)}`,lt(e,{spacing:c})));for(let c of r)o.push(U(`:root${D("width",c)}`,lt(e,{width:c})));for(let c of n)for(let l of i){let a=lt(e,{size:c,spacing:l});o.push(U(`:root${D("size",c)}${D("spacing",l)}`,Object.fromEntries(Je.map(([,d])=>[d,a[d]]))))}return o.join(`
5
- `)}var Ze=Object.fromEntries(K.filter(t=>t.file).map(t=>[t.file,t.build])),tr=Object.keys(Ze),Z=t=>W.join(Vs,t),Ys=(t,e,s)=>({entryPoints:[Z(t)],bundle:!0,write:!1,format:"iife",platform:"browser",target:"es2022",...typeof e=="function"?e():e,...s}),qs=t=>{let e=Ze[t];if(!e)throw new Error(`src/render/kit-build.mjs: no kit file "${t}"`);return e},dt=new Map;function Xs(t,e){let s=[...e.matchAll(/^@import\s+"\.\/([a-z0-9-]+\.css)";\s*$/gm)].map(i=>i[1]),o=V.readdirSync(W.dirname(Z(t))).filter(i=>i.endsWith(".css")&&i!==W.basename(t)),n=[...o.filter(i=>!s.includes(i)).map(i=>`${i} is not listed`),...s.filter((i,r)=>!o.includes(i)||s.indexOf(i)!==r).map(i=>`${i} is listed but missing, or listed twice`)];if(n.length>0)throw new Error(`src/render/kit/${t}: ${n.join("; ")}`);return s.map(i=>W.join(W.dirname(t),i))}var Qs=t=>t.replace(/@(text|highlight)-colors\b/g,(e,s)=>Ks.map(o=>`.doc-${s}-${o}`).join(", ")),tn=t=>{let e=Qs(t.join(`
6
- `)).replaceAll("@fold-dots",Gs).replace(/^@kit-words;$/m,()=>Ke());return e.replace(/^@kit-look;$/m,()=>Ve(e))};function jt(t,{fresh:e=!1}={}){let s=qs(t);if(Zs)return V.promises.readFile(W.join(Js,t),"utf8");if(s.read)return V.promises.readFile(Z(s.read),"utf8");if(s.styles)return V.promises.readFile(Z(s.styles),"utf8").then(o=>Promise.all(Xs(s.styles,o).map(n=>V.promises.readFile(Z(n),"utf8")))).then(tn);if(e||!dt.has(t)){let o=fe(Ys(s.bundle,s.options)).then(n=>n.outputFiles[0].text);o.catch(()=>dt.delete(t)),dt.set(t,o)}return dt.get(t)}import{kitNamespace as en}from"../browser/shared/old-names.mjs";import{attr as Rt,hasClass as ht}from"../browser/shared/html-tree.mjs";var Ye=t=>t.tagName==="section"&&ht(t,"doc-section"),on=new Set(["section","header","footer","nav","script","style","template","dialog","link","meta"]),sn=t=>!on.has(t.tagName),ft=t=>t.nodeName==="#text"?t.value:(t.childNodes??[]).map(ft).join("");function Xe(t,e=[]){for(let s of t.childNodes??[])s.tagName&&((s.tagName==="main"&&ht(s,"doc-page")||Rt(s,"data-doc-sheet")!==void 0)&&e.push(s),Xe(s.tagName==="template"?s.content:s,e));return e}var nn=/^(p|li|h[1-4]|blockquote|ul|ol)$/,Qe=["doc-summary","doc-panel","doc-note","doc-callout"],an=t=>nn.test(t.tagName)||Qe.some(e=>ht(t,e)),rn=new Set(["none","auto","100%","inherit","initial","unset","revert"]),qe=t=>[...t.matchAll(/(?:^|[;{\s])(?:max-)?width\s*:\s*([^;}]+)/gi)].some(([,e])=>!rn.has(e.replace(/!important/i,"").trim().toLowerCase())),cn=t=>{let e=t.trim().split(/\s*[\s>+~]\s*/).at(-1)??"",s=/^(p|li|h[1-4]|blockquote|ul|ol)\b/.test(e)||Qe.some(n=>e.includes(`.${n}`)),o=[...t.matchAll(/\.([\w-]+)/g)].some(([,n])=>!en(n))||t.includes("#");return s&&!o};function ln(t){let e=[],s=(o,n)=>{for(let i of o.childNodes??[]){if(!i.tagName)continue;let r=n||i.tagName==="main"&&ht(i,"doc-page");if(r&&an(i)&&qe(Rt(i,"style")??"")&&e.push(`<${i.tagName}> with style="${Rt(i,"style").trim()}"`),i.tagName==="style"){let c=ft(i).replace(/\/\*[\s\S]*?\*\//g,"");for(let[,l,a]of c.matchAll(/([^{}]+)\{([^{}]*)\}/g))if(qe(a))for(let d of l.split(","))cn(d)&&e.push(`"${d.trim()}" in the document's style`)}s(i.tagName==="template"?i.content:i,r)}};return s(t,!1),e}function to(t,{written:e=t}={}){let s=[],o=w(t),n=ln(o);n.length>0&&s.push(`body text given a width of its own (${n.slice(0,3).join("; ")}${n.length>3?`; ${n.length-3} more`:""}): its lines break before the reading column's edge, leaving an extra right margin; let body text fill the column`);for(let i of Xe(o)){let r=i.childNodes.filter(c=>c.tagName);r.forEach((c,l)=>{if(!Ye(c))return;let a=l+1;for(;a<r.length&&sn(r[a]);)a++;let d=r.slice(l+1,a);if(d.length===0||!Ye(r[a]??{})||/^h[1-4]$/.test(d[0].tagName))return;let f=c.childNodes.map(g=>g.tagName?g:null).filter(Boolean).map(ft).find(g=>g.trim())?.replace(/\s+/g," ").trim().slice(0,40)??"",[u]=d,h=ft(u).replace(/\s+/g," ").trim(),m=`<${u.tagName}>${h?` "${h.length>30?`${h.slice(0,30)}\u2026`:h}"`:""}`,p=u.sourceCodeLocation?.startLine;s.push(`${d.length} block${d.length===1?"":"s"} of body text right after the section "${f}" stand outside it${p?` (line ${p})`:""}, ${d.length===1?`the ${m}`:`the first a ${m}`}, between two sections, with no heading of their own: fine if meant, otherwise they belong inside that section`)})}return s.push(...Ae(t,{written:e})),s}import{attr as eo,hasClass as dn}from"../browser/shared/html-tree.mjs";var oo="Write instead where it came from, in words, or a path relative to materials/ (materials/data.csv)",fn=new Set(["script","style","template","noscript","textarea","pre","code","kbd","samp","var"]),hn=["doc-math-inline","doc-math-block"],un=/\\\([\s\S]*?\\\)|\\\[[\s\S]*?\\\]|\$\$[\s\S]*?\$\$/g,pn=/(?<!\\)\$(?:\\[\s\S]|[^\\$])+\$/g,mn=/[\s"'<>|()[\]{};,。;:、!?()《》「」『』“”‘’【】]/u,gn=/[^\s"'<>|()[\]{};,。;:、!?()《》「」『』“”‘’【】]+/gu,io=/^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,$n=/\.[A-Za-z0-9]{1,8}$/,wn=[/(?<![A-Za-z0-9_\\])[A-Za-z]:[\\/]/g,/(?<![A-Za-z0-9_.~:/\\-])\/(?:Users|home|root|tmp|private|mnt|opt|Volumes|var\/folders)\/(?=\S)/g,/(?<![A-Za-z0-9_.~:/\\-])~\/(?=\S)/g,/(?<![A-Za-z0-9_$\\])\$(?:HOME|\{HOME\})\/(?=\S)/g,/(?<![A-Za-z0-9_:\\])\\\\[A-Za-z0-9][\w.$-]*\\(?=[^\s\\])/g,/%(?:TEMP|TMP|APPDATA|LOCALAPPDATA|USERPROFILE)%/gi],bn=/(?:^|[\\/])(?:AppData|scratchpad)(?=[\\/]|$)/i,kn=/^(?:[A-Za-z]:|[\\/]|%[A-Za-z]+%)[\s\S]*[\\/](?:temp|tmp)(?=[\\/])/i,yn=t=>t.includes("://")&&!/^file:/i.test(t),so=12;function no(t,e){let s=e;for(;s<t.length&&!mn.test(t[s])&&!(io.test(t[s])&&$n.test(t.slice(e,s)));)s++;return t.slice(e,s).replace(/[.,;:!?]+$/,"")}function xn(t,e=!1){let s=c=>c.replace(/[^\n]/g," "),o=t.replace(un,s),n=e?o.replace(pn,s):o,i=[],r=(c,l)=>i.some(a=>a.at<=c+l.length&&c<=a.at+a.path.length);for(let c of wn)for(let l of n.matchAll(c)){let a=no(n,l.index);a.length>=l[0].length+2&&!r(l.index,a)&&i.push({at:l.index,path:a})}for(let c of n.matchAll(gn)){let l=c.index;for(;l<c.index+c[0].length&&io.test(n[l]);)l++;let a=no(n,l);/[\\/]/.test(a)&&(bn.test(a)||kn.test(a))&&!yn(a)&&!r(l,a)&&i.push({at:l,path:a})}return i.sort((c,l)=>c.at-l.at)}function ao(t,e=w(t)){let s=[],o=(r,c)=>{for(let l of r.childNodes??[])if(l.nodeName==="#text"){if(!l.sourceCodeLocation)continue;for(let{at:a,path:d}of xn(l.value,c))s.push({line:l.sourceCodeLocation.startLine+(l.value.slice(0,a).match(/\n/g)?.length??0),path:d})}else l.tagName&&!fn.has(l.tagName)&&eo(l,"hidden")===void 0&&!hn.some(a=>dn(l,a))&&o(l,c||eo(l,"data-doc-math-dollar")!==void 0)};o(e,!1);let n=s.slice(0,so).map(({line:r,path:c})=>`line ${r}: "${c.length>80?`${c.slice(0,77)}\u2026`:c}" is a path of this machine in the text a reader reads: a reader on another machine cannot open it. ${oo}`),i=s.slice(so);return i.length>0&&n.push(`${i.length} more path${i.length===1?"":"s"} of this machine in the text a reader reads, on line${new Set(i.map(({line:r})=>r)).size===1?"":"s"} ${[...new Set(i.map(({line:r})=>r))].join(", ")}. ${oo}`),n}import{elementsOf as ro}from"../browser/shared/html-tree.mjs";import{netSnapshot as Sn}from"../browser/shared/net-cache.mjs";import{hostIn as Nn,netHostsOf as vn}from"../browser/shared/net-policy.mjs";var On=(t,e)=>`<script type="application/json" data-doc-snapshot data-at="${e}">${JSON.stringify(t).replace(/</g,"\\u003c")}</script>`,Ft=t=>t.some(({needs:e})=>Array.isArray(e)&&e.includes("workspace"));function co(t,{slug:e,packages:s,root:o,at:n=new Date,workspace:i=null}){let r=s.flatMap(({needs:f})=>vn(f)),c=r.length===0?null:Sn(o,e,f=>{try{return Nn(new URL(f).hostname,r)!==null}catch{return!1}}),l={...i&&Ft(s)?i:{},...c?{net:c}:{}};if(Object.keys(l).length===0)return t;let a=ro(ro(w(t)).find(f=>f.tagName==="html")??{}).find(f=>f.tagName==="head"),d=a?.sourceCodeLocation?.endTag?.startOffset??a?.sourceCodeLocation?.startTag?.endOffset;return d===void 0?t:`${t.slice(0,d)} ${On(l,n.toISOString())}
7
- ${t.slice(d)}`}import{MENTION as En,MENTION_ICON as Tn}from"../browser/shared/components/mention.mjs";import{escapeAttribute as Ln}from"../browser/shared/escape.mjs";import{attr as lo,elementsOf as An,hasClass as fo,walk as Cn}from"../browser/shared/html-tree.mjs";import{addressOn as zn,decoded as In,fromFile as jn,hosted as Rn,pageAddress as Fn,workbenchHash as _n}from"../browser/shared/page-address.mjs";function Dn(t,e,s){let o=jn(t,e),n=zn(o,s);return n||Rn(t)?n:Fn(o)??(_n(o)===null?null:{slug:null,block:null})}function Mn(t,e,s,o){let n=w(t),i=new Set,r=[];Cn(n,a=>{let d=lo(a,"data-block-id");d!==void 0&&i.add(d),a.tagName==="a"&&lo(a,"href")!==void 0&&a.sourceCodeLocation?.startTag&&r.push(a)});let c=new Map,l=({startOffset:a,endOffset:d})=>c.set(a,[d,""]);for(let a of r){let{prefix:d,value:f}=a.attrs.find(({name:k})=>k==="href"),u=f.startsWith("#")?In(f.slice(1)):null,h=u===null?f&&Dn(f,e,o):i.has(u)?{slug:e,block:u}:null;if(!h)continue;let m=s(h,f);if(m===f)continue;let{attrs:p,startTag:g,endTag:b}=a.sourceCodeLocation;if(m===null)l(g),b&&l(b),fo(a,En)&&An(a).filter(k=>fo(k,Tn)).forEach(k=>l(k.sourceCodeLocation));else{let k=d?`${d}:href`:"href";c.set(p[k].startOffset,[p[k].endOffset,`${k}="${Ln(m)}"`])}}return[...c].sort(([a],[d])=>d-a).reduce((a,[d,[f,u]])=>`${a.slice(0,d)}${u}${a.slice(f)}`,t)}function ho(t,e,s,{blocks:o=!0,links:n}){return Mn(t,e,({slug:i,block:r})=>{let c=s(i);if(c===null)return null;if(!r||!o)return i===e&&r?null:c;let l=`#${encodeURIComponent(r)}`;return i===e?l:`${c}${l}`},n)}import ut from"node:fs";import Pn from"node:path";import{extensionOf as Un,imageFile as Wn,mediaTypeOf as Bn}from"../browser/shared/media.mjs";var Mt=1024*1024,Hn=Mt,po=2400,_t=2e3,Kn=.25,Gn=new Set(["png","gif"]),uo=.75;function Jn(t){if(t.length<16||t.toString("latin1",0,4)!=="RIFF"||t.toString("latin1",8,12)!=="WEBP")return!1;for(let e=12;e+8<=t.length;){let s=t.toString("latin1",e,e+4);if(s==="VP8L")return!0;if(s==="VP8 "||s==="ANMF")return!1;let o=t.readUInt32LE(e+4);e+=8+o+o%2}return!1}function Vn(t){let e=(s,o)=>s+o<=t.length;if(e(0,24)&&t.readUInt32BE(0)===2303741511&&t.toString("latin1",12,16)==="IHDR")return{width:t.readUInt32BE(16),height:t.readUInt32BE(20)};if(e(0,10)&&/^GIF8[79]a$/.test(t.toString("latin1",0,6)))return{width:t.readUInt16LE(6),height:t.readUInt16LE(8)};if(e(0,4)&&t[0]===255&&t[1]===216){for(let s=2;e(s,4);){if(t[s]!==255)return null;let o=t[s+1];if(o===255){s+=1;continue}if(o===216||o===1||o>=208&&o<=215){s+=2;continue}if(o>=192&&o<=207&&![196,200,204].includes(o))return e(s,9)?{width:t.readUInt16BE(s+7),height:t.readUInt16BE(s+5)}:null;if(o===217||o===218)return null;s+=2+t.readUInt16BE(s+2)}return null}if(e(0,30)&&t.toString("latin1",0,4)==="RIFF"&&t.toString("latin1",8,12)==="WEBP"){let s=t.toString("latin1",12,16);if(s==="VP8 ")return{width:t.readUInt16LE(26)&16383,height:t.readUInt16LE(28)&16383};if(s==="VP8L"){let o=t.readUInt32LE(21);return{width:(o&16383)+1,height:(o>>>14&16383)+1}}return s==="VP8X"?{width:t.readUIntLE(24,3)+1,height:t.readUIntLE(27,3)+1}:null}if(e(0,12)&&t.toString("latin1",4,8)==="ftyp"&&/avi[fs]/.test(t.toString("latin1",8,Math.min(t.length,t.readUInt32BE(0))))){let s=null;for(let o=t.indexOf("ispe",0,"latin1");o>=0&&e(o,16);o=t.indexOf("ispe",o+4,"latin1")){let n={width:t.readUInt32BE(o+8),height:t.readUInt32BE(o+12)};(!s||n.width*n.height>s.width*s.height)&&(s=n)}return s}return null}var Zn=Mt;function Yn(t){let e;try{e=ut.openSync(t,"r");let{size:s}=ut.fstatSync(e),o=Buffer.alloc(Math.min(s,Zn));return ut.readSync(e,o,0,o.length,0),{length:s,head:o}}catch{return null}finally{e!==void 0&&ut.closeSync(e)}}var j=t=>`${Math.max(.1,t/Mt).toFixed(1)} MB`;function qn({bytes:t,width:e,height:s,extension:o,lossless:n}){let i=Math.max(e,s),r=Math.min(1,_t/i),c=Math.min(t,e*s*r*r*Kn);if(i>po){if(!n)return c<=t*uo?` \u2014 a ${_t}px copy would be about ${j(c)}`:"";let l=t*r*r;return` \u2014 a ${_t}px copy would be about ${j(l)}${o==="png"&&c<l/2?`, or ${j(c)} as a JPEG (for a photograph)`:""}`}return!n&&c<=t*uo?` \u2014 written again as a JPEG of quality about 82, it would be about ${j(c)}`:o==="png"&&c<t/2?` \u2014 as a JPEG (for a photograph) it would be about ${j(c)}`:""}var Dt=t=>t===2?"twice":`${t} times`;function mo({html:t,directory:e,tree:s=w(t)}){let{embedded:o,unserved:n}=le({html:t,directory:e,tree:s}),i=new Map,r=(l,a,d,f=!1)=>{let u=i.get(l)??i.set(l,{at:[],shows:0,served:d}).get(l);u.at.push(a),f||(u.shows+=1)};for(let{file:l,line:a,icon:d}of o)Wn(l)&&r(l,a,!0,d);for(let{file:l,line:a}of n)Bn(l).startsWith("image/")&&r(l,a,!1);let c=[];for(let[l,{at:a,shows:d,served:f}]of[...i].sort(([,u],[,h])=>Math.min(...u.at)-Math.min(...h.at))){let u=Yn(Pn.join(e,l));if(!u)continue;let{length:h,head:m}=u,p=Vn(m),g=p?Math.max(p.width,p.height):0,b=h>Hn||g>po,k=f&&d>1;if(!b&&!k)continue;let x=[...new Set(a)],v=`line${x.length===1?"":"s"} ${x.length>1?`${x.slice(0,-1).join(", ")} and ${x.at(-1)}`:x[0]}`,T=k?`shown ${Dt(d)}: the export embeds it ${Dt(d)}; show it once and refer back to it in words`:"";if(!b){c.push(`${l} (${v}): ${T} (${j(Math.ceil(h/3)*4*d)} as data: URLs)`);continue}let H=a.length===1||!f?"":`, ${Dt(a.length)}`,R=f?a.length:1,q=`${j(Math.ceil(h/3)*4*R)} as ${R===1?"a data: URL":"data: URLs"}`,Uo=p?`, ${p.width}\xD7${p.height}px`:"",Kt=Un(l),Gt=p?qn({bytes:h,...p,extension:Kt,lossless:Gn.has(Kt)||Jn(m)}):"",Wo=f?`the export embeds it as it is${H}, ${q}${Gt}`:`its name keeps it out of the preview and the export (the failure at its line says why); copied into assets/ under a name they take, the export embeds it as it is, ${q}${Gt}: copy it in at the size the page needs`;c.push(`${l} (${v}): ${j(h)}${Uo}; ${Wo}${T?`; ${T}`:""}`)}return c}import{COMPONENTS as ui}from"../browser/shared/components/index.mjs";import{withLook as pi}from"../browser/shared/document-look.mjs";import{reportsDirectory as mi}from"../browser/shared/paths.mjs";import{documentLook as gi}from"../browser/shared/workspace-look.mjs";import go from"node:fs";import{MENTION as $o,MENTION_ICON as wo}from"../browser/shared/components/mention.mjs";import{escapeAttribute as Xn,escapeText as Qn}from"../browser/shared/escape.mjs";import{iconUrl as ti,validIcon as ei}from"../browser/shared/emoji/icon-value.mjs";import{attr as oi,hasClass as si,walk as ni}from"../browser/shared/html-tree.mjs";import{fromFile as ii,isFileLink as ai,pageAddress as ri}from"../browser/shared/page-address.mjs";import{reportsDirectory as ci}from"../browser/shared/paths.mjs";import{documentDirectory as li,documentFiles as di}from"../browser/shared/workspace.mjs";function fi(t,e){let{html:s,json:o}=di(li(t,e));if(!go.existsSync(s))return null;try{let{title:n,icon:i}=JSON.parse(go.readFileSync(o,"utf8"));return{title:n,icon:i}}catch{return{}}}function hi(t,e,s,o){if(s==="words"||typeof t!="string"||!ei(t))return null;if(s==="preview")return ti(t,e,{tab:!0});let n=Qt({value:t,slug:e,tab:!0,reportsDirectory:o});return n&&`data:${n.type};base64,${n.body.toString("base64")}`}function bo(t,{slug:e,mode:s="export",reportsDirectory:o=ci}){if(!t.includes($o))return t;let n=new Map,i=c=>(n.has(c)||n.set(c,fi(c,o)),n.get(c)),r=new Map;return ni(w(t),c=>{let l=c.tagName==="a"&&si(c,$o)?oi(c,"href"):void 0,{startTag:a,endTag:d}=c.sourceCodeLocation??{};if(!l||!ai(l)||!a||!d)return;let f=ri(ii(l,e))?.slug;if(!f)return;let u=i(f);if(!u)r.set(a.endOffset-1,[a.endOffset-1," data-doc-gone"]);else if(u.title){let h=hi(u.icon,f,s,o);r.set(a.endOffset,[d.startOffset,`${h?`<img class="${wo}" src="${Xn(h)}" alt="">`:`<span class="${wo}"></span>`}${Qn(u.title)}`])}}),[...r].sort(([c],[l])=>l-c).reduce((c,[l,[a,d]])=>`${c.slice(0,l)}${d}${c.slice(a)}`,t)}var $i=/<script\b[^>]*\bdata-doc-kit="runtime"[^>]*><\/script>/;function wi(t,e,s){let o=Vt(e).filter(({id:n})=>!s.some(i=>i.id===n)).map(Zt).join(" ");return o?t.replace($i,n=>`${n}
8
- <script data-doc-dev>${o}</script>`):t}var ko=/(<title\b[^>]*>)\s*(<\/title>)/i;function bi(t){if(!ko.test(t))return t;let e=/^en\b/i.test(/<html\b[^>]*\slang=["']?([^"'\s>]*)/i.exec(t)?.[1]??"");return t.replace(ko,(s,o,n)=>`${o}${e?"Untitled":"\u672A\u547D\u540D\u6587\u6863"}${n}`)}function Pt(t,{slug:e,mode:s="export",files:o=!0,reportsDirectory:n,kit:i}){let{html:r,removed:c}=ki(t,{reportsDirectory:n,kit:i,describe:s==="preview"}),l={slug:e,mode:s,...n?{reportsDirectory:n}:{}},a=te(pi(r,gi(e,n??mi)),l),d=o?de(oe(ne(ae(a,l),l),l),l):a;return{html:bi(bo(d,l)),removed:c}}function ki(t,{reportsDirectory:e,kit:s,page:o=!1,describe:n=!1}){let i=E(e),r=L(t,i),{html:c,removed:l,used:a}=ue(t,[...ui,...r]),d=xe(pe(c,{used:a,page:o,...s?{href:s}:{}}),r);return{html:n?wi(d,i,r):d,removed:l,packages:r}}import{exportsDirectory as Wt,generatedDirectory as Y,kitPublicDirectory as Ci,release as zi,reportsDirectory as I,vendorDirectory as Ii}from"../browser/shared/paths.mjs";import{referencedFile as ji}from"../browser/shared/media.mjs";import{decoded as Ri,fromFile as Fi,hashAddress as _i,hosted as Co,pageAddress as Di,workbenchHash as Mi}from"../browser/shared/page-address.mjs";import{pageLinks as Pi}from"../browser/shared/page-links.mjs";import{documentLinks as Ui,listReportSlugs as Wi}from"../browser/shared/reports.mjs";import{documentDirectory as B,documentFiles as Ht}from"../browser/shared/workspace.mjs";import{sha256 as pt}from"../browser/shared/files.mjs";import{EXPORT_CSP as Bi,GENERATOR as Hi,isolateUmd as Ki,packagesMeta as Gi,sourceMeta as Ji}from"../browser/shared/export-wrap.mjs";var vo=/__REPORT_[A-Z_]+__/,Oo=1e6,Eo=t=>t.length>1?`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`:`${t[0]}`;function Vi(t){return t.map(({id:e,lines:s,columns:o})=>{let n=new Set(s).size<s.length,i=s.map((r,c)=>n?`${r}:${o[c]}`:`${r}`);return`data-block-id repeats: "${e}" on lines ${Eo(i)}${n?" (line:column)":""}; each id names one block: remove it from the copy, which needs none (the later ${i.length>2?`ones, lines ${Eo(i.slice(1))}`:`one, line ${i[1]}`}, unless the copy went before its original)`})}var Zi=({slug:t,htmlPath:e,metadataPath:s})=>{let o=e?{html:e,json:s??e.replace(/\.html$/,".json")}:Ht(B(t,I));return{htmlName:N.basename(o.html),jsonName:N.basename(o.json)}};function Yi({slug:t,html:e,metadata:s,htmlPath:o,metadataPath:n,tree:i=w(e)}){let r=[],{htmlName:c,jsonName:l}=Zi({slug:t,htmlPath:o,metadataPath:n}),a=/<h1\b[^>]*\bclass="[^"]*\bdoc-title\b[^"]*"[^>]*>\s*<\/h1>/i.test(e),d=[[/<meta\s+name=["']viewport["']/i,"missing viewport metadata"],[a?/<title>\s*<\/title>|<title>[^<]+<\/title>/i:/<title>[^<]+<\/title>/i,"missing document title"],[/<main(?:\s|>)/i,"missing semantic main element"],[/aria-label|aria-labelledby|<title>/i,"missing accessible labels"]];for(let[p,g]of d)p.test(e)||r.push(g);let f=Buffer.byteLength(e);f>Oo&&r.push(`the document's editable source is ${f.toLocaleString("en-US")} bytes, over the ${Oo.toLocaleString("en-US")}-byte limit: aggregate or sample the embedded data, or split the document`),vo.test(e)&&r.push(`${c} still contains a starter placeholder such as __REPORT_TITLE__`);for(let[p,g]of Object.entries(s))typeof g=="string"&&vo.test(g)&&r.push(`${l} "${p}" is still a starter placeholder such as __REPORT_TITLE__`);/<[a-z][^>]*\sdata-doc-placeholder\b/i.test(e)&&r.push("starter placeholder content ([data-doc-placeholder]) is still present; replace it with the document's content");let u=new Map;M(i,p=>{let g=O(p,"data-block-id"),b=p.sourceCodeLocation?.attrs?.["data-block-id"]??p.sourceCodeLocation;g!==void 0&&u.set(g,[...u.get(g)??[],{line:b?.startLine,column:b?.startCol}])});let h=[...u].filter(([,p])=>p.length>1);r.push(...Vi(h.map(([p,g])=>({id:p,lines:g.map(({line:b})=>b),columns:g.map(({column:b})=>b)}))));let m=null;if(M(i,p=>{!m&&p.tagName==="main"&&(m=p)},{inTemplates:!1}),m){let p=O(m,"data-doc-id");p===void 0?r.push(`main.doc-page needs data-doc-id="${t}"`):p!==t&&r.push(`main[data-doc-id] is "${p}": it must be the document's slug "${t}"`)}return r}var zo=t=>So(So(t).find(e=>e.tagName==="html")??{}).find(e=>e.tagName==="head")?.sourceCodeLocation?.startTag?.endOffset,Bt=new Set(["localStorage","sessionStorage"]);function Io(t){let e=[],s=[];return M(t,o=>{o.tagName==="script"&&O(o,"src")!==void 0&&e.push(O(o,"src")),(o.tagName==="link"?(O(o,"rel")??"").toLowerCase().split(/\s+/):[]).includes("stylesheet")&&O(o,"href")!==void 0&&s.push(O(o,"href"))}),{scripts:e,styles:s}}function jo({slug:t,html:e,directory:s=B(t,I),tree:o=w(e),uses:n=Q(e,X,{tree:o}),catalog:i}){let r=[];zo(o)===void 0&&r.push("the page writes no <head> start tag, which an export puts its Content-Security-Policy right after: write <head> \u2026 </head> before <body>");let c=[];M(o,d=>{if(["script","link","img"].includes(d.tagName))for(let f of["src","href"]){let u=O(d,f)?.trim();u&&/^https?:\/\//i.test(u)&&c.push(u)}}),c.length>0&&r.push(`external resources are not portable: ${c.join(", ")}`);for(let{name:d,how:f,line:u,where:h}of n){if(!X.has(d))continue;let m={call:`calls ${d}(\u2026)`,new:`creates new ${d}(\u2026)`}[f]??`uses ${d}`;r.push(`line ${u}: ${h} ${m}: embed its data (inline JSON, DocState); the export blocks the network`)}let{scripts:l,styles:a}=Io(o);for(let d of l)we.has(d)||r.push(`unsupported script dependency ${d}`);for(let d of a)be.has(d)||r.push(`unsupported stylesheet dependency ${d}`);return r.push(...re({html:e,directory:s,tree:o}),...ie({html:e,directory:s,tree:o}),...se({html:e,directory:s,tree:o}),...ce({html:e,directory:s,tree:o})),r.push(...Se(L(e,i,o))),[...new Set(r)]}var qi=[[/\bDocSheets\.mount\s*\(/,"Sheet areas start on their own: remove DocSheets.mount (an area keeps its tab under its data-doc-sheets name)"],[/\bDocCode\.(?:View|DiffView|DiffStats|enhance)\b/,'code blocks are highlighted on their own, and a diff is declared as <div class="doc-diff"> holding { path, lines } as JSON (sdk/doc-code.d.ts)'],[/\bDocTables\.(?:enhance|enhanceAll|makeSortable)\b/,"tables start on their own: remove the call"],[/\bDocDialogs\.(?:enhance|enhanceAll)\b/,"detail cards start on their own: remove the call"]];function Xi({html:t,tree:e=w(t),uses:s=Q(t,Bt,{tree:e})}){let o=ke(t,e),n=[...me(t,e),...ge(t,e)];for(let[i,r]of qi)i.test(o)&&n.push(`${o.match(i)[0].replace(/\s*\($/,"")} is gone: ${r}`);for(let{name:i,line:r,where:c}of s)Bt.has(i)&&n.push(`line ${r}: ${c} uses ${i}: use DocState instead of direct browser storage`);return[...new Set(n)]}var Qi=(t,e)=>e.childNodes.find(s=>s.tagName||s.nodeName==="#text"&&s.value.trim())===t,ta=t=>xo(t,Ni("highlight").match)||t.tagName==="li"&&xo(t.parentNode,`ol.${vi}`),ea=`an icon is one of three kinds: an emoji, <div class="doc-icon">\u{1F3AF}</div>; an icon of Gallery's sets in one of ${No.length} colors, <div class="doc-icon" data-icon="/icons/airplane_blue.svg"></div> (MingCute's names; Tabler's as /icons/tabler/plane_blue.svg; the colors ${No.join(", ")}); or a picture of the document's folder, <div class="doc-icon"><img src="assets/logo.png" alt=""></div>`,Ro=t=>t.nodeName==="#text"?t.value:(t.childNodes??[]).map(Ro).join("");function To(t,e,s){let o=e.sourceCodeLocation?.attrs?.[s],n=o?t.slice(o.startOffset,o.endOffset):`${s}="${O(e,s)??""}"`;return n.length>72?`${n.slice(0,71)}\u2026`:n}function oa(t,e){let s=O(e,"data-icon");if(s!==void 0)return{held:To(t,e,"data-icon"),meant:Ut(s)==="glyph"?s:null};let o=null;if(M(e,i=>{o??=["img","svg"].includes(i.tagName)?i:null}),o?.tagName==="img"){let i=O(o,"src");return{held:`<img ${To(t,o,"src")}>`,meant:Ut(i)==="image"?i:null}}if(o)return{held:"an <svg>"};let n=Ro(e).replace(/\s+/g," ").trim();return{held:n?`"${n.slice(0,40)}"`:"nothing"}}function sa({set:t,name:e,color:s}){let o=Oi.find(r=>r!==t);if(gt(o).includes(e))return`; "${e}" is ${o==="tabler"?"Tabler":"MingCute"}'s: ${Ti(o,e,s)}`;let n=e.split("-").filter(r=>r.length>=3),i=gt(t).filter(r=>r.split("-").some(c=>n.includes(c))).slice(0,6);return i.length>0?`; names of its set near it: ${i.join(", ")}`:""}function na({html:t,tree:e=w(t)}){let{all:s,own:o}=ee(e),n=[],i=r=>r.sourceCodeLocation?.startLine;o.length>1&&n.push(`line ${i(o[1])}: ${o.length} page icons (.doc-icon) in the header (the first at line ${i(o[0])}): a document has one, right before its title`);for(let r of s){let c=i(r),l=r.parentNode;!o.includes(r)&&!(ta(l)&&Qi(r,l))&&n.push(`line ${c}: an icon (.doc-icon) stands only right before the document's title, first in a highlight block (.doc-panel, .doc-summary), or first in a flowchart's step (ol.doc-flow > li, in its number's place)`);let a=Ai(Yt(t,r)),{held:d,meant:f}=a?{}:oa(t,r);f?n.push(`line ${c}: an icon (.doc-icon) holds ${d}, an icon a page reads only in double quotes: write ${Li(f)}`):a?Ut(a)==="glyph"&&!Xt(a)&&n.push(`line ${c}: the icon ${a} is none of the icon sets' (MingCute: /icons/<name>_<color>.svg, Tabler: /icons/tabler/<name>_<color>.svg; src/shared/emoji/data/icons.json lists the names of each)${sa(Ei(a))}`):n.push(`line ${c}: an icon (.doc-icon) holds no icon (it holds ${d}): ${ea}`)}return[...new Set(n)]}function Fo(t){let e=w(t.html),s={...t,tree:e,uses:Q(t.html,new Set([...X,...Bt]),{tree:e})};return[...Yi(s),...At(t.html,e),...Xi(s),...na(s),...jo(s)]}function ia(t){let e=new Map(t.map(n=>[n.slug,[...Fo(n),...vt(n.html)]])),s=new Map(t.map(n=>[N.resolve(n.htmlPath),n.slug])),o=new Map(t.map(n=>[N.resolve(n.htmlPath),n]));for(let n of t)n.scriptNotes=[];if(t.length>0)for(let{htmlPath:n,text:i,typeOnly:r,note:c}of ye(t)){if(r){o.get(n)?.scriptNotes.push(c);continue}let l=n?[s.get(n)]:[...e.keys()];for(let a of l)e.get(a).push(n?i:`${i} (shared SDK declaration)`)}for(let[n,i]of e)i.length===0&&e.delete(n);return e}async function Ic(t=[],{prepare:e=null}={}){let{reports:s,failures:o}=await mt(t,{prepare:e});for(let n of s){let i=[...Fo(n),...vt(n.html)];i.length&&o.set(n.slug,i)}return o}async function aa(t=[],{prepare:e=null}={}){let{reports:s,failures:o}=await mt(t,{prepare:e});for(let[n,i]of ia(s))o.set(n,i);return{reports:s,failures:o}}async function ra({fresh:t=!1,kit:e=Ci,vendor:s=Ii}={}){if(zi)return;let o=K.map(r=>[r,r.file?jt(r.file,{fresh:t}):bt(r)]);await S.mkdir(e,{recursive:!0});let n=N.join(s,"katex","fonts");await S.mkdir(n,{recursive:!0});let i=(await S.readdir(wt)).filter(r=>r.endsWith(".woff2"));await Promise.all(i.map(r=>S.copyFile(N.join(wt,r),N.join(n,r)))),await Promise.all(o.map(async([r,c])=>S.writeFile(r.file?N.join(e,r.file):N.join(s,...r.vendor.path.split("/").slice(2)),await c)))}async function ca(t,e){let s=await S.readdir(t).catch(()=>[]);await Promise.all(s.filter(o=>o.endsWith(".html")&&!e.has(o.slice(0,-5))).map(o=>S.rm(N.join(t,o),{force:!0})))}async function la(t){let e=N.join(Y,"reports.json"),s=await S.readFile(e,"utf8").then(JSON.parse,()=>[]),o=new Map(Array.isArray(s)?s.map(i=>[i.slug,i]):[]);for(let{entry:i}of t)o.set(i.slug,i);let n=[];for(let[i,r]of[...o].sort(([c],[l])=>c.localeCompare(l))){let c=N.join(Y,`${i}.html`);await S.stat(c).then(()=>!0,()=>!1)&&n.push(r)}await S.writeFile(e,`${JSON.stringify(n,null,2)}
9
- `)}async function da(t=[],{prepare:e=null}={}){let{reports:s,failures:o}=await aa(t,{prepare:e});await ra(),await S.mkdir(Y,{recursive:!0}),await ca(Y,new Set(await Wi()));let n=[];for(let i of s){let r=`${i.slug}.html`,c=N.join(Y,r);if(o.has(i.slug)){await S.rm(c,{force:!0});continue}let{html:l,removed:a}=Pt(i.html,{slug:i.slug});await S.writeFile(c,l),n.push({report:i,html:l,removed:a,entry:{slug:i.slug,...i.metadata,preview:`/generated/${r}`,sourceSha256:pt(i.html),outputSha256:pt(l)}})}return await la(n),{built:n,failures:o}}var fa=t=>t.replace(/<\/script/gi,"<\\/script");async function _o(){return new Map(await Promise.all(K.map(async t=>{let e=await(t.file?jt(t.file):bt(t,{inline:!0}));return he(t).endsWith(".css")||(e=fa(e)),[t.id,t.umd?Ki(e):e]})))}function ha(t,e,s=null,o=[]){let n=zo(w(e));if(n===void 0)throw new Error(`${t}: the page writes no <head> start tag, which the export's Content-Security-Policy goes right after`);let i=s?`
10
- ${Ji(s)}${o.length>0?`
11
- ${Gi(o)}`:""}`:"";return`${e.slice(0,n)}
12
- <meta name="generator" content="${Hi}">
13
- <meta http-equiv="Content-Security-Policy" content="${Bi}">${i}${e.slice(n)}`}function Do(t,e,s,o=null,n=E(),i=I,r=null){let c=L(e,n);e=co(ha(t,e,o,c),{slug:t,packages:c,root:i,workspace:r}),e=$e(Ne(e,n),({id:d,element:f,attribute:u})=>{let h=s.get(d);if(typeof h!="string")throw new Error(`${t}: no inline source for the asset "${d}" (loadInlineSources in src/render/pipeline.mjs)`);return`<${f} ${u}="${d}-inline">${h}</${f}>`});let{scripts:l,styles:a}=Io(w(e));if(l.length+a.length>0)throw new Error(`${t}: export still contains a linked script or stylesheet`);return e}async function Lo(t,e=I,{components:s=!0}={}){let o=B(t,e),n=await S.readFile(Ht(o).html),i=n.toString("utf8"),r=w(i),c=s?E(e):{packages:new Map},l=[...s?At(i,r,c):[],...jo({slug:t,html:i,directory:o,tree:r,catalog:c})];if(l.length>0){let a=L(i,c,r).find(({id:d})=>l[0].startsWith(`${d}:`)||l[0].startsWith(`${d} (`))?.id;throw Object.assign(new Error(`${t}: ${l[0]}`),{reason:"check",slug:t,failures:l,...a?{component:a}:{}})}return{html:i,sha256:pt(n)}}async function jc({directory:t=I,workspace:e=null}={}){let s=await _o(),o=async(n,{files:i=!0}={})=>{let r=await Lo(n,t),c=Pt(r.html,{slug:n,files:i,reportsDirectory:t}).html,l=E(t);return Do(n,c,s,r.sha256,l,t,await Mo(e,n,c,l))};return o.check=async n=>{await Lo(n,t,{components:!1})},o}async function Mo(t,e,s,o){return typeof t!="function"||!Ft(L(s,o))?null:await t(e).catch(()=>null)??null}async function Rc(t=[],{prepare:e=null,workspace:s=null}={}){let{built:o,failures:n}=await da(t,{prepare:e}),i=await _o();await S.mkdir(Wt,{recursive:!0});let r=new Set(o.map(({report:a})=>a.slug)),{links:c}=await Ui(),l=[];for(let{report:a,html:d}of o)try{let f=ho(d,a.slug,h=>r.has(h)?`${h}.html`:null,{links:c}),u=Do(a.slug,f,i,a.fileSha256,E(),I,await Mo(s,a.slug,f,E()));await S.writeFile(N.join(Wt,`${a.slug}.html`),u),l.push({slug:a.slug,bytes:Buffer.byteLength(u),sha256:pt(u)})}catch(f){n.set(a.slug,[f.message])}return{built:o,exported:l,failures:n}}function Ao(t){let e=new Set;return M(t,s=>{for(let o of["id","data-block-id"])O(s,o)!==void 0&&e.add(O(s,o))}),e}function ua(t,e,s){if(Co(t)||/^(?:[a-z][a-z0-9+.-]*:|\/)/i.test(t)||ji(t))return!1;let{pathname:o}=new URL(e);return!o.startsWith(`/${s}/`)||o.endsWith(".html")}function pa({slug:t,tree:e,directory:s}){let o=[],n=Ao(e),i=s===B(N.basename(s),I)?I:N.dirname(s),r=new Map([[t,n]]),c=d=>{if(!r.has(d)){let f=Ht(B(d,i));r.set(d,yo(f.html)?Ao(w(yi(f.html,"utf8"))):null)}return r.get(d)},l=null,a=(d,f)=>f===null?Di(d):_i(f,l??=Pi((yo(i)?xi(i):[]).map(u=>({slug:u}))));return M(e,d=>{let f=d.tagName==="a"?O(d,"href"):void 0;if(!f||f==="#"||f==="#top")return;let u=d.sourceCodeLocation?.startLine;if(f.startsWith("#")){n.has(Ri(f.slice(1)))||o.push(`the link to ${f} (line ${u}) names no block or element of this document`);return}let h=Fi(f,t),m=Mi(h),p=a(h,m);(p?!c(p.slug):m!==null)?Co(f)||o.push(`the link to ${f} (line ${u}) names a document that is not there: gallery list has the slugs`):p?.block&&!c(p.slug).has(p.block)?o.push(`the link to ${f} (line ${u}) names a block document ${p.slug} does not hold`):h&&!p&&ua(f,h,t)&&o.push(`the link to ${f} (line ${u}) leads to no document: a link to one is ../<slug>/doc.html, gallery list has the slugs`)},Si),o}function Po({slug:t,html:e,directory:s=B(t,I),written:o=e,scriptNotes:n=[]}){let i=w(e),r=ze(e);return{fix:[...ao(e,i),...mo({html:e,directory:s,tree:i})],notes:[...to(e,{written:o}),...Be(i),...pa({slug:t,tree:i,directory:s}),...r.notes,...n],readings:r.readings}}function Fc(t){let{fix:e,notes:s}=Po(t);return[...e,...s]}function _c(t){let e=t.map(s=>[s.slug,Po(s)]);for(let[s,{fix:o}]of e)for(let n of o)console.log(`fix ${s}: ${n}`);for(let[s,{notes:o}]of e)for(let n of o)console.log(`note ${s}: ${n}`);for(let[s,{readings:o}]of e)for(let n of o)console.log(`chart ${s}: ${n}`)}async function ma(t,{exportNote:e=!1}={}){for(let[s,o]of t){console.error(`
14
- FAIL ${s}: ${o.length} problem${o.length===1?"":"s"}`);for(let i of o)console.error(` - ${i}`);let n=N.join(Wt,`${s}.html`);e&&await S.stat(n).then(()=>!0,()=>!1)&&console.error(` ${n} was not updated; it still holds an earlier export.`)}}function ga(t,{above:e=!1,allow:s=process.argv.includes("--allow-failures")}={}){t.size!==0&&(console.error(`
15
- ${t.size} document${t.size===1?"":"s"} failed: ${[...t.keys()].join(", ")}${e?" (the failures are listed first, above)":""}`),s||(process.exitCode=1))}async function Dc(t,{exportNote:e=!1,allow:s}={}){await ma(t,{exportNote:e}),ga(t,{allow:s})}export{Ts as a,Mn as b,ho as c,bo as d,Pt as e,ki as f,Vi as g,jo as h,Fo as i,ia as j,Ic as k,aa as l,ra as m,da as n,ha as o,jc as p,Rc as q,Po as r,Fc as s,_c as t,ma as u,ga as v,Dc as w};
@@ -1,2 +0,0 @@
1
- import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{b as g,i as S}from"./chunk-4OZWXZE5.mjs";import _ from"node:fs/promises";import{listExtensions as I}from"../browser/shared/extensions.mjs";import{ancestorsIn as C,moveDocument as M,outlineAndFile as P}from"../browser/shared/outline.mjs";import{DOCS as k,groupOfTop as A,isForeign as b,isTop as J,topIn as U,topOf as z}from"../browser/shared/outline-shape.mjs";import{draftFacts as B,draftOf as G,registeredIds as K,workspaceNames as R}from"../browser/shared/drafts.mjs";import{reportsDirectory as f}from"../browser/shared/paths.mjs";import{findPreviewServer as W}from"../browser/shared/preview-server.mjs";import{roleOf as X}from"../browser/shared/reports.mjs";import{nameStops as q,workspaceName as H}from"../browser/shared/workspace-name.mjs";import{workspaceKey as w}from"../browser/shared/workspace-registry.mjs";import{defaultWorkspace as Q,documentDirectory as y,documentFiles as V,pageSlug as Y,readLink as Z}from"../browser/shared/workspace.mjs";async function we(e=f,{others:t=w(e)===w(f)}={}){let{outline:{children:n,groups:o,links:s,shown:i},others:c}=await P(e,{others:t}),u=ee(e,o,i),a=new Set(i.map(({id:r})=>r)),p=o.map(r=>({...r,name:u.get(r.id)??null,...t&&r.workspace&&!a.has(r.workspace)?{away:!0}:{}})),$=p.filter(r=>!r.extension),F=await I(e),x=Object.values(n).flat(),O=r=>typeof r=="string"?r.replace(/\s+/g," ").trim():"",j=x.some(b)?K():null,E=new Map(await Promise.all(x.map(async r=>{if(b(r)){let d=G(r),N=c.find(({id:L})=>L===d?.ws)?.facts.get(d.slug),m=N?{...N,missing:null}:await B(r,j);return[r,{slug:r,title:m.title,description:m.description,icon:m.icon,draft:{path:m.path,missing:m.missing,ws:d?.ws??null}}]}if(s.includes(r)){let d=await Z(y(r,e));return[r,{slug:r,title:d?.title??r,description:"",icon:d?.icon??null,url:d?.url??""}]}let h=await _.readFile(V(y(r,e)).json,"utf8").then(JSON.parse).catch(()=>({}));return[r,{slug:r,title:O(h?.title)||r,description:O(h?.description),icon:typeof h?.icon=="string"?h.icon:null}]})));return{children:n,groups:$,columns:p,extensions:F,documents:E}}function ee(e,t,n=[]){let o=w(Q()),s=new Set(t.map(({workspace:a})=>a).filter(Boolean)),i=q(),c=s.size?R(s,{stops:i}):new Map,u=new Map;for(let a of t)if(a.id===k)u.set(a.id,w(e)===o?"\u9ED8\u8BA4\u6587\u6863":H(e,{stops:i}).name);else if(a.workspace){let p=n.find(({id:$})=>$===a.workspace);u.set(a.id,p?.isDefault?"\u9ED8\u8BA4\u6587\u6863":c.get(a.workspace)?.name??a.workspace)}else a.role==="links"&&u.set(a.id,"\u94FE\u63A5");return u}var v=e=>e?.title??e?.name??(e?.id===k?"\u6587\u6863":e?.role==="links"?"\u94FE\u63A5":e?"\u672A\u547D\u540D\u680F":"\u6587\u6863"),T=(e,t)=>e.groups?.find(({id:n})=>n===A(t));function $e(e,t){let n=e.documents.get(t);if(!n||n.url!==void 0)return null;let o=D(e,t),s=n.draft?.ws??null,i=s?e.groups.find(c=>c.workspace===s):e.groups.find(c=>c.id===k);return i&&z(i.id)===o?null:i?i.hidden?i.name??s:v(i):s}var l=({documents:e},t)=>`${t} (${e.get(t)?.title??t})`,D=(e,t)=>U(e.children,t)??"";function ge(e,t){let n=C(e.children,t).map(i=>l(e,i)),o=D(e,t),s=[...o===""?[]:[`${v(T(e,o))}\u680F`],...n];return`\u4F4D\u7F6E\uFF1A${s.length?s.join(" \u203A "):"\u9876\u5C42"}`}async function ye(e,t,n){let{slug:o}=await S(e);if(o===await Y(f))return{refused:`${e} is the \u5199\u4F5C\u504F\u597D page, which the sidebar lists apart: it moves nowhere and holds no documents (${t}).`};if(!n.documents.has(o)){let s=y(o,f);return{refused:await X(s)==="instructions"?`${e} is the \u5199\u4F5C\u504F\u597D page, which the sidebar lists apart: it moves nowhere and holds no documents (${t}).`:`No document "${e}" (${t}): gallery list --tree shows the documents and where they are.`}}return{slug:o}}var te={missing:(e,t)=>`No document "${t}" in the sidebar's tree: gallery list --tree shows them.`,parent:(e,t,{parent:n})=>`No document "${n}" to put ${l(e,t)} under: gallery list --tree shows them.`,after:(e,t,{after:n})=>`No document "${n}" to put ${l(e,t)} after: gallery list --tree shows them.`,level:(e,t,{parent:n,after:o})=>`${l(e,o)} is not under ${n?l(e,n):"the top level"}: --after names a document at the level it goes to.`,itself:(e,t)=>`${l(e,t)} cannot go after itself.`,inside:(e,t,{parent:n,after:o})=>n===void 0&&o?`${l(e,t)} cannot go after ${l(e,o)}, which is under it.`:`${l(e,t)} cannot go under ${n===t?"itself":`${l(e,n)}, which is under it`}.`,instructions:(e,t)=>"The \u5199\u4F5C\u504F\u597D page is listed apart: it moves nowhere and holds no documents."},ke=(e,t,n,o={})=>(te[n]??((s,i,{message:c})=>`Not moved: ${c??n}.`))(e,t,o);async function ne(e,t,n="move"){let o=`127.0.0.1:${e.port}`;try{let i=await(await fetch(`http://${o}/__gallery/workspace/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Origin:`http://${o}`,"X-Gallery-Token":e.token},body:JSON.stringify({...t,workspace:f}),signal:AbortSignal.timeout(3e4)})).json().catch(()=>null);return typeof i?.ok!="boolean"||["elsewhere","token","host","origin","unknown"].includes(i.reason)?null:i}catch{return null}}async function ve(e,{parent:t=void 0,after:n=null,first:o=!1}={}){let s=await W({reportsDirectory:f}),i={slug:e,...t!==void 0?{parent:t}:{},after:n,first:o},c=s?await ne(s,i):null;return c||M(f,e,{parent:t,after:n,first:o})}function xe(e,{parent:t,index:n}){let o=e.children[t]??[],s=t===""?"at the top level":J(t)?`at the top of the ${v(T(e,t))} column`:`under ${l(e,t)}`;return o.length===1?`${s}, the only ${o.some(i=>e.documents.get(i)?.url!==void 0)?"entry":"document"} there`:n===0?`${s}, first`:`${s}, right after ${l(e,o[n-1])}${n===o.length-1?", last":""}`}function Oe(e,t,{top:n=!0}={}){let o=e.get("--under"),s=e.get("--after");if(o!==void 0&&t.has("--top"))throw new g("--under and --top are two places: give one.");if(s!==void 0&&t.has("--first"))throw new g("--after and --first are two places: give one.");return{under:o,top:n&&t.has("--top"),after:s,first:t.has("--first")}}export{we as a,v as b,$e as c,l as d,ge as e,ye as f,ke as g,ne as h,ve as i,xe as j,Oe as k};