@diagc/cli 0.10.0 → 0.12.0
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.
- package/README.md +3 -12
- package/assets/guide/activity.md +27 -0
- package/assets/guide/c4.md +25 -0
- package/assets/guide/causal-loop.md +22 -0
- package/assets/guide/deployment.md +28 -0
- package/assets/guide/er.md +25 -0
- package/assets/guide/fishbone.md +28 -0
- package/assets/guide/git-graph.md +28 -0
- package/assets/guide/index.md +112 -0
- package/assets/guide/plan.md +28 -0
- package/assets/guide/second-order.md +26 -0
- package/assets/guide/threat-model.md +28 -0
- package/assets/starters/activity/starter.diagram.ts +22 -0
- package/assets/starters/basic/starter.diagram.ts +21 -0
- package/assets/starters/c4/starter.diagram.ts +19 -0
- package/assets/starters/causal-loop/starter.diagram.ts +16 -0
- package/assets/starters/deployment/starter.diagram.ts +19 -0
- package/assets/starters/er/starter.diagram.ts +23 -0
- package/assets/starters/fishbone/starter.diagram.ts +11 -0
- package/assets/starters/git-graph/starter.diagram.ts +15 -0
- package/assets/starters/plan/starter.diagram.ts +26 -0
- package/assets/starters/second-order/starter.diagram.ts +14 -0
- package/assets/starters/threat-model/starter.diagram.ts +16 -0
- package/assets/studio/assets/{index-DL_lrezG.js → index-C0LPHkb1.js} +1 -1
- package/assets/studio/index.html +1 -1
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +74 -6
- package/dist/compile.d.ts +26 -0
- package/dist/compile.js +50 -2
- package/dist/guide.d.ts +39 -0
- package/dist/guide.js +152 -0
- package/dist/home.d.ts +9 -0
- package/dist/home.js +19 -1
- package/dist/init.d.ts +54 -0
- package/dist/init.js +197 -0
- package/dist/lint.d.ts +3 -0
- package/dist/lint.js +14 -2
- package/dist/starters.d.ts +16 -0
- package/dist/starters.js +34 -0
- package/package.json +2 -2
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { model } from '@diagc/core';
|
|
2
|
+
|
|
3
|
+
const m = model('password-reset', { name: 'Password reset flow' });
|
|
4
|
+
const tm = m.threatModel();
|
|
5
|
+
|
|
6
|
+
const customer = tm.entity('customer', 'Customer');
|
|
7
|
+
const auth = tm.process('auth', 'Auth service');
|
|
8
|
+
tm.boundary('internet-facing', 'DMZ').contains(auth);
|
|
9
|
+
|
|
10
|
+
tm.flow(customer, auth, 'HTTPS: reset request').threat({
|
|
11
|
+
category: 'I',
|
|
12
|
+
title: 'Reset token leaks to third parties via the Referer header',
|
|
13
|
+
severity: 'medium',
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
export default m;
|
|
@@ -106,4 +106,4 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
106
106
|
${e}</tr>
|
|
107
107
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
108
108
|
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${QT(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=$T(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+QT(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=$T(e);if(i===null)return QT(n);e=i;let a=`<img src="${e}" alt="${QT(n)}"`;return t&&(a+=` title="${QT(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:QT(e.text)}},cE=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},lE=class e{options;renderer;textRenderer;constructor(e){this.options=e||aT,this.options.renderer=this.options.renderer||new sE,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new cE}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},uE=class{options;block;constructor(e){this.options=e||aT}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?oE.lex:oE.lexInline}provideParser(e=this.block){return e?lE.parse:lE.parseInline}},dE=new class{defaults=iT();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=lE;Renderer=sE;TextRenderer=cE;Lexer=oE;Tokenizer=aE;Hooks=uE;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new sE(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new aE(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new uE;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];uE.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&uE.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:t[r]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return oE.lex(e,t??this.defaults)}parser(e,t){return lE.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?oE.lex:oE.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?lE.parse:lE.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?oE.lex:oE.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?lE.parse:lE.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
|
|
109
|
-
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+QT(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function fE(e,t){return dE.parse(e,t)}fE.options=fE.setOptions=function(e){return dE.setOptions(e),fE.defaults=dE.defaults,oT(fE.defaults),fE},fE.getDefaults=iT,fE.defaults=aT,fE.use=function(...e){return dE.use(...e),fE.defaults=dE.defaults,oT(fE.defaults),fE},fE.walkTokens=function(e,t){return dE.walkTokens(e,t)},fE.parseInline=dE.parseInline,fE.Parser=lE,fE.parser=lE.parse,fE.Renderer=sE,fE.TextRenderer=cE,fE.Lexer=oE,fE.lexer=oE.lex,fE.Tokenizer=aE,fE.Hooks=uE,fE.parse=fE,fE.options,fE.setOptions,fE.use,fE.walkTokens,fE.parseInline,lE.parse,oE.lex;function Qle({metadata:e}){let t=Object.entries(e);return t.length===0?null:(0,D.jsx)(`dl`,{className:`meta`,children:t.map(([e,t])=>(0,D.jsxs)(`div`,{className:`meta-row`,children:[(0,D.jsx)(`dt`,{children:e}),(0,D.jsx)(`dd`,{children:typeof t==`string`&&/^https?:\/\//.test(t)?(0,D.jsx)(`a`,{href:t,target:`_blank`,rel:`noreferrer`,children:t}):String(t)})]},e))})}function $le({model:e,selection:t}){if(t===null)return(0,D.jsx)(`aside`,{className:`sidebar muted`,children:`Select a node or edge for details.`});if(t.kind===`node`){let n=e.nodes.find(e=>e.id===t.id);return n?(0,D.jsxs)(`aside`,{className:`sidebar`,children:[(0,D.jsx)(`h2`,{children:n.name}),(0,D.jsxs)(`p`,{className:`muted`,children:[n.type,` · `,(0,D.jsx)(`code`,{children:n.id})]}),n.description!==void 0&&(0,D.jsx)(`div`,{dangerouslySetInnerHTML:{__html:fE.parse(n.description)}}),n.metadata!==void 0&&(0,D.jsx)(Qle,{metadata:n.metadata})]}):(0,D.jsx)(`aside`,{className:`sidebar muted`,children:`Aggregate node (zoom in for details).`})}let[n]=t.id.split(`:`),[r,i]=(n??``).split(`=>`),a=new Set(t.constituentIds??[]),o=e.relations.filter(e=>a.has(e.id));return(0,D.jsxs)(`aside`,{className:`sidebar`,children:[(0,D.jsxs)(`h2`,{children:[r,` → `,i]}),o.length===0?(0,D.jsx)(`p`,{className:`muted`,children:`No relation details available.`}):(0,D.jsx)(`ul`,{children:o.map(e=>(0,D.jsxs)(`li`,{children:[(0,D.jsx)(`code`,{children:e.from}),` → `,(0,D.jsx)(`code`,{children:e.to}),` `,(0,D.jsx)(`b`,{children:e.kind}),e.label===void 0?``:` — ${e.label}`,e.description!==void 0&&(0,D.jsx)(`div`,{dangerouslySetInnerHTML:{__html:fE.parse(e.description)}})]},e.id))})]})}var pE=xi(),eue=Ty(),tue={query:``,toggled:{},groupToggled:{}},mE=(e,t)=>{let{libraryBase:n}=Kx();return n!==void 0&&t.startsWith(`/library/`)?`${n}${t.slice(9)}`:t.startsWith(`/`)||/^https?:/.test(t)?t:`${e}${t}`},nue=16,rue=64;function iue(e){let t=[],n=new Map;for(let r of e){if(r.group===void 0){t.push({cats:[r]});continue}let e=n.get(r.group);e===void 0&&(e={group:r.group,cats:[]},n.set(r.group,e),t.push(e)),e.cats.push(r)}return t}function hE({entry:e,assetBase:t}){if(e.template.image!==void 0)return(0,D.jsx)(`img`,{className:`lib-thumb`,src:mE(t,e.template.image),alt:e.name,draggable:!1});if(e.template.shape!==void 0){let n=`url("${mE(t,e.template.shape)}")`;return(0,D.jsx)(`span`,{className:`lib-thumb lib-shape-thumb`,"aria-hidden":`true`,style:{WebkitMaskImage:n,maskImage:n,background:e.template.color??`var(--dg-text-muted)`}})}let n=e.template.color??`var(--dg-border)`,r=e.template.type===void 0?void 0:pE.resolve(e.template.type),i=r?.icon===void 0?void 0:eue.resolve(r.icon),a=r?.outline===!0||r?.dashed===!0;return(0,D.jsx)(`span`,{className:`lib-swatch lib-swatch-${r?.shape??`box`}${a?` lib-swatch-outline`:``}`,style:a?{border:`1.5px ${r?.dashed===!0?`dashed`:`solid`} ${n}`,color:n}:{background:n},children:i!==void 0&&(0,D.jsx)(i,{size:14,className:`lib-swatch-icon`})})}function aue({library:e,onPlace:t,onApply:n,applyTarget:r,onAddNode:i,onAddImages:a,onAddCategory:o,onDeleteCategory:s,onImportIcon:c,onImportShape:l,assetBase:u=`/api/assets/`,viewState:d}){let f=(0,v.useState)(tue),[{query:p,toggled:m,groupToggled:h},g]=d??f,_=e=>g(t=>({...t,query:e})),[y,b]=(0,v.useState)(``),[x,S]=(0,v.useState)(`place`),C=(0,v.useMemo)(()=>nce(e,p),[e,p]),w=(0,v.useMemo)(()=>{let e=new Map;for(let t of C){let n=e.get(t.category);n===void 0?e.set(t.category,[t]):n.push(t)}return e},[C]),T=p.trim()!==``,E=(0,v.useMemo)(()=>iue(e.categories),[e.categories]),ee=r!==void 0&&n!==void 0,te=ee&&x===`apply`;(0,v.useEffect)(()=>{S(`place`)},[r?.id]);let ne=()=>{let e=y.trim();e===``||o===void 0||(o(e),b(``))};return(0,D.jsxs)(`aside`,{className:`sidebar lib-panel`,children:[(0,D.jsx)(`div`,{className:`panel-head`,children:(0,D.jsx)(`h3`,{children:`Library`})}),(i!==void 0||a!==void 0)&&(0,D.jsxs)(`div`,{className:`lib-actions`,children:[i!==void 0&&(0,D.jsx)(`button`,{type:`button`,className:`chip`,onClick:i,children:`Add node`}),a!==void 0&&(0,D.jsxs)(`label`,{className:`chip icon-btn`,title:`Add image`,children:[`Add image`,(0,D.jsx)(`input`,{type:`file`,accept:`image/*`,multiple:!0,hidden:!0,"aria-label":`Add image`,onChange:e=>{let t=[...e.target.files??[]];t.length>0&&a(t),e.target.value=``}})]})]}),ee&&(0,D.jsxs)(`div`,{className:`lib-apply-toggle`,role:`group`,"aria-label":`Card click action`,children:[(0,D.jsx)(`button`,{type:`button`,className:`chip${te?``:` active`}`,"aria-pressed":!te,title:`Clicking a card adds a new node`,onClick:()=>S(`place`),children:`Place new`}),(0,D.jsxs)(`button`,{type:`button`,className:`chip${te?` active`:``}`,"aria-pressed":te,title:`Clicking a card restyles ${r.name} to match it`,onClick:()=>S(`apply`),children:[`Apply to `,r.name]})]}),(0,D.jsx)(`input`,{className:`lib-search`,type:`search`,"aria-label":`Search library`,placeholder:`Search nodes…`,value:p,onChange:e=>_(e.target.value)}),E.map(e=>{let i=e=>{let i=w.get(e.id)??[];if(i.length===0&&(T||e.builtin===!0))return null;let a=m[e.id]??(T||i.length<=nue);return(0,D.jsxs)(`section`,{className:`lib-category`,children:[(0,D.jsxs)(`div`,{className:`lib-cat-head`,children:[(0,D.jsx)(`h4`,{className:`lib-cat-name`,children:(0,D.jsxs)(`button`,{type:`button`,className:`lib-cat-toggle`,"aria-label":e.name,"aria-expanded":a,title:`${a?`Collapse`:`Expand`} ${e.name}`,onClick:()=>g(t=>({...t,toggled:{...t.toggled,[e.id]:!a}})),children:[(0,D.jsx)(`span`,{className:`lib-cat-caret`,"aria-hidden":`true`,children:a?`▾`:`▸`}),(0,D.jsx)(`span`,{className:`lib-cat-label`,children:e.name}),(0,D.jsx)(`span`,{className:`lib-cat-count`,children:i.length})]})}),e.builtin!==!0&&(0,D.jsxs)(`span`,{className:`lib-cat-actions`,children:[c!==void 0&&(0,D.jsxs)(`label`,{className:`chip icon-btn`,title:`Import icon into ${e.name}`,children:[`Icon`,(0,D.jsx)(`input`,{type:`file`,accept:`image/*`,hidden:!0,"aria-label":`Import icon into ${e.name}`,onChange:t=>{let n=t.target.files?.[0];n!==void 0&&c(e.id,n),t.target.value=``}})]}),l!==void 0&&(0,D.jsxs)(`label`,{className:`chip icon-btn`,title:`Import shape into ${e.name}`,children:[`Shape`,(0,D.jsx)(`input`,{type:`file`,accept:`.svg,image/svg+xml`,hidden:!0,"aria-label":`Import shape into ${e.name}`,onChange:t=>{let n=t.target.files?.[0];n!==void 0&&l(e.id,n),t.target.value=``}})]}),s!==void 0&&(0,D.jsx)(`button`,{type:`button`,className:`chip icon-btn`,"aria-label":`Delete category ${e.name}`,title:`Delete category ${e.name}`,onClick:()=>void Kx().confirmDialog(`Delete category '${e.name}' and its imported icons?`).then(t=>{t&&s(e.id)}),children:`✕`})]})]}),a&&(0,D.jsx)(`div`,{className:`lib-grid`,children:i.map(e=>(0,D.jsxs)(`button`,{type:`button`,className:`lib-entry`,"aria-label":te?`Apply ${e.name}`:`Place ${e.name}`,title:te?`Apply ${e.name} to ${r.name}`:`Place ${e.name}`,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(`application/x-dg-library-entry`,e.id),t.dataTransfer.effectAllowed=`copy`},onClick:()=>te?n(e):t(e),children:[(0,D.jsx)(hE,{entry:e,assetBase:u}),(0,D.jsx)(`span`,{className:`lib-entry-name`,children:e.name})]},e.id))})]},e.id)};if(e.group===void 0)return i(e.cats[0]);let a=e.group,o=e.cats.reduce((e,t)=>e+(w.get(t.id)??[]).length,0);if(o===0&&T)return null;let d=h[a]??(T||o<=rue);return(0,D.jsxs)(`section`,{className:`lib-group`,children:[(0,D.jsx)(`h4`,{className:`lib-cat-name lib-group-name`,children:(0,D.jsxs)(`button`,{type:`button`,className:`lib-cat-toggle`,"aria-label":a,"aria-expanded":d,title:`${d?`Collapse`:`Expand`} ${a}`,onClick:()=>g(e=>({...e,groupToggled:{...e.groupToggled,[a]:!d}})),children:[(0,D.jsx)(`span`,{className:`lib-cat-caret`,"aria-hidden":`true`,children:d?`▾`:`▸`}),(0,D.jsx)(`span`,{className:`lib-cat-label`,children:a}),(0,D.jsx)(`span`,{className:`lib-cat-count`,children:o})]})}),d&&(0,D.jsx)(`div`,{className:`lib-group-body`,children:e.cats.map(i)})]},`group:${a}`)}),o!==void 0&&(0,D.jsxs)(`div`,{className:`add-member`,children:[(0,D.jsx)(`input`,{"aria-label":`New category name`,placeholder:`New category…`,value:y,onChange:e=>b(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),ne())}}),(0,D.jsx)(`button`,{type:`button`,className:`chip`,"aria-label":`Add category`,onClick:ne,children:`+`})]})]})}var gE={categories:[],entries:[]};async function oue(){try{let e=await Kx().apiFetch(`/api/library`);if(!e.ok)return gE;let t=await e.json();return{categories:t.categories??[],entries:t.entries??[]}}catch{return gE}}async function _E(e){let t=await Kx().apiFetch(`/api/library`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>null);throw Error(e?.issues?.[0]?.message??`Library save failed (${t.status})`)}}var vE=new Set(ww.categories.map(e=>e.id));function yE(){let[e,t]=(0,v.useState)({categories:[],entries:[]}),n=(0,v.useRef)(e);n.current=e,(0,v.useEffect)(()=>{oue().then(t)},[]);let r=(0,v.useMemo)(()=>LS(ww,e),[e]),i=(0,v.useCallback)(e=>{t(e),_E(e).catch(()=>{})},[]);return{library:r,addCategory:(0,v.useCallback)(e=>{let t=n.current,r=RS(e,new Set(LS(ww,t).categories.map(e=>e.id)),`category`);i({...t,categories:[...t.categories,{id:r,name:e.trim()||r}]})},[i]),deleteCategory:(0,v.useCallback)(e=>{if(vE.has(e))return;let t=n.current;i({categories:t.categories.filter(t=>t.id!==e),entries:t.entries.filter(t=>t.category!==e)})},[i]),addEntry:(0,v.useCallback)(e=>{let t=n.current;i({...t,entries:[...t.entries,e]})},[i])}}function bE(e,t){let n=new Map(e.nodes.map(e=>[e.id,e.type])),r=new Set(e.relations.map(e=>e.id)),i=e=>oe.includes(n.get(e)??``),a=new Set;for(let r of t.nodeIds)if(!(!n.has(r)||!i(r)))for(let t of Fe(e,r))t!==r&&a.add(t);let o=[...t.relationIds.filter(e=>r.has(e)).map(e=>({type:`delete-relation`,id:e})),...t.nodeIds.filter(e=>n.has(e)&&!a.has(e)).map(e=>({type:`delete-node`,id:e,...i(e)?{cascade:!0}:{}}))];return o.length===0?null:o.length===1?o[0]:{type:`batch`,commands:o}}function sue(e,t,n,r,i){let a=e.nodes.find(e=>e.id===t);if(a?.type!==`db-table`||a.columns===void 0)return null;let o=a.columns.find(e=>e.name===r);if(o===void 0)return null;let s=e.nodes.find(e=>e.id===n)?.columns?.find(e=>e.pk===!0)?.name,c=[{type:`add-relation`,from:t,to:n,opts:{kind:`fk`,fromColumn:o.name,...s===void 0?{}:{toColumn:s},...i?.layer===void 0?{}:{layer:i.layer}}}];return o.fk!==!0&&c.push({type:`set-table-columns`,id:t,columns:a.columns.map(e=>e.name===o.name?{...e,fk:!0}:e)}),c}var xE=e=>e.map(e=>oC(e).label).join(`, `),SE=(e,t,n)=>{let r=[...sC(e)[t.id]];return r[t.index]=n,gC(e,t.id,r)};function CE({overrides:e,onChange:t,onClose:n,mac:r=rC()}){let i=(0,v.useMemo)(()=>sC(e),[e]),[a,o]=(0,v.useState)(``),[s,c]=(0,v.useState)(null),[l,u]=(0,v.useState)(null),[d,f]=(0,v.useState)(null),p=(0,v.useRef)(null);(0,v.useEffect)(()=>{p.current?.focus()},[]);let m=e=>nC(e,r),h=e=>{f(null),u(null),c(e)},g=a=>{if(s===null){if(a.key!==`Escape`)return;a.stopPropagation(),l===null?n():u(null);return}if(a.preventDefault(),a.stopPropagation(),a.key===`Escape`){c(null);return}let o=QS(a.nativeEvent,r);if(o===null)return;c(null);let d=hC(o);if(d!==null){f(`${m(o)}: ${d}`);return}if(i[s.id].includes(o))return;let p=bce(i,s.id,o);p.length>0?u({...s,chord:o,conflicts:p}):t(SE(e,s,o))},_=()=>{if(l===null)return;let n=e;for(let e of l.conflicts)n=gC(n,e,sC(n)[e].filter(e=>e!==l.chord));t(SE(n,l,l.chord)),u(null)},y=n=>{let r={...e};delete r[n],t(r)},b=async()=>{await Kx().confirmDialog(`Reset every keyboard shortcut to its default?`)&&t({})},x=a.trim().toLowerCase(),S=aC.filter(e=>x===``||e.label.toLowerCase().includes(x)||e.group.toLowerCase().includes(x)||i[e.id].some(e=>m(e).toLowerCase().includes(x))),C=(e,t)=>s?.id===e&&s.index===t;return(0,D.jsx)(`div`,{className:`hotkeys-backdrop`,"data-testid":`hotkeys-backdrop`,onMouseDown:e=>{e.target===e.currentTarget&&n()},children:(0,D.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Keyboard shortcuts`,className:`hotkeys-dialog`,tabIndex:-1,onKeyDownCapture:g,children:[(0,D.jsxs)(`header`,{className:`hotkeys-head`,children:[(0,D.jsx)(`strong`,{children:`Keyboard shortcuts`}),(0,D.jsx)(`button`,{type:`button`,className:`chip`,"aria-label":`Close`,onClick:n,children:`✕`})]}),(0,D.jsx)(`input`,{ref:p,className:`hotkeys-search`,"aria-label":`Search shortcuts`,placeholder:`search actions…`,value:a,onChange:e=>o(e.target.value)}),l!==null&&(0,D.jsxs)(`div`,{className:`hotkeys-note`,role:`alert`,children:[(0,D.jsxs)(`span`,{children:[m(l.chord),` is already `,xE(l.conflicts),`.`]}),(0,D.jsx)(`button`,{type:`button`,className:`chip primary`,onClick:_,children:`Reassign`}),(0,D.jsx)(`button`,{type:`button`,className:`chip`,onClick:()=>u(null),children:`Cancel`})]}),d!==null&&(0,D.jsx)(`div`,{className:`hotkeys-note`,role:`alert`,children:d}),(0,D.jsxs)(`div`,{className:`hotkeys-list`,children:[iC.map(n=>{let r=S.filter(e=>e.group===n);return r.length===0?null:(0,D.jsxs)(`section`,{"aria-label":n,children:[(0,D.jsx)(`h3`,{className:`hotkeys-group`,children:n}),r.map(n=>{let r=i[n.id];return(0,D.jsxs)(`div`,{className:`hotkeys-row`,children:[(0,D.jsx)(`span`,{className:`hotkeys-label`,children:n.label}),(0,D.jsxs)(`span`,{className:`hotkeys-keys`,children:[r.length===0&&!C(n.id,0)&&(0,D.jsx)(`span`,{className:`hotkeys-unbound`,children:`—`}),r.map((a,o)=>{let s=bce(i,n.id,a);return(0,D.jsxs)(`span`,{className:`hotkeys-key`,children:[(0,D.jsx)(`button`,{type:`button`,className:`hotkey-chip`,"aria-label":`Change ${m(a)} for ${n.label}`,...s.length>0?{title:`Also bound to ${xE(s)}`,"data-conflict":``}:{},...C(n.id,o)?{"data-recording":``}:{},onClick:()=>h({id:n.id,index:o}),children:C(n.id,o)?`Press a key…`:m(a)}),(0,D.jsx)(`button`,{type:`button`,className:`hotkey-x`,"aria-label":`Remove ${m(a)} from ${n.label}`,onClick:()=>t(gC(e,n.id,r.filter((e,t)=>t!==o))),children:`×`})]},a)}),(0,D.jsx)(`button`,{type:`button`,className:`hotkey-chip hotkey-add`,"aria-label":`Add a key for ${n.label}`,...C(n.id,r.length)?{"data-recording":``}:{},onClick:()=>h({id:n.id,index:r.length}),children:C(n.id,r.length)?`Press a key…`:`+`}),e[n.id]!==void 0&&(0,D.jsx)(`button`,{type:`button`,className:`hotkey-x`,"aria-label":`Reset ${n.label}`,title:`Back to the default`,onClick:()=>y(n.id),children:`↺`})]})]},n.id)})]},n)}),x===``&&(0,D.jsxs)(`section`,{"aria-label":`Fixed`,children:[(0,D.jsx)(`h3`,{className:`hotkeys-group`,children:`Fixed`}),vce.map(e=>(0,D.jsxs)(`div`,{className:`hotkeys-row`,children:[(0,D.jsx)(`span`,{className:`hotkeys-label`,children:e.label}),(0,D.jsx)(`span`,{className:`hotkeys-keys hotkeys-fixed`,children:e.keys})]},e.label))]})]}),(0,D.jsxs)(`footer`,{className:`hotkeys-foot`,children:[(0,D.jsx)(`button`,{type:`button`,className:`chip`,disabled:Object.keys(e).length===0,onClick:()=>void b(),children:`Reset all to defaults`}),(0,D.jsx)(`span`,{className:`hotkeys-hint`,children:`Click a key to change it. Esc cancels.`})]})]})})}var cue=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`||e.isContentEditable===!0||e.closest(`[contenteditable=""], [contenteditable="true"]`)!==null},wE=(e,t)=>e instanceof Element&&e!==document.body&&e!==document.documentElement&&t!==null&&!t.contains(e);function lue({rootRef:e,keymap:t,mode:n,handlersRef:r,suspended:i,mac:a=rC()}){let o=(0,v.useRef)({keymap:t,mode:n,suspended:i});o.current={keymap:t,mode:n,suspended:i};let s=(0,v.useRef)(null);(0,v.useEffect)(()=>{let t=t=>{let{keymap:n,mode:i,suspended:c}=o.current;if(c||t.defaultPrevented||wE(t.target,e.current))return;let l=QS(t,a);if(l===null)return;let u=uC(n,l,i);if(u===void 0)return;let d=oC(u);if(cue(t.target)&&!(d.inFields===!0&&(t.ctrlKey||t.metaKey||t.altKey)))return;if(t.repeat&&d.repeat!==!0){s.current?.chord===l&&s.current.claimed&&t.preventDefault();return}let f=r.current?.[u],p=f!==void 0&&f()!==!1;t.repeat||(s.current={chord:l,claimed:p}),p&&t.preventDefault()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,r,a])}var uue=`diagc.style`,TE=`diagc.snap`,EE=10,DE=`diagc.rightDock`,due=`diagc.leftDock`,fue=`diagc.leftDockWidth`,OE=`diagc.rightDockWidth`,kE=560,AE=220,jE=240,pue=300,ME=320,NE=(e,t,n)=>{if(e===null)return null;let r=Number(e);return Number.isFinite(r)?nT(r,t,n):null},PE=(e,t)=>{if(t?.kind!==`node`)return;let n=e.nodes.find(e=>e.id===t.id);return n===void 0?void 0:{applyTarget:{id:n.id,name:n.name||n.id}}};function mue({initialTheme:e=`dark`}={}){let{artifacts:t,names:n,booted:r,ownedNames:i,setOwnedNames:a,setDrafts:o,setLoaded:s,setSources:c,canDesign:l}=Jx(),[u,d]=(0,v.useState)(e),[f,p]=Zx(uue,`clean`,e=>e),[m,h]=Zx(TE,!1,e=>e===null?null:e===`true`),[g,_]=Zx(yce,{},Sce,JSON.stringify),y=(0,v.useMemo)(()=>sC(g),[g]),[S,C]=(0,v.useState)(!1),T=(0,v.useMemo)(rC,[]),E=(0,v.useRef)(null),ee=(0,v.useRef)(null),te=(0,v.useRef)(null),ne=(0,v.useRef)(null),re=(0,v.useRef)({}),[ie,ae]=(0,v.useState)(void 0),[oe,se]=(0,v.useState)([]),[ce,le]=(0,v.useState)(null),[ue,de]=(0,v.useState)({}),[fe,pe]=(0,v.useState)({}),[me,he]=(0,v.useState)({}),[ge,_e]=(0,v.useState)({}),[ve,ye]=(0,v.useState)(!1),[be,xe]=(0,v.useState)(!1),[Se,Ce]=(0,v.useState)(null),[we,Te]=(0,v.useState)(null),[Ee,De]=(0,v.useState)(void 0),Oe=e=>De(t=>({id:e,nonce:(t?.nonce??0)+1})),[ke,Ae]=(0,v.useState)(void 0),je=(e,t)=>Ae(n=>({target:e,id:t,nonce:(n?.nonce??0)+1})),[Me,Ne]=(0,v.useState)([]),Pe=(0,v.useCallback)(e=>Ne(t=>t.length===e.length&&t.every((t,n)=>t===e[n])?t:e),[]),[Fe,Ie]=(0,v.useState)(null),[Le,Re]=(0,v.useState)([]),ze=(0,v.useCallback)(e=>Re(e),[]),[Be,Ve]=(0,v.useState)(null),[He,Ue]=(0,v.useState)(`properties`),We=(0,v.useState)(tue),[Ge,Ke]=Zx(due,!1,e=>e===`collapsed`,e=>e?`collapsed`:`expanded`),[qe,Je]=Zx(DE,!1,e=>e===`collapsed`,e=>e?`collapsed`:`expanded`),[Ye,Xe]=Zx(fue,pue,e=>NE(e,AE,kE)),[Ze,Qe]=Zx(OE,ME,e=>NE(e,jE,kE)),$e=yE(),et=(0,v.useRef)(()=>!0),{selected:tt,setSelected:nt,enteredPath:rt,setEnteredPath:it,handleEnteredPathChange:at}=tS({names:n,booted:r,leaveEditRef:et}),ot=rt.length>0?rt[rt.length-1]:void 0,st=(0,v.useRef)(tt);st.current=tt,(0,v.useEffect)(()=>{xe(!1)},[tt]),(0,v.useEffect)(()=>{pe({})},[tt]);let[ct,lt]=(0,v.useState)(`select`),[ut,dt]=(0,v.useState)(``),[ft,pt]=(0,v.useState)(3),{editing:mt,setEditing:ht,editor:gt,layoutApiRef:vt,saveIssues:yt,setSaveIssues:bt,saving:xt,doSave:St,enterEdit:Ct,leaveEdit:wt}=cS({setDrafts:o,resetInspector:()=>Ue(`properties`),leaveEditRef:et});(0,v.useEffect)(()=>{(!mt||rt.length>0)&<(`select`)},[mt,tt,rt]),(0,v.useEffect)(()=>{w(document.documentElement,u===`dark`?x:b),document.documentElement.dataset.theme=u},[u]);let Tt=t[tt],Et=gt.session,Dt=mt?Et?.state.model:Tt?.model,Ot=mt?Et?.state.layout:Tt?.layout,kt=mt?Et?.state.drawings:Tt?.drawings,At=Dt?.style!==void 0&&Ov(Dt.style)?Dt.style:void 0,jt=Dt?.planes??[],Mt=ie,Nt=Hr(jt,Mt,Dt?.notation),Pt=dae(),Ft=Eh(Nt).partitionOf!==void 0,It=jt.find(e=>e.id===Mt)?.containmentOf!==void 0,Lt=(0,v.useRef)(null);(0,v.useEffect)(()=>{if(Dt===void 0||Lt.current===tt)return;Lt.current=tt,se(Vr(Dt.planes,ie));let e=Ot?.export?.collapsed??[];de({...Object.fromEntries(e.map(e=>[e,`collapsed`])),...Xr(Ot,Dt,ie)})},[tt,Dt,ie,Ot]);let Rt=Dt!==void 0&&Ot?.manual?.[Yr(Dt,Mt)]===!0,zt=(0,v.useMemo)(()=>mt?Ot:Pce(Ot,Dt,Mt,fe),[mt,Ot,Dt,Mt,fe]),Bt=(Dt===void 0?void 0:zt?.settings?.[Yr(Dt,Mt)])??{},Vt=ce!==null&&(Dt?.layers??[]).some(e=>e.id===ce)?ce:null,Ht=(e,t,n)=>{let r={...Dt?.relations.find(t=>t.id===e)?.style},i=t===`from`?`fromSide`:`toSide`;return n===null?delete r[i]:r[i]=n,Object.keys(r).length>0?r:null},Ut=(e,t,n,r)=>{if(Dt===void 0)return;let i=JS(Dt,e);i!==null&>.dispatch({type:`update-relation`,id:e,patch:{labels:fce(i,t,n,r)}})},Wt=(e,t,n)=>{if(Dt===void 0)return;let r=JS(Dt,e);r!==null&>.dispatch({type:`update-relation`,id:e,patch:{labels:pce(r,t,n)}})},Gt=(e,t,n,r)=>{if(Dt===void 0)return;let i=JS(Dt,e);i!==null&>.dispatch({type:`update-relation`,id:e,patch:{labels:mce(i,t,n,r)}})},Kt=Et?.lastRelationId;(0,v.useEffect)(()=>{mt&&Kt!==void 0&&(Ce({kind:`edge`,id:Kt}),Te(null))},[mt,Kt]);let qt=qS({editor:gt,model:Dt,selection:Se,groupSel:Me,editing:mt,notation:Nt,activePlane:Mt,activePlaneBorrowsContainment:It,planes:jt,activeLayer:ce,activeLayers:oe,setSelection:Ce,setRenameId:Te,setLeverageFocus:Ve,setCompareId:Ie,setPlane:ae,setPins:de,layout:Ot,pins:ue,setLayoutPreview:pe,setActiveLayers:se,setActiveLayer:le}),{select:Jt,switchPlane:Yt,activateLayer:Xt,toggleLayer:Zt,mergeSelectedLayers:Qt,toggleExpand:$t,resetView:en}=qt;yS({editing:mt,editor:gt,layoutApiRef:vt,activePlane:Mt,activePlaneBorrowsContainment:It,activePlaneManual:Rt,penLayer:Vt,selection:Se,multiSelection:Me,select:Jt});let{compareSelect:tn,groupSelected:nn}=qt,rn={notation:Nt,plane:Mt,borrowsContainment:It,penLayer:Vt},an=(e,t)=>{let n=gt.peek()?.state.model;if(!mt||n===void 0)return!1;let r=Tle(n,e,rn,t);if(r===void 0)return!1;let i=Yr(n,Mt),a=Ot?.sizes?.[e];return gt.dispatch(Ele(r,{pinned:Rt||Ot?.planes[i]?.[e]!==void 0,source:vt.current?.snapshotPositions()[e],width:a?.w??qr.width,...a===void 0?{}:{size:a},plane:Mt})),Jt({kind:`node`,id:r.id}),Oe(r.id),!0},on=Mt===void 0?{}:{plane:Mt},cn=e=>{let t=gt.peek()?.state.model;if(t===void 0)return;let n=ln(t,e);if(n===void 0)return;let r=`node`in e?t.nodes.find(t=>t.id===e.node)?.type:t.relations.find(t=>t.id===e.relation)?.kind,i=un(n);gt.dispatch({type:`batch`,commands:[{type:`add-threat`,target:e,threat:{id:i,category:pn(r)[0]??`S`,title:sn}},{type:`set-note-open`,target:e,open:!0,...on}]}),je(e,i)},dn=(e,t,n)=>{let r=gt.peek()?.state.model,i=r===void 0?void 0:ln(r,e)?.find(e=>e.id===t);if(i!==void 0){if(n===``){i.title===`New threat`&>.dispatch({type:`remove-threat`,target:e,id:t});return}n!==i.title&>.dispatch({type:`update-threat`,target:e,id:t,patch:{title:n}})}},fn=(e,t,n)=>gt.dispatch({type:`update-threat`,target:e,id:t,patch:{status:n}}),mn=(e,t,n,r)=>{let i=gt.peek()?.state.model,a=i===void 0?void 0:ln(i,e)?.find(e=>e.id===t);a!==void 0&&(a[n]??``)!==r&>.dispatch({type:`update-threat`,target:e,id:t,patch:{[n]:r===``?null:r}})},hn=Dt!==void 0&&Ot!==void 0&&Sn(Dt,Ot,Yr(Dt,Mt)),gn=Dt!==void 0&&(Dt.nodes.some(e=>(e.threats?.length??0)>0)||Dt.relations.some(e=>(e.threats?.length??0)>0)),_n=Dt!==void 0&&(Nt===`threat-model`||gn),vn=sce({editing:mt,selected:tt,current:Tt,names:n,ownedNames:i,setOwnedNames:a,setDrafts:o,setLoaded:s,setSources:c,setSelected:nt,setEnteredPath:it,setEditing:ht,leaveEdit:wt,resetView:en,editor:gt}),{addNode:yn,createAt:bn,placeFromLibrary:xn,applyFromLibrary:Cn,dropLibraryEntry:wn,addImages:Tn}=rce({editor:gt,layoutApiRef:vt,setSelection:Ce,setRenameId:Te,setLeftTab:Ue,requestLabelEdit:Oe,setSaveIssues:bt,activePlane:Mt,activePlaneBorrowsContainment:It,activePlaneManual:Rt,penLayer:Vt,selection:Se,drillRoot:ot,model:Dt,lib:$e,notation:Nt,today:Pt}),En=async(e,t)=>{try{let n=await bS(t),r=RS(t.name,new Set($e.library.entries.map(e=>e.id)),`icon`),i=t.name.replace(/\.[^.]*$/,``)||`icon`;$e.addEntry({id:r,category:e,name:i,template:{type:`image`,image:n,width:64,height:64}})}catch(e){bt([{message:Ar(e)}])}},Dn=async(e,t)=>{try{let n=await bS(t),r=RS(t.name,new Set($e.library.entries.map(e=>e.id)),`shape`),i=t.name.replace(/\.[^.]*$/,``)||`shape`;$e.addEntry({id:r,category:e,name:i,template:{shape:n}})}catch(e){bt([{message:Ar(e)}])}},On=async()=>{let e=tt;try{let t=await Kx().apiFetch(`/api/diagrams/${e}`);if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(st.current!==e)return;pe({}),Ct(e,n.model,n.layout??Jr(),n.drawings??Er())}catch(t){if(st.current!==e)return;bt([{message:`Could not load '${e}' for editing: ${Ar(t)}`}])}},kn=()=>{gt.session?.state.model!==void 0&&(Rt?gt.dispatch({type:`set-plane-layout`,manual:!1,...on}):(gt.dispatch({type:`set-positions`,positions:vt.current?.snapshotPositions()??{},...on}),gt.dispatch({type:`set-plane-layout`,manual:!0,...on})))},An=e=>{gt.session?.state.model!==void 0&>.dispatch({type:`set-layout-settings`,patch:e,...Mt===void 0?{}:{plane:Mt}})},jn=(0,v.useCallback)(async e=>{ye(!0);try{let t=await Kx().apiFetch(`/api/layouts/${tt}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json();return bt(e.issues??[{message:`Could not save layout`}]),!1}return s(t=>{let n=t[tt];return n===void 0?t:{...t,[tt]:{...n,layout:e}}}),bt(null),!0}finally{ye(!1)}},[tt,s,bt]),Mn=Dt===void 0?``:(Ot?.unfolded?.[Yr(Dt,Mt)]??[]).join(`\0`),Nn=(0,v.useRef)(null);(0,v.useEffect)(()=>{let e=Nn.current;Nn.current=mt?Mn:null,!(!mt||e===null||e===Mn||Dt===void 0)&&de(e=>KS(e).join(`\0`)===Mn?e:Xr(Ot,Dt,Mt))},[mt,Mn]);let Pn=(0,v.useMemo)(()=>KS(ue),[ue]),Fn=Dt!==void 0&&Pn.join(`\0`)!==Mn,In=Object.keys(me).length>0||Object.keys(ge).length>0||Fn,Ln=(0,v.useCallback)(async()=>{Dt===void 0||!In||await jn(lce(Ot,Dt,Mt,me,Pn,ge))&&(he({}),_e({}))},[Dt,me,ge,In,Pn,Ot,Mt,jn]),Rn=(0,v.useCallback)(async()=>{if(Dt===void 0)return;let e=!Rt,t=e?vt.current?.snapshotPositions()??{}:null;await jn(uce(Ot,Dt,Mt,t,e?Pn:void 0,e?ge:{}))&&e&&(he({}),_e({}))},[Dt,Ot,Mt,Rt,vt,jn,Pn,ge]),zn=(0,v.useCallback)(e=>{if(Dt===void 0)return;let t=Yr(Dt,Mt);pe(n=>PC(n,t,e))},[Dt,Mt]),Bn=mt&&Dt!==void 0?YS(Dt,Se,gt.dispatch):null,Vn=Se?.kind===`node`&&Dt!==void 0?Ot?.planes[Yr(Dt,Mt)]?.[Se.id]:void 0,Hn=Se?.kind===`node`&&Dt!==void 0?vt.current?.snapshotPositions()[Se.id]:void 0,Wn=(e,t)=>e?t:void 0,Gn=i.has(tt),Kn=!mt&&Dt!==void 0,qn=Dt!==void 0&&Object.keys(Ot?.planes[Yr(Dt,Mt)]??{}).length>0,Jn=e=>Wn(Dt!==void 0,()=>te.current!==null&&e(te.current)),Yn=e=>()=>rt.length>0?!1:(lt(e),!0);re.current={"diagram.picker":()=>ne.current?.(),"diagram.toggle-edit":Wn(Dt!==void 0&&Gn,()=>void(mt?wt():On())),"diagram.rename":Wn(l&&!mt&&Gn,()=>void vn.renameDiagram()),"diagram.new":Wn(l,()=>void vn.newDiagram()),"diagram.duplicate":Wn(l&&Kn,()=>void vn.duplicateDiagram()),"diagram.eject":Wn(l&&!mt&&Gn,()=>void vn.ejectDiagram()),"edit.add-node":Wn(mt,()=>yn()),"edit.add-child":Wn(mt,()=>Se?.kind===`node`&&an(Se.id)),"edit.undo":Wn(mt,()=>gt.undo()),"edit.redo":Wn(mt,()=>gt.redo()),"edit.save":Wn(mt,()=>void St()),"edit.group":Wn(mt&&Me.length>=2,()=>void nn()),"edit.relayout":Wn(mt,()=>void DC(gt,{autoLayout:!Rt,activePlane:Mt,getAutoPositions:()=>vt.current?.autoPositions()??{}})),"edit.toggle-auto-layout":Wn(mt,kn),"edit.toggle-notes":Wn(mt&&_n&&gn,()=>gt.dispatch({type:`set-notes-open`,open:!hn,...on})),"tool.select":Wn(mt,()=>lt(`select`)),"tool.pen":Wn(mt,Yn(`pen`)),"tool.eraser":Wn(mt,Yn(`eraser`)),"pen.thin":Wn(mt&&ct===`pen`,()=>pt(2)),"pen.medium":Wn(mt&&ct===`pen`,()=>pt(3)),"pen.thick":Wn(mt&&ct===`pen`,()=>pt(6)),"canvas.fit":Jn(e=>e.fitView()),"canvas.zoom-in":Jn(e=>e.zoomIn()),"canvas.zoom-out":Jn(e=>e.zoomOut()),"canvas.laser":Jn(e=>e.toggleLaser()),"canvas.legend":Jn(e=>e.toggleLegend()),"canvas.dim":Jn(e=>e.toggleDim()),"canvas.drawings":Jn(e=>e.toggleDrawings()),"canvas.loops":Jn(e=>e.toggleLoops()),"view.freeze":Wn(Kn&&!ve&&rt.length===0,()=>void Rn()),"view.save-positions":Wn(Kn&&In&&!ve,()=>void Ln()),"view.auto-arrange":Wn(Kn&&qn,()=>xe(e=>!e)),"arrange.align-left":Jn(e=>e.align(`left`)),"arrange.align-center":Jn(e=>e.align(`centerX`)),"arrange.align-right":Jn(e=>e.align(`right`)),"arrange.align-top":Jn(e=>e.align(`top`)),"arrange.align-middle":Jn(e=>e.align(`middle`)),"arrange.align-bottom":Jn(e=>e.align(`bottom`)),"arrange.distribute-x":Jn(e=>e.distribute(`x`)),"arrange.distribute-y":Jn(e=>e.distribute(`y`)),"window.left-dock":Wn(Dt!==void 0,()=>Ke(e=>!e)),"window.right-dock":Wn(Dt!==void 0,()=>Je(e=>!e)),"window.inspector-properties":Wn(mt,()=>{Ue(`properties`),Ke(!1)}),"window.inspector-library":Wn(mt,()=>{Ue(`library`),Ke(!1)}),"window.theme":()=>d(e=>e===`dark`?`light`:`dark`),"window.snap":()=>h(e=>!e),"window.hotkeys":()=>C(!0)},lue({rootRef:E,keymap:y,mode:mt?`edit`:`view`,handlersRef:re,suspended:S,mac:T});let Xn=e=>bC(y,e,T),Zn=[...Gn?[{id:`rename`,label:`Rename`,title:`Rename this diagram${Xn(`diagram.rename`)}`,onSelect:()=>void vn.renameDiagram()}]:[],...Dt===void 0?[]:[{id:`export-png`,label:`Export PNG`,title:`Save the canvas as drawn — folds, layers, theme and drawings — as a PNG image`,onSelect:()=>void Dce(vt.current,tt??``)},{id:`duplicate`,label:`Duplicate`,title:`Copy this diagram — layout and all — to a new editable one and open it${Xn(`diagram.duplicate`)}`,onSelect:()=>void vn.duplicateDiagram()}],...Gn?[{id:`eject`,label:`Eject`,title:`Promote this diagram to a TypeScript source — it becomes read-only here${Xn(`diagram.eject`)}`,onSelect:()=>void vn.ejectDiagram()}]:[]],Qn=(0,v.useMemo)(()=>({keymap:y,mac:T}),[y,T]),$n=(0,v.useMemo)(()=>({laser:yC(y,`canvas.laser`,T),dim:yC(y,`canvas.dim`,T),legend:yC(y,`canvas.legend`,T),drawings:yC(y,`canvas.drawings`,T),loops:yC(y,`canvas.loops`,T)}),[y,T]);return(0,D.jsx)(vC.Provider,{value:Qn,children:(0,D.jsxs)(`div`,{className:`app`,ref:E,children:[(0,D.jsxs)(`header`,{className:`topbar`,children:[(0,D.jsx)(`strong`,{className:`brand`,children:`diagc studio`}),(0,D.jsx)(Tce,{names:n,selected:tt,onSelect:e=>{wt()&&(nt(e),it([]),en())},toggleRef:ne}),l&&(0,D.jsx)(`button`,{type:`button`,className:`chip icon`,"aria-label":`New diagram`,title:`New diagram${Xn(`diagram.new`)}`,onClick:()=>void vn.newDiagram(),children:`+`}),l&&!mt&&(0,D.jsx)(Nce,{label:`Diagram actions`,items:Zn,children:`⋯`}),Dt!==void 0&&(Gn?!mt&&(0,D.jsx)(`button`,{className:`chip`,onClick:()=>void On(),title:`Edit this diagram${Xn(`diagram.toggle-edit`)}`,children:`Edit`}):(0,D.jsx)(`span`,{className:`chip read-only`,title:`Compiled from TypeScript — edit the source`,children:`read-only`})),(0,D.jsx)(`span`,{className:`spacer`}),!mt&&Dt!==void 0&&In&&(0,D.jsx)(`button`,{className:`chip primary`,disabled:ve,title:`Write the boxes and edge labels you moved, and which groups are open, to this diagram's layout file. Safe on a generated diagram: re-compiling rewrites the model, never the layout.${Xn(`view.save-positions`)}`,onClick:()=>void Ln(),children:ve?`Saving…`:`Save positions`}),mt&&_n&&(0,D.jsx)(`button`,{type:`button`,className:`chip${hn?` active`:``}`,"aria-pressed":hn,disabled:!gn,title:`${hn?`Close all threat notes`:`Open all threat notes`}${Xn(`edit.toggle-notes`)}`,onClick:()=>gt.dispatch({type:`set-notes-open`,open:!hn,...on}),children:`Notes`}),(0,D.jsx)(`span`,{className:`sep`}),(0,D.jsx)(`button`,{type:`button`,className:`chip icon${m?` active`:``}`,"aria-label":`Snap to grid`,"aria-pressed":m,title:`${m?`Snapping to a ${EE}px grid. Click to place boxes freely.`:`Snap dragged boxes to a ${EE}px grid; arrow keys step by it too.`}${Xn(`window.snap`)}`,onClick:()=>h(e=>!e),children:`⋮⋮`}),(0,D.jsx)(`button`,{type:`button`,className:`chip icon`,"aria-label":u===`dark`?`Switch to light theme`:`Switch to dark theme`,title:`${u===`dark`?`Light theme`:`Dark theme`}${Xn(`window.theme`)}`,onClick:()=>d(u===`dark`?`light`:`dark`),children:u===`dark`?`☀`:`☾`}),(0,D.jsx)(`button`,{ref:ee,type:`button`,className:`chip icon`,"aria-label":`Keyboard shortcuts`,title:`Keyboard shortcuts${Xn(`window.hotkeys`)}`,onClick:()=>C(!0),children:`⚙`}),(0,D.jsx)(`a`,{className:`chip source-link`,href:kr,target:`_blank`,rel:`noreferrer`,title:`diagc is free software under the AGPL-3.0 — get the source`,children:`source`})]}),mt&&(0,D.jsx)(EC,{editor:gt,onExit:wt,onSave:()=>void St(),saving:xt,saveIssues:yt,selectionColor:Bn,tool:ct,onSetTool:lt,pen:{color:ut,width:ft},onSetPen:e=>{e.color!==void 0&&dt(e.color),e.width!==void 0&&pt(e.width)},drawingDisabled:rt.length>0}),n.length===0&&(0,D.jsx)(`div`,{className:`banner`,children:l?(0,D.jsxs)(D.Fragment,{children:[`No diagrams yet — use `,(0,D.jsx)(`b`,{children:`New diagram`}),` to create one.`]}):(0,D.jsxs)(D.Fragment,{children:[`No artifacts found — run `,(0,D.jsx)(`code`,{children:`pnpm compile`}),` (or `,(0,D.jsx)(`code`,{children:`pnpm compile:watch`}),`) first.`]})}),!mt&&Tt!==void 0&&Tt.issues.length>0&&(0,D.jsxs)(`div`,{className:`banner error`,children:[(0,D.jsx)(`b`,{children:Tt.name}),` failed validation:`,(0,D.jsx)(`ul`,{children:Tt.issues.map((e,t)=>(0,D.jsx)(`li`,{children:e.message},t))})]}),!mt&&yt!==null&&yt.length>0&&(0,D.jsx)(`div`,{className:`banner error`,children:(0,D.jsx)(`ul`,{children:yt.map((e,t)=>(0,D.jsx)(`li`,{children:e.message},t))})}),(0,D.jsx)(`main`,{className:`body`,children:Dt!==void 0&&(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(rT,{side:`left`,collapsed:Ge,onToggle:()=>Ke(e=>!e),hasContent:mt?!0:Se!==null,width:Ye,minWidth:AE,maxWidth:kE,onWidthChange:Xe,children:mt?(0,D.jsx)(tT,{activeTab:He,onTabChange:Ue,properties:Se?.kind===`node`&&Dt.nodes.some(e=>e.id===Se.id)?(0,D.jsx)(Ow,{model:Dt,nodeId:Se.id,activePlane:Mt,hasPin:Vn!==void 0,...Vn===void 0?{}:{pinned:Vn},...Hn===void 0?{}:{live:Hn},autoFocusName:Se.id===we,...Nt===void 0?{}:{notation:Nt},today:Pt,onCommand:gt.dispatch,onClose:()=>Jt(null),onDeleted:()=>Jt(null)},Se.id):Se?.kind===`edge`?(0,D.jsx)(Mw,{model:Dt,constituentIds:Se.constituentIds??[Se.id],onCommand:gt.dispatch,onClose:()=>Jt(null),...Nt===void 0?{}:{notation:Nt},...Mt===void 0?{}:{activePlane:Mt}},Se.id):(0,D.jsx)($le,{model:Dt,selection:Se}),library:(0,D.jsx)(aue,{library:$e.library,onPlace:xn,onApply:Cn,...PE(Dt,Se)??{},onAddNode:yn,onAddImages:e=>void Tn(e),onAddCategory:$e.addCategory,onDeleteCategory:$e.deleteCategory,onImportIcon:(e,t)=>void En(e,t),onImportShape:(e,t)=>void Dn(e,t),assetBase:Kx().assetBase,viewState:We})}):Nt===`causal-loop`&&Se?.kind===`node`&&Dt.nodes.some(e=>e.id===Se.id)?(0,D.jsx)(sy,{model:Dt,edges:Le,target:Se.id,activeFocusKey:Be?.key??null,onFocus:Ve,onClose:()=>Jt(null),compareId:Fe,onClearCompare:()=>Ie(null)},Se.id):Se===null?(0,D.jsx)(`div`,{className:`sidebar dock-empty`,children:`Select a node or edge for details.`}):(0,D.jsx)($le,{model:Dt,selection:Se})}),(0,D.jsxs)(`div`,{className:`canvas-area`,children:[(0,D.jsx)(Gse,{model:Dt,plane:Mt,today:Pt,activeLayers:oe,onToggleLayer:Zt,pins:ue,onToggleExpand:$t,onSelect:Jt,onMultiSelect:Pe,onEnteredPathChange:at,enteredPath:rt,onCompareSelect:tn,colorMode:u,assetBase:Kx().assetBase,...Kx().libraryBase===void 0?{}:{libraryBase:Kx().libraryBase},onOpenLink:e=>Kx().openLink(e),styleId:At??f,...m?{snapGrid:EE}:{},onCldEdges:ze,onViewPositionsChange:he,onViewLabelMovesChange:_e,layoutApiRef:vt,canvasCommandsRef:te,builtinKeys:!1,keyHints:$n,ignoreSavedPositions:be,externalHighlight:mt?Me.length>=2?{nodes:Me,edges:[]}:null:Be??(Fe!==null&&Se?.kind===`node`?{nodes:[Se.id,Fe],edges:[]}:null),...Nt===void 0?{}:{notation:Nt},...zt===void 0?{}:{layout:zt},...kt===void 0?{}:{drawings:kt},...mt?{mode:`edit`,tool:ct,pen:{...ut===``?{}:{color:ut},width:ft},edit:{...Ee===void 0?{}:{editLabelRequest:Ee},...ke===void 0?{}:{editThreatRequest:ke},onNoteMoved:(e,t)=>gt.dispatch({type:`set-note-offset`,target:e,offset:t,...on}),onToggleNote:(e,t)=>gt.dispatch({type:`set-note-open`,target:e,open:t,...on}),onAddThreat:cn,onRetitleThreat:dn,onSetThreatStatus:fn,onEditThreatText:mn,quickAdd:{label:(e,t)=>Dt===void 0?void 0:wle(Dt,e,rn,t),run:an},onNodesMoved:(e,t)=>{if(Nt===`plan`&&Dt!==void 0){let n=AS(Dt,Mt,e,t);n!==void 0&>.dispatch(n);return}gt.dispatch({type:`set-positions`,positions:e,...Mt===void 0?{}:{plane:Mt}})},onDropInto:(e,t,n)=>{if(Nt===`plan`&&Dt!==void 0){let r=$se(Dt,Mt,e,t,n);r!==void 0&>.dispatch(r)}},onMoveLane:(e,t,n)=>{let r=Vw(e,t,n,Mt);r!==null&>.dispatch(r)},onSetRole:(e,t,n)=>{if(Dt===void 0)return;let r=Zse(Dt,e,t,n);r!==void 0&>.dispatch(r)},onCreateAt:e=>bn(e),onImageFiles:(e,t)=>void Tn(e,t),onDropLibraryEntry:wn,onResize:(e,t,n,r)=>{if(Nt===`plan`&&Dt!==void 0){let n=Dt.nodes.find(t=>t.id===e);if(n!==void 0&&Un(n)){let n=jS(Dt,Mt,e,r.x,t);n!==void 0&>.dispatch(n);return}}gt.dispatch({type:`set-size`,nodeId:e,w:t,h:n}),gt.dispatch({type:`set-position`,nodeId:e,x:r.x,y:r.y,...Mt===void 0?{}:{plane:Mt}})},onConnect:(e,t,n)=>{let r=gt.session?.state.model,i=r===void 0?null:sue(r,e,t,n,Vt===null?void 0:{layer:Vt});if(i!==null){for(let e of i)gt.dispatch(e);return}gt.dispatch({type:`add-relation`,from:e,to:t,opts:{kind:Xw(Nt,r,e,t),...Vt===null?{}:{layer:Vt}}})},onDeleteSelection:e=>{let t=gt.peek()?.state.model,n=t===void 0?null:bE(t,e);n!==null&&(gt.dispatch(n),Jt(null))},onSetTableColumns:(e,t)=>gt.dispatch({type:`set-table-columns`,id:e,columns:t}),onRenameNode:(e,t)=>gt.dispatch({type:`rename-node`,id:e,name:t}),onSetNodeRich:(e,t)=>gt.dispatch({type:`set-node-rich`,id:e,runs:t}),onAddEdgeLabel:Ut,onEditEdgeLabel:Wt,onMoveEdgeLabel:Gt,onReconnect:(e,t,n,r)=>gt.dispatch({type:`update-relation`,id:e,patch:{from:t,to:n,...r===void 0?{}:{style:Ht(e,r.end,r.side)}}}),onSetEdgeSide:(e,t,n)=>gt.dispatch({type:`update-relation`,id:e,patch:{style:Ht(e,t,n)}}),onAddStroke:e=>{let t=gt.peek()?.state.drawings,n=gt.peek()?.state.model;t===void 0||n===void 0||gt.dispatch({type:`add-stroke`,stroke:{id:Dr(t,Yr(n,Mt)),...e},...Mt===void 0?{}:{plane:Mt}})},onDeleteStroke:e=>gt.dispatch({type:`delete-stroke`,id:e,...Mt===void 0?{}:{plane:Mt}})}}:{}}),mt&&Me.length>=2&&(0,D.jsxs)(`button`,{className:`chip group-action`,title:`Group the selection${Xn(`edit.group`)}`,onClick:()=>void nn(),children:[`⊞ Group `,Me.length]})]}),(0,D.jsxs)(rT,{side:`right`,collapsed:qe,onToggle:()=>Je(e=>!e),hasContent:!0,width:Ze,minWidth:jE,maxWidth:kE,onWidthChange:Qe,children:[mt&&Nt===`git-graph`&&(0,D.jsx)(ule,{model:Dt,plane:Mt,selection:Se,onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e})}),mt&&Nt===`plan`&&(0,D.jsx)(Yw,{model:Dt,plane:Mt,selection:Se,onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e}),today:Pt}),mt&&Nt===`second-order`&&(0,D.jsx)(hle,{model:Dt,selection:Se,...Mt!==void 0&&!It?{plane:Mt}:{},onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e}),onCreated:Oe}),mt&&Nt===`fishbone`&&(0,D.jsx)(yle,{model:Dt,selection:Se,...Mt!==void 0&&!It?{plane:Mt}:{},onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e}),onCreated:Oe}),Nt===`threat-model`&&(0,D.jsx)(qw,{model:Dt,...Mt===void 0?{}:{plane:Mt},onSelect:Jt}),mt&&(0,D.jsx)(Hw,{model:Dt,plane:Mt,selection:Se,onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e})}),(0,D.jsxs)(Mce,{controls:Eh(Nt).layout===void 0?{settings:Bt,onChange:mt?An:zn,defaultDirection:_t(Dt),algorithmLocked:Ft,...Eh(Nt).defaultAlgorithm===void 0?{}:{defaultAlgorithm:Eh(Nt).defaultAlgorithm}}:null,styleControl:mt?(0,D.jsxs)(`select`,{className:`chip-select`,"aria-label":`Diagram style`,title:`Diagram style (saved with the diagram)`,value:At??``,onChange:e=>gt.dispatch({type:`set-diagram-style`,style:e.target.value===``?null:e.target.value}),children:[(0,D.jsx)(`option`,{value:``,children:`(app default)`}),Ev.map(e=>(0,D.jsx)(`option`,{value:e.id,children:e.label},e.id))]}):(0,D.jsx)(`select`,{className:`chip-select`,"aria-label":`Style`,title:At===void 0?`Visual style`:`Set by diagram`,value:At??(Ov(f)?f:`clean`),disabled:At!==void 0,onChange:e=>p(e.target.value),children:Ev.map(e=>(0,D.jsx)(`option`,{value:e.id,children:e.label},e.id))}),children:[mt&&(0,D.jsx)(OC,{editor:gt,activePlane:Mt,autoLayout:!Rt,onToggleAutoLayout:kn,getAutoPositions:()=>vt.current?.autoPositions()??{}}),!mt&&fe[Yr(Dt,Mt)]!==void 0&&(0,D.jsx)(`button`,{className:`chip`,title:`Drop the preview and go back to this diagram's own layout settings`,onClick:()=>pe(e=>{let t={...e};return delete t[Yr(Dt,Mt)],t}),children:`Reset layout`}),!mt&&Object.keys(Ot?.planes[Yr(Dt,Mt)]??{}).length>0&&(0,D.jsx)(`button`,{type:`button`,className:`chip${be?` active`:``}`,"aria-pressed":be,title:`${be?`Ignoring this diagram’s saved positions, so the layout algorithm arranges every node. Click to put them back.`:`This plane has saved positions, which override the layout algorithm. Click to arrange those nodes automatically instead (nothing is written).`}${Xn(`view.auto-arrange`)}`,onClick:()=>xe(e=>!e),children:`Auto-arrange`}),!mt&&(0,D.jsx)(`button`,{type:`button`,className:`chip${Rt?` active`:``}`,"aria-pressed":Rt,disabled:ve||rt.length>0,title:`${rt.length>0?`Freezing pins the whole plane, but a drilled view only has positions for what it shows — leave the drilled view first.`:Rt?`Positions are pinned. Click to let the layout algorithm arrange this plane again (your positions are kept).`:`Pin every box where it is so the layout algorithm stops moving them. Boxes added to the source later are still placed automatically until you move them.`}${Xn(`view.freeze`)}`,onClick:()=>void Rn(),children:`Freeze layout`})]}),(0,D.jsx)(Bw,{model:Dt,onCommand:gt.dispatch,mode:mt?`edit`:`view`,activeLayer:Vt,onActivateLayer:Xt,activePlane:Mt,onSelectPlane:e=>e===void 0?en():Yt(e),activeLayers:oe,onToggleLayer:Zt,onMergeLayers:Qt})]})]})}),S&&(0,D.jsx)(CE,{overrides:g,onChange:_,onClose:()=>{C(!1),ee.current?.focus()},mac:T})]})})}var hue=document.getElementById(`root`);hue&&(0,y.createRoot)(hue).render((0,D.jsx)(mue,{}));
|
|
109
|
+
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+QT(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function fE(e,t){return dE.parse(e,t)}fE.options=fE.setOptions=function(e){return dE.setOptions(e),fE.defaults=dE.defaults,oT(fE.defaults),fE},fE.getDefaults=iT,fE.defaults=aT,fE.use=function(...e){return dE.use(...e),fE.defaults=dE.defaults,oT(fE.defaults),fE},fE.walkTokens=function(e,t){return dE.walkTokens(e,t)},fE.parseInline=dE.parseInline,fE.Parser=lE,fE.parser=lE.parse,fE.Renderer=sE,fE.TextRenderer=cE,fE.Lexer=oE,fE.lexer=oE.lex,fE.Tokenizer=aE,fE.Hooks=uE,fE.parse=fE,fE.options,fE.setOptions,fE.use,fE.walkTokens,fE.parseInline,lE.parse,oE.lex;function Qle({metadata:e}){let t=Object.entries(e);return t.length===0?null:(0,D.jsx)(`dl`,{className:`meta`,children:t.map(([e,t])=>(0,D.jsxs)(`div`,{className:`meta-row`,children:[(0,D.jsx)(`dt`,{children:e}),(0,D.jsx)(`dd`,{children:typeof t==`string`&&/^https?:\/\//.test(t)?(0,D.jsx)(`a`,{href:t,target:`_blank`,rel:`noreferrer`,children:t}):String(t)})]},e))})}function $le({model:e,selection:t}){if(t===null)return(0,D.jsx)(`aside`,{className:`sidebar muted`,children:`Select a node or edge for details.`});if(t.kind===`node`){let n=e.nodes.find(e=>e.id===t.id);return n?(0,D.jsxs)(`aside`,{className:`sidebar`,children:[(0,D.jsx)(`h2`,{children:n.name}),(0,D.jsxs)(`p`,{className:`muted`,children:[n.type,` · `,(0,D.jsx)(`code`,{children:n.id})]}),n.description!==void 0&&(0,D.jsx)(`div`,{dangerouslySetInnerHTML:{__html:fE.parse(n.description)}}),n.metadata!==void 0&&(0,D.jsx)(Qle,{metadata:n.metadata})]}):(0,D.jsx)(`aside`,{className:`sidebar muted`,children:`Aggregate node (zoom in for details).`})}let[n]=t.id.split(`:`),[r,i]=(n??``).split(`=>`),a=new Set(t.constituentIds??[]),o=e.relations.filter(e=>a.has(e.id));return(0,D.jsxs)(`aside`,{className:`sidebar`,children:[(0,D.jsxs)(`h2`,{children:[r,` → `,i]}),o.length===0?(0,D.jsx)(`p`,{className:`muted`,children:`No relation details available.`}):(0,D.jsx)(`ul`,{children:o.map(e=>(0,D.jsxs)(`li`,{children:[(0,D.jsx)(`code`,{children:e.from}),` → `,(0,D.jsx)(`code`,{children:e.to}),` `,(0,D.jsx)(`b`,{children:e.kind}),e.label===void 0?``:` — ${e.label}`,e.description!==void 0&&(0,D.jsx)(`div`,{dangerouslySetInnerHTML:{__html:fE.parse(e.description)}})]},e.id))})]})}var pE=xi(),eue=Ty(),tue={query:``,toggled:{},groupToggled:{}},mE=(e,t)=>{let{libraryBase:n}=Kx();return n!==void 0&&t.startsWith(`/library/`)?`${n}${t.slice(9)}`:t.startsWith(`/`)||/^https?:/.test(t)?t:`${e}${t}`},nue=16,rue=64;function iue(e){let t=[],n=new Map;for(let r of e){if(r.group===void 0){t.push({cats:[r]});continue}let e=n.get(r.group);e===void 0&&(e={group:r.group,cats:[]},n.set(r.group,e),t.push(e)),e.cats.push(r)}return t}function hE({entry:e,assetBase:t}){if(e.template.image!==void 0)return(0,D.jsx)(`img`,{className:`lib-thumb`,src:mE(t,e.template.image),alt:e.name,draggable:!1});if(e.template.shape!==void 0){let n=`url("${mE(t,e.template.shape)}")`;return(0,D.jsx)(`span`,{className:`lib-thumb lib-shape-thumb`,"aria-hidden":`true`,style:{WebkitMaskImage:n,maskImage:n,background:e.template.color??`var(--dg-text-muted)`}})}let n=e.template.color??`var(--dg-border)`,r=e.template.type===void 0?void 0:pE.resolve(e.template.type),i=r?.icon===void 0?void 0:eue.resolve(r.icon),a=r?.outline===!0||r?.dashed===!0;return(0,D.jsx)(`span`,{className:`lib-swatch lib-swatch-${r?.shape??`box`}${a?` lib-swatch-outline`:``}`,style:a?{border:`1.5px ${r?.dashed===!0?`dashed`:`solid`} ${n}`,color:n}:{background:n},children:i!==void 0&&(0,D.jsx)(i,{size:14,className:`lib-swatch-icon`})})}function aue({library:e,onPlace:t,onApply:n,applyTarget:r,onAddNode:i,onAddImages:a,onAddCategory:o,onDeleteCategory:s,onImportIcon:c,onImportShape:l,assetBase:u=`/api/assets/`,viewState:d}){let f=(0,v.useState)(tue),[{query:p,toggled:m,groupToggled:h},g]=d??f,_=e=>g(t=>({...t,query:e})),[y,b]=(0,v.useState)(``),[x,S]=(0,v.useState)(`place`),C=(0,v.useMemo)(()=>nce(e,p),[e,p]),w=(0,v.useMemo)(()=>{let e=new Map;for(let t of C){let n=e.get(t.category);n===void 0?e.set(t.category,[t]):n.push(t)}return e},[C]),T=p.trim()!==``,E=(0,v.useMemo)(()=>iue(e.categories),[e.categories]),ee=r!==void 0&&n!==void 0,te=ee&&x===`apply`;(0,v.useEffect)(()=>{S(`place`)},[r?.id]);let ne=()=>{let e=y.trim();e===``||o===void 0||(o(e),b(``))};return(0,D.jsxs)(`aside`,{className:`sidebar lib-panel`,children:[(0,D.jsx)(`div`,{className:`panel-head`,children:(0,D.jsx)(`h3`,{children:`Library`})}),(i!==void 0||a!==void 0)&&(0,D.jsxs)(`div`,{className:`lib-actions`,children:[i!==void 0&&(0,D.jsx)(`button`,{type:`button`,className:`chip`,onClick:i,children:`Add node`}),a!==void 0&&(0,D.jsxs)(`label`,{className:`chip icon-btn`,title:`Add image`,children:[`Add image`,(0,D.jsx)(`input`,{type:`file`,accept:`image/*`,multiple:!0,hidden:!0,"aria-label":`Add image`,onChange:e=>{let t=[...e.target.files??[]];t.length>0&&a(t),e.target.value=``}})]})]}),ee&&(0,D.jsxs)(`div`,{className:`lib-apply-toggle`,role:`group`,"aria-label":`Card click action`,children:[(0,D.jsx)(`button`,{type:`button`,className:`chip${te?``:` active`}`,"aria-pressed":!te,title:`Clicking a card adds a new node`,onClick:()=>S(`place`),children:`Place new`}),(0,D.jsxs)(`button`,{type:`button`,className:`chip${te?` active`:``}`,"aria-pressed":te,title:`Clicking a card restyles ${r.name} to match it`,onClick:()=>S(`apply`),children:[`Apply to `,r.name]})]}),(0,D.jsx)(`input`,{className:`lib-search`,type:`search`,"aria-label":`Search library`,placeholder:`Search nodes…`,value:p,onChange:e=>_(e.target.value)}),E.map(e=>{let i=e=>{let i=w.get(e.id)??[];if(i.length===0&&(T||e.builtin===!0))return null;let a=m[e.id]??(T||i.length<=nue);return(0,D.jsxs)(`section`,{className:`lib-category`,children:[(0,D.jsxs)(`div`,{className:`lib-cat-head`,children:[(0,D.jsx)(`h4`,{className:`lib-cat-name`,children:(0,D.jsxs)(`button`,{type:`button`,className:`lib-cat-toggle`,"aria-label":e.name,"aria-expanded":a,title:`${a?`Collapse`:`Expand`} ${e.name}`,onClick:()=>g(t=>({...t,toggled:{...t.toggled,[e.id]:!a}})),children:[(0,D.jsx)(`span`,{className:`lib-cat-caret`,"aria-hidden":`true`,children:a?`▾`:`▸`}),(0,D.jsx)(`span`,{className:`lib-cat-label`,children:e.name}),(0,D.jsx)(`span`,{className:`lib-cat-count`,children:i.length})]})}),e.builtin!==!0&&(0,D.jsxs)(`span`,{className:`lib-cat-actions`,children:[c!==void 0&&(0,D.jsxs)(`label`,{className:`chip icon-btn`,title:`Import icon into ${e.name}`,children:[`Icon`,(0,D.jsx)(`input`,{type:`file`,accept:`image/*`,hidden:!0,"aria-label":`Import icon into ${e.name}`,onChange:t=>{let n=t.target.files?.[0];n!==void 0&&c(e.id,n),t.target.value=``}})]}),l!==void 0&&(0,D.jsxs)(`label`,{className:`chip icon-btn`,title:`Import shape into ${e.name}`,children:[`Shape`,(0,D.jsx)(`input`,{type:`file`,accept:`.svg,image/svg+xml`,hidden:!0,"aria-label":`Import shape into ${e.name}`,onChange:t=>{let n=t.target.files?.[0];n!==void 0&&l(e.id,n),t.target.value=``}})]}),s!==void 0&&(0,D.jsx)(`button`,{type:`button`,className:`chip icon-btn`,"aria-label":`Delete category ${e.name}`,title:`Delete category ${e.name}`,onClick:()=>void Kx().confirmDialog(`Delete category '${e.name}' and its imported icons?`).then(t=>{t&&s(e.id)}),children:`✕`})]})]}),a&&(0,D.jsx)(`div`,{className:`lib-grid`,children:i.map(e=>(0,D.jsxs)(`button`,{type:`button`,className:`lib-entry`,"aria-label":te?`Apply ${e.name}`:`Place ${e.name}`,title:te?`Apply ${e.name} to ${r.name}`:`Place ${e.name}`,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(`application/x-dg-library-entry`,e.id),t.dataTransfer.effectAllowed=`copy`},onClick:()=>te?n(e):t(e),children:[(0,D.jsx)(hE,{entry:e,assetBase:u}),(0,D.jsx)(`span`,{className:`lib-entry-name`,children:e.name})]},e.id))})]},e.id)};if(e.group===void 0)return i(e.cats[0]);let a=e.group,o=e.cats.reduce((e,t)=>e+(w.get(t.id)??[]).length,0);if(o===0&&T)return null;let d=h[a]??(T||o<=rue);return(0,D.jsxs)(`section`,{className:`lib-group`,children:[(0,D.jsx)(`h4`,{className:`lib-cat-name lib-group-name`,children:(0,D.jsxs)(`button`,{type:`button`,className:`lib-cat-toggle`,"aria-label":a,"aria-expanded":d,title:`${d?`Collapse`:`Expand`} ${a}`,onClick:()=>g(e=>({...e,groupToggled:{...e.groupToggled,[a]:!d}})),children:[(0,D.jsx)(`span`,{className:`lib-cat-caret`,"aria-hidden":`true`,children:d?`▾`:`▸`}),(0,D.jsx)(`span`,{className:`lib-cat-label`,children:a}),(0,D.jsx)(`span`,{className:`lib-cat-count`,children:o})]})}),d&&(0,D.jsx)(`div`,{className:`lib-group-body`,children:e.cats.map(i)})]},`group:${a}`)}),o!==void 0&&(0,D.jsxs)(`div`,{className:`add-member`,children:[(0,D.jsx)(`input`,{"aria-label":`New category name`,placeholder:`New category…`,value:y,onChange:e=>b(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),ne())}}),(0,D.jsx)(`button`,{type:`button`,className:`chip`,"aria-label":`Add category`,onClick:ne,children:`+`})]})]})}var gE={categories:[],entries:[]};async function oue(){try{let e=await Kx().apiFetch(`/api/library`);if(!e.ok)return gE;let t=await e.json();return{categories:t.categories??[],entries:t.entries??[]}}catch{return gE}}async function _E(e){let t=await Kx().apiFetch(`/api/library`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>null);throw Error(e?.issues?.[0]?.message??`Library save failed (${t.status})`)}}var vE=new Set(ww.categories.map(e=>e.id));function yE(){let[e,t]=(0,v.useState)({categories:[],entries:[]}),n=(0,v.useRef)(e);n.current=e,(0,v.useEffect)(()=>{oue().then(t)},[]);let r=(0,v.useMemo)(()=>LS(ww,e),[e]),i=(0,v.useCallback)(e=>{t(e),_E(e).catch(()=>{})},[]);return{library:r,addCategory:(0,v.useCallback)(e=>{let t=n.current,r=RS(e,new Set(LS(ww,t).categories.map(e=>e.id)),`category`);i({...t,categories:[...t.categories,{id:r,name:e.trim()||r}]})},[i]),deleteCategory:(0,v.useCallback)(e=>{if(vE.has(e))return;let t=n.current;i({categories:t.categories.filter(t=>t.id!==e),entries:t.entries.filter(t=>t.category!==e)})},[i]),addEntry:(0,v.useCallback)(e=>{let t=n.current;i({...t,entries:[...t.entries,e]})},[i])}}function bE(e,t){let n=new Map(e.nodes.map(e=>[e.id,e.type])),r=new Set(e.relations.map(e=>e.id)),i=e=>oe.includes(n.get(e)??``),a=new Set;for(let r of t.nodeIds)if(!(!n.has(r)||!i(r)))for(let t of Fe(e,r))t!==r&&a.add(t);let o=[...t.relationIds.filter(e=>r.has(e)).map(e=>({type:`delete-relation`,id:e})),...t.nodeIds.filter(e=>n.has(e)&&!a.has(e)).map(e=>({type:`delete-node`,id:e,...i(e)?{cascade:!0}:{}}))];return o.length===0?null:o.length===1?o[0]:{type:`batch`,commands:o}}function sue(e,t,n,r,i){let a=e.nodes.find(e=>e.id===t);if(a?.type!==`db-table`||a.columns===void 0)return null;let o=a.columns.find(e=>e.name===r);if(o===void 0)return null;let s=e.nodes.find(e=>e.id===n)?.columns?.find(e=>e.pk===!0)?.name,c=[{type:`add-relation`,from:t,to:n,opts:{kind:`fk`,fromColumn:o.name,...s===void 0?{}:{toColumn:s},...i?.layer===void 0?{}:{layer:i.layer}}}];return o.fk!==!0&&c.push({type:`set-table-columns`,id:t,columns:a.columns.map(e=>e.name===o.name?{...e,fk:!0}:e)}),c}var xE=e=>e.map(e=>oC(e).label).join(`, `),SE=(e,t,n)=>{let r=[...sC(e)[t.id]];return r[t.index]=n,gC(e,t.id,r)};function CE({overrides:e,onChange:t,onClose:n,mac:r=rC()}){let i=(0,v.useMemo)(()=>sC(e),[e]),[a,o]=(0,v.useState)(``),[s,c]=(0,v.useState)(null),[l,u]=(0,v.useState)(null),[d,f]=(0,v.useState)(null),p=(0,v.useRef)(null);(0,v.useEffect)(()=>{p.current?.focus()},[]);let m=e=>nC(e,r),h=e=>{f(null),u(null),c(e)},g=a=>{if(s===null){if(a.key!==`Escape`)return;a.stopPropagation(),l===null?n():u(null);return}if(a.preventDefault(),a.stopPropagation(),a.key===`Escape`){c(null);return}let o=QS(a.nativeEvent,r);if(o===null)return;c(null);let d=hC(o);if(d!==null){f(`${m(o)}: ${d}`);return}if(i[s.id].includes(o))return;let p=bce(i,s.id,o);p.length>0?u({...s,chord:o,conflicts:p}):t(SE(e,s,o))},_=()=>{if(l===null)return;let n=e;for(let e of l.conflicts)n=gC(n,e,sC(n)[e].filter(e=>e!==l.chord));t(SE(n,l,l.chord)),u(null)},y=n=>{let r={...e};delete r[n],t(r)},b=async()=>{await Kx().confirmDialog(`Reset every keyboard shortcut to its default?`)&&t({})},x=a.trim().toLowerCase(),S=aC.filter(e=>x===``||e.label.toLowerCase().includes(x)||e.group.toLowerCase().includes(x)||i[e.id].some(e=>m(e).toLowerCase().includes(x))),C=(e,t)=>s?.id===e&&s.index===t;return(0,D.jsx)(`div`,{className:`hotkeys-backdrop`,"data-testid":`hotkeys-backdrop`,onMouseDown:e=>{e.target===e.currentTarget&&n()},children:(0,D.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Keyboard shortcuts`,className:`hotkeys-dialog`,tabIndex:-1,onKeyDownCapture:g,children:[(0,D.jsxs)(`header`,{className:`hotkeys-head`,children:[(0,D.jsx)(`strong`,{children:`Keyboard shortcuts`}),(0,D.jsx)(`button`,{type:`button`,className:`chip`,"aria-label":`Close`,onClick:n,children:`✕`})]}),(0,D.jsx)(`input`,{ref:p,className:`hotkeys-search`,"aria-label":`Search shortcuts`,placeholder:`search actions…`,value:a,onChange:e=>o(e.target.value)}),l!==null&&(0,D.jsxs)(`div`,{className:`hotkeys-note`,role:`alert`,children:[(0,D.jsxs)(`span`,{children:[m(l.chord),` is already `,xE(l.conflicts),`.`]}),(0,D.jsx)(`button`,{type:`button`,className:`chip primary`,onClick:_,children:`Reassign`}),(0,D.jsx)(`button`,{type:`button`,className:`chip`,onClick:()=>u(null),children:`Cancel`})]}),d!==null&&(0,D.jsx)(`div`,{className:`hotkeys-note`,role:`alert`,children:d}),(0,D.jsxs)(`div`,{className:`hotkeys-list`,children:[iC.map(n=>{let r=S.filter(e=>e.group===n);return r.length===0?null:(0,D.jsxs)(`section`,{"aria-label":n,children:[(0,D.jsx)(`h3`,{className:`hotkeys-group`,children:n}),r.map(n=>{let r=i[n.id];return(0,D.jsxs)(`div`,{className:`hotkeys-row`,children:[(0,D.jsx)(`span`,{className:`hotkeys-label`,children:n.label}),(0,D.jsxs)(`span`,{className:`hotkeys-keys`,children:[r.length===0&&!C(n.id,0)&&(0,D.jsx)(`span`,{className:`hotkeys-unbound`,children:`—`}),r.map((a,o)=>{let s=bce(i,n.id,a);return(0,D.jsxs)(`span`,{className:`hotkeys-key`,children:[(0,D.jsx)(`button`,{type:`button`,className:`hotkey-chip`,"aria-label":`Change ${m(a)} for ${n.label}`,...s.length>0?{title:`Also bound to ${xE(s)}`,"data-conflict":``}:{},...C(n.id,o)?{"data-recording":``}:{},onClick:()=>h({id:n.id,index:o}),children:C(n.id,o)?`Press a key…`:m(a)}),(0,D.jsx)(`button`,{type:`button`,className:`hotkey-x`,"aria-label":`Remove ${m(a)} from ${n.label}`,onClick:()=>t(gC(e,n.id,r.filter((e,t)=>t!==o))),children:`×`})]},a)}),(0,D.jsx)(`button`,{type:`button`,className:`hotkey-chip hotkey-add`,"aria-label":`Add a key for ${n.label}`,...C(n.id,r.length)?{"data-recording":``}:{},onClick:()=>h({id:n.id,index:r.length}),children:C(n.id,r.length)?`Press a key…`:`+`}),e[n.id]!==void 0&&(0,D.jsx)(`button`,{type:`button`,className:`hotkey-x`,"aria-label":`Reset ${n.label}`,title:`Back to the default`,onClick:()=>y(n.id),children:`↺`})]})]},n.id)})]},n)}),x===``&&(0,D.jsxs)(`section`,{"aria-label":`Fixed`,children:[(0,D.jsx)(`h3`,{className:`hotkeys-group`,children:`Fixed`}),vce.map(e=>(0,D.jsxs)(`div`,{className:`hotkeys-row`,children:[(0,D.jsx)(`span`,{className:`hotkeys-label`,children:e.label}),(0,D.jsx)(`span`,{className:`hotkeys-keys hotkeys-fixed`,children:e.keys})]},e.label))]})]}),(0,D.jsxs)(`footer`,{className:`hotkeys-foot`,children:[(0,D.jsx)(`button`,{type:`button`,className:`chip`,disabled:Object.keys(e).length===0,onClick:()=>void b(),children:`Reset all to defaults`}),(0,D.jsx)(`span`,{className:`hotkeys-hint`,children:`Click a key to change it. Esc cancels.`})]})]})})}var cue=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`||e.isContentEditable===!0||e.closest(`[contenteditable=""], [contenteditable="true"]`)!==null},wE=(e,t)=>e instanceof Element&&e!==document.body&&e!==document.documentElement&&t!==null&&!t.contains(e);function lue({rootRef:e,keymap:t,mode:n,handlersRef:r,suspended:i,mac:a=rC()}){let o=(0,v.useRef)({keymap:t,mode:n,suspended:i});o.current={keymap:t,mode:n,suspended:i};let s=(0,v.useRef)(null);(0,v.useEffect)(()=>{let t=t=>{let{keymap:n,mode:i,suspended:c}=o.current;if(c||t.defaultPrevented||wE(t.target,e.current))return;let l=QS(t,a);if(l===null)return;let u=uC(n,l,i);if(u===void 0)return;let d=oC(u);if(cue(t.target)&&!(d.inFields===!0&&(t.ctrlKey||t.metaKey||t.altKey)))return;if(t.repeat&&d.repeat!==!0){s.current?.chord===l&&s.current.claimed&&t.preventDefault();return}let f=r.current?.[u],p=f!==void 0&&f()!==!1;t.repeat||(s.current={chord:l,claimed:p}),p&&t.preventDefault()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,r,a])}var uue=`diagc.style`,TE=`diagc.snap`,EE=10,DE=`diagc.rightDock`,due=`diagc.leftDock`,fue=`diagc.leftDockWidth`,OE=`diagc.rightDockWidth`,kE=560,AE=220,jE=240,pue=300,ME=320,NE=(e,t,n)=>{if(e===null)return null;let r=Number(e);return Number.isFinite(r)?nT(r,t,n):null},PE=(e,t)=>{if(t?.kind!==`node`)return;let n=e.nodes.find(e=>e.id===t.id);return n===void 0?void 0:{applyTarget:{id:n.id,name:n.name||n.id}}};function mue({initialTheme:e=`dark`}={}){let{artifacts:t,names:n,booted:r,ownedNames:i,setOwnedNames:a,setDrafts:o,setLoaded:s,setSources:c,canDesign:l}=Jx(),[u,d]=(0,v.useState)(e),[f,p]=Zx(uue,`clean`,e=>e),[m,h]=Zx(TE,!1,e=>e===null?null:e===`true`),[g,_]=Zx(yce,{},Sce,JSON.stringify),y=(0,v.useMemo)(()=>sC(g),[g]),[S,C]=(0,v.useState)(!1),T=(0,v.useMemo)(rC,[]),E=(0,v.useRef)(null),ee=(0,v.useRef)(null),te=(0,v.useRef)(null),ne=(0,v.useRef)(null),re=(0,v.useRef)({}),[ie,ae]=(0,v.useState)(void 0),[oe,se]=(0,v.useState)([]),[ce,le]=(0,v.useState)(null),[ue,de]=(0,v.useState)({}),[fe,pe]=(0,v.useState)({}),[me,he]=(0,v.useState)({}),[ge,_e]=(0,v.useState)({}),[ve,ye]=(0,v.useState)(!1),[be,xe]=(0,v.useState)(!1),[Se,Ce]=(0,v.useState)(null),[we,Te]=(0,v.useState)(null),[Ee,De]=(0,v.useState)(void 0),Oe=e=>De(t=>({id:e,nonce:(t?.nonce??0)+1})),[ke,Ae]=(0,v.useState)(void 0),je=(e,t)=>Ae(n=>({target:e,id:t,nonce:(n?.nonce??0)+1})),[Me,Ne]=(0,v.useState)([]),Pe=(0,v.useCallback)(e=>Ne(t=>t.length===e.length&&t.every((t,n)=>t===e[n])?t:e),[]),[Fe,Ie]=(0,v.useState)(null),[Le,Re]=(0,v.useState)([]),ze=(0,v.useCallback)(e=>Re(e),[]),[Be,Ve]=(0,v.useState)(null),[He,Ue]=(0,v.useState)(`properties`),We=(0,v.useState)(tue),[Ge,Ke]=Zx(due,!1,e=>e===`collapsed`,e=>e?`collapsed`:`expanded`),[qe,Je]=Zx(DE,!1,e=>e===`collapsed`,e=>e?`collapsed`:`expanded`),[Ye,Xe]=Zx(fue,pue,e=>NE(e,AE,kE)),[Ze,Qe]=Zx(OE,ME,e=>NE(e,jE,kE)),$e=yE(),et=(0,v.useRef)(()=>!0),{selected:tt,setSelected:nt,enteredPath:rt,setEnteredPath:it,handleEnteredPathChange:at}=tS({names:n,booted:r,leaveEditRef:et}),ot=rt.length>0?rt[rt.length-1]:void 0,st=(0,v.useRef)(tt);st.current=tt,(0,v.useEffect)(()=>{xe(!1)},[tt]),(0,v.useEffect)(()=>{pe({})},[tt]);let[ct,lt]=(0,v.useState)(`select`),[ut,dt]=(0,v.useState)(``),[ft,pt]=(0,v.useState)(3),{editing:mt,setEditing:ht,editor:gt,layoutApiRef:vt,saveIssues:yt,setSaveIssues:bt,saving:xt,doSave:St,enterEdit:Ct,leaveEdit:wt}=cS({setDrafts:o,resetInspector:()=>Ue(`properties`),leaveEditRef:et});(0,v.useEffect)(()=>{(!mt||rt.length>0)&<(`select`)},[mt,tt,rt]),(0,v.useEffect)(()=>{w(document.documentElement,u===`dark`?x:b),document.documentElement.dataset.theme=u},[u]);let Tt=t[tt],Et=gt.session,Dt=mt?Et?.state.model:Tt?.model,Ot=mt?Et?.state.layout:Tt?.layout,kt=mt?Et?.state.drawings:Tt?.drawings,At=Dt?.style!==void 0&&Ov(Dt.style)?Dt.style:void 0,jt=Dt?.planes??[],Mt=ie,Nt=Hr(jt,Mt,Dt?.notation),Pt=dae(),Ft=Eh(Nt).partitionOf!==void 0,It=jt.find(e=>e.id===Mt)?.containmentOf!==void 0,Lt=(0,v.useRef)(null);(0,v.useEffect)(()=>{if(Dt===void 0||Lt.current===tt)return;Lt.current=tt,se(Vr(Dt.planes,ie));let e=Ot?.export?.collapsed??[];de({...Object.fromEntries(e.map(e=>[e,`collapsed`])),...Xr(Ot,Dt,ie)})},[tt,Dt,ie,Ot]);let Rt=Dt!==void 0&&Ot?.manual?.[Yr(Dt,Mt)]===!0,zt=(0,v.useMemo)(()=>mt?Ot:Pce(Ot,Dt,Mt,fe),[mt,Ot,Dt,Mt,fe]),Bt=(Dt===void 0?void 0:zt?.settings?.[Yr(Dt,Mt)])??{},Vt=ce!==null&&(Dt?.layers??[]).some(e=>e.id===ce)?ce:null,Ht=(e,t,n)=>{let r={...Dt?.relations.find(t=>t.id===e)?.style},i=t===`from`?`fromSide`:`toSide`;return n===null?delete r[i]:r[i]=n,Object.keys(r).length>0?r:null},Ut=(e,t,n,r)=>{if(Dt===void 0)return;let i=JS(Dt,e);i!==null&>.dispatch({type:`update-relation`,id:e,patch:{labels:fce(i,t,n,r)}})},Wt=(e,t,n)=>{if(Dt===void 0)return;let r=JS(Dt,e);r!==null&>.dispatch({type:`update-relation`,id:e,patch:{labels:pce(r,t,n)}})},Gt=(e,t,n,r)=>{if(Dt===void 0)return;let i=JS(Dt,e);i!==null&>.dispatch({type:`update-relation`,id:e,patch:{labels:mce(i,t,n,r)}})},Kt=Et?.lastRelationId;(0,v.useEffect)(()=>{mt&&Kt!==void 0&&(Ce({kind:`edge`,id:Kt}),Te(null))},[mt,Kt]);let qt=qS({editor:gt,model:Dt,selection:Se,groupSel:Me,editing:mt,notation:Nt,activePlane:Mt,activePlaneBorrowsContainment:It,planes:jt,activeLayer:ce,activeLayers:oe,setSelection:Ce,setRenameId:Te,setLeverageFocus:Ve,setCompareId:Ie,setPlane:ae,setPins:de,layout:Ot,pins:ue,setLayoutPreview:pe,setActiveLayers:se,setActiveLayer:le}),{select:Jt,switchPlane:Yt,activateLayer:Xt,toggleLayer:Zt,mergeSelectedLayers:Qt,toggleExpand:$t,resetView:en}=qt;yS({editing:mt,editor:gt,layoutApiRef:vt,activePlane:Mt,activePlaneBorrowsContainment:It,activePlaneManual:Rt,penLayer:Vt,selection:Se,multiSelection:Me,select:Jt});let{compareSelect:tn,groupSelected:nn}=qt,rn={notation:Nt,plane:Mt,borrowsContainment:It,penLayer:Vt},an=(e,t)=>{let n=gt.peek()?.state.model;if(!mt||n===void 0)return!1;let r=Tle(n,e,rn,t);if(r===void 0)return!1;let i=Yr(n,Mt),a=Ot?.sizes?.[e];return gt.dispatch(Ele(r,{pinned:Rt||Ot?.planes[i]?.[e]!==void 0,source:vt.current?.snapshotPositions()[e],width:a?.w??qr.width,...a===void 0?{}:{size:a},plane:Mt})),Jt({kind:`node`,id:r.id}),Oe(r.id),!0},on=Mt===void 0?{}:{plane:Mt},cn=e=>{let t=gt.peek()?.state.model;if(t===void 0)return;let n=ln(t,e);if(n===void 0)return;let r=`node`in e?t.nodes.find(t=>t.id===e.node)?.type:t.relations.find(t=>t.id===e.relation)?.kind,i=un(n);gt.dispatch({type:`batch`,commands:[{type:`add-threat`,target:e,threat:{id:i,category:pn(r)[0]??`S`,title:sn}},{type:`set-note-open`,target:e,open:!0,...on}]}),je(e,i)},dn=(e,t,n)=>{let r=gt.peek()?.state.model,i=r===void 0?void 0:ln(r,e)?.find(e=>e.id===t);if(i!==void 0){if(n===``){i.title===`New threat`&>.dispatch({type:`remove-threat`,target:e,id:t});return}n!==i.title&>.dispatch({type:`update-threat`,target:e,id:t,patch:{title:n}})}},fn=(e,t,n)=>gt.dispatch({type:`update-threat`,target:e,id:t,patch:{status:n}}),mn=(e,t,n,r)=>{let i=gt.peek()?.state.model,a=i===void 0?void 0:ln(i,e)?.find(e=>e.id===t);a!==void 0&&(a[n]??``)!==r&>.dispatch({type:`update-threat`,target:e,id:t,patch:{[n]:r===``?null:r}})},hn=Dt!==void 0&&Ot!==void 0&&Sn(Dt,Ot,Yr(Dt,Mt)),gn=Dt!==void 0&&(Dt.nodes.some(e=>(e.threats?.length??0)>0)||Dt.relations.some(e=>(e.threats?.length??0)>0)),_n=Dt!==void 0&&(Nt===`threat-model`||gn),vn=sce({editing:mt,selected:tt,current:Tt,names:n,ownedNames:i,setOwnedNames:a,setDrafts:o,setLoaded:s,setSources:c,setSelected:nt,setEnteredPath:it,setEditing:ht,leaveEdit:wt,resetView:en,editor:gt}),{addNode:yn,createAt:bn,placeFromLibrary:xn,applyFromLibrary:Cn,dropLibraryEntry:wn,addImages:Tn}=rce({editor:gt,layoutApiRef:vt,setSelection:Ce,setRenameId:Te,setLeftTab:Ue,requestLabelEdit:Oe,setSaveIssues:bt,activePlane:Mt,activePlaneBorrowsContainment:It,activePlaneManual:Rt,penLayer:Vt,selection:Se,drillRoot:ot,model:Dt,lib:$e,notation:Nt,today:Pt}),En=async(e,t)=>{try{let n=await bS(t),r=RS(t.name,new Set($e.library.entries.map(e=>e.id)),`icon`),i=t.name.replace(/\.[^.]*$/,``)||`icon`;$e.addEntry({id:r,category:e,name:i,template:{type:`image`,image:n,width:64,height:64}})}catch(e){bt([{message:Ar(e)}])}},Dn=async(e,t)=>{try{let n=await bS(t),r=RS(t.name,new Set($e.library.entries.map(e=>e.id)),`shape`),i=t.name.replace(/\.[^.]*$/,``)||`shape`;$e.addEntry({id:r,category:e,name:i,template:{shape:n}})}catch(e){bt([{message:Ar(e)}])}},On=async()=>{let e=tt;try{let t=await Kx().apiFetch(`/api/diagrams/${e}`);if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(st.current!==e)return;pe({}),Ct(e,n.model,n.layout??Jr(),n.drawings??Er())}catch(t){if(st.current!==e)return;bt([{message:`Could not load '${e}' for editing: ${Ar(t)}`}])}},kn=()=>{gt.session?.state.model!==void 0&&(Rt?gt.dispatch({type:`set-plane-layout`,manual:!1,...on}):(gt.dispatch({type:`set-positions`,positions:vt.current?.snapshotPositions()??{},...on}),gt.dispatch({type:`set-plane-layout`,manual:!0,...on})))},An=e=>{gt.session?.state.model!==void 0&>.dispatch({type:`set-layout-settings`,patch:e,...Mt===void 0?{}:{plane:Mt}})},jn=(0,v.useCallback)(async e=>{ye(!0);try{let t=await Kx().apiFetch(`/api/layouts/${tt}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json();return bt(e.issues??[{message:`Could not save layout`}]),!1}return s(t=>{let n=t[tt];return n===void 0?t:{...t,[tt]:{...n,layout:e}}}),bt(null),!0}finally{ye(!1)}},[tt,s,bt]),Mn=Dt===void 0?``:(Ot?.unfolded?.[Yr(Dt,Mt)]??[]).join(`\0`),Nn=(0,v.useRef)(null);(0,v.useEffect)(()=>{let e=Nn.current;Nn.current=mt?Mn:null,!(!mt||e===null||e===Mn||Dt===void 0)&&de(e=>KS(e).join(`\0`)===Mn?e:Xr(Ot,Dt,Mt))},[mt,Mn]);let Pn=(0,v.useMemo)(()=>KS(ue),[ue]),Fn=Dt!==void 0&&Pn.join(`\0`)!==Mn,In=Object.keys(me).length>0||Object.keys(ge).length>0||Fn,Ln=(0,v.useCallback)(async()=>{Dt===void 0||!In||await jn(lce(Ot,Dt,Mt,me,Pn,ge))&&(he({}),_e({}))},[Dt,me,ge,In,Pn,Ot,Mt,jn]),Rn=(0,v.useCallback)(async()=>{if(Dt===void 0)return;let e=!Rt,t=e?vt.current?.snapshotPositions()??{}:null;await jn(uce(Ot,Dt,Mt,t,e?Pn:void 0,e?ge:{}))&&e&&(he({}),_e({}))},[Dt,Ot,Mt,Rt,vt,jn,Pn,ge]),zn=(0,v.useCallback)(e=>{if(Dt===void 0)return;let t=Yr(Dt,Mt);pe(n=>PC(n,t,e))},[Dt,Mt]),Bn=mt&&Dt!==void 0?YS(Dt,Se,gt.dispatch):null,Vn=Se?.kind===`node`&&Dt!==void 0?Ot?.planes[Yr(Dt,Mt)]?.[Se.id]:void 0,Hn=Se?.kind===`node`&&Dt!==void 0?vt.current?.snapshotPositions()[Se.id]:void 0,Wn=(e,t)=>e?t:void 0,Gn=i.has(tt),Kn=!mt&&Dt!==void 0,qn=Dt!==void 0&&Object.keys(Ot?.planes[Yr(Dt,Mt)]??{}).length>0,Jn=e=>Wn(Dt!==void 0,()=>te.current!==null&&e(te.current)),Yn=e=>()=>rt.length>0?!1:(lt(e),!0);re.current={"diagram.picker":()=>ne.current?.(),"diagram.toggle-edit":Wn(Dt!==void 0&&Gn,()=>void(mt?wt():On())),"diagram.rename":Wn(l&&!mt&&Gn,()=>void vn.renameDiagram()),"diagram.new":Wn(l,()=>void vn.newDiagram()),"diagram.duplicate":Wn(l&&Kn,()=>void vn.duplicateDiagram()),"diagram.eject":Wn(l&&!mt&&Gn,()=>void vn.ejectDiagram()),"edit.add-node":Wn(mt,()=>yn()),"edit.add-child":Wn(mt,()=>Se?.kind===`node`&&an(Se.id)),"edit.undo":Wn(mt,()=>gt.undo()),"edit.redo":Wn(mt,()=>gt.redo()),"edit.save":Wn(mt,()=>void St()),"edit.group":Wn(mt&&Me.length>=2,()=>void nn()),"edit.relayout":Wn(mt,()=>void DC(gt,{autoLayout:!Rt,activePlane:Mt,getAutoPositions:()=>vt.current?.autoPositions()??{}})),"edit.toggle-auto-layout":Wn(mt,kn),"edit.toggle-notes":Wn(mt&&_n&&gn,()=>gt.dispatch({type:`set-notes-open`,open:!hn,...on})),"tool.select":Wn(mt,()=>lt(`select`)),"tool.pen":Wn(mt,Yn(`pen`)),"tool.eraser":Wn(mt,Yn(`eraser`)),"pen.thin":Wn(mt&&ct===`pen`,()=>pt(2)),"pen.medium":Wn(mt&&ct===`pen`,()=>pt(3)),"pen.thick":Wn(mt&&ct===`pen`,()=>pt(6)),"canvas.fit":Jn(e=>e.fitView()),"canvas.zoom-in":Jn(e=>e.zoomIn()),"canvas.zoom-out":Jn(e=>e.zoomOut()),"canvas.laser":Jn(e=>e.toggleLaser()),"canvas.legend":Jn(e=>e.toggleLegend()),"canvas.dim":Jn(e=>e.toggleDim()),"canvas.drawings":Jn(e=>e.toggleDrawings()),"canvas.loops":Jn(e=>e.toggleLoops()),"view.freeze":Wn(Kn&&!ve&&rt.length===0,()=>void Rn()),"view.save-positions":Wn(Kn&&In&&!ve,()=>void Ln()),"view.auto-arrange":Wn(Kn&&qn,()=>xe(e=>!e)),"arrange.align-left":Jn(e=>e.align(`left`)),"arrange.align-center":Jn(e=>e.align(`centerX`)),"arrange.align-right":Jn(e=>e.align(`right`)),"arrange.align-top":Jn(e=>e.align(`top`)),"arrange.align-middle":Jn(e=>e.align(`middle`)),"arrange.align-bottom":Jn(e=>e.align(`bottom`)),"arrange.distribute-x":Jn(e=>e.distribute(`x`)),"arrange.distribute-y":Jn(e=>e.distribute(`y`)),"window.left-dock":Wn(Dt!==void 0,()=>Ke(e=>!e)),"window.right-dock":Wn(Dt!==void 0,()=>Je(e=>!e)),"window.inspector-properties":Wn(mt,()=>{Ue(`properties`),Ke(!1)}),"window.inspector-library":Wn(mt,()=>{Ue(`library`),Ke(!1)}),"window.theme":()=>d(e=>e===`dark`?`light`:`dark`),"window.snap":()=>h(e=>!e),"window.hotkeys":()=>C(!0)},lue({rootRef:E,keymap:y,mode:mt?`edit`:`view`,handlersRef:re,suspended:S,mac:T});let Xn=e=>bC(y,e,T),Zn=[...Gn?[{id:`rename`,label:`Rename`,title:`Rename this diagram${Xn(`diagram.rename`)}`,onSelect:()=>void vn.renameDiagram()}]:[],...Dt===void 0?[]:[{id:`export-png`,label:`Export PNG`,title:`Save the canvas as drawn — folds, layers, theme and drawings — as a PNG image`,onSelect:()=>void Dce(vt.current,tt??``)},{id:`duplicate`,label:`Duplicate`,title:`Copy this diagram — layout and all — to a new editable one and open it${Xn(`diagram.duplicate`)}`,onSelect:()=>void vn.duplicateDiagram()}],...Gn?[{id:`eject`,label:`Eject`,title:`Promote this diagram to a TypeScript source — it becomes read-only here${Xn(`diagram.eject`)}`,onSelect:()=>void vn.ejectDiagram()}]:[]],Qn=(0,v.useMemo)(()=>({keymap:y,mac:T}),[y,T]),$n=(0,v.useMemo)(()=>({laser:yC(y,`canvas.laser`,T),dim:yC(y,`canvas.dim`,T),legend:yC(y,`canvas.legend`,T),drawings:yC(y,`canvas.drawings`,T),loops:yC(y,`canvas.loops`,T)}),[y,T]);return(0,D.jsx)(vC.Provider,{value:Qn,children:(0,D.jsxs)(`div`,{className:`app`,ref:E,children:[(0,D.jsxs)(`header`,{className:`topbar`,children:[(0,D.jsx)(`strong`,{className:`brand`,children:`diagc studio`}),(0,D.jsx)(Tce,{names:n,selected:tt,onSelect:e=>{wt()&&(nt(e),it([]),en())},toggleRef:ne}),l&&(0,D.jsx)(`button`,{type:`button`,className:`chip icon`,"aria-label":`New diagram`,title:`New diagram${Xn(`diagram.new`)}`,onClick:()=>void vn.newDiagram(),children:`+`}),l&&!mt&&(0,D.jsx)(Nce,{label:`Diagram actions`,items:Zn,children:`⋯`}),Dt!==void 0&&(Gn?!mt&&(0,D.jsx)(`button`,{className:`chip`,onClick:()=>void On(),title:`Edit this diagram${Xn(`diagram.toggle-edit`)}`,children:`Edit`}):(0,D.jsx)(`span`,{className:`chip read-only`,title:`Compiled from TypeScript — edit the source`,children:`read-only`})),(0,D.jsx)(`span`,{className:`spacer`}),!mt&&Dt!==void 0&&In&&(0,D.jsx)(`button`,{className:`chip primary`,disabled:ve,title:`Write the boxes and edge labels you moved, and which groups are open, to this diagram's layout file. Safe on a generated diagram: re-compiling rewrites the model, never the layout.${Xn(`view.save-positions`)}`,onClick:()=>void Ln(),children:ve?`Saving…`:`Save positions`}),mt&&_n&&(0,D.jsx)(`button`,{type:`button`,className:`chip${hn?` active`:``}`,"aria-pressed":hn,disabled:!gn,title:`${hn?`Close all threat notes`:`Open all threat notes`}${Xn(`edit.toggle-notes`)}`,onClick:()=>gt.dispatch({type:`set-notes-open`,open:!hn,...on}),children:`Notes`}),(0,D.jsx)(`span`,{className:`sep`}),(0,D.jsx)(`button`,{type:`button`,className:`chip icon${m?` active`:``}`,"aria-label":`Snap to grid`,"aria-pressed":m,title:`${m?`Snapping to a ${EE}px grid. Click to place boxes freely.`:`Snap dragged boxes to a ${EE}px grid; arrow keys step by it too.`}${Xn(`window.snap`)}`,onClick:()=>h(e=>!e),children:`⋮⋮`}),(0,D.jsx)(`button`,{type:`button`,className:`chip icon`,"aria-label":u===`dark`?`Switch to light theme`:`Switch to dark theme`,title:`${u===`dark`?`Light theme`:`Dark theme`}${Xn(`window.theme`)}`,onClick:()=>d(u===`dark`?`light`:`dark`),children:u===`dark`?`☀`:`☾`}),(0,D.jsx)(`button`,{ref:ee,type:`button`,className:`chip icon`,"aria-label":`Keyboard shortcuts`,title:`Keyboard shortcuts${Xn(`window.hotkeys`)}`,onClick:()=>C(!0),children:`⚙`}),(0,D.jsx)(`a`,{className:`chip source-link`,href:kr,target:`_blank`,rel:`noreferrer`,title:`diagc is free software under the AGPL-3.0 — get the source`,children:`source`})]}),mt&&(0,D.jsx)(EC,{editor:gt,onExit:wt,onSave:()=>void St(),saving:xt,saveIssues:yt,selectionColor:Bn,tool:ct,onSetTool:lt,pen:{color:ut,width:ft},onSetPen:e=>{e.color!==void 0&&dt(e.color),e.width!==void 0&&pt(e.width)},drawingDisabled:rt.length>0}),n.length===0&&(0,D.jsx)(`div`,{className:`banner`,children:l?(0,D.jsxs)(D.Fragment,{children:[`No diagrams yet — use `,(0,D.jsx)(`b`,{children:`New diagram`}),` to create one.`]}):(0,D.jsxs)(D.Fragment,{children:[`No artifacts found — run `,(0,D.jsx)(`code`,{children:`diagc compile`}),` (or `,(0,D.jsx)(`code`,{children:`diagc watch`}),`) first.`]})}),!mt&&Tt!==void 0&&Tt.issues.length>0&&(0,D.jsxs)(`div`,{className:`banner error`,children:[(0,D.jsx)(`b`,{children:Tt.name}),` failed validation:`,(0,D.jsx)(`ul`,{children:Tt.issues.map((e,t)=>(0,D.jsx)(`li`,{children:e.message},t))})]}),!mt&&yt!==null&&yt.length>0&&(0,D.jsx)(`div`,{className:`banner error`,children:(0,D.jsx)(`ul`,{children:yt.map((e,t)=>(0,D.jsx)(`li`,{children:e.message},t))})}),(0,D.jsx)(`main`,{className:`body`,children:Dt!==void 0&&(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(rT,{side:`left`,collapsed:Ge,onToggle:()=>Ke(e=>!e),hasContent:mt?!0:Se!==null,width:Ye,minWidth:AE,maxWidth:kE,onWidthChange:Xe,children:mt?(0,D.jsx)(tT,{activeTab:He,onTabChange:Ue,properties:Se?.kind===`node`&&Dt.nodes.some(e=>e.id===Se.id)?(0,D.jsx)(Ow,{model:Dt,nodeId:Se.id,activePlane:Mt,hasPin:Vn!==void 0,...Vn===void 0?{}:{pinned:Vn},...Hn===void 0?{}:{live:Hn},autoFocusName:Se.id===we,...Nt===void 0?{}:{notation:Nt},today:Pt,onCommand:gt.dispatch,onClose:()=>Jt(null),onDeleted:()=>Jt(null)},Se.id):Se?.kind===`edge`?(0,D.jsx)(Mw,{model:Dt,constituentIds:Se.constituentIds??[Se.id],onCommand:gt.dispatch,onClose:()=>Jt(null),...Nt===void 0?{}:{notation:Nt},...Mt===void 0?{}:{activePlane:Mt}},Se.id):(0,D.jsx)($le,{model:Dt,selection:Se}),library:(0,D.jsx)(aue,{library:$e.library,onPlace:xn,onApply:Cn,...PE(Dt,Se)??{},onAddNode:yn,onAddImages:e=>void Tn(e),onAddCategory:$e.addCategory,onDeleteCategory:$e.deleteCategory,onImportIcon:(e,t)=>void En(e,t),onImportShape:(e,t)=>void Dn(e,t),assetBase:Kx().assetBase,viewState:We})}):Nt===`causal-loop`&&Se?.kind===`node`&&Dt.nodes.some(e=>e.id===Se.id)?(0,D.jsx)(sy,{model:Dt,edges:Le,target:Se.id,activeFocusKey:Be?.key??null,onFocus:Ve,onClose:()=>Jt(null),compareId:Fe,onClearCompare:()=>Ie(null)},Se.id):Se===null?(0,D.jsx)(`div`,{className:`sidebar dock-empty`,children:`Select a node or edge for details.`}):(0,D.jsx)($le,{model:Dt,selection:Se})}),(0,D.jsxs)(`div`,{className:`canvas-area`,children:[(0,D.jsx)(Gse,{model:Dt,plane:Mt,today:Pt,activeLayers:oe,onToggleLayer:Zt,pins:ue,onToggleExpand:$t,onSelect:Jt,onMultiSelect:Pe,onEnteredPathChange:at,enteredPath:rt,onCompareSelect:tn,colorMode:u,assetBase:Kx().assetBase,...Kx().libraryBase===void 0?{}:{libraryBase:Kx().libraryBase},onOpenLink:e=>Kx().openLink(e),styleId:At??f,...m?{snapGrid:EE}:{},onCldEdges:ze,onViewPositionsChange:he,onViewLabelMovesChange:_e,layoutApiRef:vt,canvasCommandsRef:te,builtinKeys:!1,keyHints:$n,ignoreSavedPositions:be,externalHighlight:mt?Me.length>=2?{nodes:Me,edges:[]}:null:Be??(Fe!==null&&Se?.kind===`node`?{nodes:[Se.id,Fe],edges:[]}:null),...Nt===void 0?{}:{notation:Nt},...zt===void 0?{}:{layout:zt},...kt===void 0?{}:{drawings:kt},...mt?{mode:`edit`,tool:ct,pen:{...ut===``?{}:{color:ut},width:ft},edit:{...Ee===void 0?{}:{editLabelRequest:Ee},...ke===void 0?{}:{editThreatRequest:ke},onNoteMoved:(e,t)=>gt.dispatch({type:`set-note-offset`,target:e,offset:t,...on}),onToggleNote:(e,t)=>gt.dispatch({type:`set-note-open`,target:e,open:t,...on}),onAddThreat:cn,onRetitleThreat:dn,onSetThreatStatus:fn,onEditThreatText:mn,quickAdd:{label:(e,t)=>Dt===void 0?void 0:wle(Dt,e,rn,t),run:an},onNodesMoved:(e,t)=>{if(Nt===`plan`&&Dt!==void 0){let n=AS(Dt,Mt,e,t);n!==void 0&>.dispatch(n);return}gt.dispatch({type:`set-positions`,positions:e,...Mt===void 0?{}:{plane:Mt}})},onDropInto:(e,t,n)=>{if(Nt===`plan`&&Dt!==void 0){let r=$se(Dt,Mt,e,t,n);r!==void 0&>.dispatch(r)}},onMoveLane:(e,t,n)=>{let r=Vw(e,t,n,Mt);r!==null&>.dispatch(r)},onSetRole:(e,t,n)=>{if(Dt===void 0)return;let r=Zse(Dt,e,t,n);r!==void 0&>.dispatch(r)},onCreateAt:e=>bn(e),onImageFiles:(e,t)=>void Tn(e,t),onDropLibraryEntry:wn,onResize:(e,t,n,r)=>{if(Nt===`plan`&&Dt!==void 0){let n=Dt.nodes.find(t=>t.id===e);if(n!==void 0&&Un(n)){let n=jS(Dt,Mt,e,r.x,t);n!==void 0&>.dispatch(n);return}}gt.dispatch({type:`set-size`,nodeId:e,w:t,h:n}),gt.dispatch({type:`set-position`,nodeId:e,x:r.x,y:r.y,...Mt===void 0?{}:{plane:Mt}})},onConnect:(e,t,n)=>{let r=gt.session?.state.model,i=r===void 0?null:sue(r,e,t,n,Vt===null?void 0:{layer:Vt});if(i!==null){for(let e of i)gt.dispatch(e);return}gt.dispatch({type:`add-relation`,from:e,to:t,opts:{kind:Xw(Nt,r,e,t),...Vt===null?{}:{layer:Vt}}})},onDeleteSelection:e=>{let t=gt.peek()?.state.model,n=t===void 0?null:bE(t,e);n!==null&&(gt.dispatch(n),Jt(null))},onSetTableColumns:(e,t)=>gt.dispatch({type:`set-table-columns`,id:e,columns:t}),onRenameNode:(e,t)=>gt.dispatch({type:`rename-node`,id:e,name:t}),onSetNodeRich:(e,t)=>gt.dispatch({type:`set-node-rich`,id:e,runs:t}),onAddEdgeLabel:Ut,onEditEdgeLabel:Wt,onMoveEdgeLabel:Gt,onReconnect:(e,t,n,r)=>gt.dispatch({type:`update-relation`,id:e,patch:{from:t,to:n,...r===void 0?{}:{style:Ht(e,r.end,r.side)}}}),onSetEdgeSide:(e,t,n)=>gt.dispatch({type:`update-relation`,id:e,patch:{style:Ht(e,t,n)}}),onAddStroke:e=>{let t=gt.peek()?.state.drawings,n=gt.peek()?.state.model;t===void 0||n===void 0||gt.dispatch({type:`add-stroke`,stroke:{id:Dr(t,Yr(n,Mt)),...e},...Mt===void 0?{}:{plane:Mt}})},onDeleteStroke:e=>gt.dispatch({type:`delete-stroke`,id:e,...Mt===void 0?{}:{plane:Mt}})}}:{}}),mt&&Me.length>=2&&(0,D.jsxs)(`button`,{className:`chip group-action`,title:`Group the selection${Xn(`edit.group`)}`,onClick:()=>void nn(),children:[`⊞ Group `,Me.length]})]}),(0,D.jsxs)(rT,{side:`right`,collapsed:qe,onToggle:()=>Je(e=>!e),hasContent:!0,width:Ze,minWidth:jE,maxWidth:kE,onWidthChange:Qe,children:[mt&&Nt===`git-graph`&&(0,D.jsx)(ule,{model:Dt,plane:Mt,selection:Se,onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e})}),mt&&Nt===`plan`&&(0,D.jsx)(Yw,{model:Dt,plane:Mt,selection:Se,onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e}),today:Pt}),mt&&Nt===`second-order`&&(0,D.jsx)(hle,{model:Dt,selection:Se,...Mt!==void 0&&!It?{plane:Mt}:{},onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e}),onCreated:Oe}),mt&&Nt===`fishbone`&&(0,D.jsx)(yle,{model:Dt,selection:Se,...Mt!==void 0&&!It?{plane:Mt}:{},onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e}),onCreated:Oe}),Nt===`threat-model`&&(0,D.jsx)(qw,{model:Dt,...Mt===void 0?{}:{plane:Mt},onSelect:Jt}),mt&&(0,D.jsx)(Hw,{model:Dt,plane:Mt,selection:Se,onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e})}),(0,D.jsxs)(Mce,{controls:Eh(Nt).layout===void 0?{settings:Bt,onChange:mt?An:zn,defaultDirection:_t(Dt),algorithmLocked:Ft,...Eh(Nt).defaultAlgorithm===void 0?{}:{defaultAlgorithm:Eh(Nt).defaultAlgorithm}}:null,styleControl:mt?(0,D.jsxs)(`select`,{className:`chip-select`,"aria-label":`Diagram style`,title:`Diagram style (saved with the diagram)`,value:At??``,onChange:e=>gt.dispatch({type:`set-diagram-style`,style:e.target.value===``?null:e.target.value}),children:[(0,D.jsx)(`option`,{value:``,children:`(app default)`}),Ev.map(e=>(0,D.jsx)(`option`,{value:e.id,children:e.label},e.id))]}):(0,D.jsx)(`select`,{className:`chip-select`,"aria-label":`Style`,title:At===void 0?`Visual style`:`Set by diagram`,value:At??(Ov(f)?f:`clean`),disabled:At!==void 0,onChange:e=>p(e.target.value),children:Ev.map(e=>(0,D.jsx)(`option`,{value:e.id,children:e.label},e.id))}),children:[mt&&(0,D.jsx)(OC,{editor:gt,activePlane:Mt,autoLayout:!Rt,onToggleAutoLayout:kn,getAutoPositions:()=>vt.current?.autoPositions()??{}}),!mt&&fe[Yr(Dt,Mt)]!==void 0&&(0,D.jsx)(`button`,{className:`chip`,title:`Drop the preview and go back to this diagram's own layout settings`,onClick:()=>pe(e=>{let t={...e};return delete t[Yr(Dt,Mt)],t}),children:`Reset layout`}),!mt&&Object.keys(Ot?.planes[Yr(Dt,Mt)]??{}).length>0&&(0,D.jsx)(`button`,{type:`button`,className:`chip${be?` active`:``}`,"aria-pressed":be,title:`${be?`Ignoring this diagram’s saved positions, so the layout algorithm arranges every node. Click to put them back.`:`This plane has saved positions, which override the layout algorithm. Click to arrange those nodes automatically instead (nothing is written).`}${Xn(`view.auto-arrange`)}`,onClick:()=>xe(e=>!e),children:`Auto-arrange`}),!mt&&(0,D.jsx)(`button`,{type:`button`,className:`chip${Rt?` active`:``}`,"aria-pressed":Rt,disabled:ve||rt.length>0,title:`${rt.length>0?`Freezing pins the whole plane, but a drilled view only has positions for what it shows — leave the drilled view first.`:Rt?`Positions are pinned. Click to let the layout algorithm arrange this plane again (your positions are kept).`:`Pin every box where it is so the layout algorithm stops moving them. Boxes added to the source later are still placed automatically until you move them.`}${Xn(`view.freeze`)}`,onClick:()=>void Rn(),children:`Freeze layout`})]}),(0,D.jsx)(Bw,{model:Dt,onCommand:gt.dispatch,mode:mt?`edit`:`view`,activeLayer:Vt,onActivateLayer:Xt,activePlane:Mt,onSelectPlane:e=>e===void 0?en():Yt(e),activeLayers:oe,onToggleLayer:Zt,onMergeLayers:Qt})]})]})}),S&&(0,D.jsx)(CE,{overrides:g,onChange:_,onClose:()=>{C(!1),ee.current?.focus()},mac:T})]})})}var hue=document.getElementById(`root`);hue&&(0,y.createRoot)(hue).render((0,D.jsx)(mue,{}));
|
package/assets/studio/index.html
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
<meta charset="UTF-8" />
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>diagc studio</title>
|
|
7
|
-
<script type="module" crossorigin src="/assets/index-
|
|
7
|
+
<script type="module" crossorigin src="/assets/index-C0LPHkb1.js"></script>
|
|
8
8
|
<link rel="stylesheet" crossorigin href="/assets/index-Csx5rLJC.css">
|
|
9
9
|
</head>
|
|
10
10
|
<body>
|
package/dist/cli.d.ts
CHANGED
|
@@ -14,6 +14,10 @@ interface Args {
|
|
|
14
14
|
imageUrl?: string;
|
|
15
15
|
/** diff `--labels before,after`: names for the two sides in place of the refs */
|
|
16
16
|
labels?: [string, string];
|
|
17
|
+
/** init `--type`: which starter to copy */
|
|
18
|
+
type?: string;
|
|
19
|
+
/** init `--agents`: write the coding-agent block */
|
|
20
|
+
agents: boolean;
|
|
17
21
|
}
|
|
18
22
|
/** Parse argv into command + flags. Unknown flags (anything `--…` that is not
|
|
19
23
|
* recognized) are an error rather than being silently treated as a file path,
|
package/dist/cli.js
CHANGED
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
*
|
|
20
20
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
21
21
|
*/
|
|
22
|
-
import { existsSync } from 'node:fs';
|
|
22
|
+
import { existsSync, statSync } from 'node:fs';
|
|
23
23
|
import path from 'node:path';
|
|
24
24
|
import { fileURLToPath } from 'node:url';
|
|
25
25
|
import fg from 'fast-glob';
|
|
@@ -29,16 +29,21 @@ import { compareDiagramSets, formatDiffSummary, loadDiagramSet, writeDiffPages }
|
|
|
29
29
|
import { checkoutDiagrams } from './git-ref.js';
|
|
30
30
|
import { ejectDiagram } from './eject.js';
|
|
31
31
|
import { formatLintReport, lintFile } from './lint.js';
|
|
32
|
-
import {
|
|
32
|
+
import { runGuide } from './guide.js';
|
|
33
|
+
import { cliVersion, findHome, homePaths } from './home.js';
|
|
34
|
+
import { diagramName, runInit } from './init.js';
|
|
33
35
|
import { resolveInclude } from './includes.js';
|
|
34
36
|
import { snapshotSession } from './snapshots.js';
|
|
35
37
|
import { formatCompileEvent, startWatch } from './watch.js';
|
|
36
38
|
import { galleryLink } from './publish/gallery.js';
|
|
37
39
|
import { publishDiagrams } from './publish/publish.js';
|
|
38
40
|
import { runStudio } from './studio.js';
|
|
39
|
-
const USAGE = `Usage: diagc <compile|lint|watch|publish|studio|eject|diff> [files...] [--out dir]
|
|
41
|
+
const USAGE = `Usage: diagc <init|compile|lint|watch|publish|studio|eject|diff|guide> [files...] [--out dir]
|
|
40
42
|
|
|
41
43
|
Commands:
|
|
44
|
+
init init [name] [--type <type>] [--agents]: set a repository up — a starter
|
|
45
|
+
diagram under .diagrams/src (compiled), the .gitignore lines, and with
|
|
46
|
+
--agents a pointer to the guide for coding agents (AGENTS.md / CLAUDE.md)
|
|
42
47
|
compile Compile *.diagram.{ts,json} sources into overlay artifacts once
|
|
43
48
|
lint Report suspicious diagrams (typos, duplicates, unused or undrawn parts); exit 1 on any
|
|
44
49
|
watch Recompile — and live-recompile — a directory of sources
|
|
@@ -47,6 +52,8 @@ Commands:
|
|
|
47
52
|
eject Promote a JSON diagram to a generated TypeScript source (verified)
|
|
48
53
|
diff diff <from>[..<to>] [names...]: what changed in the diagrams between two git
|
|
49
54
|
refs (or a ref and the working tree), with before/after pages and PNGs
|
|
55
|
+
guide guide [topic]: how to write a diagram, for a person or a coding agent — the
|
|
56
|
+
DSL, then one topic per diagram type ('guide all' prints every topic)
|
|
50
57
|
|
|
51
58
|
Options:
|
|
52
59
|
--out dir Artifact output directory (default .diagrams/.artifacts;
|
|
@@ -57,6 +64,8 @@ Options:
|
|
|
57
64
|
--labels a,b diff: name the two sides (default: the refs)
|
|
58
65
|
--image-url t diff: summary.md's image links as t, {path} standing for each PNG
|
|
59
66
|
--update-includes Refetch remote includes and rewrite the snapshot lock
|
|
67
|
+
--type <type> init: the starter to copy (default basic; 'diagc guide' lists the types)
|
|
68
|
+
--agents init: write the coding-agent block into AGENTS.md / CLAUDE.md
|
|
60
69
|
--help, -h Show this help and exit
|
|
61
70
|
`;
|
|
62
71
|
/** Parse argv into command + flags. Unknown flags (anything `--…` that is not
|
|
@@ -73,6 +82,8 @@ export function parseArgs(argv) {
|
|
|
73
82
|
let link;
|
|
74
83
|
let imageUrl;
|
|
75
84
|
let labels;
|
|
85
|
+
let type;
|
|
86
|
+
let agents = false;
|
|
76
87
|
let commandSeen = false;
|
|
77
88
|
for (let i = 0; i < argv.length; i++) {
|
|
78
89
|
const arg = argv[i];
|
|
@@ -93,6 +104,19 @@ export function parseArgs(argv) {
|
|
|
93
104
|
json = true;
|
|
94
105
|
continue;
|
|
95
106
|
}
|
|
107
|
+
if (arg === '--type') {
|
|
108
|
+
// No fallback: a missing value would otherwise swallow the next flag as the type.
|
|
109
|
+
const value = argv[i + 1];
|
|
110
|
+
if (value === undefined || value.startsWith('--'))
|
|
111
|
+
throw new BadFlagValueError('--type', "needs a diagram type, e.g. --type c4 ('diagc guide' lists them)");
|
|
112
|
+
type = value;
|
|
113
|
+
i++;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (arg === '--agents') {
|
|
117
|
+
agents = true;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
96
120
|
if (arg === '--image-url') {
|
|
97
121
|
const value = argv[++i] ?? '';
|
|
98
122
|
if (!value.includes('{path}'))
|
|
@@ -142,6 +166,8 @@ export function parseArgs(argv) {
|
|
|
142
166
|
images,
|
|
143
167
|
updateIncludes,
|
|
144
168
|
json,
|
|
169
|
+
agents,
|
|
170
|
+
...(type !== undefined ? { type } : {}),
|
|
145
171
|
...(link !== undefined ? { link } : {}),
|
|
146
172
|
...(imageUrl !== undefined ? { imageUrl } : {}),
|
|
147
173
|
...(labels !== undefined ? { labels } : {}),
|
|
@@ -170,6 +196,12 @@ export class BadFlagValueError extends Error {
|
|
|
170
196
|
this.name = 'BadFlagValueError';
|
|
171
197
|
}
|
|
172
198
|
}
|
|
199
|
+
const SOURCES = '.diagrams/src/**/*.diagram.{ts,json}';
|
|
200
|
+
/** The one message a repository with no diagrams gets, on stderr: `lint --json`'s
|
|
201
|
+
* stdout stays an array and the exit codes hold, so CI without diagrams passes. */
|
|
202
|
+
function warnNoSources(dir = '.diagrams/src') {
|
|
203
|
+
console.error(`No diagrams under ${dir} — run 'diagc init' to create one.`);
|
|
204
|
+
}
|
|
173
205
|
async function main() {
|
|
174
206
|
let args;
|
|
175
207
|
try {
|
|
@@ -194,7 +226,9 @@ async function main() {
|
|
|
194
226
|
// own separate always-locked session below instead of sharing this one.
|
|
195
227
|
const snap = snapshotSession(resolveInclude, '.diagrams', args.updateIncludes ? 'update' : 'locked');
|
|
196
228
|
if (args.command === 'compile') {
|
|
197
|
-
const files = args.files.length > 0 ? args.files : await fg(
|
|
229
|
+
const files = args.files.length > 0 ? args.files : await fg(SOURCES);
|
|
230
|
+
if (args.files.length === 0 && files.length === 0)
|
|
231
|
+
warnNoSources();
|
|
198
232
|
let failed = false;
|
|
199
233
|
for (const file of files) {
|
|
200
234
|
try {
|
|
@@ -219,7 +253,9 @@ async function main() {
|
|
|
219
253
|
process.exit(failed ? 1 : 0);
|
|
220
254
|
}
|
|
221
255
|
else if (args.command === 'lint') {
|
|
222
|
-
const files = args.files.length > 0 ? args.files : await fg(
|
|
256
|
+
const files = args.files.length > 0 ? args.files : await fg(SOURCES);
|
|
257
|
+
if (args.files.length === 0 && files.length === 0)
|
|
258
|
+
warnNoSources();
|
|
223
259
|
const reports = [];
|
|
224
260
|
for (const file of files) {
|
|
225
261
|
reports.push(...(await lintFile(file, { rootDir: '.diagrams/src', coreEntry: home.coreEntry, resolver: snap.resolver })));
|
|
@@ -239,6 +275,8 @@ async function main() {
|
|
|
239
275
|
if (args.updateIncludes)
|
|
240
276
|
console.error('ignoring --update-includes: watch always runs locked');
|
|
241
277
|
const dir = args.files[0] ?? '.diagrams/src';
|
|
278
|
+
if (existsSync(dir) && statSync(dir).isDirectory() && (await fg('**/*.diagram.{ts,json}', { cwd: dir })).length === 0)
|
|
279
|
+
warnNoSources(dir);
|
|
242
280
|
const watchSnap = snapshotSession(resolveInclude, '.diagrams', 'locked');
|
|
243
281
|
startWatch(dir, args.out, {
|
|
244
282
|
coreEntry: home.coreEntry,
|
|
@@ -268,6 +306,8 @@ async function main() {
|
|
|
268
306
|
const artifactsDir = '.diagrams/.artifacts';
|
|
269
307
|
// Compile first so artifacts reflect current sources (TS + include expansion).
|
|
270
308
|
const sources = await fg('**/*.diagram.{ts,json}', { cwd: srcDir, absolute: true });
|
|
309
|
+
if (sources.length === 0)
|
|
310
|
+
warnNoSources(srcDir);
|
|
271
311
|
for (const f of sources) {
|
|
272
312
|
try {
|
|
273
313
|
await compileFile(f, artifactsDir, { rootDir: srcDir, coreEntry: home.coreEntry, resolver: snap.resolver });
|
|
@@ -325,7 +365,7 @@ async function main() {
|
|
|
325
365
|
// eject.ts) — same reasoning as watch above.
|
|
326
366
|
if (args.updateIncludes)
|
|
327
367
|
console.error('ignoring --update-includes: eject always runs locked');
|
|
328
|
-
const name = args.files[0]
|
|
368
|
+
const name = args.files[0] === undefined ? undefined : diagramName(args.files[0]);
|
|
329
369
|
if (name === undefined || name === '') {
|
|
330
370
|
console.error('diagc: eject needs a diagram name.');
|
|
331
371
|
console.error(USAGE);
|
|
@@ -344,6 +384,34 @@ async function main() {
|
|
|
344
384
|
else if (args.command === 'diff') {
|
|
345
385
|
process.exit(await runDiff(args, home));
|
|
346
386
|
}
|
|
387
|
+
else if (args.command === 'guide') {
|
|
388
|
+
// exitCode and a return, not process.exit: the guide is tens of kilobytes and
|
|
389
|
+
// is read through a pipe by an agent. Exiting while part of it is still
|
|
390
|
+
// queued would hand over a page that stops mid-sentence.
|
|
391
|
+
process.exitCode = runGuide(args.files, {
|
|
392
|
+
guideDir: home.guideDir,
|
|
393
|
+
startersDir: home.startersDir,
|
|
394
|
+
version: cliVersion(home.root),
|
|
395
|
+
});
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
else if (args.command === 'init') {
|
|
399
|
+
if (args.files.length > 1) {
|
|
400
|
+
console.error(`diagc: init takes one name, got ${args.files.length} — e.g. diagc init shop --type c4`);
|
|
401
|
+
process.exit(1);
|
|
402
|
+
}
|
|
403
|
+
process.exitCode = await runInit({
|
|
404
|
+
cwd: process.cwd(),
|
|
405
|
+
...(args.files[0] !== undefined ? { name: args.files[0] } : {}),
|
|
406
|
+
...(args.type !== undefined ? { type: args.type } : {}),
|
|
407
|
+
agents: args.agents,
|
|
408
|
+
startersDir: home.startersDir,
|
|
409
|
+
version: cliVersion(home.root),
|
|
410
|
+
coreEntry: home.coreEntry,
|
|
411
|
+
resolver: snap.resolver,
|
|
412
|
+
});
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
347
415
|
else {
|
|
348
416
|
console.error(`diagc: Unknown command '${args.command}'.`);
|
|
349
417
|
console.error(USAGE);
|
package/dist/compile.d.ts
CHANGED
|
@@ -1,4 +1,30 @@
|
|
|
1
1
|
import { type DiagramModel, type IncludeResolver } from '@diagc/core';
|
|
2
|
+
/**
|
|
3
|
+
* A source that threw while running — a misspelled method, a builder call that
|
|
4
|
+
* refused — placed at the first stack frame inside that file. V8 writes the file
|
|
5
|
+
* into every frame and jiti keeps the author's lines, so no source map is needed;
|
|
6
|
+
* taking the first frame *in the user's file* also puts a refusal the builder
|
|
7
|
+
* throws at the call that caused it. A transform error has no such frame: then
|
|
8
|
+
* there is no position and the message is left as it was.
|
|
9
|
+
*/
|
|
10
|
+
export declare class LoadError extends Error {
|
|
11
|
+
readonly file: string;
|
|
12
|
+
readonly reason: string;
|
|
13
|
+
readonly line: number | undefined;
|
|
14
|
+
readonly column: number | undefined;
|
|
15
|
+
constructor(file: string, reason: string, position?: {
|
|
16
|
+
line: number;
|
|
17
|
+
column: number;
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
/** The line and column of the first `at` frame inside `file`. Matched on the
|
|
21
|
+
* basename after a path separator: a frame spells the path as it was imported,
|
|
22
|
+
* which a symlinked temp dir would not equal; the message line is skipped because
|
|
23
|
+
* a transform error quotes `file:line:col` there and that is not a frame. */
|
|
24
|
+
export declare function positionIn(stack: string | undefined, file: string): {
|
|
25
|
+
line: number;
|
|
26
|
+
column: number;
|
|
27
|
+
} | undefined;
|
|
2
28
|
/**
|
|
3
29
|
* Execute a `.diagram.ts` through jiti (core pinned to `coreEntry`) and return
|
|
4
30
|
* its model — shape-guarded but not validated; callers own validation.
|
package/dist/compile.js
CHANGED
|
@@ -2,7 +2,7 @@ import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
|
2
2
|
import { createRequire } from 'node:module';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { createJiti } from 'jiti';
|
|
5
|
-
import { composeIncludes, DiagramValidationError, diagramWarnings, validate, } from '@diagc/core';
|
|
5
|
+
import { composeIncludes, DiagramValidationError, diagramWarnings, errMessage, validate, } from '@diagc/core';
|
|
6
6
|
import { resolveInclude } from './includes.js';
|
|
7
7
|
import { snapshotSession } from './snapshots.js';
|
|
8
8
|
/**
|
|
@@ -18,6 +18,44 @@ function assertDiagramShape(model, file) {
|
|
|
18
18
|
throw new Error(`${file}: no default export or not a diagram model`);
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
+
/**
|
|
22
|
+
* A source that threw while running — a misspelled method, a builder call that
|
|
23
|
+
* refused — placed at the first stack frame inside that file. V8 writes the file
|
|
24
|
+
* into every frame and jiti keeps the author's lines, so no source map is needed;
|
|
25
|
+
* taking the first frame *in the user's file* also puts a refusal the builder
|
|
26
|
+
* throws at the call that caused it. A transform error has no such frame: then
|
|
27
|
+
* there is no position and the message is left as it was.
|
|
28
|
+
*/
|
|
29
|
+
export class LoadError extends Error {
|
|
30
|
+
file;
|
|
31
|
+
reason;
|
|
32
|
+
line;
|
|
33
|
+
column;
|
|
34
|
+
constructor(file, reason, position) {
|
|
35
|
+
super(position !== undefined ? `${file}:${position.line}:${position.column}: ${reason}` : reason);
|
|
36
|
+
this.file = file;
|
|
37
|
+
this.reason = reason;
|
|
38
|
+
this.name = 'LoadError';
|
|
39
|
+
this.line = position?.line;
|
|
40
|
+
this.column = position?.column;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** The line and column of the first `at` frame inside `file`. Matched on the
|
|
44
|
+
* basename after a path separator: a frame spells the path as it was imported,
|
|
45
|
+
* which a symlinked temp dir would not equal; the message line is skipped because
|
|
46
|
+
* a transform error quotes `file:line:col` there and that is not a frame. */
|
|
47
|
+
export function positionIn(stack, file) {
|
|
48
|
+
const base = path.basename(file).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
49
|
+
const frame = new RegExp(`[\\\\/]${base}:(\\d+):(\\d+)`);
|
|
50
|
+
for (const line of (stack ?? '').split('\n')) {
|
|
51
|
+
if (!line.trimStart().startsWith('at '))
|
|
52
|
+
continue;
|
|
53
|
+
const m = frame.exec(line);
|
|
54
|
+
if (m !== null)
|
|
55
|
+
return { line: Number(m[1]), column: Number(m[2]) };
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
21
59
|
/**
|
|
22
60
|
* Execute a `.diagram.ts` through jiti (core pinned to `coreEntry`) and return
|
|
23
61
|
* its model — shape-guarded but not validated; callers own validation.
|
|
@@ -33,7 +71,17 @@ export async function executeDiagramTs(file, coreEntry) {
|
|
|
33
71
|
moduleCache: false,
|
|
34
72
|
alias: { '@diagc/core': resolvedCoreEntry },
|
|
35
73
|
});
|
|
36
|
-
|
|
74
|
+
let def;
|
|
75
|
+
try {
|
|
76
|
+
def = await jiti.import(path.resolve(file), { default: true });
|
|
77
|
+
}
|
|
78
|
+
catch (e) {
|
|
79
|
+
// A validation error thrown inside the module keeps its shape: lint reads its
|
|
80
|
+
// `issues` by name. Everything else is the source failing to run.
|
|
81
|
+
if (e instanceof Error && e.name === 'DiagramValidationError')
|
|
82
|
+
throw e;
|
|
83
|
+
throw new LoadError(file, errMessage(e), positionIn(e instanceof Error ? e.stack : undefined, file));
|
|
84
|
+
}
|
|
37
85
|
const hasToJSON = typeof def?.toJSON === 'function';
|
|
38
86
|
const model = (hasToJSON ? def.toJSON() : def);
|
|
39
87
|
assertDiagramShape(model, file);
|
package/dist/guide.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Where `diagc guide` reads from, and the release it speaks for. */
|
|
2
|
+
export interface GuideContext {
|
|
3
|
+
guideDir: string;
|
|
4
|
+
startersDir: string;
|
|
5
|
+
version: string;
|
|
6
|
+
}
|
|
7
|
+
/** `diagc guide all`: the index, then every topic — for a reader who cannot ask
|
|
8
|
+
* for one (the copy published on the website). */
|
|
9
|
+
export declare const ALL_TOPIC = "all";
|
|
10
|
+
/**
|
|
11
|
+
* Which node types a topic owns. Core's `NODE_TYPES` is one flat list — it only
|
|
12
|
+
* feeds the lint — so a diagram type's own ids are recognised by their prefix.
|
|
13
|
+
* The index prints whatever no topic claims. A test holds each prefix to at
|
|
14
|
+
* least one real type, so a renamed family cannot quietly empty a topic's list.
|
|
15
|
+
*/
|
|
16
|
+
export declare const TOPIC_TYPE_PREFIXES: Record<string, readonly string[]>;
|
|
17
|
+
/** Thrown for a topic there is no page for; the message lists what there is. */
|
|
18
|
+
export declare class UnknownTopicError extends Error {
|
|
19
|
+
constructor(topic: string, topics: string[]);
|
|
20
|
+
}
|
|
21
|
+
/** Thrown when the guide's own files are not where the install says they are. */
|
|
22
|
+
export declare class GuideMissingError extends Error {
|
|
23
|
+
constructor(guideDir: string);
|
|
24
|
+
}
|
|
25
|
+
/** The topics a guide directory holds: every page but the index, sorted. */
|
|
26
|
+
export declare function guideTopics(guideDir: string): string[];
|
|
27
|
+
/** The guide as Markdown: the index, one topic, or (`all`) everything. A topic is
|
|
28
|
+
* looked up in the listing and never joined into a path first, so `../x` is an
|
|
29
|
+
* unknown topic like any other. */
|
|
30
|
+
export declare function renderGuide(topic: string | undefined, ctx: GuideContext): string;
|
|
31
|
+
export interface GuideIo {
|
|
32
|
+
out(text: string): void;
|
|
33
|
+
err(text: string): void;
|
|
34
|
+
}
|
|
35
|
+
/** `diagc guide [topic]`: print, and return the exit code. The errors a user can
|
|
36
|
+
* cause or meet — a topic that does not exist, an install with no guide, an
|
|
37
|
+
* install with no starter files — are one line on stderr; anything else is a bug
|
|
38
|
+
* in the guide's own files and is left to throw. */
|
|
39
|
+
export declare function runGuide(topics: readonly string[], ctx: GuideContext, io?: GuideIo): number;
|