@smartkomm/plexus-cli 0.1.377 → 0.1.379

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
@@ -11850,7 +11850,7 @@ The link is valid for 30 days and answers in your name. Please do not forward th
11850
11850
  {key,name,gradeLevel|null}, run {key,name,startDate|null}, applicant
11851
11851
  {language: 'de'|'en'|null (null = no applicant account), channel:
11852
11852
  'self-service'|'staff'}. A missing key fails loud, exactly like a start.
11853
- `,examples:[["Portal application to an offer",`$0 assignment simulate --dir ~/scratch/kindergarten-r17 --env-json '{"applicant":{"language":"de","channel":"self-service"}}'`],["The next pick of a \u201EReihum\u201C row whose last start took 'finanzen'","$0 assignment simulate --dir <bundle> --env-file env.json --rotation-previous team:finanzen=finanzen"],["A leastLoaded rotation with open-task counts","$0 assignment simulate --dir <bundle> --env-file env.json --open finanzen=3 --open finanzen_2=1"]]});dir=p.String("--dir",{required:!0,description:"Offer bundle directory (its workflow.json carries the rule)"});envJson=p.String("--env-json",{description:"The application's environment ($env) as JSON"});envFile=p.String("--env-file",{description:"\u2026or a file holding it"});creator=p.String("--creator",{description:"Label for the staff creator (only a staff start has one)"});rotationPrevious=p.Array("--rotation-previous",{description:"<slot>=<personKey>: the last pick of that slot's \u201EReihum\u201C row (repeatable; none = its first start)"});left=p.Array("--left",{description:"<personKey>: someone who has left \u2014 every rotation skips them (repeatable)"});open=p.Array("--open",{description:"<personKey>=<n>: open tasks, for a leastLoaded rotation (repeatable; absent = 0)"});async execute(){let t=it(this.dir),n=XW(t.workflow?.graph,`bundle ${this.dir}`),i=Ede(this.envJson,this.envFile),r=O4(n,i,{...this.creator!==void 0?{creator:this.creator}:{},rotationPrevious:P4("--rotation-previous",this.rotationPrevious),openCounts:Rde(this.open),left:this.left??[]});return this.print(r,o=>o.slots.map(a=>({slot:a.slot,row:`#${a.row}`,value:a.value,rotation:a.rotation===void 0?"":`${a.rotation.mode} [${a.rotation.pool.join(", ")}] after ${a.rotation.previous??"\u2014"} \u2192 ${a.rotation.picked}`}))),0}},N4=[HT];import{createHash as _de}from"node:crypto";var QT=/^[a-z0-9][a-z0-9-]*$/;function ec(e){return QT.test(e)}s(ec,"isFileKey");function ll(e){return e.trim()===""?"is empty":e==="."||e===".."?"is not a file name":/[/\\]/.test(e)?"must not contain a path separator":[...e].some(t=>t.charCodeAt(0)<=31)?"must not contain control characters":null}s(ll,"fileNameDefect");var F4={".pdf":"application/pdf",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword",".odt":"application/vnd.oasis.opendocument.text",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png"},ob={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".avif":"image/avif",".woff2":"font/woff2"};function tc(e){return _de("sha256").update(e).digest("hex")}s(tc,"sha256Hex");function jf(e,t=F4){let n=ee.resolve(e),i;try{i=Be(n)}catch{throw new w(`File not found: ${e}`)}let r=t[ee.extname(n).toLowerCase()];if(r===void 0)throw new w(`${e}: unsupported file type \u2014 allowed: ${Object.keys(t).join(", ")}.`);return{bytes:i,filename:ee.basename(n),mimeType:r,sha256:tc(i),sizeBytes:i.length}}s(jf,"readLocalFile");var Ode={tenantFile:A.tenantFiles.platformGenerateUploadUrl,brandingAsset:A.branding.platformGenerateBrandingAssetUploadUrl,brandingLogo:A.branding.platformGenerateBrandingLogoUploadUrl,contractTwin:A.contractTwins.generateUploadUrl};async function ns(e,t,n,i,r){let{uploadUrl:o,uploadTicket:a}=await e.mutation(Ode[r],{client:t}),l=await e.upload(o,n,i);return await e.mutation(A.uploads.registerUpload,{uploadTicket:a,storageId:l}),l}s(ns,"uploadStaged");async function L4(e,t,n,i){return await ns(e,t,n,i,"tenantFile")}s(L4,"uploadTenantFile");function XT(e){let t=[...e].filter(([,n])=>"fileName"in n||"size"in n).map(([n])=>n);if(t.length!==0)throw new Error(`[cli/serverPredatesFileRef] ${t.join(", ")}: the target deployment still answers fileName / size \u2014 it runs a release from before file references. Use a plexus-cli built from that release, or wait for the next release.`)}s(XT,"requireFileRefNames");async function qf(e,t){let n=await e.query(A.tenantFiles.platformList,{client:t});return XT(n.map(i=>[`files["${i.key}"]`,i])),n}s(qf,"listLibrary");function M4(e,t,n,i,r){let o=jf(ee.resolve(e,t),r);if(o.mimeType!==n)throw new w(`${i}: ${t} is ${o.mimeType}, the entry declares ${n}.`);return o}s(M4,"readSnapshotEntry");function j4(e,t){let n=new Map,i=(e.files??[]).map(l=>{if(l.path===void 0)return l;let{path:d,...c}=l,u=M4(t,d,c.mimeType,`files["${c.key}"]`,F4);return n.set(c.key,u),{...c,sha256:u.sha256,sizeBytes:u.sizeBytes}}),r=C4(e.tenant.brandingAssets,t,"tenant"),o=new Map,a=(e.foundation?.legalEntities??[]).map(l=>{if(l.brandingAssets===void 0)return l;let d=C4(l.brandingAssets,t,`foundation.legalEntities.${l.key}`);return o.set(l.key,d.bytes),{...l,brandingAssets:d.assets}});return{config:{...e,tenant:{...e.tenant,...r.assets!==void 0?{brandingAssets:r.assets}:{}},...e.foundation!==void 0?{foundation:{...e.foundation,legalEntities:a}}:{},files:i},bytes:n,brandingBytes:r.bytes,legalEntityBrandingBytes:o}}s(j4,"resolveSnapshotFiles");function C4(e,t,n){let i=new Map,r=e;if(r===void 0)return{assets:void 0,bytes:i};let o={};for(let[a,l]of Object.entries(r)){if(l.path===void 0){o[a]=l;continue}let{path:d,...c}=l,u=M4(t,d,c.mimeType,`${n}.brandingAssets.${a}`,ob);i.set(a,u),o[a]={...c,sha256:u.sha256,sizeBytes:u.sizeBytes}}return{assets:o,bytes:i}}s(C4,"resolveSnapshotBranding");async function q4(e,t,n,i,r){let o={},a={contents:o,changed:[],unavailable:[]};for(let l of e){if(t.get(l.key)===l.sha256)continue;a.changed.push(l.key);let d=await n(l.key);if(d===void 0){a.unavailable.push(l.key);continue}if(tc(d)!==l.sha256)throw new w(`${l.at}: the supplied bytes do not match sha256 ${l.sha256}.`);r||(o[l.key]=await i(d,l.mimeType))}return a}s(q4,"stageChanged");async function z4(e,t,n,i,r){let o=new Map(Object.entries(await e.query(A.tenantFiles.platformFileHashes,{client:t})??{})),a=new Map(n.map(l=>[l.key,l]));return await q4(n.map(l=>({key:l.key,sha256:l.sha256,mimeType:l.mimeType,at:`files["${l.key}"]`})),o,l=>i(a.get(l)),(l,d)=>ns(e,t,l,d,"tenantFile"),r)}s(z4,"stageFileContents");function U4(e){return e===void 0?"tenant":`foundation.legalEntities.${e}`}s(U4,"brandingHolder");async function sb(e,t,n){let i=await e.query(A.branding.platformBrandingAssets,{client:t,...n!==void 0?{legalEntity:n}:{}});return XT(Object.entries(i??{}).map(([r,o])=>[`${U4(n)}.brandingAssets.${r}`,o])),i}s(sb,"listBrandingAssets");async function eR(e,t,n,i,r,o){let a=new Map(Object.entries(await sb(e,t,o)??{}).map(([d,c])=>[d,c.sha256])),l=U4(o);return await q4(Object.entries(n??{}).map(([d,c])=>({key:d,sha256:c.sha256,mimeType:c.mimeType,at:`${l}.brandingAssets.${d}`})),a,i,(d,c)=>ns(e,t,d,c,"brandingAsset"),r)}s(eR,"stageBrandingAssets");async function K4(e,t,n,i){if(e===null||t===void 0)throw new Error(`${n}: its stored object is gone \u2014 ${i}`);let r=await fetch(e);if(!r.ok)throw new Error(`download of ${n} failed (${r.status}).`);let o=new Uint8Array(await r.arrayBuffer());if(tc(o)!==t)throw new Error(`download of ${n} does not match its sha256 ${t}.`);return o}s(K4,"downloadVerified");async function tR(e){return await K4(e.url,e.sha256,`"${e.key}"`,"replace it with `files put` first.")}s(tR,"downloadLibraryFile");async function nR(e,t,n){return await K4(t.url,t.sha256,n===void 0?`branding/${e}`:`branding/${n}/${e}`,"upload it again with `branding set-logo` / `branding set-font` first.")}s(nR,"downloadBrandingAsset");function Pde(e,t,n){let i=Object.keys(ob).find(r=>ob[r]===t);if(i===void 0)throw new Error(`export: branding/${e} is ${t}, which a snapshot cannot name (${Object.keys(ob).join(", ")}).`);if(n===void 0)return ee.join("branding",`${e}${i}`);if(!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(n))throw new Error(`export: legal entity key "${n}" is not a safe directory name for its brand files.`);return ee.join("branding",n,`${e}${i}`)}s(Pde,"brandingAssetPath");function V4(e,t,n){let i=ee.join(e,t);bn(ee.dirname(i),{recursive:!0}),ft(i,n)}s(V4,"writeBeside");async function B4(e,t,n,i){XT([...n.files.map(c=>[`files["${c.key}"]`,c]),...Object.entries(n.tenant.brandingAssets??{}).map(([c,u])=>[`tenant.brandingAssets.${c}`,u]),...(n.foundation?.legalEntities??[]).flatMap(c=>Object.entries(c.brandingAssets??{}).map(([u,f])=>[`foundation.legalEntities.${c.key}.brandingAssets.${u}`,f]))]);let r=new Map((await qf(e,t)).map(c=>[c.key,c])),o=ee.dirname(i),a=[];for(let c of n.files){let u=r.get(c.key);if(u===void 0)throw new Error(`export: "${c.key}" vanished from the library between two reads \u2014 rerun.`);let f=ll(c.filename);if(f!==null||!ec(c.key))throw new Error(`export: "${c.key}" / "${c.filename}" is not a safe path (${f??"bad key"}).`);let h=ee.join("files",c.key,c.filename);V4(o,h,await tR(u)),a.push({...c,path:h})}let l=await D4(e,t,n.tenant.brandingAssets,o,void 0),d=[];for(let c of n.foundation?.legalEntities??[]){if(c.brandingAssets===void 0){d.push(c);continue}d.push({...c,brandingAssets:await D4(e,t,c.brandingAssets,o,c.key)})}return{...n,tenant:{...n.tenant,...l!==void 0?{brandingAssets:l}:{}},...n.foundation!==void 0?{foundation:{...n.foundation,legalEntities:d}}:{},files:a}}s(B4,"writeSnapshotFiles");async function D4(e,t,n,i,r){if(n===void 0)return;let o=await sb(e,t,r)??{},a={};for(let[l,d]of Object.entries(n)){let c=o[l],u=Pde(l,d.mimeType,r);if(c===void 0||c.sha256!==d.sha256)throw new Error(`export: ${u} changed between two reads \u2014 rerun.`);V4(i,u,await nR(l,c,r)),a[l]={...d,path:u}}return a}s(D4,"writeSnapshotBranding");var Nde={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml",".avif":"image/avif"};function G4(e){return Nde[ee.extname(e).toLowerCase()]}s(G4,"guessImageContentType");async function Cde(e,t){if(e===void 0==(t===void 0))throw new w("Pass exactly one of --file <path> or --url <url>.");if(t!==void 0&&Dt())throw new w("Hosted agents cannot fetch arbitrary logo URLs. Upload the image to the chat and use --file <path>.");if(e!==void 0){let a=ee.resolve(e),l;try{l=Be(a)}catch{throw new w(`File not found: ${e}`)}let d=G4(a);if(d===void 0)throw new w(`Cannot infer an image content-type from "${ee.basename(a)}" \u2014 use a .png/.jpg/.webp/.gif file.`);return{bytes:new Uint8Array(l),contentType:d}}let n=await fetch(t);if(!n.ok)throw new Error(`Fetch failed for ${t} (${n.status} ${n.statusText}).`);let i=new Uint8Array(await n.arrayBuffer()),r=n.headers.get("content-type")?.split(";")[0]?.trim(),o=r&&r.startsWith("image/")?r:G4(new URL(t).pathname);if(o===void 0)throw new Error(`Response for ${t} is not an image (content-type "${r??"unknown"}").`);return{bytes:i,contentType:o}}s(Cde,"loadLogoBytes");function nc(){return p.String("--legal-entity",{description:"A legal entity's config key \u2014 its own brand, which overrides the tenant's for its units"})}s(nc,"legalEntityOption");function rc(e){return e===void 0?{}:{legalEntity:e}}s(rc,"ownerArgs");async function Dde(e,t,n,i){return await ns(e,t,n,i,"brandingLogo")}s(Dde,"uploadLogo");var rR=class extends F{static{s(this,"BrandingSetLogoCommand")}static paths=[["branding","set-logo"]];static usage=E.Usage({category:"Branding",description:"Upload a tenant's portal logo",details:"Sets the external-portal logo for --tenant from a local --file or a remote --url. A one-off upload without the tenant's Branding admin UI. To move the logo with the rest of the config (export \u2192 apply, env \u2192 env), use `config apply` \u2014 it carries the file by hash (`tenant.brandingAssets.logo`).",examples:[["Upload the test tenant's logo to staging from a file","$0 --env staging --tenant test branding set-logo --file logo.png"],["Upload from an S3 URL","$0 --env staging --tenant test branding set-logo --url https://s3.example/logo.png"],["Upload a Tr\xE4ger's own logo (its units' portal pages and letters wear it)","$0 --env staging --tenant test branding set-logo --legal-entity test_seminare --file seminare.png"]]});file=p.String("--file",{description:"Local image file to upload"});url=p.String("--url",{description:"Fetch the logo image from this URL"});legalEntity=nc();async execute(){let t=await this.caller(),n=this.requireTenant(t),{bytes:i,contentType:r}=await Cde(this.file,this.url),o=await Dde(t,n,i,r);return await t.mutation(A.branding.platformSetBrandingLogo,{client:n,...rc(this.legalEntity),slot:"primary",storageId:o}),this.print({tenant:n,slot:"primary",contentType:r,bytes:i.length,storageId:o},a=>[{field:"tenant",value:a.tenant},{field:"slot",value:a.slot},{field:"contentType",value:a.contentType},{field:"bytes",value:String(a.bytes)},{field:"storageId",value:a.storageId}]),0}},iR=class extends F{static{s(this,"BrandingClearLogoCommand")}static paths=[["branding","clear-logo"]];static usage=E.Usage({category:"Branding",description:"Remove a tenant's portal logo"});legalEntity=nc();async execute(){let t=await this.caller(),n=this.requireTenant(t);return await t.mutation(A.branding.platformClearBrandingLogo,{client:n,...rc(this.legalEntity),slot:"primary"}),this.print({tenant:n,slot:"primary",cleared:!0},i=>[{field:"tenant",value:i.tenant},{field:"slot",value:i.slot},{field:"cleared",value:String(i.cleared)}]),0}};function W4(e){if(e!=="heading"&&e!=="body")throw new w(`branding: --slot must be heading or body (got "${e}")`);return e}s(W4,"parseFontSlot");var oR=class extends F{static{s(this,"BrandingSetFontCommand")}static paths=[["branding","set-font"]];static usage=E.Usage({category:"Branding",description:"Upload a tenant's portal font file (WOFF2) for a slot",details:"Uploads --file as the font of --slot (heading|body). The backend checks the WOFF2 signature and the 2 MB cap and applies the file under the slot's configured family (`fonts.<slot>.family` \u2014 set it first with `branding set-theme` or `config apply`). A replaced file is deleted. `config apply` carries font files by hash too (`tenant.brandingAssets.fontHeading|fontBody`).",examples:[["Upload the test tenant's heading font to staging","$0 --env staging --tenant test branding set-font --slot heading --file heading.woff2"]]});slot=p.String("--slot",{required:!0,description:"heading | body"});file=p.String("--file",{required:!0,description:"Local .woff2 file"});legalEntity=nc();async execute(){let t=W4(this.slot),n=ee.resolve(this.file),i;try{i=Be(n)}catch{throw new w(`File not found: ${this.file}`)}let r=await this.caller(),o=this.requireTenant(r),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),{storageId:l}=await r.action(A.brandingFonts.platformSetBrandingFont,{client:o,...rc(this.legalEntity),slot:t,bytes:a});return this.print({tenant:o,slot:t,bytes:i.length,storageId:l},d=>[{field:"tenant",value:d.tenant},{field:"slot",value:d.slot},{field:"bytes",value:String(d.bytes)},{field:"storageId",value:d.storageId}]),0}},sR=class extends F{static{s(this,"BrandingClearFontCommand")}static paths=[["branding","clear-font"]];static usage=E.Usage({category:"Branding",description:"Remove a tenant's portal font file for a slot (the family stays)"});slot=p.String("--slot",{required:!0,description:"heading | body"});legalEntity=nc();async execute(){let t=W4(this.slot),n=await this.caller(),i=this.requireTenant(n);return await n.mutation(A.branding.platformClearBrandingFont,{client:i,...rc(this.legalEntity),slot:t}),this.print({tenant:i,slot:t,cleared:!0},r=>[{field:"tenant",value:r.tenant},{field:"slot",value:r.slot},{field:"cleared",value:String(r.cleared)}]),0}},aR=class extends F{static{s(this,"BrandingSetThemeCommand")}static paths=[["branding","set-theme"]];static usage=E.Usage({category:"Branding",description:"Set a tenant's portal theme tokens from a JSON file",details:"Replaces the branding THEME (colors/radius/logoSize/bannerDensity/filledHeader/websiteUrl/font families) wholesale from --file. Does NOT touch the uploaded logo or font files (see `branding set-logo` / `branding set-font`). The same brand tokens `config apply` writes, but surgical \u2014 it touches only branding, not the rest of the tenant config.",examples:[["Apply the test tenant's theme to staging","$0 --env staging --tenant test branding set-theme --file theme.json"],["Give a Tr\xE4ger its own theme (replaces the tenant's brand as a block for its units)","$0 --env staging --tenant test branding set-theme --legal-entity test_seminare --file seminare.json"]]});file=p.String("--file",{required:!0,description:"Branding theme JSON"});legalEntity=nc();async execute(){let t=await this.caller(),n=this.requireTenant(t),i=ee.resolve(this.file),r=at(i,"--file");return await t.mutation(A.branding.platformUpdateBranding,{client:n,...rc(this.legalEntity),branding:r}),this.print({tenant:n,applied:!0},o=>[{field:"tenant",value:o.tenant},{field:"applied",value:String(o.applied)}]),0}},lR=class extends F{static{s(this,"BrandingShowCommand")}static paths=[["branding","show"]];static usage=E.Usage({category:"Branding",description:"Show a tenant's current branding + resolved logo and font-file URLs",details:"With --legal-entity <key>, that Tr\xE4ger's own brand \u2014 `branding: null` and no files means it has none, and its units wear the next brand up (a parent Tr\xE4ger's, else the tenant's)."});legalEntity=nc();async execute(){let t=await this.caller(),n=this.requireTenant(t),i=await t.query(A.branding.platformGetBranding,{client:n,...rc(this.legalEntity)});return this.print(i),0}},Z4=[lR,aR,rR,iR,oR,sR];var ic=s(()=>p.String("--output",{hidden:!0}),"retiredOutputOption"),Kt=s(()=>p.Boolean("--force",!1,{description:"Overwrite an existing --out file."}),"forceOption");function oc(e){if(e.retiredOutput===void 0)return e.out;if(e.out!==void 0&&e.out!==e.retiredOutput)throw new Le(`--out "${e.out}" and --output "${e.retiredOutput}" disagree \u2014 pass only --out.`);return Pt(e.context.stderr,"--output","--out"),e.retiredOutput}s(oc,"resolveOut");function fn(e,t){let n=ee.resolve(e);if(Fe(n)&&!t)throw new Le(`${n} exists \u2014 pick another --out or pass --force.`);return n}s(fn,"assertOutFree");function Fde(e){try{return Ji(e)}catch{throw new Le(`${e} is not a directory \u2014 --out names a directory here.`)}}s(Fde,"entriesOf");function dR(e,t){let n=ee.resolve(e);if(Fe(n)&&Fde(n).length>0&&!t)throw new Le(`${n} is not empty \u2014 pick another --out or pass --force.`);return n}s(dR,"assertOutDirFree");function J4(e,t,n){let i=fn(e,n),r=t.map(o=>ee.join(ee.dirname(i),o)).filter(o=>Fe(o));if(r.length>0&&!n)throw new Le(`${r.join(", ")} exist(s) beside --out \u2014 pick another directory or pass --force.`);return i}s(J4,"assertSnapshotOutFree");var lWe=Symbol();var mWe=m.optional(m.any());var lb=class extends Error{static{s(this,"ValidationError")}expected;got;path;constructor(t,n,i){let r=`Validator error${i?` for ${i}`:""}: Expected \`${t}\`, got \`${n}\``;super(r),this.expected=t,this.got=n,this.path=i,this.name="ValidationError"}};function rs(e,t,n){let i=!0,r=e.kind,o;if(t===void 0)e.isOptional!=="optional"&&(i=!1);else switch(e.kind){case"null":{t!==null&&(i=!1);break}case"float64":{typeof t!="number"&&(r="number",i=!1);break}case"int64":{typeof t!="bigint"&&(r="bigint",i=!1);break}case"boolean":{typeof t!="boolean"&&(i=!1);break}case"string":{typeof t!="string"&&(i=!1);break}case"bytes":{t instanceof ArrayBuffer||(i=!1);break}case"any":break;case"literal":{t!==e.value&&(i=!1,r=e.value,["string","number","boolean","bigint"].includes(typeof t)&&(o=`"${t}"`));break}case"id":{typeof t!="string"?i=!1:n?.db&&(r=`Id<${e.tableName}>`,(e.tableName.startsWith("_")?n.db.system.normalizeId(e.tableName,t):n.db.normalizeId(e.tableName,t))||(i=!1));break}case"array":{if(!Array.isArray(t)){i=!1;break}for(let[a,l]of t.entries()){let d=`${n?._pathPrefix??""}[${a}]`;if(i=rs(e.element,l,{...n,_pathPrefix:d}),!i){r=e.element.kind;break}}break}case"object":{if(typeof t!="object"||t===null){i=!1;break}let a=Object.getPrototypeOf(t);if(!(a===null||a===Object.prototype||a?.constructor?.name==="Object")){r=(a?.constructor?.name??typeof a)||"object",i=!1;break}for(let[d,c]of Object.entries(e.fields)){let u=Y4(t,d)?t[d]:void 0;if(i=rs(c,u,{...n,_pathPrefix:ab(n,d)}),!i)break}if(!n?.allowUnknownFields){for(let d of Object.keys(t))if(!Y4(e.fields,d)&&t[d]!==void 0){if(n?.throw)throw new lb("nothing",typeof t[d],ab(n,d));i=!1;break}}break}case"union":{i=!1;let a;for(let l of e.members)try{if(rs(l,t,n)){i=!0;break}}catch(d){a=d}if(!i&&a)throw a;break}case"record":{if(typeof t!="object"||t===null){i=!1;break}for(let[a,l]of Object.entries(t))if(l!==void 0){if(i=rs(e.key,a,{...n,_pathPrefix:ab(n,a)}),!i){r=e.key.kind;break}if(i=rs(e.value,l,{...n,_pathPrefix:ab(n,a)}),!i){r=e.value.kind;break}}break}}if(!i&&n?.throw)throw new lb(r,o??(t===null?"null":typeof t),n?._pathPrefix);return i}s(rs,"validate");function Y4(e,t){return Object.prototype.hasOwnProperty.call(e,t)}s(Y4,"hasOwn");function ab(e,t){return e?._pathPrefix?`${e._pathPrefix}.${t}`:t}s(ab,"appendPath");var Lde=new WeakMap,Mde=new WeakSet;function cR(e,t){t(e);let i=e.asOptional.bind(e);return Object.defineProperty(e,"asOptional",{value:s(()=>cR(i(),t),"value"),enumerable:!1}),e}s(cR,"carry");function sc(e,t){return cR(e,n=>Lde.set(n,t))}s(sc,"tagged");var jde="tenant teardown drains every table explicitly (config/wipe.ts)",Ue={belongsTo:s(e=>sc(e,{kind:"belongsTo"}),"belongsTo"),owns:s(e=>sc(e,{kind:"owns"}),"owns"),holds:s(e=>sc(e,{kind:"holds"}),"holds"),restrict:s((e,t)=>sc(e,t?{kind:"restrict",unindexed:t.unindexed}:{kind:"restrict"}),"restrict"),history:s(e=>sc(e,{kind:"history"}),"history"),tenant:s(e=>sc(e,{kind:"restrict",unindexed:jde}),"tenant"),historyOf:s(e=>cR(e,t=>Mde.add(t)),"historyOf")};var pi={filename:m.string(),mimeType:m.string(),sizeBytes:m.number(),sha256:m.string()},qde=m.object({storageId:m.id("_storage"),filename:pi.filename,mimeType:pi.mimeType,sizeBytes:pi.sizeBytes,sha256:m.optional(pi.sha256)}),vWe=m.object({storageId:qde.fields.storageId,filename:pi.filename,mimeType:m.optional(pi.mimeType),sizeBytes:m.optional(pi.sizeBytes),sha256:m.optional(pi.sha256),url:m.union(m.string(),m.null())});var TWe=m.union(m.literal("de"),m.literal("en")),RWe=m.record(m.string(),m.string()),Vt=m.object({de:m.string(),en:m.string()}),EWe=m.object({value:m.string(),label:Vt,countryCode:m.optional(m.union(m.string(),m.null()))}),_We=m.object({title:Vt,body:Vt,confirmLabel:Vt}),Q4=m.union(m.string(),Vt);function db(e){return Xe.includes(e)}s(db,"isSupportedLocale");var zde=m.object({street:m.string(),hausnr:m.string(),plz:m.string(),ort:m.string(),land:m.string()}),H4=m.object({storageId:m.string(),filename:pi.filename,uploadedAt:m.number()}),OWe=m.union(m.string(),m.number(),m.boolean(),m.null(),zde,H4,m.array(m.string()),m.array(H4)),PWe=m.record(m.string(),m.string()),NWe=m.union(m.object({filterKey:m.string(),optionKeys:m.array(m.string())}),m.object({filterKey:m.string(),text:m.string()}),m.object({filterKey:m.string(),min:m.optional(m.number()),max:m.optional(m.number())}));var Ude=m.object({key:m.string(),label:Vt,type:m.string(),required:m.optional(m.boolean()),options:m.optional(m.array(m.object({value:m.string(),label:Vt}))),defaultValue:m.optional(m.union(m.string(),m.number(),m.boolean(),m.object({itemKey:m.string(),grantKeys:m.array(m.string())}))),priceDate:m.optional(m.string()),processSource:m.optional(m.union(...Gs.map(e=>m.literal(e))))}),uR=m.object({fields:m.array(Ude),localeField:m.optional(m.string())}),UWe=En({officeSession:m.optional(m.object({key:m.string(),userId:Ue.history(m.id("users")),expiresAt:m.number(),baseStorageId:Ue.restrict(m.id("_storage")),baseUpdatedAt:m.number(),status:m.union(m.literal("editing"),m.literal("saving"),m.literal("ready"),m.literal("error")),requestId:m.optional(m.string()),error:m.optional(Vt),draftStorageId:m.optional(Ue.owns(m.id("_storage"))),draftSize:m.optional(m.number()),placeholders:m.optional(m.array(m.string())),signatureAnchorKeys:m.optional(m.array(m.string()))})),tenantId:Ue.tenant(m.id("tenants")),configKey:m.optional(m.string()),name:Q4,icon:m.optional(m.string()),fileNamePattern:m.optional(m.string()),roleId:Ue.restrict(m.id("roles")),storageId:Ue.restrict(m.id("_storage")),filename:m.optional(pi.filename),fileName:m.optional(m.string()),detectedCustomFieldIds:m.array(Ue.restrict(m.id("custom_fields"),{unindexed:"array of fields detected in the template file"})),detectedPlaceholders:m.array(m.string()),signatureAnchorKeys:m.optional(m.array(m.string())),parameters:m.optional(uR),createdAt:m.number(),updatedAt:m.number(),createdByUserId:m.optional(Ue.history(m.id("users"))),updatedByUserId:m.optional(Ue.history(m.id("users")))}).index("by_tenantId",["tenantId"]).index("by_tenantId_and_configKey",["tenantId","configKey"]).index("by_tenantId_and_roleId",["tenantId","roleId"]).index("by_storageId",["storageId"]).index("by_officeSession_draftStorageId",["officeSession.draftStorageId"]).index("by_officeSession_baseStorageId",["officeSession.baseStorageId"]);function cb(e){(!Number.isSafeInteger(e)||e<0)&&ge("INVALID",{de:"Betr\xE4ge m\xFCssen nichtnegative ganze Centbetr\xE4ge sein.",en:"Amounts must be non-negative whole amounts in cents."})}s(cb,"assertMoney");var fR=["month","year","once","unit"];var Kde=s(e=>e!==void 0&&/^[1-9]\d{0,8}$/.test(e),"positiveIntegerText");function is(e,t){return ge("CONFLICT",{de:e,en:t})}s(is,"missing");var X4=s(e=>e!==void 0&&/^\d{4}-\d{2}-\d{2}$/.test(e)&&Number.isFinite(new Date(`${e}T00:00:00Z`).valueOf())&&new Date(`${e}T00:00:00Z`).toISOString().slice(0,10)===e,"isoDate");function e6(e,t,n){return{label:t,kind:"chosen",valueType:"choice",choices:n,resolve(i){let r=i.selections?.[e];return(!r||!n.includes(r))&&is(`Die Auswahl f\xFCr \u201E${t.de}\u201C fehlt oder ist ung\xFCltig.`,`The selection for \u201C${t.en}\u201D is missing or invalid.`),{value:r,explanation:{de:`${t.de}: ${r} (Vertragsauswahl)`,en:`${t.en}: ${r} (contract selection)`}}}}}s(e6,"chosen");function pR(e,t){let n=e.enrollment,i=n?.contextDate??t;return(!n||!n.startDate||n.startDate>i||n.endDate&&n.endDate<i)&&is("F\xFCr dieses Datum fehlt eine eindeutige Einschreibung.","An unambiguous enrollment is missing for this date."),n}s(pR,"enrollment");var Vde={paymentFrequency:e6("paymentFrequency",{de:"Zahlungsweise",en:"Payment frequency"},["monthly","yearly"]),gradeLevel:{label:{de:"Klassenstufe",en:"Grade level"},kind:"derived",valueType:"integer",resolve(e,t){let n=pR(e,t).gradeLevel;return(!Number.isSafeInteger(n)||n<1)&&is("Die Klassenstufe fehlt.","The grade level is missing."),{value:n,explanation:{de:`Klassenstufe ${n} am ${t}`,en:`Grade ${n} on ${t}`}}}},schoolYear:{label:{de:"Schuljahr",en:"School year"},kind:"derived",valueType:"integer",resolve(e,t){let n=pR(e,t).schoolYear;return(!Number.isSafeInteger(n)||n<1)&&is("F\xFCr dieses Datum fehlt ein j\xE4hrlicher Schuljahreslauf.","An annual school-year run is missing for this date."),{value:n,explanation:{de:`Schuljahr ${n}/${n+1}`,en:`School year ${n}/${n+1}`}}}},siblingRank:{label:{de:"Geschwisterrang",en:"Sibling rank"},kind:"derived",valueType:"integer",resolve(e,t){if(e.chosenCriteria?.includes("siblingRank")){let c=e.selections?.siblingRank;return Kde(c)||is("Der im Vertrag gew\xE4hlte Geschwisterrang fehlt oder ist keine ganze Zahl ab 1.","The sibling rank chosen on the contract is missing or not a whole number from 1."),{value:Number(c),explanation:{de:`Geschwisterrang ${c} (im Vertrag gew\xE4hlt)`,en:`Sibling rank ${c} (chosen on the contract)`}}}e.unavailable?.siblingRank&&ge("CONFLICT",e.unavailable.siblingRank);let n=e.siblings?[...new Map(e.siblings.filter(c=>c.eligible).map(c=>[c.partyId,c])).values()]:void 0;(!e.partyId||!n?.some(c=>c.partyId===e.partyId))&&is("F\xFCr dieses Datum fehlt die Sch\xFClerrolle des Kindes.","The child\u2019s Student role is missing for this date."),n.some(c=>!X4(c.firstEnrolledOn)||c.firstEnrolledOn>t)&&is("F\xFCr den Geschwisterrang fehlt ein g\xFCltiger erster Einschreibungsbeginn.","A valid first enrollment start is missing for sibling ranking.");let i=n.find(c=>c.partyId===e.partyId),r=i.firstEnrolledOn,o=n.filter(c=>c.firstEnrolledOn===r);o.length>1&&o.some(c=>!X4(c.birthDate)||c.birthDate>t)&&is("Geschwister wurden am selben Tag erstmals eingeschrieben, und f\xFCr die Reihenfolge fehlt ein g\xFCltiges Geburtsdatum.","Siblings first enrolled on the same day, and a valid birth date is missing to order them.");let a=s(c=>c.birthDate<i.birthDate||c.birthDate===i.birthDate&&c.partyId<i.partyId,"before"),l=n.filter(c=>c.firstEnrolledOn<r).length+o.filter(c=>c!==i&&a(c)).length+1,d=o.length>1?{de:`; gleicher Beginn wie ${o.length-1} Geschwister: \xE4lteste zuerst, bei gleichem Geburtsdatum nach Personen-ID`,en:`; same start as ${o.length-1} sibling${o.length>2?"s":""}: oldest first, then party ID for equal birth dates`}:{de:"",en:""};return{value:l,explanation:{de:`${l}. Kind von ${n.length} berechtigten Kindern am ${t}; erste Einschreibung am ${r}, zuerst eingeschriebene Kinder zuerst${d.de}.`,en:`Child ${l} of ${n.length} eligible children on ${t}; first enrollment on ${r}, first enrolled first${d.en}.`}}}},program:{label:{de:"Programm",en:"Program"},kind:"derived",valueType:"program",resolve(e,t){let n=pR(e,t).programId;return n||is("Das Programm fehlt.","The program is missing."),{value:n,explanation:{de:`Programm der Einschreibung am ${t}`,en:`Enrollment program on ${t}`}}}},admissionFeeTier:e6("admissionFeeTier",{de:"Anmeldegeb\xFChrensatz",en:"Admission fee tier"},["100","75","50"])},Bde=Object.fromEntries(Object.entries(Vde).map(([e,t])=>[e,{...t,matchSchema:{parse(n){return Wde(t,n),n}},matches:Gde}])),JWe=Object.keys(Bde);function Gde(e,t){return"else"in t?!0:"eq"in t?e===t.eq:"in"in t?t.in.includes(e):typeof e=="number"&&(t.gte===void 0||e>=t.gte)&&(t.lte===void 0||e<=t.lte)}s(Gde,"matchesPrice");function Wde(e,t){let n=s(()=>ge("INVALID",{de:"Der Match passt nicht zum Preiskriterium.",en:"The match does not fit the price criterion."}),"fail");if(!t||typeof t!="object"||Array.isArray(t))return n();let i=t,r=Object.keys(i).sort().join();if(r==="else"&&i.else===!0)return;let o=s(a=>e.valueType==="integer"?Number.isSafeInteger(a)&&Number(a)>=1:typeof a=="string"&&a.length>0&&(e.valueType!=="choice"||e.choices.includes(a)),"validValue");if(!(r==="eq"&&o(i.eq))&&!(r==="in"&&Array.isArray(i.in)&&i.in.length>0&&new Set(i.in).size===i.in.length&&i.in.every(o))&&!(e.valueType==="integer"&&["gte","lte","gte,lte"].includes(r)&&Object.values(i).every(a=>Number.isSafeInteger(a)&&Number(a)>=1)&&(i.gte===void 0||i.lte===void 0||Number(i.gte)<=Number(i.lte))))return n()}s(Wde,"validateMatch");function t6(e,t){if(Object.keys(t).some(n=>!["percent","amountMinor"].includes(n))&&ge("INVALID",{de:"Die Erm\xE4\xDFigung braucht genau eine Prozentregel oder einen Centbetrag.",en:"The reduction needs exactly one percentage rule or one amount in cents."}),e==="percent"&&"percent"in t&&!("amountMinor"in t)){(!Number.isFinite(t.percent)||t.percent<0||t.percent>100)&&ge("INVALID",{de:"Prozentwerte m\xFCssen zwischen 0 und 100 liegen.",en:"Percentages must be between 0 and 100."});return}if(e==="absolute"&&"amountMinor"in t&&!("percent"in t))return cb(t.amountMinor);ge("INVALID",{de:"Die Erm\xE4\xDFigung braucht genau eine Prozentregel oder einen Centbetrag.",en:"The reduction needs exactly one percentage rule or one amount in cents."})}s(t6,"validateRule");var Zde=/^[a-z][a-z0-9_-]{0,63}$/;function n6(e){return Zde.test(e)}s(n6,"isTemplateConfigKey");import{createHash as ece}from"node:crypto";import{inflateRawSync as tce}from"node:zlib";var r6=/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/,Jde=/{{\s*([^{}]+?)\s*}}|<<\s*([^<>]+?)\s*>>/g,Yde=/^[#/]\s*/;function Hde(e){let t=e.trim(),n=t.match(/^{{\s*([^{}]+?)\s*}}$/);if(n)return n[1]?.trim()??t;let i=t.match(/^<<\s*([^<>]+?)\s*>>$/);return i?i[1]?.trim()??t:t}s(Hde,"innerTemplatePlaceholder");function ub(e){return Hde(e).replace(Yde,"")}s(ub,"normalizeTemplatePlaceholderKey");function fb(e){return ub(e).toLowerCase()}s(fb,"canonicalTemplatePlaceholderKey");function i6(e){let t=new Map;for(let n of Qde(e))t.has(n.key)||t.set(n.key,n.placeholder);return Array.from(t.entries()).sort(([n],[i])=>n.localeCompare(i,"de")).map(([,n])=>n)}s(i6,"extractTemplatePlaceholders");function Qde(e){let t=[];for(let n of e.matchAll(Jde)){let i=ub(n[1]??n[2]??"");i&&t.push({key:fb(i),placeholder:n[0].trim()})}return t}s(Qde,"extractTemplatePlaceholderOccurrences");var o6=/^word\/(document|header\d+|footer\d+|footnotes|endnotes)\.xml$/;function Xde(e){return e.replace(/<[^>]+>/g,"").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&#(\d+);/g,(t,n)=>String.fromCodePoint(Number(n))).replace(/&#x([0-9a-f]+);/gi,(t,n)=>String.fromCodePoint(parseInt(n,16))).replace(/&amp;/g,"&")}s(Xde,"templateXmlText");function s6(e){return e.map(Xde).join(`
11853
+ `,examples:[["Portal application to an offer",`$0 assignment simulate --dir ~/scratch/kindergarten-r17 --env-json '{"applicant":{"language":"de","channel":"self-service"}}'`],["The next pick of a \u201EReihum\u201C row whose last start took 'finanzen'","$0 assignment simulate --dir <bundle> --env-file env.json --rotation-previous team:finanzen=finanzen"],["A leastLoaded rotation with open-task counts","$0 assignment simulate --dir <bundle> --env-file env.json --open finanzen=3 --open finanzen_2=1"]]});dir=p.String("--dir",{required:!0,description:"Offer bundle directory (its workflow.json carries the rule)"});envJson=p.String("--env-json",{description:"The application's environment ($env) as JSON"});envFile=p.String("--env-file",{description:"\u2026or a file holding it"});creator=p.String("--creator",{description:"Label for the staff creator (only a staff start has one)"});rotationPrevious=p.Array("--rotation-previous",{description:"<slot>=<personKey>: the last pick of that slot's \u201EReihum\u201C row (repeatable; none = its first start)"});left=p.Array("--left",{description:"<personKey>: someone who has left \u2014 every rotation skips them (repeatable)"});open=p.Array("--open",{description:"<personKey>=<n>: open tasks, for a leastLoaded rotation (repeatable; absent = 0)"});async execute(){let t=it(this.dir),n=XW(t.workflow?.graph,`bundle ${this.dir}`),i=Ede(this.envJson,this.envFile),r=O4(n,i,{...this.creator!==void 0?{creator:this.creator}:{},rotationPrevious:P4("--rotation-previous",this.rotationPrevious),openCounts:Rde(this.open),left:this.left??[]});return this.print(r,o=>o.slots.map(a=>({slot:a.slot,row:`#${a.row}`,value:a.value,rotation:a.rotation===void 0?"":`${a.rotation.mode} [${a.rotation.pool.join(", ")}] after ${a.rotation.previous??"\u2014"} \u2192 ${a.rotation.picked}`}))),0}},N4=[HT];import{createHash as _de}from"node:crypto";var QT=/^[a-z0-9][a-z0-9-]*$/;function ec(e){return QT.test(e)}s(ec,"isFileKey");function ll(e){return e.trim()===""?"is empty":e==="."||e===".."?"is not a file name":/[/\\]/.test(e)?"must not contain a path separator":[...e].some(t=>t.charCodeAt(0)<=31)?"must not contain control characters":null}s(ll,"fileNameDefect");var F4={".pdf":"application/pdf",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword",".odt":"application/vnd.oasis.opendocument.text",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png"},ob={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".avif":"image/avif",".woff2":"font/woff2"};function tc(e){return _de("sha256").update(e).digest("hex")}s(tc,"sha256Hex");function jf(e,t=F4){let n=ee.resolve(e),i;try{i=Be(n)}catch{throw new w(`File not found: ${e}`)}let r=t[ee.extname(n).toLowerCase()];if(r===void 0)throw new w(`${e}: unsupported file type \u2014 allowed: ${Object.keys(t).join(", ")}.`);return{bytes:i,filename:ee.basename(n),mimeType:r,sha256:tc(i),sizeBytes:i.length}}s(jf,"readLocalFile");var Ode={tenantFile:A.tenantFiles.platformGenerateUploadUrl,brandingAsset:A.branding.platformGenerateBrandingAssetUploadUrl,brandingLogo:A.branding.platformGenerateBrandingLogoUploadUrl,contractTwin:A.contractTwins.generateUploadUrl};async function ns(e,t,n,i,r){let{uploadUrl:o,uploadTicket:a}=await e.mutation(Ode[r],{client:t}),l=await e.upload(o,n,i);return await e.mutation(A.uploads.registerUpload,{uploadTicket:a,storageId:l}),l}s(ns,"uploadStaged");async function L4(e,t,n,i){return await ns(e,t,n,i,"tenantFile")}s(L4,"uploadTenantFile");function XT(e){let t=[...e].filter(([,n])=>"fileName"in n||"size"in n).map(([n])=>n);if(t.length!==0)throw new Error(`[cli/serverPredatesFileRef] ${t.join(", ")}: the target deployment still answers fileName / size \u2014 it runs a release from before file references. Use a plexus-cli built from that release, or wait for the next release.`)}s(XT,"requireFileRefNames");async function qf(e,t){let n=await e.query(A.tenantFiles.platformList,{client:t});return XT(n.map(i=>[`files["${i.key}"]`,i])),n}s(qf,"listLibrary");function M4(e,t,n,i,r){let o=jf(ee.resolve(e,t),r);if(o.mimeType!==n)throw new w(`${i}: ${t} is ${o.mimeType}, the entry declares ${n}.`);return o}s(M4,"readSnapshotEntry");function j4(e,t){let n=new Map,i=(e.files??[]).map(l=>{if(l.path===void 0)return l;let{path:d,...c}=l,u=M4(t,d,c.mimeType,`files["${c.key}"]`,F4);return n.set(c.key,u),{...c,sha256:u.sha256,sizeBytes:u.sizeBytes}}),r=C4(e.tenant.brandingAssets,t,"tenant"),o=new Map,a=(e.foundation?.legalEntities??[]).map(l=>{if(l.brandingAssets===void 0)return l;let d=C4(l.brandingAssets,t,`foundation.legalEntities.${l.key}`);return o.set(l.key,d.bytes),{...l,brandingAssets:d.assets}});return{config:{...e,tenant:{...e.tenant,...r.assets!==void 0?{brandingAssets:r.assets}:{}},...e.foundation!==void 0?{foundation:{...e.foundation,legalEntities:a}}:{},files:i},bytes:n,brandingBytes:r.bytes,legalEntityBrandingBytes:o}}s(j4,"resolveSnapshotFiles");function C4(e,t,n){let i=new Map,r=e;if(r===void 0)return{assets:void 0,bytes:i};let o={};for(let[a,l]of Object.entries(r)){if(l.path===void 0){o[a]=l;continue}let{path:d,...c}=l,u=M4(t,d,c.mimeType,`${n}.brandingAssets.${a}`,ob);i.set(a,u),o[a]={...c,sha256:u.sha256,sizeBytes:u.sizeBytes}}return{assets:o,bytes:i}}s(C4,"resolveSnapshotBranding");async function q4(e,t,n,i,r){let o={},a={contents:o,changed:[],unavailable:[]};for(let l of e){if(t.get(l.key)===l.sha256)continue;a.changed.push(l.key);let d=await n(l.key);if(d===void 0){a.unavailable.push(l.key);continue}if(tc(d)!==l.sha256)throw new w(`${l.at}: the supplied bytes do not match sha256 ${l.sha256}.`);r||(o[l.key]=await i(d,l.mimeType))}return a}s(q4,"stageChanged");async function z4(e,t,n,i,r){let o=new Map(Object.entries(await e.query(A.tenantFiles.platformFileHashes,{client:t})??{})),a=new Map(n.map(l=>[l.key,l]));return await q4(n.map(l=>({key:l.key,sha256:l.sha256,mimeType:l.mimeType,at:`files["${l.key}"]`})),o,l=>i(a.get(l)),(l,d)=>ns(e,t,l,d,"tenantFile"),r)}s(z4,"stageFileContents");function U4(e){return e===void 0?"tenant":`foundation.legalEntities.${e}`}s(U4,"brandingHolder");async function sb(e,t,n){let i=await e.query(A.branding.platformBrandingAssets,{client:t,...n!==void 0?{legalEntity:n}:{}});return XT(Object.entries(i??{}).map(([r,o])=>[`${U4(n)}.brandingAssets.${r}`,o])),i}s(sb,"listBrandingAssets");async function eR(e,t,n,i,r,o){let a=new Map(Object.entries(await sb(e,t,o)??{}).map(([d,c])=>[d,c.sha256])),l=U4(o);return await q4(Object.entries(n??{}).map(([d,c])=>({key:d,sha256:c.sha256,mimeType:c.mimeType,at:`${l}.brandingAssets.${d}`})),a,i,(d,c)=>ns(e,t,d,c,"brandingAsset"),r)}s(eR,"stageBrandingAssets");async function K4(e,t,n,i){if(e===null||t===void 0)throw new Error(`${n}: its stored object is gone \u2014 ${i}`);let r=await fetch(e);if(!r.ok)throw new Error(`download of ${n} failed (${r.status}).`);let o=new Uint8Array(await r.arrayBuffer());if(tc(o)!==t)throw new Error(`download of ${n} does not match its sha256 ${t}.`);return o}s(K4,"downloadVerified");async function tR(e){return await K4(e.url,e.sha256,`"${e.key}"`,"replace it with `files put` first.")}s(tR,"downloadLibraryFile");async function nR(e,t,n){return await K4(t.url,t.sha256,n===void 0?`branding/${e}`:`branding/${n}/${e}`,"upload it again with `branding set-logo` / `branding set-font` first.")}s(nR,"downloadBrandingAsset");function Pde(e,t,n){let i=Object.keys(ob).find(r=>ob[r]===t);if(i===void 0)throw new Error(`export: branding/${e} is ${t}, which a snapshot cannot name (${Object.keys(ob).join(", ")}).`);if(n===void 0)return ee.join("branding",`${e}${i}`);if(!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(n))throw new Error(`export: legal entity key "${n}" is not a safe directory name for its brand files.`);return ee.join("branding",n,`${e}${i}`)}s(Pde,"brandingAssetPath");function V4(e,t,n){let i=ee.join(e,t);bn(ee.dirname(i),{recursive:!0}),ft(i,n)}s(V4,"writeBeside");async function B4(e,t,n,i){XT([...n.files.map(c=>[`files["${c.key}"]`,c]),...Object.entries(n.tenant.brandingAssets??{}).map(([c,u])=>[`tenant.brandingAssets.${c}`,u]),...(n.foundation?.legalEntities??[]).flatMap(c=>Object.entries(c.brandingAssets??{}).map(([u,f])=>[`foundation.legalEntities.${c.key}.brandingAssets.${u}`,f]))]);let r=new Map((await qf(e,t)).map(c=>[c.key,c])),o=ee.dirname(i),a=[];for(let c of n.files){let u=r.get(c.key);if(u===void 0)throw new Error(`export: "${c.key}" vanished from the library between two reads \u2014 rerun.`);let f=ll(c.filename);if(f!==null||!ec(c.key))throw new Error(`export: "${c.key}" / "${c.filename}" is not a safe path (${f??"bad key"}).`);let h=ee.join("files",c.key,c.filename);V4(o,h,await tR(u)),a.push({...c,path:h})}let l=await D4(e,t,n.tenant.brandingAssets,o,void 0),d=[];for(let c of n.foundation?.legalEntities??[]){if(c.brandingAssets===void 0){d.push(c);continue}d.push({...c,brandingAssets:await D4(e,t,c.brandingAssets,o,c.key)})}return{...n,tenant:{...n.tenant,...l!==void 0?{brandingAssets:l}:{}},...n.foundation!==void 0?{foundation:{...n.foundation,legalEntities:d}}:{},files:a}}s(B4,"writeSnapshotFiles");async function D4(e,t,n,i,r){if(n===void 0)return;let o=await sb(e,t,r)??{},a={};for(let[l,d]of Object.entries(n)){let c=o[l],u=Pde(l,d.mimeType,r);if(c===void 0||c.sha256!==d.sha256)throw new Error(`export: ${u} changed between two reads \u2014 rerun.`);V4(i,u,await nR(l,c,r)),a[l]={...d,path:u}}return a}s(D4,"writeSnapshotBranding");var Nde={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml",".avif":"image/avif"};function G4(e){return Nde[ee.extname(e).toLowerCase()]}s(G4,"guessImageContentType");async function Cde(e,t){if(e===void 0==(t===void 0))throw new w("Pass exactly one of --file <path> or --url <url>.");if(t!==void 0&&Dt())throw new w("Hosted agents cannot fetch arbitrary logo URLs. Upload the image to the chat and use --file <path>.");if(e!==void 0){let a=ee.resolve(e),l;try{l=Be(a)}catch{throw new w(`File not found: ${e}`)}let d=G4(a);if(d===void 0)throw new w(`Cannot infer an image content-type from "${ee.basename(a)}" \u2014 use a .png/.jpg/.webp/.gif file.`);return{bytes:new Uint8Array(l),contentType:d}}let n=await fetch(t);if(!n.ok)throw new Error(`Fetch failed for ${t} (${n.status} ${n.statusText}).`);let i=new Uint8Array(await n.arrayBuffer()),r=n.headers.get("content-type")?.split(";")[0]?.trim(),o=r&&r.startsWith("image/")?r:G4(new URL(t).pathname);if(o===void 0)throw new Error(`Response for ${t} is not an image (content-type "${r??"unknown"}").`);return{bytes:i,contentType:o}}s(Cde,"loadLogoBytes");function nc(){return p.String("--legal-entity",{description:"A legal entity's config key \u2014 its own brand, which overrides the tenant's for its units"})}s(nc,"legalEntityOption");function rc(e){return e===void 0?{}:{legalEntity:e}}s(rc,"ownerArgs");async function Dde(e,t,n,i){return await ns(e,t,n,i,"brandingLogo")}s(Dde,"uploadLogo");var rR=class extends F{static{s(this,"BrandingSetLogoCommand")}static paths=[["branding","set-logo"]];static usage=E.Usage({category:"Branding",description:"Upload a tenant's portal logo",details:"Sets the external-portal logo for --tenant from a local --file or a remote --url. A one-off upload without the tenant's Branding admin UI. To move the logo with the rest of the config (export \u2192 apply, env \u2192 env), use `config apply` \u2014 it carries the file by hash (`tenant.brandingAssets.logo`).",examples:[["Upload the test tenant's logo to staging from a file","$0 --env staging --tenant test branding set-logo --file logo.png"],["Upload from an S3 URL","$0 --env staging --tenant test branding set-logo --url https://s3.example/logo.png"],["Upload a Tr\xE4ger's own logo (its units' portal pages and letters wear it)","$0 --env staging --tenant test branding set-logo --legal-entity test_seminare --file seminare.png"]]});file=p.String("--file",{description:"Local image file to upload"});url=p.String("--url",{description:"Fetch the logo image from this URL"});legalEntity=nc();async execute(){let t=await this.caller(),n=this.requireTenant(t),{bytes:i,contentType:r}=await Cde(this.file,this.url),o=await Dde(t,n,i,r);return await t.mutation(A.branding.platformSetBrandingLogo,{client:n,...rc(this.legalEntity),slot:"primary",storageId:o}),this.print({tenant:n,slot:"primary",contentType:r,bytes:i.length,storageId:o},a=>[{field:"tenant",value:a.tenant},{field:"slot",value:a.slot},{field:"contentType",value:a.contentType},{field:"bytes",value:String(a.bytes)},{field:"storageId",value:a.storageId}]),0}},iR=class extends F{static{s(this,"BrandingClearLogoCommand")}static paths=[["branding","clear-logo"]];static usage=E.Usage({category:"Branding",description:"Remove a tenant's portal logo"});legalEntity=nc();async execute(){let t=await this.caller(),n=this.requireTenant(t);return await t.mutation(A.branding.platformClearBrandingLogo,{client:n,...rc(this.legalEntity),slot:"primary"}),this.print({tenant:n,slot:"primary",cleared:!0},i=>[{field:"tenant",value:i.tenant},{field:"slot",value:i.slot},{field:"cleared",value:String(i.cleared)}]),0}};function W4(e){if(e!=="heading"&&e!=="body")throw new w(`branding: --slot must be heading or body (got "${e}")`);return e}s(W4,"parseFontSlot");var oR=class extends F{static{s(this,"BrandingSetFontCommand")}static paths=[["branding","set-font"]];static usage=E.Usage({category:"Branding",description:"Upload a tenant's portal font file (WOFF2) for a slot",details:"Uploads --file as the font of --slot (heading|body). The backend checks the WOFF2 signature and the 2 MB cap and applies the file under the slot's configured family (`fonts.<slot>.family` \u2014 set it first with `branding set-theme` or `config apply`). A replaced file is deleted. `config apply` carries font files by hash too (`tenant.brandingAssets.fontHeading|fontBody`).",examples:[["Upload the test tenant's heading font to staging","$0 --env staging --tenant test branding set-font --slot heading --file heading.woff2"]]});slot=p.String("--slot",{required:!0,description:"heading | body"});file=p.String("--file",{required:!0,description:"Local .woff2 file"});legalEntity=nc();async execute(){let t=W4(this.slot),n=ee.resolve(this.file),i;try{i=Be(n)}catch{throw new w(`File not found: ${this.file}`)}let r=await this.caller(),o=this.requireTenant(r),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),{storageId:l}=await r.action(A.brandingFonts.platformSetBrandingFont,{client:o,...rc(this.legalEntity),slot:t,bytes:a});return this.print({tenant:o,slot:t,bytes:i.length,storageId:l},d=>[{field:"tenant",value:d.tenant},{field:"slot",value:d.slot},{field:"bytes",value:String(d.bytes)},{field:"storageId",value:d.storageId}]),0}},sR=class extends F{static{s(this,"BrandingClearFontCommand")}static paths=[["branding","clear-font"]];static usage=E.Usage({category:"Branding",description:"Remove a tenant's portal font file for a slot (the family stays)"});slot=p.String("--slot",{required:!0,description:"heading | body"});legalEntity=nc();async execute(){let t=W4(this.slot),n=await this.caller(),i=this.requireTenant(n);return await n.mutation(A.branding.platformClearBrandingFont,{client:i,...rc(this.legalEntity),slot:t}),this.print({tenant:i,slot:t,cleared:!0},r=>[{field:"tenant",value:r.tenant},{field:"slot",value:r.slot},{field:"cleared",value:String(r.cleared)}]),0}},aR=class extends F{static{s(this,"BrandingSetThemeCommand")}static paths=[["branding","set-theme"]];static usage=E.Usage({category:"Branding",description:"Set a tenant's portal theme tokens from a JSON file",details:"Replaces the branding THEME (colors/radius/logoSize/bannerDensity/filledHeader/websiteUrl/font families) wholesale from --file. Does NOT touch the uploaded logo or font files (see `branding set-logo` / `branding set-font`). The same brand tokens `config apply` writes, but surgical \u2014 it touches only branding, not the rest of the tenant config.",examples:[["Apply the test tenant's theme to staging","$0 --env staging --tenant test branding set-theme --file theme.json"],["Give a Tr\xE4ger its own theme (replaces the tenant's brand as a block for its units)","$0 --env staging --tenant test branding set-theme --legal-entity test_seminare --file seminare.json"]]});file=p.String("--file",{required:!0,description:"Branding theme JSON"});legalEntity=nc();async execute(){let t=await this.caller(),n=this.requireTenant(t),i=ee.resolve(this.file),r=at(i,"--file");return await t.mutation(A.branding.platformUpdateBranding,{client:n,...rc(this.legalEntity),branding:r}),this.print({tenant:n,applied:!0},o=>[{field:"tenant",value:o.tenant},{field:"applied",value:String(o.applied)}]),0}},lR=class extends F{static{s(this,"BrandingShowCommand")}static paths=[["branding","show"]];static usage=E.Usage({category:"Branding",description:"Show a tenant's current branding + resolved logo and font-file URLs",details:"With --legal-entity <key>, that Tr\xE4ger's own brand \u2014 `branding: null` and no files means it has none, and its units wear the next brand up (a parent Tr\xE4ger's, else the tenant's)."});legalEntity=nc();async execute(){let t=await this.caller(),n=this.requireTenant(t),i=await t.query(A.branding.platformGetBranding,{client:n,...rc(this.legalEntity)});return this.print(i),0}},Z4=[lR,aR,rR,iR,oR,sR];var ic=s(()=>p.String("--output",{hidden:!0}),"retiredOutputOption"),Kt=s(()=>p.Boolean("--force",!1,{description:"Overwrite an existing --out file."}),"forceOption");function oc(e){if(e.retiredOutput===void 0)return e.out;if(e.out!==void 0&&e.out!==e.retiredOutput)throw new Le(`--out "${e.out}" and --output "${e.retiredOutput}" disagree \u2014 pass only --out.`);return Pt(e.context.stderr,"--output","--out"),e.retiredOutput}s(oc,"resolveOut");function fn(e,t){let n=ee.resolve(e);if(Fe(n)&&!t)throw new Le(`${n} exists \u2014 pick another --out or pass --force.`);return n}s(fn,"assertOutFree");function Fde(e){try{return Ji(e)}catch{throw new Le(`${e} is not a directory \u2014 --out names a directory here.`)}}s(Fde,"entriesOf");function dR(e,t){let n=ee.resolve(e);if(Fe(n)&&Fde(n).length>0&&!t)throw new Le(`${n} is not empty \u2014 pick another --out or pass --force.`);return n}s(dR,"assertOutDirFree");function J4(e,t,n){let i=fn(e,n),r=t.map(o=>ee.join(ee.dirname(i),o)).filter(o=>Fe(o));if(r.length>0&&!n)throw new Le(`${r.join(", ")} exist(s) beside --out \u2014 pick another directory or pass --force.`);return i}s(J4,"assertSnapshotOutFree");var lWe=Symbol();var mWe=m.optional(m.any());var lb=class extends Error{static{s(this,"ValidationError")}expected;got;path;constructor(t,n,i){let r=`Validator error${i?` for ${i}`:""}: Expected \`${t}\`, got \`${n}\``;super(r),this.expected=t,this.got=n,this.path=i,this.name="ValidationError"}};function rs(e,t,n){let i=!0,r=e.kind,o;if(t===void 0)e.isOptional!=="optional"&&(i=!1);else switch(e.kind){case"null":{t!==null&&(i=!1);break}case"float64":{typeof t!="number"&&(r="number",i=!1);break}case"int64":{typeof t!="bigint"&&(r="bigint",i=!1);break}case"boolean":{typeof t!="boolean"&&(i=!1);break}case"string":{typeof t!="string"&&(i=!1);break}case"bytes":{t instanceof ArrayBuffer||(i=!1);break}case"any":break;case"literal":{t!==e.value&&(i=!1,r=e.value,["string","number","boolean","bigint"].includes(typeof t)&&(o=`"${t}"`));break}case"id":{typeof t!="string"?i=!1:n?.db&&(r=`Id<${e.tableName}>`,(e.tableName.startsWith("_")?n.db.system.normalizeId(e.tableName,t):n.db.normalizeId(e.tableName,t))||(i=!1));break}case"array":{if(!Array.isArray(t)){i=!1;break}for(let[a,l]of t.entries()){let d=`${n?._pathPrefix??""}[${a}]`;if(i=rs(e.element,l,{...n,_pathPrefix:d}),!i){r=e.element.kind;break}}break}case"object":{if(typeof t!="object"||t===null){i=!1;break}let a=Object.getPrototypeOf(t);if(!(a===null||a===Object.prototype||a?.constructor?.name==="Object")){r=(a?.constructor?.name??typeof a)||"object",i=!1;break}for(let[d,c]of Object.entries(e.fields)){let u=Y4(t,d)?t[d]:void 0;if(i=rs(c,u,{...n,_pathPrefix:ab(n,d)}),!i)break}if(!n?.allowUnknownFields){for(let d of Object.keys(t))if(!Y4(e.fields,d)&&t[d]!==void 0){if(n?.throw)throw new lb("nothing",typeof t[d],ab(n,d));i=!1;break}}break}case"union":{i=!1;let a;for(let l of e.members)try{if(rs(l,t,n)){i=!0;break}}catch(d){a=d}if(!i&&a)throw a;break}case"record":{if(typeof t!="object"||t===null){i=!1;break}for(let[a,l]of Object.entries(t))if(l!==void 0){if(i=rs(e.key,a,{...n,_pathPrefix:ab(n,a)}),!i){r=e.key.kind;break}if(i=rs(e.value,l,{...n,_pathPrefix:ab(n,a)}),!i){r=e.value.kind;break}}break}}if(!i&&n?.throw)throw new lb(r,o??(t===null?"null":typeof t),n?._pathPrefix);return i}s(rs,"validate");function Y4(e,t){return Object.prototype.hasOwnProperty.call(e,t)}s(Y4,"hasOwn");function ab(e,t){return e?._pathPrefix?`${e._pathPrefix}.${t}`:t}s(ab,"appendPath");var Lde=new WeakMap,Mde=new WeakSet;function cR(e,t){t(e);let n=e.optional.bind(e);return Object.defineProperty(e,"asOptional",{value:s(()=>cR(n(),t),"value"),enumerable:!1}),e}s(cR,"carry");function sc(e,t){return cR(e,n=>Lde.set(n,t))}s(sc,"tagged");var jde="tenant teardown drains every table explicitly (config/wipe.ts)",Ue={belongsTo:s(e=>sc(e,{kind:"belongsTo"}),"belongsTo"),owns:s(e=>sc(e,{kind:"owns"}),"owns"),holds:s(e=>sc(e,{kind:"holds"}),"holds"),restrict:s((e,t)=>sc(e,t?{kind:"restrict",unindexed:t.unindexed}:{kind:"restrict"}),"restrict"),history:s(e=>sc(e,{kind:"history"}),"history"),tenant:s(e=>sc(e,{kind:"restrict",unindexed:jde}),"tenant"),historyOf:s(e=>cR(e,t=>Mde.add(t)),"historyOf")};var pi={filename:m.string(),mimeType:m.string(),sizeBytes:m.number(),sha256:m.string()},qde=m.object({storageId:m.id("_storage"),filename:pi.filename,mimeType:pi.mimeType,sizeBytes:pi.sizeBytes,sha256:m.optional(pi.sha256)}),vWe=m.object({storageId:qde.fields.storageId,filename:pi.filename,mimeType:m.optional(pi.mimeType),sizeBytes:m.optional(pi.sizeBytes),sha256:m.optional(pi.sha256),url:m.union(m.string(),m.null())});var TWe=m.union(m.literal("de"),m.literal("en")),RWe=m.record(m.string(),m.string()),Vt=m.object({de:m.string(),en:m.string()}),EWe=m.object({value:m.string(),label:Vt,countryCode:m.optional(m.union(m.string(),m.null()))}),_We=m.object({title:Vt,body:Vt,confirmLabel:Vt}),Q4=m.union(m.string(),Vt);function db(e){return Xe.includes(e)}s(db,"isSupportedLocale");var zde=m.object({street:m.string(),hausnr:m.string(),plz:m.string(),ort:m.string(),land:m.string()}),H4=m.object({storageId:m.string(),filename:pi.filename,uploadedAt:m.number()}),OWe=m.union(m.string(),m.number(),m.boolean(),m.null(),zde,H4,m.array(m.string()),m.array(H4)),PWe=m.record(m.string(),m.string()),NWe=m.union(m.object({filterKey:m.string(),optionKeys:m.array(m.string())}),m.object({filterKey:m.string(),text:m.string()}),m.object({filterKey:m.string(),min:m.optional(m.number()),max:m.optional(m.number())}));var Ude=m.object({key:m.string(),label:Vt,type:m.string(),required:m.optional(m.boolean()),options:m.optional(m.array(m.object({value:m.string(),label:Vt}))),defaultValue:m.optional(m.union(m.string(),m.number(),m.boolean(),m.object({itemKey:m.string(),grantKeys:m.array(m.string())}))),priceDate:m.optional(m.string()),processSource:m.optional(m.union(...Gs.map(e=>m.literal(e))))}),uR=m.object({fields:m.array(Ude),localeField:m.optional(m.string())}),UWe=En({officeSession:m.optional(m.object({key:m.string(),userId:Ue.history(m.id("users")),expiresAt:m.number(),baseStorageId:Ue.restrict(m.id("_storage")),baseUpdatedAt:m.number(),status:m.union(m.literal("editing"),m.literal("saving"),m.literal("ready"),m.literal("error")),requestId:m.optional(m.string()),error:m.optional(Vt),draftStorageId:m.optional(Ue.owns(m.id("_storage"))),draftSize:m.optional(m.number()),placeholders:m.optional(m.array(m.string())),signatureAnchorKeys:m.optional(m.array(m.string()))})),tenantId:Ue.tenant(m.id("tenants")),configKey:m.optional(m.string()),name:Q4,icon:m.optional(m.string()),fileNamePattern:m.optional(m.string()),roleId:Ue.restrict(m.id("roles")),storageId:Ue.restrict(m.id("_storage")),filename:m.optional(pi.filename),fileName:m.optional(m.string()),detectedCustomFieldIds:m.array(Ue.restrict(m.id("custom_fields"),{unindexed:"array of fields detected in the template file"})),detectedPlaceholders:m.array(m.string()),signatureAnchorKeys:m.optional(m.array(m.string())),parameters:m.optional(uR),createdAt:m.number(),updatedAt:m.number(),createdByUserId:m.optional(Ue.history(m.id("users"))),updatedByUserId:m.optional(Ue.history(m.id("users")))}).index("by_tenantId",["tenantId"]).index("by_tenantId_and_configKey",["tenantId","configKey"]).index("by_tenantId_and_roleId",["tenantId","roleId"]).index("by_storageId",["storageId"]).index("by_officeSession_draftStorageId",["officeSession.draftStorageId"]).index("by_officeSession_baseStorageId",["officeSession.baseStorageId"]);function cb(e){(!Number.isSafeInteger(e)||e<0)&&ge("INVALID",{de:"Betr\xE4ge m\xFCssen nichtnegative ganze Centbetr\xE4ge sein.",en:"Amounts must be non-negative whole amounts in cents."})}s(cb,"assertMoney");var fR=["month","year","once","unit"];var Kde=s(e=>e!==void 0&&/^[1-9]\d{0,8}$/.test(e),"positiveIntegerText");function is(e,t){return ge("CONFLICT",{de:e,en:t})}s(is,"missing");var X4=s(e=>e!==void 0&&/^\d{4}-\d{2}-\d{2}$/.test(e)&&Number.isFinite(new Date(`${e}T00:00:00Z`).valueOf())&&new Date(`${e}T00:00:00Z`).toISOString().slice(0,10)===e,"isoDate");function e6(e,t,n){return{label:t,kind:"chosen",valueType:"choice",choices:n,resolve(i){let r=i.selections?.[e];return(!r||!n.includes(r))&&is(`Die Auswahl f\xFCr \u201E${t.de}\u201C fehlt oder ist ung\xFCltig.`,`The selection for \u201C${t.en}\u201D is missing or invalid.`),{value:r,explanation:{de:`${t.de}: ${r} (Vertragsauswahl)`,en:`${t.en}: ${r} (contract selection)`}}}}}s(e6,"chosen");function pR(e,t){let n=e.enrollment,i=n?.contextDate??t;return(!n||!n.startDate||n.startDate>i||n.endDate&&n.endDate<i)&&is("F\xFCr dieses Datum fehlt eine eindeutige Einschreibung.","An unambiguous enrollment is missing for this date."),n}s(pR,"enrollment");var Vde={paymentFrequency:e6("paymentFrequency",{de:"Zahlungsweise",en:"Payment frequency"},["monthly","yearly"]),gradeLevel:{label:{de:"Klassenstufe",en:"Grade level"},kind:"derived",valueType:"integer",resolve(e,t){let n=pR(e,t).gradeLevel;return(!Number.isSafeInteger(n)||n<1)&&is("Die Klassenstufe fehlt.","The grade level is missing."),{value:n,explanation:{de:`Klassenstufe ${n} am ${t}`,en:`Grade ${n} on ${t}`}}}},schoolYear:{label:{de:"Schuljahr",en:"School year"},kind:"derived",valueType:"integer",resolve(e,t){let n=pR(e,t).schoolYear;return(!Number.isSafeInteger(n)||n<1)&&is("F\xFCr dieses Datum fehlt ein j\xE4hrlicher Schuljahreslauf.","An annual school-year run is missing for this date."),{value:n,explanation:{de:`Schuljahr ${n}/${n+1}`,en:`School year ${n}/${n+1}`}}}},siblingRank:{label:{de:"Geschwisterrang",en:"Sibling rank"},kind:"derived",valueType:"integer",resolve(e,t){if(e.chosenCriteria?.includes("siblingRank")){let c=e.selections?.siblingRank;return Kde(c)||is("Der im Vertrag gew\xE4hlte Geschwisterrang fehlt oder ist keine ganze Zahl ab 1.","The sibling rank chosen on the contract is missing or not a whole number from 1."),{value:Number(c),explanation:{de:`Geschwisterrang ${c} (im Vertrag gew\xE4hlt)`,en:`Sibling rank ${c} (chosen on the contract)`}}}e.unavailable?.siblingRank&&ge("CONFLICT",e.unavailable.siblingRank);let n=e.siblings?[...new Map(e.siblings.filter(c=>c.eligible).map(c=>[c.partyId,c])).values()]:void 0;(!e.partyId||!n?.some(c=>c.partyId===e.partyId))&&is("F\xFCr dieses Datum fehlt die Sch\xFClerrolle des Kindes.","The child\u2019s Student role is missing for this date."),n.some(c=>!X4(c.firstEnrolledOn)||c.firstEnrolledOn>t)&&is("F\xFCr den Geschwisterrang fehlt ein g\xFCltiger erster Einschreibungsbeginn.","A valid first enrollment start is missing for sibling ranking.");let i=n.find(c=>c.partyId===e.partyId),r=i.firstEnrolledOn,o=n.filter(c=>c.firstEnrolledOn===r);o.length>1&&o.some(c=>!X4(c.birthDate)||c.birthDate>t)&&is("Geschwister wurden am selben Tag erstmals eingeschrieben, und f\xFCr die Reihenfolge fehlt ein g\xFCltiges Geburtsdatum.","Siblings first enrolled on the same day, and a valid birth date is missing to order them.");let a=s(c=>c.birthDate<i.birthDate||c.birthDate===i.birthDate&&c.partyId<i.partyId,"before"),l=n.filter(c=>c.firstEnrolledOn<r).length+o.filter(c=>c!==i&&a(c)).length+1,d=o.length>1?{de:`; gleicher Beginn wie ${o.length-1} Geschwister: \xE4lteste zuerst, bei gleichem Geburtsdatum nach Personen-ID`,en:`; same start as ${o.length-1} sibling${o.length>2?"s":""}: oldest first, then party ID for equal birth dates`}:{de:"",en:""};return{value:l,explanation:{de:`${l}. Kind von ${n.length} berechtigten Kindern am ${t}; erste Einschreibung am ${r}, zuerst eingeschriebene Kinder zuerst${d.de}.`,en:`Child ${l} of ${n.length} eligible children on ${t}; first enrollment on ${r}, first enrolled first${d.en}.`}}}},program:{label:{de:"Programm",en:"Program"},kind:"derived",valueType:"program",resolve(e,t){let n=pR(e,t).programId;return n||is("Das Programm fehlt.","The program is missing."),{value:n,explanation:{de:`Programm der Einschreibung am ${t}`,en:`Enrollment program on ${t}`}}}},admissionFeeTier:e6("admissionFeeTier",{de:"Anmeldegeb\xFChrensatz",en:"Admission fee tier"},["100","75","50"])},Bde=Object.fromEntries(Object.entries(Vde).map(([e,t])=>[e,{...t,matchSchema:{parse(n){return Wde(t,n),n}},matches:Gde}])),JWe=Object.keys(Bde);function Gde(e,t){return"else"in t?!0:"eq"in t?e===t.eq:"in"in t?t.in.includes(e):typeof e=="number"&&(t.gte===void 0||e>=t.gte)&&(t.lte===void 0||e<=t.lte)}s(Gde,"matchesPrice");function Wde(e,t){let n=s(()=>ge("INVALID",{de:"Der Match passt nicht zum Preiskriterium.",en:"The match does not fit the price criterion."}),"fail");if(!t||typeof t!="object"||Array.isArray(t))return n();let i=t,r=Object.keys(i).sort().join();if(r==="else"&&i.else===!0)return;let o=s(a=>e.valueType==="integer"?Number.isSafeInteger(a)&&Number(a)>=1:typeof a=="string"&&a.length>0&&(e.valueType!=="choice"||e.choices.includes(a)),"validValue");if(!(r==="eq"&&o(i.eq))&&!(r==="in"&&Array.isArray(i.in)&&i.in.length>0&&new Set(i.in).size===i.in.length&&i.in.every(o))&&!(e.valueType==="integer"&&["gte","lte","gte,lte"].includes(r)&&Object.values(i).every(a=>Number.isSafeInteger(a)&&Number(a)>=1)&&(i.gte===void 0||i.lte===void 0||Number(i.gte)<=Number(i.lte))))return n()}s(Wde,"validateMatch");function t6(e,t){if(Object.keys(t).some(n=>!["percent","amountMinor"].includes(n))&&ge("INVALID",{de:"Die Erm\xE4\xDFigung braucht genau eine Prozentregel oder einen Centbetrag.",en:"The reduction needs exactly one percentage rule or one amount in cents."}),e==="percent"&&"percent"in t&&!("amountMinor"in t)){(!Number.isFinite(t.percent)||t.percent<0||t.percent>100)&&ge("INVALID",{de:"Prozentwerte m\xFCssen zwischen 0 und 100 liegen.",en:"Percentages must be between 0 and 100."});return}if(e==="absolute"&&"amountMinor"in t&&!("percent"in t))return cb(t.amountMinor);ge("INVALID",{de:"Die Erm\xE4\xDFigung braucht genau eine Prozentregel oder einen Centbetrag.",en:"The reduction needs exactly one percentage rule or one amount in cents."})}s(t6,"validateRule");var Zde=/^[a-z][a-z0-9_-]{0,63}$/;function n6(e){return Zde.test(e)}s(n6,"isTemplateConfigKey");import{createHash as ece}from"node:crypto";import{inflateRawSync as tce}from"node:zlib";var r6=/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/,Jde=/{{\s*([^{}]+?)\s*}}|<<\s*([^<>]+?)\s*>>/g,Yde=/^[#/]\s*/;function Hde(e){let t=e.trim(),n=t.match(/^{{\s*([^{}]+?)\s*}}$/);if(n)return n[1]?.trim()??t;let i=t.match(/^<<\s*([^<>]+?)\s*>>$/);return i?i[1]?.trim()??t:t}s(Hde,"innerTemplatePlaceholder");function ub(e){return Hde(e).replace(Yde,"")}s(ub,"normalizeTemplatePlaceholderKey");function fb(e){return ub(e).toLowerCase()}s(fb,"canonicalTemplatePlaceholderKey");function i6(e){let t=new Map;for(let n of Qde(e))t.has(n.key)||t.set(n.key,n.placeholder);return Array.from(t.entries()).sort(([n],[i])=>n.localeCompare(i,"de")).map(([,n])=>n)}s(i6,"extractTemplatePlaceholders");function Qde(e){let t=[];for(let n of e.matchAll(Jde)){let i=ub(n[1]??n[2]??"");i&&t.push({key:fb(i),placeholder:n[0].trim()})}return t}s(Qde,"extractTemplatePlaceholderOccurrences");var o6=/^word\/(document|header\d+|footer\d+|footnotes|endnotes)\.xml$/;function Xde(e){return e.replace(/<[^>]+>/g,"").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&#(\d+);/g,(t,n)=>String.fromCodePoint(Number(n))).replace(/&#x([0-9a-f]+);/gi,(t,n)=>String.fromCodePoint(parseInt(n,16))).replace(/&amp;/g,"&")}s(Xde,"templateXmlText");function s6(e){return e.map(Xde).join(`
11854
11854
  `)}s(s6,"templateTextFromParts");var nce="application/vnd.openxmlformats-officedocument.wordprocessingml.document";async function zf(e){let t=ee.resolve(e);if(!t.toLowerCase().endsWith(".docx"))throw new w("Word templates must be a .docx file.");let n=new Uint8Array(await yg(t));return{file:t,bytes:n,sha256:ece("sha256").update(n).digest("base64"),placeholders:i6(rce(n)).map(ub)}}s(zf,"readLocalDocx");async function pb(e,t,n,i){let r=await e.query(A.templates.roleOptions,{client:t}),o=r.find(d=>d.key===i.role);if(o===void 0)throw new w(`Unknown leaf role "${i.role}". Available: ${r.map(d=>d.key).join(", ")}`);let a=await l6(e,t,n),{templateId:l}=await e.action(A.templateFileActions.create,{client:t,name:i.name,roleId:o.id,storageId:a,filename:ee.basename(n.file),...i.configKey===void 0?{}:{configKey:i.configKey},...i.icon===void 0?{}:{icon:i.icon},...i.fileNamePattern===void 0?{}:{fileNamePattern:i.fileNamePattern}});return l}s(pb,"uploadDocumentTemplate");async function a6(e,t,n,i){let r=await l6(e,t,i);await e.action(A.templateFileActions.replaceFile,{client:t,templateId:n,storageId:r,filename:ee.basename(i.file)})}s(a6,"replaceDocumentTemplateFile");async function l6(e,t,n){let{uploadUrl:i,uploadTicket:r}=await e.mutation(A.templates.generateUploadUrl,{client:t}),o=await e.upload(i,n.bytes,nce);return await e.mutation(A.uploads.registerUpload,{uploadTicket:r,storageId:o}),o}s(l6,"stageDocx");function rce(e){let t=ice(e,n=>o6.test(n));if(!t.has("word/document.xml"))throw new w("word/document.xml not found \u2014 the file is not a readable .docx.");return s6([...t.values()])}s(rce,"docxPlaceholderText");function ice(e,t){let n=new DataView(e.buffer,e.byteOffset,e.byteLength),i=new w("No ZIP central directory \u2014 the file is not a readable .docx."),r=-1;for(let d=e.length-22;d>=Math.max(0,e.length-22-65535);d--)if(n.getUint32(d,!0)===101010256){r=d;break}if(r<0)throw i;let o=n.getUint16(r+10,!0),a=n.getUint32(r+16,!0),l=new Map;for(let d=0;d<o;d++){if(a+46>e.length||n.getUint32(a,!0)!==33639248)throw i;let c=n.getUint16(a+10,!0),u=n.getUint32(a+20,!0),f=n.getUint16(a+28,!0),h=n.getUint16(a+30,!0),g=n.getUint16(a+32,!0),b=n.getUint32(a+42,!0),y=new TextDecoder().decode(e.subarray(a+46,a+46+f));if(a+=46+f+h+g,!t(y))continue;if(n.getUint32(b,!0)!==67324752)throw i;let v=b+30+n.getUint16(b+26,!0)+n.getUint16(b+28,!0),S=Buffer.from(e.subarray(v,v+u));l.set(y,(c===0?S:tce(S)).toString("utf8"))}return l}s(ice,"readZipEntries");function pn(e,t,n){if(typeof e!="object"||e===null||Array.isArray(e))throw new w(`${n}: ${t} muss ein Objekt sein.`);return e}s(pn,"record");function ut(e,t,n){if(typeof e!="string"||e.trim().length===0)throw new w(`${n}: ${t} fehlt.`);return e.trim()}s(ut,"text");function rr(e,t,n,i){let r=sn(e);if(r==="not-localized"){let a=typeof e=="string"&&e.trim()!==""?e.trim():"\u2026";throw new w(`${n}: ${t}: erwartet { "de": "\u2026", "en": "\u2026" } (${i} sind zweisprachig) \u2014 z. B. "name": ${JSON.stringify({de:a,en:"\u2026"})}`)}if(r.length>0)throw new w(`${n}: ${t}.${r.join(` und ${t}.`)} ${r.length>1?"fehlen":"fehlt"} (${i} sind zweisprachig; kein R\xFCckfall auf Deutsch).`);let o=e;return{de:o.de.trim(),en:o.en.trim()}}s(rr,"localizedName");function Kr(e,t,n){if(!Array.isArray(e))throw new w(`${n}: ${t} muss eine Liste sein.`);return e}s(Kr,"list");function mb(e,t){return Kr(e,"revenueAccounts",t).map((n,i)=>{let r=pn(n,`revenueAccounts[${i}]`,t);return{code:ut(r.code,`revenueAccounts[${i}].code`,t),name:ut(r.name,`revenueAccounts[${i}].name`,t)}})}s(mb,"parseRevenueAccounts");function hb(e,t){return Kr(e,"billingItems",t).map((n,i)=>{let r=`billingItems[${i}]`,o=pn(n,r,t),a=ut(o.itemType,`${r}.itemType`,t),l=ut(o.taxTreatment,`${r}.taxTreatment`,t);if(l!=="exempt_ustg_4_nr_21"&&l!=="vat_19"&&l!=="vat_7")throw new w(`${t}: ${r}.taxTreatment ist unbekannt.`);if(a!=="recurring"&&a!=="one_time"&&a!=="usage")throw new w(`${t}: ${r}.itemType "${a}" ist unbekannt.`);if(o.minAmount!==void 0)throw new w(`${t}: ${r}.minAmount wird nicht mehr unterst\xFCtzt; eine Vertragserm\xE4\xDFigung mit Untergrenze verwenden.`);let d=pn(o.price,`${r}.price`,t),c=d.effectiveFrom===void 0?{}:{effectiveFrom:ut(d.effectiveFrom,`${r}.price.effectiveFrom`,t)},u=ut(d.currency,`${r}.price.currency`,t),f=d.tree===void 0?(()=>{let h=ut(d.period,`${r}.price.period`,t);if(!["month","year","once","unit"].includes(h))throw new w(`${t}: ${r}.price.period ist unbekannt.`);return{currency:u,amount:d.amount,period:h,...c}})():(()=>{if(d.amount!==void 0||d.period!==void 0)throw new w(`${t}: ${r}.price: tree wird nicht mit amount oder period kombiniert.`);return{currency:u,tree:pn(d.tree,`${r}.price.tree`,t),...c}})();return{key:ut(o.key,`${r}.key`,t),name:rr(o.name,`${r}.name`,t,"Artikelnamen"),itemType:a,revenueAccount:ut(o.revenueAccount,`${r}.revenueAccount`,t),taxTreatment:l,config:pn(o.config??{},`${r}.config`,t),...o.programs===void 0?{}:{programs:Kr(o.programs,`${r}.programs`,t).map((h,g)=>ut(h,`${r}.programs[${g}]`,t))},price:f}})}s(hb,"parseBillingItems");var Me="catalog",oce=["sibling","stipend","promo","needsBased","singleParent"],sce=["percent","absolute"];function mR(e,t){let n=new Set;for(let i of e){if(n.has(i))throw new w(`${Me}: ${t}: Schl\xFCssel "${i}" steht zweimal in der Datei.`);n.add(i)}}s(mR,"uniqueKeys");function gb(e,t,n){if(!t.includes(e))throw new w(`${Me}: ${n} "${e}" ist unbekannt (${t.join(", ")}).`);return e}s(gb,"oneOf");function ace(e,t){let n=pn(e,"Datei",Me);if(n.plans!==void 0)throw new w("catalog: plans wurden entfernt. Geb\xFChrengruppen geh\xF6ren in die Generatorrevision; Programmzuordnungen unter billingItems[].programs angeben.");let i=["revenueAccounts","billingItems","grantTemplates","documentTemplates"],r=Object.keys(n).filter(c=>!i.includes(c));if(r.length>0)throw new w(`${Me}: unbekannte Abschnitte ${r.join(", ")} (erlaubt: ${i.join(", ")}).`);let o=hb(n.billingItems??[],Me).map((c,u)=>{let f=`billingItems[${u}].price`;if(!("tree"in c.price)&&(typeof c.price.amount!="number"||!Number.isFinite(c.price.amount)))throw new w(`${Me}: ${f}.amount muss eine Zahl sein (${JSON.stringify("amount"in c.price?c.price.amount:null)}).`);if(c.price.effectiveFrom===void 0)throw new w(`${Me}: ${f}.effectiveFrom fehlt \u2014 der erste Tag, ab dem der Preis gilt (YYYY-MM-DD).`);return{...c,price:"tree"in c.price?{currency:c.price.currency,tree:c.price.tree,effectiveFrom:c.price.effectiveFrom}:{currency:c.price.currency,amount:c.price.amount,effectiveFrom:c.price.effectiveFrom,period:c.price.period}}}),a=Kr(n.grantTemplates??[],"grantTemplates",Me).map((c,u)=>{let f=`grantTemplates[${u}]`,h=pn(c,f,Me);if(h.item!==void 0||h.plan!==void 0||h.value!==void 0)throw new w(`${Me}: ${f}: eligibleItems, scope und rule statt item/plan/value verwenden.`);if(typeof h.retroactiveRevocation!="boolean")throw new w(`${Me}: ${f}.retroactiveRevocation muss true oder false sein.`);let g=gb(ut(h.scope,`${f}.scope`,Me),["line","aggregate"],`${f}.scope`),b=gb(ut(h.kind,`${f}.kind`,Me),sce,`${f}.kind`),y=pn(h.rule,`${f}.rule`,Me);t6(b,y);let v=gb(ut(h.pricePeriod,`${f}.pricePeriod`,Me),["month","year","once","unit"],`${f}.pricePeriod`);if(h.floorTotal!==void 0){if(typeof h.floorTotal!="number"||g!=="aggregate")throw new w(`${Me}: ${f}.floorTotal geh\xF6rt zu einer Aggregaterm\xE4\xDFigung.`);cb(h.floorTotal)}let S=Kr(h.eligibleItems,`${f}.eligibleItems`,Me).map((x,_)=>ut(x,`${f}.eligibleItems[${_}]`,Me));if(S.length===0||new Set(S).size!==S.length)throw new w(`${Me}: ${f}.eligibleItems braucht eindeutige Artikel.`);return{key:ut(h.key,`${f}.key`,Me),name:rr(h.name,`${f}.name`,Me,"Erm\xE4\xDFigungsnamen"),eligibleItems:S,scope:g,rule:y,pricePeriod:v,...h.floorTotal===void 0?{}:{floorTotal:h.floorTotal},...h.offeredFrom===void 0?{}:{offeredFrom:ut(h.offeredFrom,`${f}.offeredFrom`,Me)},...h.offeredUntil===void 0?{}:{offeredUntil:ut(h.offeredUntil,`${f}.offeredUntil`,Me)},reason:gb(ut(h.reason,`${f}.reason`,Me),oce,`${f}.reason`),kind:b,eligibility:pn(h.eligibility,`${f}.eligibility`,Me),retroactiveRevocation:h.retroactiveRevocation}}),l=Kr(n.documentTemplates??[],"documentTemplates",Me).map((c,u)=>{let f=`documentTemplates[${u}]`,h=pn(c,f,Me),g=ut(h.key,`${f}.key`,Me);if(!n6(g))throw new w(`${Me}: ${f}.key "${g}" ist kein g\xFCltiger Vorlagen-Schl\xFCssel (Kleinbuchstaben, Ziffern, - und _, beginnend mit einem Buchstaben).`);let b=ee.resolve(t,ut(h.file,`${f}.file`,Me));if(!b.toLowerCase().endsWith(".docx"))throw new w(`${Me}: ${f}.file muss eine .docx sein.`);return{key:g,name:rr(h.name,`${f}.name`,Me,"Vorlagennamen"),file:b,role:ut(h.role,`${f}.role`,Me),...h.icon===void 0?{}:{icon:ut(h.icon,`${f}.icon`,Me)},...h.fileNamePattern===void 0?{}:{fileNamePattern:ut(h.fileNamePattern,`${f}.fileNamePattern`,Me)},...h.parameters===void 0?{}:{parameters:h.parameters===null?null:lce(h.parameters,`${f}.parameters`)}}});mR(o.map(c=>c.key),"billingItems"),mR(a.map(c=>c.key),"grantTemplates");for(let[c,u]of o.entries()){if(u.programs===void 0)throw new w(`${Me}: billingItems[${c}] (${u.key}) geh\xF6rt keinem Programm \u2014 "programs" nennen (die Programm-Schl\xFCssel, die den Artikel einzeln verkaufen; [] f\xFCr einen stillgelegten Artikel) oder den Artikel in ein Paket aufnehmen.`);if(u.programs!==void 0&&new Set(u.programs).size!==u.programs.length)throw new w(`${Me}: billingItems[${c}].programs: ein Programm steht zweimal.`)}mR(l.map(c=>c.key),"documentTemplates");let d=mb(n.revenueAccounts??[],Me);if(d.length+o.length+a.length+l.length===0)throw new w(`${Me}: die Datei deklariert nichts (${i.join(", ")}).`);return{revenueAccounts:d,billingItems:o,grantTemplates:a,documentTemplates:l}}s(ace,"parseCatalog");function hR(e){let t=ee.resolve(e);if(!Fe(t))throw new w(`${Me}: ${t} gibt es nicht.`);return ace(at(t,Me),ee.dirname(t))}s(hR,"readCatalog");function lce(e,t){let n=pn(e,t,Me);if(Kr(n.fields,`${t}.fields`,Me),!rs(uR,n))throw new w(`${Me}: ${t} is not a valid template parameter schema.`);return{...n,fields:n.fields.map(i=>{if(!si(i.type))throw new w(`${Me}: ${t}.${i.key}: unknown value type ${i.type}.`);return{...i,type:i.type}})}}s(lce,"declaredParameters");function dce(e){return{revenueAccounts:e.revenueAccounts,billingItems:e.billingItems.map(t=>({key:t.key,name:t.name,itemType:t.itemType,revenueAccountCode:t.revenueAccount,taxTreatment:t.taxTreatment,config:t.config,price:t.price,programs:t.programs}))}}s(dce,"billingArgs");function cce(e){return{articlePrograms:e.billingItems.map(t=>({item:t.key,programs:t.programs??[]}))}}s(cce,"planArgs");async function gR(e,t,n,i=zf){let r=[],o=[],a=null;if(n.billingItems.length>0||n.revenueAccounts.length>0){a=dce(n);let u=await e.query(A.contractSetup.planBillingSetup,{client:t,...a});for(let f of u.rows)r.push({step:f.kind,target:f.key,action:f.action,detail:f.detail}),f.kind==="billingItem"&&f.action==="create"&&o.push(f.key)}let l=null;if(n.billingItems.length>0){l=cce(n);let u=await e.query(A.catalogPrograms.planProgramSetup,{client:t,...l,pendingItems:o});for(let f of u.rows)r.push({step:f.kind,target:f.key,action:f.action,detail:f.detail?.de??""});for(let f of n.billingItems)f.programs?.length===0&&r.push({step:"billingItemProgram",target:f.key,action:"none",detail:"kein Programm verkauft den Artikel (stillgelegt?) \u2014 Finanzen zeigt \u201EKein Programm\u201C"})}let d=null;if(n.grantTemplates.length>0){d={grantTemplates:n.grantTemplates};let u=await e.query(A.contractSetup.planGrantSetup,{client:t,grantTemplates:n.grantTemplates,pendingItems:o});for(let f of u.rows)r.push({step:"grantTemplate",target:f.key,action:f.action,detail:f.detail})}let c=[];if(n.documentTemplates.length>0){let u=await e.query(A.templates.roleOptions,{client:t});for(let f of n.documentTemplates){let h=u.find(_=>_.key===f.role);if(h===void 0)throw new w(`${Me}: Vorlage ${f.key}: Rolle "${f.role}" ist keine Blatt-Rolle dieses Mandanten (${u.map(_=>_.key).join(", ")}).`);let g=await i(f.file),b=await e.query(A.templates.stateByConfigKey,{client:t,configKey:f.key});if(b!==null&&b.roleKey!==f.role)throw new w(`${Me}: Vorlage ${f.key} geh\xF6rt zur Rolle "${b.roleKey}", die Datei nennt "${f.role}" \u2014 die Rolle einer bestehenden Vorlage \xE4ndert catalog nicht (Vorlagenverwaltung).`);let y=b===null||b.sha256!==g.sha256,v=f.parameters!==void 0&&Ge(f.parameters)!==Ge(b?.parameters??null),S=[];b!==null&&(cd(b.name,f.name)||S.push(`Name ${b.name.de} / ${b.name.en||"\u2014"} \u2192 ${f.name.de} / ${f.name.en}`),f.icon!==void 0&&b.icon!==f.icon&&S.push(`Icon \u2192 ${f.icon}`),f.fileNamePattern!==void 0&&b.fileNamePattern!==f.fileNamePattern&&S.push("Dateinamensmuster")),c.push({declared:f,docx:g,roleId:h.id,state:b,upload:y,metadata:S,parametersChange:v});let x=v?[f.parameters===null?"Parameter entfernen":`Parameter (${f.parameters.fields.length} Felder)`]:[];r.push({step:"documentTemplate",target:f.key,action:b===null?"create":y||S.length>0||v?"update":"same",detail:b===null?[`${f.name.de} \xB7 ${ee.basename(f.file)}`,...x].join(", "):[...y?[`Datei ersetzen (${ee.basename(f.file)})`]:[],...S,...x].join(", ")})}}return{rows:r,billing:a,programs:l,grants:d,templates:c}}s(gR,"planCatalog");async function d6(e,t,n,i=zf){let r=await gR(e,t,n,i),o=[];if(r.billing!==null){let a=await e.mutation(A.contractSetup.applyBillingSetup,{client:t,...r.billing});for(let l of a.rows)o.push({step:l.kind,target:l.key,action:l.action,detail:l.detail})}if(r.programs!==null){let a=await e.mutation(A.catalogPrograms.applyProgramSetup,{client:t,...r.programs});for(let l of a.rows)o.push({step:l.kind,target:l.key,action:l.action,detail:l.detail?.de??""})}if(r.grants!==null){let a=await e.mutation(A.contractSetup.applyGrantSetup,{client:t,grantTemplates:r.grants.grantTemplates});for(let l of a.rows)o.push({step:"grantTemplate",target:l.key,action:l.action,detail:l.detail})}for(let a of r.templates){let{declared:l,state:d}=a;if(d===null)await pb(e,t,a.docx,{name:l.name,role:l.role,configKey:l.key,...l.icon===void 0?{}:{icon:l.icon},...l.fileNamePattern===void 0?{}:{fileNamePattern:l.fileNamePattern}});else if(a.upload&&await a6(e,t,d.templateId,a.docx),a.metadata.length>0){let c=l.icon??d.icon,u=l.fileNamePattern??d.fileNamePattern;await e.mutation(A.templates.updateMetadata,{client:t,templateId:d.templateId,name:l.name,roleId:a.roleId,configKey:l.key,...c===null?{}:{icon:c},...u===null?{}:{fileNamePattern:u}})}a.parametersChange&&await e.mutation(A.templates.setParameters,{client:t,configKey:l.key,parameters:l.parameters??null}),o.push(r.rows.find(c=>c.step==="documentTemplate"&&c.target===l.key))}return o}s(d6,"applyCatalog");async function c6(e,t){let{unkeyed:n,...i}=await e.query(A.catalogExport.exportCatalog,{client:t});return{file:{revenueAccounts:i.revenueAccounts,billingItems:i.billingItems,grantTemplates:i.grantTemplates},unkeyed:n}}s(c6,"exportCatalog");var u6={required:!0,description:"catalog.json (revenueAccounts, billingItems with their programs, grantTemplates, documentTemplates)"},f6=["step","target","action","detail"],yR=class extends F{static{s(this,"CatalogPlanCommand")}file=p.String("--file",u6);static paths=[["catalog","plan"]];static usage=E.Usage({category:"Contracts",description:"Read-only: what `catalog apply` would write (revenue accounts, articles, price versions, program assignments, packages, tiers, Word templates)."});async execute(){let t=await this.caller(),n=await gR(t,this.requireTenant(t),hR(this.file));return this.print(n.rows,i=>i,f6),0}},wR=class extends F{static{s(this,"CatalogApplyCommand")}file=p.String("--file",u6);static paths=[["catalog","apply"]];static usage=E.Usage({category:"Contracts",description:"Bring a catalog file onto the environment by stable key; a Word file is uploaded only when its SHA-256 differs. Idempotent."});async execute(){let t=await this.caller();return this.print(await d6(t,this.requireTenant(t),hR(this.file)),n=>n,f6),0}},bR=class extends F{static{s(this,"CatalogExportCommand")}out=p.String("--out",{required:!0,description:"catalog.json to write (refused when it exists, unless --force)"});force=Kt();static paths=[["catalog","export"]];static usage=E.Usage({category:"Contracts",description:"Read-only: write the tenant's catalog (revenue accounts, articles with price, floor and programs, packages, grant templates) as catalog.json \u2014 `catalog plan` on it reports `same` everywhere. Word templates are not exported."});async execute(){let t=fn(this.out,this.force),n=await this.caller(),{file:i,unkeyed:r}=await c6(n,this.requireTenant(n));ft(t,`${JSON.stringify(i,null,2)}
