@modeldesk/cli 0.6.0 → 0.8.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/dist/modeldesk.js CHANGED
@@ -1,78 +1,296 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
3
- import{chmodSync as vn,existsSync as Qo,mkdirSync as es,readFileSync as ts,writeFileSync as ns}from"node:fs";import{homedir as rs}from"node:os";import{join as Cn}from"node:path";var Nn=448,An=384,D=class{dir;file;constructor(t=Cn(rs(),".modeldesk")){this.dir=t,this.file=Cn(t,"credentials.json")}getRefreshToken(t){let n=this.read().hosts[t]?.refreshToken;return typeof n=="string"?n:void 0}saveRefreshToken(t,n){let r=this.read();r.hosts[t]={refreshToken:n},this.write(r)}saveRefreshTokenIfPresent(t,n){n&&this.saveRefreshToken(t,n)}clearHost(t){let n=this.read();return n.hosts[t]?(delete n.hosts[t],this.write(n),!0):!1}read(){if(!Qo(this.file))return{hosts:{}};try{let t=JSON.parse(ts(this.file,"utf8"));if(t&&typeof t=="object"&&t.hosts&&typeof t.hosts=="object")return t}catch{}return{hosts:{}}}write(t){es(this.dir,{recursive:!0,mode:Nn}),ns(this.file,`${JSON.stringify(t,null,2)}
4
- `,{mode:An}),vn(this.dir,Nn),vn(this.file,An)}};var Et=e=>{let t=e.split(".");if(t.length===3)try{let n=Buffer.from(t[1],"base64url").toString("utf8"),r=JSON.parse(n);return r&&typeof r=="object"&&!Array.isArray(r)?r:void 0}catch{return}},Oe=e=>{let t=Et(e);if(t)return t.name&&t.email?`${t.name} <${t.email}>`:t.email??t.name??t.sub};import{spawn as os}from"node:child_process";import{platform as ss}from"node:process";var Mn=e=>{if(!is(e))return;let{command:t,args:n,verbatim:r}=as(e);try{let o=os(t,n,{stdio:"ignore",detached:!0,windowsVerbatimArguments:r});o.on("error",()=>{}),o.unref()}catch{}},is=e=>{try{let{protocol:t}=new URL(e);return t==="http:"||t==="https:"}catch{return!1}},as=(e,t=ss)=>{switch(t){case"darwin":return{command:"open",args:[e]};case"win32":return{command:"cmd",args:["/c","start",'""',ds(e)],verbatim:!0};default:return{command:"xdg-open",args:[e]}}},ds=e=>e.replace(/[&|<>^()%"]/g,t=>`^${t}`);var xe="modeldesk-cli",Rn="modeldesk-federation",Pn="openid",$t="/callback";var ce=e=>e instanceof Error?e.message:String(e),l=class extends Error{exitCode;constructor(t,n=1){super(t),this.name="CliError",this.exitCode=n}};var G=async e=>{let t=`${e.replace(/\/+$/,"")}/.well-known/openid-configuration`,n;try{n=await fetch(t,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(3e4)})}catch(o){throw new l(`Could not reach the auth server at ${e} (${o.message}).`)}if(!n.ok)throw new l(`OpenID discovery failed at ${t}: ${n.status} ${n.statusText}`);let r=await n.json();if(!r.authorization_endpoint||!r.token_endpoint)throw new l(`OpenID discovery at ${t} did not return the authorization and token endpoints.`);return{authorizationEndpoint:r.authorization_endpoint,tokenEndpoint:r.token_endpoint}};import{createServer as cs}from"node:http";var ls=3e5,_n=(e,t=ls)=>new Promise((n,r)=>{let o,s=new Promise((f,m)=>{o={resolve:f,reject:m}}),i=cs((f,m)=>{let u=new URL(f.url??"/","http://127.0.0.1");if(u.pathname!==$t){m.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Not found");return}ms(u,m,e,o)}),a=setTimeout(()=>o.reject(new l("Timed out waiting for the browser login to complete.")),t);a.unref();let d=!1,c=()=>{d||(d=!0,clearTimeout(a),i.close())};s.then(c,c),i.once("error",f=>r(new l(`Could not start the loopback listener: ${f.message}`))),i.listen(0,"127.0.0.1",()=>{let{port:f}=i.address();n({redirectUri:`http://127.0.0.1:${f}${$t}`,waitForCode:()=>s,close:c})})}),ms=(e,t,n,r)=>{if(e.searchParams.get("state")!==n){t.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Unexpected request");return}let o=e.searchParams.get("error");if(o){let i=e.searchParams.get("error_description");xt(t,"Sign-in failed","Sign-in failed. You can close this window and return to the terminal."),r.reject(new l(`Authorization failed: ${i?`${o} (${i})`:o}`));return}let s=e.searchParams.get("code");if(!s){xt(t,"Sign-in failed","No authorization code was returned. You can close this window."),r.reject(new l("Login failed: no authorization code was returned."));return}xt(t,"Signed in","You are signed in to the ModelDesk CLI. You can close this window and return to the terminal."),r.resolve(s)},xt=(e,t,n)=>{let r=`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${t}</title></head><body style="font-family: system-ui, sans-serif; text-align: center; padding: 3rem;"><h1>${t}</h1><p>${n}</p></body></html>`;e.writeHead(200,{"Content-Type":"text/html; charset=utf-8",Connection:"close"}).end(r)};import{createHash as fs,randomBytes as Ln}from"node:crypto";var bt=e=>e.toString("base64url"),Dn=()=>{let e=bt(Ln(32)),t=bt(fs("sha256").update(e).digest());return{verifier:e,challenge:t,method:"S256"}},On=()=>bt(Ln(16));var le=class extends l{oauthError;errorDescription;constructor(t,n,r){super(t),this.name="TokenEndpointError",this.oauthError=n,this.errorDescription=r}},Fn=e=>e instanceof le&&e.oauthError==="invalid_grant",Hn=(e,t)=>He(e,new URLSearchParams({grant_type:"authorization_code",code:t.code,redirect_uri:t.redirectUri,client_id:xe,code_verifier:t.codeVerifier})),Fe=(e,t)=>He(e,new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:xe})),Un=(e,t)=>He(e,new URLSearchParams({grant_type:"client_credentials",client_id:t.clientId,client_secret:t.clientSecret})),Bn=(e,t)=>He(e,new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token:t,subject_token_type:"urn:ietf:params:oauth:token-type:jwt",client_id:Rn})),He=async(e,t)=>{let n;try{n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:t.toString(),signal:AbortSignal.timeout(3e4)})}catch(o){throw new l(`Could not reach the token endpoint (${o.message}).`)}if(!n.ok){let{message:o,code:s,description:i}=await ps(n);throw new le(`Token request failed: ${o}`,s,i)}let r=await n.json();if(!r.access_token)throw new l("The token response did not include an access token.");return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresInSeconds:r.expires_in??0}},ps=async e=>{try{if((e.headers.get("content-type")??"").includes("json")){let n=await e.json();if(n.error)return{message:n.error_description?`${n.error} (${n.error_description})`:n.error,code:n.error,description:n.error_description}}}catch{}return{message:`${e.status} ${e.statusText}`.trim()}};var Ue={info:e=>process.stderr.write(`${e}
5
- `)},Be=async(e,t)=>{let{authorizationEndpoint:n,tokenEndpoint:r}=await G(e.issuer),o=Dn(),s=On(),i=await _n(s);try{let a=us(n,i.redirectUri,o.challenge,s);t.info(`Opening your browser to sign in to ${e.host}...`),t.info(`If it does not open automatically, visit:
6
- ${a}`),Mn(a);let d=await i.waitForCode();return await Hn(r,{code:d,redirectUri:i.redirectUri,codeVerifier:o.verifier})}finally{i.close()}},us=(e,t,n,r)=>{let o=new URL(e);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",xe),o.searchParams.set("redirect_uri",t),o.searchParams.set("scope",Pn),o.searchParams.set("state",r),o.searchParams.set("code_challenge",n),o.searchParams.set("code_challenge_method","S256"),o.toString()};var St="modeldesk.io",k={host:"MODELDESK_HOST",model:"MODELDESK_MODEL",stack:"MODELDESK_STACK",template:"MODELDESK_TEMPLATE",version:"MODELDESK_VERSION",clientId:"MODELDESK_CLIENT_ID",clientSecret:"MODELDESK_CLIENT_SECRET",apiKey:"MODELDESK_API_KEY"},be=(...e)=>e.find(t=>t!==void 0&&t!==""),Se=(e,t,n)=>({host:be(e.host,t[k.host],n.host)??St,model:be(e.model,t[k.model],n.model),stack:be(e.stack,t[k.stack],n.stack),template:be(e.template,t[k.template],n.template),version:be(e.version,t[k.version],n.version)});var jn={requestUrl:"ACTIONS_ID_TOKEN_REQUEST_URL",requestToken:"ACTIONS_ID_TOKEN_REQUEST_TOKEN"},K=e=>e!==void 0&&e!=="",Wn=e=>e==="true"||e==="1",hs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Tt="mdsk_",zn=57,ee=(e,t)=>({mode:"error",reason:e,message:t}),V="org settings \u2192 Service accounts",Te=e=>{if(K(e[k.apiKey]))return ee("legacy-api-key",`${k.apiKey} is no longer supported: the CI credential shipped as service accounts, not bearer keys. Use secret mode (set ${k.clientId} and ${k.clientSecret} from ${V}) or, on GitHub Actions, federated auth (grant 'permissions: id-token: write' and add a trust rule). Unset ${k.apiKey}.`);let t=e[k.clientId],n=e[k.clientSecret];if(K(t)!==K(n)){let[s,i]=K(t)?[k.clientId,k.clientSecret]:[k.clientSecret,k.clientId];return ee("partial-secret-config",`${s} is set but ${i} is not \u2014 both are required for secret-mode auth. Check the pipeline's secret configuration.`)}if(K(t)&&K(n))return hs.test(t)?n.startsWith(Tt)?n.length!==zn?ee("invalid-client-secret",`${k.clientSecret} has the wrong length: expected ${zn} characters, got ${n.length}. Check for truncation in the pipeline's secret store.`):{mode:"secret",clientId:t,clientSecret:n}:ee("invalid-client-secret",`${k.clientSecret} does not start with '${Tt}' (an issued secret always does). Check for quoting or truncation in the pipeline's secret store.`):ee("invalid-client-id",`${k.clientId} is not a service-account id: expected a UUID, got a ${t.length}-character value. Copy the account id from ${V}.`);let r=e[jn.requestUrl],o=e[jn.requestToken];return K(r)&&K(o)?{mode:"federated",oidcRequestUrl:r,oidcRequestToken:o}:Wn(e.GITHUB_ACTIONS)?ee("headless-ci",`Running on GitHub Actions without machine credentials. Grant 'permissions: id-token: write' to use federated auth (with a trust rule in ${V}), or set ${k.clientId} and ${k.clientSecret}. The CLI never opens a browser login in CI.`):Wn(e.CI)?ee("headless-ci",`Running in CI without machine credentials. Set ${k.clientId} and ${k.clientSecret} (${V}). The CLI never opens a browser login in CI.`):{mode:"interactive"}},Y=e=>{let t=Te(e);return t.mode==="secret"||t.mode==="federated"?t.mode:void 0},Gn=e=>`${e.slice(0,Tt.length+8)}\u2026`,Kn=`Check ${k.clientId} and ${k.clientSecret}; issue or rotate a secret in ${V}.`,Vn=`The service account may be disabled or deleted \u2014 check ${V}.`,Yn={issuer:"the auth server does not trust this token issuer \u2014 federated auth currently supports GitHub Actions only.",signature:"the OIDC token's signature could not be verified \u2014 re-run the job; if it persists, the issuer's keys and the auth server disagree.",audience:`the workflow's OIDC audience does not match this host \u2014 check that --host/${k.host} names the ModelDesk instance the trust rule lives on.`,expired:"the OIDC token expired before the exchange \u2014 re-run the job.",repository:"no active trust rule matches this repository. This is also the failure for a pull-request-triggered run unless the rule enables 'Allow pull requests', and for a revoked rule.",binding:"the trust rule pins a branch or environment that does not match this run."},je={unauthorized:`The machine token was rejected. A disabled or deleted service account fails on the next request; a revoked secret within five minutes. Check ${V}.`,forbidden:`The service account's scopes do not permit this \u2014 pulling content needs the 'model:content' scope (${V}).`,notFound:"Check the model id. A machine credential reads SHARED models only (creator-private models are not visible), and the model's metamodel must be entitled under the organization's subscription."};var gs="http://localhost:8080",ys="http://localhost:8082",ws="localhost",ks=e=>{let t=e.trim(),n=/:\/\//.test(t)?t:`https://${t}`;try{return new URL(n).hostname}catch{return t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").split("/")[0].split(":")[0]}},Es=e=>e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]",It=e=>{let t=ks(e);return Es(t)?{host:ws,apiBase:gs,issuer:ys}:{host:t,apiBase:`https://api.${t}`,issuer:`https://auth.${t}`}};import{existsSync as xs,readFileSync as bs}from"node:fs";import{join as Ss}from"node:path";import{posix as $s}from"node:path";var me=e=>{if(e.trim()==="")return"is empty";if(e.includes("\\"))return'has a backslash; separate folders with "/"';if(/[\t\r\n]/.test(e))return"has a tab or a line break";if(e.startsWith("/")||/^[A-Za-z]:/.test(e))return"is absolute";if(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e))return"is a URL";if(e.includes("%"))return'has a "%", which the document reads as a percent-escape; name the file without one';if(e.includes("#"))return'has a "#", which the document reads as the start of a fragment; name the file without one';if(e.includes("?"))return'has a "?", which the document reads as the start of a query; name the file without one';if(e.split("/").some(t=>t!==t.trim()))return"has a folder or file name that starts or ends with a space";if(e.split("/").includes(".."))return'has a ".." segment'},T=e=>$s.normalize(e).replace(/(.)\/+$/,"$1"),te=(e,t)=>{let n=T(e),r=T(t);return r==="."||n===r||n.startsWith(`${r}/`)};var pe=".modeldesk",Ts="config.json",We="md-notes/",ze=e=>e.configPath!==void 0,Ie=e=>{let t=Ss(e,pe,Ts);return xs(t)?{config:Is(t),configPath:t,repoRoot:e}:{config:{},repoRoot:e}},Is=e=>{let t;try{t=bs(e,"utf8")}catch(o){throw new l(`Could not read ${e}: ${o.message}`)}let n;try{n=JSON.parse(t)}catch(o){throw new l(`${e} is not valid JSON: ${o.message}`)}if(n===null||typeof n!="object"||Array.isArray(n))throw new l(`${e} must contain a JSON object.`);let r=n;return{host:fe(r,"host",e),model:fe(r,"model",e),stack:fe(r,"stack",e),template:fe(r,"template",e),version:fe(r,"version",e),notesDir:vs(r,"notesDir",e),publishDirs:Cs(r,"publishDirs",e)}},fe=(e,t,n)=>{let r=e[t];if(r!==void 0){if(typeof r!="string")throw new l(`${n}: "${t}" must be a string.`);return r}},vs=(e,t,n)=>{let r=fe(e,t,n);return r!==void 0&&Xn(r,`"${t}"`,n),r},Cs=(e,t,n)=>{let r=e[t];if(r!==void 0){if(!Array.isArray(r)||!r.every(o=>typeof o=="string"))throw new l(`${n}: "${t}" must be an array of strings.`);return r.forEach((o,s)=>Xn(o,`"${t}"[${s}]`,n)),r}},Xn=(e,t,n)=>{let r=me(e);if(r!==void 0)throw new l(`${n}: ${t} ${JSON.stringify(e)} ${r}; give a folder relative to the repository root.`)};import{parseArgs as Ns}from"node:util";var X=(e,t,{positionals:n}={})=>{try{return Ns({args:e,options:t,allowPositionals:n??!1,strict:!0})}catch(r){throw new l(r.message)}};var Jn=(e,t,n)=>{let r=n[k.host];return!(t!==void 0&&t!==""||r!==void 0&&r!=="")&&ze(e)&&!!e.config.host},qn=(e,t,n)=>{Jn(e,t,n)&&e.config.host!==St&&process.stderr.write(`note: using host '${e.config.host}' from ${e.configPath} (it drives login and API calls).
7
- `)},Zn=(e,t,n)=>{if(Y(n)&&Jn(e,t,n))throw new l(`In a machine-auth run the host must be set explicitly: pass --host or set ${k.host}. The committed ${e.configPath??".modeldesk/config.json"} is not a trusted source for where machine credentials are sent.`)},ue=(e,t={})=>{let{values:n}=X(e.argv,{host:{type:"string"}}),r=Ie(e.cwd),o=Se({host:n.host},e.env,r.config);return t.gateMachineHost&&Zn(r,n.host,e.env),qn(r,n.host,e.env),It(o.host)},Ge=(e,t)=>{let n=Ie(e.cwd),r=Se(t,e.env,n.config);if(Zn(n,t.host,e.env),qn(n,t.host,e.env),!r.model)throw new l(`No model specified. Pass --model, set ${k.model}, or add "model" to .modeldesk/config.json.`);return{instance:It(r.host),model:r.model,stack:r.stack,template:r.template,version:r.version,loaded:n}},ve=(e,t,n,r)=>{let o=e?.trim();if(!o)throw new l(`No ${t} specified. Pass ${r}, set ${n}, or add "${t}" to .modeldesk/config.json. Run 'modeldesk bundle templates' to list a model's stacks and templates.`);return o};var Qn=async e=>{let t=Y(e.env);t&&process.stderr.write(`warning: machine auth (${t} mode) is active in this environment and takes precedence for API commands; this login only affects interactive use.
8
- `);let n=ue(e),r=await Be(n,Ue),o=new D;r.refreshToken?o.saveRefreshToken(n.host,r.refreshToken):o.clearHost(n.host);let s=Oe(r.accessToken);return process.stdout.write(`Logged in to ${n.host}${s?` as ${s}`:""}.
9
- `),r.refreshToken||process.stderr.write(`warning: the server returned no refresh token, so later commands will re-open the browser each time instead of running unattended.
10
- `),0};var er=async e=>{let t=Y(e.env);t&&process.stderr.write(`warning: machine auth (${t} mode) is active in this environment and takes precedence for API commands; this logout does not remove machine credentials.
11
- `);let n=ue(e),r=new D().clearHost(n.host);return process.stdout.write(r?`Logged out of ${n.host}.
12
- `:`No stored credential for ${n.host}.
13
- `),0};var vt=6e4,Ke=class{constructor(t,n={}){this.instance=t;this.store=n.store??new D,this.io=n.io??Ue,this.now=n.now??Date.now}instance;store;io;now;accessToken;accessTokenExpiresAt=0;endpoints;async getAccessToken(){if(this.accessToken&&this.now()<this.accessTokenExpiresAt-vt)return this.accessToken;let t=this.store.getRefreshToken(this.instance.host);if(t){let n=await this.tryRefresh(t);if(n)return n}return this.login()}async tryRefresh(t){let{tokenEndpoint:n}=await this.getEndpoints();try{return this.apply(await Fe(n,t))}catch(r){if(Fn(r))return;throw r}}async login(){return this.apply(await Be(this.instance,this.io))}apply(t){return this.accessToken=t.accessToken,this.accessTokenExpiresAt=this.now()+t.expiresInSeconds*1e3,this.store.saveRefreshTokenIfPresent(this.instance.host,t.refreshToken),t.accessToken}async getEndpoints(){return this.endpoints||(this.endpoints=await G(this.instance.issuer)),this.endpoints}};var Ct=class{constructor(t,n,r,o={}){this.instance=t;this.mode=n;this.mint=r;this.now=o.now??Date.now,this.discover=o.discover??G}instance;mode;mint;now;discover;accessToken;accessTokenExpiresAt=0;endpoints;inflight;async getAccessToken(){return this.accessToken&&this.now()<this.accessTokenExpiresAt-vt?this.accessToken:(this.inflight||(this.inflight=this.mintFresh().finally(()=>{this.inflight=void 0})),this.inflight)}async mintFresh(){let{tokenEndpoint:t}=await this.getEndpoints(),n;try{n=await this.mint(t)}catch(r){throw Ms(r,this.mode)}if(n.expiresInSeconds<=0)throw new l("The token response did not include a token lifetime (expires_in), so the machine token cannot be cached. This indicates a server problem.");return this.accessToken=n.accessToken,this.accessTokenExpiresAt=this.now()+n.expiresInSeconds*1e3,n.accessToken}async getEndpoints(){return this.endpoints||(this.endpoints=await this.discover(this.instance.issuer)),this.endpoints}},As=async(e,t,n)=>{let r;try{r=await fetch(`${e}&audience=${encodeURIComponent(n)}`,{headers:{Authorization:`bearer ${t}`,Accept:"application/json"},signal:AbortSignal.timeout(3e4)})}catch(s){throw new l(`Could not reach the GitHub OIDC token endpoint (${s.message}).`)}if(!r.ok)throw new l(`The GitHub OIDC token request failed (${r.status} ${r.statusText}). Check that the workflow grants 'permissions: id-token: write'.`);let o=await r.json().catch(()=>{});if(!o?.value)throw new l("The GitHub OIDC token response did not include a token value. Check that the workflow grants 'permissions: id-token: write'.");return o.value},Ve=(e,t,n={})=>{let r=t.mode==="secret"?o=>Un(o,{clientId:t.clientId,clientSecret:t.clientSecret}):async o=>Bn(o,await As(t.oidcRequestUrl,t.oidcRequestToken,e.issuer));return new Ct(e,t.mode,r,n)},Ms=(e,t)=>{if(!(e instanceof le)||!e.oauthError)return e;if(t==="secret")return e.oauthError==="invalid_client"?new l(`${e.message} ${Kn}`):e;if(e.errorDescription===void 0)return e.oauthError==="invalid_grant"?new l(`${e.message} ${Vn}`):e;let n=Yn[e.errorDescription];return n?new l(`${e.message} \u2014 ${n}`):e};var U=e=>{process.stdout.write(`${e}
14
- `)},tr=async e=>{let t=Te(e.env);if(t.mode==="error")throw new l(t.message);let n=t.mode==="secret"||t.mode==="federated",r=ue(e,{gateMachineHost:n});return U(`Host: ${r.host}`),U(`API: ${r.apiBase}`),t.mode==="secret"||t.mode==="federated"?Rs(r,t,e.env):Ps(r)},Rs=async(e,t,n)=>{t.mode==="secret"?U(`Auth: service account (secret mode), client ${t.clientId}, secret ${Gn(t.clientSecret)}`):U(`Auth: federated (GitHub Actions), repository ${n.GITHUB_REPOSITORY??"unknown"}, ref ${n.GITHUB_REF??"unknown"}`);let r=await Ve(e,t).getAccessToken(),o=Et(r)??{};U(`Status: credential valid. Account ${o.sub??"unknown"}, organization ${o.mdsk_org??"unknown"}.`);let s=typeof o.scope=="string"?o.scope.trim():"";return U(s?`Scopes: ${s}`:"Scopes: enforced server-side from the account's current scopes."),0},Ps=async e=>{let t=new D,n=t.getRefreshToken(e.host);if(!n)return U("Status: not logged in. Run 'modeldesk auth login'."),1;try{let{tokenEndpoint:r}=await G(e.issuer),o=await Fe(r,n);t.saveRefreshTokenIfPresent(e.host,o.refreshToken);let s=Oe(o.accessToken);return U(`Status: logged in${s?` as ${s}`:""} (credential valid).`),0}catch{return U("Status: the stored credential could not be verified (it may be expired or revoked, or the server is unreachable). Run 'modeldesk auth login'."),1}};var Ye=(e,t)=>e.at(-1)===""&&t==="";var _s=e=>`<figure data-md-diagram="${e}">`,Ls="</figure>",Nt=(e,t)=>{if(t.size===0||e.payloads===void 0)return e;let n=new Set([...t].map(_s)),r=Object.fromEntries(Object.entries(e.payloads).map(([o,s])=>[o,Ds(s,n)]));return{...e,payloads:r}},Ds=(e,t)=>{let n=e.split(`
15
- `),r=[];for(let o=0;o<n.length;o+=1){let s=t.has(n[o])?n.indexOf(Ls,o):-1;if(s===-1){r.push(n[o]);continue}o=s,Ye(r,n[o+1])&&(o+=1)}return r.join(`
16
- `)};var At=e=>`${JSON.stringify(e,null,2)}
17
- `;var A=["intro","after"],O=e=>{let t=new Map;for(let n of e.fragments??[]){let r=t.get(n.elementId)??{};t.set(n.elementId,{title:r.title||n.title||void 0,kind:r.kind||n.kind||void 0,anchor:r.anchor||n.realization?.anchor||void 0})}return t},Os=/^<!-- md-slot (?=intro [0-9a-f-]{36} -->$|after )(intro|after) ([0-9a-f-]{36})(?: heading=([1-6]))? -->$/,Fs="<!-- md-slot ",Ce=class extends Error{constructor(n){super(`The bundle carries a note slot this version cannot read: ${n}. The client is older than the server.`);this.line=n;this.name="UnreadableSlotError"}line},rr=e=>{if(!e.startsWith(Fs))return;let t=Os.exec(e);if(t===null)throw new Ce(e);let n={name:t[1],elementId:t[2]};return t[3]===void 0?n:{...n,heading:Number(t[3])}},or=e=>{let t=new Map;for(let[n,r]of Object.entries(e.payloads??{})){let o=r.split(`
18
- `).flatMap(s=>rr(s)??[]);o.length>0&&t.set(n,o)}return t},Mt=(e,t)=>{if(e.payloads===void 0)return{bundle:e,filled:[],dropped:[]};let n=O(e.manifest),r=a=>n.get(a)?.anchor,o=[],s=[],i=Object.fromEntries(Object.entries(e.payloads).map(([a,d])=>{let c=Hs(d,t,r);return o.push(...c.filled.map(f=>({...f,address:a}))),s.push(...c.dropped.map(f=>({...f,address:a}))),[a,c.text]}));return{bundle:{...e,payloads:i},filled:o,dropped:s}},Hs=(e,t,n)=>{let r=e.split(`
19
- `),o=[],s=new Set,i=[],a=[];for(let d=0;d<r.length;d+=1){let c=rr(r[d]);if(c===void 0){o.push(r[d]);continue}let f=t.get(c.elementId)?.[c.name],m=`${c.name} ${c.elementId}`;if(f!==void 0&&!s.has(m)){s.add(m),i.push(c),o.push(...Us(c,f,n));continue}f!==void 0&&a.push(c),Ye(o,r[d+1])&&(d+=1)}return{text:o.join(`
20
- `),filled:i,dropped:a}},Us=(e,t,n)=>{if(e.heading===void 0){if(typeof t!="string")throw new Error(`The ${e.name} slot of ${e.elementId} takes a note path, not a heading.`);return[nr(t)]}if(typeof t=="string")throw new Error(`The ${e.name} slot of ${e.elementId} takes a note with a heading.`);let r=n(e.elementId);if(r===void 0)throw new Error(`The bundle's manifest has no anchor for ${e.elementId}.`);let o=t.heading.replace(/\s+/g," ").trim();if(o==="")throw new Error(`The ${e.name} note of ${e.elementId} has an empty heading.`);let s=`${r}-${ne(o)||e.name}`;return[`${"#".repeat(e.heading)} ${js(o)} {#${s}}`,"",nr(t.file)]},ne=e=>e.normalize("NFD").replace(new RegExp("\\p{M}","gu"),"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),nr=e=>`<div data-include-format="markdown" data-include="${Bs(e)}"></div>`,Bs=e=>e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\n/g,"&#10;").replace(/\r/g,"&#13;"),js=e=>e.replace(/[\\`*_[\]()!#|~]/g,"\\$&").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\{/g,"&#123;").replace(/\}/g,"&#125;");var Ws=/[ \t\n\r\f]+/g,zs=/^[ \t\n\r\f]+|[ \t\n\r\f]+$/g,Gs=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Ne=e=>e.replace(Gs,"");var Ks=(e,t)=>{if(!Number.isFinite(e))throw new Error(`Cannot write ${e} as an SVG number`);let n=10**t,r=Math.sign(e)*Math.round(Math.abs(e)*n)/n;return String(r===0?0:r)},Rt=e=>Ks(e,2);var Vs=e=>e.replace(Ws," ").replace(zs,""),Pt=e=>Vs(Ne(e)).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;");var Ae="http://www.w3.org/2000/svg",ar="Inter, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",_t="group",Lt="spacingAndGlyphs",Dt="italic",Ot="underline",he="none";var Xe="hidden",Je="stroke",Ft="auto";var Ys="start",qe="clip",Xs=/^[A-Za-z0-9_-]+$/,Js=/[^A-Za-z0-9_-]+/g,Ht=e=>Xs.test(e),dr=e=>e.replace(Js,"-");var Ut=(e,t)=>t?`${e}-${Ys}`:e,sr=String.raw`-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?`,ir=String.raw`[a-zA-Z]+\(\s*(?:${sr}(?:[\s,]+${sr})*)?\s*\)`,qs=new RegExp(String.raw`^${ir}(?:\s+${ir})*$`),cr=e=>qs.test(e);var Zs=/[\u0000- \u007F]/g,Qs=/^([a-zA-Z][a-zA-Z0-9+.-]*):/,ei=new Set(["http","https","mailto"]),Ze=e=>{let t=Ne(e).replace(Zs,"");if(t==="")return!1;let n=Qs.exec(t);return n===null||ei.has(n[1].toLowerCase())};var $="#4b5563";var P="white";var Bt="strokeWidth",Qe=[{id:"triangle-filled",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"line",x1:16,y1:10,x2:20,y2:10,stroke:"white",strokeWidth:2},{element:"path",d:"M 6 4 L 19 10 L 6 16 L 10 10 Z",fill:$,stroke:$,strokeWidth:1}]},{id:"triangle-hollow",markerWidth:24,markerHeight:24,refX:24,refY:12,shapes:[{element:"line",x1:20,y1:12,x2:24,y2:12,stroke:"white",strokeWidth:2},{element:"path",d:"M 6 2 L 22 12 L 6 22 Z",fill:P,stroke:$,strokeWidth:2}]},{id:"diamond-filled",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"path",d:"M 10 5 L 19 10 L 10 15 L 1 10 Z",fill:$,stroke:$,strokeWidth:1.5}]},{id:"diamond-hollow",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"path",d:"M 10 5 L 19 10 L 10 15 L 1 10 Z",fill:P,stroke:$,strokeWidth:1.5}]},{id:"arrow-open",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"path",d:"M 6 4 L 19 10 L 6 16",fill:"none",stroke:$,strokeWidth:2}]},{id:"bar",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"line",x1:13,y1:1,x2:13,y2:11,stroke:$,strokeWidth:1.5}]},{id:"circle",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"circle",cx:13.5,cy:6,r:2.75,fill:P,stroke:$,strokeWidth:1.5}]},{id:"crowsfoot",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 18 1 L 8 6 L 18 11 M 8 6 L 18 6",fill:"none",stroke:$,strokeWidth:1.5}]},{id:"crowsfoot-bar",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 18 1 L 8 6 L 18 11 M 8 6 L 18 6",fill:"none",stroke:$,strokeWidth:1.5},{element:"line",x1:4,y1:1,x2:4,y2:11,stroke:$,strokeWidth:1.5}]},{id:"crowsfoot-circle",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 18 1 L 8 6 L 18 11 M 8 6 L 18 6",fill:"none",stroke:$,strokeWidth:1.5},{element:"circle",cx:4,cy:6,r:2.75,fill:P,stroke:$,strokeWidth:1.5}]},{id:"bar-circle",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"line",x1:13,y1:1,x2:13,y2:11,stroke:$,strokeWidth:1.5},{element:"circle",cx:4,cy:6,r:2.75,fill:P,stroke:$,strokeWidth:1.5}]},{id:"crowsfoot-triangle-circle",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 24 3 L 19 3 M 24 6 L 19 6 M 24 9 L 19 9",fill:"none",stroke:$,strokeWidth:1.5},{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:P,stroke:$,strokeWidth:1.5,strokeLinejoin:"round"},{element:"circle",cx:8.25,cy:6,r:2.75,fill:P,stroke:$,strokeWidth:1.5}]},{id:"crowsfoot-triangle-bar",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 24 3 L 19 3 M 24 6 L 19 6 M 24 9 L 19 9",fill:"none",stroke:$,strokeWidth:1.5},{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:P,stroke:$,strokeWidth:1.5,strokeLinejoin:"round"},{element:"line",x1:8,y1:1,x2:8,y2:11,stroke:$,strokeWidth:1.5}]},{id:"triangle-circle",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:P,stroke:$,strokeWidth:1.5,strokeLinejoin:"round"},{element:"circle",cx:8.25,cy:6,r:2.75,fill:P,stroke:$,strokeWidth:1.5}]},{id:"triangle-bar",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:P,stroke:$,strokeWidth:1.5,strokeLinejoin:"round"},{element:"line",x1:8,y1:1,x2:8,y2:11,stroke:$,strokeWidth:1.5}]},{id:"cup",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 13 1 A 5 5 0 0 0 13 11",fill:"none",stroke:$,strokeWidth:1.5}]}],El=new Map(Qe.map(e=>[e.id,e]));var si=" ",jt=["fill","fill-opacity","stroke","stroke-opacity","stroke-width","stroke-dasharray"],ii={svg:["xmlns","viewBox","width","height","role","aria-label","font-family"],defs:[],marker:["id","markerWidth","markerHeight","refX","refY","orient","markerUnits"],clipPath:["id"],g:["data-md-element","clip-path","transform"],a:["href"],title:[],desc:[],rect:["x","y","width","height","rx",...jt],path:["d",...jt,"stroke-linejoin","marker-start","marker-end","visibility","pointer-events"],polygon:["points",...jt],line:["x1","y1","x2","y2","fill","stroke","stroke-opacity","stroke-width","stroke-dasharray"],circle:["cx","cy","r","fill","stroke","stroke-width"],text:["x","y","font-size","font-weight","font-style","text-decoration","fill","fill-opacity","textLength","lengthAdjust"]},hr=new Map(Object.entries(ii).map(([e,t])=>[e,new Set(t)])),ai=new Set(["title","desc","text"]),lr="svg",ge="g",B="a",gr="title",Me="data-md-element",yr="path",wr=["visibility","pointer-events"],kr=new Set(["rect","text","polygon","line"]),di={"clip-path":"clipPath","marker-start":"marker","marker-end":"marker"},Er=/&(amp|lt|gt|quot|apos);/g,ci={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},li=/[<>"']/,mi=/[\u0000-\u001F]/,fi=/^<([^\s/>]+)/,pi=/^<\/([^\s/>]+)>/,Wt=/ ([^\s=/>"'<]+)=/y,zt=/"([^"]*)"/y,ui=/^on/i,hi=/^ */,gi=64,mr=/[\p{Cc}\p{Cf}\u2028\u2029]/gu,j=String.raw`-?\d+(?:\.\d+)?(?:e\+\d+)?`,yi=new RegExp(`^${j}$`),wi=/^(?:[1-9]\d{0,2}|1000)$/,ki=new RegExp(`^0 0 ${j} ${j}$`),Ei=new RegExp(`^${j}(?:[ ,]${j})*$`),$i=new RegExp(`^(?:${j},${j}(?: ${j},${j})*)?$`),xi=/^[MmZzLlHhVvCcSsQqTtAa0-9eE.,+\- ]*$/,$r=/^url\(#([A-Za-z0-9_-]+)\)$/,xr=/^#[0-9a-f]{6}$/,fr=Array.from(new Set([he,...Qe.flatMap(({shapes:e})=>e.flatMap(t=>["fill"in t?t.fill:he,t.stroke])).filter(e=>!xr.test(e))])),br=Qe.flatMap(({id:e})=>[Ut(e,!1),Ut(e,!0)]),bi=new RegExp(`^${qe}-[1-9]\\d*$`),Si=new RegExp(`-${qe}-[1-9]\\d*$`),Vt=`${"md"}-`,Yt=e=>`U+${e.codePointAt(0).toString(16).toUpperCase().padStart(4,"0")}`,C=e=>{let t=[];for(let n of e){if(t.length===gi)return`${t.join("").replace(mr,Yt)}\u2026`;t.push(n)}return e.replace(mr,Yt)},Sr=e=>{if(e.includes("&#"))return"a numeric character reference is not allowed";let t=e.replace(Er,"");if(t.includes("&"))return"& does not start one of the five XML entities";let n=li.exec(t);return n===null?void 0:`an unescaped ${n[0]} is not allowed`},Tr=e=>e.replace(Er,(t,n)=>ci[n]),re=(e,t)=>n=>e.test(n)?void 0:`"${C(n)}" is not ${t}`,_=(e,t)=>n=>e.includes(Tr(n))?void 0:`"${C(n)}" is not ${t}`,pr=()=>{},S=re(yi,"a number as the serializer writes one"),ur=e=>xr.test(e)||fr.includes(e)?void 0:`"${C(e)}" is not a paint the serializer writes (#rrggbb, ${fr.join(", ")})`,Gt=re($r,"a reference to a definition in the file, as url(#\u2026)"),Ti=e=>bi.test(e)?"clipPath":br.includes(e)?"marker":void 0,Ii=(e,t)=>{if(!e.startsWith(Vt))return;let n=e.slice(Vt.length);if(t!==void 0)return n.startsWith(`${t}-`)?Ti(n.slice(t.length+1)):void 0;if(Ht(n))return(Si.exec(n)?.index??0)>0?"clipPath":br.some(r=>n.length>r.length+1&&n.endsWith(`-${r}`))?"marker":void 0},vi=(e,t,{idPrefix:n})=>{if(Ii(e,n)===t)return;let r=n??"<prefix>",o=t==="marker"?"<marker>[-start]":`${qe}-<n>`;return`"${C(e)}" is not an id the serializer gives a <${t}> (${Vt}${r}-${o})`},Ci=e=>{let t=Tr(e);return t.startsWith("#")&&Ze(t)?void 0:`"${C(e)}" does not point at a section of the page (#\u2026)`},Ni={xmlns:_([Ae],"the SVG namespace"),viewBox:re(ki,"a viewBox the serializer writes (0 0 width height)"),width:S,height:S,role:_([_t],`the role the serializer writes (${_t})`),"aria-label":pr,"font-family":_([ar],"the serializer's font stack"),id:vi,markerWidth:S,markerHeight:S,refX:S,refY:S,orient:_([Ft],`the marker orientation the serializer writes (${Ft})`),markerUnits:_([Bt],`the marker units the serializer writes (${Bt})`),"data-md-element":pr,"clip-path":Gt,transform:e=>cr(e)?void 0:`"${C(e)}" is not a transform of numbers the serializer writes`,href:Ci,x:S,y:S,rx:S,fill:ur,"fill-opacity":S,stroke:ur,"stroke-opacity":S,"stroke-width":S,"stroke-dasharray":re(Ei,"a dash pattern of numbers"),d:re(xi,"path data (commands and numbers only)"),"stroke-linejoin":_(["round"],"the line join the serializer writes (round)"),"marker-start":Gt,"marker-end":Gt,points:re($i,"polygon points as the serializer writes them (x,y x,y \u2026)"),x1:S,y1:S,x2:S,y2:S,cx:S,cy:S,r:S,"font-size":S,"font-weight":re(wi,"a numeric font weight (1 to 1000)"),"font-style":_([Dt],`the font style the serializer writes (${Dt})`),"text-decoration":_([Ot],`the decoration the serializer writes (${Ot})`),textLength:S,lengthAdjust:_([Lt],`the length adjustment the serializer writes (${Lt})`),visibility:_([Xe],`the visibility of a hit area (${Xe})`),"pointer-events":_([Je],`the pointer events of a hit area (${Je})`)},Ai=(e,t)=>{if(ui.test(t))return`the event-handler attribute ${C(t)} is not allowed`;if(t.toLowerCase()==="style")return"a style attribute is not allowed";if(t.toLowerCase()==="class")return"a class attribute is not allowed";if(t.includes(":"))return`the namespaced attribute ${C(t)} is not allowed`;if(!hr.get(e).has(t))return`<${e}> does not take the attribute ${C(t)}`},Mi=(e,t,n,r)=>{let o=Sr(n)??Ni[t](n,e,r);return o===void 0?void 0:`${t}: ${o}`},Ri=(e,t,n,r)=>{let o=new Map,s=n;for(;t[s]!==">"&&!t.startsWith("/>",s);){Wt.lastIndex=s;let i=Wt.exec(t)?.[1];if(i===void 0)return{problem:'a tag the serializer would not write: expected ` name="value"`, `>` or `/>`'};zt.lastIndex=Wt.lastIndex;let a=zt.exec(t)?.[1];if(a===void 0)return{problem:`the value of ${C(i)} is not double-quoted`};let d=Ai(e,i)??Mi(e,i,a,r);if(d!==void 0)return{problem:d};if(o.has(i))return{problem:`<${e}> repeats the attribute ${i}`};o.set(i,a),s=zt.lastIndex}return{attributes:o,end:s}},Kt=e=>e.startsWith("<")?"more than one element on one line":"text outside <title> and <text>",Pi=(e,t)=>{if(e.includes("<!"))return{problem:"a markup declaration (<!\u2026>: a DOCTYPE, an ENTITY, a comment or CDATA) is not allowed"};if(e.includes("<?"))return{problem:"a processing instruction (<?\u2026?>) is not allowed"};if(e.startsWith("</")){let m=pi.exec(e);if(m===null)return{problem:"a closing tag the serializer would not write"};let u=e.slice(m[0].length);return u!==""?{problem:Kt(u)}:{line:{kind:"close",name:m[1]}}}let n=fi.exec(e)?.[1];if(n===void 0)return{problem:"the line does not start with a tag"};if(!hr.has(n))return{problem:`<${C(n)}> is not an element the diagram serializer writes`};let r=Ri(n,e,n.length+1,t);if("problem"in r)return r;let{attributes:o,end:s}=r,i=e.startsWith("/>",s),a=e.slice(s+(i?2:1));if(!ai.has(n))return a!==""?{problem:Kt(a)}:{line:{kind:i?"empty":"open",name:n,attributes:o}};if(i||a==="")return{problem:`<${n}> has to hold its text on one line, as <${n}>\u2026</${n}>`};let d=`</${n}>`,c=a.indexOf(d);if(c===-1)return{problem:`<${n}> is not closed on its line`};if(c+d.length!==a.length)return{problem:Kt(a.slice(c+d.length))};let f=Sr(a.slice(0,c));return f===void 0?{line:{kind:"text",name:n,attributes:o}}:{problem:`text: ${f}`}},_i=(e,t)=>{if(e.name===lr!=(t===0))return t===0?`the file opens with <${e.name}>, not the serializer's <svg xmlns="${Ae}"> root`:"<svg> is only the root, never nested";if(e.name===lr&&(e.kind!=="open"||e.attributes.get("xmlns")!==Ae))return`the root is not the serializer's <svg xmlns="${Ae}">`;if(e.name===B&&!e.attributes.has("href"))return"<a> without an href"},Li=(e,t,n)=>{if(t.name===B&&t.children===0&&e.name!==gr)return"<a> has to open with the <title> of the group it links";if(e.name===B)return e.kind!=="open"?"<a> is only written open, around the title and body of the group it links":t.name!==ge||!t.stamped||t.children!==0?`<a> is only written as the first child of a <g ${Me}>`:n>0?"an <a> inside another <a>":void 0},Ir=e=>wr.some(t=>e.attributes.has(t)),Di=(e,t)=>e.size===t.size&&Array.from(t).every(([n,r])=>e.get(n)===r),vr=e=>e.findLast(t=>t.stamped),Cr="a line's group draws no box: it holds no <rect>, <text>, <polygon> or <line>",Nr="a line's group holds no stamped group of its own",et="desc",Oi=e=>e!==void 0&&(e.hitArea||e.described),Fi={d:()=>!0,fill:e=>e===he,stroke:e=>e===$,"stroke-opacity":e=>e==="0","stroke-width":e=>e===Rt(1),"stroke-dasharray":e=>e==="6 4","marker-start":()=>!0,"marker-end":()=>!0},Ar=e=>e.name===yr&&e.attributes.get("fill")===he&&e.attributes.get("stroke")===$&&Array.from(e.attributes).every(([t,n])=>Fi[t]?.(n)??!1),Mr=e=>{let t=e.at(-1),n=t?.name===B?e.at(-2):t;return n?.name===ge&&n.stamped?n:void 0},Hi=(e,t)=>{if(!Ir(e))return;let n=t.at(-1),r=n.name===B?t.at(-2):n;if(r?.name!==ge||!r.stamped)return`a hit area (${wr.join(", ")}) is only written in a <g ${Me}>`;if(r.hitArea)return"a stamped group holds one hit area";if(r===n&&r.linked)return"in a linked group, the hit area is inside the link";if(r.drawsBox)return Cr;if(r.nestsStamp)return Nr;let o=n.previous;if(o===void 0||o!==n.firstPath||!Ar(o))return"a hit area follows the line's route, the first path of its group";let s=new Map([["d",o.attributes.get("d")??""],["fill",he],["stroke",$],["stroke-width",Rt(10)],["visibility",Xe],["pointer-events",Je]]);return Di(e.attributes,s)?void 0:`a hit area is the route before it as <path ${Array.from(s.keys()).join(" ")}>, with the serializer's values`},Ui=(e,t)=>{let n=vr(t);if(Oi(n))return kr.has(e.name)?Cr:e.name===ge&&e.attributes.has(Me)?Nr:void 0},Bi=(e,t)=>{if(e.name!==et)return;let n=t.at(-1);return Mr(t)===void 0||n.children!==1||n.previous?.name!==gr?`a <${et}> is only written right after the <title> that opens a stamped group`:void 0},Xt=(e,t={})=>{if(t.idPrefix!==void 0&&!Ht(t.idPrefix))return`the id prefix "${C(t.idPrefix)}" is not one the serializer accepts`;let n=e.split(`
21
- `);if(n.at(-1)===""&&n.pop(),n.length===0)return"the file is empty";let r=[],o=new Map,s=[],i=0,a=!1;for(let[f,m]of n.entries()){let u=f+1,h=x=>`line ${u}: ${x}`;if(m==="")return h("a blank line");let p=mi.exec(m);if(p!==null)return h(`the control character ${Yt(p[0])} is not allowed`);if(Ne(m)!==m)return h("a code point XML cannot carry is not allowed");if(a)return h("content after the root element");let y=m.replace(hi,""),E=Pi(y,t);if("problem"in E)return h(E.problem);let{line:g}=E,w=g.kind==="close"?r.pop():void 0;if(g.kind==="close"&&w?.name!==g.name)return h(w===void 0?`</${C(g.name)}> closes nothing`:`</${C(g.name)}> closes <${w.name}>, opened on line ${w.lineNumber}`);let b=m.length-y.length,N=r.length*si.length;if(b!==N)return h(`indented ${b} spaces where the nesting calls for ${N}`);if(g.kind==="close"){if(w.name===B){if(w.children===0)return h("<a> has to open with the <title> of the group it links");i-=1}if(w.described&&!w.drawsRoute)return h(`a <${et}> belongs to a line's route group, and this group draws no route`);a=r.length===0;continue}let I=r.at(-1),M=_i(g,r.length)??(I&&(Li(g,I,i)??Hi(g,r)??Bi(g,r)??Ui(g,r)));if(M!==void 0)return h(M);let L=g.attributes.get("id");if(L!==void 0){if(o.has(L))return h(`the id ${C(L)} is declared twice`);o.set(L,g.name)}for(let[x,Z]of g.attributes){let Q=di[x];Q!==void 0&&s.push({attribute:x,id:$r.exec(Z)[1],kind:Q,lineNumber:u})}I!==void 0&&(I.children+=1,I.previous=g,I.firstPath??=g.name===yr?g:void 0,I.linked||=I.stamped&&g.name===B),Ir(g)&&((I.name===B?r.at(-2):I).hitArea=!0);let F=Mr(r);F!==void 0&&(F.described||=g.name===et,F.drawsRoute||=I.firstPath===g&&Ar(g));let H=vr(r);H!==void 0&&kr.has(g.name)&&(H.drawsBox=!0),H!==void 0&&g.name===ge&&g.attributes.has(Me)&&(H.nestsStamp=!0),g.kind==="open"&&(r.push({name:g.name,lineNumber:u,stamped:g.name===ge&&g.attributes.has(Me),children:0,linked:!1,hitArea:!1,drawsBox:!1,described:!1,drawsRoute:!1,nestsStamp:!1}),i+=g.name===B?1:0)}let d=r.at(-1);if(d!==void 0)return`<${d.name}> opened on line ${d.lineNumber} is never closed`;let c=s.find(({id:f,kind:m})=>o.get(f)!==m);return c===void 0?void 0:`line ${c.lineNumber}: ${c.attribute}: url(#${C(c.id)}) names no <${c.kind}> the file declares`};var Jt=" ",_r=/^( *)<g data-md-element="([^"]*)">$/,ji=/^<title>[^<]*<\/title>$/,qt=".svg",Rr=".png",Pr=[137,80,78,71,13,10,26,10],Wi=e=>{let t=new Map,n=(r,o)=>{o&&!t.has(r)&&t.set(r,`#${o}`)};for(let r of e.fragments??[]){n(r.elementId,r.realization?.anchor);for(let o of r.anchors??[])n(o.elementId,o.anchor)}return t},zi=e=>{let t=new Map;for(let[n,r]of e){let o=Pt(n);!t.has(o)&&Ze(r)&&t.set(o,r)}return t},Gi=(e,t,n)=>{let r=n+Jt,o=`${n}</g>`,s=`${r}<g data-md-element="`;for(let i=t+1;i<e.length;i+=1){let a=e[i];if(a===o||a.startsWith(s))return i;if(!a.startsWith(r))return}},Ki=(e,t)=>{if(t.size===0)return e;let n=e.split(`
22
- `),r=[],o=0;for(;o<n.length;){let s=n[o];r.push(s),o+=1;let i=_r.exec(s),a=i?t.get(i[2]):void 0;if(!i||a===void 0)continue;let d=i[1],c=d+Jt,f=n[o];if(f===void 0||!f.startsWith(c)||!ji.test(f.slice(c.length)))continue;let m=Gi(n,o-1,d);if(m!==void 0){for(r.push(`${c}<a href="${Pt(a)}">`);o<m;o+=1)r.push(Jt+n[o]);r.push(`${c}</a>`)}}return r.join(`
23
- `)},Vi=e=>e.split(`
24
- `).some(t=>_r.test(t)),Lr=(e,t)=>e.toLowerCase().endsWith(qt)&&!Vi(new TextDecoder().decode(t));var W=class extends Error{path;problem;constructor(t,n){super(`Refused the diagram file ${t}: ${n}`),this.name="RefusedMediaError",this.path=t,this.problem=n}},Yi=e=>e.length>=Pr.length&&Pr.every((t,n)=>e[n]===t),Xi=(e,t)=>{let n=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return typeof n=="string"?{idPrefix:dr(n)}:{}},Dr=({manifest:e,mediaIndex:t})=>{let n=zi(Wi(e)),r=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),o=new TextEncoder,s=(i,a)=>{let d;try{d=r.decode(a)}catch{throw new W(i,"the bytes are not UTF-8 text")}let c=Xi(t,i),f=Xt(d,c);if(f!==void 0)throw new W(i,f);let m=Ki(d,n);if(m===d)return a;let u=Xt(m,c);if(u!==void 0)throw new W(i,`once linked, ${u}`);return o.encode(m)};return(i,a)=>{let d=i.toLowerCase();if(d.endsWith(qt))return s(i,a);if(!d.endsWith(Rr))throw new W(i,`a diagram file is an ${qt} or a ${Rr}, and this is neither`);if(!Yi(a))throw new W(i,"the bytes are not a PNG image");return a}};var oe=e=>{let t=e.payloads??{},n=[];for(let r of e.manifest.fragments??[]){let o=r.realization?.path;if(!o)continue;let s=t[r.address];s!==void 0&&n.push({path:o,content:s})}return n},Or="image/svg+xml, image/png",tt=e=>{let t=[];for(let n of e.fragments??[])for(let r of n.realization?.media??[])t.push(r);return[...new Set(t)]},ye=(e,t={})=>{let n=new Set,r=new Set;for(let o of e)Object.hasOwn(t,o)?n.add(t[o]):r.add(o);return n.size+r.size};var Fr=(e,t)=>{let n=Dr(e),r=Hr(e),o=new Map,s=[],i=[];for(let{path:m,bytes:u}of t){if(u===void 0){s.push(m);continue}try{o.set(m,n(m,u))}catch(h){if(!(h instanceof W))throw h;s.push(m),i.push({path:m,problem:h.problem})}}let a=new Set;for(let[m,u]of o){let h=r(m);h!==void 0&&Lr(m,u)&&a.add(h)}let d=m=>{let u=r(m);return u!==void 0&&a.has(u)},c=new Map([...o].filter(([m])=>!d(m))),f=s.filter(m=>!d(m));return{mediaBytesByPath:c,missingPaths:f,refusals:i.filter(({path:m})=>!d(m)),emptyDiagramIds:a,emptyDiagramPaths:t.map(({path:m})=>m).filter(d),...Ji(e,f,c)}},Hr=e=>{let t=e.mediaIndex??{};return n=>Object.hasOwn(t,n)?t[n]:void 0},Ji=(e,t,n)=>{let r=e.mediaIndex??{},o=Hr(e),s=new Set([...n.keys()].map(o)),i=a=>{let d=o(a);return d!==void 0&&s.has(d)};return{missingDiagrams:ye(t.filter(a=>!i(a)),r),partialDiagrams:ye(t.filter(i),r)}};import{existsSync as Zt,lstatSync as Br,realpathSync as qi,statSync as Zi}from"node:fs";import{homedir as Qi}from"node:os";import{basename as ea,dirname as ta,isAbsolute as jr,join as Wr,relative as na,resolve as we,sep as ra}from"node:path";var nt=(e,t,n)=>{if(jr(n))throw new l(`Refusing an absolute path from the bundle manifest: ${n}`);let r=we(e,t),o=we(e,n);if(o===r||!Qt(r,o))throw new l(`Refusing a bundle path that escapes the content root: ${n}`);return o},Qt=(e,t)=>{let n=na(e,t);return n===""||!jr(n)&&n!==".."&&!n.startsWith(`..${ra}`)},Re=(e,t,{ignoreCase:n=!1}={})=>{let r=Ur(e),o=Ur(t);return n?Qt(r.toLowerCase(),o.toLowerCase()):Qt(r,o)},se=e=>{try{return Br(e)}catch{return}},ie=e=>{try{return Zi(e)}catch{return}},Ur=e=>{let t=[],n=e;for(;!Zt(n);){let o=ta(n);if(o===n)return e;t.unshift(ea(n)),n=o}let r=qi(n);return t.length>0?Wr(r,...t):r},z=e=>{if(se(e)?.isSymbolicLink())throw new l(`Refusing to write through an existing symlink at a managed path: ${e}`)},rt=(e,t)=>{if(!Re(e,t))throw new l(`Refusing a path that escapes the content root through a symlink: ${t}`)},en=(e,t)=>{let n=we(e,t);if(n===we(e))throw new l(`The content root resolves to the repository root (${n}); refusing to sync it.`);if(n===we(Qi()))throw new l("The content root resolves to your home directory; refusing to sync it.");if(Zt(n)){if(Br(n).isSymbolicLink())throw new l(`The content root ${n} is a symlink; refusing to sync it.`);if(Zt(Wr(n,".git")))throw new l(`The content root ${n} contains a .git directory (it looks like a repo root); refusing.`)}if(!Re(we(e),n))throw new l(`The content root ${n} resolves outside the repository via a symlinked ancestor; refusing.`);return n};var zr={respec:"data/model"},tn=e=>Object.hasOwn(zr,e)?zr[e]:void 0,ot=e=>{let t=tn(e);if(!t)throw new l(`The CLI does not know the content root for stack '${e}'.`);return t};var oa=1500,sa=6e5,ia=e=>new Promise(t=>setTimeout(t,e)),aa=e=>e==="COMPLETED"||e==="COMPLETED_WITH_ERRORS"||e==="FAILED",Gr=async(e,t,n)=>{let r=await e.postForJson(`/models/${t}/content-bundle/diagrams`,{template:n.template,version:n.version});if(!r.commit)throw new l("The diagram render did not return a resolved commit; cannot pin the pull.");return r},Kr=async(e,t,n,r,o,s={})=>{let i=s.sleep??ia,a=s.now??Date.now,d=a()+sa;for(r.update(0,o);;){let c=await e.getJson(`/models/${t}/export-jobs/${n}`);if(c.progress&&r.update(c.progress.completed,c.progress.total,c.progress.currentItem),aa(c.status))return r.done(),c;if(a()>=d)throw new l("Timed out waiting for the diagram render to finish.");await i(oa)}},Vr=(e,t,n,r)=>e.getBytes(`/models/${t}/content-bundle/media`,{path:n,template:r.template,commit:r.commit});var Yr=e=>{let t=new Map;for(let n of e.fragments??[])n.realization?.path&&t.set(n.elementId,n.realization.path);return t},Xr=(e,t)=>{let n=Yr(e),r=[];for(let[o,s]of Yr(t)){let i=n.get(o);i&&i!==s&&r.push({elementId:o,oldPath:i,newPath:s})}return r};import{existsSync as da,mkdirSync as ca,readFileSync as la,writeFileSync as ma}from"node:fs";import{join as Jr}from"node:path";var qr=(e,t)=>Jr(e,pe,`${t}.manifest.json`),st=(e,t)=>{let n=qr(e,t);if(!da(n))return;let r;try{r=JSON.parse(la(n,"utf8"))}catch{return}return fa(r)?r:void 0},fa=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let{fragments:t}=e;return t===void 0?!0:Array.isArray(t)&&t.every(n=>n!==null&&typeof n=="object")},Zr=(e,t,n)=>{ca(Jr(e,pe),{recursive:!0}),ma(qr(e,t),At(n))},Qr=e=>{let t=[];for(let n of e.fragments??[]){n.realization?.path&&t.push(n.realization.path);for(let r of n.realization?.media??[])t.push(r)}return t};import{existsSync as eo,mkdirSync as to,readdirSync as pa,rmSync as ua,writeFileSync as no}from"node:fs";import{dirname as ro,join as Pe,relative as ha,sep as ga}from"node:path";var oo=(e,t)=>{let n=Pe(e,t);if(!eo(n))return[];let r=[],o=s=>{for(let i of pa(s,{withFileTypes:!0})){let a=Pe(s,i.name);i.isDirectory()?o(a):i.isFile()&&r.push(ha(e,a).split(ga).join("/"))}};return o(n),r},nn=(e,t,n)=>{let r=Pe(e,t);for(let o of n){let s=nt(e,t,o.path);z(s),rt(r,s),to(ro(s),{recursive:!0}),no(s,o.content)}},ya=(e,t,n,r)=>{let o=Pe(e,t),s=nt(e,t,n);z(s),rt(o,s),to(ro(s),{recursive:!0}),no(s,r)},so=(e,t,n,{mediaBytesByPath:r,emptyDiagramIds:o})=>{let s=[];for(let[d,c]of r)try{ya(e,t,d,c)}catch(f){s.push({path:d,error:f})}if(o.size===0)return s;let i=new Map(oe(n).map(d=>[d.path,d.content])),a=oe(Nt(n,o)).filter(d=>i.get(d.path)!==d.content);return nn(e,t,a),s},rn=(e,t,n)=>{let r=nt(e,t,n);return rt(Pe(e,t),r),eo(r)?(ua(r),!0):!1},io=(e,t,n)=>{for(let r of n)rn(e,t,r)};var wa=100,co=e=>{if(e.newTextPaths.length===0&&!e.allowEmpty)throw new l("The content fetch returned no fragments (usually the wrong model or format, or a server error). Nothing was written or deleted. Re-run with --allow-empty only if the model is genuinely empty.");let t=ao([...e.newTextPaths,...e.newMediaPaths]).sort(),n=new Set(t),r=new Set(e.existingFiles),o=t.filter(f=>r.has(f)),s=e.priorManifestPaths!==void 0?"manifest-tracked":"full-sync",i=e.priorManifestPaths??e.existingFiles,a=ao(i).filter(f=>!n.has(f)).sort(),d=a.length>0&&!e.adopted,c=a.length>0&&(a.length>t.length||a.length>wa);return{writes:t,overwrites:o,orphanCandidates:a,mode:s,adoptionNeeded:d,outsized:c}},on=(e,t)=>{if(e.orphanCandidates.length===0)return{deletes:[],warnings:[]};if(e.adoptionNeeded&&!t.adopt)return{deletes:[],warnings:[`${e.orphanCandidates.length} file(s) under the content root are not tracked by the CLI and were left in place. Pass --adopt to let the CLI manage (and prune) this directory.`]};if(e.outsized&&!t.yes)throw new l(`This pull would remove ${e.orphanCandidates.length} file(s), more than the ${e.writes.length} it writes. That often signals a wrong model or format. Nothing was changed. Re-run with --yes if intended.`);return{deletes:e.orphanCandidates,warnings:[]}},ao=e=>[...new Set(e)];var lo=(e,t)=>{let n=Te(t);switch(n.mode){case"error":throw new l(n.message);case"secret":case"federated":return Ve(e,n);case"interactive":return new Ke(e)}};var ka=6e4,mo={unauthorized:"Run 'modeldesk auth login' and try again.",forbidden:"Your account may lack access to this model."},Ea={unauthorized:je.unauthorized,forbidden:je.forbidden,notFound:je.notFound},J=class extends l{status;constructor(t,n){super(t),this.name="ApiError",this.status=n}},it=(e,t)=>new sn(e.apiBase,lo(e,t),Y(t)?Ea:mo),sn=class{constructor(t,n,r=mo){this.apiBase=t;this.tokens=n;this.hints=r}apiBase;tokens;hints;async getJson(t,n){return await(await this.request(t,{method:"GET"},n)).json()}async postForJson(t,n){return await(await this.request(t,{method:"POST"},n)).json()}async getBytes(t,n){let r=await this.request(t,{method:"GET",headers:{Accept:Or}},n);return new Uint8Array(await r.arrayBuffer())}async request(t,n,r){let o=await this.tokens.getAccessToken(),s=$a(this.apiBase,t,r),i;try{i=await fetch(s,{...n,headers:{Authorization:`Bearer ${o}`,Accept:"application/json",...n.headers??{}},signal:AbortSignal.timeout(ka)})}catch(a){throw new l(`Could not reach ${this.apiBase} (${a.message}). Check the host and that the ModelDesk server is reachable.`)}if(!i.ok)throw await xa(i,t,this.hints);return i}},$a=(e,t,n)=>{let r=new URL(t,e);if(n)for(let[o,s]of Object.entries(n))s!==void 0&&r.searchParams.set(o,s);return r.toString()},xa=async(e,t,n)=>{let r=`${e.status} ${e.statusText}`.trim();try{if((e.headers.get("content-type")??"").includes("json")){let s=await e.json(),i=s.detail??s.title;i&&(r=`${e.status} ${i}`)}}catch{}return e.status===401?new J(`Authentication failed (${r}). ${n.unauthorized}`,e.status):e.status===403?new J(`Not authorized (${r}). ${n.forbidden}`,e.status):e.status===404&&n.notFound?new J(`Not found (${r}). ${n.notFound}`,e.status):new J(`Request to ${t} failed: ${r}`,e.status)};import{readdirSync as Sa}from"node:fs";import{join as _e,posix as Le}from"node:path";var po=e=>{let t=O(e),n=new Map;for(let r of e.fragments??[]){let o=n.get(r.elementId),s=r.realization?.path,i=s!==void 0&&(s===fo||s.endsWith(`/${fo}`));n.set(r.elementId,{elementId:r.elementId,title:t.get(r.elementId)?.title,kind:t.get(r.elementId)?.kind,path:o?.path??s,anchor:t.get(r.elementId)?.anchor,container:(o?.container??!1)||i})}return[...n.values()]},fo="index.md",an=e=>{let t=O(e);return(e.fragments??[]).flatMap(n=>(n.anchors??[]).map(r=>({elementId:r.elementId,kind:r.kind,slug:r.address.split("/").at(-1)??"",owner:t.get(n.elementId)?.title})))},uo=(e,t)=>{let n=ne(t);return n===""?[]:e.filter(r=>r.slug===n)},at=e=>e.replace(/\s+/g," ").trim().toLowerCase(),dn=(e,t)=>{let n=at(t);return e.filter(r=>r.title!==void 0&&at(r.title)===n)},ba=5,ho=(e,t)=>{let n=at(t),r=n.length>=4?2:1,s=e.flatMap(i=>i.title===void 0?[]:[i.title]).filter(i=>{let a=at(i);return n.length>=3&&a.includes(n)||cn(a,n)<=r});return[...new Set(s)].slice(0,ba)},cn=(e,t)=>{let n=Array.from({length:t.length+1},(r,o)=>o);for(let r=1;r<=e.length;r+=1){let o=[r];for(let s=1;s<=t.length;s+=1)o[s]=Math.min(n[s]+1,o[s-1]+1,n[s-1]+(e[r-1]===t[s-1]?0:1));n=o}return n[t.length]};var dt=".after.md",ae=".md",yo=e=>e.toLowerCase().endsWith(dt),wo=e=>yo(e)?"after":"intro",ct=(e,t)=>{let n=me(e);if(n!==void 0)return`the notes folder ${JSON.stringify(e)} ${n}; give a folder relative to the repository root`;if(T(e)===".")return"the notes folder is the repository root, so every Markdown file in the repository would be read as a note; give a folder of its own, such as md-notes/";if(te(e.toLowerCase(),t.toLowerCase())||te(t.toLowerCase(),e.toLowerCase()))return`the notes folder ${e} overlaps the content root ${t}/, which every pull replaces; keep notes outside it`},lt=(e,t,n,r)=>{let o=`${T(t)}/`,s=T(n);if(!s.startsWith(o)||!s.endsWith(ae))return;let i=s.slice(o.length,-ae.length);return Le.join(T(e),`${i}${r==="after"?dt:ae}`)},ln=(e,t)=>se(_e(e,T(t)))?.isSymbolicLink()?`the notes folder ${T(t)} is a symlink, which the pull does not follow; make it a folder of its own, or set "notesDir" in .modeldesk/config.json to the folder it points to`:void 0,ko=(e,t)=>{let n=T(t),r=ln(e,t);if(r!==void 0)throw new l(`${r[0].toUpperCase()}${r.slice(1)}.`);if(se(_e(e,n))?.isDirectory()!==!0)return[];let o=[],s=a=>{try{return Sa(_e(e,a),{withFileTypes:!0})}catch(d){throw new l(`Could not read the notes folder ${a}: ${d.message}`)}},i=a=>{for(let d of s(a)){if(d.name.startsWith("."))continue;let c=Le.join(a,d.name);d.isDirectory()?i(c):d.name.toLowerCase().endsWith(ae)&&!Ta(e,c,d)&&o.push(c)}};return i(n),o.sort()},Ta=(e,t,n)=>n.isSymbolicLink()?ie(_e(e,t))?.isDirectory()===!0:!1,Ia=5,Eo=({repoRoot:e,files:t,notesDir:n,contentRoot:r,manifest:o,entries:s})=>{let i=[...s.values()].flatMap(h=>A.flatMap(p=>h[p]===void 0?[]:[T(h[p])])),a=new Set(i),d=new Set(i.flatMap(h=>go(e,h)??[])),c=h=>{if(a.has(T(h)))return!0;let p=go(e,h);return p!==void 0&&d.has(p)},f=new Map;for(let h of o.fragments??[]){let p=h.realization?.path;p!==void 0&&!f.has(T(p))&&f.set(T(p),{elementId:h.elementId,title:h.title||void 0})}let m=[],u=new Map;for(let h of t.filter(p=>!c(p))){let p=wo(h),y=va(n,r,h),E=y===void 0?void 0:f.get(y);if(E===void 0){m.push(Ca(h,y,n,r,[...f.keys()]));continue}let g=s.get(E.elementId)?.[p],w=E.title??E.elementId;if(g!==void 0){m.push(`the note ${h} would be the ${p} note of ${w}, which notes.json already gives as ${g}; keep one of the two files.`);continue}let b=`${p} ${E.elementId}`,N=u.get(b);if(N!==void 0){m.push(`the notes ${N.file} and ${h} would both be the ${p} note of ${w}, which appears at more than one place in the document; keep one of the two files.`);continue}u.set(b,{file:h,elementId:E.elementId,slot:p,title:E.title})}return{adoptions:[...u.values()],errors:m}},go=(e,t)=>{let n=ie(_e(e,t));return n?.isFile()?`${n.dev}:${n.ino}`:void 0},va=(e,t,n)=>{let r=`${T(e)}/`,o=T(n);if(!o.startsWith(r))return;let s=o.slice(r.length),i=yo(s)?s.slice(0,-dt.length):s.toLowerCase().endsWith(ae)?s.slice(0,-ae.length):void 0;return i===void 0?void 0:Le.join(T(t),`${i}${ae}`)},Ca=(e,t,n,r,o)=>{let s=`A note's path is its element's file under ${T(r)}/ with ${T(n)}/ in its place, ending in ${dt} for the note after the element's content.`;if(t===void 0)return`the note ${e} matches no element: its name does not end in .md. ${s}`;let i=Le.basename(t),a=o.map(c=>({path:c,distance:cn(c,t)})).filter(({path:c,distance:f})=>Le.basename(c)===i||f<=2).sort((c,f)=>c.distance-f.distance||c.path.localeCompare(f.path)).slice(0,Ia).map(({path:c})=>lt(n,r,c,wo(e))).filter(c=>c!==void 0),d=a.length===0?"":` Did you mean ${a.join(", ")}?`;return`the note ${e} matches no element: this bundle has no ${t}.${d} ${s}`},mn=(e,t)=>{let n=new Map(e);for(let{file:r,elementId:o,slot:s,title:i}of t){let a=n.get(o);n.set(o,a===void 0?{...i===void 0?{}:{name:i},[s]:r}:{...a,[s]:r})}return n};import{join as fn}from"node:path";var pn=({repoRoot:e,contentRoot:t,entries:n})=>[...n].flatMap(([r,o])=>A.flatMap(s=>{let i=o[s];return i===void 0?[]:Na(e,t,i).map(a=>`${ke(r,o.name)} ${s}: ${a}.`)})),$o=({manifest:e,slots:t,entries:n,notesDir:r})=>{let o=Ma(e,t),s=[],i=[],d=[...n].some(([c,f])=>o.has(c)&&A.some(m=>f[m]!==void 0))&&t.size===0?`The server rendered stack ${e.stack} ${e.stackVersion}, which carries no note slots, so the notes cannot be placed. Either the server is older than note support, or this template has no slots: notes work with the MIM templates. Pull without notes by moving .modeldesk/notes.json and the notes folder ${r} aside, or pull again once the server is updated.`:void 0;for(let[c,f]of n){let m=o.get(c),u=ke(c,m?.title??f.name);if(m===void 0){i.push(`${u} is not in this bundle; its entry in notes.json is kept.`);continue}if(d===void 0)for(let h of A)f[h]!==void 0&&s.push(...Aa(m,h).map(p=>`${u} ${h}: ${p}.`))}return{errors:s,warnings:i,slotless:d}},un=e=>typeof e=="string"?e:e.file,hn=(e,t,n)=>{let r=me(n);if(r!==void 0)return[`the note path ${JSON.stringify(n)} ${r}; note paths are relative to the repository root`];if(te(n.toLowerCase(),t.toLowerCase()))return[`the note ${n} lies in the content root ${t}/, which every pull replaces, so the pull would remove it; keep notes outside it`];let o=fn(e,n);return Re(fn(e,t),o,{ignoreCase:!0})?[`the note ${n} lies in the content root ${t}/ through a symlink, and every pull replaces that folder, so the pull would remove it; keep notes outside it`]:Re(e,o)?[]:[`the note ${n} lies outside the repository through a symlink; keep notes inside it`]},Na=(e,t,n)=>{let r=hn(e,t,n);if(r.length>0)return r;let o=ie(fn(e,n));return o===void 0?[`the note ${n} does not exist`]:o.isFile()?[]:[`the note ${n} is not a file`]},Aa=(e,t)=>{let n=e.slots.get(t);if(n===void 0){let r=[...e.slots.keys()],o=e.kind===void 0?"the element":`this ${e.kind}`;return[r.length===0?`${o} carries no slots`:`${o} carries no ${t} slot, only ${r.join(" and ")}`]}return n.headed&&e.anchor===void 0?["the bundle's manifest gives the element no anchor to build the heading's id from"]:[]},Ma=(e,t)=>{let n=new Map;for(let[r,o]of O(e))n.set(r,{...o,slots:new Map});for(let r of(e.fragments??[]).flatMap(o=>o.anchors??[]))n.has(r.elementId)||n.set(r.elementId,{kind:r.kind,slots:new Map});for(let r of[...t.values()].flat()){let o=n.get(r.elementId)??{slots:new Map};n.set(r.elementId,o);let s=o.slots.get(r.name)?.headed??!1;o.slots.set(r.name,{headed:s||r.heading!==void 0})}return n},ke=(e,t)=>t===void 0?e:`${t} (${e})`;import{existsSync as Ra,readFileSync as xo}from"node:fs";import{join as Pa}from"node:path";var _a="notes.json",La=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Da=["name",...A],Oa=e=>Pa(e,pe,_a),mt=e=>{let t=Oa(e);if(!Ra(t))return{path:t,entries:new Map};let n;try{n=xo(t,"utf8")}catch(s){throw new l(`Could not read ${t}: ${s.message}`)}let r;try{r=JSON.parse(n)}catch(s){throw new l(`${t} is not valid JSON: ${s.message}`)}if(!gn(r))throw new l(`${t} must contain a JSON object with a "notes" object.`);for(let s of Object.keys(r))if(s!=="notes")throw new l(`${t}: unknown key "${s}"; the file holds only "notes".`);if(!gn(r.notes))throw new l(`${t}: "notes" must be an object of entries keyed by element id.`);let o=new Map;for(let[s,i]of Object.entries(r.notes))o.set(s,Ua(t,s,i));return Ha(t,n,o),{path:t,entries:o,raw:n}},Fa=/"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"\s*:/g,Ha=(e,t,n)=>{let r=new Map;for(let[,o]of t.matchAll(Fa))r.set(o,(r.get(o)??0)+1);for(let o of n.keys())if((r.get(o)??0)>1)throw new l(`${e}: notes key "${o}" appears more than once, and JSON keeps only the last; merge the entries.`)},Ua=(e,t,n)=>{if(!La.test(t))throw new l(`${e}: notes key "${t}" is not an element id. Entries are keyed by the element's id, a lowercase UUID as the bundle's manifest gives it.`);let r=`notes.${t}`;if(!gn(n))throw new l(`${e}: ${r} must be an object.`);for(let o of Object.keys(n))if(!Da.includes(o))throw new l(`${e}: ${r} has an unknown key "${o}"; an entry takes "name", "intro" and "after".`);if(n.name!==void 0&&typeof n.name!="string")throw new l(`${e}: ${r}.name must be a string.`);for(let o of A)if(n[o]!==void 0&&typeof n[o]!="string")throw new l(`${e}: ${r}.${o} must be a note path. A note that comes under a heading names it on its own first line, <!-- heading: \u2026 -->.`);return n},gn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),bo=e=>{try{return xo(e,"utf8")}catch{return}};import{readFileSync as Ya}from"node:fs";import{join as vo,posix as Xa}from"node:path";var Ba=/^ {0,3}(`{3,}|~{3,})/,yn=/^(?: {4}|\t)/,ja=/^ {0,3}(?:[-+*]|\d{1,9}[.)])(?:[ \t]|$)/,To=e=>{let t=[],n,r=!1,o=!0,s=!1;for(let i of e.split(/\r?\n/)){let a=i.trim()==="",d=Ba.exec(i)?.[1];if(n!==void 0){d!==void 0&&d[0]===n[0]&&d.length>=n.length&&i.trim()===d&&(n=void 0);continue}if(!(r&&(a||yn.test(i)))){if(r=!1,d!==void 0){n=d,o=!1;continue}if(yn.test(i)&&o&&!s){r=!0;continue}a||(s=ja.test(i)||s&&yn.test(i)),o=a,t.push(i)}}return t},Wa=/(?<!`)(`+)(?!`)(.*?[^`])\1(?!`)/g,za=/!\[([^\]]*)\]\(\s*(?:<([^>]*)>|([^\s)]+))(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*\)/g,Ga=/<img\b([^>]*)>/gi,Ka=/([^\s=/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g,Io=e=>{let t=To(e).map(r=>r.replace(Wa,o=>" ".repeat(o.length))).join(`
25
- `),n=[];for(let r of t.matchAll(za))n.push({src:r[2]??r[3],alt:r[1],syntax:"markdown"});for(let r of t.matchAll(Ga)){let o=new Map;for(let i of r[1].matchAll(Ka))o.set(i[1].toLowerCase(),i[2]??i[3]??i[4]??"");let s=o.get("src");s!==void 0&&n.push({src:s,alt:o.get("alt"),syntax:"html"})}return n},Va=/^ {0,3}#{1,6}(?=[ \t]|$)(.*)$/,So=/\s*\{#[^\s}]+\}$/,wn=e=>To(e).flatMap(t=>{let n=Va.exec(t);if(n===null)return[];let r=n[1].replace(/(?:^|[ \t]+)#+[ \t]*$/,"").trim(),o=So.test(r),s=o?r.replace(So,""):r;return s===""?[]:[{text:s,explicitId:o}]});var Co=e=>{let{repoRoot:t,manifest:n,slots:r,entries:o,notes:s,placed:i}=e,a=O(n),d=p=>a.get(p)?.title??o.get(p)?.name,c=new Map;for(let{name:p,elementId:y}of i.filled){let E=s.get(y)?.[p],g=`${p} ${y}`;E!==void 0&&!c.has(g)&&c.set(g,{elementId:y,title:d(y)??y,slot:p,target:E})}let f=[],m=[],u=new Map;for(let{target:p}of c.values())u.set(un(p),(u.get(un(p))??0)+1);for(let[p,y]of u)try{m.push({file:p,text:Ya(vo(t,p),"utf8"),slots:y})}catch(E){f.push(`could not read the note ${p}, so its images and headings were not checked: ${ce(E)}`)}for(let p of m)f.push(...Za(t,p.file,p.text,e.publishDirs));f.push(...Qa(m),...ed(n,i.dropped,d));let h=[...r.values()].reduce((p,y)=>p+y.length,0);return{warnings:f,substitutions:[...c.values()],removedSlots:h-i.filled.length}},Ja=/^(?:https?:|data:|\/\/)/i,qa=e=>{let t=e.replace(/[?#].*$/,""),n=t;try{n=decodeURIComponent(t)}catch{}return Xa.normalize(n.replace(/^\/+/,""))},Za=(e,t,n,r)=>Io(n).flatMap(({src:o,alt:s,syntax:i})=>{let a=[];if((s===void 0||i==="markdown"&&s.trim()==="")&&a.push(`the note ${t} has an image without alt text, ${o}; describe it for readers who cannot see it.`),Ja.test(o))return a;let d=qa(o);if(d==="."||d==="")return a;if(ie(vo(e,d))?.isFile()!==!0){let c=d===o?"":` (${d} in the repository)`;a.push(`the note ${t} links the image ${o}${c}, which does not exist; image paths resolve against the repository root.`)}return r!==void 0&&!r.some(c=>te(d,c))&&a.push(`the note ${t} links the image ${o}, which lies outside the publishDirs (${r.join(", ")||"none"}), so the published copy will miss it.`),a}),Qa=e=>{let t=new Map;for(let o of e)for(let s of wn(o.text)){if(s.explicitId)continue;let i=ne(s.text),a=t.get(i)??{text:s.text,files:[]};a.files.includes(o.file)||t.set(i,{...a,files:[...a.files,o.file]})}let n=[...t.values()].filter(({files:o})=>o.length>1).map(({text:o,files:s})=>`the notes ${s.join(" and ")} each have the heading "${o}" without an explicit {#id}. ReSpec numbers the later ids, so a link to one shifts when the notes change; give each heading its own {#id}.`),r=e.filter(o=>o.slots>1&&wn(o.text).length>0).map(o=>`the note ${o.file} fills ${o.slots} slots, so each of its headings appears ${o.slots} times and their ids repeat or get numbered; give each place its own note file.`);return[...n,...r]},ed=(e,t,n)=>{let r=new Map((e.fragments??[]).map(s=>[s.address,s.realization?.path])),o=new Map;for(let{name:s,elementId:i,address:a}of t){let d=`${s} ${i}`,c=o.get(d)??{slot:s,elementId:i,files:new Set};o.set(d,{...c,files:c.files.add(r.get(a)??a)})}return[...o.values()].map(({slot:s,elementId:i,files:a})=>`${ke(i,n(i))} appears more than once in ${[...a].join(", ")}; its ${s} note goes in at the first place only.`)};import{renameSync as td,rmSync as No,writeFileSync as nd}from"node:fs";var Ao=(e,t)=>{let n=O(t);return[...e].flatMap(([r,o])=>{let s=n.get(r)?.title;return s===void 0||s===o.name?[]:[{elementId:r,from:o.name,to:s}]})},Mo=(e,t)=>{let n=new Map(t.map(r=>[r.elementId,r.to]));return new Map([...e].map(([r,o])=>{let s=n.get(r);return s===void 0?[r,o]:[r,"name"in o?{...o,name:s}:{name:s,...o}]}))},Ee=e=>`${JSON.stringify({notes:Object.fromEntries(e)},null,2)}
26
- `,ft=(e,t)=>{z(e);let n=`${e}.tmp`;try{No(n,{force:!0}),nd(n,t,{flag:"wx"}),td(n,e)}catch(r){throw No(n,{force:!0}),r}};import{readFileSync as od}from"node:fs";import{join as sd}from"node:path";var rd=/^<!--\s*heading:(.*)-->$/i,Ro=e=>{let t=e.split(/\r?\n/).find(n=>n.trim()!=="");return t===void 0?void 0:rd.exec(t.trim())?.[1].trim()},pt=e=>`<!-- heading: ${e} -->`,De=e=>{if(e.trim()==="")return"is blank";if(/[\r\n]/.test(e))return"has a line break";let t=["-->","--!>"].find(n=>e.includes(n));return t===void 0?void 0:`has "${t}", which would end the heading line early`};var Po=({repoRoot:e,slots:t,entries:n})=>{let r=[...t.values()].flat(),o=new Set(r.flatMap(c=>c.heading===void 0?[]:[`${c.name} ${c.elementId}`])),s=new Set(r.map(c=>c.elementId)),i=new Map,a=[],d=[];for(let[c,f]of n){let m={};for(let u of A){let h=f[u];if(h===void 0)continue;if(!s.has(c)){m[u]=h;continue}let p=id(e,h),y=`${ke(c,f.name)} ${u}`;o.has(`${u} ${c}`)?p===void 0||p===""?a.push(`${y}: the note ${h} comes under a heading of its own, so its first line names it, such as ${pt("Afsluiting")}.`):De(p)!==void 0?a.push(`${y}: the heading line of the note ${h} ${De(p)}.`):m[u]={file:h,heading:p}:(p!==void 0&&d.push(`${y}: the note ${h} starts with a heading line, which only the closing note of a package or the model takes; the line is left as a comment.`),m[u]=h)}i.set(c,m)}return{notes:i,errors:a,warnings:d}},id=(e,t)=>{try{return Ro(od(sd(e,t),"utf8"))}catch{return}};var ad=(e,t)=>{let n=t>0?Math.min(1,e/t):0,r=Math.round(n*24);return`[${"#".repeat(r)}${"-".repeat(24-r)}]`},_o=(e,t=n=>{process.stderr.write(n)})=>{let n=-1;return{update(r,o,s){if(e){let i=s?` ${s}`:"";t(`\r${ad(r,o)} ${r}/${o}${i}\x1B[K`)}else if(r!==n){let i=s?` (${s})`:"";t(`Rendering diagrams: ${r}/${o}${i}
3
+ var _I=Object.create;var Zp=Object.defineProperty;var jI=Object.getOwnPropertyDescriptor;var FI=Object.getOwnPropertyNames;var qI=Object.getPrototypeOf,WI=Object.prototype.hasOwnProperty;var qo=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var M=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}};var BI=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of FI(t))!WI.call(e,s)&&s!==n&&Zp(e,s,{get:()=>t[s],enumerable:!(r=jI(t,s))||r.enumerable});return e};var Xd=(e,t,n)=>(n=e!=null?_I(qI(e)):{},BI(t||!e||!e.__esModule?Zp(n,"default",{value:e,enumerable:!0}):n,e));var G=M(Re=>{"use strict";var pm=Symbol.for("yaml.alias"),Lk=Symbol.for("yaml.document"),aa=Symbol.for("yaml.map"),Dk=Symbol.for("yaml.pair"),um=Symbol.for("yaml.scalar"),da=Symbol.for("yaml.seq"),Ot=Symbol.for("yaml.node.type"),uD=e=>!!e&&typeof e=="object"&&e[Ot]===pm,hD=e=>!!e&&typeof e=="object"&&e[Ot]===Lk,gD=e=>!!e&&typeof e=="object"&&e[Ot]===aa,yD=e=>!!e&&typeof e=="object"&&e[Ot]===Dk,_k=e=>!!e&&typeof e=="object"&&e[Ot]===um,wD=e=>!!e&&typeof e=="object"&&e[Ot]===da;function jk(e){if(e&&typeof e=="object")switch(e[Ot]){case aa:case da:return!0}return!1}function bD(e){if(e&&typeof e=="object")switch(e[Ot]){case pm:case aa:case um:case da:return!0}return!1}var kD=e=>(_k(e)||jk(e))&&!!e.anchor;Re.ALIAS=pm;Re.DOC=Lk;Re.MAP=aa;Re.NODE_TYPE=Ot;Re.PAIR=Dk;Re.SCALAR=um;Re.SEQ=da;Re.hasAnchor=kD;Re.isAlias=uD;Re.isCollection=jk;Re.isDocument=hD;Re.isMap=gD;Re.isNode=bD;Re.isPair=yD;Re.isScalar=_k;Re.isSeq=wD});var Hs=M(hm=>{"use strict";var ke=G(),De=Symbol("break visit"),Fk=Symbol("skip children"),ht=Symbol("remove node");function la(e,t){let n=qk(t);ke.isDocument(e)?jr(null,e.contents,n,Object.freeze([e]))===ht&&(e.contents=null):jr(null,e,n,Object.freeze([]))}la.BREAK=De;la.SKIP=Fk;la.REMOVE=ht;function jr(e,t,n,r){let s=Wk(e,t,n,r);if(ke.isNode(s)||ke.isPair(s))return Bk(e,r,s),jr(e,s,n,r);if(typeof s!="symbol"){if(ke.isCollection(t)){r=Object.freeze(r.concat(t));for(let o=0;o<t.items.length;++o){let i=jr(o,t.items[o],n,r);if(typeof i=="number")o=i-1;else{if(i===De)return De;i===ht&&(t.items.splice(o,1),o-=1)}}}else if(ke.isPair(t)){r=Object.freeze(r.concat(t));let o=jr("key",t.key,n,r);if(o===De)return De;o===ht&&(t.key=null);let i=jr("value",t.value,n,r);if(i===De)return De;i===ht&&(t.value=null)}}return s}async function ca(e,t){let n=qk(t);ke.isDocument(e)?await Fr(null,e.contents,n,Object.freeze([e]))===ht&&(e.contents=null):await Fr(null,e,n,Object.freeze([]))}ca.BREAK=De;ca.SKIP=Fk;ca.REMOVE=ht;async function Fr(e,t,n,r){let s=await Wk(e,t,n,r);if(ke.isNode(s)||ke.isPair(s))return Bk(e,r,s),Fr(e,s,n,r);if(typeof s!="symbol"){if(ke.isCollection(t)){r=Object.freeze(r.concat(t));for(let o=0;o<t.items.length;++o){let i=await Fr(o,t.items[o],n,r);if(typeof i=="number")o=i-1;else{if(i===De)return De;i===ht&&(t.items.splice(o,1),o-=1)}}}else if(ke.isPair(t)){r=Object.freeze(r.concat(t));let o=await Fr("key",t.key,n,r);if(o===De)return De;o===ht&&(t.key=null);let i=await Fr("value",t.value,n,r);if(i===De)return De;i===ht&&(t.value=null)}}return s}function qk(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Wk(e,t,n,r){if(typeof n=="function")return n(e,t,r);if(ke.isMap(t))return n.Map?.(e,t,r);if(ke.isSeq(t))return n.Seq?.(e,t,r);if(ke.isPair(t))return n.Pair?.(e,t,r);if(ke.isScalar(t))return n.Scalar?.(e,t,r);if(ke.isAlias(t))return n.Alias?.(e,t,r)}function Bk(e,t,n){let r=t[t.length-1];if(ke.isCollection(r))r.items[e]=n;else if(ke.isPair(r))e==="key"?r.key=n:r.value=n;else if(ke.isDocument(r))r.contents=n;else{let s=ke.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}hm.visit=la;hm.visitAsync=ca});var gm=M(Uk=>{"use strict";var Hk=G(),ED=Hs(),CD={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},vD=e=>e.replace(/[!,[\]{}]/g,t=>CD[t]),Us=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),s=r.shift();switch(s){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[o,i]=r;return this.tags[o]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[o]=r;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let i=/^\d+\.\d+$/.test(o);return n(6,`Unsupported YAML version ${o}`,i),!1}}default:return n(0,`Unknown directive ${s}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let i=t.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,s]=t.match(/^(.*!)([^!]*)$/s);s||n(`The ${t} tag has no suffix`);let o=this.tags[r];if(o)try{return o+decodeURIComponent(s)}catch(i){return n(String(i)),null}return r==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[n,r]of Object.entries(this.tags))if(t.startsWith(r))return n+vD(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),s;if(t&&r.length>0&&Hk.isNode(t.contents)){let o={};ED.visit(t.contents,(i,a)=>{Hk.isNode(a)&&a.tag&&(o[a.tag]=!0)}),s=Object.keys(o)}else s=[];for(let[o,i]of r)o==="!!"&&i==="tag:yaml.org,2002:"||(!t||s.some(a=>a.startsWith(i)))&&n.push(`%TAG ${o} ${i}`);return n.join(`
4
+ `)}};Us.defaultYaml={explicit:!1,version:"1.2"};Us.defaultTags={"!!":"tag:yaml.org,2002:"};Uk.Directives=Us});var ma=M(Vs=>{"use strict";var Vk=G(),RD=Hs();function SD(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function Gk(e){let t=new Set;return RD.visit(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function Kk(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function ID(e,t){let n=[],r=new Map,s=null;return{onAnchor:o=>{n.push(o),s??(s=Gk(e));let i=Kk(t,s);return s.add(i),i},setAnchors:()=>{for(let o of n){let i=r.get(o);if(typeof i=="object"&&i.anchor&&(Vk.isScalar(i.node)||Vk.isCollection(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=o,a}}},sourceObjects:r}}Vs.anchorIsValid=SD;Vs.anchorNames=Gk;Vs.createNodeAnchors=ID;Vs.findNewAnchor=Kk});var ym=M(Yk=>{"use strict";function Gs(e,t,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let s=0,o=r.length;s<o;++s){let i=r[s],a=Gs(e,r,String(s),i);a===void 0?delete r[s]:a!==i&&(r[s]=a)}else if(r instanceof Map)for(let s of Array.from(r.keys())){let o=r.get(s),i=Gs(e,r,s,o);i===void 0?r.delete(s):i!==o&&r.set(s,i)}else if(r instanceof Set)for(let s of Array.from(r)){let o=Gs(e,r,s,s);o===void 0?r.delete(s):o!==s&&(r.delete(s),r.add(o))}else for(let[s,o]of Object.entries(r)){let i=Gs(e,r,s,o);i===void 0?delete r[s]:i!==o&&(r[s]=i)}return e.call(t,n,r)}Yk.applyReviver=Gs});var nn=M(Jk=>{"use strict";var $D=G();function zk(e,t,n){if(Array.isArray(e))return e.map((r,s)=>zk(r,String(s),n));if(e&&typeof e.toJSON=="function"){if(!n||!$D.hasAnchor(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=o=>{r.res=o,delete n.onCreate};let s=e.toJSON(t,n);return n.onCreate&&n.onCreate(s),s}return typeof e=="bigint"&&!n?.keep?Number(e):e}Jk.toJS=zk});var fa=M(Qk=>{"use strict";var xD=ym(),Xk=G(),TD=nn(),wm=class{constructor(t){Object.defineProperty(this,Xk.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:r,onAnchor:s,reviver:o}={}){if(!Xk.isDocument(t))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=TD.toJS(this,"",i);if(typeof s=="function")for(let{count:d,res:l}of i.anchors.values())s(l,d);return typeof o=="function"?xD.applyReviver(o,{"":a},"",a):a}};Qk.NodeBase=wm});var Ks=M(Zk=>{"use strict";var AD=ma(),OD=Hs(),qr=G(),MD=fa(),ND=nn(),bm=class extends MD.NodeBase{constructor(t){super(qr.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],OD.visit(t,{Node:(o,i)=>{(qr.isAlias(i)||qr.hasAnchor(i))&&r.push(i)}}),n&&(n.aliasResolveCache=r));let s;for(let o of r){if(o===this)break;o.anchor===this.source&&(s=o)}if(s&&n){let{anchors:o,doc:i,maxAliasCount:a}=n,d=o.get(s);if(d||(ND.toJS(s,null,n),d=o.get(s)),d?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(d.count+=1,d.aliasCount===0&&(d.aliasCount=pa(i,s,o)),d.count*d.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}}return s}toJSON(t,n){if(!n)return{source:this.source};let r=this.resolve(n.doc,n);if(!r){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(s)}return n.anchors.get(r).res}toString(t,n,r){let s=`*${this.source}`;if(t){if(AD.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(t.implicitKey)return`${s} `}return s}};function pa(e,t,n){if(qr.isAlias(t)){let r=t.resolve(e),s=n&&r&&n.get(r);return s?s.count*s.aliasCount:0}else if(qr.isCollection(t)){let r=0;for(let s of t.items){let o=pa(e,s,n);o>r&&(r=o)}return r}else if(qr.isPair(t)){let r=pa(e,t.key,n),s=pa(e,t.value,n);return Math.max(r,s)}return 1}Zk.Alias=bm});var ge=M(km=>{"use strict";var PD=G(),LD=fa(),DD=nn(),_D=e=>!e||typeof e!="function"&&typeof e!="object",rn=class extends LD.NodeBase{constructor(t){super(PD.SCALAR),this.value=t}toJSON(t,n){return n?.keep?this.value:DD.toJS(this.value,t,n)}toString(){return String(this.value)}};rn.BLOCK_FOLDED="BLOCK_FOLDED";rn.BLOCK_LITERAL="BLOCK_LITERAL";rn.PLAIN="PLAIN";rn.QUOTE_DOUBLE="QUOTE_DOUBLE";rn.QUOTE_SINGLE="QUOTE_SINGLE";km.Scalar=rn;km.isScalarValue=_D});var Ys=M(tE=>{"use strict";var jD=Ks(),Wn=G(),eE=ge(),FD="tag:yaml.org,2002:";function qD(e,t,n){if(t){let r=n.filter(o=>o.tag===t),s=r.find(o=>!o.format)??r[0];if(!s)throw new Error(`Tag ${t} not found`);return s}return n.find(r=>r.identify?.(e)&&!r.format)}function WD(e,t,n){if(Wn.isDocument(e)&&(e=e.contents),Wn.isNode(e))return e;if(Wn.isPair(e)){let m=n.schema[Wn.MAP].createNode?.(n.schema,null,n);return m.items.push(e),m}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:s,onTagObj:o,schema:i,sourceObjects:a}=n,d;if(r&&e&&typeof e=="object"){if(d=a.get(e),d)return d.anchor??(d.anchor=s(e)),new jD.Alias(d.anchor);d={anchor:null,node:null},a.set(e,d)}t?.startsWith("!!")&&(t=FD+t.slice(2));let l=qD(e,t,i.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let m=new eE.Scalar(e);return d&&(d.node=m),m}l=e instanceof Map?i[Wn.MAP]:Symbol.iterator in Object(e)?i[Wn.SEQ]:i[Wn.MAP]}o&&(o(l),delete n.onTagObj);let c=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,e,n):new eE.Scalar(e);return t?c.tag=t:l.default||(c.tag=l.tag),d&&(d.node=c),c}tE.createNode=WD});var ha=M(ua=>{"use strict";var BD=Ys(),gt=G(),HD=fa();function Em(e,t,n){let r=n;for(let s=t.length-1;s>=0;--s){let o=t[s];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let i=[];i[o]=r,r=i}else r=new Map([[o,r]])}return BD.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var nE=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Cm=class extends HD.NodeBase{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(r=>gt.isNode(r)||gt.isPair(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(nE(t))this.add(n);else{let[r,...s]=t,o=this.get(r,!0);if(gt.isCollection(o))o.addIn(s,n);else if(o===void 0&&this.schema)this.set(r,Em(this.schema,s,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`)}}deleteIn(t){let[n,...r]=t;if(r.length===0)return this.delete(n);let s=this.get(n,!0);if(gt.isCollection(s))return s.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(t,n){let[r,...s]=t,o=this.get(r,!0);return s.length===0?!n&&gt.isScalar(o)?o.value:o:gt.isCollection(o)?o.getIn(s,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!gt.isPair(n))return!1;let r=n.value;return r==null||t&&gt.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[n,...r]=t;if(r.length===0)return this.has(n);let s=this.get(n,!0);return gt.isCollection(s)?s.hasIn(r):!1}setIn(t,n){let[r,...s]=t;if(s.length===0)this.set(r,n);else{let o=this.get(r,!0);if(gt.isCollection(o))o.setIn(s,n);else if(o===void 0&&this.schema)this.set(r,Em(this.schema,s,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`)}}};ua.Collection=Cm;ua.collectionFromPath=Em;ua.isEmptyPath=nE});var zs=M(ga=>{"use strict";var UD=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function vm(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var VD=(e,t,n)=>e.endsWith(`
5
+ `)?vm(n,t):n.includes(`
6
+ `)?`
7
+ `+vm(n,t):(e.endsWith(" ")?"":" ")+n;ga.indentComment=vm;ga.lineComment=VD;ga.stringifyComment=UD});var sE=M(Js=>{"use strict";var GD="flow",Rm="block",ya="quoted";function KD(e,t,n="flow",{indentAtStart:r,lineWidth:s=80,minContentWidth:o=20,onFold:i,onOverflow:a}={}){if(!s||s<0)return e;s<o&&(o=0);let d=Math.max(1+o,1+s-t.length);if(e.length<=d)return e;let l=[],c={},m=s-t.length;typeof r=="number"&&(r>s-Math.max(2,o)?l.push(0):m=s-r);let f,h,p=!1,g=-1,w=-1,k=-1;n===Rm&&(g=rE(e,g,t.length),g!==-1&&(m=g+d));for(let R;R=e[g+=1];){if(n===ya&&R==="\\"){switch(w=g,e[g+1]){case"x":g+=3;break;case"u":g+=5;break;case"U":g+=9;break;default:g+=1}k=g}if(R===`
8
+ `)n===Rm&&(g=rE(e,g,t.length)),m=g+t.length+d,f=void 0;else{if(R===" "&&h&&h!==" "&&h!==`
9
+ `&&h!==" "){let $=e[g+1];$&&$!==" "&&$!==`
10
+ `&&$!==" "&&(f=g)}if(g>=m)if(f)l.push(f),m=f+d,f=void 0;else if(n===ya){for(;h===" "||h===" ";)h=R,R=e[g+=1],p=!0;let $=g>k+1?g-2:w-1;if(c[$])return e;l.push($),c[$]=!0,m=$+d,f=void 0}else p=!0}h=R}if(p&&a&&a(),l.length===0)return e;i&&i();let C=e.slice(0,l[0]);for(let R=0;R<l.length;++R){let $=l[R],v=l[R+1]||e.length;$===0?C=`
11
+ ${t}${e.slice(0,v)}`:(n===ya&&c[$]&&(C+=`${e[$]}\\`),C+=`
12
+ ${t}${e.slice($+1,v)}`)}return C}function rE(e,t,n){let r=t,s=t+1,o=e[s];for(;o===" "||o===" ";)if(t<s+n)o=e[++t];else{do o=e[++t];while(o&&o!==`
13
+ `);r=t,s=t+1,o=e[s]}return r}Js.FOLD_BLOCK=Rm;Js.FOLD_FLOW=GD;Js.FOLD_QUOTED=ya;Js.foldFlowLines=KD});var Qs=M(oE=>{"use strict";var nt=ge(),sn=sE(),ba=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ka=e=>/^(%|---|\.\.\.)/m.test(e);function YD(e,t,n){if(!t||t<0)return!1;let r=t-n,s=e.length;if(s<=r)return!1;for(let o=0,i=0;o<s;++o)if(e[o]===`
14
+ `){if(o-i>r)return!0;if(i=o+1,s-i<=r)return!1}return!0}function Xs(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,s=t.options.doubleQuotedMinMultiLineLength,o=t.indent||(ka(e)?" ":""),i="",a=0;for(let d=0,l=n[d];l;l=n[++d])if(l===" "&&n[d+1]==="\\"&&n[d+2]==="n"&&(i+=n.slice(a,d)+"\\ ",d+=1,a=d,l="\\"),l==="\\")switch(n[d+1]){case"u":{i+=n.slice(a,d);let c=n.substr(d+2,4);switch(c){case"0000":i+="\\0";break;case"0007":i+="\\a";break;case"000b":i+="\\v";break;case"001b":i+="\\e";break;case"0085":i+="\\N";break;case"00a0":i+="\\_";break;case"2028":i+="\\L";break;case"2029":i+="\\P";break;default:c.substr(0,2)==="00"?i+="\\x"+c.substr(2):i+=n.substr(d,6)}d+=5,a=d+1}break;case"n":if(r||n[d+2]==='"'||n.length<s)d+=1;else{for(i+=n.slice(a,d)+`
15
+
16
+ `;n[d+2]==="\\"&&n[d+3]==="n"&&n[d+4]!=='"';)i+=`
17
+ `,d+=2;i+=o,n[d+2]===" "&&(i+="\\"),d+=1,a=d+1}break;default:d+=1}return i=a?i+n.slice(a):n,r?i:sn.foldFlowLines(i,o,sn.FOLD_QUOTED,ba(t,!1))}function Sm(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
18
+ `)||/[ \t]\n|\n[ \t]/.test(e))return Xs(e,t);let n=t.indent||(ka(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
19
+ ${n}`)+"'";return t.implicitKey?r:sn.foldFlowLines(r,n,sn.FOLD_FLOW,ba(t,!1))}function Wr(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=Xs;else{let s=e.includes('"'),o=e.includes("'");s&&!o?r=Sm:o&&!s?r=Xs:r=n?Sm:Xs}return r(e,t)}var Im;try{Im=new RegExp(`(^|(?<!
20
+ ))
21
+ +(?!
22
+ |$)`,"g")}catch{Im=/\n+(?!\n|$)/g}function wa({comment:e,type:t,value:n},r,s,o){let{blockQuote:i,commentString:a,lineWidth:d}=r.options;if(!i||/\n[\t ]+$/.test(n))return Wr(n,r);let l=r.indent||(r.forceBlockIndent||ka(n)?" ":""),c=i==="literal"?!0:i==="folded"||t===nt.Scalar.BLOCK_FOLDED?!1:t===nt.Scalar.BLOCK_LITERAL?!0:!YD(n,d,l.length);if(!n)return c?`|
23
+ `:`>
24
+ `;let m,f;for(f=n.length;f>0;--f){let v=n[f-1];if(v!==`
25
+ `&&v!==" "&&v!==" ")break}let h=n.substring(f),p=h.indexOf(`
26
+ `);p===-1?m="-":n===h||p!==h.length-1?(m="+",o&&o()):m="",h&&(n=n.slice(0,-h.length),h[h.length-1]===`
27
+ `&&(h=h.slice(0,-1)),h=h.replace(Im,`$&${l}`));let g=!1,w,k=-1;for(w=0;w<n.length;++w){let v=n[w];if(v===" ")g=!0;else if(v===`
28
+ `)k=w;else break}let C=n.substring(0,k<w?k+1:w);C&&(n=n.substring(C.length),C=C.replace(/\n+/g,`$&${l}`));let $=(g?l?"2":"1":"")+m;if(e&&($+=" "+a(e.replace(/ ?[\r\n]+/g," ")),s&&s()),!c){let v=n.replace(/\n+/g,`
29
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),T=!1,N=ba(r,!0);i!=="folded"&&t!==nt.Scalar.BLOCK_FOLDED&&(N.onOverflow=()=>{T=!0});let E=sn.foldFlowLines(`${C}${v}${h}`,l,sn.FOLD_BLOCK,N);if(!T)return`>${$}
30
+ ${l}${E}`}return n=n.replace(/\n+/g,`$&${l}`),`|${$}
31
+ ${l}${C}${n}${h}`}function zD(e,t,n,r){let{type:s,value:o}=e,{actualString:i,implicitKey:a,indent:d,indentStep:l,inFlow:c}=t;if(a&&o.includes(`
32
+ `)||c&&/[[\]{},]/.test(o))return Wr(o,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return a||c||!o.includes(`
33
+ `)?Wr(o,t):wa(e,t,n,r);if(!a&&!c&&s!==nt.Scalar.PLAIN&&o.includes(`
34
+ `))return wa(e,t,n,r);if(ka(o)){if(d==="")return t.forceBlockIndent=!0,wa(e,t,n,r);if(a&&d===l)return Wr(o,t)}let m=o.replace(/\n+/g,`$&
35
+ ${d}`);if(i){let f=g=>g.default&&g.tag!=="tag:yaml.org,2002:str"&&g.test?.test(m),{compat:h,tags:p}=t.doc.schema;if(p.some(f)||h?.some(f))return Wr(o,t)}return a?m:sn.foldFlowLines(m,d,sn.FOLD_FLOW,ba(t,!1))}function JD(e,t,n,r){let{implicitKey:s,inFlow:o}=t,i=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;a!==nt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=nt.Scalar.QUOTE_DOUBLE);let d=c=>{switch(c){case nt.Scalar.BLOCK_FOLDED:case nt.Scalar.BLOCK_LITERAL:return s||o?Wr(i.value,t):wa(i,t,n,r);case nt.Scalar.QUOTE_DOUBLE:return Xs(i.value,t);case nt.Scalar.QUOTE_SINGLE:return Sm(i.value,t);case nt.Scalar.PLAIN:return zD(i,t,n,r);default:return null}},l=d(a);if(l===null){let{defaultKeyType:c,defaultStringType:m}=t.options,f=s&&c||m;if(l=d(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}oE.stringifyString=JD});var Zs=M($m=>{"use strict";var XD=ma(),on=G(),QD=zs(),ZD=Qs();function e0(e,t){let n=Object.assign({blockQuote:!0,commentString:QD.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function t0(e,t){if(t.tag){let s=e.filter(o=>o.tag===t.tag);if(s.length>0)return s.find(o=>o.format===t.format)??s[0]}let n,r;if(on.isScalar(t)){r=t.value;let s=e.filter(o=>o.identify?.(r));if(s.length>1){let o=s.filter(i=>i.test);o.length>0&&(s=o)}n=s.find(o=>o.format===t.format)??s.find(o=>!o.format)}else r=t,n=e.find(s=>s.nodeClass&&r instanceof s.nodeClass);if(!n){let s=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${s} value`)}return n}function n0(e,t,{anchors:n,doc:r}){if(!r.directives)return"";let s=[],o=(on.isScalar(e)||on.isCollection(e))&&e.anchor;o&&XD.anchorIsValid(o)&&(n.add(o),s.push(`&${o}`));let i=e.tag??(t.default?null:t.tag);return i&&s.push(r.directives.tagString(i)),s.join(" ")}function r0(e,t,n,r){if(on.isPair(e))return e.toString(t,n,r);if(on.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let s,o=on.isNode(e)?e:t.doc.createNode(e,{onTagObj:d=>s=d});s??(s=t0(t.doc.schema.tags,o));let i=n0(o,s,t);i.length>0&&(t.indentAtStart=(t.indentAtStart??0)+i.length+1);let a=typeof s.stringify=="function"?s.stringify(o,t,n,r):on.isScalar(o)?ZD.stringifyString(o,t,n,r):o.toString(t,n,r);return i?on.isScalar(o)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}
36
+ ${t.indent}${a}`:a}$m.createStringifyContext=e0;$m.stringify=r0});var lE=M(dE=>{"use strict";var Mt=G(),iE=ge(),aE=Zs(),eo=zs();function s0({key:e,value:t},n,r,s){let{allNullValues:o,doc:i,indent:a,indentStep:d,options:{commentString:l,indentSeq:c,simpleKeys:m}}=n,f=Mt.isNode(e)&&e.comment||null;if(m){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Mt.isCollection(e)||!Mt.isNode(e)&&typeof e=="object"){let N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let h=!m&&(!e||f&&t==null&&!n.inFlow||Mt.isCollection(e)||(Mt.isScalar(e)?e.type===iE.Scalar.BLOCK_FOLDED||e.type===iE.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(m||!o),indent:a+d});let p=!1,g=!1,w=aE.stringify(e,n,()=>p=!0,()=>g=!0);if(!h&&!n.inFlow&&w.length>1024){if(m)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(o||t==null)return p&&r&&r(),w===""?"?":h?`? ${w}`:w}else if(o&&!m||t==null&&h)return w=`? ${w}`,f&&!p?w+=eo.lineComment(w,n.indent,l(f)):g&&s&&s(),w;p&&(f=null),h?(f&&(w+=eo.lineComment(w,n.indent,l(f))),w=`? ${w}
37
+ ${a}:`):(w=`${w}:`,f&&(w+=eo.lineComment(w,n.indent,l(f))));let k,C,R;Mt.isNode(t)?(k=!!t.spaceBefore,C=t.commentBefore,R=t.comment):(k=!1,C=null,R=null,t&&typeof t=="object"&&(t=i.createNode(t))),n.implicitKey=!1,!h&&!f&&Mt.isScalar(t)&&(n.indentAtStart=w.length+1),g=!1,!c&&d.length>=2&&!n.inFlow&&!h&&Mt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let $=!1,v=aE.stringify(t,n,()=>$=!0,()=>g=!0),T=" ";if(f||k||C){if(T=k?`
38
+ `:"",C){let N=l(C);T+=`
39
+ ${eo.indentComment(N,n.indent)}`}v===""&&!n.inFlow?T===`
40
+ `&&R&&(T=`
41
+
42
+ `):T+=`
43
+ ${n.indent}`}else if(!h&&Mt.isCollection(t)){let N=v[0],E=v.indexOf(`
44
+ `),S=E!==-1,x=n.inFlow??t.flow??t.items.length===0;if(S||!x){let A=!1;if(S&&(N==="&"||N==="!")){let O=v.indexOf(" ");N==="&"&&O!==-1&&O<E&&v[O+1]==="!"&&(O=v.indexOf(" ",O+1)),(O===-1||E<O)&&(A=!0)}A||(T=`
45
+ ${n.indent}`)}}else(v===""||v[0]===`
46
+ `)&&(T="");return w+=T+v,n.inFlow?$&&r&&r():R&&!$?w+=eo.lineComment(w,n.indent,l(R)):g&&s&&s(),w}dE.stringifyPair=s0});var Tm=M(xm=>{"use strict";var cE=qo("process");function o0(e,...t){e==="debug"&&console.log(...t)}function i0(e,t){(e==="debug"||e==="warn")&&(typeof cE.emitWarning=="function"?cE.emitWarning(t):console.warn(t))}xm.debug=o0;xm.warn=i0});var Sa=M(Ra=>{"use strict";var va=G(),mE=ge(),Ea="<<",Ca={identify:e=>e===Ea||typeof e=="symbol"&&e.description===Ea,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new mE.Scalar(Symbol(Ea)),{addToJSMap:fE}),stringify:()=>Ea},a0=(e,t)=>(Ca.identify(t)||va.isScalar(t)&&(!t.type||t.type===mE.Scalar.PLAIN)&&Ca.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===Ca.tag&&n.default);function fE(e,t,n){let r=pE(e,n);if(va.isSeq(r))for(let s of r.items)Am(e,t,s);else if(Array.isArray(r))for(let s of r)Am(e,t,s);else Am(e,t,r)}function Am(e,t,n){let r=pE(e,n);if(!va.isMap(r))throw new Error("Merge sources must be maps or map aliases");let s=r.toJSON(null,e,Map);for(let[o,i]of s)t instanceof Map?t.has(o)||t.set(o,i):t instanceof Set?t.add(o):Object.prototype.hasOwnProperty.call(t,o)||Object.defineProperty(t,o,{value:i,writable:!0,enumerable:!0,configurable:!0});return t}function pE(e,t){return e&&va.isAlias(t)?t.resolve(e.doc,e):t}Ra.addMergeToJSMap=fE;Ra.isMergeKey=a0;Ra.merge=Ca});var Mm=M(gE=>{"use strict";var d0=Tm(),uE=Sa(),l0=Zs(),hE=G(),Om=nn();function c0(e,t,{key:n,value:r}){if(hE.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(uE.isMergeKey(e,n))uE.addMergeToJSMap(e,t,r);else{let s=Om.toJS(n,"",e);if(t instanceof Map)t.set(s,Om.toJS(r,s,e));else if(t instanceof Set)t.add(s);else{let o=m0(n,s,e),i=Om.toJS(r,o,e);o in t?Object.defineProperty(t,o,{value:i,writable:!0,enumerable:!0,configurable:!0}):t[o]=i}}return t}function m0(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(hE.isNode(e)&&n?.doc){let r=l0.createStringifyContext(n.doc,{});r.anchors=new Set;for(let o of n.anchors.keys())r.anchors.add(o.anchor);r.inFlow=!0,r.inStringifyKey=!0;let s=e.toString(r);if(!n.mapKeyWarned){let o=JSON.stringify(s);o.length>40&&(o=o.substring(0,36)+'..."'),d0.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return s}return JSON.stringify(t)}gE.addPairToJSMap=c0});var an=M(Nm=>{"use strict";var yE=Ys(),f0=lE(),p0=Mm(),Ia=G();function u0(e,t,n){let r=yE.createNode(e,void 0,n),s=yE.createNode(t,void 0,n);return new $a(r,s)}var $a=class e{constructor(t,n=null){Object.defineProperty(this,Ia.NODE_TYPE,{value:Ia.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return Ia.isNode(n)&&(n=n.clone(t)),Ia.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return p0.addPairToJSMap(n,r,this)}toString(t,n,r){return t?.doc?f0.stringifyPair(this,t,n,r):JSON.stringify(this)}};Nm.Pair=$a;Nm.createPair=u0});var Pm=M(bE=>{"use strict";var Bn=G(),wE=Zs(),xa=zs();function h0(e,t,n){return(t.inFlow??e.flow?y0:g0)(e,t,n)}function g0({comment:e,items:t},n,{blockItemPrefix:r,flowChars:s,itemIndent:o,onChompKeep:i,onComment:a}){let{indent:d,options:{commentString:l}}=n,c=Object.assign({},n,{indent:o,type:null}),m=!1,f=[];for(let p=0;p<t.length;++p){let g=t[p],w=null;if(Bn.isNode(g))!m&&g.spaceBefore&&f.push(""),Ta(n,f,g.commentBefore,m),g.comment&&(w=g.comment);else if(Bn.isPair(g)){let C=Bn.isNode(g.key)?g.key:null;C&&(!m&&C.spaceBefore&&f.push(""),Ta(n,f,C.commentBefore,m))}m=!1;let k=wE.stringify(g,c,()=>w=null,()=>m=!0);w&&(k+=xa.lineComment(k,o,l(w))),m&&w&&(m=!1),f.push(r+k)}let h;if(f.length===0)h=s.start+s.end;else{h=f[0];for(let p=1;p<f.length;++p){let g=f[p];h+=g?`
47
+ ${d}${g}`:`
48
+ `}}return e?(h+=`
49
+ `+xa.indentComment(l(e),d),a&&a()):m&&i&&i(),h}function y0({items:e},t,{flowChars:n,itemIndent:r}){let{indent:s,indentStep:o,flowCollectionPadding:i,options:{commentString:a}}=t;r+=o;let d=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,c=0,m=[];for(let p=0;p<e.length;++p){let g=e[p],w=null;if(Bn.isNode(g))g.spaceBefore&&m.push(""),Ta(t,m,g.commentBefore,!1),g.comment&&(w=g.comment);else if(Bn.isPair(g)){let C=Bn.isNode(g.key)?g.key:null;C&&(C.spaceBefore&&m.push(""),Ta(t,m,C.commentBefore,!1),C.comment&&(l=!0));let R=Bn.isNode(g.value)?g.value:null;R?(R.comment&&(w=R.comment),R.commentBefore&&(l=!0)):g.value==null&&C?.comment&&(w=C.comment)}w&&(l=!0);let k=wE.stringify(g,d,()=>w=null);l||(l=m.length>c||k.includes(`
50
+ `)),p<e.length-1?k+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=m.reduce((C,R)=>C+R.length+2,2)+(k.length+2)>t.options.lineWidth)),l&&(k+=",")),w&&(k+=xa.lineComment(k,r,a(w))),m.push(k),c=m.length}let{start:f,end:h}=n;if(m.length===0)return f+h;if(!l){let p=m.reduce((g,w)=>g+w.length+2,2);l=t.options.lineWidth>0&&p>t.options.lineWidth}if(l){let p=f;for(let g of m)p+=g?`
51
+ ${o}${s}${g}`:`
52
+ `;return`${p}
53
+ ${s}${h}`}else return`${f}${i}${m.join(" ")}${i}${h}`}function Ta({indent:e,options:{commentString:t}},n,r,s){if(r&&s&&(r=r.replace(/^\n+/,"")),r){let o=xa.indentComment(t(r),e);n.push(o.trimStart())}}bE.stringifyCollection=h0});var ln=M(Dm=>{"use strict";var w0=Pm(),b0=Mm(),k0=ha(),dn=G(),Aa=an(),E0=ge();function to(e,t){let n=dn.isScalar(t)?t.value:t;for(let r of e)if(dn.isPair(r)&&(r.key===t||r.key===n||dn.isScalar(r.key)&&r.key.value===n))return r}var Lm=class extends k0.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(dn.MAP,t),this.items=[]}static from(t,n,r){let{keepUndefined:s,replacer:o}=r,i=new this(t),a=(d,l)=>{if(typeof o=="function")l=o.call(n,d,l);else if(Array.isArray(o)&&!o.includes(d))return;(l!==void 0||s)&&i.items.push(Aa.createPair(d,l,r))};if(n instanceof Map)for(let[d,l]of n)a(d,l);else if(n&&typeof n=="object")for(let d of Object.keys(n))a(d,n[d]);return typeof t.sortMapEntries=="function"&&i.items.sort(t.sortMapEntries),i}add(t,n){let r;dn.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Aa.Pair(t,t?.value):r=new Aa.Pair(t.key,t.value);let s=to(this.items,r.key),o=this.schema?.sortMapEntries;if(s){if(!n)throw new Error(`Key ${r.key} already set`);dn.isScalar(s.value)&&E0.isScalarValue(r.value)?s.value.value=r.value:s.value=r.value}else if(o){let i=this.items.findIndex(a=>o(r,a)<0);i===-1?this.items.push(r):this.items.splice(i,0,r)}else this.items.push(r)}delete(t){let n=to(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let s=to(this.items,t)?.value;return(!n&&dn.isScalar(s)?s.value:s)??void 0}has(t){return!!to(this.items,t)}set(t,n){this.add(new Aa.Pair(t,n),!0)}toJSON(t,n,r){let s=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(s);for(let o of this.items)b0.addPairToJSMap(n,s,o);return s}toString(t,n,r){if(!t)return JSON.stringify(this);for(let s of this.items)if(!dn.isPair(s))throw new Error(`Map items must all be pairs; found ${JSON.stringify(s)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),w0.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:n})}};Dm.YAMLMap=Lm;Dm.findPair=to});var Br=M(EE=>{"use strict";var C0=G(),kE=ln(),v0={collection:"map",default:!0,nodeClass:kE.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return C0.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>kE.YAMLMap.from(e,t,n)};EE.map=v0});var cn=M(CE=>{"use strict";var R0=Ys(),S0=Pm(),I0=ha(),Ma=G(),$0=ge(),x0=nn(),_m=class extends I0.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Ma.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=Oa(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let r=Oa(t);if(typeof r!="number")return;let s=this.items[r];return!n&&Ma.isScalar(s)?s.value:s}has(t){let n=Oa(t);return typeof n=="number"&&n<this.items.length}set(t,n){let r=Oa(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let s=this.items[r];Ma.isScalar(s)&&$0.isScalarValue(n)?s.value=n:this.items[r]=n}toJSON(t,n){let r=[];n?.onCreate&&n.onCreate(r);let s=0;for(let o of this.items)r.push(x0.toJS(o,String(s++),n));return r}toString(t,n,r){return t?S0.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(t,n,r){let{replacer:s}=r,o=new this(t);if(n&&Symbol.iterator in Object(n)){let i=0;for(let a of n){if(typeof s=="function"){let d=n instanceof Set?a:String(i++);a=s.call(n,d,a)}o.items.push(R0.createNode(a,void 0,r))}}return o}};function Oa(e){let t=Ma.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}CE.YAMLSeq=_m});var Hr=M(RE=>{"use strict";var T0=G(),vE=cn(),A0={collection:"seq",default:!0,nodeClass:vE.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return T0.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>vE.YAMLSeq.from(e,t,n)};RE.seq=A0});var no=M(SE=>{"use strict";var O0=Qs(),M0={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),O0.stringifyString(e,t,n,r)}};SE.string=M0});var Na=M(xE=>{"use strict";var IE=ge(),$E={identify:e=>e==null,createNode:()=>new IE.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new IE.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&$E.test.test(e)?e:t.options.nullStr};xE.nullTag=$E});var jm=M(AE=>{"use strict";var N0=ge(),TE={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new N0.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&TE.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?n.options.trueStr:n.options.falseStr}};AE.boolTag=TE});var Ur=M(OE=>{"use strict";function P0({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r=="bigint")return String(r);let s=typeof r=="number"?r:Number(r);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let o=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(o)&&!o.includes("e")){let i=o.indexOf(".");i<0&&(i=o.length,o+=".");let a=t-(o.length-i-1);for(;a-- >0;)o+="0"}return o}OE.stringifyNumber=P0});var qm=M(Pa=>{"use strict";var L0=ge(),Fm=Ur(),D0={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Fm.stringifyNumber},_0={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Fm.stringifyNumber(e)}},j0={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new L0.Scalar(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:Fm.stringifyNumber};Pa.float=j0;Pa.floatExp=_0;Pa.floatNaN=D0});var Bm=M(Da=>{"use strict";var ME=Ur(),La=e=>typeof e=="bigint"||Number.isInteger(e),Wm=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function NE(e,t,n){let{value:r}=e;return La(r)&&r>=0?n+r.toString(t):ME.stringifyNumber(e)}var F0={identify:e=>La(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Wm(e,2,8,n),stringify:e=>NE(e,8,"0o")},q0={identify:La,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Wm(e,0,10,n),stringify:ME.stringifyNumber},W0={identify:e=>La(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Wm(e,2,16,n),stringify:e=>NE(e,16,"0x")};Da.int=q0;Da.intHex=W0;Da.intOct=F0});var LE=M(PE=>{"use strict";var B0=Br(),H0=Na(),U0=Hr(),V0=no(),G0=jm(),Hm=qm(),Um=Bm(),K0=[B0.map,U0.seq,V0.string,H0.nullTag,G0.boolTag,Um.intOct,Um.int,Um.intHex,Hm.floatNaN,Hm.floatExp,Hm.float];PE.schema=K0});var jE=M(_E=>{"use strict";var Y0=ge(),z0=Br(),J0=Hr();function DE(e){return typeof e=="bigint"||Number.isInteger(e)}var _a=({value:e})=>JSON.stringify(e),X0=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:_a},{identify:e=>e==null,createNode:()=>new Y0.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:_a},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:_a},{identify:DE,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>DE(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:_a}],Q0={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Z0=[z0.map,J0.seq].concat(X0,Q0);_E.schema=Z0});var Gm=M(FE=>{"use strict";var ro=qo("buffer"),Vm=ge(),e_=Qs(),t_={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof ro.Buffer=="function")return ro.Buffer.from(e,"base64");if(typeof atob=="function"){let n=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let s=0;s<n.length;++s)r[s]=n.charCodeAt(s);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},r,s,o){if(!n)return"";let i=n,a;if(typeof ro.Buffer=="function")a=i instanceof ro.Buffer?i.toString("base64"):ro.Buffer.from(i.buffer).toString("base64");else if(typeof btoa=="function"){let d="";for(let l=0;l<i.length;++l)d+=String.fromCharCode(i[l]);a=btoa(d)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Vm.Scalar.BLOCK_LITERAL),t!==Vm.Scalar.QUOTE_DOUBLE){let d=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(a.length/d),c=new Array(l);for(let m=0,f=0;m<l;++m,f+=d)c[m]=a.substr(f,d);a=c.join(t===Vm.Scalar.BLOCK_LITERAL?`
54
+ `:" ")}return e_.stringifyString({comment:e,type:t,value:a},r,s,o)}};FE.binary=t_});var qa=M(Fa=>{"use strict";var ja=G(),Km=an(),n_=ge(),r_=cn();function qE(e,t){if(ja.isSeq(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!ja.isPair(r)){if(ja.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let s=r.items[0]||new Km.Pair(new n_.Scalar(null));if(r.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${r.commentBefore}
55
+ ${s.key.commentBefore}`:r.commentBefore),r.comment){let o=s.value??s.key;o.comment=o.comment?`${r.comment}
56
+ ${o.comment}`:r.comment}r=s}e.items[n]=ja.isPair(r)?r:new Km.Pair(r)}}else t("Expected a sequence for this tag");return e}function WE(e,t,n){let{replacer:r}=n,s=new r_.YAMLSeq(e);s.tag="tag:yaml.org,2002:pairs";let o=0;if(t&&Symbol.iterator in Object(t))for(let i of t){typeof r=="function"&&(i=r.call(t,String(o++),i));let a,d;if(Array.isArray(i))if(i.length===2)a=i[0],d=i[1];else throw new TypeError(`Expected [key, value] tuple: ${i}`);else if(i&&i instanceof Object){let l=Object.keys(i);if(l.length===1)a=l[0],d=i[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=i;s.items.push(Km.createPair(a,d,n))}return s}var s_={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:qE,createNode:WE};Fa.createPairs=WE;Fa.pairs=s_;Fa.resolvePairs=qE});var Jm=M(zm=>{"use strict";var BE=G(),Ym=nn(),so=ln(),o_=cn(),HE=qa(),Hn=class e extends o_.YAMLSeq{constructor(){super(),this.add=so.YAMLMap.prototype.add.bind(this),this.delete=so.YAMLMap.prototype.delete.bind(this),this.get=so.YAMLMap.prototype.get.bind(this),this.has=so.YAMLMap.prototype.has.bind(this),this.set=so.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,n){if(!n)return super.toJSON(t);let r=new Map;n?.onCreate&&n.onCreate(r);for(let s of this.items){let o,i;if(BE.isPair(s)?(o=Ym.toJS(s.key,"",n),i=Ym.toJS(s.value,o,n)):o=Ym.toJS(s,"",n),r.has(o))throw new Error("Ordered maps must not include duplicate keys");r.set(o,i)}return r}static from(t,n,r){let s=HE.createPairs(t,n,r),o=new this;return o.items=s.items,o}};Hn.tag="tag:yaml.org,2002:omap";var i_={collection:"seq",identify:e=>e instanceof Map,nodeClass:Hn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=HE.resolvePairs(e,t),r=[];for(let{key:s}of n.items)BE.isScalar(s)&&(r.includes(s.value)?t(`Ordered maps must not include duplicate keys: ${s.value}`):r.push(s.value));return Object.assign(new Hn,n)},createNode:(e,t,n)=>Hn.from(e,t,n)};zm.YAMLOMap=Hn;zm.omap=i_});var YE=M(Xm=>{"use strict";var UE=ge();function VE({value:e,source:t},n){return t&&(e?GE:KE).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var GE={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new UE.Scalar(!0),stringify:VE},KE={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new UE.Scalar(!1),stringify:VE};Xm.falseTag=KE;Xm.trueTag=GE});var zE=M(Wa=>{"use strict";var a_=ge(),Qm=Ur(),d_={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Qm.stringifyNumber},l_={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Qm.stringifyNumber(e)}},c_={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new a_.Scalar(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let r=e.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:Qm.stringifyNumber};Wa.float=c_;Wa.floatExp=l_;Wa.floatNaN=d_});var XE=M(io=>{"use strict";var JE=Ur(),oo=e=>typeof e=="bigint"||Number.isInteger(e);function Ba(e,t,n,{intAsBigInt:r}){let s=e[0];if((s==="-"||s==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let i=BigInt(e);return s==="-"?BigInt(-1)*i:i}let o=parseInt(e,n);return s==="-"?-1*o:o}function Zm(e,t,n){let{value:r}=e;if(oo(r)){let s=r.toString(t);return r<0?"-"+n+s.substr(1):n+s}return JE.stringifyNumber(e)}var m_={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Ba(e,2,2,n),stringify:e=>Zm(e,2,"0b")},f_={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Ba(e,1,8,n),stringify:e=>Zm(e,8,"0")},p_={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Ba(e,0,10,n),stringify:JE.stringifyNumber},u_={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Ba(e,2,16,n),stringify:e=>Zm(e,16,"0x")};io.int=p_;io.intBin=m_;io.intHex=u_;io.intOct=f_});var tf=M(ef=>{"use strict";var Va=G(),Ha=an(),Ua=ln(),Un=class e extends Ua.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;Va.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new Ha.Pair(t.key,null):n=new Ha.Pair(t,null),Ua.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let r=Ua.findPair(this.items,t);return!n&&Va.isPair(r)?Va.isScalar(r.key)?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=Ua.findPair(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new Ha.Pair(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(t,n,r){let{replacer:s}=r,o=new this(t);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof s=="function"&&(i=s.call(n,i,i)),o.items.push(Ha.createPair(i,null,r));return o}};Un.tag="tag:yaml.org,2002:set";var h_={collection:"map",identify:e=>e instanceof Set,nodeClass:Un,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>Un.from(e,t,n),resolve(e,t){if(Va.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Un,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ef.YAMLSet=Un;ef.set=h_});var rf=M(Ga=>{"use strict";var g_=Ur();function nf(e,t){let n=e[0],r=n==="-"||n==="+"?e.substring(1):e,s=i=>t?BigInt(i):Number(i),o=r.replace(/_/g,"").split(":").reduce((i,a)=>i*s(60)+s(a),s(0));return n==="-"?s(-1)*o:o}function QE(e){let{value:t}=e,n=i=>i;if(typeof t=="bigint")n=i=>BigInt(i);else if(isNaN(t)||!isFinite(t))return g_.stringifyNumber(e);let r="";t<0&&(r="-",t*=n(-1));let s=n(60),o=[t%s];return t<60?o.unshift(0):(t=(t-o[0])/s,o.unshift(t%s),t>=60&&(t=(t-o[0])/s,o.unshift(t))),r+o.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var y_={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>nf(e,n),stringify:QE},w_={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>nf(e,!1),stringify:QE},ZE={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(ZE.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,s,o,i,a]=t.map(Number),d=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(n,r-1,s,o||0,i||0,a||0,d),c=t[8];if(c&&c!=="Z"){let m=nf(c,!1);Math.abs(m)<30&&(m*=60),l-=6e4*m}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Ga.floatTime=w_;Ga.intTime=y_;Ga.timestamp=ZE});var nC=M(tC=>{"use strict";var b_=Br(),k_=Na(),E_=Hr(),C_=no(),v_=Gm(),eC=YE(),sf=zE(),Ka=XE(),R_=Sa(),S_=Jm(),I_=qa(),$_=tf(),of=rf(),x_=[b_.map,E_.seq,C_.string,k_.nullTag,eC.trueTag,eC.falseTag,Ka.intBin,Ka.intOct,Ka.int,Ka.intHex,sf.floatNaN,sf.floatExp,sf.float,v_.binary,R_.merge,S_.omap,I_.pairs,$_.set,of.intTime,of.floatTime,of.timestamp];tC.schema=x_});var fC=M(lf=>{"use strict";var iC=Br(),T_=Na(),aC=Hr(),A_=no(),O_=jm(),af=qm(),df=Bm(),M_=LE(),N_=jE(),dC=Gm(),ao=Sa(),lC=Jm(),cC=qa(),rC=nC(),mC=tf(),Ya=rf(),sC=new Map([["core",M_.schema],["failsafe",[iC.map,aC.seq,A_.string]],["json",N_.schema],["yaml11",rC.schema],["yaml-1.1",rC.schema]]),oC={binary:dC.binary,bool:O_.boolTag,float:af.float,floatExp:af.floatExp,floatNaN:af.floatNaN,floatTime:Ya.floatTime,int:df.int,intHex:df.intHex,intOct:df.intOct,intTime:Ya.intTime,map:iC.map,merge:ao.merge,null:T_.nullTag,omap:lC.omap,pairs:cC.pairs,seq:aC.seq,set:mC.set,timestamp:Ya.timestamp},P_={"tag:yaml.org,2002:binary":dC.binary,"tag:yaml.org,2002:merge":ao.merge,"tag:yaml.org,2002:omap":lC.omap,"tag:yaml.org,2002:pairs":cC.pairs,"tag:yaml.org,2002:set":mC.set,"tag:yaml.org,2002:timestamp":Ya.timestamp};function L_(e,t,n){let r=sC.get(t);if(r&&!e)return n&&!r.includes(ao.merge)?r.concat(ao.merge):r.slice();let s=r;if(!s)if(Array.isArray(e))s=[];else{let o=Array.from(sC.keys()).filter(i=>i!=="yaml11").map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${o} or define customTags array`)}if(Array.isArray(e))for(let o of e)s=s.concat(o);else typeof e=="function"&&(s=e(s.slice()));return n&&(s=s.concat(ao.merge)),s.reduce((o,i)=>{let a=typeof i=="string"?oC[i]:i;if(!a){let d=JSON.stringify(i),l=Object.keys(oC).map(c=>JSON.stringify(c)).join(", ");throw new Error(`Unknown custom tag ${d}; use one of ${l}`)}return o.includes(a)||o.push(a),o},[])}lf.coreKnownTags=P_;lf.getTags=L_});var ff=M(pC=>{"use strict";var cf=G(),D_=Br(),__=Hr(),j_=no(),za=fC(),F_=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,mf=class e{constructor({compat:t,customTags:n,merge:r,resolveKnownTags:s,schema:o,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(t)?za.getTags(t,"compat"):t?za.getTags(null,t):null,this.name=typeof o=="string"&&o||"core",this.knownTags=s?za.coreKnownTags:{},this.tags=za.getTags(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,cf.MAP,{value:D_.map}),Object.defineProperty(this,cf.SCALAR,{value:j_.string}),Object.defineProperty(this,cf.SEQ,{value:__.seq}),this.sortMapEntries=typeof i=="function"?i:i===!0?F_:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};pC.Schema=mf});var hC=M(uC=>{"use strict";var q_=G(),pf=Zs(),lo=zs();function W_(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let d=e.directives.toString(e);d?(n.push(d),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");let s=pf.createStringifyContext(e,t),{commentString:o}=s.options;if(e.commentBefore){n.length!==1&&n.unshift("");let d=o(e.commentBefore);n.unshift(lo.indentComment(d,""))}let i=!1,a=null;if(e.contents){if(q_.isNode(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){let c=o(e.contents.commentBefore);n.push(lo.indentComment(c,""))}s.forceBlockIndent=!!e.comment,a=e.contents.comment}let d=a?void 0:()=>i=!0,l=pf.stringify(e.contents,s,()=>a=null,d);a&&(l+=lo.lineComment(l,"",o(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(pf.stringify(e.contents,s));if(e.directives?.docEnd)if(e.comment){let d=o(e.comment);d.includes(`
57
+ `)?(n.push("..."),n.push(lo.indentComment(d,""))):n.push(`... ${d}`)}else n.push("...");else{let d=e.comment;d&&i&&(d=d.replace(/^\n+/,"")),d&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(lo.indentComment(o(d),"")))}return n.join(`
58
+ `)+`
59
+ `}uC.stringifyDocument=W_});var co=M(gC=>{"use strict";var B_=Ks(),Vr=ha(),Ye=G(),H_=an(),U_=nn(),V_=ff(),G_=hC(),uf=ma(),K_=ym(),Y_=Ys(),hf=gm(),gf=class e{constructor(t,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ye.NODE_TYPE,{value:Ye.DOC});let s=null;typeof n=="function"||Array.isArray(n)?s=n:r===void 0&&n&&(r=n,n=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=o;let{version:i}=o;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(i=this.directives.yaml.version)):this.directives=new hf.Directives({version:i}),this.setSchema(i,r),this.contents=t===void 0?null:this.createNode(t,s,r)}clone(){let t=Object.create(e.prototype,{[Ye.NODE_TYPE]:{value:Ye.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Ye.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Gr(this.contents)&&this.contents.add(t)}addIn(t,n){Gr(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let r=uf.anchorNames(this);t.anchor=!n||r.has(n)?uf.findNewAnchor(n||"a",r):n}return new B_.Alias(t.anchor)}createNode(t,n,r){let s;if(typeof n=="function")t=n.call({"":t},"",t),s=n;else if(Array.isArray(n)){let w=C=>typeof C=="number"||C instanceof String||C instanceof Number,k=n.filter(w).map(String);k.length>0&&(n=n.concat(k)),s=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:o,anchorPrefix:i,flow:a,keepUndefined:d,onTagObj:l,tag:c}=r??{},{onAnchor:m,setAnchors:f,sourceObjects:h}=uf.createNodeAnchors(this,i||"a"),p={aliasDuplicateObjects:o??!0,keepUndefined:d??!1,onAnchor:m,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:h},g=Y_.createNode(t,c,p);return a&&Ye.isCollection(g)&&(g.flow=!0),f(),g}createPair(t,n,r={}){let s=this.createNode(t,null,r),o=this.createNode(n,null,r);return new H_.Pair(s,o)}delete(t){return Gr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Vr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Gr(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return Ye.isCollection(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return Vr.isEmptyPath(t)?!n&&Ye.isScalar(this.contents)?this.contents.value:this.contents:Ye.isCollection(this.contents)?this.contents.getIn(t,n):void 0}has(t){return Ye.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Vr.isEmptyPath(t)?this.contents!==void 0:Ye.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=Vr.collectionFromPath(this.schema,[t],n):Gr(this.contents)&&this.contents.set(t,n)}setIn(t,n){Vr.isEmptyPath(t)?this.contents=n:this.contents==null?this.contents=Vr.collectionFromPath(this.schema,Array.from(t),n):Gr(this.contents)&&this.contents.setIn(t,n)}setSchema(t,n={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new hf.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new hf.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let s=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${s}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new V_.Schema(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:n,mapAsMap:r,maxAliasCount:s,onAnchor:o,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},d=U_.toJS(this.contents,n??"",a);if(typeof o=="function")for(let{count:l,res:c}of a.anchors.values())o(c,l);return typeof i=="function"?K_.applyReviver(i,{"":d},"",d):d}toJSON(t,n){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:n})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let n=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return G_.stringifyDocument(this,t)}};function Gr(e){if(Ye.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}gC.Document=gf});var po=M(fo=>{"use strict";var mo=class extends Error{constructor(t,n,r,s){super(),this.name=t,this.code=r,this.message=s,this.pos=n}},yf=class extends mo{constructor(t,n,r){super("YAMLParseError",t,n,r)}},wf=class extends mo{constructor(t,n,r){super("YAMLWarning",t,n,r)}},z_=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>t.linePos(a));let{line:r,col:s}=n.linePos[0];n.message+=` at line ${r}, column ${s}`;let o=s-1,i=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(o>=60&&i.length>80){let a=Math.min(o-39,i.length-79);i="\u2026"+i.substring(a),o-=a-1}if(i.length>80&&(i=i.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(i.substring(0,o))){let a=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
60
+ `),i=a+i}if(/[^ ]/.test(i)){let a=1,d=n.linePos[1];d?.line===r&&d.col>s&&(a=Math.max(1,Math.min(d.col-s,80-o)));let l=" ".repeat(o)+"^".repeat(a);n.message+=`:
61
+
62
+ ${i}
63
+ ${l}
64
+ `}};fo.YAMLError=mo;fo.YAMLParseError=yf;fo.YAMLWarning=wf;fo.prettifyError=z_});var uo=M(yC=>{"use strict";function J_(e,{flow:t,indicator:n,next:r,offset:s,onError:o,parentIndent:i,startOnNewline:a}){let d=!1,l=a,c=a,m="",f="",h=!1,p=!1,g=null,w=null,k=null,C=null,R=null,$=null,v=null;for(let E of e)switch(p&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&o(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p=!1),g&&(l&&E.type!=="comment"&&E.type!=="newline"&&o(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),g=null),E.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&E.source.includes(" ")&&(g=E),c=!0;break;case"comment":{c||o(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let S=E.source.substring(1)||" ";m?m+=f+S:m=S,f="",l=!1;break}case"newline":l?m?m+=E.source:(!$||n!=="seq-item-ind")&&(d=!0):f+=E.source,l=!0,h=!0,(w||k)&&(C=E),c=!0;break;case"anchor":w&&o(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&o(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),w=E,v??(v=E.offset),l=!1,c=!1,p=!0;break;case"tag":{k&&o(E,"MULTIPLE_TAGS","A node can have at most one tag"),k=E,v??(v=E.offset),l=!1,c=!1,p=!0;break}case n:(w||k)&&o(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),$&&o(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${t??"collection"}`),$=E,l=n==="seq-item-ind"||n==="explicit-key-ind",c=!1;break;case"comma":if(t){R&&o(E,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),R=E,l=!1,c=!1;break}default:o(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),l=!1,c=!1}let T=e[e.length-1],N=T?T.offset+T.source.length:s;return p&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&o(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g&&(l&&g.indent<=i||r?.type==="block-map"||r?.type==="block-seq")&&o(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:R,found:$,spaceBefore:d,comment:m,hasNewline:h,anchor:w,tag:k,newlineAfterProp:C,end:N,start:v??N}}yC.resolveProps=J_});var Ja=M(wC=>{"use strict";function bf(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
65
+ `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(bf(t.key)||bf(t.value))return!0}return!1;default:return!0}}wC.containsNewline=bf});var kf=M(bC=>{"use strict";var X_=Ja();function Q_(e,t,n){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&X_.containsNewline(t)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}bC.flowIndentCheck=Q_});var Ef=M(EC=>{"use strict";var kC=G();function Z_(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let s=typeof r=="function"?r:(o,i)=>o===i||kC.isScalar(o)&&kC.isScalar(i)&&o.value===i.value;return t.some(o=>s(o.key,n))}EC.mapIncludes=Z_});var $C=M(IC=>{"use strict";var CC=an(),ej=ln(),vC=uo(),tj=Ja(),RC=kf(),nj=Ef(),SC="All mapping items must start at the same column";function rj({composeNode:e,composeEmptyNode:t},n,r,s,o){let i=o?.nodeClass??ej.YAMLMap,a=new i(n.schema);n.atRoot&&(n.atRoot=!1);let d=r.offset,l=null;for(let c of r.items){let{start:m,key:f,sep:h,value:p}=c,g=vC.resolveProps(m,{indicator:"explicit-key-ind",next:f??h?.[0],offset:d,onError:s,parentIndent:r.indent,startOnNewline:!0}),w=!g.found;if(w){if(f&&(f.type==="block-seq"?s(d,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&s(d,"BAD_INDENT",SC)),!g.anchor&&!g.tag&&!h){l=g.end,g.comment&&(a.comment?a.comment+=`
66
+ `+g.comment:a.comment=g.comment);continue}(g.newlineAfterProp||tj.containsNewline(f))&&s(f??m[m.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else g.found?.indent!==r.indent&&s(d,"BAD_INDENT",SC);n.atKey=!0;let k=g.end,C=f?e(n,f,g,s):t(n,k,m,null,g,s);n.schema.compat&&RC.flowIndentCheck(r.indent,f,s),n.atKey=!1,nj.mapIncludes(n,a.items,C)&&s(k,"DUPLICATE_KEY","Map keys must be unique");let R=vC.resolveProps(h??[],{indicator:"map-value-ind",next:p,offset:C.range[2],onError:s,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(d=R.end,R.found){w&&(p?.type==="block-map"&&!R.hasNewline&&s(d,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&g.start<R.found.offset-1024&&s(C.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let $=p?e(n,p,R,s):t(n,d,h,null,R,s);n.schema.compat&&RC.flowIndentCheck(r.indent,p,s),d=$.range[2];let v=new CC.Pair(C,$);n.options.keepSourceTokens&&(v.srcToken=c),a.items.push(v)}else{w&&s(C.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),R.comment&&(C.comment?C.comment+=`
67
+ `+R.comment:C.comment=R.comment);let $=new CC.Pair(C);n.options.keepSourceTokens&&($.srcToken=c),a.items.push($)}}return l&&l<d&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,d,l??d],a}IC.resolveBlockMap=rj});var TC=M(xC=>{"use strict";var sj=cn(),oj=uo(),ij=kf();function aj({composeNode:e,composeEmptyNode:t},n,r,s,o){let i=o?.nodeClass??sj.YAMLSeq,a=new i(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let d=r.offset,l=null;for(let{start:c,value:m}of r.items){let f=oj.resolveProps(c,{indicator:"seq-item-ind",next:m,offset:d,onError:s,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||m)m?.type==="block-seq"?s(f.end,"BAD_INDENT","All sequence items must start at the same column"):s(d,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let h=m?e(n,m,f,s):t(n,f.end,c,null,f,s);n.schema.compat&&ij.flowIndentCheck(r.indent,m,s),d=h.range[2],a.items.push(h)}return a.range=[r.offset,d,l??d],a}xC.resolveBlockSeq=aj});var Kr=M(AC=>{"use strict";function dj(e,t,n,r){let s="";if(e){let o=!1,i="";for(let a of e){let{source:d,type:l}=a;switch(l){case"space":o=!0;break;case"comment":{n&&!o&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let c=d.substring(1)||" ";s?s+=i+c:s=c,i="";break}case"newline":s&&(i+=d),o=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=d.length}}return{comment:s,offset:t}}AC.resolveEnd=dj});var PC=M(NC=>{"use strict";var lj=G(),cj=an(),OC=ln(),mj=cn(),fj=Kr(),MC=uo(),pj=Ja(),uj=Ef(),Cf="Block collections are not allowed within flow collections",vf=e=>e&&(e.type==="block-map"||e.type==="block-seq");function hj({composeNode:e,composeEmptyNode:t},n,r,s,o){let i=r.start.source==="{",a=i?"flow map":"flow sequence",d=o?.nodeClass??(i?OC.YAMLMap:mj.YAMLSeq),l=new d(n.schema);l.flow=!0;let c=n.atRoot;c&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let m=r.offset+r.start.source.length;for(let w=0;w<r.items.length;++w){let k=r.items[w],{start:C,key:R,sep:$,value:v}=k,T=MC.resolveProps(C,{flow:a,indicator:"explicit-key-ind",next:R??$?.[0],offset:m,onError:s,parentIndent:r.indent,startOnNewline:!1});if(!T.found){if(!T.anchor&&!T.tag&&!$&&!v){w===0&&T.comma?s(T.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):w<r.items.length-1&&s(T.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),T.comment&&(l.comment?l.comment+=`
68
+ `+T.comment:l.comment=T.comment),m=T.end;continue}!i&&n.options.strict&&pj.containsNewline(R)&&s(R,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(w===0)T.comma&&s(T.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(T.comma||s(T.start,"MISSING_CHAR",`Missing , between ${a} items`),T.comment){let N="";e:for(let E of C)switch(E.type){case"comma":case"space":break;case"comment":N=E.source.substring(1);break e;default:break e}if(N){let E=l.items[l.items.length-1];lj.isPair(E)&&(E=E.value??E.key),E.comment?E.comment+=`
69
+ `+N:E.comment=N,T.comment=T.comment.substring(N.length+1)}}if(!i&&!$&&!T.found){let N=v?e(n,v,T,s):t(n,T.end,$,null,T,s);l.items.push(N),m=N.range[2],vf(v)&&s(N.range,"BLOCK_IN_FLOW",Cf)}else{n.atKey=!0;let N=T.end,E=R?e(n,R,T,s):t(n,N,C,null,T,s);vf(R)&&s(E.range,"BLOCK_IN_FLOW",Cf),n.atKey=!1;let S=MC.resolveProps($??[],{flow:a,indicator:"map-value-ind",next:v,offset:E.range[2],onError:s,parentIndent:r.indent,startOnNewline:!1});if(S.found){if(!i&&!T.found&&n.options.strict){if($)for(let O of $){if(O===S.found)break;if(O.type==="newline"){s(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}T.start<S.found.offset-1024&&s(S.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else v&&("source"in v&&v.source?.[0]===":"?s(v,"MISSING_CHAR",`Missing space after : in ${a}`):s(S.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let x=v?e(n,v,S,s):S.found?t(n,S.end,$,null,S,s):null;x?vf(v)&&s(x.range,"BLOCK_IN_FLOW",Cf):S.comment&&(E.comment?E.comment+=`
70
+ `+S.comment:E.comment=S.comment);let A=new cj.Pair(E,x);if(n.options.keepSourceTokens&&(A.srcToken=k),i){let O=l;uj.mapIncludes(n,O.items,E)&&s(N,"DUPLICATE_KEY","Map keys must be unique"),O.items.push(A)}else{let O=new OC.YAMLMap(n.schema);O.flow=!0,O.items.push(A);let L=(x??E).range;O.range=[E.range[0],L[1],L[2]],l.items.push(O)}m=x?x.range[2]:S.end}}let f=i?"}":"]",[h,...p]=r.end,g=m;if(h?.source===f)g=h.offset+h.source.length;else{let w=a[0].toUpperCase()+a.substring(1),k=c?`${w} must end with a ${f}`:`${w} in block collection must be sufficiently indented and end with a ${f}`;s(m,c?"MISSING_CHAR":"BAD_INDENT",k),h&&h.source.length!==1&&p.unshift(h)}if(p.length>0){let w=fj.resolveEnd(p,g,n.options.strict,s);w.comment&&(l.comment?l.comment+=`
71
+ `+w.comment:l.comment=w.comment),l.range=[r.offset,g,w.offset]}else l.range=[r.offset,g,g];return l}NC.resolveFlowCollection=hj});var DC=M(LC=>{"use strict";var gj=G(),yj=ge(),wj=ln(),bj=cn(),kj=$C(),Ej=TC(),Cj=PC();function Rf(e,t,n,r,s,o){let i=n.type==="block-map"?kj.resolveBlockMap(e,t,n,r,o):n.type==="block-seq"?Ej.resolveBlockSeq(e,t,n,r,o):Cj.resolveFlowCollection(e,t,n,r,o),a=i.constructor;return s==="!"||s===a.tagName?(i.tag=a.tagName,i):(s&&(i.tag=s),i)}function vj(e,t,n,r,s){let o=r.tag,i=o?t.directives.tagName(o.source,f=>s(o,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=r,p=f&&o?f.offset>o.offset?f:o:f??o;p&&(!h||h.offset<p.offset)&&s(p,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!o||!i||i==="!"||i===wj.YAMLMap.tagName&&a==="map"||i===bj.YAMLSeq.tagName&&a==="seq")return Rf(e,t,n,s,i);let d=t.schema.tags.find(f=>f.tag===i&&f.collection===a);if(!d){let f=t.schema.knownTags[i];if(f?.collection===a)t.schema.tags.push(Object.assign({},f,{default:!1})),d=f;else return f?s(o,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):s(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),Rf(e,t,n,s,i)}let l=Rf(e,t,n,s,i,d),c=d.resolve?.(l,f=>s(o,"TAG_RESOLVE_FAILED",f),t.options)??l,m=gj.isNode(c)?c:new yj.Scalar(c);return m.range=l.range,m.tag=i,d?.format&&(m.format=d.format),m}LC.composeCollection=vj});var If=M(_C=>{"use strict";var Sf=ge();function Rj(e,t,n){let r=t.offset,s=Sj(t,e.options.strict,n);if(!s)return{value:"",type:null,comment:"",range:[r,r,r]};let o=s.mode===">"?Sf.Scalar.BLOCK_FOLDED:Sf.Scalar.BLOCK_LITERAL,i=t.source?Ij(t.source):[],a=i.length;for(let g=i.length-1;g>=0;--g){let w=i[g][1];if(w===""||w==="\r")a=g;else break}if(a===0){let g=s.chomp==="+"&&i.length>0?`
72
+ `.repeat(Math.max(1,i.length-1)):"",w=r+s.length;return t.source&&(w+=t.source.length),{value:g,type:o,comment:s.comment,range:[r,w,w]}}let d=t.indent+s.indent,l=t.offset+s.length,c=0;for(let g=0;g<a;++g){let[w,k]=i[g];if(k===""||k==="\r")s.indent===0&&w.length>d&&(d=w.length);else{w.length<d&&n(l+w.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(d=w.length),c=g,d===0&&!e.atRoot&&n(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=w.length+k.length+1}for(let g=i.length-1;g>=a;--g)i[g][0].length>d&&(a=g+1);let m="",f="",h=!1;for(let g=0;g<c;++g)m+=i[g][0].slice(d)+`
73
+ `;for(let g=c;g<a;++g){let[w,k]=i[g];l+=w.length+k.length+1;let C=k[k.length-1]==="\r";if(C&&(k=k.slice(0,-1)),k&&w.length<d){let $=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;n(l-k.length-(C?2:1),"BAD_INDENT",$),w=""}o===Sf.Scalar.BLOCK_LITERAL?(m+=f+w.slice(d)+k,f=`
74
+ `):w.length>d||k[0]===" "?(f===" "?f=`
75
+ `:!h&&f===`
76
+ `&&(f=`
77
+
78
+ `),m+=f+w.slice(d)+k,f=`
79
+ `,h=!0):k===""?f===`
80
+ `?m+=`
81
+ `:f=`
82
+ `:(m+=f+k,f=" ",h=!1)}switch(s.chomp){case"-":break;case"+":for(let g=a;g<i.length;++g)m+=`
83
+ `+i[g][0].slice(d);m[m.length-1]!==`
84
+ `&&(m+=`
85
+ `);break;default:m+=`
86
+ `}let p=r+s.length+t.source.length;return{value:m,type:o,comment:s.comment,range:[r,p,p]}}function Sj({offset:e,props:t},n,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=t[0],o=s[0],i=0,a="",d=-1;for(let f=1;f<s.length;++f){let h=s[f];if(!a&&(h==="-"||h==="+"))a=h;else{let p=Number(h);!i&&p?i=p:d===-1&&(d=e+f)}}d!==-1&&r(d,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,c="",m=s.length;for(let f=1;f<t.length;++f){let h=t[f];switch(h.type){case"space":l=!0;case"newline":m+=h.source.length;break;case"comment":n&&!l&&r(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),m+=h.source.length,c=h.source.substring(1);break;case"error":r(h,"UNEXPECTED_TOKEN",h.message),m+=h.source.length;break;default:{let p=`Unexpected token in block scalar header: ${h.type}`;r(h,"UNEXPECTED_TOKEN",p);let g=h.source;g&&typeof g=="string"&&(m+=g.length)}}}return{mode:o,indent:i,chomp:a,comment:c,length:m}}function Ij(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),o=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let i=1;i<t.length;i+=2)o.push([t[i],t[i+1]]);return o}_C.resolveBlockScalar=Rj});var xf=M(FC=>{"use strict";var $f=ge(),$j=Kr();function xj(e,t,n){let{offset:r,type:s,source:o,end:i}=e,a,d,l=(f,h,p)=>n(r+f,h,p);switch(s){case"scalar":a=$f.Scalar.PLAIN,d=Tj(o,l);break;case"single-quoted-scalar":a=$f.Scalar.QUOTE_SINGLE,d=Aj(o,l);break;case"double-quoted-scalar":a=$f.Scalar.QUOTE_DOUBLE,d=Oj(o,l);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[r,r+o.length,r+o.length]}}let c=r+o.length,m=$j.resolveEnd(i,c,t,n);return{value:d,type:a,comment:m.comment,range:[r,c,m.offset]}}function Tj(e,t){let n="";switch(e[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}return n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),jC(e)}function Aj(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),jC(e.slice(1,-1)).replace(/''/g,"'")}function jC(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,s;try{r=new RegExp("(?<![ ])[ ]+$"),s=new RegExp("^[ ]+|(?<![ ])[ ]+$","g")}catch{r=/[ \t]+$/,s=/^[ \t]+|[ \t]+$/g}let o=n[1].replace(r,""),i=" ",a=t.lastIndex;for(;n=t.exec(e);){let l=n[1].replace(s,"");l===""?i===`
87
+ `?o+=i:i=`
88
+ `:(o+=i+l,i=" "),a=t.lastIndex}let d=/[ \t]*(.*)/sy;return d.lastIndex=a,n=d.exec(e),o+i+(n?.[1]??"")}function Oj(e,t){let n="";for(let r=1;r<e.length-1;++r){let s=e[r];if(!(s==="\r"&&e[r+1]===`
89
+ `))if(s===`
90
+ `){let{fold:o,offset:i}=Mj(e,r);n+=o,r=i}else if(s==="\\"){let o=e[++r],i=Nj[o];if(i)n+=i;else if(o===`
91
+ `)for(o=e[r+1];o===" "||o===" ";)o=e[++r+1];else if(o==="\r"&&e[r+1]===`
92
+ `)for(o=e[++r+1];o===" "||o===" ";)o=e[++r+1];else if(o==="x"||o==="u"||o==="U"){let a=o==="x"?2:o==="u"?4:8;n+=Pj(e,r+1,a,t),r+=a}else{let a=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(s===" "||s===" "){let o=r,i=e[r+1];for(;i===" "||i===" ";)i=e[++r+1];i!==`
93
+ `&&!(i==="\r"&&e[r+2]===`
94
+ `)&&(n+=r>o?e.slice(o,r+1):s)}else n+=s}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function Mj(e,t){let n="",r=e[t+1];for(;(r===" "||r===" "||r===`
95
+ `||r==="\r")&&!(r==="\r"&&e[t+2]!==`
96
+ `);)r===`
97
+ `&&(n+=`
98
+ `),t+=1,r=e[t+1];return n||(n=" "),{fold:n,offset:t}}var Nj={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
99
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Pj(e,t,n,r){let s=e.substr(t,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;try{return String.fromCodePoint(i)}catch{let a=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}FC.resolveFlowScalar=xj});var BC=M(WC=>{"use strict";var Vn=G(),qC=ge(),Lj=If(),Dj=xf();function _j(e,t,n,r){let{value:s,type:o,comment:i,range:a}=t.type==="block-scalar"?Lj.resolveBlockScalar(e,t,r):Dj.resolveFlowScalar(t,e.options.strict,r),d=n?e.directives.tagName(n.source,m=>r(n,"TAG_RESOLVE_FAILED",m)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Vn.SCALAR]:d?l=jj(e.schema,s,d,n,r):t.type==="scalar"?l=Fj(e,s,t,r):l=e.schema[Vn.SCALAR];let c;try{let m=l.resolve(s,f=>r(n??t,"TAG_RESOLVE_FAILED",f),e.options);c=Vn.isScalar(m)?m:new qC.Scalar(m)}catch(m){let f=m instanceof Error?m.message:String(m);r(n??t,"TAG_RESOLVE_FAILED",f),c=new qC.Scalar(s)}return c.range=a,c.source=s,o&&(c.type=o),d&&(c.tag=d),l.format&&(c.format=l.format),i&&(c.comment=i),c}function jj(e,t,n,r,s){if(n==="!")return e[Vn.SCALAR];let o=[];for(let a of e.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)o.push(a);else return a;for(let a of o)if(a.test?.test(t))return a;let i=e.knownTags[n];return i&&!i.collection?(e.tags.push(Object.assign({},i,{default:!1,test:void 0})),i):(s(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[Vn.SCALAR])}function Fj({atKey:e,directives:t,schema:n},r,s,o){let i=n.tags.find(a=>(a.default===!0||e&&a.default==="key")&&a.test?.test(r))||n[Vn.SCALAR];if(n.compat){let a=n.compat.find(d=>d.default&&d.test?.test(r))??n[Vn.SCALAR];if(i.tag!==a.tag){let d=t.tagString(i.tag),l=t.tagString(a.tag),c=`Value may be parsed as either ${d} or ${l}`;o(s,"TAG_RESOLVE_FAILED",c,!0)}}return i}WC.composeScalar=_j});var UC=M(HC=>{"use strict";function qj(e,t,n){if(t){n??(n=t.length);for(let r=n-1;r>=0;--r){let s=t[r];switch(s.type){case"space":case"comment":case"newline":e-=s.source.length;continue}for(s=t[++r];s?.type==="space";)e+=s.source.length,s=t[++r];break}}return e}HC.emptyScalarPosition=qj});var KC=M(Af=>{"use strict";var Wj=Ks(),Bj=G(),Hj=DC(),VC=BC(),Uj=Kr(),Vj=UC(),Gj={composeNode:GC,composeEmptyNode:Tf};function GC(e,t,n,r){let s=e.atKey,{spaceBefore:o,comment:i,anchor:a,tag:d}=n,l,c=!0;switch(t.type){case"alias":l=Kj(e,t,r),(a||d)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=VC.composeScalar(e,t,d,r),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Hj.composeCollection(Gj,e,t,n,r),a&&(l.anchor=a.source.substring(1))}catch(m){let f=m instanceof Error?m.message:String(m);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let m=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",m),c=!1}}return l??(l=Tf(e,t.offset,void 0,null,n,r)),a&&l.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&e.options.stringKeys&&(!Bj.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(d??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(l.spaceBefore=!0),i&&(t.type==="scalar"&&t.source===""?l.comment=i:l.commentBefore=i),e.options.keepSourceTokens&&c&&(l.srcToken=t),l}function Tf(e,t,n,r,{spaceBefore:s,comment:o,anchor:i,tag:a,end:d},l){let c={type:"scalar",offset:Vj.emptyScalarPosition(t,n,r),indent:-1,source:""},m=VC.composeScalar(e,c,a,l);return i&&(m.anchor=i.source.substring(1),m.anchor===""&&l(i,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(m.spaceBefore=!0),o&&(m.comment=o,m.range[2]=d),m}function Kj({options:e},{offset:t,source:n,end:r},s){let o=new Wj.Alias(n.substring(1));o.source===""&&s(t,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&s(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=t+n.length,a=Uj.resolveEnd(r,i,e.strict,s);return o.range=[t,i,a.offset],a.comment&&(o.comment=a.comment),o}Af.composeEmptyNode=Tf;Af.composeNode=GC});var JC=M(zC=>{"use strict";var Yj=co(),YC=KC(),zj=Kr(),Jj=uo();function Xj(e,t,{offset:n,start:r,value:s,end:o},i){let a=Object.assign({_directives:t},e),d=new Yj.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:d.directives,options:d.options,schema:d.schema},c=Jj.resolveProps(r,{indicator:"doc-start",next:s??o?.[0],offset:n,onError:i,parentIndent:0,startOnNewline:!0});c.found&&(d.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!c.hasNewline&&i(c.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),d.contents=s?YC.composeNode(l,s,c,i):YC.composeEmptyNode(l,c.end,r,null,c,i);let m=d.contents.range[2],f=zj.resolveEnd(o,m,!1,i);return f.comment&&(d.comment=f.comment),d.range=[n,m,f.offset],d}zC.composeDoc=Xj});var Mf=M(ZC=>{"use strict";var Qj=qo("process"),Zj=gm(),e1=co(),ho=po(),XC=G(),t1=JC(),n1=Kr();function go(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n=="string"?n.length:1)]}function QC(e){let t="",n=!1,r=!1;for(let s=0;s<e.length;++s){let o=e[s];switch(o[0]){case"#":t+=(t===""?"":r?`
100
+
101
+ `:`
102
+ `)+(o.substring(1)||" "),n=!0,r=!1;break;case"%":e[s+1]?.[0]!=="#"&&(s+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var Of=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,s,o)=>{let i=go(n);o?this.warnings.push(new ho.YAMLWarning(i,r,s)):this.errors.push(new ho.YAMLParseError(i,r,s))},this.directives=new Zj.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:r,afterEmptyLine:s}=QC(this.prelude);if(r){let o=t.contents;if(n)t.comment=t.comment?`${t.comment}
103
+ ${r}`:r;else if(s||t.directives.docStart||!o)t.commentBefore=r;else if(XC.isCollection(o)&&!o.flow&&o.items.length>0){let i=o.items[0];XC.isPair(i)&&(i=i.key);let a=i.commentBefore;i.commentBefore=a?`${r}
104
+ ${a}`:r}else{let i=o.commentBefore;o.commentBefore=i?`${r}
105
+ ${i}`:r}}if(n){for(let o=0;o<this.errors.length;++o)t.errors.push(this.errors[o]);for(let o=0;o<this.warnings.length;++o)t.warnings.push(this.warnings[o])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:QC(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,n=!1,r=-1){for(let s of t)yield*this.next(s);yield*this.end(n,r)}*next(t){switch(Qj.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(n,r,s)=>{let o=go(t);o[0]+=n,this.onError(o,"BAD_DIRECTIVE",r,s)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=t1.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let n=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new ho.YAMLParseError(go(t),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new ho.YAMLParseError(go(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=n1.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
106
+ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new ho.YAMLParseError(go(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),s=new e1.Document(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),s.range=[0,n,n],this.decorate(s,!1),yield s}}};ZC.Composer=Of});var nv=M(Xa=>{"use strict";var r1=If(),s1=xf(),o1=po(),ev=Qs();function i1(e,t=!0,n){if(e){let r=(s,o,i)=>{let a=typeof s=="number"?s:Array.isArray(s)?s[0]:s.offset;if(n)n(a,o,i);else throw new o1.YAMLParseError([a,a+1],o,i)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return s1.resolveFlowScalar(e,t,r);case"block-scalar":return r1.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function a1(e,t){let{implicitKey:n=!1,indent:r,inFlow:s=!1,offset:o=-1,type:i="PLAIN"}=t,a=ev.stringifyString({type:i,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}}),d=t.end??[{type:"newline",offset:-1,indent:r,source:`
107
+ `}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
108
+ `),c=a.substring(0,l),m=a.substring(l+1)+`
109
+ `,f=[{type:"block-scalar-header",offset:o,indent:r,source:c}];return tv(f,d)||f.push({type:"newline",offset:-1,indent:r,source:`
110
+ `}),{type:"block-scalar",offset:o,indent:r,props:f,source:m}}case'"':return{type:"double-quoted-scalar",offset:o,indent:r,source:a,end:d};case"'":return{type:"single-quoted-scalar",offset:o,indent:r,source:a,end:d};default:return{type:"scalar",offset:o,indent:r,source:a,end:d}}}function d1(e,t,n={}){let{afterKey:r=!1,implicitKey:s=!1,inFlow:o=!1,type:i}=n,a="indent"in e?e.indent:null;if(r&&typeof a=="number"&&(a+=2),!i)switch(e.type){case"single-quoted-scalar":i="QUOTE_SINGLE";break;case"double-quoted-scalar":i="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:i="PLAIN"}let d=ev.stringifyString({type:i,value:t},{implicitKey:s||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(d[0]){case"|":case">":l1(e,d);break;case'"':Nf(e,d,"double-quoted-scalar");break;case"'":Nf(e,d,"single-quoted-scalar");break;default:Nf(e,d,"scalar")}}function l1(e,t){let n=t.indexOf(`
111
+ `),r=t.substring(0,n),s=t.substring(n+1)+`
112
+ `;if(e.type==="block-scalar"){let o=e.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=r,e.source=s}else{let{offset:o}=e,i="indent"in e?e.indent:-1,a=[{type:"block-scalar-header",offset:o,indent:i,source:r}];tv(a,"end"in e?e.end:void 0)||a.push({type:"newline",offset:-1,indent:i,source:`
113
+ `});for(let d of Object.keys(e))d!=="type"&&d!=="offset"&&delete e[d];Object.assign(e,{type:"block-scalar",indent:i,props:a,source:s})}}function tv(e,t){if(t)for(let n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function Nf(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),s=t.length;e.props[0].type==="block-scalar-header"&&(s-=e.props[0].source.length);for(let o of r)o.offset+=s;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case"block-map":case"block-seq":{let s={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
114
+ `};delete e.items,Object.assign(e,{type:n,source:t,end:[s]});break}default:{let r="indent"in e?e.indent:-1,s="end"in e&&Array.isArray(e.end)?e.end.filter(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(e))o!=="type"&&o!=="offset"&&delete e[o];Object.assign(e,{type:n,indent:r,source:t,end:s})}}}Xa.createScalarToken=a1;Xa.resolveAsScalar=i1;Xa.setScalarValue=d1});var sv=M(rv=>{"use strict";var c1=e=>"type"in e?Za(e):Qa(e);function Za(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=Za(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=Qa(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=Qa(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=Qa(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function Qa({start:e,key:t,sep:n,value:r}){let s="";for(let o of e)s+=o.source;if(t&&(s+=Za(t)),n)for(let o of n)s+=o.source;return r&&(s+=Za(r)),s}rv.stringify=c1});var dv=M(av=>{"use strict";var Pf=Symbol("break visit"),m1=Symbol("skip children"),ov=Symbol("remove item");function Gn(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),iv(Object.freeze([]),e,t)}Gn.BREAK=Pf;Gn.SKIP=m1;Gn.REMOVE=ov;Gn.itemAtPath=(e,t)=>{let n=e;for(let[r,s]of t){let o=n?.[r];if(o&&"items"in o)n=o.items[s];else return}return n};Gn.parentCollection=(e,t)=>{let n=Gn.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],s=n?.[r];if(s&&"items"in s)return s;throw new Error("Parent collection not found")};function iv(e,t,n){let r=n(t,e);if(typeof r=="symbol")return r;for(let s of["key","value"]){let o=t[s];if(o&&"items"in o){for(let i=0;i<o.items.length;++i){let a=iv(Object.freeze(e.concat([[s,i]])),o.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Pf)return Pf;a===ov&&(o.items.splice(i,1),i-=1)}}typeof r=="function"&&s==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}av.visit=Gn});var ed=M(_e=>{"use strict";var Lf=nv(),f1=sv(),p1=dv(),Df="\uFEFF",_f="",jf="",Ff="",u1=e=>!!e&&"items"in e,h1=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function g1(e){switch(e){case Df:return"<BOM>";case _f:return"<DOC>";case jf:return"<FLOW_END>";case Ff:return"<SCALAR>";default:return JSON.stringify(e)}}function y1(e){switch(e){case Df:return"byte-order-mark";case _f:return"doc-mode";case jf:return"flow-error-end";case Ff:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
115
+ `:case`\r
116
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}_e.createScalarToken=Lf.createScalarToken;_e.resolveAsScalar=Lf.resolveAsScalar;_e.setScalarValue=Lf.setScalarValue;_e.stringify=f1.stringify;_e.visit=p1.visit;_e.BOM=Df;_e.DOCUMENT=_f;_e.FLOW_END=jf;_e.SCALAR=Ff;_e.isCollection=u1;_e.isScalar=h1;_e.prettyToken=g1;_e.tokenType=y1});var Bf=M(cv=>{"use strict";var yo=ed();function rt(e){switch(e){case void 0:case" ":case`
117
+ `:case"\r":case" ":return!0;default:return!1}}var lv=new Set("0123456789ABCDEFabcdef"),w1=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),td=new Set(",[]{}"),b1=new Set(` ,[]{}
118
+ \r `),qf=e=>!e||b1.has(e),Wf=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,n=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,n=this.buffer[t];for(;n===" "||n===" ";)n=this.buffer[++t];return!n||n==="#"||n===`
119
+ `?!0:n==="\r"?this.buffer[t+1]===`
120
+ `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let n=this.buffer[t];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+t];if(n==="\r"){let s=this.buffer[r+t+1];if(s===`
121
+ `||!s&&!this.atEnd)return t+r+1}return n===`
122
+ `||r>=this.indentNext||!n&&!this.atEnd?t+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&rt(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
123
+ `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===yo.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let n=t.length,r=t.indexOf("#");for(;r!==-1;){let o=t[r-1];if(o===" "||o===" "){n=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let o=t[n-1];if(o===" "||o===" ")n-=1;else break}let s=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-s),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-n),yield*this.pushNewline(),"stream"}return yield yo.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&rt(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!rt(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&rt(n)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(t[n]){case"#":yield*this.pushCount(t.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(qf),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,n,r=-1;do t=yield*this.pushNewline(),t>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(t+n>0);let s=this.getLine();if(s===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&s[0]!=="#"||r===0&&(s.startsWith("---")||s.startsWith("..."))&&rt(s[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield yo.FLOW_END,yield*this.parseLineStart();let o=0;for(;s[o]===",";)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),s[o]){case void 0:return"flow";case"#":return yield*this.pushCount(s.length-o),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(qf),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||rt(i)||i===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),n=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let o=0;for(;this.buffer[n-1-o]==="\\";)o+=1;if(o%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),s=r.indexOf(`
124
+ `,this.pos);if(s!==-1){for(;s!==-1;){let o=this.continueScalar(s+1);if(o===-1)break;s=r.indexOf(`
125
+ `,o)}s!==-1&&(n=s-(r[s-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let n=this.buffer[++t];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>rt(n)||n==="#")}*parseBlockScalar(){let t=this.pos-1,n=0,r;e:for(let o=this.pos;r=this.buffer[o];++o)switch(r){case" ":n+=1;break;case`
126
+ `:t=o,n=0;break;case"\r":{let i=this.buffer[o+1];if(!i&&!this.atEnd)return this.setNext("block-scalar");if(i===`
127
+ `)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let o=this.continueScalar(t+1);if(o===-1)break;t=this.buffer.indexOf(`
128
+ `,o)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let s=t+1;for(r=this.buffer[s];r===" ";)r=this.buffer[++s];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
129
+ `;)r=this.buffer[++s];t=s-1}else if(!this.blockScalarKeep)do{let o=t-1,i=this.buffer[o];i==="\r"&&(i=this.buffer[--o]);let a=o;for(;i===" ";)i=this.buffer[--o];if(i===`
130
+ `&&o>=this.pos&&o+1+n>a)t=o;else break}while(!0);return yield yo.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,n=this.pos-1,r=this.pos-1,s;for(;s=this.buffer[++r];)if(s===":"){let o=this.buffer[r+1];if(rt(o)||t&&td.has(o))break;n=r}else if(rt(s)){let o=this.buffer[r+1];if(s==="\r"&&(o===`
131
+ `?(r+=1,s=`
132
+ `,o=this.buffer[r+1]):n=r),o==="#"||t&&td.has(o))break;if(s===`
133
+ `){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(t&&td.has(s))break;n=r}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield yo.SCALAR,yield*this.pushToIndex(n+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,n){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(qf),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(rt(r)||n&&td.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,n=this.buffer[t];for(;!rt(n)&&n!==">";)n=this.buffer[++t];return yield*this.pushToIndex(n===">"?t+1:t,!1)}else{let t=this.pos+1,n=this.buffer[t];for(;n;)if(w1.has(n))n=this.buffer[++t];else if(n==="%"&&lv.has(this.buffer[t+1])&&lv.has(this.buffer[t+2]))n=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
134
+ `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
135
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||t&&r===" ");let s=n-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=n),s}*pushUntil(t){let n=this.pos,r=this.buffer[n];for(;!t(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};cv.Lexer=Wf});var Uf=M(mv=>{"use strict";var Hf=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let n=0,r=this.lineStarts.length;for(;n<r;){let o=n+r>>1;this.lineStarts[o]<t?n=o+1:r=o}if(this.lineStarts[n]===t)return{line:n+1,col:1};if(n===0)return{line:0,col:t};let s=this.lineStarts[n-1];return{line:n,col:t-s+1}}}};mv.LineCounter=Hf});var Gf=M(gv=>{"use strict";var k1=qo("process"),fv=ed(),E1=Bf();function mn(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function pv(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function hv(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function nd(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Yr(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function rd(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function uv(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!mn(t.start,"explicit-key-ind")&&!mn(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,hv(t.value)?t.value.end?rd(t.value.end,t.sep):t.value.end=t.sep:rd(t.start,t.sep),delete t.sep)}var Vf=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new E1.Lexer,this.onNewLine=t}*parse(t,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,n))yield*this.next(r);n||(yield*this.end())}*next(t){if(this.source=t,k1.env.LOG_TOKENS&&console.log("|",fv.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let n=fv.tokenType(t);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let n=t??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&uv(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let s=r.items[r.items.length-1];if(s.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(s.sep)s.value=n;else{Object.assign(s,{key:n,sep:[]}),this.onKeyLine=!s.explicitKey;return}break}case"block-seq":{let s=r.items[r.items.length-1];s.value?r.items.push({start:[],value:n}):s.value=n;break}case"flow-collection":{let s=r.items[r.items.length-1];!s||s.value?r.items.push({start:[],key:n,sep:[]}):s.sep?s.value=n:Object.assign(s,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let s=n.items[n.items.length-1];s&&!s.sep&&!s.value&&s.start.length>0&&pv(s.start)===-1&&(n.indent===0||s.start.every(o=>o.type!=="comment"||o.indent<n.indent))&&(r.type==="document"?r.end=s.start:r.items.push({start:s.start}),n.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{pv(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let n=nd(this.peek(2)),r=Yr(n),s;t.end?(s=t.end,s.push(this.sourceToken),delete t.end):s=[this.sourceToken];let o={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=o}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`
136
+ `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
137
+ `,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,t.indent)){let s=t.items[t.items.length-2]?.value?.end;if(Array.isArray(s)){rd(s,n.start),s.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,s=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",o=[];if(s&&n.sep&&!n.value){let i=[];for(let a=0;a<n.sep.length;++a){let d=n.sep[a];switch(d.type){case"newline":i.push(a);break;case"space":break;case"comment":d.indent>t.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(o=n.sep.splice(i[1]))}switch(this.type){case"anchor":case"tag":s||n.value?(o.push(this.sourceToken),t.items.push({start:o}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):s||n.value?(o.push(this.sourceToken),t.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(mn(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(hv(n.key)&&!mn(n.sep,"newline")){let i=Yr(n.start),a=n.key,d=n.sep;d.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:a,sep:d}]})}else o.length>0?n.sep=n.sep.concat(o,this.sourceToken):n.sep.push(this.sourceToken);else if(mn(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=Yr(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||s?t.items.push({start:o,key:null,sep:[this.sourceToken]}):mn(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);s||n.value?(t.items.push({start:o,key:i,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(i):(Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(t);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!mn(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:o});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,t.indent)){let s=t.items[t.items.length-2]?.value?.end;if(Array.isArray(s)){rd(s,n.start),s.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=t.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;n.value||mn(n.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let n=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?t.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);!n||n.value?t.items.push({start:[],key:s,sep:[]}):n.sep?this.stack.push(s):Object.assign(n,{key:s,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let s=nd(r),o=Yr(s);uv(t);let i=t.end.splice(1,t.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:o,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let n=this.source.indexOf(`
138
+ `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
139
+ `,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=nd(t),r=Yr(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=nd(t),r=Yr(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};gv.Parser=Vf});var Ev=M(bo=>{"use strict";var yv=Mf(),C1=co(),wo=po(),v1=Tm(),R1=G(),S1=Uf(),wv=Gf();function bv(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new S1.LineCounter||null,prettyErrors:t}}function I1(e,t={}){let{lineCounter:n,prettyErrors:r}=bv(t),s=new wv.Parser(n?.addNewLine),o=new yv.Composer(t),i=Array.from(o.compose(s.parse(e)));if(r&&n)for(let a of i)a.errors.forEach(wo.prettifyError(e,n)),a.warnings.forEach(wo.prettifyError(e,n));return i.length>0?i:Object.assign([],{empty:!0},o.streamInfo())}function kv(e,t={}){let{lineCounter:n,prettyErrors:r}=bv(t),s=new wv.Parser(n?.addNewLine),o=new yv.Composer(t),i=null;for(let a of o.compose(s.parse(e),!0,e.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new wo.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(wo.prettifyError(e,n)),i.warnings.forEach(wo.prettifyError(e,n))),i}function $1(e,t,n){let r;typeof t=="function"?r=t:n===void 0&&t&&typeof t=="object"&&(n=t);let s=kv(e,n);if(!s)return null;if(s.warnings.forEach(o=>v1.warn(s.options.logLevel,o)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:r},n))}function x1(e,t,n){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n=="string"&&(n=n.length),typeof n=="number"){let s=Math.round(n);n=s<1?void 0:s>8?{indent:8}:{indent:s}}if(e===void 0){let{keepUndefined:s}=n??t??{};if(!s)return}return R1.isDocument(e)&&!r?e.toString(n):new C1.Document(e,r,n).toString(n)}bo.parse=$1;bo.parseAllDocuments=I1;bo.parseDocument=kv;bo.stringify=x1});var od=M(Q=>{"use strict";var T1=Mf(),A1=co(),O1=ff(),Kf=po(),M1=Ks(),fn=G(),N1=an(),P1=ge(),L1=ln(),D1=cn(),_1=ed(),j1=Bf(),F1=Uf(),q1=Gf(),sd=Ev(),Cv=Hs();Q.Composer=T1.Composer;Q.Document=A1.Document;Q.Schema=O1.Schema;Q.YAMLError=Kf.YAMLError;Q.YAMLParseError=Kf.YAMLParseError;Q.YAMLWarning=Kf.YAMLWarning;Q.Alias=M1.Alias;Q.isAlias=fn.isAlias;Q.isCollection=fn.isCollection;Q.isDocument=fn.isDocument;Q.isMap=fn.isMap;Q.isNode=fn.isNode;Q.isPair=fn.isPair;Q.isScalar=fn.isScalar;Q.isSeq=fn.isSeq;Q.Pair=N1.Pair;Q.Scalar=P1.Scalar;Q.YAMLMap=L1.YAMLMap;Q.YAMLSeq=D1.YAMLSeq;Q.CST=_1;Q.Lexer=j1.Lexer;Q.LineCounter=F1.LineCounter;Q.Parser=q1.Parser;Q.parse=sd.parse;Q.parseAllDocuments=sd.parseAllDocuments;Q.parseDocument=sd.parseDocument;Q.stringify=sd.stringify;Q.visit=Cv.visit;Q.visitAsync=Cv.visitAsync});var b={Success:0,Failure:1,Usage:2,NotFound:3,Validation:4,Conflict:5,NeedsHuman:6,Transient:7},eu="timed-out",Fe=e=>e instanceof Error?e.message:String(e),u=class extends Error{exitCode;reason;hint;type;requestId;details;hosted;report;constructor(t,n={}){let r=typeof n=="number"?{exitCode:n}:n;super(r.hint?`${t} ${r.hint}`:t),this.name="CliError",this.exitCode=r.exitCode??b.Failure,this.reason=t,this.hint=r.hint,this.type=r.type,this.requestId=r.requestId,this.details=r.details??{},this.hosted=r.hosted,this.report=r.report}},I=(e,t="modeldesk --help",n)=>new u(e,{exitCode:b.Usage,hint:`Run '${t}'.`,hosted:n});var HI=/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,pe=e=>e.replace(HI,""),y=e=>e.replace(/\s+/g," ").trim(),P=(e,t)=>`${e} ${t}${e===1?"":"s"}`;import{createHash as UI,randomUUID as VI}from"node:crypto";var Qd=200,GI=64,es=e=>e.session?.trim().replace(/[^A-Za-z0-9._-]+/g,"-").slice(0,GI)||void 0,Zn=e=>{let t=es(e);return[e.surface,...t?[t]:[],VI()].join("-")},KI=e=>{let t=UI("sha256").update(e).digest("hex");return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-8${t.slice(17,20)}-${t.slice(20,32)}`},Wo=(e,t)=>{let n=es(e);return[e.surface,...n?[n]:[],KI(t)].join("-")},En=(e,t,n)=>n!==void 0&&n.total>1?Wo(e,`${t}:${n.number}`):qt(t)===e.surface&&nu.test(t)&&ts(t,e)?t:Wo(e,t),YI=["web","cli","mcp"],qt=e=>YI.find(t=>e?.startsWith(`${t}-`))??"api",tu=["cli","mcp"],zI=36,nu=/-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Zd=e=>{if(e===void 0||!nu.test(e))return;let t=e.slice(0,-zI-1),n=tu.find(r=>t.startsWith(`${r}-`));return n&&t.slice(n.length+1)||void 0},ts=(e,t)=>{if(!tu.includes(qt(e)))return!1;let n=es(t);return n===void 0||Zd(e)===n};var er={read:{gate:"none",ownChangesOnly:!1,site:"dispatcher"},local:{gate:"none",ownChangesOnly:!1,site:"dispatcher"},stage:{gate:"none",ownChangesOnly:!1,site:"dispatcher"},create:{gate:"none",ownChangesOnly:!1,site:"dispatcher"},unstage:{gate:"none",ownChangesOnly:!0,site:"dispatcher"},"land-draft":{gate:"allow-commit",ownChangesOnly:!0,site:"landing"},"land-direct":{gate:"allow-commit",ownChangesOnly:!1,site:"dispatcher"},destroy:{gate:"refuse",ownChangesOnly:!1,site:"dispatcher"}},Wt="agent/",JI=e=>"name"in e&&e.name.toLowerCase().startsWith(Wt),ru=(e,t,n,r)=>{if(r)return"read";if(t===void 0)return e;let s=n[t.flag];return s===!0||Array.isArray(s)&&s.length>0?t.to:e},XI={"land-direct":"changes committed state with no draft to review",destroy:"destroys content, other users' work included"},el="agent-policy",su=(e,t)=>{let{gate:n}=er[t];return n==="none"||n==="allow-commit"&&e.allowCommit},tl=e=>`${e.wording.askAPerson} ${e.howToGrant}`,nl=(e,t,n,r,s={})=>new u(`${n}, so it is left to a person while an agent (${e.host}) ${e.wording.works}; nothing was changed.`,{exitCode:b.NeedsHuman,type:el,hint:r,details:{effect:t,gate:er[t].gate,...s}}),ou=({agent:e},t,n)=>{if(!(e===void 0||er[t].site==="landing"||su(e,t)))throw nl(e,t,`'${n}' ${XI[t]}`,er[t].gate==="allow-commit"?tl(e):e.wording.askAPerson)},tr=(e,t,n,r)=>{let{agent:s,effect:o}=e;if(s===void 0||er[o].site!=="landing"||JI(r)||su(s,o))return;let i=y(n.name);throw"name"in r?nl(s,o,`'${t}' lands your draft of ${i} on ${y(r.name)}, which is not an agent's own branch (${Wt}<topic>)`,`${tl(s)} Or commit on a branch of your own: ${s.wording.branchLane(n.id)}, then stage and commit there; a person reviews and merges it in the app.`,{branch:{id:r.id,name:r.name}}):nl(s,o,`'${t}' lands your draft of ${n.kind} ${i} on its one branch, which no agent owns`,tl(s),{branch:{id:r.id}})},QI=e=>({id:e.id,...e.requestId?{requestId:e.requestId}:{},surface:qt(e.requestId),...e.message?{message:e.message}:{}}),qe=async(e,t,n,r)=>{let{agent:s}=e;if(s===void 0||!er[e.effect].ownChangesOnly||r.anySurface||n.changeCount===0)return;let i=`Ask the person you work for to review the draft ${t.url?`in the app at ${t.url}`:"in the app"}; ${s.wording.noOverride??r.override}`,a=t.url?{url:t.url}:{};if(t.changes===void 0)throw new u(`${r.action} is left to a person while an agent (${s.host}) ${s.wording.works}, since a dataset's staged changes cannot be listed to tell whose they are. Nothing was changed.`,{exitCode:b.NeedsHuman,type:el,hint:i,details:a});let{scope:d}=r,l=await t.changes(n.id,d.kind==="last"?1:void 0),m=(d.kind==="ids"?l.filter(g=>d.ids.includes(g.id)):l).filter(g=>!ts(g.requestId,e.origin));if(m.length===0)return;let f="outside this agent session (in the app, by a script, or by another session)",h=m.length===1?"was":"were",p=d.kind==="last"?`the last staged change was made ${f}`:`${P(m.length,"staged change")} of the draft ${h} made ${f}`;throw new u(`${r.action} is left to a person while an agent (${s.host}) ${s.wording.works}: ${p}. Nothing was changed.`,{exitCode:b.NeedsHuman,type:el,hint:i,details:{...a,changes:m.map(QI)}})},nr={"any-surface":{type:"boolean",description:"Under an agent host, also act on changes staged outside an agent session (in the app, or by a script), which the CLI otherwise leaves to a person."}};var Et={host:{env:"MODELDESK_HOST"},model:{env:"MODELDESK_MODEL"},stack:{env:"MODELDESK_STACK"},template:{env:"MODELDESK_TEMPLATE"},version:{env:"MODELDESK_VERSION"}};var ns="modeldesk.io",B={host:Et.host.env,model:Et.model.env,stack:Et.stack.env,template:Et.template.env,version:Et.version.env,clientId:"MODELDESK_CLIENT_ID",clientSecret:"MODELDESK_CLIENT_SECRET",apiKey:"MODELDESK_API_KEY",agentSession:"MODELDESK_AGENT_SESSION",allowCommit:"MODELDESK_ALLOW_COMMIT"},rs=e=>e!==void 0&&e!==""&&e!=="0",ZI=(...e)=>e.find(t=>t!==void 0&&t!==""),ss=(e,t,n)=>{let r={};for(let[s,{env:o}]of Object.entries(Et))r[s]=ZI(e[s],t[o],n[s]);return{...r,host:r.host??ns}};var e$=`A person who trusts this agent to commit unattended sets ${B.allowCommit}=1.`,Bo={works:"runs the CLI",askAPerson:"Ask them to run it from a plain shell, or to do it in the app.",grant:`${B.allowCommit}=1`,branchLane:e=>`'modeldesk branch create ${e} ${Wt}<topic> --open'`,afterLanding:e=>`Unaddressed invocations now default to main. Address ${e}, or run: modeldesk draft open ${e}`,allRows:e=>`pass --limit ${e} for all of them.`},rr=e=>e.agent?.wording??Bo,t$=[{variable:"CLAUDECODE",host:()=>"claude-code"},{variable:"CLAUDE_CODE_CHILD_SESSION",host:()=>"claude-code"},{variable:"CURSOR_AGENT",host:()=>"cursor"},{variable:"AI_AGENT",host:e=>n$(e)}],n$=e=>{let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").slice(0,40);return t===""||t==="1"||t==="true"?"agent":t},rl=e=>{let t=t$.find(({variable:n})=>rs(e[n]));return t?t.host(e[t.variable]):void 0},iu=e=>{let t=e[B.agentSession];return{surface:"cli",...t===void 0?{}:{session:t}}},au=(e,t)=>{let n=rl(e);return n===void 0?void 0:{...t,host:n,allowCommit:e[B.allowCommit]==="1",howToGrant:e$,wording:Bo}};var Ee=(e,t)=>e.replace(/\{(\w+)\}/g,(n,r)=>{let s=t[r];if(s===""||s==="."||s==="..")throw I(`'${s}' is not a valid ${r}.`);return encodeURIComponent(s)}),j=(e,t,n,r)=>e.getJson(Ee(t,n),r),Ho=(e,t,n,r,s)=>e.getJsonIfChanged(Ee(t,n),r,s),ee=(e,t,n,r,s)=>e.postJson(Ee(t,n),r,s),os=e=>e&&e.length>0?e.join(","):void 0;var du=e=>({list:t=>j(e,"/models/{modelId}/branches",{modelId:t}),create:(t,n)=>ee(e,"/models/{modelId}/branches",{modelId:t},n),delete:(t,n,r)=>e.delete(Ee("/models/{modelId}/branches/{branchId}",{modelId:t,branchId:n}),{force:r?"true":void 0}),diff:(t,n,r)=>j(e,"/models/{modelId}/branches/{branchId}/diff",{modelId:t,branchId:n},{base:r}),mergePreview:(t,n,r)=>j(e,"/models/{modelId}/branches/{branchId}/merge-preview",{modelId:t,branchId:n},{source:r}),merge:(t,n,r)=>ee(e,"/models/{modelId}/branches/{branchId}/merge",{modelId:t,branchId:n},r)});var r$=/[ \t\n\r\f]+/g,s$=/^[ \t\n\r\f]+|[ \t\n\r\f]+$/g,o$=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,is=e=>e.replace(o$,"");var i$=(e,t)=>{if(!Number.isFinite(e))throw new Error(`Cannot write ${e} as an SVG number`);let n=10**t,r=Math.sign(e)*Math.round(Math.abs(e)*n)/n;return String(r===0?0:r)},sl=e=>i$(e,2);var a$=e=>e.replace(r$," ").replace(s$,""),as=e=>a$(is(e)).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;");var lu="index.json",Uo=e=>{let t=e.fragments?.find(r=>r.address==="")?.realization?.path;if(t===void 0)return;let n=t.lastIndexOf("/");return n===-1?lu:`${t.slice(0,n)}/${lu}`},ds=e=>[...new Set(e)].sort(),d$=(e,t,n)=>{let r=new Map((e.elements??[]).map(i=>[as(i.id),i.id])),s=(e.diagrams??[]).filter(i=>!n.has(i.id)).map(i=>({...i,elements:ds([...t.get(i.id)??[]].flatMap(a=>r.get(a)??[]))})),o=new Map;for(let i of s)for(let a of i.elements??[])o.set(a,[...o.get(a)??[],i.id]);return{...e,elements:(e.elements??[]).map(i=>({...i,diagrams:ds(o.get(i.id)??[])})),diagrams:s}},l$=e=>({id:e.id,anchor:e.anchor,path:e.path,title:e.title,kind:e.kind,...e.status===void 0?{}:{status:e.status},...e.uri===void 0?{}:{uri:e.uri},refs:ds(e.refs??[]),diagrams:ds(e.diagrams??[])}),c$=e=>({id:e.id,path:e.path,title:e.title,elements:ds(e.elements??[])}),cu=e=>{let t={convention:e.convention,...e.generatedFrom===void 0?{}:{generatedFrom:e.generatedFrom},elements:(e.elements??[]).map(l$),diagrams:(e.diagrams??[]).map(c$).sort((n,r)=>n.path<r.path?-1:n.path>r.path?1:0)};return`${JSON.stringify(t,null,2)}
140
+ `},Vo=(e,t,n)=>e.index===void 0?e:{...e,index:d$(e.index,t,n)};var Cn=e=>{let t=e.payloads??{},n=[];for(let s of e.manifest.fragments??[]){let o=s.realization?.path;if(!o)continue;let i=t[s.address];i!==void 0&&n.push({path:o,content:i})}let r=e.index===void 0?void 0:Uo(e.manifest);return e.index!==void 0&&r!==void 0&&n.push({path:r,content:cu(e.index)}),n},mu="image/svg+xml, image/png",sr=e=>{let t=[];for(let n of e.fragments??[])for(let r of n.realization?.media??[])t.push(r);return[...new Set(t)]},or=(e,t={})=>{let n=new Set,r=new Set;for(let s of e)Object.hasOwn(t,s)?n.add(t[s]):r.add(s);return n.size+r.size};var fu=e=>({get:(t,n)=>j(e,"/models/{modelId}/content-bundle",{modelId:t},n),renderDiagrams:(t,n)=>ee(e,"/models/{modelId}/content-bundle/diagrams",{modelId:t},void 0,n),media:(t,n)=>e.getBytes(Ee("/models/{modelId}/content-bundle/media",{modelId:t}),mu,n)});var pu=e=>({get:t=>j(e,"/datasets/{datasetId}",{datasetId:t}),commits:(t,n={})=>j(e,"/datasets/{datasetId}/commits",{datasetId:t},{limit:n.limit===void 0?void 0:String(n.limit),cursor:n.cursor})});var uu=e=>({list:(t,n={})=>j(e,"/models/{modelId}/dependencies",{modelId:t},n),update:async(t,n,r)=>{let o={...await ee(e,"/models/{modelId}/dependencies/{dependencyId}",{modelId:t,dependencyId:n},r)};return delete o.model,o}});var hu=e=>({draftHeadId:e}),gu=e=>({model:{stage:async(t,n)=>{let{body:r,headers:s}=await e.postJsonWithHeaders(Ee("/models/{modelId}/draft/changes",{modelId:t}),n);return{envelope:r,draftId:s.get("draft-ref")??void 0}},undo:(t,n)=>ee(e,"/models/{modelId}/draft/undo",{modelId:t},{draftHeadId:n}),commit:(t,n)=>ee(e,"/models/{modelId}/draft/commit",{modelId:t},n),rebase:(t,n)=>ee(e,"/models/{modelId}/draft/rebase",{modelId:t},n),diff:t=>j(e,"/models/{modelId}/draft/diff",{modelId:t}),discard:(t,n)=>e.delete(Ee("/models/{modelId}/draft",{modelId:t}),hu(n)),handoff:(t,n)=>ee(e,"/models/{modelId}/draft/handoff",{modelId:t},n),open:(t,n)=>ee(e,"/models/{modelId}/draft",{modelId:t},{branchId:n})},dataset:{get:t=>j(e,"/datasets/{datasetId}/draft",{datasetId:t}),undo:(t,n)=>ee(e,"/datasets/{datasetId}/draft/undo",{datasetId:t},{draftHeadId:n}),commit:(t,n)=>ee(e,"/datasets/{datasetId}/draft/commit",{datasetId:t},n),rebase:(t,n)=>ee(e,"/datasets/{datasetId}/draft/rebase",{datasetId:t},n),diff:t=>j(e,"/datasets/{datasetId}/draft/diff",{datasetId:t}),discard:(t,n)=>e.delete(Ee("/datasets/{datasetId}/draft",{datasetId:t}),hu(n))}});var yu=e=>({encode:(t,n)=>j(e,"/models/{modelId}/encoding",{modelId:t},{format:n.format,mapping:n.mapping}),encodeCompressed:(t,n)=>e.getBytes(Ee("/models/{modelId}/encoding",{modelId:t}),"application/octet-stream",{format:n.format,mapping:n.mapping,compressed:"true"})});var wu=e=>({list:t=>j(e,"/metamodels/{metamodelId}/encoding-formats",{metamodelId:t})});var bu=e=>({get:(t,n)=>j(e,"/models/{modelId}/export-jobs/{jobId}",{modelId:t,jobId:n})});var ku=e=>({list:t=>j(e,"/imports",{},{ownerId:t}),create:t=>ee(e,"/imports",{},t),get:t=>j(e,"/imports/{importId}",{importId:t}),model:t=>j(e,"/imports/{importId}/model",{importId:t}),complete:(t,n)=>ee(e,"/imports/{importId}/complete",{importId:t},{name:n}),delete:t=>e.delete(Ee("/imports/{importId}",{importId:t}))});var Eu=e=>({list:t=>j(e,"/metamodel-extensions",{},{metamodelId:t})});var Cu=e=>({list:()=>j(e,"/metamodel-models",{}),create:t=>ee(e,"/metamodel-models",{},t),versions:t=>j(e,"/metamodel-models/{metamodelModelId}/versions",{metamodelModelId:t})});var vu=e=>({list:t=>j(e,"/metamodels/{metamodelId}/versions",{metamodelId:t})});var Ru=e=>({list:()=>j(e,"/metamodels",{}),templates:(t,n={})=>j(e,"/metamodels/{metamodelId}/templates",{metamodelId:t},{metamodelExtensions:os(n.metamodelExtensions)})});var Su=e=>({catalog:()=>j(e,"/model-loaders",{}),forMetamodel:(t,n)=>j(e,"/metamodels/{metamodelId}/loaders",{metamodelId:t},{version:n})});var Iu=e=>({list:(t={})=>j(e,"/model-mappings",{},{sourceMetamodel:t.sourceMetamodel})});var $u=e=>({limit:e.limit===void 0?void 0:String(e.limit),cursor:e.cursor}),xu=e=>({create:t=>ee(e,"/models",{},t),delete:t=>e.delete(Ee("/models/{modelId}",{modelId:t})),list:(t={})=>j(e,"/models",{},{ownerId:t.ownerId,metamodel:t.metamodel}),get:(t,n)=>j(e,"/models/{modelId}",{modelId:t},n&&{ref:n.ref,commit:n.commit,expand:os(n.expand)}),getIfChanged:(t,n,r)=>Ho(e,"/models/{modelId}",{modelId:t},n,{ref:r.ref,expand:os(r.expand)}),identity:(t,n={})=>j(e,"/models/{modelId}/identity",{modelId:t},n),identityIfChanged:(t,n)=>Ho(e,"/models/{modelId}/identity",{modelId:t},n),overview:t=>j(e,"/models/{modelId}/overview",{modelId:t}),versions:(t,n={})=>j(e,"/models/{modelId}/versions",{modelId:t},$u(n)),commits:(t,n={})=>j(e,"/models/{modelId}/commits",{modelId:t},{...$u(n),ref:n.ref,includeSystem:n.includeSystem?"true":void 0}),commitHeader:(t,n,r={})=>j(e,"/models/{modelId}/commits/{commitId}/header",{modelId:t,commitId:n},{ref:r.ref}),events:(t,n)=>e.openEventStream(Ee("/models/{modelId}/events",{modelId:t}),n),draft:t=>j(e,"/models/{modelId}/draft",{modelId:t}),schema:(t,n={})=>j(e,"/models/{modelId}/schema",{modelId:t},{ref:n.ref,type:n.type}),schemaIfChanged:(t,n,r={})=>Ho(e,"/models/{modelId}/schema",{modelId:t},n,{ref:r.ref,type:r.type})});var Tu=e=>({createVersion:(t,n)=>ee(e,"/models/{modelId}/versions",{modelId:t},n),createMetamodelRelease:(t,n)=>ee(e,"/metamodel-models/{metamodelModelId}/versions",{metamodelModelId:t},n===void 0?{}:{description:n}),refreshExtensionBase:t=>ee(e,"/metamodel-models/{extensionId}/refresh-base-dependency",{extensionId:t}),metamodelOverview:()=>j(e,"/metamodel-overview",{})});var Au=e=>({get:async(t,n={})=>{let r=await j(e,"/models/{modelId}/validation",{modelId:t},n);return{valid:r.valid,logEntries:r.logEntries??[]}}});var Ou=e=>({models:xu(e),branches:du(e),metamodels:Ru(e),metamodelModels:Cu(e),metamodelExtensions:Eu(e),drafts:gu(e),datasets:pu(e),contentBundles:fu(e),exportJobs:bu(e),validation:Au(e),imports:ku(e),modelLoaders:Su(e),metamodelVersions:vu(e),encodingFormats:wu(e),encoding:yu(e),modelMappings:Iu(e),dependencies:uu(e),releases:Tu(e),accessTokenClaims:()=>e.accessTokenClaims()});var Mu={requestUrl:"ACTIONS_ID_TOKEN_REQUEST_URL",requestToken:"ACTIONS_ID_TOKEN_REQUEST_TOKEN"},Bt=e=>e!==void 0&&e!=="",Nu=e=>e==="true"||e==="1",m$=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ol="mdsk_",Pu=57,vn=(e,t)=>({mode:"error",reason:e,message:t}),Ht="org settings \u2192 Service accounts",ls=e=>{if(Bt(e[B.apiKey]))return vn("legacy-api-key",`${B.apiKey} is no longer supported: the CI credential shipped as service accounts, not bearer keys. Use secret mode (set ${B.clientId} and ${B.clientSecret} from ${Ht}) or, on GitHub Actions, federated auth (grant 'permissions: id-token: write' and add a trust rule). Unset ${B.apiKey}.`);let t=e[B.clientId],n=e[B.clientSecret];if(Bt(t)!==Bt(n)){let[o,i]=Bt(t)?[B.clientId,B.clientSecret]:[B.clientSecret,B.clientId];return vn("partial-secret-config",`${o} is set but ${i} is not \u2014 both are required for secret-mode auth. Check the pipeline's secret configuration.`)}if(Bt(t)&&Bt(n))return m$.test(t)?n.startsWith(ol)?n.length!==Pu?vn("invalid-client-secret",`${B.clientSecret} has the wrong length: expected ${Pu} characters, got ${n.length}. Check for truncation in the pipeline's secret store.`):{mode:"secret",clientId:t,clientSecret:n}:vn("invalid-client-secret",`${B.clientSecret} does not start with '${ol}' (an issued secret always does). Check for quoting or truncation in the pipeline's secret store.`):vn("invalid-client-id",`${B.clientId} is not a service-account id: expected a UUID, got a ${t.length}-character value. Copy the account id from ${Ht}.`);let r=e[Mu.requestUrl],s=e[Mu.requestToken];return Bt(r)&&Bt(s)?{mode:"federated",oidcRequestUrl:r,oidcRequestToken:s}:Nu(e.GITHUB_ACTIONS)?vn("headless-ci",`Running on GitHub Actions without machine credentials. Grant 'permissions: id-token: write' to use federated auth (with a trust rule in ${Ht}), or set ${B.clientId} and ${B.clientSecret}. The CLI never opens a browser login in CI.`):Nu(e.CI)?vn("headless-ci",`Running in CI without machine credentials. Set ${B.clientId} and ${B.clientSecret} (${Ht}). The CLI never opens a browser login in CI.`):{mode:"interactive"}},le=e=>{let t=ls(e);return t.mode==="secret"||t.mode==="federated"?t.mode:void 0},Lu=e=>`${e.slice(0,ol.length+8)}\u2026`,Du=`Check ${B.clientId} and ${B.clientSecret}; issue or rotate a secret in ${Ht}.`,_u=`The service account may be disabled or deleted \u2014 check ${Ht}.`,ju={issuer:"the auth server does not trust this token issuer \u2014 federated auth currently supports GitHub Actions only.",signature:"the OIDC token's signature could not be verified \u2014 re-run the job; if it persists, the issuer's keys and the auth server disagree.",audience:`the workflow's OIDC audience does not match this host \u2014 check that --host/${B.host} names the ModelDesk instance the trust rule lives on.`,expired:"the OIDC token expired before the exchange \u2014 re-run the job.",repository:"no active trust rule matches this repository. This is also the failure for a pull-request-triggered run unless the rule enables 'Allow pull requests', and for a revoked rule.",binding:"the trust rule pins a branch or environment that does not match this run."},Go={unauthorized:`The machine token was rejected. A disabled or deleted service account fails on the next request; a revoked secret within five minutes. Check ${Ht}.`,forbidden:`The service account's scopes do not permit this \u2014 pulling content needs the 'model:content' scope (${Ht}).`,notFound:"Check the model id. A machine credential reads SHARED models only (creator-private models are not visible), and the model's metamodel must be entitled under the organization's subscription."};var f$="http://localhost:8080",p$="http://localhost:8082",u$="http://localhost:3000",h$="localhost",g$=e=>{let t=e.trim(),n=/:\/\//.test(t)?t:`https://${t}`;try{return new URL(n).hostname}catch{return t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").split("/")[0].split(":")[0]}},y$=e=>e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]",cs=e=>{let t=g$(e);return y$(t)?{host:h$,apiBase:f$,issuer:p$,appBase:u$}:{host:t,apiBase:`https://api.${t}`,issuer:`https://auth.${t}`,appBase:`https://app.${t}`}};import{existsSync as b$,readFileSync as k$}from"node:fs";import{join as E$}from"node:path";import{posix as w$}from"node:path";var ir=e=>{if(e.trim()==="")return"is empty";if(e.includes("\\"))return'has a backslash; separate folders with "/"';if(/[\t\r\n]/.test(e))return"has a tab or a line break";if(e.startsWith("/")||/^[A-Za-z]:/.test(e))return"is absolute";if(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e))return"is a URL";if(e.includes("%"))return'has a "%", which the document reads as a percent-escape; name the file without one';if(e.includes("#"))return'has a "#", which the document reads as the start of a fragment; name the file without one';if(e.includes("?"))return'has a "?", which the document reads as the start of a query; name the file without one';if(e.split("/").some(t=>t!==t.trim()))return"has a folder or file name that starts or ends with a space";if(e.split("/").includes(".."))return'has a ".." segment'},be=e=>w$.normalize(e).replace(/(.)\/+$/,"$1"),Rn=(e,t)=>{let n=be(e),r=be(t);return r==="."||n===r||n.startsWith(`${r}/`)};var ar=".modeldesk",C$="config.json",Ko="md-notes/",Yo=e=>e.configPath!==void 0,dr=e=>{let t=E$(e,ar,C$);return b$(t)?{config:v$(t),configPath:t,repoRoot:e}:{config:{},repoRoot:e}},v$=e=>{let t;try{t=k$(e,"utf8")}catch(s){throw new u(`Could not read ${e}: ${s.message}`)}let n;try{n=JSON.parse(t)}catch(s){throw new u(`${e} is not valid JSON: ${s.message}`)}if(n===null||typeof n!="object"||Array.isArray(n))throw new u(`${e} must contain a JSON object.`);let r=n;return{...Object.fromEntries(Object.keys(Et).map(s=>[s,Fu(r,s,e)])),notesDir:R$(r,"notesDir",e),publishDirs:S$(r,"publishDirs",e)}},Fu=(e,t,n)=>{let r=e[t];if(r!==void 0){if(typeof r!="string")throw new u(`${n}: "${t}" must be a string.`);return r}},R$=(e,t,n)=>{let r=Fu(e,t,n);return r!==void 0&&qu(r,`"${t}"`,n),r},S$=(e,t,n)=>{let r=e[t];if(r!==void 0){if(!Array.isArray(r)||!r.every(s=>typeof s=="string"))throw new u(`${n}: "${t}" must be an array of strings.`);return r.forEach((s,o)=>qu(s,`"${t}"[${o}]`,n)),r}},qu=(e,t,n)=>{let r=ir(e);if(r!==void 0)throw new u(`${n}: ${t} ${JSON.stringify(e)} ${r}; give a folder relative to the repository root.`)};var il=(e,t,n)=>{let r=n[B.host];return!(t!==void 0&&t!==""||r!==void 0&&r!=="")&&Yo(e)&&!!e.config.host},I$=(e,t)=>{il(t,e.globals.host,e.env)&&t.config.host!==ns&&e.io.err(`note: using host '${t.config.host}' from ${t.configPath} (it drives login and API calls).
141
+ `)},$$=(e,t,n)=>{if(le(n)&&il(e,t,n))throw new u(`In a machine-auth run the host must be set explicitly: pass --host or set ${B.host}. The committed ${e.configPath??".modeldesk/config.json"} is not a trusted source for where machine credentials are sent.`)},Wu=e=>{let t=dr(e.cwd);if(!e.interactive&&il(t,e.globals.host,e.env))throw new u(`A login without a terminal takes its host only from --host or ${B.host}, not from ${t.configPath??".modeldesk/config.json"}.`,{hint:`Pass --host ${t.config.host} if you trust it, or log in from a terminal.`})},lr=(e,t={})=>{let n=dr(e.cwd),r=ss({host:e.globals.host},e.env,n.config);return t.gateMachineHost&&$$(n,e.globals.host,e.env),I$(e,n),cs(r.host)},zo=(e,t)=>{let n=e.instance(),r=dr(e.cwd),s=ss({...t,host:e.globals.host},e.env,r.config);if(!s.model)throw new u(`No model specified. Pass --model, set ${B.model}, or add "model" to .modeldesk/config.json.`);return{instance:n,model:s.model,stack:s.stack,template:s.template,version:s.version,loaded:r}},ms=(e,t,n,r)=>{let s=e?.trim();if(!s)throw new u(`No ${t} specified. Pass ${r}, set ${n}, or add "${t}" to .modeldesk/config.json. Run 'modeldesk bundle templates' to list a model's stacks and templates.`);return s};var x$=e=>{let t=[];for(let n of e)n.forEach((r,s)=>{t[s]=Math.max(t[s]??0,r.length)});return t},F=(e,{indent:t="",gap:n=2,widths:r}={})=>{let o=x$(e).map((a,d)=>r?.[d]??a),i=" ".repeat(n);return e.map(a=>(t+a.map((d,l)=>l===a.length-1?d:d.padEnd(o[l])).join(i)).trimEnd())};var T$={draft:"@draft for your draft",head:"@head for your working branch without the draft",branch:"@main or @<branch> for a branch head",commit:"@<commit id> for a commit",release:"@<release> for a release"},A$={working:"your draft while it holds staged changes, else your working branch",head:"your working branch head",main:"main",draft:"your draft"},Bu=e=>{if(e.kinds.length===0)return"It takes no @ref: this command reads main.";let t=e.kinds.includes("release"),n=e.kinds.map(r=>r==="branch"&&t?"@main for its head":T$[r]).join(", ");return"required"in e?`At a ref: ${n}. The ref is required.`:`Optionally at a ref: ${n}. Without a ref: ${A$[e.default]}.`},O$=e=>e.kinds.includes("release")?e.kinds.map(t=>t==="branch"?"main":t).join("|"):e.kinds.length===1?e.kinds[0]:"ref",al=e=>{if(e.kinds.length===0)return"";let t=O$(e);return"required"in e?`@${t}`:`[@${t}]`},_=e=>({name:"model",type:{address:"model",slot:e},required:!0,description:`The model's id, from model list. ${Bu(e)}`}),Hu=e=>({name:"resource",type:{address:"resource",slot:e},required:!0,description:`The model's id, from model list, or dataset/<id>. ${Bu(e)}`}),We=e=>({name:e,type:{address:"element"},required:!0,description:"The element's id, or its label path from the model root (SHACL/NodeShape/severity; write a '/' inside "+String.raw`a label as '\/').`});var cr={json:{type:"boolean",description:"Print one JSON document on stdout instead of text."},"no-json":{type:"boolean",description:"Print text even where an agent host makes JSON the default."},host:{type:"string",placeholder:"host",description:"The ModelDesk instance to target (default: modeldesk.io, or MODELDESK_HOST or the repo config)."},"dry-run":{type:"boolean",description:"Report what would change and write nothing (commands that write)."},yes:{type:"boolean",description:"Answer yes to confirmations; required to confirm when not interactive."},help:{type:"boolean",short:"h",description:"Show help."},version:{type:"boolean",short:"v",description:"Show the CLI version."}},Uu=new Set(["json","no-json","host","dry-run","yes","help"]),dl=50,fs={limit:{type:"number",placeholder:"n",default:dl,description:"Return at most this many rows."},cursor:{type:"string",placeholder:"cursor",description:"Continue a truncated listing from the nextCursor it returned."},all:{type:"boolean",description:"Return every row; with --json, one JSON object per line (NDJSON)."}},Vu=e=>e.defaultLimit===void 0?fs:{...fs,limit:{...fs.limit,default:e.defaultLimit}};import{parseArgs as j$}from"node:util";var M$=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Y=e=>M$.test(e);var N$={noun:"A model",listing:"modeldesk model list"},Jo="dataset/",P$={draft:"@draft (your draft)",head:"@head (your working branch without the draft)",branch:"@main or @<branch>",commit:"@<commit id>",release:"@<release>"},L$=(e,t)=>e==="branch"&&t.kinds.includes("release")?"@main":P$[e],Gu=e=>{let t=e.kinds.map(n=>L$(n,e));return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} or ${t.at(-1)}`},ll=e=>new u(e,{exitCode:b.Usage,type:"ref-unsupported"}),D$=(e,t)=>e==="draft"||e==="head"?{kind:e}:Y(e)?{kind:"commit",id:e}:e!=="main"&&t.kinds.includes("release")?{kind:"release",name:e}:{kind:"branch",name:e},_$=e=>{if(e.kind!=="working")return e.kind==="branch-id"?"branch":e.kind},Ku=e=>e.slice(e.indexOf("@")),cl=(e,t)=>{let n=_$(e.ref);if(n===void 0){if("required"in t)throw ll(`'${e.text}' names no ref, and this argument needs one: ${Gu(t)}.`);return e}if(t.kinds.length===0)throw ll(`This command reads main only, so the model takes no ref; drop '${Ku(e.text)}'.`);if(!t.kinds.includes(n))throw ll(`'${Ku(e.text)}' is not accepted here; the ref can be ${Gu(t)}.`);return e},ml=(e,t)=>{if(e.startsWith(Jo)&&Y(e.slice(Jo.length).split("@")[0]))throw new u(`'${e}' names a dataset, and this argument takes a model.`,{exitCode:b.Usage});let n=e.indexOf("@"),r=n===-1?e:e.slice(0,n),s=n===-1?void 0:e.slice(n+1);if(r==="")throw new u(`'${e}' names no model; write <model> or <model>@<ref>.`,{exitCode:b.Usage});if(s==="")throw new u(`'${e}' ends in '@' with no ref after it.`,{exitCode:b.Usage});if(!Y(r)){let{noun:i,listing:a}=t.names??N$;throw new u(`'${r}' is not an id. ${i} is addressed by its id: run '${a}' to find it.`,{exitCode:b.Usage,type:"id-required",...t.names===void 0?{hosted:{reason:d=>`'${r}' is not an id. ${i} is addressed by its id: call ${d("model list")} to find it.`}}:{}})}let o=s===void 0?{kind:"working"}:D$(s,t);return cl({model:r.toLowerCase(),ref:o,text:e},t)},mr=e=>e.ref.kind==="release"?e.ref.name:void 0,Yu=(e,t)=>{if(!e.startsWith(Jo))return{kind:"model",address:ml(e,t)};let n=e.slice(Jo.length);if(n.includes("@"))throw new u(`'${e}' names a ref on a dataset, which has drafts and no branches; drop the '@'.`,{exitCode:b.Usage});if(!Y(n))throw new u(`'${e}' is not a dataset address; write dataset/<id>.`,{exitCode:b.Usage});return{kind:"dataset",id:n,text:e}};var Be=e=>typeof e=="object"&&"list"in e,Qo=e=>typeof e=="object"&&"enum"in e,Zo=e=>typeof e=="object"&&"address"in e,F$=(e,t,n)=>{try{switch(t.address){case"model":return ml(e,t.slot);case"resource":return Yu(e,t.slot);case"element":return e}}catch(r){throw r instanceof u?new u(r.reason,{exitCode:b.Usage,type:r.type,hint:`Run '${n}'.`,hosted:r.hosted}):r}},Ct=e=>({...e.flags,...e.listing?Vu(e.listing):{}}),Xu=e=>({type:e.type==="boolean"?"boolean":"string",...Be(e.type)?{multiple:!0}:{},...e.short?{short:e.short}:{}}),Qu=e=>Object.fromEntries(Object.entries(cr).filter(([t])=>!(t in e)).map(([t,n])=>[t,Xu(n)])),Zu=(e,t,n)=>{try{return j$({args:e,options:t,allowPositionals:!0,strict:!0})}catch(r){throw I(r.message,n)}},eh=(e,t)=>({json:e.json===!0,noJson:e["no-json"]===!0,host:typeof e.host=="string"?e.host:void 0,dryRun:e["dry-run"]===!0,yes:e.yes===!0,help:e.help===!0,version:!("version"in t)&&e.version===!0}),fl=(e,t)=>{let{values:n,positionals:r}=Zu(e,Qu({}),t);return{globals:eh(n,{}),positionals:r}},zu=(e,t)=>Qo(t)?`${e} must be one of ${t.enum.join(", ")}`:`${e} expects a ${t==="number"?"number":"value"}`,Xo=(e,t,n,r)=>{let s=Be(t)?t.list:t;if(Zo(s))return F$(e,s,r);if(s==="number"){let o=Number(e);if(e.trim()===""||!Number.isFinite(o))throw I(`${zu(n,s)}, got '${e}'.`,r);return o}if(s==="boolean"){if(e!=="true"&&e!=="false")throw I(`${n} expects true or false, got '${e}'.`,r);return e==="true"}if(Qo(s)&&!s.enum.includes(e))throw I(`${zu(n,s)}, got '${e}'.`,r);return e},Ju=(e,t,n)=>{let r=t.short?` (-${t.short})`:"",s=t.requiredReason?` ${t.requiredReason}`:"";return I(`Missing required flag --${e}${r}.${s}`,n)},q$=(e,t,n,r)=>{let s=`--${e}`;if(t.type==="boolean")return n===!0;if(Be(t.type)){let o=n??[];if(o.length===0&&t.required)throw Ju(e,t,r);return o.length===0&&t.default!==void 0?t.default:o.map(i=>Xo(i,t.type,s,r))}if(n===void 0){if(t.required)throw Ju(e,t,r);return t.default}return Xo(n,t.type,s,r)},W$=(e,t,n)=>{let r={};if(e.forEach((o,i)=>{let a=`<${o.name}>`;if(Be(o.type)){let l=t.slice(i);if(l.length===0&&o.required)throw I(`Missing required argument ${a}.`,n);r[o.name]=l.map(c=>Xo(c,o.type,a,n));return}let d=t[i];if(d===void 0){if(o.required)throw I(`Missing required argument ${a}.`,n);r[o.name]=void 0;return}r[o.name]=Xo(d,o.type,a,n)}),!e.some(o=>Be(o.type))&&t.length>e.length)throw I(`Unexpected argument '${t[e.length]}'.`,n);return r},th=(e,t,n)=>{let r=Ct(e),s={...Qu(r),...Object.fromEntries(Object.entries(r).map(([c,m])=>[c,Xu(m)]))},{values:o,positionals:i}=Zu(t,s,n),a=eh(o,r),d=Object.fromEntries(Object.entries(r).map(([c,m])=>[c,q$(c,m,o[c],n)]));if(e.listing){let c=d.limit;if(!Number.isInteger(c)||c<1)throw I(`--limit must be a positive whole number, got ${c}.`,n)}let l=W$(e.positionals??[],i,n);return{flags:d,args:l,globals:a}};var nh=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/,B$=new Set(Object.values(cr).flatMap(e=>e.short?[e.short]:[])),H$=(e,t)=>{for(let[n,r]of Object.entries(t.flags??{})){if(Uu.has(n))throw new Error(`'${e}' declares --${n}, which is a global flag every command already takes.`);if(t.listing&&n in fs)throw new Error(`'${e}' declares --${n}, which its listing already provides.`);if(r.type==="boolean"&&r.default!==void 0)throw new Error(`'${e}' gives --${n} a default; a boolean flag is off unless passed.`)}},U$=(e,t)=>{let n=Object.entries(t.flags??{}).flatMap(([r,s])=>s.short===void 0?[]:[[r,s.short]]);for(let[r,s]of n)if(!/^[a-z]$/.test(s)||B$.has(s)||n.filter(([,o])=>o===s).length>1)throw new Error(`'${e}' gives --${r} the alias -${s}; an alias is one free lowercase letter.`)},V$=(e,t)=>{let n=t.positionals??[];n.forEach((r,s)=>{let o=s===n.length-1;if(Be(r.type)&&!o)throw new Error(`'${e}': only the last argument may take a list (<${r.name}>).`);let i=n[s-1];if(r.required&&i&&!i.required)throw new Error(`'${e}': required argument <${r.name}> follows an optional one.`)})},G$=e=>{let t=e.path.join(" ");if(e.path.length===0||e.path.some(r=>!nh.test(r)))throw new Error(`Command path '${t}' must be one or more kebab-case words.`);H$(t,e),U$(t,e);let n=e.listing?.defaultLimit;if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error(`'${t}' gives its listing a default limit of ${n}; it must be a positive whole number.`);for(let r of Object.keys(Ct(e)))if(!nh.test(r))throw new Error(`'${t}' declares --${r}; flag names are kebab-case.`);V$(t,e)},pl=e=>{let t={kind:"group",path:[],children:new Map};for(let n of e){G$(n);let r=t;n.path.forEach((s,o)=>{let i=n.path.slice(0,o+1),a=r.children.get(s);if(o===n.path.length-1){if(a)throw new Error(`'${i.join(" ")}' is declared twice, or as both a command and a group.`);r.children.set(s,{kind:"command",path:i,spec:n});return}if(a?.kind==="command")throw new Error(`'${i.join(" ")}' is both a command and a group.`);let l=a??{kind:"group",path:i,children:new Map};r.children.set(s,l),r=l})}return t},ei=e=>[...e.children.values()].flatMap(t=>t.kind==="group"?ei(t):[t]);var ti="modeldesk",sh=[["0","success"],["1","failure (generic or server)"],["2","usage error"],["3","not found"],["4","validation or check failure (input refused, or an assertion the caller asked for failed)"],["5","conflict (stale base, lost compare-and-set)"],["6","needs a human (log in, confirm, commit in the app)"],["7","transient, safe to retry (network, 429, 5xx)"]],K$=sh.map(([e,t])=>`${e} ${t.replace(/ \(.*\)$/,"")}`),Y$=`Exit codes: ${K$.join(", ")}.`,z$=`With --json, a command's stdout is one JSON document led by schemaVersion (help and version stay text); on failure the last stderr line is {"error": {code, message, hint?, retryable, type?, requestId?, details}}.`,J$=(e,t)=>{if(t)return`<${t}>`;let n=Be(e)?e.list:e;return Qo(n)?`<${n.enum.join("|")}>`:Zo(n)?`<${n.address}${n.address==="element"?"":al(n.slot)}>`:n==="number"?"<n>":"<value>"},hl=(e,t)=>{let n=t.short?`, -${t.short}`:"";return t.type==="boolean"?`--${e}${n}`:`--${e}${n} ${J$(t.type,t.placeholder)}`},X$=e=>Array.isArray(e)?e.join(", "):String(e),rh=e=>{let t=[];return e.required&&t.push("required"),e.default!==void 0&&e.type!=="boolean"&&t.push(`default: ${X$(e.default)}`),Be(e.type)&&t.push("repeatable"),t.length>0?` (${t.join("; ")})`:""},ul=e=>{let t=Be(e.type)?e.type.list:e.type,n=Zo(t)&&t.address!=="element"?al(t.slot):"";return`<${e.name}${n}>`},Q$=e=>{let t=Be(e.type)?`${ul(e)}...`:ul(e);return e.required?t:`[${t}]`},oh=e=>{let t=Ct(e),n=Object.entries(t).filter(([,s])=>s.required).map(([s,o])=>hl(s,o)),r=Object.values(t).some(s=>!s.required);return[ti,...e.path,...(e.positionals??[]).map(Q$),...n,...r?["[options]"]:["[global options]"]].join(" ")},Sn=(e,t)=>t.length===0?[]:[`${e}:`,...F(t,{indent:" "}),""],ih=e=>{let t=e?Ct(e):{};return Object.entries(cr).filter(([n])=>!(n in t)).filter(([n])=>n!=="dry-run"||e===void 0||e.dryRun===!0).map(([n,r])=>[hl(n,r),r.description])},Z$=e=>ei(e).map(t=>[t.path.slice(e.path.length).join(" "),t.spec.summary]),ah=e=>["ModelDesk CLI","",`Usage: ${ti} <command> [options]`,"",...Sn("Commands",Z$(e)),...Sn("Global options",ih()),...Sn("Exit codes",sh),z$,`Run '${ti} <command> --help' for a command's arguments and flags.`,""].join(`
142
+ `),dh=e=>{let t=[ti,...e.path].join(" "),n=ei(e).flatMap(r=>[[r.path.slice(e.path.length).join(" "),r.spec.summary],["",oh(r.spec)]]);return[`Usage: ${t} <command> [options]`,"",...Sn("Commands",n),`Run '${t} <command> --help' for a command's arguments and flags.`,""].join(`
143
+ `)},lh=e=>{let t=(e.positionals??[]).map(s=>[ul(s),s.description+rh(s)]),n=Object.entries(Ct(e)).map(([s,o])=>[hl(s,o),o.description+rh(o)]),r=(e.examples??[]).map(s=>` ${s}`);return[`Usage: ${oh(e)}`,"",e.summary,...e.description?["",e.description]:[],"",...Sn("Arguments",t),...Sn("Flags",n),...Sn("Global options",ih(e)),...r.length>0?["Examples:",...r,""]:[],Y$,...e.listing?[`Listings are truncated at --limit; ${ex(e)}`]:[],""].join(`
144
+ `)},ex=e=>`a truncated one carries nextCursor and truncated: true.${e.listing?.narrowHint?` ${e.listing.narrowHint}`:""}`;var ch='# Working in a ModelDesk model from a shell\n\nYou have a shell, so drive the CLI. You pay for a command only when you run it and read help only when you need it (`modeldesk <command> --help`). Under an agent host the output is one JSON document; pass `--no-json` for text.\n\nA person owns the model and reviews your work. You stage proposals; they decide what lands.\n\n## On every invocation\n\n- **Always write the ref.** Address `<model>@<branch>` every time, for example `<model>@agent/<topic>`, and never leave it out. A commit from any surface, the app included, deletes the draft, and unaddressed invocations then read and write `main`.\n- **Read your own work at `@draft`.** A change addressed `<model>@<branch>` is staged in your draft, but a read addressed `<model>@<branch>`, such as `modeldesk search`, `modeldesk el show` or `modeldesk validate`, sees the branch head without it. Read back and validate what you staged with `<model>@draft`.\n- **Keep one session.** Set `MODELDESK_AGENT_SESSION` before the first change and keep the same value for every command up to the wait, in every shell you start: it groups your changes for the person, and the wait finds your changes by it.\n- **Stage small steps, each with a message** (`-m`). The message is what the person reads first, in the app and in `modeldesk model log <model> --changes`.\n- **Add a dependency before you refer to another model.** Check `modeldesk pin list <model>@<branch>`. When the model is missing, run `modeldesk dependency add <model>@<branch> <target>@<release|main>` first: it is a staged change of its own, which the person reviews with the rest.\n- **Never merge, and never delete.** `modeldesk branch merge` lands on a shared branch with no draft to review, so it is refused unless the person set `MODELDESK_ALLOW_COMMIT=1`, and even then the merge is theirs to make. `modeldesk model delete` and `modeldesk branch delete` are refused to an agent.\n- **Commits elsewhere need the person\'s grant.** Commit only on a branch named `agent/<topic>`. A commit on any other branch is left to the person, unless they set `MODELDESK_ALLOW_COMMIT=1` for you.\n\n## The loop\n\n1. **Discover the schema.** `modeldesk describe <model>` gives the overview, `modeldesk describe <model> <type>` one type.\n2. **Read before you write.** `modeldesk search <model>@<branch> <text>` finds elements and `modeldesk el show <model>@<branch> <element>` reads one.\n3. **Stage.** Use `modeldesk el create`, `modeldesk el set`, `modeldesk el relate` and their siblings for small edits and `modeldesk el bulk` for sweeps. For bulk authoring use the file workspace: `modeldesk model pull <model>@<branch>`, edit the files, check them with `modeldesk model diff`, then stage them with `modeldesk model push -m <message>`.\n - To create an element with what it owns as one change, use `el create --from <file>`. In the file, attribute values are arrays, `"name": ["Address"]`; a reference is `"relations": {"type": {"@@": [{"id": "<id>", "owned": false}]}}`; owned elements nest under `"children"`, keyed by the owning relation.\n4. **Verify.** `modeldesk draft diff <model>@<branch>` shows what your draft changes and `modeldesk validate <model>@draft` checks the model with it. Validate after the first change that sets a pattern, not only at the end, so a mistake is not repeated across the draft. To repair your last change, undo it with `modeldesk draft undo <model>@<branch>` and stage it again complete, rather than adding changes that patch it: the person reviews each change by itself.\n5. **Keep the proposal rebased.** When `modeldesk draft status <model>@<branch>` shows `behind: true`, run `modeldesk draft rebase <model>@<branch>`. A `rebase-conflict` names your own rejected changes: correct and stage them again, and drop only what you cannot repair.\n\nThen pick a lane.\n\n## The draft lane\n\nFor a proposal that fits one draft. You stage into the draft you share with the person, who reviews it in their open model and answers it there.\n\n1. **Stage on the branch your draft aims at.** One draft per user per model; `modeldesk draft status` names where it aims. While it holds changes on another branch, staging elsewhere is refused with `draft-target-taken`: ask the person to commit or discard those changes.\n2. **End with `modeldesk draft handoff <model>@<branch> -m <summary>`.** The summary is your own account of what the draft does. Do not commit on this lane: the commit is the person\'s answer.\n3. **Wait for the verdict.** Run `modeldesk draft status <model>@<branch> --wait` and act on its `verdict`:\n - `committed`: tell the person it landed, with `url` and how many of your changes (`landed`).\n - `discarded`: none of your changes landed. Ask the person what to change.\n - `changed`: the person removed or undid changes. Read `modeldesk draft diff <model>@<branch> --changes`, then hand off again or wait again.\n - `branch-moved`: run `modeldesk draft rebase <model>@<branch>`, resolve any conflict in your own changes, then wait again.\n\n When the wait exits 7 (`retryable: true`) run it again. When you cannot keep waiting, tell the person how to check: `modeldesk draft status <model>@<branch>`.\n - A wait that finds no draft is refused with `no-draft`: the person has already answered (committed or discarded the draft), or nothing was handed off. Run `modeldesk model log <model>@<branch> --changes` to see whether your changes landed.\n - A wait refused with `no-own-changes` found none of your changes in the draft: it runs under another `MODELDESK_AGENT_SESSION` than the one that staged them, or the person removed them first. Run `modeldesk draft diff <model>@<branch> --changes` to see where each change came from.\n\n## The branch lane\n\nFor work too large for one draft. You commit on a branch of your own, and the person reviews and merges the branch.\n\n1. **Start on a branch of your own.** `modeldesk branch create <model> agent/<topic> --open`. While your draft holds changes on another branch this is refused with `draft-target-taken`, as above.\n2. **Commit as you go.** `modeldesk draft commit <model>@agent/<topic>`, with `-m` or without it to compose the message from your staged messages. Commit before `changeCount` in `modeldesk draft status` nears `maxChanges`, since a draft holds at most 500 changes.\n3. **End with the commit.** The last commit on `agent/<topic>` is the handoff: its message is the summary and its record lists every change with its message. There is no draft to wait on. Name the branch in the chat and ask the person to review and merge it in the app; `modeldesk branch list <model>` shows it unmerged until then.\n';var D=e=>e,q=e=>e;var mh=q({path:["agent-guide"],effect:"local",summary:"Print the guide for an agent that uses the CLI",description:"Prints, as Markdown, how an agent with a shell works in a model: always write the ref, stage small steps with a message each, and choose the draft lane (hand off, then wait for the verdict) or the branch lane (commit on agent/<topic>, then ask the person to merge). Under an agent host the output is a JSON document with the guide as its `guide` member; pass --no-json to print the Markdown itself.",examples:["modeldesk agent-guide --no-json"],run:async()=>({result:{guide:ch}}),render:({guide:e})=>e});import{randomBytes as gl,randomInt as tx}from"node:crypto";import{chmodSync as yl,closeSync as kl,fsyncSync as wh,linkSync as nx,mkdirSync as rx,openSync as El,readFileSync as ni,renameSync as fh,rmSync as ri,statSync as ph,utimesSync as sx,writeSync as uh}from"node:fs";import{homedir as ox,hostname as hh}from"node:os";import{join as gh}from"node:path";var wl=448,bl=384,ix=5e3,ax=3e4,dx=9e4,yh=50,lx=e=>new Promise(t=>setTimeout(t,e)),fr=(e,t)=>e instanceof Error&&e.code===t,ot=class{dir;file;lockFile;lockTimeoutMs;staleLockMs;now;sleep;queue=Promise.resolve();constructor(t=gh(ox(),".modeldesk"),n={}){this.dir=t,this.file=gh(t,"credentials.json"),this.lockFile=`${this.file}.lock`,this.lockTimeoutMs=n.lockTimeoutMs??dx,this.staleLockMs=n.staleLockMs??ax,this.now=n.now??Date.now,this.sleep=n.sleep??lx}read(t){let n=this.readFile().hosts[t];return n&&typeof n.refreshToken=="string"?n:void 0}async save(t,n){await this.transact(async r=>r.write(t,n))}async clearHost(t){return this.transact(async n=>{let r=n.read(t)!==void 0;return r&&n.write(t,void 0),r})}async transact(t){let n=this.queue.then(async()=>{let r=await this.acquireLock(),s=setInterval(()=>this.touchLock(r),ix);s.unref();try{return await t({read:o=>this.read(o),write:(o,i)=>this.writeHost(o,i)})}finally{clearInterval(s),this.releaseLock(r)}});return this.queue=n.catch(()=>{}),n}readFile(){let t;try{t=ni(this.file,"utf8")}catch(n){if(fr(n,"ENOENT"))return{hosts:{}};throw new u(`Could not read ${this.file}: ${n.message}`)}try{let n=JSON.parse(t);if(n&&typeof n=="object"&&n.hosts&&typeof n.hosts=="object")return n}catch(n){if(!(n instanceof SyntaxError))throw n}return{hosts:{}}}writeHost(t,n){let r=this.readFile();n?r.hosts[t]=n:delete r.hosts[t],this.writeAtomically(`${JSON.stringify(r,null,2)}
145
+ `)}writeAtomically(t){this.ensureDir();let n=`${this.file}.${process.pid}.${gl(6).toString("hex")}.tmp`;try{let r=El(n,"wx",bl);try{uh(r,t),wh(r)}finally{kl(r)}fh(n,this.file)}catch(r){throw ri(n,{force:!0}),r}mx(this.dir),yl(this.dir,wl),yl(this.file,bl)}ensureDir(){rx(this.dir,{recursive:!0,mode:wl})!==void 0&&yl(this.dir,wl)}async acquireLock(){this.ensureDir();let t=`${hh()} ${process.pid} ${gl(8).toString("hex")} ${new Date(this.now()).toISOString()}
146
+ `,n=this.now()+this.lockTimeoutMs;for(;;){if(this.tryCreateLock(t))return t;if(!this.takeOverAbandonedLock()){if(this.now()>=n)throw new u(`Timed out waiting for another modeldesk process to release ${this.lockFile}.`,{exitCode:b.Transient,hint:"Retry; if no other modeldesk process is running, delete the lock file."});await this.sleep(yh+tx(yh))}}}tryCreateLock(t){let n;try{n=El(this.lockFile,"wx",bl)}catch(r){if(fr(r,"EEXIST"))return!1;throw r}try{return uh(n,t),!0}catch(r){throw ri(this.lockFile,{force:!0}),r}finally{kl(n)}}isAbandoned(t,n){if(this.now()-t>=this.staleLockMs)return!0;let[r,s]=n.split(" "),o=Number.parseInt(s??"",10);return r===hh()&&Number.isInteger(o)&&o>0&&!cx(o)}takeOverAbandonedLock(){let t,n;try{t=ph(this.lockFile),n=ni(this.lockFile,"utf8")}catch(o){if(fr(o,"ENOENT"))return!0;throw o}if(!this.isAbandoned(t.mtimeMs,n))return!1;let r=`${this.lockFile}.${process.pid}.${gl(6).toString("hex")}.stale`;try{fh(this.lockFile,r)}catch(o){if(fr(o,"ENOENT"))return!0;throw o}let s=ph(r);if(s.ino!==t.ino||s.mtimeMs!==t.mtimeMs)try{nx(r,this.lockFile)}catch{}return ri(r,{force:!0}),!0}touchLock(t){try{if(ni(this.lockFile,"utf8")===t){let n=new Date(this.now());sx(this.lockFile,n,n)}}catch{}}releaseLock(t){try{ni(this.lockFile,"utf8")===t&&ri(this.lockFile,{force:!0})}catch(n){if(!fr(n,"ENOENT"))throw n}}},cx=e=>{try{return process.kill(e,0),!0}catch(t){return!fr(t,"ESRCH")}},mx=e=>{let t;try{t=El(e,"r"),wh(t)}catch{}finally{t!==void 0&&kl(t)}},Cl=(e,t,n)=>e?.accessToken&&e.accessTokenExpiresAt!==void 0&&e.accessTokenExpiresAt-t>n?e.accessToken:void 0;var Ut="modeldesk-cli",bh="modeldesk-federation",kh="openid",vl="/callback";var Vt=async e=>{let t=`${e.replace(/\/+$/,"")}/.well-known/openid-configuration`,n;try{n=await fetch(t,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(3e4)})}catch(s){throw new u(`Could not reach the auth server at ${e} (${s.message}).`,b.Transient)}if(!n.ok)throw new u(`OpenID discovery failed at ${t}: ${n.status} ${n.statusText}`,n.status===429||n.status>=500?b.Transient:b.Failure);let r=await n.json();if(!r.authorization_endpoint||!r.token_endpoint)throw new u(`OpenID discovery at ${t} did not return the authorization and token endpoints.`);for(let s of[r.authorization_endpoint,r.token_endpoint,r.device_authorization_endpoint])if(s!==void 0&&!fx(s,e))throw new u(`OpenID discovery at ${t} names an endpoint outside the issuer's origin: ${s}.`);return{authorizationEndpoint:r.authorization_endpoint,tokenEndpoint:r.token_endpoint,...r.device_authorization_endpoint?{deviceAuthorizationEndpoint:r.device_authorization_endpoint}:{}}},fx=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}};var Gt=class extends u{oauthError;errorDescription;constructor(t,n,r,s=b.Failure){super(t,s),this.name="TokenEndpointError",this.oauthError=n,this.errorDescription=r}},Eh=e=>e instanceof Gt&&e.oauthError==="invalid_grant",Ch=(e,t)=>ps(e,new URLSearchParams({grant_type:"authorization_code",code:t.code,redirect_uri:t.redirectUri,client_id:Ut,code_verifier:t.codeVerifier})),px="urn:ietf:params:oauth:grant-type:device_code",vh=(e,t)=>ps(e,new URLSearchParams({grant_type:px,device_code:t,client_id:Ut})),Rh=(e,t)=>ps(e,new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:Ut})),Sh=(e,t)=>ps(e,new URLSearchParams({grant_type:"client_credentials",client_id:t.clientId,client_secret:t.clientSecret})),Ih=(e,t)=>ps(e,new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token:t,subject_token_type:"urn:ietf:params:oauth:token-type:jwt",client_id:bh})),ux=new Set(["server_error","temporarily_unavailable"]),ps=async(e,t)=>{let n;try{n=await fetch(e,{method:"POST",redirect:"error",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:t.toString(),signal:AbortSignal.timeout(3e4)})}catch(s){throw new u(`Could not reach the token endpoint (${s.message}).`,b.Transient)}if(!n.ok){let{message:s,code:o,description:i}=await hx(n),a=ux.has(o??"")||n.status===429||n.status>=500;throw new Gt(`Token request failed: ${s}`,o,i,a?b.Transient:b.Failure)}let r=await n.json();if(!r.access_token)throw new u("The token response did not include an access token.");return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresInSeconds:r.expires_in??0}},hx=async e=>{try{if((e.headers.get("content-type")??"").includes("json")){let n=await e.json();if(n.error)return{message:n.error_description?`${n.error} (${n.error_description})`:n.error,code:n.error,description:n.error_description}}}catch{}return{message:`${e.status} ${e.statusText}`.trim()}};var gx=5,yx=5,wx=1,bx=60,kx=600,Ex=1800,Th=e=>Math.min(bx,Math.max(wx,e)),$h=(e,t)=>{let n;try{n=new URL(e)}catch{throw new u("The device authorization response carries an invalid verification URL.")}let r=new URL(t.issuer);if(!(n.protocol==="https:"||n.protocol==="http:"&&r.protocol==="http:")||n.hostname!==r.hostname)throw new u(`The device authorization response points to ${n.origin}, not to the auth server ${r.origin}; refusing to show its code.`);return n.toString()},xh=(e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:t,Ah=new Set(["unauthorized_client","unsupported_grant_type","invalid_client"]),Cx=e=>new Promise(t=>setTimeout(t,e)),Rl=e=>new u(`Device login is not enabled on ${e.host}.`,{hint:"Run 'modeldesk auth login' where a browser can reach this machine."}),vx=async(e,t)=>{let n;try{n=await fetch(e,{method:"POST",redirect:"error",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:Ut}).toString(),signal:AbortSignal.timeout(3e4)})}catch(s){throw new u(`Could not reach the device authorization endpoint (${s.message}).`,{exitCode:b.Transient})}let r=await n.json().catch(()=>({}));if(!n.ok){if(r.error&&Ah.has(r.error))throw Rl(t);let s=r.error??`${n.status} ${n.statusText}`;throw new u(`Device authorization failed: ${s}`,{exitCode:n.status===429||n.status>=500?b.Transient:b.Failure})}return r},Oh=()=>new u("The code expired before it was approved.",{hint:"Run 'modeldesk auth login --device' again."}),Rx=(e,t,n)=>{if(!(e instanceof Gt))throw e;switch(e.oauthError){case"authorization_pending":return t;case"slow_down":return Th(t+yx);case"access_denied":throw new u("The sign-in was declined, so nothing was stored.");case"expired_token":throw Oh();default:throw e.oauthError&&Ah.has(e.oauthError)?Rl(n):e}},Sx=(e,t,n)=>{let{device_code:r,user_code:s,verification_uri:o}=e;if(!r||!s||!o)throw new u("The device authorization response is missing its code or verification URL.");let i=$h(o,t),a=e.verification_uri_complete?$h(e.verification_uri_complete,t):void 0;return n.info(`To sign in to ${t.host}, open ${i} and enter the code ${s}.`),a&&n.info(`Or open this link, which carries the code:
147
+ ${a}`),r},Mh=async(e,t,n={})=>{let r=n.sleep??Cx,s=n.now??Date.now,{deviceAuthorizationEndpoint:o,tokenEndpoint:i}=await Vt(e.issuer);if(!o)throw Rl(e);let a=await vx(o,e),d=Sx(a,e,t),l=Math.min(Ex,xh(a.expires_in,kx)),c=s()+l*1e3,m=Th(xh(a.interval,gx));for(;;){await r(m*1e3);try{return await vh(i,d)}catch(f){if(f instanceof u&&f.exitCode===b.Transient){if(s()>=c)throw f;continue}m=Rx(f,m,e)}if(s()>=c)throw Oh()}};import{spawn as Ix}from"node:child_process";import{platform as $x}from"node:process";var Nh=e=>{if(!xx(e))return;let{command:t,args:n,verbatim:r}=Tx(e);try{let s=Ix(t,n,{stdio:"ignore",detached:!0,windowsVerbatimArguments:r});s.on("error",()=>{}),s.unref()}catch{}},xx=e=>{try{let{protocol:t}=new URL(e);return t==="http:"||t==="https:"}catch{return!1}},Tx=(e,t=$x)=>{switch(t){case"darwin":return{command:"open",args:[e]};case"win32":return{command:"cmd",args:["/c","start",'""',Ax(e)],verbatim:!0};default:return{command:"xdg-open",args:[e]}}},Ax=e=>e.replace(/[&|<>^()%"]/g,t=>`^${t}`);import{createServer as Ox}from"node:http";var Mx=3e5,Ph=(e,t=Mx)=>new Promise((n,r)=>{let s,o=new Promise((c,m)=>{s={resolve:c,reject:m}}),i=Ox((c,m)=>{let f=new URL(c.url??"/","http://127.0.0.1");if(f.pathname!==vl){m.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Not found");return}Nx(f,m,e,s)}),a=setTimeout(()=>s.reject(new u("Timed out waiting for the browser login to complete.")),t);a.unref();let d=!1,l=()=>{d||(d=!0,clearTimeout(a),i.close())};o.then(l,l),i.once("error",c=>r(new u(`Could not start the loopback listener: ${c.message}`))),i.listen(0,"127.0.0.1",()=>{let{port:c}=i.address();n({redirectUri:`http://127.0.0.1:${c}${vl}`,waitForCode:()=>o,close:l})})}),Nx=(e,t,n,r)=>{if(e.searchParams.get("state")!==n){t.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Unexpected request");return}let s=e.searchParams.get("error");if(s){let i=e.searchParams.get("error_description");Sl(t,"Sign-in failed","Sign-in failed. You can close this window and return to the terminal."),r.reject(new u(`Authorization failed: ${i?`${s} (${i})`:s}`));return}let o=e.searchParams.get("code");if(!o){Sl(t,"Sign-in failed","No authorization code was returned. You can close this window."),r.reject(new u("Login failed: no authorization code was returned."));return}Sl(t,"Signed in","You are signed in to the ModelDesk CLI. You can close this window and return to the terminal."),r.resolve(o)},Sl=(e,t,n)=>{let r=`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${t}</title></head><body style="font-family: system-ui, sans-serif; text-align: center; padding: 3rem;"><h1>${t}</h1><p>${n}</p></body></html>`;e.writeHead(200,{"Content-Type":"text/html; charset=utf-8",Connection:"close"}).end(r)};import{createHash as Px,randomBytes as Lh}from"node:crypto";var Il=e=>e.toString("base64url"),Dh=()=>{let e=Il(Lh(32)),t=Il(Px("sha256").update(e).digest());return{verifier:e,challenge:t,method:"S256"}},_h=()=>Il(Lh(16));var jh={info:e=>process.stderr.write(`${e}
148
+ `)},si=async(e,t)=>{let{authorizationEndpoint:n,tokenEndpoint:r}=await Vt(e.issuer),s=Dh(),o=_h(),i=await Ph(o);try{let a=Lx(n,i.redirectUri,s.challenge,o);t.info(`Opening your browser to sign in to ${e.host}...`),t.info(`If it does not open automatically, visit:
149
+ ${a}`),Nh(a);let d=await i.waitForCode();return await Ch(r,{code:d,redirectUri:i.redirectUri,codeVerifier:s.verifier})}finally{i.close()}},Lx=(e,t,n,r)=>{let s=new URL(e);return s.searchParams.set("response_type","code"),s.searchParams.set("client_id",Ut),s.searchParams.set("redirect_uri",t),s.searchParams.set("scope",kh),s.searchParams.set("state",r),s.searchParams.set("code_challenge",n),s.searchParams.set("code_challenge_method","S256"),s.toString()};var us=6e4,oi=(e,t,n)=>{let r=e.refreshToken??t;if(r)return e.expiresInSeconds>0?{refreshToken:r,accessToken:e.accessToken,accessTokenExpiresAt:n+e.expiresInSeconds*1e3}:{refreshToken:r}},pr=class{constructor(t,n={}){this.instance=t;this.store=n.store??new ot,this.io=n.io??jh,this.now=n.now??Date.now,this.allowBrowserLogin=n.allowBrowserLogin??!0}instance;store;io;now;allowBrowserLogin;accessToken;accessTokenExpiresAt=0;endpoints;pendingLogin;async getAccessToken(){if(this.accessToken&&this.now()<this.accessTokenExpiresAt-us)return this.accessToken;let t=this.store.read(this.instance.host),n=Cl(t,this.now(),us);if(n)return this.remember({accessToken:n,expiresAt:t?.accessTokenExpiresAt??0});if(t){let r=await this.refresh({force:!1});if(r)return r}return this.login()}async refreshNow(){return this.refresh({force:!0})}async refresh({force:t}){let{tokenEndpoint:n}=await this.getEndpoints(),r=await this.store.transact(async s=>{let o=s.read(this.instance.host),i=t?void 0:Cl(o,this.now(),us);if(i)return{accessToken:i,expiresAt:o?.accessTokenExpiresAt??0};if(o)try{let a=await Rh(n,o.refreshToken);return s.write(this.instance.host,oi(a,o.refreshToken,this.now())),{accessToken:a.accessToken,expiresAt:this.now()+a.expiresInSeconds*1e3}}catch(a){if(Eh(a)){s.write(this.instance.host,void 0);return}throw a}});return r?this.remember(r):void 0}login(){return this.pendingLogin??=this.browserLogin().finally(()=>{this.pendingLogin=void 0}),this.pendingLogin}async browserLogin(){if(!this.allowBrowserLogin)throw new u(`Not logged in to ${this.instance.host}, and this run cannot open a browser to log in.`,{exitCode:b.NeedsHuman,hint:"Run 'modeldesk auth login' in a terminal, or 'modeldesk auth login --device' where no browser can reach this machine, then retry."});let t=await si(this.instance,this.io),n=oi(t,void 0,this.now());return n&&await this.store.save(this.instance.host,n),this.remember({accessToken:t.accessToken,expiresAt:this.now()+t.expiresInSeconds*1e3})}remember({accessToken:t,expiresAt:n}){return this.accessToken=t,this.accessTokenExpiresAt=n,t}async getEndpoints(){return this.endpoints||(this.endpoints=await Vt(this.instance.issuer)),this.endpoints}};var hs=e=>{let t=e.split(".");if(t.length===3)try{let n=Buffer.from(t[1],"base64url").toString("utf8"),r=JSON.parse(n);return r&&typeof r=="object"&&!Array.isArray(r)?r:void 0}catch{return}},ii=e=>{let t=hs(e);if(t)return t.name&&t.email?`${t.name} <${t.email}>`:t.email??t.name??t.sub};import{createInterface as _x}from"node:readline";var Fh={name:"@modeldesk/cli",version:"0.8.0",description:"Command-line interface (CLI) for the ModelDesk platform",keywords:["modeldesk","cli","documentation","content-bundle","respec","mim","information-model"],homepage:"https://modeldesk.io",repository:{type:"git",url:"git+https://github.com/model-desk/modeldesk.git",directory:"packages/cli"},license:"MIT",type:"module",bin:{modeldesk:"dist/modeldesk.js"},"//":"The ./headless export is the hosted MCP server's entry within this workspace, as TypeScript source. The published package is the binary alone: files ships dist, so the bin runs as before, and an import of @modeldesk/cli/headless or of any other path from it fails, as none is an API.",exports:{"./headless":"./src/headless.ts"},files:["dist","THIRD-PARTY-NOTICES.txt"],publishConfig:{access:"public"},engines:{node:">=22"},scripts:{build:"node esbuild.config.mjs",prepublishOnly:"npm run build",typecheck:"node scripts/api-types.mjs --check && node scripts/result-schemas.mjs --check && node scripts/guides.mjs --check && tsc --noEmit","generate:api":"node scripts/api-types.mjs","generate:result-schemas":"node scripts/result-schemas.mjs","generate:guides":"node scripts/guides.mjs",lint:"eslint","lint:fix":"eslint --fix",test:"vitest run","test:watch":"vitest"},devDependencies:{"@eslint/js":"^10.0.1","@modelcontextprotocol/client":"^2.4.0","@modelcontextprotocol/server":"^2.4.0","@modeldesk/content-bundle":"*","@types/node":"^24.19.2",esbuild:"^0.28.2",eslint:"^10.14.0","eslint-config-prettier":"^10.1.5","eslint-plugin-prettier":"^5.5.7",globals:"^17.14.0","openapi-typescript":"^7.13.0",prettier:"^3.9.10",typescript:"^6.0.3","typescript-eslint":"^8.72.2",vitest:"^5.1.0",yaml:"^2.9.1"}};var ur=Fh.version;var qh={out:e=>{process.stdout.write(e)},err:e=>{process.stderr.write(e)}},jx=async e=>{let t=_x({input:process.stdin,output:process.stderr});try{return await new Promise(n=>{t.once("close",()=>n(void 0)),t.question(e,n)})}finally{t.close()}},Fx=async()=>{process.stdin.setEncoding("utf8");let e="";for await(let t of process.stdin)e+=t;return e},Wh=()=>({env:process.env,cwd:process.cwd(),stdinIsTTY:!!process.stdin.isTTY,stdoutIsTTY:!!process.stdout.isTTY,ask:jx,readStdin:Fx}),$l=e=>rs(e.CI)&&e.CI?.toLowerCase()!=="false",Bh=e=>e.stdinIsTTY&&e.stdoutIsTTY&&!$l(e.env)&&rl(e.env)===void 0,Hh=e=>e.stdoutIsTTY&&!rs(e.env.NO_COLOR)&&e.env.TERM!=="dumb",Uh=e=>e?`modeldesk-cli/${ur} (${e})`:`modeldesk-cli/${ur}`;var Vh=q({path:["auth","login"],effect:"local",summary:"Log in through the browser, or with --device by approving a code on another device",description:"Opens the browser to sign in to the host and stores the credential in ~/.modeldesk/credentials.json (mode 0600), so later commands run unattended. With --device, prints a code to approve in a browser on any device instead, for SSH sessions, containers and remote agents that cannot receive the browser redirect. Machine credentials in the environment take precedence for API commands; this login only affects interactive use.",flags:{device:{type:"boolean",description:"Log in by approving a code in a browser on another device (OAuth device authorization)."}},examples:["modeldesk auth login","modeldesk auth login --device --host modeldesk.io"],run:async e=>{let t=le(e.env);if(t&&e.warn(`machine auth (${t} mode) is active in this environment and takes precedence for API commands; this login only affects interactive use.`),Wu(e),!e.flags.device&&$l(e.env))throw new u("A browser login cannot complete in CI.",{exitCode:b.NeedsHuman,hint:"Use a service account (MODELDESK_CLIENT_ID and MODELDESK_CLIENT_SECRET), or auth login --device."});let n=lr(e),r={info:a=>e.io.err(pe(`${a}
150
+ `))},s=e.flags.device?await Mh(n,r):await si(n,r),o=new ot,i=oi(s,void 0,Date.now());return i?await o.save(n.host,i):(await o.clearHost(n.host),e.warn("the server returned no refresh token, so later commands will re-open the browser each time instead of running unattended.")),{result:{host:n.host,identity:ii(s.accessToken),refreshTokenStored:!!s.refreshToken}}},render:({host:e,identity:t})=>{let n=t?` as ${t}`:"";return`Logged in to ${e}${n}.`}});var Gh=q({path:["auth","logout"],effect:"local",summary:"Remove the stored credential for the active host",examples:["modeldesk auth logout","modeldesk auth logout --host modeldesk.io"],description:"Removes the refresh token stored for the host. Machine credentials in the environment are untouched.",run:async e=>{let t=le(e.env);t&&e.warn(`machine auth (${t} mode) is active in this environment and takes precedence for API commands; this logout does not remove machine credentials.`);let n=lr(e);return{result:{host:n.host,removed:await new ot().clearHost(n.host)}}},render:({host:e,removed:t})=>t?`Logged out of ${e}.`:`No stored credential for ${e}.`});var xl=class{constructor(t,n,r,s={}){this.instance=t;this.mode=n;this.mint=r;this.now=s.now??Date.now,this.discover=s.discover??Vt}instance;mode;mint;now;discover;accessToken;accessTokenExpiresAt=0;endpoints;inflight;async getAccessToken(){return this.accessToken&&this.now()<this.accessTokenExpiresAt-us?this.accessToken:(this.inflight||(this.inflight=this.mintFresh().finally(()=>{this.inflight=void 0})),this.inflight)}async mintFresh(){let{tokenEndpoint:t}=await this.getEndpoints(),n;try{n=await this.mint(t)}catch(r){throw Wx(r,this.mode)}if(n.expiresInSeconds<=0)throw new u("The token response did not include a token lifetime (expires_in), so the machine token cannot be cached. This indicates a server problem.");return this.accessToken=n.accessToken,this.accessTokenExpiresAt=this.now()+n.expiresInSeconds*1e3,n.accessToken}async getEndpoints(){return this.endpoints||(this.endpoints=await this.discover(this.instance.issuer)),this.endpoints}},qx=async(e,t,n)=>{let r;try{r=await fetch(`${e}&audience=${encodeURIComponent(n)}`,{headers:{Authorization:`bearer ${t}`,Accept:"application/json"},signal:AbortSignal.timeout(3e4)})}catch(o){throw new u(`Could not reach the GitHub OIDC token endpoint (${o.message}).`,b.Transient)}if(!r.ok)throw new u(`The GitHub OIDC token request failed (${r.status} ${r.statusText}). Check that the workflow grants 'permissions: id-token: write'.`);let s=await r.json().catch(()=>{});if(!s?.value)throw new u("The GitHub OIDC token response did not include a token value. Check that the workflow grants 'permissions: id-token: write'.");return s.value},ai=(e,t,n={})=>{let r=t.mode==="secret"?s=>Sh(s,{clientId:t.clientId,clientSecret:t.clientSecret}):async s=>Ih(s,await qx(t.oidcRequestUrl,t.oidcRequestToken,e.issuer));return new xl(e,t.mode,r,n)},Wx=(e,t)=>{if(!(e instanceof Gt)||!e.oauthError)return e;if(t==="secret")return e.oauthError==="invalid_client"?new u(`${e.message} ${Du}`):e;if(e.errorDescription===void 0)return e.oauthError==="invalid_grant"?new u(`${e.message} ${_u}`):e;let n=ju[e.errorDescription];return n?new u(`${e.message} \u2014 ${n}`):e};var Kh="Run 'modeldesk auth login'.",Yh=q({path:["auth","status"],effect:"read",summary:"Show the active host, logged-in identity, and token validity",examples:["modeldesk auth status","modeldesk auth status --host modeldesk.io --json"],description:"Proves the credential the CLI would use: a machine mode (service-account secret or GitHub federation) mints a token, interactive mode silently refreshes the stored login. Exits 6 when not logged in or the stored login was rejected, and 7 when the auth server could not be reached.",run:async e=>{let t=ls(e.env);if(t.mode==="error")throw new u(t.message);let n=e.instance();return e.print(`Host: ${n.host}
151
+ `),e.print(`API: ${n.apiBase}
152
+ `),t.mode==="secret"||t.mode==="federated"?Bx(e,n,t):Hx(e,n)}}),Bx=async(e,t,n)=>{let r={host:t.host,apiBase:t.apiBase,mode:n.mode},s=n.mode==="secret"?{clientId:n.clientId,secretFingerprint:Lu(n.clientSecret)}:{repository:e.env.GITHUB_REPOSITORY??"unknown",ref:e.env.GITHUB_REF??"unknown"};n.mode==="secret"?e.print(`Auth: service account (secret mode), client ${s.clientId}, secret ${s.secretFingerprint}
153
+ `):e.print(`Auth: federated (GitHub Actions), repository ${s.repository}, ref ${s.ref}
154
+ `);let o=await ai(t,n).getAccessToken(),i=hs(o)??{},a=typeof i.sub=="string"?i.sub:"unknown",d=typeof i.mdsk_org=="string"?i.mdsk_org:"unknown",l=typeof i.scope=="string"?i.scope.trim():"";return e.print(`Status: credential valid. Account ${a}, organization ${d}.
155
+ `),e.print(l?`Scopes: ${l}
156
+ `:`Scopes: enforced server-side from the account's current scopes.
157
+ `),{result:{...r,...s,credentialValid:!0,account:a,organization:d,scopes:l}}},Hx=async(e,t)=>{let n={host:t.host,apiBase:t.apiBase,mode:"interactive"},r=new ot;if(!r.read(t.host)){let s=`not logged in. ${Kh}`;return e.print(`Status: ${s}
158
+ `),{result:{...n,credentialValid:!1,problem:s},exitCode:b.NeedsHuman}}try{let s=await new pr(t,{store:r,allowBrowserLogin:!1}).refreshNow();if(!s)throw new u("The stored credential was rejected.",b.NeedsHuman);let o=ii(s),i=o?` as ${o}`:"";return e.print(`Status: logged in${i} (credential valid).
159
+ `),{result:{...n,credentialValid:!0,identity:o}}}catch(s){let o=`the stored credential could not be verified (it may be expired or revoked, or the server is unreachable). ${Kh}`;e.print(`Status: ${o}
160
+ `);let i=s instanceof u&&s.exitCode===b.Transient;return{result:{...n,credentialValid:!1,problem:o},exitCode:i?b.Transient:b.NeedsHuman}}};var Kt=e=>e.superAdmin===!0,Xh=async(e,t)=>{let[n,r]=await Promise.all([t.models?e.models.list({ownerId:t.ownerId,metamodel:t.metamodel}):void 0,t.metamodels?e.metamodelModels.list():void 0]),s=new Set((r?.items??[]).map(o=>o.id));return[...(n?.items??[]).filter(o=>!s.has(o.id)).map(o=>({model:o,kind:"model"})),...(r?.items??[]).map(o=>({model:o,kind:"metamodel"}))]},zh=e=>{let t;return()=>t??=e()},Jh=new WeakMap,ce=(e,t)=>{let n=Jh.get(e)??new Map;Jh.set(e,n);let r=n.get(t);if(r!==void 0)return r;let s=async()=>t,o=zh(async()=>e.api().models.identity(await s())),i=zh(async()=>e.api().branches.list(await s())),a={id:s,identity:o,branches:i};return n.set(t,a),a};var Qh=(e,t,n={})=>{let r=ls(t);switch(r.mode){case"error":throw new u(r.message);case"secret":case"federated":return ai(e,r);case"interactive":return new pr(e,{allowBrowserLogin:n.interactive??!0})}};var Ux=6e4,Zh={unauthorized:"Run 'modeldesk auth login' and try again.",forbidden:"Your account may lack access to this model."},Vx={unauthorized:Go.unauthorized,forbidden:Go.forbidden,notFound:Go.notFound},Gx=new Set(["type","title","status","detail","instance"]),Kx={"change-validation-failed":b.Validation,"draft-target-taken":b.Conflict,"invalid-branch-name":b.Validation,"branch-limit-reached":b.Validation,"ambiguous-merge-base":b.Failure,"invalid-resolution":b.Validation},U=class extends u{status;problem;constructor(t,n,r,s){super(t,s),this.name="ApiError",this.status=n,this.problem=r}},eg=(e,t)=>new Tl(e.apiBase,Qh(e,t.env,{interactive:t.interactive}),{hints:le(t.env)?Vx:Zh,userAgent:Uh(t.agentHost)}),Tl=class{constructor(t,n,r={}){this.apiBase=t;this.tokens=n;this.hints=r.hints??Zh,this.userAgent=r.userAgent}apiBase;tokens;hints;userAgent;async getJson(t,n){return gs(await this.request("GET",t,{query:n}),t)}async getJsonIfChanged(t,n,r){let s=await this.request("GET",t,{query:r,ifNoneMatch:n});if(s.status===304)return{notModified:!0};let{body:o,bytes:i}=await Yx(s,t);return{notModified:!1,body:o,etag:s.headers.get("etag")??void 0,bytes:i}}async postJson(t,n,r){return gs(await this.request("POST",t,{query:r,body:n}),t)}async postJsonWithHeaders(t,n,r){let s=await this.request("POST",t,{query:r,body:n});return{body:await gs(s,t),headers:s.headers}}async putJson(t,n,r){return gs(await this.request("PUT",t,{query:r,body:n}),t)}async delete(t,n){return gs(await this.request("DELETE",t,{query:n}),t)}async getBytes(t,n,r){let s=await this.request("GET",t,{query:r,accept:n});return di(t,async()=>new Uint8Array(await s.arrayBuffer()))}async openEventStream(t,n){let r=await this.request("GET",t,{accept:"text/event-stream",signal:n});if(r.body===null)throw new u(`The event stream at ${t} opened without a body.`,{exitCode:b.Transient});return r.body}async accessTokenClaims(){return hs(await this.tokens.getAccessToken())??{}}async request(t,n,r){let s=await this.tokens.getAccessToken(),o=zx(this.apiBase,n,r.query),i={Authorization:`Bearer ${s}`,Accept:r.accept??"application/json",...this.userAgent?{"User-Agent":this.userAgent}:{},...r.body!==void 0?{"Content-Type":"application/json"}:{},...r.ifNoneMatch?{"If-None-Match":r.ifNoneMatch}:{}},a;try{a=await fetch(o,{method:t,headers:i,...r.body!==void 0?{body:JSON.stringify(r.body)}:{},signal:r.signal??AbortSignal.timeout(Ux)})}catch(d){throw new u(`Could not reach ${this.apiBase} (${d.message}).`,{exitCode:b.Transient,hint:"Check the host and that the ModelDesk server is reachable."})}if(a.status===304&&r.ifNoneMatch)return a;if(!a.ok)throw await nT(a,n,this.hints);return a}},di=async(e,t)=>{try{return await t()}catch(n){throw n instanceof SyntaxError?new u(`The response from ${e} is not JSON (${n.message}).`):new u(`Reading the response from ${e} failed (${n.message}).`,{exitCode:b.Transient})}},gs=(e,t)=>e.status===204||e.headers.get("content-length")==="0"?Promise.resolve(void 0):di(t,()=>e.json()),Yx=async(e,t)=>{if(e.status===204||e.headers.get("content-length")==="0")return{body:void 0,bytes:0};let n=await di(t,()=>e.text());return{body:await di(t,async()=>JSON.parse(n)),bytes:Buffer.byteLength(n,"utf8")}},zx=(e,t,n)=>{let r=new URL(t,e);if(n)for(let[s,o]of Object.entries(n))o!==void 0&&r.searchParams.set(s,o);return r.toString()},Jx=(e,t)=>{let n=t===void 0?void 0:Kx[t];return n!==void 0?n:e===401?b.NeedsHuman:e===404?b.NotFound:e===409?b.Conflict:e===429||e>=500?b.Transient:b.Failure},Xx=e=>{if(!e||e==="about:blank")return;let t="/problems/",n=e.lastIndexOf(t);return n===-1?e:e.slice(n+t.length)},Qx=async e=>{try{if((e.headers.get("content-type")??"").includes("json")){let n=await e.json();if(n!==null&&typeof n=="object"&&!Array.isArray(n))return n}}catch{}},Zx=e=>Object.fromEntries(Object.entries(e??{}).filter(([t])=>!Gx.has(t))),eT="Run 'modeldesk model list' to see the ids; 'modeldesk model list --kind metamodel' for a metamodel-model.",tT=(e,t)=>t?.startsWith("Model not found")?/^\/(?:metamodel-)?models\/([0-9a-f-]{36})(?:[/?]|$)/.exec(e)?.[1]:void 0,nT=async(e,t,n)=>{let r=await Qx(e),s=r?.detail??r?.title,o=s?`${e.status} ${s}`:`${e.status} ${e.statusText}`.trim(),i=Xx(r?.type),{requestId:a,...d}=Zx(r),l={exitCode:Jx(e.status,i),type:i,requestId:typeof a=="string"?a:e.headers.get("x-request-id")??void 0,details:typeof a=="string"||a===void 0?d:{requestId:a,...d}};if(e.status===401)return new U(`Authentication failed (${o}).`,401,r,{...l,hint:n.unauthorized,hosted:{hint:"The person you work for connects ModelDesk again."}});if(e.status===403)return new U(`Not authorized (${o}).`,403,r,{...l,hint:n.forbidden});let c=e.status===404?tT(t,s):void 0;return c!==void 0?new U(`No model has the id '${c}'.`,404,r,{...l,hint:n.notFound??eT,hosted:{hint:m=>`Call ${m("model list")} to see the ids.`}}):e.status===404&&n.notFound?new U(`Not found (${o}).`,404,r,{...l,hint:n.notFound}):new U(`Request to ${t} failed: ${o}`,e.status,r,l)};var rT="@Root",sT=e=>{let t=new Map;for(let[n,r]of Object.entries(e?.relations??{}))for(let s of Object.values(r))for(let o of s){let i=`${n}\0${o.id}`;t.has(i)||t.set(i,t.size)}return t},Yt=e=>{let{elements:t}=e,n=a=>Object.hasOwn(t,a),r=e.rootElementId??Object.values(t).find(a=>a.type===rT)?.id;if(r===void 0||!n(r))throw new u("The model read carries no root element, so its tree cannot be built.");let s=new Map,o=new Map;for(let[a,d]of Object.entries(e.elementIndexEntries)){if(!n(a))continue;let l=(d.owners??[]).filter(c=>n(c.id));s.set(a,l);for(let c of l){let m=o.get(c.id)??[];m.push({id:a,relation:c.relation}),o.set(c.id,m)}}for(let[a,d]of o){let l=sT(t[a]),c=m=>l.get(`${m.relation}\0${m.id}`)??Number.MAX_SAFE_INTEGER;d.sort((m,f)=>c(m)-c(f))}let i=e.elementLabels??{};return{rootId:r,element:a=>n(a)?t[a]:void 0,label:a=>Object.hasOwn(i,a)?i[a]:void 0,owners:a=>s.get(a)??[],children:a=>o.get(a)??[]}},In=e=>e.startsWith("@"),hr={internal:{type:"boolean",description:"Include the platform's internal `@` elements."}},Al=e=>e.replace(/[\\/]/g,t=>`\\${t}`),it=(e,t={})=>{let n=c=>{let m=e.element(c);return m!==void 0&&(t.internal===!0||!In(m.type))},r=c=>{let m=new Set;return e.children(c).filter(f=>m.has(f.id)?!1:(m.add(f.id),!0))},s=c=>{let m=e.label(c);return m===void 0||m.trim()===""?void 0:m},o=new Map,i=c=>{let m=o.get(c);if(m!==void 0)return m;let f=new Map;for(let{id:h}of r(c)){let p=s(h);p!==void 0&&n(h)&&f.set(p,(f.get(p)??0)+1)}return o.set(c,f),f},a=(c,m)=>{let f=s(m);return f===void 0||(i(c).get(f)??0)>1?m:Al(f)},d=new Map,l=(c,m,f,h)=>{let p=e.element(c.id);if(p===void 0||!n(c.id)||t.maxDepth!==void 0&&f>t.maxDepth)return[];let g=h===""?a(m,c.id):`${h}/${a(m,c.id)}`,w=d.get(c.id);w===void 0&&d.set(c.id,g);let k=w===void 0?r(c.id).flatMap(v=>l(v,c.id,f+1,g)):[],C=t.types===void 0||t.types.has(p.type);if(!C&&k.length===0)return[];let R=e.label(c.id);return[{id:c.id,...R===void 0?{}:{label:R},type:p.type,depth:f,parentId:m,relation:c.relation,path:g,...e.owners(c.id).length>1?{multiOwned:!0}:{},...w===void 0?{}:{subtreeAt:w},...C?{}:{context:!0}},...k]};return d.set(e.rootId,""),r(e.rootId).flatMap(c=>l(c,e.rootId,1,""))},zt=e=>{let t=new Set;return e.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))};var vt={kinds:["draft","head","branch","commit"],default:"working"},Oe={kinds:["draft","head","branch"],default:"working"},Ml={kinds:["draft","head","branch"],default:"head"},me={kinds:["draft","head","branch"],default:"working"},xn={kinds:["head","branch"],default:"head"},Rt={kinds:["branch"],required:!0},Nl={kinds:["branch"],default:"draft"},tg={kinds:["commit"],default:"main"},ng={kinds:["release","branch"],required:!0,names:{noun:"A dependency",listing:"modeldesk pin list <model>"}},rg={kinds:["release","branch"],required:!0},sg={noun:"A metamodel",listing:"modeldesk metamodel list"},li={kinds:["release"],default:"main",names:sg},og={kinds:[],default:"main",names:sg},ci={kinds:["release"],default:"main",names:{noun:"An extension",listing:"modeldesk metamodel extensions <metamodel>"}},Ae={kinds:[],default:"main"},ig="ref-not-found",mi=e=>e instanceof U&&(e.status===404||e.type===ig),dt=async e=>{try{return await e()}catch(t){if(mi(t))return;throw t}},fi=e=>({id:e.branch.id,name:e.branch.name,main:!0,head:e.branch.head.id}),at=e=>({id:e.id,name:e.name,main:e.main,head:e.head.id}),oT=(e,t)=>e!==void 0&&e.headCommitId!==e.baselineCommitId?{kind:"draft",draft:e}:{kind:"branch",branch:t},iT={working:{kind:"working"},head:{kind:"head"},main:{kind:"branch",name:"main"},draft:{kind:"draft"}},$n=(e,t)=>e.localeCompare(t,void 0,{sensitivity:"accent"})===0,Pl="branch-gone",aT=(e,t,n)=>new u(`Branch ${y(t.name)} (${t.id}) of ${y(e)} is gone`+(n===void 0?".":`; the branch named ${y(n.name)} now is another one (${n.id}), and it is not taken for it.`),{exitCode:b.NotFound,type:Pl,details:{branch:{id:t.id,name:t.name},...n&&{namesake:{id:n.id,name:n.name}}}}),Ll="Ask the person you work for to discard the draft in the app, or address the model at a branch.",Ol=(e,t={})=>new u(e,{exitCode:b.NotFound,type:ig,...t}),Z=async(e,t,n)=>{cl(t,n);let r=e.api(),s=ce(e,t.model),o=await s.id(),[i,a]=await Promise.all([s.identity(),dt(()=>r.models.draft(o))]),d=fi(i),l=async w=>{if(w===d.id)return d;let k=(await s.branches()).find(C=>C.id===w);return k===void 0?void 0:at(k)},c=async w=>{let k=await l(w);if(k===void 0)throw Ol(`Your draft of ${y(i.name)} targets a branch that is gone (${w}).`,{hint:"Discard the draft with 'modeldesk draft discard', or address the model at a branch.",hosted:{hint:Ll}});return k},m=async w=>{if($n(w,d.name))return d;let k=await s.branches(),C=k.find(R=>$n(R.name,w));if(C===void 0)throw Ol(`${y(i.name)} has no branch named '${y(w)}'.`,{details:{branches:k.map(R=>R.name)}});return at(C)},f=a===void 0?void 0:{...a,target:await c(a.targetRefId)},h=f?.target??d,p=t.ref.kind==="working"&&"default"in n?iT[n.default]:t.ref,g=await(async()=>{switch(p.kind){case"working":return oT(f,h);case"head":return{kind:"branch",branch:h};case"draft":if(f===void 0)throw Ol(`You hold no draft of ${y(i.name)}.`,{hint:"Leave the ref out to read the branch, or stage a change to open a draft."});return{kind:"draft",draft:f};case"branch":return{kind:"branch",branch:await m(p.name)};case"branch-id":{let w=await l(p.id);if(w===void 0){let k=(await s.branches()).find(C=>$n(C.name,p.name));throw aT(i.name,p,k&&at(k))}return{kind:"branch",branch:w}}case"commit":return{kind:"commit",id:p.id};case"release":throw new u(`A release ref is not readable here (${t.text}).`,{exitCode:b.Usage})}})();return{id:o,name:i.name,ref:g,main:d,working:h,draft:f,...n.kinds.length===0&&!h.main?{note:`reads main; your draft targets ${h.name}`}:{}}},Xe=({ref:e})=>{if(e.kind!=="branch")throw new Error(`A branch-only slot resolved to a ${e.kind}.`);return e.branch},Qe=e=>{switch(e.kind){case"branch":return{ref:e.branch.id};case"draft":return{ref:e.draft.id};case"commit":return{commit:e.id}}},dT=e=>{switch(e.kind){case"branch":return{kind:"branch",id:e.branch.id,name:e.branch.name};case"draft":return{kind:"draft",id:e.draft.id,branch:{id:e.draft.target.id,name:e.draft.target.name}};case"commit":return{kind:"commit",id:e.id}}},re=({ref:e,draft:t,note:n})=>{let r=dT(e),s=t!==void 0&&e.kind==="branch"&&e.branch.id!==t.target.id;return{...r,...s?{draftIgnored:!0}:{},...n===void 0?{}:{note:n}}},lT=(e,t)=>{switch(e.kind){case"draft":return`Reading your draft of ${t}, aimed at ${y(e.branch.name)}.`;case"branch":return`Reading branch ${y(e.name)} of ${t}.`;case"commit":return`Reading commit ${e.id} of ${t}.`}},Ie=(e,t)=>{let n=y(t.name);return[lT(e,n),...e.draftIgnored?["Your draft aims at another branch and was not read."]:[],...e.note?[`${e.note[0].toUpperCase()}${e.note.slice(1)}.`]:[]].join(" ")},gr=async(e,t,n)=>{let r=await Z(e,t,n),s=await e.content.read(e.api(),r.id,r.ref);return{model:{id:r.id,name:r.name},ref:re(r),resolved:r,read:s,tree:Yt(s)}};var pi=e=>e.draft?.id??e.branch.id,Dl="draft-target-taken",ys=(e,t,n,r,s=r)=>{let o=y(e.name),i=t.changeCount>0,a=y(t.target.name),d=m=>`Your draft of ${o} aims at ${a}`+(i?` and holds ${P(t.changeCount,"staged change")}`:" and holds no staged change")+`, so ${m}.`,l=`${e.id}@${a}`,c=`${e.id}@${y(n.name)}`;return new u(d(r),{exitCode:b.Conflict,type:Dl,hint:i?`Commit or discard your changes on ${a} first: 'modeldesk draft commit ${e.id}@${a}' or 'modeldesk draft discard ${e.id}@${a}'. Or address ${e.id}@${a} to work where your draft aims.`:`Run 'modeldesk draft open ${e.id}@${y(n.name)}', which loses nothing.`,details:{targetRefId:t.target.id,targetRefName:t.target.name,requestedRefId:n.id,requestedRefName:n.name,changeCount:t.changeCount},hosted:{reason:d(s),hint:m=>i?`Commit your changes on ${a} first with ${m("draft commit")} (model ${l}), or ask the person you work for to discard them in the app. Or address ${l} to work where your draft aims.`:`Call ${m("draft open")} with model ${c}, which loses nothing.`}})},lt=async(e,t)=>{let n=await Z(e,t,me),{ref:r,draft:s}=n;if(r.kind==="commit")throw new u(`A change cannot be staged at a commit (${t.text}); address a branch.`,{exitCode:b.Usage,type:"ref-unsupported"});let o=r.kind==="branch"?r.branch:r.draft.target;if(s!==void 0&&s.target.id!==o.id)throw ys(n,s,o,`nothing was staged on ${y(o.name)}`);let i=await e.content.read(e.api(),n.id,s?{kind:"draft",draft:s}:{kind:"branch",branch:o});return{address:t,model:{id:n.id,name:n.name},branch:o,draft:s,resolved:n,read:i,tree:Yt(i),head:i.branch.head.id}};var cT=e=>({id:e.id,createdAt:e.createdAt,...e.message?{message:e.message}:{},...e.requestId?{requestId:e.requestId}:{},actionTypes:[...new Set(e.actions.map(t=>t.type))].sort(),elementIds:e.actions.reduce((t,n)=>({...t,[n.type]:[...t[n.type]??[],...n.elementIds??[]]}),{})}),He=async(e,t,n,r)=>{let s=[],o;for(;;){let i=r===void 0?ws:Math.min(ws,r-s.length),a=(await e.models.commits(t,{ref:n,limit:i,cursor:o})).items;if(s.push(...a.map(cT)),a.length<i||r!==void 0&&s.length>=r)return s;o=a.at(-1)?.id}},Me={...Hu(Nl),description:"The model's id, from model list, or dataset/<id>. Your draft wherever it aims; a model's @<branch> asserts where it aims, and a draft aimed elsewhere is refused (exit 5) with nothing done."},mT=5,ws=100,dg=async(e,t,n)=>{let r;for(let s=0;s<mT;s++){let o=await e(r);for(let i of o){if(i.requestId===t)return i;if(i.id===n)return}if(o.length<ws)return;r=o.at(-1)?.id}},ui=(e,t)=>({url:e.webUrl({kind:"model",modelId:t}),changes:(n,r)=>He(e.api(),t,n,r)}),bs=async(e,t)=>{let n=e.api(),r=ce(e,t),s=await r.identity(),o=s.id,i=n.drafts.model,a=async d=>{if(d===s.branch.id)return fi(s);let l=(await r.branches()).find(c=>c.id===d);if(l===void 0)throw new u(`Your draft of ${y(s.name)} targets a branch that is gone (${d}).`,{exitCode:b.NotFound,type:"ref-not-found",hint:"Discard the draft with 'modeldesk draft discard', or address the model at a branch.",hosted:{hint:Ll}});return at(l)};return{ref:{kind:"model",id:o,name:s.name},url:e.webUrl({kind:"model",modelId:o}),read:()=>dt(()=>n.models.draft(o)),workingBranch:async d=>{let l=d===void 0?fi(s):await a(d.targetRefId);return{branch:l,head:l.head}},branch:a,undo:async d=>({headCommitId:(await i.undo(o,d)).commitId}),commit:async d=>{let l=await i.commit(o,d),{id:c,message:m,requestId:f,createdAt:h,actionTypes:p}=l.commit;return{branch:await a(l.refId),commit:{id:c,...m?{message:m}:{},...f?{requestId:f}:{},createdAt:h,actionTypes:p},draftHeadCommitId:l.draftHeadCommitId}},rebase:async d=>{let l=await i.rebase(o,d);return{draft:l.draft,dropped:l.dropped,closureChanged:l.closureChanged,schemaChanged:l.schemaChanged}},discard:d=>i.discard(o,d),changes:(d,l)=>He(n,o,d,l),findLanding:async(d,l)=>{let c=await dg(async m=>(await n.models.commits(o,{ref:l.targetRefId,limit:ws,cursor:m})).items,d,l.baselineCommitId);return c&&{id:c.id,message:c.message,requestId:c.requestId,createdAt:c.createdAt,actionTypes:[...new Set(c.actions.map(m=>m.type))].sort()}}}},fT=async(e,t)=>{let n=e.api(),r=await n.datasets.get(t),s=n.drafts.dataset,o=async(i,a)=>(await n.datasets.commits(r.id,{limit:i,cursor:a})).items??[];return{ref:{kind:"dataset",id:r.id,name:r.name},read:()=>dt(()=>s.get(r.id)),branch:async i=>({id:i}),workingBranch:async i=>{let[a]=await o(1);if(a===void 0)throw new u(`Dataset ${r.name} has no commits, so its branch head is unknown.`);return{branch:i===void 0?void 0:{id:i.targetRefId},head:a.id}},undo:async i=>{let{draft:a}=await s.undo(r.id,i);return{headCommitId:a.headCommitId,changeCount:a.changeCount}},commit:async i=>{let{refId:a,commit:d}=await s.commit(r.id,i);return{branch:{id:a},commit:{id:d.id,...d.message?{message:d.message}:{},...d.requestId?{requestId:d.requestId}:{},...d.createdAt?{createdAt:d.createdAt}:{},...d.rowsChanged===void 0?{}:{rowsChanged:d.rowsChanged}}}},rebase:async i=>{let a=await s.rebase(r.id,i);return{draft:a.draft,dropped:a.dropped.map(d=>({commitId:d.id,...d.requestId?{requestId:d.requestId}:{},...d.message?{message:d.message}:{},...d.rowsChanged===void 0?{}:{rowsChanged:d.rowsChanged}}))}},discard:i=>s.discard(r.id,i),findLanding:async(i,a)=>{let d=await dg(l=>o(ws,l),i,a.baselineCommitId);return d&&{id:d.id,message:d.message,requestId:d.requestId,rowsChanged:d.rowsChanged}}}},pT=async(e,t,n)=>{let r=await Z(e,t,Nl),{draft:s,ref:o}=r;if(s!==void 0&&o.kind==="branch"&&s.target.id!==o.branch.id)throw ys(r,s,o.branch,`'modeldesk ${n}' did nothing on ${y(o.branch.name)}`,`'${n}' did nothing on ${y(o.branch.name)}`)},ag=new WeakMap,Ne=e=>{let t=ag.get(e);if(t!==void 0)return t;let{resource:n}=e.args,r=n.kind==="dataset"?fT(e,n.id):(async()=>(n.address.ref.kind==="branch"&&await pT(e,n.address,e.commandName),bs(e,n.address.model)))();return ag.set(e,r),r},uT=e=>{if(e instanceof u&&e.type==="feature-not-enabled"){let{feature:t,organizationId:n}=e.details,r=typeof t=="string"?`The '${t}' feature`:"A feature this change needs",s=typeof n=="string"?` (${n})`:"";return new u(`${r} is not enabled for this organization${s}.`,{type:e.type,details:e.details,requestId:e.requestId,hint:"Ask ModelDesk to enable the feature for your organization, or leave out the change that needs it."})}return e},X=async e=>{try{return await e()}catch(t){throw uT(t)}},se=e=>`${e.kind} ${y(e.name)}`,yr=(e,t)=>"name"in t?`${e.id}@${y(t.name)}`:e.id,je=500;var lg={draftOpen:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}}},draft:{type:"object",properties:{id:{type:"string"},targetRefId:{type:"string"},baselineCommitId:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"},createdAt:{type:"string"},updatedAt:{type:"string"},movesBaseTo:{type:"string"},handoff:{type:"object",properties:{summary:{type:"string"},headCommitId:{type:"string"},at:{type:"string"}}},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}}},opened:{type:"boolean",description:"False when the draft already aimed at the branch and was left as it was. One of false, true."},reopenedFrom:{type:"object",properties:{id:{type:"string"},name:{type:"string"}},description:"The branch an empty draft aimed at before it was discarded and opened on this one."}},required:["schemaVersion","model","ref","draft","opened"]}};var mg=({id:e,name:t})=>({id:e,name:t}),cg=({id:e,targetRefId:t,baselineCommitId:n,headCommitId:r,changeCount:s,createdAt:o,updatedAt:i},a)=>({id:e,targetRefId:t,baselineCommitId:n,headCommitId:r,changeCount:s,createdAt:o,updatedAt:i,target:mg(a)}),_l=async(e,t,n)=>{let{draft:r}=t;if(r?.target.id===n.id)return{draft:cg(r,n),opened:!1};if(r!==void 0&&r.changeCount>0)throw ys(t,r,n,`no draft was opened on ${y(n.name)}`);let s=e.api().drafts.model;if(r!==void 0)try{await s.discard(t.id,r.headCommitId)}catch(i){if(!(i instanceof U&&i.status===404))throw i}let o=await s.open(t.id,n.id);return{draft:cg(o,n),opened:!0,...r===void 0?{}:{reopenedFrom:mg(r.target)}}},jl=(e,t)=>{let n=y(e.name),r=y(t.draft.target.name);return t.opened?t.reopenedFrom===void 0?`Opened your draft of ${n} on ${r}.`:`Discarded your empty draft of ${n} on ${y(t.reopenedFrom.name)} and opened one on ${r}.`:`Your draft of ${n} already aims at ${r}; it was left as it was.`},fg=D({path:["draft","open"],effect:"stage",summary:"Aim your draft of a model at a branch",description:"Opens your draft of the model on the branch, so the writes that name no branch stage there. A draft already on the branch is left as it is (opened: false). A draft on another branch that holds nothing is discarded and opened here, which loses nothing (reopenedFrom names where it was). A draft holding staged changes on another branch is refused (exit 5): commit or discard them first. Only this command and 'branch create --open' discard a draft on your behalf. A dataset has no branches, so it takes a model.",positionals:[_(Rt)],examples:["modeldesk draft open <model>@feat/x","modeldesk draft open <model>@agent/tidy-names --json"],mcp:{name:"draft_open",description:"Aims your draft of the model at a branch (model@<branch>), so calls that name no ref stage there. A draft already there is kept; an empty draft elsewhere moves here; a draft holding changes elsewhere is refused. For new work, branch_create with open: true cuts a branch and opens it in one call."},resultSchema:lg.draftOpen,run:async e=>X(async()=>{let t=await Z(e,e.args.model,Rt),n=await _l(e,t,Xe(t));return{result:{model:{id:t.id,name:t.name},ref:{kind:"draft",id:n.draft.id,branch:n.draft.target},...n}}}),render:e=>jl(e.model,e)});var pg={branchCreate:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},name:{type:"string",description:"The name asked for, trimmed as the server trims it."},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"},main:{type:"boolean",description:"One of false, true."},head:{type:"string"}},description:"The branch created, or the one that has the name when asked to take it; absent under a dry run that would create it."},from:{type:"object",properties:{id:{type:"string"},name:{type:"string"}},description:"The branch it is created from: the working branch, or the one the address named."},created:{type:"boolean",description:"False when the name was taken and the branch that has it answered instead, and under a dry run. One of false, true."},dryRun:{type:"boolean",description:"Always true."},open:{type:"object",properties:{draft:{type:"object",properties:{id:{type:"string"},targetRefId:{type:"string"},baselineCommitId:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"},createdAt:{type:"string"},updatedAt:{type:"string"},movesBaseTo:{type:"string"},handoff:{type:"object",properties:{summary:{type:"string"},headCommitId:{type:"string"},at:{type:"string"}}},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}}},opened:{type:"boolean",description:"False when the draft already aimed at the branch and was left as it was. One of false, true."},reopenedFrom:{type:"object",properties:{id:{type:"string"},name:{type:"string"}},description:"The branch an empty draft aimed at before it was discarded and opened on this one."}},description:"When asked to open the branch: where your draft now aims."},note:{type:"string",description:"Under an agent host, for a name outside `agent/`: where an agent may commit without a person's say-so."}},required:["schemaVersion","model","name","from","created"]}};var yT={draft:"'@draft' in an address means your draft",head:"'@head' in an address means your working branch head",main:"'@main' in an address means the main branch"},wT=e=>{let t=yT[e.toLowerCase()]??(Y(e)?"a UUID in an address is a commit":void 0);if(t!==void 0)throw new u(`A branch cannot be named '${y(e)}': ${t}.`,{exitCode:b.Validation,type:"invalid-branch-name",hint:"Pick another name.",details:{rule:"reserved-name"}})},bT=(e,t,n,r)=>{let{branch:s}=e;return s===void 0?`Would create branch ${t} of ${n} from ${r}; nothing was created (dry run).`:e.dryRun?`Branch ${t} of ${n} exists (${s.id}); --exist-ok would use it; nothing was created (dry run).`:e.created?`Created branch ${t} of ${n} from ${r}: ${s.id}`:`Branch ${t} of ${n} already exists: ${s.id}`},ug=D({path:["branch","create"],effect:"create",summary:"Create a branch of a model",description:`Creates a branch at the head of your working branch (the one your draft aims at, else main), or of the branch the address names. A name another branch already has (in any case) exits 5 unless --exist-ok, which answers that branch with created: false, so a retried script converges. A name the server refuses exits 4 naming the rule; so do 'draft', 'head', 'main' and a UUID, which an address cannot reach as a branch. --open then aims your draft at the branch as draft open does, discarding an empty draft elsewhere. An agent's own branch is named ${Wt}<topic>: a draft landing there needs no MODELDESK_ALLOW_COMMIT=1, since a person reviews and merges the branch in the app.`,positionals:[_(xn),{name:"name",type:"string",required:!0,description:"The new branch name."}],flags:{open:{type:"boolean",description:"Aim your draft at the branch, as draft open does."},"exist-ok":{type:"boolean",description:"Answer the branch that already has the name (created: false) instead of exiting 5.",toolDescription:"Answer the branch that already has the name (created: false) instead of refusing the name."}},dryRun:!0,examples:["modeldesk branch create <model> feat/assoc-ends","modeldesk branch create <model> agent/tidy-names --open --json","modeldesk branch create <model>@feat/x feat/x-followup --exist-ok"],mcp:{name:"branch_create",description:"Creates a branch of the model at your working branch head, or at the branch the address names. For larger work, name it agent/<topic> and pass open: true: your draft then aims at it, and draft_commit lands there without the person's commit permission; end by asking the person to review and merge it in the app, naming the branch. A name outside agent/ is created with notes saying an agent commits there only with that permission. existOk answers a branch that already has the name instead of failing."},resultSchema:pg.branchCreate,run:async e=>X(async()=>{let t=e.args.name.trim();wT(t);let n=e.args.model,r=await Z(e,n,xn),s=Xe(r),o={id:r.id,name:r.name},i=e.agent!==void 0&&!t.toLowerCase().startsWith(Wt)?`An agent commits without ${e.agent.wording.grant} only on a branch named ${Wt}\u2026`:void 0;i!==void 0&&e.note(i);let a={model:o,name:t,from:{id:s.id,name:s.name},...i?{note:i}:{}},d=async()=>{let f=(await ce(e,n.model).branches()).find(h=>$n(h.name,t));return f===void 0?void 0:at(f)};if(e.dryRun){let f=await d();if(f!==void 0&&!e.flags["exist-ok"])throw new u(`${y(o.name)} already has a branch named '${y(f.name)}'.`,{exitCode:b.Conflict,type:"branch-name-taken",hint:"Pick another name, or pass --exist-ok to use that branch.",hosted:{hint:"Pick another name, or set existOk to use that branch."}});return{result:{...a,...f?{branch:f}:{},created:!1,dryRun:!0}}}let l=await(async()=>{try{let f=await e.api().branches.create(o.id,{name:t,from:s.id});return{branch:at(f),created:!0}}catch(f){let h=f instanceof u&&f.type==="branch-name-taken"&&e.flags["exist-ok"]?await d():void 0;if(h===void 0)throw f;return{branch:h,created:!1}}})(),c=e.flags.open?await _l(e,r,l.branch):void 0;return{result:{...a,...l,...c?{open:c}:{}}}}),render:e=>{let t=y(e.model.name),n=y(e.name),r=y(e.from.name);return[bT(e,n,t,r),...e.open?[jl(e.model,e.open)]:[]].join(`
161
+ `)}});var ct=async(e,t,n)=>{if(!e.globals.yes){if(!e.interactive)throw new u(`${n} needs confirmation, and this run cannot ask for it. Nothing was changed.`,{exitCode:b.NeedsHuman,hint:"Re-run with --yes to confirm."});if(!await e.confirm(t))throw new u(`${n} was cancelled. Nothing was changed.`)}};var kT=(e,t,n)=>{let r=n?Math.max(t,1):t;return r===0?`Deleting ${e} deletes only the branch. No one has a draft on it.`:r===1?`Deleting ${e} also deletes ${n?"your draft":"the one draft"} on it. It cannot be recovered.`:`Deleting ${e} also deletes the ${r} drafts on it${n?", yours among them":""}. They cannot be recovered.`},ET=(e,t)=>t===0?`Everything committed on ${e} is on main.`:t===1?`1 commit on ${e} is not on main. It is lost with the branch.`:`${t} commits on ${e} are not on main. They are lost with the branch.`,CT="modeldesk branch delete --help",vT=(e,t)=>{if(!(e instanceof u))return e;let n={exitCode:e.exitCode,type:e.type,requestId:e.requestId,details:e.details};if(e.type==="branch-has-drafts"){let r=Number(e.details.draftCount),s=r===1?"a draft":`${r} drafts`;return new u(`Other users hold ${s} with staged changes on ${t}, so it was not deleted.`,{...n,hint:"Pass --force to delete the branch with their drafts, which cannot be recovered."})}if(e.type==="branch-unmerged"){let r=Number(e.details.unmergedCommitCount),s=r===1?"1 commit":`${r} commits`;return new u(`${s} on ${t} ${r===1?"is":"are"} not on main, so it was not deleted.`,{...n,hint:"Merge it into main first to keep them, or pass --force to lose them with the branch."})}return e instanceof U&&e.status===403?new u(e.message,{...n,hint:"Deleting a branch needs the model:delete scope, which model:write does not imply, since other users' drafts are lost with it. Ask an owner of the model to delete it, or sign in with a token that carries that scope."}):e},hg=q({path:["branch","delete"],effect:"destroy",summary:"Delete a branch with every draft on it",description:"Deletes the branch together with every draft that aims at it, whoever owns it. It restates how many drafts go with it and how many of its commits main does not reach, and asks at a terminal; anywhere else it needs --yes. While other users' drafts on it hold staged changes, or it holds commits main does not reach, the delete exits 5 unless --force, which loses them. main cannot be deleted (exit 2). It needs the model:delete scope. --dry-run restates what would go and deletes nothing; the server then checks neither the refusals nor the scope. Under an agent host deleting a branch is left to a person (exit 6).",positionals:[_(Rt)],dryRun:!0,flags:{force:{type:"boolean",description:"Delete even when other users' drafts on the branch hold staged changes, or main lacks its commits."}},examples:["modeldesk branch delete <model>@feat/x --dry-run","modeldesk branch delete <model>@feat/x --yes","modeldesk branch delete <model>@feat/x --force --yes"],run:async e=>{let t=e.args.model,n=await Z(e,t,Rt),r=Xe(n),s=y(r.name);if(r.main)throw I(`${s} is the main branch of ${y(n.name)}, which cannot be deleted.`,CT);let o=(await ce(e,t.model).branches()).find(h=>h.id===r.id),i=o?.draftCount??0,a=o?.unmergedCommitCount??0,d=n.draft?.target.id===r.id;e.print(`${kT(s,i,d)}
162
+ ${ET(s,a)}
163
+ `);let{force:l}=e.flags,{dryRun:c}=e.globals,m={model:{id:n.id,name:n.name},branch:{id:r.id,name:r.name},deleted:!c,dryRun:c,forced:l,draftCount:i,unmergedCommitCount:a};if(c)return{result:m};let f=`branch ${s} of ${y(n.name)}`;await ct(e,`Delete ${f}?`,`Deleting ${f}`);try{await e.api().branches.delete(n.id,r.id,l)}catch(h){throw vT(h,s)}return{result:m}},render:e=>{let t=`branch ${y(e.branch.name)} of ${y(e.model.name)}`;return e.dryRun?`Would delete ${t}. Dry run: nothing was deleted.`:`Deleted ${t}.`}});var gg={draftDiff:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},resource:{type:"object",properties:{kind:{type:"string",description:'One of "dataset", "model".'},id:{type:"string"},name:{type:"string"}}},draft:{properties:{id:{type:"string"},targetRefId:{type:"string"},baselineCommitId:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"},createdAt:{type:"string"},updatedAt:{type:"string"},movesBaseTo:{type:"string"},handoff:{type:"object",properties:{summary:{type:"string"},headCommitId:{type:"string"},at:{type:"string"}}}},description:"Your draft, or null when you hold none. May be null."},elements:{type:"array",items:{type:"object",properties:{elementId:{type:"string"},elementName:{type:"string"},elementType:{type:"string"},diffType:{type:"string",description:'One of "ADDED", "MODIFIED", "REMOVED".'},attributes:{type:"object",additionalProperties:{type:"object",properties:{before:{type:"array",items:{}},after:{type:"array",items:{}}}}},relations:{type:"object",additionalProperties:{type:"object",properties:{before:{type:"array",items:{type:"string"}},after:{type:"array",items:{type:"string"}},addedTargets:{type:"array",items:{type:"string"}},removedTargets:{type:"array",items:{type:"string"}}}}}}},description:"A model draft's net difference from its baseline, one entry per element, as the server renders a commit's."},names:{type:"object",additionalProperties:{type:"string"},description:"The name of every element the diff mentions, relation targets included, keyed by id."},rows:{type:"object",properties:{added:{type:"array",items:{type:"string"}},changed:{type:"array",items:{type:"string"}},removed:{type:"array",items:{type:"string"}}},description:"A dataset draft's difference from its baseline."},changes:{type:"array",items:{type:"object",properties:{id:{type:"string"},createdAt:{type:"string"},message:{type:"string"},requestId:{type:"string",description:"The `changeRequestId` it was staged under."},surface:{type:"string",description:'Where it came from, read off the request id\'s prefix: the app (`web`), `cli`, `mcp`, or `api`. One of "api", "cli", "mcp", "web".'},actionTypes:{type:"array",items:{type:"string"},description:"The action types the change recorded."}}},description:"When changes are asked for: the staged changes, oldest first, instead of the difference."}},required:["schemaVersion","resource","draft"]}};var ST={ADDED:"+",MODIFIED:"~",REMOVED:"-"},yg=e=>e===void 0||e.length===0?"(none)":e.map(t=>y(typeof t=="string"?t:JSON.stringify(t))).join(", "),wg=(e,t)=>e[t]===void 0?t:`${y(e[t])} (${t})`,Fl=(e,t)=>[` ${ST[e.diffType]} ${y(e.elementName??t[e.elementId]??"(no name)")} (${e.elementType}) ${e.elementId}`,...Object.entries(e.attributes??{}).map(([n,r])=>` ${n}: ${yg(r.before)} -> ${yg(r.after)}`),...Object.entries(e.relations??{}).map(([n,r])=>[` ${n}:`,...(r.addedTargets??[]).map(s=>`+ ${wg(t,s)}`),...(r.removedTargets??[]).map(s=>`- ${wg(t,s)}`)].join(" "))],IT=(e,t)=>{let n=e.requestId?` [${e.requestId}]`:"";return` ${t+1}. ${e.id} ${e.createdAt} ${e.surface.toUpperCase()} ${y(e.message??"(no message)")}${n} ${e.actionTypes.join(", ")}`},$T=e=>{let t=se(e.resource);if(e.draft===null)return`You hold no draft of ${t}, so nothing is staged.`;if(e.changes)return[`The staged changes of your draft of ${t}, oldest first:`,...e.changes.length===0?[" none"]:e.changes.map((s,o)=>IT(s,o))].join(`
164
+ `);if(e.rows){let{added:s,changed:o,removed:i}=e.rows;return[`Your draft of ${t} against its baseline:`,...s.map(a=>` + ${a}`),...o.map(a=>` ~ ${a}`),...i.map(a=>` - ${a}`),...s.length+o.length+i.length===0?[" no rows differ"]:[]].join(`
165
+ `)}let n=e.names??{},r=e.elements??[];return[`Your draft of ${t} against its baseline:`,...r.length===0?[" no elements differ"]:r.flatMap(s=>Fl(s,n))].join(`
166
+ `)},bg=D({path:["draft","diff"],effect:"read",summary:"Show what your draft changes",description:"Shows your draft's net difference from its baseline: per element of a model (added, modified with each changed attribute and relation, removed), per row of a dataset. With --changes it lists the staged changes instead, oldest first, each with its message, request id and the surface it came from (WEB for the app, CLI, MCP, or API for anything else). A dataset serves no list of its staged changes, so --changes takes a model.",positionals:[Me],flags:{changes:{type:"boolean",description:"List the staged changes, oldest first, instead of the difference."}},examples:["modeldesk draft diff <model>","modeldesk draft diff <model> --changes --json"],mcp:{name:"draft_diff",description:"Shows what your draft changes against its baseline, per element: added, modified with each changed attribute and relation, removed. changes: true lists the staged changes instead, oldest first, each with its message, request id and the surface it came from. Call it to check your work before draft_handoff or draft_commit."},resultSchema:gg.draftDiff,run:async e=>X(async()=>{if(e.flags.changes&&e.args.resource.kind==="dataset")throw I("A dataset's draft serves no list of its staged changes, so --changes takes a model.","modeldesk draft diff --help");let t=await Ne(e),n=await t.read(),r={resource:t.ref,draft:n??null};if(n===void 0)return{result:r};let s=e.api();if(e.flags.changes&&t.changes){let i=(await t.changes(n.id)).reverse().map(a=>({id:a.id,createdAt:a.createdAt,...a.message?{message:a.message}:{},...a.requestId?{requestId:a.requestId}:{},surface:qt(a.requestId),actionTypes:a.actionTypes}));return{result:{...r,changes:i}}}if(t.ref.kind==="dataset"){let i=await s.drafts.dataset.diff(t.ref.id);return{result:{...r,rows:{added:i.added??[],changed:i.changed??[],removed:i.removed??[]}}}}let o=await s.drafts.model.diff(t.ref.id);return{result:{...r,elements:o.elements,names:o.resolvedNames??{}}}}),render:$T});var kg={branchDiff:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"The branch whose changes are listed."},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"},head:{type:"string"}}},base:{type:"object",properties:{id:{type:"string"},name:{type:"string"}},description:"The branch it is compared with, main by default."},mergeBaseId:{type:"string",description:"The commit the two diverged at: what the changes are counted from."},elements:{type:"array",items:{type:"object",properties:{elementId:{type:"string"},elementName:{type:"string"},elementType:{type:"string"},diffType:{type:"string",description:'One of "ADDED", "MODIFIED", "REMOVED".'},attributes:{type:"object",additionalProperties:{type:"object",properties:{before:{type:"array",items:{}},after:{type:"array",items:{}}}}},relations:{type:"object",additionalProperties:{type:"object",properties:{before:{type:"array",items:{type:"string"}},after:{type:"array",items:{type:"string"}},addedTargets:{type:"array",items:{type:"string"}},removedTargets:{type:"array",items:{type:"string"}}}}}}},description:"The branch's net change since `mergeBaseId`, one entry per element, as a draft's diff renders it."},names:{type:"object",additionalProperties:{type:"string"},description:"The name of every element the diff mentions, relation targets included, keyed by id."}},required:["schemaVersion","model","ref","branch","base","elements","names"]}};var Eg=D({path:["branch","diff"],effect:"read",summary:"Show what a branch changed since it diverged",description:"Shows the branch's net change since it diverged from the base branch (main unless --base), per element as draft diff shows a draft: what merging it into the base would bring before conflicts. The branch is your working branch unless the address names one. Two branches each merged into the other have no single point where they split and exit 1, naming the candidate commits.",positionals:[_(xn)],flags:{base:{type:"string",placeholder:"branch",description:"The branch to compare with, by name; main by default."}},examples:["modeldesk branch diff <model>@feat/x","modeldesk branch diff <model>@feat/x --base feat/y --json"],mcp:{name:"branch_diff",description:"Shows what a branch changed since it diverged from base (main unless given), per element as draft_diff shows a draft: what merging it would bring, before conflicts. Without a ref, your working branch."},resultSchema:kg.branchDiff,run:async e=>{let t=e.args.model,n=await Z(e,t,xn),r=Xe(n),s=e.flags.base===void 0?n.main:Xe(await Z(e,{model:t.model,ref:{kind:"branch",name:e.flags.base},text:`${t.model}@${e.flags.base}`},xn)),o=await(async()=>{try{return await e.api().branches.diff(n.id,r.id,s.id)}catch(a){if(a instanceof u&&a.type==="ambiguous-merge-base"){let d=Array.isArray(a.details.candidateBaseIds)?a.details.candidateBaseIds:[];throw new u(`${y(r.name)} and ${y(s.name)} were each merged into the other, so they have ${d.length||"several"} equally close common commits and no single point where they split.`,{exitCode:a.exitCode,type:a.type,requestId:a.requestId,details:a.details,hint:"Delete whichever branch holds nothing of its own since the two merges and create it again from the other, or create a new branch from one of them and redo the other changes there."})}throw a}})();return{result:{model:{id:n.id,name:n.name},ref:re(n),branch:{id:r.id,name:r.name,head:o.commitId},base:{id:s.id,name:s.name},...o.parentCommitId?{mergeBaseId:o.parentCommitId}:{},elements:o.elements,names:o.resolvedNames??{}}}},render:e=>{let t=e.mergeBaseId?`, since ${e.mergeBaseId}`:"";return[`${y(e.branch.name)} of ${y(e.model.name)} against ${y(e.base.name)}${t}:`,...e.elements.length===0?[" no elements differ"]:e.elements.flatMap(r=>Fl(r,e.names))].join(`
167
+ `)}});var Cg={branchList:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},items:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},main:{type:"boolean",description:"One of false, true."},head:{type:"string",description:"The commit the branch points at."},draftCount:{type:"number",description:"How many drafts aim at the branch, whoever owns them; a delete takes every one."},unmergedCommitCount:{type:"number",description:"How many commits on the branch main does not reach; a delete loses them."},working:{type:"boolean",description:"True for the branch your draft aims at, which an invocation that names no ref works on. One of false, true."}}}},truncated:{type:"boolean",description:"True when more rows exist than this page carries. One of false, true."},nextCursor:{type:"string",description:"Where the next page starts, to continue from; present exactly when truncated."},hint:{type:"string",description:"One line on how to continue or narrow the query; present exactly when truncated."}},required:["schemaVersion","model","items","truncated"]}};var AT=["","NAME","HEAD","DRAFTS","UNMERGED","ID"],vg=D({path:["branch","list"],effect:"read",summary:"List a model's branches",description:"Lists the model's branches, main first, each with its head, how many drafts aim at it (whoever owns them) and how many of its commits main does not reach. The branch your draft aims at is marked working (* in the table): an invocation that names no ref works there, and on main when you hold no draft.",positionals:[_(Ae)],listing:{},examples:["modeldesk branch list <model>","modeldesk branch list <model> --json"],mcp:{name:"branch_list",description:"Lists the model's branches, main first, each with its head, how many drafts aim at it and how many of its commits main does not reach. The branch your draft aims at is marked working: a call that names no ref works there."},resultSchema:Cg.branchList,run:async e=>{let t=ce(e,e.args.model.model),n=await t.id(),[r,s,o]=await Promise.all([t.identity(),t.branches(),dt(()=>e.api().models.draft(n))]),i=o?.targetRefId??r.branch.id,a=s.map(l=>({id:l.id,name:l.name,main:l.main,head:l.head.id,draftCount:l.draftCount,unmergedCommitCount:l.unmergedCommitCount,working:l.id===i}));return{result:{model:{id:n,name:r.name},...await e.list(a)}}},render:e=>{let t=e.items.map(n=>[n.working?"*":"",y(n.name),n.head,String(n.draftCount),String(n.unmergedCommitCount),n.id]);return[`Branches of ${y(e.model.name)}:`,...F([AT,...t])].join(`
168
+ `)}});var OT=e=>Object.fromEntries(e.map(({key:t,kind:n,base:r,target:s,source:o})=>[t,{kind:n,...r===void 0?{}:{base:r},...s===void 0?{}:{target:s},...o===void 0?{}:{source:o}}])),Sg=e=>({elementId:e.elementId,reason:e.reason,target:e.target,source:e.source,fields:OT(e.fields),...e.managedDependencyChanges===void 0?{}:{managedDependencyChanges:e.managedDependencyChanges}}),MT=e=>({elementId:String(e.elementId),rule:e.code,message:e.message,...e.property===void 0?{}:{property:e.property}}),Ig=e=>({conflicts:e.conflicts.map(Sg),mergeBaseId:e.mergeBaseId,targetHead:e.targetCommitId,sourceHead:e.sourceCommitId,names:e.resolvedNames,blockers:e.blockers,rejected:[]}),Rg=e=>Array.isArray(e)?e:[],$g=e=>{let t=e;return{conflicts:Rg(t.conflicts).map(Sg),mergeBaseId:String(t.mergeBaseId??""),targetHead:String(t.targetCommitId??""),sourceHead:String(t.sourceCommitId??""),names:t.resolvedNames??{},blockers:[],rejected:Rg(t.rejected).map(MT)}},ks=(e,t)=>e[t]===void 0?t:y(e[t]),NT=(e,t)=>{let[n]=e.target.present?e.target.owners:e.source.owners,r=ks(t,e.elementId);return n===void 0?r:`${ks(t,n)}/${r}`},PT=(e,t)=>{let n=t.rejected.filter(r=>r.elementId===e.elementId).map(r=>({rule:r.rule,message:r.message,...r.property===void 0?{}:{property:r.property}}));return{elementId:e.elementId,label:NT(e,t.names),reason:e.reason,target:e.target,source:e.source,fields:Object.fromEntries(Object.entries(e.fields).map(([r,s])=>[r,{...s}])),...e.managedDependencyChanges===void 0?{}:{managedDependencyChanges:e.managedDependencyChanges},...n.length===0?{}:{rejected:n}}},xg=e=>e.blockers.length>0?"blocked":e.conflicts.length>0?"conflicts":"clean",ql=(e,t,n,r)=>{let s=new Set(t.conflicts.map(i=>i.elementId)),o=t.rejected.filter(i=>!s.has(i.elementId));return{...e,target:{...e.target,head:t.targetHead},source:{...e.source,head:t.sourceHead},outcome:n,mergeBaseId:t.mergeBaseId,blockers:t.blockers,names:t.names,resolutions:t.conflicts.map(i=>PT(i,t)),...r===void 0?{}:{takeOthers:r},...o.length===0?{}:{rejected:o}}};var oe="modeldesk branch merge --help",LT=new Set(["target","source"]),Es=e=>LT.has(e),Wl=e=>typeof e=="string"?e:JSON.stringify(e)??"undefined",wr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),hi=(e,t,n)=>{let r=e[t];if(typeof r!="string"||r==="")throw I(`The resolution file has no '${t}' on ${n}.`,oe);return r},Tg=(e,t)=>{let n=e[t];if(!wr(n))throw I(`The resolution file has no '${t}' branch.`,oe);return{id:hi(n,"id",t),head:hi(n,"head",t)}},DT=(e,t)=>{let{take:n}=e;if(n!=null){if(Es(n)||n==="fields")return n;throw I(`The entry for ${t} has take '${Wl(n)}'; it takes 'target', 'source' or 'fields'.`,oe)}},_T=(e,t)=>{let{fields:n}=e;if(n==null)return{};if(!wr(n))throw I(`The entry for ${t} has 'fields' that is not an object keyed by field.`,oe);return Object.fromEntries(Object.entries(n).flatMap(([r,s])=>{let o=wr(s)?s.take:void 0;if(o==null)return[];if(!Es(o))throw I(`The field '${r}' of ${t} has take '${Wl(o)}'; a field takes 'target' or 'source'.`,oe);return[[r,o]]}))},jT=(e,t)=>{if(!wr(e))throw I(`Entry ${t+1} of the resolution file is not an object.`,oe);let n=hi(e,"elementId",`entry ${t+1}`),r=DT(e,n),s=_T(e,n),o=Object.keys(s);if(r!==void 0&&r!=="fields"&&o.length>0)throw I(`The entry for ${n} takes '${r}' whole and also takes fields (${o.join(", ")}); pick one: a side for the element, or 'fields' with a side per field.`,oe);return{elementId:n,take:r??(o.length>0?"fields":void 0),fields:s}},Ag=e=>{let t;try{t=JSON.parse(e)}catch(s){throw I(`The resolution file is not JSON (${s.message}).`,oe)}if(!wr(t))throw I("The resolution file is not a JSON object.",oe);if(!wr(t.model))throw I("The resolution file has no 'model'.",oe);let{takeOthers:n}=t;if(n!=null&&!Es(n))throw I(`The resolution file has takeOthers '${Wl(n)}'; it takes 'target' or 'source'.`,oe);let{resolutions:r}=t;if(r!==void 0&&!Array.isArray(r))throw I("The resolution file's 'resolutions' is not a list.",oe);return{model:{id:hi(t.model,"id","model")},target:Tg(t,"target"),source:Tg(t,"source"),...Es(n)?{takeOthers:n}:{},entries:(r??[]).map((s,o)=>jT(s,o))}},Og=e=>{let t=e.lastIndexOf("="),n=t===-1?void 0:e.slice(t+1),r=()=>I(`--take takes <element>[#<field>]=target|source, got '${e}'.`,oe,{reason:`'take' takes <element>[#<field>]=target|source, got '${e}'.`});if(t===-1||!Es(n))throw r();let s=e.slice(0,t),o=s.lastIndexOf("#"),i=o===-1?s:s.slice(0,o),a=o===-1?void 0:s.slice(o+1);if(i===""||a==="")throw r();return{element:i,...a===void 0?{}:{field:a},side:n}},Mg=(e,t)=>{let n=e.find(s=>s.elementId===t.elementId),r=t.field===void 0?{elementId:t.elementId,take:t.side,fields:{}}:{elementId:t.elementId,take:"fields",fields:{...n?.take==="fields"?n.fields:{},[t.field]:t.side}};return n===void 0?[...e,r]:e.map(s=>s.elementId===t.elementId?r:s)},FT=e=>e.takeOthers===void 0?e.entries.filter(t=>t.take===void 0).map(t=>t.elementId):[],Ng=e=>{let t=FT(e);if(t.length>0){let n=t.length===1?"One entry has":`${t.length} entries have`;throw I(`${n} no take: ${t.join(", ")}. Fill in 'take' on each, or pass --take-others target|source for every entry left open.`,oe,{reason:`${n} no take: ${t.join(", ")}. Give a take for each, or takeOthers (target or source) for every entry left open.`})}},Pg=(e,t)=>{let n=e.entries.flatMap(r=>r.take===void 0?[]:r.take!=="fields"?[{elementId:r.elementId,take:r.take}]:Object.keys(r.fields).length===0?[{elementId:r.elementId,take:"target"}]:[{elementId:r.elementId,take:"fields",fields:r.fields}]);return{source:e.source.id,message:t,expectedHeadId:e.target.head,expectedSourceHeadId:e.source.head,...n.length===0?{}:{resolutions:n},...e.takeOthers===void 0?{}:{takeOthers:e.takeOthers}}};var Lg=String.raw`Separate labels with '/'; inside a label, write '/' as '\/' and '\' as '\\'.`,qT=e=>{let t=[],n="";for(let r=0;r<e.length;r++){let s=e[r];if(s==="\\"){let o=e[r+1];if(o!=="/"&&o!=="\\")throw new u(String.raw`'${e}' is not an element path: a '\' escapes only '/' or '\'.`,{exitCode:b.Usage,hint:Lg});n+=o,r++}else s==="/"?(t.push(n),n=""):n+=s}if(t.push(n),t[0]===""&&t.shift(),t.at(-1)===""&&t.pop(),t.length===0||t.includes(""))throw new u(`'${e}' is not an element path.`,{exitCode:b.Usage,hint:Lg});return t},Dg=e=>e.map(Al).join("/"),_g=(e,t,n,r)=>{let s=[...new Set(e.children(t).map(d=>d.id))].filter(d=>r||!In(e.element(d)?.type??"")),o=s.filter(d=>d.toLowerCase()===n.toLowerCase());if(o.length>0)return o;let i=s.filter(d=>e.label(d)===n);if(i.length>0)return i;let a=n.toLowerCase();return s.filter(d=>e.label(d)?.toLowerCase()===a)},Bl="$",WT=(e,t,n)=>{let r=t.get(n.slice(Bl.length));if(r===void 0){let s=[...t.keys()].map(i=>`${Bl}${i}`).join(", "),o=s===""?"Give a create operation a key first.":`The keys so far: ${s}.`;throw new u(`No earlier operation of this batch created an element under '${n}'.`,{exitCode:b.Usage,hint:o,hosted:{hint:o}})}if(e.element(r)===void 0)throw new u(`The element created as ${n} was deleted by an earlier operation of this batch.`,{exitCode:b.Usage});return r},BT=(e,t)=>{let n=e.element(t)?t:t.toLowerCase();if(e.element(n)===void 0)throw new u(`No element ${t} in this model.`,{exitCode:b.NotFound});return n},HT=(e,t,n,r)=>new u(`No element labelled '${e}' ${t}.`,{exitCode:b.NotFound,hint:n?"It names an internal element; pass --internal to address it.":"Run 'modeldesk model tree' or 'modeldesk search' to find it.",details:r,hosted:{hint:n?"It names an internal element; address it by its id.":s=>`Call ${s("search")} or ${s("describe")} to find it.`}}),he=(e,t,n={})=>{if(e.keys!==void 0&&t.startsWith(Bl))return WT(e,e.keys,t);let r=n.internal??!1;if(Y(t))return BT(e,t);let s=[],o=e.rootId;for(let i of qT(t)){let a=s.length===0?"at the top of the model":`under '${Dg(s)}'`,d=_g(e,o,i,r);if(d.length===0){let l=!r&&_g(e,o,i,!0).length>0;throw HT(i,a,l,{resolvedPath:Dg(s),resolvedId:o})}if(d.length>1)throw new u(`'${i}' ${a} names ${d.length} elements; address the one you mean by id.`,{exitCode:b.Usage,details:{candidates:d.map(l=>({id:l,type:e.element(l)?.type,label:e.label(l)}))}});o=d[0],s.push(i)}return o},UT="/",gi=(e,t)=>t===UT?e.rootId:he(e,t);var br=(e,t,n,r,s)=>new u(t,{exitCode:n,hint:r,type:e.type,requestId:e.requestId,details:e.details,hosted:s}),Hl=e=>({hint:t=>`${e(t)}, then commit again.`}),VT=(e,t)=>br(t,`You hold no draft of ${e} any more: it was committed or discarded since it was read. Nothing was committed.`,b.Failure,"Run 'modeldesk model log' to see what landed.",{hint:n=>`Call ${n("model log")} to see what landed.`}),GT=(e,t,n)=>{switch((e instanceof U?e.status:void 0)===404?"no-draft":e.type){case"draft-head-conflict":return br(e,`The branch of ${t} moved past the commit your draft is based on, so the draft cannot land as it stands.`,b.Conflict,"Run 'modeldesk draft rebase', review what it reports, then commit again.",Hl(s=>`Call ${s("draft rebase")} and review what it reports`));case"draft-moved":return br(e,`Your draft of ${t} is not at ${n} any more: a change was staged, undone or rebased since, so nothing landed.`,b.Conflict,"Review it with 'modeldesk draft diff --changes', then commit again.",Hl(s=>`Review it with ${s("draft diff")} and changes: true`));case"branch-head-conflict":return br(e,`Your draft of ${t} changed while it was being committed, so nothing landed.`,b.Conflict,"Run 'modeldesk draft status', then commit again.",Hl(s=>`Call ${s("draft status")}`));case"nothing-to-commit":return br(e,`Your draft of ${t} holds no staged change, so there is nothing to commit.`,b.Failure);case"no-draft":return VT(t,e);default:return e}},KT=(e,t)=>{let r=(Array.isArray(e.details.commits)?e.details.commits:[]).find(s=>s.requestId===t);return r&&{id:r.id,message:r.message,requestId:r.requestId,actionTypes:r.actionTypes}},YT=async(e,t)=>{let{holder:n,draft:r,commitRequestId:s,retried:o}=t,i=e.exitCode===b.Transient,a=e instanceof U&&e.status===404;if(i||o&&a)try{let l=await n.findLanding(s,r);return l===void 0?{kind:"none"}:{kind:"landed",commit:l}}catch{return{kind:"unknown"}}let d=e.type==="draft-head-conflict"?KT(e,s):void 0;return d===void 0?{kind:"none"}:{kind:"landed",commit:d}},zT=(e,t)=>br(e,`${e.reason} Whether your draft of ${t} landed is unknown: the branch could not be read to look for the commit.`,b.Transient,"Run 'modeldesk model log' to see whether it landed before you commit again.",{hint:n=>`Call ${n("model log")} to see whether it landed before you commit again.`}),kr=async(e,t,n,r)=>{let s=await JT(e,t,n,r);return t.ref.kind==="model"&&e.content.drop(t.ref.id,n.id),s},JT=async(e,t,n,r)=>{let s=Zn(e.origin),o={message:r.message,commitRequestId:s,expectedDraftHeadId:r.expectedDraftHeadId},i=async d=>({landing:{branch:await t.branch(n.targetRefId),commit:d},commitRequestId:s,recovered:!0}),a=async(d,l)=>{if(!(d instanceof u))throw d;let c=await YT(d,{holder:t,draft:n,commitRequestId:s,retried:l});if(c.kind==="landed")return c.commit;if(!l&&d.exitCode===b.Transient)return"retry";throw c.kind==="unknown"?zT(d,t.ref.name):GT(d,t.ref.name,r.expectedDraftHeadId)};for(let d=!1;;d=!0)try{return{landing:await t.commit(o),commitRequestId:s,recovered:!1}}catch(l){let c=await a(l,d);if(c!=="retry")return i(c)}},Er=({branch:e,commit:t})=>({branch:"name"in e?{id:e.id,name:e.name}:{id:e.id},commit:t}),Cr=(e,t,n=Bo)=>{let{branch:r}=e;if(!(!("main"in r)||r.main))return n.afterLanding(`${t.id}@${y(r.name)}`)};var XT=/ \((\d+)\/(\d+)\)$/,QT=e=>{let t=XT.exec(e);if(t===null)return e;let[,n,r]=t.map(Number);return r>1&&n>=1&&n<=r?e.slice(0,t.index):e},ZT=e=>QT(e.trim().split(/\r?\n/)[0].trim()),eA=e=>{let t=e.join("; ");if(t.length<=72)return t;let[n]=e;return`${n.length<=72?n:`${n.slice(0,71)}\u2026`} (and ${e.length-1} more)`},jg=e=>{let t=e.flatMap(o=>o.message===void 0?[]:[ZT(o.message)]).filter(o=>o!=="").filter((o,i,a)=>o!==a[i-1]);if(t.length<=1)return t[0];let n=`${eA(t)}
169
+
170
+ `,r=t.map(o=>`- ${o}`),s=n+r.join(`
171
+ `);if(s.length<=2e3)return s;for(let o=r.length-1;;o--){let i=`${n}${r.slice(0,o).join(`
172
+ `)}${o===0?"":`
173
+ `}- and ${r.length-o} more`;if(i.length<=2e3)return i}};var Fg={draftCommit:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},resource:{type:"object",properties:{kind:{type:"string",description:'One of "dataset", "model".'},id:{type:"string"},name:{type:"string"}}},landed:{type:"object",properties:{branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},commit:{type:"object",properties:{id:{type:"string"},message:{type:"string"},requestId:{type:"string",description:"The `commitRequestId` the landing was sent with."},createdAt:{type:"string"},actionTypes:{type:"array",items:{type:"string"},description:"A model commit's action types: the whole chain's."},rowsChanged:{type:"number",description:"A dataset commit's count of the rows it wrote or removed."}}}},description:"The branch the draft landed on and the commit it became."},draftHeadCommitId:{type:"string",description:"The draft head that landed, where the server reports it."},recovered:{type:"boolean",description:"True when the answer was lost and the landing was recognised on the branch by its request id. One of false, true."},next:{type:"string",description:"Present after a landing off main: where unaddressed invocations now go, and how to get back."},url:{type:"string",description:"The commit in the app; absent for a dataset."}},required:["schemaVersion","resource","landed","recovered"]}};var wi={message:{type:"string",short:"m",required:!0,placeholder:"message",description:"Why, in your words: the line a person reviews the change by in the app and in history.",requiredReason:"Every change carries a message, the rationale a reviewer reads first; none is invented."}},St=(e,t)=>{if(e.trim()==="")throw I("The message (-m) is blank; say why, in your words.",t,{reason:"The message is blank; say why, in your words."});if(e.length>2e3)throw I(`The message (-m) is ${e.length} characters long; it holds at most ${2e3}.`,t,{reason:`The message is ${e.length} characters long; it holds at most ${2e3}.`});return e},yi="modeldesk draft commit --help",nA=async(e,t,n)=>{if(e.changes===void 0)throw new u(`The staged changes of ${n} cannot be listed, so committing it takes -m.`);let r=jg((await e.changes(t)).reverse());if(r===void 0)throw I(`No change staged in your draft of ${n} carries a message, so committing it takes -m: a landing message is composed from what the author wrote, never invented.`,yi);return r},qg=D({path:["draft","commit"],effect:"land-draft",summary:"Commit your draft as one commit",description:"Lands everything your draft holds on its branch as one commit carrying the message: every staged change, whichever surface staged it, which is what a standalone commit means. Without -m, a model draft lands under a message composed from its staged changes' own messages, oldest first; a dataset draft takes -m. The landing names the draft head it read, or the one --expect gives, so a draft that moved since exits 5 with nothing written. Under an agent host (Claude Code, Cursor, AI_AGENT) committing is left to a person (exit 6) unless MODELDESK_ALLOW_COMMIT=1 or the draft aims at a branch named agent/<topic>, an agent's own, which a person reviews and merges in the app; a draft holding changes staged outside an agent session is left to them unless --any-surface. A draft based on a branch head that has moved on exits 5: run 'modeldesk draft rebase' first. After a landing off main you hold no draft, so unaddressed invocations default to main; the result says so.",positionals:[Me],flags:{message:{type:"string",short:"m",placeholder:"message",description:"Why, in your words: the line a person reviews the commit by. Without it a model draft lands under its staged changes' own messages, never an invented one."},expect:{type:"string",placeholder:"draft-head",description:"The draft head the landing must find: a draft at any other head is refused (exit 5).",toolDescription:"The draft head the landing must find: a draft at any other head is refused as a conflict."},...nr},examples:['modeldesk draft commit <model> -m "Add the severity binding"',"modeldesk draft commit <model>"],mcp:{name:"draft_commit",description:"Lands everything your draft holds on its branch as one commit. On a branch named agent/<topic> it needs no further permission; on any other branch only the person's 'Commit to any branch and merge branches' permission lets it land, and without it the call is refused before anything is sent. It lands only your own changes: a draft holding the person's or another session's changes is left to them. Without message the commit is described by your staged changes' messages. A branch that moved past the baseline needs draft_rebase first. Commit before draft_status shows changeCount near maxChanges."},resultSchema:Fg.draftCommit,run:async e=>X(async()=>{let{message:t,expect:n}=e.flags;if(t!==void 0)St(t,yi);else if(e.args.resource.kind==="dataset")throw I("Committing a dataset draft takes -m: its staged changes cannot be listed, so there is no message to compose from them.",yi);if(n!==void 0&&!Y(n))throw I("--expect takes the draft head id a read reported.",yi,{reason:"'expect' takes the draft head id a read reported."});let r=await Ne(e),s=se(r.ref),o=await r.read();if(o!==void 0&&tr(e,e.commandName,r.ref,await r.branch(o.targetRefId)),o===void 0||o.changeCount===0)throw new u(`You hold no staged change on ${s}, so there is nothing to commit.`,{type:"nothing-to-commit"});await qe(e,r,o,{scope:{kind:"all"},action:`Committing your draft of ${s}`,anySurface:e.flags["any-surface"],override:"pass --any-surface only when they asked for it."});let{landing:i,recovered:a}=await kr(e,r,o,{message:t??await nA(r,o.id,s),expectedDraftHeadId:n??o.headCommitId}),d=Cr(i,r.ref,rr(e));return{result:{resource:r.ref,landed:Er(i),...i.draftHeadCommitId?{draftHeadCommitId:i.draftHeadCommitId}:{},recovered:a,...d===void 0?{}:{next:d},...r.ref.kind==="model"?{url:e.webUrl({kind:"commit",modelId:r.ref.id,commitId:i.commit.id})}:{}}}}),render:e=>{let t=e.landed.branch.name===void 0?"":` on ${y(e.landed.branch.name)}`;return[`Committed your draft of ${se(e.resource)} as ${e.landed.commit.id}${t}: ${y(e.landed.commit.message?.split(`
174
+ `)[0]??"")}`,...e.recovered?["(The answer was lost; the commit was found on the branch by its request id.)"]:[],...e.next?[e.next]:[],...e.url?[`url: ${e.url}`]:[]].join(`
175
+ `)}});import{readFileSync as rA}from"node:fs";import{resolve as sA}from"node:path";var Wg=async(e,t,n)=>{if(t==="-")return e.readStdin();try{return rA(sA(e.cwd,t),"utf8")}catch(r){throw I(`Could not read the resolution file ${t} (${r.message}).`,n)}};var Bg={branchMerge:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}}},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"},head:{type:"string",description:"The head the facts were computed at: what a resolution sends back as the expected head."}}},source:{type:"object",properties:{id:{type:"string"},name:{type:"string"},head:{type:"string",description:"The head the facts were computed at: what a resolution sends back as the expected head."}}},outcome:{type:"string",description:'One of "already-merged", "blocked", "clean", "conflicts", "merged".'},mergeBaseId:{type:"string"},blockers:{type:"array",items:{type:"string"}},names:{type:"object",additionalProperties:{type:"string"}},resolutions:{type:"array",items:{type:"object",properties:{elementId:{type:"string"},label:{type:"string",description:"Context for the reader: the element's name under its owner's, as the server names them."},reason:{type:"string",description:'One of "both-changed", "changed-and-deleted", "dependency-removed", "owner-deleted", "pinned-differently", "target-deleted".'},target:{type:"object",properties:{present:{type:"boolean",description:"One of false, true."},type:{type:"string"},owners:{type:"array",items:{type:"string"}}}},source:{type:"object",properties:{present:{type:"boolean",description:"One of false, true."},type:{type:"string"},owners:{type:"array",items:{type:"string"}}}},take:{type:"string",description:'One of "fields", "source", "target".'},fields:{type:"object",additionalProperties:{type:"object",properties:{take:{type:"string",description:'One of "source", "target".'},kind:{type:"string",description:'One of "attribute", "relation".'},base:{type:"array",items:{}},target:{type:"array",items:{}},source:{type:"array",items:{}}}}},managedDependencyChanges:{type:"object",properties:{target:{type:"number"},source:{type:"number"}}},rejected:{type:"array",items:{type:"object",properties:{message:{type:"string"},rule:{type:"string"},property:{type:"string"}}}}}}},takeOthers:{type:"string",description:'One of "source", "target".'},rejected:{type:"array",items:{type:"object",properties:{elementId:{type:"string"},rule:{type:"string"},message:{type:"string"},property:{type:"string"}}},description:"Refused picks that name an element no card covers: one the merge repaired, which then broke a rule."},commit:{type:"object",properties:{id:{type:"string"},message:{type:"string"},requestId:{type:"string",description:"The `commitRequestId` the landing was sent with."},createdAt:{type:"string"},actionTypes:{type:"array",items:{type:"string"},description:"A model commit's action types: the whole chain's."},rowsChanged:{type:"number",description:"A dataset commit's count of the rows it wrote or removed."}}},resolved:{type:"number",description:"How many resolutions the request carried."}},required:["schemaVersion","model","ref","target","source","outcome"]}};var iA={clean:b.Success,conflicts:b.Conflict,blocked:b.Validation},aA=e=>{for(let[t,n,r]of[["--expect","expect",e.expect],["--expect-source","expectSource",e["expect-source"]]])if(r!==void 0&&!Y(r))throw I(`${t} takes the commit id the preview reported as that branch's head.`,oe,{reason:`'${n}' takes the commit id the preview reported as that branch's head.`});return{...e.expect?{target:e.expect}:{},...e["expect-source"]?{source:e["expect-source"]}:{}}},dA=(e,t,n,r)=>{let s=e.take.length>0||e["take-others"]!==void 0;if(n&&(s||r||t.target!==void 0||t.source!==void 0))throw I("A dry run previews the merge and takes no --resolve, --take, --take-others, --expect or --expect-source.",oe);if(r&&(t.target!==void 0||t.source!==void 0))throw I("--resolve carries both heads in the file; --expect and --expect-source are not taken with it.",oe);if(s&&!r&&(t.target===void 0||t.source===void 0))throw I("--take and --take-others bind to the heads you reviewed: pass both --expect <target-head> and --expect-source <source-head> as the preview reported them, or --resolve <file>.",oe,{reason:`take and takeOthers bind to the heads you reviewed: pass both expect and expectSource as ${Vl} reported them.`})},Hg=(e,t,n)=>{let r=e.take.map(Og),s=aA(e);dA(e,s,t,n);let o=e.message===void 0?void 0:St(e.message,oe);return{takes:r,heads:s,message:o}},lA=(e,t)=>{if(e.model.id!==t.model.id)throw I(`The resolution file is for model ${e.model.id}, not ${y(t.model.name)} (${t.model.id}).`,oe);if(e.target.id!==t.target.id||e.source.id!==t.source.id)throw I(`The resolution file is for merging ${e.source.id} into ${e.target.id}, not ${y(t.source.name)} (${t.source.id}) into ${y(t.target.name)} (${t.target.id}).`,oe)},cA=async(e,t,n,r,s)=>{let o=await ce(e,t).branches(),i=Y(n),a=o.find(l=>i?l.id===n.toLowerCase():$n(l.name,n));if(a===void 0){let l=i?n:`named '${y(n)}'`;throw new u(`${y(s)} has no branch ${l}.`,{exitCode:b.NotFound,type:"ref-not-found",details:{branches:o.map(c=>c.name)}})}let d=at(a);if(d.id===r.id)throw I(`The source and the target are the same branch (${y(d.name)}); a merge takes two.`,oe);return d},mA=e=>({id:e.id,...e.message?{message:e.message}:{},...e.requestId?{requestId:e.requestId}:{},createdAt:e.createdAt,actionTypes:e.actionTypes}),fA=(e,t,n)=>{let r=n.conflicts.length,s=n.rejected.length,o=s===1?"was":"were",i=s===0?"":`, and ${P(s,"resolution")} it was given ${o} refused`;return new u(`Merging ${y(t.source.name)} into ${y(t.target.name)} of ${y(t.model.name)} conflicts on ${P(r,"element")}${i}; nothing was merged.`,{exitCode:b.Conflict,type:"merge-conflict",requestId:e.requestId,hint:"The report is on stdout (--json > merge.json captures it): fill in 'take' on each entry (target, source, or fields with a side per field) and run again with --resolve merge.json. An entry marked rejected needs another pick.",details:{conflicts:r,rejected:s},hosted:{hint:"The result carries the report. Pick a side for each conflict with 'take' (element[#field]=target|source) or 'takeOthers', pass the heads the report gives as 'expect' and 'expectSource', and call again. An entry marked rejected needs another pick."}})},Vl="merge_preview",Gg=`Call ${Vl} again and pick on its report.`,Kg=e=>`modeldesk branch merge ${e.model.id}@${y(e.target.name)} ${y(e.source.name)} --dry-run --json > merge.json`,pA=(e,t)=>{let n=e.details.conflict??{},r=n.branchId===t.source.id?t.source:t.target,s=typeof n.currentHeadCommitId=="string"?` (its head is now ${n.currentHeadCommitId})`:"";return new u(`${y(r.name)} moved since the heads this merge was bound to${s}, so nothing was merged.`,{exitCode:b.Conflict,type:"branch-head-conflict",requestId:e.requestId,hint:`Run the preview again, '${Kg(t)}', fill in the takes, and run again with --resolve merge.json.`,details:e.details,hosted:{hint:Gg}})},uA=(e,t)=>{let n=typeof e.details.rule=="string"?e.details.rule:"unknown",r=typeof e.details.elementId=="string"?` on ${e.details.elementId}`:"";return new u(`The merge refused a resolution${r} (${n}); nothing was merged.`,{exitCode:e.exitCode,type:e.type,requestId:e.requestId,hint:`Run the preview again, '${Kg(t)}', and fill in the takes on its report.`,details:e.details,hosted:{hint:Gg}})},hA=async(e,t)=>{let n;try{n=await e.branches.mergePreview(t.model.id,t.target.id,t.source.id)}catch(o){if(o instanceof u&&o.type==="nothing-to-merge")return{result:{...t,outcome:"already-merged"}};throw o}let r=Ig(n),s=xg(r);return{result:ql(t,r,s),exitCode:iA[s]}},gA=(e,t,n,r,s)=>{let o=r===void 0?{}:{takeOthers:r};if(e!==void 0)return{...e,...o};if(!(n.target===void 0||n.source===void 0||t.length===0&&r===void 0))return{model:{id:s.model.id},target:{id:s.target.id,head:n.target},source:{id:s.source.id,head:n.source},...o,entries:[]}},yA=async(e,t,{bound:n,heads:r,takes:s,text:o})=>{if(n===void 0)return{source:t.source.id,message:o,...r.target===void 0?{}:{expectedHeadId:r.target},...r.source===void 0?{}:{expectedSourceHeadId:r.source}};let i=await bA(e,t,s),a={...n,entries:i.reduce((d,l)=>Mg(d,l),n.entries)};return Ng(a),Pg(a,o)},wA=(e,t,n)=>{if(!(e instanceof u))throw e;switch(e.type){case"nothing-to-merge":return{result:{...t,outcome:"already-merged"}};case"merge-conflict":{let r=$g(e.details);return{result:ql(t,r,"conflicts",n.takeOthers),refusal:fA(e,t,r)}}case"branch-head-conflict":throw pA(e,t);case"invalid-resolution":throw uA(e,t);default:throw e}},Yg=D({path:["branch","merge"],effect:"land-direct",summary:"Merge a branch into the addressed one",description:"Merges the source branch into the branch the address names, as one commit with both heads as parents. --dry-run is the preview: it exits 0 when the merge would land clean, 5 when the branches conflict, 4 when the merged model would break a rule no pick resolves, and the report it prints under --json is the resolution file: fill in 'take' on each entry (target, source, or fields with a side per field) and pass it back with --resolve <file> or - for standard input. The file carries both heads, so a branch that moved since the preview exits 5. A person picks inline with --take <element>[#<field>]=target|source, together with --expect and --expect-source as the preview reported the heads; --take-others takes every other conflict from one side. A merge refused with conflicts prints the same report on stdout and the error on stderr, exit 5; one with nothing to merge exits 0 as already-merged, so a re-run converges. Under an agent host a merge is left to a person (exit 6) unless MODELDESK_ALLOW_COMMIT=1, whatever the branches; the preview runs.",positionals:[_(Rt),{name:"source",type:"string",required:!0,description:"The branch to merge from, by name (ignoring case) or id: another branch of the same model."}],flags:{message:{type:"string",short:"m",placeholder:"message",description:"What the merge commit is called in history; 'Merged <source> into <target>' unless given."},resolve:{type:"string",readsFile:!0,placeholder:"file",description:"The report printed by --dry-run --json or by a refused merge, with 'take' filled in; '-' reads standard input. Only ids, takes and both heads are read from it."},take:{type:{list:"string"},placeholder:"element[#field]=target|source",description:"Take one conflicting element, or one of its fields, from a side; the element by id, or by its label path on the target branch. Needs both --expect flags, or --resolve, so the pick binds to heads you reviewed.",toolDescription:"Take one conflicting element, or one of its fields, from a side; the element by id, or by its label path on the target branch. Needs expect and expectSource, so the pick binds to heads you reviewed."},"take-others":{type:{enum:["target","source"]},description:"The side every conflict no other pick names is taken from whole. Needs the heads as --take does.",toolDescription:"The side every conflict no other pick names is taken from whole. Needs the heads as take does."},expect:{type:"string",placeholder:"target-head",description:"The head the target branch must still be at, as the preview reported it (exit 5 otherwise).",toolDescription:"The head the target branch must still be at, as the preview reported it; a conflict otherwise."},"expect-source":{type:"string",placeholder:"source-head",description:"The head the source branch must still be at, as the preview reported it (exit 5 otherwise).",toolDescription:"The head the source branch must still be at, as the preview reported it; a conflict otherwise."}},dryRun:!0,examples:["modeldesk branch merge <model>@main feat/x --dry-run --json > merge.json","modeldesk branch merge <model>@main feat/x --resolve merge.json","modeldesk branch merge <model>@main feat/x --take SHACL/NodeShape#severity=source --take-others target --expect <target-head> --expect-source <source-head>"],mcp:[{name:Vl,description:"Previews merging source into the branch the address names (model@<target>) and changes nothing: whether it lands clean, each conflict with both sides' values, and any rule the merged model would break. Show it to the person when you ask them to merge your branch in the app.",pin:{dryRun:!0,take:void 0,"take-others":void 0,expect:void 0,"expect-source":void 0,message:void 0}},{name:"branch_merge",description:"Merges source into the branch the address names (model@<target>) as one commit. It needs the person's 'Commit to any branch and merge branches' permission, and the call is refused without it. Never merge unless the person asked you to; ask them to review and merge in the app instead. Resolve conflicts merge_preview reported with take (element[#field]=target|source) and takeOthers, passing expect and expectSource as the heads it reported.",pin:{dryRun:!1}}],resultSchema:Bg.branchMerge,prepare:async e=>{let{flags:t}=e;if(t.resolve!==void 0)return Hg(t,e.dryRun,!0),Wg(e,t.resolve,oe)},run:async(e,t)=>{let{flags:n,dryRun:r}=e;if(t===void 0&&n.resolve!==void 0)throw I(`--resolve ${n.resolve} was not read, so there is no resolution to merge with.`,oe);let{takes:s,heads:o,message:i}=Hg(n,r,t!==void 0),a=t===void 0?void 0:Ag(t),d=e.args.model,l=await Z(e,d,Rt),c=Xe(l),m=await cA(e,d.model,e.args.source,c,l.name),f={model:{id:l.id,name:l.name},ref:re(l),target:{id:c.id,name:c.name,head:c.head},source:{id:m.id,name:m.name,head:m.head}},h=e.api();if(r)return hA(h,f);a!==void 0&&lA(a,f);let p=gA(a,s,o,n["take-others"]??a?.takeOthers,f),g=i??`Merged ${m.name} into ${c.name}`,w=await yA(e,f,{bound:p,heads:o,takes:s,text:g});try{let k=await h.branches.merge(f.model.id,c.id,w);return{result:{...f,target:{...f.target,head:k.targetCommitId},source:{...f.source,head:k.sourceCommitId},outcome:"merged",mergeBaseId:k.mergeBaseId,commit:mA(k.commit),resolved:w.resolutions?.length??0,...w.takeOthers===void 0?{}:{takeOthers:w.takeOthers}}}}catch(k){return wA(k,f,w)}},render:e=>{let t=y(e.model.name),n=y(e.target.name),r=y(e.source.name);switch(e.outcome){case"already-merged":return`${n} of ${t} already holds everything on ${r}; there is nothing to merge.`;case"merged":{let s=e.resolved>0?` (${P(e.resolved,"conflict")} resolved)`:"";return`Merged ${r} into ${n} of ${t} as ${e.commit.id}${s}: `+y(e.commit.message?.split(`
176
+ `)[0]??"")}case"clean":return`Merging ${r} into ${n} of ${t} would land clean (merge base ${e.mergeBaseId}); nothing was merged (dry run).`;case"blocked":return[`Merging ${r} into ${n} of ${t} is blocked by ${P(e.blockers.length,"rule")} the merged model would break:`,...e.blockers.map(s=>` - ${y(s)}`),...e.resolutions.length===0?[]:[`It also conflicts on ${P(e.resolutions.length,"element")}:`,...e.resolutions.flatMap(s=>Vg(s,e.names,n,r))]].join(`
177
+ `);case"conflicts":return[`Merging ${r} into ${n} of ${t} conflicts on ${P(e.resolutions.length,"element")} (merge base ${e.mergeBaseId}):`,...e.resolutions.flatMap(s=>Vg(s,e.names,n,r)),...(e.rejected??[]).map(s=>` rejected on ${s.elementId}: ${y(s.message)} (${s.rule})`),"Run with --json > merge.json, fill in 'take' on each entry, and pass it back with --resolve merge.json."].join(`
178
+ `)}}}),bA=async(e,t,n)=>{let s=n.filter(o=>!Y(o.element)).length===0?void 0:Yt(await e.api().models.get(t.model.id,{ref:t.target.id,expand:["labels"]}));return n.map(o=>({elementId:s===void 0||Y(o.element)?o.element.toLowerCase():he(s,o.element,{internal:!0}),...o.field===void 0?{}:{field:o.field},side:o.side}))},kA=(e,t,n)=>typeof e=="string"?n?ks(t,e):y(e):y(JSON.stringify(e)),Ul=(e,t,n)=>e===void 0||e.length===0?"(none)":e.map(r=>kA(r,t,n)).join(", "),Ug=(e,t)=>{if(!e.present)return"absent";let n=e.owners.length===0?"":` under ${e.owners.map(r=>ks(t,r)).join(", ")}`;return`${e.type??"present"}${n}`},EA=(e,t,n,r,s)=>{let o=t.kind==="relation",i=t.base===void 0?"":` | base ${Ul(t.base,n,o)}`;return` ${e}: ${r} ${Ul(t.target,n,o)} | ${s} ${Ul(t.source,n,o)}${i}`},Vg=(e,t,n,r)=>{let s=[Ug(e.target,t),Ug(e.source,t)];return[` ${y(e.label)} ${e.reason} ${e.elementId}`,...s[0]===s[1]?[]:[` on ${n}: ${s[0]}; on ${r}: ${s[1]}`],...Object.entries(e.fields).map(([o,i])=>EA(o,i,t,n,r)),...(e.rejected??[]).map(o=>` rejected: ${y(o.message)} (${o.rule})`)]};var bi=(e,t)=>e.at(-1)===""&&t==="";var CA=/^<figure data-md-diagram="([^"]*)"[ >]/,vA=e=>CA.exec(e)?.[1],RA="</figure>",zg=(e,t)=>{if(t.size===0||e.payloads===void 0)return e;let n=Object.fromEntries(Object.entries(e.payloads).map(([r,s])=>[r,SA(s,t)]));return{...e,payloads:n}},SA=(e,t)=>{let n=e.split(`
179
+ `),r=[];for(let s=0;s<n.length;s+=1){let o=vA(n[s]),i=o!==void 0&&t.has(o)?n.indexOf(RA,s):-1;if(i===-1){r.push(n[s]);continue}s=i,bi(r,n[s+1])&&(s+=1)}return r.join(`
180
+ `)};var Gl=e=>`${JSON.stringify(e,null,2)}
181
+ `;var Pe=["intro","after"],mt=e=>{let t=new Map;for(let n of e.fragments??[]){let r=t.get(n.elementId)??{};t.set(n.elementId,{title:r.title||n.title||void 0,kind:r.kind||n.kind||void 0,anchor:r.anchor||n.realization?.anchor||void 0})}return t},IA=/^<!-- md-slot (?=intro [0-9a-f-]{36} -->$|after )(intro|after) ([0-9a-f-]{36})(?: heading=([1-6]))? -->$/,$A="<!-- md-slot ",Cs=class extends Error{constructor(n){super(`The bundle carries a note slot this version cannot read: ${n}. The client is older than the server.`);this.line=n;this.name="UnreadableSlotError"}line},Xg=e=>{if(!e.startsWith($A))return;let t=IA.exec(e);if(t===null)throw new Cs(e);let n={name:t[1],elementId:t[2]};return t[3]===void 0?n:{...n,heading:Number(t[3])}},Qg=e=>{let t=new Map;for(let[n,r]of Object.entries(e.payloads??{})){let s=r.split(`
182
+ `).flatMap(o=>Xg(o)??[]);s.length>0&&t.set(n,s)}return t},Kl=(e,t)=>{if(e.payloads===void 0)return{bundle:e,filled:[],dropped:[]};let n=mt(e.manifest),r=a=>n.get(a)?.anchor,s=[],o=[],i=Object.fromEntries(Object.entries(e.payloads).map(([a,d])=>{let l=xA(d,t,r);return s.push(...l.filled.map(c=>({...c,address:a}))),o.push(...l.dropped.map(c=>({...c,address:a}))),[a,l.text]}));return{bundle:{...e,payloads:i},filled:s,dropped:o}},xA=(e,t,n)=>{let r=e.split(`
183
+ `),s=[],o=new Set,i=[],a=[];for(let d=0;d<r.length;d+=1){let l=Xg(r[d]);if(l===void 0){s.push(r[d]);continue}let c=t.get(l.elementId)?.[l.name],m=`${l.name} ${l.elementId}`;if(c!==void 0&&!o.has(m)){o.add(m),i.push(l),s.push(...TA(l,c,n));continue}c!==void 0&&a.push(l),bi(s,r[d+1])&&(d+=1)}return{text:s.join(`
184
+ `),filled:i,dropped:a}},TA=(e,t,n)=>{if(e.heading===void 0){if(typeof t!="string")throw new Error(`The ${e.name} slot of ${e.elementId} takes a note path, not a heading.`);return[Jg(t)]}if(typeof t=="string")throw new Error(`The ${e.name} slot of ${e.elementId} takes a note with a heading.`);let r=n(e.elementId);if(r===void 0)throw new Error(`The bundle's manifest has no anchor for ${e.elementId}.`);let s=t.heading.replace(/\s+/g," ").trim();if(s==="")throw new Error(`The ${e.name} note of ${e.elementId} has an empty heading.`);let o=`${r}-${Tn(s)||e.name}`;return[`${"#".repeat(e.heading)} ${OA(s)} {#${o}}`,"",Jg(t.file)]},Tn=e=>e.normalize("NFD").replace(new RegExp("\\p{M}","gu"),"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),Jg=e=>`<div data-include-format="markdown" data-include="${AA(e)}"></div>`,AA=e=>e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\n/g,"&#10;").replace(/\r/g,"&#13;"),OA=e=>e.replace(/[\\`*_[\]()!#|~]/g,"\\$&").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\{/g,"&#123;").replace(/\}/g,"&#125;");var vs="http://www.w3.org/2000/svg",ty="Inter, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",Yl="group",zl="spacingAndGlyphs",Jl="italic",Xl="underline",Rr="none";var ki="hidden",Ei="stroke",Ql="auto";var MA="start",Ci="clip",NA=/^[A-Za-z0-9_-]+$/,PA=/[^A-Za-z0-9_-]+/g,Zl=e=>NA.test(e),ny=e=>e.replace(PA,"-");var ec=(e,t)=>t?`${e}-${MA}`:e,Zg=String.raw`-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?`,ey=String.raw`[a-zA-Z]+\(\s*(?:${Zg}(?:[\s,]+${Zg})*)?\s*\)`,LA=new RegExp(String.raw`^${ey}(?:\s+${ey})*$`),ry=e=>LA.test(e);var DA=/[\u0000- \u007F]/g,_A=/^([a-zA-Z][a-zA-Z0-9+.-]*):/,jA=new Set(["http","https","mailto"]),vi=e=>{let t=is(e).replace(DA,"");if(t==="")return!1;let n=_A.exec(t);return n===null||jA.has(n[1].toLowerCase())};var z="#4b5563";var Ze="white";var tc="strokeWidth",Ri=[{id:"triangle-filled",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"line",x1:16,y1:10,x2:20,y2:10,stroke:"white",strokeWidth:2},{element:"path",d:"M 6 4 L 19 10 L 6 16 L 10 10 Z",fill:z,stroke:z,strokeWidth:1}]},{id:"triangle-hollow",markerWidth:24,markerHeight:24,refX:24,refY:12,shapes:[{element:"line",x1:20,y1:12,x2:24,y2:12,stroke:"white",strokeWidth:2},{element:"path",d:"M 6 2 L 22 12 L 6 22 Z",fill:Ze,stroke:z,strokeWidth:2}]},{id:"diamond-filled",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"path",d:"M 10 5 L 19 10 L 10 15 L 1 10 Z",fill:z,stroke:z,strokeWidth:1.5}]},{id:"diamond-hollow",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"path",d:"M 10 5 L 19 10 L 10 15 L 1 10 Z",fill:Ze,stroke:z,strokeWidth:1.5}]},{id:"arrow-open",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"path",d:"M 6 4 L 19 10 L 6 16",fill:"none",stroke:z,strokeWidth:2}]},{id:"bar",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"line",x1:13,y1:1,x2:13,y2:11,stroke:z,strokeWidth:1.5}]},{id:"circle",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"circle",cx:13.5,cy:6,r:2.75,fill:Ze,stroke:z,strokeWidth:1.5}]},{id:"crowsfoot",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 18 1 L 8 6 L 18 11 M 8 6 L 18 6",fill:"none",stroke:z,strokeWidth:1.5}]},{id:"crowsfoot-bar",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 18 1 L 8 6 L 18 11 M 8 6 L 18 6",fill:"none",stroke:z,strokeWidth:1.5},{element:"line",x1:4,y1:1,x2:4,y2:11,stroke:z,strokeWidth:1.5}]},{id:"crowsfoot-circle",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 18 1 L 8 6 L 18 11 M 8 6 L 18 6",fill:"none",stroke:z,strokeWidth:1.5},{element:"circle",cx:4,cy:6,r:2.75,fill:Ze,stroke:z,strokeWidth:1.5}]},{id:"bar-circle",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"line",x1:13,y1:1,x2:13,y2:11,stroke:z,strokeWidth:1.5},{element:"circle",cx:4,cy:6,r:2.75,fill:Ze,stroke:z,strokeWidth:1.5}]},{id:"crowsfoot-triangle-circle",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 24 3 L 19 3 M 24 6 L 19 6 M 24 9 L 19 9",fill:"none",stroke:z,strokeWidth:1.5},{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:Ze,stroke:z,strokeWidth:1.5,strokeLinejoin:"round"},{element:"circle",cx:8.25,cy:6,r:2.75,fill:Ze,stroke:z,strokeWidth:1.5}]},{id:"crowsfoot-triangle-bar",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 24 3 L 19 3 M 24 6 L 19 6 M 24 9 L 19 9",fill:"none",stroke:z,strokeWidth:1.5},{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:Ze,stroke:z,strokeWidth:1.5,strokeLinejoin:"round"},{element:"line",x1:8,y1:1,x2:8,y2:11,stroke:z,strokeWidth:1.5}]},{id:"triangle-circle",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:Ze,stroke:z,strokeWidth:1.5,strokeLinejoin:"round"},{element:"circle",cx:8.25,cy:6,r:2.75,fill:Ze,stroke:z,strokeWidth:1.5}]},{id:"triangle-bar",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:Ze,stroke:z,strokeWidth:1.5,strokeLinejoin:"round"},{element:"line",x1:8,y1:1,x2:8,y2:11,stroke:z,strokeWidth:1.5}]},{id:"cup",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 13 1 A 5 5 0 0 0 13 11",fill:"none",stroke:z,strokeWidth:1.5}]}],sJ=new Map(Ri.map(e=>[e.id,e]));var HA=" ",nc=["fill","fill-opacity","stroke","stroke-opacity","stroke-width","stroke-dasharray"],UA={svg:["xmlns","viewBox","width","height","role","aria-label","font-family"],defs:[],marker:["id","markerWidth","markerHeight","refX","refY","orient","markerUnits"],clipPath:["id"],g:["data-md-element","clip-path","transform"],a:["href"],title:[],desc:[],rect:["x","y","width","height","rx",...nc],path:["d",...nc,"stroke-linejoin","marker-start","marker-end","visibility","pointer-events"],polygon:["points",...nc],line:["x1","y1","x2","y2","fill","stroke","stroke-opacity","stroke-width","stroke-dasharray"],circle:["cx","cy","r","fill","stroke","stroke-width"],text:["x","y","font-size","font-weight","font-style","text-decoration","fill","fill-opacity","textLength","lengthAdjust"]},ly=new Map(Object.entries(UA).map(([e,t])=>[e,new Set(t)])),VA=new Set(["title","desc","text"]),sy="svg",Sr="g",It="a",cy="title",Rs="data-md-element",my="path",fy=["visibility","pointer-events"],py=new Set(["rect","text","polygon","line"]),GA={"clip-path":"clipPath","marker-start":"marker","marker-end":"marker"},uy=/&(amp|lt|gt|quot|apos);/g,KA={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},YA=/[<>"']/,zA=/[\u0000-\u001F]/,JA=/^<([^\s/>]+)/,XA=/^<\/([^\s/>]+)>/,rc=/ ([^\s=/>"'<]+)=/y,sc=/"([^"]*)"/y,QA=/^on/i,ZA=/^ */,eO=64,oy=/[\p{Cc}\p{Cf}\u2028\u2029]/gu,$t=String.raw`-?\d+(?:\.\d+)?(?:e\+\d+)?`,tO=new RegExp(`^${$t}$`),nO=/^(?:[1-9]\d{0,2}|1000)$/,rO=new RegExp(`^0 0 ${$t} ${$t}$`),sO=new RegExp(`^${$t}(?:[ ,]${$t})*$`),oO=new RegExp(`^(?:${$t},${$t}(?: ${$t},${$t})*)?$`),iO=/^[MmZzLlHhVvCcSsQqTtAa0-9eE.,+\- ]*$/,hy=/^url\(#([A-Za-z0-9_-]+)\)$/,gy=/^#[0-9a-f]{6}$/,iy=Array.from(new Set([Rr,...Ri.flatMap(({shapes:e})=>e.flatMap(t=>["fill"in t?t.fill:Rr,t.stroke])).filter(e=>!gy.test(e))])),yy=Ri.flatMap(({id:e})=>[ec(e,!1),ec(e,!0)]),aO=new RegExp(`^${Ci}-[1-9]\\d*$`),dO=new RegExp(`-${Ci}-[1-9]\\d*$`),ac=`${"md"}-`,dc=e=>`U+${e.codePointAt(0).toString(16).toUpperCase().padStart(4,"0")}`,$e=e=>{let t=[];for(let n of e){if(t.length===eO)return`${t.join("").replace(oy,dc)}\u2026`;t.push(n)}return e.replace(oy,dc)},wy=e=>{if(e.includes("&#"))return"a numeric character reference is not allowed";let t=e.replace(uy,"");if(t.includes("&"))return"& does not start one of the five XML entities";let n=YA.exec(t);return n===null?void 0:`an unescaped ${n[0]} is not allowed`},by=e=>e.replace(uy,(t,n)=>KA[n]),An=(e,t)=>n=>e.test(n)?void 0:`"${$e(n)}" is not ${t}`,et=(e,t)=>n=>e.includes(by(n))?void 0:`"${$e(n)}" is not ${t}`,ay=()=>{},ue=An(tO,"a number as the serializer writes one"),dy=e=>gy.test(e)||iy.includes(e)?void 0:`"${$e(e)}" is not a paint the serializer writes (#rrggbb, ${iy.join(", ")})`,oc=An(hy,"a reference to a definition in the file, as url(#\u2026)"),lO=e=>aO.test(e)?"clipPath":yy.includes(e)?"marker":void 0,cO=(e,t)=>{if(!e.startsWith(ac))return;let n=e.slice(ac.length);if(t!==void 0)return n.startsWith(`${t}-`)?lO(n.slice(t.length+1)):void 0;if(Zl(n))return(dO.exec(n)?.index??0)>0?"clipPath":yy.some(r=>n.length>r.length+1&&n.endsWith(`-${r}`))?"marker":void 0},mO=(e,t,{idPrefix:n})=>{if(cO(e,n)===t)return;let r=n??"<prefix>",s=t==="marker"?"<marker>[-start]":`${Ci}-<n>`;return`"${$e(e)}" is not an id the serializer gives a <${t}> (${ac}${r}-${s})`},fO=e=>{let t=by(e);return t.startsWith("#")&&vi(t)?void 0:`"${$e(e)}" does not point at a section of the page (#\u2026)`},pO={xmlns:et([vs],"the SVG namespace"),viewBox:An(rO,"a viewBox the serializer writes (0 0 width height)"),width:ue,height:ue,role:et([Yl],`the role the serializer writes (${Yl})`),"aria-label":ay,"font-family":et([ty],"the serializer's font stack"),id:mO,markerWidth:ue,markerHeight:ue,refX:ue,refY:ue,orient:et([Ql],`the marker orientation the serializer writes (${Ql})`),markerUnits:et([tc],`the marker units the serializer writes (${tc})`),"data-md-element":ay,"clip-path":oc,transform:e=>ry(e)?void 0:`"${$e(e)}" is not a transform of numbers the serializer writes`,href:fO,x:ue,y:ue,rx:ue,fill:dy,"fill-opacity":ue,stroke:dy,"stroke-opacity":ue,"stroke-width":ue,"stroke-dasharray":An(sO,"a dash pattern of numbers"),d:An(iO,"path data (commands and numbers only)"),"stroke-linejoin":et(["round"],"the line join the serializer writes (round)"),"marker-start":oc,"marker-end":oc,points:An(oO,"polygon points as the serializer writes them (x,y x,y \u2026)"),x1:ue,y1:ue,x2:ue,y2:ue,cx:ue,cy:ue,r:ue,"font-size":ue,"font-weight":An(nO,"a numeric font weight (1 to 1000)"),"font-style":et([Jl],`the font style the serializer writes (${Jl})`),"text-decoration":et([Xl],`the decoration the serializer writes (${Xl})`),textLength:ue,lengthAdjust:et([zl],`the length adjustment the serializer writes (${zl})`),visibility:et([ki],`the visibility of a hit area (${ki})`),"pointer-events":et([Ei],`the pointer events of a hit area (${Ei})`)},uO=(e,t)=>{if(QA.test(t))return`the event-handler attribute ${$e(t)} is not allowed`;if(t.toLowerCase()==="style")return"a style attribute is not allowed";if(t.toLowerCase()==="class")return"a class attribute is not allowed";if(t.includes(":"))return`the namespaced attribute ${$e(t)} is not allowed`;if(!ly.get(e).has(t))return`<${e}> does not take the attribute ${$e(t)}`},hO=(e,t,n,r)=>{let s=wy(n)??pO[t](n,e,r);return s===void 0?void 0:`${t}: ${s}`},gO=(e,t,n,r)=>{let s=new Map,o=n;for(;t[o]!==">"&&!t.startsWith("/>",o);){rc.lastIndex=o;let i=rc.exec(t)?.[1];if(i===void 0)return{problem:'a tag the serializer would not write: expected ` name="value"`, `>` or `/>`'};sc.lastIndex=rc.lastIndex;let a=sc.exec(t)?.[1];if(a===void 0)return{problem:`the value of ${$e(i)} is not double-quoted`};let d=uO(e,i)??hO(e,i,a,r);if(d!==void 0)return{problem:d};if(s.has(i))return{problem:`<${e}> repeats the attribute ${i}`};s.set(i,a),o=sc.lastIndex}return{attributes:s,end:o}},ic=e=>e.startsWith("<")?"more than one element on one line":"text outside <title> and <text>",yO=(e,t)=>{if(e.includes("<!"))return{problem:"a markup declaration (<!\u2026>: a DOCTYPE, an ENTITY, a comment or CDATA) is not allowed"};if(e.includes("<?"))return{problem:"a processing instruction (<?\u2026?>) is not allowed"};if(e.startsWith("</")){let m=XA.exec(e);if(m===null)return{problem:"a closing tag the serializer would not write"};let f=e.slice(m[0].length);return f!==""?{problem:ic(f)}:{line:{kind:"close",name:m[1]}}}let n=JA.exec(e)?.[1];if(n===void 0)return{problem:"the line does not start with a tag"};if(!ly.has(n))return{problem:`<${$e(n)}> is not an element the diagram serializer writes`};let r=gO(n,e,n.length+1,t);if("problem"in r)return r;let{attributes:s,end:o}=r,i=e.startsWith("/>",o),a=e.slice(o+(i?2:1));if(!VA.has(n))return a!==""?{problem:ic(a)}:{line:{kind:i?"empty":"open",name:n,attributes:s}};if(i||a==="")return{problem:`<${n}> has to hold its text on one line, as <${n}>\u2026</${n}>`};let d=`</${n}>`,l=a.indexOf(d);if(l===-1)return{problem:`<${n}> is not closed on its line`};if(l+d.length!==a.length)return{problem:ic(a.slice(l+d.length))};let c=wy(a.slice(0,l));return c===void 0?{line:{kind:"text",name:n,attributes:s}}:{problem:`text: ${c}`}},wO=(e,t)=>{if(e.name===sy!=(t===0))return t===0?`the file opens with <${e.name}>, not the serializer's <svg xmlns="${vs}"> root`:"<svg> is only the root, never nested";if(e.name===sy&&(e.kind!=="open"||e.attributes.get("xmlns")!==vs))return`the root is not the serializer's <svg xmlns="${vs}">`;if(e.name===It&&!e.attributes.has("href"))return"<a> without an href"},bO=(e,t,n)=>{if(t.name===It&&t.children===0&&e.name!==cy)return"<a> has to open with the <title> of the group it links";if(e.name===It)return e.kind!=="open"?"<a> is only written open, around the title and body of the group it links":t.name!==Sr||!t.stamped||t.children!==0?`<a> is only written as the first child of a <g ${Rs}>`:n>0?"an <a> inside another <a>":void 0},ky=e=>fy.some(t=>e.attributes.has(t)),kO=(e,t)=>e.size===t.size&&Array.from(t).every(([n,r])=>e.get(n)===r),Ey=e=>e.findLast(t=>t.stamped),Cy="a line's group draws no box: it holds no <rect>, <text>, <polygon> or <line>",vy="a line's group holds no stamped group of its own",Si="desc",EO=e=>e!==void 0&&(e.hitArea||e.described),CO={d:()=>!0,fill:e=>e===Rr,stroke:e=>e===z,"stroke-opacity":e=>e==="0","stroke-width":e=>e===sl(1),"stroke-dasharray":e=>e==="6 4","marker-start":()=>!0,"marker-end":()=>!0},Ry=e=>e.name===my&&e.attributes.get("fill")===Rr&&e.attributes.get("stroke")===z&&Array.from(e.attributes).every(([t,n])=>CO[t]?.(n)??!1),Sy=e=>{let t=e.at(-1),n=t?.name===It?e.at(-2):t;return n?.name===Sr&&n.stamped?n:void 0},vO=(e,t)=>{if(!ky(e))return;let n=t.at(-1),r=n.name===It?t.at(-2):n;if(r?.name!==Sr||!r.stamped)return`a hit area (${fy.join(", ")}) is only written in a <g ${Rs}>`;if(r.hitArea)return"a stamped group holds one hit area";if(r===n&&r.linked)return"in a linked group, the hit area is inside the link";if(r.drawsBox)return Cy;if(r.nestsStamp)return vy;let s=n.previous;if(s===void 0||s!==n.firstPath||!Ry(s))return"a hit area follows the line's route, the first path of its group";let o=new Map([["d",s.attributes.get("d")??""],["fill",Rr],["stroke",z],["stroke-width",sl(10)],["visibility",ki],["pointer-events",Ei]]);return kO(e.attributes,o)?void 0:`a hit area is the route before it as <path ${Array.from(o.keys()).join(" ")}>, with the serializer's values`},RO=(e,t)=>{let n=Ey(t);if(EO(n))return py.has(e.name)?Cy:e.name===Sr&&e.attributes.has(Rs)?vy:void 0},SO=(e,t)=>{if(e.name!==Si)return;let n=t.at(-1);return Sy(t)===void 0||n.children!==1||n.previous?.name!==cy?`a <${Si}> is only written right after the <title> that opens a stamped group`:void 0},lc=(e,t={})=>{if(t.idPrefix!==void 0&&!Zl(t.idPrefix))return`the id prefix "${$e(t.idPrefix)}" is not one the serializer accepts`;let n=e.split(`
185
+ `);if(n.at(-1)===""&&n.pop(),n.length===0)return"the file is empty";let r=[],s=new Map,o=[],i=0,a=!1;for(let[c,m]of n.entries()){let f=c+1,h=x=>`line ${f}: ${x}`;if(m==="")return h("a blank line");let p=zA.exec(m);if(p!==null)return h(`the control character ${dc(p[0])} is not allowed`);if(is(m)!==m)return h("a code point XML cannot carry is not allowed");if(a)return h("content after the root element");let g=m.replace(ZA,""),w=yO(g,t);if("problem"in w)return h(w.problem);let{line:k}=w,C=k.kind==="close"?r.pop():void 0;if(k.kind==="close"&&C?.name!==k.name)return h(C===void 0?`</${$e(k.name)}> closes nothing`:`</${$e(k.name)}> closes <${C.name}>, opened on line ${C.lineNumber}`);let R=m.length-g.length,$=r.length*HA.length;if(R!==$)return h(`indented ${R} spaces where the nesting calls for ${$}`);if(k.kind==="close"){if(C.name===It){if(C.children===0)return h("<a> has to open with the <title> of the group it links");i-=1}if(C.described&&!C.drawsRoute)return h(`a <${Si}> belongs to a line's route group, and this group draws no route`);a=r.length===0;continue}let v=r.at(-1),T=wO(k,r.length)??(v&&(bO(k,v,i)??vO(k,r)??SO(k,r)??RO(k,r)));if(T!==void 0)return h(T);let N=k.attributes.get("id");if(N!==void 0){if(s.has(N))return h(`the id ${$e(N)} is declared twice`);s.set(N,k.name)}for(let[x,A]of k.attributes){let O=GA[x];O!==void 0&&o.push({attribute:x,id:hy.exec(A)[1],kind:O,lineNumber:f})}v!==void 0&&(v.children+=1,v.previous=k,v.firstPath??=k.name===my?k:void 0,v.linked||=v.stamped&&k.name===It),ky(k)&&((v.name===It?r.at(-2):v).hitArea=!0);let E=Sy(r);E!==void 0&&(E.described||=k.name===Si,E.drawsRoute||=v.firstPath===k&&Ry(k));let S=Ey(r);S!==void 0&&py.has(k.name)&&(S.drawsBox=!0),S!==void 0&&k.name===Sr&&k.attributes.has(Rs)&&(S.nestsStamp=!0),k.kind==="open"&&(r.push({name:k.name,lineNumber:f,stamped:k.name===Sr&&k.attributes.has(Rs),children:0,linked:!1,hitArea:!1,drawsBox:!1,described:!1,drawsRoute:!1,nestsStamp:!1}),i+=k.name===It?1:0)}let d=r.at(-1);if(d!==void 0)return`<${d.name}> opened on line ${d.lineNumber} is never closed`;let l=o.find(({id:c,kind:m})=>s.get(c)!==m);return l===void 0?void 0:`line ${l.lineNumber}: ${l.attribute}: url(#${$e(l.id)}) names no <${l.kind}> the file declares`};var cc=" ",mc=/^( *)<g data-md-element="([^"]*)">$/,IO=/^<title>[^<]*<\/title>$/,Ii=".svg",Iy=".png",$y=[137,80,78,71,13,10,26,10],$O=e=>{let t=new Map,n=(r,s)=>{s&&!t.has(r)&&t.set(r,`#${s}`)};for(let r of e.fragments??[]){n(r.elementId,r.realization?.anchor);for(let s of r.anchors??[])n(s.elementId,s.anchor)}return t},xO=e=>{let t=new Map;for(let[n,r]of e){let s=as(n);!t.has(s)&&vi(r)&&t.set(s,r)}return t},TO=(e,t,n)=>{let r=n+cc,s=`${n}</g>`,o=`${r}<g data-md-element="`;for(let i=t+1;i<e.length;i+=1){let a=e[i];if(a===s||a.startsWith(o))return i;if(!a.startsWith(r))return}},AO=(e,t)=>{if(t.size===0)return e;let n=e.split(`
186
+ `),r=[],s=0;for(;s<n.length;){let o=n[s];r.push(o),s+=1;let i=mc.exec(o),a=i?t.get(i[2]):void 0;if(!i||a===void 0)continue;let d=i[1],l=d+cc,c=n[s];if(c===void 0||!c.startsWith(l)||!IO.test(c.slice(l.length)))continue;let m=TO(n,s-1,d);if(m!==void 0){for(r.push(`${l}<a href="${as(a)}">`);s<m;s+=1)r.push(cc+n[s]);r.push(`${l}</a>`)}}return r.join(`
187
+ `)},OO=e=>e.split(`
188
+ `).some(t=>mc.test(t)),MO=e=>new Set(e.split(`
189
+ `).flatMap(t=>mc.exec(t)?.[2]??[])),$i=(e,t)=>e.toLowerCase().endsWith(Ii)?MO(new TextDecoder().decode(t)):void 0,xy=(e,t)=>e.toLowerCase().endsWith(Ii)&&!OO(new TextDecoder().decode(t));var xt=class extends Error{path;problem;constructor(t,n){super(`Refused the diagram file ${t}: ${n}`),this.name="RefusedMediaError",this.path=t,this.problem=n}},NO=e=>e.length>=$y.length&&$y.every((t,n)=>e[n]===t),PO=(e,t)=>{let n=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return typeof n=="string"?{idPrefix:ny(n)}:{}},Ty=({manifest:e,mediaIndex:t})=>{let n=xO($O(e)),r=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),s=new TextEncoder,o=(i,a)=>{let d;try{d=r.decode(a)}catch{throw new xt(i,"the bytes are not UTF-8 text")}let l=PO(t,i),c=lc(d,l);if(c!==void 0)throw new xt(i,c);let m=AO(d,n);if(m===d)return a;let f=lc(m,l);if(f!==void 0)throw new xt(i,`once linked, ${f}`);return s.encode(m)};return(i,a)=>{let d=i.toLowerCase();if(d.endsWith(Ii))return o(i,a);if(!d.endsWith(Iy))throw new xt(i,`a diagram file is an ${Ii} or a ${Iy}, and this is neither`);if(!NO(a))throw new xt(i,"the bytes are not a PNG image");return a}};var Ay=(e,t)=>{let n=Ty(e),r=Oy(e),s=new Map,o=[],i=[];for(let{path:f,bytes:h}of t){if(h===void 0){o.push(f);continue}try{s.set(f,n(f,h))}catch(p){if(!(p instanceof xt))throw p;o.push(f),i.push({path:f,problem:p.problem})}}let a=new Set;for(let[f,h]of s){let p=r(f);p!==void 0&&xy(f,h)&&a.add(p)}let d=f=>{let h=r(f);return h!==void 0&&a.has(h)},l=new Map([...s].filter(([f])=>!d(f))),c=o.filter(f=>!d(f)),m=new Map;for(let[f,h]of l){let p=r(f),g=$i(f,h);p!==void 0&&g!==void 0&&m.set(p,g)}return{mediaBytesByPath:l,missingPaths:c,refusals:i.filter(({path:f})=>!d(f)),emptyDiagramIds:a,emptyDiagramPaths:t.map(({path:f})=>f).filter(d),stampsByDiagram:m,...LO(e,c,l)}},Oy=e=>{let t=e.mediaIndex??{};return n=>Object.hasOwn(t,n)?t[n]:void 0},LO=(e,t,n)=>{let r=e.mediaIndex??{},s=Oy(e),o=new Set([...n.keys()].map(s)),i=a=>{let d=s(a);return d!==void 0&&o.has(d)};return{missingDiagrams:or(t.filter(a=>!i(a)),r),partialDiagrams:or(t.filter(i),r)}},My=(e,{emptyDiagramIds:t,stampsByDiagram:n})=>Vo(zg(e,t),n,t);import{existsSync as fc,lstatSync as Py,realpathSync as DO,statSync as _O}from"node:fs";import{homedir as jO}from"node:os";import{basename as FO,dirname as qO,isAbsolute as Ly,join as Dy,relative as WO,resolve as Ir,sep as BO}from"node:path";var Ss=(e,t,n)=>{if(Ly(n))throw new u(`Refusing an absolute path from the bundle manifest: ${n}`);let r=Ir(e,t),s=Ir(e,n);if(s===r||!pc(r,s))throw new u(`Refusing a bundle path that escapes the content root: ${n}`);return s},pc=(e,t)=>{let n=WO(e,t);return n===""||!Ly(n)&&n!==".."&&!n.startsWith(`..${BO}`)},Is=(e,t,{ignoreCase:n=!1}={})=>{let r=Ny(e),s=Ny(t);return n?pc(r.toLowerCase(),s.toLowerCase()):pc(r,s)},On=e=>{try{return Py(e)}catch{return}},Mn=e=>{try{return _O(e)}catch{return}},Ny=e=>{let t=[],n=e;for(;!fc(n);){let s=qO(n);if(s===n)return e;t.unshift(FO(n)),n=s}let r=DO(n);return t.length>0?Dy(r,...t):r},Tt=e=>{if(On(e)?.isSymbolicLink())throw new u(`Refusing to write through an existing symlink at a managed path: ${e}`)},$s=(e,t)=>{if(!Is(e,t))throw new u(`Refusing a path that escapes the content root through a symlink: ${t}`)},uc=(e,t)=>{let n=Ir(e,t);if(n===Ir(e))throw new u(`The content root resolves to the repository root (${n}); refusing to sync it.`);if(n===Ir(jO()))throw new u("The content root resolves to your home directory; refusing to sync it.");if(fc(n)){if(Py(n).isSymbolicLink())throw new u(`The content root ${n} is a symlink; refusing to sync it.`);if(fc(Dy(n,".git")))throw new u(`The content root ${n} contains a .git directory (it looks like a repo root); refusing.`)}if(!Is(Ir(e),n))throw new u(`The content root ${n} resolves outside the repository via a symlinked ancestor; refusing.`);return n};var _y={respec:"data/model"},hc=e=>Object.hasOwn(_y,e)?_y[e]:void 0,xi=e=>{let t=hc(e);if(!t)throw new u(`The CLI does not know the content root for stack '${e}'.`);return t};var HO=1500,UO=6e5,VO=e=>new Promise(t=>setTimeout(t,e)),GO=e=>e==="COMPLETED"||e==="COMPLETED_WITH_ERRORS"||e==="FAILED",jy=async(e,t,n)=>{let r=await e.contentBundles.renderDiagrams(t,{template:n.template,version:n.version});if(!r.commit)throw new u("The diagram render did not return a resolved commit; cannot pin the pull.");return r},Fy=async(e,t,n,r,s,o={})=>{let i=o.sleep??VO,a=o.now??Date.now,d=a()+UO;for(r.update(0,s);;){let l=await e.exportJobs.get(t,n);if(l.progress&&r.update(l.progress.completed,l.progress.total,l.progress.currentItem),GO(l.status))return r.done(),l;if(a()>=d)throw new u("Timed out waiting for the diagram render to finish.");await i(HO)}},qy=(e,t,n,r)=>e.contentBundles.media(t,{path:n,template:r.template,commit:r.commit});var Wy=e=>{let t=new Map;for(let n of e.fragments??[])n.realization?.path&&t.set(n.elementId,n.realization.path);return t},By=(e,t)=>{let n=Wy(e),r=[];for(let[s,o]of Wy(t)){let i=n.get(s);i&&i!==o&&r.push({elementId:s,oldPath:i,newPath:o})}return r};import{existsSync as KO,mkdirSync as YO,readFileSync as zO,writeFileSync as JO}from"node:fs";import{join as Hy}from"node:path";var Uy=(e,t)=>Hy(e,ar,`${t}.manifest.json`),Ti=(e,t)=>{let n=Uy(e,t);if(!KO(n))return;let r;try{r=JSON.parse(zO(n,"utf8"))}catch{return}return XO(r)?r:void 0},XO=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let{fragments:t}=e;return t===void 0?!0:Array.isArray(t)&&t.every(n=>n!==null&&typeof n=="object")},Vy=(e,t,n)=>{YO(Hy(e,ar),{recursive:!0}),JO(Uy(e,t),Gl(n))},Gy=e=>{let t=[];for(let r of e.fragments??[]){r.realization?.path&&t.push(r.realization.path);for(let s of r.realization?.media??[])t.push(s)}let n=Uo(e);return n!==void 0&&t.push(n),t};import{existsSync as gc,lstatSync as QO,mkdirSync as Ky,readdirSync as ZO,readFileSync as eM,rmSync as tM,writeFileSync as Yy}from"node:fs";import{dirname as zy,join as $r,relative as nM,sep as rM}from"node:path";var Jy=(e,t)=>{let n=$r(e,t);if(!gc(n))return[];let r=[],s=o=>{for(let i of ZO(o,{withFileTypes:!0})){let a=$r(o,i.name);i.isDirectory()?s(a):i.isFile()&&r.push(nM(e,a).split(rM).join("/"))}};return s(n),r},yc=(e,t,n)=>{let r=$r(e,t);for(let s of n){let o=Ss(e,t,s.path);Tt(o),$s(r,o),Ky(zy(o),{recursive:!0}),Yy(o,s.content)}},sM=(e,t,n,r)=>{let s=$r(e,t),o=Ss(e,t,n);Tt(o),$s(s,o),Ky(zy(o),{recursive:!0}),Yy(o,r)},wc=(e,t,n,r)=>{let s=n.mediaIndex??{},o=$r(e,t),i=new Map;for(let a of r){let d=Object.hasOwn(s,a)?s[a]:void 0;if(d!==void 0)try{let l=Ss(e,t,a);if(!gc(l)||QO(l).isSymbolicLink())continue;$s(o,l);let c=$i(a,eM(l));c!==void 0&&i.set(d,c)}catch{}}return i},Xy=(e,t,n,r,s=Cn(n))=>{let o=[];for(let[l,c]of r.mediaBytesByPath)try{sM(e,t,l,c)}catch(m){o.push({path:l,error:m})}let i=new Map([...wc(e,t,n,sr(n.manifest)),...r.stampsByDiagram]),a=new Map(s.map(l=>[l.path,l.content])),d=Cn(My(n,{...r,stampsByDiagram:i})).filter(l=>a.get(l.path)!==l.content);return yc(e,t,d),o},bc=(e,t,n)=>{let r=Ss(e,t,n);return $s($r(e,t),r),gc(r)?(tM(r),!0):!1},Qy=(e,t,n)=>{for(let r of n)bc(e,t,r)};var oM=100,ew=e=>{if(e.newTextPaths.length===0&&!e.allowEmpty)throw new u("The content fetch returned no fragments (usually the wrong model or format, or a server error). Nothing was written or deleted. Re-run with --allow-empty only if the model is genuinely empty.");let t=Zy([...e.newTextPaths,...e.newMediaPaths]).sort(),n=new Set(t),r=new Set(e.existingFiles),s=t.filter(c=>r.has(c)),o=e.priorManifestPaths!==void 0?"manifest-tracked":"full-sync",i=e.priorManifestPaths??e.existingFiles,a=Zy(i).filter(c=>!n.has(c)).sort(),d=a.length>0&&!e.adopted,l=a.length>0&&(a.length>t.length||a.length>oM);return{writes:t,overwrites:s,orphanCandidates:a,mode:o,adoptionNeeded:d,outsized:l}},kc=(e,t)=>{if(e.orphanCandidates.length===0)return{deletes:[],warnings:[]};if(e.adoptionNeeded&&!t.adopt)return{deletes:[],warnings:[`${e.orphanCandidates.length} file(s) under the content root are not tracked by the CLI and were left in place. Pass --adopt to let the CLI manage (and prune) this directory.`]};if(e.outsized&&!t.yes)throw new u(`This pull would remove ${e.orphanCandidates.length} file(s), more than the ${e.writes.length} it writes. That often signals a wrong model or format. Nothing was changed. Re-run with --yes if intended.`);return{deletes:e.orphanCandidates,warnings:[]}},Zy=e=>[...new Set(e)];import{readdirSync as aM}from"node:fs";import{join as xs,posix as Ts}from"node:path";var nw=e=>{let t=mt(e),n=new Map;for(let r of e.fragments??[]){let s=n.get(r.elementId),o=r.realization?.path,i=o!==void 0&&(o===tw||o.endsWith(`/${tw}`));n.set(r.elementId,{elementId:r.elementId,title:t.get(r.elementId)?.title,kind:t.get(r.elementId)?.kind,path:s?.path??o,anchor:t.get(r.elementId)?.anchor,container:(s?.container??!1)||i})}return[...n.values()]},tw="index.md",Ec=e=>{let t=mt(e);return(e.fragments??[]).flatMap(n=>(n.anchors??[]).map(r=>({elementId:r.elementId,kind:r.kind,slug:r.address.split("/").at(-1)??"",owner:t.get(n.elementId)?.title})))},rw=(e,t)=>{let n=Tn(t);return n===""?[]:e.filter(r=>r.slug===n)},Ai=e=>e.replace(/\s+/g," ").trim().toLowerCase(),Cc=(e,t)=>{let n=Ai(t);return e.filter(r=>r.title!==void 0&&Ai(r.title)===n)},iM=5,sw=(e,t)=>{let n=Ai(t),r=n.length>=4?2:1,o=e.flatMap(i=>i.title===void 0?[]:[i.title]).filter(i=>{let a=Ai(i);return n.length>=3&&a.includes(n)||vc(a,n)<=r});return[...new Set(o)].slice(0,iM)},vc=(e,t)=>{let n=Array.from({length:t.length+1},(r,s)=>s);for(let r=1;r<=e.length;r+=1){let s=[r];for(let o=1;o<=t.length;o+=1)s[o]=Math.min(n[o]+1,s[o-1]+1,n[o-1]+(e[r-1]===t[o-1]?0:1));n=s}return n[t.length]};var Oi=".after.md",Nn=".md",iw=e=>e.toLowerCase().endsWith(Oi),aw=e=>iw(e)?"after":"intro",Mi=(e,t)=>{let n=ir(e);if(n!==void 0)return`the notes folder ${JSON.stringify(e)} ${n}; give a folder relative to the repository root`;if(be(e)===".")return"the notes folder is the repository root, so every Markdown file in the repository would be read as a note; give a folder of its own, such as md-notes/";if(Rn(e.toLowerCase(),t.toLowerCase())||Rn(t.toLowerCase(),e.toLowerCase()))return`the notes folder ${e} overlaps the content root ${t}/, which every pull replaces; keep notes outside it`},Ni=(e,t,n,r)=>{let s=`${be(t)}/`,o=be(n);if(!o.startsWith(s)||!o.endsWith(Nn))return;let i=o.slice(s.length,-Nn.length);return Ts.join(be(e),`${i}${r==="after"?Oi:Nn}`)},Rc=(e,t)=>On(xs(e,be(t)))?.isSymbolicLink()?`the notes folder ${be(t)} is a symlink, which the pull does not follow; make it a folder of its own, or set "notesDir" in .modeldesk/config.json to the folder it points to`:void 0,dw=(e,t)=>{let n=be(t),r=Rc(e,t);if(r!==void 0)throw new u(`${r[0].toUpperCase()}${r.slice(1)}.`);if(On(xs(e,n))?.isDirectory()!==!0)return[];let s=[],o=a=>{try{return aM(xs(e,a),{withFileTypes:!0})}catch(d){throw new u(`Could not read the notes folder ${a}: ${d.message}`)}},i=a=>{for(let d of o(a)){if(d.name.startsWith("."))continue;let l=Ts.join(a,d.name);d.isDirectory()?i(l):d.name.toLowerCase().endsWith(Nn)&&!dM(e,l,d)&&s.push(l)}};return i(n),s.sort()},dM=(e,t,n)=>n.isSymbolicLink()?Mn(xs(e,t))?.isDirectory()===!0:!1,lM=5,lw=({repoRoot:e,files:t,notesDir:n,contentRoot:r,manifest:s,entries:o})=>{let i=[...o.values()].flatMap(h=>Pe.flatMap(p=>h[p]===void 0?[]:[be(h[p])])),a=new Set(i),d=new Set(i.flatMap(h=>ow(e,h)??[])),l=h=>{if(a.has(be(h)))return!0;let p=ow(e,h);return p!==void 0&&d.has(p)},c=new Map;for(let h of s.fragments??[]){let p=h.realization?.path;p!==void 0&&!c.has(be(p))&&c.set(be(p),{elementId:h.elementId,title:h.title||void 0})}let m=[],f=new Map;for(let h of t.filter(p=>!l(p))){let p=aw(h),g=cM(n,r,h),w=g===void 0?void 0:c.get(g);if(w===void 0){m.push(mM(h,g,n,r,[...c.keys()]));continue}let k=o.get(w.elementId)?.[p],C=w.title??w.elementId;if(k!==void 0){m.push(`the note ${h} would be the ${p} note of ${C}, which notes.json already gives as ${k}; keep one of the two files.`);continue}let R=`${p} ${w.elementId}`,$=f.get(R);if($!==void 0){m.push(`the notes ${$.file} and ${h} would both be the ${p} note of ${C}, which appears at more than one place in the document; keep one of the two files.`);continue}f.set(R,{file:h,elementId:w.elementId,slot:p,title:w.title})}return{adoptions:[...f.values()],errors:m}},ow=(e,t)=>{let n=Mn(xs(e,t));return n?.isFile()?`${n.dev}:${n.ino}`:void 0},cM=(e,t,n)=>{let r=`${be(e)}/`,s=be(n);if(!s.startsWith(r))return;let o=s.slice(r.length),i=iw(o)?o.slice(0,-Oi.length):o.toLowerCase().endsWith(Nn)?o.slice(0,-Nn.length):void 0;return i===void 0?void 0:Ts.join(be(t),`${i}${Nn}`)},mM=(e,t,n,r,s)=>{let o=`A note's path is its element's file under ${be(r)}/ with ${be(n)}/ in its place, ending in ${Oi} for the note after the element's content.`;if(t===void 0)return`the note ${e} matches no element: its name does not end in .md. ${o}`;let i=Ts.basename(t),a=s.map(l=>({path:l,distance:vc(l,t)})).filter(({path:l,distance:c})=>Ts.basename(l)===i||c<=2).sort((l,c)=>l.distance-c.distance||l.path.localeCompare(c.path)).slice(0,lM).map(({path:l})=>Ni(n,r,l,aw(e))).filter(l=>l!==void 0),d=a.length===0?"":` Did you mean ${a.join(", ")}?`;return`the note ${e} matches no element: this bundle has no ${t}.${d} ${o}`},Sc=(e,t)=>{let n=new Map(e);for(let{file:r,elementId:s,slot:o,title:i}of t){let a=n.get(s);n.set(s,a===void 0?{...i===void 0?{}:{name:i},[o]:r}:{...a,[o]:r})}return n};import{join as Ic}from"node:path";var $c=({repoRoot:e,contentRoot:t,entries:n})=>[...n].flatMap(([r,s])=>Pe.flatMap(o=>{let i=s[o];return i===void 0?[]:fM(e,t,i).map(a=>`${xr(r,s.name)} ${o}: ${a}.`)})),cw=({manifest:e,slots:t,entries:n,notesDir:r})=>{let s=uM(e,t),o=[],i=[],d=[...n].some(([l,c])=>s.has(l)&&Pe.some(m=>c[m]!==void 0))&&t.size===0?`The server rendered stack ${e.stack} ${e.stackVersion}, which carries no note slots, so the notes cannot be placed. Either the server is older than note support, or this template has no slots: notes work with the MIM templates. Pull without notes by moving .modeldesk/notes.json and the notes folder ${r} aside, or pull again once the server is updated.`:void 0;for(let[l,c]of n){let m=s.get(l),f=xr(l,m?.title??c.name);if(m===void 0){i.push(`${f} is not in this bundle; its entry in notes.json is kept.`);continue}if(d===void 0)for(let h of Pe)c[h]!==void 0&&o.push(...pM(m,h).map(p=>`${f} ${h}: ${p}.`))}return{errors:o,warnings:i,slotless:d}},xc=e=>typeof e=="string"?e:e.file,Tc=(e,t,n)=>{let r=ir(n);if(r!==void 0)return[`the note path ${JSON.stringify(n)} ${r}; note paths are relative to the repository root`];if(Rn(n.toLowerCase(),t.toLowerCase()))return[`the note ${n} lies in the content root ${t}/, which every pull replaces, so the pull would remove it; keep notes outside it`];let s=Ic(e,n);return Is(Ic(e,t),s,{ignoreCase:!0})?[`the note ${n} lies in the content root ${t}/ through a symlink, and every pull replaces that folder, so the pull would remove it; keep notes outside it`]:Is(e,s)?[]:[`the note ${n} lies outside the repository through a symlink; keep notes inside it`]},fM=(e,t,n)=>{let r=Tc(e,t,n);if(r.length>0)return r;let s=Mn(Ic(e,n));return s===void 0?[`the note ${n} does not exist`]:s.isFile()?[]:[`the note ${n} is not a file`]},pM=(e,t)=>{let n=e.slots.get(t);if(n===void 0){let r=[...e.slots.keys()],s=e.kind===void 0?"the element":`this ${e.kind}`;return[r.length===0?`${s} carries no slots`:`${s} carries no ${t} slot, only ${r.join(" and ")}`]}return n.headed&&e.anchor===void 0?["the bundle's manifest gives the element no anchor to build the heading's id from"]:[]},uM=(e,t)=>{let n=new Map;for(let[r,s]of mt(e))n.set(r,{...s,slots:new Map});for(let r of(e.fragments??[]).flatMap(s=>s.anchors??[]))n.has(r.elementId)||n.set(r.elementId,{kind:r.kind,slots:new Map});for(let r of[...t.values()].flat()){let s=n.get(r.elementId)??{slots:new Map};n.set(r.elementId,s);let o=s.slots.get(r.name)?.headed??!1;s.slots.set(r.name,{headed:o||r.heading!==void 0})}return n},xr=(e,t)=>t===void 0?e:`${t} (${e})`;import{existsSync as hM,readFileSync as mw}from"node:fs";import{join as gM}from"node:path";var yM="notes.json",wM=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,bM=["name",...Pe],kM=e=>gM(e,ar,yM),Pi=e=>{let t=kM(e);if(!hM(t))return{path:t,entries:new Map};let n;try{n=mw(t,"utf8")}catch(o){throw new u(`Could not read ${t}: ${o.message}`)}let r;try{r=JSON.parse(n)}catch(o){throw new u(`${t} is not valid JSON: ${o.message}`)}if(!Ac(r))throw new u(`${t} must contain a JSON object with a "notes" object.`);for(let o of Object.keys(r))if(o!=="notes")throw new u(`${t}: unknown key "${o}"; the file holds only "notes".`);if(!Ac(r.notes))throw new u(`${t}: "notes" must be an object of entries keyed by element id.`);let s=new Map;for(let[o,i]of Object.entries(r.notes))s.set(o,vM(t,o,i));return CM(t,n,s),{path:t,entries:s,raw:n}},EM=/"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"\s*:/g,CM=(e,t,n)=>{let r=new Map;for(let[,s]of t.matchAll(EM))r.set(s,(r.get(s)??0)+1);for(let s of n.keys())if((r.get(s)??0)>1)throw new u(`${e}: notes key "${s}" appears more than once, and JSON keeps only the last; merge the entries.`)},vM=(e,t,n)=>{if(!wM.test(t))throw new u(`${e}: notes key "${t}" is not an element id. Entries are keyed by the element's id, a lowercase UUID as the bundle's manifest gives it.`);let r=`notes.${t}`;if(!Ac(n))throw new u(`${e}: ${r} must be an object.`);for(let s of Object.keys(n))if(!bM.includes(s))throw new u(`${e}: ${r} has an unknown key "${s}"; an entry takes "name", "intro" and "after".`);if(n.name!==void 0&&typeof n.name!="string")throw new u(`${e}: ${r}.name must be a string.`);for(let s of Pe)if(n[s]!==void 0&&typeof n[s]!="string")throw new u(`${e}: ${r}.${s} must be a note path. A note that comes under a heading names it on its own first line, <!-- heading: \u2026 -->.`);return n},Ac=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),fw=e=>{try{return mw(e,"utf8")}catch{return}};import{readFileSync as OM}from"node:fs";import{join as gw,posix as MM}from"node:path";var RM=/^ {0,3}(`{3,}|~{3,})/,Oc=/^(?: {4}|\t)/,SM=/^ {0,3}(?:[-+*]|\d{1,9}[.)])(?:[ \t]|$)/,uw=e=>{let t=[],n,r=!1,s=!0,o=!1;for(let i of e.split(/\r?\n/)){let a=i.trim()==="",d=RM.exec(i)?.[1];if(n!==void 0){d!==void 0&&d[0]===n[0]&&d.length>=n.length&&i.trim()===d&&(n=void 0);continue}if(!(r&&(a||Oc.test(i)))){if(r=!1,d!==void 0){n=d,s=!1;continue}if(Oc.test(i)&&s&&!o){r=!0;continue}a||(o=SM.test(i)||o&&Oc.test(i)),s=a,t.push(i)}}return t},IM=/(?<!`)(`+)(?!`)(.*?[^`])\1(?!`)/g,$M=/!\[([^\]]*)\]\(\s*(?:<([^>]*)>|([^\s)]+))(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*\)/g,xM=/<img\b([^>]*)>/gi,TM=/([^\s=/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g,hw=e=>{let t=uw(e).map(r=>r.replace(IM,s=>" ".repeat(s.length))).join(`
190
+ `),n=[];for(let r of t.matchAll($M))n.push({src:r[2]??r[3],alt:r[1],syntax:"markdown"});for(let r of t.matchAll(xM)){let s=new Map;for(let i of r[1].matchAll(TM))s.set(i[1].toLowerCase(),i[2]??i[3]??i[4]??"");let o=s.get("src");o!==void 0&&n.push({src:o,alt:s.get("alt"),syntax:"html"})}return n},AM=/^ {0,3}#{1,6}(?=[ \t]|$)(.*)$/,pw=/\s*\{#[^\s}]+\}$/,Mc=e=>uw(e).flatMap(t=>{let n=AM.exec(t);if(n===null)return[];let r=n[1].replace(/(?:^|[ \t]+)#+[ \t]*$/,"").trim(),s=pw.test(r),o=s?r.replace(pw,""):r;return o===""?[]:[{text:o,explicitId:s}]});var yw=e=>{let{repoRoot:t,manifest:n,slots:r,entries:s,notes:o,placed:i}=e,a=mt(n),d=p=>a.get(p)?.title??s.get(p)?.name,l=new Map;for(let{name:p,elementId:g}of i.filled){let w=o.get(g)?.[p],k=`${p} ${g}`;w!==void 0&&!l.has(k)&&l.set(k,{elementId:g,title:d(g)??g,slot:p,target:w})}let c=[],m=[],f=new Map;for(let{target:p}of l.values())f.set(xc(p),(f.get(xc(p))??0)+1);for(let[p,g]of f)try{m.push({file:p,text:OM(gw(t,p),"utf8"),slots:g})}catch(w){c.push(`could not read the note ${p}, so its images and headings were not checked: ${Fe(w)}`)}for(let p of m)c.push(...LM(t,p.file,p.text,e.publishDirs));c.push(...DM(m),..._M(n,i.dropped,d));let h=[...r.values()].reduce((p,g)=>p+g.length,0);return{warnings:c,substitutions:[...l.values()],removedSlots:h-i.filled.length}},NM=/^(?:https?:|data:|\/\/)/i,PM=e=>{let t=e.replace(/[?#].*$/,""),n=t;try{n=decodeURIComponent(t)}catch{}return MM.normalize(n.replace(/^\/+/,""))},LM=(e,t,n,r)=>hw(n).flatMap(({src:s,alt:o,syntax:i})=>{let a=[];if((o===void 0||i==="markdown"&&o.trim()==="")&&a.push(`the note ${t} has an image without alt text, ${s}; describe it for readers who cannot see it.`),NM.test(s))return a;let d=PM(s);if(d==="."||d==="")return a;if(Mn(gw(e,d))?.isFile()!==!0){let l=d===s?"":` (${d} in the repository)`;a.push(`the note ${t} links the image ${s}${l}, which does not exist; image paths resolve against the repository root.`)}return r!==void 0&&!r.some(l=>Rn(d,l))&&a.push(`the note ${t} links the image ${s}, which lies outside the publishDirs (${r.join(", ")||"none"}), so the published copy will miss it.`),a}),DM=e=>{let t=new Map;for(let s of e)for(let o of Mc(s.text)){if(o.explicitId)continue;let i=Tn(o.text),a=t.get(i)??{text:o.text,files:[]};a.files.includes(s.file)||t.set(i,{...a,files:[...a.files,s.file]})}let n=[...t.values()].filter(({files:s})=>s.length>1).map(({text:s,files:o})=>`the notes ${o.join(" and ")} each have the heading "${s}" without an explicit {#id}. ReSpec numbers the later ids, so a link to one shifts when the notes change; give each heading its own {#id}.`),r=e.filter(s=>s.slots>1&&Mc(s.text).length>0).map(s=>`the note ${s.file} fills ${s.slots} slots, so each of its headings appears ${s.slots} times and their ids repeat or get numbered; give each place its own note file.`);return[...n,...r]},_M=(e,t,n)=>{let r=new Map((e.fragments??[]).map(o=>[o.address,o.realization?.path])),s=new Map;for(let{name:o,elementId:i,address:a}of t){let d=`${o} ${i}`,l=s.get(d)??{slot:o,elementId:i,files:new Set};s.set(d,{...l,files:l.files.add(r.get(a)??a)})}return[...s.values()].map(({slot:o,elementId:i,files:a})=>`${xr(i,n(i))} appears more than once in ${[...a].join(", ")}; its ${o} note goes in at the first place only.`)};import{renameSync as jM,rmSync as ww,writeFileSync as FM}from"node:fs";var bw=(e,t)=>{let n=mt(t);return[...e].flatMap(([r,s])=>{let o=n.get(r)?.title;return o===void 0||o===s.name?[]:[{elementId:r,from:s.name,to:o}]})},kw=(e,t)=>{let n=new Map(t.map(r=>[r.elementId,r.to]));return new Map([...e].map(([r,s])=>{let o=n.get(r);return o===void 0?[r,s]:[r,"name"in s?{...s,name:o}:{name:o,...s}]}))},Tr=e=>`${JSON.stringify({notes:Object.fromEntries(e)},null,2)}
191
+ `,Li=(e,t)=>{Tt(e);let n=`${e}.tmp`;try{ww(n,{force:!0}),FM(n,t,{flag:"wx"}),jM(n,e)}catch(r){throw ww(n,{force:!0}),r}};import{readFileSync as WM}from"node:fs";import{join as BM}from"node:path";var qM=/^<!--\s*heading:(.*)-->$/i,Ew=e=>{let t=e.split(/\r?\n/).find(n=>n.trim()!=="");return t===void 0?void 0:qM.exec(t.trim())?.[1].trim()},Di=e=>`<!-- heading: ${e} -->`,As=e=>{if(e.trim()==="")return"is blank";if(/[\r\n]/.test(e))return"has a line break";let t=["-->","--!>"].find(n=>e.includes(n));return t===void 0?void 0:`has "${t}", which would end the heading line early`};var Cw=({repoRoot:e,slots:t,entries:n})=>{let r=[...t.values()].flat(),s=new Set(r.flatMap(l=>l.heading===void 0?[]:[`${l.name} ${l.elementId}`])),o=new Set(r.map(l=>l.elementId)),i=new Map,a=[],d=[];for(let[l,c]of n){let m={};for(let f of Pe){let h=c[f];if(h===void 0)continue;if(!o.has(l)){m[f]=h;continue}let p=HM(e,h),g=`${xr(l,c.name)} ${f}`;s.has(`${f} ${l}`)?p===void 0||p===""?a.push(`${g}: the note ${h} comes under a heading of its own, so its first line names it, such as ${Di("Afsluiting")}.`):As(p)!==void 0?a.push(`${g}: the heading line of the note ${h} ${As(p)}.`):m[f]={file:h,heading:p}:(p!==void 0&&d.push(`${g}: the note ${h} starts with a heading line, which only the closing note of a package or the model takes; the line is left as a comment.`),m[f]=h)}i.set(l,m)}return{notes:i,errors:a,warnings:d}},HM=(e,t)=>{try{return Ew(WM(BM(e,t),"utf8"))}catch{return}};var UM=(e,t)=>{let n=t>0?Math.min(1,e/t):0,r=Math.round(n*24);return`[${"#".repeat(r)}${"-".repeat(24-r)}]`},vw=(e,t=n=>{process.stderr.write(n)})=>{let n=-1;return{update(r,s,o){if(e){let i=o?` ${o}`:"";t(`\r${UM(r,s)} ${r}/${s}${i}\x1B[K`)}else if(r!==n){let i=o?` (${o})`:"";t(`Rendering diagrams: ${r}/${s}${i}
27
192
  `),n=r}},done(){e&&t(`
28
- `)}}};import{createInterface as dd}from"node:readline";var de=()=>!!(process.stdin.isTTY&&process.stdout.isTTY),Lo=async e=>{let t=dd({input:process.stdin,output:process.stderr});try{return await new Promise(n=>{t.once("close",()=>n(void 0)),t.question(e,n)})}finally{t.close()}},kn=async e=>{if(!de())return!1;let t=await Lo(`${e} [y/N] `);return t!==void 0&&/^y(es)?$/i.test(t.trim())},Do=async(e,t)=>{if(!de())return;let n=await Lo(`${e} [1-${t}] `);if(n===void 0)return;let r=Number(n.trim());return Number.isInteger(r)&&r>=1&&r<=t?r-1:void 0};var v=e=>{process.stdout.write(e)},R=e=>{process.stderr.write(e)},En=e=>{for(let t of e)R(`warning: ${t}
29
- `)},Oo=e=>{for(let t of e)R(` ${t}
30
- `)},Uo=async e=>{let{values:t}=X(e.argv,{host:{type:"string"},model:{type:"string"},stack:{type:"string"},template:{type:"string"},version:{type:"string"},"no-diagrams":{type:"boolean"},"dry-run":{type:"boolean"},"allow-empty":{type:"boolean"},adopt:{type:"boolean"},yes:{type:"boolean"}}),n=Ge(e,{host:t.host,model:t.model,stack:t.stack,template:t.template,version:t.version}),r={noDiagrams:!!t["no-diagrams"],dryRun:!!t["dry-run"],allowEmpty:!!t["allow-empty"],adopt:!!t.adopt,yes:!!t.yes},o=it(n.instance,e.env),s=ve(n.stack,"stack",k.stack,"--stack"),i=ve(n.template,"template",k.template,"--template"),{repoRoot:a}=n.loaded,d=mt(a),c=n.loaded.config.notesDir??We,f=tn(s);f!==void 0&&(ld(c,f),ut(pn({repoRoot:a,contentRoot:f,entries:d.entries})));let u=!r.noDiagrams&&!r.dryRun?await Gr(o,n.model,{template:i,version:n.version}):void 0,h=u?.commit,p=await o.getJson(`/models/${n.model}/content-bundle`,{template:i,commit:h,version:h?void 0:n.version});if(p.manifest.stack!==s)throw new l(`Requested stack '${s}', but template '${i}' renders under stack '${p.manifest.stack}'. Run 'modeldesk bundle templates' to see valid stack/template pairs.`);let y=ot(s);en(a,y);let{adoptions:E,errors:g}=Eo({repoRoot:a,files:ko(a,c),notesDir:c,contentRoot:y,manifest:p.manifest,entries:d.entries});ut([...g,...pn({repoRoot:a,contentRoot:y,entries:md(E)})]);let w=mn(d.entries,E),b=Fo(()=>or(p));cd($o({manifest:p.manifest,slots:b,entries:w,notesDir:c}));let N=Po({repoRoot:a,slots:b,entries:w});En(N.warnings),ut(N.errors);let I=Fo(()=>Mt(p,N.notes)),{bundle:M}=I,L=Co({repoRoot:a,manifest:p.manifest,slots:b,entries:w,notes:N.notes,placed:I,publishDirs:n.loaded.config.publishDirs});En(L.warnings);let F=Ao(w,M.manifest),H=Mo(w,F),x=Ee(H)!==Ee(d.entries),Z=oe(M),Q=tt(M.manifest),wt=ye(Q,M.mediaIndex),$e=st(n.loaded.repoRoot,s),kt=co({newTextPaths:Z.map(Zo=>Zo.path),newMediaPaths:Q,priorManifestPaths:$e?Qr($e):void 0,existingFiles:oo(n.loaded.repoRoot,y),adopted:$e!==void 0||ze(n.loaded),allowEmpty:r.allowEmpty}),Sn=$e?Xr($e,M.manifest):[],Tn={stack:s,version:M.manifest.stackVersion};if(r.dryRun)return Ho(n,i,Tn,h,kt,void 0,Sn,wt,!0),wd(L,E,F),0;x&&z(d.path);let In=await pd(kt,r);return Ho(n,i,Tn,h,kt,In,Sn,wt,!1),en(a,y),nn(a,y,Z),io(a,y,In.deletes),Zr(a,s,M.manifest),x&&fd(d,H,E.length,F.length),Q.length===0||!u?0:ud(o,n,i,h,u,M,{media:Q,diagramCount:wt},y)},Fo=e=>{try{return e()}catch(t){throw t instanceof Ce?new l(`${t.message} Update @modeldesk/cli and pull again.`):t}},cd=e=>{if(En(e.warnings),e.slotless!==void 0)throw new l(e.slotless);ut(e.errors)},ut=e=>{if(e.length>0)throw new l(`The notes have ${e.length} problem(s), so the pull stopped before writing anything:
193
+ `)}}};var $w=q({path:["bundle","pull"],effect:"local",summary:"Materialize a model's content bundle into a local folder",description:"A full sync of the content root (for ReSpec, data/model/): writes every generated fragment, removes files a previous pull left orphaned, then renders and fetches the diagrams, all pinned to one commit. Text lands first, so a diagram failure leaves valid text and exits 1. A removal larger than the write set needs --yes (exit 6 when not interactive), and a content root the CLI has not managed before is pruned only with --adopt. The repo's element notes (.modeldesk/notes.json and the notes folder) fill the slots the bundle carries; a problem in them stops the pull before anything is written.",flags:{model:{type:"string",placeholder:"id",description:"The model's UUID (default: MODELDESK_MODEL or the repo config)."},stack:{type:"string",placeholder:"id",description:"The content stack to render (required via flag, env or config; see bundle templates)."},template:{type:"string",placeholder:"slug",description:"The document shape within the stack (required via flag, env or config; see bundle templates)."},version:{type:"string",placeholder:"name",description:"Pin a released model version for a reproducible pull (default: live HEAD)."},"no-diagrams":{type:"boolean",description:"Write text fragments only; skip the diagram render and fetch."},adopt:{type:"boolean",description:"Allow the CLI to prune a content root it did not previously manage."},"allow-empty":{type:"boolean",description:"Permit a pull that returns no fragments (a genuinely emptied model)."}},dryRun:!0,examples:["modeldesk bundle pull","modeldesk bundle pull --model <model> --stack respec --template conceptueel-toc --dry-run"],run:async e=>{let{flags:t,globals:n}=e,r=zo(e,{model:t.model,stack:t.stack,template:t.template,version:t.version}),s=e.api(),o=ms(r.stack,"stack",B.stack,"--stack"),i=ms(r.template,"template",B.template,"--template"),{repoRoot:a}=r.loaded,d=Pi(a),l=r.loaded.config.notesDir??Ko,c=hc(o);c!==void 0&&(GM(l,c),_i($c({repoRoot:a,contentRoot:c,entries:d.entries})));let f=!t["no-diagrams"]&&!n.dryRun?await jy(s,r.model,{template:i,version:r.version}):void 0,h=f?.commit,p=await s.contentBundles.get(r.model,{template:i,commit:h,version:h?void 0:r.version});if(p.manifest.stack!==o)throw new u(`Requested stack '${o}', but template '${i}' renders under stack '${p.manifest.stack}'. Run 'modeldesk bundle templates' to see valid stack/template pairs.`);let g=xi(o);uc(a,g);let{adoptions:w,errors:k}=lw({repoRoot:a,files:dw(a,l),notesDir:l,contentRoot:g,manifest:p.manifest,entries:d.entries});_i([...k,...$c({repoRoot:a,contentRoot:g,entries:KM(w)})]);let C=Sc(d.entries,w),R=Rw(()=>Qg(p)),$=cw({manifest:p.manifest,slots:R,entries:C,notesDir:l});$.warnings.forEach(Te=>e.warn(Te)),VM($);let v=Cw({repoRoot:a,slots:R,entries:C});v.warnings.forEach(Te=>e.warn(Te)),_i(v.errors);let T=Rw(()=>Kl(p,v.notes)),{bundle:N}=T,E=yw({repoRoot:a,manifest:p.manifest,slots:R,entries:C,notes:v.notes,placed:T,publishDirs:r.loaded.config.publishDirs});E.warnings.forEach(Te=>e.warn(Te));let S=[...$.warnings,...v.warnings,...E.warnings],x=bw(C,N.manifest),A=kw(C,x),O=Tr(A)!==Tr(d.entries),L=sr(N.manifest),V=wc(a,g,N,L),ne=Cn(Vo(N,V,new Set)),K=or(L,N.mediaIndex),H=Ti(a,o),we=ew({newTextPaths:ne.map(Te=>Te.path),newMediaPaths:L,priorManifestPaths:H?Gy(H):void 0,existingFiles:Jy(a,g),adopted:H!==void 0||Yo(r.loaded),allowEmpty:t["allow-empty"]}),Ft=H?By(H,N.manifest):[],de={stack:o,version:N.manifest.stackVersion},Kp=Te=>({host:r.instance.host,model:r.model,stack:o,stackVersion:de.version,template:i,...h?{commit:h}:{},...r.version?{version:r.version}:{},dryRun:n.dryRun,syncMode:we.mode,written:we.writes.length,overwritten:we.overwrites.length,removed:Te?Te.deletes:we.orphanCandidates,withheld:Te?.deletes.length===0?we.orphanCandidates.length:0,moved:Ft.map(Fo=>({from:Fo.oldPath,to:Fo.newPath})),diagrams:{count:K,status:"skipped",failed:[],leftOut:[]},notes:{adopted:w.map(Fo=>Fo.file),filled:E.substitutions.length,renamed:x.length,slotsRemoved:E.removedSlots},warnings:[...S,...Te?.warnings??[]]});if(n.dryRun)return Iw(e,r,i,de,h,we,void 0,Ft,K,!0),eN(e,E,w,x),{result:Kp(void 0)};O&&Tt(d.path);let Jd=await zM(e,we,t.adopt);Iw(e,r,i,de,h,we,Jd,Ft,K,!1),uc(a,g),yc(a,g,ne),Qy(a,g,Jd.deletes),Vy(a,o,N.manifest);let Yp=[],zp={...e,warn:Te=>{Yp.push(Te),e.warn(Te)}};O&&YM(zp,d,A,w.length,x.length);let Jp=Kp(Jd),Xp=()=>({...Jp,warnings:[...Jp.warnings,...Yp]});if(L.length===0||!f)return{result:Xp()};let Qp=await JM(zp,s,r,{template:i,commit:h,job:f,bundle:N,media:L,written:ne},{diagramCount:K,contentRoot:g});return{result:{...Xp(),diagrams:{count:K,...Qp}},exitCode:Qp.status==="complete"?b.Success:b.Failure}}}),Rw=e=>{try{return e()}catch(t){throw t instanceof Cs?new u(`${t.message} Update @modeldesk/cli and pull again.`):t}},VM=e=>{if(e.slotless!==void 0)throw new u(e.slotless);_i(e.errors)},_i=e=>{if(e.length>0)throw new u(`The notes have ${e.length} problem(s), so the pull stopped before writing anything:
31
194
  `+e.map(t=>` - ${t}`).join(`
32
- `))},ld=(e,t)=>{let n=ct(e,t);if(n!==void 0)throw new l(`${n[0].toUpperCase()}${n.slice(1)}. Set "notesDir" in .modeldesk/config.json.`)},md=e=>mn(new Map,e),fd=(e,t,n,r)=>{if(bo(e.path)!==e.raw){R(`warning: ${e.path} changed while the pull ran, so the pull left it as it is. Pull again to record the new notes and names in it.
33
- `);return}ft(e.path,Ee(t));let o=[...n>0?[`${n} note(s) added`]:[],...r>0?[`${r} name(s) updated`]:[]];v(` notes.json: ${o.join(", ")||"rewritten"}
34
- `)},pd=async(e,t)=>{let{adopt:n,yes:r}=t;if(e.orphanCandidates.length===0)return on(e,{adopt:n,yes:r});let o=de();return e.adoptionNeeded&&!n&&(R(`The content root has ${e.orphanCandidates.length} file(s) the CLI does not track:
35
- `),Oo(e.orphanCandidates),o&&(n=await kn("Adopt this directory and allow the CLI to remove these files?"))),e.outsized&&!r&&(n||!e.adoptionNeeded)&&(R(`This pull would remove ${e.orphanCandidates.length} file(s), more than the ${e.writes.length} it writes:
36
- `),Oo(e.orphanCandidates),o&&(r=await kn("Proceed with removing them?"))),on(e,{adopt:n,yes:r})},ud=async(e,t,n,r,o,s,{media:i,diagramCount:a},d)=>{let c=_o(de()),f=await Kr(e,t.model,o.id,c,a);if(f.status==="FAILED")return R(`warning: the diagram render failed. Text fragments are written; media was not fetched. Re-run to retry.
37
- `),1;let{repoRoot:m}=t.loaded,u=[],h=new Map;for(let w of i)try{u.push({path:w,bytes:await Vr(e,t.model,w,{template:n,commit:r})})}catch(b){u.push({path:w}),h.set(w,b)}let p=Fr(s,u),y=so(m,d,s,p),E=new Map(p.refusals.map(({path:w,problem:b})=>[w,b]));for(let w of p.missingPaths){let b=E.get(w),N=h.get(w);R(b!==void 0?`warning: refused the diagram file ${w} and did not write it: ${b}
38
- `:`warning: could not fetch media ${w}: ${ce(N)}
39
- `),(b!==void 0||yd(N))&&Bo(m,d,w)}for(let{path:w,error:b}of y)R(`warning: could not write media ${w}: ${ce(b)}
40
- `);p.emptyDiagramIds.size>0&&hd(m,d,p.emptyDiagramIds.size,p.emptyDiagramPaths);let g=p.missingPaths.length+y.length;return f.status==="COMPLETED_WITH_ERRORS"||g>0?(R(`warning: ${g} media file(s) could not be written; the pull is re-runnable.
41
- `),1):0},hd=(e,t,n,r)=>{v(` Left out ${n} empty diagram(s), which draw no model element:
42
- `);for(let o of r.filter(s=>s.toLowerCase().endsWith(".svg")))v(` - ${o}
43
- `);for(let o of r)Bo(e,t,o,s=>v(` ${s}`))},gd=404,yd=e=>e instanceof J&&e.status===gd,Bo=(e,t,n,r=o=>R(`warning: ${o}`))=>{try{rn(e,t,n)&&r(`removed the copy of ${n} an earlier pull wrote.
44
- `)}catch(o){R(`warning: could not remove the copy of ${n} an earlier pull wrote: ${ce(o)}
45
- `)}},Ho=(e,t,n,r,o,s,i,a,d)=>{let c=r?`commit ${r}`:e.version?`version ${e.version}`:"HEAD",f=`${n.stack} ${n.version}`;v(`${d?"Dry run: ":""}Pulling ${e.model} (stack ${f}, template ${t}) at ${c} into ${e.instance.host}.
46
- `),v(` Write: ${o.writes.length} file(s)${o.overwrites.length?` (${o.overwrites.length} overwritten)`:""}
47
- `),v(` Diagrams: ${a}
48
- `);let m=d?o.orphanCandidates:s?.deletes??[];v(` Remove: ${m.length} file(s) [${o.mode}]
49
- `);for(let u of m)v(` - ${u}
50
- `);if(d)o.adoptionNeeded&&v(` note: removing these needs --adopt (the root is not CLI-managed yet).
51
- `),o.outsized&&v(` note: this removal is larger than the write set and needs --yes.
52
- `);else for(let u of s?.warnings??[])R(`warning: ${u}
53
- `);for(let u of i)v(` moved: ${u.oldPath} -> ${u.newPath}
54
- `);if(d)for(let u of o.writes)v(` write ${u}
55
- `)},wd=(e,t,n)=>{for(let{file:r,elementId:o,slot:s,title:i}of t)v(` adopt ${r}: ${i??o} ${s}
56
- `);for(let{title:r,slot:o,target:s}of e.substitutions){let i=typeof s=="string"?s:`${s.file} under the heading "${s.heading}"`;v(` fill ${r} ${o}: ${i}
57
- `)}v(` slots removed: ${e.removedSlots}
58
- `);for(let{elementId:r,from:o,to:s}of n)v(` rename ${r} in notes.json: ${o===void 0?"(no name)":`"${o}"`} -> "${s}"
59
- `)};var ht=e=>{let t=[];for(let n of e)n.forEach((r,o)=>{t[o]=Math.max(t[o]??0,r.length)});return t},q=(e,{indent:t="",gap:n=2,widths:r}={})=>{let s=ht(e).map((a,d)=>r?.[d]??a),i=" ".repeat(n);return e.map(a=>t+a.map((d,c)=>c===a.length-1?d:d.padEnd(s[c])).join(i))};var kd=["STACK","TEMPLATE","NAME"],jo=async e=>{let{values:t}=X(e.argv,{host:{type:"string"},model:{type:"string"},stack:{type:"string"}}),n=Ge(e,{host:t.host,model:t.model}),r=it(n.instance,e.env),o=await r.getJson(`/models/${n.model}`),s=(o.metamodelExtensions??[]).map(u=>u.id),i=s.length>0?{metamodelExtensions:s.join(",")}:void 0,{items:a}=await r.getJson(`/metamodels/${o.metamodel.id}/templates`,i),d=a??[];if(d.length===0)return process.stdout.write(`This model has no document templates.
60
- `),0;let c=t.stack,f=c?d.filter(u=>u.stack===c):d;if(f.length===0)return process.stdout.write(`No document templates for stack '${c}'.
61
- `),0;let m=f.map(u=>[u.stack??"",u.key??u.id,u.name]);for(let u of q([kd,...m]))process.stdout.write(`${u}
62
- `);return 0};import{mkdirSync as Ed,rmdirSync as $d,rmSync as xd,writeFileSync as bd}from"node:fs";import{dirname as $n,join as Wo,posix as gt}from"node:path";var Sd=e=>{process.stdout.write(e)},xn=e=>{process.stderr.write(e)},zo=async e=>{let{values:t,positionals:n}=X(e.argv,{slot:{type:"string"},heading:{type:"string"},dir:{type:"string"},element:{type:"string"},stack:{type:"string"}},{positionals:!0}),r=Ie(e.cwd),{repoRoot:o}=r,s=ve(Se({stack:t.stack},e.env,r.config).stack,"stack",k.stack,"--stack"),i=Td(t.slot),a=st(o,s);if(a===void 0)throw new l("Run 'modeldesk bundle pull' first: note add finds the element in the last pull's manifest.");let d=po(a),c=await Id(a,d,n.join(" "),t.element),f=yt(c),m=Cd(c,i,f,t.heading),u=ot(s),h=r.config.notesDir??We,p=Nd(o,u,t.dir??h,c,i),y=Wo(o,p),E=mt(o),g=E.entries.get(c.elementId),w=g?.[i];if(w!==void 0){let x=se(Wo(o,w))===void 0?"That file does not exist yet: create it":"Write in that file";throw new l(`${f} already has an ${i} note, ${w}. ${x}, or take the entry out of ${E.path} first.`)}let b=[...E.entries].find(([,x])=>A.some(Z=>x[Z]!==void 0&&gt.normalize(x[Z])===gt.normalize(p)));if(b!==void 0)throw new l(`${E.path} already names ${p} as a note of ${b[1].name??b[0]}; pick another folder with --dir.`);if(se(y)!==void 0){let x=c.path!==void 0&&lt(h,u,c.path,i)===p;throw new l(Ad(p,f,i,x))}z(E.path);let N=gt.dirname(p),I;try{I=Ed($n(y),{recursive:!0})}catch(x){throw new l(`Could not create ${N}: ${x.message}`)}let M=()=>{if(I!==void 0)for(let x=$n(y);;x=$n(x)){try{$d(x)}catch{return}if(x===I)return}};try{bd(y,m===void 0?"":`${pt(m)}
195
+ `))},GM=(e,t)=>{let n=Mi(e,t);if(n!==void 0)throw new u(`${n[0].toUpperCase()}${n.slice(1)}. Set "notesDir" in .modeldesk/config.json.`)},KM=e=>Sc(new Map,e),YM=(e,t,n,r,s)=>{if(fw(t.path)!==t.raw){e.warn(`${t.path} changed while the pull ran, so the pull left it as it is. Pull again to record the new notes and names in it.`);return}Li(t.path,Tr(n));let o=[...r>0?[`${r} note(s) added`]:[],...s>0?[`${s} name(s) updated`]:[]];e.print(` notes.json: ${o.join(", ")||"rewritten"}
196
+ `)},zM=async(e,t,n)=>{let r=n,s=e.globals.yes;if(t.orphanCandidates.length===0)return kc(t,{adopt:r,yes:s});if(t.adoptionNeeded&&!r&&(e.io.err(`The content root has ${t.orphanCandidates.length} file(s) the CLI does not track:
197
+ `),Sw(e,t.orphanCandidates),r=await e.confirm("Adopt this directory and allow the CLI to remove these files?")),t.outsized&&!s&&(r||!t.adoptionNeeded)){if(e.io.err(`This pull would remove ${t.orphanCandidates.length} file(s), more than the ${t.writes.length} it writes:
198
+ `),Sw(e,t.orphanCandidates),!e.interactive)throw new u(`This pull would remove ${t.orphanCandidates.length} file(s), more than the ${t.writes.length} it writes, and this run cannot ask for confirmation. Nothing was changed.`,{exitCode:b.NeedsHuman,hint:"Re-run with --yes if the removal is intended."});s=await e.confirm("Proceed with removing them?")}return kc(t,{adopt:r,yes:s})},Sw=(e,t)=>{for(let n of t)e.io.err(` ${n}
199
+ `)},JM=async(e,t,n,{template:r,commit:s,job:o,bundle:i,media:a,written:d},{diagramCount:l,contentRoot:c})=>{let m=vw(e.interactive,v=>{e.globals.json||e.io.err(v)}),f=await Fy(t,n.model,o.id,m,l);if(f.status==="FAILED")return e.warn("the diagram render failed. Text fragments are written; media was not fetched. Re-run to retry."),{status:"failed",failed:a,leftOut:[]};let{repoRoot:h}=n.loaded,p=[],g=new Map;for(let v of a)try{p.push({path:v,bytes:await qy(t,n.model,v,{template:r,commit:s})})}catch(T){p.push({path:v}),g.set(v,T)}let w=Ay(i,p),k=new Map(w.refusals.map(({path:v,problem:T})=>[v,T]));for(let v of w.missingPaths){let T=k.get(v),N=g.get(v);T!==void 0?e.warn(`refused the diagram file ${v} and did not write it: ${T}`):e.warn(`could not fetch media ${v}: ${Fe(N)}`),(T!==void 0||ZM(N))&&Tw(e,h,c,v)}let C=Xy(h,c,i,w,d);for(let{path:v,error:T}of C)e.warn(`could not write media ${v}: ${Fe(T)}`);let R=w.emptyDiagramPaths.filter(xw);w.emptyDiagramIds.size>0&&XM(e,h,c,w.emptyDiagramIds.size,w.emptyDiagramPaths);let $=[...w.missingPaths,...C.map(({path:v})=>v)];return f.status==="COMPLETED_WITH_ERRORS"||$.length>0?(e.warn(`${$.length} media file(s) could not be written; the pull is re-runnable.`),{status:"partial",failed:$,leftOut:R}):{status:"complete",failed:$,leftOut:R}},xw=e=>e.toLowerCase().endsWith(".svg"),XM=(e,t,n,r,s)=>{e.print(` Left out ${r} empty diagram(s), which draw no model element:
200
+ `);for(let o of s.filter(xw))e.print(` - ${o}
201
+ `);for(let o of s)Tw(e,t,n,o,i=>e.print(` ${i}
202
+ `))},QM=404,ZM=e=>e instanceof U&&e.status===QM,Tw=(e,t,n,r,s=e.warn)=>{try{bc(t,n,r)&&s(`removed the copy of ${r} an earlier pull wrote.`)}catch(o){e.warn(`could not remove the copy of ${r} an earlier pull wrote: ${Fe(o)}`)}},Iw=(e,t,n,r,s,o,i,a,d,l)=>{let c=e.print,m=s?`commit ${s}`:t.version?`version ${t.version}`:"HEAD",f=`${r.stack} ${r.version}`;c(`${l?"Dry run: ":""}Pulling ${t.model} (stack ${f}, template ${n}) at ${m} into ${t.instance.host}.
203
+ `),c(` Write: ${o.writes.length} file(s)${o.overwrites.length?` (${o.overwrites.length} overwritten)`:""}
204
+ `),c(` Diagrams: ${d}
205
+ `);let h=l?o.orphanCandidates:i?.deletes??[];c(` Remove: ${h.length} file(s) [${o.mode}]
206
+ `);for(let p of h)c(` - ${p}
207
+ `);if(l)o.adoptionNeeded&&c(` note: removing these needs --adopt (the root is not CLI-managed yet).
208
+ `),o.outsized&&c(` note: this removal is larger than the write set and needs --yes.
209
+ `);else for(let p of i?.warnings??[])e.warn(p);for(let p of a)c(` moved: ${p.oldPath} -> ${p.newPath}
210
+ `);if(l)for(let p of o.writes)c(` write ${p}
211
+ `)},eN=(e,t,n,r)=>{let s=e.print;for(let{file:o,elementId:i,slot:a,title:d}of n)s(` adopt ${o}: ${d??i} ${a}
212
+ `);for(let{title:o,slot:i,target:a}of t.substitutions){let d=typeof a=="string"?a:`${a.file} under the heading "${a.heading}"`;s(` fill ${o} ${i}: ${d}
213
+ `)}s(` slots removed: ${t.removedSlots}
214
+ `);for(let{elementId:o,from:i,to:a}of r)s(` rename ${o} in notes.json: ${i===void 0?"(no name)":`"${i}"`} -> "${a}"
215
+ `)};var tN=["STACK","TEMPLATE","NAME"],Aw=q({path:["bundle","templates"],effect:"read",summary:"List a model's document templates",description:"Lists the stack/template pairs a model can be pulled as, one per document shape. A template slug is unique only within its stack, so bundle pull takes both.",flags:{model:{type:"string",placeholder:"id",description:"The model's UUID (default: MODELDESK_MODEL or the repo config)."},stack:{type:"string",placeholder:"id",description:"List only the templates of this content stack."}},listing:{narrowHint:"Pass --stack to list one content stack."},examples:["modeldesk bundle templates --model <model>","modeldesk bundle templates --stack respec --json"],run:async e=>{let t=zo(e,{model:e.flags.model}),n=e.api(),r=await n.models.get(t.model),s=(r.metamodelExtensions??[]).map(m=>m.id),{items:o}=await n.metamodels.templates(r.metamodel.id,{metamodelExtensions:s}),i=e.flags.stack,a=o??[],d=a.filter(m=>!i||m.stack===i).map(m=>({stack:m.stack??"",template:m.key??m.id,name:m.name,id:m.id})),l=await e.list(d);return{result:{model:t.model,...i?{stack:i}:{},modelTemplateCount:a.length,...l}}},render:({items:e,stack:t,modelTemplateCount:n})=>{if(n===0)return"This model has no document templates.";if(e.length===0)return`No document templates for stack '${t}'.`;let r=e.map(s=>[s.stack,s.template,s.name]);return F([tN,...r]).join(`
216
+ `)}});var Ar=e=>({id:e.id,name:e.name,commitId:e.commitId,createdAt:e.createdAt,...e.description?{description:e.description}:{}}),Pn=e=>{let t=e.compiledMetamodel?.standardVersion??e.compiledExtension?.standardVersion,n=e.builtInElementModelCommitId;return{...Ar(e),...t?{standardVersion:t}:{},...n?{builtInCommitId:n}:{}}},ft=async(e,t)=>Nc((await e.metamodelModels.versions(t)).map(Pn));var Or=async(e,t,n)=>{let r;for(;;){let{items:s}=await e.models.versions(t,{limit:100,cursor:r}),o=s.find(a=>a.name===n);if(o!==void 0)return o.commitId;let i=s.at(-1)?.id;if(s.length<100||i===void 0||i===r)return null;r=i}},Nc=e=>[...e].sort((t,n)=>Date.parse(n.createdAt)-Date.parse(t.createdAt)||n.name.localeCompare(t.name)),ji=(e,t)=>e.find(n=>t===void 0?n.standardVersion===void 0:n.name===t);var Ce="@HEAD",nN=e=>e.kind==="pin"||e.kind==="base-pin",Ow=e=>e.models.flatMap(t=>t.steps),Lc=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:"base"})||e.id.localeCompare(t.id),rN=e=>{let t=e.hiddenDependents.filter(({count:s})=>s>0);if(t.length===0)return;let n=t.reduce((s,{count:o})=>s+o,0),r=t.map(({modelId:s,count:o})=>`${o} of ${e.models[s]?.name??s}`);throw new u(`${P(n,"model")} depending on the cascade's metamodels ${n===1?"is":"are"} hidden from you (${r.join(", ")}), so the cascade cannot plan ${n===1?"its":"their"} pins. Nothing was changed.`,{hint:"Run the cascade as a super-admin, who can read every metamodel-model.",details:{hiddenDependents:t}})},sN=e=>{let t=new Map(Object.keys(e.models).map(n=>[n,new Set]));for(let{modelId:n,targetId:r}of[...e.edges,...e.basePins])n!==r&&e.models[r]!==void 0&&t.get(n)?.add(r);return t},oN=(e,t,n)=>{let r=a=>[...a].map(d=>e.models[d]).sort(Lc)[0].id,s=[],o=new Map,i=r(n);for(;!o.has(i);)o.set(i,s.length),s.push(i),i=r([...t.get(i)??[]].filter(a=>n.has(a)));return[...s.slice(o.get(i)),i].map(a=>e.models[a].name)},iN=e=>{let t=sN(e),n=new Map([...t].map(([o,i])=>[o,new Set(i)])),r=[],s=()=>[...n].filter(([,o])=>o.size===0).map(([o])=>e.models[o]).sort(Lc).map(o=>o.id);for(let o=s();o.length>0;o=s()){let[i]=o;r.push(i),n.delete(i),n.forEach(a=>a.delete(i))}if(n.size>0){let o=oN(e,t,new Set(n.keys()));throw new u(`The metamodels depend on each other in a cycle, so there is no order to release them in: ${o.join(" \u2192 ")} (each depends on the next). Nothing was changed.`,{hint:"Remove one of the dependencies in the app, then run the cascade again.",details:{cycle:o}})}return r},Pc=(e,t,n,r)=>e?t:n!==r?"stale":void 0,Mw=e=>{rN(e);let t=iN(e),n=p=>e.models[p],r=new Set,s=new Map,o=[],i=0,a=(p,g,w)=>{if(w===Ce)return Pc(r.has(g.id),"target-moves",p.commitId,g.headCommitId);if(s.has(g.id)&&s.get(g.id)===w)return r.has(g.id)||p.commitId!==g.headCommitId?"release-moves":void 0;let k=g.releases.find(C=>C.name===w);return k===void 0?"unresolved":p.commitId!==k.commitId?"stale":void 0},d=(p,g)=>{let w=n(p.targetId),k=p.versionRef??Ce,C=a(p,w,k);if(C==="unresolved"){o.push({modelId:g.id,modelName:g.name,dependencyId:p.dependencyId,name:p.name,targetId:w.id,targetName:w.name,versionRef:k});return}let R={dependencyId:p.dependencyId,targetId:w.id,targetName:w.name,...p.newerRelease?{newerRelease:p.newerRelease}:{}};return C===void 0?{kind:"pin",name:p.name,...p.versionRef===void 0?{}:{versionRef:p.versionRef},commitId:p.commitId,...R}:{kind:"refresh-pin",step:++i,modelId:g.id,modelName:g.name,dependencyName:p.name,versionRef:k,legacy:p.versionRef===void 0,fromCommitId:p.commitId,reason:C,...R}},l=(p,g)=>{let w=n(p.targetId),k=Pc(r.has(w.id),"base-moves",p.commitId,w.headCommitId);return k===void 0?{kind:"base-pin",dependencyId:p.dependencyId,name:w.name,targetId:w.id,targetName:w.name,commitId:p.commitId}:{kind:"refresh-base-pin",step:++i,modelId:g.id,modelName:g.name,dependencyId:p.dependencyId,baseId:w.id,baseName:w.name,fromCommitId:p.commitId,reason:k}},c=p=>{let g=r.has(p.id);if(!p.released||!g&&p.outdated===void 0)return;let w=ji(p.releases,p.standardVersion);return s.set(p.id,w?.name??p.standardVersion),{kind:"re-release",step:++i,modelId:p.id,modelName:p.name,...p.standardVersion?{release:p.standardVersion}:{},inPlace:w!==void 0,...w?{releaseId:w.id,releaseName:w.name,fromCommitId:w.commitId,...w.builtInCommitId?{fromBuiltInCommitId:w.builtInCommitId}:{},...w.description?{description:w.description}:{}}:{},reason:g?"pins-move":"outdated",...p.outdated?{outdated:p.outdated}:{},...p.outdated==="SOURCE"||p.outdated==="BOTH"?{unreleasedEdits:!0}:{},...p.instanceModelCount===void 0?{}:{instanceModelCount:p.instanceModelCount}}},m=t.map(p=>{let g=n(p),w=[],k=[],C=$=>{$!==void 0&&(nN($)?k.push($):(w.push($),r.add(p)))};e.edges.filter($=>$.modelId===p&&e.models[$.targetId]!==void 0).sort(($,v)=>Lc({name:$.name,id:$.dependencyId},{name:v.name,id:v.dependencyId})).forEach($=>C(d($,g))),e.basePins.filter($=>$.modelId===p&&e.models[$.targetId]!==void 0).forEach($=>C(l($,g)));let R=c(g);return R!==void 0&&w.push(R),{id:p,name:g.name,role:g.role,...g.baseId?{baseId:g.baseId}:{},released:g.released,steps:w,current:k,...g.outdated?{outdated:g.outdated}:{},...g.instanceModelCount===void 0?{}:{instanceModelCount:g.instanceModelCount}}}),f=e.siblingPins.flatMap(p=>{let g=e.models[p.targetId],w=e.models[p.modelId];if(g===void 0||w===void 0)return[];let k=Pc(r.has(g.id),"target-moves",p.commitId,g.headCommitId);return k===void 0?[]:[{modelId:w.id,modelName:w.name,dependencyId:p.dependencyId,targetId:g.id,targetName:g.name,commitId:p.commitId,reason:k}]}),h=n(e.baseId);return{base:{id:h.id,name:h.name},models:m,stepCount:i,staleSiblingPins:f,unresolvedPins:o,outsideDependents:e.outsideDependents.map(p=>({...p,targetName:e.models[p.targetId]?.name??p.targetId}))}};import{randomUUID as WN}from"node:crypto";var Dc=e=>{let t=new Map;for(let[n,r]of e)for(let s of r){let o=t.get(s.id);o===void 0?t.set(s.id,[n]):o.push(n)}return t};import{randomUUID as dN}from"node:crypto";var _c=(e,t)=>e.id===t.id&&e.relation===t.relation,Fi=e=>Object.values(e??{}).flat(),Nw=e=>Object.keys(e).some(t=>t!=="@@"),aN=(e,t)=>`${e}\0${t}`,Pw=e=>{let t={...e.elements},n=new Map(Object.entries(e.elementIndexEntries).map(([E,S])=>[E,[...S.owners??[]]])),r=new Map;for(let[E,S]of n)for(let x of S)r.set(x.id,(r.get(x.id)??new Set).add(E));let s=new Set,o=E=>{let S=t[E];if(S===void 0||s.has(E))return S;let x={...S,...S.attributes&&{attributes:{...S.attributes}},...S.relations&&{relations:Object.fromEntries(Object.entries(S.relations).map(([A,O])=>[A,Object.fromEntries(Object.entries(O).map(([L,V])=>[L,[...V]]))]))}};return t[E]=x,s.add(E),x},i=(E,S)=>{let x=E.relations?.[S];if(!(x===void 0||E.relations===void 0)){for(let A of Object.keys(x))x[A].length===0&&delete x[A];Object.keys(x).length===0&&delete E.relations[S],Object.keys(E.relations).length===0&&delete E.relations}},a,d=(E,S,x)=>{a!==void 0&&a.set(E,(a.get(E)??new Set).add(aN(S,x)))},l=E=>{if(a===void 0){a=new Map;for(let[S,x]of Object.entries(t))for(let[A,O]of Object.entries(x.relations??{}))Fi(O).forEach(L=>d(L.id,S,A))}return a.get(E)??new Set},c=(E,S)=>{let x=n.get(E)??[];x.some(A=>_c(A,S))||(n.set(E,[...x,S]),r.set(S.id,(r.get(S.id)??new Set).add(E)))},m=(E,S)=>{let x=(n.get(E)??[]).filter(A=>!_c(A,S));n.set(E,x),x.some(A=>A.id===S.id)||r.get(S.id)?.delete(E)},f=(E,S,x)=>{let A=o(E);if(A===void 0)return;Fi(A.relations?.[S]).filter(L=>L.owned).forEach(L=>m(L.id,{id:E,relation:S}));let O=Fi(x);O.filter(L=>L.owned).forEach(L=>c(L.id,{id:E,relation:S})),O.forEach(L=>d(L.id,E,S)),A.relations??={},A.relations[S]=Object.fromEntries(Object.entries(x).map(([L,V])=>[L,[...V]])),i(A,S)},h=(E,S,x)=>{let A=o(E),O=A?.relations?.[S];if(A===void 0||O===void 0)return;let L=Object.keys(O).find(V=>O[V].some(ne=>ne.id===x));if(L!==void 0)return O[L].splice(O[L].findIndex(V=>V.id===x),1),i(A,S),L},p=(E,S,x,A)=>{let O=o(E.id);if(O===void 0)return;O.relations??={};let L=O.relations[E.relation]??{},V=Nw(L)?x:"@@";if(V===void 0||V==="@@"&&Nw(L))return;O.relations[E.relation]=L;let ne=L[V]??=[];ne.splice(A??ne.length,0,S),d(S.id,E.id,E.relation)},g=(E,S)=>{let x=E.id;t[x]={id:x,type:E.type,...E.attributes&&{attributes:E.attributes},...E.relations&&{relations:E.relations}},s.delete(x);for(let[A,O]of Object.entries(E.relations??{}))Fi(O).forEach(L=>d(L.id,x,A));c(x,S),p(S,{id:x,owned:!0},void 0);for(let[A,O]of Object.entries(E.ownedElements??{}))O.forEach(L=>g(L,{id:x,relation:A}))},w=(E,S)=>{let x=o(E);if(x!==void 0){for(let[A,O]of Object.entries(S.attributes??{}))x.attributes??={},O.length===0?delete x.attributes[A]:x.attributes[A]=O;for(let[A,O]of Object.entries(S.relations??{}))f(E,A,O)}},k=({elements:E,targetParent:S,position:x})=>{for(let{id:A,parent:O}of E){let L=_c(O,S),V=(t[O.id]?.relations?.[O.relation]?.["@@"]??[]).findIndex(H=>H.id===A),ne=h(O.id,O.relation,A);m(A,O),c(A,S);let K=L&&x!==void 0&&V!==-1&&x>V?x-1:x;p(S,{id:A,owned:!0},ne,K)}},C=E=>{let S=new Set(E),x=[...S];for(let A=x.pop();A!==void 0;A=x.pop())for(let O of r.get(A)??[])!S.has(O)&&(n.get(O)??[]).every(L=>S.has(L.id))&&(S.add(O),x.push(O));return S},R=(E,S)=>{for(let x of l(E)){let[A,O]=x.split("\0"),L=S.has(A)?void 0:o(A),V=L?.relations?.[O];if(L!==void 0&&V!==void 0){for(let ne of Object.keys(V))V[ne]=V[ne].filter(K=>K.modelId!==void 0||K.id!==E);i(L,O)}}},$=E=>{let S=C([E]);for(let x of S){for(let A of r.get(x)??[])(n.get(A)??[]).filter(O=>O.id===x).forEach(O=>m(A,O));R(x,S),a?.delete(x),delete t[x],s.delete(x),n.delete(x),r.delete(x)}},v=({relation:E,targetElementId:S,addSourceElementIds:x=[],removeSourceElementIds:A=[]})=>{for(let O of x)p({id:O,relation:E},{id:S,owned:!1},void 0);for(let O of A)h(O,E,S)};return{element:E=>t[E],owners:E=>n.get(E)??[],cascade:C,apply:E=>{switch(E.type){case"ELEMENT_CREATE":E.creation.owner&&g(E.creation,E.creation.owner);return;case"ELEMENT_UPDATE":w(E.elementId,E.update);return;case"ELEMENT_MOVE":k(E.move);return;case"ELEMENT_DELETE":$(E.elementId);return;case"RELATION_MEMBERSHIP_UPDATE":v(E.update);return;default:return}},snapshot:()=>(s.clear(),{elements:{...t},elementIndexEntries:{...e.elementIndexEntries,...Object.fromEntries([...n].map(([E,S])=>[E,{...e.elementIndexEntries[E],owners:[...S]}]))}})}};var Ue=["external","extensionLayer","lineage"],qi=class extends u{errors;constructor(t){let n=t.length>1?` (and ${t.length-1} more)`:"";super(`${t[0].message}${n}`,{exitCode:b.Validation,details:{errors:t}}),this.name="EditRefusedError",this.errors=t}},Wi=class extends Error{constructor(n,r,s={}){super(r);this.code=n;this.at=s}code;at},fe=(e,t,n)=>{throw new Wi(e,t,n)},At=(e,t=!0)=>({action:e,resendable:t}),Mr=e=>Object.keys(e).length===0,lN=new Set(Ue),Os=(e,t)=>{for(let n of e)lN.has(n)&&fe("read-only-field",`'${n}' is read-only: the server serves it on an element, but no staged write accepts it.`,{elementId:t,property:n})},Dw=e=>fe("element-not-found",`Element '${e}' is not in the model.`,{elementId:e}),jc=({starting:e,working:t},n)=>t.element(n)??(e.elements[n]===void 0?Dw(n):fe("element-not-found",`Element '${n}' is removed by an earlier delete of this change.`,{elementId:n})),_w=(e,t)=>e.get(t)??fe("unknown-key",`No new element of this change has the key '${t}'.`),Fc=(e,t,n)=>{if(!("key"in e))return e.id;let r=_w(n.keys,e.key);return r.editIndex>=t&&fe("key-before-definition",`The key '${e.key}' is used before the create that makes it; create it first.`),r.id},qc=e=>({id:e.id,owned:e.owned,...e.modelId!==void 0&&{modelId:e.modelId}}),cN=(e,t)=>"key"in e?{id:_w(t.keys,e.key).id,owned:e.owned}:qc(e),jw=(e,t)=>Object.fromEntries(Object.entries(e).map(([n,r])=>[n,r.map(s=>cN(s,t))])),Fw=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.map(qc)])),qw=e=>Object.values(e).every(t=>t.length===0),Ww=(e,t)=>{for(let[n,r]of Object.entries(e)){let s=r.find(o=>o.id===t);if(s)return{group:n,ref:s}}},mN=(e,t)=>e.id===t.id&&e.owned===t.owned&&e.modelId===t.modelId,fN=(e,t)=>[t.owned?"owned":"unowned",...t.modelId!==void 0?[`in model '${t.modelId}'`]:[],...e!=="@@"?[`in group '${e}'`]:[]].join(", "),pN=(e,t,n)=>{let r=new Map,s=new Map;return e.forEach((o,i)=>{if(o.kind!=="create")return;let a=d=>{let l=t();r.set(d,l),d.key!==void 0&&(s.has(d.key)&&fe("duplicate-key",`The key '${d.key}' names two new elements; give each its own.`),s.set(d.key,{id:l,editIndex:i})),Object.values(d.children??{}).flat().forEach(a)};n(i,()=>a(o.element))}),{idOf:r,keys:s}},Bw=(e,t)=>{let n=t.idOf.get(e);if(n===void 0)throw new Error("Every new element of an edit that was not refused has a minted id.");let r=e.attributes??{},s=e.relations??{},o=Object.entries(e.children??{}).filter(([,i])=>i.length>0);Os([...Object.keys(e),...Object.keys(r),...Object.keys(s),...o.map(([i])=>i)],n);for(let[i,a]of Object.entries(r))a.length===0&&fe("empty-value",`The attribute '${i}' of a new element has no value; leave it out.`,{elementId:n,property:i});for(let[i,a]of Object.entries(s))qw(a)&&fe("empty-value",`The relation '${i}' of a new element has no target; leave it out.`,{elementId:n,property:i}),Object.values(a).some(d=>d.some(l=>l.owned))&&fe("owned-on-create",`A new element cannot own through a reference in '${i}': nest what it owns under its children.`,{elementId:n,property:i});return{id:n,type:e.type,...!Mr(r)&&{attributes:{...r}},...!Mr(s)&&{relations:Object.fromEntries(Object.entries(s).map(([i,a])=>[i,jw(a,t)]))},...o.length>0&&{ownedElements:Object.fromEntries(o.map(([i,a])=>[i,a.map(d=>Bw(d,t))]))}}},uN=(e,t,n)=>At({type:"ELEMENT_CREATE",creation:{...Bw(e.element,n),owner:{id:Fc(e.parent,t,n),relation:e.relation}}}),hN=(e,t)=>{let n=e.attributes??{},r=e.relations??{},s=o=>({elementId:e.element,property:o});Os([...Object.keys(e),...Object.keys(n),...Object.keys(r)],e.element),Mr(n)&&Mr(r)&&fe("empty-edit",`The set names no attribute or relation of '${e.element}'.`,{elementId:e.element});for(let[o,i]of Object.entries(n))i.length===0&&fe("empty-value",`The attribute '${o}' is set to no value; unset it instead.`,s(o));for(let[o,i]of Object.entries(r))qw(i)&&fe("empty-value",`The relation '${o}' is set to no target; unset it instead.`,s(o));return At({type:"ELEMENT_UPDATE",elementId:e.element,update:{...!Mr(n)&&{attributes:{...n}},...!Mr(r)&&{relations:Object.fromEntries(Object.entries(r).map(([o,i])=>[o,jw(i,t)]))}}})},gN=e=>{let t=e.attributes??[],n=e.relations??[];return t.length===0&&n.length===0&&fe("empty-edit",`The unset names no attribute or relation of '${e.element}'.`,{elementId:e.element}),Os([...t,...n],e.element),At({type:"ELEMENT_UPDATE",elementId:e.element,update:{...t.length>0&&{attributes:Object.fromEntries(t.map(r=>[r,[]]))},...n.length>0&&{relations:Object.fromEntries(n.map(r=>[r,{}]))}}})},yN=e=>{let t=e.filter(n=>n.kind==="delete");return{named:new Set(t.map(n=>n.element)),recursive:new Set(t.filter(n=>n.recursive).map(n=>n.element))}},wN=(e,t)=>{let{working:n,deletes:r}=t;if(n.element(e.element)===void 0)return t.starting.elements[e.element]===void 0?Dw(e.element):void 0;let s=n.owners(e.element),o=n.cascade(r.named);if(s.length>0&&s.every(d=>o.has(d.id)))return;let i=n.cascade(r.recursive),a=[...n.cascade([e.element])].filter(d=>!r.named.has(d)&&!i.has(d));return a.length>0&&fe("owns-elements",`Element '${e.element}' owns ${P(a.length,"element")} that deleting it removes as well; delete it recursively to remove them with it.`,{elementId:e.element}),At({type:"ELEMENT_DELETE",elementId:e.element})},Lw=e=>`'${e.id}' through '${e.relation}'`,bN=(e,t)=>{let n={elementId:e.element},{from:r}=e;return r?t.find(s=>s.id===r.id&&s.relation===r.relation)??fe("not-an-owner",`Element '${e.element}' is not owned by ${Lw(r)}.`,n):(t.length===0&&fe("no-owner",`Element '${e.element}' has no owner to move it out of.`,n),t.length>1&&fe("ambiguous-owner",`Element '${e.element}' has ${t.length} owners (${t.map(Lw).join("; ")}); name the one it leaves.`,n),t[0])},kN=(e,t,n)=>{jc(n,e.element),e.position!==void 0&&!(Number.isInteger(e.position)&&e.position>=0)&&fe("invalid-position",`The position ${e.position} is not a whole number from 0 up.`,{elementId:e.element});let r=bN(e,n.working.owners(e.element));return At({type:"ELEMENT_MOVE",move:{elements:[{id:e.element,parent:{id:r.id,relation:r.relation}}],targetParent:{id:Fc(e.parent,t,n),relation:e.relation},...e.position!==void 0&&{position:e.position}}})},EN=(e,t,n)=>{let r=jc(n,e.element),s={elementId:e.element,property:e.relation};Os([e.relation],e.element);let o="key"in e.target?{id:Fc({key:e.target.key},t,n),owned:e.target.owned}:qc(e.target),i=r.relations?.[e.relation]??{},a=Object.keys(i),d=a.some(f=>f!=="@@"),l=e.group??(d?fe("group-required",`The relation '${e.relation}' of '${e.element}' is grouped (${a.join(", ")}); name the group the target belongs in.`,s):"@@");a.length>0&&d!==(l!=="@@")&&fe("group-mismatch",d?`The relation '${e.relation}' of '${e.element}' is grouped (${a.join(", ")}); name the group the target belongs in rather than '${"@@"}'.`:`The relation '${e.relation}' of '${e.element}' is ungrouped; leave the group out.`,s);let c=Ww(i,o.id);if(c&&!(c.group===l&&mN(c.ref,o))&&fe("already-related",`'${e.element}' already relates to '${o.id}' through '${e.relation}' (${fN(c.group,c.ref)}); unrelate it first.`,s),!o.owned&&o.modelId===void 0&&l==="@@")return At({type:"RELATION_MEMBERSHIP_UPDATE",update:{relation:e.relation,targetElementId:o.id,addSourceElementIds:[e.element]}});let m=Fw(i);return c||(m[l]=[...m[l]??[],o]),At({type:"ELEMENT_UPDATE",elementId:e.element,update:{relations:{[e.relation]:m}}},!1)},CN=(e,t)=>{let n=jc(t,e.element);Os([e.relation],e.element);let r=n.relations?.[e.relation]??{};if((Ww(r,e.target)??fe("not-related",`'${e.element}' does not relate to '${e.target}' through '${e.relation}'.`,{elementId:e.element,property:e.relation})).ref.modelId===void 0)return At({type:"RELATION_MEMBERSHIP_UPDATE",update:{relation:e.relation,targetElementId:e.target,removeSourceElementIds:[e.element]}});let o=Object.fromEntries(Object.entries(Fw(r)).map(([i,a])=>[i,a.filter(d=>d.id!==e.target)]).filter(([,i])=>i.length>0));return At({type:"ELEMENT_UPDATE",elementId:e.element,update:{relations:{[e.relation]:o}}},!1)},vN=(e,t,n)=>{switch(e.kind){case"create":return uN(e,t,n);case"set":return hN(e,n);case"unset":return gN(e);case"delete":return wN(e,n);case"move":return kN(e,t,n);case"relate":return EN(e,t,n);case"unrelate":return CN(e,n)}},Ms=(e,t,{mintId:n=dN}={})=>{let r=[],s=(d,l)=>{try{return l()}catch(c){if(!(c instanceof Wi))throw c;let{elementId:m,property:f}=c.at;r.push({editIndex:d,code:c.code,message:c.message,...m!==void 0&&{elementId:m},...f!==void 0&&{property:f}});return}},o=d=>r.some(l=>l.editIndex===d),i={starting:t,working:Pw(t),...pN(e,n,s),deletes:yN(e)},a=[];if(e.forEach((d,l)=>{let c=o(l)?void 0:s(l,()=>vN(d,l,i));c!==void 0&&(a.push(c),i.working.apply(c.action))}),r.length>0)throw new qi(r.toSorted((d,l)=>d.editIndex-l.editIndex));return{actions:a.map(({action:d})=>d),ids:Object.fromEntries([...i.keys].map(([d,{id:l}])=>[d,l])),resendable:a.every(({resendable:d})=>d)}};var RN=e=>e instanceof u&&e.type==="draft-head-conflict"&&e.details.ancestor===!0,SN=(e,t)=>e.length===t.length&&e.every(n=>t.includes(n)),IN=e=>{switch(e.type){case"ELEMENT_UPDATE":case"ELEMENT_DELETE":return{all:[e.elementId]};case"ELEMENT_MOVE":return{all:e.move.elements.map(t=>t.id)};case"RELATION_MEMBERSHIP_UPDATE":return{among:[...e.update.addSourceElementIds??[],...e.update.removeSourceElementIds??[]]};case"ELEMENT_BULK_UPDATE":return{among:[...e.update.elementIds??[],...(e.update.updates??[]).map(t=>t.elementId)]};default:return{}}},Hw=e=>[...new Set(e.actions.map(t=>t.type))].sort(),$N=(e,t)=>{let n=Hw(t);if(!SN(e.actionTypes,n))return`it recorded ${e.actionTypes.join(", ")||"no action"}, and this one stages ${n.join(", ")}`;let{elementIds:r}=e;return r===void 0?void 0:t.actions.some(o=>{let i=r[o.type]??[],{all:a,among:d}=IN(o);return a?.some(l=>!i.includes(l))||d!==void 0&&i.some(l=>!d.includes(l))})?"it changed other elements than this one names":void 0},Uw=(e,t,n,r)=>{let s=(r.sameChange??$N)(e,t);if(s!==void 0)throw new u(`Request id ${t.changeRequestId} was already used for a different change of your draft of ${n} (${e.id}): ${s}. Nothing was staged.`,{hint:"Leave --request-id out to stage this change under an id of its own.",hosted:{hint:"Call again: the call stages the change under an id of its own."},details:{changeRequestId:t.changeRequestId,stagedCommitId:e.id,recordedActionTypes:e.actionTypes,actionTypes:Hw(t)}})},Vw="Run 'modeldesk draft status', then stage the change again.",Gw={hint:e=>`Call ${e("draft status")}, then stage the change again.`},xN=(e,t,n,r)=>new u(e.details.ancestor===!0?`Your draft of ${t} moved again while ${n} was being sent a second time, so it was not staged.`:`Your draft of ${t} was undone, rebased or committed while ${n} was being staged, so it was not staged.`,{...r,exitCode:b.Conflict,hint:Vw,hosted:Gw}),TN=(e,t,n,r)=>{let s=e.details.targetRefName??e.details.targetRefId,o=typeof s=="string"?` (${s})`:"";return new u(`Your draft of ${t} aims at another branch${o} since it was read, so ${n} was not staged.`,{...r,exitCode:b.Conflict,hint:Vw,hosted:Gw})},AN=e=>{let t=e.length;for(;t>0&&(e[t-1]==="."||e[t-1].trim()==="");)t--;return e.slice(0,t)},ON=(e,t,n,r,s)=>{let o=Array.isArray(e.details.errors)?e.details.errors:[];if(o.some(l=>l.code==="chain-too-long"))return new u(`Your draft of ${t} holds the most changes a draft can (${je}), so ${n} was not staged.`,{...r,exitCode:b.Validation,hint:"Commit the draft first ('modeldesk draft commit', or in the app); splitting the change does not help.",hosted:{hint:l=>`Commit the draft first (${l("draft commit")}, or the person in the app); splitting the change does not help.`}});let[i]=o,a=s.chunks>1?`Change ${s.chunk} of ${s.chunks}`:"The change",d=o.length>1?` (and ${o.length-1} more)`:"";return new u(i?`${a} was refused: ${AN(i.message)}${d}.`:e.reason,{...r,exitCode:b.Validation})},MN=(e,t,n,r)=>({reason:r==="absent"?`${e.reason} Your draft holds no change under ${n} yet, but the server may still be staging ${t}.`:`${e.reason} Whether ${t} was staged is unknown: your draft could not be read to look for it.`,hint:s=>`Call ${s("draft diff")} with changes: true and look for request id ${n} before you call again: a change staged under it is in your draft.`,exitCode:b.Failure}),Bc=(e,t,n,r,s,o="unknown")=>{if(!(e instanceof u))return e;let i=r.chunks>1?`change ${r.chunk} of ${r.chunks}`:"this change",a={type:e.type,requestId:e.requestId,details:{...e.details,...r}};return e.exitCode===b.Transient?new u(`${e.reason} Whether ${i} was staged is unknown.`,{...a,exitCode:b.Transient,details:{...a.details,changeRequestId:n.changeRequestId},hint:s,hosted:MN(e,i,n.changeRequestId,o)}):e.type==="draft-head-conflict"?xN(e,t,i,a):e.type===Dl?TN(e,t,i,a):e.type==="change-validation-failed"?ON(e,t,i,a,r):new u(e.reason,{...a,exitCode:e.exitCode,hint:e.hint,hosted:e.hosted})},Bi=async(e,t,n)=>{let r={context:e,api:e.api(),address:t.address,plan:n,name:y(t.model.name),current:t,chunks:[...n.chunks],head:t.head,draftId:t.draft?.id,replanned:!1,chain:t.draft===void 0?void 0:n.knownChain,staged:[]};for(let s=0;s<r.chunks.length;){let o=r.chunks[s];if(o.actions.length===0){s++;continue}let i=n.stableIds?await LN(r,o):void 0;if(i!==void 0){await Wc(r,i,s),s++;continue}let a=await DN(r,s);if("resumeAt"in a){s=a.resumeAt;continue}r.head=a.sent.commitId,r.draftId=a.sent.draftId,r.chain=void 0;let{envelope:d,draftId:l}=a.sent;d!==void 0&&l!==void 0&&e.content.advance(r.current.model.id,l,d),await Wc(r,a.sent,s),s++}return{target:r.current,chunks:r.staged,head:r.head,draftId:r.draftId}},NN=e=>e.staged.map(t=>({number:e.chunks.indexOf(t.chunk)+1,changeRequestId:t.chunk.changeRequestId,commitId:t.commitId})),Hc=(e,t)=>({chunk:t+1,chunks:e.chunks.length,landed:NN(e),baseCommitId:e.head}),PN=(e,t)=>t===void 0?Promise.resolve([]):(e.chain??=He(e.api,e.current.model.id,t),e.chain),Wc=async(e,t,n)=>{e.staged.push(t),await e.plan.persisted?.(t,n)},LN=async(e,t)=>{let n=(await PN(e,e.draftId)).find(r=>r.requestId===t.changeRequestId);if(n!==void 0)return Uw(n,t,e.name,e.plan),{chunk:t,commitId:n.id,draftId:e.draftId,alreadyStaged:!0,staged:!0}},DN=async(e,t)=>{let n=e.chunks[t];try{let r=await e.api.drafts.model.stage(e.current.model.id,{actions:[...n.actions],draftHeadId:e.head,changeRequestId:n.changeRequestId,message:n.message,...e.draftId===void 0?{branchId:e.current.branch.id}:{},...e.plan.dryRun?{dryRun:!0}:{}});return{sent:{chunk:n,commitId:r.envelope.commitId,draftId:r.draftId??e.draftId,envelope:r.envelope,alreadyStaged:!1,staged:r.envelope.commitId!==e.head}}}catch(r){if(!(r instanceof u))throw r;if(e.plan.dryRun)throw r.exitCode===b.Transient?r:Bc(r,e.name,n,Hc(e,t),e.plan.retryHint);return r.exitCode===b.Transient?{sent:await _N(e,r,t)}:{resumeAt:await jN(e,r,t)}}},_N=async(e,t,n)=>{let r=e.chunks[n],s=await FN(e.context,e.current.model.id,r.changeRequestId);if(typeof s=="string")throw Bc(t,e.name,r,Hc(e,n),e.plan.retryHint,s);return{chunk:r,commitId:s.commitId,draftId:s.draftId,alreadyStaged:!1,staged:!0}},jN=async(e,t,n)=>{let r=e.chunks[n];if(e.replanned||!RN(t)||e.plan.replan===void 0)throw Bc(t,e.name,r,Hc(e,n),e.plan.retryHint);let s=Array.isArray(t.details.commits)?t.details.commits:[];e.current=await lt(e.context,e.address),e.head=e.current.head,e.draftId=e.current.draft?.id,e.chain=void 0,e.replanned=!0;let o=n,i=s.find(a=>a.requestId===r.changeRequestId);return i!==void 0&&(Uw(i,r,e.name,e.plan),await Wc(e,{chunk:r,commitId:i.id,draftId:e.draftId,alreadyStaged:!0,staged:!0},n),o++),e.chunks=[...e.chunks.slice(0,o),...await e.plan.replan(e.current,e.chunks.slice(o))],o},FN=async(e,t,n)=>{let r=e.api();try{let s=await dt(()=>r.models.draft(t));if(s===void 0)return"absent";let i=(await He(r,t,s.id,qN)).find(a=>a.requestId===n);return i?{commitId:i.id,draftId:s.id}:"absent"}catch{return"unknown"}},qN=10,Ln=e=>e.chunks.some(t=>t.staged);var Le="The change is staged in your draft of the model, opened on the addressed branch by the first change, where the person you work for sees it in the app and commits it; -m says why, in your words. A lost race with another session is resent once; a refusal exits 4 with every reason in details.errors.",Uc={"with-staged":{type:"boolean",description:"With --commit: also land the changes the draft held before this run, which the commit message then covers; required when there are any."}},BN={"request-id":{type:"string",placeholder:"id",description:"The idempotency key to stage under, to retry a change whose outcome is unknown: a change already staged under it is not staged again. A cli-\u2026 id this session minted is sent as given, any other id seeds a cli-\u2026 id derived from it, the same one on every run. Minted (cli-\u2026) when left out."}},HN={commit:{type:"boolean",description:"Land the draft right after staging, with the same message. Under an agent host this is left to a person (exit 6) unless MODELDESK_ALLOW_COMMIT=1 or the draft aims at a branch named agent/<topic>."}},ve={...wi,...BN,...HN,...Uc},UN=(e,t,n)=>{if(e!==void 0)return"id"in e?e.id:t===void 0?n[e.key]:void 0},Vc=()=>{let e=[],t=0;return{mint:()=>(t===e.length&&e.push(WN()),e[t++]),rewind:()=>{t=0}}},Gc=(e,t)=>{if(!/^[\x21-\x7e]+$/.test(e)||e.length>Qd)throw I(`--request-id takes 1 to ${Qd} printable characters without spaces, such as the changeRequestId a failed run reported.`,t);return e},VN=e=>`Retry with --request-id ${e}: a change already staged under it is found and not staged again.`,Ns=async(e,t,n,r)=>{let s=r.requestId===void 0?Zn(e.origin):En(e.origin,r.requestId),o=await n(t),i=d=>({actions:d.actions,message:r.message,changeRequestId:s});return{staged:await Bi(e,t,{chunks:[i(o)],stableIds:r.requestId!==void 0,replan:async(d,l)=>(e.flags.commit&&await Yw(e,d,s),l.length===0?[]:(o=await n(d),[i(o)])),retryHint:VN(s),...r.dryRun?{dryRun:!0}:{},...r.sameChange?{sameChange:r.sameChange}:{},...r.knownChain?{knownChain:r.knownChain}:{}}),translation:o,changeRequestId:s}},Kw=e=>e.staged.chunks[0],Ps=e=>{let t=e.staged.target.draft,n=Kw(e);if(n===void 0)return t?{id:t.id,headCommitId:t.headCommitId,changeCount:t.changeCount}:null;let r=Ln(e.staged),s=e.staged.draftId;return s===void 0&&!r?null:{...s?{id:s}:{},headCommitId:e.staged.head,changeCount:(t?.changeCount??0)+(r&&!n.alreadyStaged?1:0)}},Ls=e=>{let{target:t,draftId:n}=e.staged;return n===void 0?re({ref:{kind:"branch",branch:t.branch},draft:void 0}):{kind:"draft",id:n,branch:{id:t.branch.id,name:t.branch.name}}},Ds=async(e,t)=>{let{target:n,head:r}=t.staged,s=await bs(e,n.model.id),o=y(n.model.name),i=t.staged.draftId;if(i===void 0)throw new u(`The change left ${o} as it was, so there is nothing to commit.`,{type:"nothing-to-commit"});let{landing:a,recovered:d}=await kr(e,s,{id:i,targetRefId:n.branch.id,baselineCommitId:n.draft?.baselineCommitId??n.head},{message:e.flags.message,expectedDraftHeadId:r}),l=Cr(a,n.model,rr(e));return{...Er(a),recovered:d,...l===void 0?{}:{next:l},url:e.webUrl({kind:"commit",modelId:n.model.id,commitId:a.commit.id})}},Kc=(e,t)=>{if(e>0&&!t)throw new u(`Your draft already holds ${P(e,"staged change")}, and a commit lands every one of them under its message.`,{hint:"Review them with 'modeldesk draft diff --changes', then pass --with-staged to commit them too.",details:{changeCount:e}})},Yc=e=>`land it from a plain shell with 'modeldesk draft commit ${e} --any-surface'.`,Yw=async(e,t,n)=>{tr(e,`${e.commandName} --commit`,{kind:"model",id:t.model.id,name:t.model.name},t.branch);let r=n!==void 0&&t.draft!==void 0?(await He(e.api(),t.model.id,t.draft.id)).filter(s=>s.requestId!==n).length:t.draft?.changeCount??0;if(Kc(r,e.flags["with-staged"]),t.draft!==void 0){let s=y(t.model.name);await qe(e,ui(e,t.model.id),t.draft,{scope:{kind:"all"},action:`Committing your draft of ${s}`,anySurface:!1,override:Yc(t.model.id)})}},Hi=e=>{let{commit:t}=e.flags,n=`modeldesk ${e.commandName} --help`;St(e.flags.message,n);let r=e.flags["request-id"];if(r!==void 0&&Gc(r,n),e.flags["with-staged"]&&!t)throw I("--with-staged goes with --commit.",n)},_s=async e=>{let{commit:t}=e.flags;Hi(e);let n=e.flags["request-id"],r=await lt(e,e.args.model);if(t){let s=n===void 0?void 0:En(e.origin,n);await Yw(e,r,s)}return r},Ve=(e,t)=>X(async()=>{let n=await _s(e),r=Vc(),s,o=await Ns(e,n,async w=>{let k=await t(w);return s=k.subject,r.rewind(),Ms(k.edits,w.read,{mintId:r.mint})},{message:e.flags.message,requestId:e.flags["request-id"]}),{translation:i}=o,a=Kw(o),d=a?.alreadyStaged?a.commitId:void 0,l=a?.envelope,c=Ln(o.staged),m=n.model.id,f=UN(s,d,i.ids),h=l?.removedElementIds??[],p=f===void 0||h.includes(f)?void 0:l?.revisions[f]?.element??o.staged.target.read.elements[f],g={model:n.model,ref:Ls(o),draft:Ps(o),message:e.flags.message,changeRequestId:o.changeRequestId,staged:c,...d?{alreadyStaged:!0,stagedCommitId:d}:{},...p?{element:p}:{},...h.length>0?{removedElementIds:h}:{},url:p?e.webUrl({kind:"element",modelId:m,elementId:p.id}):e.webUrl({kind:"model",modelId:m})};if(e.flags.commit){if(!c)throw new u(`The change left ${y(n.model.name)} as it was, so there is nothing to commit.`,{type:"nothing-to-commit"});g.commit=await Ds(e,o)}return{result:g}}),GN=e=>y(typeof e=="string"?e:JSON.stringify(e)),KN=e=>e.kind==="draft"?e.branch.name:e.kind==="branch"?e.name:"",YN=e=>{let t=y(e.model.name);if(e.alreadyStaged)return`Already staged in your draft of ${t} under ${e.changeRequestId} (${e.stagedCommitId}); not staged again.`;let n=KN(e.ref);return e.staged?`Staged in your draft of ${t} on ${y(n)} (${P(e.draft?.changeCount??0,"change")}, at most ${je}): ${y(e.message)}`:`Nothing was staged: the change leaves ${t} as it is.`},Dn=e=>[`Committed as ${e.commit.id} on ${e.branch.name===void 0?e.branch.id:y(e.branch.name)}${e.recovered?" (found on the branch by its request id)":""}.`,...e.next?[e.next]:[],`commit: ${e.url}`],zN=(e,t)=>[e.id,...e.owned?["(owned)"]:[],...t==="@@"?[]:[`[${t}]`]].join(" "),Ge=e=>{let{element:t}=e;return[YN(e),...t?[`${t.id} (${t.type})`,...Object.entries(t.attributes??{}).map(([n,r])=>` ${n}: ${r.map(GN).join(", ")}`),...Object.entries(t.relations??{}).map(([n,r])=>` ${n}: ${Object.entries(r).flatMap(([s,o])=>o.map(i=>zN(i,s))).join(", ")}`)]:[],...e.removedElementIds?[`Removed ${P(e.removedElementIds.length,"element")}.`]:[],`url: ${e.url}`,...e.commit?Dn(e.commit):[]].join(`
217
+ `)};var te=(e,t)=>{if(t.kind==="import")return`${e.appBase}/imports/${encodeURIComponent(t.importId)}`;let n=`${e.appBase}/models/${encodeURIComponent(t.modelId)}`;switch(t.kind){case"model":return n;case"element":return`${n}/editor?elementId=${encodeURIComponent(t.elementId)}`;case"commit":return`${n}/history/${encodeURIComponent(t.commitId)}`}};var J=e=>e?e.slice(0,8):"none",Ui=(e,t)=>new u(e.reason,{exitCode:e.exitCode,hint:t,type:e.type,requestId:e.requestId,details:e.details});var zc="daaddd57-d61e-41e2-8751-19497881b8b2",JN="@element",XN=[["@metamodel","metamodel"],["@metamodelExtensions","extension"]],Nr=(e,t)=>{let n=e?.attributes?.[t]?.[0];return typeof n=="string"&&n!==""?n:void 0},zw=(e,t)=>Object.values(e?.relations?.[t]??{}).flatMap(n=>n.map(r=>r.id)),Jw=e=>e.rootElementId===void 0?void 0:e.elements[e.rootElementId],Vi=e=>{let t=Jw(e);return XN.flatMap(([n,r])=>zw(t,n).flatMap(s=>{let o=e.elements[s],i=Nr(o,"@modelId");if(i===void 0)return[];let a=Nr(o,"@commitId"),d=Nr(o,"@version");return[{role:r,modelId:i,...a?{commitId:a}:{},...d?{version:d}:{}}]}))},Gi=e=>{let[t]=zw(Jw(e),JN);return t===void 0?void 0:Nr(e.elements[t],"standardVersion")},Xw=e=>Object.values(e.elements).flatMap(t=>{if(t.type!=="@ManagedDependency")return[];let n=Nr(t,"@sourceMetamodelId"),r=Nr(t,"@commitId");return n&&r?[{sourceMetamodelId:n,commitId:r}]:[]});var Qw="super-admin-required",QN=e=>{let t;return()=>t??=e()},Zw=new WeakMap,tt=(e,t)=>{let n=Zw.get(e)??new Map;Zw.set(e,n);let r=n.get(t);if(r!==void 0)return r;let s=ce(e,t),o=QN(async()=>{try{return{overview:await e.api().models.overview(await s.id())}}catch(d){if(d instanceof U&&d.status===403)return{refusal:d};throw d}}),i=async()=>{let d=await o();if("refusal"in d)throw d.refusal;return d.overview},a={model:s,overview:i,overviewIfReadable:async()=>{let d=await o();return"overview"in d?d.overview:void 0},isMetamodelModel:async()=>(await i()).metamodel?.modelId===zc};return n.set(t,a),a},ZN="Ask a super-admin to look at it in the app.",eP=(e,t,n)=>n.machine?new u(`'${e.commandName}' on the metamodel-model '${t}' needs an interactive super-admin login: no /metamodel-models route is open to a service account, so CI cannot release, re-pin or plan metamodels. Nothing was changed.`,{exitCode:b.NeedsHuman,type:Qw,hint:"Run it from a terminal logged in as a super-admin ('modeldesk auth login')."}):new u(`'${e.commandName}' on the metamodel-model '${t}' needs a super-admin: only a super-admin may call the /metamodel-models routes that release and pin metamodels. Nothing was changed.`,{exitCode:b.NeedsHuman,type:Qw,hint:"Ask a super-admin to run it, or log in as one with 'modeldesk auth login'.",hosted:{hint:ZN}}),pt=async(e,t,n)=>{if(Kt(await e.api().accessTokenClaims()))return;let r=tt(e,t);if((n.readsOnly?await r.overviewIfReadable():await r.overview())?.metamodel?.modelId===zc)throw eP(e,t,n)};var js=(e,t)=>e.filter(n=>n.id.toLowerCase()===t||"modelId"in n&&n.modelId?.toLowerCase()===t),Jc=(e,t,n)=>{let r=`'${y(e.name)}'`,s=o=>o===void 0?{}:{hint:o};if(e.type==="MANAGED")throw new u(`${r} is a managed dependency of ${t}: built-in elements its metamodel supplies, ${n.managed.reason}`,s(n.managed.hint));if(e.type==="EXTERNAL")throw new u(`${r} is an external document, ${n.external.reason}`,s(n.external.hint));if(e.transitive){let o=(e.providedVia??[]).map(a=>`'${y(a.name)}'`),i=o.length?`, brought in by ${o.join(", ")}`:"";throw new u(`${r} is a transitive dependency of ${t}${i}: ${n.transitive.reason}`,{hint:n.transitive.hint})}return e},tP={managed:{reason:"pinned through the metamodel version, which pin set does not change.",hint:"Change the model's metamodel version in the app's model settings."},external:{reason:"not a model, so it has no version to pin."},transitive:{reason:"it follows the dependency that provides it.",hint:"Pin the direct dependency that provides it instead."}},Xc=(e,t,n)=>{let r=js(e,t);if(r.length===0)throw new u(`${n.name} has no dependency with the id '${t}'.`,{exitCode:b.NotFound,hint:`Run 'modeldesk pin list ${n.address}' to see its dependencies.`});if(r.length>1)throw new u(`${r.length} dependencies of ${n.name} match '${t}'; address the one you mean by id.`,{exitCode:b.Usage,details:{candidates:r.map(s=>({id:s.id,name:s.name,type:s.type,..."modelId"in s?{modelId:s.modelId}:{}}))}});return r[0]},nP=(e,t,n)=>Jc(Xc(e,t,n),n.name,tP),Qc=({ref:e})=>e.kind==="release"?e.name:Ce,eb=q({path:["pin","set"],effect:"land-direct",summary:"Pin a dependency to a release or to the head",description:"Re-pins one of the model's direct dependencies on another model. <dependency>@<release> pins that release's commit; <dependency>@main pins the target's head as it is now, and moves again only when you re-pin. The server resolves the selector, and writes nothing when the pin already resolves there. Managed, external and transitive dependencies are refused, with the reason.",positionals:[_(Ae),{name:"dependency",type:{address:"model",slot:ng},required:!0,description:"The dependency's id, or its target model's id, from pin list, at @<release> for that release of the target or @main for the target's head now."}],dryRun:!0,examples:["modeldesk pin set <model> <dependency>@1.2.0","modeldesk pin set <model> <dependency>@main --json"],run:async e=>{await pt(e,e.args.model.model,{machine:le(e.env)!==void 0});let t=tt(e,e.args.model.model),n=e.api(),r=await t.model.id(),[s,o]=await Promise.all([t.model.identity(),n.dependencies.list(r)]),i={id:s.id,name:s.name},a=nP(o.items,e.args.dependency.model,{name:y(s.name),address:e.args.model.model}),d=Qc(e.args.dependency),l=te(e.instance(),{kind:"model",modelId:s.id}),c={id:a.id,name:a.name,target:{id:a.modelId},versionRef:a.versionRef??null,commitId:a.commitId};if(e.globals.dryRun){if(d!==Ce&&await Or(n,a.modelId,d)===null)throw new u(`The target of '${y(a.name)}' has no release named '${d}'.`,{exitCode:b.NotFound,hint:`Run 'modeldesk release list ${a.modelId}' to see the releases it can be pinned to.`});return{result:{dryRun:!0,model:i,dependency:c,versionRef:d,url:l}}}let m;try{m=await n.dependencies.update(r,a.id,{versionRef:d})}catch(w){throw w instanceof U&&w.status===400?Ui(w,`Run 'modeldesk release list ${a.modelId}' to see the releases it can be pinned to.`):w}let f=m,h=f.versionRef??Ce,p=f.commitId!==c.commitId||h!==(c.versionRef??Ce),g=p&&await t.isMetamodelModel()?`${y(s.name)} is a metamodel-model and its head moved: run 'modeldesk release cascade ${s.id}' to re-release it and refresh the metamodels depending on it.`:void 0;return{result:{model:i,dependency:{id:f.id,name:f.name,target:{id:f.modelId},versionRef:h,commitId:f.commitId,...h===Ce?{}:{release:h}},previous:{versionRef:c.versionRef,commitId:c.commitId},changed:p,...g?{hint:g}:{},url:l}}},render:e=>{let t=`'${y(e.dependency.name)}' of ${y(e.model.name)}`;if("dryRun"in e)return`Dry run: would re-pin ${t} to ${y(e.versionRef)} (now ${y(e.dependency.versionRef??"@HEAD (legacy)")} at ${J(e.dependency.commitId)}). Nothing was changed.`;let n=`${y(e.dependency.versionRef)} at ${J(e.dependency.commitId)}`;return[e.changed?`Pinned ${t} to ${n} (was ${y(e.previous.versionRef??"@HEAD (legacy)")} at ${J(e.previous.commitId)}).`:`${t} is already pinned to ${n}; nothing changed.`,...e.hint?[e.hint]:[],` url: ${e.url}`].join(`
218
+ `)}});var tb={dependencyAdd:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}},description:"The model depended on."},versionRef:{type:"string",description:"The selector that was sent: `@HEAD` for `@main`, else the release name."},promoted:{type:"boolean",description:"True when the model already reached the target through another dependency: that edge became a direct one in place and kept its id. Always true."},dependency:{type:"object",properties:{id:{type:"string"},name:{type:"string"},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},versionRef:{type:"string",description:"The selector: `@HEAD`, or the name of the release it is pinned to."},commitId:{type:"string"},release:{type:"string",description:"The release pinned, for a version selector."}},description:"The dependency as your draft holds it; absent on a dry run and when nothing was staged."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"Where the change went: the draft it sits in, aimed at its branch; on a dry run, what was read."},draft:{properties:{id:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"}},description:"The draft the change sits in; on a dry run, the draft as it was; null when you hold none. May be null."},message:{type:"string"},changeRequestId:{type:"string"},staged:{type:"boolean",description:"Whether the change is in your draft: staged now, or found staged under the request id. One of false, true."},dryRun:{type:"boolean",description:"Present on a dry run: the server tried the change and kept nothing. Always true."},alreadyStaged:{type:"boolean",description:"True when a change staged under the same request id was found in your draft and not staged again. One of false, true."},stagedCommitId:{type:"string"},commit:{type:"object",properties:{recovered:{type:"boolean",description:"One of false, true."},next:{type:"string",description:"What a landing off main leaves the caller with."},url:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},commit:{type:"object",properties:{id:{type:"string"},message:{type:"string"},requestId:{type:"string",description:"The `commitRequestId` the landing was sent with."},createdAt:{type:"string"},actionTypes:{type:"array",items:{type:"string"},description:"A model commit's action types: the whole chain's."},rowsChanged:{type:"number",description:"A dataset commit's count of the rows it wrote or removed."}}}},description:"Present when the draft was landed right after the change was staged."},url:{type:"string"}},required:["schemaVersion","target","versionRef","model","ref","draft","message","changeRequestId","staged","url"]}};var Ki="The change is staged in your draft of the model as a change of its own, where the person you work for sees it in the app and commits it; -m says why, in your words. --dry-run has the server try the change and keep nothing, so it answers the refusal the change would meet.",sP=e=>(t,n)=>{let{types:r,ids:s}=e(),[o,...i]=t.actionTypes,a=n.actions.map(l=>l.type).join(", ");if(o===void 0||i.length>0||!r.includes(o))return`it recorded ${t.actionTypes.join(", ")||"no action"}, and this one stages ${a}`;let d=t.elementIds?.[o];if(!(s===void 0||d===void 0))return d.some(l=>s.includes(l.toLowerCase()))?void 0:"it changed another dependency"},Pr=(e,t)=>{let n=e.versionRef??Ce;return{id:e.id,name:e.name,target:{id:e.modelId,...t?{name:t}:{}},versionRef:n,commitId:e.commitId,...n===Ce?{}:{release:n}}},oP=e=>{if(e.dryRun&&e.flags.commit)throw I("--commit has nothing to commit under --dry-run, which stages nothing.",`modeldesk ${e.commandName} --help`)},iP=(e,t)=>{let[n]=e.staged.chunks,r=n?.alreadyStaged===!0,s=r||!t.dryRun&&Ln(e.staged),o=t.dryRun&&!r,i=e.staged.target.draft,a=i?{id:i.id,headCommitId:i.headCommitId,changeCount:i.changeCount}:null;return{model:e.staged.target.model,ref:o?re(e.staged.target.resolved):Ls(e),draft:o?a:Ps(e),message:t.message,changeRequestId:e.changeRequestId,staged:s,...t.dryRun?{dryRun:!0}:{},...r?{alreadyStaged:!0,stagedCommitId:n.commitId}:{},url:t.url}},Yi=(e,t)=>X(async()=>{let{dryRun:n}=e,{message:r,commit:s}=e.flags,o=e.flags["request-id"];oP(e);let i=await _s(e),a=e.api(),d=i.model.id,l=o===void 0?void 0:En(e.origin,o),c=l===void 0||i.draft===void 0?void 0:He(a,d,i.draft.id),m=c!==void 0&&(await c).some(C=>C.requestId===l),f={types:[]},h=await Ns(e,i,async C=>{let R=(await a.dependencies.list(d,{ref:pi(C)})).items,$=await t({target:C,edges:R,retried:m});return f=$.recorded,{actions:[$.action],ids:{},resendable:!1}},{message:r,requestId:o,dryRun:n,sameChange:sP(()=>f),...c?{knownChain:c}:{}}),p=iP(h,{dryRun:n,message:r,url:e.webUrl({kind:"model",modelId:d})}),{staged:g}=p,w=h.staged.draftId,k=g&&w!==void 0?(await a.dependencies.list(d,{ref:w})).items:void 0;if(s){if(!g)throw new u(`The change left ${y(i.model.name)} as it was, so there is nothing to commit.`,{type:"nothing-to-commit"});p.commit=await Ds(e,h)}return{base:p,edgesAfter:k}}),aP=e=>e.kind==="draft"?e.branch.name:e.kind==="branch"?e.name:"",dP=e=>{let t=y(e.model.name);return e.alreadyStaged?`Already staged in your draft of ${t} under ${e.changeRequestId} (${e.stagedCommitId}); not staged again.`:e.dryRun?`Dry run: the server accepted the change and kept nothing. Nothing was staged in your draft of ${t}.`:e.staged?`Staged in your draft of ${t} on ${y(aP(e.ref))} (${P(e.draft?.changeCount??0,"change")}, at most ${je}): ${y(e.message)}`:`Nothing was staged: the change leaves ${t} as it is.`},zi=(e,t)=>{let n=[];return e.staged?n.push(t.done):e.dryRun&&n.push(t.would),[...n,dP(e),`url: ${e.url}`,...e.commit?Dn(e.commit):[]].join(`
219
+ `)},Zc=e=>`${y(e.versionRef)} at ${J(e.commitId)}`;var sb="dependency-exists",nb=(e,t)=>e.filter(n=>n.type==="INTERNAL"&&n.modelId.toLowerCase()===t),lP=(e,t,n)=>n?`Move its pin with 'modeldesk pin set ${e} ${t}@<release|main>'.`:`It is not on main, where pin set works: to change its pin, remove it with 'modeldesk dependency rm ${e} ${t}' and add it again.`,cP="Stage against the release it pins (list_dependencies shows it); moving the pin is for the person to decide. If your own session added it, draft_undo takes the add back.",mP=(e,t,n)=>new u(`${y(e.name)} already depends on '${y(t.name)}' (${t.id}), pinned to ${Zc(Pr(t))}. Nothing was staged.`,{exitCode:b.Validation,type:sb,hint:lP(e.id,t.id,n),details:{dependency:Pr(t)},hosted:{hint:cP}}),rb=["DEPENDENCY_CREATE","DEPENDENCY_UPDATE"],fP=e=>e instanceof u&&Array.isArray(e.details.errors)&&e.details.errors.some(t=>t.code===sb),ob=D({path:["dependency","add"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a dependency on another model",description:"Adds a dependency on another model of the organization. <target>@<release> pins that release; <target>@main pins the target's head as it is now, which moves again only when you re-pin. A target the model already depends on is refused (exit 4), naming the dependency to re-pin with pin set; one it reaches only through another dependency becomes a direct one in place. Dependencies on an external document are added in the app. "+Ki,positionals:[_(me),{name:"target",type:{address:"model",slot:rg},required:!0,description:"The id of the model to depend on, from model list, at @<release> for that release or @main for its head now.",toolDescription:"The model to depend on"}],flags:ve,dryRun:!0,examples:['modeldesk dependency add <model> <target>@2.5.1 -m "Profile of UML 2.5.1"','modeldesk dependency add <model>@agent/profile <target>@main -m "Track the head" --dry-run'],mcp:{name:"dependency_add",description:"Stages a dependency of model on another model of the organization, which a relation to an element of that model needs first. target is that model's id from list_models, at @<release> to pin a release or @main to pin its head now; list_dependencies shows what the model has. A dependency change is always a change of its own, which the server refuses beside any other action: add it, then stage the elements with stage_changes on the same ref, where describe and allowed_types show the types it brings. It goes to your draft with message for the person to commit; draft_undo takes back your own add.",pin:{dryRun:!1}},resultSchema:tb.dependencyAdd,run:async e=>{let t=e.args.target.model,n=Qc(e.args.target),r=e.api(),s,o=async()=>{try{return s??=(await r.models.identity(t)).name,s}catch(c){throw c instanceof U&&(c.status===404||c.status===403)?new u(`No model '${t}' that you can read, so it cannot be depended on.`,{exitCode:b.NotFound,hint:"Run 'modeldesk model list' to find the model's id.",hosted:{hint:m=>`Call ${m("model list")} to find the model's id.`}}):c}},i=Vc(),a=!1,d;try{d=await Yi(e,async({target:c,edges:m,retried:f})=>{if(await o(),c.model.id.toLowerCase()===t)throw new u(`${y(c.model.name)} cannot depend on itself.`,{exitCode:b.Validation});let h=nb(m,t),p=h.find(w=>!w.transitive);i.rewind();let g={type:"DEPENDENCY_CREATE",id:i.mint(),modelId:t,versionRef:n};if(f)return{action:g,recorded:{types:rb,ids:p?[p.id.toLowerCase()]:[]}};if(p!==void 0){let k=c.draft===void 0&&c.branch.main||(await r.dependencies.list(c.model.id)).items.some(C=>C.id===p.id&&!C.transitive);throw mP(c.model,p,k)}return a=h.length>0,{action:g,recorded:{types:rb}}})}catch(c){if(fP(c)){let{model:m}=e.args.model;throw new u(c.reason,{exitCode:c.exitCode,hint:`Run 'modeldesk pin list ${m}' to see the dependency it has.`,type:c.type,requestId:c.requestId,details:c.details,hosted:{hint:f=>`Call ${f("pin list")} with model ${m} to see the dependency it has.`}})}throw c}let l=d.edgesAfter&&nb(d.edgesAfter,t).find(c=>!c.transitive);return{result:{...d.base,target:{id:t,name:s??t},versionRef:n,...a?{promoted:!0}:{},...l?{dependency:Pr(l,s??t)}:{}}}},render:e=>{let t=`'${y(e.target.name)}'`,n=e.versionRef===Ce?"its head":y(e.versionRef),r=e.dependency?`${Zc(e.dependency)} (${e.dependency.id})`:n,s=e.promoted?", until now reached through another dependency":"",o=y(e.model.name);return zi(e,{done:`${o} depends on ${t}${s}, pinned to ${r}.`,would:`${o} would depend on ${t}${s}, pinned to ${n}.`})}});var pP={managed:{reason:"which stay while the model is written in that metamodel."},external:{reason:"which dependency rm does not remove.",hint:"Remove it in the app's model settings."},transitive:{reason:"it stays as long as the dependency that provides it.",hint:"Remove the direct dependency that provides it instead."}},ib=["DEPENDENCY_DELETE","DEPENDENCY_UPDATE"],ab=(e,t)=>js(e,t).find(n=>n.type==="INTERNAL"&&!n.transitive),db=D({path:["dependency","rm"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the removal of a dependency",description:"Removes one of the model's direct dependencies on another model, with the dependencies it brought along that nothing else needs. One another dependency still brings along stays as a transitive one. A dependency whose content elements of the model still refer to is refused (exit 4), with the referring elements in details.errors. Managed, external and transitive dependencies are refused, with the reason. "+Ki,positionals:[_(me),{name:"dependency",type:"string",required:!0,description:"The dependency's id, or its target model's id, from pin list."}],flags:ve,dryRun:!0,examples:['modeldesk dependency rm <model> <dependency> -m "No longer a profile of UML"','modeldesk dependency rm <model> <dependency> -m "No longer a profile of UML" --dry-run'],run:async e=>{let t=e.args.dependency.toLowerCase(),n=e.api(),r,s=await Yi(e,async({target:l,edges:c,retried:m})=>{let f=y(l.model.name);if(m){let p=(await n.dependencies.list(l.model.id,{ref:l.branch.id})).items;r=ab(p,t)??ab(c,t);let g=[...js([...p,...c],t).map(w=>w.id.toLowerCase()),t];return{action:{type:"DEPENDENCY_DELETE",dependencyId:r?.id??t},recorded:{types:ib,ids:g}}}let h=Xc(c,t,{name:f,address:e.args.model.model});return r=Jc(h,f,pP),{action:{type:"DEPENDENCY_DELETE",dependencyId:r.id},recorded:{types:ib,ids:[r.id.toLowerCase()]}}}),{edgesAfter:o}=s,i=r?.modelId.toLowerCase(),a=o&&(i===void 0?js(o,t):o.filter(l=>l.type==="INTERNAL"&&l.modelId.toLowerCase()===i)),d=a?.some(l=>l.transitive)?"kept-as-transitive":"removed";return{result:{...s.base,...r?{dependency:Pr(r)}:{},...a?{outcome:d}:{}}}},render:e=>{let t=e.dependency?`'${y(e.dependency.name)}'`:"The dependency",n=y(e.model.name);return zi(e,{done:e.outcome==="kept-as-transitive"?`${t} is no longer a direct dependency of ${n}; another dependency still brings it along.`:`${t} is removed from the dependencies of ${n}.`,would:`${t} would be removed from the direct dependencies of ${n}.`})}});var lb={describe:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"What the schema was resolved at: your draft while it holds staged changes, else your working branch, or the ref named."},schema:{type:"object",properties:{modelId:{type:"string"},metamodel:{type:"object",properties:{id:{type:"string"},name:{type:"string"},version:{type:"string"},prefix:{type:"string"}}},root:{type:"array",items:{type:"object",properties:{type:{type:"string"},label:{type:"string"},multiplicity:{type:"object",properties:{min:{type:"number"},max:{type:"number"}}},instantiableTypes:{type:"array",items:{type:"string"}}}}},types:{type:"array",items:{type:"object",properties:{name:{type:"string"},label:{type:"string"},abstract:{type:"boolean",description:"One of false, true."},package:{type:"boolean",description:"One of false, true."},trait:{type:"boolean",description:"One of false, true."},internal:{type:"boolean",description:"One of false, true."},specializes:{type:"array",items:{type:"string"}},traits:{type:"array",items:{type:"string"}}}}},type:{type:"object",properties:{name:{type:"string"},label:{type:"string"},definition:{type:"string"},abstract:{type:"boolean",description:"One of false, true."},package:{type:"boolean",description:"One of false, true."},trait:{type:"boolean",description:"One of false, true."},internal:{type:"boolean",description:"One of false, true."},specializes:{type:"array",items:{type:"string"}},supertypes:{type:"array",items:{type:"string"}},traits:{type:"array",items:{type:"string"}},keyProperties:{type:"array",items:{type:"string"}},instantiableTypes:{type:"array",items:{type:"string"}},attributes:{type:"array",items:{type:"object",properties:{name:{type:"string"},label:{type:"string"},definedBy:{type:"string"},multiplicity:{type:"object",properties:{min:{type:"number"},max:{type:"number"}}},schema:{type:"object",properties:{type:{type:"string",description:'One of "any", "boolean", "integer", "number", "object", "string".'},properties:{type:"object",additionalProperties:{type:"object",properties:{type:{type:"string",description:'One of "any", "boolean", "integer", "number", "string".'},absentDiffers:{type:"boolean",description:"One of false, true."},trueLabel:{type:"object",additionalProperties:{type:"string"}},falseLabel:{type:"object",additionalProperties:{type:"string"}},format:{type:"string"},minimum:{type:"number"},maximum:{type:"number"},enum:{type:"array",items:{type:"string"}},multiline:{type:"boolean",description:"One of false, true."},tokenSet:{type:"boolean",description:"One of false, true."},exclusiveTokens:{type:"array",items:{type:"string"}},lang:{type:"object",properties:{optional:{type:"boolean",description:"One of false, true."},uniqueLang:{type:"boolean",description:"One of false, true."}}},enumLabels:{type:"object",additionalProperties:{type:"object",additionalProperties:{type:"string"}}}}}},required:{type:"array",items:{type:"string"}},absentDiffers:{type:"boolean",description:"One of false, true."},trueLabel:{type:"object",additionalProperties:{type:"string"}},falseLabel:{type:"object",additionalProperties:{type:"string"}},format:{type:"string"},minimum:{type:"number"},maximum:{type:"number"},enum:{type:"array",items:{type:"string"}},multiline:{type:"boolean",description:"One of false, true."},tokenSet:{type:"boolean",description:"One of false, true."},exclusiveTokens:{type:"array",items:{type:"string"}},lang:{type:"object",properties:{optional:{type:"boolean",description:"One of false, true."},uniqueLang:{type:"boolean",description:"One of false, true."}}},enumLabels:{type:"object",additionalProperties:{type:"object",additionalProperties:{type:"string"}}}}},derived:{type:"boolean",description:"One of false, true."}}}},relations:{type:"array",items:{type:"object",properties:{name:{type:"string"},label:{type:"string"},definedBy:{type:"string"},multiplicity:{type:"object",properties:{min:{type:"number"},max:{type:"number"}}},ownership:{type:"string",description:'One of "MIXED", "MULTI_OWNED", "OWNED", "UNOWNED".'},allowedTargetTypes:{type:"array",items:{type:"object",properties:{name:{type:"string"},label:{type:"string"},foreign:{type:"boolean",description:"One of false, true."},metamodelId:{type:"string"}}}},parentBound:{type:"boolean",description:"One of false, true."},unrestricted:{type:"boolean",description:"One of false, true."},derived:{type:"boolean",description:"One of false, true."},abstract:{type:"boolean",description:"One of false, true."}}}},homeSlots:{type:"array",items:{type:"object",properties:{ownerType:{type:"string"},relation:{type:"string"}}}},childSlots:{type:"array",items:{type:"object",properties:{relation:{type:"string"},targetTypes:{type:"array",items:{type:"string"}}}}},kindGroups:{type:"array",items:{type:"object",properties:{classifier:{type:"string"},kinds:{type:"array",items:{type:"string"}},shared:{type:"array",items:{type:"string"}},distinguishing:{type:"array",items:{type:"object",properties:{binding:{type:"string"},kinds:{type:"array",items:{type:"string"}}}}}}}}}}}}},required:["schemaVersion","model","ref","schema"]}};var cb="type-not-found",em=({min:e,max:t})=>`${e??0}..${t===void 0||t<0?"*":t}`,hP=e=>{if(e===void 0)return"";switch(e.type){case"string":{let t=[e.format,e.lang?"language-tagged":void 0,e.enum?`one of ${e.enum.join(", ")}`:void 0].filter(n=>n!==void 0);return t.length===0?"string":`string (${t.join("; ")})`}case"integer":case"number":{let t=e.minimum!==void 0||e.maximum!==void 0?` ${e.minimum??""}..${e.maximum??""}`:"";return`${e.type}${t}`}default:return e.type}},mb=e=>["abstract","package","trait","internal"].filter(t=>e[t]).join(", "),gP=e=>e.parentBound?"the owner's type ($parent)":e.unrestricted?"any type":(e.allowedTargetTypes??[]).map(t=>t.foreign?`${t.name} (foreign)`:t.name).join(", "),_n=(e,t)=>[`${e}:`,...t.length===0?[" none"]:t],yP=(e,t)=>{let n=new Set((e.types??[]).filter(a=>a.internal).map(a=>a.name)),r=a=>t||!(n.has(a)||In(a)),s=(e.root??[]).filter(a=>r(a.type)),o=(e.types??[]).filter(a=>r(a.name)),i=(e.types??[]).length-o.length;return[..._n("Root",F(s.map(a=>[a.type,y(a.label),em(a.multiplicity),a.instantiableTypes&&a.instantiableTypes.join()!==a.type?`creates ${a.instantiableTypes.join(", ")}`:""]),{indent:" "})),..._n("Types",o.length===0?[]:F([["NAME","LABEL","KIND","SPECIALIZES"],...o.map(a=>[a.name,y(a.label),mb(a),(a.specializes??[]).join(", ")])],{indent:" "})),...i>0?[`(${i} internal types not shown; pass --internal to list them.)`]:[]]},wP=e=>{let t=[["kind:",mb(e)],["definition:",y(e.definition??"")],["supertypes:",(e.supertypes??[]).join(", ")],["traits:",(e.traits??[]).join(", ")],["instantiable as:",(e.instantiableTypes??[]).join(", ")],["keyed by:",(e.keyProperties??[]).join(", ")]],n=i=>[i.derived?"derived":"",i.abstract?"abstract":""].filter(a=>a!=="").join(", "),r=(e.attributes??[]).map(i=>[i.name,y(i.label),hP(i.schema),em(i.multiplicity),i.definedBy?`from ${i.definedBy}`:"",n(i)]),s=(e.relations??[]).map(i=>[i.name,y(i.label),em(i.multiplicity),i.ownership,gP(i),i.definedBy?`from ${i.definedBy}`:"",n(i)]),o=(e.kindGroups??[]).flatMap(i=>[` ${i.classifier}: ${i.kinds.join(", ")}`,...i.shared?.length?[` shared: ${i.shared.join(", ")}`]:[],...(i.distinguishing??[]).map(a=>` ${a.binding}: ${a.kinds.join(", ")}`)]);return[`${e.name} (${y(e.label)})`,...F(t.filter(([,i])=>i!==""),{indent:" "}),..._n("Attributes",r.length===0?[]:F([["NAME","LABEL","SCHEMA","MULT","DEFINED",""],...r],{indent:" "})),..._n("Relations",s.length===0?[]:F([["NAME","LABEL","MULT","OWNERSHIP","TARGETS","DEFINED",""],...s],{indent:" "})),..._n("Home slots (where it can live)",(e.homeSlots??[]).map(i=>` ${i.ownerType}.${i.relation}`)),..._n("Child slots (what can be created inside it)",(e.childSlots??[]).map(i=>` ${i.relation}: ${i.targetTypes.join(", ")}`)),...o.length===0?[]:_n("Kind groups",o)]},bP=(e,t)=>{let{metamodel:n}=e;return[`Metamodel ${y(n.name)}`+(n.version?` ${n.version}`:"")+(n.prefix?` (prefix ${n.prefix})`:""),...e.type?wP(e.type):yP(e,t)].join(`
220
+ `)},kP=(e,t)=>{let n=e.problem?.candidates,r=Array.isArray(n)?n.filter(s=>typeof s=="string"):[];return new u(e.problem?.detail??`The metamodel declares no type '${e.problem?.typeName}'.`,{exitCode:r.length>0?b.Usage:b.NotFound,type:cb,requestId:e.requestId,details:e.details,hint:r.length>0?"Pass one of the candidates.":`Run 'modeldesk describe ${t}' to list the types of its metamodel.`,hosted:{hint:s=>r.length>0?"Pass one of the candidates.":`Call ${s("describe")} with model ${t} alone to list the types of its metamodel.`}})},fb=D({path:["describe"],effect:"read",summary:"Describe the schema a model is written against",description:"Without a type: the types the model root admits and every classifier of its metamodel, with its label, kind and supertypes. With a type (canonical, such as sh:NodeShape, or any spelling naming one classifier): its supertypes and traits, its attributes with value schema and multiplicity, its relations with multiplicity, ownership and resolved allowed targets, where an element of it can live, what can be created inside one, and the kind groups of a discriminated branch. Read at the ref the address names, else where you work, since a dependency staged in your draft brings its target's metamodel into the schema. --json prints the server document as schema.",positionals:[_(Oe),{name:"type",type:"string",description:"The classifier to describe in full."}],flags:{internal:{type:"boolean",description:"List the internal types (`@` types and auxiliary ones) in the overview too; --json always carries them."}},examples:["modeldesk describe <model>","modeldesk describe <model>@agent/profile sh:NodeShape --json"],mcp:{name:"describe",description:"Describes the schema a model is written against at the ref you give. Without type it lists the types the model root admits and every classifier with its label, kind and supertypes. With type it gives that type's attributes with value schema and multiplicity, its relations with their allowed targets, where an element of it can live and what can be created inside one. Call it before staging, to learn the type, attribute and relation names that stage_changes takes. Write the ref you stage on: a dependency staged there adds its types.",pin:{internal:!1}},resultSchema:lb.describe,run:async e=>{let{model:t,type:n}=e.args,r=await Z(e,t,Oe),s=re(r);s.note!==void 0&&e.note(s.note);try{let o=await e.api().models.schema(r.id,{ref:s.id,type:n});return{result:{model:{id:r.id,name:r.name},ref:s,schema:o}}}catch(o){throw o instanceof U&&o.type===cb?kP(o,t.text):o}},render:(e,t)=>bP(e.schema,t.internal)});var pb=q({path:["draft","discard"],effect:"unstage",summary:"Discard your draft and everything staged on it",description:"Discards your draft with every change staged on it, whichever surface staged them. It restates what it will discard and asks at a terminal; anywhere else it needs --yes. It sends the draft head it read, so a change staged after that is not destroyed unseen (exit 5). Holding no draft is reported, not refused. --dry-run restates what it would discard and discards nothing. Under an agent host a draft holding changes made outside an agent session (in the app) is left to a person (exit 6) unless --any-surface.",positionals:[Me],flags:nr,dryRun:!0,examples:["modeldesk draft discard <model> --dry-run","modeldesk draft discard <model> --yes"],run:async e=>X(async()=>{let t=await Ne(e),n=se(t.ref),r=await t.read(),{dryRun:s}=e.globals,o={resource:t.ref,discarded:!1,dryRun:s,draft:null};if(r===void 0)return{result:o};if(s)return{result:{resource:t.ref,discarded:!1,dryRun:s,draft:r}};let i=P(r.changeCount,"staged change");await qe(e,t,r,{scope:{kind:"all"},action:`Discarding your draft of ${n}`,anySurface:e.flags["any-surface"],override:"pass --any-surface only when they asked for it."}),await ct(e,`Discard your draft of ${n} with its ${i}?`,`Discarding your draft of ${n} (${i})`);try{await t.discard(r.headCommitId)}catch(a){if(a instanceof U&&a.status===404)return{result:o};throw a instanceof u&&a.type==="draft-moved"?new u(`Your draft of ${n} moved after this command read it, so nothing was discarded.`,{exitCode:b.Conflict,type:a.type,details:a.details,hint:"Run 'modeldesk draft status' to see what it now holds, then discard again if you still mean to."}):a}return{result:{resource:t.ref,discarded:!0,dryRun:s,draft:r}}}),render:e=>{let t=se(e.resource);if(e.draft===null)return`You hold no draft of ${t}; nothing was discarded.`;let n=`${t} (${P(e.draft.changeCount,"staged change")})`;return e.dryRun?`Would discard your draft of ${n}. Dry run: nothing was discarded.`:`Discarded your draft of ${n}.`}});var jn=async(e,t,n)=>{let r=0,s=!1,o=async()=>{for(;!s&&r<e.length;)try{await n(e[r++])}catch(i){throw s=!0,i}};await Promise.all(Array.from({length:Math.min(t,e.length)},o))};var nm=600,Xi=86400,rm=90,Qi=120,Fs={kind:"keep-waiting"},hb={kind:"draft-reset"},EP=(e,t)=>{let n=e.find(o=>o.refId===t.draftId);if(n===void 0)return{reading:{kind:"draft-missing"},held:t};if(t.draftResets!==void 0&&n.resets!==t.draftResets)return{reading:hb,held:t};let r=e.find(o=>o.refId===t.targetRefId);if(r!==void 0&&r.headCommitId!==t.targetHead)return{reading:{kind:"branch-moved",branchHeadId:r.headCommitId},held:t};let s={...t,draftHead:n.headCommitId,draftResets:n.resets};return t.draftResets===void 0&&n.headCommitId!==t.draftHead?{reading:{kind:"draft-moved",from:t.draftHead},held:s}:{reading:Fs,held:s}},CP=(e,t)=>{switch(e.event){case"heads":return EP(e.heads,t);case"ref-deleted":return{reading:e.refId===t.draftId?{kind:"draft-deleted"}:Fs,held:t};case"head-advanced":return e.refId===t.draftId?e.reset?{reading:hb,held:t}:{reading:Fs,held:{...t,draftHead:e.headCommitId}}:e.refId===t.targetRefId&&e.headCommitId!==t.targetHead?{reading:{kind:"branch-moved",branchHeadId:e.headCommitId},held:t}:{reading:Fs,held:t};default:return{reading:Fs,held:t}}},vP=8,RP=5,gb=100,SP=async(e,t,n,r)=>{try{return(await e.api().models.commits(t,{ref:n,limit:gb,cursor:r})).items}catch(s){if(s instanceof U&&s.status===404)return;throw s}},IP=async(e,t,n)=>{let r=[],s;for(let o=0;o<RP;o++){let i=await SP(e,t,n.targetRefId,s);if(i===void 0)return;for(let a of i){if(a.id===n.baselineCommitId)return r;a.stagedChangeCount!==void 0&&r.push(a)}if(i.length<gb)return r;s=i.at(-1)?.id}return r},$P=async(e,t,n,r)=>{let s=await IP(e,t,n);if(s===void 0)return{verdict:"discarded"};let o=new Map;await jn(s,vP,async a=>{let d=await e.api().models.commitHeader(t,a.id,{ref:n.targetRefId});o.set(a.id,(d.stagedChanges??[]).filter(l=>r.has(l.requestId??"")).length)});let i=s.find(a=>(o.get(a.id)??0)>0);return i===void 0?{verdict:"discarded"}:{verdict:"committed",commitId:i.id,url:e.webUrl({kind:"commit",modelId:t,commitId:i.id}),landed:o.get(i.id)??0}},xP=[500,1500],yb=e=>e instanceof u&&e.exitCode===b.Transient,Lr=class extends Error{},TP=e=>new Promise(t=>setTimeout(t,e)),wb=async e=>{for(let t of xP)try{return await e()}catch(n){if(!yb(n))throw n;await TP(t)}return e()},bb=(e,t)=>new Promise((n,r)=>{let s=()=>r(new Lr);if(e.aborted){s();return}e.addEventListener("abort",s,{once:!0}),t().then(n,r).finally(()=>e.removeEventListener("abort",s))}),AP=async(e,t,n)=>{let r=await dt(()=>e.api().models.draft(t));return r?.id===n?r:void 0},tm={kind:"gone"},Ji={kind:"keep-waiting"},ub=e=>({kind:"verdict",verdict:{verdict:"changed",changeCount:e.changeCount}}),OP=async(e,t,n,r,s)=>{if(r.baselineCommitId!==n.baselineCommitId)return!1;if(s===n.baselineCommitId)return!0;try{return(await He(e.api(),t,n.id)).some(i=>i.id===s)}catch(o){if(mi(o))return;throw o}},MP=async(e,t,n,r)=>{if(e.kind==="keep-waiting")return Ji;if(e.kind==="draft-deleted")return tm;let s=await AP(t,n,r.id);if(s===void 0)return tm;switch(e.kind){case"draft-missing":return Ji;case"draft-reset":return ub(s);case"branch-moved":return{kind:"verdict",verdict:{verdict:"branch-moved",branchHeadId:e.branchHeadId}};case"draft-moved":{let o=await OP(t,n,r,s,e.from);return o===void 0?tm:o?Ji:ub(s)}}},sm=(e,t)=>new u(`You hold no draft of ${e}, so there is nothing to wait on.`,{type:"no-draft",hint:`It was committed or discarded before the wait began, or never opened. Run 'modeldesk model log ${t} --changes' to see whether your changes landed.`,hosted:{hint:n=>`The person has already answered (committed or discarded the draft), or nothing was handed off. Call ${n("model log")} with model ${t} and changes true to see whether your changes landed.`}}),NP=async(e,t,n,r)=>{let s;try{s=await He(e.api(),t,n)}catch(o){throw mi(o)?sm(r.subject,r.address):o}return new Set(s.map(o=>o.requestId).filter(o=>o!==void 0&&ts(o,e.origin)))},PP=(e,t,n)=>{let r=`'modeldesk draft diff ${t} --changes' to see where each change came from.`,s=o=>`Call ${o("draft diff")} with model ${t} and changes true to see where each change came from.`;return es(n)===void 0?new u(`None of the staged changes in your draft of ${e} was made by the CLI or an agent, so there is nothing of yours to wait on.`,{type:"no-own-changes",hint:`Run ${r}`,hosted:{hint:s}}):new u(`None of the staged changes in your draft of ${e} was made by this agent session, so there is nothing of its own to wait on.`,{type:"no-own-changes",hint:`Wait from the session that staged them, under the same MODELDESK_AGENT_SESSION, or run ${r}`,hosted:{hint:o=>`The person may have removed them first, or another connection staged them. ${s(o)}`}})},kb=(e,t,n,r)=>new u(`No verdict on your draft of ${e} within ${t} seconds; the draft is as it was.`,{exitCode:b.Transient,type:eu,hint:`Run '${n}' again to keep waiting.`,hosted:{reason:`No verdict on your draft of ${e} yet; the draft is as it was.`,hint:s=>`Call ${s("draft status")} again with wait: true to keep waiting.`},report:r}),LP=(e,t,n)=>new u(`Your draft of ${e} is gone, and the commits that say whether it landed could not be read (${n.reason}).`,{exitCode:b.Transient,type:"verdict-unread",hint:`Run 'modeldesk model log ${t} --changes' to see whether your changes landed.`,hosted:{hint:r=>`Call ${r("model log")} with model ${t} and changes true to see whether your changes landed.`}}),DP=async(e,t,n,r,s)=>{let{modelId:o,draft:i}=s,{held:a}=s;try{for await(let d of e.events(o,AbortSignal.any([r,n]))){let l=CP(d,a);a=l.held;let c=await bb(n,()=>wb(()=>MP(l.reading,t,o,i)));if(c.kind!=="keep-waiting")return c}}catch(d){if(!(d instanceof Lr))throw d}return Ji},Eb=async(e,t,n,r)=>{let s=await NP(e,t,n.id,r);if(s.size===0)throw PP(r.subject,r.address,e.origin);if(r.branchHeadId!==n.baselineCommitId)return{verdict:"branch-moved",branchHeadId:r.branchHeadId};let o={draftId:n.id,targetRefId:n.targetRefId,draftHead:n.headCommitId,targetHead:r.branchHeadId},i=new AbortController,a=setTimeout(()=>i.abort(),Math.max(0,r.deadline()-Date.now())),d=new AbortController,l=e.deadline===void 0?void 0:setTimeout(()=>d.abort(),Math.max(0,e.deadline-Date.now())),c=e.signal===void 0?d.signal:AbortSignal.any([d.signal,e.signal]),m={...e,api:()=>{if(c.aborted)throw new Lr;return e.api()}};try{let f;try{f=await DP(e,m,c,i.signal,{modelId:t,draft:n,held:o})}finally{clearTimeout(a),i.abort()}switch(f.kind){case"keep-waiting":return{verdict:"timed-out"};case"verdict":return f.verdict;case"gone":try{return await bb(c,()=>wb(()=>$P(m,t,n,s)))}catch(h){if(h instanceof Lr)return{verdict:"timed-out"};throw yb(h)?LP(r.subject,r.address,h):h}}}finally{clearTimeout(l)}};var Cb={draftStatus:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},resource:{type:"object",properties:{kind:{type:"string",description:'One of "dataset", "model".'},id:{type:"string"},name:{type:"string"}}},draft:{properties:{id:{type:"string"},targetRefId:{type:"string"},baselineCommitId:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"},createdAt:{type:"string"},updatedAt:{type:"string"},movesBaseTo:{type:"string"},handoff:{type:"object",properties:{summary:{type:"string"},headCommitId:{type:"string"},at:{type:"string"}}},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"Your draft and the branch it targets, or null when you hold none. May be null."},maxChanges:{type:"number",description:"The most changes a draft holds; staging past it is refused until the draft is committed."},branchHeadCommitId:{type:"string",description:"The head of the branch the draft lands on, main's (the dataset's) without a draft."},behind:{type:"boolean",description:"Whether the branch moved past the draft's baseline, so a commit needs a rebase first. Absent without a draft. One of false, true."},reads:{type:"object",properties:{default:{type:"string",description:'One of "draft", "head".'},head:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"What an invocation that names no ref reads right now: your draft while it holds staged changes, else the head of the branch it targets, main when you hold none. A dataset's branch is named only by a draft that targets it."},url:{type:"string",description:"The app page where the draft is reviewed and committed; absent for a dataset."},verdict:{type:"string",description:'One of "branch-moved", "changed", "committed", "discarded".'},branchHeadId:{type:"string",description:"The head the branch moved to."},changeCount:{type:"number",description:"How many changes the draft holds now."},commitId:{type:"string",description:"The landing that holds this session's changes."},landed:{type:"number",description:"How many of this session's changes it landed."}},required:["schemaVersion","resource","draft","maxChanges","branchHeadCommitId","reads"]}};var vb=e=>"name"in e?y(e.name):e.id,jP=e=>{let{draft:t,reads:n}=e,r=()=>{let o=n.head===void 0?"the branch head":`the head of ${vb(n.head)}`;return`Unaddressed reads see ${n.default==="draft"?"your draft":o}.`};if(t===null)return[`You hold no draft of ${se(e.resource)}.`,r(),...e.url?[`url: ${e.url}`]:[]].join(`
221
+ `);let s=e.behind?`${t.baselineCommitId} (behind the branch head ${e.branchHeadCommitId}: rebase before committing)`:t.baselineCommitId;return[`Your draft of ${se(e.resource)}, aimed at ${vb(t.target)}:`,...F([["draft:",t.id],["changes:",`${t.changeCount} of at most ${e.maxChanges}`],["baseline:",s],["head:",t.headCommitId],["created:",t.createdAt],["updated:",t.updatedAt],...e.url?[["url:",e.url]]:[]],{indent:" "}),r()].join(`
222
+ `)},FP=e=>{let t=se(e.resource);switch(e.verdict){case"committed":return[`Your draft of ${t} was committed as ${e.commitId}, with ${e.landed} of your changes.`,`url: ${e.url}`].join(`
223
+ `);case"discarded":return`None of your changes to ${t} landed: the draft was discarded, or they were removed before it was committed.`;case"changed":return`Your draft of ${t} was changed in review; it now holds ${P(e.changeCount,"change")}.`;case"branch-moved":{let n=e.draft===null?e.resource.id:yr(e.resource,e.draft.target);return`The branch your draft of ${t} aims at moved to ${e.branchHeadId}. Run 'modeldesk draft rebase ${n}', resolve any conflict in your own changes, then wait again.`}}},om=e=>e.name===void 0?{id:e.id}:{id:e.id,name:e.name},Zi="modeldesk draft status --help",qP=(e,t,n)=>{if(t!==void 0&&!e)throw I("--timeout bounds --wait; pass both, or neither.",Zi,{reason:"timeout bounds wait; pass both, or neither."});if(t!==void 0&&t<=0)throw I(`--timeout takes a positive number of seconds, got ${t}.`,Zi,{reason:`timeout takes a positive number of seconds, got ${t}.`});if(t!==void 0&&t>Xi)throw I(`--timeout takes at most ${Xi} seconds (a day), got ${t}.`,Zi);if(e&&n.kind==="dataset")throw I("--wait takes a model: a dataset's changes are announced on no event stream.",Zi,{reason:"wait takes a model: a dataset's changes are announced on no event stream."})},WP=e=>e.kind==="model"&&e.address.ref.kind==="branch"?y(e.address.text):void 0,Rb=D({path:["draft","status"],effect:"read",summary:"Show your draft of a model or dataset",description:`Shows your own draft: the branch it aims at, the head it is based on, its head, how many changes it holds against the ${je}-change cap, and whether that branch has moved past its baseline (a commit then needs a rebase first). reads says what an invocation that names no ref reads right now: your draft while it holds changes, else the head of the branch it aims at, main when you hold none. Holding no draft is reported, not refused. Drafts are private: you see only your own. With --wait it then waits on the model's change stream for what a person does with the draft, typically after 'draft handoff', and reports the verdict beside the status: committed, discarded, changed or branch-moved, each exit 0. A forward move of the draft (the person staging edits of their own) is no verdict. When --timeout elapses or the stream cannot be re-established it exits 7, retryable: run it again. A draft the branch already left behind answers branch-moved at once.`,positionals:[Me],flags:{wait:{type:"boolean",description:"Wait for what a person does with your draft of a model and report it as verdict: committed (with the commit and how many of your changes landed), discarded, changed, or branch-moved (rebase, then wait again). Exits 7, retryable, when --timeout elapses.",toolDescription:"Wait for what a person does with your draft and answer it as verdict: committed (with the commit, its url and how many of your changes landed), discarded, changed, or branch-moved (call draft_rebase, then wait again). A wait that ends with no answer returns verdict timed-out; call again to keep waiting."},timeout:{type:"number",placeholder:"seconds",description:`How long --wait waits for a verdict before exiting 7; ${nm} when not given, ${Xi} (a day) at most.`,toolDescription:`How long wait waits for a verdict, in seconds; ${rm} when not given, ${Qi} at most (a larger value waits ${Qi}).`}},examples:["modeldesk draft status <model>","modeldesk draft status dataset/<dataset-id> --json","modeldesk draft status <model> --wait --timeout 300"],mcp:{name:"draft_status",description:"Shows your draft of the model: the branch it aims at, its baseline and head, how many changes it holds against the cap, and whether the branch has moved past its baseline (call draft_rebase before committing then). reads says what a call that names no ref reads right now. After draft_handoff, call it with wait: true to hear the person's answer as verdict (committed, discarded, changed, branch-moved); a wait that ends with no answer returns verdict timed-out and the draft as it was, so call again.",wait:{defaultSeconds:rm,maxSeconds:Qi}},resultSchema:Cb.draftStatus,run:async e=>X(async()=>{let{wait:t,timeout:n}=e.flags;qP(t===!0,n,e.args.resource);let r=await Ne(e),s=await r.read(),o=await r.workingBranch(s),i=o.branch===void 0?void 0:om(o.branch),a=s!==void 0&&s.headCommitId!==s.baselineCommitId,d={resource:r.ref,draft:s===void 0||i===void 0?null:{...s,target:i},maxChanges:je,branchHeadCommitId:o.head,...s?{behind:s.baselineCommitId!==o.head}:{},reads:{default:a?"draft":"head",...i===void 0?{}:{head:i}},...r.url?{url:r.url}:{}};if(!t)return{result:d};let l=se(r.ref),c=i===void 0?r.ref.id:yr(r.ref,i);if(s===void 0)throw sm(l,WP(e.args.resource)??c);let m=n??nm,f=await Eb(e,r.ref.id,s,{subject:l,address:c,deadline:()=>Math.min(Date.now()+m*1e3,e.deadline??Number.POSITIVE_INFINITY),branchHeadId:o.head});if(f.verdict==="timed-out"){let p=n===void 0?"":` --timeout ${n}`;throw kb(l,m,`modeldesk draft status ${c} --wait${p}`,{...d})}return{result:{...d,...f}}}),render:e=>"verdict"in e?FP(e):jP(e)});var Sb={draftHandoff:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},resource:{type:"object",properties:{kind:{type:"string",description:'One of "dataset", "model".'},id:{type:"string"},name:{type:"string"}}},draft:{type:"object",properties:{id:{type:"string"},targetRefId:{type:"string"},baselineCommitId:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"},createdAt:{type:"string"},updatedAt:{type:"string"},movesBaseTo:{type:"string"},handoff:{type:"object",properties:{summary:{type:"string"},headCommitId:{type:"string"},at:{type:"string"}}},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"Your draft as the server answered the handoff, carrying it as `handoff`, and the branch it targets."},url:{type:"string",description:"The model in the app, where the person reviews and commits the draft."}},required:["schemaVersion","resource","draft"]}};var Ib="modeldesk draft handoff --help",HP=async e=>{try{let t=await e.read();return t===void 0?e.ref.id:yr(e.ref,await e.branch(t.targetRefId))}catch{return e.ref.id}},UP=async(e,t)=>{let n=se(t.ref);if(!(e instanceof u))return e;let r={type:e.type,requestId:e.requestId,details:e.details};switch(e.type){case"nothing-to-hand-off":return new u(`Your draft of ${n} holds no staged change, so there is nothing to hand off.`,{...r,exitCode:b.Failure});case"draft-moved":{let s=await HP(t);return new u(`Your draft of ${n} moved while it was being handed off (a change was staged, undone or rebased), so no handoff was stored.`,{...r,exitCode:b.Conflict,hint:`Review it with 'modeldesk draft diff ${s} --changes', then hand it off again.`,hosted:{hint:o=>`Review it with ${o("draft diff")} (model ${s}, changes: true), then hand it off again.`}})}default:return e}},$b=D({path:["draft","handoff"],effect:"stage",summary:"Hand your draft off to a person for review, with a summary",description:"Stores the summary on your draft and marks it ready for review: the open model shows a notice with it, the panel header carries it, the commit dialog starts from it, and the model list reads Ready for review. Nothing is staged or committed, and a second handoff replaces the first. The person answers by committing, removing changes or discarding in the app; 'draft status --wait' reports which. A draft holding no staged change exits 1, and one that moved while it was handed off exits 5 with nothing stored. Models only: a dataset draft has no handoff (exit 2).",positionals:[Me],flags:{message:{type:"string",short:"m",required:!0,placeholder:"summary",description:"What the draft does, in your words: the summary the person reviews it by. Plain text.",requiredReason:"The summary is your own account of the draft; none is composed."}},examples:['modeldesk draft handoff <model> -m "Tidy the shape names and add the severity binding"','modeldesk draft handoff <model>@feat/x -m "Ready: the new bindings on feat/x" --json'],mcp:{name:"draft_handoff",description:"Hands your draft to the person for review, with message as the summary they review it by; nothing is staged or committed, and a second handoff replaces the first. Then call draft_status with wait: true to hear the person's answer. This is the lane for a small change; for larger work, commit on a branch of your own (branch_create with an agent/<topic> name and open: true)."},resultSchema:Sb.draftHandoff,run:async e=>X(async()=>{if(e.args.resource.kind==="dataset")throw I("A dataset draft has no handoff; draft handoff takes a model.",Ib);let t=St(e.flags.message,Ib),n=await Ne(e),r;try{r=await e.api().drafts.model.handoff(n.ref.id,{summary:t})}catch(o){throw await UP(o,n)}return{result:{resource:n.ref,draft:{...r,target:om(await n.branch(r.targetRefId))},...n.url?{url:n.url}:{}}}}),render:e=>[`Handed off your draft of ${se(e.resource)} for review (${P(e.draft.changeCount,"staged change")}): ${y(e.draft.handoff?.summary.split(`
224
+ `)[0]??"")}`,...e.url?[`url: ${e.url}`]:[],`Wait for the verdict: modeldesk draft status ${yr(e.resource,e.draft.target)} --wait`].join(`
225
+ `)});var xb={draftRebase:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},resource:{type:"object",properties:{kind:{type:"string",description:'One of "dataset", "model".'},id:{type:"string"},name:{type:"string"}}},draft:{type:"object",properties:{id:{type:"string"},targetRefId:{type:"string"},baselineCommitId:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"},createdAt:{type:"string"},updatedAt:{type:"string"},movesBaseTo:{type:"string"},handoff:{type:"object",properties:{summary:{type:"string"},headCommitId:{type:"string"},at:{type:"string"}}}},description:"The draft as it now stands: based on the branch head, holding the chain less what was dropped."},dropped:{type:"array",items:{type:"object",properties:{commitId:{type:"string"},requestId:{type:"string"},message:{type:"string"},actionTypes:{type:"array",items:{type:"string"}},rowsChanged:{type:"number"}}},description:"The changes left out as asked, in chain order."},closureChanged:{type:"boolean",description:"Whether the branch changed the model's dependencies while the draft was open (models only). One of false, true."},schemaChanged:{type:"boolean",description:"Whether the branch changed the model's metamodel pin while the draft was open (models only). One of false, true."}},required:["schemaVersion","resource","draft","dropped"]}};var GP=e=>{let t=[e.code,e.actionIndex===void 0?void 0:`action ${e.actionIndex}`,e.elementId===void 0?void 0:`element ${e.elementId}`,e.property===void 0?void 0:`property ${e.property}`].filter(n=>n!==void 0);return`${y(e.message)} (${t.join(", ")})`},Tb=e=>e?` (${e})`:"",KP=e=>e.flatMap(t=>[`Change ${t.sourceCommitId}${Tb(t.requestId)}: ${y(t.description)}`,...t.actionTypes?.length?[` actions: ${t.actionTypes.join(", ")}`]:[],...(t.errors??[]).map(n=>` - ${GP(n)}`),...t.rowIds?.length?[` rows: ${t.rowIds.join(", ")}`]:[]]).map(t=>`${t}
226
+ `).join(""),Ab=e=>Array.isArray(e.details.conflicts)?e.details.conflicts:[],YP=(e,t)=>{if(!(e instanceof u))return e;if(e.type==="rebase-conflict"){let n=Ab(e);return new u(`The branch head refuses ${P(n.length,"staged change")} of your draft of ${t}, so nothing was rebased.`,{exitCode:b.Conflict,type:e.type,requestId:e.requestId,details:e.details,hint:"Correct those changes, or leave them out with --drop <change id> (a change id is its sourceCommitId).",hosted:{hint:"Correct those changes, or leave them out by listing their ids in 'drop' (a change id is its sourceCommitId)."}})}return e.type==="draft-head-conflict"||e.type==="branch-head-conflict"?new u(`Your draft of ${t} moved while it was being rebased, so nothing was rebased.`,{exitCode:b.Conflict,type:e.type,requestId:e.requestId,details:e.details,hint:"Run 'modeldesk draft status', then rebase again.",hosted:{hint:n=>`Call ${n("draft status")}, then rebase again.`}}):e},zP=e=>[`Rebased your draft of ${se(e.resource)} onto ${e.draft.baselineCommitId}; it holds ${P(e.draft.changeCount,"change")}.`,...e.dropped.length>0?["Dropped:",...e.dropped.map(t=>` ${t.commitId}${Tb(t.requestId)} ${y(t.message??"")}`.trimEnd())]:[],...e.closureChanged?["The branch changed the model's dependencies meanwhile."]:[],...e.schemaChanged?["The branch changed the model's metamodel pin meanwhile; re-read its schema."]:[]].join(`
227
+ `),Ob=D({path:["draft","rebase"],effect:"stage",escalate:{flag:"drop",to:"unstage"},summary:"Move your draft onto the branch head",description:"Replays every staged change onto the current branch head and moves your draft there, as a commit needs once the branch has moved past its baseline. Nothing is left out unless --drop names it. A change the branch head refuses swaps nothing: the command prints each refused change (its id, request id, action types and errors) and exits 5; correct the change, or rebase again with --drop <id>. On success it reports the dropped changes and whether the branch changed the model's dependencies or metamodel pin meanwhile.",positionals:[Me],flags:{drop:{type:{list:"string"},placeholder:"change-id",description:"A staged change to leave out, by the id a conflict report gives it."}},examples:["modeldesk draft rebase <model>","modeldesk draft rebase <model> --drop <change-id> --json"],mcp:{name:"draft_rebase",description:"Replays your draft's staged changes onto the branch's current head and moves the draft there, which a commit needs once draft_status reports the branch moved past the baseline. A change the new head refuses moves nothing: the error lists each refused change with its errors. Correct and re-stage your change, or rebase again with drop naming the change ids to leave out (your own only)."},resultSchema:xb.draftRebase,run:async e=>X(async()=>{let t=await Ne(e),n=se(t.ref),r=await t.read();if(r===void 0)throw new u(`You hold no draft of ${n}, so there is nothing to rebase.`);let{drop:s}=e.flags;s.length>0&&await qe(e,t,r,{scope:{kind:"ids",ids:s},action:`Dropping ${P(s.length,"staged change")} from your draft of ${n}`,anySurface:!1,override:"ask them to run 'modeldesk draft rebase --drop' from a plain shell."});let o=i=>{i===!0&&t.ref.kind==="model"&&e.content.schemaChanged(t.ref.id)};try{let i=await t.rebase({draftHeadId:r.headCommitId,...s.length>0?{drop:s}:{}});return o(i.schemaChanged),{result:{resource:t.ref,...i}}}catch(i){throw i instanceof u&&o(i.details.schemaChanged),YP(i,n)}}),render:zP,renderRefusal:e=>e.type==="rebase-conflict"?KP(Ab(e)):void 0});var Mb={draftUndo:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},resource:{type:"object",properties:{kind:{type:"string",description:'One of "dataset", "model".'},id:{type:"string"},name:{type:"string"}}},undone:{type:"string",description:"The staged change that was undone: the draft head before the undo."},draft:{type:"object",properties:{id:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"}},description:"The draft after the undo: its head, and how many changes it still holds."}},required:["schemaVersion","resource","undone","draft"]}};var Nb=D({path:["draft","undo"],effect:"unstage",summary:"Undo the last change staged in your draft",description:"Takes the last staged change back out of your draft, whichever surface staged it, guarded by the head this command read: a change staged in between is not undone in its place. Undo never goes below the branch commit the draft started from, and there is no redo: stage the change again instead. A draft with nothing staged, or no draft, exits 1. Under an agent host a last change made outside an agent session (in the app) is left to a person (exit 6) unless --any-surface.",positionals:[Me],flags:nr,examples:["modeldesk draft undo <model>"],mcp:{name:"draft_undo",description:"Takes the last staged change back out of your draft. It undoes only a change your own session staged: a change the person or another session made is refused, and you leave it to them. There is no redo: stage the change again instead."},resultSchema:Mb.draftUndo,run:async e=>X(async()=>{let t=await Ne(e),n=await t.read();if(n===void 0)throw new u(`You hold no draft of ${se(t.ref)}, so there is nothing to undo.`);await qe(e,t,n,{scope:{kind:"last"},action:`Undoing the last change of your draft of ${se(t.ref)}`,anySurface:e.flags["any-surface"],override:"pass --any-surface only when they asked for it."});try{let r=await t.undo(n.headCommitId);return{result:{resource:t.ref,undone:n.headCommitId,draft:{id:n.id,headCommitId:r.headCommitId,changeCount:r.changeCount??n.changeCount-1}}}}catch(r){throw r instanceof u&&r.type==="nothing-to-undo"?new u(`Your draft of ${se(t.ref)} holds no staged change to undo.`,{type:r.type,details:r.details}):r instanceof u&&r.type==="draft-head-conflict"?new u(`Your draft of ${se(t.ref)} moved after this command read it, so nothing was undone.`,{exitCode:b.Conflict,type:r.type,details:r.details,hint:"Run 'modeldesk draft status' and undo again if you still mean to.",hosted:{hint:s=>`Call ${s("draft status")} and undo again if you still mean to.`}}):r}}),render:e=>`Undid the last staged change (${e.undone}) of your draft of ${se(e.resource)}; ${P(e.draft.changeCount,"change")} remain${e.draft.changeCount===1?"s":""}.`});var XP={minimum:-2147483648,maximum:2147483647},QP={minimum:Number.MIN_SAFE_INTEGER,maximum:Number.MAX_SAFE_INTEGER},Pb=34028234663852886e22,ZP={minimum:-Pb,maximum:Pb},Lb=new Set(["true","false"]),eL=/^-?\d+$/,tL=/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/,nL=/^-?\d+(\.\d+)?$/,rL=/^(\d{4})-(\d{2})-(\d{2})$/,sL=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/,oL=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,iL=/^(?:[a-z][a-z0-9+.-]*:\/\/|urn:)[^\s<>"{}|\\^`]+$/i,Dr=e=>({value:e}),Jt=(e,t,n={})=>({problem:{code:e,expected:t,...n}}),_b=({minimum:e,maximum:t})=>e===void 0||t===void 0?{...e!==void 0&&{minimum:e},...t!==void 0&&{maximum:t}}:e===0&&t===0?{}:t<e?{minimum:e}:{minimum:e,maximum:t},aL=(e,{minimum:t,maximum:n})=>t!==void 0&&n!==void 0?`${e} from ${t} to ${n}`:t!==void 0?`${e} of at least ${t}`:`${e} of at most ${n}`,jb=(e,t,...n)=>{for(let r of n)if(r.minimum!==void 0&&e<r.minimum||r.maximum!==void 0&&e>r.maximum)return Jt("out-of-range",aL(t,r),r);return Dr(e)},dL=(e,t)=>eL.test(e)?jb(Number(e),"a whole number",t.format==="INT64"?QP:XP,_b(t)):Jt("invalid-value","a whole number"),lL=(e,t)=>{let n=Number(e);return!tL.test(e)||!Number.isFinite(n)?Jt("invalid-value","a number, such as 2.5 or 1e-3"):jb(n,"a number",t.format==="FLOAT"?ZP:{},_b(t))},cL=e=>e%4===0&&(e%100!==0||e%400===0),mL=[31,28,31,30,31,30,31,31,30,31,30,31],Fb=(e,t,n)=>t>=1&&t<=12&&n>=1&&n<=(t===2&&cL(e)?29:mL[t-1]),fL=e=>{let t=rL.exec(e);return t!==null&&Fb(Number(t[1]),Number(t[2]),Number(t[3]))},pL=e=>{let t=sL.exec(e);if(t===null)return!1;let[n,r,s,o,i,a]=t.slice(1,7).map(Number),d=t[7]===void 0?0:Number(t[7]),l=t[8]===void 0?0:Number(t[8]);return Fb(n,r,s)&&o<=23&&i<=59&&a<=59&&d<=23&&l<=59},uL=e=>{if(!iL.test(e))return Jt("invalid-value","an absolute IRI, such as https://example.org/def#Term or urn:example:term");let t=Math.max(e.lastIndexOf("#"),e.lastIndexOf("/"),e.lastIndexOf(":"))+1,n=e.slice(0,t),r=e.slice(t);return Dr(r===""?{namespace:n}:{namespace:n,localName:r})},Db={expected:"a date-time written YYYY-MM-DDThh:mm:ss with a Z or \xB1hh:mm offset (RFC 3339)",test:pL},hL=new Map([["date",{expected:"a date written YYYY-MM-DD",test:fL}],["date-time",Db],["datetime",Db],["uuid",{expected:"a UUID",test:e=>oL.test(e)}]]),gL=(e,t)=>{if(t.format==="iri")return uL(e);if(t.enum&&t.enum.length>0&&!t.enum.includes(e))return Jt("not-in-enum",`one of ${t.enum.join(", ")}`,{validValues:[...t.enum]});let n=t.format===void 0?void 0:hL.get(t.format);return n&&!n.test(e)?Jt("invalid-value",n.expected):Dr(e)},yL=e=>Dr(e==="true"||e==="false"?e==="true":nL.test(e)&&String(Number(e))===e?Number(e):e),qb=(e,t)=>{switch(t?.type){case void 0:case"any":return yL(e);case"boolean":return Lb.has(e)?Dr(e==="true"):Jt("invalid-value","true or false",{validValues:[...Lb]});case"integer":return dL(e,t);case"number":return lL(e,t);case"string":return gL(e,t);case"object":return Jt("structured-value","a structured value, given as JSON with --json-value")}};var ea=class extends u{errors;constructor(t,n=[]){let r=t.length>1?` (and ${t.length-1} more)`:"",s=t.map((o,i)=>({...o,message:n[i]??o.message}));super(`${t[0].message}${r}`,{exitCode:b.Validation,details:{errors:t},...n.some(o=>o!==void 0)?{hosted:{reason:`${s[0].message}${r}`,details:{errors:s}}}:{}}),this.name="CoercionRefusedError",this.errors=t}},wL={"structured-value":"a structured value, given as JSON in jsonValue"},bL=/^[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})*$/,Wb=-1,kL=e=>e.slice(e.lastIndexOf(":")+1),EL=(e,t)=>{let n=new Map,r=new Set;for(let s of[e,...t]){for(let o of s.attributes??[])!n.has(o.name)&&!r.has(o.name)&&n.set(o.name,o);for(let o of s.relations??[])n.has(o.name)||r.add(o.name)}return{typeName:e.name,attributes:n,relations:r}},CL=e=>[...e.attributes.values()].filter(t=>!t.derived).map(t=>t.name),Bb=(e,t,n)=>e.flatMap(r=>{let s=r.indexOf("=");if(s<=0){let o=t==="json"?"<attribute>=<json>":"<attribute>=<value>";return n(s<0?r:"","malformed-assignment",`'${r}' is not an assignment; write ${o}.`,{value:r}),[]}return[{attribute:r.slice(0,s),text:r.slice(s+1),form:t}]}),vL=(e,t,n)=>{let{typeName:r,attributes:s,relations:o}=e,i=t.toLowerCase(),a=[...s.keys(),...o],d=a.includes(t)?[t]:a.filter(m=>m.toLowerCase()===i||kL(m).toLowerCase()===i);if(d.length===0){let m=CL(e);n(t,"unknown-attribute",m.length>0?`${r} has no attribute '${t}'. Its attributes: ${m.join(", ")}.`:`${r} has no attribute '${t}', nor any attribute to set.`,{validValues:m});return}if(d.length>1){n(t,"ambiguous-attribute",`'${t}' names ${d.length} properties of ${r} (${d.join(", ")}); pass the full name.`,{validValues:d});return}let[l]=d,c=s.get(l);if(c===void 0){n(t,"relation-not-attribute",`'${l}' is a relation of ${r}, not an attribute; relate its targets with 'el relate'.`,{property:l});return}if(c.derived){n(t,"derived-attribute",`'${l}' is derived: ${r} computes it on read, so it is never written.`,{property:l});return}return c},Hb=e=>typeof e=="object"&&e!==null&&"lang"in e&&typeof e.lang=="string"?e.lang:null,Ub=(e,t)=>(e??"").toLowerCase()===(t??"").toLowerCase(),RL=e=>e.map(Hb).filter((t,n,r)=>r.findIndex(s=>Ub(s,t))===n),SL=(e,t,n,r,s)=>{let o=e.attribute.name;if(r.lang!==void 0){if(bL.test(r.lang))return{lang:r.lang};s(e.given,"invalid-language",`--lang '${r.lang}' is not a language tag, such as nl or en-GB.`,{property:o,value:r.lang},`'lang' '${r.lang}' is not a language tag, such as nl or en-GB.`);return}let i=RL(n);if(i.length===1&&(i[0]!==null||t.optional))return{lang:i[0]};if(i.length===0&&t.optional)return{lang:null};let a=i.filter(l=>l!==null),d=i.length>1?`holds values in ${i.map(l=>l??"no language").join(", ")}`:"takes language-tagged strings";s(e.given,"language-required",`'${o}' ${d}; pass --lang to say which language to write.`,{property:o,...a.length>0&&{validValues:a}},`'${o}' ${d}; give lang to say which language to write.`)},IL=(e,t,n,r)=>{let s=e.attribute.name,o=n.current?.[s]??[],i=SL(e,t,o,n,r);if(i===void 0)return e.assignments.map(({text:d})=>d);let a=e.assignments.map(({text:d})=>({lang:i.lang,value:d}));return t.uniqueLang&&i.lang!==null&&a.length>1&&r(e.given,"duplicate-language",`'${s}' takes one value per language, and ${a.length} are given in '${i.lang}'.`,{property:s}),[...o.filter(d=>!Ub(Hb(d),i.lang)),...a]},$L=(e,t)=>e.assignments.flatMap(({attribute:n,text:r})=>{try{return[JSON.parse(r)]}catch{return t(n,"invalid-json",`The --json-value of '${n}' is not valid JSON: '${r}'.`,{property:e.attribute.name,value:r},`The jsonValue of '${n}' is not valid JSON: '${r}'.`),[]}}),xL=(e,t,n)=>{let{attribute:r,assignments:s}=e,o=r.name,i=r.schema;if(s.some(({form:d})=>d==="json"))return $L(e,n);for(let{attribute:d}of s.filter(({text:l})=>l===""))n(d,"empty-value",`'${o}' is given an empty value; unset the attribute to remove its values.`,{property:o,value:""});let a=s.filter(({text:d})=>d!=="");return i?.type==="string"&&i.lang?IL({...e,assignments:a},i.lang,t,n):a.map(({attribute:d,text:l})=>{let c=qb(l,i);if("problem"in c){let{code:m,expected:f,...h}=c.problem,p=wL[m];n(d,m,`'${o}' takes ${f}, not '${l}'.`,{property:o,value:l,...h},p===void 0?void 0:`'${o}' takes ${p}, not '${l}'.`)}return"value"in c?c.value:l})},Fn=(e,t,n={})=>{let r=[],s=[],o=(m,f,h,p={},g=void 0)=>{r.push({attribute:m,code:f,message:h,...p}),s.push(g)},i=EL(t,n.traits??[]),a=[...Bb(e.values??[],"value",o),...Bb(e.json??[],"json",o)],d=new Map,l=new Map;for(let m of a){d.has(m.attribute)||d.set(m.attribute,vL(i,m.attribute,o));let f=d.get(m.attribute);if(f!==void 0){let h=l.get(f.name)??{attribute:f,given:m.attribute,assignments:[]};h.assignments.push(m),l.set(f.name,h)}}let c={};for(let[m,f]of l){if(new Set(f.assignments.map(({form:g})=>g)).size>1){o(f.given,"mixed-forms",`'${m}' is given both as ${m}=<value> and with --json-value; give all of its values one way.`,{property:m},`'${m}' is given both as ${m}=<value> and in jsonValue; give all of its values one way.`);continue}let h=xL(f,n,o),p=f.attribute.multiplicity.max??Wb;p!==Wb&&h.length>p&&o(f.given,"too-many-values",`'${m}' takes at most ${P(p,"value")}, and this assignment leaves it with ${h.length}.`,{property:m,maximum:p}),c[m]=h}if(r.length>0)throw new ea(r,s);return c};var Xt="modeldesk el bulk --help",im=["equalTo","empty","notEmpty","contains","greaterThan","lessThan"],TL={"=":"equalTo","~":"contains",">":"greaterThan","<":"lessThan"},AL={empty:"empty","not-empty":"notEmpty"},OL=/^([^=~<>]+)([=~<>])(.*)$/s,ML=/^(.+):(empty|not-empty)$/,NL="type=<T>[,<T>\u2026], <attr>=<value>, <attr>~<text>, <attr>><n>, <attr><<n>, <attr>:empty or <attr>:not-empty",PL=e=>{let t;try{t=JSON.parse(e)}catch(s){throw I(`--where is not valid JSON (${s.message}).`,Xt,{reason:`'where' is not valid JSON (${s.message}).`})}let{type:n,conditions:r}=t??{};if(n!==void 0&&!(Array.isArray(n)&&n.every(s=>typeof s=="string")))throw I('--where: "type" is a list of type names.',Xt,{reason:`'where': "type" is a list of type names.`});if(r!==void 0&&!Array.isArray(r))throw I('--where: "conditions" is a list of {attribute, operator, value}.',Xt,{reason:`'where': "conditions" is a list of {attribute, operator, value}.`});for(let s of r??[])if(typeof s?.attribute!="string"||!im.includes(s.operator))throw I(`--where: every condition names an "attribute" and an "operator" (${im.join(", ")}).`,Xt,{reason:`'where': every condition names an "attribute" and an "operator" (${im.join(", ")}).`});return{...n===void 0?{}:{type:n},...r===void 0?{}:{conditions:r}}},LL=e=>{let t=OL.exec(e);if(t){let[,r,s,o]=t;if(r==="type"&&s==="="){let i=o.split(",").map(a=>a.trim()).filter(a=>a!=="");if(i.length===0)throw I(`'${e}' names no type.`,Xt);return{type:i}}return{condition:{attribute:r,operator:TL[s],value:o}}}let n=ML.exec(e);if(n)return{condition:{attribute:n[1],operator:AL[n[2]]}};throw I(`'${e}' is not a criterion; write one of ${NL}.`,Xt)},Vb=e=>{if(e.some(r=>r.trimStart().startsWith("{"))){if(e.length>1)throw I("--where as JSON holds the whole selection; give it once, without other clauses.",Xt,{reason:"'where' as JSON holds the whole selection; give it once, without other clauses."});return PL(e[0])}let t,n=[];for(let r of e){let s=LL(r);if("type"in s){if(t!==void 0)throw I("Name every type in one type= clause (type=A,B); two would both have to hold.",Xt);t=s.type}else n.push(s.condition)}return{...t?{type:t}:{},...n.length>0?{conditions:n}:{}}},ta=e=>{if(e!==null&&typeof e=="object"){if("value"in e)return String(e.value);if("namespace"in e||"localName"in e){let{namespace:t,localName:n}=e;return`${t??""}${n??""}`}return JSON.stringify(e)}return String(e)},DL=e=>e!=null&&e!=="",_L=(e,t)=>{let n=t.value===void 0?"":ta(t.value);switch(t.operator){case"empty":return e.length===0;case"notEmpty":return e.some(DL);case"equalTo":return e.some(r=>ta(r)===n);case"contains":return e.some(r=>ta(r).toLowerCase().includes(n.toLowerCase()));case"greaterThan":case"lessThan":{let r=Number(n);return n.trim()!==""&&!Number.isNaN(r)&&e.some(s=>{let o=Number(ta(s));return!Number.isNaN(o)&&(t.operator==="greaterThan"?o>r:o<r)})}}},Gb=(e,t,n)=>n.types!==void 0&&!n.types.has(e.type)?!1:(t.conditions??[]).every(r=>{let s=n.attributeOf(e,r.attribute);return s!==void 0&&_L(e.attributes?.[s]??[],r)});var jL="@trait",Kb="@Root",FL="@element",ut=e=>({modelId:e.model.id,refId:pi(e)}),Qt=async(e,t,n)=>{let{type:r}=await e.models.schema(t.modelId,{ref:t.refId,type:n});if(r===void 0)throw new u(`The schema of this model describes no type '${n}'.`,{exitCode:b.NotFound});return r},Yb=async(e,t,n,r,s)=>{if((r.values?.length??0)+(r.json?.length??0)===0)return{};let o=(n.attributes?.[jL]??[]).filter(d=>typeof d=="string"),[i,...a]=await Promise.all([n.type,...o].map(d=>Qt(e,t,d)));return Fn(r,i,{lang:s,current:n.attributes,traits:a})},qs=async(e,t,n,r,s,o,i)=>{if(o!==void 0)return o;let a=n.element(r)?.type??Kb;if(a===Kb){let{root:m=[]}=await e.models.schema(t.modelId,{ref:t.refId});if(m.some(f=>(f.instantiableTypes??[f.type]).includes(s)))return FL;throw new u(`The model root holds no ${s}.`,{exitCode:b.Validation,hint:`Types the root holds: ${m.flatMap(f=>f.instantiableTypes??[f.type]).join(", ")||"none"}.`})}let{childSlots:d=[]}=await Qt(e,t,a),l=d.filter(m=>m.targetTypes.includes(s));if(l.length===1)return l[0].relation;if(l.length>1)throw I(`A ${a} holds a ${s} through ${l.map(m=>m.relation).join(", ")}; pass --relation to pick one.`,i,{reason:`A ${a} holds a ${s} through ${l.map(m=>m.relation).join(", ")}; give relation to pick one.`});let c=d.map(m=>`${m.relation} (${m.targetTypes.join(", ")})`).join("; ");throw new u(`A ${a} holds no ${s}.`,{exitCode:b.Validation,hint:d.length===0?`A ${a} holds no children at all.`:`What it holds: ${c}.`})},qL=e=>e.slice(e.lastIndexOf(":")+1),Ke=(e,t)=>{if(e.includes(t))return t;let n=t.toLowerCase(),r=e.filter(s=>s.toLowerCase()===n||qL(s).toLowerCase()===n);if(r.length>1)throw new u(`'${t}' names ${r.length} properties (${r.join(", ")}); pass the full name.`,{exitCode:b.Usage,details:{candidates:r}});return r[0]},na=e=>e.ownership==="OWNED"||e.ownership==="MULTI_OWNED";var zb={elBulk:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"What the selection read: your draft while it holds staged changes, else your working branch head."},criteria:{type:"object",properties:{type:{type:"array",items:{type:"string"}},conditions:{type:"array",items:{type:"object",properties:{attribute:{type:"string"},operator:{type:"string",description:'One of "contains", "empty", "equalTo", "greaterThan", "lessThan", "notEmpty".'},value:{description:"The value compared against; none for `empty` and `notEmpty`."}}}}}},elements:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string"},label:{type:"string"},path:{type:"string"},before:{type:"object",additionalProperties:{type:"array",items:{}},description:"The values of each written attribute before the update."},after:{type:"object",additionalProperties:{type:"array",items:{}},description:"The values of each written attribute after it."},changes:{type:"boolean",description:"False when the element already holds these values, so the update leaves it out. One of false, true."}}},description:"Every selected element in tree order, with what the update writes to it."},dryRun:{type:"boolean",description:"True for a dry run: the preview alone, nothing staged. One of false, true."},staged:{type:"boolean",description:"Whether a change was staged; false on a dry run and when no selected element would change. One of false, true."},message:{type:"string"},changeRequestId:{type:"string",description:"The staged change's request id, when one was sent."},alreadyStaged:{type:"boolean",description:"True when a change staged under the same request id was found in your draft and not staged again. One of false, true."},stagedCommitId:{type:"string"},draft:{properties:{id:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"}},description:"The draft the change sits in, when one was staged. May be null."},commit:{type:"object",properties:{recovered:{type:"boolean",description:"One of false, true."},next:{type:"string",description:"What a landing off main leaves the caller with."},url:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},commit:{type:"object",properties:{id:{type:"string"},message:{type:"string"},requestId:{type:"string",description:"The `commitRequestId` the landing was sent with."},createdAt:{type:"string"},actionTypes:{type:"array",items:{type:"string"},description:"A model commit's action types: the whole chain's."},rowsChanged:{type:"number",description:"A dataset commit's count of the rows it wrote or removed."}}}}},url:{type:"string"}},required:["schemaVersion","model","ref","criteria","elements","dryRun","staged","message","url"]}};var ra="modeldesk el bulk --help",Jb=100,BL="@trait",Xb=e=>(e.attributes?.[BL]??[]).filter(t=>typeof t=="string"),am=(e,t)=>e===t?!0:e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(e)!==Array.isArray(t)?!1:[...new Set([...Object.keys(e),...Object.keys(t)])].every(r=>am(e[r],t[r])),HL=(e,t)=>{let n=new Map;return r=>{let s=n.get(r);if(s!==void 0)return s;let o=Qt(e.api(),t,r);return n.set(r,o),o}},Qb=async(e,t,n,r)=>{let s=HL(e,ut(t)),o=n.type?new Set((await Promise.all(n.type.map(s))).flatMap(R=>R.instantiableTypes??[R.name])):void 0,i=zt(it(t.tree)).filter(R=>o===void 0||o.has(R.type)),a=i.map(R=>t.read.elements[R.id]),d=[...new Set(a.flatMap(R=>[R.type,...Xb(R)]))],l=new Map(await Promise.all(d.map(async R=>[R,await s(R)]))),c=R=>({type:l.get(R.type),traits:Xb(R).map($=>l.get($))}),m=R=>{let{type:$,traits:v}=c(R);return[$,...v].flatMap(T=>(T.attributes??[]).map(N=>N.name))},h=(n.conditions??[]).find(R=>!a.some($=>Ke(m($),R.attribute)!==void 0));if(h!==void 0&&a.length>0)throw new u(`No element type the selection reaches has an attribute '${h.attribute}'.`,{exitCode:b.Validation,hint:"Run 'modeldesk describe <model> <type>' to see a type's attributes.",hosted:{hint:R=>`Call ${R("describe")} with the model and a type to see its attributes.`}});let g=i.filter((R,$)=>Gb(a[$],n,{attributeOf:(v,T)=>Ke(m(v),T)})).map(R=>{let $=t.read.elements[R.id],{type:v,traits:T}=c($),N=Fn({values:r.set,json:r.json},v,{lang:r.lang,current:$.attributes,traits:T});for(let S of r.unset){let x=Ke(m($),S);if(x===void 0)throw new u(`A ${$.type} has no attribute '${S}' to unset.`,{exitCode:b.Validation,details:{elementId:$.id}});if(x in N)throw I(`'${x}' is both set and unset.`,ra);N[x]=[]}let E=Object.fromEntries(Object.keys(N).map(S=>[S,$.attributes?.[S]??[]]));return{id:R.id,type:R.type,...R.label===void 0?{}:{label:R.label},path:R.path,before:E,after:N,changes:Object.keys(N).some(S=>!am(E[S],N[S]))}}),w=g.filter(R=>R.changes),C=w.every(R=>am(R.after,w[0].after))&&w.length>0?{elementIds:w.map(R=>R.id),attributes:w[0].after}:{updates:w.map(R=>({elementId:R.id,attributes:R.after}))};return{rows:g,update:C}},UL=e=>y(typeof e=="string"?e:JSON.stringify(e)),Zb=e=>e.length===0?"(none)":e.map(UL).join(", "),VL=e=>e.dryRun?"Dry run: nothing was staged.":e.staged?`Staged as one change in your draft (${P(e.draft?.changeCount??0,"change")}): ${y(e.message)}`:"Nothing was staged: no selected element changes.",GL=e=>{let t=e.elements.filter(s=>s.changes).length,n=e.elements.slice(0,Jb).flatMap(s=>[` ${y(s.path)} (${s.type}) ${s.id}${s.changes?"":" unchanged"}`,...Object.keys(s.after).map(o=>` ${o}: ${Zb(s.before[o])} -> ${Zb(s.after[o])}`)]),r=e.elements.length-Jb;return[Ie(e.ref,e.model),`Selected ${P(e.elements.length,"element")}, of which ${t} change:`,...n,...r>0?[` \u2026 and ${r} more (pass --json for every one).`]:[],VL(e),`url: ${e.url}`,...e.commit?Dn(e.commit):[]].join(`
228
+ `)},ek=D({path:["el","bulk"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage one update of every element the criteria select",description:`Selects elements by --where and stages one bulk update writing the same attribute values to each, as the app's bulk update does. Each --where clause must hold: type=<T>[,<T>\u2026] (subtypes and trait appliers included), <attr>=<value>, <attr>~<text> (contains, ignoring case), <attr>><n>, <attr><<n>, <attr>:empty, <attr>:not-empty. A --where starting with { is the app's criteria as JSON, and stands alone. Conditions read stored values only, not defaults. --set values are typed by each element's schema as in 'el set'; --unset empties an attribute. --dry-run lists every selected element with its values before and after and stages nothing. ${Le}`,positionals:[_(me)],flags:{where:{type:{list:"string"},required:!0,placeholder:"criterion",description:"A criterion every selected element meets, or the app's criteria as JSON."},set:{type:{list:"string"},placeholder:"attr=value",description:"A value to write, typed by the schema."},"json-value":{type:{list:"string"},placeholder:"attr=json",description:"A value to write given as JSON, written as it is."},unset:{type:{list:"string"},placeholder:"attr",description:"An attribute to empty."},lang:{type:"string",placeholder:"tag",description:"The language of the language-tagged values given."},...ve},dryRun:!0,examples:['modeldesk el bulk <model> --where type=ElementType --where notation:empty --set notation=uml -m "Default notation" --dry-run',`modeldesk el bulk <model> --where '{"type":["ElementType"],"conditions":[{"attribute":"notation","operator":"empty"}]}' --set notation=uml -m "Default notation"`],mcp:{name:"bulk_update",description:"Stages one bulk update that writes the same attribute values to every element the criteria select, as one change with message. Each where clause must hold: type=<T>[,<T>...] (subtypes included), <attr>=<value>, <attr>~<text> (contains, ignoring case), <attr>><n>, <attr><<n>, <attr>:empty, <attr>:not-empty; or the app's criteria as one JSON object. set writes attr=value typed by each element's schema, jsonValue attr=<json> a structured value, unset empties an attribute. Run it with dryRun: true first: that lists every selected element before and after and stages nothing. For edits to a few named elements use stage_changes."},resultSchema:zb.elBulk,run:async e=>X(async()=>{let{flags:t}=e,n=Vb(t.where),r={set:t.set,json:t["json-value"],unset:t.unset,lang:t.lang};if(r.set.length+r.json.length+r.unset.length===0)throw I("Say what to write: --set attr=value, --json-value attr=json or --unset attr.",ra,{reason:"Say what to write: set attr=value, jsonValue attr=json or unset attr."});let s=e.dryRun;if(s&&t.commit)throw I("--commit has nothing to commit under --dry-run, which stages nothing.",ra);if(t["with-staged"]&&!t.commit)throw I("--with-staged goes with --commit.",ra);let o=s?await lt(e,e.args.model):await _s(e),i=o.model.id,a=await Qb(e,o,n,r),d={model:o.model,ref:re(o.resolved),criteria:n,elements:a.rows,dryRun:s,staged:!1,message:t.message,url:e.webUrl({kind:"model",modelId:i})};if(s)return{result:d};if(a.rows.length===0)throw new u(`The criteria select no element of ${o.model.name}, so nothing was staged.`,{hint:"Preview a selection with --dry-run.",hosted:{hint:"Preview a selection with dryRun: true."}});let l=()=>new u(`No selected element of ${o.model.name} changes, so nothing was staged or committed.`,{type:"nothing-to-commit"});if(!a.rows.some(h=>h.changes)){if(t.commit)throw l();return{result:d}}let c=await Ns(e,o,async h=>(a=h===o?a:await Qb(e,h,n,r),{actions:a.rows.some(p=>p.changes)?[{type:"ELEMENT_BULK_UPDATE",update:a.update}]:[],ids:{},resendable:!1}),{message:t.message,requestId:t["request-id"]}),m=Ln(c.staged);if(t.commit&&!m)throw l();let[f]=c.staged.chunks;return{result:{...d,ref:Ls(c),elements:a.rows,staged:m,changeRequestId:c.changeRequestId,...f?.alreadyStaged?{alreadyStaged:!0,stagedCommitId:f.commitId}:{},draft:Ps(c),...t.commit?{commit:await Ds(e,c)}:{}}}}),render:GL});var _r=e=>{let t=new Set(Object.keys(e.metamodel?.elementTypes??{}));for(let n of e.metamodelExtensions??[])Object.keys(n.elementTypes??{}).forEach(r=>t.add(r));return Object.values(e.elements).forEach(n=>t.add(n.type)),[...t].sort()},KL=e=>e.slice(e.lastIndexOf(":")+1),dm=(e,t)=>{if(e.includes(t))return t;let n=t.toLowerCase(),r=e.filter(s=>s.toLowerCase()===n||KL(s).toLowerCase()===n);if(r.length===0)throw new u(`No element type '${t}' in this model's metamodel.`,{exitCode:b.NotFound});if(r.length>1)throw new u(`'${t}' names ${r.length} element types; pass the full name.`,{exitCode:b.Usage,details:{candidates:r}});return r[0]},sa=(e,t,n)=>{let r=dm(e,t);if(In(r)&&!n)throw I(`'${r}' is an internal type; pass --internal to include internal elements.`,void 0,{reason:`'${r}' is an internal type; set internal to include internal elements.`});return r};import{readFileSync as YL}from"node:fs";import{resolve as zL}from"node:path";var tk=(e,t)=>{try{return JSON.parse(YL(zL(e,t),"utf8"))}catch(n){throw new u(`Could not read the element in ${t} (${n.message}).`,{exitCode:b.Usage})}};var lm="new",qn="modeldesk el create --help",JL=e=>{let t=e.indexOf("=");if(t<=0||t===e.length-1)throw I(`'${e}' is not a relation to set; write --relate <relation>=<target>.`,qn,{reason:`'${e}' is not a relation to set; write <relation>=<target>.`});return[e.slice(0,t),e.slice(t+1)]},sk=["key","type","attributes","relations","children"],ok=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))return[];let{children:n,...r}=e,s=Object.keys(r).filter(i=>!sk.includes(i)).map(i=>`${t}${i}`),o=n!==null&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).flatMap(([i,a])=>Array.isArray(a)?a.flatMap((d,l)=>ok(d,`${t}children.${i}[${l}].`)):[]):[];return[...s,...o]},XL=(e,t)=>{let n=e;if(n===null||typeof n!="object"||Array.isArray(n)||typeof n.type!="string")throw new u(`${t} holds no element: write an object with its "type", and "attributes", "relations" and "children" as needed.`,{exitCode:b.Usage});let r=ok(n,"");if(r.length>0){let s=sk.map(o=>`"${o}"`).join(", ");throw new u(`${t} names what an element does not have: ${r.join(", ")}. An element takes ${s}.`,{exitCode:b.Validation,details:{unknownKeys:r}})}return n},nk=(e,t)=>{let n=[...t.type===void 0?[]:["--type"],...t["json-value"].length===0?[]:["--json-value"],...t.lang===void 0?[]:["--lang"],...t.relate.length===0?[]:["--relate"]];if(e.length>0)throw I(`--from holds the whole element, so it takes no attr=value ('${e[0]}').`,qn);if(n.length>0)throw I(`--from holds the whole element, so it takes no ${n.join(", ")}.`,qn)},QL=(e,t,n,r)=>{let s=(n.relations??[]).map(i=>i.name),o={};for(let i of e){let[a,d]=JL(i),l=Ke(s,a);if(l===void 0)throw new u(`A ${t} has no relation '${a}'.`,{exitCode:b.Validation,hint:`Its relations: ${s.join(", ")||"none"}.`});let c=n.relations?.find(h=>h.name===l),m=c!==void 0&&na(c),f=o[l]?.["@@"]??[];o[l]={"@@":[...f,{id:he(r,d),owned:m}]}}return o},rk=async(e,t,n)=>{let{flags:r}=e,s=e.api(),{tree:o}=t,i=gi(o,e.args.parent),a=ut(t);if(n!==void 0){let h=await qs(s,a,o,i,n.type,r.relation,qn),p=n.key??lm;return{edits:[{kind:"create",parent:{id:i},relation:h,element:{...n,key:p}}],subject:{key:p}}}if(r.type===void 0)throw I("Pass the --type of the new element, or --from with a file describing it.",qn,{reason:"Give the new element's type."});let d=dm(_r(t.read),r.type),[l,c]=await Promise.all([Qt(s,a,d),qs(s,a,o,i,d,r.relation,qn)]),m=Fn({values:e.args.values,json:r["json-value"]},l,{lang:r.lang}),f=QL(r.relate,d,l,o);return{edits:[{kind:"create",parent:{id:i},relation:c,element:{key:lm,type:d,...Object.keys(m).length>0?{attributes:m}:{},...Object.keys(f).length>0?{relations:f}:{}}}],subject:{key:lm}}},ik=D({path:["el","create"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a new element under a parent",description:`Stages one new element under <parent> (an id, a label path, or / for the model root), owned through --relation, or through the one child relation of the parent's type that admits --type. Attribute values are checked and typed by the type's schema (see 'modeldesk describe'): attr=value as on 'el set' (repeat a name for several values), --json-value for a structured value, --lang for the language of a language-tagged one. --relate rel=target adds a reference. --from <file> stages a whole subtree in one change instead: a JSON element {"type", "attributes", "relations", "children": {relation: [elements]}}, written as it is. The element's id is minted by the CLI and reported. ${Le}`,positionals:[_(me),{name:"parent",type:{address:"element"},required:!0,description:"The parent's id, its label path from the model root, or / for the model root."},{name:"values",type:{list:"string"},description:"attr=value, once per value."}],flags:{type:{type:"string",placeholder:"type",description:"The new element's type (required unless --from).",toolDescription:"The new element's type; required."},relation:{type:"string",placeholder:"relation",description:"The parent's relation that owns it; needed only where the parent's type has several for the type."},"json-value":{type:{list:"string"},placeholder:"attr=json",description:"An attribute value given as JSON and written as it is."},lang:{type:"string",placeholder:"tag",description:"The language of the language-tagged values given."},relate:{type:{list:"string"},placeholder:"relation=target",description:"A reference to an existing element (id or label path), not owned by the new one.",elementEntries:!0},from:{type:"string",readsFile:!0,placeholder:"file",description:"A JSON file holding the element and the subtree it owns, staged as one change."},...ve},examples:['modeldesk el create <model> SHACL name=Shape --type ElementType -m "Add the Shape type"','modeldesk el create <model> / sh:deactivated=false --type sh:NodeShape -m "Add a shape"'],mcp:{name:"create",operationOf:"stage_changes",creates:!0,description:"Create an element of type under parent (an id, a label path, or / for the model root), with values as attr=value."},plan:(e,t)=>rk(e,t,void 0),prepare:async e=>{let{flags:t}=e;if(t.from!==void 0)return Hi(e),nk(e.args.values,t),tk(e.cwd,t.from)},run:async(e,t)=>{let{flags:n}=e;if(t===void 0&&n.from!==void 0)throw I(`--from ${n.from} was not read, so there is no element to stage.`,qn);let r;return t!==void 0&&(Hi(e),nk(e.args.values,n),r=XL(t,n.from??"The element given")),Ve(e,s=>rk(e,s,r))},render:Ge});var ak=async(e,t)=>{let{read:n,tree:r}=t,{flags:s}=e,o=he(r,e.args.element),i=gi(r,e.args["new-parent"]),a=await qs(e.api(),ut(t),r,i,n.elements[o].type,s.relation,"modeldesk el mv --help"),d;if(s["from-owner"]!==void 0){let l=he(r,s["from-owner"]),c=r.owners(o).filter(m=>m.id===l);if(c.length!==1)throw new u(c.length===0?`Element ${l} does not own element ${o}.`:`Element ${l} owns element ${o} through several relations.`,{exitCode:b.Validation});d={id:l,relation:c[0].relation}}return{edits:[{kind:"move",element:o,parent:{id:i},relation:a,...s.position===void 0?{}:{position:s.position},...d?{from:d}:{}}],subject:{id:o}}},dk=D({path:["el","mv"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage moving an element under another parent",description:`Moves the element, with everything it owns, under <new-parent> (an id, a label path, or / for the model root), through --relation or the one child relation of the new parent's type that admits it, at --position among the children there (from 0; last when left out). An element with several owners needs --from-owner to say which one it leaves. ${Le}`,positionals:[_(me),We("element"),{name:"new-parent",type:{address:"element"},required:!0,description:"The new parent's id, its label path, or / for the model root."}],flags:{relation:{type:"string",placeholder:"relation",description:"The new parent's relation to own it through, where its type has several for the element."},position:{type:"number",placeholder:"n",description:"Its place among the children there, from 0."},"from-owner":{type:{address:"element"},placeholder:"element",description:"The owner it leaves (id or label path), for an element several elements own."},...ve},examples:['modeldesk el mv <model> SHACL/NodeShape/severity SHACL/Shape -m "Severity applies to every shape"'],mcp:{name:"mv",operationOf:"stage_changes",description:"Move element, with what it owns, under newParent, at position among its children."},plan:ak,run:async e=>Ve(e,t=>ak(e,t)),render:Ge});var mk={name:"relation",type:"string",required:!0,description:"The relation's name (its canonical name, or a spelling differing in case or prefix)."},fk={name:"target",type:{address:"element"},required:!0,description:"The target's id, or its label path from the model root."},ZL=(e,t)=>{if(!na(e))return e.ownership==="MIXED"&&!t;if(t)throw I(`The relation '${e.name}' owns every target it holds, so --unowned does not apply.`,"modeldesk el relate --help",{reason:`The relation '${e.name}' owns every target it holds, so unowned does not apply.`});return!0},lk=async(e,t)=>{let{model:n,read:r,tree:s}=t,{flags:o}=e,i=e.api(),a=he(s,e.args.element),d=r.elements[a],l=(d.attributes?.["@trait"]??[]).filter(C=>typeof C=="string"),c=ut(t),f=(await Promise.all([d.type,...l].map(C=>Qt(i,c,C)))).flatMap(C=>C.relations??[]),h=Ke(f.map(C=>C.name),e.args.relation),p=f.find(C=>C.name===h);if(p===void 0)throw new u(`A ${d.type} has no relation '${e.args.relation}'.`,{exitCode:b.Validation,hint:`Its relations: ${[...new Set(f.map(C=>C.name))].join(", ")||"none"}.`});let g=ZL(p,o.unowned),{target:w}=e.args,k;if(o["target-model"]!==void 0){if(!Y(w))throw I("With --target-model, name the target by its id.","modeldesk el relate --help",{reason:"With targetModel, name the target by its id."});let C=await ce(e,o["target-model"].model).id(),R=w.toLowerCase();k=C===n.id?{id:R,owned:g}:{id:R,owned:g,modelId:C}}else k={id:he(s,w),owned:g};return{edits:[{kind:"relate",element:a,relation:p.name,target:k,...o.group===void 0?{}:{group:o.group}}],subject:{id:a}}},pk=D({path:["el","relate"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage adding a target to an element's relation",description:`Adds <target> to the element's <relation>, keeping the targets it already holds. Whether the target is owned follows the relation: a reference relation refers to it, an owning one adopts it, and one that holds both (MIXED) adopts it unless --unowned. A grouped relation needs --group. A target in another model is named by its id with --target-model. ${Le}`,positionals:[_(me),We("element"),mk,fk],flags:{unowned:{type:"boolean",description:"Refer to the target rather than own it, on a relation that does both."},group:{type:"string",placeholder:"group",description:"The group of a grouped relation the target joins."},"target-model":{type:{address:"model",slot:Ae},placeholder:"model",description:"The id of the model the target lives in, when it is not this one; the target is then an id."},...ve},examples:['modeldesk el relate <model> SHACL/NodeShape extends SHACL/Shape -m "NodeShape is a Shape"'],mcp:{name:"relate",operationOf:"stage_changes",description:"Add target to the relation of element."},plan:lk,run:async e=>Ve(e,t=>lk(e,t)),render:Ge}),ck=(e,{read:t,tree:n})=>{let r=he(n,e.args.element),s=Object.keys(t.elements[r].relations??{}),o=Ke(s,e.args.relation)??e.args.relation,{target:i}=e.args,a=Y(i)?i.toLowerCase():he(n,i);return{edits:[{kind:"unrelate",element:r,relation:o,target:a}],subject:{id:r}}},uk=D({path:["el","unrelate"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage removing a target from an element's relation",description:`Removes <target> from the element's <relation>, from whichever group holds it, keeping the other targets. A target in another model is named by its id. ${Le}`,positionals:[_(me),We("element"),mk,fk],flags:ve,examples:['modeldesk el unrelate <model> SHACL/NodeShape extends SHACL/Shape -m "NodeShape stands alone"'],mcp:{name:"unrelate",operationOf:"stage_changes",description:"Remove target from the relation of element."},plan:ck,run:async e=>Ve(e,t=>ck(e,t)),render:Ge});var hk=(e,{tree:t})=>{let n=he(t,e.args.element);return{edits:[{kind:"delete",element:n,recursive:e.flags.recursive}],subject:{id:n}}},gk=D({path:["el","rm"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the deletion of an element",description:"Deletes the element, and with it everything it owns that no other element owns too. An element that owns anything is refused (exit 4) unless --recursive says to delete what it owns with it. "+Le,positionals:[_(me),We("element")],flags:{recursive:{type:"boolean",description:"Delete what the element owns with it."},...ve},examples:['modeldesk el rm <model> SHACL/NodeShape/severity -m "Severity moved to Shape"'],mcp:{name:"rm",operationOf:"stage_changes",description:"Delete element, and what it owns with recursive: true."},plan:hk,run:async e=>Ve(e,t=>hk(e,t)),render:Ge});var yk=async(e,t)=>{let{read:n,tree:r}=t,{values:s}=e.args,o=e.flags["json-value"];if(s.length===0&&o.length===0)throw I("Name at least one attr=value to set.","modeldesk el set --help");let i=he(r,e.args.element),a=await Yb(e.api(),ut(t),n.elements[i],{values:s,json:o},e.flags.lang);return{edits:[{kind:"set",element:i,attributes:a}],subject:{id:i}}},bk=D({path:["el","set"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage new values for an element's attributes",description:`Replaces each named attribute's values with the ones given, typed by the attribute's declaration in the schema (see 'modeldesk describe'): true or false for a boolean, a number for a number, one of the listed values for an enum. Name an attribute again for several values. A language-tagged attribute is written in the --lang given (or the one language it already holds) and keeps its other languages. --json-value attr=<json> writes a structured value as it is. An unknown attribute exits 4 listing the valid ones. Relations are changed with 'el relate' and 'el unrelate'. ${Le}`,positionals:[_(me),We("element"),{name:"values",type:{list:"string"},description:"attr=value, once per value."}],flags:{"json-value":{type:{list:"string"},placeholder:"attr=json",description:"An attribute value given as JSON and written as it is."},lang:{type:"string",placeholder:"tag",description:"The language of the language-tagged values given."},...ve},examples:['modeldesk el set <model> SHACL/NodeShape abstract=true -m "NodeShape is only ever specialized"','modeldesk el set <model> <element> rdfs:label=Persoon --lang nl -m "Dutch label"'],mcp:{name:"set",operationOf:"stage_changes",description:"Replace the values of attributes of element, given in values as attr=value."},plan:yk,run:async e=>Ve(e,t=>yk(e,t)),render:Ge}),wk=(e,{read:t,tree:n})=>{let r=he(n,e.args.element),s=t.elements[r],o={attributes:Object.keys(s.attributes??{}),relations:Object.keys(s.relations??{})},i=[],a=[];for(let d of e.args.names){let l=Ke(o.attributes,d),c=l===void 0?Ke(o.relations,d):void 0;if(l!==void 0)i.push(l);else if(c!==void 0)a.push(c);else throw new u(`Element ${r} holds nothing under '${d}'.`,{exitCode:b.Validation,hint:`It holds: ${[...o.attributes,...o.relations].join(", ")||"nothing"}.`})}return{edits:[{kind:"unset",element:r,attributes:i,relations:a}],subject:{id:r}}},kk=D({path:["el","unset"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the removal of attribute or relation values",description:`Removes every value the element holds under each name given, an attribute or a relation (a relation with all of its targets; to remove one target use 'el unrelate'). A name the element holds nothing under exits 4 listing the names it does hold. ${Le}`,positionals:[_(me),We("element"),{name:"names",type:{list:"string"},required:!0,description:"An attribute or relation to empty."}],flags:ve,examples:['modeldesk el unset <model> SHACL/NodeShape alias -m "The alias was a typo"'],mcp:{name:"unset",operationOf:"stage_changes",description:"Remove every value element holds under each of names."},plan:wk,run:async e=>Ve(e,t=>wk(e,t)),render:Ge});var vk=(e,t)=>{let n=e.label(t),r=e.element(t)?.type;return{id:t,...n===void 0?{}:{label:n},...r===void 0?{}:{type:r}}},Ek=(e,t)=>t.map(n=>({...vk(e,n.id),relation:n.relation})),eD=(e,t,n)=>{let{id:r}=t,s=Object.fromEntries(Object.entries(t.relations??{}).map(([i,a])=>[i,Object.entries(a).flatMap(([d,l])=>l.map(c=>({...vk(e,c.id),owned:c.owned,...d==="@@"?{}:{group:d},...c.modelId?{modelId:c.modelId}:{}})))])),o=e.label(r);return{id:r,type:t.type,...o===void 0?{}:{label:o},...n.path===void 0?{}:{path:n.path},attributes:t.attributes??{},relations:s,owners:Ek(e,e.owners(r)),children:Ek(e,e.children(r)),url:n.url}},tD=e=>y(e!==null&&typeof e=="object"?JSON.stringify(e):String(e)),Ck=e=>{let t=e.label===void 0?"(no label)":y(e.label),n=e.type?` (${e.type})`:"";return`${t}${n}`},nD=e=>{let t=[["id:",e.id],["type:",e.type],...e.path===void 0?[]:[["path:",y(e.path)]],["url:",e.url]],n=Object.entries(e.attributes).map(([o,i])=>[`${o}:`,i.map(tD).join(", ")]),r=Object.entries(e.relations).flatMap(([o,i])=>[` ${o}:`,...F(i.map(a=>[Ck(a),a.id,[a.owned?"owned":"",a.group?`group ${a.group}`:"",a.modelId?`model ${a.modelId}`:""].filter(d=>d!=="").join(", ")]),{indent:" "})]),s=o=>o.length===0?[" none"]:F(o.map(i=>[Ck(i),i.id,`via ${i.relation}`]),{indent:" "});return[Ie(e.ref,e.model),e.label===void 0?"(no label)":y(e.label),...F(t,{indent:" "}),"Attributes:",...n.length===0?[" none"]:F(n,{indent:" "}),"Relations:",...r.length===0?[" none"]:r,"Owners:",...s(e.owners),"Children:",...s(e.children)].join(`
229
+ `)},Rk=D({path:["el","show"],effect:"read",summary:"Show one element of a model",description:"Shows an element's id, type, label, attribute values, relations (each target with its label), owners and children. Address the element by its id, or by its label path from the model root "+String.raw`(SHACL/NodeShape/severity; write a '/' inside a label as '\/'); a path must name exactly one element, `+"and passes through the platform's internal `@` elements only with --internal. Without a ref, reads your draft while it holds staged changes.",positionals:[_(vt),We("element")],flags:{...hr},examples:["modeldesk el show <model> SHACL/NodeShape/severity","modeldesk el show <model>@head SHACL/NodeShape/severity","modeldesk el show <model> <element> --json"],run:async e=>{let{model:t,ref:n,tree:r}=await gr(e,e.args.model,vt),{internal:s}=e.flags,o=he(r,e.args.element,{internal:s}),i=r.element(o);if(i===void 0)throw new u(`No element ${o} in ${t.name}.`,{exitCode:b.NotFound});let a=zt(it(r,{internal:s})).find(c=>c.id===o)?.path,d=e.webUrl({kind:"element",modelId:t.id,elementId:o});return{result:{model:t,ref:n,...eD(r,i,{path:a,url:d})}}},render:nD});var Zt="modeldesk metamodel list",oa=e=>`modeldesk metamodel extensions ${e}`,en=(e,t,n,r)=>{let s=e.find(o=>o.id.toLowerCase()===t);if(s===void 0)throw new u(`No ${n} has the id '${t}'.`,{exitCode:b.NotFound,hint:`Run '${r}' to see the ids.`,details:{candidates:e.map(o=>({id:o.id,name:o.name}))}});return s};var rD=["ID","NAME","RELEASE","ABSTRACT"],sD=["ID","NAME","RELEASE","COMPLETES"],Sk=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:"base"})||e.id.localeCompare(t.id),Ik=e=>y(e??""),$k=e=>e?"yes":"",xk=D({path:["metamodel","list"],effect:"read",summary:"List the metamodels a model can be written in",description:"Lists each metamodel with the id --metamodel takes, its name, the release @<release> takes, and whether it is abstract. An abstract metamodel needs an extension that completes it: run metamodel extensions <id>. Names are not unique, so a metamodel is addressed by its id. To read a metamodel as a model, a super-admin uses model list --kind metamodel.",listing:{},examples:["modeldesk metamodel list","modeldesk metamodel list --json"],run:async e=>{let{items:t}=await e.api().metamodels.list(),n=t.filter(s=>s.kind!=="DATA_SCHEMA").map(({id:s,name:o,fullName:i,standardVersion:a,abstract:d})=>({id:s,name:o,...i?{fullName:i}:{},...a?{standardVersion:a}:{},abstract:d===!0})).sort(Sk);return{result:await e.list(n)}},render:({items:e})=>e.length===0?"No metamodels.":F([rD,...e.map(t=>[t.id,y(t.name),Ik(t.standardVersion),$k(t.abstract)])]).join(`
230
+ `)}),Tk=D({path:["metamodel","extensions"],effect:"read",summary:"List the extensions of a metamodel",description:"Lists the extensions a model written in the metamodel can apply, each with the id --extension takes. COMPLETES marks an extension that completes an abstract metamodel; a new model on one needs such an extension. Names are not unique, so an extension is addressed by its id.",positionals:[{name:"metamodel",type:{address:"model",slot:og},required:!0,description:"The metamodel's id, from metamodel list."}],listing:{},examples:["modeldesk metamodel extensions <metamodel>","modeldesk metamodel extensions <metamodel> --json"],run:async e=>{let t=e.api(),{id:n,name:r}=en((await t.metamodels.list()).items,e.args.metamodel.model,"metamodel",Zt),{items:s}=await t.metamodelExtensions.list(n),o=s.map(({id:a,name:d,fullName:l,standardVersion:c,concretizes:m,dependsOnExtensions:f})=>({id:a,name:d,...l?{fullName:l}:{},...c?{standardVersion:c}:{},completes:m===!0,dependsOn:f??[]})).sort(Sk);return{result:{metamodel:{id:n,name:r},...await e.list(o)}}},render:({items:e})=>e.length===0?"No extensions.":F([sD,...e.map(t=>[t.id,y(t.name),Ik(t.standardVersion),$k(t.completes)])]).join(`
231
+ `)});var oD=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],tn=e=>{let t=e.orgs;return t!==null&&typeof t=="object"?Object.entries(t).map(([n,r])=>{let{name:s,seatAssignments:o}=r??{};return{id:n,...typeof s=="string"?{name:s}:{},seatAssignments:oD(o)}}):typeof e.mdsk_org=="string"?[{id:e.mdsk_org}]:[]},cm=e=>e.name?`${e.name} (${e.id})`:e.id,ia=e=>e.map(({id:t,name:n})=>({id:t,...n?{name:n}:{}})),iD=(e,t)=>e.seatAssignments===void 0||e.seatAssignments.some(n=>n.toLowerCase()===t.toLowerCase()),aD="me",Ws=(e,t)=>{let n=t.toLowerCase(),r=e.filter(s=>Y(t)?s.id.toLowerCase()===n:s.name?.toLowerCase()===n);if(r.length===1)return r[0];throw r.length>1?new u(`${r.length} of your organizations are named '${t}'; pass --owner with an id.`,{exitCode:b.Usage,details:{candidates:ia(r)},hosted:{reason:`${r.length} of your organizations are named '${t}'; give the owner by its id.`}}):new u(`You are not a member of an organization '${t}'.`,{exitCode:b.NotFound,hint:e.length===0?"Your credential names no organization.":`Your organizations: ${e.map(cm).join(", ")}.`,details:{candidates:ia(e)}})},mm=(e,t)=>{if(t===aD)throw new u("An import is owned by an organization in which you hold a seat for its metamodel, so --owner me does not apply.",{exitCode:b.Usage,hint:"Pass --owner <organization> with one of your organizations."});return Ws(e,t)},Ak=(e,t,n)=>{if(n!==void 0){let{id:s,name:o}=mm(e,n);return{id:s,...o?{name:o}:{},chosen:"owner-flag"}}let r=e.filter(s=>iD(s,t.id));if(r.length===1){let[{id:s,name:o}]=r;return{id:s,...o?{name:o}:{},chosen:"only-seated"}}throw r.length===0?new u(`None of your organizations gives you a seat for ${t.name}, and an import must be owned by one that does.`,{exitCode:b.Usage,hint:e.length===0?"Your credential names no organization.":`Pass --owner to choose one anyway (yours: ${e.map(cm).join(", ")}); the server checks the seat.`,details:{candidates:ia(e)}}):new u(`${r.length} of your organizations give you a seat for ${t.name}: ${r.map(cm).join(", ")}.`,{exitCode:b.Usage,hint:"Pass --owner <organization> to choose the owner.",details:{candidates:ia(r)}})};var Bs="modeldesk model create --help",dD=(e,t)=>{let n=tn(e);if(t==="me"){if(typeof e.sub!="string")throw I("This credential is no user, so --owner me names no one.",Bs);return{id:e.sub,type:"USER"}}if(t!==void 0){if(Y(t))return{id:t.toLowerCase(),type:"ORGANIZATION"};let{id:r,name:s}=Ws(n,t);return{id:r,type:"ORGANIZATION",...s?{name:s}:{}}}if(n.length===1){let[r]=n;return{id:r.id,type:"ORGANIZATION",...r.name?{name:r.name}:{}}}throw I(n.length===0?"You belong to no organization: pass --owner <organization>, or --owner me for a model of your own.":`You belong to ${n.length} organizations (${n.map(r=>r.name??r.id).join(", ")}); pass --owner <organization> to say which owns the model.`,Bs)},lD=async(e,t,n)=>{let r=(await e.metamodels.list()).items.filter(a=>a.kind!=="DATA_SCHEMA"),s=en(r,t.model,"metamodel",Zt),o=n.length>0?(await e.metamodelExtensions.list(s.id)).items:[],i=(a,d)=>{let l=mr(d);return{id:a.id,name:a.name,...l?{version:l}:{}}};return{metamodel:i(s,t),extensions:n.map(a=>i(en(o,a.model,`extension of ${s.name}`,oa(s.id)),a))}},cD=(e,t,n,r)=>{let s=r.filter(o=>o.version!==void 0);return{name:e,metamodelId:n.id,...n.version?{metamodelVersion:n.version}:{},...r.length>0?{metamodelExtensionIds:r.map(o=>o.id)}:{},...s.length>0?{metamodelExtensionVersions:Object.fromEntries(s.map(o=>[o.id,o.version]))}:{},owner:{id:t.id,type:t.type}}},Ok=async(e,t)=>{try{return await e()}catch(n){throw n instanceof u&&n.exitCode===b.Transient?new u(`${n.reason} The model may or may not have been created.`,{exitCode:b.Transient,type:n.type,requestId:n.requestId,details:n.details,hint:`Run 'modeldesk model list' and look for ${y(t)} before retrying: a creation carries no idempotency key, so a retry after one that landed creates a second model.`}):n}},Mk=e=>{let t=e.version?`@${e.version}`:"";return`${y(e.name)}${t}`},mD=e=>e?.length?` with ${e.map(Mk).join(", ")}`:"",fD=e=>e.metamodel?` on ${Mk(e.metamodel)}${mD(e.extensions)}`:" as a metamodel-model",pD=e=>{let{model:t}=e,n=fD(t),r=t.owner?`, owned by ${y(t.owner.name??t.owner.id)}`:"";return e.dryRun?`Would create ${y(t.name)}${n}${r}. Dry run: nothing was created.`:[`Created ${y(t.name)} (${t.id})${n}${r}.`,...e.url?[`url: ${e.url}`]:[]].join(`
232
+ `)},Nk=q({path:["model","create"],effect:"create",summary:"Create a model",description:"Creates a model written in --metamodel (its id from metamodel list, with @<release> to pin one; the latest stable release otherwise), with the --extension(s) given the same way (ids from metamodel extensions <metamodel>), owned by --owner (an organization of yours by name or id, or me) or by your one organization. An abstract metamodel needs an extension that completes it. The creation is committed directly; no draft is involved. --kind metamodel creates a metamodel-model instead, which belongs to the platform and takes a super-admin. --dry-run checks the ids and shows what would be created.",flags:{name:{type:"string",required:!0,placeholder:"name",description:"The new model's name."},metamodel:{type:{address:"model",slot:li},placeholder:"metamodel[@release]",description:"The metamodel's id, from metamodel list, at @<release> or else its latest stable release (required for a model)."},extension:{type:{list:{address:"model",slot:ci}},placeholder:"extension[@release]",description:"An extension's id, from metamodel extensions <metamodel>, at @<release> or else its latest stable release."},owner:{type:"string",placeholder:"organization|me",description:"Who owns it: an organization of yours, by name or id, or me; default your one organization."},kind:{type:{enum:["model","metamodel"]},default:"model",description:"model, or metamodel for a metamodel-model (super-admin)."},"standard-version":{type:"string",placeholder:"version",description:"A metamodel-model's standard version (such as 0.1.0)."}},dryRun:!0,examples:["modeldesk model create --name Shapes --metamodel <metamodel>","modeldesk model create --name Catalog --metamodel <metamodel>@1.2.0 --owner Acme --json"],run:async e=>{let{flags:t}=e,n=e.api(),{dryRun:r}=e.globals;if(t.kind==="metamodel"){if(t.metamodel!==void 0||t.owner!==void 0||t.extension.length>0)throw I("A metamodel-model is written in the meta-metamodel and owned by the platform: it takes no --metamodel, --extension or --owner.",Bs);if(!Kt(await n.accessTokenClaims()))throw new u("Creating a metamodel-model takes a super-admin.");let c={name:t.name,...t["standard-version"]?{standardVersion:t["standard-version"]}:{}};if(r)return{result:{model:{name:t.name,kind:"metamodel"},dryRun:r}};let m=await Ok(()=>n.metamodelModels.create(c),t.name);return{result:{model:{id:m.id,name:m.name,kind:"metamodel",owner:m.owner},dryRun:r,url:te(e.instance(),{kind:"model",modelId:m.id})}}}if(t["standard-version"]!==void 0)throw I("--standard-version belongs to a metamodel-model (--kind metamodel).",Bs);if(t.metamodel===void 0)throw I("Pass the --metamodel the model is written in.",Bs);let[s,{metamodel:o,extensions:i}]=await Promise.all([n.accessTokenClaims().then(c=>dD(c,t.owner)),lD(n,t.metamodel,t.extension)]),a={name:t.name,kind:"model",metamodel:o,...i.length>0?{extensions:i}:{},owner:s};if(r)return{result:{model:a,dryRun:r}};let d=await Ok(()=>n.models.create(cD(t.name,s,o,i)),t.name);return{result:{model:{...a,id:d.id,name:d.name,owner:d.owner},dryRun:r,url:te(e.instance(),{kind:"model",modelId:d.id})}}},render:pD});var fm=e=>{let t=e.owner?`, owned by ${y(e.owner.name??e.owner.id)}`:"";return`model ${y(e.name)} (${e.id})${t}`},Pk=q({path:["model","delete"],effect:"destroy",summary:"Delete a model",description:"Deletes the model with its content, history and releases. It restates which model that is and asks at a terminal; anywhere else it needs --yes. A model other models still depend on is refused (exit 5). --dry-run restates which model it would delete and deletes nothing; the server then checks no dependents. Under an agent host deleting a model is left to a person (exit 6).",positionals:[_(Ae)],dryRun:!0,examples:["modeldesk model delete <model> --dry-run","modeldesk model delete <model> --yes"],run:async e=>{let t=await ce(e,e.args.model.model).identity(),n={id:t.id,name:t.name,...t.owner?{owner:t.owner}:{},headCommitId:t.branch.head.id},r=fm(n);if(e.globals.dryRun)return{result:{model:n,deleted:!1,dryRun:!0}};e.print(`This deletes ${r}: its content, its history and its releases.
233
+ `),await ct(e,`Delete ${r}?`,`Deleting ${r}`);try{await e.api().models.delete(n.id)}catch(o){throw o instanceof u&&o.exitCode===b.Conflict?new u(`Other models depend on ${r}, so it was not deleted.`,{exitCode:b.Conflict,type:o.type,details:o.details,hint:"Run 'modeldesk model show' to see what depends on it."}):o}return{result:{model:n,deleted:!0,dryRun:!1}}},render:e=>e.dryRun?`Would delete ${fm(e.model)}. Dry run: nothing was deleted.`:`Deleted ${fm(e.model)}.`});import{createHash as lF,randomUUID as cF}from"node:crypto";import{closeSync as mF,lstatSync as fF,mkdirSync as pF,openSync as uF,readdirSync as Fv,readFileSync as hF,readSync as gF,renameSync as yF,rmdirSync as wF,rmSync as qv,writeFileSync as bF}from"node:fs";import{dirname as kF,join as Yn,posix as EF,resolve as op}from"node:path";var ye=Xd(od(),1);var Nt=2,id=".modeldesk",Yf="workspace.json",Pt="model.yaml",vv="_element.yaml",Rv="_unowned",yt="model.json",W1="# modeldesk",Sv=/^# modeldesk(?::|\s|$)/,ad=8*1024*1024,zf=128*1024*1024,ze=100,Jf=["id","type","attributes","relations","readOnly"],Xf=["ref","owned","model"],Iv=[...Ue,"relations"],B1="@element",Lt=e=>e.startsWith("@")&&e!==B1,$v={lineWidth:0,minContentWidth:0,doubleQuotedAsJSON:!0,indentSeq:!0},Qf={version:"1.2",schema:"core",uniqueKeys:!0,prettyErrors:!1},pn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Zf=e=>e in Object.prototype,W=e=>pe(y(e)),H1=/^[A-Za-z_][A-Za-z0-9_-]*$/,U1=/^(?:y|yes|n|no|true|false|on|off|null)$/i,xv=e=>{let t=new ye.Scalar(e);return(!H1.test(e)||U1.test(e))&&(t.type=ye.Scalar.QUOTE_DOUBLE),t},ko=(e,t=0)=>{if(t>ze)throw new u(`A value nests more than ${ze} deep, deeper than a workspace is written.`,{type:"model-too-deep"});if(Array.isArray(e)){let r=new ye.YAMLSeq;return r.items=e.map(s=>ko(s,t+1)),r}if(e!==null&&typeof e=="object")return Dt(Object.keys(e).sort(ie).map(r=>[r,ko(e[r],t+1)]));let n=new ye.Scalar(e);return typeof e=="string"&&(n.type=ye.Scalar.QUOTE_DOUBLE),n},Dt=e=>{let t=new ye.YAMLMap;return t.items=e.map(([n,r])=>new ye.Pair(xv(n),r)),t},Kn=(e,t)=>{let n=new ye.Scalar(e);return n.type=ye.Scalar.QUOTE_DOUBLE,t!==void 0&&t!==""&&(n.comment=` ${t}`),n},ie=(e,t)=>e<t?-1:e>t?1:0,dd=(e,t)=>{let n=new ye.Document;return n.contents=e,n.commentBefore=`${W1.slice(1)}: ${t}`,n.toString($v)},Tv=(e,t)=>{let n=(0,ye.parseDocument)(e,Qf),r=[];for(let{path:s,id:o}of t){let i=s.length===0?n.contents:n.getIn(s,!0);if(!(0,ye.isMap)(i)||i.has("id")){r.push(s);continue}i.items.unshift(new ye.Pair(xv("id"),Kn(o)))}return{text:n.toString($v),missed:r}},V1=/^(?:con|prn|aux|nul|com\d|lpt\d)$/,G1=64,ep=e=>e.normalize("NFKD").replace(new RegExp("\\p{M}+","gu"),"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,G1).replace(/-$/g,""),tp=e=>e===""||V1.test(e),wt=e=>e.map(t=>`/${String(t).replaceAll("~","~0").replaceAll("/","~1")}`).join("");var cd=Xd(od(),1);var K1=100,rp=50,Je=class extends u{constructor(n){let[r]=n,s=n.length>1?` (and ${n.length-1} more)`:"",o=r.at?` at ${r.at}`:"";super(W(`${r.file}${o}: ${r.message}${s}`),{exitCode:b.Validation,type:"workspace-invalid",hint:"The workspace format is described in the CLI's README; 'modeldesk model pull --force' rewrites the files.",details:{errors:n}});this.problems=n;this.name="WorkspaceInvalidError"}problems},xe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),np=class{elements=new Map;fileLevel=new Set;problems=[];add(t,n){let r=this.elements.get(t.key);if(r!==void 0){n.problem([...t.location.path],"duplicate-id",`The id ${t.key} is also used at ${r.location.file}${wt(r.location.path)||" (its top)"}; every element is written once. Give a copy no id (a new element), or reference it by id.`);return}this.elements.set(t.key,t)}full(){return this.problems.length>=rp}},ld=(e,t,n)=>{if(typeof e!="string"||!pn.test(e)){n.problem(t,"invalid-id",`An id is a UUID in quotes, not ${JSON.stringify(e)?.slice(0,60)}.`);return}return e.toLowerCase()},Y1=(e,t,n)=>{let r=Object.keys(e).filter(i=>!Xf.includes(i));if(!("ref"in e)||r.length>0){n.problem(t,"invalid-reference",r.length>0?`A reference takes only ${Xf.join(", ")}; '${r[0]}' is not one of them. A nested element needs a type.`:"A reference mapping names its target with `ref: <id>`; a nested element needs a type.");return}let s=ld(e.ref,[...t,"ref"],n);if(e.owned!==void 0&&typeof e.owned!="boolean"){n.problem([...t,"owned"],"invalid-reference","`owned` is true or false.");return}let o=e.model===void 0?void 0:ld(e.model,[...t,"model"],n);if(!(s===void 0||e.model!==void 0&&o===void 0))return{key:s,owned:e.owned===!0,...o!==void 0&&{modelId:o}}},z1=(e,t,n,r,s)=>{if(typeof e=="string"){let o=ld(e,t,n);return o===void 0?void 0:{key:o,owned:!1}}if(!xe(e)){n.problem(t,"invalid-reference","A relation lists ids, `{ref: <id>, owned: true}` mappings or nested elements (a mapping with a type).");return}if("type"in e){let o=Pv(e,t,n,r,!1,s+1);return o===void 0?void 0:{key:o.key,owned:!0}}return Y1(e,t,n)},sp=(e,t,n,r)=>Zf(e)?(n.problem(t,"reserved-name",`'${e}' cannot name ${r}: every JavaScript object already has a member of that name.`),!0):!1,Av=(e,t,n,r,s)=>{if(!Array.isArray(e)){n.problem(t,"invalid-relations","A relation's references are a list; write [] for none.");return}return e.flatMap((o,i)=>z1(o,[...t,i],n,r,s)??[])},J1=(e,t,n,r,s)=>{if(Array.isArray(e))return{"@@":Av(e,t,n,r,s)??[]};if(!xe(e)){n.problem(t,"invalid-relations",`The relation '${t.at(-1)}' is a list of references, or a mapping of groups to lists; write [] for none.`);return}return Object.fromEntries(Object.entries(e).filter(([o])=>!sp(o,[...t,o],n,"a group")).map(([o,i])=>[o,Av(i,[...t,o],n,r,s)??[]]))},Nv=(e,t,n,r,s)=>{if(!xe(e))return n.problem(t,"invalid-relations","`relations:` maps each relation name to its references."),{};let o={};for(let[i,a]of Object.entries(e)){if(sp(i,[...t,i],n,"a relation"))continue;let d=J1(a,[...t,i],n,r,s);d!==void 0&&(o[i]=d)}return o},X1=(e,t,n)=>{let r=Object.keys(e).filter(s=>!Jf.includes(s));for(let s of r)n.problem([...t,s],"unknown-key",`An element block takes ${Jf.join(", ")}; '${s}' is none of them. An attribute goes under \`attributes:\`, a relation under \`relations:\`.`)},Q1=(e,t,n)=>{let r={};if(e===void 0)return r;if(!xe(e))return n.problem([...t,"attributes"],"invalid-attributes","`attributes:` maps each name to a list of values."),r;for(let[s,o]of Object.entries(e))sp(s,[...t,"attributes",s],n,"an attribute")||(Array.isArray(o)?r[s]=o:n.problem([...t,"attributes",s],"invalid-attributes",`The attribute '${s}' holds a list of values: write - "value" on the line below it, or [] for none.`));return r},Z1=(e,t)=>t?`\`readOnly:\` holds ${Iv.join(", ")}; '${e}' is none of them.`:`\`readOnly:\` holds ${Ue.join(", ")} here; '${e}' is none of them.`,eF=(e,t,n,r,s,o)=>{let i={},a={};if(e===void 0)return{readOnly:i,relations:a};if(!xe(e))return n.problem([...t,"readOnly"],"invalid-read-only","`readOnly:` is a mapping."),{readOnly:i,relations:a};for(let[d,l]of Object.entries(e))d==="relations"&&o?Object.assign(a,Nv(l,[...t,"readOnly","relations"],n,r,s)):Ue.includes(d)?i[d]=l:n.problem([...t,"readOnly",d],"unknown-key",Z1(d,o));return{readOnly:i,relations:a}},Pv=(e,t,n,r,s,o)=>{if(r.full())return;if(o>ze){n.problem(t,"too-deep",`Elements nest more than ${ze} deep here; write the rest in files of their own.`);return}if(!xe(e)){n.problem(t,"invalid-element","An element is a mapping with at least a `type`.");return}X1(e,t,n);let i={file:n.file,path:[...t]},a=e.id===void 0?void 0:ld(e.id,[...t,"id"],n);if(typeof e.type!="string"||e.type===""){n.problem([...t,"type"],"missing-type","Every element names its `type`.");return}let d=Q1(e.attributes,t,n),l=e.relations===void 0?{}:Nv(e.relations,[...t,"relations"],n,r,o),c=eF(e.readOnly,t,n,r,o,s);Object.assign(l,c.relations);let{readOnly:m}=c,f={key:a??`${n.file}#${wt(t)}`,...a!==void 0&&{id:a},type:e.type,attributes:d,relations:l,readOnly:m,location:i};return r.add(f,n),f},tF=(e,t)=>e?.range?t.linePos(e.range[0]).line:void 0,Ov=(e,t)=>({file:e,code:"invalid-yaml",message:t instanceof RangeError?"The file nests too deeply to be read.":`The file cannot be read as YAML: ${t.message.split(`
234
+ `)[0]}`}),nF=(e,t)=>{let n=new cd.LineCounter,r;try{r=(0,cd.parseDocument)(e.text,{...Qf,lineCounter:n})}catch(i){t.problems.push(Ov(e.path,i));return}let s={file:e.path,problem:(i,a,d)=>{let l=i.length===0?r.contents:r.getIn(i,!0),c=tF(l,n);t.problems.push({file:e.path,...i.length>0&&{at:wt(i)},...c!==void 0&&{line:c},code:a,message:W(d)})}};if(r.errors.length>0){for(let i of r.errors.slice(0,3))t.problems.push({file:e.path,line:n.linePos(i.pos[0]).line,code:"invalid-yaml",message:i.message.split(`
235
+ `)[0]});return}let o;try{o=r.toJS({maxAliasCount:K1})}catch(i){t.problems.push(Ov(e.path,i));return}return Pv(o,[],s,t,e.path===Pt,0)},Lv=e=>{let t=new np,n;for(let r of[...e].sort((s,o)=>ie(s.path,o.path))){if(t.full())break;let s=nF(r,t);s!==void 0&&(t.fileLevel.add(s.key),r.path===Pt&&(n=s.key))}if(n===void 0&&!t.problems.some(r=>r.file===Pt)&&t.problems.push({file:Pt,code:"missing-root",message:`The workspace has no ${Pt}, which holds the model's root element.`}),t.problems.length>0)throw new Je(t.problems.slice(0,rp));return{format:"yaml",rootKey:n,elements:t.elements,fileLevel:t.fileLevel}},rF=e=>[...Object.keys(xe(e.attributes)?e.attributes:{}),...Object.entries(xe(e.relations)?e.relations:{}).flatMap(([t,n])=>[t,...Object.keys(xe(n)?n:{})])].find(t=>Zf(t)),Mv=e=>typeof e=="string"&&pn.test(e),sF=e=>xe(e)&&Mv(e.id)&&(e.owned===void 0||typeof e.owned=="boolean")&&(e.modelId===void 0||Mv(e.modelId)),oF=e=>xe(e)&&Object.values(e).every(t=>Array.isArray(t)&&t.every(sF)),iF=e=>e.relations!==void 0&&!(xe(e.relations)&&Object.values(e.relations).every(oF)),aF=e=>e.attributes!==void 0&&!(xe(e.attributes)&&Object.values(e.attributes).every(t=>Array.isArray(t))),dF=(e,t,n,r)=>{let s={},o=n.relations??{};for(let[l,c]of Object.entries(o))s[l]=Object.fromEntries(Object.entries(c).map(([m,f])=>[m,f.map(h=>({key:h.id.toLowerCase(),owned:h.owned===!0,...typeof h.modelId=="string"&&{modelId:h.modelId}}))]));let i=n.attributes??{},a=Object.fromEntries(Ue.filter(l=>l in n).map(l=>[l,n[l]])),d=t.toLowerCase();return{key:d,id:d,type:r,attributes:i,relations:s,readOnly:a,location:{file:e,path:["elements",t]}}},Dv=e=>{let t=[],n=(i,a,d)=>t.push({file:e.path,...i!==void 0&&{at:i},code:a,message:d}),r;try{r=JSON.parse(e.text)}catch(i){throw new Je([{file:e.path,code:"invalid-json",message:i.message}])}if(!xe(r)||typeof r.rootElementId!="string"||!xe(r.elements))throw new Je([{file:e.path,code:"invalid-json",message:`${yt} holds {"rootElementId": \u2026, "elements": {\u2026}}.`}]);let s=new Map;for(let[i,a]of Object.entries(r.elements)){let d=wt(["elements",i]);if(!pn.test(i)||!xe(a)||a.id!==i||typeof a.type!="string"){n(d,"invalid-element","Each entry is an element keyed by its own id, with a type.");continue}let l=rF(a);if(l!==void 0){n(d,"reserved-name",`'${l}' cannot name an attribute, relation or group: every JavaScript object already has a member of that name.`);continue}if(iF(a)){n(d,"invalid-reference",'Relations map each name to its groups, and each group lists references: {"id": <uuid>, "owned": <boolean>}, with "modelId" for another model.');continue}if(aF(a)){n(d,"invalid-attributes","Attributes map each name to a list of values.");continue}s.set(i.toLowerCase(),dF(e.path,i,a,a.type))}let o=r.rootElementId.toLowerCase();if(s.has(o)||n("/rootElementId","missing-root","rootElementId names no element of the map."),t.length>0)throw new Je(t.slice(0,rp));return{format:"json",rootKey:o,elements:s,fileLevel:new Set(s.keys())}};var Wv=`${id}/${Yf}`,CF=16*1024*1024,_v=Math.max(zf,ad),vF=e=>e.startsWith(".")||e==="node_modules",RF=/^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/,SF=/^[0-9a-f]{64}$/,Bv=(e,t)=>e<t?-1:e>t?1:0,Hv=e=>lF("sha256").update(e,"utf8").digest("hex"),Co=e=>Object.fromEntries(e.map(t=>[t.path,Hv(t.text)])),vo=e=>Yn(e,id,Yf),md=(e,t,n)=>new u(`${W(Yn(e,t))} ${n}, so the workspace does not touch it.`,{type:"workspace-path-refused",hint:"Replace it with a plain file or directory, or use another workspace directory.",details:{path:t}}),fd=e=>{try{return fF(e)}catch(t){if(t.code==="ENOENT")return;throw t}},Uv=e=>e===""||e.includes("\\")||e.includes("\0")||EF.isAbsolute(e)||e.split("/").some(n=>n===""||n==="."||n==="..")?void 0:e,un=(e,t)=>{let n=Uv(t);if(n===void 0)throw md(e,t,"is not a plain path inside the workspace");let r=n.split("/"),s=op(e),o=s;for(let[i,a]of r.entries()){o=Yn(o,a);let d=fd(o);if(d===void 0)return Yn(s,...r);if(d.isSymbolicLink())throw md(e,r.slice(0,i+1).join("/"),"is a symbolic link");if(i<r.length-1&&!d.isDirectory())throw md(e,r.slice(0,i+1).join("/"),"is not a directory")}return o},Eo=(e,t,n)=>{let r=un(e,t),s=fd(r);if(s!==void 0){if(!s.isFile())throw md(e,t,"is not a plain file");if(s.size>n)throw new u(`${W(Yn(e,t))} holds ${s.size} bytes, more than a workspace file may (${n}); it was not read.`,{type:"workspace-file-too-large",details:{path:t,bytes:s.size,limit:n}});return hF(r,"utf8")}},bt=(e,t)=>new u(`${W(vo(e))} ${t}.`,{hint:"Re-pull the workspace into an empty directory with 'modeldesk model pull'."}),IF=(e,t)=>{if(t.schemaVersion===1){let n=typeof t.modelId=="string"?W(t.modelId):"<model>";throw new u(`${W(vo(e))} is a workspace of format 1, which records no branch, and this CLI reads format ${Nt} only.`,{hint:`Copy aside any edits you have not pushed, then pull the model again into an empty directory: 'modeldesk model pull ${n}@<branch> <dir>'.`})}if(t.schemaVersion!==Nt)throw bt(e,`has workspace format ${W(String(t.schemaVersion))}, which this CLI does not read (it reads ${Nt}); update the CLI`)},jv=(e,t,n)=>{let r=t[n];if(typeof r!="object"||r===null||typeof r.id!="string"||!pn.test(r.id)||typeof r.name!="string")throw bt(e,`lacks "${n}" with its id and name`);return{id:r.id.toLowerCase(),name:r.name}},$F=(e,t)=>{for(let[n,r]of Object.entries(t))if(Uv(n)===void 0||n.split("/")[0]===id||typeof r!="string"||!SF.test(r))throw bt(e,`lists ${W(n)} among its files, which is not a workspace path with its SHA-256`)},Vv=e=>{let t=Eo(e,Wv,CF);if(t===void 0)return;let n;try{n=JSON.parse(t)}catch(a){throw bt(e,`is not valid JSON (${W(a.message)})`)}if(n===null||typeof n!="object"||Array.isArray(n))throw bt(e,"is not a JSON object");let r=n;if(IF(e,r),typeof r.host!="string"||!RF.test(r.host))throw bt(e,"names a host that is not a bare host name (such as modeldesk.io)");if(typeof r.baseCommitId!="string"||!pn.test(r.baseCommitId))throw bt(e,'lacks "baseCommitId", the UUID of the commit its files reflect');let s=r.baseRootRevision;if(s!==void 0&&(typeof s!="string"||!pn.test(s)))throw bt(e,'has a "baseRootRevision" that is not a UUID');let o=r.format??"yaml";if(o!=="yaml"&&o!=="json")throw bt(e,'has a format that is neither "yaml" nor "json"');let i=r.files??{};if(i===null||typeof i!="object"||Array.isArray(i))throw bt(e,'has a "files" member that is not an object');return $F(e,i),{schemaVersion:Nt,host:r.host,model:jv(e,r,"model"),branch:jv(e,r,"branch"),baseCommitId:r.baseCommitId.toLowerCase(),...s!==void 0&&{baseRootRevision:s.toLowerCase()},format:o,files:Object.fromEntries(Object.entries(i))}},ip=(e,t)=>{pF(kF(e),{recursive:!0});let n=`${e}.${cF()}.tmp`;try{bF(n,t),yF(n,e)}catch(r){throw qv(n,{force:!0}),r}},hn=(e,t)=>ip(un(e,Wv),`${JSON.stringify(t,null,2)}
236
+ `),xF=e=>{let t=Buffer.alloc(64),n=uF(e,"r");try{let r=gF(n,t,0,t.length,0);return Sv.test(t.subarray(0,r).toString("utf8").replace(/^\uFEFF/,""))}finally{mF(n)}},TF=e=>{try{return Fv(e,{withFileTypes:!0})}catch(t){if(t.code==="ENOENT")return;throw t}},Gv=(e,t,n,r,s)=>{let o=Yn(e,t),i=TF(o);if(i!==void 0)for(let a of i){let d=t===""?a.name:`${t}/${a.name}`;if(a.isDirectory()){if(!vF(a.name)){let l=n||t===""&&r.has(a.name);Gv(e,d,l,r,s)}}else a.isFile()&&a.name.endsWith(".yaml")&&!s.has(d)&&(n||xF(Yn(o,a.name)))&&s.add(d)}},AF=(e,t)=>{let n=new Set,r=Object.keys(t.files);for(let o of[...r,...t.format==="json"?[yt]:[]])fd(un(e,o))!==void 0&&n.add(o);if(t.format==="json")return[...n].filter(o=>o===yt);let s=new Set(r.filter(o=>o.includes("/")).map(o=>o.split("/")[0]));return s.forEach(o=>un(e,o)),Gv(op(e),"",!1,s,n),[...n].sort(Bv)},ap=(e,t)=>AF(e,t).flatMap(n=>{let r=Eo(e,n,n===yt?zf:ad);return r===void 0?[]:[{path:n,text:r}]}),dp=(e,t)=>{if(t==="json"){let n=e.find(r=>r.path===yt);if(n===void 0)throw new Je([{file:yt,code:"missing-root",message:"The workspace has no model.json."}]);return Dv(n)}return Lv(e)},gn=(e,t)=>dp(ap(e,t),t.format),pd=(e,t,n)=>{let r={written:[],unchanged:[],removed:[],kept:[],collisions:[]},s=new Set(t.map(o=>o.path));for(let o of t){let i=Eo(e,o.path,_v);i===o.text?r.unchanged.push(o.path):i!==void 0&&!Object.hasOwn(n,o.path)?r.collisions.push(o.path):r.written.push(o.path)}for(let o of Object.keys(n).sort(Bv)){if(s.has(o))continue;let i=Eo(e,o,_v);i!==void 0&&(Hv(i)===n[o]?r.removed:r.kept).push(o)}return r},ud=(e,t,n)=>{if(n.collisions.length>0)throw new Error("A write plan with collisions is not applied.");let r=new Map(t.map(o=>[o.path,o.text]));for(let o of n.written)ip(un(e,o),r.get(o));let s=new Set;for(let o of n.removed){qv(un(e,o),{force:!0});let i=o.split("/");for(let a=i.length-1;a>0;a--)s.add(i.slice(0,a).join("/"))}for(let o of[...s].sort((i,a)=>a.length-i.length)){let i=un(e,o);fd(i)?.isDirectory()&&Fv(i).length===0&&wF(i)}},Kv=(e,t)=>{let n=[],r=new Map;for(let s of t)r.set(s.location.file,[...r.get(s.location.file)??[],s]);for(let[s,o]of r)try{let i=Eo(e,s,ad);if(i===void 0){n.push(...o.map(l=>({...l,reason:"its file is gone"})));continue}let a=Tv(i,o.map(({location:l,id:c})=>({path:l.path,id:c}))),d=new Set(a.missed.map(l=>JSON.stringify(l)));n.push(...o.filter(l=>d.has(JSON.stringify(l.location.path))).map(l=>({...l,reason:"its block is no longer where it was"}))),ip(un(e,s),a.text)}catch(i){n.push(...o.map(a=>({...a,reason:W(i.message)})))}return n},Yv=(e,t)=>op(e,t??".");var hd=e=>JSON.stringify(e,(t,n)=>n!==null&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.keys(n).sort(ie).map(r=>[r,n[r]])):n),zr=(e,t)=>hd(e)===hd(t),Ro=e=>Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t.length>0)),OF=e=>({key:e.id,owned:e.owned===!0,...e.modelId!==void 0&&{modelId:e.modelId}}),zn=(e,t)=>Object.fromEntries(Object.entries(e.relations?.[t]??{}).map(([n,r])=>[n,r.map(OF)])),Jn=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t.length>0)),lp=e=>Object.keys(e).some(t=>t!=="@@"),Se=e=>Object.keys(e).sort(ie).flatMap(t=>e[t]),So=e=>{let t=new Map;for(let n of Object.keys(e).sort(ie)){let r=e[n].relations??{};for(let s of Object.keys(r).sort(ie))for(let o of Se(r[s])){if(o.owned!==!0)continue;let i=t.get(o.id)??[];i.some(a=>a.id===n&&a.relation===s)||i.push({id:n,relation:s}),t.set(o.id,i)}}return t},gd=e=>{for(let t of e??[]){if(typeof t=="string"&&t.trim()!=="")return t;if(t!==null&&typeof t=="object"&&typeof t.value=="string")return t.value}};var kt=class extends u{constructor(n){let r=n.length>1?` (and ${n.length-1} more)`:"";super(W(`${n[0].message}${r}`),{exitCode:b.Validation,type:"workspace-refused",details:{errors:n}});this.problems=n;this.name="WorkspaceRefusedError"}problems},yd=e=>`${e.id}\0${e.relation}`,MF=e=>{let t=[],n=new Array(e.length).fill(-1);e.forEach((s,o)=>{let i=0,a=t.length;for(;i<a;){let d=i+a>>1;e[t[d]]<s?i=d+1:a=d}n[o]=i>0?t[i-1]:-1,t[i]=o});let r=new Set;for(let s=t.at(-1)??-1;s!==-1;s=n[s])r.add(s);return r},Io=e=>"id"in e?e.id:e.new,NF=e=>{let t=new Map;for(let[n,r]of e)for(let[s,o]of Object.entries(r.relations))for(let i of Se(o).filter(a=>a.owned)){let a=t.get(i.key)??[];a.some(d=>d.id===n&&d.relation===s)||a.push({id:n,relation:s}),t.set(i.key,a)}return t},PF=e=>Object.values(e.relations??{}).flatMap(t=>Se(t)).filter(t=>t.owned===!0).map(t=>t.id),LF=(e,t)=>{let n=new Map,r=e[t]?.relations??{},s=Object.keys(r).filter(Lt).flatMap(o=>Se(r[o]).filter(i=>i.owned===!0).map(i=>[i.id,o]));for(let o=s.shift();o!==void 0;o=s.shift()){let[i,a]=o;n.has(i)||!Object.hasOwn(e,i)||(n.set(i,a),PF(e[i]).forEach(d=>s.push([d,a])))}return n},DF=(e,t)=>{let n=e.elements,r=t.elements,s=e.rootId,o=[],i=c=>Object.hasOwn(n,c),a=c=>r.has(c)&&!i(c),d=So(n),l=NF(r);return{C:n,W:r,rootId:s,problems:o,currentOwners:d,pinnedVia:LF(n,s),vanished:new Set(Object.keys(n).filter(c=>c!==s&&!r.has(c)).sort(ie)),has:i,isNew:a,nodeRef:c=>i(c)||r.get(c)?.id!==void 0?{id:c}:{new:c},opRef:c=>a(c.key)&&r.get(c.key)?.id===void 0?{new:c.key,owned:c.owned}:{id:c.key,owned:c.owned,...c.modelId!==void 0&&{modelId:c.modelId}},ownersNow:c=>d.get(c)??[],ownersThen:c=>l.get(c)??[],viaPin:c=>c.id===s&&Lt(c.relation),refuse:(c,m,f)=>{o.push({code:c,message:W(m),...f.elementId!==void 0&&{elementId:f.elementId},...f.element?.id!==void 0&&f.elementId===void 0&&{elementId:f.element.id},...f.property!==void 0&&{property:f.property},...f.element!==void 0&&{file:f.element.location.file},...f.element!==void 0&&f.element.location.path.length>0&&{at:wt(f.element.location.path)}})}}},Xv=(e,t)=>({attributes:Ro(e),relations:Object.fromEntries(Object.entries(t).map(([n,r])=>[n,Jn(r)]).filter(([,n])=>Object.keys(n).length>0))}),_F=(e,t)=>Xv(e[t].attributes??{},Object.fromEntries(Object.keys(e[t].relations??{}).map(n=>[n,zn(e[t],n)]))),jF=(e,t)=>{let{C:n,rootId:r,refuse:s}=e,o=n[r]?.relations??{},i=new Set([...Object.keys(o),...Object.keys(t.relations)]);for(let a of[...i].filter(Lt).sort(ie)){let d=Jn(zn(n[r],a)),l=Jn(t.relations[a]??{});zr(d,l)||s("read-only-field",`The root's '${a}' is read-only in a workspace: add or remove a dependency with 'modeldesk dependency add' or 'dependency rm', and move a pin with 'modeldesk pin set'.`,{element:t,elementId:r,property:a})}},FF=(e,t)=>{let{W:n,has:r,pinnedVia:s,refuse:o}=e;for(let[i,a]of Object.entries(t.relations))for(let d of Se(a))d.owned&&!n.has(d.key)&&r(d.key)&&!s.has(d.key)&&o("missing-block",`'${i}' owns ${d.key} (owned: true), but its block is gone from the workspace. Write its block here in place of the reference, or drop the reference to delete it.`,{element:t,property:i})},zv=e=>e.length===0?"no owner":e.map(t=>`${t.id} via ${t.relation}`).join(", "),qF=(e,t,n)=>n.length>0&&t.length===0?`Element ${e} is written on its own, and the element that owns it (${n[0].id}) is deleted. To delete it as well, remove its block. To keep it, reference it from its new owner as \`- ref: <id>\` with \`owned: true\`: the push moves it there before deleting the old owner.`:`Element ${e} is written on its own, but nothing in the workspace owns it any more: nest it where it belongs, or reference it from its owner with \`owned: true\`.`,WF=(e,t,n,r)=>{let{ownersNow:s,ownersThen:o,vanished:i,viaPin:a,refuse:d}=e,l=s(t),c=o(t),m=l.filter(g=>!c.some(w=>yd(w)===yd(g))),f=c.filter(g=>!l.some(w=>yd(w)===yd(g))),h=m.filter(g=>!i.has(g.id)),p=m.filter(g=>i.has(g.id));if(f.some(a))d("read-only-field",`Element ${t} cannot be placed under the root's read-only relations.`,{element:n});else if(c.length===0&&l.length>0)d("unowned",qF(t,h,p),{element:n});else{if(f.length===0&&h.length===0)return;f.length===1&&h.length===1?r.set(t,{from:h[0],to:f[0]}):f.length===1&&h.length===0&&p.length>0?r.set(t,{from:p[0],to:f[0]}):d("ownership-change",`Element ${t} would go from ${zv(l)} to ${zv(c)}. A push moves an element from one owner to another; adding an owner, or dropping one that is not deleted, is done in the app. Keep its other owners as they are and change one at a time.`,{element:n})}},BF=(e,t,n,r)=>{let{C:s,rootId:o,pinnedVia:i,refuse:a}=e;n.type!==s[t].type&&a("type-changed",`Element ${t} is a ${s[t].type} and cannot become a ${n.type}: an element's type is fixed. Delete it and write a new element without an id.`,{element:n,property:"type"});for(let l of Ue)zr(s[t][l]??null,n.readOnly[l]??null)||a("read-only-field",`'${l}' of ${t} is read-only: the server serves it, no staged write accepts it.`,{element:n,property:l});let d=i.get(t);d!==void 0&&!zr(_F(s,t),Xv(n.attributes,n.relations))&&a("read-only-field",`Element ${t} belongs to the root's read-only '${d}' and cannot be changed.`,{element:n,property:d}),!(t===o||d!==void 0)&&WF(e,t,n,r)},HF=(e,t,n)=>{let{rootId:r,ownersThen:s,viaPin:o,refuse:i}=e,a=s(t),d=n.id??`the new ${n.type} at ${W(n.location.file)}${W(wt(n.location.path))}`;Object.keys(n.readOnly).length>0&&i("read-only-field",`${d} carries read-only fields, which no staged write accepts.`,{element:n,property:Object.keys(n.readOnly)[0]}),a.length===0&&t!==r?i("unowned",`${d} is new and nothing owns it: nest it under its owner's relation, or give it an id and reference it from its owner as \`- ref: <id>\` with \`owned: true\`.`,{element:n}):a.length>1?i("multi-owned-create",`${d} is new and has ${a.length} owners; a new element starts with one.`,{element:n}):a.some(o)&&i("read-only-field",`${d} cannot be created under the root's read-only relations.`,{element:n})},UF=(e,t)=>{for(let[n,r]of e.W)FF(e,r),e.has(n)?BF(e,n,r,t):HF(e,n,r)},VF=e=>{for(let t of e.vanished){let n=e.pinnedVia.get(t);n!==void 0&&e.refuse("read-only-field",`Element ${t} belongs to the root's read-only '${n}' and cannot be removed.`,{elementId:t,property:n})}},Qv=e=>{let t=[],n=new Set;return{order:t,seen:n,visit:s=>{let o=[s];for(let i=o.pop();i!==void 0;i=o.pop()){if(n.has(i))continue;n.add(i),t.push(i);let a=e(i),d=Object.keys(a).sort(ie).flatMap(l=>Se(a[l]).filter(c=>c.owned).map(c=>c.key));for(let l=d.length-1;l>=0;l--)o.push(d[l])}}}},GF=(e,t)=>{let n=Qv(r=>e.W.get(r)?.relations??{});return n.visit(e.rootId),[...t.fileLevel].sort(ie).forEach(n.visit),n.order.filter(r=>e.W.has(r))},cp=(e,t)=>e.ownersThen(t)[0],Zv=(e,t,n,r)=>{let s=cp(e,r.key);return r.owned&&e.isNew(r.key)&&!t.has(r.key)&&s?.id===n.key&&s.relation===n.relation},KF=(e,t,n)=>{let r=[n];for(let s=r.pop();s!==void 0;s=r.pop()){t.add(s);for(let[o,i]of Object.entries(e.W.get(s)?.relations??{}))for(let a of Se(i))Zv(e,t,{key:s,relation:o},a)&&r.push(a.key)}},eR=(e,t,n,r=0)=>{t.add(n);let s=e.W.get(n);if(r>ze)return e.refuse("too-deep",`New elements nest more than ${ze} deep under ${W(s.location.file)}; push them in parts.`,{element:s}),KF(e,t,n),{element:e.nodeRef(n),type:s.type};let o={},i={};for(let d of Object.keys(s.relations).sort(ie)){let l=s.relations[d],c=Jn(Object.fromEntries(Object.entries(l).map(([f,h])=>[f,h.filter(p=>!p.owned).map(p=>e.opRef(p))])));Object.keys(c).length>0&&(o[d]=c);let m=Se(l).filter(f=>Zv(e,t,{key:n,relation:d},f));m.length>0&&(i[d]=m.map(f=>eR(e,t,f.key,r+1)))}let a=Ro(s.attributes);return{element:e.nodeRef(n),type:s.type,...Object.keys(a).length>0&&{attributes:a},...Object.keys(o).length>0&&{relations:o},...Object.keys(i).length>0&&{children:i}}},YF=(e,t)=>{let n=new Set,s=t.filter(o=>{let i=cp(e,o);return e.isNew(o)&&i!==void 0&&e.has(i.id)&&e.ownersThen(o).length===1}).map(o=>({key:o,home:cp(e,o),node:eR(e,n,o)}));for(let o of t)e.isNew(o)&&!n.has(o)&&e.ownersThen(o).length===1&&e.refuse("unowned",`The new ${e.W.get(o)?.type} at ${W(e.W.get(o)?.location.file??"")} hangs from no existing element.`,{element:e.W.get(o)});return s},tR=(e,t=[])=>(t.push(Io(e.element)),Object.values(e.children??{}).flat().forEach(n=>tR(n,t)),t),nR=(e,t=new Set)=>{for(let n of Object.values(e.relations??{}))for(let r of Se(n))t.add(Io(r));return Object.values(e.children??{}).flat().forEach(n=>nR(n,t)),t},zF=e=>{let t=[],n=new Array(e.length).fill(-1),r=new Array(e.length).fill(0),s=new Array(e.length).fill(!1),o=[],i=0,a=c=>{n[c]=i,r[c]=i,i++,o.push(c),s[c]=!0},d=c=>{let m=[];for(let f=o.pop();f!==void 0&&(s[f]=!1,m.push(f),f!==c);f=o.pop());t.push(m.toSorted((f,h)=>f-h))},l=c=>{let m=[{node:c,edge:0}];a(c);for(let f=m.at(-1);f!==void 0;f=m.at(-1)){let{node:h}=f;if(f.edge<e[h].length){let g=e[h][f.edge++];n[g]===-1?(a(g),m.push({node:g,edge:0})):s[g]&&(r[h]=Math.min(r[h],n[g]));continue}m.pop();let p=m.at(-1);p!==void 0&&(r[p.node]=Math.min(r[p.node],r[h])),r[h]===n[h]&&d(h)}};return e.forEach((c,m)=>{n[m]===-1&&l(m)}),t},JF=e=>{let t=new Map;e.forEach((r,s)=>tR(r.node).forEach(o=>t.set(o,s)));let n=e.map((r,s)=>[...nR(r.node)].map(o=>t.get(o)).filter(o=>o!==void 0&&o!==s));return zF(n)},XF=e=>{let t=new Map;return(n,r)=>{let s=`${n}\0${r}`,o=t.get(s);return o===void 0&&(o=e.has(n)?Se(zn(e.C[n],r)).map(i=>i.key):[],t.set(s,o)),o}},rR=(e,t)=>{let n=Io(t.element);for(let[r,s]of Object.entries(t.relations??{}))e(n,r).push(...Se(s).map(Io));for(let[r,s]of Object.entries(t.children??{}))for(let o of s)e(n,r).push(Io(o.element)),rR(e,o)},QF=(e,t,n,r,s)=>{for(let o of n){let i=s.ops.length;for(let a of o){let{key:d,home:l,node:c}=t[a];s.ops.push({op:"create",parent:e.nodeRef(l.id),relation:l.relation,element:c}),r(l.id,l.relation).push(d),rR(r,c)}o.length>1&&s.together.push(o.map((a,d)=>i+d))}},sR=({ctx:e},{parent:t,relation:n},r,s,o)=>({op:"move",element:e.nodeRef(r),from:{parent:e.nodeRef(s.id),relation:s.relation},parent:e.nodeRef(t),relation:n,...o!==void 0&&{position:o}}),oR=(e,t,n,r)=>{let{from:s}=e.moves.get(n);e.staged.ops.push(sR(e,t,n,s,r));let o=e.listOf(s.id,s.relation),i=o.indexOf(n);i!==-1&&o.splice(i,1)},ZF=(e,t)=>Object.entries(t).some(([n,r])=>{let s=(e[n]??[]).map(l=>l.key),o=new Set(s),i=r.map(l=>l.key).filter(l=>o.has(l)),a=new Set(i),d=s.filter(l=>a.has(l));return i.some((l,c)=>l!==d[c])}),eq=(e,t,n)=>{let{ctx:r,staged:s,moved:o}=e,i=r.has(t.parent)?zn(r.C[t.parent],t.relation):{};ZF(i,n)&&s.warnings.push(`The order of '${W(t.relation)}' of ${t.parent} changed in the files, and a grouped relation is not reordered by a push: its order stays as it is.`);for(let a of t.order.filter(d=>t.arriving.has(d)))oR(e,t,a,void 0),t.list.push(a),o.add(a)},iR=(e,t)=>t===void 0?0:e.indexOf(t)+1,tq=(e,t,n,r)=>{let s=iR(t.list,r);oR(e,t,n,s>=t.list.length?void 0:s),t.list.splice(s,0,n),t.inList.add(n),e.moved.add(n)},nq=(e,t,n,r)=>{let s=t.list.indexOf(n);t.list.splice(s,1);let o=iR(t.list,r);if(t.list.splice(o,0,n),o!==s){let i={id:t.parent,relation:t.relation};e.staged.ops.push(sR(e,t,n,i,s>=o?o:o+1))}},rq=(e,t,n,r)=>{if(t.inPlace.has(n)||!t.owned.has(n))return;let s=t.arriving.has(n);if(!s&&!t.inList.has(n))return;let o=t.order.slice(0,r).findLast(i=>t.inList.has(i)&&i!==n);s?tq(e,t,n,o):nq(e,t,n,o)},sq=(e,t)=>{let{order:n,list:r,arriving:s}=t,o=new Map;n.forEach((c,m)=>{o.has(c)||o.set(c,m)});let i=new Set(n),a=r.filter(c=>i.has(c)&&!s.has(c)),d=MF(a.map(c=>o.get(c))),l={...t,inPlace:new Set([...d].map(c=>a[c])),inList:new Set(r)};n.forEach((c,m)=>rq(e,l,c,m))},oq=(e,t,n,r)=>{let{ctx:s,moves:o,listOf:i}=e,a=Se(r),d=a.map(m=>m.key),l={parent:t,relation:n,order:d,owned:new Set(a.filter(m=>m.owned).map(m=>m.key)),arriving:new Set(d.filter(m=>{let f=o.get(m);return f?.to.id===t&&f.to.relation===n})),list:i(t,n)};lp(r)||s.has(t)&&lp(s.C[t].relations?.[n]??{"@@":[]})?eq(e,l,r):sq(e,l)},iq=(e,t)=>{let{ctx:n,moves:r,moved:s}=e;for(let o of t){let i=n.W.get(o);for(let a of Object.keys(i.relations).sort(ie))o===n.rootId&&Lt(a)||oq(e,o,a,i.relations[a])}for(let o of r.keys())if(!s.has(o))throw new Error(`The move of ${o} found no place in the workspace walk.`)},Jv=e=>Jn(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.filter(r=>!r.owned).map(r=>({key:r.key,modelId:r.modelId??null}))]))),aq=(e,t)=>{let n={},r=[];for(let s of[...new Set([...Object.keys(e),...Object.keys(t)])].sort(ie))t[s]===void 0?r.push(s):(e[s]===void 0||!zr(e[s],t[s]))&&(n[s]=t[s]);return{set:n,unset:r}},dq=(e,t,n)=>{let r=new Set(Se(n).map(o=>o.key)),s=Object.fromEntries(Object.entries(n).map(([o,i])=>[o,i.map(a=>e.opRef(a))]));for(let[o,i]of Object.entries(t))for(let a of i)a.owned&&e.vanished.has(a.key)&&!r.has(a.key)&&(s[o]=[...s[o]??[],e.opRef(a)]);return Jn(s)},lq=(e,t,n)=>{let r={},s=[],o=new Set([...Object.keys(e.C[t].relations??{}),...Object.keys(n.relations)]);for(let i of[...o].sort(ie)){if(t===e.rootId&&Lt(i))continue;let a=zn(e.C[t],i),d=n.relations[i]??{};if(zr(Jv(a),Jv(d)))continue;let l=dq(e,a,d);Object.keys(l).length===0?s.push(i):r[i]=l}return{set:r,unset:s}},cq=(e,t)=>{let n=e.W.get(t),r=aq(Ro(e.C[t].attributes),Ro(n.attributes)),s=lq(e,t,n),o={...Object.keys(r.set).length>0&&{attributes:r.set},...Object.keys(s.set).length>0&&{relations:s.set}},i={...r.unset.length>0&&{attributes:r.unset},...s.unset.length>0&&{relations:s.unset}};if(!(Object.keys(o).length===0&&Object.keys(i).length===0))return{op:"update",element:t,...Object.keys(o).length>0&&{set:o},...Object.keys(i).length>0&&{unset:i}}},mq=(e,t,n)=>{for(let r of t){if(!e.has(r)||e.pinnedVia.has(r))continue;let s=cq(e,r);s!==void 0&&n.push(s)}},fq=(e,t,n)=>{let r=[],s=new Set([n]),o=[n];for(let i=o.shift();i!==void 0;i=o.shift())for(let a of t.get(i)??[])!s.has(a)&&e.vanished.has(a)&&e.ownersNow(a).every(d=>s.has(d.id))&&(s.add(a),r.push(a),o.push(a));return r},pq=(e,t)=>{let{C:n,vanished:r,rootId:s}=e,o=Dc(e.currentOwners),i=Qv(a=>Object.fromEntries(Object.keys(n[a]?.relations??{}).map(d=>[d,zn(n[a],d)])));i.visit(s),Object.keys(n).sort(ie).forEach(i.visit);for(let a of i.order){if(!r.has(a))continue;let d=e.ownersNow(a);d.length>0&&d.every(l=>r.has(l.id))||t.push({op:"delete",element:a,removes:fq(e,o,a)})}},_t=(e,t,{createOrder:n="workspace"}={})=>{let r=e.rootId;if(t.rootKey!==r)throw new kt([{code:"root-changed",message:`The root element in model.yaml has to keep the model's root id ${r}.`,elementId:r}]);let s=DF(e,t);jF(s,s.W.get(r));let o=new Map;UF(s,o),VF(s);let i=GF(s,t),a=YF(s,i);if(s.problems.length>0)throw new kt(s.problems);let d={ops:[],together:[],warnings:[]},l=XF(s),c=n==="references"?JF(a):a.map((m,f)=>[f]);return QF(s,a,c,l,d),iq({ctx:s,moves:o,listOf:l,staged:d,moved:new Set},i),mq(s,i,d.ops),pq(s,d.ops),d};import{createHash as uq,randomUUID as hq}from"node:crypto";var mp=1e3,gq=8*1024*1024,fp=Math.floor(gq*.9),yq=(e,t,n)=>uq("sha256").update(hd({format:Nt,modelId:e,baseCommitId:t,ops:n})).digest("hex"),dR=e=>"id"in e?e.id:e.new,wq=(e,t)=>{let n=new Map,r=s=>{n.set(dR(s.element),"id"in s.element?s.element.id:t()),Object.values(s.children??{}).flat().forEach(r)};return e.forEach(s=>s.op==="create"&&r(s.element)),n},bq=(e,t)=>{let n=i=>"id"in i?i.id:t.get(i.new),r=i=>"new"in i?{id:t.get(i.new),owned:i.owned}:{id:i.id,owned:i.owned,...i.modelId!==void 0&&{modelId:i.modelId}},s=i=>Object.fromEntries(Object.entries(i).map(([a,d])=>[a,Object.fromEntries(Object.entries(d).map(([l,c])=>[l,c.map(r)]))])),o=i=>({key:dR(i.element),type:i.type,...i.attributes&&{attributes:i.attributes},...i.relations&&{relations:s(i.relations)},...i.children&&{children:Object.fromEntries(Object.entries(i.children).map(([a,d])=>[a,d.map(o)]))}});return e.map(i=>{switch(i.op){case"create":return[{kind:"create",parent:{id:n(i.parent)},relation:i.relation,element:o(i.element)}];case"move":return[{kind:"move",element:n(i.element),parent:{id:n(i.parent)},relation:i.relation,from:{id:n(i.from.parent),relation:i.from.relation},...i.position!==void 0&&{position:i.position}}];case"update":return[...i.set?[{kind:"set",element:i.element,...i.set.attributes&&{attributes:i.set.attributes},...i.set.relations&&{relations:s(i.set.relations)}}]:[],...i.unset?[{kind:"unset",element:i.element,...i.unset.attributes&&{attributes:i.unset.attributes},...i.unset.relations&&{relations:i.unset.relations}}]:[]];case"delete":return[{kind:"delete",element:i.element,recursive:!0}]}})},kq=(e,t,n)=>{let r={...e.elements},s=Object.fromEntries([...So(e.elements)].map(([d,l])=>[d,{owners:l}])),o=d=>"id"in d?d.id:n.get(d.new),i=(d,l)=>{let c=o(d.element);r[c]={id:c,type:d.type},s[c]={owners:[l]};for(let[m,f]of Object.entries(d.children??{}))f.forEach(h=>i(h,{id:c,relation:m}))};for(let d of t)d.op==="create"&&i(d.element,{id:o(d.parent),relation:d.relation});return{elements:r,elementIndexEntries:s}},lR=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g,cR=e=>{let t=[],n=r=>{r.id!==void 0&&t.push(r.id),Object.values(r.ownedElements??{}).flat().forEach(n)};return e.forEach(r=>r.type==="ELEMENT_CREATE"&&n(r.creation)),t},Eq=e=>e.flatMap(t=>{switch(t.type){case"ELEMENT_UPDATE":case"ELEMENT_DELETE":return[t.elementId];case"ELEMENT_MOVE":return t.move.elements.map(n=>n.id);default:return[]}}),Cq=e=>Buffer.byteLength(JSON.stringify(e),"utf8"),vq=(e,t)=>{let n=0;return t.map(r=>(n+=r,e.slice(n-r,n)))},Rq=(e,t)=>{let n=new Map;t.forEach(s=>s.forEach(o=>n.set(o,s)));let r=[];for(let s=0;s<e;){let o=n.get(s)??[s];r.push([...o]),s=(o.at(-1)??s)+1}return r},aR=(e,t,n,{mintId:r=hq}={})=>{let{ops:s}=t,o=wq(s,r),i=bq(s,o),a=i.flat(),d=[],l=v=>{d.push(o.get(v.key)),Object.values(v.children??{}).flat().forEach(l)};a.forEach(v=>v.kind==="create"&&l(v.element));let c=Ms(a,kq(e,s,o),{mintId:()=>{let v=d.shift();if(v===void 0)throw new Error("The translation asked for more element ids than the plan creates.");return v}});if(c.actions.length!==a.length||[...o].some(([v,T])=>c.ids[v]!==T))throw new Error("The translation did not map the plan one edit to one action.");let m=vq(c.actions,i.map(v=>v.length)),f=Rq(s.length,t.together),h=[],p;for(let v of f){let T=v.flatMap(E=>m[E]),N=T.reduce((E,S)=>E+Cq(S)+1,0);if(T.length>mp||N>fp){let E=v.length>1?`${v.length} new elements that reference each other`:"One operation";throw new u(`${E} would need ${T.length} actions of ${N} bytes in one change, more than a change carries (${mp} actions, ${fp} bytes).`,{exitCode:b.Validation,type:"change-too-large",hint:"Push the workspace in parts: leave part of the new content out, push, then add the rest.",details:{ops:v}})}(p===void 0||p.actions.length+T.length>mp||p.bytes+N>fp)&&(p={number:h.length+1,ops:[],actions:[],bytes:2,dependsOn:[]},h.push(p)),p.ops.push(...v),p.actions.push(...T),p.bytes+=N}let g=So(e.elements),w=v=>`${v.id}\0${v.relation}`,k=v=>v.flatMap(T=>{switch(T.type){case"ELEMENT_CREATE":return T.creation.owner?[w(T.creation.owner)]:[];case"ELEMENT_MOVE":return[w(T.move.targetParent),...T.move.elements.map(N=>w(N.parent))];case"ELEMENT_DELETE":return(g.get(T.elementId)??[]).map(w);default:return[]}}),C=new Map,R=new Map,$=new Map;for(let v of h){let T=new Set(JSON.stringify(v.actions).match(lR)??[]),N=v.actions.flatMap(E=>E.type==="ELEMENT_MOVE"&&E.move.position!==void 0?[w(E.move.targetParent)]:[]);v.dependsOn=[...new Set([...[...T].flatMap(E=>C.has(E)?[C.get(E)]:[]),...[...T].flatMap(E=>R.get(E)??[]),...N.flatMap(E=>$.get(E)??[])])].sort((E,S)=>E-S),cR(v.actions).forEach(E=>C.set(E,v.number));for(let E of Eq(v.actions))R.set(E,[...new Set([...R.get(E)??[],v.number])]);for(let E of k(v.actions))$.set(E,[...new Set([...$.get(E)??[],v.number])])}return{hash:yq(n.modelId,n.baseCommitId,s),ops:s,chunks:h,ids:o,warnings:t.warnings}},Sq=e=>{let t=new Map;return e.chunks.forEach(n=>cR(n.actions).forEach(r=>t.set(r,n.number))),e.chunks.some(n=>n.actions.some(r=>r.type==="ELEMENT_CREATE"&&(JSON.stringify(r).match(lR)??[]).some(s=>(t.get(s)??0)>n.number)))},wd=(e,t,n,r={})=>{let s=aR(e,_t(e,t),n,r);return s.chunks.length<2||!Sq(s)?s:aR(e,_t(e,t,{createOrder:"references"}),n,r)};var bd=e=>({create:e.filter(t=>t.op==="create").length,move:e.filter(t=>t.op==="move").length,update:e.filter(t=>t.op==="update").length,delete:e.filter(t=>t.op==="delete").length}),$o=e=>["create","move","update","delete"].filter(t=>e[t]>0).map(t=>P(e[t],t)).join(", "),kd=(e,t={})=>{let n={};for(let r of JSON.stringify(e).match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g)??[])Object.hasOwn(t,r)&&(n[r]=t[r]);return n},fR=e=>1+Object.values(e.children??{}).flat().reduce((t,n)=>t+fR(n),0),mR=e=>typeof e=="string"?e:"id"in e?e.id:e.new,Ed=(e,t)=>{let n=new Map,r=o=>{let i=gd(o.attributes?.name),a=i===void 0?"":` "${y(i)}"`;n.set(mR(o.element),`new ${o.type}${a}`),Object.values(o.children??{}).flat().forEach(r)};e.forEach(o=>o.op==="create"&&r(o.element));let s=o=>{let i=mR(o),a=n.get(i);return a!==void 0?a:Object.hasOwn(t,i)?`${y(t[i])} (${i.slice(0,8)})`:i};return e.map(o=>{switch(o.op){case"create":{let i=fR(o.element)-1;return`+ create ${s(o.element.element)} under ${s(o.parent)} via ${o.relation}`+(i>0?`, with ${P(i,"nested element")}`:"")}case"move":{let i=s(o.from.parent)===s(o.parent)&&o.from.relation===o.relation?"within its list":void 0,a=o.position===void 0?"at the end":`at position ${o.position}`;return i?`> move ${s(o.element)} ${i}, ${a}`:`> move ${s(o.element)} from ${s(o.from.parent)}.${o.from.relation} to ${s(o.parent)}.${o.relation}, ${a}`}case"update":{let i=[...Object.keys(o.set?.attributes??{}).map(a=>`set ${a}`),...Object.keys(o.set?.relations??{}).map(a=>`set ${a}`),...(o.unset?.attributes??[]).map(a=>`unset ${a}`),...(o.unset?.relations??[]).map(a=>`unset ${a}`)];return`~ update ${s(o.element)}: ${i.join(", ")}`}case"delete":return`- delete ${s(o.element)}`+(o.removes.length>0?`, and ${P(o.removes.length,"element")} it owns`:"")}})};var Jr={name:"dir",type:"string",description:"The workspace directory (default: the current directory)."},pR=new WeakMap,pp=e=>{let t=Yv(e.cwd,e.args.dir),n=Vv(t);pR.set(e,{dir:t,...n&&{state:n}}),n!==void 0&&Iq(e,t,n)},Cd=e=>{pp(e),xo(e)},Iq=(e,t,n)=>{let r=e.env[B.host],s=e.globals.host??(r!==void 0&&r!==""?r:void 0);if(s!==void 0){let o=cs(s).host;if(o!==n.host)throw new u(`The workspace in ${W(t)} was pulled from ${n.host}, and this run targets ${W(o)}.`,{exitCode:b.Usage,hint:`Run it against ${n.host}, or pull the model from the other instance into another directory.`});return}if(n.host===cs(ns).host){e.globals.host=n.host;return}if(le(e.env))throw new u(`In a machine-auth run the host must be set explicitly: pass --host or set ${B.host}. The workspace's ${W(vo(t))} is not a trusted source for where machine credentials are sent.`);e.io.err(`note: using host '${W(n.host)}' from ${W(vo(t))}.
237
+ `),e.globals.host=n.host},up=e=>{let t=pR.get(e);if(t===void 0)throw new Error("The workspace is loaded before the command runs.");return t},xo=e=>{let{dir:t,state:n}=up(e);if(n===void 0)throw new u(`${W(t)} is not a model workspace: it has no .modeldesk/workspace.json.`,{exitCode:b.Usage,hint:"Run 'modeldesk model pull <model> <dir>' to make one, or pass the workspace's directory."});return{dir:t,state:n}},To=async(e,t,n)=>{let r={model:n.model.id,ref:{kind:"branch-id",id:n.branch.id,name:n.branch.name},text:`${n.model.id}@${n.branch.name}`};try{return await lt(e,r)}catch(s){if(!(s instanceof u)||s.type!==Pl)throw s;let o=s.details.namesake,i=`modeldesk model pull ${n.model.id}@${y(o?.name??"<branch>")} ${W(t)} --force`;throw new u(`${s.reason} The workspace in ${W(t)} tracks it, so nothing was read or staged.`,{exitCode:s.exitCode,type:s.type,details:s.details,hint:`Copy aside any edits you have not pushed, then pull ${o?"that branch":"a branch that exists"} over the workspace: '${i}'.`})}},Xn=e=>e.read.branch.head.rootElement.revision,vd=(e,t,n)=>{if(n.head===t.baseCommitId)return{kind:"fresh"};if(t.baseRootRevision===Xn(n))return{kind:"rebound",from:t.baseCommitId};try{return _t(jt(n.read),gn(e,t)).ops.length===0?{kind:"rebound",from:t.baseCommitId}:{kind:"stale"}}catch(r){if(r instanceof kt||r instanceof Je)return{kind:"stale"};throw r}},Xr=({draft:e,branch:t})=>re({ref:e!==void 0&&e.headCommitId!==t.head?{kind:"draft",draft:e}:{kind:"branch",branch:t},draft:e}),Rd=({draft:e,branch:t,model:n})=>e===void 0||e.baselineCommitId===t.head?void 0:`Your draft of ${y(n.name)} is based on ${e.baselineCommitId}, and ${y(t.name)} has moved on to ${t.head}.`,Sd=(e,t,n,r)=>`The workspace was rebound: ${st(e,t)} moved from ${n} to ${r} and holds exactly what the files hold, so its base is now ${r}.`,Id=(e,t,n)=>{let r={...t,model:n.model,branch:{id:n.branch.id,name:n.branch.name},baseCommitId:n.head,baseRootRevision:Xn(n)};return hn(e,r),r},jt=e=>{let t=e.rootElementId??Object.values(e.elements).find(n=>n.type==="@Root")?.id;if(t===void 0)throw new u(`The read of ${e.name} carries no root element.`);return{rootId:t,elements:e.elements,...e.elementLabels&&{labels:e.elementLabels}}},$q=e=>{let t=new Set,n=r=>{for(let[s,o]of Object.entries(r??{}))o?.package===!0&&t.add(s)};return n(e.metamodel?.elementTypes),e.metamodelExtensions?.forEach(r=>n(r.elementTypes)),t},$d=e=>{let t=jt(e);return{modelName:e.name,rootId:t.rootId,elements:t.elements,...t.labels&&{labels:t.labels},indexOwners:n=>e.elementIndexEntries[n]?.owners,packageTypes:$q(e)}},st=(e,t)=>e.kind==="draft"?`your draft of ${t} (aimed at ${e.branch.name})`:e.kind==="branch"?`the head of branch ${e.name} of ${t}`:`commit ${e.id} of ${t}`;var uR=q({path:["model","diff"],effect:"read",summary:"Show what pushing a workspace would change",description:"Compares the workspace files with the branch the workspace was pulled from (your draft on it while you hold one, otherwise the branch head) and lists the operations a push stages, in order: creates, moves, updates and deletes. When that head moved since the workspace's base (an edit in the app, an 'el' command, an undo), the workspace is stale and the list is not pushable, since it would revert those changes; when it moved and holds exactly what the files hold (the draft they reflected was committed), the base moves to it and is reported as rebound. --exit-code exits 1 when there are differences, as git diff does.",positionals:[Jr],flags:{"exit-code":{type:"boolean",description:"Exit 1 when the workspace differs from its target, 0 when not."}},prepare:Cd,examples:["modeldesk model diff","modeldesk model diff shacl-workspace --exit-code"],run:e=>X(async()=>{let t=xo(e),{dir:n}=t,{state:r}=t,s=await To(e,n,r),o=vd(n,r,s),i=o.kind==="rebound"?{from:o.from}:void 0;i&&(r=Id(n,r,s));let a=o.kind==="stale",d=gn(n,r),l=jt(s.read),c,m;try{c=wd(l,d,{modelId:r.model.id,baseCommitId:s.head})}catch(g){if(!(a&&g instanceof kt))throw g;m={message:g.reason,errors:g.problems}}let f=c?.ops??[],h={model:s.model,ref:Xr(s),dir:n,baseCommitId:r.baseCommitId,...i&&{rebound:i},headCommitId:s.head,stale:a,pushable:!a,ops:f,counts:bd(f),chunks:c?.chunks.length??0,...!a&&c!==void 0&&f.length>0&&{planHash:c.hash},labels:kd(f,l.labels),warnings:c?.warnings??[],...m&&{refused:m},url:te(e.instance(),{kind:"model",modelId:r.model.id})},p=f.length>0||m!==void 0;return{result:h,...e.flags["exit-code"]&&p&&{exitCode:b.Failure}}}),render:e=>{let t=y(e.model.name),n=[];return e.rebound&&n.push(Sd(e.ref,t,e.rebound.from,e.headCommitId)),e.stale&&n.push(`The workspace is stale: ${st(e.ref,t)} moved from ${e.baseCommitId} to ${e.headCommitId} since it was pulled. The operations below are not pushable: they would revert what changed in between. Push nothing; re-pull with 'modeldesk model pull' (--force discards local edits).`),e.refused!==void 0?n.push(`Note: the files also change what a push cannot stage: ${e.refused.message}`):e.ops.length===0?n.push(`No differences with ${st(e.ref,t)}.`):(n.push(`${e.ops.length} operation(s) against ${st(e.ref,t)}: ${$o(e.counts)}`+(e.chunks>1?`, in ${e.chunks} changes`:"")+".",...Ed(e.ops,e.labels).map(r=>` ${r}`)),e.counts.delete>0&&n.push("Deletes are pushed only with --allow-delete."),e.planHash!==void 0&&n.push(`plan: ${e.planHash}`)),n.push(...e.warnings.map(r=>`Note: ${r}`)),n.join(`
238
+ `)}});import{basename as Jq}from"node:path";import{randomUUID as Oq}from"node:crypto";import{chmodSync as Mq,closeSync as Nq,fchmodSync as Pq,fsyncSync as Lq,openSync as Dq,renameSync as kR,rmSync as hp,statSync as _q,writeSync as jq}from"node:fs";import{dirname as ER,join as gp,resolve as gR}from"node:path";import{existsSync as xq,mkdirSync as Tq}from"node:fs";import{dirname as hR,resolve as Aq}from"node:path";var xd=(e,t)=>{let n=[];for(let r=Aq(e);!xq(r)&&hR(r)!==r;r=hR(r))n.unshift(r);return Tq(e,{recursive:!0,mode:t})===void 0?[]:n};var Td="modeldesk model export --help",yR=e=>{try{return _q(e)}catch{return}},CR=e=>{let{output:t,compressed:n,json:r,cwd:s}=e;if(n){if(t===void 0)throw I("--compressed writes a ZIP file and needs -o <file>; it never writes to stdout.",Td);let a=gR(s,t);if(yR(a)?.isDirectory())throw I(`-o ${t} is a directory; --compressed writes one ZIP file, so name the file.`,Td);return{kind:"zip",file:a}}if(t===void 0){if(r)throw I("--json needs -o <dir>: stdout carries the result document, so the exported documents cannot share it.",Td);return{kind:"stdout"}}let o=gR(s,t),i=yR(o);if(i!==void 0&&!i.isDirectory())throw I(`-o ${t} is a file; without --compressed, -o names the directory to write into.`,Td);return{kind:"directory",dir:o}},Fq=/[\u0000-\u001f\u007f-\u009f<>:"|?*]/,qq=/^(con|prn|aux|nul|com\d|lpt\d)(\..*)?$/i,Wq=e=>{if(e===""||e==="."||e==="..")return"it is not a file name";if(Fq.test(e))return'it holds a control character or one of < > : " | ? *';if(e.includes("/")||e.includes("\\"))return"it names a path, not a file";if(qq.test(e))return"Windows reserves it for a device";if(/[. ]$/.test(e))return"it ends in a dot or a space, which Windows drops"},vR=e=>{for(let{filename:t}of e){let n=Wq(t);if(n!==void 0)throw new u(`Refusing to write the document named ${JSON.stringify(t)}: ${n}.`,{hint:"Nothing was written. Report the format to ModelDesk: its documents should carry portable file names.",details:{filename:t}})}},RR=e=>{let t=new Map;for(let{filename:n}of e){let r=n.normalize("NFC").toLowerCase(),s=t.get(r);if(s!==void 0)throw new u(`The export holds documents named ${JSON.stringify(s)} and ${JSON.stringify(n)}, which one directory cannot hold apart.`,{hint:"Nothing was written, since the second would overwrite the first.",details:{filenames:[s,n]}});t.set(r,n)}},SR=e=>new u(`The export produced ${e.length} documents, and stdout takes one.`,{exitCode:b.Usage,hint:"Pass -o <dir> to write each under its file name, or --compressed -o <file> for one ZIP.",details:{filenames:e.map(t=>t.filename)}}),Bq=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g,IR=(e,t)=>t?e.replace(Bq,""):e,Ad=e=>e.code??e.message,wR=420,bR=493,$R=e=>{xd(e,bR).forEach(t=>Mq(t,bR))},xR=e=>gp(ER(e),`.modeldesk-${Oq().slice(0,8)}.tmp`),TR=(e,t)=>{let n=Dq(e,"wx",wR);try{Pq(n,wR);let r=0;for(;r<t.length;)r+=jq(n,t,r,t.length-r);Lq(n)}finally{Nq(n)}},AR=(e,t)=>{$R(ER(e));let n=xR(e);try{TR(n,t),kR(n,e)}catch(r){throw hp(n,{force:!0}),new u(`Could not write ${e} (${Ad(r)}).`)}},OR=(e,t)=>{try{$R(e)}catch(o){throw new u(`Could not create ${e} (${Ad(o)}).`,{details:{renamed:[]}})}let n=[],r=()=>n.forEach(({temp:o})=>hp(o,{force:!0}));for(let{filename:o,contents:i}of t){let a=gp(e,o),d=Buffer.from(i,"utf8"),l=xR(a);try{TR(l,d)}catch(c){throw hp(l,{force:!0}),r(),new u(`Could not write ${a} (${Ad(c)}); nothing was written.`,{details:{failed:o,renamed:[]}})}n.push({temp:l,written:{filename:o,path:a,bytes:d.length}})}let s=[];for(;n.length>0;){let{temp:o,written:i}=n[0];try{kR(o,i.path)}catch(a){throw r(),new u(`Could not move ${i.path} into place (${Ad(a)}); `+(s.length===0?"nothing was written.":`${s.length} document(s) before it were.`),{details:{failed:i.filename,renamed:s}})}s.push(i.filename),n.shift()}return t.map(({filename:o,contents:i})=>({filename:o,path:gp(e,o),bytes:Buffer.byteLength(i,"utf8")}))};var MR=(e,t,n)=>{let r=t.toLowerCase(),s=e.filter(i=>Y(t)?i.id.toLowerCase()===r:i.name.toLowerCase()===r);if(s.length===1)return s[0];let o=[...e].sort((i,a)=>(i.sortOrder??0)-(a.sortOrder??0)||i.name.localeCompare(a.name)).map(({id:i,name:a,mediaType:d,fileExtension:l})=>({id:i,name:a,...d?{mediaType:d}:{},...l?{fileExtension:l}:{}}));throw s.length>1?new u(`${s.length} ${n} formats are named '${t}'; pass --format with an id.`,{exitCode:b.Usage,details:{formats:o.filter(i=>i.name.toLowerCase()===r)}}):new u(`${n} has no encoding format '${t}'.`,{exitCode:b.NotFound,hint:o.length===0?`${n} offers no encoding formats.`:`Its formats: ${o.map(i=>i.name).join(", ")}.`,details:{formats:o}})};var NR=e=>{let t=String.raw`'\''`;return`'${e.replaceAll("'",t)}'`},Hq=new Set(["sig","key","apikey","api_key","api-key"]),Uq=["auth","token","secret","password","signature","credential"],Qr="REDACTED",Vq="<unparseable URL redacted>",PR=e=>{let t=e.toLowerCase();return Hq.has(t)||Uq.some(n=>t.includes(n))},Gq=(e,t,n)=>t===-1||n!==-1&&n<t?"":e.slice(t+1,n===-1?void 0:n),Ao=e=>{try{return decodeURIComponent(e.replaceAll("+"," "))}catch{return e}},wn=e=>{let t;try{t=new URL(e)}catch{return Vq}let n=!1;(t.username!==""||t.password!=="")&&(t.username=Qr,t.password="",n=!0),t.hash!==""&&(t.hash="",n=!0);for(let r of new Set(t.searchParams.keys()))if(PR(r)){let s=t.searchParams.getAll(r).length;t.searchParams.delete(r);for(let o=0;o<s;o+=1)t.searchParams.append(r,Qr);n=!0}return n?t.toString():e},Kq=e=>{let t=[[e,wn(e)]],n=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)@/i.exec(e)?.[1];n&&t.push([`${n}@`,`${Qr}@`],[`${Ao(n)}@`,`${Qr}@`]);let r=e.indexOf("#"),s=r===-1?"":e.slice(r+1);s!==""&&t.push([`#${s}`,""]);let o=e.indexOf("?"),i=Gq(e,o,r);for(let a of[...i.split("&"),...s.split("&")]){let d=a.indexOf("="),l=d===-1?a:a.slice(0,d),c=d===-1?"":a.slice(d+1);c!==""&&PR(Ao(l))&&t.push([a,`${l}=${Qr}`],[`${Ao(l)}=${Ao(c)}`,`${Ao(l)}=${Qr}`])}return t.filter(([a])=>a!=="").sort(([a],[d])=>d.length-a.length)},Od=e=>{if(e===void 0)return n=>n;let t=Kq(e);return n=>t.reduce((r,[s,o])=>r.split(s).join(o),n)},yn=(e,t)=>typeof e=="string"?t(e):Array.isArray(e)?e.map(n=>yn(n,t)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,yn(r,t)])):e;var Md=e=>({ERROR:e.filter(t=>t.logLevel==="ERROR").length,WARN:e.filter(t=>t.logLevel==="WARN").length,INFO:e.filter(t=>t.logLevel==="INFO").length}),yp=e=>{let t=[e.modelElementId?`element ${e.modelElementId}`:void 0,e.property?`property ${e.property}`:void 0].filter(Boolean),n=e.detailMessage&&e.detailMessage!==e.title?`: ${e.detailMessage}`:"",r=t.length>0?` (${t.join(", ")})`:"";return y(`${e.logLevel} [${e.code}] ${e.title}${n}${r}`)},Oo=e=>e.map(t=>`${yp(t)}
239
+ `).join("");var wp={initialMs:500,maxMs:5e3,factor:1.5},Yq=(e,t)=>({settled:!1,...e===void 0?{}:{last:e},...t===void 0?{}:{lastError:t}}),Mo=async({read:e,settled:t,deadline:n,clock:r,interval:s=wp,onRead:o,tolerate:i=()=>!1})=>{let a=s.initialMs,d,l;for(;;){try{let m=await e();if(d=m,l=void 0,o?.(m),t(m))return{settled:!0,value:m}}catch(m){if(!i(m))throw m;l=m}let c=n-r.now();if(c<=0)return Yq(d,l);await r.sleep(Math.min(a,c)),a=Math.min(s.maxMs,a*s.factor)}};var zq=new Set(["INITIALIZED","PROCESSING"]),LR=e=>!zq.has(e.status),DR=e=>e.status==="COMPLETED"||e.status==="ERROR",No=e=>e instanceof u&&e.exitCode===b.Transient,bp=(e,t)=>e.now()+t*1e3,Po=e=>`modeldesk model imports show ${e}`,Zr=(e,t)=>`modeldesk model imports complete ${e} --name ${t===void 0?"<name>":NR(t)}`,kp=(e,t)=>t?[...e]:e.map(yp),Ep=e=>Od(e.source.type==="remote"?e.source.location:void 0),Lo=e=>yn(e,Ep(e)),_R=(e,t,n)=>{let r=Lo(e);return new u(`Import ${r.id} failed ${t==="parse"?"while parsing":"while completing"}: ${r.errorMessage??"the server gave no reason"}`,{details:{importId:r.id,status:r.status,...r.errorMessage?{errorMessage:r.errorMessage}:{},logEntries:kp(r.logEntries??[],n)}})},jR=(e,t,n,r,s,o)=>{let i=o instanceof u?` The last status check failed: ${o.reason}`:"";return new u(`Import ${e} is still ${t} after ${r} s; it continues on the server.${i}`,{exitCode:b.Transient,hint:n==="parse"?`Check it with '${Po(e)}' and, once it is READY, finish it with '${Zr(e,s)}'. Do not run the import again; that starts a second one.`:`Check it with '${Po(e)}'; it names the new model once the completion lands.`,details:{importId:e,status:t,phase:n}})},FR=(e,t,n,r={})=>new u(`${e.reason} (import ${t})`,{exitCode:b.Transient,hint:n,type:e.type,requestId:e.requestId,details:{...e.details,importId:t,...r}}),qR=(e,t)=>{let n;return r=>{r.status!==n&&(n=r.status,e.note(`Import ${t}: ${r.status}`))}},WR=async(e,t)=>{try{return await e.api.imports.create(t)}catch(n){throw No(n)?new u(n.reason,{exitCode:b.Transient,hint:"The import may exist anyway: run 'modeldesk model imports list' before retrying, then complete or delete the one that is there rather than starting another.",type:n.type,requestId:n.requestId,details:n.details}):n}},BR=async(e,t,n,r,s)=>{let o=qR(e,t.id);o(t);let i=t;if(!LR(t)){let a=await Mo({read:()=>e.api.imports.get(t.id),settled:LR,deadline:n,clock:e.clock,onRead:o,tolerate:No});if(!a.settled){let d=(a.last??t).status;throw jR(t.id,d,"parse",r,s,a.lastError)}i=a.value}if(i.status==="ERROR")throw _R(i,"parse",e.json);return i},Cp=async(e,t,n,r,s)=>{e.note(`Completing import ${t} as '${n}'.`);let o;try{o=await e.api.imports.complete(t,n)}catch(a){throw No(a)?FR(a,t,`Check it with '${Po(t)}': once it is COMPLETED it names the model; while it is still READY, run '${Zr(t,n)}' again.`,{phase:"completion"}):a}let i=o;if(!DR(o)){let a=await Mo({read:()=>e.api.imports.get(t),settled:DR,deadline:r,clock:e.clock,onRead:qR(e,t),tolerate:No});if(!a.settled){let d=(a.last??o).status;throw jR(t,d,"completion",s,n,a.lastError)}i=a.value}if(i.status==="ERROR")throw _R(i,"completion",e.json);if(i.modelId===void 0)throw new u(`Import ${t} completed without naming the model it created.`,{hint:`Run '${Po(t)}'.`});return i},HR=async(e,t,n)=>{try{return await t()}catch(r){throw No(r)?FR(r,e,`The import is READY: review it with '${Po(e)}' and finish it with '${Zr(e,n)}'.`):r}},vp=(e,t)=>e instanceof u?new u(t(e.reason),{exitCode:e.exitCode,...e.hint===void 0?{}:{hint:t(e.hint)},type:e.type,requestId:e.requestId,details:yn(e.details,t)}):e;var Xq="modeldesk model export --help",Qq=async(e,t,n)=>{if(Y(t))return{id:t};if(le(e.env)!==void 0)throw I(`--mapping '${t}' is a name, and mappings can be looked up by name only in a user session.`,Xq);let{items:r}=await e.api().modelMappings.list({sourceMetamodel:n}),s=r.filter(o=>o.name.toLowerCase()===t.toLowerCase());if(s.length===1)return{id:s[0].id,name:s[0].name};throw s.length>1?new u(`${s.length} mappings are named '${t}'; pass --mapping with an id.`,{exitCode:b.Usage,details:{candidates:s.map(({id:o,name:i})=>({id:o,name:i}))}}):new u(`No mapping named '${t}' applies to this model's metamodel.`,{exitCode:b.NotFound,hint:r.length===0?"None does.":`Mappings that do: ${r.map(o=>o.name).join(", ")}.`,details:{candidates:r.map(({id:o,name:i})=>({id:o,name:i}))}})},Zq=e=>CR({output:e.flags.output,compressed:e.flags.compressed,json:e.globals.json,cwd:e.cwd}),eW=async(e,t)=>{let{metamodel:n}=await e.api().models.overview(t);if(n===void 0)throw new u("This is a metamodel-model; its encoding formats are not listed per metamodel.",{exitCode:b.NotFound});return{id:n.modelId,name:n.name}},UR=(e,t)=>{!e.globals.json&&t.length>0&&e.io.err(pe(Oo(t)))},tW=async(e,t,n,r,s)=>{e.warn("a compressed export carries no log entries, so encode errors cannot fail this command; use -o <dir> without --compressed where errors must fail the run (CI).");let o=await e.api().encoding.encodeCompressed(n,r);return AR(t,o),{...s,compressed:!0,documents:[{filename:Jq(t),path:t,bytes:o.length}],logEntries:[],logEntriesAvailable:!1,errorCount:0}},nW=(e,t,n,r)=>{if(!(t.length>0))throw new u(`The ${r.format} encoder produced no documents for ${r.model}.`,{hint:n.length>0?"Its log entries may say why.":"Check the model holds what the format encodes, or try another format.",details:{logEntries:kp(n,e.globals.json)}})},rW=(e,t,n)=>{let r=n[0]?` (${n[0].filename})`:"";e.io.err(pe(`Exported ${t.model} as ${t.format}${r}.
240
+ `))},sW=(e,t,n)=>{let r=n===1?"y":"ies";e.io.err(pe(`error: the ${t} encoder reported ${n} ERROR log entr${r}; the documents were written anyway. Pass --lenient to exit 0 for a format that reports them routinely.
241
+ `))},VR=q({path:["model","export"],effect:"read",summary:"Encode a model in a format of its metamodel",description:"Encodes a model in an encoding format of its metamodel (XSD, JSON Schema, Turtle, ...). One document goes to stdout, or to <dir>/<filename> with -o <dir>; several need -o <dir> or --compressed -o <file>. The encoder's log entries go to stderr (or the --json result, which needs -o). An ERROR entry exits 1, with the documents still written; --lenient exits 0 instead. --compressed returns no log entries, so it cannot fail on them. An export with no documents exits 1. Into a directory, a document whose server-supplied name is not a portable file name, or two names one directory cannot hold apart, exit 1 before anything is written. At a terminal, a document on stdout loses its control characters; piped or redirected it is byte-exact. Exports main only: a draft or a branch cannot be encoded yet.",positionals:[_(Ae)],flags:{format:{type:"string",required:!0,placeholder:"name|id",description:"The encoding format, by name (ignoring case) or id, among the model's metamodel's formats."},mapping:{type:"string",placeholder:"id",description:"A model mapping to apply before encoding, by id (a name works in a user session only)."},output:{type:"string",short:"o",placeholder:"path",description:"The directory to write the documents into, or the ZIP file with --compressed."},compressed:{type:"boolean",description:"Fetch the documents as one ZIP (needs -o <file>); it carries no log entries."},lenient:{type:"boolean",description:"Exit 0 even when the encoder reports ERROR log entries."}},examples:['modeldesk model export <model> --format "MIM-LD - Turtle" > buildings.ttl',"modeldesk model export <model> --format XSD -o xsd/","modeldesk model export <model> --format XSD --compressed -o schemas.zip"],run:async e=>{let{flags:t,args:n}=e,r=Zq(e),s=e.api(),o=await Z(e,n.model,Ae),i=re(o);i.note!==void 0&&e.warn(i.note);let a=o.id,d=await eW(e,a),{items:l}=await s.encodingFormats.list(d.id),c=MR(l,t.format,d.name),m=t.mapping===void 0?void 0:await Qq(e,t.mapping,d.id),f={format:c.id,mapping:m?.id},h={model:{id:a,name:o.name},ref:i,format:{id:c.id,name:c.name},...m?{mapping:m}:{}};if(r.kind==="zip")return{result:await tW(e,r.file,a,f,h)};let p=await s.encoding.encode(a,f),g=p.documents??[],w=p.logEntries??[],k={format:c.name,model:o.name};if(nW(e,g,w,k),r.kind==="stdout"&&g.length>1)throw UR(e,w),SR(g);let C;if(r.kind==="stdout"){let[{filename:T,contents:N}]=g;e.io.out(IR(N,e.stdoutIsTTY)),C=[{filename:T,path:"-",bytes:Buffer.byteLength(N,"utf8")}]}else vR(g),RR(g),C=OR(r.dir,g);UR(e,w);let R=Md(w).ERROR,$=R>0&&!t.lenient;return e.globals.json||(r.kind==="stdout"&&rW(e,k,C),$&&sW(e,c.name,R)),{result:{...h,compressed:!1,documents:C,logEntries:w,logEntriesAvailable:!0,errorCount:R},exitCode:$?b.Failure:b.Success}},render:e=>e.documents.every(t=>t.path==="-")?"":[`Exported ${e.model.name} as ${e.format.name}:`,...e.documents.map(t=>` ${t.path} ${t.bytes} bytes`)].join(`
242
+ `)});var Nd={now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))};import{readFileSync as oW,statSync as iW}from"node:fs";import{basename as aW,resolve as dW}from"node:path";var bn=["mim-ld","nl-sbb","dsv","shacl-ap"],Rp=["rdf-file",...bn],GR={".ttl":Rp,".trig":Rp,".nt":Rp,".n3":bn,".nq":bn,".rdf":bn,".rdfs":bn,".owl":bn,".jsonld":bn,".xml":[...bn,"xmi-2.1-file","mim-xml"],".xmi":["xmi-2.1-file"],".eap":["eap-file"],".eapx":["eap-file"],".xsd":["xsd-file"],".zip":["shacl-ap"]};var KR={ADDRESS:"an address (--url)",FILE:"an uploaded file"},Do=e=>e.length===0?"none":e.join(", "),zR=e=>e.kind==="file"?"FILE":"ADDRESS",Sp=(e,t)=>e.sourceKinds.includes(zR(t)),Pd=(e,t)=>new u(e,{exitCode:b.Usage,hint:"Pass --loader <name> to choose one.",details:{candidates:[...t]}}),Ip=e=>{let t="";if(e.kind==="file")t=e.filename;else try{t=decodeURIComponent(new URL(e.location).pathname.split("/").at(-1)??"")}catch{}let n=t.lastIndexOf(".");return n>0?t.slice(n).toLowerCase():void 0},YR=(e,t)=>{let n=e.map(s=>`'${s.name}' reads ${s.sourceKinds.map(o=>KR[o]).join(" or ")} only`),r=e.every(s=>s.sourceKinds.includes("ADDRESS"));return new u(`${n.join("; ")}, and this import gives ${KR[zR(t)]}.`,{exitCode:b.Usage,hint:r?"Publish the file at an address and pass that with --url.":"Download the file and pass its path instead of --url.",details:{loaders:e.map(s=>({name:s.name,sourceKinds:[...s.sourceKinds]}))}})},JR=({source:e,metamodelLoaders:t,metamodelLabel:n,explicit:r})=>{let s=t.map(c=>c.name);if(r!==void 0){let c=t.find(m=>m.name===r);if(c===void 0)throw Pd(`Loader '${r}' does not import into ${n}, which imports with ${Do(s)}.`,s);if(!Sp(c,e))throw YR([c],e);return{name:c.name,inferred:!1}}let o=Ip(e),i=o===void 0?void 0:GR[o],a=t.filter(c=>Sp(c,e)).map(c=>c.name);if(i===void 0){let c=o===void 0?"a source without a file extension":`'${o}' files`;throw Pd(`No loader is known for ${c}; ${n} imports with ${Do(s)}.`,a)}let d=t.filter(c=>i.includes(c.name));if(d.length===0)throw Pd(`None of the loaders for '${o}' files (${Do(i)}) imports into ${n}, which imports with ${Do(s)}.`,a);let l=d.filter(c=>Sp(c,e));if(l.length===0)throw YR(d,e);if(l.length>1){let c=l.map(m=>m.name);throw Pd(`Several loaders read '${o}' files into ${n}: ${Do(c)}.`,c)}return{name:l[0].name,inferred:!0}};var $p=70*1024*1024,XR=e=>`${(e/(1024*1024)).toFixed(1)} MB`,ZR=(e,t,n)=>{let r="modeldesk model import --help";if(e!==void 0&&t!==void 0)throw I("Pass a file or --url, not both.",r);if(t!==void 0){let i;try{i=new URL(t)}catch{throw I("--url takes an absolute http or https address, and this one does not parse.",r)}if(i.protocol!=="http:"&&i.protocol!=="https:")throw I(`--url takes an http or https address, got '${wn(t)}'.`,r);return{type:"remote",location:t}}if(e===void 0)throw I("Name the file to import, or pass --url.",r);let s=dW(n,e),o;try{let i=iW(s);if(!i.isFile())throw I(`'${e}' is not a file.`,r);if(i.size>$p)throw new u(`'${e}' is ${XR(i.size)}, and an upload is at most ${XR($p)} (the server takes 100 MB of request, and base64 adds a third).`,{exitCode:b.Usage,hint:"Publish the file at an address the server can reach and import it with --url, or split the model.",details:{bytes:i.size,maxBytes:$p}});o=oW(s)}catch(i){throw i instanceof u?i:I(`Cannot read '${e}' (${i.code??i.message}).`,r)}return{type:"upload",filename:aW(s),path:s,bytes:o.length,binaryData:o.toString("base64")}},eS=e=>e.type==="upload"?{kind:"file",filename:e.filename}:{kind:"url",location:e.location},lW=e=>e.type==="upload"?e.filename:wn(e.location),tS=async(e,t)=>{let{items:n}=await e.metamodels.list(),{id:r,name:s}=en(n,t,"metamodel",Zt);return{id:r,name:s}},xp=e=>e.standardVersion??e.name,Tp=async(e,t,n)=>{let r=await e.metamodelVersions.list(t.id);if(n===void 0){if(r.length===0)throw new u(`${t.name} has no release to import into.`,{exitCode:b.NotFound});return{...t,version:xp(r[0]),chosen:"newest"}}let s=r.find(o=>o.standardVersion===n||o.name===n);if(s===void 0){let o=r.map(xp);throw new u(`${t.name} has no release '${n}'.`,{exitCode:b.NotFound,hint:`Its releases: ${o.join(", ")||"none"}.`,details:{candidates:o}})}return{...t,version:xp(s),chosen:"given"}},nS=async(e,t,n)=>{if(n.length===0)return[];let{items:r}=await e.metamodelExtensions.list(t.id),s=new Map(r.map(a=>[a.id,a])),o=new Map;for(let a of n){let d=en(r,a.model,`extension of ${t.name}`,oa(t.id));o.set(d.id,{version:mr(a)})}let i=[...o.keys()];for(;i.length>0;){let a=s.get(i.shift());for(let d of a?.dependsOnExtensions??[])s.has(d)&&!o.has(d)&&(o.set(d,{requiredBy:a?.name}),i.push(d))}return Promise.all([...o].map(async([a,{version:d,requiredBy:l}])=>{let{name:c}=s.get(a);return{...await Tp(e,{id:a,name:c},d),...l?{requiredBy:l}:{}}}))},rS=async(e,t,n)=>Ak(tn(await e.accessTokenClaims()),t,n),sS=async(e,t,n,r)=>{let{items:s}=await e.modelLoaders.forMetamodel(t.id,t.version);return JR({source:eS(n),metamodelLoaders:s,metamodelLabel:`${t.name} ${t.version}`,explicit:r})},oS=e=>({metamodel:e.metamodel.id,metamodelVersion:e.metamodel.version,...e.extensions.length>0?{metamodelExtensions:e.extensions.map(t=>t.id)}:{},metamodelExtensionVersions:Object.fromEntries(e.extensions.map(t=>[t.id,t.version])),loader:e.loader.name,source:e.source.type==="upload"?{type:"upload",filename:e.source.filename,binaryData:e.source.binaryData}:{type:"remote",location:e.source.location},owner:{id:e.owner.id,type:"ORGANIZATION"}}),QR=e=>`${e.name} ${e.version}${e.chosen==="newest"?" (newest release)":""}`,iS=e=>{let t=Ip(eS(e.source)),n=e.loader.inferred?`${e.loader.name} (inferred from ${t})`:e.loader.name,r=e.owner.name??e.owner.id,s=e.owner.chosen==="only-seated"?` (your one organization with a ${e.metamodel.name} seat)`:"",o=a=>{let d=a.requiredBy?` (required by ${a.requiredBy})`:"";return`${QR(a)}${d}`},i=e.extensions.length===0?"":`, with ${e.extensions.map(o).join(", ")}`;return`Importing ${lW(e.source)} into ${QR(e.metamodel)}${i} with loader ${n}, owned by ${r}${s}.`};var cW=e=>e.type==="remote"?{type:"remote",location:wn(e.location)}:{type:"upload",...e.filename?{filename:e.filename}:{}},Ap=e=>({id:e.id,status:e.status,createdAt:e.createdAt,metamodel:{id:e.metamodelId,...e.metamodel?.name?{name:e.metamodel.name}:{},...e.metamodelVersion?{version:e.metamodelVersion}:{}},...e.loader?{loader:e.loader}:{},source:cW(e.source),owner:{id:e.owner.id,type:e.owner.type,...e.owner.name?{name:e.owner.name}:{}},...e.modelId?{modelId:e.modelId}:{}}),aS=(e,t)=>{let n=new Map((t.metamodelExtensions??[]).map(o=>[o.id,o.name])),r=t.metamodelExtensionVersions??{},s=t.metamodelExtensionIds??[...n.keys()];return{...Ap(t),...t.createdBy?{createdBy:{id:t.createdBy.id,...t.createdBy.name?{name:t.createdBy.name}:{}}}:{},extensions:s.map(o=>({id:o,...n.get(o)?{name:n.get(o)}:{},...r[o]?{version:r[o]}:{}})),...t.errorMessage?{errorMessage:t.errorMessage}:{},logEntries:t.logEntries??[],url:te(e,{kind:"import",importId:t.id}),...t.modelId?{model:{id:t.modelId,url:te(e,{kind:"model",modelId:t.modelId})}}:{}}},dS=e=>{let t=new Map;for(let r of Object.values(e.elements??{}))r.type.startsWith("@")||t.set(r.type,(t.get(r.type)??0)+1);let n=[...t].map(([r,s])=>({type:r,count:s})).sort((r,s)=>s.count-r.count||r.type.localeCompare(s.type));return{...e.name?{name:e.name}:{},elementCount:n.reduce((r,{count:s})=>r+s,0),elementsByType:n}};var lS="modeldesk model import --help",mW=600,mS={type:"number",default:mW,placeholder:"seconds",description:"How long to wait for the server before exiting 7; the import carries on server-side and can be resumed."},Op={name:"import-id",type:"string",required:!0,description:"The import's id, as 'model import' or 'model imports list' prints it."},fS=e=>t=>{e.globals.json||e.io.err(pe(`${t}
243
+ `))},pS=e=>({api:e.api(),clock:Nd,json:e.globals.json,note:fS(e)}),uS=(e,t)=>{if(!Number.isFinite(e)||e<=0)throw I(`--timeout takes a positive number of seconds, got ${e}.`,t)},Mp=(e,t)=>{if(!Y(e))throw I(`'${e}' is not an import id.`,`modeldesk model imports ${t} --help`)},fW=(e,t)=>{if(e.globals.json||t.length===0)return;let{ERROR:n,WARN:r,INFO:s}=Md(t);e.io.err(pe(`Log: ${n} error(s), ${r} warning(s), ${s} info
244
+ ${Oo(t)}`))},hS=e=>e.type==="upload"?{type:"upload",filename:e.filename,bytes:e.bytes}:{type:"remote",location:wn(e.location)},gS=q({path:["model","import"],effect:"create",summary:"Import a file or an address as a new model",description:"Creates an import, waits for the parse, completes it as a model named --name, and prints the model id and link. The metamodel release is the one --metamodel names after @, or its newest; the loader is --loader or inferred from the file extension among the release's loaders; the owner is --owner or your one organization with a seat for the metamodel. Every choice is printed, and carried in --json. --review stops after the parse with a summary; finish with 'model imports complete'. Exits 1 when the server puts the import in ERROR, 2 for an ambiguous or mismatched loader or owner, and 7 when --timeout passes (the import then carries on server-side).",positionals:[{name:"file",type:"string",description:"The file to upload; its name travels with it, since some loaders read the format from it."}],flags:{url:{type:"string",placeholder:"uri",description:"Import from this address instead of a file; the server fetches it."},metamodel:{type:{address:"model",slot:li},required:!0,placeholder:"metamodel[@release]",description:"The metamodel's id, from metamodel list, at @<release> or else its newest release."},name:{type:"string",placeholder:"name",description:"The name of the model the import creates; required unless --review."},owner:{type:"string",placeholder:"organization",description:"The organization that owns the import and the model, by name or id; needed when several give you a seat."},extension:{type:{list:{address:"model",slot:ci}},placeholder:"extension[@release]",description:"An extension's id, from metamodel extensions <metamodel>, at @<release> or else its newest release."},loader:{type:"string",placeholder:"name",description:"The loader to read the source with, instead of inferring it from the extension."},review:{type:"boolean",description:"Stop once the parse is READY and summarize it; complete with 'model imports complete'."},timeout:mS},dryRun:!0,examples:["modeldesk model import vocabulary.ttl --metamodel <metamodel> --name Vocabulary","modeldesk model import --url https://example.org/schema.xsd --metamodel <metamodel>@1.0 --name Schema","modeldesk model import model.eap --metamodel <metamodel> --owner Acme --review"],run:async e=>{let{flags:t}=e;if(uS(t.timeout,lS),!t.review&&t.name===void 0)throw I("Pass --name for the model the import creates, or --review to stop before completing.",lS);let n=e.api(),r=ZR(e.args.file,t.url,e.cwd),s=await tS(n,t.metamodel.model),o=await rS(n,s,t.owner),i=await Tp(n,s,mr(t.metamodel)),a=await nS(n,s,t.extension),d=await sS(n,i,r,t.loader),l={source:r,metamodel:i,extensions:a,loader:d,owner:o};fS(e)(iS(l));let m={source:hS(r),metamodel:i,extensions:a,loader:d,owner:o,...t.name!==void 0?{name:t.name}:{}};if(e.globals.dryRun)return{result:{dryRun:!0,...m,logEntries:[]}};let f=Od(r.type==="remote"?r.location:void 0);try{return await pW(e,l,f)}catch(h){throw vp(h,f)}},render:e=>{if(e.dryRun)return`Dry run: nothing was imported; ${cS(e.source)} would be read by ${e.loader.name}.`;if(e.status==="READY")return uW(e);let t=e.model;return[`Imported ${cS(e.source)} as model '${y(t.name)}' (${t.id}).`,t.url].join(`
245
+ `)}}),pW=async(e,t,n)=>{let{flags:r}=e,s=e.api(),o={source:hS(t.source),metamodel:t.metamodel,extensions:t.extensions,loader:t.loader,owner:t.owner,...r.name!==void 0?{name:r.name}:{}},i=pS(e),a=bp(i.clock,r.timeout),d=await WR(i,oS(t)),l=await BR(i,d,a,r.timeout,r.name),c=yn(l.logEntries??[],n);if(fW(e,c),r.review||r.name===void 0){let g=yn(dS(await HR(l.id,()=>s.imports.model(l.id),r.name)),n);return{result:{dryRun:!1,importId:l.id,status:"READY",...o,logEntries:c,review:g,url:te(e.instance(),{kind:"import",importId:l.id}),next:Zr(l.id,r.name)}}}let m=await Cp(i,l.id,r.name,a,r.timeout),f=m.modelId,h=te(e.instance(),{kind:"model",modelId:f});return{result:{dryRun:!1,importId:m.id,status:"COMPLETED",...o,logEntries:c,model:{id:f,name:r.name,url:h},url:h}}},cS=e=>e.type==="upload"?e.filename:e.location,uW=e=>{let t=e.review,n=t.name?` '${y(t.name)}'`:"",r=t.elementsByType.length===0?[" (no elements)"]:F(t.elementsByType.map(({type:s,count:o})=>[String(o),s])).map(s=>` ${s}`);return[`Import ${e.importId} is READY for review.`,`Parsed model${n}: ${t.elementCount} element(s)`,...r,`Complete it with: ${e.next}`,e.url].join(`
246
+ `)},Ld=e=>e.api().imports.get(e.args["import-id"]),yS=q({path:["model","imports","complete"],effect:"create",summary:"Complete a READY import as a model",description:'Completes an import the parse left READY (after "model import --review", or one started in the app) as a model named --name, waits for the model, and prints its id and link. The name is the only completion input the server reads. An import that is not READY is refused (exit 1).',positionals:[Op],flags:{name:{type:"string",required:!0,placeholder:"name",description:"The name of the model the import creates."},timeout:mS},dryRun:!0,examples:["modeldesk model imports complete f0909fb8-6867-42e0-a931-26d73185d949 --name Vocabulary"],run:async e=>{let{flags:t,args:n}=e;if(Mp(n["import-id"],"complete"),uS(t.timeout,"modeldesk model imports complete --help"),e.globals.dryRun){let d=await Ld(e);if(d.status!=="READY")throw new u(`Import ${d.id} is ${d.status}; only a READY import can be completed.`);return{result:{dryRun:!0,importId:d.id,status:"READY",name:t.name,logEntries:Lo(d).logEntries??[],url:te(e.instance(),{kind:"import",importId:d.id})}}}let r=pS(e),s;try{s=await Cp(r,n["import-id"],t.name,bp(r.clock,t.timeout),t.timeout)}catch(d){let l=await Ld(e).then(c=>c,()=>{});throw l===void 0?d:vp(d,Ep(l))}let o=s.modelId,i=te(e.instance(),{kind:"model",modelId:o});return{result:{dryRun:!1,importId:s.id,status:"COMPLETED",name:t.name,logEntries:Lo(s).logEntries??[],model:{id:o,name:t.name,url:i},url:i}}},render:e=>e.dryRun?`Dry run: import ${e.importId} is READY and would be completed as '${y(e.name)}'.`:[`Completed import ${e.importId} as model '${y(e.name)}' (${e.model?.id}).`,e.url].join(`
247
+ `)}),hW=["ID","STATUS","DATE","METAMODEL","SOURCE","OWNER"],wS=e=>{let t=e.version?` ${e.version}`:"";return`${e.name??e.id}${t}`},bS=e=>e.source.type==="remote"?e.source.location:e.source.filename??"(upload)",kS=q({path:["model","imports","list"],effect:"read",summary:"List imports, pending and finished",description:"Lists the imports you can see, newest first: id, status, creation time, metamodel and release, source and owner. A READY import awaits completion; a COMPLETED one names the model it created.",flags:{owner:{type:"string",placeholder:"organization",description:"List only the imports this organization owns, by name or id."}},listing:{narrowHint:"Pass --owner to narrow the list."},examples:["modeldesk model imports list","modeldesk model imports list --owner Acme --json"],run:async e=>{let t=e.api(),n=e.flags.owner===void 0?void 0:mm(tn(await t.accessTokenClaims()),e.flags.owner),{items:r}=await t.imports.list(n?.id),s=r.map(Ap).sort((i,a)=>a.createdAt.localeCompare(i.createdAt)||i.id.localeCompare(a.id));return{result:{...n?{owner:{id:n.id,...n.name?{name:n.name}:{}}}:{},...await e.list(s)}}},render:({items:e})=>e.length===0?"No imports.":F([hW,...e.map(t=>[t.id,t.status,t.createdAt,y(wS(t.metamodel)),y(bS(t)),y(t.owner.name??t.owner.id)])]).join(`
248
+ `)}),ES=q({path:["model","imports","show"],effect:"read",summary:"Show one import",description:"Shows an import's status, metamodel release, extensions, loader, source, owner, error message and log entries, and the model it created once COMPLETED.",positionals:[Op],examples:["modeldesk model imports show f0909fb8-6867-42e0-a931-26d73185d949"],run:async e=>(Mp(e.args["import-id"],"show"),{result:aS(e.instance(),Lo(await Ld(e)))}),render:e=>{let t=wS(e.metamodel),n=e.createdBy?` by ${e.createdBy.name??e.createdBy.id}`:"";return[`Import ${e.id}`,` status ${e.status}`,` created ${e.createdAt}${n}`,` metamodel ${y(t)}`,...e.extensions.map(s=>{let o=s.version?` ${s.version}`:"";return` extension ${y(s.name??s.id)}${o}`}),...e.loader?[` loader ${e.loader}`]:[],` source ${y(bS(e))}`,` owner ${y(e.owner.name??e.owner.id)}`,...e.errorMessage?[` error ${y(e.errorMessage)}`]:[],...e.model?[` model ${e.model.id}`]:[],...e.logEntries.length>0?["","Log:",...Oo(e.logEntries).trimEnd().split(`
249
+ `)]:[],"",e.status==="READY"?`Complete it with: ${Zr(e.id)}`:void 0,e.model?.url??e.url].filter(s=>s!==void 0).join(`
250
+ `)}}),CS=q({path:["model","imports","delete"],effect:"create",summary:"Discard an import",description:"Deletes an import and the parsed state it holds. A model an import already created is not affected. The server allows it to the import creator or an organization admin with a seat for the metamodel.",positionals:[Op],dryRun:!0,examples:["modeldesk model imports delete f0909fb8-6867-42e0-a931-26d73185d949"],run:async e=>{let t=e.args["import-id"];Mp(t,"delete");let n=await Ld(e);return e.globals.dryRun||await e.api().imports.delete(t),{result:{dryRun:e.globals.dryRun,importId:n.id,deleted:!e.globals.dryRun,status:n.status}}},render:e=>e.dryRun?`Dry run: import ${e.importId} (${e.status}) would be deleted.`:`Deleted import ${e.importId}.`});var vS={modelList:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},kind:{type:"string",description:'The kind of model asked for. One of "all", "metamodel", "model".'},kinds:{type:"array",items:{type:"string",description:'One of "metamodel", "model".'},description:"The kinds actually listed: `metamodel` only for a super-admin, the one caller its listing answers."},items:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},kind:{type:"string",description:'One of "metamodel", "model".'},metamodel:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},owner:{type:"object",properties:{id:{type:"string"},type:{type:"string"},name:{type:"string"}}}}}},truncated:{type:"boolean",description:"True when more rows exist than this page carries. One of false, true."},nextCursor:{type:"string",description:"Where the next page starts, to continue from; present exactly when truncated."},hint:{type:"string",description:"One line on how to continue or narrow the query; present exactly when truncated."}},required:["schemaVersion","kind","kinds","items","truncated"]}};var yW=["model","metamodel","all"],wW=["ID","NAME","KIND","METAMODEL","OWNER"],bW=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:"base"})||e.id.localeCompare(t.id),kW=(e,t)=>t==="me"&&typeof e.sub=="string"?e.sub:t===void 0||Y(t)?t:Ws(tn(e),t).id,EW=({model:e,kind:t})=>({id:e.id,name:e.name,kind:t,metamodel:{id:e.metamodel.id,name:e.metamodel.name},owner:{id:e.owner.id,type:e.owner.type,...e.owner.name?{name:e.owner.name}:{}}}),RS=D({path:["model","list"],effect:"read",summary:"List the models you can read",description:"Lists the models you can read with their id, name, kind, metamodel and owner. Metamodel-models (the metamodels themselves, as models) are listed only on --kind metamodel or --kind all, and for a super-admin only; --json reports the kinds listed as kinds. To choose a metamodel, run metamodel list.",flags:{metamodel:{type:"string",placeholder:"id",description:"List only models written in this metamodel, by its id from metamodel list.",toolDescription:"List only models written in this metamodel, by its id."},owner:{type:"string",placeholder:"organization|me",description:"List only models this owner has: an organization of yours by name, any owner by id, or me."},kind:{type:{enum:yW},default:"model",description:"List models, metamodel-models (super-admin), or both."}},listing:{narrowHint:"Pass --metamodel or --owner to narrow the list.",toolNarrowHint:"Give a metamodel or an owner to narrow the list."},examples:["modeldesk model list","modeldesk model list --metamodel <metamodel> --json"],mcp:{name:"list_models",description:"Lists the models the person can read, with id, name, metamodel and owner. Call it first: every other tool takes a model id from here. Narrow with metamodel (an id) or owner (an organization name, an id, or me). A long list comes back truncated with nextCursor; pass it as cursor for the next page.",pin:{kind:"model"}},resultSchema:vS.modelList,run:async e=>{let{metamodel:t,owner:n,kind:r}=e.flags;if(t!==void 0&&!Y(t))throw I(`--metamodel takes a metamodel's id, got '${t}'; run '${Zt}' to find it.`,"modeldesk model list --help",{reason:`'metamodel' takes a metamodel's id, got '${t}'.`});let s=e.api(),o=await s.accessTokenClaims(),i=Kt(o),a=kW(o,n),d=(r==="all"?["model","metamodel"]:[r]).filter(f=>f==="model"||i),c=(await Xh(s,{ownerId:a,metamodel:t,models:d.includes("model"),metamodels:d.includes("metamodel")})).map(EW).filter(f=>t===void 0||f.metamodel.id.toLowerCase()===t.toLowerCase()).filter(f=>a===void 0||f.owner.id.toLowerCase()===a.toLowerCase()).sort(bW);return{result:{kind:r,kinds:d,...await e.list(c)}}},render:({items:e,kind:t,kinds:n})=>{let r=e.length===0?["No models."]:F([wW,...e.map(o=>[o.id,y(o.name),o.kind,y(o.metamodel.name),y(o.owner.name??o.owner.id)])]),s=t!=="model"&&!n.includes("metamodel");return[...r,...s?["","Metamodel-models are not listed: only a super-admin can list them."]:[]].join(`
251
+ `)}});var Dd=(e,t)=>async(n,r)=>{let s=Math.min(r,99),o=await e(s+1,n),i=o.slice(0,s);return o.length>s?{items:i,nextCursor:t(i.at(-1))}:{items:i}};var SS={modelLog:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"What was read: a branch, or your draft (its staged commits) when addressed as"},items:{type:"array",items:{type:"object",properties:{id:{type:"string"},createdAt:{type:"string"},author:{type:"object",properties:{id:{type:"string"},type:{type:"string",description:'One of "MACHINE", "ORGANIZATION", "SYSTEM", "USER".'},name:{type:"string"}}},message:{type:"string"},requestId:{type:"string",description:"The idempotency key of the request that made the commit, as its client sent it."},versions:{type:"array",items:{type:"string"},description:"The names of the releases cut at this commit."},changes:{type:"number",description:"How many staged changes a landing landed; absent on any other commit and on a landing older than the record."},stagedChanges:{type:"array",items:{type:"object",properties:{requestId:{type:"string"},message:{type:"string"},actionTypes:{type:"array",items:{type:"string"}}}},description:"When changes are asked for, what the landing recorded of each staged change, in the order they were staged."}}}},truncated:{type:"boolean",description:"True when more rows exist than this page carries. One of false, true."},nextCursor:{type:"string",description:"Where the next page starts, to continue from; present exactly when truncated."},hint:{type:"string",description:"One line on how to continue or narrow the query; present exactly when truncated."}},required:["schemaVersion","model","ref","items","truncated"]}};var vW=["ID","DATE","AUTHOR","CHANGES","MESSAGE","REQUEST"],RW=8,SW=" ",IW=e=>({id:e.id,createdAt:e.createdAt,author:e.createdBy,...e.message?{message:e.message}:{},...e.requestId?{requestId:e.requestId}:{},...e.versions?.length?{versions:e.versions.map(t=>t.name)}:{},...e.stagedChangeCount===void 0?{}:{changes:e.stagedChangeCount}}),$W=e=>{let t=y((e.message??"").split(/\r?\n/)[0]);return e.versions?`${t}${t?" ":""}[released ${e.versions.join(", ")}]`:t},xW=e=>[qt(e.requestId),y(Zd(e.requestId)??""),y(e.message??""),e.actionTypes.length?`[${e.actionTypes.join(", ")}]`:""],IS=D({path:["model","log"],effect:"read",summary:"List a model's commits",description:"Lists commits newest first with their id, time, author, message and request id. The platform hides the commits it makes itself (metamodel seeding, release re-pins) unless --include-system is passed. Without a ref it lists your working branch; @draft lists the staged chain of your draft instead. CHANGES counts the staged changes a landing landed; --changes lists them beneath it.",positionals:[_(Ml)],flags:{"include-system":{type:"boolean",description:"Include the commits the platform made itself, such as the re-pins a metamodel release writes."},changes:{type:"boolean",description:"List what each landing held: every staged change with its surface, agent session, message and action types, in the order they were staged. Reads one request per listed landing."}},listing:{defaultLimit:20},examples:["modeldesk model log <model>","modeldesk model log <model>@draft","modeldesk model log <model>@agent/nightly-pass --changes","modeldesk model log <model>@feat/shapes --include-system --limit 100 --json"],mcp:{name:"model_log",description:"Lists a model's commits newest first, with id, time, author, message and request id. Without a ref it lists your working branch; @draft lists the staged chain of your draft. changes: true lists what each landing held: every staged change with its surface, agent session and message. includeSystem adds the commits the platform made itself."},resultSchema:SS.modelLog,run:async e=>{let t=e.api(),n=await Z(e,e.args.model,Ml),{id:r}=n,s={...Qe(n.ref),includeSystem:e.flags["include-system"]},o=Dd(async(d,l)=>(await t.models.commits(r,{...s,limit:d,cursor:l})).items.map(IW),d=>d.id),i=await e.list(o);if(e.flags.changes){let d=i.items.filter(l=>l.changes!==void 0);await jn(d,RW,async l=>{l.stagedChanges=(await t.models.commitHeader(r,l.id,{ref:s.ref})).stagedChanges??[]})}return{result:{model:{id:r,name:n.name},ref:re(n),...i}}},render:e=>{let t=[Ie(e.ref,e.model),...e.ref.kind==="draft"?["The log of a draft lists its staged commits only."]:[]];if(e.items.length===0)return[...t,"No commits."].join(`
252
+ `);let[n,...r]=F([vW,...e.items.map(o=>[o.id,o.createdAt,y(o.author.name??o.author.id),o.changes===void 0?"":String(o.changes),$W(o),o.requestId??""])]),s=e.items.flatMap((o,i)=>[r[i],...o.stagedChanges?.length?F(o.stagedChanges.map(xW),{indent:SW}):[]]);return[...t,n,...s].join(`
253
+ `)}});var jd=Xd(od(),1);import{posix as _d}from"node:path";var TW=8,Fd=e=>{let{elements:t,labels:n={},packageTypes:r=new Set}=e,s=[],o=new Set([e.rootId]),i=S=>Object.hasOwn(t,S)?t[S]:void 0,a=S=>{let x=Object.hasOwn(n,S)?n[S]:void 0,A=i(S);return x??(A&&(gd(A.attributes?.name)??A.type))},d=S=>{let x=a(S);return x===void 0?void 0:pe(y(x))},l=(S,x,A)=>Se(i(S)?.relations?.[x]??{}).some(O=>O.owned===!0&&O.id===A),c=S=>e.indexOwners?.(S)?.find(x=>l(x.id,x.relation,S)),m=(S,x,A)=>{if(i(A)===void 0||o.has(A))return!1;let O=c(A);return O===void 0||O.id===S&&O.relation===x},f=(S,x,A,O)=>{let L=A.owned===!0;if(L&&m(S,x,A.id)){if(o.add(A.id),O===void 0)return g(A.id);O(A.id)}let V=d(A.id);return!L&&A.modelId===void 0?Kn(A.id,V):Dt([["ref",Kn(A.id,A.modelId===void 0?V:void 0)],...L?[["owned",new jd.Scalar(!0)]]:[],...A.modelId!==void 0?[["model",Kn(A.modelId)]]:[]])},h=(S,x,A)=>{let O=i(S)?.relations?.[x]??{},L=ne=>{let K=new jd.YAMLSeq;return K.items=ne.map(H=>f(S,x,H,A)),K},V=Object.keys(O);return V.length===1&&V[0]==="@@"?L(O["@@"]):Dt(V.toSorted(ie).map(ne=>[ne,L(O[ne])]))},p=0,g=(S,x)=>{if(++p>ze)throw new u(`The model nests elements more than ${ze} deep (at ${S}), deeper than a workspace is written.`,{type:"model-too-deep",details:{elementId:S,limit:ze}});try{return w(S,x)}finally{p--}},w=(S,x)=>{let A=t[S],O=S===e.rootId,L=A.attributes??{},V=A.relations??{},ne=Object.keys(V).sort(ie),K=ne.filter(de=>!(O&&Lt(de))),H=ne.filter(de=>O&&Lt(de)),we=Ue.filter(de=>Object.hasOwn(A,de)&&A[de]!==void 0),Ft=[["id",Kn(A.id)],["type",Kn(A.type)]];return Object.keys(L).length>0&&Ft.push(["attributes",Dt(Object.keys(L).sort(ie).map(de=>[de,ko(L[de])]))]),K.length>0&&Ft.push(["relations",Dt(K.map(de=>[de,h(S,de,x)]))]),(we.length>0||H.length>0)&&Ft.push(["readOnly",Dt([...we.map(de=>[de,ko(A[de])]),...H.length>0?[["relations",Dt(H.map(de=>[de,h(S,de)]))]]:[]])]),Dt(Ft)},k=S=>Object.values(S.relations??{}).some(x=>Se(x).some(A=>A.owned===!0&&r.has(i(A.id)?.type??""))),C=S=>{let x=t[S];return r.has(x.type)&&k(x)},R=(S,x)=>{let A=new Map(S.map(K=>{let H=ep(a(K)??"");return[K,tp(H)?ep(t[K].type):H]})),O=K=>{let H=new Map;for(let we of K)H.set(we,(H.get(we)??0)+1);return H},L=O(A.values()),V=new Map(S.map(K=>{let H=A.get(K),we=tp(H)||x.has(H)||(L.get(H)??0)>1;return[K,we?[H,K.slice(0,TW)].filter(Boolean).join("-"):H]})),ne=O(V.values());return new Map(S.map(K=>{let H=V.get(K);return[K,(ne.get(H)??0)>1?[A.get(K),K].filter(Boolean).join("-"):H]}))},$=S=>{let x=d(S);return x===void 0?t[S].type:`${x} (${t[S].type})`},v=(S,x,A,O,L)=>{let V=[],ne=g(S,H=>V.push(H));s.push({path:_d.join(x,A),text:dd(ne,O)});let K=R(V,L);p++;try{for(let H of V){let we=K.get(H);C(H)?v(H,_d.join(x,we),vv,$(H),new Set):s.push({path:_d.join(x,`${we}.yaml`),text:dd(g(H),$(H))})}}finally{p--}},T=`${e.modelName===void 0?"A ModelDesk model":pe(y(e.modelName))}. Edit these files, then run 'modeldesk model diff' and 'modeldesk model push'.`;v(e.rootId,"",Pt,T,new Set([Pt.replace(/\.yaml$/,"")]));let N=[];for(let S of Object.keys(t).sort(ie))o.has(S)||(o.add(S),N.push([S,g(S)]));let E=R(N.map(([S])=>S),new Set);for(let[S,x]of N)s.push({path:_d.join(Rv,`${E.get(S)}.yaml`),text:dd(x,$(S))});return s.sort((S,x)=>ie(S.path,x.path))},qd=e=>[{path:yt,text:`${JSON.stringify({rootElementId:e.rootId,elements:Object.fromEntries(Object.keys(e.elements).sort(ie).map(t=>[t,e.elements[t]]))},null,2)}
254
+ `}];var AW=async(e,t,n)=>{if(n.head===t.baseCommitId||t.baseRootRevision===Xn(n))return n.read;try{return await e.api().models.get(t.model.id,{commit:t.baseCommitId})}catch(r){if(r instanceof U&&(r.status===404||r.status===400))return;throw r}},$S=e=>`${e.slice(0,3).map(W).join(", ")}${e.length>3?", \u2026":""}`,OW=(e,t)=>{if(t.collisions.length!==0)throw new u(`The pull would overwrite ${t.collisions.length} file(s) in ${W(e)} that the workspace did not write (${$S(t.collisions)}), so nothing was written.`,{type:"workspace-collision",hint:"Move those files away, or pull into another directory.",details:{collisions:t.collisions}})},MW=(e,t)=>{t.length!==0&&e.warn(`${t.length} file(s) the model no longer needs were edited since the workspace wrote them, so they were left in place (${$S(t)}). Remove them, or the next diff reads them.`)},NW=async(e,t,n,r)=>{let s;try{s=gn(t,n)}catch(i){if(i instanceof Je)return{changed:!0,reason:`its files do not parse (${i.reason})`};throw i}let o=i=>_t(jt(i),s).ops.length;try{if(o(r.read)===0)return{changed:!1};let i=await AW(e,n,r);if(i===void 0)return{changed:!0,reason:`its base commit ${n.baseCommitId} can no longer be read`};let a=o(i);return a>0?{changed:!0,reason:`it holds ${a} local change(s)`,ops:a}:{changed:!1}}catch(i){if(i instanceof kt)return{changed:!0,reason:`its files change what cannot be pushed (${i.reason})`};throw i}},xS=q({path:["model","pull"],effect:"local",summary:"Pull a model into a file workspace to edit",description:"Writes the model as a tree of YAML files, one element per file with what it owns inline (the format is described in the CLI's README), and records what it pulled in .modeldesk/workspace.json: the branch (@<branch>, or your working branch), which 'modeldesk model diff' and 'modeldesk model push' then address by its id, and the head the files reflect. It pulls what you write to: your draft on the branch, otherwise the branch head, so your edits build on what you staged. A draft the branch moved past is pulled as it stands, with a warning naming 'modeldesk draft rebase'. A commit is no ref to pull: a workspace tracks a branch to push to. Pulling again updates the files in place and moves the workspace's base to the current head, on the branch the address names; a workspace with local changes is refused unless --force, which discards them. --format json writes the element map exactly as the server serves it, in one model.json.",positionals:[_(me),Jr],flags:{force:{type:"boolean",description:"Pull over local changes in the workspace, discarding them."},format:{type:{enum:["yaml","json"]},description:"yaml (the default, or the workspace's format on a re-pull): the editable file tree; json: the lossless element map in one model.json."}},dryRun:!0,prepare:pp,examples:["modeldesk model pull <model> shacl-workspace","modeldesk model pull <model>@agent/tidy-names . --format json"],run:e=>X(async()=>{let{dir:t,state:n}=up(e),r=e.args.model,s=await ce(e,r.model).id();if(n!==void 0&&n.model.id!==s)throw new u(`${W(t)} is a workspace of another model (${W(n.model.name)}).`,{hint:"Pull into another directory."});let o=await lt(e,r),i=Xr(o);if(n!==void 0&&!e.flags.force){let p=await NW(e,t,n,o);if(p.changed)throw new u(`The workspace in ${W(t)} is not pulled over: ${p.reason}.`,{exitCode:b.Failure,hint:"Push them with 'modeldesk model push', or pass --force to discard them. 'modeldesk model diff' shows them.",details:{...p.ops!==void 0&&{changes:p.ops}}})}let a=$d(o.read),d=e.flags.format??n?.format??"yaml",l=d==="json"?qd(a):Fd(a),c=pd(t,l,n?.files??{});OW(t,c);let m=e.instance().host;e.globals.dryRun||(ud(t,l,c),hn(t,{schemaVersion:Nt,host:m,model:o.model,branch:{id:o.branch.id,name:o.branch.name},baseCommitId:o.head,baseRootRevision:Xn(o),format:d,files:Co(l)}));let f=Rd(o);return f!==void 0&&e.warn(`${f} The files hold what the draft holds: run 'modeldesk draft rebase', then pull again.`),MW(e,c.kept),{result:{model:o.model,ref:i,dir:t,format:d,baseCommitId:o.head,...n!==void 0&&{previousBaseCommitId:n.baseCommitId},elements:Object.keys(o.read.elements).length,files:{written:c.written,removed:c.removed,kept:c.kept,unchanged:c.unchanged.length},...e.globals.dryRun&&{dryRun:!0},url:te(e.instance(),{kind:"model",modelId:s})}}}),render:e=>[`${e.dryRun?"Would pull":"Pulled"} ${st(e.ref,y(e.model.name))} into ${W(e.dir)}: ${e.elements} elements as ${e.format==="json"?"model.json":"YAML files"}.`,`${e.dryRun?"Would write":"Wrote"} ${e.files.written.length} file(s), ${e.dryRun?"would remove":"removed"} ${e.files.removed.length}, left ${e.files.unchanged} unchanged.`,...e.files.removed.map(t=>` removed ${W(t)}`),...e.files.kept.map(t=>` kept ${W(t)} (edited since it was written)`),`base: ${e.baseCommitId}`+(e.previousBaseCommitId!==void 0&&e.previousBaseCommitId!==e.baseCommitId?` (was ${e.previousBaseCommitId})`:""),`url: ${e.url}`].join(`
255
+ `)});var AS=e=>({number:e.number,opCount:e.ops.length,firstOp:e.ops[0]??0,actions:e.actions.length,bytes:e.bytes,...e.dependsOn.length>0&&{dependsOn:e.dependsOn}}),OS=(e,t,n)=>n>1?`${e} (${t.number}/${n})`:e,PW=(e,t,n)=>{let r=[],s=o=>{if("new"in o.element){let i=n.elements.get(o.element.new);i!==void 0&&r.push({location:i.location,id:t.ids.get(o.element.new)})}Object.values(o.children??{}).flat().forEach(s)};for(let o of e.ops){let i=t.ops[o];i.op==="create"&&s(i.element)}return r},Np=e=>e.length===0?"Nothing was staged.":`${MS(e)}: 'modeldesk model diff' shows only what is left.`,MS=e=>{let t=e.length===1?"it":"them";return`${P(e.length,"earlier change")} landed and the workspace records ${t}`},LW=e=>Array.isArray(e.details.landed)?e.details.landed:[],NS=e=>Array.isArray(e.details.errors)?e.details.errors:[],DW=(e,t,n,r)=>{let s=NS(e),o=s.some(a=>a.code==="invalid-position")?" A relation the metamodel orders alphabetically takes no position: list the element at its end.":"",i=s.some(a=>a.code==="chain-too-long");return new u(`${e.reason} ${Np(n)}${o}`,{...t,hint:i?`Commit the draft first ('modeldesk draft commit ${r}', or in the app), then push again.`:void 0})},_W=(e,t,n)=>{let r=n.length===0?"No earlier change of this push landed.":`${MS(n)}.`;return new u(`${e.reason} ${r}`,{...t,hint:e.hint})},jW=(e,t)=>{if(!(e instanceof u)||e.type==="workspace-not-recorded")return e;let n=LW(e),r={type:e.type,requestId:e.requestId,details:e.details,exitCode:e.exitCode};return e.type==="draft-head-conflict"?new u(`${e.reason} ${Np(n)}`,{...r,hint:"Re-pull the workspace with 'modeldesk model pull' and push what is left again."}):e.type==="change-validation-failed"&&e.exitCode===b.Validation?DW(e,r,n,t):e.exitCode===b.Transient?_W(e,r,n):new u(`${e.reason} ${Np(n)}`,{...r,hint:e.hint})},TS=(e,t,n,r,s,o)=>{let[i]=n.slice(-1),a=t>1?`Change ${e.number} of ${t}`:"The change";return new u(`${a} landed as ${i.commitId}, but ${s}. The workspace's base stays at ${r}, so it reads as stale and nothing more was pushed.`,{type:"workspace-not-recorded",hint:"Copy aside any edits you have not pushed, then re-pull with 'modeldesk model pull --force' to bring the files to what landed.",details:{...o,chunk:e.number,chunks:t,landed:n,baseCommitId:r}})},FW=(e,t,n,r)=>e===void 0?Wo(r,`${t}:${n.number}`):En(r,e,n),qW=(e,t)=>{let{dryRun:n}=e.globals,{message:r,plan:s,commit:o}=e.flags,i=e.flags["request-id"];if(n&&s!==void 0)throw I("--dry-run makes a plan and --plan pushes one; pass one of them.",t);if(n&&o)throw I("--commit has nothing to commit under --dry-run, which stages nothing.",t);if(e.flags["with-staged"]&&!o)throw I("--with-staged goes with --commit.",t);if(s!==void 0&&!/^[0-9a-f]{12,64}$/.test(s))throw I("--plan takes the hash a dry run printed (at least its first 12 characters).",t);St(r,t),i!==void 0&&Gc(i,t)},WW=(e,t,n)=>new u(`The workspace is stale: ${n} moved from ${e.baseCommitId} to ${t.head} since it was pulled. Nothing was staged.`,{exitCode:b.Conflict,type:"workspace-stale",hint:"Re-pull with 'modeldesk model pull' (--force discards local edits) and edit on top of what changed; a push now would revert it.",details:{baseCommitId:e.baseCommitId,headCommitId:t.head}}),BW=(e,t)=>{let n=Rd(e);if(n===void 0)return[];if(t)throw new u(`${n} It cannot be committed as it stands, so nothing was staged.`,{exitCode:b.Conflict,type:"draft-baseline-stale",hint:"Run 'modeldesk draft rebase', re-pull the workspace, then push again.",details:{baselineCommitId:e.draft?.baselineCommitId,branchHeadCommitId:e.branch.head}});return[`${n} Committing it needs 'modeldesk draft rebase' first; re-pulling does not help.`]},HW=async(e,t,n,r)=>{let{draft:s,branch:o}=t;tr(e,`${e.commandName} --commit`,{kind:"model",id:n,name:r},o),Kc(s?.changeCount??0,e.flags["with-staged"]),s!==void 0&&await qe(e,ui(e,n),s,{scope:{kind:"all"},action:`Committing your draft of ${r}`,anySurface:!1,override:Yc(n)})},UW=(e,t)=>{if(t!==void 0&&!e.hash.startsWith(t))throw new u("The workspace no longer matches the plan: its operations or its base changed since.",{exitCode:b.Validation,type:"plan-mismatch",hint:"Run the dry run again and review the new plan.",details:{expected:t,planHash:e.hash}})},VW=(e,t,n)=>{let r=t>1?` (${t}/${t})`.length:0;if(e.length+r>2e3)throw I(`The message (-m) is ${e.length} characters long; the push stages ${t} changes, each message suffixed (n/${t}), so it holds at most ${2e3-r}.`,n)},GW=(e,t,n)=>{let r=e?.changeCount??0;if(r+t>je)throw new u(`The push needs ${P(t,"change")} and your draft of ${n} holds ${r} of the ${je} a draft can. Nothing was staged.`,{exitCode:b.Validation,type:"draft-change-cap",hint:"Commit the draft first ('modeldesk draft commit', or in the app).",details:{changes:t,changeCount:r,limit:je}})},KW=async e=>{let t=xo(e),{dir:n}=t,{state:r}=t,{dryRun:s}=e.globals,{message:o,plan:i,commit:a}=e.flags,d=`modeldesk ${e.commandName} --help`;qW(e,d);let l=r.model.id,c=te(e.instance(),{kind:"model",modelId:l}),m=await To(e,n,r),f=y(m.model.name),h=Xr(m),p=vd(n,r,m);if(p.kind==="stale")throw WW(r,m,st(h,f));let g=p.kind==="rebound"?{from:p.from}:void 0;g&&!s&&(r=Id(n,r,m));let w=BW(m,a);a&&await HW(e,m,l,f);let k=jt(m.read),C=gn(n,r),R=wd(k,C,{modelId:l,baseCommitId:m.head});UW(R,i),w.push(...R.warnings),w.forEach(v=>e.warn(v));let $=R.chunks.length;return VW(o,$,d),GW(m.draft,$,f),{context:e,dir:n,modelId:l,state:r,target:m,name:f,workspace:C,plan:R,deletes:R.ops.flatMap(v=>v.op==="delete"?[v.element]:[]),base:{model:m.model,ref:h,dir:n,message:o,baseCommitId:m.head,...g&&{rebound:g},planHash:R.hash,ops:R.ops,counts:bd(R.ops),labels:kd(R.ops,k.labels),warnings:w,url:c}}},PS=({context:e,deletes:t})=>t.length>0&&!e.flags["allow-delete"],YW=async(e,t)=>{let{context:n,modelId:r,target:s,plan:o,base:i}=e,a=AS(t);if(t.number>1&&t.dependsOn.length>0)return{...a,validation:"client-checked"};let d={actions:t.actions,draftHeadId:s.head,changeRequestId:Zn(n.origin),message:OS(i.message,t,o.chunks.length),dryRun:!0,...s.draft===void 0?{branchId:s.branch.id}:{}};try{let{envelope:l}=await n.api().drafts.model.stage(r,d);return{...a,validation:"server",verdict:"valid",affected:{changed:Object.keys(l.revisions).sort(),removed:l.removedElementIds??[]}}}catch(l){if(l instanceof u&&l.type==="change-validation-failed")return{...a,validation:"server",verdict:"refused",errors:NS(l)};throw l}},zW=async e=>{let{target:t,plan:n,base:r}=e,s=[];for(let a of n.chunks)s.push(await YW(e,a));let o=s.some(a=>a.verdict==="refused");return{result:{...r,dryRun:!0,headCommitId:t.head,chunks:s,staged:0},...(o||PS(e))&&{exitCode:b.Validation}}},JW=e=>new u(`The workspace deletes ${P(e.length,"element")} (${e.slice(0,5).join(", ")}${e.length>5?", \u2026":""}), and a push deletes only with --allow-delete. Nothing was staged.`,{exitCode:b.Validation,type:"deletes-not-allowed",hint:"Review them with 'modeldesk model diff'; restore a file removed by mistake, or pass --allow-delete.",details:{deletes:e}}),XW=({dir:e,plan:t,workspace:n},r)=>(s,o)=>{let{landed:i}=r,a=t.chunks.length,d=t.chunks[o];i.push({number:d.number,changeRequestId:s.chunk.changeRequestId,commitId:s.commitId});let l=Kv(e,PW(d,t,n));if(l.length>0)throw TS(d,a,i,r.recorded.baseCommitId,`the ids of ${P(l.length,"new element")} could not be written into the files (${W(l[0].location.file)}: ${l[0].reason})`,{missing:l.map(m=>({file:m.location.file,at:wt(m.location.path),id:m.id,reason:m.reason}))});let c={...r.recorded,baseCommitId:s.commitId,baseRootRevision:s.envelope?.rootElement.revisionId};try{hn(e,c)}catch(m){throw TS(d,a,i,r.recorded.baseCommitId,`workspace.json could not be written (${W(m.message)})`,{})}r.recorded=c},QW=async(e,t)=>{let{context:n,target:r,plan:s,base:o}=e,i=s.chunks.length,a=n.flags["request-id"],d=a===void 0?"":` with --request-id ${a}`;try{return await Bi(n,r,{chunks:s.chunks.map(l=>({actions:l.actions,message:OS(o.message,l,i),changeRequestId:FW(a,s.hash,{number:l.number,total:i},n.origin)})),stableIds:!1,persisted:XW(e,t),retryHint:`Run 'modeldesk model diff': a stale workspace means it landed (re-pull, then push what is left); otherwise push again${d}.`})}catch(l){throw jW(l,r.model.id)}},ZW=async(e,t,n)=>{let{context:r,dir:s,modelId:o,target:i,name:a,base:d}=e;if(t.draftId===void 0)throw new u(`Your draft of ${a} holds no staged change, so there is nothing to commit.`,{type:"nothing-to-commit"});let l=await bs(r,o),{landing:c,recovered:m}=await kr(r,l,{id:t.draftId,targetRefId:i.branch.id,baselineCommitId:i.draft?.baselineCommitId??i.head},{message:d.message,expectedDraftHeadId:t.head}),f=c.commit.id;n.recorded={...n.recorded,baseCommitId:f},hn(s,n.recorded);let h=Cr(c,i.model),p={...Er(c),recovered:m,...h===void 0?{}:{next:h},url:te(r.instance(),{kind:"commit",modelId:o,commitId:c.commit.id})};return{headNow:f,commit:p}},eB=(e,t,n)=>{try{return _t(jt(e.read),dp(t,n)).ops.length>0}catch{return!0}},tB=(e,t,n,r,s)=>{let o=$d(n.read),i=r.format==="json"?qd(o):Fd(o),a=pd(t,i,s);return a.collisions.length===0?(ud(t,i,a),{manifest:Co(i),refreshed:!0}):(e.warn(`The files stay as pushed: rewriting them from the server would overwrite files the workspace did not write (${a.collisions.slice(0,3).map(W).join(", ")}).`),{manifest:s,refreshed:!1})},nB=async(e,t,n)=>{let{context:r,dir:s}=e,{recorded:o}=t,i=await To(r,s,o);if(i.head!==n)return r.warn("The target moved right after the push, so the files stay as pushed; re-pull before editing on."),!1;let a=ap(s,o),d={manifest:Co(a),refreshed:!1};return eB(i,a,o.format)&&(d=tB(r,s,i,o,d.manifest)),hn(s,{...o,files:d.manifest,baseRootRevision:Xn(i)}),d.refreshed},rB=async e=>{let{context:t,state:n,plan:r,base:s}=e;if(PS(e))throw JW(e.deletes);let o={recorded:n,landed:[]},i=await QW(e,o),a=i.head,d=i.chunks.map((p,g)=>({...AS(r.chunks[g]),changeRequestId:p.chunk.changeRequestId,commitId:p.commitId})),l;t.flags.commit&&({headNow:a,commit:l}=await ZW(e,i,o));let m=(o.landed.length>0||l!==void 0)&&await nB(e,o,a),f=Object.fromEntries(r.ids);return{result:{...s,headCommitId:a,chunks:d,staged:o.landed.length,...Object.keys(f).length>0&&{createdIds:f},...l&&{commit:l},...m&&{refreshed:m}}}},sB=e=>X(async()=>{let t=await KW(e);return e.globals.dryRun?zW(t):rB(t)}),oB=e=>e.validation==="client-checked"?`client-checked: it stands on change ${(e.dependsOn??[]).join(", ")} (an element it creates, updates, moves or deletes, or a list it changes that this change places into), which a dry run does not keep, so the server validates it when it is staged`:e.verdict==="valid"?`validated by the server: ${e.affected?.changed.length??0} element(s) changed, ${e.affected?.removed.length??0} removed`:`REFUSED by the server: ${(e.errors??[]).map(t=>y(t.message)).join("; ")}`,iB=(e,t)=>{let n=[`Plan against ${st(e.ref,t)} at ${e.baseCommitId}: `+(e.ops.length===0?"nothing to push.":`${P(e.ops.length,"operation")} (${$o(e.counts)}) in ${P(e.chunks.length,"change")}.`)],r=Ed(e.ops,e.labels);for(let s of e.chunks){let o=e.chunks.length>1?`Change ${s.number}/${e.chunks.length}`:"The change";n.push(`${o} (${P(s.actions,"action")}): ${oB(s)}.`,...r.slice(s.firstOp,s.firstOp+s.opCount).map(i=>` ${i}`))}return e.ops.length>0&&(n.push(`plan: ${e.planHash}`),e.counts.delete>0&&n.push("The plan deletes; push it with --allow-delete."),n.push(`Push exactly this plan: modeldesk model push ${W(e.dir)} -m <message> --plan ${e.planHash.slice(0,16)}`+(e.counts.delete>0?" --allow-delete":""))),n.join(`
256
+ `)},aB=e=>{let t=y(e.model.name);if(e.dryRun)return iB(e,t);let n=[];return e.rebound&&n.push(Sd(e.ref,t,e.rebound.from,e.baseCommitId)),e.staged===0&&e.commit===void 0?n.push(`Nothing to push: the workspace matches ${st(e.ref,t)}.`):e.staged>0&&n.push(`Staged ${P(e.staged,"change")} (${$o(e.counts)}) in your draft of ${t}: ${y(e.message)}`,...e.chunks.map(r=>` change ${r.number}/${e.chunks.length}: ${r.commitId} (${P(r.actions,"action")})`)),e.commit?n.push(...Dn(e.commit)):e.staged>0&&n.push("Review and commit it in the app, where the changes panel shows it."),(e.staged>0||e.commit)&&n.push(`Workspace base: ${e.headCommitId}${e.refreshed?" (files refreshed from the server)":""}.`),n.push(`url: ${e.url}`),n.join(`
257
+ `)},LS=q({path:["model","push"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a workspace's changes on your draft",description:"Stages what 'modeldesk model diff' shows on your draft on the workspace's branch (opening the draft there when you hold none), as validated changes carrying the message, cut into as many changes as the server bounds need (1000 actions or 8 MiB each), each message suffixed (n/m). A workspace whose target moved since it was pulled is refused (exit 5) before anything is written. --dry-run has the server validate each change without keeping it and prints the plan with its hash; --plan <hash> then pushes only that exact plan. After each change lands the workspace records it (new ids written into the files, the base moved on), so a push stopped by a refusal leaves a workspace whose diff shows only what is left. Deletes need --allow-delete. --commit then lands the draft as one commit, under the same rules as draft commit.",positionals:[Jr],flags:{...wi,plan:{type:"string",placeholder:"hash",description:"Push only if the plan hash (or at least its first 12 characters) still matches."},"allow-delete":{type:"boolean",description:"Allow the push to delete the elements the workspace dropped."},"request-id":{type:"string",placeholder:"id",description:"The request id to stage under: a cli-\u2026 id this session minted is sent as given, any other id seeds a cli-\u2026 id derived from it (for each change of a push of several, from it and the change number). Derived from the plan hash when left out. Unlike on an el write it is not looked up: a change that landed leaves the workspace stale, which is what stops a push staging it twice."},commit:{type:"boolean",description:"Land the draft after staging, with the same message. Under an agent host this is left to a person (exit 6) unless MODELDESK_ALLOW_COMMIT=1 or the draft aims at a branch named agent/<topic>."},...Uc},dryRun:!0,prepare:Cd,examples:['modeldesk model push -m "Add the severity binding" --dry-run','modeldesk model push -m "Add the severity binding" --plan 3f2a9c1e5b7d'],run:sB,render:aB});var Pp=10,dB=e=>({id:e.id,name:e.name,commitId:e.commitId,createdAt:e.createdAt,...e.description?{description:e.description}:{}}),DS=e=>e instanceof U&&(e.status===403||e.status===404),_S=e=>({items:e.slice(0,Pp).map(dB),truncated:e.length>Pp}),lB=async(e,t,n)=>{if(n)try{let r=await e.metamodelModels.versions(t);return _S([...r].sort((s,o)=>Date.parse(o.createdAt)-Date.parse(s.createdAt)))}catch(r){if(!DS(r))throw r}try{return _S((await e.models.versions(t,{limit:Pp+1})).items)}catch(r){if(DS(r))return;throw r}},cB=({name:e,pin:t})=>{let n=t?.versionName??t?.versionRef??(t?.commitId?`commit ${t.commitId}`:void 0);return n===void 0?y(e):`${y(e)} (pinned to ${y(n)})`},mB=e=>{if(e===void 0)return"unknown";let t=e.name?` ${e.id}`:"";return`${y(e.name??e.id)} (${e.type.toLowerCase()}${t})`},jS=(e,t)=>{let n=t.items.map(s=>{let o=s.pin?.versionRef??(s.pin?"@HEAD":void 0),i=s.pin?.versionName&&s.pin.versionName!==o?` (release ${s.pin.versionName})`:"";return[y(s.name),s.kind.toLowerCase(),o?y(`pinned ${o}${i}`):"",s.modelId??""]}),r=[...F(n,{indent:" "}),...t.hiddenCount>0?[` and ${t.hiddenCount} you cannot read`]:[]];return[`${e}:`,...r.length===0?[" none"]:r]},fB=e=>e.kind==="draft"?e.branch:e.kind==="branch"?e:void 0,pB=({latest:e,changesSinceRelease:t,changesCapped:n})=>{let r=`${t}${n?"+":""} change${t===1?"":"s"}`;return e?`${e.name} (${e.createdAt}), ${r} since`:`none yet, ${r} so far`},uB=(e,t)=>e===void 0?[" not readable with your access"]:t.length===0?[" none"]:F(t,{indent:" "}),hB=e=>{let{head:t}=e.branch,n=t.message?`: ${t.message}`:"",{overview:r}=e,s=[["id:",e.id],["kind:",e.kind],...e.metamodel===void 0?[]:[["metamodel:",cB(e.metamodel)]],["owner:",mB(e.owner)],["branch:",`${y(e.branch.name)} at ${t.id}`],["head:",y(`${t.createdAt} by ${t.author.name??t.author.id}${n}`)],["release:",pB(r.release)],...r.instanceModelCount===void 0?[]:[["instances:",`${r.instanceModelCount} models`]],["url:",e.url]],o=r.signals.map(a=>[a.tone,a.code,y(a.subject?.name??""),Object.entries(a.detail).map(([d,l])=>`${d} ${String(l)}`).join(", ")]),i=(e.versions?.items??[]).map(a=>[a.name,a.createdAt,a.commitId]);return[y(e.name),Ie(e.ref,e),...F(s,{indent:" "}),"",`Overview of branch ${y(r.ref.name)}:`,...jS("Depends on",r.dependsOn),...jS("Depended on by",r.dependedOnBy),"Signals:",...o.length===0?[" none"]:F(o,{indent:" "}),"Versions:",...uB(e.versions,i),...e.versions?.truncated?[" (older versions not shown)"]:[]].join(`
258
+ `)},FS=D({path:["model","show"],effect:"read",summary:"Show a model's identity, dependencies and releases",description:"Shows a model's metamodel and its pin, owner, branch head and latest release, the models it depends on and that depend on it (with their pins and staleness signals), and its newest releases. The identity and the head are read at the ref; the overview and the releases are always main's, and the result says so.",positionals:[_(Oe)],examples:["modeldesk model show <model>","modeldesk model show <model>@feat/shapes","modeldesk model show <model> --json"],run:async e=>{let t=ce(e,e.args.model.model),n=e.api(),r=await Z(e,e.args.model,Oe),{id:s}=r,[o,i,a]=await Promise.all([r.ref.kind==="branch"&&r.ref.branch.main?t.identity():n.models.identity(s,Qe(r.ref)),n.models.overview(s),n.accessTokenClaims()]),d=i.instanceModelCount===void 0?"model":"metamodel",l=await lB(n,s,d==="metamodel"&&Kt(a)),{branch:c}=o,m=re(r),f=fB(m);return{result:{id:o.id,name:o.name,kind:d,...i.metamodel===void 0?{}:{metamodel:{id:i.metamodel.modelId,name:i.metamodel.name,...i.metamodel.pin?{pin:i.metamodel.pin}:{}}},...o.owner?{owner:o.owner}:{},createdAt:o.createdAt,updatedAt:o.updatedAt,ref:m,branch:{id:f?.id??c.id,name:f?.name??c.name,head:{id:c.head.id,createdAt:c.head.createdAt,author:c.head.createdBy,...c.head.message?{message:c.head.message}:{}}},overview:{ref:{kind:"branch",id:r.main.id,name:r.main.name},release:i.release,dependsOn:i.dependsOn,dependedOnBy:i.dependedOnBy,signals:i.signals,...i.instanceModelCount===void 0?{}:{instanceModelCount:i.instanceModelCount}},...l===void 0?{}:{versions:l},url:e.webUrl({kind:"model",modelId:o.id})}}},render:hB});var gB=e=>e.subtreeAt!==void 0?` [multi-owned, listed under ${y(e.subtreeAt)}]`:e.multiOwned?" [multi-owned]":"",yB=e=>e.map(t=>`${" ".repeat(t.depth-1)}${t.label===void 0?"(no label)":y(t.label)} (${t.type})`+gB(t)),qS=D({path:["model","tree"],effect:"read",summary:"Show a model's element tree",description:"Shows the elements of a model as a tree, one line per element with its label and type. An element owned twice appears under each owner, marked. The platform's internal `@` elements are left out, as in the app, unless --internal is passed. Without a ref, reads your draft while it holds staged changes; --json carries every row's id, its label path (usable wherever an element is addressed) and what was read as ref.",positionals:[_(vt)],flags:{depth:{type:"number",placeholder:"n",description:"Show this many levels below the model root."},type:{type:"string",placeholder:"type",description:"Show only elements of this type, with their ancestors for context."},...hr},listing:{narrowHint:"Pass --depth or --type to narrow the tree."},examples:["modeldesk model tree <model> --depth 2","modeldesk model tree <model>@main --type NodeShape --json","modeldesk model tree <model>@feat/shapes"],run:async e=>{let{depth:t,type:n,internal:r}=e.flags;if(t!==void 0&&(!Number.isInteger(t)||t<1))throw I(`--depth must be a positive whole number, got ${t}.`,"modeldesk model tree --help");let{model:s,ref:o,read:i,tree:a}=await gr(e,e.args.model,vt),d=n===void 0?void 0:new Set([sa(_r(i),n,r)]),l=await e.list(it(a,{maxDepth:t,types:d,internal:r}));return{result:{model:s,ref:o,rootElementId:a.rootId,...l}}},render:e=>[Ie(e.ref,e.model),...e.items.length===0?["No elements."]:yB(e.items)].join(`
259
+ `)});import{rmdirSync as wB,rmSync as bB,writeFileSync as kB}from"node:fs";import{dirname as EB,join as WS,posix as Wd}from"node:path";var BS=q({path:["note","add"],effect:"local",summary:"Create an empty note file for an element and add it to the repo's notes.json",description:"Finds the element by name in the last pull's manifest (or by --element), creates an empty note file at the path the next pull reads it from, and records it in .modeldesk/notes.json. A name several elements share is asked about at a terminal and refused elsewhere, listing their ids. The after note of the model or a package needs --heading. Nothing is overwritten, and nothing is written when the command refuses.",positionals:[{name:"name",type:{list:"string"},description:"The element's title; a name of several words may be passed unquoted."}],flags:{slot:{type:{enum:Pe},default:"intro",description:"The slot the note fills: intro, after the element's heading, or after, after its content."},heading:{type:"string",placeholder:"text",description:"The heading the after note of the model or a package comes under (required there)."},dir:{type:"string",placeholder:"dir",description:"The folder to create the note in (default: notesDir in the repo config, or md-notes/)."},element:{type:"string",placeholder:"id",description:"The element's id, which decides when a name is given too."},stack:{type:"string",placeholder:"id",description:"The content stack whose last pull is searched (default: MODELDESK_STACK or the repo config)."}},examples:["modeldesk note add Pand","modeldesk note add Domein Fundering --slot after --heading Afsluiting"],run:async e=>{let{flags:t,args:n}=e,r=dr(e.cwd),{repoRoot:s}=r,o=ms(ss({stack:t.stack},e.env,r.config).stack,"stack",B.stack,"--stack"),i=t.slot,a=Ti(s,o);if(a===void 0)throw new u("Run 'modeldesk bundle pull' first: note add finds the element in the last pull's manifest.");let d=nw(a),l=await IB(e,a,d,n.name.join(" "),t.element),c=Bd(l),m=xB(l,i,c,t.heading),f=xi(o),h=r.config.notesDir??Ko,p=TB(s,f,t.dir??h,l,i),g=WS(s,p),w=Pi(s),k=w.entries.get(l.elementId);if(CB(s,w,k,{slot:i,label:c}),vB(w,p),On(g)!==void 0){let T=l.path!==void 0&&Ni(h,f,l.path,i)===p;throw new u(AB(p,c,i,T))}Tt(w.path);let C=SB(g,p,m),R=new Map(w.entries),$=k===void 0?{...l.title===void 0?{}:{name:l.title},[i]:p}:{...k,[i]:p};R.set(l.elementId,$);try{Li(w.path,Tr(R))}catch(T){throw bB(g,{force:!0}),C(),T instanceof u?T:new u(`Could not write ${w.path}, so ${p} was not kept: ${Fe(T)}`)}return{result:{file:p,slot:i,elementId:l.elementId,...l.title===void 0?{}:{name:l.title},label:c,...m===void 0?{}:{heading:m}}}},render:({file:e,slot:t,label:n,heading:r})=>{let s=r===void 0?"":`, under the heading "${r}"`;return`Created ${e}, the ${t} note of ${n}${s}.`}}),CB=(e,t,n,{slot:r,label:s})=>{let o=n?.[r];if(o===void 0)return;let i=On(WS(e,o))===void 0?"That file does not exist yet: create it":"Write in that file";throw new u(`${s} already has an ${r} note, ${o}. ${i}, or take the entry out of ${t.path} first.`)},vB=(e,t)=>{let n=[...e.entries].find(([,r])=>Pe.some(s=>r[s]!==void 0&&Wd.normalize(r[s])===Wd.normalize(t)));if(n!==void 0)throw new u(`${e.path} already names ${t} as a note of ${n[1].name??n[0]}; pick another folder with --dir.`)},RB=e=>{for(let t of e.toReversed())try{wB(t)}catch{return}},SB=(e,t,n)=>{let r;try{r=xd(EB(e))}catch(o){throw new u(`Could not create ${Wd.dirname(t)}: ${Fe(o)}`)}let s=()=>RB(r);try{kB(e,n===void 0?"":`${Di(n)}
63
260
 
64
- `,{flag:"wx"})}catch(x){throw M(),new l(`Could not create ${p}: ${x.message}`)}let L=new Map(E.entries),F=g===void 0?{...c.title===void 0?{}:{name:c.title},[i]:p}:{...g,[i]:p};L.set(c.elementId,F);try{ft(E.path,Ee(L))}catch(x){throw xd(y,{force:!0}),M(),x instanceof l?x:new l(`Could not write ${E.path}, so ${p} was not kept: ${x.message}`)}let H=m===void 0?"":`, under the heading "${m}"`;return Sd(`Created ${p}, the ${i} note of ${f}${H}.
65
- `),0},Td=e=>{if(e===void 0)return"intro";if(!A.includes(e))throw new l(`--slot takes ${A.join(" or ")}, not "${e}".`);return e},yt=e=>{let t=e.kind===void 0?"":` (${e.kind})`;return e.title===void 0?`${e.elementId}${t}`:`${e.title}${t}`},Id=async(e,t,n,r)=>{if(r!==void 0)return vd(e,t,n,r);if(n.trim()==="")throw new l("Name the element: modeldesk note add <name>, or pass --element <id>.");let o=dn(t,n);if(o.length===1)return o[0];if(o.length===0){let i=uo(an(e),n);if(i.length>0)throw new l(`"${n.trim()}" is ${Go(i)}; anchor-level parts carry no note slots.`);let a=ho(t,n),d=a.length===0?"":` Did you mean ${a.map(c=>`"${c}"`).join(", ")}?`;throw new l(`No element in the last pull's manifest is named "${n.trim()}".${d}`)}if(de()){xn(`Several elements are named "${n.trim()}":
66
- `);let i=o.map((d,c)=>[`${c+1}.`,yt(d),d.path??""]);xn(`${q(i,{indent:" "}).join(`
261
+ `,{flag:"wx"})}catch(o){throw s(),new u(`Could not create ${t}: ${Fe(o)}`)}return s},Bd=e=>{let t=e.kind===void 0?"":` (${e.kind})`;return e.title===void 0?`${e.elementId}${t}`:`${e.title}${t}`},IB=async(e,t,n,r,s)=>{if(s!==void 0)return $B(e,t,n,r,s);if(r.trim()==="")throw new u("Name the element: modeldesk note add <name>, or pass --element <id>.");let o=Cc(n,r);if(o.length===1)return o[0];if(o.length===0){let a=rw(Ec(t),r);if(a.length>0)throw new u(`"${r.trim()}" is ${HS(a)}; anchor-level parts carry no note slots.`);let d=sw(n,r),l=d.map(m=>`"${m}"`).join(", "),c=d.length===0?"":` Did you mean ${l}?`;throw new u(`No element in the last pull's manifest is named "${r.trim()}".${c}`)}if(e.interactive){e.io.err(`Several elements are named "${r.trim()}":
262
+ `);let a=o.map((l,c)=>[`${c+1}.`,Bd(l),l.path??""]);e.io.err(`${F(a,{indent:" "}).join(`
67
263
  `)}
68
- `);let a=await Do("Which one?",o.length);if(a===void 0)throw new l("No element chosen, so nothing was created.");return o[a]}let s=o.map(i=>[i.elementId,yt(i),i.path??""]);throw new l(`Several elements in the last pull's manifest are named "${n.trim()}"; pass --element <id> to pick one:
69
- `+q(s,{indent:" "}).join(`
70
- `))},vd=(e,t,n,r)=>{let o=r.trim().toLowerCase();if(o==="")throw new l("--element is blank; give the id of the element the note is for.");let s=t.find(i=>i.elementId===o);if(s===void 0){let i=an(e).filter(a=>a.elementId===o);throw i.length>0?new l(`${r.trim()} is ${Go(i)}; anchor-level parts carry no note slots.`):new l(`The last pull's manifest has no element ${r.trim()}. Run 'modeldesk bundle pull' if the model changed since.`)}return n.trim()!==""&&dn([s],n).length===0&&xn(`note: --element picks ${yt(s)}, so the name "${n.trim()}" was ignored.
71
- `),s},Go=e=>{let t=e.map(n=>{let r=/^[aeiou]/i.test(n.kind)?"an":"a";return n.owner===void 0?`${r} ${n.kind}`:`${r} ${n.kind} inside ${n.owner}`});return[...new Set(t)].join(" or ")},Cd=(e,t,n,r)=>{if(t==="after"&&e.container){if(e.anchor===void 0)throw new l(`The last pull's manifest gives ${n} no anchor to build its after heading's id from, so a note there cannot be placed.`);if(r===void 0)throw new l(`The after note of ${n} comes under a heading of its own; pass --heading <text>.`);let o=De(r);if(o!==void 0)throw new l(`--heading ${o}; give the text of the heading the note comes under on one line.`);return r.trim()}if(r!==void 0)throw new l(`--heading is only for the after note of the model or a package; the ${t} note of ${n} takes none.`)},Nd=(e,t,n,r,o)=>{let s=ct(n,t)??ln(e,n);if(s!==void 0)throw new l(`${s[0].toUpperCase()}${s.slice(1)}.`);let a=(r.path===void 0?void 0:lt(n,t,r.path,o))??gt.join(n,`${ne(r.title??"")||r.elementId}${o==="after"?".after":""}.md`),[d]=hn(e,t,a);if(d!==void 0)throw new l(`${d[0].toUpperCase()}${d.slice(1)}. Pick another folder with --dir, or "notesDir" in .modeldesk/config.json.`);return a},Ad=(e,t,n,r)=>r?`${e} already exists, and note add never overwrites a file. The next pull places it as the ${n} note of ${t}; write in it.`:`${e} already exists, and note add never overwrites a file; pick another folder with --dir.`;var bn={bundle:{pull:{summary:"Materialize a model's content bundle into a local folder",usage:"bundle pull --model <id> --stack <id> --template <slug> [--host <host>] [--version <name>] [--no-diagrams] [--dry-run]",handler:Uo},templates:{summary:"List a model's document templates",usage:"bundle templates --model <id> [--stack <id>] [--host <host>]",handler:jo}},note:{add:{summary:"Create an empty note file for an element and add it to the repo's notes.json",usage:"note add <name> [--slot intro|after] [--heading <text>] [--dir <dir>] [--element <id>] [--stack <id>]",handler:zo}},auth:{login:{summary:"Log in through the browser (OAuth authorization code + PKCE)",usage:"auth login [--host <host>]",handler:Qn},logout:{summary:"Remove the stored credential for the active host",usage:"auth logout [--host <host>]",handler:er},status:{summary:"Show the active host, logged-in identity, and token validity",usage:"auth status [--host <host>]",handler:tr}}};var Ko={name:"@modeldesk/cli",version:"0.6.0",description:"Command-line interface (CLI) for the ModelDesk platform",keywords:["modeldesk","cli","documentation","content-bundle","respec","mim","information-model"],homepage:"https://modeldesk.io",repository:{type:"git",url:"git+https://github.com/model-desk/modeldesk.git",directory:"packages/cli"},license:"MIT",type:"module",bin:{modeldesk:"dist/modeldesk.js"},files:["dist"],publishConfig:{access:"public"},engines:{node:">=22"},scripts:{build:"node esbuild.config.mjs",prepublishOnly:"npm run build",typecheck:"tsc --noEmit",lint:"eslint","lint:fix":"eslint --fix",test:"vitest run","test:watch":"vitest"},devDependencies:{"@eslint/js":"^10.0.1","@modeldesk/content-bundle":"*","@types/node":"^24.19.1",esbuild:"^0.28.2",eslint:"^10.12.0","eslint-config-prettier":"^10.1.5","eslint-plugin-prettier":"^5.5.6",globals:"^17.13.0",prettier:"^3.9.9",typescript:"^6.0.3","typescript-eslint":"^8.71.1",vitest:"^5.0.4"}};var Vo=Ko.version;var Rd={out:e=>process.stdout.write(e),err:e=>process.stderr.write(e)},Xo=new Set(["--help","-h","help"]),qo=async(e,t=Rd)=>{try{return await Pd(e,t)}catch(n){return n instanceof l?(t.err(`error: ${n.message}
72
- `),n.exitCode):(t.err(`error: ${n instanceof Error?n.message:String(n)}
73
- `),1)}},Pd=async(e,t)=>{let[n,...r]=e;if(n===void 0||Xo.has(n))return t.out(_d()),0;if(n==="--version"||n==="-v")return t.out(`${Vo}
74
- `),0;let o=bn[n];if(!o)throw new l(`Unknown command '${n}'. Run 'modeldesk --help' to see available commands.`);let[s,...i]=r;if(s===void 0){let f=Object.keys(o).join(", ");throw new l(`'${n}' requires a subcommand (${f}). Run 'modeldesk ${n} --help'.`)}if(Xo.has(s))return t.out(Ld(n,o)),0;let a=o[s];if(!a)throw new l(`Unknown '${n}' command '${s}'. Run 'modeldesk ${n} --help'.`);let d={argv:i,env:process.env,cwd:process.cwd()},c=await a.handler(d);return typeof c=="number"?c:0},Jo=[["--help, -h","Show help"],["--version, -v","Show the CLI version"]],_d=()=>{let e=[];for(let[r,o]of Object.entries(bn))for(let[s,i]of Object.entries(o))e.push([`${r} ${s}`,i.summary]);let[t]=ht([...e,...Jo]);return`${["ModelDesk CLI","","Usage: modeldesk <command> <subcommand> [options]","","Commands:",...q(e,{indent:" ",widths:[t]}),"","Global options:",...q(Jo,{indent:" ",widths:[t]}),""].join(`
264
+ `);let d=await e.choose("Which one?",o.length);if(d===void 0)throw new u("No element chosen, so nothing was created.");return o[d]}let i=o.map(a=>[a.elementId,Bd(a),a.path??""]);throw new u(`Several elements in the last pull's manifest are named "${r.trim()}"; pass --element <id> to pick one:
265
+ `+F(i,{indent:" "}).join(`
266
+ `))},$B=(e,t,n,r,s)=>{let o=s.trim().toLowerCase();if(o==="")throw new u("--element is blank; give the id of the element the note is for.");let i=n.find(a=>a.elementId===o);if(i===void 0){let a=Ec(t).filter(d=>d.elementId===o);throw a.length>0?new u(`${s.trim()} is ${HS(a)}; anchor-level parts carry no note slots.`):new u(`The last pull's manifest has no element ${s.trim()}. Run 'modeldesk bundle pull' if the model changed since.`)}return r.trim()!==""&&Cc([i],r).length===0&&e.io.err(`note: --element picks ${Bd(i)}, so the name "${r.trim()}" was ignored.
267
+ `),i},HS=e=>{let t=e.map(n=>{let r=/^[aeiou]/i.test(n.kind)?"an":"a";return n.owner===void 0?`${r} ${n.kind}`:`${r} ${n.kind} inside ${n.owner}`});return[...new Set(t)].join(" or ")},xB=(e,t,n,r)=>{if(t==="after"&&e.container){if(e.anchor===void 0)throw new u(`The last pull's manifest gives ${n} no anchor to build its after heading's id from, so a note there cannot be placed.`);if(r===void 0)throw new u(`The after note of ${n} comes under a heading of its own; pass --heading <text>.`);let s=As(r);if(s!==void 0)throw new u(`--heading ${s}; give the text of the heading the note comes under on one line.`);return r.trim()}if(r!==void 0)throw new u(`--heading is only for the after note of the model or a package; the ${t} note of ${n} takes none.`)},TB=(e,t,n,r,s)=>{let o=Mi(n,t)??Rc(e,n);if(o!==void 0)throw new u(`${o[0].toUpperCase()}${o.slice(1)}.`);let a=(r.path===void 0?void 0:Ni(n,t,r.path,s))??Wd.join(n,`${Tn(r.title??"")||r.elementId}${s==="after"?".after":""}.md`),[d]=Tc(e,t,a);if(d!==void 0)throw new u(`${d[0].toUpperCase()}${d.slice(1)}. Pick another folder with --dir, or "notesDir" in .modeldesk/config.json.`);return a},AB=(e,t,n,r)=>r?`${e} already exists, and note add never overwrites a file. The next pull places it as the ${n} note of ${t}; write in it.`:`${e} already exists, and note add never overwrites a file; pick another folder with --dir.`;var Lp=e=>e===void 0||e===Ce,US=e=>{let t=[];return Lp(e.versionRef)?e.targetHeadCommitId!==void 0&&e.targetHeadCommitId!==e.commitId&&t.push("head-moved"):(e.newerRelease!==void 0&&t.push("newer-release"),e.releaseCommitId===null?t.push("release-missing"):e.releaseCommitId!==void 0&&e.releaseCommitId!==e.commitId&&t.push("release-moved")),{standing:t.length===0?"current":"behind",reasons:t}};var VS={pinList:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"What the pins were read at: your draft while it holds staged changes, else your working branch, or the ref named."},newerReleaseChecked:{type:"boolean",description:"Whether the newer-release check ran. It reads the overview, which a caller's access may not reach; the commit comparisons run either way. One of false, true."},items:{type:"array",items:{type:"object",properties:{kind:{type:"string",description:'`internal`: a dependency on another model, whose pin can be moved. `managed`: built-in elements a metamodel supplies, pinned through the metamodel version. `external`: a document outside the platform. `metamodel` and `extension`: the model\'s own metamodel and the extensions it applies. One of "extension", "external", "internal", "managed", "metamodel".'},name:{type:"string"},dependencyId:{type:"string",description:"The dependency's id, by which its pin is moved; absent on a metamodel or extension pin."},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},location:{type:"string",description:"An external document's address."},versionRef:{description:"An internal pin's selector as authored: `@HEAD`, a version name, or null on a legacy edge (tracks the head). May be null."},commitId:{type:"string"},release:{type:"string",description:"The release the pin resolves to: a version pin's, or the version label of a metamodel pin. Never a head pin's."},source:{type:"object",properties:{metamodelId:{type:"string"},version:{type:"string"}},description:"A managed pin's source: the metamodel or extension, and its release, that supplies the built-ins."},settable:{type:"boolean",description:"Whether its pin can be moved: an internal pin main holds. Read at a draft or another branch, a dependency that exists only there cannot, since a pin is moved on main. One of false, true."},standing:{type:"string",description:`An internal pin's standing; read-only pins have none. One of "behind", "current".`},reasons:{type:"array",items:{type:"string",description:'One of "head-moved", "newer-release", "release-missing", "release-moved".'}},latestRelease:{type:"string",description:"The newer release a version pin trails."}}}},truncated:{type:"boolean",description:"True when more rows exist than this page carries. One of false, true."},nextCursor:{type:"string",description:"Where the next page starts, to continue from; present exactly when truncated."},hint:{type:"string",description:"One line on how to continue or narrow the query; present exactly when truncated."}},required:["schemaVersion","model","ref","newerReleaseChecked","items","truncated"]}};var MB=e=>new Map((e?.signals??[]).flatMap(t=>t.code==="DEPENDENCY_MOVED_ON"&&t.subject&&typeof t.detail.latestVersion=="string"?[[t.subject.modelId,t.detail.latestVersion]]:[])),NB=(e,t)=>new Map([...e.metamodel?[[e.metamodel.id,e.metamodel.name]]:[],...(e.metamodelExtensions??[]).map(n=>[n.id,n.name]),...t?.metamodel?[[t.metamodel.modelId,t.metamodel.name]]:[]]),PB=(e,t)=>Vi(e).map(n=>{let r=t.get(n.modelId)??n.modelId;return{kind:n.role,name:r,target:{id:n.modelId,name:r},...n.commitId?{commitId:n.commitId}:{},...n.version?{release:n.version}:{},settable:!1}}),LB=async(e,t,n,r,s)=>{let o=Lp(t.versionRef),[i,a]=await Promise.all([o?e.models.identity(t.modelId).then(m=>m.branch.head.id):void 0,o||t.versionRef===void 0?void 0:Or(e,t.modelId,t.versionRef)]),d=o?void 0:r.get(t.modelId),{standing:l,reasons:c}=US({versionRef:t.versionRef,commitId:t.commitId,...i===void 0?{}:{targetHeadCommitId:i},...a===void 0?{}:{releaseCommitId:a},...d===void 0?{}:{newerRelease:d}});return{kind:"internal",name:t.name,dependencyId:t.id,target:{id:t.modelId,...n?{name:n}:{}},versionRef:t.versionRef??null,commitId:t.commitId,...o?{}:{release:t.versionRef},settable:s,standing:l,...c.length>0?{reasons:c}:{},...d?{latestRelease:d}:{}}},DB=async(e,t,n,r,s)=>{let o=new Map((n?.dependsOn.items??[]).flatMap(d=>d.modelId?[[d.modelId,d.name]]:[])),i=MB(n),a=t.filter(d=>!d.transitive);return Promise.all(a.map(async d=>{switch(d.type){case"EXTERNAL":return{kind:"external",name:d.name,dependencyId:d.id,location:d.location,settable:!1};case"MANAGED":{let l=s.get(d.sourceMetamodelId);return{kind:"managed",name:d.name,dependencyId:d.id,target:{id:d.modelId,...l?{name:l}:{}},commitId:d.commitId,source:{metamodelId:d.sourceMetamodelId,version:d.sourceMetamodelVersion},settable:!1}}case"INTERNAL":return LB(e,d,o.get(d.modelId)??d.name,i,r?.has(d.id)??!0)}}))},_B={"newer-release":"newer release","release-moved":"release re-released","release-missing":"release gone","head-moved":"head moved"},jB=e=>e.kind!=="internal"?"":e.versionRef===null?"@HEAD (legacy)":y(e.versionRef??""),FB=e=>e.standing===void 0?"read-only":e.standing==="current"?"current":`behind (${(e.reasons??[]).map(n=>n==="newer-release"&&e.latestRelease?`newer release ${y(e.latestRelease)}`:_B[n]).join(", ")})`,qB=["ID","KIND","NAME","TARGET","SELECTOR","COMMIT","RELEASE","STANDING"],GS=D({path:["pin","list"],effect:"read",summary:"List a model's pins and whether each is behind",description:"Lists the model's metamodel and extension pins and its direct dependencies, as the addressed ref holds them, so a dependency staged in your draft shows before it is committed: the id pin set takes, name, target, selector (@HEAD, a version name, or @HEAD (legacy) on an edge that predates selectors), commit, release and standing. A version pin is behind when a newer release exists or its release was re-released in place; a @HEAD pin is behind when the target's head moved past it. Managed, external, metamodel and extension pins are read-only here. pin set moves a pin on main only, so a dependency that exists only in your draft or on a branch is listed as not settable; a newer release is looked for on main.",positionals:[_(Oe)],listing:{},examples:["modeldesk pin list <model>","modeldesk pin list <model>@draft --json"],mcp:{name:"list_dependencies",description:"Lists the model's dependencies at the ref you give, ones staged in your draft included: each with its dependencyId, the target model's id and name, the release it is pinned to (versionRef @HEAD tracks the target's head) and whether it is behind. Its metamodel and extension pins come first. Call it before dependency_add, to see whether the model already depends on a model and which release it pins."},resultSchema:VS.pinList,prepare:async e=>({machine:le(e.env)!==void 0}),run:async(e,t)=>{await pt(e,e.args.model.model,{readsOnly:!0,machine:t?.machine===!0});let n=tt(e,e.args.model.model),r=e.api(),s=await Z(e,e.args.model,Oe),o=s.id,i=Qe(s.ref),[a,d,l,c]=await Promise.all([n.model.identity(),n.overviewIfReadable(),r.dependencies.list(o,i),r.models.get(o,i)]),f=s.ref.kind==="branch"&&s.ref.branch.main?void 0:new Set((await r.dependencies.list(o)).items.filter(w=>!w.transitive).map(w=>w.id)),h=NB(c,d),p=[...PB(c,h),...await DB(r,l.items,d,f,h)];return{result:{model:{id:a.id,name:a.name},ref:re(s),newerReleaseChecked:d!==void 0,...await e.list(p)}}},render:e=>{let t=e.items.map(n=>[n.dependencyId??"",n.kind,y(n.name),y(n.target?.name??n.target?.id??n.location??""),jB(n),n.commitId?J(n.commitId):"",y(n.release??""),FB(n)]);return[Ie(e.ref,e.model),`Pins of ${y(e.model.name)}:`,...t.length===0?["No pins."]:F([qB,...t]),...e.newerReleaseChecked?[]:["Newer releases were not checked: your access does not reach the model's overview."]].join(`
268
+ `)}});var WB=e=>String.raw`\u${e.codePointAt(0).toString(16).padStart(4,"0")}`,_p=e=>`${JSON.stringify(e).replace(/[\u007f-\u009f]/g,WB)}
269
+ `,BB=(e,t)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`'${e.path.join(" ")}' returned a result that is not a JSON object.`);return{schemaVersion:e.schemaVersion??1,...t}},YS=(e,t,n,r,s={})=>{if(t&&n.listing&&s.allRows){for(let a of r.items)e.out(_p(a));return}if(t){e.out(_p(BB(n,r)));return}let o=pe(n.render?.(r,s.flags??{})??"");o!==""&&e.out(o.endsWith(`
270
+ `)?o:`${o}
271
+ `);let i=r;n.listing&&i.truncated&&i.hint&&e.err(pe(`note: ${i.hint}
272
+ `))},HB=e=>e instanceof Error?e.message:String(e),_o=e=>e instanceof u?e:new u(HB(e)),UB=e=>({code:e.exitCode,message:e.reason,...e.hint?{hint:e.hint}:{},retryable:e.exitCode===b.Transient,...e.type?{type:e.type}:{},...e.requestId?{requestId:e.requestId}:{},details:e.details}),Dp=e=>e!==null&&typeof e=="object"?JSON.stringify(e):String(e),KS=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return Dp(e);let{message:t,...n}=e,r=Object.entries(n).filter(([,o])=>o!=null).map(([o,i])=>`${o} ${Dp(i)}`).join(", ");if(t===void 0)return r;let s=Dp(t);return r===""?s:`${s} (${r})`},VB=e=>Object.entries(e).flatMap(([t,n])=>Array.isArray(n)?[` ${t}:`,...n.map(r=>` - ${KS(r)}`)]:[` ${t}: ${KS(n)}`]),jp=(e,t,n)=>{let r=_o(n);if(t)e.err(_p({error:UB(r)}));else{let o=VB(r.details).map(i=>`${i}
273
+ `).join("");e.err(pe(`error: ${r.message}
274
+ ${o}`))}return r.exitCode};var GB=(e,t)=>{let r=Object.values(e.elements).find(s=>s.type==="@ManagedDependency"&&s.attributes?.["@modelId"]?.[0]===t)?.attributes?.["@commitId"]?.[0];return typeof r=="string"?r:void 0},KB=async(e,t)=>{let n=t.releaseId?(await ft(e,t.modelId)).find(a=>a.id===t.releaseId):void 0,r=Pn(await e.releases.createMetamodelRelease(t.modelId,n?.description)),s=t.releaseId!==void 0&&r.id===t.releaseId,o=n??{commitId:t.fromCommitId,builtInCommitId:t.fromBuiltInCommitId};return{...{id:r.id,name:r.name,commitId:r.commitId,createdAt:r.createdAt,...r.description?{description:r.description}:{}},inPlace:s,moved:s&&(r.commitId!==o.commitId||r.builtInCommitId!==o.builtInCommitId)}},YB=async(e,t)=>{if(t.kind==="refresh-pin"){let r=await e.dependencies.update(t.modelId,t.dependencyId,{versionRef:t.versionRef}),s="commitId"in r?r.commitId:void 0;return{changed:s!==t.fromCommitId,...s?{commitId:s}:{}}}let n=GB(await e.releases.refreshExtensionBase(t.modelId),t.baseId);return{changed:n!==t.fromCommitId,...n?{commitId:n}:{}}},zS=async(e,t,n)=>{let r=[],s=new Set;for(let o of t){let i={step:o.step,kind:o.kind,modelId:o.modelId,modelName:o.modelName},a;try{if(o.kind!=="re-release"){let d=await YB(e,o);d.changed&&s.add(o.modelId),a={...i,status:"done",...d}}else o.reason==="pins-move"&&o.outdated===void 0&&!s.has(o.modelId)?a={...i,status:"skipped"}:a={...i,status:"done",release:await KB(e,o)}}catch(d){let l=_o(d);return a={...i,status:"failed",error:{message:l.message,code:l.exitCode,...l.type?{type:l.type}:{}}},r.push(a),n(a),{outcomes:r,failure:l}}r.push(a),n(a)}return{outcomes:r}};var zB=e=>new Map([...e.draftModelIds.map(t=>[t,{role:"metamodel"}]),...e.metamodels.map(t=>[t.id,{role:"metamodel"}]),...e.extensions.map(t=>[t.id,{role:"extension",baseId:t.metamodel}])]),JB=async(e,t)=>{let[n,r,s]=await Promise.all([e.models.overview(t),e.models.identity(t),e.dependencies.list(t)]);return{id:t,name:r.name,headCommitId:r.branch.head.id,overview:n,dependencies:s.items}},XB=async(e,t)=>{let[n,r]=await Promise.all([ft(e,t),e.models.get(t)]),s=Gi(r);return{releases:n,...s?{standardVersion:s}:{}}},QB=e=>{let t=new Map;for(let{id:n,overview:r}of e)for(let s of r.signals){let o=s.detail.latestVersion;s.subject===void 0||typeof o!="string"||(s.code==="DEPENDENT_BEHIND"?t.set(`${s.subject.modelId} ${n}`,o):s.code==="DEPENDENCY_MOVED_ON"&&t.set(`${n} ${s.subject.modelId}`,o))}return t},ZB=(e,t,n,r)=>{let s=new Set,{dependedOnBy:o}=e.overview;o.hiddenCount>0&&r.hiddenDependents.push({modelId:e.id,count:o.hiddenCount});for(let i of o.items)i.modelId!==void 0&&(t.has(i.modelId)?s.add(i.modelId):r.outside.set(`${i.modelId} ${e.id}`,{modelId:i.modelId,name:i.name,targetId:e.id}));return n.extensions.filter(i=>i.metamodel===e.id).forEach(({id:i})=>s.add(i)),s},eH=async(e,t,n,r)=>{let s={nodes:new Map,hiddenDependents:[],outside:new Map},o=[t];for(;o.length>0;){let i=await Promise.all(o.map(d=>JB(e,d)));i.forEach(d=>s.nodes.set(d.id,d)),o=[...new Set(i.flatMap(d=>[...ZB(d,n,r,s)]))].filter(d=>!s.nodes.has(d))}return s},tH=(e,t,n,r)=>({id:e.id,name:e.name,role:t.role,...t.baseId?{baseId:t.baseId}:{},headCommitId:e.headCommitId,released:n!==void 0,...r?{outdated:r}:{},...n?.standardVersion?{standardVersion:n.standardVersion}:{},releases:n?.releases??[],...e.overview.instanceModelCount===void 0?{}:{instanceModelCount:e.overview.instanceModelCount}}),nH=async(e,t,n,r)=>{let s=new Map(await Promise.all([...t.keys()].filter(i=>!r.draftModelIds.includes(i)).map(async i=>[i,await XB(e,i)]))),o=r.outdatedReleases;return Object.fromEntries([...t.values()].map(i=>[i.id,tH(i,n.get(i.id)??{role:"metamodel"},s.get(i.id),o[i.id])]))},rH=(e,t,n,r)=>{if(t.transitive||!n.has(t.modelId)||t.modelId===e.id)return;let s=r.get(`${e.id} ${t.modelId}`);return{modelId:e.id,dependencyId:t.id,name:t.name,targetId:t.modelId,...t.versionRef?{versionRef:t.versionRef}:{},commitId:t.commitId,...s?{newerRelease:s}:{}}},sH=e=>{let t=QB([...e.values()]);return[...e.values()].flatMap(n=>n.dependencies.flatMap(r=>r.type==="INTERNAL"?rH(n,r,e,t)??[]:[]))},oH=(e,t,n)=>{let r=[],s=[];for(let o of e.values()){let i=t[o.id].baseId;if(i!==void 0)for(let a of o.dependencies){if(a.type!=="MANAGED"||!e.has(a.modelId))continue;let d={modelId:o.id,dependencyId:a.id,targetId:a.modelId,commitId:a.commitId};a.modelId===i?r.push(d):n.get(a.modelId)?.role==="extension"&&s.push(d)}}return{basePins:r,siblingPins:s}},JS=async(e,t,n)=>{let r=zB(n),{nodes:s,hiddenDependents:o,outside:i}=await eH(e,t,r,n),a=await nH(e,s,r,n);return{baseId:t,models:a,edges:sH(s),...oH(s,a,r),hiddenDependents:o,outsideDependents:[...i.values()]}},XS=async(e,t)=>{let n=Object.values(t.models);return(await Promise.all(n.map(async s=>{let[o,i]=await Promise.all([e.models.identity(s.id),s.released?ft(e,s.id):Promise.resolve([])]),a={modelId:s.id,modelName:s.name},d=o.branch.head.id===s.headCommitId?[]:[{...a,kind:"head",from:s.headCommitId,to:o.branch.head.id}],l=new Map(i.map(f=>[f.id,f])),c=new Map(s.releases.map(f=>[f.id,f])),m=[...new Set([...l.keys(),...c.keys()])].flatMap(f=>{let h=c.get(f),p=l.get(f);return h?.commitId===p?.commitId&&h?.builtInCommitId===p?.builtInCommitId?[]:[{...a,kind:"release",release:(p??h)?.name,...h?{from:h.commitId}:{},...p?{to:p.commitId}:{}}]});return[...d,...m]}))).flat()};var QS=8,Fp=500,iH=(e,t,n,r)=>{let s=e.refs.find(a=>a.modelId===t.id&&a.role===(t.role==="metamodel"?"metamodel":"extension"));if(s===void 0)return{status:"not-pinned"};let o=n.find(a=>a.name===s.version);if(s.version===void 0||o===void 0)return{status:"unknown-release",...s.version?{version:s.version}:{}};if(r==="run"&&s.version!==t.awaited)return{status:"other-release",version:s.version};let i=o.builtInCommitId===void 0?void 0:e.builtIns.find(a=>a.sourceMetamodelId===t.id&&a.commitId!==o.builtInCommitId);return s.commitId===o.commitId&&i===void 0?{status:"current",version:s.version}:{status:"behind",version:s.version,...s.commitId?{commitId:s.commitId}:{},expectedCommitId:o.commitId,...i?{builtInCommitId:i.commitId,expectedBuiltInCommitId:o.builtInCommitId}:{}}},ZS=e=>e.behind+e.stuck+e.unverified>0,Hd=e=>e.role==="extension"&&e.baseId?e.baseId:e.id,aH=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:"base"})||e.id.localeCompare(t.id),dH=e=>e instanceof u&&e.exitCode===b.Transient,eI=async(e,t,n)=>{let r=new Map(await Promise.all(t.map(async p=>[p.id,await ft(e,p.id)]))),s=[...new Set(t.map(Hd))],o=[];await jn(s,QS,async p=>{let g=[...(await e.models.list({metamodel:p})).items].sort(aH);o.push({group:p,models:g.slice(0,n.limit),truncated:g.length>n.limit})});let i=o.flatMap(({group:p,models:g})=>g.map(w=>({id:w.id,name:w.name,group:p}))),a=new Set(o.filter(({truncated:p})=>p).map(({group:p})=>p)),d=new Map(i.map(p=>[p.id,{kind:"unread"}])),l=async p=>{try{let g=await e.models.get(p.id),w={refs:Vi(g),builtIns:Xw(g)},k=new Map(t.filter(C=>Hd(C)===p.group).map(C=>[C.id,iH(w,C,r.get(C.id)??[],n.scope)]));d.set(p.id,{kind:"read",standings:k})}catch(g){if(g instanceof U&&g.status===404)d.set(p.id,{kind:"gone"});else if(!dH(g))throw g}},c=p=>{let g=d.get(p.id);return g?.kind==="unread"?!0:g?.kind!=="read"?!1:[...g.standings].some(([w,k])=>{let C=t.find(R=>R.id===w)?.awaited;return k.status==="behind"&&k.version===C})},m=i;await Mo({read:async()=>(await jn(m,QS,l),m=m.filter(c),m.length),settled:p=>p===0,deadline:n.clock.now()+n.timeoutMs,clock:n.clock,interval:n.interval??wp});let f=t.map(p=>{let g=i.filter(v=>v.group===Hd(p)),w=v=>{let T=d.get(v.id);return T?.kind==="read"?T.standings.get(p.id):void 0},k=v=>{let T=w(v);return T?.status!=="behind"?[]:[{id:v.id,name:v.name,version:T.version,...T.commitId?{commitId:T.commitId}:{},expectedCommitId:T.expectedCommitId,...T.builtInCommitId?{builtInCommitId:T.builtInCommitId,expectedBuiltInCommitId:T.expectedBuiltInCommitId}:{}}]},C=g.flatMap(k),R=v=>v.version===p.awaited,$=g.filter(v=>w(v)?.status==="current").length;return{id:p.id,name:p.name,releasedNow:p.releasedNow,...p.awaited?{awaited:p.awaited}:{},checked:g.filter(v=>{let T=w(v);return T!==void 0&&T.status!=="not-pinned"}).length,repinned:$,behind:C.filter(R),stuck:C.filter(v=>!R(v)),otherRelease:g.filter(v=>w(v)?.status==="other-release").length,unknownRelease:g.flatMap(v=>{let T=w(v);return T?.status==="unknown-release"?[{id:v.id,name:v.name,...T.version?{version:T.version}:{}}]:[]}),unverified:g.filter(v=>d.get(v.id)?.kind==="unread").map(({id:v,name:T})=>({id:v,name:T})),gone:g.filter(v=>d.get(v.id)?.kind==="gone").map(({id:v,name:T})=>({id:v,name:T})),truncated:a.has(Hd(p))}}),h=p=>f.reduce((g,w)=>g+p(w),0);return{scope:n.scope,timeoutSeconds:n.timeoutMs/1e3,repinned:h(p=>p.repinned),behind:h(p=>p.behind.length),stuck:h(p=>p.stuck.length),unverified:new Set(f.flatMap(p=>p.unverified.map(g=>g.id))).size,unknownRelease:h(p=>p.unknownRelease.length),truncated:f.some(p=>p.truncated),models:f}};var qp=e=>`'${y(e)}'`,Wp=(e,t=e===void 0)=>t?`${Ce} (legacy)`:y(e??Ce),nI=(e,t)=>e?`; ${y(t)} has a newer release ${y(e)}, which 'pin set' adopts`:"",jo=e=>{switch(e.kind){case"refresh-pin":return`refresh pin ${qp(e.dependencyName)} of ${y(e.modelName)} (${Wp(e.versionRef,e.legacy)})`;case"refresh-base-pin":return`re-pin ${y(e.modelName)} to the head of its base ${y(e.baseName)}`;case"re-release":{if(e.inPlace)return`re-release ${y(e.modelName)} ${y(e.releaseName??"")} in place`;let t=e.release?y(e.release):"(named by the server)";return`release ${y(e.modelName)} ${t} for the first time`}}},lH=(e,t)=>e.reason==="target-moves"?`${t}'s head moves first`:e.reason==="release-moves"?`${t} ${y(e.versionRef)} is re-released first`:`it already trails what ${Wp(e.versionRef,e.legacy)} resolves to`,cH=e=>{switch(e.kind){case"refresh-pin":{let t=y(e.targetName),n=lH(e,t);return`pinned at ${J(e.fromCommitId)}; ${n}${nI(e.newerRelease,e.targetName)}`}case"refresh-base-pin":return`pinned at ${J(e.fromCommitId)}; ${e.reason==="base-moves"?`${y(e.baseName)}'s head moves first`:"it already trails the base head"}`;case"re-release":{let t=e.reason==="pins-move"?"its pins move":`its release trails its head (${e.outdated})`,n=e.unreleasedEdits?"; this publishes its current head, including the edits made since its last release":"",r=e.inPlace&&e.instanceModelCount?`; then the platform re-pins its ${P(e.instanceModelCount,"instance model")}`:"";return`${t}${n}${r}`}}},mH=e=>e.kind==="base-pin"?`- base pin on ${y(e.targetName)} at ${J(e.commitId)} is current`:`- pin ${qp(e.name)} (${Wp(e.versionRef)}) at ${J(e.commitId)} is current`+nI(e.newerRelease,e.targetName),fH=(e,t)=>{let n=e.baseId?t.models.find(o=>o.id===e.baseId)?.name:void 0,r=n?` of ${y(n)}`:"",s=e.role==="extension"?`extension${r}`:"metamodel";return` ${y(e.name)} (${s}${e.released?"":", never released"})`},rI=e=>{let t=[`Release cascade from ${y(e.base.name)}: ${P(e.models.length,"metamodel-model")}, ${P(e.stepCount,"step")}.`,...e.models.flatMap(n=>[fH(n,e),...n.steps.map(r=>` ${r.step}. ${jo(r)}: ${cH(r)}`),...n.current.map(r=>` ${mH(r)}`),...n.steps.length===0&&n.current.length===0?[" - nothing to do"]:[]])];return e.staleSiblingPins.length>0&&t.push("Not refreshed, since no route refreshes a dependsOn pin between sibling extensions (re-add it in the app):",...e.staleSiblingPins.map(n=>` ${y(n.modelName)} on ${y(n.targetName)} at ${J(n.commitId)}: `+(n.reason==="target-moves"?`${y(n.targetName)}'s head moves`:"it trails the head"))),e.unresolvedPins.length>0&&t.push("Left as they are, since they name a release that no longer exists (re-pin them with pin set):",...e.unresolvedPins.map(n=>` ${qp(n.name)} of ${y(n.modelName)} pins ${y(n.targetName)} ${y(n.versionRef)}`)),e.outsideDependents.length>0&&t.push("Not in the cascade, since they are not metamodel-models (their owners re-pin them with pin set):",...e.outsideDependents.map(n=>` ${y(n.name)} depends on ${y(n.targetName)}`)),`${t.join(`
75
275
  `)}
76
- `},Ld=(e,t)=>{let[n=0]=ht(Object.keys(t).map(o=>[o])),r=[`Usage: modeldesk ${e} <subcommand> [options]`,"","Subcommands:"];for(let[o,s]of Object.entries(t))r.push(` ${o.padEnd(n)}${" ".repeat(2)}${s.summary}`),r.push(` ${" ".repeat(n+2)}modeldesk ${s.usage}`);return r.push(""),`${r.join(`
77
- `)}
78
- `};var Dd=await qo(process.argv.slice(2));process.exitCode=Dd;
276
+
277
+ `},sI=(e,t,n)=>{let r=`[${e.step}/${n}]`;if(e.status==="failed")return`${r} FAILED: ${jo(t)}: ${y(e.error?.message??"")}
278
+ `;if(e.status==="skipped")return`${r} skipped: ${jo(t)}, since none of its pins moved
279
+ `;if(e.release)return`${r} done: ${jo(t)}, at ${J(e.release.commitId)}
280
+ `;let s=e.changed&&t.kind!=="re-release"?`${J(t.fromCommitId)} -> ${J(e.commitId)}`:`already at ${J(e.commitId)}`;return`${r} done: ${jo(t)} (${s})
281
+ `},tI=(e,t)=>` ${y(e.name)} (${e.id}) pins ${y(t.name)} ${y(e.version)} `+(e.builtInCommitId?`with its built-in elements at ${J(e.builtInCommitId)}, not ${J(e.expectedBuiltInCommitId)}`:`at ${J(e.commitId)}, not ${J(e.expectedCommitId)}`),Ud=e=>e.map(t=>`${y(t.name)} (${t.id})`).join(", "),oI=e=>[`Instance re-pins (${e.scope==="all"?"every release of the family":"the releases this run moved"}): ${e.repinned} at their release's commit, ${e.behind} still behind after ${e.timeoutSeconds} s, ${e.stuck} behind a release this run did not move, ${e.unverified} not read.`,...e.models.flatMap(t=>[...t.behind.map(n=>tI(n,t)),...t.stuck.map(n=>`${tI(n,t)} (not waited on)`),...t.unverified.length>0?[` ${y(t.name)}: not verified, never read before the timeout: ${Ud(t.unverified)}`]:[],...t.unknownRelease.map(n=>` ${y(n.name)} (${n.id}) pins ${y(t.name)} ${y(n.version??"(no version)")}, which has no release: it cannot be verified`),...t.gone.length>0?[` ${y(t.name)}: deleted while being checked: ${Ud(t.gone)}`]:[],...t.otherRelease>0?[` ${y(t.name)}: ${P(t.otherRelease,"instance model")} pin another release, which this run did not move (--verify-all checks them)`]:[],...t.truncated?[` ${y(t.name)}: more instance models exist than were checked`]:[]])],iI=e=>{let t=e.models.flatMap(r=>r.stuck),n=e.models.flatMap(r=>r.unknownRelease);return[...e.unverified>0?[`${P(e.unverified,"instance model")} could not be read before the timeout, so ${e.unverified===1?"its pins are":"their pins are"} not verified: re-run the cascade to check again.`]:[],...e.behind>0?["Re-run the cascade to check again (it plans to no-ops and re-reads the pins). A model that stays behind across runs was skipped by the platform's background re-pin; the repin-models maintenance task re-pins every dependent idempotently."]:[],...t.length>0?[`Not waited on, since the platform moves them on no release of this run: ${Ud(t)}; the repin-models maintenance task re-pins them.`]:[],...n.length>0?[`Not verifiable, since they pin a version that has no release: ${Ud(n)}; re-pin them in the app's model settings.`]:[]]};var pH=e=>e.map(t=>y(t).replace(/["\\$`,]/g,"")).join(","),Vd=e=>{let t=pH(e);return[{description:"Regenerate the committed bundles of what was released, from the repository root",command:`config/metamodels/regenerate.sh --models "${t}"`},{description:"Review the regenerated bundles in config/metamodels/ and commit them"},{description:"Promote them to each target environment: from backend/, with TARGET_API_URL and TARGET_SERVICE_TOKEN set for that environment (add --dry-run first to see its plan)",command:`java -jar maintenance/target/modeldesk-backend-maintenance-*-exec.jar push-metamodels --models "${t}"`}]},Gd=e=>e.length===0?[]:["Next steps (the CLI runs none of these):",...e.flatMap((t,n)=>[` ${n+1}. ${t.description}${t.command?":":"."}`,...t.command?[` ${t.command}`]:[]])];var Bp="modeldesk release cascade --help",uH="Re-run the cascade to resume: it plans again from live state, so the finished steps read as no-ops and only the rest runs.",aI=(e,t,n)=>{if(!Number.isInteger(e)||e<1)throw I(`${t} must be a positive whole number, got ${e}.`,Bp);if(n!==void 0&&e>n)throw I(`${t} is at most ${n}, got ${e}.`,Bp);return e},hH=e=>{let t=y(e.modelName);if(e.kind==="head")return`${t}'s head moved (${J(e.from)} -> ${J(e.to)})`;let n=`${t} ${y(e.release??"")}`;return e.from===void 0?`${n} was released`:e.to===void 0?`${n} was removed`:`${n} was re-released (${J(e.from)} -> ${J(e.to)})`},gH=e=>{if(e.length>0)throw new u(`The metamodels changed after the plan was made: ${e.map(hH).join("; ")}. Nothing was changed.`,{exitCode:b.Conflict,hint:"Re-run the cascade to plan again from what is there now.",details:{changes:e}})},Hp=e=>e.filter(t=>t.status==="done"&&t.release!==void 0),yH=(e,t,n)=>{let r=new Map(Hp(t).map(s=>[s.modelId,s.release]));return Object.values(e.models).flatMap(s=>{let o=r.get(s.id),i=o?.moved?o.name:void 0;return i===void 0&&!(n&&(s.released||o!==void 0))?[]:[{id:s.id,name:s.name,role:s.role,...s.baseId?{baseId:s.baseId}:{},releasedNow:o!==void 0,...i?{awaited:i}:{}}]})},wH=e=>({message:e.message,code:e.exitCode,...e.type?{type:e.type}:{}}),bH=e=>{let t=e.steps.find(a=>a.status==="failed"),n=e.steps.filter(a=>a.status==="done").length,r=e.steps.filter(a=>a.status==="skipped").length,s=r>0?`, ${r} skipped`:"",o=`${P(n,"step")} run${s}`;return[{planned:"Dry run: nothing was changed.","nothing-to-do":"Every pin and release is current: nothing to run.",completed:`Cascade complete: ${o}.`,failed:`Stopped at step ${t?.step}, after ${o} (they stay done).`}[e.outcome],...e.verification?oI(e.verification):[],...e.verificationError?[`Checking the instance re-pins failed: ${y(e.verificationError.message)}`]:[],...e.hint?[e.hint]:[],` url: ${e.url}`,...Gd(e.nextSteps)].join(`
282
+ `)},dI=q({path:["release","cascade"],effect:"land-direct",summary:"Re-pin and re-release the metamodels depending on a metamodel",description:"Plans from live state over the metamodel-models that depend on <base> (transitively) and the extensions of any of them: which dependency pins to refresh, which extensions to re-pin to their base, which models to re-release in place (those whose pins move or whose release trails their head, unreleased edits included), and which pins are already current. It prints the plan and asks to go on (--yes when it cannot ask), checks that nothing moved since the plan, runs the steps in order and stops at the first failure. Then it waits for the platform to re-pin the instance models of the releases it moved, and names any left behind or not verified; --verify-all checks every release of the family. Re-running it plans again, so finished steps read as no-ops. Needs an interactive super-admin login.",positionals:[{name:"base",type:{address:"model",slot:Ae},required:!0,description:"The id of the metamodel-model that changed, from model list --kind metamodel."}],flags:{timeout:{type:"number",placeholder:"seconds",default:120,description:"How many seconds to wait for the platform to re-pin the instance models."},"instance-limit":{type:"number",placeholder:"n",default:50,description:`How many instance models to check per metamodel, at most ${Fp}.`},"verify-all":{type:"boolean",description:"Check the instance pins of every release in the family, not only the releases this run moved."}},dryRun:!0,examples:["modeldesk release cascade <model> --dry-run","modeldesk release cascade <model> --yes --json"],run:async e=>{let t=aI(e.flags.timeout,"--timeout"),n=aI(e.flags["instance-limit"],"--instance-limit",Fp),r=e.flags["verify-all"];await pt(e,e.args.base.model,{machine:le(e.env)!==void 0});let s=tt(e,e.args.base.model),o=e.api(),[i,a]=await Promise.all([s.model.identity(),s.isMetamodelModel()]);if(!a)throw I(`'release cascade' works on metamodel-models, and ${y(i.name)} is a model. A model's dependents own their pins: list them with 'modeldesk pin list', move one with 'modeldesk pin set'.`,Bp);let d=await JS(o,i.id,await o.releases.metamodelOverview()),l=Mw(d),c=Ow(l);e.print(rI(l));let m={id:i.id,name:i.name},f=te(e.instance(),{kind:"model",modelId:i.id});if(e.globals.dryRun)return{result:{base:m,plan:l,outcome:"planned",steps:[],nextSteps:[],url:f}};c.length>0&&(await ct(e,`Run the ${P(c.length,"step")} of this cascade?`,`The release cascade from ${y(i.name)}`),gH(await XS(o,d)));let h=new Map(c.map($=>[$.step,$])),p=await zS(o,c,$=>{let v=h.get($.step);v&&e.print(sI($,v,c.length))}),g=$=>$.length>0?Vd($.map(v=>v.modelName)):[];if(p.failure)return{result:{base:m,plan:l,outcome:"failed",steps:p.outcomes,nextSteps:g(Hp(p.outcomes)),hint:uH,url:f},exitCode:p.failure.exitCode};let w=c.length===0?"nothing-to-do":"completed",k={base:m,plan:l,outcome:w,steps:p.outcomes,nextSteps:g(Hp(p.outcomes)),url:f},C=yH(d,p.outcomes,r);if(C.length===0)return{result:k};e.print(`Checking the platform's instance re-pins (up to ${t} s)...
283
+ `);try{k.verification=await eI(o,C,{timeoutMs:t*1e3,limit:n,clock:Nd,scope:r?"all":"run"})}catch($){let v=_o($);return k.verificationError=wH(v),k.hint="The steps above stand. Re-run the cascade to check the instance re-pins again.",{result:k,exitCode:v.exitCode}}let R=iI(k.verification);return R.length>0&&(k.hint=R.join(" ")),{result:k,...ZS(k.verification)?{exitCode:b.Transient}:{}}},render:bH});var Kd="modeldesk release create --help",lI=({ref:e})=>e.kind==="commit"?e.id:void 0,Yd=e=>({id:e.id,name:e.name}),kH=async(e,t,n,r,s)=>{if(r!==void 0&&r.toLowerCase()!==t.branch.head.id.toLowerCase())throw new u(`${J(r)} is not the head of ${y(t.name)}: a release is cut at the head.`,{exitCode:b.Validation,hint:`Drop @${r} to release the head.`});if(await Or(e,t.id,n)!==null)throw new u(`Version name '${y(n)}' already exists for this model.`,{exitCode:b.Validation,hint:`Run 'modeldesk release list ${s}' to see the releases it has.`})},EH=async(e,t,n)=>{let{name:r,description:s}=e.flags,o=lI(e.args.model);if(r===void 0||r.trim()==="")throw I("'release create' on a model needs --name <version>: you name a model's releases.",Kd);if(r.includes("@"))throw I(`--name '${y(r)}' must not contain '@': it starts refs such as @HEAD.`,Kd);let i=te(e.instance(),{kind:"model",modelId:n.id});if(e.globals.dryRun)return await kH(t,n,r,o,e.args.model.model),{dryRun:!0,model:Yd(n),kind:"model",outcome:"created",release:{name:r,commitId:o??n.branch.head.id,...s?{description:s}:{}},url:i};try{let a=await t.releases.createVersion(n.id,{name:r,...s===void 0?{}:{description:s},...o===void 0?{}:{commitId:o}});return{model:Yd(n),kind:"model",outcome:"created",release:Ar(a),url:i}}catch(a){throw a instanceof U&&a.status===400?Ui(a,`Run 'modeldesk release list ${e.args.model.model}' to see the releases it has.`):a}},CH=async(e,t,n,r)=>{if(e.flags.name!==void 0)throw I(`${n.name} is a metamodel-model: its release is named after the standard version it declares, so --name does not apply. Change its standardVersion to release another version.`,Kd);if(lI(e.args.model)!==void 0)throw I(`${n.name} is a metamodel-model: its release is always cut at the branch head, so @<commit> does not apply.`,Kd);let[s,o]=await Promise.all([ft(t,n.id),t.models.get(n.id)]),i=Gi(o),a=ji(s,i),d=e.flags.description??a?.description,l=te(e.instance(),{kind:"model",modelId:n.id});if(e.globals.dryRun){let w=a?.name??i;return{dryRun:!0,model:Yd(n),kind:"metamodel",outcome:a?"in-place":"created",release:{...w?{name:w}:{},commitId:n.branch.head.id,...d?{description:d}:{}},standardVersion:i??null,url:l}}let c=d;if(a!==void 0){let w=y(n.name);await ct(e,`Re-release ${w} ${y(a.name)} in place? The platform then re-pins the models written in it.`,`Re-releasing ${w} ${y(a.name)} in place`);let k=(await ft(t,n.id)).find(C=>C.id===a.id);c=e.flags.description??k?.description}let m=await t.releases.createMetamodelRelease(n.id,c),f=Pn(m),h=Ar(m),p=s.find(w=>w.id===h.id),g=p!==void 0&&(p.commitId!==h.commitId||p.builtInCommitId!==f.builtInCommitId);return{model:Yd(n),kind:"metamodel",outcome:p?"in-place":"created",release:h,...p?{previousCommitId:p.commitId}:{},standardVersion:i??null,...g&&r!==void 0?{instanceModelCount:r}:{},nextSteps:[{description:`Re-pin and re-release the metamodels depending on ${n.name}, and check the platform's instance re-pins (the platform re-pins instance models only)`,command:`modeldesk release cascade ${n.id}`},...Vd([n.name])],url:l}},Up=e=>`${e.name?y(e.name):"(named by the server)"} at ${J(e.commitId)}`+(e.description?` ("${y(e.description)}")`:""),vH=e=>{let t=y(e.model.name),n=e.standardVersion===null?[`${t} declares no standard version, so the server names the release itself.`]:[];return"dryRun"in e?[`Dry run: would ${e.outcome==="in-place"?"overwrite its release in place:":"cut a new release:"} ${t} ${Up(e.release)}. Nothing was changed.`,...n].join(`
284
+ `):[...e.outcome==="in-place"?[`Re-released ${t} ${Up(e.release)} in place (was ${J(e.previousCommitId)}): the same release id, name and date, at the new commit.`,e.previousCommitId===e.release.commitId?"The release already pointed at the head, so nothing moved and no model is re-pinned.":`The platform re-pins the ${P(e.instanceModelCount??0,"model")} written in ${t} in the background.`]:[`Released ${t} ${Up(e.release)}.`],...n,` url: ${e.url}`,...Gd(e.nextSteps??[])].join(`
285
+ `)},cI=q({path:["release","create"],effect:"land-direct",summary:"Release a model, or re-release a metamodel in place",description:"On an ordinary model, cuts a version named --name at main's head (or at <model>@<commit>, which must be the head). On a metamodel-model, releases it under the standard version its head declares: --name and @<commit> do not apply, and re-releasing a version overwrites that release in place (same id, name and date, advanced commit), after which the platform re-pins the instance models in the background; it asks first (--yes when it cannot ask). Without --description an in-place re-release keeps the description it had. A metamodel release needs an interactive super-admin login.",positionals:[_(tg)],flags:{name:{type:"string",placeholder:"name",description:"The version's name; required on an ordinary model, refused on a metamodel-model."},description:{type:"string",placeholder:"text",description:"What the release is, in a sentence."}},dryRun:!0,examples:['modeldesk release create <model> --name 1.2.0 --description "Adds severity"',"modeldesk release create <model> --dry-run"],run:async e=>{await pt(e,e.args.model.model,{machine:le(e.env)!==void 0});let t=tt(e,e.args.model.model),n=e.api(),[r,s]=await Promise.all([t.model.identity(),t.isMetamodelModel()]);if(!s)return{result:await EH(e,n,r)};let o=await t.overview();return{result:await CH(e,n,r,o?.instanceModelCount)}},render:vH});var RH=["NAME","DATE","COMMIT","DESCRIPTION"],mI=q({path:["release","list"],effect:"read",summary:"List a model's releases",description:"Lists a model's releases newest first, with name, date, commit and description. A metamodel-model's releases are its standard versions; re-releasing one overwrites it in place, so its date stays and its commit moves. A metamodel-model's releases are listed for a super-admin only.",positionals:[_(Ae)],listing:{},examples:["modeldesk release list <model>","modeldesk release list <model> --json"],run:async e=>{await pt(e,e.args.model.model,{machine:le(e.env)!==void 0});let t=tt(e,e.args.model.model),n=e.api(),[r,s]=await Promise.all([t.model.identity(),t.isMetamodelModel()]),o=s?await e.list(Nc((await n.metamodelModels.versions(r.id)).map(Pn))):await e.list(Dd(async(a,d)=>(await n.models.versions(r.id,{limit:a,cursor:d})).items.map(Ar),a=>a.id));return{result:{model:{id:r.id,name:r.name},kind:s?"metamodel":"model",...o}}},render:e=>{let t=e.kind==="metamodel"?`Releases of ${y(e.model.name)}, a metamodel-model (a re-release overwrites its version in place):`:`Releases of ${y(e.model.name)}:`,n=e.items.map(r=>[y(r.name),r.createdAt,r.commitId,y(r.description??"")]);return[t,...n.length===0?["No releases."]:F([RH,...n])].join(`
286
+ `)}});var fI={search:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"What was read: a branch, your draft or a commit, as the address resolved."},items:{type:"array",items:{type:"object",properties:{id:{type:"string"},path:{type:"string"},type:{type:"string"},label:{type:"string"}}}},truncated:{type:"boolean",description:"True when more rows exist than this page carries. One of false, true."},nextCursor:{type:"string",description:"Where the next page starts, to continue from; present exactly when truncated."},hint:{type:"string",description:"One line on how to continue or narrow the query; present exactly when truncated."}},required:["schemaVersion","model","ref","items","truncated"]}};var IH=["ID","TYPE","PATH"],Vp=e=>e==null?[]:Array.isArray(e)?e.flatMap(Vp):typeof e=="object"?Object.values(e).flatMap(Vp):typeof e=="string"||typeof e=="number"||typeof e=="boolean"?[String(e)]:[],$H=(e,t,n={})=>{let{type:r,internal:s}=n,o=t.toLowerCase(),i=a=>a?.toLowerCase().includes(o)??!1;return zt(it(e,{internal:s})).filter(a=>r===void 0||a.type===r).filter(a=>i(a.label)||Object.values(e.element(a.id)?.attributes??{}).some(d=>Vp(d).some(i))).map(a=>({id:a.id,path:a.path,type:a.type,...a.label===void 0?{}:{label:a.label}}))},pI=D({path:["search"],effect:"read",summary:"Find elements of a model by label or attribute value",description:"Finds the elements whose label or any attribute value contains the text, ignoring case, in tree order. Each row carries the element id and its label path, either of which el show takes. The platform's internal `@` elements are searched only with --internal. Without a ref, reads your draft while it holds staged changes.",positionals:[_(vt),{name:"text",type:"string",required:!0,description:"The text to look for."}],flags:{type:{type:"string",placeholder:"type",description:"Find only elements of this type."},...hr},listing:{narrowHint:"Pass --type or longer text to narrow the search.",toolNarrowHint:"Give a type or longer text to narrow the search."},examples:["modeldesk search <model> severity","modeldesk search <model>@main severity","modeldesk search <model> person --type Objecttype --json"],mcp:{name:"search_elements",description:"Finds the model's elements whose label or any attribute value contains text, ignoring case, in tree order. Each row carries the element's id and label path, either of which stage_changes takes to address it. Narrow with type; internal: true includes the platform's own @ elements. A long result is truncated with nextCursor. Write the ref (model@agent/<topic>) to read where you work.",slot:Oe},resultSchema:fI.search,run:async e=>{let{text:t}=e.args;if(t.trim()==="")throw I("Pass the text to search for.","modeldesk search --help");let{model:n,ref:r,read:s,tree:o}=await gr(e,e.args.model,vt),{internal:i}=e.flags,a=e.flags.type===void 0?void 0:sa(_r(s),e.flags.type,i);return{result:{model:n,ref:r,...await e.list($H(o,t,{type:a,internal:i}))}}},render:e=>{let t=e.items.map(n=>[n.id,n.type,y(n.path)]);return[Ie(e.ref,e.model),...t.length===0?["No matches."]:F([IH,...t])].join(`
287
+ `)}});var xH=/<([a-zA-Z][a-zA-Z0-9-]*)((?:\s+[^\s<>"'=/]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s<>"'=]+))?)*)\s*\/?>/g,TH=/([^\s<>"'=/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s<>"'=]+)))?/g,AH=/^ {0,3}#{1,6}[ \t].*\{#([\w-]+)\}[ \t]*$/gm,OH=/\]\(#([^)\s]+)\)/g,MH=/<!--[\s\S]*?-->/g,NH={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},PH=e=>e.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g,(t,n)=>n.startsWith("#x")?String.fromCodePoint(Number.parseInt(n.slice(2),16)):n.startsWith("#")?String.fromCodePoint(Number.parseInt(n.slice(1),10)):NH[n]),LH=e=>{let t=new Map;for(let n of e.matchAll(TH)){let r=n[1].toLowerCase();t.has(r)||t.set(r,PH(n[2]??n[3]??n[4]??""))}return t},DH=e=>e.replace(MH,t=>t.replace(/[^\n]/g," ")),uI=e=>{let t=[0];for(let n=e.indexOf(`
288
+ `);n!==-1;n=e.indexOf(`
289
+ `,n+1))t.push(n+1);return n=>{let r=0,s=t.length-1;for(;r<s;){let o=r+s+1>>1;t[o]<=n?r=o:s=o-1}return r+1}},_H=e=>{let t=uI(e);return[...e.matchAll(xH)].map(n=>({name:n[1].toLowerCase(),attributes:LH(n[2]),line:t(n.index)}))},kn=e=>`${e.kind} '${e.title}'`,hI=(e,t)=>{let n=t.elements??[],r=new Map(n.map(a=>[a.anchor,a])),s=new Map(n.map(a=>[a.id,a])),o=[],i=new Map;for(let[a,d]of e){let l=DH(d),c=uI(l),m=new Set;i.set(a,m);for(let f of _H(l)){let h=f.attributes.get("id"),p=f.attributes.get("data-md-element"),g=h===void 0?void 0:r.get(h);if(g!==void 0)m.add(g.anchor),p!==g.id&&o.push({kind:"unmarked-container",path:a,line:f.line,message:p===void 0?`<${f.name} id="${h}"> declares the anchor of ${kn(g)} but carries no data-md-element.`:`<${f.name} id="${h}"> declares the anchor of ${kn(g)} but its data-md-element names '${p}'.`});else if(p!==void 0){let C=s.get(p);o.push(C===void 0?{kind:"unindexed-container",path:a,line:f.line,message:`<${f.name}> carries data-md-element="${p}", an element the index does not list.`}:{kind:"unmarked-container",path:a,line:f.line,message:`<${f.name}> carries the markers of ${kn(C)} but not its anchor, id="${C.anchor}".`})}let w=f.name==="a"?f.attributes.get("href"):void 0,k=w?.startsWith("#")?r.get(w.slice(1)):void 0;k!==void 0&&f.attributes.get("data-md-ref")!==k.id&&o.push({kind:"unmarked-link",path:a,line:f.line,message:`The link to ${kn(k)} (${w}) carries no data-md-ref="${k.id}".`})}for(let f of l.matchAll(AH)){let h=r.get(f[1]);h!==void 0&&(m.add(h.anchor),o.push({kind:"unmarked-container",path:a,line:c(f.index),message:`A Markdown heading declares the anchor of ${kn(h)} and cannot carry its markers; write it as <hN id="${h.anchor}" data-md-element="${h.id}">.`}))}for(let f of l.matchAll(OH)){let h=r.get(f[1]);h!==void 0&&o.push({kind:"unmarked-link",path:a,line:c(f.index),message:`A Markdown link to ${kn(h)} (#${f[1]}) cannot carry data-md-ref; write it as <a href="#${f[1]}" data-md-ref="${h.id}">.`})}}for(let a of n){let d=i.get(a.path);(d===void 0||!d.has(a.anchor))&&o.push({kind:"missing-container",path:a.path,message:d===void 0?`The index places ${kn(a)} in ${a.path}, which the document does not have.`:`The index places ${kn(a)} in ${a.path}, which does not declare its anchor '${a.anchor}'.`})}return o};import{existsSync as jH,readdirSync as FH,readFileSync as yI,statSync as qH}from"node:fs";import{join as wI,relative as WH,resolve as BH,sep as bI}from"node:path";var gI="index.json",HH=".md",kI=q({path:["template","lint"],effect:"local",summary:"Check a rendered document against the marker convention its index.json relies on",description:"Reads the document's index.json and every Markdown fragment beside it, and checks that each element's anchor is declared where its markers are, each link to an element is marked, each element of the index is declared in its file, and no file marks an element the index does not list. Each problem is printed with its file and line; any problem exits 4.",positionals:[{name:"dir",type:"string",required:!0,description:"The folder that holds the document's index.json beside its fragments (data/model in a repo)."}],examples:["modeldesk template lint data/model","modeldesk template lint data/model --json"],run:async({args:e,cwd:t})=>{let n=BH(t,e.dir),r=UH(n),s=KH(n,(r.elements??[]).map(d=>d.path)),o=YH(n,s),i=hI(o,r);return{result:{dir:e.dir,files:o.size,elements:r.elements?.length??0,problems:i},...i.length===0?{}:{exitCode:b.Validation}}},render:({files:e,elements:t,problems:n})=>[...n.map(r=>`${JH(r)}: ${r.message}`),n.length===0?`No problems in ${e} file(s) against ${t} element(s) of the index.`:`${n.length} problem(s) in ${e} file(s).`].join(`
290
+ `)}),UH=e=>{let t=wI(e,gI);if(!jH(t))throw new u(`There is no ${gI} in ${e}; name the folder a pull writes it to, such as data/model.`);let n;try{n=JSON.parse(yI(t,"utf8"))}catch(s){throw new u(`${t} is not JSON: ${s instanceof Error?s.message:String(s)}`)}let r=GH(n);if(r!==void 0)throw new u(`${t} is not a document index: ${r}. Pull the bundle again to rewrite it.`);return n},VH=["id","anchor","path","title","kind"],GH=e=>{let t=typeof e=="object"&&e!==null?e.elements:void 0;if(!Array.isArray(t))return"it has no list of elements";for(let[n,r]of t.entries()){let s=typeof r=="object"&&r!==null?r:{},o=VH.find(i=>typeof s[i]!="string");if(o!==void 0)return`element ${n+1} has no ${o}`}},KH=(e,t)=>{if(t.length===0)return"";let n=t.map(o=>o.split("/").slice(0,-1)),r=[];for(let[o,i]of n[0].entries()){if(!n.every(a=>a[o]===i))break;r.push(i)}let s=e.split(bI).filter(o=>o!=="");for(let o=r.length;o>0;o-=1){let i=r.slice(0,o);if(i.every((a,d)=>s[s.length-o+d]===a))return`${i.join("/")}/`}return""},YH=(e,t)=>{let n=new Map,r=s=>{for(let o of FH(s,{withFileTypes:!0})){let i=wI(s,o.name);o.isDirectory()?r(i):o.isFile()&&o.name.endsWith(HH)&&n.set(t+WH(e,i).split(bI).join("/"),yI(i,"utf8"))}};return qH(e).isDirectory()&&r(e),new Map([...n].sort(([s],[o])=>zH(s,o)))},zH=(e,t)=>e===t?0:e<t?-1:1,JH=({path:e,line:t})=>t===void 0?e:`${e}:${t}`;var EI={validate:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"What was validated: a branch head, or your draft, as the address resolved."},valid:{type:"boolean",description:"The server's verdict, false on any `ERROR` or `WARN`. The gate reads the entries instead. One of false, true."},counts:{type:"object",properties:{error:{type:"number"},warn:{type:"number"},info:{type:"number"}},description:"Every entry the server reported, by level, however many `logEntries` carries."},logEntries:{type:"array",items:{type:"object",properties:{logLevel:{type:"string",description:'One of "ERROR", "INFO", "WARN".'},code:{type:"string"},title:{type:"string"},detailMessage:{type:"string"},modelElementId:{type:"string"},elementPath:{type:"string",description:"The element's label path from the model root, which `el show` takes. Absent for an element the tree does not show: the platform's internal `@` elements, and an element no owner reaches."},property:{type:"string"},valueIndex:{type:"number",description:"Which value of {@link property} the finding is about."}}},description:"`ERROR` first, then `WARN`, then `INFO`, each level in the server's order; at most the limit asked for."},truncated:{type:"boolean",description:"One of false, true."},hint:{type:"string",description:"How to see the entries left out; present exactly when truncated."},gate:{type:"object",properties:{failOn:{type:"string",description:'One of "error", "warning".'},passed:{type:"boolean",description:"One of false, true."}},description:"The threshold applied, and whether the model passed it."}},required:["schemaVersion","model","ref","valid","counts","logEntries","truncated","gate"]}};var QH={error:new Set(["ERROR"]),warning:new Set(["ERROR","WARN"])},CI=["ERROR","WARN","INFO"],ZH=["LEVEL","ELEMENT","CODE","MESSAGE"],vI=e=>{let t=CI.indexOf(e);return t===-1?CI.length:t},eU=e=>[...e].sort((t,n)=>vI(t.logLevel)-vI(n.logLevel)),tU=e=>{let t=n=>e.filter(r=>r.logLevel===n).length;return{error:t("ERROR"),warn:t("WARN"),info:t("INFO")}},nU=async(e,t,n,r)=>{if(r.size===0)return new Map;let s=await e.models.get(t,{...Qe(n),expand:["labels"]});return new Map(zt(it(Yt(s))).filter(o=>r.has(o.id)).map(o=>[o.id,o.path]))},rU=(e,t)=>{let n=e.modelElementId===void 0?void 0:t.get(e.modelElementId);return{logLevel:e.logLevel,code:e.code,title:e.title,detailMessage:e.detailMessage,...e.modelElementId===void 0?{}:{modelElementId:e.modelElementId},...n===void 0?{}:{elementPath:n},...e.property===void 0?{}:{property:e.property,...e.valueIndex===void 0?{}:{valueIndex:e.valueIndex}}}},sU=e=>{let{counts:t,gate:n}=e,r=e.logEntries.map(o=>[o.logLevel,y(o.elementPath??o.modelElementId??""),y(o.code),y(o.detailMessage)]),s=`${n.passed?"passes":"fails"} --fail-on ${n.failOn}`;return[Ie(e.ref,e.model),...r.length===0?["No findings."]:F([ZH,...r]),...e.hint?[e.hint]:[],`${P(t.error,"error")}, ${P(t.warn,"warning")}, ${t.info} info: ${s}.`].join(`
291
+ `)},RI=D({path:["validate"],effect:"read",summary:"Validate a model and gate on its findings",description:"Runs the server's validation of a model, metamodel-models included, and lists its findings errors first. Exits 4 when a finding at or above --fail-on exists: any ERROR by default, any ERROR or WARN with --fail-on warning. INFO never fails, and neither does the server marking a model invalid over warnings alone. Without a ref it validates your draft while it holds staged changes, else your working branch head. When a listed finding names an element, one more read of the model gives the element its label path.",positionals:[_(Oe)],flags:{"fail-on":{type:{enum:["error","warning"]},default:"error",placeholder:"level",description:"The least severe level that fails the gate (exit 4): error, or warning for ERROR and WARN.",toolDescription:"The least severe level that fails the gate, which makes the call an error whose result still lists the findings: error, or warning for ERROR and WARN."},limit:{type:"number",default:dl,placeholder:"n",description:"List at most this many findings, errors first; the counts and the gate cover them all."}},examples:["modeldesk validate <model>","modeldesk validate <model>@draft --fail-on warning","modeldesk validate <model>@feat/shapes --json"],mcp:{name:"validate",description:"Runs the server's validation of the model and lists its findings, errors first. Without a ref it validates your draft while it holds staged changes, else your working branch head. A finding at or above failOn (error by default) makes the call an error whose result still lists the findings. Call it after staging, before you hand off or commit."},resultSchema:EI.validate,run:async e=>{let{limit:t}=e.flags,n=e.flags["fail-on"];if(!Number.isInteger(t)||t<1)throw I(`--limit must be a positive whole number, got ${t}.`,"modeldesk validate --help");let r=e.api(),s=await Z(e,e.args.model,Oe),{id:o}=s,i=await r.validation.get(o,Qe(s.ref)),a=eU(i.logEntries),d=a.slice(0,t),l=new Set(d.flatMap(p=>p.modelElementId?[p.modelElementId]:[])),c=await nU(r,o,s.ref,l),m=!a.some(p=>QH[n].has(p.logLevel)),f=d.length<a.length;return{result:{model:{id:o,name:s.name},ref:re(s),valid:i.valid,counts:tU(a),logEntries:d.map(p=>rU(p,c)),truncated:f,...f?{hint:`Showing the first ${d.length} of ${a.length} findings; ${rr(e).allRows(a.length)}`}:{},gate:{failOn:n,passed:m}},...m?{}:{exitCode:b.Validation}}},render:sU});var SI=[$w,Aw,BS,kI,Vh,Gh,Yh,RS,FS,qS,IS,Nk,Pk,gS,kS,ES,yS,CS,VR,xS,uR,LS,xk,Tk,Rk,ik,bk,kk,gk,dk,pk,uk,ek,pI,fb,RI,fg,Rb,bg,Nb,qg,$b,pb,Ob,vg,ug,hg,Eg,Yg,cI,mI,dI,GS,eb,ob,db,mh];var oU=2e3,iU=6e4,aU=3,II=/\r\n|\r|\n/,xI=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="string",dU=(e,t)=>{let n=[],r=e;for(let s=II.exec(r);s!==null&&!(!t&&s[0]==="\r"&&s.index===r.length-1);s=II.exec(r))n.push(r.slice(0,s.index)),r=r.slice(s.index+s[0].length);return{lines:n,rest:r}},lU=e=>{let t=e.indexOf(":");return t===-1?{field:e,value:""}:{field:e.slice(0,t),value:e.slice(t+1).replace(/^ /,"")}},cU=()=>{let e="",t=[];return n=>{if(n===""){let o=t.length>0?{event:e||"message",data:t.join(`
292
+ `)}:void 0;return e="",t=[],o}let{field:r,value:s}=lU(n);r==="event"?e=s:r==="data"&&t.push(s)}};async function*mU(e,t){let n=e.getReader(),r=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",r);let s=new TextDecoder,o=cU(),i="";try{for(let a=t.aborted;!a;){let d=await n.read();a=d.done;let l=d.done?s.decode():s.decode(d.value,{stream:!0}),{lines:c,rest:m}=dU(i+l,a);i=m;for(let f of c){let h=o(f);h!==void 0&&(yield h)}}}finally{t.removeEventListener("abort",r),r()}}var fU=e=>xI(e)&&Qn(e.refId)&&Qn(e.headCommitId)&&typeof e.resets=="number",pU=e=>{let t;try{t=JSON.parse(e.data)}catch{return}if(!xI(t))return;let{refId:n,headCommitId:r}=t;switch(e.event){case"heads":return Array.isArray(t.heads)?{event:"heads",heads:t.heads.filter(fU)}:void 0;case"ref-created":return Qn(n)&&Qn(r)&&(t.kind==="BRANCH"||t.kind==="DRAFT")?{event:"ref-created",refId:n,kind:t.kind,headCommitId:r}:void 0;case"head-advanced":return Qn(n)&&Qn(r)?{event:"head-advanced",refId:n,headCommitId:r,reset:t.reset===!0}:void 0;case"ref-deleted":case"draft-handoff":return Qn(n)?{event:e.event,refId:n}:void 0;case"resync":return{event:"resync"};default:return}},uU=e=>e instanceof u&&e.exitCode===b.Transient,hU=e=>new u(`The model's event stream could not be re-established (${e}).`,{exitCode:b.Transient,hint:"Run the same command again to keep waiting.",hosted:{hint:"Call again to keep waiting."}}),gU=(e,t)=>new Promise(n=>{let r=()=>{clearTimeout(s),t.removeEventListener("abort",r),n()},s=setTimeout(r,e);t.addEventListener("abort",r)}),$I=e=>e instanceof u?e.reason:Fe(e);async function*yU(e,t,n){let r=new AbortController,s="the stream ended before its first event",o=()=>r.abort(),i=()=>{s=`no event within ${n/1e3} seconds`,r.abort()};t.addEventListener("abort",o);let a=setTimeout(i,n);try{let d;try{d=await e(r.signal)}catch(c){if(r.signal.aborted||uU(c))return{delivered:!1,reason:r.signal.aborted?s:$I(c)};throw c}let l=!1;try{for await(let c of mU(d,r.signal)){l=!0,clearTimeout(a);let m=pU(c);m!==void 0&&(yield m),a=setTimeout(i,n)}}catch(c){s=$I(c)}return l?{delivered:l}:{delivered:l,reason:s}}finally{clearTimeout(a),t.removeEventListener("abort",o)}}async function*TI(e,t){let{signal:n}=t,r=t.sleep??gU,s=0;for(;!n.aborted;){let o=yield*yU(e,n,t.idleMs??iU);if(n.aborted)return;if(s=o.delivered?0:s+1,!o.delivered&&s>=aU)throw hU(o.reason);await r(oU,n)}}var wU=500,AI=async(e,t,n)=>{let r=await e(t,n);if(r.items.length>n)throw new u(`The listing returned ${r.items.length} rows for a page of at most ${n}, so it cannot say where to continue.`);if(r.nextCursor!==void 0&&r.nextCursor===t)throw new u(`The listing returned the cursor it was asked for (${t}), so it cannot advance.`);return r},bU=(e,t)=>{if(!Number.isInteger(e)||e<1)throw I(`--limit must be a positive whole number, got ${e}.`,t);return e},kU=e=>`Continue with --cursor ${e}, or pass --all for every row.`,EU=(e,t,n)=>`Showing the first ${e} rows; more exist. ${(n.continueHint??kU)(t)}`+(n.narrowHint?` ${n.narrowHint}`:""),Gp=async(e,t,n)=>{let r=[];if(t.all){let i=t.cursor;do{let a=await AI(e,i,wU);r.push(...a.items),i=a.nextCursor}while(i!==void 0);return{items:r,truncated:!1}}let s=bU(t.limit,n.helpCommand),o=t.cursor;do{let i=await AI(e,o,s-r.length);r.push(...i.items),o=i.nextCursor}while(o!==void 0&&r.length<s);return o===void 0?{items:r,truncated:!1}:{items:r,truncated:!0,nextCursor:o,hint:EU(r.length,o,n)}},OI=(e,t,n)=>Gp(async(r,s)=>{let o=r===void 0?0:Number(r);if(!/^\d+$/.test(r??"0")||o>e.length)throw I(`--cursor ${r} is not a cursor this listing returned.`,n.helpCommand,{reason:`'cursor' ${r} is not a cursor this listing returned.`});let i=o+s;return{items:e.slice(o,i),nextCursor:i<e.length?String(i):void 0}},t,n);var MI={read:(e,t,n)=>e.models.get(t,{...Qe(n),expand:["labels"]}),advance:()=>{},drop:()=>{},schema:(e,t,n,r)=>e.models.schema(t,{ref:n,type:r}),schemaChanged:()=>{}};var PI="modeldesk",NI=e=>{let t;return()=>(t??={value:e()},t.value)},CU=pl(SI),zd=e=>{let t=e.indexOf("--");return t===-1?e:e.slice(0,t)},LI=e=>zd(e).some(t=>t==="--help"||t==="-h"),vU=(e,t)=>!("version"in Ct(e))&&zd(t).some(n=>n==="--version"||n==="-v"),RU=(e,t)=>{let n=zd(e);return n.includes("--no-json")?!1:n.includes("--json")||t!==void 0},SU=(e,t)=>{let n=e,r=[],s=!0;for(let o=0;o<t.length;o++){let i=t[o];if(i==="--"){r.push(...t.slice(o));break}if(s&&n.kind==="group")if(i.startsWith("-")){if(i==="--host"&&o+1<t.length){r.push(i,t[++o]);continue}}else{let a=n.children.get(i);if(a){n=a;continue}s=!1}r.push(i)}return{node:n,rest:r}},IU=(e,t)=>{try{let[n]=fl(e,t).positionals;return n==="help"?void 0:n}catch{return}},$U=(e,t,n)=>{let s=`${[PI,...e.path].join(" ")} --help`,o=e.path.length===0?ah(e):dh(e);if(LI(t)&&IU(t,s)===void 0)return n.out(o),0;let{globals:i,positionals:a}=fl(t,s),[d]=a;if(d==="help")return n.out(o),0;if(d!==void 0){let l=e.path.length===0?`Unknown command '${d}'.`:`Unknown '${e.path.join(" ")}' command '${d}'.`;throw I(l,s)}if(i.version)return n.out(`${ur}
293
+ `),0;if(e.path.length===0)return n.out(o),0;throw I(`'${e.path.join(" ")}' requires a subcommand (${[...e.children.keys()].join(", ")}).`,s)},xU=async(e,t,n,r,s,o,i)=>{let{spec:a}=e,d=e.path.join(" "),l=`${PI} ${d} --help`;if(LI(t))return n.out(lh(a)),0;if(vU(a,t))return n.out(`${ur}
294
+ `),0;let c=th(a,t,l);if(c.globals.json&&c.globals.noJson)throw I("Pass --json or --no-json, not both.",l);if(c.globals.dryRun&&!a.dryRun)throw I(`'${d}' has no --dry-run; nothing was run.`,l);let m=!c.globals.noJson&&(c.globals.json||s!==void 0);m&&!c.globals.json&&i();let f=ru(a.effect,a.escalate,c.flags,c.globals.dryRun),h=f===a.escalate?.to&&f!==a.effect;ou({agent:s},f,h?`${d} --${a.escalate?.flag}`:d);let p=Bh(r),g=C=>n.err(pe(`warning: ${C}
295
+ `)),w={flags:c.flags,args:c.args,commandName:d,effect:f,agent:s,origin:o,api:NI(()=>Ou(eg(w.instance(),{env:r.env,interactive:p,agentHost:s?.host}))),content:MI,events:(C,R)=>TI($=>w.api().models.events(C,$),{signal:R}),list:async C=>{if(!a.listing)throw new Error(`'${d}' lists rows but declares no listing.`);let R={limit:c.flags.limit,cursor:c.flags.cursor,all:c.flags.all===!0},$={helpCommand:l,narrowHint:a.listing.narrowHint};return typeof C=="function"?Gp(C,R,$):OI(C,R,$)},note:g,dryRun:c.globals.dryRun,webUrl:C=>te(w.instance(),C),globals:{json:m,host:c.globals.host,dryRun:c.globals.dryRun,yes:c.globals.yes},env:r.env,cwd:r.cwd,io:n,interactive:p,stdoutIsTTY:r.stdoutIsTTY,color:!m&&Hh(r),print:C=>{m||n.out(pe(C))},warn:g,confirm:async C=>{if(!p)return!1;let R=await r.ask(`${C} [y/N] `);return R!==void 0&&/^y(es)?$/i.test(R.trim())},choose:async(C,R)=>{if(!p)return;let $=Number((await r.ask(`${C} [1-${R}] `))?.trim());return Number.isInteger($)&&$>=1&&$<=R?$-1:void 0},readStdin:r.readStdin,instance:NI(()=>lr(w,{gateMachineHost:!0}))},k=await TU(a,w,m);return YS(n,m,a,k.result,{allRows:c.flags.all===!0,flags:c.flags}),k.refusal!==void 0?jp(n,m,k.refusal):k.exitCode??0},TU=async(e,t,n)=>{try{let r=await e.prepare?.(t);return await e.run(t,r)}catch(r){if(n||!(r instanceof u))throw r;let s=e.renderRefusal?.(r);throw s===void 0?r:(t.print(s),new u(r.reason,{exitCode:r.exitCode,type:r.type,hint:r.hint,requestId:r.requestId}))}},DI=async(e,t=qh,n={})=>{let r=n.runtime??Wh(),s=iu(r.env),o=au(r.env,s),i=!1,a=()=>{i||(i=!0,t.err(`note: running under ${o?.host}, so output is JSON. Pass --no-json for text.
296
+ `))};try{let d=n.commands?pl(n.commands):CU,{node:l,rest:c}=SU(d,e);return l.kind==="group"?$U(l,c,t):await xU(l,c,t,r,o,s,a)}catch(d){let l=RU(e,o);return l&&!zd(e).includes("--json")&&a(),jp(t,l,d)}};var AU=await DI(process.argv.slice(2));process.exitCode=AU;