@smartkomm/plexus-cli 0.1.183 → 0.1.184

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
@@ -11242,35 +11242,35 @@ The link is valid for {{gueltigkeit}} and works once. Afterwards you are signed
11242
11242
 
11243
11243
  {{einstellungenLink}}`,en:`Open Plexus and, in the user menu, \u201CSettings\u201D \u2192 \u201CSignature\u201D:
11244
11244
 
11245
- {{einstellungenLink}}`}}]},Ew=[q1,G1,Y1,H1,J1,n2,e2,E2,$2,M2,K2,V2,G2,Y2,J2,X2,tY,oY,aY,R2,I2,O2,lY,dY,cY,t2,r2,s2,a2,c2,h2,f2,w2,S2,D2,OY,NY,j1,B1,fY,mY,gY,wY,vY,SY,EY];function Tw(e){let n=Ew.find(t=>t.id===e);return n===void 0&&L(`notifications: unknown letter "${e}"`),n}s(Tw,"letterDefFor");function $w(e){return Ew.some(n=>n.id===e)}s($w,"hasLetterDef");function Rw(e,n){return n===void 0?!0:jf(e,n)}s(Rw,"letterArgCompatible");function Gl(e){return e==="localizedText"?{de:"Text in jeder Sprache (localizedText)",en:"Text in every language (localizedText)"}:{de:`${tt(e)} (${e})`,en:`${tt(e)} (${e})`}}s(Gl,"letterArgTypeLabel");function iN(e){let n=new Map,t=s((r,i)=>{let o=n.get(r);o===void 0?n.set(r,[i]):o.push(i)},"add");for(let r of e.args)t(r.key,{source:`Ereignis "${e.id}"`,type:r.type,always:r.required===!0});for(let r of V_)t(r.key,{source:"Kontext des Versands",type:r.type,always:!0});return n}s(iN,"eventArgSources");function oN(e,n){let t=e.type===void 0?[...n]:n.filter(r=>Rw(r.type,e.type));if(t.length>1)return{status:"ambiguous",matches:t};if(t.length===1){let r=t[0];return!e.required||r.always?{status:"resolved",source:r}:{status:"sometimes",source:r}}return e.required?{status:"missing",rejected:[...n]}:{status:"unused"}}s(oN,"resolveLetterParam");var Iw=["booked","rescheduled","cancelled"],PY={booked:"admission.appointmentBooked",rescheduled:"admission.appointmentRescheduled",cancelled:"admission.appointmentCancelled"},aN=":";function lN(e,n){return`${e}${aN}${n}`}s(lN,"appointmentEventId");function CY(e){let n=e.lastIndexOf(aN);if(n<=0)return null;let t=e.slice(n+1);return Iw.includes(t)?{taskKey:e.slice(0,n),kind:t}:null}s(CY,"parseAppointmentEventId");var sN={booked:{de:"Termin vereinbart",en:"Appointment booked"},rescheduled:{de:"Termin verschoben",en:"Appointment moved"},cancelled:{de:"Termin abgesagt",en:"Appointment cancelled"}};function ta(e){return Array.isArray(e.tasks)?e.tasks.filter(n=>typeof n?.key=="string"&&n.result?.kind==="appointment"):[]}s(ta,"appointmentTasksOf");function DY(e){return Iw.map(n=>({id:lN(e.key,n),label:{de:`${sN[n].de} \u2013 \u201E${e.title.de}\u201C`,en:`${sN[n].en} \u2013 \u201C${e.title.en}\u201D`},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"bookingId",type:"string",required:!0}]}))}s(DY,"appointmentTaskEvents");function dN(e,n){let t=n.notificationEvents?.(e)??[],r=ta(e).flatMap(DY);return r.length===0?t:[...t,...r]}s(dN,"nodeNotificationEvents");function FY(e){return Object.fromEntries(Iw.map(n=>[lN(e,n),{templateId:PY[n]}]))}s(FY,"defaultAppointmentBindings");function LY(e,n){if(e===void 0)return{notifications:e,dropped:[]};let t=[],r={};for(let[i,o]of Object.entries(e))CY(i)?.taskKey===n?t.push(i):r[i]=o;return t.length===0?{notifications:e,dropped:t}:{notifications:Object.keys(r).length===0?void 0:r,dropped:t}}s(LY,"withoutAppointmentBindings");function ap(e,n,t){let r=new Set(ta(n).map(d=>d.key)),i=new Set(ta(t).map(d=>d.key)),o=e,a=[];for(let d of r){if(i.has(d))continue;let c=LY(o,d);o=c.notifications,a.push(...c.dropped)}let l=[];for(let d of i)if(!r.has(d))for(let[c,u]of Object.entries(FY(d)))o?.[c]===void 0&&(o={...o??{},[c]:u},l.push(c));return{notifications:o,bound:l,dropped:a}}s(ap,"syncAppointmentBindings");function MY(e){return e.kind==="task"&&!("title"in e)}s(MY,"isLegacyFreeTodoContext");function Ow(e){let{context:n}=e;if(MY(n)&&L(`[workItems/legacyFreeTodo] work_item ${e._id} is a free to-do in its former shape \u2014 run migrations:freeTodosToContext`),n.kind==="task")return{...e,context:n,kind:"task",createdVia:"human",partyId:n.partyId};let{anchor:t,task:r,kind:i,title:o,description:a,...l}=n,d=t.scope==="node"?{nodeId:t.nodeId,templateKey:t.templateKey,gatesNode:t.gatesNode,blocks:t.blocks}:t.scope==="application"?{scope:"application",templateKey:t.templateKey}:t.scope==="crossNode"?{scope:"application",nodeId:t.nodeId,templateKey:t.templateKey,blocks:t.blocks}:{};return{...e,context:n,...l,...d,...r??{},kind:i}}s(Ow,"readWorkItem");async function zl(e,n){let t;if(n.nodeId!==void 0){let r=n.nodeId;t=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",i=>i.eq("context.applicationId",n.applicationId).eq("context.anchor.nodeId",r)).collect()}else if(n.isOpen!==void 0){let r=n.isOpen;t=await e.db.query("work_items").withIndex("by_applicationId_and_isOpen",i=>i.eq("context.applicationId",n.applicationId).eq("isOpen",r)).collect()}else t=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",r=>r.eq("context.applicationId",n.applicationId)).collect();return t.filter(r=>n.isOpen===void 0||r.isOpen===n.isOpen).map(Ow)}s(zl,"listWorkItemsForApplication");var Kme=m.union(m.literal("approved"),m.literal("rejected")),Wl=new Set(["task","approval"]);function KY(e,n){switch(e){case"task":return n?.gatesNode===!0&&L("expandComposedTask: gatesNode is approval-only \u2014 a 'task' template never gates its node (use blocks to hold a gating sibling back)"),{kind:"task",recipient:"internal",gatesNode:!1};case"approval":return{kind:"approval",recipient:"internal",isApproval:!0,gatesNode:n?.gatesNode??!0};default:L(`expandComposedTask: unknown composed-task kind ${JSON.stringify(e)} \u2014 authorable: ${[...Wl].join(", ")}`)}}s(KY,"expandComposedTask");for(let e of["task","approval"]){let n=KY(e);n.kind==="approval"!=(n.isApproval===!0)&&L(`composed-task kind "${e}": isApproval must be present iff kind === 'approval'`)}var cN=Di,Gi=`${cN}.`,jY=new Set(["text","number","date","boolean","option","edge"]);function lp(e,n){let t=e[n];return t===void 0&&L(`[env/unknownKey] no environment key '${n}'`),typeof t=="string"?null:Object.keys(t)}s(lp,"contextFields");function uN(e,n){return Object.hasOwn(e,n)}s(uN,"isContextKey");function fN(e){let n=[];for(let t of Object.keys(e)){let r=lp(e,t);if(r===null)n.push(t);else for(let i of r)n.push(`${t}.${i}`)}return n}s(fN,"leafPaths");function Yl(e,n){let[t="",r,...i]=n.split(".");if(!uN(e,t)||i.length>0)return;let o=e[t];if(typeof o=="string")return r===void 0?o:void 0;if(!(r===void 0||!Object.hasOwn(o,r)))return o[r]}s(Yl,"leafType");function pN(e){let n=new Set;for(let t of e){let r=ra(t);r!==null&&n.add(r.split(".")[0])}return[...n]}s(pN,"contextKeysOf");function ra(e){return e.startsWith(Gi)?e.slice(Gi.length):null}s(ra,"contextPathOf");function Hl(e){return e===cN||e.startsWith(Gi)}s(Hl,"isContextIdentifier");function dp(e,n){let t=ra(n)??"",[r=""]=t.split("."),i=Object.keys(e);if(!uN(e,r))return{code:"env/unknownKey",message:{de:`'${n}' nennt keinen Umgebungsschl\xFCssel \u2014 bekannt: ${i.join(", ")}.`,en:`'${n}' names no environment key \u2014 known: ${i.join(", ")}.`}};if(Yl(e,t)!==void 0)return null;let o=lp(e,r);return{code:"env/unknownKey",message:o===null?{de:`'${n}': der Umgebungsschl\xFCssel '${r}' ist ein einzelner Wert \u2014 lies ihn als '${Gi}${r}'.`,en:`'${n}': environment key '${r}' is a single value \u2014 read it as '${Gi}${r}'.`}:{de:`'${n}': der Umgebungsschl\xFCssel '${r}' hat die Felder ${o.join(", ")}.`,en:`'${n}': environment key '${r}' has the fields ${o.join(", ")}.`}}}s(dp,"identifierIssue");function cp(e,n,t=Object.keys(e)){let r={};for(let i of t){let o=lp(e,i),a=Object.hasOwn(n,i)?n[i]:void 0;if(a===void 0&&L(`[env/missing] context key '${i}' was not supplied`),o===null){r[`${Gi}${i}`]=a;continue}for(let l of o){let d=typeof a=="object"&&a!==null&&Object.hasOwn(a,l)?a[l]:void 0;d===void 0&&L(`[env/missing] context key '${i}' carries no '${l}'`),r[`${Gi}${i}.${l}`]=d}}return r}s(cp,"flatten");function mN(e,n,t){if(t===void 0)return!1;let r=lp(e,n);return r===null?!0:typeof t=="object"&&t!==null&&r.every(i=>t[i]!==void 0)}s(mN,"contextValueComplete");function VY(e,n){switch(n){case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"date":return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}/.test(e);default:return typeof e=="string"}}s(VY,"valueMatchesDataType");function hN(e,n,t=Object.keys(e.types)){let r=new Set(t);for(let i of fN(e.types)){if(!r.has(i.split(".")[0]))continue;let o=n[`${Gi}${i}`];o===void 0&&L(`[env/missing] context path '${i}' was not supplied`);let a=e.fields[i];if(o===null){a.nullable||L(`[env/null] context path '${i}' is not nullable but carries null`);continue}let l=tt(Yl(e.types,i));VY(o,l)||L(`[env/type] context path '${i}' expects ${l}, got ${JSON.stringify(o)}`),a.valueSet.kind==="fixed"&&!a.valueSet.values.includes(o)&&L(`[env/value] context path '${i}' carries '${String(o)}', outside ${a.valueSet.values.join(" | ")}`)}}s(hN,"assertContextValues");function BY(e){let n=[],t=fN(e.types);for(let r of t){let i=Yl(e.types,r),o=tt(i);if(!qi(i)||o===void 0||!jY.has(o)){n.push(`'${r}' has type '${String(i)}', not a scalar value type`);continue}let a=Object.hasOwn(e.fields,r)?e.fields[r]:void 0;if(a===void 0){n.push(`'${r}' has no field spec (value set + nullability)`);continue}a.valueSet.kind==="fixed"&&(a.valueSet.values.length===0&&n.push(`'${r}' has an empty fixed value set`),o!=="text"&&o!=="option"&&n.push(`'${r}' is ${o}; a fixed value set needs a text or option leaf`))}for(let r of Object.keys(e.fields))t.includes(r)||n.push(`field spec '${r}' names no leaf of the schema`);return n}s(BY,"schemaIssues");function ia(e){let n=BY(e);n.length>0&&L(`[env/schema] ${n.join("; ")}`)}s(ia,"assertSchema");var up={length:{params:["text"],returns:"number"},years_between:{params:["date","date"],returns:"number"}};function zi(e){return JSON.stringify(e)}s(zi,"canonical");function sa(e){return e.kind==="binary"&&e.op==="&&"?[...sa(e.left),...sa(e.right)]:[e]}s(sa,"conjuncts");function wN(e,n){let t;try{t=In(e)}catch{return!1}let r=zi(In(n));return sa(t).some(i=>zi(i)===r)}s(wN,"hasConjunct");function kN(e,n){try{return zi(In(e))===zi(In(n))}catch{return!1}}s(kN,"sameCondition");function bN(e){let n=[];for(let t of e)n.push(...On(ii(t)));return pN(n)}s(bN,"contextKeysRead");function vN(e){try{return On(In(e)).some(Hl)}catch{return!1}}s(vN,"readsContext");var UY=/^\d{4}-\d{2}-\d{2}$/,GY=new Set(["==","!=","<","<=",">",">=","in"]),zY=new Set(["<","<=",">",">="]);function pp(e,n,t=[]){ia(n);let r;try{r=In(e)}catch(a){let l=a.message;return[Gn("condition/parse",`Bedingung '${e}' ist nicht lesbar: ${l}`,`condition '${e}' does not parse: ${l}`)]}let i=[];for(let a of On(r)){if(!Hl(a)){i.push(Gn("condition/foreignIdentifier",`'${a}' ist kein Umgebungswert \u2014 Bedingungen lesen nur '$env.*'`,`'${a}' is not a context identifier \u2014 conditions read only '$env.*'`));continue}let l=dp(n.types,a);l!==null&&i.push(Gn("condition/unknownIdentifier",l.message.de,l.message.en))}if(i.length>0)return i;let o=Mr(r,n,i);Jl(o)||i.push(Gn("condition/notBoolean",`Bedingung '${e}' ist kein Ja/Nein-Ausdruck`,`condition '${e}' is not a yes/no expression`)),JY(r,n,i);for(let{identifier:a,op:l}of Pw(r,n))i.push(Gn("condition/unguardedNullable",`'${l}' \xFCber '${a}', das leer sein kann, braucht davor eine Absicherung '${a} != null &&'`,`'${l}' over '${a}', which may be null, needs a guard '${a} != null &&' before it`));return i.push(...WY(r,t)),i}s(pp,"conditionIssues");function WY(e,n){let t=sa(e).map(zi);return n.flatMap(r=>{let i=In(r),o=YY(i);return o===null||!t.includes(zi(o))?[]:[{severity:"info",code:"condition/guardForm",message:{de:`[condition/guardForm] eine gespiegelte Absicherung z\xE4hlt nicht \u2014 schreibe sie genau als '${r}'`,en:`[condition/guardForm] a mirrored guard does not count \u2014 write it exactly as '${r}'`}}]})}s(WY,"guardFormHints");function YY(e){if(e.kind!=="binary"||e.op!=="=="&&e.op!=="!=")return null;let n={...e,left:e.right,right:e.left};return zi(n)===zi(e)?null:n}s(YY,"mirror");function Jl(e){return e.t==="unknown"||e.t==="data"&&e.dt==="boolean"}s(Jl,"isBooleanish");function xN(e){let n=ra(e);return n===null&&L(`[condition/invariant] '${e}' reached a pass that only sees $env identifiers`),n}s(xN,"contextPath");function SN(e,n){let t=ra(n);return t!==null&&e.fields[t]?.nullable===!0}s(SN,"isNullableLeaf");function HY(e,n){let t=tt(Yl(e.types,xN(n)));return t===void 0?{t:"unknown"}:{t:"data",dt:t}}s(HY,"identType");function fp(e,n){return e.t==="unknown"||n.t==="unknown"||e.t==="null"||n.t==="null"?!0:e.t==="array"||n.t==="array"?!1:e.t==="str"&&n.t==="str"?!0:e.t==="str"?gN(e.value,n.dt):n.t==="str"?gN(n.value,e.dt):e.dt===n.dt}s(fp,"fits");function gN(e,n){return n==="text"||n==="option"||n==="edge"?!0:n==="date"?UY.test(e):!1}s(gN,"strFits");function yN(e){return e.t==="unknown"?"unknown":e.t==="data"&&e.dt==="number"?"number":null}s(yN,"orderedCategory");function Mr(e,n,t){switch(e.kind){case"num":return{t:"data",dt:"number"};case"bool":return{t:"data",dt:"boolean"};case"str":return{t:"str",value:e.value};case"null":return{t:"null"};case"ident":return HY(n,e.path);case"arr":for(let r of e.items)Mr(r,n,t);return{t:"array"};case"unary":{let r=Mr(e.operand,n,t);return Jl(r)||t.push(Gn("condition/notBoolean","'!' braucht einen Ja/Nein-Operanden","'!' needs a yes/no operand")),{t:"data",dt:"boolean"}}case"call":{let r=Object.hasOwn(up,e.name)?up[e.name]:void 0,i=e.args.map(l=>Mr(l,n,t));return r===void 0?(t.push(Gn("condition/functionNotAllowed",`Funktion '${e.name}' ist nicht erlaubt \u2014 erlaubt: ${Object.keys(up).join(", ")}`,`function '${e.name}' is not allowed \u2014 allowed: ${Object.keys(up).join(", ")}`)),{t:"unknown"}):(i.length===r.params.length&&i.every((l,d)=>l.t!=="null"&&fp(l,{t:"data",dt:r.params[d]}))||t.push(Gn("condition/typeMismatch",`'${e.name}' nimmt (${r.params.join(", ")})`,`'${e.name}' takes (${r.params.join(", ")})`)),{t:"data",dt:r.returns})}case"if":{let r=Mr(e.cond,n,t);Jl(r)||t.push(Gn("condition/notBoolean","'if' braucht eine Ja/Nein-Bedingung","'if' needs a yes/no condition"));let i=Mr(e.then,n,t),o=Mr(e.else,n,t);return fp(i,o)||t.push(Gn("condition/typeMismatch","die beiden Zweige von 'if' haben verschiedene Typen","the two arms of 'if' differ in type")),i.t==="null"?o:i}case"binary":{let r=Mr(e.left,n,t),i=Mr(e.right,n,t);if(e.op==="&&"||e.op==="||")(!Jl(r)||!Jl(i))&&t.push(Gn("condition/notBoolean",`'${e.op}' braucht Ja/Nein-Operanden`,`'${e.op}' needs yes/no operands`));else if(e.op==="in")e.right.kind!=="arr"?t.push(Gn("condition/inWithoutArray","'in' braucht rechts eine Liste, z. B. ['a', 'b']","'in' needs a list on its right, e.g. ['a', 'b']")):e.right.items.every(o=>fp(r,Mr(o,n,[])))||t.push(Gn("condition/typeMismatch","ein Listeneintrag von 'in' passt nicht zum Typ des linken Operanden","a list item of 'in' does not match the left operand's type"));else if(zY.has(e.op)){let o=yN(r),a=yN(i);(o===null||a===null||o!=="unknown"&&a!=="unknown"&&o!==a)&&t.push(Gn("condition/orderedComparison",`'${e.op}' vergleicht nur Zahlen \u2014 f\xFCr Daten years_between(\u2026) verwenden`,`'${e.op}' compares only numbers \u2014 for dates use years_between(\u2026)`))}else fp(r,i)||t.push(Gn("condition/typeMismatch",`'${e.op}' vergleicht Werte verschiedener Typen`,`'${e.op}' compares values of different types`));return{t:"data",dt:"boolean"}}}}s(Mr,"typeOf");function _w(e){return e.kind==="str"||e.kind==="num"||e.kind==="bool"}s(_w,"isLiteral");function AN(e){let n=[],t=s(r=>{if(r.kind==="binary"&&GY.has(r.op)){if(r.left.kind==="ident"){let i=r.op==="in"&&r.right.kind==="arr"?r.right.items.filter(_w):_w(r.right)?[r.right]:[];i.length>0&&n.push({ident:r.left.path,literals:i})}r.right.kind==="ident"&&_w(r.left)&&n.push({ident:r.right.path,literals:[r.left]})}EN(r,t)},"visit");return t(e),n}s(AN,"comparedLiterals");function JY(e,n,t){for(let{ident:r,literals:i}of AN(e)){let o=QY(r,i,n);o!==null&&t.push(o)}}s(JY,"literalIssues");function Nw(e,n){let t;try{t=In(e)}catch{return[]}let r=[];for(let{ident:i,literals:o}of AN(t)){let a=ra(i);if(!(a===null||n.fields[a]?.valueSet.kind!=="live"))for(let l of o)l.kind==="str"&&r.push({path:a,value:l.value})}return r}s(Nw,"liveLiterals");function QY(e,n,t){let r=t.fields[xN(e)]?.valueSet;if(r?.kind==="unstable")return Gn("condition/literalOnUnstable",`'${e}' ist nicht \xFCber Umgebungen stabil \u2014 vergleiche ihn mit keinem festen Wert; verzweige stattdessen \xFCber ein stabiles Merkmal`,`'${e}' is not stable across environments \u2014 compare it to no literal; branch on a stable attribute instead`);if(r?.kind!=="fixed")return null;let i=n.flatMap(a=>a.kind==="str"&&!r.values.includes(a.value)?[`'${a.value}'`]:[]);if(i.length===0)return null;let o=r.values.map(a=>`'${a}'`).join(", ");return Gn("condition/literalOutsideSet",`'${e}' kennt nur ${o} \u2014 nicht ${i.join(", ")}`,`'${e}' takes only ${o} \u2014 not ${i.join(", ")}`)}s(QY,"valueSetIssue");function EN(e,n){switch(e.kind){case"binary":n(e.left),n(e.right);return;case"unary":n(e.operand);return;case"call":e.args.forEach(n);return;case"arr":e.items.forEach(n);return;case"if":n(e.cond),n(e.then),n(e.else);return;default:return}}s(EN,"forEachChild");function TN(e){return e.kind==="binary"&&(e.op==="=="||e.op==="!=")&&(e.left.kind==="ident"&&e.right.kind==="null"||e.left.kind==="null"&&e.right.kind==="ident")}s(TN,"isNullTest");function $N(e){return sa(e).flatMap(n=>{let t=RN(n);return t===null?[]:[t]})}s($N,"guardsOf");function Ql(e,n,t){switch(e.kind){case"ident":return SN(n,e.path)&&!t.has(e.path)?e.path:null;case"call":for(let r of e.args){let i=Ql(r,n,t);if(i!==null)return i}return null;case"if":return Ql(e.then,n,new Set([...t,...$N(e.cond)]))??Ql(e.else,n,t);default:return null}}s(Ql,"unguardedNullSource");function RN(e){return!TN(e)||e.kind!=="binary"||e.op!=="!="?null:e.left.kind==="ident"?e.left.path:e.right.kind==="ident"?e.right.path:null}s(RN,"guardedIdent");function oa(e,n,t,r){if(e.kind==="binary"&&e.op==="&&"){let i=new Set(t);for(let o of sa(e)){oa(o,n,i,r);let a=RN(o);a!==null&&i.add(a)}return}if(e.kind==="if"){oa(e.cond,n,t,r),oa(e.then,n,new Set([...t,...$N(e.cond)]),r),oa(e.else,n,t,r);return}if(e.kind==="binary"&&e.op==="!="&&e.left.kind!=="null"&&e.right.kind!=="null"){let i=Ql(e.left,n,t)??Ql(e.right,n,t);i!==null&&r(i,"!=")}if(e.kind==="unary"&&!TN(e.operand)){let i=On(e.operand).filter(o=>SN(n,o)&&!t.has(o));i.length>0&&r(i[0],"!")}EN(e,i=>oa(i,n,t,r))}s(oa,"nullableReads");function Pw(e,n){ia(n);let t=[];return oa(e,n,new Set,(r,i)=>{t.some(o=>o.identifier===r)||t.push({identifier:r,op:i})}),t}s(Pw,"unguardedNullableReads");function Gn(e,n,t){return{severity:"error",code:e,message:{de:`[${e}] ${n}`,en:`[${e}] ${t}`}}}s(Gn,"error");function Zl(e){let n=Array.isArray(e.nodes)?e.nodes:[],t=new Set;for(let r of n)for(let i of Wf(r))i.key!==null&&Us[i.leaf].involves&&t.add(i.key);return t}s(Zl,"declaredGroupKeys");var aa=vf;var ZY="unit.key",XY="offer.key";function IN(e,n){return e===ZY?n.unitKeys:e===XY?n.offerKeys:null}s(IN,"liveKeyUniverse");function mp(e){return[gn,...[...Zl(e)].sort((n,t)=>n.localeCompare(t)).map(Rf)]}s(mp,"requiredSlots");var Wi=`${Sf("applicant.channel")} == 'staff'`;var Dw=["strict","leastLoaded"];var Cw=2;function ON(e){return e.some(n=>n.length===0)?{de:"nennt einen leeren Personenschl\xFCssel",en:"names an empty person key"}:new Set(e).size!==e.length?{de:"nennt eine Person zweimal",en:"names a person twice"}:e.length<Cw?{de:`braucht mindestens ${Cw} Personen`,en:`needs at least ${Cw} people`}:null}s(ON,"rotationPoolProblem");function eH(e,n){let t=n===null?-1:e.indexOf(n);return[...e.slice(t+1),...e.slice(0,t+1)]}s(eH,"strictOrder");function _N(e){let n=eH(e.pool,e.previous).filter(i=>e.eligible.has(i));if(n.length===0)return null;if(e.mode==="strict")return n[0];let t=e.openCounts;t===void 0&&L("[assignment/rotation] leastLoaded needs the open counts");let r=s(i=>{let o=t.get(i);return o===void 0&&L(`[assignment/rotation] no open count for '${i}'`),o},"load");return n.reduce((i,o)=>r(o)<r(i)?o:i)}s(_N,"pickFromPool");function PN(e){return e.map(n=>({slot:jI(n.slot),rules:[...n.rules]}))}s(PN,"rulesOfStored");function CN(e){return e.map(n=>({slot:nH(n.slot),rules:[...n.rules]}))}s(CN,"storedOfRules");function nH(e){let n=Of(e);return n===null&&L(`[assignment/unknownSlot] '${e}' is no slot \u2014 'responsible' or 'team:<teamKey>'`),n}s(nH,"slotOf");function DN(e,n){let t=e?.assignmentRules;t===void 0&&L(`[assignment/noRules] ${n}: the workflow has no assignment rule`);let r=qN(t);return r.length>0&&L(`${r.join("; ")} (${n})`),PN(t)}s(DN,"rulesOfGraph");function tH(e){return e===gn?{slot:e,rules:[{when:Wi,assign:{kind:"creator"}},{when:null,assign:{kind:"unassigned"}}]}:{slot:e,rules:[{when:null,assign:{kind:"queue"}}]}}s(tH,"defaultSlotRules");function FN(e,n){let t=new Set(e.map(o=>o.slot)),r=n.filter(o=>!t.has(o)).map(tH);return[...r.filter(o=>o.slot===gn),...e,...r.filter(o=>o.slot!==gn)]}s(FN,"withRequiredSlots");function Nn(e,n){return n===void 0?`slot '${e}'`:`slot '${e}' row #${n+1}`}s(Nn,"where");function Ct(e,n){return n===void 0?`Liste '${e}'`:`Liste '${e}', Zeile #${n+1}`}s(Ct,"whereDe");function xt(e,n,t={},r="error"){return{severity:r,code:e,message:{de:`[${e}] ${n.de}`,en:`[${e}] ${n.en}`},...t}}s(xt,"issue");function NN(e){if(e===gn)return!0;let n=If(e);return n!==null&&n.length>0}s(NN,"isKnownSlot");function rH(e,n){ia(aa);let t=[],r=new Set;e.forEach((o,a)=>{let{slot:l}=o;NN(l)||t.push(xt("assignment/unknownSlot",{de:`'${l}' ist keine Liste \u2014 'responsible' oder 'team:<teamKey>'`,en:`'${l}' is no slot \u2014 'responsible' or 'team:<teamKey>'`},{slot:l})),r.has(l)&&t.push(xt("assignment/duplicateSlot",{de:`${Ct(l)} steht zweimal da`,en:`${Nn(l)} is listed twice`},{slot:l})),r.add(l),l===gn&&a!==0&&t.push(xt("assignment/responsibleFirst",{de:`'${gn}' muss die erste Liste sein \u2014 Team-Zeilen \xFCbernehmen sie`,en:`'${gn}' must be the first slot \u2014 team rows copy it`},{slot:l})),t.push(...iH(o))});for(let o of n)r.has(o)||t.push(xt("assignment/slotMissing",{de:`${Ct(o)} hat keine Regeln \u2014 der Workflow braucht sie`,en:`${Nn(o)} has no rule list \u2014 the workflow needs it`},{slot:o}));let i=new Set(n);for(let{slot:o}of e)o!==gn&&!i.has(o)&&NN(o)&&t.push(xt("assignment/unusedSlot",{de:`${Ct(o)} wird hier nicht gebraucht \u2014 erlaubt, und nicht ausgewertet`,en:`${Nn(o)} is not needed here \u2014 allowed, and not evaluated`},{slot:o},"info"));return t}s(rH,"validateRules");function iH({slot:e,rules:n}){let t=[];return(n.length===0||n[n.length-1].when!==null)&&t.push(xt("assignment/defaultRowMissing",{de:`${Ct(e)} muss mit einer Zeile ohne Bedingung enden (\u201Esonst\u201C)`,en:`${Nn(e)} must end with a row without condition ("otherwise")`},{slot:e})),n.forEach((r,i)=>{let o={slot:e,row:i},{when:a,assign:l}=r;if(a===null&&i<n.length-1&&t.push(xt("assignment/ruleAfterDefault",{de:`${Ct(e,i)} hat keine Bedingung, aber es folgen Zeilen \u2014 sie treffen nie zu`,en:`${Nn(e,i)} has no condition, but rows follow it \u2014 they can never match`},o)),a!==null){let d=pp(a,aa,[Wi]);for(let c of d)t.push({...c,message:{de:`${c.message.de} (${Ct(e,i)})`,en:`${c.message.en} (${Nn(e,i)})`},...o});if(d.every(c=>c.severity!=="error")){vN(a)||t.push(xt("assignment/shadowedRule",{de:`${Ct(e,i)} liest nichts aus dem Vorgang \u2014 sie gilt immer oder nie`,en:`${Nn(e,i)} reads nothing of the application \u2014 it holds for every application or for none`},o));let c=n.slice(0,i).findIndex(u=>u.when!==null&&kN(u.when,a));c!==-1&&t.push(xt("assignment/shadowedRule",{de:`${Ct(e,i)} wiederholt die Bedingung von Zeile #${c+1} \u2014 sie trifft nie zu`,en:`${Nn(e,i)} repeats the condition of row #${c+1} \u2014 it can never match`},o))}}if(e===gn&&l.kind==="slot"&&t.push(xt("assignment/slotForwardRef",{de:`${Ct(e,i)} \xFCbernimmt '${l.slot}' \u2014 das darf nur eine Team-Liste nach '${gn}'`,en:`${Nn(e,i)} copies '${l.slot}' \u2014 only a team slot after '${gn}' may`},o)),e===gn&&l.kind==="queue"&&t.push(xt("assignment/queueOnProcessSlot",{de:`${Ct(e,i)} weist die Queue zu \u2014 die Prozesszust\xE4ndigkeit ist immer eine Person`,en:`${Nn(e,i)} assigns the queue \u2014 the responsible slot is always a person`},o)),l.kind==="unassigned"&&t.push(xt("assignment/targetMissing",{de:`${Ct(e,i)} nennt noch niemanden \u2014 Person w\xE4hlen`,en:`${Nn(e,i)} names no one yet \u2014 choose a person`},o)),l.kind==="rotation"){let d=ON(l.configKeys);d!==null&&t.push(xt("assignment/rotationPool",{de:`${Ct(e,i)}: die Reihum-Liste ${d.de}`,en:`${Nn(e,i)} rotates over a pool that ${d.en}`},o))}l.kind==="creator"&&(a===null||!wN(a,Wi))&&t.push(xt("assignment/unguardedTarget",{de:`${Ct(e,i)} weist die anlegende Person zu \u2014 die gibt es nur, wenn die Bedingung der Zeile '${Wi}' ist (oder enth\xE4lt)`,en:`${Nn(e,i)} assigns the creator, which exists only when the row's condition is (or has the conjunct) '${Wi}'`},o))}),t}s(iH,"rowIssues");function LN(e,n){for(let r of n)e.some(i=>i.slot===r)||L(`[assignment/slotMissing] ${Nn(r)} has no rule list`);let t=new Set(n);return e.filter(r=>t.has(r.slot))}s(LN,"selectSlots");function oH(e,n){return bN(LN(e,n).flatMap(t=>t.rules.flatMap(r=>r.when===null?[]:[r.when])))}s(oH,"contextKeysOfRules");function MN(e,n,t,r){ia(aa);let i=LN(e,t),o=oH(e,t),a=cp(aa.types,n,o);hN(aa,a,o);let l=[];for(let{slot:d,rules:c}of i){let u=c.findIndex((h,y)=>{if(h.when===null)return!0;for(let k of On(ii(h.when)))Object.hasOwn(a,k)||L(`[condition/unknownIdentifier] ${Nn(d,y)} reads '${k}', which the context does not carry`);return yO(h.when,{values:a})});u===-1&&L(`[assignment/defaultRowMissing] ${Nn(d)}: no row matched and there is no default row`);let p=c[u].assign;l.push({slot:d,ruleIndex:u,assign:p,value:sH(d,u,p,l,r)})}return l}s(MN,"evaluateRules");function sH(e,n,t,r,i){switch(t.kind){case"person":return{kind:"value",value:i.person(t.configKey)};case"creator":return{kind:"value",value:i.creator()};case"rotation":return{kind:"value",value:i.rotation(t,{slot:e,row:n})};case"unassigned":return L(`[assignment/targetMissing] ${Nn(e,n)} names no one`);case"queue":return e===gn&&L(`[assignment/queueOnProcessSlot] ${Nn(e,n)} assigns the queue`),{kind:"queue"};case"slot":{let o=e===gn?void 0:r.find(a=>a.slot===t.slot);return o===void 0&&L(`[assignment/slotForwardRef] ${Nn(e,n)} copies '${t.slot}', which is not decided before it`),o.value}}}s(sH,"resolveTarget");var Fw={person:["kind","configKey"],creator:["kind"],slot:["kind","slot"],queue:["kind"],rotation:["kind","configKeys","mode"],unassigned:["kind"]};function aH(e){if(typeof e!="object"||e===null)return!1;let{kind:n,groupKey:t,...r}=e;return Object.keys(r).length>0?!1:n==="responsible"?t===void 0:n==="team"&&typeof t=="string"&&t.length>0}s(aH,"isStoredSlot");function qN(e){let n=[],t=s((r,i)=>n.push(`[assignment/shape] ${r}: ${i}`),"bad");return Array.isArray(e)?(e.forEach((r,i)=>{let o=`slots[${i}]`;if(typeof r!="object"||r===null)return t(o,"must be { slot, rules }");let{slot:a,rules:l,...d}=r;if(Object.keys(d).length>0&&t(o,`unknown field(s) ${Object.keys(d).join(", ")}`),aH(a)||t(o,"slot must be { kind: 'responsible' } or { kind: 'team', groupKey: '<team key>' }"),!Array.isArray(l))return t(o,"rules must be a list");l.forEach((c,u)=>{let p=`${o}.rules[${u}]`;if(typeof c!="object"||c===null)return t(p,"must be { when, assign }");let{when:h,assign:y,...k}=c;Object.keys(k).length>0&&t(p,`unknown field(s) ${Object.keys(k).join(", ")}`),h!==null&&typeof h!="string"&&t(p,"when must be a condition string or null (\u201Esonst\u201C)");let w=y?.kind;if(typeof y!="object"||y===null||typeof w!="string"||!Object.hasOwn(Fw,w))return t(p,`assign must be one of ${Object.keys(Fw).map(R=>`{kind:'${R}'}`).join(", ")}`);let v=Fw[w],A=Object.keys(y);(A.some(R=>!v.includes(R))||v.some(R=>!A.includes(R)))&&t(p,`a '${w}' target has exactly the field(s) ${v.join(", ")}`);let E=y;if(w==="person"&&(typeof E.configKey!="string"||E.configKey.length===0)&&t(p,"a 'person' target needs a non-empty configKey"),w==="rotation"){let R=E.configKeys;(!Array.isArray(R)||R.some(P=>typeof P!="string"))&&t(p,"a 'rotation' target needs configKeys, a list of person keys"),Dw.includes(E.mode)||t(p,`a 'rotation' target's mode is one of ${Dw.map(P=>`'${P}'`).join(", ")}`)}w==="slot"&&E.slot!==gn&&t(p,`a 'slot' target copies '${gn}' and nothing else`)})}),n):(t("slots","must be a list of { slot, rules }"),n)}s(qN,"ruleShapeIssues");function KN(e){let n=e??{},t=[];if(n.teamOwnerBindings!==void 0&&t.push({de:"[assignment/legacyBindings] der Workflow tr\xE4gt noch teamOwnerBindings \u2014 die Zust\xE4ndigkeitsregel ersetzt sie; das Feld entfernen",en:"[assignment/legacyBindings] the workflow still carries teamOwnerBindings \u2014 the assignment rule replaces them; remove the field"}),n.assignmentRules===void 0)return t.push({de:"[assignment/noRules] der Workflow hat keine Zust\xE4ndigkeitsregel (graph.assignmentRules) \u2014 jeder Workflow muss sagen, wer zust\xE4ndig wird",en:"[assignment/noRules] the workflow has no assignment rule (graph.assignmentRules) \u2014 every workflow must say who becomes responsible"}),t;let r=qN(n.assignmentRules);if(r.length>0)return[...t,...r.map(o=>({de:o,en:o}))];let i=mp({nodes:Array.isArray(n.nodes)?n.nodes:[]});for(let o of rH(PN(n.assignmentRules),i))o.severity==="error"&&t.push(o.message);return t}s(KN,"workflowAssignmentIssues");function hp(e,n){let o=new Map;for(let d of e)o.set(d,0);let a=new Map,l=[];for(let d of e){if((o.get(d)??0)!==0)continue;let c=[{id:d,edges:n(d),idx:0}];for(o.set(d,1),a.set(d,null);c.length>0;){let u=c[c.length-1];if(u.idx>=u.edges.length){o.set(u.id,2),c.pop();continue}let{target:p,edge:h}=u.edges[u.idx];u.idx++;let y=o.get(p)??0;if(y===1){let k=[p],w=u.id;for(;w&&w!==p;)k.push(w),w=a.get(w)??null;k.reverse(),l.push({edge:h,source:u.id,target:p,cycle:k})}else y===0&&(o.set(p,1),a.set(p,u.id),c.push({id:p,edges:n(p),idx:0}))}}return l}s(hp,"detectBackEdges");var Lw="team:",lH=/^[a-z0-9][a-z0-9-]*$/;function dH(e){if(!e.startsWith(Lw))return null;let n=e.slice(Lw.length);return n.length>0?n:null}s(dH,"teamKeyOfMember");function gp(e){return`${Lw}${e}`}s(gp,"teamMember");function la(e){let n=e.channels;return n===void 0?[]:(Array.isArray(n)||L("graph.channels must be an array"),n)}s(la,"readAuthoredChannels");function jN(e){return[...Zl(e)].sort()}s(jN,"derivedChannelTeamKeys");function VN(e,n){let t=e.toLowerCase().replace(/ä/g,"ae").replace(/ö/g,"oe").replace(/ü/g,"ue").replace(/ß/g,"ss").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"channel";if(!n.has(t))return t;for(let r=2;;r++){let i=`${t}-${r}`;if(!n.has(i))return i}}s(VN,"mintChannelKey");function BN(e,n){let t=e.channels;if(t===void 0)return[];if(!Array.isArray(t))return[{path:"channels",reason:{de:"[channels/shape] graph.channels muss eine Liste sein.",en:"[channels/shape] graph.channels must be a list."}}];let r=[],i=Zl(e),o=new Set,a=new Map;return t.forEach((l,d)=>{let c=`channels[${d}]`,u=l;if(u===null||typeof u!="object"||typeof u.key!="string"||Rn(u.label)==="not-localized"||!Array.isArray(u.members)||!u.members.every(A=>typeof A=="string")){r.push({path:c,reason:{de:"[channels/shape] Ein Kanal braucht key, label ({ de, en }) und members (Liste von Texten).",en:"[channels/shape] A channel needs key, label ({ de, en }) and members (a list of texts)."}});return}let p={de:`Kanal "${u.key}"`,en:`Channel "${u.key}"`};lH.test(u.key)||r.push({path:`${c}.key`,reason:{de:`[channels/invalidKey] ${p.de}: Schl\xFCssel nur aus Kleinbuchstaben, Ziffern und Bindestrich.`,en:`[channels/invalidKey] ${p.en}: key only from lowercase letters, digits and hyphens.`}}),o.has(u.key)&&r.push({path:`${c}.key`,reason:{de:`[channels/duplicateKey] ${p.de}: Schl\xFCssel ist doppelt vergeben.`,en:`[channels/duplicateKey] ${p.en}: key is used twice.`}}),o.add(u.key);let h=Rn(u.label);if(h!=="not-localized"&&h.length===2?r.push({path:`${c}.label`,reason:{de:`[channels/emptyLabel] ${p.de}: Bezeichnung fehlt.`,en:`[channels/emptyLabel] ${p.en}: name is missing.`}}):h!=="not-localized"&&h.length>0&&r.push({path:`${c}.label`,reason:{de:`[i18n/missingTranslation] ${p.de}: Bezeichnung fehlt in: ${h.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`,en:`[i18n/missingTranslation] ${p.en}: name is missing in: ${h.join(", ")} \u2014 every displayed text needs German and English.`}}),u.members.length===0){r.push({path:`${c}.members`,reason:{de:`[channels/emptyMembers] ${p.de}: mindestens ein Team.`,en:`[channels/emptyMembers] ${p.en}: at least one team.`}});return}let y=[];for(let A of u.members){let E=dH(A);if(E===null){r.push({path:`${c}.members`,reason:{de:`[channels/invalidMember] ${p.de}: "${A}" ist kein "team:<schl\xFCssel>".`,en:`[channels/invalidMember] ${p.en}: "${A}" is not a "team:<key>".`}});continue}if(y.includes(E)){r.push({path:`${c}.members`,reason:{de:`[channels/duplicateMember] ${p.de}: Team "${E}" ist doppelt genannt.`,en:`[channels/duplicateMember] ${p.en}: team "${E}" is named twice.`}});continue}n!==void 0&&!n.has(E)&&r.push({path:`${c}.members`,reason:{de:`[channels/unknownTeam] ${p.de}: Team "${E}" gibt es in diesem Mandanten nicht (oder es ist die Bewerbergruppe).`,en:`[channels/unknownTeam] ${p.en}: team "${E}" does not exist at this school (or it is the applicant group).`}}),y.push(E)}if(y.length===0)return;let k=[...y].sort().join("+"),[w]=y;y.length===1&&w!==void 0&&i.has(w)&&r.push({path:`${c}.members`,reason:{de:`[channels/duplicatesDerived] ${p.de}: Team "${w}" ist am Prozess beteiligt und hat seinen Kanal schon automatisch.`,en:`[channels/duplicatesDerived] ${p.en}: team "${w}" takes part in the process and already has its channel automatically.`}});let v=a.get(k);v!==void 0?r.push({path:`${c}.members`,reason:{de:`[channels/duplicateMembership] ${p.de}: dieselben Teams wie Kanal "${v}" \u2014 zwei Tabs w\xE4ren derselbe Chat.`,en:`[channels/duplicateMembership] ${p.en}: the same teams as channel "${v}" \u2014 two tabs would be the same chat.`}}):a.set(k,u.key)}),r}s(BN,"channelIssues");var Phe=Object.freeze({});function cH(e,n){return Object.freeze(cp(Zr,e,n))}s(cH,"formContextEntries");function UN(e){return e.env??[]}s(UN,"declaredContextKeys");function GN(e,n){return UN(e).every(t=>zN(t,n?.[t]))}s(GN,"scenarioContextComplete");function zN(e,n){return mN(Zr,e,n)}s(zN,"contextValueComplete");function WN(e,n){return cH(n??{},UN(e))}s(WN,"scenarioContextEntries");function qw(e){return Hl(e)}s(qw,"isContextIdentifier");function uH(e,n,t){let r=dp(Zr,e);if(r!==null)return{severity:"error",path:t,code:"env/unknownKey",message:r.message};let[,i=""]=e.split(".");return n.has(i)?null:{severity:"error",path:t,code:"env/undeclared",message:{de:`'${e}' liest den Umgebungsschl\xFCssel '${i}', den das Formular nicht in \`env\` deklariert.`,en:`'${e}' reads the environment key '${i}', which the form does not declare in \`env\`.`}}}s(uH,"contextIdentifierIssue");var Mw=Sf("stage.key");function fH(e){let n=[],t=s(i=>i.kind==="ident"&&i.path===Mw,"isStageKey"),r=s(i=>{switch(i.kind){case"binary":if((i.op==="=="||i.op==="!=")&&(t(i.left)&&i.right.kind==="str"&&n.push(i.right.value),t(i.right)&&i.left.kind==="str"&&n.push(i.left.value)),i.op==="in"&&t(i.left)&&i.right.kind==="arr")for(let o of i.right.items)o.kind==="str"&&n.push(o.value);r(i.left),r(i.right);return;case"unary":r(i.operand);return;case"if":r(i.cond),r(i.then),r(i.else);return;case"call":i.args.forEach(r);return;case"arr":i.items.forEach(r);return;default:return}},"walk");return r(e),n}s(fH,"stageKeyLiterals");function yp(e,n,t){return n===void 0?[]:fH(e).filter(r=>!n.has(r)).map(r=>HN(r,n,t))}s(yp,"stageKeyAstIssues");function YN(e,n){if(n===void 0)return[];let t=[];for(let r of e.testScenarios??[]){let i=r.env?.stage;typeof i?.key=="string"&&!n.has(i.key)&&t.push(HN(i.key,n,`scenario:${r.id}/env`))}return t}s(YN,"scenarioStageKeyIssues");function HN(e,n,t){let r=[...n].sort();return{severity:"error",path:t,code:"env/unknownStageKey",message:{de:`'${e}' ist kein Stufenschl\xFCssel des Programms dieses Angebots \u2014 `+(r.length>0?`bekannt: ${r.join(", ")}.`:"das Angebot hat kein Programm mit Stufen.")+` \`${Mw}\` ist der Bundle-Schl\xFCssel (\`program.stages[].key\`), nie das gespeicherte \`<program>-stufe-<key>\`.`,en:`'${e}' is not a stage key of the offer's program \u2014 `+(r.length>0?`known: ${r.join(", ")}.`:"the offer has no program with stages.")+` \`${Mw}\` is the bundle key (\`program.stages[].key\`), never the stored \`<program>-stufe-<key>\`.`}}}s(HN,"unknownStageKeyIssue");function JN(e,n,t){let r=[];for(let i of On(e)){if(!qw(i))continue;let o=uH(i,n,t);o!==null&&r.push(o)}if(r.length>0)return r;for(let{identifier:i,op:o}of Pw(e,vf))r.push({severity:"error",path:t,code:"env/unguardedNullable",message:{de:`'${o}' \xFCber '${i}', das bei manchen Bewerbungen leer ist, braucht davor eine Absicherung '${i} != null &&' \u2014 lege fest, was ein leerer Wert bedeutet.`,en:`'${o}' over '${i}', which is empty for some applications, needs a guard '${i} != null &&' before it \u2014 say what an empty value means.`}});return r}s(JN,"contextAstIssues");function QN(e,n){let t=[...pH(e)],r=new Set(e.env??[]);for(let i of e.env??[]){if(!Ns(i)){t.push({severity:"error",path:"env",code:"env/unknownKey",message:{de:`Der deklarierte Umgebungsschl\xFCssel '${i}' geh\xF6rt nicht zum Vokabular (${_s.join(", ")}).`,en:`Declared environment key '${i}' is not in the vocabulary (${_s.join(", ")}).`}});continue}n!==void 0&&!n.has(i)&&t.push({severity:"error",path:"env",code:"env/unsupplied",message:{de:`Das Formular deklariert den Umgebungsschl\xFCssel '${i}', aber sein Host liefert ihn nicht.`,en:`The form declares environment key '${i}', but its host does not supply it.`}})}for(let i of e.testScenarios??[]){let o=[...r].filter(a=>Ns(a)&&!zN(a,i.env?.[a]));o.length>0&&t.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unsampled",message:{de:`Szenario '${i.id}' belegt den deklarierten Umgebungsschl\xFCssel ${o.map(a=>`'${a}'`).join(", ")} nicht vollst\xE4ndig \u2014 eine echte Bewerbung tr\xE4gt immer jedes seiner Felder (ein leeres als null).`,en:`Scenario '${i.id}' does not sample the declared environment key(s) ${o.map(a=>`'${a}'`).join(", ")} completely \u2014 a real application always carries every field of them (an empty one as null).`}});for(let a of Object.keys(i.env??{}))Ns(a)?r.has(a)||t.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/undeclared",message:{de:`Szenario '${i.id}' belegt den Umgebungsschl\xFCssel '${a}', den das Formular nicht deklariert.`,en:`Scenario '${i.id}' samples environment key '${a}', which the form does not declare.`}}):t.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unknownKey",message:{de:`Szenario '${i.id}' belegt den unbekannten Umgebungsschl\xFCssel '${a}'.`,en:`Scenario '${i.id}' samples unknown environment key '${a}'.`}})}return t}s(QN,"formContextIssues");function pH(e){let n=[];Object.hasOwn(e,"context")&&n.push({severity:"error",path:"context",code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Formular deklariert die gelesene Umgebung als `env`.",en:"`context` is retired \u2014 a form declares the environment it reads as `env`."}});let t=e.testScenarios;for(let r of Array.isArray(t)?t:[])r!==null&&typeof r=="object"&&Object.hasOwn(r,"context")&&n.push({severity:"error",path:`scenario:${String(r.id)}/context`,code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Szenario belegt die Umgebung als `env`.",en:"`context` is retired \u2014 a scenario samples the environment as `env`."}});return n}s(pH,"retiredContextFields");function wp(e,n,t){let r=pp(e,n).filter(o=>o.severity==="error").map(o=>o.message);if(r.length>0)return r;let i=[];if(t?.liveEnvKeys!==void 0)for(let o of Nw(e,n)){let a=IN(o.path,t.liveEnvKeys);a===null&&L(`[condition] no live-key universe for '${o.path}' \u2014 extend liveKeyUniverse`),a.has(o.value)||i.push({de:`$env.${o.path} == '${o.value}' nennt keinen Schl\xFCssel dieses Mandanten.`,en:`$env.${o.path} == '${o.value}' names no key of this school.`})}for(let o of yp(In(e),t?.stageKeys,""))i.push({de:`[${o.code}] ${o.message.de}`,en:`[${o.code}] ${o.message.en}`});return i}s(wp,"envConditionFindings");function kp(e){return e.kind==="entered"&&!e.repeated&&e.reviewRequired}s(kp,"isReviewField");function da(e){let n=[],t=[];function r(w,v){try{return In(w)}catch(A){n.push({path:v,src:w,reason:A instanceof Error?A.message:String(A)});return}}s(r,"tryParse");function i(w,v){return{...w,visibleIf:w.visibleIf?r(w.visibleIf,`${v}.visibleIf`):void 0,requiredIf:w.requiredIf?r(w.requiredIf,`${v}.requiredIf`):void 0,disabledIf:w.disabledIf?r(w.disabledIf,`${v}.disabledIf`):void 0,defaultValue:w.defaultValue?r(w.defaultValue,`${v}.defaultValue`):void 0}}s(i,"compileField");function o(w,v){return{...w,visibleIf:w.visibleIf?r(w.visibleIf,`${v}.visibleIf`):void 0,fields:w.fields.map((A,E)=>i(A,`${v}.fields[${E}]`))}}s(o,"compileGroup");function a(w,v){return{...w,itemTemplate:w.itemTemplate.map((A,E)=>i(A,`${v}.itemTemplate[${E}]`)),effects:w.effects?.map((A,E)=>d(A,`${v}.effects[${E}]`)),itemVisibleIf:w.itemVisibleIf?r(w.itemVisibleIf,`${v}.itemVisibleIf`):void 0}}s(a,"compileRepeated");function l(w,v){let A=[];return w.fields.forEach((E,R)=>{if(E.externalFlag){t.push({key:E.key,label:E.label,defaultValue:E.defaultValue?r(E.defaultValue,`${v}.fields[${R}].defaultValue`):void 0});return}A.push(i(E,`${v}.fields[${R}]`))}),{...w,visibleIf:w.visibleIf?r(w.visibleIf,`${v}.visibleIf`):void 0,fields:A,groups:w.groups?.map((E,R)=>o(E,`${v}.groups[${R}]`)),computed:w.computed?.map((E,R)=>{let P=r(E.expression,`${v}.computed[${R}].expression`);return{key:E.key,expression:P??{kind:"null"}}}),subsections:w.subsections?.map((E,R)=>l(E,`${v}.subsections[${R}]`)),repeated:w.repeated?.map((E,R)=>a(E,`${v}.repeated[${R}]`)),validators:w.validators}}s(l,"compileSection");function d(w,v){return{...w,when:w.when?r(w.when,`${v}.when`):void 0}}s(d,"compileEffect");function c(w,v){let A=r(w.when,`${v}.when`);return A?{...w,when:A}:null}s(c,"compileOutcome");let u=e.sections.map((w,v)=>l(w,`sections[${v}]`)),p=(e.effects??[]).map((w,v)=>d(w,`effects[${v}]`)),h=[],y=e.outcomes??[];for(let w=0;w<y.length;w++){let v=y[w],A=c(v,`outcomes[${w}]`);A&&h.push(A)}return{compiled:{...e,sections:u,effects:p,outcomes:h,flags:t},errors:n}}s(da,"compileForm");var mH=new Set(["decision","review","governedDocument"]);function XN(e){return mH.has(e.type)&&!(e.type==="governedDocument"&&e.production==="none")}s(XN,"isReadinessGatedNode");function hH(e){let n=new Map,t=yH(e),r=s((i,o)=>{let a=Kw(o),l=[...i.fields,...(i.groups??[]).flatMap(d=>d.fields)];for(let d of l)d.externalFlag!==!0&&n.set(d.key,{kind:"entered",key:d.key,label:d.label,qualifier:gH(d.bucket,t,a),section:a,type:d.type,enumSource:ZN(d),repeated:!1,reviewRequired:d.reviewRequired===!0});for(let d of i.repeated??[])for(let c of d.itemTemplate){let u=`${d.key}.${c.key}`;n.set(u,{kind:"entered",key:u,label:c.label,qualifier:Kw(d),section:a,type:c.type,enumSource:ZN(c),repeated:!0,reviewRequired:!1})}for(let d of i.computed??[]){let c=On(In(d.expression));n.set(d.key,{kind:"computed",key:d.key,label:d.label??{de:d.key,en:d.key},qualifier:a,deps:c})}for(let d of i.subsections??[])r(d,o)},"visit");for(let i of e.sections)r(i,i);return n}s(hH,"formFieldCatalog");function ZN(e){return e.type==="enum"?e:null}s(ZN,"enumSourceOf");function gH(e,n,t){return e===void 0?t:n.get(e)??t}s(gH,"fieldQualifier");function yH(e){let n=new Map,t=s((r,i)=>{i===void 0||n.has(r)||n.set(r,Kw(i))},"add");for(let r of nP(e))r.kind==="person"?t(r.bucket,r.display):r.kind==="organization"&&t(r.id.replace(/^o\./,""),r.display);return n}s(yH,"bucketWordings");function eP(e){return e.flatMap(n=>[n,...eP(n.subsections??[])])}s(eP,"allSections");function nP(e){return[...e.effects,...eP(e.sections).flatMap(n=>(n.repeated??[]).flatMap(t=>t.effects??[]))]}s(nP,"allEffects");function Kw(e){return{label:e.label}}s(Kw,"wordingOf");function tP(e){return Pl(e).flatMap(({slot:n,address:t})=>{let r=SO(t);return r===null||Nl.includes(r.path)?[]:[{slotId:n,owner:r.owner,fieldKey:r.path}]})}s(tP,"admissionBindingLeaves");function wH(e,n){let t=e.get(n);if(t===void 0)return null;let r=[],i=new Set,o=s(a=>{if(!i.has(a.key)&&(i.add(a.key),r.push({fieldKey:a.key,kind:a.kind}),a.kind==="computed"))for(let l of a.deps){let d=e.get(l);d!==void 0&&o(d)}},"walk");return o(t),r}s(wH,"expandKey");function kH(e){let n=new Set;for(let t of nP(e))if(!(t.kind!=="person"||t.contractParty===void 0)&&t.when!==void 0)for(let r of On(In(t.when)))n.add(r);return[...n]}s(kH,"contractPartyConditionKeys");function bH(e){return da(e).compiled.flags.map(n=>({key:n.key,name:n.label}))}s(bH,"formExternalFlags");function rP(e){return{readinessFormFieldsByFormNode:new Map([...e].map(([n,t])=>[n,hH(t)])),readinessPartyConditionKeysByFormNode:new Map([...e].map(([n,t])=>[n,new Set(kH(t))])),formFlagKeysByFormNode:new Map([...e].map(([n,t])=>[n,new Set(bH(t).map(r=>r.key))])),formViewKeysByFormNode:new Map([...e].map(([n,t])=>[n,new Set((t.views??[]).map(r=>r.key))]))}}s(rP,"readinessUniverse");function jw(e,n){let t=new Set;for(let r of n)for(let i of wH(e,r)??[])i.kind==="entered"&&t.add(i.fieldKey);return t}s(jw,"enteredFieldsBehind");var vH=new Set(["label","sublabel","title","description","body","chipLabel","nextAction","confirmLabel","placeholder","helpText","subject","heading","hint","notice","reason"]);function xH(e){return vH.has(e)?!0:iP(e)?!1:/(Label|Title|Body|Description|Text|Hint|Heading|Placeholder)$/.test(e)}s(xH,"isTextKey");function iP(e){return/^localized[A-Z]/.test(e)}s(iP,"isLegacyTwinKey");var SH=new Set(["titles","responseLabels","outputLabels","enumOptionLabels"]),AH=new Set(["inputs","resolver","library"]);function vp(e,n){let t=[];return Vw(e,n,t),t}s(vp,"findUnlocalizedTexts");function Vw(e,n,t){if(Array.isArray(e)){e.forEach((i,o)=>Vw(i,`${n}[${TH(i,o)}]`,t));return}if(e===null||typeof e!="object")return;let r=e;for(let[i,o]of Object.entries(r)){let a=`${n}.${i}`;if(!AH.has(i)){if(iP(i)){t.push({path:a,missing:"legacy-twin"});continue}if(xH(i)){EH(o,a,t);continue}if(SH.has(i)&&o!==null&&typeof o=="object"){for(let[l,d]of Object.entries(o))d!==void 0&&oP(d,`${a}.${l}`,t);continue}Vw(o,a,t)}}}s(Vw,"walk");function EH(e,n,t){e!=null&&oP(e,n,t)}s(EH,"checkText");function oP(e,n,t){let r=Rn(e);(r==="not-localized"||r.length>0)&&t.push({path:n,missing:r})}s(oP,"report");function TH(e,n){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.id=="string")return t.id;if(typeof t.key=="string")return t.key}return String(n)}s(TH,"keyOf");function bp(e,n){return e==="not-localized"?n==="de"?"ist kein zweisprachiger Text ({ de, en })":"is not a bilingual text ({ de, en })":e==="legacy-twin"?n==="de"?'ist ein Zwilling der alten Form \u2014 der Text geh\xF6rt in das Feld ohne \u201Elocalized"':'is a twin of the old shape \u2014 the text belongs in the field without "localized"':n==="de"?`fehlt in: ${e.join(", ")}`:`is missing in: ${e.join(", ")}`}s(bp,"describe");function Bw({path:e,missing:n}){return n==="legacy-twin"?{de:`[i18n/legacyTwin] ${e} ${bp(n,"de")}.`,en:`[i18n/legacyTwin] ${e} ${bp(n,"en")}.`}:{de:`[i18n/missingTranslation] ${e} ${bp(n,"de")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch; die Sprache folgt dem Konto des Lesenden.`,en:`[i18n/missingTranslation] ${e} ${bp(n,"en")} \u2014 every displayed text needs German and English; the language follows the reader's account.`}}s(Bw,"unlocalizedTextReason");var $H={engagePush:["engage"]};function RH(e){let n=$H[e.type];return n===void 0?e:Object.fromEntries(Object.entries(e).filter(([t])=>!n.includes(t)))}s(RH,"withoutMachineData");function sP(e,n){return[...vp(e.nodes.map(RH),"nodes"),...n===void 0?[]:vp(n,`layout.${n.id}`)].map(r=>({layer:"GRAPH",kind:"i18n",path:r.path,reason:Bw(r),severity:"error"}))}s(sP,"checkLocalizedTexts");var Lo=5,Mo=480;function di(e){return typeof e=="string"&&e.trim().length>0}s(di,"isNonEmptyString");function lP(e,n,t){return Object.keys(e).filter(r=>!n.includes(r)).map(r=>({field:`result.${r}`,code:Ue.unknownField,message:{de:`Unbekanntes Feld '${r}' im ${t.de}; erlaubt sind: ${n.join(", ")}.`,en:`Unknown field '${r}' in the ${t.en}; allowed: ${n.join(", ")}.`}}))}s(lP,"unknownFieldIssues");function IH(e){let n=[],t=e.title;(t===void 0||typeof t!="object"||t===null||!di(t.de)||!di(t.en))&&n.push({field:"result.title",code:Ue.appointmentMissingTitle,message:{de:"Ein Termin-Ergebnis braucht einen neutralen Titel in beiden Sprachen ({ de, en }) \u2014 er steht in der Mail und in der Kalenderdatei der Familie, deshalb nie ein Familienname.",en:"An appointment result needs a neutral title in both languages ({ de, en }) \u2014 it appears in the email and in the family's calendar file, so never a family name."}});let r=e.durationMinutes;return(typeof r!="number"||!Number.isInteger(r)||r<Lo||r>Mo)&&n.push({field:"result.durationMinutes",code:Ue.appointmentInvalidDuration,message:{de:`'durationMinutes' muss eine ganze Zahl von ${Lo} bis ${Mo} sein, erhalten ${JSON.stringify(r)}.`,en:`'durationMinutes' must be a whole number from ${Lo} to ${Mo}, got ${JSON.stringify(r)}.`}}),n.push(...lP(e,["kind","title","durationMinutes","primaryHostTeams","participants"],{de:"Termin-Ergebnis",en:"appointment result"})),n}s(IH,"appointmentIssues");function aP(e){if(typeof e!="object"||e===null)return!1;let n=e;return di(n.de)&&di(n.en)}s(aP,"isBilingual");var Uw=["key","type","label","writes","options","min","suggest","evidence","evidenceFrom","multiple","tasks","maxLength"];function OH(e,n){let t=s((o,a)=>({field:o,code:Ue.recordFields,message:a}),"issue");if(!Array.isArray(e)||e.length===0)return[t("result.fields",{de:"Eine Erfassung braucht mindestens ein Feld ('result.fields').",en:"A record needs at least one field ('result.fields')."})];let r=[],i=new Set;for(let[o,a]of e.entries()){let l=`result.fields[${o}]`;if(typeof a!="object"||a===null||Array.isArray(a)){r.push(t(l,{de:"Ein Feld der Erfassung muss ein Objekt sein.",en:"A field of the record must be an object."}));continue}let d=a,c=d.key;typeof c!="string"||!/^[a-z][a-zA-Z0-9_]*$/.test(c)?r.push(t(`${l}.key`,{de:`Feld-Schl\xFCssel ${JSON.stringify(c)} \u2014 erlaubt sind Buchstaben, Ziffern und _, beginnend mit einem Kleinbuchstaben.`,en:`Field key ${JSON.stringify(c)} \u2014 letters, digits and _ are allowed, starting with a lowercase letter.`})):i.has(c)?r.push(t(`${l}.key`,{de:`Feld-Schl\xFCssel "${c}" ist doppelt.`,en:`Field key "${c}" is duplicated.`})):i.add(c);let u=typeof c=="string"?`"${c}"`:`Nr. ${o+1}`,p=typeof c=="string"?`"${c}"`:`no. ${o+1}`;if(Dy(d.type)||r.push(t(`${l}.type`,{de:`Feld ${u}: Typ ${JSON.stringify(d.type)} \u2014 erlaubt: ${Nf.join(", ")}.`,en:`Field ${p}: type ${JSON.stringify(d.type)} \u2014 allowed: ${Nf.join(", ")}.`})),aP(d.label)||r.push(t(`${l}.label`,{de:`Feld ${u} braucht ein Label in beiden Sprachen ({ de, en }).`,en:`Field ${p} needs a label in both languages ({ de, en }).`})),di(d.writes)||r.push(t(`${l}.writes`,{de:`Feld ${u} schreibt in keinen Vorgangs-Schl\xFCssel ('writes') \u2014 ein Wert, den niemand lesen kann, geh\xF6rt nicht in eine Erfassung.`,en:`Field ${p} writes to no process key ('writes') \u2014 a value nobody can read does not belong in a record.`})),d.type==="enum"){let y=Array.isArray(d.options)?d.options:[],k=y.map(w=>w.key);(y.length<2||k.some(w=>typeof w!="string"||w.length===0)||new Set(k).size!==k.length||y.some(w=>!aP(w.label)))&&r.push(t(`${l}.options`,{de:`Feld ${u} (Auswahl) braucht mindestens 2 Optionen mit eindeutigen Schl\xFCsseln und Labels in beiden Sprachen.`,en:`Field ${p} (choice) needs at least 2 options with unique keys and labels in both languages.`}))}else d.options!==void 0&&r.push(t(`${l}.options`,{de:`Feld ${u}: 'options' gibt es nur bei Typ 'enum'.`,en:`Field ${p}: 'options' exists only for type 'enum'.`}));if(d.min!==void 0&&(d.type!=="number"||typeof d.min!="number"||!Number.isInteger(d.min))&&r.push(t(`${l}.min`,{de:`Feld ${u}: 'min' gibt es nur bei Typ 'number', als ganze Zahl.`,en:`Field ${p}: 'min' exists only for type 'number', as a whole number.`})),d.evidence!==void 0&&typeof d.evidence!="boolean"&&r.push(t(`${l}.evidence`,{de:`Feld ${u}: 'evidence' ist true oder false.`,en:`Field ${p}: 'evidence' is true or false.`})),d.evidenceFrom!==void 0){let y=typeof d.min=="number"?d.min:0;(d.type!=="number"||d.evidence!==!0||typeof d.evidenceFrom!="number"||!Number.isInteger(d.evidenceFrom)||d.evidenceFrom<=y)&&r.push(t(`${l}.evidenceFrom`,{de:`Feld ${u}: 'evidenceFrom' gibt es nur bei Typ 'number' mit 'evidence', als ganze Zahl \xFCber dem Minimum (${y}) \u2014 sonst g\xE4lte der Nachweis immer.`,en:`Field ${p}: 'evidenceFrom' exists only for type 'number' with 'evidence', as a whole number above the minimum (${y}) \u2014 otherwise the proof would always apply.`}))}if(r.push(..._H(d,l,u,p,n)),d.suggest!==void 0){let y=d.suggest,k=typeof y=="object"&&y!==null?y.kind:void 0,w=k==="form"&&"address"in y&&Object.keys(y).length===2&&(!be(y.address)||un(y.address))||k==="siblingRank"&&Object.keys(y).length===1&&d.type==="number";aO(d.type)?w||r.push({field:`${l}.suggest`,code:Ue.recordSuggest,message:{de:`Feld ${u}: Vorschlag ${JSON.stringify(d.suggest)} \u2014 erlaubt: { kind: 'form', address: '$node.<formular>.admission.<export>' } oder { kind: 'siblingRank' } (nur bei Typ 'number'); bekannte Arten: ${Fy.join(", ")}.`,en:`Field ${p}: suggestion ${JSON.stringify(d.suggest)} \u2014 allowed: { kind: 'form', address: '$node.<form>.admission.<export>' } or { kind: 'siblingRank' } (only for type 'number'); known kinds: ${Fy.join(", ")}.`}}):r.push({field:`${l}.suggest`,code:Ue.recordSuggest,message:{de:`Feld ${u}: einen Vorschlag gibt es nur bei Typ number, boolean oder enum.`,en:`Field ${p}: a suggestion exists only for type number, boolean or enum.`}})}let h=Object.keys(d).filter(y=>!Uw.includes(y));h.length>0&&r.push(t(l,{de:`Feld ${u}: unbekannte Angabe ${h.map(y=>`'${y}'`).join(", ")}; erlaubt: ${Uw.join(", ")}.`,en:`Field ${p}: unknown entry ${h.map(y=>`'${y}'`).join(", ")}; allowed: ${Uw.join(", ")}.`}))}return r}s(OH,"recordFieldIssues");function _H(e,n,t,r,i){let o=[],a=e.maxLength;if(a!==void 0&&(e.type!=="text"||typeof a!="number"||!Number.isInteger(a)||a<1||a>Pf)&&o.push({field:`${n}.maxLength`,code:Ue.recordText,message:{de:`Feld ${t}: 'maxLength' gibt es nur bei Typ 'text', als ganze Zahl von 1 bis ${Pf}.`,en:`Field ${r}: 'maxLength' exists only for type 'text', as a whole number from 1 to ${Pf}.`}}),e.multiple!==void 0&&(e.type!=="person"||typeof e.multiple!="boolean")&&o.push({field:`${n}.multiple`,code:Ue.recordPerson,message:{de:`Feld ${t}: 'multiple' gibt es nur bei Typ 'person', als true oder false.`,en:`Field ${r}: 'multiple' exists only for type 'person', as true or false.`}}),e.type!=="assignment")return e.tasks!==void 0&&o.push({field:`${n}.tasks`,code:Ue.recordAssignment,message:{de:`Feld ${t}: 'tasks' gibt es nur bei Typ 'assignment'.`,en:`Field ${r}: 'tasks' exists only for type 'assignment'.`}}),o;let l=e.tasks;if(!Array.isArray(l)||l.length===0||l.some(d=>typeof d!="string"||d.length===0)||new Set(l).size!==l.length)return o.push({field:`${n}.tasks`,code:Ue.recordAssignment,message:{de:`Feld ${t} (Zuordnung) braucht in 'tasks' mindestens eine Aufgabe, jede einmal.`,en:`Field ${r} (assignment) needs at least one task in 'tasks', each once.`}}),o;if(i.nodeTasks===void 0)return o;for(let d of l){let c=i.nodeTasks.get(d);c?.feedback!==!0&&o.push({field:`${n}.tasks`,code:Ue.recordAssignment,message:c===void 0?{de:`Feld ${t}: "${d}" ist keine Aufgabe dieses Knotens.`,en:`Field ${r}: "${d}" is no task of this node.`}:{de:`Feld ${t}: "${d}" ist keine Feedback-Aufgabe ('feedback: true') \u2014 zugeordnet wird nur, wer eine R\xFCckmeldung gibt.`,en:`Field ${r}: "${d}" is no feedback task ('feedback: true') \u2014 only a person who gives feedback is assigned.`}})}return o}s(_H,"typedFieldIssues");function NH(e,n,t){let r=[],i=n.options;if(e==="choice"){let o=Array.isArray(i)?i:[],a=o.map(l=>l.key);(o.length<2||a.some(l=>typeof l!="string"||l.length===0)||new Set(a).size!==a.length)&&r.push({field:"result.options",code:Ue.choiceOptions,message:{de:`Ein Auswahl-Ergebnis braucht mindestens 2 Optionen mit eindeutigen Schl\xFCsseln, erhalten ${JSON.stringify(a)}.`,en:`A choice result needs at least 2 options with unique keys, got ${JSON.stringify(a)}.`}})}else i!==void 0&&r.push({field:"result.options",code:Ue.choiceOptions,message:{de:`'result.options' gibt es nur bei 'choice' \u2014 ${e==="recommendation"?"eine Empfehlung hat die festen Tendenzen Positiv/Neutral/Negativ":"ein Freitext hat keine Auswahl"}.`,en:`'result.options' exists only for 'choice' \u2014 ${e==="recommendation"?"a recommendation has the fixed leanings Positive/Neutral/Negative":"a free text has no choice"}.`}});if(e==="pricedItem"){let o=n.item;if(!di(o))r.push({field:"result.item",code:Ue.pricedItemMissingItem,message:{de:"Ein Preispositions-Ergebnis nennt den Artikel, den es bepreist \u2014 'result.item' (der Schl\xFCssel des Artikels, z. B. 'tuition') fehlt.",en:"A priced-item result names the article it prices \u2014 'result.item' (the article's key, e.g. 'tuition') is missing."}});else if(t.billingItemKeys!==void 0&&!t.billingItemKeys.has(o))r.push({field:"result.item",code:Ue.pricedItemUnknownItem,message:{de:`'result.item' "${o}" \u2014 kein Artikel dieses Mandanten tr\xE4gt diesen Schl\xFCssel (bekannt: ${[...t.billingItemKeys].join(", ")||"keine"}).`,en:`'result.item' "${o}" \u2014 no article of this school has this key (known: ${[...t.billingItemKeys].join(", ")||"none"}).`}});else if(t.offerProgram===null)r.push({field:"result.item",code:Ue.pricedItemOfferWithoutProgram,message:{de:`'result.item' "${o}" \u2014 das Angebot ist keinem Programm zugeordnet, also geh\xF6rt kein Artikel zu ihm; dem Angebot ein Programm geben.`,en:`'result.item' "${o}" \u2014 the offer is not assigned to a program, so no article belongs to it; give the offer a program.`}});else if(t.offerProgram!==void 0&&!t.offerProgram.billingItemKeys.has(o)){let l=t.offerProgram;r.push({field:"result.item",code:Ue.pricedItemNotInProgram,message:{de:`'result.item' "${o}" \u2014 der Artikel ist dem Programm \u201E${l.nameDe}\u201C des Angebots nicht zugeordnet (zugeordnet: ${[...l.billingItemKeys].join(", ")||"keine"}); unter Finanzen \u2192 Artikel zuordnen, direkt oder \xFCber ein Paket.`,en:`'result.item' "${o}" \u2014 the article is not assigned to the offer's program "${l.nameDe}" (assigned: ${[...l.billingItemKeys].join(", ")||"none"}); assign it under Finance \u2192 articles, directly or through a package.`}})}let a=n.label;(typeof a!="object"||a===null||!di(a.de)||!di(a.en))&&r.push({field:"result.label",code:Ue.labelMissing,message:{de:"Ein Preispositions-Ergebnis braucht einen Namen f\xFCr seinen Wert in beiden Sprachen ('result.label', z. B. { de: 'Schulgeld mit Erm\xE4\xDFigung', en: 'Tuition after reduction' }) \u2014 so hei\xDFt er im Workflow und in der Verdrahtung.",en:"A priced-item result needs a name for its value in both languages ('result.label', e.g. { de: 'Schulgeld mit Erm\xE4\xDFigung', en: 'Tuition after reduction' }) \u2014 that is what it is called in the workflow and in the wiring."}})}else n.item!==void 0&&r.push({field:"result.item",code:Ue.itemOnNonPricedItem,message:{de:`'result.item' gibt es nur bei 'pricedItem' \u2014 ein ${e}-Ergebnis bepreist keinen Artikel.`,en:`'result.item' exists only for 'pricedItem' \u2014 a ${e} result prices no article.`}});if(e==="record"?(r.push(...OH(n.fields,t)),n.writes!==void 0&&r.push({field:"result.writes",code:Ue.writesOnProse,message:{de:"Eine Erfassung schreibt je Feld ('fields[].writes'), nie als Ganzes ('result.writes').",en:"A record writes per field ('fields[].writes'), never as a whole ('result.writes')."}}),n.label!==void 0&&r.push({field:"result.label",code:Ue.unknownField,message:{de:"Eine Erfassung benennt ihre Werte je Feld ('fields[].label'), nicht als Ganzes ('result.label').",en:"A record names its values per field ('fields[].label'), not as a whole ('result.label')."}})):n.fields!==void 0&&r.push({field:"result.fields",code:Ue.fieldsOnNonRecord,message:{de:`'result.fields' gibt es nur bei 'record' \u2014 ein ${e}-Ergebnis hat keine Felder.`,en:`'result.fields' exists only for 'record' \u2014 a ${e} result has no fields.`}}),e==="reduction"&&(di(n.writes)||r.push({field:"result.writes",code:Ue.reductionPrices,message:{de:"Eine Reduktion schreibt ihren Betrag in einen Vorgangs-Schl\xFCssel vom Typ reduction ('result.writes') \u2014 sonst l\xE4se ihn kein Preis.",en:"A reduction writes its amount to a process key of type reduction ('result.writes') \u2014 otherwise no price would read it."}})),n.writes!==void 0&&(e==="freetext"||e==="recommendation")&&r.push({field:"result.writes",code:Ue.writesOnProse,message:{de:`'result.writes' gibt es nur bei Ergebnissen mit Wert (Auswahl, Preisposition) \u2014 ein ${e}-Ergebnis bleibt im Chat und schreibt nichts in den Vorgang.`,en:`'result.writes' exists only for results with a value (choice, priced item) \u2014 a ${e} result stays in the chat and writes nothing to the process.`}}),e==="freetext"&&n.textRequired!==void 0&&r.push({field:"result.textRequired",code:Ue.textRequiredOnFreetext,message:{de:"'textRequired' auf einem Freitext-Ergebnis \u2014 der Text eines Freitexts ist immer Pflicht; die Angabe entfernen.",en:"'textRequired' on a free-text result \u2014 the text of a free text is always required; remove the entry."}}),n.chat===void 0)r.push({field:"result.chat",code:Ue.chatMissing,message:{de:"Ein Aufgaben-Ergebnis steht nur im Chat \u2014 'result.chat' fehlt: 'all', 'team:<Gruppe>' oder einen Kanal des Workflows angeben.",en:"A task result appears only in the chat \u2014 'result.chat' is missing: give 'all', 'team:<group>' or a channel of the workflow."}});else{let o=n.chat,a=typeof o=="string"?Ms(o):null;o==="external"||a===null?r.push({field:"result.chat",code:Ue.chatExternal,message:{de:`'result.chat' ${JSON.stringify(o)} \u2014 ein Aufgaben-Ergebnis bleibt intern: erlaubt sind 'all', 'team:<Gruppe>' oder ein Kanal des Workflows, nie 'external'.`,en:`'result.chat' ${JSON.stringify(o)} \u2014 a task result stays internal: 'all', 'team:<group>' or a channel of the workflow are allowed, never 'external'.`}}):a.kind==="channel"&&!t.channelKeys.has(a.channelKey)&&r.push({field:"result.chat",code:Ue.chatUnknownChannel,message:{de:`'result.chat' "${a.channelKey}" ist weder 'all' noch 'team:<Gruppe>' noch ein Kanal des Workflows (bekannt: ${[...t.channelKeys].join(", ")||"keine"}).`,en:`'result.chat' "${a.channelKey}" is neither 'all' nor 'team:<group>' nor a channel of the workflow (known: ${[...t.channelKeys].join(", ")||"none"}).`}})}return r.push(...lP(n,["kind","options","textRequired","chat","item","label","writes","fields","prices"],{de:"Aufgaben-Ergebnis",en:"task result"})),r}s(NH,"recordedIssues");function dP(e,n,t={channelKeys:new Set}){if(n===void 0)return[];if(e!=="task")return[{field:"result",code:Ue.onApproval,message:{de:`'result' gilt nur f\xFCr die Art 'task' \u2014 eine '${e}' wird durch ihr Votum abgeschlossen, nicht durch ein Ergebnis.`,en:`'result' applies only to the kind 'task' \u2014 an '${e}' is completed by its vote, not by a result.`}}];if(typeof n!="object"||n===null||Array.isArray(n))return[{field:"result",code:Ue.unknownKind,message:{de:`'result' muss ein Objekt mit 'kind' sein; bekannte Arten: ${Fs.join(", ")}.`,en:`'result' must be an object with 'kind'; known kinds: ${Fs.join(", ")}.`}}];let r=n;return sO(r.kind)?r.kind==="appointment"?IH(r):NH(r.kind,r,t):[{field:"result.kind",code:Ue.unknownKind,message:{de:`Unbekannte Ergebnisart ${JSON.stringify(r.kind)}; bekannte Arten: ${Fs.join(", ")}.`,en:`Unknown result kind ${JSON.stringify(r.kind)}; known kinds: ${Fs.join(", ")}.`}}]}s(dP,"taskResultIssues");var Gw=60;function ci(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"error"}}s(ci,"error");function PH(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"warning"}}s(PH,"warning");function cP(e){return Array.isArray(e.tasks)?e.tasks:[]}s(cP,"tasksOf");function fP(e,n){return(Array.isArray(e.optionalActions)?e.optionalActions:[]).filter(r=>r.action==="spawnTasks"&&Array.isArray(r.tasks)&&r.tasks.includes(n))}s(fP,"spawnActionsOf");function uP(e,n){return fP(e,n).map(t=>String(t.key)).sort()}s(uP,"bindingsOf");function pP(e,n){let t=[],r=cP(e),i=new Map;for(let o of r){if(o.appointment===void 0)continue;let a=typeof o.key=="string"?o.key:"?",l=`nodes.${e.id}.tasks.${a}`,d={de:`Terminaufgabe "${a}" (Knoten "${e.id}")`,en:`Appointment task "${a}" (node "${e.id}")`},c=o.appointment,p=typeof c=="object"&&c!==null&&Object.keys(c).every(P=>P==="of"||P==="dueDaysAfterEnd")&&typeof c.of=="string"?c.of:void 0,h=p===void 0?void 0:r.find(P=>P.key===p),y=h?.result;if(p===void 0||h===void 0||y?.kind!=="appointment")t.push(ci(`${l}.appointment.of`,{de:`[workItems/appointmentOfUnknown] ${d.de} braucht 'appointment: { of, dueDaysAfterEnd }', und 'of' nennt eine Aufgabe desselben Knotens, die mit einem Termin abschlie\xDFt (result.kind 'appointment'); erhalten ${JSON.stringify(o.appointment)}.`,en:`[workItems/appointmentOfUnknown] ${d.en} needs 'appointment: { of, dueDaysAfterEnd }', and 'of' names a task of the same node that ends with an appointment (result.kind 'appointment'); got ${JSON.stringify(o.appointment)}.`}));else{i.set(p,(i.get(p)??0)+1);let P=h.blocks,F=[...["when","optional"].filter(b=>h[b]!==void 0),...typeof P?.node=="string"&&P.node!==e.id?["blocks"]:[]];F.length>0&&t.push(ci(`nodes.${e.id}.tasks.${p}.${F[0]}`,{de:`[workItems/appointmentTaskShape] "${p}" bucht den Termin f\xFCr ${d.de} und tr\xE4gt ${F.map(b=>b==="blocks"?"ein knoten\xFCbergreifendes 'blocks'":`'${b}'`).join(", ")} \u2014 fiele sie ohne Buchung weg oder \xFCberlebte sie ihren Knoten, wartete die Terminaufgabe f\xFCr immer bzw. f\xE4nde die Buchung keine Terminaufgabe mehr.`,en:`[workItems/appointmentTaskShape] "${p}" books the appointment for ${d.en} and carries ${F.map(b=>b==="blocks"?"a cross-node 'blocks'":`'${b}'`).join(", ")} \u2014 if it dropped out without a booking or outlived its node, the appointment task would wait forever or the booking would find no appointment task any more.`}));for(let b of fP(e,p))b.repeatable!==!0&&t.push(ci(`nodes.${e.id}.optionalActions.${String(b.key)}.repeatable`,{de:`[workItems/appointmentActionRepeatable] Die optionale Aktion "${String(b.key)}" legt "${p}" an, die den Termin f\xFCr ${d.de} bucht, und ist nicht 'repeatable: true'. Eine Absage beendet die Runde; ohne zweite Runde lie\xDFe sich die Aktion nie wieder ausl\xF6sen, und eine Entscheidung, die auf sie wartet (requiresOneOf), bliebe h\xE4ngen.`,en:`[workItems/appointmentActionRepeatable] The optional action "${String(b.key)}" creates "${p}", which books the appointment for ${d.en}, and is not 'repeatable: true'. A cancellation ends the round; without a second round the action could never be triggered again, and a decision waiting for it (requiresOneOf) would hang.`}));uP(e,a).join(",")!==uP(e,p).join(",")&&t.push(ci(`${l}.appointment.of`,{de:`[workItems/appointmentTaskBinding] ${d.de} geh\xF6rt zu anderen optionalen Aktionen als "${p}", die ihren Termin bucht \u2014 beide Zeilen sind eine Runde: entweder beide in derselben Aktion (spawnTasks) oder beide in keiner.`,en:`[workItems/appointmentTaskBinding] ${d.en} belongs to different optional actions than "${p}", which books its appointment \u2014 both rows are one round: either both in the same action (spawnTasks) or both in none.`}))}let k=c?.dueDaysAfterEnd;(typeof k!="number"||!Number.isInteger(k)||k<0||k>Gw)&&t.push(ci(`${l}.appointment.dueDaysAfterEnd`,{de:`[workItems/appointmentTaskDue] ${d.de}: 'dueDaysAfterEnd' ist eine ganze Zahl von 0 bis ${Gw} \u2014 die Tage nach dem Terminende, bis die Aufgabe f\xE4llig ist; erhalten ${JSON.stringify(k)}.`,en:`[workItems/appointmentTaskDue] ${d.en}: 'dueDaysAfterEnd' is a whole number from 0 to ${Gw} \u2014 the days after the appointment ends until the task is due; got ${JSON.stringify(k)}.`})),o.params?.dueInDays!==void 0&&t.push(ci(`${l}.params.dueInDays`,{de:`[workItems/appointmentTaskDue] ${d.de} tr\xE4gt 'params.dueInDays' neben 'appointment.dueDaysAfterEnd' \u2014 eine Terminaufgabe ist ab dem Terminende f\xE4llig, nie ab ihrer Anlage.`,en:`[workItems/appointmentTaskDue] ${d.en} carries 'params.dueInDays' next to 'appointment.dueDaysAfterEnd' \u2014 an appointment task is due from the end of the appointment, never from its creation.`}));let w=o.result,v=["when","optional","familyRequest","reads","locksEvidence"].filter(P=>o[P]!==void 0).map(P=>`'${P}'`),A=typeof o.blocks?.node=="string"&&o.blocks.node!==e.id,E=s(P=>[...o.kind!=="task"?["'kind: approval'"]:[],...w===void 0||!Mi(w.kind)?[P==="de"?"kein erfasstes Ergebnis (Feedback)":"no recorded result (feedback)"]:[],...v,...A?[P==="de"?"ein knoten\xFCbergreifendes 'blocks'":"a cross-node 'blocks'"]:[]],"shapeFaults");E("de").length>0&&t.push(ci(`${l}.appointment`,{de:`[workItems/appointmentTaskShape] ${d.de}: ${E("de").join(", ")} \u2014 eine Terminaufgabe ist eine Aufgabe, die mit ihrem Feedback (Freitext, Empfehlung, Auswahl) abschlie\xDFt, und sie entsteht, weil der Termin entsteht: ohne Bedingung, nicht optional, keine Nachforderung, ohne Belege (nichts l\xE4sst sie ungebunden neu entstehen) und an ihrem Knoten.`,en:`[workItems/appointmentTaskShape] ${d.en}: ${E("en").join(", ")} \u2014 an appointment task is a task that ends with its feedback (free text, recommendation, choice), and it exists because the appointment exists: no condition, not optional, no follow-up request, no evidence (nothing lets it be created again unbound) and on its own node.`}));let R=o.result?.chat;typeof R=="string"&&R.startsWith("team:")&&t.push(PH(`${l}.result.chat`,{de:`[workItems/appointmentChatUnreadable] ${d.de} schreibt ihr Feedback in "${R}" \u2014 Gastgeberin bzw. Gastgeber kann jede Mitarbeiterin und jeder Mitarbeiter sein und liest das eigene Feedback dort nur als Mitglied dieses Teams. 'all' w\xE4hlen, damit jede Gastgeberin bzw. jeder Gastgeber es liest.`,en:`[workItems/appointmentChatUnreadable] ${d.en} writes its feedback to "${R}" \u2014 any staff member can be the host and reads their own feedback there only as a member of that team. Choose 'all' so every host reads it.`}));for(let P of n)for(let F of cP(P)){let b=F.blocks;b?.templateKey!==a||(typeof b.node=="string"?b.node:P.id)!==e.id||t.push(ci(`nodes.${P.id}.tasks.${String(F.key)}.blocks.templateKey`,{de:`[workItems/appointmentTaskBlocked] Task "${String(F.key)}" (Knoten "${P.id}") h\xE4lt ${d.de} zur\xFCck \u2014 eine Terminaufgabe wartet nur auf ihren Termin (abgeleitet aus 'appointment.of'); ein 'blocks' auf sie entf\xE4llt.`,en:`[workItems/appointmentTaskBlocked] Task "${String(F.key)}" (node "${P.id}") holds back ${d.en} \u2014 an appointment task only waits for its appointment (derived from 'appointment.of'); a 'blocks' on it is dropped.`}))}}for(let[o,a]of i)a<2||t.push(ci(`nodes.${e.id}.tasks.${o}`,{de:`[workItems/appointmentOfTwice] ${a} Terminaufgaben auf Knoten "${e.id}" geh\xF6ren zum Termin von "${o}" \u2014 ein Termin hat eine Terminaufgabe.`,en:`[workItems/appointmentOfTwice] ${a} appointment tasks on node "${e.id}" belong to the appointment of "${o}" \u2014 an appointment has one appointment task.`}));return t}s(pP,"appointmentTaskIssues");var CH="optionalAction:";function mP(e){return`${CH}${e}:trigger`}s(mP,"optionalActionTriggerActionId");var DH="processDecide";function hP(e){let n=e.optionalActions;return n==null?[]:(Array.isArray(n)||L(`[optionalAction/corrupt-section] node's 'optionalActions' is ${typeof n}, not an array \u2014 corrupt pinned graph (publish stores the section as authored)`),n)}s(hP,"optionalActionBindings");function gP(e){return hP(e).map(n=>({id:mP(n.key),kind:"internal",label:n.label,surface:DH,placement:"overflow",superUserOnly:!0}))}s(gP,"optionalActionTriggers");function yP(e){let n=e.tasks;return Array.isArray(n)?n:[]}s(yP,"authoredTemplates");function wP(e){let n=e?.result;return n?.kind!=="appointment"?[]:n.participants?.feedback?.tasks??[]}s(wP,"personTasksOf");function zw(e){let n=yP(e);return hP(e).map(t=>{let r=new Set(t.tasks??[]),i=new Set;for(let o of r)for(let a of wP(n.find(l=>l.key===o)))i.add(a);return{binding:t,tasks:r,personTasks:i,keys:new Set([...r,...i])}})}s(zw,"optionalActionMembership");function FH(e){let n=new Set;for(let t of yP(e))for(let r of wP(t))n.add(r);return n}s(FH,"personRowTemplateKeys");function kP(e){let n=new Set(FH(e));for(let{keys:t}of zw(e))for(let r of t)n.add(r);return n}s(kP,"referencedTaskTemplateKeys");var br={shape:"[taskInput/shape]",notInRound:"[taskInput/notInRound]",notRecord:"[taskInput/notRecord]",prefillNotDeclared:"[taskInput/prefillNotDeclared]",prefillType:"[taskInput/prefillType]",feedbackTasks:"[appointment/feedbackTasks]",feedbackOptional:"[appointment/feedbackOptional]",recordAssignment:"[taskResult/recordAssignment]"},Ww=60;function ui(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:`${n} ${t.de}`,en:`${n} ${t.en}`},severity:"error"}}s(ui,"error");function ca(e){return Array.isArray(e.tasks)?e.tasks:[]}s(ca,"tasksOf");function LH(e){return(Array.isArray(e.optionalActions)?e.optionalActions:[]).filter(t=>t.action==="spawnTasks")}s(LH,"spawnBindingsOf");function Xl(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}s(Xl,"stringList");function qr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}s(qr,"record");function Yw(e){let n=qr(e?.result);return n?.kind==="appointment"?qr(n.participants):null}s(Yw,"participantsOf");function bP(e){return Xl(qr(Yw(e)?.feedback)?.tasks)}s(bP,"feedbackTasksOf");function vP(e,n){return zw(e).find(t=>t.keys.has(n))}s(vP,"roundOf");function MH(e,n,t){let r=s(u=>({code:br.notInRound,reason:u}),"notInRound"),i=vP(e,n);if(i===void 0)return r({de:`Aufgabe "${n}" geh\xF6rt zu keiner optionalen Aktion \u2014 Vorgaben liest nur eine Aufgabe einer Runde.`,en:`Task "${n}" belongs to no optional action \u2014 only a task of a round reads inputs.`});if(t.scope!=="task"||t.path!==void 0)return r({de:`${ue(t)} ist kein Wert einer Aufgabe ($task.<aufgabe>.<schl\xFCssel>).`,en:`${ue(t)} is no value of a task ($task.<task>.<key>).`});let{binding:o}=i,a=t.owner;if(a===n)return r({de:`Aufgabe "${n}" liest ihren eigenen Wert.`,en:`Task "${n}" reads its own value.`});let l=ca(e).find(u=>u.key===a),d=qr(l?.blocks),c=i.tasks.has(a)&&d?.templateKey===n&&(d.node===void 0||d.node===e.id);return a!==o.input&&!c?r({de:`"${a}" ist weder die Eingabe der Aktion "${o.key}" noch eine ihrer Aufgaben, die "${n}" per 'blocks' zur\xFCckh\xE4lt \u2014 der Wert st\xFCnde nicht fest, wenn die Aufgabe \xF6ffnet.`,en:`"${a}" is neither the input of the action "${o.key}" nor one of its tasks that holds "${n}" through 'blocks' \u2014 the value would not be settled when the task opens.`}):qr(l?.result)?.kind!=="record"?{code:br.notRecord,reason:{de:`"${a}" hat kein Ergebnis vom Typ 'record' \u2014 Vorgaben sind Felder einer Eingabe.`,en:`"${a}" has no result of kind 'record' \u2014 inputs are fields of an input task.`}}:null}s(MH,"taskInputRefusal");function qH(e,n){if(n.scope!=="task")return;let t=ca(e).find(i=>i.key===n.owner),r=qr(t?.result);if(r?.kind==="record")return(Array.isArray(r.fields)?r.fields:[]).map(qr).find(i=>i?.writes===n.key)??void 0}s(qH,"writerField");function KH(e,n,t){let r=String(n.key);if(n.inputs===void 0)return[];if(!Array.isArray(n.inputs))return[ui(`${t}.inputs`,br.shape,{de:"'inputs' ist eine Liste von Adressen.",en:"'inputs' is a list of addresses."})];let i=[],o=new Set;for(let[a,l]of n.inputs.entries()){if(!be(l))continue;let d=ue(l);if(o.has(d)){i.push(ui(`${t}.inputs.${a}`,br.shape,{de:`${d} steht zweimal in 'inputs'.`,en:`${d} is listed twice in 'inputs'.`}));continue}o.add(d);let c=MH(e,r,l);c!==null&&i.push(ui(`${t}.inputs.${a}`,c.code,c.reason))}return i}s(KH,"inputIssues");function jH(e,n,t,r){let o=Yw(t)?.prefill;if(o===void 0)return[];let a=`${r}.result.participants.prefill`,l=Array.isArray(t.inputs)?t.inputs.filter(be).map(ue):[];if(!be(o)||!l.includes(ue(o)))return[ui(a,br.prefillNotDeclared,{de:"Die Vorbelegung der Teilnehmenden ist keine der Vorgaben ('inputs') der Aufgabe.",en:"The participants' prefill is none of the task's inputs ('inputs')."})];let d=bP(t),c=_l(e,o);if(c===void 0)return[];if(tt(c)==="staffUser")return d.length===1?[]:[ui(a,br.prefillType,{de:"Eine Personenliste belegt nur vor, wenn 'feedback.tasks' genau eine Feedback-Art nennt \u2014 sonst w\xE4re offen, wer welche Art gibt.",en:"A list of persons prefills only when 'feedback.tasks' names exactly one feedback kind \u2014 otherwise who gives which kind would be open."})];if(c==="taskAssignment"){let h=Xl(qH(n,o)?.tasks).filter(y=>!d.includes(y));return h.length===0?[]:[ui(a,br.prefillType,{de:`Die Zuordnung ordnet ${h.map(y=>`"${y}"`).join(", ")} zu, die 'feedback.tasks' nicht nennt.`,en:`The assignment assigns ${h.map(y=>`"${y}"`).join(", ")}, which 'feedback.tasks' does not name.`})]}return[ui(a,br.prefillType,{de:`Vorbelegt werden Teilnehmende nur aus Personen ('person') oder einer Zuordnung ('assignment'), nicht aus "${c}".`,en:`Participants are prefilled only from persons ('person') or an assignment ('assignment'), not from "${c}".`})]}s(jH,"prefillIssues");function VH(e,n,t){let r=Yw(n);if(r===null||r.feedback===void 0)return[];let i=String(n.key),o=`${t}.result.participants.feedback`,a=qr(r.feedback),l=a?.tasks,d=[],c=s((y,k,w=br.feedbackTasks)=>d.push(ui(y,w,k)),"fail");if(!Array.isArray(l)||l.length===0||l.some(y=>typeof y!="string")||new Set(l).size!==l.length)return c(`${o}.tasks`,{de:"'feedback.tasks' nennt mindestens eine Feedback-Aufgabe, jede einmal.",en:"'feedback.tasks' names at least one feedback task, each once."}),d;let u=a?.dueDaysAfterEnd;(typeof u!="number"||!Number.isInteger(u)||u<0||u>Ww)&&c(`${o}.dueDaysAfterEnd`,{de:`'feedback.dueDaysAfterEnd' ist eine ganze Zahl von 0 bis ${Ww}.`,en:`'feedback.dueDaysAfterEnd' is a whole number from 0 to ${Ww}.`});let p=LH(e);p.some(y=>Xl(y.tasks).includes(i))||c(o,{de:`Aufgabe "${i}" legt Personenzeilen an, geh\xF6rt aber zu keiner optionalen Aktion \u2014 Personenzeilen geh\xF6ren zur Runde einer Aktion.`,en:`Task "${i}" creates person rows but belongs to no optional action \u2014 person rows belong to an action's round.`});let h=new Map(ca(e).map(y=>[y.key,y]));for(let y of l){let k=h.get(y),w=`${o}.tasks`;if(k===void 0){c(w,{de:`"${y}" ist keine Aufgabe dieses Knotens.`,en:`"${y}" is no task of this node.`});continue}k.feedback!==!0&&c(w,{de:`"${y}" ist keine Feedback-Aufgabe ('feedback: true').`,en:`"${y}" is no feedback task ('feedback: true').`}),p.some(E=>Xl(E.tasks).includes(y))&&c(w,{de:`"${y}" steht in den Aufgaben einer optionalen Aktion \u2014 eine Personenzeile entsteht nur beim Buchen.`,en:`"${y}" is among an optional action's tasks \u2014 a person row exists only through a booking.`});let v=ca(e).find(E=>E!==n&&bP(E).includes(y));v!==void 0&&c(w,{de:`"${y}" wird auch von "${String(v.key)}" angelegt \u2014 jede Feedback-Art geh\xF6rt zu genau einem Termin.`,en:`"${y}" is also created by "${String(v.key)}" \u2014 each feedback kind belongs to exactly one appointment.`});let A=["when","blocks","appointment"].filter(E=>k[E]!==void 0);A.length>0&&c(w,{de:`"${y}" tr\xE4gt ${A.map(E=>`'${E}'`).join(", ")} \u2014 eine Personenzeile entsteht nur beim Buchen und h\xE4lt nur ihre Runde.`,en:`"${y}" carries ${A.map(E=>`'${E}'`).join(", ")} \u2014 a person row exists only through a booking and holds only its round.`}),k.optional!==void 0&&c(w,{de:`"${y}" ist optional \u2014 eine Personenzeile h\xE4lt ihre Runde und damit die Pause, sie kann nicht \xFCbersprungen werden.`,en:`"${y}" is optional \u2014 a person row holds its round and with it the pause; it cannot be skipped.`},br.feedbackOptional)}return d}s(VH,"feedbackIssues");function BH(e,n,t){let r=qr(n.result);if(r?.kind!=="record"||!Array.isArray(r.fields))return[];let i=vP(e,String(n.key))?.personTasks??new Set,o=new Map(ca(e).map(l=>[l.key,l])),a=[];for(let[l,d]of r.fields.entries()){let c=qr(d);if(c?.type!=="assignment")continue;let u=Xl(c.tasks).filter(p=>o.get(p)?.feedback===!0&&!i.has(p));u.length!==0&&a.push(ui(`${t}.result.fields.${l}.tasks`,br.recordAssignment,{de:`Feld "${String(c.key)}": ${u.map(p=>`"${p}"`).join(", ")} legt kein Termin derselben optionalen Aktion an ('participants.feedback.tasks') \u2014 die Zuordnung h\xE4tte keine Zeile, die sie erh\xE4lt.`,en:`Field "${String(c.key)}": ${u.map(p=>`"${p}"`).join(", ")} is created by no appointment of the same optional action ('participants.feedback.tasks') \u2014 the assignment would have no row to receive it.`}))}return a}s(BH,"assignmentIssues");function xP(e,n){let t=[];for(let r of ca(n)){if(typeof r.key!="string")continue;let i=`nodes.${n.id}.tasks.${r.key}`;t.push(...KH(n,r,i)),t.push(...jH(e,n,r,i)),t.push(...VH(n,r,i)),t.push(...BH(n,r,i))}return t}s(xP,"taskInputIssues");var St={notOptionalAction:"[workItems/familyRequestNotOptionalAction]",notTask:"[workItems/familyRequestNotTask]",closedOtherwise:"[workItems/familyRequestClosedOtherwise]",blocks:"[workItems/familyRequestBlocks]",noDeadline:"[workItems/familyRequestNoDeadline]",fields:"[workItems/familyRequestFields]",unknownField:"[workItems/familyRequestUnknownField]",shape:"[workItems/familyRequestShape]",twicePerAction:"[workItems/familyRequestTwicePerAction]",deadlock:"[workItems/familyRequestOnlyWayButAsked]"};function At(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:`${n} ${t.de}`,en:`${n} ${t.en}`},severity:"error"}}s(At,"issue");function UH(e,n,t){return e.flatMap(r=>(Array.isArray(r.tasks)?r.tasks:[]).filter(i=>{let o=i.blocks,a=typeof o?.node=="string"?o.node:r.id;return o?.templateKey===t&&a===n}).map(i=>({nodeId:r.id,key:String(i.key)})))}s(UH,"blockersOf");function SP(e){let{graph:n,node:t,task:r}=e,i=r.familyRequest;if(i===void 0)return[];let o=typeof r.key=="string"?r.key:"?",a=`nodes.${t.id}.tasks.${o}`,l={de:`Task "${o}" auf Knoten \u201E${_e(n,t.id,"de")}\u201C (${t.id})`,en:`Task "${o}" on node "${_e(n,t.id,"en")}" (${t.id})`},d=[];if(typeof i!="object"||i===null||Array.isArray(i))return[At(`${a}.familyRequest`,St.shape,{de:`${l.de}: 'familyRequest' muss ein Objekt { fields } oder { from } sein.`,en:`${l.en}: 'familyRequest' must be an object { fields } or { from }.`})];let c=Object.keys(i).filter(k=>k!=="fields"&&k!=="from");c.length>0&&d.push(At(`${a}.familyRequest.${c[0]}`,St.shape,{de:`${l.de}: 'familyRequest' kennt nur 'fields' oder 'from', nicht ${c.map(k=>`'${k}'`).join(", ")} \u2014 was angefordert wird und der Text an die Familie werden beim Ausl\xF6sen gew\xE4hlt.`,en:`${l.en}: 'familyRequest' only knows 'fields' or 'from', not ${c.map(k=>`'${k}'`).join(", ")} \u2014 what is requested and the text to the family are chosen when the action is triggered.`}));let{fields:u,from:p}=i;u===void 0==(p===void 0)&&d.push(At(`${a}.familyRequest`,St.shape,{de:`${l.de}: 'familyRequest' nennt genau eines \u2014 'fields' (die anforderbaren Felder) oder 'from' (das Formular, dessen Dateifelder alle zur Wahl stehen).`,en:`${l.en}: 'familyRequest' names exactly one \u2014 'fields' (the fields that can be requested) or 'from' (the form whose file fields are all available).`})),e.onTrigger.has(o)||d.push(At(`${a}.familyRequest`,St.notOptionalAction,{de:`${l.de} fordert bei der Familie an, geh\xF6rt aber zu keiner optionalen Aktion (spawnTasks) \u2014 nur deren Ausl\xF6sen \xF6ffnet die Anfrage an die Familie.`,en:`${l.en} requests from the family but belongs to no optional action (spawnTasks) \u2014 only triggering one opens the request to the family.`})),r.kind!=="task"&&d.push(At(`${a}.kind`,St.notTask,{de:`${l.de} fordert bei der Familie an und muss die Art 'task' haben, nicht ${JSON.stringify(r.kind)}.`,en:`${l.en} requests from the family and must have the kind 'task', not ${JSON.stringify(r.kind)}.`}));for(let k of["result","when","locksEvidence","gatesNode"])r[k]!==void 0&&d.push(At(`${a}.${k}`,St.closedOtherwise,{de:`${l.de} wartet auf die Familie und erledigt sich mit ihrer Antwort \u2014 '${k}' passt nicht dazu.`,en:`${l.en} waits for the family and completes with their answer \u2014 '${k}' does not fit that.`}));r.blocks!==void 0&&d.push(At(`${a}.blocks`,St.blocks,{de:`${l.de} wartet auf die Familie und darf nichts zur\xFCckhalten ('blocks') \u2014 sie h\xE4lt ihren Knoten schon als Aufgabe einer optionalen Aktion.`,en:`${l.en} waits for the family and must not hold anything back ('blocks') \u2014 as the task of an optional action it already holds its node.`}));for(let k of UH(n.nodes,t.id,o))d.push(At(`nodes.${k.nodeId}.tasks.${k.key}.blocks`,St.blocks,{de:`Task "${k.key}" auf Knoten "${k.nodeId}" h\xE4lt ${l.de} zur\xFCck \u2014 eine Nachforderung darf nie zur\xFCckgehalten werden: zur\xFCckgehalten h\xE4tte sie keine Frist und k\xF6nnte mit der Antwort der Familie nicht erledigt werden.`,en:`Task "${k.key}" on node "${k.nodeId}" holds back ${l.en} \u2014 a follow-up request must never be held back: held back, it would have no deadline and could not be completed by the family's answer.`}));let h=r.params?.dueInDays;if((typeof h!="number"||!Number.isInteger(h)||h<1)&&d.push(At(`${a}.params.dueInDays`,St.noDeadline,{de:`${l.de} fordert bei der Familie an und braucht eine Frist in ganzen Tagen ('params.dueInDays' \u2265 1) \u2014 sie ist die Frist der Familie und Anlass der Erinnerung.`,en:`${l.en} requests from the family and needs a deadline in whole days ('params.dueInDays' \u2265 1) \u2014 it is the family's deadline and the reason for the reminder.`})),u===void 0)return d;if(!Array.isArray(u)||u.length===0)return d.push(At(`${a}.familyRequest.fields`,St.fields,{de:`${l.de}: 'familyRequest.fields' muss mindestens ein Feld eines Formulars nennen \u2014 oder statt dessen 'from' das Formular, dann stehen alle seine Dateifelder zur Wahl.`,en:`${l.en}: 'familyRequest.fields' must name at least one field of a form \u2014 or 'from' the form instead, then all its file fields are available.`})),d;let y=new Set;for(let k of u){if(!be(k))continue;let w=ue(k);if(y.has(w)){d.push(At(`${a}.familyRequest.fields`,St.fields,{de:`${l.de}: 'familyRequest.fields' nennt ${je(n,k,"de")} mehrfach.`,en:`${l.en}: 'familyRequest.fields' names ${je(n,k,"en")} more than once.`}));continue}y.add(w),un(k)||d.push(At(`${a}.familyRequest.fields`,St.unknownField,{de:`${l.de}: 'familyRequest.fields' nennt ${je(n,k,"de")} \u2014 anfordern l\xE4sst sich nur ein Feld eines Formulars ($node.<formular>.admission.<feld>).`,en:`${l.en}: 'familyRequest.fields' names ${je(n,k,"en")} \u2014 only a field of a form ($node.<form>.admission.<field>) can be requested.`}))}return d}s(SP,"familyRequestIssues");function AP(e){let n=new Set((Array.isArray(e.tasks)?e.tasks:[]).flatMap(r=>r.familyRequest!==void 0&&typeof r.key=="string"?[r.key]:[]));return(Array.isArray(e.optionalActions)?e.optionalActions:[]).flatMap((r,i)=>{if(r.action!=="spawnTasks"||!Array.isArray(r.tasks))return[];let o=r.tasks.filter(a=>typeof a=="string"&&n.has(a));return o.length<=1?[]:[At(`nodes.${e.id}.optionalActions.${i}.tasks`,St.twicePerAction,{de:`Optionale Aktion \u201E${String(r.key)}\u201C auf Knoten "${e.id}" startet ${o.length} Nachforderungen (${o.join(", ")}) \u2014 ein Ausl\xF6sen fragt die Familie nach EINER Sache; h\xF6chstens eine Nachforderung je Aktion.`,en:`Optional action "${String(r.key)}" on node "${e.id}" starts ${o.length} follow-up requests (${o.join(", ")}) \u2014 one trigger asks the family for ONE thing; at most one follow-up request per action.`})]})}s(AP,"familyRequestActionIssues");function EP(e,n){let t=e.nodes,r=new Map;for(let a of t)if(!(a.type!=="completenessCheck"||!Array.isArray(a.requires)))for(let l of a.requires)un(l)&&r.set(ue(l),l);if(r.size===0)return[];let i=s(a=>{let l=ai(n,a);return l===void 0||l!==null&&l.kind==="entered"&&l.type==="docRef"},"isFileField"),o=s(a=>{let{fields:l,from:d}=a??{};return Array.isArray(l)?l.filter(un):!be(d)||d.scope!=="node"?[]:[...r.values()].filter(c=>c.owner===d.owner&&i(c))},"offeredBy");return t.flatMap(a=>{let l=Array.isArray(a.requiresOneOf)?a.requiresOneOf:[],c=(Array.isArray(a.optionalActions)?a.optionalActions:[]).filter(h=>l.includes(h.key)),u=Array.isArray(a.tasks)?a.tasks:[];return c.filter(h=>Array.isArray(h.tasks)&&c.every(y=>y===h||y.when!==void 0)).flatMap(h=>u.flatMap(y=>{if(y.familyRequest===void 0||!h.tasks.includes(y.key))return[];let k=o(y.familyRequest).filter(w=>r.has(ue(w)));return k.length===0?[]:[{...At(`nodes.${a.id}.requiresOneOf`,St.deadlock,{de:`Auf Knoten \u201E${_e(e,a.id,"de")}\u201C (${a.id}) ist die Nachforderung \u201E${String(h.key)}\u201C der einzige Weg durch 'requiresOneOf', und eine Vollst\xE4ndigkeitspr\xFCfung fragt dieselben Felder an (${k.map(w=>je(e,w,"de")).join(", ")}). Ist deren Anfrage offen, lassen sich diese Felder nicht nachfordern \u2014 die Entscheidung bliebe gesperrt. Eine zweite Aktion in 'requiresOneOf' oder andere Felder l\xF6sen das.`,en:`On node "${_e(e,a.id,"en")}" (${a.id}) the follow-up request "${String(h.key)}" is the only way through 'requiresOneOf', and a completeness check asks for the same fields (${k.map(w=>je(e,w,"en")).join(", ")}). While its request is open, these fields cannot be requested \u2014 the decision would stay locked. A second action in 'requiresOneOf' or other fields solve this.`}),severity:"warning"}]}))})}s(EP,"familyRequestDeadlockWarnings");var Hw={key:!0,kind:!0,title:!0,assign:!0,gatesNode:!0,blocks:!0,completableIf:!0,result:!0,when:!0,onConditionReturn:!0,reads:!0,locksEvidence:!0,feedback:!0,description:!0,documents:!0,view:!0,familyRequest:!0,optional:!0,appointment:!0,inputs:!0,params:!0};function GH(e){let n=He(e);return new Map((typeof n.workItemTemplates=="function"?n.workItemTemplates(e):[]).map(t=>[t.key,t]))}s(GH,"intrinsicTemplatesOf");function TP(e,n,t){if(t!==void 0&&typeof t!="string")return null;let r=t??n,i=e.nodes.find(l=>l.id===r);if(i===void 0)return null;let o=i,a=He(i);return{node:o,composedKeys:new Set((Array.isArray(o.tasks)?o.tasks:[]).map(l=>l.key).filter(l=>typeof l=="string")),intrinsicByKey:GH(i),refuse:s(l=>typeof a.refuseBlocksTarget=="function"?a.refuseBlocksTarget(i,l):null,"refuse")}}s(TP,"resolveBlocksTargetNode");function zH(e){let n=new Map;for(let r of Zt(e.nodes)){let i=n.get(r.source)??[];i.push(r.target),n.set(r.source,i)}let t=new Map;return r=>{let i=t.get(r);if(i!==void 0)return i;let o=new Set,a=[...n.get(r)??[]];for(;a.length>0;){let l=a.shift();o.has(l)||(o.add(l),a.push(...n.get(l)??[]))}return t.set(r,o),o}}s(zH,"reachability");function $P(e){let n=[],t=new Map;for(let o of e.nodes){let a=o;for(let l of Array.isArray(a.tasks)?a.tasks:[]){let d=typeof l.key=="string"?l.key:void 0,c=l.blocks;if(d===void 0||typeof c?.templateKey!="string")continue;let u=typeof c.node=="string"?c.node:o.id;t.set(`${o.id}::${d}`,`${u}::${c.templateKey}`)}}let r=new Map,i=s((o,a)=>{if(r.get(o)==="done")return;if(r.get(o)==="visiting"){let d=[...a.slice(a.indexOf(o)),o],[c,u]=o.split("::");n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${c}.tasks.${u}.blocks`,reason:{de:`[workItems/blocksCycle] Zyklus im 'blocks'-Graphen: ${d.map(p=>`"${p.replace("::"," \xB7 ")}"`).join(" \u2192 ")} \u2014 jedes Mitglied w\xFCrde auf ein anderes warten, keines w\xFCrde je frei.`,en:`[workItems/blocksCycle] Cycle in the 'blocks' graph: ${d.map(p=>`"${p.replace("::"," \xB7 ")}"`).join(" \u2192 ")} \u2014 every member would wait for another, none would ever be released.`},severity:"error"});return}r.set(o,"visiting");let l=t.get(o);l!==void 0&&t.has(l)&&i(l,[...a,o]),r.set(o,"done")},"walk");for(let o of t.keys())i(o,[]);return n}s($P,"checkBlocksCycles");function WH(e){let{requiresOneOf:n,optionalActions:t}=e;if(!Array.isArray(n)||!Array.isArray(t))return new Set;let r=new Set(n.filter(o=>typeof o=="string")),i=new Set;for(let o of t)if(!(typeof o.key!="string"||!r.has(o.key)||!Array.isArray(o.tasks)))for(let a of o.tasks)typeof a=="string"&&i.add(a);return i}s(WH,"tasksOfRequiresOneOf");function RP(e){if(typeof e!="object"||e===null)return!1;let{de:n,en:t}=e;return typeof n=="string"&&n.trim().length>0&&typeof t=="string"&&t.trim().length>0}s(RP,"isFilledBilingual");var YH=["blocks","gatesNode","locksEvidence","completableIf"];function HH(e,n){let t={de:`Task "${n.key}" (Knoten "${n.nodeId}")`,en:`Task "${n.key}" (node "${n.nodeId}")`},r=[];e.feedback!==!0&&r.push(An(`${n.base}.feedback`,{de:`[workItems/feedbackNotTrue] ${t.de}: 'feedback' kennt nur true; erhalten ${JSON.stringify(e.feedback)}.`,en:`[workItems/feedbackNotTrue] ${t.en}: 'feedback' only knows true; got ${JSON.stringify(e.feedback)}.`}));let i=e.result;(e.kind!=="task"||i?.kind!=="freetext")&&r.push(An(`${n.base}.feedback`,{de:`[workItems/feedbackNeedsFreetext] ${t.de} ist eine Feedback-Aufgabe und schlie\xDFt daher mit Freitext ('result: { kind: "freetext" }'); erhalten ${e.kind!=="task"?`kind ${String(e.kind)}`:`Ergebnis ${String(i?.kind)}`}.`,en:`[workItems/feedbackNeedsFreetext] ${t.en} is a feedback task, so it closes with free text ('result: { kind: "freetext" }'); got ${e.kind!=="task"?`kind ${String(e.kind)}`:`result ${String(i?.kind)}`}.`}));let o=["blocks","gatesNode","completableIf","locksEvidence","familyRequest","appointment"].filter(a=>e[a]!==void 0);return o.length>0&&r.push(An(`${n.base}.feedback`,{de:`[workItems/feedbackSteersProcess] ${t.de} ist eine Feedback-Aufgabe; die Antwort kommt von einer Seite ohne weitere Daten und darf deshalb nicht von ${o.join(", ")} abh\xE4ngen.`,en:`[workItems/feedbackSteersProcess] ${t.en} is a feedback task; its answer comes from a page without application data, so it may not depend on ${o.join(", ")}.`})),r}s(HH,"feedbackTaskIssues");function JH(e,n){let t=[],r={de:`Task "${n.key}" (Knoten "${n.nodeId}")`,en:`Task "${n.key}" (node "${n.nodeId}")`},i=e.optional;(!(typeof i=="object"&&i!==null&&Object.keys(i).every(d=>d==="skipLabel"))||!RP(i.skipLabel))&&t.push(An(`${n.base}.optional.skipLabel`,{de:`[workItems/optionalSkipLabel] ${r.de} ist optional, braucht daf\xFCr '{ skipLabel: { de, en } }' \u2014 die Worte des Knopfs, mit dem die zust\xE4ndige Person ohne Ergebnis abschlie\xDFt (\u201EKeine Einsch\xE4tzung abgeben"); erhalten ${JSON.stringify(i)}.`,en:`[workItems/optionalSkipLabel] ${r.en} is optional and needs '{ skipLabel: { de, en } }' for that \u2014 the words of the button the responsible person uses to finish without a result ("Give no assessment"); got ${JSON.stringify(i)}.`})),e.kind!=="task"&&t.push(An(`${n.base}.optional`,{de:`[workItems/optionalOnApproval] ${r.de} ist eine Freigabe \u2014 optional ist nur eine Aufgabe; eine Freigabe schlie\xDFt mit ihrem Urteil.`,en:`[workItems/optionalOnApproval] ${r.en} is an approval \u2014 only a task can be optional; an approval ends with its verdict.`}));let a=e.result;(a===void 0||typeof a.kind!="string"||!lO({kind:a.kind,writes:a.writes}))&&t.push(An(`${n.base}.optional`,{de:`[workItems/optionalNeedsProseResult] ${r.de} ist optional, schlie\xDFt aber ${a===void 0?"ohne Ergebnis":`mit einem ${String(a.kind)}-Ergebnis${a.writes!==void 0?" mit Wert":""}`} \u2014 optional ist nur eine Aufgabe mit Freitext, Empfehlung oder einer Auswahl ohne 'writes': einen Wert, den ein sp\xE4terer Schritt liest, g\xE4be es dann nie.`,en:`[workItems/optionalNeedsProseResult] ${r.en} is optional but ends ${a===void 0?"without a result":`with a ${String(a.kind)} result${a.writes!==void 0?" with a value":""}`} \u2014 only a task with free text, a recommendation or a choice without 'writes' can be optional: a value a later step reads would then never arrive.`}));let l=YH.filter(d=>e[d]!==void 0);return l.length>0&&t.push(An(`${n.base}.${l[0]}`,{de:`[workItems/optionalHolds] ${r.de} ist optional und tr\xE4gt ${l.map(d=>`'${d}'`).join(", ")} \u2014 auf eine optionale Aufgabe wartet nichts: sie h\xE4lt keinen Schritt zur\xFCck. Entweder optional oder zur\xFCckhaltend.`,en:`[workItems/optionalHolds] ${r.en} is optional and carries ${l.map(d=>`'${d}'`).join(", ")} \u2014 nothing waits for an optional task: it holds no step back. Either optional or holding back.`})),n.requiredByRule&&t.push(An(`${n.base}.optional`,{de:`[workItems/optionalInRequiresOneOf] ${r.de} ist optional, geh\xF6rt aber zu einer Aktion, die 'requiresOneOf' verlangt \u2014 \u201EKeine Einsch\xE4tzung abgeben" w\xFCrde die Regel erf\xFCllen, ohne dass etwas geschehen ist.`,en:`[workItems/optionalInRequiresOneOf] ${r.en} is optional but belongs to an action that 'requiresOneOf' requires \u2014 "Give no assessment" would satisfy the rule without anything having happened.`})),t}s(JH,"optionalTaskIssues");function An(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"error"}}s(An,"issue");function IP(e,n){let t=[],r=zH(e),i=new Set(la(e).map(o=>o.key));t.push(...EP(e,n));for(let o of e.nodes){let a=o,l=kP(a);t.push(...AP(a));let d=WH(a);t.push(...pP(a,e.nodes)),t.push(...xP(e,a));let c=new Map((Array.isArray(a.tasks)?a.tasks:[]).filter(u=>typeof u.key=="string").map(u=>[u.key,{feedback:u.feedback===!0}]));for(let u of Array.isArray(a.tasks)?a.tasks:[]){let p=typeof u.key=="string"?u.key:"?",h=`nodes.${o.id}.tasks.${p}`,y=u.kind,k=u.result,w=u.blocks,v=typeof w?.node=="string"&&w.node!==o.id?w.node:void 0;if(typeof w?.templateKey=="string"){let $=typeof w.node=="string"?w.node:o.id,I=e.nodes.find(le=>le.id===$),B=(Array.isArray(I?.tasks)?I.tasks:[]).find(le=>le.key===w.templateKey)?.blocks;typeof B?.node=="string"&&B.node!==$&&t.push(An(`${h}.blocks.templateKey`,{de:`[workItems/blocksCrossNodeTask] Task "${p}" auf Knoten "${o.id}" h\xE4lt "${w.templateKey}" auf Knoten "${$}" zur\xFCck \u2014 das ist selbst eine knoten\xFCbergreifende Aufgabe, die ihren Knoten \xFCberlebt; zur\xFCckgehalten k\xF6nnte sie nach dessen Verlassen weder bearbeitet noch freigegeben werden. Nur Aufgaben, die an ihrem Knoten bleiben, und intrinsische Vorlagen sind Ziele.`,en:`[workItems/blocksCrossNodeTask] Task "${p}" on node "${o.id}" holds back "${w.templateKey}" on node "${$}" \u2014 that is itself a cross-node task that outlives its node; held back, it could be neither worked nor released after the node is left. Only tasks that stay on their node and intrinsic templates are targets.`}))}if(v!==void 0){let $=v;e.nodes.some(I=>I.id===$)&&!r(o.id).has($)&&t.push(An(`${h}.blocks.node`,{de:`[workItems/blocksTargetNotAfter] Task "${p}" auf Knoten "${o.id}" blockiert Knoten "${$}", der von hier aus nicht erreichbar ist \u2014 die Aufgabe entst\xFCnde erst, wenn ihr Ziel schon hinter dem Prozess liegt. Ziel ist derselbe Knoten oder ein sp\xE4terer.`,en:`[workItems/blocksTargetNotAfter] Task "${p}" on node "${o.id}" blocks node "${$}", which cannot be reached from here \u2014 the task would only be created when its target is already behind the process. The target is the same node or a later one.`})),(k===void 0||!Mi(k.kind))&&t.push(An(`${h}.blocks.node`,{de:`[workItems/crossNodeBlocksNeedsResult] Task "${p}" auf Knoten "${o.id}" blockiert einen anderen Knoten ("${$}"), hat aber kein 'result' \u2014 eine knoten\xFCbergreifende Aufgabe \xFCberlebt ihren Knoten und wird \xFCber ihr Ergebnis abgeschlossen (Freitext, Empfehlung oder Auswahl).`,en:`[workItems/crossNodeBlocksNeedsResult] Task "${p}" on node "${o.id}" blocks another node ("${$}") but has no 'result' \u2014 a cross-node task outlives its node and is completed through its result (free text, recommendation or choice).`})),l.has(p)&&t.push(An(`${h}.blocks.node`,{de:`[optionalAction/crossNodeBlocks] Task "${p}" geh\xF6rt zu einer optionalen Aktion (spawnTasks) auf Knoten "${o.id}" und darf keinen anderen Knoten blockieren \u2014 ihre Zeilen sind die Runde der Aktion.`,en:`[optionalAction/crossNodeBlocks] Task "${p}" belongs to an optional action (spawnTasks) on node "${o.id}" and must not block another node \u2014 its rows are the round of the action.`}))}for(let $ of dP(String(y),k,{channelKeys:i,nodeTasks:c,...n?.billingItemKeys!==void 0?{billingItemKeys:n.billingItemKeys}:{},...n?.offerProgram!==void 0?{offerProgram:n.offerProgram}:{}}))t.push(An(`${h}.${$.field}`,{de:`${$.code} ${$.message.de} (Task "${p}" auf Knoten "${o.id}").`,en:`${$.code} ${$.message.en} (task "${p}" on node "${o.id}").`}));let A=u.when,E=s(($,I,G)=>{!be(I)||un(I)||t.push(An($,{de:`[workItems/evidenceNotFormField] ${G} auf Task "${p}" (Knoten "${o.id}") nennt ${je(e,I,"de")} \u2014 Bedingung und Belege einer Aufgabe sind Felder eines Formulars ($node.<formular>.admission.<feld>).`,en:`[workItems/evidenceNotFormField] ${G} on task "${p}" (node "${o.id}") names ${je(e,I,"en")} \u2014 the condition and evidence of a task are fields of a form ($node.<form>.admission.<field>).`}))},"notFormField");A!==void 0?(E(`${h}.when`,A,"'when'"),u.onConditionReturn!=="respawn"&&u.onConditionReturn!=="stayClosed"&&t.push(An(`${h}.onConditionReturn`,{de:`[workItems/whenNeedsOnConditionReturn] Task "${p}" (Knoten "${o.id}") hat eine Bedingung, aber kein 'onConditionReturn' ('respawn' | 'stayClosed') \u2014 was bei der R\xFCckkehr der Bedingung geschieht, muss entschieden sein.`,en:`[workItems/whenNeedsOnConditionReturn] Task "${p}" (node "${o.id}") has a condition but no 'onConditionReturn' ('respawn' | 'stayClosed') \u2014 what happens when the condition returns must be decided.`}))):u.onConditionReturn!==void 0&&t.push(An(`${h}.onConditionReturn`,{de:`[workItems/whenNeedsOnConditionReturn] 'onConditionReturn' ohne 'when' auf Task "${p}" (Knoten "${o.id}") \u2014 ohne Bedingung kehrt nichts zur\xFCck.`,en:`[workItems/whenNeedsOnConditionReturn] 'onConditionReturn' without 'when' on task "${p}" (node "${o.id}") \u2014 without a condition nothing returns.`}));let R=u.reads;if(R!==void 0)if(!Array.isArray(R))t.push(An(`${h}.reads`,{de:`[workItems/readsUnknownField] 'reads' auf Task "${p}" (Knoten "${o.id}") muss eine Liste von Feldadressen sein.`,en:`[workItems/readsUnknownField] 'reads' on task "${p}" (node "${o.id}") must be a list of field addresses.`}));else for(let[$,I]of R.entries())E(`${h}.reads.${$}`,I,"'reads'");let P=u.locksEvidence,F=s(($,I)=>t.push(An(`${h}.locksEvidence`,{de:`[workItems/${$}] Task "${p}" (Knoten "${o.id}") ${I.de}`,en:`[workItems/${$}] Task "${p}" (node "${o.id}") ${I.en}`})),"lockIssue");P!==void 0&&P!==!0&&F("locksEvidenceNotTrue",{de:`tr\xE4gt 'locksEvidence' ${JSON.stringify(P)} \u2014 nur 'true' ist erlaubt; ohne Sperre entf\xE4llt das Feld.`,en:`carries 'locksEvidence' ${JSON.stringify(P)} \u2014 only 'true' is allowed; without a lock the field is dropped.`}),P===!0&&(R===void 0&&A===void 0&&F("locksEvidenceWithoutEvidence",{de:"sperrt seine Belege, hat aber weder 'reads' noch 'when' \u2014 es gibt nichts, worauf die Entscheidung beruht.",en:"locks its evidence but has neither 'reads' nor 'when' \u2014 there is nothing the decision rests on."}),(k===void 0||!Mi(k.kind))&&F("locksEvidenceNeedsRecordedResult",{de:"sperrt seine Belege, schlie\xDFt aber nicht mit einem erfassten Ergebnis (Freitext, Empfehlung, Auswahl) \u2014 nur eine Entscheidung, die das Team wieder\xF6ffnen kann, darf Belege sperren (ein Termin bleibt gebucht).",en:"locks its evidence but does not end with a recorded result (free text, recommendation, choice) \u2014 only a decision the team can reopen may lock evidence (an appointment stays booked)."}),l.has(p)&&F("locksEvidenceOnOptionalAction",{de:"geh\xF6rt zu einer optionalen Aktion (spawnTasks) \u2014 ihre Zeilen sind die Runde der Aktion, wieder\xF6ffnen l\xE4sst sie sich nicht; Belege sperrt nur eine Knotenaufgabe.",en:"belongs to an optional action (spawnTasks) \u2014 its rows are the round of the action and cannot be reopened; only a node task locks evidence."})),t.push(...SP({graph:e,node:a,task:u,onTrigger:l,specCtx:n}));let b=Object.keys(u).filter($=>!Object.hasOwn(Hw,$));b.length>0&&t.push(An(`${h}.${b[0]}`,{de:`[workItems/unknownKey] Task "${p}" (Knoten "${o.id}") tr\xE4gt ${b.map($=>`'${$}'`).join(", ")} \u2014 kein Feld einer Aufgabe. Erlaubt: ${Object.keys(Hw).join(", ")}. (Checklisten gibt es nicht mehr: Text als 'description', mehrere Arbeitsschritte sind mehrere Aufgaben.)`,en:`[workItems/unknownKey] Task "${p}" (node "${o.id}") carries ${b.map($=>`'${$}'`).join(", ")} \u2014 not a field of a task. Allowed: ${Object.keys(Hw).join(", ")}. (Checklists no longer exist: text goes in 'description', several work steps are several tasks.)`}));let O=u.description;O!==void 0&&!RP(O)&&t.push(An(`${h}.description`,{de:`[workItems/descriptionInvalid] 'description' auf Task "${p}" (Knoten "${o.id}") braucht Text in beiden Sprachen ({ de, en }), erhalten ${JSON.stringify(O)}.`,en:`[workItems/descriptionInvalid] 'description' on task "${p}" (node "${o.id}") needs text in both languages ({ de, en }), got ${JSON.stringify(O)}.`})),u.feedback!==void 0&&t.push(...HH(u,{key:p,nodeId:o.id,base:h})),u.optional!==void 0&&t.push(...JH(u,{key:p,nodeId:o.id,base:h,requiredByRule:d.has(p)}))}}return t}s(IP,"checkNodeTasks");function OP(e){let n=e.indexOf(":"),t=n===-1?"":e.slice(0,n),r=n===-1?"":e.slice(n+1).trim();if(t==="artifact"&&r.length>0)return{kind:t,key:r};let i=Qr(r);return t==="field"&&i!==null?{kind:t,address:i}:se("INVALID",{de:`Dokument-Verweis "${e}" ist ung\xFCltig \u2014 erwartet artifact:<Slot-Schl\xFCssel> (auch der Slot eines anderen Knotens) oder field:$node.<Formular>.admission.<Feld>.`,en:`Document reference "${e}" is invalid \u2014 expected artifact:<slot key> (another node's slot too) or field:$node.<form>.admission.<field>.`})}s(OP,"parseTaskDocumentRef");function Jw(e){return e.kind==="artifact"?`artifact:${e.key}`:`field:${ue(e.address)}`}s(Jw,"taskDocumentId");function fi(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"error"}}s(fi,"issue");function _P(e){return Array.isArray(e.tasks)?e.tasks:[]}s(_P,"tasksOf");function ed(e){let n=new Map;for(let t of e){let{id:r,artifacts:i}=t;for(let o of Array.isArray(i)?i:[])typeof o?.key=="string"&&n.set(o.key,[...n.get(o.key)??[],{nodeId:r,slot:o}])}return n}s(ed,"artifactSlotDeclarations");function QH(e){return e.flatMap(n=>{let{id:t,artifacts:r}=n;return(Array.isArray(r)?r:[]).filter(i=>!ep(i?.type)).map(i=>({nodeId:String(t),slotKey:String(i?.key),type:JSON.stringify(i?.type??null)}))})}s(QH,"unknownArtifactSlotTypes");function NP(e){let n=[];for(let{nodeId:t,slotKey:r,type:i}of QH(e.nodes))n.push(fi(`nodes.${t}.artifacts.${r}.type`,{de:`[artifact/unknownType] Knoten "${t}" deklariert den Dokument-Slot \u201E${r}" mit der Art ${i} \u2014 erlaubt sind ${Xs.join(", ")}.`,en:`[artifact/unknownType] Node "${t}" declares the document slot "${r}" with the type ${i} \u2014 allowed are ${Xs.join(", ")}.`}));for(let[t,r]of ed(e.nodes))for(let i of r.slice(1))n.push(fi(`nodes.${i.nodeId}.artifacts`,{de:`[governedDocument/slotKeyTaken] Knoten "${i.nodeId}" deklariert den Dokument-Slot \u201E${t}", den schon "${r[0].nodeId}" deklariert \u2014 jeder Slot-Schl\xFCssel geh\xF6rt genau einem Knoten.`,en:`[governedDocument/slotKeyTaken] Node "${i.nodeId}" declares the document slot "${t}", which "${r[0].nodeId}" already declares \u2014 every slot key belongs to exactly one node.`}));return n}s(NP,"checkArtifactSlotKeys");function ZH(e,n,t,r=ed(e.nodes)){let i=r.get(n)?.[0]?.nodeId;return i===void 0?{reason:"unknown"}:zs(e,i,t)?null:{reason:"notBefore",owner:i}}s(ZH,"slotLinkRefusal");function PP(e){if(!Array.isArray(e)||e.length===0)return null;let n=[];for(let t of e){let r=typeof t=="object"&&t!==null?t:{},i=Object.keys(r).sort().join(",");if(r.kind==="artifact"&&i==="key,kind"&&typeof r.key=="string"&&r.key.length>0)n.push({kind:"artifact",key:r.key});else if(r.kind==="field"&&i==="address,kind")n.push({kind:"field",address:r.address});else return null}return n}s(PP,"authoredRefs");function CP(e){let n=[],t=ed(e.nodes);for(let r of e.nodes)for(let i of _P(r)){if(i.documents===void 0)continue;let o=typeof i.key=="string"?i.key:"?",a=`nodes.${r.id}.tasks.${o}.documents`,l={de:`Task "${o}" (Knoten "${r.id}")`,en:`Task "${o}" (node "${r.id}")`},d=PP(i.documents);if(d===null){n.push(fi(a,{de:`[workItems/documentsInvalid] 'documents' auf ${l.de} muss eine nicht leere Liste von { kind: 'artifact', key } (Dokument-Slot eines Knotens) oder { kind: 'field', address } (Dateifeld eines Formulars) sein, erhalten ${JSON.stringify(i.documents)} \u2014 ein { kind: 'document', address } schreibt \`plexus-cli offer upgrade\` auf den Slot um.`,en:`[workItems/documentsInvalid] 'documents' on ${l.en} must be a non-empty list of { kind: 'artifact', key } (document slot of a node) or { kind: 'field', address } (file field of a form), got ${JSON.stringify(i.documents)} \u2014 \`plexus-cli offer upgrade\` rewrites a { kind: 'document', address } onto its slot.`}));continue}let c=new Set;for(let u of d){if(u.kind!=="artifact"&&!be(u.address))continue;let p=u.kind==="artifact"?Jw(u):Jw({kind:"field",address:u.address});if(c.has(p)&&n.push(fi(a,{de:`[workItems/documentsDuplicate] ${l.de} verweist zweimal auf ${p}.`,en:`[workItems/documentsDuplicate] ${l.en} refers to ${p} twice.`})),c.add(p),u.kind==="artifact"){let h=ZH(e,u.key,r.id,t);h?.reason==="unknown"?n.push(fi(a,{de:`[workItems/documentsUnknownArtifact] ${l.de} verweist auf das Dokument "${u.key}", aber kein Knoten deklariert einen solchen Slot.`,en:`[workItems/documentsUnknownArtifact] ${l.en} refers to the document "${u.key}", but no node declares such a slot.`})):h?.reason==="notBefore"&&n.push(fi(a,{de:`[workItems/documentsNotBefore] ${l.de} verweist auf das Dokument "${u.key}" des Knotens "${h.owner}", der nicht auf jedem Weg vor "${r.id}" liegt \u2014 auf einem Weg an ihm vorbei g\xE4be es das Dokument nie.`,en:`[workItems/documentsNotBefore] ${l.en} refers to the document "${u.key}" of node "${h.owner}", which does not lie on every path before "${r.id}" \u2014 on a path around it the document would never exist.`}))}u.kind==="field"&&!un(u.address)&&n.push(fi(a,{de:`[workItems/documentsInvalid] ${l.de}: ein Feld-Dokument nennt ein Feld eines Formulars ($node.<formular>.admission.<feld>), nicht ${je(e,u.address,"de")}.`,en:`[workItems/documentsInvalid] ${l.en}: a field document names a field of a form ($node.<form>.admission.<field>), not ${je(e,u.address,"en")}.`}))}}return n}s(CP,"checkTaskDocuments");function DP(e,n){let t=[];for(let r of e.nodes)for(let i of _P(r)){let o=PP(i.documents);if(o===null)continue;let a=typeof i.key=="string"?i.key:"?",l=`nodes.${r.id}.tasks.${a}.documents`;for(let d of o){if(d.kind!=="field"||!un(d.address))continue;let c=ai(n,d.address);if(c==null)continue;let u={de:je(e,d.address,"de"),en:je(e,d.address,"en")},p=Ys("taskDocument",Ws(c));if(p==="repeated"){t.push(fi(l,{de:`[workItems/documentsUnknownField] Task "${a}" (Knoten "${r.id}") verweist auf das Feld ${u.de} \u2014 ein Feld in einer Wiederholgruppe ist kein einzelnes Dokument der Anmeldung.`,en:`[workItems/documentsUnknownField] Task "${a}" (node "${r.id}") refers to the field ${u.en} \u2014 a field in a repeated group is not a single document of the application.`}));continue}p==="notDocument"&&t.push(fi(l,{de:`[workItems/documentsNotDocument] Task "${a}" (Knoten "${r.id}") verweist auf das Feld ${u.de}, das keine Datei enth\xE4lt \u2014 nur Datei-Felder (docRef) sind Dokumente.`,en:`[workItems/documentsNotDocument] Task "${a}" (node "${r.id}") refers to the field ${u.en}, which holds no file \u2014 only file fields (docRef) are documents.`}))}}return t}s(DP,"checkTaskDocumentFields");var Zw=["form","artifact","field"],fa=["coverLetter","contract"],FP=/^[A-Za-z0-9_.-]+$/;function XH(e){return fa.includes(e)}s(XH,"isArtifactPart");function ua(e){return se("INVALID",{de:`Ansichts-Adresse "${e}" ist ung\xFCltig \u2014 erwartet form:<Formularknoten>#<Ansicht>, artifact:<Slot>[#${fa.join("|")}] oder field:$node.<Formular>.admission.<Feld>.`,en:`View address "${e}" is invalid \u2014 expected form:<form node>#<view>, artifact:<slot>[#${fa.join("|")}] or field:$node.<form>.admission.<field>.`})}s(ua,"invalid");function Xw(e){let n=e.indexOf(":");if(n===-1)return ua(e);let t=e.slice(0,n),r=e.slice(n+1);if(t==="field"){let l=Qr(r);return l===null?ua(e):{kind:t,address:l}}let i=r.indexOf("#"),o=i===-1?r:r.slice(0,i),a=i===-1?null:r.slice(i+1);return FP.test(o)?t==="form"?a!==null&&FP.test(a)?{kind:t,form:o,view:a}:ua(e):t==="artifact"?a===null?{kind:t,slot:o}:XH(a)?{kind:t,slot:o,part:a}:ua(e):ua(e):ua(e)}s(Xw,"parseViewAddress");function LP(e){let n=nJ(e);if(n===null)return null;let t=eJ(n);return t!==null&&JSON.stringify(Qw(t))===JSON.stringify(Qw(e))?t:null}s(LP,"viewAddressOf");function eJ(e){try{return Xw(e)}catch{return null}}s(eJ,"tryParseViewAddress");function nJ(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e;if(n.kind==="form"&&typeof n.form=="string"&&typeof n.view=="string")return`form:${n.form}#${n.view}`;if(n.kind==="artifact"&&typeof n.slot=="string")return n.part===void 0?`artifact:${n.slot}`:typeof n.part=="string"?`artifact:${n.slot}#${n.part}`:null;if(n.kind==="field"&&n.address!==null&&typeof n.address=="object"){let t=n.address;return typeof t.scope!="string"||typeof t.key!="string"?null:`field:${ue(t)}`}return null}s(nJ,"spellingOf");function Qw(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([n],[t])=>n<t?-1:n>t?1:0).map(([n,t])=>[n,Qw(t)]))}s(Qw,"canonical");function MP(e){switch(e.kind){case"form":return`form:${e.form}#${e.view}`;case"artifact":return e.part===void 0?`artifact:${e.slot}`:`artifact:${e.slot}#${e.part}`;case"field":return`field:${ue(e.address)}`}}s(MP,"formatViewAddress");var ek=["form","documents"],tJ=/^[a-z][a-zA-Z0-9_-]*$/;function rJ(e){let n=new Map,t=s(r=>{for(let i of[...r.fields,...(r.groups??[]).flatMap(o=>o.fields)])n.set(i.key,i.type==="docRef"?"document":"other");for(let i of r.repeated??[]){n.set(i.key,"other");for(let o of i.itemTemplate)n.set(`${i.key}[].${o.key}`,o.type==="docRef"?"row":"other")}r.subsections?.forEach(t)},"visit");return e.sections.forEach(t),n}s(rJ,"fieldPlaces");function qP(e,n,t){let r=[],i=new Set;return e.forEach((o,a)=>{if(typeof o!="string"||!tJ.test(o)){r.push({severity:"error",path:`${t(a)}.key`,code:"view.invalid-key",message:{de:`${n.de}: '${String(o)}' ist kein g\xFCltiger Schl\xFCssel (Kleinbuchstabe am Anfang, dann Buchstaben, Ziffern, - oder _).`,en:`${n.en}: '${String(o)}' is no valid key (a lower-case letter first, then letters, digits, - or _).`}});return}i.has(o)&&r.push({severity:"error",path:`${t(a)}.key`,code:"view.duplicate-key",message:{de:`${n.de}: Der Schl\xFCssel '${o}' kommt doppelt vor.`,en:`${n.en}: the key '${o}' occurs twice.`}}),i.add(o)}),r}s(qP,"keyIssues");function iJ(e,n,t){return e==="document"?null:e===void 0?{severity:"error",path:t,code:"view.unknown-field",message:{de:`Ansicht: Das Formular hat kein Feld '${n}'.`,en:`View: the form has no field '${n}'.`}}:e==="row"?{severity:"error",path:t,code:"view.field-in-row",message:{de:`Ansicht: Das Dateifeld '${n}' liegt in einem wiederholten Block und kann nicht einzeln genannt werden.`,en:`View: the file field '${n}' sits in a repeated block and cannot be named on its own.`}}:{severity:"error",path:t,code:"view.not-a-document",message:{de:`Ansicht: Das Feld '${n}' enth\xE4lt keine Datei.`,en:`View: the field '${n}' holds no file.`}}}s(iJ,"fieldIssue");function oJ(e,n,t){let r=[];ek.includes(e.key)&&r.push({severity:"error",path:`${n}.key`,code:"view.reserved-key",message:{de:`Der Ansichtsschl\xFCssel '${e.key}' ist f\xFCr die Standardansicht reserviert.`,en:`The view key '${e.key}' is reserved for the standard view.`}});let i=e.groups;i.length===0&&r.push({severity:"error",path:`${n}.groups`,code:"view.empty",message:{de:`Ansicht '${e.key}' hat keine Gruppen.`,en:`View '${e.key}' has no groups.`}}),r.push(...qP(i.map(a=>a.key),{de:`Gruppe der Ansicht '${e.key}'`,en:`Group of view '${e.key}'`},a=>`${n}.groups[${a}]`));let o=new Set;return i.forEach((a,l)=>{let d=`${n}.groups[${l}]`,c=a.fields;c.length===0&&r.push({severity:"error",path:`${d}.fields`,code:"view.empty",message:{de:`Gruppe '${a.key}' der Ansicht '${e.key}' hat keine Felder.`,en:`Group '${a.key}' of view '${e.key}' has no fields.`}}),c.forEach((u,p)=>{let h=`${d}.fields[${p}]`,y=iJ(t.get(u),u,h);y!==null&&r.push(y),o.has(u)&&r.push({severity:"error",path:h,code:"view.field-twice",message:{de:`Ansicht '${e.key}': Das Feld '${u}' steht mehrfach; eine Datei hat einen Platz.`,en:`View '${e.key}': the field '${u}' is listed more than once; a file has one place.`}}),o.add(u)})}),r}s(oJ,"viewIssues");function sJ(e){if(!Array.isArray(e))return"views";for(let[n,t]of e.entries()){let r=t?.groups;if(!Array.isArray(r))return`views[${n}].groups`;for(let[i,o]of r.entries()){let a=o?.fields;if(!Array.isArray(a)||a.some(l=>typeof l!="string"))return`views[${n}].groups[${i}].fields`}}return null}s(sJ,"malformedAt");function KP(e){let n=e.views;if(n===void 0)return[];let t=sJ(n);if(t!==null)return[{severity:"error",path:t,code:"view.malformed",message:{de:`${t} hat nicht die Form einer Ansicht: views ist eine Liste von { key, label, groups }, groups eine Liste von { key, label, fields }, fields eine Liste von Feldschl\xFCsseln.`,en:`${t} is not shaped like a view: views is a list of { key, label, groups }, groups a list of { key, label, fields }, fields a list of field keys.`}}];let r=rJ(e);return[...qP(n.map(i=>i.key),{de:"Ansicht",en:"View"},i=>`views[${i}]`),...n.flatMap((i,o)=>oJ(i,`views[${o}]`,r))]}s(KP,"formViewIssues");function pa(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"error"}}s(pa,"issue");function jP(e,n,t,r,i){let o=LP(e);if(o===null)return[pa(n,{de:`[view/invalid] 'view' auf ${t.de} ist keine Ansichts-Adresse \u2014 erwartet { kind: ${Zw.join(" | ")}, \u2026 }: form:<Formularknoten>#<Ansicht>, artifact:<Slot>[#${fa.join("|")}] oder field:$node.<Formular>.admission.<Feld>.`,en:`[view/invalid] 'view' on ${t.en} is no view address \u2014 expected { kind: ${Zw.join(" | ")}, \u2026 }: form:<form node>#<view>, artifact:<slot>[#${fa.join("|")}] or field:$node.<form>.admission.<field>.`})];let a=MP(o);switch(o.kind){case"artifact":return r.has(o.slot)?[]:[pa(n,{de:`[view/unknownSlot] ${t.de} nennt "${a}", aber kein Knoten dieses Graphen hat den Dokument-Slot "${o.slot}".`,en:`[view/unknownSlot] ${t.en} names "${a}", but no node of this graph has the document slot "${o.slot}".`})];case"form":case"field":{let l=o.kind==="form"?o.form:o.address.scope==="node"?o.address.owner:null;if(l===null)return[pa(n,{de:`[view/invalid] ${t.de} nennt "${a}" \u2014 ein Dateifeld liegt in einem Formular: field:$node.<Formular>.admission.<Feld>.`,en:`[view/invalid] ${t.en} names "${a}" \u2014 a file field lives in a form: field:$node.<form>.admission.<field>.`})];let d=i?.formViewKeysByFormNode;if(d===void 0)return[];let c=d.get(l);return c===void 0?[pa(n,{de:`[view/unknownForm] ${t.de} nennt "${a}", aber kein Formularknoten hei\xDFt so.`,en:`[view/unknownForm] ${t.en} names "${a}", but no form node has that id.`})]:o.kind==="field"?[]:c.has(o.view)||ek.includes(o.view)?[]:[pa(n,{de:`[view/unknownView] ${t.de} nennt "${a}", aber das Formular "${o.form}" hat keine Ansicht "${o.view}".`,en:`[view/unknownView] ${t.en} names "${a}", but the form "${o.form}" has no view "${o.view}".`})]}}}s(jP,"viewIssues");function VP(e,n){let t=[],r=new Set(ed(e.nodes).keys());for(let i of e.nodes){if(i.view!==void 0){let o={de:`Knoten "${i.id}"`,en:`node "${i.id}"`};i.type!=="decision"?t.push(pa(`nodes.${i.id}.view`,{de:`[view/invalid] ${o.de}: 'view' am Knoten gilt nur f\xFCr eine Entscheidung; eine Aufgabe tr\xE4gt ihre eigene.`,en:`[view/invalid] ${o.en}: 'view' on a node applies to a decision only; a task carries its own.`})):t.push(...jP(i.view,`nodes.${i.id}.view`,o,r,n))}for(let o of Array.isArray(i.tasks)?i.tasks:[]){if(o.view===void 0)continue;let a=String(o.key);t.push(...jP(o.view,`nodes.${i.id}.tasks.${a}.view`,{de:`Task "${a}" (Knoten "${i.id}")`,en:`Task "${a}" (node "${i.id}")`},r,n))}}return t}s(VP,"checkTaskViews");var Dt="traeger",BP={de:"Tr\xE4ger",en:"Provider"};function ma(e){let n=e.inputs?.[Dt];return n?.kind==="literal"&&typeof n.value=="string"&&n.value.length>0?n.value:null}s(ma,"traegerKeyOfNode");var xp={name:"input.traeger.name",address:"input.traeger.anschrift"},Tye=Object.values(xp);var UP="governedDocument",qo="prepareDocument",nd="prepareDocument:revision",Kr="releaseApproval",Ko="documentResponse",Yi="coverLetterResponse",Sp="confirmCoverLetter",Ap="requestCoverLetterRevision",ha="coverLetterConfirmation",jr="responseCheck",Ep="returnSigned";var GP="requestApproval";var zP="issueDocument",WP="correctInPlace",YP="rescindAndReissue",Tp="requestChange";var ga="releaseArtifact",ft="signingRecovery",$p="resendESignature",jo="switchToPaper";var nk=new Set([qo,nd]),HP=["pending","producing","producingHeld","deferred","awaitingApproval","awaitingCoverLetter","awaitingResponse","responseReturned","responseInCheck","awaitingSignature","signatureStalled","done"],Rp=["upload","resolver","template","none"],Vo=1,Bo=366,pi="responseDueInDays";function Uo(e){let n=e.inputs?.[ha];return n?.kind==="literal"&&n.value===!0}s(Uo,"coverLetterConfirmationOf");function td(e){let n=e.inputs?.[pi];return n?.kind==="literal"&&rd(n.value)?n.value:void 0}s(td,"responseDueInDaysForVocabulary");function rd(e){return typeof e=="number"&&Number.isInteger(e)&&e>=Vo&&e<=Bo}s(rd,"isValidResponseDueInDays");var Ip=["generatedAt","responseDueInDays","countersignature"],Go=["release","none"],Op=["confirm","signedUpload","signedUploadChecked","eSignature"];var aJ={kind:"confirm",acceptOutcomeId:"accepted",declineOutcomeId:"declined",outcomeSemantics:{accept:"granted",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!1,declineIsAnswer:!0,acceptStatus:"accepted",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Annehmen",en:"Accept"},decline:{de:"Ablehnen",en:"Decline"}}},JP={kind:"signedUpload",acceptOutcomeId:"signed",declineOutcomeId:"absage",outcomeSemantics:{accept:"other",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!0,declineIsAnswer:!1,acceptStatus:"signed",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Unterschrieben zur\xFCcksenden",en:"Return signed"},decline:{de:"Ablehnen",en:"Decline"}}},QP={...JP,kind:"signedUploadChecked",acceptEvent:"contractEvent",checksReturn:!0},lJ={...QP,kind:"eSignature",issuesBy:"provider"},mi={confirm:aJ,signedUpload:JP,signedUploadChecked:QP,eSignature:lJ};function hi(e){let n=e.responseStrategy;if(typeof n=="string"&&n in mi)return mi[n];L(`governedDocument node "${e.id}" declares no valid responseStrategy (got ${JSON.stringify(n)}) \u2014 publish validation should have blocked this; corrupt pinned graph`)}s(hi,"responseStrategyOf");function _p(e){if(e.type!==UP||e.production!=="resolver")return!1;let n=e.responseStrategy;return typeof n=="string"&&n in mi?mi[n].acceptEvent==="contractEvent":!1}s(_p,"isFamilySignedContractNode");function wa(e){return e.label}s(wa,"governedDocTitle");function tk(e){return e.approval==="release"?GP:zP}s(tk,"submitActionId");function ZP(e,n,t){return{key:n,recipient:"internal",title:t,unlocks:[tk(e)],gatesNode:!0,advancesNode:!0}}s(ZP,"producerTemplate");function dJ(e){return e.titles?.respond??e.label}s(dJ,"responseTitle");var ya={de:"\u27E8Titel fehlt\u27E9",en:"\u27E8title missing\u27E9"};function Np(e){let n=hi(e),t=[];if(e.production!=="none"&&t.push(ZP(e,qo,e.titles?.prepare??ya),ZP(e,nd,e.titles?.revise??ya)),e.approval==="release"&&t.push({key:Kr,recipient:"internal",title:e.titles?.approve??ya,unlocks:[],verdictResolved:!0,gatesNode:!0,advancesNode:!0}),t.push({key:Ko,recipient:"external",title:dJ(e),unlocks:n.producesResponseArtifact?[n.checksReturn?Ep:n.acceptOutcomeId,n.declineOutcomeId,Tp]:[n.acceptOutcomeId,n.declineOutcomeId],advancesNode:!0,...td(e)!==void 0?{dueInDays:td(e)}:{}}),Uo(e)){let r=wa(e);t.push({key:Yi,recipient:"external",title:{de:`${r.de}: Angebot best\xE4tigen`,en:`${r.en}: confirm offer`},unlocks:[Sp,Ap,n.declineOutcomeId],advancesNode:!0,...td(e)!==void 0?{dueInDays:td(e)}:{}})}if(n.checksReturn&&t.push({key:jr,recipient:"internal",title:e.titles?.check??ya,unlocks:[],verdictResolved:!0,gatesNode:!1,advancesNode:!0}),n.issuesBy==="provider"){let r=wa(e);t.push({key:ft,recipient:"internal",title:{de:`${r.de}: elektronische Unterschrift kl\xE4ren`,en:`${r.en}: resolve the e-signature`},unlocks:[$p,jo],gatesNode:!1,advancesNode:!1})}return t}s(Np,"governedDocIntrinsicTemplates");function cJ(e){e.production==="none"&&L(`governedDocSlot: node "${e.id}" has production 'none' \u2014 it governs no artifact slot`);let n=e.artifacts??[];n.length!==1&&L(`governedDocSlot: node "${e.id}" declares ${n.length} artifact slots \u2014 exactly ONE is required (publish validation [governedDocument/slotContract])`);let t=n[0];return(typeof t.key!="string"||t.key.length===0)&&L(`governedDocSlot: node "${e.id}" declares an artifact slot without a key \u2014 corrupt pinned graph`),t}s(cJ,"governedDocSlot");function Pp(e){return cJ(e).key}s(Pp,"governedDocSlotKey");var Xt="processFooter";var Cp="countersign",rk="countersign",XP="countersigned",eC="countersigning",nC="countersigned";var tC={de:"Vertrag gegenzeichnen",en:"Countersign the contract"},id=["scan","eSignature"],Dp="service_provider:1",rC=["countersigning","awaitingSignature","signatureStalled","done"],iC={de:"Elektronische Gegenzeichnung kl\xE4ren",en:"Resolve the electronic countersignature"};function oC(e){return{de:`[countersign/traegerSignatoryMissing] Die Schule zeichnet elektronisch gegen, aber f\xFCr ${e} ist keine Unterschriftsperson hinterlegt, die unterschreiben kann (Rechtstr\xE4ger \u2192 signatoryUserKey, aktives Personal der Schule).`,en:`[countersign/traegerSignatoryMissing] The school countersigns electronically, but no signatory who can sign is on file for ${e} (legal entity \u2192 signatoryUserKey, active staff of the school).`}}s(oC,"traegerSignatoryMissingReason");function er(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(er,"issue");function Fp(e,n){return e.nodes.filter(t=>{let r=t.contract;return t.type==="countersign"&&be(r)&&r.scope==="node"&&r.owner===n})}s(Fp,"countersignersOf");function od(e){return e.signing==="eSignature"}s(od,"isElectronic");function uJ(e,n){if(n===void 0||n.sendable||!od(e))return[];let t=e.label?.de??e.id,r=e.label?.en||e.id;return[er(e,"signing",{de:`[countersign/eSignatureNeedsProvider] \u201E${t}\u201C zeichnet elektronisch gegen, aber die Schule kann nicht senden: ${n.reason.de}`,en:`[countersign/eSignatureNeedsProvider] "${r}" countersigns electronically, but the school cannot send: ${n.reason.en}`})]}s(uJ,"countersignProviderIssues");function fJ(e,n,t){if(t.scope!=="node")return[];let r=e.nodes.find(o=>o.id===t.owner);if(r===void 0)return[];let i=[];return _p(r)||i.push("sourceNotCheckedContract"),Fp(e,r.id).some(o=>o.id!==n)&&i.push("twice"),i}s(fJ,"countersignContractRefusals");function sC(e){let n=e.inputs?.dueInDays;return n?.kind==="literal"&&typeof n.value=="number"&&Number.isInteger(n.value)&&n.value>=1?n.value:void 0}s(sC,"validDueInDays");function pJ(e,n,t){let r=e.label?.de??e.id,i=e.label?.en||e.id,o=e.signing;if(o!==void 0&&!id.includes(o))return[er(e,"signing",{de:`[countersign/unknownSigning] \u201E${r}\u201C: signing ist scan oder eSignature (gefunden: ${JSON.stringify(o)}).`,en:`[countersign/unknownSigning] "${i}": signing is scan or eSignature (found: ${JSON.stringify(o)}).`})];let a=e.assign?.[ft];if(!od(e))return a===void 0?[]:[er(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet auf Papier gegen \u2014 \`assign.signingRecovery\` h\xE4lt keine Aufgabe und geh\xF6rt entfernt.`,en:`[countersign/recoveryAssign] "${i}" countersigns on paper \u2014 \`assign.signingRecovery\` holds no task and must be removed.`})];let l=[];return(typeof a!="string"||a.length===0)&&l.push(er(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet elektronisch gegen \u2014 wer eine gescheiterte Gegenzeichnung kl\xE4rt, fehlt: \`assign.signingRecovery\` nennt das Team.`,en:`[countersign/recoveryAssign] "${i}" countersigns electronically \u2014 who resolves a failed countersignature is missing: \`assign.signingRecovery\` names the team.`})),l.push(...mJ(e,n,t),...hJ(e,n,t),...uJ(e,t?.signingProvider)),l}s(pJ,"signingIssues");function lC(e,n){let t=e.contract;if(!(!be(t)||t.scope!=="node"))return n.nodes.find(r=>r.id===t.owner)}s(lC,"contractNodeOf");function mJ(e,n,t){let r=lC(e,n),i=r===void 0?null:ma(r),o=i===null?void 0:t?.traeger?.get(i);return o===void 0||o.hasSignatory?[]:[er(e,"signing",oC(o.name))]}s(mJ,"traegerSignatoryIssues");function hJ(e,n,t){let r=lC(e,n);if(r===void 0)return[];let i=t?.resolverDocumentAnchors?.get(r.id);if(i===void 0)return[];let o=e.label?.de??e.id,a=e.label?.en||e.id,l=[];for(let d of i)d.documentAnchors===null?l.push(er(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage des Generators \u201E${d.pin}\u201C wurde nie auf Unterschriftsanker gelesen \u2014 Vorlage neu hochladen und den Generator neu versiegeln.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of generator "${d.pin}" was never read for signature anchors \u2014 upload the template again and seal the generator again.`})):d.documentAnchors.has(Dp)||l.push(er(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage von \u201E${d.pin}\u201C tr\xE4gt keinen Anker /unterschrift:${Dp}/ \u2014 der Anbieter f\xE4nde f\xFCr die Schule kein Unterschriftsfeld.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of "${d.pin}" carries no anchor /unterschrift:${Dp}/ \u2014 the provider would find no signature field for the school.`}));return l}s(hJ,"traegerAnchorIssues");var ik=100;async function gJ(e,n){let t=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",o=>o.eq("context.applicationId",n.applicationId).eq("context.anchor.nodeId",n.node.id)).take(ik+1);t.length>ik&&L(`countersign node "${n.node.id}" of ${n.applicationId} holds more than ${ik} rows`);let r=t.filter(o=>o.isOpen),i=s(o=>{if(o.context.kind!=="admission")return;let a=o.context.anchor;return"templateKey"in a?a.templateKey:void 0},"templateKeyOf");return r.some(o=>i(o)===ft)?"signatureStalled":r.some(o=>i(o)===Cp)?"countersigning":od(n.node)?"awaitingSignature":"done"}s(gJ,"countersignCurrentState");var aC={[eC]:{label:te("Gegenzeichnung","Countersignature"),tone:"teal",phase:{key:"gegenzeichnung",label:te("Gegenzeichnung","Countersignature"),scope:"node"},external:Xe(te("Vertrag unterschrieben","Contract signed"),"blue",te("Die Schule zeichnet Ihren Vertrag gegen","The school is countersigning your contract"),te("Vielen Dank f\xFCr Ihre Unterschrift. Sobald die Schule gegengezeichnet hat, finden Sie Ihr Exemplar hier.","Thank you for signing. As soon as the school has countersigned, you will find your copy here."))}},dC={inputs:s(()=>[{id:"dueInDays",label:{de:"Frist der Aufgabe (Tage)",en:"Task due in (days)"},type:"number",inspector:"literal-only"}],"inputs"),role:"user-action",effect:"side-effect",outcomes:[{id:XP,label:{de:"Gegengezeichnet",en:"Countersigned"}}],progressDefaults:aC,progressEvents:Ln(aC),notificationEvents:s(()=>[{id:nC,label:{de:"Vertrag gegengezeichnet",en:"Contract countersigned"},audience:"external",required:!0,args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0}]}],"notificationEvents"),actions:s(e=>[{id:rk,kind:"internal",label:tC,surface:Xt,availableIn:["countersigning"]},...od(e)?[{id:jo,kind:"internal",surface:Xt,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}]:[]],"actions"),workItemTemplates:s(e=>[{key:Cp,recipient:"internal",title:e.titles?.countersign??ya,unlocks:[rk],advancesNode:!0,...sC(e)!==void 0?{dueInDays:sC(e)}:{}},...od(e)?[{key:ft,recipient:"internal",title:iC,unlocks:[jo],gatesNode:!1,advancesNode:!1}]:[]],"workItemTemplates"),states:rC,currentState:gJ,validate:s((e,n,t)=>{let r=[],i=e.label?.de??e.id,o=e.label?.en||e.id,a=e.assign?.[Cp];(typeof a!="string"||a.length===0)&&r.push(er(e,"assign",{de:`[countersign/assign] \u201E${i}": wer gegenzeichnet, fehlt \u2014 \`assign.countersign\` nennt das Team.`,en:`[countersign/assign] "${o}": who countersigns is missing \u2014 \`assign.countersign\` names the team.`})),Pi(e.titles?.countersign)||r.push(er(e,"titles",{de:`[countersign/missingTitle] \u201E${i}": der Titel der Aufgabe fehlt \u2014 \`titles.countersign\` auf Deutsch und Englisch.`,en:`[countersign/missingTitle] "${o}": the task title is missing \u2014 \`titles.countersign\` in German and English.`}));let l=e.inputs?.dueInDays;l!==void 0&&l.kind!=="unset"&&!(l.kind==="literal"&&typeof l.value=="number"&&Number.isInteger(l.value)&&l.value>=1)&&r.push(er(e,"inputs.dueInDays",{de:`[countersign/dueInDays] \u201E${i}": dueInDays ist eine ganze Zahl \u2265 1.`,en:`[countersign/dueInDays] "${o}": dueInDays is a whole number \u2265 1.`})),r.push(...pJ(e,n,t));let d=e.contract;if(!be(d))return r;let c=fJ(n,e.id,d);if(c.length===0)return r;let u=n.nodes.find(p=>d.scope==="node"&&p.id===d.owner);if(c.includes("sourceNotCheckedContract")&&r.push(er(e,"contract",{de:`[countersign/sourceNotCheckedContract] \u201E${i}" zeichnet das Dokument von \u201E${u.label?.de??u.id}" (${u.id}) gegen \u2014 gegenzeichnen l\xE4sst sich nur ein erzeugter Vertrag, den die Familie mit verbuchten Unterschriften unterschreibt (governedDocument mit production: resolver und responseStrategy: signedUploadChecked oder eSignature).`,en:`[countersign/sourceNotCheckedContract] "${o}" countersigns the document of "${u.label?.en||u.id}" (${u.id}) \u2014 only a generated contract that the family signs with booked signatures can be countersigned (governedDocument with production: resolver and responseStrategy: signedUploadChecked or eSignature).`})),c.includes("twice")){let p=Fp(n,u.id).filter(h=>h.id!==e.id);r.push(er(e,"contract",{de:`[countersign/twice] \u201E${i}": \u201E${u.label?.de??u.id}" (${u.id}) wird schon von ${p.map(h=>`"${h.id}"`).join(", ")} gegengezeichnet \u2014 ein Vertrag hat eine Gegenzeichnung.`,en:`[countersign/twice] "${o}": "${u.label?.en||u.id}" (${u.id}) is already countersigned by ${p.map(h=>`"${h.id}"`).join(", ")} \u2014 a contract has one countersignature.`}))}return r},"validate")};function yJ(e){return _p(e)?ma(e):null}s(yJ,"traegerSignerOf");var wJ=s(e=>e.type==="end"&&Co(e)==="approved","isApprovedEnd");function cC(e){let n=[];for(let t of e.nodes){let r=yJ(t);if(r===null)continue;let i=Fp(e,t.id).map(u=>u.id),o=w_(e,t.id,new Set(i),wJ);if(o===null)continue;let a=t.label?.de||t.id,l=t.label?.en||t.id,d={de:`Einen Knoten \u201EUnterschrift (intern)\u201C (countersign) mit contract: $node.${t.id}.contract auf jeden Weg zu einem Ende mit Ergebnis approved setzen.`,en:`Place an "Internal signature" node (countersign) with contract: $node.${t.id}.contract on every path to an end with outcome approved.`},c=i.length===0?{de:`[countersign/missingForContract] \u201E${a}\u201C (${t.id}) erzeugt einen Vertrag, den der Tr\xE4ger \u201E${r}\u201C mitunterschreibt, aber keine Gegenzeichnung nennt ihn \u2014 der Vertrag w\xFCrde nie unterschrieben und nie abgerechnet. ${d.de}`,en:`[countersign/missingForContract] "${l}" (${t.id}) generates a contract the legal entity "${r}" co-signs, but no countersignature names it \u2014 the contract would never be signed and never billed. ${d.en}`}:{de:`[countersign/missingForContract] \u201E${a}\u201C (${t.id}): ein Weg erreicht das Ende \u201E${o}\u201C (Ergebnis approved), ohne durch die Gegenzeichnung ${i.map(u=>`\u201E${u}\u201C`).join(", ")} zu laufen \u2014 dort bliebe der Vertrag ohne Unterschrift des Tr\xE4gers \u201E${r}\u201C und w\xFCrde nie abgerechnet. ${d.de}`,en:`[countersign/missingForContract] "${l}" (${t.id}): a path reaches the end "${o}" (outcome approved) without passing the countersignature ${i.map(u=>`"${u}"`).join(", ")} \u2014 there the contract would lack the signature of the legal entity "${r}" and never be billed. ${d.en}`};n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}`,reason:c,severity:"error"})}return n}s(cC,"checkCountersignCoverage");var kJ=[{key:"blocks",why:{de:"sie h\xE4lt nichts zur\xFCck, sie ist mit dem Ausl\xF6sen erledigt",en:"it holds nothing back, it is done with the press"}},{key:"when",why:{de:"sie entsteht bei jedem Ausl\xF6sen",en:"it is created on every press"}},{key:"optional",why:{de:"wer ausl\xF6st, beantwortet sie immer",en:"whoever presses always answers it"}},{key:"appointment",why:{de:"sie wird beim Ausl\xF6sen beantwortet, nicht bei einem Termin",en:"it is answered at the press, not at an appointment"}},{key:"familyRequest",why:{de:"sie fragt nicht die Familie",en:"it does not ask the family"}},{key:"feedback",why:{de:"sie beantwortet die ausl\xF6sende Person, nicht ein Link",en:"the presser answers it, not a link"}},{key:"completableIf",why:{de:"sie wird beim Ausl\xF6sen erledigt, eine Vorbedingung w\xFCrde jedes Ausl\xF6sen ablehnen",en:"it is completed at the press, a precondition would refuse every press"}},{key:"locksEvidence",why:{de:"eine offene Korrektur w\xFCrde jedes Ausl\xF6sen ablehnen",en:"an open correction would refuse every press"}}];function uC(e){let{nodeId:n,bindingKey:t,binding:r}=e;if(r.input===void 0)return[];let i=[],o=`nodes.${n}.optionalActions.${t}.input`,a=s(y=>{i.push({layer:"GRAPH",kind:"nodeRule",path:o,severity:"error",reason:{de:`[optionalAction/input] Optionale Aktion "${t}" auf Knoten "${n}": ${y.de}`,en:`[optionalAction/input] Optional action "${t}" on node "${n}": ${y.en}`}})},"push"),l=r.input;if(typeof l!="string"||l.trim().length===0)return a({de:"'input' muss der Schl\xFCssel einer ihrer Aufgaben sein.",en:"'input' must be the key of one of its tasks."}),i;let d=Array.isArray(r.tasks)?r.tasks:[];if(!d.includes(l))return a({de:`Die Eingabe "${l}" ist keine ihrer Aufgaben ('tasks') \u2014 die Eingabe geh\xF6rt zur Runde der Aktion.`,en:`The input "${l}" is none of its tasks ('tasks') \u2014 the input belongs to the action's round.`}),i;let c=s(y=>{let k=e.templates.find(w=>w.key===y);return k!==void 0&&k.optional===void 0&&k.blocks===void 0},"holdsNode");d.some(y=>y!==l&&c(y))||a({de:`Neben der Eingabe "${l}" hat die Aktion keine Aufgabe, die den Schritt zur\xFCckh\xE4lt (weder 'optional' noch hinter 'blocks') \u2014 die Runde w\xE4re mit dem Ausl\xF6sen schon erledigt.`,en:`Besides the input "${l}" the action has no task that holds the step (neither 'optional' nor behind 'blocks') \u2014 the round would be done with the press.`});let u=e.templates.find(y=>y.key===l);if(u===void 0)return i;u.result?.kind!=="record"&&a({de:`Die Eingabe "${l}" braucht ein Ergebnis der Art 'record' \u2014 nur dessen Werte lesen die anderen Aufgaben der Runde.`,en:`The input "${l}" needs a result of kind 'record' \u2014 only its values are read by the round's other tasks.`});let p=u.assign?.group;typeof r.trigger!="string"?a({de:"Mit einer Eingabe braucht die Aktion ein 'trigger'-Team \u2014 die Eingabe ist eine Aufgabe dieses Teams.",en:"With an input the action needs a 'trigger' team \u2014 the input is a task of that team."}):p!==void 0&&p!==r.trigger&&a({de:`Die Eingabe "${l}" geh\xF6rt dem Team "${String(p)}", ausgel\xF6st wird die Aktion vom Team "${r.trigger}" \u2014 wer ausl\xF6st, beantwortet die Eingabe, also ist es dasselbe Team.`,en:`The input "${l}" belongs to the team "${String(p)}", the action is pressed by the team "${r.trigger}" \u2014 whoever presses answers the input, so it is the same team.`});let h=u.result?.fields;for(let y of Array.isArray(h)?h:[])y.evidence===!0&&a({de:`Das Feld "${String(y.key)}" der Eingabe "${l}" verlangt eine Datei ('evidence') \u2014 das Ausl\xF6sen tr\xE4gt nur Werte.`,en:`The field "${String(y.key)}" of the input "${l}" demands a file ('evidence') \u2014 the press carries values only.`});for(let{key:y,why:k}of kJ)u[y]!==void 0&&a({de:`Die Eingabe "${l}" tr\xE4gt '${y}' \u2014 ${k.de}.`,en:`The input "${l}" carries '${y}' \u2014 ${k.en}.`});for(let y of e.templates){let k=y.blocks;k?.templateKey!==l||k.node!==void 0&&k.node!==n||a({de:`"${String(y.key)}" h\xE4lt die Eingabe "${l}" per 'blocks' zur\xFCck \u2014 sie ist beim Anlegen der Runde schon erledigt, es gibt nichts zur\xFCckzuhalten.`,en:`"${String(y.key)}" holds the input "${l}" back through 'blocks' \u2014 it is already done when the round is created, there is nothing to hold back.`})}return i}s(uC,"optionalActionInputIssues");function bJ(e){let n="error",t=new Map;for(let a of Zt(e.nodes)){let l=t.get(a.source)??[];l.push({id:a.id,target:a.target}),t.set(a.source,l)}let r=[],i=new Set,o=hp(e.nodes.map(a=>a.id),a=>(t.get(a)??[]).map(({id:l,target:d})=>({target:d,edge:l})));for(let a of o)i.has(a.edge)||(i.add(a.edge),r.push({layer:"GRAPH",kind:"cycle",path:`edge.${a.edge}`,reason:{de:`Zyklus \xFCber Kante ${a.source} \u2192 ${a.target}`,en:`Cycle through edge ${a.source} \u2192 ${a.target}`},severity:n}));return r}s(bJ,"checkAcyclic");function vJ(e){let n=[],t=new Set(e.nodes.map(i=>i.id)),r="error";for(let i of e.nodes){let o=i.next;if(o)for(let[a,l]of Object.entries(o))t.has(l.to)||n.push({layer:"GRAPH",kind:"routing",path:`node.${i.id}.next.${a}`,reason:{de:`${i.label.de}: next.${a} verweist auf nicht-existenten Knoten '${l.to}'`,en:`${i.label.en}: next.${a} points to a node that does not exist: '${l.to}'`},severity:"error"});if(i.type!=="end"&&!(!i.outcomes||i.outcomes.length===0))for(let a of i.outcomes)(!o||!(a.id in o))&&n.push({layer:"GRAPH",kind:"routing",path:`node.${i.id}.outcome.${a.id}`,reason:{de:`${i.label.de}: Outcome '${a.label.de}' fehlt im next-Mapping`,en:`${i.label.en}: outcome '${a.label.en}' is missing from the next mapping`},severity:r})}return n}s(vJ,"checkNextTargets");function xJ(e){let n=[];for(let t of e.nodes){let r=t.next;if(!r)continue;let i=mw(t),o=new Set(i?i.map(a=>a.id):[ea]);for(let a of Object.keys(r))o.has(a)||n.push({layer:"GRAPH",kind:"unknownOutcome",path:`node.${t.id}.next.${a}`,reason:{de:`${t.label.de}: next-Schl\xFCssel '${a}' ist kein g\xFCltiges Outcome dieses Knotens (erlaubt: ${[...o].join(", ")}) \u2014 die Kante w\xFCrde im Editor verschwinden`,en:`${t.label.en}: next key '${a}' is not a valid outcome of this node (allowed: ${[...o].join(", ")}) \u2014 the edge would disappear in the editor`},severity:"error"})}return n}s(xJ,"checkNextOutcomesKnown");function SJ(e){let n=[],t=new Set(Zt(e.nodes).map(o=>o.target)),r=e.nodes.filter(o=>!t.has(o.id));return r.length===0?n.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:"Kein Start-Knoten",en:"No start node"},severity:"error"}):r.length>1&&n.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:`Mehrere Start-Knoten (${r.map(o=>o.label.de).join(", ")})`,en:`Multiple start nodes (${r.map(o=>o.label.en).join(", ")})`},severity:"warning"}),e.nodes.filter(o=>o.type==="end").length===0&&n.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:"Kein End-Knoten",en:"No end node"},severity:"warning"}),n}s(SJ,"checkStartEnd");function AJ(e){let n=new Map;for(let r of Zt(e.nodes))n.set(r.source,(n.get(r.source)??0)+1);let t=[];for(let r of e.nodes)r.type!=="end"&&(n.get(r.id)??0)===0&&t.push({layer:"GRAPH",kind:"startEnd",path:`node.${r.id}`,reason:{de:`${r.label.de}: keine ausgehende Kante`,en:`${r.label.en}: no outgoing edge`},severity:"warning"});return t}s(AJ,"checkNoOutgoingEdge");function EJ(e){return e.nodes.filter(n=>!gy(n.id)).map(n=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${n.id}.id`,reason:{de:`[graph/nodeIdFormat] Knoten "${n.id}": eine Knoten-ID ist ein Bezeichner ohne Punkt (${hr.source}), z. B. "reviewEingereicht". Ein Bundle von vor der Umstellung neu exportieren.`,en:`[graph/nodeIdFormat] Node "${n.id}": a node id is an identifier without a dot (${hr.source}), e.g. "reviewSubmitted". Export a bundle from before the change again.`},severity:"error"}))}s(EJ,"checkNodeIdFormat");function TJ(e){let n=new Set(e.nodes.map(r=>r.id)),t=[];for(let r of Zt(e.nodes))n.has(r.source)||t.push({layer:"GRAPH",kind:"startEnd",path:`edge.${r.id}`,reason:{de:`Kante ${r.id}: Quelle '${r.source}' nicht gefunden`,en:`Edge ${r.id}: source '${r.source}' not found`},severity:"error"}),n.has(r.target)||t.push({layer:"GRAPH",kind:"startEnd",path:`edge.${r.id}`,reason:{de:`Kante ${r.id}: Ziel '${r.target}' nicht gefunden`,en:`Edge ${r.id}: target '${r.target}' not found`},severity:"error"});return t}s(TJ,"checkEdgeEndpoints");var $J=new Set(["countersignature"]);function RJ(e){let n=[],t=s((o,a)=>{n.push({layer:"GRAPH",kind:"nodeRule",path:o,reason:{de:`[graph/retiredField] ${a.de}`,en:`[graph/retiredField] ${a.en}`},severity:"error"})},"retired"),r={de:"Preise rechnet der Vertragsgenerator (`prices`), nicht der Workflow \u2014 binde Rang und Reduktion an seine Eing\xE4nge.",en:"Prices are computed by the contract generator (`prices`), not the workflow \u2014 bind rank and reduction to its inputs."},i=e;"pricingRules"in i&&t("pricingRules",r);for(let[o,a]of(Array.isArray(i.processStore)?i.processStore:[]).entries())for(let l of["derive","absentValue"])a!==null&&typeof a=="object"&&l in a&&t(`processStore.${o}.${l}`,r);for(let o of e.nodes)for(let a of o.tasks??[]){let l=a.result;l!==null&&typeof l=="object"&&"prices"in l&&t(`nodes.${o.id}.tasks.${a.key}.result.prices`,r)}for(let o of e.nodes){let a=o,l={de:`Knoten \u201E${_e(e,o.id,"de")}\u201C (${o.id})`,en:`Node "${_e(e,o.id,"en")}" (${o.id})`};for(let[c,u]of Object.entries(a.next??{}))u!==null&&typeof u=="object"&&"emits"in u&&t(`nodes.${o.id}.next.${c}.emits`,{de:`${l.de}: \`next.${c}.emits\` gibt es nicht mehr \u2014 ein Ausgang routet nur; ein Knoten liest Daten \xFCber Adressen in seinen eigenen Feldern.`,en:`${l.en}: \`next.${c}.emits\` no longer exists \u2014 an outcome only routes; a node reads data through addresses in its own fields.`});for(let c of Array.isArray(a.outcomes)?a.outcomes:[])c!==null&&typeof c=="object"&&"emits"in c&&t(`nodes.${o.id}.outcomes.${String(c.id)}.emits`,{de:`${l.de}: \`emits\` am Ausgang "${String(c.id)}" gibt es nicht mehr \u2014 ein Knoten liest Daten \xFCber Adressen in seinen eigenen Feldern.`,en:`${l.en}: \`emits\` on the outcome "${String(c.id)}" no longer exists \u2014 a node reads data through addresses in its own fields.`});"targetFormNodeId"in a&&t(`nodes.${o.id}.targetFormNodeId`,{de:`${l.de}: \`targetFormNodeId\` gibt es nicht mehr \u2014 welches Formular freigeschaltet wird, sagt die Adresse, an die der Eingang \`inputs.target\` gebunden ist ($node.<formular>.admission).`,en:`${l.en}: \`targetFormNodeId\` no longer exists \u2014 the address the input \`inputs.target\` is bound to says which form is unlocked ($node.<form>.admission).`}),"wires"in a&&t(`nodes.${o.id}.wires`,{de:`${l.de}: Datenkanten (\`wires\`) gibt es nicht mehr \u2014 jedes Feld, das Daten eines anderen Knotens liest, tr\xE4gt selbst die volle Adresse ($node.\u2026, $task.\u2026, $env.\u2026).`,en:`${l.en}: data edges (\`wires\`) no longer exist \u2014 every field that reads data of another node carries the full address itself ($node.\u2026, $task.\u2026, $env.\u2026).`});for(let[c,u]of Object.entries(a.inputs??{}))u!==null&&typeof u=="object"&&u.kind==="binding"&&"path"in u&&t(`nodes.${o.id}.inputs.${c}.path`,{de:`${l.de}: Der Eingang \u201E${c}\u201C ist \xFCber einen Pfad (\`path\`) gebunden \u2014 eine Bindung tr\xE4gt die volle Adresse (\`address\`) dessen, was sie liest.`,en:`${l.en}: The input "${c}" is bound through a path (\`path\`) \u2014 a binding carries the full address (\`address\`) of what it reads.`});o.type==="governedDocument"&&"resolver"in a&&t(`nodes.${o.id}.resolver`,{de:`${l.de}: \`resolver\` gibt es nicht mehr \u2014 der Generator ist der Eingang \`inputs.contractGenerator\` ({ kind, key }), seine Parameter stempelt die Plattform (\`generatorStamp\`), ein im Cockpit erg\xE4nzter Parameter ist sein Eingang \`{ kind: "cockpit" }\`.`,en:`${l.en}: \`resolver\` no longer exists \u2014 the generator is the input \`inputs.contractGenerator\` ({ kind, key }), the platform stamps its parameters (\`generatorStamp\`), a parameter completed in the cockpit is its input \`{ kind: "cockpit" }\`.`});let d=a.template;if(o.type==="governedDocument"&&d!==null&&typeof d=="object")for(let c of["key","cockpitFields"])c in d&&t(`nodes.${o.id}.template.${c}`,{de:`${l.de}: \`template.${c}\` gibt es nicht mehr \u2014 ${c==="key"?"die Vorlage ist der Eingang `inputs.documentTemplate`":'ein im Cockpit erg\xE4nzter Parameter ist sein Eingang `{ kind: "cockpit" }`'}.`,en:`${l.en}: \`template.${c}\` no longer exists \u2014 ${c==="key"?"the template is the input `inputs.documentTemplate`":'a parameter completed in the cockpit is its input `{ kind: "cockpit" }`'}.`});if(o.type==="setFlag")for(let c of["target","flagKey","value"])c in a&&t(`nodes.${o.id}.${c}`,{de:`${l.de}: \`${c}\` gibt es am setFlag-Knoten nicht mehr \u2014 Formular, Merkmal und Wert sind die Eing\xE4nge \`inputs.target\` (gebunden an die Adresse $node.<formular>.admission), \`inputs.flagKey\` und \`inputs.value\` (feste Werte).`,en:`${l.en}: \`${c}\` no longer exists on a setFlag node \u2014 form, flag and value are the inputs \`inputs.target\` (bound to the address $node.<form>.admission), \`inputs.flagKey\` and \`inputs.value\` (literals).`});for(let c of Object.keys(Hy[o.type]??{}))c in a&&t(`nodes.${o.id}.${c}`,{de:`${l.de}: \`${c}\` gibt es als Knoteneigenschaft nicht mehr \u2014 es ist der Eingang \`inputs.${c}\` (ein fester Wert im Parameter-Bereich).`,en:`${l.en}: \`${c}\` no longer exists as a node property \u2014 it is the input \`inputs.${c}\` (a fixed value among the parameters).`});for(let c of Array.isArray(a.tasks)?a.tasks:[]){let u=c?.assign;u===null||typeof u!="object"||!("userId"in u)||t(`nodes.${o.id}.tasks.${String(c.key)}.assign.userId`,{de:`Aufgabe "${String(c.key)}" an ${l.de}: \`assign.userId\` gibt es nicht mehr \u2014 eine Aufgabe nennt ihr Team (\`assign.group\`), nie eine feste Person.`,en:`Task "${String(c.key)}" on ${l.en}: \`assign.userId\` no longer exists \u2014 a task names its team (\`assign.group\`), never a fixed person.`})}for(let c of Jy[o.type]??[])c in a&&t(`nodes.${o.id}.${c}`,{de:`${l.de}: \`${c}\` gibt es nicht mehr \u2014 dieser Knotentyp liest es nicht.`,en:`${l.en}: \`${c}\` no longer exists \u2014 this node type does not read it.`});for(let[c,u]of Object.entries(HO[o.type]??{}))c in a&&t(`nodes.${o.id}.${c}`,{de:`${l.de}: ${u.de}`,en:`${l.en}: ${u.en}`});a.adoptForm===!0&&t(`nodes.${o.id}.adoptForm`,{de:`${l.de}: \`adoptForm: true\` gibt es nicht mehr \u2014 \`adoptForm\` ist die Adresse des \xFCbernommenen Formulars ($node.<anlegender Formularknoten>.admission).`,en:`${l.en}: \`adoptForm: true\` no longer exists \u2014 \`adoptForm\` is the address of the adopted form ($node.<creating form node>.admission).`});for(let c of Array.isArray(a.tasks)?a.tasks:[]){let u=c?.result?.kind;typeof u=="string"&&$J.has(u)&&t(`nodes.${o.id}.tasks.${String(c.key)}.result`,{de:`Aufgabe "${String(c.key)}" an ${l.de}: das Ergebnis \u201E${u}" gibt es nicht mehr \u2014 die Gegenzeichnung ist der Knotentyp \u201EUnterschrift (intern)" (countersign).`,en:`Task "${String(c.key)}" on ${l.en}: the result "${u}" no longer exists \u2014 the countersignature is the node type "Signature (internal)" (countersign).`})}}return n}s(RJ,"checkRetiredDataFields");function ka(e,n){return n?.wiring&&n.layout?{wiring:n.wiring,layout:n.layout}:null}s(ka,"resolveLayoutContext");function IJ(e,n){let t=ka(e,n);if(!t)return e.nodes.some(o=>(He(o)?.progressEvents?.length??0)>0)?[{layer:"GRAPH",kind:"progressState",path:"graph.progressWiring",reason:{de:`Graph emittiert Progress-Events, aber (Layout, Wiring) konnte nicht aufgel\xF6st werden (Wiring ${n?.wiring?"vorhanden":"fehlt"}, Layout ${n?.layout?"vorhanden":"fehlt"}) \u2014 der Engine wirft beim Spiegeln zur Laufzeit. Der Workflow-Entwurf muss progressLayout und progressWiring tragen.`,en:`The graph emits progress events, but (layout, wiring) could not be resolved (wiring ${n?.wiring?"present":"missing"}, layout ${n?.layout?"present":"missing"}) \u2014 the engine throws at runtime when mirroring. The workflow draft must carry progressLayout and progressWiring.`},severity:"error"}]:[];let r=[];for(let i of e.nodes){let a=He(i)?.progressEvents;if(a)for(let l of a){let d=Hs(t.wiring,{id:i.id,type:i.type},l);if(!d){r.push({layer:"GRAPH",kind:"progressState",path:`node.${i.id}.progressEvents.${l}`,reason:{de:`${i.type} '${i.id}': Progress-Event '${l}' ist im Wiring (Layout '${t.layout.id}') keinem (Bus, State) zugeordnet \u2014 der Engine wirft beim Spiegeln`,en:`${i.type} '${i.id}': progress event '${l}' is not mapped to any (bus, state) in the wiring (layout '${t.layout.id}') \u2014 the engine throws when mirroring`},severity:"error"});continue}let c;try{c=Hf(t.layout,d.bus)}catch{r.push({layer:"GRAPH",kind:"progressState",path:`node.${i.id}.progressEvents.${l}`,reason:{de:`${i.type} '${i.id}': Event '${l}' verweist auf unbekannten Bus '${d.bus}' im Layout '${t.layout.id}'`,en:`${i.type} '${i.id}': event '${l}' points to unknown bus '${d.bus}' in layout '${t.layout.id}'`},severity:"error"});continue}Kl(c,d.state)||r.push({layer:"GRAPH",kind:"progressState",path:`node.${i.id}.progressEvents.${l}`,reason:{de:`${i.type} '${i.id}': Event '${l}' verweist auf State '${d.state}', der nicht im Bus '${d.bus}' deklariert ist`,en:`${i.type} '${i.id}': event '${l}' points to state '${d.state}', which is not declared in bus '${d.bus}'`},severity:"error"})}}return r}s(IJ,"checkProgressEventMappings");function OJ(e,n){let t=ka(e,n);if(!t)return[];let r=[];for(let i of t.layout.buses){if(!i.boards||i.boards.length===0)continue;let o=new Set(i.unboarded??[]),a=new Set;for(let l of i.boards)for(let d of l.columns)for(let c of d.states)a.add(c),Kl(i,c)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.board.${l.id}.column.${d.id}.${c}`,reason:{de:`Board '${l.id}', Spalte '${d.id}' referenziert State '${c}', der nicht im Bus '${i.key}' deklariert ist`,en:`Board '${l.id}', column '${d.id}' references state '${c}', which is not declared in bus '${i.key}'`},severity:"error"});for(let l of i.states)a.has(l.id)||o.has(l.id)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.${l.id}`,reason:{de:`State '${l.id}' (${l.label.de}) erscheint in keiner Board-Spalte und nicht in 'unboarded' \u2014 nicht darstellbar`,en:`State '${l.id}' (${l.label.en}) appears in no board column and not in 'unboarded' \u2014 it cannot be displayed`},severity:"error"})}return r}s(OJ,"checkProgressBoardCoverage");function _J(e,n){let t=ka(e,n);if(!t)return[];let r=[];for(let i of t.layout.buses)if(!(!i.boards||i.boards.length===0))for(let o of i.boards)for(let a of We){let l=new Map;for(let d of o.columns){if(!Pi(d.label))continue;let c=d.label[a],u=c.trim().toLocaleLowerCase(a),p=l.get(u);if(p===void 0){l.set(u,d.id);continue}r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.board.${o.id}.column.${d.id}.label.${a}`,reason:{de:`Board '${o.id}' hat zwei Spalten mit dem Label '${c}' (${a}) ('${p}' und '${d.id}') \u2014 f\xFCr Lesende nicht unterscheidbar. F\xFChre die Spalten zusammen (states beider in EINE Spalte) oder vergib unterschiedliche Labels.`,en:`Board '${o.id}' has two columns with the label '${c}' (${a}) ('${p}' and '${d.id}') \u2014 readers cannot tell them apart. Merge the columns (put the states of both into ONE column) or give them different labels.`},severity:"error"})}}return r}s(_J,"checkProgressBoardDistinctLabels");function NJ(e,n){let t=ka(e,n);if(!t)return[];let r=[];for(let i of t.layout.buses)for(let o of i.states){let a=Jf(i,o.id);o.terminal&&!a&&r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.${o.id}.terminalSemantics`,reason:{de:`Terminal-State '${o.id}' hat keine Terminal-Semantik im Bus '${i.key}' \u2014 der Engine wirft beim Versiegeln`,en:`Terminal state '${o.id}' has no terminal semantics in bus '${i.key}' \u2014 the engine throws when sealing`},severity:"error"}),!o.terminal&&a&&r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.${o.id}.terminalSemantics`,reason:{de:`State '${o.id}' ist nicht terminal, hat aber Terminal-Semantik im Bus '${i.key}' \u2014 Inkonsistenz`,en:`State '${o.id}' is not terminal but has terminal semantics in bus '${i.key}' \u2014 inconsistent`},severity:"error"})}return r}s(NJ,"checkProgressTerminalSemantics");function PJ(e,n){let t=ka(e,n);if(!t)return[];let r=[];for(let i of t.layout.buses){let o=new Set(i.holdsSeat??[]);for(let a of i.holdsSeat??[])Kl(i,a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.holdsSeat.${a}`,reason:{de:`holdsSeat referenziert '${a}', das kein State im Bus '${i.key}' ist`,en:`holdsSeat references '${a}', which is not a state in bus '${i.key}'`},severity:"error"});for(let a of i.commitsSeat??[])Kl(i,a)?o.has(a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.commitsSeat.${a}`,reason:{de:`commitsSeat '${a}' ist nicht in holdsSeat \u2014 ein fest belegter Platz muss auch belegt sein`,en:`commitsSeat '${a}' is not in holdsSeat \u2014 a firmly committed seat must also be held`},severity:"error"}):r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.commitsSeat.${a}`,reason:{de:`commitsSeat referenziert '${a}', das kein State im Bus '${i.key}' ist`,en:`commitsSeat references '${a}', which is not a state in bus '${i.key}'`},severity:"error"});for(let[a,l]of Object.entries(i.terminalSemantics??{}))l.outcome==="approved"&&(o.has(a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.holdsSeat`,reason:{de:`Endzustand '${a}' schlie\xDFt den Prozess positiv ab (outcome 'approved'), steht aber nicht in holdsSeat \u2014 damit z\xE4hlt er als Absage und f\xE4llt aus dem Fortschrittsbalken. Nimm '${a}' in holdsSeat (und in commitsSeat, wenn der Platz damit wirklich belegt ist) auf.`,en:`Final state '${a}' ends the process positively (outcome 'approved'), but is not in holdsSeat \u2014 so it counts as a rejection and drops out of the progress bar. Add '${a}' to holdsSeat (and to commitsSeat, if the seat is really taken by it).`},severity:"error"}))}return r}s(PJ,"checkProgressSeatStates");var Lp={de:"Abhilfe: nach dem Formularknoten einen review-Knoten einf\xFCgen und dessen 'reviewing' auf diesen Zustand mappen",en:"Remedy: insert a review node after the form node and map its 'reviewing' to this state"};function CJ(e){return e==="both"?{de:`${Lp.de} \u2014 die Spalte ist auch der Schritt, den die Familie sieht; den Zustand in die Spalte des Nachfolgers zu legen, n\xE4hme ihr diesen Schritt.`,en:`${Lp.en} \u2014 the column is also the step the family sees; moving the state into the successor's column would take that step away from them.`}:{de:`${Lp.de}, oder den Zustand in die Spalte des Nachfolgers legen.`,en:`${Lp.en}, or move the state into the successor's column.`}}s(CJ,"passThroughRemedy");function DJ(e,n){let t=ka(e,n);if(!t)return[];let{layout:r,wiring:i}=t;if(!r.buses.some(v=>v.key==="process"))return[];let o=E_(r);if(!o)return[];let a=new Map(e.nodes.map(v=>[v.id,v])),l=s(v=>He(v).progressEvents??[],"eventsOf"),d=s(v=>Object.values(v.next??{}).map(A=>A.to),"routesOf"),c=s((v,A)=>{let E=a.get(v);if(!E||A.has(v))return null;if(l(E).length>0)return[E];if(pC[E.type]!==!1)return null;let R=d(E);if(R.length===0)return null;let P=[];for(let F of R){let b=c(F,new Set([...A,v]));if(!b)return null;P.push(...b)}return P},"firstProgressNodes"),u=s((v,A)=>{let E=[];for(let R of l(v)){let P=Hs(i,v,R);if(!P||P.bus!==A.bus||P.state===A.state)return null;E.push(P.state)}return[...new Set(E)].join("' / '")},"overwrites"),p=s((v,A)=>{let E=d(v);if(E.length===0)return null;let R=[];for(let P of E){let F=c(P,new Set([v.id]));if(!F)return null;for(let b of F){let O=u(b,A);if(O===null)return null;R.push({de:`'${b.id}' (${b.type}) mit '${O}'`,en:`'${b.id}' (${b.type}) with '${O}'`})}}return[...new Map(R.map(P=>[P.de,P])).values()]},"submitOverwrittenBy"),h=new Map;for(let v of e.nodes)for(let A of l(v)){let E=Hs(i,v,A);if(!E||E.bus!=="process")continue;let R=v.type==="form"&&A===yf?p(v,E):null,P=R?{de:`'${v.id}'.${A} erreicht ihn, und ${R.map(F=>F.de).join(", ")} \xFCberschreibt ihn in derselben Transaktion`,en:`'${v.id}'.${A} reaches it, and ${R.map(F=>F.en).join(", ")} overwrites it in the same transaction`}:null;h.set(E.state,[...h.get(E.state)??[],P])}let y=Hf(r,"process"),k=new Map;for(let[v,A]of h){if(!A.every(R=>R!==null))continue;let E=[...new Map(A.map(R=>[R.de,R])).values()];k.set(v,{de:E.map(R=>R.de).join("; "),en:E.map(R=>R.en).join("; ")})}let w=[];for(let v of o.columns){if(v.states.length===0||!v.states.every(R=>k.has(R)))continue;let A=v.states.map(R=>{let P=y.holdsSeat?.includes(R)===!0,F=k.get(R);return{de:`Zustand '${R}'${P?" (steht in holdsSeat, belegt aber nie einen Platz)":""}: ${F.de}`,en:`State '${R}'${P?" (is in holdsSeat, but never takes a seat)":""}: ${F.en}`}}),E=CJ(o.audience);w.push({layer:"GRAPH",kind:"progressState",path:`progressLayout.process.boards.${o.id}.columns.${v.id}`,reason:{de:`[progress/passThroughState] Spalte \u201E${v.label.de}" ('${v.id}', Board '${o.id}') bleibt immer leer \u2014 ${A.map(R=>R.de).join("; ")}. ${E.de}`,en:`[progress/passThroughState] Column "${v.label.en}" ('${v.id}', board '${o.id}') always stays empty \u2014 ${A.map(R=>R.en).join("; ")}. ${E.en}`},severity:"warning"})}return w}s(DJ,"checkProgressPassThroughColumns");function FJ(e){let n=["workItems","workitems","work_items","taskTemplates"],t=[];for(let r of e.nodes){let i=r;for(let o of n){let a=i[o];a!=null&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.${o}`,reason:{de:`[workItems/misnamedTasksKey] Knoten "${r.id}" deklariert "${o}" \u2014 komponierte Aufgaben werden ausschlie\xDFlich unter "tasks" gelesen. So wie es dasteht, w\xFCrde die Aufgabenkette stillschweigend nie entstehen. Benenne den Schl\xFCssel in "tasks" um.`,en:`[workItems/misnamedTasksKey] Node "${r.id}" declares "${o}" \u2014 composed tasks are read only from "tasks". As it stands, the task chain would silently never be created. Rename the key to "tasks".`},severity:"error"})}}return t}s(FJ,"checkMisnamedTasksKey");function LJ(e){let n=[];for(let t of e.nodes){let r=t,i=Array.isArray(r.tasks)?r.tasks:[],o=new Set;for(let c of i){let u=typeof c.key=="string"?c.key:void 0;u!==void 0&&(o.has(u)&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}`,reason:{de:`[workItems/duplicateTemplateKey] Doppelter Template-Key "${u}" auf Knoten "${r.id}".`,en:`[workItems/duplicateTemplateKey] Duplicate template key "${u}" on node "${r.id}".`},severity:"error"}),o.add(u))}let a=new Set;for(let c of Array.isArray(r.artifacts)?r.artifacts:[])typeof c.key=="string"&&a.add(`${c.key}Uploaded`);let l=He(t),d=new Map((typeof l.workItemTemplates=="function"?l.workItemTemplates(t):[]).map(c=>[c.key,c]));for(let c of i){let u=typeof c.key=="string"?c.key:"?",p=typeof c.kind=="string"?c.kind:void 0;if(p===void 0||!Wl.has(p)){n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.kind`,reason:{de:`[workItems/invalidKind] Task "${u}" auf Knoten "${r.id}" hat Art ${JSON.stringify(c.kind)}; komponierbar sind: ${[...Wl].join(", ")}.`,en:`[workItems/invalidKind] Task "${u}" on node "${r.id}" has kind ${JSON.stringify(c.kind)}; composable kinds are: ${[...Wl].join(", ")}.`},severity:"error"});continue}p==="task"&&c.gatesNode!==void 0&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.gatesNode`,reason:{de:`[workItems/gatesNodeOnTask] 'gatesNode' ist nur f\xFCr die Art 'approval' zul\xE4ssig \u2014 eine Task gated ihren Knoten nie direkt. Um eine gatende Freigabe zur\xFCckzuhalten, 'blocks' verwenden (Task "${u}" auf Knoten "${r.id}").`,en:`[workItems/gatesNodeOnTask] 'gatesNode' is only allowed for the kind 'approval' \u2014 a task never gates its node directly. To hold back a gating approval, use 'blocks' (task "${u}" on node "${r.id}").`},severity:"error"});let h=c.blocks,y=h===void 0?void 0:TP(e,r.id,h.node);if(h!==void 0&&y===null)n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.node`,reason:{de:`[workItems/blocksUnknownNode] 'blocks.node' auf Task "${u}" (Knoten "${r.id}") nennt ${JSON.stringify(h.node)} \u2014 diesen Knoten gibt es im Workflow nicht.`,en:`[workItems/blocksUnknownNode] 'blocks.node' on task "${u}" (node "${r.id}") names ${JSON.stringify(h.node)} \u2014 there is no such node in the workflow.`},severity:"error"});else if(h!==void 0&&y!==void 0&&y!==null){let w=y.node.id===r.id,v=y.node.id,A=w?o:y.composedKeys,E=w?d:y.intrinsicByKey,R=y.node.assign??{};p==="approval"&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks`,reason:{de:`[workItems/blocksOnApproval] 'blocks' ist auf der Art 'approval' verboten \u2014 nur Task-Zeilen d\xFCrfen einen Geschwister-Spawn zur\xFCckhalten (Approval "${u}" auf Knoten "${r.id}").`,en:`[workItems/blocksOnApproval] 'blocks' is forbidden on the kind 'approval' \u2014 only task rows may hold back a sibling spawn (approval "${u}" on node "${r.id}").`},severity:"error"});let P=h.templateKey,F=[...new Set([...A,...E.keys()])].filter(O=>!w||O!==u).join(", "),b={de:F||"keine",en:F||"none"};if(typeof P!="string"||w&&P===u||!A.has(P)&&!E.has(P))n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.templateKey`,reason:{de:`[workItems/blocksUnknownTarget] 'blocks' muss ein Template auf dem Zielknoten benennen \u2014 komponiert ODER intrinsisch (nie sich selbst, nie ohne 'templateKey': die zielfreie Form geh\xF6rt der Maschine, nicht dem Autor). Ziel ${JSON.stringify(P)} auf Knoten "${v}"; zul\xE4ssige Ziele: ${b.de}.`,en:`[workItems/blocksUnknownTarget] 'blocks' must name a template on the target node \u2014 composed OR intrinsic (never itself, never without 'templateKey': the target-less form belongs to the engine, not the author). Target ${JSON.stringify(P)} on node "${v}"; allowed targets: ${b.en}.`},severity:"error"});else if(y.refuse(P)!==null)n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.templateKey`,reason:y.refuse(P),severity:"error"});else{let O=E.get(P);h.except!==void 0&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.except`,reason:{de:`[workItems/blocksExceptRetired] 'blocks.except' auf Task "${u}" (Knoten "${r.id}") gibt es nicht mehr: eine blockierende Aufgabe sperrt die ganze Aktionsgruppe ihres Ziels (bei einer Entscheidung Freigeben, Warteliste, Ablehnen und das Nachr\xFCcken). 'except' entfernen.`,en:`[workItems/blocksExceptRetired] 'blocks.except' on task "${u}" (node "${r.id}") no longer exists: a blocking task locks the whole action group of its target (for a decision: approve, waitlist, reject and promote). Remove 'except'.`},severity:"error"}),O!==void 0&&O.recipient!=="external"&&O.verdictResolved!==!0&&typeof R[P]!="string"&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.templateKey`,reason:{de:`[workItems/blocksUnwiredTarget] Task "${u}" auf Knoten "${r.id}" h\xE4lt "${P}" (Knoten "${v}") zur\xFCck, aber der Knoten weist "${P}" keiner Gruppe zu \u2014 ohne 'assign.${P}' entsteht diese Zeile nie: kein Team bekommt die zur\xFCckgehaltene Arbeit, niemand au\xDFer der verantwortlichen Person kann sie tun. Entweder 'assign.${P}' erg\xE4nzen oder das 'blocks' entfernen.`,en:`[workItems/blocksUnwiredTarget] Task "${u}" on node "${r.id}" holds back "${P}" (node "${v}"), but the node assigns "${P}" to no group \u2014 without 'assign.${P}' this row is never created: no team receives the held-back work, and nobody except the responsible person can do it. Either add 'assign.${P}' or remove the 'blocks'.`},severity:"error"})}}{let w=c.completableIf;if(typeof w=="string"&&w.trim().length>0){let v=w.trim().replace(/^!/,"").trim();a.has(v)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.completableIf`,reason:{de:`[workItems/unknownExport] completableIf "${w}" verweist auf unbekannten Node-Export "${v}"; bekannt: ${[...a].join(", ")||"keine"}.`,en:`[workItems/unknownExport] completableIf "${w}" refers to unknown node export "${v}"; known: ${[...a].join(", ")||"none"}.`},severity:"error"})}}let k=c.params;if(k?.commentRequired!==void 0&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.params.commentRequired`,reason:{de:"[workItems/removedParam] 'params.commentRequired' wurde entfernt \u2014 Kommentar-Pflichten werden am Decision-Node ('commentRequired') autorisiert.",en:"[workItems/removedParam] 'params.commentRequired' was removed \u2014 comment requirements are authored on the decision node ('commentRequired')."},severity:"error"}),p!=="approval"){let w=[];k?.onReject!==void 0&&w.push("params.onReject"),k?.revisionGroup!==void 0&&w.push("params.revisionGroup");for(let v of w)n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.${v}`,reason:{de:`[workItems/approvalOnlyField] '${v}' gilt nur f\xFCr die Art 'approval' (Task "${u}" ist '${p}').`,en:`[workItems/approvalOnlyField] '${v}' only applies to the kind 'approval' (task "${u}" is '${p}').`},severity:"error"});continue}k?.onReject!==void 0&&k.onReject!=="spawnRevision"&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.params.onReject`,reason:{de:`[workItems/invalidOnReject] Erwartet 'spawnRevision', erhalten ${JSON.stringify(k.onReject)}.`,en:`[workItems/invalidOnReject] Expected 'spawnRevision', got ${JSON.stringify(k.onReject)}.`},severity:"error"}),k?.onReject==="spawnRevision"&&(typeof k.revisionGroup!="string"||k.revisionGroup.length===0)&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.params.revisionGroup`,reason:{de:`[workItems/spawnRevisionNoTarget] Approval "${u}" mit 'params.onReject: spawnRevision' ohne 'params.revisionGroup' \u2014 die \xDCberarbeitung h\xE4tte keine Ziel-Gruppe.`,en:`[workItems/spawnRevisionNoTarget] Approval "${u}" with 'params.onReject: spawnRevision' but no 'params.revisionGroup' \u2014 the revision would have no target group.`},severity:"error"})}}return n.push(...$P(e)),n}s(LJ,"checkWorkItemTemplates");var MJ=new Set(["complete","approve","reject"]),pC={form:!0,decision:!0,review:!0,waitlist:!0,completenessCheck:!0,collectPayment:!0,eventTrigger:!0,join:!1,roleAssign:!1,setFlag:!1,if:!1,end:!1,countersign:!0,engagePush:!1,governedDocument:!0};function qJ(e){let n=[];for(let t of e.nodes){let r=t,i=He(t),o=Array.isArray(r.tasks)?r.tasks.length:0,a=i.workItemTemplates?.(t)??[];if(o+a.length>0){let v=pC[r.type];v===void 0?n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks`,reason:{de:`[workItems/unknownParkSemantics] Knotentyp "${r.type}" hat keine bekannte Park-Semantik \u2014 NODE_TYPE_PARKS in validators.ts erg\xE4nzen.`,en:`[workItems/unknownParkSemantics] Node type "${r.type}" has no known parking semantics \u2014 add it to NODE_TYPE_PARKS in validators.ts.`},severity:"error"}):v||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks`,reason:{de:`[workItems/templatesOnNonParkingNode] Knoten "${r.id}" (Typ "${r.type}") parkt nie \u2014 seine Work-Item-Templates w\xFCrden im selben Dispatch gespawnt und storniert (totes Muster).`,en:`[workItems/templatesOnNonParkingNode] Node "${r.id}" (type "${r.type}") never parks \u2014 its work-item templates would be spawned and cancelled in the same dispatch (dead pattern).`},severity:"error"})}let l=i.actions?.(t)??[];if(l.length===0&&a.length===0)continue;let d=new Map(l.map(v=>[v.id,v]));for(let v of l)MJ.has(v.id)&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}`,reason:{de:`[capability/reservedActionId] Knotentyp "${r.type}" deklariert die Action "${v.id}" \u2014 reserviert f\xFCr den generischen Complete-/Verdict-Pfad (complete, approve, reject); die Spec muss eine andere Action-Id w\xE4hlen.`,en:`[capability/reservedActionId] Node type "${r.type}" declares the action "${v.id}" \u2014 reserved for the generic complete/verdict path (complete, approve, reject); the spec must choose a different action id.`},severity:"error"});let c=new Set(i.states??[j_]);for(let v of l)if(v.availableIn!==void 0)for(let A of v.availableIn)c.has(A)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}.availableIn`,reason:{de:`[capability/unknownActionState] Action "${v.id}" auf Knotentyp "${r.type}" ist f\xFCr Zustand "${A}" deklariert \u2014 der Typ kennt nur: ${[...c].join(", ")}.`,en:`[capability/unknownActionState] Action "${v.id}" on node type "${r.type}" is declared for state "${A}" \u2014 the type only knows: ${[...c].join(", ")}.`},severity:"error"});let u=mw(t),p=new Set(u?u.map(v=>v.id):[ea]);for(let v of l){if(v.external===void 0)continue;let A=K_(v.external.event),E={de:"hat keine Beschriftung (der Empf\xE4nger bekommt einen leeren Button)",en:"has no label (the recipient would get an empty button)"},R=A?v.kind==="advance"?{de:`ist als "advance" deklariert, l\xF6st den Knoten aber nicht auf (Ereignis "${v.external.event}") \u2014 solche Aktionen sind "internal"`,en:`is declared as "advance", but does not resolve the node (event "${v.external.event}") \u2014 such actions are "internal"`}:v.outcome!==void 0?{de:`nennt das Outcome "${v.outcome}", l\xF6st den Knoten aber nicht auf (Ereignis "${v.external.event}") \u2014 ein Outcome w\xFCrde eine zweite, stille Routing-Vokabel behaupten`,en:`names the outcome "${v.outcome}", but does not resolve the node (event "${v.external.event}") \u2014 an outcome would claim a second, silent routing vocabulary`}:v.label===void 0?E:null:v.kind!=="advance"?{de:`ist als "${v.kind}" deklariert (externe Aktionen l\xF6sen den Knoten auf und m\xFCssen "advance" sein)`,en:`is declared as "${v.kind}" (external actions resolve the node and must be "advance")`}:v.outcome===void 0?{de:"nennt kein Outcome",en:"names no outcome"}:p.has(v.outcome)?v.label===void 0?E:null:{de:`verweist auf das unbekannte Outcome "${v.outcome}" (deklariert: ${[...p].join(", ")||"keine"})`,en:`refers to the unknown outcome "${v.outcome}" (declared: ${[...p].join(", ")||"none"})`};R!==null&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}.external`,reason:{de:`[capability/externalActionNeedsOutcome] Externe Aktion "${v.id}" auf Knotentyp "${r.type}" ${R.de}.`,en:`[capability/externalActionNeedsOutcome] External action "${v.id}" on node type "${r.type}" ${R.en}.`},severity:"error"})}for(let v of a){let A=v.unlocks;if(A.length===0&&v.verdictResolved!==!0&&v.informational!==!0){n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.workItemTemplates.${v.key}.unlocks`,reason:{de:`[capability/emptyUnlocks] Intrinsisches Template "${v.key}" auf Knoten "${r.id}" schaltet keine Action frei (B5).`,en:`[capability/emptyUnlocks] Intrinsic template "${v.key}" on node "${r.id}" unlocks no action (B5).`},severity:"error"});continue}for(let E of A)d.get(E)===void 0&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.workItemTemplates.${v.key}.unlocks`,reason:{de:`[capability/danglingUnlock] Template "${v.key}" auf Knoten "${r.id}" schaltet unbekannte Action "${E}" frei; deklariert: ${[...d.keys()].join(", ")||"keine"}.`,en:`[capability/danglingUnlock] Template "${v.key}" on node "${r.id}" unlocks the unknown action "${E}"; declared: ${[...d.keys()].join(", ")||"none"}.`},severity:"error"})}let h=new Set(a.map(v=>v.key));for(let v of Object.keys(r.assign??{}))h.has(v)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.assign.${v}`,reason:{de:`[capability/unknownAssignKey] assign-Key "${v}" auf Knoten "${r.id}" ist kein intrinsisches Template dieses Knotentyps; bekannt: ${[...h].join(", ")||"keine"}.`,en:`[capability/unknownAssignKey] assign key "${v}" on node "${r.id}" is not an intrinsic template of this node type; known: ${[...h].join(", ")||"none"}.`},severity:"error"});let y=l.filter(v=>v.teamAssignable===!0).map(v=>v.id);for(let v of Object.keys(r.actionTeams??{}))y.includes(v)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actionTeams.${v}`,reason:{de:`[capability/unknownActionTeam] Knoten "${r.id}" nennt ein Team f\xFCr "${v}", aber diese Aktion l\xE4sst sich hier keinem Team geben; m\xF6glich: ${y.join(", ")||"keine"}.`,en:`[capability/unknownActionTeam] Node "${r.id}" names a team for "${v}", but this action cannot be given to a team here; possible: ${y.join(", ")||"none"}.`},severity:"error"});let k=new Set;for(let v of a)if(v.recipient==="external"||typeof(r.assign??{})[v.key]=="string")for(let E of v.unlocks)k.add(E);let w=i.strictActionCoverage===!0;for(let v of l){if(k.has(v.id)||v.superUserOnly===!0)continue;let A=a.find(R=>R.unlocks.includes(v.id)),E=A!==void 0?{de:` Fehlt die Zuweisung assign.${A.key}?`,en:` Is the assignment assign.${A.key} missing?`}:{de:"",en:""};n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}`,reason:{de:`[capability/superUserOnly] Action "${v.id}" auf Knoten "${r.id}" ist von keinem verdrahteten Work-Item freigeschaltet \u2014 nur die verantwortliche Person (Super-User) kann sie ausf\xFChren.${E.de}`,en:`[capability/superUserOnly] Action "${v.id}" on node "${r.id}" is unlocked by no wired work item \u2014 only the responsible person (super user) can perform it.${E.en}`},severity:w?"error":"warning"})}}return n}s(qJ,"checkNodeCapabilityWiring");function KJ(e){let n=new Set(vO()),t=[];for(let r of e.nodes)n.has(r.type)||t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.type`,reason:{de:`[graph/unknownNodeType] Knoten "${r.id}" hat den unbekannten Typ "${String(r.type)}". Registrierte Typen: ${[...n].join(", ")}.`,en:`[graph/unknownNodeType] Node "${r.id}" has the unknown type "${String(r.type)}". Registered types: ${[...n].join(", ")}.`},severity:"error"});return t}s(KJ,"checkKnownNodeTypes");function jJ(e,n){let t=[],r=s((a,l)=>{t.push({layer:"GRAPH",kind:"nodeRule",path:a,reason:l,severity:"error"})},"push"),i=II(e),o=s(a=>typeof a=="object"&&a!==null&&Object.values(a).some(l=>typeof l=="string"&&l.trim().length>0),"hasText");for(let a of e.nodes){let l=a,d=Array.isArray(l.optionalActions)?l.optionalActions:[];if(t.push(...n6(l,d)),d.length===0)continue;let c=He(a),u=new Set(c.optionalActionKinds??[]),p=Array.isArray(l.tasks)?l.tasks:[],h=new Map;for(let w of p)typeof w.key=="string"&&h.set(w.key,w);let y=new Set,k=new Map;for(let w of d){let v=w.key,A=typeof v=="string"&&v.trim().length>0?v:void 0,E=A??"?",R=`nodes.${l.id}.optionalActions.${E}`,P=typeof w.action=="string"?w.action:void 0;if(w.when!==void 0){let F=s(b=>r(`${R}.when`,{de:`[optionalAction/when] Optionale Aktion "${E}" auf Knoten "${l.id}": ${b.de}`,en:`[optionalAction/when] Optional action "${E}" on node "${l.id}": ${b.en}`}),"conditionFinding");if(typeof w.when!="string"||w.when.trim()==="")F({de:"Die Bedingung ist leer \u2014 ohne Bedingung das Feld weglassen.",en:"The condition is empty \u2014 without a condition, omit the field."});else for(let b of wp(w.when,i,n))F(b)}if((P===void 0||!u.has(P))&&r(`${R}.action`,{de:`[optionalAction/kindNotDeclared] Optionale Aktion "${E}" auf Knoten "${l.id}" hat die Art ${JSON.stringify(w.action)} \u2014 `+(u.size===0?`Knotentyp "${l.type}" deklariert keine Familien (spec.optionalActionKinds fehlt).`:`Knotentyp "${l.type}" deklariert nur: ${[...u].join(", ")}.`),en:`[optionalAction/kindNotDeclared] Optional action "${E}" on node "${l.id}" has the kind ${JSON.stringify(w.action)} \u2014 `+(u.size===0?`node type "${l.type}" declares no families (spec.optionalActionKinds is missing).`:`node type "${l.type}" only declares: ${[...u].join(", ")}.`)}),A===void 0?r(`${R}.key`,{de:`[optionalAction/missingKey] Optionale Aktion auf Knoten "${l.id}" ohne (oder mit leerem) 'key' \u2014 Trigger-Action und Template-Keys w\xE4ren namenlos ('optionalAction::\u2026').`,en:`[optionalAction/missingKey] Optional action on node "${l.id}" without (or with an empty) 'key' \u2014 the trigger action and template keys would be nameless ('optionalAction::\u2026').`}):(y.has(A)&&r(`${R}.key`,{de:`[optionalAction/duplicateKey] Doppelter Aktions-Key "${A}" auf Knoten "${l.id}" \u2014 die projizierten Trigger-Actions w\xFCrden kollidieren.`,en:`[optionalAction/duplicateKey] Duplicate action key "${A}" on node "${l.id}" \u2014 the projected trigger actions would collide.`}),y.add(A)),o(w.label)||r(`${R}.label`,{de:`[optionalAction/missingLabel] Optionale Aktion "${E}" auf Knoten "${l.id}" ohne Label \u2014 der Trigger-Button w\xE4re unbeschriftet.`,en:`[optionalAction/missingLabel] Optional action "${E}" on node "${l.id}" without a label \u2014 the trigger button would be unlabeled.`}),P==="spawnTasks"){w.except!==void 0&&r(`${R}.except`,{de:`[optionalAction/exceptRetired] Optionale Aktion "${E}" auf Knoten "${l.id}" tr\xE4gt 'except' \u2014 das gibt es nicht mehr: solange die Aufgaben offen sind, ist die ganze Aktionsgruppe des Knotens gesperrt. 'except' entfernen.`,en:`[optionalAction/exceptRetired] Optional action "${E}" on node "${l.id}" carries 'except' \u2014 that no longer exists: while the tasks are open, the node's whole action group is locked. Remove 'except'.`}),t.push(...uC({nodeId:l.id,bindingKey:E,binding:w,templates:p}));let F=Array.isArray(w.tasks)?w.tasks:void 0;if(F===void 0||F.length===0)r(`${R}.tasks`,{de:`[optionalAction/tasksEmpty] Optionale Aktion "${E}" auf Knoten "${l.id}" referenziert keine Aufgaben-Templates \u2014 der Trigger w\xFCrde nichts erzeugen.`,en:`[optionalAction/tasksEmpty] Optional action "${E}" on node "${l.id}" references no task templates \u2014 the trigger would create nothing.`});else{let b=new Set,O=new Set(F.filter($=>typeof $=="string"));for(let $ of F){let I=typeof $=="string"?$:void 0;if(I===void 0||I.length===0){r(`${R}.tasks`,{de:`[optionalAction/unknownTaskRef] Optionale Aktion "${E}" auf Knoten "${l.id}" enth\xE4lt eine leere/ung\xFCltige Template-Referenz.`,en:`[optionalAction/unknownTaskRef] Optional action "${E}" on node "${l.id}" contains an empty or invalid template reference.`});continue}if(b.has(I)){r(`${R}.tasks.${I}`,{de:`[optionalAction/duplicateTaskRef] Template "${I}" ist in der Aktion "${E}" auf Knoten "${l.id}" doppelt referenziert.`,en:`[optionalAction/duplicateTaskRef] Template "${I}" is referenced twice in the action "${E}" on node "${l.id}".`});continue}b.add(I);let G=h.get(I);if(G===void 0){r(`${R}.tasks.${I}`,{de:`[optionalAction/unknownTaskRef] Optionale Aktion "${E}" auf Knoten "${l.id}" referenziert das Template "${I}", das node.tasks nicht deklariert. Vorhanden: ${[...h.keys()].join(", ")||"keine"}.`,en:`[optionalAction/unknownTaskRef] Optional action "${E}" on node "${l.id}" references the template "${I}", which node.tasks does not declare. Present: ${[...h.keys()].join(", ")||"none"}.`});continue}let B=k.get(I);B!==void 0&&B!==E?r(`${R}.tasks.${I}`,{de:`[optionalAction/taskDoublyBound] Template "${I}" auf Knoten "${l.id}" ist bereits von der Aktion "${B}" referenziert \u2014 ein Template geh\xF6rt zu h\xF6chstens einer optionalen Aktion.`,en:`[optionalAction/taskDoublyBound] Template "${I}" on node "${l.id}" is already referenced by the action "${B}" \u2014 a template belongs to at most one optional action.`}):k.set(I,E);let le=G.blocks?.templateKey;typeof le=="string"&&!O.has(le)&&r(`${R}.tasks.${I}`,{de:`[optionalAction/taskRefBlocks] Template "${I}" auf Knoten "${l.id}" tr\xE4gt 'blocks' auf "${le}", das nicht zur selben Aktion "${E}" geh\xF6rt \u2014 eine Referenz darf nur eine Referenz DERSELBEN Aktion zur\xFCckhalten (Checklisten-Reihenfolge), nie ein Template au\xDFerhalb.`,en:`[optionalAction/taskRefBlocks] Template "${I}" on node "${l.id}" carries 'blocks' on "${le}", which does not belong to the same action "${E}" \u2014 a reference may only hold back a reference of the SAME action (checklist order), never a template outside it.`});for(let Q of p){let re=typeof Q.key=="string"?Q.key:void 0;Q.blocks?.templateKey===I&&(re!==void 0&&O.has(re)||r(`${R}.tasks.${I}`,{de:`[optionalAction/taskRefBlocks] Template "${I}" auf Knoten "${l.id}" ist Ziel eines 'blocks' von ${re!==void 0?`"${re}"`:"einem Template"} au\xDFerhalb der Aktion "${E}" \u2014 ein Template au\xDFerhalb darf eine Referenz nie zur\xFCckhalten (ihr Spawn geh\xF6rt dem Trigger, nicht onEnter).`,en:`[optionalAction/taskRefBlocks] Template "${I}" on node "${l.id}" is the target of a 'blocks' from ${re!==void 0?`"${re}"`:"a template"} outside the action "${E}" \u2014 a template outside may never hold back a reference (its spawn belongs to the trigger, not to onEnter).`}))}}}}}}return t}s(jJ,"checkOptionalActions");function VJ(e){return typeof e=="number"?"number":typeof e=="boolean"?"boolean":"string"}s(VJ,"literalValueType");function BJ(e,n){let t=[],r=n?.notificationTemplates;for(let i of e.nodes){let o=i,a=dN(i,He(i)),l=o.notifications??{};if(a.length===0&&Object.keys(l).length===0)continue;let d=new Map(a.map(c=>[c.id,c]));for(let c of Object.keys(l))d.has(c)||t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${o.id}.notifications.${c}`,reason:{de:`[notification/unknownEvent] Knoten "${o.id}" bindet einen Brief an das Ereignis "${c}", das der Knotentyp "${o.type}" nicht kennt. Angeboten werden: ${a.map(u=>u.id).join(", ")||"(keine)"}.`,en:`[notification/unknownEvent] Node "${o.id}" binds a letter to the event "${c}", which the node type "${o.type}" does not know. Offered: ${a.map(u=>u.id).join(", ")||"(none)"}.`},severity:"error"});for(let c of a){let u=l[c.id];if(c.required===!0&&(u===void 0||u.disabled===!0)){t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${o.id}.notifications.${c.id}`,reason:{de:`[notification/missingBinding] Knoten "${o.id}" muss beim Ereignis "${c.label.de}" (${c.id}) einen Brief verschicken \u2014 es ist ${u===void 0?"keiner gebunden":"einer gebunden, aber abgeschaltet"}.`,en:`[notification/missingBinding] Node "${o.id}" must send a letter on the event "${c.label.en}" (${c.id}) \u2014 ${u===void 0?"none is bound":"one is bound, but switched off"}.`},severity:"error"});continue}if(u===void 0||u.disabled===!0)continue;let p=`nodes.${o.id}.notifications.${c.id}`;if(c.audience!=="external"){t.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/internalAudienceUnsupported] Knoten "${o.id}": das Ereignis "${c.id}" richtet sich an die Schule, und Briefe an die Schule k\xF6nnen noch nicht zugestellt werden \u2014 der gebundene Brief "${u.templateId}" w\xFCrde den Vorgang beim Versand abbrechen.`,en:`[notification/internalAudienceUnsupported] Node "${o.id}": the event "${c.id}" is addressed to the school, and letters to the school cannot be delivered yet \u2014 the bound letter "${u.templateId}" would abort the process when it is sent.`},severity:"error"});continue}if(r===void 0)continue;let h=r.get(u.templateId);if(h===void 0){t.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/unknownTemplate] Knoten "${o.id}": der Brief "${u.templateId}" ist nicht im Katalog. Bekannt sind: ${[...r.keys()].sort().join(", ")||"(keine)"}.`,en:`[notification/unknownTemplate] Node "${o.id}": the letter "${u.templateId}" is not in the catalog. Known: ${[...r.keys()].sort().join(", ")||"(none)"}.`},severity:"error"});continue}h.audience!==void 0&&h.audience!==c.audience&&t.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/audienceMismatch] Der Brief "${h.id}" ist f\xFCr ${h.audience==="internal"?"die Schule":"die Familie"} geschrieben, das Ereignis "${c.id}" richtet sich aber an die Familie.`,en:`[notification/audienceMismatch] The letter "${h.id}" is written for ${h.audience==="internal"?"the school":"the family"}, but the event "${c.id}" is addressed to the family.`},severity:"warning"});let y=iN(c),k=new Set(h.params.map(w=>w.key));for(let w of Object.keys(u.args??{}))k.has(w)||t.push({layer:"GRAPH",kind:"nodeRule",path:`${p}.args.${w}`,reason:{de:`[notification/unknownArg] Der Brief "${h.id}" hat kein Argument "${w}" \u2014 erwartet werden: ${h.params.map(v=>v.key).join(", ")||"(keine)"}.`,en:`[notification/unknownArg] The letter "${h.id}" has no argument "${w}" \u2014 expected: ${h.params.map(v=>v.key).join(", ")||"(none)"}.`},severity:"error"});for(let w of h.params){let v=u.args?.[w.key],A=`${p}.args.${w.key}`;if(v!==void 0&&"literal"in v){let R=VJ(v.literal);w.type!==void 0&&!Rw(R,w.type)&&t.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/argTypeMismatch] "${w.key}" erwartet ${Gl(w.type).de}, festgelegt ist aber ${JSON.stringify(v.literal)} (${R}).`,en:`[notification/argTypeMismatch] "${w.key}" expects ${Gl(w.type).en}, but ${JSON.stringify(v.literal)} (${R}) is set.`},severity:"error"});continue}if(v!==void 0){t.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/unsupportedArg] "${w.key}" ist an ${JSON.stringify(v)} gebunden \u2014 ein Brief-Argument kann nur ein Festwert ({ literal }) sein oder automatisch aus ${fC(y,"de")} kommen.`,en:`[notification/unsupportedArg] "${w.key}" is bound to ${JSON.stringify(v)} \u2014 a letter argument can only be a fixed value ({ literal }) or come automatically from ${fC(y,"en")}.`},severity:"error"});continue}let E=oN(w,y.get(w.key)??[]);if(!(E.status==="resolved"||E.status==="unused")){if(E.status==="sometimes"){t.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/unresolvedArg] Der Brief "${h.id}" braucht "${w.key}" immer, ${E.source.source} liefert es aber nur manchmal. In notifications.${c.id}.args.${w.key} einen Festwert benennen \u2014 oder einen Brief w\xE4hlen, der ohne "${w.key}" auskommt.`,en:`[notification/unresolvedArg] The letter "${h.id}" always needs "${w.key}", but ${E.source.source} provides it only sometimes. Name a fixed value in notifications.${c.id}.args.${w.key} \u2014 or choose a letter that works without "${w.key}".`},severity:"error"});continue}if(E.status==="ambiguous"){t.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/ambiguousArg] "${w.key}" hat mehrere passende Quellen \u2014 ${E.matches.map(R=>R.source).join(", ")}. In notifications.${c.id}.args.${w.key} einen Festwert setzen.`,en:`[notification/ambiguousArg] "${w.key}" has several matching sources \u2014 ${E.matches.map(R=>R.source).join(", ")}. Set a fixed value in notifications.${c.id}.args.${w.key}.`},severity:"error"});continue}t.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/unresolvedArg] Der Brief "${h.id}" braucht "${w.key}"${w.type!==void 0?` (${Gl(w.type).de})`:""}, und der Knoten hat daf\xFCr ${E.rejected.length===0?"keine Quelle":`nur unpassende Quellen: ${E.rejected.map(R=>`${R.source} (${R.type})`).join(", ")}`}.`,en:`[notification/unresolvedArg] The letter "${h.id}" needs "${w.key}"${w.type!==void 0?` (${Gl(w.type).en})`:""}, and the node has ${E.rejected.length===0?"no source for it":`only unsuitable sources for it: ${E.rejected.map(R=>`${R.source} (${R.type})`).join(", ")}`}.`},severity:"error"})}}}}return t}s(BJ,"checkNotificationBindings");function UJ(e){return KN(e).map(n=>({layer:"GRAPH",kind:"assignment",path:"assignmentRules",reason:n,severity:"error"}))}s(UJ,"checkAssignmentRules");function fC(e,n){let t=[...e.keys()].sort();return t.length===0?n==="de"?"(nichts)":"(nothing)":t.join(", ")}s(fC,"describeCandidates");function GJ(e,n){return BN(e,n?.teamKeys).map(t=>({layer:"GRAPH",kind:"nodeRule",path:t.path,reason:t.reason,severity:"error"}))}s(GJ,"checkChannels");function zJ(e){return _I(e).map(n=>({layer:"GRAPH",kind:"nodeRule",path:n.path,reason:n.reason,severity:"error"}))}s(zJ,"checkStaffInputs");function WJ(e,n){let t=[];for(let r of e.nodes){let i=r.reads;if(i===void 0)continue;let o=`nodes.${r.id}.reads`,a={de:`Knoten \u201E${_e(e,r.id,"de")}\u201C (${r.id})`,en:`Node "${_e(e,r.id,"en")}" (${r.id})`},l=s(c=>{t.push({layer:"GRAPH",kind:"nodeRule",path:o,reason:c,severity:"error"})},"issue");if(!XN(r)){l({de:`[readiness/readsNotGated] ${a.de} (${r.type}) deklariert \`reads\`, aber die Bereitschaftspr\xFCfung h\xE4lt nur Entscheidungs-Knoten und Dokument-Knoten mit Produktion \u2014 hier w\xFCrde \`reads\` nichts bewirken.`,en:`[readiness/readsNotGated] ${a.en} (${r.type}) declares \`reads\`, but the readiness check only holds decision nodes and document nodes with production \u2014 here \`reads\` would have no effect.`});continue}if(!Array.isArray(i)){l({de:`[readiness/readsDuplicate] \`reads\` von ${a.de} muss eine Liste von Feldadressen sein, erhalten ${JSON.stringify(i)}.`,en:`[readiness/readsDuplicate] \`reads\` of ${a.en} must be a list of field addresses, got ${JSON.stringify(i)}.`});continue}let d=new Set;for(let c of i){if(!be(c))continue;let u=ue(c);if(d.has(u)){l({de:`[readiness/readsDuplicate] ${a.de} liest ${je(e,c,"de")} mehrfach.`,en:`[readiness/readsDuplicate] ${a.en} reads ${je(e,c,"en")} more than once.`});continue}if(d.add(u),!un(c)){l({de:`[readiness/readsUnknownField] ${a.de} liest ${je(e,c,"de")} \u2014 \`reads\` nennt nur Felder eines Formulars ($node.<formular>.admission.<feld>).`,en:`[readiness/readsUnknownField] ${a.en} reads ${je(e,c,"en")} \u2014 \`reads\` only names fields of a form ($node.<form>.admission.<field>).`});continue}let p=ai(n,c);p!=null&&Ys("nodeReads",Ws(p))==="repeated"&&l({de:`[readiness/readsUnknownField] ${a.de} liest ${je(e,c,"de")} \u2014 ein Feld in einer Wiederholgruppe ist kein einzelnes Feld der Anmeldung und kann nicht gelesen werden.`,en:`[readiness/readsUnknownField] ${a.en} reads ${je(e,c,"en")} \u2014 a field in a repeated group is not a single field of the application and cannot be read.`})}}return t}s(WJ,"checkReadinessReads");function YJ(e,n){let t=[];for(let r of e.nodes){if(r.type!=="setFlag")continue;let i=PO(r),o=qf(r);if(i===null||o===null)continue;let a=n?.formFlagKeysByFormNode?.get(i);if(a===void 0||a.has(o))continue;let l=[...a].sort();t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.inputs.${_n.flagKey}`,reason:{de:`[setFlag/unknownFlag] Knoten \u201E${_e(e,r.id,"de")}\u201C (${r.id}) setzt \u201E${o}\u201C, aber das Formular von \u201E${_e(e,i,"de")}\u201C hat kein externes Merkmal dieses Namens`+(l.length>0?` (vorhanden: ${l.join(", ")}).`:" \u2014 es deklariert gar keins."),en:`[setFlag/unknownFlag] Node "${_e(e,r.id,"en")}" (${r.id}) sets "${o}", but the form of "${_e(e,i,"en")}" has no external flag of that name`+(l.length>0?` (present: ${l.join(", ")}).`:" \u2014 it declares none at all.")},severity:"error"})}return t}s(YJ,"checkSetFlagKeys");function HJ(e,n){let t=n?.readinessFormFieldsByFormNode,r=n?.readinessPartyConditionKeysByFormNode;if(t===void 0||r===void 0)return[];let i=[];for(let o of e.nodes){if(o.type!=="governedDocument"||o.production!=="resolver")continue;let a=o.form;if(!be(a)||!kr(a))continue;let l=t.get(a.owner),d=r.get(a.owner);if(l===void 0||d===void 0||d.size===0)continue;let c=jw(l,d);if(c.size===0)continue;let u=o.reads,p=(Array.isArray(u)?u:[]).filter(w=>un(w)&&w.owner===a.owner),h=jw(l,[...p.map(w=>w.path),...tP(o).filter(w=>w.owner===a.owner).map(w=>w.fieldKey)]),y=[...c].filter(w=>!h.has(w)).sort();if(y.length===0)continue;let k={de:_e(e,a.owner,"de"),en:_e(e,a.owner,"en")};i.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${o.id}.reads`,reason:{de:`[readiness/readsMissesPartyCondition] Knoten \u201E${_e(e,o.id,"de")}\u201C (${o.id}) erzeugt ein Dokument, dessen Vertragsparteien von Angaben im Formular \u201E${k.de}\u201C abh\xE4ngen, die er weder liest noch bindet: ${y.join(", ")}. Eine Korrektur darauf h\xE4lt den Knoten nicht an und kann nach der Ausstellung eine Vertragspartei entfernen \u2014 die Felder (oder den berechneten Schl\xFCssel) aus \u201E${k.de}\u201C in \`reads\` erg\xE4nzen.`,en:`[readiness/readsMissesPartyCondition] Node "${_e(e,o.id,"en")}" (${o.id}) generates a document whose contract parties depend on answers in the form "${k.en}" that it neither reads nor binds: ${y.join(", ")}. A correction to them does not hold the node and can remove a contract party after issuing \u2014 add the fields (or the computed key) from "${k.en}" to \`reads\`.`},severity:"warning"})}return i}s(HJ,"checkReadinessPartyConditions");function ok(e){let n=Object.keys(e.inputs??{});if(n.length===0)return[];let t=e.generatorStamp,r=e.production,i=e.templateStamp;if(e.type==="governedDocument"&&(r==="resolver"&&!Array.isArray(t?.inputSchema?.fields)||r==="template"&&!Array.isArray(i?.fields)))return[];let a=new Set(Zs(e).map(l=>l.id));return n.filter(l=>!a.has(l))}s(ok,"undeclaredInputKeys");function JJ(e,n){return e.nodes.flatMap(t=>[...ZJ(e,t,Zs(t),n),...QJ(e,t,n)])}s(JJ,"checkUnknownResources");function QJ(e,n,t){let r=[],i=new Set((He(n).workItemTemplates?.(n)??[]).map(a=>a.key)),o=new Set((n.tasks??[]).filter(a=>a.familyRequest!==void 0).map(a=>String(a.key)));for(let a of Wf(n)){if(a.leaf==="assign{}"&&!i.has(a.owner)||a.leaf==="tasks[].assign.group"&&a.missing&&o.has(a.owner))continue;let l=Us[a.leaf],d=`nodes.${n.id}.${a.path}`,c=s(h=>h==="de"?`Knoten \u201E${_e(e,n.id,"de")}\u201C (${n.id}), ${l.what.de} \u201E${a.owner}\u201C`:`node "${_e(e,n.id,"en")}" (${n.id}), ${l.what.en} "${a.owner}"`,"where");if(a.missing){if(!l.required){r.push({layer:"GRAPH",kind:"nodeRule",path:d,severity:"error",reason:{de:`[inputs/emptyReference] ${c("de")}: der Eintrag ist leer oder kein Schl\xFCssel \u2014 ${l.consequence.de}. Team w\xE4hlen oder den Eintrag entfernen.`,en:`[inputs/emptyReference] ${c("en")}: the entry is empty or no key \u2014 ${l.consequence.en}. Choose a team or remove the entry.`}});continue}r.push({layer:"GRAPH",kind:"nodeRule",path:d,severity:"error",reason:{de:`[workItems/needsTeam] ${c("de")}: kein Team gew\xE4hlt \u2014 ${l.consequence.de}. Jede Aufgabe geh\xF6rt der Warteschlange eines Teams.`,en:`[workItems/needsTeam] ${c("en")}: no team chosen \u2014 ${l.consequence.en}. Every task belongs to a team's queue.`}});continue}if(a.key===null)continue;let u=t?.teamKeys;if(u===void 0||u.has(a.key))continue;let p=[...u].sort().join(", ")||"\u2014";r.push({layer:"GRAPH",kind:"nodeRule",path:d,severity:"error",reason:{de:`[inputs/unknownResource] ${c("de")}: \u201E${a.key}\u201C ist kein Team dieses Mandanten \u2014 ${l.consequence.de}. Teams: ${p}.`,en:`[inputs/unknownResource] ${c("en")}: "${a.key}" is no team of this school \u2014 ${l.consequence.en}. Teams: ${p}.`}})}return r}s(QJ,"referenceIssues");function ZJ(e,n,t,r){let i=[];for(let o of t){if(!Kf(o.type))continue;let a=js[o.type].existence;if(a.check!=="generic")continue;let l=r?.[a.catalog];if(l===void 0)continue;let d=n.inputs?.[o.id];if(d?.kind!=="literal"||typeof d.value!="string"||l.has(d.value))continue;let c=js[o.type].label;i.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${n.id}.inputs.${o.id}`,reason:{de:`[inputs/unknownResource] Knoten \u201E${_e(e,n.id,"de")}\u201C (${n.id}) nennt im Eingang \u201E${o.label.de}\u201C ${c.de} \u201E${d.value}\u201C \u2014 diesen Schl\xFCssel kennt dieser Mandant nicht.`,en:`[inputs/unknownResource] Node "${_e(e,n.id,"en")}" (${n.id}) names the ${c.en.toLowerCase()} "${d.value}" in its input "${o.label.en}", which does not exist in this school.`},severity:"error"})}return i}s(ZJ,"unknownResourceIssues");function XJ(e){let n=[];for(let t of e.nodes)for(let r of ok(t))n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.inputs.${r}`,reason:{de:`[inputs/undeclared] Knoten \u201E${_e(e,t.id,"de")}\u201C (${t.id}) hat einen Eingang \u201E${r}\u201C, den sein Typ nicht deklariert \u2014 ein Rest einer fr\xFCheren Einstellung (z. B. eines anderen Generators). Im Parameter-Bereich ist er nicht sichtbar; entfernen.`,en:`[inputs/undeclared] Node "${_e(e,t.id,"en")}" (${t.id}) has an input "${r}" its type does not declare \u2014 a leftover of an earlier setting (e.g. another generator). It is not visible among the parameters; remove it.`},severity:"error"});return n}s(XJ,"checkUndeclaredInputs");function e6(e){let n=[];for(let t of e.nodes){let r=new Set;for(let i of Zs(t)){if(!r.has(i.id)){r.add(i.id);continue}n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.inputs.${i.id}`,reason:{de:`[inputs/duplicateSlot] Knoten \u201E${_e(e,t.id,"de")}\u201C (${t.id}) hat den Eingang \u201E${i.id}\u201C zweimal \u2014 ein Parameter des Generators oder der Vorlage tr\xE4gt den Namen eines Eingangs des Knotentyps. Den Parameter umbenennen.`,en:`[inputs/duplicateSlot] Node "${_e(e,t.id,"en")}" (${t.id}) has the input "${i.id}" twice \u2014 a parameter of the generator or template carries the name of an input of the node type. Rename the parameter.`},severity:"error"})}}return n}s(e6,"checkDuplicateSlots");function mC(e,n,t){let r=[],i=KJ(e);if(i.length>0)return i;r.push(...EJ(e)),r.push(...SJ(e)),r.push(...TJ(e)),r.push(...AJ(e)),r.push(...bJ(e)),r.push(...vJ(e)),r.push(...xJ(e)),r.push(...RJ(e)),r.push(...O_(e,n)),r.push(...IJ(e,n)),r.push(...OJ(e,n)),r.push(..._J(e,n)),r.push(...sP(e,n?.layout)),r.push(...NJ(e,n)),r.push(...PJ(e,n)),r.push(...DJ(e,n)),r.push(...v_(e,t)),r.push(...C_(e)),r.push(...q_(e)),r.push(...N_(e)),r.push(...P_(e)),r.push(...XJ(e)),r.push(...JJ(e,t)),r.push(...e6(e)),r.push(...FJ(e)),r.push(...LJ(e)),r.push(...IP(e,t)),r.push(...CP(e)),r.push(...NP(e)),r.push(...DP(e,t)),r.push(...VP(e,t)),r.push(...qJ(e)),r.push(...BJ(e,t)),r.push(...jJ(e,t)),r.push(...UJ(e)),r.push(...WJ(e,t)),r.push(...HJ(e,t)),r.push(...YJ(e,t)),r.push(...GJ(e,t)),r.push(...zJ(e)),r.push(...cC(e));for(let o of e.nodes){let a=He(o);a.validate&&r.push(...a.validate(o,e,t))}return r}s(mC,"checkGraph");function n6(e,n){let t=e.requiresOneOf;if(t===void 0)return[];let r=`nodes.${e.id}.requiresOneOf`,i=s(d=>({layer:"GRAPH",kind:"nodeRule",path:r,reason:d,severity:"error"}),"issue");if(e.type!=="decision")return[i({de:`[decision/requiresOneOfNotDecision] Knoten "${e.id}" (Typ "${e.type}") tr\xE4gt 'requiresOneOf' \u2014 die Regel gilt nur an Entscheidungsknoten (decision).`,en:`[decision/requiresOneOfNotDecision] Node "${e.id}" (type "${e.type}") carries 'requiresOneOf' \u2014 the rule only applies to decision nodes (decision).`})];if(!Array.isArray(t)||t.length===0||t.some(d=>typeof d!="string"||d.length===0))return[i({de:`[decision/requiresOneOfEmpty] 'requiresOneOf' an Knoten "${e.id}" muss eine nicht-leere Liste von Aktions-Keys sein \u2014 sonst Feld weglassen.`,en:`[decision/requiresOneOfEmpty] 'requiresOneOf' on node "${e.id}" must be a non-empty list of action keys \u2014 otherwise omit the field.`})];let o=n.map(d=>d.key).filter(d=>typeof d=="string"),a=[],l=new Set;for(let d of t){if(l.has(d)){a.push(i({de:`[decision/requiresOneOfDuplicate] 'requiresOneOf' an Knoten "${e.id}" nennt "${d}" doppelt.`,en:`[decision/requiresOneOfDuplicate] 'requiresOneOf' on node "${e.id}" names "${d}" twice.`}));continue}l.add(d),o.includes(d)||a.push(i({de:`[decision/requiresOneOfUnknownAction] 'requiresOneOf' an Knoten "${e.id}" nennt "${d}", aber dieser Knoten hat keine optionale Aktion mit diesem Key \u2014 die Regel w\xE4re nie erf\xFCllbar. `+(o.length===0?"Der Knoten hat keine optionalen Aktionen.":`Optionale Aktionen dieses Knotens: ${o.join(", ")}.`),en:`[decision/requiresOneOfUnknownAction] 'requiresOneOf' on node "${e.id}" names "${d}", but this node has no optional action with that key \u2014 the rule could never be met. `+(o.length===0?"The node has no optional actions.":`Optional actions of this node: ${o.join(", ")}.`)}))}return a}s(n6,"checkRequiresOneOf");function t6(e){return e.nodes.flatMap(n=>ok(n).map(t=>({nodeId:n.id,key:t,binding:n.inputs?.[t]?.kind==="binding"})))}s(t6,"undeclaredInputCells");function hC(e,n){let t=t6(e).filter(o=>n.bindings||!o.binding);if(t.length===0)return{graph:e,dropped:t};let r=new Map;for(let o of t)r.set(o.nodeId,(r.get(o.nodeId)??new Set).add(o.key));let i=e.nodes.map(o=>{let a=r.get(String(o.id));if(a===void 0)return o;let l=Object.fromEntries(Object.entries(o.inputs).filter(([d])=>!a.has(d)));return{...o,inputs:l}});return{graph:{...e,nodes:i},dropped:t}}s(hC,"dropUndeclaredInputs");function sk(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(sk,"isObject");function gC(e){return sk(e)&&e.type==="governedDocument"&&("template"in e||"cockpitFields"in e)}s(gC,"oldShape");function yC(e){return(e?.nodes??[]).some(gC)}s(yC,"needsTemplateStampMove");function r6(e){let n=e.generatorStamp?.inputSchema?.fields;if(e.production==="resolver")return Array.isArray(n)?n:null;let t=e.templateStamp?.fields;return e.production==="template"&&Array.isArray(t)?t:null}s(r6,"stampedFields");function i6(e){let n=String(e.id);if("template"in e&&"templateStamp"in e)return{unmoved:{nodeId:n,reason:"templateAndStamp"}};let t={...e},r=[];if("template"in e){let{template:i}=e;if(delete t.template,sk(i))t.templateStamp={fields:Array.isArray(i.fields)?i.fields:[],...i.localeField===void 0?{}:{localeField:i.localeField}};else return{unmoved:{nodeId:n,reason:"templateNotObject"}}}if("cockpitFields"in e){let i=Array.isArray(e.cockpitFields)?e.cockpitFields.filter(l=>typeof l=="string"):[];delete t.cockpitFields;let o=sk(e.inputs)?{...e.inputs}:{},a=r6(t);if(a===null&&i.length>0)return{unmoved:{nodeId:n,key:i[0],reason:"noStamp"}};for(let l of i){let d=l in o&&o[l]?.kind!=="unset",c=(a??[]).find(u=>u.key===l);if(c===void 0)r.push({nodeId:n,key:l,reason:"unknownKey"});else{if(c.type==="party"||c.type==="personList")continue;c.processSource!==void 0?r.push({nodeId:n,key:l,reason:"processSource"}):d?r.push({nodeId:n,key:l,reason:"cellExists"}):o[l]={kind:"cockpit"}}}t.inputs=o}return{node:t,reports:r}}s(i6,"moveNode");function wC(e){let n=[],t=[],r=[],i=e.nodes.map(o=>{if(!gC(o))return o;let a=i6(o);return"unmoved"in a?(r.push(a.unmoved),o):(n.push(String(o.id)),t.push(...a.reports),a.node)});return n.length===0?{graph:e,moved:n,reports:t,unmoved:r}:{graph:{...e,nodes:i},moved:n,reports:t,unmoved:r}}s(wC,"moveTemplateStampAndCockpit");var kC=wf,o6="applicant.applicationSubmitted";function Mp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Mp,"isObject");function bC(e){return Mp(e)&&e.type==="form"&&typeof e.id=="string"&&!vt(e)}s(bC,"isCreatingFormNode");function s6(e){return Mp(e.notifications)&&kC in e.notifications}s(s6,"hasSubmittedBinding");function ak(e){let n={toBind:[],alreadyBound:[],malformed:[]};for(let t of e?.nodes??[])bC(t)&&(t.notifications!==void 0&&!Mp(t.notifications)?n.malformed.push(t.id):s6(t)?n.alreadyBound.push(t.id):n.toBind.push(t.id));return n}s(ak,"submitReceiptInventory");function vC(e){let{toBind:n}=ak(e);if(n.length===0)return{graph:e,bound:[]};let t=new Set(n),r=e.nodes.map(i=>{if(!bC(i)||!t.has(i.id))return i;let o=Mp(i.notifications)?i.notifications:{};return{...i,notifications:{...o,[kC]:{templateId:o6}}}});return{graph:{...e,nodes:r},bound:n}}s(vC,"bindSubmitReceipt");var zo=["park","advance"],nr="whenNothingOwed",xC={park:{de:"Jemand schaut drauf",en:"Someone looks at it"},advance:{de:"Durchreichen",en:"Pass through"}};function SC(e){let n=e.inputs?.[nr],t=n?.kind==="literal"?n.value:void 0;return lk(t)?t:null}s(SC,"reviewModeOrNull");function lk(e){return zo.includes(e)}s(lk,"isReviewMode");function dk(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(dk,"isObject");function AC(e){return dk(e)&&e.type==="review"&&!(dk(e.inputs)&&nr in e.inputs)}s(AC,"lacksMode");function EC(e){return(e?.nodes??[]).some(AC)}s(EC,"needsReviewMode");function TC(e){let n=[],t=e.nodes.map(r=>{if(!AC(r))return r;n.push(r.id);let i=dk(r.inputs)?r.inputs:{};return{...r,inputs:{...i,[nr]:{kind:"literal",value:"park"}}}});return{graph:{...e,nodes:t},set:n}}s(TC,"setReviewModePark");function qp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(qp,"isObject");function $C(e){let{notifications:n,bound:t}=ap(e.notifications,{tasks:[]},e);return{next:n,bound:t}}s($C,"bindingsFor");function RC(e){let n={toBind:[],malformed:[]};for(let t of e?.nodes??[])if(!(!qp(t)||typeof t.id!="string"||ta(t).length===0)){if(t.notifications!==void 0&&!qp(t.notifications)){n.malformed.push(t.id);continue}for(let r of $C(t).bound)n.toBind.push(`${t.id}.${r}`)}return n}s(RC,"appointmentLetterInventory");function IC(e){let n=[],t=!1,r=e.nodes.map(i=>{if(!qp(i)||typeof i.id!="string"||ta(i).length===0||i.notifications!==void 0&&!qp(i.notifications))return i;let{next:o,bound:a}=$C(i);return a.length===0?i:(t=!0,n.push(...a.map(l=>`${i.id}.${l}`)),{...i,notifications:o})});return t?{graph:{...e,nodes:r},bound:n}:{graph:e,bound:[]}}s(IC,"bindAppointmentLetters");function ba(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(ba,"isObject");var OC=["id","label","dataFlow"],_C=["audience","populates","stages","expectedOutcomes"];function NC(e){return Array.isArray(e.assignmentRules)&&e.assignmentRules.some(n=>ba(n)&&typeof n.slot=="string")}s(NC,"carriesStringSlots");function PC(e){return(e.nodes??[]).some(n=>ba(n)&&n.type==="form"&&_C.some(t=>t in n))}s(PC,"carriesRetiredFormNodeKey");var a6=[{key:"generatorPin",editor:!0,holds:tO,what:{de:"Generator als `resolver`",en:"generator as `resolver`"}},{key:"setFlagProperties",editor:!0,holds:MO,what:{de:"Formular und Merkmal eines \u201EFlag setzen\u201C-Knotens als Eigenschaften",en:'form and flag of a "Set flag" node as properties'}},{key:"scalarProperties",editor:!0,holds:UO,what:{de:"Einstellungen eines Knotens als Eigenschaften statt als Eing\xE4nge",en:"a node's settings as properties instead of inputs"}},{key:"nodeConfigProperties",editor:!0,holds:ZO,what:{de:"Hinweis einer Zahlung als Eigenschaft oder ein entferntes Muster-Dokument",en:"a payment's note as a property, or a removed sample document"}},{key:"outcomeWithoutSemantic",editor:!0,holds:zI,what:{de:"Entscheidungsausg\xE4nge ohne Bedeutung",en:"decision outcomes without a meaning"}},{key:"startNodeOutcomes",editor:!0,holds:JI,what:{de:"ein Start-Knoten mit eigenen Ausg\xE4ngen",en:"a start node with its own outcomes"}},{key:"templateParameters",editor:!0,holds:yC,what:{de:"Parameter einer Vorlage am Knoten oder Cockpit-Felder als Liste",en:"a template's parameters on the node, or cockpit fields as a list"}},{key:"paymentSettlement",editor:!0,holds:o_,what:{de:"Zahlungsknoten mit \u201EAbrechnung\u201C (`inputs.settlement`) statt \u201EZahlungsweg\u201C (`inputs.mode`)",en:'payment node with "Settlement" (`inputs.settlement`) instead of "Payment mode" (`inputs.mode`)'}},{key:"documentRef",editor:!0,holds:u_,what:{de:"Dokument eines anderen Knotens als `document:$node.<Knoten>.document` statt als Slot `artifact:<Slot>`",en:"another node's document as `document:$node.<node>.document` instead of the slot `artifact:<slot>`"}},{key:"formView",editor:!0,holds:d_,what:{de:"Ansicht einer Aufgabe als `formView` statt als Ansichts-Adresse `view`",en:"a task's view as `formView` instead of the view address `view`"}},{key:"reviewWithoutMode",editor:!0,holds:EC,what:{de:"Pr\xFCfknoten ohne \u201EWenn nichts zu pr\xFCfen ist\u201C",en:'review nodes without "When nothing is owed"'}},{key:"taskAssignUser",editor:!1,holds:s(e=>zf(e).length>0,"holds"),what:{de:"eine Aufgabe mit fester Person (`assign.userId`)",en:"a task with a fixed person (`assign.userId`)"}},{key:"retiredGraphKey",editor:!1,holds:s(e=>OC.some(n=>n in e),"holds"),what:{de:"`graph.id` / `graph.label` / `graph.dataFlow`",en:"`graph.id` / `graph.label` / `graph.dataFlow`"}},{key:"assignmentSlotString",editor:!1,holds:NC,what:{de:"Zust\xE4ndigkeitsregeln mit Slot als Text (`responsible` / `team:<Schl\xFCssel>`)",en:"assignment rules with a slot as text (`responsible` / `team:<key>`)"}},{key:"retiredFormNodeKey",editor:!1,holds:PC,what:{de:"Formularknoten mit `audience` / `populates` / `stages` / `expectedOutcomes`",en:"form nodes with `audience` / `populates` / `stages` / `expectedOutcomes`"}}];function CC(e){if(!ba(e)||!Array.isArray(e.nodes))return[];let n=e;return a6.filter(t=>t.holds(n)).map(({key:t,what:r,editor:i})=>({key:t,what:r,editor:i}))}s(CC,"legacyGraphShapes");function DC(e,n){let t=n.answers??{},r=[],i=[],o=e,a=OC.filter($=>$ in o);if(a.length>0){let $={...o};for(let I of a)delete $[I],r.push({message:`graph.${I}: deleted (read by nothing)`});o=$}if(PC(o)&&(o={...o,nodes:o.nodes.map($=>{if(!ba($)||$.type!=="form")return $;let I=_C.filter(B=>B in $);if(I.length===0)return $;let G={...$};for(let B of I)delete G[B];return r.push({nodeId:String($.id),message:`form node: deleted ${I.map(B=>`\`${B}\``).join(", ")} (read by nothing)`}),G})}),NC(o)){let $=o.assignmentRules.map((I,G)=>{if(!ba(I)||typeof I.slot!="string")return I;let B=Of(I.slot);return B===null?(i.push({code:"assignment/slotUnknown",answer:"edit",message:`assignmentRules[${G}].slot "${I.slot}" is neither \`responsible\` nor \`team:<key>\` \u2014 edit it by hand`}),I):(r.push({message:`assignmentRules[${G}].slot "${I.slot}" \u2192 ${JSON.stringify(B)}`}),{...I,slot:B})});o={...o,assignmentRules:$}}let l=rO(o);o=l.graph;for(let $ of l.moved)r.push({nodeId:$,message:"generator / template pin moved into its input"});for(let $ of l.unmoved)i.push({code:`generatorPin/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`the generator or template pin cannot be moved (${$.reason}) \u2014 edit the node by hand`});let d=qO(o);o=d.graph;for(let $ of d.moved)r.push({nodeId:$,message:"setFlag `target` / `flagKey` / `value` moved into its inputs"});for(let $ of d.unmoved)i.push({code:`setFlag/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`the setFlag properties cannot be moved (${$.reason}) \u2014 edit the node by hand`});let c=GO(o);o=c.graph;for(let $ of c.moved)r.push({nodeId:$,message:"scalar settings moved into inputs"});for(let $ of c.unmoved)i.push({code:`scalar/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`\`${$.key}\` cannot be moved into an input (${$.reason}) \u2014 edit the node by hand`});let u=XO(o);o=u.graph;for(let $ of u.moved)r.push({nodeId:$,message:"payment note moved into `inputs.reason` / retired sample document deleted"});for(let $ of u.unmoved)i.push({code:`nodeConfig/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`\`${$.key}\` cannot be moved into an input (${$.reason}) \u2014 edit the node by hand`});let p=wC(o);o=p.graph;for(let $ of p.moved){let I=o.nodes.find(le=>ba(le)&&le.id===$),G=I?.inputs?.documentTemplate,B=G?.kind==="literal"&&typeof G.value=="string"?G.value:null;r.push({nodeId:$,message:I!==void 0&&"templateStamp"in I&&B!==null?`template parameters moved onto \`templateStamp\` / cockpit list into cells \u2014 the record \`${B}\` must declare the same parameters (tenant catalog \`documentTemplates[].parameters\` / \`templates:setParameters\`) before publish, else [governedDocument/templateWithoutParameters]`:"cockpit list moved into `{ kind: 'cockpit' }` cells"})}for(let $ of p.reports)r.push({nodeId:$.nodeId,message:`cockpit field \`${$.key??""}\` deleted (${$.reason}: ${$.reason==="unknownKey"?"the stamp declares no such parameter":$.reason==="processSource"?"the case fills it itself":"the input already holds a cell"})`});for(let $ of p.unmoved)i.push({code:`templateStamp/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:$.reason==="noStamp"?"the cockpit list cannot be judged: the node carries no parameter stamp \u2014 run `offer workflow restamp-pins` against the environment, then upgrade again":$.reason==="templateAndStamp"?"the node carries both `template` and `templateStamp` \u2014 delete one by hand":"`template` is no object \u2014 edit the node by hand"});let h=QI(o);o=h.graph;for(let $ of h.moved)r.push({nodeId:$,message:"start node: own `outcomes` / `event` / `effect` deleted (the node type declares its outcome)"});for(let $ of h.unmoved)i.push({code:`eventTrigger/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`the start node cannot be reduced to its type's outcome (${$.reason}) \u2014 edit the node by hand`});let y=WI(o,t.semantics);o=y.graph;for(let $ of y.written){if($.source==="formerDefault"){r.push({nodeId:$.nodeId,message:`outcome \`${$.outcomeId}\`: semantic "${$.semantic}" (DEFAULT \u2014 the meaning it ran with; the retired id parser knew no other)`,defaulted:{answer:"semantic",answerKey:`${$.nodeId}.${$.outcomeId}`,value:$.semantic}});continue}r.push({nodeId:$.nodeId,message:`outcome \`${$.outcomeId}\`: semantic "${$.semantic}" (${$.source==="answer"?"answered":"the meaning the retired id parser gave this id"})`})}for(let $ of y.refused)i.push({code:$.answer===void 0?"outcome/formerMeaningNotAllowed":"outcome/semanticNotAllowed",nodeId:$.nodeId,answer:"semantic",answerKey:`${$.nodeId}.${$.outcomeId}`,candidates:$.allowed,message:$.answer===void 0?`${$.nodeType} outcome \`${$.outcomeId}\` ran as "${Ny($.outcomeId)??""}", which a ${$.nodeType} outcome may no longer carry \u2014 say which one it is`:`${$.nodeType} outcome \`${$.outcomeId}\`: "${$.answer}" is not a meaning a ${$.nodeType} outcome may carry`});for(let $ of y.invalid)i.push({code:"outcome/semanticInvalid",nodeId:$.nodeId,answer:"edit",candidates:bt,message:`outcome \`${$.outcomeId}\` carries the semantic "${$.value}", which is no meaning \u2014 edit it`});let k=eO(o,n.selection,t.waitlistPolicy);o=k.graph;for(let $ of k.moved){let I=$.policy.waitlistOrder;r.push({nodeId:$.nodeId,message:`waitlist policy into inputs: ${l6($.policy)} (${$.source==="answer"?"answered":$.source==="manifest"?"from manifest `selection`":"DEFAULT \u2014 the manifest stated no `selection.waitlistOrder`; the former code default it ran with"})`,...$.source==="formerDefault"?{defaulted:{answer:"waitlistPolicy",answerKey:$.nodeId,value:I}}:{}})}for(let $ of k.refused)i.push({code:`waitlist/${$.reason}`,nodeId:$.nodeId,answer:"waitlistPolicy",answerKey:$.nodeId,candidates:Jt,message:"manifest `selection` is malformed \u2014 say the queue order of this waitlist"});let w=s_(o);o=w.graph;for(let $ of w.moved)r.push({nodeId:$,message:"payment: `inputs.settlement` \u2192 `inputs.mode` (separate \u2192 manual)"});for(let $ of w.refused)i.push({code:`collectPayment/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:$.reason==="bothCells"?"the payment node carries both `inputs.settlement` and `inputs.mode` \u2014 delete `settlement` by hand":"`inputs.settlement` is no literal online | separate \u2014 set `inputs.mode` by hand"});let v=c_(o);o=v.graph;for(let $ of v.moved)r.push({nodeId:$.split(".")[0],message:`\`formView\` \u2192 \`view\` (${$})`});for(let $ of v.refused){let I=$.taskKey===void 0?"the node":`task "${$.taskKey}"`;i.push({code:`view/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:$.reason==="bothFields"?`${I} carries both \`formView\` and \`view\` \u2014 delete \`formView\` by hand`:`${I}'s \`formView\` is no { form, key } \u2014 set \`view\` by hand`})}let A=f_(o);o=A.graph;for(let $ of A.moved)r.push({nodeId:$.split(".")[0],message:`documents: \`document:$node.<node>.document\` \u2192 \`artifact:<slot>\` (${$})`});for(let $ of A.refused)i.push({code:`workItems/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`task "${$.taskKey}" links a document whose node declares no single slot \u2014 name the slot as \`artifact:<slot>\` by hand`});if(n_(o)){let $=t_(o,t.payee);o=$.graph;for(let I of $.set)r.push({nodeId:I.nodeId,message:`online payment: payee "${I.payee}" (answered)`});for(let I of $.refused)i.push({code:"collectPayment/payeeMissing",nodeId:I,answer:"payee",answerKey:I,message:"an online payment names the Tr\xE4ger its money goes to \u2014 say its key (a `legal_entities.configKey` of the tenant)"})}for(let $ of ak(o).malformed)i.push({code:"submitReceipt/notificationsMalformed",nodeId:$,answer:"edit",message:"the form node's `notifications` is no record \u2014 edit it by hand"});let E=vC(o);o=E.graph;for(let $ of E.bound)r.push({nodeId:$,message:"submit receipt bound to `notifications.submitted` (`applicant.applicationSubmitted`, sent by code before)"});let R=TC(o);o=R.graph;for(let $ of R.set)r.push({nodeId:$,message:"review: `whenNothingOwed` = park (every review parked before the input existed)"});for(let $ of RC(o).malformed)i.push({code:"appointmentLetters/notificationsMalformed",nodeId:$,answer:"edit",message:"the node's `notifications` is no record \u2014 edit it by hand"});let P=IC(o);o=P.graph;for(let $ of P.bound){let I=$.indexOf(".");r.push({nodeId:$.slice(0,I),message:`appointment letter bound to \`notifications.${$.slice(I+1)}\` (the standard letter, sent by code before)`})}let F=zf(o).filter($=>!$.hasTeam);for(let $ of F)i.push({code:"task/userWithoutTeam",nodeId:$.nodeId,answer:"edit",message:`task \`${$.taskKey}\` names a fixed person and no team \u2014 give it a team (\`assign.group\`) by hand`});let b=p_(o);o=b.graph;for(let $ of b.dropped.filter(I=>I.hasTeam))r.push({nodeId:$.nodeId,message:`task \`${$.taskKey}\`: \`assign.userId\` deleted (the team holds the row)`});let O=hC(o,{bindings:!0});o=O.graph;for(let $ of O.dropped){if(!$.binding){r.push({nodeId:$.nodeId,message:`input \`${$.key}\` deleted (no slot of the node declares it)`});continue}r.push({nodeId:$.nodeId,message:`input \`${$.key}\` deleted (DEFAULT \u2014 a binding no slot declares: no slot handed its value to the node, but the readiness gate waited for it; the node no longer waits for that value)`,defaulted:{answer:"undeclaredBinding",answerKey:`${$.nodeId}.${$.key}`,value:"deleted"}})}return{graph:o,changes:r,refusals:i}}s(DC,"upgradeGraph");function l6(e){return`waitlistOrder=${e.waitlistOrder}`}s(l6,"formatPolicy");function gi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(gi,"isObject");var FC="admission.generic",LC=Object.keys($f).filter(e=>e!=="label");function MC(e){return gi(e.smartforms)?Object.entries(e.smartforms):[]}s(MC,"smartformEntries");function d6(e){let n=[];MC(e.index).some(([,i])=>gi(i)&&"outcomeFnRef"in i)&&n.push({de:"`smartforms.<slug>.outcomeFnRef` in bundle.yaml",en:"`smartforms.<slug>.outcomeFnRef` in bundle.yaml"});let t=Object.keys(e.manifest).filter(i=>Object.hasOwn(Rl,i));if(t.length>0){let i=t.map(o=>`\`${o}\``).join(", ");n.push({de:`manifest.json mit ${i}`,en:`manifest.json with ${i}`})}Object.values(e.smartforms??{}).some(i=>LC.some(o=>o in i))&&n.push({de:"Formulardateien mit `id` / `outcomeIds` / `schoolSlug`",en:"form files with `id` / `outcomeIds` / `schoolSlug`"});let r=e.workflow;return r!==void 0&&(gi(r.progressWiring)&&"layoutId"in r.progressWiring&&n.push({de:"`progressWiring.layoutId`",en:"`progressWiring.layoutId`"}),n.push(...CC(r.graph).map(i=>i.what))),n}s(d6,"legacyBundleShapes");function jp(e,n){let t=d6(e);t.length!==0&&se("BUNDLE_NEEDS_UPGRADE",{de:`offer: ${n} stammt aus einem \xE4lteren Bundle-Format (${t.map(r=>r.de).join("; ")}). Zuerst \`plexus-cli offer upgrade --dir <Bundle>\` ausf\xFChren (Probelauf, beantwortet die offenen Fragen), dann mit \`--write\` schreiben und erneut pr\xFCfen.`,en:`offer: ${n} is in an older bundle format (${t.map(r=>r.en).join("; ")}). Run \`plexus-cli offer upgrade --dir <bundle>\` first (a dry run that asks what it cannot decide), then write with \`--write\` and validate again.`})}s(jp,"assertBundleCurrent");function Kp(e){let n=s(t=>Array.isArray(t)?t.map(n):gi(t)?Object.fromEntries(Object.keys(t).sort().map(r=>[r,n(t[r])])):t,"sort");return JSON.stringify(n(e))}s(Kp,"canonical");function qC(e,n={}){let t=[],r=[],i=e.index,o=MC(i);if(o.some(([,u])=>gi(u)&&Object.keys(u).length>0)){let u={};for(let[p,h]of o){if(!gi(h)||Object.keys(h).length===0){u[p]=h;continue}let{outcomeFnRef:y,...k}=h;if(Object.keys(k).length>0||y!==void 0&&y!==FC){r.push({file:"bundle.yaml",code:"index/smartformEntry",answer:"edit",message:`smartforms.${p} carries ${Object.keys(h).map(w=>`\`${w}\``).join(", ")} \u2014 only \`outcomeFnRef: ${FC}\` is known; edit the entry to {} by hand`}),u[p]=h;continue}t.push({file:"bundle.yaml",message:`smartforms.${p}.outcomeFnRef deleted (a form routes by its own declared outcomes)`}),u[p]={}}i={...i,smartforms:u}}let a={},l=e.workflow,d;for(let[u,p]of Object.entries(e.manifest)){if(u==="selection"){d=p,t.push({file:"manifest.json",message:"`selection` deleted (its queue policy goes to the waitlist node's inputs; release strategy and deadline were read by nothing)"});continue}if(u==="progressLayout"){l===void 0?t.push({file:"manifest.json",message:"`progressLayout` deleted (the bundle has no workflow it could belong to)"}):l.progressLayout===void 0?(l={...l,progressLayout:p},t.push({file:"manifest.json",message:"`progressLayout` moved to workflow.json `progressLayout`"})):Kp(l.progressLayout)===Kp(p)?t.push({file:"manifest.json",message:"`progressLayout` deleted (workflow.json carries the same layout)"}):(r.push({file:"manifest.json",code:"manifest/progressLayoutTwice",answer:"edit",message:"`progressLayout` differs from workflow.json `progressLayout` \u2014 keep one by hand"}),a[u]=p);continue}let h=Object.hasOwn(Rl,u)?Rl[u]:void 0;if(h===void 0){r.push({file:"manifest.json",code:"manifest/unknownKey",answer:"edit",message:`unknown key \`${u}\` \u2014 manifest.json carries no key; decide by hand where it belongs`}),a[u]=p;continue}t.push({file:"manifest.json",message:`\`${u}\` deleted (${h.en})`})}if(l!==void 0){if(gi(l.progressWiring)&&"layoutId"in l.progressWiring){let{layoutId:p,...h}=l.progressWiring;l={...l,progressWiring:h},t.push({file:"workflow.json",message:"`progressWiring.layoutId` deleted (the layout is the workflow's own)"})}let u=l.graph;if(gi(u)&&Array.isArray(u.nodes)){let p=DC(u,{selection:d,answers:n});l={...l,graph:p.graph},t.push(...p.changes.map(h=>({...h,file:"workflow.json"}))),r.push(...p.refusals.map(h=>({...h,file:"workflow.json"})))}else r.push({file:"workflow.json",code:"workflow/graphShape",answer:"edit",message:"`graph` is no object with a node list"})}let c=e.smartforms;if(c!==void 0){let u={};for(let[p,h]of Object.entries(c)){let y={...h},k=`smartforms/${p}.json`;for(let w of LC)if(w in h){if(w==="outcomeIds"){let v=Array.isArray(h.outcomes)?h.outcomes.map(A=>gi(A)?A.id:void 0):[];if(Kp([...Array.isArray(h.outcomeIds)?h.outcomeIds:[]].map(String).sort())!==Kp(v.map(String).sort())){r.push({file:k,code:"smartform/outcomeIdsDiffer",answer:"edit",message:"`outcomeIds` differs from the ids of `outcomes[]` \u2014 reconcile them by hand"});continue}}delete y[w],t.push({file:k,message:`\`${w}\` deleted (${$f[w].en})`})}u[p]=y}c=u}return{bundle:{index:i,manifest:a,...c!==void 0?{smartforms:c}:{},...l!==void 0?{workflow:l}:{}},changes:t,refusals:r}}s(qC,"upgradeOfferBundle");var c6={createManifest:x.workflow.createManifest,publishManifest:x.workflow.publishManifest,publishOfferInternal:x.workflow.publishOfferInternal,publishOfferExternal:x.workflow.publishOfferExternal,getOfferPublishState:x.workflow.getOfferPublishState,upsertCustomField:x.admission.upsertCustomField,upsertDerivedAttributeRule:x.admission.upsertDerivedAttributeRule,createSmartForm:x.forms.createSmartForm,getSmartFormBySlug:x.forms.getSmartFormBySlug,saveSmartFormDraft:x.forms.saveSmartFormDraft,publishSmartForm:x.forms.publishSmartForm,createWorkflow:x.workflow.createWorkflow,getWorkflowGraph:x.workflow.getWorkflowGraph,saveWorkflowDraft:x.workflow.saveWorkflowDraft,publishWorkflow:x.workflow.publishWorkflow},zke={createManifest:et.workflow.createManifestInternal,publishManifest:et.workflow.publishManifestInternal,publishOfferInternal:et.workflow.publishOfferInternalInternal,publishOfferExternal:et.workflow.publishOfferExternalInternal,getOfferPublishState:et.workflow.getOfferPublishStateInternal,upsertCustomField:et.admission.upsertCustomFieldInternal,upsertDerivedAttributeRule:et.admission.upsertDerivedAttributeRuleInternal,createSmartForm:et.forms.createSmartFormInternal,getSmartFormBySlug:et.forms.getSmartFormBySlugInternal,saveSmartFormDraft:et.forms.saveSmartFormDraftInternal,publishSmartForm:et.forms.publishSmartFormInternal,createWorkflow:et.workflow.createWorkflowInternal,getWorkflowGraph:et.workflow.getWorkflowGraphInternal,saveWorkflowDraft:et.workflow.saveWorkflowDraftInternal,publishWorkflow:et.workflow.publishWorkflowInternal};function ck(e,n){for(let[t,r]of Object.entries(e.smartforms??{})){(r===null||typeof r!="object"||Array.isArray(r))&&se("INVALID",{de:`offer: ${n}: smartforms.${t} muss eine leere Zuordnung ({}) sein.`,en:`offer: ${n}: smartforms.${t} must be an empty mapping ({}).`});let i=Object.keys(r);if(i.length===0)continue;let o=i.map(l=>`\`${l}\``).join(", "),a=i.includes("outcomeFnRef");se("INVALID",{de:`offer: ${n}: smartforms.${t} enth\xE4lt unbekannte Schl\xFCssel ${o} \u2014 der Eintrag muss leer sein ({}).${a?" `outcomeFnRef` geh\xF6rt nicht mehr zum Bundle-Format: ein Formular entscheidet \xFCber seine eigenen Ergebnisse. Die Zeile l\xF6schen.":""}`,en:`offer: ${n}: smartforms.${t} carries unknown key(s) ${o} \u2014 the entry must be empty ({}).${a?" `outcomeFnRef` is no longer part of the bundle format: a form routes by its own declared outcomes. Delete the line.":""}`})}}s(ck,"assertSmartformEntries");function KC(e){let n=s(t=>Array.isArray(t)?t.map(n):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(r=>[r,n(t[r])])):t,"sort");return JSON.stringify(n(e))}s(KC,"canonicalJson");function jC(e,n){return n==null?!0:KC(e)!==KC(n)}s(jC,"changed");async function VC(e,n,t,r={},i=c6){let{index:o}=n;jp({index:o,manifest:n.manifest,...n.smartforms!==void 0?{smartforms:n.smartforms}:{},...n.workflow!==void 0?{workflow:n.workflow}:{}},`bundle of ${o.slugs.manifest}`),ck(o,`bundle of ${o.slugs.manifest}`);let a=Tf(n.manifest);a.length>0&&se("INVALID",{de:`offer: manifest.json von ${o.slugs.manifest} ist ung\xFCltig:
11245
+ {{einstellungenLink}}`}}]},Ew=[q1,G1,Y1,H1,J1,n2,e2,E2,$2,M2,K2,V2,G2,Y2,J2,X2,tY,oY,aY,R2,I2,O2,lY,dY,cY,t2,r2,s2,a2,c2,h2,f2,w2,S2,D2,OY,NY,j1,B1,fY,mY,gY,wY,vY,SY,EY];function Tw(e){let n=Ew.find(t=>t.id===e);return n===void 0&&L(`notifications: unknown letter "${e}"`),n}s(Tw,"letterDefFor");function $w(e){return Ew.some(n=>n.id===e)}s($w,"hasLetterDef");function Rw(e,n){return n===void 0?!0:jf(e,n)}s(Rw,"letterArgCompatible");function Gl(e){return e==="localizedText"?{de:"Text in jeder Sprache (localizedText)",en:"Text in every language (localizedText)"}:{de:`${tt(e)} (${e})`,en:`${tt(e)} (${e})`}}s(Gl,"letterArgTypeLabel");function iN(e){let n=new Map,t=s((r,i)=>{let o=n.get(r);o===void 0?n.set(r,[i]):o.push(i)},"add");for(let r of e.args)t(r.key,{source:`Ereignis "${e.id}"`,type:r.type,always:r.required===!0});for(let r of V_)t(r.key,{source:"Kontext des Versands",type:r.type,always:!0});return n}s(iN,"eventArgSources");function oN(e,n){let t=e.type===void 0?[...n]:n.filter(r=>Rw(r.type,e.type));if(t.length>1)return{status:"ambiguous",matches:t};if(t.length===1){let r=t[0];return!e.required||r.always?{status:"resolved",source:r}:{status:"sometimes",source:r}}return e.required?{status:"missing",rejected:[...n]}:{status:"unused"}}s(oN,"resolveLetterParam");var Iw=["booked","rescheduled","cancelled"],PY={booked:"admission.appointmentBooked",rescheduled:"admission.appointmentRescheduled",cancelled:"admission.appointmentCancelled"},aN=":";function lN(e,n){return`${e}${aN}${n}`}s(lN,"appointmentEventId");function CY(e){let n=e.lastIndexOf(aN);if(n<=0)return null;let t=e.slice(n+1);return Iw.includes(t)?{taskKey:e.slice(0,n),kind:t}:null}s(CY,"parseAppointmentEventId");var sN={booked:{de:"Termin vereinbart",en:"Appointment booked"},rescheduled:{de:"Termin verschoben",en:"Appointment moved"},cancelled:{de:"Termin abgesagt",en:"Appointment cancelled"}};function ta(e){return Array.isArray(e.tasks)?e.tasks.filter(n=>typeof n?.key=="string"&&n.result?.kind==="appointment"):[]}s(ta,"appointmentTasksOf");function DY(e){return Iw.map(n=>({id:lN(e.key,n),label:{de:`${sN[n].de} \u2013 \u201E${e.title.de}\u201C`,en:`${sN[n].en} \u2013 \u201C${e.title.en}\u201D`},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"bookingId",type:"string",required:!0}]}))}s(DY,"appointmentTaskEvents");function dN(e,n){let t=n.notificationEvents?.(e)??[],r=ta(e).flatMap(DY);return r.length===0?t:[...t,...r]}s(dN,"nodeNotificationEvents");function FY(e){return Object.fromEntries(Iw.map(n=>[lN(e,n),{templateId:PY[n]}]))}s(FY,"defaultAppointmentBindings");function LY(e,n){if(e===void 0)return{notifications:e,dropped:[]};let t=[],r={};for(let[i,o]of Object.entries(e))CY(i)?.taskKey===n?t.push(i):r[i]=o;return t.length===0?{notifications:e,dropped:t}:{notifications:Object.keys(r).length===0?void 0:r,dropped:t}}s(LY,"withoutAppointmentBindings");function ap(e,n,t){let r=new Set(ta(n).map(d=>d.key)),i=new Set(ta(t).map(d=>d.key)),o=e,a=[];for(let d of r){if(i.has(d))continue;let c=LY(o,d);o=c.notifications,a.push(...c.dropped)}let l=[];for(let d of i)if(!r.has(d))for(let[c,u]of Object.entries(FY(d)))o?.[c]===void 0&&(o={...o??{},[c]:u},l.push(c));return{notifications:o,bound:l,dropped:a}}s(ap,"syncAppointmentBindings");function MY(e){return e.kind==="task"&&!("title"in e)}s(MY,"isLegacyFreeTodoContext");function Ow(e){let{context:n}=e;if(MY(n)&&L(`[workItems/legacyFreeTodo] work_item ${e._id} is a free to-do in its former shape \u2014 run migrations:freeTodosToContext`),n.kind==="task")return{...e,context:n,kind:"task",createdVia:"human",partyId:n.partyId};let{anchor:t,task:r,kind:i,title:o,description:a,...l}=n,d=t.scope==="node"?{nodeId:t.nodeId,templateKey:t.templateKey,gatesNode:t.gatesNode,blocks:t.blocks}:t.scope==="application"?{scope:"application",templateKey:t.templateKey}:t.scope==="crossNode"?{scope:"application",nodeId:t.nodeId,templateKey:t.templateKey,blocks:t.blocks}:{};return{...e,context:n,...l,...d,...r??{},kind:i}}s(Ow,"readWorkItem");async function zl(e,n){let t;if(n.nodeId!==void 0){let r=n.nodeId;t=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",i=>i.eq("context.applicationId",n.applicationId).eq("context.anchor.nodeId",r)).collect()}else if(n.isOpen!==void 0){let r=n.isOpen;t=await e.db.query("work_items").withIndex("by_applicationId_and_isOpen",i=>i.eq("context.applicationId",n.applicationId).eq("isOpen",r)).collect()}else t=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",r=>r.eq("context.applicationId",n.applicationId)).collect();return t.filter(r=>n.isOpen===void 0||r.isOpen===n.isOpen).map(Ow)}s(zl,"listWorkItemsForApplication");var Kme=m.union(m.literal("approved"),m.literal("rejected")),Wl=new Set(["task","approval"]);function KY(e,n){switch(e){case"task":return n?.gatesNode===!0&&L("expandComposedTask: gatesNode is approval-only \u2014 a 'task' template never gates its node (use blocks to hold a gating sibling back)"),{kind:"task",recipient:"internal",gatesNode:!1};case"approval":return{kind:"approval",recipient:"internal",isApproval:!0,gatesNode:n?.gatesNode??!0};default:L(`expandComposedTask: unknown composed-task kind ${JSON.stringify(e)} \u2014 authorable: ${[...Wl].join(", ")}`)}}s(KY,"expandComposedTask");for(let e of["task","approval"]){let n=KY(e);n.kind==="approval"!=(n.isApproval===!0)&&L(`composed-task kind "${e}": isApproval must be present iff kind === 'approval'`)}var cN=Di,Gi=`${cN}.`,jY=new Set(["text","number","date","boolean","option","edge"]);function lp(e,n){let t=e[n];return t===void 0&&L(`[env/unknownKey] no environment key '${n}'`),typeof t=="string"?null:Object.keys(t)}s(lp,"contextFields");function uN(e,n){return Object.hasOwn(e,n)}s(uN,"isContextKey");function fN(e){let n=[];for(let t of Object.keys(e)){let r=lp(e,t);if(r===null)n.push(t);else for(let i of r)n.push(`${t}.${i}`)}return n}s(fN,"leafPaths");function Yl(e,n){let[t="",r,...i]=n.split(".");if(!uN(e,t)||i.length>0)return;let o=e[t];if(typeof o=="string")return r===void 0?o:void 0;if(!(r===void 0||!Object.hasOwn(o,r)))return o[r]}s(Yl,"leafType");function pN(e){let n=new Set;for(let t of e){let r=ra(t);r!==null&&n.add(r.split(".")[0])}return[...n]}s(pN,"contextKeysOf");function ra(e){return e.startsWith(Gi)?e.slice(Gi.length):null}s(ra,"contextPathOf");function Hl(e){return e===cN||e.startsWith(Gi)}s(Hl,"isContextIdentifier");function dp(e,n){let t=ra(n)??"",[r=""]=t.split("."),i=Object.keys(e);if(!uN(e,r))return{code:"env/unknownKey",message:{de:`'${n}' nennt keinen Umgebungsschl\xFCssel \u2014 bekannt: ${i.join(", ")}.`,en:`'${n}' names no environment key \u2014 known: ${i.join(", ")}.`}};if(Yl(e,t)!==void 0)return null;let o=lp(e,r);return{code:"env/unknownKey",message:o===null?{de:`'${n}': der Umgebungsschl\xFCssel '${r}' ist ein einzelner Wert \u2014 lies ihn als '${Gi}${r}'.`,en:`'${n}': environment key '${r}' is a single value \u2014 read it as '${Gi}${r}'.`}:{de:`'${n}': der Umgebungsschl\xFCssel '${r}' hat die Felder ${o.join(", ")}.`,en:`'${n}': environment key '${r}' has the fields ${o.join(", ")}.`}}}s(dp,"identifierIssue");function cp(e,n,t=Object.keys(e)){let r={};for(let i of t){let o=lp(e,i),a=Object.hasOwn(n,i)?n[i]:void 0;if(a===void 0&&L(`[env/missing] context key '${i}' was not supplied`),o===null){r[`${Gi}${i}`]=a;continue}for(let l of o){let d=typeof a=="object"&&a!==null&&Object.hasOwn(a,l)?a[l]:void 0;d===void 0&&L(`[env/missing] context key '${i}' carries no '${l}'`),r[`${Gi}${i}.${l}`]=d}}return r}s(cp,"flatten");function mN(e,n,t){if(t===void 0)return!1;let r=lp(e,n);return r===null?!0:typeof t=="object"&&t!==null&&r.every(i=>t[i]!==void 0)}s(mN,"contextValueComplete");function VY(e,n){switch(n){case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"date":return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}/.test(e);default:return typeof e=="string"}}s(VY,"valueMatchesDataType");function hN(e,n,t=Object.keys(e.types)){let r=new Set(t);for(let i of fN(e.types)){if(!r.has(i.split(".")[0]))continue;let o=n[`${Gi}${i}`];o===void 0&&L(`[env/missing] context path '${i}' was not supplied`);let a=e.fields[i];if(o===null){a.nullable||L(`[env/null] context path '${i}' is not nullable but carries null`);continue}let l=tt(Yl(e.types,i));VY(o,l)||L(`[env/type] context path '${i}' expects ${l}, got ${JSON.stringify(o)}`),a.valueSet.kind==="fixed"&&!a.valueSet.values.includes(o)&&L(`[env/value] context path '${i}' carries '${String(o)}', outside ${a.valueSet.values.join(" | ")}`)}}s(hN,"assertContextValues");function BY(e){let n=[],t=fN(e.types);for(let r of t){let i=Yl(e.types,r),o=tt(i);if(!qi(i)||o===void 0||!jY.has(o)){n.push(`'${r}' has type '${String(i)}', not a scalar value type`);continue}let a=Object.hasOwn(e.fields,r)?e.fields[r]:void 0;if(a===void 0){n.push(`'${r}' has no field spec (value set + nullability)`);continue}a.valueSet.kind==="fixed"&&(a.valueSet.values.length===0&&n.push(`'${r}' has an empty fixed value set`),o!=="text"&&o!=="option"&&n.push(`'${r}' is ${o}; a fixed value set needs a text or option leaf`))}for(let r of Object.keys(e.fields))t.includes(r)||n.push(`field spec '${r}' names no leaf of the schema`);return n}s(BY,"schemaIssues");function ia(e){let n=BY(e);n.length>0&&L(`[env/schema] ${n.join("; ")}`)}s(ia,"assertSchema");var up={length:{params:["text"],returns:"number"},years_between:{params:["date","date"],returns:"number"}};function zi(e){return JSON.stringify(e)}s(zi,"canonical");function sa(e){return e.kind==="binary"&&e.op==="&&"?[...sa(e.left),...sa(e.right)]:[e]}s(sa,"conjuncts");function wN(e,n){let t;try{t=In(e)}catch{return!1}let r=zi(In(n));return sa(t).some(i=>zi(i)===r)}s(wN,"hasConjunct");function kN(e,n){try{return zi(In(e))===zi(In(n))}catch{return!1}}s(kN,"sameCondition");function bN(e){let n=[];for(let t of e)n.push(...On(ii(t)));return pN(n)}s(bN,"contextKeysRead");function vN(e){try{return On(In(e)).some(Hl)}catch{return!1}}s(vN,"readsContext");var UY=/^\d{4}-\d{2}-\d{2}$/,GY=new Set(["==","!=","<","<=",">",">=","in"]),zY=new Set(["<","<=",">",">="]);function pp(e,n,t=[]){ia(n);let r;try{r=In(e)}catch(a){let l=a.message;return[Gn("condition/parse",`Bedingung '${e}' ist nicht lesbar: ${l}`,`condition '${e}' does not parse: ${l}`)]}let i=[];for(let a of On(r)){if(!Hl(a)){i.push(Gn("condition/foreignIdentifier",`'${a}' ist kein Umgebungswert \u2014 Bedingungen lesen nur '$env.*'`,`'${a}' is not a context identifier \u2014 conditions read only '$env.*'`));continue}let l=dp(n.types,a);l!==null&&i.push(Gn("condition/unknownIdentifier",l.message.de,l.message.en))}if(i.length>0)return i;let o=Mr(r,n,i);Jl(o)||i.push(Gn("condition/notBoolean",`Bedingung '${e}' ist kein Ja/Nein-Ausdruck`,`condition '${e}' is not a yes/no expression`)),JY(r,n,i);for(let{identifier:a,op:l}of Pw(r,n))i.push(Gn("condition/unguardedNullable",`'${l}' \xFCber '${a}', das leer sein kann, braucht davor eine Absicherung '${a} != null &&'`,`'${l}' over '${a}', which may be null, needs a guard '${a} != null &&' before it`));return i.push(...WY(r,t)),i}s(pp,"conditionIssues");function WY(e,n){let t=sa(e).map(zi);return n.flatMap(r=>{let i=In(r),o=YY(i);return o===null||!t.includes(zi(o))?[]:[{severity:"info",code:"condition/guardForm",message:{de:`[condition/guardForm] eine gespiegelte Absicherung z\xE4hlt nicht \u2014 schreibe sie genau als '${r}'`,en:`[condition/guardForm] a mirrored guard does not count \u2014 write it exactly as '${r}'`}}]})}s(WY,"guardFormHints");function YY(e){if(e.kind!=="binary"||e.op!=="=="&&e.op!=="!=")return null;let n={...e,left:e.right,right:e.left};return zi(n)===zi(e)?null:n}s(YY,"mirror");function Jl(e){return e.t==="unknown"||e.t==="data"&&e.dt==="boolean"}s(Jl,"isBooleanish");function xN(e){let n=ra(e);return n===null&&L(`[condition/invariant] '${e}' reached a pass that only sees $env identifiers`),n}s(xN,"contextPath");function SN(e,n){let t=ra(n);return t!==null&&e.fields[t]?.nullable===!0}s(SN,"isNullableLeaf");function HY(e,n){let t=tt(Yl(e.types,xN(n)));return t===void 0?{t:"unknown"}:{t:"data",dt:t}}s(HY,"identType");function fp(e,n){return e.t==="unknown"||n.t==="unknown"||e.t==="null"||n.t==="null"?!0:e.t==="array"||n.t==="array"?!1:e.t==="str"&&n.t==="str"?!0:e.t==="str"?gN(e.value,n.dt):n.t==="str"?gN(n.value,e.dt):e.dt===n.dt}s(fp,"fits");function gN(e,n){return n==="text"||n==="option"||n==="edge"?!0:n==="date"?UY.test(e):!1}s(gN,"strFits");function yN(e){return e.t==="unknown"?"unknown":e.t==="data"&&e.dt==="number"?"number":null}s(yN,"orderedCategory");function Mr(e,n,t){switch(e.kind){case"num":return{t:"data",dt:"number"};case"bool":return{t:"data",dt:"boolean"};case"str":return{t:"str",value:e.value};case"null":return{t:"null"};case"ident":return HY(n,e.path);case"arr":for(let r of e.items)Mr(r,n,t);return{t:"array"};case"unary":{let r=Mr(e.operand,n,t);return Jl(r)||t.push(Gn("condition/notBoolean","'!' braucht einen Ja/Nein-Operanden","'!' needs a yes/no operand")),{t:"data",dt:"boolean"}}case"call":{let r=Object.hasOwn(up,e.name)?up[e.name]:void 0,i=e.args.map(l=>Mr(l,n,t));return r===void 0?(t.push(Gn("condition/functionNotAllowed",`Funktion '${e.name}' ist nicht erlaubt \u2014 erlaubt: ${Object.keys(up).join(", ")}`,`function '${e.name}' is not allowed \u2014 allowed: ${Object.keys(up).join(", ")}`)),{t:"unknown"}):(i.length===r.params.length&&i.every((l,d)=>l.t!=="null"&&fp(l,{t:"data",dt:r.params[d]}))||t.push(Gn("condition/typeMismatch",`'${e.name}' nimmt (${r.params.join(", ")})`,`'${e.name}' takes (${r.params.join(", ")})`)),{t:"data",dt:r.returns})}case"if":{let r=Mr(e.cond,n,t);Jl(r)||t.push(Gn("condition/notBoolean","'if' braucht eine Ja/Nein-Bedingung","'if' needs a yes/no condition"));let i=Mr(e.then,n,t),o=Mr(e.else,n,t);return fp(i,o)||t.push(Gn("condition/typeMismatch","die beiden Zweige von 'if' haben verschiedene Typen","the two arms of 'if' differ in type")),i.t==="null"?o:i}case"binary":{let r=Mr(e.left,n,t),i=Mr(e.right,n,t);if(e.op==="&&"||e.op==="||")(!Jl(r)||!Jl(i))&&t.push(Gn("condition/notBoolean",`'${e.op}' braucht Ja/Nein-Operanden`,`'${e.op}' needs yes/no operands`));else if(e.op==="in")e.right.kind!=="arr"?t.push(Gn("condition/inWithoutArray","'in' braucht rechts eine Liste, z. B. ['a', 'b']","'in' needs a list on its right, e.g. ['a', 'b']")):e.right.items.every(o=>fp(r,Mr(o,n,[])))||t.push(Gn("condition/typeMismatch","ein Listeneintrag von 'in' passt nicht zum Typ des linken Operanden","a list item of 'in' does not match the left operand's type"));else if(zY.has(e.op)){let o=yN(r),a=yN(i);(o===null||a===null||o!=="unknown"&&a!=="unknown"&&o!==a)&&t.push(Gn("condition/orderedComparison",`'${e.op}' vergleicht nur Zahlen \u2014 f\xFCr Daten years_between(\u2026) verwenden`,`'${e.op}' compares only numbers \u2014 for dates use years_between(\u2026)`))}else fp(r,i)||t.push(Gn("condition/typeMismatch",`'${e.op}' vergleicht Werte verschiedener Typen`,`'${e.op}' compares values of different types`));return{t:"data",dt:"boolean"}}}}s(Mr,"typeOf");function _w(e){return e.kind==="str"||e.kind==="num"||e.kind==="bool"}s(_w,"isLiteral");function AN(e){let n=[],t=s(r=>{if(r.kind==="binary"&&GY.has(r.op)){if(r.left.kind==="ident"){let i=r.op==="in"&&r.right.kind==="arr"?r.right.items.filter(_w):_w(r.right)?[r.right]:[];i.length>0&&n.push({ident:r.left.path,literals:i})}r.right.kind==="ident"&&_w(r.left)&&n.push({ident:r.right.path,literals:[r.left]})}EN(r,t)},"visit");return t(e),n}s(AN,"comparedLiterals");function JY(e,n,t){for(let{ident:r,literals:i}of AN(e)){let o=QY(r,i,n);o!==null&&t.push(o)}}s(JY,"literalIssues");function Nw(e,n){let t;try{t=In(e)}catch{return[]}let r=[];for(let{ident:i,literals:o}of AN(t)){let a=ra(i);if(!(a===null||n.fields[a]?.valueSet.kind!=="live"))for(let l of o)l.kind==="str"&&r.push({path:a,value:l.value})}return r}s(Nw,"liveLiterals");function QY(e,n,t){let r=t.fields[xN(e)]?.valueSet;if(r?.kind==="unstable")return Gn("condition/literalOnUnstable",`'${e}' ist nicht \xFCber Umgebungen stabil \u2014 vergleiche ihn mit keinem festen Wert; verzweige stattdessen \xFCber ein stabiles Merkmal`,`'${e}' is not stable across environments \u2014 compare it to no literal; branch on a stable attribute instead`);if(r?.kind!=="fixed")return null;let i=n.flatMap(a=>a.kind==="str"&&!r.values.includes(a.value)?[`'${a.value}'`]:[]);if(i.length===0)return null;let o=r.values.map(a=>`'${a}'`).join(", ");return Gn("condition/literalOutsideSet",`'${e}' kennt nur ${o} \u2014 nicht ${i.join(", ")}`,`'${e}' takes only ${o} \u2014 not ${i.join(", ")}`)}s(QY,"valueSetIssue");function EN(e,n){switch(e.kind){case"binary":n(e.left),n(e.right);return;case"unary":n(e.operand);return;case"call":e.args.forEach(n);return;case"arr":e.items.forEach(n);return;case"if":n(e.cond),n(e.then),n(e.else);return;default:return}}s(EN,"forEachChild");function TN(e){return e.kind==="binary"&&(e.op==="=="||e.op==="!=")&&(e.left.kind==="ident"&&e.right.kind==="null"||e.left.kind==="null"&&e.right.kind==="ident")}s(TN,"isNullTest");function $N(e){return sa(e).flatMap(n=>{let t=RN(n);return t===null?[]:[t]})}s($N,"guardsOf");function Ql(e,n,t){switch(e.kind){case"ident":return SN(n,e.path)&&!t.has(e.path)?e.path:null;case"call":for(let r of e.args){let i=Ql(r,n,t);if(i!==null)return i}return null;case"if":return Ql(e.then,n,new Set([...t,...$N(e.cond)]))??Ql(e.else,n,t);default:return null}}s(Ql,"unguardedNullSource");function RN(e){return!TN(e)||e.kind!=="binary"||e.op!=="!="?null:e.left.kind==="ident"?e.left.path:e.right.kind==="ident"?e.right.path:null}s(RN,"guardedIdent");function oa(e,n,t,r){if(e.kind==="binary"&&e.op==="&&"){let i=new Set(t);for(let o of sa(e)){oa(o,n,i,r);let a=RN(o);a!==null&&i.add(a)}return}if(e.kind==="if"){oa(e.cond,n,t,r),oa(e.then,n,new Set([...t,...$N(e.cond)]),r),oa(e.else,n,t,r);return}if(e.kind==="binary"&&e.op==="!="&&e.left.kind!=="null"&&e.right.kind!=="null"){let i=Ql(e.left,n,t)??Ql(e.right,n,t);i!==null&&r(i,"!=")}if(e.kind==="unary"&&!TN(e.operand)){let i=On(e.operand).filter(o=>SN(n,o)&&!t.has(o));i.length>0&&r(i[0],"!")}EN(e,i=>oa(i,n,t,r))}s(oa,"nullableReads");function Pw(e,n){ia(n);let t=[];return oa(e,n,new Set,(r,i)=>{t.some(o=>o.identifier===r)||t.push({identifier:r,op:i})}),t}s(Pw,"unguardedNullableReads");function Gn(e,n,t){return{severity:"error",code:e,message:{de:`[${e}] ${n}`,en:`[${e}] ${t}`}}}s(Gn,"error");function Zl(e){let n=Array.isArray(e.nodes)?e.nodes:[],t=new Set;for(let r of n)for(let i of Wf(r))i.key!==null&&Us[i.leaf].involves&&t.add(i.key);return t}s(Zl,"declaredGroupKeys");var aa=vf;var ZY="unit.key",XY="offer.key";function IN(e,n){return e===ZY?n.unitKeys:e===XY?n.offerKeys:null}s(IN,"liveKeyUniverse");function mp(e){return[gn,...[...Zl(e)].sort((n,t)=>n.localeCompare(t)).map(Rf)]}s(mp,"requiredSlots");var Wi=`${Sf("applicant.channel")} == 'staff'`;var Dw=["strict","leastLoaded"];var Cw=2;function ON(e){return e.some(n=>n.length===0)?{de:"nennt einen leeren Personenschl\xFCssel",en:"names an empty person key"}:new Set(e).size!==e.length?{de:"nennt eine Person zweimal",en:"names a person twice"}:e.length<Cw?{de:`braucht mindestens ${Cw} Personen`,en:`needs at least ${Cw} people`}:null}s(ON,"rotationPoolProblem");function eH(e,n){let t=n===null?-1:e.indexOf(n);return[...e.slice(t+1),...e.slice(0,t+1)]}s(eH,"strictOrder");function _N(e){let n=eH(e.pool,e.previous).filter(i=>e.eligible.has(i));if(n.length===0)return null;if(e.mode==="strict")return n[0];let t=e.openCounts;t===void 0&&L("[assignment/rotation] leastLoaded needs the open counts");let r=s(i=>{let o=t.get(i);return o===void 0&&L(`[assignment/rotation] no open count for '${i}'`),o},"load");return n.reduce((i,o)=>r(o)<r(i)?o:i)}s(_N,"pickFromPool");function PN(e){return e.map(n=>({slot:jI(n.slot),rules:[...n.rules]}))}s(PN,"rulesOfStored");function CN(e){return e.map(n=>({slot:nH(n.slot),rules:[...n.rules]}))}s(CN,"storedOfRules");function nH(e){let n=Of(e);return n===null&&L(`[assignment/unknownSlot] '${e}' is no slot \u2014 'responsible' or 'team:<teamKey>'`),n}s(nH,"slotOf");function DN(e,n){let t=e?.assignmentRules;t===void 0&&L(`[assignment/noRules] ${n}: the workflow has no assignment rule`);let r=qN(t);return r.length>0&&L(`${r.join("; ")} (${n})`),PN(t)}s(DN,"rulesOfGraph");function tH(e){return e===gn?{slot:e,rules:[{when:Wi,assign:{kind:"creator"}},{when:null,assign:{kind:"unassigned"}}]}:{slot:e,rules:[{when:null,assign:{kind:"queue"}}]}}s(tH,"defaultSlotRules");function FN(e,n){let t=new Set(e.map(o=>o.slot)),r=n.filter(o=>!t.has(o)).map(tH);return[...r.filter(o=>o.slot===gn),...e,...r.filter(o=>o.slot!==gn)]}s(FN,"withRequiredSlots");function Nn(e,n){return n===void 0?`slot '${e}'`:`slot '${e}' row #${n+1}`}s(Nn,"where");function Ct(e,n){return n===void 0?`Liste '${e}'`:`Liste '${e}', Zeile #${n+1}`}s(Ct,"whereDe");function xt(e,n,t={},r="error"){return{severity:r,code:e,message:{de:`[${e}] ${n.de}`,en:`[${e}] ${n.en}`},...t}}s(xt,"issue");function NN(e){if(e===gn)return!0;let n=If(e);return n!==null&&n.length>0}s(NN,"isKnownSlot");function rH(e,n){ia(aa);let t=[],r=new Set;e.forEach((o,a)=>{let{slot:l}=o;NN(l)||t.push(xt("assignment/unknownSlot",{de:`'${l}' ist keine Liste \u2014 'responsible' oder 'team:<teamKey>'`,en:`'${l}' is no slot \u2014 'responsible' or 'team:<teamKey>'`},{slot:l})),r.has(l)&&t.push(xt("assignment/duplicateSlot",{de:`${Ct(l)} steht zweimal da`,en:`${Nn(l)} is listed twice`},{slot:l})),r.add(l),l===gn&&a!==0&&t.push(xt("assignment/responsibleFirst",{de:`'${gn}' muss die erste Liste sein \u2014 Team-Zeilen \xFCbernehmen sie`,en:`'${gn}' must be the first slot \u2014 team rows copy it`},{slot:l})),t.push(...iH(o))});for(let o of n)r.has(o)||t.push(xt("assignment/slotMissing",{de:`${Ct(o)} hat keine Regeln \u2014 der Workflow braucht sie`,en:`${Nn(o)} has no rule list \u2014 the workflow needs it`},{slot:o}));let i=new Set(n);for(let{slot:o}of e)o!==gn&&!i.has(o)&&NN(o)&&t.push(xt("assignment/unusedSlot",{de:`${Ct(o)} wird hier nicht gebraucht \u2014 erlaubt, und nicht ausgewertet`,en:`${Nn(o)} is not needed here \u2014 allowed, and not evaluated`},{slot:o},"info"));return t}s(rH,"validateRules");function iH({slot:e,rules:n}){let t=[];return(n.length===0||n[n.length-1].when!==null)&&t.push(xt("assignment/defaultRowMissing",{de:`${Ct(e)} muss mit einer Zeile ohne Bedingung enden (\u201Esonst\u201C)`,en:`${Nn(e)} must end with a row without condition ("otherwise")`},{slot:e})),n.forEach((r,i)=>{let o={slot:e,row:i},{when:a,assign:l}=r;if(a===null&&i<n.length-1&&t.push(xt("assignment/ruleAfterDefault",{de:`${Ct(e,i)} hat keine Bedingung, aber es folgen Zeilen \u2014 sie treffen nie zu`,en:`${Nn(e,i)} has no condition, but rows follow it \u2014 they can never match`},o)),a!==null){let d=pp(a,aa,[Wi]);for(let c of d)t.push({...c,message:{de:`${c.message.de} (${Ct(e,i)})`,en:`${c.message.en} (${Nn(e,i)})`},...o});if(d.every(c=>c.severity!=="error")){vN(a)||t.push(xt("assignment/shadowedRule",{de:`${Ct(e,i)} liest nichts aus dem Vorgang \u2014 sie gilt immer oder nie`,en:`${Nn(e,i)} reads nothing of the application \u2014 it holds for every application or for none`},o));let c=n.slice(0,i).findIndex(u=>u.when!==null&&kN(u.when,a));c!==-1&&t.push(xt("assignment/shadowedRule",{de:`${Ct(e,i)} wiederholt die Bedingung von Zeile #${c+1} \u2014 sie trifft nie zu`,en:`${Nn(e,i)} repeats the condition of row #${c+1} \u2014 it can never match`},o))}}if(e===gn&&l.kind==="slot"&&t.push(xt("assignment/slotForwardRef",{de:`${Ct(e,i)} \xFCbernimmt '${l.slot}' \u2014 das darf nur eine Team-Liste nach '${gn}'`,en:`${Nn(e,i)} copies '${l.slot}' \u2014 only a team slot after '${gn}' may`},o)),e===gn&&l.kind==="queue"&&t.push(xt("assignment/queueOnProcessSlot",{de:`${Ct(e,i)} weist die Queue zu \u2014 die Prozesszust\xE4ndigkeit ist immer eine Person`,en:`${Nn(e,i)} assigns the queue \u2014 the responsible slot is always a person`},o)),l.kind==="unassigned"&&t.push(xt("assignment/targetMissing",{de:`${Ct(e,i)} nennt noch niemanden \u2014 Person w\xE4hlen`,en:`${Nn(e,i)} names no one yet \u2014 choose a person`},o)),l.kind==="rotation"){let d=ON(l.configKeys);d!==null&&t.push(xt("assignment/rotationPool",{de:`${Ct(e,i)}: die Reihum-Liste ${d.de}`,en:`${Nn(e,i)} rotates over a pool that ${d.en}`},o))}l.kind==="creator"&&(a===null||!wN(a,Wi))&&t.push(xt("assignment/unguardedTarget",{de:`${Ct(e,i)} weist die anlegende Person zu \u2014 die gibt es nur, wenn die Bedingung der Zeile '${Wi}' ist (oder enth\xE4lt)`,en:`${Nn(e,i)} assigns the creator, which exists only when the row's condition is (or has the conjunct) '${Wi}'`},o))}),t}s(iH,"rowIssues");function LN(e,n){for(let r of n)e.some(i=>i.slot===r)||L(`[assignment/slotMissing] ${Nn(r)} has no rule list`);let t=new Set(n);return e.filter(r=>t.has(r.slot))}s(LN,"selectSlots");function oH(e,n){return bN(LN(e,n).flatMap(t=>t.rules.flatMap(r=>r.when===null?[]:[r.when])))}s(oH,"contextKeysOfRules");function MN(e,n,t,r){ia(aa);let i=LN(e,t),o=oH(e,t),a=cp(aa.types,n,o);hN(aa,a,o);let l=[];for(let{slot:d,rules:c}of i){let u=c.findIndex((h,y)=>{if(h.when===null)return!0;for(let k of On(ii(h.when)))Object.hasOwn(a,k)||L(`[condition/unknownIdentifier] ${Nn(d,y)} reads '${k}', which the context does not carry`);return yO(h.when,{values:a})});u===-1&&L(`[assignment/defaultRowMissing] ${Nn(d)}: no row matched and there is no default row`);let p=c[u].assign;l.push({slot:d,ruleIndex:u,assign:p,value:sH(d,u,p,l,r)})}return l}s(MN,"evaluateRules");function sH(e,n,t,r,i){switch(t.kind){case"person":return{kind:"value",value:i.person(t.configKey)};case"creator":return{kind:"value",value:i.creator()};case"rotation":return{kind:"value",value:i.rotation(t,{slot:e,row:n})};case"unassigned":return L(`[assignment/targetMissing] ${Nn(e,n)} names no one`);case"queue":return e===gn&&L(`[assignment/queueOnProcessSlot] ${Nn(e,n)} assigns the queue`),{kind:"queue"};case"slot":{let o=e===gn?void 0:r.find(a=>a.slot===t.slot);return o===void 0&&L(`[assignment/slotForwardRef] ${Nn(e,n)} copies '${t.slot}', which is not decided before it`),o.value}}}s(sH,"resolveTarget");var Fw={person:["kind","configKey"],creator:["kind"],slot:["kind","slot"],queue:["kind"],rotation:["kind","configKeys","mode"],unassigned:["kind"]};function aH(e){if(typeof e!="object"||e===null)return!1;let{kind:n,groupKey:t,...r}=e;return Object.keys(r).length>0?!1:n==="responsible"?t===void 0:n==="team"&&typeof t=="string"&&t.length>0}s(aH,"isStoredSlot");function qN(e){let n=[],t=s((r,i)=>n.push(`[assignment/shape] ${r}: ${i}`),"bad");return Array.isArray(e)?(e.forEach((r,i)=>{let o=`slots[${i}]`;if(typeof r!="object"||r===null)return t(o,"must be { slot, rules }");let{slot:a,rules:l,...d}=r;if(Object.keys(d).length>0&&t(o,`unknown field(s) ${Object.keys(d).join(", ")}`),aH(a)||t(o,"slot must be { kind: 'responsible' } or { kind: 'team', groupKey: '<team key>' }"),!Array.isArray(l))return t(o,"rules must be a list");l.forEach((c,u)=>{let p=`${o}.rules[${u}]`;if(typeof c!="object"||c===null)return t(p,"must be { when, assign }");let{when:h,assign:y,...k}=c;Object.keys(k).length>0&&t(p,`unknown field(s) ${Object.keys(k).join(", ")}`),h!==null&&typeof h!="string"&&t(p,"when must be a condition string or null (\u201Esonst\u201C)");let w=y?.kind;if(typeof y!="object"||y===null||typeof w!="string"||!Object.hasOwn(Fw,w))return t(p,`assign must be one of ${Object.keys(Fw).map(R=>`{kind:'${R}'}`).join(", ")}`);let v=Fw[w],A=Object.keys(y);(A.some(R=>!v.includes(R))||v.some(R=>!A.includes(R)))&&t(p,`a '${w}' target has exactly the field(s) ${v.join(", ")}`);let E=y;if(w==="person"&&(typeof E.configKey!="string"||E.configKey.length===0)&&t(p,"a 'person' target needs a non-empty configKey"),w==="rotation"){let R=E.configKeys;(!Array.isArray(R)||R.some(P=>typeof P!="string"))&&t(p,"a 'rotation' target needs configKeys, a list of person keys"),Dw.includes(E.mode)||t(p,`a 'rotation' target's mode is one of ${Dw.map(P=>`'${P}'`).join(", ")}`)}w==="slot"&&E.slot!==gn&&t(p,`a 'slot' target copies '${gn}' and nothing else`)})}),n):(t("slots","must be a list of { slot, rules }"),n)}s(qN,"ruleShapeIssues");function KN(e){let n=e??{},t=[];if(n.teamOwnerBindings!==void 0&&t.push({de:"[assignment/legacyBindings] der Workflow tr\xE4gt noch teamOwnerBindings \u2014 die Zust\xE4ndigkeitsregel ersetzt sie; das Feld entfernen",en:"[assignment/legacyBindings] the workflow still carries teamOwnerBindings \u2014 the assignment rule replaces them; remove the field"}),n.assignmentRules===void 0)return t.push({de:"[assignment/noRules] der Workflow hat keine Zust\xE4ndigkeitsregel (graph.assignmentRules) \u2014 jeder Workflow muss sagen, wer zust\xE4ndig wird",en:"[assignment/noRules] the workflow has no assignment rule (graph.assignmentRules) \u2014 every workflow must say who becomes responsible"}),t;let r=qN(n.assignmentRules);if(r.length>0)return[...t,...r.map(o=>({de:o,en:o}))];let i=mp({nodes:Array.isArray(n.nodes)?n.nodes:[]});for(let o of rH(PN(n.assignmentRules),i))o.severity==="error"&&t.push(o.message);return t}s(KN,"workflowAssignmentIssues");function hp(e,n){let o=new Map;for(let d of e)o.set(d,0);let a=new Map,l=[];for(let d of e){if((o.get(d)??0)!==0)continue;let c=[{id:d,edges:n(d),idx:0}];for(o.set(d,1),a.set(d,null);c.length>0;){let u=c[c.length-1];if(u.idx>=u.edges.length){o.set(u.id,2),c.pop();continue}let{target:p,edge:h}=u.edges[u.idx];u.idx++;let y=o.get(p)??0;if(y===1){let k=[p],w=u.id;for(;w&&w!==p;)k.push(w),w=a.get(w)??null;k.reverse(),l.push({edge:h,source:u.id,target:p,cycle:k})}else y===0&&(o.set(p,1),a.set(p,u.id),c.push({id:p,edges:n(p),idx:0}))}}return l}s(hp,"detectBackEdges");var Lw="team:",lH=/^[a-z0-9][a-z0-9-]*$/;function dH(e){if(!e.startsWith(Lw))return null;let n=e.slice(Lw.length);return n.length>0?n:null}s(dH,"teamKeyOfMember");function gp(e){return`${Lw}${e}`}s(gp,"teamMember");function la(e){let n=e.channels;return n===void 0?[]:(Array.isArray(n)||L("graph.channels must be an array"),n)}s(la,"readAuthoredChannels");function jN(e){return[...Zl(e)].sort()}s(jN,"derivedChannelTeamKeys");function VN(e,n){let t=e.toLowerCase().replace(/ä/g,"ae").replace(/ö/g,"oe").replace(/ü/g,"ue").replace(/ß/g,"ss").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"channel";if(!n.has(t))return t;for(let r=2;;r++){let i=`${t}-${r}`;if(!n.has(i))return i}}s(VN,"mintChannelKey");function BN(e,n){let t=e.channels;if(t===void 0)return[];if(!Array.isArray(t))return[{path:"channels",reason:{de:"[channels/shape] graph.channels muss eine Liste sein.",en:"[channels/shape] graph.channels must be a list."}}];let r=[],i=Zl(e),o=new Set,a=new Map;return t.forEach((l,d)=>{let c=`channels[${d}]`,u=l;if(u===null||typeof u!="object"||typeof u.key!="string"||Rn(u.label)==="not-localized"||!Array.isArray(u.members)||!u.members.every(A=>typeof A=="string")){r.push({path:c,reason:{de:"[channels/shape] Ein Kanal braucht key, label ({ de, en }) und members (Liste von Texten).",en:"[channels/shape] A channel needs key, label ({ de, en }) and members (a list of texts)."}});return}let p={de:`Kanal "${u.key}"`,en:`Channel "${u.key}"`};lH.test(u.key)||r.push({path:`${c}.key`,reason:{de:`[channels/invalidKey] ${p.de}: Schl\xFCssel nur aus Kleinbuchstaben, Ziffern und Bindestrich.`,en:`[channels/invalidKey] ${p.en}: key only from lowercase letters, digits and hyphens.`}}),o.has(u.key)&&r.push({path:`${c}.key`,reason:{de:`[channels/duplicateKey] ${p.de}: Schl\xFCssel ist doppelt vergeben.`,en:`[channels/duplicateKey] ${p.en}: key is used twice.`}}),o.add(u.key);let h=Rn(u.label);if(h!=="not-localized"&&h.length===2?r.push({path:`${c}.label`,reason:{de:`[channels/emptyLabel] ${p.de}: Bezeichnung fehlt.`,en:`[channels/emptyLabel] ${p.en}: name is missing.`}}):h!=="not-localized"&&h.length>0&&r.push({path:`${c}.label`,reason:{de:`[i18n/missingTranslation] ${p.de}: Bezeichnung fehlt in: ${h.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`,en:`[i18n/missingTranslation] ${p.en}: name is missing in: ${h.join(", ")} \u2014 every displayed text needs German and English.`}}),u.members.length===0){r.push({path:`${c}.members`,reason:{de:`[channels/emptyMembers] ${p.de}: mindestens ein Team.`,en:`[channels/emptyMembers] ${p.en}: at least one team.`}});return}let y=[];for(let A of u.members){let E=dH(A);if(E===null){r.push({path:`${c}.members`,reason:{de:`[channels/invalidMember] ${p.de}: "${A}" ist kein "team:<schl\xFCssel>".`,en:`[channels/invalidMember] ${p.en}: "${A}" is not a "team:<key>".`}});continue}if(y.includes(E)){r.push({path:`${c}.members`,reason:{de:`[channels/duplicateMember] ${p.de}: Team "${E}" ist doppelt genannt.`,en:`[channels/duplicateMember] ${p.en}: team "${E}" is named twice.`}});continue}n!==void 0&&!n.has(E)&&r.push({path:`${c}.members`,reason:{de:`[channels/unknownTeam] ${p.de}: Team "${E}" gibt es in diesem Mandanten nicht (oder es ist die Bewerbergruppe).`,en:`[channels/unknownTeam] ${p.en}: team "${E}" does not exist at this school (or it is the applicant group).`}}),y.push(E)}if(y.length===0)return;let k=[...y].sort().join("+"),[w]=y;y.length===1&&w!==void 0&&i.has(w)&&r.push({path:`${c}.members`,reason:{de:`[channels/duplicatesDerived] ${p.de}: Team "${w}" ist am Prozess beteiligt und hat seinen Kanal schon automatisch.`,en:`[channels/duplicatesDerived] ${p.en}: team "${w}" takes part in the process and already has its channel automatically.`}});let v=a.get(k);v!==void 0?r.push({path:`${c}.members`,reason:{de:`[channels/duplicateMembership] ${p.de}: dieselben Teams wie Kanal "${v}" \u2014 zwei Tabs w\xE4ren derselbe Chat.`,en:`[channels/duplicateMembership] ${p.en}: the same teams as channel "${v}" \u2014 two tabs would be the same chat.`}}):a.set(k,u.key)}),r}s(BN,"channelIssues");var Phe=Object.freeze({});function cH(e,n){return Object.freeze(cp(Zr,e,n))}s(cH,"formContextEntries");function UN(e){return e.env??[]}s(UN,"declaredContextKeys");function GN(e,n){return UN(e).every(t=>zN(t,n?.[t]))}s(GN,"scenarioContextComplete");function zN(e,n){return mN(Zr,e,n)}s(zN,"contextValueComplete");function WN(e,n){return cH(n??{},UN(e))}s(WN,"scenarioContextEntries");function qw(e){return Hl(e)}s(qw,"isContextIdentifier");function uH(e,n,t){let r=dp(Zr,e);if(r!==null)return{severity:"error",path:t,code:"env/unknownKey",message:r.message};let[,i=""]=e.split(".");return n.has(i)?null:{severity:"error",path:t,code:"env/undeclared",message:{de:`'${e}' liest den Umgebungsschl\xFCssel '${i}', den das Formular nicht in \`env\` deklariert.`,en:`'${e}' reads the environment key '${i}', which the form does not declare in \`env\`.`}}}s(uH,"contextIdentifierIssue");var Mw=Sf("stage.key");function fH(e){let n=[],t=s(i=>i.kind==="ident"&&i.path===Mw,"isStageKey"),r=s(i=>{switch(i.kind){case"binary":if((i.op==="=="||i.op==="!=")&&(t(i.left)&&i.right.kind==="str"&&n.push(i.right.value),t(i.right)&&i.left.kind==="str"&&n.push(i.left.value)),i.op==="in"&&t(i.left)&&i.right.kind==="arr")for(let o of i.right.items)o.kind==="str"&&n.push(o.value);r(i.left),r(i.right);return;case"unary":r(i.operand);return;case"if":r(i.cond),r(i.then),r(i.else);return;case"call":i.args.forEach(r);return;case"arr":i.items.forEach(r);return;default:return}},"walk");return r(e),n}s(fH,"stageKeyLiterals");function yp(e,n,t){return n===void 0?[]:fH(e).filter(r=>!n.has(r)).map(r=>HN(r,n,t))}s(yp,"stageKeyAstIssues");function YN(e,n){if(n===void 0)return[];let t=[];for(let r of e.testScenarios??[]){let i=r.env?.stage;typeof i?.key=="string"&&!n.has(i.key)&&t.push(HN(i.key,n,`scenario:${r.id}/env`))}return t}s(YN,"scenarioStageKeyIssues");function HN(e,n,t){let r=[...n].sort();return{severity:"error",path:t,code:"env/unknownStageKey",message:{de:`'${e}' ist kein Stufenschl\xFCssel des Programms dieses Angebots \u2014 `+(r.length>0?`bekannt: ${r.join(", ")}.`:"das Angebot hat kein Programm mit Stufen.")+` \`${Mw}\` ist der Bundle-Schl\xFCssel (\`program.stages[].key\`), nie das gespeicherte \`<program>-stufe-<key>\`.`,en:`'${e}' is not a stage key of the offer's program \u2014 `+(r.length>0?`known: ${r.join(", ")}.`:"the offer has no program with stages.")+` \`${Mw}\` is the bundle key (\`program.stages[].key\`), never the stored \`<program>-stufe-<key>\`.`}}}s(HN,"unknownStageKeyIssue");function JN(e,n,t){let r=[];for(let i of On(e)){if(!qw(i))continue;let o=uH(i,n,t);o!==null&&r.push(o)}if(r.length>0)return r;for(let{identifier:i,op:o}of Pw(e,vf))r.push({severity:"error",path:t,code:"env/unguardedNullable",message:{de:`'${o}' \xFCber '${i}', das bei manchen Bewerbungen leer ist, braucht davor eine Absicherung '${i} != null &&' \u2014 lege fest, was ein leerer Wert bedeutet.`,en:`'${o}' over '${i}', which is empty for some applications, needs a guard '${i} != null &&' before it \u2014 say what an empty value means.`}});return r}s(JN,"contextAstIssues");function QN(e,n){let t=[...pH(e)],r=new Set(e.env??[]);for(let i of e.env??[]){if(!Ns(i)){t.push({severity:"error",path:"env",code:"env/unknownKey",message:{de:`Der deklarierte Umgebungsschl\xFCssel '${i}' geh\xF6rt nicht zum Vokabular (${_s.join(", ")}).`,en:`Declared environment key '${i}' is not in the vocabulary (${_s.join(", ")}).`}});continue}n!==void 0&&!n.has(i)&&t.push({severity:"error",path:"env",code:"env/unsupplied",message:{de:`Das Formular deklariert den Umgebungsschl\xFCssel '${i}', aber sein Host liefert ihn nicht.`,en:`The form declares environment key '${i}', but its host does not supply it.`}})}for(let i of e.testScenarios??[]){let o=[...r].filter(a=>Ns(a)&&!zN(a,i.env?.[a]));o.length>0&&t.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unsampled",message:{de:`Szenario '${i.id}' belegt den deklarierten Umgebungsschl\xFCssel ${o.map(a=>`'${a}'`).join(", ")} nicht vollst\xE4ndig \u2014 eine echte Bewerbung tr\xE4gt immer jedes seiner Felder (ein leeres als null).`,en:`Scenario '${i.id}' does not sample the declared environment key(s) ${o.map(a=>`'${a}'`).join(", ")} completely \u2014 a real application always carries every field of them (an empty one as null).`}});for(let a of Object.keys(i.env??{}))Ns(a)?r.has(a)||t.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/undeclared",message:{de:`Szenario '${i.id}' belegt den Umgebungsschl\xFCssel '${a}', den das Formular nicht deklariert.`,en:`Scenario '${i.id}' samples environment key '${a}', which the form does not declare.`}}):t.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unknownKey",message:{de:`Szenario '${i.id}' belegt den unbekannten Umgebungsschl\xFCssel '${a}'.`,en:`Scenario '${i.id}' samples unknown environment key '${a}'.`}})}return t}s(QN,"formContextIssues");function pH(e){let n=[];Object.hasOwn(e,"context")&&n.push({severity:"error",path:"context",code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Formular deklariert die gelesene Umgebung als `env`.",en:"`context` is retired \u2014 a form declares the environment it reads as `env`."}});let t=e.testScenarios;for(let r of Array.isArray(t)?t:[])r!==null&&typeof r=="object"&&Object.hasOwn(r,"context")&&n.push({severity:"error",path:`scenario:${String(r.id)}/context`,code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Szenario belegt die Umgebung als `env`.",en:"`context` is retired \u2014 a scenario samples the environment as `env`."}});return n}s(pH,"retiredContextFields");function wp(e,n,t){let r=pp(e,n).filter(o=>o.severity==="error").map(o=>o.message);if(r.length>0)return r;let i=[];if(t?.liveEnvKeys!==void 0)for(let o of Nw(e,n)){let a=IN(o.path,t.liveEnvKeys);a===null&&L(`[condition] no live-key universe for '${o.path}' \u2014 extend liveKeyUniverse`),a.has(o.value)||i.push({de:`$env.${o.path} == '${o.value}' nennt keinen Schl\xFCssel dieses Mandanten.`,en:`$env.${o.path} == '${o.value}' names no key of this school.`})}for(let o of yp(In(e),t?.stageKeys,""))i.push({de:`[${o.code}] ${o.message.de}`,en:`[${o.code}] ${o.message.en}`});return i}s(wp,"envConditionFindings");function kp(e){return e.kind==="entered"&&!e.repeated&&e.reviewRequired}s(kp,"isReviewField");function da(e){let n=[],t=[];function r(w,v){try{return In(w)}catch(A){n.push({path:v,src:w,reason:A instanceof Error?A.message:String(A)});return}}s(r,"tryParse");function i(w,v){return{...w,visibleIf:w.visibleIf?r(w.visibleIf,`${v}.visibleIf`):void 0,requiredIf:w.requiredIf?r(w.requiredIf,`${v}.requiredIf`):void 0,disabledIf:w.disabledIf?r(w.disabledIf,`${v}.disabledIf`):void 0,defaultValue:w.defaultValue?r(w.defaultValue,`${v}.defaultValue`):void 0}}s(i,"compileField");function o(w,v){return{...w,visibleIf:w.visibleIf?r(w.visibleIf,`${v}.visibleIf`):void 0,fields:w.fields.map((A,E)=>i(A,`${v}.fields[${E}]`))}}s(o,"compileGroup");function a(w,v){return{...w,itemTemplate:w.itemTemplate.map((A,E)=>i(A,`${v}.itemTemplate[${E}]`)),effects:w.effects?.map((A,E)=>d(A,`${v}.effects[${E}]`)),itemVisibleIf:w.itemVisibleIf?r(w.itemVisibleIf,`${v}.itemVisibleIf`):void 0}}s(a,"compileRepeated");function l(w,v){let A=[];return w.fields.forEach((E,R)=>{if(E.externalFlag){t.push({key:E.key,label:E.label,defaultValue:E.defaultValue?r(E.defaultValue,`${v}.fields[${R}].defaultValue`):void 0});return}A.push(i(E,`${v}.fields[${R}]`))}),{...w,visibleIf:w.visibleIf?r(w.visibleIf,`${v}.visibleIf`):void 0,fields:A,groups:w.groups?.map((E,R)=>o(E,`${v}.groups[${R}]`)),computed:w.computed?.map((E,R)=>{let P=r(E.expression,`${v}.computed[${R}].expression`);return{key:E.key,expression:P??{kind:"null"}}}),subsections:w.subsections?.map((E,R)=>l(E,`${v}.subsections[${R}]`)),repeated:w.repeated?.map((E,R)=>a(E,`${v}.repeated[${R}]`)),validators:w.validators}}s(l,"compileSection");function d(w,v){return{...w,when:w.when?r(w.when,`${v}.when`):void 0}}s(d,"compileEffect");function c(w,v){let A=r(w.when,`${v}.when`);return A?{...w,when:A}:null}s(c,"compileOutcome");let u=e.sections.map((w,v)=>l(w,`sections[${v}]`)),p=(e.effects??[]).map((w,v)=>d(w,`effects[${v}]`)),h=[],y=e.outcomes??[];for(let w=0;w<y.length;w++){let v=y[w],A=c(v,`outcomes[${w}]`);A&&h.push(A)}return{compiled:{...e,sections:u,effects:p,outcomes:h,flags:t},errors:n}}s(da,"compileForm");var mH=new Set(["decision","review","governedDocument"]);function XN(e){return mH.has(e.type)&&!(e.type==="governedDocument"&&e.production==="none")}s(XN,"isReadinessGatedNode");function hH(e){let n=new Map,t=yH(e),r=s((i,o)=>{let a=Kw(o),l=[...i.fields,...(i.groups??[]).flatMap(d=>d.fields)];for(let d of l)d.externalFlag!==!0&&n.set(d.key,{kind:"entered",key:d.key,label:d.label,qualifier:gH(d.bucket,t,a),section:a,type:d.type,enumSource:ZN(d),repeated:!1,reviewRequired:d.reviewRequired===!0});for(let d of i.repeated??[])for(let c of d.itemTemplate){let u=`${d.key}.${c.key}`;n.set(u,{kind:"entered",key:u,label:c.label,qualifier:Kw(d),section:a,type:c.type,enumSource:ZN(c),repeated:!0,reviewRequired:!1})}for(let d of i.computed??[]){let c=On(In(d.expression));n.set(d.key,{kind:"computed",key:d.key,label:d.label??{de:d.key,en:d.key},qualifier:a,deps:c})}for(let d of i.subsections??[])r(d,o)},"visit");for(let i of e.sections)r(i,i);return n}s(hH,"formFieldCatalog");function ZN(e){return e.type==="enum"?e:null}s(ZN,"enumSourceOf");function gH(e,n,t){return e===void 0?t:n.get(e)??t}s(gH,"fieldQualifier");function yH(e){let n=new Map,t=s((r,i)=>{i===void 0||n.has(r)||n.set(r,Kw(i))},"add");for(let r of nP(e))r.kind==="person"?t(r.bucket,r.display):r.kind==="organization"&&t(r.id.replace(/^o\./,""),r.display);return n}s(yH,"bucketWordings");function eP(e){return e.flatMap(n=>[n,...eP(n.subsections??[])])}s(eP,"allSections");function nP(e){return[...e.effects,...eP(e.sections).flatMap(n=>(n.repeated??[]).flatMap(t=>t.effects??[]))]}s(nP,"allEffects");function Kw(e){return{label:e.label}}s(Kw,"wordingOf");function tP(e){return Pl(e).flatMap(({slot:n,address:t})=>{let r=SO(t);return r===null||Nl.includes(r.path)?[]:[{slotId:n,owner:r.owner,fieldKey:r.path}]})}s(tP,"admissionBindingLeaves");function wH(e,n){let t=e.get(n);if(t===void 0)return null;let r=[],i=new Set,o=s(a=>{if(!i.has(a.key)&&(i.add(a.key),r.push({fieldKey:a.key,kind:a.kind}),a.kind==="computed"))for(let l of a.deps){let d=e.get(l);d!==void 0&&o(d)}},"walk");return o(t),r}s(wH,"expandKey");function kH(e){let n=new Set;for(let t of nP(e))if(!(t.kind!=="person"||t.contractParty===void 0)&&t.when!==void 0)for(let r of On(In(t.when)))n.add(r);return[...n]}s(kH,"contractPartyConditionKeys");function bH(e){return da(e).compiled.flags.map(n=>({key:n.key,name:n.label}))}s(bH,"formExternalFlags");function rP(e){return{readinessFormFieldsByFormNode:new Map([...e].map(([n,t])=>[n,hH(t)])),readinessPartyConditionKeysByFormNode:new Map([...e].map(([n,t])=>[n,new Set(kH(t))])),formFlagKeysByFormNode:new Map([...e].map(([n,t])=>[n,new Set(bH(t).map(r=>r.key))])),formViewKeysByFormNode:new Map([...e].map(([n,t])=>[n,new Set((t.views??[]).map(r=>r.key))]))}}s(rP,"readinessUniverse");function jw(e,n){let t=new Set;for(let r of n)for(let i of wH(e,r)??[])i.kind==="entered"&&t.add(i.fieldKey);return t}s(jw,"enteredFieldsBehind");var vH=new Set(["label","sublabel","title","description","body","chipLabel","nextAction","confirmLabel","placeholder","helpText","subject","heading","hint","notice","reason"]);function xH(e){return vH.has(e)?!0:iP(e)?!1:/(Label|Title|Body|Description|Text|Hint|Heading|Placeholder)$/.test(e)}s(xH,"isTextKey");function iP(e){return/^localized[A-Z]/.test(e)}s(iP,"isLegacyTwinKey");var SH=new Set(["titles","responseLabels","outputLabels","enumOptionLabels"]),AH=new Set(["inputs","resolver","library"]);function vp(e,n){let t=[];return Vw(e,n,t),t}s(vp,"findUnlocalizedTexts");function Vw(e,n,t){if(Array.isArray(e)){e.forEach((i,o)=>Vw(i,`${n}[${TH(i,o)}]`,t));return}if(e===null||typeof e!="object")return;let r=e;for(let[i,o]of Object.entries(r)){let a=`${n}.${i}`;if(!AH.has(i)){if(iP(i)){t.push({path:a,missing:"legacy-twin"});continue}if(xH(i)){EH(o,a,t);continue}if(SH.has(i)&&o!==null&&typeof o=="object"){for(let[l,d]of Object.entries(o))d!==void 0&&oP(d,`${a}.${l}`,t);continue}Vw(o,a,t)}}}s(Vw,"walk");function EH(e,n,t){e!=null&&oP(e,n,t)}s(EH,"checkText");function oP(e,n,t){let r=Rn(e);(r==="not-localized"||r.length>0)&&t.push({path:n,missing:r})}s(oP,"report");function TH(e,n){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.id=="string")return t.id;if(typeof t.key=="string")return t.key}return String(n)}s(TH,"keyOf");function bp(e,n){return e==="not-localized"?n==="de"?"ist kein zweisprachiger Text ({ de, en })":"is not a bilingual text ({ de, en })":e==="legacy-twin"?n==="de"?'ist ein Zwilling der alten Form \u2014 der Text geh\xF6rt in das Feld ohne \u201Elocalized"':'is a twin of the old shape \u2014 the text belongs in the field without "localized"':n==="de"?`fehlt in: ${e.join(", ")}`:`is missing in: ${e.join(", ")}`}s(bp,"describe");function Bw({path:e,missing:n}){return n==="legacy-twin"?{de:`[i18n/legacyTwin] ${e} ${bp(n,"de")}.`,en:`[i18n/legacyTwin] ${e} ${bp(n,"en")}.`}:{de:`[i18n/missingTranslation] ${e} ${bp(n,"de")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch; die Sprache folgt dem Konto des Lesenden.`,en:`[i18n/missingTranslation] ${e} ${bp(n,"en")} \u2014 every displayed text needs German and English; the language follows the reader's account.`}}s(Bw,"unlocalizedTextReason");var $H={engagePush:["engage"]};function RH(e){let n=$H[e.type];return n===void 0?e:Object.fromEntries(Object.entries(e).filter(([t])=>!n.includes(t)))}s(RH,"withoutMachineData");function sP(e,n){return[...vp(e.nodes.map(RH),"nodes"),...n===void 0?[]:vp(n,`layout.${n.id}`)].map(r=>({layer:"GRAPH",kind:"i18n",path:r.path,reason:Bw(r),severity:"error"}))}s(sP,"checkLocalizedTexts");var Lo=5,Mo=480;function di(e){return typeof e=="string"&&e.trim().length>0}s(di,"isNonEmptyString");function lP(e,n,t){return Object.keys(e).filter(r=>!n.includes(r)).map(r=>({field:`result.${r}`,code:Ue.unknownField,message:{de:`Unbekanntes Feld '${r}' im ${t.de}; erlaubt sind: ${n.join(", ")}.`,en:`Unknown field '${r}' in the ${t.en}; allowed: ${n.join(", ")}.`}}))}s(lP,"unknownFieldIssues");function IH(e){let n=[],t=e.title;(t===void 0||typeof t!="object"||t===null||!di(t.de)||!di(t.en))&&n.push({field:"result.title",code:Ue.appointmentMissingTitle,message:{de:"Ein Termin-Ergebnis braucht einen neutralen Titel in beiden Sprachen ({ de, en }) \u2014 er steht in der Mail und in der Kalenderdatei der Familie, deshalb nie ein Familienname.",en:"An appointment result needs a neutral title in both languages ({ de, en }) \u2014 it appears in the email and in the family's calendar file, so never a family name."}});let r=e.durationMinutes;return(typeof r!="number"||!Number.isInteger(r)||r<Lo||r>Mo)&&n.push({field:"result.durationMinutes",code:Ue.appointmentInvalidDuration,message:{de:`'durationMinutes' muss eine ganze Zahl von ${Lo} bis ${Mo} sein, erhalten ${JSON.stringify(r)}.`,en:`'durationMinutes' must be a whole number from ${Lo} to ${Mo}, got ${JSON.stringify(r)}.`}}),n.push(...lP(e,["kind","title","durationMinutes","primaryHostTeams","participants"],{de:"Termin-Ergebnis",en:"appointment result"})),n}s(IH,"appointmentIssues");function aP(e){if(typeof e!="object"||e===null)return!1;let n=e;return di(n.de)&&di(n.en)}s(aP,"isBilingual");var Uw=["key","type","label","writes","options","min","suggest","evidence","evidenceFrom","multiple","tasks","maxLength"];function OH(e,n){let t=s((o,a)=>({field:o,code:Ue.recordFields,message:a}),"issue");if(!Array.isArray(e)||e.length===0)return[t("result.fields",{de:"Eine Erfassung braucht mindestens ein Feld ('result.fields').",en:"A record needs at least one field ('result.fields')."})];let r=[],i=new Set;for(let[o,a]of e.entries()){let l=`result.fields[${o}]`;if(typeof a!="object"||a===null||Array.isArray(a)){r.push(t(l,{de:"Ein Feld der Erfassung muss ein Objekt sein.",en:"A field of the record must be an object."}));continue}let d=a,c=d.key;typeof c!="string"||!/^[a-z][a-zA-Z0-9_]*$/.test(c)?r.push(t(`${l}.key`,{de:`Feld-Schl\xFCssel ${JSON.stringify(c)} \u2014 erlaubt sind Buchstaben, Ziffern und _, beginnend mit einem Kleinbuchstaben.`,en:`Field key ${JSON.stringify(c)} \u2014 letters, digits and _ are allowed, starting with a lowercase letter.`})):i.has(c)?r.push(t(`${l}.key`,{de:`Feld-Schl\xFCssel "${c}" ist doppelt.`,en:`Field key "${c}" is duplicated.`})):i.add(c);let u=typeof c=="string"?`"${c}"`:`Nr. ${o+1}`,p=typeof c=="string"?`"${c}"`:`no. ${o+1}`;if(Dy(d.type)||r.push(t(`${l}.type`,{de:`Feld ${u}: Typ ${JSON.stringify(d.type)} \u2014 erlaubt: ${Nf.join(", ")}.`,en:`Field ${p}: type ${JSON.stringify(d.type)} \u2014 allowed: ${Nf.join(", ")}.`})),aP(d.label)||r.push(t(`${l}.label`,{de:`Feld ${u} braucht ein Label in beiden Sprachen ({ de, en }).`,en:`Field ${p} needs a label in both languages ({ de, en }).`})),di(d.writes)||r.push(t(`${l}.writes`,{de:`Feld ${u} schreibt in keinen Vorgangs-Schl\xFCssel ('writes') \u2014 ein Wert, den niemand lesen kann, geh\xF6rt nicht in eine Erfassung.`,en:`Field ${p} writes to no process key ('writes') \u2014 a value nobody can read does not belong in a record.`})),d.type==="enum"){let y=Array.isArray(d.options)?d.options:[],k=y.map(w=>w.key);(y.length<2||k.some(w=>typeof w!="string"||w.length===0)||new Set(k).size!==k.length||y.some(w=>!aP(w.label)))&&r.push(t(`${l}.options`,{de:`Feld ${u} (Auswahl) braucht mindestens 2 Optionen mit eindeutigen Schl\xFCsseln und Labels in beiden Sprachen.`,en:`Field ${p} (choice) needs at least 2 options with unique keys and labels in both languages.`}))}else d.options!==void 0&&r.push(t(`${l}.options`,{de:`Feld ${u}: 'options' gibt es nur bei Typ 'enum'.`,en:`Field ${p}: 'options' exists only for type 'enum'.`}));if(d.min!==void 0&&(d.type!=="number"||typeof d.min!="number"||!Number.isInteger(d.min))&&r.push(t(`${l}.min`,{de:`Feld ${u}: 'min' gibt es nur bei Typ 'number', als ganze Zahl.`,en:`Field ${p}: 'min' exists only for type 'number', as a whole number.`})),d.evidence!==void 0&&typeof d.evidence!="boolean"&&r.push(t(`${l}.evidence`,{de:`Feld ${u}: 'evidence' ist true oder false.`,en:`Field ${p}: 'evidence' is true or false.`})),d.evidenceFrom!==void 0){let y=typeof d.min=="number"?d.min:0;(d.type!=="number"||d.evidence!==!0||typeof d.evidenceFrom!="number"||!Number.isInteger(d.evidenceFrom)||d.evidenceFrom<=y)&&r.push(t(`${l}.evidenceFrom`,{de:`Feld ${u}: 'evidenceFrom' gibt es nur bei Typ 'number' mit 'evidence', als ganze Zahl \xFCber dem Minimum (${y}) \u2014 sonst g\xE4lte der Nachweis immer.`,en:`Field ${p}: 'evidenceFrom' exists only for type 'number' with 'evidence', as a whole number above the minimum (${y}) \u2014 otherwise the proof would always apply.`}))}if(r.push(..._H(d,l,u,p,n)),d.suggest!==void 0){let y=d.suggest,k=typeof y=="object"&&y!==null?y.kind:void 0,w=k==="form"&&"address"in y&&Object.keys(y).length===2&&(!be(y.address)||un(y.address))||k==="siblingRank"&&Object.keys(y).length===1&&d.type==="number";aO(d.type)?w||r.push({field:`${l}.suggest`,code:Ue.recordSuggest,message:{de:`Feld ${u}: Vorschlag ${JSON.stringify(d.suggest)} \u2014 erlaubt: { kind: 'form', address: '$node.<formular>.admission.<export>' } oder { kind: 'siblingRank' } (nur bei Typ 'number'); bekannte Arten: ${Fy.join(", ")}.`,en:`Field ${p}: suggestion ${JSON.stringify(d.suggest)} \u2014 allowed: { kind: 'form', address: '$node.<form>.admission.<export>' } or { kind: 'siblingRank' } (only for type 'number'); known kinds: ${Fy.join(", ")}.`}}):r.push({field:`${l}.suggest`,code:Ue.recordSuggest,message:{de:`Feld ${u}: einen Vorschlag gibt es nur bei Typ number, boolean oder enum.`,en:`Field ${p}: a suggestion exists only for type number, boolean or enum.`}})}let h=Object.keys(d).filter(y=>!Uw.includes(y));h.length>0&&r.push(t(l,{de:`Feld ${u}: unbekannte Angabe ${h.map(y=>`'${y}'`).join(", ")}; erlaubt: ${Uw.join(", ")}.`,en:`Field ${p}: unknown entry ${h.map(y=>`'${y}'`).join(", ")}; allowed: ${Uw.join(", ")}.`}))}return r}s(OH,"recordFieldIssues");function _H(e,n,t,r,i){let o=[],a=e.maxLength;if(a!==void 0&&(e.type!=="text"||typeof a!="number"||!Number.isInteger(a)||a<1||a>Pf)&&o.push({field:`${n}.maxLength`,code:Ue.recordText,message:{de:`Feld ${t}: 'maxLength' gibt es nur bei Typ 'text', als ganze Zahl von 1 bis ${Pf}.`,en:`Field ${r}: 'maxLength' exists only for type 'text', as a whole number from 1 to ${Pf}.`}}),e.multiple!==void 0&&(e.type!=="person"||typeof e.multiple!="boolean")&&o.push({field:`${n}.multiple`,code:Ue.recordPerson,message:{de:`Feld ${t}: 'multiple' gibt es nur bei Typ 'person', als true oder false.`,en:`Field ${r}: 'multiple' exists only for type 'person', as true or false.`}}),e.type!=="assignment")return e.tasks!==void 0&&o.push({field:`${n}.tasks`,code:Ue.recordAssignment,message:{de:`Feld ${t}: 'tasks' gibt es nur bei Typ 'assignment'.`,en:`Field ${r}: 'tasks' exists only for type 'assignment'.`}}),o;let l=e.tasks;if(!Array.isArray(l)||l.length===0||l.some(d=>typeof d!="string"||d.length===0)||new Set(l).size!==l.length)return o.push({field:`${n}.tasks`,code:Ue.recordAssignment,message:{de:`Feld ${t} (Zuordnung) braucht in 'tasks' mindestens eine Aufgabe, jede einmal.`,en:`Field ${r} (assignment) needs at least one task in 'tasks', each once.`}}),o;if(i.nodeTasks===void 0)return o;for(let d of l){let c=i.nodeTasks.get(d);c?.feedback!==!0&&o.push({field:`${n}.tasks`,code:Ue.recordAssignment,message:c===void 0?{de:`Feld ${t}: "${d}" ist keine Aufgabe dieses Knotens.`,en:`Field ${r}: "${d}" is no task of this node.`}:{de:`Feld ${t}: "${d}" ist keine Feedback-Aufgabe ('feedback: true') \u2014 zugeordnet wird nur, wer eine R\xFCckmeldung gibt.`,en:`Field ${r}: "${d}" is no feedback task ('feedback: true') \u2014 only a person who gives feedback is assigned.`}})}return o}s(_H,"typedFieldIssues");function NH(e,n,t){let r=[],i=n.options;if(e==="choice"){let o=Array.isArray(i)?i:[],a=o.map(l=>l.key);(o.length<2||a.some(l=>typeof l!="string"||l.length===0)||new Set(a).size!==a.length)&&r.push({field:"result.options",code:Ue.choiceOptions,message:{de:`Ein Auswahl-Ergebnis braucht mindestens 2 Optionen mit eindeutigen Schl\xFCsseln, erhalten ${JSON.stringify(a)}.`,en:`A choice result needs at least 2 options with unique keys, got ${JSON.stringify(a)}.`}})}else i!==void 0&&r.push({field:"result.options",code:Ue.choiceOptions,message:{de:`'result.options' gibt es nur bei 'choice' \u2014 ${e==="recommendation"?"eine Empfehlung hat die festen Tendenzen Positiv/Neutral/Negativ":"ein Freitext hat keine Auswahl"}.`,en:`'result.options' exists only for 'choice' \u2014 ${e==="recommendation"?"a recommendation has the fixed leanings Positive/Neutral/Negative":"a free text has no choice"}.`}});if(e==="pricedItem"){let o=n.item;if(!di(o))r.push({field:"result.item",code:Ue.pricedItemMissingItem,message:{de:"Ein Preispositions-Ergebnis nennt den Artikel, den es bepreist \u2014 'result.item' (der Schl\xFCssel des Artikels, z. B. 'tuition') fehlt.",en:"A priced-item result names the article it prices \u2014 'result.item' (the article's key, e.g. 'tuition') is missing."}});else if(t.billingItemKeys!==void 0&&!t.billingItemKeys.has(o))r.push({field:"result.item",code:Ue.pricedItemUnknownItem,message:{de:`'result.item' "${o}" \u2014 kein Artikel dieses Mandanten tr\xE4gt diesen Schl\xFCssel (bekannt: ${[...t.billingItemKeys].join(", ")||"keine"}).`,en:`'result.item' "${o}" \u2014 no article of this school has this key (known: ${[...t.billingItemKeys].join(", ")||"none"}).`}});else if(t.offerProgram===null)r.push({field:"result.item",code:Ue.pricedItemOfferWithoutProgram,message:{de:`'result.item' "${o}" \u2014 das Angebot ist keinem Programm zugeordnet, also geh\xF6rt kein Artikel zu ihm; dem Angebot ein Programm geben.`,en:`'result.item' "${o}" \u2014 the offer is not assigned to a program, so no article belongs to it; give the offer a program.`}});else if(t.offerProgram!==void 0&&!t.offerProgram.billingItemKeys.has(o)){let l=t.offerProgram;r.push({field:"result.item",code:Ue.pricedItemNotInProgram,message:{de:`'result.item' "${o}" \u2014 der Artikel ist dem Programm \u201E${l.nameDe}\u201C des Angebots nicht zugeordnet (zugeordnet: ${[...l.billingItemKeys].join(", ")||"keine"}); unter Finanzen \u2192 Artikel zuordnen, direkt oder \xFCber ein Paket.`,en:`'result.item' "${o}" \u2014 the article is not assigned to the offer's program "${l.nameDe}" (assigned: ${[...l.billingItemKeys].join(", ")||"none"}); assign it under Finance \u2192 articles, directly or through a package.`}})}let a=n.label;(typeof a!="object"||a===null||!di(a.de)||!di(a.en))&&r.push({field:"result.label",code:Ue.labelMissing,message:{de:"Ein Preispositions-Ergebnis braucht einen Namen f\xFCr seinen Wert in beiden Sprachen ('result.label', z. B. { de: 'Schulgeld mit Erm\xE4\xDFigung', en: 'Tuition after reduction' }) \u2014 so hei\xDFt er im Workflow und in der Verdrahtung.",en:"A priced-item result needs a name for its value in both languages ('result.label', e.g. { de: 'Schulgeld mit Erm\xE4\xDFigung', en: 'Tuition after reduction' }) \u2014 that is what it is called in the workflow and in the wiring."}})}else n.item!==void 0&&r.push({field:"result.item",code:Ue.itemOnNonPricedItem,message:{de:`'result.item' gibt es nur bei 'pricedItem' \u2014 ein ${e}-Ergebnis bepreist keinen Artikel.`,en:`'result.item' exists only for 'pricedItem' \u2014 a ${e} result prices no article.`}});if(e==="record"?(r.push(...OH(n.fields,t)),n.writes!==void 0&&r.push({field:"result.writes",code:Ue.writesOnProse,message:{de:"Eine Erfassung schreibt je Feld ('fields[].writes'), nie als Ganzes ('result.writes').",en:"A record writes per field ('fields[].writes'), never as a whole ('result.writes')."}}),n.label!==void 0&&r.push({field:"result.label",code:Ue.unknownField,message:{de:"Eine Erfassung benennt ihre Werte je Feld ('fields[].label'), nicht als Ganzes ('result.label').",en:"A record names its values per field ('fields[].label'), not as a whole ('result.label')."}})):n.fields!==void 0&&r.push({field:"result.fields",code:Ue.fieldsOnNonRecord,message:{de:`'result.fields' gibt es nur bei 'record' \u2014 ein ${e}-Ergebnis hat keine Felder.`,en:`'result.fields' exists only for 'record' \u2014 a ${e} result has no fields.`}}),e==="reduction"&&(di(n.writes)||r.push({field:"result.writes",code:Ue.reductionPrices,message:{de:"Eine Reduktion schreibt ihren Betrag in einen Vorgangs-Schl\xFCssel vom Typ reduction ('result.writes') \u2014 sonst l\xE4se ihn kein Preis.",en:"A reduction writes its amount to a process key of type reduction ('result.writes') \u2014 otherwise no price would read it."}})),n.writes!==void 0&&(e==="freetext"||e==="recommendation")&&r.push({field:"result.writes",code:Ue.writesOnProse,message:{de:`'result.writes' gibt es nur bei Ergebnissen mit Wert (Auswahl, Preisposition) \u2014 ein ${e}-Ergebnis bleibt im Chat und schreibt nichts in den Vorgang.`,en:`'result.writes' exists only for results with a value (choice, priced item) \u2014 a ${e} result stays in the chat and writes nothing to the process.`}}),e==="freetext"&&n.textRequired!==void 0&&r.push({field:"result.textRequired",code:Ue.textRequiredOnFreetext,message:{de:"'textRequired' auf einem Freitext-Ergebnis \u2014 der Text eines Freitexts ist immer Pflicht; die Angabe entfernen.",en:"'textRequired' on a free-text result \u2014 the text of a free text is always required; remove the entry."}}),n.chat===void 0)r.push({field:"result.chat",code:Ue.chatMissing,message:{de:"Ein Aufgaben-Ergebnis steht nur im Chat \u2014 'result.chat' fehlt: 'all', 'team:<Gruppe>' oder einen Kanal des Workflows angeben.",en:"A task result appears only in the chat \u2014 'result.chat' is missing: give 'all', 'team:<group>' or a channel of the workflow."}});else{let o=n.chat,a=typeof o=="string"?Ms(o):null;o==="external"||a===null?r.push({field:"result.chat",code:Ue.chatExternal,message:{de:`'result.chat' ${JSON.stringify(o)} \u2014 ein Aufgaben-Ergebnis bleibt intern: erlaubt sind 'all', 'team:<Gruppe>' oder ein Kanal des Workflows, nie 'external'.`,en:`'result.chat' ${JSON.stringify(o)} \u2014 a task result stays internal: 'all', 'team:<group>' or a channel of the workflow are allowed, never 'external'.`}}):a.kind==="channel"&&!t.channelKeys.has(a.channelKey)&&r.push({field:"result.chat",code:Ue.chatUnknownChannel,message:{de:`'result.chat' "${a.channelKey}" ist weder 'all' noch 'team:<Gruppe>' noch ein Kanal des Workflows (bekannt: ${[...t.channelKeys].join(", ")||"keine"}).`,en:`'result.chat' "${a.channelKey}" is neither 'all' nor 'team:<group>' nor a channel of the workflow (known: ${[...t.channelKeys].join(", ")||"none"}).`}})}return r.push(...lP(n,["kind","options","textRequired","chat","item","label","writes","fields","prices"],{de:"Aufgaben-Ergebnis",en:"task result"})),r}s(NH,"recordedIssues");function dP(e,n,t={channelKeys:new Set}){if(n===void 0)return[];if(e!=="task")return[{field:"result",code:Ue.onApproval,message:{de:`'result' gilt nur f\xFCr die Art 'task' \u2014 eine '${e}' wird durch ihr Votum abgeschlossen, nicht durch ein Ergebnis.`,en:`'result' applies only to the kind 'task' \u2014 an '${e}' is completed by its vote, not by a result.`}}];if(typeof n!="object"||n===null||Array.isArray(n))return[{field:"result",code:Ue.unknownKind,message:{de:`'result' muss ein Objekt mit 'kind' sein; bekannte Arten: ${Fs.join(", ")}.`,en:`'result' must be an object with 'kind'; known kinds: ${Fs.join(", ")}.`}}];let r=n;return sO(r.kind)?r.kind==="appointment"?IH(r):NH(r.kind,r,t):[{field:"result.kind",code:Ue.unknownKind,message:{de:`Unbekannte Ergebnisart ${JSON.stringify(r.kind)}; bekannte Arten: ${Fs.join(", ")}.`,en:`Unknown result kind ${JSON.stringify(r.kind)}; known kinds: ${Fs.join(", ")}.`}}]}s(dP,"taskResultIssues");var Gw=60;function ci(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"error"}}s(ci,"error");function PH(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"warning"}}s(PH,"warning");function cP(e){return Array.isArray(e.tasks)?e.tasks:[]}s(cP,"tasksOf");function fP(e,n){return(Array.isArray(e.optionalActions)?e.optionalActions:[]).filter(r=>r.action==="spawnTasks"&&Array.isArray(r.tasks)&&r.tasks.includes(n))}s(fP,"spawnActionsOf");function uP(e,n){return fP(e,n).map(t=>String(t.key)).sort()}s(uP,"bindingsOf");function pP(e,n){let t=[],r=cP(e),i=new Map;for(let o of r){if(o.appointment===void 0)continue;let a=typeof o.key=="string"?o.key:"?",l=`nodes.${e.id}.tasks.${a}`,d={de:`Terminaufgabe "${a}" (Knoten "${e.id}")`,en:`Appointment task "${a}" (node "${e.id}")`},c=o.appointment,p=typeof c=="object"&&c!==null&&Object.keys(c).every(P=>P==="of"||P==="dueDaysAfterEnd")&&typeof c.of=="string"?c.of:void 0,h=p===void 0?void 0:r.find(P=>P.key===p),y=h?.result;if(p===void 0||h===void 0||y?.kind!=="appointment")t.push(ci(`${l}.appointment.of`,{de:`[workItems/appointmentOfUnknown] ${d.de} braucht 'appointment: { of, dueDaysAfterEnd }', und 'of' nennt eine Aufgabe desselben Knotens, die mit einem Termin abschlie\xDFt (result.kind 'appointment'); erhalten ${JSON.stringify(o.appointment)}.`,en:`[workItems/appointmentOfUnknown] ${d.en} needs 'appointment: { of, dueDaysAfterEnd }', and 'of' names a task of the same node that ends with an appointment (result.kind 'appointment'); got ${JSON.stringify(o.appointment)}.`}));else{i.set(p,(i.get(p)??0)+1);let P=h.blocks,F=[...["when","optional"].filter(b=>h[b]!==void 0),...typeof P?.node=="string"&&P.node!==e.id?["blocks"]:[]];F.length>0&&t.push(ci(`nodes.${e.id}.tasks.${p}.${F[0]}`,{de:`[workItems/appointmentTaskShape] "${p}" bucht den Termin f\xFCr ${d.de} und tr\xE4gt ${F.map(b=>b==="blocks"?"ein knoten\xFCbergreifendes 'blocks'":`'${b}'`).join(", ")} \u2014 fiele sie ohne Buchung weg oder \xFCberlebte sie ihren Knoten, wartete die Terminaufgabe f\xFCr immer bzw. f\xE4nde die Buchung keine Terminaufgabe mehr.`,en:`[workItems/appointmentTaskShape] "${p}" books the appointment for ${d.en} and carries ${F.map(b=>b==="blocks"?"a cross-node 'blocks'":`'${b}'`).join(", ")} \u2014 if it dropped out without a booking or outlived its node, the appointment task would wait forever or the booking would find no appointment task any more.`}));for(let b of fP(e,p))b.repeatable!==!0&&t.push(ci(`nodes.${e.id}.optionalActions.${String(b.key)}.repeatable`,{de:`[workItems/appointmentActionRepeatable] Die optionale Aktion "${String(b.key)}" legt "${p}" an, die den Termin f\xFCr ${d.de} bucht, und ist nicht 'repeatable: true'. Eine Absage beendet die Runde; ohne zweite Runde lie\xDFe sich die Aktion nie wieder ausl\xF6sen, und eine Entscheidung, die auf sie wartet (requiresOneOf), bliebe h\xE4ngen.`,en:`[workItems/appointmentActionRepeatable] The optional action "${String(b.key)}" creates "${p}", which books the appointment for ${d.en}, and is not 'repeatable: true'. A cancellation ends the round; without a second round the action could never be triggered again, and a decision waiting for it (requiresOneOf) would hang.`}));uP(e,a).join(",")!==uP(e,p).join(",")&&t.push(ci(`${l}.appointment.of`,{de:`[workItems/appointmentTaskBinding] ${d.de} geh\xF6rt zu anderen optionalen Aktionen als "${p}", die ihren Termin bucht \u2014 beide Zeilen sind eine Runde: entweder beide in derselben Aktion (spawnTasks) oder beide in keiner.`,en:`[workItems/appointmentTaskBinding] ${d.en} belongs to different optional actions than "${p}", which books its appointment \u2014 both rows are one round: either both in the same action (spawnTasks) or both in none.`}))}let k=c?.dueDaysAfterEnd;(typeof k!="number"||!Number.isInteger(k)||k<0||k>Gw)&&t.push(ci(`${l}.appointment.dueDaysAfterEnd`,{de:`[workItems/appointmentTaskDue] ${d.de}: 'dueDaysAfterEnd' ist eine ganze Zahl von 0 bis ${Gw} \u2014 die Tage nach dem Terminende, bis die Aufgabe f\xE4llig ist; erhalten ${JSON.stringify(k)}.`,en:`[workItems/appointmentTaskDue] ${d.en}: 'dueDaysAfterEnd' is a whole number from 0 to ${Gw} \u2014 the days after the appointment ends until the task is due; got ${JSON.stringify(k)}.`})),o.params?.dueInDays!==void 0&&t.push(ci(`${l}.params.dueInDays`,{de:`[workItems/appointmentTaskDue] ${d.de} tr\xE4gt 'params.dueInDays' neben 'appointment.dueDaysAfterEnd' \u2014 eine Terminaufgabe ist ab dem Terminende f\xE4llig, nie ab ihrer Anlage.`,en:`[workItems/appointmentTaskDue] ${d.en} carries 'params.dueInDays' next to 'appointment.dueDaysAfterEnd' \u2014 an appointment task is due from the end of the appointment, never from its creation.`}));let w=o.result,v=["when","optional","familyRequest","reads","locksEvidence"].filter(P=>o[P]!==void 0).map(P=>`'${P}'`),A=typeof o.blocks?.node=="string"&&o.blocks.node!==e.id,E=s(P=>[...o.kind!=="task"?["'kind: approval'"]:[],...w===void 0||!Mi(w.kind)?[P==="de"?"kein erfasstes Ergebnis (Feedback)":"no recorded result (feedback)"]:[],...v,...A?[P==="de"?"ein knoten\xFCbergreifendes 'blocks'":"a cross-node 'blocks'"]:[]],"shapeFaults");E("de").length>0&&t.push(ci(`${l}.appointment`,{de:`[workItems/appointmentTaskShape] ${d.de}: ${E("de").join(", ")} \u2014 eine Terminaufgabe ist eine Aufgabe, die mit ihrem Feedback (Freitext, Empfehlung, Auswahl) abschlie\xDFt, und sie entsteht, weil der Termin entsteht: ohne Bedingung, nicht optional, keine Nachforderung, ohne Belege (nichts l\xE4sst sie ungebunden neu entstehen) und an ihrem Knoten.`,en:`[workItems/appointmentTaskShape] ${d.en}: ${E("en").join(", ")} \u2014 an appointment task is a task that ends with its feedback (free text, recommendation, choice), and it exists because the appointment exists: no condition, not optional, no follow-up request, no evidence (nothing lets it be created again unbound) and on its own node.`}));let R=o.result?.chat;typeof R=="string"&&R.startsWith("team:")&&t.push(PH(`${l}.result.chat`,{de:`[workItems/appointmentChatUnreadable] ${d.de} schreibt ihr Feedback in "${R}" \u2014 Gastgeberin bzw. Gastgeber kann jede Mitarbeiterin und jeder Mitarbeiter sein und liest das eigene Feedback dort nur als Mitglied dieses Teams. 'all' w\xE4hlen, damit jede Gastgeberin bzw. jeder Gastgeber es liest.`,en:`[workItems/appointmentChatUnreadable] ${d.en} writes its feedback to "${R}" \u2014 any staff member can be the host and reads their own feedback there only as a member of that team. Choose 'all' so every host reads it.`}));for(let P of n)for(let F of cP(P)){let b=F.blocks;b?.templateKey!==a||(typeof b.node=="string"?b.node:P.id)!==e.id||t.push(ci(`nodes.${P.id}.tasks.${String(F.key)}.blocks.templateKey`,{de:`[workItems/appointmentTaskBlocked] Task "${String(F.key)}" (Knoten "${P.id}") h\xE4lt ${d.de} zur\xFCck \u2014 eine Terminaufgabe wartet nur auf ihren Termin (abgeleitet aus 'appointment.of'); ein 'blocks' auf sie entf\xE4llt.`,en:`[workItems/appointmentTaskBlocked] Task "${String(F.key)}" (node "${P.id}") holds back ${d.en} \u2014 an appointment task only waits for its appointment (derived from 'appointment.of'); a 'blocks' on it is dropped.`}))}}for(let[o,a]of i)a<2||t.push(ci(`nodes.${e.id}.tasks.${o}`,{de:`[workItems/appointmentOfTwice] ${a} Terminaufgaben auf Knoten "${e.id}" geh\xF6ren zum Termin von "${o}" \u2014 ein Termin hat eine Terminaufgabe.`,en:`[workItems/appointmentOfTwice] ${a} appointment tasks on node "${e.id}" belong to the appointment of "${o}" \u2014 an appointment has one appointment task.`}));return t}s(pP,"appointmentTaskIssues");var CH="optionalAction:";function mP(e){return`${CH}${e}:trigger`}s(mP,"optionalActionTriggerActionId");var DH="processDecide";function hP(e){let n=e.optionalActions;return n==null?[]:(Array.isArray(n)||L(`[optionalAction/corrupt-section] node's 'optionalActions' is ${typeof n}, not an array \u2014 corrupt pinned graph (publish stores the section as authored)`),n)}s(hP,"optionalActionBindings");function gP(e){return hP(e).map(n=>({id:mP(n.key),kind:"internal",label:n.label,surface:DH,placement:"overflow",superUserOnly:!0}))}s(gP,"optionalActionTriggers");function yP(e){let n=e.tasks;return Array.isArray(n)?n:[]}s(yP,"authoredTemplates");function wP(e){let n=e?.result;return n?.kind!=="appointment"?[]:n.participants?.feedback?.tasks??[]}s(wP,"personTasksOf");function zw(e){let n=yP(e);return hP(e).map(t=>{let r=new Set(t.tasks??[]),i=new Set;for(let o of r)for(let a of wP(n.find(l=>l.key===o)))i.add(a);return{binding:t,tasks:r,personTasks:i,keys:new Set([...r,...i])}})}s(zw,"optionalActionMembership");function FH(e){let n=new Set;for(let t of yP(e))for(let r of wP(t))n.add(r);return n}s(FH,"personRowTemplateKeys");function kP(e){let n=new Set(FH(e));for(let{keys:t}of zw(e))for(let r of t)n.add(r);return n}s(kP,"referencedTaskTemplateKeys");var br={shape:"[taskInput/shape]",notInRound:"[taskInput/notInRound]",notRecord:"[taskInput/notRecord]",prefillNotDeclared:"[taskInput/prefillNotDeclared]",prefillType:"[taskInput/prefillType]",feedbackTasks:"[appointment/feedbackTasks]",feedbackOptional:"[appointment/feedbackOptional]",recordAssignment:"[taskResult/recordAssignment]"},Ww=60;function ui(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:`${n} ${t.de}`,en:`${n} ${t.en}`},severity:"error"}}s(ui,"error");function ca(e){return Array.isArray(e.tasks)?e.tasks:[]}s(ca,"tasksOf");function LH(e){return(Array.isArray(e.optionalActions)?e.optionalActions:[]).filter(t=>t.action==="spawnTasks")}s(LH,"spawnBindingsOf");function Xl(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}s(Xl,"stringList");function qr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}s(qr,"record");function Yw(e){let n=qr(e?.result);return n?.kind==="appointment"?qr(n.participants):null}s(Yw,"participantsOf");function bP(e){return Xl(qr(Yw(e)?.feedback)?.tasks)}s(bP,"feedbackTasksOf");function vP(e,n){return zw(e).find(t=>t.keys.has(n))}s(vP,"roundOf");function MH(e,n,t){let r=s(u=>({code:br.notInRound,reason:u}),"notInRound"),i=vP(e,n);if(i===void 0)return r({de:`Aufgabe "${n}" geh\xF6rt zu keiner optionalen Aktion \u2014 Vorgaben liest nur eine Aufgabe einer Runde.`,en:`Task "${n}" belongs to no optional action \u2014 only a task of a round reads inputs.`});if(t.scope!=="task"||t.path!==void 0)return r({de:`${ue(t)} ist kein Wert einer Aufgabe ($task.<aufgabe>.<schl\xFCssel>).`,en:`${ue(t)} is no value of a task ($task.<task>.<key>).`});let{binding:o}=i,a=t.owner;if(a===n)return r({de:`Aufgabe "${n}" liest ihren eigenen Wert.`,en:`Task "${n}" reads its own value.`});let l=ca(e).find(u=>u.key===a),d=qr(l?.blocks),c=i.tasks.has(a)&&d?.templateKey===n&&(d.node===void 0||d.node===e.id);return a!==o.input&&!c?r({de:`"${a}" ist weder die Eingabe der Aktion "${o.key}" noch eine ihrer Aufgaben, die "${n}" per 'blocks' zur\xFCckh\xE4lt \u2014 der Wert st\xFCnde nicht fest, wenn die Aufgabe \xF6ffnet.`,en:`"${a}" is neither the input of the action "${o.key}" nor one of its tasks that holds "${n}" through 'blocks' \u2014 the value would not be settled when the task opens.`}):qr(l?.result)?.kind!=="record"?{code:br.notRecord,reason:{de:`"${a}" hat kein Ergebnis vom Typ 'record' \u2014 Vorgaben sind Felder einer Eingabe.`,en:`"${a}" has no result of kind 'record' \u2014 inputs are fields of an input task.`}}:null}s(MH,"taskInputRefusal");function qH(e,n){if(n.scope!=="task")return;let t=ca(e).find(i=>i.key===n.owner),r=qr(t?.result);if(r?.kind==="record")return(Array.isArray(r.fields)?r.fields:[]).map(qr).find(i=>i?.writes===n.key)??void 0}s(qH,"writerField");function KH(e,n,t){let r=String(n.key);if(n.inputs===void 0)return[];if(!Array.isArray(n.inputs))return[ui(`${t}.inputs`,br.shape,{de:"'inputs' ist eine Liste von Adressen.",en:"'inputs' is a list of addresses."})];let i=[],o=new Set;for(let[a,l]of n.inputs.entries()){if(!be(l))continue;let d=ue(l);if(o.has(d)){i.push(ui(`${t}.inputs.${a}`,br.shape,{de:`${d} steht zweimal in 'inputs'.`,en:`${d} is listed twice in 'inputs'.`}));continue}o.add(d);let c=MH(e,r,l);c!==null&&i.push(ui(`${t}.inputs.${a}`,c.code,c.reason))}return i}s(KH,"inputIssues");function jH(e,n,t,r){let o=Yw(t)?.prefill;if(o===void 0)return[];let a=`${r}.result.participants.prefill`,l=Array.isArray(t.inputs)?t.inputs.filter(be).map(ue):[];if(!be(o)||!l.includes(ue(o)))return[ui(a,br.prefillNotDeclared,{de:"Die Vorbelegung der Teilnehmenden ist keine der Vorgaben ('inputs') der Aufgabe.",en:"The participants' prefill is none of the task's inputs ('inputs')."})];let d=bP(t),c=_l(e,o);if(c===void 0)return[];if(tt(c)==="staffUser")return d.length===1?[]:[ui(a,br.prefillType,{de:"Eine Personenliste belegt nur vor, wenn 'feedback.tasks' genau eine Feedback-Art nennt \u2014 sonst w\xE4re offen, wer welche Art gibt.",en:"A list of persons prefills only when 'feedback.tasks' names exactly one feedback kind \u2014 otherwise who gives which kind would be open."})];if(c==="taskAssignment"){let h=Xl(qH(n,o)?.tasks).filter(y=>!d.includes(y));return h.length===0?[]:[ui(a,br.prefillType,{de:`Die Zuordnung ordnet ${h.map(y=>`"${y}"`).join(", ")} zu, die 'feedback.tasks' nicht nennt.`,en:`The assignment assigns ${h.map(y=>`"${y}"`).join(", ")}, which 'feedback.tasks' does not name.`})]}return[ui(a,br.prefillType,{de:`Vorbelegt werden Teilnehmende nur aus Personen ('person') oder einer Zuordnung ('assignment'), nicht aus "${c}".`,en:`Participants are prefilled only from persons ('person') or an assignment ('assignment'), not from "${c}".`})]}s(jH,"prefillIssues");function VH(e,n,t){let r=Yw(n);if(r===null||r.feedback===void 0)return[];let i=String(n.key),o=`${t}.result.participants.feedback`,a=qr(r.feedback),l=a?.tasks,d=[],c=s((y,k,w=br.feedbackTasks)=>d.push(ui(y,w,k)),"fail");if(!Array.isArray(l)||l.length===0||l.some(y=>typeof y!="string")||new Set(l).size!==l.length)return c(`${o}.tasks`,{de:"'feedback.tasks' nennt mindestens eine Feedback-Aufgabe, jede einmal.",en:"'feedback.tasks' names at least one feedback task, each once."}),d;let u=a?.dueDaysAfterEnd;(typeof u!="number"||!Number.isInteger(u)||u<0||u>Ww)&&c(`${o}.dueDaysAfterEnd`,{de:`'feedback.dueDaysAfterEnd' ist eine ganze Zahl von 0 bis ${Ww}.`,en:`'feedback.dueDaysAfterEnd' is a whole number from 0 to ${Ww}.`});let p=LH(e);p.some(y=>Xl(y.tasks).includes(i))||c(o,{de:`Aufgabe "${i}" legt Personenzeilen an, geh\xF6rt aber zu keiner optionalen Aktion \u2014 Personenzeilen geh\xF6ren zur Runde einer Aktion.`,en:`Task "${i}" creates person rows but belongs to no optional action \u2014 person rows belong to an action's round.`});let h=new Map(ca(e).map(y=>[y.key,y]));for(let y of l){let k=h.get(y),w=`${o}.tasks`;if(k===void 0){c(w,{de:`"${y}" ist keine Aufgabe dieses Knotens.`,en:`"${y}" is no task of this node.`});continue}k.feedback!==!0&&c(w,{de:`"${y}" ist keine Feedback-Aufgabe ('feedback: true').`,en:`"${y}" is no feedback task ('feedback: true').`}),p.some(E=>Xl(E.tasks).includes(y))&&c(w,{de:`"${y}" steht in den Aufgaben einer optionalen Aktion \u2014 eine Personenzeile entsteht nur beim Buchen.`,en:`"${y}" is among an optional action's tasks \u2014 a person row exists only through a booking.`});let v=ca(e).find(E=>E!==n&&bP(E).includes(y));v!==void 0&&c(w,{de:`"${y}" wird auch von "${String(v.key)}" angelegt \u2014 jede Feedback-Art geh\xF6rt zu genau einem Termin.`,en:`"${y}" is also created by "${String(v.key)}" \u2014 each feedback kind belongs to exactly one appointment.`});let A=["when","blocks","appointment"].filter(E=>k[E]!==void 0);A.length>0&&c(w,{de:`"${y}" tr\xE4gt ${A.map(E=>`'${E}'`).join(", ")} \u2014 eine Personenzeile entsteht nur beim Buchen und h\xE4lt nur ihre Runde.`,en:`"${y}" carries ${A.map(E=>`'${E}'`).join(", ")} \u2014 a person row exists only through a booking and holds only its round.`}),k.optional!==void 0&&c(w,{de:`"${y}" ist optional \u2014 eine Personenzeile h\xE4lt ihre Runde und damit die Pause, sie kann nicht \xFCbersprungen werden.`,en:`"${y}" is optional \u2014 a person row holds its round and with it the pause; it cannot be skipped.`},br.feedbackOptional)}return d}s(VH,"feedbackIssues");function BH(e,n,t){let r=qr(n.result);if(r?.kind!=="record"||!Array.isArray(r.fields))return[];let i=vP(e,String(n.key))?.personTasks??new Set,o=new Map(ca(e).map(l=>[l.key,l])),a=[];for(let[l,d]of r.fields.entries()){let c=qr(d);if(c?.type!=="assignment")continue;let u=Xl(c.tasks).filter(p=>o.get(p)?.feedback===!0&&!i.has(p));u.length!==0&&a.push(ui(`${t}.result.fields.${l}.tasks`,br.recordAssignment,{de:`Feld "${String(c.key)}": ${u.map(p=>`"${p}"`).join(", ")} legt kein Termin derselben optionalen Aktion an ('participants.feedback.tasks') \u2014 die Zuordnung h\xE4tte keine Zeile, die sie erh\xE4lt.`,en:`Field "${String(c.key)}": ${u.map(p=>`"${p}"`).join(", ")} is created by no appointment of the same optional action ('participants.feedback.tasks') \u2014 the assignment would have no row to receive it.`}))}return a}s(BH,"assignmentIssues");function xP(e,n){let t=[];for(let r of ca(n)){if(typeof r.key!="string")continue;let i=`nodes.${n.id}.tasks.${r.key}`;t.push(...KH(n,r,i)),t.push(...jH(e,n,r,i)),t.push(...VH(n,r,i)),t.push(...BH(n,r,i))}return t}s(xP,"taskInputIssues");var St={notOptionalAction:"[workItems/familyRequestNotOptionalAction]",notTask:"[workItems/familyRequestNotTask]",closedOtherwise:"[workItems/familyRequestClosedOtherwise]",blocks:"[workItems/familyRequestBlocks]",noDeadline:"[workItems/familyRequestNoDeadline]",fields:"[workItems/familyRequestFields]",unknownField:"[workItems/familyRequestUnknownField]",shape:"[workItems/familyRequestShape]",twicePerAction:"[workItems/familyRequestTwicePerAction]",deadlock:"[workItems/familyRequestOnlyWayButAsked]"};function At(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:`${n} ${t.de}`,en:`${n} ${t.en}`},severity:"error"}}s(At,"issue");function UH(e,n,t){return e.flatMap(r=>(Array.isArray(r.tasks)?r.tasks:[]).filter(i=>{let o=i.blocks,a=typeof o?.node=="string"?o.node:r.id;return o?.templateKey===t&&a===n}).map(i=>({nodeId:r.id,key:String(i.key)})))}s(UH,"blockersOf");function SP(e){let{graph:n,node:t,task:r}=e,i=r.familyRequest;if(i===void 0)return[];let o=typeof r.key=="string"?r.key:"?",a=`nodes.${t.id}.tasks.${o}`,l={de:`Task "${o}" auf Knoten \u201E${_e(n,t.id,"de")}\u201C (${t.id})`,en:`Task "${o}" on node "${_e(n,t.id,"en")}" (${t.id})`},d=[];if(typeof i!="object"||i===null||Array.isArray(i))return[At(`${a}.familyRequest`,St.shape,{de:`${l.de}: 'familyRequest' muss ein Objekt { fields } oder { from } sein.`,en:`${l.en}: 'familyRequest' must be an object { fields } or { from }.`})];let c=Object.keys(i).filter(k=>k!=="fields"&&k!=="from");c.length>0&&d.push(At(`${a}.familyRequest.${c[0]}`,St.shape,{de:`${l.de}: 'familyRequest' kennt nur 'fields' oder 'from', nicht ${c.map(k=>`'${k}'`).join(", ")} \u2014 was angefordert wird und der Text an die Familie werden beim Ausl\xF6sen gew\xE4hlt.`,en:`${l.en}: 'familyRequest' only knows 'fields' or 'from', not ${c.map(k=>`'${k}'`).join(", ")} \u2014 what is requested and the text to the family are chosen when the action is triggered.`}));let{fields:u,from:p}=i;u===void 0==(p===void 0)&&d.push(At(`${a}.familyRequest`,St.shape,{de:`${l.de}: 'familyRequest' nennt genau eines \u2014 'fields' (die anforderbaren Felder) oder 'from' (das Formular, dessen Dateifelder alle zur Wahl stehen).`,en:`${l.en}: 'familyRequest' names exactly one \u2014 'fields' (the fields that can be requested) or 'from' (the form whose file fields are all available).`})),e.onTrigger.has(o)||d.push(At(`${a}.familyRequest`,St.notOptionalAction,{de:`${l.de} fordert bei der Familie an, geh\xF6rt aber zu keiner optionalen Aktion (spawnTasks) \u2014 nur deren Ausl\xF6sen \xF6ffnet die Anfrage an die Familie.`,en:`${l.en} requests from the family but belongs to no optional action (spawnTasks) \u2014 only triggering one opens the request to the family.`})),r.kind!=="task"&&d.push(At(`${a}.kind`,St.notTask,{de:`${l.de} fordert bei der Familie an und muss die Art 'task' haben, nicht ${JSON.stringify(r.kind)}.`,en:`${l.en} requests from the family and must have the kind 'task', not ${JSON.stringify(r.kind)}.`}));for(let k of["result","when","locksEvidence","gatesNode"])r[k]!==void 0&&d.push(At(`${a}.${k}`,St.closedOtherwise,{de:`${l.de} wartet auf die Familie und erledigt sich mit ihrer Antwort \u2014 '${k}' passt nicht dazu.`,en:`${l.en} waits for the family and completes with their answer \u2014 '${k}' does not fit that.`}));r.blocks!==void 0&&d.push(At(`${a}.blocks`,St.blocks,{de:`${l.de} wartet auf die Familie und darf nichts zur\xFCckhalten ('blocks') \u2014 sie h\xE4lt ihren Knoten schon als Aufgabe einer optionalen Aktion.`,en:`${l.en} waits for the family and must not hold anything back ('blocks') \u2014 as the task of an optional action it already holds its node.`}));for(let k of UH(n.nodes,t.id,o))d.push(At(`nodes.${k.nodeId}.tasks.${k.key}.blocks`,St.blocks,{de:`Task "${k.key}" auf Knoten "${k.nodeId}" h\xE4lt ${l.de} zur\xFCck \u2014 eine Nachforderung darf nie zur\xFCckgehalten werden: zur\xFCckgehalten h\xE4tte sie keine Frist und k\xF6nnte mit der Antwort der Familie nicht erledigt werden.`,en:`Task "${k.key}" on node "${k.nodeId}" holds back ${l.en} \u2014 a follow-up request must never be held back: held back, it would have no deadline and could not be completed by the family's answer.`}));let h=r.params?.dueInDays;if((typeof h!="number"||!Number.isInteger(h)||h<1)&&d.push(At(`${a}.params.dueInDays`,St.noDeadline,{de:`${l.de} fordert bei der Familie an und braucht eine Frist in ganzen Tagen ('params.dueInDays' \u2265 1) \u2014 sie ist die Frist der Familie und Anlass der Erinnerung.`,en:`${l.en} requests from the family and needs a deadline in whole days ('params.dueInDays' \u2265 1) \u2014 it is the family's deadline and the reason for the reminder.`})),u===void 0)return d;if(!Array.isArray(u)||u.length===0)return d.push(At(`${a}.familyRequest.fields`,St.fields,{de:`${l.de}: 'familyRequest.fields' muss mindestens ein Feld eines Formulars nennen \u2014 oder statt dessen 'from' das Formular, dann stehen alle seine Dateifelder zur Wahl.`,en:`${l.en}: 'familyRequest.fields' must name at least one field of a form \u2014 or 'from' the form instead, then all its file fields are available.`})),d;let y=new Set;for(let k of u){if(!be(k))continue;let w=ue(k);if(y.has(w)){d.push(At(`${a}.familyRequest.fields`,St.fields,{de:`${l.de}: 'familyRequest.fields' nennt ${je(n,k,"de")} mehrfach.`,en:`${l.en}: 'familyRequest.fields' names ${je(n,k,"en")} more than once.`}));continue}y.add(w),un(k)||d.push(At(`${a}.familyRequest.fields`,St.unknownField,{de:`${l.de}: 'familyRequest.fields' nennt ${je(n,k,"de")} \u2014 anfordern l\xE4sst sich nur ein Feld eines Formulars ($node.<formular>.admission.<feld>).`,en:`${l.en}: 'familyRequest.fields' names ${je(n,k,"en")} \u2014 only a field of a form ($node.<form>.admission.<field>) can be requested.`}))}return d}s(SP,"familyRequestIssues");function AP(e){let n=new Set((Array.isArray(e.tasks)?e.tasks:[]).flatMap(r=>r.familyRequest!==void 0&&typeof r.key=="string"?[r.key]:[]));return(Array.isArray(e.optionalActions)?e.optionalActions:[]).flatMap((r,i)=>{if(r.action!=="spawnTasks"||!Array.isArray(r.tasks))return[];let o=r.tasks.filter(a=>typeof a=="string"&&n.has(a));return o.length<=1?[]:[At(`nodes.${e.id}.optionalActions.${i}.tasks`,St.twicePerAction,{de:`Optionale Aktion \u201E${String(r.key)}\u201C auf Knoten "${e.id}" startet ${o.length} Nachforderungen (${o.join(", ")}) \u2014 ein Ausl\xF6sen fragt die Familie nach EINER Sache; h\xF6chstens eine Nachforderung je Aktion.`,en:`Optional action "${String(r.key)}" on node "${e.id}" starts ${o.length} follow-up requests (${o.join(", ")}) \u2014 one trigger asks the family for ONE thing; at most one follow-up request per action.`})]})}s(AP,"familyRequestActionIssues");function EP(e,n){let t=e.nodes,r=new Map;for(let a of t)if(!(a.type!=="completenessCheck"||!Array.isArray(a.requires)))for(let l of a.requires)un(l)&&r.set(ue(l),l);if(r.size===0)return[];let i=s(a=>{let l=ai(n,a);return l===void 0||l!==null&&l.kind==="entered"&&l.type==="docRef"},"isFileField"),o=s(a=>{let{fields:l,from:d}=a??{};return Array.isArray(l)?l.filter(un):!be(d)||d.scope!=="node"?[]:[...r.values()].filter(c=>c.owner===d.owner&&i(c))},"offeredBy");return t.flatMap(a=>{let l=Array.isArray(a.requiresOneOf)?a.requiresOneOf:[],c=(Array.isArray(a.optionalActions)?a.optionalActions:[]).filter(h=>l.includes(h.key)),u=Array.isArray(a.tasks)?a.tasks:[];return c.filter(h=>Array.isArray(h.tasks)&&c.every(y=>y===h||y.when!==void 0)).flatMap(h=>u.flatMap(y=>{if(y.familyRequest===void 0||!h.tasks.includes(y.key))return[];let k=o(y.familyRequest).filter(w=>r.has(ue(w)));return k.length===0?[]:[{...At(`nodes.${a.id}.requiresOneOf`,St.deadlock,{de:`Auf Knoten \u201E${_e(e,a.id,"de")}\u201C (${a.id}) ist die Nachforderung \u201E${String(h.key)}\u201C der einzige Weg durch 'requiresOneOf', und eine Vollst\xE4ndigkeitspr\xFCfung fragt dieselben Felder an (${k.map(w=>je(e,w,"de")).join(", ")}). Ist deren Anfrage offen, lassen sich diese Felder nicht nachfordern \u2014 die Entscheidung bliebe gesperrt. Eine zweite Aktion in 'requiresOneOf' oder andere Felder l\xF6sen das.`,en:`On node "${_e(e,a.id,"en")}" (${a.id}) the follow-up request "${String(h.key)}" is the only way through 'requiresOneOf', and a completeness check asks for the same fields (${k.map(w=>je(e,w,"en")).join(", ")}). While its request is open, these fields cannot be requested \u2014 the decision would stay locked. A second action in 'requiresOneOf' or other fields solve this.`}),severity:"warning"}]}))})}s(EP,"familyRequestDeadlockWarnings");var Hw={key:!0,kind:!0,title:!0,assign:!0,gatesNode:!0,blocks:!0,completableIf:!0,result:!0,when:!0,onConditionReturn:!0,reads:!0,locksEvidence:!0,feedback:!0,description:!0,documents:!0,view:!0,familyRequest:!0,optional:!0,appointment:!0,inputs:!0,params:!0};function GH(e){let n=He(e);return new Map((typeof n.workItemTemplates=="function"?n.workItemTemplates(e):[]).map(t=>[t.key,t]))}s(GH,"intrinsicTemplatesOf");function TP(e,n,t){if(t!==void 0&&typeof t!="string")return null;let r=t??n,i=e.nodes.find(l=>l.id===r);if(i===void 0)return null;let o=i,a=He(i);return{node:o,composedKeys:new Set((Array.isArray(o.tasks)?o.tasks:[]).map(l=>l.key).filter(l=>typeof l=="string")),intrinsicByKey:GH(i),refuse:s(l=>typeof a.refuseBlocksTarget=="function"?a.refuseBlocksTarget(i,l):null,"refuse")}}s(TP,"resolveBlocksTargetNode");function zH(e){let n=new Map;for(let r of Zt(e.nodes)){let i=n.get(r.source)??[];i.push(r.target),n.set(r.source,i)}let t=new Map;return r=>{let i=t.get(r);if(i!==void 0)return i;let o=new Set,a=[...n.get(r)??[]];for(;a.length>0;){let l=a.shift();o.has(l)||(o.add(l),a.push(...n.get(l)??[]))}return t.set(r,o),o}}s(zH,"reachability");function $P(e){let n=[],t=new Map;for(let o of e.nodes){let a=o;for(let l of Array.isArray(a.tasks)?a.tasks:[]){let d=typeof l.key=="string"?l.key:void 0,c=l.blocks;if(d===void 0||typeof c?.templateKey!="string")continue;let u=typeof c.node=="string"?c.node:o.id;t.set(`${o.id}::${d}`,`${u}::${c.templateKey}`)}}let r=new Map,i=s((o,a)=>{if(r.get(o)==="done")return;if(r.get(o)==="visiting"){let d=[...a.slice(a.indexOf(o)),o],[c,u]=o.split("::");n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${c}.tasks.${u}.blocks`,reason:{de:`[workItems/blocksCycle] Zyklus im 'blocks'-Graphen: ${d.map(p=>`"${p.replace("::"," \xB7 ")}"`).join(" \u2192 ")} \u2014 jedes Mitglied w\xFCrde auf ein anderes warten, keines w\xFCrde je frei.`,en:`[workItems/blocksCycle] Cycle in the 'blocks' graph: ${d.map(p=>`"${p.replace("::"," \xB7 ")}"`).join(" \u2192 ")} \u2014 every member would wait for another, none would ever be released.`},severity:"error"});return}r.set(o,"visiting");let l=t.get(o);l!==void 0&&t.has(l)&&i(l,[...a,o]),r.set(o,"done")},"walk");for(let o of t.keys())i(o,[]);return n}s($P,"checkBlocksCycles");function WH(e){let{requiresOneOf:n,optionalActions:t}=e;if(!Array.isArray(n)||!Array.isArray(t))return new Set;let r=new Set(n.filter(o=>typeof o=="string")),i=new Set;for(let o of t)if(!(typeof o.key!="string"||!r.has(o.key)||!Array.isArray(o.tasks)))for(let a of o.tasks)typeof a=="string"&&i.add(a);return i}s(WH,"tasksOfRequiresOneOf");function RP(e){if(typeof e!="object"||e===null)return!1;let{de:n,en:t}=e;return typeof n=="string"&&n.trim().length>0&&typeof t=="string"&&t.trim().length>0}s(RP,"isFilledBilingual");var YH=["blocks","gatesNode","locksEvidence","completableIf"];function HH(e,n){let t={de:`Task "${n.key}" (Knoten "${n.nodeId}")`,en:`Task "${n.key}" (node "${n.nodeId}")`},r=[];e.feedback!==!0&&r.push(An(`${n.base}.feedback`,{de:`[workItems/feedbackNotTrue] ${t.de}: 'feedback' kennt nur true; erhalten ${JSON.stringify(e.feedback)}.`,en:`[workItems/feedbackNotTrue] ${t.en}: 'feedback' only knows true; got ${JSON.stringify(e.feedback)}.`}));let i=e.result;(e.kind!=="task"||i?.kind!=="freetext")&&r.push(An(`${n.base}.feedback`,{de:`[workItems/feedbackNeedsFreetext] ${t.de} ist eine Feedback-Aufgabe und schlie\xDFt daher mit Freitext ('result: { kind: "freetext" }'); erhalten ${e.kind!=="task"?`kind ${String(e.kind)}`:`Ergebnis ${String(i?.kind)}`}.`,en:`[workItems/feedbackNeedsFreetext] ${t.en} is a feedback task, so it closes with free text ('result: { kind: "freetext" }'); got ${e.kind!=="task"?`kind ${String(e.kind)}`:`result ${String(i?.kind)}`}.`}));let o=["blocks","gatesNode","completableIf","locksEvidence","familyRequest","appointment"].filter(a=>e[a]!==void 0);return o.length>0&&r.push(An(`${n.base}.feedback`,{de:`[workItems/feedbackSteersProcess] ${t.de} ist eine Feedback-Aufgabe; die Antwort kommt von einer Seite ohne weitere Daten und darf deshalb nicht von ${o.join(", ")} abh\xE4ngen.`,en:`[workItems/feedbackSteersProcess] ${t.en} is a feedback task; its answer comes from a page without application data, so it may not depend on ${o.join(", ")}.`})),r}s(HH,"feedbackTaskIssues");function JH(e,n){let t=[],r={de:`Task "${n.key}" (Knoten "${n.nodeId}")`,en:`Task "${n.key}" (node "${n.nodeId}")`},i=e.optional;(!(typeof i=="object"&&i!==null&&Object.keys(i).every(d=>d==="skipLabel"))||!RP(i.skipLabel))&&t.push(An(`${n.base}.optional.skipLabel`,{de:`[workItems/optionalSkipLabel] ${r.de} ist optional, braucht daf\xFCr '{ skipLabel: { de, en } }' \u2014 die Worte des Knopfs, mit dem die zust\xE4ndige Person ohne Ergebnis abschlie\xDFt (\u201EKeine Einsch\xE4tzung abgeben"); erhalten ${JSON.stringify(i)}.`,en:`[workItems/optionalSkipLabel] ${r.en} is optional and needs '{ skipLabel: { de, en } }' for that \u2014 the words of the button the responsible person uses to finish without a result ("Give no assessment"); got ${JSON.stringify(i)}.`})),e.kind!=="task"&&t.push(An(`${n.base}.optional`,{de:`[workItems/optionalOnApproval] ${r.de} ist eine Freigabe \u2014 optional ist nur eine Aufgabe; eine Freigabe schlie\xDFt mit ihrem Urteil.`,en:`[workItems/optionalOnApproval] ${r.en} is an approval \u2014 only a task can be optional; an approval ends with its verdict.`}));let a=e.result;(a===void 0||typeof a.kind!="string"||!lO({kind:a.kind,writes:a.writes}))&&t.push(An(`${n.base}.optional`,{de:`[workItems/optionalNeedsProseResult] ${r.de} ist optional, schlie\xDFt aber ${a===void 0?"ohne Ergebnis":`mit einem ${String(a.kind)}-Ergebnis${a.writes!==void 0?" mit Wert":""}`} \u2014 optional ist nur eine Aufgabe mit Freitext, Empfehlung oder einer Auswahl ohne 'writes': einen Wert, den ein sp\xE4terer Schritt liest, g\xE4be es dann nie.`,en:`[workItems/optionalNeedsProseResult] ${r.en} is optional but ends ${a===void 0?"without a result":`with a ${String(a.kind)} result${a.writes!==void 0?" with a value":""}`} \u2014 only a task with free text, a recommendation or a choice without 'writes' can be optional: a value a later step reads would then never arrive.`}));let l=YH.filter(d=>e[d]!==void 0);return l.length>0&&t.push(An(`${n.base}.${l[0]}`,{de:`[workItems/optionalHolds] ${r.de} ist optional und tr\xE4gt ${l.map(d=>`'${d}'`).join(", ")} \u2014 auf eine optionale Aufgabe wartet nichts: sie h\xE4lt keinen Schritt zur\xFCck. Entweder optional oder zur\xFCckhaltend.`,en:`[workItems/optionalHolds] ${r.en} is optional and carries ${l.map(d=>`'${d}'`).join(", ")} \u2014 nothing waits for an optional task: it holds no step back. Either optional or holding back.`})),n.requiredByRule&&t.push(An(`${n.base}.optional`,{de:`[workItems/optionalInRequiresOneOf] ${r.de} ist optional, geh\xF6rt aber zu einer Aktion, die 'requiresOneOf' verlangt \u2014 \u201EKeine Einsch\xE4tzung abgeben" w\xFCrde die Regel erf\xFCllen, ohne dass etwas geschehen ist.`,en:`[workItems/optionalInRequiresOneOf] ${r.en} is optional but belongs to an action that 'requiresOneOf' requires \u2014 "Give no assessment" would satisfy the rule without anything having happened.`})),t}s(JH,"optionalTaskIssues");function An(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"error"}}s(An,"issue");function IP(e,n){let t=[],r=zH(e),i=new Set(la(e).map(o=>o.key));t.push(...EP(e,n));for(let o of e.nodes){let a=o,l=kP(a);t.push(...AP(a));let d=WH(a);t.push(...pP(a,e.nodes)),t.push(...xP(e,a));let c=new Map((Array.isArray(a.tasks)?a.tasks:[]).filter(u=>typeof u.key=="string").map(u=>[u.key,{feedback:u.feedback===!0}]));for(let u of Array.isArray(a.tasks)?a.tasks:[]){let p=typeof u.key=="string"?u.key:"?",h=`nodes.${o.id}.tasks.${p}`,y=u.kind,k=u.result,w=u.blocks,v=typeof w?.node=="string"&&w.node!==o.id?w.node:void 0;if(typeof w?.templateKey=="string"){let $=typeof w.node=="string"?w.node:o.id,I=e.nodes.find(le=>le.id===$),B=(Array.isArray(I?.tasks)?I.tasks:[]).find(le=>le.key===w.templateKey)?.blocks;typeof B?.node=="string"&&B.node!==$&&t.push(An(`${h}.blocks.templateKey`,{de:`[workItems/blocksCrossNodeTask] Task "${p}" auf Knoten "${o.id}" h\xE4lt "${w.templateKey}" auf Knoten "${$}" zur\xFCck \u2014 das ist selbst eine knoten\xFCbergreifende Aufgabe, die ihren Knoten \xFCberlebt; zur\xFCckgehalten k\xF6nnte sie nach dessen Verlassen weder bearbeitet noch freigegeben werden. Nur Aufgaben, die an ihrem Knoten bleiben, und intrinsische Vorlagen sind Ziele.`,en:`[workItems/blocksCrossNodeTask] Task "${p}" on node "${o.id}" holds back "${w.templateKey}" on node "${$}" \u2014 that is itself a cross-node task that outlives its node; held back, it could be neither worked nor released after the node is left. Only tasks that stay on their node and intrinsic templates are targets.`}))}if(v!==void 0){let $=v;e.nodes.some(I=>I.id===$)&&!r(o.id).has($)&&t.push(An(`${h}.blocks.node`,{de:`[workItems/blocksTargetNotAfter] Task "${p}" auf Knoten "${o.id}" blockiert Knoten "${$}", der von hier aus nicht erreichbar ist \u2014 die Aufgabe entst\xFCnde erst, wenn ihr Ziel schon hinter dem Prozess liegt. Ziel ist derselbe Knoten oder ein sp\xE4terer.`,en:`[workItems/blocksTargetNotAfter] Task "${p}" on node "${o.id}" blocks node "${$}", which cannot be reached from here \u2014 the task would only be created when its target is already behind the process. The target is the same node or a later one.`})),(k===void 0||!Mi(k.kind))&&t.push(An(`${h}.blocks.node`,{de:`[workItems/crossNodeBlocksNeedsResult] Task "${p}" auf Knoten "${o.id}" blockiert einen anderen Knoten ("${$}"), hat aber kein 'result' \u2014 eine knoten\xFCbergreifende Aufgabe \xFCberlebt ihren Knoten und wird \xFCber ihr Ergebnis abgeschlossen (Freitext, Empfehlung oder Auswahl).`,en:`[workItems/crossNodeBlocksNeedsResult] Task "${p}" on node "${o.id}" blocks another node ("${$}") but has no 'result' \u2014 a cross-node task outlives its node and is completed through its result (free text, recommendation or choice).`})),l.has(p)&&t.push(An(`${h}.blocks.node`,{de:`[optionalAction/crossNodeBlocks] Task "${p}" geh\xF6rt zu einer optionalen Aktion (spawnTasks) auf Knoten "${o.id}" und darf keinen anderen Knoten blockieren \u2014 ihre Zeilen sind die Runde der Aktion.`,en:`[optionalAction/crossNodeBlocks] Task "${p}" belongs to an optional action (spawnTasks) on node "${o.id}" and must not block another node \u2014 its rows are the round of the action.`}))}for(let $ of dP(String(y),k,{channelKeys:i,nodeTasks:c,...n?.billingItemKeys!==void 0?{billingItemKeys:n.billingItemKeys}:{},...n?.offerProgram!==void 0?{offerProgram:n.offerProgram}:{}}))t.push(An(`${h}.${$.field}`,{de:`${$.code} ${$.message.de} (Task "${p}" auf Knoten "${o.id}").`,en:`${$.code} ${$.message.en} (task "${p}" on node "${o.id}").`}));let A=u.when,E=s(($,I,G)=>{!be(I)||un(I)||t.push(An($,{de:`[workItems/evidenceNotFormField] ${G} auf Task "${p}" (Knoten "${o.id}") nennt ${je(e,I,"de")} \u2014 Bedingung und Belege einer Aufgabe sind Felder eines Formulars ($node.<formular>.admission.<feld>).`,en:`[workItems/evidenceNotFormField] ${G} on task "${p}" (node "${o.id}") names ${je(e,I,"en")} \u2014 the condition and evidence of a task are fields of a form ($node.<form>.admission.<field>).`}))},"notFormField");A!==void 0?(E(`${h}.when`,A,"'when'"),u.onConditionReturn!=="respawn"&&u.onConditionReturn!=="stayClosed"&&t.push(An(`${h}.onConditionReturn`,{de:`[workItems/whenNeedsOnConditionReturn] Task "${p}" (Knoten "${o.id}") hat eine Bedingung, aber kein 'onConditionReturn' ('respawn' | 'stayClosed') \u2014 was bei der R\xFCckkehr der Bedingung geschieht, muss entschieden sein.`,en:`[workItems/whenNeedsOnConditionReturn] Task "${p}" (node "${o.id}") has a condition but no 'onConditionReturn' ('respawn' | 'stayClosed') \u2014 what happens when the condition returns must be decided.`}))):u.onConditionReturn!==void 0&&t.push(An(`${h}.onConditionReturn`,{de:`[workItems/whenNeedsOnConditionReturn] 'onConditionReturn' ohne 'when' auf Task "${p}" (Knoten "${o.id}") \u2014 ohne Bedingung kehrt nichts zur\xFCck.`,en:`[workItems/whenNeedsOnConditionReturn] 'onConditionReturn' without 'when' on task "${p}" (node "${o.id}") \u2014 without a condition nothing returns.`}));let R=u.reads;if(R!==void 0)if(!Array.isArray(R))t.push(An(`${h}.reads`,{de:`[workItems/readsUnknownField] 'reads' auf Task "${p}" (Knoten "${o.id}") muss eine Liste von Feldadressen sein.`,en:`[workItems/readsUnknownField] 'reads' on task "${p}" (node "${o.id}") must be a list of field addresses.`}));else for(let[$,I]of R.entries())E(`${h}.reads.${$}`,I,"'reads'");let P=u.locksEvidence,F=s(($,I)=>t.push(An(`${h}.locksEvidence`,{de:`[workItems/${$}] Task "${p}" (Knoten "${o.id}") ${I.de}`,en:`[workItems/${$}] Task "${p}" (node "${o.id}") ${I.en}`})),"lockIssue");P!==void 0&&P!==!0&&F("locksEvidenceNotTrue",{de:`tr\xE4gt 'locksEvidence' ${JSON.stringify(P)} \u2014 nur 'true' ist erlaubt; ohne Sperre entf\xE4llt das Feld.`,en:`carries 'locksEvidence' ${JSON.stringify(P)} \u2014 only 'true' is allowed; without a lock the field is dropped.`}),P===!0&&(R===void 0&&A===void 0&&F("locksEvidenceWithoutEvidence",{de:"sperrt seine Belege, hat aber weder 'reads' noch 'when' \u2014 es gibt nichts, worauf die Entscheidung beruht.",en:"locks its evidence but has neither 'reads' nor 'when' \u2014 there is nothing the decision rests on."}),(k===void 0||!Mi(k.kind))&&F("locksEvidenceNeedsRecordedResult",{de:"sperrt seine Belege, schlie\xDFt aber nicht mit einem erfassten Ergebnis (Freitext, Empfehlung, Auswahl) \u2014 nur eine Entscheidung, die das Team wieder\xF6ffnen kann, darf Belege sperren (ein Termin bleibt gebucht).",en:"locks its evidence but does not end with a recorded result (free text, recommendation, choice) \u2014 only a decision the team can reopen may lock evidence (an appointment stays booked)."}),l.has(p)&&F("locksEvidenceOnOptionalAction",{de:"geh\xF6rt zu einer optionalen Aktion (spawnTasks) \u2014 ihre Zeilen sind die Runde der Aktion, wieder\xF6ffnen l\xE4sst sie sich nicht; Belege sperrt nur eine Knotenaufgabe.",en:"belongs to an optional action (spawnTasks) \u2014 its rows are the round of the action and cannot be reopened; only a node task locks evidence."})),t.push(...SP({graph:e,node:a,task:u,onTrigger:l,specCtx:n}));let b=Object.keys(u).filter($=>!Object.hasOwn(Hw,$));b.length>0&&t.push(An(`${h}.${b[0]}`,{de:`[workItems/unknownKey] Task "${p}" (Knoten "${o.id}") tr\xE4gt ${b.map($=>`'${$}'`).join(", ")} \u2014 kein Feld einer Aufgabe. Erlaubt: ${Object.keys(Hw).join(", ")}. (Checklisten gibt es nicht mehr: Text als 'description', mehrere Arbeitsschritte sind mehrere Aufgaben.)`,en:`[workItems/unknownKey] Task "${p}" (node "${o.id}") carries ${b.map($=>`'${$}'`).join(", ")} \u2014 not a field of a task. Allowed: ${Object.keys(Hw).join(", ")}. (Checklists no longer exist: text goes in 'description', several work steps are several tasks.)`}));let O=u.description;O!==void 0&&!RP(O)&&t.push(An(`${h}.description`,{de:`[workItems/descriptionInvalid] 'description' auf Task "${p}" (Knoten "${o.id}") braucht Text in beiden Sprachen ({ de, en }), erhalten ${JSON.stringify(O)}.`,en:`[workItems/descriptionInvalid] 'description' on task "${p}" (node "${o.id}") needs text in both languages ({ de, en }), got ${JSON.stringify(O)}.`})),u.feedback!==void 0&&t.push(...HH(u,{key:p,nodeId:o.id,base:h})),u.optional!==void 0&&t.push(...JH(u,{key:p,nodeId:o.id,base:h,requiredByRule:d.has(p)}))}}return t}s(IP,"checkNodeTasks");function OP(e){let n=e.indexOf(":"),t=n===-1?"":e.slice(0,n),r=n===-1?"":e.slice(n+1).trim();if(t==="artifact"&&r.length>0)return{kind:t,key:r};let i=Qr(r);return t==="field"&&i!==null?{kind:t,address:i}:se("INVALID",{de:`Dokument-Verweis "${e}" ist ung\xFCltig \u2014 erwartet artifact:<Slot-Schl\xFCssel> (auch der Slot eines anderen Knotens) oder field:$node.<Formular>.admission.<Feld>.`,en:`Document reference "${e}" is invalid \u2014 expected artifact:<slot key> (another node's slot too) or field:$node.<form>.admission.<field>.`})}s(OP,"parseTaskDocumentRef");function Jw(e){return e.kind==="artifact"?`artifact:${e.key}`:`field:${ue(e.address)}`}s(Jw,"taskDocumentId");function fi(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"error"}}s(fi,"issue");function _P(e){return Array.isArray(e.tasks)?e.tasks:[]}s(_P,"tasksOf");function ed(e){let n=new Map;for(let t of e){let{id:r,artifacts:i}=t;for(let o of Array.isArray(i)?i:[])typeof o?.key=="string"&&n.set(o.key,[...n.get(o.key)??[],{nodeId:r,slot:o}])}return n}s(ed,"artifactSlotDeclarations");function QH(e){return e.flatMap(n=>{let{id:t,artifacts:r}=n;return(Array.isArray(r)?r:[]).filter(i=>!ep(i?.type)).map(i=>({nodeId:String(t),slotKey:String(i?.key),type:JSON.stringify(i?.type??null)}))})}s(QH,"unknownArtifactSlotTypes");function NP(e){let n=[];for(let{nodeId:t,slotKey:r,type:i}of QH(e.nodes))n.push(fi(`nodes.${t}.artifacts.${r}.type`,{de:`[artifact/unknownType] Knoten "${t}" deklariert den Dokument-Slot \u201E${r}" mit der Art ${i} \u2014 erlaubt sind ${Xs.join(", ")}.`,en:`[artifact/unknownType] Node "${t}" declares the document slot "${r}" with the type ${i} \u2014 allowed are ${Xs.join(", ")}.`}));for(let[t,r]of ed(e.nodes))for(let i of r.slice(1))n.push(fi(`nodes.${i.nodeId}.artifacts`,{de:`[governedDocument/slotKeyTaken] Knoten "${i.nodeId}" deklariert den Dokument-Slot \u201E${t}", den schon "${r[0].nodeId}" deklariert \u2014 jeder Slot-Schl\xFCssel geh\xF6rt genau einem Knoten.`,en:`[governedDocument/slotKeyTaken] Node "${i.nodeId}" declares the document slot "${t}", which "${r[0].nodeId}" already declares \u2014 every slot key belongs to exactly one node.`}));return n}s(NP,"checkArtifactSlotKeys");function ZH(e,n,t,r=ed(e.nodes)){let i=r.get(n)?.[0]?.nodeId;return i===void 0?{reason:"unknown"}:zs(e,i,t)?null:{reason:"notBefore",owner:i}}s(ZH,"slotLinkRefusal");function PP(e){if(!Array.isArray(e)||e.length===0)return null;let n=[];for(let t of e){let r=typeof t=="object"&&t!==null?t:{},i=Object.keys(r).sort().join(",");if(r.kind==="artifact"&&i==="key,kind"&&typeof r.key=="string"&&r.key.length>0)n.push({kind:"artifact",key:r.key});else if(r.kind==="field"&&i==="address,kind")n.push({kind:"field",address:r.address});else return null}return n}s(PP,"authoredRefs");function CP(e){let n=[],t=ed(e.nodes);for(let r of e.nodes)for(let i of _P(r)){if(i.documents===void 0)continue;let o=typeof i.key=="string"?i.key:"?",a=`nodes.${r.id}.tasks.${o}.documents`,l={de:`Task "${o}" (Knoten "${r.id}")`,en:`Task "${o}" (node "${r.id}")`},d=PP(i.documents);if(d===null){n.push(fi(a,{de:`[workItems/documentsInvalid] 'documents' auf ${l.de} muss eine nicht leere Liste von { kind: 'artifact', key } (Dokument-Slot eines Knotens) oder { kind: 'field', address } (Dateifeld eines Formulars) sein, erhalten ${JSON.stringify(i.documents)} \u2014 ein { kind: 'document', address } schreibt \`plexus-cli offer upgrade\` auf den Slot um.`,en:`[workItems/documentsInvalid] 'documents' on ${l.en} must be a non-empty list of { kind: 'artifact', key } (document slot of a node) or { kind: 'field', address } (file field of a form), got ${JSON.stringify(i.documents)} \u2014 \`plexus-cli offer upgrade\` rewrites a { kind: 'document', address } onto its slot.`}));continue}let c=new Set;for(let u of d){if(u.kind!=="artifact"&&!be(u.address))continue;let p=u.kind==="artifact"?Jw(u):Jw({kind:"field",address:u.address});if(c.has(p)&&n.push(fi(a,{de:`[workItems/documentsDuplicate] ${l.de} verweist zweimal auf ${p}.`,en:`[workItems/documentsDuplicate] ${l.en} refers to ${p} twice.`})),c.add(p),u.kind==="artifact"){let h=ZH(e,u.key,r.id,t);h?.reason==="unknown"?n.push(fi(a,{de:`[workItems/documentsUnknownArtifact] ${l.de} verweist auf das Dokument "${u.key}", aber kein Knoten deklariert einen solchen Slot.`,en:`[workItems/documentsUnknownArtifact] ${l.en} refers to the document "${u.key}", but no node declares such a slot.`})):h?.reason==="notBefore"&&n.push(fi(a,{de:`[workItems/documentsNotBefore] ${l.de} verweist auf das Dokument "${u.key}" des Knotens "${h.owner}", der nicht auf jedem Weg vor "${r.id}" liegt \u2014 auf einem Weg an ihm vorbei g\xE4be es das Dokument nie.`,en:`[workItems/documentsNotBefore] ${l.en} refers to the document "${u.key}" of node "${h.owner}", which does not lie on every path before "${r.id}" \u2014 on a path around it the document would never exist.`}))}u.kind==="field"&&!un(u.address)&&n.push(fi(a,{de:`[workItems/documentsInvalid] ${l.de}: ein Feld-Dokument nennt ein Feld eines Formulars ($node.<formular>.admission.<feld>), nicht ${je(e,u.address,"de")}.`,en:`[workItems/documentsInvalid] ${l.en}: a field document names a field of a form ($node.<form>.admission.<field>), not ${je(e,u.address,"en")}.`}))}}return n}s(CP,"checkTaskDocuments");function DP(e,n){let t=[];for(let r of e.nodes)for(let i of _P(r)){let o=PP(i.documents);if(o===null)continue;let a=typeof i.key=="string"?i.key:"?",l=`nodes.${r.id}.tasks.${a}.documents`;for(let d of o){if(d.kind!=="field"||!un(d.address))continue;let c=ai(n,d.address);if(c==null)continue;let u={de:je(e,d.address,"de"),en:je(e,d.address,"en")},p=Ys("taskDocument",Ws(c));if(p==="repeated"){t.push(fi(l,{de:`[workItems/documentsUnknownField] Task "${a}" (Knoten "${r.id}") verweist auf das Feld ${u.de} \u2014 ein Feld in einer Wiederholgruppe ist kein einzelnes Dokument der Anmeldung.`,en:`[workItems/documentsUnknownField] Task "${a}" (node "${r.id}") refers to the field ${u.en} \u2014 a field in a repeated group is not a single document of the application.`}));continue}p==="notDocument"&&t.push(fi(l,{de:`[workItems/documentsNotDocument] Task "${a}" (Knoten "${r.id}") verweist auf das Feld ${u.de}, das keine Datei enth\xE4lt \u2014 nur Datei-Felder (docRef) sind Dokumente.`,en:`[workItems/documentsNotDocument] Task "${a}" (node "${r.id}") refers to the field ${u.en}, which holds no file \u2014 only file fields (docRef) are documents.`}))}}return t}s(DP,"checkTaskDocumentFields");var Zw=["form","artifact","field"],fa=["coverLetter","contract"],FP=/^[A-Za-z0-9_.-]+$/;function XH(e){return fa.includes(e)}s(XH,"isArtifactPart");function ua(e){return se("INVALID",{de:`Ansichts-Adresse "${e}" ist ung\xFCltig \u2014 erwartet form:<Formularknoten>#<Ansicht>, artifact:<Slot>[#${fa.join("|")}] oder field:$node.<Formular>.admission.<Feld>.`,en:`View address "${e}" is invalid \u2014 expected form:<form node>#<view>, artifact:<slot>[#${fa.join("|")}] or field:$node.<form>.admission.<field>.`})}s(ua,"invalid");function Xw(e){let n=e.indexOf(":");if(n===-1)return ua(e);let t=e.slice(0,n),r=e.slice(n+1);if(t==="field"){let l=Qr(r);return l===null?ua(e):{kind:t,address:l}}let i=r.indexOf("#"),o=i===-1?r:r.slice(0,i),a=i===-1?null:r.slice(i+1);return FP.test(o)?t==="form"?a!==null&&FP.test(a)?{kind:t,form:o,view:a}:ua(e):t==="artifact"?a===null?{kind:t,slot:o}:XH(a)?{kind:t,slot:o,part:a}:ua(e):ua(e):ua(e)}s(Xw,"parseViewAddress");function LP(e){let n=nJ(e);if(n===null)return null;let t=eJ(n);return t!==null&&JSON.stringify(Qw(t))===JSON.stringify(Qw(e))?t:null}s(LP,"viewAddressOf");function eJ(e){try{return Xw(e)}catch{return null}}s(eJ,"tryParseViewAddress");function nJ(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e;if(n.kind==="form"&&typeof n.form=="string"&&typeof n.view=="string")return`form:${n.form}#${n.view}`;if(n.kind==="artifact"&&typeof n.slot=="string")return n.part===void 0?`artifact:${n.slot}`:typeof n.part=="string"?`artifact:${n.slot}#${n.part}`:null;if(n.kind==="field"&&n.address!==null&&typeof n.address=="object"){let t=n.address;return typeof t.scope!="string"||typeof t.key!="string"?null:`field:${ue(t)}`}return null}s(nJ,"spellingOf");function Qw(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([n],[t])=>n<t?-1:n>t?1:0).map(([n,t])=>[n,Qw(t)]))}s(Qw,"canonical");function MP(e){switch(e.kind){case"form":return`form:${e.form}#${e.view}`;case"artifact":return e.part===void 0?`artifact:${e.slot}`:`artifact:${e.slot}#${e.part}`;case"field":return`field:${ue(e.address)}`}}s(MP,"formatViewAddress");var ek=["form","documents"],tJ=/^[a-z][a-zA-Z0-9_-]*$/;function rJ(e){let n=new Map,t=s(r=>{for(let i of[...r.fields,...(r.groups??[]).flatMap(o=>o.fields)])n.set(i.key,i.type==="docRef"?"document":"other");for(let i of r.repeated??[]){n.set(i.key,"other");for(let o of i.itemTemplate)n.set(`${i.key}[].${o.key}`,o.type==="docRef"?"row":"other")}r.subsections?.forEach(t)},"visit");return e.sections.forEach(t),n}s(rJ,"fieldPlaces");function qP(e,n,t){let r=[],i=new Set;return e.forEach((o,a)=>{if(typeof o!="string"||!tJ.test(o)){r.push({severity:"error",path:`${t(a)}.key`,code:"view.invalid-key",message:{de:`${n.de}: '${String(o)}' ist kein g\xFCltiger Schl\xFCssel (Kleinbuchstabe am Anfang, dann Buchstaben, Ziffern, - oder _).`,en:`${n.en}: '${String(o)}' is no valid key (a lower-case letter first, then letters, digits, - or _).`}});return}i.has(o)&&r.push({severity:"error",path:`${t(a)}.key`,code:"view.duplicate-key",message:{de:`${n.de}: Der Schl\xFCssel '${o}' kommt doppelt vor.`,en:`${n.en}: the key '${o}' occurs twice.`}}),i.add(o)}),r}s(qP,"keyIssues");function iJ(e,n,t){return e==="document"?null:e===void 0?{severity:"error",path:t,code:"view.unknown-field",message:{de:`Ansicht: Das Formular hat kein Feld '${n}'.`,en:`View: the form has no field '${n}'.`}}:e==="row"?{severity:"error",path:t,code:"view.field-in-row",message:{de:`Ansicht: Das Dateifeld '${n}' liegt in einem wiederholten Block und kann nicht einzeln genannt werden.`,en:`View: the file field '${n}' sits in a repeated block and cannot be named on its own.`}}:{severity:"error",path:t,code:"view.not-a-document",message:{de:`Ansicht: Das Feld '${n}' enth\xE4lt keine Datei.`,en:`View: the field '${n}' holds no file.`}}}s(iJ,"fieldIssue");function oJ(e,n,t){let r=[];ek.includes(e.key)&&r.push({severity:"error",path:`${n}.key`,code:"view.reserved-key",message:{de:`Der Ansichtsschl\xFCssel '${e.key}' ist f\xFCr die Standardansicht reserviert.`,en:`The view key '${e.key}' is reserved for the standard view.`}});let i=e.groups;i.length===0&&r.push({severity:"error",path:`${n}.groups`,code:"view.empty",message:{de:`Ansicht '${e.key}' hat keine Gruppen.`,en:`View '${e.key}' has no groups.`}}),r.push(...qP(i.map(a=>a.key),{de:`Gruppe der Ansicht '${e.key}'`,en:`Group of view '${e.key}'`},a=>`${n}.groups[${a}]`));let o=new Set;return i.forEach((a,l)=>{let d=`${n}.groups[${l}]`,c=a.fields;c.length===0&&r.push({severity:"error",path:`${d}.fields`,code:"view.empty",message:{de:`Gruppe '${a.key}' der Ansicht '${e.key}' hat keine Felder.`,en:`Group '${a.key}' of view '${e.key}' has no fields.`}}),c.forEach((u,p)=>{let h=`${d}.fields[${p}]`,y=iJ(t.get(u),u,h);y!==null&&r.push(y),o.has(u)&&r.push({severity:"error",path:h,code:"view.field-twice",message:{de:`Ansicht '${e.key}': Das Feld '${u}' steht mehrfach; eine Datei hat einen Platz.`,en:`View '${e.key}': the field '${u}' is listed more than once; a file has one place.`}}),o.add(u)})}),r}s(oJ,"viewIssues");function sJ(e){if(!Array.isArray(e))return"views";for(let[n,t]of e.entries()){let r=t?.groups;if(!Array.isArray(r))return`views[${n}].groups`;for(let[i,o]of r.entries()){let a=o?.fields;if(!Array.isArray(a)||a.some(l=>typeof l!="string"))return`views[${n}].groups[${i}].fields`}}return null}s(sJ,"malformedAt");function KP(e){let n=e.views;if(n===void 0)return[];let t=sJ(n);if(t!==null)return[{severity:"error",path:t,code:"view.malformed",message:{de:`${t} hat nicht die Form einer Ansicht: views ist eine Liste von { key, label, groups }, groups eine Liste von { key, label, fields }, fields eine Liste von Feldschl\xFCsseln.`,en:`${t} is not shaped like a view: views is a list of { key, label, groups }, groups a list of { key, label, fields }, fields a list of field keys.`}}];let r=rJ(e);return[...qP(n.map(i=>i.key),{de:"Ansicht",en:"View"},i=>`views[${i}]`),...n.flatMap((i,o)=>oJ(i,`views[${o}]`,r))]}s(KP,"formViewIssues");function pa(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"error"}}s(pa,"issue");function jP(e,n,t,r,i){let o=LP(e);if(o===null)return[pa(n,{de:`[view/invalid] 'view' auf ${t.de} ist keine Ansichts-Adresse \u2014 erwartet { kind: ${Zw.join(" | ")}, \u2026 }: form:<Formularknoten>#<Ansicht>, artifact:<Slot>[#${fa.join("|")}] oder field:$node.<Formular>.admission.<Feld>.`,en:`[view/invalid] 'view' on ${t.en} is no view address \u2014 expected { kind: ${Zw.join(" | ")}, \u2026 }: form:<form node>#<view>, artifact:<slot>[#${fa.join("|")}] or field:$node.<form>.admission.<field>.`})];let a=MP(o);switch(o.kind){case"artifact":return r.has(o.slot)?[]:[pa(n,{de:`[view/unknownSlot] ${t.de} nennt "${a}", aber kein Knoten dieses Graphen hat den Dokument-Slot "${o.slot}".`,en:`[view/unknownSlot] ${t.en} names "${a}", but no node of this graph has the document slot "${o.slot}".`})];case"form":case"field":{let l=o.kind==="form"?o.form:o.address.scope==="node"?o.address.owner:null;if(l===null)return[pa(n,{de:`[view/invalid] ${t.de} nennt "${a}" \u2014 ein Dateifeld liegt in einem Formular: field:$node.<Formular>.admission.<Feld>.`,en:`[view/invalid] ${t.en} names "${a}" \u2014 a file field lives in a form: field:$node.<form>.admission.<field>.`})];let d=i?.formViewKeysByFormNode;if(d===void 0)return[];let c=d.get(l);return c===void 0?[pa(n,{de:`[view/unknownForm] ${t.de} nennt "${a}", aber kein Formularknoten hei\xDFt so.`,en:`[view/unknownForm] ${t.en} names "${a}", but no form node has that id.`})]:o.kind==="field"?[]:c.has(o.view)||ek.includes(o.view)?[]:[pa(n,{de:`[view/unknownView] ${t.de} nennt "${a}", aber das Formular "${o.form}" hat keine Ansicht "${o.view}".`,en:`[view/unknownView] ${t.en} names "${a}", but the form "${o.form}" has no view "${o.view}".`})]}}}s(jP,"viewIssues");function VP(e,n){let t=[],r=new Set(ed(e.nodes).keys());for(let i of e.nodes){if(i.view!==void 0){let o={de:`Knoten "${i.id}"`,en:`node "${i.id}"`};i.type!=="decision"?t.push(pa(`nodes.${i.id}.view`,{de:`[view/invalid] ${o.de}: 'view' am Knoten gilt nur f\xFCr eine Entscheidung; eine Aufgabe tr\xE4gt ihre eigene.`,en:`[view/invalid] ${o.en}: 'view' on a node applies to a decision only; a task carries its own.`})):t.push(...jP(i.view,`nodes.${i.id}.view`,o,r,n))}for(let o of Array.isArray(i.tasks)?i.tasks:[]){if(o.view===void 0)continue;let a=String(o.key);t.push(...jP(o.view,`nodes.${i.id}.tasks.${a}.view`,{de:`Task "${a}" (Knoten "${i.id}")`,en:`Task "${a}" (node "${i.id}")`},r,n))}}return t}s(VP,"checkTaskViews");var Dt="traeger",BP={de:"Tr\xE4ger",en:"Provider"};function ma(e){let n=e.inputs?.[Dt];return n?.kind==="literal"&&typeof n.value=="string"&&n.value.length>0?n.value:null}s(ma,"traegerKeyOfNode");var xp={name:"input.traeger.name",address:"input.traeger.anschrift"},Tye=Object.values(xp);var UP="governedDocument",qo="prepareDocument",nd="prepareDocument:revision",Kr="releaseApproval",Ko="documentResponse",Yi="coverLetterResponse",Sp="confirmCoverLetter",Ap="requestCoverLetterRevision",ha="coverLetterConfirmation",jr="responseCheck",Ep="returnSigned";var GP="requestApproval";var zP="issueDocument",WP="correctInPlace",YP="rescindAndReissue",Tp="requestChange";var ga="releaseArtifact",ft="signingRecovery",$p="resendESignature",jo="switchToPaper";var nk=new Set([qo,nd]),HP=["pending","producing","producingHeld","deferred","awaitingApproval","awaitingCoverLetter","awaitingResponse","responseReturned","responseInCheck","awaitingSignature","signatureStalled","done"],Rp=["upload","resolver","template","none"],Vo=1,Bo=366,pi="responseDueInDays";function Uo(e){let n=e.inputs?.[ha];return n?.kind==="literal"&&n.value===!0}s(Uo,"coverLetterConfirmationOf");function td(e){let n=e.inputs?.[pi];return n?.kind==="literal"&&rd(n.value)?n.value:void 0}s(td,"responseDueInDaysForVocabulary");function rd(e){return typeof e=="number"&&Number.isInteger(e)&&e>=Vo&&e<=Bo}s(rd,"isValidResponseDueInDays");var Ip=["generatedAt","responseDueInDays","countersignature"],Go=["release","none"],Op=["confirm","signedUpload","signedUploadChecked","eSignature"];var aJ={kind:"confirm",acceptOutcomeId:"accepted",declineOutcomeId:"declined",outcomeSemantics:{accept:"granted",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!1,declineIsAnswer:!0,acceptStatus:"accepted",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Annehmen",en:"Accept"},decline:{de:"Ablehnen",en:"Decline"}}},JP={kind:"signedUpload",acceptOutcomeId:"signed",declineOutcomeId:"absage",outcomeSemantics:{accept:"other",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!0,declineIsAnswer:!1,acceptStatus:"signed",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Unterschrieben zur\xFCcksenden",en:"Return signed"},decline:{de:"Ablehnen",en:"Decline"}}},QP={...JP,kind:"signedUploadChecked",acceptEvent:"contractEvent",checksReturn:!0},lJ={...QP,kind:"eSignature",issuesBy:"provider"},mi={confirm:aJ,signedUpload:JP,signedUploadChecked:QP,eSignature:lJ};function hi(e){let n=e.responseStrategy;if(typeof n=="string"&&n in mi)return mi[n];L(`governedDocument node "${e.id}" declares no valid responseStrategy (got ${JSON.stringify(n)}) \u2014 publish validation should have blocked this; corrupt pinned graph`)}s(hi,"responseStrategyOf");function _p(e){if(e.type!==UP||e.production!=="resolver")return!1;let n=e.responseStrategy;return typeof n=="string"&&n in mi?mi[n].acceptEvent==="contractEvent":!1}s(_p,"isFamilySignedContractNode");function wa(e){return e.label}s(wa,"governedDocTitle");function tk(e){return e.approval==="release"?GP:zP}s(tk,"submitActionId");function ZP(e,n,t){return{key:n,recipient:"internal",title:t,unlocks:[tk(e)],gatesNode:!0,advancesNode:!0}}s(ZP,"producerTemplate");function dJ(e){return e.titles?.respond??e.label}s(dJ,"responseTitle");var ya={de:"\u27E8Titel fehlt\u27E9",en:"\u27E8title missing\u27E9"};function Np(e){let n=hi(e),t=[];if(e.production!=="none"&&t.push(ZP(e,qo,e.titles?.prepare??ya),ZP(e,nd,e.titles?.revise??ya)),e.approval==="release"&&t.push({key:Kr,recipient:"internal",title:e.titles?.approve??ya,unlocks:[],verdictResolved:!0,gatesNode:!0,advancesNode:!0}),t.push({key:Ko,recipient:"external",title:dJ(e),unlocks:n.producesResponseArtifact?[n.checksReturn?Ep:n.acceptOutcomeId,n.declineOutcomeId,Tp]:[n.acceptOutcomeId,n.declineOutcomeId],advancesNode:!0,...td(e)!==void 0?{dueInDays:td(e)}:{}}),Uo(e)){let r=wa(e);t.push({key:Yi,recipient:"external",title:{de:`${r.de}: Angebot best\xE4tigen`,en:`${r.en}: confirm offer`},unlocks:[Sp,Ap,n.declineOutcomeId],advancesNode:!0,...td(e)!==void 0?{dueInDays:td(e)}:{}})}if(n.checksReturn&&t.push({key:jr,recipient:"internal",title:e.titles?.check??ya,unlocks:[],verdictResolved:!0,gatesNode:!1,advancesNode:!0}),n.issuesBy==="provider"){let r=wa(e);t.push({key:ft,recipient:"internal",title:{de:`${r.de}: elektronische Unterschrift kl\xE4ren`,en:`${r.en}: resolve the e-signature`},unlocks:[$p,jo],gatesNode:!1,advancesNode:!1})}return t}s(Np,"governedDocIntrinsicTemplates");function cJ(e){e.production==="none"&&L(`governedDocSlot: node "${e.id}" has production 'none' \u2014 it governs no artifact slot`);let n=e.artifacts??[];n.length!==1&&L(`governedDocSlot: node "${e.id}" declares ${n.length} artifact slots \u2014 exactly ONE is required (publish validation [governedDocument/slotContract])`);let t=n[0];return(typeof t.key!="string"||t.key.length===0)&&L(`governedDocSlot: node "${e.id}" declares an artifact slot without a key \u2014 corrupt pinned graph`),t}s(cJ,"governedDocSlot");function Pp(e){return cJ(e).key}s(Pp,"governedDocSlotKey");var Xt="processFooter";var Cp="countersign",rk="countersign",XP="countersigned",eC="countersigning",nC="countersigned";var tC={de:"Vertrag gegenzeichnen",en:"Countersign the contract"},id=["scan","eSignature"],Dp="service_provider:1",rC=["countersigning","awaitingSignature","signatureStalled","done"],iC={de:"Elektronische Gegenzeichnung kl\xE4ren",en:"Resolve the electronic countersignature"};function oC(e){return{de:`[countersign/traegerSignatoryMissing] Die Schule zeichnet elektronisch gegen, aber f\xFCr ${e} ist keine Unterschriftsperson hinterlegt, die unterschreiben kann (Rechtstr\xE4ger \u2192 signatoryUserKey, aktives Personal der Schule).`,en:`[countersign/traegerSignatoryMissing] The school countersigns electronically, but no signatory who can sign is on file for ${e} (legal entity \u2192 signatoryUserKey, active staff of the school).`}}s(oC,"traegerSignatoryMissingReason");function er(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(er,"issue");function Fp(e,n){return e.nodes.filter(t=>{let r=t.contract;return t.type==="countersign"&&be(r)&&r.scope==="node"&&r.owner===n})}s(Fp,"countersignersOf");function od(e){return e.signing==="eSignature"}s(od,"isElectronic");function uJ(e,n){if(n===void 0||n.sendable||!od(e))return[];let t=e.label?.de??e.id,r=e.label?.en||e.id;return[er(e,"signing",{de:`[countersign/eSignatureNeedsProvider] \u201E${t}\u201C zeichnet elektronisch gegen, aber die Schule kann nicht senden: ${n.reason.de}`,en:`[countersign/eSignatureNeedsProvider] "${r}" countersigns electronically, but the school cannot send: ${n.reason.en}`})]}s(uJ,"countersignProviderIssues");function fJ(e,n,t){if(t.scope!=="node")return[];let r=e.nodes.find(o=>o.id===t.owner);if(r===void 0)return[];let i=[];return _p(r)||i.push("sourceNotCheckedContract"),Fp(e,r.id).some(o=>o.id!==n)&&i.push("twice"),i}s(fJ,"countersignContractRefusals");function sC(e){let n=e.inputs?.dueInDays;return n?.kind==="literal"&&typeof n.value=="number"&&Number.isInteger(n.value)&&n.value>=1?n.value:void 0}s(sC,"validDueInDays");function pJ(e,n,t){let r=e.label?.de??e.id,i=e.label?.en||e.id,o=e.signing;if(o!==void 0&&!id.includes(o))return[er(e,"signing",{de:`[countersign/unknownSigning] \u201E${r}\u201C: signing ist scan oder eSignature (gefunden: ${JSON.stringify(o)}).`,en:`[countersign/unknownSigning] "${i}": signing is scan or eSignature (found: ${JSON.stringify(o)}).`})];let a=e.assign?.[ft];if(!od(e))return a===void 0?[]:[er(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet auf Papier gegen \u2014 \`assign.signingRecovery\` h\xE4lt keine Aufgabe und geh\xF6rt entfernt.`,en:`[countersign/recoveryAssign] "${i}" countersigns on paper \u2014 \`assign.signingRecovery\` holds no task and must be removed.`})];let l=[];return(typeof a!="string"||a.length===0)&&l.push(er(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet elektronisch gegen \u2014 wer eine gescheiterte Gegenzeichnung kl\xE4rt, fehlt: \`assign.signingRecovery\` nennt das Team.`,en:`[countersign/recoveryAssign] "${i}" countersigns electronically \u2014 who resolves a failed countersignature is missing: \`assign.signingRecovery\` names the team.`})),l.push(...mJ(e,n,t),...hJ(e,n,t),...uJ(e,t?.signingProvider)),l}s(pJ,"signingIssues");function lC(e,n){let t=e.contract;if(!(!be(t)||t.scope!=="node"))return n.nodes.find(r=>r.id===t.owner)}s(lC,"contractNodeOf");function mJ(e,n,t){let r=lC(e,n),i=r===void 0?null:ma(r),o=i===null?void 0:t?.traeger?.get(i);return o===void 0||o.hasSignatory?[]:[er(e,"signing",oC(o.name))]}s(mJ,"traegerSignatoryIssues");function hJ(e,n,t){let r=lC(e,n);if(r===void 0)return[];let i=t?.resolverDocumentAnchors?.get(r.id);if(i===void 0)return[];let o=e.label?.de??e.id,a=e.label?.en||e.id,l=[];for(let d of i)d.documentAnchors===null?l.push(er(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage des Generators \u201E${d.pin}\u201C wurde nie auf Unterschriftsanker gelesen \u2014 Vorlage neu hochladen und den Generator neu versiegeln.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of generator "${d.pin}" was never read for signature anchors \u2014 upload the template again and seal the generator again.`})):d.documentAnchors.has(Dp)||l.push(er(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage von \u201E${d.pin}\u201C tr\xE4gt keinen Anker /unterschrift:${Dp}/ \u2014 der Anbieter f\xE4nde f\xFCr die Schule kein Unterschriftsfeld.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of "${d.pin}" carries no anchor /unterschrift:${Dp}/ \u2014 the provider would find no signature field for the school.`}));return l}s(hJ,"traegerAnchorIssues");var ik=100;async function gJ(e,n){let t=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",o=>o.eq("context.applicationId",n.applicationId).eq("context.anchor.nodeId",n.node.id)).take(ik+1);t.length>ik&&L(`countersign node "${n.node.id}" of ${n.applicationId} holds more than ${ik} rows`);let r=t.filter(o=>o.isOpen),i=s(o=>{if(o.context.kind!=="admission")return;let a=o.context.anchor;return"templateKey"in a?a.templateKey:void 0},"templateKeyOf");return r.some(o=>i(o)===ft)?"signatureStalled":r.some(o=>i(o)===Cp)?"countersigning":od(n.node)?"awaitingSignature":"done"}s(gJ,"countersignCurrentState");var aC={[eC]:{label:te("Gegenzeichnung","Countersignature"),tone:"teal",phase:{key:"gegenzeichnung",label:te("Gegenzeichnung","Countersignature"),scope:"node"},external:Xe(te("Vertrag unterschrieben","Contract signed"),"blue",te("Die Schule zeichnet Ihren Vertrag gegen","The school is countersigning your contract"),te("Vielen Dank f\xFCr Ihre Unterschrift. Sobald die Schule gegengezeichnet hat, finden Sie Ihr Exemplar hier.","Thank you for signing. As soon as the school has countersigned, you will find your copy here."))}},dC={inputs:s(()=>[{id:"dueInDays",label:{de:"Frist der Aufgabe (Tage)",en:"Task due in (days)"},type:"number",inspector:"literal-only"}],"inputs"),role:"user-action",effect:"side-effect",outcomes:[{id:XP,label:{de:"Gegengezeichnet",en:"Countersigned"}}],progressDefaults:aC,progressEvents:Ln(aC),notificationEvents:s(()=>[{id:nC,label:{de:"Vertrag gegengezeichnet",en:"Contract countersigned"},audience:"external",required:!0,args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0}]}],"notificationEvents"),actions:s(e=>[{id:rk,kind:"internal",label:tC,surface:Xt,availableIn:["countersigning"]},...od(e)?[{id:jo,kind:"internal",surface:Xt,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}]:[]],"actions"),workItemTemplates:s(e=>[{key:Cp,recipient:"internal",title:e.titles?.countersign??ya,unlocks:[rk],advancesNode:!0,...sC(e)!==void 0?{dueInDays:sC(e)}:{}},...od(e)?[{key:ft,recipient:"internal",title:iC,unlocks:[jo],gatesNode:!1,advancesNode:!1}]:[]],"workItemTemplates"),states:rC,currentState:gJ,validate:s((e,n,t)=>{let r=[],i=e.label?.de??e.id,o=e.label?.en||e.id,a=e.assign?.[Cp];(typeof a!="string"||a.length===0)&&r.push(er(e,"assign",{de:`[countersign/assign] \u201E${i}": wer gegenzeichnet, fehlt \u2014 \`assign.countersign\` nennt das Team.`,en:`[countersign/assign] "${o}": who countersigns is missing \u2014 \`assign.countersign\` names the team.`})),Pi(e.titles?.countersign)||r.push(er(e,"titles",{de:`[countersign/missingTitle] \u201E${i}": der Titel der Aufgabe fehlt \u2014 \`titles.countersign\` auf Deutsch und Englisch.`,en:`[countersign/missingTitle] "${o}": the task title is missing \u2014 \`titles.countersign\` in German and English.`}));let l=e.inputs?.dueInDays;l!==void 0&&l.kind!=="unset"&&!(l.kind==="literal"&&typeof l.value=="number"&&Number.isInteger(l.value)&&l.value>=1)&&r.push(er(e,"inputs.dueInDays",{de:`[countersign/dueInDays] \u201E${i}": dueInDays ist eine ganze Zahl \u2265 1.`,en:`[countersign/dueInDays] "${o}": dueInDays is a whole number \u2265 1.`})),r.push(...pJ(e,n,t));let d=e.contract;if(!be(d))return r;let c=fJ(n,e.id,d);if(c.length===0)return r;let u=n.nodes.find(p=>d.scope==="node"&&p.id===d.owner);if(c.includes("sourceNotCheckedContract")&&r.push(er(e,"contract",{de:`[countersign/sourceNotCheckedContract] \u201E${i}" zeichnet das Dokument von \u201E${u.label?.de??u.id}" (${u.id}) gegen \u2014 gegenzeichnen l\xE4sst sich nur ein erzeugter Vertrag, den die Familie mit verbuchten Unterschriften unterschreibt (governedDocument mit production: resolver und responseStrategy: signedUploadChecked oder eSignature).`,en:`[countersign/sourceNotCheckedContract] "${o}" countersigns the document of "${u.label?.en||u.id}" (${u.id}) \u2014 only a generated contract that the family signs with booked signatures can be countersigned (governedDocument with production: resolver and responseStrategy: signedUploadChecked or eSignature).`})),c.includes("twice")){let p=Fp(n,u.id).filter(h=>h.id!==e.id);r.push(er(e,"contract",{de:`[countersign/twice] \u201E${i}": \u201E${u.label?.de??u.id}" (${u.id}) wird schon von ${p.map(h=>`"${h.id}"`).join(", ")} gegengezeichnet \u2014 ein Vertrag hat eine Gegenzeichnung.`,en:`[countersign/twice] "${o}": "${u.label?.en||u.id}" (${u.id}) is already countersigned by ${p.map(h=>`"${h.id}"`).join(", ")} \u2014 a contract has one countersignature.`}))}return r},"validate")};function yJ(e){return _p(e)?ma(e):null}s(yJ,"traegerSignerOf");var wJ=s(e=>e.type==="end"&&Co(e)==="approved","isApprovedEnd");function cC(e){let n=[];for(let t of e.nodes){let r=yJ(t);if(r===null)continue;let i=Fp(e,t.id).map(u=>u.id),o=w_(e,t.id,new Set(i),wJ);if(o===null)continue;let a=t.label?.de||t.id,l=t.label?.en||t.id,d={de:`Einen Knoten \u201EUnterschrift (intern)\u201C (countersign) mit contract: $node.${t.id}.contract auf jeden Weg zu einem Ende mit Ergebnis approved setzen.`,en:`Place an "Internal signature" node (countersign) with contract: $node.${t.id}.contract on every path to an end with outcome approved.`},c=i.length===0?{de:`[countersign/missingForContract] \u201E${a}\u201C (${t.id}) erzeugt einen Vertrag, den der Tr\xE4ger \u201E${r}\u201C mitunterschreibt, aber keine Gegenzeichnung nennt ihn \u2014 der Vertrag w\xFCrde nie unterschrieben und nie abgerechnet. ${d.de}`,en:`[countersign/missingForContract] "${l}" (${t.id}) generates a contract the legal entity "${r}" co-signs, but no countersignature names it \u2014 the contract would never be signed and never billed. ${d.en}`}:{de:`[countersign/missingForContract] \u201E${a}\u201C (${t.id}): ein Weg erreicht das Ende \u201E${o}\u201C (Ergebnis approved), ohne durch die Gegenzeichnung ${i.map(u=>`\u201E${u}\u201C`).join(", ")} zu laufen \u2014 dort bliebe der Vertrag ohne Unterschrift des Tr\xE4gers \u201E${r}\u201C und w\xFCrde nie abgerechnet. ${d.de}`,en:`[countersign/missingForContract] "${l}" (${t.id}): a path reaches the end "${o}" (outcome approved) without passing the countersignature ${i.map(u=>`"${u}"`).join(", ")} \u2014 there the contract would lack the signature of the legal entity "${r}" and never be billed. ${d.en}`};n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}`,reason:c,severity:"error"})}return n}s(cC,"checkCountersignCoverage");var kJ=[{key:"blocks",why:{de:"sie h\xE4lt nichts zur\xFCck, sie ist mit dem Ausl\xF6sen erledigt",en:"it holds nothing back, it is done with the press"}},{key:"when",why:{de:"sie entsteht bei jedem Ausl\xF6sen",en:"it is created on every press"}},{key:"optional",why:{de:"wer ausl\xF6st, beantwortet sie immer",en:"whoever presses always answers it"}},{key:"appointment",why:{de:"sie wird beim Ausl\xF6sen beantwortet, nicht bei einem Termin",en:"it is answered at the press, not at an appointment"}},{key:"familyRequest",why:{de:"sie fragt nicht die Familie",en:"it does not ask the family"}},{key:"feedback",why:{de:"sie beantwortet die ausl\xF6sende Person, nicht ein Link",en:"the presser answers it, not a link"}},{key:"completableIf",why:{de:"sie wird beim Ausl\xF6sen erledigt, eine Vorbedingung w\xFCrde jedes Ausl\xF6sen ablehnen",en:"it is completed at the press, a precondition would refuse every press"}},{key:"locksEvidence",why:{de:"eine offene Korrektur w\xFCrde jedes Ausl\xF6sen ablehnen",en:"an open correction would refuse every press"}}];function uC(e){let{nodeId:n,bindingKey:t,binding:r}=e;if(r.input===void 0)return[];let i=[],o=`nodes.${n}.optionalActions.${t}.input`,a=s(y=>{i.push({layer:"GRAPH",kind:"nodeRule",path:o,severity:"error",reason:{de:`[optionalAction/input] Optionale Aktion "${t}" auf Knoten "${n}": ${y.de}`,en:`[optionalAction/input] Optional action "${t}" on node "${n}": ${y.en}`}})},"push"),l=r.input;if(typeof l!="string"||l.trim().length===0)return a({de:"'input' muss der Schl\xFCssel einer ihrer Aufgaben sein.",en:"'input' must be the key of one of its tasks."}),i;let d=Array.isArray(r.tasks)?r.tasks:[];if(!d.includes(l))return a({de:`Die Eingabe "${l}" ist keine ihrer Aufgaben ('tasks') \u2014 die Eingabe geh\xF6rt zur Runde der Aktion.`,en:`The input "${l}" is none of its tasks ('tasks') \u2014 the input belongs to the action's round.`}),i;let c=s(y=>{let k=e.templates.find(w=>w.key===y);return k!==void 0&&k.optional===void 0&&k.blocks===void 0},"holdsNode");d.some(y=>y!==l&&c(y))||a({de:`Neben der Eingabe "${l}" hat die Aktion keine Aufgabe, die den Schritt zur\xFCckh\xE4lt (weder 'optional' noch hinter 'blocks') \u2014 die Runde w\xE4re mit dem Ausl\xF6sen schon erledigt.`,en:`Besides the input "${l}" the action has no task that holds the step (neither 'optional' nor behind 'blocks') \u2014 the round would be done with the press.`});let u=e.templates.find(y=>y.key===l);if(u===void 0)return i;u.result?.kind!=="record"&&a({de:`Die Eingabe "${l}" braucht ein Ergebnis der Art 'record' \u2014 nur dessen Werte lesen die anderen Aufgaben der Runde.`,en:`The input "${l}" needs a result of kind 'record' \u2014 only its values are read by the round's other tasks.`});let p=u.assign?.group;typeof r.trigger!="string"?a({de:"Mit einer Eingabe braucht die Aktion ein 'trigger'-Team \u2014 die Eingabe ist eine Aufgabe dieses Teams.",en:"With an input the action needs a 'trigger' team \u2014 the input is a task of that team."}):p!==void 0&&p!==r.trigger&&a({de:`Die Eingabe "${l}" geh\xF6rt dem Team "${String(p)}", ausgel\xF6st wird die Aktion vom Team "${r.trigger}" \u2014 wer ausl\xF6st, beantwortet die Eingabe, also ist es dasselbe Team.`,en:`The input "${l}" belongs to the team "${String(p)}", the action is pressed by the team "${r.trigger}" \u2014 whoever presses answers the input, so it is the same team.`});let h=u.result?.fields;for(let y of Array.isArray(h)?h:[])y.evidence===!0&&a({de:`Das Feld "${String(y.key)}" der Eingabe "${l}" verlangt eine Datei ('evidence') \u2014 das Ausl\xF6sen tr\xE4gt nur Werte.`,en:`The field "${String(y.key)}" of the input "${l}" demands a file ('evidence') \u2014 the press carries values only.`});for(let{key:y,why:k}of kJ)u[y]!==void 0&&a({de:`Die Eingabe "${l}" tr\xE4gt '${y}' \u2014 ${k.de}.`,en:`The input "${l}" carries '${y}' \u2014 ${k.en}.`});for(let y of e.templates){let k=y.blocks;k?.templateKey!==l||k.node!==void 0&&k.node!==n||a({de:`"${String(y.key)}" h\xE4lt die Eingabe "${l}" per 'blocks' zur\xFCck \u2014 sie ist beim Anlegen der Runde schon erledigt, es gibt nichts zur\xFCckzuhalten.`,en:`"${String(y.key)}" holds the input "${l}" back through 'blocks' \u2014 it is already done when the round is created, there is nothing to hold back.`})}return i}s(uC,"optionalActionInputIssues");function bJ(e){let n="error",t=new Map;for(let a of Zt(e.nodes)){let l=t.get(a.source)??[];l.push({id:a.id,target:a.target}),t.set(a.source,l)}let r=[],i=new Set,o=hp(e.nodes.map(a=>a.id),a=>(t.get(a)??[]).map(({id:l,target:d})=>({target:d,edge:l})));for(let a of o)i.has(a.edge)||(i.add(a.edge),r.push({layer:"GRAPH",kind:"cycle",path:`edge.${a.edge}`,reason:{de:`Zyklus \xFCber Kante ${a.source} \u2192 ${a.target}`,en:`Cycle through edge ${a.source} \u2192 ${a.target}`},severity:n}));return r}s(bJ,"checkAcyclic");function vJ(e){let n=[],t=new Set(e.nodes.map(i=>i.id)),r="error";for(let i of e.nodes){let o=i.next;if(o)for(let[a,l]of Object.entries(o))t.has(l.to)||n.push({layer:"GRAPH",kind:"routing",path:`node.${i.id}.next.${a}`,reason:{de:`${i.label.de}: next.${a} verweist auf nicht-existenten Knoten '${l.to}'`,en:`${i.label.en}: next.${a} points to a node that does not exist: '${l.to}'`},severity:"error"});if(i.type!=="end"&&!(!i.outcomes||i.outcomes.length===0))for(let a of i.outcomes)(!o||!(a.id in o))&&n.push({layer:"GRAPH",kind:"routing",path:`node.${i.id}.outcome.${a.id}`,reason:{de:`${i.label.de}: Outcome '${a.label.de}' fehlt im next-Mapping`,en:`${i.label.en}: outcome '${a.label.en}' is missing from the next mapping`},severity:r})}return n}s(vJ,"checkNextTargets");function xJ(e){let n=[];for(let t of e.nodes){let r=t.next;if(!r)continue;let i=mw(t),o=new Set(i?i.map(a=>a.id):[ea]);for(let a of Object.keys(r))o.has(a)||n.push({layer:"GRAPH",kind:"unknownOutcome",path:`node.${t.id}.next.${a}`,reason:{de:`${t.label.de}: next-Schl\xFCssel '${a}' ist kein g\xFCltiges Outcome dieses Knotens (erlaubt: ${[...o].join(", ")}) \u2014 die Kante w\xFCrde im Editor verschwinden`,en:`${t.label.en}: next key '${a}' is not a valid outcome of this node (allowed: ${[...o].join(", ")}) \u2014 the edge would disappear in the editor`},severity:"error"})}return n}s(xJ,"checkNextOutcomesKnown");function SJ(e){let n=[],t=new Set(Zt(e.nodes).map(o=>o.target)),r=e.nodes.filter(o=>!t.has(o.id));return r.length===0?n.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:"Kein Start-Knoten",en:"No start node"},severity:"error"}):r.length>1&&n.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:`Mehrere Start-Knoten (${r.map(o=>o.label.de).join(", ")})`,en:`Multiple start nodes (${r.map(o=>o.label.en).join(", ")})`},severity:"warning"}),e.nodes.filter(o=>o.type==="end").length===0&&n.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:"Kein End-Knoten",en:"No end node"},severity:"warning"}),n}s(SJ,"checkStartEnd");function AJ(e){let n=new Map;for(let r of Zt(e.nodes))n.set(r.source,(n.get(r.source)??0)+1);let t=[];for(let r of e.nodes)r.type!=="end"&&(n.get(r.id)??0)===0&&t.push({layer:"GRAPH",kind:"startEnd",path:`node.${r.id}`,reason:{de:`${r.label.de}: keine ausgehende Kante`,en:`${r.label.en}: no outgoing edge`},severity:"warning"});return t}s(AJ,"checkNoOutgoingEdge");function EJ(e){return e.nodes.filter(n=>!gy(n.id)).map(n=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${n.id}.id`,reason:{de:`[graph/nodeIdFormat] Knoten "${n.id}": eine Knoten-ID ist ein Bezeichner ohne Punkt (${hr.source}), z. B. "reviewEingereicht". Ein Bundle von vor der Umstellung neu exportieren.`,en:`[graph/nodeIdFormat] Node "${n.id}": a node id is an identifier without a dot (${hr.source}), e.g. "reviewSubmitted". Export a bundle from before the change again.`},severity:"error"}))}s(EJ,"checkNodeIdFormat");function TJ(e){let n=new Set(e.nodes.map(r=>r.id)),t=[];for(let r of Zt(e.nodes))n.has(r.source)||t.push({layer:"GRAPH",kind:"startEnd",path:`edge.${r.id}`,reason:{de:`Kante ${r.id}: Quelle '${r.source}' nicht gefunden`,en:`Edge ${r.id}: source '${r.source}' not found`},severity:"error"}),n.has(r.target)||t.push({layer:"GRAPH",kind:"startEnd",path:`edge.${r.id}`,reason:{de:`Kante ${r.id}: Ziel '${r.target}' nicht gefunden`,en:`Edge ${r.id}: target '${r.target}' not found`},severity:"error"});return t}s(TJ,"checkEdgeEndpoints");var $J=new Set(["countersignature"]);function RJ(e){let n=[],t=s((o,a)=>{n.push({layer:"GRAPH",kind:"nodeRule",path:o,reason:{de:`[graph/retiredField] ${a.de}`,en:`[graph/retiredField] ${a.en}`},severity:"error"})},"retired"),r={de:"Preise rechnet der Vertragsgenerator (`prices`), nicht der Workflow \u2014 binde Rang und Reduktion an seine Eing\xE4nge.",en:"Prices are computed by the contract generator (`prices`), not the workflow \u2014 bind rank and reduction to its inputs."},i=e;"pricingRules"in i&&t("pricingRules",r);for(let[o,a]of(Array.isArray(i.processStore)?i.processStore:[]).entries())for(let l of["derive","absentValue"])a!==null&&typeof a=="object"&&l in a&&t(`processStore.${o}.${l}`,r);for(let o of e.nodes)for(let a of o.tasks??[]){let l=a.result;l!==null&&typeof l=="object"&&"prices"in l&&t(`nodes.${o.id}.tasks.${a.key}.result.prices`,r)}for(let o of e.nodes){let a=o,l={de:`Knoten \u201E${_e(e,o.id,"de")}\u201C (${o.id})`,en:`Node "${_e(e,o.id,"en")}" (${o.id})`};for(let[c,u]of Object.entries(a.next??{}))u!==null&&typeof u=="object"&&"emits"in u&&t(`nodes.${o.id}.next.${c}.emits`,{de:`${l.de}: \`next.${c}.emits\` gibt es nicht mehr \u2014 ein Ausgang routet nur; ein Knoten liest Daten \xFCber Adressen in seinen eigenen Feldern.`,en:`${l.en}: \`next.${c}.emits\` no longer exists \u2014 an outcome only routes; a node reads data through addresses in its own fields.`});for(let c of Array.isArray(a.outcomes)?a.outcomes:[])c!==null&&typeof c=="object"&&"emits"in c&&t(`nodes.${o.id}.outcomes.${String(c.id)}.emits`,{de:`${l.de}: \`emits\` am Ausgang "${String(c.id)}" gibt es nicht mehr \u2014 ein Knoten liest Daten \xFCber Adressen in seinen eigenen Feldern.`,en:`${l.en}: \`emits\` on the outcome "${String(c.id)}" no longer exists \u2014 a node reads data through addresses in its own fields.`});"targetFormNodeId"in a&&t(`nodes.${o.id}.targetFormNodeId`,{de:`${l.de}: \`targetFormNodeId\` gibt es nicht mehr \u2014 welches Formular freigeschaltet wird, sagt die Adresse, an die der Eingang \`inputs.target\` gebunden ist ($node.<formular>.admission).`,en:`${l.en}: \`targetFormNodeId\` no longer exists \u2014 the address the input \`inputs.target\` is bound to says which form is unlocked ($node.<form>.admission).`}),"wires"in a&&t(`nodes.${o.id}.wires`,{de:`${l.de}: Datenkanten (\`wires\`) gibt es nicht mehr \u2014 jedes Feld, das Daten eines anderen Knotens liest, tr\xE4gt selbst die volle Adresse ($node.\u2026, $task.\u2026, $env.\u2026).`,en:`${l.en}: data edges (\`wires\`) no longer exist \u2014 every field that reads data of another node carries the full address itself ($node.\u2026, $task.\u2026, $env.\u2026).`});for(let[c,u]of Object.entries(a.inputs??{}))u!==null&&typeof u=="object"&&u.kind==="binding"&&"path"in u&&t(`nodes.${o.id}.inputs.${c}.path`,{de:`${l.de}: Der Eingang \u201E${c}\u201C ist \xFCber einen Pfad (\`path\`) gebunden \u2014 eine Bindung tr\xE4gt die volle Adresse (\`address\`) dessen, was sie liest.`,en:`${l.en}: The input "${c}" is bound through a path (\`path\`) \u2014 a binding carries the full address (\`address\`) of what it reads.`});o.type==="governedDocument"&&"resolver"in a&&t(`nodes.${o.id}.resolver`,{de:`${l.de}: \`resolver\` gibt es nicht mehr \u2014 der Generator ist der Eingang \`inputs.contractGenerator\` ({ kind, key }), seine Parameter stempelt die Plattform (\`generatorStamp\`), ein im Cockpit erg\xE4nzter Parameter ist sein Eingang \`{ kind: "cockpit" }\`.`,en:`${l.en}: \`resolver\` no longer exists \u2014 the generator is the input \`inputs.contractGenerator\` ({ kind, key }), the platform stamps its parameters (\`generatorStamp\`), a parameter completed in the cockpit is its input \`{ kind: "cockpit" }\`.`});let d=a.template;if(o.type==="governedDocument"&&d!==null&&typeof d=="object")for(let c of["key","cockpitFields"])c in d&&t(`nodes.${o.id}.template.${c}`,{de:`${l.de}: \`template.${c}\` gibt es nicht mehr \u2014 ${c==="key"?"die Vorlage ist der Eingang `inputs.documentTemplate`":'ein im Cockpit erg\xE4nzter Parameter ist sein Eingang `{ kind: "cockpit" }`'}.`,en:`${l.en}: \`template.${c}\` no longer exists \u2014 ${c==="key"?"the template is the input `inputs.documentTemplate`":'a parameter completed in the cockpit is its input `{ kind: "cockpit" }`'}.`});if(o.type==="setFlag")for(let c of["target","flagKey","value"])c in a&&t(`nodes.${o.id}.${c}`,{de:`${l.de}: \`${c}\` gibt es am setFlag-Knoten nicht mehr \u2014 Formular, Merkmal und Wert sind die Eing\xE4nge \`inputs.target\` (gebunden an die Adresse $node.<formular>.admission), \`inputs.flagKey\` und \`inputs.value\` (feste Werte).`,en:`${l.en}: \`${c}\` no longer exists on a setFlag node \u2014 form, flag and value are the inputs \`inputs.target\` (bound to the address $node.<form>.admission), \`inputs.flagKey\` and \`inputs.value\` (literals).`});for(let c of Object.keys(Hy[o.type]??{}))c in a&&t(`nodes.${o.id}.${c}`,{de:`${l.de}: \`${c}\` gibt es als Knoteneigenschaft nicht mehr \u2014 es ist der Eingang \`inputs.${c}\` (ein fester Wert im Parameter-Bereich).`,en:`${l.en}: \`${c}\` no longer exists as a node property \u2014 it is the input \`inputs.${c}\` (a fixed value among the parameters).`});for(let c of Array.isArray(a.tasks)?a.tasks:[]){let u=c?.assign;u===null||typeof u!="object"||!("userId"in u)||t(`nodes.${o.id}.tasks.${String(c.key)}.assign.userId`,{de:`Aufgabe "${String(c.key)}" an ${l.de}: \`assign.userId\` gibt es nicht mehr \u2014 eine Aufgabe nennt ihr Team (\`assign.group\`), nie eine feste Person.`,en:`Task "${String(c.key)}" on ${l.en}: \`assign.userId\` no longer exists \u2014 a task names its team (\`assign.group\`), never a fixed person.`})}for(let c of Jy[o.type]??[])c in a&&t(`nodes.${o.id}.${c}`,{de:`${l.de}: \`${c}\` gibt es nicht mehr \u2014 dieser Knotentyp liest es nicht.`,en:`${l.en}: \`${c}\` no longer exists \u2014 this node type does not read it.`});for(let[c,u]of Object.entries(HO[o.type]??{}))c in a&&t(`nodes.${o.id}.${c}`,{de:`${l.de}: ${u.de}`,en:`${l.en}: ${u.en}`});a.adoptForm===!0&&t(`nodes.${o.id}.adoptForm`,{de:`${l.de}: \`adoptForm: true\` gibt es nicht mehr \u2014 \`adoptForm\` ist die Adresse des \xFCbernommenen Formulars ($node.<anlegender Formularknoten>.admission).`,en:`${l.en}: \`adoptForm: true\` no longer exists \u2014 \`adoptForm\` is the address of the adopted form ($node.<creating form node>.admission).`});for(let c of Array.isArray(a.tasks)?a.tasks:[]){let u=c?.result?.kind;typeof u=="string"&&$J.has(u)&&t(`nodes.${o.id}.tasks.${String(c.key)}.result`,{de:`Aufgabe "${String(c.key)}" an ${l.de}: das Ergebnis \u201E${u}" gibt es nicht mehr \u2014 die Gegenzeichnung ist der Knotentyp \u201EUnterschrift (intern)" (countersign).`,en:`Task "${String(c.key)}" on ${l.en}: the result "${u}" no longer exists \u2014 the countersignature is the node type "Signature (internal)" (countersign).`})}}return n}s(RJ,"checkRetiredDataFields");function ka(e,n){return n?.wiring&&n.layout?{wiring:n.wiring,layout:n.layout}:null}s(ka,"resolveLayoutContext");function IJ(e,n){let t=ka(e,n);if(!t)return e.nodes.some(o=>(He(o)?.progressEvents?.length??0)>0)?[{layer:"GRAPH",kind:"progressState",path:"graph.progressWiring",reason:{de:`Graph emittiert Progress-Events, aber (Layout, Wiring) konnte nicht aufgel\xF6st werden (Wiring ${n?.wiring?"vorhanden":"fehlt"}, Layout ${n?.layout?"vorhanden":"fehlt"}) \u2014 der Engine wirft beim Spiegeln zur Laufzeit. Der Workflow-Entwurf muss progressLayout und progressWiring tragen.`,en:`The graph emits progress events, but (layout, wiring) could not be resolved (wiring ${n?.wiring?"present":"missing"}, layout ${n?.layout?"present":"missing"}) \u2014 the engine throws at runtime when mirroring. The workflow draft must carry progressLayout and progressWiring.`},severity:"error"}]:[];let r=[];for(let i of e.nodes){let a=He(i)?.progressEvents;if(a)for(let l of a){let d=Hs(t.wiring,{id:i.id,type:i.type},l);if(!d){r.push({layer:"GRAPH",kind:"progressState",path:`node.${i.id}.progressEvents.${l}`,reason:{de:`${i.type} '${i.id}': Progress-Event '${l}' ist im Wiring (Layout '${t.layout.id}') keinem (Bus, State) zugeordnet \u2014 der Engine wirft beim Spiegeln`,en:`${i.type} '${i.id}': progress event '${l}' is not mapped to any (bus, state) in the wiring (layout '${t.layout.id}') \u2014 the engine throws when mirroring`},severity:"error"});continue}let c;try{c=Hf(t.layout,d.bus)}catch{r.push({layer:"GRAPH",kind:"progressState",path:`node.${i.id}.progressEvents.${l}`,reason:{de:`${i.type} '${i.id}': Event '${l}' verweist auf unbekannten Bus '${d.bus}' im Layout '${t.layout.id}'`,en:`${i.type} '${i.id}': event '${l}' points to unknown bus '${d.bus}' in layout '${t.layout.id}'`},severity:"error"});continue}Kl(c,d.state)||r.push({layer:"GRAPH",kind:"progressState",path:`node.${i.id}.progressEvents.${l}`,reason:{de:`${i.type} '${i.id}': Event '${l}' verweist auf State '${d.state}', der nicht im Bus '${d.bus}' deklariert ist`,en:`${i.type} '${i.id}': event '${l}' points to state '${d.state}', which is not declared in bus '${d.bus}'`},severity:"error"})}}return r}s(IJ,"checkProgressEventMappings");function OJ(e,n){let t=ka(e,n);if(!t)return[];let r=[];for(let i of t.layout.buses){if(!i.boards||i.boards.length===0)continue;let o=new Set(i.unboarded??[]),a=new Set;for(let l of i.boards)for(let d of l.columns)for(let c of d.states)a.add(c),Kl(i,c)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.board.${l.id}.column.${d.id}.${c}`,reason:{de:`Board '${l.id}', Spalte '${d.id}' referenziert State '${c}', der nicht im Bus '${i.key}' deklariert ist`,en:`Board '${l.id}', column '${d.id}' references state '${c}', which is not declared in bus '${i.key}'`},severity:"error"});for(let l of i.states)a.has(l.id)||o.has(l.id)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.${l.id}`,reason:{de:`State '${l.id}' (${l.label.de}) erscheint in keiner Board-Spalte und nicht in 'unboarded' \u2014 nicht darstellbar`,en:`State '${l.id}' (${l.label.en}) appears in no board column and not in 'unboarded' \u2014 it cannot be displayed`},severity:"error"})}return r}s(OJ,"checkProgressBoardCoverage");function _J(e,n){let t=ka(e,n);if(!t)return[];let r=[];for(let i of t.layout.buses)if(!(!i.boards||i.boards.length===0))for(let o of i.boards)for(let a of We){let l=new Map;for(let d of o.columns){if(!Pi(d.label))continue;let c=d.label[a],u=c.trim().toLocaleLowerCase(a),p=l.get(u);if(p===void 0){l.set(u,d.id);continue}r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.board.${o.id}.column.${d.id}.label.${a}`,reason:{de:`Board '${o.id}' hat zwei Spalten mit dem Label '${c}' (${a}) ('${p}' und '${d.id}') \u2014 f\xFCr Lesende nicht unterscheidbar. F\xFChre die Spalten zusammen (states beider in EINE Spalte) oder vergib unterschiedliche Labels.`,en:`Board '${o.id}' has two columns with the label '${c}' (${a}) ('${p}' and '${d.id}') \u2014 readers cannot tell them apart. Merge the columns (put the states of both into ONE column) or give them different labels.`},severity:"error"})}}return r}s(_J,"checkProgressBoardDistinctLabels");function NJ(e,n){let t=ka(e,n);if(!t)return[];let r=[];for(let i of t.layout.buses)for(let o of i.states){let a=Jf(i,o.id);o.terminal&&!a&&r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.${o.id}.terminalSemantics`,reason:{de:`Terminal-State '${o.id}' hat keine Terminal-Semantik im Bus '${i.key}' \u2014 der Engine wirft beim Versiegeln`,en:`Terminal state '${o.id}' has no terminal semantics in bus '${i.key}' \u2014 the engine throws when sealing`},severity:"error"}),!o.terminal&&a&&r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.${o.id}.terminalSemantics`,reason:{de:`State '${o.id}' ist nicht terminal, hat aber Terminal-Semantik im Bus '${i.key}' \u2014 Inkonsistenz`,en:`State '${o.id}' is not terminal but has terminal semantics in bus '${i.key}' \u2014 inconsistent`},severity:"error"})}return r}s(NJ,"checkProgressTerminalSemantics");function PJ(e,n){let t=ka(e,n);if(!t)return[];let r=[];for(let i of t.layout.buses){let o=new Set(i.holdsSeat??[]);for(let a of i.holdsSeat??[])Kl(i,a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.holdsSeat.${a}`,reason:{de:`holdsSeat referenziert '${a}', das kein State im Bus '${i.key}' ist`,en:`holdsSeat references '${a}', which is not a state in bus '${i.key}'`},severity:"error"});for(let a of i.commitsSeat??[])Kl(i,a)?o.has(a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.commitsSeat.${a}`,reason:{de:`commitsSeat '${a}' ist nicht in holdsSeat \u2014 ein fest belegter Platz muss auch belegt sein`,en:`commitsSeat '${a}' is not in holdsSeat \u2014 a firmly committed seat must also be held`},severity:"error"}):r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.commitsSeat.${a}`,reason:{de:`commitsSeat referenziert '${a}', das kein State im Bus '${i.key}' ist`,en:`commitsSeat references '${a}', which is not a state in bus '${i.key}'`},severity:"error"});for(let[a,l]of Object.entries(i.terminalSemantics??{}))l.outcome==="approved"&&(o.has(a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.layout.id}.bus.${i.key}.holdsSeat`,reason:{de:`Endzustand '${a}' schlie\xDFt den Prozess positiv ab (outcome 'approved'), steht aber nicht in holdsSeat \u2014 damit z\xE4hlt er als Absage und f\xE4llt aus dem Fortschrittsbalken. Nimm '${a}' in holdsSeat (und in commitsSeat, wenn der Platz damit wirklich belegt ist) auf.`,en:`Final state '${a}' ends the process positively (outcome 'approved'), but is not in holdsSeat \u2014 so it counts as a rejection and drops out of the progress bar. Add '${a}' to holdsSeat (and to commitsSeat, if the seat is really taken by it).`},severity:"error"}))}return r}s(PJ,"checkProgressSeatStates");var Lp={de:"Abhilfe: nach dem Formularknoten einen review-Knoten einf\xFCgen und dessen 'reviewing' auf diesen Zustand mappen",en:"Remedy: insert a review node after the form node and map its 'reviewing' to this state"};function CJ(e){return e==="both"?{de:`${Lp.de} \u2014 die Spalte ist auch der Schritt, den die Familie sieht; den Zustand in die Spalte des Nachfolgers zu legen, n\xE4hme ihr diesen Schritt.`,en:`${Lp.en} \u2014 the column is also the step the family sees; moving the state into the successor's column would take that step away from them.`}:{de:`${Lp.de}, oder den Zustand in die Spalte des Nachfolgers legen.`,en:`${Lp.en}, or move the state into the successor's column.`}}s(CJ,"passThroughRemedy");function DJ(e,n){let t=ka(e,n);if(!t)return[];let{layout:r,wiring:i}=t;if(!r.buses.some(v=>v.key==="process"))return[];let o=E_(r);if(!o)return[];let a=new Map(e.nodes.map(v=>[v.id,v])),l=s(v=>He(v).progressEvents??[],"eventsOf"),d=s(v=>Object.values(v.next??{}).map(A=>A.to),"routesOf"),c=s((v,A)=>{let E=a.get(v);if(!E||A.has(v))return null;if(l(E).length>0)return[E];if(pC[E.type]!==!1)return null;let R=d(E);if(R.length===0)return null;let P=[];for(let F of R){let b=c(F,new Set([...A,v]));if(!b)return null;P.push(...b)}return P},"firstProgressNodes"),u=s((v,A)=>{let E=[];for(let R of l(v)){let P=Hs(i,v,R);if(!P||P.bus!==A.bus||P.state===A.state)return null;E.push(P.state)}return[...new Set(E)].join("' / '")},"overwrites"),p=s((v,A)=>{let E=d(v);if(E.length===0)return null;let R=[];for(let P of E){let F=c(P,new Set([v.id]));if(!F)return null;for(let b of F){let O=u(b,A);if(O===null)return null;R.push({de:`'${b.id}' (${b.type}) mit '${O}'`,en:`'${b.id}' (${b.type}) with '${O}'`})}}return[...new Map(R.map(P=>[P.de,P])).values()]},"submitOverwrittenBy"),h=new Map;for(let v of e.nodes)for(let A of l(v)){let E=Hs(i,v,A);if(!E||E.bus!=="process")continue;let R=v.type==="form"&&A===yf?p(v,E):null,P=R?{de:`'${v.id}'.${A} erreicht ihn, und ${R.map(F=>F.de).join(", ")} \xFCberschreibt ihn in derselben Transaktion`,en:`'${v.id}'.${A} reaches it, and ${R.map(F=>F.en).join(", ")} overwrites it in the same transaction`}:null;h.set(E.state,[...h.get(E.state)??[],P])}let y=Hf(r,"process"),k=new Map;for(let[v,A]of h){if(!A.every(R=>R!==null))continue;let E=[...new Map(A.map(R=>[R.de,R])).values()];k.set(v,{de:E.map(R=>R.de).join("; "),en:E.map(R=>R.en).join("; ")})}let w=[];for(let v of o.columns){if(v.states.length===0||!v.states.every(R=>k.has(R)))continue;let A=v.states.map(R=>{let P=y.holdsSeat?.includes(R)===!0,F=k.get(R);return{de:`Zustand '${R}'${P?" (steht in holdsSeat, belegt aber nie einen Platz)":""}: ${F.de}`,en:`State '${R}'${P?" (is in holdsSeat, but never takes a seat)":""}: ${F.en}`}}),E=CJ(o.audience);w.push({layer:"GRAPH",kind:"progressState",path:`progressLayout.process.boards.${o.id}.columns.${v.id}`,reason:{de:`[progress/passThroughState] Spalte \u201E${v.label.de}" ('${v.id}', Board '${o.id}') bleibt immer leer \u2014 ${A.map(R=>R.de).join("; ")}. ${E.de}`,en:`[progress/passThroughState] Column "${v.label.en}" ('${v.id}', board '${o.id}') always stays empty \u2014 ${A.map(R=>R.en).join("; ")}. ${E.en}`},severity:"warning"})}return w}s(DJ,"checkProgressPassThroughColumns");function FJ(e){let n=["workItems","workitems","work_items","taskTemplates"],t=[];for(let r of e.nodes){let i=r;for(let o of n){let a=i[o];a!=null&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.${o}`,reason:{de:`[workItems/misnamedTasksKey] Knoten "${r.id}" deklariert "${o}" \u2014 komponierte Aufgaben werden ausschlie\xDFlich unter "tasks" gelesen. So wie es dasteht, w\xFCrde die Aufgabenkette stillschweigend nie entstehen. Benenne den Schl\xFCssel in "tasks" um.`,en:`[workItems/misnamedTasksKey] Node "${r.id}" declares "${o}" \u2014 composed tasks are read only from "tasks". As it stands, the task chain would silently never be created. Rename the key to "tasks".`},severity:"error"})}}return t}s(FJ,"checkMisnamedTasksKey");function LJ(e){let n=[];for(let t of e.nodes){let r=t,i=Array.isArray(r.tasks)?r.tasks:[],o=new Set;for(let c of i){let u=typeof c.key=="string"?c.key:void 0;u!==void 0&&(o.has(u)&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}`,reason:{de:`[workItems/duplicateTemplateKey] Doppelter Template-Key "${u}" auf Knoten "${r.id}".`,en:`[workItems/duplicateTemplateKey] Duplicate template key "${u}" on node "${r.id}".`},severity:"error"}),o.add(u))}let a=new Set;for(let c of Array.isArray(r.artifacts)?r.artifacts:[])typeof c.key=="string"&&a.add(`${c.key}Uploaded`);let l=He(t),d=new Map((typeof l.workItemTemplates=="function"?l.workItemTemplates(t):[]).map(c=>[c.key,c]));for(let c of i){let u=typeof c.key=="string"?c.key:"?",p=typeof c.kind=="string"?c.kind:void 0;if(p===void 0||!Wl.has(p)){n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.kind`,reason:{de:`[workItems/invalidKind] Task "${u}" auf Knoten "${r.id}" hat Art ${JSON.stringify(c.kind)}; komponierbar sind: ${[...Wl].join(", ")}.`,en:`[workItems/invalidKind] Task "${u}" on node "${r.id}" has kind ${JSON.stringify(c.kind)}; composable kinds are: ${[...Wl].join(", ")}.`},severity:"error"});continue}p==="task"&&c.gatesNode!==void 0&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.gatesNode`,reason:{de:`[workItems/gatesNodeOnTask] 'gatesNode' ist nur f\xFCr die Art 'approval' zul\xE4ssig \u2014 eine Task gated ihren Knoten nie direkt. Um eine gatende Freigabe zur\xFCckzuhalten, 'blocks' verwenden (Task "${u}" auf Knoten "${r.id}").`,en:`[workItems/gatesNodeOnTask] 'gatesNode' is only allowed for the kind 'approval' \u2014 a task never gates its node directly. To hold back a gating approval, use 'blocks' (task "${u}" on node "${r.id}").`},severity:"error"});let h=c.blocks,y=h===void 0?void 0:TP(e,r.id,h.node);if(h!==void 0&&y===null)n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.node`,reason:{de:`[workItems/blocksUnknownNode] 'blocks.node' auf Task "${u}" (Knoten "${r.id}") nennt ${JSON.stringify(h.node)} \u2014 diesen Knoten gibt es im Workflow nicht.`,en:`[workItems/blocksUnknownNode] 'blocks.node' on task "${u}" (node "${r.id}") names ${JSON.stringify(h.node)} \u2014 there is no such node in the workflow.`},severity:"error"});else if(h!==void 0&&y!==void 0&&y!==null){let w=y.node.id===r.id,v=y.node.id,A=w?o:y.composedKeys,E=w?d:y.intrinsicByKey,R=y.node.assign??{};p==="approval"&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks`,reason:{de:`[workItems/blocksOnApproval] 'blocks' ist auf der Art 'approval' verboten \u2014 nur Task-Zeilen d\xFCrfen einen Geschwister-Spawn zur\xFCckhalten (Approval "${u}" auf Knoten "${r.id}").`,en:`[workItems/blocksOnApproval] 'blocks' is forbidden on the kind 'approval' \u2014 only task rows may hold back a sibling spawn (approval "${u}" on node "${r.id}").`},severity:"error"});let P=h.templateKey,F=[...new Set([...A,...E.keys()])].filter(O=>!w||O!==u).join(", "),b={de:F||"keine",en:F||"none"};if(typeof P!="string"||w&&P===u||!A.has(P)&&!E.has(P))n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.templateKey`,reason:{de:`[workItems/blocksUnknownTarget] 'blocks' muss ein Template auf dem Zielknoten benennen \u2014 komponiert ODER intrinsisch (nie sich selbst, nie ohne 'templateKey': die zielfreie Form geh\xF6rt der Maschine, nicht dem Autor). Ziel ${JSON.stringify(P)} auf Knoten "${v}"; zul\xE4ssige Ziele: ${b.de}.`,en:`[workItems/blocksUnknownTarget] 'blocks' must name a template on the target node \u2014 composed OR intrinsic (never itself, never without 'templateKey': the target-less form belongs to the engine, not the author). Target ${JSON.stringify(P)} on node "${v}"; allowed targets: ${b.en}.`},severity:"error"});else if(y.refuse(P)!==null)n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.templateKey`,reason:y.refuse(P),severity:"error"});else{let O=E.get(P);h.except!==void 0&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.except`,reason:{de:`[workItems/blocksExceptRetired] 'blocks.except' auf Task "${u}" (Knoten "${r.id}") gibt es nicht mehr: eine blockierende Aufgabe sperrt die ganze Aktionsgruppe ihres Ziels (bei einer Entscheidung Freigeben, Warteliste, Ablehnen und das Nachr\xFCcken). 'except' entfernen.`,en:`[workItems/blocksExceptRetired] 'blocks.except' on task "${u}" (node "${r.id}") no longer exists: a blocking task locks the whole action group of its target (for a decision: approve, waitlist, reject and promote). Remove 'except'.`},severity:"error"}),O!==void 0&&O.recipient!=="external"&&O.verdictResolved!==!0&&typeof R[P]!="string"&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.templateKey`,reason:{de:`[workItems/blocksUnwiredTarget] Task "${u}" auf Knoten "${r.id}" h\xE4lt "${P}" (Knoten "${v}") zur\xFCck, aber der Knoten weist "${P}" keiner Gruppe zu \u2014 ohne 'assign.${P}' entsteht diese Zeile nie: kein Team bekommt die zur\xFCckgehaltene Arbeit, niemand au\xDFer der verantwortlichen Person kann sie tun. Entweder 'assign.${P}' erg\xE4nzen oder das 'blocks' entfernen.`,en:`[workItems/blocksUnwiredTarget] Task "${u}" on node "${r.id}" holds back "${P}" (node "${v}"), but the node assigns "${P}" to no group \u2014 without 'assign.${P}' this row is never created: no team receives the held-back work, and nobody except the responsible person can do it. Either add 'assign.${P}' or remove the 'blocks'.`},severity:"error"})}}{let w=c.completableIf;if(typeof w=="string"&&w.trim().length>0){let v=w.trim().replace(/^!/,"").trim();a.has(v)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.completableIf`,reason:{de:`[workItems/unknownExport] completableIf "${w}" verweist auf unbekannten Node-Export "${v}"; bekannt: ${[...a].join(", ")||"keine"}.`,en:`[workItems/unknownExport] completableIf "${w}" refers to unknown node export "${v}"; known: ${[...a].join(", ")||"none"}.`},severity:"error"})}}let k=c.params;if(k?.commentRequired!==void 0&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.params.commentRequired`,reason:{de:"[workItems/removedParam] 'params.commentRequired' wurde entfernt \u2014 Kommentar-Pflichten werden am Decision-Node ('commentRequired') autorisiert.",en:"[workItems/removedParam] 'params.commentRequired' was removed \u2014 comment requirements are authored on the decision node ('commentRequired')."},severity:"error"}),p!=="approval"){let w=[];k?.onReject!==void 0&&w.push("params.onReject"),k?.revisionGroup!==void 0&&w.push("params.revisionGroup");for(let v of w)n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.${v}`,reason:{de:`[workItems/approvalOnlyField] '${v}' gilt nur f\xFCr die Art 'approval' (Task "${u}" ist '${p}').`,en:`[workItems/approvalOnlyField] '${v}' only applies to the kind 'approval' (task "${u}" is '${p}').`},severity:"error"});continue}k?.onReject!==void 0&&k.onReject!=="spawnRevision"&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.params.onReject`,reason:{de:`[workItems/invalidOnReject] Erwartet 'spawnRevision', erhalten ${JSON.stringify(k.onReject)}.`,en:`[workItems/invalidOnReject] Expected 'spawnRevision', got ${JSON.stringify(k.onReject)}.`},severity:"error"}),k?.onReject==="spawnRevision"&&(typeof k.revisionGroup!="string"||k.revisionGroup.length===0)&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.params.revisionGroup`,reason:{de:`[workItems/spawnRevisionNoTarget] Approval "${u}" mit 'params.onReject: spawnRevision' ohne 'params.revisionGroup' \u2014 die \xDCberarbeitung h\xE4tte keine Ziel-Gruppe.`,en:`[workItems/spawnRevisionNoTarget] Approval "${u}" with 'params.onReject: spawnRevision' but no 'params.revisionGroup' \u2014 the revision would have no target group.`},severity:"error"})}}return n.push(...$P(e)),n}s(LJ,"checkWorkItemTemplates");var MJ=new Set(["complete","approve","reject"]),pC={form:!0,decision:!0,review:!0,waitlist:!0,completenessCheck:!0,collectPayment:!0,eventTrigger:!0,join:!1,roleAssign:!1,setFlag:!1,if:!1,end:!1,countersign:!0,engagePush:!1,governedDocument:!0};function qJ(e){let n=[];for(let t of e.nodes){let r=t,i=He(t),o=Array.isArray(r.tasks)?r.tasks.length:0,a=i.workItemTemplates?.(t)??[];if(o+a.length>0){let v=pC[r.type];v===void 0?n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks`,reason:{de:`[workItems/unknownParkSemantics] Knotentyp "${r.type}" hat keine bekannte Park-Semantik \u2014 NODE_TYPE_PARKS in validators.ts erg\xE4nzen.`,en:`[workItems/unknownParkSemantics] Node type "${r.type}" has no known parking semantics \u2014 add it to NODE_TYPE_PARKS in validators.ts.`},severity:"error"}):v||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks`,reason:{de:`[workItems/templatesOnNonParkingNode] Knoten "${r.id}" (Typ "${r.type}") parkt nie \u2014 seine Work-Item-Templates w\xFCrden im selben Dispatch gespawnt und storniert (totes Muster).`,en:`[workItems/templatesOnNonParkingNode] Node "${r.id}" (type "${r.type}") never parks \u2014 its work-item templates would be spawned and cancelled in the same dispatch (dead pattern).`},severity:"error"})}let l=i.actions?.(t)??[];if(l.length===0&&a.length===0)continue;let d=new Map(l.map(v=>[v.id,v]));for(let v of l)MJ.has(v.id)&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}`,reason:{de:`[capability/reservedActionId] Knotentyp "${r.type}" deklariert die Action "${v.id}" \u2014 reserviert f\xFCr den generischen Complete-/Verdict-Pfad (complete, approve, reject); die Spec muss eine andere Action-Id w\xE4hlen.`,en:`[capability/reservedActionId] Node type "${r.type}" declares the action "${v.id}" \u2014 reserved for the generic complete/verdict path (complete, approve, reject); the spec must choose a different action id.`},severity:"error"});let c=new Set(i.states??[j_]);for(let v of l)if(v.availableIn!==void 0)for(let A of v.availableIn)c.has(A)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}.availableIn`,reason:{de:`[capability/unknownActionState] Action "${v.id}" auf Knotentyp "${r.type}" ist f\xFCr Zustand "${A}" deklariert \u2014 der Typ kennt nur: ${[...c].join(", ")}.`,en:`[capability/unknownActionState] Action "${v.id}" on node type "${r.type}" is declared for state "${A}" \u2014 the type only knows: ${[...c].join(", ")}.`},severity:"error"});let u=mw(t),p=new Set(u?u.map(v=>v.id):[ea]);for(let v of l){if(v.external===void 0)continue;let A=K_(v.external.event),E={de:"hat keine Beschriftung (der Empf\xE4nger bekommt einen leeren Button)",en:"has no label (the recipient would get an empty button)"},R=A?v.kind==="advance"?{de:`ist als "advance" deklariert, l\xF6st den Knoten aber nicht auf (Ereignis "${v.external.event}") \u2014 solche Aktionen sind "internal"`,en:`is declared as "advance", but does not resolve the node (event "${v.external.event}") \u2014 such actions are "internal"`}:v.outcome!==void 0?{de:`nennt das Outcome "${v.outcome}", l\xF6st den Knoten aber nicht auf (Ereignis "${v.external.event}") \u2014 ein Outcome w\xFCrde eine zweite, stille Routing-Vokabel behaupten`,en:`names the outcome "${v.outcome}", but does not resolve the node (event "${v.external.event}") \u2014 an outcome would claim a second, silent routing vocabulary`}:v.label===void 0?E:null:v.kind!=="advance"?{de:`ist als "${v.kind}" deklariert (externe Aktionen l\xF6sen den Knoten auf und m\xFCssen "advance" sein)`,en:`is declared as "${v.kind}" (external actions resolve the node and must be "advance")`}:v.outcome===void 0?{de:"nennt kein Outcome",en:"names no outcome"}:p.has(v.outcome)?v.label===void 0?E:null:{de:`verweist auf das unbekannte Outcome "${v.outcome}" (deklariert: ${[...p].join(", ")||"keine"})`,en:`refers to the unknown outcome "${v.outcome}" (declared: ${[...p].join(", ")||"none"})`};R!==null&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}.external`,reason:{de:`[capability/externalActionNeedsOutcome] Externe Aktion "${v.id}" auf Knotentyp "${r.type}" ${R.de}.`,en:`[capability/externalActionNeedsOutcome] External action "${v.id}" on node type "${r.type}" ${R.en}.`},severity:"error"})}for(let v of a){let A=v.unlocks;if(A.length===0&&v.verdictResolved!==!0&&v.informational!==!0){n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.workItemTemplates.${v.key}.unlocks`,reason:{de:`[capability/emptyUnlocks] Intrinsisches Template "${v.key}" auf Knoten "${r.id}" schaltet keine Action frei (B5).`,en:`[capability/emptyUnlocks] Intrinsic template "${v.key}" on node "${r.id}" unlocks no action (B5).`},severity:"error"});continue}for(let E of A)d.get(E)===void 0&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.workItemTemplates.${v.key}.unlocks`,reason:{de:`[capability/danglingUnlock] Template "${v.key}" auf Knoten "${r.id}" schaltet unbekannte Action "${E}" frei; deklariert: ${[...d.keys()].join(", ")||"keine"}.`,en:`[capability/danglingUnlock] Template "${v.key}" on node "${r.id}" unlocks the unknown action "${E}"; declared: ${[...d.keys()].join(", ")||"none"}.`},severity:"error"})}let h=new Set(a.map(v=>v.key));for(let v of Object.keys(r.assign??{}))h.has(v)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.assign.${v}`,reason:{de:`[capability/unknownAssignKey] assign-Key "${v}" auf Knoten "${r.id}" ist kein intrinsisches Template dieses Knotentyps; bekannt: ${[...h].join(", ")||"keine"}.`,en:`[capability/unknownAssignKey] assign key "${v}" on node "${r.id}" is not an intrinsic template of this node type; known: ${[...h].join(", ")||"none"}.`},severity:"error"});let y=l.filter(v=>v.teamAssignable===!0).map(v=>v.id);for(let v of Object.keys(r.actionTeams??{}))y.includes(v)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actionTeams.${v}`,reason:{de:`[capability/unknownActionTeam] Knoten "${r.id}" nennt ein Team f\xFCr "${v}", aber diese Aktion l\xE4sst sich hier keinem Team geben; m\xF6glich: ${y.join(", ")||"keine"}.`,en:`[capability/unknownActionTeam] Node "${r.id}" names a team for "${v}", but this action cannot be given to a team here; possible: ${y.join(", ")||"none"}.`},severity:"error"});let k=new Set;for(let v of a)if(v.recipient==="external"||typeof(r.assign??{})[v.key]=="string")for(let E of v.unlocks)k.add(E);let w=i.strictActionCoverage===!0;for(let v of l){if(k.has(v.id)||v.superUserOnly===!0)continue;let A=a.find(R=>R.unlocks.includes(v.id)),E=A!==void 0?{de:` Fehlt die Zuweisung assign.${A.key}?`,en:` Is the assignment assign.${A.key} missing?`}:{de:"",en:""};n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}`,reason:{de:`[capability/superUserOnly] Action "${v.id}" auf Knoten "${r.id}" ist von keinem verdrahteten Work-Item freigeschaltet \u2014 nur die verantwortliche Person (Super-User) kann sie ausf\xFChren.${E.de}`,en:`[capability/superUserOnly] Action "${v.id}" on node "${r.id}" is unlocked by no wired work item \u2014 only the responsible person (super user) can perform it.${E.en}`},severity:w?"error":"warning"})}}return n}s(qJ,"checkNodeCapabilityWiring");function KJ(e){let n=new Set(vO()),t=[];for(let r of e.nodes)n.has(r.type)||t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.type`,reason:{de:`[graph/unknownNodeType] Knoten "${r.id}" hat den unbekannten Typ "${String(r.type)}". Registrierte Typen: ${[...n].join(", ")}.`,en:`[graph/unknownNodeType] Node "${r.id}" has the unknown type "${String(r.type)}". Registered types: ${[...n].join(", ")}.`},severity:"error"});return t}s(KJ,"checkKnownNodeTypes");function jJ(e,n){let t=[],r=s((a,l)=>{t.push({layer:"GRAPH",kind:"nodeRule",path:a,reason:l,severity:"error"})},"push"),i=II(e),o=s(a=>typeof a=="object"&&a!==null&&Object.values(a).some(l=>typeof l=="string"&&l.trim().length>0),"hasText");for(let a of e.nodes){let l=a,d=Array.isArray(l.optionalActions)?l.optionalActions:[];if(t.push(...n4(l,d)),d.length===0)continue;let c=He(a),u=new Set(c.optionalActionKinds??[]),p=Array.isArray(l.tasks)?l.tasks:[],h=new Map;for(let w of p)typeof w.key=="string"&&h.set(w.key,w);let y=new Set,k=new Map;for(let w of d){let v=w.key,A=typeof v=="string"&&v.trim().length>0?v:void 0,E=A??"?",R=`nodes.${l.id}.optionalActions.${E}`,P=typeof w.action=="string"?w.action:void 0;if(w.when!==void 0){let F=s(b=>r(`${R}.when`,{de:`[optionalAction/when] Optionale Aktion "${E}" auf Knoten "${l.id}": ${b.de}`,en:`[optionalAction/when] Optional action "${E}" on node "${l.id}": ${b.en}`}),"conditionFinding");if(typeof w.when!="string"||w.when.trim()==="")F({de:"Die Bedingung ist leer \u2014 ohne Bedingung das Feld weglassen.",en:"The condition is empty \u2014 without a condition, omit the field."});else for(let b of wp(w.when,i,n))F(b)}if((P===void 0||!u.has(P))&&r(`${R}.action`,{de:`[optionalAction/kindNotDeclared] Optionale Aktion "${E}" auf Knoten "${l.id}" hat die Art ${JSON.stringify(w.action)} \u2014 `+(u.size===0?`Knotentyp "${l.type}" deklariert keine Familien (spec.optionalActionKinds fehlt).`:`Knotentyp "${l.type}" deklariert nur: ${[...u].join(", ")}.`),en:`[optionalAction/kindNotDeclared] Optional action "${E}" on node "${l.id}" has the kind ${JSON.stringify(w.action)} \u2014 `+(u.size===0?`node type "${l.type}" declares no families (spec.optionalActionKinds is missing).`:`node type "${l.type}" only declares: ${[...u].join(", ")}.`)}),A===void 0?r(`${R}.key`,{de:`[optionalAction/missingKey] Optionale Aktion auf Knoten "${l.id}" ohne (oder mit leerem) 'key' \u2014 Trigger-Action und Template-Keys w\xE4ren namenlos ('optionalAction::\u2026').`,en:`[optionalAction/missingKey] Optional action on node "${l.id}" without (or with an empty) 'key' \u2014 the trigger action and template keys would be nameless ('optionalAction::\u2026').`}):(y.has(A)&&r(`${R}.key`,{de:`[optionalAction/duplicateKey] Doppelter Aktions-Key "${A}" auf Knoten "${l.id}" \u2014 die projizierten Trigger-Actions w\xFCrden kollidieren.`,en:`[optionalAction/duplicateKey] Duplicate action key "${A}" on node "${l.id}" \u2014 the projected trigger actions would collide.`}),y.add(A)),o(w.label)||r(`${R}.label`,{de:`[optionalAction/missingLabel] Optionale Aktion "${E}" auf Knoten "${l.id}" ohne Label \u2014 der Trigger-Button w\xE4re unbeschriftet.`,en:`[optionalAction/missingLabel] Optional action "${E}" on node "${l.id}" without a label \u2014 the trigger button would be unlabeled.`}),P==="spawnTasks"){w.except!==void 0&&r(`${R}.except`,{de:`[optionalAction/exceptRetired] Optionale Aktion "${E}" auf Knoten "${l.id}" tr\xE4gt 'except' \u2014 das gibt es nicht mehr: solange die Aufgaben offen sind, ist die ganze Aktionsgruppe des Knotens gesperrt. 'except' entfernen.`,en:`[optionalAction/exceptRetired] Optional action "${E}" on node "${l.id}" carries 'except' \u2014 that no longer exists: while the tasks are open, the node's whole action group is locked. Remove 'except'.`}),t.push(...uC({nodeId:l.id,bindingKey:E,binding:w,templates:p}));let F=Array.isArray(w.tasks)?w.tasks:void 0;if(F===void 0||F.length===0)r(`${R}.tasks`,{de:`[optionalAction/tasksEmpty] Optionale Aktion "${E}" auf Knoten "${l.id}" referenziert keine Aufgaben-Templates \u2014 der Trigger w\xFCrde nichts erzeugen.`,en:`[optionalAction/tasksEmpty] Optional action "${E}" on node "${l.id}" references no task templates \u2014 the trigger would create nothing.`});else{let b=new Set,O=new Set(F.filter($=>typeof $=="string"));for(let $ of F){let I=typeof $=="string"?$:void 0;if(I===void 0||I.length===0){r(`${R}.tasks`,{de:`[optionalAction/unknownTaskRef] Optionale Aktion "${E}" auf Knoten "${l.id}" enth\xE4lt eine leere/ung\xFCltige Template-Referenz.`,en:`[optionalAction/unknownTaskRef] Optional action "${E}" on node "${l.id}" contains an empty or invalid template reference.`});continue}if(b.has(I)){r(`${R}.tasks.${I}`,{de:`[optionalAction/duplicateTaskRef] Template "${I}" ist in der Aktion "${E}" auf Knoten "${l.id}" doppelt referenziert.`,en:`[optionalAction/duplicateTaskRef] Template "${I}" is referenced twice in the action "${E}" on node "${l.id}".`});continue}b.add(I);let G=h.get(I);if(G===void 0){r(`${R}.tasks.${I}`,{de:`[optionalAction/unknownTaskRef] Optionale Aktion "${E}" auf Knoten "${l.id}" referenziert das Template "${I}", das node.tasks nicht deklariert. Vorhanden: ${[...h.keys()].join(", ")||"keine"}.`,en:`[optionalAction/unknownTaskRef] Optional action "${E}" on node "${l.id}" references the template "${I}", which node.tasks does not declare. Present: ${[...h.keys()].join(", ")||"none"}.`});continue}let B=k.get(I);B!==void 0&&B!==E?r(`${R}.tasks.${I}`,{de:`[optionalAction/taskDoublyBound] Template "${I}" auf Knoten "${l.id}" ist bereits von der Aktion "${B}" referenziert \u2014 ein Template geh\xF6rt zu h\xF6chstens einer optionalen Aktion.`,en:`[optionalAction/taskDoublyBound] Template "${I}" on node "${l.id}" is already referenced by the action "${B}" \u2014 a template belongs to at most one optional action.`}):k.set(I,E);let le=G.blocks?.templateKey;typeof le=="string"&&!O.has(le)&&r(`${R}.tasks.${I}`,{de:`[optionalAction/taskRefBlocks] Template "${I}" auf Knoten "${l.id}" tr\xE4gt 'blocks' auf "${le}", das nicht zur selben Aktion "${E}" geh\xF6rt \u2014 eine Referenz darf nur eine Referenz DERSELBEN Aktion zur\xFCckhalten (Checklisten-Reihenfolge), nie ein Template au\xDFerhalb.`,en:`[optionalAction/taskRefBlocks] Template "${I}" on node "${l.id}" carries 'blocks' on "${le}", which does not belong to the same action "${E}" \u2014 a reference may only hold back a reference of the SAME action (checklist order), never a template outside it.`});for(let Q of p){let re=typeof Q.key=="string"?Q.key:void 0;Q.blocks?.templateKey===I&&(re!==void 0&&O.has(re)||r(`${R}.tasks.${I}`,{de:`[optionalAction/taskRefBlocks] Template "${I}" auf Knoten "${l.id}" ist Ziel eines 'blocks' von ${re!==void 0?`"${re}"`:"einem Template"} au\xDFerhalb der Aktion "${E}" \u2014 ein Template au\xDFerhalb darf eine Referenz nie zur\xFCckhalten (ihr Spawn geh\xF6rt dem Trigger, nicht onEnter).`,en:`[optionalAction/taskRefBlocks] Template "${I}" on node "${l.id}" is the target of a 'blocks' from ${re!==void 0?`"${re}"`:"a template"} outside the action "${E}" \u2014 a template outside may never hold back a reference (its spawn belongs to the trigger, not to onEnter).`}))}}}}}}return t}s(jJ,"checkOptionalActions");function VJ(e){return typeof e=="number"?"number":typeof e=="boolean"?"boolean":"string"}s(VJ,"literalValueType");function BJ(e,n){let t=[],r=n?.notificationTemplates;for(let i of e.nodes){let o=i,a=dN(i,He(i)),l=o.notifications??{};if(a.length===0&&Object.keys(l).length===0)continue;let d=new Map(a.map(c=>[c.id,c]));for(let c of Object.keys(l))d.has(c)||t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${o.id}.notifications.${c}`,reason:{de:`[notification/unknownEvent] Knoten "${o.id}" bindet einen Brief an das Ereignis "${c}", das der Knotentyp "${o.type}" nicht kennt. Angeboten werden: ${a.map(u=>u.id).join(", ")||"(keine)"}.`,en:`[notification/unknownEvent] Node "${o.id}" binds a letter to the event "${c}", which the node type "${o.type}" does not know. Offered: ${a.map(u=>u.id).join(", ")||"(none)"}.`},severity:"error"});for(let c of a){let u=l[c.id];if(c.required===!0&&(u===void 0||u.disabled===!0)){t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${o.id}.notifications.${c.id}`,reason:{de:`[notification/missingBinding] Knoten "${o.id}" muss beim Ereignis "${c.label.de}" (${c.id}) einen Brief verschicken \u2014 es ist ${u===void 0?"keiner gebunden":"einer gebunden, aber abgeschaltet"}.`,en:`[notification/missingBinding] Node "${o.id}" must send a letter on the event "${c.label.en}" (${c.id}) \u2014 ${u===void 0?"none is bound":"one is bound, but switched off"}.`},severity:"error"});continue}if(u===void 0||u.disabled===!0)continue;let p=`nodes.${o.id}.notifications.${c.id}`;if(c.audience!=="external"){t.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/internalAudienceUnsupported] Knoten "${o.id}": das Ereignis "${c.id}" richtet sich an die Schule, und Briefe an die Schule k\xF6nnen noch nicht zugestellt werden \u2014 der gebundene Brief "${u.templateId}" w\xFCrde den Vorgang beim Versand abbrechen.`,en:`[notification/internalAudienceUnsupported] Node "${o.id}": the event "${c.id}" is addressed to the school, and letters to the school cannot be delivered yet \u2014 the bound letter "${u.templateId}" would abort the process when it is sent.`},severity:"error"});continue}if(r===void 0)continue;let h=r.get(u.templateId);if(h===void 0){t.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/unknownTemplate] Knoten "${o.id}": der Brief "${u.templateId}" ist nicht im Katalog. Bekannt sind: ${[...r.keys()].sort().join(", ")||"(keine)"}.`,en:`[notification/unknownTemplate] Node "${o.id}": the letter "${u.templateId}" is not in the catalog. Known: ${[...r.keys()].sort().join(", ")||"(none)"}.`},severity:"error"});continue}h.audience!==void 0&&h.audience!==c.audience&&t.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/audienceMismatch] Der Brief "${h.id}" ist f\xFCr ${h.audience==="internal"?"die Schule":"die Familie"} geschrieben, das Ereignis "${c.id}" richtet sich aber an die Familie.`,en:`[notification/audienceMismatch] The letter "${h.id}" is written for ${h.audience==="internal"?"the school":"the family"}, but the event "${c.id}" is addressed to the family.`},severity:"warning"});let y=iN(c),k=new Set(h.params.map(w=>w.key));for(let w of Object.keys(u.args??{}))k.has(w)||t.push({layer:"GRAPH",kind:"nodeRule",path:`${p}.args.${w}`,reason:{de:`[notification/unknownArg] Der Brief "${h.id}" hat kein Argument "${w}" \u2014 erwartet werden: ${h.params.map(v=>v.key).join(", ")||"(keine)"}.`,en:`[notification/unknownArg] The letter "${h.id}" has no argument "${w}" \u2014 expected: ${h.params.map(v=>v.key).join(", ")||"(none)"}.`},severity:"error"});for(let w of h.params){let v=u.args?.[w.key],A=`${p}.args.${w.key}`;if(v!==void 0&&"literal"in v){let R=VJ(v.literal);w.type!==void 0&&!Rw(R,w.type)&&t.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/argTypeMismatch] "${w.key}" erwartet ${Gl(w.type).de}, festgelegt ist aber ${JSON.stringify(v.literal)} (${R}).`,en:`[notification/argTypeMismatch] "${w.key}" expects ${Gl(w.type).en}, but ${JSON.stringify(v.literal)} (${R}) is set.`},severity:"error"});continue}if(v!==void 0){t.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/unsupportedArg] "${w.key}" ist an ${JSON.stringify(v)} gebunden \u2014 ein Brief-Argument kann nur ein Festwert ({ literal }) sein oder automatisch aus ${fC(y,"de")} kommen.`,en:`[notification/unsupportedArg] "${w.key}" is bound to ${JSON.stringify(v)} \u2014 a letter argument can only be a fixed value ({ literal }) or come automatically from ${fC(y,"en")}.`},severity:"error"});continue}let E=oN(w,y.get(w.key)??[]);if(!(E.status==="resolved"||E.status==="unused")){if(E.status==="sometimes"){t.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/unresolvedArg] Der Brief "${h.id}" braucht "${w.key}" immer, ${E.source.source} liefert es aber nur manchmal. In notifications.${c.id}.args.${w.key} einen Festwert benennen \u2014 oder einen Brief w\xE4hlen, der ohne "${w.key}" auskommt.`,en:`[notification/unresolvedArg] The letter "${h.id}" always needs "${w.key}", but ${E.source.source} provides it only sometimes. Name a fixed value in notifications.${c.id}.args.${w.key} \u2014 or choose a letter that works without "${w.key}".`},severity:"error"});continue}if(E.status==="ambiguous"){t.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/ambiguousArg] "${w.key}" hat mehrere passende Quellen \u2014 ${E.matches.map(R=>R.source).join(", ")}. In notifications.${c.id}.args.${w.key} einen Festwert setzen.`,en:`[notification/ambiguousArg] "${w.key}" has several matching sources \u2014 ${E.matches.map(R=>R.source).join(", ")}. Set a fixed value in notifications.${c.id}.args.${w.key}.`},severity:"error"});continue}t.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/unresolvedArg] Der Brief "${h.id}" braucht "${w.key}"${w.type!==void 0?` (${Gl(w.type).de})`:""}, und der Knoten hat daf\xFCr ${E.rejected.length===0?"keine Quelle":`nur unpassende Quellen: ${E.rejected.map(R=>`${R.source} (${R.type})`).join(", ")}`}.`,en:`[notification/unresolvedArg] The letter "${h.id}" needs "${w.key}"${w.type!==void 0?` (${Gl(w.type).en})`:""}, and the node has ${E.rejected.length===0?"no source for it":`only unsuitable sources for it: ${E.rejected.map(R=>`${R.source} (${R.type})`).join(", ")}`}.`},severity:"error"})}}}}return t}s(BJ,"checkNotificationBindings");function UJ(e){return KN(e).map(n=>({layer:"GRAPH",kind:"assignment",path:"assignmentRules",reason:n,severity:"error"}))}s(UJ,"checkAssignmentRules");function fC(e,n){let t=[...e.keys()].sort();return t.length===0?n==="de"?"(nichts)":"(nothing)":t.join(", ")}s(fC,"describeCandidates");function GJ(e,n){return BN(e,n?.teamKeys).map(t=>({layer:"GRAPH",kind:"nodeRule",path:t.path,reason:t.reason,severity:"error"}))}s(GJ,"checkChannels");function zJ(e){return _I(e).map(n=>({layer:"GRAPH",kind:"nodeRule",path:n.path,reason:n.reason,severity:"error"}))}s(zJ,"checkStaffInputs");function WJ(e,n){let t=[];for(let r of e.nodes){let i=r.reads;if(i===void 0)continue;let o=`nodes.${r.id}.reads`,a={de:`Knoten \u201E${_e(e,r.id,"de")}\u201C (${r.id})`,en:`Node "${_e(e,r.id,"en")}" (${r.id})`},l=s(c=>{t.push({layer:"GRAPH",kind:"nodeRule",path:o,reason:c,severity:"error"})},"issue");if(!XN(r)){l({de:`[readiness/readsNotGated] ${a.de} (${r.type}) deklariert \`reads\`, aber die Bereitschaftspr\xFCfung h\xE4lt nur Entscheidungs-Knoten und Dokument-Knoten mit Produktion \u2014 hier w\xFCrde \`reads\` nichts bewirken.`,en:`[readiness/readsNotGated] ${a.en} (${r.type}) declares \`reads\`, but the readiness check only holds decision nodes and document nodes with production \u2014 here \`reads\` would have no effect.`});continue}if(!Array.isArray(i)){l({de:`[readiness/readsDuplicate] \`reads\` von ${a.de} muss eine Liste von Feldadressen sein, erhalten ${JSON.stringify(i)}.`,en:`[readiness/readsDuplicate] \`reads\` of ${a.en} must be a list of field addresses, got ${JSON.stringify(i)}.`});continue}let d=new Set;for(let c of i){if(!be(c))continue;let u=ue(c);if(d.has(u)){l({de:`[readiness/readsDuplicate] ${a.de} liest ${je(e,c,"de")} mehrfach.`,en:`[readiness/readsDuplicate] ${a.en} reads ${je(e,c,"en")} more than once.`});continue}if(d.add(u),!un(c)){l({de:`[readiness/readsUnknownField] ${a.de} liest ${je(e,c,"de")} \u2014 \`reads\` nennt nur Felder eines Formulars ($node.<formular>.admission.<feld>).`,en:`[readiness/readsUnknownField] ${a.en} reads ${je(e,c,"en")} \u2014 \`reads\` only names fields of a form ($node.<form>.admission.<field>).`});continue}let p=ai(n,c);p!=null&&Ys("nodeReads",Ws(p))==="repeated"&&l({de:`[readiness/readsUnknownField] ${a.de} liest ${je(e,c,"de")} \u2014 ein Feld in einer Wiederholgruppe ist kein einzelnes Feld der Anmeldung und kann nicht gelesen werden.`,en:`[readiness/readsUnknownField] ${a.en} reads ${je(e,c,"en")} \u2014 a field in a repeated group is not a single field of the application and cannot be read.`})}}return t}s(WJ,"checkReadinessReads");function YJ(e,n){let t=[];for(let r of e.nodes){if(r.type!=="setFlag")continue;let i=PO(r),o=qf(r);if(i===null||o===null)continue;let a=n?.formFlagKeysByFormNode?.get(i);if(a===void 0||a.has(o))continue;let l=[...a].sort();t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.inputs.${_n.flagKey}`,reason:{de:`[setFlag/unknownFlag] Knoten \u201E${_e(e,r.id,"de")}\u201C (${r.id}) setzt \u201E${o}\u201C, aber das Formular von \u201E${_e(e,i,"de")}\u201C hat kein externes Merkmal dieses Namens`+(l.length>0?` (vorhanden: ${l.join(", ")}).`:" \u2014 es deklariert gar keins."),en:`[setFlag/unknownFlag] Node "${_e(e,r.id,"en")}" (${r.id}) sets "${o}", but the form of "${_e(e,i,"en")}" has no external flag of that name`+(l.length>0?` (present: ${l.join(", ")}).`:" \u2014 it declares none at all.")},severity:"error"})}return t}s(YJ,"checkSetFlagKeys");function HJ(e,n){let t=n?.readinessFormFieldsByFormNode,r=n?.readinessPartyConditionKeysByFormNode;if(t===void 0||r===void 0)return[];let i=[];for(let o of e.nodes){if(o.type!=="governedDocument"||o.production!=="resolver")continue;let a=o.form;if(!be(a)||!kr(a))continue;let l=t.get(a.owner),d=r.get(a.owner);if(l===void 0||d===void 0||d.size===0)continue;let c=jw(l,d);if(c.size===0)continue;let u=o.reads,p=(Array.isArray(u)?u:[]).filter(w=>un(w)&&w.owner===a.owner),h=jw(l,[...p.map(w=>w.path),...tP(o).filter(w=>w.owner===a.owner).map(w=>w.fieldKey)]),y=[...c].filter(w=>!h.has(w)).sort();if(y.length===0)continue;let k={de:_e(e,a.owner,"de"),en:_e(e,a.owner,"en")};i.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${o.id}.reads`,reason:{de:`[readiness/readsMissesPartyCondition] Knoten \u201E${_e(e,o.id,"de")}\u201C (${o.id}) erzeugt ein Dokument, dessen Vertragsparteien von Angaben im Formular \u201E${k.de}\u201C abh\xE4ngen, die er weder liest noch bindet: ${y.join(", ")}. Eine Korrektur darauf h\xE4lt den Knoten nicht an und kann nach der Ausstellung eine Vertragspartei entfernen \u2014 die Felder (oder den berechneten Schl\xFCssel) aus \u201E${k.de}\u201C in \`reads\` erg\xE4nzen.`,en:`[readiness/readsMissesPartyCondition] Node "${_e(e,o.id,"en")}" (${o.id}) generates a document whose contract parties depend on answers in the form "${k.en}" that it neither reads nor binds: ${y.join(", ")}. A correction to them does not hold the node and can remove a contract party after issuing \u2014 add the fields (or the computed key) from "${k.en}" to \`reads\`.`},severity:"warning"})}return i}s(HJ,"checkReadinessPartyConditions");function ok(e){let n=Object.keys(e.inputs??{});if(n.length===0)return[];let t=e.generatorStamp,r=e.production,i=e.templateStamp;if(e.type==="governedDocument"&&(r==="resolver"&&!Array.isArray(t?.inputSchema?.fields)||r==="template"&&!Array.isArray(i?.fields)))return[];let a=new Set(Zs(e).map(l=>l.id));return n.filter(l=>!a.has(l))}s(ok,"undeclaredInputKeys");function JJ(e,n){return e.nodes.flatMap(t=>[...ZJ(e,t,Zs(t),n),...QJ(e,t,n)])}s(JJ,"checkUnknownResources");function QJ(e,n,t){let r=[],i=new Set((He(n).workItemTemplates?.(n)??[]).map(a=>a.key)),o=new Set((n.tasks??[]).filter(a=>a.familyRequest!==void 0).map(a=>String(a.key)));for(let a of Wf(n)){if(a.leaf==="assign{}"&&!i.has(a.owner)||a.leaf==="tasks[].assign.group"&&a.missing&&o.has(a.owner))continue;let l=Us[a.leaf],d=`nodes.${n.id}.${a.path}`,c=s(h=>h==="de"?`Knoten \u201E${_e(e,n.id,"de")}\u201C (${n.id}), ${l.what.de} \u201E${a.owner}\u201C`:`node "${_e(e,n.id,"en")}" (${n.id}), ${l.what.en} "${a.owner}"`,"where");if(a.missing){if(!l.required){r.push({layer:"GRAPH",kind:"nodeRule",path:d,severity:"error",reason:{de:`[inputs/emptyReference] ${c("de")}: der Eintrag ist leer oder kein Schl\xFCssel \u2014 ${l.consequence.de}. Team w\xE4hlen oder den Eintrag entfernen.`,en:`[inputs/emptyReference] ${c("en")}: the entry is empty or no key \u2014 ${l.consequence.en}. Choose a team or remove the entry.`}});continue}r.push({layer:"GRAPH",kind:"nodeRule",path:d,severity:"error",reason:{de:`[workItems/needsTeam] ${c("de")}: kein Team gew\xE4hlt \u2014 ${l.consequence.de}. Jede Aufgabe geh\xF6rt der Warteschlange eines Teams.`,en:`[workItems/needsTeam] ${c("en")}: no team chosen \u2014 ${l.consequence.en}. Every task belongs to a team's queue.`}});continue}if(a.key===null)continue;let u=t?.teamKeys;if(u===void 0||u.has(a.key))continue;let p=[...u].sort().join(", ")||"\u2014";r.push({layer:"GRAPH",kind:"nodeRule",path:d,severity:"error",reason:{de:`[inputs/unknownResource] ${c("de")}: \u201E${a.key}\u201C ist kein Team dieses Mandanten \u2014 ${l.consequence.de}. Teams: ${p}.`,en:`[inputs/unknownResource] ${c("en")}: "${a.key}" is no team of this school \u2014 ${l.consequence.en}. Teams: ${p}.`}})}return r}s(QJ,"referenceIssues");function ZJ(e,n,t,r){let i=[];for(let o of t){if(!Kf(o.type))continue;let a=js[o.type].existence;if(a.check!=="generic")continue;let l=r?.[a.catalog];if(l===void 0)continue;let d=n.inputs?.[o.id];if(d?.kind!=="literal"||typeof d.value!="string"||l.has(d.value))continue;let c=js[o.type].label;i.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${n.id}.inputs.${o.id}`,reason:{de:`[inputs/unknownResource] Knoten \u201E${_e(e,n.id,"de")}\u201C (${n.id}) nennt im Eingang \u201E${o.label.de}\u201C ${c.de} \u201E${d.value}\u201C \u2014 diesen Schl\xFCssel kennt dieser Mandant nicht.`,en:`[inputs/unknownResource] Node "${_e(e,n.id,"en")}" (${n.id}) names the ${c.en.toLowerCase()} "${d.value}" in its input "${o.label.en}", which does not exist in this school.`},severity:"error"})}return i}s(ZJ,"unknownResourceIssues");function XJ(e){let n=[];for(let t of e.nodes)for(let r of ok(t))n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.inputs.${r}`,reason:{de:`[inputs/undeclared] Knoten \u201E${_e(e,t.id,"de")}\u201C (${t.id}) hat einen Eingang \u201E${r}\u201C, den sein Typ nicht deklariert \u2014 ein Rest einer fr\xFCheren Einstellung (z. B. eines anderen Generators). Im Parameter-Bereich ist er nicht sichtbar; entfernen.`,en:`[inputs/undeclared] Node "${_e(e,t.id,"en")}" (${t.id}) has an input "${r}" its type does not declare \u2014 a leftover of an earlier setting (e.g. another generator). It is not visible among the parameters; remove it.`},severity:"error"});return n}s(XJ,"checkUndeclaredInputs");function e4(e){let n=[];for(let t of e.nodes){let r=new Set;for(let i of Zs(t)){if(!r.has(i.id)){r.add(i.id);continue}n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.inputs.${i.id}`,reason:{de:`[inputs/duplicateSlot] Knoten \u201E${_e(e,t.id,"de")}\u201C (${t.id}) hat den Eingang \u201E${i.id}\u201C zweimal \u2014 ein Parameter des Generators oder der Vorlage tr\xE4gt den Namen eines Eingangs des Knotentyps. Den Parameter umbenennen.`,en:`[inputs/duplicateSlot] Node "${_e(e,t.id,"en")}" (${t.id}) has the input "${i.id}" twice \u2014 a parameter of the generator or template carries the name of an input of the node type. Rename the parameter.`},severity:"error"})}}return n}s(e4,"checkDuplicateSlots");function mC(e,n,t){let r=[],i=KJ(e);if(i.length>0)return i;r.push(...EJ(e)),r.push(...SJ(e)),r.push(...TJ(e)),r.push(...AJ(e)),r.push(...bJ(e)),r.push(...vJ(e)),r.push(...xJ(e)),r.push(...RJ(e)),r.push(...O_(e,n)),r.push(...IJ(e,n)),r.push(...OJ(e,n)),r.push(..._J(e,n)),r.push(...sP(e,n?.layout)),r.push(...NJ(e,n)),r.push(...PJ(e,n)),r.push(...DJ(e,n)),r.push(...v_(e,t)),r.push(...C_(e)),r.push(...q_(e)),r.push(...N_(e)),r.push(...P_(e)),r.push(...XJ(e)),r.push(...JJ(e,t)),r.push(...e4(e)),r.push(...FJ(e)),r.push(...LJ(e)),r.push(...IP(e,t)),r.push(...CP(e)),r.push(...NP(e)),r.push(...DP(e,t)),r.push(...VP(e,t)),r.push(...qJ(e)),r.push(...BJ(e,t)),r.push(...jJ(e,t)),r.push(...UJ(e)),r.push(...WJ(e,t)),r.push(...HJ(e,t)),r.push(...YJ(e,t)),r.push(...GJ(e,t)),r.push(...zJ(e)),r.push(...cC(e));for(let o of e.nodes){let a=He(o);a.validate&&r.push(...a.validate(o,e,t))}return r}s(mC,"checkGraph");function n4(e,n){let t=e.requiresOneOf;if(t===void 0)return[];let r=`nodes.${e.id}.requiresOneOf`,i=s(d=>({layer:"GRAPH",kind:"nodeRule",path:r,reason:d,severity:"error"}),"issue");if(e.type!=="decision")return[i({de:`[decision/requiresOneOfNotDecision] Knoten "${e.id}" (Typ "${e.type}") tr\xE4gt 'requiresOneOf' \u2014 die Regel gilt nur an Entscheidungsknoten (decision).`,en:`[decision/requiresOneOfNotDecision] Node "${e.id}" (type "${e.type}") carries 'requiresOneOf' \u2014 the rule only applies to decision nodes (decision).`})];if(!Array.isArray(t)||t.length===0||t.some(d=>typeof d!="string"||d.length===0))return[i({de:`[decision/requiresOneOfEmpty] 'requiresOneOf' an Knoten "${e.id}" muss eine nicht-leere Liste von Aktions-Keys sein \u2014 sonst Feld weglassen.`,en:`[decision/requiresOneOfEmpty] 'requiresOneOf' on node "${e.id}" must be a non-empty list of action keys \u2014 otherwise omit the field.`})];let o=n.map(d=>d.key).filter(d=>typeof d=="string"),a=[],l=new Set;for(let d of t){if(l.has(d)){a.push(i({de:`[decision/requiresOneOfDuplicate] 'requiresOneOf' an Knoten "${e.id}" nennt "${d}" doppelt.`,en:`[decision/requiresOneOfDuplicate] 'requiresOneOf' on node "${e.id}" names "${d}" twice.`}));continue}l.add(d),o.includes(d)||a.push(i({de:`[decision/requiresOneOfUnknownAction] 'requiresOneOf' an Knoten "${e.id}" nennt "${d}", aber dieser Knoten hat keine optionale Aktion mit diesem Key \u2014 die Regel w\xE4re nie erf\xFCllbar. `+(o.length===0?"Der Knoten hat keine optionalen Aktionen.":`Optionale Aktionen dieses Knotens: ${o.join(", ")}.`),en:`[decision/requiresOneOfUnknownAction] 'requiresOneOf' on node "${e.id}" names "${d}", but this node has no optional action with that key \u2014 the rule could never be met. `+(o.length===0?"The node has no optional actions.":`Optional actions of this node: ${o.join(", ")}.`)}))}return a}s(n4,"checkRequiresOneOf");function t4(e){return e.nodes.flatMap(n=>ok(n).map(t=>({nodeId:n.id,key:t,binding:n.inputs?.[t]?.kind==="binding"})))}s(t4,"undeclaredInputCells");function hC(e,n){let t=t4(e).filter(o=>n.bindings||!o.binding);if(t.length===0)return{graph:e,dropped:t};let r=new Map;for(let o of t)r.set(o.nodeId,(r.get(o.nodeId)??new Set).add(o.key));let i=e.nodes.map(o=>{let a=r.get(String(o.id));if(a===void 0)return o;let l=Object.fromEntries(Object.entries(o.inputs).filter(([d])=>!a.has(d)));return{...o,inputs:l}});return{graph:{...e,nodes:i},dropped:t}}s(hC,"dropUndeclaredInputs");function sk(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(sk,"isObject");function gC(e){return sk(e)&&e.type==="governedDocument"&&("template"in e||"cockpitFields"in e)}s(gC,"oldShape");function yC(e){return(e?.nodes??[]).some(gC)}s(yC,"needsTemplateStampMove");function r4(e){let n=e.generatorStamp?.inputSchema?.fields;if(e.production==="resolver")return Array.isArray(n)?n:null;let t=e.templateStamp?.fields;return e.production==="template"&&Array.isArray(t)?t:null}s(r4,"stampedFields");function i4(e){let n=String(e.id);if("template"in e&&"templateStamp"in e)return{unmoved:{nodeId:n,reason:"templateAndStamp"}};let t={...e},r=[];if("template"in e){let{template:i}=e;if(delete t.template,sk(i))t.templateStamp={fields:Array.isArray(i.fields)?i.fields:[],...i.localeField===void 0?{}:{localeField:i.localeField}};else return{unmoved:{nodeId:n,reason:"templateNotObject"}}}if("cockpitFields"in e){let i=Array.isArray(e.cockpitFields)?e.cockpitFields.filter(l=>typeof l=="string"):[];delete t.cockpitFields;let o=sk(e.inputs)?{...e.inputs}:{},a=r4(t);if(a===null&&i.length>0)return{unmoved:{nodeId:n,key:i[0],reason:"noStamp"}};for(let l of i){let d=l in o&&o[l]?.kind!=="unset",c=(a??[]).find(u=>u.key===l);if(c===void 0)r.push({nodeId:n,key:l,reason:"unknownKey"});else{if(c.type==="party"||c.type==="personList")continue;c.processSource!==void 0?r.push({nodeId:n,key:l,reason:"processSource"}):d?r.push({nodeId:n,key:l,reason:"cellExists"}):o[l]={kind:"cockpit"}}}t.inputs=o}return{node:t,reports:r}}s(i4,"moveNode");function wC(e){let n=[],t=[],r=[],i=e.nodes.map(o=>{if(!gC(o))return o;let a=i4(o);return"unmoved"in a?(r.push(a.unmoved),o):(n.push(String(o.id)),t.push(...a.reports),a.node)});return n.length===0?{graph:e,moved:n,reports:t,unmoved:r}:{graph:{...e,nodes:i},moved:n,reports:t,unmoved:r}}s(wC,"moveTemplateStampAndCockpit");var kC=wf,o4="applicant.applicationSubmitted";function Mp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Mp,"isObject");function bC(e){return Mp(e)&&e.type==="form"&&typeof e.id=="string"&&!vt(e)}s(bC,"isCreatingFormNode");function s4(e){return Mp(e.notifications)&&kC in e.notifications}s(s4,"hasSubmittedBinding");function ak(e){let n={toBind:[],alreadyBound:[],malformed:[]};for(let t of e?.nodes??[])bC(t)&&(t.notifications!==void 0&&!Mp(t.notifications)?n.malformed.push(t.id):s4(t)?n.alreadyBound.push(t.id):n.toBind.push(t.id));return n}s(ak,"submitReceiptInventory");function vC(e){let{toBind:n}=ak(e);if(n.length===0)return{graph:e,bound:[]};let t=new Set(n),r=e.nodes.map(i=>{if(!bC(i)||!t.has(i.id))return i;let o=Mp(i.notifications)?i.notifications:{};return{...i,notifications:{...o,[kC]:{templateId:o4}}}});return{graph:{...e,nodes:r},bound:n}}s(vC,"bindSubmitReceipt");var zo=["park","advance"],nr="whenNothingOwed",xC={park:{de:"Jemand schaut drauf",en:"Someone looks at it"},advance:{de:"Durchreichen",en:"Pass through"}};function SC(e){let n=e.inputs?.[nr],t=n?.kind==="literal"?n.value:void 0;return lk(t)?t:null}s(SC,"reviewModeOrNull");function lk(e){return zo.includes(e)}s(lk,"isReviewMode");function dk(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(dk,"isObject");function AC(e){return dk(e)&&e.type==="review"&&!(dk(e.inputs)&&nr in e.inputs)}s(AC,"lacksMode");function EC(e){return(e?.nodes??[]).some(AC)}s(EC,"needsReviewMode");function TC(e){let n=[],t=e.nodes.map(r=>{if(!AC(r))return r;n.push(r.id);let i=dk(r.inputs)?r.inputs:{};return{...r,inputs:{...i,[nr]:{kind:"literal",value:"park"}}}});return{graph:{...e,nodes:t},set:n}}s(TC,"setReviewModePark");function qp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(qp,"isObject");function $C(e){let{notifications:n,bound:t}=ap(e.notifications,{tasks:[]},e);return{next:n,bound:t}}s($C,"bindingsFor");function RC(e){let n={toBind:[],malformed:[]};for(let t of e?.nodes??[])if(!(!qp(t)||typeof t.id!="string"||ta(t).length===0)){if(t.notifications!==void 0&&!qp(t.notifications)){n.malformed.push(t.id);continue}for(let r of $C(t).bound)n.toBind.push(`${t.id}.${r}`)}return n}s(RC,"appointmentLetterInventory");function IC(e){let n=[],t=!1,r=e.nodes.map(i=>{if(!qp(i)||typeof i.id!="string"||ta(i).length===0||i.notifications!==void 0&&!qp(i.notifications))return i;let{next:o,bound:a}=$C(i);return a.length===0?i:(t=!0,n.push(...a.map(l=>`${i.id}.${l}`)),{...i,notifications:o})});return t?{graph:{...e,nodes:r},bound:n}:{graph:e,bound:[]}}s(IC,"bindAppointmentLetters");function ba(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(ba,"isObject");var OC=["id","label","dataFlow"],_C=["audience","populates","stages","expectedOutcomes"];function NC(e){return Array.isArray(e.assignmentRules)&&e.assignmentRules.some(n=>ba(n)&&typeof n.slot=="string")}s(NC,"carriesStringSlots");function PC(e){return(e.nodes??[]).some(n=>ba(n)&&n.type==="form"&&_C.some(t=>t in n))}s(PC,"carriesRetiredFormNodeKey");var a4=[{key:"generatorPin",editor:!0,holds:tO,what:{de:"Generator als `resolver`",en:"generator as `resolver`"}},{key:"setFlagProperties",editor:!0,holds:MO,what:{de:"Formular und Merkmal eines \u201EFlag setzen\u201C-Knotens als Eigenschaften",en:'form and flag of a "Set flag" node as properties'}},{key:"scalarProperties",editor:!0,holds:UO,what:{de:"Einstellungen eines Knotens als Eigenschaften statt als Eing\xE4nge",en:"a node's settings as properties instead of inputs"}},{key:"nodeConfigProperties",editor:!0,holds:ZO,what:{de:"Hinweis einer Zahlung als Eigenschaft oder ein entferntes Muster-Dokument",en:"a payment's note as a property, or a removed sample document"}},{key:"outcomeWithoutSemantic",editor:!0,holds:zI,what:{de:"Entscheidungsausg\xE4nge ohne Bedeutung",en:"decision outcomes without a meaning"}},{key:"startNodeOutcomes",editor:!0,holds:JI,what:{de:"ein Start-Knoten mit eigenen Ausg\xE4ngen",en:"a start node with its own outcomes"}},{key:"templateParameters",editor:!0,holds:yC,what:{de:"Parameter einer Vorlage am Knoten oder Cockpit-Felder als Liste",en:"a template's parameters on the node, or cockpit fields as a list"}},{key:"paymentSettlement",editor:!0,holds:o_,what:{de:"Zahlungsknoten mit \u201EAbrechnung\u201C (`inputs.settlement`) statt \u201EZahlungsweg\u201C (`inputs.mode`)",en:'payment node with "Settlement" (`inputs.settlement`) instead of "Payment mode" (`inputs.mode`)'}},{key:"documentRef",editor:!0,holds:u_,what:{de:"Dokument eines anderen Knotens als `document:$node.<Knoten>.document` statt als Slot `artifact:<Slot>`",en:"another node's document as `document:$node.<node>.document` instead of the slot `artifact:<slot>`"}},{key:"formView",editor:!0,holds:d_,what:{de:"Ansicht einer Aufgabe als `formView` statt als Ansichts-Adresse `view`",en:"a task's view as `formView` instead of the view address `view`"}},{key:"reviewWithoutMode",editor:!0,holds:EC,what:{de:"Pr\xFCfknoten ohne \u201EWenn nichts zu pr\xFCfen ist\u201C",en:'review nodes without "When nothing is owed"'}},{key:"taskAssignUser",editor:!1,holds:s(e=>zf(e).length>0,"holds"),what:{de:"eine Aufgabe mit fester Person (`assign.userId`)",en:"a task with a fixed person (`assign.userId`)"}},{key:"retiredGraphKey",editor:!1,holds:s(e=>OC.some(n=>n in e),"holds"),what:{de:"`graph.id` / `graph.label` / `graph.dataFlow`",en:"`graph.id` / `graph.label` / `graph.dataFlow`"}},{key:"assignmentSlotString",editor:!1,holds:NC,what:{de:"Zust\xE4ndigkeitsregeln mit Slot als Text (`responsible` / `team:<Schl\xFCssel>`)",en:"assignment rules with a slot as text (`responsible` / `team:<key>`)"}},{key:"retiredFormNodeKey",editor:!1,holds:PC,what:{de:"Formularknoten mit `audience` / `populates` / `stages` / `expectedOutcomes`",en:"form nodes with `audience` / `populates` / `stages` / `expectedOutcomes`"}}];function CC(e){if(!ba(e)||!Array.isArray(e.nodes))return[];let n=e;return a4.filter(t=>t.holds(n)).map(({key:t,what:r,editor:i})=>({key:t,what:r,editor:i}))}s(CC,"legacyGraphShapes");function DC(e,n){let t=n.answers??{},r=[],i=[],o=e,a=OC.filter($=>$ in o);if(a.length>0){let $={...o};for(let I of a)delete $[I],r.push({message:`graph.${I}: deleted (read by nothing)`});o=$}if(PC(o)&&(o={...o,nodes:o.nodes.map($=>{if(!ba($)||$.type!=="form")return $;let I=_C.filter(B=>B in $);if(I.length===0)return $;let G={...$};for(let B of I)delete G[B];return r.push({nodeId:String($.id),message:`form node: deleted ${I.map(B=>`\`${B}\``).join(", ")} (read by nothing)`}),G})}),NC(o)){let $=o.assignmentRules.map((I,G)=>{if(!ba(I)||typeof I.slot!="string")return I;let B=Of(I.slot);return B===null?(i.push({code:"assignment/slotUnknown",answer:"edit",message:`assignmentRules[${G}].slot "${I.slot}" is neither \`responsible\` nor \`team:<key>\` \u2014 edit it by hand`}),I):(r.push({message:`assignmentRules[${G}].slot "${I.slot}" \u2192 ${JSON.stringify(B)}`}),{...I,slot:B})});o={...o,assignmentRules:$}}let l=rO(o);o=l.graph;for(let $ of l.moved)r.push({nodeId:$,message:"generator / template pin moved into its input"});for(let $ of l.unmoved)i.push({code:`generatorPin/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`the generator or template pin cannot be moved (${$.reason}) \u2014 edit the node by hand`});let d=qO(o);o=d.graph;for(let $ of d.moved)r.push({nodeId:$,message:"setFlag `target` / `flagKey` / `value` moved into its inputs"});for(let $ of d.unmoved)i.push({code:`setFlag/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`the setFlag properties cannot be moved (${$.reason}) \u2014 edit the node by hand`});let c=GO(o);o=c.graph;for(let $ of c.moved)r.push({nodeId:$,message:"scalar settings moved into inputs"});for(let $ of c.unmoved)i.push({code:`scalar/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`\`${$.key}\` cannot be moved into an input (${$.reason}) \u2014 edit the node by hand`});let u=XO(o);o=u.graph;for(let $ of u.moved)r.push({nodeId:$,message:"payment note moved into `inputs.reason` / retired sample document deleted"});for(let $ of u.unmoved)i.push({code:`nodeConfig/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`\`${$.key}\` cannot be moved into an input (${$.reason}) \u2014 edit the node by hand`});let p=wC(o);o=p.graph;for(let $ of p.moved){let I=o.nodes.find(le=>ba(le)&&le.id===$),G=I?.inputs?.documentTemplate,B=G?.kind==="literal"&&typeof G.value=="string"?G.value:null;r.push({nodeId:$,message:I!==void 0&&"templateStamp"in I&&B!==null?`template parameters moved onto \`templateStamp\` / cockpit list into cells \u2014 the record \`${B}\` must declare the same parameters (tenant catalog \`documentTemplates[].parameters\` / \`templates:setParameters\`) before publish, else [governedDocument/templateWithoutParameters]`:"cockpit list moved into `{ kind: 'cockpit' }` cells"})}for(let $ of p.reports)r.push({nodeId:$.nodeId,message:`cockpit field \`${$.key??""}\` deleted (${$.reason}: ${$.reason==="unknownKey"?"the stamp declares no such parameter":$.reason==="processSource"?"the case fills it itself":"the input already holds a cell"})`});for(let $ of p.unmoved)i.push({code:`templateStamp/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:$.reason==="noStamp"?"the cockpit list cannot be judged: the node carries no parameter stamp \u2014 run `offer workflow restamp-pins` against the environment, then upgrade again":$.reason==="templateAndStamp"?"the node carries both `template` and `templateStamp` \u2014 delete one by hand":"`template` is no object \u2014 edit the node by hand"});let h=QI(o);o=h.graph;for(let $ of h.moved)r.push({nodeId:$,message:"start node: own `outcomes` / `event` / `effect` deleted (the node type declares its outcome)"});for(let $ of h.unmoved)i.push({code:`eventTrigger/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`the start node cannot be reduced to its type's outcome (${$.reason}) \u2014 edit the node by hand`});let y=WI(o,t.semantics);o=y.graph;for(let $ of y.written){if($.source==="formerDefault"){r.push({nodeId:$.nodeId,message:`outcome \`${$.outcomeId}\`: semantic "${$.semantic}" (DEFAULT \u2014 the meaning it ran with; the retired id parser knew no other)`,defaulted:{answer:"semantic",answerKey:`${$.nodeId}.${$.outcomeId}`,value:$.semantic}});continue}r.push({nodeId:$.nodeId,message:`outcome \`${$.outcomeId}\`: semantic "${$.semantic}" (${$.source==="answer"?"answered":"the meaning the retired id parser gave this id"})`})}for(let $ of y.refused)i.push({code:$.answer===void 0?"outcome/formerMeaningNotAllowed":"outcome/semanticNotAllowed",nodeId:$.nodeId,answer:"semantic",answerKey:`${$.nodeId}.${$.outcomeId}`,candidates:$.allowed,message:$.answer===void 0?`${$.nodeType} outcome \`${$.outcomeId}\` ran as "${Ny($.outcomeId)??""}", which a ${$.nodeType} outcome may no longer carry \u2014 say which one it is`:`${$.nodeType} outcome \`${$.outcomeId}\`: "${$.answer}" is not a meaning a ${$.nodeType} outcome may carry`});for(let $ of y.invalid)i.push({code:"outcome/semanticInvalid",nodeId:$.nodeId,answer:"edit",candidates:bt,message:`outcome \`${$.outcomeId}\` carries the semantic "${$.value}", which is no meaning \u2014 edit it`});let k=eO(o,n.selection,t.waitlistPolicy);o=k.graph;for(let $ of k.moved){let I=$.policy.waitlistOrder;r.push({nodeId:$.nodeId,message:`waitlist policy into inputs: ${l4($.policy)} (${$.source==="answer"?"answered":$.source==="manifest"?"from manifest `selection`":"DEFAULT \u2014 the manifest stated no `selection.waitlistOrder`; the former code default it ran with"})`,...$.source==="formerDefault"?{defaulted:{answer:"waitlistPolicy",answerKey:$.nodeId,value:I}}:{}})}for(let $ of k.refused)i.push({code:`waitlist/${$.reason}`,nodeId:$.nodeId,answer:"waitlistPolicy",answerKey:$.nodeId,candidates:Jt,message:"manifest `selection` is malformed \u2014 say the queue order of this waitlist"});let w=s_(o);o=w.graph;for(let $ of w.moved)r.push({nodeId:$,message:"payment: `inputs.settlement` \u2192 `inputs.mode` (separate \u2192 manual)"});for(let $ of w.refused)i.push({code:`collectPayment/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:$.reason==="bothCells"?"the payment node carries both `inputs.settlement` and `inputs.mode` \u2014 delete `settlement` by hand":"`inputs.settlement` is no literal online | separate \u2014 set `inputs.mode` by hand"});let v=c_(o);o=v.graph;for(let $ of v.moved)r.push({nodeId:$.split(".")[0],message:`\`formView\` \u2192 \`view\` (${$})`});for(let $ of v.refused){let I=$.taskKey===void 0?"the node":`task "${$.taskKey}"`;i.push({code:`view/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:$.reason==="bothFields"?`${I} carries both \`formView\` and \`view\` \u2014 delete \`formView\` by hand`:`${I}'s \`formView\` is no { form, key } \u2014 set \`view\` by hand`})}let A=f_(o);o=A.graph;for(let $ of A.moved)r.push({nodeId:$.split(".")[0],message:`documents: \`document:$node.<node>.document\` \u2192 \`artifact:<slot>\` (${$})`});for(let $ of A.refused)i.push({code:`workItems/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`task "${$.taskKey}" links a document whose node declares no single slot \u2014 name the slot as \`artifact:<slot>\` by hand`});if(n_(o)){let $=t_(o,t.payee);o=$.graph;for(let I of $.set)r.push({nodeId:I.nodeId,message:`online payment: payee "${I.payee}" (answered)`});for(let I of $.refused)i.push({code:"collectPayment/payeeMissing",nodeId:I,answer:"payee",answerKey:I,message:"an online payment names the Tr\xE4ger its money goes to \u2014 say its key (a `legal_entities.configKey` of the tenant)"})}for(let $ of ak(o).malformed)i.push({code:"submitReceipt/notificationsMalformed",nodeId:$,answer:"edit",message:"the form node's `notifications` is no record \u2014 edit it by hand"});let E=vC(o);o=E.graph;for(let $ of E.bound)r.push({nodeId:$,message:"submit receipt bound to `notifications.submitted` (`applicant.applicationSubmitted`, sent by code before)"});let R=TC(o);o=R.graph;for(let $ of R.set)r.push({nodeId:$,message:"review: `whenNothingOwed` = park (every review parked before the input existed)"});for(let $ of RC(o).malformed)i.push({code:"appointmentLetters/notificationsMalformed",nodeId:$,answer:"edit",message:"the node's `notifications` is no record \u2014 edit it by hand"});let P=IC(o);o=P.graph;for(let $ of P.bound){let I=$.indexOf(".");r.push({nodeId:$.slice(0,I),message:`appointment letter bound to \`notifications.${$.slice(I+1)}\` (the standard letter, sent by code before)`})}let F=zf(o).filter($=>!$.hasTeam);for(let $ of F)i.push({code:"task/userWithoutTeam",nodeId:$.nodeId,answer:"edit",message:`task \`${$.taskKey}\` names a fixed person and no team \u2014 give it a team (\`assign.group\`) by hand`});let b=p_(o);o=b.graph;for(let $ of b.dropped.filter(I=>I.hasTeam))r.push({nodeId:$.nodeId,message:`task \`${$.taskKey}\`: \`assign.userId\` deleted (the team holds the row)`});let O=hC(o,{bindings:!0});o=O.graph;for(let $ of O.dropped){if(!$.binding){r.push({nodeId:$.nodeId,message:`input \`${$.key}\` deleted (no slot of the node declares it)`});continue}r.push({nodeId:$.nodeId,message:`input \`${$.key}\` deleted (DEFAULT \u2014 a binding no slot declares: no slot handed its value to the node, but the readiness gate waited for it; the node no longer waits for that value)`,defaulted:{answer:"undeclaredBinding",answerKey:`${$.nodeId}.${$.key}`,value:"deleted"}})}return{graph:o,changes:r,refusals:i}}s(DC,"upgradeGraph");function l4(e){return`waitlistOrder=${e.waitlistOrder}`}s(l4,"formatPolicy");function gi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(gi,"isObject");var FC="admission.generic",LC=Object.keys($f).filter(e=>e!=="label");function MC(e){return gi(e.smartforms)?Object.entries(e.smartforms):[]}s(MC,"smartformEntries");function d4(e){let n=[];MC(e.index).some(([,i])=>gi(i)&&"outcomeFnRef"in i)&&n.push({de:"`smartforms.<slug>.outcomeFnRef` in bundle.yaml",en:"`smartforms.<slug>.outcomeFnRef` in bundle.yaml"});let t=Object.keys(e.manifest).filter(i=>Object.hasOwn(Rl,i));if(t.length>0){let i=t.map(o=>`\`${o}\``).join(", ");n.push({de:`manifest.json mit ${i}`,en:`manifest.json with ${i}`})}Object.values(e.smartforms??{}).some(i=>LC.some(o=>o in i))&&n.push({de:"Formulardateien mit `id` / `outcomeIds` / `schoolSlug`",en:"form files with `id` / `outcomeIds` / `schoolSlug`"});let r=e.workflow;return r!==void 0&&(gi(r.progressWiring)&&"layoutId"in r.progressWiring&&n.push({de:"`progressWiring.layoutId`",en:"`progressWiring.layoutId`"}),n.push(...CC(r.graph).map(i=>i.what))),n}s(d4,"legacyBundleShapes");function jp(e,n){let t=d4(e);t.length!==0&&se("BUNDLE_NEEDS_UPGRADE",{de:`offer: ${n} stammt aus einem \xE4lteren Bundle-Format (${t.map(r=>r.de).join("; ")}). Zuerst \`plexus-cli offer upgrade --dir <Bundle>\` ausf\xFChren (Probelauf, beantwortet die offenen Fragen), dann mit \`--write\` schreiben und erneut pr\xFCfen.`,en:`offer: ${n} is in an older bundle format (${t.map(r=>r.en).join("; ")}). Run \`plexus-cli offer upgrade --dir <bundle>\` first (a dry run that asks what it cannot decide), then write with \`--write\` and validate again.`})}s(jp,"assertBundleCurrent");function Kp(e){let n=s(t=>Array.isArray(t)?t.map(n):gi(t)?Object.fromEntries(Object.keys(t).sort().map(r=>[r,n(t[r])])):t,"sort");return JSON.stringify(n(e))}s(Kp,"canonical");function qC(e,n={}){let t=[],r=[],i=e.index,o=MC(i);if(o.some(([,u])=>gi(u)&&Object.keys(u).length>0)){let u={};for(let[p,h]of o){if(!gi(h)||Object.keys(h).length===0){u[p]=h;continue}let{outcomeFnRef:y,...k}=h;if(Object.keys(k).length>0||y!==void 0&&y!==FC){r.push({file:"bundle.yaml",code:"index/smartformEntry",answer:"edit",message:`smartforms.${p} carries ${Object.keys(h).map(w=>`\`${w}\``).join(", ")} \u2014 only \`outcomeFnRef: ${FC}\` is known; edit the entry to {} by hand`}),u[p]=h;continue}t.push({file:"bundle.yaml",message:`smartforms.${p}.outcomeFnRef deleted (a form routes by its own declared outcomes)`}),u[p]={}}i={...i,smartforms:u}}let a={},l=e.workflow,d;for(let[u,p]of Object.entries(e.manifest)){if(u==="selection"){d=p,t.push({file:"manifest.json",message:"`selection` deleted (its queue policy goes to the waitlist node's inputs; release strategy and deadline were read by nothing)"});continue}if(u==="progressLayout"){l===void 0?t.push({file:"manifest.json",message:"`progressLayout` deleted (the bundle has no workflow it could belong to)"}):l.progressLayout===void 0?(l={...l,progressLayout:p},t.push({file:"manifest.json",message:"`progressLayout` moved to workflow.json `progressLayout`"})):Kp(l.progressLayout)===Kp(p)?t.push({file:"manifest.json",message:"`progressLayout` deleted (workflow.json carries the same layout)"}):(r.push({file:"manifest.json",code:"manifest/progressLayoutTwice",answer:"edit",message:"`progressLayout` differs from workflow.json `progressLayout` \u2014 keep one by hand"}),a[u]=p);continue}let h=Object.hasOwn(Rl,u)?Rl[u]:void 0;if(h===void 0){r.push({file:"manifest.json",code:"manifest/unknownKey",answer:"edit",message:`unknown key \`${u}\` \u2014 manifest.json carries no key; decide by hand where it belongs`}),a[u]=p;continue}t.push({file:"manifest.json",message:`\`${u}\` deleted (${h.en})`})}if(l!==void 0){if(gi(l.progressWiring)&&"layoutId"in l.progressWiring){let{layoutId:p,...h}=l.progressWiring;l={...l,progressWiring:h},t.push({file:"workflow.json",message:"`progressWiring.layoutId` deleted (the layout is the workflow's own)"})}let u=l.graph;if(gi(u)&&Array.isArray(u.nodes)){let p=DC(u,{selection:d,answers:n});l={...l,graph:p.graph},t.push(...p.changes.map(h=>({...h,file:"workflow.json"}))),r.push(...p.refusals.map(h=>({...h,file:"workflow.json"})))}else r.push({file:"workflow.json",code:"workflow/graphShape",answer:"edit",message:"`graph` is no object with a node list"})}let c=e.smartforms;if(c!==void 0){let u={};for(let[p,h]of Object.entries(c)){let y={...h},k=`smartforms/${p}.json`;for(let w of LC)if(w in h){if(w==="outcomeIds"){let v=Array.isArray(h.outcomes)?h.outcomes.map(A=>gi(A)?A.id:void 0):[];if(Kp([...Array.isArray(h.outcomeIds)?h.outcomeIds:[]].map(String).sort())!==Kp(v.map(String).sort())){r.push({file:k,code:"smartform/outcomeIdsDiffer",answer:"edit",message:"`outcomeIds` differs from the ids of `outcomes[]` \u2014 reconcile them by hand"});continue}}delete y[w],t.push({file:k,message:`\`${w}\` deleted (${$f[w].en})`})}u[p]=y}c=u}return{bundle:{index:i,manifest:a,...c!==void 0?{smartforms:c}:{},...l!==void 0?{workflow:l}:{}},changes:t,refusals:r}}s(qC,"upgradeOfferBundle");var c4={createManifest:x.workflow.createManifest,publishManifest:x.workflow.publishManifest,publishOfferInternal:x.workflow.publishOfferInternal,publishOfferExternal:x.workflow.publishOfferExternal,getOfferPublishState:x.workflow.getOfferPublishState,upsertCustomField:x.admission.upsertCustomField,upsertDerivedAttributeRule:x.admission.upsertDerivedAttributeRule,createSmartForm:x.forms.createSmartForm,getSmartFormBySlug:x.forms.getSmartFormBySlug,saveSmartFormDraft:x.forms.saveSmartFormDraft,publishSmartForm:x.forms.publishSmartForm,createWorkflow:x.workflow.createWorkflow,getWorkflowGraph:x.workflow.getWorkflowGraph,saveWorkflowDraft:x.workflow.saveWorkflowDraft,publishWorkflow:x.workflow.publishWorkflow},zke={createManifest:et.workflow.createManifestInternal,publishManifest:et.workflow.publishManifestInternal,publishOfferInternal:et.workflow.publishOfferInternalInternal,publishOfferExternal:et.workflow.publishOfferExternalInternal,getOfferPublishState:et.workflow.getOfferPublishStateInternal,upsertCustomField:et.admission.upsertCustomFieldInternal,upsertDerivedAttributeRule:et.admission.upsertDerivedAttributeRuleInternal,createSmartForm:et.forms.createSmartFormInternal,getSmartFormBySlug:et.forms.getSmartFormBySlugInternal,saveSmartFormDraft:et.forms.saveSmartFormDraftInternal,publishSmartForm:et.forms.publishSmartFormInternal,createWorkflow:et.workflow.createWorkflowInternal,getWorkflowGraph:et.workflow.getWorkflowGraphInternal,saveWorkflowDraft:et.workflow.saveWorkflowDraftInternal,publishWorkflow:et.workflow.publishWorkflowInternal};function ck(e,n){for(let[t,r]of Object.entries(e.smartforms??{})){(r===null||typeof r!="object"||Array.isArray(r))&&se("INVALID",{de:`offer: ${n}: smartforms.${t} muss eine leere Zuordnung ({}) sein.`,en:`offer: ${n}: smartforms.${t} must be an empty mapping ({}).`});let i=Object.keys(r);if(i.length===0)continue;let o=i.map(l=>`\`${l}\``).join(", "),a=i.includes("outcomeFnRef");se("INVALID",{de:`offer: ${n}: smartforms.${t} enth\xE4lt unbekannte Schl\xFCssel ${o} \u2014 der Eintrag muss leer sein ({}).${a?" `outcomeFnRef` geh\xF6rt nicht mehr zum Bundle-Format: ein Formular entscheidet \xFCber seine eigenen Ergebnisse. Die Zeile l\xF6schen.":""}`,en:`offer: ${n}: smartforms.${t} carries unknown key(s) ${o} \u2014 the entry must be empty ({}).${a?" `outcomeFnRef` is no longer part of the bundle format: a form routes by its own declared outcomes. Delete the line.":""}`})}}s(ck,"assertSmartformEntries");function KC(e){let n=s(t=>Array.isArray(t)?t.map(n):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(r=>[r,n(t[r])])):t,"sort");return JSON.stringify(n(e))}s(KC,"canonicalJson");function jC(e,n){return n==null?!0:KC(e)!==KC(n)}s(jC,"changed");async function VC(e,n,t,r={},i=c4){let{index:o}=n;jp({index:o,manifest:n.manifest,...n.smartforms!==void 0?{smartforms:n.smartforms}:{},...n.workflow!==void 0?{workflow:n.workflow}:{}},`bundle of ${o.slugs.manifest}`),ck(o,`bundle of ${o.slugs.manifest}`);let a=Tf(n.manifest);a.length>0&&se("INVALID",{de:`offer: manifest.json von ${o.slugs.manifest} ist ung\xFCltig:
11246
11246
  - ${a.join(`
11247
11247
  - `)}`,en:`offer: manifest.json of ${o.slugs.manifest} is invalid:
11248
11248
  - ${a.join(`
11249
11249
  - `)}`});let l=[],d=o.tenant,c=!1,u=[];if(!t.dryRun){for(let w of o.customFields??[])await e.mutation(i.upsertCustomField,{client:d,key:w.key,label:w.label,data:w.data}),u.push(`field:${w.key}`);for(let w of o.derivedAttributes??[])await e.mutation(i.upsertDerivedAttributeRule,{client:d,key:w.key,type:w.type,expression:w.expression}),u.push(`derived:${w.key}`)}(o.customFields?.length??0)+(o.derivedAttributes?.length??0)>0&&l.push({step:"catalog",action:"scaffolded",detail:u.join(", ")||"(dry-run)"});let h=(await e.mutation(i.createManifest,{client:d,slug:o.slugs.manifest,label:o.label,...o.sortOrder!==void 0?{sortOrder:o.sortOrder}:{}})).offerVersionId;if(!t.dryRun&&r.afterManifestPublish){let w=await r.afterManifestPublish(h);l.push({step:"link",action:"scaffolded",...w?{detail:w}:{}})}(o.contractTemplates?.length??0)>0&&se("INVALID",{de:"Das Angebot deklariert contractTemplates[], die beim Anwenden noch nicht unterst\xFCtzt werden. Entfernen Sie diese Eintr\xE4ge.",en:"The offer declares contractTemplates[], which are not yet supported when applying. Remove these entries."});let y={};if(n.smartforms!==void 0)for(let[w,v]of Object.entries(n.smartforms)){let{label:A,...E}=v;Pi(A)||se("INVALID",{de:`[i18n/missingTranslation] SmartForm "${w}": \`label\` muss ein zweisprachiger Text ({ de, en }) sein.`,en:`[i18n/missingTranslation] SmartForm "${w}": \`label\` must be a bilingual text ({ de, en }).`});let R=A,F=(await e.mutation(i.createSmartForm,{client:d,slug:w,label:R,offerVersionId:h})).smartFormDefinitionId;y[w]=F;let b=await e.query(i.getSmartFormBySlug,{client:d,offerVersionId:h,slug:w}),O=jC({definition:E},b?.def?{definition:b.def.definition}:void 0);O&&!t.dryRun&&await e.mutation(i.saveSmartFormDraft,{smartFormDefinitionId:F,definition:E}),O&&(c=!0),l.push({step:`smartform:${w}`,action:O?"created":"unchanged"})}let k;if(n.workflow!==void 0){o.slugs.workflow||se("INVALID",{de:"Das B\xFCndel enth\xE4lt einen Workflow, aber slugs.workflow fehlt.",en:"The bundle contains a workflow, but slugs.workflow is missing."}),k=(await e.mutation(i.createWorkflow,{client:d,offerVersionId:h})).workflowDefinitionId;let A=await e.query(i.getWorkflowGraph,{workflowDefinitionId:k}),E={graph:Cs(n.workflow.graph),progressLayout:n.workflow.progressLayout??A?.progressLayout,progressWiring:n.workflow.progressWiring??A?.progressWiring},R=A?{graph:Cs(A.graph),progressLayout:A.progressLayout,progressWiring:A.progressWiring}:void 0,P=jC(E,R);P&&!t.dryRun&&await e.mutation(i.saveWorkflowDraft,{workflowDefinitionId:k,graph:n.workflow.graph,...n.workflow.progressLayout!==void 0?{progressLayout:n.workflow.progressLayout}:{},...n.workflow.progressWiring!==void 0?{progressWiring:n.workflow.progressWiring}:{}}),P&&(c=!0),l.push({step:"workflow",action:P?"created":"unchanged"})}if(t.publish){let w=t.publishStage??"external",v=await e.query(i.getOfferPublishState,{client:d,offerKey:o.slugs.manifest});v===null&&se("NOT_FOUND",{de:`Der Mandant \u201E${d}\u201C hat keine Angebotsfamilie \u201E${o.slugs.manifest}\u201C zum Ver\xF6ffentlichen. Pr\xFCfen Sie den Mandanten und den Manifest-Slug.`,en:`Tenant \u201C${d}\u201D has no offer family \u201C${o.slugs.manifest}\u201D to publish. Check the tenant and the manifest slug.`});let A=w==="internal"?v.draftDiffersFromInternal:v.draftDiffersFromExternal,E=t.dryRun&&c||A;if(E&&!t.dryRun){let R=w==="external"&&v.internalCandidateMatchesDraft;if(!R){for(let P of Object.values(y))await e.mutation(i.publishSmartForm,{smartFormDefinitionId:P});k!==void 0&&await e.mutation(i.publishWorkflow,{workflowDefinitionId:k})}if(r.beforeOfferPublish){let P=await r.beforeOfferPublish(h,k);l.push({step:"pre-publish",action:"scaffolded",...P?{detail:P}:{}})}w==="internal"?await e.mutation(i.publishOfferInternal,{offerVersionId:h}):R?await e.mutation(i.publishOfferExternal,{offerVersionId:h}):await e.mutation(i.publishManifest,{offerVersionId:h}),l.push({step:w==="internal"?"offer:internal":"offer",action:"published",...R?{detail:"promoted the tested candidate"}:{}})}else l.push({step:w==="internal"?"offer:internal":"offer",action:E?"published":"already-live"})}return{steps:l,offerVersionId:h,...k!==void 0?{workflowDefinitionId:k}:{},...Object.keys(y).length>0?{smartFormDefIds:y}:{}}}s(VC,"applyOfferSteps");var sd="bundle.yaml",fk="manifest.json",ad="smartforms",pk="workflow.json";function va(e){return JSON.parse(he(e,"utf8"))}s(va,"readJson");function Ne(e){return JSON.stringify(uk(e),null,2)+`
11250
- `}s(Ne,"canonicalJson");function uk(e){return Array.isArray(e)?e.map(uk):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,uk(e[n])])):e}s(uk,"sortKeys");function qe(e){let n=Y.resolve(e),t=Y.join(n,sd);if(!Ae(t))throw new Error(`offer: no ${sd} in ${n}`);let r=_i.load(he(t,"utf8"));UC(r,t);let i=Y.join(n,pk),o,a=Object.keys(r.smartforms??{});if(a.length>0){o={};for(let c of a){let u=Y.join(n,ad,`${c}.json`);if(!Ae(u))throw new Error(`offer: bundle.yaml declares smartform "${c}" but ${ad}/${c}.json is missing`);o[c]=va(u)}}let l=va(Y.join(n,fk)),d=Ae(i)?va(i):void 0;return jp({index:r,manifest:l,...o?{smartforms:o}:{},...d?{workflow:d}:{}},t),ck(r,t),{dir:n,index:r,manifest:l,...o?{smartforms:o}:{},...d?{workflow:d}:{}}}s(qe,"readBundle");function BC(e){let n=Y.resolve(e),t=Y.join(n,sd);if(!Ae(t))throw new Error(`offer: no ${sd} in ${n}`);let r=_i.load(he(t,"utf8"));UC(r,t);let i=Object.keys(r.smartforms??{}),o;if(i.length>0){o={};for(let l of i){let d=Y.join(n,ad,`${l}.json`);if(!Ae(d))throw new Error(`offer: bundle.yaml declares smartform "${l}" but ${ad}/${l}.json is missing`);o[l]=va(d)}}let a=Y.join(n,pk);return{dir:n,index:r,manifest:va(Y.join(n,fk)),...o?{smartforms:o}:{},...Ae(a)?{workflow:va(a)}:{}}}s(BC,"readRawBundle");function Vp(e,n,t,r){Ae(e)&&Ne(r(he(e,"utf8")))===Ne(n)||ze(e,t,"utf8")}s(Vp,"writeIfChanged");function Et(e){if(Fn(e.dir,{recursive:!0}),Vp(Y.join(e.dir,sd),e.index,_i.dump(e.index,{lineWidth:100,sortKeys:!1}),n=>_i.load(n)),Vp(Y.join(e.dir,fk),e.manifest,Ne(e.manifest),JSON.parse),e.smartforms!==void 0){let n=Y.join(e.dir,ad);Fn(n,{recursive:!0});for(let[t,r]of Object.entries(e.smartforms))Vp(Y.join(n,`${t}.json`),r,Ne(r),JSON.parse)}e.workflow!==void 0&&Vp(Y.join(e.dir,pk),e.workflow,Ne(e.workflow),JSON.parse)}s(Et,"writeBundle");function UC(e,n){let t=[];if(e?.module||t.push("module"),e?.tenant||t.push("tenant"),e?.label||t.push("label"),e?.slugs?.manifest||t.push("slugs.manifest"),t.length>0)throw new Error(`offer: ${n} is missing required keys: ${t.join(", ")}`)}s(UC,"assertIndex");function GC(e,n,t={}){let r=new Map;return{slots:MN(e,n,t.slots??e.map(o=>o.slot),{person:s(o=>`person:${o}`,"person"),creator:s(()=>(t.creator===void 0&&se("INVALID",{de:"[assignment/noCreator] Die zutreffende Zeile weist die anlegende Person zu, aber es wurde kein --creator angegeben (ein Selbststart hat keine).",en:"[assignment/noCreator] The matching row assigns the creating person, but no --creator was given (a self-start has none)."}),`creator:${t.creator}`),"creator"),rotation:s((o,{slot:a})=>{let l=t.rotationPrevious?.[a]??null,d=_N({pool:o.configKeys,mode:o.mode,previous:l,eligible:new Set(o.configKeys.filter(c=>!(t.left??[]).includes(c))),openCounts:new Map(o.configKeys.map(c=>[c,t.openCounts?.[c]??0]))});return d===null&&se("INVALID",{de:`[assignment/rotationEmpty] Platz \u201E${a}\u201C: alle aus dem Pool sind ausgeschieden`,en:`[assignment/rotationEmpty] slot '${a}': everyone in the pool has left`}),r.set(a,{pool:[...o.configKeys],mode:o.mode,previous:l,picked:d}),`person:${d}`},"rotation")}).map(o=>{let a=r.get(o.slot);return{slot:o.slot,row:o.ruleIndex+1,assign:o.assign,value:o.value.kind==="queue"?"queue":o.value.value,...a!==void 0?{rotation:a}:{}}})}}s(GC,"simulateRules");function zC(e,n){let t={};for(let r of n??[]){let i=r.lastIndexOf("=");if(i<=0||i===r.length-1)throw new Error(`assignment simulate: ${e} takes <key>=<value>, got '${r}'`);let o=r.slice(0,i);if(Object.hasOwn(t,o))throw new Error(`assignment simulate: ${e} names '${o}' twice`);t[o]=r.slice(i+1)}return t}s(zC,"parsePairs");function u6(e){let n={};for(let[t,r]of Object.entries(zC("--open",e))){let i=Number(r);if(!Number.isInteger(i)||i<0)throw new Error(`assignment simulate: --open ${t}=${r} is no count`);n[t]=i}return n}s(u6,"parseCounts");function f6(e,n){if(e===void 0==(n===void 0))throw new Error("assignment simulate: pass exactly one of --env-json '<json>' or --env-file <path>");let t=e??he(n,"utf8"),r=JSON.parse(t);if(typeof r!="object"||r===null||Array.isArray(r))throw new Error("assignment simulate: the environment must be a JSON object");return r}s(f6,"parseEnv");var mk=class extends xe{static{s(this,"AssignmentSimulateCommand")}static paths=[["assignment","simulate"]];static usage=T.Usage({category:"Admission",description:"Evaluate an offer bundle's assignment rule over an application's environment ($env), offline",details:`
11250
+ `}s(Ne,"canonicalJson");function uk(e){return Array.isArray(e)?e.map(uk):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,uk(e[n])])):e}s(uk,"sortKeys");function qe(e){let n=Y.resolve(e),t=Y.join(n,sd);if(!Ae(t))throw new Error(`offer: no ${sd} in ${n}`);let r=_i.load(he(t,"utf8"));UC(r,t);let i=Y.join(n,pk),o,a=Object.keys(r.smartforms??{});if(a.length>0){o={};for(let c of a){let u=Y.join(n,ad,`${c}.json`);if(!Ae(u))throw new Error(`offer: bundle.yaml declares smartform "${c}" but ${ad}/${c}.json is missing`);o[c]=va(u)}}let l=va(Y.join(n,fk)),d=Ae(i)?va(i):void 0;return jp({index:r,manifest:l,...o?{smartforms:o}:{},...d?{workflow:d}:{}},t),ck(r,t),{dir:n,index:r,manifest:l,...o?{smartforms:o}:{},...d?{workflow:d}:{}}}s(qe,"readBundle");function BC(e){let n=Y.resolve(e),t=Y.join(n,sd);if(!Ae(t))throw new Error(`offer: no ${sd} in ${n}`);let r=_i.load(he(t,"utf8"));UC(r,t);let i=Object.keys(r.smartforms??{}),o;if(i.length>0){o={};for(let l of i){let d=Y.join(n,ad,`${l}.json`);if(!Ae(d))throw new Error(`offer: bundle.yaml declares smartform "${l}" but ${ad}/${l}.json is missing`);o[l]=va(d)}}let a=Y.join(n,pk);return{dir:n,index:r,manifest:va(Y.join(n,fk)),...o?{smartforms:o}:{},...Ae(a)?{workflow:va(a)}:{}}}s(BC,"readRawBundle");function Vp(e,n,t,r){Ae(e)&&Ne(r(he(e,"utf8")))===Ne(n)||ze(e,t,"utf8")}s(Vp,"writeIfChanged");function Et(e){if(Fn(e.dir,{recursive:!0}),Vp(Y.join(e.dir,sd),e.index,_i.dump(e.index,{lineWidth:100,sortKeys:!1}),n=>_i.load(n)),Vp(Y.join(e.dir,fk),e.manifest,Ne(e.manifest),JSON.parse),e.smartforms!==void 0){let n=Y.join(e.dir,ad);Fn(n,{recursive:!0});for(let[t,r]of Object.entries(e.smartforms))Vp(Y.join(n,`${t}.json`),r,Ne(r),JSON.parse)}e.workflow!==void 0&&Vp(Y.join(e.dir,pk),e.workflow,Ne(e.workflow),JSON.parse)}s(Et,"writeBundle");function UC(e,n){let t=[];if(e?.module||t.push("module"),e?.tenant||t.push("tenant"),e?.label||t.push("label"),e?.slugs?.manifest||t.push("slugs.manifest"),t.length>0)throw new Error(`offer: ${n} is missing required keys: ${t.join(", ")}`)}s(UC,"assertIndex");function GC(e,n,t={}){let r=new Map;return{slots:MN(e,n,t.slots??e.map(o=>o.slot),{person:s(o=>`person:${o}`,"person"),creator:s(()=>(t.creator===void 0&&se("INVALID",{de:"[assignment/noCreator] Die zutreffende Zeile weist die anlegende Person zu, aber es wurde kein --creator angegeben (ein Selbststart hat keine).",en:"[assignment/noCreator] The matching row assigns the creating person, but no --creator was given (a self-start has none)."}),`creator:${t.creator}`),"creator"),rotation:s((o,{slot:a})=>{let l=t.rotationPrevious?.[a]??null,d=_N({pool:o.configKeys,mode:o.mode,previous:l,eligible:new Set(o.configKeys.filter(c=>!(t.left??[]).includes(c))),openCounts:new Map(o.configKeys.map(c=>[c,t.openCounts?.[c]??0]))});return d===null&&se("INVALID",{de:`[assignment/rotationEmpty] Platz \u201E${a}\u201C: alle aus dem Pool sind ausgeschieden`,en:`[assignment/rotationEmpty] slot '${a}': everyone in the pool has left`}),r.set(a,{pool:[...o.configKeys],mode:o.mode,previous:l,picked:d}),`person:${d}`},"rotation")}).map(o=>{let a=r.get(o.slot);return{slot:o.slot,row:o.ruleIndex+1,assign:o.assign,value:o.value.kind==="queue"?"queue":o.value.value,...a!==void 0?{rotation:a}:{}}})}}s(GC,"simulateRules");function zC(e,n){let t={};for(let r of n??[]){let i=r.lastIndexOf("=");if(i<=0||i===r.length-1)throw new Error(`assignment simulate: ${e} takes <key>=<value>, got '${r}'`);let o=r.slice(0,i);if(Object.hasOwn(t,o))throw new Error(`assignment simulate: ${e} names '${o}' twice`);t[o]=r.slice(i+1)}return t}s(zC,"parsePairs");function u4(e){let n={};for(let[t,r]of Object.entries(zC("--open",e))){let i=Number(r);if(!Number.isInteger(i)||i<0)throw new Error(`assignment simulate: --open ${t}=${r} is no count`);n[t]=i}return n}s(u4,"parseCounts");function f4(e,n){if(e===void 0==(n===void 0))throw new Error("assignment simulate: pass exactly one of --env-json '<json>' or --env-file <path>");let t=e??he(n,"utf8"),r=JSON.parse(t);if(typeof r!="object"||r===null||Array.isArray(r))throw new Error("assignment simulate: the environment must be a JSON object");return r}s(f4,"parseEnv");var mk=class extends xe{static{s(this,"AssignmentSimulateCommand")}static paths=[["assignment","simulate"]];static usage=T.Usage({category:"Admission",description:"Evaluate an offer bundle's assignment rule over an application's environment ($env), offline",details:`
11251
11251
  The environment carries every key the rule reads ($env): offer
11252
11252
  {key,title}, unit {key,name} (key = the unit's configKey), stage
11253
11253
  {key,name,gradeLevel|null}, run {key,name,startDate|null}, applicant
11254
11254
  {language: 'de'|'en'|null (null = no applicant account), channel:
11255
11255
  'self-service'|'staff'}. A missing key fails loud, exactly like a start.
11256
- `,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=f.String("--dir",{required:!0,description:"Offer bundle directory (its workflow.json carries the rule)"});envJson=f.String("--env-json",{description:"The application's environment ($env) as JSON"});envFile=f.String("--env-file",{description:"\u2026or a file holding it"});creator=f.String("--creator",{description:"Label for the staff creator (only a staff start has one)"});rotationPrevious=f.Array("--rotation-previous",{description:"<slot>=<personKey>: the last pick of that slot's \u201EReihum\u201C row (repeatable; none = its first start)"});left=f.Array("--left",{description:"<personKey>: someone who has left \u2014 every rotation skips them (repeatable)"});open=f.Array("--open",{description:"<personKey>=<n>: open tasks, for a leastLoaded rotation (repeatable; absent = 0)"});async execute(){let n=qe(this.dir),t=DN(n.workflow?.graph,`bundle ${this.dir}`),r=f6(this.envJson,this.envFile),i=GC(t,r,{...this.creator!==void 0?{creator:this.creator}:{},rotationPrevious:zC("--rotation-previous",this.rotationPrevious),openCounts:u6(this.open),left:this.left??[]});return this.print(i,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}},WC=[mk];import{createHash as p6}from"node:crypto";var hk=/^[a-z0-9][a-z0-9-]*$/;function xa(e){return hk.test(e)}s(xa,"isFileKey");function Wo(e){return e.trim()===""?"is empty":e==="."||e===".."?"is not a file name":/[/\\]/.test(e)?"must not contain a path separator":/[\u0000-\u001f]/.test(e)?"must not contain control characters":null}s(Wo,"fileNameDefect");var JC={".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"},Bp={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".avif":"image/avif",".woff2":"font/woff2"};function Sa(e){return p6("sha256").update(e).digest("hex")}s(Sa,"sha256Hex");function gk(e,n=JC){let t=Y.resolve(e),r;try{r=he(t)}catch{throw new Error(`File not found: ${e}`)}let i=n[Y.extname(t).toLowerCase()];if(i===void 0)throw new Error(`${e}: unsupported file type \u2014 allowed: ${Object.keys(n).join(", ")}.`);return{bytes:r,filename:Y.basename(t),mimeType:i,sha256:Sa(r),sizeBytes:r.length}}s(gk,"readLocalFile");var m6={tenantFile:x.tenantFiles.platformGenerateUploadUrl,brandingAsset:x.branding.platformGenerateBrandingAssetUploadUrl,brandingLogo:x.branding.platformGenerateBrandingLogoUploadUrl};async function Yo(e,n,t,r,i){let{uploadUrl:o,uploadTicket:a}=await e.mutation(m6[i],{client:n}),l=await e.upload(o,t,r);return await e.mutation(x.uploads.registerUpload,{uploadTicket:a,storageId:l}),l}s(Yo,"uploadStaged");async function QC(e,n,t,r){return await Yo(e,n,t,r,"tenantFile")}s(QC,"uploadTenantFile");function yk(e){let n=[...e].filter(([,t])=>"fileName"in t||"size"in t).map(([t])=>t);if(n.length!==0)throw new Error(`[cli/serverPredatesFileRef] ${n.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(yk,"requireFileRefNames");async function ld(e,n){let t=await e.query(x.tenantFiles.platformList,{client:n});return yk(t.map(r=>[`files["${r.key}"]`,r])),t}s(ld,"listLibrary");function ZC(e,n,t,r,i){let o=gk(Y.resolve(e,n),i);if(o.mimeType!==t)throw new Error(`${r}: ${n} is ${o.mimeType}, the entry declares ${t}.`);return o}s(ZC,"readSnapshotEntry");function XC(e,n){let t=new Map,r=(e.files??[]).map(l=>{if(l.path===void 0)return l;let{path:d,...c}=l,u=ZC(n,d,c.mimeType,`files["${c.key}"]`,JC);return t.set(c.key,u),{...c,sha256:u.sha256,sizeBytes:u.sizeBytes}}),i=YC(e.tenant.brandingAssets,n,"tenant"),o=new Map,a=(e.foundation?.legalEntities??[]).map(l=>{if(l.brandingAssets===void 0)return l;let d=YC(l.brandingAssets,n,`foundation.legalEntities.${l.key}`);return o.set(l.key,d.bytes),{...l,brandingAssets:d.assets}});return{config:{...e,tenant:{...e.tenant,...i.assets!==void 0?{brandingAssets:i.assets}:{}},...e.foundation!==void 0?{foundation:{...e.foundation,legalEntities:a}}:{},files:r},bytes:t,brandingBytes:i.bytes,legalEntityBrandingBytes:o}}s(XC,"resolveSnapshotFiles");function YC(e,n,t){let r=new Map,i=e;if(i===void 0)return{assets:void 0,bytes:r};let o={};for(let[a,l]of Object.entries(i)){if(l.path===void 0){o[a]=l;continue}let{path:d,...c}=l,u=ZC(n,d,c.mimeType,`${t}.brandingAssets.${a}`,Bp);r.set(a,u),o[a]={...c,sha256:u.sha256,sizeBytes:u.sizeBytes}}return{assets:o,bytes:r}}s(YC,"resolveSnapshotBranding");async function eD(e,n,t,r,i){let o={},a={contents:o,changed:[],unavailable:[]};for(let l of e){if(n.get(l.key)===l.sha256)continue;a.changed.push(l.key);let d=await t(l.key);if(d===void 0){a.unavailable.push(l.key);continue}if(Sa(d)!==l.sha256)throw new Error(`${l.at}: the supplied bytes do not match sha256 ${l.sha256}.`);i||(o[l.key]=await r(d,l.mimeType))}return a}s(eD,"stageChanged");async function nD(e,n,t,r,i){let o=new Map(Object.entries(await e.query(x.tenantFiles.platformFileHashes,{client:n})??{})),a=new Map(t.map(l=>[l.key,l]));return await eD(t.map(l=>({key:l.key,sha256:l.sha256,mimeType:l.mimeType,at:`files["${l.key}"]`})),o,l=>r(a.get(l)),(l,d)=>Yo(e,n,l,d,"tenantFile"),i)}s(nD,"stageFileContents");function tD(e){return e===void 0?"tenant":`foundation.legalEntities.${e}`}s(tD,"brandingHolder");async function Up(e,n,t){let r=await e.query(x.branding.platformBrandingAssets,{client:n,...t!==void 0?{legalEntity:t}:{}});return yk(Object.entries(r??{}).map(([i,o])=>[`${tD(t)}.brandingAssets.${i}`,o])),r}s(Up,"listBrandingAssets");async function wk(e,n,t,r,i,o){let a=new Map(Object.entries(await Up(e,n,o)??{}).map(([d,c])=>[d,c.sha256])),l=tD(o);return await eD(Object.entries(t??{}).map(([d,c])=>({key:d,sha256:c.sha256,mimeType:c.mimeType,at:`${l}.brandingAssets.${d}`})),a,r,(d,c)=>Yo(e,n,d,c,"brandingAsset"),i)}s(wk,"stageBrandingAssets");async function rD(e,n,t,r){if(e===null||n===void 0)throw new Error(`${t}: its stored object is gone \u2014 ${r}`);let i=await fetch(e);if(!i.ok)throw new Error(`download of ${t} failed (${i.status}).`);let o=new Uint8Array(await i.arrayBuffer());if(Sa(o)!==n)throw new Error(`download of ${t} does not match its sha256 ${n}.`);return o}s(rD,"downloadVerified");async function kk(e){return await rD(e.url,e.sha256,`"${e.key}"`,"replace it with `files put` first.")}s(kk,"downloadLibraryFile");async function bk(e,n,t){return await rD(n.url,n.sha256,t===void 0?`branding/${e}`:`branding/${t}/${e}`,"upload it again with `branding set-logo` / `branding set-font` first.")}s(bk,"downloadBrandingAsset");function h6(e,n,t){let r=Object.keys(Bp).find(i=>Bp[i]===n);if(r===void 0)throw new Error(`export: branding/${e} is ${n}, which a snapshot cannot name (${Object.keys(Bp).join(", ")}).`);if(t===void 0)return Y.join("branding",`${e}${r}`);if(!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(t))throw new Error(`export: legal entity key "${t}" is not a safe directory name for its brand files.`);return Y.join("branding",t,`${e}${r}`)}s(h6,"brandingAssetPath");function iD(e,n,t){let r=Y.join(e,n);Fn(Y.dirname(r),{recursive:!0}),ze(r,t)}s(iD,"writeBeside");async function oD(e,n,t,r){yk([...t.files.map(c=>[`files["${c.key}"]`,c]),...Object.entries(t.tenant.brandingAssets??{}).map(([c,u])=>[`tenant.brandingAssets.${c}`,u]),...(t.foundation?.legalEntities??[]).flatMap(c=>Object.entries(c.brandingAssets??{}).map(([u,p])=>[`foundation.legalEntities.${c.key}.brandingAssets.${u}`,p]))]);let i=new Map((await ld(e,n)).map(c=>[c.key,c])),o=Y.dirname(r),a=[];for(let c of t.files){let u=i.get(c.key);if(u===void 0)throw new Error(`export: "${c.key}" vanished from the library between two reads \u2014 rerun.`);let p=Wo(c.filename);if(p!==null||!xa(c.key))throw new Error(`export: "${c.key}" / "${c.filename}" is not a safe path (${p??"bad key"}).`);let h=Y.join("files",c.key,c.filename);iD(o,h,await kk(u)),a.push({...c,path:h})}let l=await HC(e,n,t.tenant.brandingAssets,o,void 0),d=[];for(let c of t.foundation?.legalEntities??[]){if(c.brandingAssets===void 0){d.push(c);continue}d.push({...c,brandingAssets:await HC(e,n,c.brandingAssets,o,c.key)})}return{...t,tenant:{...t.tenant,...l!==void 0?{brandingAssets:l}:{}},...t.foundation!==void 0?{foundation:{...t.foundation,legalEntities:d}}:{},files:a}}s(oD,"writeSnapshotFiles");async function HC(e,n,t,r,i){if(t===void 0)return;let o=await Up(e,n,i)??{},a={};for(let[l,d]of Object.entries(t)){let c=o[l],u=h6(l,d.mimeType,i);if(c===void 0||c.sha256!==d.sha256)throw new Error(`export: ${u} changed between two reads \u2014 rerun.`);iD(r,u,await bk(l,c,i)),a[l]={...d,path:u}}return a}s(HC,"writeSnapshotBranding");var g6={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml",".avif":"image/avif"};function sD(e){return g6[Y.extname(e).toLowerCase()]}s(sD,"guessImageContentType");async function y6(e,n){if(e===void 0==(n===void 0))throw new Error("Pass exactly one of --file <path> or --url <url>.");if(n!==void 0&&ln())throw new Error("Hosted agents cannot fetch arbitrary logo URLs. Upload the image to the chat and use --file <path>.");if(e!==void 0){let a=Y.resolve(e),l;try{l=he(a)}catch{throw new Error(`File not found: ${e}`)}let d=sD(a);if(d===void 0)throw new Error(`Cannot infer an image content-type from "${Y.basename(a)}" \u2014 use a .png/.jpg/.webp/.gif file.`);return{bytes:new Uint8Array(l),contentType:d}}let t=await fetch(n);if(!t.ok)throw new Error(`Fetch failed for ${n} (${t.status} ${t.statusText}).`);let r=new Uint8Array(await t.arrayBuffer()),i=t.headers.get("content-type")?.split(";")[0]?.trim(),o=i&&i.startsWith("image/")?i:sD(new URL(n).pathname);if(o===void 0)throw new Error(`Response for ${n} is not an image (content-type "${i??"unknown"}").`);return{bytes:r,contentType:o}}s(y6,"loadLogoBytes");function Aa(){return f.String("--legal-entity",{description:"A legal entity's config key \u2014 its own brand, which overrides the tenant's for its units"})}s(Aa,"legalEntityOption");function Ea(e){return e===void 0?{}:{legalEntity:e}}s(Ea,"ownerArgs");async function w6(e,n,t,r){return await Yo(e,n,t,r,"brandingLogo")}s(w6,"uploadLogo");var vk=class extends D{static{s(this,"BrandingSetLogoCommand")}static paths=[["branding","set-logo"]];static usage=T.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=f.String("--file",{description:"Local image file to upload"});url=f.String("--url",{description:"Fetch the logo image from this URL"});legalEntity=Aa();async execute(){let n=await this.caller(),t=this.requireTenant(n),{bytes:r,contentType:i}=await y6(this.file,this.url),o=await w6(n,t,r,i);return await n.mutation(x.branding.platformSetBrandingLogo,{client:t,...Ea(this.legalEntity),slot:"primary",storageId:o}),this.print({tenant:t,slot:"primary",contentType:i,bytes:r.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}},xk=class extends D{static{s(this,"BrandingClearLogoCommand")}static paths=[["branding","clear-logo"]];static usage=T.Usage({category:"Branding",description:"Remove a tenant's portal logo"});legalEntity=Aa();async execute(){let n=await this.caller(),t=this.requireTenant(n);return await n.mutation(x.branding.platformClearBrandingLogo,{client:t,...Ea(this.legalEntity),slot:"primary"}),this.print({tenant:t,slot:"primary",cleared:!0},r=>[{field:"tenant",value:r.tenant},{field:"slot",value:r.slot},{field:"cleared",value:String(r.cleared)}]),0}};function aD(e){if(e!=="heading"&&e!=="body")throw new Error(`branding: --slot must be heading or body (got "${e}")`);return e}s(aD,"parseFontSlot");var Sk=class extends D{static{s(this,"BrandingSetFontCommand")}static paths=[["branding","set-font"]];static usage=T.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=f.String("--slot",{required:!0,description:"heading | body"});file=f.String("--file",{required:!0,description:"Local .woff2 file"});legalEntity=Aa();async execute(){let n=aD(this.slot),t=Y.resolve(this.file),r;try{r=he(t)}catch{throw new Error(`File not found: ${this.file}`)}let i=await this.caller(),o=this.requireTenant(i),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),{storageId:l}=await i.action(x.brandingFonts.platformSetBrandingFont,{client:o,...Ea(this.legalEntity),slot:n,bytes:a});return this.print({tenant:o,slot:n,bytes:r.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}},Ak=class extends D{static{s(this,"BrandingClearFontCommand")}static paths=[["branding","clear-font"]];static usage=T.Usage({category:"Branding",description:"Remove a tenant's portal font file for a slot (the family stays)"});slot=f.String("--slot",{required:!0,description:"heading | body"});legalEntity=Aa();async execute(){let n=aD(this.slot),t=await this.caller(),r=this.requireTenant(t);return await t.mutation(x.branding.platformClearBrandingFont,{client:r,...Ea(this.legalEntity),slot:n}),this.print({tenant:r,slot:n,cleared:!0},i=>[{field:"tenant",value:i.tenant},{field:"slot",value:i.slot},{field:"cleared",value:String(i.cleared)}]),0}},Ek=class extends D{static{s(this,"BrandingSetThemeCommand")}static paths=[["branding","set-theme"]];static usage=T.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=f.String("--file",{required:!0,description:"Branding theme JSON"});legalEntity=Aa();async execute(){let n=await this.caller(),t=this.requireTenant(n),r=Y.resolve(this.file),i;try{i=JSON.parse(he(r,"utf8"))}catch(o){throw new Error(`Cannot read branding JSON ${this.file}: ${kt(o)}`,{cause:o})}return await n.mutation(x.branding.platformUpdateBranding,{client:t,...Ea(this.legalEntity),branding:i}),this.print({tenant:t,applied:!0},o=>[{field:"tenant",value:o.tenant},{field:"applied",value:String(o.applied)}]),0}},Tk=class extends D{static{s(this,"BrandingShowCommand")}static paths=[["branding","show"]];static usage=T.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=Aa();async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.query(x.branding.platformGetBranding,{client:t,...Ea(this.legalEntity)});return this.print(r),0}},lD=[Tk,Ek,vk,xk,Sk,Ak];var Ta=s(()=>f.String("--output",{hidden:!0}),"retiredOutputOption"),wn=s(()=>f.Boolean("--force",!1,{description:"Overwrite an existing --out file."}),"forceOption");function $a(e){if(e.retiredOutput===void 0)return e.out;if(e.out!==void 0&&e.out!==e.retiredOutput)throw new Oe(`--out "${e.out}" and --output "${e.retiredOutput}" disagree \u2014 pass only --out.`);return sn(e.context.stderr,"--output","--out"),e.retiredOutput}s($a,"resolveOut");function Pn(e,n){let t=Y.resolve(e);if(Ae(t)&&!n)throw new Oe(`${t} exists \u2014 pick another --out or pass --force.`);return t}s(Pn,"assertOutFree");function k6(e){try{return Or(e)}catch{throw new Oe(`${e} is not a directory \u2014 --out names a directory here.`)}}s(k6,"entriesOf");function $k(e,n){let t=Y.resolve(e);if(Ae(t)&&k6(t).length>0&&!n)throw new Oe(`${t} is not empty \u2014 pick another --out or pass --force.`);return t}s($k,"assertOutDirFree");function dD(e,n,t){let r=Pn(e,t),i=n.map(o=>Y.join(Y.dirname(r),o)).filter(o=>Ae(o));if(i.length>0&&!t)throw new Oe(`${i.join(", ")} exist(s) beside --out \u2014 pick another directory or pass --force.`);return r}s(dD,"assertSnapshotOutFree");function Gp(e){(!Number.isSafeInteger(e)||e<0)&&se("INVALID",{de:"Betr\xE4ge m\xFCssen nichtnegative ganze Centbetr\xE4ge sein.",en:"Amounts must be non-negative whole amounts in cents."})}s(Gp,"assertMoney");var Rk=["month","year","once","unit"];var b6=s(e=>e!==void 0&&/^[1-9]\d{0,8}$/.test(e),"positiveIntegerText");function yi(e,n){return se("CONFLICT",{de:e,en:n})}s(yi,"missing");var cD=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 uD(e,n,t){return{label:n,kind:"chosen",valueType:"choice",choices:t,resolve(r){let i=r.selections?.[e];return(!i||!t.includes(i))&&yi(`Die Auswahl f\xFCr \u201E${n.de}\u201C fehlt oder ist ung\xFCltig.`,`The selection for \u201C${n.en}\u201D is missing or invalid.`),{value:i,explanation:{de:`${n.de}: ${i} (Vertragsauswahl)`,en:`${n.en}: ${i} (contract selection)`}}}}}s(uD,"chosen");function Ik(e,n){let t=e.enrollment,r=t?.contextDate??n;return(!t||!t.startDate||t.startDate>r||t.endDate&&t.endDate<r)&&yi("F\xFCr dieses Datum fehlt eine eindeutige Einschreibung.","An unambiguous enrollment is missing for this date."),t}s(Ik,"enrollment");var v6={paymentFrequency:uD("paymentFrequency",{de:"Zahlungsweise",en:"Payment frequency"},["monthly","yearly"]),gradeLevel:{label:{de:"Klassenstufe",en:"Grade level"},kind:"derived",valueType:"integer",resolve(e,n){let t=Ik(e,n).gradeLevel;return(!Number.isSafeInteger(t)||t<1)&&yi("Die Klassenstufe fehlt.","The grade level is missing."),{value:t,explanation:{de:`Klassenstufe ${t} am ${n}`,en:`Grade ${t} on ${n}`}}}},schoolYear:{label:{de:"Schuljahr",en:"School year"},kind:"derived",valueType:"integer",resolve(e,n){let t=Ik(e,n).schoolYear;return(!Number.isSafeInteger(t)||t<1)&&yi("F\xFCr dieses Datum fehlt ein j\xE4hrlicher Schuljahreslauf.","An annual school-year run is missing for this date."),{value:t,explanation:{de:`Schuljahr ${t}/${t+1}`,en:`School year ${t}/${t+1}`}}}},siblingRank:{label:{de:"Geschwisterrang",en:"Sibling rank"},kind:"derived",valueType:"integer",resolve(e,n){if(e.chosenCriteria?.includes("siblingRank")){let c=e.selections?.siblingRank;return b6(c)||yi("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&&se("CONFLICT",e.unavailable.siblingRank);let t=e.siblings?[...new Map(e.siblings.filter(c=>c.eligible).map(c=>[c.partyId,c])).values()]:void 0;(!e.partyId||!t?.some(c=>c.partyId===e.partyId))&&yi("F\xFCr dieses Datum fehlt die Sch\xFClerrolle des Kindes.","The child\u2019s Student role is missing for this date."),t.some(c=>!cD(c.firstEnrolledOn)||c.firstEnrolledOn>n)&&yi("F\xFCr den Geschwisterrang fehlt ein g\xFCltiger erster Einschreibungsbeginn.","A valid first enrollment start is missing for sibling ranking.");let r=t.find(c=>c.partyId===e.partyId),i=r.firstEnrolledOn,o=t.filter(c=>c.firstEnrolledOn===i);o.length>1&&o.some(c=>!cD(c.birthDate)||c.birthDate>n)&&yi("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<r.birthDate||c.birthDate===r.birthDate&&c.partyId<r.partyId,"before"),l=t.filter(c=>c.firstEnrolledOn<i).length+o.filter(c=>c!==r&&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 ${t.length} berechtigten Kindern am ${n}; erste Einschreibung am ${i}, zuerst eingeschriebene Kinder zuerst${d.de}.`,en:`Child ${l} of ${t.length} eligible children on ${n}; first enrollment on ${i}, first enrolled first${d.en}.`}}}},program:{label:{de:"Programm",en:"Program"},kind:"derived",valueType:"program",resolve(e,n){let t=Ik(e,n).programId;return t||yi("Das Programm fehlt.","The program is missing."),{value:t,explanation:{de:`Programm der Einschreibung am ${n}`,en:`Enrollment program on ${n}`}}}},admissionFeeTier:uD("admissionFeeTier",{de:"Anmeldegeb\xFChrensatz",en:"Admission fee tier"},["100","75","50"])},x6=Object.fromEntries(Object.entries(v6).map(([e,n])=>[e,{...n,matchSchema:{parse(t){return A6(n,t),t}},matches:S6}])),zbe=Object.keys(x6);function S6(e,n){return"else"in n?!0:"eq"in n?e===n.eq:"in"in n?n.in.includes(e):typeof e=="number"&&(n.gte===void 0||e>=n.gte)&&(n.lte===void 0||e<=n.lte)}s(S6,"matchesPrice");function A6(e,n){let t=s(()=>se("INVALID",{de:"Der Match passt nicht zum Preiskriterium.",en:"The match does not fit the price criterion."}),"fail");if(!n||typeof n!="object"||Array.isArray(n))return t();let r=n,i=Object.keys(r).sort().join();if(i==="else"&&r.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(!(i==="eq"&&o(r.eq))&&!(i==="in"&&Array.isArray(r.in)&&r.in.length>0&&new Set(r.in).size===r.in.length&&r.in.every(o))&&!(e.valueType==="integer"&&["gte","lte","gte,lte"].includes(i)&&Object.values(r).every(a=>Number.isSafeInteger(a)&&Number(a)>=1)&&(r.gte===void 0||r.lte===void 0||Number(r.gte)<=Number(r.lte))))return t()}s(A6,"validateMatch");function fD(e,n){if(Object.keys(n).some(t=>!["percent","amountMinor"].includes(t))&&se("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 n&&!("amountMinor"in n)){(!Number.isFinite(n.percent)||n.percent<0||n.percent>100)&&se("INVALID",{de:"Prozentwerte m\xFCssen zwischen 0 und 100 liegen.",en:"Percentages must be between 0 and 100."});return}if(e==="absolute"&&"amountMinor"in n&&!("percent"in n))return Gp(n.amountMinor);se("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(fD,"validateRule");var E6=/^[a-z][a-z0-9_-]{0,63}$/;function pD(e){return E6.test(e)}s(pD,"isTemplateConfigKey");import{createHash as _6}from"node:crypto";import{inflateRawSync as N6}from"node:zlib";var mD=/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/,T6=/{{\s*([^{}]+?)\s*}}|<<\s*([^<>]+?)\s*>>/g,$6=/^[#/]\s*/;function R6(e){let n=e.trim(),t=n.match(/^{{\s*([^{}]+?)\s*}}$/);if(t)return t[1]?.trim()??n;let r=n.match(/^<<\s*([^<>]+?)\s*>>$/);return r?r[1]?.trim()??n:n}s(R6,"innerTemplatePlaceholder");function zp(e){return R6(e).replace($6,"")}s(zp,"normalizeTemplatePlaceholderKey");function Wp(e){return zp(e).toLowerCase()}s(Wp,"canonicalTemplatePlaceholderKey");function hD(e){let n=new Map;for(let t of I6(e))n.has(t.key)||n.set(t.key,t.placeholder);return Array.from(n.entries()).sort(([t],[r])=>t.localeCompare(r,"de")).map(([,t])=>t)}s(hD,"extractTemplatePlaceholders");function I6(e){let n=[];for(let t of e.matchAll(T6)){let r=zp(t[1]??t[2]??"");r&&n.push({key:Wp(r),placeholder:t[0].trim()})}return n}s(I6,"extractTemplatePlaceholderOccurrences");var gD=/^word\/(document|header\d+|footer\d+|footnotes|endnotes)\.xml$/;function O6(e){return e.replace(/<[^>]+>/g,"").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&#(\d+);/g,(n,t)=>String.fromCodePoint(Number(t))).replace(/&#x([0-9a-f]+);/gi,(n,t)=>String.fromCodePoint(parseInt(t,16))).replace(/&amp;/g,"&")}s(O6,"templateXmlText");function yD(e){return e.map(O6).join(`
11257
- `)}s(yD,"templateTextFromParts");var P6="application/vnd.openxmlformats-officedocument.wordprocessingml.document";async function dd(e){let n=Y.resolve(e);if(!n.toLowerCase().endsWith(".docx"))throw new Error("Word templates must be a .docx file.");let t=new Uint8Array(await Ut(n));return{file:n,bytes:t,sha256:_6("sha256").update(t).digest("base64"),placeholders:hD(C6(t)).map(zp)}}s(dd,"readLocalDocx");async function Yp(e,n,t,r){let i=await e.query(x.templates.roleOptions,{client:n}),o=i.find(d=>d.key===r.role);if(o===void 0)throw new Error(`Unknown leaf role "${r.role}". Available: ${i.map(d=>d.key).join(", ")}`);let a=await kD(e,n,t),{templateId:l}=await e.action(x.templateFileActions.create,{client:n,name:r.name,roleId:o.id,storageId:a,filename:Y.basename(t.file),...r.configKey===void 0?{}:{configKey:r.configKey},...r.icon===void 0?{}:{icon:r.icon},...r.fileNamePattern===void 0?{}:{fileNamePattern:r.fileNamePattern}});return l}s(Yp,"uploadDocumentTemplate");async function wD(e,n,t,r){let i=await kD(e,n,r);await e.action(x.templateFileActions.replaceFile,{client:n,templateId:t,storageId:i,filename:Y.basename(r.file)})}s(wD,"replaceDocumentTemplateFile");async function kD(e,n,t){let{uploadUrl:r,uploadTicket:i}=await e.mutation(x.templates.generateUploadUrl,{client:n}),o=await e.upload(r,t.bytes,P6);return await e.mutation(x.uploads.registerUpload,{uploadTicket:i,storageId:o}),o}s(kD,"stageDocx");function C6(e){let n=D6(e,t=>gD.test(t));if(!n.has("word/document.xml"))throw new Error("word/document.xml not found \u2014 the file is not a readable .docx.");return yD([...n.values()])}s(C6,"docxPlaceholderText");function D6(e,n){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new Error("No ZIP central directory \u2014 the file is not a readable .docx."),i=-1;for(let d=e.length-22;d>=Math.max(0,e.length-22-65535);d--)if(t.getUint32(d,!0)===101010256){i=d;break}if(i<0)throw r;let o=t.getUint16(i+10,!0),a=t.getUint32(i+16,!0),l=new Map;for(let d=0;d<o;d++){if(a+46>e.length||t.getUint32(a,!0)!==33639248)throw r;let c=t.getUint16(a+10,!0),u=t.getUint32(a+20,!0),p=t.getUint16(a+28,!0),h=t.getUint16(a+30,!0),y=t.getUint16(a+32,!0),k=t.getUint32(a+42,!0),w=new TextDecoder().decode(e.subarray(a+46,a+46+p));if(a+=46+p+h+y,!n(w))continue;if(t.getUint32(k,!0)!==67324752)throw r;let v=k+30+t.getUint16(k+26,!0)+t.getUint16(k+28,!0),A=Buffer.from(e.subarray(v,v+u));l.set(w,(c===0?A:N6(A)).toString("utf8"))}return l}s(D6,"readZipEntries");function Cn(e,n,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${t}: ${n} muss ein Objekt sein.`);return e}s(Cn,"record");function Ge(e,n,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t}: ${n} fehlt.`);return e.trim()}s(Ge,"text");function pt(e,n,t,r){let i=Rn(e);if(i==="not-localized"){let a=typeof e=="string"&&e.trim()!==""?e.trim():"\u2026";throw new Error(`${t}: ${n}: erwartet { "de": "\u2026", "en": "\u2026" } (${r} sind zweisprachig) \u2014 z. B. "name": ${JSON.stringify({de:a,en:"\u2026"})}`)}if(i.length>0)throw new Error(`${t}: ${n}.${i.join(` und ${n}.`)} ${i.length>1?"fehlen":"fehlt"} (${r} sind zweisprachig; kein R\xFCckfall auf Deutsch).`);let o=e;return{de:o.de.trim(),en:o.en.trim()}}s(pt,"localizedName");function Ft(e,n,t){if(!Array.isArray(e))throw new Error(`${t}: ${n} muss eine Liste sein.`);return e}s(Ft,"list");function Hp(e,n){return Ft(e,"revenueAccounts",n).map((t,r)=>{let i=Cn(t,`revenueAccounts[${r}]`,n);return{code:Ge(i.code,`revenueAccounts[${r}].code`,n),name:Ge(i.name,`revenueAccounts[${r}].name`,n)}})}s(Hp,"parseRevenueAccounts");function Jp(e,n){return Ft(e,"billingItems",n).map((t,r)=>{let i=`billingItems[${r}]`,o=Cn(t,i,n),a=Ge(o.itemType,`${i}.itemType`,n),l=Ge(o.taxTreatment,`${i}.taxTreatment`,n);if(l!=="exempt_ustg_4_nr_21"&&l!=="vat_19"&&l!=="vat_7")throw new Error(`${n}: ${i}.taxTreatment ist unbekannt.`);if(a!=="recurring"&&a!=="one_time"&&a!=="usage")throw new Error(`${n}: ${i}.itemType "${a}" ist unbekannt.`);if(o.minAmount!==void 0)throw new Error(`${n}: ${i}.minAmount wird nicht mehr unterst\xFCtzt; eine Vertragserm\xE4\xDFigung mit Untergrenze verwenden.`);let d=Cn(o.price,`${i}.price`,n),c=d.effectiveFrom===void 0?{}:{effectiveFrom:Ge(d.effectiveFrom,`${i}.price.effectiveFrom`,n)},u=Ge(d.currency,`${i}.price.currency`,n),p=d.tree===void 0?(()=>{let h=Ge(d.period,`${i}.price.period`,n);if(!["month","year","once","unit"].includes(h))throw new Error(`${n}: ${i}.price.period ist unbekannt.`);return{currency:u,amount:d.amount,period:h,...c}})():(()=>{if(d.amount!==void 0||d.period!==void 0)throw new Error(`${n}: ${i}.price: tree wird nicht mit amount oder period kombiniert.`);return{currency:u,tree:Cn(d.tree,`${i}.price.tree`,n),...c}})();return{key:Ge(o.key,`${i}.key`,n),name:pt(o.name,`${i}.name`,n,"Artikelnamen"),itemType:a,revenueAccount:Ge(o.revenueAccount,`${i}.revenueAccount`,n),taxTreatment:l,config:Cn(o.config??{},`${i}.config`,n),...o.programs===void 0?{}:{programs:Ft(o.programs,`${i}.programs`,n).map((h,y)=>Ge(h,`${i}.programs[${y}]`,n))},price:p}})}s(Jp,"parseBillingItems");var Ie="catalog",F6=["sibling","stipend","promo","needsBased","singleParent"],L6=["percent","absolute"];function Ok(e,n){let t=new Set;for(let r of e){if(t.has(r))throw new Error(`${Ie}: ${n}: Schl\xFCssel "${r}" steht zweimal in der Datei.`);t.add(r)}}s(Ok,"uniqueKeys");function Qp(e,n,t){if(!n.includes(e))throw new Error(`${Ie}: ${t} "${e}" ist unbekannt (${n.join(", ")}).`);return e}s(Qp,"oneOf");function M6(e,n){let t=Cn(e,"Datei",Ie);if(t.plans!==void 0)throw new Error("catalog: plans wurden entfernt. Geb\xFChrengruppen geh\xF6ren in die Generatorrevision; Programmzuordnungen unter billingItems[].programs angeben.");let r=["revenueAccounts","billingItems","grantTemplates","documentTemplates"],i=Object.keys(t).filter(c=>!r.includes(c));if(i.length>0)throw new Error(`${Ie}: unbekannte Abschnitte ${i.join(", ")} (erlaubt: ${r.join(", ")}).`);let o=Jp(t.billingItems??[],Ie).map((c,u)=>{let p=`billingItems[${u}].price`;if(!("tree"in c.price)&&(typeof c.price.amount!="number"||!Number.isFinite(c.price.amount)))throw new Error(`${Ie}: ${p}.amount muss eine Zahl sein (${JSON.stringify("amount"in c.price?c.price.amount:null)}).`);if(c.price.effectiveFrom===void 0)throw new Error(`${Ie}: ${p}.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=Ft(t.grantTemplates??[],"grantTemplates",Ie).map((c,u)=>{let p=`grantTemplates[${u}]`,h=Cn(c,p,Ie);if(h.item!==void 0||h.plan!==void 0||h.value!==void 0)throw new Error(`${Ie}: ${p}: eligibleItems, scope und rule statt item/plan/value verwenden.`);if(typeof h.retroactiveRevocation!="boolean")throw new Error(`${Ie}: ${p}.retroactiveRevocation muss true oder false sein.`);let y=Qp(Ge(h.scope,`${p}.scope`,Ie),["line","aggregate"],`${p}.scope`),k=Qp(Ge(h.kind,`${p}.kind`,Ie),L6,`${p}.kind`),w=Cn(h.rule,`${p}.rule`,Ie);fD(k,w);let v=Qp(Ge(h.pricePeriod,`${p}.pricePeriod`,Ie),["month","year","once","unit"],`${p}.pricePeriod`);if(h.floorTotal!==void 0){if(typeof h.floorTotal!="number"||y!=="aggregate")throw new Error(`${Ie}: ${p}.floorTotal geh\xF6rt zu einer Aggregaterm\xE4\xDFigung.`);Gp(h.floorTotal)}let A=Ft(h.eligibleItems,`${p}.eligibleItems`,Ie).map((E,R)=>Ge(E,`${p}.eligibleItems[${R}]`,Ie));if(A.length===0||new Set(A).size!==A.length)throw new Error(`${Ie}: ${p}.eligibleItems braucht eindeutige Artikel.`);return{key:Ge(h.key,`${p}.key`,Ie),name:pt(h.name,`${p}.name`,Ie,"Erm\xE4\xDFigungsnamen"),eligibleItems:A,scope:y,rule:w,pricePeriod:v,...h.floorTotal===void 0?{}:{floorTotal:h.floorTotal},...h.offeredFrom===void 0?{}:{offeredFrom:Ge(h.offeredFrom,`${p}.offeredFrom`,Ie)},...h.offeredUntil===void 0?{}:{offeredUntil:Ge(h.offeredUntil,`${p}.offeredUntil`,Ie)},reason:Qp(Ge(h.reason,`${p}.reason`,Ie),F6,`${p}.reason`),kind:k,eligibility:Cn(h.eligibility,`${p}.eligibility`,Ie),retroactiveRevocation:h.retroactiveRevocation}}),l=Ft(t.documentTemplates??[],"documentTemplates",Ie).map((c,u)=>{let p=`documentTemplates[${u}]`,h=Cn(c,p,Ie),y=Ge(h.key,`${p}.key`,Ie);if(!pD(y))throw new Error(`${Ie}: ${p}.key "${y}" ist kein g\xFCltiger Vorlagen-Schl\xFCssel (Kleinbuchstaben, Ziffern, - und _, beginnend mit einem Buchstaben).`);let k=Y.resolve(n,Ge(h.file,`${p}.file`,Ie));if(!k.toLowerCase().endsWith(".docx"))throw new Error(`${Ie}: ${p}.file muss eine .docx sein.`);return{key:y,name:pt(h.name,`${p}.name`,Ie,"Vorlagennamen"),file:k,role:Ge(h.role,`${p}.role`,Ie),...h.icon===void 0?{}:{icon:Ge(h.icon,`${p}.icon`,Ie)},...h.fileNamePattern===void 0?{}:{fileNamePattern:Ge(h.fileNamePattern,`${p}.fileNamePattern`,Ie)},...h.parameters===void 0?{}:{parameters:h.parameters===null?null:q6(h.parameters,`${p}.parameters`)}}});Ok(o.map(c=>c.key),"billingItems"),Ok(a.map(c=>c.key),"grantTemplates");for(let[c,u]of o.entries()){if(u.programs===void 0)throw new Error(`${Ie}: 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 Error(`${Ie}: billingItems[${c}].programs: ein Programm steht zweimal.`)}Ok(l.map(c=>c.key),"documentTemplates");let d=Hp(t.revenueAccounts??[],Ie);if(d.length+o.length+a.length+l.length===0)throw new Error(`${Ie}: die Datei deklariert nichts (${r.join(", ")}).`);return{revenueAccounts:d,billingItems:o,grantTemplates:a,documentTemplates:l}}s(M6,"parseCatalog");function _k(e){let n=Y.resolve(e);if(!Ae(n))throw new Error(`${Ie}: ${n} gibt es nicht.`);return M6(JSON.parse(he(n,"utf8")),Y.dirname(n))}s(_k,"readCatalog");function q6(e,n){let t=Cn(e,n,Ie);return Ft(t.fields,`${n}.fields`,Ie),t}s(q6,"declaredParameters");function K6(e){return{revenueAccounts:e.revenueAccounts,billingItems:e.billingItems.map(n=>({key:n.key,name:n.name,itemType:n.itemType,revenueAccountCode:n.revenueAccount,taxTreatment:n.taxTreatment,config:n.config,price:n.price,programs:n.programs}))}}s(K6,"billingArgs");function j6(e){return{articlePrograms:e.billingItems.map(n=>({item:n.key,programs:n.programs??[]}))}}s(j6,"planArgs");async function Nk(e,n,t,r=dd){let i=[],o=[],a=null;if(t.billingItems.length>0||t.revenueAccounts.length>0){a=K6(t);let u=await e.query(x.contractSetup.planBillingSetup,{client:n,...a});for(let p of u.rows)i.push({step:p.kind,target:p.key,action:p.action,detail:p.detail}),p.kind==="billingItem"&&p.action==="create"&&o.push(p.key)}let l=null;if(t.billingItems.length>0){l=j6(t);let u=await e.query(x.catalogPrograms.planProgramSetup,{client:n,...l,pendingItems:o});for(let p of u.rows)i.push({step:p.kind,target:p.key,action:p.action,detail:p.detail?.de??""});for(let p of t.billingItems)p.programs?.length===0&&i.push({step:"billingItemProgram",target:p.key,action:"none",detail:"kein Programm verkauft den Artikel (stillgelegt?) \u2014 Finanzen zeigt \u201EKein Programm\u201C"})}let d=null;if(t.grantTemplates.length>0){d={grantTemplates:t.grantTemplates};let u=await e.query(x.contractSetup.planGrantSetup,{client:n,grantTemplates:t.grantTemplates,pendingItems:o});for(let p of u.rows)i.push({step:"grantTemplate",target:p.key,action:p.action,detail:p.detail})}let c=[];if(t.documentTemplates.length>0){let u=await e.query(x.templates.roleOptions,{client:n});for(let p of t.documentTemplates){let h=u.find(R=>R.key===p.role);if(h===void 0)throw new Error(`${Ie}: Vorlage ${p.key}: Rolle "${p.role}" ist keine Blatt-Rolle dieses Mandanten (${u.map(R=>R.key).join(", ")}).`);let y=await r(p.file),k=await e.query(x.templates.stateByConfigKey,{client:n,configKey:p.key});if(k!==null&&k.roleKey!==p.role)throw new Error(`${Ie}: Vorlage ${p.key} geh\xF6rt zur Rolle "${k.roleKey}", die Datei nennt "${p.role}" \u2014 die Rolle einer bestehenden Vorlage \xE4ndert catalog nicht (Vorlagenverwaltung).`);let w=k===null||k.sha256!==y.sha256,v=p.parameters!==void 0&&Ne(p.parameters)!==Ne(k?.parameters??null),A=[];k!==null&&(Is(k.name,p.name)||A.push(`Name ${k.name.de} / ${k.name.en||"\u2014"} \u2192 ${p.name.de} / ${p.name.en}`),p.icon!==void 0&&k.icon!==p.icon&&A.push(`Icon \u2192 ${p.icon}`),p.fileNamePattern!==void 0&&k.fileNamePattern!==p.fileNamePattern&&A.push("Dateinamensmuster")),c.push({declared:p,docx:y,roleId:h.id,state:k,upload:w,metadata:A,parametersChange:v});let E=v?[p.parameters===null?"Parameter entfernen":`Parameter (${p.parameters.fields.length} Felder)`]:[];i.push({step:"documentTemplate",target:p.key,action:k===null?"create":w||A.length>0||v?"update":"same",detail:k===null?[`${p.name.de} \xB7 ${Y.basename(p.file)}`,...E].join(", "):[...w?[`Datei ersetzen (${Y.basename(p.file)})`]:[],...A,...E].join(", ")})}}return{rows:i,billing:a,programs:l,grants:d,templates:c}}s(Nk,"planCatalog");async function bD(e,n,t,r=dd){let i=await Nk(e,n,t,r),o=[];if(i.billing!==null){let a=await e.mutation(x.contractSetup.applyBillingSetup,{client:n,...i.billing});for(let l of a.rows)o.push({step:l.kind,target:l.key,action:l.action,detail:l.detail})}if(i.programs!==null){let a=await e.mutation(x.catalogPrograms.applyProgramSetup,{client:n,...i.programs});for(let l of a.rows)o.push({step:l.kind,target:l.key,action:l.action,detail:l.detail?.de??""})}if(i.grants!==null){let a=await e.mutation(x.contractSetup.applyGrantSetup,{client:n,grantTemplates:i.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 i.templates){let{declared:l,state:d}=a;if(d===null)await Yp(e,n,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 wD(e,n,d.templateId,a.docx),a.metadata.length>0){let c=l.icon??d.icon,u=l.fileNamePattern??d.fileNamePattern;await e.mutation(x.templates.updateMetadata,{client:n,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(x.templates.setParameters,{client:n,configKey:l.key,parameters:l.parameters??null}),o.push(i.rows.find(c=>c.step==="documentTemplate"&&c.target===l.key))}return o}s(bD,"applyCatalog");async function vD(e,n){let{unkeyed:t,...r}=await e.query(x.catalogExport.exportCatalog,{client:n});return{file:{revenueAccounts:r.revenueAccounts,billingItems:r.billingItems,grantTemplates:r.grantTemplates},unkeyed:t}}s(vD,"exportCatalog");var xD={required:!0,description:"catalog.json (revenueAccounts, billingItems with their programs, grantTemplates, documentTemplates)"},SD=["step","target","action","detail"],Pk=class extends D{static{s(this,"CatalogPlanCommand")}file=f.String("--file",xD);static paths=[["catalog","plan"]];static usage=T.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 n=await this.caller(),t=await Nk(n,this.requireTenant(n),_k(this.file));return this.print(t.rows,r=>r,SD),0}},Ck=class extends D{static{s(this,"CatalogApplyCommand")}file=f.String("--file",xD);static paths=[["catalog","apply"]];static usage=T.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 n=await this.caller();return this.print(await bD(n,this.requireTenant(n),_k(this.file)),t=>t,SD),0}},Dk=class extends D{static{s(this,"CatalogExportCommand")}out=f.String("--out",{required:!0,description:"catalog.json to write (refused when it exists, unless --force)"});force=wn();static paths=[["catalog","export"]];static usage=T.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 n=Pn(this.out,this.force),t=await this.caller(),{file:r,unkeyed:i}=await vD(t,this.requireTenant(t));ze(n,`${JSON.stringify(r,null,2)}
11256
+ `,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=f.String("--dir",{required:!0,description:"Offer bundle directory (its workflow.json carries the rule)"});envJson=f.String("--env-json",{description:"The application's environment ($env) as JSON"});envFile=f.String("--env-file",{description:"\u2026or a file holding it"});creator=f.String("--creator",{description:"Label for the staff creator (only a staff start has one)"});rotationPrevious=f.Array("--rotation-previous",{description:"<slot>=<personKey>: the last pick of that slot's \u201EReihum\u201C row (repeatable; none = its first start)"});left=f.Array("--left",{description:"<personKey>: someone who has left \u2014 every rotation skips them (repeatable)"});open=f.Array("--open",{description:"<personKey>=<n>: open tasks, for a leastLoaded rotation (repeatable; absent = 0)"});async execute(){let n=qe(this.dir),t=DN(n.workflow?.graph,`bundle ${this.dir}`),r=f4(this.envJson,this.envFile),i=GC(t,r,{...this.creator!==void 0?{creator:this.creator}:{},rotationPrevious:zC("--rotation-previous",this.rotationPrevious),openCounts:u4(this.open),left:this.left??[]});return this.print(i,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}},WC=[mk];import{createHash as p4}from"node:crypto";var hk=/^[a-z0-9][a-z0-9-]*$/;function xa(e){return hk.test(e)}s(xa,"isFileKey");function Wo(e){return e.trim()===""?"is empty":e==="."||e===".."?"is not a file name":/[/\\]/.test(e)?"must not contain a path separator":/[\u0000-\u001f]/.test(e)?"must not contain control characters":null}s(Wo,"fileNameDefect");var JC={".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"},Bp={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".avif":"image/avif",".woff2":"font/woff2"};function Sa(e){return p4("sha256").update(e).digest("hex")}s(Sa,"sha256Hex");function gk(e,n=JC){let t=Y.resolve(e),r;try{r=he(t)}catch{throw new Error(`File not found: ${e}`)}let i=n[Y.extname(t).toLowerCase()];if(i===void 0)throw new Error(`${e}: unsupported file type \u2014 allowed: ${Object.keys(n).join(", ")}.`);return{bytes:r,filename:Y.basename(t),mimeType:i,sha256:Sa(r),sizeBytes:r.length}}s(gk,"readLocalFile");var m4={tenantFile:x.tenantFiles.platformGenerateUploadUrl,brandingAsset:x.branding.platformGenerateBrandingAssetUploadUrl,brandingLogo:x.branding.platformGenerateBrandingLogoUploadUrl};async function Yo(e,n,t,r,i){let{uploadUrl:o,uploadTicket:a}=await e.mutation(m4[i],{client:n}),l=await e.upload(o,t,r);return await e.mutation(x.uploads.registerUpload,{uploadTicket:a,storageId:l}),l}s(Yo,"uploadStaged");async function QC(e,n,t,r){return await Yo(e,n,t,r,"tenantFile")}s(QC,"uploadTenantFile");function yk(e){let n=[...e].filter(([,t])=>"fileName"in t||"size"in t).map(([t])=>t);if(n.length!==0)throw new Error(`[cli/serverPredatesFileRef] ${n.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(yk,"requireFileRefNames");async function ld(e,n){let t=await e.query(x.tenantFiles.platformList,{client:n});return yk(t.map(r=>[`files["${r.key}"]`,r])),t}s(ld,"listLibrary");function ZC(e,n,t,r,i){let o=gk(Y.resolve(e,n),i);if(o.mimeType!==t)throw new Error(`${r}: ${n} is ${o.mimeType}, the entry declares ${t}.`);return o}s(ZC,"readSnapshotEntry");function XC(e,n){let t=new Map,r=(e.files??[]).map(l=>{if(l.path===void 0)return l;let{path:d,...c}=l,u=ZC(n,d,c.mimeType,`files["${c.key}"]`,JC);return t.set(c.key,u),{...c,sha256:u.sha256,sizeBytes:u.sizeBytes}}),i=YC(e.tenant.brandingAssets,n,"tenant"),o=new Map,a=(e.foundation?.legalEntities??[]).map(l=>{if(l.brandingAssets===void 0)return l;let d=YC(l.brandingAssets,n,`foundation.legalEntities.${l.key}`);return o.set(l.key,d.bytes),{...l,brandingAssets:d.assets}});return{config:{...e,tenant:{...e.tenant,...i.assets!==void 0?{brandingAssets:i.assets}:{}},...e.foundation!==void 0?{foundation:{...e.foundation,legalEntities:a}}:{},files:r},bytes:t,brandingBytes:i.bytes,legalEntityBrandingBytes:o}}s(XC,"resolveSnapshotFiles");function YC(e,n,t){let r=new Map,i=e;if(i===void 0)return{assets:void 0,bytes:r};let o={};for(let[a,l]of Object.entries(i)){if(l.path===void 0){o[a]=l;continue}let{path:d,...c}=l,u=ZC(n,d,c.mimeType,`${t}.brandingAssets.${a}`,Bp);r.set(a,u),o[a]={...c,sha256:u.sha256,sizeBytes:u.sizeBytes}}return{assets:o,bytes:r}}s(YC,"resolveSnapshotBranding");async function eD(e,n,t,r,i){let o={},a={contents:o,changed:[],unavailable:[]};for(let l of e){if(n.get(l.key)===l.sha256)continue;a.changed.push(l.key);let d=await t(l.key);if(d===void 0){a.unavailable.push(l.key);continue}if(Sa(d)!==l.sha256)throw new Error(`${l.at}: the supplied bytes do not match sha256 ${l.sha256}.`);i||(o[l.key]=await r(d,l.mimeType))}return a}s(eD,"stageChanged");async function nD(e,n,t,r,i){let o=new Map(Object.entries(await e.query(x.tenantFiles.platformFileHashes,{client:n})??{})),a=new Map(t.map(l=>[l.key,l]));return await eD(t.map(l=>({key:l.key,sha256:l.sha256,mimeType:l.mimeType,at:`files["${l.key}"]`})),o,l=>r(a.get(l)),(l,d)=>Yo(e,n,l,d,"tenantFile"),i)}s(nD,"stageFileContents");function tD(e){return e===void 0?"tenant":`foundation.legalEntities.${e}`}s(tD,"brandingHolder");async function Up(e,n,t){let r=await e.query(x.branding.platformBrandingAssets,{client:n,...t!==void 0?{legalEntity:t}:{}});return yk(Object.entries(r??{}).map(([i,o])=>[`${tD(t)}.brandingAssets.${i}`,o])),r}s(Up,"listBrandingAssets");async function wk(e,n,t,r,i,o){let a=new Map(Object.entries(await Up(e,n,o)??{}).map(([d,c])=>[d,c.sha256])),l=tD(o);return await eD(Object.entries(t??{}).map(([d,c])=>({key:d,sha256:c.sha256,mimeType:c.mimeType,at:`${l}.brandingAssets.${d}`})),a,r,(d,c)=>Yo(e,n,d,c,"brandingAsset"),i)}s(wk,"stageBrandingAssets");async function rD(e,n,t,r){if(e===null||n===void 0)throw new Error(`${t}: its stored object is gone \u2014 ${r}`);let i=await fetch(e);if(!i.ok)throw new Error(`download of ${t} failed (${i.status}).`);let o=new Uint8Array(await i.arrayBuffer());if(Sa(o)!==n)throw new Error(`download of ${t} does not match its sha256 ${n}.`);return o}s(rD,"downloadVerified");async function kk(e){return await rD(e.url,e.sha256,`"${e.key}"`,"replace it with `files put` first.")}s(kk,"downloadLibraryFile");async function bk(e,n,t){return await rD(n.url,n.sha256,t===void 0?`branding/${e}`:`branding/${t}/${e}`,"upload it again with `branding set-logo` / `branding set-font` first.")}s(bk,"downloadBrandingAsset");function h4(e,n,t){let r=Object.keys(Bp).find(i=>Bp[i]===n);if(r===void 0)throw new Error(`export: branding/${e} is ${n}, which a snapshot cannot name (${Object.keys(Bp).join(", ")}).`);if(t===void 0)return Y.join("branding",`${e}${r}`);if(!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(t))throw new Error(`export: legal entity key "${t}" is not a safe directory name for its brand files.`);return Y.join("branding",t,`${e}${r}`)}s(h4,"brandingAssetPath");function iD(e,n,t){let r=Y.join(e,n);Fn(Y.dirname(r),{recursive:!0}),ze(r,t)}s(iD,"writeBeside");async function oD(e,n,t,r){yk([...t.files.map(c=>[`files["${c.key}"]`,c]),...Object.entries(t.tenant.brandingAssets??{}).map(([c,u])=>[`tenant.brandingAssets.${c}`,u]),...(t.foundation?.legalEntities??[]).flatMap(c=>Object.entries(c.brandingAssets??{}).map(([u,p])=>[`foundation.legalEntities.${c.key}.brandingAssets.${u}`,p]))]);let i=new Map((await ld(e,n)).map(c=>[c.key,c])),o=Y.dirname(r),a=[];for(let c of t.files){let u=i.get(c.key);if(u===void 0)throw new Error(`export: "${c.key}" vanished from the library between two reads \u2014 rerun.`);let p=Wo(c.filename);if(p!==null||!xa(c.key))throw new Error(`export: "${c.key}" / "${c.filename}" is not a safe path (${p??"bad key"}).`);let h=Y.join("files",c.key,c.filename);iD(o,h,await kk(u)),a.push({...c,path:h})}let l=await HC(e,n,t.tenant.brandingAssets,o,void 0),d=[];for(let c of t.foundation?.legalEntities??[]){if(c.brandingAssets===void 0){d.push(c);continue}d.push({...c,brandingAssets:await HC(e,n,c.brandingAssets,o,c.key)})}return{...t,tenant:{...t.tenant,...l!==void 0?{brandingAssets:l}:{}},...t.foundation!==void 0?{foundation:{...t.foundation,legalEntities:d}}:{},files:a}}s(oD,"writeSnapshotFiles");async function HC(e,n,t,r,i){if(t===void 0)return;let o=await Up(e,n,i)??{},a={};for(let[l,d]of Object.entries(t)){let c=o[l],u=h4(l,d.mimeType,i);if(c===void 0||c.sha256!==d.sha256)throw new Error(`export: ${u} changed between two reads \u2014 rerun.`);iD(r,u,await bk(l,c,i)),a[l]={...d,path:u}}return a}s(HC,"writeSnapshotBranding");var g4={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml",".avif":"image/avif"};function sD(e){return g4[Y.extname(e).toLowerCase()]}s(sD,"guessImageContentType");async function y4(e,n){if(e===void 0==(n===void 0))throw new Error("Pass exactly one of --file <path> or --url <url>.");if(n!==void 0&&ln())throw new Error("Hosted agents cannot fetch arbitrary logo URLs. Upload the image to the chat and use --file <path>.");if(e!==void 0){let a=Y.resolve(e),l;try{l=he(a)}catch{throw new Error(`File not found: ${e}`)}let d=sD(a);if(d===void 0)throw new Error(`Cannot infer an image content-type from "${Y.basename(a)}" \u2014 use a .png/.jpg/.webp/.gif file.`);return{bytes:new Uint8Array(l),contentType:d}}let t=await fetch(n);if(!t.ok)throw new Error(`Fetch failed for ${n} (${t.status} ${t.statusText}).`);let r=new Uint8Array(await t.arrayBuffer()),i=t.headers.get("content-type")?.split(";")[0]?.trim(),o=i&&i.startsWith("image/")?i:sD(new URL(n).pathname);if(o===void 0)throw new Error(`Response for ${n} is not an image (content-type "${i??"unknown"}").`);return{bytes:r,contentType:o}}s(y4,"loadLogoBytes");function Aa(){return f.String("--legal-entity",{description:"A legal entity's config key \u2014 its own brand, which overrides the tenant's for its units"})}s(Aa,"legalEntityOption");function Ea(e){return e===void 0?{}:{legalEntity:e}}s(Ea,"ownerArgs");async function w4(e,n,t,r){return await Yo(e,n,t,r,"brandingLogo")}s(w4,"uploadLogo");var vk=class extends D{static{s(this,"BrandingSetLogoCommand")}static paths=[["branding","set-logo"]];static usage=T.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=f.String("--file",{description:"Local image file to upload"});url=f.String("--url",{description:"Fetch the logo image from this URL"});legalEntity=Aa();async execute(){let n=await this.caller(),t=this.requireTenant(n),{bytes:r,contentType:i}=await y4(this.file,this.url),o=await w4(n,t,r,i);return await n.mutation(x.branding.platformSetBrandingLogo,{client:t,...Ea(this.legalEntity),slot:"primary",storageId:o}),this.print({tenant:t,slot:"primary",contentType:i,bytes:r.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}},xk=class extends D{static{s(this,"BrandingClearLogoCommand")}static paths=[["branding","clear-logo"]];static usage=T.Usage({category:"Branding",description:"Remove a tenant's portal logo"});legalEntity=Aa();async execute(){let n=await this.caller(),t=this.requireTenant(n);return await n.mutation(x.branding.platformClearBrandingLogo,{client:t,...Ea(this.legalEntity),slot:"primary"}),this.print({tenant:t,slot:"primary",cleared:!0},r=>[{field:"tenant",value:r.tenant},{field:"slot",value:r.slot},{field:"cleared",value:String(r.cleared)}]),0}};function aD(e){if(e!=="heading"&&e!=="body")throw new Error(`branding: --slot must be heading or body (got "${e}")`);return e}s(aD,"parseFontSlot");var Sk=class extends D{static{s(this,"BrandingSetFontCommand")}static paths=[["branding","set-font"]];static usage=T.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=f.String("--slot",{required:!0,description:"heading | body"});file=f.String("--file",{required:!0,description:"Local .woff2 file"});legalEntity=Aa();async execute(){let n=aD(this.slot),t=Y.resolve(this.file),r;try{r=he(t)}catch{throw new Error(`File not found: ${this.file}`)}let i=await this.caller(),o=this.requireTenant(i),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),{storageId:l}=await i.action(x.brandingFonts.platformSetBrandingFont,{client:o,...Ea(this.legalEntity),slot:n,bytes:a});return this.print({tenant:o,slot:n,bytes:r.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}},Ak=class extends D{static{s(this,"BrandingClearFontCommand")}static paths=[["branding","clear-font"]];static usage=T.Usage({category:"Branding",description:"Remove a tenant's portal font file for a slot (the family stays)"});slot=f.String("--slot",{required:!0,description:"heading | body"});legalEntity=Aa();async execute(){let n=aD(this.slot),t=await this.caller(),r=this.requireTenant(t);return await t.mutation(x.branding.platformClearBrandingFont,{client:r,...Ea(this.legalEntity),slot:n}),this.print({tenant:r,slot:n,cleared:!0},i=>[{field:"tenant",value:i.tenant},{field:"slot",value:i.slot},{field:"cleared",value:String(i.cleared)}]),0}},Ek=class extends D{static{s(this,"BrandingSetThemeCommand")}static paths=[["branding","set-theme"]];static usage=T.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=f.String("--file",{required:!0,description:"Branding theme JSON"});legalEntity=Aa();async execute(){let n=await this.caller(),t=this.requireTenant(n),r=Y.resolve(this.file),i;try{i=JSON.parse(he(r,"utf8"))}catch(o){throw new Error(`Cannot read branding JSON ${this.file}: ${kt(o)}`,{cause:o})}return await n.mutation(x.branding.platformUpdateBranding,{client:t,...Ea(this.legalEntity),branding:i}),this.print({tenant:t,applied:!0},o=>[{field:"tenant",value:o.tenant},{field:"applied",value:String(o.applied)}]),0}},Tk=class extends D{static{s(this,"BrandingShowCommand")}static paths=[["branding","show"]];static usage=T.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=Aa();async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.query(x.branding.platformGetBranding,{client:t,...Ea(this.legalEntity)});return this.print(r),0}},lD=[Tk,Ek,vk,xk,Sk,Ak];var Ta=s(()=>f.String("--output",{hidden:!0}),"retiredOutputOption"),wn=s(()=>f.Boolean("--force",!1,{description:"Overwrite an existing --out file."}),"forceOption");function $a(e){if(e.retiredOutput===void 0)return e.out;if(e.out!==void 0&&e.out!==e.retiredOutput)throw new Oe(`--out "${e.out}" and --output "${e.retiredOutput}" disagree \u2014 pass only --out.`);return sn(e.context.stderr,"--output","--out"),e.retiredOutput}s($a,"resolveOut");function Pn(e,n){let t=Y.resolve(e);if(Ae(t)&&!n)throw new Oe(`${t} exists \u2014 pick another --out or pass --force.`);return t}s(Pn,"assertOutFree");function k4(e){try{return Or(e)}catch{throw new Oe(`${e} is not a directory \u2014 --out names a directory here.`)}}s(k4,"entriesOf");function $k(e,n){let t=Y.resolve(e);if(Ae(t)&&k4(t).length>0&&!n)throw new Oe(`${t} is not empty \u2014 pick another --out or pass --force.`);return t}s($k,"assertOutDirFree");function dD(e,n,t){let r=Pn(e,t),i=n.map(o=>Y.join(Y.dirname(r),o)).filter(o=>Ae(o));if(i.length>0&&!t)throw new Oe(`${i.join(", ")} exist(s) beside --out \u2014 pick another directory or pass --force.`);return r}s(dD,"assertSnapshotOutFree");function Gp(e){(!Number.isSafeInteger(e)||e<0)&&se("INVALID",{de:"Betr\xE4ge m\xFCssen nichtnegative ganze Centbetr\xE4ge sein.",en:"Amounts must be non-negative whole amounts in cents."})}s(Gp,"assertMoney");var Rk=["month","year","once","unit"];var b4=s(e=>e!==void 0&&/^[1-9]\d{0,8}$/.test(e),"positiveIntegerText");function yi(e,n){return se("CONFLICT",{de:e,en:n})}s(yi,"missing");var cD=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 uD(e,n,t){return{label:n,kind:"chosen",valueType:"choice",choices:t,resolve(r){let i=r.selections?.[e];return(!i||!t.includes(i))&&yi(`Die Auswahl f\xFCr \u201E${n.de}\u201C fehlt oder ist ung\xFCltig.`,`The selection for \u201C${n.en}\u201D is missing or invalid.`),{value:i,explanation:{de:`${n.de}: ${i} (Vertragsauswahl)`,en:`${n.en}: ${i} (contract selection)`}}}}}s(uD,"chosen");function Ik(e,n){let t=e.enrollment,r=t?.contextDate??n;return(!t||!t.startDate||t.startDate>r||t.endDate&&t.endDate<r)&&yi("F\xFCr dieses Datum fehlt eine eindeutige Einschreibung.","An unambiguous enrollment is missing for this date."),t}s(Ik,"enrollment");var v4={paymentFrequency:uD("paymentFrequency",{de:"Zahlungsweise",en:"Payment frequency"},["monthly","yearly"]),gradeLevel:{label:{de:"Klassenstufe",en:"Grade level"},kind:"derived",valueType:"integer",resolve(e,n){let t=Ik(e,n).gradeLevel;return(!Number.isSafeInteger(t)||t<1)&&yi("Die Klassenstufe fehlt.","The grade level is missing."),{value:t,explanation:{de:`Klassenstufe ${t} am ${n}`,en:`Grade ${t} on ${n}`}}}},schoolYear:{label:{de:"Schuljahr",en:"School year"},kind:"derived",valueType:"integer",resolve(e,n){let t=Ik(e,n).schoolYear;return(!Number.isSafeInteger(t)||t<1)&&yi("F\xFCr dieses Datum fehlt ein j\xE4hrlicher Schuljahreslauf.","An annual school-year run is missing for this date."),{value:t,explanation:{de:`Schuljahr ${t}/${t+1}`,en:`School year ${t}/${t+1}`}}}},siblingRank:{label:{de:"Geschwisterrang",en:"Sibling rank"},kind:"derived",valueType:"integer",resolve(e,n){if(e.chosenCriteria?.includes("siblingRank")){let c=e.selections?.siblingRank;return b4(c)||yi("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&&se("CONFLICT",e.unavailable.siblingRank);let t=e.siblings?[...new Map(e.siblings.filter(c=>c.eligible).map(c=>[c.partyId,c])).values()]:void 0;(!e.partyId||!t?.some(c=>c.partyId===e.partyId))&&yi("F\xFCr dieses Datum fehlt die Sch\xFClerrolle des Kindes.","The child\u2019s Student role is missing for this date."),t.some(c=>!cD(c.firstEnrolledOn)||c.firstEnrolledOn>n)&&yi("F\xFCr den Geschwisterrang fehlt ein g\xFCltiger erster Einschreibungsbeginn.","A valid first enrollment start is missing for sibling ranking.");let r=t.find(c=>c.partyId===e.partyId),i=r.firstEnrolledOn,o=t.filter(c=>c.firstEnrolledOn===i);o.length>1&&o.some(c=>!cD(c.birthDate)||c.birthDate>n)&&yi("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<r.birthDate||c.birthDate===r.birthDate&&c.partyId<r.partyId,"before"),l=t.filter(c=>c.firstEnrolledOn<i).length+o.filter(c=>c!==r&&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 ${t.length} berechtigten Kindern am ${n}; erste Einschreibung am ${i}, zuerst eingeschriebene Kinder zuerst${d.de}.`,en:`Child ${l} of ${t.length} eligible children on ${n}; first enrollment on ${i}, first enrolled first${d.en}.`}}}},program:{label:{de:"Programm",en:"Program"},kind:"derived",valueType:"program",resolve(e,n){let t=Ik(e,n).programId;return t||yi("Das Programm fehlt.","The program is missing."),{value:t,explanation:{de:`Programm der Einschreibung am ${n}`,en:`Enrollment program on ${n}`}}}},admissionFeeTier:uD("admissionFeeTier",{de:"Anmeldegeb\xFChrensatz",en:"Admission fee tier"},["100","75","50"])},x4=Object.fromEntries(Object.entries(v4).map(([e,n])=>[e,{...n,matchSchema:{parse(t){return A4(n,t),t}},matches:S4}])),zbe=Object.keys(x4);function S4(e,n){return"else"in n?!0:"eq"in n?e===n.eq:"in"in n?n.in.includes(e):typeof e=="number"&&(n.gte===void 0||e>=n.gte)&&(n.lte===void 0||e<=n.lte)}s(S4,"matchesPrice");function A4(e,n){let t=s(()=>se("INVALID",{de:"Der Match passt nicht zum Preiskriterium.",en:"The match does not fit the price criterion."}),"fail");if(!n||typeof n!="object"||Array.isArray(n))return t();let r=n,i=Object.keys(r).sort().join();if(i==="else"&&r.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(!(i==="eq"&&o(r.eq))&&!(i==="in"&&Array.isArray(r.in)&&r.in.length>0&&new Set(r.in).size===r.in.length&&r.in.every(o))&&!(e.valueType==="integer"&&["gte","lte","gte,lte"].includes(i)&&Object.values(r).every(a=>Number.isSafeInteger(a)&&Number(a)>=1)&&(r.gte===void 0||r.lte===void 0||Number(r.gte)<=Number(r.lte))))return t()}s(A4,"validateMatch");function fD(e,n){if(Object.keys(n).some(t=>!["percent","amountMinor"].includes(t))&&se("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 n&&!("amountMinor"in n)){(!Number.isFinite(n.percent)||n.percent<0||n.percent>100)&&se("INVALID",{de:"Prozentwerte m\xFCssen zwischen 0 und 100 liegen.",en:"Percentages must be between 0 and 100."});return}if(e==="absolute"&&"amountMinor"in n&&!("percent"in n))return Gp(n.amountMinor);se("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(fD,"validateRule");var E4=/^[a-z][a-z0-9_-]{0,63}$/;function pD(e){return E4.test(e)}s(pD,"isTemplateConfigKey");import{createHash as _4}from"node:crypto";import{inflateRawSync as N4}from"node:zlib";var mD=/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/,T4=/{{\s*([^{}]+?)\s*}}|<<\s*([^<>]+?)\s*>>/g,$4=/^[#/]\s*/;function R4(e){let n=e.trim(),t=n.match(/^{{\s*([^{}]+?)\s*}}$/);if(t)return t[1]?.trim()??n;let r=n.match(/^<<\s*([^<>]+?)\s*>>$/);return r?r[1]?.trim()??n:n}s(R4,"innerTemplatePlaceholder");function zp(e){return R4(e).replace($4,"")}s(zp,"normalizeTemplatePlaceholderKey");function Wp(e){return zp(e).toLowerCase()}s(Wp,"canonicalTemplatePlaceholderKey");function hD(e){let n=new Map;for(let t of I4(e))n.has(t.key)||n.set(t.key,t.placeholder);return Array.from(n.entries()).sort(([t],[r])=>t.localeCompare(r,"de")).map(([,t])=>t)}s(hD,"extractTemplatePlaceholders");function I4(e){let n=[];for(let t of e.matchAll(T4)){let r=zp(t[1]??t[2]??"");r&&n.push({key:Wp(r),placeholder:t[0].trim()})}return n}s(I4,"extractTemplatePlaceholderOccurrences");var gD=/^word\/(document|header\d+|footer\d+|footnotes|endnotes)\.xml$/;function O4(e){return e.replace(/<[^>]+>/g,"").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&#(\d+);/g,(n,t)=>String.fromCodePoint(Number(t))).replace(/&#x([0-9a-f]+);/gi,(n,t)=>String.fromCodePoint(parseInt(t,16))).replace(/&amp;/g,"&")}s(O4,"templateXmlText");function yD(e){return e.map(O4).join(`
11257
+ `)}s(yD,"templateTextFromParts");var P4="application/vnd.openxmlformats-officedocument.wordprocessingml.document";async function dd(e){let n=Y.resolve(e);if(!n.toLowerCase().endsWith(".docx"))throw new Error("Word templates must be a .docx file.");let t=new Uint8Array(await Ut(n));return{file:n,bytes:t,sha256:_4("sha256").update(t).digest("base64"),placeholders:hD(C4(t)).map(zp)}}s(dd,"readLocalDocx");async function Yp(e,n,t,r){let i=await e.query(x.templates.roleOptions,{client:n}),o=i.find(d=>d.key===r.role);if(o===void 0)throw new Error(`Unknown leaf role "${r.role}". Available: ${i.map(d=>d.key).join(", ")}`);let a=await kD(e,n,t),{templateId:l}=await e.action(x.templateFileActions.create,{client:n,name:r.name,roleId:o.id,storageId:a,filename:Y.basename(t.file),...r.configKey===void 0?{}:{configKey:r.configKey},...r.icon===void 0?{}:{icon:r.icon},...r.fileNamePattern===void 0?{}:{fileNamePattern:r.fileNamePattern}});return l}s(Yp,"uploadDocumentTemplate");async function wD(e,n,t,r){let i=await kD(e,n,r);await e.action(x.templateFileActions.replaceFile,{client:n,templateId:t,storageId:i,filename:Y.basename(r.file)})}s(wD,"replaceDocumentTemplateFile");async function kD(e,n,t){let{uploadUrl:r,uploadTicket:i}=await e.mutation(x.templates.generateUploadUrl,{client:n}),o=await e.upload(r,t.bytes,P4);return await e.mutation(x.uploads.registerUpload,{uploadTicket:i,storageId:o}),o}s(kD,"stageDocx");function C4(e){let n=D4(e,t=>gD.test(t));if(!n.has("word/document.xml"))throw new Error("word/document.xml not found \u2014 the file is not a readable .docx.");return yD([...n.values()])}s(C4,"docxPlaceholderText");function D4(e,n){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new Error("No ZIP central directory \u2014 the file is not a readable .docx."),i=-1;for(let d=e.length-22;d>=Math.max(0,e.length-22-65535);d--)if(t.getUint32(d,!0)===101010256){i=d;break}if(i<0)throw r;let o=t.getUint16(i+10,!0),a=t.getUint32(i+16,!0),l=new Map;for(let d=0;d<o;d++){if(a+46>e.length||t.getUint32(a,!0)!==33639248)throw r;let c=t.getUint16(a+10,!0),u=t.getUint32(a+20,!0),p=t.getUint16(a+28,!0),h=t.getUint16(a+30,!0),y=t.getUint16(a+32,!0),k=t.getUint32(a+42,!0),w=new TextDecoder().decode(e.subarray(a+46,a+46+p));if(a+=46+p+h+y,!n(w))continue;if(t.getUint32(k,!0)!==67324752)throw r;let v=k+30+t.getUint16(k+26,!0)+t.getUint16(k+28,!0),A=Buffer.from(e.subarray(v,v+u));l.set(w,(c===0?A:N4(A)).toString("utf8"))}return l}s(D4,"readZipEntries");function Cn(e,n,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${t}: ${n} muss ein Objekt sein.`);return e}s(Cn,"record");function Ge(e,n,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t}: ${n} fehlt.`);return e.trim()}s(Ge,"text");function pt(e,n,t,r){let i=Rn(e);if(i==="not-localized"){let a=typeof e=="string"&&e.trim()!==""?e.trim():"\u2026";throw new Error(`${t}: ${n}: erwartet { "de": "\u2026", "en": "\u2026" } (${r} sind zweisprachig) \u2014 z. B. "name": ${JSON.stringify({de:a,en:"\u2026"})}`)}if(i.length>0)throw new Error(`${t}: ${n}.${i.join(` und ${n}.`)} ${i.length>1?"fehlen":"fehlt"} (${r} sind zweisprachig; kein R\xFCckfall auf Deutsch).`);let o=e;return{de:o.de.trim(),en:o.en.trim()}}s(pt,"localizedName");function Ft(e,n,t){if(!Array.isArray(e))throw new Error(`${t}: ${n} muss eine Liste sein.`);return e}s(Ft,"list");function Hp(e,n){return Ft(e,"revenueAccounts",n).map((t,r)=>{let i=Cn(t,`revenueAccounts[${r}]`,n);return{code:Ge(i.code,`revenueAccounts[${r}].code`,n),name:Ge(i.name,`revenueAccounts[${r}].name`,n)}})}s(Hp,"parseRevenueAccounts");function Jp(e,n){return Ft(e,"billingItems",n).map((t,r)=>{let i=`billingItems[${r}]`,o=Cn(t,i,n),a=Ge(o.itemType,`${i}.itemType`,n),l=Ge(o.taxTreatment,`${i}.taxTreatment`,n);if(l!=="exempt_ustg_4_nr_21"&&l!=="vat_19"&&l!=="vat_7")throw new Error(`${n}: ${i}.taxTreatment ist unbekannt.`);if(a!=="recurring"&&a!=="one_time"&&a!=="usage")throw new Error(`${n}: ${i}.itemType "${a}" ist unbekannt.`);if(o.minAmount!==void 0)throw new Error(`${n}: ${i}.minAmount wird nicht mehr unterst\xFCtzt; eine Vertragserm\xE4\xDFigung mit Untergrenze verwenden.`);let d=Cn(o.price,`${i}.price`,n),c=d.effectiveFrom===void 0?{}:{effectiveFrom:Ge(d.effectiveFrom,`${i}.price.effectiveFrom`,n)},u=Ge(d.currency,`${i}.price.currency`,n),p=d.tree===void 0?(()=>{let h=Ge(d.period,`${i}.price.period`,n);if(!["month","year","once","unit"].includes(h))throw new Error(`${n}: ${i}.price.period ist unbekannt.`);return{currency:u,amount:d.amount,period:h,...c}})():(()=>{if(d.amount!==void 0||d.period!==void 0)throw new Error(`${n}: ${i}.price: tree wird nicht mit amount oder period kombiniert.`);return{currency:u,tree:Cn(d.tree,`${i}.price.tree`,n),...c}})();return{key:Ge(o.key,`${i}.key`,n),name:pt(o.name,`${i}.name`,n,"Artikelnamen"),itemType:a,revenueAccount:Ge(o.revenueAccount,`${i}.revenueAccount`,n),taxTreatment:l,config:Cn(o.config??{},`${i}.config`,n),...o.programs===void 0?{}:{programs:Ft(o.programs,`${i}.programs`,n).map((h,y)=>Ge(h,`${i}.programs[${y}]`,n))},price:p}})}s(Jp,"parseBillingItems");var Ie="catalog",F4=["sibling","stipend","promo","needsBased","singleParent"],L4=["percent","absolute"];function Ok(e,n){let t=new Set;for(let r of e){if(t.has(r))throw new Error(`${Ie}: ${n}: Schl\xFCssel "${r}" steht zweimal in der Datei.`);t.add(r)}}s(Ok,"uniqueKeys");function Qp(e,n,t){if(!n.includes(e))throw new Error(`${Ie}: ${t} "${e}" ist unbekannt (${n.join(", ")}).`);return e}s(Qp,"oneOf");function M4(e,n){let t=Cn(e,"Datei",Ie);if(t.plans!==void 0)throw new Error("catalog: plans wurden entfernt. Geb\xFChrengruppen geh\xF6ren in die Generatorrevision; Programmzuordnungen unter billingItems[].programs angeben.");let r=["revenueAccounts","billingItems","grantTemplates","documentTemplates"],i=Object.keys(t).filter(c=>!r.includes(c));if(i.length>0)throw new Error(`${Ie}: unbekannte Abschnitte ${i.join(", ")} (erlaubt: ${r.join(", ")}).`);let o=Jp(t.billingItems??[],Ie).map((c,u)=>{let p=`billingItems[${u}].price`;if(!("tree"in c.price)&&(typeof c.price.amount!="number"||!Number.isFinite(c.price.amount)))throw new Error(`${Ie}: ${p}.amount muss eine Zahl sein (${JSON.stringify("amount"in c.price?c.price.amount:null)}).`);if(c.price.effectiveFrom===void 0)throw new Error(`${Ie}: ${p}.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=Ft(t.grantTemplates??[],"grantTemplates",Ie).map((c,u)=>{let p=`grantTemplates[${u}]`,h=Cn(c,p,Ie);if(h.item!==void 0||h.plan!==void 0||h.value!==void 0)throw new Error(`${Ie}: ${p}: eligibleItems, scope und rule statt item/plan/value verwenden.`);if(typeof h.retroactiveRevocation!="boolean")throw new Error(`${Ie}: ${p}.retroactiveRevocation muss true oder false sein.`);let y=Qp(Ge(h.scope,`${p}.scope`,Ie),["line","aggregate"],`${p}.scope`),k=Qp(Ge(h.kind,`${p}.kind`,Ie),L4,`${p}.kind`),w=Cn(h.rule,`${p}.rule`,Ie);fD(k,w);let v=Qp(Ge(h.pricePeriod,`${p}.pricePeriod`,Ie),["month","year","once","unit"],`${p}.pricePeriod`);if(h.floorTotal!==void 0){if(typeof h.floorTotal!="number"||y!=="aggregate")throw new Error(`${Ie}: ${p}.floorTotal geh\xF6rt zu einer Aggregaterm\xE4\xDFigung.`);Gp(h.floorTotal)}let A=Ft(h.eligibleItems,`${p}.eligibleItems`,Ie).map((E,R)=>Ge(E,`${p}.eligibleItems[${R}]`,Ie));if(A.length===0||new Set(A).size!==A.length)throw new Error(`${Ie}: ${p}.eligibleItems braucht eindeutige Artikel.`);return{key:Ge(h.key,`${p}.key`,Ie),name:pt(h.name,`${p}.name`,Ie,"Erm\xE4\xDFigungsnamen"),eligibleItems:A,scope:y,rule:w,pricePeriod:v,...h.floorTotal===void 0?{}:{floorTotal:h.floorTotal},...h.offeredFrom===void 0?{}:{offeredFrom:Ge(h.offeredFrom,`${p}.offeredFrom`,Ie)},...h.offeredUntil===void 0?{}:{offeredUntil:Ge(h.offeredUntil,`${p}.offeredUntil`,Ie)},reason:Qp(Ge(h.reason,`${p}.reason`,Ie),F4,`${p}.reason`),kind:k,eligibility:Cn(h.eligibility,`${p}.eligibility`,Ie),retroactiveRevocation:h.retroactiveRevocation}}),l=Ft(t.documentTemplates??[],"documentTemplates",Ie).map((c,u)=>{let p=`documentTemplates[${u}]`,h=Cn(c,p,Ie),y=Ge(h.key,`${p}.key`,Ie);if(!pD(y))throw new Error(`${Ie}: ${p}.key "${y}" ist kein g\xFCltiger Vorlagen-Schl\xFCssel (Kleinbuchstaben, Ziffern, - und _, beginnend mit einem Buchstaben).`);let k=Y.resolve(n,Ge(h.file,`${p}.file`,Ie));if(!k.toLowerCase().endsWith(".docx"))throw new Error(`${Ie}: ${p}.file muss eine .docx sein.`);return{key:y,name:pt(h.name,`${p}.name`,Ie,"Vorlagennamen"),file:k,role:Ge(h.role,`${p}.role`,Ie),...h.icon===void 0?{}:{icon:Ge(h.icon,`${p}.icon`,Ie)},...h.fileNamePattern===void 0?{}:{fileNamePattern:Ge(h.fileNamePattern,`${p}.fileNamePattern`,Ie)},...h.parameters===void 0?{}:{parameters:h.parameters===null?null:q4(h.parameters,`${p}.parameters`)}}});Ok(o.map(c=>c.key),"billingItems"),Ok(a.map(c=>c.key),"grantTemplates");for(let[c,u]of o.entries()){if(u.programs===void 0)throw new Error(`${Ie}: 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 Error(`${Ie}: billingItems[${c}].programs: ein Programm steht zweimal.`)}Ok(l.map(c=>c.key),"documentTemplates");let d=Hp(t.revenueAccounts??[],Ie);if(d.length+o.length+a.length+l.length===0)throw new Error(`${Ie}: die Datei deklariert nichts (${r.join(", ")}).`);return{revenueAccounts:d,billingItems:o,grantTemplates:a,documentTemplates:l}}s(M4,"parseCatalog");function _k(e){let n=Y.resolve(e);if(!Ae(n))throw new Error(`${Ie}: ${n} gibt es nicht.`);return M4(JSON.parse(he(n,"utf8")),Y.dirname(n))}s(_k,"readCatalog");function q4(e,n){let t=Cn(e,n,Ie);return Ft(t.fields,`${n}.fields`,Ie),t}s(q4,"declaredParameters");function K4(e){return{revenueAccounts:e.revenueAccounts,billingItems:e.billingItems.map(n=>({key:n.key,name:n.name,itemType:n.itemType,revenueAccountCode:n.revenueAccount,taxTreatment:n.taxTreatment,config:n.config,price:n.price,programs:n.programs}))}}s(K4,"billingArgs");function j4(e){return{articlePrograms:e.billingItems.map(n=>({item:n.key,programs:n.programs??[]}))}}s(j4,"planArgs");async function Nk(e,n,t,r=dd){let i=[],o=[],a=null;if(t.billingItems.length>0||t.revenueAccounts.length>0){a=K4(t);let u=await e.query(x.contractSetup.planBillingSetup,{client:n,...a});for(let p of u.rows)i.push({step:p.kind,target:p.key,action:p.action,detail:p.detail}),p.kind==="billingItem"&&p.action==="create"&&o.push(p.key)}let l=null;if(t.billingItems.length>0){l=j4(t);let u=await e.query(x.catalogPrograms.planProgramSetup,{client:n,...l,pendingItems:o});for(let p of u.rows)i.push({step:p.kind,target:p.key,action:p.action,detail:p.detail?.de??""});for(let p of t.billingItems)p.programs?.length===0&&i.push({step:"billingItemProgram",target:p.key,action:"none",detail:"kein Programm verkauft den Artikel (stillgelegt?) \u2014 Finanzen zeigt \u201EKein Programm\u201C"})}let d=null;if(t.grantTemplates.length>0){d={grantTemplates:t.grantTemplates};let u=await e.query(x.contractSetup.planGrantSetup,{client:n,grantTemplates:t.grantTemplates,pendingItems:o});for(let p of u.rows)i.push({step:"grantTemplate",target:p.key,action:p.action,detail:p.detail})}let c=[];if(t.documentTemplates.length>0){let u=await e.query(x.templates.roleOptions,{client:n});for(let p of t.documentTemplates){let h=u.find(R=>R.key===p.role);if(h===void 0)throw new Error(`${Ie}: Vorlage ${p.key}: Rolle "${p.role}" ist keine Blatt-Rolle dieses Mandanten (${u.map(R=>R.key).join(", ")}).`);let y=await r(p.file),k=await e.query(x.templates.stateByConfigKey,{client:n,configKey:p.key});if(k!==null&&k.roleKey!==p.role)throw new Error(`${Ie}: Vorlage ${p.key} geh\xF6rt zur Rolle "${k.roleKey}", die Datei nennt "${p.role}" \u2014 die Rolle einer bestehenden Vorlage \xE4ndert catalog nicht (Vorlagenverwaltung).`);let w=k===null||k.sha256!==y.sha256,v=p.parameters!==void 0&&Ne(p.parameters)!==Ne(k?.parameters??null),A=[];k!==null&&(Is(k.name,p.name)||A.push(`Name ${k.name.de} / ${k.name.en||"\u2014"} \u2192 ${p.name.de} / ${p.name.en}`),p.icon!==void 0&&k.icon!==p.icon&&A.push(`Icon \u2192 ${p.icon}`),p.fileNamePattern!==void 0&&k.fileNamePattern!==p.fileNamePattern&&A.push("Dateinamensmuster")),c.push({declared:p,docx:y,roleId:h.id,state:k,upload:w,metadata:A,parametersChange:v});let E=v?[p.parameters===null?"Parameter entfernen":`Parameter (${p.parameters.fields.length} Felder)`]:[];i.push({step:"documentTemplate",target:p.key,action:k===null?"create":w||A.length>0||v?"update":"same",detail:k===null?[`${p.name.de} \xB7 ${Y.basename(p.file)}`,...E].join(", "):[...w?[`Datei ersetzen (${Y.basename(p.file)})`]:[],...A,...E].join(", ")})}}return{rows:i,billing:a,programs:l,grants:d,templates:c}}s(Nk,"planCatalog");async function bD(e,n,t,r=dd){let i=await Nk(e,n,t,r),o=[];if(i.billing!==null){let a=await e.mutation(x.contractSetup.applyBillingSetup,{client:n,...i.billing});for(let l of a.rows)o.push({step:l.kind,target:l.key,action:l.action,detail:l.detail})}if(i.programs!==null){let a=await e.mutation(x.catalogPrograms.applyProgramSetup,{client:n,...i.programs});for(let l of a.rows)o.push({step:l.kind,target:l.key,action:l.action,detail:l.detail?.de??""})}if(i.grants!==null){let a=await e.mutation(x.contractSetup.applyGrantSetup,{client:n,grantTemplates:i.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 i.templates){let{declared:l,state:d}=a;if(d===null)await Yp(e,n,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 wD(e,n,d.templateId,a.docx),a.metadata.length>0){let c=l.icon??d.icon,u=l.fileNamePattern??d.fileNamePattern;await e.mutation(x.templates.updateMetadata,{client:n,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(x.templates.setParameters,{client:n,configKey:l.key,parameters:l.parameters??null}),o.push(i.rows.find(c=>c.step==="documentTemplate"&&c.target===l.key))}return o}s(bD,"applyCatalog");async function vD(e,n){let{unkeyed:t,...r}=await e.query(x.catalogExport.exportCatalog,{client:n});return{file:{revenueAccounts:r.revenueAccounts,billingItems:r.billingItems,grantTemplates:r.grantTemplates},unkeyed:t}}s(vD,"exportCatalog");var xD={required:!0,description:"catalog.json (revenueAccounts, billingItems with their programs, grantTemplates, documentTemplates)"},SD=["step","target","action","detail"],Pk=class extends D{static{s(this,"CatalogPlanCommand")}file=f.String("--file",xD);static paths=[["catalog","plan"]];static usage=T.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 n=await this.caller(),t=await Nk(n,this.requireTenant(n),_k(this.file));return this.print(t.rows,r=>r,SD),0}},Ck=class extends D{static{s(this,"CatalogApplyCommand")}file=f.String("--file",xD);static paths=[["catalog","apply"]];static usage=T.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 n=await this.caller();return this.print(await bD(n,this.requireTenant(n),_k(this.file)),t=>t,SD),0}},Dk=class extends D{static{s(this,"CatalogExportCommand")}out=f.String("--out",{required:!0,description:"catalog.json to write (refused when it exists, unless --force)"});force=wn();static paths=[["catalog","export"]];static usage=T.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 n=Pn(this.out,this.force),t=await this.caller(),{file:r,unkeyed:i}=await vD(t,this.requireTenant(t));ze(n,`${JSON.stringify(r,null,2)}
11258
11258
  `);let o=Object.entries(i).filter(([,a])=>a>0).map(([a,l])=>`${l} ${a}`);return this.context.stdout.write(`${this.out}: ${r.billingItems.length} Artikel, ${r.grantTemplates.length} Rabattvorlagen`+(o.length===0?`
11259
11259
  `:` \u2014 ohne Schl\xFCssel nicht exportiert: ${o.join(", ")}
11260
- `)),0}},AD=[Pk,Ck,Dk];var V6=65279;function Zp(e,n,t){(n.length!==1||n==='"'||n===`
11261
- `||n==="\r")&&se("INVALID",{de:`${t}: ung\xFCltiges CSV-Trennzeichen ${JSON.stringify(n)}.`,en:`${t}: invalid CSV delimiter ${JSON.stringify(n)}.`});let r=e.charCodeAt(0)===V6?e.slice(1):e,i=B6(r,n,t),o=i.shift();(o===void 0||o.cells.every(u=>u.trim()===""))&&se("INVALID",{de:`${t}: Die Datei hat keine Kopfzeile.`,en:`${t}: the file has no header row.`});let a=o.cells.map(u=>u.trim()),l=a.findIndex(u=>u==="");l!==-1&&se("INVALID",{de:`${t}: Spalte ${l+1} der Kopfzeile hat keinen Namen.`,en:`${t}: header column ${l+1} has no name.`});let d=new Set;for(let u of a)d.has(u)&&se("INVALID",{de:`${t}: Die Kopfzeile nennt die Spalte \u201E${u}\u201C zweimal.`,en:`${t}: the header names column "${u}" twice.`}),d.add(u);let c=[];for(let u of i)u.cells.length===1&&u.cells[0]===""||(u.cells.length!==a.length&&se("INVALID",{de:`${t}: Zeile ${u.line} hat ${u.cells.length} Zellen, die Kopfzeile ${a.length} \u2014 die Datei ist keine Tabelle.`,en:`${t}: line ${u.line} has ${u.cells.length} cells, the header ${a.length} \u2014 the file is not one table.`}),c.push({line:u.line,cells:Object.fromEntries(a.map((p,h)=>[p,u.cells[h]]))}));return{columns:a,rows:c}}s(Zp,"parseCsv");function B6(e,n,t){let r=[],i=[],o="",a=!1,l=1,d=1;for(let c=0;c<e.length;c++){let u=e[c];if(a){u==='"'?e[c+1]==='"'?(o+='"',c++):a=!1:(u===`
11260
+ `)),0}},AD=[Pk,Ck,Dk];var V4=65279;function Zp(e,n,t){(n.length!==1||n==='"'||n===`
11261
+ `||n==="\r")&&se("INVALID",{de:`${t}: ung\xFCltiges CSV-Trennzeichen ${JSON.stringify(n)}.`,en:`${t}: invalid CSV delimiter ${JSON.stringify(n)}.`});let r=e.charCodeAt(0)===V4?e.slice(1):e,i=B4(r,n,t),o=i.shift();(o===void 0||o.cells.every(u=>u.trim()===""))&&se("INVALID",{de:`${t}: Die Datei hat keine Kopfzeile.`,en:`${t}: the file has no header row.`});let a=o.cells.map(u=>u.trim()),l=a.findIndex(u=>u==="");l!==-1&&se("INVALID",{de:`${t}: Spalte ${l+1} der Kopfzeile hat keinen Namen.`,en:`${t}: header column ${l+1} has no name.`});let d=new Set;for(let u of a)d.has(u)&&se("INVALID",{de:`${t}: Die Kopfzeile nennt die Spalte \u201E${u}\u201C zweimal.`,en:`${t}: the header names column "${u}" twice.`}),d.add(u);let c=[];for(let u of i)u.cells.length===1&&u.cells[0]===""||(u.cells.length!==a.length&&se("INVALID",{de:`${t}: Zeile ${u.line} hat ${u.cells.length} Zellen, die Kopfzeile ${a.length} \u2014 die Datei ist keine Tabelle.`,en:`${t}: line ${u.line} has ${u.cells.length} cells, the header ${a.length} \u2014 the file is not one table.`}),c.push({line:u.line,cells:Object.fromEntries(a.map((p,h)=>[p,u.cells[h]]))}));return{columns:a,rows:c}}s(Zp,"parseCsv");function B4(e,n,t){let r=[],i=[],o="",a=!1,l=1,d=1;for(let c=0;c<e.length;c++){let u=e[c];if(a){u==='"'?e[c+1]==='"'?(o+='"',c++):a=!1:(u===`
11262
11262
  `&&l++,o+=u);continue}u==='"'&&o===""?a=!0:u===n?(i.push(o),o=""):u===`
11263
11263
  `||u==="\r"?(u==="\r"&&e[c+1]===`
11264
- `&&c++,i.push(o),r.push({line:d,cells:i}),i=[],o="",l++,d=l):o+=u}return a&&se("INVALID",{de:`${t}: Die in Zeile ${d} ge\xF6ffnete Anf\xFChrung schlie\xDFt nie.`,en:`${t}: the quoted cell opened on line ${d} never closes.`}),(o!==""||i.length>0)&&(i.push(o),r.push({line:d,cells:i})),r}s(B6,"csvRecords");function Xp(e){return e.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}s(Xp,"slugify");var ED="tenant";function TD(e){if(e.length===0||Xp(e)!==e)return"must be lowercase a-z/0-9 words joined by single dashes";if(e===ED)return`"${ED}" is reserved for the tenant-wide scope`}s(TD,"unitSlugError");var $D=["school","vocational","care","seminar","other"],RD=["none","manual","annual_rollover"],ID=/^\d{4}-\d{2}-\d{2}$/;function cd(e){return Xp(e.trim())}s(cd,"importSlug");function Fk(e,n,t){return`${e}:${cd(n)}:${cd(t)}`}s(Fk,"learningGroupImportKey");function ND(e){let n=[];if(!vr(e))return["The mapping is not a JSON object."];e.version!==1&&n.push(`version must be 1 (got ${JSON.stringify(e.version)}).`),[";",","," "].includes(e.delimiter)||n.push('delimiter must be ";", "," or "\\t".');let t=e.schoolYear;vr(t)?((typeof t.key!="string"||cd(t.key)==="")&&n.push("schoolYear.key must name the year (e.g. 2026-27)."),G6(t.name)||n.push("schoolYear.name must be { de, en }."),(typeof t.startDate!="string"||!ID.test(t.startDate))&&n.push("schoolYear.startDate must be YYYY-MM-DD."),(typeof t.endDate!="string"||!ID.test(t.endDate))&&n.push("schoolYear.endDate must be YYYY-MM-DD."),typeof t.startDate=="string"&&typeof t.endDate=="string"&&t.endDate<t.startDate&&n.push("schoolYear.endDate lies before startDate.")):n.push("schoolYear is missing.");let r=e.columns;!vr(r)||typeof r.code!="string"||typeof r.unit!="string"?n.push("columns.code and columns.unit must name columns."):r.capacity!==void 0&&typeof r.capacity!="string"&&n.push("columns.capacity must name a column.");let i=e.program;return vr(i)?((!Array.isArray(i.nameColumns)||i.nameColumns.length===0||!i.nameColumns.every(o=>typeof o=="string"))&&n.push("program.nameColumns must list at least one column."),n.push(..._D("program.kind",i.kind,o=>$D.includes(o),$D.join(", "))),RD.includes(i.progressionMode)||n.push(`program.progressionMode must be one of ${RD.join(", ")}.`),i.existing!==void 0&&(!vr(i.existing)||!Object.entries(i.existing).every(([o,a])=>o.includes("/")&&typeof a=="string"&&a!==""))&&n.push("program.existing must map `<unit key>/<program name>` to a program key.")):n.push("program is missing."),n.push(..._D("gradeLevel",e.gradeLevel,o=>o===null||Number.isInteger(o)&&o>=0,"a whole number or null")),(!Array.isArray(e.ignoredColumns)||!e.ignoredColumns.every(o=>vr(o)&&typeof o.column=="string"&&typeof o.reason=="string"&&o.reason.trim()!==""))&&n.push("ignoredColumns must list { column, reason } entries, each with a reason."),n}s(ND,"learningGroupMappingProblems");function U6(e){let n=[e.columns.code,e.columns.unit,...e.program.nameColumns];e.columns.capacity!==void 0&&n.push(e.columns.capacity);for(let t of[e.program.kind,e.gradeLevel])CD(t)&&n.push(t.column);return[...new Set(n)]}s(U6,"learningGroupMappingColumns");function PD(e,n){let t=[],r=U6(n),i=n.ignoredColumns.map(w=>w.column),o=new Set(e.columns),a=new Set([...r,...i]),l=e.columns.filter(w=>!a.has(w));l.length>0&&t.push(`Columns neither read by the mapping nor in ignoredColumns: ${l.join(", ")}.`);let d=i.filter(w=>r.includes(w));d.length>0&&t.push(`Columns both read by the mapping and in ignoredColumns: ${d.join(", ")}.`);let c=[...r,...i].filter(w=>!o.has(w));if(c.length>0&&t.push(`The mapping names columns the file does not have: ${[...new Set(c)].join(", ")}.`),t.length>0)return{rows:[],problems:t};let u=[],p=new Map,h=new Map,y=new Set;for(let{line:w,cells:v}of e.rows){let A=`line ${w}`,E=v[n.columns.code].trim(),R=v[n.columns.unit].trim();if(E===""||cd(E)===""){t.push(`${A}: the class code is empty or has no letter or digit.`);continue}if(R===""){t.push(`${A} (${E}): the unit is empty.`);continue}let P=n.program.nameColumns.map(Q=>v[Q].trim()).filter(Q=>Q!=="").join(" ");if(P===""){t.push(`${A} (${E}): the program columns ${n.program.nameColumns.join(", ")} are empty.`);continue}let F=OD(n.program.kind,v,A,t),b=OD(n.gradeLevel,v,A,t),O=null;if(n.columns.capacity!==void 0){let Q=v[n.columns.capacity].trim();if(Q!==""){if(!/^\d+$/.test(Q)){t.push(`${A} (${E}): capacity "${Q}" is no whole number.`);continue}O=Number(Q)}}if(F===void 0||b===void 0)continue;let $=Fk(R,n.schoolYear.key,E),I=p.get($);if(I!==void 0){t.push(I===E?`${A}: the class "${E}" of unit "${R}" is listed twice.`:`${A}: the codes "${I}" and "${E}" share one key (${$}) \u2014 rename one of them in the file.`);continue}p.set($,E);let G=n.program.existing?.[`${R}/${P}`];G!==void 0&&y.add(`${R}/${P}`);let B=G??`${R}-${cd(P)}`,le=h.get(B);if(le===void 0)h.set(B,{unitKey:R,name:P,kind:F});else if(le.unitKey!==R||le.name!==P||le.kind!==F){t.push(`${A} (${E}): the program key ${B} stands for "${le.name}" (${le.unitKey}, ${le.kind}) and for "${P}" (${R}, ${F}) \u2014 one key, one program.`);continue}u.push({line:w,unitKey:R,program:{key:B,name:P,kind:F,progressionMode:n.program.progressionMode,existing:G!==void 0},group:{key:$,code:E,gradeLevel:b,capacity:O}})}let k=Object.keys(n.program.existing??{}).filter(w=>!y.has(w));return k.length>0&&t.push(`program.existing entries no row names (a typo would create a second program): ${k.join(", ")}.`),t.length===0&&u.length===0&&t.push("The file holds no class row."),{rows:u,problems:t}}s(PD,"learningGroupRows");function OD(e,n,t,r){if(!CD(e))return e;let i=n[e.column].trim();if(!Object.hasOwn(e.values,i)){r.push(`${t}: column "${e.column}" holds "${i}", which the mapping's values do not list.`);return}return e.values[i]}s(OD,"mappedValue");function _D(e,n,t,r){if(vr(n)&&"column"in n){if(typeof n.column!="string"||!vr(n.values))return[`${e} must be a constant or { column, values }.`];let i=Object.entries(n.values).filter(([,o])=>!t(o)).map(([o])=>o);return i.length===0?[]:[`${e}.values for ${i.map(o=>`"${o}"`).join(", ")} must be ${r}.`]}return t(n)?[]:[`${e} must be ${r}, or { column, values }.`]}s(_D,"mappedValueProblems");function CD(e){return vr(e)&&typeof e.column=="string"&&vr(e.values)}s(CD,"isColumnValue");function vr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(vr,"isRecord");function G6(e){return vr(e)&&typeof e.de=="string"&&e.de.trim()!==""&&typeof e.en=="string"&&e.en.trim()!==""}s(G6,"isText");function ud(e,n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(he(n))}catch(t){throw new Error(`${e}: ${n} is not UTF-8 text \u2014 save it as "CSV UTF-8".`,{cause:t})}}s(ud,"readUtf8File");function em(e,n,t){let r;try{r=JSON.parse(ud(e,n))}catch(o){throw new Error(`${e}: ${n} is no JSON file (${o instanceof Error?o.message:String(o)}).`,{cause:o})}let i=t(r);if(i.length>0)throw new Error(`${e}: the mapping ${n} is invalid:
11264
+ `&&c++,i.push(o),r.push({line:d,cells:i}),i=[],o="",l++,d=l):o+=u}return a&&se("INVALID",{de:`${t}: Die in Zeile ${d} ge\xF6ffnete Anf\xFChrung schlie\xDFt nie.`,en:`${t}: the quoted cell opened on line ${d} never closes.`}),(o!==""||i.length>0)&&(i.push(o),r.push({line:d,cells:i})),r}s(B4,"csvRecords");function Xp(e){return e.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}s(Xp,"slugify");var ED="tenant";function TD(e){if(e.length===0||Xp(e)!==e)return"must be lowercase a-z/0-9 words joined by single dashes";if(e===ED)return`"${ED}" is reserved for the tenant-wide scope`}s(TD,"unitSlugError");var $D=["school","vocational","care","seminar","other"],RD=["none","manual","annual_rollover"],ID=/^\d{4}-\d{2}-\d{2}$/;function cd(e){return Xp(e.trim())}s(cd,"importSlug");function Fk(e,n,t){return`${e}:${cd(n)}:${cd(t)}`}s(Fk,"learningGroupImportKey");function ND(e){let n=[];if(!vr(e))return["The mapping is not a JSON object."];e.version!==1&&n.push(`version must be 1 (got ${JSON.stringify(e.version)}).`),[";",","," "].includes(e.delimiter)||n.push('delimiter must be ";", "," or "\\t".');let t=e.schoolYear;vr(t)?((typeof t.key!="string"||cd(t.key)==="")&&n.push("schoolYear.key must name the year (e.g. 2026-27)."),G4(t.name)||n.push("schoolYear.name must be { de, en }."),(typeof t.startDate!="string"||!ID.test(t.startDate))&&n.push("schoolYear.startDate must be YYYY-MM-DD."),(typeof t.endDate!="string"||!ID.test(t.endDate))&&n.push("schoolYear.endDate must be YYYY-MM-DD."),typeof t.startDate=="string"&&typeof t.endDate=="string"&&t.endDate<t.startDate&&n.push("schoolYear.endDate lies before startDate.")):n.push("schoolYear is missing.");let r=e.columns;!vr(r)||typeof r.code!="string"||typeof r.unit!="string"?n.push("columns.code and columns.unit must name columns."):r.capacity!==void 0&&typeof r.capacity!="string"&&n.push("columns.capacity must name a column.");let i=e.program;return vr(i)?((!Array.isArray(i.nameColumns)||i.nameColumns.length===0||!i.nameColumns.every(o=>typeof o=="string"))&&n.push("program.nameColumns must list at least one column."),n.push(..._D("program.kind",i.kind,o=>$D.includes(o),$D.join(", "))),RD.includes(i.progressionMode)||n.push(`program.progressionMode must be one of ${RD.join(", ")}.`),i.existing!==void 0&&(!vr(i.existing)||!Object.entries(i.existing).every(([o,a])=>o.includes("/")&&typeof a=="string"&&a!==""))&&n.push("program.existing must map `<unit key>/<program name>` to a program key.")):n.push("program is missing."),n.push(..._D("gradeLevel",e.gradeLevel,o=>o===null||Number.isInteger(o)&&o>=0,"a whole number or null")),(!Array.isArray(e.ignoredColumns)||!e.ignoredColumns.every(o=>vr(o)&&typeof o.column=="string"&&typeof o.reason=="string"&&o.reason.trim()!==""))&&n.push("ignoredColumns must list { column, reason } entries, each with a reason."),n}s(ND,"learningGroupMappingProblems");function U4(e){let n=[e.columns.code,e.columns.unit,...e.program.nameColumns];e.columns.capacity!==void 0&&n.push(e.columns.capacity);for(let t of[e.program.kind,e.gradeLevel])CD(t)&&n.push(t.column);return[...new Set(n)]}s(U4,"learningGroupMappingColumns");function PD(e,n){let t=[],r=U4(n),i=n.ignoredColumns.map(w=>w.column),o=new Set(e.columns),a=new Set([...r,...i]),l=e.columns.filter(w=>!a.has(w));l.length>0&&t.push(`Columns neither read by the mapping nor in ignoredColumns: ${l.join(", ")}.`);let d=i.filter(w=>r.includes(w));d.length>0&&t.push(`Columns both read by the mapping and in ignoredColumns: ${d.join(", ")}.`);let c=[...r,...i].filter(w=>!o.has(w));if(c.length>0&&t.push(`The mapping names columns the file does not have: ${[...new Set(c)].join(", ")}.`),t.length>0)return{rows:[],problems:t};let u=[],p=new Map,h=new Map,y=new Set;for(let{line:w,cells:v}of e.rows){let A=`line ${w}`,E=v[n.columns.code].trim(),R=v[n.columns.unit].trim();if(E===""||cd(E)===""){t.push(`${A}: the class code is empty or has no letter or digit.`);continue}if(R===""){t.push(`${A} (${E}): the unit is empty.`);continue}let P=n.program.nameColumns.map(Q=>v[Q].trim()).filter(Q=>Q!=="").join(" ");if(P===""){t.push(`${A} (${E}): the program columns ${n.program.nameColumns.join(", ")} are empty.`);continue}let F=OD(n.program.kind,v,A,t),b=OD(n.gradeLevel,v,A,t),O=null;if(n.columns.capacity!==void 0){let Q=v[n.columns.capacity].trim();if(Q!==""){if(!/^\d+$/.test(Q)){t.push(`${A} (${E}): capacity "${Q}" is no whole number.`);continue}O=Number(Q)}}if(F===void 0||b===void 0)continue;let $=Fk(R,n.schoolYear.key,E),I=p.get($);if(I!==void 0){t.push(I===E?`${A}: the class "${E}" of unit "${R}" is listed twice.`:`${A}: the codes "${I}" and "${E}" share one key (${$}) \u2014 rename one of them in the file.`);continue}p.set($,E);let G=n.program.existing?.[`${R}/${P}`];G!==void 0&&y.add(`${R}/${P}`);let B=G??`${R}-${cd(P)}`,le=h.get(B);if(le===void 0)h.set(B,{unitKey:R,name:P,kind:F});else if(le.unitKey!==R||le.name!==P||le.kind!==F){t.push(`${A} (${E}): the program key ${B} stands for "${le.name}" (${le.unitKey}, ${le.kind}) and for "${P}" (${R}, ${F}) \u2014 one key, one program.`);continue}u.push({line:w,unitKey:R,program:{key:B,name:P,kind:F,progressionMode:n.program.progressionMode,existing:G!==void 0},group:{key:$,code:E,gradeLevel:b,capacity:O}})}let k=Object.keys(n.program.existing??{}).filter(w=>!y.has(w));return k.length>0&&t.push(`program.existing entries no row names (a typo would create a second program): ${k.join(", ")}.`),t.length===0&&u.length===0&&t.push("The file holds no class row."),{rows:u,problems:t}}s(PD,"learningGroupRows");function OD(e,n,t,r){if(!CD(e))return e;let i=n[e.column].trim();if(!Object.hasOwn(e.values,i)){r.push(`${t}: column "${e.column}" holds "${i}", which the mapping's values do not list.`);return}return e.values[i]}s(OD,"mappedValue");function _D(e,n,t,r){if(vr(n)&&"column"in n){if(typeof n.column!="string"||!vr(n.values))return[`${e} must be a constant or { column, values }.`];let i=Object.entries(n.values).filter(([,o])=>!t(o)).map(([o])=>o);return i.length===0?[]:[`${e}.values for ${i.map(o=>`"${o}"`).join(", ")} must be ${r}.`]}return t(n)?[]:[`${e} must be ${r}, or { column, values }.`]}s(_D,"mappedValueProblems");function CD(e){return vr(e)&&typeof e.column=="string"&&vr(e.values)}s(CD,"isColumnValue");function vr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(vr,"isRecord");function G4(e){return vr(e)&&typeof e.de=="string"&&e.de.trim()!==""&&typeof e.en=="string"&&e.en.trim()!==""}s(G4,"isText");function ud(e,n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(he(n))}catch(t){throw new Error(`${e}: ${n} is not UTF-8 text \u2014 save it as "CSV UTF-8".`,{cause:t})}}s(ud,"readUtf8File");function em(e,n,t){let r;try{r=JSON.parse(ud(e,n))}catch(o){throw new Error(`${e}: ${n} is no JSON file (${o instanceof Error?o.message:String(o)}).`,{cause:o})}let i=t(r);if(i.length>0)throw new Error(`${e}: the mapping ${n} is invalid:
11265
11265
  - ${i.join(`
11266
- - `)}`);return r}s(em,"readMappingFile");async function fd(e,n,t,r,i){let o=[];for(let a=0;a<n.length;a+=t)try{o.push(...await i(n.slice(a,a+t)))}catch(l){let d=a===0?"":r?` The first ${a} of ${n.length} rows were written; a re-run finds them again.`:` (after ${a} of ${n.length} rows planned; nothing was written)`;throw new Error(`${e}: ${l instanceof Error?l.message:String(l)}${d}`,{cause:l})}return o}s(fd,"sendInBatches");var z6=100,Lk="learning-groups apply",Mk=class extends D{static{s(this,"LearningGroupsApplyCommand")}file=f.String("--file",{required:!0,description:"The class list (CSV, header row, the mapping's delimiter)."});mapping=f.String("--mapping",{required:!0,description:"The mapping file (JSON): which column is code, unit, program, grade level, capacity; every other column ignored with a reason."});confirm=f.Boolean("--confirm",!1,{description:"Write (else the plan only)."});static paths=[["learning-groups","apply"]];static usage=T.Usage({category:"Master data",description:"Bring a school's classes in from a file: program, school year and learning group per row, by stable key \u2014 plan unless --confirm.",details:"Every column of the file is read by the mapping or listed in its ignoredColumns, every mapped value is listed \u2014 else the plan names each problem and nothing is sent. An existing program is reused and never renamed; a class is found again by its key (unit, school year, class code), so a re-run creates nothing.",examples:[["Plan","$0 --env staging --tenant <slug> learning-groups apply --file ./klassen.csv --mapping ./klassen.mapping.json"],["Write","$0 --env staging --tenant <slug> learning-groups apply --file ./klassen.csv --mapping ./klassen.mapping.json --confirm"]]});async execute(){let n=em(Lk,this.mapping,ND),t=Zp(ud(Lk,this.file),n.delimiter,this.file),{rows:r,problems:i}=PD(t,n);if(i.length>0)throw new Error(`learning-groups apply: ${i.length} problems, nothing was sent:
11266
+ - `)}`);return r}s(em,"readMappingFile");async function fd(e,n,t,r,i){let o=[];for(let a=0;a<n.length;a+=t)try{o.push(...await i(n.slice(a,a+t)))}catch(l){let d=a===0?"":r?` The first ${a} of ${n.length} rows were written; a re-run finds them again.`:` (after ${a} of ${n.length} rows planned; nothing was written)`;throw new Error(`${e}: ${l instanceof Error?l.message:String(l)}${d}`,{cause:l})}return o}s(fd,"sendInBatches");var z4=100,Lk="learning-groups apply",Mk=class extends D{static{s(this,"LearningGroupsApplyCommand")}file=f.String("--file",{required:!0,description:"The class list (CSV, header row, the mapping's delimiter)."});mapping=f.String("--mapping",{required:!0,description:"The mapping file (JSON): which column is code, unit, program, grade level, capacity; every other column ignored with a reason."});confirm=f.Boolean("--confirm",!1,{description:"Write (else the plan only)."});static paths=[["learning-groups","apply"]];static usage=T.Usage({category:"Master data",description:"Bring a school's classes in from a file: program, school year and learning group per row, by stable key \u2014 plan unless --confirm.",details:"Every column of the file is read by the mapping or listed in its ignoredColumns, every mapped value is listed \u2014 else the plan names each problem and nothing is sent. An existing program is reused and never renamed; a class is found again by its key (unit, school year, class code), so a re-run creates nothing.",examples:[["Plan","$0 --env staging --tenant <slug> learning-groups apply --file ./klassen.csv --mapping ./klassen.mapping.json"],["Write","$0 --env staging --tenant <slug> learning-groups apply --file ./klassen.csv --mapping ./klassen.mapping.json --confirm"]]});async execute(){let n=em(Lk,this.mapping,ND),t=Zp(ud(Lk,this.file),n.delimiter,this.file),{rows:r,problems:i}=PD(t,n);if(i.length>0)throw new Error(`learning-groups apply: ${i.length} problems, nothing was sent:
11267
11267
  - ${i.join(`
11268
- - `)}`);let o=await this.caller(),a=this.requireTenant(o),l=await fd(Lk,r,z6,this.confirm,async d=>(await o.mutation(x.learningGroupImport.apply,{client:a,dryRun:!this.confirm,schoolYear:n.schoolYear,rows:d})).rows);return this.print(W6(l,this.confirm),d=>[...d.classes.map(c=>({...c})),{class:"\u2014",program:`${d.programsCreated} new / ${d.programsTotal}`,schoolYear:`${d.runsCreated} new / ${d.runsTotal}`,action:d.totals,changes:d.mode}],["class","program","schoolYear","action","changes"]),0}};function W6(e,n){let t=s(a=>{let l=new Map;for(let[d,c]of a)l.get(d)!=="create"&&l.set(d,c);return l},"created"),r=t(e.map(a=>[a.program.key,a.program.action])),i=t(e.map(a=>[a.run.key,a.run.action])),o=s(a=>e.filter(l=>l.group.action===a).length,"count");return{mode:n?"COMMITTED":"PLAN (re-run with --confirm to write)",programsTotal:r.size,programsCreated:[...r.values()].filter(a=>a==="create").length,runsTotal:i.size,runsCreated:[...i.values()].filter(a=>a==="create").length,totals:`${o("create")} create \xB7 ${o("update")} update \xB7 ${o("unchanged")} unchanged`,classes:e.map(a=>({class:a.code,program:`${a.program.key}${a.program.action==="create"?" (new)":""}`,schoolYear:`${a.run.key}${a.run.action==="create"?" (new)":""}`,action:a.group.action,changes:a.group.changes.join("; ")}))}}s(W6,"summary");var DD=[Mk];var Y6=["permanentLink","periodLink"],uxe=720*60*1e3;function FD(e){if(typeof e!="object"||e===null)return!1;let n=e;return n.mode==="oneTimeLink"&&Object.keys(n).join(",")==="mode"}s(FD,"isExternalSignIn");function LD(e){if(typeof e!="object"||e===null)return!1;let n=e.mode;return Y6.includes(n)}s(LD,"namesRetiredExternalSignIn");function MD(e,n,t){let r=new Map,i=new Set,o=e;for(;o!==void 0;){i.has(o)&&L(`Role inheritance cycle at ${o}.`),n.has(o)||L(`Missing role ${o} in inheritance path.`),i.add(o);for(let a of t.get(o)??[]){let l=r.get(a.customFieldId);l&&se("ROLE_FIELD_INHERITED",{de:`Das Feld ${a.customFieldId} ist auf dem Vererbungspfad der Rolle mehrfach zugeordnet (${l.roleId}, ${o}). Geerbte Felder lassen sich nicht \xFCberschreiben.`,en:`The field ${a.customFieldId} is assigned more than once on the role's inheritance path (${l.roleId}, ${o}). Inherited fields cannot be overridden.`}),r.set(a.customFieldId,a)}o=n.get(o)}return[...r.values()]}s(MD,"resolveRoleFields");var qD=new Set(["input","parties"]);function KD(e,n){let t=new Set(Array.from(e,Wp));for(let i of t)(!/^[a-z][a-z0-9_]*$/.test(i)||qD.has(i))&&se("INVALID",{de:`Ung\xFCltiger oder reservierter Feldschl\xFCssel: ${i}.`,en:`Invalid or reserved field key: ${i}.`});let r=new Set;for(let i of n){let o=Wp(i);(!/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/.test(o)||qD.has(o.split(".")[0]))&&se("INVALID",{de:`Ung\xFCltiger oder reservierter Parameterschl\xFCssel des Resolvers: ${i}.`,en:`Invalid or reserved resolver parameter key: ${i}.`}),t.has(o)&&se("INVALID",{de:`Der Resolver-Parameter ${i} kollidiert mit einem Feldschl\xFCssel.`,en:`The resolver parameter ${i} collides with a field key.`}),r.has(o)&&se("INVALID",{de:`Doppelter Parameterschl\xFCssel des Resolvers: ${i}.`,en:`Duplicate resolver parameter key: ${i}.`}),r.add(o)}}s(KD,"assertResolverFieldKeys");var qk=["debtor","beneficiary","service_provider"];var jD=["stammdaten","bewerbungsmanagement","finanzen_vertraege","administration","aufgaben","notifications"],H6={stammdaten:{_self:["access","read","write","configure"],parties:["read","write","delete"],customFields:["read","configure","editAutomatic"]},bewerbungsmanagement:{_self:["access"],branding:["manage"],applications:["read","manage","submitOwn","viewExternal","assignResponsibility"],forms:["configure"],workflow:["approval"],testActions:["run"]},finanzen_vertraege:{_self:["access"],contracts:["manage"],payments:["connect"]},administration:{_self:["access"],roles:["manage"],permissions:["manage"],users:["manage"],masterData:["manage"],feedback:["viewAll"],organizationStructure:["manage"],apiTokens:["manage"],config:["read","manage"]},aufgaben:{_self:["access"],items:["read","write","assign","decide"]},notifications:{_self:["access"],mail:["configure"],deliveries:["read"]}},Kk=Object.entries(H6).flatMap(([e,n])=>Object.entries(n).flatMap(([t,r])=>r.map(i=>`${e}.${t}.${i}`))),VD=["read","write","configure"];var J6={tenants:["accessAll"],workers:["monitor"],notifications:["monitor"],users:["manage"],feedback:["read","manage","tags","assign"],config:["read","manage"],schema:["read"],audit:["read","readActor"],apiTokens:["manage"],demoLinks:["manage"]};var jk=Object.entries(J6).flatMap(([e,n])=>n.map(t=>`_platform.${e}.${t}`)),Q6=jk,Z6=["_platform.feedback.assign","_platform.audit.readActor","_platform.apiTokens.manage"],xxe=Q6.filter(e=>!Z6.includes(e));function nm(e,n){return e?.includes(n)??!1}s(nm,"tenantHasModule");var BD=["bewerbungsmanagement.applications.submitOwn"];function UD(e){return Number.isSafeInteger(e)&&e>=1&&e<=36500}s(UD,"isRetentionDays");var Rxe=m.union(m.literal("persons.firstName"),m.literal("persons.lastName"),m.literal("organizations.name"));var X6={Abholberechtigt:"Authorized pickup",Abholzeitfenster:"Pickup window","Abmeldung vom Religionsunterricht seit":"Withdrawn from religion class since","5a, 7b, Vorkurs":"5a, 7b, prep course",Adresszusatz:"Address supplement",Aktiv:"Active","Allergien & Besonderheiten":"Allergies & special notes","Alle Einrichtungen":"All units",Anrede:"Salutation",Ansprechpartner:"Contact person",Arbeitsverh\u00E4ltnis:"Employment",Arbeitszeit:"Working time",Art:"Type","Art der rechtlichen Vertretung":"Legal representation type",Aufenthalt:"Residence","Aufnahme am":"Admission date",Auskunftsberechtigt:"Authorized for information","Ausweis erforderlich":"ID required",Bewerbung:"Application",Bereiche:"Areas","Bedarf an sonderp\xE4dagogischer Unterst\xFCtzung":"Special educational support needed",befreit:"Exempt","Betreuung bis":"Care until",Beziehungen:"Relationships",Daten:"Data",Deutsch:"German",Deutschland:"Germany",divers:"Diverse",Divers:"Diverse","Dokumente & Nachweise":"Documents & evidence",Eintrittsdatum:"Start date","Einwilligung f\xFCr Videoaufnahmen":"Video recording consent",Einschulung:"School enrollment","Endg\xFCltige Zuweisung liegt vor":"Final assignment confirmed","elterliche Sorge":"Parental custody","Entlassung am":"Release date",Entscheidungsbefugt:"Authorized to decide",Erg\u00E4nzungspflegschaft:"Supplementary guardianship",Erstsprache:"First language",Evangelisch:"Protestant",evangelisch:"Protestant",Ehemalig:"Alumni","E-Mail":"Email","Empfehlung Bedarf sonderpad. Unterst.":"Recommendation: special educational support","Empfehlung F\xF6rderort":"Recommendation: support location","Empfehlung F\xF6rderschwerpunkt":"Recommendation: support focus","Extern/Bewerber":"External/applicant",F\u00F6rderbedarf:"Support needs",F\u00F6rderschule:"Special school",F\u00F6rderstunden:"Support hours","F\xF6rderstunden/Woche":"Support hours/week","F\xF6rderschwerpunkte (Mehrfachauswahl)":"Support focuses (multiple selection)",Fotoerlaubnis:"Photo consent",F\u00F6rderung:"Support",Frau:"Ms.",Ganztag:"Full-day care","Ganztag aktiv":"Full-day active",Gasth\u00F6rer:"Guest student",Geburtsdatum:"Date of birth",Geburtsland:"Country of birth",Geburtsort:"Place of birth","Gemeinsames Lernen":"Inclusive learning",Geschlecht:"Gender",Gesundheit:"Health","Gesundheit & Nachweise":"Health & evidence","Getrennt lebend":"Living separately","Gutachten an Schulamt/BezReg":"Report sent to school authority/district government","Gutachten erstellt von":"Report prepared by","Gutachten-Beauftragung bis":"Report commissioned until",Herr:"Mr.",Hinweis:"Note",Hinweise:"Notes","in Kl\xE4rung":"Clarifying","In Pr\xFCfung":"Under review","in Pr\xFCfung":"Under review",Islamisch:"Islamic",islamisch:"Islamic",Ja:"Yes","Ja \u2014 \xA74 Abs. 1 S. 1":"Yes \u2014 Section 4 (1) sentence 1",Katholisch:"Catholic",katholisch:"Catholic",Keine:"None","Keine Auskunft an Dritte":"No information to third parties","keine Teilnahme":"No participation","kein Bedarf":"No need",Klasse:"Class","Klassenlehrer/in":"Class teacher",Konfession:"Denomination",Kontaktarten:"Contact types",Korrespondenz:"Correspondence","K\xF6rperliche und motorische Entwicklung":"Physical and motor development",Land:"Country",Lernen:"Learning","LRS / Rechenschw\xE4che":"Dyslexia / dyscalculia",m\u00E4nnlich:"male",Masernimpfnachweis:"Measles vaccination proof","Mit Einschr\xE4nkungen":"With restrictions","Mitarbeiter/in":"Staff member",Mutter:"Mother",Nachname:"Last name","Name der Organisation":"Organization name",Nein:"No","Nicht gruppiert":"Ungrouped",Notfallkontakt:"Emergency contact","Nr.":"No.","Ohne Angabe":"Not specified","ohne Angabe":"not specified","Operative Kontaktart":"Operational contact type","Operativer Kontakt":"Operational contact",Organisation:"Organization",Organisationen:"Organizations",Ort:"City",Ortsteil:"District",Person:"Person",PLZ:"Postal code",Polen:"Poland",Position:"Position",Prim\u00E4rkontakt:"Primary contact",Priorit\u00E4t:"Priority","Probeweise Zuweisung liegt vor bis":"Trial assignment confirmed until",Regelschule:"Mainstream school","Rechtliche Vertretung":"Legal representation",Religionsunterricht:"Religion class",Rolle:"Role",Schule:"School",Schulinformationen:"School information","Sch\xFCler/in":"Student","Sch\xFClerinteressent/in":"Prospective student",Sch\u00FClernummer:"Student number",Sch\u00FClerstatus:"Student status","Sch\xFClerverzeichnis Nr.":"Student directory no.",Schwimmunterricht:"Swimming class","Scope der rechtlichen Vertretung":"Legal representation scope",Sprache:"Language",Staatsangeh\u00F6rigkeit:"Nationality",Stammdaten:"Master data",Standort:"Location","Standort/Schule":"Location/school",Status:"Status",Stra\u00DFe:"Street",Syrien:"Syria",Telefon:"Phone",Teilnahme:"Participation",T\u00FCrkei:"Turkey",T\u00FCrkisch:"Turkish",Ukraine:"Ukraine",Umfang:"Extent","Umfang der rechtlichen Vertretung":"Legal representation extent",Verwaltung:"Administration",Verwandtschaft:"Kinship",Verwandtschaftsart:"Kinship type",Verwandtschaftsgrad:"Degree of kinship",Vater:"Father",Vietnamesisch:"Vietnamese",Vollst\u00E4ndig:"Complete",voll:"full",Vorname:"First name","Vormundschaft Amt":"Public guardianship","Vormundschaft Einzelner":"Individual guardianship","Vormundschaft Verein":"Association guardianship",weiblich:"female",Wohnadresse:"Residential address",Wohnort:"City of residence","Aktives Programm \xFCber Einschreibung, Lerngruppe und Programm.":"Active program across enrollment, learning group, and program.",Arabisch:"Arabic","Auskunft gesperrt":"Information blocked","Campus Lindenfeld":"Campus Lindenfeld","Campus Sonnhalde":"Campus Sonnhalde","Emotionale Entwicklung":"Emotional development","Emotionale und soziale Entwicklung":"Emotional and social development","Foto eingeschr\xE4nkt":"Photo restricted","Geistige Entwicklung":"Cognitive development",Gro\u00DFeltern:"Grandparents","Grundschule Sonnenberg":"Sonnenberg Elementary School","Interessent/in":"Prospect","Keine Einwilligung f\xFCr Videoaufnahmen":"No video recording consent","Keine Fotos":"No photos","K\xF6rper/Motorik":"Physical/motor",Lehrer:"Teacher",Mitarbeitende:"Staff","Moers, Krefeld":"Moers, Krefeld","Namen der verkn\xFCpften rechtlichen Vertretungen.":"Names of the linked legal representatives.",Pflegeperson:"Caregiver",Programm:"Program","Rechtliche Vertretungen":"Legal representatives",Schulleitung:"School leadership",Schulverwaltung:"School administration",Stiefeltern:"Stepparents",Verm\u00F6gen:"Assets",teilweise:"partial"};function Ho(e,n=X6[e]){return(n===void 0||n.trim()==="")&&L(`label("${e}"): no English text \u2014 pass it, or add it to ENGLISH_LABELS`),{de:e.trim(),en:n.trim()}}s(Ho,"label");var Vk=[{key:"first_name",label:Ho("Vorname","First name"),type:"string",systemColumn:"persons.firstName",partyKind:"person",required:!0},{key:"last_name",label:Ho("Nachname","Last name"),type:"string",systemColumn:"persons.lastName",partyKind:"person",required:!0},{key:"organization_name",label:Ho("Name der Organisation","Organization name"),type:"string",systemColumn:"organizations.name",partyKind:"organization",required:!0}],e4=new Map(Vk.map(e=>[e.key,e]));function GD(e){return e4.has(e)}s(GD,"isSystemFieldKey");var Bk={string:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},textarea:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},email:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},tel:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},date:{dataType:"date",valueColumn:"valueDate",fieldMapTarget:!0},number:{dataType:"number",valueColumn:"valueNumber",fieldMapTarget:!0},boolean:{dataType:"boolean",valueColumn:"valueBoolean",fieldMapTarget:!0},files:{dataType:"file",valueColumn:"valueJson",fieldMapTarget:!0},"auto-string":{dataType:"text",valueColumn:"valueString",fieldMapTarget:!1},"0-1-select":{dataType:"option",valueColumn:"valueString",fieldMapTarget:!0},"0-n-select":{dataType:"option",valueColumn:"valueJson",fieldMapTarget:!0},object:{dataType:"composite",valueColumn:"valueJson",fieldMapTarget:!0},relationship:{dataType:"edge",valueColumn:"valueJson",fieldMapTarget:!1},"program-interest":{dataType:"edge",valueColumn:"valueJson",fieldMapTarget:!1}};var Vxe=11*6e4;var Bxe=30*6e4;var Uxe=5*6e4;var Gxe=5*6e4;var tm="tenant",zxe=m.record(m.string(),m.string());var Hi=1024*1024,pd=["application/pdf","image/jpeg","image/png","image/webp"];var rm=["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/msword","application/vnd.oasis.opendocument.text","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","image/jpeg","image/png"],zD={docRef:{maxBytes:25*Hi,allowedMime:pd},partyFile:{maxBytes:25*Hi,allowedMime:pd},import:{maxBytes:500*Hi,allowedMime:null},signedContract:{maxBytes:25*Hi,allowedMime:pd},artifactVersion:{maxBytes:25*Hi,allowedMime:pd},chatAttachment:{maxBytes:25*Hi,allowedMime:pd},tenantFile:{maxBytes:20*Hi,allowedMime:rm},documentTemplate:{maxBytes:25*Hi,allowedMime:null}};function WD(e){let n=atob(e),t="";for(let r=0;r<n.length;r++)t+=n.charCodeAt(r).toString(16).padStart(2,"0");return t}s(WD,"sha256Base64ToHex");var Lt={filename:m.string(),mimeType:m.string(),sizeBytes:m.number(),sha256:m.string()},n4=m.object({storageId:m.id("_storage"),filename:Lt.filename,mimeType:Lt.mimeType,sizeBytes:Lt.sizeBytes,sha256:m.optional(Lt.sha256)}),nSe=m.object({storageId:n4.fields.storageId,filename:Lt.filename,mimeType:m.optional(Lt.mimeType),sizeBytes:m.optional(Lt.sizeBytes),sha256:m.optional(Lt.sha256),url:m.union(m.string(),m.null())});async function t4(e,n){let t=await e.db.system.get("_storage",n);return t===null?null:{...t.contentType===void 0?{}:{mimeType:t.contentType},sizeBytes:t.size,sha256:WD(t.sha256)}}s(t4,"storedObjectMeta");async function Uk(e,n){let t=(await t4(e,n))?.mimeType;return t===void 0?{}:{mimeType:t}}s(Uk,"objectType");var aSe=m.union(m.literal("de"),m.literal("en")),lSe=m.record(m.string(),m.string()),Ji=m.object({de:m.string(),en:m.string()}),dSe=m.object({title:Ji,body:Ji,confirmLabel:Ji}),cSe=m.union(m.string(),Ji);function im(e){return We.includes(e)}s(im,"isSupportedLocale");var r4=m.object({street:m.string(),hausnr:m.string(),plz:m.string(),ort:m.string(),land:m.string()}),YD=m.object({storageId:m.string(),filename:Lt.filename,mimeType:m.optional(Lt.mimeType),sizeBytes:m.optional(Lt.sizeBytes),sha256:m.optional(Lt.sha256),uploadedAt:m.number()}),uSe=m.union(m.string(),m.number(),m.boolean(),m.null(),r4,YD,m.array(m.string()),m.array(YD)),fSe=m.record(m.string(),m.string());var Gk=["Bewerbung","Anmeldung"];var JD=m.object({application:m.optional(m.union(...Gk.map(e=>m.literal(e))))}),gSe=m.object({application:m.union(...Gk.map(e=>m.literal(e)))}),HD={application:Gk};function zk(e,n="tenant.terms"){if(e===null||typeof e!="object"||Array.isArray(e))return[`[terms/shape] ${n} muss ein Objekt sein, z. B. { "application": "Anmeldung" }.`];let t=[];for(let[r,i]of Object.entries(e)){let o=HD[r];if(o===void 0){t.push(`[terms/unknownTerm] ${n}.${r} gibt es nicht. Einstellbar: ${Object.keys(HD).join(", ")}.`);continue}(typeof i!="string"||!o.includes(i))&&t.push(`[terms/unknownChoice] ${n}.${r} = ${JSON.stringify(i)} ist keine Wahl. M\xF6glich: ${o.join(", ")}.`)}return t}s(zk,"termsFindings");var Vr="recipientName",Ra="Name der Empf\xE4ngerin oder des Empf\xE4ngers";var md={de:{greeting:`Hallo {{${Vr}}},`,closing:`Viele Gr\xFC\xDFe
11268
+ - `)}`);let o=await this.caller(),a=this.requireTenant(o),l=await fd(Lk,r,z4,this.confirm,async d=>(await o.mutation(x.learningGroupImport.apply,{client:a,dryRun:!this.confirm,schoolYear:n.schoolYear,rows:d})).rows);return this.print(W4(l,this.confirm),d=>[...d.classes.map(c=>({...c})),{class:"\u2014",program:`${d.programsCreated} new / ${d.programsTotal}`,schoolYear:`${d.runsCreated} new / ${d.runsTotal}`,action:d.totals,changes:d.mode}],["class","program","schoolYear","action","changes"]),0}};function W4(e,n){let t=s(a=>{let l=new Map;for(let[d,c]of a)l.get(d)!=="create"&&l.set(d,c);return l},"created"),r=t(e.map(a=>[a.program.key,a.program.action])),i=t(e.map(a=>[a.run.key,a.run.action])),o=s(a=>e.filter(l=>l.group.action===a).length,"count");return{mode:n?"COMMITTED":"PLAN (re-run with --confirm to write)",programsTotal:r.size,programsCreated:[...r.values()].filter(a=>a==="create").length,runsTotal:i.size,runsCreated:[...i.values()].filter(a=>a==="create").length,totals:`${o("create")} create \xB7 ${o("update")} update \xB7 ${o("unchanged")} unchanged`,classes:e.map(a=>({class:a.code,program:`${a.program.key}${a.program.action==="create"?" (new)":""}`,schoolYear:`${a.run.key}${a.run.action==="create"?" (new)":""}`,action:a.group.action,changes:a.group.changes.join("; ")}))}}s(W4,"summary");var DD=[Mk];var Y4=["permanentLink","periodLink"],uxe=720*60*1e3;function FD(e){if(typeof e!="object"||e===null)return!1;let n=e;return n.mode==="oneTimeLink"&&Object.keys(n).join(",")==="mode"}s(FD,"isExternalSignIn");function LD(e){if(typeof e!="object"||e===null)return!1;let n=e.mode;return Y4.includes(n)}s(LD,"namesRetiredExternalSignIn");function MD(e,n,t){let r=new Map,i=new Set,o=e;for(;o!==void 0;){i.has(o)&&L(`Role inheritance cycle at ${o}.`),n.has(o)||L(`Missing role ${o} in inheritance path.`),i.add(o);for(let a of t.get(o)??[]){let l=r.get(a.customFieldId);l&&se("ROLE_FIELD_INHERITED",{de:`Das Feld ${a.customFieldId} ist auf dem Vererbungspfad der Rolle mehrfach zugeordnet (${l.roleId}, ${o}). Geerbte Felder lassen sich nicht \xFCberschreiben.`,en:`The field ${a.customFieldId} is assigned more than once on the role's inheritance path (${l.roleId}, ${o}). Inherited fields cannot be overridden.`}),r.set(a.customFieldId,a)}o=n.get(o)}return[...r.values()]}s(MD,"resolveRoleFields");var qD=new Set(["input","parties"]);function KD(e,n){let t=new Set(Array.from(e,Wp));for(let i of t)(!/^[a-z][a-z0-9_]*$/.test(i)||qD.has(i))&&se("INVALID",{de:`Ung\xFCltiger oder reservierter Feldschl\xFCssel: ${i}.`,en:`Invalid or reserved field key: ${i}.`});let r=new Set;for(let i of n){let o=Wp(i);(!/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/.test(o)||qD.has(o.split(".")[0]))&&se("INVALID",{de:`Ung\xFCltiger oder reservierter Parameterschl\xFCssel des Resolvers: ${i}.`,en:`Invalid or reserved resolver parameter key: ${i}.`}),t.has(o)&&se("INVALID",{de:`Der Resolver-Parameter ${i} kollidiert mit einem Feldschl\xFCssel.`,en:`The resolver parameter ${i} collides with a field key.`}),r.has(o)&&se("INVALID",{de:`Doppelter Parameterschl\xFCssel des Resolvers: ${i}.`,en:`Duplicate resolver parameter key: ${i}.`}),r.add(o)}}s(KD,"assertResolverFieldKeys");var qk=["debtor","beneficiary","service_provider"];var jD=["stammdaten","bewerbungsmanagement","finanzen_vertraege","administration","aufgaben","notifications"],H4={stammdaten:{_self:["access","read","write","configure"],parties:["read","write","delete"],customFields:["read","configure","editAutomatic"]},bewerbungsmanagement:{_self:["access"],branding:["manage"],applications:["read","manage","submitOwn","viewExternal","assignResponsibility"],forms:["configure"],workflow:["approval"],testActions:["run"]},finanzen_vertraege:{_self:["access"],contracts:["manage"],payments:["connect"]},administration:{_self:["access"],roles:["manage"],permissions:["manage"],users:["manage"],masterData:["manage"],feedback:["viewAll"],organizationStructure:["manage"],apiTokens:["manage"],config:["read","manage"]},aufgaben:{_self:["access"],items:["read","write","assign","decide"]},notifications:{_self:["access"],mail:["configure"],deliveries:["read"]}},Kk=Object.entries(H4).flatMap(([e,n])=>Object.entries(n).flatMap(([t,r])=>r.map(i=>`${e}.${t}.${i}`))),VD=["read","write","configure"];var J4={tenants:["accessAll"],workers:["monitor"],notifications:["monitor"],users:["manage"],feedback:["read","manage","tags","assign"],config:["read","manage"],schema:["read"],audit:["read","readActor"],apiTokens:["manage"],demoLinks:["manage"]};var jk=Object.entries(J4).flatMap(([e,n])=>n.map(t=>`_platform.${e}.${t}`)),Q4=jk,Z4=["_platform.feedback.assign","_platform.audit.readActor","_platform.apiTokens.manage"],xxe=Q4.filter(e=>!Z4.includes(e));function nm(e,n){return e?.includes(n)??!1}s(nm,"tenantHasModule");var BD=["bewerbungsmanagement.applications.submitOwn"];function UD(e){return Number.isSafeInteger(e)&&e>=1&&e<=36500}s(UD,"isRetentionDays");var Rxe=m.union(m.literal("persons.firstName"),m.literal("persons.lastName"),m.literal("organizations.name"));var X4={Abholberechtigt:"Authorized pickup",Abholzeitfenster:"Pickup window","Abmeldung vom Religionsunterricht seit":"Withdrawn from religion class since","5a, 7b, Vorkurs":"5a, 7b, prep course",Adresszusatz:"Address supplement",Aktiv:"Active","Allergien & Besonderheiten":"Allergies & special notes","Alle Einrichtungen":"All units",Anrede:"Salutation",Ansprechpartner:"Contact person",Arbeitsverh\u00E4ltnis:"Employment",Arbeitszeit:"Working time",Art:"Type","Art der rechtlichen Vertretung":"Legal representation type",Aufenthalt:"Residence","Aufnahme am":"Admission date",Auskunftsberechtigt:"Authorized for information","Ausweis erforderlich":"ID required",Bewerbung:"Application",Bereiche:"Areas","Bedarf an sonderp\xE4dagogischer Unterst\xFCtzung":"Special educational support needed",befreit:"Exempt","Betreuung bis":"Care until",Beziehungen:"Relationships",Daten:"Data",Deutsch:"German",Deutschland:"Germany",divers:"Diverse",Divers:"Diverse","Dokumente & Nachweise":"Documents & evidence",Eintrittsdatum:"Start date","Einwilligung f\xFCr Videoaufnahmen":"Video recording consent",Einschulung:"School enrollment","Endg\xFCltige Zuweisung liegt vor":"Final assignment confirmed","elterliche Sorge":"Parental custody","Entlassung am":"Release date",Entscheidungsbefugt:"Authorized to decide",Erg\u00E4nzungspflegschaft:"Supplementary guardianship",Erstsprache:"First language",Evangelisch:"Protestant",evangelisch:"Protestant",Ehemalig:"Alumni","E-Mail":"Email","Empfehlung Bedarf sonderpad. Unterst.":"Recommendation: special educational support","Empfehlung F\xF6rderort":"Recommendation: support location","Empfehlung F\xF6rderschwerpunkt":"Recommendation: support focus","Extern/Bewerber":"External/applicant",F\u00F6rderbedarf:"Support needs",F\u00F6rderschule:"Special school",F\u00F6rderstunden:"Support hours","F\xF6rderstunden/Woche":"Support hours/week","F\xF6rderschwerpunkte (Mehrfachauswahl)":"Support focuses (multiple selection)",Fotoerlaubnis:"Photo consent",F\u00F6rderung:"Support",Frau:"Ms.",Ganztag:"Full-day care","Ganztag aktiv":"Full-day active",Gasth\u00F6rer:"Guest student",Geburtsdatum:"Date of birth",Geburtsland:"Country of birth",Geburtsort:"Place of birth","Gemeinsames Lernen":"Inclusive learning",Geschlecht:"Gender",Gesundheit:"Health","Gesundheit & Nachweise":"Health & evidence","Getrennt lebend":"Living separately","Gutachten an Schulamt/BezReg":"Report sent to school authority/district government","Gutachten erstellt von":"Report prepared by","Gutachten-Beauftragung bis":"Report commissioned until",Herr:"Mr.",Hinweis:"Note",Hinweise:"Notes","in Kl\xE4rung":"Clarifying","In Pr\xFCfung":"Under review","in Pr\xFCfung":"Under review",Islamisch:"Islamic",islamisch:"Islamic",Ja:"Yes","Ja \u2014 \xA74 Abs. 1 S. 1":"Yes \u2014 Section 4 (1) sentence 1",Katholisch:"Catholic",katholisch:"Catholic",Keine:"None","Keine Auskunft an Dritte":"No information to third parties","keine Teilnahme":"No participation","kein Bedarf":"No need",Klasse:"Class","Klassenlehrer/in":"Class teacher",Konfession:"Denomination",Kontaktarten:"Contact types",Korrespondenz:"Correspondence","K\xF6rperliche und motorische Entwicklung":"Physical and motor development",Land:"Country",Lernen:"Learning","LRS / Rechenschw\xE4che":"Dyslexia / dyscalculia",m\u00E4nnlich:"male",Masernimpfnachweis:"Measles vaccination proof","Mit Einschr\xE4nkungen":"With restrictions","Mitarbeiter/in":"Staff member",Mutter:"Mother",Nachname:"Last name","Name der Organisation":"Organization name",Nein:"No","Nicht gruppiert":"Ungrouped",Notfallkontakt:"Emergency contact","Nr.":"No.","Ohne Angabe":"Not specified","ohne Angabe":"not specified","Operative Kontaktart":"Operational contact type","Operativer Kontakt":"Operational contact",Organisation:"Organization",Organisationen:"Organizations",Ort:"City",Ortsteil:"District",Person:"Person",PLZ:"Postal code",Polen:"Poland",Position:"Position",Prim\u00E4rkontakt:"Primary contact",Priorit\u00E4t:"Priority","Probeweise Zuweisung liegt vor bis":"Trial assignment confirmed until",Regelschule:"Mainstream school","Rechtliche Vertretung":"Legal representation",Religionsunterricht:"Religion class",Rolle:"Role",Schule:"School",Schulinformationen:"School information","Sch\xFCler/in":"Student","Sch\xFClerinteressent/in":"Prospective student",Sch\u00FClernummer:"Student number",Sch\u00FClerstatus:"Student status","Sch\xFClerverzeichnis Nr.":"Student directory no.",Schwimmunterricht:"Swimming class","Scope der rechtlichen Vertretung":"Legal representation scope",Sprache:"Language",Staatsangeh\u00F6rigkeit:"Nationality",Stammdaten:"Master data",Standort:"Location","Standort/Schule":"Location/school",Status:"Status",Stra\u00DFe:"Street",Syrien:"Syria",Telefon:"Phone",Teilnahme:"Participation",T\u00FCrkei:"Turkey",T\u00FCrkisch:"Turkish",Ukraine:"Ukraine",Umfang:"Extent","Umfang der rechtlichen Vertretung":"Legal representation extent",Verwaltung:"Administration",Verwandtschaft:"Kinship",Verwandtschaftsart:"Kinship type",Verwandtschaftsgrad:"Degree of kinship",Vater:"Father",Vietnamesisch:"Vietnamese",Vollst\u00E4ndig:"Complete",voll:"full",Vorname:"First name","Vormundschaft Amt":"Public guardianship","Vormundschaft Einzelner":"Individual guardianship","Vormundschaft Verein":"Association guardianship",weiblich:"female",Wohnadresse:"Residential address",Wohnort:"City of residence","Aktives Programm \xFCber Einschreibung, Lerngruppe und Programm.":"Active program across enrollment, learning group, and program.",Arabisch:"Arabic","Auskunft gesperrt":"Information blocked","Campus Lindenfeld":"Campus Lindenfeld","Campus Sonnhalde":"Campus Sonnhalde","Emotionale Entwicklung":"Emotional development","Emotionale und soziale Entwicklung":"Emotional and social development","Foto eingeschr\xE4nkt":"Photo restricted","Geistige Entwicklung":"Cognitive development",Gro\u00DFeltern:"Grandparents","Grundschule Sonnenberg":"Sonnenberg Elementary School","Interessent/in":"Prospect","Keine Einwilligung f\xFCr Videoaufnahmen":"No video recording consent","Keine Fotos":"No photos","K\xF6rper/Motorik":"Physical/motor",Lehrer:"Teacher",Mitarbeitende:"Staff","Moers, Krefeld":"Moers, Krefeld","Namen der verkn\xFCpften rechtlichen Vertretungen.":"Names of the linked legal representatives.",Pflegeperson:"Caregiver",Programm:"Program","Rechtliche Vertretungen":"Legal representatives",Schulleitung:"School leadership",Schulverwaltung:"School administration",Stiefeltern:"Stepparents",Verm\u00F6gen:"Assets",teilweise:"partial"};function Ho(e,n=X4[e]){return(n===void 0||n.trim()==="")&&L(`label("${e}"): no English text \u2014 pass it, or add it to ENGLISH_LABELS`),{de:e.trim(),en:n.trim()}}s(Ho,"label");var Vk=[{key:"first_name",label:Ho("Vorname","First name"),type:"string",systemColumn:"persons.firstName",partyKind:"person",required:!0},{key:"last_name",label:Ho("Nachname","Last name"),type:"string",systemColumn:"persons.lastName",partyKind:"person",required:!0},{key:"organization_name",label:Ho("Name der Organisation","Organization name"),type:"string",systemColumn:"organizations.name",partyKind:"organization",required:!0}],e6=new Map(Vk.map(e=>[e.key,e]));function GD(e){return e6.has(e)}s(GD,"isSystemFieldKey");var Bk={string:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},textarea:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},email:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},tel:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},date:{dataType:"date",valueColumn:"valueDate",fieldMapTarget:!0},number:{dataType:"number",valueColumn:"valueNumber",fieldMapTarget:!0},boolean:{dataType:"boolean",valueColumn:"valueBoolean",fieldMapTarget:!0},files:{dataType:"file",valueColumn:"valueJson",fieldMapTarget:!0},"auto-string":{dataType:"text",valueColumn:"valueString",fieldMapTarget:!1},"0-1-select":{dataType:"option",valueColumn:"valueString",fieldMapTarget:!0},"0-n-select":{dataType:"option",valueColumn:"valueJson",fieldMapTarget:!0},object:{dataType:"composite",valueColumn:"valueJson",fieldMapTarget:!0},relationship:{dataType:"edge",valueColumn:"valueJson",fieldMapTarget:!1},"program-interest":{dataType:"edge",valueColumn:"valueJson",fieldMapTarget:!1}};var Vxe=11*6e4;var Bxe=30*6e4;var Uxe=5*6e4;var Gxe=5*6e4;var tm="tenant",zxe=m.record(m.string(),m.string());var Hi=1024*1024,pd=["application/pdf","image/jpeg","image/png","image/webp"];var rm=["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/msword","application/vnd.oasis.opendocument.text","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","image/jpeg","image/png"],zD={docRef:{maxBytes:25*Hi,allowedMime:pd},partyFile:{maxBytes:25*Hi,allowedMime:pd},import:{maxBytes:500*Hi,allowedMime:null},signedContract:{maxBytes:25*Hi,allowedMime:pd},artifactVersion:{maxBytes:25*Hi,allowedMime:pd},chatAttachment:{maxBytes:25*Hi,allowedMime:pd},tenantFile:{maxBytes:20*Hi,allowedMime:rm},documentTemplate:{maxBytes:25*Hi,allowedMime:null}};function WD(e){let n=atob(e),t="";for(let r=0;r<n.length;r++)t+=n.charCodeAt(r).toString(16).padStart(2,"0");return t}s(WD,"sha256Base64ToHex");var Lt={filename:m.string(),mimeType:m.string(),sizeBytes:m.number(),sha256:m.string()},n6=m.object({storageId:m.id("_storage"),filename:Lt.filename,mimeType:Lt.mimeType,sizeBytes:Lt.sizeBytes,sha256:m.optional(Lt.sha256)}),nSe=m.object({storageId:n6.fields.storageId,filename:Lt.filename,mimeType:m.optional(Lt.mimeType),sizeBytes:m.optional(Lt.sizeBytes),sha256:m.optional(Lt.sha256),url:m.union(m.string(),m.null())});async function t6(e,n){let t=await e.db.system.get("_storage",n);return t===null?null:{...t.contentType===void 0?{}:{mimeType:t.contentType},sizeBytes:t.size,sha256:WD(t.sha256)}}s(t6,"storedObjectMeta");async function Uk(e,n){let t=(await t6(e,n))?.mimeType;return t===void 0?{}:{mimeType:t}}s(Uk,"objectType");var aSe=m.union(m.literal("de"),m.literal("en")),lSe=m.record(m.string(),m.string()),Ji=m.object({de:m.string(),en:m.string()}),dSe=m.object({title:Ji,body:Ji,confirmLabel:Ji}),cSe=m.union(m.string(),Ji);function im(e){return We.includes(e)}s(im,"isSupportedLocale");var r6=m.object({street:m.string(),hausnr:m.string(),plz:m.string(),ort:m.string(),land:m.string()}),YD=m.object({storageId:m.string(),filename:Lt.filename,mimeType:m.optional(Lt.mimeType),sizeBytes:m.optional(Lt.sizeBytes),sha256:m.optional(Lt.sha256),uploadedAt:m.number()}),uSe=m.union(m.string(),m.number(),m.boolean(),m.null(),r6,YD,m.array(m.string()),m.array(YD)),fSe=m.record(m.string(),m.string());var Gk=["Bewerbung","Anmeldung"];var JD=m.object({application:m.optional(m.union(...Gk.map(e=>m.literal(e))))}),gSe=m.object({application:m.union(...Gk.map(e=>m.literal(e)))}),HD={application:Gk};function zk(e,n="tenant.terms"){if(e===null||typeof e!="object"||Array.isArray(e))return[`[terms/shape] ${n} muss ein Objekt sein, z. B. { "application": "Anmeldung" }.`];let t=[];for(let[r,i]of Object.entries(e)){let o=HD[r];if(o===void 0){t.push(`[terms/unknownTerm] ${n}.${r} gibt es nicht. Einstellbar: ${Object.keys(HD).join(", ")}.`);continue}(typeof i!="string"||!o.includes(i))&&t.push(`[terms/unknownChoice] ${n}.${r} = ${JSON.stringify(i)} ist keine Wahl. M\xF6glich: ${o.join(", ")}.`)}return t}s(zk,"termsFindings");var Vr="recipientName",Ra="Name der Empf\xE4ngerin oder des Empf\xE4ngers";var md={de:{greeting:`Hallo {{${Vr}}},`,closing:`Viele Gr\xFC\xDFe
11269
11269
  Ihr Aufnahme-Team`,noReplyNote:"Diese E-Mail wurde automatisch versandt. Bitte antworten Sie nicht auf diese Nachricht."},en:{greeting:`Hello {{${Vr}}},`,closing:`Kind regards
11270
- The admissions team`,noReplyNote:"This e-mail was sent automatically. Please do not reply to it."}},i4={de:{...md.de,closing:`Viele Gr\xFC\xDFe
11270
+ The admissions team`,noReplyNote:"This e-mail was sent automatically. Please do not reply to it."}},i6={de:{...md.de,closing:`Viele Gr\xFC\xDFe
11271
11271
  Ihr Plexus-Team`},en:{...md.en,closing:`Kind regards
11272
- The Plexus team`}},o4={de:{...md.de,closing:null},en:{...md.en,closing:null}};var s4=/\{\{([a-zA-Z][a-zA-Z0-9_]*)\}\}/g,Jo=2e3;function om(e){let n=[];for(let t of e.matchAll(s4)){let r=t[1];n.includes(r)||n.push(r)}return n}s(om,"placeholdersIn");function QD(e){return e.slots??[]}s(QD,"slotsOf");function a4(e){return e.bodyVariants!==void 0?e.bodyVariants:[QD(e).filter(n=>n.key!==jl).map(n=>n.key)]}s(a4,"bodyVariantsOf");var l4=/:\/\/|www\.|mailto:/i;function d4(e,n){let t=`{{${n}}}`,r=0;for(;;){let i=e.indexOf(t,r);if(i===-1)return!1;let o=i===0?"":e[i-1],a=e[i+t.length]??"";if(o!==""&&!/\s/.test(o)||a!==""&&!/[\s.,;:!?)]/.test(a))return!0;r=i+t.length}}s(d4,"linkGlued");function c4(e,n){let t=e.default[n];return(typeof t!="string"||t.length===0)&&L(`notifications: slot "${e.key}" has no "${n}" text`),t}s(c4,"defaultText");function ZD(e,n,t){let r=[],i=QD(e),o=e.placeholders??[],a=o.map(u=>u.key),l=o.filter(u=>u.subjectSafe===!0).map(u=>u.key);for(let[u,p]of Object.entries(n)){let h=i.find(y=>y.key===u);if(h===void 0){r.push({slotKey:u,code:"unknownSlot",message:i.length===0?{de:`Der Brief \u201E${e.label}\u201C l\xE4sst sich nicht anpassen.`,en:`The letter "${e.label}" cannot be customized.`}:{de:`Der Baustein \u201E${u}\u201C geh\xF6rt nicht zum Brief \u201E${e.label}\u201C.`,en:`The block "${u}" does not belong to the letter "${e.label}".`}});continue}if(p.trim().length===0){r.push({slotKey:u,code:"empty",message:{de:`\u201E${h.label}\u201C darf nicht leer sein. Zum Entfernen den Baustein zur\xFCcksetzen.`,en:`"${h.label}" must not be empty. To remove it, reset the block.`}});continue}if(p.length>Jo){r.push({slotKey:u,code:"tooLong",message:{de:`\u201E${h.label}\u201C ist ${p.length} Zeichen lang, erlaubt sind ${Jo}.`,en:`"${h.label}" is ${p.length} characters long; the limit is ${Jo}.`}});continue}if(J_(e)){l4.test(p)&&r.push({slotKey:u,code:"foreignUrl",message:{de:`\u201E${h.label}\u201C enth\xE4lt eine Adresse. Der Brief \u201E${e.label}\u201C tr\xE4gt einen Anmeldeschl\xFCssel und darf keine weiteren Links enthalten.`,en:`"${h.label}" contains an address. The letter "${e.label}" carries a sign-in key and must not contain any further links.`}});for(let y of o)y.link!==!0||!d4(p,y.key)||r.push({slotKey:u,code:"linkNotStandalone",message:{de:`\u201E{{${y.key}}}\u201C (${y.label}) muss f\xFCr sich stehen \u2014 davor und dahinter nur ein Leerzeichen, ein Zeilenumbruch oder ein Satzzeichen.`,en:`"{{${y.key}}}" (${y.label}) must stand on its own \u2014 only a space, a line break or punctuation before and after it.`}})}for(let y of om(p)){if(!a.includes(y)){r.push({slotKey:u,code:"unknownPlaceholder",message:y===Vr?{de:`\u201E{{${Vr}}}\u201C (${Ra}) geh\xF6rt in die Anrede des Briefrahmens, nicht in \u201E${h.label}\u201C \u2014 dort gibt es eine neutrale Anrede, wenn kein Name bekannt ist.`,en:`"{{${Vr}}}" (${Ra}) belongs in the greeting of the letter frame, not in "${h.label}" \u2014 the greeting has a neutral form for when no name is known.`}:a.length===0?{de:`Der Brief \u201E${e.label}\u201C kennt keine Platzhalter, \u201E{{${y}}}\u201C bliebe unersetzt stehen.`,en:`The letter "${e.label}" has no placeholders; "{{${y}}}" would stay in the text unreplaced.`}:{de:`\u201E{{${y}}}\u201C gibt es in \u201E${e.label}\u201C nicht. Erlaubt: ${a.map(w=>`{{${w}}}`).join(", ")}.`,en:`"{{${y}}}" does not exist in "${e.label}". Allowed: ${a.map(w=>`{{${w}}}`).join(", ")}.`}});continue}if(u!==jl||l.includes(y))continue;let k=o.find(w=>w.key===y)?.label??y;r.push({slotKey:u,code:"subjectUnsupported",message:{de:`\u201E{{${y}}}\u201C (${k}) l\xE4sst sich im Betreff nicht einsetzen \u2014 der Wert entsteht erst beim Versand. `+(l.length===0?"In diesem Brief kann der Betreff keine Platzhalter tragen.":`Im Betreff m\xF6glich: ${l.map(w=>`{{${w}}}`).join(", ")}.`),en:`"{{${y}}}" (${k}) cannot be used in the subject \u2014 the value only exists when the mail is sent. `+(l.length===0?"In this letter the subject cannot carry placeholders.":`Possible in the subject: ${l.map(w=>`{{${w}}}`).join(", ")}.`)}})}}let d=s(u=>n[u]??u4(i,u,t),"textOf"),c=a4(e);for(let u of o){if(u.required!==!0)continue;let p=c.filter(w=>!om(w.map(d).join(`
11273
- `)).includes(u.key));if(p.length===0)continue;let h=s((w,v)=>w.map(A=>v(i.find(E=>E.key===A)?.label??A)).join(" + "),"variantLabel"),y=c.length===1?"":` Er fehlt in der Fassung aus ${p.map(w=>h(w,v=>`\u201E${v}\u201C`)).join(" und in der aus ")}.`,k=c.length===1?"":` It is missing in the version made of ${p.map(w=>h(w,v=>`"${v}"`)).join(" and in the one made of ")}.`;r.push({slotKey:u.key,code:"missingRequired",message:{de:`Ohne \u201E{{${u.key}}}\u201C (${u.label}) funktioniert der Brief \u201E${e.label}\u201C nicht \u2014 der Platzhalter muss im Text stehen, nicht nur im Betreff.`+y,en:`Without "{{${u.key}}}" (${u.label}) the letter "${e.label}" does not work \u2014 the placeholder must be in the text, not only in the subject.`+k}})}return r}s(ZD,"validateOverride");function u4(e,n,t){let r=e.find(i=>i.key===n);return r===void 0?"":c4(r,t)}s(u4,"defaultTextOf");function Wk(e){let n=e?.trim();return n===void 0||n.length===0?void 0:n}s(Wk,"normalizeChromeText");var Qo=s(e=>String.fromCharCode(e),"cp"),f4=new RegExp(`[${Qo(0)}-${Qo(31)}${Qo(127)}]`,"g"),p4=new RegExp(`[${Qo(8234)}-${Qo(8238)}${Qo(8294)}-${Qo(8297)}]`,"g");var m4=200;function h4(e,n=m4){return e.replace(f4," ").replace(p4,"").replace(/\s+/g," ").trim().slice(0,n)}s(h4,"sanitizeHeaderValue");function sm(e){return h4(e.replace(/["<>@]/g,""),100)}s(sm,"sanitizeDisplayName");var Yk={de:{de:"Deutsch",en:"German"},en:{de:"Englisch",en:"English"}},g4={greeting:{de:"Anrede",en:"Greeting"},closing:{de:"Gru\xDFformel",en:"Closing"}};function XD(e){let n=[],t=[];for(let i of["greeting","closing"]){let o=e[i];if(o===void 0)continue;let a=g4[i],l=Rn(o);l!=="not-localized"&&l.length>0&&l.length<We.length&&t.push({de:`${a.de} fehlt auf ${l.map(d=>Yk[d].de).join(" und ")}`,en:`${a.en} is missing in ${l.map(d=>Yk[d].en).join(" and ")}`});for(let d of We){let c=hw(h=>`${a[h]} (${Yk[d][h]})`),u=Wk(o[d]);u!==void 0&&u.length>Jo&&n.push({de:`${c.de} hat ${u.length} Zeichen \u2014 h\xF6chstens ${Jo}; der Briefrahmen ist eine Zeile der Mail, kein Dokument.`,en:`${c.en} has ${u.length} characters \u2014 at most ${Jo}; the letter frame is one line of the mail, not a document.`});let p=i==="greeting"?[Vr]:[];for(let h of om(u??""))p.includes(h)||n.push(p.length===0?{de:`${c.de} kann keine Platzhalter tragen \u2014 \u201E{{${h}}}\u201C bliebe unersetzt stehen.`,en:`${c.en} cannot carry placeholders \u2014 "{{${h}}}" would stay in the text unreplaced.`}:{de:`\u201E{{${h}}}\u201C gibt es in der ${c.de} nicht. Erlaubt: {{${Vr}}} (${Ra}).`,en:`"{{${h}}}" does not exist in the ${c.en}. Allowed: {{${Vr}}} (${Ra}).`})}}t.length>0&&n.unshift({de:`[notification/chromeMissingTranslation] ${t.map(i=>i.de).join("; ")} \u2014 der Briefrahmen gilt f\xFCr jeden Brief, in jeder Sprache.`,en:`[notification/chromeMissingTranslation] ${t.map(i=>i.en).join("; ")} \u2014 the letter frame applies to every letter, in every language.`});let r=Wk(e.senderName);return r!==void 0&&sm(r)!==r&&n.push({de:`Absendername (senderName) \u201E${r}\u201C \xFCbersteht die Kopfzeile der Mail nicht unver\xE4ndert \u2014 er ginge als \u201E${sm(r)}\u201C hinaus. Keine Anf\xFChrungszeichen, spitzen Klammern, \u201E@\u201C oder Steuerzeichen.`,en:`The sender name (senderName) "${r}" does not survive the mail header unchanged \u2014 it would go out as "${sm(r)}". No quotation marks, angle brackets, "@" or control characters.`}),n}s(XD,"chromeFindings");var eF=m.object({family:m.string()}),nF=m.object({family:m.string(),url:m.optional(m.string())}),rAe=m.object({heading:m.optional(nF),body:m.optional(nF)}),y4=m.union(m.literal("sharp"),m.literal("rounded"),m.literal("soft")),w4=m.union(m.literal("light"),m.literal("dark")),k4=m.union(m.literal("sm"),m.literal("md"),m.literal("lg"),m.literal("max")),b4=m.union(m.literal("compact"),m.literal("normal"),m.literal("spacious")),v4=m.object({primary:m.optional(m.string()),accent:m.optional(m.string()),background:m.optional(m.string()),foreground:m.optional(m.string())}),x4=m.object({heading:m.optional(eF),body:m.optional(eF)}),iAe=m.object({colors:m.optional(v4),radius:m.optional(y4),logoSize:m.optional(k4),bannerDensity:m.optional(b4),logoGround:m.optional(w4),filledHeader:m.optional(m.boolean()),websiteUrl:m.optional(m.string()),fonts:m.optional(x4)}),oAe=m.object({primaryUrl:m.union(m.null(),m.string())}),sAe=m.literal("primary"),aAe=m.object({headingUrl:m.union(m.null(),m.string()),bodyUrl:m.union(m.null(),m.string())}),lAe=m.union(m.literal("heading"),m.literal("body")),am=["logo","fontHeading","fontBody"],tF={logo:null,fontHeading:"heading",fontBody:"body"};function rF(e){let{contentType:n,size:t}=e;return n==null||!n.startsWith("image/")?{de:`Das Logo muss ein Bild sein (erhalten: \u201E${n??"unbekannt"}\u201C).`,en:`The logo must be an image (received: "${n??"unknown"}").`}:n.startsWith("image/svg")?{de:"Das Logo muss eine Rastergrafik sein (PNG, JPEG oder GIF) \u2013 E-Mail-Programme zeigen SVG nicht an.",en:"The logo must be a raster image (PNG, JPEG or GIF) \u2013 email clients do not display SVG."}:t>3e6?{de:`Das Logo ist zu gro\xDF (${t} Byte, h\xF6chstens 3000000 Byte).`,en:`The logo is too large (${t} bytes, at most 3000000 bytes).`}:null}s(rF,"logoFileProblem");var Hk="font/woff2";var S4=["Inter Variable","Azeret Mono Variable","Source Sans 3 Variable"];function iF(e){return e?.trim()?S4.some(n=>n.toLowerCase()===e.trim().toLowerCase())?{de:`\u201E${e}\u201C ist die Schrift von Plexus selbst \u2013 w\xE4hlen Sie f\xFCr eine eigene Datei einen anderen Familiennamen.`,en:`"${e}" is Plexus's own typeface \u2013 choose a different family name for your own file.`}:null:{de:"Speichern Sie zuerst die Schriftfamilie \u2013 die Datei wird unter diesem Namen eingebunden.",en:"Save the font family first \u2013 the file is registered under that name."}}s(iF,"fontFamilyProblem");var A4=["approved","rejected","withdrawn","waitlist","expired"];var lm=["admitted","rejected","withdrawn","waitlist","expired","unknown"],hAe=m.union(...A4.map(e=>m.literal(e))),gAe=m.union(...lm.map(e=>m.literal(e))),E4=["approved","rejected","waitlist"],T4=["withdrawn","expired"],$4=m.union(...E4.map(e=>m.literal(e))),R4=m.union(...T4.map(e=>m.literal(e))),yAe={active:{status:m.literal("active")},completed:{status:m.literal("completed"),outcome:$4,endedAt:m.number()},aborted:{status:m.literal("aborted"),outcome:m.optional(R4),endedAt:m.number()}};var oF=30,sF=3650;var I4=m.object({admitted:m.optional(m.number()),rejected:m.optional(m.number()),withdrawn:m.optional(m.number()),expired:m.optional(m.number()),waitlist:m.optional(m.number()),unknown:m.optional(m.number())}),SAe=I4.fields,O4=s(e=>lm.includes(e),"isClassification");function aF(e,n="tenant.retentionDays"){if(e===null||typeof e!="object"||Array.isArray(e))return[`[retention/shape] ${n} must be an object of days per classification (got ${JSON.stringify(e)}).`];let t=[];for(let[r,i]of Object.entries(e)){if(!O4(r)){t.push(`[retention/unknownClassification] ${n}.${r} is no retention classification \u2014 one of ${lm.join(", ")}.`);continue}(typeof i!="number"||!Number.isSafeInteger(i)||i<oF||i>sF)&&t.push(`[retention/days] ${n}.${r} must be a whole number of days from ${oF} to ${sF} (got ${JSON.stringify(i)}).`)}return t}s(aF,"retentionDaysFindings");var _4=["ad","ae","af","ag","ai","al","am","ao","aq","ar","as","at","au","aw","ax","az","ba","bb","bd","be","bf","bg","bh","bi","bj","bl","bm","bn","bo","bq","br","bs","bt","bv","bw","by","bz","ca","cc","cd","cf","cg","ch","ci","ck","cl","cm","cn","co","cr","cu","cv","cw","cx","cy","cz","de","dj","dk","dm","do","dz","ec","ee","eg","eh","er","es","et","fi","fj","fk","fm","fo","fr","ga","gb","gd","ge","gf","gg","gh","gi","gl","gm","gn","gp","gq","gr","gs","gt","gu","gw","gy","hk","hm","hn","hr","ht","hu","id","ie","il","im","in","io","iq","ir","is","it","je","jm","jo","jp","ke","kg","kh","ki","km","kn","kp","kr","kw","ky","kz","la","lb","lc","li","lk","lr","ls","lt","lu","lv","ly","ma","mc","md","me","mf","mg","mh","mk","ml","mm","mn","mo","mp","mq","mr","ms","mt","mu","mv","mw","mx","my","mz","na","nc","ne","nf","ng","ni","nl","no","np","nr","nu","nz","om","pa","pe","pf","pg","ph","pk","pl","pm","pn","pr","ps","pt","pw","py","qa","re","ro","rs","ru","rw","sa","sb","sc","sd","se","sg","sh","si","sj","sk","sl","sm","sn","so","sr","ss","st","sv","sx","sy","sz","tc","td","tf","tg","th","tj","tk","tl","tm","tn","to","tr","tt","tv","tw","tz","ua","ug","um","us","uy","uz","va","vc","ve","vg","vi","vn","vu","wf","ws","xk","ye","yt","za","zm","zw"],N4=new Set(_4);function dm(e){return N4.has(e)}s(dm,"isCountryCode");var Jk=["off","always","deviating"],lF={mode:"deviating",defaultCountryCode:"de"};var P4=["street","plz","ort"];function C4(e){return P4.filter(n=>!e.has(n))}s(C4,"missingInvoiceAddressParts");var D4=new Set(["0-1-select","0-n-select"]);function dF(e){return e===void 0?null:new Set(e.properties.flatMap(n=>n.addressPart!==void 0&&WO(n.addressPart)?[n.addressPart]:[]))}s(dF,"declaredAddressParts");function F4(e){return D4.has(e)}s(F4,"isSelectFieldKind");function cF(e){let n=[];for(let o of e)if(o.isNationality&&(F4(o.kind)?o.listKind!=="country"&&n.push({code:"nationality/notCountryList",fieldKey:o.key}):n.push({code:"nationality/wrongFieldKind",fieldKey:o.key})),o.isAccountEmail&&o.kind!=="email"&&n.push({code:"accountEmail/wrongFieldKind",fieldKey:o.key}),o.isContactPhone&&o.kind!=="tel"&&n.push({code:"contactPhone/wrongFieldKind",fieldKey:o.key}),o.isInvoiceAddress)if(o.addressParts===null)n.push({code:"invoiceAddress/wrongFieldKind",fieldKey:o.key});else{let a=C4(o.addressParts);a.length>0&&n.push({code:"invoiceAddress/missingPart",fieldKey:o.key,parts:a})}let t=e.filter(o=>o.isAccountEmail);if(t.length>1)for(let o of t)n.push({code:"accountEmail/multiple",fieldKey:o.key});let r=e.filter(o=>o.isContactPhone);if(r.length>1)for(let o of r)n.push({code:"contactPhone/multiple",fieldKey:o.key});let i=e.filter(o=>o.isInvoiceAddress);if(i.length>1)for(let o of i)n.push({code:"invoiceAddress/multiple",fieldKey:o.key});return n}s(cF,"fieldRoleFindings");function uF(e,n,...t){let r=e[n.code];return r(n,...t)}s(uF,"wordListElementFinding");function fF(e,n){let t=[];for(let r of n){if(e.kind==="plain"){r.countryCode!==void 0&&t.push({code:"list/countryCodeOnPlain",elementKey:r.key,countryCode:r.countryCode});continue}r.countryCode===void 0?t.push({code:"list/countryCodeMissing",elementKey:r.key}):r.countryCode!==null&&!dm(r.countryCode)&&t.push({code:"list/unknownCountryCode",elementKey:r.key,countryCode:r.countryCode})}return t}s(fF,"listElementCountryFindings");var M4={key:!0,tenant:!0,foundation:!0,source:!0,displayGroups:!0,lists:!0,roles:!0,fields:!0,roleFields:!0,contractRoleMappings:!0,templatePlaceholders:!0,searchTargets:!0,searchFilters:!0,partyResultIcons:!0,notificationLetters:!0,admission:!0,files:!0,agent:!0,deferredColumns:!0,ignoredColumns:!0},q4={slug:!0,name:!0,enabledModules:!0,permissions:!0,defaultApplicantGroupKey:!0,defaultEnrolleeRoleKey:!0,priceCriteriaFacts:!0,defaultInteressentRoleKey:!0,admissionFieldDisplayGroupKey:!0,defaultStartInProxy:!0,terms:!0,retentionDays:!0,mailLevel:!0,notificationChrome:!0,hideMailLevelNotice:!0,unassignedTaskNoticeDays:!0,magicLinkLogin:!0,externalSignIn:!0,nationalityFlag:!0,adminSeesSignatureImages:!0,signatureStamp:!0,bankImportScope:!0,branding:!0,brandingAssets:!0,partyRetention:!0},K4=new Set(["enabledMailCategories","mailEnabled"]);function j4(e){let n=s((t,r,i)=>t.filter(o=>!Object.hasOwn(r,o)&&!(i==="tenant."&&K4.has(o))).map(o=>`[config/unknownKey] ${i}${o} is not a config field of this release \u2014 a typo, or a field a newer release introduced.`),"unknown");return[...n(Object.keys(e),M4,""),...n(Object.keys(e.tenant),q4,"tenant.")]}s(j4,"unknownKeyFindings");var pF=["plain","country"],V4={"list/countryCodeMissing":s(({elementKey:e},n)=>`Element "${n}.${e}" of a country list must state countryCode (null for no state).`,"list/countryCodeMissing"),"list/countryCodeOnPlain":s(({elementKey:e},n)=>`Element "${n}.${e}" carries countryCode, but list "${n}" is not kind "country".`,"list/countryCodeOnPlain"),"list/unknownCountryCode":s(({elementKey:e,countryCode:n},t)=>`Element "${t}.${e}" has unknown countryCode ${JSON.stringify(n)}.`,"list/unknownCountryCode")},B4={"nationality/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isNationality but not a 0-1-select / 0-n-select.`,"nationality/wrongFieldKind"),"nationality/notCountryList":s(({fieldKey:e})=>`Field "${e}" is isNationality but its list is not kind "country".`,"nationality/notCountryList"),"accountEmail/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isAccountEmail but not an email field.`,"accountEmail/wrongFieldKind"),"accountEmail/multiple":s(({fieldKey:e})=>`Field "${e}" is one of several isAccountEmail fields \u2014 at most one per tenant.`,"accountEmail/multiple"),"contactPhone/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isContactPhone but not a tel field.`,"contactPhone/wrongFieldKind"),"contactPhone/multiple":s(({fieldKey:e})=>`Field "${e}" is one of several isContactPhone fields \u2014 at most one per tenant.`,"contactPhone/multiple"),"invoiceAddress/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isInvoiceAddress but not an object field.`,"invoiceAddress/wrongFieldKind"),"invoiceAddress/missingPart":s(({fieldKey:e,parts:n})=>`Field "${e}" is isInvoiceAddress but declares no property for the address part(s) ${n.join(", ")} (objectSchema.properties[].addressPart) \u2014 an invoice cannot print its address without them.`,"invoiceAddress/missingPart"),"invoiceAddress/multiple":s(({fieldKey:e})=>`Field "${e}" is one of several isInvoiceAddress fields \u2014 at most one per tenant.`,"invoiceAddress/multiple")};function U4(e){let n=B4[e.code];return n(e)}s(U4,"roleText");function G4(e){let n=[],t=e.tenant.nationalityFlag,r=typeof t=="object"&&t!==null?t:{},i=r.mode;if(Jk.includes(i)||n.push(`[nationality/flagMode] tenant.nationalityFlag.mode must be one of ${Jk.join(", ")} (got ${t===void 0?"no tenant.nationalityFlag":JSON.stringify(i??null)}).`),t!==void 0){let l=r.defaultCountryCode;(typeof l!="string"||!dm(l))&&n.push(`[nationality/defaultCountryCode] tenant.nationalityFlag.defaultCountryCode must be a lowercase ISO 3166-1 alpha-2 code (got ${JSON.stringify(l??null)}).`)}let o=new Map;for(let l of e.lists){let d=l.kind;if(!pF.includes(d)){n.push(`[list/kind] List "${l.key}" has kind ${JSON.stringify(d??null)} \u2014 one of ${pF.join(", ")}.`);continue}o.set(l.key,l.kind);for(let c of fF({key:l.key,kind:l.kind},l.elements))n.push(`[${c.code}] ${uF(V4,c,l.key)}`)}let a=cF(e.fields.map(l=>({key:l.key,kind:l.type,listKind:l.listKey===void 0?null:o.get(l.listKey)??null,isNationality:l.isNationality===!0,isAccountEmail:l.isAccountEmail===!0,isContactPhone:l.isContactPhone===!0,isInvoiceAddress:l.isInvoiceAddress===!0,addressParts:l.type==="object"?dF(l.objectSchema??{properties:[]}):null})));for(let l of a)n.push(`[${l.code}] ${U4(l)}`);return n}s(G4,"nationalityFindings");function mF(e){return $i(e)?.message.de??(e instanceof Error?e.message:String(e))}s(mF,"errorText");function yF(e,n={}){let t=[...j4(e)],r=[];try{KD(e.fields.map(b=>b.key),[])}catch(b){t.push(mF(b))}e.tenant.terms!==void 0&&t.push(...zk(e.tenant.terms)),e.tenant.retentionDays!==void 0&&t.push(...aF(e.tenant.retentionDays)),W_(e.tenant.mailLevel)?e.tenant.mailLevel==="all"&&!nm(e.tenant.enabledModules,"notifications")&&t.push('[notification/levelWithoutModule] tenant.mailLevel is "all" but the notifications module is not enabled \u2014 only sign-in and security mail would go out. Enable the module or set "loginOnly".'):t.push(`[notification/mailLevel] tenant.mailLevel must be one of ${kw.join(", ")} (got ${e.tenant.mailLevel===void 0?"nothing":JSON.stringify(e.tenant.mailLevel)}).`),"enabledMailCategories"in e.tenant&&t.push('[notification/mailCategoriesRetired] tenant.enabledMailCategories was replaced by tenant.mailLevel \u2014 "all" for every mail, "loginOnly" for sign-in mail only to families (staff mail follows personal settings).'),"mailEnabled"in e.tenant&&t.push('[notification/mailEnabledRetired] tenant.mailEnabled was replaced by tenant.mailLevel \u2014 "all" for every mail, "loginOnly" for sign-in mail only to families (staff mail follows personal settings).'),En(e.displayGroups.map(b=>b.key),"display group",t),En(e.lists.map(b=>b.key),"list",t),En(e.roles.map(b=>b.key),"role",t),En(e.fields.map(b=>b.key),"field",t),En(e.foundation.legalEntities.map(b=>b.key),"legal entity",t),En(e.foundation.units.map(b=>b.key),"unit",t),En(e.foundation.permissionGroups.map(b=>b.key),"permission group",t),"teams"in e.foundation&&t.push("foundation.teams is retired: a team is a permission group \u2014 move each team to foundation.permissionGroups (same key) and remove the block.");for(let b of e.foundation.users)"teamKeys"in b&&t.push(`User "${b.email}" carries teamKeys, retired: team membership is the user's permission-group membership.`);En(e.foundation.users.map(b=>b.key),"user",t),En((e.searchFilters??[]).map(b=>b.key),"search filter",t),En((e.searchTargets??[]).map(b=>b.objectPropertyKey===void 0?b.fieldKey:`${b.fieldKey}.${b.objectPropertyKey}`),"search target",t),En((e.partyResultIcons??[]).map(b=>b.key),"party result icon",t),En((e.templatePlaceholders??[]).map(b=>b.key),"template placeholder",t),En((e.notificationLetters??[]).map(wF),"notification letter",t),X4(e.notificationLetters??[],t),e3(e.tenant.notificationChrome,t),e.tenant.bankImportScope!==void 0&&!["sepa_only","full_statement"].includes(e.tenant.bankImportScope)&&t.push("tenant.bankImportScope must be sepa_only or full_statement."),e.tenant.hideMailLevelNotice!==void 0&&typeof e.tenant.hideMailLevelNotice!="boolean"&&t.push("tenant.hideMailLevelNotice must be true or false (the dashboard's mail-level notice)."),e.tenant.unassignedTaskNoticeDays!==void 0&&!Y_(e.tenant.unassignedTaskNoticeDays)&&t.push("tenant.unassignedTaskNoticeDays must be a whole number from 1 to 30 (days before an unassigned team task is reported); leave it out for the platform default."),typeof e.tenant.magicLinkLogin!="boolean"&&t.push("tenant.magicLinkLogin must be true or false (the login page's sign-in link option)."),typeof e.tenant.adminSeesSignatureImages!="boolean"&&t.push("tenant.adminSeesSignatureImages must be true or false (whether a school administrator sees other accounts' signature images)."),typeof e.tenant.signatureStamp!="boolean"&&t.push("tenant.signatureStamp must be true or false (whether the school offers the signature stamp at the countersignature)."),LD(e.tenant.externalSignIn)?t.push(`[auth/externalSignInRetired] tenant.externalSignIn names the retired mode "${String(e.tenant.externalSignIn.mode)}" \u2014 every sign-in link now signs in once; state { mode: "oneTimeLink" }.`):FD(e.tenant.externalSignIn)||t.push('[auth/externalSignIn] tenant.externalSignIn must be { mode: "oneTimeLink" } (how families sign in).');let i=new Set(e.displayGroups.map(b=>b.key)),o=new Set(e.lists.map(b=>b.key)),a=new Set(e.roles.map(b=>b.key)),l=new Set(e.fields.map(b=>b.key)),d=new Map(e.fields.map(b=>[b.key,b])),c=new Set(e.foundation.legalEntities.map(b=>b.key)),u=new Set(e.foundation.units.map(b=>b.key)),p=new Set(e.foundation.permissionGroups.map(b=>b.key));nm(e.tenant.enabledModules,"bewerbungsmanagement")&&e.tenant.defaultApplicantGroupKey!==void 0&&(e.foundation.permissionGroups.find(O=>O.key===e.tenant.defaultApplicantGroupKey)?.permissions.includes("bewerbungsmanagement.applications.submitOwn")||t.push(`Default applicant group "${e.tenant.defaultApplicantGroupKey}" must grant submitOwn.`));let h=e.tenant.admissionFieldDisplayGroupKey;h!==void 0&&!i.has(h)&&t.push(`tenant.admissionFieldDisplayGroupKey "${h}" names no display group of this config.`),h===void 0&&(nm(e.tenant.enabledModules,"bewerbungsmanagement")||(e.admission?.fields.length??0)>0)&&t.push("tenant.admissionFieldDisplayGroupKey is required when admissions is enabled or admission.fields declares fields: it names the display group the fields an offer creates land in."),t.push(...G4(e)),En(e.fields.flatMap(b=>(b.relationshipKinds??[]).map(O=>O.key)),"relationship kind",t);for(let b of e.fields){i.has(b.displayGroupKey)||t.push(`Field "${b.key}" references missing display group "${b.displayGroupKey}".`),W4(b,t),b.formWritable===!0&&!Bk[b.type].fieldMapTarget&&t.push(`Field "${b.key}" is formWritable, but a form cannot write a "${b.type}" field.`),b.type==="files"&&b.shareable===!0&&t.push(`[field/filesShareable] Field "${b.key}" is a files field and cannot be shareable.`),b.type==="auto-string"?Y4(b,d,t):b.autoString!==void 0&&t.push(`Non-automatic field "${b.key}" must not define autoString.`),(!Number.isFinite(b.sortOrder)||b.sortOrder<0)&&t.push(`Field "${b.key}" has invalid sortOrder "${b.sortOrder}" (must be a non-negative number).`),(b.type==="0-1-select"||b.type==="0-n-select")&&!b.listKey&&t.push(`Select field "${b.key}" must define listKey.`),b.type!=="0-1-select"&&b.type!=="0-n-select"&&b.listKey!==void 0&&t.push(`Non-select field "${b.key}" must not define listKey.`),b.listKey&&!o.has(b.listKey)&&t.push(`Field "${b.key}" references missing list "${b.listKey}".`),(b.type==="object"||b.type==="relationship")&&!b.objectSchema&&t.push(`Field "${b.key}" must define objectSchema.`),b.type!=="object"&&b.type!=="relationship"&&b.objectSchema&&t.push(`Non-object field "${b.key}" must not define objectSchema.`);for(let O of b.objectSchema?.properties??[])(O.type==="0-1-select"||O.type==="0-n-select")&&!O.listKey&&t.push(`Object select property "${b.key}.${O.key}" must define listKey.`),O.listKey&&!o.has(O.listKey)&&t.push(`Object property "${b.key}.${O.key}" references missing list "${O.listKey}".`);z4(b,t)}let y=e.tenant.priceCriteriaFacts;if(y){let b=e.fields.find(O=>O.key===y.birthDateFieldKey);(!b||b.type!=="date")&&t.push("Price criteria require a configured date field for birth dates."),a.has(y.studentRoleKey)||t.push("Price criteria require a configured Student eligibility role."),y.siblingRankSource!==void 0&&y.siblingRankSource!=="derived"&&y.siblingRankSource!=="chosen"&&t.push('Price criteria siblingRankSource must be "derived" or "chosen".');for(let O of Object.keys(y))O!=="birthDateFieldKey"&&O!=="studentRoleKey"&&O!=="siblingRankSource"&&t.push(`Unknown price criteria fact setting "${O}".`)}let k=e.tenant.defaultEnrolleeRoleKey;k&&!a.has(k)&&t.push(`Default enrollment role "${k}" does not exist.`),k&&e.roles.some(b=>b.parentRoleKey===k)&&t.push(`Default enrollment role "${k}" must be a leaf role.`);for(let b of e.roles){(typeof b.icon!="string"||b.icon.trim().length===0)&&t.push(`Role "${b.key}" must define an icon.`),b.parentRoleKey&&!a.has(b.parentRoleKey)&&t.push(`Role "${b.key}" references missing parent role "${b.parentRoleKey}".`);for(let O of b.listDisplayFieldKeys??[])l.has(O)||t.push(`Role "${b.key}" list display references missing field "${O}".`)}let w=new Map(e.roles.map(b=>[b.key,b.parentRoleKey])),v=new Map;for(let b of e.roleFields){let O=v.get(b.roleKey)??[];O.push({roleId:b.roleKey,customFieldId:b.fieldKey}),v.set(b.roleKey,O)}for(let b of e.roles)try{MD(b.key,w,v)}catch(O){t.push(mF(O))}for(let b of e.roleFields){a.has(b.roleKey)||t.push(`Role field references missing role "${b.roleKey}" for field "${b.fieldKey}".`),l.has(b.fieldKey)||t.push(`Role field references missing field "${b.fieldKey}" for role "${b.roleKey}".`);for(let O of b.targetRequirementFieldKeys??[])l.has(O)||t.push(`Role field "${b.roleKey}.${b.fieldKey}" references missing target requirement field "${O}".`)}Z4(e.contractRoleMappings??[],a,t);for(let b of e.templatePlaceholders??[])mD.test(b.key)||t.push(`Template placeholder "${b.key}" must use lower_snake_case segments, optionally separated by dots.`),b.source.kind==="customField"?cm(b.source,d,t,`Template placeholder "${b.key}"`):b.source.kind==="relationshipTargetField"&&H4(b,d,t);for(let b of e.searchTargets??[])cm(b,d,t,"Search target");for(let b of e.fields)GD(b.key)&&(b.defaultValue!==void 0||b.validations!==void 0)&&t.push(`System field "${b.key}" takes no defaultValue or validations.`);for(let b of e.lists)En(b.elements.map((O,$)=>String(O.sortOrder??($+1)*10)),`sortOrder of an element of list "${b.key}"`,t);for(let b of e.searchFilters??[])En((b.options??[]).map((O,$)=>String(O.sortOrder??($+1)*10)),`sortOrder of an option of search filter "${b.key}"`,t);for(let b of e.foundation.permissionGroups){b.grantAllCustomFields===!0&&b.customFieldPermissions!==void 0&&t.push(`Permission group "${b.key}" states both grantAllCustomFields and customFieldPermissions \u2014 one of them.`),En((b.customFieldPermissions??[]).map(O=>O.displayGroupKey),`display group of a field permission of group "${b.key}"`,t);for(let O of b.customFieldPermissions??[]){i.has(O.displayGroupKey)||t.push(`Permission group "${b.key}" grants field permissions on missing display group "${O.displayGroupKey}".`);for(let $ of O.permissions)VD.includes($)||t.push(`Permission group "${b.key}" grants unknown field permission "${$}".`)}}let A=e.tenant.partyRetention;A!==void 0&&(UD(A.days)||t.push(`tenant.partyRetention.days must be a whole number of days from 1 to ${36500} (got ${JSON.stringify(A.days)}).`),Number.isFinite(A.enabledAt)||t.push("tenant.partyRetention.enabledAt must be a timestamp (epoch ms)."),A.formerRoleKey!==void 0&&!a.has(A.formerRoleKey)&&t.push(`tenant.partyRetention references missing role "${A.formerRoleKey}".`));for(let b of e.searchFilters??[]){(b.kind==="chips"||b.kind==="select")&&(b.options?.length??0)===0&&t.push(`Search filter "${b.key}" must define options.`),(b.kind==="text"||b.kind==="numberRange")&&b.target===void 0&&t.push(`Search filter "${b.key}" must define a target field.`),b.options!==void 0&&En(b.options.map(O=>O.key),`search filter option for "${b.key}"`,t),cm(b.target,d,t,`Search filter "${b.key}"`);for(let O of b.options??[]){O.predicates.length===0&&t.push(`Search filter option "${b.key}.${O.key}" must define at least one predicate.`);for(let $ of O.predicates){if($.kind==="role"){a.has($.roleKey)||t.push(`Search filter option "${b.key}.${O.key}" references missing role "${$.roleKey}".`);continue}cm($,d,t,`Search filter option "${b.key}.${O.key}"`)}}}for(let b of e.partyResultIcons??[])J4(b,d,t);for(let b of e.foundation.legalEntities)if(b.terms!==void 0&&t.push(...zk(b.terms,`foundation.legalEntities.${b.key}.terms`)),hF(b.branding,t,`foundation.legalEntities.${b.key}.branding`),gF(b,t,`foundation.legalEntities.${b.key}`),b.signatoryUserKey!==void 0&&b.type==="school_group"&&t.push(`[config/signatoryOnGroup] Legal entity "${b.key}" is a school_group \u2014 only a Tr\xE4ger (school_operator, service_entity) declares an Unterschriftsperson.`),b.parentLegalEntityKey&&!c.has(b.parentLegalEntityKey)&&t.push(`Legal entity "${b.key}" references missing parent "${b.parentLegalEntityKey}".`),b.address!==void 0){let O=b.address,$=["street","hausnr","plz","ort"];b.type==="school_group"?t.push(`Legal entity "${b.key}" is a school_group \u2014 only a Tr\xE4ger (school_operator, service_entity) has an address.`):(typeof O!="object"||O===null||Array.isArray(O)||Object.keys(O).some(I=>!$.includes(I))||$.some(I=>typeof O[I]!="string"||(O[I]??"").trim()===""))&&t.push(`Legal entity "${b.key}" has an invalid address \u2014 expected { street, hausnr, plz, ort }, each non-empty.`)}let E=new Map;for(let b of e.foundation.units){if(b.slug!==void 0){let O=typeof b.slug=="string"?TD(b.slug):"must be a string";O!==void 0&&t.push(`Unit "${b.key}" has invalid slug "${b.slug}" (${O}).`);let $=E.get(b.slug);$!==void 0&&t.push(`Units "${$}" and "${b.key}" both declare slug "${b.slug}" (unit slugs are unique per tenant).`),E.set(b.slug,b.key)}c.has(b.legalEntityKey)||t.push(`Unit "${b.key}" references missing legal entity "${b.legalEntityKey}".`),b.parentUnitKey&&!u.has(b.parentUnitKey)&&t.push(`Unit "${b.key}" references missing parent unit "${b.parentUnitKey}".`),b.sortOrder!==void 0&&(!Number.isFinite(b.sortOrder)||b.sortOrder<0)&&t.push(`Unit "${b.key}" has invalid sortOrder "${b.sortOrder}" (must be a non-negative number).`)}let R=/^[0-9a-f]{32}:[0-9a-f]{128}$/;for(let b of e.foundation.users){p.has(b.permissionGroupKey)||t.push(`User "${b.email}" references missing permission group "${b.permissionGroupKey}".`),b.unitKey&&!u.has(b.unitKey)&&t.push(`User "${b.email}" references missing unit "${b.unitKey}".`),b.status!==void 0&&b.status!=="deactivated"&&t.push(`User "${b.email}": status must be "deactivated" or absent, not "${String(b.status)}".`);let O=[b,...b.additionalMemberships??[]];for(let I of b.additionalMemberships??[])p.has(I.permissionGroupKey)||t.push(`User "${b.email}" references missing permission group "${I.permissionGroupKey}".`),I.unitKey&&!u.has(I.unitKey)&&t.push(`User "${b.email}" references missing unit "${I.unitKey}".`);En(O.map(I=>`${I.permissionGroupKey}/${I.unitKey??""}`),`membership (permission group/unit) of user "${b.email}"`,t);for(let I of O)I.validFrom!==void 0&&I.validTo!==void 0&&I.validTo<=I.validFrom&&t.push(`User "${b.email}": membership "${I.permissionGroupKey}" ends (validTo) before it starts (validFrom).`);let $=[b.firstName,b.lastName];$.some(I=>I!==void 0)&&$.some(I=>typeof I!="string"||I.trim()==="")&&t.push(`[config/userNameIncomplete] User "${b.email}" states only part of firstName/lastName (or an empty one) \u2014 set both or neither.`);for(let I of["staging","prod"]){let G=b.passwordHashes?.[I];G!==void 0&&!R.test(G)&&t.push(`User "${b.email}" passwordHashes.${I} is not in Better Auth scrypt format "<32hex>:<128hex>".`)}}hF(e.tenant.branding,t),gF(e.tenant,t);let P=kF(e.fields.flatMap(b=>b.sourceColumns));for(let b of P)r.push(`Source column "${b}" is mapped by more than one field.`);r3(e,t);let F=n.sourceColumns===void 0||e.source===void 0?void 0:n3(e,n.sourceColumns,t);return{ok:t.length===0,errors:t,warnings:r,coverage:F}}s(yF,"validateTenantConfig");function z4(e,n){let t=new Map;for(let r of e.objectSchema?.properties??[]){let i=r.addressPart;if(i===void 0)continue;let o=`Object property "${e.key}.${r.key}"`;if(!Zy.includes(i)){n.push(`${o}: addressPart "${i}" is none of ${Zy.join(", ")}.`);continue}e.type!=="object"&&n.push(`${o}: only an object field stores an address (addressPart).`),r.type!=="string"&&n.push(`${o}: addressPart "${i}" needs a string property, not "${r.type}".`);let a=t.get(i);a!==void 0&&n.push(`${o}: addressPart "${i}" is already declared by "${e.key}.${a}".`),t.set(i,r.key)}}s(z4,"validateAddressParts");function W4(e,n){let t=e.relationshipKinds;if(t===void 0)return;if(e.type!=="relationship"){n.push(`Field "${e.key}" declares relationshipKinds, but only a relationship field carries them.`);return}let r=new Map((e.objectSchema?.properties??[]).map(i=>[i.key,i]));for(let i of t){let o=`Field "${e.key}" relationship kind "${i.key}"`;if(typeof i.key!="string"||i.key.trim()===""){n.push(`Field "${e.key}": a relationship kind needs a key.`);continue}for(let l of["de","en"])(i.label?.[l]??"").trim()===""&&n.push(`${o}: label.${l} is required \u2014 [i18n/missingTranslation] every shown text needs German and English.`);if(i.edge===null||typeof i.edge!="object"||Array.isArray(i.edge)){n.push(`${o}: edge must be an object.`);continue}i.sibling!==void 0&&i.sibling!==!0&&n.push(`${o}: sibling must be true or absent.`),i.sibling===!0&&i.mergeInto!==void 0&&n.push(`${o}: a sibling kind's edge is its identity \u2014 it cannot declare mergeInto.`);let a=t.flatMap(l=>l.mergeInto!==void 0?[l.mergeInto]:[]);if(i.sibling===!0&&a.some(l=>l in i.edge)&&n.push(`${o}: a sibling kind's edge is its identity \u2014 it cannot declare a property another kind of the field merges into.`),i.sibling===!0&&Object.keys(i.edge).length===0&&n.push(`${o}: a sibling kind's edge is its identity \u2014 an empty edge would count every edge of the field.`),i.mergeInto!==void 0){let l=r.get(i.mergeInto);l===void 0||l.type!=="0-n-select"?n.push(`${o}: mergeInto "${i.mergeInto}" must name a 0-n-select property of the field's objectSchema.`):Array.isArray(i.edge[i.mergeInto])||n.push(`${o}: mergeInto "${i.mergeInto}" must be set to a list in the edge.`)}}}s(W4,"validateRelationshipKinds");function Y4(e,n,t){if(e.autoString===void 0){t.push(`Automatic field "${e.key}" must define autoString.`);return}e.allowMultiple===!0&&t.push(`Automatic field "${e.key}" must not allow multiple values.`),e.shareable===!0&&t.push(`Automatic field "${e.key}" must not be shareable.`),e.autoString.segments.length===0&&t.push(`Automatic field "${e.key}" must define at least one segment.`),e.autoString.segments.filter(i=>i.kind==="sequence").length!==1&&t.push(`Automatic field "${e.key}" must define exactly one sequence segment.`);for(let i of e.autoString.segments)if(i.kind==="literal"&&i.value.length===0&&t.push(`Automatic field "${e.key}" has an empty literal segment.`),i.kind==="sequence"&&(i.startAt!==void 0&&(!Number.isInteger(i.startAt)||i.startAt<1)&&t.push(`Automatic field "${e.key}" sequence startAt must be an integer >= 1.`),i.minDigits!==void 0&&(!Number.isInteger(i.minDigits)||i.minDigits<0)&&t.push(`Automatic field "${e.key}" sequence minDigits must be an integer >= 0.`)),i.kind==="field"){let o=n.get(i.fieldKey);if(o===void 0){t.push(`Automatic field "${e.key}" references missing field "${i.fieldKey}".`);continue}i.objectPropertyKey!==void 0&&o.objectSchema?.properties.find(l=>l.key===i.objectPropertyKey)===void 0&&t.push(`Automatic field "${e.key}" references missing object property "${i.fieldKey}.${i.objectPropertyKey}".`)}}s(Y4,"validateAutomaticStringField");function cm(e,n,t,r){if(e===void 0)return;let i=n.get(e.fieldKey);if(i===void 0){t.push(`${r} references missing field "${e.fieldKey}".`);return}if(e.objectPropertyKey===void 0)return;(i.objectSchema?.properties.some(a=>a.key===e.objectPropertyKey)??!1)||t.push(`${r} references missing object property "${e.fieldKey}.${e.objectPropertyKey}".`)}s(cm,"validateSearchTarget");function H4(e,n,t){if(e.source.kind!=="relationshipTargetField")return;let r=`Template placeholder "${e.key}"`,i=n.get(e.source.relationshipFieldKey);if(i===void 0)t.push(`${r} references missing relationship field "${e.source.relationshipFieldKey}".`);else if(i.type!=="relationship")t.push(`${r} relationship field "${e.source.relationshipFieldKey}" must be a relationship field.`);else{for(let a of e.source.edgeFilters??[])Qk(i,a.propertyKey,t,`${r} edge filter`);e.source.selection?.sortPropertyKey!==void 0&&Qk(i,e.source.selection.sortPropertyKey,t,`${r} selection sort`)}let o=n.get(e.source.targetFieldKey);if(o===void 0){t.push(`${r} references missing target field "${e.source.targetFieldKey}".`);return}o.type==="relationship"&&t.push(`${r} target field "${e.source.targetFieldKey}" must not be a relationship field.`),e.source.targetObjectPropertyKey!==void 0&&Qk(o,e.source.targetObjectPropertyKey,t,`${r} target`)}s(H4,"validateRelationshipTemplatePlaceholder");function Qk(e,n,t,r){(e.objectSchema?.properties.some(o=>o.key===n)??!1)||t.push(`${r} references missing object property "${e.key}.${n}".`)}s(Qk,"validateObjectPropertyReference");function J4(e,n,t){let r=`Party result icon "${e.key}"`,i=n.get(e.when.fieldKey);if(i===void 0){t.push(`${r} references missing field "${e.when.fieldKey}".`);return}if(e.when.objectPropertyKey===void 0){i.type!=="boolean"&&t.push(`${r} must target a Boolean field or object property.`);return}let o=i.objectSchema?.properties.find(a=>a.key===e.when.objectPropertyKey);if(o===void 0){t.push(`${r} references missing object property "${e.when.fieldKey}.${e.when.objectPropertyKey}".`);return}o.type!=="boolean"&&t.push(`${r} must target a Boolean field or object property.`)}s(J4,"validatePartyResultIconTarget");function wF(e){return`${e.templateId}:${e.locale}:${e.scopeKey}`}s(wF,"letterIdentity");function Q4(e){return`${e.generatorKey??"*"}/${e.partyKind}/${e.roleKey}`}s(Q4,"contractRoleMappingIdentity");function Z4(e,n,t){let r=new Set;for(let i of e){let o=Q4(i),a=`Contract role mapping "${o}"`;qk.includes(i.partyKind)||t.push(`${a}: partyKind must be one of ${qk.join(", ")}.`),n.has(i.roleKey)||t.push(`${a} references missing role "${i.roleKey}".`),i.generatorKey!==void 0&&i.generatorKey.trim()===""&&t.push(`${a}: generatorKey must not be blank \u2014 omit it for the tenant default.`),r.has(o)&&t.push(`${a} is declared twice.`),r.add(o)}}s(Z4,"validateContractRoleMappings");function X4(e,n){for(let t of e){let r=`Notification letter "${wF(t)}"`;if(!im(t.locale)){n.push(`${r} declares locale "${String(t.locale)}" \u2014 letters are written in ${We.map(i=>`"${i}"`).join(" and ")} only, so no mail would ever read this deviation.`);continue}if(t.scopeKey!==tm){n.push(`${r} declares scopeKey "${t.scopeKey}" \u2014 the only scope is "${tm}" (the whole school).`);continue}if(Object.keys(t.slots).length===0){n.push(`${r} overrides no block. A deviation that deviates in nothing is not an entry \u2014 remove it.`);continue}if(!$w(t.templateId)){n.push(`${r} references no registered letter \u2014 "${t.templateId}" is not in the letter catalog.`);continue}for(let i of ZD(Tw(t.templateId),t.slots,t.locale))n.push(`${r}, block "${i.slotKey}" [${i.code}]: ${i.message.de}`)}}s(X4,"validateNotificationLetters");function e3(e,n){if(e!==void 0)for(let t of XD(e))n.push(`Notification chrome: ${t.de}`)}s(e3,"validateNotificationChrome");function hF(e,n,t){if(e===void 0)return;let r=t===void 0?n:{push:s((...p)=>n.push(...p.map(h=>`${t}: ${h}`)),"push")},i=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/,o=/^(?:rgb|rgba|hsl|hsla)\(.+\)$/i,a=s(p=>i.test(p.trim())||o.test(p.trim()),"isColor");for(let[p,h]of Object.entries(e.colors??{}))h!==void 0&&(a(h)||r.push(`Branding color "colors.${p}" has invalid value "${h}" (expected hex "#rgb"/"#rrggbb"/"#rrggbbaa" or rgb()/rgba()/hsl()/hsla()).`));let l=["sharp","rounded","soft"];e.radius!==void 0&&!l.includes(e.radius)&&r.push(`Branding radius "${e.radius}" is invalid (expected "sharp", "rounded", or "soft").`);let d=["sm","md","lg","max"];e.logoSize!==void 0&&!d.includes(e.logoSize)&&r.push(`Branding logoSize "${e.logoSize}" is invalid (expected "sm", "md", "lg", or "max").`);let c=["compact","normal","spacious"];e.bannerDensity!==void 0&&!c.includes(e.bannerDensity)&&r.push(`Branding bannerDensity "${e.bannerDensity}" is invalid (expected "compact", "normal", or "spacious").`);let u=["light","dark"];e.logoGround!==void 0&&!u.includes(e.logoGround)&&r.push(`Branding logoGround "${e.logoGround}" is invalid (expected "light" or "dark").`),e.websiteUrl!==void 0&&!e.websiteUrl.startsWith("https://")&&r.push(`Branding websiteUrl must be an https:// URL (got "${e.websiteUrl}").`);for(let p of["heading","body"]){let h=e.fonts?.[p];h!==void 0&&((typeof h.family!="string"||h.family.trim().length===0)&&r.push(`Branding font "fonts.${p}" must define a non-empty family.`),Object.hasOwn(h,"url")&&r.push(`Branding font "fonts.${p}.url" is no longer supported \u2014 the font file is uploaded (plexus-cli branding set-font --slot ${p} --file <woff2>) and config carries the family only.`))}}s(hF,"validateBranding");function gF(e,n,t="tenant"){let r=e.brandingAssets;if(r!==void 0){if(typeof r!="object"||r===null||Array.isArray(r)){n.push(`${t}.brandingAssets must be an object keyed by slot (${am.join(", ")}).`);return}for(let[i,o]of Object.entries(r)){let a=`${t}.brandingAssets.${i}`;if(!am.includes(i)){n.push(`${a}: unknown slot (expected ${am.join(", ")}).`);continue}if(typeof o!="object"||o===null){n.push(`${a}: must be { sha256, sizeBytes, mimeType }.`);continue}if("size"in o){n.push(`[config/fileRefRenamed] ${a} still names size \u2014 this bundle was exported before the file-field rename, or by a plexus-cli older than this release (now sizeBytes). Update plexus-cli, export it again (plexus-cli --env <env> config export) and re-apply.`);continue}bF.test(o.sha256??"")||n.push(`${a}: sha256 must be 64 lowercase hex chars.`),(!Number.isInteger(o.sizeBytes)||o.sizeBytes<=0)&&n.push(`${a}: sizeBytes must be a positive integer.`);let l=tF[i];if(l===null){let d=rF({contentType:o.mimeType,size:o.sizeBytes});d!==null&&n.push(`${a}: ${d.de}`)}else{o.mimeType!==Hk&&n.push(`${a}: mimeType must be "${Hk}" (got "${o.mimeType}").`);let d=iF(e.branding?.fonts?.[l]?.family);d!==null&&n.push(`${a}: [branding/fontFamilyMissing] ${t}.branding.fonts.${l}: ${d.de}`)}"path"in o&&n.push(`${a}: "path" is a CLI snapshot field \u2014 resolve it with plexus-cli config apply.`)}}}s(gF,"validateBrandingAssets");function n3(e,n,t){let{source:r}=e;r===void 0&&L("validateSourceCoverage: called without a `source` block.");let i=new Set(n),o=new Set(e.fields.flatMap(k=>k.sourceColumns)),a=new Set(e.deferredColumns.map(k=>k.column)),l=new Set(e.ignoredColumns.map(k=>k.column)),d=new Set([...o,...a,...l]),c=r.requiredColumns.filter(k=>!i.has(k)),u=n.filter(k=>!d.has(k)),p=[...o].filter(k=>!i.has(k)),h=[...a].filter(k=>!i.has(k)),y=[...l].filter(k=>!i.has(k));for(let k of c)t.push(`Required source column "${k}" is missing from ${r.primaryTable}.`);for(let k of u)t.push(`Source column "${k}" is neither mapped nor explicitly deferred/ignored.`);for(let k of p)t.push(`Mapped source column "${k}" does not exist in the source schema.`);for(let k of h)t.push(`Deferred source column "${k}" does not exist in the source schema.`);for(let k of y)t.push(`Ignored source column "${k}" does not exist in the source schema.`);return{table:r.primaryTable,availableColumns:n.length,mappedColumns:[...o].filter(k=>i.has(k)).length,deferredColumns:[...a].filter(k=>i.has(k)).length,ignoredColumns:[...l].filter(k=>i.has(k)).length,missingRequiredColumns:c,unmappedColumns:u,unknownMappedColumns:p,unknownDeferredColumns:h,unknownIgnoredColumns:y}}s(n3,"validateSourceCoverage");function En(e,n,t){for(let r of kF(e))t.push(`Duplicate ${n} key "${r}".`)}s(En,"requireUnique");function kF(e){let n=new Set,t=new Set;for(let r of e)n.has(r)&&t.add(r),n.add(r);return[...t]}s(kF,"duplicates");var bF=/^[0-9a-f]{64}$/,t3=["fileName","size"];function r3(e,n){if(!Array.isArray(e.files)){n.push('"files" is missing \u2014 declare the file library (an empty list is fine).');return}En(e.files.map(t=>t.key),"file",n);for(let t of e.files){let r=`files["${t.key}"]`;xa(t.key)||n.push(`${r}: key must match ${hk}.`);for(let o of["de","en"])(t.label?.[o]??"").trim()===""&&n.push(`${r}: label.${o} is required \u2014 [i18n/missingTranslation] every shown text needs German and English.`);let i=t3.filter(o=>o in t);if(i.length>0){n.push(`[config/fileRefRenamed] ${r} still names ${i.join(", ")} \u2014 this bundle was exported before the file-field rename, or by a plexus-cli older than this release (now filename / sizeBytes). Update plexus-cli, export it again (plexus-cli --env <env> config export) and re-apply.`);continue}if(typeof t.filename!="string")n.push(`${r}: filename is missing.`);else{let o=Wo(t.filename);o!==null&&n.push(`${r}: filename ${o}.`)}rm.includes(t.mimeType)||n.push(`${r}: mimeType "${t.mimeType}" is not allowed (${rm.join(", ")}).`),bF.test(t.sha256??"")||n.push(`${r}: sha256 must be 64 lowercase hex chars.`),(!Number.isInteger(t.sizeBytes)||t.sizeBytes<=0)&&n.push(`${r}: sizeBytes must be a positive integer.`),"path"in t&&n.push(`${r}: "path" is a CLI snapshot field \u2014 resolve it with plexus-cli config apply.`)}}s(r3,"validateFiles");var i3=new WeakMap,o3=new WeakSet;function Zk(e,n){n(e);let r=e.asOptional.bind(e);return Object.defineProperty(e,"asOptional",{value:s(()=>Zk(r(),n),"value"),enumerable:!1}),e}s(Zk,"carry");function Ia(e,n){return Zk(e,t=>i3.set(t,n))}s(Ia,"tagged");var s3="tenant teardown drains every table explicitly (config/wipe.ts)",Ve={belongsTo:s(e=>Ia(e,{kind:"belongsTo"}),"belongsTo"),owns:s(e=>Ia(e,{kind:"owns"}),"owns"),holds:s(e=>Ia(e,{kind:"holds"}),"holds"),restrict:s((e,n)=>Ia(e,n?{kind:"restrict",unindexed:n.unindexed}:{kind:"restrict"}),"restrict"),history:s(e=>Ia(e,{kind:"history"}),"history"),tenant:s(e=>Ia(e,{kind:"restrict",unindexed:s3}),"tenant"),historyOf:s(e=>Zk(e,n=>o3.add(n)),"historyOf")};var a3=m.object({street:m.string(),hausnr:m.string(),plz:m.string(),ort:m.string()}),vF=m.union(m.literal("school_operator"),m.literal("school_group"),m.literal("service_entity")),Br=vF.members.map(e=>e.value),l3={tenantId:Ve.tenant(m.id("tenants")),name:m.optional(m.string()),type:vF,parentLegalEntityId:m.optional(Ve.restrict(m.id("legal_entities"))),configKey:m.optional(m.string()),partyId:m.optional(Ve.restrict(m.id("parties"))),address:m.optional(a3),signatoryUserId:m.optional(Ve.restrict(m.id("users"))),terms:m.optional(JD)},bEe=Nt(l3).index("by_tenantId",["tenantId"]).index("by_parentLegalEntityId",["parentLegalEntityId"]).index("by_tenantId_and_configKey",["tenantId","configKey"]).index("by_partyId",["partyId"]).index("by_signatoryUserId",["signatoryUserId"]);var d3=m.union(m.literal("school"),m.literal("kindergarten"),m.literal("after_school_care"),m.literal("department"),m.literal("site"),m.literal("other")),Mt=d3.members.map(e=>e.value),SEe=m.union(m.literal("school"),m.literal("vocational"),m.literal("care"),m.literal("seminar"),m.literal("other")),AEe=m.union(m.literal("none"),m.literal("manual"),m.literal("annual_rollover")),EEe=m.union(m.literal("grade_level"),m.literal("module"),m.literal("phase"),m.literal("other")),TEe=m.union(m.literal("school_year"),m.literal("cohort"),m.literal("seminar"),m.literal("care_period"),m.literal("other")),$Ee=m.union(m.literal("planned"),m.literal("active"),m.literal("completed"),m.literal("archived")),REe=m.union(m.literal("class"),m.literal("course"),m.literal("care_group"),m.literal("seminar_group"),m.literal("mixed_age_group"),m.literal("other")),IEe=m.union(m.literal("planned"),m.literal("active"),m.literal("completed"),m.literal("cancelled")),OEe=m.union(m.literal("class_teacher"),m.literal("teacher"),m.literal("mentor"),m.literal("instructor"),m.literal("assistant"),m.literal("other")),_Ee=m.union(m.literal("units"),m.literal("unit_profiles"),m.literal("programs"),m.literal("program_stages"),m.literal("program_runs"),m.literal("learning_groups"),m.literal("enrollments"),m.literal("learning_group_staff_assignments")),NEe=m.union(m.literal("open"),m.literal("mapped"),m.literal("ignored"));function SF(e){let n=["street","hausnr","plz","ort"].filter(t=>e[t]!==void 0);if(n.length!==0){if(n.length!==4)throw new Error(`config legal-entity add: an address needs all of --street, --hausnr, --plz and --ort (got ${n.map(t=>`--${t}`).join(", ")})`);return{street:e.street,hausnr:e.hausnr,plz:e.plz,ort:e.ort}}}s(SF,"addressFrom");function AF(e){if(!Br.includes(e))throw new Error(`config legal-entity add: --type "${e}" is none of ${Br.join(", ")}`);return e}s(AF,"legalEntityType");function EF(e){if(!Mt.includes(e))throw new Error(`config unit add: --kind "${e}" is none of ${Mt.join(", ")}`);return e}s(EF,"unitKind");function TF(e,n,t){let r=e.find(i=>i.key===n.key);if(r===void 0)return e.push(n),"create";if(Ne(r)===Ne(n))return"same";throw new Error(`${t} "${n.key}" already exists with other values \u2014 decide by hand, nothing written.
11272
+ The Plexus team`}},o6={de:{...md.de,closing:null},en:{...md.en,closing:null}};var s6=/\{\{([a-zA-Z][a-zA-Z0-9_]*)\}\}/g,Jo=2e3;function om(e){let n=[];for(let t of e.matchAll(s6)){let r=t[1];n.includes(r)||n.push(r)}return n}s(om,"placeholdersIn");function QD(e){return e.slots??[]}s(QD,"slotsOf");function a6(e){return e.bodyVariants!==void 0?e.bodyVariants:[QD(e).filter(n=>n.key!==jl).map(n=>n.key)]}s(a6,"bodyVariantsOf");var l6=/:\/\/|www\.|mailto:/i;function d6(e,n){let t=`{{${n}}}`,r=0;for(;;){let i=e.indexOf(t,r);if(i===-1)return!1;let o=i===0?"":e[i-1],a=e[i+t.length]??"";if(o!==""&&!/\s/.test(o)||a!==""&&!/[\s.,;:!?)]/.test(a))return!0;r=i+t.length}}s(d6,"linkGlued");function c6(e,n){let t=e.default[n];return(typeof t!="string"||t.length===0)&&L(`notifications: slot "${e.key}" has no "${n}" text`),t}s(c6,"defaultText");function ZD(e,n,t){let r=[],i=QD(e),o=e.placeholders??[],a=o.map(u=>u.key),l=o.filter(u=>u.subjectSafe===!0).map(u=>u.key);for(let[u,p]of Object.entries(n)){let h=i.find(y=>y.key===u);if(h===void 0){r.push({slotKey:u,code:"unknownSlot",message:i.length===0?{de:`Der Brief \u201E${e.label}\u201C l\xE4sst sich nicht anpassen.`,en:`The letter "${e.label}" cannot be customized.`}:{de:`Der Baustein \u201E${u}\u201C geh\xF6rt nicht zum Brief \u201E${e.label}\u201C.`,en:`The block "${u}" does not belong to the letter "${e.label}".`}});continue}if(p.trim().length===0){r.push({slotKey:u,code:"empty",message:{de:`\u201E${h.label}\u201C darf nicht leer sein. Zum Entfernen den Baustein zur\xFCcksetzen.`,en:`"${h.label}" must not be empty. To remove it, reset the block.`}});continue}if(p.length>Jo){r.push({slotKey:u,code:"tooLong",message:{de:`\u201E${h.label}\u201C ist ${p.length} Zeichen lang, erlaubt sind ${Jo}.`,en:`"${h.label}" is ${p.length} characters long; the limit is ${Jo}.`}});continue}if(J_(e)){l6.test(p)&&r.push({slotKey:u,code:"foreignUrl",message:{de:`\u201E${h.label}\u201C enth\xE4lt eine Adresse. Der Brief \u201E${e.label}\u201C tr\xE4gt einen Anmeldeschl\xFCssel und darf keine weiteren Links enthalten.`,en:`"${h.label}" contains an address. The letter "${e.label}" carries a sign-in key and must not contain any further links.`}});for(let y of o)y.link!==!0||!d6(p,y.key)||r.push({slotKey:u,code:"linkNotStandalone",message:{de:`\u201E{{${y.key}}}\u201C (${y.label}) muss f\xFCr sich stehen \u2014 davor und dahinter nur ein Leerzeichen, ein Zeilenumbruch oder ein Satzzeichen.`,en:`"{{${y.key}}}" (${y.label}) must stand on its own \u2014 only a space, a line break or punctuation before and after it.`}})}for(let y of om(p)){if(!a.includes(y)){r.push({slotKey:u,code:"unknownPlaceholder",message:y===Vr?{de:`\u201E{{${Vr}}}\u201C (${Ra}) geh\xF6rt in die Anrede des Briefrahmens, nicht in \u201E${h.label}\u201C \u2014 dort gibt es eine neutrale Anrede, wenn kein Name bekannt ist.`,en:`"{{${Vr}}}" (${Ra}) belongs in the greeting of the letter frame, not in "${h.label}" \u2014 the greeting has a neutral form for when no name is known.`}:a.length===0?{de:`Der Brief \u201E${e.label}\u201C kennt keine Platzhalter, \u201E{{${y}}}\u201C bliebe unersetzt stehen.`,en:`The letter "${e.label}" has no placeholders; "{{${y}}}" would stay in the text unreplaced.`}:{de:`\u201E{{${y}}}\u201C gibt es in \u201E${e.label}\u201C nicht. Erlaubt: ${a.map(w=>`{{${w}}}`).join(", ")}.`,en:`"{{${y}}}" does not exist in "${e.label}". Allowed: ${a.map(w=>`{{${w}}}`).join(", ")}.`}});continue}if(u!==jl||l.includes(y))continue;let k=o.find(w=>w.key===y)?.label??y;r.push({slotKey:u,code:"subjectUnsupported",message:{de:`\u201E{{${y}}}\u201C (${k}) l\xE4sst sich im Betreff nicht einsetzen \u2014 der Wert entsteht erst beim Versand. `+(l.length===0?"In diesem Brief kann der Betreff keine Platzhalter tragen.":`Im Betreff m\xF6glich: ${l.map(w=>`{{${w}}}`).join(", ")}.`),en:`"{{${y}}}" (${k}) cannot be used in the subject \u2014 the value only exists when the mail is sent. `+(l.length===0?"In this letter the subject cannot carry placeholders.":`Possible in the subject: ${l.map(w=>`{{${w}}}`).join(", ")}.`)}})}}let d=s(u=>n[u]??u6(i,u,t),"textOf"),c=a6(e);for(let u of o){if(u.required!==!0)continue;let p=c.filter(w=>!om(w.map(d).join(`
11273
+ `)).includes(u.key));if(p.length===0)continue;let h=s((w,v)=>w.map(A=>v(i.find(E=>E.key===A)?.label??A)).join(" + "),"variantLabel"),y=c.length===1?"":` Er fehlt in der Fassung aus ${p.map(w=>h(w,v=>`\u201E${v}\u201C`)).join(" und in der aus ")}.`,k=c.length===1?"":` It is missing in the version made of ${p.map(w=>h(w,v=>`"${v}"`)).join(" and in the one made of ")}.`;r.push({slotKey:u.key,code:"missingRequired",message:{de:`Ohne \u201E{{${u.key}}}\u201C (${u.label}) funktioniert der Brief \u201E${e.label}\u201C nicht \u2014 der Platzhalter muss im Text stehen, nicht nur im Betreff.`+y,en:`Without "{{${u.key}}}" (${u.label}) the letter "${e.label}" does not work \u2014 the placeholder must be in the text, not only in the subject.`+k}})}return r}s(ZD,"validateOverride");function u6(e,n,t){let r=e.find(i=>i.key===n);return r===void 0?"":c6(r,t)}s(u6,"defaultTextOf");function Wk(e){let n=e?.trim();return n===void 0||n.length===0?void 0:n}s(Wk,"normalizeChromeText");var Qo=s(e=>String.fromCharCode(e),"cp"),f6=new RegExp(`[${Qo(0)}-${Qo(31)}${Qo(127)}]`,"g"),p6=new RegExp(`[${Qo(8234)}-${Qo(8238)}${Qo(8294)}-${Qo(8297)}]`,"g");var m6=200;function h6(e,n=m6){return e.replace(f6," ").replace(p6,"").replace(/\s+/g," ").trim().slice(0,n)}s(h6,"sanitizeHeaderValue");function sm(e){return h6(e.replace(/["<>@]/g,""),100)}s(sm,"sanitizeDisplayName");var Yk={de:{de:"Deutsch",en:"German"},en:{de:"Englisch",en:"English"}},g6={greeting:{de:"Anrede",en:"Greeting"},closing:{de:"Gru\xDFformel",en:"Closing"}};function XD(e){let n=[],t=[];for(let i of["greeting","closing"]){let o=e[i];if(o===void 0)continue;let a=g6[i],l=Rn(o);l!=="not-localized"&&l.length>0&&l.length<We.length&&t.push({de:`${a.de} fehlt auf ${l.map(d=>Yk[d].de).join(" und ")}`,en:`${a.en} is missing in ${l.map(d=>Yk[d].en).join(" and ")}`});for(let d of We){let c=hw(h=>`${a[h]} (${Yk[d][h]})`),u=Wk(o[d]);u!==void 0&&u.length>Jo&&n.push({de:`${c.de} hat ${u.length} Zeichen \u2014 h\xF6chstens ${Jo}; der Briefrahmen ist eine Zeile der Mail, kein Dokument.`,en:`${c.en} has ${u.length} characters \u2014 at most ${Jo}; the letter frame is one line of the mail, not a document.`});let p=i==="greeting"?[Vr]:[];for(let h of om(u??""))p.includes(h)||n.push(p.length===0?{de:`${c.de} kann keine Platzhalter tragen \u2014 \u201E{{${h}}}\u201C bliebe unersetzt stehen.`,en:`${c.en} cannot carry placeholders \u2014 "{{${h}}}" would stay in the text unreplaced.`}:{de:`\u201E{{${h}}}\u201C gibt es in der ${c.de} nicht. Erlaubt: {{${Vr}}} (${Ra}).`,en:`"{{${h}}}" does not exist in the ${c.en}. Allowed: {{${Vr}}} (${Ra}).`})}}t.length>0&&n.unshift({de:`[notification/chromeMissingTranslation] ${t.map(i=>i.de).join("; ")} \u2014 der Briefrahmen gilt f\xFCr jeden Brief, in jeder Sprache.`,en:`[notification/chromeMissingTranslation] ${t.map(i=>i.en).join("; ")} \u2014 the letter frame applies to every letter, in every language.`});let r=Wk(e.senderName);return r!==void 0&&sm(r)!==r&&n.push({de:`Absendername (senderName) \u201E${r}\u201C \xFCbersteht die Kopfzeile der Mail nicht unver\xE4ndert \u2014 er ginge als \u201E${sm(r)}\u201C hinaus. Keine Anf\xFChrungszeichen, spitzen Klammern, \u201E@\u201C oder Steuerzeichen.`,en:`The sender name (senderName) "${r}" does not survive the mail header unchanged \u2014 it would go out as "${sm(r)}". No quotation marks, angle brackets, "@" or control characters.`}),n}s(XD,"chromeFindings");var eF=m.object({family:m.string()}),nF=m.object({family:m.string(),url:m.optional(m.string())}),rAe=m.object({heading:m.optional(nF),body:m.optional(nF)}),y6=m.union(m.literal("sharp"),m.literal("rounded"),m.literal("soft")),w6=m.union(m.literal("light"),m.literal("dark")),k6=m.union(m.literal("sm"),m.literal("md"),m.literal("lg"),m.literal("max")),b6=m.union(m.literal("compact"),m.literal("normal"),m.literal("spacious")),v6=m.object({primary:m.optional(m.string()),accent:m.optional(m.string()),background:m.optional(m.string()),foreground:m.optional(m.string())}),x6=m.object({heading:m.optional(eF),body:m.optional(eF)}),iAe=m.object({colors:m.optional(v6),radius:m.optional(y6),logoSize:m.optional(k6),bannerDensity:m.optional(b6),logoGround:m.optional(w6),filledHeader:m.optional(m.boolean()),websiteUrl:m.optional(m.string()),fonts:m.optional(x6)}),oAe=m.object({primaryUrl:m.union(m.null(),m.string())}),sAe=m.literal("primary"),aAe=m.object({headingUrl:m.union(m.null(),m.string()),bodyUrl:m.union(m.null(),m.string())}),lAe=m.union(m.literal("heading"),m.literal("body")),am=["logo","fontHeading","fontBody"],tF={logo:null,fontHeading:"heading",fontBody:"body"};function rF(e){let{contentType:n,size:t}=e;return n==null||!n.startsWith("image/")?{de:`Das Logo muss ein Bild sein (erhalten: \u201E${n??"unbekannt"}\u201C).`,en:`The logo must be an image (received: "${n??"unknown"}").`}:n.startsWith("image/svg")?{de:"Das Logo muss eine Rastergrafik sein (PNG, JPEG oder GIF) \u2013 E-Mail-Programme zeigen SVG nicht an.",en:"The logo must be a raster image (PNG, JPEG or GIF) \u2013 email clients do not display SVG."}:t>3e6?{de:`Das Logo ist zu gro\xDF (${t} Byte, h\xF6chstens 3000000 Byte).`,en:`The logo is too large (${t} bytes, at most 3000000 bytes).`}:null}s(rF,"logoFileProblem");var Hk="font/woff2";var S6=["Inter Variable","Azeret Mono Variable","Source Sans 3 Variable"];function iF(e){return e?.trim()?S6.some(n=>n.toLowerCase()===e.trim().toLowerCase())?{de:`\u201E${e}\u201C ist die Schrift von Plexus selbst \u2013 w\xE4hlen Sie f\xFCr eine eigene Datei einen anderen Familiennamen.`,en:`"${e}" is Plexus's own typeface \u2013 choose a different family name for your own file.`}:null:{de:"Speichern Sie zuerst die Schriftfamilie \u2013 die Datei wird unter diesem Namen eingebunden.",en:"Save the font family first \u2013 the file is registered under that name."}}s(iF,"fontFamilyProblem");var A6=["approved","rejected","withdrawn","waitlist","expired"];var lm=["admitted","rejected","withdrawn","waitlist","expired","unknown"],hAe=m.union(...A6.map(e=>m.literal(e))),gAe=m.union(...lm.map(e=>m.literal(e))),E6=["approved","rejected","waitlist"],T6=["withdrawn","expired"],$6=m.union(...E6.map(e=>m.literal(e))),R6=m.union(...T6.map(e=>m.literal(e))),yAe={active:{status:m.literal("active")},completed:{status:m.literal("completed"),outcome:$6,endedAt:m.number()},aborted:{status:m.literal("aborted"),outcome:m.optional(R6),endedAt:m.number()}};var oF=30,sF=3650;var I6=m.object({admitted:m.optional(m.number()),rejected:m.optional(m.number()),withdrawn:m.optional(m.number()),expired:m.optional(m.number()),waitlist:m.optional(m.number()),unknown:m.optional(m.number())}),SAe=I6.fields,O6=s(e=>lm.includes(e),"isClassification");function aF(e,n="tenant.retentionDays"){if(e===null||typeof e!="object"||Array.isArray(e))return[`[retention/shape] ${n} must be an object of days per classification (got ${JSON.stringify(e)}).`];let t=[];for(let[r,i]of Object.entries(e)){if(!O6(r)){t.push(`[retention/unknownClassification] ${n}.${r} is no retention classification \u2014 one of ${lm.join(", ")}.`);continue}(typeof i!="number"||!Number.isSafeInteger(i)||i<oF||i>sF)&&t.push(`[retention/days] ${n}.${r} must be a whole number of days from ${oF} to ${sF} (got ${JSON.stringify(i)}).`)}return t}s(aF,"retentionDaysFindings");var _6=["ad","ae","af","ag","ai","al","am","ao","aq","ar","as","at","au","aw","ax","az","ba","bb","bd","be","bf","bg","bh","bi","bj","bl","bm","bn","bo","bq","br","bs","bt","bv","bw","by","bz","ca","cc","cd","cf","cg","ch","ci","ck","cl","cm","cn","co","cr","cu","cv","cw","cx","cy","cz","de","dj","dk","dm","do","dz","ec","ee","eg","eh","er","es","et","fi","fj","fk","fm","fo","fr","ga","gb","gd","ge","gf","gg","gh","gi","gl","gm","gn","gp","gq","gr","gs","gt","gu","gw","gy","hk","hm","hn","hr","ht","hu","id","ie","il","im","in","io","iq","ir","is","it","je","jm","jo","jp","ke","kg","kh","ki","km","kn","kp","kr","kw","ky","kz","la","lb","lc","li","lk","lr","ls","lt","lu","lv","ly","ma","mc","md","me","mf","mg","mh","mk","ml","mm","mn","mo","mp","mq","mr","ms","mt","mu","mv","mw","mx","my","mz","na","nc","ne","nf","ng","ni","nl","no","np","nr","nu","nz","om","pa","pe","pf","pg","ph","pk","pl","pm","pn","pr","ps","pt","pw","py","qa","re","ro","rs","ru","rw","sa","sb","sc","sd","se","sg","sh","si","sj","sk","sl","sm","sn","so","sr","ss","st","sv","sx","sy","sz","tc","td","tf","tg","th","tj","tk","tl","tm","tn","to","tr","tt","tv","tw","tz","ua","ug","um","us","uy","uz","va","vc","ve","vg","vi","vn","vu","wf","ws","xk","ye","yt","za","zm","zw"],N6=new Set(_6);function dm(e){return N6.has(e)}s(dm,"isCountryCode");var Jk=["off","always","deviating"],lF={mode:"deviating",defaultCountryCode:"de"};var P6=["street","plz","ort"];function C6(e){return P6.filter(n=>!e.has(n))}s(C6,"missingInvoiceAddressParts");var D6=new Set(["0-1-select","0-n-select"]);function dF(e){return e===void 0?null:new Set(e.properties.flatMap(n=>n.addressPart!==void 0&&WO(n.addressPart)?[n.addressPart]:[]))}s(dF,"declaredAddressParts");function F6(e){return D6.has(e)}s(F6,"isSelectFieldKind");function cF(e){let n=[];for(let o of e)if(o.isNationality&&(F6(o.kind)?o.listKind!=="country"&&n.push({code:"nationality/notCountryList",fieldKey:o.key}):n.push({code:"nationality/wrongFieldKind",fieldKey:o.key})),o.isAccountEmail&&o.kind!=="email"&&n.push({code:"accountEmail/wrongFieldKind",fieldKey:o.key}),o.isContactPhone&&o.kind!=="tel"&&n.push({code:"contactPhone/wrongFieldKind",fieldKey:o.key}),o.isInvoiceAddress)if(o.addressParts===null)n.push({code:"invoiceAddress/wrongFieldKind",fieldKey:o.key});else{let a=C6(o.addressParts);a.length>0&&n.push({code:"invoiceAddress/missingPart",fieldKey:o.key,parts:a})}let t=e.filter(o=>o.isAccountEmail);if(t.length>1)for(let o of t)n.push({code:"accountEmail/multiple",fieldKey:o.key});let r=e.filter(o=>o.isContactPhone);if(r.length>1)for(let o of r)n.push({code:"contactPhone/multiple",fieldKey:o.key});let i=e.filter(o=>o.isInvoiceAddress);if(i.length>1)for(let o of i)n.push({code:"invoiceAddress/multiple",fieldKey:o.key});return n}s(cF,"fieldRoleFindings");function uF(e,n,...t){let r=e[n.code];return r(n,...t)}s(uF,"wordListElementFinding");function fF(e,n){let t=[];for(let r of n){if(e.kind==="plain"){r.countryCode!==void 0&&t.push({code:"list/countryCodeOnPlain",elementKey:r.key,countryCode:r.countryCode});continue}r.countryCode===void 0?t.push({code:"list/countryCodeMissing",elementKey:r.key}):r.countryCode!==null&&!dm(r.countryCode)&&t.push({code:"list/unknownCountryCode",elementKey:r.key,countryCode:r.countryCode})}return t}s(fF,"listElementCountryFindings");var M6={key:!0,tenant:!0,foundation:!0,source:!0,displayGroups:!0,lists:!0,roles:!0,fields:!0,roleFields:!0,contractRoleMappings:!0,templatePlaceholders:!0,searchTargets:!0,searchFilters:!0,partyResultIcons:!0,notificationLetters:!0,admission:!0,files:!0,agent:!0,deferredColumns:!0,ignoredColumns:!0},q6={slug:!0,name:!0,enabledModules:!0,permissions:!0,defaultApplicantGroupKey:!0,defaultEnrolleeRoleKey:!0,priceCriteriaFacts:!0,defaultInteressentRoleKey:!0,admissionFieldDisplayGroupKey:!0,defaultStartInProxy:!0,terms:!0,retentionDays:!0,mailLevel:!0,notificationChrome:!0,hideMailLevelNotice:!0,unassignedTaskNoticeDays:!0,magicLinkLogin:!0,externalSignIn:!0,nationalityFlag:!0,adminSeesSignatureImages:!0,signatureStamp:!0,bankImportScope:!0,branding:!0,brandingAssets:!0,partyRetention:!0},K6=new Set(["enabledMailCategories","mailEnabled"]);function j6(e){let n=s((t,r,i)=>t.filter(o=>!Object.hasOwn(r,o)&&!(i==="tenant."&&K6.has(o))).map(o=>`[config/unknownKey] ${i}${o} is not a config field of this release \u2014 a typo, or a field a newer release introduced.`),"unknown");return[...n(Object.keys(e),M6,""),...n(Object.keys(e.tenant),q6,"tenant.")]}s(j6,"unknownKeyFindings");var pF=["plain","country"],V6={"list/countryCodeMissing":s(({elementKey:e},n)=>`Element "${n}.${e}" of a country list must state countryCode (null for no state).`,"list/countryCodeMissing"),"list/countryCodeOnPlain":s(({elementKey:e},n)=>`Element "${n}.${e}" carries countryCode, but list "${n}" is not kind "country".`,"list/countryCodeOnPlain"),"list/unknownCountryCode":s(({elementKey:e,countryCode:n},t)=>`Element "${t}.${e}" has unknown countryCode ${JSON.stringify(n)}.`,"list/unknownCountryCode")},B6={"nationality/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isNationality but not a 0-1-select / 0-n-select.`,"nationality/wrongFieldKind"),"nationality/notCountryList":s(({fieldKey:e})=>`Field "${e}" is isNationality but its list is not kind "country".`,"nationality/notCountryList"),"accountEmail/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isAccountEmail but not an email field.`,"accountEmail/wrongFieldKind"),"accountEmail/multiple":s(({fieldKey:e})=>`Field "${e}" is one of several isAccountEmail fields \u2014 at most one per tenant.`,"accountEmail/multiple"),"contactPhone/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isContactPhone but not a tel field.`,"contactPhone/wrongFieldKind"),"contactPhone/multiple":s(({fieldKey:e})=>`Field "${e}" is one of several isContactPhone fields \u2014 at most one per tenant.`,"contactPhone/multiple"),"invoiceAddress/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isInvoiceAddress but not an object field.`,"invoiceAddress/wrongFieldKind"),"invoiceAddress/missingPart":s(({fieldKey:e,parts:n})=>`Field "${e}" is isInvoiceAddress but declares no property for the address part(s) ${n.join(", ")} (objectSchema.properties[].addressPart) \u2014 an invoice cannot print its address without them.`,"invoiceAddress/missingPart"),"invoiceAddress/multiple":s(({fieldKey:e})=>`Field "${e}" is one of several isInvoiceAddress fields \u2014 at most one per tenant.`,"invoiceAddress/multiple")};function U6(e){let n=B6[e.code];return n(e)}s(U6,"roleText");function G6(e){let n=[],t=e.tenant.nationalityFlag,r=typeof t=="object"&&t!==null?t:{},i=r.mode;if(Jk.includes(i)||n.push(`[nationality/flagMode] tenant.nationalityFlag.mode must be one of ${Jk.join(", ")} (got ${t===void 0?"no tenant.nationalityFlag":JSON.stringify(i??null)}).`),t!==void 0){let l=r.defaultCountryCode;(typeof l!="string"||!dm(l))&&n.push(`[nationality/defaultCountryCode] tenant.nationalityFlag.defaultCountryCode must be a lowercase ISO 3166-1 alpha-2 code (got ${JSON.stringify(l??null)}).`)}let o=new Map;for(let l of e.lists){let d=l.kind;if(!pF.includes(d)){n.push(`[list/kind] List "${l.key}" has kind ${JSON.stringify(d??null)} \u2014 one of ${pF.join(", ")}.`);continue}o.set(l.key,l.kind);for(let c of fF({key:l.key,kind:l.kind},l.elements))n.push(`[${c.code}] ${uF(V6,c,l.key)}`)}let a=cF(e.fields.map(l=>({key:l.key,kind:l.type,listKind:l.listKey===void 0?null:o.get(l.listKey)??null,isNationality:l.isNationality===!0,isAccountEmail:l.isAccountEmail===!0,isContactPhone:l.isContactPhone===!0,isInvoiceAddress:l.isInvoiceAddress===!0,addressParts:l.type==="object"?dF(l.objectSchema??{properties:[]}):null})));for(let l of a)n.push(`[${l.code}] ${U6(l)}`);return n}s(G6,"nationalityFindings");function mF(e){return $i(e)?.message.de??(e instanceof Error?e.message:String(e))}s(mF,"errorText");function yF(e,n={}){let t=[...j6(e)],r=[];try{KD(e.fields.map(b=>b.key),[])}catch(b){t.push(mF(b))}e.tenant.terms!==void 0&&t.push(...zk(e.tenant.terms)),e.tenant.retentionDays!==void 0&&t.push(...aF(e.tenant.retentionDays)),W_(e.tenant.mailLevel)?e.tenant.mailLevel==="all"&&!nm(e.tenant.enabledModules,"notifications")&&t.push('[notification/levelWithoutModule] tenant.mailLevel is "all" but the notifications module is not enabled \u2014 only sign-in and security mail would go out. Enable the module or set "loginOnly".'):t.push(`[notification/mailLevel] tenant.mailLevel must be one of ${kw.join(", ")} (got ${e.tenant.mailLevel===void 0?"nothing":JSON.stringify(e.tenant.mailLevel)}).`),"enabledMailCategories"in e.tenant&&t.push('[notification/mailCategoriesRetired] tenant.enabledMailCategories was replaced by tenant.mailLevel \u2014 "all" for every mail, "loginOnly" for sign-in mail only to families (staff mail follows personal settings).'),"mailEnabled"in e.tenant&&t.push('[notification/mailEnabledRetired] tenant.mailEnabled was replaced by tenant.mailLevel \u2014 "all" for every mail, "loginOnly" for sign-in mail only to families (staff mail follows personal settings).'),En(e.displayGroups.map(b=>b.key),"display group",t),En(e.lists.map(b=>b.key),"list",t),En(e.roles.map(b=>b.key),"role",t),En(e.fields.map(b=>b.key),"field",t),En(e.foundation.legalEntities.map(b=>b.key),"legal entity",t),En(e.foundation.units.map(b=>b.key),"unit",t),En(e.foundation.permissionGroups.map(b=>b.key),"permission group",t),"teams"in e.foundation&&t.push("foundation.teams is retired: a team is a permission group \u2014 move each team to foundation.permissionGroups (same key) and remove the block.");for(let b of e.foundation.users)"teamKeys"in b&&t.push(`User "${b.email}" carries teamKeys, retired: team membership is the user's permission-group membership.`);En(e.foundation.users.map(b=>b.key),"user",t),En((e.searchFilters??[]).map(b=>b.key),"search filter",t),En((e.searchTargets??[]).map(b=>b.objectPropertyKey===void 0?b.fieldKey:`${b.fieldKey}.${b.objectPropertyKey}`),"search target",t),En((e.partyResultIcons??[]).map(b=>b.key),"party result icon",t),En((e.templatePlaceholders??[]).map(b=>b.key),"template placeholder",t),En((e.notificationLetters??[]).map(wF),"notification letter",t),X6(e.notificationLetters??[],t),e3(e.tenant.notificationChrome,t),e.tenant.bankImportScope!==void 0&&!["sepa_only","full_statement"].includes(e.tenant.bankImportScope)&&t.push("tenant.bankImportScope must be sepa_only or full_statement."),e.tenant.hideMailLevelNotice!==void 0&&typeof e.tenant.hideMailLevelNotice!="boolean"&&t.push("tenant.hideMailLevelNotice must be true or false (the dashboard's mail-level notice)."),e.tenant.unassignedTaskNoticeDays!==void 0&&!Y_(e.tenant.unassignedTaskNoticeDays)&&t.push("tenant.unassignedTaskNoticeDays must be a whole number from 1 to 30 (days before an unassigned team task is reported); leave it out for the platform default."),typeof e.tenant.magicLinkLogin!="boolean"&&t.push("tenant.magicLinkLogin must be true or false (the login page's sign-in link option)."),typeof e.tenant.adminSeesSignatureImages!="boolean"&&t.push("tenant.adminSeesSignatureImages must be true or false (whether a school administrator sees other accounts' signature images)."),typeof e.tenant.signatureStamp!="boolean"&&t.push("tenant.signatureStamp must be true or false (whether the school offers the signature stamp at the countersignature)."),LD(e.tenant.externalSignIn)?t.push(`[auth/externalSignInRetired] tenant.externalSignIn names the retired mode "${String(e.tenant.externalSignIn.mode)}" \u2014 every sign-in link now signs in once; state { mode: "oneTimeLink" }.`):FD(e.tenant.externalSignIn)||t.push('[auth/externalSignIn] tenant.externalSignIn must be { mode: "oneTimeLink" } (how families sign in).');let i=new Set(e.displayGroups.map(b=>b.key)),o=new Set(e.lists.map(b=>b.key)),a=new Set(e.roles.map(b=>b.key)),l=new Set(e.fields.map(b=>b.key)),d=new Map(e.fields.map(b=>[b.key,b])),c=new Set(e.foundation.legalEntities.map(b=>b.key)),u=new Set(e.foundation.units.map(b=>b.key)),p=new Set(e.foundation.permissionGroups.map(b=>b.key));nm(e.tenant.enabledModules,"bewerbungsmanagement")&&e.tenant.defaultApplicantGroupKey!==void 0&&(e.foundation.permissionGroups.find(O=>O.key===e.tenant.defaultApplicantGroupKey)?.permissions.includes("bewerbungsmanagement.applications.submitOwn")||t.push(`Default applicant group "${e.tenant.defaultApplicantGroupKey}" must grant submitOwn.`));let h=e.tenant.admissionFieldDisplayGroupKey;h!==void 0&&!i.has(h)&&t.push(`tenant.admissionFieldDisplayGroupKey "${h}" names no display group of this config.`),h===void 0&&(nm(e.tenant.enabledModules,"bewerbungsmanagement")||(e.admission?.fields.length??0)>0)&&t.push("tenant.admissionFieldDisplayGroupKey is required when admissions is enabled or admission.fields declares fields: it names the display group the fields an offer creates land in."),t.push(...G6(e)),En(e.fields.flatMap(b=>(b.relationshipKinds??[]).map(O=>O.key)),"relationship kind",t);for(let b of e.fields){i.has(b.displayGroupKey)||t.push(`Field "${b.key}" references missing display group "${b.displayGroupKey}".`),W6(b,t),b.formWritable===!0&&!Bk[b.type].fieldMapTarget&&t.push(`Field "${b.key}" is formWritable, but a form cannot write a "${b.type}" field.`),b.type==="files"&&b.shareable===!0&&t.push(`[field/filesShareable] Field "${b.key}" is a files field and cannot be shareable.`),b.type==="auto-string"?Y6(b,d,t):b.autoString!==void 0&&t.push(`Non-automatic field "${b.key}" must not define autoString.`),(!Number.isFinite(b.sortOrder)||b.sortOrder<0)&&t.push(`Field "${b.key}" has invalid sortOrder "${b.sortOrder}" (must be a non-negative number).`),(b.type==="0-1-select"||b.type==="0-n-select")&&!b.listKey&&t.push(`Select field "${b.key}" must define listKey.`),b.type!=="0-1-select"&&b.type!=="0-n-select"&&b.listKey!==void 0&&t.push(`Non-select field "${b.key}" must not define listKey.`),b.listKey&&!o.has(b.listKey)&&t.push(`Field "${b.key}" references missing list "${b.listKey}".`),(b.type==="object"||b.type==="relationship")&&!b.objectSchema&&t.push(`Field "${b.key}" must define objectSchema.`),b.type!=="object"&&b.type!=="relationship"&&b.objectSchema&&t.push(`Non-object field "${b.key}" must not define objectSchema.`);for(let O of b.objectSchema?.properties??[])(O.type==="0-1-select"||O.type==="0-n-select")&&!O.listKey&&t.push(`Object select property "${b.key}.${O.key}" must define listKey.`),O.listKey&&!o.has(O.listKey)&&t.push(`Object property "${b.key}.${O.key}" references missing list "${O.listKey}".`);z6(b,t)}let y=e.tenant.priceCriteriaFacts;if(y){let b=e.fields.find(O=>O.key===y.birthDateFieldKey);(!b||b.type!=="date")&&t.push("Price criteria require a configured date field for birth dates."),a.has(y.studentRoleKey)||t.push("Price criteria require a configured Student eligibility role."),y.siblingRankSource!==void 0&&y.siblingRankSource!=="derived"&&y.siblingRankSource!=="chosen"&&t.push('Price criteria siblingRankSource must be "derived" or "chosen".');for(let O of Object.keys(y))O!=="birthDateFieldKey"&&O!=="studentRoleKey"&&O!=="siblingRankSource"&&t.push(`Unknown price criteria fact setting "${O}".`)}let k=e.tenant.defaultEnrolleeRoleKey;k&&!a.has(k)&&t.push(`Default enrollment role "${k}" does not exist.`),k&&e.roles.some(b=>b.parentRoleKey===k)&&t.push(`Default enrollment role "${k}" must be a leaf role.`);for(let b of e.roles){(typeof b.icon!="string"||b.icon.trim().length===0)&&t.push(`Role "${b.key}" must define an icon.`),b.parentRoleKey&&!a.has(b.parentRoleKey)&&t.push(`Role "${b.key}" references missing parent role "${b.parentRoleKey}".`);for(let O of b.listDisplayFieldKeys??[])l.has(O)||t.push(`Role "${b.key}" list display references missing field "${O}".`)}let w=new Map(e.roles.map(b=>[b.key,b.parentRoleKey])),v=new Map;for(let b of e.roleFields){let O=v.get(b.roleKey)??[];O.push({roleId:b.roleKey,customFieldId:b.fieldKey}),v.set(b.roleKey,O)}for(let b of e.roles)try{MD(b.key,w,v)}catch(O){t.push(mF(O))}for(let b of e.roleFields){a.has(b.roleKey)||t.push(`Role field references missing role "${b.roleKey}" for field "${b.fieldKey}".`),l.has(b.fieldKey)||t.push(`Role field references missing field "${b.fieldKey}" for role "${b.roleKey}".`);for(let O of b.targetRequirementFieldKeys??[])l.has(O)||t.push(`Role field "${b.roleKey}.${b.fieldKey}" references missing target requirement field "${O}".`)}Z6(e.contractRoleMappings??[],a,t);for(let b of e.templatePlaceholders??[])mD.test(b.key)||t.push(`Template placeholder "${b.key}" must use lower_snake_case segments, optionally separated by dots.`),b.source.kind==="customField"?cm(b.source,d,t,`Template placeholder "${b.key}"`):b.source.kind==="relationshipTargetField"&&H6(b,d,t);for(let b of e.searchTargets??[])cm(b,d,t,"Search target");for(let b of e.fields)GD(b.key)&&(b.defaultValue!==void 0||b.validations!==void 0)&&t.push(`System field "${b.key}" takes no defaultValue or validations.`);for(let b of e.lists)En(b.elements.map((O,$)=>String(O.sortOrder??($+1)*10)),`sortOrder of an element of list "${b.key}"`,t);for(let b of e.searchFilters??[])En((b.options??[]).map((O,$)=>String(O.sortOrder??($+1)*10)),`sortOrder of an option of search filter "${b.key}"`,t);for(let b of e.foundation.permissionGroups){b.grantAllCustomFields===!0&&b.customFieldPermissions!==void 0&&t.push(`Permission group "${b.key}" states both grantAllCustomFields and customFieldPermissions \u2014 one of them.`),En((b.customFieldPermissions??[]).map(O=>O.displayGroupKey),`display group of a field permission of group "${b.key}"`,t);for(let O of b.customFieldPermissions??[]){i.has(O.displayGroupKey)||t.push(`Permission group "${b.key}" grants field permissions on missing display group "${O.displayGroupKey}".`);for(let $ of O.permissions)VD.includes($)||t.push(`Permission group "${b.key}" grants unknown field permission "${$}".`)}}let A=e.tenant.partyRetention;A!==void 0&&(UD(A.days)||t.push(`tenant.partyRetention.days must be a whole number of days from 1 to ${36500} (got ${JSON.stringify(A.days)}).`),Number.isFinite(A.enabledAt)||t.push("tenant.partyRetention.enabledAt must be a timestamp (epoch ms)."),A.formerRoleKey!==void 0&&!a.has(A.formerRoleKey)&&t.push(`tenant.partyRetention references missing role "${A.formerRoleKey}".`));for(let b of e.searchFilters??[]){(b.kind==="chips"||b.kind==="select")&&(b.options?.length??0)===0&&t.push(`Search filter "${b.key}" must define options.`),(b.kind==="text"||b.kind==="numberRange")&&b.target===void 0&&t.push(`Search filter "${b.key}" must define a target field.`),b.options!==void 0&&En(b.options.map(O=>O.key),`search filter option for "${b.key}"`,t),cm(b.target,d,t,`Search filter "${b.key}"`);for(let O of b.options??[]){O.predicates.length===0&&t.push(`Search filter option "${b.key}.${O.key}" must define at least one predicate.`);for(let $ of O.predicates){if($.kind==="role"){a.has($.roleKey)||t.push(`Search filter option "${b.key}.${O.key}" references missing role "${$.roleKey}".`);continue}cm($,d,t,`Search filter option "${b.key}.${O.key}"`)}}}for(let b of e.partyResultIcons??[])J6(b,d,t);for(let b of e.foundation.legalEntities)if(b.terms!==void 0&&t.push(...zk(b.terms,`foundation.legalEntities.${b.key}.terms`)),hF(b.branding,t,`foundation.legalEntities.${b.key}.branding`),gF(b,t,`foundation.legalEntities.${b.key}`),b.signatoryUserKey!==void 0&&b.type==="school_group"&&t.push(`[config/signatoryOnGroup] Legal entity "${b.key}" is a school_group \u2014 only a Tr\xE4ger (school_operator, service_entity) declares an Unterschriftsperson.`),b.parentLegalEntityKey&&!c.has(b.parentLegalEntityKey)&&t.push(`Legal entity "${b.key}" references missing parent "${b.parentLegalEntityKey}".`),b.address!==void 0){let O=b.address,$=["street","hausnr","plz","ort"];b.type==="school_group"?t.push(`Legal entity "${b.key}" is a school_group \u2014 only a Tr\xE4ger (school_operator, service_entity) has an address.`):(typeof O!="object"||O===null||Array.isArray(O)||Object.keys(O).some(I=>!$.includes(I))||$.some(I=>typeof O[I]!="string"||(O[I]??"").trim()===""))&&t.push(`Legal entity "${b.key}" has an invalid address \u2014 expected { street, hausnr, plz, ort }, each non-empty.`)}let E=new Map;for(let b of e.foundation.units){if(b.slug!==void 0){let O=typeof b.slug=="string"?TD(b.slug):"must be a string";O!==void 0&&t.push(`Unit "${b.key}" has invalid slug "${b.slug}" (${O}).`);let $=E.get(b.slug);$!==void 0&&t.push(`Units "${$}" and "${b.key}" both declare slug "${b.slug}" (unit slugs are unique per tenant).`),E.set(b.slug,b.key)}c.has(b.legalEntityKey)||t.push(`Unit "${b.key}" references missing legal entity "${b.legalEntityKey}".`),b.parentUnitKey&&!u.has(b.parentUnitKey)&&t.push(`Unit "${b.key}" references missing parent unit "${b.parentUnitKey}".`),b.sortOrder!==void 0&&(!Number.isFinite(b.sortOrder)||b.sortOrder<0)&&t.push(`Unit "${b.key}" has invalid sortOrder "${b.sortOrder}" (must be a non-negative number).`)}let R=/^[0-9a-f]{32}:[0-9a-f]{128}$/;for(let b of e.foundation.users){p.has(b.permissionGroupKey)||t.push(`User "${b.email}" references missing permission group "${b.permissionGroupKey}".`),b.unitKey&&!u.has(b.unitKey)&&t.push(`User "${b.email}" references missing unit "${b.unitKey}".`),b.status!==void 0&&b.status!=="deactivated"&&t.push(`User "${b.email}": status must be "deactivated" or absent, not "${String(b.status)}".`);let O=[b,...b.additionalMemberships??[]];for(let I of b.additionalMemberships??[])p.has(I.permissionGroupKey)||t.push(`User "${b.email}" references missing permission group "${I.permissionGroupKey}".`),I.unitKey&&!u.has(I.unitKey)&&t.push(`User "${b.email}" references missing unit "${I.unitKey}".`);En(O.map(I=>`${I.permissionGroupKey}/${I.unitKey??""}`),`membership (permission group/unit) of user "${b.email}"`,t);for(let I of O)I.validFrom!==void 0&&I.validTo!==void 0&&I.validTo<=I.validFrom&&t.push(`User "${b.email}": membership "${I.permissionGroupKey}" ends (validTo) before it starts (validFrom).`);let $=[b.firstName,b.lastName];$.some(I=>I!==void 0)&&$.some(I=>typeof I!="string"||I.trim()==="")&&t.push(`[config/userNameIncomplete] User "${b.email}" states only part of firstName/lastName (or an empty one) \u2014 set both or neither.`);for(let I of["staging","prod"]){let G=b.passwordHashes?.[I];G!==void 0&&!R.test(G)&&t.push(`User "${b.email}" passwordHashes.${I} is not in Better Auth scrypt format "<32hex>:<128hex>".`)}}hF(e.tenant.branding,t),gF(e.tenant,t);let P=kF(e.fields.flatMap(b=>b.sourceColumns));for(let b of P)r.push(`Source column "${b}" is mapped by more than one field.`);r3(e,t);let F=n.sourceColumns===void 0||e.source===void 0?void 0:n3(e,n.sourceColumns,t);return{ok:t.length===0,errors:t,warnings:r,coverage:F}}s(yF,"validateTenantConfig");function z6(e,n){let t=new Map;for(let r of e.objectSchema?.properties??[]){let i=r.addressPart;if(i===void 0)continue;let o=`Object property "${e.key}.${r.key}"`;if(!Zy.includes(i)){n.push(`${o}: addressPart "${i}" is none of ${Zy.join(", ")}.`);continue}e.type!=="object"&&n.push(`${o}: only an object field stores an address (addressPart).`),r.type!=="string"&&n.push(`${o}: addressPart "${i}" needs a string property, not "${r.type}".`);let a=t.get(i);a!==void 0&&n.push(`${o}: addressPart "${i}" is already declared by "${e.key}.${a}".`),t.set(i,r.key)}}s(z6,"validateAddressParts");function W6(e,n){let t=e.relationshipKinds;if(t===void 0)return;if(e.type!=="relationship"){n.push(`Field "${e.key}" declares relationshipKinds, but only a relationship field carries them.`);return}let r=new Map((e.objectSchema?.properties??[]).map(i=>[i.key,i]));for(let i of t){let o=`Field "${e.key}" relationship kind "${i.key}"`;if(typeof i.key!="string"||i.key.trim()===""){n.push(`Field "${e.key}": a relationship kind needs a key.`);continue}for(let l of["de","en"])(i.label?.[l]??"").trim()===""&&n.push(`${o}: label.${l} is required \u2014 [i18n/missingTranslation] every shown text needs German and English.`);if(i.edge===null||typeof i.edge!="object"||Array.isArray(i.edge)){n.push(`${o}: edge must be an object.`);continue}i.sibling!==void 0&&i.sibling!==!0&&n.push(`${o}: sibling must be true or absent.`),i.sibling===!0&&i.mergeInto!==void 0&&n.push(`${o}: a sibling kind's edge is its identity \u2014 it cannot declare mergeInto.`);let a=t.flatMap(l=>l.mergeInto!==void 0?[l.mergeInto]:[]);if(i.sibling===!0&&a.some(l=>l in i.edge)&&n.push(`${o}: a sibling kind's edge is its identity \u2014 it cannot declare a property another kind of the field merges into.`),i.sibling===!0&&Object.keys(i.edge).length===0&&n.push(`${o}: a sibling kind's edge is its identity \u2014 an empty edge would count every edge of the field.`),i.mergeInto!==void 0){let l=r.get(i.mergeInto);l===void 0||l.type!=="0-n-select"?n.push(`${o}: mergeInto "${i.mergeInto}" must name a 0-n-select property of the field's objectSchema.`):Array.isArray(i.edge[i.mergeInto])||n.push(`${o}: mergeInto "${i.mergeInto}" must be set to a list in the edge.`)}}}s(W6,"validateRelationshipKinds");function Y6(e,n,t){if(e.autoString===void 0){t.push(`Automatic field "${e.key}" must define autoString.`);return}e.allowMultiple===!0&&t.push(`Automatic field "${e.key}" must not allow multiple values.`),e.shareable===!0&&t.push(`Automatic field "${e.key}" must not be shareable.`),e.autoString.segments.length===0&&t.push(`Automatic field "${e.key}" must define at least one segment.`),e.autoString.segments.filter(i=>i.kind==="sequence").length!==1&&t.push(`Automatic field "${e.key}" must define exactly one sequence segment.`);for(let i of e.autoString.segments)if(i.kind==="literal"&&i.value.length===0&&t.push(`Automatic field "${e.key}" has an empty literal segment.`),i.kind==="sequence"&&(i.startAt!==void 0&&(!Number.isInteger(i.startAt)||i.startAt<1)&&t.push(`Automatic field "${e.key}" sequence startAt must be an integer >= 1.`),i.minDigits!==void 0&&(!Number.isInteger(i.minDigits)||i.minDigits<0)&&t.push(`Automatic field "${e.key}" sequence minDigits must be an integer >= 0.`)),i.kind==="field"){let o=n.get(i.fieldKey);if(o===void 0){t.push(`Automatic field "${e.key}" references missing field "${i.fieldKey}".`);continue}i.objectPropertyKey!==void 0&&o.objectSchema?.properties.find(l=>l.key===i.objectPropertyKey)===void 0&&t.push(`Automatic field "${e.key}" references missing object property "${i.fieldKey}.${i.objectPropertyKey}".`)}}s(Y6,"validateAutomaticStringField");function cm(e,n,t,r){if(e===void 0)return;let i=n.get(e.fieldKey);if(i===void 0){t.push(`${r} references missing field "${e.fieldKey}".`);return}if(e.objectPropertyKey===void 0)return;(i.objectSchema?.properties.some(a=>a.key===e.objectPropertyKey)??!1)||t.push(`${r} references missing object property "${e.fieldKey}.${e.objectPropertyKey}".`)}s(cm,"validateSearchTarget");function H6(e,n,t){if(e.source.kind!=="relationshipTargetField")return;let r=`Template placeholder "${e.key}"`,i=n.get(e.source.relationshipFieldKey);if(i===void 0)t.push(`${r} references missing relationship field "${e.source.relationshipFieldKey}".`);else if(i.type!=="relationship")t.push(`${r} relationship field "${e.source.relationshipFieldKey}" must be a relationship field.`);else{for(let a of e.source.edgeFilters??[])Qk(i,a.propertyKey,t,`${r} edge filter`);e.source.selection?.sortPropertyKey!==void 0&&Qk(i,e.source.selection.sortPropertyKey,t,`${r} selection sort`)}let o=n.get(e.source.targetFieldKey);if(o===void 0){t.push(`${r} references missing target field "${e.source.targetFieldKey}".`);return}o.type==="relationship"&&t.push(`${r} target field "${e.source.targetFieldKey}" must not be a relationship field.`),e.source.targetObjectPropertyKey!==void 0&&Qk(o,e.source.targetObjectPropertyKey,t,`${r} target`)}s(H6,"validateRelationshipTemplatePlaceholder");function Qk(e,n,t,r){(e.objectSchema?.properties.some(o=>o.key===n)??!1)||t.push(`${r} references missing object property "${e.key}.${n}".`)}s(Qk,"validateObjectPropertyReference");function J6(e,n,t){let r=`Party result icon "${e.key}"`,i=n.get(e.when.fieldKey);if(i===void 0){t.push(`${r} references missing field "${e.when.fieldKey}".`);return}if(e.when.objectPropertyKey===void 0){i.type!=="boolean"&&t.push(`${r} must target a Boolean field or object property.`);return}let o=i.objectSchema?.properties.find(a=>a.key===e.when.objectPropertyKey);if(o===void 0){t.push(`${r} references missing object property "${e.when.fieldKey}.${e.when.objectPropertyKey}".`);return}o.type!=="boolean"&&t.push(`${r} must target a Boolean field or object property.`)}s(J6,"validatePartyResultIconTarget");function wF(e){return`${e.templateId}:${e.locale}:${e.scopeKey}`}s(wF,"letterIdentity");function Q6(e){return`${e.generatorKey??"*"}/${e.partyKind}/${e.roleKey}`}s(Q6,"contractRoleMappingIdentity");function Z6(e,n,t){let r=new Set;for(let i of e){let o=Q6(i),a=`Contract role mapping "${o}"`;qk.includes(i.partyKind)||t.push(`${a}: partyKind must be one of ${qk.join(", ")}.`),n.has(i.roleKey)||t.push(`${a} references missing role "${i.roleKey}".`),i.generatorKey!==void 0&&i.generatorKey.trim()===""&&t.push(`${a}: generatorKey must not be blank \u2014 omit it for the tenant default.`),r.has(o)&&t.push(`${a} is declared twice.`),r.add(o)}}s(Z6,"validateContractRoleMappings");function X6(e,n){for(let t of e){let r=`Notification letter "${wF(t)}"`;if(!im(t.locale)){n.push(`${r} declares locale "${String(t.locale)}" \u2014 letters are written in ${We.map(i=>`"${i}"`).join(" and ")} only, so no mail would ever read this deviation.`);continue}if(t.scopeKey!==tm){n.push(`${r} declares scopeKey "${t.scopeKey}" \u2014 the only scope is "${tm}" (the whole school).`);continue}if(Object.keys(t.slots).length===0){n.push(`${r} overrides no block. A deviation that deviates in nothing is not an entry \u2014 remove it.`);continue}if(!$w(t.templateId)){n.push(`${r} references no registered letter \u2014 "${t.templateId}" is not in the letter catalog.`);continue}for(let i of ZD(Tw(t.templateId),t.slots,t.locale))n.push(`${r}, block "${i.slotKey}" [${i.code}]: ${i.message.de}`)}}s(X6,"validateNotificationLetters");function e3(e,n){if(e!==void 0)for(let t of XD(e))n.push(`Notification chrome: ${t.de}`)}s(e3,"validateNotificationChrome");function hF(e,n,t){if(e===void 0)return;let r=t===void 0?n:{push:s((...p)=>n.push(...p.map(h=>`${t}: ${h}`)),"push")},i=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/,o=/^(?:rgb|rgba|hsl|hsla)\(.+\)$/i,a=s(p=>i.test(p.trim())||o.test(p.trim()),"isColor");for(let[p,h]of Object.entries(e.colors??{}))h!==void 0&&(a(h)||r.push(`Branding color "colors.${p}" has invalid value "${h}" (expected hex "#rgb"/"#rrggbb"/"#rrggbbaa" or rgb()/rgba()/hsl()/hsla()).`));let l=["sharp","rounded","soft"];e.radius!==void 0&&!l.includes(e.radius)&&r.push(`Branding radius "${e.radius}" is invalid (expected "sharp", "rounded", or "soft").`);let d=["sm","md","lg","max"];e.logoSize!==void 0&&!d.includes(e.logoSize)&&r.push(`Branding logoSize "${e.logoSize}" is invalid (expected "sm", "md", "lg", or "max").`);let c=["compact","normal","spacious"];e.bannerDensity!==void 0&&!c.includes(e.bannerDensity)&&r.push(`Branding bannerDensity "${e.bannerDensity}" is invalid (expected "compact", "normal", or "spacious").`);let u=["light","dark"];e.logoGround!==void 0&&!u.includes(e.logoGround)&&r.push(`Branding logoGround "${e.logoGround}" is invalid (expected "light" or "dark").`),e.websiteUrl!==void 0&&!e.websiteUrl.startsWith("https://")&&r.push(`Branding websiteUrl must be an https:// URL (got "${e.websiteUrl}").`);for(let p of["heading","body"]){let h=e.fonts?.[p];h!==void 0&&((typeof h.family!="string"||h.family.trim().length===0)&&r.push(`Branding font "fonts.${p}" must define a non-empty family.`),Object.hasOwn(h,"url")&&r.push(`Branding font "fonts.${p}.url" is no longer supported \u2014 the font file is uploaded (plexus-cli branding set-font --slot ${p} --file <woff2>) and config carries the family only.`))}}s(hF,"validateBranding");function gF(e,n,t="tenant"){let r=e.brandingAssets;if(r!==void 0){if(typeof r!="object"||r===null||Array.isArray(r)){n.push(`${t}.brandingAssets must be an object keyed by slot (${am.join(", ")}).`);return}for(let[i,o]of Object.entries(r)){let a=`${t}.brandingAssets.${i}`;if(!am.includes(i)){n.push(`${a}: unknown slot (expected ${am.join(", ")}).`);continue}if(typeof o!="object"||o===null){n.push(`${a}: must be { sha256, sizeBytes, mimeType }.`);continue}if("size"in o){n.push(`[config/fileRefRenamed] ${a} still names size \u2014 this bundle was exported before the file-field rename, or by a plexus-cli older than this release (now sizeBytes). Update plexus-cli, export it again (plexus-cli --env <env> config export) and re-apply.`);continue}bF.test(o.sha256??"")||n.push(`${a}: sha256 must be 64 lowercase hex chars.`),(!Number.isInteger(o.sizeBytes)||o.sizeBytes<=0)&&n.push(`${a}: sizeBytes must be a positive integer.`);let l=tF[i];if(l===null){let d=rF({contentType:o.mimeType,size:o.sizeBytes});d!==null&&n.push(`${a}: ${d.de}`)}else{o.mimeType!==Hk&&n.push(`${a}: mimeType must be "${Hk}" (got "${o.mimeType}").`);let d=iF(e.branding?.fonts?.[l]?.family);d!==null&&n.push(`${a}: [branding/fontFamilyMissing] ${t}.branding.fonts.${l}: ${d.de}`)}"path"in o&&n.push(`${a}: "path" is a CLI snapshot field \u2014 resolve it with plexus-cli config apply.`)}}}s(gF,"validateBrandingAssets");function n3(e,n,t){let{source:r}=e;r===void 0&&L("validateSourceCoverage: called without a `source` block.");let i=new Set(n),o=new Set(e.fields.flatMap(k=>k.sourceColumns)),a=new Set(e.deferredColumns.map(k=>k.column)),l=new Set(e.ignoredColumns.map(k=>k.column)),d=new Set([...o,...a,...l]),c=r.requiredColumns.filter(k=>!i.has(k)),u=n.filter(k=>!d.has(k)),p=[...o].filter(k=>!i.has(k)),h=[...a].filter(k=>!i.has(k)),y=[...l].filter(k=>!i.has(k));for(let k of c)t.push(`Required source column "${k}" is missing from ${r.primaryTable}.`);for(let k of u)t.push(`Source column "${k}" is neither mapped nor explicitly deferred/ignored.`);for(let k of p)t.push(`Mapped source column "${k}" does not exist in the source schema.`);for(let k of h)t.push(`Deferred source column "${k}" does not exist in the source schema.`);for(let k of y)t.push(`Ignored source column "${k}" does not exist in the source schema.`);return{table:r.primaryTable,availableColumns:n.length,mappedColumns:[...o].filter(k=>i.has(k)).length,deferredColumns:[...a].filter(k=>i.has(k)).length,ignoredColumns:[...l].filter(k=>i.has(k)).length,missingRequiredColumns:c,unmappedColumns:u,unknownMappedColumns:p,unknownDeferredColumns:h,unknownIgnoredColumns:y}}s(n3,"validateSourceCoverage");function En(e,n,t){for(let r of kF(e))t.push(`Duplicate ${n} key "${r}".`)}s(En,"requireUnique");function kF(e){let n=new Set,t=new Set;for(let r of e)n.has(r)&&t.add(r),n.add(r);return[...t]}s(kF,"duplicates");var bF=/^[0-9a-f]{64}$/,t3=["fileName","size"];function r3(e,n){if(!Array.isArray(e.files)){n.push('"files" is missing \u2014 declare the file library (an empty list is fine).');return}En(e.files.map(t=>t.key),"file",n);for(let t of e.files){let r=`files["${t.key}"]`;xa(t.key)||n.push(`${r}: key must match ${hk}.`);for(let o of["de","en"])(t.label?.[o]??"").trim()===""&&n.push(`${r}: label.${o} is required \u2014 [i18n/missingTranslation] every shown text needs German and English.`);let i=t3.filter(o=>o in t);if(i.length>0){n.push(`[config/fileRefRenamed] ${r} still names ${i.join(", ")} \u2014 this bundle was exported before the file-field rename, or by a plexus-cli older than this release (now filename / sizeBytes). Update plexus-cli, export it again (plexus-cli --env <env> config export) and re-apply.`);continue}if(typeof t.filename!="string")n.push(`${r}: filename is missing.`);else{let o=Wo(t.filename);o!==null&&n.push(`${r}: filename ${o}.`)}rm.includes(t.mimeType)||n.push(`${r}: mimeType "${t.mimeType}" is not allowed (${rm.join(", ")}).`),bF.test(t.sha256??"")||n.push(`${r}: sha256 must be 64 lowercase hex chars.`),(!Number.isInteger(t.sizeBytes)||t.sizeBytes<=0)&&n.push(`${r}: sizeBytes must be a positive integer.`),"path"in t&&n.push(`${r}: "path" is a CLI snapshot field \u2014 resolve it with plexus-cli config apply.`)}}s(r3,"validateFiles");var i3=new WeakMap,o3=new WeakSet;function Zk(e,n){n(e);let r=e.asOptional.bind(e);return Object.defineProperty(e,"asOptional",{value:s(()=>Zk(r(),n),"value"),enumerable:!1}),e}s(Zk,"carry");function Ia(e,n){return Zk(e,t=>i3.set(t,n))}s(Ia,"tagged");var s3="tenant teardown drains every table explicitly (config/wipe.ts)",Ve={belongsTo:s(e=>Ia(e,{kind:"belongsTo"}),"belongsTo"),owns:s(e=>Ia(e,{kind:"owns"}),"owns"),holds:s(e=>Ia(e,{kind:"holds"}),"holds"),restrict:s((e,n)=>Ia(e,n?{kind:"restrict",unindexed:n.unindexed}:{kind:"restrict"}),"restrict"),history:s(e=>Ia(e,{kind:"history"}),"history"),tenant:s(e=>Ia(e,{kind:"restrict",unindexed:s3}),"tenant"),historyOf:s(e=>Zk(e,n=>o3.add(n)),"historyOf")};var a3=m.object({street:m.string(),hausnr:m.string(),plz:m.string(),ort:m.string()}),vF=m.union(m.literal("school_operator"),m.literal("school_group"),m.literal("service_entity")),Br=vF.members.map(e=>e.value),l3={tenantId:Ve.tenant(m.id("tenants")),name:m.optional(m.string()),type:vF,parentLegalEntityId:m.optional(Ve.restrict(m.id("legal_entities"))),configKey:m.optional(m.string()),partyId:m.optional(Ve.restrict(m.id("parties"))),address:m.optional(a3),signatoryUserId:m.optional(Ve.restrict(m.id("users"))),terms:m.optional(JD)},bEe=Nt(l3).index("by_tenantId",["tenantId"]).index("by_parentLegalEntityId",["parentLegalEntityId"]).index("by_tenantId_and_configKey",["tenantId","configKey"]).index("by_partyId",["partyId"]).index("by_signatoryUserId",["signatoryUserId"]);var d3=m.union(m.literal("school"),m.literal("kindergarten"),m.literal("after_school_care"),m.literal("department"),m.literal("site"),m.literal("other")),Mt=d3.members.map(e=>e.value),SEe=m.union(m.literal("school"),m.literal("vocational"),m.literal("care"),m.literal("seminar"),m.literal("other")),AEe=m.union(m.literal("none"),m.literal("manual"),m.literal("annual_rollover")),EEe=m.union(m.literal("grade_level"),m.literal("module"),m.literal("phase"),m.literal("other")),TEe=m.union(m.literal("school_year"),m.literal("cohort"),m.literal("seminar"),m.literal("care_period"),m.literal("other")),$Ee=m.union(m.literal("planned"),m.literal("active"),m.literal("completed"),m.literal("archived")),REe=m.union(m.literal("class"),m.literal("course"),m.literal("care_group"),m.literal("seminar_group"),m.literal("mixed_age_group"),m.literal("other")),IEe=m.union(m.literal("planned"),m.literal("active"),m.literal("completed"),m.literal("cancelled")),OEe=m.union(m.literal("class_teacher"),m.literal("teacher"),m.literal("mentor"),m.literal("instructor"),m.literal("assistant"),m.literal("other")),_Ee=m.union(m.literal("units"),m.literal("unit_profiles"),m.literal("programs"),m.literal("program_stages"),m.literal("program_runs"),m.literal("learning_groups"),m.literal("enrollments"),m.literal("learning_group_staff_assignments")),NEe=m.union(m.literal("open"),m.literal("mapped"),m.literal("ignored"));function SF(e){let n=["street","hausnr","plz","ort"].filter(t=>e[t]!==void 0);if(n.length!==0){if(n.length!==4)throw new Error(`config legal-entity add: an address needs all of --street, --hausnr, --plz and --ort (got ${n.map(t=>`--${t}`).join(", ")})`);return{street:e.street,hausnr:e.hausnr,plz:e.plz,ort:e.ort}}}s(SF,"addressFrom");function AF(e){if(!Br.includes(e))throw new Error(`config legal-entity add: --type "${e}" is none of ${Br.join(", ")}`);return e}s(AF,"legalEntityType");function EF(e){if(!Mt.includes(e))throw new Error(`config unit add: --kind "${e}" is none of ${Mt.join(", ")}`);return e}s(EF,"unitKind");function TF(e,n,t){let r=e.find(i=>i.key===n.key);if(r===void 0)return e.push(n),"create";if(Ne(r)===Ne(n))return"same";throw new Error(`${t} "${n.key}" already exists with other values \u2014 decide by hand, nothing written.
11274
11274
  in the file: ${JSON.stringify(r)}
11275
11275
  requested: ${JSON.stringify(n)}`)}s(TF,"addRow");function xF(e){return new Set(yF(e).errors)}s(xF,"findings");function $F(e,n){let t=s(()=>JSON.parse(he(e,"utf8")),"read"),r=t();if(typeof r!="object"||r===null||typeof r.foundation!="object")throw new Error(`config: ${e} is no exported tenant config (no "foundation" block) \u2014 export one with \`config export --out <file>\``);let i=xF(r),o=t(),a=n(o),l=[...xF(o)].filter(d=>!i.has(d));if(l.length>0)throw new Error(`config: the edit is refused by the config validator, nothing written:
11276
11276
  ${l.join(`
@@ -11508,6 +11508,6 @@ ${t.length} unusable ${o}:
11508
11508
  `),r.length>0&&this.context.stdout.write(` ${r.length} linkable \u2014 plexus-cli platform users relink-auth <email>
11509
11509
  `),i.length>0&&this.context.stdout.write(` ${i.length} without any login account \u2014 plexus-cli platform users provision --tenant <slug> --email <email> --name <name>
11510
11510
  `)}else this.context.stdout.write(`No unusable identities.
11511
- `);return t.length>0?1:0}},kT=class extends cr{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=T.Usage({category:"Users",description:"Relink a user's identity row to its live Better Auth account (heals an orphan)."});email=f.String({required:!0});async execute(){let t=await(await this.caller()).mutation(x.platformAdmin.relinkAuthAccount,{email:this.email}),r=t.changed?`Relinked ${this.email} to live auth account ${t.authId}.`:`${this.email} already linked to the live auth account (no change).`;return this.report(t,r),0}};function gB(e,n){if(e===n)throw new Error("Pass exactly one of --on or --off.");return e}s(gB,"requireOnOff");var yB=[tT,rT,iT,oT,sT,aT,lT,dT,cT,uT,ku,fT,pT,mT,hT,gT,yT,wT,kT];function wB(e){return e.de??e.en??Object.values(e)[0]??""}s(wB,"titleDe");function gX(e){return{id:e._id,kind:e.kind,status:e.status,title:wB(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(gX,"row");var yX=["id","kind","status","title","assignee","group","outcome"],xT=class extends D{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=T.Usage({category:"Work-Items",description:"List work-items for the active tenant (filter by --mine/--application/--group)."});mine=f.Boolean("--mine",!1,{description:"Only items assigned to me."});application=f.String("--application",{description:"Filter by application id."});group=f.String("--group",{description:"Filter by team (permission-group) id."});assignee=f.String("--assignee",{description:"Filter by assignee users._id."});openOnly=f.Boolean("--open-only",!1,{description:"Only open items."});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.query(x.workItems.list,{client:t,...this.mine?{mine:!0}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{},...this.openOnly?{openOnly:!0}:{}});return this.print(r,i=>i.map(gX),yX),0}},ST=class extends D{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=T.Usage({category:"Work-Items",description:"Show one work-item by id."});workItemId=f.String({required:!0,name:"workItemId"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.query(x.workItems.get,{client:t,workItemId:this.workItemId});if(r===null)throw new Error(`work-item ${this.workItemId} not found in tenant ${t}.`);return this.print(r,i=>[{field:"id",value:i._id},{field:"kind",value:i.kind},{field:"status",value:i.status},{field:"title",value:wB(i.title)},{field:"assignee",value:i.assigneeUserId??""},{field:"group",value:i.queueGroupId??""},{field:"application",value:i.applicationId??""},{field:"node",value:i.nodeId??""},{field:"outcome",value:i.outcome??""}]),0}},AT=class extends D{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=T.Usage({category:"Work-Items",description:"Create a manual task work-item."});title=f.String("--title",{required:!0,description:"Task title."});description=f.String("--description",{description:"Task description."});application=f.String("--application",{description:"Link to an application id."});group=f.String("--group",{description:"Team (permission-group) id whose queue holds the task."});assignee=f.String("--assignee",{description:"Assignee users._id."});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.mutation(x.workItems.createManual,{client:t,title:this.title,...this.description?{description:this.description}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{}});return this.print({workItemId:r.workItemId},i=>[{field:"workItemId",value:i.workItemId}]),0}},ET=class extends D{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=T.Usage({category:"Work-Items",description:"Complete a work-item (optionally with an outcome)."});workItemId=f.String({required:!0,name:"workItemId"});outcome=f.String("--outcome",{description:"Outcome id to record."});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.mutation(x.workItems.complete,{client:t,workItemId:this.workItemId,...this.outcome?{outcome:this.outcome}:{}});return this.print({workItemId:r.workItemId,status:"done"},i=>[{field:"workItemId",value:i.workItemId},{field:"status",value:i.status}]),0}},TT=class extends D{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=T.Usage({category:"Work-Items",description:"Assign a work-item to a user (omit --user to unassign)."});workItemId=f.String({required:!0,name:"workItemId"});user=f.String("--user",{description:"Assignee users._id (omit to clear)."});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.mutation(x.workItems.assign,{client:t,workItemId:this.workItemId,...this.user?{userId:this.user}:{}});return this.print({workItemId:r.workItemId,assignee:this.user??"(cleared)"},i=>[{field:"workItemId",value:i.workItemId},{field:"assignee",value:i.assignee}]),0}},kB=[xT,ST,AT,ET,TT];var bu=[...sI,...AD,...DD,...LF,...FF,...dL,...gL,...hL,...mB,...yB,...pB,...Zj,...iV,...lD,...oL,...nB,...iI,...NI,...WC,...kL,...wL,...xL,...SL,...rL,...BF,...kB,...zq,...DK,...Jj,...FK,...MV,...zV,...oV,...mV,...yV,...vV,...SV,...HV,...sB,...xI];for(let e of bu){let n=e.paths?.[0];n===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:$$(e.usage.category,n.join(" "))})}var bB="0.1.183";function vB(){return bu.flatMap(e=>(e.paths??[]).map(n=>{let t=n.join(" "),r=S$[ho(t)];return{path:t,effect:go(t),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,n)=>e.path.localeCompare(n.path))}s(vB,"plexusCommandCatalog");import fs from"node:path";function wX(e){let n=ln()?.workspaceRoot??process.cwd(),t=fs.resolve(n,e),r=fs.relative(n,t);if(fs.isAbsolute(e)||r===".."||r.startsWith(`..${fs.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:t,relative:r}}s(wX,"workspacePath");function kX(e){let{absolute:n,relative:t}=wX(e.path??".");if(e.operation==="list"){if(!Ae(n))return{files:[]};let r=[],i=s(o=>{for(let a of Or(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=fs.join(o,a.name);if(a.isDirectory()?i(l):r.push(fs.relative(n,l)),r.length>200)throw new Error("plexus: the workspace contains too many files. List a subdirectory.")}},"visit");return i(n),{files:r.sort()}}if(!t)throw new Error("plexus: name a workspace file.");if(["read","search","edit"].includes(e.operation)){let r=he(n);if(r.length>10*1024*1024)throw new Error("plexus: the workspace file exceeds 10 MB.");let i=new TextDecoder("utf-8",{fatal:!0}).decode(r);if(e.operation==="read"){let l=e.offset??0,d=e.maxChars??8e3,c=i.slice(l,l+d);return{path:t,content:c,...l||c.length<i.length?{offset:l,nextOffset:l+c.length<i.length?l+c.length:null,totalCharacters:i.length}:{}}}if(e.operation==="search"){if(!e.query)throw new Error("plexus: search needs a nonempty query.");let l=[],d=e.offset??0;for(;l.length<10;){let c=i.indexOf(e.query,d);if(c<0)break;l.push({offset:c,text:i.slice(Math.max(0,c-160),c+e.query.length+240)}),d=c+e.query.length}return{path:t,matches:l,nextOffset:l.length===10?d:null}}if(!e.oldText||typeof e.content!="string")throw new Error("plexus: edit needs oldText and replacement content.");let o=i.indexOf(e.oldText);if(o<0||o!==i.lastIndexOf(e.oldText))throw new Error("plexus: oldText must match exactly once. Read the current file and choose unique context.");let a=i.slice(0,o)+e.content+i.slice(o+e.oldText.length);if(Buffer.byteLength(a)>10*1024*1024)throw new Error("plexus: the edited file exceeds 10 MB.");return ze(n,a,"utf8"),{path:t,sizeBytes:Buffer.byteLength(a)}}if(e.operation==="write"){if(typeof e.content!="string"||Buffer.byteLength(e.content)>1e6)throw new Error("plexus: file content is missing or too large.");return Fn(fs.dirname(n),{recursive:!0}),ze(n,e.content,"utf8"),{path:t,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return gs(n),{path:t,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(kX,"plexusWorkspace");function xB(e){return s(async function(t,r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("plexus: tool input must be an object.");let i=r,o=Al[t];if(!o||!Object.hasOwn(Al,t))throw new Error("plexus: unknown agent tool.");if(Object.keys(i).some(a=>!Object.hasOwn(o.inputSchema.properties,a)))throw new Error("plexus: unexpected tool argument.");if(t==="plexus"){if(!Array.isArray(i.argv)||i.argv.some(a=>typeof a!="string")||i.stdin!==void 0&&typeof i.stdin!="string")throw new Error("plexus: invalid command input.");return e.inspectCommand(i.argv),e.executeCommand({argv:i.argv,...i.stdin===void 0?{}:{stdin:i.stdin}})}if(t==="plexus_skill"){if(typeof i.path!="string"||i.path.length>240||!Object.hasOwn(cy,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:cy[i.path],skillHash:hf}}if(typeof i.operation!="string"||!["list","read","search","edit","write","remove"].includes(i.operation)||i.path!==void 0&&(typeof i.path!="string"||i.path.length>500)||i.content!==void 0&&(typeof i.content!="string"||i.content.length>1e6)||i.oldText!==void 0&&(typeof i.oldText!="string"||i.oldText.length>1e6)||i.query!==void 0&&(typeof i.query!="string"||!i.query.length||i.query.length>1e3)||i.offset!==void 0&&(typeof i.offset!="number"||!Number.isSafeInteger(i.offset)||i.offset<0)||i.maxChars!==void 0&&(typeof i.maxChars!="number"||!Number.isSafeInteger(i.maxChars)||i.maxChars<1||i.maxChars>24e3))throw new Error("plexus: invalid workspace input.");return kX(i)},"executePlexusAgentTool")}s(xB,"createPlexusAgentToolExecutor");var Hh=xB({inspectCommand:AB,executeCommand:EB});function Jh(){let e=new bs({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:bB});e.register(al.HelpCommand),e.register(al.VersionCommand);for(let t of bu)e.register(t);async function n(t,r){let i;try{i=e.process(t,r)}catch(o){return(r.stderr??process.stderr).write(e.error(o,{colored:!1})),2}return xX(i,r.stderr??process.stderr),e.run(i,r)}return s(n,"run"),{process(t,r){return e.process(t,r)},run:n,async runExit(t,r){process.exitCode=await n(t,r)}}}s(Jh,"createPlexusCli");function xX(e,n){let t=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&t!==r&&fl[t]===r&&sn(n,t,r),t in fl&&go(t)==="confirm"&&!pl(e)&&n.write(`plexus-cli: \`${fl[t]}\` only prints its plan without --confirm \u2014 nothing was changed.
11511
+ `);return t.length>0?1:0}},kT=class extends cr{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=T.Usage({category:"Users",description:"Relink a user's identity row to its live Better Auth account (heals an orphan)."});email=f.String({required:!0});async execute(){let t=await(await this.caller()).mutation(x.platformAdmin.relinkAuthAccount,{email:this.email}),r=t.changed?`Relinked ${this.email} to live auth account ${t.authId}.`:`${this.email} already linked to the live auth account (no change).`;return this.report(t,r),0}};function gB(e,n){if(e===n)throw new Error("Pass exactly one of --on or --off.");return e}s(gB,"requireOnOff");var yB=[tT,rT,iT,oT,sT,aT,lT,dT,cT,uT,ku,fT,pT,mT,hT,gT,yT,wT,kT];function wB(e){return e.de??e.en??Object.values(e)[0]??""}s(wB,"titleDe");function gX(e){return{id:e._id,kind:e.kind,status:e.status,title:wB(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(gX,"row");var yX=["id","kind","status","title","assignee","group","outcome"],xT=class extends D{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=T.Usage({category:"Work-Items",description:"List work-items for the active tenant (filter by --mine/--application/--group)."});mine=f.Boolean("--mine",!1,{description:"Only items assigned to me."});application=f.String("--application",{description:"Filter by application id."});group=f.String("--group",{description:"Filter by team (permission-group) id."});assignee=f.String("--assignee",{description:"Filter by assignee users._id."});openOnly=f.Boolean("--open-only",!1,{description:"Only open items."});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.query(x.workItems.list,{client:t,...this.mine?{mine:!0}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{},...this.openOnly?{openOnly:!0}:{}});return this.print(r,i=>i.map(gX),yX),0}},ST=class extends D{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=T.Usage({category:"Work-Items",description:"Show one work-item by id."});workItemId=f.String({required:!0,name:"workItemId"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.query(x.workItems.get,{client:t,workItemId:this.workItemId});if(r===null)throw new Error(`work-item ${this.workItemId} not found in tenant ${t}.`);return this.print(r,i=>[{field:"id",value:i._id},{field:"kind",value:i.kind},{field:"status",value:i.status},{field:"title",value:wB(i.title)},{field:"assignee",value:i.assigneeUserId??""},{field:"group",value:i.queueGroupId??""},{field:"application",value:i.applicationId??""},{field:"node",value:i.nodeId??""},{field:"outcome",value:i.outcome??""}]),0}},AT=class extends D{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=T.Usage({category:"Work-Items",description:"Create a manual task work-item."});title=f.String("--title",{required:!0,description:"Task title."});description=f.String("--description",{description:"Task description."});application=f.String("--application",{description:"Link to an application id."});group=f.String("--group",{description:"Team (permission-group) id whose queue holds the task."});assignee=f.String("--assignee",{description:"Assignee users._id."});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.mutation(x.workItems.createManual,{client:t,title:this.title,...this.description?{description:this.description}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{}});return this.print({workItemId:r.workItemId},i=>[{field:"workItemId",value:i.workItemId}]),0}},ET=class extends D{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=T.Usage({category:"Work-Items",description:"Complete a work-item (optionally with an outcome)."});workItemId=f.String({required:!0,name:"workItemId"});outcome=f.String("--outcome",{description:"Outcome id to record."});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.mutation(x.workItems.complete,{client:t,workItemId:this.workItemId,...this.outcome?{outcome:this.outcome}:{}});return this.print({workItemId:r.workItemId,status:"done"},i=>[{field:"workItemId",value:i.workItemId},{field:"status",value:i.status}]),0}},TT=class extends D{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=T.Usage({category:"Work-Items",description:"Assign a work-item to a user (omit --user to unassign)."});workItemId=f.String({required:!0,name:"workItemId"});user=f.String("--user",{description:"Assignee users._id (omit to clear)."});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.mutation(x.workItems.assign,{client:t,workItemId:this.workItemId,...this.user?{userId:this.user}:{}});return this.print({workItemId:r.workItemId,assignee:this.user??"(cleared)"},i=>[{field:"workItemId",value:i.workItemId},{field:"assignee",value:i.assignee}]),0}},kB=[xT,ST,AT,ET,TT];var bu=[...sI,...AD,...DD,...LF,...FF,...dL,...gL,...hL,...mB,...yB,...pB,...Zj,...iV,...lD,...oL,...nB,...iI,...NI,...WC,...kL,...wL,...xL,...SL,...rL,...BF,...kB,...zq,...DK,...Jj,...FK,...MV,...zV,...oV,...mV,...yV,...vV,...SV,...HV,...sB,...xI];for(let e of bu){let n=e.paths?.[0];n===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:$$(e.usage.category,n.join(" "))})}var bB="0.1.184";function vB(){return bu.flatMap(e=>(e.paths??[]).map(n=>{let t=n.join(" "),r=S$[ho(t)];return{path:t,effect:go(t),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,n)=>e.path.localeCompare(n.path))}s(vB,"plexusCommandCatalog");import fs from"node:path";function wX(e){let n=ln()?.workspaceRoot??process.cwd(),t=fs.resolve(n,e),r=fs.relative(n,t);if(fs.isAbsolute(e)||r===".."||r.startsWith(`..${fs.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:t,relative:r}}s(wX,"workspacePath");function kX(e){let{absolute:n,relative:t}=wX(e.path??".");if(e.operation==="list"){if(!Ae(n))return{files:[]};let r=[],i=s(o=>{for(let a of Or(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=fs.join(o,a.name);if(a.isDirectory()?i(l):r.push(fs.relative(n,l)),r.length>200)throw new Error("plexus: the workspace contains too many files. List a subdirectory.")}},"visit");return i(n),{files:r.sort()}}if(!t)throw new Error("plexus: name a workspace file.");if(["read","search","edit"].includes(e.operation)){let r=he(n);if(r.length>10*1024*1024)throw new Error("plexus: the workspace file exceeds 10 MB.");let i=new TextDecoder("utf-8",{fatal:!0}).decode(r);if(e.operation==="read"){let l=e.offset??0,d=e.maxChars??8e3,c=i.slice(l,l+d);return{path:t,content:c,...l||c.length<i.length?{offset:l,nextOffset:l+c.length<i.length?l+c.length:null,totalCharacters:i.length}:{}}}if(e.operation==="search"){if(!e.query)throw new Error("plexus: search needs a nonempty query.");let l=[],d=e.offset??0;for(;l.length<10;){let c=i.indexOf(e.query,d);if(c<0)break;l.push({offset:c,text:i.slice(Math.max(0,c-160),c+e.query.length+240)}),d=c+e.query.length}return{path:t,matches:l,nextOffset:l.length===10?d:null}}if(!e.oldText||typeof e.content!="string")throw new Error("plexus: edit needs oldText and replacement content.");let o=i.indexOf(e.oldText);if(o<0||o!==i.lastIndexOf(e.oldText))throw new Error("plexus: oldText must match exactly once. Read the current file and choose unique context.");let a=i.slice(0,o)+e.content+i.slice(o+e.oldText.length);if(Buffer.byteLength(a)>10*1024*1024)throw new Error("plexus: the edited file exceeds 10 MB.");return ze(n,a,"utf8"),{path:t,sizeBytes:Buffer.byteLength(a)}}if(e.operation==="write"){if(typeof e.content!="string"||Buffer.byteLength(e.content)>1e6)throw new Error("plexus: file content is missing or too large.");return Fn(fs.dirname(n),{recursive:!0}),ze(n,e.content,"utf8"),{path:t,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return gs(n),{path:t,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(kX,"plexusWorkspace");function xB(e){return s(async function(t,r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("plexus: tool input must be an object.");let i=r,o=Al[t];if(!o||!Object.hasOwn(Al,t))throw new Error("plexus: unknown agent tool.");if(Object.keys(i).some(a=>!Object.hasOwn(o.inputSchema.properties,a)))throw new Error("plexus: unexpected tool argument.");if(t==="plexus"){if(!Array.isArray(i.argv)||i.argv.some(a=>typeof a!="string")||i.stdin!==void 0&&typeof i.stdin!="string")throw new Error("plexus: invalid command input.");return e.inspectCommand(i.argv),e.executeCommand({argv:i.argv,...i.stdin===void 0?{}:{stdin:i.stdin}})}if(t==="plexus_skill"){if(typeof i.path!="string"||i.path.length>240||!Object.hasOwn(cy,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:cy[i.path],skillHash:hf}}if(typeof i.operation!="string"||!["list","read","search","edit","write","remove"].includes(i.operation)||i.path!==void 0&&(typeof i.path!="string"||i.path.length>500)||i.content!==void 0&&(typeof i.content!="string"||i.content.length>1e6)||i.oldText!==void 0&&(typeof i.oldText!="string"||i.oldText.length>1e6)||i.query!==void 0&&(typeof i.query!="string"||!i.query.length||i.query.length>1e3)||i.offset!==void 0&&(typeof i.offset!="number"||!Number.isSafeInteger(i.offset)||i.offset<0)||i.maxChars!==void 0&&(typeof i.maxChars!="number"||!Number.isSafeInteger(i.maxChars)||i.maxChars<1||i.maxChars>24e3))throw new Error("plexus: invalid workspace input.");return kX(i)},"executePlexusAgentTool")}s(xB,"createPlexusAgentToolExecutor");var Hh=xB({inspectCommand:AB,executeCommand:EB});function Jh(){let e=new bs({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:bB});e.register(al.HelpCommand),e.register(al.VersionCommand);for(let t of bu)e.register(t);async function n(t,r){let i;try{i=e.process(t,r)}catch(o){return(r.stderr??process.stderr).write(e.error(o,{colored:!1})),2}return xX(i,r.stderr??process.stderr),e.run(i,r)}return s(n,"run"),{process(t,r){return e.process(t,r)},run:n,async runExit(t,r){process.exitCode=await n(t,r)}}}s(Jh,"createPlexusCli");function xX(e,n){let t=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&t!==r&&fl[t]===r&&sn(n,t,r),t in fl&&go(t)==="confirm"&&!pl(e)&&n.write(`plexus-cli: \`${fl[t]}\` only prints its plan without --confirm \u2014 nothing was changed.
11512
11512
  `)}s(xX,"noteRetiredPath");function AB(e){let n=Jh().process(Za(e),{executePlexusAgentTool:Hh}),t=n.path.join(" ");if(t.startsWith("agent "))throw new Error("plexus: nested agent transports are not allowed.");let r=vB().find(l=>l.path===t);if(!r){if(t===""||t==="--help"||t==="--version")return{path:t,writes:!1,host:"shared"};throw new Error(`plexus: command ${t} has no host classification.`)}let i=n,o=r.effect==="callKind"?bm(Oa(_a),i.fn??"",i.kind):void 0,a=nf(t,{confirm:pl(n),callKind:o});return{...r,writes:a}}s(AB,"inspectPlexusCommand");async function EB(e,n){if(n)return IT(n,()=>EB(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 t="",r="",i=Jh();if(ln()){let l=AB(e.argv);if(l.host==="terminal")throw new Error(`plexus: this command requires a local machine. ${l.reason??""}`)}return{exitCode:await i.run(Za(e.argv),{executePlexusAgentTool:Hh,stdin:vX.from(e.stdin===void 0?[]:[e.stdin]),stdout:new SB({write(l,d,c){t+=String(l),c()}}),stderr:new SB({write(l,d,c){r+=String(l),c()}})}),stdout:t,stderr:r}}s(EB,"executePlexusCommand");CT({source:SX.join(import.meta.dirname,"skill")});Jh().runExit(Za(process.argv.slice(2)),{executePlexusAgentTool:Hh});
11513
11513
  //# sourceMappingURL=cli.mjs.map