11855
11855
  `);let o=Object.entries(r).filter(([,a])=>a>0).map(([a,l])=>`${l} ${a}`);return this.context.stdout.write(`${this.out}: ${i.billingItems.length} Artikel, ${i.grantTemplates.length} Rabattvorlagen`+(o.length===0?`
11856
11856
  `:` \u2014 ohne Schl\xFCssel nicht exportiert: ${o.join(", ")}
@@ -12173,7 +12173,7 @@ ${n.length} unusable ${o}:
12173
12173
  `),i.length>0&&this.context.stdout.write(` ${i.length} linkable \u2014 plexus-cli platform users relink-auth <email>
12174
12174
  `),r.length>0&&this.context.stdout.write(` ${r.length} without any login account \u2014 plexus-cli platform users provision --tenant <slug> --email <email> --name <name>
12175
12175
  `)}else this.context.stdout.write(`No unusable identities.
12176
- `);return n.length>0?1:0}},Oq=class extends $i{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=E.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(A.platformAdmin.relinkAuthAccount,{email:this.email}),i=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,i),0}};function lee(e,t){if(e===t)throw new w("Pass exactly one of --on or --off.");return e}s(lee,"requireOnOff");var dee=[mq,hq,gq,yq,wq,bq,kq,vq,xq,Sq,fg,$q,Aq,Iq,Tq,Rq,Eq,_q,Oq];function cee(e){return e.de??e.en??Object.values(e)[0]??""}s(cee,"titleDe");function ySe(e){return{id:e._id,kind:e.kind,status:e.status,title:cee(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(ySe,"row");var wSe=["id","kind","status","title","assignee","group","outcome"],Cq=class extends F{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=E.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),i=await t.query(A.workItems.list,{client:n,...this.mine?{mine:!0}:{},...this.application?{applicationId:se(this.application,"application")}:{},...this.group?{queueGroupId:se(this.group,"permission group")}:{},...this.assignee?{assigneeUserId:se(this.assignee,"user")}:{},...this.openOnly?{openOnly:!0}:{}});return this.print(i,r=>r.map(ySe),wSe),0}},Dq=class extends F{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=E.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),i=await t.query(A.workItems.get,{client:n,workItemId:se(this.workItemId,"work item")});if(i===null)throw new w(`work-item ${this.workItemId} not found in tenant ${n}.`);return this.print(i,r=>[{field:"id",value:r._id},{field:"kind",value:r.kind},{field:"status",value:r.status},{field:"title",value:cee(r.title)},{field:"assignee",value:r.assigneeUserId??""},{field:"group",value:r.queueGroupId??""},{field:"application",value:r.applicationId??""},{field:"node",value:r.nodeId??""},{field:"outcome",value:r.outcome??""}]),0}},Fq=class extends F{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=E.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),i=await t.mutation(A.workItems.createManual,{client:n,title:this.title,...this.description?{description:this.description}:{},...this.application?{applicationId:se(this.application,"application")}:{},...this.group?{queueGroupId:se(this.group,"permission group")}:{},...this.assignee?{assigneeUserId:se(this.assignee,"user")}:{}});return this.print({workItemId:i.workItemId},r=>[{field:"workItemId",value:r.workItemId}]),0}},Lq=class extends F{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=E.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),i=await t.mutation(A.workItems.complete,{client:n,workItemId:se(this.workItemId,"work item"),...this.outcome?{outcome:this.outcome}:{}});return this.print({workItemId:i.workItemId,status:"done"},r=>[{field:"workItemId",value:r.workItemId},{field:"status",value:r.status}]),0}},Mq=class extends F{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=E.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),i=await t.mutation(A.workItems.assign,{client:n,workItemId:se(this.workItemId,"work item"),...this.user?{userId:se(this.user,"user")}:{}});return this.print({workItemId:i.workItemId,assignee:this.user??"(cleared)"},r=>[{field:"workItemId",value:r.workItemId},{field:"assignee",value:r.assignee}]),0}},uee=[Cq,Dq,Fq,Lq,Mq];var bu=[...NK,...p6,...x6,...OZ,...DZ,..._Z,...aJ,...mJ,...pJ,...see,...dee,...oee,...qX,...GX,...HX,...Z4,...rJ,...W7,..._K,...dV,...N4,...yJ,...gJ,...kJ,...SJ,...tJ,...zZ,...uee,...H9,...qQ,...MX,...zQ,...O7,...M7,...QX,...a7,...c7,...m7,...g7,...z7,...Q7,...XK];for(let e of bu){let t=e.paths?.[0];t===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:Gz(e.usage.category,t.join(" "))})}var fee="0.1.377";function jq(){return bu.flatMap(e=>(e.paths??[]).map(t=>{let n=t.join(" "),i=Uz[Ia(n)];return{path:n,effect:No(n),host:i===void 0?"shared":"terminal",...i===void 0?{}:{reason:i}}})).sort((e,t)=>e.path.localeCompare(t.path))}s(jq,"plexusCommandCatalog");import Bl from"node:path";function bSe(e){let t=Dt()?.workspaceRoot??process.cwd(),n=Bl.resolve(t,e),i=Bl.relative(t,n);if(Bl.isAbsolute(e)||i===".."||i.startsWith(`..${Bl.sep}`))throw new w("plexus: use a relative path inside the current workspace.");return{absolute:n,relative:i}}s(bSe,"workspacePath");function kSe(e){let{absolute:t,relative:n}=bSe(e.path??".");if(e.operation==="list"){if(!Fe(t))return{files:[]};let i=[],r=s(o=>{for(let a of Ji(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new w("plexus: workspace symlinks are not supported.");let l=Bl.join(o,a.name);if(a.isDirectory()?r(l):i.push(Bl.relative(t,l)),i.length>200)throw new w("plexus: the workspace contains too many files. List a subdirectory.")}},"visit");return r(t),{files:i.sort()}}if(!n)throw new w("plexus: name a workspace file.");if(["read","search","edit"].includes(e.operation)){let i=Be(t);if(i.length>10*1024*1024)throw new w("plexus: the workspace file exceeds 10 MB.");let r=new TextDecoder("utf-8",{fatal:!0}).decode(i);if(e.operation==="read"){let l=e.offset??0,d=e.maxChars??8e3,c=r.slice(l,l+d);return{path:n,content:c,...l||c.length<r.length?{offset:l,nextOffset:l+c.length<r.length?l+c.length:null,totalCharacters:r.length}:{}}}if(e.operation==="search"){if(!e.query)throw new w("plexus: search needs a nonempty query.");let l=[],d=e.offset??0;for(;l.length<10;){let c=r.indexOf(e.query,d);if(c<0)break;l.push({offset:c,text:r.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 w("plexus: edit needs oldText and replacement content.");let o=r.indexOf(e.oldText);if(o<0||o!==r.lastIndexOf(e.oldText))throw new w("plexus: oldText must match exactly once. Read the current file and choose unique context.");let a=r.slice(0,o)+e.content+r.slice(o+e.oldText.length);if(Buffer.byteLength(a)>10*1024*1024)throw new w("plexus: the edited file exceeds 10 MB.");return ft(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 w("plexus: file content is missing or too large.");return bn(Bl.dirname(t),{recursive:!0}),ft(t,e.content,"utf8"),{path:n,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return Jl(t),{path:n,removed:!0};throw new w("plexus: unknown workspace operation.")}s(kSe,"plexusWorkspace");function pee(e){return s(async function(n,i){if(!i||typeof i!="object"||Array.isArray(i))throw new w("plexus: tool input must be an object.");let r=i,o=Xu[n];if(!o||!Object.hasOwn(Xu,n))throw new w("plexus: unknown agent tool.");if(Object.keys(r).some(a=>!Object.hasOwn(o.inputSchema.properties,a)))throw new w("plexus: unexpected tool argument.");if(n==="plexus"){if(!Array.isArray(r.argv)||r.argv.some(a=>typeof a!="string")||r.stdin!==void 0&&typeof r.stdin!="string")throw new w("plexus: invalid command input.");return e.inspectCommand(r.argv),e.executeCommand({argv:r.argv,...r.stdin===void 0?{}:{stdin:r.stdin}})}if(n==="plexus_skill"){if(typeof r.path!="string"||r.path.length>240||!Object.hasOwn(hA,r.path))throw new w("plexus: unknown skill reference. Start with SKILL.md.");return{path:r.path,content:hA[r.path],skillHash:Sy}}if(typeof r.operation!="string"||!["list","read","search","edit","write","remove"].includes(r.operation)||r.path!==void 0&&(typeof r.path!="string"||r.path.length>500)||r.content!==void 0&&(typeof r.content!="string"||r.content.length>1e6)||r.oldText!==void 0&&(typeof r.oldText!="string"||r.oldText.length>1e6)||r.query!==void 0&&(typeof r.query!="string"||!r.query.length||r.query.length>1e3)||r.offset!==void 0&&(typeof r.offset!="number"||!Number.isSafeInteger(r.offset)||r.offset<0)||r.maxChars!==void 0&&(typeof r.maxChars!="number"||!Number.isSafeInteger(r.maxChars)||r.maxChars<1||r.maxChars>24e3))throw new w("plexus: invalid workspace input.");return kSe(r)},"executePlexusAgentTool")}s(pee,"createPlexusAgentToolExecutor");var vSe=["--env","--tenant"];function mee(e){let t=[],n=[];for(let i=0;i<e.length;i++){let r=e[i];if(r==="--"){t.push(...e.slice(i));break}let o=vSe.find(l=>r===l||r.startsWith(`${l}=`)),a=e[i+1];o===void 0?t.push(r):r!==o?n.push({name:o,value:r.slice(o.length+1)}):a!==void 0&&!a.startsWith("-")?(n.push({name:o,value:a}),i++):t.push(r)}return{rest:t,given:n}}s(mee,"splitGlobalOptions");function hee(e,t){let n=R$(e)==="offline";if(n&&No(e)==="read")return t.map(r=>`plexus-cli: ${r.name} ${r.value} has no effect: \`${e}\` runs offline (this CLI's own files, no deployment).
12176
+ `);return n.length>0?1:0}},Oq=class extends $i{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=E.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(A.platformAdmin.relinkAuthAccount,{email:this.email}),i=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,i),0}};function lee(e,t){if(e===t)throw new w("Pass exactly one of --on or --off.");return e}s(lee,"requireOnOff");var dee=[mq,hq,gq,yq,wq,bq,kq,vq,xq,Sq,fg,$q,Aq,Iq,Tq,Rq,Eq,_q,Oq];function cee(e){return e.de??e.en??Object.values(e)[0]??""}s(cee,"titleDe");function ySe(e){return{id:e._id,kind:e.kind,status:e.status,title:cee(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(ySe,"row");var wSe=["id","kind","status","title","assignee","group","outcome"],Cq=class extends F{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=E.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),i=await t.query(A.workItems.list,{client:n,...this.mine?{mine:!0}:{},...this.application?{applicationId:se(this.application,"application")}:{},...this.group?{queueGroupId:se(this.group,"permission group")}:{},...this.assignee?{assigneeUserId:se(this.assignee,"user")}:{},...this.openOnly?{openOnly:!0}:{}});return this.print(i,r=>r.map(ySe),wSe),0}},Dq=class extends F{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=E.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),i=await t.query(A.workItems.get,{client:n,workItemId:se(this.workItemId,"work item")});if(i===null)throw new w(`work-item ${this.workItemId} not found in tenant ${n}.`);return this.print(i,r=>[{field:"id",value:r._id},{field:"kind",value:r.kind},{field:"status",value:r.status},{field:"title",value:cee(r.title)},{field:"assignee",value:r.assigneeUserId??""},{field:"group",value:r.queueGroupId??""},{field:"application",value:r.applicationId??""},{field:"node",value:r.nodeId??""},{field:"outcome",value:r.outcome??""}]),0}},Fq=class extends F{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=E.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),i=await t.mutation(A.workItems.createManual,{client:n,title:this.title,...this.description?{description:this.description}:{},...this.application?{applicationId:se(this.application,"application")}:{},...this.group?{queueGroupId:se(this.group,"permission group")}:{},...this.assignee?{assigneeUserId:se(this.assignee,"user")}:{}});return this.print({workItemId:i.workItemId},r=>[{field:"workItemId",value:r.workItemId}]),0}},Lq=class extends F{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=E.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),i=await t.mutation(A.workItems.complete,{client:n,workItemId:se(this.workItemId,"work item"),...this.outcome?{outcome:this.outcome}:{}});return this.print({workItemId:i.workItemId,status:"done"},r=>[{field:"workItemId",value:r.workItemId},{field:"status",value:r.status}]),0}},Mq=class extends F{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=E.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),i=await t.mutation(A.workItems.assign,{client:n,workItemId:se(this.workItemId,"work item"),...this.user?{userId:se(this.user,"user")}:{}});return this.print({workItemId:i.workItemId,assignee:this.user??"(cleared)"},r=>[{field:"workItemId",value:r.workItemId},{field:"assignee",value:r.assignee}]),0}},uee=[Cq,Dq,Fq,Lq,Mq];var bu=[...NK,...p6,...x6,...OZ,...DZ,..._Z,...aJ,...mJ,...pJ,...see,...dee,...oee,...qX,...GX,...HX,...Z4,...rJ,...W7,..._K,...dV,...N4,...yJ,...gJ,...kJ,...SJ,...tJ,...zZ,...uee,...H9,...qQ,...MX,...zQ,...O7,...M7,...QX,...a7,...c7,...m7,...g7,...z7,...Q7,...XK];for(let e of bu){let t=e.paths?.[0];t===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:Gz(e.usage.category,t.join(" "))})}var fee="0.1.379";function jq(){return bu.flatMap(e=>(e.paths??[]).map(t=>{let n=t.join(" "),i=Uz[Ia(n)];return{path:n,effect:No(n),host:i===void 0?"shared":"terminal",...i===void 0?{}:{reason:i}}})).sort((e,t)=>e.path.localeCompare(t.path))}s(jq,"plexusCommandCatalog");import Bl from"node:path";function bSe(e){let t=Dt()?.workspaceRoot??process.cwd(),n=Bl.resolve(t,e),i=Bl.relative(t,n);if(Bl.isAbsolute(e)||i===".."||i.startsWith(`..${Bl.sep}`))throw new w("plexus: use a relative path inside the current workspace.");return{absolute:n,relative:i}}s(bSe,"workspacePath");function kSe(e){let{absolute:t,relative:n}=bSe(e.path??".");if(e.operation==="list"){if(!Fe(t))return{files:[]};let i=[],r=s(o=>{for(let a of Ji(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new w("plexus: workspace symlinks are not supported.");let l=Bl.join(o,a.name);if(a.isDirectory()?r(l):i.push(Bl.relative(t,l)),i.length>200)throw new w("plexus: the workspace contains too many files. List a subdirectory.")}},"visit");return r(t),{files:i.sort()}}if(!n)throw new w("plexus: name a workspace file.");if(["read","search","edit"].includes(e.operation)){let i=Be(t);if(i.length>10*1024*1024)throw new w("plexus: the workspace file exceeds 10 MB.");let r=new TextDecoder("utf-8",{fatal:!0}).decode(i);if(e.operation==="read"){let l=e.offset??0,d=e.maxChars??8e3,c=r.slice(l,l+d);return{path:n,content:c,...l||c.length<r.length?{offset:l,nextOffset:l+c.length<r.length?l+c.length:null,totalCharacters:r.length}:{}}}if(e.operation==="search"){if(!e.query)throw new w("plexus: search needs a nonempty query.");let l=[],d=e.offset??0;for(;l.length<10;){let c=r.indexOf(e.query,d);if(c<0)break;l.push({offset:c,text:r.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 w("plexus: edit needs oldText and replacement content.");let o=r.indexOf(e.oldText);if(o<0||o!==r.lastIndexOf(e.oldText))throw new w("plexus: oldText must match exactly once. Read the current file and choose unique context.");let a=r.slice(0,o)+e.content+r.slice(o+e.oldText.length);if(Buffer.byteLength(a)>10*1024*1024)throw new w("plexus: the edited file exceeds 10 MB.");return ft(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 w("plexus: file content is missing or too large.");return bn(Bl.dirname(t),{recursive:!0}),ft(t,e.content,"utf8"),{path:n,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return Jl(t),{path:n,removed:!0};throw new w("plexus: unknown workspace operation.")}s(kSe,"plexusWorkspace");function pee(e){return s(async function(n,i){if(!i||typeof i!="object"||Array.isArray(i))throw new w("plexus: tool input must be an object.");let r=i,o=Xu[n];if(!o||!Object.hasOwn(Xu,n))throw new w("plexus: unknown agent tool.");if(Object.keys(r).some(a=>!Object.hasOwn(o.inputSchema.properties,a)))throw new w("plexus: unexpected tool argument.");if(n==="plexus"){if(!Array.isArray(r.argv)||r.argv.some(a=>typeof a!="string")||r.stdin!==void 0&&typeof r.stdin!="string")throw new w("plexus: invalid command input.");return e.inspectCommand(r.argv),e.executeCommand({argv:r.argv,...r.stdin===void 0?{}:{stdin:r.stdin}})}if(n==="plexus_skill"){if(typeof r.path!="string"||r.path.length>240||!Object.hasOwn(hA,r.path))throw new w("plexus: unknown skill reference. Start with SKILL.md.");return{path:r.path,content:hA[r.path],skillHash:Sy}}if(typeof r.operation!="string"||!["list","read","search","edit","write","remove"].includes(r.operation)||r.path!==void 0&&(typeof r.path!="string"||r.path.length>500)||r.content!==void 0&&(typeof r.content!="string"||r.content.length>1e6)||r.oldText!==void 0&&(typeof r.oldText!="string"||r.oldText.length>1e6)||r.query!==void 0&&(typeof r.query!="string"||!r.query.length||r.query.length>1e3)||r.offset!==void 0&&(typeof r.offset!="number"||!Number.isSafeInteger(r.offset)||r.offset<0)||r.maxChars!==void 0&&(typeof r.maxChars!="number"||!Number.isSafeInteger(r.maxChars)||r.maxChars<1||r.maxChars>24e3))throw new w("plexus: invalid workspace input.");return kSe(r)},"executePlexusAgentTool")}s(pee,"createPlexusAgentToolExecutor");var vSe=["--env","--tenant"];function mee(e){let t=[],n=[];for(let i=0;i<e.length;i++){let r=e[i];if(r==="--"){t.push(...e.slice(i));break}let o=vSe.find(l=>r===l||r.startsWith(`${l}=`)),a=e[i+1];o===void 0?t.push(r):r!==o?n.push({name:o,value:r.slice(o.length+1)}):a!==void 0&&!a.startsWith("-")?(n.push({name:o,value:a}),i++):t.push(r)}return{rest:t,given:n}}s(mee,"splitGlobalOptions");function hee(e,t){let n=R$(e)==="offline";if(n&&No(e)==="read")return t.map(r=>`plexus-cli: ${r.name} ${r.value} has no effect: \`${e}\` runs offline (this CLI's own files, no deployment).
12177
12177
  `);let i=[...new Set(t.map(r=>r.name))].join(", ");throw new w(n?`\`${e}\` does not take ${i}: it never targets a chosen deployment \u2014 drop the option.`:`\`${e}\` does not take ${i}.`)}s(hee,"globalOptionNotes");var e$=pee({inspectCommand:yee,executeCommand:wee});function t$(){let e=new Xl({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:fee});e.register(Ou.HelpCommand),e.register(Ou.VersionCommand);for(let i of bu)e.register(i);function t(i,r){try{return{command:e.process(i,r),notes:[]}}catch(o){let{rest:a,given:l}=mee(i);if(l.length===0)throw o;let d;try{d=e.process(a,r)}catch{throw o}if(!bu.some(u=>d instanceof u))return{command:d,notes:[]};let c=d.path.join(" ");if(!jq().some(u=>u.path===c))throw o;return{command:d,notes:hee(c,l)}}}s(t,"resolve");async function n(i,r){let o=r.stderr??process.stderr,a;try{a=t(i,r)}catch(l){return o.write(e.error(l,{colored:!1})),2}for(let l of a.notes)o.write(l);return $Se(a.command,o),e.run(a.command,r)}return s(n,"run"),{process(i,r){return t(i,r).command},run:n,async runExit(i,r){process.exitCode=await n(i,r)}}}s(t$,"createPlexusCli");function $Se(e,t){let n=e.path.join(" "),i=e.constructor.paths?.[0]?.join(" ");i!==void 0&&n!==i&&Mu[n]===i&&Pt(t,n,i),n in Mu&&No(n)==="confirm"&&!ju(e)&&t.write(`plexus-cli: \`${Mu[n]}\` only prints its plan without --confirm \u2014 nothing was changed.
12178
12178
  `)}s($Se,"noteRetiredPath");function yee(e){let t=t$().process(xu(e),{executePlexusAgentTool:e$}),n=t.path.join(" ");if(n.startsWith("agent "))throw new Error("plexus: nested agent transports are not allowed.");let i=jq().find(d=>d.path===n);if(!i){if(n===""||n==="--help"||n==="--version")return{path:n,writes:!1,host:"shared"};throw new Error(`plexus: command ${n} has no host classification.`)}let r="fn"in t&&typeof t.fn=="string"?t.fn:"",o="kind"in t&&typeof t.kind=="string"?t.kind:void 0,a=i.effect==="callKind"?Lb(lc(dc),r,o):void 0,l=Gg(n,{confirm:ju(t),callKind:a});return{...i,writes:l}}s(yee,"inspectPlexusCommand");async function wee(e,t){if(t)return Gq(t,()=>wee(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="",i="",r=t$();if(Dt()){let l=yee(e.argv);if(l.host==="terminal")throw new Error(`plexus: this command requires a local machine. ${l.reason??""}`)}return{exitCode:await r.run(xu(e.argv),{executePlexusAgentTool:e$,stdin:SSe.from(e.stdin===void 0?[]:[e.stdin]),stdout:new gee({write(l,d,c){n+=String(l),c()}}),stderr:new gee({write(l,d,c){i+=String(l),c()}})}),stdout:n,stderr:i}}s(wee,"executePlexusCommand");Vq();Hq({source:ASe.join(import.meta.dirname,"skill")});t$().runExit(xu(process.argv.slice(2)),{executePlexusAgentTool:e$});
12179
12179
  //# sourceMappingURL=cli.mjs.map