@smartkomm/plexus-cli 0.1.77 → 0.1.78

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/cli.mjs CHANGED
@@ -10934,13 +10934,17 @@ At most PLEXUS_SEED_SLOTS (default 2) seeds run at once on this machine, across
10934
10934
  `),nA(Yt.join(n,a,"files"),{recursive:!0})}for(let{part:a,file:l}of r.files){let d=Io(l.filename);if(d!==null||!/^[0-9a-f]{64}$/.test(l.sha256)||!RK.test(a))throw new Error(`setup export: "${l.filename}" (${a}) is not a safe path (${d??"bad hash or part"}).`);let c=await YS(l.url,l.sha256,`${a}/${l.filename}`);WS(Yt.join(n,a,"files",l.sha256,l.filename),c)}return{tenant:t??"(platform)",out:n,parts:Object.entries(r.partHashes).map(([a,l])=>`${a}:${l.slice(0,12)}`).join(" "),files:r.files.length}}s(iQ,"exportTenant");var HS=class extends C{static{s(this,"SetupExportCommand")}static paths=[["setup","export"]];static usage=T.Usage({category:"Setup",description:"Export a tenant's setup (Einrichtung) with its files (platform-admin) / Einrichtung exportieren",details:"Records an export on the server and downloads it: setup.json, one folder per part and every referenced file, each checked against its sha256. --out must be a new directory outside any git working tree. --platform exports the platform's own setup instead (the contract input registry every tenant names), with no tenant; restore it before a tenant whose setup names its keys."});out=p.String("--out",{required:!0,description:"New directory to write the export into"});allTenants=p.Boolean("--all-tenants",!1,{description:"Every tenant, one sub-directory each"});platform=p.Boolean("--platform",!1,{description:"The platform export (no tenant)"});async execute(){if(this.platform&&(this.allTenants||this.tenant!==void 0))throw new Error("setup export: --platform takes no tenant (--tenant, --all-tenants).");let t=rQ(this.out);if(t!==null)throw new Error(`setup export: ${t}`);let n=Yt.resolve(this.out),r=`${n}.partial`,i=await this.caller(),o=this.platform?[null]:this.allTenants?(await i.query(x.platformAdmin.listAllTenants,{})).map(l=>l.slug).sort():[this.requireTenant(i)];nA(r,{recursive:!0});let a=[];for(let l of o){let d=await iQ(i,l,this.allTenants&&l!==null?Yt.join(r,l):r);a.push({...d,out:this.allTenants&&l!==null?Yt.join(n,l):n})}return tQ(r,n),this.print(a,l=>l.map(d=>({tenant:d.tenant,parts:d.parts,files:String(d.files),out:d.out})),["tenant","parts","files","out"]),0}},oQ="plexus.setup-export/1",IK="plexus.platform-setup-export/1";function NK(e,t,n){let r=Yt.join(Yt.resolve(e),"setup.json");if(!tA(r))throw new Error(`setup: ${r} does not exist \u2014 point --dir at a directory written by setup export.`);let i=JSON.parse(CK(r,"utf8")),o=n?IK:oQ;if(i.format!==o){let l=i.format===IK?" \u2014 it is the platform export: add --platform":n?" \u2014 drop --platform for a tenant's export":"";throw new Error(`setup: ${r} is not a ${n?"platform ":""}setup export (format ${String(i.format)})${l}.`)}if(!n&&i.platformRefs===void 0)throw new Error(`setup: ${r} lists no platformRefs \u2014 it predates the platform export; export the tenant again.`);let a=t.filter(l=>!i.partOrder.includes(l));if(a.length>0)throw new Error(`setup: --part ${a.join(", ")} is not in this export (${i.partOrder.join(", ")}).`);return{...i,selected:i.partOrder.filter(l=>t.length===0||t.includes(l))}}s(NK,"readExport");function sQ(e,t,n,r){let i=r.find(l=>l.sha256===n);if(i===void 0)throw new Error(`setup: ${t} needs ${n}, which its files[] does not name.`);if(Io(i.filename)!==null||!/^[0-9a-f]{64}$/.test(n))throw new Error(`setup: "${i.filename}" is not a safe path.`);let o=Yt.join(Yt.resolve(e),t,"files",n,i.filename);if(!tA(o))throw new Error(`setup: ${o} is missing \u2014 the export directory is incomplete.`);let a=new Uint8Array(CK(o));if(ia(a)!==n)throw new Error(`setup: ${o} does not match its sha256 ${n}.`);return a}s(sQ,"exportedBytes");function nh(e,t){return[...t.create.map(n=>({part:e,change:"+ create",...n})),...t.update.map(n=>({part:e,change:"~ update",...n})),...t.delete.map(n=>({part:e,change:"- delete",...n})),...t.extra.map(n=>({part:e,change:"? extra (kept)",...n})),{part:e,change:"\xB7 unchanged",table:"",key:String(t.unchanged)}]}s(nh,"planRows");var JS=class extends C{static{s(this,"SetupPlanCommand")}static paths=[["setup","plan"]];static usage=T.Usage({category:"Setup",description:"Preview restoring a setup export directory (platform-admin) / Wiederherstellung pr\xFCfen",details:"Read-only: per part and table what an apply would create, update, delete, or keep as extra."});dir=p.String("--dir",{required:!0,description:"Directory written by setup export"});part=p.Array("--part",[],{description:"Only these parts (repeatable)"});prune=p.Boolean("--prune",!1,{description:"Preview an apply with --prune (a part that refuses it refuses here)"});platform=p.Boolean("--platform",!1,{description:"The directory is the platform export (setup export --platform)"});async execute(){let t=NK(this.dir,this.part,this.platform),n=await this.caller(),r=[];for(let i of t.selected){let o={data:t.parts[i].data,files:t.parts[i].files};if(t.tenant===void 0){r.push(...nh(i,await n.action(x.setupExport.platformPlanPlatformPart,{part:i,section:o,prune:this.prune})));continue}let{plan:a,uploads:l,missingPlatformRefs:d}=await n.action(x.setupExport.platformPlanPart,{tenant:t.tenant,part:i,section:o,platformRefs:t.platformRefs,prune:this.prune});r.push(...nh(i,a),{part:i,change:"\u2191 upload",table:"files",key:String(l.length)});for(let[c,u]of Object.entries(d))for(let f of u)r.push({part:i,change:"\u2716 missing platform key",table:c,key:f})}return this.print(r,i=>i.map(o=>({...o})),["part","change","table","key"]),0}},QS=class extends C{static{s(this,"SetupApplyCommand")}static paths=[["setup","apply"]];static usage=T.Usage({category:"Setup",description:"Restore a setup export directory onto its tenant (platform-admin) / Einrichtung wiederherstellen",details:"Applies part by part in the export's order. Uploads only the files the target lacks, each checked against its hash. Rows the target holds that the export lacks are kept unless --prune."});dir=p.String("--dir",{required:!0,description:"Directory written by setup export"});part=p.Array("--part",[],{description:"Only these parts (repeatable)"});confirm=p.Boolean("--confirm",!1,{description:"Required: actually apply"});prune=p.Boolean("--prune",!1,{description:"Also delete rows the export lacks"});platform=p.Boolean("--platform",!1,{description:"The directory is the platform export (setup export --platform)"});async execute(){if(!this.confirm)throw new Error("setup apply writes \u2014 add --confirm (preview with setup plan).");let t=NK(this.dir,this.part,this.platform),n=await this.caller(),r=[],i=[],o=s(f=>({data:t.parts[f].data,files:t.parts[f].files}),"sectionOf");if(t.tenant===void 0){for(let f of t.selected)r.push(...nh(f,await n.action(x.setupExport.platformApplyPlatformPart,{part:f,section:o(f),staged:[],prune:this.prune})));return this.print(r,f=>f.map(m=>({...m})),["part","change","table","key"]),0}let a=t.tenant,l=t.platformRefs,d=[];for(let f of t.selected)d.push({part:f,...await n.action(x.setupExport.platformPlanPart,{tenant:a,part:f,section:o(f),platformRefs:l,prune:this.prune})});let c=d.flatMap(f=>Object.entries(f.missingPlatformRefs).flatMap(([m,y])=>y.map(k=>`${m}:${k}`)));if(c.length>0)throw new Error(`setup apply: the target lacks platform keys this export names: ${[...new Set(c)].join(", ")} \u2014 apply the platform export first (setup apply --platform).`);let u=s(()=>i.map(f=>({part:"accounts",change:"password",table:f.email,key:f.password})),"mintedRows");try{for(let{part:f,uploads:m}of d){let y=o(f),k=[];for(let v of m){let A=sQ(this.dir,f,v.sha256,t.parts[f].files);k.push({sha256:v.sha256,storageId:await Kl(n,a,A,v.mimeType,v.surface)})}let g=await n.action(x.setupExport.platformApplyPart,{tenant:a,part:f,section:y,staged:k,prune:this.prune,platformRefs:l});r.push(...nh(f,g),{part:f,change:"\u2191 uploaded",table:"files",key:String(k.length)}),i.push(...g.minted)}}catch(f){throw i.length>0&&this.print([...r,...u()],m=>m.map(y=>({...y})),["part","change","table","key"]),f}return this.print([...r,...u()],f=>f.map(m=>({...m})),["part","change","table","key"]),0}},aQ=/^[A-Za-z_$][A-Za-z0-9_$-]*$/,OK=120;function PK(e,t){return typeof t=="number"?`${e}[${t}]`:aQ.test(t)?e===""?t:`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}s(PK,"pathOf");function th(e){if(e===void 0)return"";let t=JSON.stringify(e);return t.length>OK?`${t.slice(0,OK-1)}\u2026`:t}s(th,"shown");var _K=s(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObject");function ZS(e,t,n,r){if(!(t===void 0&&n===void 0)){if(t===void 0){r.push({path:e,change:"+",before:"",after:th(n)});return}if(n===void 0){r.push({path:e,change:"-",before:th(t),after:""});return}if(_K(t)&&_K(n)){let i=[...new Set([...Object.keys(t),...Object.keys(n)])].sort();for(let o of i)ZS(PK(e,o),t[o],n[o],r);return}if(Array.isArray(t)&&Array.isArray(n)){for(let i=0;i<Math.max(t.length,n.length);i+=1)ZS(PK(e,i),t[i],n[i],r);return}JSON.stringify(t)!==JSON.stringify(n)&&r.push({path:e,change:"~",before:th(t),after:th(n)})}}s(ZS,"walk");function lQ(e,t){let n=s(({generatedAt:i,...o})=>o,"strip"),r=[];return ZS("",n(e),n(t),r),r}s(lQ,"diffSetupDocuments");var dQ=s(e=>new Date(e).toISOString().replace(".000Z","Z"),"day"),XS=class extends C{static{s(this,"SetupListCommand")}static paths=[["setup","list"]];static usage=T.Usage({category:"Setup",description:"List a tenant's recorded setup exports (platform-admin) / Einrichtungsexporte auflisten",details:"Newest first: the nightly exports (prod, 7 daily + 4 weekly) and the manual ones, with status, size and part hashes. --platform lists the platform export's instead. Compare two with setup diff <a> <b>."});platform=p.Boolean("--platform",!1,{description:"List the platform export (no tenant) instead of a tenant's"});async execute(){if(this.platform&&this.tenant!==void 0)throw new Error("setup list: --platform takes no --tenant.");let t=await this.caller(),n=await t.query(x.setupExport.platformSetupHistory,this.platform?{platform:!0}:{tenant:this.requireTenant(t)});return this.print(n,r=>r.map(i=>({id:i.exportId,created:dQ(i.createdAt),trigger:i.trigger,status:i.status,bytes:i.sizeBytes===null?"":String(i.sizeBytes),parts:i.status==="failed"?i.error??"":i.partHashes.map(o=>`${o.part}:${o.hash.slice(0,12)}`).join(" ")})),["id","created","trigger","status","bytes","parts"]),0}},eA=class extends C{static{s(this,"SetupDiffCommand")}static paths=[["setup","diff"]];static usage=T.Usage({category:"Setup",description:"Show what changed between two setup exports (platform-admin) / Zwei Einrichtungsexporte vergleichen",details:"Downloads both stored setup.json files (ids from setup list), checks each against its sha256 and lists every changed leaf: + added, - removed, ~ changed. The run time (generatedAt) is ignored. Both must be exports of one tenant. Lists compare by position, so read the snapshot section (rows keyed by identity) for an inserted row.",examples:[["Compare two nightly exports","plexus-cli --env prod setup diff <older-id> <newer-id>"]]});before=p.String({required:!0,name:"a"});after=p.String({required:!0,name:"b"});async execute(){let t=await this.caller(),n=s(async a=>{let{tenantSlug:l,file:d}=await t.query(x.setupExport.platformSetupExportFile,{exportId:a}),c=await YS(d.url,d.sha256,`export ${a}`);return{tenantSlug:l,document:JSON.parse(new TextDecoder().decode(c))}},"load"),[r,i]=[await n(this.before),await n(this.after)];if(r.tenantSlug!==i.tenantSlug){let a=s(l=>l===null?"the platform":`"${l}"`,"owner");throw new Error(`setup diff: ${this.before} is an export of ${a(r.tenantSlug)}, ${this.after} of ${a(i.tenantSlug)} \u2014 compare two exports of one owner.`)}let o=lQ(r.document,i.document);return this.print(o,a=>a.map(l=>({...l})),["change","path","before","after"]),0}},DK=[HS,JS,QS,XS,eA];var FK={docusign:"hmacKey",insign:"password"};function LK(e){let t=e.detail??"?";switch(e.code){case"credentialsKeyMissing":return{de:"SIGNING_CREDENTIALS_KEY ist auf dieser Installation nicht gesetzt",en:"SIGNING_CREDENTIALS_KEY is not set on this installation"};case"credentialsKeyInvalid":return{de:"SIGNING_CREDENTIALS_KEY ist keine 32 Byte in base64",en:"SIGNING_CREDENTIALS_KEY is not 32 bytes in base64"};case"credentialsKeyPreviousInvalid":return{de:"SIGNING_CREDENTIALS_KEY_PREVIOUS ist gesetzt, aber unbrauchbar (kein 32-Byte-Schl\xFCssel, gleich dem aktuellen oder ohne aktuellen)",en:"SIGNING_CREDENTIALS_KEY_PREVIOUS is set but unusable (not a 32-byte key, equal to the current one, or without a current one)"};case"sealedWithUnknownKey":return{de:`das Geheimnis ist mit Schl\xFCssel ${t} versiegelt, den weder SIGNING_CREDENTIALS_KEY noch SIGNING_CREDENTIALS_KEY_PREVIOUS tr\xE4gt \u2014 vorherigen Schl\xFCssel wieder setzen oder Geheimnis neu eingeben`,en:`the secret is sealed with key ${t}, which neither SIGNING_CREDENTIALS_KEY nor SIGNING_CREDENTIALS_KEY_PREVIOUS holds \u2014 set the previous key again or re-enter the secret`};case"docusignPlatformMissing":return{de:`${t} fehlt auf dieser Installation`,en:`${t} is missing on this installation`};case"environmentMismatch":return{de:`das Konto wurde als ${t} gespeichert, die Installation spricht inzwischen ein anderes an \u2014 neu speichern`,en:`the account was saved as ${t}, but the installation now speaks a different one \u2014 save again`};case"productionOutsideProd":return{de:"Ein Produktivkonto wird nur auf der Produktionsumgebung verwendet.",en:"A production account is only used in the production environment."};case"redirectRequired":return{de:"Ein Demo-/Sandbox-Konto braucht eine Umleitungsadresse \u2014 niemand darf aus einer Sandbox echte Familien anschreiben.",en:"A demo/sandbox account needs a redirect address \u2014 nobody may email real families from a sandbox."};case"redirectForbidden":return{de:"Ein Produktivkonto darf keine Umleitungsadresse tragen \u2014 sonst ginge jeder Vertrag an ein einziges Postfach.",en:"A production account must not carry a redirect address \u2014 otherwise every contract would go to a single mailbox."};case"secretMissing":return{de:`das Geheimnis \u201E${t}\u201C ist nicht hinterlegt`,en:`the secret \u201C${t}\u201D is not stored`}}}s(LK,"describeProblem");function vr(e){return e==null?"":new Date(e).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}s(vr,"ts");function cQ(e){return e.map(t=>({id:t.id,contract:t.contractId,rev:String(t.revisionNumber),provider:t.provider,env:t.environment??"",status:t.status,ref:t.providerRef??"",signers:t.signers.map(n=>`${n.name}:${n.status}`).join(", "),sent:vr(t.sentAt),completed:vr(t.completedAt),reconciled:vr(t.lastReconciledAt),error:t.error?.de??""}))}s(cQ,"requestRows");var uQ=["id","contract","rev","provider","env","status","ref","signers","sent","completed","reconciled","error"];function rh(e){if(Bi.includes(e))return e;throw new Error(`--provider must be one of ${Bi.join(" | ")}, got "${e}"`)}s(rh,"parseProvider");var rA=class extends C{static{s(this,"SigningConnectionShowCommand")}static paths=[["signing","connection","show"]];static usage=T.Usage({category:"Signing",description:"The tenant's e-signature connections: which provider its contracts go out through (\u201EE-Signatur: \u2026\u201C), and per provider the state, what keeps it from `ready`, the non-secret settings and which secrets are held (name + fingerprint, never the value). No network call.",examples:[["Show","$0 signing connection show --env local --tenant test"]]});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(x.signingConnections.list,{client:n});return this.json||this.context.stdout.write(`E-Signatur: ${r.activeProvider===null?"keine":Sd[r.activeProvider]}
10935
10935
  `),this.print(r,i=>i.providers.map(o=>{let a=o.connection,l=a===null?"":a.settings.provider==="docusign"?`userId=${a.settings.userId}${a.settings.accountId?` accountId=${a.settings.accountId}`:""}`:`baseUrl=${a.settings.baseUrl} username=${a.settings.username} ownerId=${a.settings.ownerId}`,d=[...o.platformProblems,...a?.problems??[]];return{provider:Sd[o.provider],state:a===null?"nicht eingerichtet":a.state,active:a?.active?"yes":"no",environment:a?.environment??"",settings:l,redirect:a?.settings.signerRedirectTo??"",secrets:a===null||a.secrets.names.length===0?"":`${a.secrets.names.join(", ")} \xB7 ${a.secrets.fingerprint??"?"} \xB7 ${vr(a.secrets.setAt)}${fQ[a.secrets.sealedWith??"current"]}`,lastCheck:a?.lastCheck?`${a.lastCheck.ok?"ok":"FAILED"} ${vr(a.lastCheck.at)}${a.lastCheck.message?` \u2014 ${a.lastCheck.message}`:""}`:"",webhook:o.webhookConfigured?"configured":"none (poll only)",problems:[...new Set(d.map(c=>LK(c).de))].join("; ")}})),0}},iA=class extends C{static{s(this,"SigningConnectionSetCommand")}static paths=[["platform","signing","connection","set"],["signing","connection","set"]];static usage=T.Usage({category:"Signing",description:"Set up or change the tenant's connection at ONE provider (platform right `_platform.config.manage`). Non-secret fields are written as given; the secret (DocuSign: Connect HMAC key, inSign: API password) comes ONLY from stdin or a file and is left unchanged when neither is given. A demo/sandbox account needs --redirect-to, a production account forbids it and is refused outside prod.",examples:[["inSign sandbox",'printf %s "$INSIGN_PASSWORD" | $0 signing connection set --provider insign --base-url https://sandbox.test.getinsign.show --username controller --owner-id plexus-dev --redirect-to admin@plexus.swop.schule --secret-stdin --env local --tenant test'],["DocuSign sender, HMAC key from a file","$0 signing connection set --provider docusign --user-id <GUID> --redirect-to admin@plexus.swop.schule --secret-file ./hmac.txt --env staging --tenant <slug>"],["Remove the HMAC key (poll only)","$0 signing connection set --provider docusign --user-id <GUID> --clear-secret hmacKey --env staging --tenant <slug>"]]});provider=p.String("--provider",{required:!0,description:Bi.join(" | ")});userId=p.String("--user-id",{description:"DocuSign: the school's sender (API user id, GUID)."});baseUrl=p.String("--base-url",{description:"inSign: bare https origin of the account."});username=p.String("--username",{description:"inSign: API user."});ownerId=p.String("--owner-id",{description:"inSign: owner (`foruser`) of every session."});redirectTo=p.String("--redirect-to",{description:"Demo/sandbox only: every recipient address is replaced by this one. Omit on a production account."});secretStdin=p.Boolean("--secret-stdin",!1,{description:"Read the secret from stdin."});secretFile=p.String("--secret-file",{description:"Read the secret from this file."});clearSecret=p.String("--clear-secret",{description:"Remove the stored secret of this name (hmacKey | password)."});async execute(){let t=rh(this.provider),r=this.secretStdin||this.secretFile!==void 0?await us({stdin:this.secretStdin,file:this.secretFile},cs(this.context.stdin)):void 0,i=this.redirectTo!==void 0?{signerRedirectTo:this.redirectTo}:{},o;if(t==="docusign"){if(this.userId===void 0)throw new Error("--user-id is required for docusign");o={provider:t,userId:this.userId,...i}}else{if(this.baseUrl===void 0||this.username===void 0||this.ownerId===void 0)throw new Error("--base-url, --username and --owner-id are required for insign");o={provider:t,baseUrl:this.baseUrl,username:this.username,ownerId:this.ownerId,...i}}let a=await this.caller(),l=this.requireTenant(a),d=await a.action(x.signingConnections.save,{client:l,settings:o,...r!==void 0?{secrets:{[FK[t]]:r}}:{},...this.clearSecret!==void 0?{clearSecrets:[this.clearSecret]}:{}});return this.print(d,c=>[{connectionId:c.connectionId,next:"signing connection test --provider "+t}]),0}},oA=class extends C{static{s(this,"SigningConnectionTestCommand")}static paths=[["signing","connection","test"]];static usage=T.Usage({category:"Signing",description:"\u201EVerbindung testen\u201C: reach the school's account (DocuSign: JWT grant \u2192 token \u2192 userinfo; inSign: version + owner) and record the result on the connection. A DocuSign consent_required answer prints the URL the school's sender must open once. Exit 1 when the test fails.",examples:[["Test inSign","$0 signing connection test --provider insign --env local --tenant test"]]});provider=p.String("--provider",{required:!0,description:Bi.join(" | ")});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.action(x.signingActions.testConnection,{client:n,provider:rh(this.provider)});return this.print(r,i=>[{ok:i.ok?"yes":"NO",provider:i.provider,environment:i.environment,accountId:i.accountId??"",baseUri:i.baseUri??"",sender:i.sender?`${i.sender.email??i.sender.userId}${i.sender.name?` (${i.sender.name})`:""}`:"",error:i.error??"",consentUrl:i.consentUrl??""}]),r.ok?0:1}},fQ={current:"",previous:" \xB7 mit vorherigem Schl\xFCssel versiegelt (signing connection reseal)",unknown:" \xB7 mit unbekanntem Schl\xFCssel versiegelt \u2014 nicht zu \xF6ffnen"},sA=class extends C{static{s(this,"SigningConnectionResealCommand")}static paths=[["platform","signing","connection","reseal"],["signing","connection","reseal"]];static usage=T.Usage({category:"Signing",description:"After a key rotation: seal every school's connection secrets that are still under SIGNING_CREDENTIALS_KEY_PREVIOUS anew under SIGNING_CREDENTIALS_KEY \u2014 same secrets, same binding to tenant, provider and target. Idempotent. Platform-wide, platform right `_platform.config.manage`. Runbook: docs/signing/operations.md \u2192 \u201ERotating the key\u201C.",examples:[["Reseal on staging","$0 signing connection reseal --env staging"]]});async execute(){let n=await(await this.caller()).action(x.signingConnections.reseal,{});return this.print(n,r=>[{resealed:String(r.resealed),changedMeanwhile:String(r.changedMeanwhile),remainingUnderPrevious:String(r.remainingUnderPrevious),underUnknownKey:String(r.underUnknownKey),previousRemovable:r.previousRemovable?"yes \u2014 SIGNING_CREDENTIALS_KEY_PREVIOUS can go":"no"}]),pQ(n)?1:0}};function pQ(e){return e.remainingUnderPrevious>0||e.underUnknownKey>0}s(pQ,"resealLeftWork");var aA=class extends C{static{s(this,"SigningStatusCommand")}static paths=[["platform","signing","status"],["signing","status"]];static usage=T.Usage({category:"Signing",description:"The installation's signing key slots: which key every school's secrets are sealed under (current / previous / unknown), and whether SIGNING_CREDENTIALS_KEY_PREVIOUS can be removed because nothing is sealed under it any more. Platform right `_platform.config.manage`.",examples:[["Key status on prod","$0 signing status --env prod"]]});async execute(){let n=await(await this.caller()).query(x.signingConnections.keyStatus,{});return this.print(n,r=>[{currentKey:r.currentKeyId??"\u2014 (SIGNING_CREDENTIALS_KEY unset)",previousKey:r.previousKeyId??"\u2014",sealedCurrent:String(r.sealed.current),sealedPrevious:String(r.sealed.previous),sealedUnknown:String(r.sealed.unknown),previousSlot:r.previousConfigured?r.previousRemovable?"nothing sealed under it \u2014 can be removed":"still in use \u2014 run `platform signing connection reseal`":"unset"}]),n.sealed.unknown>0?1:0}},lA=class extends C{static{s(this,"SigningConnectionActivateCommand")}static paths=[["platform","signing","connection","activate"],["signing","connection","activate"]];static usage=T.Usage({category:"Signing",description:"\u201EF\xFCr Vertr\xE4ge verwenden\u201C: make this provider the one the tenant's contracts go out through (any other connection is deactivated in the same step), or switch it off with --off. Open Vorg\xE4nge stay on the account they started on. Platform right `_platform.config.manage`.",examples:[["Activate inSign","$0 signing connection activate --provider insign --env local --tenant test"],["No provider any more","$0 signing connection activate --provider insign --off --env local --tenant test"]]});provider=p.String("--provider",{required:!0,description:Bi.join(" | ")});off=p.Boolean("--off",!1,{description:"Deactivate instead."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=rh(this.provider);return await t.mutation(x.signingConnections.setActive,{client:n,provider:r,active:!this.off}),this.print({provider:r,active:!this.off},i=>[{provider:i.provider,active:i.active?"yes":"no"}]),0}},dA=class extends C{static{s(this,"SigningConnectionDeleteCommand")}static paths=[["platform","signing","connection","delete"],["signing","connection","delete"],["signing","connection","remove"]];static usage=T.Usage({category:"Signing",description:"Delete the tenant's connection at ONE provider, secrets included. Refused while an open Vorgang talks through it. Dry-run unless --confirm. Platform right `_platform.config.manage`.",examples:[["Delete","$0 signing connection delete --provider docusign --confirm --env staging --tenant <slug>"]]});provider=p.String("--provider",{required:!0,description:Bi.join(" | ")});confirm=p.Boolean("--confirm",!1,{description:"Actually delete (default: say what would go)."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=rh(this.provider);return this.confirm?(await t.mutation(x.signingConnections.remove,{client:n,provider:r}),this.print({provider:r,deleted:!0},i=>[{provider:i.provider,deleted:"yes"}]),0):(this.context.stdout.write(`Would delete the ${Sd[r]} connection of ${n} (secrets included). Re-run with --confirm.
10936
10936
  `),0)}},cA=class extends C{static{s(this,"SigningListCommand")}static paths=[["signing","list"]];static usage=T.Usage({category:"Signing",description:"List Signaturvorg\xE4nge of a tenant (newest first), optionally for one contract or one status.",examples:[["Everything open","$0 signing list --env local --tenant test --status sent"],["One contract","$0 signing list --env local --tenant test --contract <contractId>"]]});contract=p.String("--contract",{description:"Contract id (contracts table)."});status=p.String("--status",{description:"pending | sent | partially_signed | completed | declined | voided | expired | failed"});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=this.contract?await t.query(x.signing.listForContract,{client:n,contractId:this.contract}):await t.query(x.signing.listForTenant,{client:n,...this.status?{status:this.status}:{}});return this.print(r,cQ,uQ),0}},uA=class extends C{static{s(this,"SigningStartCommand")}static paths=[["signing","start"]];static usage=T.Usage({category:"Signing",description:"Start a Signaturvorgang on a frozen contract revision (contract_snapshots id) through the tenant's ACTIVE connection (`signing connection show`) \u2014 there is no provider to choose. Inserts the request and schedules the provider call; follow with `signing show`.",examples:[["Start","$0 signing start --env local --tenant test --snapshot <contractSnapshotId>"]]});snapshot=p.String("--snapshot",{required:!0,description:"contract_snapshots id of the revision to sign."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(x.signing.start,{client:n,contractSnapshotId:this.snapshot});return this.print(r,i=>[{signingRequestId:i.signingRequestId,next:"signing show <id> (the provider call runs async)"}]),0}},fA=class extends C{static{s(this,"SigningShowCommand")}static paths=[["signing","show"]];static usage=T.Usage({category:"Signing",description:"One Signaturvorgang with its signers, artefact URLs and received provider callbacks.",examples:[["Show","$0 signing show <signingRequestId> --env local --tenant test"]]});id=p.String({required:!0,name:"signingRequestId"});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(x.signing.get,{client:n,signingRequestId:this.id});return r===null?(this.context.stderr.write(`signing: request ${this.id} not found in tenant ${n}
10937
- `),1):(this.print(r,i=>{let o=i.request,a=[{key:"id",value:o.id},{key:"provider",value:o.provider},{key:"status",value:o.status},...o.environment!==null?[{key:"environment",value:o.environment}]:[],{key:"contract",value:o.contractId},{key:"snapshot",value:`${o.contractSnapshotId} (rev ${o.revisionNumber})`},...o.providerRef!==null?[{key:"providerRef",value:o.providerRef}]:[],{key:"created",value:vr(o.createdAt)},{key:"sent",value:vr(o.sentAt)},{key:"completed",value:vr(o.completedAt)},...o.lastReconciledAt!==null?[{key:"reconciled",value:vr(o.lastReconciledAt)}]:[],...o.note!==null?[{key:"note",value:o.note}]:[],...o.error!==null?[{key:"error",value:o.error.de}]:[],...o.voidedReason!==null?[{key:"voidedReason",value:o.voidedReason.de}]:[],...o.declinedReason!==null?[{key:"declinedReason",value:o.declinedReason}]:[],...o.certificateUrl!==null?[{key:"certificate",value:o.certificateUrl}]:[]],l=o.signedDocuments.map((u,f)=>({key:`signedDocument ${f+1}`,value:`${u.filename} sha256=${u.sha256} uploaded=${vr(u.uploadedAt)} signers=${u.signers.map(m=>m.role).join(", ")} url=${u.url??"-"}`})),d=o.signers.map(u=>({key:`signer ${u.recipientId??u.role}`,value:[u.name,...u.email!==void 0?[`<${u.email}>`]:[],...u.originalEmail!==void 0?[`(orig ${u.originalEmail})`]:[],`role=${u.role}`,`status=${u.status}`,...u.signedAt!==void 0?[`signedAt=${u.signedAt}`]:[],...u.declinedReason!==void 0?[`declined="${u.declinedReason}"`]:[]].join(" ")})),c=i.receipts.map(u=>({key:`receipt ${u.event}`,value:`generated=${u.generatedDateTime} retry=${u.retryCount} received=${vr(u.receivedAt)}`}));return[...a,...l,...d,...c]},["key","value"]),0)}},pA=class extends C{static{s(this,"SigningVoidCommand")}static paths=[["signing","void"]];static usage=T.Usage({category:"Signing",description:"Withdraw the process at the provider (schedules the void; the request ends `voided`) \u2014 irreversible, plan unless --confirm.",examples:[["Plan",'$0 signing void <signingRequestId> --reason "Neuer Vertrag folgt" --env local --tenant test'],["Void",'$0 signing void <signingRequestId> --reason "Neuer Vertrag folgt" --confirm --env local --tenant test']]});id=p.String({required:!0,name:"signingRequestId"});reason=p.String("--reason",{required:!0,description:"Recorded on the request (and shown to the recipients where the provider supports it, e.g. DocuSign)."});confirm=p.Boolean("--confirm",!1,{description:"Void (without it, only the plan is printed)."});async execute(){let t=await this.caller(),n=this.requireTenant(t);if(!this.confirm){let r=await t.query(x.signing.get,{client:n,signingRequestId:this.id});if(r===null)throw new Error(`signing: request ${this.id} not found in tenant ${n}.`);let i=r.request;return this.print({signingRequestId:i.id,provider:i.provider,status:i.status,voided:!1},o=>[{ok:"would void",signingRequestId:`${o.signingRequestId} (${o.provider}, ${o.status})`},{ok:"next",signingRequestId:"re-run with --confirm"}]),0}return await t.mutation(x.signing.voidRequest,{client:n,signingRequestId:this.id,reason:this.reason}),this.print({ok:!0,signingRequestId:this.id},r=>[{ok:r.ok?"yes":"no",signingRequestId:r.signingRequestId}]),0}},mA=class extends C{static{s(this,"SigningResendCommand")}static paths=[["signing","resend"]];static usage=T.Usage({category:"Signing",description:"Re-notify one signer (by party id) of an open envelope.",examples:[["Resend","$0 signing resend <signingRequestId> --party <partyId> --env local --tenant test"]]});id=p.String({required:!0,name:"signingRequestId"});party=p.String("--party",{required:!0,description:"parties id of the signer."});async execute(){let t=await this.caller(),n=this.requireTenant(t);return await t.mutation(x.signing.resend,{client:n,signingRequestId:this.id,partyId:this.party}),this.print({ok:!0,signingRequestId:this.id,partyId:this.party},r=>[{ok:r.ok?"yes":"no",signingRequestId:r.signingRequestId,partyId:r.partyId}]),0}},hA=class extends C{static{s(this,"SigningReconcileCommand")}static paths=[["signing","reconcile"]];static usage=T.Usage({category:"Signing",description:"Re-read the process from its provider now and apply it (bypasses the 15-minute poll window on purpose \u2014 the local-dev return path without a webhook).",examples:[["Reconcile","$0 signing reconcile <signingRequestId> --env local --tenant test"]]});id=p.String({required:!0,name:"signingRequestId"});async execute(){let t=await this.caller(),n=this.requireTenant(t);return await t.mutation(x.signing.reconcileNow,{client:n,signingRequestId:this.id}),this.print({ok:!0,signingRequestId:this.id,next:"signing show <id> in a few seconds"},r=>[{ok:r.ok?"yes":"no",signingRequestId:r.signingRequestId,next:r.next}]),0}},MK=[rA,iA,oA,lA,dA,sA,aA,cA,uA,fA,pA,mA,hA];var mQ=/^[a-z0-9][a-z0-9._-]*$/,hQ=/^\d{4}-\d{2}-\d{2}$/,gA=["first_name","last_name"];function BK(e){let t=[];if(!In(e))return["The mapping is not a JSON object."];e.version!==1&&t.push(`version must be 1 (got ${JSON.stringify(e.version)}).`),[";",","," "].includes(e.delimiter)||t.push('delimiter must be ";", "," or "\\t".'),(typeof e.sourceKey!="string"||!mQ.test(e.sourceKey))&&t.push("sourceKey must be a lower-case key (letters, digits, . _ -), e.g. altsystem-schueler.");let n=e.person;if((!In(n)||typeof n.key!="string"||n.key==="")&&t.push("person.key must name the column of the person's stable key."),In(n)&&t.push(...qK("person",n)),!Array.isArray(e.related))t.push("related must be a list (empty when the file has no related persons).");else{let i=new Set;for(let[o,a]of e.related.entries()){let l=`related[${o}]`;if(!In(a)){t.push(`${l} is not an object.`);continue}if(typeof a.block!="string"||a.block.trim()===""?t.push(`${l}.block must name the block.`):i.has(a.block)?t.push(`${l}.block "${a.block}" is used twice.`):i.add(a.block),t.push(...qK(l,a)),(!ih(a.presentWhen)||a.presentWhen.length===0)&&t.push(`${l}.presentWhen must list at least one column.`),a.mergeOn!==void 0&&(!ih(a.mergeOn)||a.mergeOn.length===0))t.push(`${l}.mergeOn must list field keys (or be left out: the person then belongs to the row alone).`);else if(ih(a.mergeOn)&&In(a.fields)){let d=a.mergeOn.filter(c=>!(c in a.fields));d.length>0&&t.push(`${l}.mergeOn names fields the block does not map: ${d.join(", ")}.`)}if(!Array.isArray(a.relationships)||a.relationships.length===0)t.push(`${l}.relationships must list at least one edge \u2014 a related person without an edge links to nobody.`);else for(let[d,c]of a.relationships.entries()){if(!In(c)||typeof c.field!="string"||!In(c.edge)){t.push(`${l}.relationships[${d}] must be { field, edge }.`);continue}for(let[u,f]of Object.entries(c.edge))wQ(f)||t.push(`${l}.relationships[${d}].edge.${u} must be a column or { value }.`)}}}e.values!==void 0&&(!In(e.values)||!Object.values(e.values).every(i=>In(i)&&Object.values(i).every(o=>typeof o=="string"&&o!=="")))&&t.push("values must map column \u2192 raw value \u2192 list element key.");let r=e.enrollment;if(r!==void 0)if(!In(r)||typeof r.unit!="string"||typeof r.code!="string"||typeof r.schoolYear!="string"||r.schoolYear.trim()==="")t.push("enrollment must name the unit and class columns and the school year (the key learning-groups apply used).");else for(let i of["startDate","endDate"])r[i]!==void 0&&typeof r[i]!="string"&&t.push(`enrollment.${i} must name a column.`);return(!Array.isArray(e.ignoredColumns)||!e.ignoredColumns.every(i=>In(i)&&typeof i.column=="string"&&typeof i.reason=="string"&&i.reason.trim()!==""))&&t.push("ignoredColumns must list { column, reason } entries, each with a reason."),t}s(BK,"personMappingProblems");function qK(e,t){let n=[];if(!In(t.fields))return[`${e}.fields must map field keys to columns.`];for(let r of gA)typeof t.fields[r]!="string"&&n.push(`${e}.fields.${r} must name a column \u2014 every person has a first and last name.`);for(let[r,i]of Object.entries(t.fields))typeof i!="string"&&(!In(i)||!Object.values(i).every(o=>typeof o=="string"))&&n.push(`${e}.fields.${r} must be a column, or property \u2192 column for an object field.`);return(!ih(t.roles)||t.roles.length===0)&&n.push(`${e}.roles must list at least one role key.`),n}s(qK,"blockProblems");function gQ(e){let t=[e.person.key,...KK(e.person)];for(let n of e.related){t.push(...KK(n),...n.presentWhen);for(let r of n.relationships)for(let i of Object.values(r.edge))typeof i=="string"&&t.push(i)}if(e.enrollment!==void 0){let{unit:n,code:r,startDate:i,endDate:o}=e.enrollment;t.push(n,r,...[i,o].filter(a=>a!==void 0))}return[...new Set(t)]}s(gQ,"personMappingColumns");function KK(e){return Object.values(e.fields).flatMap(t=>typeof t=="string"?[t]:Object.values(t))}s(KK,"blockColumns");function UK(e,t){let n=[],r=gQ(t),i=t.ignoredColumns.map(y=>y.column),o=new Set(e.columns),a=new Set([...r,...i]),l=e.columns.filter(y=>!a.has(y));l.length>0&&n.push(`Columns neither read by the mapping nor in ignoredColumns: ${l.join(", ")}.`);let d=i.filter(y=>r.includes(y));d.length>0&&n.push(`Columns both read by the mapping and in ignoredColumns: ${d.join(", ")}.`);let c=[...new Set([...r,...i])].filter(y=>!o.has(y));c.length>0&&n.push(`The mapping names columns the file does not have: ${c.join(", ")}.`);let u=Object.keys(t.values??{}).filter(y=>!r.includes(y));if(u.length>0&&n.push(`values maps columns the mapping does not read: ${u.join(", ")}.`),n.length>0)return{rows:[],problems:n};let f=[],m=new Map;for(let y of e.rows){let k=`line ${y.line}`,g=Qi(y,t.person.key);if(g===""){n.push(`${k}: the key column "${t.person.key}" is empty.`);continue}let v=m.get(g);if(v!==void 0){n.push(`${k}: the key "${g}" was already used on line ${v}.`);continue}m.set(g,y.line);let A=jK(t.person,y,t),R=gA.filter(b=>A[b]===void 0);if(R.length>0){n.push(`${k} (${g}): ${R.join(" and ")} is empty.`);continue}let E=[],I=!1;for(let b of t.related){if(b.presentWhen.every(_=>Qi(y,_)===""))continue;let $=jK(b,y,t),q=gA.filter(_=>$[_]===void 0);if(q.length>0){n.push(`${k} (${g}): block ${b.block} names a person but ${q.join(" and ")} is empty.`),I=!0;continue}E.push({block:b.block,mergeOn:b.mergeOn??[],roles:b.roles,values:$,edges:b.relationships.map(_=>({field:_.field,edge:Object.fromEntries(Object.entries(_.edge).map(([H,G])=>[H,typeof G=="string"?yA(t,G,Qi(y,G)):G.value]).filter(([,H])=>H!==""))}))})}if(I)continue;let F=yQ(t,y,k,n);F!==void 0&&f.push({line:y.line,key:g,roles:t.person.roles,values:A,related:E,enrollment:F})}return n.length===0&&f.length===0&&n.push("The file holds no data row."),{rows:f,problems:n}}s(UK,"personRows");function yQ(e,t,n,r){let i=e.enrollment;if(i===void 0)return null;let o=Qi(t,i.unit),a=Qi(t,i.code);if(o===""||a===""){r.push(`${n}: the class columns "${i.unit}"/"${i.code}" are empty.`);return}let l={startDate:null,endDate:null};for(let d of["startDate","endDate"]){let c=i[d];if(c===void 0)continue;let u=Qi(t,c);if(u!==""){if(!hQ.test(u)){r.push(`${n}: ${c} "${u}" is no YYYY-MM-DD date.`);return}l[d]=u}}return{groupKey:Ow(o,i.schoolYear,a),...l}}s(yQ,"enrollmentOf");function jK(e,t,n){let r={};for(let[i,o]of Object.entries(e.fields)){if(typeof o=="string"){let l=yA(n,o,Qi(t,o));l!==""&&(r[i]=l);continue}let a=Object.fromEntries(Object.entries(o).map(([l,d])=>[l,yA(n,d,Qi(t,d))]).filter(([,l])=>l!==""));Object.keys(a).length>0&&(r[i]=a)}return r}s(jK,"blockValues");function yA(e,t,n){let r=e.values!==void 0&&Object.hasOwn(e.values,t)?e.values[t]:void 0;return r!==void 0&&Object.hasOwn(r,n)?r[n]:n}s(yA,"mapped");function Qi(e,t){return(e.cells[t]??"").trim()}s(Qi,"cell");function wQ(e){return typeof e=="string"||In(e)&&["string","boolean","number"].includes(typeof e.value)}s(wQ,"isCellSource");function ih(e){return Array.isArray(e)&&e.every(t=>typeof t=="string"&&t!=="")}s(ih,"isStringList");function In(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(In,"isRecord");var wA=class extends C{static{s(this,"PersonsListCommand")}static paths=[["persons","list"],["stammdaten","persons"]];static usage=T.Usage({category:"Persons",description:"Search persons in the active tenant"});query=p.String("-q,--query","",{description:"Free-text search"});limit=p.String("--limit","25",{description:"Max rows (default 25)"});all=p.Boolean("--all",!1,{description:"Fetch every page (ignores --limit)"});deleted=p.Boolean("--deleted",!1,{description:"List the persons staff deleted (the app's \u201EGel\xF6schte\u201C view) instead"});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=Number.parseInt(this.limit,10);if(!Number.isFinite(r)||r<=0)throw new Error(`persons list: --limit must be a positive integer, got "${this.limit}".`);let i=this.all?void 0:r,o=await this.paginate(t,x.parties.listForMainPage,this.deleted?{client:n,deleted:!0}:{client:n,q:this.query},{max:i});return this.print(o,a=>a.map(l=>({id:l.id,name:l.name,roles:l.roles.map(d=>d.key).join(",")})),["id","name","roles"]),0}},kA=class extends C{static{s(this,"PersonsPurgeCommand")}static paths=[["platform","persons","purge"],["persons","purge"],["stammdaten","persons","purge"]];static usage=T.Usage({category:"Persons",description:"Hard-delete a person staff already deleted, with everything that belongs to it (plan unless --confirm). Needs _platform.config.manage.",details:"Only a person in the app's \u201EGel\xF6schte\u201C view can be purged. The plan lists the rows per table, the person's stored files (taken unless something else still holds them) and every receipt (contract, invoice, signature, \u2026) that refuses the commit. A person a running application still holds, or one linked to a user account, is refused.",examples:[["Plan","plexus-cli --env staging --tenant test platform persons purge <partyId>"],["Apply","plexus-cli --env prod --tenant <slug> platform persons purge <partyId> --confirm --allow-prod"]]});partyId=p.String({required:!0});confirm=p.Boolean("--confirm",!1,{description:"Delete for good (without it, only the plan is printed)."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(x.parties.purgeDeletedParty,{tenantSlug:n,partyId:this.partyId,dryRun:!this.confirm});if(this.json)return this.print(r),0;let i=this.context.stdout;i.write(`${r.applied?"Deleted":"Would delete"} ${r.name??"(unbenannt)"} (${r.partyId}), `),i.write(`soft-deleted ${new Date(r.deletedAt).toISOString()}
10938
- `);for(let a of r.rows)i.write(` ${a.table}: ${a.count}
10939
- `);let o=r.files.filter(a=>a.heldBy===null);i.write(`Files: ${o.length} ${r.applied?"deleted":"to delete"}, ${r.files.length-o.length} kept
10940
- `);for(let a of r.files)a.heldBy!==null&&i.write(` kept ${a.storageId} \u2014 held by ${a.heldBy}
10937
+ `),1):(this.print(r,i=>{let o=i.request,a=[{key:"id",value:o.id},{key:"provider",value:o.provider},{key:"status",value:o.status},...o.environment!==null?[{key:"environment",value:o.environment}]:[],{key:"contract",value:o.contractId},{key:"snapshot",value:`${o.contractSnapshotId} (rev ${o.revisionNumber})`},...o.providerRef!==null?[{key:"providerRef",value:o.providerRef}]:[],{key:"created",value:vr(o.createdAt)},{key:"sent",value:vr(o.sentAt)},{key:"completed",value:vr(o.completedAt)},...o.lastReconciledAt!==null?[{key:"reconciled",value:vr(o.lastReconciledAt)}]:[],...o.note!==null?[{key:"note",value:o.note}]:[],...o.error!==null?[{key:"error",value:o.error.de}]:[],...o.voidedReason!==null?[{key:"voidedReason",value:o.voidedReason.de}]:[],...o.declinedReason!==null?[{key:"declinedReason",value:o.declinedReason}]:[],...o.certificateUrl!==null?[{key:"certificate",value:o.certificateUrl}]:[]],l=o.signedDocuments.map((u,f)=>({key:`signedDocument ${f+1}`,value:`${u.filename} sha256=${u.sha256} uploaded=${vr(u.uploadedAt)} signers=${u.signers.map(m=>m.role).join(", ")} url=${u.url??"-"}`})),d=o.signers.map(u=>({key:`signer ${u.recipientId??u.role}`,value:[u.name,...u.email!==void 0?[`<${u.email}>`]:[],...u.originalEmail!==void 0?[`(orig ${u.originalEmail})`]:[],`role=${u.role}`,`status=${u.status}`,...u.signedAt!==void 0?[`signedAt=${u.signedAt}`]:[],...u.declinedReason!==void 0?[`declined="${u.declinedReason}"`]:[]].join(" ")})),c=i.receipts.map(u=>({key:`receipt ${u.event}`,value:`generated=${u.generatedDateTime} retry=${u.retryCount} received=${vr(u.receivedAt)}`}));return[...a,...l,...d,...c]},["key","value"]),0)}},pA=class extends C{static{s(this,"SigningVoidCommand")}static paths=[["signing","void"]];static usage=T.Usage({category:"Signing",description:"Withdraw the process at the provider (schedules the void; the request ends `voided`) \u2014 irreversible, plan unless --confirm.",examples:[["Plan",'$0 signing void <signingRequestId> --reason "Neuer Vertrag folgt" --env local --tenant test'],["Void",'$0 signing void <signingRequestId> --reason "Neuer Vertrag folgt" --confirm --env local --tenant test']]});id=p.String({required:!0,name:"signingRequestId"});reason=p.String("--reason",{required:!0,description:"Recorded on the request (and shown to the recipients where the provider supports it, e.g. DocuSign)."});confirm=p.Boolean("--confirm",!1,{description:"Void (without it, only the plan is printed)."});async execute(){let t=await this.caller(),n=this.requireTenant(t);if(!this.confirm){let r=await t.query(x.signing.get,{client:n,signingRequestId:this.id});if(r===null)throw new Error(`signing: request ${this.id} not found in tenant ${n}.`);let i=r.request;return this.print({signingRequestId:i.id,provider:i.provider,status:i.status,voided:!1},o=>[{ok:"would void",signingRequestId:`${o.signingRequestId} (${o.provider}, ${o.status})`},{ok:"next",signingRequestId:"re-run with --confirm"}]),0}return await t.mutation(x.signing.voidRequest,{client:n,signingRequestId:this.id,reason:this.reason}),this.print({ok:!0,signingRequestId:this.id},r=>[{ok:r.ok?"yes":"no",signingRequestId:r.signingRequestId}]),0}},mA=class extends C{static{s(this,"SigningResendCommand")}static paths=[["signing","resend"]];static usage=T.Usage({category:"Signing",description:"Re-notify one signer (by party id) of an open envelope.",examples:[["Resend","$0 signing resend <signingRequestId> --party <partyId> --env local --tenant test"]]});id=p.String({required:!0,name:"signingRequestId"});party=p.String("--party",{required:!0,description:"parties id of the signer."});async execute(){let t=await this.caller(),n=this.requireTenant(t);return await t.mutation(x.signing.resend,{client:n,signingRequestId:this.id,partyId:this.party}),this.print({ok:!0,signingRequestId:this.id,partyId:this.party},r=>[{ok:r.ok?"yes":"no",signingRequestId:r.signingRequestId,partyId:r.partyId}]),0}},hA=class extends C{static{s(this,"SigningReconcileCommand")}static paths=[["signing","reconcile"]];static usage=T.Usage({category:"Signing",description:"Re-read the process from its provider now and apply it (bypasses the 15-minute poll window on purpose \u2014 the local-dev return path without a webhook).",examples:[["Reconcile","$0 signing reconcile <signingRequestId> --env local --tenant test"]]});id=p.String({required:!0,name:"signingRequestId"});async execute(){let t=await this.caller(),n=this.requireTenant(t);return await t.mutation(x.signing.reconcileNow,{client:n,signingRequestId:this.id}),this.print({ok:!0,signingRequestId:this.id,next:"signing show <id> in a few seconds"},r=>[{ok:r.ok?"yes":"no",signingRequestId:r.signingRequestId,next:r.next}]),0}},MK=[rA,iA,oA,lA,dA,sA,aA,cA,uA,fA,pA,mA,hA];var mQ=/^[a-z0-9][a-z0-9._-]*$/,hQ=/^\d{4}-\d{2}-\d{2}$/,gA=["first_name","last_name"];function BK(e){let t=[];if(!In(e))return["The mapping is not a JSON object."];e.version!==1&&t.push(`version must be 1 (got ${JSON.stringify(e.version)}).`),[";",","," "].includes(e.delimiter)||t.push('delimiter must be ";", "," or "\\t".'),(typeof e.sourceKey!="string"||!mQ.test(e.sourceKey))&&t.push("sourceKey must be a lower-case key (letters, digits, . _ -), e.g. altsystem-schueler.");let n=e.person;if((!In(n)||typeof n.key!="string"||n.key==="")&&t.push("person.key must name the column of the person's stable key."),In(n)&&t.push(...qK("person",n)),!Array.isArray(e.related))t.push("related must be a list (empty when the file has no related persons).");else{let i=new Set;for(let[o,a]of e.related.entries()){let l=`related[${o}]`;if(!In(a)){t.push(`${l} is not an object.`);continue}if(typeof a.block!="string"||a.block.trim()===""?t.push(`${l}.block must name the block.`):i.has(a.block)?t.push(`${l}.block "${a.block}" is used twice.`):i.add(a.block),t.push(...qK(l,a)),(!ih(a.presentWhen)||a.presentWhen.length===0)&&t.push(`${l}.presentWhen must list at least one column.`),a.mergeOn!==void 0&&(!ih(a.mergeOn)||a.mergeOn.length===0))t.push(`${l}.mergeOn must list field keys (or be left out: the person then belongs to the row alone).`);else if(ih(a.mergeOn)&&In(a.fields)){let d=a.mergeOn.filter(c=>!(c in a.fields));d.length>0&&t.push(`${l}.mergeOn names fields the block does not map: ${d.join(", ")}.`)}if(!Array.isArray(a.relationships)||a.relationships.length===0)t.push(`${l}.relationships must list at least one edge \u2014 a related person without an edge links to nobody.`);else for(let[d,c]of a.relationships.entries()){if(!In(c)||typeof c.field!="string"||!In(c.edge)){t.push(`${l}.relationships[${d}] must be { field, edge }.`);continue}for(let[u,f]of Object.entries(c.edge))wQ(f)||t.push(`${l}.relationships[${d}].edge.${u} must be a column or { value }.`)}}}e.values!==void 0&&(!In(e.values)||!Object.values(e.values).every(i=>In(i)&&Object.values(i).every(o=>typeof o=="string"&&o!=="")))&&t.push("values must map column \u2192 raw value \u2192 list element key.");let r=e.enrollment;if(r!==void 0)if(!In(r)||typeof r.unit!="string"||typeof r.code!="string"||typeof r.schoolYear!="string"||r.schoolYear.trim()==="")t.push("enrollment must name the unit and class columns and the school year (the key learning-groups apply used).");else for(let i of["startDate","endDate"])r[i]!==void 0&&typeof r[i]!="string"&&t.push(`enrollment.${i} must name a column.`);return(!Array.isArray(e.ignoredColumns)||!e.ignoredColumns.every(i=>In(i)&&typeof i.column=="string"&&typeof i.reason=="string"&&i.reason.trim()!==""))&&t.push("ignoredColumns must list { column, reason } entries, each with a reason."),t}s(BK,"personMappingProblems");function qK(e,t){let n=[];if(!In(t.fields))return[`${e}.fields must map field keys to columns.`];for(let r of gA)typeof t.fields[r]!="string"&&n.push(`${e}.fields.${r} must name a column \u2014 every person has a first and last name.`);for(let[r,i]of Object.entries(t.fields))typeof i!="string"&&(!In(i)||!Object.values(i).every(o=>typeof o=="string"))&&n.push(`${e}.fields.${r} must be a column, or property \u2192 column for an object field.`);return(!ih(t.roles)||t.roles.length===0)&&n.push(`${e}.roles must list at least one role key.`),n}s(qK,"blockProblems");function gQ(e){let t=[e.person.key,...KK(e.person)];for(let n of e.related){t.push(...KK(n),...n.presentWhen);for(let r of n.relationships)for(let i of Object.values(r.edge))typeof i=="string"&&t.push(i)}if(e.enrollment!==void 0){let{unit:n,code:r,startDate:i,endDate:o}=e.enrollment;t.push(n,r,...[i,o].filter(a=>a!==void 0))}return[...new Set(t)]}s(gQ,"personMappingColumns");function KK(e){return Object.values(e.fields).flatMap(t=>typeof t=="string"?[t]:Object.values(t))}s(KK,"blockColumns");function UK(e,t){let n=[],r=gQ(t),i=t.ignoredColumns.map(y=>y.column),o=new Set(e.columns),a=new Set([...r,...i]),l=e.columns.filter(y=>!a.has(y));l.length>0&&n.push(`Columns neither read by the mapping nor in ignoredColumns: ${l.join(", ")}.`);let d=i.filter(y=>r.includes(y));d.length>0&&n.push(`Columns both read by the mapping and in ignoredColumns: ${d.join(", ")}.`);let c=[...new Set([...r,...i])].filter(y=>!o.has(y));c.length>0&&n.push(`The mapping names columns the file does not have: ${c.join(", ")}.`);let u=Object.keys(t.values??{}).filter(y=>!r.includes(y));if(u.length>0&&n.push(`values maps columns the mapping does not read: ${u.join(", ")}.`),n.length>0)return{rows:[],problems:n};let f=[],m=new Map;for(let y of e.rows){let k=`line ${y.line}`,g=Qi(y,t.person.key);if(g===""){n.push(`${k}: the key column "${t.person.key}" is empty.`);continue}let v=m.get(g);if(v!==void 0){n.push(`${k}: the key "${g}" was already used on line ${v}.`);continue}m.set(g,y.line);let A=jK(t.person,y,t),R=gA.filter(b=>A[b]===void 0);if(R.length>0){n.push(`${k} (${g}): ${R.join(" and ")} is empty.`);continue}let E=[],I=!1;for(let b of t.related){if(b.presentWhen.every(_=>Qi(y,_)===""))continue;let $=jK(b,y,t),q=gA.filter(_=>$[_]===void 0);if(q.length>0){n.push(`${k} (${g}): block ${b.block} names a person but ${q.join(" and ")} is empty.`),I=!0;continue}E.push({block:b.block,mergeOn:b.mergeOn??[],roles:b.roles,values:$,edges:b.relationships.map(_=>({field:_.field,edge:Object.fromEntries(Object.entries(_.edge).map(([H,G])=>[H,typeof G=="string"?yA(t,G,Qi(y,G)):G.value]).filter(([,H])=>H!==""))}))})}if(I)continue;let F=yQ(t,y,k,n);F!==void 0&&f.push({line:y.line,key:g,roles:t.person.roles,values:A,related:E,enrollment:F})}return n.length===0&&f.length===0&&n.push("The file holds no data row."),{rows:f,problems:n}}s(UK,"personRows");function yQ(e,t,n,r){let i=e.enrollment;if(i===void 0)return null;let o=Qi(t,i.unit),a=Qi(t,i.code);if(o===""||a===""){r.push(`${n}: the class columns "${i.unit}"/"${i.code}" are empty.`);return}let l={startDate:null,endDate:null};for(let d of["startDate","endDate"]){let c=i[d];if(c===void 0)continue;let u=Qi(t,c);if(u!==""){if(!hQ.test(u)){r.push(`${n}: ${c} "${u}" is no YYYY-MM-DD date.`);return}l[d]=u}}return{groupKey:Ow(o,i.schoolYear,a),...l}}s(yQ,"enrollmentOf");function jK(e,t,n){let r={};for(let[i,o]of Object.entries(e.fields)){if(typeof o=="string"){let l=yA(n,o,Qi(t,o));l!==""&&(r[i]=l);continue}let a=Object.fromEntries(Object.entries(o).map(([l,d])=>[l,yA(n,d,Qi(t,d))]).filter(([,l])=>l!==""));Object.keys(a).length>0&&(r[i]=a)}return r}s(jK,"blockValues");function yA(e,t,n){let r=e.values!==void 0&&Object.hasOwn(e.values,t)?e.values[t]:void 0;return r!==void 0&&Object.hasOwn(r,n)?r[n]:n}s(yA,"mapped");function Qi(e,t){return(e.cells[t]??"").trim()}s(Qi,"cell");function wQ(e){return typeof e=="string"||In(e)&&["string","boolean","number"].includes(typeof e.value)}s(wQ,"isCellSource");function ih(e){return Array.isArray(e)&&e.every(t=>typeof t=="string"&&t!=="")}s(ih,"isStringList");function In(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(In,"isRecord");var wA=class extends C{static{s(this,"PersonsListCommand")}static paths=[["persons","list"],["stammdaten","persons"]];static usage=T.Usage({category:"Persons",description:"Search persons in the active tenant"});query=p.String("-q,--query","",{description:"Free-text search"});limit=p.String("--limit","25",{description:"Max rows (default 25)"});all=p.Boolean("--all",!1,{description:"Fetch every page (ignores --limit)"});deleted=p.Boolean("--deleted",!1,{description:"List the persons staff deleted (the app's \u201EGel\xF6schte\u201C view) instead"});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=Number.parseInt(this.limit,10);if(!Number.isFinite(r)||r<=0)throw new Error(`persons list: --limit must be a positive integer, got "${this.limit}".`);let i=this.all?void 0:r,o=await this.paginate(t,x.parties.listForMainPage,this.deleted?{client:n,deleted:!0}:{client:n,q:this.query},{max:i});return this.print(o,a=>a.map(l=>({id:l.id,name:l.name,roles:l.roles.map(d=>d.key).join(",")})),["id","name","roles"]),0}},kA=class extends C{static{s(this,"PersonsPurgeCommand")}static paths=[["platform","persons","purge"],["persons","purge"],["stammdaten","persons","purge"]];static usage=T.Usage({category:"Persons",description:"Hard-delete a person staff already deleted, with everything that belongs to it (plan unless --confirm). Needs _platform.config.manage.",details:"Only a person in the app's \u201EGel\xF6schte\u201C view can be purged. The plan lists the rows per table, the person's stored files (taken unless something else still holds them) and every receipt (contract, invoice, signature, \u2026) that refuses the commit. A person a running application still holds, or one linked to a user account, is refused. A person finished applications name as applicant is deleted in two steps: each --confirm starts the purge of the next such application and deletes nothing else (JSON: purgingApplications non-empty, applied false); once none is listed, --confirm deletes the person.",examples:[["Plan","plexus-cli --env staging --tenant test platform persons purge <partyId>"],["Apply","plexus-cli --env prod --tenant <slug> platform persons purge <partyId> --confirm --allow-prod"]]});partyId=p.String({required:!0});confirm=p.Boolean("--confirm",!1,{description:"Delete for good (without it, only the plan is printed)."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(x.parties.purgeDeletedParty,{tenantSlug:n,partyId:this.partyId,dryRun:!this.confirm});if(this.json)return this.print(r),0;let i=this.context.stdout,o=r.purgingApplications.length>0,a=r.applied?"Deleted":o?"Not deleted yet \u2014":"Would delete";i.write(`${a} ${r.name??"(unbenannt)"} (${r.partyId}), `),i.write(`soft-deleted ${new Date(r.deletedAt).toISOString()}
10938
+ `);for(let d of r.rows)i.write(` ${d.table}: ${d.count}
10939
+ `);let l=r.files.filter(d=>d.heldBy===null);i.write(`Files: ${l.length} ${r.applied?"deleted":o?"to delete in the last step":"to delete"}, ${r.files.length-l.length} kept
10940
+ `);for(let d of r.files)d.heldBy!==null&&i.write(` kept ${d.storageId} \u2014 held by ${d.heldBy}
10941
10941
  `);if(r.blockers.length>0){i.write(`Refused \u2014 still referenced:
10942
- `);for(let a of r.blockers)i.write(` ${a}
10943
- `);return 1}return r.applied||i.write(`Dry run \u2014 re-run with --confirm to delete.
10942
+ `);for(let d of r.blockers)i.write(` ${d}
10943
+ `);return 1}if(o){i.write(`Applications naming the person as applicant, purged first: ${r.purgingApplications.length}
10944
+ `);for(let d of r.purgingApplications)i.write(` ${d}
10945
+ `);return i.write(this.confirm?`Purge started (one application per run). Re-run with --confirm until no application is listed; the run after that deletes the person. "Not found" means an open application's purge took the person along \u2014 nothing is left.
10946
+ `:`Dry run \u2014 each --confirm starts the next application's purge; once none is listed, --confirm deletes the person.
10947
+ `),0}return r.applied||i.write(`Dry run \u2014 re-run with --confirm to delete.
10944
10948
  `),0}},Wc="persons import",kQ=2,bQ=25,bA=class extends C{static{s(this,"PersonsImportCommand")}file=p.String("--file",{required:!0,description:"The person list (CSV, header row, the mapping's delimiter)."});mapping=p.String("--mapping",{required:!0,description:"The mapping file (JSON): key column, fields and roles of the row's person and of each related block, edges, enrollment; every other column ignored with a reason."});confirm=p.Boolean("--confirm",!1,{description:"Write (else the plan only)."});static paths=[["persons","import"]];static usage=T.Usage({category:"Persons",description:"Bring persons in from a file: the row's person, related persons with their edges, the class enrollment \u2014 by stable key, plan unless --confirm.",details:"Every column of the file is read by the mapping or listed in its ignoredColumns \u2014 else the plan names each problem and nothing is sent. A person is found again by the mapping's key column, a related person by the fields the mapping merges on (else per row), so a re-run creates nothing; a changed row is reported, never overwritten. Classes must exist first (learning-groups apply).",examples:[["Plan","$0 --env staging --tenant <slug> persons import --file ./schueler.csv --mapping ./schueler.mapping.json"],["Write","$0 --env staging --tenant <slug> persons import --file ./schueler.csv --mapping ./schueler.mapping.json --confirm"]]});async execute(){let t=lp(Wc,this.mapping,BK),n=sp(Dl(Wc,this.file),t.delimiter,this.file),{rows:r,problems:i}=UK(n,t);if(i.length>0){let A=i.slice(0,30),R=i.length>A.length?`
10945
10949
  \u2026 and ${i.length-A.length} more`:"";throw new Error(`${Wc}: ${i.length} problems, nothing was sent:
10946
10950
  - ${A.join(`
@@ -10984,6 +10988,6 @@ ${n.length} unusable ${o}:
10984
10988
  `),r.length>0&&this.context.stdout.write(` ${r.length} linkable \u2014 plexus-cli platform users relink-auth <email>
10985
10989
  `),i.length>0&&this.context.stdout.write(` ${i.length} without any login account \u2014 plexus-cli platform users provision --tenant <slug> --email <email> --name <name>
10986
10990
  `)}else this.context.stdout.write(`No unusable identities.
10987
- `);return n.length>0?1:0}},uE=class extends or{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=T.Usage({category:"Users",description:"Relink a user's identity row to its live Better Auth account (heals an orphan)."});email=p.String({required:!0});async execute(){let n=await(await this.caller()).mutation(x.platformAdmin.relinkAuthAccount,{email:this.email}),r=n.changed?`Relinked ${this.email} to live auth account ${n.authId}.`:`${this.email} already linked to the live auth account (no change).`;return this.report(n,r),0}};function ij(e,t){if(e===t)throw new Error("Pass exactly one of --on or --off.");return e}s(ij,"requireOnOff");var oj=[YA,HA,JA,QA,ZA,XA,eE,tE,nE,rE,Yc,iE,oE,sE,aE,lE,dE,cE,uE];function sj(e){return e.de??e.en??Object.values(e)[0]??""}s(sj,"titleDe");function GQ(e){return{id:e._id,kind:e.kind,status:e.status,title:sj(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(GQ,"row");var zQ=["id","kind","status","title","assignee","group","outcome"],mE=class extends C{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=T.Usage({category:"Work-Items",description:"List work-items for the active tenant (filter by --mine/--application/--group)."});mine=p.Boolean("--mine",!1,{description:"Only items assigned to me."});application=p.String("--application",{description:"Filter by application id."});group=p.String("--group",{description:"Filter by team (permission-group) id."});assignee=p.String("--assignee",{description:"Filter by assignee users._id."});openOnly=p.Boolean("--open-only",!1,{description:"Only open items."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(x.workItems.list,{client:n,...this.mine?{mine:!0}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{},...this.openOnly?{openOnly:!0}:{}});return this.print(r,i=>i.map(GQ),zQ),0}},hE=class extends C{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=T.Usage({category:"Work-Items",description:"Show one work-item by id."});workItemId=p.String({required:!0,name:"workItemId"});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(x.workItems.get,{client:n,workItemId:this.workItemId});if(r===null)throw new Error(`work-item ${this.workItemId} not found in tenant ${n}.`);return this.print(r,i=>[{field:"id",value:i._id},{field:"kind",value:i.kind},{field:"status",value:i.status},{field:"title",value:sj(i.title)},{field:"assignee",value:i.assigneeUserId??""},{field:"group",value:i.queueGroupId??""},{field:"application",value:i.applicationId??""},{field:"node",value:i.nodeId??""},{field:"outcome",value:i.outcome??""}]),0}},gE=class extends C{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=T.Usage({category:"Work-Items",description:"Create a manual task work-item."});title=p.String("--title",{required:!0,description:"Task title."});description=p.String("--description",{description:"Task description."});application=p.String("--application",{description:"Link to an application id."});group=p.String("--group",{description:"Team (permission-group) id whose queue holds the task."});assignee=p.String("--assignee",{description:"Assignee users._id."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(x.workItems.createManual,{client:n,title:this.title,...this.description?{description:this.description}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{}});return this.print({workItemId:r.workItemId},i=>[{field:"workItemId",value:i.workItemId}]),0}},yE=class extends C{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=T.Usage({category:"Work-Items",description:"Complete a work-item (optionally with an outcome)."});workItemId=p.String({required:!0,name:"workItemId"});outcome=p.String("--outcome",{description:"Outcome id to record."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(x.workItems.complete,{client:n,workItemId:this.workItemId,...this.outcome?{outcome:this.outcome}:{}});return this.print({workItemId:r.workItemId,status:"done"},i=>[{field:"workItemId",value:i.workItemId},{field:"status",value:i.status}]),0}},wE=class extends C{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=T.Usage({category:"Work-Items",description:"Assign a work-item to a user (omit --user to unassign)."});workItemId=p.String({required:!0,name:"workItemId"});user=p.String("--user",{description:"Assignee users._id (omit to clear)."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(x.workItems.assign,{client:n,workItemId:this.workItemId,...this.user?{userId:this.user}:{}});return this.print({workItemId:r.workItemId,assignee:this.user??"(cleared)"},i=>[{field:"workItemId",value:i.workItemId},{field:"assignee",value:i.assignee}]),0}},aj=[mE,hE,gE,yE,wE];var Hc=[...Z$,...V_,...tC,...mN,...pN,...KN,...WN,...zN,...nj,...oj,...tj,...Hq,...R_,...FN,...VK,...J$,...xR,...E_,...JN,...HN,...XN,...eD,...NN,...bN,...aj,...Y0,...CM,...Wq,...NM,...$K,...DK,...Jq,...oK,...lK,...cK,...fK,...MK,...YK,...mR];for(let e of Hc){let t=e.paths?.[0];t===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:kT(e.usage.category,t.join(" "))})}var lj="0.1.77";function dj(){return Hc.flatMap(e=>(e.paths??[]).map(t=>{let n=t.join(" "),r=hT[so(n)];return{path:n,effect:ao(n),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,t)=>e.path.localeCompare(t.path))}s(dj,"plexusCommandCatalog");import Ho from"node:path";function WQ(e){let t=at()?.workspaceRoot??process.cwd(),n=Ho.resolve(t,e),r=Ho.relative(t,n);if(Ho.isAbsolute(e)||r===".."||r.startsWith(`..${Ho.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:n,relative:r}}s(WQ,"workspacePath");function YQ(e){let{absolute:t,relative:n}=WQ(e.path??".");if(e.operation==="list"){if(!Ae(t))return{files:[]};let r=[],i=s(o=>{for(let a of Ar(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=Ho.join(o,a.name);if(a.isDirectory()?i(l):r.push(Ho.relative(t,l)),r.length>200)throw new Error("plexus: the workspace contains too many files. List a subdirectory.")}},"visit");return i(t),{files:r.sort()}}if(!n)throw new Error("plexus: name a workspace file.");if(["read","search","edit"].includes(e.operation)){let r=ye(t);if(r.length>10*1024*1024)throw new Error("plexus: the workspace file exceeds 10 MB.");let i=new TextDecoder("utf-8",{fatal:!0}).decode(r);if(e.operation==="read"){let l=e.offset??0,d=e.maxChars??8e3,c=i.slice(l,l+d);return{path:n,content:c,...l||c.length<i.length?{offset:l,nextOffset:l+c.length<i.length?l+c.length:null,totalCharacters:i.length}:{}}}if(e.operation==="search"){if(!e.query)throw new Error("plexus: search needs a nonempty query.");let l=[],d=e.offset??0;for(;l.length<10;){let c=i.indexOf(e.query,d);if(c<0)break;l.push({offset:c,text:i.slice(Math.max(0,c-160),c+e.query.length+240)}),d=c+e.query.length}return{path:n,matches:l,nextOffset:l.length===10?d:null}}if(!e.oldText||typeof e.content!="string")throw new Error("plexus: edit needs oldText and replacement content.");let o=i.indexOf(e.oldText);if(o<0||o!==i.lastIndexOf(e.oldText))throw new Error("plexus: oldText must match exactly once. Read the current file and choose unique context.");let a=i.slice(0,o)+e.content+i.slice(o+e.oldText.length);if(Buffer.byteLength(a)>10*1024*1024)throw new Error("plexus: the edited file exceeds 10 MB.");return Je(t,a,"utf8"),{path:n,sizeBytes:Buffer.byteLength(a)}}if(e.operation==="write"){if(typeof e.content!="string"||Buffer.byteLength(e.content)>1e6)throw new Error("plexus: file content is missing or too large.");return _t(Ho.dirname(t),{recursive:!0}),Je(t,e.content,"utf8"),{path:n,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return Xo(t),{path:n,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(YQ,"plexusWorkspace");function cj(e){return s(async function(n,r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("plexus: tool input must be an object.");let i=r,o=el[n];if(!o||!Object.hasOwn(el,n))throw new Error("plexus: unknown agent tool.");if(Object.keys(i).some(a=>!Object.hasOwn(o.inputSchema.properties,a)))throw new Error("plexus: unexpected tool argument.");if(n==="plexus"){if(!Array.isArray(i.argv)||i.argv.some(a=>typeof a!="string")||i.stdin!==void 0&&typeof i.stdin!="string")throw new Error("plexus: invalid command input.");return e.inspectCommand(i.argv),e.executeCommand({argv:i.argv,...i.stdin===void 0?{}:{stdin:i.stdin}})}if(n==="plexus_skill"){if(typeof i.path!="string"||i.path.length>240||!Object.hasOwn($g,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:$g[i.path],skillHash:Uu}}if(typeof i.operation!="string"||!["list","read","search","edit","write","remove"].includes(i.operation)||i.path!==void 0&&(typeof i.path!="string"||i.path.length>500)||i.content!==void 0&&(typeof i.content!="string"||i.content.length>1e6)||i.oldText!==void 0&&(typeof i.oldText!="string"||i.oldText.length>1e6)||i.query!==void 0&&(typeof i.query!="string"||!i.query.length||i.query.length>1e3)||i.offset!==void 0&&(typeof i.offset!="number"||!Number.isSafeInteger(i.offset)||i.offset<0)||i.maxChars!==void 0&&(typeof i.maxChars!="number"||!Number.isSafeInteger(i.maxChars)||i.maxChars<1||i.maxChars>24e3))throw new Error("plexus: invalid workspace input.");return YQ(i)},"executePlexusAgentTool")}s(cj,"createPlexusAgentToolExecutor");var fh=cj({inspectCommand:fj,executeCommand:pj});function ph(){let e=new rs({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:lj});e.register(La.HelpCommand),e.register(La.VersionCommand);for(let n of Hc)e.register(n);async function t(n,r){let i;try{i=e.process(n,r)}catch(o){return(r.stderr??process.stderr).write(e.error(o,{colored:!1})),2}return QQ(i,r.stderr??process.stderr),e.run(i,r)}return s(t,"run"),{process(n,r){return e.process(n,r)},run:t,async runExit(n,r){process.exitCode=await t(n,r)}}}s(ph,"createPlexusCli");function QQ(e,t){let n=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&n!==r&&Ba[n]===r&&ot(t,n,r),n in Ba&&ao(n)==="confirm"&&!Ua(e)&&t.write(`plexus-cli: \`${Ba[n]}\` only prints its plan without --confirm \u2014 nothing was changed.
10991
+ `);return n.length>0?1:0}},uE=class extends or{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=T.Usage({category:"Users",description:"Relink a user's identity row to its live Better Auth account (heals an orphan)."});email=p.String({required:!0});async execute(){let n=await(await this.caller()).mutation(x.platformAdmin.relinkAuthAccount,{email:this.email}),r=n.changed?`Relinked ${this.email} to live auth account ${n.authId}.`:`${this.email} already linked to the live auth account (no change).`;return this.report(n,r),0}};function ij(e,t){if(e===t)throw new Error("Pass exactly one of --on or --off.");return e}s(ij,"requireOnOff");var oj=[YA,HA,JA,QA,ZA,XA,eE,tE,nE,rE,Yc,iE,oE,sE,aE,lE,dE,cE,uE];function sj(e){return e.de??e.en??Object.values(e)[0]??""}s(sj,"titleDe");function GQ(e){return{id:e._id,kind:e.kind,status:e.status,title:sj(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(GQ,"row");var zQ=["id","kind","status","title","assignee","group","outcome"],mE=class extends C{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=T.Usage({category:"Work-Items",description:"List work-items for the active tenant (filter by --mine/--application/--group)."});mine=p.Boolean("--mine",!1,{description:"Only items assigned to me."});application=p.String("--application",{description:"Filter by application id."});group=p.String("--group",{description:"Filter by team (permission-group) id."});assignee=p.String("--assignee",{description:"Filter by assignee users._id."});openOnly=p.Boolean("--open-only",!1,{description:"Only open items."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(x.workItems.list,{client:n,...this.mine?{mine:!0}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{},...this.openOnly?{openOnly:!0}:{}});return this.print(r,i=>i.map(GQ),zQ),0}},hE=class extends C{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=T.Usage({category:"Work-Items",description:"Show one work-item by id."});workItemId=p.String({required:!0,name:"workItemId"});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(x.workItems.get,{client:n,workItemId:this.workItemId});if(r===null)throw new Error(`work-item ${this.workItemId} not found in tenant ${n}.`);return this.print(r,i=>[{field:"id",value:i._id},{field:"kind",value:i.kind},{field:"status",value:i.status},{field:"title",value:sj(i.title)},{field:"assignee",value:i.assigneeUserId??""},{field:"group",value:i.queueGroupId??""},{field:"application",value:i.applicationId??""},{field:"node",value:i.nodeId??""},{field:"outcome",value:i.outcome??""}]),0}},gE=class extends C{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=T.Usage({category:"Work-Items",description:"Create a manual task work-item."});title=p.String("--title",{required:!0,description:"Task title."});description=p.String("--description",{description:"Task description."});application=p.String("--application",{description:"Link to an application id."});group=p.String("--group",{description:"Team (permission-group) id whose queue holds the task."});assignee=p.String("--assignee",{description:"Assignee users._id."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(x.workItems.createManual,{client:n,title:this.title,...this.description?{description:this.description}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{}});return this.print({workItemId:r.workItemId},i=>[{field:"workItemId",value:i.workItemId}]),0}},yE=class extends C{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=T.Usage({category:"Work-Items",description:"Complete a work-item (optionally with an outcome)."});workItemId=p.String({required:!0,name:"workItemId"});outcome=p.String("--outcome",{description:"Outcome id to record."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(x.workItems.complete,{client:n,workItemId:this.workItemId,...this.outcome?{outcome:this.outcome}:{}});return this.print({workItemId:r.workItemId,status:"done"},i=>[{field:"workItemId",value:i.workItemId},{field:"status",value:i.status}]),0}},wE=class extends C{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=T.Usage({category:"Work-Items",description:"Assign a work-item to a user (omit --user to unassign)."});workItemId=p.String({required:!0,name:"workItemId"});user=p.String("--user",{description:"Assignee users._id (omit to clear)."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(x.workItems.assign,{client:n,workItemId:this.workItemId,...this.user?{userId:this.user}:{}});return this.print({workItemId:r.workItemId,assignee:this.user??"(cleared)"},i=>[{field:"workItemId",value:i.workItemId},{field:"assignee",value:i.assignee}]),0}},aj=[mE,hE,gE,yE,wE];var Hc=[...Z$,...V_,...tC,...mN,...pN,...KN,...WN,...zN,...nj,...oj,...tj,...Hq,...R_,...FN,...VK,...J$,...xR,...E_,...JN,...HN,...XN,...eD,...NN,...bN,...aj,...Y0,...CM,...Wq,...NM,...$K,...DK,...Jq,...oK,...lK,...cK,...fK,...MK,...YK,...mR];for(let e of Hc){let t=e.paths?.[0];t===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:kT(e.usage.category,t.join(" "))})}var lj="0.1.78";function dj(){return Hc.flatMap(e=>(e.paths??[]).map(t=>{let n=t.join(" "),r=hT[so(n)];return{path:n,effect:ao(n),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,t)=>e.path.localeCompare(t.path))}s(dj,"plexusCommandCatalog");import Ho from"node:path";function WQ(e){let t=at()?.workspaceRoot??process.cwd(),n=Ho.resolve(t,e),r=Ho.relative(t,n);if(Ho.isAbsolute(e)||r===".."||r.startsWith(`..${Ho.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:n,relative:r}}s(WQ,"workspacePath");function YQ(e){let{absolute:t,relative:n}=WQ(e.path??".");if(e.operation==="list"){if(!Ae(t))return{files:[]};let r=[],i=s(o=>{for(let a of Ar(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=Ho.join(o,a.name);if(a.isDirectory()?i(l):r.push(Ho.relative(t,l)),r.length>200)throw new Error("plexus: the workspace contains too many files. List a subdirectory.")}},"visit");return i(t),{files:r.sort()}}if(!n)throw new Error("plexus: name a workspace file.");if(["read","search","edit"].includes(e.operation)){let r=ye(t);if(r.length>10*1024*1024)throw new Error("plexus: the workspace file exceeds 10 MB.");let i=new TextDecoder("utf-8",{fatal:!0}).decode(r);if(e.operation==="read"){let l=e.offset??0,d=e.maxChars??8e3,c=i.slice(l,l+d);return{path:n,content:c,...l||c.length<i.length?{offset:l,nextOffset:l+c.length<i.length?l+c.length:null,totalCharacters:i.length}:{}}}if(e.operation==="search"){if(!e.query)throw new Error("plexus: search needs a nonempty query.");let l=[],d=e.offset??0;for(;l.length<10;){let c=i.indexOf(e.query,d);if(c<0)break;l.push({offset:c,text:i.slice(Math.max(0,c-160),c+e.query.length+240)}),d=c+e.query.length}return{path:n,matches:l,nextOffset:l.length===10?d:null}}if(!e.oldText||typeof e.content!="string")throw new Error("plexus: edit needs oldText and replacement content.");let o=i.indexOf(e.oldText);if(o<0||o!==i.lastIndexOf(e.oldText))throw new Error("plexus: oldText must match exactly once. Read the current file and choose unique context.");let a=i.slice(0,o)+e.content+i.slice(o+e.oldText.length);if(Buffer.byteLength(a)>10*1024*1024)throw new Error("plexus: the edited file exceeds 10 MB.");return Je(t,a,"utf8"),{path:n,sizeBytes:Buffer.byteLength(a)}}if(e.operation==="write"){if(typeof e.content!="string"||Buffer.byteLength(e.content)>1e6)throw new Error("plexus: file content is missing or too large.");return _t(Ho.dirname(t),{recursive:!0}),Je(t,e.content,"utf8"),{path:n,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return Xo(t),{path:n,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(YQ,"plexusWorkspace");function cj(e){return s(async function(n,r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("plexus: tool input must be an object.");let i=r,o=el[n];if(!o||!Object.hasOwn(el,n))throw new Error("plexus: unknown agent tool.");if(Object.keys(i).some(a=>!Object.hasOwn(o.inputSchema.properties,a)))throw new Error("plexus: unexpected tool argument.");if(n==="plexus"){if(!Array.isArray(i.argv)||i.argv.some(a=>typeof a!="string")||i.stdin!==void 0&&typeof i.stdin!="string")throw new Error("plexus: invalid command input.");return e.inspectCommand(i.argv),e.executeCommand({argv:i.argv,...i.stdin===void 0?{}:{stdin:i.stdin}})}if(n==="plexus_skill"){if(typeof i.path!="string"||i.path.length>240||!Object.hasOwn($g,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:$g[i.path],skillHash:Uu}}if(typeof i.operation!="string"||!["list","read","search","edit","write","remove"].includes(i.operation)||i.path!==void 0&&(typeof i.path!="string"||i.path.length>500)||i.content!==void 0&&(typeof i.content!="string"||i.content.length>1e6)||i.oldText!==void 0&&(typeof i.oldText!="string"||i.oldText.length>1e6)||i.query!==void 0&&(typeof i.query!="string"||!i.query.length||i.query.length>1e3)||i.offset!==void 0&&(typeof i.offset!="number"||!Number.isSafeInteger(i.offset)||i.offset<0)||i.maxChars!==void 0&&(typeof i.maxChars!="number"||!Number.isSafeInteger(i.maxChars)||i.maxChars<1||i.maxChars>24e3))throw new Error("plexus: invalid workspace input.");return YQ(i)},"executePlexusAgentTool")}s(cj,"createPlexusAgentToolExecutor");var fh=cj({inspectCommand:fj,executeCommand:pj});function ph(){let e=new rs({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:lj});e.register(La.HelpCommand),e.register(La.VersionCommand);for(let n of Hc)e.register(n);async function t(n,r){let i;try{i=e.process(n,r)}catch(o){return(r.stderr??process.stderr).write(e.error(o,{colored:!1})),2}return QQ(i,r.stderr??process.stderr),e.run(i,r)}return s(t,"run"),{process(n,r){return e.process(n,r)},run:t,async runExit(n,r){process.exitCode=await t(n,r)}}}s(ph,"createPlexusCli");function QQ(e,t){let n=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&n!==r&&Ba[n]===r&&ot(t,n,r),n in Ba&&ao(n)==="confirm"&&!Ua(e)&&t.write(`plexus-cli: \`${Ba[n]}\` only prints its plan without --confirm \u2014 nothing was changed.
10988
10992
  `)}s(QQ,"noteRetiredPath");function fj(e){let t=ph().process(Ra(e),{executePlexusAgentTool:fh}),n=t.path.join(" ");if(n.startsWith("agent "))throw new Error("plexus: nested agent transports are not allowed.");let r=dj().find(l=>l.path===n);if(!r){if(n===""||n==="--help"||n==="--version")return{path:n,writes:!1,host:"shared"};throw new Error(`plexus: command ${n} has no host classification.`)}let i=t,o=r.effect==="callKind"?Op(oa(sa),i.fn??"",i.kind):void 0,a=Ou(n,{confirm:Ua(t),callKind:o});return{...r,writes:a}}s(fj,"inspectPlexusCommand");async function pj(e,t){if(t)return vE(t,()=>pj(e));if(!Array.isArray(e.argv)||e.argv.length===0||e.argv.length>128||e.argv.some(l=>typeof l!="string"||l.length>128e3)||(e.stdin?.length??0)>1e6)throw new Error("plexus: invalid command invocation.");let n="",r="",i=ph();if(at()){let l=fj(e.argv);if(l.host==="terminal")throw new Error(`plexus: this command requires a local machine. ${l.reason??""}`)}return{exitCode:await i.run(Ra(e.argv),{executePlexusAgentTool:fh,stdin:JQ.from(e.stdin===void 0?[]:[e.stdin]),stdout:new uj({write(l,d,c){n+=String(l),c()}}),stderr:new uj({write(l,d,c){r+=String(l),c()}})}),stdout:n,stderr:r}}s(pj,"executePlexusCommand");TE({source:ZQ.join(import.meta.dirname,"skill")});ph().runExit(Ra(process.argv.slice(2)),{executePlexusAgentTool:fh});
10989
10993
  //# sourceMappingURL=cli.mjs.map