@heycys/gallery 0.2.2 → 0.2.3

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 (52) hide show
  1. package/THIRD-PARTY-NOTICES.md +1 -1
  2. package/browser/editor/page/editor.mjs +4 -2
  3. package/browser/shared/workspace-address.mjs +3 -0
  4. package/dist/{chunk-K3JKPFL5.mjs → chunk-225ALKYI.mjs} +1 -1
  5. package/dist/{chunk-PDZR3L3C.mjs → chunk-2HS7ZBPU.mjs} +1 -1
  6. package/dist/{chunk-ZFGMJVJC.mjs → chunk-3F57LEN5.mjs} +1 -1
  7. package/dist/{chunk-XZCFPKGO.mjs → chunk-5GK7HS62.mjs} +1 -1
  8. package/dist/{chunk-IA2SIEJQ.mjs → chunk-6Y3HYOBM.mjs} +1 -1
  9. package/dist/{chunk-USIHBCSW.mjs → chunk-BX5AKINW.mjs} +1 -1
  10. package/dist/{chunk-ERE2BXYV.mjs → chunk-BYNPEUDS.mjs} +1 -1
  11. package/dist/{chunk-6L6V7YR2.mjs → chunk-CRDG6EF2.mjs} +1 -1
  12. package/dist/{chunk-PLB7L22J.mjs → chunk-FJLM7YE7.mjs} +1 -1
  13. package/dist/{chunk-VPMRP2TL.mjs → chunk-FNCCVGKX.mjs} +1 -1
  14. package/dist/{chunk-65NTKF4N.mjs → chunk-FOJ3K5Z3.mjs} +1 -1
  15. package/dist/{chunk-E4IHAIJ7.mjs → chunk-FQ72LZHB.mjs} +1 -1
  16. package/dist/{chunk-BMX3VUHY.mjs → chunk-G7N7YFVD.mjs} +1 -1
  17. package/dist/{chunk-CHQU37CA.mjs → chunk-GIRXJBGC.mjs} +1 -1
  18. package/dist/{chunk-Q4MS6OFC.mjs → chunk-GQJMVSSN.mjs} +1 -1
  19. package/dist/{chunk-3SKOU6OZ.mjs → chunk-HX4DLE3J.mjs} +1 -1
  20. package/dist/chunk-IS7N3N6Q.mjs +168 -0
  21. package/dist/{chunk-GJJRBGMY.mjs → chunk-JJNHKGTD.mjs} +1 -1
  22. package/dist/{chunk-4SNV4HA5.mjs → chunk-JYK5WJPM.mjs} +1 -1
  23. package/dist/{chunk-WFGPMCTZ.mjs → chunk-L55NOXBE.mjs} +1 -1
  24. package/dist/{chunk-NHP66IWR.mjs → chunk-LCB6MARS.mjs} +1 -1
  25. package/dist/{chunk-4KUO7R2M.mjs → chunk-LJLVCU6W.mjs} +1 -1
  26. package/dist/{chunk-FFV733MA.mjs → chunk-NLDF35P5.mjs} +1 -1
  27. package/dist/{chunk-Q7P3Q5YX.mjs → chunk-NMF3IPYA.mjs} +1 -1
  28. package/dist/{chunk-2T4PZQEP.mjs → chunk-ONKC4BCC.mjs} +1 -1
  29. package/dist/{chunk-ULXSPX5H.mjs → chunk-OU6ZZVBX.mjs} +2 -2
  30. package/dist/{chunk-236JJXWY.mjs → chunk-PKVK6WFC.mjs} +2 -2
  31. package/dist/{chunk-MNWJ4EZY.mjs → chunk-QJAVCTY7.mjs} +1 -1
  32. package/dist/{chunk-BN7M3IN7.mjs → chunk-SQ3FQCCN.mjs} +2 -2
  33. package/dist/{chunk-2KAVXMKG.mjs → chunk-T4Y2ZSVX.mjs} +1 -1
  34. package/dist/{chunk-53XDTHTG.mjs → chunk-UTF7GBQU.mjs} +2 -2
  35. package/dist/{chunk-VZ2RQ3AM.mjs → chunk-UTMAY3WK.mjs} +1 -1
  36. package/dist/{chunk-3XZOA7AH.mjs → chunk-V4ZHRALW.mjs} +2 -2
  37. package/dist/{chunk-JXXHAXYH.mjs → chunk-WD4U6XXT.mjs} +1 -1
  38. package/dist/{chunk-MKIBJTJZ.mjs → chunk-XBNFXWAW.mjs} +1 -1
  39. package/dist/{chunk-C257H6IA.mjs → chunk-XZV72SQ4.mjs} +1 -1
  40. package/dist/{chunk-OEIJLMPI.mjs → chunk-YFJB534W.mjs} +1 -1
  41. package/dist/{chunk-5XV3YYLG.mjs → chunk-Z6OKLRHC.mjs} +1 -1
  42. package/dist/{chunk-6Q7ASAXJ.mjs → chunk-ZLS2FRS6.mjs} +1 -1
  43. package/dist/{chunk-7ISBBDJR.mjs → chunk-ZMHUDYLV.mjs} +1 -1
  44. package/dist/cli.mjs +1 -1
  45. package/dist/server.mjs +1 -1
  46. package/kit/runtime.js +1 -0
  47. package/package.json +1 -1
  48. package/release.json +4 -4
  49. package/skill/SKILL.md +5 -5
  50. package/web/assets/{index-czjrXVjf.js → index-D8P8uhDW.js} +1 -1
  51. package/web/index.html +1 -1
  52. package/dist/chunk-BLNQUR5R.mjs +0 -168
@@ -0,0 +1,168 @@
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 Gn,b as Kn}from"./chunk-6GV3CBB2.mjs";import{a as Jn}from"./chunk-DR73Y2UJ.mjs";import{b as zn}from"./chunk-M4NRDYI5.mjs";import{a as Un,i as Hn,j as Bn}from"./chunk-PUOQ65NC.mjs";import{a as Wn,b as Mn}from"./chunk-6QWQXHAV.mjs";import{k as Qe}from"./chunk-ZLS2FRS6.mjs";import{h as Rn,i as Fn}from"./chunk-S3SX3COT.mjs";import{a as An}from"./chunk-JJNHKGTD.mjs";import{a as Dn}from"./chunk-JPG2LBQM.mjs";import{a as In,b as Nn}from"./chunk-ALZ6ZENZ.mjs";import{a as Ln}from"./chunk-2OHANJ6Q.mjs";import{a as Cn,b as qe,d as _n,e as Pn,f as jn,g as Tn}from"./chunk-7M2BQQGZ.mjs";import{b as Et,e as ln,g as Ot,h as dn,j as fn,k as mn}from"./chunk-4B2TB5K2.mjs";import{a as qt,d as en,e as tn,f as nn,k as on,l as an,m as rn,r as sn,t as bt,u as cn}from"./chunk-KLQP46Y3.mjs";import{b as kn,c as vn,d as Pe,e as xn,f as $n,g as Ze,i as Sn,m as bn,p as En,q as On}from"./chunk-BX5AKINW.mjs";import{d as wn,e as Fe,f as Xe,g as Ct,h as yn,k as Ve}from"./chunk-FJLM7YE7.mjs";import{b as un,c as pn}from"./chunk-PAREWQGB.mjs";import{i as Ke,j as Je,k as Ye}from"./chunk-BFJGHSQN.mjs";import{d as gn}from"./chunk-U5XL7D6A.mjs";import{a as hn}from"./chunk-HYMEEXKN.mjs";import{a as We}from"./chunk-E7656LR7.mjs";import{c as $t,g as se,j as Yt,k as Xt,p as Vt,q as Zt,v as Qt,w as St}from"./chunk-TKWEX4FD.mjs";import wt from"node:fs";import oi from"node:fs/promises";import ai from"node:http";import{kitPublicDirectory as ri,release as si,releaseFile as yt,vendorDirectory as ii,workbenchDirectory as ci}from"../browser/shared/paths.mjs";import{serviceLocation as li}from"../browser/shared/service-location.mjs";import{serve as ga}from"../browser/shared/http.mjs";import{defaultWorkspace as di,ensureWorkspace as fi,layoutOf as mi}from"../browser/shared/workspace.mjs";import Yn from"node:fs";import Sa from"node:fs/promises";import _t from"node:path";import ba from"node:http";import Zn from"node:net";import{spawn as Xn}from"node:child_process";import{extensionDirectory as Ea,extensionFile as Oa,listCapabilities as et,setExtensionEnabled as Ca}from"../browser/shared/extension-manifest.mjs";import{serviceLocation as _a}from"../browser/shared/service-location.mjs";import{sendJson as ie,serve as Pa}from"../browser/shared/http.mjs";var Vn=e=>new Promise(a=>setTimeout(a,e)),ja=()=>new Promise((e,a)=>{let t=Zn.createServer();t.once("error",a),t.listen(0,"127.0.0.1",()=>{let{port:o}=t.address();t.close(()=>e(o))})}),Ta=e=>new Promise(a=>{let t=Zn.connect(e,"127.0.0.1");t.setTimeout(250),t.once("connect",()=>{t.destroy(),a(!0)}),t.once("error",()=>a(!1)),t.once("timeout",()=>{t.destroy(),a(!1)})}),Ra={".js":"text/javascript",".mjs":"text/javascript",".css":"text/css",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".woff2":"font/woff2"};function Qn({edits:e}){let a=new Map,t=Promise.resolve(),o=0,i=n=>{o++;let c=t.then(n);return t=c.catch(()=>{}),c.finally(()=>{o--})},f=!1,s=async n=>{let c=a.get(n);c&&(await l(c),a.delete(n))},m=setInterval(()=>{et().then(async n=>{for(let c of a.values()){let v=n.find(P=>P.id===c.id);(!v?.enabled||v.manifest.revision!==c.revision)&&await s(c.id)}}).catch(()=>{})},1e3);m.unref();function l(n){return n.stopping??=p(n)}async function p(n){n.stopped=!0,clearTimeout(n.timer),await n.starting?.catch(()=>{});let c=n.child;c&&c.exitCode===null&&c.signalCode===null&&(process.platform==="win32"?await new Promise(v=>{let P=Xn("taskkill",["/pid",String(c.pid),"/t","/f"],{windowsHide:!0,stdio:"ignore"});P.once("error",v),P.once("exit",v)}):(c.kill("SIGTERM"),await Promise.race([new Promise(v=>c.once("exit",v)),Vn(1500)]),c.exitCode===null&&c.kill("SIGKILL"))),n.log?.end()}async function k(n){if(f||n.stopped)return;let c=(await et()).find(C=>C.id===n.id);if(!c?.enabled||c.manifest.revision!==n.revision){n.stopped=!0,n.log.end(),a.delete(n.id);return}if(n.port=await ja(),f||n.stopped)return;let[v,...P]=c.manifest.server.command,h=Xn(v==="node"?process.execPath:v,P,{cwd:c.folder,windowsHide:!0,shell:!1,env:{...process.env,PORT:String(n.port),GALLERY_EXTENSION_PORT:String(n.port),GALLERY_EXTENSION_HOST:"127.0.0.1",GALLERY_EXTENSION_ID:n.id},stdio:["ignore","pipe","pipe"]});n.child=h;let M=Date.now();h.stdout?.pipe(n.log,{end:!1}),h.stderr?.pipe(n.log,{end:!1});let x=!1,$=C=>{x||(x=!0,n.log.write(`[${new Date().toISOString()}] ${C?.message??"Backend exited"}
3
+ `),!(f||n.stopped)&&(n.failures=Date.now()-M>3e4?0:n.failures+1,n.timer=setTimeout(()=>{n.starting=k(n).finally(()=>{n.starting=null}),n.starting.catch(w=>n.log.write(w.message+`
4
+ `))},Math.min(3e4,500*2**Math.min(n.failures,6))),n.timer.unref()))};h.once("error",$),h.once("exit",()=>$())}async function S(n){if(o||f)throw new Error("\u6269\u5C55\u6B63\u5728\u66F4\u65B0\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");let c=a.get(n.id);if(c&&c.revision!==n.manifest.revision&&(await l(c),a.delete(n.id),c=null),!c){let P=_t.join(_a().data,"logs","extensions",`${n.id}.log`);Yn.mkdirSync(_t.dirname(P),{recursive:!0}),c={id:n.id,revision:n.manifest.revision,failures:0,stopped:!1,log:Yn.createWriteStream(P,{flags:"a"})},c.log.on("error",()=>{}),a.set(n.id,c),c.starting=k(c).finally(()=>{c.starting=null})}await c.starting;let v=Date.now()+1e4;for(;!f&&!c.stopped&&Date.now()<v;){if(c.child?.exitCode===null&&!c.child.signalCode&&await Ta(c.port))return c.port;await Vn(100)}throw new Error("\u6269\u5C55\u540E\u53F0\u6682\u672A\u5C31\u7EEA\uFF0C\u8BF7\u67E5\u770B\u6269\u5C55\u65E5\u5FD7")}async function b(n,c){let v=new URL(n.url,"http://localhost");if(!v.pathname.startsWith("/__gallery/extensions"))return!1;let P=`127.0.0.1:${n.socket.localPort}`;if(n.headers.host!==P)return ie(c,403,{ok:!1,reason:"host"}),!0;try{if(v.pathname==="/__gallery/extensions"&&n.method==="GET")return ie(c,200,{ok:!0,extensions:await et()}),!0;let h=/^\/__gallery\/extensions\/(install|remove)$/.exec(v.pathname)?.[1];if(h){let T=await e.check(n,65536);if(T.error)ie(c,...T.error);else if(h==="install"){let G=await i(()=>Gn(T.body.path,{inService:!0,beforeReplace:s}));ie(c,200,{ok:!0,installed:G})}else await i(()=>Kn(T.body.id,{inService:!0,beforeReplace:s})),ie(c,200,{ok:!0});return!0}if(v.pathname==="/__gallery/extensions"&&n.method==="POST"){let T=await e.check(n,65536);return T.error?ie(c,...T.error):(await i(async()=>{await Ca(T.body),T.body.enabled||await s(T.body.id)}),ie(c,200,{ok:!0})),!0}let M=/^\/__gallery\/extensions\/([^/]+)\/(files|api)\/(.*)$/.exec(v.pathname);if(!M)return ie(c,404,{ok:!1}),!0;if(o||f)return ie(c,503,{ok:!1,message:"\u6269\u5C55\u6B63\u5728\u66F4\u65B0\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5"}),!0;let[,x,$,C]=M,w=(await et()).find(T=>T.id===x);if(!w?.enabled)return ie(c,403,{ok:!1,reason:"disabled"}),!0;if($==="files"){if(n.method!=="GET"&&n.method!=="HEAD")return ie(c,405,{ok:!1}),!0;let T=await Oa(Ea(x),decodeURIComponent(C));return Pa(c,{type:Ra[_t.extname(T)]??"application/octet-stream",headers:{"X-Content-Type-Options":"nosniff","Cache-Control":"no-cache"},body:n.method==="HEAD"?void 0:await Sa.readFile(T)}),!0}let j={...n.headers};if(!j.origin&&["GET","HEAD"].includes(n.method))try{j.origin=new URL(j.referer).origin}catch{}let L=e.checkHeaders({method:"POST",headers:j,socket:n.socket});if(L)return ie(c,...L),!0;if(!w.manifest.server)return ie(c,404,{ok:!1,reason:"backend"}),!0;let E=await S(w),U={...n.headers,host:`127.0.0.1:${E}`};delete U["x-gallery-token"],delete U.cookie;let J=ba.request({host:"127.0.0.1",port:E,method:n.method,path:"/"+C+v.search,headers:U},T=>{let G={...T.headers};delete G["access-control-allow-origin"],delete G["set-cookie"],c.writeHead(T.statusCode,G),T.pipe(c)});return J.setTimeout(3e4,()=>J.destroy(new Error("\u6269\u5C55\u540E\u53F0\u8BF7\u6C42\u8D85\u65F6"))),J.once("error",T=>{c.headersSent?c.destroy():ie(c,502,{ok:!1,message:T.message})}),c.once("close",()=>J.destroy()),n.pipe(J),!0}catch(h){return ie(c,400,{ok:!1,message:h.message}),!0}}return{handle:b,async close(){f=!0,clearInterval(m),await t,await Promise.all([...a.values()].map(l)),a.clear()}}}import ca from"node:fs";import{serviceLocation as Gs}from"../browser/shared/service-location.mjs";import we from"node:fs/promises";import X from"node:path";import{assetFile as Fa,referencedFile as qn}from"../browser/shared/media.mjs";import{pageAssetAddress as La}from"../browser/shared/pages.mjs";function Pt(e,a){if(!/assets\//i.test(e))return e;let t=Je(e,o=>qn(o)!==null);return Ke(e,Ye(t,o=>{let i=qn(o.value);return Fa(i)?`${La(a,i)}${/[?#].*$/.exec(o.value.trim())?.[0]??""}`:null}))}function eo(e,{reportsDirectory:a,kit:t,slug:o=null}={}){let{html:i,packages:f}=$n(o?Pt(e,o):e,{reportsDirectory:a,kit:t,page:!0});return{html:i,packages:f}}import{Z as Aa}from"../browser/shared/layers.mjs";import{escapeMarkup as jt}from"../browser/shared/escape.mjs";import{layoutNotesScript as Ia}from"../browser/shared/qa-levels.mjs";var tt=30,Na=`
5
+ [data-doc-dev].doc-checks { position: fixed; z-index: ${Aa.checks}; left: 12px; bottom: 12px; max-width: min(520px, calc(100vw - 24px));
6
+ font: 13px/1.5 system-ui, sans-serif; color: light-dark(#37352f, #e3e2e0); }
7
+ [data-doc-dev].doc-checks[hidden] { display: none; }
8
+ [data-doc-dev].doc-checks > summary { display: inline-flex; gap: 6px; align-items: center; padding: 4px 10px; border-radius: 999px; cursor: pointer;
9
+ list-style: none; color: light-dark(#a1352b, #f19c92); background: light-dark(#fce9e7, #3b2321);
10
+ box-shadow: 0 0 0 1px light-dark(rgb(161 53 43 / 18%), rgb(241 156 146 / 22%)); user-select: none; }
11
+ [data-doc-dev].doc-checks > summary::-webkit-details-marker { display: none; }
12
+ [data-doc-dev].doc-checks > div { margin-top: 6px; padding: 8px 12px; max-height: 50vh; overflow: auto; border-radius: 10px;
13
+ background: light-dark(#ffffff, #252525); box-shadow: 0 0 0 1px light-dark(rgb(42 28 0 / 7%), #383836), 0 20px 24px light-dark(rgb(25 25 25 / 5%), rgb(0 0 0 / 20%)); }
14
+ [data-doc-dev].doc-checks ul { margin: 0; padding-left: 18px; }
15
+ [data-doc-dev].doc-checks li { margin: 2px 0; overflow-wrap: anywhere; }
16
+ [data-doc-dev].doc-checks p { margin: 6px 0 0; color: light-dark(#787774, #9b9a97); }
17
+ [data-doc-dev].doc-checks .doc-checks-live:not(:first-child) { margin-top: 8px; }
18
+ @media print { [data-doc-dev].doc-checks { display: none; } }`,Da=`(() => {
19
+ document.currentScript.remove();
20
+ ${Ia()}
21
+ const panel = document.querySelector("details.doc-checks[data-doc-dev]");
22
+ if (!panel) return;
23
+ const failures = Number(panel.dataset.failures) || 0;
24
+ const live = panel.querySelector(".doc-checks-live ul");
25
+ // The note's words in the UI's language (the root's data-ge-language).
26
+ const english = document.documentElement.getAttribute("data-ge-language") === "en";
27
+ const WORDS = english
28
+ ? { card: "Chart card", table: "Table", named: (kind, name) => kind + " \u201C" + name + "\u201D", first: (name) => "Table (first column \u201C" + name + "\u201D)", colon: ": ",
29
+ failing: (count) => "Checks failed \xB7 " + count, more: (count) => count + " more", all: (slug) => "gallery check " + slug + " runs every check (TypeScript too)." }
30
+ : { card: "\u56FE\u8868\u5361\u7247", table: "\u8868\u683C", named: (kind, name) => kind + "\u300C" + name + "\u300D", first: (name) => "\u8868\u683C\uFF08\u9996\u5217\u300C" + name + "\u300D\uFF09", colon: "\uFF1A",
31
+ failing: (count) => "\u68C0\u67E5\u672A\u901A\u8FC7 \xB7 " + count + " \u9879", more: (count) => "\u8FD8\u6709 " + count + " \u9879", all: (slug) => "gallery check " + slug + " \u8DD1\u5168\u90E8\u68C0\u67E5\uFF08\u542B TypeScript\uFF09\u3002" };
32
+ const more = panel.querySelector("[data-more]");
33
+ if (more) more.textContent = WORDS.more(more.dataset.more);
34
+ const all = panel.querySelector("[data-all]");
35
+ if (all) all.textContent = WORDS.all(all.dataset.all);
36
+ const tidy = (node) => (node?.textContent ?? "").replace(/\\s+/g, " ").trim().slice(0, 40);
37
+ const what = (host) => {
38
+ const card = host.closest("figure");
39
+ const title = card?.querySelector(":scope > h3, :scope > figcaption");
40
+ const table = host.closest(".doc-table-wrap, table");
41
+ const caption = table?.querySelector("caption");
42
+ const header = table?.querySelector("th");
43
+ return title ? WORDS.named(WORDS.card, tidy(title)) : card ? WORDS.card : caption && tidy(caption) ? WORDS.named(WORDS.table, tidy(caption)) : header ? WORDS.first(tidy(header)) : host.localName;
44
+ };
45
+ // A chart that drew nothing says why in its card (the kit's line, in the same language): that line, else the note in words.
46
+ const said = (host, name, note) => (name === "data-missing" && tidy(host.querySelector(".doc-chart-message"))) || noteInWords(note, { english });
47
+ let shown = "";
48
+ let frame = 0;
49
+ const draw = () => {
50
+ frame = 0;
51
+ const notes = [...document.querySelectorAll("[data-doc-layout]")].filter((host) => !host.closest("[data-doc-dev]"))
52
+ .flatMap((host) => layoutNotesOf(host.getAttribute("data-doc-layout"), document.documentElement.clientWidth)
53
+ .filter(({ level }) => level === "fail")
54
+ .map(({ note, name }) => ({ line: what(host) + WORDS.colon + said(host, name, note), note })));
55
+ const key = notes.map(({ line }) => line).join("\\n");
56
+ if (key === shown) return;
57
+ shown = key;
58
+ live.replaceChildren(...notes.map(({ line, note }) => Object.assign(document.createElement("li"), { textContent: line, title: note })));
59
+ live.parentElement.hidden = notes.length === 0;
60
+ const failing = failures + notes.length;
61
+ panel.querySelector("summary").textContent = failing ? WORDS.failing(failing) : "";
62
+ panel.hidden = failing === 0;
63
+ };
64
+ const later = (records) => {
65
+ if (!globalThis.document?.defaultView) return; // the page is gone
66
+ if (!frame && records.some((record) => !record.target.closest?.("[data-doc-dev]"))) frame = requestAnimationFrame(draw);
67
+ };
68
+ new MutationObserver(later).observe(document.documentElement, { subtree: true, childList: true, attributes: true, attributeFilter: ["data-doc-layout"] });
69
+ addEventListener("resize", () => { if (!frame) frame = requestAnimationFrame(draw); });
70
+ draw();
71
+ })();`;function to(e,a,t={},{directory:o}={}){let i=Sn({slug:e,html:a,metadata:t,...o?{directory:o}:{}}),f=i.slice(0,tt).map(p=>`<li>${jt(p)}</li>`).join(""),s=i.length>tt?`<p data-more="${i.length-tt}">\u8FD8\u6709 ${i.length-tt} \u9879</p>`:"",m=i.length?`<ul>${f}</ul>${s}<p data-all="${jt(e)}">gallery check ${jt(e)} \u8DD1\u5168\u90E8\u68C0\u67E5\uFF08\u542B TypeScript\uFF09\u3002</p>`:"";return`<details class="doc-checks" data-doc-dev data-failures="${i.length}"${i.length?"":" hidden"}><summary>${i.length?`\u68C0\u67E5\u672A\u901A\u8FC7 \xB7 ${i.length} \u9879`:""}</summary><div>${m}<div class="doc-checks-live" hidden><ul></ul></div></div><style>${Na}</style></details>
72
+ <script data-doc-dev>${Da}</script>`}import{browserDirectory as ds,kitSourceDirectory as na,release as fs,reportsDirectory as ms}from"../browser/shared/paths.mjs";import{FRAMED_BY as us,sendJson as Ho,serve as zt,serveFound as Ie}from"../browser/shared/http.mjs";import{languageScript as Bo}from"../browser/shared/i18n/index.mjs";import{announcePreviewServer as ps,galleryVersion as hs,sameDirectory as gs}from"../browser/shared/preview-server.mjs";import{registerQuietly as ws}from"../browser/shared/workspace-registry.mjs";import{lookWord as zo}from"../browser/shared/document-look.mjs";import{documentLook as Go,ownLookAt as ys}from"../browser/shared/workspace-look.mjs";import{slugPattern as oa}from"../browser/shared/reports.mjs";import{ATTRIBUTE as pt,PACKAGE_ID as ks}from"../browser/shared/components/installed.mjs";import{COMPONENTS_FOLDER as Ko,DOCUMENT_FOLDERS as Jo,EXTENSIONS_FOLDER as vs,PAGES_FOLDER as xs,WORKSPACE_FILE as ht,defaultWorkspace as Te,documentDirectory as ft,documentFiles as $s,isDocumentFile as Ss,isDocumentSource as Yo,isSlugName as aa,layoutOf as Me}from"../browser/shared/workspace.mjs";import{PAGE_FILES as Xo,homeCardsNew as bs,isBlankPage as Es,isPageFile as Os,pageFiles as Vo,pageHintShown as Cs,pageMetaNow as _s,pageVersion as Zo}from"../browser/shared/pages.mjs";import{LINK_FILE as Ps}from"../browser/shared/web-links.mjs";import{SIDEBAR_FILE as mt}from"../browser/shared/extension-sidebar.mjs";import{extensionColumnIds as Qo}from"../browser/shared/extensions.mjs";import{isExtensionId as js}from"../browser/shared/outline-shape.mjs";import{createHash as Qa,randomBytes as qa}from"node:crypto";import ee from"node:fs";import Tt from"node:os";import ge from"node:path";import{Transform as er}from"node:stream";import{pipeline as tr}from"node:stream/promises";import{exportSourceOf as nr}from"../browser/shared/export-wrap.mjs";import{writeAtomic as Rt}from"../browser/shared/files.mjs";import{sendJson as V}from"../browser/shared/http.mjs";import{said as Ft,saying as or}from"../browser/shared/i18n/index.mjs";import{IMPORT_LIMIT as so}from"../browser/shared/import-types.mjs";import{mediaUrl as ar}from"../browser/shared/media.mjs";import{fullAddress as rr}from"../browser/shared/page-address.mjs";import{documentLinks as io,slugPattern as co}from"../browser/shared/reports.mjs";import{documentDirectory as sr,documentFiles as lo,newDocSlug as ir,pageSlug as cr}from"../browser/shared/workspace.mjs";import{readWritingPreferences as lr,saysAnything as dr,unshownLines as fr}from"../browser/shared/writing-preferences.mjs";import no from"node:fs/promises";import Ka from"node:path";import{Worker as Wa}from"node:worker_threads";import{refusal as Ma,said as Ua}from"../browser/shared/i18n/index.mjs";var Ha=6e4,me=null,Ba=0,nt=0,je=new Map;function za(){me=new Wa(new URL("./worker.mjs",import.meta.url)),me.on("message",({id:a,result:t,error:o})=>{let i=je.get(a);i&&(je.delete(a),o?i.reject(Object.assign(new Error(o.message),o)):i.resolve(t),je.size===0&&(me?.unref(),Ga()))});let e=a=>{for(let t of je.values())t.reject(a);je.clear(),me=null};me.on("error",e),me.on("exit",a=>e(Ma(Ua("\u8F6C\u6362\u8FDB\u7A0B\u610F\u5916\u9000\u51FA\uFF08{0}\uFF09",a))))}function Ga(){clearTimeout(nt),nt=setTimeout(()=>{if(je.size===0&&me){let e=me;me=null,e.removeAllListeners("exit"),e.terminate()}},Ha),nt.unref?.()}function ve(e,a){clearTimeout(nt),me||za();let t=++Ba;return new Promise((o,i)=>{je.set(t,{resolve:o,reject:i}),me.ref(),me.postMessage({id:t,type:e,payload:a})})}import{pageLanguage as Ja}from"../browser/shared/components/page.mjs";function ot(e){return String(e??"").replace(/[\\/:*?"<>|\u0000-\u001f\u007f]/g," ").replace(/\s+/g," ").trim().slice(0,100).trim()||"Untitled"}function at(e,a){let t=e.lastIndexOf("."),[o,i]=t>0?[e.slice(0,t),e.slice(t)]:[e,""];for(let f=0;;f+=1){let s=f===0?e:`${o} ${f}${i}`;if(!a.has(s.toLowerCase()))return a.add(s.toLowerCase()),s}}function rt(e,a){let t=e.split("/").slice(0,-1),o=a.split("/"),i=0;for(;i<t.length&&i<o.length-1&&t[i]===o[i];)i+=1;return[...t.slice(i).map(()=>".."),...o.slice(i)].map(s=>s===".."?s:encodeURIComponent(s).replace(/\(/g,"%28").replace(/\)/g,"%29")).join("/")}import{documentDirectory as Ya,documentFiles as Xa}from"../browser/shared/workspace.mjs";var oo={markdown:"md",html:"html",pdf:"pdf"},Va={markdown:"text/markdown; charset=utf-8",html:"text/html; charset=utf-8",pdf:"application/pdf"},Za=e=>typeof e=="number"&&e>.1&&e<2;function ao(e){let{format:a,content:t="everything",subpages:o=!1,folders:i=!0,paper:f="A4",scale:s=1}=e??{};return Object.hasOwn(oo,a)&&["everything","no_files"].includes(t)&&typeof o=="boolean"&&typeof i=="boolean"&&["A4","A3","Letter","Legal","Tabloid"].includes(f)&&Za(s)}async function ro(e,a,t){let{format:o,content:i="everything",subpages:f=!1,folders:s=!0,paper:m="A4",scale:l=1}=a,p=oo[o],k=i==="everything",S=[],b=new Map,n=$=>b.get($)??b.set($,new Set).get($),c=async($,C)=>{let w=await t.titleOf($),j=at(`${ot(w)}.${p}`,n(C)),L=C?`${C}/${j}`:j,E=s?L.slice(0,-(p.length+1)):"";if(S.push({slug:$,title:w,file:L,folder:E,files:C?`${C}/assets`:"assets"}),f)for(let U of await t.childrenOf($))await c(U,E)};await c(e,"");let{links:v}=await t.links(),P=($,C)=>vn(C,$.slug,w=>{let j=o==="pdf"?null:S.find(L=>L.slug===w)?.file??null;return j&&rt($.file,j)},{blocks:o!=="markdown",links:v}),h=[],M=[];for(let $ of S)if(o==="markdown"){await t.check($.slug);let C=Ya($.slug,t.reportsDirectory),w=Pe(await no.readFile(Xa(C).html,"utf8"),{slug:$.slug,mode:"words",reportsDirectory:t.reportsDirectory}),j=P($,w),L=k&&!!Un(),{text:E,files:U,charts:J,charted:T}=await ve("markdown",{source:j,title:$.title,pictures:L}),G=E,Z=new Map;if(U.forEach(({src:g,name:y},A)=>{Z.has(g)||(Z.set(g,`${$.files}/${at(ot(y),n($.files))}`),k&&M.push({from:Ka.join(C,g),name:Z.get(g)}));let R=Z.get(g);G=G.replace(`\0F${A}\0`,()=>rt($.file,R))}),L&&J>0&&G.includes("\0C")){let g=await Bn(await t.offline($.slug,{files:!0})).catch(()=>[]);G=G.replace(/^.*\u0000C(\d+)\u0000.*$/gm,(y,A)=>{let R=g[Number(A)];if(!R)return"\0gone\0";let I=`${$.files}/${at(Ja(j)==="en"?T[Number(A)]?"Chart.png":"Figure.png":T[Number(A)]?"\u56FE\u8868.png":"\u56FE.png",n($.files))}`;return h.push({name:I,data:R,later:!0}),y.replace(`\0C${A}\0`,()=>rt($.file,I))}).replace(/\n*\u0000gone\u0000\n*/g,`
73
+
74
+ `).replace(/^\n+|\n+$/g,"")}h.push({name:$.file,data:G})}else o==="html"?h.push({name:$.file,data:P($,await t.offline($.slug,{files:k}))}):h.push({name:$.file,data:await Hn(P($,await t.offline($.slug,{files:k})),{paper:m,scale:l})});for(let $ of M){let C=await no.readFile($.from).catch(()=>null);C&&h.push({name:$.name,data:C})}let x=[...h.filter($=>!$.later&&S.some(C=>C.file===$.name)),...h.filter($=>$.later||!S.some(C=>C.file===$.name))];return x.length===1?{name:x[0].name,type:Va[o],data:Buffer.isBuffer(x[0].data)?x[0].data:Buffer.from(x[0].data,"utf8")}:{name:`${ot(S[0].title)}.zip`,type:"application/zip",data:Ln(x)}}var mr=3600*1e3,Lt=new Set,fo=!1,ur=e=>{Lt.add(e),!fo&&(fo=!0,process.once("exit",()=>{for(let a of Lt)try{ee.rmSync(a,{recursive:!0,force:!0})}catch{}}))},pr=/^u-[a-f0-9]{16}$/;function mo({edits:e,workspace:a,reports:t,reportsDirectory:o,offline:i}){let f=null,s=()=>f??=ee.promises.mkdtemp(ge.join(Tt.tmpdir(),"gallery-uploads-")).then(g=>(ur(g),g)),m=new Map,l=(g,y,A)=>[g,{ok:!1,reason:y,...or(A)}],p=g=>ee.promises.access(g).then(()=>!0,()=>!1),k=g=>sr(g,o),S=g=>lo(k(g)),b=async g=>{try{return JSON.parse(await ee.promises.readFile(S(g).json,"utf8")).title||g}catch{return g}};function n(g){if(g.method!=="POST")return[405,{ok:!1,reason:"method"}];let y=g.headers.host??"",A=g.socket.localPort;return y!==`127.0.0.1:${A}`&&y!==`localhost:${A}`?[403,{ok:!1,reason:"host"}]:g.headers.origin!==`http://${y}`?[403,{ok:!1,reason:"origin"}]:g.headers["x-gallery-token"]!==e.token?[403,{ok:!1,reason:"token"}]:/^application\/octet-stream\b/i.test(g.headers["content-type"]??"")?Number(g.headers["content-length"]??0)>so?l(413,"size","\u6587\u4EF6\u592A\u5927\uFF08\u6700\u591A 5GB\uFF09"):null:[415,{ok:!1,reason:"type"}]}async function c(){for(let[g,y]of m)Date.now()-y.at<mr||(m.delete(g),await ee.promises.rm(y.file,{force:!0}).catch(()=>{}))}async function v(g,y){let A=n(g);if(A)return g.resume(),V(y,...A);let R=new URL(g.url,"http://localhost").searchParams.get("name")?.replace(/[\u0000-\u001f]/g,"").trim()??"";if(!R||R.length>255)return g.resume(),V(y,...l(400,"name","\u6587\u4EF6\u540D\u4E0D\u5BF9"));await c();let I=`u-${qa(8).toString("hex")}`,N=ge.join(await s(),I),B=0,z=new er({transform(H,Q,q){B+=H.length,q(B>so?Object.assign(new Error("too-large"),{reason:"size"}):null,H)}});try{await tr(g,z,ee.createWriteStream(N))}catch(H){return await ee.promises.rm(N,{force:!0}).catch(()=>{}),H.reason==="size"?V(y,...l(413,"size","\u6587\u4EF6\u592A\u5927\uFF08\u6700\u591A 5GB\uFF09")):V(y,...l(400,"body","\u6587\u4EF6\u6CA1\u6709\u4F20\u5B8C"))}return m.set(I,{file:N,name:R,at:Date.now()}),V(y,200,{ok:!0,id:I})}async function P(g,y){let A=await e.check(g);if(A.error)return V(y,...A.error);let{slug:R,options:I}=A.body??{};if(typeof R!="string"||!co.test(R)||!await p(S(R).html))return V(y,...l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"));if(!ao(I))return V(y,...l(400,"options","\u5BFC\u51FA\u9009\u9879\u4E0D\u5BF9"));try{let N=await i(),B=new Map,z=D=>(B.has(D)||B.set(D,e.handIn(D,{reader:!0}).then(Y=>{if(!Y.ok)throw Object.assign(new Error(Y.message??Y.reason),{reason:Y.reason});if(Y.repeated.length)throw Object.assign(new Error("check"),{reason:"check",slug:D,failures:Ze(Y.repeated)})})),B.get(D)),H=new Map,Q={reportsDirectory:o,titleOf:b,childrenOf:async D=>{let{children:Y,links:re=[]}=await a.outline(),ne=ye=>(Y[ye]??[]).flatMap(pe=>re.includes(pe)||pe.startsWith("~")?ne(pe):[pe]);return ne(D)},links:()=>io(o),offline:async(D,Y)=>{await z(D);let re=await N(D,Y),ne=I.format==="markdown"?null:nr(re);return ne&&H.set(D,ne),re},check:async D=>(await z(D),N.check(D))},{name:q,type:te,data:K}=await ro(R,I,Q);H.size&&await(await Qe([...H.keys()],o)).keep([...H.keys()],H),y.writeHead(200,{"Content-Type":te,"Content-Length":K.length,"Content-Disposition":`attachment; filename*=UTF-8''${encodeURIComponent(q)}`,"X-File-Name":encodeURIComponent(q),"Cache-Control":"no-store"}),y.end(K)}catch(N){if(N.reason==="check"){let B=await b(N.slug),z=N.component?Ft("\u300C{0}\u300D\u91CC\u7684\u7EC4\u4EF6 {1} \u6709\u9519\u8BEF\uFF0C\u6CA1\u6709\u751F\u6210\u6587\u4EF6\uFF1A\u53EF\u4EE5\u8BA9 AI \u68C0\u67E5\u8FD9\u4EFD\u6587\u6863\u5E76\u4FEE\u597D",B,N.component):N.failures.length>1?Ft("\u300C{0}\u300D\u6CA1\u6709\u901A\u8FC7\u5BFC\u51FA\u524D\u7684\u68C0\u67E5\uFF0C\u6CA1\u6709\u751F\u6210\u6587\u4EF6\uFF1A{1}\uFF08\u5171 {2} \u5904\uFF1A\u53EF\u4EE5\u8BA9 AI \u68C0\u67E5\u8FD9\u4EFD\u6587\u6863\uFF0C\u5217\u51FA\u5168\u90E8\u5E76\u4FEE\u597D\uFF09",B,N.failures[0],N.failures.length):Ft("\u300C{0}\u300D\u6CA1\u6709\u901A\u8FC7\u5BFC\u51FA\u524D\u7684\u68C0\u67E5\uFF0C\u6CA1\u6709\u751F\u6210\u6587\u4EF6\uFF1A{1}",B,N.failures[0]);return V(y,...l(422,"check",z))}V(y,...l(N.reason==="browser"?422:N.reason==="busy"?409:N.reason==="missing"?404:500,N.reason??"export",N))}}async function h(g,y){let A=await e.check(g);if(A.error)return V(y,...A.error);let{slug:R}=A.body??{},I=(await e.readTaken(R,{wait:0}))?.text??null;if(I===null)return V(y,...l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"));let N=`http://${g.headers.host}`,{named:B}=await io(o),z=kn(Pe(I,{slug:R,mode:"words",reportsDirectory:o}),R,te=>te.slug&&rr(N,te,B),B),{text:H,files:Q}=await ve("markdown",{source:z,title:await b(R),pictures:!1}),q=H.replace(/\u0000F(\d+)\u0000/g,(te,K)=>{let{src:D,kind:Y}=Q[Number(K)];return encodeURI(`${N}${ar(Y==="image"?"asset":"file",R,D)}`)});return V(y,200,{ok:!0,text:q})}let M=async g=>{let y=await e.readTaken(g,{wait:0});return{source:y?.text??"",version:y?.version??null}},x=async(g,y=null)=>{let{source:A,version:R}=y??await M(g),I="\u5199\u4F5C\u504F\u597D",{text:N,files:B}=await ve("markdown",{source:A,title:I,pictures:!1}),z=N.split(`
75
+ `).slice(1).join(`
76
+ `).replace(/^[\s>]*(?:```.*|\d+\.|- \[x\])/gm,"").replace(/<\/?aside>/g,"");if(!/[\p{L}\p{N}]|\u0000F\d+\u0000/u.test(z))return{markdown:`# ${I}
77
+ `,empty:!0,version:R};let H=ge.relative(o,k(g)).split(ge.sep).join("/");return{markdown:`${N.replace(/\u0000F(\d+)\u0000/g,(Q,q)=>encodeURI(`${H}/${B[Number(q)].src}`))}
78
+ `,empty:!1,version:R}},$=g=>S(g).json,C=async g=>{try{let y=JSON.parse(await ee.promises.readFile($(g),"utf8"));return y&&typeof y=="object"?y:null}catch{return null}},w=g=>Qa("sha256").update(g).digest("hex").slice(0,16);async function j(g,y,A,R){let I=await C(g);if(!I||A===null)return;let{synced:N,...B}=I,z={file:w(y),page:A,unshown:R},H=I.madeSame;N===void 0&&H?.file===z.file&&H?.page===z.page&&JSON.stringify(H?.unshown)===JSON.stringify(R)||await Rt($(g),`${JSON.stringify({...B,madeSame:z},null,2)}
79
+ `)}async function L(g,y){let A=await ee.promises.mkdtemp(ge.join(Tt.tmpdir(),"gallery-preferences-"));try{let I=(await ve("import",{uploads:[{file:y,name:"preferences.md"}],scratch:A})).pages[0]??{nodes:[],raws:[],files:[],icon:null,lang:null},N=k(g),B=await C(g)??{},z=lo(N).html,H=await ee.promises.readFile(z,"utf8").catch(()=>""),Q=/<html\b[^>]*\slang="([^"]*)"/i.exec(H)?.[1]??null,{html:q}=await pn(g,B.title||"\u5199\u4F5C\u504F\u597D",B.description||"",{blank:!0,lang:Q}),te=typeof B.icon=="string"&&B.icon?B.icon:null,K=await ve("fill",{source:q,nodes:I.nodes,icon:te,raws:I.raws,lang:I.lang});I.files.length&&await ee.promises.mkdir(ge.join(N,"assets"),{recursive:!0});for(let{from:Y,name:re}of I.files){let ne=ge.join(N,"assets",re);await p(ne)||await ee.promises.copyFile(Y,ne)}let D=await ee.promises.readFile(z,"utf8").catch(()=>null);D!==null&&e.keepVersion?.(g,D),await Rt(z,Ve(K))}finally{await ee.promises.rm(A,{recursive:!0,force:!0}).catch(()=>{})}}async function E(g,y){let A=await e.check(g);if(A.error)return V(y,...A.error);let R=A.body?.opening===!0,I=await cr(o);if(!I)return V(y,...l(404,"missing","\u8FD8\u6CA1\u6709\u5199\u4F5C\u504F\u597D"));let N=null,B=(z,H)=>[200,{ok:!0,path:ge.resolve(N),remade:z,unshown:H}];return e.respond(async()=>{let z;({file:N,text:z}=await lr(o));let H=await M(I),Q=(await C(I))?.madeSame??null,q=Q===null||Q.page===H.version,te=Q!==null&&q&&Q.file===w(z);if(R&&te&&Array.isArray(Q.unshown))return B(!1,Q.unshown);let[K,D,Y,re]=[z,"",H.version,!1];if(R&&!q)await L(I,N),{markdown:D,version:Y}=await x(I),re=!0;else{let ye=await x(I,H),pe=z.trim()===ye.markdown.trim()||ye.empty&&!dr(z);D=ye.markdown,R?!pe&&!te&&(await L(I,N),{markdown:D,version:Y}=await x(I),re=!0):pe||(await Rt(N,ye.markdown),K=ye.markdown)}let ne=fr(K,D);return await j(I,K,Y,ne),B(re,ne)})(g,y)}async function U(g,y){let A=await e.check(g);if(A.error)return V(y,...A.error);let{uploads:R,parent:I="",from:N,language:B}=A.body??{},z={said:typeof N=="string"&&N.includes("{0}")&&N.length<=60?N:"\u5BFC\u5165\u81EA {0}",lang:B==="en"?"en":null};if(!Array.isArray(R)||R.length===0||R.length>1e3||!R.every(D=>typeof D=="string"&&pr.test(D)))return V(y,...l(400,"body"));let H=R.map(D=>m.get(D)).filter(Boolean);if(H.length!==R.length)return V(y,...l(410,"gone","\u4E0A\u4F20\u7684\u6587\u4EF6\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u5BFC\u5165"));for(let D of R)m.delete(D);let Q=typeof I=="string"&&co.test(I)&&await p(ge.join(o,I))?I:"",q=await ee.promises.mkdtemp(ge.join(Tt.tmpdir(),"gallery-import-")),te=()=>Promise.all([ee.promises.rm(q,{recursive:!0,force:!0}),...H.map(({file:D})=>ee.promises.rm(D,{force:!0}))]).catch(()=>{}),K;try{K=await ve("import",{uploads:H.map(({file:D,name:Y})=>({file:D,name:Y})),scratch:q})}catch(D){return await te(),V(y,...l(500,"convert",D))}return e.respond(async()=>{try{let{made:D,top:Y}=await An(K.pages,{create:t.create,slugOf:()=>ir(o),folderOf:k,fill:re=>ve("fill",re),place:a.place,under:Q,...z});return[200,{ok:!0,pages:D.length,reports:Y,skipped:K.skipped,missing:J(K.pages)}]}finally{await te()}})(g,y)}let J=g=>[...new Set(g.flatMap(function y(A){return[...(A.notes??[]).filter(R=>R.kind==="picture-missing").map(R=>R.name),...A.children.flatMap(y)]}))],T={export:P,markdown:h,upload:v,import:U,preferences:E};function G(g,y,A){return Object.hasOwn(T,A)?T[A](g,y).catch(R=>{y.headersSent||V(y,...l(500,"transfer",R))}):V(y,404,{ok:!1,reason:"unknown"})}async function Z(){let g=f;f=null,m.clear();let y=await g?.catch(()=>null);y&&(Lt.delete(y),await ee.promises.rm(y,{recursive:!0,force:!0}).catch(()=>{}))}return{handle:G,close:Z}}import{FACT_KINDS as Ts,QUERY_ROUTE as Rs,WORKSPACE_GLOBAL as Fs}from"../browser/shared/workspace-query.mjs";function uo({settled:e,tell:a,delay:t=120,recheck:o=1e3}){let i=new Map,f=(s,m=t)=>{clearTimeout(i.get(s));let l=setTimeout(async()=>{let p=await e(s).catch(()=>({source:null,held:!1,wait:0}));if(i.get(s)===l){if(p.held)return f(s,Math.min(Math.max(p.wait,50),o));if(p.wait>0)return f(s,p.wait);await a(s,p)}},m);i.set(s,l)};return f}import xe from"node:fs";import Ce from"node:path";import{isExtensionId as hr}from"../browser/shared/outline-shape.mjs";import{DOCUMENT_FOLDERS as po,isSlugName as At,layoutOf as ho}from"../browser/shared/workspace.mjs";function gr(e,a=!1,t=!1){let{components:o,gallery:i,preferencesPage:f,customPages:s,extensions:m}=ho(e),l=(n,c)=>{try{return xe.readdirSync(n,{withFileTypes:!0}).filter(v=>v.isDirectory()&&c(v.name)).map(v=>Ce.join(n,v.name))}catch{return[]}},p=l(m,n=>hr(n)&&!po.includes(n));if(a){let n=Ce.dirname(e);for(;!xe.existsSync(n)&&Ce.dirname(n)!==n;)n=Ce.dirname(n);return[n,e,...t?[i]:[],m,...p].filter(c=>xe.existsSync(c))}let k=[...l(e,n=>At(n)),...l(f,n=>At(n))],S=n=>[n,...l(n,c=>!c.startsWith(".")).flatMap(S)],b=l(s,n=>At(n)&&!po.includes(n));return[...new Set([e,...[i,f,s,m].filter(n=>xe.existsSync(n)),...b,...p,...k,...k.map(n=>Ce.join(n,"assets")).filter(n=>xe.existsSync(n)),...xe.existsSync(o)?S(o):[]])]}function Le(e,a,{folders:t=process.platform==="linux",extensionsOnly:o=!1,outline:i=!1}={}){let f=It(e),s=(b,n)=>{!(i&&n===ho(e).outline)&&(f(n)||Ce.basename(n).startsWith("."))||xe.stat(n,(v,P)=>{if(v)return a(v.code==="ENOENT"?"unlink":"change",n);let h=P.isDirectory();a(b==="rename"?h?"addDir":"add":h?"addDir":"change",n)})},m=()=>{};if(!t&&!o)try{let b=xe.watch(e,{recursive:!0},(n,c)=>c?s(n,Ce.join(e,c.toString())):a("reset",e));return b.on("error",m),{close:()=>b.close()}}catch(b){if(b.code!=="ERR_FEATURE_UNAVAILABLE_ON_PLATFORM")throw b}let l=new Map,p=null,k=()=>{let b=new Set(gr(e,o,i));for(let[n,c]of l)b.has(n)||(c.close(),l.delete(n));for(let n of b)if(!l.has(n))try{let c=xe.watch(n,(v,P)=>{if(!P)return a("reset",n);v==="rename"&&S(),s(v,Ce.join(n,P.toString()))});c.on("error",m),l.set(n,c)}catch{}},S=()=>{p??=setTimeout(()=>{p=null,k()},50)};return k(),{close(){clearTimeout(p);for(let b of l.values())b.close();l.clear()},get folders(){return[...l.keys()]}}}import wr from"node:fs/promises";import{packageScript as yr}from"../browser/shared/export-wrap.mjs";import{serveFound as kr}from"../browser/shared/http.mjs";import{extensionOf as vr,mediaTypeOf as xr}from"../browser/shared/media.mjs";var $r="/__gallery/components/",Sr=/^\/__gallery\/components\/([a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*)\/(.+)$/,br={js:"text/javascript; charset=utf-8",mjs:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",wasm:"application/wasm"};async function go(e,a,t,{root:o}){if(!e.startsWith($r))return!1;let[,i,f]=Sr.exec(e)??[],s=i?se(o).packages.get(i):null,m=s?.files.includes(f)?Vt(s,f):null,l=m?await wr.readFile(m).catch(()=>null):null,p=l&&f==="kit.js"?Buffer.from(yr(l.toString("utf8").replace(/^\uFEFF/,""))):l,k=p&&a===s.stamp&&a===Zt(s);return kr(t,p,{type:p?br[vr(f)]??xr(f):void 0,headers:{"X-Content-Type-Options":"nosniff","Cache-Control":k?"max-age=31536000, immutable":"no-store"}}),!0}import{BLOCK_ICON as Er}from"../browser/editor/components/icons.mjs";import{LISTED_BLOCKS as wo}from"../browser/editor/components/registry.mjs";import{PACKAGE_ID as Or}from"../browser/shared/components/installed.mjs";import{netHostsOf as yo}from"../browser/shared/net-policy.mjs";import{inLanguage as ko,refusal as st,said as _e}from"../browser/shared/i18n/index.mjs";function vo({root:e,taken:a}){let t=()=>{let s=se(e);return{packages:Qt(s).map(m=>{let l=nn(m.id)?tn(m.id):null;return{...m,newer:l?on(e,l):null,...l?{addAs:l.pack===qt?l.name:l.id}:{}}}),packs:bt(e,{settings:s.settings}),packageIcon:Er,blocks:wo.map(({id:m,name:l,icon:p,hideable:k})=>({id:m,name:{zh:ko("zh",l),en:ko("en",l)},icon:p,hidden:k&&s.settings.hidden.includes(m),hideable:k})),problem:Xt(s)}},o=({id:s,hidden:m,shown:l,disabled:p,unlisted:k,net:S})=>{if(![m,l,p,k,S].every(n=>n===void 0||typeof n=="boolean"))return _e("\u5F00\u5173\u7684\u503C\u4E0D\u5BF9");let b=wo.find(n=>n.id===s);return b?p!==void 0||l!==void 0||k!==void 0||S!==void 0?_e("\u5185\u7F6E\u5757\u53EA\u80FD\u9690\u85CF\uFF0C\u4E0D\u80FD\u505C\u7528"):m&&!b.hideable?_e("\u8FD9\u4E2A\u5757\u4E0D\u80FD\u9690\u85CF"):null:typeof s=="string"&&Or.test(s)?S&&yo(se(e).packages.get(s)?.needs).length===0?_e("\u8FD9\u4E2A\u5757\u4E0D\u8054\u7F51"):null:_e("\u6CA1\u6709\u8FD9\u4E2A\u7EC4\u4EF6")};return{read:t,write:async s=>{if(s?.pack!==void 0){let{pack:S,enabled:b}=s;if(typeof b!="boolean")throw st(_e("\u5F00\u5173\u7684\u503C\u4E0D\u5BF9"));if(typeof S!="string"||!bt(e,{settings:se(e).settings}).some(({id:n})=>n===S))throw st(_e("\u6CA1\u6709\u8FD9\u4E2A\u5757\u5305"));return await $t(e,{pack:S,enabled:b}),a(),t()}let m=o(s);if(m)throw st(m);let{net:l,...p}=s,k=l===void 0?void 0:l?yo(se(e).packages.get(s.id)?.needs):[];return await $t(e,{...p,...k?{net:k}:{}}),a(),t()},install:({path:s,zip:m}={})=>{let l=typeof m=="string"?Mn(Buffer.from(m,"base64")):typeof s=="string"&&s.trim()?Wn(s):null;if(!l)throw st(_e("\u7C98\u8D34\u5757\u5305\u7684\u6587\u4EF6\u5939\u6216 zip \u7684\u8DEF\u5F84"),{code:"path"});let p=sn(e,l);return a(),{...t(),installed:p}}}}import Cr from"node:path";import{reportsDirectory as _r}from"../browser/shared/paths.mjs";import{layoutOf as Pr}from"../browser/shared/workspace.mjs";async function xo(e,a,{root:t=_r,workspace:o=null}={}){let{exports:i}=Pr(t),f=Cr.join(i,`${a}.html`),s=await Qe([a],t),m=await e.handInReport(a,{reader:!0});if(!m.ok)return{problems:[],refused:{reason:m.reason,message:m.message},file:f};if(m.repeated.length)return{problems:Ze(m.repeated),file:f};let{exported:l,failures:p}=await On([a],{workspace:o,directory:t});return await s.keep(l.map(k=>k.slug)),{problems:p.get(a)??[],file:f}}import $o from"node:fs/promises";import So from"node:path";import{MEDIA_ROUTES as bo,assetFile as jr,extensionOf as Tr,imageFile as Rr,mediaTypeOf as Fr}from"../browser/shared/media.mjs";import{serveFound as Eo}from"../browser/shared/http.mjs";import{slugPattern as Oo}from"../browser/shared/reports.mjs";import{pageFiles as Lr}from"../browser/shared/pages.mjs";import{documentDirectory as Ar}from"../browser/shared/workspace.mjs";var Nt={asset:e=>({"Content-Type":Fr(e),"Cache-Control":"no-cache"}),file:()=>({"Content-Type":"application/octet-stream","Content-Disposition":"attachment","X-Content-Type-Options":"nosniff","Cache-Control":"no-cache"}),embed:e=>/\.pdf$/i.test(e)?{"Content-Type":"application/pdf","X-Content-Type-Options":"nosniff","Cache-Control":"no-cache"}:{"Content-Type":"text/html; charset=utf-8","Content-Security-Policy":"sandbox allow-scripts allow-popups allow-forms allow-modals","X-Content-Type-Options":"nosniff","Cache-Control":"no-cache"}},Ir=new RegExp(`^/__gallery/edit/(${Object.keys(bo).join("|")})/([^/]+)/(assets/[^/]+)$`);async function Co(e,a,{reportsDirectory:t}){let[,o,i,f]=Ir.exec(e)??[];if(!o)return!1;let s=Oo.test(i)&&bo[o](f)?await $o.readFile(So.join(Ar(i,t),f)).catch(()=>null):null;return Eo(a,s,{headers:Nt[o](f)}),!0}var Nr={css:"text/css; charset=utf-8",js:"text/javascript; charset=utf-8",mjs:"text/javascript; charset=utf-8"},Dr=/^\/pages\/([^/]+)\/(assets\/[^/]+)$/;async function _o(e,a,{reportsDirectory:t}){let[,o,i]=Dr.exec(e)??[];if(!o)return!1;let f=Oo.test(o)&&jr(i)?await $o.readFile(So.join(Lr(o,t).folder,i)).catch(()=>null):null,s=Nr[Tr(i??"")];return Eo(a,f,{headers:s?{"Content-Type":s,"X-Content-Type-Options":"nosniff","Cache-Control":"no-cache"}:(Rr(i)?Nt.asset:Nt.file)(i)}),!0}import Wr from"node:dns";import{sendJson as Ae}from"../browser/shared/http.mjs";import{createNetCache as Mr,dataOf as Ur}from"../browser/shared/net-cache.mjs";import{readKeys as Hr}from"../browser/shared/net-keys.mjs";import{addressKind as ct,addressOf as Io,hostIn as Po,keptHere as jo,keyIn as To,mapsHere as Br,netHostsOf as zr,proxyHere as Gr,withKey as Kr}from"../browser/shared/net-policy.mjs";import{galleryVersion as Jr}from"../browser/shared/preview-server.mjs";var it=512*1024,Yr=6e4,Ro=20,Fo=5,Lo=1e4,Xr=16*1024,Vr=new Set([301,302,303,307,308]),Zr=/^(?:application\/(?:[\w.-]+\+)?json|text\/[\w.+-]+)$/i,$e=(e,a={})=>({ok:!1,code:e,...a}),ae=(e,a={},t)=>Object.assign(new Error(e),{refusal:$e(e,a),...t===void 0?{}:{detail:t}});function Qr(e,a){let t;try{t=new URL(e,a)}catch{return{code:"url",why:"a redirect to an address that does not parse"}}let o=Io(t.href);return o.code?{code:"url",why:`a redirect to ${t.host?`${t.protocol}//${t.host}`:t.protocol}: ${o.why}`}:o}function Ao(e,a){let t=[...new Set([a,encodeURIComponent(a)])].filter(Boolean),o=i=>typeof i=="string"?t.reduce((f,s)=>f.split(s).join("{key}"),i):i;return Object.fromEntries(Object.entries(e).map(([i,f])=>[i,o(f)]))}var qr=e=>Wr.promises.lookup(e,{all:!0,verbatim:!0}),Dt=e=>URL.parse(e)?.host||"?",Wt=e=>ct(e)==="fake-ip"?"an address a fake-ip proxy's DNS gives":"an address of this computer or of a private network";async function es(e,{resolve:a,proxy:t}){let o=e.hostname,i=Gr(t),f=c=>{let v=ct(c);return v==="public"||v==="fake-ip"&&i},s=o.replace(/^\[|\]$/g,"");if(ct(s)!=="none"){if(f(s))return{address:s};throw ae("private",{host:o,address:s,why:`${s} is ${Wt(s)}`})}let m;try{m=(await a(o)).map(c=>typeof c=="string"?c:c.address)}catch(c){throw ae("offline",{why:`${o} did not resolve (${c.code??c.message})`})}if(m.length===0)throw ae("offline",{why:`${o} did not resolve`});let l=m.filter(c=>!f(c));if(l.length===0)return{address:m[0]};let p=l.filter(c=>!Br(c)),k=p.length?p:l,S=k.find(c=>!c.includes(":"))??k[0],b=`${o} resolved to ${S}, ${Wt(S)}`,n=jo(o)?"and its name is one kept for this computer (localhost)":t?i?e.protocol!=="https:"?"and an http address is never handed to a proxy by its name (no TLS to check the site)":p.length?"and a private network's address is never handed to a proxy by its name (that network's own machines are there)":null:"and the proxy it goes through is not on this computer":"and no proxy of this computer goes between to reach it by its name";if(n===null)return{address:null,resolved:S,said:b};throw ae("private",{host:o,address:S,why:`${b}, ${n}`},i||!t||jo(o)?void 0:`${b}, and the proxy it goes through (${Dt(t)}) is not on this computer`)}var ts=({resolve:e=qr,proxyFor:a=Cn,connect:t,ca:o}={})=>async(i,{headers:f,signal:s})=>{let m=await a(i.href),l=await es(i,{resolve:e,proxy:m}),{address:p}=l,k={...t?{connect:t}:{},...o?{ca:o}:{}};try{return await qe(i,{address:p,proxy:m,headers:f,signal:s,...k})}catch(S){if(!(m&&S.proxyFailed&&(p!==null||S.code==="ECONNREFUSED")))throw p===null&&!s?.aborted?ae("offline",{why:`${l.said}, and no site the proxy of this computer reached by its name proved to be it`},`${l.said}, handed by its name to the proxy (${Dt(m)}): ${S.code??S.message}`):S;let b=c=>`and the proxy of this computer that would reach it${c?` (${Dt(m)})`:""} is not running`,n=p===null?l.said:`${i.hostname.replace(/^\[|\]$/g,"")===p?p:`${i.hostname} resolved to ${p}`}, ${Wt(p)}`;if(p===null||ct(p)!=="public")throw ae("private",{host:i.hostname,address:p??l.resolved,why:`${n}, ${b(!1)}`},`${n}, ${b(!0)}`);return qe(i,{address:p,proxy:null,headers:f,signal:s,...k})}},No=e=>(a,{headers:t,signal:o})=>qe(new URL(`http://127.0.0.1:${e}/${a.protocol.slice(0,-1)}/${a.host}${a.pathname}${a.search}`),{address:"127.0.0.1",headers:t,signal:o});async function ns(e){let a=0,t=[];for await(let o of e){if(a+=o.length,a>Xr)throw Object.assign(new Error("too-large"),{status:413});t.push(o)}return JSON.parse(Buffer.concat(t).toString("utf8"))}function os(e,a){let t=/;\s*charset="?([^";]+)"?/i.exec(a)?.[1];try{return new TextDecoder(t||"utf-8").decode(e)}catch{return new TextDecoder("utf-8").decode(e)}}function Do({root:e,catalog:a=()=>se(e),hop:t=null,now:o=Date.now,cache:i=Mr(e),log:f=()=>{}}){let s=t??ts(),m=new Map,l=c=>{let v=o(),P=(m.get(c)??[]).filter(h=>v-h<6e4);return P.length>=Ro?(m.set(c,P),!1):(m.set(c,[...P,v]),!0)},p={accept:"application/json, text/plain;q=0.9, text/*;q=0.8","user-agent":`Gallery/${Jr} (a custom block's card)`};async function k(c,{hosts:v,allowed:P,key:h}){let M=AbortSignal.timeout(Lo),x=c;for(let $=0;;$++){let C;try{C=await s(h===void 0?x:new URL(Kr(x.href,h)),{headers:p,signal:M})}catch(E){throw E.refusal?E:ae("offline",{why:M.aborted?`no answer within ${Lo/1e3} s`:String(E.code??E.message)})}if(Vr.has(C.status)&&C.headers.get("location")){if(C.body?.cancel().catch(()=>{}),$>=Fo)throw ae("status",{status:C.status,why:`more than ${Fo} redirects`});let E=Qr(C.headers.get("location"),x);if(E.code)throw ae("url",{why:E.why});let U=Po(E.url.hostname,v);if(!U)throw ae("host",{host:E.url.hostname,why:`a redirect to ${E.url.hostname}, which the block's needs do not name`});if(!P.includes(U))throw ae("consent",{hosts:v.filter(J=>!P.includes(J))});x=E.url,h=To(x.href)?h:void 0;continue}if(C.status<200||C.status>299)throw C.body?.cancel().catch(()=>{}),ae("status",{status:C.status});let w=C.headers.get("content-type")??"",j=w.split(";")[0].trim();if(j&&!Zr.test(j))throw C.body?.cancel().catch(()=>{}),ae("type",{type:j});if(Number(C.headers.get("content-length"))>it)throw C.body?.cancel().catch(()=>{}),ae("too-large",{limit:it});let L;try{L=C.body?await _n(C,it):Buffer.alloc(0)}catch(E){throw ae("offline",{why:String(E.code??E.message)})}if(L===null)throw ae("too-large",{limit:it});return{type:j||"text/plain",text:os(L,w)}}}let S=(c,v,P)=>{let h=Ur(c,v);return h===void 0?$e("type",{why:"the answer is no JSON"}):{ok:!0,data:h,at:c.at,cached:P}};async function b(c){let{block:v,url:P,as:h="json",doc:M=null}=c??{},x=typeof v=="string"?a().packages.get(v):null;if(!x)return $e("missing",{why:"no custom block of that id loads in this workspace"});let $=zr(x.needs);if(h!=="json"&&h!=="text")return $e("url",{why:'as is "json" or "text"'});let C=Io(P);if(C.code)return $e("url",{why:C.why});let{url:w}=C,j=Po(w.hostname,$);if(!j)return $e("host",{host:w.hostname,why:$.length?`its needs name ${$.join(", ")}`:"its needs name no host of the net"});let L=a().settings.net?.[v]??[];if(!L.includes(j))return $e("consent",{hosts:$.filter(T=>!L.includes(T))});let E;if(To(w.href)){let T=Hr(e);if(E=T[w.hostname]??T[j],E===void 0)return $e("key",{host:w.hostname})}let U=w.href,J=i.get(U);if(i.used(U,M,h),J&&o()-Date.parse(J.at)<Yr)return S(J,h,!0);if(!l(v))return J?S(J,h,!0):$e("rate",{why:`more than ${Ro} fetches in a minute`});try{let{type:T,text:G}=await k(w,{hosts:$,allowed:L,key:E});return S(i.put(U,{type:T,text:G,at:new Date(o()).toISOString()}),h,!1)}catch(T){if(!T.refusal)throw T;if(J&&T.refusal.code!=="consent")return S(J,h,!0);let G=E===void 0?T.refusal:Ao(T.refusal,E),Z=T.detail===void 0?G.why:E===void 0?T.detail:Ao({why:T.detail},E).why;return(G.code!=="offline"||T.detail!==void 0)&&f(`${v}: ${w.hostname} refused (${G.code}${Z?`: ${Z}`:""})`),G}}async function n(c,v){if(c.method!=="POST")return Ae(v,405,{ok:!1,reason:"method"});if(c.headers.origin!==`http://${c.headers.host}`)return Ae(v,403,{ok:!1,reason:"origin"});if(!/^application\/json\b/i.test(c.headers["content-type"]??""))return Ae(v,415,{ok:!1,reason:"type"});let P;try{P=await ns(c)}catch(h){return Ae(v,h.status??400,{ok:!1,reason:"body"})}try{return Ae(v,200,await b(P))}catch(h){return Ae(v,500,{ok:!1,code:"offline",why:h.message})}}return{handle:n,answer:b,cache:i}}import{walk as as,attr as Mt}from"../browser/shared/html-tree.mjs";import{workspaceAddress as Ut}from"../browser/shared/workspace-address.mjs";function lt(e,a){if(!a)return e;let t=hn(e),o=Je(e,s=>Ut(s,a)!==s,t),i=Ye(o,s=>Ut(s.value,a)),f=s=>s.replace(/(["'`])(\/(?:__gallery\/(?:edit\/(?:v\/[a-f0-9]{16}\/)?src\/|components\/)|__gallery\/|generated\/|pages\/))/g,(m,l,p)=>l+Ut(p,a));return as(t,s=>{if(s.tagName==="script"&&(Mt(s,"data-doc-dev")!==void 0||Mt(s,"data-doc-package")!==void 0)&&!Mt(s,"src")){let m=s.sourceCodeLocation?.startTag?.endOffset,l=s.sourceCodeLocation?.endTag?.startOffset;m!==void 0&&l!==void 0&&i.push({start:m,end:l,text:f(e.slice(m,l))})}}),Ke(e,i)}function Wo({max:e=20}={}){let a=new Map;return{get(t,o,i){let f=`${t} ${o}`,s=a.get(f);return!s||s.text!==i?null:(a.delete(f),a.set(f,s),s.page)},set(t,o,i,f){let s=`${t} ${o}`;for(a.delete(s),a.set(s,{slug:t,text:i,page:f});a.size>e;)a.delete(a.keys().next().value)},clear(){a.clear()},forget(t){for(let[o,i]of a)i.slug===t&&a.delete(o)},get size(){return a.size}}}import{createHash as rs}from"node:crypto";import{readFileSync as ss}from"node:fs";import Mo from"node:fs/promises";import is from"node:path";import{release as cs,releaseFile as ls}from"../browser/shared/paths.mjs";async function dt(e){let a=await Promise.all(e.map(o=>Mo.stat(o).then(({mtimeMs:i,size:f})=>`${i} ${f}`,()=>"none"))),t=rs("sha256");return e.forEach((o,i)=>t.update(`${o}\0${a[i]}
80
+ `)),t.digest("hex").slice(0,16)}function Uo(e,a){let t=null,o=async()=>(await Promise.all(e.map(async i=>(await Mo.readdir(i,{recursive:!0,withFileTypes:!0}).catch(()=>[])).filter(s=>s.isFile()).map(s=>is.join(s.parentPath,s.name))))).flat().filter(a).sort();return{files:()=>t??=o(),changed:()=>{t=null}}}var Ht=cs?JSON.parse(ss(ls,"utf8")).stamps:null;var gt=oa.source.slice(1,-1),Ls=new RegExp(`^/generated/(${gt})\\.html$`),As=new RegExp(`^/(${gt})/(?:doc|report)\\.html$`),Is=new RegExp(`^/pages/(${gt})$`),Ns=new RegExp(`^/__gallery/pages/(${gt})/(cards|library|hint)$`),Gt="/__gallery/events",Re=ds,ra=/^\/__gallery\/edit\/(v\/[a-f0-9]{16}\/)?src\/((?:shared(?:\/components|\/emoji|\/i18n)?\/|editor\/(?:page|components)(?:\/[a-z]+(?:-[a-z]+)*){0,2}\/(?!files?\.mjs))[a-z]+(?:-[a-z]+)*\.mjs)$/,Ds=/^\/__gallery\/edit\/(?:v\/[a-f0-9]{16}\/)?src\/(shared\/emoji\/data\/[a-z]+(?:-[a-z]+)*\.(json|bin))$/,ut=[X.join(Re,"editor","page"),X.join(Re,"editor","components"),X.join(Re,"shared")],Ws=e=>ra.test(`/__gallery/edit/src/${X.relative(Re,e).split(X.sep).join("/")}`);var Ms=[na,X.join(Re,"shared","components")],vd=[na,...ut],Ue={"Cache-Control":"no-store"},qo={"Cache-Control":"max-age=31536000, immutable"},Bt=(e,a,t)=>zt(e,{type:a,headers:{...Ue,...us},body:t});function Us(e){let a=e.headers?.host??"",t=e.socket?.localPort;return!!t&&(a===`127.0.0.1:${t}`||a===`localhost:${t}`)}function Hs(e){if(e.method!=="GET"&&e.method!=="HEAD")return null;let a=e.socket?.localPort;if(!a||e.headers?.host!==`localhost:${a}`)return null;let t=new URL(e.url||"/","http://localhost");return t.pathname==="/"||t.pathname==="/index.html"?`http://127.0.0.1:${a}${t.pathname}${t.search}`:null}var sa=`window.addEventListener("doc-net-fetch", (event) => {
81
+ event.preventDefault();
82
+ event.detail.answer(fetch("/__gallery/net", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(event.detail.ask) }).then((response) => response.json()));
83
+ });`,ia=`let lost = false;
84
+ events.onerror = () => { lost = true; };
85
+ events.onopen = () => {
86
+ if (!lost) return;
87
+ lost = false;
88
+ for (const kind of ${JSON.stringify(Ts)}) window.dispatchEvent(new CustomEvent("doc-workspace-change", { detail: kind }));
89
+ };`,Bs=(e,a,t)=>`<script data-doc-dev>
90
+ (() => {
91
+ document.currentScript.remove();
92
+ ${sa}
93
+ const solo = new URLSearchParams(location.search).has("solo");
94
+ let catalog = "${t}";
95
+ const holds = (ids) => document.querySelector(ids === undefined ? "[${pt}]" : ids.split(",").map((id) => '[${pt}="' + id + '"]').join());
96
+ const events = new EventSource("${Gt}?slug=${e}");
97
+ ${ia}
98
+ events.onmessage = (event) => {
99
+ const [kind, next, ids, more, consents, unlisted, packs] = event.data.split(" ");
100
+ if (kind === "notes") return void window.dispatchEvent(new CustomEvent("doc-annotations-changed", { detail: { version: next ?? "" } }));
101
+ if (kind === "changes") return void window.dispatchEvent(new CustomEvent("doc-changes-changed", { detail: { stamp: next ?? "" } }));
102
+ if (kind === "look") return void window.dispatchEvent(new CustomEvent("doc-look-request", { detail: { look: Object.fromEntries(new URLSearchParams(next ?? "")), from: "file" } }));
103
+ if (kind === "settings") return void window.dispatchEvent(new CustomEvent("doc-settings-changed", { detail: { hidden: next ? next.split(",") : [], disabled: ids ? ids.split(",") : [], shown: more ? more.split(",") : [], net: consents ? consents.split(",") : [], unlisted: unlisted ? unlisted.split(",") : [], packsOff: packs ? packs.split(",") : [] } }));
104
+ if (kind === "data") return void window.dispatchEvent(new CustomEvent("doc-workspace-change", { detail: next ?? "" }));
105
+ if (kind !== "report" && kind !== "assets" && kind !== "components") return;
106
+ if (kind === "components") {
107
+ if (document.readyState === "loading") return void document.addEventListener("DOMContentLoaded", () => events.onmessage(event), { once: true });
108
+ if (solo || next === catalog) return;
109
+ catalog = next;
110
+ if (!holds(ids)) return void window.dispatchEvent(new CustomEvent("doc-catalog-changed", { detail: { ids: ids === undefined ? null : ids.split(",").filter(Boolean) } }));
111
+ }
112
+ if (window.__galleryEditBusy) {
113
+ window.dispatchEvent(new CustomEvent({ report: "doc-source-changed", assets: "doc-assets-changed", components: "doc-components-changed" }[kind], { detail: { version: next ?? null } }));
114
+ return;
115
+ }
116
+ if (kind === "report" && next === "${a}") return;
117
+ if (window.__galleryEditReload) return window.__galleryEditReload(); // in a workbench: swapped in, no reload seen
118
+ location.reload();
119
+ };
120
+ })();
121
+ </script>`,zs=(e,a,t)=>`<script>
122
+ (() => {
123
+ document.currentScript.remove();
124
+ ${sa}
125
+ let catalog = "${t}";
126
+ const holds = (ids) => {
127
+ const named = ids === undefined ? "[${pt}]" : ids.split(",").filter(Boolean).map((id) => '[${pt}="' + id + '"]').join() || ":not(*)";
128
+ return Boolean(document.querySelector(named)) || [...document.querySelectorAll("template[data-ge-held]")].some((held) => held.content.querySelector(named));
129
+ };
130
+ const again = () => (window.__galleryEditReload ? window.__galleryEditReload() : location.reload());
131
+ const events = new EventSource("${Gt}?page=${e}");
132
+ ${ia}
133
+ events.onmessage = (event) => {
134
+ const [kind, next, ids, more, consents, unlisted, packs] = event.data.split(" ");
135
+ if (kind === "page") return void (window.__galleryPageChanged ? window.__galleryPageChanged(next) : next !== "${a}" && again());
136
+ if (kind === "assets") return void again();
137
+ if (kind === "settings") return void window.dispatchEvent(new CustomEvent("doc-settings-changed", { detail: { hidden: next ? next.split(",") : [], disabled: ids ? ids.split(",") : [], shown: more ? more.split(",") : [], net: consents ? consents.split(",") : [], unlisted: unlisted ? unlisted.split(",") : [], packsOff: packs ? packs.split(",") : [] } }));
138
+ if (kind === "data") return void window.dispatchEvent(new CustomEvent("doc-workspace-change", { detail: next ?? "" }));
139
+ if (kind !== "components") return;
140
+ if (document.readyState === "loading") return void document.addEventListener("DOMContentLoaded", () => events.onmessage(event), { once: true });
141
+ if (next === catalog) return;
142
+ catalog = next;
143
+ if (holds(ids)) again();
144
+ };
145
+ })();
146
+ </script>`;function ea(e,a){let t=X.relative(e,a).split(X.sep);if(t[0]===".."||X.isAbsolute(t[0])||t[0]==="")return null;if(t.length===1&&t[0]===ht)return{slug:null,name:ht,packages:!0};let o=l=>process.platform==="win32"?l.toLowerCase():l;if(o(t[0])===vs&&t.length>=2&&js(t[1])&&!Jo.includes(t[1])){let l=t.slice(2);return l.some(p=>p.startsWith("."))?null:{extension:t[1],name:l.length===1?l[0]:null}}if(o(t[0])===xs&&t.length>=2&&aa(t[1])&&!Jo.includes(t[1])){let l=t.slice(2);return l.some(p=>p.startsWith("."))?null:{page:t[1],name:l.length===1?l[0]:null}}let i=t[0]===".gallery"&&t[1]==="pages"&&t.length>=3,[f,...s]=i?t.slice(2):t,m=!i&&o(f)===Ko;return!(m||oa.test(f))||f==="exports"||s.some(l=>l.startsWith("."))?null:{slug:m?Ko:f,name:s.length===1?s[0]:null,...m?{packages:m}:{}}}function It(e){let a=S=>process.platform==="win32"?X.resolve(S).toLowerCase():X.resolve(S),{gallery:t,preferencesPage:o,exports:i,extensions:f}=Me(e),[s,m,l,p]=[a(t),a(o),a(i),a(f)],k=(S,b)=>S===b||S.startsWith(b+X.sep);return S=>{let b=a(S);return k(b,p)&&b!==p&&b.slice(p.length+1).split(X.sep).some((n,c)=>c>0&&(n==="node_modules"||n===".git"))?!0:k(b,s)&&b!==s&&!k(b,m)||k(b,l)}}var ta=`<script data-doc-dev>document.currentScript.remove(); globalThis.${Fs} = ${JSON.stringify(Rs)};</script>`,ue=(e,a,t)=>new RegExp(`</${a}>`,"i").test(e)?e.replace(new RegExp(`</${a}>`,"i"),()=>` ${t}
147
+ </${a}>`):`${e}
148
+ ${t}`;function Kt({token:e=null,unified:a=!1,base:t="",reportsDirectory:o=ms,stateDirectory:i=Me(o).state,projects:f=void 0,onWorkspaceChange:s=()=>{},announceServer:m=!0,logger:l=console,kind:p="dev",workbenchPage:k=null,closeServer:S=async()=>{},exit:b=()=>process.exit(0)}={}){let n=new Set,c=(r,d="",u="report")=>{for(let _ of n)(!r||_.slug===r)&&_.response.write(`data: ${r?`${u} ${d}`:"assets"}
149
+
150
+ `)},v=(r,d)=>{for(let u of n)u.page===r&&u.response.write(`data: page ${d}
151
+
152
+ `)},P=()=>{K("workspace",()=>{for(let r of n)r.workspace&&r.response.write(`data: workspace ${Date.now()}
153
+
154
+ `)})},h=()=>{P(),s(o)},M=r=>c(r,String(Date.now()),"changes"),x=Fn({base:t,token:e,reportsDirectory:o,stateDirectory:i,finish:Ve,log:r=>l.info?.(`[gallery] ${r}`),onChanges:M}),$=(r,d,u,{lang:_=null,page:W=!1}={})=>un(r,d,u,{directory:o,blank:!0,lang:_,page:W}),C=i?Jn({file:X.join(i,"activity.json")}):null,w=Nn({root:o,read:In(x),activity:C,draw:(r,d)=>Pe(r,{slug:d,mode:"words",reportsDirectory:o})}),j=new Set,L=r=>{for(let d of r)j.add(d);j.size!==0&&K("data",()=>{let d=[...j];j.clear();for(let u of n)if(u.slug||u.page)for(let _ of d)u.response.write(`data: data ${_}
155
+
156
+ `)})},E=r=>X.resolve(X.dirname(ft(r,o)))===X.resolve(o),U=null,J=null,T=()=>J??=(async()=>{for(let r of n)r.response.end();n.clear(),await Promise.race([S().catch(()=>{}),new Promise(r=>setTimeout(r,3e3))]),await C?.close(),await U?.().catch(()=>{}),await Z.close(),b()})(),G=Dn({reportsDirectory:o,projects:f,unified:a,server:{kind:p,version:hs,stop:T},edits:x,reports:{create:$,export:r=>xo(x,r,{root:o,workspace:d=>w.snapshot(d)}),words:(r,d)=>Pe(r,{slug:d,mode:"words",reportsDirectory:o})},components:vo({root:Te(),taken:()=>ne.taken()}),changed:h,index:w,web:{frameable:Pn,title:jn,icon:r=>Tn(r)}}),Z=mo({edits:x,workspace:G,reports:{create:$},reportsDirectory:o,offline:r=>En({...r,directory:o,workspace:d=>w.snapshot(d)})}),g=Do({root:Te(),hop:process.env.GALLERY_TEST_NET?No(Number(process.env.GALLERY_TEST_NET)):null,log:r=>l.info?.(`[gallery] ${r}`)}),y=dn({root:Te(),edits:x,stateDirectory:Me(Te()).state,catalogTaken:()=>ne.taken(),log:r=>l.info?.(`[gallery] ${r}`),shown:(r,d)=>lt(Pt(r,d),t)}),A=(r,d,{present:u=!1,editorModule:_,kit:W}={})=>{let O=d,ce="",oe="",de=!0;try{u||({html:O,snippet:ce,head:oe}=x.preview(r,d,{editor:_,kitTags:fe=>yn(fe,W)}))}catch(fe){de=!1,l.warn(`[gallery] text editing unavailable for ${r}: ${fe.message}`)}if({html:O}=xn(O,{slug:r,mode:"preview",reportsDirectory:o,kit:W}),O=ue(O,"head",Bs(r,We(d),se().stamp)),O=ue(O,"head",`<script data-doc-dev>${Bo()}</script>`),O=ue(O,"head",ta),oe&&(O=ue(O,"head",oe)),u)return{html:ue(O,"head",`<style data-doc-present>.doc-display { display: none !important; }</style>
157
+ <script type="module" src="/__gallery/edit/src/editor/page/present-links.mjs" data-doc-dev></script>`),whole:de};let ke="";try{ke=to(r,d,{},{directory:ft(r,o)})}catch(fe){de=!1,l.warn(`[gallery] checks unavailable for ${r}: ${fe.message}`)}return ke&&(O=ue(O,"body",ke)),{html:ce?ue(O,"body",ce):O,whole:de}},R=Wo(),I=Uo(ut,Ws),N=r=>{let d=ft(r,o);return[d,X.join(d,"assets")]},B=()=>Ht?.editor??I.files().then(dt),z=r=>Ht?.kit?.[r.id]??dt([Ct(r)]),H=async(r,d,{present:u})=>{let[_,W,O]=await Promise.all([u?"":B(),Promise.all(Fe.map(z)),dt(N(r))]),ce=[u?"present":_,...W,O,se().stamp,`look:${zo(Go(r,o))}`].join(" "),oe=R.get(r,ce,d);if(oe!==null)return u||x.opened(d),oe;let de=new Map(Fe.map((he,be)=>[he,W[be]])),ke=u?void 0:`/__gallery/edit/v/${_}/src/editor/page/editor.mjs`,{html:fe,whole:le}=A(r,d,{present:u,editorModule:ke,kit:he=>`${Xe(he)}?v=${de.get(he)}`}),Se=lt(fe,t);return le&&R.set(r,ce,d,Se),Se},Q=async r=>{let d=Vo(r,o),[u,_]=await Promise.all([we.readFile(d.html,"utf8").catch(()=>null),we.readFile(d.json,"utf8").catch(()=>"")]);if(u===null)return null;let[W,O]=await Promise.all([B(),Promise.all(Fe.map(z))]),ce=new Map(Fe.map((F,Oe)=>[F,O[Oe]])),oe=se(),de=Zo(u,_),ke=ln(u,{blockOf:F=>Ot(oe,F)}),fe=Object.fromEntries([...new Set(Et(u).cards.map(({block:F})=>F).filter(Boolean))].map(F=>[F,Ot(oe,F)])),{html:le}=eo(ke,{reportsDirectory:o,slug:r,kit:F=>`${Xe(F)}?v=${ce.get(F)}`}),Se=_s(r,o),he=Cs(r,o),be=Se?.defaultCards===!0,ze=Es(u),Ge=F=>oe.packages.get(F)?.name??en().find(Oe=>Oe.id===F)?.title??null,Ee=be?bs(o,Et(u).cards.map(({block:F})=>F)).map(F=>({block:F,name:Ge(F)})):[],De=JSON.stringify({slug:r,title:Se?.title??r,token:x.token,version:de,blocks:fe,...he?{hint:he}:{},...be?{defaults:be}:{},...Ee.length?{news:Ee}:{},...ze?{blank:ze}:{}}).replace(/</g,"\\u003c");return le=ue(le,"head",`<script type="application/json" data-ge-page data-doc-dev>${De}</script>`),le=ue(le,"head",zs(r,de,oe.stamp)),le=ue(le,"head",`<script data-doc-dev>${Bo()}</script>`),le=ue(le,"head",ta),ue(le,"head",`<script type="module" src="/__gallery/edit/v/${W}/src/editor/page/custom-page.mjs" data-doc-dev></script>`)};async function q(r,d,u){try{if(!Us(r))return Ho(d,403,{ok:!1,reason:"host"});let _=Hs(r);if(_)return zt(d,{status:302,headers:{Location:_,...Ue}});let W=new URL(r.url||"/","http://localhost"),O=decodeURI(W.pathname);if(O===Gt){d.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-store",Connection:"keep-alive"}),d.write(`retry: 3000
158
+
159
+ `);let F={slug:W.searchParams.get("slug"),page:W.searchParams.get("page"),workspace:W.searchParams.has("workspace"),response:d};n.add(F);let{stamp:Oe,settings:$a}=se();d.write(`data: components ${Oe}
160
+
161
+ `),d.write(`data: ${St($a)}
162
+
163
+ `),r.on("close",()=>n.delete(F));return}if(O==="/__gallery/net")return g.handle(r,d);if(O==="/__gallery/edit/commit")return x.commit(r,d);if(O==="/__gallery/edit/reverted")return x.reverted(r,d);if(O==="/__gallery/edit/hand-in")return x.handInRequest(r,d);if(O==="/__gallery/edit/settle")return x.settleRequest(r,d);if(O==="/__gallery/edit/round")return x.roundRequest(r,d);if(O==="/__gallery/edit/upload")return x.upload(r,d);if(O==="/__gallery/edit/unfurl")return x.unfurl(r,d);if(O==="/__gallery/edit/emoji-library"){if(r.method==="POST")return x.addEmoji(r,d);let[F,Oe]=await x.listEmojis();return Ho(d,F,Oe)}if(O==="/__gallery/edit/icon"){let F=gn({value:W.searchParams.get("value")??"",slug:W.searchParams.get("slug"),tab:W.searchParams.has("tab")});return Ie(d,F?.body,{type:F?.type,headers:{"Cache-Control":"max-age=31536000, immutable"}})}if(await Co(O,d,{reportsDirectory:o})||await _o(O,d,{reportsDirectory:o})||await go(O,W.searchParams.get("v"),d,{root:Te()}))return;let ce=O.match(/^\/__gallery\/edit\/emoji-library\/([^/]+)$/)?.[1];if(ce){let F=await x.readEmoji(ce);return Ie(d,F?.body,{type:F?.type,headers:{"Cache-Control":"no-cache"}})}if(O==="/__gallery/edit/frameable")return x.frameable(r,d);if(O==="/__gallery/edit/annotations")return x.annotations(r,d);if(O==="/__gallery/edit/changes")return x.changes(r,d);let oe=O.match(/^\/__gallery\/transfer\/([a-z]+)$/)?.[1];if(oe)return Z.handle(r,d,oe);let[,de,ke]=O.match(Ns)??[];if(de)return y.handle(r,d,de,ke);let fe=O.match(/^\/__gallery\/workspace\/([a-z]+(?:-[a-z]+)*)$/)?.[1];if(fe)return G.handle(r,d,fe);let[,le,Se]=O.match(ra)??[];if(Se){let F=await we.readFile(X.join(Re,Se),"utf8").catch(()=>null);return Ie(d,F,{type:"text/javascript; charset=utf-8",headers:le?qo:Ue})}let he=W.searchParams.has("v")&&Fe.find(F=>Xe(F)===O);if(he){let F=await we.readFile(Ct(he)).catch(()=>null);return Ie(d,F,{type:O.endsWith(".css")?"text/css; charset=utf-8":"text/javascript; charset=utf-8",headers:qo})}if(O==="/__gallery/edit/mhchem.js"){let F=await we.readFile(wn).catch(()=>null);return Ie(d,F,{type:"text/javascript; charset=utf-8",headers:Ue})}let[,be,ze]=O.match(Ds)??[];if(be){let F=await we.readFile(X.join(Re,be)).catch(()=>null);return Ie(d,F,{type:ze==="json"?"application/json; charset=utf-8":"application/octet-stream",headers:{"Cache-Control":"max-age=86400"}})}if(k&&(O==="/"||O==="/index.html"))return Bt(d,"text/html; charset=utf-8",await k(W.pathname,r));let Ge=O.match(Is)?.[1];if(Ge){let F=await Q(Ge);return F===null?u():Bt(d,"text/html; charset=utf-8",lt(F,t))}let Ee=O.match(Ls)?.[1];if(!Ee){let F=O.match(As)?.[1];return aa(F)&&await we.access($s(ft(F,o)).html).then(()=>!0,()=>!1)?zt(d,{status:302,headers:{Location:`${t}/generated/${F}.html${W.search}`,...Ue}}):u()}let De=await x.readTaken(Ee);if(De===null)return u();W.searchParams.has("present")||x.noteTaken(Ee,De.source).then(F=>F&&M(Ee),()=>{}),Bt(d,"text/html; charset=utf-8",await H(Ee,De.text,{present:W.searchParams.has("present")}))}catch(_){u(_)}}let te=new Map,K=(r,d)=>{clearTimeout(te.get(r)),te.set(r,setTimeout(d,120))},D=r=>{ys(r,o).reads&&c(r,zo(Go(r,o)),"look")},Y=uo({settled:x.settled,async tell(r,d){let u=await x.read(r,d.source).catch(_=>(l.error(`[gallery] ${r}: ${_.message}`),{version:We(d.source??"")}));if(c(r,u?.version??We("")),E(r)){let _=x.writerOf(r,d.source)??"agent";w.changed(r,{source:d.source??null,text:u?.text??null,by:_}).then(L,W=>l.error(`[gallery] ${r}: its facts not read: ${W.message}`))}x.noteTaken(r,d.source).then(_=>_&&M(r),_=>l.error(`[gallery] ${r}: the Agent's changes not kept: ${_.message}`)),x.checkAnnotations(r).catch(_=>l.error(`[gallery] ${r}: annotations not checked: ${_.message}`))}}),re=({id:r,problem:d,off:u})=>u||l.warn(`[gallery] custom block ${r} does not load: ${Yt("en",d)}`),ne=zn({root:Te(),tell({stamp:r,problems:d,settings:u},_){for(let W of _)d.has(W)&&re(d.get(W));for(let{response:W}of n)W.write(`data: components ${r} ${_.filter(O=>ks.test(O)).join(",")}
164
+
165
+ `),W.write(`data: ${St(u)}
166
+
167
+ `)}});for(let r of se().problems.values())re(r);w.start().then(r=>r>0&&L(["activity"]));let ye=It(o),pe=Qo(o).then(r=>r.join("/"),()=>""),kt=!1,vt=r=>{kt||=r===mt,K("extensions",async()=>{let d=kt;kt=!1;let u=await pe;pe=Qo(o).then(_=>_.join("/"),()=>u),(d||await pe!==u)&&h()})},Be=Te(),wa=Me(Be).extensions,ya=t?null:Le(Be,(r,d)=>{if(gs(d,Me(Be).outline)){h();return}let u=X.relative(d,wa);if(r==="reset"||u===""||!u.startsWith("..")&&!X.isAbsolute(u)){vt(mt);return}let _=ea(Be,d);_?.extension&&(_.name===mt||_.name===null)&&vt(_.name)},{extensionsOnly:!0,outline:!0}),xt=(r,d)=>!fs&&d.some(u=>r.startsWith(u+X.sep));function ka(r,d){if(r==="reset"){R.clear(),I.changed(),ne.changed(),h();return}if(ye(d))return;let u=ea(o,d);if(u?.page){let{page:_,name:W}=u;W&&Os(W)&&K(`page:${_}`,async()=>{let O=Vo(_,o),[ce,oe]=await Promise.all([we.readFile(O.html,"utf8").catch(()=>null),we.readFile(O.json,"utf8").catch(()=>"")]);ce!==null&&v(_,Zo(ce,oe))}),(W===Xo.json||W===Xo.html&&/^(add|unlink)$/.test(r)||W===null&&/^(add|unlink)Dir$/.test(r))&&h();return}if(u?.extension){(u.name===mt||u.name===null)&&vt(u.name);return}if(u?.packages&&ne.changed(),u?.name===ht&&u.slug===null&&K("look:*",()=>new Set([...n].map(({slug:_})=>_).filter(Boolean)).forEach(D)),u?.name===ht&&u.slug===null&&h(),u?.slug&&!(u.name&&Ss(u.name))&&R.forget(u.slug),u&&(/^(doc|report)\.json$/.test(u.name??"")||/^(add|unlink)Dir$/.test(r)&&u.name===null)&&R.clear(),u?.slug&&!u.packages&&u.name===null&&/^(add|unlink)Dir$/.test(r)&&E(u.slug)&&(w.forget(u.slug),L(["todos","recent","stats"])),u?.slug&&!(u.packages&&u.name===null)&&(/^(doc|report)\.json$/.test(u.name??"")||/^(add|unlink)Dir$/.test(r)&&u.name===null||/^(add|unlink)$/.test(r)&&Yo(u.name??""))&&h(),u?.slug&&!u.packages&&u.name===Ps&&h(),/^(add|unlink)(Dir)?$/.test(r)&&xt(d,ut)&&I.changed(),u?.name&&(Yo(u.name)||/^(doc|report)\.json$/.test(u.name))){if(Y(u.slug),/^(doc|report)\.json$/.test(u.name)){let{slug:_}=u;K(`look:${_}`,()=>D(_))}}else if(u?.name==="annotations.json"){let{slug:_}=u;K(`notes:${_}`,async()=>{let W=await we.readFile(d,"utf8").catch(()=>null);c(_,W===null?"":We(W),"notes")})}else xt(d,Ms)?K("kit",async()=>{try{await bn({fresh:!0}),c()}catch(_){l.error(`[gallery] shared kit rebuild failed: ${_.message}`)}}):xt(d,ut)&&K("editor",()=>c())}async function va(r){m&&(U=await ps({home:o,port:r,token:x.token,kind:p})),await ws(o)}async function xa(){for(let r of n)r.response.end();n.clear(),ya?.close();for(let r of te.values())clearTimeout(r);ne.close(),await C?.close(),await U?.().catch(()=>{}),U=null,await Z.close(),await x.drain()}return{handle:q,changed:ka,listening:va,close:xa,stop:T,edits:x,workspace:G,transfer:Z,refresh:P,get listeners(){return n.size},get workbenchListeners(){return[...n].filter(r=>r.workspace).length}}}import{forgetSnapshot as Ks,idsOf as Jt}from"../browser/shared/workspace-columns.mjs";import{isWorkspace as la,readRegistry as Js,registryFile as da,workspaceId as Ys,workspaceKey as He}from"../browser/shared/workspace-registry.mjs";import{layoutOf as Xs}from"../browser/shared/workspace.mjs";import{projectBase as fa,projectOfPath as Vs,localPath as Zs}from"../browser/shared/workspace-address.mjs";import{sendJson as ma}from"../browser/shared/http.mjs";function ua({reportsDirectory:e,watch:a=!0,...t}){let o=Rn(Gs().data),i=new Map,f=new Map,s=new Map,m=!1,l=He(e),p=w=>{Ks(w);for(let j of i.values())j.refresh()},k=new Map,S=new Map,b={touch:w=>{let j=Jt();for(let L of w.values())v(L,j).catch(E=>t.logger?.warn?.(`[gallery] ${E.message}`))},indexOf:async w=>(await v(w))?.workspace.index??null},n=Kt({...t,token:o,reportsDirectory:e,unified:!0,projects:b,onWorkspaceChange:p,closeServer:async()=>{await $(),await t.closeServer?.()}}),c=Qn({edits:n.edits});n.base="",i.set(l,n);async function v(w,j=null){if(m)return null;let L=Ys(w),E=He(w);if(E!==l){let U=(j??Jt()).get(L);if(!la(w)||U?.length!==1||He(U[0])!==E)return null}return k.set(E,Date.now()),i.has(E)?i.get(E):(f.has(E)||f.set(E,(async()=>{let U=Kt({...t,token:o,reportsDirectory:w,stateDirectory:Xs(w).state,base:fa(L),projects:b,onWorkspaceChange:p,announceServer:!1,workbenchPage:null});return U.base=fa(L),m?(await U.close(),null):(i.set(E,U),a&&s.set(E,Le(w,U.changed)),U)})().finally(()=>f.delete(E))),f.get(E))}let P=null;function h(){return m?Promise.resolve():P??=(async()=>{let w=Js().workspaces.map(({root:L})=>L),j=new Set([l,...w.filter(la).map(L=>He(L))]);for(let[L,E]of i)j.has(L)||(i.delete(L),s.get(L)?.close(),s.delete(L),await E.close())})().catch(w=>t.logger?.warn?.(`[gallery] ${w.message}`)).finally(()=>{P=null})}async function M(w,j,L){try{if(m)return ma(j,503,{ok:!1,reason:"closing"});let E=new URL(w.url??"/","http://localhost");if(await c.handle(w,j))return;let U=Vs(E.pathname);if(!U)return n.handle(w,j,L);let J=Jt(),T=J.get(U),G=T?.length===1?await v(T[0],J):null;if(!G)return ma(j,404,{ok:!1,reason:"workspace"});let Z=Zs(E.pathname);if(G===n||/^\/pages(?:\/|$)|^\/__gallery\/(?:pages?|components|net)(?:\/|$)|^\/__gallery\/workspace\/(?:stop|head|new-page|instructions|extension-edit|components)(?:\/|$)/.test(Z)){j.writeHead(307,{Location:Z+E.search}),j.end();return}let y=He(T[0]);return S.set(y,(S.get(y)??0)+1),j.once("close",()=>{S.set(y,S.get(y)-1),k.set(y,Date.now())}),w.url=Z+E.search,G.handle(w,j,A=>{w.url=E.pathname+E.search,L(A)})}catch(E){L(E)}}let x=setInterval(()=>{for(let[w,j]of i)w!==l&&!n.workbenchListeners&&!S.get(w)&&!j.listeners&&Date.now()-k.get(w)>12e4&&(i.delete(w),s.get(w)?.close(),s.delete(w),k.delete(w),S.delete(w),j.close().catch(L=>t.logger?.warn?.(`[gallery] ${L.message}`)))},3e4);x.unref();async function $(){if(!m){m=!0,clearInterval(x),ca.unwatchFile(da(),C),await c.close();for(let w of s.values())w?.close();await Promise.all([...f.values()]),await Promise.all([...i.values()].map(w=>w.close())),i.clear()}}let C=()=>{p(e),h()};return{handle:M,resolve:v,edits:n.edits,workspace:n.workspace,stop:n.stop,changed(w,j){for(let L of i.values())L.changed(w,j)},async listening(w){await n.listening(w),await h(),ca.watchFile(da(),{interval:500,persistent:!1},C)},close:$}}import Qs from"node:fs/promises";import Ne from"node:path";import{FRAMED_BY as qs,serve as pa}from"../browser/shared/http.mjs";var ei={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff",".ttf":"font/ttf",".txt":"text/plain; charset=utf-8"},ti=e=>ei[Ne.extname(e).toLowerCase()]??"application/octet-stream";function ni(e,a){if(/%(?:2f|5c|00)/i.test(a)||/[\\\0]/.test(a))return null;let t;try{t=decodeURIComponent(a)}catch{return null}let o=t.split("/");if(o.some(s=>s===""||s==="."||s===".."||/[\\\0:]/.test(s)))return null;let i=Ne.resolve(e,...o),f=Ne.relative(e,i);return f&&!f.startsWith("..")&&!Ne.isAbsolute(f)?i:null}async function ha(e,a,{web:t,kit:o,vendor:i}){if(e.method!=="GET"&&e.method!=="HEAD")return!1;let f=new URL(e.url||"/","http://localhost").pathname,s=null,m=null;if(f==="/"||f==="/index.html"){if(!t)return!1;[s,m]=[Ne.join(t,"index.html"),{"Cache-Control":"no-store",...qs}]}else{let k=[["/assets/",t&&Ne.join(t,"assets"),"max-age=31536000, immutable"],["/kit/",o,"no-cache"],["/vendor/",i,"no-cache"]].find(([S,b])=>b&&f.startsWith(S));if(!k)return!1;s=ni(k[1],f.slice(k[0].length)),m={"Cache-Control":k[2]}}let l=s?await Qs.readFile(s).catch(()=>null):null;return l?(pa(a,{type:ti(s),headers:{...m,"X-Content-Type-Options":"nosniff"},body:e.method==="HEAD"?void 0:l}),!0):(pa(a,{status:404}),!0)}async function qd({reportsDirectory:e=di(),port:a,web:t=ci,kind:o=process.env.GALLERY_SERVER_KIND==="dev"?"dev":"cli",stateDirectory:i=mi(e).state,exit:f=(p=0)=>process.exit(p),watch:s=!0,signals:m=!0,log:l=console}={}){await fi(e),await cn(e,{log:h=>l.log(`[gallery] ${new Date().toISOString()} ${h}`)}),rn(e,h=>l.log(`[gallery] ${new Date().toISOString()} ${h}`)),an(e);let p=await fn(e,{stateDirectory:i});p.did==="made"?l.log(`[gallery] ${new Date().toISOString()} the default home page made: ${p.file} (${p.cards.length} cards)`):p.did==="failed"&&l.warn(`[gallery] ${new Date().toISOString()} ${mn(p)}`);let k=null,S=null,b=null,n=li(),c=async()=>{S?.close(),b&&wt.unwatchFile(yt,b),await oi.writeFile(n.lastPortFile,`${a}
168
+ `).catch(()=>{}),await new Promise(h=>{k.close(()=>h()),k.closeAllConnections()})},P=ua({reportsDirectory:e,watch:s,stateDirectory:i,logger:{info:h=>l.log(h),warn:h=>l.warn(h),error:h=>l.error(h)},kind:o,closeServer:c,exit:()=>f(0)});k=ai.createServer((h,M)=>{P.handle(h,M,async x=>{if(x){l.error(`[gallery] ${h.method} ${h.url}: ${x.stack??x.message}`),M.headersSent?M.end():ga(M,{status:500});return}try{if(await ha(h,M,{web:t,kit:ri,vendor:ii}))return}catch($){l.error(`[gallery] ${h.url}: ${$.message}`)}M.headersSent||ga(M,{status:404})})}),k.keepAliveTimeout=5e3,await new Promise((h,M)=>{k.once("error",M),k.listen(a,"127.0.0.1",()=>{k.off("error",M),h()})}),a=k.address().port;try{await P.listening(a)}catch(h){throw await c(),await P.close(),h}if(s&&(S=Le(e,P.changed)),si){let h=wt.readFileSync(yt,"utf8");b=()=>{let M=null;try{M=wt.readFileSync(yt,"utf8")}catch{}M!==h&&(l.log("[gallery] The package was replaced (another version installed): this server stops; the next gallery command starts the new one."),P.stop())},wt.watchFile(yt,{interval:3e3,persistent:!1},b)}if(m)for(let h of["SIGINT","SIGTERM","SIGHUP"])process.once(h,()=>P.stop());return{server:k,port:a,routes:P,async close(){await c(),await P.close()}}}export{qd as a};
@@ -1,3 +1,3 @@
1
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{k as u}from"./chunk-PLB7L22J.mjs";import n from"node:fs/promises";import d from"node:path";import{writeAtomic as h}from"../browser/shared/files.mjs";import{documentFiles as A}from"../browser/shared/workspace.mjs";var I=s=>n.access(s).then(()=>!0,()=>!1);async function q(s,{create:y,slugOf:F,folderOf:j,fill:p,place:x,under:N="",said:J="\u5BFC\u5165\u81EA {0}",lang:O=null}){let e=[],c=[];async function f(t,r,S){let i=await F(t,S);await y(i,t.title,J.replace("{0}",()=>t.from),{lang:O});let a=j(i),{html:l,json:m}=A(a),k=await n.readFile(l,"utf8");await h(l,u(await p({source:k,nodes:t.nodes,icon:t.icon,own:t.own,raws:t.raws,lang:t.lang}))),t.files.length&&await n.mkdir(d.join(a,"assets"),{recursive:!0});for(let{from:o,name:v}of t.files){let w=d.join(a,"assets",v);await I(w)||await n.copyFile(o,w)}if(t.icon){let o=JSON.parse(await n.readFile(m,"utf8"));await h(m,`${JSON.stringify({...o,icon:t.icon},null,2)}
2
+ import{k as u}from"./chunk-FJLM7YE7.mjs";import n from"node:fs/promises";import d from"node:path";import{writeAtomic as h}from"../browser/shared/files.mjs";import{documentFiles as A}from"../browser/shared/workspace.mjs";var I=s=>n.access(s).then(()=>!0,()=>!1);async function q(s,{create:y,slugOf:F,folderOf:j,fill:p,place:x,under:N="",said:J="\u5BFC\u5165\u81EA {0}",lang:O=null}){let e=[],c=[];async function f(t,r,S){let i=await F(t,S);await y(i,t.title,J.replace("{0}",()=>t.from),{lang:O});let a=j(i),{html:l,json:m}=A(a),k=await n.readFile(l,"utf8");await h(l,u(await p({source:k,nodes:t.nodes,icon:t.icon,own:t.own,raws:t.raws,lang:t.lang}))),t.files.length&&await n.mkdir(d.join(a,"assets"),{recursive:!0});for(let{from:o,name:v}of t.files){let w=d.join(a,"assets",v);await I(w)||await n.copyFile(o,w)}if(t.icon){let o=JSON.parse(await n.readFile(m,"utf8"));await h(m,`${JSON.stringify({...o,icon:t.icon},null,2)}
3
3
  `)}await x(i,r),e.push(i);for(let o of t.children??[])await f(o,i,null);return i}for(let[t,r]of s.entries())c.push(await f(r,N,t));return{made:e,top:c}}export{q as a};
@@ -1,2 +1,2 @@
1
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-BLNQUR5R.mjs";import"./chunk-6GV3CBB2.mjs";import"./chunk-DR73Y2UJ.mjs";import"./chunk-M4NRDYI5.mjs";import"./chunk-PUOQ65NC.mjs";import"./chunk-6QWQXHAV.mjs";import"./chunk-6Q7ASAXJ.mjs";import"./chunk-S3SX3COT.mjs";import"./chunk-GJJRBGMY.mjs";import"./chunk-JPG2LBQM.mjs";import"./chunk-ALZ6ZENZ.mjs";import"./chunk-IA4PSIMD.mjs";import"./chunk-2OHANJ6Q.mjs";import"./chunk-F4ZA6JRZ.mjs";import"./chunk-7M2BQQGZ.mjs";import"./chunk-6NLXUKAY.mjs";import"./chunk-VRPVVMRB.mjs";import"./chunk-4B2TB5K2.mjs";import"./chunk-KLQP46Y3.mjs";import"./chunk-USIHBCSW.mjs";import"./chunk-3SKOU6OZ.mjs";import"./chunk-ZTHICSSF.mjs";import"./chunk-PLB7L22J.mjs";import"./chunk-PAREWQGB.mjs";import"./chunk-BFJGHSQN.mjs";import"./chunk-U5XL7D6A.mjs";import"./chunk-HYMEEXKN.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-W5NPH5UA.mjs";import"./chunk-ECZBLQKK.mjs";import"./chunk-E7656LR7.mjs";import"./chunk-TKWEX4FD.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";export{a as startProductionServer};
2
+ import{a}from"./chunk-IS7N3N6Q.mjs";import"./chunk-6GV3CBB2.mjs";import"./chunk-DR73Y2UJ.mjs";import"./chunk-M4NRDYI5.mjs";import"./chunk-PUOQ65NC.mjs";import"./chunk-6QWQXHAV.mjs";import"./chunk-ZLS2FRS6.mjs";import"./chunk-S3SX3COT.mjs";import"./chunk-JJNHKGTD.mjs";import"./chunk-JPG2LBQM.mjs";import"./chunk-ALZ6ZENZ.mjs";import"./chunk-IA4PSIMD.mjs";import"./chunk-2OHANJ6Q.mjs";import"./chunk-F4ZA6JRZ.mjs";import"./chunk-7M2BQQGZ.mjs";import"./chunk-6NLXUKAY.mjs";import"./chunk-VRPVVMRB.mjs";import"./chunk-4B2TB5K2.mjs";import"./chunk-KLQP46Y3.mjs";import"./chunk-BX5AKINW.mjs";import"./chunk-HX4DLE3J.mjs";import"./chunk-ZTHICSSF.mjs";import"./chunk-FJLM7YE7.mjs";import"./chunk-PAREWQGB.mjs";import"./chunk-BFJGHSQN.mjs";import"./chunk-U5XL7D6A.mjs";import"./chunk-HYMEEXKN.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-W5NPH5UA.mjs";import"./chunk-ECZBLQKK.mjs";import"./chunk-E7656LR7.mjs";import"./chunk-TKWEX4FD.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";export{a as startProductionServer};
@@ -1,4 +1,4 @@
1
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-7UZUQQ7Q.mjs";import{readFileSync as E,realpathSync as S}from"node:fs";import p from"node:path";import{fileURLToPath as $}from"node:url";var j=p.dirname($(import.meta.url));function v(r=j){for(let o=r;;o=p.dirname(o)){try{let n=JSON.parse(E(p.join(o,"package.json"),"utf8"));if(n.name==="@heycys/gallery")return n.version}catch{}if(p.dirname(o)===o)return"0.0.0"}}var x={init:()=>import("./chunk-VZ2RQ3AM.mjs"),new:()=>import("./chunk-Q4MS6OFC.mjs"),import:()=>import("./chunk-65NTKF4N.mjs"),open:()=>import("./chunk-MNWJ4EZY.mjs"),serve:()=>import("./chunk-53XDTHTG.mjs"),stop:()=>import("./chunk-QVGOPHOF.mjs"),check:()=>import("./chunk-BMX3VUHY.mjs"),export:()=>import("./chunk-E4IHAIJ7.mjs"),qa:()=>import("./chunk-VPMRP2TL.mjs"),list:()=>import("./chunk-QNECWMGR.mjs"),workspaces:()=>import("./chunk-ERE2BXYV.mjs"),move:()=>import("./chunk-GKOBB6DH.mjs"),set:()=>import("./chunk-7EFHNQ5B.mjs"),link:()=>import("./chunk-LMUZQK5O.mjs"),extension:()=>import("./chunk-6XD6U3QA.mjs"),block:()=>import("./chunk-OEIJLMPI.mjs"),page:()=>import("./chunk-2T4PZQEP.mjs"),skill:()=>import("./chunk-JXXHAXYH.mjs")},N=new Set(["stop","init","skill","workspaces"]),A=(r,o)=>`${r.split(`
2
+ import{a as w,b as k,c as f,g as u}from"./chunk-7UZUQQ7Q.mjs";import{readFileSync as E,realpathSync as S}from"node:fs";import p from"node:path";import{fileURLToPath as $}from"node:url";var j=p.dirname($(import.meta.url));function v(r=j){for(let o=r;;o=p.dirname(o)){try{let n=JSON.parse(E(p.join(o,"package.json"),"utf8"));if(n.name==="@heycys/gallery")return n.version}catch{}if(p.dirname(o)===o)return"0.0.0"}}var x={init:()=>import("./chunk-UTMAY3WK.mjs"),new:()=>import("./chunk-GQJMVSSN.mjs"),import:()=>import("./chunk-FOJ3K5Z3.mjs"),open:()=>import("./chunk-QJAVCTY7.mjs"),serve:()=>import("./chunk-UTF7GBQU.mjs"),stop:()=>import("./chunk-QVGOPHOF.mjs"),check:()=>import("./chunk-G7N7YFVD.mjs"),export:()=>import("./chunk-FQ72LZHB.mjs"),qa:()=>import("./chunk-FNCCVGKX.mjs"),list:()=>import("./chunk-QNECWMGR.mjs"),workspaces:()=>import("./chunk-BYNPEUDS.mjs"),move:()=>import("./chunk-GKOBB6DH.mjs"),set:()=>import("./chunk-7EFHNQ5B.mjs"),link:()=>import("./chunk-LMUZQK5O.mjs"),extension:()=>import("./chunk-6XD6U3QA.mjs"),block:()=>import("./chunk-YFJB534W.mjs"),page:()=>import("./chunk-ONKC4BCC.mjs"),skill:()=>import("./chunk-WD4U6XXT.mjs")},N=new Set(["stop","init","skill","workspaces"]),A=(r,o)=>`${r.split(`
3
3
  `)[0]} (gallery ${o?`${o} --help`:"help"} says more)`,g=r=>/^--.|^-[A-Za-z]/.test(r);function L(r){let o=r.indexOf("--"),n=o===-1?r:r.slice(0,o),h=o===-1?[]:r.slice(o),i=[],a=null;for(let e=0;e<n.length;e++){let s=n[e];if(s==="--workspace"||s.startsWith("--workspace=")){let t=s.includes("=")?s.slice(s.indexOf("=")+1):e+1<n.length&&!g(n[e+1])?n[++e]:"";if(!t)return{error:"--workspace takes a folder: --workspace <dir>",usage:u};if(a!==null&&p.resolve(a)!==p.resolve(t))return{error:`Two workspaces named: ${a} and ${t}.`,usage:u};a=t;continue}i.push(s)}if(i[0]==="--version"||i[0]==="-v"||i[0]==="-V")return i.length===1&&h.length===0?{version:!0}:{error:"--version takes nothing else.",usage:u};if(i.length===0||i[0]==="help"||i[0]==="--help"||i[0]==="-h"){let e=i[0]==="help"?i[1]:void 0;return e===void 0?{help:u}:Object.hasOwn(f,e)?{help:f[e]}:{error:`No such command: ${e} (${w.join(", ")}).`,usage:u}}let[c,...m]=i,l=k[c]??c;if(!Object.hasOwn(x,l))return{error:g(l)?`Unknown option: ${l} (the command comes first: gallery <command> [options]).`:`No such command: ${l} (${w.join(", ")}).`,usage:u};let d=[...m,...h];if(m.some(e=>e==="--help"||e==="-h"))return{help:f[l]};if(l==="init"){let e=new Set(["--from","--name"]),s=[];for(let t=0;t<m.length;t++)e.has(m[t])?t++:g(m[t])||s.push(m[t]);if(s.push(...h.slice(1)),s.length>1)return{error:"Name one folder at most.",usage:f.init,command:l};if(s.length===1){if(a!==null&&p.resolve(a)!==p.resolve(s[0]))return{error:`Two workspaces named: ${s[0]} and --workspace ${a}.`,usage:f.init,command:l};a=s[0]}}return{command:l,argv:d,flag:a}}var G=(r,o)=>`Cannot write the workspace ${r} (${o}): allow Gallery to write there, or pass --workspace <a folder you may write>.`,b=(r,o=!0)=>o?`${p.join(r,"gallery.json")} is not Gallery's (another program's file of that name): pass --workspace <another folder> for Gallery's documents.`:`${p.join(r,"gallery.json")} does not read as JSON: mend the file, or pass --workspace <another folder> for Gallery's documents.`;async function W(r=process.argv.slice(2)){process.stdout.on("error",e=>{throw e.code==="EPIPE"&&process.exit(process.exitCode??0),e});let o=L(r);if(o.version){let e=v();console.log(e);try{let{versionNotes:s}=await import("./chunk-TANZRINB.mjs");for(let t of s(e))console.log(t)}catch{}return}if(o.help)return void console.log(o.help);o.error&&(console.error(`${o.error}
4
4
  ${A(o.usage,o.command)}`),process.exit(2));let{command:n,flag:h}=o,{findWorkspace:i,defaultWorkspace:a}=await import("../browser/shared/workspace.mjs"),c=["page","block","extension"].includes(n)?{root:a(),how:"default"}:i({flag:h});if(process.env.GALLERY_WORKSPACE=c.root,!N.has(n)){let{ensureWorkspace:e}=await import("../browser/shared/workspace.mjs");try{await e(a());let{ours:t,reads:O}=await e(c.root,{state:n!=="init"||c.root===a()});t||(console.error(b(c.root,O)),process.exit(1))}catch(t){if(!t.code)throw t;console.error(G(c.root,t.code)),process.exit(1)}let{registerQuietly:s}=await import("../browser/shared/workspace-registry.mjs");await s(c.root)}let{UsageError:m,usageFailureText:l}=await import("./chunk-GPIWQ4X4.mjs"),d=await x[n]();try{await d.run(o.argv,{command:n,workspace:c.root,how:c.how,version:v()})}catch(e){if(!(e instanceof m))throw e;console.error(l(f[n],e.message,e.synopsis)),process.exit(2)}}var y=r=>{try{return S.native(r)}catch{return null}};process.argv[1]&&y(process.argv[1])===y($(import.meta.url))&&W();export{v as a,L as b,G as c,b as d,W as e};
@@ -1,5 +1,5 @@
1
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 ue,b as we,k as ge,v as $e,w as be}from"./chunk-4KUO7R2M.mjs";import{M as ye}from"./chunk-MKIBJTJZ.mjs";import"./chunk-342HXE3Q.mjs";import"./chunk-2KAVXMKG.mjs";import{c as R,f as ke}from"./chunk-3XZOA7AH.mjs";import"./chunk-XZCFPKGO.mjs";import{a as P}from"./chunk-JEUK3ZO7.mjs";import"./chunk-PUOQ65NC.mjs";import"./chunk-6QWQXHAV.mjs";import"./chunk-6Q7ASAXJ.mjs";import"./chunk-S3SX3COT.mjs";import"./chunk-IA4PSIMD.mjs";import"./chunk-2OHANJ6Q.mjs";import"./chunk-F4ZA6JRZ.mjs";import"./chunk-7M2BQQGZ.mjs";import"./chunk-6NLXUKAY.mjs";import{b as de,h as D}from"./chunk-VRPVVMRB.mjs";import"./chunk-7UZUQQ7Q.mjs";import{n as ie}from"./chunk-KLQP46Y3.mjs";import"./chunk-4OZWXZE5.mjs";import{a as pe,j as fe,s as me}from"./chunk-USIHBCSW.mjs";import{d as re,e as le,i as I,j as ce,k as he}from"./chunk-3SKOU6OZ.mjs";import"./chunk-ZTHICSSF.mjs";import{a as g}from"./chunk-PLB7L22J.mjs";import"./chunk-PAREWQGB.mjs";import"./chunk-BFJGHSQN.mjs";import"./chunk-U5XL7D6A.mjs";import{a as z,c as S}from"./chunk-HYMEEXKN.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-W5NPH5UA.mjs";import"./chunk-ECZBLQKK.mjs";import{c as ae}from"./chunk-E7656LR7.mjs";import{a as F,f as te,h as se,j as U,r as ne,s as oe}from"./chunk-TKWEX4FD.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";import{isUtf8 as Ue}from"node:buffer";import X from"node:fs";import E from"node:path";import{instanceSlots as ze,instancesOf as Y,isInstance as Z,partOf as W}from"../browser/shared/components/index.mjs";import{fewestSyllables as Oe}from"../browser/shared/pinyin.mjs";import{ATTRIBUTE as $,refusedInCopy as De}from"../browser/shared/components/installed.mjs";import{attr as b,elementsOf as Q,walk as A}from"../browser/shared/html-tree.mjs";import{blankedCss as M}from"../browser/shared/css-references.mjs";import{ATTRIBUTE as G,SLOT as Le}from"../browser/shared/components/installed.mjs";var Ae=new Set(["media","supports","container","layer","starting-style"]);function K(e,t){let s=0,o="";for(let n=0;n<e.length;n++){let i=e[n];i==="\\"?n++:o?o=i===o?"":o:i==='"'||i==="'"?o=i:i===")"||i==="]"?s--:(s===0&&t(i,n),(i==="("||i==="[")&&s++)}}function Ce(e){let t=M(e),s=M(e,{strings:!0}),o={children:[]},n=[o],i=0,r=0;for(let a=0;a<t.length;a++){let l=t[a];if(l==="\\")a++;else if(l==="("||l==="[")r++;else if(l===")"||l==="]")r=Math.max(0,r-1);else{if(r>0)continue;if(l==="{"){let c={prelude:s.slice(i,a),start:i,children:[]};n.at(-1).children.push(c),n.push(c),i=a+1}else l==="}"?(n.length>1&&n.pop(),i=a+1):l===";"&&(i=a+1)}}return o.children}function _(e){let t=[],s=0;return K(e,(o,n)=>{o===","&&(t.push({text:e.slice(s,n),start:s}),s=n+1)}),t.push({text:e.slice(s),start:s}),t.filter(({text:o})=>o.trim())}function H(e){let t=[],s=e.trim(),o="",n=0,i=0,r=a=>{(i||a)>n&&t.push({combinator:o,compound:s.slice(n,i||a)}),i=0};return K(s,(a,l)=>{/\s/.test(a)?l===n?n=l+1:i||=l:">+~".includes(a)?(r(l),o=a,n=l+1):i&&(r(l),o=" ",n=l)}),r(s.length),t}function B(e){let t=[],s=-1,o=0,n="";for(let r=0;r<e.length;r++){let a=e[r];a==="\\"?r++:n?n=a===n?"":n:a==='"'||a==="'"?n=a:a==="("?o++:a===")"?o--:a==="["&&o===0?s=r:a==="]"&&o===0&&s>=0&&(t.push(e.slice(s,r+1)),s=-1)}let i=!1;return K(e,r=>{i||=r==="&"}),{attributes:t,nesting:i,scope:/(?:^|[^\w-]):scope\b/.test(e)}}var Ie=e=>new RegExp(`^\\[\\s*${G}\\s*=\\s*(["'])${e.replace(/[/-]/g,"\\$&")}\\1\\s*i?\\s*\\]$`,"i"),Pe=e=>M(e).replace(/\\.|\[[^\]]*\]/g,"").includes("&");function xe(e,t,s,o=!1){let n=H(e),i=({compound:f})=>B(f).attributes.some(h=>t.test(h)),r=({compound:f})=>{let{nesting:h,scope:m}=B(f);return!!s&&(h||m)},a=f=>["+","~"].includes(f?.combinator),l=f=>n.slice(f).some(({combinator:h},m)=>(m+f===0?h||" ":h)===" "),c=n.findLastIndex(f=>i(f)||r(f));if(c<0)return!s||Pe(e)?{why:"outside"}:{why:s==="instance"&&a(n[0])?"beside":null,subject:"inside",deep:o||l(0)};let p=i(n[c])||s==="instance";return{why:p&&a(n[c+1])?"beside":null,subject:p&&c===n.length-1?"instance":"inside",deep:!i(n[c])&&o||l(c+1)}}var Se=e=>e.some(({subject:t})=>t==="instance")?"instance":"inside",Re=new RegExp(`^\\[\\s*${Le}\\s*(?:\\]|=)`,"i"),Fe=e=>_(/\)\s*to\s*\(([^)]*)\)/i.exec(e)?.[1]??"").some(({text:t})=>H(t).length===1&&B(t).attributes.some(s=>Re.test(s))),je=(e,t)=>Ne(e,t).outside;function Ee(e,t,s){if(s.length===0)return[];let o=`slot${s.length===1?"":"s"} ${s.join(" and ")}`;return Ne(e,t).deep.map(({line:n,words:i})=>({line:n,what:`${i} also reaches the blocks in ${o}, the document's: write each step with > or wrap the rules in @scope ([${G}="${t}"]) to ([${Le}])`}))}function Ne(e,t){let s=Ie(t),o=`[${G}="${t}"]`,n=[],i=[],r=(l,c,p)=>{let f=c.replace(/\s+/g," ").trim();n.push({line:S(e,l),what:p==="beside"?`${f} reaches what stands beside the instance: what it styles has to stand in it`:`${f} reaches outside the instance: start it at ${o}`})},a=(l,c,p=!1,f=!1)=>{for(let h of l){let m=h.prelude.length-h.prelude.trimStart().length,u=h.start+m,y=/^@([\w-]+)\s*/.exec(h.prelude.trim());if(y){let d=y[1].toLowerCase();if(Ae.has(d))a(h.children,c,p,f);else if(d==="page")n.push({line:S(e,u),what:"@page reaches the paper of the whole document: an instance has no page of its own"});else if(d==="scope"){let x=/^@scope\s*\(([^)]*)\)/i.exec(h.prelude.trim())?.[1]??"",L=_(x).map(({text:j})=>({...xe(j,s,c),steps:H(j).length}));x&&L.every(({why:j,steps:Te})=>!j&&Te===1)?a(h.children,Se(L),!1,f||Fe(h.prelude.trim())):r(u,h.prelude,"outside")}continue}let k=_(h.prelude).map(({text:d,start:x})=>{let L=xe(d,s,c,p),j=h.start+x+d.length-d.trimStart().length;return L.why?r(j,d,L.why):L.deep&&!f&&!p&&i.push({line:S(e,j),words:d.replace(/\s+/g," ").trim()}),L});k.some(({why:d})=>d)||a(h.children,Se(k),k.some(d=>d.deep),f)}};return a(Ce(e),null),{outside:n,deep:i}}var w="template.html",N="example.html",O="component.json",Me=new Set(["localStorage","sessionStorage"]),_e=/^\S+: (?:line \d+ of )?its (?:kit\.js|style\.css) /,Be=/(?: (?:names a file that )?is not in the document's folder|: it is (?:no file of|not in) the document's .*)$|^external resources are not portable: .*$/,Ge=": an example stands in no document: write a picture as a data: address, or draw it from style.css with a file the manifest's assets name",Ke=e=>e.replace(Be,t=>(t.startsWith("external")?t:"")+Ge),T=(e,t)=>I({folder:e},t);function C(e,t){let s=null;try{s=X.readFileSync(E.join(e,t))}catch{return null}return Ue(s)?null:{file:t,what:"it is not UTF-8: save it as UTF-8 (PowerShell's > writes UTF-16; Set-Content -Encoding utf8 does not)"}}function J(e,t){let s=/^line (\d+): | \(line (\d+)\)/.exec(t);return s?{file:e,line:Number(s[1]??s[2]),what:t.replace(s[0],"")}:{file:e,what:t}}function v(e,t){let s=g.parseJsonText(O,e),o=s.statements[0]?.expression,n=null;for(let i of t.split(".")){let r=o?.properties?.find(({name:a})=>a?.text===i);if(!r)break;n=s.getLineAndCharacterOfPosition(r.getStart(s)).line+1,o=r.initializer}return n}function He(e,{message:t,text:s="",values:o=[]}){let n=/at position (\d+)/.exec(t)?.[1];if(n)return S(e,Number(n));for(let i of[...o.map(String),...s.match(/[a-zA-Z][\w.]*/g)??[]]){let r=v(e,i);if(r)return r}return null}var Je=e=>D(e).map(t=>/^line (\d+): <([^>]+)>: ([\s\S]*)$/.exec(t)).filter(Boolean).map(([,t,s,o])=>({line:Number(t),tag:s,why:o}));function qe(e,{file:t,tree:s,html:o}){let n=[],i=Je(o),r=Object.entries(e.parts).filter(([,c])=>c.edit==="text"),a=Object.entries(e.parts).filter(([,c])=>c.edit==="data"),l=(c,p)=>{let f=!1;return A(c,h=>{f||=h===p}),f};for(let c of Y(s,e))for(let[p,f]of r)for(let h of W(c,f.at)){let m=h.sourceCodeLocation?.startLine,u=Q(h).find(d=>ae.has(d.tagName)),y=i.find(d=>d.line===m&&d.tag===h.tagName),k=a.find(([,d])=>W(c,d.at).some(x=>x===h||l(x,h)||l(h,x)))?.[0];k?n.push({file:t,line:m,what:`the part ${p} (${f.at}) is edited as text, and stands in the part ${k}, edited as data, or around it, which is the component's: the editor leaves it read-only: name elements apart`}):u?n.push({file:t,line:m,what:`the part ${p} (${f.at}) is edited as text and holds a block, its <${u.tagName}> at line ${u.sourceCodeLocation?.startLine}: a text part holds words and marks alone, and the editor would leave this one read-only: write its \`at\` as what holds the words (${f.at} > ${u.tagName}), or give each block a part of its own`}):y&&n.push({file:t,line:m,what:`the part ${p} (${f.at}) is edited as text, and the editor would leave it read-only for what it holds: ${y.why}. A text part holds words and marks alone`})}return n}var ee=new RegExp("\\p{Script=Han}","u"),ve=e=>[...e].filter(t=>ee.test(t)).length,Ve={test:e=>{let t=Oe(e);return t!==null&&t<=8}};function We({name:e,words:t}){let s=ve(e.zh),o=t.split(/\s+/).filter(Boolean);return s===0?ee.test(t)&&!o.some(n=>Ve.test(n)):!o.some(n=>Oe(n.toLowerCase())===s)}function Xe({id:e,folder:t,catalog:s,off:o,parts:n}){let i=s.packages.get(e),r=s.problems.get(e)?.problem,a=T(t,O)??"",l=[];r&&l.push({file:O,line:He(a,r),what:U("en",r)}),i?.template===null&&l.push({file:w,what:`there is none, and it is what "/" puts in a document: with none, no menu offers the block: write one <div ${$}="${e}"> with what a new instance holds`}),l.push(...n);let c=C(t,"writing.md");c&&l.push(c);let p=c||T(t,"writing.md")?.trim()?[]:[{file:"writing.md",what:"there is none, so gallery block show has nothing to say of how to write it"}];i&&We(i)&&p.push({file:O,line:v(a,"words")??v(a,"name.zh"),what:ee.test(i.name.zh)?`no word of words spells its whole name ${i.name.zh} in pinyin as an input method composes it, its ${ve(i.name.zh)} Chinese characters a syllable each in one word (as \u65B9\u6848\u6253\u5206 is fangandafen): "/" finds it while those letters are being composed only by such a word. What is counted is how many syllables a word reads as, not which characters they spell`:'its words are Chinese and none of them is pinyin: "/" goes by the letters an input method is composing, so write the pinyin there (\u770B\u677F kanban)'});let f=(()=>{try{return ie(X.readFileSync(E.join(t,"preview.svg")),e)}catch{return null}})();return f&&p.push({file:"preview.svg",what:`it is Gallery's ${f.id} picture, byte for byte (a block made with --recipe keeps its recipe's drawing, which the menu shows beside this block's name): draw this block's own, or delete preview.svg, which the menu does without`}),o&&p.push({file:"gallery.json",what:"the user turned it off in \u8BBE\u7F6E \u203A \u7EC4\u4EF6\u5217\u8868, which is theirs to change and says nothing of the block: it is checked as if it were on, and the instances of a document show what they hold, read-only, until it is on"}),i&&(l.push(...Ze(i)),p.push(...Ye(i,a))),{title:"manifest",problems:l,notes:p}}function Ye({places:e,parts:t,card:s},o){let n=[];if(e.includes("page"))for(let[i,r]of Object.entries(t))r.edit==="text"&&n.push({file:O,line:v(o,`parts.${i}`),what:`the part ${i} is edited as text, which is read-only on a custom page (no editor runs there): a block whose places hold page keeps what a reader changes there in a data part, with its own field or the card's settings`});else v(o,"card")&&n.push({file:O,line:v(o,"card"),what:`card is for a custom page's board, and its places (${e.join(", ")}) hold no page: nothing reads it`});return n}function Ze(e){if(e.settings.length===0||!e.template)return[];let t=ne(e.template,e.id),s=t?W(t.root,e.parts[F].at):[];if(s.length!==1||(b(s[0],"type")??"").trim().toLowerCase()!=="application/json")return[{file:w,what:`its manifest has settings, and the template holds ${s.length===1?`a <${s[0].tagName}> where`:`${s.length} elements of`} its settings part (${e.parts[F].at}): it is to hold one <script type="application/json">, the values a new card starts with ({} for each setting's default)`}];let o=s[0].childNodes.map(n=>n.value??"").join("").trim();try{let n=JSON.parse(o||"{}");if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("it is no object");return[]}catch(n){return[{file:w,line:s[0].sourceCodeLocation?.startLine,what:`its settings part is not a JSON object (${n.message}): write {} or the values of some of its settings, by key`}]}}function Qe(e){let t=g.createSourceFile("kit.js",e,g.ScriptTarget.Latest,!0,g.ScriptKind.JS),s=[],o=n=>{let i=g.isCallExpression(n)&&g.isPropertyAccessExpression(n.expression)?n.expression:null;if(i?.name.text==="component"&&/\bDocKit$/.test(i.expression.getText(t))){let[r]=n.arguments,a=r&&g.isObjectLiteralExpression(r)?r.properties.find(c=>c.name?.getText(t)==="id"):null,l=a&&g.isPropertyAssignment(a)&&g.isStringLiteralLike(a.initializer)?a.initializer.text:null;s.push({id:l,at:n.getStart(t)})}g.forEachChild(n,o)};return o(t),s}function et(e){let t="kit.js";if(!e.files.includes("kit.js"))return{title:t,none:"none: a static block"};let s=C(e.folder,t);if(s)return{title:t,stops:!0,problems:[s]};let o=I(e,"kit.js")??"",n=pe(o);if(n)return{title:t,stops:!0,problems:[{file:t,line:n.line,what:`a browser refuses it: ${n.message}`}]};let i=he(e).map(({line:c,what:p})=>({file:t,line:c,what:p})),r=i.length>0;for(let{name:c,at:p}of re(o,Me))i.push({file:t,line:S(o,p),what:`uses ${c}: an instance keeps what a reader chose with context.state`});let a=Qe(o);for(let{id:c,at:p}of a)c!==null&&c!==e.id&&i.push({file:t,line:S(o,p),what:`it registers ${c}, and this block is ${e.id}`});let l=a.length?[]:[{file:t,what:`no DocKit.component({ id: "${e.id}", mount(host, context) { \u2026 } }) is to be read in it, and a script may make that call in ways reading does not tell: running it says whether it starts one`}];for(let{line:c,code:p,message:f,refused:h}of le(o,{assets:e.assets}))(h?i:l).push({file:t,line:c,what:`TS${p}: ${f}`});return{title:t,stops:r,problems:i.sort((c,p)=>(c.line??0)-(p.line??0)),notes:l}}function tt(e){let t="style.css";if(!e.files.includes("style.css"))return{title:t,none:"none"};let s=C(e.folder,t);if(s)return{title:t,stops:!0,problems:[s]};let o=I(e,"style.css")??"",n=ce(e),i=[...je(o,e.id),...n].map(({line:l,what:c})=>({file:t,line:l,what:c})),r=Object.entries(e.parts??{}).filter(([,{edit:l}])=>l==="flow").map(([l])=>l),a=Ee(o,e.id,r).map(({line:l,what:c})=>({file:t,line:l,what:c}));return{title:t,stops:n.length>0,problems:i.sort((l,c)=>l.line-c.line),notes:a}}function st(e,{tree:t}){let s=null;A(t,a=>{s??=a.tagName==="main"?a:null});let o=Q(s??{}),n=(s?.childNodes??[]).some(a=>a.nodeName==="#text"&&a.value.trim()),[i]=o;if(o.length!==1||n||!Z(i)||b(i,$)!==e)return[{file:w,line:i?.sourceCodeLocation?.startLine,what:`a template is one element, a <div ${$}="${e}"> or a <section>, and it holds ${o.length===1&&!n?`<${i.tagName}${b(i,$)?` ${$}="${b(i,$)}"`:""}>`:`${o.length} element${o.length===1?"":"s"}${n?" and words":""}`}`}];let r=[];return A({childNodes:[i]},a=>{b(a,"data-block-id")!==void 0&&r.push({file:w,line:a.sourceCodeLocation?.startLine,what:"it writes a data-block-id, which every instance made of it would repeat: leave it out, Gallery gives a block its id"})}),r}var nt=[[e=>b(e,"data-doc-chart")!==void 0,e=>`a chart (<${e.tagName} data-doc-chart="${b(e,"data-doc-chart")}">)`],[e=>e.tagName==="figure",()=>"a card (<figure>)"],[e=>e.tagName==="caption",()=>"a table's <caption>"],[Z,e=>`an instance of ${b(e,$)}`]];function ot(e,t){let s=null;if(A(z(t),i=>{s??=Z(i)&&b(i,$)===e?i:null}),!s)return[];let o=[],n=(i,r)=>{for(let a of Q(i)){let l=nt.find(([c])=>c(a));l?o.push({file:w,line:a.sourceCodeLocation?.startLine,what:`its slot ${b(r,"data-doc-slot")} holds ${l[1](a)}, which a new block from "/" would not have: a menu makes what a template's slot holds as a paste of it makes blocks, and a paste makes no chart, card, table caption or instance of a block. Keep the template's slots to blocks the page makes (paragraphs, headings, lists, quotes, code, a plain table, a disclosure), and show the rest in example.html`}):n(a.tagName==="template"?a.content:a,r)}};for(let i of ze(s))n(i,i);return o}function it(e,{tree:t}){let s=oe(e);if(!s)return[];let[o]=Y(t,e),n=null;return o&&A({childNodes:[o]},i=>{De(i.tagName,i.attrs)&&(n??=i)}),[{file:w,line:(n??o)?.sourceCodeLocation?.startLine,what:U("en",s)}]}function at(e){return[[w,"component-template"],[N,"component-example"]].flatMap(([t,s])=>{let o=T(e,t);if(o===null||!o.trim()||C(e,t))return[];let n=ge(s,o),{text:i}=de(n);return[{file:t,slug:s,written:n,html:i,tree:z(i)}]})}function rt({id:e,folder:t,found:s,pages:o,parts:n}){let i="template.html and example.html",r=[],a=[];for(let h of[w,N]){let m=C(t,h);m?r.push(m):h===w&&!T(t,h)?.trim()&&s.template!==null?r.push({file:h,what:"it is empty"}):h===N&&!o.some(u=>u.file===h)&&r.push({file:h,what:`there is none or it is empty: write an instance as a writer would fill it, a <div ${$}="${e}">; it is what this check runs`})}let l=o.find(h=>h.file===w);l&&r.push(...st(e,l),...ot(e,l.written));let c=o.find(h=>h.file===N);c&&Y(c.tree,s).length===0&&r.push({file:N,what:`it holds no instance of ${e}: a <div ${$}="${e}">`});let p=o.map(({slug:h,written:m,html:u,file:y})=>({file:y,slug:h,written:m,html:u,directory:E.join(t,h),htmlPath:E.join(t,h,"doc.html"),metadata:{title:h,description:h,type:"component"}})),f=fe(p);for(let h of p){for(let m of f.get(h.slug)??[])_e.test(m)||r.push(J(h.file,Ke(m)));for(let m of me(h))a.push(J(h.file,m));for(let m of D(h.html)){let u=J(h.file,`${m} (read-only in the preview)`);n.some(({file:y,line:k})=>y===u.file&&k===u.line)||a.push(u)}}return l&&!r.some(({file:h})=>h===w)&&r.push(...it(s,l)),{title:i,problems:r,notes:a}}function lt(e,t){let s=te(e,void 0,{on:t}),o=R(e,t);if(!s.packages.has(t)&&!s.problems.has(t))return null;se(e,s);let n=s.packages.has(t)&&s.settings.disabled.includes(t),i=s.packages.get(t)??{id:t,folder:o,files:["kit.js","style.css"].filter(c=>X.existsSync(E.join(o,c)))},r=at(o),a=s.packages.has(t)?null:"its manifest does not load",l=a?[]:r.flatMap(c=>qe(i,c));return{found:s.packages.get(t)??null,pages:r,sections:[Xe({id:t,folder:o,catalog:s,off:n,parts:l}),et(i),tt(i),a?{title:"template.html and example.html",skipped:a}:rt({id:t,folder:o,found:i,pages:r,parts:l})]}}var q=({file:e,line:t})=>t?`${e}:${t}`:e;function V({title:e,problems:t=[],notes:s=[],told:o=[],none:n,skipped:i,unverified:r,pictures:a},l){let c=r?`UNVERIFIED ${r}`:i?`not run: ${i}`:n??(t.length?`${t.length} problem${t.length===1?"":"s"}`:`ok${s.length?`, ${s.length} note${s.length===1?"":"s"}`:""}`);return[`${l}. ${e}: ${c}`,...t.map(p=>` FAIL ${q(p)}: ${p.what}`),...s.map(p=>` note ${q(p)}: ${p.what}`),...o.map(p=>` way back ${q(p)}: ${p.what}`),...a?[ct(a)]:[]]}function ct({folder:e,overviews:t,each:s,edited:o=[],asExport:n=[],documents:i=!1}){let r=t.length?`${P(E.join(e,t[0]))}${t.slice(1).map(c=>` and ${c}`).join("")}, the three widths of each theme side by side; then each at full size: `:`${P(e)}: `,a=n.length===0?"":n.length===o.length?", each the same picture as the export's at its width: the block draws nothing more where a reader can edit":`, ${n.join(" and ")} the same picture as the export's at its width`,l=o.length?`; and ${o.join(" and ")}, as the editing page draws it (context.canEdit() true)${a}`:"";return` Pictures (none looked at for you; ${i?"each instance under a line naming where it stands in the document":"example.html above the line, template.html below it, each under its name"}): ${r}${s.join(", ")}${l}`}function ht([e,t,s,o]){return e.problems.length?"the manifest":t.stops?"kit.js":s.stops?"style.css":o.skipped||o.problems.length?"template.html and example.html":null}async function Ut(e,t,{documents:s=!1}={}){let o=lt(e,t);o||(console.error(ke(e,t)),process.exit(1)),console.log(`${t}: ${P(R(e,t))}`),o.sections.forEach((p,f)=>console.log(V(p,f+1).join(`
2
+ import{a as ue,b as we,k as ge,v as $e,w as be}from"./chunk-LJLVCU6W.mjs";import{M as ye}from"./chunk-XBNFXWAW.mjs";import"./chunk-342HXE3Q.mjs";import"./chunk-T4Y2ZSVX.mjs";import{c as R,f as ke}from"./chunk-V4ZHRALW.mjs";import"./chunk-5GK7HS62.mjs";import{a as P}from"./chunk-JEUK3ZO7.mjs";import"./chunk-PUOQ65NC.mjs";import"./chunk-6QWQXHAV.mjs";import"./chunk-ZLS2FRS6.mjs";import"./chunk-S3SX3COT.mjs";import"./chunk-IA4PSIMD.mjs";import"./chunk-2OHANJ6Q.mjs";import"./chunk-F4ZA6JRZ.mjs";import"./chunk-7M2BQQGZ.mjs";import"./chunk-6NLXUKAY.mjs";import{b as de,h as D}from"./chunk-VRPVVMRB.mjs";import"./chunk-7UZUQQ7Q.mjs";import{n as ie}from"./chunk-KLQP46Y3.mjs";import"./chunk-4OZWXZE5.mjs";import{a as pe,j as fe,s as me}from"./chunk-BX5AKINW.mjs";import{d as re,e as le,i as I,j as ce,k as he}from"./chunk-HX4DLE3J.mjs";import"./chunk-ZTHICSSF.mjs";import{a as g}from"./chunk-FJLM7YE7.mjs";import"./chunk-PAREWQGB.mjs";import"./chunk-BFJGHSQN.mjs";import"./chunk-U5XL7D6A.mjs";import{a as z,c as S}from"./chunk-HYMEEXKN.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-W5NPH5UA.mjs";import"./chunk-ECZBLQKK.mjs";import{c as ae}from"./chunk-E7656LR7.mjs";import{a as F,f as te,h as se,j as U,r as ne,s as oe}from"./chunk-TKWEX4FD.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";import{isUtf8 as Ue}from"node:buffer";import X from"node:fs";import E from"node:path";import{instanceSlots as ze,instancesOf as Y,isInstance as Z,partOf as W}from"../browser/shared/components/index.mjs";import{fewestSyllables as Oe}from"../browser/shared/pinyin.mjs";import{ATTRIBUTE as $,refusedInCopy as De}from"../browser/shared/components/installed.mjs";import{attr as b,elementsOf as Q,walk as A}from"../browser/shared/html-tree.mjs";import{blankedCss as M}from"../browser/shared/css-references.mjs";import{ATTRIBUTE as G,SLOT as Le}from"../browser/shared/components/installed.mjs";var Ae=new Set(["media","supports","container","layer","starting-style"]);function K(e,t){let s=0,o="";for(let n=0;n<e.length;n++){let i=e[n];i==="\\"?n++:o?o=i===o?"":o:i==='"'||i==="'"?o=i:i===")"||i==="]"?s--:(s===0&&t(i,n),(i==="("||i==="[")&&s++)}}function Ce(e){let t=M(e),s=M(e,{strings:!0}),o={children:[]},n=[o],i=0,r=0;for(let a=0;a<t.length;a++){let l=t[a];if(l==="\\")a++;else if(l==="("||l==="[")r++;else if(l===")"||l==="]")r=Math.max(0,r-1);else{if(r>0)continue;if(l==="{"){let c={prelude:s.slice(i,a),start:i,children:[]};n.at(-1).children.push(c),n.push(c),i=a+1}else l==="}"?(n.length>1&&n.pop(),i=a+1):l===";"&&(i=a+1)}}return o.children}function _(e){let t=[],s=0;return K(e,(o,n)=>{o===","&&(t.push({text:e.slice(s,n),start:s}),s=n+1)}),t.push({text:e.slice(s),start:s}),t.filter(({text:o})=>o.trim())}function H(e){let t=[],s=e.trim(),o="",n=0,i=0,r=a=>{(i||a)>n&&t.push({combinator:o,compound:s.slice(n,i||a)}),i=0};return K(s,(a,l)=>{/\s/.test(a)?l===n?n=l+1:i||=l:">+~".includes(a)?(r(l),o=a,n=l+1):i&&(r(l),o=" ",n=l)}),r(s.length),t}function B(e){let t=[],s=-1,o=0,n="";for(let r=0;r<e.length;r++){let a=e[r];a==="\\"?r++:n?n=a===n?"":n:a==='"'||a==="'"?n=a:a==="("?o++:a===")"?o--:a==="["&&o===0?s=r:a==="]"&&o===0&&s>=0&&(t.push(e.slice(s,r+1)),s=-1)}let i=!1;return K(e,r=>{i||=r==="&"}),{attributes:t,nesting:i,scope:/(?:^|[^\w-]):scope\b/.test(e)}}var Ie=e=>new RegExp(`^\\[\\s*${G}\\s*=\\s*(["'])${e.replace(/[/-]/g,"\\$&")}\\1\\s*i?\\s*\\]$`,"i"),Pe=e=>M(e).replace(/\\.|\[[^\]]*\]/g,"").includes("&");function xe(e,t,s,o=!1){let n=H(e),i=({compound:f})=>B(f).attributes.some(h=>t.test(h)),r=({compound:f})=>{let{nesting:h,scope:m}=B(f);return!!s&&(h||m)},a=f=>["+","~"].includes(f?.combinator),l=f=>n.slice(f).some(({combinator:h},m)=>(m+f===0?h||" ":h)===" "),c=n.findLastIndex(f=>i(f)||r(f));if(c<0)return!s||Pe(e)?{why:"outside"}:{why:s==="instance"&&a(n[0])?"beside":null,subject:"inside",deep:o||l(0)};let p=i(n[c])||s==="instance";return{why:p&&a(n[c+1])?"beside":null,subject:p&&c===n.length-1?"instance":"inside",deep:!i(n[c])&&o||l(c+1)}}var Se=e=>e.some(({subject:t})=>t==="instance")?"instance":"inside",Re=new RegExp(`^\\[\\s*${Le}\\s*(?:\\]|=)`,"i"),Fe=e=>_(/\)\s*to\s*\(([^)]*)\)/i.exec(e)?.[1]??"").some(({text:t})=>H(t).length===1&&B(t).attributes.some(s=>Re.test(s))),je=(e,t)=>Ne(e,t).outside;function Ee(e,t,s){if(s.length===0)return[];let o=`slot${s.length===1?"":"s"} ${s.join(" and ")}`;return Ne(e,t).deep.map(({line:n,words:i})=>({line:n,what:`${i} also reaches the blocks in ${o}, the document's: write each step with > or wrap the rules in @scope ([${G}="${t}"]) to ([${Le}])`}))}function Ne(e,t){let s=Ie(t),o=`[${G}="${t}"]`,n=[],i=[],r=(l,c,p)=>{let f=c.replace(/\s+/g," ").trim();n.push({line:S(e,l),what:p==="beside"?`${f} reaches what stands beside the instance: what it styles has to stand in it`:`${f} reaches outside the instance: start it at ${o}`})},a=(l,c,p=!1,f=!1)=>{for(let h of l){let m=h.prelude.length-h.prelude.trimStart().length,u=h.start+m,y=/^@([\w-]+)\s*/.exec(h.prelude.trim());if(y){let d=y[1].toLowerCase();if(Ae.has(d))a(h.children,c,p,f);else if(d==="page")n.push({line:S(e,u),what:"@page reaches the paper of the whole document: an instance has no page of its own"});else if(d==="scope"){let x=/^@scope\s*\(([^)]*)\)/i.exec(h.prelude.trim())?.[1]??"",L=_(x).map(({text:j})=>({...xe(j,s,c),steps:H(j).length}));x&&L.every(({why:j,steps:Te})=>!j&&Te===1)?a(h.children,Se(L),!1,f||Fe(h.prelude.trim())):r(u,h.prelude,"outside")}continue}let k=_(h.prelude).map(({text:d,start:x})=>{let L=xe(d,s,c,p),j=h.start+x+d.length-d.trimStart().length;return L.why?r(j,d,L.why):L.deep&&!f&&!p&&i.push({line:S(e,j),words:d.replace(/\s+/g," ").trim()}),L});k.some(({why:d})=>d)||a(h.children,Se(k),k.some(d=>d.deep),f)}};return a(Ce(e),null),{outside:n,deep:i}}var w="template.html",N="example.html",O="component.json",Me=new Set(["localStorage","sessionStorage"]),_e=/^\S+: (?:line \d+ of )?its (?:kit\.js|style\.css) /,Be=/(?: (?:names a file that )?is not in the document's folder|: it is (?:no file of|not in) the document's .*)$|^external resources are not portable: .*$/,Ge=": an example stands in no document: write a picture as a data: address, or draw it from style.css with a file the manifest's assets name",Ke=e=>e.replace(Be,t=>(t.startsWith("external")?t:"")+Ge),T=(e,t)=>I({folder:e},t);function C(e,t){let s=null;try{s=X.readFileSync(E.join(e,t))}catch{return null}return Ue(s)?null:{file:t,what:"it is not UTF-8: save it as UTF-8 (PowerShell's > writes UTF-16; Set-Content -Encoding utf8 does not)"}}function J(e,t){let s=/^line (\d+): | \(line (\d+)\)/.exec(t);return s?{file:e,line:Number(s[1]??s[2]),what:t.replace(s[0],"")}:{file:e,what:t}}function v(e,t){let s=g.parseJsonText(O,e),o=s.statements[0]?.expression,n=null;for(let i of t.split(".")){let r=o?.properties?.find(({name:a})=>a?.text===i);if(!r)break;n=s.getLineAndCharacterOfPosition(r.getStart(s)).line+1,o=r.initializer}return n}function He(e,{message:t,text:s="",values:o=[]}){let n=/at position (\d+)/.exec(t)?.[1];if(n)return S(e,Number(n));for(let i of[...o.map(String),...s.match(/[a-zA-Z][\w.]*/g)??[]]){let r=v(e,i);if(r)return r}return null}var Je=e=>D(e).map(t=>/^line (\d+): <([^>]+)>: ([\s\S]*)$/.exec(t)).filter(Boolean).map(([,t,s,o])=>({line:Number(t),tag:s,why:o}));function qe(e,{file:t,tree:s,html:o}){let n=[],i=Je(o),r=Object.entries(e.parts).filter(([,c])=>c.edit==="text"),a=Object.entries(e.parts).filter(([,c])=>c.edit==="data"),l=(c,p)=>{let f=!1;return A(c,h=>{f||=h===p}),f};for(let c of Y(s,e))for(let[p,f]of r)for(let h of W(c,f.at)){let m=h.sourceCodeLocation?.startLine,u=Q(h).find(d=>ae.has(d.tagName)),y=i.find(d=>d.line===m&&d.tag===h.tagName),k=a.find(([,d])=>W(c,d.at).some(x=>x===h||l(x,h)||l(h,x)))?.[0];k?n.push({file:t,line:m,what:`the part ${p} (${f.at}) is edited as text, and stands in the part ${k}, edited as data, or around it, which is the component's: the editor leaves it read-only: name elements apart`}):u?n.push({file:t,line:m,what:`the part ${p} (${f.at}) is edited as text and holds a block, its <${u.tagName}> at line ${u.sourceCodeLocation?.startLine}: a text part holds words and marks alone, and the editor would leave this one read-only: write its \`at\` as what holds the words (${f.at} > ${u.tagName}), or give each block a part of its own`}):y&&n.push({file:t,line:m,what:`the part ${p} (${f.at}) is edited as text, and the editor would leave it read-only for what it holds: ${y.why}. A text part holds words and marks alone`})}return n}var ee=new RegExp("\\p{Script=Han}","u"),ve=e=>[...e].filter(t=>ee.test(t)).length,Ve={test:e=>{let t=Oe(e);return t!==null&&t<=8}};function We({name:e,words:t}){let s=ve(e.zh),o=t.split(/\s+/).filter(Boolean);return s===0?ee.test(t)&&!o.some(n=>Ve.test(n)):!o.some(n=>Oe(n.toLowerCase())===s)}function Xe({id:e,folder:t,catalog:s,off:o,parts:n}){let i=s.packages.get(e),r=s.problems.get(e)?.problem,a=T(t,O)??"",l=[];r&&l.push({file:O,line:He(a,r),what:U("en",r)}),i?.template===null&&l.push({file:w,what:`there is none, and it is what "/" puts in a document: with none, no menu offers the block: write one <div ${$}="${e}"> with what a new instance holds`}),l.push(...n);let c=C(t,"writing.md");c&&l.push(c);let p=c||T(t,"writing.md")?.trim()?[]:[{file:"writing.md",what:"there is none, so gallery block show has nothing to say of how to write it"}];i&&We(i)&&p.push({file:O,line:v(a,"words")??v(a,"name.zh"),what:ee.test(i.name.zh)?`no word of words spells its whole name ${i.name.zh} in pinyin as an input method composes it, its ${ve(i.name.zh)} Chinese characters a syllable each in one word (as \u65B9\u6848\u6253\u5206 is fangandafen): "/" finds it while those letters are being composed only by such a word. What is counted is how many syllables a word reads as, not which characters they spell`:'its words are Chinese and none of them is pinyin: "/" goes by the letters an input method is composing, so write the pinyin there (\u770B\u677F kanban)'});let f=(()=>{try{return ie(X.readFileSync(E.join(t,"preview.svg")),e)}catch{return null}})();return f&&p.push({file:"preview.svg",what:`it is Gallery's ${f.id} picture, byte for byte (a block made with --recipe keeps its recipe's drawing, which the menu shows beside this block's name): draw this block's own, or delete preview.svg, which the menu does without`}),o&&p.push({file:"gallery.json",what:"the user turned it off in \u8BBE\u7F6E \u203A \u7EC4\u4EF6\u5217\u8868, which is theirs to change and says nothing of the block: it is checked as if it were on, and the instances of a document show what they hold, read-only, until it is on"}),i&&(l.push(...Ze(i)),p.push(...Ye(i,a))),{title:"manifest",problems:l,notes:p}}function Ye({places:e,parts:t,card:s},o){let n=[];if(e.includes("page"))for(let[i,r]of Object.entries(t))r.edit==="text"&&n.push({file:O,line:v(o,`parts.${i}`),what:`the part ${i} is edited as text, which is read-only on a custom page (no editor runs there): a block whose places hold page keeps what a reader changes there in a data part, with its own field or the card's settings`});else v(o,"card")&&n.push({file:O,line:v(o,"card"),what:`card is for a custom page's board, and its places (${e.join(", ")}) hold no page: nothing reads it`});return n}function Ze(e){if(e.settings.length===0||!e.template)return[];let t=ne(e.template,e.id),s=t?W(t.root,e.parts[F].at):[];if(s.length!==1||(b(s[0],"type")??"").trim().toLowerCase()!=="application/json")return[{file:w,what:`its manifest has settings, and the template holds ${s.length===1?`a <${s[0].tagName}> where`:`${s.length} elements of`} its settings part (${e.parts[F].at}): it is to hold one <script type="application/json">, the values a new card starts with ({} for each setting's default)`}];let o=s[0].childNodes.map(n=>n.value??"").join("").trim();try{let n=JSON.parse(o||"{}");if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("it is no object");return[]}catch(n){return[{file:w,line:s[0].sourceCodeLocation?.startLine,what:`its settings part is not a JSON object (${n.message}): write {} or the values of some of its settings, by key`}]}}function Qe(e){let t=g.createSourceFile("kit.js",e,g.ScriptTarget.Latest,!0,g.ScriptKind.JS),s=[],o=n=>{let i=g.isCallExpression(n)&&g.isPropertyAccessExpression(n.expression)?n.expression:null;if(i?.name.text==="component"&&/\bDocKit$/.test(i.expression.getText(t))){let[r]=n.arguments,a=r&&g.isObjectLiteralExpression(r)?r.properties.find(c=>c.name?.getText(t)==="id"):null,l=a&&g.isPropertyAssignment(a)&&g.isStringLiteralLike(a.initializer)?a.initializer.text:null;s.push({id:l,at:n.getStart(t)})}g.forEachChild(n,o)};return o(t),s}function et(e){let t="kit.js";if(!e.files.includes("kit.js"))return{title:t,none:"none: a static block"};let s=C(e.folder,t);if(s)return{title:t,stops:!0,problems:[s]};let o=I(e,"kit.js")??"",n=pe(o);if(n)return{title:t,stops:!0,problems:[{file:t,line:n.line,what:`a browser refuses it: ${n.message}`}]};let i=he(e).map(({line:c,what:p})=>({file:t,line:c,what:p})),r=i.length>0;for(let{name:c,at:p}of re(o,Me))i.push({file:t,line:S(o,p),what:`uses ${c}: an instance keeps what a reader chose with context.state`});let a=Qe(o);for(let{id:c,at:p}of a)c!==null&&c!==e.id&&i.push({file:t,line:S(o,p),what:`it registers ${c}, and this block is ${e.id}`});let l=a.length?[]:[{file:t,what:`no DocKit.component({ id: "${e.id}", mount(host, context) { \u2026 } }) is to be read in it, and a script may make that call in ways reading does not tell: running it says whether it starts one`}];for(let{line:c,code:p,message:f,refused:h}of le(o,{assets:e.assets}))(h?i:l).push({file:t,line:c,what:`TS${p}: ${f}`});return{title:t,stops:r,problems:i.sort((c,p)=>(c.line??0)-(p.line??0)),notes:l}}function tt(e){let t="style.css";if(!e.files.includes("style.css"))return{title:t,none:"none"};let s=C(e.folder,t);if(s)return{title:t,stops:!0,problems:[s]};let o=I(e,"style.css")??"",n=ce(e),i=[...je(o,e.id),...n].map(({line:l,what:c})=>({file:t,line:l,what:c})),r=Object.entries(e.parts??{}).filter(([,{edit:l}])=>l==="flow").map(([l])=>l),a=Ee(o,e.id,r).map(({line:l,what:c})=>({file:t,line:l,what:c}));return{title:t,stops:n.length>0,problems:i.sort((l,c)=>l.line-c.line),notes:a}}function st(e,{tree:t}){let s=null;A(t,a=>{s??=a.tagName==="main"?a:null});let o=Q(s??{}),n=(s?.childNodes??[]).some(a=>a.nodeName==="#text"&&a.value.trim()),[i]=o;if(o.length!==1||n||!Z(i)||b(i,$)!==e)return[{file:w,line:i?.sourceCodeLocation?.startLine,what:`a template is one element, a <div ${$}="${e}"> or a <section>, and it holds ${o.length===1&&!n?`<${i.tagName}${b(i,$)?` ${$}="${b(i,$)}"`:""}>`:`${o.length} element${o.length===1?"":"s"}${n?" and words":""}`}`}];let r=[];return A({childNodes:[i]},a=>{b(a,"data-block-id")!==void 0&&r.push({file:w,line:a.sourceCodeLocation?.startLine,what:"it writes a data-block-id, which every instance made of it would repeat: leave it out, Gallery gives a block its id"})}),r}var nt=[[e=>b(e,"data-doc-chart")!==void 0,e=>`a chart (<${e.tagName} data-doc-chart="${b(e,"data-doc-chart")}">)`],[e=>e.tagName==="figure",()=>"a card (<figure>)"],[e=>e.tagName==="caption",()=>"a table's <caption>"],[Z,e=>`an instance of ${b(e,$)}`]];function ot(e,t){let s=null;if(A(z(t),i=>{s??=Z(i)&&b(i,$)===e?i:null}),!s)return[];let o=[],n=(i,r)=>{for(let a of Q(i)){let l=nt.find(([c])=>c(a));l?o.push({file:w,line:a.sourceCodeLocation?.startLine,what:`its slot ${b(r,"data-doc-slot")} holds ${l[1](a)}, which a new block from "/" would not have: a menu makes what a template's slot holds as a paste of it makes blocks, and a paste makes no chart, card, table caption or instance of a block. Keep the template's slots to blocks the page makes (paragraphs, headings, lists, quotes, code, a plain table, a disclosure), and show the rest in example.html`}):n(a.tagName==="template"?a.content:a,r)}};for(let i of ze(s))n(i,i);return o}function it(e,{tree:t}){let s=oe(e);if(!s)return[];let[o]=Y(t,e),n=null;return o&&A({childNodes:[o]},i=>{De(i.tagName,i.attrs)&&(n??=i)}),[{file:w,line:(n??o)?.sourceCodeLocation?.startLine,what:U("en",s)}]}function at(e){return[[w,"component-template"],[N,"component-example"]].flatMap(([t,s])=>{let o=T(e,t);if(o===null||!o.trim()||C(e,t))return[];let n=ge(s,o),{text:i}=de(n);return[{file:t,slug:s,written:n,html:i,tree:z(i)}]})}function rt({id:e,folder:t,found:s,pages:o,parts:n}){let i="template.html and example.html",r=[],a=[];for(let h of[w,N]){let m=C(t,h);m?r.push(m):h===w&&!T(t,h)?.trim()&&s.template!==null?r.push({file:h,what:"it is empty"}):h===N&&!o.some(u=>u.file===h)&&r.push({file:h,what:`there is none or it is empty: write an instance as a writer would fill it, a <div ${$}="${e}">; it is what this check runs`})}let l=o.find(h=>h.file===w);l&&r.push(...st(e,l),...ot(e,l.written));let c=o.find(h=>h.file===N);c&&Y(c.tree,s).length===0&&r.push({file:N,what:`it holds no instance of ${e}: a <div ${$}="${e}">`});let p=o.map(({slug:h,written:m,html:u,file:y})=>({file:y,slug:h,written:m,html:u,directory:E.join(t,h),htmlPath:E.join(t,h,"doc.html"),metadata:{title:h,description:h,type:"component"}})),f=fe(p);for(let h of p){for(let m of f.get(h.slug)??[])_e.test(m)||r.push(J(h.file,Ke(m)));for(let m of me(h))a.push(J(h.file,m));for(let m of D(h.html)){let u=J(h.file,`${m} (read-only in the preview)`);n.some(({file:y,line:k})=>y===u.file&&k===u.line)||a.push(u)}}return l&&!r.some(({file:h})=>h===w)&&r.push(...it(s,l)),{title:i,problems:r,notes:a}}function lt(e,t){let s=te(e,void 0,{on:t}),o=R(e,t);if(!s.packages.has(t)&&!s.problems.has(t))return null;se(e,s);let n=s.packages.has(t)&&s.settings.disabled.includes(t),i=s.packages.get(t)??{id:t,folder:o,files:["kit.js","style.css"].filter(c=>X.existsSync(E.join(o,c)))},r=at(o),a=s.packages.has(t)?null:"its manifest does not load",l=a?[]:r.flatMap(c=>qe(i,c));return{found:s.packages.get(t)??null,pages:r,sections:[Xe({id:t,folder:o,catalog:s,off:n,parts:l}),et(i),tt(i),a?{title:"template.html and example.html",skipped:a}:rt({id:t,folder:o,found:i,pages:r,parts:l})]}}var q=({file:e,line:t})=>t?`${e}:${t}`:e;function V({title:e,problems:t=[],notes:s=[],told:o=[],none:n,skipped:i,unverified:r,pictures:a},l){let c=r?`UNVERIFIED ${r}`:i?`not run: ${i}`:n??(t.length?`${t.length} problem${t.length===1?"":"s"}`:`ok${s.length?`, ${s.length} note${s.length===1?"":"s"}`:""}`);return[`${l}. ${e}: ${c}`,...t.map(p=>` FAIL ${q(p)}: ${p.what}`),...s.map(p=>` note ${q(p)}: ${p.what}`),...o.map(p=>` way back ${q(p)}: ${p.what}`),...a?[ct(a)]:[]]}function ct({folder:e,overviews:t,each:s,edited:o=[],asExport:n=[],documents:i=!1}){let r=t.length?`${P(E.join(e,t[0]))}${t.slice(1).map(c=>` and ${c}`).join("")}, the three widths of each theme side by side; then each at full size: `:`${P(e)}: `,a=n.length===0?"":n.length===o.length?", each the same picture as the export's at its width: the block draws nothing more where a reader can edit":`, ${n.join(" and ")} the same picture as the export's at its width`,l=o.length?`; and ${o.join(" and ")}, as the editing page draws it (context.canEdit() true)${a}`:"";return` Pictures (none looked at for you; ${i?"each instance under a line naming where it stands in the document":"example.html above the line, template.html below it, each under its name"}): ${r}${s.join(", ")}${l}`}function ht([e,t,s,o]){return e.problems.length?"the manifest":t.stops?"kit.js":s.stops?"style.css":o.skipped||o.problems.length?"template.html and example.html":null}async function Ut(e,t,{documents:s=!1}={}){let o=lt(e,t);o||(console.error(ke(e,t)),process.exit(1)),console.log(`${t}: ${P(R(e,t))}`),o.sections.forEach((p,f)=>console.log(V(p,f+1).join(`
3
3
  `)));let n=ht(o.sections),i=R(e,t),r=n?{title:ue,skipped:`${n} first`}:await $e(e,o.found,{example:T(i,N),template:T(i,w)});console.log(V(r,5).join(`
4
4
  `));let a=s?n?[{title:we(),skipped:`${n} first`}]:await be(e,o.found):[];a.forEach((p,f)=>console.log(V(p,6+f).join(`
5
5
  `)));let l=ye([r,...a].filter(({pictures:p})=>p).map(({pictures:{folder:p,overviews:f,each:h,edited:m=[]}})=>({folder:p,files:[...f,...h,...m].map(u=>E.join(p,u))})));l&&console.log(l);let c=[...o.sections,r,...a].reduce((p,{problems:f=[]})=>p+f.length,0);c?(console.log(`FAIL ${t}: ${c} problem${c===1?"":"s"}`),process.exitCode=1):r.unverified||a.some(({unverified:p})=>p)?(console.log(`UNVERIFIED ${t}: the rest passed, and no browser ran ${r.unverified?"it":"the documents' instances"}: export a document that holds it and open that in Chrome or Edge.`),process.exitCode=3):console.log(`OK ${t}${s?" and its instances in the workspace's documents":""}`)}export{Ut as checkCommand,Oe as fewestSyllables,lt as readSections,V as sectionLines,We as wantsPinyin};
@@ -1,5 +1,5 @@
1
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 Te}from"./chunk-JEUK3ZO7.mjs";import{a as Ne,b as Oe,c as Xe,d as Ze,g as Ae,h as et}from"./chunk-PUOQ65NC.mjs";import{g as Qe}from"./chunk-6NLXUKAY.mjs";import{b as je}from"./chunk-VRPVVMRB.mjs";import{p as Se}from"./chunk-USIHBCSW.mjs";import{a as ce}from"./chunk-HYMEEXKN.mjs";import{a as Ee,f as le,p as ze}from"./chunk-TKWEX4FD.mjs";import T from"node:fs/promises";import pe from"node:os";import x from"node:path";import{pathToFileURL as De}from"node:url";import{instancesOf as ot,isInstance as bt}from"../browser/shared/components/index.mjs";import{ATTRIBUTE as $t,FALLBACK as xt,INSTANCE as he,SLOT as vt,SLOT_PART as tt}from"../browser/shared/components/installed.mjs";import{jsonIn as Et}from"../browser/shared/json-layout.mjs";import{QUERY_ROUTE as St}from"../browser/shared/workspace-query.mjs";import{documentDirectory as jt,documentFiles as Tt,layoutOf as it,listDocumentSlugs as Nt,PACKAGE_MANIFEST as Ot}from"../browser/shared/workspace.mjs";var At="in a browser, under the export's policy",de=(e=null)=>e?`the instances in ${e}, in a browser under the export's policy`:"the workspace's documents",q="component-check",ae=[360,736,1024],Le=["light","dark"],Lt=[1024,360],nt=1e4,rt=6e4,se=3e4,Dn=12e4,lt=2e3,Rt=3e3,Dt=60,Mn=15e3,Mt=2,Pt=8,Ct=se/2,_t=/^(?:wasm-)?eval$/,It=new Set(["TargetCloseError","ConnectionClosedError"]),Pn=e=>e.evaluateOnNewDocument(Ft,St);function Ft(e){let t=globalThis.fetch;if(typeof t!="function"||globalThis.__galleryQueries)return;let i={pending:new Map,count:0};globalThis.__galleryQueries=i,globalThis.fetch=function(r,n){let a=t.apply(this,arguments);try{let p=new URL(typeof r=="string"?r:r?.url??String(r),location.href);if(p.pathname===e){let u=++i.count,w=/\/__gallery\/components\/([a-z0-9-]+\/[a-z0-9-]+)\/kit\.js/.exec(new Error().stack??"");i.pending.set(u,{kind:p.searchParams.get("kind"),block:w?w[1]:null,at:Date.now()});let l=()=>{i.pending.delete(u)};Promise.resolve(a).then(l,l)}}catch{}return a}}var oe=e=>String(e?.message??e).split(`
2
+ import{a as Te}from"./chunk-JEUK3ZO7.mjs";import{a as Ne,b as Oe,c as Xe,d as Ze,g as Ae,h as et}from"./chunk-PUOQ65NC.mjs";import{g as Qe}from"./chunk-6NLXUKAY.mjs";import{b as je}from"./chunk-VRPVVMRB.mjs";import{p as Se}from"./chunk-BX5AKINW.mjs";import{a as ce}from"./chunk-HYMEEXKN.mjs";import{a as Ee,f as le,p as ze}from"./chunk-TKWEX4FD.mjs";import T from"node:fs/promises";import pe from"node:os";import x from"node:path";import{pathToFileURL as De}from"node:url";import{instancesOf as ot,isInstance as bt}from"../browser/shared/components/index.mjs";import{ATTRIBUTE as $t,FALLBACK as xt,INSTANCE as he,SLOT as vt,SLOT_PART as tt}from"../browser/shared/components/installed.mjs";import{jsonIn as Et}from"../browser/shared/json-layout.mjs";import{QUERY_ROUTE as St}from"../browser/shared/workspace-query.mjs";import{documentDirectory as jt,documentFiles as Tt,layoutOf as it,listDocumentSlugs as Nt,PACKAGE_MANIFEST as Ot}from"../browser/shared/workspace.mjs";var At="in a browser, under the export's policy",de=(e=null)=>e?`the instances in ${e}, in a browser under the export's policy`:"the workspace's documents",q="component-check",ae=[360,736,1024],Le=["light","dark"],Lt=[1024,360],nt=1e4,rt=6e4,se=3e4,Dn=12e4,lt=2e3,Rt=3e3,Dt=60,Mn=15e3,Mt=2,Pt=8,Ct=se/2,_t=/^(?:wasm-)?eval$/,It=new Set(["TargetCloseError","ConnectionClosedError"]),Pn=e=>e.evaluateOnNewDocument(Ft,St);function Ft(e){let t=globalThis.fetch;if(typeof t!="function"||globalThis.__galleryQueries)return;let i={pending:new Map,count:0};globalThis.__galleryQueries=i,globalThis.fetch=function(r,n){let a=t.apply(this,arguments);try{let p=new URL(typeof r=="string"?r:r?.url??String(r),location.href);if(p.pathname===e){let u=++i.count,w=/\/__gallery\/components\/([a-z0-9-]+\/[a-z0-9-]+)\/kit\.js/.exec(new Error().stack??"");i.pending.set(u,{kind:p.searchParams.get("kind"),block:w?w[1]:null,at:Date.now()});let l=()=>{i.pending.delete(u)};Promise.resolve(a).then(l,l)}}catch{}return a}}var oe=e=>String(e?.message??e).split(`
3
3
  `)[0],ct=(e,t)=>`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${e}</title></head><body><main class="doc-page" data-doc-id="${e}">${t}
4
4
  </main></body></html>
5
5
  `,Bt=({example:e,template:t})=>`<p>example.html</p>${e}
@@ -1,2 +1,2 @@
1
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 l,d as g}from"./chunk-WFGPMCTZ.mjs";import{j as p,k as d}from"./chunk-4B2TB5K2.mjs";import{u as f}from"./chunk-KLQP46Y3.mjs";import{b as h,f as u}from"./chunk-4OZWXZE5.mjs";import b from"node:fs/promises";import x from"node:path";import{reportsDirectory as j}from"../browser/shared/paths.mjs";import{sameDirectory as i}from"../browser/shared/preview-server.mjs";import{copyOldDocuments as v,defaultWorkspace as k,ensureWorkspace as D,layoutOf as G}from"../browser/shared/workspace.mjs";import{nameProblem as N,writeWorkspaceName as O}from"../browser/shared/workspace-name.mjs";import{registerQuietly as C}from"../browser/shared/workspace-registry.mjs";var $=(o,t)=>`${o} ${t}${o===1?"":"s"}`;function W(o,t,r){let{preferences:s}=G(r);return[o.copied.length?`Copied ${$(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: ${$(o.history,"document")}`]:[],...o.packages.length?[`Custom blocks: ${o.packages.join(", ")}`]:[]]}async function q(o){let{values:t}=u({values:["--from","--name"],argv:o}),r=j,s=t.get("--name"),c=s===void 0?null:N(s);if(c)throw new h(c);let m;try{let{made:e,ours:a,reads:y}=await D(r,{state:i(r,k())});a||(console.error(g(r,y)),process.exit(1)),m=e}catch(e){if(!e.code)throw e;console.error(l(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 O(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?l(r,e.code):e.message),process.exit(1)}if(await C(r),t.has("--from")){let e=x.resolve(t.get("--from"));await b.stat(e).then(a=>a.isDirectory(),()=>!1)||(console.error(`No such folder: ${e} (--from names an older Gallery's reports/ folder).`),process.exit(1)),i(e,r)&&(console.error(`${e} is this workspace: --from names another folder (an older Gallery's reports/).`),process.exit(1));for(let a of W(await v({from:e,to:r}),e,r))console.log(a)}if(!i(r,k())){console.log('Next: gallery new <slug> "<title>" makes a document; gallery open opens Gallery.');return}let w=await f(r);for(let e of w.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 n=await p(r);n.did==="made"?console.log(`\u9996\u9875\uFF1A${n.file} (the home page, its cards Gallery's today and note; the workbench opens it first)`):n.did==="failed"&&console.warn(`\u9996\u9875\uFF1A${d(n)}`),console.log('Next: gallery new <slug> "<title>" makes a document; gallery open opens the workbench.')}export{W as a,q as b};
2
+ import{c as l,d as g}from"./chunk-L55NOXBE.mjs";import{j as p,k as d}from"./chunk-4B2TB5K2.mjs";import{u as f}from"./chunk-KLQP46Y3.mjs";import{b as h,f as u}from"./chunk-4OZWXZE5.mjs";import b from"node:fs/promises";import x from"node:path";import{reportsDirectory as j}from"../browser/shared/paths.mjs";import{sameDirectory as i}from"../browser/shared/preview-server.mjs";import{copyOldDocuments as v,defaultWorkspace as k,ensureWorkspace as D,layoutOf as G}from"../browser/shared/workspace.mjs";import{nameProblem as N,writeWorkspaceName as O}from"../browser/shared/workspace-name.mjs";import{registerQuietly as C}from"../browser/shared/workspace-registry.mjs";var $=(o,t)=>`${o} ${t}${o===1?"":"s"}`;function W(o,t,r){let{preferences:s}=G(r);return[o.copied.length?`Copied ${$(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: ${$(o.history,"document")}`]:[],...o.packages.length?[`Custom blocks: ${o.packages.join(", ")}`]:[]]}async function q(o){let{values:t}=u({values:["--from","--name"],argv:o}),r=j,s=t.get("--name"),c=s===void 0?null:N(s);if(c)throw new h(c);let m;try{let{made:e,ours:a,reads:y}=await D(r,{state:i(r,k())});a||(console.error(g(r,y)),process.exit(1)),m=e}catch(e){if(!e.code)throw e;console.error(l(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 O(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?l(r,e.code):e.message),process.exit(1)}if(await C(r),t.has("--from")){let e=x.resolve(t.get("--from"));await b.stat(e).then(a=>a.isDirectory(),()=>!1)||(console.error(`No such folder: ${e} (--from names an older Gallery's reports/ folder).`),process.exit(1)),i(e,r)&&(console.error(`${e} is this workspace: --from names another folder (an older Gallery's reports/).`),process.exit(1));for(let a of W(await v({from:e,to:r}),e,r))console.log(a)}if(!i(r,k())){console.log('Next: gallery new <slug> "<title>" makes a document; gallery open opens Gallery.');return}let w=await f(r);for(let e of w.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 n=await p(r);n.did==="made"?console.log(`\u9996\u9875\uFF1A${n.file} (the home page, its cards Gallery's today and note; the workbench opens it first)`):n.did==="failed"&&console.warn(`\u9996\u9875\uFF1A${d(n)}`),console.log('Next: gallery new <slug> "<title>" makes a document; gallery open opens the workbench.')}export{W as a,q as b};
@@ -1,5 +1,5 @@
1
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 Oe,f as we,g as ge,h as $e,i as We,j as ne,l as Y,m as Ge,n as Ae,o as Ke,p as Ve,q as ze,r as g,t as Qe,u as Ye}from"./chunk-4KUO7R2M.mjs";import{M as Xe}from"./chunk-MKIBJTJZ.mjs";import{f as Te,i as Je}from"./chunk-BN7M3IN7.mjs";import{a as K}from"./chunk-JEUK3ZO7.mjs";import{a as me}from"./chunk-M4NRDYI5.mjs";import{a as Ue,b as Ze,f as pe,g as qe}from"./chunk-PUOQ65NC.mjs";import{e as Ne,g as te}from"./chunk-S3SX3COT.mjs";import{b as Se}from"./chunk-VRPVVMRB.mjs";import{b as T,i as Pe}from"./chunk-4OZWXZE5.mjs";import{a as Be}from"./chunk-HYMEEXKN.mjs";import{f as Ee,j as He}from"./chunk-TKWEX4FD.mjs";import{randomBytes as Ct}from"node:crypto";import{existsSync as It}from"node:fs";import N from"node:fs/promises";import A from"node:path";import{isInstance as Re,isSlot as jt,partOf as Mt}from"../browser/shared/components/index.mjs";import{ATTRIBUTE as ke,FALLBACK as Rt,FIELDS as Dt,INSTANCE as ft,PACKAGE_ID as _t,SLOT as Ft}from"../browser/shared/components/installed.mjs";import{attr as ce,walk as Ht}from"../browser/shared/html-tree.mjs";import{documentDirectory as Pt,documentFiles as Bt,layoutOf as se,packageFolders as Jt,slugTaken as Ut}from"../browser/shared/workspace.mjs";var et=10,Ce=6,Zt=3,qt=100,De=1024,_e=900,Wt=4e3,le=3e4,Gt=1500,Ie=3e4,je=500,Kt=5e3,Vt=200,tt=20,nt=160,ye=12,zt=3600*1e3,Qt=["p","pi","pin"],he=e=>new Promise(t=>setTimeout(t,e));async function at(e){let{_keyDefinitions:t}=await import("./chunk-43B75J5T.mjs"),n=Object.hasOwn(t,e)?[e]:e.split("+"),a=new Set(["Control","Shift","Alt","Meta"]);if(n.some(s=>!Object.hasOwn(t,s))||n.slice(0,-1).some(s=>!a.has(s)))throw new T(`Not a key: ${e} (a key as a browser names it, Enter, Space, Escape, Tab, ArrowRight, a letter or a digit, after modifiers joined by "+": Shift+Tab, Control+Enter).`);return n}var ie={press:"<selector>",drag:'<selector>, with "to": <selector>',key:"[<selector>, <key>]",type:"[<selector>, <words>]",select:"[<selector>, <value>]"};async function ut(e,t=null){let n=d=>new T(t?`${t[0].toUpperCase()}${t.slice(1)}: ${d}`:`${d[0].toUpperCase()}${d.slice(1)}`);if(!e||typeof e!="object"||Array.isArray(e))throw n(`a step is an object naming one gesture: ${Object.entries(ie).map(([d,h])=>`"${d}": ${h}`).join(", ")}, and "then": <key> after it.`);let a=Object.keys(e).filter(d=>!Object.hasOwn(ie,d)&&!["to","then","replace"].includes(d));if(a.length)throw n(`no such field: ${a.join(", ")} (a step names one of ${Object.keys(ie).join(", ")}, "to" with a drag, "replace": true with typing and "then" after any).`);let s=Object.keys(ie).filter(d=>e[d]!==void 0),o=d=>t?`"${d}"`:`--${d}`;if(s.length!==1)throw n(s.length?`one gesture at a time: ${s.map(o).join(" or ")}.`:t?`name the gesture: ${Object.keys(ie).map(o).join(", ")}.`:"Say the gesture: --press <selector>, --drag <selector> --to <selector>, --key <selector> <key>, --type <selector> <words> or --select <selector> <value>; or --steps <file>.");let[i]=s;if(e.to!==void 0&&i!=="drag")throw n(`${o("to")} goes with ${o("drag")}: ${t?'"drag": <selector>, "to": <selector>':"--drag <selector> --to <selector>"}.`);if(i==="drag"&&e.to===void 0)throw n(`${o("drag")} takes ${o("to")}: ${t?'"drag": <selector>, "to": <selector>':"--drag <selector> --to <selector>"}, where it is dropped.`);if(e.replace!==void 0&&i!=="type")throw n(`${o("replace")} goes with ${o("type")}: it selects what the field holds before the words go in.`);if(e.replace!==void 0&&e.replace!==!0)throw n(`${o("replace")} is true: ${t?'"replace": true':"--replace"} selects what the field holds before the words go in.`);let l=(d,h)=>{if(typeof d!="string"||!d)throw n(`${h} is words: ${JSON.stringify(d)}.`);return d},c=(d,h)=>{if(!Array.isArray(d)||d.length!==2)throw n(`${o(i)} takes ${t?`[<selector>, ${h}]`:`<selector> ${h}`}.`);return[l(d[0],"a selector"),l(d[1],h)]},r={kind:i};if(i==="press"&&(r.at=l(e.press,"a selector")),i==="drag"&&Object.assign(r,{at:l(e.drag,"a selector"),to:l(e.to,"a selector")}),i==="key"){let[d,h]=c(e.key,"<key>");Object.assign(r,{at:d,key:h,keys:await at(h)})}return i==="type"&&([r.at,r.text]=c(e.type,"<words>"),e.replace&&(r.replace=!0)),i==="select"&&([r.at,r.value]=c(e.select,"<value>")),e.then!==void 0&&(r.then={key:l(e.then,"a key"),keys:await at(l(e.then,"a key"))}),r}async function Yt(e,t={},n=!1){if(n&&e.has("--steps"))throw new T('--steps <file> holds every gesture: --replace goes in a step of it, as { "type": [".name", "\u65B0\u540D\u5B57"], "replace": true }, not beside it.');if(e.has("--steps")){let s=["--press","--drag","--to","--key","--type","--select","--then"].filter(o=>e.has(o));if(s.length)throw new T(`--steps <file> holds every gesture: ${s.join(", ")} goes in it, not beside it.`);return null}let a={};for(let s of["press","drag","to","then"])e.has(`--${s}`)&&(a[s]=e.get(`--${s}`));for(let s of["key","type","select"])e.has(`--${s}`)&&(a[s]=[e.get(`--${s}`),t[`--${s}`]]);return n&&(a.replace=!0),ut(a)}async function Xt(e){let t=A.basename(e),n;try{n=await N.readFile(e,"utf8")}catch(o){throw new T(`No steps file: ${K(e)} (${o.code??ne(o)}).`)}let a;try{a=JSON.parse(n.replace(/^/,""))}catch(o){throw new T(`${t} is no JSON: ${ne(o)}. A steps file is a list of steps, as [{ "press": ".add" }, { "type": [".name", "\u65B0\u540D\u5B57"], "then": "Enter" }].`)}if(!Array.isArray(a)||a.length===0)throw new T(`${t} holds no list of steps: write [{ "press": ".add" }, { "type": [".name", "\u65B0\u540D\u5B57"], "then": "Enter" }].`);if(a.length>tt)throw new T(`${t} holds ${a.length} steps, and a trial makes ${tt} at most: try fewer at a time.`);let s=[];for(let[o,i]of a.entries())s.push(await ut(i,`step ${o+1} of ${t}`));return s}var pt=e=>{let t=e.parentNode;for(;t&&!Re(t);)t=t.parentNode;return t??null},en=(e,t)=>{for(let n=e.parentNode;n&&n!==t;n=n.parentNode)if(jt(n))return ce(n,Ft);return null};function wt(e){let t=[];return Ht(Be(e),n=>{if(!Re(n))return;let a=pt(n);t.push({element:n,id:ce(n,ke),blockId:ce(n,"data-block-id")??null,line:n.sourceCodeLocation?.startLine,in:a?{id:ce(a,ke),line:a.sourceCodeLocation?.startLine,slot:en(n,a)}:null})},{inTemplates:!1}),t}var gt=({line:e,in:t},n)=>`${n}:${e}${t?`, in ${t.slot?`the slot ${t.slot} of `:""}${t.id} at ${n}:${t.line}`:""}`,tn=(e,{id:t,blockId:n})=>n??(e.filter(a=>a.id===t).length===1?t:null);function nn(e,t,{slug:n,name:a}){let s=()=>e.map(c=>` ${tn(e,c)??"(no id yet: gallery export gives it one)"} ${c.id} at ${gt(c,a)}`).join(`
2
+ import{c as Oe,f as we,g as ge,h as $e,i as We,j as ne,l as Y,m as Ge,n as Ae,o as Ke,p as Ve,q as ze,r as g,t as Qe,u as Ye}from"./chunk-LJLVCU6W.mjs";import{M as Xe}from"./chunk-XBNFXWAW.mjs";import{f as Te,i as Je}from"./chunk-SQ3FQCCN.mjs";import{a as K}from"./chunk-JEUK3ZO7.mjs";import{a as me}from"./chunk-M4NRDYI5.mjs";import{a as Ue,b as Ze,f as pe,g as qe}from"./chunk-PUOQ65NC.mjs";import{e as Ne,g as te}from"./chunk-S3SX3COT.mjs";import{b as Se}from"./chunk-VRPVVMRB.mjs";import{b as T,i as Pe}from"./chunk-4OZWXZE5.mjs";import{a as Be}from"./chunk-HYMEEXKN.mjs";import{f as Ee,j as He}from"./chunk-TKWEX4FD.mjs";import{randomBytes as Ct}from"node:crypto";import{existsSync as It}from"node:fs";import N from"node:fs/promises";import A from"node:path";import{isInstance as Re,isSlot as jt,partOf as Mt}from"../browser/shared/components/index.mjs";import{ATTRIBUTE as ke,FALLBACK as Rt,FIELDS as Dt,INSTANCE as ft,PACKAGE_ID as _t,SLOT as Ft}from"../browser/shared/components/installed.mjs";import{attr as ce,walk as Ht}from"../browser/shared/html-tree.mjs";import{documentDirectory as Pt,documentFiles as Bt,layoutOf as se,packageFolders as Jt,slugTaken as Ut}from"../browser/shared/workspace.mjs";var et=10,Ce=6,Zt=3,qt=100,De=1024,_e=900,Wt=4e3,le=3e4,Gt=1500,Ie=3e4,je=500,Kt=5e3,Vt=200,tt=20,nt=160,ye=12,zt=3600*1e3,Qt=["p","pi","pin"],he=e=>new Promise(t=>setTimeout(t,e));async function at(e){let{_keyDefinitions:t}=await import("./chunk-43B75J5T.mjs"),n=Object.hasOwn(t,e)?[e]:e.split("+"),a=new Set(["Control","Shift","Alt","Meta"]);if(n.some(s=>!Object.hasOwn(t,s))||n.slice(0,-1).some(s=>!a.has(s)))throw new T(`Not a key: ${e} (a key as a browser names it, Enter, Space, Escape, Tab, ArrowRight, a letter or a digit, after modifiers joined by "+": Shift+Tab, Control+Enter).`);return n}var ie={press:"<selector>",drag:'<selector>, with "to": <selector>',key:"[<selector>, <key>]",type:"[<selector>, <words>]",select:"[<selector>, <value>]"};async function ut(e,t=null){let n=d=>new T(t?`${t[0].toUpperCase()}${t.slice(1)}: ${d}`:`${d[0].toUpperCase()}${d.slice(1)}`);if(!e||typeof e!="object"||Array.isArray(e))throw n(`a step is an object naming one gesture: ${Object.entries(ie).map(([d,h])=>`"${d}": ${h}`).join(", ")}, and "then": <key> after it.`);let a=Object.keys(e).filter(d=>!Object.hasOwn(ie,d)&&!["to","then","replace"].includes(d));if(a.length)throw n(`no such field: ${a.join(", ")} (a step names one of ${Object.keys(ie).join(", ")}, "to" with a drag, "replace": true with typing and "then" after any).`);let s=Object.keys(ie).filter(d=>e[d]!==void 0),o=d=>t?`"${d}"`:`--${d}`;if(s.length!==1)throw n(s.length?`one gesture at a time: ${s.map(o).join(" or ")}.`:t?`name the gesture: ${Object.keys(ie).map(o).join(", ")}.`:"Say the gesture: --press <selector>, --drag <selector> --to <selector>, --key <selector> <key>, --type <selector> <words> or --select <selector> <value>; or --steps <file>.");let[i]=s;if(e.to!==void 0&&i!=="drag")throw n(`${o("to")} goes with ${o("drag")}: ${t?'"drag": <selector>, "to": <selector>':"--drag <selector> --to <selector>"}.`);if(i==="drag"&&e.to===void 0)throw n(`${o("drag")} takes ${o("to")}: ${t?'"drag": <selector>, "to": <selector>':"--drag <selector> --to <selector>"}, where it is dropped.`);if(e.replace!==void 0&&i!=="type")throw n(`${o("replace")} goes with ${o("type")}: it selects what the field holds before the words go in.`);if(e.replace!==void 0&&e.replace!==!0)throw n(`${o("replace")} is true: ${t?'"replace": true':"--replace"} selects what the field holds before the words go in.`);let l=(d,h)=>{if(typeof d!="string"||!d)throw n(`${h} is words: ${JSON.stringify(d)}.`);return d},c=(d,h)=>{if(!Array.isArray(d)||d.length!==2)throw n(`${o(i)} takes ${t?`[<selector>, ${h}]`:`<selector> ${h}`}.`);return[l(d[0],"a selector"),l(d[1],h)]},r={kind:i};if(i==="press"&&(r.at=l(e.press,"a selector")),i==="drag"&&Object.assign(r,{at:l(e.drag,"a selector"),to:l(e.to,"a selector")}),i==="key"){let[d,h]=c(e.key,"<key>");Object.assign(r,{at:d,key:h,keys:await at(h)})}return i==="type"&&([r.at,r.text]=c(e.type,"<words>"),e.replace&&(r.replace=!0)),i==="select"&&([r.at,r.value]=c(e.select,"<value>")),e.then!==void 0&&(r.then={key:l(e.then,"a key"),keys:await at(l(e.then,"a key"))}),r}async function Yt(e,t={},n=!1){if(n&&e.has("--steps"))throw new T('--steps <file> holds every gesture: --replace goes in a step of it, as { "type": [".name", "\u65B0\u540D\u5B57"], "replace": true }, not beside it.');if(e.has("--steps")){let s=["--press","--drag","--to","--key","--type","--select","--then"].filter(o=>e.has(o));if(s.length)throw new T(`--steps <file> holds every gesture: ${s.join(", ")} goes in it, not beside it.`);return null}let a={};for(let s of["press","drag","to","then"])e.has(`--${s}`)&&(a[s]=e.get(`--${s}`));for(let s of["key","type","select"])e.has(`--${s}`)&&(a[s]=[e.get(`--${s}`),t[`--${s}`]]);return n&&(a.replace=!0),ut(a)}async function Xt(e){let t=A.basename(e),n;try{n=await N.readFile(e,"utf8")}catch(o){throw new T(`No steps file: ${K(e)} (${o.code??ne(o)}).`)}let a;try{a=JSON.parse(n.replace(/^/,""))}catch(o){throw new T(`${t} is no JSON: ${ne(o)}. A steps file is a list of steps, as [{ "press": ".add" }, { "type": [".name", "\u65B0\u540D\u5B57"], "then": "Enter" }].`)}if(!Array.isArray(a)||a.length===0)throw new T(`${t} holds no list of steps: write [{ "press": ".add" }, { "type": [".name", "\u65B0\u540D\u5B57"], "then": "Enter" }].`);if(a.length>tt)throw new T(`${t} holds ${a.length} steps, and a trial makes ${tt} at most: try fewer at a time.`);let s=[];for(let[o,i]of a.entries())s.push(await ut(i,`step ${o+1} of ${t}`));return s}var pt=e=>{let t=e.parentNode;for(;t&&!Re(t);)t=t.parentNode;return t??null},en=(e,t)=>{for(let n=e.parentNode;n&&n!==t;n=n.parentNode)if(jt(n))return ce(n,Ft);return null};function wt(e){let t=[];return Ht(Be(e),n=>{if(!Re(n))return;let a=pt(n);t.push({element:n,id:ce(n,ke),blockId:ce(n,"data-block-id")??null,line:n.sourceCodeLocation?.startLine,in:a?{id:ce(a,ke),line:a.sourceCodeLocation?.startLine,slot:en(n,a)}:null})},{inTemplates:!1}),t}var gt=({line:e,in:t},n)=>`${n}:${e}${t?`, in ${t.slot?`the slot ${t.slot} of `:""}${t.id} at ${n}:${t.line}`:""}`,tn=(e,{id:t,blockId:n})=>n??(e.filter(a=>a.id===t).length===1?t:null);function nn(e,t,{slug:n,name:a}){let s=()=>e.map(c=>` ${tn(e,c)??"(no id yet: gallery export gives it one)"} ${c.id} at ${gt(c,a)}`).join(`
3
3
  `);if(t===null){if(e.length===1)return 0;throw new T(`${n} holds ${e.length} instances: name one, gallery block try ${n} <instance id> \u2026
4
4
  ${s()}`)}let o=e.findIndex(({blockId:c})=>c===t);if(o>=0)return o;let i=t.includes("/")?t:`local/${t}`,l=_t.test(i)?e.flatMap((c,r)=>c.id===i?[r]:[]):[];if(l.length===1)return l[0];throw new T(l.length?`${n} holds ${l.length} instances of ${i}: name one by its id
5
5
  ${s()}`:`${n} holds no instance ${t}: